@xmov/avatar 2.4.0-alpha.3 → 2.4.0-alpha.4

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.
@@ -1,2 +1,2 @@
1
- function _extends(){return _extends=Object.assign?Object.assign.bind():function(t){for(var e=1;e<arguments.length;e++){var n=arguments[e];for(var r in n)({}).hasOwnProperty.call(n,r)&&(t[r]=n[r])}return t},_extends.apply(null,arguments)}var EErrorCode;!function(t){t[t.CONTAINER_NOT_FOUND=10001]="CONTAINER_NOT_FOUND",t[t.CONNECT_SOCKET_ERROR=10002]="CONNECT_SOCKET_ERROR",t[t.START_SESSION_ERROR=10003]="START_SESSION_ERROR",t[t.STOP_SESSION_ERROR=10004]="STOP_SESSION_ERROR",t[t.INIT_ERROR=10005]="INIT_ERROR",t[t.SOCKET_QUIT=10006]="SOCKET_QUIT",t[t.SOCKET_DISCONNECT=10007]="SOCKET_DISCONNECT",t[t.VIDEO_FRAME_EXTRACT_ERROR=20001]="VIDEO_FRAME_EXTRACT_ERROR",t[t.INIT_WORKER_ERROR=20002]="INIT_WORKER_ERROR",t[t.PROCESS_VIDEO_STREAM_ERROR=20003]="PROCESS_VIDEO_STREAM_ERROR",t[t.FACE_PROCESSING_ERROR=20004]="FACE_PROCESSING_ERROR",t[t.RENDER_BODY_ERROR=20005]="RENDER_BODY_ERROR",t[t.RENDER_FACE_ERROR=20006]="RENDER_FACE_ERROR",t[t.WebGL_RENDER_ERROR=20007]="WebGL_RENDER_ERROR",t[t.RENDER_DATA_MISSING=20008]="RENDER_DATA_MISSING",t[t.RENDER_FACE_DATA_MISSING=20009]="RENDER_FACE_DATA_MISSING",t[t.EVENT_WITHOUT_SPEECH_ID=20010]="EVENT_WITHOUT_SPEECH_ID",t[t.EVENT_TRIGGERED=20011]="EVENT_TRIGGERED",t[t.BACKGROUND_IMAGE_LOAD_ERROR=30001]="BACKGROUND_IMAGE_LOAD_ERROR",t[t.FACE_BIN_LOAD_ERROR=30002]="FACE_BIN_LOAD_ERROR",t[t.INVALID_BODY_NAME=30003]="INVALID_BODY_NAME",t[t.VIDEO_DOWNLOAD_ERROR=30004]="VIDEO_DOWNLOAD_ERROR",t[t.BODY_DATA_EXPIRED=30005]="BODY_DATA_EXPIRED",t[t.EVENT_SPEAK_START_EXPIRED=30006]="EVENT_SPEAK_START_EXPIRED",t[t.EVENT_VOICE_START_EXPIRED=30007]="EVENT_VOICE_START_EXPIRED",t[t.AUDIO_DECODE_ERROR=40001]="AUDIO_DECODE_ERROR",t[t.FACE_DECODE_ERROR=40002]="FACE_DECODE_ERROR",t[t.VIDEO_DECODE_ERROR=40003]="VIDEO_DECODE_ERROR",t[t.EVENT_DECODE_ERROR=40004]="EVENT_DECODE_ERROR",t[t.INVALID_DATA_STRUCTURE=40005]="INVALID_DATA_STRUCTURE",t[t.TTSA_ERROR=40006]="TTSA_ERROR",t[t.AUDIO_DATA_EXPIRED=40007]="AUDIO_DATA_EXPIRED",t[t.NETWORK_DOWN=50001]="NETWORK_DOWN",t[t.NETWORK_UP=50002]="NETWORK_UP",t[t.NETWORK_RETRY=50003]="NETWORK_RETRY",t[t.NETWORK_BREAK=50004]="NETWORK_BREAK",t[t.WEBGL_CONTEXT_LOST=60001]="WEBGL_CONTEXT_LOST",t[t.WEBGL_CONTEXT_RESTORED=60002]="WEBGL_CONTEXT_RESTORED",t[t.WEBGL_CONTEXT_RESTORE_TIMEOUT=60003]="WEBGL_CONTEXT_RESTORE_TIMEOUT",t[t.WEBGL_CONTEXT_RECOVERED=60004]="WEBGL_CONTEXT_RECOVERED",t[t.WEBGL_CONTEXT_RECOVERY_FAILED=60005]="WEBGL_CONTEXT_RECOVERY_FAILED",t[t.WEBGL_CONTEXT_RECOVERY_MAX_ATTEMPTS=60006]="WEBGL_CONTEXT_RECOVERY_MAX_ATTEMPTS",t[t.WEBGL_RESOLUTION_RESTORED=60007]="WEBGL_RESOLUTION_RESTORED",t[t.WEBGL_CONTEXT_MANUAL_RESTARTED=60008]="WEBGL_CONTEXT_MANUAL_RESTARTED"}(EErrorCode||(EErrorCode={}));const ERROR_CODE_MAP={10001:3101,10002:3102,10003:3103,10004:3104,10005:3105,10006:3106,10007:3107,20001:3201,20002:3202,20003:3203,20004:3204,20005:3205,20006:3206,20007:3207,20008:3208,20009:3209,20010:3210,20011:3211,30001:3301,30002:3302,30003:3303,30004:3304,30005:3305,30006:3306,30007:3307,40001:3401,40002:3402,40003:3403,40004:3404,40005:3405,40006:3406,40007:3407,50001:3501,50002:3502,50003:3503,50004:3504,60001:3601,60002:3602,60003:3603,60004:3604,60005:3605,60006:3606,60007:3607,60008:3608},ERROR_NAME_MAP={10001:"CONTAINER_NOT_FOUND",10002:"CONNECT_SOCKET_ERROR",10003:"START_SESSION_ERROR",10004:"STOP_SESSION_ERROR",10005:"INIT_ERROR",10006:"SOCKET_QUIT",10007:"SOCKET_DISCONNECT",20001:"VIDEO_FRAME_EXTRACT_ERROR",20002:"INIT_WORKER_ERROR",20003:"PROCESS_VIDEO_STREAM_ERROR",20004:"FACE_PROCESSING_ERROR",20005:"RENDER_BODY_ERROR",20006:"RENDER_FACE_ERROR",20007:"WebGL_RENDER_ERROR",20008:"RENDER_DATA_MISSING",20009:"RENDER_FACE_DATA_MISSING",20010:"EVENT_WITHOUT_SPEECH_ID",20011:"EVENT_TRIGGERED",30001:"BACKGROUND_IMAGE_LOAD_ERROR",30002:"FACE_BIN_LOAD_ERROR",30003:"INVALID_BODY_NAME",30004:"VIDEO_DOWNLOAD_ERROR",30005:"BODY_DATA_EXPIRED",30006:"EVENT_SPEAK_START_EXPIRED",30007:"EVENT_VOICE_START_EXPIRED",40001:"AUDIO_DECODE_ERROR",40002:"FACE_DECODE_ERROR",40003:"VIDEO_DECODE_ERROR",40004:"EVENT_DECODE_ERROR",40005:"INVALID_DATA_STRUCTURE",40006:"TTSA_ERROR",40007:"AUDIO_DATA_EXPIRED",50001:"NETWORK_DOWN",50002:"NETWORK_UP",50003:"NETWORK_RETRY",50004:"NETWORK_BREAK",60001:"WEBGL_CONTEXT_LOST",60002:"WEBGL_CONTEXT_RESTORED",60003:"WEBGL_CONTEXT_RESTORE_TIMEOUT",60004:"WEBGL_CONTEXT_RECOVERED",60005:"WEBGL_CONTEXT_RECOVERY_FAILED",60006:"WEBGL_CONTEXT_RECOVERY_MAX_ATTEMPTS",60007:"WEBGL_RESOLUTION_RESTORED",60008:"WEBGL_CONTEXT_MANUAL_RESTARTED"};var AvatarStatus,RenderState,InitModel,EFrameDataType;!function(t){t[t.online=0]="online",t[t.offline=1]="offline",t[t.network_on=2]="network_on",t[t.network_off=3]="network_off",t[t.close=4]="close",t[t.visible=5]="visible",t[t.invisible=6]="invisible",t[t.stopped=7]="stopped"}(AvatarStatus||(AvatarStatus={})),function(t){t.init="init",t.rendering="rendering",t.pausing="pausing",t.paused="paused",t.resumed="resumed",t.stopped="stopped"}(RenderState||(RenderState={})),function(t){t.normal="normal",t.invisible="invisible"}(InitModel||(InitModel={})),function(t){t.AUDIO="tts_audio",t.BODY="body_data",t.FACE="face_data",t.EVENT="event_data",t.AA_FRAME="aa_frame",t.SYNC_FRAME="sync_frame"}(EFrameDataType||(EFrameDataType={}));const FRAME_SOURCE_SOURCE="xmov_avatar_js_sdk";class DataCacheQueue{constructor(){this.TAG="[DataCacheQueue]",this._bodyQueue=new Map,this._facialQueue=[],this._realFacialQueue=[],this.audioQueue=[],this.eventQueue=[],this.videoIdList=[],this._currentPlayState="idle",this._currentTtsaState=null,window.__dev_event_queue__=this.eventQueue}set currentPlayState(t){this._currentPlayState=t}get currentPlayState(){return this._currentPlayState}set currentTtsaState(t){this._currentTtsaState=t}get currentTtsaState(){return this._currentTtsaState}get bodyQueue(){return Array.from(this._bodyQueue.values())}_updateBodyImageBitmap(t){const e=this._bodyQueue.get(t.frameIndex);e&&e.frame&&"function"==typeof e.frame.close&&e.frame.close();for(const[e,n]of this._bodyQueue.entries())n.body_id<t.body_id&&n.frameIndex>=t.frameIndex&&(n.frame.close(),this._bodyQueue.delete(e));this._bodyQueue.set(t.frameIndex,t)}clearOldFrames(t){for(const[e,n]of this._bodyQueue.entries())e>=t&&(n.frame.close(),this._bodyQueue.delete(e))}clearOldFaceData(t){this._facialQueue=this._facialQueue.filter(e=>e.frameIndex>=t),this._realFacialQueue=this._realFacialQueue.filter(e=>e.frameIndex>=t)}setVideoIdList(t){this.videoIdList.includes(t)||this.videoIdList.push(t)}getVideoIdList(){return this.videoIdList}_getBodyImageBitmap(t){const e=this._bodyQueue.get(t);for(const[e,n]of this._bodyQueue.entries())e<t&&(n.frame.close(),this._bodyQueue.delete(e));if(e)return e}getBodyVideoNameListLength(){const t=[];return this.bodyQueue.forEach(e=>{t.includes(e.name)||t.push(e.name)}),t.length}_getFaceImageBitmap(t,e){let n=null;for(let r=this._facialQueue.length-1;r>=0;r--){const i=this._facialQueue[r];if(i.frameIndex===t&&i.body_id===e){n=i;break}}return this._facialQueue=this._facialQueue.filter(e=>e.frameIndex>=t),n}_updateFacial(t){this._facialQueue.push(...t)}get facialQueue(){return this._facialQueue}_getRealFaceImageBitmap(t,e){let n=null;for(let r=this._realFacialQueue.length-1;r>=0;r--){const i=this._realFacialQueue[r];if((null==i?void 0:i.frameIndex)===t&&(null==i?void 0:i.body_id)===e){n=i;break}}return this._realFacialQueue=this._realFacialQueue.filter(e=>(null==e?void 0:e.frameIndex)>=t),n}_updateRealFacial(t){this._realFacialQueue.push(...t)}get realFacialQueue(){return this._realFacialQueue}clearAllFaceData(){var t;this._facialQueue=[],this._realFacialQueue=[],null==(t=window.avatarSDKLogger)||t.log(this.TAG,"已清空所有表情数据")}_updateAudio(t){this.audioQueue.push(...t)}_clearAudio(t){this.audioQueue=-1!==t?this.audioQueue.filter(e=>e.sid!==t):[]}_getAudio(t){const e=this.audioQueue.findIndex(e=>e.sf===t);if(-1===e)return;const[n]=this.audioQueue.splice(e,1);return n}_getAudioInterval(t,e){const n=this.audioQueue.filter(n=>n.sf>=t&&n.sf<=e);if(0===n.length)return;const r=n[n.length-1],i=this.audioQueue.findIndex(t=>t.id===r.id);return this.audioQueue.splice(i,1),r}_updateUiEvent(t){this.eventQueue.push(...t)}clearOldEvent(t){this.eventQueue=this.eventQueue.filter(e=>e.sf>=t)}clearSubtitleOn(t){this.eventQueue=this.eventQueue.map(e=>{var n;return _extends({},e,{e:null==(n=e.e)?void 0:n.filter(e=>e.speech_id>t||"subtitle_on"!==e.type)})})}_clearEvent(){this.eventQueue=[]}_getEvent(t){const e=this.eventQueue.filter(e=>e.sf===t);if(0!==e.length)return this.eventQueue=this.eventQueue.filter(e=>e.sf!==t),this._mergeEventsBySf(e)}_getEventInterval(t,e){const n=this.eventQueue.filter(n=>n.sf>=t&&n.sf<=e);if(0!==n.length)return this.eventQueue=this.eventQueue.filter(n=>!(n.sf>=t&&n.sf<=e)),this._mergeEventsBySf(n)}_mergeEventsBySf(t){const e={};for(const n of t){const t=n.sf;e[t]||(e[t]=_extends({},n,{e:[]})),e[t].e.push(...n.e)}const n=Object.values(e);if(0===n.length)return null;if(n.length>1){const t=[];return n.forEach(e=>t.push(...e.e)),_extends({},n[0],{mergeFrameFlag:1,e:t})}return n[0]}checkValidData(t,e){switch(e){case EFrameDataType.BODY:case EFrameDataType.FACE:break;case EFrameDataType.AUDIO:var n,r;if(0===this.audioQueue.length||0===t.length)return;if((null==(n=this.audioQueue[this.audioQueue.length-1])?void 0:n.ef)<t[0].sf||t[0].sf<(null==(r=this.audioQueue[0])?void 0:r.sf)){const e=this.audioQueue.findIndex(e=>e.sf>=t[0].sf);-1!==e&&(this.audioQueue.length=e)}}}destroy(){this._bodyQueue.forEach(t=>{t.frame&&"function"==typeof t.frame.close&&t.frame.close()}),this._bodyQueue.clear(),this._facialQueue=[],this.audioQueue=[],this.eventQueue=[]}}class GLDevice{constructor(t){this.running=!0,this.syncMedia=null,this.syncMediaTime=null,this._lost_context_sim=null,this._isDestroyed=!1,this.canvas=t,this.frameID=null;const e=()=>{const t=this.canvas.getContext("webgl2",{antialias:!1,premultipliedAlpha:!0,preserveDrawingBuffer:!0});if(!t)throw Error("WebGL context cannot be created.");this.gl=t,this._lost_context_sim=this.gl.getExtension("WEBGL_lose_context"),this.shaderStage={vertex:this.gl.VERTEX_SHADER,fragment:this.gl.FRAGMENT_SHADER},this._ElementTypeMap_JS2GL={Uint8Array:this.gl.UNSIGNED_BYTE,Uint8ClampedArray:this.gl.UNSIGNED_BYTE,Int8Array:this.gl.BYTE,Uint16Array:this.gl.UNSIGNED_SHORT,Int16Array:this.gl.SHORT,Uint32Array:this.gl.UNSIGNED_INT,Int32Array:this.gl.INT,Float16Array:this.gl.HALF_FLOAT,Float32Array:this.gl.FLOAT};const e=[[this.gl.UNSIGNED_BYTE,[[this.gl.RED,this.gl.R8],[this.gl.RED_INTEGER,this.gl.R8UI],[this.gl.RG,this.gl.RG8],[this.gl.RG_INTEGER,this.gl.RG8UI],[this.gl.RGB,this.gl.RGB8],[this.gl.RGB_INTEGER,this.gl.RGB8UI],[this.gl.RGBA,this.gl.RGBA8],[this.gl.RGBA_INTEGER,this.gl.RGBA8UI]]],[this.gl.BYTE,[[this.gl.RED,this.gl.R8_SNORM],[this.gl.RED_INTEGER,this.gl.R8I],[this.gl.RG,this.gl.RG8_SNORM],[this.gl.RG_INTEGER,this.gl.RG8I],[this.gl.RGB,this.gl.RGB8_SNORM],[this.gl.RGB_INTEGER,this.gl.RGB8I],[this.gl.RGBA,this.gl.RGBA8_SNORM],[this.gl.RGBA_INTEGER,this.gl.RGBA8I]]],[this.gl.UNSIGNED_SHORT,[[this.gl.RED_INTEGER,this.gl.R16UI],[this.gl.RG_INTEGER,this.gl.RG16UI],[this.gl.RGB_INTEGER,this.gl.RGB16UI],[this.gl.RGBA_INTEGER,this.gl.RGBA16UI],[this.gl.DEPTH_COMPONENT,this.gl.DEPTH_COMPONENT16]]],[this.gl.SHORT,[[this.gl.RED_INTEGER,this.gl.R16I],[this.gl.RG_INTEGER,this.gl.RG16I],[this.gl.RGB_INTEGER,this.gl.RGB16I],[this.gl.RGBA_INTEGER,this.gl.RGBA16I]]],[this.gl.UNSIGNED_INT,[[this.gl.RED_INTEGER,this.gl.R32UI],[this.gl.RG_INTEGER,this.gl.RG32UI],[this.gl.RGB_INTEGER,this.gl.RGB32UI],[this.gl.RGBA_INTEGER,this.gl.RGBA32UI],[this.gl.DEPTH_COMPONENT,this.gl.DEPTH_COMPONENT24]]],[this.gl.INT,[[this.gl.RED_INTEGER,this.gl.R32I],[this.gl.RG_INTEGER,this.gl.RG32I],[this.gl.RGB_INTEGER,this.gl.RGB32I],[this.gl.RGBA_INTEGER,this.gl.RGBA32I]]],[this.gl.HALF_FLOAT,[[this.gl.RED,this.gl.R16F],[this.gl.RG,this.gl.RG16F],[this.gl.RGB,this.gl.RGB16F],[this.gl.RGBA,this.gl.RGBA16F]]],[this.gl.FLOAT,[[this.gl.RED,this.gl.R32F],[this.gl.RG,this.gl.RG32F],[this.gl.RGB,this.gl.RGB32F],[this.gl.RGBA,this.gl.RGBA32F],[this.gl.DEPTH_COMPONENT,this.gl.DEPTH_COMPONENT32F]]],[this.gl.UNSIGNED_SHORT_5_6_5,[[this.gl.RGB,this.gl.RGB565]]],[this.gl.UNSIGNED_SHORT_4_4_4_4,[[this.gl.RGBA,this.gl.RGBA4]]],[this.gl.UNSIGNED_SHORT_5_5_5_1,[[this.gl.RGBA,this.gl.RGB5_A1]]],[this.gl.UNSIGNED_INT_2_10_10_10_REV,[[this.gl.RGBA,this.gl.RGB10_A2]]],[this.gl.UNSIGNED_INT_10F_11F_11F_REV,[[this.gl.RGB,this.gl.R11F_G11F_B10F]]],[this.gl.UNSIGNED_INT_5_9_9_9_REV,[[this.gl.RGB,this.gl.RGB9_E5]]],[this.gl.UNSIGNED_INT_24_8,[[this.gl.DEPTH_STENCIL,this.gl.DEPTH24_STENCIL8]]],[this.gl.FLOAT_32_UNSIGNED_INT_24_8_REV,[[this.gl.DEPTH_STENCIL,this.gl.DEPTH32F_STENCIL8]]]];this._FormatTypeMap_Ext2Int=new Map;for(const[t,n]of e){const e=new Map;for(const[t,r]of n)e.set(t,r);this._FormatTypeMap_Ext2Int.set(t,e)}const n={GL_RED:this.gl.RED,GL_RED_INTEGER:this.gl.RED_INTEGER,GL_RG:this.gl.RG,GL_RG_INTEGER:this.gl.RG_INTEGER,GL_RGB:this.gl.RGB,GL_RGB_INTEGER:this.gl.RGB_INTEGER,GL_RGBA:this.gl.RGBA,GL_RGBA_INTEGER:this.gl.RGBA_INTEGER,GL_DEPTH_COMPONENT:this.gl.DEPTH_COMPONENT,GL_DEPTH_STENCIL:this.gl.DEPTH_STENCIL};this._FormatTypeMap_Ext2Str=new Map;for(const[t,e]of Object.entries(n))this._FormatTypeMap_Ext2Str.set(e,t)};this.frameID=null,this.cbRender=()=>{},this._onContextLost=t=>{t.preventDefault(),this.stop()},this._onContextRestored=e,this._onContextCreationError=t=>{console.error(t.statusMessage||"WebGL context creation error: unknown error.")},this.canvas.addEventListener("webglcontextlost",this._onContextLost,!1),this.canvas.addEventListener("webglcontextrestored",this._onContextRestored,!1),this.canvas.addEventListener("webglcontextcreationerror",this._onContextCreationError,!1),e()}compileShaderProgram(t){let e=this.gl.createProgram();if(!e)throw new Error("WebGL shader program creation failed.");for(const[n,r]of Object.entries(t)){const t=this.gl.createShader(this.shaderStage[n]);if(!t)throw new Error("WebGL shader creation failed.");if(this.gl.shaderSource(t,r),this.gl.compileShader(t),!this.gl.getShaderParameter(t,this.gl.COMPILE_STATUS)){const e=this.gl.getShaderInfoLog(t);throw this.gl.deleteShader(t),new Error("WebGL shader compile failed:"+e)}this.gl.attachShader(e,t)}if(this.gl.linkProgram(e),!this.gl.getProgramParameter(e,this.gl.LINK_STATUS)){const t=this.gl.getProgramInfoLog(e);throw this.gl.deleteProgram(e),new Error("WebGL shader compile failed:"+t)}return e}getShaderProgramUniformLocation(t,e){let n={};for(const r of e)n[r]=this.gl.getUniformLocation(t,r);return n}getShaderProgramUniformBlockLocation(t,e){let n={};for(const r of e)n[r]=this.gl.getUniformBlockIndex(t,r);return n}getShaderProgramAttribLocation(t,e){let n={};for(const r of e)n[r]=this.gl.getAttribLocation(t,r);return n}getGLArrayElementType(t){const e=t[Symbol.toStringTag];return e in this._ElementTypeMap_JS2GL?this._ElementTypeMap_JS2GL[e]:null}getGLTexInternalFormat(t,e){const n=this._FormatTypeMap_Ext2Int.get(e);if(n){const e=n.get(t);if(e)return e}return null}texImage2D(t,e,n,r,i,s){var a;const o=this.getGLArrayElementType(s);if(!o)throw new Error(`Unsupported data format: ${s[Symbol.toStringTag]}`);const l=this.getGLTexInternalFormat(i,o);if(!l)throw new Error(`No available internal format for ${s[Symbol.toStringTag]} and ${null!=(a=this._FormatTypeMap_Ext2Str.get(i))?a:"unknown"}.`);this.gl.HALF_FLOAT==o&&(s=new Uint16Array(s.buffer)),this.gl.texImage2D(t,e,l,n,r,0,i,o,s)}texImage3D(t,e,n,r,i,s,a){var o;const l=this.getGLArrayElementType(a);if(!l)throw new Error("Unsupported data format: "+a[Symbol.toStringTag]);const c=this.getGLTexInternalFormat(s,l);if(!c)throw new Error(`No available internal format for ${a[Symbol.toStringTag]} and ${null!=(o=this._FormatTypeMap_Ext2Str.get(s))?o:"unknown"}.`);this.gl.HALF_FLOAT==l&&(a=new Uint16Array(a.buffer)),this.gl.texImage3D(t,e,c,n,r,i,0,s,l,a)}run(t,e){if(this.running=!0,this.cbRender=t,e&&e instanceof HTMLVideoElement){this.syncMedia=e;const t=(n,r)=>{this.running&&(this.syncMediaTime=r.mediaTime,this.cbRender(this),this.frameID=e.requestVideoFrameCallback(t))};this.syncMediaTime=e.currentTime,this.cbRender(this),e.requestVideoFrameCallback(t)}else{const t=()=>{this.running&&(this.cbRender(this),this.frameID=requestAnimationFrame(t))};t()}}refresh(){this.cbRender(this)}getSyncMediaTime(){return this.syncMediaTime}stop(){null!==this.frameID&&(this.syncMedia?(this.syncMedia.cancelVideoFrameCallback(this.frameID),this.syncMedia=null,this.syncMediaTime=null):cancelAnimationFrame(this.frameID),this.frameID=null),this.running=!1}simulateContextFault(t){this._lost_context_sim&&(t?this._lost_context_sim.restoreContext():this._lost_context_sim.loseContext())}captureFrame(){const t=this.canvas.width,e=this.canvas.height,n=new Uint8ClampedArray(t*e*4);return this.gl.readPixels(0,0,t,e,this.gl.RGBA,this.gl.UNSIGNED_BYTE,n),{width:t,height:e,data:n}}destroy(){if(this._isDestroyed||!this.gl)return;const t=this.gl;try{const e=t.getExtension("WEBGL_lose_context");if(e&&e.loseContext(),t.clear(t.COLOR_BUFFER_BIT|t.DEPTH_BUFFER_BIT|t.STENCIL_BUFFER_BIT),t.flush(),this.canvas){const t=this.canvas.getContext("2d");t&&t.clearRect(0,0,this.canvas.width,this.canvas.height)}this.canvas&&(this.canvas.removeEventListener("webglcontextlost",this._onContextLost,!1),this.canvas.removeEventListener("webglcontextrestored",this._onContextRestored,!1),this.canvas.removeEventListener("webglcontextcreationerror",this._onContextCreationError,!1)),this.gl=null,this._isDestroyed=!0}catch(t){this._isDestroyed=!0}}}function length(t){return Math.sqrt(t.reduce((t,e)=>t+e*e,0))}function normalize$1(t){let e=length(t);return t.map(t=>t/e)}function mvmul(t,e){const n=t.length,r=e.length;let i=Array(n);for(let s=0;s<n;s++){i[s]=0;for(let n=0;n<r;n++)i[s]+=t[s][n]*e[n]}return i}function mmul(t,e){const n=t.length,r=e.length,i=e[0].length;let s=Array(n);for(let a=0;a<n;a++){let n=Array(i);for(let s=0;s<i;s++){n[s]=0;for(let i=0;i<r;i++)n[s]+=t[a][i]*e[i][s]}s[a]=n}return s}function transpose(t){const e=t.length,n=t[0].length;let r=Array(n);for(let i=0;i<n;i++){let n=Array(e);for(let r=0;r<e;r++)n[r]=t[r][i];r[i]=n}return r}function identity(t){let e=Array(t);for(let n=0;n<t;n++){let r=Array(t);for(let e=0;e<t;e++)r[e]=n==e?1:0;e[n]=r}return e}function det3(t){let e=0;return e+=t[0][0]*t[1][1]*t[2][2],e+=t[0][1]*t[1][2]*t[2][0],e+=t[0][2]*t[1][0]*t[2][1],e-=t[0][2]*t[1][1]*t[2][0],e-=t[0][1]*t[1][0]*t[2][2],e-=t[0][0]*t[1][2]*t[2][1],e}function inv3(t){const e=1/det3(t);return[[(t[1][1]*t[2][2]-t[2][1]*t[1][2])*e,(t[0][2]*t[2][1]-t[0][1]*t[2][2])*e,(t[0][1]*t[1][2]-t[0][2]*t[1][1])*e],[(t[1][2]*t[2][0]-t[1][0]*t[2][2])*e,(t[0][0]*t[2][2]-t[0][2]*t[2][0])*e,(t[1][0]*t[0][2]-t[0][0]*t[1][2])*e],[(t[1][0]*t[2][1]-t[2][0]*t[1][1])*e,(t[2][0]*t[0][1]-t[0][0]*t[2][1])*e,(t[0][0]*t[1][1]-t[1][0]*t[0][1])*e]]}function inv4(t){let e=[[...t[0]],[...t[1]],[...t[2]],[...t[3]]],n=[0,0,0,0],r=[0,0,0,0],i=0;for(let t=0;t<4;t++){let s=0;for(let i=t;i<4;i++)for(let a=t;a<4;a++)Math.abs(e[i][a])>s&&(s=Math.abs(e[i][a]),n[t]=i,r[t]=a);if(s<Number.EPSILON)return new Array(4).fill(new Array(4).fill(NaN));if(n[t]!=t)for(let r=0;r<4;r++)i=e[t][r],e[t][r]=e[n[t]][r],e[n[t]][r]=i;if(r[t]!=t)for(let n=0;n<4;n++)i=e[n][t],e[n][t]=e[n][r[t]],e[n][r[t]]=i;e[t][t]=1/e[t][t];for(let n=0;n<4;n++)n!=t&&(e[t][n]*=e[t][t]);for(let n=0;n<4;n++)if(n!=t)for(let r=0;r<4;r++)r!=t&&(e[n][r]-=e[n][t]*e[t][r]);for(let n=0;n<4;n++)n!=t&&(e[n][t]*=-e[t][t])}for(let t=3;t>=0;t--){if(r[t]!=t)for(let n=0;n<4;n++)i=e[t][n],e[t][n]=e[r[t]][n],e[r[t]][n]=i;if(n[t]!=t)for(let r=0;r<4;r++)i=e[r][t],e[r][t]=e[r][n[t]],e[r][n[t]]=i}return e}function quaternion_conj(t){return[t[0],-t[1],-t[2],-t[3]]}function quaternion_mul(t,e){return[t[0]*e[0]-t[1]*e[1]-t[2]*e[2]-t[3]*e[3],t[0]*e[1]+t[1]*e[0]+t[2]*e[3]-t[3]*e[2],t[0]*e[2]-t[1]*e[3]+t[2]*e[0]+t[3]*e[1],t[0]*e[3]+t[1]*e[2]-t[2]*e[1]+t[3]*e[0]]}function quaternion_to_mat(t){const[e,n,r,i]=t;return[[e*e+n*n-r*r-i*i,2*(n*r-i*e),2*(n*i+r*e)],[2*(n*r+i*e),e*e-n*n+r*r-i*i,2*(r*i-n*e)],[2*(n*i-r*e),2*(r*i+n*e),e*e-n*n-r*r+i*i]]}function GivensTransform(t,e,n,r){const i=Math.sin(r),s=Math.cos(r),a=t[0].length;for(let r=0;r<a;r++){const a=i*t[e][r]+s*t[n][r];t[e][r]=s*t[e][r]-i*t[n][r],t[n][r]=a}}function Euler_to_mat(t,e="xyz"){let n=identity(3);switch(e){case"xyz":case"zxy":GivensTransform(n,1,2,t[0]),GivensTransform(n,2,0,t[1]),GivensTransform(n,0,1,t[2]);break;case"yzx":GivensTransform(n,0,1,t[2]),GivensTransform(n,1,2,t[0]),GivensTransform(n,2,0,t[1]);break;case"xzy":GivensTransform(n,1,2,t[0]),GivensTransform(n,0,1,t[2]),GivensTransform(n,2,0,t[1]);break;case"yxz":GivensTransform(n,2,0,t[1]),GivensTransform(n,1,2,t[0]),GivensTransform(n,0,1,t[2]);break;case"zyx":GivensTransform(n,0,1,t[2]),GivensTransform(n,2,0,t[1]),GivensTransform(n,1,2,t[0]);break;default:throw Error("Unrecognizable rotation order.")}return n}function make_homogeneous(t,e){return[[t[0][0],t[0][1],t[0][2],e[0]],[t[1][0],t[1][1],t[1][2],e[1]],[t[2][0],t[2][1],t[2][2],e[2]],[0,0,0,1]]}function flatten(t){const e=t.length,n=t[0].length;let r=Array(e*n);for(let i=0;i<e;i++)for(let e=0;e<n;e++)r[i*n+e]=t[i][e];return r}const performanceConstant={load_resource:"load_resource",ttsa_connect:"ttsa_connect",ttsa_ready:"ttsa_ready",first_avatar_render:"first_avatar_render",first_webgl_render:"first_webgl_render",ttsa_body_res:"ttsa_body_res",start_action_res:"start_action_res",start_action_render:"start_action_render",load_video:"load_video",decode_video:"decode_video",voice_response_play:"voice_response_play",first_decode_video:"first_decode_video",first_render:"first_render"};class PerformanceTracker{constructor(){this.marks=new Map,this.measures=new Map,this.reportFunc=null,this.onStateRenderChange=()=>{},this.firstDecodeTime=0,this.firstRenderTime=0,this.marks=new Map,this.measures=new Map}getFirstInfo(){return{decode_speed:this.firstDecodeTime,render_speed:this.firstRenderTime}}markStart(t,e){this.marks.set(t,{state:e,time:performance.now()})}markEnd(t,e){const n=this.marks.get(t);if(!n)return;if(e&&"string"==typeof e&&e!==(null==n?void 0:n.state))return;const r=performance.now()-n.time;return this.measures.set(t,{state:null==n?void 0:n.state,time:r}),n.state&&t===performanceConstant.start_action_render&&this.onStateRenderChange(n.state,r),this.reportMetric(),t!==performanceConstant.load_video&&t!==performanceConstant.decode_video&&this.marks.delete(t),t===performanceConstant.first_decode_video&&(this.firstDecodeTime=r),t===performanceConstant.first_render&&(this.firstRenderTime=r),r}getAllMetrics(){return Object.fromEntries(this.measures.entries())}getVideoMetrics(){const t=this.getAllMetrics();return Object.fromEntries(Object.entries(t).filter(([t])=>[performanceConstant.decode_video,performanceConstant.load_video].includes(t)))}setReportFunc(t){this.reportFunc=t}reportMetric(){var t;const e=this.getAllMetrics();if(Object.keys(e).length>0&&null!=(t=this.reportFunc)&&t.getStatus()){const t=Object.fromEntries(Object.entries(e).filter(([t])=>![performanceConstant.load_video,performanceConstant.decode_video].includes(t)));var n;Object.keys(t).length>0&&(null==(n=this.reportFunc)||n.sendPerfLog(t));for(const e in t)e!==performanceConstant.decode_video&&e!==performanceConstant.load_video&&this.measures.delete(e)}}setOnStateRenderChange(t){this.onStateRenderChange=t}}window.performanceTracker=new PerformanceTracker;const shadow_sample_count=4,shader_common="\n float randFloat(vec2 p) {\n // generate a uniformely distributed float in [0, 1).\n return fract(sin(dot(p, vec2(127.1, 311.7))) * 43758.5453);\n }\n bool isMaskedBitSet(uint value, uint mask){\n return bool(value & mask);\n }\n vec4 RGB2sRGB(vec4 color){\n for(uint i = 0u; i < 4u; i++){\n if(color[i] <= 0.0031308)color[i] *= 12.92;\n else color[i] = 1.055 * pow(color[i], 1.0 / 2.4) - 0.055;\n }\n return color;\n }\n vec4 sRGB2RGB(vec4 color){\n for(uint i = 0u; i < 4u; i++){\n if(color[i] <= 0.04045)color[i] /= 12.92;\n else color[i] = pow((color[i] + 0.055) / 1.055, 2.4);\n }\n return color;\n }\n",vs_background="#version 300 es\n layout(location = 0) in vec2 pos;\n layout(location = 1) in vec2 texCoord;\n out vec2 v_texCoord;\n void main() {\n gl_Position = vec4(pos, 0, 1);\n v_texCoord = texCoord;\n }\n",fs_background=`#version 300 es\n precision mediump float;\n uniform sampler2D u_image_bg, u_image_char_body, u_image_mesh_color, u_image_mesh_alpha;\n uniform mat2 u_transform_2d; // mat2[0] = scale, mat2[1] = translation\n uniform uint flags; // 1 - has background, 2 - with multisample coverage, 4 - shadow fx\n\n layout (std140) uniform ub_shadow_fx_info {\n mat3 transform[2];\n vec4 color;\n vec4 sampleParams; // sample radius, unused, unused, unused \n } ub_shadow_fx;\n\n in vec2 v_texCoord;\n out vec4 fragColor;\n\n ${shader_common}\n\n vec2 tex2scr(vec2 coord){\n return vec2(coord.x * 2.0 - 1.0, 1.0 - coord.y * 2.0);\n }\n vec2 scr2tex(vec2 coord){\n return vec2(coord.x * 0.5 + 0.5, 0.5 - coord.y * 0.5);\n }\n vec2 randomUnitVec2D(float seed) {\n float theta = seed * 2.0 * 3.14159265359;\n return vec2(cos(theta), sin(theta));\n }\n float sampleOpacity(vec2 texCoord, mat2 u_transform_2d){\n float result = texture(u_image_mesh_color, vec2(texCoord.x, 1.0 - texCoord.y)).a;\n texCoord = texCoord * u_transform_2d[0] + u_transform_2d[1];\n texCoord.x = texCoord.x * 0.5 + 0.5;\n result += (1.0 - result) * texture(u_image_char_body, texCoord).r;\n return result;\n }\n float PI = 3.14159265359;\n\n void main() {\n float randSeed = randFloat(vec2(gl_FragCoord.xy));\n\n vec2 texcoord_transformed = v_texCoord * u_transform_2d[0] + u_transform_2d[1];\n texcoord_transformed = clamp(texcoord_transformed, 0.0, 1.0);\n vec2 texCoord_char_color = vec2(texcoord_transformed.x * 0.5, texcoord_transformed.y);\n vec2 texCoord_char_alpha = vec2(texcoord_transformed.x * 0.5 + 0.5, texcoord_transformed.y);\n vec2 texCoord_mesh = vec2(v_texCoord.x, 1.0 - v_texCoord.y);\n\n vec4 char_color = texture(u_image_char_body, texCoord_char_color);\n vec4 char_alpha = texture(u_image_char_body, texCoord_char_alpha);\n char_color = sRGB2RGB(char_color);\n char_alpha = sRGB2RGB(char_alpha);\n float char_alpha_back = char_alpha.r;\n float char_alpha_front = max(char_alpha.r - char_alpha.b, 0.0);\n\n vec4 mesh_color_srgb = texture(u_image_mesh_color, texCoord_mesh);\n float mesh_alpha = mesh_color_srgb.a;\n if(isMaskedBitSet(flags, 2u)){\n float mesh_coverage = texture(u_image_mesh_alpha, texCoord_mesh).r;\n mesh_color_srgb.rgb /= max(mesh_coverage, 9e-5); // epsilon for float16\n }\n\n vec3 final_rgb = char_alpha_back * char_color.rgb;\n float final_alpha = char_alpha_back;\n\n if(isMaskedBitSet(flags, 4u)){ // fake shadow\n vec3 pos_shadow = vec3(tex2scr(v_texCoord), 1.0);\n pos_shadow = ub_shadow_fx.transform[1] * pos_shadow;\n if(pos_shadow.z > 0.0 && pos_shadow.y > 0.0){\n // simple and noisy blur\n pos_shadow /= pos_shadow.z;\n float radius = ub_shadow_fx.sampleParams.x * pos_shadow.y;\n vec2 randVec = randomUnitVec2D(randSeed);\n mat2 randMat = mat2(randVec.x, randVec.y, -randVec.y, randVec.x);\n float shadow_opacity = 0.0;\n\n int sampleCount = radius > 0.0 ? ${shadow_sample_count} : 1;\n for(int i=0;i<sampleCount;i++){\n float sampleDist = (float(i) + 0.5) / float(sampleCount);\n float angle = 26.0 * PI * sampleDist; // prime number * 2pi\n sampleDist = radius * sqrt(sampleDist);\n vec2 sampleVec = sampleDist * randMat * vec2(cos(angle), sin(angle));\n\n vec3 pos_shadow_proj = ub_shadow_fx.transform[0] * (pos_shadow + vec3(sampleVec, 0.0));\n vec2 texCoord_shadow = clamp(pos_shadow_proj.xy / pos_shadow_proj.z, -1.0, 1.0);\n texCoord_shadow = scr2tex(texCoord_shadow);\n shadow_opacity += sampleOpacity(texCoord_shadow, u_transform_2d);\n }\n shadow_opacity /= float(sampleCount);\n float shadow_alpha = shadow_opacity * ub_shadow_fx.color.a;\n\n final_rgb = final_rgb + (1.0 - final_alpha) * shadow_alpha * ub_shadow_fx.color.rgb;\n final_alpha = final_alpha + (1.0 - final_alpha) * shadow_alpha;\n }\n }\n final_rgb = mesh_alpha * mesh_color_srgb.rgb + (1.0 - mesh_alpha) * final_rgb;\n final_alpha = mesh_alpha + (1.0 - mesh_alpha) * final_alpha;\n final_rgb = char_alpha_front * char_color.rgb + (1.0 - char_alpha_front) * final_rgb;\n final_alpha = char_alpha_front + (1.0 - char_alpha_front) * final_alpha;\n\n if(isMaskedBitSet(flags, 1u)){\n vec4 bg_color = sRGB2RGB(texture(u_image_bg, v_texCoord));\n final_rgb += bg_color.rgb * (1.0 - final_alpha);\n final_alpha = 1.0;\n }\n final_rgb = RGB2sRGB(vec4(final_rgb, 1.0)).rgb;\n fragColor = vec4(final_rgb, final_alpha);\n }\n`,uniform_var_list_bg=["u_image_bg","u_image_char_body","u_image_mesh_color","u_image_mesh_alpha","u_transform_2d","flags"],uniform_block_list_bg=["ub_shadow_fx_info"];function generateMeshPipelineShader(t){return{vertex:`#version 300 es\n precision highp float;\n\n layout (std140) uniform ub_rig_info {\n mat4 joint_matrices[${t.max_bones}];\n vec4 bs_weights[${t.max_bs_count/4}];\n } ub_rig;\n \n uniform sampler2D u_image_bs; // used for blendshape deformation\n uniform mat4 u_proj_mat;\n uniform mat2 u_transform_2d; // mat2[0] = scale, mat2[1] = translation\n uniform uint u_bs_count; // number of bs weight vectors (divided by 4)\n uniform uint flags; // 1 - has opacity\n\n layout(location = 0) in vec3 pos;\n layout(location = 1) in vec2 tex_coord;\n layout(location = 2) in float opacity;\n layout(location = 3) in uvec4 bone_index_0_4;\n layout(location = 4) in uvec4 bone_index_4_8;\n layout(location = 5) in vec4 bone_weight_0_4;\n layout(location = 6) in vec4 bone_weight_4_8;\n\n out vec4 v_pos;\n out vec2 v_tex_coord;\n out float v_opacity;\n\n ${shader_common}\n\n vec4 lbs_transform(vec3 pos){\n float total_weight = 0.0;\n vec4 aug_pos = vec4(pos, 1.0);\n vec4 result = vec4(0.0);\n uint index;\n for(index = 0u;index < 8u;index++){\n uint joint_index;\n float joint_weight;\n if(index < 4u) {\n joint_index = bone_index_0_4[index];\n joint_weight = bone_weight_0_4[index];\n }\n else {\n joint_index = bone_index_4_8[index - 4u];\n joint_weight = bone_weight_4_8[index - 4u];\n }\n if(255u == joint_index)break;\n else result += joint_weight * (ub_rig.joint_matrices[joint_index] * aug_pos);\n }\n result /= result.w;\n return vec4(result.xyz, 1.0);\n }\n\n vec3 bs_accumulate(uint vertex_id){\n uint texWidth = uint(textureSize(u_image_bs, 0).x);\n vec3 pos = vec3(0.0);\n\n uint vertex_offset = vertex_id * u_bs_count * 3u;\n for(uint i = 0u; i < u_bs_count; i++){\n vec4 bs_weight_vec = ub_rig.bs_weights[i];\n for (uint j = 0u; j < 3u; j++){\n uint texel_offset = j * u_bs_count + vertex_offset + i;\n uint texel_x = texel_offset % texWidth;\n uint texel_y = texel_offset / texWidth;\n vec4 data = texelFetch(u_image_bs, ivec2(texel_x, texel_y), 0);\n pos[j] += dot(data, bs_weight_vec);\n }\n }\n return pos;\n }\n \n void main() {\n if(isMaskedBitSet(flags, 1u))v_opacity = opacity; else v_opacity = 1.0;\n \n vec3 bs_pos = vec3(0.0);\n if(u_bs_count > 0u)bs_pos = bs_accumulate(uint(gl_VertexID)) * v_opacity;\n v_pos = u_proj_mat * lbs_transform(pos + bs_pos);\n v_pos /= v_pos.w;\n v_pos.xy = u_transform_2d[0] * v_pos.xy + u_transform_2d[1];\n v_tex_coord = tex_coord;\n gl_Position = v_pos;\n }\n`,fragment_mask:"#version 300 es\n precision highp float;\n \n in vec4 v_pos;\n in float v_opacity;\n in vec2 v_tex_coord;\n\n out vec4 fragColor;\n\n void main() {\n if(gl_FrontFacing)fragColor = vec4(1.0);\n else fragColor = vec4(0.0);\n }\n",fragment:`#version 300 es\n precision highp int;\n precision highp float;\n precision highp sampler2DArray;\n precision highp sampler3D;\n layout (std140) uniform ub_pca_info {\n vec4 weights[${t.max_pca_component_count/4}];\n } ub_pca;\n uniform sampler2DArray u_image_pca;\n uniform sampler3D u_image_lut;\n uniform uint flags; // 2 - has LUT, 4 - unsigned PCA component\n uniform vec3 u_gamma;\n uniform vec3 u_color_balance; // r/c, g/m, b/y\n\n ${shader_common}\n \n vec4 pca_accumulate(vec2 tex_coord, bool _unsigned){\n ivec3 texSize = textureSize(u_image_pca, 0);\n vec4 result = vec4(0.0);\n for(int i = 0; i < texSize.z; i++){\n int vec_index = i / 4;\n int elem_index = i % 4;\n vec4 pca_sample = texture(u_image_pca, vec3(tex_coord, float(i)));\n if(_unsigned)pca_sample = 2.0 * pca_sample - 1.0;\n result += ub_pca.weights[vec_index][elem_index] * pca_sample;\n }\n return result;\n }\n \n in vec4 v_pos;\n in float v_opacity;\n in vec2 v_tex_coord;\n\n out vec4 fragColor;\n\n void main() {\n if(gl_FrontFacing){\n vec2 fragTexCoord = v_tex_coord;\n vec4 sample_color = pca_accumulate(v_tex_coord, isMaskedBitSet(flags, 4u));\n if(isMaskedBitSet(flags, 2u))sample_color = texture(u_image_lut, sample_color.rgb);\n // Apply gamma correction\n vec3 final_color = pow(sample_color.rgb, u_gamma);\n\n // Apply color balance\n // Convert -100 to 100 range to -0.5 to 0.5 range\n vec3 balance_adjusted = u_color_balance / 200.0; // Map -100..100 to -0.5..0.5\n\n // Red/Cyan adjustment\n final_color.r += balance_adjusted.x;\n final_color.g -= balance_adjusted.x; // Cyan is opposite of Red\n\n // Green/Magenta adjustment\n final_color.g += balance_adjusted.y;\n final_color.b -= balance_adjusted.y; // Magenta is opposite of Green\n\n // Blue/Yellow adjustment\n final_color.b += balance_adjusted.z;\n final_color.r -= balance_adjusted.z; // Yellow is opposite of Blue\n\n // Clamp values to [0, 1]\n final_color = clamp(final_color, 0.0, 1.0);\n fragColor = sRGB2RGB(vec4(final_color.bgr, v_opacity));\n }\n else fragColor = vec4(0.0);\n }\n`}}const uniform_var_list_mesh=["u_proj_mat","u_transform_2d","u_image","u_image_bs","u_image_pca","u_image_lut","u_bs_count","flags","u_gamma","u_color_balance"],uniform_block_list_mesh=["ub_pca_info","ub_rig_info"];class GLPipeline{assembleBackgroundPipeline(){this._ub_shadow_fx_data=new Float32Array(32);const t=this.device.compileShaderProgram({vertex:vs_background,fragment:fs_background}),e=this.device.getShaderProgramUniformLocation(t,uniform_var_list_bg),n=this.device.getShaderProgramUniformBlockLocation(t,uniform_block_list_bg);this.backgroundPipelineInfo={program:t,progUniforms:e,progUniformBlocks:n},this.device.gl.uniformBlockBinding(this.backgroundPipelineInfo.program,this.backgroundPipelineInfo.progUniformBlocks.ub_shadow_fx_info,0),this.backgroundVAO=this.device.gl.createVertexArray(),this.device.gl.bindVertexArray(this.backgroundVAO);const r=this.device.gl.createBuffer();this.device.gl.bindBuffer(this.device.gl.ARRAY_BUFFER,r),this.device.gl.bufferData(this.device.gl.ARRAY_BUFFER,new Float32Array([-1,-1,0,1,1,-1,1,1,-1,1,0,0,-1,1,0,0,1,-1,1,1,1,1,1,0]),this.device.gl.STATIC_DRAW),this.device.gl.enableVertexAttribArray(0),this.device.gl.vertexAttribPointer(0,2,this.device.gl.FLOAT,!1,16,0),this.device.gl.enableVertexAttribArray(1),this.device.gl.vertexAttribPointer(1,2,this.device.gl.FLOAT,!1,16,8),this.device.gl.bindBuffer(this.device.gl.ARRAY_BUFFER,null);let i={};i.ub_shadow_fx_info=this.device.gl.createBuffer(),this.device.gl.bindBuffer(this.device.gl.UNIFORM_BUFFER,i.ub_shadow_fx_info),this.device.gl.bufferData(this.device.gl.UNIFORM_BUFFER,this._ub_shadow_fx_data,this.device.gl.DYNAMIC_DRAW),this.backgroundBuffers=i,this.device.gl.bindVertexArray(null);let s={};if(s.u_image_bg=this.device.gl.createTexture(),!s.u_image_bg)throw new Error("WebGL texture creation failed.");if(this.device.gl.bindTexture(this.device.gl.TEXTURE_2D,s.u_image_bg),this.device.gl.texParameteri(this.device.gl.TEXTURE_2D,this.device.gl.TEXTURE_WRAP_S,this.device.gl.CLAMP_TO_EDGE),this.device.gl.texParameteri(this.device.gl.TEXTURE_2D,this.device.gl.TEXTURE_WRAP_T,this.device.gl.CLAMP_TO_EDGE),this.device.gl.texParameteri(this.device.gl.TEXTURE_2D,this.device.gl.TEXTURE_MIN_FILTER,this.device.gl.LINEAR),s.u_image_char_body=this.device.gl.createTexture(),!s.u_image_char_body)throw new Error("WebGL texture creation failed.");this.device.gl.bindTexture(this.device.gl.TEXTURE_2D,s.u_image_char_body),this.device.gl.texParameteri(this.device.gl.TEXTURE_2D,this.device.gl.TEXTURE_WRAP_S,this.device.gl.CLAMP_TO_EDGE),this.device.gl.texParameteri(this.device.gl.TEXTURE_2D,this.device.gl.TEXTURE_WRAP_T,this.device.gl.CLAMP_TO_EDGE),this.device.gl.texParameteri(this.device.gl.TEXTURE_2D,this.device.gl.TEXTURE_MIN_FILTER,this.device.gl.LINEAR),this.backgroundTextures=s}assembleMeshPipelines(t){if(t.char){const e=t.char;let n={max_pca_component_count:4,max_bs_count:4,max_bones:Math.max(e.skeleton.length,1)};for(let t=0;t<e.mesh.length;t++){const r=e.mesh[t].textureModels;let i=0;for(let t of r){let e=t.data.size[0]+3;e-=e%4,i=Math.max(i,e)}n.max_pca_component_count=Math.max(n.max_pca_component_count,i);let s=e.mesh[t].blendshapes.size[2]+3;s-=s%4,n.max_bs_count=Math.max(n.max_bs_count,s)}this.meshStatistics=n,this._ub_rig_info_data=new Float32Array(16*this.meshStatistics.max_bones+this.meshStatistics.max_bs_count),this._ub_pca_info_data=new Float32Array(this.meshStatistics.max_pca_component_count);const r=generateMeshPipelineShader(this.meshStatistics);let i=this.device.compileShaderProgram({vertex:r.vertex,fragment:r.fragment}),s=this.device.getShaderProgramUniformLocation(i,uniform_var_list_mesh),a=this.device.getShaderProgramUniformBlockLocation(i,uniform_block_list_mesh);this.meshPipelineInfo={program:i,progUniforms:s,progUniformBlocks:a},this.device.gl.uniformBlockBinding(this.meshPipelineInfo.program,this.meshPipelineInfo.progUniformBlocks.ub_rig_info,0),this.device.gl.uniformBlockBinding(this.meshPipelineInfo.program,this.meshPipelineInfo.progUniformBlocks.ub_pca_info,1),i=this.device.compileShaderProgram({vertex:r.vertex,fragment:r.fragment_mask}),s=this.device.getShaderProgramUniformLocation(i,uniform_var_list_mesh),a=this.device.getShaderProgramUniformBlockLocation(i,uniform_block_list_mesh),this.maskPipelineInfo={program:i,progUniforms:s,progUniformBlocks:a},this.device.gl.uniformBlockBinding(this.maskPipelineInfo.program,this.maskPipelineInfo.progUniformBlocks.ub_rig_info,0),this.meshInfos=[];for(let t=0;t<e.mesh.length;t++){let r={VAO:this.device.gl.createVertexArray(),buffers:{},textures:{},texturePCAModels:[],uniformUInts:{}};if(this.device.gl.bindVertexArray(r.VAO),null===this.device.getGLArrayElementType(e.mesh[t].blendshapes.data))throw new Error(`Data type unsupported by WebGL: ${e.mesh[t].blendshapes.data}`);if(r.buffers.pos=this.device.gl.createBuffer(),this.device.gl.bindBuffer(this.device.gl.ARRAY_BUFFER,r.buffers.pos),this.device.gl.bufferData(this.device.gl.ARRAY_BUFFER,e.mesh[t].vertices.data,this.device.gl.STATIC_DRAW),this.device.gl.enableVertexAttribArray(0),this.device.gl.vertexAttribPointer(0,3,this.device.getGLArrayElementType(e.mesh[t].blendshapes.data),!1,0,0),null===this.device.getGLArrayElementType(e.mesh[t].UVCoord.data))throw new Error(`Data type unsupported by WebGL: ${e.mesh[t].UVCoord.data}`);if(r.buffers.tex_coord=this.device.gl.createBuffer(),this.device.gl.bindBuffer(this.device.gl.ARRAY_BUFFER,r.buffers.tex_coord),this.device.gl.bufferData(this.device.gl.ARRAY_BUFFER,e.mesh[t].UVCoord.data,this.device.gl.STATIC_DRAW),this.device.gl.enableVertexAttribArray(1),this.device.gl.vertexAttribPointer(1,2,this.device.getGLArrayElementType(e.mesh[t].UVCoord.data),!0,0,0),e.mesh[t].opacity){if(null===this.device.getGLArrayElementType(e.mesh[t].opacity.data))throw new Error(`Data type unsupported by WebGL: ${e.mesh[t].opacity.data}`);r.buffers.opacity=this.device.gl.createBuffer(),this.device.gl.bindBuffer(this.device.gl.ARRAY_BUFFER,r.buffers.opacity),this.device.gl.bufferData(this.device.gl.ARRAY_BUFFER,e.mesh[t].opacity.data,this.device.gl.STATIC_DRAW),this.device.gl.enableVertexAttribArray(2),this.device.gl.vertexAttribPointer(2,1,this.device.getGLArrayElementType(e.mesh[t].opacity.data),!0,0,0)}if(r.buffers.bone_indices=this.device.gl.createBuffer(),this.device.gl.bindBuffer(this.device.gl.ARRAY_BUFFER,r.buffers.bone_indices),this.device.gl.bufferData(this.device.gl.ARRAY_BUFFER,e.mesh[t].jointIndex,this.device.gl.STATIC_DRAW),this.device.gl.enableVertexAttribArray(3),this.device.gl.vertexAttribIPointer(3,4,this.device.gl.UNSIGNED_BYTE,8,0),this.device.gl.enableVertexAttribArray(4),this.device.gl.vertexAttribIPointer(4,4,this.device.gl.UNSIGNED_BYTE,8,4),r.buffers.bone_weight=this.device.gl.createBuffer(),this.device.gl.bindBuffer(this.device.gl.ARRAY_BUFFER,r.buffers.bone_weight),this.device.gl.bufferData(this.device.gl.ARRAY_BUFFER,e.mesh[t].jointWeight,this.device.gl.STATIC_DRAW),this.device.gl.enableVertexAttribArray(5),this.device.gl.vertexAttribPointer(5,4,this.device.gl.FLOAT,!1,32,0),this.device.gl.enableVertexAttribArray(6),this.device.gl.vertexAttribPointer(6,4,this.device.gl.FLOAT,!1,32,16),this.device.gl.bindBuffer(this.device.gl.ARRAY_BUFFER,null),null===this.device.getGLArrayElementType(e.mesh[t].triangles.data))throw new Error(`Data type unsupported by WebGL: ${e.mesh[t].triangles.data}`);if(r.buffers.indices=this.device.gl.createBuffer(),this.device.gl.bindBuffer(this.device.gl.ELEMENT_ARRAY_BUFFER,r.buffers.indices),this.device.gl.bufferData(this.device.gl.ELEMENT_ARRAY_BUFFER,e.mesh[t].triangles.data,this.device.gl.STATIC_DRAW),r.buffers.ub_pca_info=this.device.gl.createBuffer(),this.device.gl.bindBuffer(this.device.gl.UNIFORM_BUFFER,r.buffers.ub_pca_info),this.device.gl.bufferData(this.device.gl.UNIFORM_BUFFER,new Float32Array(n.max_pca_component_count),this.device.gl.DYNAMIC_DRAW),r.buffers.ub_rig_info=this.device.gl.createBuffer(),this.device.gl.bindBuffer(this.device.gl.UNIFORM_BUFFER,r.buffers.ub_rig_info),this.device.gl.bufferData(this.device.gl.UNIFORM_BUFFER,new Float32Array(16*n.max_bones+n.max_bs_count),this.device.gl.DYNAMIC_DRAW),this.device.gl.bindVertexArray(null),e.mesh[t].blendshapes.size[2]>0){let n=[Math.ceil(e.mesh[t].blendshapes.size[2]/4),e.mesh[t].blendshapes.size[0]*e.mesh[t].blendshapes.size[1]],i=Math.ceil(Math.sqrt(n[0]*n[1])),s=4*n[0],a=new Float32Array(i*i*4);for(let r=0;r<n[1];r++){for(let n=0;n<e.mesh[t].blendshapes.size[2];n++)a[r*s+n]=e.mesh[t].blendshapes.data[r*e.mesh[t].blendshapes.size[2]+n];for(let n=e.mesh[t].blendshapes.size[2];n<s;n++)a[r*s+n]=0}if(r.textures.u_image_bs=this.device.gl.createTexture(),!r.textures.u_image_bs)throw new Error("WebGL texture creation failed.");this.device.gl.bindTexture(this.device.gl.TEXTURE_2D,r.textures.u_image_bs),this.device.gl.texParameteri(this.device.gl.TEXTURE_2D,this.device.gl.TEXTURE_WRAP_S,this.device.gl.CLAMP_TO_EDGE),this.device.gl.texParameteri(this.device.gl.TEXTURE_2D,this.device.gl.TEXTURE_WRAP_T,this.device.gl.CLAMP_TO_EDGE),this.device.gl.texParameteri(this.device.gl.TEXTURE_2D,this.device.gl.TEXTURE_MIN_FILTER,this.device.gl.NEAREST),this.device.gl.texParameteri(this.device.gl.TEXTURE_2D,this.device.gl.TEXTURE_MAG_FILTER,this.device.gl.NEAREST),this.device.texImage2D(this.device.gl.TEXTURE_2D,0,i,i,this.device.gl.RGBA,a),r.uniformUInts.u_bs_count=n[0]}else r.uniformUInts.u_bs_count=0;for(let n of e.mesh[t].textureModels){let t=this.device.gl.createTexture();if(!t)throw new Error("WebGL texture creation failed.");this.device.gl.bindTexture(this.device.gl.TEXTURE_2D_ARRAY,t),this.device.gl.texParameteri(this.device.gl.TEXTURE_2D_ARRAY,this.device.gl.TEXTURE_WRAP_R,this.device.gl.CLAMP_TO_EDGE),this.device.gl.texParameteri(this.device.gl.TEXTURE_2D_ARRAY,this.device.gl.TEXTURE_WRAP_S,this.device.gl.CLAMP_TO_EDGE),this.device.gl.texParameteri(this.device.gl.TEXTURE_2D_ARRAY,this.device.gl.TEXTURE_WRAP_T,this.device.gl.CLAMP_TO_EDGE),this.device.gl.texParameteri(this.device.gl.TEXTURE_2D_ARRAY,this.device.gl.TEXTURE_MIN_FILTER,this.device.gl.LINEAR),this.device.gl.texParameteri(this.device.gl.TEXTURE_2D_ARRAY,this.device.gl.TEXTURE_MAG_FILTER,this.device.gl.LINEAR);let e=this.device.getGLArrayElementType(n.data.data),i={texture:t,unsigned:this.device.gl.UNSIGNED_BYTE===e||this.device.gl.UNSIGNED_SHORT===e||this.device.gl.UNSIGNED_INT===e},s=n.data.data;if("Float64Array"===n.data.data[Symbol.toStringTag]||this.device.gl.FLOAT===e&&!this.compat_features.OES_texture_float_linear||this.device.gl.HALF_FLOAT===e&&!this.compat_features.OES_texture_half_float_linear){const t=n.data.size[1]*n.data.size[2]*3,e=new Uint8Array(n.data.size[0]*t);let r=new Float32Array(n.data.size[0]);for(let i=0;i<n.data.size[0];i++){let s=1e-6;for(let e=0;e<t;e++)s=Math.max(s,Math.abs(n.data.data[i*t+e]));let a=1/s;for(let r=0;r<t;r++)e[i*t+r]=Math.round(255*(n.data.data[i*t+r]*a*.5+.5));r[i]=s}s=e,i.unsigned=!0,i.scalingFactor=r}n.scalingFactor&&(i.scalingFactor=n.scalingFactor.data),this.device.texImage3D(this.device.gl.TEXTURE_2D_ARRAY,0,n.data.size[1],n.data.size[2],n.data.size[0],this.device.gl.RGB,s),this.device.gl.bindTexture(this.device.gl.TEXTURE_2D_ARRAY,null),r.texturePCAModels.push(i)}this.meshInfos.push(r)}this.initSkeletonStatus=e.evalSkeleton()}if(this.FrameTexture_meshColor=this.device.gl.createTexture(),!this.FrameTexture_meshColor)throw Error("WebGL texture creation failed.");if(this.device.gl.bindTexture(this.device.gl.TEXTURE_2D,this.FrameTexture_meshColor),this.device.gl.texParameteri(this.device.gl.TEXTURE_2D,this.device.gl.TEXTURE_WRAP_S,this.device.gl.CLAMP_TO_EDGE),this.device.gl.texParameteri(this.device.gl.TEXTURE_2D,this.device.gl.TEXTURE_WRAP_T,this.device.gl.CLAMP_TO_EDGE),this.device.gl.texParameteri(this.device.gl.TEXTURE_2D,this.device.gl.TEXTURE_MIN_FILTER,this.device.gl.NEAREST),this.device.gl.texParameteri(this.device.gl.TEXTURE_2D,this.device.gl.TEXTURE_MAG_FILTER,this.device.gl.NEAREST),this.device.gl.texImage2D(this.device.gl.TEXTURE_2D,0,this.device.gl.RGBA8,this.device.canvas.width,this.device.canvas.height,0,this.device.gl.RGBA,this.device.gl.UNSIGNED_BYTE,null),t.multisample){if(this.FrameTexture_meshAlpha=this.device.gl.createTexture(),!this.FrameTexture_meshAlpha)throw Error("WebGL texture creation failed.");this.device.gl.bindTexture(this.device.gl.TEXTURE_2D,this.FrameTexture_meshAlpha),this.device.gl.texParameteri(this.device.gl.TEXTURE_2D,this.device.gl.TEXTURE_WRAP_S,this.device.gl.CLAMP_TO_EDGE),this.device.gl.texParameteri(this.device.gl.TEXTURE_2D,this.device.gl.TEXTURE_WRAP_T,this.device.gl.CLAMP_TO_EDGE),this.device.gl.texParameteri(this.device.gl.TEXTURE_2D,this.device.gl.TEXTURE_MIN_FILTER,this.device.gl.NEAREST),this.device.gl.texParameteri(this.device.gl.TEXTURE_2D,this.device.gl.TEXTURE_MAG_FILTER,this.device.gl.NEAREST),this.device.gl.texImage2D(this.device.gl.TEXTURE_2D,0,this.device.gl.RGBA8,this.device.canvas.width,this.device.canvas.height,0,this.device.gl.RGBA,this.device.gl.UNSIGNED_BYTE,null),this.FrameBuffer_meshColor=this.device.gl.createFramebuffer(),this.device.gl.bindFramebuffer(this.device.gl.FRAMEBUFFER,this.FrameBuffer_meshColor),this.device.gl.framebufferTexture2D(this.device.gl.FRAMEBUFFER,this.device.gl.COLOR_ATTACHMENT0,this.device.gl.TEXTURE_2D,this.FrameTexture_meshColor,0),this.FrameBuffer_meshAlpha=this.device.gl.createFramebuffer(),this.device.gl.bindFramebuffer(this.device.gl.FRAMEBUFFER,this.FrameBuffer_meshAlpha),this.device.gl.framebufferTexture2D(this.device.gl.FRAMEBUFFER,this.device.gl.COLOR_ATTACHMENT0,this.device.gl.TEXTURE_2D,this.FrameTexture_meshAlpha,0);const e=this.device.gl.createRenderbuffer();this.device.gl.bindRenderbuffer(this.device.gl.RENDERBUFFER,e),this.device.gl.renderbufferStorageMultisample(this.device.gl.RENDERBUFFER,t.multisample,this.device.gl.DEPTH_COMPONENT16,this.device.canvas.width,this.device.canvas.height);const n=this.device.gl.createRenderbuffer();this.device.gl.bindRenderbuffer(this.device.gl.RENDERBUFFER,n),this.device.gl.renderbufferStorageMultisample(this.device.gl.RENDERBUFFER,t.multisample,this.device.gl.RGBA8,this.device.canvas.width,this.device.canvas.height);const r=this.device.gl.createRenderbuffer();this.device.gl.bindRenderbuffer(this.device.gl.RENDERBUFFER,r),this.device.gl.renderbufferStorageMultisample(this.device.gl.RENDERBUFFER,t.multisample,this.device.gl.R8,this.device.canvas.width,this.device.canvas.height),this.FrameBuffer_mesh=this.device.gl.createFramebuffer(),this.device.gl.bindFramebuffer(this.device.gl.FRAMEBUFFER,this.FrameBuffer_mesh),this.device.gl.framebufferRenderbuffer(this.device.gl.FRAMEBUFFER,this.device.gl.COLOR_ATTACHMENT0,this.device.gl.RENDERBUFFER,n),this.device.gl.framebufferRenderbuffer(this.device.gl.FRAMEBUFFER,this.device.gl.COLOR_ATTACHMENT1,this.device.gl.RENDERBUFFER,r),this.device.gl.framebufferRenderbuffer(this.device.gl.FRAMEBUFFER,this.device.gl.DEPTH_ATTACHMENT,this.device.gl.RENDERBUFFER,e)}else{this.FrameTexture_meshAlpha=null,this.FrameBuffer_meshColor=null,this.FrameBuffer_meshAlpha=null;const t=this.device.gl.createRenderbuffer();this.device.gl.bindRenderbuffer(this.device.gl.RENDERBUFFER,t),this.device.gl.renderbufferStorage(this.device.gl.RENDERBUFFER,this.device.gl.DEPTH_COMPONENT16,this.device.canvas.width,this.device.canvas.height),this.FrameBuffer_mesh=this.device.gl.createFramebuffer(),this.device.gl.bindFramebuffer(this.device.gl.FRAMEBUFFER,this.FrameBuffer_mesh),this.device.gl.framebufferTexture2D(this.device.gl.FRAMEBUFFER,this.device.gl.COLOR_ATTACHMENT0,this.device.gl.TEXTURE_2D,this.FrameTexture_meshColor,0),this.device.gl.framebufferRenderbuffer(this.device.gl.FRAMEBUFFER,this.device.gl.DEPTH_ATTACHMENT,this.device.gl.RENDERBUFFER,t)}if(this.device.gl.bindFramebuffer(this.device.gl.FRAMEBUFFER,null),null===t.LUT)this.LUTTexture=null;else{if(this.LUTTexture=this.device.gl.createTexture(),!this.LUTTexture)throw new Error("WebGL texture creation failed.");if(this.device.gl.bindTexture(this.device.gl.TEXTURE_3D,this.LUTTexture),this.device.gl.texParameteri(this.device.gl.TEXTURE_3D,this.device.gl.TEXTURE_WRAP_R,this.device.gl.CLAMP_TO_EDGE),this.device.gl.texParameteri(this.device.gl.TEXTURE_3D,this.device.gl.TEXTURE_WRAP_S,this.device.gl.CLAMP_TO_EDGE),this.device.gl.texParameteri(this.device.gl.TEXTURE_3D,this.device.gl.TEXTURE_WRAP_T,this.device.gl.CLAMP_TO_EDGE),this.device.gl.texParameteri(this.device.gl.TEXTURE_3D,this.device.gl.TEXTURE_MIN_FILTER,this.device.gl.LINEAR),this.device.gl.texParameteri(this.device.gl.TEXTURE_3D,this.device.gl.TEXTURE_MAG_FILTER,this.device.gl.LINEAR),this.compat_features.OES_texture_float_linear)this.device.texImage3D(this.device.gl.TEXTURE_3D,0,t.LUT.size[1],t.LUT.size[2],t.LUT.size[0],this.device.gl.RGB,t.LUT.data);else{const e=new Uint8Array(t.LUT.size[0]*t.LUT.size[1]*t.LUT.size[2]*3);for(let n=0;n<e.length;n++)e[n]=Math.round(255*t.LUT.data[n]);this.device.texImage3D(this.device.gl.TEXTURE_3D,0,t.LUT.size[1],t.LUT.size[2],t.LUT.size[0],this.device.gl.RGB,e)}this.device.gl.bindTexture(this.device.gl.TEXTURE_3D,null)}this.backgroundTextureSrc=null}getProjMat(t){return mmul(t.getProjMatrix([this.device.canvas.width,this.device.canvas.height],200,800),t.getExtrinsicMatrix())}initFrame(){this.device.gl.viewport(0,0,this.device.gl.drawingBufferWidth,this.device.gl.drawingBufferHeight),this.device.gl.clearColor(0,0,0,0),this.device.gl.clearDepth(1),this.charData&&(this.charData.multisample?(this.device.gl.bindFramebuffer(this.device.gl.FRAMEBUFFER,this.FrameBuffer_meshColor),this.device.gl.clear(this.device.gl.COLOR_BUFFER_BIT),this.device.gl.bindFramebuffer(this.device.gl.FRAMEBUFFER,this.FrameBuffer_meshAlpha),this.device.gl.clear(this.device.gl.COLOR_BUFFER_BIT)):(this.device.gl.bindFramebuffer(this.device.gl.FRAMEBUFFER,this.FrameBuffer_mesh),this.device.gl.clear(this.device.gl.COLOR_BUFFER_BIT))),this.device.gl.bindFramebuffer(this.device.gl.FRAMEBUFFER,null),this.device.gl.clear(this.device.gl.COLOR_BUFFER_BIT|this.device.gl.DEPTH_BUFFER_BIT)}renderBackground(t){this.device.gl.disable(this.device.gl.DEPTH_TEST),this.device.gl.disable(this.device.gl.CULL_FACE),this.device.gl.disable(this.device.gl.BLEND);let e=0;t.backgroundTexture&&(e+=1),this.charData.multisample&&(e+=2),this.device.gl.useProgram(this.backgroundPipelineInfo.program);let n=this.charData?this.charData.transform:null;if(t.fx&&(t.fx.transform&&(n=t.fx.transform),t.fx.shadow)){const n=t.fx.shadow,r=this.getBillboardShadowGeometryInfo(n.refPos,n.light,"point"===n.lightType);e+=4;for(let t=0;t<3;t++)for(let e=0;e<3;e++)this._ub_shadow_fx_data[4*t+e]=r.Mat_World2ObjImage[e][t];for(let t=0;t<3;t++)for(let e=0;e<3;e++)this._ub_shadow_fx_data[4*t+e+12]=r.Mat_ShadowImage2World[e][t];for(let t=0;t<3;t++)this._ub_shadow_fx_data[24+t]=n.tint[t];this._ub_shadow_fx_data[27]=n.intensity,this._ub_shadow_fx_data[28]=n.blurRadius,this.device.gl.bindBuffer(this.device.gl.UNIFORM_BUFFER,this.backgroundBuffers.ub_shadow_fx_info),this.device.gl.bufferData(this.device.gl.UNIFORM_BUFFER,this._ub_shadow_fx_data,this.device.gl.DYNAMIC_DRAW)}this.device.gl.bindBufferBase(this.device.gl.UNIFORM_BUFFER,0,this.backgroundBuffers.ub_shadow_fx_info),this.device.gl.uniformMatrix2fv(this.backgroundPipelineInfo.progUniforms.u_transform_2d,!1,n?new Float32Array([1/n.scaleX,1/n.scaleY,-n.offsetX/n.scaleX,-n.offsetY/n.scaleY]):new Float32Array([1,1,0,0])),this.device.gl.uniform1ui(this.backgroundPipelineInfo.progUniforms.flags,e),this.device.gl.bindVertexArray(this.backgroundVAO),this.device.gl.uniform1i(this.backgroundPipelineInfo.progUniforms.u_image_bg,0),null!==t.backgroundTexture&&(this.device.gl.activeTexture(this.device.gl.TEXTURE0+0),this.device.gl.bindTexture(this.device.gl.TEXTURE_2D,this.backgroundTextures.u_image_bg),this.backgroundTextureSrc!==t.backgroundTexture&&(this.device.gl.texImage2D(this.device.gl.TEXTURE_2D,0,this.device.gl.RGB,this.device.gl.RGB,this.device.gl.UNSIGNED_BYTE,t.backgroundTexture),this.backgroundTextureSrc=t.backgroundTexture)),this.device.gl.uniform1i(this.backgroundPipelineInfo.progUniforms.u_image_char_body,1),this.device.gl.activeTexture(this.device.gl.TEXTURE0+1),this.device.gl.bindTexture(this.device.gl.TEXTURE_2D,this.backgroundTextures.u_image_char_body),this.device.gl.texImage2D(this.device.gl.TEXTURE_2D,0,this.device.gl.RGB,this.device.gl.RGB,this.device.gl.UNSIGNED_BYTE,t.charBodyTexture),this.charData&&(this.device.gl.uniform1i(this.backgroundPipelineInfo.progUniforms.u_image_mesh_color,2),this.device.gl.activeTexture(this.device.gl.TEXTURE0+2),this.device.gl.bindTexture(this.device.gl.TEXTURE_2D,this.FrameTexture_meshColor),this.device.gl.uniform1i(this.backgroundPipelineInfo.progUniforms.u_image_mesh_alpha,3),this.charData.multisample&&(this.device.gl.activeTexture(this.device.gl.TEXTURE0+3),this.device.gl.bindTexture(this.device.gl.TEXTURE_2D,this.FrameTexture_meshAlpha))),this.device.gl.drawArrays(this.device.gl.TRIANGLES,0,6)}renderMesh(t,e){this.device.gl.enable(this.device.gl.DEPTH_TEST),this.device.gl.disable(this.device.gl.CULL_FACE),this.device.gl.disable(this.device.gl.BLEND);const n=t.char;let r,i=new Float32Array(flatten(this.getProjMat(n.cameraConfig))),s=this.charData?this.charData.transform:null;e.fx&&e.fx.transform&&(s=e.fx.transform),r=s?new Float32Array([s.scaleX,s.scaleY,s.scaleX-1+2*s.offsetX,1-s.scaleY-2*s.offsetY]):new Float32Array([1,1,0,0]);let a=n.evalSkeletonFromMovable(e.data.movableJointTransforms),o=Array(n.skeleton.length);for(let t=0;t<n.skeleton.length;t++){const e=a[t].apply(this.initSkeletonStatus[t].inv());o[t]=e.homogeneous_matrix()}let l=0;for(let t=0;t<Math.min(this.meshStatistics.max_bones,n.skeleton.length);t++){for(let e=0;e<4;e++)for(let n=0;n<4;n++)this._ub_rig_info_data[l+4*e+n]=o[t][n][e];l+=16}if(this.device.gl.clearColor(0,0,0,0),this.device.gl.clearDepth(1),this.charData.multisample){this.device.gl.bindFramebuffer(this.device.gl.FRAMEBUFFER,this.FrameBuffer_mesh),this.device.gl.clear(this.device.gl.COLOR_BUFFER_BIT|this.device.gl.DEPTH_BUFFER_BIT),this.device.gl.useProgram(this.maskPipelineInfo.program),this.device.gl.uniformMatrix4fv(this.maskPipelineInfo.progUniforms.u_proj_mat,!0,i),this.device.gl.uniformMatrix2fv(this.maskPipelineInfo.progUniforms.u_transform_2d,!1,r);for(let t=0;t<n.mesh.length;t++)if(n.mesh[t].genMask){const r=this.meshInfos[t];if(n.mesh[t].blendshapes.size[2]>0){l=16*this.meshStatistics.max_bones;let r=Math.min(n.mesh[t].blendshapeIndices.length,this.meshStatistics.max_bs_count);for(let i=0;i<r;i++)this._ub_rig_info_data[l+i]=e.data.blendshapeWeights[n.mesh[t].blendshapeIndices[i]];for(let t=r;t<this.meshStatistics.max_bs_count;t++)this._ub_rig_info_data[l+t]=0}let i=0;n.mesh[t].opacity&&(i+=1);for(const t in r.uniformUInts)this.device.gl.uniform1ui(this.maskPipelineInfo.progUniforms[t],r.uniformUInts[t]);this.device.gl.uniform1ui(this.maskPipelineInfo.progUniforms.flags,i),this.device.gl.bindBuffer(this.device.gl.UNIFORM_BUFFER,r.buffers.ub_rig_info),this.device.gl.bufferData(this.device.gl.UNIFORM_BUFFER,this._ub_rig_info_data,this.device.gl.DYNAMIC_DRAW),this.device.gl.bindBufferBase(this.device.gl.UNIFORM_BUFFER,0,r.buffers.ub_rig_info),this.device.gl.bindVertexArray(r.VAO),this.device.gl.bindBuffer(this.device.gl.ELEMENT_ARRAY_BUFFER,r.buffers.indices),this.device.gl.uniform1i(this.maskPipelineInfo.progUniforms.u_image_bs,0),this.device.gl.activeTexture(this.device.gl.TEXTURE0+0),this.device.gl.bindTexture(this.device.gl.TEXTURE_2D,r.textures.u_image_bs),this.device.gl.drawElements(this.device.gl.TRIANGLES,n.mesh[t].triangles.itemSize(),this.device.getGLArrayElementType(n.mesh[t].triangles.data),0)}this.device.gl.bindFramebuffer(this.device.gl.DRAW_FRAMEBUFFER,this.FrameBuffer_meshAlpha),this.device.gl.blitFramebuffer(0,0,this.device.canvas.width,this.device.canvas.height,0,0,this.device.canvas.width,this.device.canvas.height,this.device.gl.COLOR_BUFFER_BIT,this.device.gl.NEAREST)}this.device.gl.bindFramebuffer(this.device.gl.FRAMEBUFFER,this.FrameBuffer_mesh),this.device.gl.clear(this.device.gl.COLOR_BUFFER_BIT|this.device.gl.DEPTH_BUFFER_BIT),this.device.gl.useProgram(this.meshPipelineInfo.program),this.device.gl.uniformMatrix4fv(this.meshPipelineInfo.progUniforms.u_proj_mat,!0,i),this.device.gl.uniformMatrix2fv(this.meshPipelineInfo.progUniforms.u_transform_2d,!1,r);let c=!0;for(let t=0;t<n.mesh.length;t++){const r=this.meshInfos[t];let i=r.texturePCAModels[e.data.mesh[t].textureModelIndex];if(n.mesh[t].blendshapes.size[0]>0){l=16*this.meshStatistics.max_bones;let r=Math.min(n.mesh[t].blendshapeIndices.length,this.meshStatistics.max_bs_count);for(let i=0;i<r;i++)this._ub_rig_info_data[l+i]=e.data.blendshapeWeights[n.mesh[t].blendshapeIndices[i]];for(let t=r;t<this.meshStatistics.max_bs_count;t++)this._ub_rig_info_data[l+t]=0}let s=0;n.mesh[t].opacity&&(s+=1),null!==this.LUTTexture&&(s+=2),i.unsigned&&(s+=4),c!=n.mesh[t].genMask&&(this.device.gl.colorMask(!0,!0,!0,!!n.mesh[t].genMask),c=n.mesh[t].genMask);for(const t in r.uniformUInts)this.device.gl.uniform1ui(this.meshPipelineInfo.progUniforms[t],r.uniformUInts[t]);this.device.gl.uniform1ui(this.meshPipelineInfo.progUniforms.flags,s),this.device.gl.uniform3f(this.meshPipelineInfo.progUniforms.u_gamma,this.currentGamma.r,this.currentGamma.g,this.currentGamma.b),this.device.gl.uniform3f(this.meshPipelineInfo.progUniforms.u_color_balance,this.currentColorBalance.rc,this.currentColorBalance.gm,this.currentColorBalance.by),this.device.gl.bindBuffer(this.device.gl.UNIFORM_BUFFER,r.buffers.ub_rig_info),this.device.gl.bufferData(this.device.gl.UNIFORM_BUFFER,this._ub_rig_info_data,this.device.gl.DYNAMIC_DRAW),this.device.gl.bindBufferBase(this.device.gl.UNIFORM_BUFFER,0,r.buffers.ub_rig_info);let a=Math.min(e.data.mesh[t].texturePCAWeights.length+1,this._ub_pca_info_data.length);this._ub_pca_info_data[0]=1;for(let n=1;n<a;n++)this._ub_pca_info_data[n]=e.data.mesh[t].texturePCAWeights[n-1];if(i.scalingFactor)for(let t=0;t<a;t++)this._ub_pca_info_data[t]*=i.scalingFactor[t];for(let t=a;t<this.meshStatistics.max_pca_component_count;t++)this._ub_pca_info_data[t]=0;this.device.gl.bindBuffer(this.device.gl.UNIFORM_BUFFER,r.buffers.ub_pca_info),this.device.gl.bufferData(this.device.gl.UNIFORM_BUFFER,this._ub_pca_info_data,this.device.gl.DYNAMIC_DRAW),this.device.gl.bindBufferBase(this.device.gl.UNIFORM_BUFFER,1,r.buffers.ub_pca_info),this.device.gl.bindVertexArray(r.VAO),this.device.gl.bindBuffer(this.device.gl.ELEMENT_ARRAY_BUFFER,r.buffers.indices),this.device.gl.uniform1i(this.meshPipelineInfo.progUniforms.u_image_bs,0),this.device.gl.activeTexture(this.device.gl.TEXTURE0+0),this.device.gl.bindTexture(this.device.gl.TEXTURE_2D,r.textures.u_image_bs),this.device.gl.uniform1i(this.meshPipelineInfo.progUniforms.u_image_pca,1),this.device.gl.activeTexture(this.device.gl.TEXTURE0+1),i.texture&&this.device.gl.bindTexture(this.device.gl.TEXTURE_2D_ARRAY,i.texture),this.device.gl.uniform1i(this.meshPipelineInfo.progUniforms.u_image_lut,2),this.LUTTexture&&(this.device.gl.activeTexture(this.device.gl.TEXTURE0+2),this.device.gl.bindTexture(this.device.gl.TEXTURE_3D,this.LUTTexture)),this.device.gl.drawElements(this.device.gl.TRIANGLES,n.mesh[t].triangles.itemSize(),this.device.getGLArrayElementType(n.mesh[t].triangles.data),0)}c||this.device.gl.colorMask(!0,!0,!0,!0),this.charData.multisample&&(this.device.gl.bindFramebuffer(this.device.gl.DRAW_FRAMEBUFFER,this.FrameBuffer_meshColor),this.device.gl.blitFramebuffer(0,0,this.device.canvas.width,this.device.canvas.height,0,0,this.device.canvas.width,this.device.canvas.height,this.device.gl.COLOR_BUFFER_BIT,this.device.gl.NEAREST)),this.device.gl.bindFramebuffer(this.device.gl.FRAMEBUFFER,null)}constructor(t,e){this.compat_features={},this.charData=null,this.backgroundBuffers={},this.backgroundTextures={},this.backgroundTextureSrc=null,this.meshPipelineInfo=null,this.maskPipelineInfo=null,this.meshInfos=[],this.meshStatistics={max_pca_component_count:4,max_bs_count:4,max_bones:1},this.FrameTexture_meshColor=null,this.FrameTexture_meshAlpha=null,this.LUTTexture=null,this.FrameBuffer_mesh=null,this.FrameBuffer_meshColor=null,this.FrameBuffer_meshAlpha=null,this.initSkeletonStatus=[],this.frameDataCallback=()=>null,this.currentGamma={r:1,g:1,b:1},this.currentColorBalance={rc:0,gm:0,by:0},this._ub_shadow_fx_data=null,this._ub_rig_info_data=null,this._ub_pca_info_data=null,this.first_webgl_render=!0,this.sendSdkPoint=()=>{},this.device=t,this.sendSdkPoint=e,this.reinitialize()}reinitialize(){this.compat_features={},this.compat_features.OES_texture_float_linear=this.device.gl.getExtension("OES_texture_float_linear"),this.compat_features.OES_texture_half_float_linear=this.device.gl.getExtension("OES_texture_half_float_linear"),this.assembleBackgroundPipeline(),this.charData&&this.assembleMeshPipelines(this.charData)}setSyncMedia(t){this.device.run(t=>this.render(),t)}setCharData(t){t?(this.charData=_extends({},t),this.charData.multisample=null,this.assembleMeshPipelines(this.charData)):this.charData=null}setFrameDataCallback(t){this.frameDataCallback=t}setGamma(t,e,n){this.currentGamma={r:t,g:e,b:n}}setColorBalance(t,e,n){this.currentColorBalance={rc:t,gm:e,by:n}}getBillboardTransform2D(t,e){if(null==this.charData||null==this.charData.char)return{offsetX:0,offsetY:0,scaleX:1,scaleY:1};{const n=this.getProjMat(this.charData.char.cameraConfig),r=inv4(n),i=mmul(n,[[t[0],e[0]],[t[1],e[1]],[t[2],e[2]],[1,1]]),s=i[3][0]/i[3][1],a=[r[0][0]-e[0]*r[3][0],r[1][0]-e[1]*r[3][0],r[2][0]-e[2]*r[3][0]],o=[r[0][1]-t[0]*r[3][1],r[1][1]-t[1]*r[3][1],r[2][1]-t[2]*r[3][1]],l=[r[0][1]-e[0]*r[3][1],r[1][1]-e[1]*r[3][1],r[2][1]-e[2]*r[3][1]],c=s*Math.sqrt([r[0][0]-t[0]*r[3][0],r[1][0]-t[1]*r[3][0],r[2][0]-t[2]*r[3][0]].reduce((t,e)=>t+e*e,0)/a.reduce((t,e)=>t+e*e,0)),d=s*Math.sqrt(o.reduce((t,e)=>t+e*e,0)/l.reduce((t,e)=>t+e*e,0));return{offsetX:.5*(i[0][1]/i[3][1]-i[0][0]/i[3][0]-(c-1)),offsetY:.5*(1-d-(i[1][1]/i[3][1]-i[1][0]/i[3][0])),scaleX:c,scaleY:d}}}getBillboardShadowGeometryInfo(t,e,n){if(null==this.charData||null==this.charData.char)return{Mat_ShadowImage2World:identity(3),Mat_World2ObjImage:identity(3)};{const r=this.getProjMat(this.charData.char.cameraConfig),i=inv4(r),s=[[1,0,0],[0,t[1],1],[0,0,0]],a=[[1,0,0],[0,t[2],1],[0,0,0]];n?(s[2]=[e[0],e[1],1],a[2]=[t[0],-e[2],0]):(s[2]=[e[0],e[1],0],a[2]=[0,-e[2],0]);const o=transpose(mmul(inv3(a),s)),l=mvmul(r,[t[0],t[1],t[2],1]),c=l[2]/l[3];return{Mat_ShadowImage2World:mmul(o,inv3([[r[0][0],r[0][2],r[0][1]*t[1]+r[0][3]],[r[1][0],r[1][2],r[1][1]*t[1]+r[1][3]],[r[3][0],r[3][2],r[3][1]*t[1]+r[3][3]]])),Mat_World2ObjImage:inv3([[i[0][0],i[0][1],i[0][2]*c+i[0][3]],[i[1][0],i[1][1],i[1][2]*c+i[1][3]],[i[3][0],i[3][1],i[3][2]*c+i[3][3]]])}}}render(){var t;const e=this.frameDataCallback();null!==e&&(this.initFrame(),null!==this.charData&&null!==this.charData.char&&null!==e.data?this.renderMesh(this.charData,e):(this.device.gl.bindFramebuffer(this.device.gl.FRAMEBUFFER,this.FrameBuffer_mesh),this.device.gl.clear(this.device.gl.COLOR_BUFFER_BIT|this.device.gl.DEPTH_BUFFER_BIT),this.device.gl.bindFramebuffer(this.device.gl.FRAMEBUFFER,null)),this.renderBackground(e),null!==e.onPostRender&&e.onPostRender(this)),null==(t=this.device.gl)||t.flush()}renderFrame(t){this.initFrame(),null!==this.charData&&null!==this.charData.char&&null!==t.data&&this.renderMesh(this.charData,t),this.renderBackground(t),this.first_webgl_render&&(window.performanceTracker.markEnd(performanceConstant.first_render),window.performanceTracker.markEnd(performanceConstant.first_webgl_render),this.first_webgl_render=!1,this.sendSdkPoint("render_success_time",{timestamp:Date.now()})),this.device.gl.flush()}destroy(){var t,e,n,r;this.device.gl&&(this.meshInfos&&(this.meshInfos.forEach(t=>{t.VAO&&this.device.gl.deleteVertexArray(t.VAO),Object.values(t.buffers).forEach(t=>{t&&this.device.gl.deleteBuffer(t)}),Object.values(t.textures).forEach(t=>{t&&this.device.gl.deleteTexture(t)}),t.texturePCAModels.forEach(t=>{t.texture&&this.device.gl.deleteTexture(t.texture)})}),this.meshInfos=[]),this.FrameBuffer_MSAA&&(this.device.gl.deleteFramebuffer(this.FrameBuffer_MSAA),this.FrameBuffer_MSAA=null),this.FrameBuffer_meshColor&&(this.device.gl.deleteFramebuffer(this.FrameBuffer_meshColor),this.FrameBuffer_meshColor=null),this.FrameBuffer_meshAlpha&&(this.device.gl.deleteFramebuffer(this.FrameBuffer_meshAlpha),this.FrameBuffer_meshAlpha=null),this.FrameTexture_meshColor&&(this.device.gl.deleteTexture(this.FrameTexture_meshColor),this.FrameTexture_meshColor=null),this.FrameTexture_meshAlpha&&(this.device.gl.deleteTexture(this.FrameTexture_meshAlpha),this.FrameTexture_meshAlpha=null),this.LUTTexture&&(this.device.gl.deleteTexture(this.LUTTexture),this.LUTTexture=null),null!=(n=this.meshPipelineInfo)&&n.program&&(this.device.gl.deleteProgram(this.meshPipelineInfo.program),this.meshPipelineInfo.program=null),null!=(r=this.maskPipelineInfo)&&r.program&&(this.device.gl.deleteProgram(this.maskPipelineInfo.program),this.maskPipelineInfo.program=null)),this._ub_rig_info_data=null,this._ub_pca_info_data=null,this.first_webgl_render=!0,null==(t=(e=this.device).destroy)||t.call(e)}}const containerWidgetMaps=new Map;let containerIdCounter=0;function getContainerElement(t){return t&&t.el&&t.el instanceof HTMLElement?t.el:null}function getContainerId(t){if(t.id)return t.id;const e=t.getAttribute("data-widget-container-id");if(e)return e;const n="widget-container-"+ ++containerIdCounter;return t.setAttribute("data-widget-container-id",n),n}function getContainerWidgetMap(t){const e=getContainerId(t);return containerWidgetMaps.has(e)||containerWidgetMaps.set(e,new Map),containerWidgetMaps.get(e)}const subtitleStyle="bottom: 50px;\nleft: 50%;\ntransform: translateX(-50%);\nbackground: rgba(0, 0, 0, 0.8);\ncolor: white;\npadding: 12px 20px;\nborder-radius: 8px;\nfont-size: 16px;\nfont-weight: 500;\nz-index: 1000;\nmax-width: 80%;\nmin-width: 200px;\nword-break: break-word;\nbox-shadow: 0 4px 12px rgba(0, 0, 0, 0.3);\ntext-align: center;",WidgetDefaultRenderer={_el(t){const{axis_id:e,x_location:n,y_location:r,width:i,height:s}=t,a=document.createElement("div");a.setAttribute("class","avatar-sdk-widget-container");let o="position:absolute;";return o+=void 0!==e?`z-index:${e};`:"z-index:1;",void 0!==n&&void 0!==r&&(o+=`top:${100*r}%;left:${100*n}%;`),void 0!==i&&void 0!==s&&(o+=`width:${100*i}%;height:${100*s}%;`),a.setAttribute("style",o),a},_getWidgetKey:(t,e)=>`${t}-${null!=e?e:"default"}`,_replaceWidget(t,e,n,r){const i=this._getWidgetKey(t,e),s=getContainerElement(r||this._currentInstance);if(!s)return;const a=getContainerWidgetMap(s);if(a.has(i)){const t=a.get(i);t&&t.parentNode&&t.remove()}a.set(i,n)},WIDGET_PIC(t,e){const n=this._el(t),r=document.createElement("img");return r.crossOrigin="anonymous",r.setAttribute("style","width:100%;height:100%;"),r.src=t.image,n.appendChild(r),this._replaceWidget("WIDGET_PIC",t.axis_id,n,e),n},WIDGET_SUBTITLE(t,e){const{type:n,text:r,axis_id:i}=t,s=getContainerElement(e||this._currentInstance);if("subtitle_off"===n){if(s){const t=getContainerWidgetMap(s),e=this._getWidgetKey("WIDGET_SUBTITLE",i);if(t.has(e)){const n=t.get(e);n&&n.parentNode&&n.remove(),t.delete(e)}}return null}const a=this._el(t);return a.innerHTML=r,a.setAttribute("style",a.style.cssText+subtitleStyle),this._replaceWidget("WIDGET_SUBTITLE",i,a,e),a},destroy(t){const e=getContainerElement(t||this._currentInstance);if(e){const t=getContainerId(e);if(containerWidgetMaps.has(t)){const e=containerWidgetMaps.get(t);e.forEach((t,e)=>{(e.startsWith("WIDGET_SUBTITLE")||e.startsWith("WIDGET_PIC"))&&t&&t.parentNode&&t.remove()}),e.clear(),containerWidgetMaps.delete(t)}else e.querySelectorAll(".avatar-sdk-widget-container").forEach(t=>{t.remove()})}}},__version__="3.0.0";function checkVersion(t,e){t instanceof ArrayBuffer&&(t={offset:0,dataview:new DataView(t)});const n=[0,0,0];for(let e=0;e<3;e++)n[e]=t.dataview.getUint8(t.offset),t.offset+=1;const r=e.split(".").map(t=>parseInt(t));if(r[0]<n[0])throw new Error(`Data version (${n[0]}.${n[1]}.${n[2]}) is incompatible with the version of current data interface (${r[0]}.${r[1]}.${r[2]}).`);return n}function decodeStr(t){t instanceof ArrayBuffer&&(t={offset:0,dataview:new DataView(t)});const e=new Uint8Array(t.dataview.buffer,t.offset,t.dataview.byteLength-t.offset);let n=0;for(;n<e.byteLength&&e[n]>0;)n++;t.offset+=n+1;const r=e.slice(0,n);return new TextDecoder("utf-8").decode(r)}function decodeLongInt(t){t instanceof ArrayBuffer&&(t={offset:0,dataview:new DataView(t)});let e=0,n=0;for(;;){let r=t.dataview.getUint8(t.offset);t.offset++;let i=e|(127&r)<<n;if(i<e)throw new Error("Integer too large to decode.");if(e=i,!(128&r))break;n+=7}return e}const TensorDataTypeMap={B:Uint8Array,b:Int8Array,H:Uint16Array,h:Int16Array,I:Uint32Array,i:Int32Array,L:BigUint64Array,l:BigInt64Array,f:Float32Array,d:Float64Array};"undefined"!=typeof Float16Array&&(TensorDataTypeMap.e=Float16Array);class Tensor{constructor(t,e){this.size=t,this.data=e}itemSize(){let t=1;for(let e of this.size)t*=e;return t}byteSize(){return this.itemSize()*this.data.BYTES_PER_ELEMENT}static zeros(t,e=Float32Array){let n=1;for(let e=0;e<t.length;e++)n*=t[e];const r=new e(n);for(let t=0;t<n;t++)r[t]=0;return new Tensor(t,r)}part(...t){if(t.length>this.size.length)throw new Error("Subtensor index length larger than tensor dimension.");let e=[],n=1;for(let r=t.length;r<this.size.length;r++)e.push(this.size[r]),n*=this.size[r];let r=0;t.length>0&&(r+=t[0]);for(let e=1;e<t.length;e++)r*=this.size[e],r+=t[e];return r*=n,new Tensor(e,this.data.slice(r,r+n))}static deserialize(t){t instanceof ArrayBuffer&&(t={offset:0,dataview:new DataView(t)});const e=t.dataview.getUint8(t.offset);t.offset++;const n=new Array(e);let r=1;for(let i=0;i<e;i++)n[i]=decodeLongInt(t),r*=n[i];const i=String.fromCodePoint(t.dataview.getUint8(t.offset));t.offset++;const s=TensorDataTypeMap[i];if(void 0===s)throw new Error(`Unsupported tensor element type "${i}".`);const a=r*s.BYTES_PER_ELEMENT,o=new s(t.dataview.buffer.slice(t.offset,t.offset+a));return t.offset+=a,new Tensor(n,o)}}function loadArchives(t){t instanceof ArrayBuffer&&(t={offset:0,dataview:new DataView(t)});let e=[null];for(;;){const n=decodeStr(t);if(""==n)break;{let r=null;if("text/plain;charset=UTF-8"===n){const e=decodeLongInt(t),n=new Uint8Array(t.dataview.buffer,t.offset,e);t.offset+=e,r=new TextDecoder("utf-8").decode(n)}else if("application/json;charset=UTF-8"==n){const e=decodeLongInt(t),n=new Uint8Array(t.dataview.buffer,t.offset,e);t.offset+=e;const i=new TextDecoder("utf-8");r=JSON.parse(i.decode(n))}else if("application/octet-stream"===n)r=Tensor.deserialize(t);else{const e=decodeLongInt(t),i=t.dataview.buffer.slice(t.offset,t.offset+e);t.offset+=e,r=new Blob([i],{type:n})}e.push(r)}}return e}class CameraConfig{constructor(){this.focalLength=75,this.filmAperture=[1,1],this.translation=[0,0,0],this.rotation=[0,0,0]}getIntrinsicMatrix(t){const[e,n]=t;let r=25.4*this.filmAperture[0];return[[this.focalLength/(r/e),0,t[0]/2],[0,this.focalLength/(r*t[1]/t[0]/n),t[1]/2],[0,0,1]]}getProjMatrix(t,e=.01,n=Infinity){const[r,i]=t,s=this.getIntrinsicMatrix(t);let a,o;return Infinity===n?(a=-1,o=-2*e):(a=-(n+e)/(n-e),o=-2*n*e/(n-e)),[[2*s[0][0]/r,0,(r-2*s[0][2])/r,0],[0,2*s[1][1]/i,(i-2*s[1][2])/i,0],[0,0,a,o],[0,0,-1,0]]}getExtrinsicMatrix(){const t=Math.PI/180,e=inv3(Euler_to_mat(this.rotation.map(e=>e*t),"xyz"));return make_homogeneous(e,mvmul(e,this.translation.map(t=>-t)))}static deserialize(t){t instanceof ArrayBuffer&&(t={offset:0,dataview:new DataView(t)});let e=new CameraConfig;e.focalLength=t.dataview.getFloat32(t.offset,!0);for(let n=0;n<2;n++)e.filmAperture[n]=t.dataview.getFloat32(t.offset+4*(n+1),!0);for(let n=0;n<3;n++)e.translation[n]=t.dataview.getFloat32(t.offset+4*(n+3),!0);for(let n=0;n<3;n++)e.rotation[n]=t.dataview.getFloat32(t.offset+4*(n+6),!0);return t.offset+=36,e}}class RigidTransform{constructor(t=[0,0,0],e=[1,0,0,0]){this.translation=t,this.rotQuaternion=e}apply(t){if(t instanceof RigidTransform){let e=quaternion_mul(this.rotQuaternion,t.rotQuaternion);e=normalize$1(e);let n=mvmul(quaternion_to_mat(this.rotQuaternion),t.translation);for(let t=0;t<3;t++)n[t]+=this.translation[t];return new RigidTransform(n,e)}{let e=mvmul(this.matrix(),t);for(let t=0;t<3;t++)e[t]+=this.translation[t];return e}}inv(){let t=quaternion_conj(this.rotQuaternion),e=mvmul(quaternion_to_mat(t),this.translation.map(t=>-t));return new RigidTransform(e,t)}matrix(){return quaternion_to_mat(this.rotQuaternion)}homogeneous_matrix(){return make_homogeneous(this.matrix(),this.translation)}static deserialize(t){t instanceof ArrayBuffer&&(t={offset:0,dataview:new DataView(t)});let e=[0,0,0],n=[1,0,0,0];for(let n=0;n<3;n++)e[n]=t.dataview.getFloat32(t.offset+4*n,!0);let r=0;for(let e=0;e<3;e++)n[e+1]=t.dataview.getFloat32(t.offset+4*(e+3),!0),r+=n[e+1]*n[e+1];return n[0]=Math.sqrt(Math.max(1-r,0)),t.offset+=24,new RigidTransform(e,n)}}class IBRMeshInfo{constructor(t,e){if(t instanceof ArrayBuffer&&(t={offset:0,dataview:new DataView(t)}),e.version[0]>2){let n=t.dataview.getUint8(t.offset);t.offset+=1,this.genMask=(1&n)>0;let r=[],i=[],s=!0;for(;;){let e=decodeLongInt(t);if(0===e){if(!s)break}else r.push(e-1);s=!1;let n=[],a=!0,o=0;for(;;){let e=decodeLongInt(t);if(a)for(let t=0;t<e;t++)n.push(o+t);if(a=!a,o+=e,0===e&&o>0)break}i.push(n)}let a=i[0].length;this.blendshapeIndices=r;let o=e.archivedItems[decodeLongInt(t)],l=Tensor.zeros([a,o.size[1]],o.data.constructor),c=Tensor.zeros([a,o.size[1],this.blendshapeIndices.length],o.data.constructor),d=0;const h=i[0];for(let t of h){for(let e=0;e<o.size[1];e++)l.data[t*o.size[1]+e]=o.data[d*o.size[1]+e];d++}const u=this.blendshapeIndices.length;for(let t=1;t<i.length;t++){const e=i[t];for(let n of e){for(let e=0;e<o.size[1];e++)c.data[(n*o.size[1]+e)*u+t-1]=o.data[d*o.size[1]+e];d++}}this.vertices=l,this.blendshapes=c,this.triangles=e.archivedItems[decodeLongInt(t)],this.opacity=e.archivedItems[decodeLongInt(t)],this.UVCoord=e.archivedItems[decodeLongInt(t)],this.jointIndex=new Uint8Array(a*e.maxJointsPerVertex),this.jointWeight=new Float32Array(a*e.maxJointsPerVertex);for(let n=0;n<a;n++){for(let r=0;r<e.maxJointsPerVertex;r++)this.jointIndex[n*e.maxJointsPerVertex+r]=t.dataview.getUint8(t.offset),t.offset+=1;for(let r=0;r<e.maxJointsPerVertex;r++)this.jointWeight[n*e.maxJointsPerVertex+r]=t.dataview.getFloat32(t.offset,!0),t.offset+=4}const p=t.dataview.getUint8(t.offset);t.offset+=1,this.textureModels=new Array(p);for(let n=0;n<p;n++)this.textureModels[n]={data:e.archivedItems[decodeLongInt(t)],scalingFactor:e.archivedItems[decodeLongInt(t)]}}else{this.genMask=!0;let n=t.dataview.getUint16(t.offset,!0);t.offset+=2;const r=new Float32Array(n);for(let e=0;e<n;e++)r[e]=t.dataview.getFloat32(t.offset,!0),t.offset+=4;this.opacity=new Tensor([n],r);let i=t.dataview.getUint16(t.offset,!0);t.offset+=2;const s=new Uint16Array(3*i);for(let e=0;e<i;e++)for(let n=0;n<3;n++)s[3*e+n]=t.dataview.getUint16(t.offset,!0),t.offset+=2;this.triangles=new Tensor([i,3],s);const a=new Float32Array(2*n);for(let e=0;e<n;e++)for(let n=0;n<2;n++)a[2*e+n]=t.dataview.getFloat32(t.offset,!0),t.offset+=4;this.UVCoord=new Tensor([n,2],a);const o=t.dataview.getUint16(t.offset,!0);t.offset+=2;const l=new Float32Array(3*n);for(let e=0;e<3*n;e++)l[e]=t.dataview.getFloat32(t.offset,!0),t.offset+=4;const c=new Float32Array((o-1)*n*3);for(let e=0;e<o-1;e++)for(let r=0;r<3*n;r++)c[r*(o-1)+e]=t.dataview.getFloat32(t.offset,!0),t.offset+=4;this.vertices=new Tensor([n,3],l),this.blendshapes=new Tensor([n,3,o-1],c),this.blendshapeIndices=[];for(let t of e.blendshapeIndices)this.blendshapeIndices.push(t);this.jointIndex=new Uint8Array(n*e.maxJointsPerVertex),this.jointWeight=new Float32Array(n*e.maxJointsPerVertex);for(let r=0;r<n;r++){for(let n=0;n<e.maxJointsPerVertex;n++)this.jointIndex[r*e.maxJointsPerVertex+n]=t.dataview.getUint8(t.offset),t.offset+=1;for(let n=0;n<e.maxJointsPerVertex;n++)this.jointWeight[r*e.maxJointsPerVertex+n]=t.dataview.getFloat32(t.offset,!0),t.offset+=4}const d=t.dataview.getUint8(t.offset);t.offset+=1,this.textureModels=new Array(d);for(let e=0;e<d;e++){const n=[0,0,0,3];for(let e=0;e<3;e++)n[e]=t.dataview.getUint16(t.offset,!0),t.offset+=2;const r=new Float32Array(n[0]*n[1]*n[2]*3);for(let e=0;e<r.length;e++)r[e]=t.dataview.getFloat32(t.offset,!0),t.offset+=4;this.textureModels[e]={data:new Tensor(n,r)}}}}}class IBRMeshFrameInfo{constructor(t,e){this.textureModelIndex=t,this.texturePCAWeights=e}static deserialize(t,e){t instanceof ArrayBuffer&&(t={offset:0,dataview:new DataView(t)});let n=t.dataview.getUint8(t.offset);t.offset+=1;let r=new Float32Array(e.textureModels[n].data.size[0]-1);for(let e=0;e<r.length;e++)r[e]=t.dataview.getFloat32(t.offset,!0),t.offset+=4;return new IBRMeshFrameInfo(n,r)}}class IBRAnimationGeneratorCharInfo_NN{constructor(t,e={}){t instanceof ArrayBuffer&&(t={offset:0,dataview:new DataView(t)});const n=checkVersion(t,__version__);let r=[];if(n[0]>2&&(r=loadArchives(t)),this.cameraConfig=CameraConfig.deserialize(t),n[0]>2)this.blendshapeCount=decodeLongInt(t);else{if(!e.blendshapeMap)throw new Error("A blendshape map is required to load the character information of v2.0 format.");let t=new Set;for(const n of e.blendshapeMap)for(const e of n)t.add(e);this.blendshapeCount=t.size}let i=t.dataview.getUint8(t.offset);t.offset+=1,this.maxJointsPerVertex=t.dataview.getUint8(t.offset),t.offset+=1;let s=t.dataview.getUint8(t.offset);t.offset+=1;let a=new Array(s);for(let e=0;e<s;e++)a[e]=t.dataview.getUint8(t.offset),t.offset+=1;this.movableJoints=a,this.skeleton=new Array(i);for(let e=0;e<i;e++){let n=t.dataview.getUint8(t.offset);n>=this.skeleton.length&&(n=null),t.offset+=1;let r=RigidTransform.deserialize(t);this.skeleton[e]={parent:n,local_transform:r}}this.jointEvalOrder=new Array(i);for(let e=0;e<i;e++)this.jointEvalOrder[e]=t.dataview.getUint8(t.offset),t.offset+=1;let o={version:n,maxJointsPerVertex:this.maxJointsPerVertex};n[0]>2&&(o.archivedItems=r);let l=t.dataview.getUint8(t.offset);t.offset+=1,this.mesh=new Array(l);for(let r=0;r<l;r++)n[0]<=2&&(o.blendshapeIndices=e.blendshapeMap[r]),this.mesh[r]=new IBRMeshInfo(t,o)}evalSkeleton(){let t=Array(this.skeleton.length);for(let e of this.jointEvalOrder)t[e]=null==this.skeleton[e].parent?this.skeleton[e].local_transform:t[this.skeleton[e].parent].apply(this.skeleton[e].local_transform);return t}evalSkeletonFromMovable(t){let e=Array(this.skeleton.length);for(let n=0;n<t.length;n++)e[this.movableJoints[n]]=t[n];for(let t of this.jointEvalOrder)null!=this.skeleton[t].parent&&(e[t]=e[this.skeleton[t].parent].apply(this.skeleton[t].local_transform));return e}}class IBRAnimationFrameData_NN{constructor(){this.mesh=[],this.blendshapeWeights=new Float32Array,this.movableJointTransforms=[]}static deserialize(t,e,n){t instanceof ArrayBuffer&&(t={offset:0,dataview:new DataView(t)});let r=new IBRAnimationFrameData_NN;const i=e.mesh.length;if(r.mesh=new Array(i),r.blendshapeWeights=new Float32Array(e.blendshapeCount),n[0]>2){for(let n=0;n<i;n++)r.mesh[n]=IBRMeshFrameInfo.deserialize(t,e.mesh[n]);for(let e=0;e<r.blendshapeWeights.length;e++)r.blendshapeWeights[e]=t.dataview.getFloat32(t.offset,!0),t.offset+=4}else for(let n=0;n<i;n++){const i=e.mesh[n].blendshapeIndices;for(let e=0;e+1<i.length;e++)r.blendshapeWeights[i[e+1]-1]=t.dataview.getFloat32(t.offset,!0),t.offset+=4;let s=t.dataview.getUint8(t.offset);t.offset+=1;let a=new Float32Array(e.mesh[n].textureModels[s].data.size[0]-1);for(let e=0;e<a.length;e++)a[e]=t.dataview.getFloat32(t.offset,!0),t.offset+=4;r.mesh[n]=new IBRMeshFrameInfo(s,a)}r.movableJointTransforms=new Array(e.movableJoints.length);for(let n=0;n<e.movableJoints.length;n++)r.movableJointTransforms[n]=RigidTransform.deserialize(t);return r}static interp(t,e,n,r,i){let s=new IBRAnimationFrameData_NN;s.blendshapeWeights=new Float32Array(t.blendshapeWeights.length);for(let n=0;n<s.blendshapeWeights.length;n++)s.blendshapeWeights[n]=r*e.blendshapeWeights[n]+(1-r)*t.blendshapeWeights[n];s.mesh=[];for(let n=0;n<t.mesh.length;n++){let i=new IBRMeshFrameInfo(t.mesh[n].textureModelIndex,new Float32Array(t.mesh[n].texturePCAWeights.length));for(let s=0;s<t.mesh[n].texturePCAWeights.length;s++)i.texturePCAWeights[s]=r*e.mesh[n].texturePCAWeights[s]+(1-r)*t.mesh[n].texturePCAWeights[s];s.mesh.push(i)}s.movableJointTransforms=new Array(n.movableJointTransforms.length);for(let t=0;t<n.movableJointTransforms.length;t++){let e=!0;for(let[n,r]of i)if(n===t){e=!1;break}e&&(s.movableJointTransforms[t]=n.movableJointTransforms[t])}for(let[a,o]of i){let i=t.movableJointTransforms[o].inv().apply(t.movableJointTransforms[a]),l=e.movableJointTransforms[o].inv().apply(e.movableJointTransforms[a]),c=[],d=[];for(let t=0;t<3;t++)c.push(r*l.translation[t]+(1-r)*i.translation[t]);for(let t=0;t<4;t++)d.push(r*l.rotQuaternion[t]+(1-r)*i.rotQuaternion[t]);d=normalize$1(d);let h=new RigidTransform(c,d);h=n.movableJointTransforms[o].apply(h),s.movableJointTransforms[a]=h}return s}}function unpackIBRAnimation(t,e){t instanceof ArrayBuffer&&(t={offset:0,dataview:new DataView(t)});const n=checkVersion(t,__version__),r=t.dataview.getUint32(t.offset,!0);t.offset+=4;let i=Array(r);for(let s=0;s<r;s++)i[s]=IBRAnimationFrameData_NN.deserialize(t,e,n);return i}function formatMJT(t,e){return new RigidTransform(t,e)}function isSupportMES(){const t=navigator.userAgent,e=navigator.vendor,n=/Chrome/.test(t),r=/Google Inc/.test(e),i=/Edg/.test(t),s=void 0!==window.MediaSource;return n&&(r||i)&&s}function getStyleStr(t){return Object.entries(t).map(([t,e])=>{const n="number"==typeof e?e.toString():e;return`${t.replace(/[A-Z]/g,t=>`-${t.toLowerCase()}`)}:${n};`}).join("")}function updateCanvasXOffset(t,e){const n=(t.style.transform||"").replace(/translateX\((-?\d+(\.\d+)?)px\)/,"").trim()+` translateX(${e}px)`;t.style.transform=n.replace(/\s+/g," ").trim()}function generateFingerprint(){const t=`${screen.width}x${screen.height}`,e=navigator.userAgent,n=navigator.language,r=Intl.DateTimeFormat().resolvedOptions().timeZone,i=encodeURIComponent(`${t}|${e}|${n}|${r}`);return btoa(i)}function getDeviceInfo(){const t=navigator.userAgent;let e="Unknown Brand",n="Unknown Model",r="Unknown Version",i="Unknown Browser",s="Unknown Version";const a=t.match(/Windows NT (\d+\.\d+)/),o=t.match(/Android (\d+\.\d+(\.\d+)?)/),l=t.match(/OS (\d+_\d+(\._\d+)?) like Mac OS X/);a?r=`Windows NT ${a[1]}`:o?r=`Android ${o[1]}`:l?r=`iOS ${l[1].replace(/_/g,".")}`:t.includes("Macintosh")?r="Macintosh":t.includes("Linux")&&(r="Linux"),t.includes("iPhone")||t.includes("iPad")||t.includes("iPod")?(e="Apple",t.includes("iPhone")?n="iPhone":t.includes("iPad")?n="iPad":t.includes("iPod")&&(n="iPod")):t.includes("Android")?(e="Android",n="Android"):t.includes("Windows")?(e="Windows",n=t.includes("Windows Phone")?"Windows Phone":"Windows Desktop"):t.includes("Linux")&&(e="Linux",n="Linux");const c=t.match(/Chrome\/(\d+\.\d+\.\d+\.\d+)/),d=t.match(/Version\/(\d+\.\d+(\.\d+)?) Safari/),h=t.match(/Firefox\/(\d+\.\d+(\.\d+)?)\b/),u=t.match(/Edg\/(\d+\.\d+\.\d+\.\d+)/),p=t.match(/Opera\/(\d+\.\d+)/),f=t.match(/MSIE (\d+\.\d+)/);return c?(i="Chrome",s=c[1]):d?(i="Safari",s=d[1]):h?(i="Firefox",s=h[1]):u?(i="Edge",s=u[1]):p?(i="Opera",s=p[1]):f&&(i="IE",s=f[1]),{device_id:generateFingerprint(),device_brand:e,device_model:n,os_version:r,browser:i,browser_version:s,browser_ua:t}}function validateScaleWithDecimal(t,e){var n;return"number"==typeof t||"string"==typeof t&&(/^\d+(\.\d+)?vh$/.test(t)||/^\d+(\.\d+)?$/.test(t))?t:(null==(n=window.avatarSDKLogger)||n.warn(e,'scale 必须是数字、带小数的数字字符串或者"xxxvh"格式(xxx为数字/小数)'),1)}function isharmony(){const t=(navigator.userAgent||"").toLowerCase();return/openharmony|arkweb/.test(t)}class AvatarRender{constructor(t){this.TAG="[AvatarRender]",this.canvas=document.createElement("canvas"),this.currentBodyFrame=null,this.lastFaceFrame=null,this.isInit=!1,this.isFirstRender=!0,this.lastFrameState="",this.lastRenderState=RenderState.init,this.onStateChange=()=>{},this.onRenderChange=()=>{},this.sendVideoInfo=()=>{},this.lostHandler=()=>{},this.restoreHandler=()=>{},this.avatarCanvasVisible=!0,this.lastRealFaceFrameData=null,this.lastRealFaceFrame=-1,this.lastWeight=0,this.lastFrameIndex=-1,this.canvasOffsetX=-1,this.baseWalkOffset=0,this.lastBodyOffset=0,this.pendingCharData=null,this.interrupt=!1,this.walkConfig=null,this.layout=null,this.allLostFrameCount=0,this.allLostFaceFrameCount=0,this.maxLostFrameCount=300,this.forceSyncDecoder=()=>{},this.createPipelineLock=!1,this.restoreTimeout=null,this.isRecovering=!1,this.recoverStartTime=0,this.recoveryStage="light",this.recoveryMaxAttempts={light:2,medium:3,full:2},this.recoveryBaseDelays={light:300,medium:4e3,full:5e3},this.recoveryMaxDelay=3e4,this.currentStageAttempts=0,this.isUsingReducedResolution=!1,this.resolutionRestoreTimer=null,this.RESOLUTION_RESTORE_DELAY=3e4,this.scale=1,this.sendSdkPoint=()=>{},this.options=t,this.onDownloadProgress=t.onDownloadProgress,this.onStateChange=t.onStateChange,this.onRenderChange=t.onRenderChange,this.sendVideoInfo=t.sendVideoInfo,this.saveAndDownload=t.saveAndDownload,this.forceSyncDecoder=t.forceSyncDecoder,this.lostHandler=this._lostHandler.bind(this),this.restoreHandler=this._restoreHandler.bind(this),this.setCanvasVisibility(this.avatarCanvasVisible),this.sendSdkPoint=t.sendSdkPoint,this.device=null,this.pipeline=null,this.copyCanvas=document.createElement("canvas"),this.copyCtx=this.copyCanvas.getContext("2d")}resetFaceFrameState(){var t;this.lastRealFaceFrame=-1,this.lastRealFaceFrameData=null,this.lastWeight=0,null==(t=window.avatarSDKLogger)||t.log(this.TAG,"重置表情状态(从隐身模式恢复)")}createPipeline(){this.pipeline||!this.device||this.createPipelineLock||(this.createPipelineLock=!0,this.pipeline=new GLPipeline(this.device,this.sendSdkPoint),this.createPipelineLock=!1,this.pendingCharData&&(this.pipeline.setCharData(this.pendingCharData),this.pipeline.setSyncMedia()))}_lostHandler(t){if(t.preventDefault(),window.avatarSDKLogger.error("Context lost.",t),this.device)try{this.device.canvas.removeEventListener("webglcontextlost",this.lostHandler),this.device.canvas.removeEventListener("webglcontextrestored",this.restoreHandler)}catch(t){}if(this.device)try{this.device.destroy()}catch(t){}if(this.pipeline)try{this.pipeline.destroy()}catch(t){}this.device=null,this.pipeline=null,this.options.reportMessage({code:EErrorCode.WEBGL_CONTEXT_LOST,message:"Context lost.",e:{event:t,timestamp:Date.now()}}),this.isRecovering?window.avatarSDKLogger.warn("Context recovery already in progress, skipping."):(this.resolutionRestoreTimer&&(clearTimeout(this.resolutionRestoreTimer),this.resolutionRestoreTimer=null,window.avatarSDKLogger.log("[Recovery] Cancelled resolution restore due to context loss")),this.isRecovering=!0,this.recoverStartTime=Date.now(),this.recoveryStage="light",this.currentStageAttempts=0,this._scheduleNextAttempt())}_restoreHandler(t){this.restoreTimeout&&(clearTimeout(this.restoreTimeout),this.restoreTimeout=null),this.isRecovering?window.avatarSDKLogger.warn("Context restore event received during recovery, skipping duplicate recovery."):(this.options.reportMessage({code:EErrorCode.WEBGL_CONTEXT_RESTORED,message:"Context restored event received.",e:{event:t,timestamp:Date.now()}}),this.isRecovering=!0,this.recoveryStage="light",this.currentStageAttempts=0,this._recoverContext())}_recoverContext(){if(this.device&&this.pipeline&&this.device.gl&&!this.device.gl.isContextLost())return window.avatarSDKLogger.log("[Recovery] Already recovered, skipping."),void(this.isRecovering=!1);window.avatarSDKLogger.log(`[Recovery] stage=${this.recoveryStage}, attempt=${this.currentStageAttempts+1}/${this.recoveryMaxAttempts[this.recoveryStage]}`),this.restoreTimeout&&(clearTimeout(this.restoreTimeout),this.restoreTimeout=null);let t=!1;try{switch(this.recoveryStage){case"light":t=this._tryLightRecovery();break;case"medium":t=this._tryMediumRecovery();break;case"full":t=this._tryFullRecovery()}}catch(t){window.avatarSDKLogger.error(`[Recovery] stage=${this.recoveryStage} threw:`,t)}t?this._onRecoverySuccess():(this.currentStageAttempts++,this.isRecovering=!1,this.currentStageAttempts<this.recoveryMaxAttempts[this.recoveryStage]?this._scheduleNextAttempt():this._advanceStage())}_tryLightRecovery(){try{if(window.avatarSDKLogger.log("[Recovery] Trying light recovery (reuse canvas)..."),this.device){try{this.device.canvas.removeEventListener("webglcontextlost",this.lostHandler),this.device.canvas.removeEventListener("webglcontextrestored",this.restoreHandler),this.device.destroy()}catch(t){}this.device=null}if(this.device=new GLDevice(this.canvas),this.device.canvas.addEventListener("webglcontextlost",this.lostHandler,!1),this.device.canvas.addEventListener("webglcontextrestored",this.restoreHandler,!1),!this.device.gl||this.device.gl.isContextLost())throw new Error("WebGL context still lost after light recovery");return this.createPipelineLock=!0,this.pipeline=new GLPipeline(this.device,this.sendSdkPoint),this.createPipelineLock=!1,this.pendingCharData&&(this.pipeline.setCharData(this.pendingCharData),this.pipeline.setSyncMedia()),this.pipeline.reinitialize(),this.pipeline.setSyncMedia(),this.isInit=!0,!0}catch(t){return window.avatarSDKLogger.warn("[Recovery] Light recovery failed:",t),this._reportRecoveryFailure("light",t),!1}}_tryMediumRecovery(){try{var t;if(window.avatarSDKLogger.log("[Recovery] Trying medium recovery (replace canvas)..."),this.device){try{this.device.canvas.removeEventListener("webglcontextlost",this.lostHandler),this.device.canvas.removeEventListener("webglcontextrestored",this.restoreHandler),this.device.destroy()}catch(t){}this.device=null}if(this.pipeline){try{this.pipeline.destroy()}catch(t){}this.pipeline=null}const r=this.canvas,i=r.style.cssText,s=r.parentNode,a=document.createElement("canvas"),o=null==(t=this.options.resourceManager.getConfig())?void 0:t.resolution;var e,n;if(o&&(a.width=null!=(e=o.width)?e:1080,a.height=null!=(n=o.height)?n:1920),a.setAttribute("style",i),s&&s.replaceChild(a,r),this.canvas=a,this.device=new GLDevice(this.canvas),this.device.canvas.addEventListener("webglcontextlost",this.lostHandler,!1),this.device.canvas.addEventListener("webglcontextrestored",this.restoreHandler,!1),!this.device.gl||this.device.gl.isContextLost())throw new Error("WebGL context lost after medium recovery");return this.createPipelineLock=!0,this.pipeline=new GLPipeline(this.device,this.sendSdkPoint),this.createPipelineLock=!1,this.pendingCharData&&(this.pipeline.setCharData(this.pendingCharData),this.pipeline.setSyncMedia()),this.pipeline.reinitialize(),this.pipeline.setSyncMedia(),this.isInit=!0,!0}catch(t){return window.avatarSDKLogger.warn("[Recovery] Medium recovery failed:",t),this._reportRecoveryFailure("medium",t),!1}}_tryFullRecovery(){try{var t,e,n;if(window.avatarSDKLogger.log("[Recovery] Trying full recovery (reduced resolution)..."),this.device){try{this.device.canvas.removeEventListener("webglcontextlost",this.lostHandler),this.device.canvas.removeEventListener("webglcontextrestored",this.restoreHandler),this.device.destroy()}catch(t){}this.device=null}if(this.pipeline){try{this.pipeline.destroy()}catch(t){}this.pipeline=null}const r=this.canvas,i=r.style.cssText,s=r.parentNode,a=document.createElement("canvas"),o=null==(t=this.options.resourceManager.getConfig())?void 0:t.resolution,l=.75,c=Math.round((null!=(e=null==o?void 0:o.width)?e:1080)*l),d=Math.round((null!=(n=null==o?void 0:o.height)?n:1920)*l);if(a.width=c,a.height=d,a.setAttribute("style",i),s&&s.replaceChild(a,r),this.canvas=a,window.avatarSDKLogger.log(`[Recovery] Using reduced resolution: ${c}x${d} (scale=${l})`),this.device=new GLDevice(this.canvas),this.device.canvas.addEventListener("webglcontextlost",this.lostHandler,!1),this.device.canvas.addEventListener("webglcontextrestored",this.restoreHandler,!1),!this.device.gl||this.device.gl.isContextLost())throw new Error("WebGL context lost after full recovery");return this.createPipelineLock=!0,this.pipeline=new GLPipeline(this.device,this.sendSdkPoint),this.createPipelineLock=!1,this.pendingCharData&&(this.pipeline.setCharData(this.pendingCharData),this.pipeline.setSyncMedia()),this.pipeline.reinitialize(),this.pipeline.setSyncMedia(),this.isInit=!0,!0}catch(t){return window.avatarSDKLogger.warn("[Recovery] Full recovery failed:",t),this._reportRecoveryFailure("full",t),!1}}_onRecoverySuccess(){const t=Date.now()-this.recoverStartTime,e="full"===this.recoveryStage;window.avatarSDKLogger.log(`[Recovery] Success! stage=${this.recoveryStage}, time=${t}ms${e?" (reduced resolution)":""}`),this.options.reportMessage({code:EErrorCode.WEBGL_CONTEXT_RECOVERED,message:`Context recovered via ${this.recoveryStage} recovery in ${t}ms.`,e:{timestamp:Date.now(),recoveryTime:t,stage:this.recoveryStage,attempts:this.currentStageAttempts+1,reducedResolution:e}}),e&&(this.isUsingReducedResolution=!0,this._scheduleResolutionRestore()),this.isRecovering=!1,this.recoveryStage="light",this.currentStageAttempts=0}_scheduleResolutionRestore(){this.resolutionRestoreTimer&&clearTimeout(this.resolutionRestoreTimer),window.avatarSDKLogger.log(`[Recovery] Scheduling resolution restore in ${this.RESOLUTION_RESTORE_DELAY}ms`),this.resolutionRestoreTimer=setTimeout(()=>{this._restoreOriginalResolution()},this.RESOLUTION_RESTORE_DELAY)}_restoreOriginalResolution(){if(this.isUsingReducedResolution&&this.device&&!this.device.gl.isContextLost())try{var t,e,n;window.avatarSDKLogger.log("[Recovery] Attempting to restore original resolution...");const r=null==(t=this.options.resourceManager.getConfig())?void 0:t.resolution,i=null!=(e=null==r?void 0:r.width)?e:1080,s=null!=(n=null==r?void 0:r.height)?n:1920,a=this.canvas.style.cssText,o=this.canvas.parentNode,l=document.createElement("canvas");if(l.width=i,l.height=s,l.setAttribute("style",a),o&&o.replaceChild(l,this.canvas),this.canvas=l,this.device){try{this.device.canvas.removeEventListener("webglcontextlost",this.lostHandler),this.device.canvas.removeEventListener("webglcontextrestored",this.restoreHandler),this.device.destroy()}catch(t){}this.device=null}if(this.pipeline){try{this.pipeline.destroy()}catch(t){}this.pipeline=null}if(this.device=new GLDevice(this.canvas),this.device.canvas.addEventListener("webglcontextlost",this.lostHandler,!1),this.device.canvas.addEventListener("webglcontextrestored",this.restoreHandler,!1),!this.device.gl||this.device.gl.isContextLost())throw new Error("Context lost after resolution restore");this.createPipelineLock=!0,this.pipeline=new GLPipeline(this.device,this.sendSdkPoint),this.createPipelineLock=!1,this.pendingCharData&&(this.pipeline.setCharData(this.pendingCharData),this.pipeline.setSyncMedia()),this.pipeline.reinitialize(),this.pipeline.setSyncMedia(),this.isUsingReducedResolution=!1,window.avatarSDKLogger.log(`[Recovery] Resolution restored to ${i}x${s}`),this.options.reportMessage({code:EErrorCode.WEBGL_RESOLUTION_RESTORED,message:`Resolution restored to ${i}x${s}.`,e:{timestamp:Date.now(),resolution:{width:i,height:s}}})}catch(t){window.avatarSDKLogger.warn("[Recovery] Failed to restore resolution, keeping reduced:",t)}finally{this.resolutionRestoreTimer=null}else window.avatarSDKLogger.warn("[Recovery] Cannot restore resolution: not in reduced mode or context lost")}_advanceStage(){const t=["light","medium","full"],e=t.indexOf(this.recoveryStage);if(e<t.length-1){const n=t[e+1];window.avatarSDKLogger.log(`[Recovery] Stage "${this.recoveryStage}" exhausted, upgrading to "${n}"`),this.recoveryStage=n,this.currentStageAttempts=0,this._scheduleNextAttempt()}else window.avatarSDKLogger.error("[Recovery] All recovery stages exhausted. Giving up."),this.options.reportMessage({code:EErrorCode.WEBGL_CONTEXT_RECOVERY_MAX_ATTEMPTS,message:"All WebGL recovery stages exhausted. SDK restart required.",e:{timestamp:Date.now(),elapsedTime:Date.now()-this.recoverStartTime,stagesAttempted:{light:this.recoveryMaxAttempts.light,medium:this.recoveryMaxAttempts.medium,full:this.recoveryMaxAttempts.full}}}),this.isRecovering=!1}_scheduleNextAttempt(){const t=this.recoveryBaseDelays[this.recoveryStage],e=this.recoveryMaxAttempts[this.recoveryStage],n=t*Math.pow(2,this.currentStageAttempts),r=Math.min(n,this.recoveryMaxDelay);window.avatarSDKLogger.log(`[Recovery] Scheduling ${this.recoveryStage} attempt ${this.currentStageAttempts+1}/${e} in ${r}ms (base=${t}ms, exp=${n}ms)`),this.restoreTimeout=setTimeout(()=>{this.isRecovering=!0,this._recoverContext()},r)}_reportRecoveryFailure(t,e){this.options.reportMessage({code:EErrorCode.WEBGL_CONTEXT_RECOVERY_FAILED,message:`[${t}] recovery attempt ${this.currentStageAttempts+1}/${this.recoveryMaxAttempts[t]} failed.`,e:{error:e,stage:t,attempt:this.currentStageAttempts+1,timestamp:Date.now()}})}init(t){var e,n,r,i,s;let a=t;this.style(null!=(e=null==(n=this.options.resourceManager.getConfig())||null==(n=n.resolution)?void 0:n.width)?e:1080,null!=(r=null==(i=this.options.resourceManager.getConfig())||null==(i=i.resolution)?void 0:i.height)?r:1920),this.setCharacterCanvasAnchor(),null!=(s=a)&&s.char||(a={char:this.options.resourceManager.getMouthShapeLib().char_info,LUT:null,transform:{offsetX:0,offsetY:0,scaleX:1,scaleY:1},multisample:4}),this.pendingCharData=a,this.isInit=!0,this.device=new GLDevice(this.canvas),this.device.canvas.addEventListener("webglcontextlost",this.lostHandler,!1),this.device.canvas.addEventListener("webglcontextrestored",this.restoreHandler,!1),this.createPipeline()}style(t=0,e=0){t>0&&e>0&&(this.canvas.width=t,this.canvas.height=e)}setCanvasStyle(t){var e,n,r,i,s,a,o,l;this.layout=t,this.canvasOffsetX=-1;const c=null!=(e=null!=(n=null==(r=this.walkConfig)?void 0:r.init_point)?n:null==(i=this.options.resourceManager.getConfig())||null==(i=i.walk_config)?void 0:i.init_point)?e:null,{width:d=1080,height:h=1920}=null!=(s=null==(a=this.options.resourceManager.getConfig())?void 0:a.resolution)?s:{width:1080,height:1920},[u,p]=null!=(o=null==(l=t.container)?void 0:l.size)?o:[d,h];let{v_align:f="center",h_align:m="center",scale:_=1,offset_x:g=0,offset_y:y=0}=t.avatar||{};if(null!=c&&(m="left",g=0),"string"==typeof _&&_.includes("vh")){const t=parseFloat(_.replace("vh",""));_=isNaN(t)?1:t/100*p/h}this.scale=Number(_);const S=h*Number(_),A=d*Number(_),v=A/2,E=S/2,b={position:"absolute",zIndex:100,height:`${S}px`,width:`${A}px`,objectFit:"contain",top:"auto",right:"auto",bottom:"auto",left:"auto",marginLeft:"0",marginTop:"0",willChange:"transform",transform:"translateZ(0)"};switch(m){case"left":b.left=null!=c?c-v+"px":"0",b.marginLeft=`${g}px`;break;case"right":b.right=`-${v}px`,b.marginLeft=`${g}px`;break;default:b.position="absolute",b.left="50%",b.marginLeft=`${-v+g}px`}switch(f){case"top":b.top="0",b.marginTop=`${y}px`;break;case"bottom":b.bottom="0",b.marginTop=`${y}px`;break;default:b.position="absolute",b.top="50%",b.marginTop=`${-E+y}px`}const T=getStyleStr(b);this.canvas.setAttribute("style",T)}setWalkConfig(t){this.walkConfig=t,this.baseWalkOffset=this.lastBodyOffset,null!=t.init_point&&this.layout&&this.setCanvasStyle(this.layout)}setCharacterCanvasAnchor(t){var e;if(null!=t&&t.avatar)this.setCanvasStyle(t);else if(null!=(e=this.options.resourceManager.getConfig())&&e.layout){var n;const t=(null==(n=this.options.resourceManager.getConfig())?void 0:n.layout)||{avatar:{v_align:"default",h_align:"default",scale:1,offset_x:0,offset_y:0}};this.setCanvasStyle(t)}else{var r;const t=getStyleStr({position:"absolute",zIndex:100,height:"100%",objectFit:"contain",top:"auto",right:"auto",bottom:"auto",left:"auto",marginLeft:"0",marginTop:"0"});this.canvas.setAttribute("style",t);const e=(null==(r=this.options.resourceManager.getConfig())||null==(r=r.init_events)?void 0:r.find(t=>"SetCharacterCanvasAnchor"===t.type))||{type:"SetCharacterCanvasAnchor",x_location:0,y_location:0,width:1,height:1},{x_location:n,y_location:i,width:s,height:a}=e;this.canvas.setAttribute("style",this.canvas.style.cssText+`left: calc(${n} * 100%); top: calc(${i} * 100%); transform: scale(${s}, ${a}); transform-origin: top left;`)}}computeWeight(t){const e=t-this.lastFrameIndex;return this.lastWeight=t>this.lastRealFaceFrame?Math.min(this.lastWeight+e,12):Math.max(this.lastWeight-e,0),this.lastWeight/12}render(t){var e,n,r,i,s,a,o;if(this.options.dataCacheQueue.clearOldFaceData(t),!this.isInit)return{canvas:this.canvas,rendered:!1};const l=this.options.dataCacheQueue._getBodyImageBitmap(t);let c=this.options.dataCacheQueue._getFaceImageBitmap(t,null!=(e=null!=(n=null==l?void 0:l.body_id)?n:null==l?void 0:l.id)?e:0),d=this.options.dataCacheQueue._getRealFaceImageBitmap(t,null!=(r=null!=(i=null==l?void 0:l.body_id)?i:null==l?void 0:l.id)?r:0);if("speak"===this.lastFrameState&&"speak"!==(null==l?void 0:l.frameState)&&(this.lastRealFaceFrame=-1,this.lastRealFaceFrameData=null,this.lastWeight=0),this.interrupt)c=d;else if(null!=(s=c)&&s.FaceFrameData&&null!=(a=c)&&a.face_frame_type){if(this.lastRealFaceFrameData=c.FaceFrameData,this.lastRealFaceFrame=t,-1!==this.lastRealFaceFrame&&this.lastWeight>0&&d){var h,u;const e=this.computeWeight(t);c={frameIndex:t,state:(null==l?void 0:l.frameState)||"idle",body_id:(null==l?void 0:l.body_id)||-1,sf:t,ef:t,cs:(null==(h=c)?void 0:h.cs)||"",face_frame_type:0,id:(null==l?void 0:l.body_id)||-1,FaceFrameData:IBRAnimationFrameData_NN.interp(this.lastRealFaceFrameData,d.FaceFrameData,d.FaceFrameData,e,(null==(u=this.options.resourceManager.resource_pack)?void 0:u.interpolate_joints)||[])}}}else if(-1===this.lastRealFaceFrame)c=d;else if(null!=d&&d.FaceFrameData)if(null===this.lastRealFaceFrameData)c=d;else{var p,f;const e=this.computeWeight(t);c={frameIndex:t,state:(null==l?void 0:l.frameState)||"idle",body_id:(null==l?void 0:l.body_id)||-1,sf:t,ef:t,cs:(null==(p=c)?void 0:p.cs)||"",face_frame_type:0,id:(null==l?void 0:l.body_id)||-1,FaceFrameData:IBRAnimationFrameData_NN.interp(this.lastRealFaceFrameData,d.FaceFrameData,d.FaceFrameData,e,(null==(f=this.options.resourceManager.resource_pack)?void 0:f.interpolate_joints)||[])}}if(this._setCurrentBodyFrame(l),!(l&&c||null==l)&&l.hfd||!(null!=l&&l.hfd||null!=l&&l.frame))return l?c||(this.allLostFaceFrameCount++,this.options.reportMessage({code:EErrorCode.RENDER_FACE_ERROR,message:`Error: 第${t}帧 faceFrame为空`,e:{bodyFrame:l,faceFrame:c}})):(this.allLostFrameCount++,this.options.reportMessage({code:EErrorCode.RENDER_BODY_ERROR,message:`Error: 第${t}帧 bodyFrame为空`,e:{bodyFrame:l,faceFrame:c}})),this.allLostFrameCount===this.maxLostFrameCount&&(this.options.reportMessage({code:EErrorCode.RENDER_DATA_MISSING,message:`连续${this.maxLostFrameCount}帧 身体渲染数据缺失`,e:{bodyFrame:l,faceFrame:c}}),this.forceSyncDecoder(),this.allLostFrameCount=0),this.allLostFaceFrameCount===this.maxLostFrameCount&&this.options.reportMessage({code:EErrorCode.RENDER_FACE_DATA_MISSING,message:`连续${this.maxLostFrameCount}帧 渲染表情数据缺失.`,e:{bodyFrame:l,frameIndex:t}}),window.avatarSDKLogger.log(this.TAG,"render第",t,"丢帧,bodyFrame",l,"faceFrame",c),{canvas:this.canvas,rendered:!1};if(this.allLostFrameCount=0,this.allLostFaceFrameCount=0,(l&&null!=(o=c)&&o.FaceFrameData&&null!=l&&l.hfd||(null==l||!l.hfd)&&null!=l&&l.frame)&&this.device){var m,_;this.sendVideoInfo({name:l.name,body_id:l.body_id,id:l.id}),(null==l?void 0:l.frameState)!==this.lastFrameState&&(null==(m=this.onStateChange)||m.call(this,null==l?void 0:l.frameState),"speak"!==l.frameState&&window.performanceTracker.markEnd(performanceConstant.start_action_render,l.frameState),this.lastFrameState=null==l?void 0:l.frameState),this.isFirstRender&&(window.performanceTracker.markEnd(performanceConstant.first_avatar_render),this.isFirstRender=!1,this.renderBackground(),window.performanceTracker.markStart(performanceConstant.first_render),null==(_=this.onDownloadProgress)||_.call(this,100));let e=!1;if(this.pipeline){var g;try{var y,S,A,v,E,b,T;const n=this.options.resourceManager.getIsEnableRobotExpression()?null!=(y=null==(S=c)?void 0:S.FaceFrameData)?y:null:null!=l&&l.hfd&&null!=(A=null==(v=c)?void 0:v.FaceFrameData)?A:null;n&&this.saveAndDownload.appendMultipleToArray("render_faceData",[c]),this.lastFaceFrame=c;let r=l.frame;var w;isharmony()&&(this.copyCanvas.width=l.frame.displayWidth,this.copyCanvas.height=l.frame.displayHeight,null==(w=this.copyCtx)||w.drawImage(l.frame,0,0),r=this.copyCanvas),this.pipeline.renderFrame({charBodyTexture:r,data:n,backgroundTexture:null,fx:null!=(E=null==(b=this.options.resourceManager.getConfig())?void 0:b.fx)?E:{},onPostRender:()=>null});let i=[0,0,0],s=[...i];const a=null!=(T=null==l?void 0:l.offset)?T:0;this.lastBodyOffset=a,s[0]+=a-this.baseWalkOffset;const o=this.pipeline.getBillboardTransform2D([i[0],i[1],i[2]],[s[0],s[1],s[2]]).offsetX*this.canvas.width*this.scale;o!==this.canvasOffsetX&&(this.canvasOffsetX=o,WidgetDefaultRenderer.CUSTOM_WIDGET?WidgetDefaultRenderer.CUSTOM_WIDGET({type:"set_character_canvas_offset",data:o}):WidgetDefaultRenderer.PROXY_WIDGET&&WidgetDefaultRenderer.PROXY_WIDGET.set_character_canvas_offset?WidgetDefaultRenderer.PROXY_WIDGET.set_character_canvas_offset(o):updateCanvasXOffset(this.canvas,o)),this.lastFrameIndex=t,e=!0}catch(e){window.avatarSDKLogger.error(this.TAG,"渲染帧失败:",e),this.options.reportMessage({code:EErrorCode.WebGL_RENDER_ERROR,message:`Error: 第${t}帧 webgl渲染异常`,e:{bodyFrame:l,faceFrame:c,error:e}})}finally{l.frame&&"function"==typeof l.frame.close&&l.frame.close()}null==(g=this.onRenderChange)||g.call(this,RenderState.rendering)}else null!=l&&l.frame&&"function"==typeof l.frame.close&&l.frame.close();return{canvas:this.canvas,rendered:e}}return{canvas:this.canvas,rendered:!1}}renderBackground(){const t=this.options.resourceManager.getBackgroundImageElement();if(!t)return;const e=document.getElementById("avatar-bg-container");e&&(e.style.backgroundImage=`url(${t.src})`,e.style.backgroundSize="cover",e.style.backgroundPosition="center")}_setCurrentBodyFrame(t){t&&(this.currentBodyFrame=t)}_getCurrentBodyFrameInfo(t){return this.currentBodyFrame&&t>0?{client_frame:t,current_ani:this.currentBodyFrame.name,current_ani_frame:this.currentBodyFrame.frameIndex-this.currentBodyFrame.sf,next_state:this.lastFrameState||"idle"}:{client_frame:0,current_ani:"",current_ani_frame:0,next_state:"idle"}}_getCurrentFrameData(t){var e,n,r,i,s;const a=this.currentBodyFrame,o=this.lastFaceFrame;return{body:a?{body_id:null!=(e=null!=(n=a.body_id)?n:a.id)?e:0,name:a.name,video_frame:a.frameIndex-a.sf,sf:a.sf,state:a.frameState}:null,face:o?{body_id:null!=(r=null!=(i=o.body_id)?i:o.id)?r:0,sf:o.sf,ef:o.ef,state:o.state,face_frame_type:null!=(s=o.face_frame_type)?s:0}:null}}setCanvasVisibility(t){this.avatarCanvasVisible=t,this.canvas&&(this.canvas.style.display=t?"":"none")}getCanvasVisibility(){return this.avatarCanvasVisible}destroy(){if(this.allLostFrameCount=0,this.allLostFaceFrameCount=0,this.restoreTimeout&&(clearTimeout(this.restoreTimeout),this.restoreTimeout=null),this.isRecovering=!1,this.recoveryStage="light",this.currentStageAttempts=0,this.device)if(this.device.canvas.removeEventListener("webglcontextlost",this.lostHandler),this.device.canvas.removeEventListener("webglcontextrestored",this.restoreHandler),this.pipeline&&(this.pipeline.destroy(),this.pipeline=null),this.device.gl){const t=this.device;this.device=null,requestAnimationFrame(()=>{try{t&&t.destroy()}catch(t){var e;null==(e=window.avatarSDKLogger)||null==e.warn||e.warn("[AvatarRenderer] 销毁 device 时出错:",t)}})}else this.device=null;this.isInit=!1,this.isFirstRender=!0,this.lastRealFaceFrame=-1,this.lastRealFaceFrameData=null,this.lastWeight=0,this.onStateChange=void 0,this.lastFrameState="",this.pipeline=null,this.pendingCharData=null,this.scale=1;const t=document.getElementById("avatar-bg-container");t&&t.parentNode&&t.parentNode.removeChild(t),this.canvas&&this.canvas.parentNode&&this.canvas.remove()}setInterrupt(t){var e;"speak"!==(null==(e=this.lastFaceFrame)?void 0:e.state)&&t||(this.interrupt=t)}simulateContextLoss(t=5e3,e=!1){if(!this.device||!this.device.gl)return void window.avatarSDKLogger.warn("[Test] No WebGL device available for testing");const n=this.device.gl.getExtension("WEBGL_lose_context");n?(window.avatarSDKLogger.log("[Test] Simulating WebGL context loss..."),e&&window.avatarSDKLogger.warn("[Test] Force fail mode enabled - will not auto-restore"),n.loseContext(),t>0&&!e&&setTimeout(()=>{window.avatarSDKLogger.log(`[Test] Auto-restoring context after ${t}ms...`),n.restoreContext()},t)):window.avatarSDKLogger.error("[Test] WEBGL_lose_context extension not available")}getRecoveryStatus(){return{isRecovering:this.isRecovering,stage:this.recoveryStage,attempts:this.currentStageAttempts,maxAttempts:this.recoveryMaxAttempts[this.recoveryStage]||0,isUsingReducedResolution:this.isUsingReducedResolution}}async testStagedRecovery(){window.avatarSDKLogger.log("[Test] Starting staged recovery test...");const t=[{desc:"Light recovery (should succeed)",delay:1e3,forceFail:!1},{desc:"Context loss again (may upgrade to medium)",delay:8e3,forceFail:!1}];for(let e=0;e<t.length;e++){const n=t[e];window.avatarSDKLogger.log(`[Test] Step ${e+1}: ${n.desc}`),await new Promise(t=>{setTimeout(()=>{this.simulateContextLoss(n.delay,n.forceFail),t()},n.delay)}),await new Promise(t=>setTimeout(t,n.delay+2e3));const r=this.getRecoveryStatus();window.avatarSDKLogger.log(`[Test] After step ${e+1}:`,r)}window.avatarSDKLogger.log("[Test] Staged recovery test completed!")}restartWebGL(){window.avatarSDKLogger.log("[restartWebGL] Starting manual WebGL restart..."),this.restoreTimeout&&(clearTimeout(this.restoreTimeout),this.restoreTimeout=null),this.resolutionRestoreTimer&&(clearTimeout(this.resolutionRestoreTimer),this.resolutionRestoreTimer=null),this.isRecovering=!1,this.recoveryStage="light",this.currentStageAttempts=0;try{var t;if(this.device){try{this.device.canvas.removeEventListener("webglcontextlost",this.lostHandler),this.device.canvas.removeEventListener("webglcontextrestored",this.restoreHandler),this.device.destroy()}catch(t){}this.device=null}if(this.pipeline){try{this.pipeline.destroy()}catch(t){}this.pipeline=null}const r=this.canvas,i=r.style.cssText,s=r.parentNode,a=document.createElement("canvas"),o=null==(t=this.options.resourceManager.getConfig())?void 0:t.resolution;var e,n;if(o&&(a.width=null!=(e=o.width)?e:1080,a.height=null!=(n=o.height)?n:1920),a.setAttribute("style",i),s&&s.replaceChild(a,r),this.canvas=a,this.device=new GLDevice(this.canvas),this.device.canvas.addEventListener("webglcontextlost",this.lostHandler,!1),this.device.canvas.addEventListener("webglcontextrestored",this.restoreHandler,!1),!this.device.gl||this.device.gl.isContextLost())throw new Error("WebGL context still lost after creating new canvas");return this.createPipelineLock=!0,this.pipeline=new GLPipeline(this.device,this.sendSdkPoint),this.createPipelineLock=!1,this.pendingCharData&&(this.pipeline.setCharData(this.pendingCharData),this.pipeline.setSyncMedia()),this.pipeline.reinitialize(),this.pipeline.setSyncMedia(),this.isInit=!0,window.avatarSDKLogger.log("[restartWebGL] WebGL restart successful!"),this.options.reportMessage({code:EErrorCode.WEBGL_CONTEXT_MANUAL_RESTARTED,message:"WebGL context recovered via manual restart.",e:{timestamp:Date.now(),method:"manual_restart"}}),!0}catch(t){return window.avatarSDKLogger.error("[restartWebGL] Failed:",t),this._reportRecoveryFailure("manual",t),!1}}}class BaseTrack{render(){}stop(){}}class ImageTrack extends BaseTrack{constructor(t,e){super(),this.data=t,this.instance=e}render(){var t;return null!=(t=this.data)&&t.image?WidgetDefaultRenderer.WIDGET_PIC(this.data,this.instance):null}}class SubtitleTrack extends BaseTrack{constructor(t,e){super(),this.data=t,this.instance=e}render(){return WidgetDefaultRenderer.WIDGET_SUBTITLE(this.data,this.instance)}}class TrackRenderer{constructor(t,e){this.TAG="[TrackRenderer]",this.instance=e;const{type:n,data:r,text:i=""}=t;var s;"widget_pic"===n&&(this.tracker=new ImageTrack(r,e)),("subtitle_on"===n||"subtitle_off"===n)&&(this.tracker=new SubtitleTrack({type:n,text:i,axis_id:null!=(s=null==r?void 0:r.axis_id)?s:1e3},e))}render(){var t;return null==(t=this.tracker)?void 0:t.render()}stop(){this.tracker.stop()}destroy(){WidgetDefaultRenderer.destroy(this.instance)}}class UIRenderer{constructor(t){this.TAG="[UIRenderer]",this.trackerRenderer=[],this.root=document.createElement("div"),this.lastFrameIndex=-1,this.initEventsRendered=!1,this.lastSpeechId=-1,this.interruptSpeechId=-1,this.enableClientInterrupt=!1,this.options=t,this.root.setAttribute("style","position:absolute;"),this.onVoiceStart=t.onVoiceStart,this.onVoiceEnd=t.onVoiceEnd,this.initEventsRendered=!1,this.onWalkStateChange=t.onWalkStateChange,this.enableClientInterrupt=t.enableClientInterrupt,this.onSpeakStateChange=t.onSpeakStateChange}render(t){var e,n,r,i,s,a,o,l,c;let d=[];if(-1===this.lastFrameIndex){const t=this.options.resourceManager.getConfig();t.init_events&&t.init_events.length>0&&(d=t.init_events.map(t=>_extends({},t,{speech_id:0})))}let h=null;if(h=t-this.lastFrameIndex>1?this.options.dataCacheQueue._getEventInterval(this.lastFrameIndex,t):this.options.dataCacheQueue._getEvent(t),this.lastFrameIndex=t,this.initEventsRendered||(this.initEventsRendered=!0,h?h.e=h.e.concat(d):h={e:d}),null==(e=h)||!e.e)return;window.avatarSDKLogger.log("当前帧",t,"获取到的事件",JSON.stringify(h));const u=null==(n=h.e)?void 0:n.filter(t=>null==(null==t?void 0:t.speech_id));if(null!=u&&u.length){const t=u.map(t=>t.type).join(",");this.options.sdk.onMessage({code:EErrorCode.EVENT_WITHOUT_SPEECH_ID,message:`Error: 事件中存在不包含speech_id的事件${t}`,e:u})}var p,f;if(this.enableClientInterrupt&&(h.e=null==(p=h.e)?void 0:p.filter(t=>t.speech_id>this.interruptSpeechId||null==t.speech_id||t.type.endsWith("_end")||"subtitle_off"===t.type)),-1!==this.lastSpeechId&&this.lastSpeechId&&(h.e=null==(f=h.e)?void 0:f.filter(t=>(null==t?void 0:t.speech_id)>=this.lastSpeechId)),null!=(r=h.e)&&r.some(t=>"speak_start"===t.type)){const t=h.e.find(t=>"speak_start"===t.type);this.lastSpeechId=null==t?void 0:t.speech_id,this.onSpeakStateChange("speak_start",t.client_speak_id,(null==t?void 0:t.speech_id)||0)}if((null!=(i=h.e)&&i.some(t=>"walk_start"===t.type)||null!=(s=h.e)&&s.some(t=>"speak_walk_start"===t.type))&&this.onWalkStateChange("walk_start"),null!=(a=h.e)&&a.some(t=>"voice_start"===t.type)){const t=h.e.find(t=>"voice_start"===t.type),e=window.performanceTracker.markEnd(performanceConstant.voice_response_play,"speak");this.options.sendSdkPoint("rendering_display",{multi_turn_conversation_id:null==t?void 0:t.multi_turn_conversation_id}),this.onVoiceStart(e,null==t?void 0:t.client_speak_id)}if((null!=(o=h.e)&&o.some(t=>"walk_end"===t.type)||null!=(l=h.e)&&l.some(t=>"speak_walk_end"===t.type))&&this.onWalkStateChange("walk_end"),null!=(c=h.e)&&c.some(t=>"voice_end"===t.type)){const t=h.e.find(t=>"voice_end"===t.type);this.onVoiceEnd((null==t?void 0:t.client_speak_id)||"",(null==t?void 0:t.speech_id)||0)}["speak_end","speak_error"].forEach(t=>{const e=h.e.find(e=>e.type===t);e&&this.onSpeakStateChange(t,e.client_speak_id,(null==e?void 0:e.speech_id)||0)});const m=[...h.e];for(let t=0;t<h.e.length;t++){const e=h.e[t];if(!Object.prototype.hasOwnProperty.call(e,"event_type"))if(WidgetDefaultRenderer.CUSTOM_WIDGET){WidgetDefaultRenderer.CUSTOM_WIDGET(e);const t=m.indexOf(e);t>-1&&m.splice(t,1)}else if(WidgetDefaultRenderer.PROXY_WIDGET&&WidgetDefaultRenderer.PROXY_WIDGET[e.type]){WidgetDefaultRenderer.PROXY_WIDGET[e.type](e);const t=m.indexOf(e);t>-1&&m.splice(t,1)}}if(m.length>0)for(const t of m){const e=new TrackRenderer(t,this.options.sdk);this.trackerRenderer.push(e)}return this.trackerRenderer}clearTrackerRenderer(){this.trackerRenderer=[]}setInterrupt(t){this.interruptSpeechId=t}destroy(){this.lastSpeechId=-1,this.interruptSpeechId=-1,this.lastFrameIndex=-1,this.initEventsRendered=!1,WidgetDefaultRenderer.destroy(this.options.sdk),this.trackerRenderer.forEach(t=>t.destroy())}}class FPSTracker{constructor(t=60){this.frameTimestamps=[],this.lastFrameTime=0,this.frameCount=0,this.lastUpdateTime=0,this.currentFPS=0,this.totalFrames=0,this.totalTime=0,this.droppedFrames=0,this.totalRenderedFrames=0,this.maxSamples=t}tick(t=!0){const e=performance.now();if(this.lastFrameTime>0){const n=e-this.lastFrameTime;this.frameTimestamps.push(n),this.frameTimestamps.length>this.maxSamples&&this.frameTimestamps.shift(),this.totalFrames++,this.totalTime+=n,t?(this.frameCount++,this.totalRenderedFrames++):this.droppedFrames++,e-this.lastUpdateTime>=1e3&&(this.currentFPS=Math.round(1e3*this.frameCount/(e-this.lastUpdateTime)),this.frameCount=0,this.lastUpdateTime=e)}this.lastFrameTime=e}getStats(){if(0===this.frameTimestamps.length)return{current:0,average:0,min:0,max:0,droppedFrames:0,totalFrames:0};const t=this.frameTimestamps.reduce((t,e)=>t+e,0)/this.frameTimestamps.length,e=Math.min(...this.frameTimestamps),n=Math.max(...this.frameTimestamps);return{current:this.currentFPS,average:this.frameTimestamps.length>0?Math.round(1e3/t):0,min:e>0?Math.round(1e3/n):0,max:n>0?Math.round(1e3/e):0,droppedFrames:this.droppedFrames,totalFrames:this.totalFrames}}getCurrentFPS(){return this.currentFPS}getAverageFPS(){return 0===this.totalTime?0:Math.round(1e3*this.totalFrames/this.totalTime)}reset(){this.frameTimestamps=[],this.lastFrameTime=0,this.frameCount=0,this.lastUpdateTime=0,this.currentFPS=0,this.totalFrames=0,this.totalTime=0,this.droppedFrames=0,this.totalRenderedFrames=0}getDroppedFrames(){return this.droppedFrames}}class Composition{constructor(t){this.TAG="[Composition]",this.container=t.container,this.avatarRenderer=t.avatarRenderer,this.restRenderers=t.restRenderers,this.audioRenderer=t.audioRenderer,this.onFPSUpdate=t.onFPSUpdate,this.audioOnlyMode=t.audioOnlyMode||!1,this.fpsTracker=new FPSTracker,this.audioOnlyMode||this.container.appendChild(t.avatarRenderer.canvas)}compose(t){if(!this.audioOnlyMode){const e=this.avatarRenderer.render(t);this.fpsTracker.tick(e.rendered);const n=this.fpsTracker.getStats();this.onFPSUpdate&&n.current>0&&this.onFPSUpdate(n)}this.audioRenderer.render(t);for(const e of this.restRenderers){const n=e.render(t);if(e.clearTrackerRenderer(),n)for(const t of n){const e=null==t?void 0:t.render();e&&this.container.appendChild(e)}}}getFPSStats(){return this.fpsTracker.getStats()}stop(){this.audioRenderer.stop(-1)}destroy(){this.avatarRenderer.destroy(),this.audioRenderer.destroy(),this.restRenderers.forEach(t=>t.destroy())}}const mp4boxSource='\nvar Log = function() {\n\tvar i = new Date,\n\tr = 4;\n\treturn {\n\t\tsetLogLevel: function(t) {\n\t\t\tr = t == this.debug ? 1 : t == this.info ? 2 : t == this.warn ? 3 : (this.error, 4)\n\t\t},\n\t\tdebug: function(t, e) {\n\t\t\tvoid 0 === console.debug && (console.debug = console.log),\n\t\t\tr <= 1 && console.debug("[" + Log.getDurationString(new Date - i, 1e3) + "]", "[" + t + "]", e)\n\t\t},\n\t\tlog: function(t, e) {\n\t\t\tthis.debug(t.msg)\n\t\t},\n\t\tinfo: function(t, e) {\n\t\t\tr <= 2 && console.info("[" + Log.getDurationString(new Date - i, 1e3) + "]", "[" + t + "]", e)\n\t\t},\n\t\twarn: function(t, e) {\n\t\t\tr <= 3 && console.warn("[" + Log.getDurationString(new Date - i, 1e3) + "]", "[" + t + "]", e)\n\t\t},\n\t\terror: function(t, e) {\n\t\t\tr <= 4 && console.error("[" + Log.getDurationString(new Date - i, 1e3) + "]", "[" + t + "]", e)\n\t\t}\n\t}\n} ();\nLog.getDurationString = function(t, e) {\n\tvar i;\n\tfunction r(t, e) {\n\t\tfor (var i = ("" + t).split("."); i[0].length < e;) i[0] = "0" + i[0];\n\t\treturn i.join(".")\n\t}\n\tt < 0 ? (i = !0, t = -t) : i = !1;\n\tvar s = t / (e || 1),\n\ta = Math.floor(s / 3600);\n\ts -= 3600 * a;\n\tt = Math.floor(s / 60),\n\te = 1e3 * (s -= 60 * t);\n\treturn e -= 1e3 * (s = Math.floor(s)),\n\te = Math.floor(e),\n\t(i ? "-": "") + a + ":" + r(t, 2) + ":" + r(s, 2) + "." + r(e, 3)\n},\nLog.printRanges = function(t) {\n\tvar e = t.length;\n\tif (0 < e) {\n\t\tfor (var i = "",\n\t\tr = 0; r < e; r++) 0 < r && (i += ","),\n\t\ti += "[" + Log.getDurationString(t.start(r)) + "," + Log.getDurationString(t.end(r)) + "]";\n\t\treturn i\n\t}\n\treturn "(empty)"\n},\n"undefined" != typeof exports && (exports.Log = Log);\nvar MP4BoxStream = function(t) {\n\tif (! (t instanceof ArrayBuffer)) throw "Needs an array buffer";\n\tthis.buffer = t,\n\tthis.dataview = new DataView(t),\n\tthis.position = 0\n};\nMP4BoxStream.prototype.getPosition = function() {\n\treturn this.position\n},\nMP4BoxStream.prototype.getEndPosition = function() {\n\treturn this.buffer.byteLength\n},\nMP4BoxStream.prototype.getLength = function() {\n\treturn this.buffer.byteLength\n},\nMP4BoxStream.prototype.seek = function(t) {\n\tt = Math.max(0, Math.min(this.buffer.byteLength, t));\n\treturn this.position = isNaN(t) || !isFinite(t) ? 0 : t,\n\t!0\n},\nMP4BoxStream.prototype.isEos = function() {\n\treturn this.getPosition() >= this.getEndPosition()\n},\nMP4BoxStream.prototype.readAnyInt = function(t, e) {\n\tvar i = 0;\n\tif (this.position + t <= this.buffer.byteLength) {\n\t\tswitch (t) {\n\t\tcase 1:\n\t\t\ti = e ? this.dataview.getInt8(this.position) : this.dataview.getUint8(this.position);\n\t\t\tbreak;\n\t\tcase 2:\n\t\t\ti = e ? this.dataview.getInt16(this.position) : this.dataview.getUint16(this.position);\n\t\t\tbreak;\n\t\tcase 3:\n\t\t\tif (e) throw "No method for reading signed 24 bits values";\n\t\t\ti = this.dataview.getUint8(this.position) << 16,\n\t\t\ti |= this.dataview.getUint8(this.position + 1) << 8,\n\t\t\ti |= this.dataview.getUint8(this.position + 2);\n\t\t\tbreak;\n\t\tcase 4:\n\t\t\ti = e ? this.dataview.getInt32(this.position) : this.dataview.getUint32(this.position);\n\t\t\tbreak;\n\t\tcase 8:\n\t\t\tif (e) throw "No method for reading signed 64 bits values";\n\t\t\ti = this.dataview.getUint32(this.position) << 32,\n\t\t\ti |= this.dataview.getUint32(this.position + 4);\n\t\t\tbreak;\n\t\tdefault:\n\t\t\tthrow "readInt method not implemented for size: " + t\n\t\t}\n\t\treturn this.position += t,\n\t\ti\n\t}\n\tthrow "Not enough bytes in buffer"\n},\nMP4BoxStream.prototype.readUint8 = function() {\n\treturn this.readAnyInt(1, !1)\n},\nMP4BoxStream.prototype.readUint16 = function() {\n\treturn this.readAnyInt(2, !1)\n},\nMP4BoxStream.prototype.readUint24 = function() {\n\treturn this.readAnyInt(3, !1)\n},\nMP4BoxStream.prototype.readUint32 = function() {\n\treturn this.readAnyInt(4, !1)\n},\nMP4BoxStream.prototype.readUint64 = function() {\n\treturn this.readAnyInt(8, !1)\n},\nMP4BoxStream.prototype.readString = function(t) {\n\tif (this.position + t <= this.buffer.byteLength) {\n\t\tfor (var e = "",\n\t\ti = 0; i < t; i++) e += String.fromCharCode(this.readUint8());\n\t\treturn e\n\t}\n\tthrow "Not enough bytes in buffer"\n},\nMP4BoxStream.prototype.readCString = function() {\n\tfor (var t = [];;) {\n\t\tvar e = this.readUint8();\n\t\tif (0 === e) break;\n\t\tt.push(e)\n\t}\n\treturn String.fromCharCode.apply(null, t)\n},\nMP4BoxStream.prototype.readInt8 = function() {\n\treturn this.readAnyInt(1, !0)\n},\nMP4BoxStream.prototype.readInt16 = function() {\n\treturn this.readAnyInt(2, !0)\n},\nMP4BoxStream.prototype.readInt32 = function() {\n\treturn this.readAnyInt(4, !0)\n},\nMP4BoxStream.prototype.readInt64 = function() {\n\treturn this.readAnyInt(8, !1)\n},\nMP4BoxStream.prototype.readUint8Array = function(t) {\n\tfor (var e = new Uint8Array(t), i = 0; i < t; i++) e[i] = this.readUint8();\n\treturn e\n},\nMP4BoxStream.prototype.readInt16Array = function(t) {\n\tfor (var e = new Int16Array(t), i = 0; i < t; i++) e[i] = this.readInt16();\n\treturn e\n},\nMP4BoxStream.prototype.readUint16Array = function(t) {\n\tfor (var e = new Int16Array(t), i = 0; i < t; i++) e[i] = this.readUint16();\n\treturn e\n},\nMP4BoxStream.prototype.readUint32Array = function(t) {\n\tfor (var e = new Uint32Array(t), i = 0; i < t; i++) e[i] = this.readUint32();\n\treturn e\n},\nMP4BoxStream.prototype.readInt32Array = function(t) {\n\tfor (var e = new Int32Array(t), i = 0; i < t; i++) e[i] = this.readInt32();\n\treturn e\n},\n"undefined" != typeof exports && (exports.MP4BoxStream = MP4BoxStream);\nvar DataStream = function(t, e, i) {\n\tthis._byteOffset = e || 0,\n\tt instanceof ArrayBuffer ? this.buffer = t: "object" == typeof t ? (this.dataView = t, e && (this._byteOffset += e)) : this.buffer = new ArrayBuffer(t || 0),\n\tthis.position = 0,\n\tthis.endianness = null == i ? DataStream.LITTLE_ENDIAN: i\n};\nDataStream.prototype = {},\nDataStream.prototype.getPosition = function() {\n\treturn this.position\n},\nDataStream.prototype._realloc = function(t) {\n\tif (this._dynamicSize) {\n\t\tvar e = this._byteOffset + this.position + t,\n\t\ti = this._buffer.byteLength;\n\t\tif (e <= i) e > this._byteLength && (this._byteLength = e);\n\t\telse {\n\t\t\tfor (i < 1 && (i = 1); i < e;) i *= 2;\n\t\t\tvar r = new ArrayBuffer(i),\n\t\t\tt = new Uint8Array(this._buffer);\n\t\t\tnew Uint8Array(r, 0, t.length).set(t),\n\t\t\tthis.buffer = r,\n\t\t\tthis._byteLength = e\n\t\t}\n\t}\n},\nDataStream.prototype._trimAlloc = function() {\n\tvar t, e, i;\n\tthis._byteLength != this._buffer.byteLength && (t = new ArrayBuffer(this._byteLength), e = new Uint8Array(t), i = new Uint8Array(this._buffer, 0, e.length), e.set(i), this.buffer = t)\n},\nDataStream.BIG_ENDIAN = !1,\nDataStream.LITTLE_ENDIAN = !0,\nDataStream.prototype._byteLength = 0,\nObject.defineProperty(DataStream.prototype, "byteLength", {\n\tget: function() {\n\t\treturn this._byteLength - this._byteOffset\n\t}\n}),\nObject.defineProperty(DataStream.prototype, "buffer", {\n\tget: function() {\n\t\treturn this._trimAlloc(),\n\t\tthis._buffer\n\t},\n\tset: function(t) {\n\t\tthis._buffer = t,\n\t\tthis._dataView = new DataView(this._buffer, this._byteOffset),\n\t\tthis._byteLength = this._buffer.byteLength\n\t}\n}),\nObject.defineProperty(DataStream.prototype, "byteOffset", {\n\tget: function() {\n\t\treturn this._byteOffset\n\t},\n\tset: function(t) {\n\t\tthis._byteOffset = t,\n\t\tthis._dataView = new DataView(this._buffer, this._byteOffset),\n\t\tthis._byteLength = this._buffer.byteLength\n\t}\n}),\nObject.defineProperty(DataStream.prototype, "dataView", {\n\tget: function() {\n\t\treturn this._dataView\n\t},\n\tset: function(t) {\n\t\tthis._byteOffset = t.byteOffset,\n\t\tthis._buffer = t.buffer,\n\t\tthis._dataView = new DataView(this._buffer, this._byteOffset),\n\t\tthis._byteLength = this._byteOffset + t.byteLength\n\t}\n}),\nDataStream.prototype.seek = function(t) {\n\tt = Math.max(0, Math.min(this.byteLength, t));\n\tthis.position = isNaN(t) || !isFinite(t) ? 0 : t\n},\nDataStream.prototype.isEof = function() {\n\treturn this.position >= this._byteLength\n},\nDataStream.prototype.mapUint8Array = function(t) {\n\tthis._realloc( + t);\n\tvar e = new Uint8Array(this._buffer, this.byteOffset + this.position, t);\n\treturn this.position += +t,\n\te\n},\nDataStream.prototype.readInt32Array = function(t, e) {\n\tt = null == t ? this.byteLength - this.position / 4 : t;\n\tvar i = new Int32Array(t);\n\treturn DataStream.memcpy(i.buffer, 0, this.buffer, this.byteOffset + this.position, t * i.BYTES_PER_ELEMENT),\n\tDataStream.arrayToNative(i, null == e ? this.endianness: e),\n\tthis.position += i.byteLength,\n\ti\n},\nDataStream.prototype.readInt16Array = function(t, e) {\n\tt = null == t ? this.byteLength - this.position / 2 : t;\n\tvar i = new Int16Array(t);\n\treturn DataStream.memcpy(i.buffer, 0, this.buffer, this.byteOffset + this.position, t * i.BYTES_PER_ELEMENT),\n\tDataStream.arrayToNative(i, null == e ? this.endianness: e),\n\tthis.position += i.byteLength,\n\ti\n},\nDataStream.prototype.readInt8Array = function(t) {\n\tt = null == t ? this.byteLength - this.position: t;\n\tvar e = new Int8Array(t);\n\treturn DataStream.memcpy(e.buffer, 0, this.buffer, this.byteOffset + this.position, t * e.BYTES_PER_ELEMENT),\n\tthis.position += e.byteLength,\n\te\n},\nDataStream.prototype.readUint32Array = function(t, e) {\n\tt = null == t ? this.byteLength - this.position / 4 : t;\n\tvar i = new Uint32Array(t);\n\treturn DataStream.memcpy(i.buffer, 0, this.buffer, this.byteOffset + this.position, t * i.BYTES_PER_ELEMENT),\n\tDataStream.arrayToNative(i, null == e ? this.endianness: e),\n\tthis.position += i.byteLength,\n\ti\n},\nDataStream.prototype.readUint16Array = function(t, e) {\n\tt = null == t ? this.byteLength - this.position / 2 : t;\n\tvar i = new Uint16Array(t);\n\treturn DataStream.memcpy(i.buffer, 0, this.buffer, this.byteOffset + this.position, t * i.BYTES_PER_ELEMENT),\n\tDataStream.arrayToNative(i, null == e ? this.endianness: e),\n\tthis.position += i.byteLength,\n\ti\n},\nDataStream.prototype.readUint8Array = function(t) {\n\tt = null == t ? this.byteLength - this.position: t;\n\tvar e = new Uint8Array(t);\n\treturn DataStream.memcpy(e.buffer, 0, this.buffer, this.byteOffset + this.position, t * e.BYTES_PER_ELEMENT),\n\tthis.position += e.byteLength,\n\te\n},\nDataStream.prototype.readFloat64Array = function(t, e) {\n\tt = null == t ? this.byteLength - this.position / 8 : t;\n\tvar i = new Float64Array(t);\n\treturn DataStream.memcpy(i.buffer, 0, this.buffer, this.byteOffset + this.position, t * i.BYTES_PER_ELEMENT),\n\tDataStream.arrayToNative(i, null == e ? this.endianness: e),\n\tthis.position += i.byteLength,\n\ti\n},\nDataStream.prototype.readFloat32Array = function(t, e) {\n\tt = null == t ? this.byteLength - this.position / 4 : t;\n\tvar i = new Float32Array(t);\n\treturn DataStream.memcpy(i.buffer, 0, this.buffer, this.byteOffset + this.position, t * i.BYTES_PER_ELEMENT),\n\tDataStream.arrayToNative(i, null == e ? this.endianness: e),\n\tthis.position += i.byteLength,\n\ti\n},\nDataStream.prototype.readInt32 = function(t) {\n\tt = this._dataView.getInt32(this.position, null == t ? this.endianness: t);\n\treturn this.position += 4,\n\tt\n},\nDataStream.prototype.readInt16 = function(t) {\n\tt = this._dataView.getInt16(this.position, null == t ? this.endianness: t);\n\treturn this.position += 2,\n\tt\n},\nDataStream.prototype.readInt8 = function() {\n\tvar t = this._dataView.getInt8(this.position);\n\treturn this.position += 1,\n\tt\n},\nDataStream.prototype.readUint32 = function(t) {\n\tt = this._dataView.getUint32(this.position, null == t ? this.endianness: t);\n\treturn this.position += 4,\n\tt\n},\nDataStream.prototype.readUint16 = function(t) {\n\tt = this._dataView.getUint16(this.position, null == t ? this.endianness: t);\n\treturn this.position += 2,\n\tt\n},\nDataStream.prototype.readUint8 = function() {\n\tvar t = this._dataView.getUint8(this.position);\n\treturn this.position += 1,\n\tt\n},\nDataStream.prototype.readFloat32 = function(t) {\n\tt = this._dataView.getFloat32(this.position, null == t ? this.endianness: t);\n\treturn this.position += 4,\n\tt\n},\nDataStream.prototype.readFloat64 = function(t) {\n\tt = this._dataView.getFloat64(this.position, null == t ? this.endianness: t);\n\treturn this.position += 8,\n\tt\n},\nDataStream.endianness = 0 < new Int8Array(new Int16Array([1]).buffer)[0],\nDataStream.memcpy = function(t, e, i, r, s) {\n\te = new Uint8Array(t, e, s),\n\ts = new Uint8Array(i, r, s);\n\te.set(s)\n},\nDataStream.arrayToNative = function(t, e) {\n\treturn e == this.endianness ? t: this.flipArrayEndianness(t)\n},\nDataStream.nativeToEndian = function(t, e) {\n\treturn this.endianness == e ? t: this.flipArrayEndianness(t)\n},\nDataStream.flipArrayEndianness = function(t) {\n\tfor (var e = new Uint8Array(t.buffer, t.byteOffset, t.byteLength), i = 0; i < t.byteLength; i += t.BYTES_PER_ELEMENT) for (var r = i + t.BYTES_PER_ELEMENT - 1,\n\ts = i; s < r; r--, s++) {\n\t\tvar a = e[s];\n\t\te[s] = e[r],\n\t\te[r] = a\n\t}\n\treturn t\n},\nDataStream.prototype.failurePosition = 0,\nString.fromCharCodeUint8 = function(t) {\n\tfor (var e = [], i = 0; i < t.length; i++) e[i] = t[i];\n\treturn String.fromCharCode.apply(null, e)\n},\nDataStream.prototype.readString = function(t, e) {\n\treturn null == e || "ASCII" == e ? String.fromCharCodeUint8.apply(null, [this.mapUint8Array(null == t ? this.byteLength - this.position: t)]) : new TextDecoder(e).decode(this.mapUint8Array(t))\n},\nDataStream.prototype.readCString = function(t) {\n\tvar e = this.byteLength - this.position,\n\ti = new Uint8Array(this._buffer, this._byteOffset + this.position),\n\tr = e;\n\tnull != t && (r = Math.min(t, e));\n\tfor (var s = 0; s < r && 0 !== i[s]; s++);\n\tvar a = String.fromCharCodeUint8.apply(null, [this.mapUint8Array(s)]);\n\treturn null != t ? this.position += r - s: s != e && (this.position += 1),\n\ta\n};\nvar MAX_SIZE = Math.pow(2, 32);\nDataStream.prototype.readInt64 = function() {\n\treturn this.readInt32() * MAX_SIZE + this.readUint32()\n},\nDataStream.prototype.readUint64 = function() {\n\treturn this.readUint32() * MAX_SIZE + this.readUint32()\n},\nDataStream.prototype.readInt64 = function() {\n\treturn this.readUint32() * MAX_SIZE + this.readUint32()\n},\nDataStream.prototype.readUint24 = function() {\n\treturn (this.readUint8() << 16) + (this.readUint8() << 8) + this.readUint8()\n},\n"undefined" != typeof exports && (exports.DataStream = DataStream),\nDataStream.prototype.save = function(t) {\n\tvar e = new Blob([this.buffer]);\n\tif (!window.URL || !URL.createObjectURL) throw "DataStream.save: Can\'t create object URL.";\n\tvar i = window.URL.createObjectURL(e),\n\te = document.createElement("a");\n\tdocument.body.appendChild(e),\n\te.setAttribute("href", i),\n\te.setAttribute("download", t),\n\te.setAttribute("target", "_self"),\n\te.click(),\n\twindow.URL.revokeObjectURL(i)\n},\nDataStream.prototype._dynamicSize = !0,\nObject.defineProperty(DataStream.prototype, "dynamicSize", {\n\tget: function() {\n\t\treturn this._dynamicSize\n\t},\n\tset: function(t) {\n\t\tt || this._trimAlloc(),\n\t\tthis._dynamicSize = t\n\t}\n}),\nDataStream.prototype.shift = function(t) {\n\tvar e = new ArrayBuffer(this._byteLength - t),\n\ti = new Uint8Array(e),\n\tr = new Uint8Array(this._buffer, t, i.length);\n\ti.set(r),\n\tthis.buffer = e,\n\tthis.position -= t\n},\nDataStream.prototype.writeInt32Array = function(t, e) {\n\tif (this._realloc(4 * t.length), t instanceof Int32Array && this.byteOffset + this.position % t.BYTES_PER_ELEMENT === 0) DataStream.memcpy(this._buffer, this.byteOffset + this.position, t.buffer, 0, t.byteLength),\n\tthis.mapInt32Array(t.length, e);\n\telse for (var i = 0; i < t.length; i++) this.writeInt32(t[i], e)\n},\nDataStream.prototype.writeInt16Array = function(t, e) {\n\tif (this._realloc(2 * t.length), t instanceof Int16Array && this.byteOffset + this.position % t.BYTES_PER_ELEMENT === 0) DataStream.memcpy(this._buffer, this.byteOffset + this.position, t.buffer, 0, t.byteLength),\n\tthis.mapInt16Array(t.length, e);\n\telse for (var i = 0; i < t.length; i++) this.writeInt16(t[i], e)\n},\nDataStream.prototype.writeInt8Array = function(t) {\n\tif (this._realloc( + t.length), t instanceof Int8Array && this.byteOffset + this.position % t.BYTES_PER_ELEMENT === 0) DataStream.memcpy(this._buffer, this.byteOffset + this.position, t.buffer, 0, t.byteLength),\n\tthis.mapInt8Array(t.length);\n\telse for (var e = 0; e < t.length; e++) this.writeInt8(t[e])\n},\nDataStream.prototype.writeUint32Array = function(t, e) {\n\tif (this._realloc(4 * t.length), t instanceof Uint32Array && this.byteOffset + this.position % t.BYTES_PER_ELEMENT === 0) DataStream.memcpy(this._buffer, this.byteOffset + this.position, t.buffer, 0, t.byteLength),\n\tthis.mapUint32Array(t.length, e);\n\telse for (var i = 0; i < t.length; i++) this.writeUint32(t[i], e)\n},\nDataStream.prototype.writeUint16Array = function(t, e) {\n\tif (this._realloc(2 * t.length), t instanceof Uint16Array && this.byteOffset + this.position % t.BYTES_PER_ELEMENT === 0) DataStream.memcpy(this._buffer, this.byteOffset + this.position, t.buffer, 0, t.byteLength),\n\tthis.mapUint16Array(t.length, e);\n\telse for (var i = 0; i < t.length; i++) this.writeUint16(t[i], e)\n},\nDataStream.prototype.writeUint8Array = function(t) {\n\tif (this._realloc( + t.length), t instanceof Uint8Array && this.byteOffset + this.position % t.BYTES_PER_ELEMENT === 0) DataStream.memcpy(this._buffer, this.byteOffset + this.position, t.buffer, 0, t.byteLength),\n\tthis.mapUint8Array(t.length);\n\telse for (var e = 0; e < t.length; e++) this.writeUint8(t[e])\n},\nDataStream.prototype.writeFloat64Array = function(t, e) {\n\tif (this._realloc(8 * t.length), t instanceof Float64Array && this.byteOffset + this.position % t.BYTES_PER_ELEMENT === 0) DataStream.memcpy(this._buffer, this.byteOffset + this.position, t.buffer, 0, t.byteLength),\n\tthis.mapFloat64Array(t.length, e);\n\telse for (var i = 0; i < t.length; i++) this.writeFloat64(t[i], e)\n},\nDataStream.prototype.writeFloat32Array = function(t, e) {\n\tif (this._realloc(4 * t.length), t instanceof Float32Array && this.byteOffset + this.position % t.BYTES_PER_ELEMENT === 0) DataStream.memcpy(this._buffer, this.byteOffset + this.position, t.buffer, 0, t.byteLength),\n\tthis.mapFloat32Array(t.length, e);\n\telse for (var i = 0; i < t.length; i++) this.writeFloat32(t[i], e)\n},\nDataStream.prototype.writeInt32 = function(t, e) {\n\tthis._realloc(4),\n\tthis._dataView.setInt32(this.position, t, null == e ? this.endianness: e),\n\tthis.position += 4\n},\nDataStream.prototype.writeInt16 = function(t, e) {\n\tthis._realloc(2),\n\tthis._dataView.setInt16(this.position, t, null == e ? this.endianness: e),\n\tthis.position += 2\n},\nDataStream.prototype.writeInt8 = function(t) {\n\tthis._realloc(1),\n\tthis._dataView.setInt8(this.position, t),\n\tthis.position += 1\n},\nDataStream.prototype.writeUint32 = function(t, e) {\n\tthis._realloc(4),\n\tthis._dataView.setUint32(this.position, t, null == e ? this.endianness: e),\n\tthis.position += 4\n},\nDataStream.prototype.writeUint16 = function(t, e) {\n\tthis._realloc(2),\n\tthis._dataView.setUint16(this.position, t, null == e ? this.endianness: e),\n\tthis.position += 2\n},\nDataStream.prototype.writeUint8 = function(t) {\n\tthis._realloc(1),\n\tthis._dataView.setUint8(this.position, t),\n\tthis.position += 1\n},\nDataStream.prototype.writeFloat32 = function(t, e) {\n\tthis._realloc(4),\n\tthis._dataView.setFloat32(this.position, t, null == e ? this.endianness: e),\n\tthis.position += 4\n},\nDataStream.prototype.writeFloat64 = function(t, e) {\n\tthis._realloc(8),\n\tthis._dataView.setFloat64(this.position, t, null == e ? this.endianness: e),\n\tthis.position += 8\n},\nDataStream.prototype.writeUCS2String = function(t, e, i) {\n\tnull == i && (i = t.length);\n\tfor (var r = 0; r < t.length && r < i; r++) this.writeUint16(t.charCodeAt(r), e);\n\tfor (; r < i; r++) this.writeUint16(0)\n},\nDataStream.prototype.writeString = function(t, e, i) {\n\tvar r = 0;\n\tif (null == e || "ASCII" == e) if (null != i) {\n\t\tfor (var s = Math.min(t.length, i), r = 0; r < s; r++) this.writeUint8(t.charCodeAt(r));\n\t\tfor (; r < i; r++) this.writeUint8(0)\n\t} else for (r = 0; r < t.length; r++) this.writeUint8(t.charCodeAt(r));\n\telse this.writeUint8Array(new TextEncoder(e).encode(t.substring(0, i)))\n},\nDataStream.prototype.writeCString = function(t, e) {\n\tvar i = 0;\n\tif (null != e) {\n\t\tfor (var r = Math.min(t.length, e), i = 0; i < r; i++) this.writeUint8(t.charCodeAt(i));\n\t\tfor (; i < e; i++) this.writeUint8(0)\n\t} else {\n\t\tfor (i = 0; i < t.length; i++) this.writeUint8(t.charCodeAt(i));\n\t\tthis.writeUint8(0)\n\t}\n},\nDataStream.prototype.writeStruct = function(t, e) {\n\tfor (var i = 0; i < t.length; i += 2) {\n\t\tvar r = t[i + 1];\n\t\tthis.writeType(r, e[t[i]], e)\n\t}\n},\nDataStream.prototype.writeType = function(t, e, i) {\n\tvar r;\n\tif ("function" == typeof t) return t(this, e);\n\tif ("object" == typeof t && !(t instanceof Array)) return t.set(this, e, i);\n\tvar s = null,\n\ta = "ASCII",\n\ti = this.position;\n\tswitch ("string" == typeof t && /:/.test(t) && (t = (r = t.split(":"))[0], s = parseInt(r[1])), "string" == typeof t && /,/.test(t) && (t = (r = t.split(","))[0], a = parseInt(r[1])), t) {\n\tcase "uint8":\n\t\tthis.writeUint8(e);\n\t\tbreak;\n\tcase "int8":\n\t\tthis.writeInt8(e);\n\t\tbreak;\n\tcase "uint16":\n\t\tthis.writeUint16(e, this.endianness);\n\t\tbreak;\n\tcase "int16":\n\t\tthis.writeInt16(e, this.endianness);\n\t\tbreak;\n\tcase "uint32":\n\t\tthis.writeUint32(e, this.endianness);\n\t\tbreak;\n\tcase "int32":\n\t\tthis.writeInt32(e, this.endianness);\n\t\tbreak;\n\tcase "float32":\n\t\tthis.writeFloat32(e, this.endianness);\n\t\tbreak;\n\tcase "float64":\n\t\tthis.writeFloat64(e, this.endianness);\n\t\tbreak;\n\tcase "uint16be":\n\t\tthis.writeUint16(e, DataStream.BIG_ENDIAN);\n\t\tbreak;\n\tcase "int16be":\n\t\tthis.writeInt16(e, DataStream.BIG_ENDIAN);\n\t\tbreak;\n\tcase "uint32be":\n\t\tthis.writeUint32(e, DataStream.BIG_ENDIAN);\n\t\tbreak;\n\tcase "int32be":\n\t\tthis.writeInt32(e, DataStream.BIG_ENDIAN);\n\t\tbreak;\n\tcase "float32be":\n\t\tthis.writeFloat32(e, DataStream.BIG_ENDIAN);\n\t\tbreak;\n\tcase "float64be":\n\t\tthis.writeFloat64(e, DataStream.BIG_ENDIAN);\n\t\tbreak;\n\tcase "uint16le":\n\t\tthis.writeUint16(e, DataStream.LITTLE_ENDIAN);\n\t\tbreak;\n\tcase "int16le":\n\t\tthis.writeInt16(e, DataStream.LITTLE_ENDIAN);\n\t\tbreak;\n\tcase "uint32le":\n\t\tthis.writeUint32(e, DataStream.LITTLE_ENDIAN);\n\t\tbreak;\n\tcase "int32le":\n\t\tthis.writeInt32(e, DataStream.LITTLE_ENDIAN);\n\t\tbreak;\n\tcase "float32le":\n\t\tthis.writeFloat32(e, DataStream.LITTLE_ENDIAN);\n\t\tbreak;\n\tcase "float64le":\n\t\tthis.writeFloat64(e, DataStream.LITTLE_ENDIAN);\n\t\tbreak;\n\tcase "cstring":\n\t\tthis.writeCString(e, s);\n\t\tbreak;\n\tcase "string":\n\t\tthis.writeString(e, a, s);\n\t\tbreak;\n\tcase "u16string":\n\t\tthis.writeUCS2String(e, this.endianness, s);\n\t\tbreak;\n\tcase "u16stringle":\n\t\tthis.writeUCS2String(e, DataStream.LITTLE_ENDIAN, s);\n\t\tbreak;\n\tcase "u16stringbe":\n\t\tthis.writeUCS2String(e, DataStream.BIG_ENDIAN, s);\n\t\tbreak;\n\tdefault:\n\t\tif (3 == t.length) {\n\t\t\tfor (var n = t[1], o = 0; o < e.length; o++) this.writeType(n, e[o]);\n\t\t\tbreak\n\t\t}\n\t\tthis.writeStruct(t, e)\n\t}\n\tnull != s && (this.position = i, this._realloc(s), this.position = i + s)\n},\nDataStream.prototype.writeUint64 = function(t) {\n\tvar e = Math.floor(t / MAX_SIZE);\n\tthis.writeUint32(e),\n\tthis.writeUint32(4294967295 & t)\n},\nDataStream.prototype.writeUint24 = function(t) {\n\tthis.writeUint8((16711680 & t) >> 16),\n\tthis.writeUint8((65280 & t) >> 8),\n\tthis.writeUint8(255 & t)\n},\nDataStream.prototype.adjustUint32 = function(t, e) {\n\tvar i = this.position;\n\tthis.seek(t),\n\tthis.writeUint32(e),\n\tthis.seek(i)\n},\nDataStream.prototype.mapInt32Array = function(t, e) {\n\tthis._realloc(4 * t);\n\tvar i = new Int32Array(this._buffer, this.byteOffset + this.position, t);\n\treturn DataStream.arrayToNative(i, null == e ? this.endianness: e),\n\tthis.position += 4 * t,\n\ti\n},\nDataStream.prototype.mapInt16Array = function(t, e) {\n\tthis._realloc(2 * t);\n\tvar i = new Int16Array(this._buffer, this.byteOffset + this.position, t);\n\treturn DataStream.arrayToNative(i, null == e ? this.endianness: e),\n\tthis.position += 2 * t,\n\ti\n},\nDataStream.prototype.mapInt8Array = function(t) {\n\tthis._realloc( + t);\n\tvar e = new Int8Array(this._buffer, this.byteOffset + this.position, t);\n\treturn this.position += +t,\n\te\n},\nDataStream.prototype.mapUint32Array = function(t, e) {\n\tthis._realloc(4 * t);\n\tvar i = new Uint32Array(this._buffer, this.byteOffset + this.position, t);\n\treturn DataStream.arrayToNative(i, null == e ? this.endianness: e),\n\tthis.position += 4 * t,\n\ti\n},\nDataStream.prototype.mapUint16Array = function(t, e) {\n\tthis._realloc(2 * t);\n\tvar i = new Uint16Array(this._buffer, this.byteOffset + this.position, t);\n\treturn DataStream.arrayToNative(i, null == e ? this.endianness: e),\n\tthis.position += 2 * t,\n\ti\n},\nDataStream.prototype.mapFloat64Array = function(t, e) {\n\tthis._realloc(8 * t);\n\tvar i = new Float64Array(this._buffer, this.byteOffset + this.position, t);\n\treturn DataStream.arrayToNative(i, null == e ? this.endianness: e),\n\tthis.position += 8 * t,\n\ti\n},\nDataStream.prototype.mapFloat32Array = function(t, e) {\n\tthis._realloc(4 * t);\n\tvar i = new Float32Array(this._buffer, this.byteOffset + this.position, t);\n\treturn DataStream.arrayToNative(i, null == e ? this.endianness: e),\n\tthis.position += 4 * t,\n\ti\n};\nvar MultiBufferStream = function(t) {\n\tthis.buffers = [],\n\tthis.bufferIndex = -1,\n\tt && (this.insertBuffer(t), this.bufferIndex = 0)\n};\nMultiBufferStream.prototype = new DataStream(new ArrayBuffer, 0, DataStream.BIG_ENDIAN),\nMultiBufferStream.prototype.initialized = function() {\n\tvar t;\n\treturn - 1 < this.bufferIndex || (0 < this.buffers.length ? 0 === (t = this.buffers[0]).fileStart ? (this.buffer = t, this.bufferIndex = 0, Log.debug("MultiBufferStream", "Stream ready for parsing"), !0) : (Log.warn("MultiBufferStream", "The first buffer should have a fileStart of 0"), this.logBufferLevel(), !1) : (Log.warn("MultiBufferStream", "No buffer to start parsing from"), this.logBufferLevel(), !1))\n},\nArrayBuffer.concat = function(t, e) {\n\tLog.debug("ArrayBuffer", "Trying to create a new buffer of size: " + (t.byteLength + e.byteLength));\n\tvar i = new Uint8Array(t.byteLength + e.byteLength);\n\treturn i.set(new Uint8Array(t), 0),\n\ti.set(new Uint8Array(e), t.byteLength),\n\ti.buffer\n},\nMultiBufferStream.prototype.reduceBuffer = function(t, e, i) {\n\tvar r = new Uint8Array(i);\n\treturn r.set(new Uint8Array(t, e, i)),\n\tr.buffer.fileStart = t.fileStart + e,\n\tr.buffer.usedBytes = 0,\n\tr.buffer\n},\nMultiBufferStream.prototype.insertBuffer = function(t) {\n\tfor (var e = !0,\n\ti = 0; i < this.buffers.length; i++) {\n\t\tvar r = this.buffers[i];\n\t\tif (t.fileStart <= r.fileStart) {\n\t\t\tif (t.fileStart === r.fileStart) {\n\t\t\t\tif (t.byteLength > r.byteLength) {\n\t\t\t\t\tthis.buffers.splice(i, 1),\n\t\t\t\t\ti--;\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\t\t\t\tLog.warn("MultiBufferStream", "Buffer (fileStart: " + t.fileStart + " - Length: " + t.byteLength + ") already appended, ignoring")\n\t\t\t} else t.fileStart + t.byteLength <= r.fileStart || (t = this.reduceBuffer(t, 0, r.fileStart - t.fileStart)),\n\t\t\tLog.debug("MultiBufferStream", "Appending new buffer (fileStart: " + t.fileStart + " - Length: " + t.byteLength + ")"),\n\t\t\tthis.buffers.splice(i, 0, t),\n\t\t\t0 === i && (this.buffer = t);\n\t\t\te = !1;\n\t\t\tbreak\n\t\t}\n\t\tif (t.fileStart < r.fileStart + r.byteLength) {\n\t\t\tvar s = r.fileStart + r.byteLength - t.fileStart,\n\t\t\tr = t.byteLength - s;\n\t\t\tif (! (0 < r)) {\n\t\t\t\te = !1;\n\t\t\t\tbreak\n\t\t\t}\n\t\t\tt = this.reduceBuffer(t, s, r)\n\t\t}\n\t}\n\te && (Log.debug("MultiBufferStream", "Appending new buffer (fileStart: " + t.fileStart + " - Length: " + t.byteLength + ")"), this.buffers.push(t), 0 === i && (this.buffer = t))\n},\nMultiBufferStream.prototype.logBufferLevel = function(t) {\n\tfor (var e, i, r = [], s = "", a = 0, n = 0, o = 0; o < this.buffers.length; o++) e = this.buffers[o],\n\t0 === o ? (i = {},\n\tr.push(i), i.start = e.fileStart, i.end = e.fileStart + e.byteLength, s += "[" + i.start + "-") : i.end === e.fileStart ? i.end = e.fileStart + e.byteLength: ((i = {}).start = e.fileStart, s += r[r.length - 1].end - 1 + "], [" + i.start + "-", i.end = e.fileStart + e.byteLength, r.push(i)),\n\ta += e.usedBytes,\n\tn += e.byteLength;\n\t0 < r.length && (s += i.end - 1 + "]");\n\tt = t ? Log.info: Log.debug;\n\t0 === this.buffers.length ? t("MultiBufferStream", "No more buffer in memory") : t("MultiBufferStream", this.buffers.length + " stored buffer(s) (" + a + "/" + n + " bytes), continuous ranges: " + s)\n},\nMultiBufferStream.prototype.cleanBuffers = function() {\n\tfor (var t, e = 0; e < this.buffers.length; e++)(t = this.buffers[e]).usedBytes === t.byteLength && (Log.debug("MultiBufferStream", "Removing buffer #" + e), this.buffers.splice(e, 1), e--)\n},\nMultiBufferStream.prototype.mergeNextBuffer = function() {\n\tvar t;\n\tif (this.bufferIndex + 1 < this.buffers.length) {\n\t\tif ((t = this.buffers[this.bufferIndex + 1]).fileStart !== this.buffer.fileStart + this.buffer.byteLength) return ! 1;\n\t\tvar e = this.buffer.byteLength,\n\t\ti = this.buffer.usedBytes,\n\t\tr = this.buffer.fileStart;\n\t\treturn this.buffers[this.bufferIndex] = ArrayBuffer.concat(this.buffer, t),\n\t\tthis.buffer = this.buffers[this.bufferIndex],\n\t\tthis.buffers.splice(this.bufferIndex + 1, 1),\n\t\tthis.buffer.usedBytes = i,\n\t\tthis.buffer.fileStart = r,\n\t\tLog.debug("ISOFile", "Concatenating buffer for box parsing (length: " + e + "->" + this.buffer.byteLength + ")"),\n\t\t!0\n\t}\n\treturn ! 1\n},\nMultiBufferStream.prototype.findPosition = function(t, e, i) {\n\tfor (var r = null,\n\ts = -1,\n\ta = !0 === t ? 0 : this.bufferIndex; a < this.buffers.length && (r = this.buffers[a]).fileStart <= e;) s = a,\n\ti && (r.fileStart + r.byteLength <= e ? r.usedBytes = r.byteLength: r.usedBytes = e - r.fileStart, this.logBufferLevel()),\n\ta++;\n\treturn - 1 !== s && (r = this.buffers[s]).fileStart + r.byteLength >= e ? (Log.debug("MultiBufferStream", "Found position in existing buffer #" + s), s) : -1\n},\nMultiBufferStream.prototype.findEndContiguousBuf = function(t) {\n\tvar e, i, t = void 0 !== t ? t: this.bufferIndex,\n\tr = this.buffers[t];\n\tif (this.buffers.length > t + 1) for (e = t + 1; e < this.buffers.length && (i = this.buffers[e]).fileStart === r.fileStart + r.byteLength; e++) r = i;\n\treturn r.fileStart + r.byteLength\n},\nMultiBufferStream.prototype.getEndFilePositionAfter = function(t) {\n\tvar e = this.findPosition(!0, t, !1);\n\treturn - 1 !== e ? this.findEndContiguousBuf(e) : t\n},\nMultiBufferStream.prototype.addUsedBytes = function(t) {\n\tthis.buffer.usedBytes += t,\n\tthis.logBufferLevel()\n},\nMultiBufferStream.prototype.setAllUsedBytes = function() {\n\tthis.buffer.usedBytes = this.buffer.byteLength,\n\tthis.logBufferLevel()\n},\nMultiBufferStream.prototype.seek = function(t, e, i) {\n\ti = this.findPosition(e, t, i);\n\treturn - 1 !== i ? (this.buffer = this.buffers[i], this.bufferIndex = i, this.position = t - this.buffer.fileStart, Log.debug("MultiBufferStream", "Repositioning parser at buffer position: " + this.position), !0) : (Log.debug("MultiBufferStream", "Position " + t + " not found in buffered data"), !1)\n},\nMultiBufferStream.prototype.getPosition = function() {\n\tif (-1 === this.bufferIndex || null === this.buffers[this.bufferIndex]) throw "Error accessing position in the MultiBufferStream";\n\treturn this.buffers[this.bufferIndex].fileStart + this.position\n},\nMultiBufferStream.prototype.getLength = function() {\n\treturn this.byteLength\n},\nMultiBufferStream.prototype.getEndPosition = function() {\n\tif (-1 === this.bufferIndex || null === this.buffers[this.bufferIndex]) throw "Error accessing position in the MultiBufferStream";\n\treturn this.buffers[this.bufferIndex].fileStart + this.byteLength\n},\n"undefined" != typeof exports && (exports.MultiBufferStream = MultiBufferStream);\nvar MPEG4DescriptorParser = function() {\n\tvar s = [];\n\ts[3] = "ES_Descriptor",\n\ts[4] = "DecoderConfigDescriptor",\n\ts[5] = "DecoderSpecificInfo",\n\ts[6] = "SLConfigDescriptor",\n\tthis.getDescriptorName = function(t) {\n\t\treturn s[t]\n\t};\n\tvar r = this,\n\ta = {};\n\treturn this.parseOneDescriptor = function(t) {\n\t\tvar e, i = 0,\n\t\tr = t.readUint8();\n\t\tfor (e = t.readUint8(), 0; 128 & e;) i = (i << 7) + (127 & e),\n\t\te = t.readUint8(),\n\t\t0;\n\t\treturn i = (i << 7) + (127 & e),\n\t\tLog.debug("MPEG4DescriptorParser", "Found " + (s[r] || "Descriptor " + r) + ", size " + i + " at position " + t.getPosition()),\n\t\t(r = new(s[r] ? a[s[r]] : a.Descriptor)(i)).parse(t),\n\t\tr\n\t},\n\ta.Descriptor = function(t, e) {\n\t\tthis.tag = t,\n\t\tthis.size = e,\n\t\tthis.descs = []\n\t},\n\ta.Descriptor.prototype.parse = function(t) {\n\t\tthis.data = t.readUint8Array(this.size)\n\t},\n\ta.Descriptor.prototype.findDescriptor = function(t) {\n\t\tfor (var e = 0; e < this.descs.length; e++) if (this.descs[e].tag == t) return this.descs[e];\n\t\treturn null\n\t},\n\ta.Descriptor.prototype.parseRemainingDescriptors = function(t) {\n\t\tfor (var e = t.position; t.position < e + this.size;) {\n\t\t\tvar i = r.parseOneDescriptor(t);\n\t\t\tthis.descs.push(i)\n\t\t}\n\t},\n\ta.ES_Descriptor = function(t) {\n\t\ta.Descriptor.call(this, 3, t)\n\t},\n\ta.ES_Descriptor.prototype = new a.Descriptor,\n\ta.ES_Descriptor.prototype.parse = function(t) {\n\t\tvar e;\n\t\tthis.ES_ID = t.readUint16(),\n\t\tthis.flags = t.readUint8(),\n\t\tthis.size -= 3,\n\t\t128 & this.flags ? (this.dependsOn_ES_ID = t.readUint16(), this.size -= 2) : this.dependsOn_ES_ID = 0,\n\t\t64 & this.flags ? (e = t.readUint8(), this.URL = t.readString(e), this.size -= e + 1) : this.URL = "",\n\t\t32 & this.flags ? (this.OCR_ES_ID = t.readUint16(), this.size -= 2) : this.OCR_ES_ID = 0,\n\t\tthis.parseRemainingDescriptors(t)\n\t},\n\ta.ES_Descriptor.prototype.getOTI = function(t) {\n\t\tvar e = this.findDescriptor(4);\n\t\treturn e ? e.oti: 0\n\t},\n\ta.ES_Descriptor.prototype.getAudioConfig = function(t) {\n\t\tvar e = this.findDescriptor(4);\n\t\tif (!e) return null;\n\t\tvar i = e.findDescriptor(5);\n\t\tif (i && i.data) {\n\t\t\te = (248 & i.data[0]) >> 3;\n\t\t\treturn 31 === e && 2 <= i.data.length && (e = 32 + ((7 & i.data[0]) << 3) + ((224 & i.data[1]) >> 5)),\n\t\t\te\n\t\t}\n\t\treturn null\n\t},\n\ta.DecoderConfigDescriptor = function(t) {\n\t\ta.Descriptor.call(this, 4, t)\n\t},\n\ta.DecoderConfigDescriptor.prototype = new a.Descriptor,\n\ta.DecoderConfigDescriptor.prototype.parse = function(t) {\n\t\tthis.oti = t.readUint8(),\n\t\tthis.streamType = t.readUint8(),\n\t\tthis.upStream = 0 != (this.streamType >> 1 & 1),\n\t\tthis.streamType = this.streamType >>> 2,\n\t\tthis.bufferSize = t.readUint24(),\n\t\tthis.maxBitrate = t.readUint32(),\n\t\tthis.avgBitrate = t.readUint32(),\n\t\tthis.size -= 13,\n\t\tthis.parseRemainingDescriptors(t)\n\t},\n\ta.DecoderSpecificInfo = function(t) {\n\t\ta.Descriptor.call(this, 5, t)\n\t},\n\ta.DecoderSpecificInfo.prototype = new a.Descriptor,\n\ta.SLConfigDescriptor = function(t) {\n\t\ta.Descriptor.call(this, 6, t)\n\t},\n\ta.SLConfigDescriptor.prototype = new a.Descriptor,\n\tthis\n};\n"undefined" != typeof exports && (exports.MPEG4DescriptorParser = MPEG4DescriptorParser);\nvar BoxParser = {\n\tERR_INVALID_DATA: -1,\n\tERR_NOT_ENOUGH_DATA: 0,\n\tOK: 1,\n\tBASIC_BOXES: [{\n\t\ttype: "mdat",\n\t\tname: "MediaDataBox"\n\t},\n\t{\n\t\ttype: "idat",\n\t\tname: "ItemDataBox"\n\t},\n\t{\n\t\ttype: "free",\n\t\tname: "FreeSpaceBox"\n\t},\n\t{\n\t\ttype: "skip",\n\t\tname: "FreeSpaceBox"\n\t},\n\t{\n\t\ttype: "meco",\n\t\tname: "AdditionalMetadataContainerBox"\n\t},\n\t{\n\t\ttype: "strk",\n\t\tname: "SubTrackBox"\n\t}],\n\tFULL_BOXES: [{\n\t\ttype: "hmhd",\n\t\tname: "HintMediaHeaderBox"\n\t},\n\t{\n\t\ttype: "nmhd",\n\t\tname: "NullMediaHeaderBox"\n\t},\n\t{\n\t\ttype: "iods",\n\t\tname: "ObjectDescriptorBox"\n\t},\n\t{\n\t\ttype: "xml ",\n\t\tname: "XMLBox"\n\t},\n\t{\n\t\ttype: "bxml",\n\t\tname: "BinaryXMLBox"\n\t},\n\t{\n\t\ttype: "ipro",\n\t\tname: "ItemProtectionBox"\n\t},\n\t{\n\t\ttype: "mere",\n\t\tname: "MetaboxRelationBox"\n\t}],\n\tCONTAINER_BOXES: [[{\n\t\ttype: "moov",\n\t\tname: "CompressedMovieBox"\n\t},\n\t["trak", "pssh"]], [{\n\t\ttype: "trak",\n\t\tname: "TrackBox"\n\t}], [{\n\t\ttype: "edts",\n\t\tname: "EditBox"\n\t}], [{\n\t\ttype: "mdia",\n\t\tname: "MediaBox"\n\t}], [{\n\t\ttype: "minf",\n\t\tname: "MediaInformationBox"\n\t}], [{\n\t\ttype: "dinf",\n\t\tname: "DataInformationBox"\n\t}], [{\n\t\ttype: "stbl",\n\t\tname: "SampleTableBox"\n\t},\n\t["sgpd", "sbgp"]], [{\n\t\ttype: "mvex",\n\t\tname: "MovieExtendsBox"\n\t},\n\t["trex"]], [{\n\t\ttype: "moof",\n\t\tname: "CompressedMovieFragmentBox"\n\t},\n\t["traf"]], [{\n\t\ttype: "traf",\n\t\tname: "TrackFragmentBox"\n\t},\n\t["trun", "sgpd", "sbgp"]], [{\n\t\ttype: "vttc",\n\t\tname: "VTTCueBox"\n\t}], [{\n\t\ttype: "tref",\n\t\tname: "TrackReferenceBox"\n\t}], [{\n\t\ttype: "iref",\n\t\tname: "ItemReferenceBox"\n\t}], [{\n\t\ttype: "mfra",\n\t\tname: "MovieFragmentRandomAccessBox"\n\t},\n\t["tfra"]], [{\n\t\ttype: "meco",\n\t\tname: "AdditionalMetadataContainerBox"\n\t}], [{\n\t\ttype: "hnti",\n\t\tname: "trackhintinformation"\n\t}], [{\n\t\ttype: "hinf",\n\t\tname: "hintstatisticsbox"\n\t}], [{\n\t\ttype: "strk",\n\t\tname: "SubTrackBox"\n\t}], [{\n\t\ttype: "strd",\n\t\tname: "SubTrackDefinitionBox"\n\t}], [{\n\t\ttype: "sinf",\n\t\tname: "ProtectionSchemeInfoBox"\n\t}], [{\n\t\ttype: "rinf",\n\t\tname: "RestrictedSchemeInfoBox"\n\t}], [{\n\t\ttype: "schi",\n\t\tname: "SchemeInformationBox"\n\t}], [{\n\t\ttype: "trgr",\n\t\tname: "TrackGroupBox"\n\t}], [{\n\t\ttype: "udta",\n\t\tname: "UserDataBox"\n\t},\n\t["kind"]], [{\n\t\ttype: "iprp",\n\t\tname: "ItemPropertiesBox"\n\t},\n\t["ipma"]], [{\n\t\ttype: "ipco",\n\t\tname: "ItemPropertyContainerBox"\n\t}], [{\n\t\ttype: "grpl",\n\t\tname: "GroupsListBox"\n\t}], [{\n\t\ttype: "j2kH",\n\t\tname: "J2KHeaderInfoBox"\n\t}], [{\n\t\ttype: "etyp",\n\t\tname: "ExtendedTypeBox"\n\t},\n\t["tyco"]]],\n\tboxCodes: [],\n\tfullBoxCodes: [],\n\tcontainerBoxCodes: [],\n\tsampleEntryCodes: {},\n\tsampleGroupEntryCodes: [],\n\ttrackGroupTypes: [],\n\tUUIDBoxes: {},\n\tUUIDs: [],\n\tinitialize: function() {\n\t\tBoxParser.FullBox.prototype = new BoxParser.Box,\n\t\tBoxParser.ContainerBox.prototype = new BoxParser.Box,\n\t\tBoxParser.SampleEntry.prototype = new BoxParser.Box,\n\t\tBoxParser.TrackGroupTypeBox.prototype = new BoxParser.FullBox,\n\t\tBoxParser.BASIC_BOXES.forEach(function(t) {\n\t\t\tBoxParser.createBoxCtor(t.type, t.name)\n\t\t}),\n\t\tBoxParser.FULL_BOXES.forEach(function(t) {\n\t\t\tBoxParser.createFullBoxCtor(t.type, t.name)\n\t\t}),\n\t\tBoxParser.CONTAINER_BOXES.forEach(function(t) {\n\t\t\tBoxParser.createContainerBoxCtor(t[0].type, t[0].name, null, t[1])\n\t\t})\n\t},\n\tBox: function(t, e, i, r) {\n\t\tthis.type = t,\n\t\tthis.box_name = i,\n\t\tthis.size = e,\n\t\tthis.uuid = r\n\t},\n\tFullBox: function(t, e, i, r) {\n\t\tBoxParser.Box.call(this, t, e, i, r),\n\t\tthis.flags = 0,\n\t\tthis.version = 0\n\t},\n\tContainerBox: function(t, e, i, r) {\n\t\tBoxParser.Box.call(this, t, e, i, r),\n\t\tthis.boxes = []\n\t},\n\tSampleEntry: function(t, e, i, r) {\n\t\tBoxParser.ContainerBox.call(this, t, e),\n\t\tthis.hdr_size = i,\n\t\tthis.start = r\n\t},\n\tSampleGroupEntry: function(t) {\n\t\tthis.grouping_type = t\n\t},\n\tTrackGroupTypeBox: function(t, e) {\n\t\tBoxParser.FullBox.call(this, t, e)\n\t},\n\tcreateBoxCtor: function(e, i, t) {\n\t\tBoxParser.boxCodes.push(e),\n\t\tBoxParser[e + "Box"] = function(t) {\n\t\t\tBoxParser.Box.call(this, e, t, i)\n\t\t},\n\t\tBoxParser[e + "Box"].prototype = new BoxParser.Box,\n\t\tt && (BoxParser[e + "Box"].prototype.parse = t)\n\t},\n\tcreateFullBoxCtor: function(e, i, r) {\n\t\tBoxParser[e + "Box"] = function(t) {\n\t\t\tBoxParser.FullBox.call(this, e, t, i)\n\t\t},\n\t\tBoxParser[e + "Box"].prototype = new BoxParser.FullBox,\n\t\tBoxParser[e + "Box"].prototype.parse = function(t) {\n\t\t\tthis.parseFullHeader(t),\n\t\t\tr && r.call(this, t)\n\t\t}\n\t},\n\taddSubBoxArrays: function(t) {\n\t\tif (t) for (var e = (this.subBoxNames = t).length, i = 0; i < e; i++) this[t[i] + "s"] = []\n\t},\n\tcreateContainerBoxCtor: function(e, i, t, r) {\n\t\tBoxParser[e + "Box"] = function(t) {\n\t\t\tBoxParser.ContainerBox.call(this, e, t, i),\n\t\t\tBoxParser.addSubBoxArrays.call(this, r)\n\t\t},\n\t\tBoxParser[e + "Box"].prototype = new BoxParser.ContainerBox,\n\t\tt && (BoxParser[e + "Box"].prototype.parse = t)\n\t},\n\tcreateMediaSampleEntryCtor: function(t, e, i) {\n\t\tBoxParser.sampleEntryCodes[t] = [],\n\t\tBoxParser[t + "SampleEntry"] = function(t, e) {\n\t\t\tBoxParser.SampleEntry.call(this, t, e),\n\t\t\tBoxParser.addSubBoxArrays.call(this, i)\n\t\t},\n\t\tBoxParser[t + "SampleEntry"].prototype = new BoxParser.SampleEntry,\n\t\te && (BoxParser[t + "SampleEntry"].prototype.parse = e)\n\t},\n\tcreateSampleEntryCtor: function(e, i, t, r) {\n\t\tBoxParser.sampleEntryCodes[e].push(i),\n\t\tBoxParser[i + "SampleEntry"] = function(t) {\n\t\t\tBoxParser[e + "SampleEntry"].call(this, i, t),\n\t\t\tBoxParser.addSubBoxArrays.call(this, r)\n\t\t},\n\t\tBoxParser[i + "SampleEntry"].prototype = new BoxParser[e + "SampleEntry"],\n\t\tt && (BoxParser[i + "SampleEntry"].prototype.parse = t)\n\t},\n\tcreateEncryptedSampleEntryCtor: function(t, e, i) {\n\t\tBoxParser.createSampleEntryCtor.call(this, t, e, i, ["sinf"])\n\t},\n\tcreateSampleGroupCtor: function(e, t) {\n\t\tBoxParser[e + "SampleGroupEntry"] = function(t) {\n\t\t\tBoxParser.SampleGroupEntry.call(this, e, t)\n\t\t},\n\t\tBoxParser[e + "SampleGroupEntry"].prototype = new BoxParser.SampleGroupEntry,\n\t\tt && (BoxParser[e + "SampleGroupEntry"].prototype.parse = t)\n\t},\n\tcreateTrackGroupCtor: function(e, t) {\n\t\tBoxParser[e + "TrackGroupTypeBox"] = function(t) {\n\t\t\tBoxParser.TrackGroupTypeBox.call(this, e, t)\n\t\t},\n\t\tBoxParser[e + "TrackGroupTypeBox"].prototype = new BoxParser.TrackGroupTypeBox,\n\t\tt && (BoxParser[e + "TrackGroupTypeBox"].prototype.parse = t)\n\t},\n\tcreateUUIDBox: function(e, i, r, s, a) {\n\t\tBoxParser.UUIDs.push(e),\n\t\tBoxParser.UUIDBoxes[e] = function(t) { (r ? BoxParser.FullBox: s ? BoxParser.ContainerBox: BoxParser.Box).call(this, "uuid", t, i, e)\n\t\t},\n\t\tBoxParser.UUIDBoxes[e].prototype = new(r ? BoxParser.FullBox: s ? BoxParser.ContainerBox: BoxParser.Box),\n\t\ta && (BoxParser.UUIDBoxes[e].prototype.parse = r ?\n\t\tfunction(t) {\n\t\t\tthis.parseFullHeader(t),\n\t\t\ta && a.call(this, t)\n\t\t}: a)\n\t}\n};\nfunction printPS(t) {\n\tvar e = "<table class=\'inner-table\'>";\n\te += "<thead><tr><th>length</th><th>nalu_data</th></tr></thead>",\n\te += "<tbody>";\n\tfor (var i = 0; i < t.length; i++) {\n\t\tvar r = t[i];\n\t\te += "<tr>",\n\t\te += "<td>" + r.length + "</td>",\n\t\te += "<td>",\n\t\te += r.nalu.reduce(function(t, e) {\n\t\t\treturn t + e.toString(16).padStart(2, "0")\n\t\t},\n\t\t"0x"),\n\t\te += "</td></tr>"\n\t}\n\treturn e += "</tbody></table>"\n}\nfunction ColorPoint(t, e) {\n\tthis.x = t,\n\tthis.y = e\n}\nfunction Pixel(t, e) {\n\tthis.bad_pixel_row = t,\n\tthis.bad_pixel_column = e\n}\nBoxParser.initialize(),\nBoxParser.TKHD_FLAG_ENABLED = 1,\nBoxParser.TKHD_FLAG_IN_MOVIE = 2,\nBoxParser.TKHD_FLAG_IN_PREVIEW = 4,\nBoxParser.TFHD_FLAG_BASE_DATA_OFFSET = 1,\nBoxParser.TFHD_FLAG_SAMPLE_DESC = 2,\nBoxParser.TFHD_FLAG_SAMPLE_DUR = 8,\nBoxParser.TFHD_FLAG_SAMPLE_SIZE = 16,\nBoxParser.TFHD_FLAG_SAMPLE_FLAGS = 32,\nBoxParser.TFHD_FLAG_DUR_EMPTY = 65536,\nBoxParser.TFHD_FLAG_DEFAULT_BASE_IS_MOOF = 131072,\nBoxParser.TRUN_FLAGS_DATA_OFFSET = 1,\nBoxParser.TRUN_FLAGS_FIRST_FLAG = 4,\nBoxParser.TRUN_FLAGS_DURATION = 256,\nBoxParser.TRUN_FLAGS_SIZE = 512,\nBoxParser.TRUN_FLAGS_FLAGS = 1024,\nBoxParser.TRUN_FLAGS_CTS_OFFSET = 2048,\nBoxParser.Box.prototype.add = function(t) {\n\treturn this.addBox(new BoxParser[t + "Box"])\n},\nBoxParser.Box.prototype.addBox = function(t) {\n\treturn this.boxes.push(t),\n\tthis[t.type + "s"] ? this[t.type + "s"].push(t) : this[t.type] = t,\n\tt\n},\nBoxParser.Box.prototype.set = function(t, e) {\n\treturn this[t] = e,\n\tthis\n},\nBoxParser.Box.prototype.addEntry = function(t, e) {\n\te = e || "entries";\n\treturn this[e] || (this[e] = []),\n\tthis[e].push(t),\n\tthis\n},\n"undefined" != typeof exports && (exports.BoxParser = BoxParser),\nBoxParser.parseUUID = function(t) {\n\treturn BoxParser.parseHex16(t)\n},\nBoxParser.parseHex16 = function(t) {\n\tfor (var e = "",\n\ti = 0; i < 16; i++) {\n\t\tvar r = t.readUint8().toString(16);\n\t\te += 1 === r.length ? "0" + r: r\n\t}\n\treturn e\n},\nBoxParser.parseOneBox = function(t, e, i) {\n\tvar r, s, a = t.getPosition(),\n\tn = 0;\n\tif (t.getEndPosition() - a < 8) return Log.debug("BoxParser", "Not enough data in stream to parse the type and size of the box"),\n\t{\n\t\tcode: BoxParser.ERR_NOT_ENOUGH_DATA\n\t};\n\tif (i && i < 8) return Log.debug("BoxParser", "Not enough bytes left in the parent box to parse a new box"),\n\t{\n\t\tcode: BoxParser.ERR_NOT_ENOUGH_DATA\n\t};\n\tvar o = t.readUint32(),\n\th = t.readString(4),\n\td = h;\n\tif (Log.debug("BoxParser", "Found box of type \'" + h + "\' and size " + o + " at position " + a), n = 8, "uuid" == h) {\n\t\tif (t.getEndPosition() - t.getPosition() < 16 || i - n < 16) return t.seek(a),\n\t\tLog.debug("BoxParser", "Not enough bytes left in the parent box to parse a UUID box"),\n\t\t{\n\t\t\tcode: BoxParser.ERR_NOT_ENOUGH_DATA\n\t\t};\n\t\tn += 16,\n\t\td = s = BoxParser.parseUUID(t)\n\t}\n\tif (1 == o) {\n\t\tif (t.getEndPosition() - t.getPosition() < 8 || i && i - n < 8) return t.seek(a),\n\t\tLog.warn("BoxParser", \'Not enough data in stream to parse the extended size of the "\' + h + \'" box\'),\n\t\t{\n\t\t\tcode: BoxParser.ERR_NOT_ENOUGH_DATA\n\t\t};\n\t\to = t.readUint64(),\n\t\tn += 8\n\t} else if (0 === o) if (i) o = i;\n\telse if ("mdat" !== h) return Log.error("BoxParser", "Unlimited box size not supported for type: \'" + h + "\'"),\n\tr = new BoxParser.Box(h, o),\n\t{\n\t\tcode: BoxParser.OK,\n\t\tbox: r,\n\t\tsize: r.size\n\t};\n\treturn 0 !== o && o < n ? (Log.error("BoxParser", "Box of type " + h + " has an invalid size " + o + " (too small to be a box)"), {\n\t\tcode: BoxParser.ERR_NOT_ENOUGH_DATA,\n\t\ttype: h,\n\t\tsize: o,\n\t\thdr_size: n,\n\t\tstart: a\n\t}) : 0 !== o && i && i < o ? (Log.error("BoxParser", "Box of type \'" + h + "\' has a size " + o + " greater than its container size " + i), {\n\t\tcode: BoxParser.ERR_NOT_ENOUGH_DATA,\n\t\ttype: h,\n\t\tsize: o,\n\t\thdr_size: n,\n\t\tstart: a\n\t}) : 0 !== o && a + o > t.getEndPosition() ? (t.seek(a), Log.info("BoxParser", "Not enough data in stream to parse the entire \'" + h + "\' box"), {\n\t\tcode: BoxParser.ERR_NOT_ENOUGH_DATA,\n\t\ttype: h,\n\t\tsize: o,\n\t\thdr_size: n,\n\t\tstart: a\n\t}) : e ? {\n\t\tcode: BoxParser.OK,\n\t\ttype: h,\n\t\tsize: o,\n\t\thdr_size: n,\n\t\tstart: a\n\t}: (BoxParser[h + "Box"] ? r = new BoxParser[h + "Box"](o) : "uuid" !== h ? (Log.warn("BoxParser", "Unknown box type: \'" + h + "\'"), (r = new BoxParser.Box(h, o)).has_unparsed_data = !0) : BoxParser.UUIDBoxes[s] ? r = new BoxParser.UUIDBoxes[s](o) : (Log.warn("BoxParser", "Unknown uuid type: \'" + s + "\'"), (r = new BoxParser.Box(h, o)).uuid = s, r.has_unparsed_data = !0), r.hdr_size = n, r.start = a, r.write === BoxParser.Box.prototype.write && "mdat" !== r.type && (Log.info("BoxParser", "\'" + d + "\' box writing not yet implemented, keeping unparsed data in memory for later write"), r.parseDataAndRewind(t)), r.parse(t), (a = t.getPosition() - (r.start + r.size)) < 0 ? (Log.warn("BoxParser", "Parsing of box \'" + d + "\' did not read the entire indicated box data size (missing " + -a + " bytes), seeking forward"), t.seek(r.start + r.size)) : 0 < a && (Log.error("BoxParser", "Parsing of box \'" + d + "\' read " + a + " more bytes than the indicated box data size, seeking backwards"), 0 !== r.size && t.seek(r.start + r.size)), {\n\t\tcode: BoxParser.OK,\n\t\tbox: r,\n\t\tsize: r.size\n\t})\n},\nBoxParser.Box.prototype.parse = function(t) {\n\t"mdat" != this.type ? this.data = t.readUint8Array(this.size - this.hdr_size) : 0 === this.size ? t.seek(t.getEndPosition()) : t.seek(this.start + this.size)\n},\nBoxParser.Box.prototype.parseDataAndRewind = function(t) {\n\tthis.data = t.readUint8Array(this.size - this.hdr_size),\n\tt.position -= this.size - this.hdr_size\n},\nBoxParser.FullBox.prototype.parseDataAndRewind = function(t) {\n\tthis.parseFullHeader(t),\n\tthis.data = t.readUint8Array(this.size - this.hdr_size),\n\tthis.hdr_size -= 4,\n\tt.position -= this.size - this.hdr_size\n},\nBoxParser.FullBox.prototype.parseFullHeader = function(t) {\n\tthis.version = t.readUint8(),\n\tthis.flags = t.readUint24(),\n\tthis.hdr_size += 4\n},\nBoxParser.FullBox.prototype.parse = function(t) {\n\tthis.parseFullHeader(t),\n\tthis.data = t.readUint8Array(this.size - this.hdr_size)\n},\nBoxParser.ContainerBox.prototype.parse = function(t) {\n\tfor (; t.getPosition() < this.start + this.size;) {\n\t\tif ((e = BoxParser.parseOneBox(t, !1, this.size - (t.getPosition() - this.start))).code !== BoxParser.OK) return;\n\t\tvar e, i = e.box;\n\t\tthis.boxes.push(i),\n\t\tthis.subBoxNames && -1 != this.subBoxNames.indexOf(i.type) ? this[this.subBoxNames[this.subBoxNames.indexOf(i.type)] + "s"].push(i) : this[e = "uuid" !== i.type ? i.type: i.uuid] ? Log.warn("Box of type " + e + " already stored in field of this type") : this[e] = i\n\t}\n},\nBoxParser.Box.prototype.parseLanguage = function(t) {\n\tthis.language = t.readUint16();\n\tt = [];\n\tt[0] = this.language >> 10 & 31,\n\tt[1] = this.language >> 5 & 31,\n\tt[2] = 31 & this.language,\n\tthis.languageString = String.fromCharCode(t[0] + 96, t[1] + 96, t[2] + 96)\n},\nBoxParser.SAMPLE_ENTRY_TYPE_VISUAL = "Visual",\nBoxParser.SAMPLE_ENTRY_TYPE_AUDIO = "Audio",\nBoxParser.SAMPLE_ENTRY_TYPE_HINT = "Hint",\nBoxParser.SAMPLE_ENTRY_TYPE_METADATA = "Metadata",\nBoxParser.SAMPLE_ENTRY_TYPE_SUBTITLE = "Subtitle",\nBoxParser.SAMPLE_ENTRY_TYPE_SYSTEM = "System",\nBoxParser.SAMPLE_ENTRY_TYPE_TEXT = "Text",\nBoxParser.SampleEntry.prototype.parseHeader = function(t) {\n\tt.readUint8Array(6),\n\tthis.data_reference_index = t.readUint16(),\n\tthis.hdr_size += 8\n},\nBoxParser.SampleEntry.prototype.parse = function(t) {\n\tthis.parseHeader(t),\n\tthis.data = t.readUint8Array(this.size - this.hdr_size)\n},\nBoxParser.SampleEntry.prototype.parseDataAndRewind = function(t) {\n\tthis.parseHeader(t),\n\tthis.data = t.readUint8Array(this.size - this.hdr_size),\n\tthis.hdr_size -= 8,\n\tt.position -= this.size - this.hdr_size\n},\nBoxParser.SampleEntry.prototype.parseFooter = function(t) {\n\tBoxParser.ContainerBox.prototype.parse.call(this, t)\n},\nBoxParser.createMediaSampleEntryCtor(BoxParser.SAMPLE_ENTRY_TYPE_HINT),\nBoxParser.createMediaSampleEntryCtor(BoxParser.SAMPLE_ENTRY_TYPE_METADATA),\nBoxParser.createMediaSampleEntryCtor(BoxParser.SAMPLE_ENTRY_TYPE_SUBTITLE),\nBoxParser.createMediaSampleEntryCtor(BoxParser.SAMPLE_ENTRY_TYPE_SYSTEM),\nBoxParser.createMediaSampleEntryCtor(BoxParser.SAMPLE_ENTRY_TYPE_TEXT),\nBoxParser.createMediaSampleEntryCtor(BoxParser.SAMPLE_ENTRY_TYPE_VISUAL,\nfunction(t) {\n\tvar e;\n\tthis.parseHeader(t),\n\tt.readUint16(),\n\tt.readUint16(),\n\tt.readUint32Array(3),\n\tthis.width = t.readUint16(),\n\tthis.height = t.readUint16(),\n\tthis.horizresolution = t.readUint32(),\n\tthis.vertresolution = t.readUint32(),\n\tt.readUint32(),\n\tthis.frame_count = t.readUint16(),\n\te = Math.min(31, t.readUint8()),\n\tthis.compressorname = t.readString(e),\n\te < 31 && t.readString(31 - e),\n\tthis.depth = t.readUint16(),\n\tt.readUint16(),\n\tthis.parseFooter(t)\n}),\nBoxParser.createMediaSampleEntryCtor(BoxParser.SAMPLE_ENTRY_TYPE_AUDIO,\nfunction(t) {\n\tthis.parseHeader(t),\n\tt.readUint32Array(2),\n\tthis.channel_count = t.readUint16(),\n\tthis.samplesize = t.readUint16(),\n\tt.readUint16(),\n\tt.readUint16(),\n\tthis.samplerate = t.readUint32() / 65536,\n\tthis.parseFooter(t)\n}),\nBoxParser.createSampleEntryCtor(BoxParser.SAMPLE_ENTRY_TYPE_VISUAL, "avc1"),\nBoxParser.createSampleEntryCtor(BoxParser.SAMPLE_ENTRY_TYPE_VISUAL, "avc2"),\nBoxParser.createSampleEntryCtor(BoxParser.SAMPLE_ENTRY_TYPE_VISUAL, "avc3"),\nBoxParser.createSampleEntryCtor(BoxParser.SAMPLE_ENTRY_TYPE_VISUAL, "avc4"),\nBoxParser.createSampleEntryCtor(BoxParser.SAMPLE_ENTRY_TYPE_VISUAL, "av01"),\nBoxParser.createSampleEntryCtor(BoxParser.SAMPLE_ENTRY_TYPE_VISUAL, "dav1"),\nBoxParser.createSampleEntryCtor(BoxParser.SAMPLE_ENTRY_TYPE_VISUAL, "hvc1"),\nBoxParser.createSampleEntryCtor(BoxParser.SAMPLE_ENTRY_TYPE_VISUAL, "hev1"),\nBoxParser.createSampleEntryCtor(BoxParser.SAMPLE_ENTRY_TYPE_VISUAL, "hvt1"),\nBoxParser.createSampleEntryCtor(BoxParser.SAMPLE_ENTRY_TYPE_VISUAL, "lhe1"),\nBoxParser.createSampleEntryCtor(BoxParser.SAMPLE_ENTRY_TYPE_VISUAL, "dvh1"),\nBoxParser.createSampleEntryCtor(BoxParser.SAMPLE_ENTRY_TYPE_VISUAL, "dvhe"),\nBoxParser.createSampleEntryCtor(BoxParser.SAMPLE_ENTRY_TYPE_VISUAL, "vvc1"),\nBoxParser.createSampleEntryCtor(BoxParser.SAMPLE_ENTRY_TYPE_VISUAL, "vvi1"),\nBoxParser.createSampleEntryCtor(BoxParser.SAMPLE_ENTRY_TYPE_VISUAL, "vvs1"),\nBoxParser.createSampleEntryCtor(BoxParser.SAMPLE_ENTRY_TYPE_VISUAL, "vvcN"),\nBoxParser.createSampleEntryCtor(BoxParser.SAMPLE_ENTRY_TYPE_VISUAL, "vp08"),\nBoxParser.createSampleEntryCtor(BoxParser.SAMPLE_ENTRY_TYPE_VISUAL, "vp09"),\nBoxParser.createSampleEntryCtor(BoxParser.SAMPLE_ENTRY_TYPE_VISUAL, "avs3"),\nBoxParser.createSampleEntryCtor(BoxParser.SAMPLE_ENTRY_TYPE_VISUAL, "j2ki"),\nBoxParser.createSampleEntryCtor(BoxParser.SAMPLE_ENTRY_TYPE_VISUAL, "mjp2"),\nBoxParser.createSampleEntryCtor(BoxParser.SAMPLE_ENTRY_TYPE_VISUAL, "mjpg"),\nBoxParser.createSampleEntryCtor(BoxParser.SAMPLE_ENTRY_TYPE_VISUAL, "uncv"),\nBoxParser.createSampleEntryCtor(BoxParser.SAMPLE_ENTRY_TYPE_AUDIO, "mp4a"),\nBoxParser.createSampleEntryCtor(BoxParser.SAMPLE_ENTRY_TYPE_AUDIO, "ac-3"),\nBoxParser.createSampleEntryCtor(BoxParser.SAMPLE_ENTRY_TYPE_AUDIO, "ac-4"),\nBoxParser.createSampleEntryCtor(BoxParser.SAMPLE_ENTRY_TYPE_AUDIO, "ec-3"),\nBoxParser.createSampleEntryCtor(BoxParser.SAMPLE_ENTRY_TYPE_AUDIO, "Opus"),\nBoxParser.createSampleEntryCtor(BoxParser.SAMPLE_ENTRY_TYPE_AUDIO, "mha1"),\nBoxParser.createSampleEntryCtor(BoxParser.SAMPLE_ENTRY_TYPE_AUDIO, "mha2"),\nBoxParser.createSampleEntryCtor(BoxParser.SAMPLE_ENTRY_TYPE_AUDIO, "mhm1"),\nBoxParser.createSampleEntryCtor(BoxParser.SAMPLE_ENTRY_TYPE_AUDIO, "mhm2"),\nBoxParser.createSampleEntryCtor(BoxParser.SAMPLE_ENTRY_TYPE_AUDIO, "fLaC"),\nBoxParser.createEncryptedSampleEntryCtor(BoxParser.SAMPLE_ENTRY_TYPE_VISUAL, "encv"),\nBoxParser.createEncryptedSampleEntryCtor(BoxParser.SAMPLE_ENTRY_TYPE_AUDIO, "enca"),\nBoxParser.createEncryptedSampleEntryCtor(BoxParser.SAMPLE_ENTRY_TYPE_SUBTITLE, "encu"),\nBoxParser.createEncryptedSampleEntryCtor(BoxParser.SAMPLE_ENTRY_TYPE_SYSTEM, "encs"),\nBoxParser.createEncryptedSampleEntryCtor(BoxParser.SAMPLE_ENTRY_TYPE_TEXT, "enct"),\nBoxParser.createEncryptedSampleEntryCtor(BoxParser.SAMPLE_ENTRY_TYPE_METADATA, "encm"),\nBoxParser.createBoxCtor("a1lx", "AV1LayeredImageIndexingProperty",\nfunction(t) {\n\tvar e = 16 * (1 + (1 & (1 & t.readUint8())));\n\tthis.layer_size = [];\n\tfor (var i = 0; i < 3; i++) this.layer_size[i] = 16 == e ? t.readUint16() : t.readUint32()\n}),\nBoxParser.createBoxCtor("a1op", "OperatingPointSelectorProperty",\nfunction(t) {\n\tthis.op_index = t.readUint8()\n}),\nBoxParser.createFullBoxCtor("auxC", "AuxiliaryTypeProperty",\nfunction(t) {\n\tthis.aux_type = t.readCString();\n\tvar e = this.size - this.hdr_size - (this.aux_type.length + 1);\n\tthis.aux_subtype = t.readUint8Array(e)\n}),\nBoxParser.createBoxCtor("av1C", "AV1CodecConfigurationBox",\nfunction(t) {\n\tvar e = t.readUint8();\n\tif (1 == (e >> 7 & 1)) if (this.version = 127 & e, 1 === this.version) if (e = t.readUint8(), this.seq_profile = e >> 5 & 7, this.seq_level_idx_0 = 31 & e, e = t.readUint8(), this.seq_tier_0 = e >> 7 & 1, this.high_bitdepth = e >> 6 & 1, this.twelve_bit = e >> 5 & 1, this.monochrome = e >> 4 & 1, this.chroma_subsampling_x = e >> 3 & 1, this.chroma_subsampling_y = e >> 2 & 1, this.chroma_sample_position = 3 & e, e = t.readUint8(), this.reserved_1 = e >> 5 & 7, 0 === this.reserved_1) {\n\t\tif (this.initial_presentation_delay_present = e >> 4 & 1, 1 === this.initial_presentation_delay_present) this.initial_presentation_delay_minus_one = 15 & e;\n\t\telse if (this.reserved_2 = 15 & e, 0 !== this.reserved_2) return void Log.error("av1C reserved_2 parsing problem");\n\t\te = this.size - this.hdr_size - 4;\n\t\tthis.configOBUs = t.readUint8Array(e)\n\t} else Log.error("av1C reserved_1 parsing problem");\n\telse Log.error("av1C version " + this.version + " not supported");\n\telse Log.error("av1C marker problem")\n}),\nBoxParser.createBoxCtor("avcC", "AVCConfigurationBox",\nfunction(t) {\n\tvar e, i;\n\tfor (this.configurationVersion = t.readUint8(), this.AVCProfileIndication = t.readUint8(), this.profile_compatibility = t.readUint8(), this.AVCLevelIndication = t.readUint8(), this.lengthSizeMinusOne = 3 & t.readUint8(), this.nb_SPS_nalus = 31 & t.readUint8(), i = this.size - this.hdr_size - 6, this.SPS = [], this.SPS.toString = function() {\n\t\treturn printPS(this)\n\t},\n\te = 0; e < this.nb_SPS_nalus; e++) this.SPS[e] = {},\n\tthis.SPS[e].length = t.readUint16(),\n\tthis.SPS[e].nalu = t.readUint8Array(this.SPS[e].length),\n\ti -= 2 + this.SPS[e].length;\n\tfor (this.nb_PPS_nalus = t.readUint8(), i--, this.PPS = [], this.PPS.toString = function() {\n\t\treturn printPS(this)\n\t},\n\te = 0; e < this.nb_PPS_nalus; e++) this.PPS[e] = {},\n\tthis.PPS[e].length = t.readUint16(),\n\tthis.PPS[e].nalu = t.readUint8Array(this.PPS[e].length),\n\ti -= 2 + this.PPS[e].length;\n\t0 < i && (this.ext = t.readUint8Array(i))\n}),\nBoxParser.createBoxCtor("btrt", "BitRateBox",\nfunction(t) {\n\tthis.bufferSizeDB = t.readUint32(),\n\tthis.maxBitrate = t.readUint32(),\n\tthis.avgBitrate = t.readUint32()\n}),\nBoxParser.createFullBoxCtor("ccst", "CodingConstraintsBox",\nfunction(t) {\n\tvar e = t.readUint8();\n\tthis.all_ref_pics_intra = 128 == (128 & e),\n\tthis.intra_pred_used = 64 == (64 & e),\n\tthis.max_ref_per_pic = (63 & e) >> 2,\n\tt.readUint24()\n}),\nBoxParser.createBoxCtor("cdef", "ComponentDefinitionBox",\nfunction(t) {\n\tvar e;\n\tfor (this.channel_count = t.readUint16(), this.channel_indexes = [], this.channel_types = [], this.channel_associations = [], e = 0; e < this.channel_count; e++) this.channel_indexes.push(t.readUint16()),\n\tthis.channel_types.push(t.readUint16()),\n\tthis.channel_associations.push(t.readUint16())\n}),\nBoxParser.createBoxCtor("clap", "CleanApertureBox",\nfunction(t) {\n\tthis.cleanApertureWidthN = t.readUint32(),\n\tthis.cleanApertureWidthD = t.readUint32(),\n\tthis.cleanApertureHeightN = t.readUint32(),\n\tthis.cleanApertureHeightD = t.readUint32(),\n\tthis.horizOffN = t.readUint32(),\n\tthis.horizOffD = t.readUint32(),\n\tthis.vertOffN = t.readUint32(),\n\tthis.vertOffD = t.readUint32()\n}),\nBoxParser.createBoxCtor("clli", "ContentLightLevelBox",\nfunction(t) {\n\tthis.max_content_light_level = t.readUint16(),\n\tthis.max_pic_average_light_level = t.readUint16()\n}),\nBoxParser.createFullBoxCtor("cmex", "CameraExtrinsicMatrixProperty",\nfunction(t) {\n\t1 & this.flags && (this.pos_x = t.readInt32()),\n\t2 & this.flags && (this.pos_y = t.readInt32()),\n\t4 & this.flags && (this.pos_z = t.readInt32()),\n\t8 & this.flags && (0 == this.version ? 16 & this.flags ? (this.quat_x = t.readInt32(), this.quat_y = t.readInt32(), this.quat_z = t.readInt32()) : (this.quat_x = t.readInt16(), this.quat_y = t.readInt16(), this.quat_z = t.readInt16()) : this.version),\n\t32 & this.flags && (this.id = t.readUint32())\n}),\nBoxParser.createFullBoxCtor("cmin", "CameraIntrinsicMatrixProperty",\nfunction(t) {\n\tthis.focal_length_x = t.readInt32(),\n\tthis.principal_point_x = t.readInt32(),\n\tthis.principal_point_y = t.readInt32(),\n\t1 & this.flags && (this.focal_length_y = t.readInt32(), this.skew_factor = t.readInt32())\n}),\nBoxParser.createBoxCtor("cmpd", "ComponentDefinitionBox",\nfunction(t) {\n\tfor (this.component_count = t.readUint32(), this.component_types = [], this.component_type_urls = [], i = 0; i < this.component_count; i++) {\n\t\tvar e = t.readUint16();\n\t\tthis.component_types.push(e),\n\t\t32768 <= e && this.component_type_urls.push(t.readCString())\n\t}\n}),\nBoxParser.createFullBoxCtor("co64", "ChunkLargeOffsetBox",\nfunction(t) {\n\tvar e, i = t.readUint32();\n\tif (this.chunk_offsets = [], 0 === this.version) for (e = 0; e < i; e++) this.chunk_offsets.push(t.readUint64())\n}),\nBoxParser.createFullBoxCtor("CoLL", "ContentLightLevelBox",\nfunction(t) {\n\tthis.maxCLL = t.readUint16(),\n\tthis.maxFALL = t.readUint16()\n}),\nBoxParser.createBoxCtor("colr", "ColourInformationBox",\nfunction(t) {\n\tvar e;\n\tthis.colour_type = t.readString(4),\n\t"nclx" === this.colour_type ? (this.colour_primaries = t.readUint16(), this.transfer_characteristics = t.readUint16(), this.matrix_coefficients = t.readUint16(), e = t.readUint8(), this.full_range_flag = e >> 7) : "rICC" !== this.colour_type && "prof" !== this.colour_type || (this.ICC_profile = t.readUint8Array(this.size - 4))\n}),\nBoxParser.createFullBoxCtor("cprt", "CopyrightBox",\nfunction(t) {\n\tthis.parseLanguage(t),\n\tthis.notice = t.readCString()\n}),\nBoxParser.createFullBoxCtor("cslg", "CompositionToDecodeBox",\nfunction(t) {\n\t0 === this.version && (this.compositionToDTSShift = t.readInt32(), this.leastDecodeToDisplayDelta = t.readInt32(), this.greatestDecodeToDisplayDelta = t.readInt32(), this.compositionStartTime = t.readInt32(), this.compositionEndTime = t.readInt32())\n}),\nBoxParser.createFullBoxCtor("ctts", "CompositionOffsetBox",\nfunction(t) {\n\tvar e, i = t.readUint32();\n\tif (this.sample_counts = [], this.sample_offsets = [], 0 === this.version) for (e = 0; e < i; e++) {\n\t\tthis.sample_counts.push(t.readUint32());\n\t\tvar r = t.readInt32();\n\t\tr < 0 && Log.warn("BoxParser", "ctts box uses negative values without using version 1"),\n\t\tthis.sample_offsets.push(r)\n\t} else if (1 == this.version) for (e = 0; e < i; e++) this.sample_counts.push(t.readUint32()),\n\tthis.sample_offsets.push(t.readInt32())\n}),\nBoxParser.createBoxCtor("dac3", "AC3SpecificBox",\nfunction(t) {\n\tvar e = t.readUint8(),\n\ti = t.readUint8(),\n\tt = t.readUint8();\n\tthis.fscod = e >> 6,\n\tthis.bsid = e >> 1 & 31,\n\tthis.bsmod = (1 & e) << 2 | i >> 6 & 3,\n\tthis.acmod = i >> 3 & 7,\n\tthis.lfeon = i >> 2 & 1,\n\tthis.bit_rate_code = 3 & i | t >> 5 & 7\n}),\nBoxParser.createBoxCtor("dec3", "EC3SpecificBox",\nfunction(t) {\n\tvar e = t.readUint16();\n\tthis.data_rate = e >> 3,\n\tthis.num_ind_sub = 7 & e,\n\tthis.ind_subs = [];\n\tfor (var i = 0; i < this.num_ind_sub + 1; i++) {\n\t\tvar r = {};\n\t\tthis.ind_subs.push(r);\n\t\tvar s = t.readUint8(),\n\t\ta = t.readUint8(),\n\t\tn = t.readUint8();\n\t\tr.fscod = s >> 6,\n\t\tr.bsid = s >> 1 & 31,\n\t\tr.bsmod = (1 & s) << 4 | a >> 4 & 15,\n\t\tr.acmod = a >> 1 & 7,\n\t\tr.lfeon = 1 & a,\n\t\tr.num_dep_sub = n >> 1 & 15,\n\t\t0 < r.num_dep_sub && (r.chan_loc = (1 & n) << 8 | t.readUint8())\n\t}\n}),\nBoxParser.createFullBoxCtor("dfLa", "FLACSpecificBox",\nfunction(t) {\n\tfor (var e = [], i = ["STREAMINFO", "PADDING", "APPLICATION", "SEEKTABLE", "VORBIS_COMMENT", "CUESHEET", "PICTURE", "RESERVED"];;) {\n\t\tvar r = t.readUint8(),\n\t\ts = Math.min(127 & r, i.length - 1);\n\t\tif (s ? t.readUint8Array(t.readUint24()) : (t.readUint8Array(13), this.samplerate = t.readUint32() >> 12, t.readUint8Array(20)), e.push(i[s]), 128 & r) break\n\t}\n\tthis.numMetadataBlocks = e.length + " (" + e.join(", ") + ")"\n}),\nBoxParser.createBoxCtor("dimm", "hintimmediateBytesSent",\nfunction(t) {\n\tthis.bytessent = t.readUint64()\n}),\nBoxParser.createBoxCtor("dmax", "hintlongestpacket",\nfunction(t) {\n\tthis.time = t.readUint32()\n}),\nBoxParser.createBoxCtor("dmed", "hintmediaBytesSent",\nfunction(t) {\n\tthis.bytessent = t.readUint64()\n}),\nBoxParser.createBoxCtor("dOps", "OpusSpecificBox",\nfunction(t) {\n\tif (this.Version = t.readUint8(), this.OutputChannelCount = t.readUint8(), this.PreSkip = t.readUint16(), this.InputSampleRate = t.readUint32(), this.OutputGain = t.readInt16(), this.ChannelMappingFamily = t.readUint8(), 0 !== this.ChannelMappingFamily) {\n\t\tthis.StreamCount = t.readUint8(),\n\t\tthis.CoupledCount = t.readUint8(),\n\t\tthis.ChannelMapping = [];\n\t\tfor (var e = 0; e < this.OutputChannelCount; e++) this.ChannelMapping[e] = t.readUint8()\n\t}\n}),\nBoxParser.createFullBoxCtor("dref", "DataReferenceBox",\nfunction(t) {\n\tvar e;\n\tthis.entries = [];\n\tfor (var i = t.readUint32(), r = 0; r < i; r++) {\n\t\tif ((e = BoxParser.parseOneBox(t, !1, this.size - (t.getPosition() - this.start))).code !== BoxParser.OK) return;\n\t\te = e.box,\n\t\tthis.entries.push(e)\n\t}\n}),\nBoxParser.createBoxCtor("drep", "hintrepeatedBytesSent",\nfunction(t) {\n\tthis.bytessent = t.readUint64()\n}),\nBoxParser.createFullBoxCtor("elng", "ExtendedLanguageBox",\nfunction(t) {\n\tthis.extended_language = t.readString(this.size - this.hdr_size)\n}),\nBoxParser.createFullBoxCtor("elst", "EditListBox",\nfunction(t) {\n\tthis.entries = [];\n\tfor (var e = t.readUint32(), i = 0; i < e; i++) {\n\t\tvar r = {};\n\t\tthis.entries.push(r),\n\t\t1 === this.version ? (r.segment_duration = t.readUint64(), r.media_time = t.readInt64()) : (r.segment_duration = t.readUint32(), r.media_time = t.readInt32()),\n\t\tr.media_rate_integer = t.readInt16(),\n\t\tr.media_rate_fraction = t.readInt16()\n\t}\n}),\nBoxParser.createFullBoxCtor("emsg", "EventMessageBox",\nfunction(t) {\n\t1 == this.version ? (this.timescale = t.readUint32(), this.presentation_time = t.readUint64(), this.event_duration = t.readUint32(), this.id = t.readUint32(), this.scheme_id_uri = t.readCString(), this.value = t.readCString()) : (this.scheme_id_uri = t.readCString(), this.value = t.readCString(), this.timescale = t.readUint32(), this.presentation_time_delta = t.readUint32(), this.event_duration = t.readUint32(), this.id = t.readUint32());\n\tvar e = this.size - this.hdr_size - (16 + (this.scheme_id_uri.length + 1) + (this.value.length + 1));\n\t1 == this.version && (e -= 4),\n\tthis.message_data = t.readUint8Array(e)\n}),\nBoxParser.createEntityToGroupCtor = function(e, r) {\n\tBoxParser[e + "Box"] = function(t) {\n\t\tBoxParser.FullBox.call(this, e, t)\n\t},\n\tBoxParser[e + "Box"].prototype = new BoxParser.FullBox,\n\tBoxParser[e + "Box"].prototype.parse = function(t) {\n\t\tif (this.parseFullHeader(t), r) r.call(this, t);\n\t\telse for (this.group_id = t.readUint32(), this.num_entities_in_group = t.readUint32(), this.entity_ids = [], i = 0; i < this.num_entities_in_group; i++) {\n\t\t\tvar e = t.readUint32();\n\t\t\tthis.entity_ids.push(e)\n\t\t}\n\t}\n},\nBoxParser.createEntityToGroupCtor("aebr"),\nBoxParser.createEntityToGroupCtor("afbr"),\nBoxParser.createEntityToGroupCtor("albc"),\nBoxParser.createEntityToGroupCtor("altr"),\nBoxParser.createEntityToGroupCtor("brst"),\nBoxParser.createEntityToGroupCtor("dobr"),\nBoxParser.createEntityToGroupCtor("eqiv"),\nBoxParser.createEntityToGroupCtor("favc"),\nBoxParser.createEntityToGroupCtor("fobr"),\nBoxParser.createEntityToGroupCtor("iaug"),\nBoxParser.createEntityToGroupCtor("pano"),\nBoxParser.createEntityToGroupCtor("slid"),\nBoxParser.createEntityToGroupCtor("ster"),\nBoxParser.createEntityToGroupCtor("tsyn"),\nBoxParser.createEntityToGroupCtor("wbbr"),\nBoxParser.createEntityToGroupCtor("prgr"),\nBoxParser.createEntityToGroupCtor("pymd",\nfunction(t) {\n\tthis.group_id = t.readUint32(),\n\tthis.num_entities_in_group = t.readUint32(),\n\tthis.entity_ids = [];\n\tfor (var e = 0; e < this.num_entities_in_group; e++) {\n\t\tvar i = t.readUint32();\n\t\tthis.entity_ids.push(i)\n\t}\n\tfor (this.tile_size_x = t.readUint16(), this.tile_size_y = t.readUint16(), this.layer_binning = [], this.tiles_in_layer_column_minus1 = [], this.tiles_in_layer_row_minus1 = [], e = 0; e < this.num_entities_in_group; e++) this.layer_binning[e] = t.readUint16(),\n\tthis.tiles_in_layer_row_minus1[e] = t.readUint16(),\n\tthis.tiles_in_layer_column_minus1[e] = t.readUint16()\n}),\nBoxParser.createFullBoxCtor("esds", "ElementaryStreamDescriptorBox",\nfunction(t) {\n\tvar e = t.readUint8Array(this.size - this.hdr_size);\n\tvoid 0 !== MPEG4DescriptorParser && (t = new MPEG4DescriptorParser, this.esd = t.parseOneDescriptor(new DataStream(e.buffer, 0, DataStream.BIG_ENDIAN)))\n}),\nBoxParser.createBoxCtor("fiel", "FieldHandlingBox",\nfunction(t) {\n\tthis.fieldCount = t.readUint8(),\n\tthis.fieldOrdering = t.readUint8()\n}),\nBoxParser.createBoxCtor("frma", "OriginalFormatBox",\nfunction(t) {\n\tthis.data_format = t.readString(4)\n}),\nBoxParser.createBoxCtor("ftyp", "FileTypeBox",\nfunction(t) {\n\tvar e = this.size - this.hdr_size;\n\tthis.major_brand = t.readString(4),\n\tthis.minor_version = t.readUint32(),\n\te -= 8,\n\tthis.compatible_brands = [];\n\tfor (var i = 0; 4 <= e;) this.compatible_brands[i] = t.readString(4),\n\te -= 4,\n\ti++\n}),\nBoxParser.createFullBoxCtor("hdlr", "HandlerBox",\nfunction(t) {\n\t0 === this.version && (t.readUint32(), this.handler = t.readString(4), t.readUint32Array(3), this.name = t.readString(this.size - this.hdr_size - 20), "\0" === this.name[this.name.length - 1] && (this.name = this.name.slice(0, -1)))\n}),\nBoxParser.createBoxCtor("hvcC", "HEVCConfigurationBox",\nfunction(t) {\n\tvar e, i;\n\tthis.configurationVersion = t.readUint8(),\n\ti = t.readUint8(),\n\tthis.general_profile_space = i >> 6,\n\tthis.general_tier_flag = (32 & i) >> 5,\n\tthis.general_profile_idc = 31 & i,\n\tthis.general_profile_compatibility = t.readUint32(),\n\tthis.general_constraint_indicator = t.readUint8Array(6),\n\tthis.general_level_idc = t.readUint8(),\n\tthis.min_spatial_segmentation_idc = 4095 & t.readUint16(),\n\tthis.parallelismType = 3 & t.readUint8(),\n\tthis.chroma_format_idc = 3 & t.readUint8(),\n\tthis.bit_depth_luma_minus8 = 7 & t.readUint8(),\n\tthis.bit_depth_chroma_minus8 = 7 & t.readUint8(),\n\tthis.avgFrameRate = t.readUint16(),\n\ti = t.readUint8(),\n\tthis.constantFrameRate = i >> 6,\n\tthis.numTemporalLayers = (13 & i) >> 3,\n\tthis.temporalIdNested = (4 & i) >> 2,\n\tthis.lengthSizeMinusOne = 3 & i,\n\tthis.nalu_arrays = [],\n\tthis.nalu_arrays.toString = function() {\n\t\tvar t = "<table class=\'inner-table\'>";\n\t\tt += "<thead><tr><th>completeness</th><th>nalu_type</th><th>nalu_data</th></tr></thead>",\n\t\tt += "<tbody>";\n\t\tfor (var e = 0; e < this.length; e++) {\n\t\t\tvar i = this[e];\n\t\t\tt += "<tr>",\n\t\t\tt += "<td rowspan=\'" + i.length + "\'>" + i.completeness + "</td>",\n\t\t\tt += "<td rowspan=\'" + i.length + "\'>" + i.nalu_type + "</td>";\n\t\t\tfor (var r = 0; r < i.length; r++) 0 !== r && (t += "<tr>"),\n\t\t\tt += "<td>",\n\t\t\tt += i[r].data.reduce(function(t, e) {\n\t\t\t\treturn t + e.toString(16).padStart(2, "0")\n\t\t\t},\n\t\t\t"0x"),\n\t\t\tt += "</td></tr>"\n\t\t}\n\t\treturn t += "</tbody></table>"\n\t};\n\tfor (var r = t.readUint8(), s = 0; s < r; s++) {\n\t\tvar a = [];\n\t\tthis.nalu_arrays.push(a),\n\t\ti = t.readUint8(),\n\t\ta.completeness = (128 & i) >> 7,\n\t\ta.nalu_type = 63 & i;\n\t\tfor (var n = t.readUint16(), o = 0; o < n; o++) {\n\t\t\tvar h = {};\n\t\t\ta.push(h),\n\t\t\te = t.readUint16(),\n\t\t\th.data = t.readUint8Array(e)\n\t\t}\n\t}\n}),\nBoxParser.createFullBoxCtor("iinf", "ItemInfoBox",\nfunction(t) {\n\tvar e;\n\t0 === this.version ? this.entry_count = t.readUint16() : this.entry_count = t.readUint32(),\n\tthis.item_infos = [];\n\tfor (var i = 0; i < this.entry_count; i++) {\n\t\tif ((e = BoxParser.parseOneBox(t, !1, this.size - (t.getPosition() - this.start))).code !== BoxParser.OK) return;\n\t\t"infe" !== e.box.type && Log.error("BoxParser", "Expected \'infe\' box, got " + e.box.type),\n\t\tthis.item_infos[i] = e.box\n\t}\n}),\nBoxParser.createFullBoxCtor("iloc", "ItemLocationBox",\nfunction(t) {\n\tvar e = t.readUint8();\n\tthis.offset_size = e >> 4 & 15,\n\tthis.length_size = 15 & e,\n\te = t.readUint8(),\n\tthis.base_offset_size = e >> 4 & 15,\n\t1 === this.version || 2 === this.version ? this.index_size = 15 & e: this.index_size = 0,\n\tthis.items = [];\n\tvar i = 0;\n\tif (this.version < 2) i = t.readUint16();\n\telse {\n\t\tif (2 !== this.version) throw "version of iloc box not supported";\n\t\ti = t.readUint32()\n\t}\n\tfor (var r = 0; r < i; r++) {\n\t\tvar s = {};\n\t\tif (this.items.push(s), this.version < 2) s.item_ID = t.readUint16();\n\t\telse {\n\t\t\tif (2 !== this.version) throw "version of iloc box not supported";\n\t\t\ts.item_ID = t.readUint32()\n\t\t}\n\t\tswitch (1 === this.version || 2 === this.version ? s.construction_method = 15 & t.readUint16() : s.construction_method = 0, s.data_reference_index = t.readUint16(), this.base_offset_size) {\n\t\tcase 0:\n\t\t\ts.base_offset = 0;\n\t\t\tbreak;\n\t\tcase 4:\n\t\t\ts.base_offset = t.readUint32();\n\t\t\tbreak;\n\t\tcase 8:\n\t\t\ts.base_offset = t.readUint64();\n\t\t\tbreak;\n\t\tdefault:\n\t\t\tthrow "Error reading base offset size"\n\t\t}\n\t\tvar a = t.readUint16();\n\t\ts.extents = [];\n\t\tfor (var n = 0; n < a; n++) {\n\t\t\tvar o = {};\n\t\t\tif (s.extents.push(o), 1 === this.version || 2 === this.version) switch (this.index_size) {\n\t\t\tcase 0:\n\t\t\t\to.extent_index = 0;\n\t\t\t\tbreak;\n\t\t\tcase 4:\n\t\t\t\to.extent_index = t.readUint32();\n\t\t\t\tbreak;\n\t\t\tcase 8:\n\t\t\t\to.extent_index = t.readUint64();\n\t\t\t\tbreak;\n\t\t\tdefault:\n\t\t\t\tthrow "Error reading extent index"\n\t\t\t}\n\t\t\tswitch (this.offset_size) {\n\t\t\tcase 0:\n\t\t\t\to.extent_offset = 0;\n\t\t\t\tbreak;\n\t\t\tcase 4:\n\t\t\t\to.extent_offset = t.readUint32();\n\t\t\t\tbreak;\n\t\t\tcase 8:\n\t\t\t\to.extent_offset = t.readUint64();\n\t\t\t\tbreak;\n\t\t\tdefault:\n\t\t\t\tthrow "Error reading extent index"\n\t\t\t}\n\t\t\tswitch (this.length_size) {\n\t\t\tcase 0:\n\t\t\t\to.extent_length = 0;\n\t\t\t\tbreak;\n\t\t\tcase 4:\n\t\t\t\to.extent_length = t.readUint32();\n\t\t\t\tbreak;\n\t\t\tcase 8:\n\t\t\t\to.extent_length = t.readUint64();\n\t\t\t\tbreak;\n\t\t\tdefault:\n\t\t\t\tthrow "Error reading extent index"\n\t\t\t}\n\t\t}\n\t}\n}),\nBoxParser.createBoxCtor("imir", "ImageMirror",\nfunction(t) {\n\tt = t.readUint8();\n\tthis.reserved = t >> 7,\n\tthis.axis = 1 & t\n}),\nBoxParser.createFullBoxCtor("infe", "ItemInfoEntry",\nfunction(t) {\n\treturn 0 !== this.version && 1 !== this.version || (this.item_ID = t.readUint16(), this.item_protection_index = t.readUint16(), this.item_name = t.readCString(), this.content_type = t.readCString(), this.content_encoding = t.readCString()),\n\t1 === this.version ? (this.extension_type = t.readString(4), Log.warn("BoxParser", "Cannot parse extension type"), void t.seek(this.start + this.size)) : void(2 <= this.version && (2 === this.version ? this.item_ID = t.readUint16() : 3 === this.version && (this.item_ID = t.readUint32()), this.item_protection_index = t.readUint16(), this.item_type = t.readString(4), this.item_name = t.readCString(), "mime" === this.item_type ? (this.content_type = t.readCString(), this.content_encoding = t.readCString()) : "uri " === this.item_type && (this.item_uri_type = t.readCString())))\n}),\nBoxParser.createFullBoxCtor("ipma", "ItemPropertyAssociationBox",\nfunction(t) {\n\tvar e, i;\n\tfor (entry_count = t.readUint32(), this.associations = [], e = 0; e < entry_count; e++) {\n\t\tvar r = {};\n\t\tthis.associations.push(r),\n\t\tthis.version < 1 ? r.id = t.readUint16() : r.id = t.readUint32();\n\t\tvar s = t.readUint8();\n\t\tfor (r.props = [], i = 0; i < s; i++) {\n\t\t\tvar a = t.readUint8(),\n\t\t\tn = {};\n\t\t\tr.props.push(n),\n\t\t\tn.essential = (128 & a) >> 7 == 1,\n\t\t\t1 & this.flags ? n.property_index = (127 & a) << 8 | t.readUint8() : n.property_index = 127 & a\n\t\t}\n\t}\n}),\nBoxParser.createFullBoxCtor("iref", "ItemReferenceBox",\nfunction(t) {\n\tvar e;\n\tfor (this.references = []; t.getPosition() < this.start + this.size;) {\n\t\tif ((e = BoxParser.parseOneBox(t, !0, this.size - (t.getPosition() - this.start))).code !== BoxParser.OK) return; (e = new(0 === this.version ? BoxParser.SingleItemTypeReferenceBox: BoxParser.SingleItemTypeReferenceBoxLarge)(e.type, e.size, e.hdr_size, e.start)).write === BoxParser.Box.prototype.write && "mdat" !== e.type && (Log.warn("BoxParser", e.type + " box writing not yet implemented, keeping unparsed data in memory for later write"), e.parseDataAndRewind(t)),\n\t\te.parse(t),\n\t\tthis.references.push(e)\n\t}\n}),\nBoxParser.createBoxCtor("irot", "ImageRotation",\nfunction(t) {\n\tthis.angle = 3 & t.readUint8()\n}),\nBoxParser.createFullBoxCtor("ispe", "ImageSpatialExtentsProperty",\nfunction(t) {\n\tthis.image_width = t.readUint32(),\n\tthis.image_height = t.readUint32()\n}),\nBoxParser.createFullBoxCtor("kind", "KindBox",\nfunction(t) {\n\tthis.schemeURI = t.readCString(),\n\tthis.value = t.readCString()\n}),\nBoxParser.createFullBoxCtor("leva", "LevelAssignmentBox",\nfunction(t) {\n\tvar e = t.readUint8();\n\tthis.levels = [];\n\tfor (var i = 0; i < e; i++) {\n\t\tvar r = {}; (this.levels[i] = r).track_ID = t.readUint32();\n\t\tvar s = t.readUint8();\n\t\tswitch (r.padding_flag = s >> 7, r.assignment_type = 127 & s, r.assignment_type) {\n\t\tcase 0:\n\t\t\tr.grouping_type = t.readString(4);\n\t\t\tbreak;\n\t\tcase 1:\n\t\t\tr.grouping_type = t.readString(4),\n\t\t\tr.grouping_type_parameter = t.readUint32();\n\t\t\tbreak;\n\t\tcase 2:\n\t\tcase 3:\n\t\t\tbreak;\n\t\tcase 4:\n\t\t\tr.sub_track_id = t.readUint32();\n\t\t\tbreak;\n\t\tdefault:\n\t\t\tLog.warn("BoxParser", "Unknown leva assignement type")\n\t\t}\n\t}\n}),\nBoxParser.createBoxCtor("lhvC", "LHEVCConfigurationBox",\nfunction(t) {\n\tvar e;\n\tthis.configurationVersion = t.readUint8(),\n\tthis.min_spatial_segmentation_idc = 4095 & t.readUint16(),\n\tthis.parallelismType = 3 & t.readUint8(),\n\te = t.readUint8(),\n\tthis.numTemporalLayers = (13 & e) >> 3,\n\tthis.temporalIdNested = (4 & e) >> 2,\n\tthis.lengthSizeMinusOne = 3 & e,\n\tthis.nalu_arrays = [],\n\tthis.nalu_arrays.toString = function() {\n\t\tvar t = "<table class=\'inner-table\'>";\n\t\tt += "<thead><tr><th>completeness</th><th>nalu_type</th><th>nalu_data</th></tr></thead>",\n\t\tt += "<tbody>";\n\t\tfor (var e = 0; e < this.length; e++) {\n\t\t\tvar i = this[e];\n\t\t\tt += "<tr>",\n\t\t\tt += "<td rowspan=\'" + i.length + "\'>" + i.completeness + "</td>",\n\t\t\tt += "<td rowspan=\'" + i.length + "\'>" + i.nalu_type + "</td>";\n\t\t\tfor (var r = 0; r < i.length; r++) 0 !== r && (t += "<tr>"),\n\t\t\tt += "<td>",\n\t\t\tt += i[r].data.reduce(function(t, e) {\n\t\t\t\treturn t + e.toString(16).padStart(2, "0")\n\t\t\t},\n\t\t\t"0x"),\n\t\t\tt += "</td></tr>"\n\t\t}\n\t\treturn t += "</tbody></table>"\n\t};\n\tfor (var i = t.readUint8(), r = 0; r < i; r++) {\n\t\tvar s = [];\n\t\tthis.nalu_arrays.push(s),\n\t\te = t.readUint8(),\n\t\ts.completeness = (128 & e) >> 7,\n\t\ts.nalu_type = 63 & e;\n\t\tfor (var a = t.readUint16(), n = 0; n < a; n++) {\n\t\t\tvar o = {};\n\t\t\ts.push(o);\n\t\t\tvar h = t.readUint16();\n\t\t\to.data = t.readUint8Array(h)\n\t\t}\n\t}\n}),\nBoxParser.createBoxCtor("lsel", "LayerSelectorProperty",\nfunction(t) {\n\tthis.layer_id = t.readUint16()\n}),\nBoxParser.createBoxCtor("maxr", "hintmaxrate",\nfunction(t) {\n\tthis.period = t.readUint32(),\n\tthis.bytes = t.readUint32()\n}),\nColorPoint.prototype.toString = function() {\n\treturn "(" + this.x + "," + this.y + ")"\n},\nBoxParser.createBoxCtor("mdcv", "MasteringDisplayColourVolumeBox",\nfunction(t) {\n\tthis.display_primaries = [],\n\tthis.display_primaries[0] = new ColorPoint(t.readUint16(), t.readUint16()),\n\tthis.display_primaries[1] = new ColorPoint(t.readUint16(), t.readUint16()),\n\tthis.display_primaries[2] = new ColorPoint(t.readUint16(), t.readUint16()),\n\tthis.white_point = new ColorPoint(t.readUint16(), t.readUint16()),\n\tthis.max_display_mastering_luminance = t.readUint32(),\n\tthis.min_display_mastering_luminance = t.readUint32()\n}),\nBoxParser.createFullBoxCtor("mdhd", "MediaHeaderBox",\nfunction(t) {\n\t1 == this.version ? (this.creation_time = t.readUint64(), this.modification_time = t.readUint64(), this.timescale = t.readUint32(), this.duration = t.readUint64()) : (this.creation_time = t.readUint32(), this.modification_time = t.readUint32(), this.timescale = t.readUint32(), this.duration = t.readUint32()),\n\tthis.parseLanguage(t),\n\tt.readUint16()\n}),\nBoxParser.createFullBoxCtor("mehd", "MovieExtendsHeaderBox",\nfunction(t) {\n\t1 & this.flags && (Log.warn("BoxParser", "mehd box incorrectly uses flags set to 1, converting version to 1"), this.version = 1),\n\t1 == this.version ? this.fragment_duration = t.readUint64() : this.fragment_duration = t.readUint32()\n}),\nBoxParser.createFullBoxCtor("meta", "MetaBox",\nfunction(t) {\n\tthis.boxes = [],\n\tBoxParser.ContainerBox.prototype.parse.call(this, t)\n}),\nBoxParser.createFullBoxCtor("mfhd", "MovieFragmentHeaderBox",\nfunction(t) {\n\tthis.sequence_number = t.readUint32()\n}),\nBoxParser.createFullBoxCtor("mfro", "MovieFragmentRandomAccessOffsetBox",\nfunction(t) {\n\tthis._size = t.readUint32()\n}),\nBoxParser.createFullBoxCtor("mskC", "MaskConfigurationProperty",\nfunction(t) {\n\tthis.bits_per_pixel = t.readUint8()\n}),\nBoxParser.createFullBoxCtor("mvhd", "MovieHeaderBox",\nfunction(t) {\n\t1 == this.version ? (this.creation_time = t.readUint64(), this.modification_time = t.readUint64(), this.timescale = t.readUint32(), this.duration = t.readUint64()) : (this.creation_time = t.readUint32(), this.modification_time = t.readUint32(), this.timescale = t.readUint32(), this.duration = t.readUint32()),\n\tthis.rate = t.readUint32(),\n\tthis.volume = t.readUint16() >> 8,\n\tt.readUint16(),\n\tt.readUint32Array(2),\n\tthis.matrix = t.readUint32Array(9),\n\tt.readUint32Array(6),\n\tthis.next_track_id = t.readUint32()\n}),\nBoxParser.createBoxCtor("npck", "hintPacketsSent",\nfunction(t) {\n\tthis.packetssent = t.readUint32()\n}),\nBoxParser.createBoxCtor("nump", "hintPacketsSent",\nfunction(t) {\n\tthis.packetssent = t.readUint64()\n}),\nBoxParser.createFullBoxCtor("padb", "PaddingBitsBox",\nfunction(t) {\n\tvar e = t.readUint32();\n\tthis.padbits = [];\n\tfor (var i = 0; i < Math.floor((e + 1) / 2); i++) this.padbits = t.readUint8()\n}),\nBoxParser.createBoxCtor("pasp", "PixelAspectRatioBox",\nfunction(t) {\n\tthis.hSpacing = t.readUint32(),\n\tthis.vSpacing = t.readUint32()\n}),\nBoxParser.createBoxCtor("payl", "CuePayloadBox",\nfunction(t) {\n\tthis.text = t.readString(this.size - this.hdr_size)\n}),\nBoxParser.createBoxCtor("payt", "hintpayloadID",\nfunction(t) {\n\tthis.payloadID = t.readUint32();\n\tvar e = t.readUint8();\n\tthis.rtpmap_string = t.readString(e)\n}),\nBoxParser.createFullBoxCtor("pdin", "ProgressiveDownloadInfoBox",\nfunction(t) {\n\tvar e = (this.size - this.hdr_size) / 8;\n\tthis.rate = [],\n\tthis.initial_delay = [];\n\tfor (var i = 0; i < e; i++) this.rate[i] = t.readUint32(),\n\tthis.initial_delay[i] = t.readUint32()\n}),\nBoxParser.createFullBoxCtor("pitm", "PrimaryItemBox",\nfunction(t) {\n\t0 === this.version ? this.item_id = t.readUint16() : this.item_id = t.readUint32()\n}),\nBoxParser.createFullBoxCtor("pixi", "PixelInformationProperty",\nfunction(t) {\n\tvar e;\n\tfor (this.num_channels = t.readUint8(), this.bits_per_channels = [], e = 0; e < this.num_channels; e++) this.bits_per_channels[e] = t.readUint8()\n}),\nBoxParser.createBoxCtor("pmax", "hintlargestpacket",\nfunction(t) {\n\tthis.bytes = t.readUint32()\n}),\nBoxParser.createFullBoxCtor("prdi", "ProgressiveDerivedImageItemInformationProperty",\nfunction(t) {\n\tif (this.step_count = t.readUint16(), this.item_count = [], 2 & this.flags) for (var e = 0; e < this.step_count; e++) this.item_count[e] = t.readUint16()\n}),\nBoxParser.createFullBoxCtor("prft", "ProducerReferenceTimeBox",\nfunction(t) {\n\tthis.ref_track_id = t.readUint32(),\n\tthis.ntp_timestamp = t.readUint64(),\n\t0 === this.version ? this.media_time = t.readUint32() : this.media_time = t.readUint64()\n}),\nBoxParser.createFullBoxCtor("pssh", "ProtectionSystemSpecificHeaderBox",\nfunction(t) {\n\tif (this.system_id = BoxParser.parseHex16(t), 0 < this.version) {\n\t\tvar e = t.readUint32();\n\t\tthis.kid = [];\n\t\tfor (var i = 0; i < e; i++) this.kid[i] = BoxParser.parseHex16(t)\n\t}\n\tvar r = t.readUint32();\n\t0 < r && (this.data = t.readUint8Array(r))\n}),\nBoxParser.createFullBoxCtor("clef", "TrackCleanApertureDimensionsBox",\nfunction(t) {\n\tthis.width = t.readUint32(),\n\tthis.height = t.readUint32()\n}),\nBoxParser.createFullBoxCtor("enof", "TrackEncodedPixelsDimensionsBox",\nfunction(t) {\n\tthis.width = t.readUint32(),\n\tthis.height = t.readUint32()\n}),\nBoxParser.createFullBoxCtor("prof", "TrackProductionApertureDimensionsBox",\nfunction(t) {\n\tthis.width = t.readUint32(),\n\tthis.height = t.readUint32()\n}),\nBoxParser.createContainerBoxCtor("tapt", "TrackApertureModeDimensionsBox", null, ["clef", "prof", "enof"]),\nBoxParser.createBoxCtor("rtp ", "rtpmoviehintinformation",\nfunction(t) {\n\tthis.descriptionformat = t.readString(4),\n\tthis.sdptext = t.readString(this.size - this.hdr_size - 4)\n}),\nBoxParser.createFullBoxCtor("saio", "SampleAuxiliaryInformationOffsetsBox",\nfunction(t) {\n\t1 & this.flags && (this.aux_info_type = t.readString(4), this.aux_info_type_parameter = t.readUint32());\n\tvar e = t.readUint32();\n\tthis.offset = [];\n\tfor (var i = 0; i < e; i++) 0 === this.version ? this.offset[i] = t.readUint32() : this.offset[i] = t.readUint64()\n}),\nBoxParser.createFullBoxCtor("saiz", "SampleAuxiliaryInformationSizesBox",\nfunction(t) {\n\tif (1 & this.flags && (this.aux_info_type = t.readString(4), this.aux_info_type_parameter = t.readUint32()), this.default_sample_info_size = t.readUint8(), this.sample_count = t.readUint32(), this.sample_info_size = [], 0 === this.default_sample_info_size) for (var e = 0; e < this.sample_count; e++) this.sample_info_size[e] = t.readUint8()\n}),\nBoxParser.createSampleEntryCtor(BoxParser.SAMPLE_ENTRY_TYPE_METADATA, "mett",\nfunction(t) {\n\tthis.parseHeader(t),\n\tthis.content_encoding = t.readCString(),\n\tthis.mime_format = t.readCString(),\n\tthis.parseFooter(t)\n}),\nBoxParser.createSampleEntryCtor(BoxParser.SAMPLE_ENTRY_TYPE_METADATA, "metx",\nfunction(t) {\n\tthis.parseHeader(t),\n\tthis.content_encoding = t.readCString(),\n\tthis.namespace = t.readCString(),\n\tthis.schema_location = t.readCString(),\n\tthis.parseFooter(t)\n}),\nBoxParser.createSampleEntryCtor(BoxParser.SAMPLE_ENTRY_TYPE_SUBTITLE, "sbtt",\nfunction(t) {\n\tthis.parseHeader(t),\n\tthis.content_encoding = t.readCString(),\n\tthis.mime_format = t.readCString(),\n\tthis.parseFooter(t)\n}),\nBoxParser.createSampleEntryCtor(BoxParser.SAMPLE_ENTRY_TYPE_SUBTITLE, "stpp",\nfunction(t) {\n\tthis.parseHeader(t),\n\tthis.namespace = t.readCString(),\n\tthis.schema_location = t.readCString(),\n\tthis.auxiliary_mime_types = t.readCString(),\n\tthis.parseFooter(t)\n}),\nBoxParser.createSampleEntryCtor(BoxParser.SAMPLE_ENTRY_TYPE_SUBTITLE, "stxt",\nfunction(t) {\n\tthis.parseHeader(t),\n\tthis.content_encoding = t.readCString(),\n\tthis.mime_format = t.readCString(),\n\tthis.parseFooter(t)\n}),\nBoxParser.createSampleEntryCtor(BoxParser.SAMPLE_ENTRY_TYPE_SUBTITLE, "tx3g",\nfunction(t) {\n\tthis.parseHeader(t),\n\tthis.displayFlags = t.readUint32(),\n\tthis.horizontal_justification = t.readInt8(),\n\tthis.vertical_justification = t.readInt8(),\n\tthis.bg_color_rgba = t.readUint8Array(4),\n\tthis.box_record = t.readInt16Array(4),\n\tthis.style_record = t.readUint8Array(12),\n\tthis.parseFooter(t)\n}),\nBoxParser.createSampleEntryCtor(BoxParser.SAMPLE_ENTRY_TYPE_METADATA, "wvtt",\nfunction(t) {\n\tthis.parseHeader(t),\n\tthis.parseFooter(t)\n}),\nBoxParser.createSampleGroupCtor("alst",\nfunction(t) {\n\tvar e, i = t.readUint16();\n\tfor (this.first_output_sample = t.readUint16(), this.sample_offset = [], e = 0; e < i; e++) this.sample_offset[e] = t.readUint32();\n\tvar r = this.description_length - 4 - 4 * i;\n\tfor (this.num_output_samples = [], this.num_total_samples = [], e = 0; e < r / 4; e++) this.num_output_samples[e] = t.readUint16(),\n\tthis.num_total_samples[e] = t.readUint16()\n}),\nBoxParser.createSampleGroupCtor("avll",\nfunction(t) {\n\tthis.layerNumber = t.readUint8(),\n\tthis.accurateStatisticsFlag = t.readUint8(),\n\tthis.avgBitRate = t.readUint16(),\n\tthis.avgFrameRate = t.readUint16()\n}),\nBoxParser.createSampleGroupCtor("avss",\nfunction(t) {\n\tthis.subSequenceIdentifier = t.readUint16(),\n\tthis.layerNumber = t.readUint8();\n\tvar e = t.readUint8();\n\tthis.durationFlag = e >> 7,\n\tthis.avgRateFlag = e >> 6 & 1,\n\tthis.durationFlag && (this.duration = t.readUint32()),\n\tthis.avgRateFlag && (this.accurateStatisticsFlag = t.readUint8(), this.avgBitRate = t.readUint16(), this.avgFrameRate = t.readUint16()),\n\tthis.dependency = [];\n\tfor (var i = t.readUint8(), r = 0; r < i; r++) {\n\t\tvar s = {};\n\t\tthis.dependency.push(s),\n\t\ts.subSeqDirectionFlag = t.readUint8(),\n\t\ts.layerNumber = t.readUint8(),\n\t\ts.subSequenceIdentifier = t.readUint16()\n\t}\n}),\nBoxParser.createSampleGroupCtor("dtrt",\nfunction(t) {\n\tLog.warn("BoxParser", "Sample Group type: " + this.grouping_type + " not fully parsed")\n}),\nBoxParser.createSampleGroupCtor("mvif",\nfunction(t) {\n\tLog.warn("BoxParser", "Sample Group type: " + this.grouping_type + " not fully parsed")\n}),\nBoxParser.createSampleGroupCtor("prol",\nfunction(t) {\n\tthis.roll_distance = t.readInt16()\n}),\nBoxParser.createSampleGroupCtor("rap ",\nfunction(t) {\n\tt = t.readUint8();\n\tthis.num_leading_samples_known = t >> 7,\n\tthis.num_leading_samples = 127 & t\n}),\nBoxParser.createSampleGroupCtor("rash",\nfunction(t) {\n\tif (this.operation_point_count = t.readUint16(), this.description_length !== 2 + (1 === this.operation_point_count ? 2 : 6 * this.operation_point_count) + 9) Log.warn("BoxParser", "Mismatch in " + this.grouping_type + " sample group length"),\n\tthis.data = t.readUint8Array(this.description_length - 2);\n\telse {\n\t\tif (1 === this.operation_point_count) this.target_rate_share = t.readUint16();\n\t\telse {\n\t\t\tthis.target_rate_share = [],\n\t\t\tthis.available_bitrate = [];\n\t\t\tfor (var e = 0; e < this.operation_point_count; e++) this.available_bitrate[e] = t.readUint32(),\n\t\t\tthis.target_rate_share[e] = t.readUint16()\n\t\t}\n\t\tthis.maximum_bitrate = t.readUint32(),\n\t\tthis.minimum_bitrate = t.readUint32(),\n\t\tthis.discard_priority = t.readUint8()\n\t}\n}),\nBoxParser.createSampleGroupCtor("roll",\nfunction(t) {\n\tthis.roll_distance = t.readInt16()\n}),\nBoxParser.SampleGroupEntry.prototype.parse = function(t) {\n\tLog.warn("BoxParser", "Unknown Sample Group type: " + this.grouping_type),\n\tthis.data = t.readUint8Array(this.description_length)\n},\nBoxParser.createSampleGroupCtor("scif",\nfunction(t) {\n\tLog.warn("BoxParser", "Sample Group type: " + this.grouping_type + " not fully parsed")\n}),\nBoxParser.createSampleGroupCtor("scnm",\nfunction(t) {\n\tLog.warn("BoxParser", "Sample Group type: " + this.grouping_type + " not fully parsed")\n}),\nBoxParser.createSampleGroupCtor("seig",\nfunction(t) {\n\tthis.reserved = t.readUint8();\n\tvar e = t.readUint8();\n\tthis.crypt_byte_block = e >> 4,\n\tthis.skip_byte_block = 15 & e,\n\tthis.isProtected = t.readUint8(),\n\tthis.Per_Sample_IV_Size = t.readUint8(),\n\tthis.KID = BoxParser.parseHex16(t),\n\tthis.constant_IV_size = 0,\n\tthis.constant_IV = 0,\n\t1 === this.isProtected && 0 === this.Per_Sample_IV_Size && (this.constant_IV_size = t.readUint8(), this.constant_IV = t.readUint8Array(this.constant_IV_size))\n}),\nBoxParser.createSampleGroupCtor("stsa",\nfunction(t) {\n\tLog.warn("BoxParser", "Sample Group type: " + this.grouping_type + " not fully parsed")\n}),\nBoxParser.createSampleGroupCtor("sync",\nfunction(t) {\n\tt = t.readUint8();\n\tthis.NAL_unit_type = 63 & t\n}),\nBoxParser.createSampleGroupCtor("tele",\nfunction(t) {\n\tt = t.readUint8();\n\tthis.level_independently_decodable = t >> 7\n}),\nBoxParser.createSampleGroupCtor("tsas",\nfunction(t) {\n\tLog.warn("BoxParser", "Sample Group type: " + this.grouping_type + " not fully parsed")\n}),\nBoxParser.createSampleGroupCtor("tscl",\nfunction(t) {\n\tLog.warn("BoxParser", "Sample Group type: " + this.grouping_type + " not fully parsed")\n}),\nBoxParser.createSampleGroupCtor("vipr",\nfunction(t) {\n\tLog.warn("BoxParser", "Sample Group type: " + this.grouping_type + " not fully parsed")\n}),\nBoxParser.createFullBoxCtor("sbgp", "SampleToGroupBox",\nfunction(t) {\n\tthis.grouping_type = t.readString(4),\n\t1 === this.version ? this.grouping_type_parameter = t.readUint32() : this.grouping_type_parameter = 0,\n\tthis.entries = [];\n\tfor (var e = t.readUint32(), i = 0; i < e; i++) {\n\t\tvar r = {};\n\t\tthis.entries.push(r),\n\t\tr.sample_count = t.readInt32(),\n\t\tr.group_description_index = t.readInt32()\n\t}\n}),\nPixel.prototype.toString = function() {\n\treturn "[row: " + this.bad_pixel_row + ", column: " + this.bad_pixel_column + "]"\n},\nBoxParser.createFullBoxCtor("sbpm", "SensorBadPixelsMapBox",\nfunction(t) {\n\tvar e;\n\tfor (this.component_count = t.readUint16(), this.component_index = [], e = 0; e < this.component_count; e++) this.component_index.push(t.readUint16());\n\tvar i = t.readUint8();\n\tfor (this.correction_applied = 128 == (128 & i), this.num_bad_rows = t.readUint32(), this.num_bad_cols = t.readUint32(), this.num_bad_pixels = t.readUint32(), this.bad_rows = [], this.bad_columns = [], this.bad_pixels = [], e = 0; e < this.num_bad_rows; e++) this.bad_rows.push(t.readUint32());\n\tfor (e = 0; e < this.num_bad_cols; e++) this.bad_columns.push(t.readUint32());\n\tfor (e = 0; e < this.num_bad_pixels; e++) {\n\t\tvar r = t.readUint32(),\n\t\ts = t.readUint32();\n\t\tthis.bad_pixels.push(new Pixel(r, s))\n\t}\n}),\nBoxParser.createFullBoxCtor("schm", "SchemeTypeBox",\nfunction(t) {\n\tthis.scheme_type = t.readString(4),\n\tthis.scheme_version = t.readUint32(),\n\t1 & this.flags && (this.scheme_uri = t.readString(this.size - this.hdr_size - 8))\n}),\nBoxParser.createBoxCtor("sdp ", "rtptracksdphintinformation",\nfunction(t) {\n\tthis.sdptext = t.readString(this.size - this.hdr_size)\n}),\nBoxParser.createFullBoxCtor("sdtp", "SampleDependencyTypeBox",\nfunction(t) {\n\tvar e, i = this.size - this.hdr_size;\n\tthis.is_leading = [],\n\tthis.sample_depends_on = [],\n\tthis.sample_is_depended_on = [],\n\tthis.sample_has_redundancy = [];\n\tfor (var r = 0; r < i; r++) e = t.readUint8(),\n\tthis.is_leading[r] = e >> 6,\n\tthis.sample_depends_on[r] = e >> 4 & 3,\n\tthis.sample_is_depended_on[r] = e >> 2 & 3,\n\tthis.sample_has_redundancy[r] = 3 & e\n}),\nBoxParser.createFullBoxCtor("senc", "SampleEncryptionBox"),\nBoxParser.createFullBoxCtor("sgpd", "SampleGroupDescriptionBox",\nfunction(t) {\n\tthis.grouping_type = t.readString(4),\n\tLog.debug("BoxParser", "Found Sample Groups of type " + this.grouping_type),\n\t1 === this.version ? this.default_length = t.readUint32() : this.default_length = 0,\n\t2 <= this.version && (this.default_group_description_index = t.readUint32()),\n\tthis.entries = [];\n\tfor (var e = t.readUint32(), i = 0; i < e; i++) {\n\t\tvar r = new(BoxParser[this.grouping_type + "SampleGroupEntry"] ? BoxParser[this.grouping_type + "SampleGroupEntry"] : BoxParser.SampleGroupEntry)(this.grouping_type);\n\t\tthis.entries.push(r),\n\t\t1 === this.version && 0 === this.default_length ? r.description_length = t.readUint32() : r.description_length = this.default_length,\n\t\tr.write === BoxParser.SampleGroupEntry.prototype.write && (Log.info("BoxParser", "SampleGroup for type " + this.grouping_type + " writing not yet implemented, keeping unparsed data in memory for later write"), r.data = t.readUint8Array(r.description_length), t.position -= r.description_length),\n\t\tr.parse(t)\n\t}\n}),\nBoxParser.createFullBoxCtor("sidx", "CompressedSegmentIndexBox",\nfunction(t) {\n\tthis.reference_ID = t.readUint32(),\n\tthis.timescale = t.readUint32(),\n\t0 === this.version ? (this.earliest_presentation_time = t.readUint32(), this.first_offset = t.readUint32()) : (this.earliest_presentation_time = t.readUint64(), this.first_offset = t.readUint64()),\n\tt.readUint16(),\n\tthis.references = [];\n\tfor (var e = t.readUint16(), i = 0; i < e; i++) {\n\t\tvar r = {};\n\t\tthis.references.push(r);\n\t\tvar s = t.readUint32();\n\t\tr.reference_type = s >> 31 & 1,\n\t\tr.referenced_size = 2147483647 & s,\n\t\tr.subsegment_duration = t.readUint32(),\n\t\ts = t.readUint32(),\n\t\tr.starts_with_SAP = s >> 31 & 1,\n\t\tr.SAP_type = s >> 28 & 7,\n\t\tr.SAP_delta_time = 268435455 & s\n\t}\n}),\nBoxParser.SingleItemTypeReferenceBox = function(t, e, i, r) {\n\tBoxParser.Box.call(this, t, e),\n\tthis.hdr_size = i,\n\tthis.start = r\n},\nBoxParser.SingleItemTypeReferenceBox.prototype = new BoxParser.Box,\nBoxParser.SingleItemTypeReferenceBox.prototype.parse = function(t) {\n\tthis.from_item_ID = t.readUint16();\n\tvar e = t.readUint16();\n\tthis.references = [];\n\tfor (var i = 0; i < e; i++) this.references[i] = {},\n\tthis.references[i].to_item_ID = t.readUint16()\n},\nBoxParser.SingleItemTypeReferenceBoxLarge = function(t, e, i, r) {\n\tBoxParser.Box.call(this, t, e),\n\tthis.hdr_size = i,\n\tthis.start = r\n},\nBoxParser.SingleItemTypeReferenceBoxLarge.prototype = new BoxParser.Box,\nBoxParser.SingleItemTypeReferenceBoxLarge.prototype.parse = function(t) {\n\tthis.from_item_ID = t.readUint32();\n\tvar e = t.readUint16();\n\tthis.references = [];\n\tfor (var i = 0; i < e; i++) this.references[i] = {},\n\tthis.references[i].to_item_ID = t.readUint32()\n},\nBoxParser.createFullBoxCtor("SmDm", "SMPTE2086MasteringDisplayMetadataBox",\nfunction(t) {\n\tthis.primaryRChromaticity_x = t.readUint16(),\n\tthis.primaryRChromaticity_y = t.readUint16(),\n\tthis.primaryGChromaticity_x = t.readUint16(),\n\tthis.primaryGChromaticity_y = t.readUint16(),\n\tthis.primaryBChromaticity_x = t.readUint16(),\n\tthis.primaryBChromaticity_y = t.readUint16(),\n\tthis.whitePointChromaticity_x = t.readUint16(),\n\tthis.whitePointChromaticity_y = t.readUint16(),\n\tthis.luminanceMax = t.readUint32(),\n\tthis.luminanceMin = t.readUint32()\n}),\nBoxParser.createFullBoxCtor("smhd", "SoundMediaHeaderBox",\nfunction(t) {\n\tthis.balance = t.readUint16(),\n\tt.readUint16()\n}),\nBoxParser.createFullBoxCtor("ssix", "CompressedSubsegmentIndexBox",\nfunction(t) {\n\tthis.subsegments = [];\n\tfor (var e = t.readUint32(), i = 0; i < e; i++) {\n\t\tvar r = {};\n\t\tthis.subsegments.push(r),\n\t\tr.ranges = [];\n\t\tfor (var s = t.readUint32(), a = 0; a < s; a++) {\n\t\t\tvar n = {};\n\t\t\tr.ranges.push(n),\n\t\t\tn.level = t.readUint8(),\n\t\t\tn.range_size = t.readUint24()\n\t\t}\n\t}\n}),\nBoxParser.createFullBoxCtor("stco", "ChunkOffsetBox",\nfunction(t) {\n\tvar e = t.readUint32();\n\tif (this.chunk_offsets = [], 0 === this.version) for (var i = 0; i < e; i++) this.chunk_offsets.push(t.readUint32())\n}),\nBoxParser.createFullBoxCtor("stdp", "DegradationPriorityBox",\nfunction(t) {\n\tvar e = (this.size - this.hdr_size) / 2;\n\tthis.priority = [];\n\tfor (var i = 0; i < e; i++) this.priority[i] = t.readUint16()\n}),\nBoxParser.createFullBoxCtor("sthd", "SubtitleMediaHeaderBox"),\nBoxParser.createFullBoxCtor("stri", "SubTrackInformationBox",\nfunction(t) {\n\tthis.switch_group = t.readUint16(),\n\tthis.alternate_group = t.readUint16(),\n\tthis.sub_track_id = t.readUint32();\n\tvar e = (this.size - this.hdr_size - 8) / 4;\n\tthis.attribute_list = [];\n\tfor (var i = 0; i < e; i++) this.attribute_list[i] = t.readUint32()\n}),\nBoxParser.createFullBoxCtor("stsc", "SampleToChunkBox",\nfunction(t) {\n\tvar e, i = t.readUint32();\n\tif (this.first_chunk = [], this.samples_per_chunk = [], this.sample_description_index = [], 0 === this.version) for (e = 0; e < i; e++) this.first_chunk.push(t.readUint32()),\n\tthis.samples_per_chunk.push(t.readUint32()),\n\tthis.sample_description_index.push(t.readUint32())\n}),\nBoxParser.createFullBoxCtor("stsd", "SampleDescriptionBox",\nfunction(t) {\n\tvar e, i, r, s;\n\tfor (this.entries = [], r = t.readUint32(), e = 1; e <= r; e++) {\n\t\tif ((i = BoxParser.parseOneBox(t, !0, this.size - (t.getPosition() - this.start))).code !== BoxParser.OK) return;\n\t\tBoxParser[i.type + "SampleEntry"] ? ((s = new BoxParser[i.type + "SampleEntry"](i.size)).hdr_size = i.hdr_size, s.start = i.start) : (Log.warn("BoxParser", "Unknown sample entry type: " + i.type), s = new BoxParser.SampleEntry(i.type, i.size, i.hdr_size, i.start)),\n\t\ts.write === BoxParser.SampleEntry.prototype.write && (Log.info("BoxParser", "SampleEntry " + s.type + " box writing not yet implemented, keeping unparsed data in memory for later write"), s.parseDataAndRewind(t)),\n\t\ts.parse(t),\n\t\tthis.entries.push(s)\n\t}\n}),\nBoxParser.createFullBoxCtor("stsg", "SubTrackSampleGroupBox",\nfunction(t) {\n\tthis.grouping_type = t.readUint32();\n\tvar e = t.readUint16();\n\tthis.group_description_index = [];\n\tfor (var i = 0; i < e; i++) this.group_description_index[i] = t.readUint32()\n}),\nBoxParser.createFullBoxCtor("stsh", "ShadowSyncSampleBox",\nfunction(t) {\n\tvar e, i = t.readUint32();\n\tif (this.shadowed_sample_numbers = [], this.sync_sample_numbers = [], 0 === this.version) for (e = 0; e < i; e++) this.shadowed_sample_numbers.push(t.readUint32()),\n\tthis.sync_sample_numbers.push(t.readUint32())\n}),\nBoxParser.createFullBoxCtor("stss", "SyncSampleBox",\nfunction(t) {\n\tvar e, i = t.readUint32();\n\tif (0 === this.version) for (this.sample_numbers = [], e = 0; e < i; e++) this.sample_numbers.push(t.readUint32())\n}),\nBoxParser.createFullBoxCtor("stsz", "SampleSizeBox",\nfunction(t) {\n\tvar e;\n\tif (this.sample_sizes = [], 0 === this.version) for (this.sample_size = t.readUint32(), this.sample_count = t.readUint32(), e = 0; e < this.sample_count; e++) 0 === this.sample_size ? this.sample_sizes.push(t.readUint32()) : this.sample_sizes[e] = this.sample_size\n}),\nBoxParser.createFullBoxCtor("stts", "TimeToSampleBox",\nfunction(t) {\n\tvar e, i, r = t.readUint32();\n\tif (this.sample_counts = [], this.sample_deltas = [], 0 === this.version) for (e = 0; e < r; e++) this.sample_counts.push(t.readUint32()),\n\t(i = t.readInt32()) < 0 && (Log.warn("BoxParser", "File uses negative stts sample delta, using value 1 instead, sync may be lost!"), i = 1),\n\tthis.sample_deltas.push(i)\n}),\nBoxParser.createFullBoxCtor("stvi", "StereoVideoBox",\nfunction(t) {\n\tvar e = t.readUint32();\n\tthis.single_view_allowed = 3 & e,\n\tthis.stereo_scheme = t.readUint32();\n\tvar i, e = t.readUint32();\n\tfor (this.stereo_indication_type = t.readString(e), this.boxes = []; t.getPosition() < this.start + this.size;) {\n\t\tif ((i = BoxParser.parseOneBox(t, !1, this.size - (t.getPosition() - this.start))).code !== BoxParser.OK) return;\n\t\ti = i.box,\n\t\tthis.boxes.push(i),\n\t\tthis[i.type] = i\n\t}\n}),\nBoxParser.createBoxCtor("styp", "SegmentTypeBox",\nfunction(t) {\n\tBoxParser.ftypBox.prototype.parse.call(this, t)\n}),\nBoxParser.createFullBoxCtor("stz2", "CompactSampleSizeBox",\nfunction(t) {\n\tvar e, i;\n\tif (this.sample_sizes = [], 0 === this.version) if (this.reserved = t.readUint24(), this.field_size = t.readUint8(), i = t.readUint32(), 4 === this.field_size) for (e = 0; e < i; e += 2) {\n\t\tvar r = t.readUint8();\n\t\tthis.sample_sizes[e] = r >> 4 & 15,\n\t\tthis.sample_sizes[e + 1] = 15 & r\n\t} else if (8 === this.field_size) for (e = 0; e < i; e++) this.sample_sizes[e] = t.readUint8();\n\telse if (16 === this.field_size) for (e = 0; e < i; e++) this.sample_sizes[e] = t.readUint16();\n\telse Log.error("BoxParser", "Error in length field in stz2 box")\n}),\nBoxParser.createFullBoxCtor("subs", "SubSampleInformationBox",\nfunction(t) {\n\tvar e, i, r, s = t.readUint32();\n\tfor (this.entries = [], e = 0; e < s; e++) {\n\t\tvar a = {};\n\t\tif ((this.entries[e] = a).sample_delta = t.readUint32(), a.subsamples = [], 0 < (r = t.readUint16())) for (i = 0; i < r; i++) {\n\t\t\tvar n = {};\n\t\t\ta.subsamples.push(n),\n\t\t\t1 == this.version ? n.size = t.readUint32() : n.size = t.readUint16(),\n\t\t\tn.priority = t.readUint8(),\n\t\t\tn.discardable = t.readUint8(),\n\t\t\tn.codec_specific_parameters = t.readUint32()\n\t\t}\n\t}\n}),\nBoxParser.createFullBoxCtor("tenc", "TrackEncryptionBox",\nfunction(t) {\n\tvar e;\n\tt.readUint8(),\n\t0 === this.version ? t.readUint8() : (e = t.readUint8(), this.default_crypt_byte_block = e >> 4 & 15, this.default_skip_byte_block = 15 & e),\n\tthis.default_isProtected = t.readUint8(),\n\tthis.default_Per_Sample_IV_Size = t.readUint8(),\n\tthis.default_KID = BoxParser.parseHex16(t),\n\t1 === this.default_isProtected && 0 === this.default_Per_Sample_IV_Size && (this.default_constant_IV_size = t.readUint8(), this.default_constant_IV = t.readUint8Array(this.default_constant_IV_size))\n}),\nBoxParser.createFullBoxCtor("tfdt", "TrackFragmentBaseMediaDecodeTimeBox",\nfunction(t) {\n\t1 == this.version ? this.baseMediaDecodeTime = t.readUint64() : this.baseMediaDecodeTime = t.readUint32()\n}),\nBoxParser.createFullBoxCtor("tfhd", "TrackFragmentHeaderBox",\nfunction(t) {\n\tvar e = 0;\n\tthis.track_id = t.readUint32(),\n\tthis.size - this.hdr_size > e && this.flags & BoxParser.TFHD_FLAG_BASE_DATA_OFFSET ? (this.base_data_offset = t.readUint64(), e += 8) : this.base_data_offset = 0,\n\tthis.size - this.hdr_size > e && this.flags & BoxParser.TFHD_FLAG_SAMPLE_DESC ? (this.default_sample_description_index = t.readUint32(), e += 4) : this.default_sample_description_index = 0,\n\tthis.size - this.hdr_size > e && this.flags & BoxParser.TFHD_FLAG_SAMPLE_DUR ? (this.default_sample_duration = t.readUint32(), e += 4) : this.default_sample_duration = 0,\n\tthis.size - this.hdr_size > e && this.flags & BoxParser.TFHD_FLAG_SAMPLE_SIZE ? (this.default_sample_size = t.readUint32(), e += 4) : this.default_sample_size = 0,\n\tthis.size - this.hdr_size > e && this.flags & BoxParser.TFHD_FLAG_SAMPLE_FLAGS ? (this.default_sample_flags = t.readUint32(), e += 4) : this.default_sample_flags = 0\n}),\nBoxParser.createFullBoxCtor("tfra", "TrackFragmentRandomAccessBox",\nfunction(t) {\n\tthis.track_ID = t.readUint32(),\n\tt.readUint24();\n\tvar e = t.readUint8();\n\tthis.length_size_of_traf_num = e >> 4 & 3,\n\tthis.length_size_of_trun_num = e >> 2 & 3,\n\tthis.length_size_of_sample_num = 3 & e,\n\tthis.entries = [];\n\tfor (var i = t.readUint32(), r = 0; r < i; r++) 1 === this.version ? (this.time = t.readUint64(), this.moof_offset = t.readUint64()) : (this.time = t.readUint32(), this.moof_offset = t.readUint32()),\n\tthis.traf_number = t["readUint" + 8 * (this.length_size_of_traf_num + 1)](),\n\tthis.trun_number = t["readUint" + 8 * (this.length_size_of_trun_num + 1)](),\n\tthis.sample_number = t["readUint" + 8 * (this.length_size_of_sample_num + 1)]()\n}),\nBoxParser.createFullBoxCtor("tkhd", "TrackHeaderBox",\nfunction(t) {\n\t1 == this.version ? (this.creation_time = t.readUint64(), this.modification_time = t.readUint64(), this.track_id = t.readUint32(), t.readUint32(), this.duration = t.readUint64()) : (this.creation_time = t.readUint32(), this.modification_time = t.readUint32(), this.track_id = t.readUint32(), t.readUint32(), this.duration = t.readUint32()),\n\tt.readUint32Array(2),\n\tthis.layer = t.readInt16(),\n\tthis.alternate_group = t.readInt16(),\n\tthis.volume = t.readInt16() >> 8,\n\tt.readUint16(),\n\tthis.matrix = t.readInt32Array(9),\n\tthis.width = t.readUint32(),\n\tthis.height = t.readUint32()\n}),\nBoxParser.createBoxCtor("tmax", "hintmaxrelativetime",\nfunction(t) {\n\tthis.time = t.readUint32()\n}),\nBoxParser.createBoxCtor("tmin", "hintminrelativetime",\nfunction(t) {\n\tthis.time = t.readUint32()\n}),\nBoxParser.createBoxCtor("totl", "hintBytesSent",\nfunction(t) {\n\tthis.bytessent = t.readUint32()\n}),\nBoxParser.createBoxCtor("tpay", "hintBytesSent",\nfunction(t) {\n\tthis.bytessent = t.readUint32()\n}),\nBoxParser.createBoxCtor("tpyl", "hintBytesSent",\nfunction(t) {\n\tthis.bytessent = t.readUint64()\n}),\nBoxParser.TrackGroupTypeBox.prototype.parse = function(t) {\n\tthis.parseFullHeader(t),\n\tthis.track_group_id = t.readUint32()\n},\nBoxParser.createTrackGroupCtor("msrc"),\nBoxParser.TrackReferenceTypeBox = function(t, e, i, r) {\n\tBoxParser.Box.call(this, t, e),\n\tthis.hdr_size = i,\n\tthis.start = r\n},\nBoxParser.TrackReferenceTypeBox.prototype = new BoxParser.Box,\nBoxParser.TrackReferenceTypeBox.prototype.parse = function(t) {\n\tthis.track_ids = t.readUint32Array((this.size - this.hdr_size) / 4)\n},\nBoxParser.trefBox.prototype.parse = function(t) {\n\tfor (var e; t.getPosition() < this.start + this.size;) {\n\t\tif ((e = BoxParser.parseOneBox(t, !0, this.size - (t.getPosition() - this.start))).code !== BoxParser.OK) return; (e = new BoxParser.TrackReferenceTypeBox(e.type, e.size, e.hdr_size, e.start)).write === BoxParser.Box.prototype.write && "mdat" !== e.type && (Log.info("BoxParser", "TrackReference " + e.type + " box writing not yet implemented, keeping unparsed data in memory for later write"), e.parseDataAndRewind(t)),\n\t\te.parse(t),\n\t\tthis.boxes.push(e)\n\t}\n},\nBoxParser.createFullBoxCtor("trep", "TrackExtensionPropertiesBox",\nfunction(t) {\n\tfor (this.track_ID = t.readUint32(), this.boxes = []; t.getPosition() < this.start + this.size;) {\n\t\tif (ret = BoxParser.parseOneBox(t, !1, this.size - (t.getPosition() - this.start)), ret.code !== BoxParser.OK) return;\n\t\tbox = ret.box,\n\t\tthis.boxes.push(box)\n\t}\n}),\nBoxParser.createFullBoxCtor("trex", "TrackExtendsBox",\nfunction(t) {\n\tthis.track_id = t.readUint32(),\n\tthis.default_sample_description_index = t.readUint32(),\n\tthis.default_sample_duration = t.readUint32(),\n\tthis.default_sample_size = t.readUint32(),\n\tthis.default_sample_flags = t.readUint32()\n}),\nBoxParser.createBoxCtor("trpy", "hintBytesSent",\nfunction(t) {\n\tthis.bytessent = t.readUint64()\n}),\nBoxParser.createFullBoxCtor("trun", "TrackRunBox",\nfunction(t) {\n\tvar e = 0;\n\tif (this.sample_count = t.readUint32(), e += 4, this.size - this.hdr_size > e && this.flags & BoxParser.TRUN_FLAGS_DATA_OFFSET ? (this.data_offset = t.readInt32(), e += 4) : this.data_offset = 0, this.size - this.hdr_size > e && this.flags & BoxParser.TRUN_FLAGS_FIRST_FLAG ? (this.first_sample_flags = t.readUint32(), e += 4) : this.first_sample_flags = 0, this.sample_duration = [], this.sample_size = [], this.sample_flags = [], this.sample_composition_time_offset = [], this.size - this.hdr_size > e) for (var i = 0; i < this.sample_count; i++) this.flags & BoxParser.TRUN_FLAGS_DURATION && (this.sample_duration[i] = t.readUint32()),\n\tthis.flags & BoxParser.TRUN_FLAGS_SIZE && (this.sample_size[i] = t.readUint32()),\n\tthis.flags & BoxParser.TRUN_FLAGS_FLAGS && (this.sample_flags[i] = t.readUint32()),\n\tthis.flags & BoxParser.TRUN_FLAGS_CTS_OFFSET && (0 === this.version ? this.sample_composition_time_offset[i] = t.readUint32() : this.sample_composition_time_offset[i] = t.readInt32())\n}),\nBoxParser.createFullBoxCtor("tsel", "TrackSelectionBox",\nfunction(t) {\n\tthis.switch_group = t.readUint32();\n\tvar e = (this.size - this.hdr_size - 4) / 4;\n\tthis.attribute_list = [];\n\tfor (var i = 0; i < e; i++) this.attribute_list[i] = t.readUint32()\n}),\nBoxParser.createFullBoxCtor("txtC", "TextConfigBox",\nfunction(t) {\n\tthis.config = t.readCString()\n}),\nBoxParser.createBoxCtor("tyco", "TypeCombinationBox",\nfunction(t) {\n\tvar e = (this.size - this.hdr_size) / 4;\n\tthis.compatible_brands = [];\n\tfor (var i = 0; i < e; i++) this.compatible_brands[i] = t.readString(4)\n}),\nBoxParser.createFullBoxCtor("udes", "UserDescriptionProperty",\nfunction(t) {\n\tthis.lang = t.readCString(),\n\tthis.name = t.readCString(),\n\tthis.description = t.readCString(),\n\tthis.tags = t.readCString()\n}),\nBoxParser.createFullBoxCtor("uncC", "UncompressedFrameConfigBox",\nfunction(t) {\n\tvar e;\n\tif (this.profile = t.readString(4), 1 != this.version && 0 == this.version) {\n\t\tfor (this.component_count = t.readUint32(), this.component_index = [], this.component_bit_depth_minus_one = [], this.component_format = [], this.component_align_size = [], e = 0; e < this.component_count; e++) this.component_index.push(t.readUint16()),\n\t\tthis.component_bit_depth_minus_one.push(t.readUint8()),\n\t\tthis.component_format.push(t.readUint8()),\n\t\tthis.component_align_size.push(t.readUint8());\n\t\tthis.sampling_type = t.readUint8(),\n\t\tthis.interleave_type = t.readUint8(),\n\t\tthis.block_size = t.readUint8();\n\t\tvar i = t.readUint8();\n\t\tthis.component_little_endian = i >> 7 & 1,\n\t\tthis.block_pad_lsb = i >> 6 & 1,\n\t\tthis.block_little_endian = i >> 5 & 1,\n\t\tthis.block_reversed = i >> 4 & 1,\n\t\tthis.pad_unknown = i >> 3 & 1,\n\t\tthis.pixel_size = t.readUint32(),\n\t\tthis.row_align_size = t.readUint32(),\n\t\tthis.tile_align_size = t.readUint32(),\n\t\tthis.num_tile_cols_minus_one = t.readUint32(),\n\t\tthis.num_tile_rows_minus_one = t.readUint32()\n\t}\n}),\nBoxParser.createFullBoxCtor("url ", "DataEntryUrlBox",\nfunction(t) {\n\t1 !== this.flags && (this.location = t.readCString())\n}),\nBoxParser.createFullBoxCtor("urn ", "DataEntryUrnBox",\nfunction(t) {\n\tthis.name = t.readCString(),\n\t0 < this.size - this.hdr_size - this.name.length - 1 && (this.location = t.readCString())\n}),\nBoxParser.createUUIDBox("a5d40b30e81411ddba2f0800200c9a66", "LiveServerManifestBox", !0, !1,\nfunction(t) {\n\tthis.LiveServerManifest = t.readString(this.size - this.hdr_size).replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;").replace(/"/g, "&quot;").replace(/\'/g, "&#039;")\n}),\nBoxParser.createUUIDBox("d08a4f1810f34a82b6c832d8aba183d3", "PiffProtectionSystemSpecificHeaderBox", !0, !1,\nfunction(t) {\n\tthis.system_id = BoxParser.parseHex16(t);\n\tvar e = t.readUint32();\n\t0 < e && (this.data = t.readUint8Array(e))\n}),\nBoxParser.createUUIDBox("a2394f525a9b4f14a2446c427c648df4", "PiffSampleEncryptionBox", !0, !1),\nBoxParser.createUUIDBox("8974dbce7be74c5184f97148f9882554", "PiffTrackEncryptionBox", !0, !1,\nfunction(t) {\n\tthis.default_AlgorithmID = t.readUint24(),\n\tthis.default_IV_size = t.readUint8(),\n\tthis.default_KID = BoxParser.parseHex16(t)\n}),\nBoxParser.createUUIDBox("d4807ef2ca3946958e5426cb9e46a79f", "TfrfBox", !0, !1,\nfunction(t) {\n\tthis.fragment_count = t.readUint8(),\n\tthis.entries = [];\n\tfor (var e = 0; e < this.fragment_count; e++) {\n\t\tvar i = {},\n\t\tr = 0,\n\t\ts = 0,\n\t\ts = 1 === this.version ? (r = t.readUint64(), t.readUint64()) : (r = t.readUint32(), t.readUint32());\n\t\ti.absolute_time = r,\n\t\ti.absolute_duration = s,\n\t\tthis.entries.push(i)\n\t}\n}),\nBoxParser.createUUIDBox("6d1d9b0542d544e680e2141daff757b2", "TfxdBox", !0, !1,\nfunction(t) {\n\t1 === this.version ? (this.absolute_time = t.readUint64(), this.duration = t.readUint64()) : (this.absolute_time = t.readUint32(), this.duration = t.readUint32())\n}),\nBoxParser.createFullBoxCtor("vmhd", "VideoMediaHeaderBox",\nfunction(t) {\n\tthis.graphicsmode = t.readUint16(),\n\tthis.opcolor = t.readUint16Array(3)\n}),\nBoxParser.createFullBoxCtor("vpcC", "VPCodecConfigurationRecord",\nfunction(t) {\n\tvar e;\n\t1 === this.version ? (this.profile = t.readUint8(), this.level = t.readUint8(), e = t.readUint8(), this.bitDepth = e >> 4, this.chromaSubsampling = e >> 1 & 7, this.videoFullRangeFlag = 1 & e, this.colourPrimaries = t.readUint8(), this.transferCharacteristics = t.readUint8(), this.matrixCoefficients = t.readUint8()) : (this.profile = t.readUint8(), this.level = t.readUint8(), e = t.readUint8(), this.bitDepth = e >> 4 & 15, this.colorSpace = 15 & e, e = t.readUint8(), this.chromaSubsampling = e >> 4 & 15, this.transferFunction = e >> 1 & 7, this.videoFullRangeFlag = 1 & e),\n\tthis.codecIntializationDataSize = t.readUint16(),\n\tthis.codecIntializationData = t.readUint8Array(this.codecIntializationDataSize)\n}),\nBoxParser.createBoxCtor("vttC", "WebVTTConfigurationBox",\nfunction(t) {\n\tthis.text = t.readString(this.size - this.hdr_size)\n}),\nBoxParser.createFullBoxCtor("vvcC", "VvcConfigurationBox",\nfunction(t) {\n\tvar e, i = {\n\t\theld_bits: void 0,\n\t\tnum_held_bits: 0,\n\t\tstream_read_1_bytes: function(t) {\n\t\t\tthis.held_bits = t.readUint8(),\n\t\t\tthis.num_held_bits = 8\n\t\t},\n\t\tstream_read_2_bytes: function(t) {\n\t\t\tthis.held_bits = t.readUint16(),\n\t\t\tthis.num_held_bits = 16\n\t\t},\n\t\textract_bits: function(t) {\n\t\t\tvar e = this.held_bits >> this.num_held_bits - t & (1 << t) - 1;\n\t\t\treturn this.num_held_bits -= t,\n\t\t\te\n\t\t}\n\t};\n\tif (i.stream_read_1_bytes(t), i.extract_bits(5), this.lengthSizeMinusOne = i.extract_bits(2), this.ptl_present_flag = i.extract_bits(1), this.ptl_present_flag) {\n\t\tif (i.stream_read_2_bytes(t), this.ols_idx = i.extract_bits(9), this.num_sublayers = i.extract_bits(3), this.constant_frame_rate = i.extract_bits(2), this.chroma_format_idc = i.extract_bits(2), i.stream_read_1_bytes(t), this.bit_depth_minus8 = i.extract_bits(3), i.extract_bits(5), i.stream_read_2_bytes(t), i.extract_bits(2), this.num_bytes_constraint_info = i.extract_bits(6), this.general_profile_idc = i.extract_bits(7), this.general_tier_flag = i.extract_bits(1), this.general_level_idc = t.readUint8(), i.stream_read_1_bytes(t), this.ptl_frame_only_constraint_flag = i.extract_bits(1), this.ptl_multilayer_enabled_flag = i.extract_bits(1), this.general_constraint_info = new Uint8Array(this.num_bytes_constraint_info), this.num_bytes_constraint_info) {\n\t\t\tfor (o = 0; o < this.num_bytes_constraint_info - 1; o++) {\n\t\t\t\tvar r = i.extract_bits(6);\n\t\t\t\ti.stream_read_1_bytes(t);\n\t\t\t\tvar s = i.extract_bits(2);\n\t\t\t\tthis.general_constraint_info[o] = r << 2 | s\n\t\t\t}\n\t\t\tthis.general_constraint_info[this.num_bytes_constraint_info - 1] = i.extract_bits(6)\n\t\t} else i.extract_bits(6);\n\t\tif (1 < this.num_sublayers) {\n\t\t\tfor (i.stream_read_1_bytes(t), this.ptl_sublayer_present_mask = 0, e = this.num_sublayers - 2; 0 <= e; --e) {\n\t\t\t\tvar a = i.extract_bits(1);\n\t\t\t\tthis.ptl_sublayer_present_mask |= a << e\n\t\t\t}\n\t\t\tfor (e = this.num_sublayers; e <= 8 && 1 < this.num_sublayers; ++e) i.extract_bits(1);\n\t\t\tfor (this.sublayer_level_idc = [], e = this.num_sublayers - 2; 0 <= e; --e) this.ptl_sublayer_present_mask & 1 << e && (this.sublayer_level_idc[e] = t.readUint8())\n\t\t}\n\t\tif (this.ptl_num_sub_profiles = t.readUint8(), this.general_sub_profile_idc = [], this.ptl_num_sub_profiles) for (o = 0; o < this.ptl_num_sub_profiles; o++) this.general_sub_profile_idc.push(t.readUint32());\n\t\tthis.max_picture_width = t.readUint16(),\n\t\tthis.max_picture_height = t.readUint16(),\n\t\tthis.avg_frame_rate = t.readUint16()\n\t}\n\tthis.nalu_arrays = [];\n\tfor (var n = t.readUint8(), o = 0; o < n; o++) {\n\t\tvar h = [];\n\t\tthis.nalu_arrays.push(h),\n\t\ti.stream_read_1_bytes(t),\n\t\th.completeness = i.extract_bits(1),\n\t\ti.extract_bits(2),\n\t\th.nalu_type = i.extract_bits(5);\n\t\tvar d = 1;\n\t\tfor (13 != h.nalu_type && 12 != h.nalu_type && (d = t.readUint16()), e = 0; e < d; e++) {\n\t\t\tvar l = t.readUint16();\n\t\t\th.push({\n\t\t\t\tdata: t.readUint8Array(l),\n\t\t\t\tlength: l\n\t\t\t})\n\t\t}\n\t}\n}),\nBoxParser.createFullBoxCtor("vvnC", "VvcNALUConfigBox",\nfunction(t) {\n\tvar e = strm.readUint8();\n\tthis.lengthSizeMinusOne = 3 & e\n}),\nBoxParser.SampleEntry.prototype.isVideo = function() {\n\treturn ! 1\n},\nBoxParser.SampleEntry.prototype.isAudio = function() {\n\treturn ! 1\n},\nBoxParser.SampleEntry.prototype.isSubtitle = function() {\n\treturn ! 1\n},\nBoxParser.SampleEntry.prototype.isMetadata = function() {\n\treturn ! 1\n},\nBoxParser.SampleEntry.prototype.isHint = function() {\n\treturn ! 1\n},\nBoxParser.SampleEntry.prototype.getCodec = function() {\n\treturn this.type.replace(".", "")\n},\nBoxParser.SampleEntry.prototype.getWidth = function() {\n\treturn ""\n},\nBoxParser.SampleEntry.prototype.getHeight = function() {\n\treturn ""\n},\nBoxParser.SampleEntry.prototype.getChannelCount = function() {\n\treturn ""\n},\nBoxParser.SampleEntry.prototype.getSampleRate = function() {\n\treturn ""\n},\nBoxParser.SampleEntry.prototype.getSampleSize = function() {\n\treturn ""\n},\nBoxParser.VisualSampleEntry.prototype.isVideo = function() {\n\treturn ! 0\n},\nBoxParser.VisualSampleEntry.prototype.getWidth = function() {\n\treturn this.width\n},\nBoxParser.VisualSampleEntry.prototype.getHeight = function() {\n\treturn this.height\n},\nBoxParser.AudioSampleEntry.prototype.isAudio = function() {\n\treturn ! 0\n},\nBoxParser.AudioSampleEntry.prototype.getChannelCount = function() {\n\treturn this.channel_count\n},\nBoxParser.AudioSampleEntry.prototype.getSampleRate = function() {\n\treturn this.samplerate\n},\nBoxParser.AudioSampleEntry.prototype.getSampleSize = function() {\n\treturn this.samplesize\n},\nBoxParser.SubtitleSampleEntry.prototype.isSubtitle = function() {\n\treturn ! 0\n},\nBoxParser.MetadataSampleEntry.prototype.isMetadata = function() {\n\treturn ! 0\n},\nBoxParser.decimalToHex = function(t, e) {\n\tvar i = Number(t).toString(16);\n\tfor (e = null == e ? e = 2 : e; i.length < e;) i = "0" + i;\n\treturn i\n},\nBoxParser.avc1SampleEntry.prototype.getCodec = BoxParser.avc2SampleEntry.prototype.getCodec = BoxParser.avc3SampleEntry.prototype.getCodec = BoxParser.avc4SampleEntry.prototype.getCodec = function() {\n\tvar t = BoxParser.SampleEntry.prototype.getCodec.call(this);\n\treturn this.avcC ? t + "." + BoxParser.decimalToHex(this.avcC.AVCProfileIndication) + BoxParser.decimalToHex(this.avcC.profile_compatibility) + BoxParser.decimalToHex(this.avcC.AVCLevelIndication) : t\n},\nBoxParser.hev1SampleEntry.prototype.getCodec = BoxParser.hvc1SampleEntry.prototype.getCodec = function() {\n\tvar t = BoxParser.SampleEntry.prototype.getCodec.call(this);\n\tif (this.hvcC) {\n\t\tswitch (t += ".", this.hvcC.general_profile_space) {\n\t\tcase 0:\n\t\t\tt += "";\n\t\t\tbreak;\n\t\tcase 1:\n\t\t\tt += "A";\n\t\t\tbreak;\n\t\tcase 2:\n\t\t\tt += "B";\n\t\t\tbreak;\n\t\tcase 3:\n\t\t\tt += "C"\n\t\t}\n\t\tt += this.hvcC.general_profile_idc,\n\t\tt += ".";\n\t\tfor (var e = this.hvcC.general_profile_compatibility,\n\t\ti = 0,\n\t\tr = 0; r < 32 && (i |= 1 & e, 31 != r); r++) i <<= 1,\n\t\te >>= 1;\n\t\tt += BoxParser.decimalToHex(i, 0),\n\t\tt += ".",\n\t\t0 === this.hvcC.general_tier_flag ? t += "L": t += "H",\n\t\tt += this.hvcC.general_level_idc;\n\t\tvar s = !1,\n\t\ta = "";\n\t\tfor (r = 5; 0 <= r; r--)(this.hvcC.general_constraint_indicator[r] || s) && (a = "." + BoxParser.decimalToHex(this.hvcC.general_constraint_indicator[r], 0) + a, s = !0);\n\t\tt += a\n\t}\n\treturn t\n},\nBoxParser.vvc1SampleEntry.prototype.getCodec = BoxParser.vvi1SampleEntry.prototype.getCodec = function() {\n\tvar t = BoxParser.SampleEntry.prototype.getCodec.call(this);\n\tif (this.vvcC) {\n\t\tt += "." + this.vvcC.general_profile_idc,\n\t\tthis.vvcC.general_tier_flag ? t += ".H": t += ".L",\n\t\tt += this.vvcC.general_level_idc;\n\t\tvar e = "";\n\t\tif (this.vvcC.general_constraint_info) {\n\t\t\tvar i, r = [],\n\t\t\ts = 0;\n\t\t\tfor (s |= this.vvcC.ptl_frame_only_constraint << 7, s |= this.vvcC.ptl_multilayer_enabled << 6, h = 0; h < this.vvcC.general_constraint_info.length; ++h) s |= this.vvcC.general_constraint_info[h] >> 2 & 63,\n\t\t\tr.push(s),\n\t\t\ts && (i = h),\n\t\t\ts = this.vvcC.general_constraint_info[h] >> 2 & 3;\n\t\t\tif (void 0 === i) e = ".CA";\n\t\t\telse {\n\t\t\t\te = ".C";\n\t\t\t\tfor (var a = "ABCDEFGHIJKLMNOPQRSTUVWXYZ234567",\n\t\t\t\tn = 0,\n\t\t\t\to = 0,\n\t\t\t\th = 0; h <= i; ++h) for (n = n << 8 | r[h], o += 8; 5 <= o;) e += a[n >> o - 5 & 31],\n\t\t\t\tn &= (1 << (o -= 5)) - 1;\n\t\t\t\to && (e += a[31 & (n <<= 5 - o)])\n\t\t\t}\n\t\t}\n\t\tt += e\n\t}\n\treturn t\n},\nBoxParser.mp4aSampleEntry.prototype.getCodec = function() {\n\tvar t = BoxParser.SampleEntry.prototype.getCodec.call(this);\n\tif (this.esds && this.esds.esd) {\n\t\tvar e = this.esds.esd.getOTI(),\n\t\ti = this.esds.esd.getAudioConfig();\n\t\treturn t + "." + BoxParser.decimalToHex(e) + (i ? "." + i: "")\n\t}\n\treturn t\n},\nBoxParser.stxtSampleEntry.prototype.getCodec = function() {\n\tvar t = BoxParser.SampleEntry.prototype.getCodec.call(this);\n\treturn this.mime_format ? t + "." + this.mime_format: t\n},\nBoxParser.vp08SampleEntry.prototype.getCodec = BoxParser.vp09SampleEntry.prototype.getCodec = function() {\n\tvar t = BoxParser.SampleEntry.prototype.getCodec.call(this),\n\te = this.vpcC.level;\n\t0 == e && (e = "00");\n\tvar i = this.vpcC.bitDepth;\n\treturn 8 == i && (i = "08"),\n\tt + ".0" + this.vpcC.profile + "." + e + "." + i\n},\nBoxParser.av01SampleEntry.prototype.getCodec = function() {\n\tvar t, e = BoxParser.SampleEntry.prototype.getCodec.call(this),\n\ti = this.av1C.seq_level_idx_0;\n\treturn i < 10 && (i = "0" + i),\n\t2 === this.av1C.seq_profile && 1 === this.av1C.high_bitdepth ? t = 1 === this.av1C.twelve_bit ? "12": "10": this.av1C.seq_profile <= 2 && (t = 1 === this.av1C.high_bitdepth ? "10": "08"),\n\te + "." + this.av1C.seq_profile + "." + i + (this.av1C.seq_tier_0 ? "H": "M") + "." + t\n},\nBoxParser.Box.prototype.writeHeader = function(t, e) {\n\tthis.size += 8,\n\tthis.size > MAX_SIZE && (this.size += 8),\n\t"uuid" === this.type && (this.size += 16),\n\tLog.debug("BoxWriter", "Writing box " + this.type + " of size: " + this.size + " at position " + t.getPosition() + (e || "")),\n\tthis.size > MAX_SIZE ? t.writeUint32(1) : (this.sizePosition = t.getPosition(), t.writeUint32(this.size)),\n\tt.writeString(this.type, null, 4),\n\t"uuid" === this.type && t.writeUint8Array(this.uuid),\n\tthis.size > MAX_SIZE && t.writeUint64(this.size)\n},\nBoxParser.FullBox.prototype.writeHeader = function(t) {\n\tthis.size += 4,\n\tBoxParser.Box.prototype.writeHeader.call(this, t, " v=" + this.version + " f=" + this.flags),\n\tt.writeUint8(this.version),\n\tt.writeUint24(this.flags)\n},\nBoxParser.Box.prototype.write = function(t) {\n\t"mdat" === this.type ? this.data && (this.size = this.data.length, this.writeHeader(t), t.writeUint8Array(this.data)) : (this.size = this.data ? this.data.length: 0, this.writeHeader(t), this.data && t.writeUint8Array(this.data))\n},\nBoxParser.ContainerBox.prototype.write = function(t) {\n\tthis.size = 0,\n\tthis.writeHeader(t);\n\tfor (var e = 0; e < this.boxes.length; e++) this.boxes[e] && (this.boxes[e].write(t), this.size += this.boxes[e].size);\n\tLog.debug("BoxWriter", "Adjusting box " + this.type + " with new size " + this.size),\n\tt.adjustUint32(this.sizePosition, this.size)\n},\nBoxParser.TrackReferenceTypeBox.prototype.write = function(t) {\n\tthis.size = 4 * this.track_ids.length,\n\tthis.writeHeader(t),\n\tt.writeUint32Array(this.track_ids)\n},\nBoxParser.avcCBox.prototype.write = function(t) {\n\tvar e;\n\tfor (this.size = 7, e = 0; e < this.SPS.length; e++) this.size += 2 + this.SPS[e].length;\n\tfor (e = 0; e < this.PPS.length; e++) this.size += 2 + this.PPS[e].length;\n\tfor (this.ext && (this.size += this.ext.length), this.writeHeader(t), t.writeUint8(this.configurationVersion), t.writeUint8(this.AVCProfileIndication), t.writeUint8(this.profile_compatibility), t.writeUint8(this.AVCLevelIndication), t.writeUint8(this.lengthSizeMinusOne + 252), t.writeUint8(this.SPS.length + 224), e = 0; e < this.SPS.length; e++) t.writeUint16(this.SPS[e].length),\n\tt.writeUint8Array(this.SPS[e].nalu);\n\tfor (t.writeUint8(this.PPS.length), e = 0; e < this.PPS.length; e++) t.writeUint16(this.PPS[e].length),\n\tt.writeUint8Array(this.PPS[e].nalu);\n\tthis.ext && t.writeUint8Array(this.ext)\n},\nBoxParser.co64Box.prototype.write = function(t) {\n\tvar e;\n\tfor (this.version = 0, this.flags = 0, this.size = 4 + 8 * this.chunk_offsets.length, this.writeHeader(t), t.writeUint32(this.chunk_offsets.length), e = 0; e < this.chunk_offsets.length; e++) t.writeUint64(this.chunk_offsets[e])\n},\nBoxParser.cslgBox.prototype.write = function(t) {\n\tthis.version = 0,\n\tthis.flags = 0,\n\tthis.size = 20,\n\tthis.writeHeader(t),\n\tt.writeInt32(this.compositionToDTSShift),\n\tt.writeInt32(this.leastDecodeToDisplayDelta),\n\tt.writeInt32(this.greatestDecodeToDisplayDelta),\n\tt.writeInt32(this.compositionStartTime),\n\tt.writeInt32(this.compositionEndTime)\n},\nBoxParser.cttsBox.prototype.write = function(t) {\n\tvar e;\n\tfor (this.version = 0, this.flags = 0, this.size = 4 + 8 * this.sample_counts.length, this.writeHeader(t), t.writeUint32(this.sample_counts.length), e = 0; e < this.sample_counts.length; e++) t.writeUint32(this.sample_counts[e]),\n\t1 === this.version ? t.writeInt32(this.sample_offsets[e]) : t.writeUint32(this.sample_offsets[e])\n},\nBoxParser.drefBox.prototype.write = function(t) {\n\tthis.version = 0,\n\tthis.flags = 0,\n\tthis.size = 4,\n\tthis.writeHeader(t),\n\tt.writeUint32(this.entries.length);\n\tfor (var e = 0; e < this.entries.length; e++) this.entries[e].write(t),\n\tthis.size += this.entries[e].size;\n\tLog.debug("BoxWriter", "Adjusting box " + this.type + " with new size " + this.size),\n\tt.adjustUint32(this.sizePosition, this.size)\n},\nBoxParser.elngBox.prototype.write = function(t) {\n\tthis.version = 0,\n\tthis.flags = 0,\n\tthis.size = this.extended_language.length,\n\tthis.writeHeader(t),\n\tt.writeString(this.extended_language)\n},\nBoxParser.elstBox.prototype.write = function(t) {\n\tthis.version = 0,\n\tthis.flags = 0,\n\tthis.size = 4 + 12 * this.entries.length,\n\tthis.writeHeader(t),\n\tt.writeUint32(this.entries.length);\n\tfor (var e = 0; e < this.entries.length; e++) {\n\t\tvar i = this.entries[e];\n\t\tt.writeUint32(i.segment_duration),\n\t\tt.writeInt32(i.media_time),\n\t\tt.writeInt16(i.media_rate_integer),\n\t\tt.writeInt16(i.media_rate_fraction)\n\t}\n},\nBoxParser.emsgBox.prototype.write = function(t) {\n\tthis.version = 0,\n\tthis.flags = 0,\n\tthis.size = 16 + this.message_data.length + (this.scheme_id_uri.length + 1) + (this.value.length + 1),\n\tthis.writeHeader(t),\n\tt.writeCString(this.scheme_id_uri),\n\tt.writeCString(this.value),\n\tt.writeUint32(this.timescale),\n\tt.writeUint32(this.presentation_time_delta),\n\tt.writeUint32(this.event_duration),\n\tt.writeUint32(this.id),\n\tt.writeUint8Array(this.message_data)\n},\nBoxParser.ftypBox.prototype.write = function(t) {\n\tthis.size = 8 + 4 * this.compatible_brands.length,\n\tthis.writeHeader(t),\n\tt.writeString(this.major_brand, null, 4),\n\tt.writeUint32(this.minor_version);\n\tfor (var e = 0; e < this.compatible_brands.length; e++) t.writeString(this.compatible_brands[e], null, 4)\n},\nBoxParser.hdlrBox.prototype.write = function(t) {\n\tthis.size = 20 + this.name.length + 1,\n\tthis.version = 0,\n\tthis.flags = 0,\n\tthis.writeHeader(t),\n\tt.writeUint32(0),\n\tt.writeString(this.handler, null, 4),\n\tt.writeUint32(0),\n\tt.writeUint32(0),\n\tt.writeUint32(0),\n\tt.writeCString(this.name)\n},\nBoxParser.hvcCBox.prototype.write = function(t) {\n\tvar e, i;\n\tfor (this.size = 23, e = 0; e < this.nalu_arrays.length; e++) for (this.size += 3, i = 0; i < this.nalu_arrays[e].length; i++) this.size += 2 + this.nalu_arrays[e][i].data.length;\n\tfor (this.writeHeader(t), t.writeUint8(this.configurationVersion), t.writeUint8((this.general_profile_space << 6) + (this.general_tier_flag << 5) + this.general_profile_idc), t.writeUint32(this.general_profile_compatibility), t.writeUint8Array(this.general_constraint_indicator), t.writeUint8(this.general_level_idc), t.writeUint16(this.min_spatial_segmentation_idc + (15 << 24)), t.writeUint8(this.parallelismType + 252), t.writeUint8(this.chroma_format_idc + 252), t.writeUint8(this.bit_depth_luma_minus8 + 248), t.writeUint8(this.bit_depth_chroma_minus8 + 248), t.writeUint16(this.avgFrameRate), t.writeUint8((this.constantFrameRate << 6) + (this.numTemporalLayers << 3) + (this.temporalIdNested << 2) + this.lengthSizeMinusOne), t.writeUint8(this.nalu_arrays.length), e = 0; e < this.nalu_arrays.length; e++) for (t.writeUint8((this.nalu_arrays[e].completeness << 7) + this.nalu_arrays[e].nalu_type), t.writeUint16(this.nalu_arrays[e].length), i = 0; i < this.nalu_arrays[e].length; i++) t.writeUint16(this.nalu_arrays[e][i].data.length),\n\tt.writeUint8Array(this.nalu_arrays[e][i].data)\n},\nBoxParser.kindBox.prototype.write = function(t) {\n\tthis.version = 0,\n\tthis.flags = 0,\n\tthis.size = this.schemeURI.length + 1 + (this.value.length + 1),\n\tthis.writeHeader(t),\n\tt.writeCString(this.schemeURI),\n\tt.writeCString(this.value)\n},\nBoxParser.mdhdBox.prototype.write = function(t) {\n\tthis.size = 20,\n\tthis.flags = 0,\n\tthis.version = 0,\n\tthis.writeHeader(t),\n\tt.writeUint32(this.creation_time),\n\tt.writeUint32(this.modification_time),\n\tt.writeUint32(this.timescale),\n\tt.writeUint32(this.duration),\n\tt.writeUint16(this.language),\n\tt.writeUint16(0)\n},\nBoxParser.mehdBox.prototype.write = function(t) {\n\tthis.version = 0,\n\tthis.flags = 0,\n\tthis.size = 4,\n\tthis.writeHeader(t),\n\tt.writeUint32(this.fragment_duration)\n},\nBoxParser.mfhdBox.prototype.write = function(t) {\n\tthis.version = 0,\n\tthis.flags = 0,\n\tthis.size = 4,\n\tthis.writeHeader(t),\n\tt.writeUint32(this.sequence_number)\n},\nBoxParser.mvhdBox.prototype.write = function(t) {\n\tthis.version = 0,\n\tthis.flags = 0,\n\tthis.size = 96,\n\tthis.writeHeader(t),\n\tt.writeUint32(this.creation_time),\n\tt.writeUint32(this.modification_time),\n\tt.writeUint32(this.timescale),\n\tt.writeUint32(this.duration),\n\tt.writeUint32(this.rate),\n\tt.writeUint16(this.volume << 8),\n\tt.writeUint16(0),\n\tt.writeUint32(0),\n\tt.writeUint32(0),\n\tt.writeUint32Array(this.matrix),\n\tt.writeUint32(0),\n\tt.writeUint32(0),\n\tt.writeUint32(0),\n\tt.writeUint32(0),\n\tt.writeUint32(0),\n\tt.writeUint32(0),\n\tt.writeUint32(this.next_track_id)\n},\nBoxParser.SampleEntry.prototype.writeHeader = function(t) {\n\tthis.size = 8,\n\tBoxParser.Box.prototype.writeHeader.call(this, t),\n\tt.writeUint8(0),\n\tt.writeUint8(0),\n\tt.writeUint8(0),\n\tt.writeUint8(0),\n\tt.writeUint8(0),\n\tt.writeUint8(0),\n\tt.writeUint16(this.data_reference_index)\n},\nBoxParser.SampleEntry.prototype.writeFooter = function(t) {\n\tfor (var e = 0; e < this.boxes.length; e++) this.boxes[e].write(t),\n\tthis.size += this.boxes[e].size;\n\tLog.debug("BoxWriter", "Adjusting box " + this.type + " with new size " + this.size),\n\tt.adjustUint32(this.sizePosition, this.size)\n},\nBoxParser.SampleEntry.prototype.write = function(t) {\n\tthis.writeHeader(t),\n\tt.writeUint8Array(this.data),\n\tthis.size += this.data.length,\n\tLog.debug("BoxWriter", "Adjusting box " + this.type + " with new size " + this.size),\n\tt.adjustUint32(this.sizePosition, this.size)\n},\nBoxParser.VisualSampleEntry.prototype.write = function(t) {\n\tthis.writeHeader(t),\n\tthis.size += 70,\n\tt.writeUint16(0),\n\tt.writeUint16(0),\n\tt.writeUint32(0),\n\tt.writeUint32(0),\n\tt.writeUint32(0),\n\tt.writeUint16(this.width),\n\tt.writeUint16(this.height),\n\tt.writeUint32(this.horizresolution),\n\tt.writeUint32(this.vertresolution),\n\tt.writeUint32(0),\n\tt.writeUint16(this.frame_count),\n\tt.writeUint8(Math.min(31, this.compressorname.length)),\n\tt.writeString(this.compressorname, null, 31),\n\tt.writeUint16(this.depth),\n\tt.writeInt16(-1),\n\tthis.writeFooter(t)\n},\nBoxParser.AudioSampleEntry.prototype.write = function(t) {\n\tthis.writeHeader(t),\n\tthis.size += 20,\n\tt.writeUint32(0),\n\tt.writeUint32(0),\n\tt.writeUint16(this.channel_count),\n\tt.writeUint16(this.samplesize),\n\tt.writeUint16(0),\n\tt.writeUint16(0),\n\tt.writeUint32(this.samplerate << 16),\n\tthis.writeFooter(t)\n},\nBoxParser.stppSampleEntry.prototype.write = function(t) {\n\tthis.writeHeader(t),\n\tthis.size += this.namespace.length + 1 + this.schema_location.length + 1 + this.auxiliary_mime_types.length + 1,\n\tt.writeCString(this.namespace),\n\tt.writeCString(this.schema_location),\n\tt.writeCString(this.auxiliary_mime_types),\n\tthis.writeFooter(t)\n},\nBoxParser.SampleGroupEntry.prototype.write = function(t) {\n\tt.writeUint8Array(this.data)\n},\nBoxParser.sbgpBox.prototype.write = function(t) {\n\tthis.version = 1,\n\tthis.flags = 0,\n\tthis.size = 12 + 8 * this.entries.length,\n\tthis.writeHeader(t),\n\tt.writeString(this.grouping_type, null, 4),\n\tt.writeUint32(this.grouping_type_parameter),\n\tt.writeUint32(this.entries.length);\n\tfor (var e = 0; e < this.entries.length; e++) {\n\t\tvar i = this.entries[e];\n\t\tt.writeInt32(i.sample_count),\n\t\tt.writeInt32(i.group_description_index)\n\t}\n},\nBoxParser.sgpdBox.prototype.write = function(t) {\n\tvar e, i;\n\tfor (this.flags = 0, this.size = 12, e = 0; e < this.entries.length; e++) i = this.entries[e],\n\t1 === this.version && (0 === this.default_length && (this.size += 4), this.size += i.data.length);\n\tfor (this.writeHeader(t), t.writeString(this.grouping_type, null, 4), 1 === this.version && t.writeUint32(this.default_length), 2 <= this.version && t.writeUint32(this.default_sample_description_index), t.writeUint32(this.entries.length), e = 0; e < this.entries.length; e++) i = this.entries[e],\n\t1 === this.version && 0 === this.default_length && t.writeUint32(i.description_length),\n\ti.write(t)\n},\nBoxParser.sidxBox.prototype.write = function(t) {\n\tthis.version = 0,\n\tthis.flags = 0,\n\tthis.size = 20 + 12 * this.references.length,\n\tthis.writeHeader(t),\n\tt.writeUint32(this.reference_ID),\n\tt.writeUint32(this.timescale),\n\tt.writeUint32(this.earliest_presentation_time),\n\tt.writeUint32(this.first_offset),\n\tt.writeUint16(0),\n\tt.writeUint16(this.references.length);\n\tfor (var e = 0; e < this.references.length; e++) {\n\t\tvar i = this.references[e];\n\t\tt.writeUint32(i.reference_type << 31 | i.referenced_size),\n\t\tt.writeUint32(i.subsegment_duration),\n\t\tt.writeUint32(i.starts_with_SAP << 31 | i.SAP_type << 28 | i.SAP_delta_time)\n\t}\n},\nBoxParser.smhdBox.prototype.write = function(t) {\n\tthis.version = 0,\n\tthis.flags = 1,\n\tthis.size = 4,\n\tthis.writeHeader(t),\n\tt.writeUint16(this.balance),\n\tt.writeUint16(0)\n},\nBoxParser.stcoBox.prototype.write = function(t) {\n\tthis.version = 0,\n\tthis.flags = 0,\n\tthis.size = 4 + 4 * this.chunk_offsets.length,\n\tthis.writeHeader(t),\n\tt.writeUint32(this.chunk_offsets.length),\n\tt.writeUint32Array(this.chunk_offsets)\n},\nBoxParser.stscBox.prototype.write = function(t) {\n\tvar e;\n\tfor (this.version = 0, this.flags = 0, this.size = 4 + 12 * this.first_chunk.length, this.writeHeader(t), t.writeUint32(this.first_chunk.length), e = 0; e < this.first_chunk.length; e++) t.writeUint32(this.first_chunk[e]),\n\tt.writeUint32(this.samples_per_chunk[e]),\n\tt.writeUint32(this.sample_description_index[e])\n},\nBoxParser.stsdBox.prototype.write = function(t) {\n\tvar e;\n\tfor (this.version = 0, this.flags = 0, this.size = 0, this.writeHeader(t), t.writeUint32(this.entries.length), this.size += 4, e = 0; e < this.entries.length; e++) this.entries[e].write(t),\n\tthis.size += this.entries[e].size;\n\tLog.debug("BoxWriter", "Adjusting box " + this.type + " with new size " + this.size),\n\tt.adjustUint32(this.sizePosition, this.size)\n},\nBoxParser.stshBox.prototype.write = function(t) {\n\tvar e;\n\tfor (this.version = 0, this.flags = 0, this.size = 4 + 8 * this.shadowed_sample_numbers.length, this.writeHeader(t), t.writeUint32(this.shadowed_sample_numbers.length), e = 0; e < this.shadowed_sample_numbers.length; e++) t.writeUint32(this.shadowed_sample_numbers[e]),\n\tt.writeUint32(this.sync_sample_numbers[e])\n},\nBoxParser.stssBox.prototype.write = function(t) {\n\tthis.version = 0,\n\tthis.flags = 0,\n\tthis.size = 4 + 4 * this.sample_numbers.length,\n\tthis.writeHeader(t),\n\tt.writeUint32(this.sample_numbers.length),\n\tt.writeUint32Array(this.sample_numbers)\n},\nBoxParser.stszBox.prototype.write = function(t) {\n\tvar e, i = !0;\n\tif (this.version = 0, (this.flags = 0) < this.sample_sizes.length) for (e = 0; e + 1 < this.sample_sizes.length;) {\n\t\tif (this.sample_sizes[e + 1] !== this.sample_sizes[0]) {\n\t\t\ti = !1;\n\t\t\tbreak\n\t\t}\n\t\te++\n\t} else i = !1;\n\tthis.size = 8,\n\ti || (this.size += 4 * this.sample_sizes.length),\n\tthis.writeHeader(t),\n\ti ? t.writeUint32(this.sample_sizes[0]) : t.writeUint32(0),\n\tt.writeUint32(this.sample_sizes.length),\n\ti || t.writeUint32Array(this.sample_sizes)\n},\nBoxParser.sttsBox.prototype.write = function(t) {\n\tvar e;\n\tfor (this.version = 0, this.flags = 0, this.size = 4 + 8 * this.sample_counts.length, this.writeHeader(t), t.writeUint32(this.sample_counts.length), e = 0; e < this.sample_counts.length; e++) t.writeUint32(this.sample_counts[e]),\n\tt.writeUint32(this.sample_deltas[e])\n},\nBoxParser.tfdtBox.prototype.write = function(t) {\n\tvar e = Math.pow(2, 32) - 1;\n\tthis.version = this.baseMediaDecodeTime > e ? 1 : 0,\n\tthis.flags = 0,\n\tthis.size = 4,\n\t1 === this.version && (this.size += 4),\n\tthis.writeHeader(t),\n\t1 === this.version ? t.writeUint64(this.baseMediaDecodeTime) : t.writeUint32(this.baseMediaDecodeTime)\n},\nBoxParser.tfhdBox.prototype.write = function(t) {\n\tthis.version = 0,\n\tthis.size = 4,\n\tthis.flags & BoxParser.TFHD_FLAG_BASE_DATA_OFFSET && (this.size += 8),\n\tthis.flags & BoxParser.TFHD_FLAG_SAMPLE_DESC && (this.size += 4),\n\tthis.flags & BoxParser.TFHD_FLAG_SAMPLE_DUR && (this.size += 4),\n\tthis.flags & BoxParser.TFHD_FLAG_SAMPLE_SIZE && (this.size += 4),\n\tthis.flags & BoxParser.TFHD_FLAG_SAMPLE_FLAGS && (this.size += 4),\n\tthis.writeHeader(t),\n\tt.writeUint32(this.track_id),\n\tthis.flags & BoxParser.TFHD_FLAG_BASE_DATA_OFFSET && t.writeUint64(this.base_data_offset),\n\tthis.flags & BoxParser.TFHD_FLAG_SAMPLE_DESC && t.writeUint32(this.default_sample_description_index),\n\tthis.flags & BoxParser.TFHD_FLAG_SAMPLE_DUR && t.writeUint32(this.default_sample_duration),\n\tthis.flags & BoxParser.TFHD_FLAG_SAMPLE_SIZE && t.writeUint32(this.default_sample_size),\n\tthis.flags & BoxParser.TFHD_FLAG_SAMPLE_FLAGS && t.writeUint32(this.default_sample_flags)\n},\nBoxParser.tkhdBox.prototype.write = function(t) {\n\tthis.version = 0,\n\tthis.size = 80,\n\tthis.writeHeader(t),\n\tt.writeUint32(this.creation_time),\n\tt.writeUint32(this.modification_time),\n\tt.writeUint32(this.track_id),\n\tt.writeUint32(0),\n\tt.writeUint32(this.duration),\n\tt.writeUint32(0),\n\tt.writeUint32(0),\n\tt.writeInt16(this.layer),\n\tt.writeInt16(this.alternate_group),\n\tt.writeInt16(this.volume << 8),\n\tt.writeUint16(0),\n\tt.writeInt32Array(this.matrix),\n\tt.writeUint32(this.width),\n\tt.writeUint32(this.height)\n},\nBoxParser.trexBox.prototype.write = function(t) {\n\tthis.version = 0,\n\tthis.flags = 0,\n\tthis.size = 20,\n\tthis.writeHeader(t),\n\tt.writeUint32(this.track_id),\n\tt.writeUint32(this.default_sample_description_index),\n\tt.writeUint32(this.default_sample_duration),\n\tt.writeUint32(this.default_sample_size),\n\tt.writeUint32(this.default_sample_flags)\n},\nBoxParser.trunBox.prototype.write = function(t) {\n\tthis.version = 0,\n\tthis.size = 4,\n\tthis.flags & BoxParser.TRUN_FLAGS_DATA_OFFSET && (this.size += 4),\n\tthis.flags & BoxParser.TRUN_FLAGS_FIRST_FLAG && (this.size += 4),\n\tthis.flags & BoxParser.TRUN_FLAGS_DURATION && (this.size += 4 * this.sample_duration.length),\n\tthis.flags & BoxParser.TRUN_FLAGS_SIZE && (this.size += 4 * this.sample_size.length),\n\tthis.flags & BoxParser.TRUN_FLAGS_FLAGS && (this.size += 4 * this.sample_flags.length),\n\tthis.flags & BoxParser.TRUN_FLAGS_CTS_OFFSET && (this.size += 4 * this.sample_composition_time_offset.length),\n\tthis.writeHeader(t),\n\tt.writeUint32(this.sample_count),\n\tthis.flags & BoxParser.TRUN_FLAGS_DATA_OFFSET && (this.data_offset_position = t.getPosition(), t.writeInt32(this.data_offset)),\n\tthis.flags & BoxParser.TRUN_FLAGS_FIRST_FLAG && t.writeUint32(this.first_sample_flags);\n\tfor (var e = 0; e < this.sample_count; e++) this.flags & BoxParser.TRUN_FLAGS_DURATION && t.writeUint32(this.sample_duration[e]),\n\tthis.flags & BoxParser.TRUN_FLAGS_SIZE && t.writeUint32(this.sample_size[e]),\n\tthis.flags & BoxParser.TRUN_FLAGS_FLAGS && t.writeUint32(this.sample_flags[e]),\n\tthis.flags & BoxParser.TRUN_FLAGS_CTS_OFFSET && (0 === this.version ? t.writeUint32(this.sample_composition_time_offset[e]) : t.writeInt32(this.sample_composition_time_offset[e]))\n},\nBoxParser["url Box"].prototype.write = function(t) {\n\tthis.version = 0,\n\tthis.location ? (this.flags = 0, this.size = this.location.length + 1) : (this.flags = 1, this.size = 0),\n\tthis.writeHeader(t),\n\tthis.location && t.writeCString(this.location)\n},\nBoxParser["urn Box"].prototype.write = function(t) {\n\tthis.version = 0,\n\tthis.flags = 0,\n\tthis.size = this.name.length + 1 + (this.location ? this.location.length + 1 : 0),\n\tthis.writeHeader(t),\n\tt.writeCString(this.name),\n\tthis.location && t.writeCString(this.location)\n},\nBoxParser.vmhdBox.prototype.write = function(t) {\n\tthis.version = 0,\n\tthis.flags = 1,\n\tthis.size = 8,\n\tthis.writeHeader(t),\n\tt.writeUint16(this.graphicsmode),\n\tt.writeUint16Array(this.opcolor)\n},\nBoxParser.cttsBox.prototype.unpack = function(t) {\n\tfor (var e, i = 0,\n\tr = 0; r < this.sample_counts.length; r++) for (e = 0; e < this.sample_counts[r]; e++) t[i].pts = t[i].dts + this.sample_offsets[r],\n\ti++\n},\nBoxParser.sttsBox.prototype.unpack = function(t) {\n\tfor (var e, i = 0,\n\tr = 0; r < this.sample_counts.length; r++) for (e = 0; e < this.sample_counts[r]; e++) t[i].dts = 0 === i ? 0 : t[i - 1].dts + this.sample_deltas[r],\n\ti++\n},\nBoxParser.stcoBox.prototype.unpack = function(t) {\n\tfor (var e = 0; e < this.chunk_offsets.length; e++) t[e].offset = this.chunk_offsets[e]\n},\nBoxParser.stscBox.prototype.unpack = function(t) {\n\tfor (var e, i, r = 0,\n\ts = 0,\n\ta = 0; a < this.first_chunk.length; a++) for (e = 0; e < (a + 1 < this.first_chunk.length ? this.first_chunk[a + 1] : 1 / 0); e++) for (s++, i = 0; i < this.samples_per_chunk[a]; i++) {\n\t\tif (!t[r]) return;\n\t\tt[r].description_index = this.sample_description_index[a],\n\t\tt[r].chunk_index = s,\n\t\tr++\n\t}\n},\nBoxParser.stszBox.prototype.unpack = function(t) {\n\tfor (var e = 0; e < this.sample_sizes.length; e++) t[e].size = this.sample_sizes[e]\n},\nBoxParser.DIFF_BOXES_PROP_NAMES = ["boxes", "entries", "references", "subsamples", "items", "item_infos", "extents", "associations", "subsegments", "ranges", "seekLists", "seekPoints", "esd", "levels"],\nBoxParser.DIFF_PRIMITIVE_ARRAY_PROP_NAMES = ["compatible_brands", "matrix", "opcolor", "sample_counts", "sample_deltas", "first_chunk", "samples_per_chunk", "sample_sizes", "chunk_offsets", "sample_offsets", "sample_description_index", "sample_duration"],\nBoxParser.boxEqualFields = function(t, e) {\n\tif (t && !e) return ! 1;\n\tfor (var i in t) if (! (-1 < BoxParser.DIFF_BOXES_PROP_NAMES.indexOf(i) || t[i] instanceof BoxParser.Box || e[i] instanceof BoxParser.Box || void 0 === t[i] || void 0 === e[i] || "function" == typeof t[i] || "function" == typeof e[i] || t.subBoxNames && -1 < t.subBoxNames.indexOf(i.slice(0, 4)) || e.subBoxNames && -1 < e.subBoxNames.indexOf(i.slice(0, 4)) || "data" === i || "start" === i || "size" === i || "creation_time" === i || "modification_time" === i || -1 < BoxParser.DIFF_PRIMITIVE_ARRAY_PROP_NAMES.indexOf(i) || t[i] === e[i])) return ! 1;\n\treturn ! 0\n},\nBoxParser.boxEqual = function(t, e) {\n\tif (!BoxParser.boxEqualFields(t, e)) return ! 1;\n\tfor (var i = 0; i < BoxParser.DIFF_BOXES_PROP_NAMES.length; i++) {\n\t\tvar r = BoxParser.DIFF_BOXES_PROP_NAMES[i];\n\t\tif (t[r] && e[r] && !BoxParser.boxEqual(t[r], e[r])) return ! 1\n\t}\n\treturn ! 0\n};\nvar VTTin4Parser = function() {};\nVTTin4Parser.prototype.parseSample = function(t) {\n\tfor (var e, i = new MP4BoxStream(t.buffer), r = []; ! i.isEos();)(e = BoxParser.parseOneBox(i, !1)).code === BoxParser.OK && "vttc" === e.box.type && r.push(e.box);\n\treturn r\n},\nVTTin4Parser.prototype.getText = function(t, e, i) {\n\tfunction s(t, e, i) {\n\t\treturn i = i || "0",\n\t\t(t += "").length >= e ? t: new Array(e - t.length + 1).join(i) + t\n\t}\n\tfunction r(t) {\n\t\tvar e = Math.floor(t / 3600),\n\t\ti = Math.floor((t - 3600 * e) / 60),\n\t\tr = Math.floor(t - 3600 * e - 60 * i),\n\t\tt = Math.floor(1e3 * (t - 3600 * e - 60 * i - r));\n\t\treturn s(e, 2) + ":" + s(i, 2) + ":" + s(r, 2) + "." + s(t, 3)\n\t}\n\tfor (var a = this.parseSample(i), n = "", o = 0; o < a.length; o++) {\n\t\tvar h = a[o];\n\t\tn += r(t) + " --\\x3e " + r(e) + "\\r\\n",\n\t\tn += h.payl.text\n\t}\n\treturn n\n};\nvar XMLSubtitlein4Parser = function() {};\nXMLSubtitlein4Parser.prototype.parseSample = function(t) {\n\tvar e, i = {\n\t\tresources: []\n\t},\n\tr = new MP4BoxStream(t.data.buffer);\n\tif (t.subsamples && 0 !== t.subsamples.length) {\n\t\tif (i.documentString = r.readString(t.subsamples[0].size), 1 < t.subsamples.length) for (e = 1; e < t.subsamples.length; e++) i.resources[e] = r.readUint8Array(t.subsamples[e].size)\n\t} else i.documentString = r.readString(t.data.length);\n\treturn "undefined" != typeof DOMParser && (i.document = (new DOMParser).parseFromString(i.documentString, "application/xml")),\n\ti\n};\nvar Textin4Parser = function() {};\nTextin4Parser.prototype.parseSample = function(t) {\n\treturn new MP4BoxStream(t.data.buffer).readString(t.data.length)\n},\nTextin4Parser.prototype.parseConfig = function(t) {\n\tt = new MP4BoxStream(t.buffer);\n\treturn t.readUint32(),\n\tt.readCString()\n},\n"undefined" != typeof exports && (exports.VTTin4Parser = VTTin4Parser, exports.XMLSubtitlein4Parser = XMLSubtitlein4Parser, exports.Textin4Parser = Textin4Parser);\nvar ISOFile = function(t) {\n\tthis.stream = t || new MultiBufferStream,\n\tthis.boxes = [],\n\tthis.mdats = [],\n\tthis.moofs = [],\n\tthis.isProgressive = !1,\n\tthis.moovStartFound = !1,\n\tthis.onMoovStart = null,\n\tthis.moovStartSent = !1,\n\tthis.onReady = null,\n\tthis.readySent = !1,\n\tthis.onSegment = null,\n\tthis.onSamples = null,\n\tthis.onError = null,\n\tthis.sampleListBuilt = !1,\n\tthis.fragmentedTracks = [],\n\tthis.extractedTracks = [],\n\tthis.isFragmentationInitialized = !1,\n\tthis.sampleProcessingStarted = !1,\n\tthis.nextMoofNumber = 0,\n\tthis.itemListBuilt = !1,\n\tthis.items = [],\n\tthis.entity_groups = [],\n\tthis.onSidx = null,\n\tthis.sidxSent = !1\n};\nISOFile.prototype.setSegmentOptions = function(t, e, i) {\n\tvar r, s = this.getTrackById(t);\n\ts && (r = {},\n\tthis.fragmentedTracks.push(r), r.id = t, r.user = e, (r.trak = s).nextSample = 0, r.segmentStream = null, r.nb_samples = 1e3, r.rapAlignement = !0, i && (i.nbSamples && (r.nb_samples = i.nbSamples), i.rapAlignement && (r.rapAlignement = i.rapAlignement)))\n},\nISOFile.prototype.unsetSegmentOptions = function(t) {\n\tfor (var e = -1,\n\ti = 0; i < this.fragmentedTracks.length; i++) this.fragmentedTracks[i].id == t && (e = i); - 1 < e && this.fragmentedTracks.splice(e, 1)\n},\nISOFile.prototype.setExtractionOptions = function(t, e, i) {\n\tvar r, s = this.getTrackById(t);\n\ts && (r = {},\n\tthis.extractedTracks.push(r), r.id = t, r.user = e, (r.trak = s).nextSample = 0, r.nb_samples = 1e3, r.samples = [], i && i.nbSamples && (r.nb_samples = i.nbSamples))\n},\nISOFile.prototype.unsetExtractionOptions = function(t) {\n\tfor (var e = -1,\n\ti = 0; i < this.extractedTracks.length; i++) this.extractedTracks[i].id == t && (e = i); - 1 < e && this.extractedTracks.splice(e, 1)\n},\nISOFile.prototype.parse = function() {\n\tvar t;\n\tif (!this.restoreParsePosition || this.restoreParsePosition()) for (;;) if (this.hasIncompleteMdat && this.hasIncompleteMdat()) {\n\t\tif (!this.processIncompleteMdat()) return\n\t} else if (this.saveParsePosition && this.saveParsePosition(), (t = BoxParser.parseOneBox(this.stream, !1)).code === BoxParser.ERR_NOT_ENOUGH_DATA) {\n\t\tif (!this.processIncompleteBox) return;\n\t\tif (!this.processIncompleteBox(t)) return\n\t} else {\n\t\tvar e, i = "uuid" !== (e = t.box).type ? e.type: e.uuid;\n\t\tswitch (this.boxes.push(e), i) {\n\t\tcase "mdat":\n\t\t\tthis.mdats.push(e);\n\t\t\tbreak;\n\t\tcase "moof":\n\t\t\tthis.moofs.push(e);\n\t\t\tbreak;\n\t\tcase "moov":\n\t\t\tthis.moovStartFound = !0,\n\t\t\t0 === this.mdats.length && (this.isProgressive = !0);\n\t\tdefault:\n\t\t\tvoid 0 !== this[i] && Log.warn("ISOFile", "Duplicate Box of type: " + i + ", overriding previous occurrence"),\n\t\t\tthis[i] = e\n\t\t}\n\t\tthis.updateUsedBytes && this.updateUsedBytes(e, t)\n\t}\n},\nISOFile.prototype.checkBuffer = function(t) {\n\tif (null == t) throw "Buffer must be defined and non empty";\n\tif (void 0 === t.fileStart) throw "Buffer must have a fileStart property";\n\treturn 0 === t.byteLength ? (Log.warn("ISOFile", "Ignoring empty buffer (fileStart: " + t.fileStart + ")"), this.stream.logBufferLevel(), !1) : (Log.info("ISOFile", "Processing buffer (fileStart: " + t.fileStart + ")"), t.usedBytes = 0, this.stream.insertBuffer(t), this.stream.logBufferLevel(), !!this.stream.initialized() || (Log.warn("ISOFile", "Not ready to start parsing"), !1))\n},\nISOFile.prototype.appendBuffer = function(t, e) {\n\tvar i;\n\tif (this.checkBuffer(t)) return this.parse(),\n\tthis.moovStartFound && !this.moovStartSent && (this.moovStartSent = !0, this.onMoovStart && this.onMoovStart()),\n\tthis.moov ? (this.sampleListBuilt || (this.buildSampleLists(), this.sampleListBuilt = !0), this.updateSampleLists(), this.onReady && !this.readySent && (this.readySent = !0, this.onReady(this.getInfo())), this.processSamples(e), this.nextSeekPosition ? (i = this.nextSeekPosition, this.nextSeekPosition = void 0) : i = this.nextParsePosition, this.stream.getEndFilePositionAfter && (i = this.stream.getEndFilePositionAfter(i))) : i = this.nextParsePosition || 0,\n\tthis.sidx && this.onSidx && !this.sidxSent && (this.onSidx(this.sidx), this.sidxSent = !0),\n\tthis.meta && (this.flattenItemInfo && !this.itemListBuilt && (this.flattenItemInfo(), this.itemListBuilt = !0), this.processItems && this.processItems(this.onItem)),\n\tthis.stream.cleanBuffers && (Log.info("ISOFile", "Done processing buffer (fileStart: " + t.fileStart + ") - next buffer to fetch should have a fileStart position of " + i), this.stream.logBufferLevel(), this.stream.cleanBuffers(), this.stream.logBufferLevel(!0), Log.info("ISOFile", "Sample data size in memory: " + this.getAllocatedSampleDataSize())),\n\ti\n},\nISOFile.prototype.getInfo = function() {\n\tvar t, e, i, r, s, a, n = {},\n\to = new Date("1904-01-01T00:00:00Z").getTime();\n\tif (this.moov) for (n.hasMoov = !0, n.duration = this.moov.mvhd.duration, n.timescale = this.moov.mvhd.timescale, n.isFragmented = null != this.moov.mvex, n.isFragmented && this.moov.mvex.mehd && (n.fragment_duration = this.moov.mvex.mehd.fragment_duration), n.isProgressive = this.isProgressive, n.hasIOD = null != this.moov.iods, n.brands = [], n.brands.push(this.ftyp.major_brand), n.brands = n.brands.concat(this.ftyp.compatible_brands), n.created = new Date(o + 1e3 * this.moov.mvhd.creation_time), n.modified = new Date(o + 1e3 * this.moov.mvhd.modification_time), n.tracks = [], n.audioTracks = [], n.videoTracks = [], n.subtitleTracks = [], n.metadataTracks = [], n.hintTracks = [], n.otherTracks = [], t = 0; t < this.moov.traks.length; t++) {\n\t\tif (a = (i = this.moov.traks[t]).mdia.minf.stbl.stsd.entries[0], r = {},\n\t\tn.tracks.push(r), r.id = i.tkhd.track_id, r.name = i.mdia.hdlr.name, r.references = [], i.tref) for (e = 0; e < i.tref.boxes.length; e++) s = {},\n\t\tr.references.push(s),\n\t\ts.type = i.tref.boxes[e].type,\n\t\ts.track_ids = i.tref.boxes[e].track_ids;\n\t\ti.edts && (r.edits = i.edts.elst.entries),\n\t\tr.created = new Date(o + 1e3 * i.tkhd.creation_time),\n\t\tr.modified = new Date(o + 1e3 * i.tkhd.modification_time),\n\t\tr.movie_duration = i.tkhd.duration,\n\t\tr.movie_timescale = n.timescale,\n\t\tr.layer = i.tkhd.layer,\n\t\tr.alternate_group = i.tkhd.alternate_group,\n\t\tr.volume = i.tkhd.volume,\n\t\tr.matrix = i.tkhd.matrix,\n\t\tr.track_width = i.tkhd.width / 65536,\n\t\tr.track_height = i.tkhd.height / 65536,\n\t\tr.timescale = i.mdia.mdhd.timescale,\n\t\tr.cts_shift = i.mdia.minf.stbl.cslg,\n\t\tr.duration = i.mdia.mdhd.duration,\n\t\tr.samples_duration = i.samples_duration,\n\t\tr.codec = a.getCodec(),\n\t\tr.kind = i.udta && i.udta.kinds.length ? i.udta.kinds[0] : {\n\t\t\tschemeURI: "",\n\t\t\tvalue: ""\n\t\t},\n\t\tr.language = i.mdia.elng ? i.mdia.elng.extended_language: i.mdia.mdhd.languageString,\n\t\tr.nb_samples = i.samples.length,\n\t\tr.size = i.samples_size,\n\t\tr.bitrate = 8 * r.size * r.timescale / r.samples_duration,\n\t\ta.isAudio() ? (r.type = "audio", n.audioTracks.push(r), r.audio = {},\n\t\tr.audio.sample_rate = a.getSampleRate(), r.audio.channel_count = a.getChannelCount(), r.audio.sample_size = a.getSampleSize()) : a.isVideo() ? (r.type = "video", n.videoTracks.push(r), r.video = {},\n\t\tr.video.width = a.getWidth(), r.video.height = a.getHeight()) : a.isSubtitle() ? (r.type = "subtitles", n.subtitleTracks.push(r)) : a.isHint() ? (r.type = "metadata", n.hintTracks.push(r)) : a.isMetadata() ? (r.type = "metadata", n.metadataTracks.push(r)) : (r.type = "metadata", n.otherTracks.push(r))\n\t} else n.hasMoov = !1;\n\tif (n.mime = "", n.hasMoov && n.tracks) {\n\t\tfor (n.videoTracks && 0 < n.videoTracks.length ? n.mime += \'video/mp4; codecs="\': n.audioTracks && 0 < n.audioTracks.length ? n.mime += \'audio/mp4; codecs="\': n.mime += \'application/mp4; codecs="\', t = 0; t < n.tracks.length; t++) 0 !== t && (n.mime += ","),\n\t\tn.mime += n.tracks[t].codec;\n\t\tn.mime += \'"; profiles="\',\n\t\tn.mime += this.ftyp.compatible_brands.join(),\n\t\tn.mime += \'"\'\n\t}\n\treturn n\n},\nISOFile.prototype.setNextSeekPositionFromSample = function(t) {\n\tt && (this.nextSeekPosition ? this.nextSeekPosition = Math.min(t.offset + t.alreadyRead, this.nextSeekPosition) : this.nextSeekPosition = t.offset + t.alreadyRead)\n},\nISOFile.prototype.processSamples = function(t) {\n\tvar e;\n\tif (this.sampleProcessingStarted) {\n\t\tif (this.isFragmentationInitialized && null !== this.onSegment) for (e = 0; e < this.fragmentedTracks.length; e++) for (var i = this.fragmentedTracks[e], r = i.trak; r.nextSample < r.samples.length && this.sampleProcessingStarted;) {\n\t\t\tLog.debug("ISOFile", "Creating media fragment on track #" + i.id + " for sample " + r.nextSample);\n\t\t\tvar s = this.createFragment(i.id, r.nextSample, i.segmentStream);\n\t\t\tif (!s) break;\n\t\t\tif (i.segmentStream = s, r.nextSample++, (r.nextSample % i.nb_samples == 0 || t || r.nextSample >= r.samples.length) && (Log.info("ISOFile", "Sending fragmented data on track #" + i.id + " for samples [" + Math.max(0, r.nextSample - i.nb_samples) + "," + (r.nextSample - 1) + "]"), Log.info("ISOFile", "Sample data size in memory: " + this.getAllocatedSampleDataSize()), this.onSegment && this.onSegment(i.id, i.user, i.segmentStream.buffer, r.nextSample, t || r.nextSample >= r.samples.length), i.segmentStream = null, i !== this.fragmentedTracks[e])) break\n\t\t}\n\t\tif (null !== this.onSamples) for (e = 0; e < this.extractedTracks.length; e++) {\n\t\t\tvar a = this.extractedTracks[e];\n\t\t\tfor (r = a.trak; r.nextSample < r.samples.length && this.sampleProcessingStarted;) {\n\t\t\t\tLog.debug("ISOFile", "Exporting on track #" + a.id + " sample #" + r.nextSample);\n\t\t\t\tvar n = this.getSample(r, r.nextSample);\n\t\t\t\tif (!n) {\n\t\t\t\t\tthis.setNextSeekPositionFromSample(r.samples[r.nextSample]);\n\t\t\t\t\tbreak\n\t\t\t\t}\n\t\t\t\tif (r.nextSample++, a.samples.push(n), (r.nextSample % a.nb_samples == 0 || r.nextSample >= r.samples.length) && (Log.debug("ISOFile", "Sending samples on track #" + a.id + " for sample " + r.nextSample), this.onSamples && this.onSamples(a.id, a.user, a.samples), a.samples = [], a !== this.extractedTracks[e])) break\n\t\t\t}\n\t\t}\n\t}\n},\nISOFile.prototype.getBox = function(t) {\n\tt = this.getBoxes(t, !0);\n\treturn t.length ? t[0] : null\n},\nISOFile.prototype.getBoxes = function(t, e) {\n\tvar i = [];\n\treturn ISOFile._sweep.call(this, t, i, e),\n\ti\n},\nISOFile._sweep = function(t, e, i) {\n\tfor (var r in this.type && this.type == t && e.push(this), this.boxes) {\n\t\tif (e.length && i) return;\n\t\tISOFile._sweep.call(this.boxes[r], t, e, i)\n\t}\n},\nISOFile.prototype.getTrackSamplesInfo = function(t) {\n\tt = this.getTrackById(t);\n\tif (t) return t.samples\n},\nISOFile.prototype.getTrackSample = function(t, e) {\n\tt = this.getTrackById(t);\n\treturn this.getSample(t, e)\n},\nISOFile.prototype.releaseUsedSamples = function(t, e) {\n\tvar i = 0,\n\tr = this.getTrackById(t);\n\tr.lastValidSample || (r.lastValidSample = 0);\n\tfor (var s = r.lastValidSample; s < e; s++) i += this.releaseSample(r, s);\n\tLog.info("ISOFile", "Track #" + t + " released samples up to " + e + " (released size: " + i + ", remaining: " + this.samplesDataSize + ")"),\n\tr.lastValidSample = e\n},\nISOFile.prototype.start = function() {\n\tthis.sampleProcessingStarted = !0,\n\tthis.processSamples(!1)\n},\nISOFile.prototype.stop = function() {\n\tthis.sampleProcessingStarted = !1\n},\nISOFile.prototype.flush = function() {\n\tLog.info("ISOFile", "Flushing remaining samples"),\n\tthis.updateSampleLists(),\n\tthis.processSamples(!0),\n\tthis.stream.cleanBuffers(),\n\tthis.stream.logBufferLevel(!0)\n},\nISOFile.prototype.seekTrack = function(t, e, i) {\n\tvar r, s, a, n, o = 0,\n\th = 0;\n\tif (0 === i.samples.length) return Log.info("ISOFile", "No sample in track, cannot seek! Using time " + Log.getDurationString(0, 1) + " and offset: 0"),\n\t{\n\t\toffset: 0,\n\t\ttime: 0\n\t};\n\tfor (r = 0; r < i.samples.length; r++) {\n\t\tif (s = i.samples[r], 0 === r) h = 0,\n\t\tn = s.timescale;\n\t\telse if (s.cts > t * s.timescale) {\n\t\t\th = r - 1;\n\t\t\tbreak\n\t\t}\n\t\te && s.is_sync && (o = r)\n\t}\n\tfor (e && (h = o), t = i.samples[h].cts, i.nextSample = h; i.samples[h].alreadyRead === i.samples[h].size && i.samples[h + 1];) h++;\n\treturn a = i.samples[h].offset + i.samples[h].alreadyRead,\n\tLog.info("ISOFile", "Seeking to " + (e ? "RAP": "") + " sample #" + i.nextSample + " on track " + i.tkhd.track_id + ", time " + Log.getDurationString(t, n) + " and offset: " + a),\n\t{\n\t\toffset: a,\n\t\ttime: t / n\n\t}\n},\nISOFile.prototype.getTrackDuration = function(t) {\n\treturn t.samples ? ((t = t.samples[t.samples.length - 1]).cts + t.duration) / t.timescale: 1 / 0\n},\nISOFile.prototype.seek = function(t, e) {\n\tvar i, r, s = this.moov,\n\ta = {\n\t\toffset: 1 / 0,\n\t\ttime: 1 / 0\n\t};\n\tif (this.moov) {\n\t\tfor (r = 0; r < s.traks.length; r++) i = s.traks[r],\n\t\tt > this.getTrackDuration(i) || ((i = this.seekTrack(t, e, i)).offset < a.offset && (a.offset = i.offset), i.time < a.time && (a.time = i.time));\n\t\treturn Log.info("ISOFile", "Seeking at time " + Log.getDurationString(a.time, 1) + " needs a buffer with a fileStart position of " + a.offset),\n\t\ta.offset === 1 / 0 ? a = {\n\t\t\toffset: this.nextParsePosition,\n\t\t\ttime: 0\n\t\t}: a.offset = this.stream.getEndFilePositionAfter(a.offset),\n\t\tLog.info("ISOFile", "Adjusted seek position (after checking data already in buffer): " + a.offset),\n\t\ta\n\t}\n\tthrow "Cannot seek: moov not received!"\n},\nISOFile.prototype.equal = function(t) {\n\tfor (var e = 0; e < this.boxes.length && e < t.boxes.length;) {\n\t\tvar i = this.boxes[e],\n\t\tr = t.boxes[e];\n\t\tif (!BoxParser.boxEqual(i, r)) return ! 1;\n\t\te++\n\t}\n\treturn ! 0\n},\n"undefined" != typeof exports && (exports.ISOFile = ISOFile),\nISOFile.prototype.lastBoxStartPosition = 0,\nISOFile.prototype.parsingMdat = null,\nISOFile.prototype.nextParsePosition = 0,\nISOFile.prototype.discardMdatData = !1,\nISOFile.prototype.processIncompleteBox = function(t) {\n\tvar e;\n\treturn "mdat" === t.type ? (e = new BoxParser[t.type + "Box"](t.size), this.parsingMdat = e, this.boxes.push(e), this.mdats.push(e), e.start = t.start, e.hdr_size = t.hdr_size, this.stream.addUsedBytes(e.hdr_size), this.lastBoxStartPosition = e.start + e.size, this.stream.seek(e.start + e.size, !1, this.discardMdatData) ? !(this.parsingMdat = null) : (this.moovStartFound ? this.nextParsePosition = this.stream.findEndContiguousBuf() : this.nextParsePosition = e.start + e.size, !1)) : ("moov" === t.type && (this.moovStartFound = !0, 0 === this.mdats.length && (this.isProgressive = !0)), !!this.stream.mergeNextBuffer && this.stream.mergeNextBuffer() ? (this.nextParsePosition = this.stream.getEndPosition(), !0) : (!t.type || this.moovStartFound ? this.nextParsePosition = this.stream.getEndPosition() : this.nextParsePosition = this.stream.getPosition() + t.size, !1))\n},\nISOFile.prototype.hasIncompleteMdat = function() {\n\treturn null !== this.parsingMdat\n},\nISOFile.prototype.processIncompleteMdat = function() {\n\tvar t = this.parsingMdat;\n\treturn this.stream.seek(t.start + t.size, !1, this.discardMdatData) ? (Log.debug("ISOFile", "Found \'mdat\' end in buffered data"), !(this.parsingMdat = null)) : (this.nextParsePosition = this.stream.findEndContiguousBuf(), !1)\n},\nISOFile.prototype.restoreParsePosition = function() {\n\treturn this.stream.seek(this.lastBoxStartPosition, !0, this.discardMdatData)\n},\nISOFile.prototype.saveParsePosition = function() {\n\tthis.lastBoxStartPosition = this.stream.getPosition()\n},\nISOFile.prototype.updateUsedBytes = function(t, e) {\n\tthis.stream.addUsedBytes && ("mdat" === t.type ? (this.stream.addUsedBytes(t.hdr_size), this.discardMdatData && this.stream.addUsedBytes(t.size - t.hdr_size)) : this.stream.addUsedBytes(t.size))\n},\nISOFile.prototype.add = BoxParser.Box.prototype.add,\nISOFile.prototype.addBox = BoxParser.Box.prototype.addBox,\nISOFile.prototype.init = function(t) {\n\tvar e = t || {},\n\tt = (this.add("ftyp").set("major_brand", e.brands && e.brands[0] || "iso4").set("minor_version", 0).set("compatible_brands", e.brands || ["iso4"]), this.add("moov"));\n\treturn t.add("mvhd").set("timescale", e.timescale || 600).set("rate", e.rate || 65536).set("creation_time", 0).set("modification_time", 0).set("duration", e.duration || 0).set("volume", e.width ? 0 : 256).set("matrix", [65536, 0, 0, 0, 65536, 0, 0, 0, 1073741824]).set("next_track_id", 1),\n\tt.add("mvex"),\n\tthis\n},\nISOFile.prototype.addTrack = function(t) {\n\tthis.moov || this.init(t);\n\tvar e = t || {};\n\te.width = e.width || 320,\n\te.height = e.height || 320,\n\te.id = e.id || this.moov.mvhd.next_track_id,\n\te.type = e.type || "avc1";\n\tvar i = this.moov.add("trak");\n\tthis.moov.mvhd.next_track_id = e.id + 1,\n\ti.add("tkhd").set("flags", BoxParser.TKHD_FLAG_ENABLED | BoxParser.TKHD_FLAG_IN_MOVIE | BoxParser.TKHD_FLAG_IN_PREVIEW).set("creation_time", 0).set("modification_time", 0).set("track_id", e.id).set("duration", e.duration || 0).set("layer", e.layer || 0).set("alternate_group", 0).set("volume", 1).set("matrix", [65536, 0, 0, 0, 65536, 0, 0, 0, 1073741824]).set("width", e.width << 16).set("height", e.height << 16);\n\tt = i.add("mdia");\n\tt.add("mdhd").set("creation_time", 0).set("modification_time", 0).set("timescale", e.timescale || 1).set("duration", e.media_duration || 0).set("language", e.language || "und"),\n\tt.add("hdlr").set("handler", e.hdlr || "vide").set("name", e.name || "Track created with MP4Box.js"),\n\tt.add("elng").set("extended_language", e.language || "fr-FR");\n\tvar r = t.add("minf");\n\tif (void 0 !== BoxParser[e.type + "SampleEntry"]) {\n\t\tvar s = new BoxParser[e.type + "SampleEntry"];\n\t\ts.data_reference_index = 1;\n\t\tvar a, n, o = "";\n\t\tfor (a in BoxParser.sampleEntryCodes) for (var h = BoxParser.sampleEntryCodes[a], d = 0; d < h.length; d++) if (-1 < h.indexOf(e.type)) {\n\t\t\to = a;\n\t\t\tbreak\n\t\t}\n\t\tswitch (o) {\n\t\tcase "Visual":\n\t\t\tr.add("vmhd").set("graphicsmode", 0).set("opcolor", [0, 0, 0]),\n\t\t\ts.set("width", e.width).set("height", e.height).set("horizresolution", 72 << 16).set("vertresolution", 72 << 16).set("frame_count", 1).set("compressorname", e.type + " Compressor").set("depth", 24),\n\t\t\te.avcDecoderConfigRecord ? ((n = new BoxParser.avcCBox).parse(new MP4BoxStream(e.avcDecoderConfigRecord)), s.addBox(n)) : e.hevcDecoderConfigRecord && ((n = new BoxParser.hvcCBox).parse(new MP4BoxStream(e.hevcDecoderConfigRecord)), s.addBox(n));\n\t\t\tbreak;\n\t\tcase "Audio":\n\t\t\tr.add("smhd").set("balance", e.balance || 0),\n\t\t\ts.set("channel_count", e.channel_count || 2).set("samplesize", e.samplesize || 16).set("samplerate", e.samplerate || 65536);\n\t\t\tbreak;\n\t\tcase "Hint":\n\t\t\tr.add("hmhd");\n\t\t\tbreak;\n\t\tcase "Subtitle":\n\t\t\tr.add("sthd"),\n\t\t\t"stpp" === e.type && s.set("namespace", e.namespace || "nonamespace").set("schema_location", e.schema_location || "").set("auxiliary_mime_types", e.auxiliary_mime_types || "");\n\t\t\tbreak;\n\t\tcase "Metadata":\n\t\tcase "System":\n\t\tdefault:\n\t\t\tr.add("nmhd")\n\t\t}\n\t\te.description && s.addBox(e.description),\n\t\te.description_boxes && e.description_boxes.forEach(function(t) {\n\t\t\ts.addBox(t)\n\t\t}),\n\t\tr.add("dinf").add("dref").addEntry((new BoxParser["url Box"]).set("flags", 1));\n\t\tt = r.add("stbl");\n\t\treturn t.add("stsd").addEntry(s),\n\t\tt.add("stts").set("sample_counts", []).set("sample_deltas", []),\n\t\tt.add("stsc").set("first_chunk", []).set("samples_per_chunk", []).set("sample_description_index", []),\n\t\tt.add("stco").set("chunk_offsets", []),\n\t\tt.add("stsz").set("sample_sizes", []),\n\t\tthis.moov.mvex.add("trex").set("track_id", e.id).set("default_sample_description_index", e.default_sample_description_index || 1).set("default_sample_duration", e.default_sample_duration || 0).set("default_sample_size", e.default_sample_size || 0).set("default_sample_flags", e.default_sample_flags || 0),\n\t\tthis.buildTrakSampleLists(i),\n\t\te.id\n\t}\n},\nBoxParser.Box.prototype.computeSize = function(t) {\n\tt = t || new DataStream;\n\tt.endianness = DataStream.BIG_ENDIAN,\n\tthis.write(t)\n},\nISOFile.prototype.addSample = function(t, e, i) {\n\tvar r = i || {},\n\ti = {},\n\tt = this.getTrackById(t);\n\tif (null !== t) {\n\t\ti.number = t.samples.length,\n\t\ti.track_id = t.tkhd.track_id,\n\t\ti.timescale = t.mdia.mdhd.timescale,\n\t\ti.description_index = r.sample_description_index ? r.sample_description_index - 1 : 0,\n\t\ti.description = t.mdia.minf.stbl.stsd.entries[i.description_index],\n\t\ti.data = e,\n\t\ti.size = e.byteLength,\n\t\ti.alreadyRead = i.size,\n\t\ti.duration = r.duration || 1,\n\t\ti.cts = r.cts || 0,\n\t\ti.dts = r.dts || 0,\n\t\ti.is_sync = r.is_sync || !1,\n\t\ti.is_leading = r.is_leading || 0,\n\t\ti.depends_on = r.depends_on || 0,\n\t\ti.is_depended_on = r.is_depended_on || 0,\n\t\ti.has_redundancy = r.has_redundancy || 0,\n\t\ti.degradation_priority = r.degradation_priority || 0,\n\t\ti.offset = 0,\n\t\ti.subsamples = r.subsamples,\n\t\tt.samples.push(i),\n\t\tt.samples_size += i.size,\n\t\tt.samples_duration += i.duration,\n\t\tvoid 0 === t.first_dts && (t.first_dts = r.dts),\n\t\tthis.processSamples();\n\t\tr = this.createSingleSampleMoof(i);\n\t\treturn this.addBox(r),\n\t\tr.computeSize(),\n\t\tr.trafs[0].truns[0].data_offset = r.size + 8,\n\t\tthis.add("mdat").data = new Uint8Array(e),\n\t\ti\n\t}\n},\nISOFile.prototype.createSingleSampleMoof = function(t) {\n\tvar e = 0,\n\te = t.is_sync ? 1 << 25 : 65536,\n\ti = new BoxParser.moofBox;\n\ti.add("mfhd").set("sequence_number", this.nextMoofNumber),\n\tthis.nextMoofNumber++;\n\tvar r = i.add("traf"),\n\ts = this.getTrackById(t.track_id);\n\treturn r.add("tfhd").set("track_id", t.track_id).set("flags", BoxParser.TFHD_FLAG_DEFAULT_BASE_IS_MOOF),\n\tr.add("tfdt").set("baseMediaDecodeTime", t.dts - (s.first_dts || 0)),\n\tr.add("trun").set("flags", BoxParser.TRUN_FLAGS_DATA_OFFSET | BoxParser.TRUN_FLAGS_DURATION | BoxParser.TRUN_FLAGS_SIZE | BoxParser.TRUN_FLAGS_FLAGS | BoxParser.TRUN_FLAGS_CTS_OFFSET).set("data_offset", 0).set("first_sample_flags", 0).set("sample_count", 1).set("sample_duration", [t.duration]).set("sample_size", [t.size]).set("sample_flags", [e]).set("sample_composition_time_offset", [t.cts - t.dts]),\n\ti\n},\nISOFile.prototype.lastMoofIndex = 0,\nISOFile.prototype.samplesDataSize = 0,\nISOFile.prototype.resetTables = function() {\n\tvar t, e;\n\tfor (this.initial_duration = this.moov.mvhd.duration, t = this.moov.mvhd.duration = 0; t < this.moov.traks.length; t++) { (e = this.moov.traks[t]).tkhd.duration = 0,\n\t\te.mdia.mdhd.duration = 0,\n\t\t(e.mdia.minf.stbl.stco || e.mdia.minf.stbl.co64).chunk_offsets = [],\n\t\t(i = e.mdia.minf.stbl.stsc).first_chunk = [],\n\t\ti.samples_per_chunk = [],\n\t\ti.sample_description_index = [],\n\t\t(e.mdia.minf.stbl.stsz || e.mdia.minf.stbl.stz2).sample_sizes = [],\n\t\t(i = e.mdia.minf.stbl.stts).sample_counts = [],\n\t\ti.sample_deltas = [],\n\t\t(i = e.mdia.minf.stbl.ctts) && (i.sample_counts = [], i.sample_offsets = []),\n\t\ti = e.mdia.minf.stbl.stss;\n\t\tvar i = e.mdia.minf.stbl.boxes.indexOf(i); - 1 != i && (e.mdia.minf.stbl.boxes[i] = null)\n\t}\n},\nISOFile.initSampleGroups = function(t, e, i, r, s) {\n\tvar a, n, o, h;\n\tfunction d(t, e, i) {\n\t\tthis.grouping_type = t,\n\t\tthis.grouping_type_parameter = e,\n\t\tthis.sbgp = i,\n\t\tthis.last_sample_in_run = -1,\n\t\tthis.entry_index = -1\n\t}\n\tfor (e && (e.sample_groups_info = []), t.sample_groups_info || (t.sample_groups_info = []), n = 0; n < i.length; n++) {\n\t\tfor (h = i[n].grouping_type + "/" + i[n].grouping_type_parameter, o = new d(i[n].grouping_type, i[n].grouping_type_parameter, i[n]), e && (e.sample_groups_info[h] = o), t.sample_groups_info[h] || (t.sample_groups_info[h] = o), a = 0; a < r.length; a++) r[a].grouping_type === i[n].grouping_type && (o.description = r[a], o.description.used = !0);\n\t\tif (s) for (a = 0; a < s.length; a++) s[a].grouping_type === i[n].grouping_type && (o.fragment_description = s[a], o.fragment_description.used = !0, o.is_fragment = !0)\n\t}\n\tif (e) {\n\t\tif (s) for (n = 0; n < s.length; n++) ! s[n].used && 2 <= s[n].version && (h = s[n].grouping_type + "/0", (o = new d(s[n].grouping_type, 0)).is_fragment = !0, e.sample_groups_info[h] || (e.sample_groups_info[h] = o))\n\t} else for (n = 0; n < r.length; n++) ! r[n].used && 2 <= r[n].version && (h = r[n].grouping_type + "/0", o = new d(r[n].grouping_type, 0), t.sample_groups_info[h] || (t.sample_groups_info[h] = o))\n},\nISOFile.setSampleGroupProperties = function(t, e, i, r) {\n\tvar s, a, n;\n\tfor (s in e.sample_groups = [], r) e.sample_groups[s] = {},\n\te.sample_groups[s].grouping_type = r[s].grouping_type,\n\te.sample_groups[s].grouping_type_parameter = r[s].grouping_type_parameter,\n\ti >= r[s].last_sample_in_run && (r[s].last_sample_in_run < 0 && (r[s].last_sample_in_run = 0), r[s].entry_index++, r[s].entry_index <= r[s].sbgp.entries.length - 1 && (r[s].last_sample_in_run += r[s].sbgp.entries[r[s].entry_index].sample_count)),\n\tr[s].entry_index <= r[s].sbgp.entries.length - 1 ? e.sample_groups[s].group_description_index = r[s].sbgp.entries[r[s].entry_index].group_description_index: e.sample_groups[s].group_description_index = -1,\n\t0 !== e.sample_groups[s].group_description_index && (n = r[s].fragment_description || r[s].description, 0 < e.sample_groups[s].group_description_index ? (a = 65535 < e.sample_groups[s].group_description_index ? (e.sample_groups[s].group_description_index >> 16) - 1 : e.sample_groups[s].group_description_index - 1, n && 0 <= a && (e.sample_groups[s].description = n.entries[a])) : n && 2 <= n.version && 0 < n.default_group_description_index && (e.sample_groups[s].description = n.entries[n.default_group_description_index - 1]))\n},\nISOFile.process_sdtp = function(t, e, i) {\n\te && (t ? (e.is_leading = t.is_leading[i], e.depends_on = t.sample_depends_on[i], e.is_depended_on = t.sample_is_depended_on[i], e.has_redundancy = t.sample_has_redundancy[i]) : (e.is_leading = 0, e.depends_on = 0, e.is_depended_on = 0, e.has_redundancy = 0))\n},\nISOFile.prototype.buildSampleLists = function() {\n\tfor (var t, e = 0; e < this.moov.traks.length; e++) t = this.moov.traks[e],\n\tthis.buildTrakSampleLists(t)\n},\nISOFile.prototype.buildTrakSampleLists = function(t) {\n\tvar e, i, r, s, a, n, o, h, d, l, p, f, u, _, c, m, x, g, y, B, S, P, U, b;\n\tif (t.samples = [], t.samples_duration = 0, t.samples_size = 0, i = t.mdia.minf.stbl.stco || t.mdia.minf.stbl.co64, r = t.mdia.minf.stbl.stsc, s = t.mdia.minf.stbl.stsz || t.mdia.minf.stbl.stz2, a = t.mdia.minf.stbl.stts, n = t.mdia.minf.stbl.ctts, o = t.mdia.minf.stbl.stss, h = t.mdia.minf.stbl.stsd, d = t.mdia.minf.stbl.subs, f = t.mdia.minf.stbl.stdp, l = t.mdia.minf.stbl.sbgps, p = t.mdia.minf.stbl.sgpds, S = B = y = g = -1, b = U = P = 0, ISOFile.initSampleGroups(t, null, l, p), void 0 !== s) {\n\t\tfor (e = 0; e < s.sample_sizes.length; e++) {\n\t\t\tvar v = {};\n\t\t\tv.number = e,\n\t\t\tv.track_id = t.tkhd.track_id,\n\t\t\tv.timescale = t.mdia.mdhd.timescale,\n\t\t\tv.alreadyRead = 0,\n\t\t\t(t.samples[e] = v).size = s.sample_sizes[e],\n\t\t\tt.samples_size += v.size,\n\t\t\t0 === e ? (_ = 1, u = 0, v.chunk_index = _, v.chunk_run_index = u, x = r.samples_per_chunk[u], m = 0, c = u + 1 < r.first_chunk.length ? r.first_chunk[u + 1] - 1 : 1 / 0) : e < x ? (v.chunk_index = _, v.chunk_run_index = u) : (_++, m = 0, (v.chunk_index = _) <= c || (c = ++u + 1 < r.first_chunk.length ? r.first_chunk[u + 1] - 1 : 1 / 0), v.chunk_run_index = u, x += r.samples_per_chunk[u]),\n\t\t\tv.description_index = r.sample_description_index[v.chunk_run_index] - 1,\n\t\t\tv.description = h.entries[v.description_index],\n\t\t\tv.offset = i.chunk_offsets[v.chunk_index - 1] + m,\n\t\t\tm += v.size,\n\t\t\tg < e && (y++, g < 0 && (g = 0), g += a.sample_counts[y]),\n\t\t\t0 < e ? (t.samples[e - 1].duration = a.sample_deltas[y], t.samples_duration += t.samples[e - 1].duration, v.dts = t.samples[e - 1].dts + t.samples[e - 1].duration) : v.dts = 0,\n\t\t\tn ? (B <= e && (S++, B < 0 && (B = 0), B += n.sample_counts[S]), v.cts = t.samples[e].dts + n.sample_offsets[S]) : v.cts = v.dts,\n\t\t\to ? (e == o.sample_numbers[P] - 1 ? (v.is_sync = !0, P++) : (v.is_sync = !1, v.degradation_priority = 0), d && d.entries[U].sample_delta + b == e + 1 && (v.subsamples = d.entries[U].subsamples, b += d.entries[U].sample_delta, U++)) : v.is_sync = !0,\n\t\t\tISOFile.process_sdtp(t.mdia.minf.stbl.sdtp, v, v.number),\n\t\t\tv.degradation_priority = f ? f.priority[e] : 0,\n\t\t\td && d.entries[U].sample_delta + b == e && (v.subsamples = d.entries[U].subsamples, b += d.entries[U].sample_delta),\n\t\t\t(0 < l.length || 0 < p.length) && ISOFile.setSampleGroupProperties(t, v, e, t.sample_groups_info)\n\t\t}\n\t\t0 < e && (t.samples[e - 1].duration = Math.max(t.mdia.mdhd.duration - t.samples[e - 1].dts, 0), t.samples_duration += t.samples[e - 1].duration)\n\t}\n},\nISOFile.prototype.updateSampleLists = function() {\n\tvar t, e, i, r, s, a, n, o, h, d, l, p;\n\tif (void 0 !== this.moov) for (; this.lastMoofIndex < this.moofs.length;) if (n = this.moofs[this.lastMoofIndex], this.lastMoofIndex++, "moof" == n.type) for (o = n, t = 0; t < o.trafs.length; t++) {\n\t\tfor (h = o.trafs[t], d = this.getTrackById(h.tfhd.track_id), l = this.getTrexById(h.tfhd.track_id), e = h.tfhd.flags & BoxParser.TFHD_FLAG_SAMPLE_DESC ? h.tfhd.default_sample_description_index: l ? l.default_sample_description_index: 1, i = h.tfhd.flags & BoxParser.TFHD_FLAG_SAMPLE_DUR ? h.tfhd.default_sample_duration: l ? l.default_sample_duration: 0, r = h.tfhd.flags & BoxParser.TFHD_FLAG_SAMPLE_SIZE ? h.tfhd.default_sample_size: l ? l.default_sample_size: 0, s = h.tfhd.flags & BoxParser.TFHD_FLAG_SAMPLE_FLAGS ? h.tfhd.default_sample_flags: l ? l.default_sample_flags: 0, (h.sample_number = 0) < h.sbgps.length && ISOFile.initSampleGroups(d, h, h.sbgps, d.mdia.minf.stbl.sgpds, h.sgpds), y = 0; y < h.truns.length; y++) for (var f = h.truns[y], u = 0; u < f.sample_count; u++) { (p = {}).moof_number = this.lastMoofIndex,\n\t\t\tp.number_in_traf = h.sample_number,\n\t\t\th.sample_number++,\n\t\t\tp.number = d.samples.length,\n\t\t\th.first_sample_index = d.samples.length,\n\t\t\td.samples.push(p),\n\t\t\tp.track_id = d.tkhd.track_id,\n\t\t\tp.timescale = d.mdia.mdhd.timescale,\n\t\t\tp.description_index = e - 1,\n\t\t\tp.description = d.mdia.minf.stbl.stsd.entries[p.description_index],\n\t\t\tp.size = r,\n\t\t\tf.flags & BoxParser.TRUN_FLAGS_SIZE && (p.size = f.sample_size[u]),\n\t\t\td.samples_size += p.size,\n\t\t\tp.duration = i,\n\t\t\tf.flags & BoxParser.TRUN_FLAGS_DURATION && (p.duration = f.sample_duration[u]),\n\t\t\td.samples_duration += p.duration,\n\t\t\td.first_traf_merged || 0 < u ? p.dts = d.samples[d.samples.length - 2].dts + d.samples[d.samples.length - 2].duration: (h.tfdt ? p.dts = h.tfdt.baseMediaDecodeTime: p.dts = 0, d.first_traf_merged = !0),\n\t\t\tp.cts = p.dts,\n\t\t\tf.flags & BoxParser.TRUN_FLAGS_CTS_OFFSET && (p.cts = p.dts + f.sample_composition_time_offset[u]),\n\t\t\tx = s,\n\t\t\tf.flags & BoxParser.TRUN_FLAGS_FLAGS ? x = f.sample_flags[u] : 0 === u && f.flags & BoxParser.TRUN_FLAGS_FIRST_FLAG && (x = f.first_sample_flags),\n\t\t\tp.is_sync = !(x >> 16 & 1),\n\t\t\tp.is_leading = x >> 26 & 3,\n\t\t\tp.depends_on = x >> 24 & 3,\n\t\t\tp.is_depended_on = x >> 22 & 3,\n\t\t\tp.has_redundancy = x >> 20 & 3,\n\t\t\tp.degradation_priority = 65535 & x;\n\t\t\tvar _ = !!(h.tfhd.flags & BoxParser.TFHD_FLAG_BASE_DATA_OFFSET),\n\t\t\tc = !!(h.tfhd.flags & BoxParser.TFHD_FLAG_DEFAULT_BASE_IS_MOOF),\n\t\t\tm = !!(f.flags & BoxParser.TRUN_FLAGS_DATA_OFFSET),\n\t\t\tx = 0,\n\t\t\tx = _ ? h.tfhd.base_data_offset: c || 0 === y ? o.start: a;\n\t\t\tp.offset = 0 === y && 0 === u ? m ? x + f.data_offset: x: a,\n\t\t\ta = p.offset + p.size,\n\t\t\t(0 < h.sbgps.length || 0 < h.sgpds.length || 0 < d.mdia.minf.stbl.sbgps.length || 0 < d.mdia.minf.stbl.sgpds.length) && ISOFile.setSampleGroupProperties(d, p, p.number_in_traf, h.sample_groups_info)\n\t\t}\n\t\tif (h.subs) {\n\t\t\td.has_fragment_subsamples = !0;\n\t\t\tfor (var g = h.first_sample_index,\n\t\t\ty = 0; y < h.subs.entries.length; y++) g += h.subs.entries[y].sample_delta,\n\t\t\t(p = d.samples[g - 1]).subsamples = h.subs.entries[y].subsamples\n\t\t}\n\t}\n},\nISOFile.prototype.getSample = function(t, e) {\n\tvar i, r = t.samples[e];\n\tif (!this.moov) return null;\n\tif (r.data) {\n\t\tif (r.alreadyRead == r.size) return r\n\t} else r.data = new Uint8Array(r.size),\n\tr.alreadyRead = 0,\n\tthis.samplesDataSize += r.size,\n\tLog.debug("ISOFile", "Allocating sample #" + e + " on track #" + t.tkhd.track_id + " of size " + r.size + " (total: " + this.samplesDataSize + ")");\n\tfor (;;) {\n\t\tvar s = this.stream.findPosition(!0, r.offset + r.alreadyRead, !1);\n\t\tif (! (-1 < s)) return null;\n\t\ts = (i = this.stream.buffers[s]).byteLength - (r.offset + r.alreadyRead - i.fileStart);\n\t\tif (r.size - r.alreadyRead <= s) return Log.debug("ISOFile", "Getting sample #" + e + " data (alreadyRead: " + r.alreadyRead + " offset: " + (r.offset + r.alreadyRead - i.fileStart) + " read size: " + (r.size - r.alreadyRead) + " full size: " + r.size + ")"),\n\t\tDataStream.memcpy(r.data.buffer, r.alreadyRead, i, r.offset + r.alreadyRead - i.fileStart, r.size - r.alreadyRead),\n\t\ti.usedBytes += r.size - r.alreadyRead,\n\t\tthis.stream.logBufferLevel(),\n\t\tr.alreadyRead = r.size,\n\t\tr;\n\t\tif (0 == s) return null;\n\t\tLog.debug("ISOFile", "Getting sample #" + e + " partial data (alreadyRead: " + r.alreadyRead + " offset: " + (r.offset + r.alreadyRead - i.fileStart) + " read size: " + s + " full size: " + r.size + ")"),\n\t\tDataStream.memcpy(r.data.buffer, r.alreadyRead, i, r.offset + r.alreadyRead - i.fileStart, s),\n\t\tr.alreadyRead += s,\n\t\ti.usedBytes += s,\n\t\tthis.stream.logBufferLevel()\n\t}\n},\nISOFile.prototype.releaseSample = function(t, e) {\n\te = t.samples[e];\n\treturn e.data ? (this.samplesDataSize -= e.size, e.data = null, e.alreadyRead = 0, e.size) : 0\n},\nISOFile.prototype.getAllocatedSampleDataSize = function() {\n\treturn this.samplesDataSize\n},\nISOFile.prototype.getCodecs = function() {\n\tfor (var t = "",\n\te = 0; e < this.moov.traks.length; e++) 0 < e && (t += ","),\n\tt += this.moov.traks[e].mdia.minf.stbl.stsd.entries[0].getCodec();\n\treturn t\n},\nISOFile.prototype.getTrexById = function(t) {\n\tvar e;\n\tif (!this.moov || !this.moov.mvex) return null;\n\tfor (e = 0; e < this.moov.mvex.trexs.length; e++) {\n\t\tvar i = this.moov.mvex.trexs[e];\n\t\tif (i.track_id == t) return i\n\t}\n\treturn null\n},\nISOFile.prototype.getTrackById = function(t) {\n\tif (void 0 === this.moov) return null;\n\tfor (var e = 0; e < this.moov.traks.length; e++) {\n\t\tvar i = this.moov.traks[e];\n\t\tif (i.tkhd.track_id == t) return i\n\t}\n\treturn null\n},\nISOFile.prototype.itemsDataSize = 0,\nISOFile.prototype.flattenItemInfo = function() {\n\tvar t = this.items,\n\te = this.entity_groups,\n\ti = this.meta;\n\tif (null != i && void 0 !== i.hdlr && void 0 !== i.iinf) {\n\t\tfor (d = 0; d < i.iinf.item_infos.length; d++)(s = {}).id = i.iinf.item_infos[d].item_ID,\n\t\t(t[s.id] = s).ref_to = [],\n\t\ts.name = i.iinf.item_infos[d].item_name,\n\t\t0 < i.iinf.item_infos[d].protection_index && (s.protection = i.ipro.protections[i.iinf.item_infos[d].protection_index - 1]),\n\t\ti.iinf.item_infos[d].item_type ? s.type = i.iinf.item_infos[d].item_type: s.type = "mime",\n\t\ts.content_type = i.iinf.item_infos[d].content_type,\n\t\ts.content_encoding = i.iinf.item_infos[d].content_encoding,\n\t\ts.item_uri_type = i.iinf.item_infos[d].item_uri_type;\n\t\tif (i.grpl) for (d = 0; d < i.grpl.boxes.length; d++) entity_group = {},\n\t\tentity_group.id = i.grpl.boxes[d].group_id,\n\t\tentity_group.entity_ids = i.grpl.boxes[d].entity_ids,\n\t\tentity_group.type = i.grpl.boxes[d].type,\n\t\te[entity_group.id] = entity_group;\n\t\tif (i.iloc) for (d = 0; d < i.iloc.items.length; d++) {\n\t\t\tvar r = i.iloc.items[d],\n\t\t\ts = t[r.item_ID];\n\t\t\tswitch (0 !== r.data_reference_index && (Log.warn("Item storage with reference to other files: not supported"), s.source = i.dinf.boxes[r.data_reference_index - 1]), r.construction_method) {\n\t\t\tcase 0:\n\t\t\tcase 1:\n\t\t\t\tbreak;\n\t\t\tcase 2:\n\t\t\t\tLog.warn("Item storage with construction_method : not supported")\n\t\t\t}\n\t\t\tfor (s.extents = [], n = s.size = 0; n < r.extents.length; n++) s.extents[n] = {},\n\t\t\ts.extents[n].offset = r.extents[n].extent_offset + r.base_offset,\n\t\t\t1 == r.construction_method && (s.extents[n].offset += i.idat.start + i.idat.hdr_size),\n\t\t\ts.extents[n].length = r.extents[n].extent_length,\n\t\t\ts.extents[n].alreadyRead = 0,\n\t\t\ts.size += s.extents[n].length\n\t\t}\n\t\tif (i.pitm && (t[i.pitm.item_id].primary = !0), i.iref) for (d = 0; d < i.iref.references.length; d++) for (var a = i.iref.references[d], n = 0; n < a.references.length; n++) t[a.from_item_ID].ref_to.push({\n\t\t\ttype: a.type,\n\t\t\tid: a.references[n]\n\t\t});\n\t\tif (i.iprp) for (var o = 0; o < i.iprp.ipmas.length; o++) for (var h = i.iprp.ipmas[o], d = 0; d < h.associations.length; d++) {\n\t\t\tvar l = h.associations[d];\n\t\t\tif (s = (s = t[l.id]) || e[l.id]) for (void 0 === s.properties && (s.properties = {},\n\t\t\ts.properties.boxes = []), n = 0; n < l.props.length; n++) {\n\t\t\t\tvar p = l.props[n];\n\t\t\t\t0 < p.property_index && p.property_index - 1 < i.iprp.ipco.boxes.length && (p = i.iprp.ipco.boxes[p.property_index - 1], s.properties[p.type] = p, s.properties.boxes.push(p))\n\t\t\t}\n\t\t}\n\t}\n},\nISOFile.prototype.getItem = function(t) {\n\tvar e, i;\n\tif (!this.meta) return null;\n\tif (! (i = this.items[t]).data && i.size) i.data = new Uint8Array(i.size),\n\ti.alreadyRead = 0,\n\tthis.itemsDataSize += i.size,\n\tLog.debug("ISOFile", "Allocating item #" + t + " of size " + i.size + " (total: " + this.itemsDataSize + ")");\n\telse if (i.alreadyRead === i.size) return i;\n\tfor (var r = 0; r < i.extents.length; r++) {\n\t\tvar s = i.extents[r];\n\t\tif (s.alreadyRead !== s.length) {\n\t\t\tvar a = this.stream.findPosition(!0, s.offset + s.alreadyRead, !1);\n\t\t\tif (! (-1 < a)) return null;\n\t\t\ta = (e = this.stream.buffers[a]).byteLength - (s.offset + s.alreadyRead - e.fileStart);\n\t\t\tif (! (s.length - s.alreadyRead <= a)) return Log.debug("ISOFile", "Getting item #" + t + " extent #" + r + " partial data (alreadyRead: " + s.alreadyRead + " offset: " + (s.offset + s.alreadyRead - e.fileStart) + " read size: " + a + " full extent size: " + s.length + " full item size: " + i.size + ")"),\n\t\t\tDataStream.memcpy(i.data.buffer, i.alreadyRead, e, s.offset + s.alreadyRead - e.fileStart, a),\n\t\t\ts.alreadyRead += a,\n\t\t\ti.alreadyRead += a,\n\t\t\te.usedBytes += a,\n\t\t\tthis.stream.logBufferLevel(),\n\t\t\tnull;\n\t\t\tLog.debug("ISOFile", "Getting item #" + t + " extent #" + r + " data (alreadyRead: " + s.alreadyRead + " offset: " + (s.offset + s.alreadyRead - e.fileStart) + " read size: " + (s.length - s.alreadyRead) + " full extent size: " + s.length + " full item size: " + i.size + ")"),\n\t\t\tDataStream.memcpy(i.data.buffer, i.alreadyRead, e, s.offset + s.alreadyRead - e.fileStart, s.length - s.alreadyRead),\n\t\t\te.usedBytes += s.length - s.alreadyRead,\n\t\t\tthis.stream.logBufferLevel(),\n\t\t\ti.alreadyRead += s.length - s.alreadyRead,\n\t\t\ts.alreadyRead = s.length\n\t\t}\n\t}\n\treturn i.alreadyRead === i.size ? i: null\n},\nISOFile.prototype.releaseItem = function(t) {\n\tvar e = this.items[t];\n\tif (e.data) {\n\t\tthis.itemsDataSize -= e.size,\n\t\te.data = null;\n\t\tfor (var i = e.alreadyRead = 0; i < e.extents.length; i++) e.extents[i].alreadyRead = 0;\n\t\treturn e.size\n\t}\n\treturn 0\n},\nISOFile.prototype.processItems = function(t) {\n\tfor (var e in this.items) {\n\t\tvar i = this.items[e];\n\t\tthis.getItem(i.id),\n\t\tt && !i.sent && (t(i), i.sent = !0, i.data = null)\n\t}\n},\nISOFile.prototype.hasItem = function(t) {\n\tfor (var e in this.items) {\n\t\tvar i = this.items[e];\n\t\tif (i.name === t) return i.id\n\t}\n\treturn - 1\n},\nISOFile.prototype.getMetaHandler = function() {\n\treturn this.meta ? this.meta.hdlr.handler: null\n},\nISOFile.prototype.getPrimaryItem = function() {\n\treturn this.meta && this.meta.pitm ? this.getItem(this.meta.pitm.item_id) : null\n},\nISOFile.prototype.itemToFragmentedTrackFile = function(t) {\n\tvar e = t || {},\n\ti = null;\n\tif (null == (i = e.itemId ? this.getItem(e.itemId) : this.getPrimaryItem())) return null;\n\tt = new ISOFile;\n\tt.discardMdatData = !1;\n\te = {\n\t\ttype: i.type,\n\t\tdescription_boxes: i.properties.boxes\n\t};\n\ti.properties.ispe && (e.width = i.properties.ispe.image_width, e.height = i.properties.ispe.image_height);\n\te = t.addTrack(e);\n\treturn e ? (t.addSample(e, i.data), t) : null\n},\nISOFile.prototype.write = function(t) {\n\tfor (var e = 0; e < this.boxes.length; e++) this.boxes[e].write(t)\n},\nISOFile.prototype.createFragment = function(t, e, i) {\n\tvar r = this.getTrackById(t),\n\tt = this.getSample(r, e);\n\tif (null == t) return this.setNextSeekPositionFromSample(r.samples[e]),\n\tnull;\n\te = i || new DataStream;\n\te.endianness = DataStream.BIG_ENDIAN;\n\ti = this.createSingleSampleMoof(t);\n\ti.write(e),\n\ti.trafs[0].truns[0].data_offset = i.size + 8,\n\tLog.debug("MP4Box", "Adjusting data_offset with new value " + i.trafs[0].truns[0].data_offset),\n\te.adjustUint32(i.trafs[0].truns[0].data_offset_position, i.trafs[0].truns[0].data_offset);\n\ti = new BoxParser.mdatBox;\n\treturn i.data = t.data,\n\ti.write(e),\n\te\n},\nISOFile.writeInitializationSegment = function(t, e, i, r) {\n\tvar s;\n\tLog.debug("ISOFile", "Generating initialization segment");\n\tvar a = new DataStream;\n\ta.endianness = DataStream.BIG_ENDIAN,\n\tt.write(a);\n\tvar n = e.add("mvex");\n\tfor (i && n.add("mehd").set("fragment_duration", i), s = 0; s < e.traks.length; s++) n.add("trex").set("track_id", e.traks[s].tkhd.track_id).set("default_sample_description_index", 1).set("default_sample_duration", r).set("default_sample_size", 0).set("default_sample_flags", 65536);\n\treturn e.write(a),\n\ta.buffer\n},\nISOFile.prototype.save = function(t) {\n\tvar e = new DataStream;\n\te.endianness = DataStream.BIG_ENDIAN,\n\tthis.write(e),\n\te.save(t)\n},\nISOFile.prototype.getBuffer = function() {\n\tvar t = new DataStream;\n\treturn t.endianness = DataStream.BIG_ENDIAN,\n\tthis.write(t),\n\tt.buffer\n},\nISOFile.prototype.initializeSegmentation = function() {\n\tvar t, e, i, r;\n\tfor (null === this.onSegment && Log.warn("MP4Box", "No segmentation callback set!"), this.isFragmentationInitialized || (this.isFragmentationInitialized = !0, this.nextMoofNumber = 0, this.resetTables()), e = [], t = 0; t < this.fragmentedTracks.length; t++) {\n\t\tvar s = new BoxParser.moovBox;\n\t\ts.mvhd = this.moov.mvhd,\n\t\ts.boxes.push(s.mvhd),\n\t\ti = this.getTrackById(this.fragmentedTracks[t].id),\n\t\ts.boxes.push(i),\n\t\ts.traks.push(i),\n\t\t(r = {}).id = i.tkhd.track_id,\n\t\tr.user = this.fragmentedTracks[t].user,\n\t\tr.buffer = ISOFile.writeInitializationSegment(this.ftyp, s, this.moov.mvex && this.moov.mvex.mehd ? this.moov.mvex.mehd.fragment_duration: void 0, 0 < this.moov.traks[t].samples.length ? this.moov.traks[t].samples[0].duration: 0),\n\t\te.push(r)\n\t}\n\treturn e\n},\nBoxParser.Box.prototype.printHeader = function(t) {\n\tthis.size += 8,\n\tthis.size > MAX_SIZE && (this.size += 8),\n\t"uuid" === this.type && (this.size += 16),\n\tt.log(t.indent + "size:" + this.size),\n\tt.log(t.indent + "type:" + this.type)\n},\nBoxParser.FullBox.prototype.printHeader = function(t) {\n\tthis.size += 4,\n\tBoxParser.Box.prototype.printHeader.call(this, t),\n\tt.log(t.indent + "version:" + this.version),\n\tt.log(t.indent + "flags:" + this.flags)\n},\nBoxParser.Box.prototype.print = function(t) {\n\tthis.printHeader(t)\n},\nBoxParser.ContainerBox.prototype.print = function(t) {\n\tthis.printHeader(t);\n\tfor (var e, i = 0; i < this.boxes.length; i++) this.boxes[i] && (e = t.indent, t.indent += " ", this.boxes[i].print(t), t.indent = e)\n},\nISOFile.prototype.print = function(t) {\n\tt.indent = "";\n\tfor (var e = 0; e < this.boxes.length; e++) this.boxes[e] && this.boxes[e].print(t)\n},\nBoxParser.mvhdBox.prototype.print = function(t) {\n\tBoxParser.FullBox.prototype.printHeader.call(this, t),\n\tt.log(t.indent + "creation_time: " + this.creation_time),\n\tt.log(t.indent + "modification_time: " + this.modification_time),\n\tt.log(t.indent + "timescale: " + this.timescale),\n\tt.log(t.indent + "duration: " + this.duration),\n\tt.log(t.indent + "rate: " + this.rate),\n\tt.log(t.indent + "volume: " + (this.volume >> 8)),\n\tt.log(t.indent + "matrix: " + this.matrix.join(", ")),\n\tt.log(t.indent + "next_track_id: " + this.next_track_id)\n},\nBoxParser.tkhdBox.prototype.print = function(t) {\n\tBoxParser.FullBox.prototype.printHeader.call(this, t),\n\tt.log(t.indent + "creation_time: " + this.creation_time),\n\tt.log(t.indent + "modification_time: " + this.modification_time),\n\tt.log(t.indent + "track_id: " + this.track_id),\n\tt.log(t.indent + "duration: " + this.duration),\n\tt.log(t.indent + "volume: " + (this.volume >> 8)),\n\tt.log(t.indent + "matrix: " + this.matrix.join(", ")),\n\tt.log(t.indent + "layer: " + this.layer),\n\tt.log(t.indent + "alternate_group: " + this.alternate_group),\n\tt.log(t.indent + "width: " + this.width),\n\tt.log(t.indent + "height: " + this.height)\n};\nvar MP4Box = {\n\tcreateFile: function(t, e) {\n\t\tt = void 0 === t || t,\n\t\te = new ISOFile(e);\n\t\treturn e.discardMdatData = !t,\n\t\te\n\t}\n};\n"undefined" != typeof exports && (exports.createFile = MP4Box.createFile);\n',workerLogic="\n// 显式将变量绑定到self上,确保全局可访问\nself.abortFlag = false;\nself.mp4boxfile = null;\nself.videoDecoder = null;\nself.samplesInRange = [];\nself.videoTrack = null;\nself.arrayBuffer = null;\n\nonmessage = function(e) {\n if (e.data.type === 'decode') {\n self.abortFlag = false;\n decodeFile(e.data.file, e.data.start, e.data.end, e.data.hardwareAcceleration);\n } else if (e.data.type === 'abort') {\n self.abortFlag = true;\n // 主动销毁所有大对象和引用\n if (self.videoDecoder) {\n try {\n self.videoDecoder.flush();\n self.videoDecoder.reset();\n self.videoDecoder.close();\n } catch (err) {}\n self.videoDecoder = null;\n }\n if (self.mp4boxfile) {\n try { self.mp4boxfile.flush(); } catch (err) {}\n self.mp4boxfile = null;\n }\n self.samplesInRange = [];\n self.videoTrack = null;\n self.arrayBuffer = null;\n // 关闭worker\n self.close();\n }\n};\n\nfunction decodeFile(file, startFrame, endFrame, hardwareAcceleration) {\n self.arrayBuffer = file.data;\n self.mp4boxfile = MP4Box.createFile();\n self.videoTrack = null;\n let nbSampleTotal = 0;\n self.samplesInRange = [];\n self.videoDecoder = null;\n let frameIndex = 0;\n let totalFrames = 0;\n self.mp4boxfile.onReady = function(info) {\n self.videoTrack = info.videoTracks[0];\n nbSampleTotal = self.videoTrack.nb_samples;\n self.mp4boxfile.setExtractionOptions(self.videoTrack.id, null, {\n nbSamples: nbSampleTotal,\n rapAlignement: true\n });\n self.mp4boxfile.start();\n };\n self.mp4boxfile.onSamples = async function(trackId, ref, samples) {\n if (self.abortFlag) return; // 确保使用self访问\n // 自动对齐到区间内第一个关键帧\n let startIdx = Math.min(0, startFrame); // 修复Math.min, 因为仅有第一帧是关键帧\n let endIdx = Math.min(samples.length - 1, endFrame);\n while (startIdx <= endIdx && !samples[startIdx].is_sync) {\n startIdx++;\n }\n if (startIdx > endIdx) {\n // 区间内没有关键帧,直接done\n postMessage({ type: 'done' });\n return;\n }\n self.samplesInRange = samples.slice(0, endIdx + 1);\n totalFrames = self.samplesInRange.length;\n if (!self.videoDecoder) {\n self.videoDecoder = new VideoDecoder({\n output: handleFrame,\n error: err => {\n postMessage({ type: 'error', error: err.message })\n }\n });\n const entry = self.mp4boxfile.moov.traks[0].mdia.minf.stbl.stsd.entries[0];\n const box = entry.avcC ?? entry.hvcC ?? entry.vpcC;\n let description = undefined;\n if (box) {\n const stream = new DataStream(undefined, 0, DataStream.BIG_ENDIAN);\n box.write(stream);\n description = new Uint8Array(stream.buffer.slice(8));\n }\n\t\tconst isIOS = /(iPhone|iPad|iPod|iOS)/i.test(navigator.userAgent);\n \tconst userAgent = (navigator.userAgent || \"\").toLowerCase();\n\t const isAndroid = /android/.test(userAgent) || /openharmony|arkweb/.test(userAgent);\n\t\tconst defaultConfig = {\n\t\t\tcodec: self.videoTrack.codec,\n\t\t\tcodedWidth: self.videoTrack.track_width,\n\t\t\tcodedHeight: self.videoTrack.track_height,\n\t\t\tdescription,\n\t\t}\n\t\t// Android 系统下,默认配置为 prefer-software 以避免硬件解码问题\n\t\tlet config = isAndroid ? { ...defaultConfig, hardwareAcceleration: 'prefer-software' } : hardwareAcceleration === 'default' ? defaultConfig\t: {\n\t\t\t...defaultConfig,\n\t\t\thardwareAcceleration: hardwareAcceleration,\n\t\t}\n\t\t// let config = hardwareAcceleration === 'default' ? defaultConfig\t: {\n\t\t// \t...defaultConfig,\n\t\t// \thardwareAcceleration: hardwareAcceleration,\n\t\t// }\n\t\tconst configSupport = (await VideoDecoder.isConfigSupported(config));\n\t\tconst isConfigSupported = configSupport.supported;\n\t\tpostMessage({ type: 'configSupport', configSupport: { config, configSupport}});\n\t\tlet isDefaultConfigSupported = false;\n\t\tif(!isConfigSupported) {\n\t\t\tconst defaultConfigSupport = await VideoDecoder.isConfigSupported(defaultConfig);\n\t\t\tpostMessage({ type: 'configSupport', configSupport: { defaultConfig, configSupport: defaultConfigSupport}});\n\t\t\tisDefaultConfigSupported = defaultConfigSupport.supported;\n\t\t}\n\t\tif(isConfigSupported) {\n\t\t\tself.videoDecoder.configure(config);\n\t\t} else if(isDefaultConfigSupported) {\n\t\t\tself.videoDecoder.configure(defaultConfig);\n\t\t} else {\n\t\t\tpostMessage({ type: 'error', error: '不支持的视频解码配置' });\n\t\t}\n }\n for (let i = 0; i < self.samplesInRange.length; i++) {\n if (self.abortFlag) break; // 确保使用self访问\n \n const sample = self.samplesInRange[i];\n const chunk = new EncodedVideoChunk({\n type: sample.is_sync ? 'key' : 'delta',\n timestamp: sample.cts,\n duration: sample.duration,\n data: sample.data\n });\n self.videoDecoder.decode(chunk);\n }\n self.videoDecoder.flush().then(() => {\n postMessage({ type: 'done' });\n });\n };\n function handleFrame(videoFrame) {\n if (self.abortFlag) { // 确保使用self访问\n videoFrame.close();\n return;\n }\n postMessage({ type: 'frame', frame: videoFrame, index: frameIndex++, total: totalFrames }, [videoFrame]);\n }\n self.arrayBuffer.fileStart = 0;\n self.mp4boxfile.appendBuffer(self.arrayBuffer);\n self.mp4boxfile.flush();\n}\n",fullWorkerScript=`\ntry {\n ${mp4boxSource}\n self.MP4Box = MP4Box;\n ${workerLogic}\n} catch (error) {\n console.error('Worker初始化失败:', error);\n throw error;\n}\n`,blob=new Blob([fullWorkerScript],{type:"application/javascript"}),workerURL=URL.createObjectURL(blob);var streamingVideo={__proto__:null,workerURL};function base64ToUint8Array(t){if(!t||""===t.trim())return new Uint8Array(0);const e=atob(t),n=new Uint8Array(e.length);for(let t=0;t<e.length;t++)n[t]=e.charCodeAt(t);return n}function twoByteToInt16(t,e){const n=t|e<<8;return Math.max(-32767,Math.min(32767,n>32767?n-65536:n))}function scaledInt16BytesToFloat32(t){const e=base64ToUint8Array(t);if(0===e.length||e.length%2!=0)return[];const n=e.length/2,r=new ArrayBuffer(4*n),i=new Float32Array(r);for(let t=0;t<n;t++){const n=2*t,r=twoByteToInt16(e[n],e[n+1]);i[t]=r/32767}return Array.from(i)}function parseUint8ToFloat32(t){if(!t||0===t.length)return[];if(t.length%4!=0)return window.avatarSDKLogger.error("Uint8Array长度不是4的倍数,无法解析为float32数组"),[];const e=new ArrayBuffer(t.length);new Uint8Array(e).set(t);const n=new Float32Array(e);return Array.from(n)}class ParallelDecoder{constructor(t){this.pendingAbort=!1,this.abortAfterEf=null,this.pendingNewQueue=null,this.currentDecodedFrameIndex=null,this.abortAfterFrame=null,this.cacheVideoCount=5,this.maxVideoCount=2,this.hardwareAcceleration="default",this.MAX_LOAD_VIDEO_TIMEOUT_MS=2e3,this._offlineLastFrame=0,this._offlineIdle=[],this._offlineIdleIndex=0,this.firstDecodeFrame=!0,this.tasks=new Map,this.queue=[],this.maxParallel=1,this.currentParallel=0,this._locked=!1,this.currentTaskId=null,this.resourceManager=t.resourceManager,this.onFrame=()=>{},this.onDone=()=>{},this.isFirstDecode=!0,this.saveAndDownload=t.saveAndDownload,this.dataCacheQueue=t.dataCacheQueue,this.bodyFrameCountMap=new Map,this.hardwareAcceleration=t.hardwareAcceleration,this.reportMessage=t.reportMessage}getRandomTaskId(){return Date.now()+"_"+Math.random().toString(36).slice(2,10)}decode(t,e){if(this.isFirstDecode){if(this._locked)return;this.abort(),this._locked=!0,this.queue=t,this.onFrame=(t,n,r)=>{this.currentDecodedFrameIndex=t.startFrameIndex+r,this._handlePendingAbort(t,r),e(t,n,r)},this.currentParallel=0,this.currentTaskId=this.getRandomTaskId(),this.isFirstDecode=!1}else this.updateQueue(t)}clearOldQueue(t){this.queue=this.queue.filter(e=>e.sf>=t)}updateQueue(t){if(this.abortAfterFrame=null,0===this.queue.length)return void this.queue.push(...t);const e=this.queue[0].sf,n=t[0].sf;if(n>=this.queue[this.queue.length-1].ef)this.queue.push(...t);else if(n<e){if(null!==this.currentDecodedFrameIndex&&n>this.currentDecodedFrameIndex+1){this.abortAfterFrame=n-1;const e=this.queue.filter(t=>t.ef<n);return void(this.queue=e.concat(t))}this.abort(),this.queue=t.slice(),this._locked=!0,this.currentTaskId=this.getRandomTaskId(),this.dataCacheQueue.clearOldFrames(this.queue[0].sf)}else if(n===e)this.queue=t.slice(),this.dataCacheQueue.clearOldFrames(this.queue[0].sf);else{const e=this.queue.findIndex(t=>t.sf>=n);-1!==e&&(this.queue.length=e),this.abortAfterFrame=n-1,this.queue.push(...t)}}_isIOS(){return/iPad|iPhone|iPod|iOS/.test(navigator.userAgent)}getQueue(){return this.queue.map(t=>_extends({},t,{x_offset:[]}))}timeoutPromise(t,e="请求超时"){return new Promise((e,n)=>{setTimeout(()=>{n()},t)})}async loadVideoWithTimeout(t){try{return await Promise.race([this.resourceManager.loadVideo(t),this.timeoutPromise(this.MAX_LOAD_VIDEO_TIMEOUT_MS,`视频 ${t} 加载超时(${this.MAX_LOAD_VIDEO_TIMEOUT_MS}ms)`)])}catch(t){return null}}async _tryStartNext(){var t;let e;if(e=(null==(t=this.queue)?void 0:t.some(t=>null!==this.currentDecodedFrameIndex&&t.sf<this.currentDecodedFrameIndex))?this._isIOS()?this.maxVideoCount:this.maxVideoCount+1:this._isIOS()?1:this.maxVideoCount,!(this.dataCacheQueue.getBodyVideoNameListLength()>=e)&&this.currentParallel<this.maxParallel&&this.queue.length>0){var n,r;const t=this.queue.shift();if(this.saveAndDownload.appendMultipleToArray("videoData",[_extends({},t,{x_offset:parseUint8ToFloat32(t.x_offset)||[]})]),this._cleanupOldWorkers(null!=(n=null!=(r=t.body_id)?r:t.id)?n:0),this.currentParallel++,window.performanceTracker.markStart(performanceConstant.load_video,t),!t.n)return this.currentParallel--,this._tryStartNext(),void this.reportMessage({code:EErrorCode.INVALID_BODY_NAME,message:`body数据无Name: ${JSON.stringify(t)}`});const e=await this.loadVideoWithTimeout(t.n);if(!e)return this.currentParallel--,void this._tryStartNext();window.performanceTracker.markEnd(performanceConstant.load_video,t),window.performanceTracker.markStart(performanceConstant.decode_video,t),window.performanceTracker.markStart(performanceConstant.first_decode_video,t),this._startWorker({name:t.n,id:t.id,frameState:t.s,start:t.asf,end:t.aef,hfd:t.hfd,data:e,startFrameIndex:t.sf,endFrameIndex:t.ef,body_id:t.body_id,x_offset:parseUint8ToFloat32(t.x_offset)||[]})}}_startWorker(t){var e,n;const r=this.currentTaskId;let i;try{i=new Worker(workerURL)}catch(t){return void this.reportMessage({code:EErrorCode.INIT_WORKER_ERROR,message:"初始化视频抽帧Worker失败",e:t})}const s=`${null!=(e=null!=(n=t.body_id)?n:t.id)?e:0}_${t.name}`,a=t.data,o=new ArrayBuffer(a.byteLength);new Uint8Array(o).set(new Uint8Array(a)),i.addEventListener("error",t=>{r===this.currentTaskId&&this.reportMessage({code:EErrorCode.INIT_WORKER_ERROR,message:"视频抽帧Worker运行时错误",e:t})});const l=e=>{if(r===this.currentTaskId)if("frame"===e.data.type)if(this.firstDecodeFrame&&(this.firstDecodeFrame=!1,window.performanceTracker.markEnd(performanceConstant.first_decode_video,t)),e.data.index<t.start||e.data.index>t.end)e.data.frame.close();else{var n;this.cacheVideo(),this.onFrame(t,e.data.frame,e.data.index);const r=null!=(n=this.bodyFrameCountMap.get(t.name))?n:0;this.bodyFrameCountMap.set(t.name,r+1),this.abortAfterFrame&&e.data.index+t.startFrameIndex>=this.abortAfterFrame&&(window.avatarSDKLogger.log("abortAfterFrame",this.abortAfterFrame,t),this.abortOne(s),this.abortAfterFrame=null,this._tryStartNext())}else if("configSupport"===e.data.type)window.avatarSDKLogger.log("configSupport",e.data);else if("done"===e.data.type){var a;window.performanceTracker.markEnd(performanceConstant.decode_video,t),(null!=(a=this.bodyFrameCountMap.get(t.name))?a:0)<t.end-t.start-1&&this.bodyFrameCountMap.delete(t.name);const e=this.tasks.get(s);e&&(e.status="done",e.worker.postMessage({type:"abort"})),this.currentParallel--,this.onDone&&this.onDone(t,s),i.removeEventListener("message",l),i.terminate(),this.tasks.delete(s),0===this.currentParallel&&0===this.queue.length&&(this._locked=!1),this._tryStartNext()}else if("error"===e.data.type){var o;const n=null!=(o=e.data.error)?o:"",r=n.includes("不支持")?EErrorCode.PROCESS_VIDEO_STREAM_ERROR:EErrorCode.VIDEO_FRAME_EXTRACT_ERROR;this.reportMessage({code:r,message:n||"视频解码错误",e:{fileName:t.name,error:n}});const a=this.tasks.get(s);a&&(a.status="error",a.worker.postMessage({type:"abort"})),this.currentParallel--,this.onDone&&this.onDone(t,s),i.removeEventListener("message",l),i.terminate(),this.tasks.delete(s),0===this.currentParallel&&0===this.queue.length&&(this._locked=!1)}};i.addEventListener("message",l),this.tasks.set(s,{worker:i,status:"decoding",onMessage:l,ef:t.endFrameIndex}),window.avatarSDKLogger.log("start decode",t.name,t.startFrameIndex,t.endFrameIndex),i.postMessage({type:"decode",file:{data:o},start:t.start,end:t.end,hardwareAcceleration:this.hardwareAcceleration,taskId:r},[o])}cacheVideo(){const t=this.queue.slice(0,this.cacheVideoCount);for(const e of t)this.resourceManager.preloadVideo(e.n)}abort(){this.tasks.forEach(({worker:t,status:e,onMessage:n})=>{"decoding"===e&&(t.postMessage({type:"abort"}),n&&t.removeEventListener("message",n),t.terminate())}),this.tasks.clear(),this.queue=[],this.currentParallel=0,this._locked=!1,this.currentTaskId=null}abortOne(t){const e=this.tasks.get(t);e&&"decoding"===e.status&&(null==e||e.worker.postMessage({type:"abort"}),null!=e&&e.onMessage&&e.worker.removeEventListener("message",e.onMessage),null==e||e.worker.terminate(),this.tasks.delete(t),this.currentParallel--,0===this.currentParallel&&0===this.queue.length&&(this._locked=!1))}destroy(){this.abort(),this.queue=[],this.currentParallel=0,this._locked=!1,this.currentTaskId=null,this.pendingAbort=!1,this.abortAfterEf=null,this.pendingNewQueue=null,this.abortAfterFrame=null,this.currentDecodedFrameIndex=null,this.firstDecodeFrame=!0}_handlePendingAbort(t,e){this.pendingAbort&&null!==this.abortAfterEf&&t.startFrameIndex+e>=this.abortAfterEf&&(this.abort(),this.queue=this.pendingNewQueue,this._locked=!0,this.currentTaskId=this.getRandomTaskId(),this.pendingAbort=!1,this.abortAfterEf=null,this.pendingNewQueue=null)}_cleanupOldWorkers(t){for(const[e,n]of this.tasks){const[r]=e.split("_"),i=parseInt(r,10);!isNaN(i)&&i<t&&(n.worker.postMessage({type:"abort"}),n.onMessage&&n.worker.removeEventListener("message",n.onMessage),n.worker.terminate(),this.tasks.delete(e))}}syncDecode(t){const e=this.queue.filter(e=>e.ef>t);0!==e.length&&(this.abort(),this.queue=e,this._locked=!0,this.currentTaskId=this.getRandomTaskId(),this._tryStartNext())}_reload(){this._offlineLastFrame=0,this.queue=[]}_offLineMode(t,e){this.abort(),this._offlineLastFrame=e,this._offlineIdle=t,this.currentParallel-=1,this.queue=[],this._offlineRun()}_offlineRun(){const t=this._offlineIdle[this._offlineIdleIndex];t?(this._offlineIdleIndex+=1,this._putOfflineBodyData(t)):this._offlineIdleIndex=0}_putOfflineBodyData(t){const e={id:-1,n:t.n,s:"idle",hfd:!1,body_id:-1,asf:t.asf,aef:t.aef,sf:this._offlineLastFrame,ef:this._offlineLastFrame+(t.aef-t.asf),x_offset:new Uint8Array};this.queue.push(e),this._offlineLastFrame=e.ef}}class FrameAnimationController{constructor({defaultSpeed:t=1,frameRate:e=24,frameCallback:n}={}){this.startTime=null,this.currentFrame=1,this.speed=t,this.frameCallback=n||null,this.frameRate=e,this.isPlaying=!1,this.animationId=null,this.startTimeFromDate=null,this.currentFrameFromDate=null}get playing(){return this.isPlaying}play(){this.isPlaying||(this.isPlaying=!0,window.avatarSDKLogger.log("开始时间",this.startTime),null===this.startTime&&(window.avatarSDKLogger.log("当前时间",performance.now()),this.startTime=performance.now(),this.startTimeFromDate=Date.now()),this.animationId=requestAnimationFrame(this._animate.bind(this)))}pause(){this.isPlaying=!1,this.animationId&&(cancelAnimationFrame(this.animationId),this.animationId=null)}reset(){this.pause(),this.startTime=null,this.currentFrame=1,this._updateFrame(),this.startTimeFromDate=null,this.currentFrameFromDate=null}setSpeed(t){this.speed=t}gotoFrame(t){t<1&&(t=1),this.currentFrame=t,this._updateFrame()}nextFrame(){this.currentFrame++,this._updateFrame()}prevFrame(){this.gotoFrame(this.currentFrame-1)}destroy(){this.pause(),this.frameCallback=null,this.startTime=null,this.startTimeFromDate=null,this.currentFrame=1,this.currentFrameFromDate=null,this.speed=1}_animate(t){let e=performance.now();if(Math.abs(t-e)<100&&(e=t),this.currentFrame<50&&window.avatarSDKLogger.log("animate时间",t,"开始时间",this.startTime,"performance",performance.now()),this.isPlaying){if(null!==this.startTime){const t=Math.floor(Math.floor((e-this.startTime)/(1e3/(2*this.frameRate)))/2)+1;t!==this.currentFrame&&(this.currentFrame=t,this._updateFrame());const n=Date.now()-this.startTimeFromDate,r=Math.floor(Math.floor(n/(1e3/(2*this.frameRate)))/2)+1;this.currentFrameFromDate=r}this.isPlaying&&(this.animationId=requestAnimationFrame(this._animate.bind(this)))}}_updateFrame(){let t=null;this.frameCallback&&(this.currentFrameFromDate!==this.currentFrame&&null!==this.currentFrameFromDate&&(t={key:"frame_number_error",Date帧号:this.currentFrameFromDate,performance帧号:this.currentFrame,开始时间:this.startTime,开始时间日期:this.startTimeFromDate,当前时间:Date.now(),"performance.now()":performance.now()}),this.frameCallback(this.currentFrame,t))}getCurrentFrame(){if(null!==this.startTime){const t=performance.now()-this.startTime;return Math.floor(Math.floor(t/(1e3/(2*this.frameRate)))/2)+1}return this.currentFrame}updateStartTime(t){this.startTime=performance.now()-1e3/this.frameRate*(t-1),this.startTimeFromDate=Date.now()-1e3/this.frameRate*(t-1)}}const captureStates=new WeakMap,playbackSessionRestoredListeners=new WeakMap;function configureWebAudioPlaybackSession(t=navigator){const e=getAudioSession(t);if(!e)return!1;const n=captureStates.get(e);return setAudioSessionType(e,null!=n&&n.count||"play-and-record"===e.type?"play-and-record":"playback")}function subscribeWebAudioPlaybackSessionRestored(t,e=navigator){const n=getAudioSession(e);if(!n)return()=>{};let r=playbackSessionRestoredListeners.get(n);return r||(r=new Set,playbackSessionRestoredListeners.set(n,r)),r.add(t),()=>{var e,i;null==(e=r)||e.delete(t),0===(null==(i=r)?void 0:i.size)&&playbackSessionRestoredListeners.delete(n)}}function getAudioSession(t){return t.audioSession}function setAudioSessionType(t,e){try{return t.type=e,t.type===e}catch(t){return!1}}const pcm_audio_script="// pcm-audio-processor.js - 运行在音频线程的Worklet处理器\nclass PCMAudioProcessor extends AudioWorkletProcessor {\n // 音量配置(与主线程保持一致)\n static get parameterDescriptors() {\n return [\n {\n name: 'volume',\n defaultValue: 1.0,\n minValue: 0.0,\n maxValue: 1.0,\n automationRate: 'a-rate' // 支持音频速率自动化\n }\n ];\n }\n\n constructor() {\n super();\n this.config = {\n sampleRate: 24000, // 固定24kHz采样率\n bytesPerSample: 2, // S16LE=2字节/采样点\n };\n this.pcmCache = new Uint8Array(0); // Worklet内的PCM缓存\n this.isActive = false; // 播放音频状态(控制是否生成声音)\n this.isDestroyed = false;\n this.fadeState = {\n // 淡入淡出状态(避免片段切换爆音)\n phase: 'idle', // idle/fadeIn/fadeOut/steady\n currentGain: 0,\n fadeTime: 0.01, // 淡入淡出时间(秒,建议最小0.01s避免爆音)\n fadeSamples: Math.floor(0.01 * 24000), // 淡入淡出样本数(24000Hz下为240样本)\n };\n this.currentSegment = null; // 当前处理的音频段(float32数组)\n this.segmentOffset = 0; // 当前音频段的播放偏移量\n \n // 监听主线程消息(接收PCM数据、状态控制等)\n this.port.onmessage = (e) => this.handleMainThreadMessage(e.data);\n \n // 初始化淡入淡出样本数\n this.fadeState.fadeSamples = Math.floor(this.fadeState.fadeTime * this.config.sampleRate);\n }\n\n /**\n * 处理主线程发来的消息(PCM数据/状态控制等)\n * @param {Object} data - 消息数据\n * @param {string} data.type - 消息类型:'pcm'/'start'/'pause'/'stop'/'config'/'destroy'/'volume'\n * @param {Uint8Array} [data.pcmData] - PCM数据(仅type='pcm'时存在)\n * @param {Object} [data.config] - 配置更新(仅type='config'时存在)\n * @param {number} [data.volume] - 音量值(仅type='volume'时存在)\n */\n handleMainThreadMessage(data) {\n switch (data.type) {\n // 接收主线程下发的PCM流数据\n case 'pcm':\n if (data.pcmData instanceof Uint8Array && data.pcmData.length > 0) {\n // 确保PCM数据字节数为2的整数倍(S16LE要求)\n const validLength = data.pcmData.length - (data.pcmData.length % this.config.bytesPerSample);\n if (validLength <= 0) break;\n \n // 合并到Worklet缓存\n const newCache = new Uint8Array(this.pcmCache.length + validLength);\n newCache.set(this.pcmCache, 0);\n newCache.set(data.pcmData.subarray(0, validLength), this.pcmCache.length);\n this.pcmCache = newCache;\n \n // 向主线程发送缓存状态\n this.port.postMessage({\n type: 'cacheStatus',\n size: this.pcmCache.length,\n sampleCount: this.pcmCache.length / this.config.bytesPerSample\n });\n }\n break;\n\n // 启动播放(继续音频生成)\n case 'start':\n this.isActive = true;\n break;\n\n // 暂停播放(停止音频生成,保留缓存)\n case 'pause':\n this.isActive = false;\n this.resetSegmentState();\n break;\n\n // 停止播放(清空缓存+重置状态)\n case 'stop':\n this.isActive = false;\n this.pcmCache = new Uint8Array(0);\n this.resetSegmentState();\n break;\n\n // 更新配置(如采样率/淡入淡出时间)\n case 'config':\n if (data.config.sampleRate) {\n this.config.sampleRate = data.config.sampleRate;\n // 重新计算淡入淡出样本数\n this.fadeState.fadeSamples = Math.floor(this.fadeState.fadeTime * this.config.sampleRate);\n }\n if (data.config.fadeTime) {\n this.fadeState.fadeTime = data.config.fadeTime;\n this.fadeState.fadeSamples = Math.floor(this.fadeState.fadeTime * this.config.sampleRate);\n }\n break;\n\n // 单独更新音量(可选,也可通过参数自动化控制)\n case 'volume':\n this.volume = Number(data.volume);\n // 通知主线程同步AudioWorkletNode的parameters\n this.port.postMessage({\n type: 'syncVolume',\n volume: this.volume\n });\n break;\n\n // 单独更新播放速率(可选,也可通过参数自动化控制)\n case 'speed':\n this.speed = Number(data.speed);\n // 通知主线程同步AudioWorkletNode的parameters\n this.port.postMessage({\n type: 'syncSpeed',\n speed: this.speed\n });\n break;\n\n // 销毁处理器\n case 'destroy':\n this.isDestroyed = true;\n this.isActive = false;\n this.pcmCache = new Uint8Array(0);\n this.resetSegmentState();\n this.port.postMessage({ type: 'destroyConfirmed' });\n break;\n \n default:\n console.warn('[PCMAudioProcessor] 未知消息类型:', data.type);\n }\n }\n\n /**\n * 重置当前音频段状态(暂停/停止时调用)\n */\n resetSegmentState() {\n this.currentSegment = null;\n this.segmentOffset = 0;\n this.fadeState.phase = 'idle';\n this.fadeState.currentGain = 0;\n }\n\n /**\n * S16LE Uint8Array 转 Float32Array(-1~1范围)\n * @param {Uint8Array} pcmData - PCM数据\n * @returns {Float32Array} 转换后的音频样本\n */\n pcmToFloat32(pcmData) {\n const sampleCount = pcmData.length / this.config.bytesPerSample;\n const floatData = new Float32Array(sampleCount);\n const dataView = new DataView(pcmData.buffer);\n\n for (let i = 0; i < sampleCount; i++) {\n // S16LE格式:小端序解析,范围-32768~32767 归一化到-1~1\n floatData[i] = dataView.getInt16(i * this.config.bytesPerSample, true) / 32768;\n }\n return floatData;\n }\n\n /**\n * 计算当前样本的增益(淡入淡出)\n * @param {number} segmentLength - 当前音频段的总样本数\n * @returns {number} 增益值(0~1)\n */\n calculateGain(segmentLength) {\n const { phase, fadeSamples } = this.fadeState;\n const { segmentOffset } = this;\n\n // 边界保护:防止无效值导致的NaN\n if (typeof segmentOffset !== 'number' || typeof segmentLength !== 'number' || segmentLength <= 0) {\n return 0;\n }\n\n switch (phase) {\n // 淡入阶段:从0线性增加到1\n case 'fadeIn':\n if (segmentOffset >= fadeSamples) {\n this.fadeState.phase = 'steady';\n return 1;\n }\n return segmentOffset / fadeSamples;\n\n // 稳定阶段:增益保持1\n case 'steady':\n // 检测是否进入淡出阶段(接近段尾)\n if (segmentOffset >= segmentLength - fadeSamples) {\n this.fadeState.phase = 'fadeOut';\n }\n return 1;\n\n // 淡出阶段:从1线性降低到0.0001(避免分音)\n case 'fadeOut':\n const fadeStart = Math.max(segmentLength - fadeSamples, 0);\n const fadeProgress = (segmentOffset - fadeStart) / fadeSamples;\n return Math.max(1 - fadeProgress, 0.0001);\n\n // 空闲阶段:增益0\n case 'idle':\n default:\n return 0;\n }\n }\n\n /**\n * AudioWorklet核心方法:实时生成音频样本(音频线程调用)\n * @param {Float32Array[][]} inputs - 输入样本\n * @param {Float32Array[][]} outputs - 输出样本(单声道)\n * @param {Object} parameters - 音频参数\n * @returns {boolean} 是否继续运行\n */\n process(inputs, outputs, parameters) {\n // 销毁状态:终止处理\n if (this.isDestroyed) {\n if (outputs.length > 0 && outputs[0].length > 0) {\n outputs[0][0].fill(0);\n }\n return false;\n }\n\n // 未激活或无输出:返回静音\n if (!this.isActive || outputs.length === 0 || outputs[0].length === 0) {\n outputs[0][0].fill(0);\n return true;\n }\n\n const outputBuffer = outputs[0][0];\n const bufferLength = outputBuffer.length;\n // 获取音量参数(支持自动化)\n const volume = parameters.volume.length > 1 \n ? parameters.volume // 自动化模式:每个样本点可能有不同值\n : parameters.volume[0]; // 控制模式:整个缓冲区使用相同值\n\n // 生成输出样本\n for (let i = 0; i < bufferLength; i++) {\n // 如当前无音频段且缓存有数据,创建新段\n if (!this.currentSegment && this.pcmCache.length > 0) {\n // 使用缓存中的所有数据创建新段\n this.currentSegment = this.pcmToFloat32(this.pcmCache);\n // 清空缓存(已处理)\n this.pcmCache = new Uint8Array(0);\n this.segmentOffset = 0;\n // 根据前一段状态决定是否淡入\n this.fadeState.phase = this.fadeState.phase === 'fadeOut' ? 'steady' : 'fadeIn';\n }\n\n // 生成当前样本\n let sample = 0;\n if (this.currentSegment) {\n const segmentLength = this.currentSegment.length;\n // 确保偏移量有效\n if (this.segmentOffset < segmentLength) {\n const gain = this.calculateGain(segmentLength);\n // 应用淡入淡出增益和音量控制\n sample = this.currentSegment[this.segmentOffset] * gain * volume;\n this.segmentOffset++;\n } else {\n // 当前段处理完毕,重置\n this.currentSegment = null;\n this.segmentOffset = 0;\n this.fadeState.phase = 'idle';\n }\n }\n\n outputBuffer[i] = sample;\n }\n\n return true;\n }\n}\n\n// 注册Worklet处理器\nregisterProcessor('pcm-audio-processor', PCMAudioProcessor);\n",pcm_capture_script="// pcm-capture-processor.js - 运行在音频线程的捕获处理器\nclass PCMCaptureProcessor extends AudioWorkletProcessor {\n constructor() {\n super();\n this.inputSampleRate = 24000; // PCM 播放器采样率\n this.outputSampleRate = 16000; // Opus 编码要求采样率\n this.bufferSize = 2400; // 100ms @ 24kHz\n this.buffer = new Float32Array(this.bufferSize);\n this.bufferIndex = 0;\n\n // 监听主线程的 reset 消息,清空内部缓冲区(打断/会话切换时使用)\n this.port.onmessage = (e) => {\n if (e.data && e.data.type === 'reset') {\n this.bufferIndex = 0;\n this.buffer.fill(0);\n }\n };\n }\n\n process(inputs) {\n const input = inputs[0];\n if (!input || !input[0] || input[0].length === 0) return true;\n\n const chunk = input[0];\n for (let i = 0; i < chunk.length; i++) {\n this.buffer[this.bufferIndex++] = chunk[i];\n\n if (this.bufferIndex >= this.bufferSize) {\n // 重采样 24kHz → 16kHz\n const resampled = this.resample(this.buffer);\n // Float32 → S16LE\n const pcmBuffer = this.float32ToS16LE(resampled);\n // 静音检测\n const hasAudio = this.detectAudio(this.buffer);\n // 回传主线程(Transferable,避免拷贝)\n this.port.postMessage(\n { pcmData: pcmBuffer.buffer, hasAudio: hasAudio },\n [pcmBuffer.buffer]\n );\n this.bufferIndex = 0;\n }\n }\n return true;\n }\n\n // 线性插值重采样 24kHz → 16kHz (3:2 比率)\n resample(input) {\n const ratio = this.outputSampleRate / this.inputSampleRate; // 2/3\n const outputLength = Math.floor(input.length * ratio); // 1600\n const output = new Float32Array(outputLength);\n for (let i = 0; i < outputLength; i++) {\n const srcIndex = i / ratio;\n const srcIndexFloor = Math.floor(srcIndex);\n const frac = srcIndex - srcIndexFloor;\n const s1 = input[srcIndexFloor] || 0;\n const s2 = input[srcIndexFloor + 1] || 0;\n output[i] = s1 + (s2 - s1) * frac;\n }\n return output;\n }\n\n // Float32 → S16LE Int16Array\n float32ToS16LE(float32) {\n const int16 = new Int16Array(float32.length);\n for (let i = 0; i < float32.length; i++) {\n let s = Math.max(-1, Math.min(1, float32[i]));\n int16[i] = s < 0 ? s * 0x8000 : s * 0x7FFF;\n }\n return int16;\n }\n\n // 静音检测\n detectAudio(buffer) {\n for (let i = 0; i < buffer.length; i++) {\n if (Math.abs(buffer[i]) > 0.0001) return true;\n }\n return false;\n }\n}\nregisterProcessor('pcm-capture-processor', PCMCaptureProcessor);\n",workletBlob=new Blob([pcm_audio_script],{type:"application/javascript"}),workletUrl=URL.createObjectURL(workletBlob),captureWorkletBlob=new Blob([pcm_capture_script],{type:"application/javascript"}),captureWorkletUrl=URL.createObjectURL(captureWorkletBlob);class PCMAudioPlayer{constructor(){this.SAMPLE_RATE=24e3,this.FRAME_ALIGNMENT=2e3,this.WORKLET_SCRIPT_URL=workletUrl,this.audioCtx=null,this.audioWorkletNode=null,this.isInitialized=!1,this.isPlaying=!1,this.destroyResolve=null,this.unsubscribePlaybackSessionRestored=null,this.captureWorklet=null,this.captureCallback=null}async init(){if(this.isInitialized)return;configureWebAudioPlaybackSession();const t=window.AudioContext||window.webkitAudioContext;if(!t||!window.AudioWorklet)throw new Error("当前浏览器不支持Web Audio Worklet,无法实现流式播放");this.audioCtx=new t({sampleRate:this.SAMPLE_RATE});const e=window.avatarSDKLogger||console;try{await this.audioCtx.audioWorklet.addModule(this.WORKLET_SCRIPT_URL),e.log(`[PCMAudioPlayer] Worklet脚本加载完成: ${this.WORKLET_SCRIPT_URL}`),this.audioWorkletNode=new AudioWorkletNode(this.audioCtx,"pcm-audio-processor"),this.audioWorkletNode.connect(this.audioCtx.destination),e.log("[PCMAudioPlayer] Worklet节点已连接到扬声器"),this.audioWorkletNode.port.onmessage=t=>{var n,r,i;switch(t.data.type){case"cacheStatus":e.log(`[PCMAudioPlayer] Worklet缓存状态: ${t.data.size}字节`);break;case"error":e.error("[PCMAudioPlayer] Worklet错误:",t.data.detail);break;case"destroyConfirmed":e.log("[PCMAudioPlayer] Worklet已确认销毁"),null==(n=this.destroyResolve)||n.call(this);break;case"syncVolume":void 0!==(null==(r=this.audioWorkletNode)||null==(r=r.parameters)||null==(r=r.get("volume"))?void 0:r.value)&&(this.audioWorkletNode.parameters.get("volume").value=t.data.volume);break;case"syncSpeed":void 0!==(null==(i=this.audioWorkletNode)||null==(i=i.parameters)||null==(i=i.get("speed"))?void 0:i.value)&&(this.audioWorkletNode.parameters.get("speed").value=t.data.speed);break;default:e.log("[PCMAudioPlayer] Worklet消息:",t.data)}},this.isInitialized=!0,this.unsubscribePlaybackSessionRestored=subscribeWebAudioPlaybackSessionRestored(()=>{this.refreshPlaybackRoute()}),e.log("[PCMAudioPlayer] 播放器初始化完成(Worklet就绪)")}catch(t){throw e.error("[PCMAudioPlayer] 初始化失败:",t),t}}refreshPlaybackRoute(){if(!(this.isInitialized&&this.isPlaying&&this.audioCtx&&this.audioWorkletNode))return!1;const t=window.avatarSDKLogger||console;try{return this.audioWorkletNode.disconnect(),this.audioWorkletNode.connect(this.audioCtx.destination),this.captureWorklet&&this.audioWorkletNode.connect(this.captureWorklet),"running"!==this.audioCtx.state&&this.audioCtx.resume().catch(e=>{t.warn("[PCMAudioPlayer] 刷新路由后恢复 AudioContext 失败:",e)}),t.log("[PCMAudioPlayer] 已刷新 playback 音频路由"),!0}catch(e){return t.warn("[PCMAudioPlayer] 刷新 playback 音频路由失败:",e),!1}}receivePCMStream(t){const e=window.avatarSDKLogger||console;if(this.isInitialized&&this.audioWorkletNode)if(t instanceof Uint8Array){e.log(`[PCMAudioPlayer] 已下发PCM数据: ${t.length}字节`);try{this.audioWorkletNode.port.postMessage({type:"pcm",pcmData:t},[t.buffer])}catch(t){e.error("[PCMAudioPlayer] 下发PCM数据到Worklet失败:",t)}}else e.error("[PCMAudioPlayer] 输入PCM数据必须是非空的Uint8Array");else e.error("[PCMAudioPlayer] 播放器未初始化,无法接收PCM数据")}async start(){if(!this.isInitialized||!this.audioCtx||!this.audioWorkletNode)throw new Error("[PCMAudioPlayer] 请先调用init()初始化播放器");const t=window.avatarSDKLogger||console;"running"!==this.audioCtx.state&&(await this.audioCtx.resume(),t.log("[PCMAudioPlayer] AudioContext已恢复运行")),this.audioWorkletNode.port.postMessage({type:"start"}),this.isPlaying=!0,t.log("[PCMAudioPlayer] 已启动播放(Worklet激活)")}pause(){if(!this.isInitialized||!this.audioWorkletNode)return;const t=window.avatarSDKLogger||console;this.audioWorkletNode.port.postMessage({type:"pause"}),this.isPlaying=!1,t.log("[PCMAudioPlayer] 已暂停播放(Worklet暂停)")}stop(){if(!this.isInitialized||!this.audioWorkletNode)return;const t=window.avatarSDKLogger||console;this.audioWorkletNode.port.postMessage({type:"stop"}),this.isPlaying=!1,t.log("[PCMAudioPlayer] 已停止播放(Worklet缓存清空)")}async destroy(){var t;const e=window.avatarSDKLogger||console;null==(t=this.unsubscribePlaybackSessionRestored)||t.call(this),this.unsubscribePlaybackSessionRestored=null,this.detachCapture(),this.isInitialized&&this.audioCtx&&this.audioWorkletNode?(await new Promise(t=>{var n;this.destroyResolve=t,null==(n=this.audioWorkletNode)||n.port.postMessage({type:"destroy"});const r=setTimeout(()=>{var t;e.warn("[PCMAudioPlayer] Worklet销毁超时,强制释放资源"),null==(t=this.destroyResolve)||t.call(this)},300);this.audioWorkletNode&&(this.audioWorkletNode.port.onmessage=t=>{var e;"destroyConfirmed"===t.data.type&&(clearTimeout(r),null==(e=this.destroyResolve)||e.call(this))})}),this.audioWorkletNode.disconnect(),this.audioWorkletNode.port.close(),this.audioWorkletNode=null,"closed"!==this.audioCtx.state&&await this.audioCtx.close(),this.audioCtx=null,e.log("[PCMAudioPlayer] AudioContext已关闭"),this.isInitialized=!1,this.isPlaying=!1,this.destroyResolve=null,e.log("[PCMAudioPlayer] 播放器已完全销毁,所有资源释放完成")):e.log("[PCMAudioPlayer] 播放器未初始化或已销毁")}async attachCapture(t){if(!this.isInitialized||!this.audioCtx||!this.audioWorkletNode)throw new Error("[PCMAudioPlayer] 播放器未初始化,无法挂载捕获");if(!this.captureWorklet){this.captureCallback=t;try{var e;await this.audioCtx.audioWorklet.addModule(captureWorkletUrl),this.captureWorklet=new AudioWorkletNode(this.audioCtx,"pcm-capture-processor"),this.audioWorkletNode.connect(this.captureWorklet),this.captureWorklet.port.onmessage=t=>{this.captureCallback&&t.data.pcmData&&this.captureCallback({pcmData:t.data.pcmData,hasAudio:t.data.hasAudio})},null==(e=window.avatarSDKLogger)||e.log("[PCMAudioPlayer] 捕获节点已挂载")}catch(t){var n;throw null==(n=window.avatarSDKLogger)||n.error("[PCMAudioPlayer] 挂载捕获节点失败:",t),t}}}detachCapture(){if(this.captureWorklet){try{var t;this.captureWorklet.port.onmessage=null,null==(t=this.audioWorkletNode)||t.disconnect(this.captureWorklet),this.captureWorklet.disconnect()}catch(t){}this.captureWorklet=null}this.captureCallback=null}resetCaptureBuffer(){this.captureWorklet&&this.captureWorklet.port.postMessage({type:"reset"})}getStatus(){return{isInitialized:this.isInitialized,isPlaying:this.isPlaying,isWorkletReady:!!this.audioWorkletNode}}setVolume(t){this.isInitialized&&this.audioWorkletNode&&this.audioWorkletNode.port.postMessage({type:"volume",volume:t})}setSpeed(t){this.isInitialized&&this.audioWorkletNode&&this.audioWorkletNode.port.postMessage({type:"speed",speed:t})}async resume(){const t=window.avatarSDKLogger||console;try{var e;"suspended"===(null==(e=this.audioCtx)?void 0:e.state)&&this.audioCtx.resume().then(()=>{window.avatarSDKLogger.info("worklet音频上下文恢复成功")}).catch(t=>{window.avatarSDKLogger.error("worklet音频上下文恢复失败:",t)})}catch(e){throw t.error("[PCMAudioPlayer] worklet恢复播放失败:",e),e}}}class MediaSourceAudioPlayer{static getInstance(t){return MediaSourceAudioPlayer.instance||(MediaSourceAudioPlayer.instance=new MediaSourceAudioPlayer(t)),MediaSourceAudioPlayer.instance}constructor(t){this.mediaSource=null,this.audioElement=null,this.sourceBuffer=null,this.isInitialized=!1,this.isPlaying=!1,this.volume=1,this.MIME_TYPE="audio/webm;codecs=opus",this.queue=[],this.isUpdating=!1,this.currentObjectURL=null,this.isDestroyed=!1,this.playbackRate=1,this.firstFrameIndex=-1,this.createAudioElement(t),this.createNewMediaSource()}createAudioElement(t){if(this.audioElement)return;const e=document.getElementById("xmov-avatar-audio");if(e)return void(this.audioElement=e);const n=document.createElement("audio");n.id="xmov-avatar-audio",n.preload="auto",n.style.position="absolute",n.style.width="1px",n.style.height="1px",n.style.opacity="0",n.style.pointerEvents="none",n.style.zIndex="-9999",t.el.appendChild(n),this.audioElement=n}createNewMediaSource(){return new Promise((t,e)=>{try{if(!this.audioElement)return;this.mediaSource=new MediaSource,this.currentObjectURL=URL.createObjectURL(this.mediaSource),this.audioElement.src=this.currentObjectURL,this.mediaSource.addEventListener("sourceopen",()=>{try{if(!this.mediaSource)return;this.sourceBuffer=this.mediaSource.addSourceBuffer(this.MIME_TYPE),this.sourceBuffer.mode="sequence",this.sourceBuffer.addEventListener("updateend",()=>{this.isUpdating=!1,this.processQueue()}),this.isInitialized=!0,t()}catch(t){e(t)}}),this.mediaSource.addEventListener("sourceclose",()=>{this.isInitialized=!1})}catch(t){e(t)}})}async destroyCurrentMediaSource(t){try{this.audioElement&&(this.audioElement.pause(),this.audioElement.removeAttribute("src"),this.audioElement.load())}catch(t){}try{this.currentObjectURL&&(URL.revokeObjectURL(this.currentObjectURL),this.currentObjectURL=null)}catch(t){}this.mediaSource=null,this.sourceBuffer=null,this.isInitialized=!1,this.isPlaying=!1,this.queue=[],this.isUpdating=!1,await this.createNewMediaSource(),t()}stop(t){this.destroyCurrentMediaSource(t)}async addAudioSegment(t){this.isDestroyed||(this.queue.push({data:t}),this.processQueue())}processQueue(){if(this.isDestroyed)return;if(!this.sourceBuffer||!this.mediaSource)return;if(this.isUpdating||0===this.queue.length)return;if(this.sourceBuffer.updating||"open"!==this.mediaSource.readyState)return;this.isUpdating=!0;const t=this.queue.shift();try{this.sourceBuffer.appendBuffer(t.data)}catch(t){this.isUpdating=!1}}async start(){if(!this.isDestroyed&&this.audioElement&&!this.isPlaying)try{this.audioElement.currentTime=0,this.isPlaying=!0,await this.audioElement.play(),window.avatarSDKLogger.log("mseAudioPlayer开始播放",this.getStats(),Date.now())}catch(t){}}getStats(){var t;return{isPlaying:this.isPlaying,isInitialized:this.isInitialized,queueLength:this.queue.length,bufferedRanges:this.getBufferedRanges(),mediaSourceReadyState:(null==(t=this.mediaSource)?void 0:t.readyState)||"null"}}setSpeed(t){this.setPlaybackRate(t)}getBufferedRanges(){try{var t;if(this.sourceBuffer&&"open"===(null==(t=this.mediaSource)?void 0:t.readyState)&&this.sourceBuffer.buffered.length>0){const t=[];for(let e=0;e<this.sourceBuffer.buffered.length;e++){const n=this.sourceBuffer.buffered.start(e).toFixed(2),r=this.sourceBuffer.buffered.end(e).toFixed(2);t.push(`[${n}-${r}]`)}return t.join(", ")}}catch(t){return"-"}return"-"}setVolume(t){this.volume=Math.max(0,Math.min(1,t)),this.audioElement&&(this.audioElement.volume=this.volume)}setPlaybackRate(t){this.playbackRate=Math.max(.5,Math.min(4,t)),this.audioElement&&(this.audioElement.playbackRate=this.playbackRate)}destroy(){if(this.isDestroyed=!0,this.audioElement&&(this.audioElement.pause(),this.audioElement.removeAttribute("src"),this.audioElement.load()),this.currentObjectURL){try{URL.revokeObjectURL(this.currentObjectURL)}catch(t){}this.currentObjectURL=null}this.audioElement&&(this.audioElement.remove(),this.audioElement=null),this.mediaSource=null,this.sourceBuffer=null,this.isInitialized=!1,this.isPlaying=!1,this.queue=[],this.isUpdating=!1,MediaSourceAudioPlayer.instance=null}}class AudioRender{constructor(t){this.TAG="[AudioRenderer]",this.isPlaying=!1,this.lastFrameIndex=-1,this.audio=null,this.firstFrameIndex=-1,this.valume=1,this.speech_id=-1,this.cacheFirstFrameIndex=-1,this.cacheAudioData=[],this.oldSpeechId=-1,this.mseCacheAudioData=[],this.mseAudioPlayer=null,this.options=t,this.resourceManager=t.resourceManager,this.resourceManager.config.raw_audio?(this.audio=new PCMAudioPlayer,this.audio.init()):this.mseAudioPlayer=MediaSourceAudioPlayer.getInstance(t.sdk)}updateAudioData(t){if(!this.resourceManager.config.raw_audio||t[0].sid===this.oldSpeechId)return;-1===this.firstFrameIndex&&(this.firstFrameIndex=t[0].sf);let e=0;for(const r of t){var n;e+=(null==(n=r.ad)?void 0:n.length)||0}const r=new Uint8Array(e);let i=0;for(const e of t)e.ad&&(r.set(new Uint8Array(e.ad),i),i+=e.ad.length);var s,a;-1===this.speech_id?(this.speech_id=t[0].sid,null==(s=this.audio)||s.receivePCMStream(r)):this.speech_id!==t[0].sid?(-1===this.cacheFirstFrameIndex&&(this.cacheFirstFrameIndex=t[0].sf),this.cacheAudioData.push(r)):null==(a=this.audio)||a.receivePCMStream(r)}_updateAudio(t){if(!this.mseAudioPlayer||0===t.length)return;const e=t[0];if(e.sid!==this.oldSpeechId)if(-1!==this.speech_id&&e.sid!==this.speech_id){var n;null==(n=window.avatarSDKLogger)||n.log(this.TAG,`检测到新的 speech_id: ${e.sid}, 当前 WebM 播放 (旧: ${this.speech_id}), 新: ${e.sid}, 缓存数据长度: ${this.mseCacheAudioData.length}`),-1===this.cacheFirstFrameIndex&&(this.cacheFirstFrameIndex=e.sf);for(const e of t)this.mseCacheAudioData.push({data:e.ad,frameIndex:e.sf,speechId:e.sid})}else{-1===this.firstFrameIndex&&(this.firstFrameIndex=e.sf),(-1===this.speech_id||this.speech_id!==e.sid)&&(this.speech_id=e.sid);for(const e of t)if(e.ad){const t=e.ad instanceof ArrayBuffer?e.ad:e.ad.buffer.slice(e.ad.byteOffset,e.ad.byteOffset+e.ad.byteLength);this.mseAudioPlayer.addAudioSegment(t)}}}async render(t){if(window.avatarSDKLogger.log("当前帧索引:",t,"音频开始播放帧:",this.firstFrameIndex),-1===this.lastFrameIndex&&(this.lastFrameIndex=t),this.options.sdk.getStatus()!==AvatarStatus.offline){var e;if(t>=this.firstFrameIndex&&-1!=this.firstFrameIndex&&!this.isPlaying&&this.resourceManager.config.raw_audio)return window.performanceTracker.markEnd(performanceConstant.start_action_render,"speak"),this.isPlaying=!0,void(null==(e=this.audio)||e.start());if(this.resourceManager.config.raw_audio||!this.mseAudioPlayer);else if(-1!==this.firstFrameIndex&&t>=this.firstFrameIndex&&!this.mseAudioPlayer.isPlaying&&!this.isPlaying){const e=this.mseAudioPlayer.getStats();if(e.queueLength>0||"-"!==e.bufferedRanges)try{window.avatarSDKLogger.log("开始播放",t),this.isPlaying=!0,await this.mseAudioPlayer.start(),window.performanceTracker.markEnd(performanceConstant.start_action_render,"speak")}catch(n){window.avatarSDKLogger.error("[AudioRenderer] WebM 音频播放失败:",{error:n,frameIndex:t,firstFrameIndex:this.firstFrameIndex,queueLength:e.queueLength})}else null==window.avatarSDKLogger.debug||window.avatarSDKLogger.debug("[AudioRenderer]",`等待更多 WebM 音频数据 (frameIndex: ${t}, queueLength: ${e.queueLength})`)}}}resume(){var t;this.audio&&this.resourceManager.config.raw_audio&&(null==(t=this.audio)||t.resume())}pause(){var t,e;this.isPlaying=!1,this.options.dataCacheQueue._clearAudio(this.speech_id),this.lastFrameIndex=-1,this.firstFrameIndex=-1,this.cacheFirstFrameIndex=-1,this.cacheAudioData=[],this.mseCacheAudioData=[],this.oldSpeechId=-1,null==(t=this.audio)||t.stop(),null==(e=this.mseAudioPlayer)||e.stop(this.addNewAudioSegment.bind(this)),this.speech_id=-1}stop(t){var e,n,r;if(!(-1!==t&&this.oldSpeechId>=t))if(this.isPlaying=!1,this.options.dataCacheQueue._clearAudio(t),this.firstFrameIndex=-1,null==(e=window.avatarSDKLogger)||e.log(this.TAG,`清除缓存数据 (speech_id: ${this.speech_id}, PCM缓存数据长度: ${this.cacheAudioData.length}, WebM缓存数据长度: ${this.mseCacheAudioData.length})`),this.resourceManager.config.raw_audio?null==(n=this.audio)||n.stop():null==(r=this.mseAudioPlayer)||r.stop(this.addNewAudioSegment.bind(this)),this.oldSpeechId=t,this.speech_id=-1,-1===t)this.cacheFirstFrameIndex=-1,this.cacheAudioData=[],this.mseCacheAudioData=[];else if(this.cacheAudioData.length>0){this.firstFrameIndex=this.cacheFirstFrameIndex,this.cacheFirstFrameIndex=-1;for(const t of this.cacheAudioData){var i;null==(i=this.audio)||i.receivePCMStream(t)}this.cacheAudioData=[]}}addNewAudioSegment(){if(this.mseCacheAudioData.length>0){this.firstFrameIndex=this.cacheFirstFrameIndex,this.cacheFirstFrameIndex=-1;for(const e of this.mseCacheAudioData){var t;e.data&&(null==(t=this.mseAudioPlayer)||t.addAudioSegment(e.data))}this.mseCacheAudioData=[]}}setVolume(t){var e,n;this.valume=t,this.resourceManager.config.raw_audio?null==(e=this.audio)||e.setVolume(t):null==(n=this.mseAudioPlayer)||n.setVolume(t)}setSpeed(t){var e,n;this.resourceManager.config.raw_audio?null==(e=this.audio)||e.setSpeed(t):null==(n=this.mseAudioPlayer)||n.setSpeed(t)}getAudioPlayer(){return this.audio}destroy(){var t,e;this.stop(-1),this.cacheAudioData=[],this.mseCacheAudioData=[],null==(t=this.audio)||t.destroy(),null==(e=this.mseAudioPlayer)||e.destroy(),this.mseAudioPlayer=null}}class SaveAndDownload{constructor(t="avatarData.json",e=!1){this.fileName=t,this.enabled=e,this.data={},this.downloadButton=null,e&&this.initDownloadButton()}initDownloadButton(){this.enabled&&(this.downloadButton=document.createElement("a"),this.downloadButton.style.position="absolute",this.downloadButton.style.left="0",this.downloadButton.style.bottom="30px",this.downloadButton.style.background="#4CAF50",this.downloadButton.style.color="white",this.downloadButton.style.fontSize="12px",this.downloadButton.style.padding="10px",this.downloadButton.style.borderRadius="4px",this.downloadButton.style.textDecoration="none",this.downloadButton.style.zIndex="1000",this.downloadButton.style.cursor="pointer",this.downloadButton.innerHTML="下载数据提交开发回放",this.downloadButton.addEventListener("click",()=>{this.download()}),document.body.appendChild(this.downloadButton))}writeFields(t){this.enabled&&Object.assign(this.data,t)}appendMultipleToArray(t,e){this.enabled&&(this.data[t]||(this.data[t]=[]),this.data[t].push(...e))}download(){if(!this.enabled)return;const t=this.generateJSONContent();this.downloadFile(t,this.fileName,"application/json")}generateJSONContent(){return JSON.stringify(this.data,null,2)}downloadFile(t,e,n){if(!this.enabled)return;const r=new Blob([t],{type:n}),i=URL.createObjectURL(r);this.downloadButton.href=i,this.downloadButton.download=e,this.downloadButton.scrollIntoView({behavior:"smooth",block:"center"}),this.downloadButton.dataset.objectUrl=i}}class RenderScheduler{constructor(t){this.TAG="[RenderScheduler]",this.currentSpeechId=-1,this.isStartPlay=!1,this.renderState=RenderState.init,this.lastSpeechId=-1,this.enableClientInterrupt=!1,this.audioOnlyMode=!1,this._speedResetTimer=null,this.offsetFrame=0,this.hasSendTimeJson=!1,this.config=t,this.setAudioInfo=t.setAudioInfo,this.setEventData=t.setEventData,this.reportMessage=t.reportMessage,this.sendSdkPoint=t.sendSdkPoint,this.onRenderChange=t.onRenderChange,this.sendMessage=t.sendMessage,this.enableClientInterrupt=t.enableClientInterrupt||!1,this.audioOnlyMode=t.audioOnlyMode||!1,this.saveAndDownload=new SaveAndDownload("avatarData.js",t.enableDebugger),this.resourceManager=t.resourceManager,this.sdk=t.sdkInstance,this.onDownloadProgress=t.onDownloadProgress,this.onFPSUpdate=t.onFPSUpdate,this.dataCacheQueue=new DataCacheQueue,this.decoder=new ParallelDecoder({hardwareAcceleration:t.hardwareAcceleration,resourceManager:this.resourceManager,saveAndDownload:this.saveAndDownload,dataCacheQueue:this.dataCacheQueue,reportMessage:this.reportMessage}),this.avatarRenderer=new AvatarRender({dataCacheQueue:this.dataCacheQueue,resourceManager:this.resourceManager,saveAndDownload:this.saveAndDownload,forceSyncDecoder:this.forceSyncDecoder.bind(this),reportMessage:this.reportMessage,sendSdkPoint:this.sendSdkPoint,onDownloadProgress:t=>{this.onDownloadProgress(t)},onStateChange:e=>{t.onStateChange(e)},onRenderChange:e=>{t.onRenderChange(e,this.renderState),this.renderState=e},sendVideoInfo:t.sendVideoInfo}),this.uiRenderer=new UIRenderer({sdk:this.sdk,dataCacheQueue:this.dataCacheQueue,resourceManager:this.resourceManager,enableClientInterrupt:this.enableClientInterrupt,onWalkStateChange:e=>{t.onWalkStateChange(e)},onVoiceStart:(e,n)=>{t.onVoiceStateChange("start",e,n)},onVoiceEnd:(e,n)=>{this.stopAudio(n),t.onVoiceStateChange("end",void 0,e)},onSpeakStateChange:(e,n,r)=>{"speak_start"===e?(this.currentSpeechId=r,this.avatarRenderer.setInterrupt(!1)):"speak_end"===e&&(this.dataCacheQueue.clearSubtitleOn(r),r>=this.currentSpeechId&&this.avatarRenderer.setInterrupt(!0)),t.onSpeakStateChange(e,n)},sendSdkPoint:(e,n,r)=>{t.sendSdkPoint(e,n,r)}}),this.audioRenderer=new AudioRender({sdk:this.sdk,dataCacheQueue:this.dataCacheQueue,resourceManager:this.resourceManager}),this.composition=new Composition({container:t.container,avatarRenderer:this.avatarRenderer,restRenderers:[this.uiRenderer],audioRenderer:this.audioRenderer,audioOnlyMode:this.audioOnlyMode,onFPSUpdate:t=>{this.onFPSUpdate(t)}}),this.frameAnimationController=new FrameAnimationController({defaultSpeed:1,frameRate:24,frameCallback:(e,n)=>{if(!this.hasSendTimeJson&&n&&(window.avatarSDKLogger.error("当前帧日期与当前帧不一致:",n),this.sendMessage("client_error",n),this.hasSendTimeJson=!0),t.renderFrameCallback(e+=this.offsetFrame),this.isStartPlay&&(this.composition.compose(e),this.decoder._tryStartNext(),t.onFrameDataUpdate)){const n=this.avatarRenderer._getCurrentFrameData(e);t.onFrameDataUpdate({frameIndex:e,body:n.body,face:n.face})}}})}init(){if(this.audioOnlyMode)return;const t=this.resourceManager.getMouthShapeLib();this.saveAndDownload.writeFields({resource_pack:this.resourceManager.resource_pack}),this.avatarRenderer.init({char:t.char_info,LUT:null,transform:{offsetX:0,offsetY:0,scaleX:1,scaleY:1},multisample:4})}async handleData(t,e){var n,r,i;if(this.audioOnlyMode&&(t===EFrameDataType.BODY||t===EFrameDataType.FACE||t===EFrameDataType.AA_FRAME))return;const s=this.getCurrentFrameIndex();switch(t){case EFrameDataType.BODY:{this.decoder.clearOldQueue(s);const t=s;let n=[...e].filter(e=>e.ef>t);window.avatarSDKLogger.log(n,"mp4List"),n.length>0&&(this.renderState!==RenderState.paused&&s&&s>e[0].sf&&s>10&&this.sdk.onMessage({code:EErrorCode.BODY_DATA_EXPIRED,message:`Error: 身体数据过期 cur:${s}-sf:${e[0].sf}`,e}),this.decoder.decode(n,(t,e,n)=>{var r,i;t.start<=n&&t.end>=n&&(this.dataCacheQueue._updateBodyImageBitmap({frame:e,frameIndex:t.startFrameIndex+n,frameState:t.frameState,id:t.id,body_id:t.body_id,name:t.name,hfd:t.hfd,sf:t.startFrameIndex,offset:(null==t?void 0:t.x_offset[n])||0}),t.endFrameIndex<=t.startFrameIndex+n&&this.decoder.abortOne(`${null!=(r=null!=(i=t.body_id)?i:t.id)?r:0}_${t.name}`))}));break}case EFrameDataType.FACE:this.dataCacheQueue.clearOldFaceData(s);const _=this.handleFaceData(e);_.length>0&&this.saveAndDownload.appendMultipleToArray("faceData",_),this.dataCacheQueue.checkValidData(_,t);let g=[],y=[];for(let t=0;t<_.length;t++){var a;null!=(a=_[t])&&a.face_frame_type?y.push(_[t]):g.push(_[t])}y.length&&this.dataCacheQueue._updateFacial(y),g.length&&this.dataCacheQueue._updateRealFacial(g);break;case EFrameDataType.AUDIO:if(this.setAudioInfo({sf:e[0].sf,ef:e[0].ef,ad:e[0].ad}),this.renderState!==RenderState.paused&&s>e[0].sf){const t=s?s-e[0].sf:0;this.reportMessage({code:EErrorCode.AUDIO_DATA_EXPIRED,message:`Error: 音频数据过期 cur:${s}-sf:${e[0].sf}`,e:{currentFrame:s,sf:e[0].sf,ef:t,timestamp:Date.now()}}),this.sendSdkPoint("audio_data_expired",{currentFrame:s,sf:e[0].sf,ef:t,timestamp:Date.now()})}const S=1e3/24,{sf:A,ef:v}=e[0],E=v-A;if(E<=0)return;const b=(s||0)-A;if(b>E)return;let T=1;if(b>0&&(T=E/Math.max(E-b,.1)),this._speedResetTimer&&clearTimeout(this._speedResetTimer),T>4)return;this.audioRenderer.setSpeed(T),this._speedResetTimer=setTimeout(()=>{this.audioRenderer.setSpeed(1),this._speedResetTimer=null},E*S/T),this.dataCacheQueue.checkValidData(e,t);const w=e.map(t=>this.resourceManager.config.raw_audio?t:_extends({},t,{ad:t.ad.buffer.slice(t.ad.byteOffset,t.ad.byteOffset+t.ad.byteLength)}));if(w[0].sid<=this.lastSpeechId)return;var o;this.resourceManager.config.raw_audio?(null==(o=window.avatarSDKLogger)||o.log(this.TAG,"processedAudioData[0].sid",w[0].sid,this.currentSpeechId,this.renderState),this.audioRenderer.updateAudioData(w)):this.audioRenderer._updateAudio(w);break;case EFrameDataType.EVENT:this.dataCacheQueue.clearOldEvent(s);const x=e;this.setEventData({sf:x[0].sf,ef:x[0].ef,event:x[0].e});let I=!1,R=null,C=null;for(const t of x){var l;const e=null!=(l=t.e)?l:[];if(e.some(t=>"speak_start"===t.type)&&(I=!0),t.sf<s&&(R||(R=e.find(t=>"speak_start"===t.type)||null),C||(C=e.find(t=>"voice_start"===t.type)||null),R&&C))break}if(I&&this.audioRenderer.isPlaying){var c;this.reportMessage({code:EErrorCode.EVENT_TRIGGERED,message:"WARNING: 有新的speak_start事件,但是上一轮仍未结束,触发兜底结束"});const t=x.flatMap(t=>{var e;return null!=(e=t.e)?e:[]}).find(t=>"speak_start"===t.type),e=null!=(c=null==t?void 0:t.speech_id)?c:0,n=this.audioRenderer.speech_id;var d,h;-1!==n&&n<e&&(this.interrupt("new_speak_start",n),-1!==this.audioRenderer.speech_id&&this.audioRenderer.pause()),t&&(this.currentSpeechId=null!=(d=t.speech_id)?d:0,this.avatarRenderer.setInterrupt(!1),this.uiRenderer.lastSpeechId=null!=(h=t.speech_id)?h:0)}if(R){const{speech_id:t,client_speak_id:e}=R;this.reportMessage({code:EErrorCode.EVENT_SPEAK_START_EXPIRED,message:"WARNING: 收到speak_start过期,主动重置avatarRender,调用onSpeakStateChange"}),this.currentSpeechId=null!=t?t:0,this.avatarRenderer.setInterrupt(!1),this.uiRenderer.lastSpeechId=null!=t?t:0,this.config.onSpeakStateChange("speak_start",null!=e?e:0)}if(C){var u,p;this.reportMessage({code:EErrorCode.EVENT_VOICE_START_EXPIRED,message:"WARNING: 收到voice_start过期,主动调用onVoiceStateChange"});const t=window.performanceTracker.markEnd(performanceConstant.voice_response_play,"speak");this.config.onVoiceStateChange("start",t,null!=(u=null==(p=C)?void 0:p.client_speak_id)?u:"")}const B=x.filter(t=>-1===t.sf&&-1===t.ef);for(const t of B)for(let e=0;e<t.e.length;e++){const n=t.e[e];if(WidgetDefaultRenderer.CUSTOM_WIDGET)WidgetDefaultRenderer.CUSTOM_WIDGET(n);else if(WidgetDefaultRenderer.PROXY_WIDGET){var f,m;null==(f=WidgetDefaultRenderer.PROXY_WIDGET)||null==(m=f[n.type])||m.call(f,n)}}const D=x.filter(t=>-1!==t.sf);this.dataCacheQueue._updateUiEvent(D);break;case EFrameDataType.SYNC_FRAME:const P=e;if(null!=(n=this.sdk.getOptions().config)&&n.replay||(null==P?void 0:P.source)!==FRAME_SOURCE_SOURCE)return;const k=Date.now()/1e3,O=null!=(r=P.client_time)?r:0,U=((null!=(i=P.server_client_frame)?i:0)+(k-O)/2*24).toFixed(0);this.offsetFrame+=Number(U)-Number(null!=s?s:0);break;default:this.sdk.onMessage({code:EErrorCode.INVALID_DATA_STRUCTURE,message:"Error: 数据类型错误",e:_extends({},e,{type:t})})}}setOffsetFrame(t){this.offsetFrame+=t}setVolume(t){this.audioRenderer.setVolume(t)}runStartFrameIndex(){var t;null==(t=this.frameAnimationController)||t.play()}stateChangeHandle(t){this.dataCacheQueue.currentPlayState=t}stopAudio(t){this.audioRenderer.stop(t)}render(){if(this.audioOnlyMode)return this.isStartPlay=!0,this.renderState=RenderState.rendering,this.onRenderChange(this.renderState),void this.onDownloadProgress(100);this.avatarRenderer.createPipeline(),this.isStartPlay=!0,this.renderState=RenderState.rendering,this.onRenderChange(this.renderState)}stop(){this.isStartPlay=!1,this.renderState=RenderState.stopped,this.onRenderChange(this.renderState),this.composition.stop()}pauseRender(){var t,e;this.renderState!==RenderState.paused&&(null==(t=this.frameAnimationController)||t.pause(),this.audioRenderer.stop(-1),this.dataCacheQueue.clearAllFaceData(),this.renderState=RenderState.paused,this.onRenderChange(this.renderState),null==(e=window.avatarSDKLogger)||e.log(this.TAG,`渲染已暂停(已清空表情数据,等待恢复): ${this.renderState}`))}resumeRender(){var t,e;this.renderState===RenderState.paused&&(this.avatarRenderer.createPipeline(),this.avatarRenderer.resetFaceFrameState(),null==(t=this.frameAnimationController)||t.play(),this.isStartPlay=!0,this.forceSyncDecoder(),this.renderState=RenderState.resumed,this.onRenderChange(this.renderState),null==(e=window.avatarSDKLogger)||e.log(this.TAG," 渲染已恢复,状态: this.currentSpeechId==="+this.currentSpeechId))}switchInvisibleMode(){var t;if(this.renderState===RenderState.rendering||this.renderState===RenderState.resumed)null==(t=window.avatarSDKLogger)||t.log(this.TAG,"switchInvisibleMode: rendering to paused"),this.pauseRender();else if(this.renderState===RenderState.paused){var e;null==(e=window.avatarSDKLogger)||e.log(this.TAG,"switchInvisibleMode: paused to rendering"),this.resumeRender()}else{var n;null==(n=window.avatarSDKLogger)||n.warn(this.TAG,`渲染状态为 ${this.renderState},无法切换隐身模式`)}}getRenderState(){var t;return null==(t=window.avatarSDKLogger)||t.log(this.TAG,`getRenderState: ${this.renderState}`),this.renderState}destroy(){var t;this.isStartPlay=!1,this.hasSendTimeJson=!1,this.offsetFrame=0,this._speedResetTimer=null,null==(t=this.frameAnimationController)||t.destroy(),this.frameAnimationController=void 0,this.dataCacheQueue.destroy(),this.composition.destroy(),this.decoder.destroy()}handleFaceData(t){try{var e;const n=this.resourceManager.resource_pack,r=this.resourceManager.getConfig().framedata_proto_version,i=[...null!=(e=n.blendshape_map)?e:[]];return t.map(t=>{let e=[];const{body_id:n,sf:s,ef:a,s:o,id:l,js:c,bsw:d,ms:h,face_frame_type:u,asf:p,aef:f,n:m,cs:_}=t;let g=[];if((null==i?void 0:i.length)>0){for(let t=0;t<i.length;t++){const n=i[t];if((null==n?void 0:n.length)>0)for(let r=0;r<n.length;r++)e[t]||(e[t]=[]),e[t][r]=d[n[r]]}g=Array.from({length:h.length},r?(t,n)=>{var r,i,s,a;return{blendshapeWeights:e[n],textureModelIndex:null!=(r=null==(i=h[n])?void 0:i.index)?r:0,texturePCAWeights:null!=(s=null==(a=h[n])?void 0:a.weights)?s:[]}}:(t,n)=>{var r,i,s,a;return{blendshapeWeights:e[n],textureModelIndex:null!=(r=null==(i=h[n])?void 0:i[0])?r:0,texturePCAWeights:null!=(s=null==(a=h[n])?void 0:a[1])?s:[]}})}else g=Array.from({length:h.length},r?(t,e)=>{var n,r,i,s;return{blendshapeWeights:0===e?d:[],textureModelIndex:null!=(n=null==(r=h[e])?void 0:r.index)?n:0,texturePCAWeights:null!=(i=null==(s=h[e])?void 0:s.weights)?i:[]}}:(t,e)=>{var n,r,i,s;return{blendshapeWeights:0===e?d:[],textureModelIndex:null!=(n=null==(r=h[e])?void 0:r[0])?n:0,texturePCAWeights:null!=(i=null==(s=h[e])?void 0:s[1])?i:[]}});let y=[];return y=c.map(r?t=>formatMJT(t.translate,t.rotate):t=>formatMJT(t[0],t[1])),{body_id:n,frameIndex:s,sf:s,ef:a,asf:p,aef:f,n:m,cs:_,state:o,id:l,face_frame_type:u,FaceFrameData:{mesh:g,movableJointTransforms:y,blendshapeWeights:d}}})}catch(t){return this.sdk.onMessage({code:EErrorCode.FACE_PROCESSING_ERROR,message:"Error: 表情数据处理失败",e:t}),[]}}forceSyncDecoder(){const t=this.getCurrentFrameIndex();t&&this.decoder.syncDecode(t)}_reload(){this.decoder._reload()}_getResumeInfo(){const t=this.getCurrentFrameIndex();return this.avatarRenderer._getCurrentBodyFrameInfo(t||0)}sendVoiceEnd(){var t,e,n;const r=(null!=(t=this.getCurrentFrameIndex())?t:0)+1;this.dataCacheQueue._updateUiEvent([{id:0,s:"",sf:r,ef:r+1,e:[{type:"speak_end",speech_id:null!=(e=this.uiRenderer.lastSpeechId)?e:-1},{type:"voice_end",speech_id:null!=(n=this.uiRenderer.lastSpeechId)?n:-1}]}])}markReconnectRecover(){this.audioRenderer.resume(),this.decoder._reload()}_offlineMode(){var t,e;this.dataCacheQueue._clearEvent();const n=null!=(t=this.getCurrentFrameIndex())?t:0;this.dataCacheQueue._updateUiEvent([{id:0,s:"",sf:n+1,ef:n+2,e:[{type:"subtitle_off",speech_id:null!=(e=this.uiRenderer.lastSpeechId)?e:-1}]}]),this.audioRenderer.pause();const r=this.getCurrentFrameIndex();r&&this.decoder._offLineMode(this.resourceManager._getOfflineIdle(),r),this.lastSpeechId=-1,this.currentSpeechId=-1,this.uiRenderer.lastSpeechId=-1}_offlineRun(){this.decoder._offlineRun(),this.dataCacheQueue.clearAllFaceData()}ttsaStateChangeHandle(t){this.dataCacheQueue.currentTtsaState=t}resume(){this.audioRenderer.resume()}setAvatarCanvasVisible(t){this.avatarRenderer.setCanvasVisibility(t)}setCharacterCanvasLayout(t){this.avatarRenderer.setCharacterCanvasAnchor(t)}setWalkConfig(t){this.avatarRenderer.setWalkConfig(t)}interrupt(t,e){var n;const r=Date.now(),i=null!=e?e:this.audioRenderer.speech_id;this.lastSpeechId="in_offline_mode"===t?-1:i,"in_offline_mode"!==t&&this.avatarRenderer.setInterrupt(!0),this.dataCacheQueue._clearAudio(i),this.dataCacheQueue.clearSubtitleOn(i);const s=null!=(n=this.getCurrentFrameIndex())?n:0;return this.dataCacheQueue._updateUiEvent([{id:0,s:"",sf:s+1,ef:s+2,e:[{type:"subtitle_off",speech_id:null!=i?i:-1}]}]),"in_offline_mode"!==t&&this.audioRenderer.stop(i),this.uiRenderer.setInterrupt(i),Date.now()-r}seekToFrame(t){var e;null==(e=this.frameAnimationController)||e.updateStartTime(t)}getCurrentFrameIndex(){var t,e;return(null!=(t=null==(e=this.frameAnimationController)?void 0:e.getCurrentFrame())?t:0)+this.offsetFrame}getSpeechId(){return this.audioRenderer.speech_id}getAudioRenderer(){return this.audioRenderer}simulateContextLoss(t=5e3,e=!1){this.avatarRenderer.simulateContextLoss(t,e)}getRecoveryStatus(){return this.avatarRenderer.getRecoveryStatus()}async testStagedRecovery(){return this.avatarRenderer.testStagedRecovery()}restartWebGL(){return this.avatarRenderer.restartWebGL()}}const Z_FIXED$1=4,Z_BINARY=0,Z_TEXT=1,Z_UNKNOWN$1=2;function zero$1(t){let e=t.length;for(;--e>=0;)t[e]=0}const STORED_BLOCK=0,STATIC_TREES=1,DYN_TREES=2,MIN_MATCH$1=3,MAX_MATCH$1=258,LENGTH_CODES$1=29,LITERALS$1=256,L_CODES$1=LITERALS$1+1+LENGTH_CODES$1,D_CODES$1=30,BL_CODES$1=19,HEAP_SIZE$1=2*L_CODES$1+1,MAX_BITS$1=15,Buf_size=16,MAX_BL_BITS=7,END_BLOCK=256,REP_3_6=16,REPZ_3_10=17,REPZ_11_138=18,extra_lbits=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]),extra_dbits=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]),extra_blbits=new Uint8Array([0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,2,3,7]),bl_order=new Uint8Array([16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15]),DIST_CODE_LEN=512,static_ltree=new Array(2*(L_CODES$1+2));zero$1(static_ltree);const static_dtree=new Array(2*D_CODES$1);zero$1(static_dtree);const _dist_code=new Array(DIST_CODE_LEN);zero$1(_dist_code);const _length_code=new Array(MAX_MATCH$1-MIN_MATCH$1+1);zero$1(_length_code);const base_length=new Array(LENGTH_CODES$1);zero$1(base_length);const base_dist=new Array(D_CODES$1);function StaticTreeDesc(t,e,n,r,i){this.static_tree=t,this.extra_bits=e,this.extra_base=n,this.elems=r,this.max_length=i,this.has_stree=t&&t.length}let static_l_desc,static_d_desc,static_bl_desc;function TreeDesc(t,e){this.dyn_tree=t,this.max_code=0,this.stat_desc=e}zero$1(base_dist);const d_code=t=>t<256?_dist_code[t]:_dist_code[256+(t>>>7)],put_short=(t,e)=>{t.pending_buf[t.pending++]=255&e,t.pending_buf[t.pending++]=e>>>8&255},send_bits=(t,e,n)=>{t.bi_valid>Buf_size-n?(t.bi_buf|=e<<t.bi_valid&65535,put_short(t,t.bi_buf),t.bi_buf=e>>Buf_size-t.bi_valid,t.bi_valid+=n-Buf_size):(t.bi_buf|=e<<t.bi_valid&65535,t.bi_valid+=n)},send_code=(t,e,n)=>{send_bits(t,n[2*e],n[2*e+1])},bi_reverse=(t,e)=>{let n=0;do{n|=1&t,t>>>=1,n<<=1}while(--e>0);return n>>>1},bi_flush=t=>{16===t.bi_valid?(put_short(t,t.bi_buf),t.bi_buf=0,t.bi_valid=0):t.bi_valid>=8&&(t.pending_buf[t.pending++]=255&t.bi_buf,t.bi_buf>>=8,t.bi_valid-=8)},gen_bitlen=(t,e)=>{const n=e.dyn_tree,r=e.max_code,i=e.stat_desc.static_tree,s=e.stat_desc.has_stree,a=e.stat_desc.extra_bits,o=e.stat_desc.extra_base,l=e.stat_desc.max_length;let c,d,h,u,p,f,m=0;for(u=0;u<=MAX_BITS$1;u++)t.bl_count[u]=0;for(n[2*t.heap[t.heap_max]+1]=0,c=t.heap_max+1;c<HEAP_SIZE$1;c++)d=t.heap[c],u=n[2*n[2*d+1]+1]+1,u>l&&(u=l,m++),n[2*d+1]=u,d>r||(t.bl_count[u]++,p=0,d>=o&&(p=a[d-o]),f=n[2*d],t.opt_len+=f*(u+p),s&&(t.static_len+=f*(i[2*d+1]+p)));if(0!==m){do{for(u=l-1;0===t.bl_count[u];)u--;t.bl_count[u]--,t.bl_count[u+1]+=2,t.bl_count[l]--,m-=2}while(m>0);for(u=l;0!==u;u--)for(d=t.bl_count[u];0!==d;)h=t.heap[--c],h>r||(n[2*h+1]!==u&&(t.opt_len+=(u-n[2*h+1])*n[2*h],n[2*h+1]=u),d--)}},gen_codes=(t,e,n)=>{const r=new Array(MAX_BITS$1+1);let i,s,a=0;for(i=1;i<=MAX_BITS$1;i++)a=a+n[i-1]<<1,r[i]=a;for(s=0;s<=e;s++){let e=t[2*s+1];0!==e&&(t[2*s]=bi_reverse(r[e]++,e))}},tr_static_init=()=>{let t,e,n,r,i;const s=new Array(MAX_BITS$1+1);for(n=0,r=0;r<LENGTH_CODES$1-1;r++)for(base_length[r]=n,t=0;t<1<<extra_lbits[r];t++)_length_code[n++]=r;for(_length_code[n-1]=r,i=0,r=0;r<16;r++)for(base_dist[r]=i,t=0;t<1<<extra_dbits[r];t++)_dist_code[i++]=r;for(i>>=7;r<D_CODES$1;r++)for(base_dist[r]=i<<7,t=0;t<1<<extra_dbits[r]-7;t++)_dist_code[256+i++]=r;for(e=0;e<=MAX_BITS$1;e++)s[e]=0;for(t=0;t<=143;)static_ltree[2*t+1]=8,t++,s[8]++;for(;t<=255;)static_ltree[2*t+1]=9,t++,s[9]++;for(;t<=279;)static_ltree[2*t+1]=7,t++,s[7]++;for(;t<=287;)static_ltree[2*t+1]=8,t++,s[8]++;for(gen_codes(static_ltree,L_CODES$1+1,s),t=0;t<D_CODES$1;t++)static_dtree[2*t+1]=5,static_dtree[2*t]=bi_reverse(t,5);static_l_desc=new StaticTreeDesc(static_ltree,extra_lbits,LITERALS$1+1,L_CODES$1,MAX_BITS$1),static_d_desc=new StaticTreeDesc(static_dtree,extra_dbits,0,D_CODES$1,MAX_BITS$1),static_bl_desc=new StaticTreeDesc(new Array(0),extra_blbits,0,BL_CODES$1,MAX_BL_BITS)},init_block=t=>{let e;for(e=0;e<L_CODES$1;e++)t.dyn_ltree[2*e]=0;for(e=0;e<D_CODES$1;e++)t.dyn_dtree[2*e]=0;for(e=0;e<BL_CODES$1;e++)t.bl_tree[2*e]=0;t.dyn_ltree[2*END_BLOCK]=1,t.opt_len=t.static_len=0,t.sym_next=t.matches=0},bi_windup=t=>{t.bi_valid>8?put_short(t,t.bi_buf):t.bi_valid>0&&(t.pending_buf[t.pending++]=t.bi_buf),t.bi_buf=0,t.bi_valid=0},smaller=(t,e,n,r)=>{const i=2*e,s=2*n;return t[i]<t[s]||t[i]===t[s]&&r[e]<=r[n]},pqdownheap=(t,e,n)=>{const r=t.heap[n];let i=n<<1;for(;i<=t.heap_len&&(i<t.heap_len&&smaller(e,t.heap[i+1],t.heap[i],t.depth)&&i++,!smaller(e,r,t.heap[i],t.depth));)t.heap[n]=t.heap[i],n=i,i<<=1;t.heap[n]=r},compress_block=(t,e,n)=>{let r,i,s,a,o=0;if(0!==t.sym_next)do{r=255&t.pending_buf[t.sym_buf+o++],r+=(255&t.pending_buf[t.sym_buf+o++])<<8,i=t.pending_buf[t.sym_buf+o++],0===r?send_code(t,i,e):(s=_length_code[i],send_code(t,s+LITERALS$1+1,e),a=extra_lbits[s],0!==a&&(i-=base_length[s],send_bits(t,i,a)),r--,s=d_code(r),send_code(t,s,n),a=extra_dbits[s],0!==a&&(r-=base_dist[s],send_bits(t,r,a)))}while(o<t.sym_next);send_code(t,END_BLOCK,e)},build_tree=(t,e)=>{const n=e.dyn_tree,r=e.stat_desc.static_tree,i=e.stat_desc.has_stree,s=e.stat_desc.elems;let a,o,l,c=-1;for(t.heap_len=0,t.heap_max=HEAP_SIZE$1,a=0;a<s;a++)0!==n[2*a]?(t.heap[++t.heap_len]=c=a,t.depth[a]=0):n[2*a+1]=0;for(;t.heap_len<2;)l=t.heap[++t.heap_len]=c<2?++c:0,n[2*l]=1,t.depth[l]=0,t.opt_len--,i&&(t.static_len-=r[2*l+1]);for(e.max_code=c,a=t.heap_len>>1;a>=1;a--)pqdownheap(t,n,a);l=s;do{a=t.heap[1],t.heap[1]=t.heap[t.heap_len--],pqdownheap(t,n,1),o=t.heap[1],t.heap[--t.heap_max]=a,t.heap[--t.heap_max]=o,n[2*l]=n[2*a]+n[2*o],t.depth[l]=(t.depth[a]>=t.depth[o]?t.depth[a]:t.depth[o])+1,n[2*a+1]=n[2*o+1]=l,t.heap[1]=l++,pqdownheap(t,n,1)}while(t.heap_len>=2);t.heap[--t.heap_max]=t.heap[1],gen_bitlen(t,e),gen_codes(n,c,t.bl_count)},scan_tree=(t,e,n)=>{let r,i,s=-1,a=e[1],o=0,l=7,c=4;for(0===a&&(l=138,c=3),e[2*(n+1)+1]=65535,r=0;r<=n;r++)i=a,a=e[2*(r+1)+1],++o<l&&i===a||(o<c?t.bl_tree[2*i]+=o:0!==i?(i!==s&&t.bl_tree[2*i]++,t.bl_tree[2*REP_3_6]++):o<=10?t.bl_tree[2*REPZ_3_10]++:t.bl_tree[2*REPZ_11_138]++,o=0,s=i,0===a?(l=138,c=3):i===a?(l=6,c=3):(l=7,c=4))},send_tree=(t,e,n)=>{let r,i,s=-1,a=e[1],o=0,l=7,c=4;for(0===a&&(l=138,c=3),r=0;r<=n;r++)if(i=a,a=e[2*(r+1)+1],!(++o<l&&i===a)){if(o<c)do{send_code(t,i,t.bl_tree)}while(0!==--o);else 0!==i?(i!==s&&(send_code(t,i,t.bl_tree),o--),send_code(t,REP_3_6,t.bl_tree),send_bits(t,o-3,2)):o<=10?(send_code(t,REPZ_3_10,t.bl_tree),send_bits(t,o-3,3)):(send_code(t,REPZ_11_138,t.bl_tree),send_bits(t,o-11,7));o=0,s=i,0===a?(l=138,c=3):i===a?(l=6,c=3):(l=7,c=4)}},build_bl_tree=t=>{let e;for(scan_tree(t,t.dyn_ltree,t.l_desc.max_code),scan_tree(t,t.dyn_dtree,t.d_desc.max_code),build_tree(t,t.bl_desc),e=BL_CODES$1-1;e>=3&&0===t.bl_tree[2*bl_order[e]+1];e--);return t.opt_len+=3*(e+1)+5+5+4,e},send_all_trees=(t,e,n,r)=>{let i;for(send_bits(t,e-257,5),send_bits(t,n-1,5),send_bits(t,r-4,4),i=0;i<r;i++)send_bits(t,t.bl_tree[2*bl_order[i]+1],3);send_tree(t,t.dyn_ltree,e-1),send_tree(t,t.dyn_dtree,n-1)},detect_data_type=t=>{let e,n=4093624447;for(e=0;e<=31;e++,n>>>=1)if(1&n&&0!==t.dyn_ltree[2*e])return Z_BINARY;if(0!==t.dyn_ltree[18]||0!==t.dyn_ltree[20]||0!==t.dyn_ltree[26])return Z_TEXT;for(e=32;e<LITERALS$1;e++)if(0!==t.dyn_ltree[2*e])return Z_TEXT;return Z_BINARY};let static_init_done=!1;const _tr_init$1=t=>{static_init_done||(tr_static_init(),static_init_done=!0),t.l_desc=new TreeDesc(t.dyn_ltree,static_l_desc),t.d_desc=new TreeDesc(t.dyn_dtree,static_d_desc),t.bl_desc=new TreeDesc(t.bl_tree,static_bl_desc),t.bi_buf=0,t.bi_valid=0,init_block(t)},_tr_stored_block$1=(t,e,n,r)=>{send_bits(t,(STORED_BLOCK<<1)+(r?1:0),3),bi_windup(t),put_short(t,n),put_short(t,~n),n&&t.pending_buf.set(t.window.subarray(e,e+n),t.pending),t.pending+=n},_tr_align$1=t=>{send_bits(t,STATIC_TREES<<1,3),send_code(t,END_BLOCK,static_ltree),bi_flush(t)},_tr_flush_block$1=(t,e,n,r)=>{let i,s,a=0;t.level>0?(t.strm.data_type===Z_UNKNOWN$1&&(t.strm.data_type=detect_data_type(t)),build_tree(t,t.l_desc),build_tree(t,t.d_desc),a=build_bl_tree(t),i=t.opt_len+3+7>>>3,s=t.static_len+3+7>>>3,s<=i&&(i=s)):i=s=n+5,n+4<=i&&-1!==e?_tr_stored_block$1(t,e,n,r):t.strategy===Z_FIXED$1||s===i?(send_bits(t,(STATIC_TREES<<1)+(r?1:0),3),compress_block(t,static_ltree,static_dtree)):(send_bits(t,(DYN_TREES<<1)+(r?1:0),3),send_all_trees(t,t.l_desc.max_code+1,t.d_desc.max_code+1,a+1),compress_block(t,t.dyn_ltree,t.dyn_dtree)),init_block(t),r&&bi_windup(t)},_tr_tally$1=(t,e,n)=>(t.pending_buf[t.sym_buf+t.sym_next++]=e,t.pending_buf[t.sym_buf+t.sym_next++]=e>>8,t.pending_buf[t.sym_buf+t.sym_next++]=n,0===e?t.dyn_ltree[2*n]++:(t.matches++,e--,t.dyn_ltree[2*(_length_code[n]+LITERALS$1+1)]++,t.dyn_dtree[2*d_code(e)]++),t.sym_next===t.sym_end);var _tr_init_1=_tr_init$1,_tr_stored_block_1=_tr_stored_block$1,_tr_flush_block_1=_tr_flush_block$1,_tr_tally_1=_tr_tally$1,_tr_align_1=_tr_align$1,trees={_tr_init:_tr_init_1,_tr_stored_block:_tr_stored_block_1,_tr_flush_block:_tr_flush_block_1,_tr_tally:_tr_tally_1,_tr_align:_tr_align_1};const adler32=(t,e,n,r)=>{let i=65535&t,s=t>>>16&65535,a=0;for(;0!==n;){a=n>2e3?2e3:n,n-=a;do{i=i+e[r++]|0,s=s+i|0}while(--a);i%=65521,s%=65521}return i|s<<16};var adler32_1=adler32;const makeTable=()=>{let t,e=[];for(var n=0;n<256;n++){t=n;for(var r=0;r<8;r++)t=1&t?3988292384^t>>>1:t>>>1;e[n]=t}return e},crcTable=new Uint32Array(makeTable()),crc32=(t,e,n,r)=>{const i=crcTable,s=r+n;t^=-1;for(let n=r;n<s;n++)t=t>>>8^i[255&(t^e[n])];return-1^t};var crc32_1=crc32,messages={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"},constants$2={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,_tr_stored_block,_tr_flush_block,_tr_tally,_tr_align}=trees,{Z_NO_FLUSH:Z_NO_FLUSH$2,Z_PARTIAL_FLUSH,Z_FULL_FLUSH:Z_FULL_FLUSH$1,Z_FINISH:Z_FINISH$3,Z_BLOCK:Z_BLOCK$1,Z_OK:Z_OK$3,Z_STREAM_END:Z_STREAM_END$3,Z_STREAM_ERROR:Z_STREAM_ERROR$2,Z_DATA_ERROR:Z_DATA_ERROR$2,Z_BUF_ERROR:Z_BUF_ERROR$1,Z_DEFAULT_COMPRESSION:Z_DEFAULT_COMPRESSION$1,Z_FILTERED,Z_HUFFMAN_ONLY,Z_RLE,Z_FIXED,Z_DEFAULT_STRATEGY:Z_DEFAULT_STRATEGY$1,Z_UNKNOWN,Z_DEFLATED:Z_DEFLATED$2}=constants$2,MAX_MEM_LEVEL=9,MAX_WBITS$1=15,DEF_MEM_LEVEL=8,LENGTH_CODES=29,LITERALS=256,L_CODES=LITERALS+1+LENGTH_CODES,D_CODES=30,BL_CODES=19,HEAP_SIZE=2*L_CODES+1,MAX_BITS=15,MIN_MATCH=3,MAX_MATCH=258,MIN_LOOKAHEAD=MAX_MATCH+MIN_MATCH+1,PRESET_DICT=32,INIT_STATE=42,GZIP_STATE=57,EXTRA_STATE=69,NAME_STATE=73,COMMENT_STATE=91,HCRC_STATE=103,BUSY_STATE=113,FINISH_STATE=666,BS_NEED_MORE=1,BS_BLOCK_DONE=2,BS_FINISH_STARTED=3,BS_FINISH_DONE=4,OS_CODE=3,err=(t,e)=>(t.msg=messages[e],e),rank=t=>2*t-(t>4?9:0),zero=t=>{let e=t.length;for(;--e>=0;)t[e]=0},slide_hash=t=>{let e,n,r,i=t.w_size;e=t.hash_size,r=e;do{n=t.head[--r],t.head[r]=n>=i?n-i:0}while(--e);e=i,r=e;do{n=t.prev[--r],t.prev[r]=n>=i?n-i:0}while(--e)};let HASH_ZLIB=(t,e,n)=>(e<<t.hash_shift^n)&t.hash_mask,HASH=HASH_ZLIB;const flush_pending=t=>{const e=t.state;let n=e.pending;n>t.avail_out&&(n=t.avail_out),0!==n&&(t.output.set(e.pending_buf.subarray(e.pending_out,e.pending_out+n),t.next_out),t.next_out+=n,e.pending_out+=n,t.total_out+=n,t.avail_out-=n,e.pending-=n,0===e.pending&&(e.pending_out=0))},flush_block_only=(t,e)=>{_tr_flush_block(t,t.block_start>=0?t.block_start:-1,t.strstart-t.block_start,e),t.block_start=t.strstart,flush_pending(t.strm)},put_byte=(t,e)=>{t.pending_buf[t.pending++]=e},putShortMSB=(t,e)=>{t.pending_buf[t.pending++]=e>>>8&255,t.pending_buf[t.pending++]=255&e},read_buf=(t,e,n,r)=>{let i=t.avail_in;return i>r&&(i=r),0===i?0:(t.avail_in-=i,e.set(t.input.subarray(t.next_in,t.next_in+i),n),1===t.state.wrap?t.adler=adler32_1(t.adler,e,i,n):2===t.state.wrap&&(t.adler=crc32_1(t.adler,e,i,n)),t.next_in+=i,t.total_in+=i,i)},longest_match=(t,e)=>{let n,r,i=t.max_chain_length,s=t.strstart,a=t.prev_length,o=t.nice_match;const l=t.strstart>t.w_size-MIN_LOOKAHEAD?t.strstart-(t.w_size-MIN_LOOKAHEAD):0,c=t.window,d=t.w_mask,h=t.prev,u=t.strstart+MAX_MATCH;let p=c[s+a-1],f=c[s+a];t.prev_length>=t.good_match&&(i>>=2),o>t.lookahead&&(o=t.lookahead);do{if(n=e,c[n+a]===f&&c[n+a-1]===p&&c[n]===c[s]&&c[++n]===c[s+1]){s+=2,n++;do{}while(c[++s]===c[++n]&&c[++s]===c[++n]&&c[++s]===c[++n]&&c[++s]===c[++n]&&c[++s]===c[++n]&&c[++s]===c[++n]&&c[++s]===c[++n]&&c[++s]===c[++n]&&s<u);if(r=MAX_MATCH-(u-s),s=u-MAX_MATCH,r>a){if(t.match_start=e,a=r,r>=o)break;p=c[s+a-1],f=c[s+a]}}}while((e=h[e&d])>l&&0!==--i);return a<=t.lookahead?a:t.lookahead},fill_window=t=>{const e=t.w_size;let n,r,i;do{if(r=t.window_size-t.lookahead-t.strstart,t.strstart>=e+(e-MIN_LOOKAHEAD)&&(t.window.set(t.window.subarray(e,e+e-r),0),t.match_start-=e,t.strstart-=e,t.block_start-=e,t.insert>t.strstart&&(t.insert=t.strstart),slide_hash(t),r+=e),0===t.strm.avail_in)break;if(n=read_buf(t.strm,t.window,t.strstart+t.lookahead,r),t.lookahead+=n,t.lookahead+t.insert>=MIN_MATCH)for(i=t.strstart-t.insert,t.ins_h=t.window[i],t.ins_h=HASH(t,t.ins_h,t.window[i+1]);t.insert&&(t.ins_h=HASH(t,t.ins_h,t.window[i+MIN_MATCH-1]),t.prev[i&t.w_mask]=t.head[t.ins_h],t.head[t.ins_h]=i,i++,t.insert--,!(t.lookahead+t.insert<MIN_MATCH)););}while(t.lookahead<MIN_LOOKAHEAD&&0!==t.strm.avail_in)},deflate_stored=(t,e)=>{let n,r,i,s=t.pending_buf_size-5>t.w_size?t.w_size:t.pending_buf_size-5,a=0,o=t.strm.avail_in;do{if(n=65535,i=t.bi_valid+42>>3,t.strm.avail_out<i)break;if(i=t.strm.avail_out-i,r=t.strstart-t.block_start,n>r+t.strm.avail_in&&(n=r+t.strm.avail_in),n>i&&(n=i),n<s&&(0===n&&e!==Z_FINISH$3||e===Z_NO_FLUSH$2||n!==r+t.strm.avail_in))break;a=e===Z_FINISH$3&&n===r+t.strm.avail_in?1:0,_tr_stored_block(t,0,0,a),t.pending_buf[t.pending-4]=n,t.pending_buf[t.pending-3]=n>>8,t.pending_buf[t.pending-2]=~n,t.pending_buf[t.pending-1]=~n>>8,flush_pending(t.strm),r&&(r>n&&(r=n),t.strm.output.set(t.window.subarray(t.block_start,t.block_start+r),t.strm.next_out),t.strm.next_out+=r,t.strm.avail_out-=r,t.strm.total_out+=r,t.block_start+=r,n-=r),n&&(read_buf(t.strm,t.strm.output,t.strm.next_out,n),t.strm.next_out+=n,t.strm.avail_out-=n,t.strm.total_out+=n)}while(0===a);return o-=t.strm.avail_in,o&&(o>=t.w_size?(t.matches=2,t.window.set(t.strm.input.subarray(t.strm.next_in-t.w_size,t.strm.next_in),0),t.strstart=t.w_size,t.insert=t.strstart):(t.window_size-t.strstart<=o&&(t.strstart-=t.w_size,t.window.set(t.window.subarray(t.w_size,t.w_size+t.strstart),0),t.matches<2&&t.matches++,t.insert>t.strstart&&(t.insert=t.strstart)),t.window.set(t.strm.input.subarray(t.strm.next_in-o,t.strm.next_in),t.strstart),t.strstart+=o,t.insert+=o>t.w_size-t.insert?t.w_size-t.insert:o),t.block_start=t.strstart),t.high_water<t.strstart&&(t.high_water=t.strstart),a?BS_FINISH_DONE:e!==Z_NO_FLUSH$2&&e!==Z_FINISH$3&&0===t.strm.avail_in&&t.strstart===t.block_start?BS_BLOCK_DONE:(i=t.window_size-t.strstart,t.strm.avail_in>i&&t.block_start>=t.w_size&&(t.block_start-=t.w_size,t.strstart-=t.w_size,t.window.set(t.window.subarray(t.w_size,t.w_size+t.strstart),0),t.matches<2&&t.matches++,i+=t.w_size,t.insert>t.strstart&&(t.insert=t.strstart)),i>t.strm.avail_in&&(i=t.strm.avail_in),i&&(read_buf(t.strm,t.window,t.strstart,i),t.strstart+=i,t.insert+=i>t.w_size-t.insert?t.w_size-t.insert:i),t.high_water<t.strstart&&(t.high_water=t.strstart),i=t.bi_valid+42>>3,i=t.pending_buf_size-i>65535?65535:t.pending_buf_size-i,s=i>t.w_size?t.w_size:i,r=t.strstart-t.block_start,(r>=s||(r||e===Z_FINISH$3)&&e!==Z_NO_FLUSH$2&&0===t.strm.avail_in&&r<=i)&&(n=r>i?i:r,a=e===Z_FINISH$3&&0===t.strm.avail_in&&n===r?1:0,_tr_stored_block(t,t.block_start,n,a),t.block_start+=n,flush_pending(t.strm)),a?BS_FINISH_STARTED:BS_NEED_MORE)},deflate_fast=(t,e)=>{let n,r;for(;;){if(t.lookahead<MIN_LOOKAHEAD){if(fill_window(t),t.lookahead<MIN_LOOKAHEAD&&e===Z_NO_FLUSH$2)return BS_NEED_MORE;if(0===t.lookahead)break}if(n=0,t.lookahead>=MIN_MATCH&&(t.ins_h=HASH(t,t.ins_h,t.window[t.strstart+MIN_MATCH-1]),n=t.prev[t.strstart&t.w_mask]=t.head[t.ins_h],t.head[t.ins_h]=t.strstart),0!==n&&t.strstart-n<=t.w_size-MIN_LOOKAHEAD&&(t.match_length=longest_match(t,n)),t.match_length>=MIN_MATCH)if(r=_tr_tally(t,t.strstart-t.match_start,t.match_length-MIN_MATCH),t.lookahead-=t.match_length,t.match_length<=t.max_lazy_match&&t.lookahead>=MIN_MATCH){t.match_length--;do{t.strstart++,t.ins_h=HASH(t,t.ins_h,t.window[t.strstart+MIN_MATCH-1]),n=t.prev[t.strstart&t.w_mask]=t.head[t.ins_h],t.head[t.ins_h]=t.strstart}while(0!==--t.match_length);t.strstart++}else t.strstart+=t.match_length,t.match_length=0,t.ins_h=t.window[t.strstart],t.ins_h=HASH(t,t.ins_h,t.window[t.strstart+1]);else r=_tr_tally(t,0,t.window[t.strstart]),t.lookahead--,t.strstart++;if(r&&(flush_block_only(t,!1),0===t.strm.avail_out))return BS_NEED_MORE}return t.insert=t.strstart<MIN_MATCH-1?t.strstart:MIN_MATCH-1,e===Z_FINISH$3?(flush_block_only(t,!0),0===t.strm.avail_out?BS_FINISH_STARTED:BS_FINISH_DONE):t.sym_next&&(flush_block_only(t,!1),0===t.strm.avail_out)?BS_NEED_MORE:BS_BLOCK_DONE},deflate_slow=(t,e)=>{let n,r,i;for(;;){if(t.lookahead<MIN_LOOKAHEAD){if(fill_window(t),t.lookahead<MIN_LOOKAHEAD&&e===Z_NO_FLUSH$2)return BS_NEED_MORE;if(0===t.lookahead)break}if(n=0,t.lookahead>=MIN_MATCH&&(t.ins_h=HASH(t,t.ins_h,t.window[t.strstart+MIN_MATCH-1]),n=t.prev[t.strstart&t.w_mask]=t.head[t.ins_h],t.head[t.ins_h]=t.strstart),t.prev_length=t.match_length,t.prev_match=t.match_start,t.match_length=MIN_MATCH-1,0!==n&&t.prev_length<t.max_lazy_match&&t.strstart-n<=t.w_size-MIN_LOOKAHEAD&&(t.match_length=longest_match(t,n),t.match_length<=5&&(t.strategy===Z_FILTERED||t.match_length===MIN_MATCH&&t.strstart-t.match_start>4096)&&(t.match_length=MIN_MATCH-1)),t.prev_length>=MIN_MATCH&&t.match_length<=t.prev_length){i=t.strstart+t.lookahead-MIN_MATCH,r=_tr_tally(t,t.strstart-1-t.prev_match,t.prev_length-MIN_MATCH),t.lookahead-=t.prev_length-1,t.prev_length-=2;do{++t.strstart<=i&&(t.ins_h=HASH(t,t.ins_h,t.window[t.strstart+MIN_MATCH-1]),n=t.prev[t.strstart&t.w_mask]=t.head[t.ins_h],t.head[t.ins_h]=t.strstart)}while(0!==--t.prev_length);if(t.match_available=0,t.match_length=MIN_MATCH-1,t.strstart++,r&&(flush_block_only(t,!1),0===t.strm.avail_out))return BS_NEED_MORE}else if(t.match_available){if(r=_tr_tally(t,0,t.window[t.strstart-1]),r&&flush_block_only(t,!1),t.strstart++,t.lookahead--,0===t.strm.avail_out)return BS_NEED_MORE}else t.match_available=1,t.strstart++,t.lookahead--}return t.match_available&&(r=_tr_tally(t,0,t.window[t.strstart-1]),t.match_available=0),t.insert=t.strstart<MIN_MATCH-1?t.strstart:MIN_MATCH-1,e===Z_FINISH$3?(flush_block_only(t,!0),0===t.strm.avail_out?BS_FINISH_STARTED:BS_FINISH_DONE):t.sym_next&&(flush_block_only(t,!1),0===t.strm.avail_out)?BS_NEED_MORE:BS_BLOCK_DONE},deflate_rle=(t,e)=>{let n,r,i,s;const a=t.window;for(;;){if(t.lookahead<=MAX_MATCH){if(fill_window(t),t.lookahead<=MAX_MATCH&&e===Z_NO_FLUSH$2)return BS_NEED_MORE;if(0===t.lookahead)break}if(t.match_length=0,t.lookahead>=MIN_MATCH&&t.strstart>0&&(i=t.strstart-1,r=a[i],r===a[++i]&&r===a[++i]&&r===a[++i])){s=t.strstart+MAX_MATCH;do{}while(r===a[++i]&&r===a[++i]&&r===a[++i]&&r===a[++i]&&r===a[++i]&&r===a[++i]&&r===a[++i]&&r===a[++i]&&i<s);t.match_length=MAX_MATCH-(s-i),t.match_length>t.lookahead&&(t.match_length=t.lookahead)}if(t.match_length>=MIN_MATCH?(n=_tr_tally(t,1,t.match_length-MIN_MATCH),t.lookahead-=t.match_length,t.strstart+=t.match_length,t.match_length=0):(n=_tr_tally(t,0,t.window[t.strstart]),t.lookahead--,t.strstart++),n&&(flush_block_only(t,!1),0===t.strm.avail_out))return BS_NEED_MORE}return t.insert=0,e===Z_FINISH$3?(flush_block_only(t,!0),0===t.strm.avail_out?BS_FINISH_STARTED:BS_FINISH_DONE):t.sym_next&&(flush_block_only(t,!1),0===t.strm.avail_out)?BS_NEED_MORE:BS_BLOCK_DONE},deflate_huff=(t,e)=>{let n;for(;;){if(0===t.lookahead&&(fill_window(t),0===t.lookahead)){if(e===Z_NO_FLUSH$2)return BS_NEED_MORE;break}if(t.match_length=0,n=_tr_tally(t,0,t.window[t.strstart]),t.lookahead--,t.strstart++,n&&(flush_block_only(t,!1),0===t.strm.avail_out))return BS_NEED_MORE}return t.insert=0,e===Z_FINISH$3?(flush_block_only(t,!0),0===t.strm.avail_out?BS_FINISH_STARTED:BS_FINISH_DONE):t.sym_next&&(flush_block_only(t,!1),0===t.strm.avail_out)?BS_NEED_MORE:BS_BLOCK_DONE};function Config(t,e,n,r,i){this.good_length=t,this.max_lazy=e,this.nice_length=n,this.max_chain=r,this.func=i}const configuration_table=[new Config(0,0,0,0,deflate_stored),new Config(4,4,8,4,deflate_fast),new Config(4,5,16,8,deflate_fast),new Config(4,6,32,32,deflate_fast),new Config(4,4,16,16,deflate_slow),new Config(8,16,32,32,deflate_slow),new Config(8,16,128,128,deflate_slow),new Config(8,32,128,256,deflate_slow),new Config(32,128,258,1024,deflate_slow),new Config(32,258,258,4096,deflate_slow)],lm_init=t=>{t.window_size=2*t.w_size,zero(t.head),t.max_lazy_match=configuration_table[t.level].max_lazy,t.good_match=configuration_table[t.level].good_length,t.nice_match=configuration_table[t.level].nice_length,t.max_chain_length=configuration_table[t.level].max_chain,t.strstart=0,t.block_start=0,t.lookahead=0,t.insert=0,t.match_length=t.prev_length=MIN_MATCH-1,t.match_available=0,t.ins_h=0};function DeflateState(){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=Z_DEFLATED$2,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(2*HEAP_SIZE),this.dyn_dtree=new Uint16Array(2*(2*D_CODES+1)),this.bl_tree=new Uint16Array(2*(2*BL_CODES+1)),zero(this.dyn_ltree),zero(this.dyn_dtree),zero(this.bl_tree),this.l_desc=null,this.d_desc=null,this.bl_desc=null,this.bl_count=new Uint16Array(MAX_BITS+1),this.heap=new Uint16Array(2*L_CODES+1),zero(this.heap),this.heap_len=0,this.heap_max=0,this.depth=new Uint16Array(2*L_CODES+1),zero(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 deflateStateCheck=t=>{if(!t)return 1;const e=t.state;return!e||e.strm!==t||e.status!==INIT_STATE&&e.status!==GZIP_STATE&&e.status!==EXTRA_STATE&&e.status!==NAME_STATE&&e.status!==COMMENT_STATE&&e.status!==HCRC_STATE&&e.status!==BUSY_STATE&&e.status!==FINISH_STATE?1:0},deflateResetKeep=t=>{if(deflateStateCheck(t))return err(t,Z_STREAM_ERROR$2);t.total_in=t.total_out=0,t.data_type=Z_UNKNOWN;const e=t.state;return e.pending=0,e.pending_out=0,e.wrap<0&&(e.wrap=-e.wrap),e.status=2===e.wrap?GZIP_STATE:e.wrap?INIT_STATE:BUSY_STATE,t.adler=2===e.wrap?0:1,e.last_flush=-2,_tr_init(e),Z_OK$3},deflateReset=t=>{const e=deflateResetKeep(t);return e===Z_OK$3&&lm_init(t.state),e},deflateSetHeader=(t,e)=>deflateStateCheck(t)||2!==t.state.wrap?Z_STREAM_ERROR$2:(t.state.gzhead=e,Z_OK$3),deflateInit2=(t,e,n,r,i,s)=>{if(!t)return Z_STREAM_ERROR$2;let a=1;if(e===Z_DEFAULT_COMPRESSION$1&&(e=6),r<0?(a=0,r=-r):r>15&&(a=2,r-=16),i<1||i>MAX_MEM_LEVEL||n!==Z_DEFLATED$2||r<8||r>15||e<0||e>9||s<0||s>Z_FIXED||8===r&&1!==a)return err(t,Z_STREAM_ERROR$2);8===r&&(r=9);const o=new DeflateState;return t.state=o,o.strm=t,o.status=INIT_STATE,o.wrap=a,o.gzhead=null,o.w_bits=r,o.w_size=1<<o.w_bits,o.w_mask=o.w_size-1,o.hash_bits=i+7,o.hash_size=1<<o.hash_bits,o.hash_mask=o.hash_size-1,o.hash_shift=~~((o.hash_bits+MIN_MATCH-1)/MIN_MATCH),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<<i+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=e,o.strategy=s,o.method=n,deflateReset(t)},deflateInit=(t,e)=>deflateInit2(t,e,Z_DEFLATED$2,MAX_WBITS$1,DEF_MEM_LEVEL,Z_DEFAULT_STRATEGY$1),deflate$2=(t,e)=>{if(deflateStateCheck(t)||e>Z_BLOCK$1||e<0)return t?err(t,Z_STREAM_ERROR$2):Z_STREAM_ERROR$2;const n=t.state;if(!t.output||0!==t.avail_in&&!t.input||n.status===FINISH_STATE&&e!==Z_FINISH$3)return err(t,0===t.avail_out?Z_BUF_ERROR$1:Z_STREAM_ERROR$2);const r=n.last_flush;if(n.last_flush=e,0!==n.pending){if(flush_pending(t),0===t.avail_out)return n.last_flush=-1,Z_OK$3}else if(0===t.avail_in&&rank(e)<=rank(r)&&e!==Z_FINISH$3)return err(t,Z_BUF_ERROR$1);if(n.status===FINISH_STATE&&0!==t.avail_in)return err(t,Z_BUF_ERROR$1);if(n.status===INIT_STATE&&0===n.wrap&&(n.status=BUSY_STATE),n.status===INIT_STATE){let e=Z_DEFLATED$2+(n.w_bits-8<<4)<<8,r=-1;if(r=n.strategy>=Z_HUFFMAN_ONLY||n.level<2?0:n.level<6?1:6===n.level?2:3,e|=r<<6,0!==n.strstart&&(e|=PRESET_DICT),e+=31-e%31,putShortMSB(n,e),0!==n.strstart&&(putShortMSB(n,t.adler>>>16),putShortMSB(n,65535&t.adler)),t.adler=1,n.status=BUSY_STATE,flush_pending(t),0!==n.pending)return n.last_flush=-1,Z_OK$3}if(n.status===GZIP_STATE)if(t.adler=0,put_byte(n,31),put_byte(n,139),put_byte(n,8),n.gzhead)put_byte(n,(n.gzhead.text?1:0)+(n.gzhead.hcrc?2:0)+(n.gzhead.extra?4:0)+(n.gzhead.name?8:0)+(n.gzhead.comment?16:0)),put_byte(n,255&n.gzhead.time),put_byte(n,n.gzhead.time>>8&255),put_byte(n,n.gzhead.time>>16&255),put_byte(n,n.gzhead.time>>24&255),put_byte(n,9===n.level?2:n.strategy>=Z_HUFFMAN_ONLY||n.level<2?4:0),put_byte(n,255&n.gzhead.os),n.gzhead.extra&&n.gzhead.extra.length&&(put_byte(n,255&n.gzhead.extra.length),put_byte(n,n.gzhead.extra.length>>8&255)),n.gzhead.hcrc&&(t.adler=crc32_1(t.adler,n.pending_buf,n.pending,0)),n.gzindex=0,n.status=EXTRA_STATE;else if(put_byte(n,0),put_byte(n,0),put_byte(n,0),put_byte(n,0),put_byte(n,0),put_byte(n,9===n.level?2:n.strategy>=Z_HUFFMAN_ONLY||n.level<2?4:0),put_byte(n,OS_CODE),n.status=BUSY_STATE,flush_pending(t),0!==n.pending)return n.last_flush=-1,Z_OK$3;if(n.status===EXTRA_STATE){if(n.gzhead.extra){let e=n.pending,r=(65535&n.gzhead.extra.length)-n.gzindex;for(;n.pending+r>n.pending_buf_size;){let i=n.pending_buf_size-n.pending;if(n.pending_buf.set(n.gzhead.extra.subarray(n.gzindex,n.gzindex+i),n.pending),n.pending=n.pending_buf_size,n.gzhead.hcrc&&n.pending>e&&(t.adler=crc32_1(t.adler,n.pending_buf,n.pending-e,e)),n.gzindex+=i,flush_pending(t),0!==n.pending)return n.last_flush=-1,Z_OK$3;e=0,r-=i}let i=new Uint8Array(n.gzhead.extra);n.pending_buf.set(i.subarray(n.gzindex,n.gzindex+r),n.pending),n.pending+=r,n.gzhead.hcrc&&n.pending>e&&(t.adler=crc32_1(t.adler,n.pending_buf,n.pending-e,e)),n.gzindex=0}n.status=NAME_STATE}if(n.status===NAME_STATE){if(n.gzhead.name){let e,r=n.pending;do{if(n.pending===n.pending_buf_size){if(n.gzhead.hcrc&&n.pending>r&&(t.adler=crc32_1(t.adler,n.pending_buf,n.pending-r,r)),flush_pending(t),0!==n.pending)return n.last_flush=-1,Z_OK$3;r=0}e=n.gzindex<n.gzhead.name.length?255&n.gzhead.name.charCodeAt(n.gzindex++):0,put_byte(n,e)}while(0!==e);n.gzhead.hcrc&&n.pending>r&&(t.adler=crc32_1(t.adler,n.pending_buf,n.pending-r,r)),n.gzindex=0}n.status=COMMENT_STATE}if(n.status===COMMENT_STATE){if(n.gzhead.comment){let e,r=n.pending;do{if(n.pending===n.pending_buf_size){if(n.gzhead.hcrc&&n.pending>r&&(t.adler=crc32_1(t.adler,n.pending_buf,n.pending-r,r)),flush_pending(t),0!==n.pending)return n.last_flush=-1,Z_OK$3;r=0}e=n.gzindex<n.gzhead.comment.length?255&n.gzhead.comment.charCodeAt(n.gzindex++):0,put_byte(n,e)}while(0!==e);n.gzhead.hcrc&&n.pending>r&&(t.adler=crc32_1(t.adler,n.pending_buf,n.pending-r,r))}n.status=HCRC_STATE}if(n.status===HCRC_STATE){if(n.gzhead.hcrc){if(n.pending+2>n.pending_buf_size&&(flush_pending(t),0!==n.pending))return n.last_flush=-1,Z_OK$3;put_byte(n,255&t.adler),put_byte(n,t.adler>>8&255),t.adler=0}if(n.status=BUSY_STATE,flush_pending(t),0!==n.pending)return n.last_flush=-1,Z_OK$3}if(0!==t.avail_in||0!==n.lookahead||e!==Z_NO_FLUSH$2&&n.status!==FINISH_STATE){let r=0===n.level?deflate_stored(n,e):n.strategy===Z_HUFFMAN_ONLY?deflate_huff(n,e):n.strategy===Z_RLE?deflate_rle(n,e):configuration_table[n.level].func(n,e);if(r!==BS_FINISH_STARTED&&r!==BS_FINISH_DONE||(n.status=FINISH_STATE),r===BS_NEED_MORE||r===BS_FINISH_STARTED)return 0===t.avail_out&&(n.last_flush=-1),Z_OK$3;if(r===BS_BLOCK_DONE&&(e===Z_PARTIAL_FLUSH?_tr_align(n):e!==Z_BLOCK$1&&(_tr_stored_block(n,0,0,!1),e===Z_FULL_FLUSH$1&&(zero(n.head),0===n.lookahead&&(n.strstart=0,n.block_start=0,n.insert=0))),flush_pending(t),0===t.avail_out))return n.last_flush=-1,Z_OK$3}return e!==Z_FINISH$3?Z_OK$3:n.wrap<=0?Z_STREAM_END$3:(2===n.wrap?(put_byte(n,255&t.adler),put_byte(n,t.adler>>8&255),put_byte(n,t.adler>>16&255),put_byte(n,t.adler>>24&255),put_byte(n,255&t.total_in),put_byte(n,t.total_in>>8&255),put_byte(n,t.total_in>>16&255),put_byte(n,t.total_in>>24&255)):(putShortMSB(n,t.adler>>>16),putShortMSB(n,65535&t.adler)),flush_pending(t),n.wrap>0&&(n.wrap=-n.wrap),0!==n.pending?Z_OK$3:Z_STREAM_END$3)},deflateEnd=t=>{if(deflateStateCheck(t))return Z_STREAM_ERROR$2;const e=t.state.status;return t.state=null,e===BUSY_STATE?err(t,Z_DATA_ERROR$2):Z_OK$3},deflateSetDictionary=(t,e)=>{let n=e.length;if(deflateStateCheck(t))return Z_STREAM_ERROR$2;const r=t.state,i=r.wrap;if(2===i||1===i&&r.status!==INIT_STATE||r.lookahead)return Z_STREAM_ERROR$2;if(1===i&&(t.adler=adler32_1(t.adler,e,n,0)),r.wrap=0,n>=r.w_size){0===i&&(zero(r.head),r.strstart=0,r.block_start=0,r.insert=0);let t=new Uint8Array(r.w_size);t.set(e.subarray(n-r.w_size,n),0),e=t,n=r.w_size}const s=t.avail_in,a=t.next_in,o=t.input;for(t.avail_in=n,t.next_in=0,t.input=e,fill_window(r);r.lookahead>=MIN_MATCH;){let t=r.strstart,e=r.lookahead-(MIN_MATCH-1);do{r.ins_h=HASH(r,r.ins_h,r.window[t+MIN_MATCH-1]),r.prev[t&r.w_mask]=r.head[r.ins_h],r.head[r.ins_h]=t,t++}while(--e);r.strstart=t,r.lookahead=MIN_MATCH-1,fill_window(r)}return r.strstart+=r.lookahead,r.block_start=r.strstart,r.insert=r.lookahead,r.lookahead=0,r.match_length=r.prev_length=MIN_MATCH-1,r.match_available=0,t.next_in=a,t.input=o,t.avail_in=s,r.wrap=i,Z_OK$3};var deflateInit_1=deflateInit,deflateInit2_1=deflateInit2,deflateReset_1=deflateReset,deflateResetKeep_1=deflateResetKeep,deflateSetHeader_1=deflateSetHeader,deflate_2$1=deflate$2,deflateEnd_1=deflateEnd,deflateSetDictionary_1=deflateSetDictionary,deflateInfo="pako deflate (from Nodeca project)",deflate_1$2={deflateInit:deflateInit_1,deflateInit2:deflateInit2_1,deflateReset:deflateReset_1,deflateResetKeep:deflateResetKeep_1,deflateSetHeader:deflateSetHeader_1,deflate:deflate_2$1,deflateEnd:deflateEnd_1,deflateSetDictionary:deflateSetDictionary_1,deflateInfo};const _has=(t,e)=>Object.prototype.hasOwnProperty.call(t,e);var assign=function(t){const e=Array.prototype.slice.call(arguments,1);for(;e.length;){const n=e.shift();if(n){if("object"!=typeof n)throw new TypeError(n+"must be non-object");for(const e in n)_has(n,e)&&(t[e]=n[e])}}return t},flattenChunks=t=>{let e=0;for(let n=0,r=t.length;n<r;n++)e+=t[n].length;const n=new Uint8Array(e);for(let e=0,r=0,i=t.length;e<i;e++){let i=t[e];n.set(i,r),r+=i.length}return n},common={assign,flattenChunks};let STR_APPLY_UIA_OK=!0;try{String.fromCharCode.apply(null,new Uint8Array(1))}catch(t){STR_APPLY_UIA_OK=!1}const _utf8len=new Uint8Array(256);for(let t=0;t<256;t++)_utf8len[t]=t>=252?6:t>=248?5:t>=240?4:t>=224?3:t>=192?2:1;_utf8len[254]=_utf8len[254]=1;var string2buf=t=>{if("function"==typeof TextEncoder&&TextEncoder.prototype.encode)return(new TextEncoder).encode(t);let e,n,r,i,s,a=t.length,o=0;for(i=0;i<a;i++)n=t.charCodeAt(i),55296==(64512&n)&&i+1<a&&(r=t.charCodeAt(i+1),56320==(64512&r)&&(n=65536+(n-55296<<10)+(r-56320),i++)),o+=n<128?1:n<2048?2:n<65536?3:4;for(e=new Uint8Array(o),s=0,i=0;s<o;i++)n=t.charCodeAt(i),55296==(64512&n)&&i+1<a&&(r=t.charCodeAt(i+1),56320==(64512&r)&&(n=65536+(n-55296<<10)+(r-56320),i++)),n<128?e[s++]=n:n<2048?(e[s++]=192|n>>>6,e[s++]=128|63&n):n<65536?(e[s++]=224|n>>>12,e[s++]=128|n>>>6&63,e[s++]=128|63&n):(e[s++]=240|n>>>18,e[s++]=128|n>>>12&63,e[s++]=128|n>>>6&63,e[s++]=128|63&n);return e};const buf2binstring=(t,e)=>{if(e<65534&&t.subarray&&STR_APPLY_UIA_OK)return String.fromCharCode.apply(null,t.length===e?t:t.subarray(0,e));let n="";for(let r=0;r<e;r++)n+=String.fromCharCode(t[r]);return n};var buf2string=(t,e)=>{const n=e||t.length;if("function"==typeof TextDecoder&&TextDecoder.prototype.decode)return(new TextDecoder).decode(t.subarray(0,e));let r,i;const s=new Array(2*n);for(i=0,r=0;r<n;){let e=t[r++];if(e<128){s[i++]=e;continue}let a=_utf8len[e];if(a>4)s[i++]=65533,r+=a-1;else{for(e&=2===a?31:3===a?15:7;a>1&&r<n;)e=e<<6|63&t[r++],a--;a>1?s[i++]=65533:e<65536?s[i++]=e:(e-=65536,s[i++]=55296|e>>10&1023,s[i++]=56320|1023&e)}}return buf2binstring(s,i)},utf8border=(t,e)=>{(e=e||t.length)>t.length&&(e=t.length);let n=e-1;for(;n>=0&&128==(192&t[n]);)n--;return n<0||0===n?e:n+_utf8len[t[n]]>e?n:e},strings={string2buf,buf2string,utf8border};function ZStream(){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}var zstream=ZStream;const toString$1=Object.prototype.toString,{Z_NO_FLUSH:Z_NO_FLUSH$1,Z_SYNC_FLUSH,Z_FULL_FLUSH,Z_FINISH:Z_FINISH$2,Z_OK:Z_OK$2,Z_STREAM_END:Z_STREAM_END$2,Z_DEFAULT_COMPRESSION,Z_DEFAULT_STRATEGY,Z_DEFLATED:Z_DEFLATED$1}=constants$2;function Deflate$1(t){this.options=common.assign({level:Z_DEFAULT_COMPRESSION,method:Z_DEFLATED$1,chunkSize:16384,windowBits:15,memLevel:8,strategy:Z_DEFAULT_STRATEGY},t||{});let e=this.options;e.raw&&e.windowBits>0?e.windowBits=-e.windowBits:e.gzip&&e.windowBits>0&&e.windowBits<16&&(e.windowBits+=16),this.err=0,this.msg="",this.ended=!1,this.chunks=[],this.strm=new zstream,this.strm.avail_out=0;let n=deflate_1$2.deflateInit2(this.strm,e.level,e.method,e.windowBits,e.memLevel,e.strategy);if(n!==Z_OK$2)throw new Error(messages[n]);if(e.header&&deflate_1$2.deflateSetHeader(this.strm,e.header),e.dictionary){let t;if(t="string"==typeof e.dictionary?strings.string2buf(e.dictionary):"[object ArrayBuffer]"===toString$1.call(e.dictionary)?new Uint8Array(e.dictionary):e.dictionary,n=deflate_1$2.deflateSetDictionary(this.strm,t),n!==Z_OK$2)throw new Error(messages[n]);this._dict_set=!0}}function deflate$1(t,e){const n=new Deflate$1(e);if(n.push(t,!0),n.err)throw n.msg||messages[n.err];return n.result}function deflateRaw$1(t,e){return(e=e||{}).raw=!0,deflate$1(t,e)}function gzip$1(t,e){return(e=e||{}).gzip=!0,deflate$1(t,e)}Deflate$1.prototype.push=function(t,e){const n=this.strm,r=this.options.chunkSize;let i,s;if(this.ended)return!1;for(s=e===~~e?e:!0===e?Z_FINISH$2:Z_NO_FLUSH$1,n.input="string"==typeof t?strings.string2buf(t):"[object ArrayBuffer]"===toString$1.call(t)?new Uint8Array(t):t,n.next_in=0,n.avail_in=n.input.length;;)if(0===n.avail_out&&(n.output=new Uint8Array(r),n.next_out=0,n.avail_out=r),(s===Z_SYNC_FLUSH||s===Z_FULL_FLUSH)&&n.avail_out<=6)this.onData(n.output.subarray(0,n.next_out)),n.avail_out=0;else{if(i=deflate_1$2.deflate(n,s),i===Z_STREAM_END$2)return n.next_out>0&&this.onData(n.output.subarray(0,n.next_out)),i=deflate_1$2.deflateEnd(this.strm),this.onEnd(i),this.ended=!0,i===Z_OK$2;if(0!==n.avail_out){if(s>0&&n.next_out>0)this.onData(n.output.subarray(0,n.next_out)),n.avail_out=0;else if(0===n.avail_in)break}else this.onData(n.output)}return!0},Deflate$1.prototype.onData=function(t){this.chunks.push(t)},Deflate$1.prototype.onEnd=function(t){t===Z_OK$2&&(this.result=common.flattenChunks(this.chunks)),this.chunks=[],this.err=t,this.msg=this.strm.msg};var Deflate_1$1=Deflate$1,deflate_2=deflate$1,deflateRaw_1$1=deflateRaw$1,gzip_1$1=gzip$1,constants$1=constants$2,deflate_1$1={Deflate:Deflate_1$1,deflate:deflate_2,deflateRaw:deflateRaw_1$1,gzip:gzip_1$1,constants:constants$1};const BAD$1=16209,TYPE$1=16191;var inffast=function(t,e){let n,r,i,s,a,o,l,c,d,h,u,p,f,m,_,g,y,S,A,v,E,b,T,w;const x=t.state;n=t.next_in,T=t.input,r=n+(t.avail_in-5),i=t.next_out,w=t.output,s=i-(e-t.avail_out),a=i+(t.avail_out-257),o=x.dmax,l=x.wsize,c=x.whave,d=x.wnext,h=x.window,u=x.hold,p=x.bits,f=x.lencode,m=x.distcode,_=(1<<x.lenbits)-1,g=(1<<x.distbits)-1;t:do{p<15&&(u+=T[n++]<<p,p+=8,u+=T[n++]<<p,p+=8),y=f[u&_];e:for(;;){if(S=y>>>24,u>>>=S,p-=S,S=y>>>16&255,0===S)w[i++]=65535&y;else{if(!(16&S)){if(64&S){if(32&S){x.mode=TYPE$1;break t}t.msg="invalid literal/length code",x.mode=BAD$1;break t}y=f[(65535&y)+(u&(1<<S)-1)];continue e}for(A=65535&y,S&=15,S&&(p<S&&(u+=T[n++]<<p,p+=8),A+=u&(1<<S)-1,u>>>=S,p-=S),p<15&&(u+=T[n++]<<p,p+=8,u+=T[n++]<<p,p+=8),y=m[u&g];;){if(S=y>>>24,u>>>=S,p-=S,S=y>>>16&255,16&S){if(v=65535&y,S&=15,p<S&&(u+=T[n++]<<p,p+=8,p<S&&(u+=T[n++]<<p,p+=8)),v+=u&(1<<S)-1,v>o){t.msg="invalid distance too far back",x.mode=BAD$1;break t}if(u>>>=S,p-=S,S=i-s,v>S){if(S=v-S,S>c&&x.sane){t.msg="invalid distance too far back",x.mode=BAD$1;break t}if(E=0,b=h,0===d){if(E+=l-S,S<A){A-=S;do{w[i++]=h[E++]}while(--S);E=i-v,b=w}}else if(d<S){if(E+=l+d-S,S-=d,S<A){A-=S;do{w[i++]=h[E++]}while(--S);if(E=0,d<A){S=d,A-=S;do{w[i++]=h[E++]}while(--S);E=i-v,b=w}}}else if(E+=d-S,S<A){A-=S;do{w[i++]=h[E++]}while(--S);E=i-v,b=w}for(;A>2;)w[i++]=b[E++],w[i++]=b[E++],w[i++]=b[E++],A-=3;A&&(w[i++]=b[E++],A>1&&(w[i++]=b[E++]))}else{E=i-v;do{w[i++]=w[E++],w[i++]=w[E++],w[i++]=w[E++],A-=3}while(A>2);A&&(w[i++]=w[E++],A>1&&(w[i++]=w[E++]))}break}if(64&S){t.msg="invalid distance code",x.mode=BAD$1;break t}y=m[(65535&y)+(u&(1<<S)-1)]}}break}}while(n<r&&i<a);A=p>>3,n-=A,p-=A<<3,u&=(1<<p)-1,t.next_in=n,t.next_out=i,t.avail_in=n<r?r-n+5:5-(n-r),t.avail_out=i<a?a-i+257:257-(i-a),x.hold=u,x.bits=p};const MAXBITS=15,ENOUGH_LENS$1=852,ENOUGH_DISTS$1=592,CODES$1=0,LENS$1=1,DISTS$1=2,lbase=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]),lext=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]),dbase=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]),dext=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]),inflate_table=(t,e,n,r,i,s,a,o)=>{const l=o.bits;let c,d,h,u,p,f,m=0,_=0,g=0,y=0,S=0,A=0,v=0,E=0,b=0,T=0,w=null;const x=new Uint16Array(MAXBITS+1),I=new Uint16Array(MAXBITS+1);let R,C,B,D=null;for(m=0;m<=MAXBITS;m++)x[m]=0;for(_=0;_<r;_++)x[e[n+_]]++;for(S=l,y=MAXBITS;y>=1&&0===x[y];y--);if(S>y&&(S=y),0===y)return i[s++]=20971520,i[s++]=20971520,o.bits=1,0;for(g=1;g<y&&0===x[g];g++);for(S<g&&(S=g),E=1,m=1;m<=MAXBITS;m++)if(E<<=1,E-=x[m],E<0)return-1;if(E>0&&(t===CODES$1||1!==y))return-1;for(I[1]=0,m=1;m<MAXBITS;m++)I[m+1]=I[m]+x[m];for(_=0;_<r;_++)0!==e[n+_]&&(a[I[e[n+_]]++]=_);if(t===CODES$1?(w=D=a,f=20):t===LENS$1?(w=lbase,D=lext,f=257):(w=dbase,D=dext,f=0),T=0,_=0,m=g,p=s,A=S,v=0,h=-1,b=1<<S,u=b-1,t===LENS$1&&b>ENOUGH_LENS$1||t===DISTS$1&&b>ENOUGH_DISTS$1)return 1;for(;;){R=m-v,a[_]+1<f?(C=0,B=a[_]):a[_]>=f?(C=D[a[_]-f],B=w[a[_]-f]):(C=96,B=0),c=1<<m-v,d=1<<A,g=d;do{d-=c,i[p+(T>>v)+d]=R<<24|C<<16|B}while(0!==d);for(c=1<<m-1;T&c;)c>>=1;if(0!==c?(T&=c-1,T+=c):T=0,_++,0===--x[m]){if(m===y)break;m=e[n+a[_]]}if(m>S&&(T&u)!==h){for(0===v&&(v=S),p+=g,A=m-v,E=1<<A;A+v<y&&(E-=x[A+v],!(E<=0));)A++,E<<=1;if(b+=1<<A,t===LENS$1&&b>ENOUGH_LENS$1||t===DISTS$1&&b>ENOUGH_DISTS$1)return 1;h=T&u,i[h]=S<<24|A<<16|p-s}}return 0!==T&&(i[p+T]=m-v<<24|64<<16),o.bits=S,0};var inftrees=inflate_table;const CODES=0,LENS=1,DISTS=2,{Z_FINISH:Z_FINISH$1,Z_BLOCK,Z_TREES,Z_OK:Z_OK$1,Z_STREAM_END:Z_STREAM_END$1,Z_NEED_DICT:Z_NEED_DICT$1,Z_STREAM_ERROR:Z_STREAM_ERROR$1,Z_DATA_ERROR:Z_DATA_ERROR$1,Z_MEM_ERROR:Z_MEM_ERROR$1,Z_BUF_ERROR,Z_DEFLATED}=constants$2,HEAD=16180,FLAGS=16181,TIME=16182,OS=16183,EXLEN=16184,EXTRA=16185,NAME=16186,COMMENT=16187,HCRC=16188,DICTID=16189,DICT=16190,TYPE=16191,TYPEDO=16192,STORED=16193,COPY_=16194,COPY=16195,TABLE=16196,LENLENS=16197,CODELENS=16198,LEN_=16199,LEN=16200,LENEXT=16201,DIST=16202,DISTEXT=16203,MATCH=16204,LIT=16205,CHECK=16206,LENGTH=16207,DONE=16208,BAD=16209,MEM=16210,SYNC=16211,ENOUGH_LENS=852,ENOUGH_DISTS=592,MAX_WBITS=15,DEF_WBITS=MAX_WBITS,zswap32=t=>(t>>>24&255)+(t>>>8&65280)+((65280&t)<<8)+((255&t)<<24);function InflateState(){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 inflateStateCheck=t=>{if(!t)return 1;const e=t.state;return!e||e.strm!==t||e.mode<HEAD||e.mode>SYNC?1:0},inflateResetKeep=t=>{if(inflateStateCheck(t))return Z_STREAM_ERROR$1;const e=t.state;return t.total_in=t.total_out=e.total=0,t.msg="",e.wrap&&(t.adler=1&e.wrap),e.mode=HEAD,e.last=0,e.havedict=0,e.flags=-1,e.dmax=32768,e.head=null,e.hold=0,e.bits=0,e.lencode=e.lendyn=new Int32Array(ENOUGH_LENS),e.distcode=e.distdyn=new Int32Array(ENOUGH_DISTS),e.sane=1,e.back=-1,Z_OK$1},inflateReset=t=>{if(inflateStateCheck(t))return Z_STREAM_ERROR$1;const e=t.state;return e.wsize=0,e.whave=0,e.wnext=0,inflateResetKeep(t)},inflateReset2=(t,e)=>{let n;if(inflateStateCheck(t))return Z_STREAM_ERROR$1;const r=t.state;return e<0?(n=0,e=-e):(n=5+(e>>4),e<48&&(e&=15)),e&&(e<8||e>15)?Z_STREAM_ERROR$1:(null!==r.window&&r.wbits!==e&&(r.window=null),r.wrap=n,r.wbits=e,inflateReset(t))},inflateInit2=(t,e)=>{if(!t)return Z_STREAM_ERROR$1;const n=new InflateState;t.state=n,n.strm=t,n.window=null,n.mode=HEAD;const r=inflateReset2(t,e);return r!==Z_OK$1&&(t.state=null),r},inflateInit=t=>inflateInit2(t,DEF_WBITS);let virgin=!0,lenfix,distfix;const fixedtables=t=>{if(virgin){lenfix=new Int32Array(512),distfix=new Int32Array(32);let e=0;for(;e<144;)t.lens[e++]=8;for(;e<256;)t.lens[e++]=9;for(;e<280;)t.lens[e++]=7;for(;e<288;)t.lens[e++]=8;for(inftrees(LENS,t.lens,0,288,lenfix,0,t.work,{bits:9}),e=0;e<32;)t.lens[e++]=5;inftrees(DISTS,t.lens,0,32,distfix,0,t.work,{bits:5}),virgin=!1}t.lencode=lenfix,t.lenbits=9,t.distcode=distfix,t.distbits=5},updatewindow=(t,e,n,r)=>{let i;const s=t.state;return null===s.window&&(s.wsize=1<<s.wbits,s.wnext=0,s.whave=0,s.window=new Uint8Array(s.wsize)),r>=s.wsize?(s.window.set(e.subarray(n-s.wsize,n),0),s.wnext=0,s.whave=s.wsize):(i=s.wsize-s.wnext,i>r&&(i=r),s.window.set(e.subarray(n-r,n-r+i),s.wnext),(r-=i)?(s.window.set(e.subarray(n-r,n),0),s.wnext=r,s.whave=s.wsize):(s.wnext+=i,s.wnext===s.wsize&&(s.wnext=0),s.whave<s.wsize&&(s.whave+=i))),0},inflate$2=(t,e)=>{let n,r,i,s,a,o,l,c,d,h,u,p,f,m,_,g,y,S,A,v,E,b,T=0;const w=new Uint8Array(4);let x,I;const R=new Uint8Array([16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15]);if(inflateStateCheck(t)||!t.output||!t.input&&0!==t.avail_in)return Z_STREAM_ERROR$1;n=t.state,n.mode===TYPE&&(n.mode=TYPEDO),a=t.next_out,i=t.output,l=t.avail_out,s=t.next_in,r=t.input,o=t.avail_in,c=n.hold,d=n.bits,h=o,u=l,b=Z_OK$1;t:for(;;)switch(n.mode){case HEAD:if(0===n.wrap){n.mode=TYPEDO;break}for(;d<16;){if(0===o)break t;o--,c+=r[s++]<<d,d+=8}if(2&n.wrap&&35615===c){0===n.wbits&&(n.wbits=15),n.check=0,w[0]=255&c,w[1]=c>>>8&255,n.check=crc32_1(n.check,w,2,0),c=0,d=0,n.mode=FLAGS;break}if(n.head&&(n.head.done=!1),!(1&n.wrap)||(((255&c)<<8)+(c>>8))%31){t.msg="incorrect header check",n.mode=BAD;break}if((15&c)!==Z_DEFLATED){t.msg="unknown compression method",n.mode=BAD;break}if(c>>>=4,d-=4,E=8+(15&c),0===n.wbits&&(n.wbits=E),E>15||E>n.wbits){t.msg="invalid window size",n.mode=BAD;break}n.dmax=1<<n.wbits,n.flags=0,t.adler=n.check=1,n.mode=512&c?DICTID:TYPE,c=0,d=0;break;case FLAGS:for(;d<16;){if(0===o)break t;o--,c+=r[s++]<<d,d+=8}if(n.flags=c,(255&n.flags)!==Z_DEFLATED){t.msg="unknown compression method",n.mode=BAD;break}if(57344&n.flags){t.msg="unknown header flags set",n.mode=BAD;break}n.head&&(n.head.text=c>>8&1),512&n.flags&&4&n.wrap&&(w[0]=255&c,w[1]=c>>>8&255,n.check=crc32_1(n.check,w,2,0)),c=0,d=0,n.mode=TIME;case TIME:for(;d<32;){if(0===o)break t;o--,c+=r[s++]<<d,d+=8}n.head&&(n.head.time=c),512&n.flags&&4&n.wrap&&(w[0]=255&c,w[1]=c>>>8&255,w[2]=c>>>16&255,w[3]=c>>>24&255,n.check=crc32_1(n.check,w,4,0)),c=0,d=0,n.mode=OS;case OS:for(;d<16;){if(0===o)break t;o--,c+=r[s++]<<d,d+=8}n.head&&(n.head.xflags=255&c,n.head.os=c>>8),512&n.flags&&4&n.wrap&&(w[0]=255&c,w[1]=c>>>8&255,n.check=crc32_1(n.check,w,2,0)),c=0,d=0,n.mode=EXLEN;case EXLEN:if(1024&n.flags){for(;d<16;){if(0===o)break t;o--,c+=r[s++]<<d,d+=8}n.length=c,n.head&&(n.head.extra_len=c),512&n.flags&&4&n.wrap&&(w[0]=255&c,w[1]=c>>>8&255,n.check=crc32_1(n.check,w,2,0)),c=0,d=0}else n.head&&(n.head.extra=null);n.mode=EXTRA;case EXTRA:if(1024&n.flags&&(p=n.length,p>o&&(p=o),p&&(n.head&&(E=n.head.extra_len-n.length,n.head.extra||(n.head.extra=new Uint8Array(n.head.extra_len)),n.head.extra.set(r.subarray(s,s+p),E)),512&n.flags&&4&n.wrap&&(n.check=crc32_1(n.check,r,p,s)),o-=p,s+=p,n.length-=p),n.length))break t;n.length=0,n.mode=NAME;case NAME:if(2048&n.flags){if(0===o)break t;p=0;do{E=r[s+p++],n.head&&E&&n.length<65536&&(n.head.name+=String.fromCharCode(E))}while(E&&p<o);if(512&n.flags&&4&n.wrap&&(n.check=crc32_1(n.check,r,p,s)),o-=p,s+=p,E)break t}else n.head&&(n.head.name=null);n.length=0,n.mode=COMMENT;case COMMENT:if(4096&n.flags){if(0===o)break t;p=0;do{E=r[s+p++],n.head&&E&&n.length<65536&&(n.head.comment+=String.fromCharCode(E))}while(E&&p<o);if(512&n.flags&&4&n.wrap&&(n.check=crc32_1(n.check,r,p,s)),o-=p,s+=p,E)break t}else n.head&&(n.head.comment=null);n.mode=HCRC;case HCRC:if(512&n.flags){for(;d<16;){if(0===o)break t;o--,c+=r[s++]<<d,d+=8}if(4&n.wrap&&c!==(65535&n.check)){t.msg="header crc mismatch",n.mode=BAD;break}c=0,d=0}n.head&&(n.head.hcrc=n.flags>>9&1,n.head.done=!0),t.adler=n.check=0,n.mode=TYPE;break;case DICTID:for(;d<32;){if(0===o)break t;o--,c+=r[s++]<<d,d+=8}t.adler=n.check=zswap32(c),c=0,d=0,n.mode=DICT;case DICT:if(0===n.havedict)return t.next_out=a,t.avail_out=l,t.next_in=s,t.avail_in=o,n.hold=c,n.bits=d,Z_NEED_DICT$1;t.adler=n.check=1,n.mode=TYPE;case TYPE:if(e===Z_BLOCK||e===Z_TREES)break t;case TYPEDO:if(n.last){c>>>=7&d,d-=7&d,n.mode=CHECK;break}for(;d<3;){if(0===o)break t;o--,c+=r[s++]<<d,d+=8}switch(n.last=1&c,c>>>=1,d-=1,3&c){case 0:n.mode=STORED;break;case 1:if(fixedtables(n),n.mode=LEN_,e===Z_TREES){c>>>=2,d-=2;break t}break;case 2:n.mode=TABLE;break;case 3:t.msg="invalid block type",n.mode=BAD}c>>>=2,d-=2;break;case STORED:for(c>>>=7&d,d-=7&d;d<32;){if(0===o)break t;o--,c+=r[s++]<<d,d+=8}if((65535&c)!=(c>>>16^65535)){t.msg="invalid stored block lengths",n.mode=BAD;break}if(n.length=65535&c,c=0,d=0,n.mode=COPY_,e===Z_TREES)break t;case COPY_:n.mode=COPY;case COPY:if(p=n.length,p){if(p>o&&(p=o),p>l&&(p=l),0===p)break t;i.set(r.subarray(s,s+p),a),o-=p,s+=p,l-=p,a+=p,n.length-=p;break}n.mode=TYPE;break;case TABLE:for(;d<14;){if(0===o)break t;o--,c+=r[s++]<<d,d+=8}if(n.nlen=257+(31&c),c>>>=5,d-=5,n.ndist=1+(31&c),c>>>=5,d-=5,n.ncode=4+(15&c),c>>>=4,d-=4,n.nlen>286||n.ndist>30){t.msg="too many length or distance symbols",n.mode=BAD;break}n.have=0,n.mode=LENLENS;case LENLENS:for(;n.have<n.ncode;){for(;d<3;){if(0===o)break t;o--,c+=r[s++]<<d,d+=8}n.lens[R[n.have++]]=7&c,c>>>=3,d-=3}for(;n.have<19;)n.lens[R[n.have++]]=0;if(n.lencode=n.lendyn,n.lenbits=7,x={bits:n.lenbits},b=inftrees(CODES,n.lens,0,19,n.lencode,0,n.work,x),n.lenbits=x.bits,b){t.msg="invalid code lengths set",n.mode=BAD;break}n.have=0,n.mode=CODELENS;case CODELENS:for(;n.have<n.nlen+n.ndist;){for(;T=n.lencode[c&(1<<n.lenbits)-1],_=T>>>24,g=T>>>16&255,y=65535&T,!(_<=d);){if(0===o)break t;o--,c+=r[s++]<<d,d+=8}if(y<16)c>>>=_,d-=_,n.lens[n.have++]=y;else{if(16===y){for(I=_+2;d<I;){if(0===o)break t;o--,c+=r[s++]<<d,d+=8}if(c>>>=_,d-=_,0===n.have){t.msg="invalid bit length repeat",n.mode=BAD;break}E=n.lens[n.have-1],p=3+(3&c),c>>>=2,d-=2}else if(17===y){for(I=_+3;d<I;){if(0===o)break t;o--,c+=r[s++]<<d,d+=8}c>>>=_,d-=_,E=0,p=3+(7&c),c>>>=3,d-=3}else{for(I=_+7;d<I;){if(0===o)break t;o--,c+=r[s++]<<d,d+=8}c>>>=_,d-=_,E=0,p=11+(127&c),c>>>=7,d-=7}if(n.have+p>n.nlen+n.ndist){t.msg="invalid bit length repeat",n.mode=BAD;break}for(;p--;)n.lens[n.have++]=E}}if(n.mode===BAD)break;if(0===n.lens[256]){t.msg="invalid code -- missing end-of-block",n.mode=BAD;break}if(n.lenbits=9,x={bits:n.lenbits},b=inftrees(LENS,n.lens,0,n.nlen,n.lencode,0,n.work,x),n.lenbits=x.bits,b){t.msg="invalid literal/lengths set",n.mode=BAD;break}if(n.distbits=6,n.distcode=n.distdyn,x={bits:n.distbits},b=inftrees(DISTS,n.lens,n.nlen,n.ndist,n.distcode,0,n.work,x),n.distbits=x.bits,b){t.msg="invalid distances set",n.mode=BAD;break}if(n.mode=LEN_,e===Z_TREES)break t;case LEN_:n.mode=LEN;case LEN:if(o>=6&&l>=258){t.next_out=a,t.avail_out=l,t.next_in=s,t.avail_in=o,n.hold=c,n.bits=d,inffast(t,u),a=t.next_out,i=t.output,l=t.avail_out,s=t.next_in,r=t.input,o=t.avail_in,c=n.hold,d=n.bits,n.mode===TYPE&&(n.back=-1);break}for(n.back=0;T=n.lencode[c&(1<<n.lenbits)-1],_=T>>>24,g=T>>>16&255,y=65535&T,!(_<=d);){if(0===o)break t;o--,c+=r[s++]<<d,d+=8}if(g&&!(240&g)){for(S=_,A=g,v=y;T=n.lencode[v+((c&(1<<S+A)-1)>>S)],_=T>>>24,g=T>>>16&255,y=65535&T,!(S+_<=d);){if(0===o)break t;o--,c+=r[s++]<<d,d+=8}c>>>=S,d-=S,n.back+=S}if(c>>>=_,d-=_,n.back+=_,n.length=y,0===g){n.mode=LIT;break}if(32&g){n.back=-1,n.mode=TYPE;break}if(64&g){t.msg="invalid literal/length code",n.mode=BAD;break}n.extra=15&g,n.mode=LENEXT;case LENEXT:if(n.extra){for(I=n.extra;d<I;){if(0===o)break t;o--,c+=r[s++]<<d,d+=8}n.length+=c&(1<<n.extra)-1,c>>>=n.extra,d-=n.extra,n.back+=n.extra}n.was=n.length,n.mode=DIST;case DIST:for(;T=n.distcode[c&(1<<n.distbits)-1],_=T>>>24,g=T>>>16&255,y=65535&T,!(_<=d);){if(0===o)break t;o--,c+=r[s++]<<d,d+=8}if(!(240&g)){for(S=_,A=g,v=y;T=n.distcode[v+((c&(1<<S+A)-1)>>S)],_=T>>>24,g=T>>>16&255,y=65535&T,!(S+_<=d);){if(0===o)break t;o--,c+=r[s++]<<d,d+=8}c>>>=S,d-=S,n.back+=S}if(c>>>=_,d-=_,n.back+=_,64&g){t.msg="invalid distance code",n.mode=BAD;break}n.offset=y,n.extra=15&g,n.mode=DISTEXT;case DISTEXT:if(n.extra){for(I=n.extra;d<I;){if(0===o)break t;o--,c+=r[s++]<<d,d+=8}n.offset+=c&(1<<n.extra)-1,c>>>=n.extra,d-=n.extra,n.back+=n.extra}if(n.offset>n.dmax){t.msg="invalid distance too far back",n.mode=BAD;break}n.mode=MATCH;case MATCH:if(0===l)break t;if(p=u-l,n.offset>p){if(p=n.offset-p,p>n.whave&&n.sane){t.msg="invalid distance too far back",n.mode=BAD;break}p>n.wnext?(p-=n.wnext,f=n.wsize-p):f=n.wnext-p,p>n.length&&(p=n.length),m=n.window}else m=i,f=a-n.offset,p=n.length;p>l&&(p=l),l-=p,n.length-=p;do{i[a++]=m[f++]}while(--p);0===n.length&&(n.mode=LEN);break;case LIT:if(0===l)break t;i[a++]=n.length,l--,n.mode=LEN;break;case CHECK:if(n.wrap){for(;d<32;){if(0===o)break t;o--,c|=r[s++]<<d,d+=8}if(u-=l,t.total_out+=u,n.total+=u,4&n.wrap&&u&&(t.adler=n.check=n.flags?crc32_1(n.check,i,u,a-u):adler32_1(n.check,i,u,a-u)),u=l,4&n.wrap&&(n.flags?c:zswap32(c))!==n.check){t.msg="incorrect data check",n.mode=BAD;break}c=0,d=0}n.mode=LENGTH;case LENGTH:if(n.wrap&&n.flags){for(;d<32;){if(0===o)break t;o--,c+=r[s++]<<d,d+=8}if(4&n.wrap&&c!==(4294967295&n.total)){t.msg="incorrect length check",n.mode=BAD;break}c=0,d=0}n.mode=DONE;case DONE:b=Z_STREAM_END$1;break t;case BAD:b=Z_DATA_ERROR$1;break t;case MEM:return Z_MEM_ERROR$1;default:return Z_STREAM_ERROR$1}return t.next_out=a,t.avail_out=l,t.next_in=s,t.avail_in=o,n.hold=c,n.bits=d,(n.wsize||u!==t.avail_out&&n.mode<BAD&&(n.mode<CHECK||e!==Z_FINISH$1))&&updatewindow(t,t.output,t.next_out,u-t.avail_out),h-=t.avail_in,u-=t.avail_out,t.total_in+=h,t.total_out+=u,n.total+=u,4&n.wrap&&u&&(t.adler=n.check=n.flags?crc32_1(n.check,i,u,t.next_out-u):adler32_1(n.check,i,u,t.next_out-u)),t.data_type=n.bits+(n.last?64:0)+(n.mode===TYPE?128:0)+(n.mode===LEN_||n.mode===COPY_?256:0),(0===h&&0===u||e===Z_FINISH$1)&&b===Z_OK$1&&(b=Z_BUF_ERROR),b},inflateEnd=t=>{if(inflateStateCheck(t))return Z_STREAM_ERROR$1;let e=t.state;return e.window&&(e.window=null),t.state=null,Z_OK$1},inflateGetHeader=(t,e)=>{if(inflateStateCheck(t))return Z_STREAM_ERROR$1;const n=t.state;return 2&n.wrap?(n.head=e,e.done=!1,Z_OK$1):Z_STREAM_ERROR$1},inflateSetDictionary=(t,e)=>{const n=e.length;let r,i,s;return inflateStateCheck(t)?Z_STREAM_ERROR$1:(r=t.state,0!==r.wrap&&r.mode!==DICT?Z_STREAM_ERROR$1:r.mode===DICT&&(i=1,i=adler32_1(i,e,n,0),i!==r.check)?Z_DATA_ERROR$1:(s=updatewindow(t,e,n,n),s?(r.mode=MEM,Z_MEM_ERROR$1):(r.havedict=1,Z_OK$1)))};var inflateReset_1=inflateReset,inflateReset2_1=inflateReset2,inflateResetKeep_1=inflateResetKeep,inflateInit_1=inflateInit,inflateInit2_1=inflateInit2,inflate_2$1=inflate$2,inflateEnd_1=inflateEnd,inflateGetHeader_1=inflateGetHeader,inflateSetDictionary_1=inflateSetDictionary,inflateInfo="pako inflate (from Nodeca project)",inflate_1$2={inflateReset:inflateReset_1,inflateReset2:inflateReset2_1,inflateResetKeep:inflateResetKeep_1,inflateInit:inflateInit_1,inflateInit2:inflateInit2_1,inflate:inflate_2$1,inflateEnd:inflateEnd_1,inflateGetHeader:inflateGetHeader_1,inflateSetDictionary:inflateSetDictionary_1,inflateInfo};function GZheader(){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}var gzheader=GZheader;const toString$2=Object.prototype.toString,{Z_NO_FLUSH,Z_FINISH,Z_OK,Z_STREAM_END,Z_NEED_DICT,Z_STREAM_ERROR,Z_DATA_ERROR,Z_MEM_ERROR}=constants$2;function Inflate$1(t){this.options=common.assign({chunkSize:65536,windowBits:15,to:""},t||{});const e=this.options;e.raw&&e.windowBits>=0&&e.windowBits<16&&(e.windowBits=-e.windowBits,0===e.windowBits&&(e.windowBits=-15)),!(e.windowBits>=0&&e.windowBits<16)||t&&t.windowBits||(e.windowBits+=32),e.windowBits>15&&e.windowBits<48&&(15&e.windowBits||(e.windowBits|=15)),this.err=0,this.msg="",this.ended=!1,this.chunks=[],this.strm=new zstream,this.strm.avail_out=0;let n=inflate_1$2.inflateInit2(this.strm,e.windowBits);if(n!==Z_OK)throw new Error(messages[n]);if(this.header=new gzheader,inflate_1$2.inflateGetHeader(this.strm,this.header),e.dictionary&&("string"==typeof e.dictionary?e.dictionary=strings.string2buf(e.dictionary):"[object ArrayBuffer]"===toString$2.call(e.dictionary)&&(e.dictionary=new Uint8Array(e.dictionary)),e.raw&&(n=inflate_1$2.inflateSetDictionary(this.strm,e.dictionary),n!==Z_OK)))throw new Error(messages[n])}function inflate$1(t,e){const n=new Inflate$1(e);if(n.push(t),n.err)throw n.msg||messages[n.err];return n.result}function inflateRaw$1(t,e){return(e=e||{}).raw=!0,inflate$1(t,e)}Inflate$1.prototype.push=function(t,e){const n=this.strm,r=this.options.chunkSize,i=this.options.dictionary;let s,a,o;if(this.ended)return!1;for(a=e===~~e?e:!0===e?Z_FINISH:Z_NO_FLUSH,n.input="[object ArrayBuffer]"===toString$2.call(t)?new Uint8Array(t):t,n.next_in=0,n.avail_in=n.input.length;;){for(0===n.avail_out&&(n.output=new Uint8Array(r),n.next_out=0,n.avail_out=r),s=inflate_1$2.inflate(n,a),s===Z_NEED_DICT&&i&&(s=inflate_1$2.inflateSetDictionary(n,i),s===Z_OK?s=inflate_1$2.inflate(n,a):s===Z_DATA_ERROR&&(s=Z_NEED_DICT));n.avail_in>0&&s===Z_STREAM_END&&n.state.wrap>0&&0!==t[n.next_in];)inflate_1$2.inflateReset(n),s=inflate_1$2.inflate(n,a);switch(s){case Z_STREAM_ERROR:case Z_DATA_ERROR:case Z_NEED_DICT:case Z_MEM_ERROR:return this.onEnd(s),this.ended=!0,!1}if(o=n.avail_out,n.next_out&&(0===n.avail_out||s===Z_STREAM_END))if("string"===this.options.to){let t=strings.utf8border(n.output,n.next_out),e=n.next_out-t,i=strings.buf2string(n.output,t);n.next_out=e,n.avail_out=r-e,e&&n.output.set(n.output.subarray(t,t+e),0),this.onData(i)}else this.onData(n.output.length===n.next_out?n.output:n.output.subarray(0,n.next_out));if(s!==Z_OK||0!==o){if(s===Z_STREAM_END)return s=inflate_1$2.inflateEnd(this.strm),this.onEnd(s),this.ended=!0,!0;if(0===n.avail_in)break}}return!0},Inflate$1.prototype.onData=function(t){this.chunks.push(t)},Inflate$1.prototype.onEnd=function(t){t===Z_OK&&(this.result="string"===this.options.to?this.chunks.join(""):common.flattenChunks(this.chunks)),this.chunks=[],this.err=t,this.msg=this.strm.msg};var Inflate_1$1=Inflate$1,inflate_2=inflate$1,inflateRaw_1$1=inflateRaw$1,ungzip$1=inflate$1,constants=constants$2,inflate_1$1={Inflate:Inflate_1$1,inflate:inflate_2,inflateRaw:inflateRaw_1$1,ungzip:ungzip$1,constants};const{Deflate,deflate,deflateRaw,gzip}=deflate_1$1,{Inflate,inflate,inflateRaw,ungzip}=inflate_1$1;var Deflate_1=Deflate,deflate_1=deflate,deflateRaw_1=deflateRaw,gzip_1=gzip,Inflate_1=Inflate,inflate_1=inflate,inflateRaw_1=inflateRaw,ungzip_1=ungzip,constants_1=constants$2,pako={Deflate:Deflate_1,deflate:deflate_1,deflateRaw:deflateRaw_1,gzip:gzip_1,Inflate:Inflate_1,inflate:inflate_1,inflateRaw:inflateRaw_1,ungzip:ungzip_1,constants:constants_1};async function request(t,e={}){const{method:n="GET",data:r,headers:i={}}=e,s={method:n,headers:_extends({"Content-Type":"application/json"},i)};if("GET"===n&&r){const e=new URLSearchParams(r).toString();t+=`${t.includes("?")?"&":"?"}${e}`}"GET"!==n&&r&&(s.body=JSON.stringify(r));try{const e=await fetch(t,s);if(!e.ok)throw{status:e.status,statusText:e.statusText,message:`HTTP error! status: ${e.status}`};return e}catch(t){if(t instanceof Error)throw{message:t.message,status:500,statusText:"Client Error"};throw t}}function XMLRequest(t){return new Promise((e,n)=>{var r;const i=new XMLHttpRequest;i.open("GET",t.url),i.responseType="arraybuffer",i.timeout=null!=(r=t.timeout)?r:6e4,i.onload=function(){4===i.readyState&&200===i.status?e([!1,i.response]):n([!0,`HTTP ${i.status} ${i.statusText}`])},i.onerror=function(){n([!0,"network error"])},i.ontimeout=function(){n([!0,`timeout after ${i.timeout}ms`])},i.onabort=function(){n([!0,"aborted"])},i.onprogress=e=>{if(e.lengthComputable){const n=Math.round(e.loaded/e.total*100);t.onProgress(n,e)}},i.send()})}var commonjsGlobal="undefined"!=typeof globalThis?globalThis:"undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof self?self:{};function createCommonjsModule(t){var e={exports:{}};return t(e,e.exports),e.exports}var md5=createCommonjsModule(function(t){!function(e){function n(t,e){var n=(65535&t)+(65535&e);return(t>>16)+(e>>16)+(n>>16)<<16|65535&n}function r(t,e,r,i,s,a){return n((o=n(n(e,t),n(i,a)))<<(l=s)|o>>>32-l,r);var o,l}function i(t,e,n,i,s,a,o){return r(e&n|~e&i,t,e,s,a,o)}function s(t,e,n,i,s,a,o){return r(e&i|n&~i,t,e,s,a,o)}function a(t,e,n,i,s,a,o){return r(e^n^i,t,e,s,a,o)}function o(t,e,n,i,s,a,o){return r(n^(e|~i),t,e,s,a,o)}function l(t,e){var r,l,c,d,h;t[e>>5]|=128<<e%32,t[14+(e+64>>>9<<4)]=e;var u=1732584193,p=-271733879,f=-1732584194,m=271733878;for(r=0;r<t.length;r+=16)l=u,c=p,d=f,h=m,u=i(u,p,f,m,t[r],7,-680876936),m=i(m,u,p,f,t[r+1],12,-389564586),f=i(f,m,u,p,t[r+2],17,606105819),p=i(p,f,m,u,t[r+3],22,-1044525330),u=i(u,p,f,m,t[r+4],7,-176418897),m=i(m,u,p,f,t[r+5],12,1200080426),f=i(f,m,u,p,t[r+6],17,-1473231341),p=i(p,f,m,u,t[r+7],22,-45705983),u=i(u,p,f,m,t[r+8],7,1770035416),m=i(m,u,p,f,t[r+9],12,-1958414417),f=i(f,m,u,p,t[r+10],17,-42063),p=i(p,f,m,u,t[r+11],22,-1990404162),u=i(u,p,f,m,t[r+12],7,1804603682),m=i(m,u,p,f,t[r+13],12,-40341101),f=i(f,m,u,p,t[r+14],17,-1502002290),u=s(u,p=i(p,f,m,u,t[r+15],22,1236535329),f,m,t[r+1],5,-165796510),m=s(m,u,p,f,t[r+6],9,-1069501632),f=s(f,m,u,p,t[r+11],14,643717713),p=s(p,f,m,u,t[r],20,-373897302),u=s(u,p,f,m,t[r+5],5,-701558691),m=s(m,u,p,f,t[r+10],9,38016083),f=s(f,m,u,p,t[r+15],14,-660478335),p=s(p,f,m,u,t[r+4],20,-405537848),u=s(u,p,f,m,t[r+9],5,568446438),m=s(m,u,p,f,t[r+14],9,-1019803690),f=s(f,m,u,p,t[r+3],14,-187363961),p=s(p,f,m,u,t[r+8],20,1163531501),u=s(u,p,f,m,t[r+13],5,-1444681467),m=s(m,u,p,f,t[r+2],9,-51403784),f=s(f,m,u,p,t[r+7],14,1735328473),u=a(u,p=s(p,f,m,u,t[r+12],20,-1926607734),f,m,t[r+5],4,-378558),m=a(m,u,p,f,t[r+8],11,-2022574463),f=a(f,m,u,p,t[r+11],16,1839030562),p=a(p,f,m,u,t[r+14],23,-35309556),u=a(u,p,f,m,t[r+1],4,-1530992060),m=a(m,u,p,f,t[r+4],11,1272893353),f=a(f,m,u,p,t[r+7],16,-155497632),p=a(p,f,m,u,t[r+10],23,-1094730640),u=a(u,p,f,m,t[r+13],4,681279174),m=a(m,u,p,f,t[r],11,-358537222),f=a(f,m,u,p,t[r+3],16,-722521979),p=a(p,f,m,u,t[r+6],23,76029189),u=a(u,p,f,m,t[r+9],4,-640364487),m=a(m,u,p,f,t[r+12],11,-421815835),f=a(f,m,u,p,t[r+15],16,530742520),u=o(u,p=a(p,f,m,u,t[r+2],23,-995338651),f,m,t[r],6,-198630844),m=o(m,u,p,f,t[r+7],10,1126891415),f=o(f,m,u,p,t[r+14],15,-1416354905),p=o(p,f,m,u,t[r+5],21,-57434055),u=o(u,p,f,m,t[r+12],6,1700485571),m=o(m,u,p,f,t[r+3],10,-1894986606),f=o(f,m,u,p,t[r+10],15,-1051523),p=o(p,f,m,u,t[r+1],21,-2054922799),u=o(u,p,f,m,t[r+8],6,1873313359),m=o(m,u,p,f,t[r+15],10,-30611744),f=o(f,m,u,p,t[r+6],15,-1560198380),p=o(p,f,m,u,t[r+13],21,1309151649),u=o(u,p,f,m,t[r+4],6,-145523070),m=o(m,u,p,f,t[r+11],10,-1120210379),f=o(f,m,u,p,t[r+2],15,718787259),p=o(p,f,m,u,t[r+9],21,-343485551),u=n(u,l),p=n(p,c),f=n(f,d),m=n(m,h);return[u,p,f,m]}function c(t){var e,n="",r=32*t.length;for(e=0;e<r;e+=8)n+=String.fromCharCode(t[e>>5]>>>e%32&255);return n}function d(t){var e,n=[];for(n[(t.length>>2)-1]=void 0,e=0;e<n.length;e+=1)n[e]=0;var r=8*t.length;for(e=0;e<r;e+=8)n[e>>5]|=(255&t.charCodeAt(e/8))<<e%32;return n}function h(t){var e,n,r="0123456789abcdef",i="";for(n=0;n<t.length;n+=1)e=t.charCodeAt(n),i+=r.charAt(e>>>4&15)+r.charAt(15&e);return i}function u(t){return unescape(encodeURIComponent(t))}function p(t){return function(t){return c(l(d(t),8*t.length))}(u(t))}function f(t,e){return function(t,e){var n,r,i=d(t),s=[],a=[];for(s[15]=a[15]=void 0,i.length>16&&(i=l(i,8*t.length)),n=0;n<16;n+=1)s[n]=909522486^i[n],a[n]=1549556828^i[n];return r=l(s.concat(d(e)),512+8*e.length),c(l(a.concat(r),640))}(u(t),u(e))}function m(t,e,n){return e?n?f(e,t):h(f(e,t)):n?p(t):h(p(t))}t.exports?t.exports=m:e.md5=m}(commonjsGlobal)});function encodeWithMd5(t){return md5(t)}function generateRequestId(t){const e=`${(()=>{try{return generateFingerprint()}catch(t){return"unknown"}})()}|${Date.now()}|${t}`;return md5(e)}function escapeNonAsciiForPythonJson(t){return t.replace(/[^\u0000-\u007E]/g,t=>`\\u${t.charCodeAt(0).toString(16).padStart(4,"0")}`)}function compareUnicodeCodePoints(t,e){const n=Array.from(t,t=>t.codePointAt(0)),r=Array.from(e,t=>t.codePointAt(0)),i=Math.min(n.length,r.length);for(let t=0;t<i;t+=1)if(n[t]!==r[t])return n[t]-r[t];return n.length-r.length}function parseUrlWithoutBase(t){try{const e=new URL(t);return{isAbsolute:!0,pathWithQuery:e.pathname+e.search}}catch(e){let n=t.trim();return n.startsWith("/")||(n="/"+n),{isAbsolute:!1,pathWithQuery:n}}}function headersNeedSign(t,e,n,r,i){const s={},a=Math.floor(Date.now()/1e3),o=parseUrlWithoutBase(r).pathWithQuery,l=function t(e){if(null==e)return e;if(Array.isArray(e))return e.map(e=>t(e));if("object"!=typeof e)return e;const n=Object.keys(e).sort(compareUnicodeCodePoints),r={};for(const i of n)r[i]=t(e[i]);return r}(i),c=escapeNonAsciiForPythonJson(JSON.stringify(l)).replace(/ /g,""),d=encodeWithMd5(`${o.toLowerCase()}${n.toLowerCase()}${c}${e}${a}`);return s["X-APP-ID"]=t,s["X-TOKEN"]=d,s["X-TIMESTAMP"]=a.toString(),{headers:s,data:l}}class CacheManager{constructor(t){this.cacheServer=t}getVideo(t){return`${this.cacheServer}/get_video?url=${encodeURIComponent(t)}`}}class ResourceManager{constructor(t){this.TAG="[ResourceManager]",this.offlineIdle=[],this.offlineCache=new Map,this.networkInfos=[],this.bg=null,this.destroyed=!1,this.progress=0,this.videoCache=new Map,this.maxCacheSize=10485760,this.maxCacheEntries=20,this.cacheCleanupInterval=null,this.isProcessingVideo=!1,this.startSessionTimer=null,this.audioOnlyMode=!1,this.downloadingVideos=new Map,this.first_load=!0,this.options=t,this.audioOnlyMode=t.audioOnlyMode||!1,this.sdk=t.sdkInstance,this.mouthShapeLib={char_info:null},this.config=t.config||{},this.resource_pack={enable_robot_expression:!1,body_data_dir:"",face_ani_char_data:"",face_ani_preload_data:"",interpolate_joints:[[4,3]]},t.cacheServer&&(this.cacheServer=new CacheManager(t.cacheServer)),this.startCacheCleanup()}getAppInfo(){return{appId:this.options.appId}}getBackgroundImage(){return new Promise((t,e)=>{try{var n,r;const e=new Image;if(e.crossOrigin="anonymous",e.src=(null==(n=this.config)?void 0:n.background_img)||"",null==(r=this.config)||!r.background_img)return;e.onload=()=>{this.bg=e,t()},e.onerror=n=>{this.sdk.onMessage({code:EErrorCode.BACKGROUND_IMAGE_LOAD_ERROR,message:"Error: 背景图片加载失败",e:{error:n,img:e}}),this.bg=null,t()}}catch(t){}})}getIsEnableRobotExpression(){var t;return null==(t=this.resource_pack)?void 0:t.enable_robot_expression}getBackgroundImageElement(){return this.bg}getConfig(){return this.config}async load(t){var e;this.destroyed=!1,null==t||t(this.progress),this.startSessionTimer&&(clearInterval(this.startSessionTimer),this.startSessionTimer=null),this.startSessionTimer=setInterval(()=>{if(this.destroyed||this.progress>=14)return clearInterval(this.startSessionTimer),void(this.startSessionTimer=null);this.progress+=1,null==t||t(this.progress)},100),this.session_request_id=generateRequestId(this.options.appId);const n=await this.startSession(),r=n;return null!=r&&r.session_id&&(this.session_id=r.session_id),this.destroyed?(window.avatarSDKLogger.warn(this.TAG,"sdk destroyed during load, aborting after startSession"),await this.stopSession("destroy_during_init"),null):n?(clearInterval(this.startSessionTimer),this.startSessionTimer=null,this.progress=15,null==t||t(this.progress),this.resource_pack=r.resource_pack,this.config=r.config,this.offlineIdle=(null==(e=r.resource_pack)?void 0:e.offline_idle)||[],!this.resource_pack||(this.audioOnlyMode||await this.loadMouthShapeLib(t),this.getBackgroundImage(),null!=(i=this.mouthShapeLib)&&i.char_info||null==r||null==(s=r.resource_pack)||!s.face_ani_char_data||this.audioOnlyMode)?r:null):(clearInterval(this.startSessionTimer),this.startSessionTimer=null,null);var i,s}async startSession(){try{const n=await this._startSession();var t,e;return null!=n&&n.verify_res&&(null==(t=(e=this.options).onStartSessionWarning)||t.call(e,n.verify_res)),n}catch(t){return null}}_startSession(){var t;if(!navigator.onLine)return this.sdk.onMessage({code:EErrorCode.NETWORK_BREAK,message:"没有网络,请联网后重试~"}),null;const e=`${this.options.gatewayServer}`,n=_extends({request_id:this.session_request_id,tag:this.options.tag,gateway_type:this.options.gateway_type},void 0!==this.options.asr_id?{asr_id:this.options.asr_id}:{},void 0!==this.options.llm_id?{llm_id:this.options.llm_id}:{},void 0!==this.options.session_speak_req_id?{session_speak_req_id:this.options.session_speak_req_id}:{},null!=(t=this.options.sessionRequestData)?t:{},{config:_extends({},this.config,{framedata_proto_version:2,walk_version:3})}),{headers:r,data:i}=headersNeedSign(this.options.appId,this.options.appSecret,"POST",e,n);return request(e,{method:"POST",data:i,headers:_extends({},r,this.options.headers)}).then(t=>t.json()).then(t=>{var e;return null!=t&&null!=(e=t.data)&&e.resource_pack?null==t?void 0:t.data:(this.sdk.onMessage({code:null==t?void 0:t.error_code,message:`Error: ${null==t?void 0:t.error_code}, ${null==t?void 0:t.error_reason}`}),null)}).catch(t=>(this.sdk.onMessage({code:EErrorCode.START_SESSION_ERROR,message:"Error: 启动会话失败",e:t}),null))}async stopSession(t){try{const e=`${this.options.gatewayServer}`;if(!this.session_id&&!this.session_request_id)return;const n={stop_reason:t};this.session_id&&(n.session_id=this.session_id),this.session_request_id&&(n.request_id=this.session_request_id);const{headers:r,data:i}=headersNeedSign(this.options.appId,this.options.appSecret,"DELETE",e,n),s=await request(e,{method:"DELETE",data:i,headers:_extends({},r,this.options.headers)});return await s.json()}catch(t){this.sdk.onMessage({code:EErrorCode.STOP_SESSION_ERROR,message:"Error: 停止会话失败",e:t})}}async loadMouthShapeLib(t){try{var e,n;if(!this.resource_pack.face_ani_char_data)return this.progress+=60,void(null==t||t(this.progress));let s=null,a=null,o="",l=0,c=0,d=0,h=0;const u=()=>(e,n)=>{var r,i;if(!n)return;const s=performance.now(),a=s-d,o=n.loaded-h;null==(r=(i=this.options).onNetworkInfo)||r.call(i,{rtt:a,downlink:a>0&&o>0?8*o/(a/1e3)/1e6:0,networkStatus:navigator.onLine}),h=n.loaded,d=s,null==t||t(this.progress+.65*e)};try{const t=`${this.resource_pack.face_ani_char_data}.gz`;o=t,c=performance.now(),d=c,h=0;const[,e]=await XMLRequest({url:t,onProgress:u()}),n=pako.ungzip(new Uint8Array(e)),r=new ArrayBuffer(n.byteLength);new Uint8Array(r).set(n),s=r}catch(t){a=t,s=null}if(!s)try{const t=this.resource_pack.face_ani_char_data;o=t,c=performance.now(),d=c,h=0;const[,e]=await XMLRequest({url:t,onProgress:u()});s=e}catch(t){var r,i;return this.first_load&&(this.first_load=!1,this.stopSession("char_bin_load_error")),void(null==(r=(i=this.sdk).onMessage)||r.call(i,{code:EErrorCode.FACE_BIN_LOAD_ERROR,message:"表情数据加载失败(.gz 和 bin 均失败)",e:{gzError:a,binError:t}}))}const p=performance.now()-c;null==(e=(n=this.options).onNetworkInfo)||e.call(n,{rtt:p,downlink:l>0&&p>0?8*l/(p/1e3)/1e6:0,networkStatus:navigator.onLine}),this.mouthShapeLib={char_info:new IBRAnimationGeneratorCharInfo_NN(s,{blendshapeMap:this.resource_pack.blendshape_map||[]})},this.progress+=65,null==t||t(this.progress)}catch(t){var s,a;this.first_load&&(this.first_load=!1,this.stopSession("char_bin_load_error")),null==(s=(a=this.sdk).onMessage)||s.call(a,{code:EErrorCode.FACE_BIN_LOAD_ERROR,message:"表情数据加载失败,请检查文件是否正确",e:t})}}getMouthShapeLib(){return this.mouthShapeLib}getVideoUrl(t){if(!this.resource_pack.body_data_dir)return"";if(!t)return this.first_load&&(this.first_load=!1,this.stopSession("no_video_name_error")),this.sdk.onMessage({code:EErrorCode.INVALID_BODY_NAME,message:"Error: 视频地址获取失败",e:t}),"";const e=`${this.resource_pack.body_data_dir}${t}.mp4`;var n;return this.cacheServer?null==(n=this.cacheServer)?void 0:n.getVideo(e):e}async preloadVideo(t){if(!this.videoCache.has(t))return this.loadVideo(t)}async loadVideo(t){const e=this.videoCache.get(t)||this.offlineCache.get(t);if(e){if(e.data)return this.updateCacheAccess(t),e.data;window.avatarSDKLogger.warn(this.TAG,`发现无效缓存条目: ${t},正在删除`),this.videoCache.delete(t)}if(this.downloadingVideos.has(t))try{return await this.downloadingVideos.get(t)}catch(e){throw this.downloadingVideos.delete(t),window.avatarSDKLogger.warn(this.TAG,`${t} 视频下载失败,从下载列表移除`),e}this.isProcessingVideo=!0;const n=this.downloadVideo(t);this.downloadingVideos.set(t,n);try{return await n}finally{this.downloadingVideos.delete(t),this.isProcessingVideo=!1}}async downloadVideo(t){const e=this.getVideoUrl(t);if(e)try{const{response:n,arrayBuffer:r}=await this._fetchVideo(e);return n.ok?(this.addToCache(t,r),r):(this.first_load&&(this.first_load=!1,this.stopSession("load_video_error")),void this.sdk.onMessage({code:EErrorCode.VIDEO_DOWNLOAD_ERROR,message:`Error: ${t} 视频下载失败`,e:{name:t,url:e,res:n}}))}catch(n){return void this.sdk.onMessage({code:EErrorCode.VIDEO_DOWNLOAD_ERROR,message:`Error: ${t} 视频下载失败`,e:{name:t,url:e,error:n}})}}async _fetchVideo(t){if(this.networkInfos.length>=4){var e,n;const t=this.networkInfos.reduce((t,e)=>t+e.rtt,0)/this.networkInfos.length,r=this.networkInfos.reduce((t,e)=>t+e.downlink,0)/this.networkInfos.length;null==(e=(n=this.options).onNetworkInfo)||e.call(n,{rtt:t,downlink:r,networkStatus:navigator.onLine}),this.networkInfos.length=0}const r=performance.now(),i=await fetch(t),s=parseFloat(i.headers.get("Content-Length")||"0"),a=performance.now(),o=await i.arrayBuffer(),l=a-r,c={rtt:l,downlink:8*s/(l/1e3*1e6),networkStatus:navigator.onLine};return this.networkInfos.push(c),{response:i,arrayBuffer:o}}addToCache(t,e){const n=Date.now();let r=0;for(const t of this.videoCache.values())r+=t.data.byteLength;if(r+e.byteLength>this.maxCacheSize||this.videoCache.size>=this.maxCacheEntries){this.cleanupCache(),r=0;for(const t of this.videoCache.values())r+=t.data.byteLength;if(r+e.byteLength>this.maxCacheSize&&e.byteLength>.5*this.maxCacheSize)return void window.avatarSDKLogger.warn(this.TAG,`视频文件过大(${(e.byteLength/1024/1024).toFixed(2)}MB),跳过缓存: ${t}`);if(r+e.byteLength>this.maxCacheSize){const t=.5*this.maxCacheSize,e=Array.from(this.videoCache.entries()).sort((t,e)=>t[1].lastAccessTime-e[1].lastAccessTime);for(const[n,i]of e){if(r<=t)break;this.videoCache.delete(n),r-=i.data.byteLength}}}this.videoCache.set(t,{data:e,lastAccessTime:n,accessCount:1})}startCacheCleanup(){this.cacheCleanupInterval=setInterval(()=>{this.cleanupCache()},3e5)}cleanupCache(){if(this.isProcessingVideo)return;const t=Date.now(),e=Array.from(this.videoCache.entries()).sort((t,e)=>t[1].lastAccessTime-e[1].lastAccessTime);let n=0;const r=[];for(const[t,e]of this.videoCache.entries())n+=e.data.byteLength;for(const[i,s]of e)t-s.lastAccessTime>6e5&&(r.push(i),n-=s.data.byteLength);if(n>this.maxCacheSize||this.videoCache.size>this.maxCacheEntries)for(const[t,i]of e)if(!r.includes(t)&&(r.push(t),n-=i.data.byteLength,this.videoCache.size-r.length<=2||n<=.8*this.maxCacheSize&&this.videoCache.size-r.length<=.8*this.maxCacheEntries))break;for(const t of r)this.videoCache.delete(t)}updateCacheAccess(t){const e=this.videoCache.get(t);e&&(e.lastAccessTime=Date.now(),e.accessCount++)}clearAllCache(){this.videoCache.clear()}_getOfflineIdle(){return this.offlineIdle}_getSessionId(){return this.session_id||""}async _reload(){var t;const e=await this.startSession();if(!e)return null;const n=e;return this.session_id=null==n?void 0:n.session_id,this.destroyed?(await this.stopSession("destroy_during_reload"),null):(this.resource_pack=n.resource_pack,this.config=n.config,this.offlineIdle=(null==(t=n.resource_pack)?void 0:t.offline_idle)||[],this.resource_pack&&this.getBackgroundImage(),n)}async _setOfflineCache(){if(!this.offlineIdle||0===this.offlineIdle.length)return;this.offlineCache.clear();const t=this.offlineIdle.map(t=>t.n);for(const e of t)try{await this._runOfflineCache(e)}catch(t){}}async _runOfflineCache(t){const e=this.getVideoUrl(t);if(e)return this._fetchVideo(e).then(({arrayBuffer:e})=>{this.offlineCache.set(t,{data:e})})}destroy(){this.destroyed=!0,this.cacheCleanupInterval&&(clearInterval(this.cacheCleanupInterval),this.cacheCleanupInterval=null),this.clearAllCache(),this.downloadingVideos.clear(),this.bg&&(this.bg=null),this.progress=0,this.session_id=void 0,this.session_request_id=void 0}}var msgpack_min=createCommonjsModule(function(t,e){t.exports=function(t){var e={};function n(r){if(e[r])return e[r].exports;var i=e[r]={i:r,l:!1,exports:{}};return t[r].call(i.exports,i,i.exports,n),i.l=!0,i.exports}return n.m=t,n.c=e,n.d=function(t,e,r){n.o(t,e)||Object.defineProperty(t,e,{enumerable:!0,get:r})},n.r=function(t){"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(t,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(t,"__esModule",{value:!0})},n.t=function(t,e){if(1&e&&(t=n(t)),8&e)return t;if(4&e&&"object"==typeof t&&t&&t.__esModule)return t;var r=Object.create(null);if(n.r(r),Object.defineProperty(r,"default",{enumerable:!0,value:t}),2&e&&"string"!=typeof t)for(var i in t)n.d(r,i,function(e){return t[e]}.bind(null,i));return r},n.n=function(t){var e=t&&t.__esModule?function(){return t.default}:function(){return t};return n.d(e,"a",e),e},n.o=function(t,e){return Object.prototype.hasOwnProperty.call(t,e)},n.p="",n(n.s=0)}([function(t,e,n){n.r(e),n.d(e,"encode",function(){return R}),n.d(e,"decode",function(){return z}),n.d(e,"decodeAsync",function(){return K}),n.d(e,"decodeArrayStream",function(){return X}),n.d(e,"decodeStream",function(){return q}),n.d(e,"Decoder",function(){return M}),n.d(e,"Encoder",function(){return x}),n.d(e,"ExtensionCodec",function(){return b}),n.d(e,"ExtData",function(){return p}),n.d(e,"EXT_TIMESTAMP",function(){return _}),n.d(e,"encodeDateToTimeSpec",function(){return y}),n.d(e,"encodeTimeSpecToTimestamp",function(){return g}),n.d(e,"decodeTimestampToTimeSpec",function(){return A}),n.d(e,"encodeTimestampExtension",function(){return S}),n.d(e,"decodeTimestampExtension",function(){return v});var r=function(t,e){var n="function"==typeof Symbol&&t[Symbol.iterator];if(!n)return t;var r,i,s=n.call(t),a=[];try{for(;(void 0===e||e-- >0)&&!(r=s.next()).done;)a.push(r.value)}catch(t){i={error:t}}finally{try{r&&!r.done&&(n=s.return)&&n.call(s)}finally{if(i)throw i.error}}return a},i=function(){for(var t=[],e=0;e<arguments.length;e++)t=t.concat(r(arguments[e]));return t},s="undefined"!=typeof process&&"undefined"!=typeof TextEncoder&&"undefined"!=typeof TextDecoder;function a(t){for(var e=t.length,n=0,r=0;r<e;){var i=t.charCodeAt(r++);if(4294967168&i)if(4294965248&i){if(i>=55296&&i<=56319&&r<e){var s=t.charCodeAt(r);56320==(64512&s)&&(++r,i=((1023&i)<<10)+(1023&s)+65536)}n+=4294901760&i?4:3}else n+=2;else n++}return n}var o=s?new TextEncoder:void 0,l="undefined"!=typeof process?200:0,c=(null==o?void 0:o.encodeInto)?function(t,e,n){o.encodeInto(t,e.subarray(n))}:function(t,e,n){e.set(o.encode(t),n)};function d(t,e,n){for(var r=e,s=r+n,a=[],o="";r<s;){var l=t[r++];if(128&l)if(192==(224&l)){var c=63&t[r++];a.push((31&l)<<6|c)}else if(224==(240&l)){c=63&t[r++];var d=63&t[r++];a.push((31&l)<<12|c<<6|d)}else if(240==(248&l)){var h=(7&l)<<18|(c=63&t[r++])<<12|(d=63&t[r++])<<6|63&t[r++];h>65535&&(a.push((h-=65536)>>>10&1023|55296),h=56320|1023&h),a.push(h)}else a.push(l);else a.push(l);a.length>=4096&&(o+=String.fromCharCode.apply(String,i(a)),a.length=0)}return a.length>0&&(o+=String.fromCharCode.apply(String,i(a))),o}var h=s?new TextDecoder:null,u="undefined"!=typeof process?200:0,p=function(t,e){this.type=t,this.data=e};function f(t,e,n){var r=Math.floor(n/4294967296),i=n;t.setUint32(e,r),t.setUint32(e+4,i)}function m(t,e){return 4294967296*t.getInt32(e)+t.getUint32(e+4)}var _=-1;function g(t){var e,n=t.sec,r=t.nsec;if(n>=0&&r>=0&&n<=17179869183){if(0===r&&n<=4294967295){var i=new Uint8Array(4);return(e=new DataView(i.buffer)).setUint32(0,n),i}var s=n/4294967296,a=4294967295&n;return i=new Uint8Array(8),(e=new DataView(i.buffer)).setUint32(0,r<<2|3&s),e.setUint32(4,a),i}return i=new Uint8Array(12),(e=new DataView(i.buffer)).setUint32(0,r),f(e,4,n),i}function y(t){var e=t.getTime(),n=Math.floor(e/1e3),r=1e6*(e-1e3*n),i=Math.floor(r/1e9);return{sec:n+i,nsec:r-1e9*i}}function S(t){return t instanceof Date?g(y(t)):null}function A(t){var e=new DataView(t.buffer,t.byteOffset,t.byteLength);switch(t.byteLength){case 4:return{sec:e.getUint32(0),nsec:0};case 8:var n=e.getUint32(0);return{sec:4294967296*(3&n)+e.getUint32(4),nsec:n>>>2};case 12:return{sec:m(e,4),nsec:e.getUint32(0)};default:throw new Error("Unrecognized data size for timestamp: "+t.length)}}function v(t){var e=A(t);return new Date(1e3*e.sec+e.nsec/1e6)}var E={type:_,encode:S,decode:v},b=function(){function t(){this.builtInEncoders=[],this.builtInDecoders=[],this.encoders=[],this.decoders=[],this.register(E)}return t.prototype.register=function(t){var e=t.type,n=t.encode,r=t.decode;if(e>=0)this.encoders[e]=n,this.decoders[e]=r;else{var i=1+e;this.builtInEncoders[i]=n,this.builtInDecoders[i]=r}},t.prototype.tryToEncode=function(t,e){for(var n=0;n<this.builtInEncoders.length;n++)if(null!=(r=this.builtInEncoders[n])&&null!=(i=r(t,e)))return new p(-1-n,i);for(n=0;n<this.encoders.length;n++){var r,i;if(null!=(r=this.encoders[n])&&null!=(i=r(t,e)))return new p(n,i)}return t instanceof p?t:null},t.prototype.decode=function(t,e,n){var r=e<0?this.builtInDecoders[-1-e]:this.decoders[e];return r?r(t,e,n):new p(e,t)},t.defaultCodec=new t,t}();function T(t){return t instanceof Uint8Array?t:ArrayBuffer.isView(t)?new Uint8Array(t.buffer,t.byteOffset,t.byteLength):t instanceof ArrayBuffer?new Uint8Array(t):Uint8Array.from(t)}var w=function(t){var e="function"==typeof Symbol&&Symbol.iterator,n=e&&t[e],r=0;if(n)return n.call(t);if(t&&"number"==typeof t.length)return{next:function(){return t&&r>=t.length&&(t=void 0),{value:t&&t[r++],done:!t}}};throw new TypeError(e?"Object is not iterable.":"Symbol.iterator is not defined.")},x=function(){function t(t,e,n,r,i,s,a){void 0===t&&(t=b.defaultCodec),void 0===n&&(n=100),void 0===r&&(r=2048),void 0===i&&(i=!1),void 0===s&&(s=!1),void 0===a&&(a=!1),this.extensionCodec=t,this.context=e,this.maxDepth=n,this.initialBufferSize=r,this.sortKeys=i,this.forceFloat32=s,this.ignoreUndefined=a,this.pos=0,this.view=new DataView(new ArrayBuffer(this.initialBufferSize)),this.bytes=new Uint8Array(this.view.buffer)}return t.prototype.encode=function(t,e){if(e>this.maxDepth)throw new Error("Too deep objects in depth "+e);null==t?this.encodeNil():"boolean"==typeof t?this.encodeBoolean(t):"number"==typeof t?this.encodeNumber(t):"string"==typeof t?this.encodeString(t):this.encodeObject(t,e)},t.prototype.getUint8Array=function(){return this.bytes.subarray(0,this.pos)},t.prototype.ensureBufferSizeToWrite=function(t){var e=this.pos+t;this.view.byteLength<e&&this.resizeBuffer(2*e)},t.prototype.resizeBuffer=function(t){var e=new ArrayBuffer(t),n=new Uint8Array(e),r=new DataView(e);n.set(this.bytes),this.view=r,this.bytes=n},t.prototype.encodeNil=function(){this.writeU8(192)},t.prototype.encodeBoolean=function(t){this.writeU8(!1===t?194:195)},t.prototype.encodeNumber=function(t){Number.isSafeInteger(t)?t>=0?t<128?this.writeU8(t):t<256?(this.writeU8(204),this.writeU8(t)):t<65536?(this.writeU8(205),this.writeU16(t)):t<4294967296?(this.writeU8(206),this.writeU32(t)):(this.writeU8(207),this.writeU64(t)):t>=-32?this.writeU8(224|t+32):t>=-128?(this.writeU8(208),this.writeI8(t)):t>=-32768?(this.writeU8(209),this.writeI16(t)):t>=-2147483648?(this.writeU8(210),this.writeI32(t)):(this.writeU8(211),this.writeI64(t)):this.forceFloat32?(this.writeU8(202),this.writeF32(t)):(this.writeU8(203),this.writeF64(t))},t.prototype.writeStringHeader=function(t){if(t<32)this.writeU8(160+t);else if(t<256)this.writeU8(217),this.writeU8(t);else if(t<65536)this.writeU8(218),this.writeU16(t);else{if(!(t<4294967296))throw new Error("Too long string: "+t+" bytes in UTF-8");this.writeU8(219),this.writeU32(t)}},t.prototype.encodeString=function(t){if(s&&t.length>l){var e=a(t);this.ensureBufferSizeToWrite(5+e),this.writeStringHeader(e),c(t,this.bytes,this.pos),this.pos+=e}else e=a(t),this.ensureBufferSizeToWrite(5+e),this.writeStringHeader(e),function(t,e,n){for(var r=t.length,i=n,s=0;s<r;){var a=t.charCodeAt(s++);if(4294967168&a){if(4294965248&a){if(a>=55296&&a<=56319&&s<r){var o=t.charCodeAt(s);56320==(64512&o)&&(++s,a=((1023&a)<<10)+(1023&o)+65536)}4294901760&a?(e[i++]=a>>18&7|240,e[i++]=a>>12&63|128,e[i++]=a>>6&63|128):(e[i++]=a>>12&15|224,e[i++]=a>>6&63|128)}else e[i++]=a>>6&31|192;e[i++]=63&a|128}else e[i++]=a}}(t,this.bytes,this.pos),this.pos+=e},t.prototype.encodeObject=function(t,e){var n=this.extensionCodec.tryToEncode(t,this.context);if(null!=n)this.encodeExtension(n);else if(Array.isArray(t))this.encodeArray(t,e);else if(ArrayBuffer.isView(t))this.encodeBinary(t);else{if("object"!=typeof t)throw new Error("Unrecognized object: "+Object.prototype.toString.apply(t));this.encodeMap(t,e)}},t.prototype.encodeBinary=function(t){var e=t.byteLength;if(e<256)this.writeU8(196),this.writeU8(e);else if(e<65536)this.writeU8(197),this.writeU16(e);else{if(!(e<4294967296))throw new Error("Too large binary: "+e);this.writeU8(198),this.writeU32(e)}var n=T(t);this.writeU8a(n)},t.prototype.encodeArray=function(t,e){var n,r,i=t.length;if(i<16)this.writeU8(144+i);else if(i<65536)this.writeU8(220),this.writeU16(i);else{if(!(i<4294967296))throw new Error("Too large array: "+i);this.writeU8(221),this.writeU32(i)}try{for(var s=w(t),a=s.next();!a.done;a=s.next())this.encode(a.value,e+1)}catch(t){n={error:t}}finally{try{a&&!a.done&&(r=s.return)&&r.call(s)}finally{if(n)throw n.error}}},t.prototype.countWithoutUndefined=function(t,e){var n,r,i=0;try{for(var s=w(e),a=s.next();!a.done;a=s.next())void 0!==t[a.value]&&i++}catch(t){n={error:t}}finally{try{a&&!a.done&&(r=s.return)&&r.call(s)}finally{if(n)throw n.error}}return i},t.prototype.encodeMap=function(t,e){var n,r,i=Object.keys(t);this.sortKeys&&i.sort();var s=this.ignoreUndefined?this.countWithoutUndefined(t,i):i.length;if(s<16)this.writeU8(128+s);else if(s<65536)this.writeU8(222),this.writeU16(s);else{if(!(s<4294967296))throw new Error("Too large map object: "+s);this.writeU8(223),this.writeU32(s)}try{for(var a=w(i),o=a.next();!o.done;o=a.next()){var l=o.value,c=t[l];this.ignoreUndefined&&void 0===c||(this.encodeString(l),this.encode(c,e+1))}}catch(t){n={error:t}}finally{try{o&&!o.done&&(r=a.return)&&r.call(a)}finally{if(n)throw n.error}}},t.prototype.encodeExtension=function(t){var e=t.data.length;if(1===e)this.writeU8(212);else if(2===e)this.writeU8(213);else if(4===e)this.writeU8(214);else if(8===e)this.writeU8(215);else if(16===e)this.writeU8(216);else if(e<256)this.writeU8(199),this.writeU8(e);else if(e<65536)this.writeU8(200),this.writeU16(e);else{if(!(e<4294967296))throw new Error("Too large extension object: "+e);this.writeU8(201),this.writeU32(e)}this.writeI8(t.type),this.writeU8a(t.data)},t.prototype.writeU8=function(t){this.ensureBufferSizeToWrite(1),this.view.setUint8(this.pos,t),this.pos++},t.prototype.writeU8a=function(t){var e=t.length;this.ensureBufferSizeToWrite(e),this.bytes.set(t,this.pos),this.pos+=e},t.prototype.writeI8=function(t){this.ensureBufferSizeToWrite(1),this.view.setInt8(this.pos,t),this.pos++},t.prototype.writeU16=function(t){this.ensureBufferSizeToWrite(2),this.view.setUint16(this.pos,t),this.pos+=2},t.prototype.writeI16=function(t){this.ensureBufferSizeToWrite(2),this.view.setInt16(this.pos,t),this.pos+=2},t.prototype.writeU32=function(t){this.ensureBufferSizeToWrite(4),this.view.setUint32(this.pos,t),this.pos+=4},t.prototype.writeI32=function(t){this.ensureBufferSizeToWrite(4),this.view.setInt32(this.pos,t),this.pos+=4},t.prototype.writeF32=function(t){this.ensureBufferSizeToWrite(4),this.view.setFloat32(this.pos,t),this.pos+=4},t.prototype.writeF64=function(t){this.ensureBufferSizeToWrite(8),this.view.setFloat64(this.pos,t),this.pos+=8},t.prototype.writeU64=function(t){this.ensureBufferSizeToWrite(8),function(t,e,n){var r=n;t.setUint32(e,n/4294967296),t.setUint32(e+4,r)}(this.view,this.pos,t),this.pos+=8},t.prototype.writeI64=function(t){this.ensureBufferSizeToWrite(8),f(this.view,this.pos,t),this.pos+=8},t}(),I={};function R(t,e){void 0===e&&(e=I);var n=new x(e.extensionCodec,e.context,e.maxDepth,e.initialBufferSize,e.sortKeys,e.forceFloat32,e.ignoreUndefined);return n.encode(t,1),n.getUint8Array()}function C(t){return(t<0?"-":"")+"0x"+Math.abs(t).toString(16).padStart(2,"0")}var B=function(){function t(t,e){void 0===t&&(t=16),void 0===e&&(e=16),this.maxKeyLength=t,this.maxLengthPerKey=e,this.caches=[];for(var n=0;n<this.maxKeyLength;n++)this.caches.push([])}return t.prototype.canBeCached=function(t){return t>0&&t<=this.maxKeyLength},t.prototype.get=function(t,e,n){var r=this.caches[n-1],i=r.length;t:for(var s=0;s<i;s++){for(var a=r[s],o=a.bytes,l=0;l<n;l++)if(o[l]!==t[e+l])continue t;return a.value}return null},t.prototype.store=function(t,e){var n=this.caches[t.length-1],r={bytes:t,value:e};n.length>=this.maxLengthPerKey?n[Math.random()*n.length|0]=r:n.push(r)},t.prototype.decode=function(t,e,n){var r=this.get(t,e,n);if(null!=r)return r;var i=d(t,e,n),s=Uint8Array.prototype.slice.call(t,e,e+n);return this.store(s,i),i},t}(),D=function(t,e){var n,r,i,s,a={label:0,sent:function(){if(1&i[0])throw i[1];return i[1]},trys:[],ops:[]};return s={next:o(0),throw:o(1),return:o(2)},"function"==typeof Symbol&&(s[Symbol.iterator]=function(){return this}),s;function o(s){return function(o){return function(s){if(n)throw new TypeError("Generator is already executing.");for(;a;)try{if(n=1,r&&(i=2&s[0]?r.return:s[0]?r.throw||((i=r.return)&&i.call(r),0):r.next)&&!(i=i.call(r,s[1])).done)return i;switch(r=0,i&&(s=[2&s[0],i.value]),s[0]){case 0:case 1:i=s;break;case 4:return a.label++,{value:s[1],done:!1};case 5:a.label++,r=s[1],s=[0];continue;case 7:s=a.ops.pop(),a.trys.pop();continue;default:if(!((i=(i=a.trys).length>0&&i[i.length-1])||6!==s[0]&&2!==s[0])){a=0;continue}if(3===s[0]&&(!i||s[1]>i[0]&&s[1]<i[3])){a.label=s[1];break}if(6===s[0]&&a.label<i[1]){a.label=i[1],i=s;break}if(i&&a.label<i[2]){a.label=i[2],a.ops.push(s);break}i[2]&&a.ops.pop(),a.trys.pop();continue}s=e.call(t,a)}catch(t){s=[6,t],r=0}finally{n=i=0}if(5&s[0])throw s[1];return{value:s[0]?s[1]:void 0,done:!0}}([s,o])}}},P=function(t){if(!Symbol.asyncIterator)throw new TypeError("Symbol.asyncIterator is not defined.");var e,n=t[Symbol.asyncIterator];return n?n.call(t):(t="function"==typeof __values?__values(t):t[Symbol.iterator](),e={},r("next"),r("throw"),r("return"),e[Symbol.asyncIterator]=function(){return this},e);function r(n){e[n]=t[n]&&function(e){return new Promise(function(r,i){!function(t,e,n,r){Promise.resolve(r).then(function(e){t({value:e,done:n})},e)}(r,i,(e=t[n](e)).done,e.value)})}}},k=function(t){return this instanceof k?(this.v=t,this):new k(t)},O=new DataView(new ArrayBuffer(0)),U=new Uint8Array(O.buffer),N=function(){try{O.getInt8(0)}catch(t){return t.constructor}throw new Error("never reached")}(),L=new N("Insufficient data"),F=new B,M=function(){function t(t,e,n,r,i,s,a,o){void 0===t&&(t=b.defaultCodec),void 0===n&&(n=4294967295),void 0===r&&(r=4294967295),void 0===i&&(i=4294967295),void 0===s&&(s=4294967295),void 0===a&&(a=4294967295),void 0===o&&(o=F),this.extensionCodec=t,this.context=e,this.maxStrLength=n,this.maxBinLength=r,this.maxArrayLength=i,this.maxMapLength=s,this.maxExtLength=a,this.cachedKeyDecoder=o,this.totalPos=0,this.pos=0,this.view=O,this.bytes=U,this.headByte=-1,this.stack=[]}return t.prototype.setBuffer=function(t){this.bytes=T(t),this.view=function(t){if(t instanceof ArrayBuffer)return new DataView(t);var e=T(t);return new DataView(e.buffer,e.byteOffset,e.byteLength)}(this.bytes),this.pos=0},t.prototype.appendBuffer=function(t){if(-1!==this.headByte||this.hasRemaining()){var e=this.bytes.subarray(this.pos),n=T(t),r=new Uint8Array(e.length+n.length);r.set(e),r.set(n,e.length),this.setBuffer(r)}else this.setBuffer(t)},t.prototype.hasRemaining=function(t){return void 0===t&&(t=1),this.view.byteLength-this.pos>=t},t.prototype.createNoExtraBytesError=function(t){return new RangeError("Extra "+(this.view.byteLength-this.pos)+" byte(s) found at buffer["+t+"]")},t.prototype.decodeSingleSync=function(){var t=this.decodeSync();if(this.hasRemaining())throw this.createNoExtraBytesError(this.pos);return t},t.prototype.decodeSingleAsync=function(t){var e,n,r,i;return function(t,e,n,r){return new(n||(n=Promise))(function(e,i){function s(t){try{o(r.next(t))}catch(t){i(t)}}function a(t){try{o(r.throw(t))}catch(t){i(t)}}function o(t){var r;t.done?e(t.value):(r=t.value,r instanceof n?r:new n(function(t){t(r)})).then(s,a)}o((r=r.apply(t,[])).next())})}(this,0,void 0,function(){var s,a,o,l,c,d,h,u;return D(this,function(p){switch(p.label){case 0:s=!1,p.label=1;case 1:p.trys.push([1,6,7,12]),e=P(t),p.label=2;case 2:return[4,e.next()];case 3:if((n=p.sent()).done)return[3,5];if(o=n.value,s)throw this.createNoExtraBytesError(this.totalPos);this.appendBuffer(o);try{a=this.decodeSync(),s=!0}catch(t){if(!(t instanceof N))throw t}this.totalPos+=this.pos,p.label=4;case 4:return[3,2];case 5:return[3,12];case 6:return l=p.sent(),r={error:l},[3,12];case 7:return p.trys.push([7,,10,11]),n&&!n.done&&(i=e.return)?[4,i.call(e)]:[3,9];case 8:p.sent(),p.label=9;case 9:return[3,11];case 10:if(r)throw r.error;return[7];case 11:return[7];case 12:if(s){if(this.hasRemaining())throw this.createNoExtraBytesError(this.totalPos);return[2,a]}throw d=(c=this).headByte,h=c.pos,u=c.totalPos,new RangeError("Insufficient data in parcing "+C(d)+" at "+u+" ("+h+" in the current buffer)")}})})},t.prototype.decodeArrayStream=function(t){return this.decodeMultiAsync(t,!0)},t.prototype.decodeStream=function(t){return this.decodeMultiAsync(t,!1)},t.prototype.decodeMultiAsync=function(t,e){return function(t,e,n){if(!Symbol.asyncIterator)throw new TypeError("Symbol.asyncIterator is not defined.");var r,i=n.apply(t,e||[]),s=[];return r={},a("next"),a("throw"),a("return"),r[Symbol.asyncIterator]=function(){return this},r;function a(t){i[t]&&(r[t]=function(e){return new Promise(function(n,r){s.push([t,e,n,r])>1||o(t,e)})})}function o(t,e){try{(n=i[t](e)).value instanceof k?Promise.resolve(n.value.v).then(l,c):d(s[0][2],n)}catch(t){d(s[0][3],t)}var n}function l(t){o("next",t)}function c(t){o("throw",t)}function d(t,e){t(e),s.shift(),s.length&&o(s[0][0],s[0][1])}}(this,arguments,function(){var n,r,i,s,a,o,l,c,d;return D(this,function(h){switch(h.label){case 0:n=e,r=-1,h.label=1;case 1:h.trys.push([1,13,14,19]),i=P(t),h.label=2;case 2:return[4,k(i.next())];case 3:if((s=h.sent()).done)return[3,12];if(a=s.value,e&&0===r)throw this.createNoExtraBytesError(this.totalPos);this.appendBuffer(a),n&&(r=this.readArraySize(),n=!1,this.complete()),h.label=4;case 4:h.trys.push([4,9,,10]),h.label=5;case 5:return[4,k(this.decodeSync())];case 6:return[4,h.sent()];case 7:return h.sent(),0==--r?[3,8]:[3,5];case 8:return[3,10];case 9:if(!((o=h.sent())instanceof N))throw o;return[3,10];case 10:this.totalPos+=this.pos,h.label=11;case 11:return[3,2];case 12:return[3,19];case 13:return l=h.sent(),c={error:l},[3,19];case 14:return h.trys.push([14,,17,18]),s&&!s.done&&(d=i.return)?[4,k(d.call(i))]:[3,16];case 15:h.sent(),h.label=16;case 16:return[3,18];case 17:if(c)throw c.error;return[7];case 18:return[7];case 19:return[2]}})})},t.prototype.decodeSync=function(){t:for(;;){var t=this.readHeadByte(),e=void 0;if(t>=224)e=t-256;else if(t<192)if(t<128)e=t;else if(t<144){if(0!=(r=t-128)){this.pushMapState(r),this.complete();continue t}e={}}else if(t<160){if(0!=(r=t-144)){this.pushArrayState(r),this.complete();continue t}e=[]}else{var n=t-160;e=this.decodeUtf8String(n,0)}else if(192===t)e=null;else if(194===t)e=!1;else if(195===t)e=!0;else if(202===t)e=this.readF32();else if(203===t)e=this.readF64();else if(204===t)e=this.readU8();else if(205===t)e=this.readU16();else if(206===t)e=this.readU32();else if(207===t)e=this.readU64();else if(208===t)e=this.readI8();else if(209===t)e=this.readI16();else if(210===t)e=this.readI32();else if(211===t)e=this.readI64();else if(217===t)n=this.lookU8(),e=this.decodeUtf8String(n,1);else if(218===t)n=this.lookU16(),e=this.decodeUtf8String(n,2);else if(219===t)n=this.lookU32(),e=this.decodeUtf8String(n,4);else if(220===t){if(0!==(r=this.readU16())){this.pushArrayState(r),this.complete();continue t}e=[]}else if(221===t){if(0!==(r=this.readU32())){this.pushArrayState(r),this.complete();continue t}e=[]}else if(222===t){if(0!==(r=this.readU16())){this.pushMapState(r),this.complete();continue t}e={}}else if(223===t){if(0!==(r=this.readU32())){this.pushMapState(r),this.complete();continue t}e={}}else if(196===t){var r=this.lookU8();e=this.decodeBinary(r,1)}else if(197===t)r=this.lookU16(),e=this.decodeBinary(r,2);else if(198===t)r=this.lookU32(),e=this.decodeBinary(r,4);else if(212===t)e=this.decodeExtension(1,0);else if(213===t)e=this.decodeExtension(2,0);else if(214===t)e=this.decodeExtension(4,0);else if(215===t)e=this.decodeExtension(8,0);else if(216===t)e=this.decodeExtension(16,0);else if(199===t)r=this.lookU8(),e=this.decodeExtension(r,1);else if(200===t)r=this.lookU16(),e=this.decodeExtension(r,2);else{if(201!==t)throw new Error("Unrecognized type byte: "+C(t));r=this.lookU32(),e=this.decodeExtension(r,4)}this.complete();for(var i=this.stack;i.length>0;){var s=i[i.length-1];if(0===s.type){if(s.array[s.position]=e,s.position++,s.position!==s.size)continue t;i.pop(),e=s.array}else{if(1===s.type){if("string"!=(a=typeof e)&&"number"!==a)throw new Error("The type of key must be string or number but "+typeof e);s.key=e,s.type=2;continue t}if(s.map[s.key]=e,s.readCount++,s.readCount!==s.size){s.key=null,s.type=1;continue t}i.pop(),e=s.map}}return e}var a},t.prototype.readHeadByte=function(){return-1===this.headByte&&(this.headByte=this.readU8()),this.headByte},t.prototype.complete=function(){this.headByte=-1},t.prototype.readArraySize=function(){var t=this.readHeadByte();switch(t){case 220:return this.readU16();case 221:return this.readU32();default:if(t<160)return t-144;throw new Error("Unrecognized array type byte: "+C(t))}},t.prototype.pushMapState=function(t){if(t>this.maxMapLength)throw new Error("Max length exceeded: map length ("+t+") > maxMapLengthLength ("+this.maxMapLength+")");this.stack.push({type:1,size:t,key:null,readCount:0,map:{}})},t.prototype.pushArrayState=function(t){if(t>this.maxArrayLength)throw new Error("Max length exceeded: array length ("+t+") > maxArrayLength ("+this.maxArrayLength+")");this.stack.push({type:0,size:t,array:new Array(t),position:0})},t.prototype.decodeUtf8String=function(t,e){var n;if(t>this.maxStrLength)throw new Error("Max length exceeded: UTF-8 byte length ("+t+") > maxStrLength ("+this.maxStrLength+")");if(this.bytes.byteLength<this.pos+e+t)throw L;var r,i=this.pos+e;return r=this.stateIsMapKey()&&(null===(n=this.cachedKeyDecoder)||void 0===n?void 0:n.canBeCached(t))?this.cachedKeyDecoder.decode(this.bytes,i,t):s&&t>u?function(t,e,n){var r=t.subarray(e,e+n);return h.decode(r)}(this.bytes,i,t):d(this.bytes,i,t),this.pos+=e+t,r},t.prototype.stateIsMapKey=function(){return this.stack.length>0&&1===this.stack[this.stack.length-1].type},t.prototype.decodeBinary=function(t,e){if(t>this.maxBinLength)throw new Error("Max length exceeded: bin length ("+t+") > maxBinLength ("+this.maxBinLength+")");if(!this.hasRemaining(t+e))throw L;var n=this.pos+e,r=this.bytes.subarray(n,n+t);return this.pos+=e+t,r},t.prototype.decodeExtension=function(t,e){if(t>this.maxExtLength)throw new Error("Max length exceeded: ext length ("+t+") > maxExtLength ("+this.maxExtLength+")");var n=this.view.getInt8(this.pos+e),r=this.decodeBinary(t,e+1);return this.extensionCodec.decode(r,n,this.context)},t.prototype.lookU8=function(){return this.view.getUint8(this.pos)},t.prototype.lookU16=function(){return this.view.getUint16(this.pos)},t.prototype.lookU32=function(){return this.view.getUint32(this.pos)},t.prototype.readU8=function(){var t=this.view.getUint8(this.pos);return this.pos++,t},t.prototype.readI8=function(){var t=this.view.getInt8(this.pos);return this.pos++,t},t.prototype.readU16=function(){var t=this.view.getUint16(this.pos);return this.pos+=2,t},t.prototype.readI16=function(){var t=this.view.getInt16(this.pos);return this.pos+=2,t},t.prototype.readU32=function(){var t=this.view.getUint32(this.pos);return this.pos+=4,t},t.prototype.readI32=function(){var t=this.view.getInt32(this.pos);return this.pos+=4,t},t.prototype.readU64=function(){var t,e,n=4294967296*(t=this.view).getUint32(e=this.pos)+t.getUint32(e+4);return this.pos+=8,n},t.prototype.readI64=function(){var t=m(this.view,this.pos);return this.pos+=8,t},t.prototype.readF32=function(){var t=this.view.getFloat32(this.pos);return this.pos+=4,t},t.prototype.readF64=function(){var t=this.view.getFloat64(this.pos);return this.pos+=8,t},t}(),G={};function z(t,e){void 0===e&&(e=G);var n=new M(e.extensionCodec,e.context,e.maxStrLength,e.maxBinLength,e.maxArrayLength,e.maxMapLength,e.maxExtLength);return n.setBuffer(t),n.decodeSingleSync()}var W=function(t,e){var n,r,i,s,a={label:0,sent:function(){if(1&i[0])throw i[1];return i[1]},trys:[],ops:[]};return s={next:o(0),throw:o(1),return:o(2)},"function"==typeof Symbol&&(s[Symbol.iterator]=function(){return this}),s;function o(s){return function(o){return function(s){if(n)throw new TypeError("Generator is already executing.");for(;a;)try{if(n=1,r&&(i=2&s[0]?r.return:s[0]?r.throw||((i=r.return)&&i.call(r),0):r.next)&&!(i=i.call(r,s[1])).done)return i;switch(r=0,i&&(s=[2&s[0],i.value]),s[0]){case 0:case 1:i=s;break;case 4:return a.label++,{value:s[1],done:!1};case 5:a.label++,r=s[1],s=[0];continue;case 7:s=a.ops.pop(),a.trys.pop();continue;default:if(!((i=(i=a.trys).length>0&&i[i.length-1])||6!==s[0]&&2!==s[0])){a=0;continue}if(3===s[0]&&(!i||s[1]>i[0]&&s[1]<i[3])){a.label=s[1];break}if(6===s[0]&&a.label<i[1]){a.label=i[1],i=s;break}if(i&&a.label<i[2]){a.label=i[2],a.ops.push(s);break}i[2]&&a.ops.pop(),a.trys.pop();continue}s=e.call(t,a)}catch(t){s=[6,t],r=0}finally{n=i=0}if(5&s[0])throw s[1];return{value:s[0]?s[1]:void 0,done:!0}}([s,o])}}},H=function(t){return this instanceof H?(this.v=t,this):new H(t)},$=function(t,e,n){if(!Symbol.asyncIterator)throw new TypeError("Symbol.asyncIterator is not defined.");var r,i=n.apply(t,e||[]),s=[];return r={},a("next"),a("throw"),a("return"),r[Symbol.asyncIterator]=function(){return this},r;function a(t){i[t]&&(r[t]=function(e){return new Promise(function(n,r){s.push([t,e,n,r])>1||o(t,e)})})}function o(t,e){try{(n=i[t](e)).value instanceof H?Promise.resolve(n.value.v).then(l,c):d(s[0][2],n)}catch(t){d(s[0][3],t)}var n}function l(t){o("next",t)}function c(t){o("throw",t)}function d(t,e){t(e),s.shift(),s.length&&o(s[0][0],s[0][1])}};function j(t){return null!=t[Symbol.asyncIterator]?t:function(t){return $(this,arguments,function(){var e,n,r;return W(this,function(i){switch(i.label){case 0:e=t.getReader(),i.label=1;case 1:i.trys.push([1,,9,10]),i.label=2;case 2:return[4,H(e.read())];case 3:return n=i.sent(),r=n.value,n.done?[4,H(void 0)]:[3,5];case 4:return[2,i.sent()];case 5:return function(t){if(null==t)throw new Error("Assertion Failure: value must not be null nor undefined")}(r),[4,H(r)];case 6:return[4,i.sent()];case 7:return i.sent(),[3,2];case 8:return[3,10];case 9:return e.releaseLock(),[7];case 10:return[2]}})})}(t)}var V=function(t,e,n,r){return new(n||(n=Promise))(function(i,s){function a(t){try{l(r.next(t))}catch(t){s(t)}}function o(t){try{l(r.throw(t))}catch(t){s(t)}}function l(t){var e;t.done?i(t.value):(e=t.value,e instanceof n?e:new n(function(t){t(e)})).then(a,o)}l((r=r.apply(t,e||[])).next())})},Y=function(t,e){var n,r,i,s,a={label:0,sent:function(){if(1&i[0])throw i[1];return i[1]},trys:[],ops:[]};return s={next:o(0),throw:o(1),return:o(2)},"function"==typeof Symbol&&(s[Symbol.iterator]=function(){return this}),s;function o(s){return function(o){return function(s){if(n)throw new TypeError("Generator is already executing.");for(;a;)try{if(n=1,r&&(i=2&s[0]?r.return:s[0]?r.throw||((i=r.return)&&i.call(r),0):r.next)&&!(i=i.call(r,s[1])).done)return i;switch(r=0,i&&(s=[2&s[0],i.value]),s[0]){case 0:case 1:i=s;break;case 4:return a.label++,{value:s[1],done:!1};case 5:a.label++,r=s[1],s=[0];continue;case 7:s=a.ops.pop(),a.trys.pop();continue;default:if(!((i=(i=a.trys).length>0&&i[i.length-1])||6!==s[0]&&2!==s[0])){a=0;continue}if(3===s[0]&&(!i||s[1]>i[0]&&s[1]<i[3])){a.label=s[1];break}if(6===s[0]&&a.label<i[1]){a.label=i[1],i=s;break}if(i&&a.label<i[2]){a.label=i[2],a.ops.push(s);break}i[2]&&a.ops.pop(),a.trys.pop();continue}s=e.call(t,a)}catch(t){s=[6,t],r=0}finally{n=i=0}if(5&s[0])throw s[1];return{value:s[0]?s[1]:void 0,done:!0}}([s,o])}}};function K(t,e){return void 0===e&&(e=G),V(this,void 0,void 0,function(){var n;return Y(this,function(r){return n=j(t),[2,new M(e.extensionCodec,e.context,e.maxStrLength,e.maxBinLength,e.maxArrayLength,e.maxMapLength,e.maxExtLength).decodeSingleAsync(n)]})})}function X(t,e){void 0===e&&(e=G);var n=j(t);return new M(e.extensionCodec,e.context,e.maxStrLength,e.maxBinLength,e.maxArrayLength,e.maxMapLength,e.maxExtLength).decodeArrayStream(n)}function q(t,e){void 0===e&&(e=G);var n=j(t);return new M(e.extensionCodec,e.context,e.maxStrLength,e.maxBinLength,e.maxArrayLength,e.maxMapLength,e.maxExtLength).decodeStream(n)}}])});const PACKET_TYPES=Object.create(null);PACKET_TYPES.open="0",PACKET_TYPES.close="1",PACKET_TYPES.ping="2",PACKET_TYPES.pong="3",PACKET_TYPES.message="4",PACKET_TYPES.upgrade="5",PACKET_TYPES.noop="6";const PACKET_TYPES_REVERSE=Object.create(null);Object.keys(PACKET_TYPES).forEach(t=>{PACKET_TYPES_REVERSE[PACKET_TYPES[t]]=t});const ERROR_PACKET={type:"error",data:"parser error"},withNativeBlob$1="function"==typeof Blob||"undefined"!=typeof Blob&&"[object BlobConstructor]"===Object.prototype.toString.call(Blob),withNativeArrayBuffer$2="function"==typeof ArrayBuffer,isView$1=t=>"function"==typeof ArrayBuffer.isView?ArrayBuffer.isView(t):t&&t.buffer instanceof ArrayBuffer,encodePacket=({type:t,data:e},n,r)=>withNativeBlob$1&&e instanceof Blob?n?r(e):encodeBlobAsBase64(e,r):withNativeArrayBuffer$2&&(e instanceof ArrayBuffer||isView$1(e))?n?r(e):encodeBlobAsBase64(new Blob([e]),r):r(PACKET_TYPES[t]+(e||"")),encodeBlobAsBase64=(t,e)=>{const n=new FileReader;return n.onload=function(){const t=n.result.split(",")[1];e("b"+(t||""))},n.readAsDataURL(t)};function toArray(t){return t instanceof Uint8Array?t:t instanceof ArrayBuffer?new Uint8Array(t):new Uint8Array(t.buffer,t.byteOffset,t.byteLength)}let TEXT_ENCODER;function encodePacketToBinary(t,e){return withNativeBlob$1&&t.data instanceof Blob?t.data.arrayBuffer().then(toArray).then(e):withNativeArrayBuffer$2&&(t.data instanceof ArrayBuffer||isView$1(t.data))?e(toArray(t.data)):void encodePacket(t,!1,t=>{TEXT_ENCODER||(TEXT_ENCODER=new TextEncoder),e(TEXT_ENCODER.encode(t))})}const chars="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",lookup$1="undefined"==typeof Uint8Array?[]:new Uint8Array(256);for(let t=0;t<chars.length;t++)lookup$1[chars.charCodeAt(t)]=t;const decode$1=t=>{let e,n,r,i,s,a=.75*t.length,o=t.length,l=0;"="===t[t.length-1]&&(a--,"="===t[t.length-2]&&a--);const c=new ArrayBuffer(a),d=new Uint8Array(c);for(e=0;e<o;e+=4)n=lookup$1[t.charCodeAt(e)],r=lookup$1[t.charCodeAt(e+1)],i=lookup$1[t.charCodeAt(e+2)],s=lookup$1[t.charCodeAt(e+3)],d[l++]=n<<2|r>>4,d[l++]=(15&r)<<4|i>>2,d[l++]=(3&i)<<6|63&s;return c},withNativeArrayBuffer$1="function"==typeof ArrayBuffer,decodePacket=(t,e)=>{if("string"!=typeof t)return{type:"message",data:mapBinary(t,e)};const n=t.charAt(0);return"b"===n?{type:"message",data:decodeBase64Packet(t.substring(1),e)}:PACKET_TYPES_REVERSE[n]?t.length>1?{type:PACKET_TYPES_REVERSE[n],data:t.substring(1)}:{type:PACKET_TYPES_REVERSE[n]}:ERROR_PACKET},decodeBase64Packet=(t,e)=>{if(withNativeArrayBuffer$1){const n=decode$1(t);return mapBinary(n,e)}return{base64:!0,data:t}},mapBinary=(t,e)=>"blob"===e?t instanceof Blob?t:new Blob([t]):t instanceof ArrayBuffer?t:t.buffer,SEPARATOR=String.fromCharCode(30),encodePayload=(t,e)=>{const n=t.length,r=new Array(n);let i=0;t.forEach((t,s)=>{encodePacket(t,!1,t=>{r[s]=t,++i===n&&e(r.join(SEPARATOR))})})},decodePayload=(t,e)=>{const n=t.split(SEPARATOR),r=[];for(let t=0;t<n.length;t++){const i=decodePacket(n[t],e);if(r.push(i),"error"===i.type)break}return r};function createPacketEncoderStream(){return new TransformStream({transform(t,e){encodePacketToBinary(t,n=>{const r=n.length;let i;if(r<126)i=new Uint8Array(1),new DataView(i.buffer).setUint8(0,r);else if(r<65536){i=new Uint8Array(3);const t=new DataView(i.buffer);t.setUint8(0,126),t.setUint16(1,r)}else{i=new Uint8Array(9);const t=new DataView(i.buffer);t.setUint8(0,127),t.setBigUint64(1,BigInt(r))}t.data&&"string"!=typeof t.data&&(i[0]|=128),e.enqueue(i),e.enqueue(n)})}})}let TEXT_DECODER;function totalLength(t){return t.reduce((t,e)=>t+e.length,0)}function concatChunks(t,e){if(t[0].length===e)return t.shift();const n=new Uint8Array(e);let r=0;for(let i=0;i<e;i++)n[i]=t[0][r++],r===t[0].length&&(t.shift(),r=0);return t.length&&r<t[0].length&&(t[0]=t[0].slice(r)),n}function createPacketDecoderStream(t,e){TEXT_DECODER||(TEXT_DECODER=new TextDecoder);const n=[];let r=0,i=-1,s=!1;return new TransformStream({transform(a,o){for(n.push(a);;){if(0===r){if(totalLength(n)<1)break;const t=concatChunks(n,1);s=!(128&~t[0]),i=127&t[0],r=i<126?3:126===i?1:2}else if(1===r){if(totalLength(n)<2)break;const t=concatChunks(n,2);i=new DataView(t.buffer,t.byteOffset,t.length).getUint16(0),r=3}else if(2===r){if(totalLength(n)<8)break;const t=concatChunks(n,8),e=new DataView(t.buffer,t.byteOffset,t.length),s=e.getUint32(0);if(s>Math.pow(2,21)-1){o.enqueue(ERROR_PACKET);break}i=s*Math.pow(2,32)+e.getUint32(4),r=3}else{if(totalLength(n)<i)break;const t=concatChunks(n,i);o.enqueue(decodePacket(s?t:TEXT_DECODER.decode(t),e)),r=0}if(0===i||i>t){o.enqueue(ERROR_PACKET);break}}}})}const protocol$1=4;function Emitter(t){if(t)return mixin(t)}function mixin(t){for(var e in Emitter.prototype)t[e]=Emitter.prototype[e];return t}Emitter.prototype.on=Emitter.prototype.addEventListener=function(t,e){return this._callbacks=this._callbacks||{},(this._callbacks["$"+t]=this._callbacks["$"+t]||[]).push(e),this},Emitter.prototype.once=function(t,e){function n(){this.off(t,n),e.apply(this,arguments)}return n.fn=e,this.on(t,n),this},Emitter.prototype.off=Emitter.prototype.removeListener=Emitter.prototype.removeAllListeners=Emitter.prototype.removeEventListener=function(t,e){if(this._callbacks=this._callbacks||{},0==arguments.length)return this._callbacks={},this;var n,r=this._callbacks["$"+t];if(!r)return this;if(1==arguments.length)return delete this._callbacks["$"+t],this;for(var i=0;i<r.length;i++)if((n=r[i])===e||n.fn===e){r.splice(i,1);break}return 0===r.length&&delete this._callbacks["$"+t],this},Emitter.prototype.emit=function(t){this._callbacks=this._callbacks||{};for(var e=new Array(arguments.length-1),n=this._callbacks["$"+t],r=1;r<arguments.length;r++)e[r-1]=arguments[r];if(n){r=0;for(var i=(n=n.slice(0)).length;r<i;++r)n[r].apply(this,e)}return this},Emitter.prototype.emitReserved=Emitter.prototype.emit,Emitter.prototype.listeners=function(t){return this._callbacks=this._callbacks||{},this._callbacks["$"+t]||[]},Emitter.prototype.hasListeners=function(t){return!!this.listeners(t).length};const nextTick="function"==typeof Promise&&"function"==typeof Promise.resolve?t=>Promise.resolve().then(t):(t,e)=>e(t,0),globalThisShim="undefined"!=typeof self?self:"undefined"!=typeof window?window:Function("return this")(),defaultBinaryType="arraybuffer";function createCookieJar(){}function pick(t,...e){return e.reduce((e,n)=>(t.hasOwnProperty(n)&&(e[n]=t[n]),e),{})}const NATIVE_SET_TIMEOUT=globalThisShim.setTimeout,NATIVE_CLEAR_TIMEOUT=globalThisShim.clearTimeout;function installTimerFunctions(t,e){e.useNativeTimers?(t.setTimeoutFn=NATIVE_SET_TIMEOUT.bind(globalThisShim),t.clearTimeoutFn=NATIVE_CLEAR_TIMEOUT.bind(globalThisShim)):(t.setTimeoutFn=globalThisShim.setTimeout.bind(globalThisShim),t.clearTimeoutFn=globalThisShim.clearTimeout.bind(globalThisShim))}const BASE64_OVERHEAD=1.33;function byteLength(t){return"string"==typeof t?utf8Length$1(t):Math.ceil((t.byteLength||t.size)*BASE64_OVERHEAD)}function utf8Length$1(t){let e=0,n=0;for(let r=0,i=t.length;r<i;r++)e=t.charCodeAt(r),e<128?n+=1:e<2048?n+=2:e<55296||e>=57344?n+=3:(r++,n+=4);return n}function randomString(){return Date.now().toString(36).substring(3)+Math.random().toString(36).substring(2,5)}function encode(t){let e="";for(let n in t)t.hasOwnProperty(n)&&(e.length&&(e+="&"),e+=encodeURIComponent(n)+"="+encodeURIComponent(t[n]));return e}function decode(t){let e={},n=t.split("&");for(let t=0,r=n.length;t<r;t++){let r=n[t].split("=");e[decodeURIComponent(r[0])]=decodeURIComponent(r[1])}return e}class TransportError extends Error{constructor(t,e,n){super(t),this.description=e,this.context=n,this.type="TransportError"}}class Transport extends Emitter{constructor(t){super(),this.writable=!1,installTimerFunctions(this,t),this.opts=t,this.query=t.query,this.socket=t.socket,this.supportsBinary=!t.forceBase64}onError(t,e,n){return super.emitReserved("error",new TransportError(t,e,n)),this}open(){return this.readyState="opening",this.doOpen(),this}close(){return"opening"!==this.readyState&&"open"!==this.readyState||(this.doClose(),this.onClose()),this}send(t){"open"===this.readyState&&this.write(t)}onOpen(){this.readyState="open",this.writable=!0,super.emitReserved("open")}onData(t){const e=decodePacket(t,this.socket.binaryType);this.onPacket(e)}onPacket(t){super.emitReserved("packet",t)}onClose(t){this.readyState="closed",super.emitReserved("close",t)}pause(t){}createUri(t,e={}){return t+"://"+this._hostname()+this._port()+this.opts.path+this._query(e)}_hostname(){const t=this.opts.hostname;return-1===t.indexOf(":")?t:"["+t+"]"}_port(){return this.opts.port&&(this.opts.secure&&Number(443!==this.opts.port)||!this.opts.secure&&80!==Number(this.opts.port))?":"+this.opts.port:""}_query(t){const e=encode(t);return e.length?"?"+e:""}}class Polling extends Transport{constructor(){super(...arguments),this._polling=!1}get name(){return"polling"}doOpen(){this._poll()}pause(t){this.readyState="pausing";const e=()=>{this.readyState="paused",t()};if(this._polling||!this.writable){let t=0;this._polling&&(t++,this.once("pollComplete",function(){--t||e()})),this.writable||(t++,this.once("drain",function(){--t||e()}))}else e()}_poll(){this._polling=!0,this.doPoll(),this.emitReserved("poll")}onData(t){decodePayload(t,this.socket.binaryType).forEach(t=>{if("opening"===this.readyState&&"open"===t.type&&this.onOpen(),"close"===t.type)return this.onClose({description:"transport closed by the server"}),!1;this.onPacket(t)}),"closed"!==this.readyState&&(this._polling=!1,this.emitReserved("pollComplete"),"open"===this.readyState&&this._poll())}doClose(){const t=()=>{this.write([{type:"close"}])};"open"===this.readyState?t():this.once("open",t)}write(t){this.writable=!1,encodePayload(t,t=>{this.doWrite(t,()=>{this.writable=!0,this.emitReserved("drain")})})}uri(){const t=this.opts.secure?"https":"http",e=this.query||{};return!1!==this.opts.timestampRequests&&(e[this.opts.timestampParam]=randomString()),this.supportsBinary||e.sid||(e.b64=1),this.createUri(t,e)}}let value=!1;try{value="undefined"!=typeof XMLHttpRequest&&"withCredentials"in new XMLHttpRequest}catch(err){}const hasCORS=value;function empty(){}class BaseXHR extends Polling{constructor(t){if(super(t),"undefined"!=typeof location){const e="https:"===location.protocol;let n=location.port;n||(n=e?"443":"80"),this.xd="undefined"!=typeof location&&t.hostname!==location.hostname||n!==t.port}}doWrite(t,e){const n=this.request({method:"POST",data:t});n.on("success",e),n.on("error",(t,e)=>{this.onError("xhr post error",t,e)})}doPoll(){const t=this.request();t.on("data",this.onData.bind(this)),t.on("error",(t,e)=>{this.onError("xhr poll error",t,e)}),this.pollXhr=t}}class Request$1 extends Emitter{constructor(t,e,n){super(),this.createRequest=t,installTimerFunctions(this,n),this._opts=n,this._method=n.method||"GET",this._uri=e,this._data=void 0!==n.data?n.data:null,this._create()}_create(){var t;const e=pick(this._opts,"agent","pfx","key","passphrase","cert","ca","ciphers","rejectUnauthorized","autoUnref");e.xdomain=!!this._opts.xd;const n=this._xhr=this.createRequest(e);try{n.open(this._method,this._uri,!0);try{if(this._opts.extraHeaders){n.setDisableHeaderCheck&&n.setDisableHeaderCheck(!0);for(let t in this._opts.extraHeaders)this._opts.extraHeaders.hasOwnProperty(t)&&n.setRequestHeader(t,this._opts.extraHeaders[t])}}catch(t){}if("POST"===this._method)try{n.setRequestHeader("Content-type","text/plain;charset=UTF-8")}catch(t){}try{n.setRequestHeader("Accept","*/*")}catch(t){}null===(t=this._opts.cookieJar)||void 0===t||t.addCookies(n),"withCredentials"in n&&(n.withCredentials=this._opts.withCredentials),this._opts.requestTimeout&&(n.timeout=this._opts.requestTimeout),n.onreadystatechange=()=>{var t;3===n.readyState&&(null===(t=this._opts.cookieJar)||void 0===t||t.parseCookies(n.getResponseHeader("set-cookie"))),4===n.readyState&&(200===n.status||1223===n.status?this._onLoad():this.setTimeoutFn(()=>{this._onError("number"==typeof n.status?n.status:0)},0))},n.send(this._data)}catch(t){return void this.setTimeoutFn(()=>{this._onError(t)},0)}"undefined"!=typeof document&&(this._index=Request$1.requestsCount++,Request$1.requests[this._index]=this)}_onError(t){this.emitReserved("error",t,this._xhr),this._cleanup(!0)}_cleanup(t){if(null!=this._xhr){if(this._xhr.onreadystatechange=empty,t)try{this._xhr.abort()}catch(t){}"undefined"!=typeof document&&delete Request$1.requests[this._index],this._xhr=null}}_onLoad(){const t=this._xhr.responseText;null!==t&&(this.emitReserved("data",t),this.emitReserved("success"),this._cleanup())}abort(){this._cleanup()}}if(Request$1.requestsCount=0,Request$1.requests={},"undefined"!=typeof document)if("function"==typeof attachEvent)attachEvent("onunload",unloadHandler);else if("function"==typeof addEventListener){const t="onpagehide"in globalThisShim?"pagehide":"unload";addEventListener(t,unloadHandler,!1)}function unloadHandler(){for(let t in Request$1.requests)Request$1.requests.hasOwnProperty(t)&&Request$1.requests[t].abort()}const hasXHR2=function(){const t=newRequest({xdomain:!1});return t&&null!==t.responseType}();class XHR extends BaseXHR{constructor(t){super(t),this.supportsBinary=hasXHR2&&!(t&&t.forceBase64)}request(t={}){return Object.assign(t,{xd:this.xd},this.opts),new Request$1(newRequest,this.uri(),t)}}function newRequest(t){const e=t.xdomain;try{if("undefined"!=typeof XMLHttpRequest&&(!e||hasCORS))return new XMLHttpRequest}catch(t){}if(!e)try{return new(globalThisShim[["Active"].concat("Object").join("X")])("Microsoft.XMLHTTP")}catch(t){}}const isReactNative="undefined"!=typeof navigator&&"string"==typeof navigator.product&&"reactnative"===navigator.product.toLowerCase();class BaseWS extends Transport{get name(){return"websocket"}doOpen(){const t=this.uri(),e=this.opts.protocols,n=isReactNative?{}:pick(this.opts,"agent","perMessageDeflate","pfx","key","passphrase","cert","ca","ciphers","rejectUnauthorized","localAddress","protocolVersion","origin","maxPayload","family","checkServerIdentity");this.opts.extraHeaders&&(n.headers=this.opts.extraHeaders);try{this.ws=this.createSocket(t,e,n)}catch(t){return this.emitReserved("error",t)}this.ws.binaryType=this.socket.binaryType,this.addEventListeners()}addEventListeners(){this.ws.onopen=()=>{this.opts.autoUnref&&this.ws._socket.unref(),this.onOpen()},this.ws.onclose=t=>this.onClose({description:"websocket connection closed",context:t}),this.ws.onmessage=t=>this.onData(t.data),this.ws.onerror=t=>this.onError("websocket error",t)}write(t){this.writable=!1;for(let e=0;e<t.length;e++){const n=t[e],r=e===t.length-1;encodePacket(n,this.supportsBinary,t=>{try{this.doWrite(n,t)}catch(t){}r&&nextTick(()=>{this.writable=!0,this.emitReserved("drain")},this.setTimeoutFn)})}}doClose(){void 0!==this.ws&&(this.ws.onerror=()=>{},this.ws.close(),this.ws=null)}uri(){const t=this.opts.secure?"wss":"ws",e=this.query||{};return this.opts.timestampRequests&&(e[this.opts.timestampParam]=randomString()),this.supportsBinary||(e.b64=1),this.createUri(t,e)}}const WebSocketCtor=globalThisShim.WebSocket||globalThisShim.MozWebSocket;class WS extends BaseWS{createSocket(t,e,n){return isReactNative?new WebSocketCtor(t,e,n):e?new WebSocketCtor(t,e):new WebSocketCtor(t)}doWrite(t,e){this.ws.send(e)}}class WT extends Transport{get name(){return"webtransport"}doOpen(){try{this._transport=new WebTransport(this.createUri("https"),this.opts.transportOptions[this.name])}catch(t){return this.emitReserved("error",t)}this._transport.closed.then(()=>{this.onClose()}).catch(t=>{this.onError("webtransport error",t)}),this._transport.ready.then(()=>{this._transport.createBidirectionalStream().then(t=>{const e=createPacketDecoderStream(Number.MAX_SAFE_INTEGER,this.socket.binaryType),n=t.readable.pipeThrough(e).getReader(),r=createPacketEncoderStream();r.readable.pipeTo(t.writable),this._writer=r.writable.getWriter();const i=()=>{n.read().then(({done:t,value:e})=>{t||(this.onPacket(e),i())}).catch(t=>{})};i();const s={type:"open"};this.query.sid&&(s.data=`{"sid":"${this.query.sid}"}`),this._writer.write(s).then(()=>this.onOpen())})})}write(t){this.writable=!1;for(let e=0;e<t.length;e++){const n=e===t.length-1;this._writer.write(t[e]).then(()=>{n&&nextTick(()=>{this.writable=!0,this.emitReserved("drain")},this.setTimeoutFn)})}}doClose(){var t;null===(t=this._transport)||void 0===t||t.close()}}const transports={websocket:WS,webtransport:WT,polling:XHR},re=/^(?:(?![^:@\/?#]+:[^:@\/]*@)(http|https|ws|wss):\/\/)?((?:(([^:@\/?#]*)(?::([^:@\/?#]*))?)?@)?((?:[a-f0-9]{0,4}:){2,7}[a-f0-9]{0,4}|[^:\/?#]*)(?::(\d*))?)(((\/(?:[^?#](?![^?#\/]*\.[^?#\/.]+(?:[?#]|$)))*\/?)?([^?#\/]*))(?:\?([^#]*))?(?:#(.*))?)/,parts=["source","protocol","authority","userInfo","user","password","host","port","relative","path","directory","file","query","anchor"];function parse(t){if(t.length>8e3)throw"URI too long";const e=t,n=t.indexOf("["),r=t.indexOf("]");-1!=n&&-1!=r&&(t=t.substring(0,n)+t.substring(n,r).replace(/:/g,";")+t.substring(r,t.length));let i=re.exec(t||""),s={},a=14;for(;a--;)s[parts[a]]=i[a]||"";return-1!=n&&-1!=r&&(s.source=e,s.host=s.host.substring(1,s.host.length-1).replace(/;/g,":"),s.authority=s.authority.replace("[","").replace("]","").replace(/;/g,":"),s.ipv6uri=!0),s.pathNames=pathNames(s,s.path),s.queryKey=queryKey(s,s.query),s}function pathNames(t,e){const n=e.replace(/\/{2,9}/g,"/").split("/");return"/"!=e.slice(0,1)&&0!==e.length||n.splice(0,1),"/"==e.slice(-1)&&n.splice(n.length-1,1),n}function queryKey(t,e){const n={};return e.replace(/(?:^|&)([^&=]*)=?([^&]*)/g,function(t,e,r){e&&(n[e]=r)}),n}const withEventListeners="function"==typeof addEventListener&&"function"==typeof removeEventListener,OFFLINE_EVENT_LISTENERS=[];withEventListeners&&addEventListener("offline",()=>{OFFLINE_EVENT_LISTENERS.forEach(t=>t())},!1);class SocketWithoutUpgrade extends Emitter{constructor(t,e){if(super(),this.binaryType=defaultBinaryType,this.writeBuffer=[],this._prevBufferLen=0,this._pingInterval=-1,this._pingTimeout=-1,this._maxPayload=-1,this._pingTimeoutTime=Infinity,t&&"object"==typeof t&&(e=t,t=null),t){const n=parse(t);e.hostname=n.host,e.secure="https"===n.protocol||"wss"===n.protocol,e.port=n.port,n.query&&(e.query=n.query)}else e.host&&(e.hostname=parse(e.host).host);installTimerFunctions(this,e),this.secure=null!=e.secure?e.secure:"undefined"!=typeof location&&"https:"===location.protocol,e.hostname&&!e.port&&(e.port=this.secure?"443":"80"),this.hostname=e.hostname||("undefined"!=typeof location?location.hostname:"localhost"),this.port=e.port||("undefined"!=typeof location&&location.port?location.port:this.secure?"443":"80"),this.transports=[],this._transportsByName={},e.transports.forEach(t=>{const e=t.prototype.name;this.transports.push(e),this._transportsByName[e]=t}),this.opts=Object.assign({path:"/engine.io",agent:!1,withCredentials:!1,upgrade:!0,timestampParam:"t",rememberUpgrade:!1,addTrailingSlash:!0,rejectUnauthorized:!0,perMessageDeflate:{threshold:1024},transportOptions:{},closeOnBeforeunload:!1},e),this.opts.path=this.opts.path.replace(/\/$/,"")+(this.opts.addTrailingSlash?"/":""),"string"==typeof this.opts.query&&(this.opts.query=decode(this.opts.query)),withEventListeners&&(this.opts.closeOnBeforeunload&&(this._beforeunloadEventListener=()=>{this.transport&&(this.transport.removeAllListeners(),this.transport.close())},addEventListener("beforeunload",this._beforeunloadEventListener,!1)),"localhost"!==this.hostname&&(this._offlineEventListener=()=>{this._onClose("transport close",{description:"network connection lost"})},OFFLINE_EVENT_LISTENERS.push(this._offlineEventListener))),this.opts.withCredentials&&(this._cookieJar=createCookieJar()),this._open()}createTransport(t){const e=Object.assign({},this.opts.query);e.EIO=protocol$1,e.transport=t,this.id&&(e.sid=this.id);const n=Object.assign({},this.opts,{query:e,socket:this,hostname:this.hostname,secure:this.secure,port:this.port},this.opts.transportOptions[t]);return new this._transportsByName[t](n)}_open(){if(0===this.transports.length)return void this.setTimeoutFn(()=>{this.emitReserved("error","No transports available")},0);const t=this.opts.rememberUpgrade&&SocketWithoutUpgrade.priorWebsocketSuccess&&-1!==this.transports.indexOf("websocket")?"websocket":this.transports[0];this.readyState="opening";const e=this.createTransport(t);e.open(),this.setTransport(e)}setTransport(t){this.transport&&this.transport.removeAllListeners(),this.transport=t,t.on("drain",this._onDrain.bind(this)).on("packet",this._onPacket.bind(this)).on("error",this._onError.bind(this)).on("close",t=>this._onClose("transport close",t))}onOpen(){this.readyState="open",SocketWithoutUpgrade.priorWebsocketSuccess="websocket"===this.transport.name,this.emitReserved("open"),this.flush()}_onPacket(t){if("opening"===this.readyState||"open"===this.readyState||"closing"===this.readyState)switch(this.emitReserved("packet",t),this.emitReserved("heartbeat"),t.type){case"open":this.onHandshake(JSON.parse(t.data));break;case"ping":this._sendPacket("pong"),this.emitReserved("ping"),this.emitReserved("pong"),this._resetPingTimeout();break;case"error":const e=new Error("server error");e.code=t.data,this._onError(e);break;case"message":this.emitReserved("data",t.data),this.emitReserved("message",t.data)}}onHandshake(t){this.emitReserved("handshake",t),this.id=t.sid,this.transport.query.sid=t.sid,this._pingInterval=t.pingInterval,this._pingTimeout=t.pingTimeout,this._maxPayload=t.maxPayload,this.onOpen(),"closed"!==this.readyState&&this._resetPingTimeout()}_resetPingTimeout(){this.clearTimeoutFn(this._pingTimeoutTimer);const t=this._pingInterval+this._pingTimeout;this._pingTimeoutTime=Date.now()+t,this._pingTimeoutTimer=this.setTimeoutFn(()=>{this._onClose("ping timeout")},t),this.opts.autoUnref&&this._pingTimeoutTimer.unref()}_onDrain(){this.writeBuffer.splice(0,this._prevBufferLen),this._prevBufferLen=0,0===this.writeBuffer.length?this.emitReserved("drain"):this.flush()}flush(){if("closed"!==this.readyState&&this.transport.writable&&!this.upgrading&&this.writeBuffer.length){const t=this._getWritablePackets();this.transport.send(t),this._prevBufferLen=t.length,this.emitReserved("flush")}}_getWritablePackets(){if(!(this._maxPayload&&"polling"===this.transport.name&&this.writeBuffer.length>1))return this.writeBuffer;let t=1;for(let e=0;e<this.writeBuffer.length;e++){const n=this.writeBuffer[e].data;if(n&&(t+=byteLength(n)),e>0&&t>this._maxPayload)return this.writeBuffer.slice(0,e);t+=2}return this.writeBuffer}_hasPingExpired(){if(!this._pingTimeoutTime)return!0;const t=Date.now()>this._pingTimeoutTime;return t&&(this._pingTimeoutTime=0,nextTick(()=>{this._onClose("ping timeout")},this.setTimeoutFn)),t}write(t,e,n){return this._sendPacket("message",t,e,n),this}send(t,e,n){return this._sendPacket("message",t,e,n),this}_sendPacket(t,e,n,r){if("function"==typeof e&&(r=e,e=void 0),"function"==typeof n&&(r=n,n=null),"closing"===this.readyState||"closed"===this.readyState)return;(n=n||{}).compress=!1!==n.compress;const i={type:t,data:e,options:n};this.emitReserved("packetCreate",i),this.writeBuffer.push(i),r&&this.once("flush",r),this.flush()}close(){const t=()=>{this._onClose("forced close"),this.transport.close()},e=()=>{this.off("upgrade",e),this.off("upgradeError",e),t()},n=()=>{this.once("upgrade",e),this.once("upgradeError",e)};return"opening"!==this.readyState&&"open"!==this.readyState||(this.readyState="closing",this.writeBuffer.length?this.once("drain",()=>{this.upgrading?n():t()}):this.upgrading?n():t()),this}_onError(t){if(SocketWithoutUpgrade.priorWebsocketSuccess=!1,this.opts.tryAllTransports&&this.transports.length>1&&"opening"===this.readyState)return this.transports.shift(),this._open();this.emitReserved("error",t),this._onClose("transport error",t)}_onClose(t,e){if("opening"===this.readyState||"open"===this.readyState||"closing"===this.readyState){if(this.clearTimeoutFn(this._pingTimeoutTimer),this.transport.removeAllListeners("close"),this.transport.close(),this.transport.removeAllListeners(),withEventListeners&&(this._beforeunloadEventListener&&removeEventListener("beforeunload",this._beforeunloadEventListener,!1),this._offlineEventListener)){const t=OFFLINE_EVENT_LISTENERS.indexOf(this._offlineEventListener);-1!==t&&OFFLINE_EVENT_LISTENERS.splice(t,1)}this.readyState="closed",this.id=null,this.emitReserved("close",t,e),this.writeBuffer=[],this._prevBufferLen=0}}}SocketWithoutUpgrade.protocol=protocol$1;class SocketWithUpgrade extends SocketWithoutUpgrade{constructor(){super(...arguments),this._upgrades=[]}onOpen(){if(super.onOpen(),"open"===this.readyState&&this.opts.upgrade)for(let t=0;t<this._upgrades.length;t++)this._probe(this._upgrades[t])}_probe(t){let e=this.createTransport(t),n=!1;SocketWithoutUpgrade.priorWebsocketSuccess=!1;const r=()=>{n||(e.send([{type:"ping",data:"probe"}]),e.once("packet",t=>{if(!n)if("pong"===t.type&&"probe"===t.data){if(this.upgrading=!0,this.emitReserved("upgrading",e),!e)return;SocketWithoutUpgrade.priorWebsocketSuccess="websocket"===e.name,this.transport.pause(()=>{n||"closed"!==this.readyState&&(c(),this.setTransport(e),e.send([{type:"upgrade"}]),this.emitReserved("upgrade",e),e=null,this.upgrading=!1,this.flush())})}else{const t=new Error("probe error");t.transport=e.name,this.emitReserved("upgradeError",t)}}))};function i(){n||(n=!0,c(),e.close(),e=null)}const s=t=>{const n=new Error("probe error: "+t);n.transport=e.name,i(),this.emitReserved("upgradeError",n)};function a(){s("transport closed")}function o(){s("socket closed")}function l(t){e&&t.name!==e.name&&i()}const c=()=>{e.removeListener("open",r),e.removeListener("error",s),e.removeListener("close",a),this.off("close",o),this.off("upgrading",l)};e.once("open",r),e.once("error",s),e.once("close",a),this.once("close",o),this.once("upgrading",l),-1!==this._upgrades.indexOf("webtransport")&&"webtransport"!==t?this.setTimeoutFn(()=>{n||e.open()},200):e.open()}onHandshake(t){this._upgrades=this._filterUpgrades(t.upgrades),super.onHandshake(t)}_filterUpgrades(t){const e=[];for(let n=0;n<t.length;n++)~this.transports.indexOf(t[n])&&e.push(t[n]);return e}}class Socket$1 extends SocketWithUpgrade{constructor(t,e={}){const n="object"==typeof t?t:e;(!n.transports||n.transports&&"string"==typeof n.transports[0])&&(n.transports=(n.transports||["polling","websocket","webtransport"]).map(t=>transports[t]).filter(t=>!!t)),super(t,n)}}function url(t,e="",n){let r=t;n=n||"undefined"!=typeof location&&location,null==t&&(t=n.protocol+"//"+n.host),"string"==typeof t&&("/"===t.charAt(0)&&(t="/"===t.charAt(1)?n.protocol+t:n.host+t),/^(https?|wss?):\/\//.test(t)||(t=void 0!==n?n.protocol+"//"+t:"https://"+t),r=parse(t)),r.port||(/^(http|ws)$/.test(r.protocol)?r.port="80":/^(http|ws)s$/.test(r.protocol)&&(r.port="443")),r.path=r.path||"/";const i=-1!==r.host.indexOf(":")?"["+r.host+"]":r.host;return r.id=r.protocol+"://"+i+":"+r.port+e,r.href=r.protocol+"://"+i+(n&&n.port===r.port?"":":"+r.port),r}const withNativeArrayBuffer="function"==typeof ArrayBuffer,isView=t=>"function"==typeof ArrayBuffer.isView?ArrayBuffer.isView(t):t.buffer instanceof ArrayBuffer,toString=Object.prototype.toString,withNativeBlob="function"==typeof Blob||"undefined"!=typeof Blob&&"[object BlobConstructor]"===toString.call(Blob),withNativeFile="function"==typeof File||"undefined"!=typeof File&&"[object FileConstructor]"===toString.call(File);function isBinary(t){return withNativeArrayBuffer&&(t instanceof ArrayBuffer||isView(t))||withNativeBlob&&t instanceof Blob||withNativeFile&&t instanceof File}function hasBinary(t,e){if(!t||"object"!=typeof t)return!1;if(Array.isArray(t)){for(let e=0,n=t.length;e<n;e++)if(hasBinary(t[e]))return!0;return!1}if(isBinary(t))return!0;if(t.toJSON&&"function"==typeof t.toJSON&&1===arguments.length)return hasBinary(t.toJSON(),!0);for(const e in t)if(Object.prototype.hasOwnProperty.call(t,e)&&hasBinary(t[e]))return!0;return!1}function deconstructPacket(t){const e=[],n=t;return n.data=_deconstructPacket(t.data,e),n.attachments=e.length,{packet:n,buffers:e}}function _deconstructPacket(t,e){if(!t)return t;if(isBinary(t)){const n={_placeholder:!0,num:e.length};return e.push(t),n}if(Array.isArray(t)){const n=new Array(t.length);for(let r=0;r<t.length;r++)n[r]=_deconstructPacket(t[r],e);return n}if("object"==typeof t&&!(t instanceof Date)){const n={};for(const r in t)Object.prototype.hasOwnProperty.call(t,r)&&(n[r]=_deconstructPacket(t[r],e));return n}return t}function reconstructPacket(t,e){return t.data=_reconstructPacket(t.data,e),delete t.attachments,t}function _reconstructPacket(t,e){if(!t)return t;if(t&&!0===t._placeholder){if("number"==typeof t.num&&t.num>=0&&t.num<e.length)return e[t.num];throw new Error("illegal attachments")}if(Array.isArray(t))for(let n=0;n<t.length;n++)t[n]=_reconstructPacket(t[n],e);else if("object"==typeof t)for(const n in t)Object.prototype.hasOwnProperty.call(t,n)&&(t[n]=_reconstructPacket(t[n],e));return t}const RESERVED_EVENTS$1=["connect","connect_error","disconnect","disconnecting","newListener","removeListener"],protocol=5;var PacketType;!function(t){t[t.CONNECT=0]="CONNECT",t[t.DISCONNECT=1]="DISCONNECT",t[t.EVENT=2]="EVENT",t[t.ACK=3]="ACK",t[t.CONNECT_ERROR=4]="CONNECT_ERROR",t[t.BINARY_EVENT=5]="BINARY_EVENT",t[t.BINARY_ACK=6]="BINARY_ACK"}(PacketType||(PacketType={}));class Encoder{constructor(t){this.replacer=t}encode(t){return t.type!==PacketType.EVENT&&t.type!==PacketType.ACK||!hasBinary(t)?[this.encodeAsString(t)]:this.encodeAsBinary({type:t.type===PacketType.EVENT?PacketType.BINARY_EVENT:PacketType.BINARY_ACK,nsp:t.nsp,data:t.data,id:t.id})}encodeAsString(t){let e=""+t.type;return t.type!==PacketType.BINARY_EVENT&&t.type!==PacketType.BINARY_ACK||(e+=t.attachments+"-"),t.nsp&&"/"!==t.nsp&&(e+=t.nsp+","),null!=t.id&&(e+=t.id),null!=t.data&&(e+=JSON.stringify(t.data,this.replacer)),e}encodeAsBinary(t){const e=deconstructPacket(t),n=this.encodeAsString(e.packet),r=e.buffers;return r.unshift(n),r}}function isObject(t){return"[object Object]"===Object.prototype.toString.call(t)}class Decoder extends Emitter{constructor(t){super(),this.reviver=t}add(t){let e;if("string"==typeof t){if(this.reconstructor)throw new Error("got plaintext data when reconstructing a packet");e=this.decodeString(t);const n=e.type===PacketType.BINARY_EVENT;n||e.type===PacketType.BINARY_ACK?(e.type=n?PacketType.EVENT:PacketType.ACK,this.reconstructor=new BinaryReconstructor(e),0===e.attachments&&super.emitReserved("decoded",e)):super.emitReserved("decoded",e)}else{if(!isBinary(t)&&!t.base64)throw new Error("Unknown type: "+t);if(!this.reconstructor)throw new Error("got binary data when not reconstructing a packet");e=this.reconstructor.takeBinaryData(t),e&&(this.reconstructor=null,super.emitReserved("decoded",e))}}decodeString(t){let e=0;const n={type:Number(t.charAt(0))};if(void 0===PacketType[n.type])throw new Error("unknown packet type "+n.type);if(n.type===PacketType.BINARY_EVENT||n.type===PacketType.BINARY_ACK){const r=e+1;for(;"-"!==t.charAt(++e)&&e!=t.length;);const i=t.substring(r,e);if(i!=Number(i)||"-"!==t.charAt(e))throw new Error("Illegal attachments");n.attachments=Number(i)}if("/"===t.charAt(e+1)){const r=e+1;for(;++e&&","!==t.charAt(e)&&e!==t.length;);n.nsp=t.substring(r,e)}else n.nsp="/";const r=t.charAt(e+1);if(""!==r&&Number(r)==r){const r=e+1;for(;++e;){const n=t.charAt(e);if(null==n||Number(n)!=n){--e;break}if(e===t.length)break}n.id=Number(t.substring(r,e+1))}if(t.charAt(++e)){const r=this.tryParse(t.substr(e));if(!Decoder.isPayloadValid(n.type,r))throw new Error("invalid payload");n.data=r}return n}tryParse(t){try{return JSON.parse(t,this.reviver)}catch(t){return!1}}static isPayloadValid(t,e){switch(t){case PacketType.CONNECT:return isObject(e);case PacketType.DISCONNECT:return void 0===e;case PacketType.CONNECT_ERROR:return"string"==typeof e||isObject(e);case PacketType.EVENT:case PacketType.BINARY_EVENT:return Array.isArray(e)&&("number"==typeof e[0]||"string"==typeof e[0]&&-1===RESERVED_EVENTS$1.indexOf(e[0]));case PacketType.ACK:case PacketType.BINARY_ACK:return Array.isArray(e)}}destroy(){this.reconstructor&&(this.reconstructor.finishedReconstruction(),this.reconstructor=null)}}class BinaryReconstructor{constructor(t){this.packet=t,this.buffers=[],this.reconPack=t}takeBinaryData(t){if(this.buffers.push(t),this.buffers.length===this.reconPack.attachments){const t=reconstructPacket(this.reconPack,this.buffers);return this.finishedReconstruction(),t}return null}finishedReconstruction(){this.reconPack=null,this.buffers=[]}}var parser={__proto__:null,protocol,get PacketType(){return PacketType},Encoder,Decoder};function on(t,e,n){return t.on(e,n),function(){t.off(e,n)}}const RESERVED_EVENTS=Object.freeze({connect:1,connect_error:1,disconnect:1,disconnecting:1,newListener:1,removeListener:1});class Socket extends Emitter{constructor(t,e,n){super(),this.connected=!1,this.recovered=!1,this.receiveBuffer=[],this.sendBuffer=[],this._queue=[],this._queueSeq=0,this.ids=0,this.acks={},this.flags={},this.io=t,this.nsp=e,n&&n.auth&&(this.auth=n.auth),this._opts=Object.assign({},n),this.io._autoConnect&&this.open()}get disconnected(){return!this.connected}subEvents(){if(this.subs)return;const t=this.io;this.subs=[on(t,"open",this.onopen.bind(this)),on(t,"packet",this.onpacket.bind(this)),on(t,"error",this.onerror.bind(this)),on(t,"close",this.onclose.bind(this))]}get active(){return!!this.subs}connect(){return this.connected||(this.subEvents(),this.io._reconnecting||this.io.open(),"open"===this.io._readyState&&this.onopen()),this}open(){return this.connect()}send(...t){return t.unshift("message"),this.emit.apply(this,t),this}emit(t,...e){var n,r,i;if(RESERVED_EVENTS.hasOwnProperty(t))throw new Error('"'+t.toString()+'" is a reserved event name');if(e.unshift(t),this._opts.retries&&!this.flags.fromQueue&&!this.flags.volatile)return this._addToQueue(e),this;const s={type:PacketType.EVENT,data:e,options:{}};if(s.options.compress=!1!==this.flags.compress,"function"==typeof e[e.length-1]){const t=this.ids++,n=e.pop();this._registerAckCallback(t,n),s.id=t}const a=null===(r=null===(n=this.io.engine)||void 0===n?void 0:n.transport)||void 0===r?void 0:r.writable,o=this.connected&&!(null===(i=this.io.engine)||void 0===i?void 0:i._hasPingExpired());return this.flags.volatile&&!a||(o?(this.notifyOutgoingListeners(s),this.packet(s)):this.sendBuffer.push(s)),this.flags={},this}_registerAckCallback(t,e){var n;const r=null!==(n=this.flags.timeout)&&void 0!==n?n:this._opts.ackTimeout;if(void 0===r)return void(this.acks[t]=e);const i=this.io.setTimeoutFn(()=>{delete this.acks[t];for(let e=0;e<this.sendBuffer.length;e++)this.sendBuffer[e].id===t&&this.sendBuffer.splice(e,1);e.call(this,new Error("operation has timed out"))},r),s=(...t)=>{this.io.clearTimeoutFn(i),e.apply(this,t)};s.withError=!0,this.acks[t]=s}emitWithAck(t,...e){return new Promise((n,r)=>{const i=(t,e)=>t?r(t):n(e);i.withError=!0,e.push(i),this.emit(t,...e)})}_addToQueue(t){let e;"function"==typeof t[t.length-1]&&(e=t.pop());const n={id:this._queueSeq++,tryCount:0,pending:!1,args:t,flags:Object.assign({fromQueue:!0},this.flags)};t.push((t,...r)=>{if(n===this._queue[0])return null!==t?n.tryCount>this._opts.retries&&(this._queue.shift(),e&&e(t)):(this._queue.shift(),e&&e(null,...r)),n.pending=!1,this._drainQueue()}),this._queue.push(n),this._drainQueue()}_drainQueue(t=!1){if(!this.connected||0===this._queue.length)return;const e=this._queue[0];e.pending&&!t||(e.pending=!0,e.tryCount++,this.flags=e.flags,this.emit.apply(this,e.args))}packet(t){t.nsp=this.nsp,this.io._packet(t)}onopen(){"function"==typeof this.auth?this.auth(t=>{this._sendConnectPacket(t)}):this._sendConnectPacket(this.auth)}_sendConnectPacket(t){this.packet({type:PacketType.CONNECT,data:this._pid?Object.assign({pid:this._pid,offset:this._lastOffset},t):t})}onerror(t){this.connected||this.emitReserved("connect_error",t)}onclose(t,e){this.connected=!1,delete this.id,this.emitReserved("disconnect",t,e),this._clearAcks()}_clearAcks(){Object.keys(this.acks).forEach(t=>{if(!this.sendBuffer.some(e=>String(e.id)===t)){const e=this.acks[t];delete this.acks[t],e.withError&&e.call(this,new Error("socket has been disconnected"))}})}onpacket(t){if(t.nsp===this.nsp)switch(t.type){case PacketType.CONNECT:t.data&&t.data.sid?this.onconnect(t.data.sid,t.data.pid):this.emitReserved("connect_error",new Error("It seems you are trying to reach a Socket.IO server in v2.x with a v3.x client, but they are not compatible (more information here: https://socket.io/docs/v3/migrating-from-2-x-to-3-0/)"));break;case PacketType.EVENT:case PacketType.BINARY_EVENT:this.onevent(t);break;case PacketType.ACK:case PacketType.BINARY_ACK:this.onack(t);break;case PacketType.DISCONNECT:this.ondisconnect();break;case PacketType.CONNECT_ERROR:this.destroy();const e=new Error(t.data.message);e.data=t.data.data,this.emitReserved("connect_error",e)}}onevent(t){const e=t.data||[];null!=t.id&&e.push(this.ack(t.id)),this.connected?this.emitEvent(e):this.receiveBuffer.push(Object.freeze(e))}emitEvent(t){if(this._anyListeners&&this._anyListeners.length){const e=this._anyListeners.slice();for(const n of e)n.apply(this,t)}super.emit.apply(this,t),this._pid&&t.length&&"string"==typeof t[t.length-1]&&(this._lastOffset=t[t.length-1])}ack(t){const e=this;let n=!1;return function(...r){n||(n=!0,e.packet({type:PacketType.ACK,id:t,data:r}))}}onack(t){const e=this.acks[t.id];"function"==typeof e&&(delete this.acks[t.id],e.withError&&t.data.unshift(null),e.apply(this,t.data))}onconnect(t,e){this.id=t,this.recovered=e&&this._pid===e,this._pid=e,this.connected=!0,this.emitBuffered(),this.emitReserved("connect"),this._drainQueue(!0)}emitBuffered(){this.receiveBuffer.forEach(t=>this.emitEvent(t)),this.receiveBuffer=[],this.sendBuffer.forEach(t=>{this.notifyOutgoingListeners(t),this.packet(t)}),this.sendBuffer=[]}ondisconnect(){this.destroy(),this.onclose("io server disconnect")}destroy(){this.subs&&(this.subs.forEach(t=>t()),this.subs=void 0),this.io._destroy(this)}disconnect(){return this.connected&&this.packet({type:PacketType.DISCONNECT}),this.destroy(),this.connected&&this.onclose("io client disconnect"),this}close(){return this.disconnect()}compress(t){return this.flags.compress=t,this}get volatile(){return this.flags.volatile=!0,this}timeout(t){return this.flags.timeout=t,this}onAny(t){return this._anyListeners=this._anyListeners||[],this._anyListeners.push(t),this}prependAny(t){return this._anyListeners=this._anyListeners||[],this._anyListeners.unshift(t),this}offAny(t){if(!this._anyListeners)return this;if(t){const e=this._anyListeners;for(let n=0;n<e.length;n++)if(t===e[n])return e.splice(n,1),this}else this._anyListeners=[];return this}listenersAny(){return this._anyListeners||[]}onAnyOutgoing(t){return this._anyOutgoingListeners=this._anyOutgoingListeners||[],this._anyOutgoingListeners.push(t),this}prependAnyOutgoing(t){return this._anyOutgoingListeners=this._anyOutgoingListeners||[],this._anyOutgoingListeners.unshift(t),this}offAnyOutgoing(t){if(!this._anyOutgoingListeners)return this;if(t){const e=this._anyOutgoingListeners;for(let n=0;n<e.length;n++)if(t===e[n])return e.splice(n,1),this}else this._anyOutgoingListeners=[];return this}listenersAnyOutgoing(){return this._anyOutgoingListeners||[]}notifyOutgoingListeners(t){if(this._anyOutgoingListeners&&this._anyOutgoingListeners.length){const e=this._anyOutgoingListeners.slice();for(const n of e)n.apply(this,t.data)}}}function Backoff(t){this.ms=(t=t||{}).min||100,this.max=t.max||1e4,this.factor=t.factor||2,this.jitter=t.jitter>0&&t.jitter<=1?t.jitter:0,this.attempts=0}Backoff.prototype.duration=function(){var t=this.ms*Math.pow(this.factor,this.attempts++);if(this.jitter){var e=Math.random(),n=Math.floor(e*this.jitter*t);t=1&Math.floor(10*e)?t+n:t-n}return 0|Math.min(t,this.max)},Backoff.prototype.reset=function(){this.attempts=0},Backoff.prototype.setMin=function(t){this.ms=t},Backoff.prototype.setMax=function(t){this.max=t},Backoff.prototype.setJitter=function(t){this.jitter=t};class Manager extends Emitter{constructor(t,e){var n;super(),this.nsps={},this.subs=[],t&&"object"==typeof t&&(e=t,t=void 0),(e=e||{}).path=e.path||"/socket.io",this.opts=e,installTimerFunctions(this,e),this.reconnection(!1!==e.reconnection),this.reconnectionAttempts(e.reconnectionAttempts||Infinity),this.reconnectionDelay(e.reconnectionDelay||1e3),this.reconnectionDelayMax(e.reconnectionDelayMax||5e3),this.randomizationFactor(null!==(n=e.randomizationFactor)&&void 0!==n?n:.5),this.backoff=new Backoff({min:this.reconnectionDelay(),max:this.reconnectionDelayMax(),jitter:this.randomizationFactor()}),this.timeout(null==e.timeout?2e4:e.timeout),this._readyState="closed",this.uri=t;const r=e.parser||parser;this.encoder=new r.Encoder,this.decoder=new r.Decoder,this._autoConnect=!1!==e.autoConnect,this._autoConnect&&this.open()}reconnection(t){return arguments.length?(this._reconnection=!!t,t||(this.skipReconnect=!0),this):this._reconnection}reconnectionAttempts(t){return void 0===t?this._reconnectionAttempts:(this._reconnectionAttempts=t,this)}reconnectionDelay(t){var e;return void 0===t?this._reconnectionDelay:(this._reconnectionDelay=t,null===(e=this.backoff)||void 0===e||e.setMin(t),this)}randomizationFactor(t){var e;return void 0===t?this._randomizationFactor:(this._randomizationFactor=t,null===(e=this.backoff)||void 0===e||e.setJitter(t),this)}reconnectionDelayMax(t){var e;return void 0===t?this._reconnectionDelayMax:(this._reconnectionDelayMax=t,null===(e=this.backoff)||void 0===e||e.setMax(t),this)}timeout(t){return arguments.length?(this._timeout=t,this):this._timeout}maybeReconnectOnOpen(){!this._reconnecting&&this._reconnection&&0===this.backoff.attempts&&this.reconnect()}open(t){if(~this._readyState.indexOf("open"))return this;this.engine=new Socket$1(this.uri,this.opts);const e=this.engine,n=this;this._readyState="opening",this.skipReconnect=!1;const r=on(e,"open",function(){n.onopen(),t&&t()}),i=e=>{this.cleanup(),this._readyState="closed",this.emitReserved("error",e),t?t(e):this.maybeReconnectOnOpen()},s=on(e,"error",i);if(!1!==this._timeout){const t=this.setTimeoutFn(()=>{r(),i(new Error("timeout")),e.close()},this._timeout);this.opts.autoUnref&&t.unref(),this.subs.push(()=>{this.clearTimeoutFn(t)})}return this.subs.push(r),this.subs.push(s),this}connect(t){return this.open(t)}onopen(){this.cleanup(),this._readyState="open",this.emitReserved("open");const t=this.engine;this.subs.push(on(t,"ping",this.onping.bind(this)),on(t,"data",this.ondata.bind(this)),on(t,"error",this.onerror.bind(this)),on(t,"close",this.onclose.bind(this)),on(this.decoder,"decoded",this.ondecoded.bind(this)))}onping(){this.emitReserved("ping")}ondata(t){try{this.decoder.add(t)}catch(t){this.onclose("parse error",t)}}ondecoded(t){nextTick(()=>{this.emitReserved("packet",t)},this.setTimeoutFn)}onerror(t){this.emitReserved("error",t)}socket(t,e){let n=this.nsps[t];return n?this._autoConnect&&!n.active&&n.connect():(n=new Socket(this,t,e),this.nsps[t]=n),n}_destroy(t){const e=Object.keys(this.nsps);for(const t of e)if(this.nsps[t].active)return;this._close()}_packet(t){const e=this.encoder.encode(t);for(let n=0;n<e.length;n++)this.engine.write(e[n],t.options)}cleanup(){this.subs.forEach(t=>t()),this.subs.length=0,this.decoder.destroy()}_close(){this.skipReconnect=!0,this._reconnecting=!1,this.onclose("forced close")}disconnect(){return this._close()}onclose(t,e){var n;this.cleanup(),null===(n=this.engine)||void 0===n||n.close(),this.backoff.reset(),this._readyState="closed",this.emitReserved("close",t,e),this._reconnection&&!this.skipReconnect&&this.reconnect()}reconnect(){if(this._reconnecting||this.skipReconnect)return this;const t=this;if(this.backoff.attempts>=this._reconnectionAttempts)this.backoff.reset(),this.emitReserved("reconnect_failed"),this._reconnecting=!1;else{const e=this.backoff.duration();this._reconnecting=!0;const n=this.setTimeoutFn(()=>{t.skipReconnect||(this.emitReserved("reconnect_attempt",t.backoff.attempts),t.skipReconnect||t.open(e=>{e?(t._reconnecting=!1,t.reconnect(),this.emitReserved("reconnect_error",e)):t.onreconnect()}))},e);this.opts.autoUnref&&n.unref(),this.subs.push(()=>{this.clearTimeoutFn(n)})}}onreconnect(){const t=this.backoff.attempts;this._reconnecting=!1,this.backoff.reset(),this.emitReserved("reconnect",t)}}const cache={};function lookup(t,e){"object"==typeof t&&(e=t,t=void 0);const n=url(t,(e=e||{}).path||"/socket.io"),r=n.source,i=n.id;let s;return e.forceNew||e["force new connection"]||!1===e.multiplex||cache[i]&&n.path in cache[i].nsps?s=new Manager(r,e):(cache[i]||(cache[i]=new Manager(r,e)),s=cache[i]),n.query&&!e.query&&(e.query=n.queryKey),s.socket(n.path,e)}var $protobuf,$Reader,$Writer,$util,$root;Object.assign(lookup,{Manager,Socket,io:lookup,connect:lookup}),function(rt){var r,e,i;r={1:[function(t,e,n){e.exports=function(t,e){for(var n=Array(arguments.length-1),r=0,i=2,s=!0;i<arguments.length;)n[r++]=arguments[i++];return new Promise(function(i,a){n[r]=function(t){if(s)if(s=!1,t)a(t);else{for(var e=Array(arguments.length-1),n=0;n<e.length;)e[n++]=arguments[n];i.apply(null,e)}};try{t.apply(e||null,n)}catch(t){s&&(s=!1,a(t))}})}},{}],2:[function(t,e,n){n.length=function(t){var e=t.length;if(!e)return 0;for(var n=0;1<--e%4&&"="==(t[0|e]||"");)++n;return Math.ceil(3*t.length)/4-n};for(var r=Array(64),i=Array(123),s=0;s<64;)i[r[s]=s<26?s+65:s<52?s+71:s<62?s-4:s-59|43]=s++;n.encode=function(t,e,n){for(var i,s=null,a=[],o=0,l=0;e<n;){var c=t[e++];switch(l){case 0:a[o++]=r[c>>2],i=(3&c)<<4,l=1;break;case 1:a[o++]=r[i|c>>4],i=(15&c)<<2,l=2;break;case 2:a[o++]=r[i|c>>6],a[o++]=r[63&c],l=0}8191<o&&((s=s||[]).push(String.fromCharCode.apply(String,a)),o=0)}return l&&(a[o++]=r[i],a[o++]=61,1===l&&(a[o++]=61)),s?(o&&s.push(String.fromCharCode.apply(String,a.slice(0,o))),s.join("")):String.fromCharCode.apply(String,a.slice(0,o))};var a="invalid encoding";n.decode=function(t,e,n){for(var r,s=n,o=0,l=0;l<t.length;){var c=t.charCodeAt(l++);if(61==c&&1<o)break;if((c=i[c])===rt)throw Error(a);switch(o){case 0:r=c,o=1;break;case 1:e[n++]=r<<2|(48&c)>>4,r=c,o=2;break;case 2:e[n++]=(15&r)<<4|(60&c)>>2,r=c,o=3;break;case 3:e[n++]=(3&r)<<6|c,o=0}}if(1===o)throw Error(a);return n-s},n.test=function(t){return/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/.test(t)}},{}],3:[function(t,e,n){(e.exports=function t(e,n){"string"==typeof e&&(n=e,e=rt);var r=[];function i(e){if("string"!=typeof e){var n=s();if(t.verbose&&console.log("codegen: "+n),n="return "+n,e){for(var a=Object.keys(e),o=Array(a.length+1),l=Array(a.length),c=0;c<a.length;)o[c]=a[c],l[c]=e[a[c++]];return o[c]=n,Function.apply(null,o).apply(null,l)}return Function(n)()}for(var d=Array(arguments.length-1),h=0;h<d.length;)d[h]=arguments[++h];if(h=0,e=e.replace(/%([%dfijs])/g,function(t,e){var n=d[h++];switch(e){case"d":case"f":return""+ +(""+n);case"i":return""+Math.floor(n);case"j":return JSON.stringify(n);case"s":return""+n}return"%"}),h!==d.length)throw Error("parameter count mismatch");return r.push(e),i}function s(t){return"function "+(t||n||"")+"("+(e&&e.join(",")||"")+"){\n "+r.join("\n ")+"\n}"}return i.toString=s,i}).verbose=!1},{}],4:[function(t,e,n){function r(){this.i={}}(e.exports=r).prototype.on=function(t,e,n){return(this.i[t]||(this.i[t]=[])).push({fn:e,ctx:n||this}),this},r.prototype.off=function(t,e){if(t===rt)this.i={};else if(e===rt)this.i[t]=[];else for(var n=this.i[t],r=0;r<n.length;)n[r].fn===e?n.splice(r,1):++r;return this},r.prototype.emit=function(t){var e=this.i[t];if(e){for(var n=[],r=1;r<arguments.length;)n.push(arguments[r++]);for(r=0;r<e.length;)e[r].fn.apply(e[r++].ctx,n)}return this}},{}],5:[function(t,e,n){e.exports=s;var r=t(1),i=t(7)("fs");function s(t,e,n){return e="function"==typeof e?(n=e,{}):e||{},n?!e.xhr&&i&&i.readFile?i.readFile(t,function(r,i){return r&&"undefined"!=typeof XMLHttpRequest?s.xhr(t,e,n):r?n(r):n(null,e.binary?i:i.toString("utf8"))}):s.xhr(t,e,n):r(s,this,t,e)}s.xhr=function(t,e,n){var r=new XMLHttpRequest;r.onreadystatechange=function(){if(4!==r.readyState)return rt;if(0!==r.status&&200!==r.status)return n(Error("status "+r.status));if(e.binary){if(!(t=r.response))for(var t=[],i=0;i<r.responseText.length;++i)t.push(255&r.responseText.charCodeAt(i));return n(null,"undefined"!=typeof Uint8Array?new Uint8Array(t):t)}return n(null,r.responseText)},e.binary&&("overrideMimeType"in r&&r.overrideMimeType("text/plain; charset=x-user-defined"),r.responseType="arraybuffer"),r.open("GET",t),r.send()}},{1:1,7:7}],6:[function(t,e,n){function r(t){function e(t,e,n,r){var i=e<0?1:0;t(0===(e=i?-e:e)?0<1/e?0:2147483648:isNaN(e)?2143289344:34028234663852886e22<e?(i<<31|2139095040)>>>0:e<11754943508222875e-54?(i<<31|Math.round(e/1401298464324817e-60))>>>0:(i<<31|127+(t=Math.floor(Math.log(e)/Math.LN2))<<23|8388607&Math.round(e*Math.pow(2,-t)*8388608))>>>0,n,r)}function n(t,e,n){return e=2*((t=t(e,n))>>31)+1,n=t>>>23&255,t&=8388607,255==n?t?NaN:1/0*e:0==n?1401298464324817e-60*e*t:e*Math.pow(2,n-150)*(8388608+t)}function r(t,e,n){h[0]=t,e[n]=u[0],e[n+1]=u[1],e[n+2]=u[2],e[n+3]=u[3]}function l(t,e,n){h[0]=t,e[n]=u[3],e[n+1]=u[2],e[n+2]=u[1],e[n+3]=u[0]}function c(t,e){return u[0]=t[e],u[1]=t[e+1],u[2]=t[e+2],u[3]=t[e+3],h[0]}function d(t,e){return u[3]=t[e],u[2]=t[e+1],u[1]=t[e+2],u[0]=t[e+3],h[0]}var h,u,p,f,m;function _(t,e,n,r,i,s){var a,o=r<0?1:0;0===(r=o?-r:r)?(t(0,i,s+e),t(0<1/r?0:2147483648,i,s+n)):isNaN(r)?(t(0,i,s+e),t(2146959360,i,s+n)):17976931348623157e292<r?(t(0,i,s+e),t((o<<31|2146435072)>>>0,i,s+n)):r<22250738585072014e-324?(t((a=r/5e-324)>>>0,i,s+e),t((o<<31|a/4294967296)>>>0,i,s+n)):(t(4503599627370496*(a=r*Math.pow(2,-(r=1024===(r=Math.floor(Math.log(r)/Math.LN2))?1023:r)))>>>0,i,s+e),t((o<<31|r+1023<<20|1048576*a&1048575)>>>0,i,s+n))}function g(t,e,n,r,i){return e=t(r,i+e),r=2*((t=t(r,i+n))>>31)+1,n=4294967296*(1048575&t)+e,2047==(i=t>>>20&2047)?n?NaN:1/0*r:0==i?5e-324*r*n:r*Math.pow(2,i-1075)*(n+4503599627370496)}function y(t,e,n){p[0]=t,e[n]=f[0],e[n+1]=f[1],e[n+2]=f[2],e[n+3]=f[3],e[n+4]=f[4],e[n+5]=f[5],e[n+6]=f[6],e[n+7]=f[7]}function S(t,e,n){p[0]=t,e[n]=f[7],e[n+1]=f[6],e[n+2]=f[5],e[n+3]=f[4],e[n+4]=f[3],e[n+5]=f[2],e[n+6]=f[1],e[n+7]=f[0]}function A(t,e){return f[0]=t[e],f[1]=t[e+1],f[2]=t[e+2],f[3]=t[e+3],f[4]=t[e+4],f[5]=t[e+5],f[6]=t[e+6],f[7]=t[e+7],p[0]}function v(t,e){return f[7]=t[e],f[6]=t[e+1],f[5]=t[e+2],f[4]=t[e+3],f[3]=t[e+4],f[2]=t[e+5],f[1]=t[e+6],f[0]=t[e+7],p[0]}return"undefined"!=typeof Float32Array?(h=new Float32Array([-0]),u=new Uint8Array(h.buffer),t.writeFloatLE=(m=128===u[3])?r:l,t.writeFloatBE=m?l:r,t.readFloatLE=m?c:d,t.readFloatBE=m?d:c):(t.writeFloatLE=e.bind(null,i),t.writeFloatBE=e.bind(null,s),t.readFloatLE=n.bind(null,a),t.readFloatBE=n.bind(null,o)),"undefined"!=typeof Float64Array?(p=new Float64Array([-0]),f=new Uint8Array(p.buffer),t.writeDoubleLE=(m=128===f[7])?y:S,t.writeDoubleBE=m?S:y,t.readDoubleLE=m?A:v,t.readDoubleBE=m?v:A):(t.writeDoubleLE=_.bind(null,i,0,4),t.writeDoubleBE=_.bind(null,s,4,0),t.readDoubleLE=g.bind(null,a,0,4),t.readDoubleBE=g.bind(null,o,4,0)),t}function i(t,e,n){e[n]=255&t,e[n+1]=t>>>8&255,e[n+2]=t>>>16&255,e[n+3]=t>>>24}function s(t,e,n){e[n]=t>>>24,e[n+1]=t>>>16&255,e[n+2]=t>>>8&255,e[n+3]=255&t}function a(t,e){return(t[e]|t[e+1]<<8|t[e+2]<<16|t[e+3]<<24)>>>0}function o(t,e){return(t[e]<<24|t[e+1]<<16|t[e+2]<<8|t[e+3])>>>0}e.exports=r(r)},{}],7:[function(t,i,n){function r(t){try{var i=eval("require")(t);if(i&&(i.length||Object.keys(i).length))return i}catch(t){}return null}i.exports=r},{}],8:[function(t,e,n){var r=n.isAbsolute=function(t){return/^(?:\/|\w+:)/.test(t)},i=n.normalize=function(t){var e=(t=t.replace(/\\/g,"/").replace(/\/{2,}/g,"/")).split("/"),n=r(t);t="",n&&(t=e.shift()+"/");for(var i=0;i<e.length;)".."===e[i]?0<i&&".."!==e[i-1]?e.splice(--i,2):n?e.splice(i,1):++i:"."===e[i]?e.splice(i,1):++i;return t+e.join("/")};n.resolve=function(t,e,n){return n||(e=i(e)),!r(e)&&(t=(t=n?t:i(t)).replace(/(?:\/|^)[^/]+$/,"")).length?i(t+"/"+e):e}},{}],9:[function(t,e,n){e.exports=function(t,e,n){var r=n||8192,i=r>>>1,s=null,a=r;return function(n){return n<1||i<n?t(n):(r<a+n&&(s=t(r),a=0),n=e.call(s,a,a+=n),7&a&&(a=1+(7|a)),n)}}},{}],10:[function(t,e,n){n.length=function(t){for(var e,n=0,r=0;r<t.length;++r)(e=t.charCodeAt(r))<128?n+=1:e<2048?n+=2:55296==(64512&e)&&56320==(64512&t.charCodeAt(r+1))?(++r,n+=4):n+=3;return n},n.read=function(t,e,n){if(n-e<1)return"";for(var r,i=null,s=[],a=0;e<n;)(r=t[e++])<128?s[a++]=r:191<r&&r<224?s[a++]=(31&r)<<6|63&t[e++]:239<r&&r<365?(r=((7&r)<<18|(63&t[e++])<<12|(63&t[e++])<<6|63&t[e++])-65536,s[a++]=55296+(r>>10),s[a++]=56320+(1023&r)):s[a++]=(15&r)<<12|(63&t[e++])<<6|63&t[e++],8191<a&&((i=i||[]).push(String.fromCharCode.apply(String,s)),a=0);return i?(a&&i.push(String.fromCharCode.apply(String,s.slice(0,a))),i.join("")):String.fromCharCode.apply(String,s.slice(0,a))},n.write=function(t,e,n){for(var r,i,s=n,a=0;a<t.length;++a)(r=t.charCodeAt(a))<128?e[n++]=r:(r<2048?e[n++]=r>>6|192:(55296==(64512&r)&&56320==(64512&(i=t.charCodeAt(a+1)))?(++a,e[n++]=(r=65536+((1023&r)<<10)+(1023&i))>>18|240,e[n++]=r>>12&63|128):e[n++]=r>>12|224,e[n++]=r>>6&63|128),e[n++]=63&r|128);return n-s}},{}],11:[function(t,e,n){e.exports=i;var r=/\/|\./;function i(t,e){r.test(t)||(t="google/protobuf/"+t+".proto",e={nested:{google:{nested:{protobuf:{nested:e}}}}}),i[t]=e}i("any",{Any:{fields:{type_url:{type:"string",id:1},value:{type:"bytes",id:2}}}}),i("duration",{Duration:e={fields:{seconds:{type:"int64",id:1},nanos:{type:"int32",id:2}}}}),i("timestamp",{Timestamp:e}),i("empty",{Empty:{fields:{}}}),i("struct",{Struct:{fields:{fields:{keyType:"string",type:"Value",id:1}}},Value:{oneofs:{kind:{oneof:["nullValue","numberValue","stringValue","boolValue","structValue","listValue"]}},fields:{nullValue:{type:"NullValue",id:1},numberValue:{type:"double",id:2},stringValue:{type:"string",id:3},boolValue:{type:"bool",id:4},structValue:{type:"Struct",id:5},listValue:{type:"ListValue",id:6}}},NullValue:{values:{NULL_VALUE:0}},ListValue:{fields:{values:{rule:"repeated",type:"Value",id:1}}}}),i("wrappers",{DoubleValue:{fields:{value:{type:"double",id:1}}},FloatValue:{fields:{value:{type:"float",id:1}}},Int64Value:{fields:{value:{type:"int64",id:1}}},UInt64Value:{fields:{value:{type:"uint64",id:1}}},Int32Value:{fields:{value:{type:"int32",id:1}}},UInt32Value:{fields:{value:{type:"uint32",id:1}}},BoolValue:{fields:{value:{type:"bool",id:1}}},StringValue:{fields:{value:{type:"string",id:1}}},BytesValue:{fields:{value:{type:"bytes",id:1}}}}),i("field_mask",{FieldMask:{fields:{paths:{rule:"repeated",type:"string",id:1}}}}),i.get=function(t){return i[t]||null}},{}],12:[function(t,e,n){var r=t(15),i=t(37);function s(t,e,n,i){var s=!1;if(e.resolvedType)if(e.resolvedType instanceof r){t("switch(d%s){",i);for(var a=e.resolvedType.values,o=Object.keys(a),l=0;l<o.length;++l)a[o[l]]!==e.typeDefault||s||(t("default:")('if(typeof(d%s)==="number"){m%s=d%s;break}',i,i,i),e.repeated||t("break"),s=!0),t("case%j:",o[l])("case %i:",a[o[l]])("m%s=%j",i,a[o[l]])("break");t("}")}else t('if(typeof d%s!=="object")',i)("throw TypeError(%j)",e.fullName+": object expected")("m%s=types[%i].fromObject(d%s)",i,n,i);else{var c=!1;switch(e.type){case"double":case"float":t("m%s=Number(d%s)",i,i);break;case"uint32":case"fixed32":t("m%s=d%s>>>0",i,i);break;case"int32":case"sint32":case"sfixed32":t("m%s=d%s|0",i,i);break;case"uint64":c=!0;case"int64":case"sint64":case"fixed64":case"sfixed64":t("if(util.Long)")("(m%s=util.Long.fromValue(d%s)).unsigned=%j",i,i,c)('else if(typeof d%s==="string")',i)("m%s=parseInt(d%s,10)",i,i)('else if(typeof d%s==="number")',i)("m%s=d%s",i,i)('else if(typeof d%s==="object")',i)("m%s=new util.LongBits(d%s.low>>>0,d%s.high>>>0).toNumber(%s)",i,i,i,c?"true":"");break;case"bytes":t('if(typeof d%s==="string")',i)("util.base64.decode(d%s,m%s=util.newBuffer(util.base64.length(d%s)),0)",i,i,i)("else if(d%s.length >= 0)",i)("m%s=d%s",i,i);break;case"string":t("m%s=String(d%s)",i,i);break;case"bool":t("m%s=Boolean(d%s)",i,i)}}return t}function a(t,e,n,i){if(e.resolvedType)e.resolvedType instanceof r?t("d%s=o.enums===String?(types[%i].values[m%s]===undefined?m%s:types[%i].values[m%s]):m%s",i,n,i,i,n,i,i):t("d%s=types[%i].toObject(m%s,o)",i,n,i);else{var s=!1;switch(e.type){case"double":case"float":t("d%s=o.json&&!isFinite(m%s)?String(m%s):m%s",i,i,i,i);break;case"uint64":s=!0;case"int64":case"sint64":case"fixed64":case"sfixed64":t('if(typeof m%s==="number")',i)("d%s=o.longs===String?String(m%s):m%s",i,i,i)("else")("d%s=o.longs===String?util.Long.prototype.toString.call(m%s):o.longs===Number?new util.LongBits(m%s.low>>>0,m%s.high>>>0).toNumber(%s):m%s",i,i,i,i,s?"true":"",i);break;case"bytes":t("d%s=o.bytes===String?util.base64.encode(m%s,0,m%s.length):o.bytes===Array?Array.prototype.slice.call(m%s):m%s",i,i,i,i,i);break;default:t("d%s=m%s",i,i)}}return t}n.fromObject=function(t){var e=t.fieldsArray,n=i.codegen(["d"],t.name+"$fromObject")("if(d instanceof this.ctor)")("return d");if(!e.length)return n("return new this.ctor");n("var m=new this.ctor");for(var a=0;a<e.length;++a){var o=e[a].resolve(),l=i.safeProp(o.name);o.map?(n("if(d%s){",l)('if(typeof d%s!=="object")',l)("throw TypeError(%j)",o.fullName+": object expected")("m%s={}",l)("for(var ks=Object.keys(d%s),i=0;i<ks.length;++i){",l),s(n,o,a,l+"[ks[i]]")("}")("}")):o.repeated?(n("if(d%s){",l)("if(!Array.isArray(d%s))",l)("throw TypeError(%j)",o.fullName+": array expected")("m%s=[]",l)("for(var i=0;i<d%s.length;++i){",l),s(n,o,a,l+"[i]")("}")("}")):(o.resolvedType instanceof r||n("if(d%s!=null){",l),s(n,o,a,l),o.resolvedType instanceof r||n("}"))}return n("return m")},n.toObject=function(t){var e=t.fieldsArray.slice().sort(i.compareFieldsById);if(!e.length)return i.codegen()("return {}");for(var n=i.codegen(["m","o"],t.name+"$toObject")("if(!o)")("o={}")("var d={}"),s=[],o=[],l=[],c=0;c<e.length;++c)e[c].partOf||(e[c].resolve().repeated?s:e[c].map?o:l).push(e[c]);if(s.length){for(n("if(o.arrays||o.defaults){"),c=0;c<s.length;++c)n("d%s=[]",i.safeProp(s[c].name));n("}")}if(o.length){for(n("if(o.objects||o.defaults){"),c=0;c<o.length;++c)n("d%s={}",i.safeProp(o[c].name));n("}")}if(l.length){for(n("if(o.defaults){"),c=0;c<l.length;++c){var d,h=i.safeProp((p=l[c]).name);p.resolvedType instanceof r?n("d%s=o.enums===String?%j:%j",h,p.resolvedType.valuesById[p.typeDefault],p.typeDefault):p.long?n("if(util.Long){")("var n=new util.Long(%i,%i,%j)",p.typeDefault.low,p.typeDefault.high,p.typeDefault.unsigned)("d%s=o.longs===String?n.toString():o.longs===Number?n.toNumber():n",h)("}else")("d%s=o.longs===String?%j:%i",h,p.typeDefault.toString(),p.typeDefault.toNumber()):p.bytes?(d="["+Array.prototype.slice.call(p.typeDefault).join(",")+"]",n("if(o.bytes===String)d%s=%j",h,String.fromCharCode.apply(String,p.typeDefault))("else{")("d%s=%s",h,d)("if(o.bytes!==Array)d%s=util.newBuffer(d%s)",h,h)("}")):n("d%s=%j",h,p.typeDefault)}n("}")}var u=!1;for(c=0;c<e.length;++c){var p,f=t.e.indexOf(p=e[c]);h=i.safeProp(p.name),p.map?(u||(u=!0,n("var ks2")),n("if(m%s&&(ks2=Object.keys(m%s)).length){",h,h)("d%s={}",h)("for(var j=0;j<ks2.length;++j){"),a(n,p,f,h+"[ks2[j]]")("}")):p.repeated?(n("if(m%s&&m%s.length){",h,h)("d%s=[]",h)("for(var j=0;j<m%s.length;++j){",h),a(n,p,f,h+"[j]")("}")):(n("if(m%s!=null&&m.hasOwnProperty(%j)){",h,p.name),a(n,p,f,h),p.partOf&&n("if(o.oneofs)")("d%s=%j",i.safeProp(p.partOf.name),p.name)),n("}")}return n("return d")}},{15:15,37:37}],13:[function(t,e,n){e.exports=function(t){for(var e=s.codegen(["r","l","e"],t.name+"$decode")("if(!(r instanceof Reader))")("r=Reader.create(r)")("var c=l===undefined?r.len:r.pos+l,m=new this.ctor"+(t.fieldsArray.filter(function(t){return t.map}).length?",k,value":""))("while(r.pos<c){")("var t=r.uint32()")("if(t===e)")("break")("switch(t>>>3){"),n=0;n<t.fieldsArray.length;++n){var a=t.e[n].resolve(),o=a.resolvedType instanceof r?"int32":a.type,l="m"+s.safeProp(a.name);e("case %i: {",a.id),a.map?(e("if(%s===util.emptyObject)",l)("%s={}",l)("var c2 = r.uint32()+r.pos"),i.defaults[a.keyType]!==rt?e("k=%j",i.defaults[a.keyType]):e("k=null"),i.defaults[o]!==rt?e("value=%j",i.defaults[o]):e("value=null"),e("while(r.pos<c2){")("var tag2=r.uint32()")("switch(tag2>>>3){")("case 1: k=r.%s(); break",a.keyType)("case 2:"),i.basic[o]===rt?e("value=types[%i].decode(r,r.uint32())",n):e("value=r.%s()",o),e("break")("default:")("r.skipType(tag2&7)")("break")("}")("}"),e(i.long[a.keyType]!==rt?'%s[typeof k==="object"?util.longToHash(k):k]=value':"%s[k]=value",l)):a.repeated?(e("if(!(%s&&%s.length))",l,l)("%s=[]",l),i.packed[o]!==rt&&e("if((t&7)===2){")("var c2=r.uint32()+r.pos")("while(r.pos<c2)")("%s.push(r.%s())",l,o)("}else"),i.basic[o]===rt?e(a.delimited?"%s.push(types[%i].decode(r,undefined,((t&~7)|4)))":"%s.push(types[%i].decode(r,r.uint32()))",l,n):e("%s.push(r.%s())",l,o)):i.basic[o]===rt?e(a.delimited?"%s=types[%i].decode(r,undefined,((t&~7)|4))":"%s=types[%i].decode(r,r.uint32())",l,n):e("%s=r.%s()",l,o),e("break")("}")}for(e("default:")("r.skipType(t&7)")("break")("}")("}"),n=0;n<t.e.length;++n){var c=t.e[n];c.required&&e("if(!m.hasOwnProperty(%j))",c.name)("throw util.ProtocolError(%j,{instance:m})","missing required '"+c.name+"'")}return e("return m")};var r=t(15),i=t(36),s=t(37)},{15:15,36:36,37:37}],14:[function(t,e,n){e.exports=function(t){for(var e,n=s.codegen(["m","w"],t.name+"$encode")("if(!w)")("w=Writer.create()"),o=t.fieldsArray.slice().sort(s.compareFieldsById),l=0;l<o.length;++l){var c=o[l].resolve(),d=t.e.indexOf(c),h=c.resolvedType instanceof r?"int32":c.type,u=i.basic[h];e="m"+s.safeProp(c.name),c.map?(n("if(%s!=null&&Object.hasOwnProperty.call(m,%j)){",e,c.name)("for(var ks=Object.keys(%s),i=0;i<ks.length;++i){",e)("w.uint32(%i).fork().uint32(%i).%s(ks[i])",(c.id<<3|2)>>>0,8|i.mapKey[c.keyType],c.keyType),u===rt?n("types[%i].encode(%s[ks[i]],w.uint32(18).fork()).ldelim().ldelim()",d,e):n(".uint32(%i).%s(%s[ks[i]]).ldelim()",16|u,h,e),n("}")("}")):c.repeated?(n("if(%s!=null&&%s.length){",e,e),c.packed&&i.packed[h]!==rt?n("w.uint32(%i).fork()",(c.id<<3|2)>>>0)("for(var i=0;i<%s.length;++i)",e)("w.%s(%s[i])",h,e)("w.ldelim()"):(n("for(var i=0;i<%s.length;++i)",e),u===rt?a(n,c,d,e+"[i]"):n("w.uint32(%i).%s(%s[i])",(c.id<<3|u)>>>0,h,e)),n("}")):(c.optional&&n("if(%s!=null&&Object.hasOwnProperty.call(m,%j))",e,c.name),u===rt?a(n,c,d,e):n("w.uint32(%i).%s(%s)",(c.id<<3|u)>>>0,h,e))}return n("return w")};var r=t(15),i=t(36),s=t(37);function a(t,e,n,r){e.delimited?t("types[%i].encode(%s,w.uint32(%i)).uint32(%i)",n,r,(e.id<<3|3)>>>0,(e.id<<3|4)>>>0):t("types[%i].encode(%s,w.uint32(%i).fork()).ldelim()",n,r,(e.id<<3|2)>>>0)}},{15:15,36:36,37:37}],15:[function(t,e,n){e.exports=a;var r=t(24),i=(((a.prototype=Object.create(r.prototype)).constructor=a).className="Enum",t(23)),s=t(37);function a(t,e,n,i,s,a){if(r.call(this,t,n),e&&"object"!=typeof e)throw TypeError("values must be an object");if(this.valuesById={},this.values=Object.create(this.valuesById),this.comment=i,this.comments=s||{},this.valuesOptions=a,this.o={},this.reserved=rt,e)for(var o=Object.keys(e),l=0;l<o.length;++l)"number"==typeof e[o[l]]&&(this.valuesById[this.values[o[l]]=e[o[l]]]=o[l])}a.prototype.u=function(t){return r.prototype.u.call(this,t=this.f||t),Object.keys(this.values).forEach(t=>{var e=Object.assign({},this.h);this.o[t]=Object.assign(e,this.valuesOptions&&this.valuesOptions[t]&&this.valuesOptions[t].features)}),this},a.fromJSON=function(t,e){return(t=new a(t,e.values,e.options,e.comment,e.comments)).reserved=e.reserved,e.edition&&(t.f=e.edition),t.a="proto3",t},a.prototype.toJSON=function(t){return t=!!t&&!!t.keepComments,s.toObject(["edition",this.c(),"options",this.options,"valuesOptions",this.valuesOptions,"values",this.values,"reserved",this.reserved&&this.reserved.length?this.reserved:rt,"comment",t?this.comment:rt,"comments",t?this.comments:rt])},a.prototype.add=function(t,e,n,r){if(!s.isString(t))throw TypeError("name must be a string");if(!s.isInteger(e))throw TypeError("id must be an integer");if(this.values[t]!==rt)throw Error("duplicate name '"+t+"' in "+this);if(this.isReservedId(e))throw Error("id "+e+" is reserved in "+this);if(this.isReservedName(t))throw Error("name '"+t+"' is reserved in "+this);if(this.valuesById[e]!==rt){if(!this.options||!this.options.allow_alias)throw Error("duplicate id "+e+" in "+this);this.values[t]=e}else this.valuesById[this.values[t]=e]=t;return r&&(this.valuesOptions===rt&&(this.valuesOptions={}),this.valuesOptions[t]=r||null),this.comments[t]=n||null,this},a.prototype.remove=function(t){if(!s.isString(t))throw TypeError("name must be a string");var e=this.values[t];if(null==e)throw Error("name '"+t+"' does not exist in "+this);return delete this.valuesById[e],delete this.values[t],delete this.comments[t],this.valuesOptions&&delete this.valuesOptions[t],this},a.prototype.isReservedId=function(t){return i.isReservedId(this.reserved,t)},a.prototype.isReservedName=function(t){return i.isReservedName(this.reserved,t)}},{23:23,24:24,37:37}],16:[function(t,e,n){e.exports=c;var r,i=t(24),s=(((c.prototype=Object.create(i.prototype)).constructor=c).className="Field",t(15)),a=t(36),o=t(37),l=/^required|optional|repeated$/;function c(t,e,n,r,s,c,d){if(o.isObject(r)?(d=s,c=r,r=s=rt):o.isObject(s)&&(d=c,c=s,s=rt),i.call(this,t,c),!o.isInteger(e)||e<0)throw TypeError("id must be a non-negative integer");if(!o.isString(n))throw TypeError("type must be a string");if(r!==rt&&!l.test(r=r.toString().toLowerCase()))throw TypeError("rule must be a string rule");if(s!==rt&&!o.isString(s))throw TypeError("extend must be a string");this.rule=(r="proto3_optional"===r?"optional":r)&&"optional"!==r?r:rt,this.type=n,this.id=e,this.extend=s||rt,this.repeated="repeated"===r,this.map=!1,this.message=null,this.partOf=null,this.typeDefault=null,this.defaultValue=null,this.long=!!o.Long&&a.long[n]!==rt,this.bytes="bytes"===n,this.resolvedType=null,this.extensionField=null,this.declaringField=null,this.comment=d}c.fromJSON=function(t,e){return t=new c(t,e.id,e.type,e.rule,e.extend,e.options,e.comment),e.edition&&(t.f=e.edition),t.a="proto3",t},Object.defineProperty(c.prototype,"required",{get:function(){return"LEGACY_REQUIRED"===this.h.field_presence}}),Object.defineProperty(c.prototype,"optional",{get:function(){return!this.required}}),Object.defineProperty(c.prototype,"delimited",{get:function(){return this.resolvedType instanceof r&&"DELIMITED"===this.h.message_encoding}}),Object.defineProperty(c.prototype,"packed",{get:function(){return"PACKED"===this.h.repeated_field_encoding}}),Object.defineProperty(c.prototype,"hasPresence",{get:function(){return!this.repeated&&!this.map&&(this.partOf||this.declaringField||this.extensionField||"IMPLICIT"!==this.h.field_presence)}}),c.prototype.setOption=function(t,e,n){return i.prototype.setOption.call(this,t,e,n)},c.prototype.toJSON=function(t){return t=!!t&&!!t.keepComments,o.toObject(["edition",this.c(),"rule","optional"!==this.rule&&this.rule||rt,"type",this.type,"id",this.id,"extend",this.extend,"options",this.options,"comment",t?this.comment:rt])},c.prototype.resolve=function(){var t;return this.resolved?this:((this.typeDefault=a.defaults[this.type])===rt?(this.resolvedType=(this.declaringField||this).parent.lookupTypeOrEnum(this.type),this.typeDefault=this.resolvedType instanceof r?null:this.resolvedType.values[Object.keys(this.resolvedType.values)[0]]):this.options&&this.options.proto3_optional&&(this.typeDefault=null),this.options&&null!=this.options.default&&(this.typeDefault=this.options.default,this.resolvedType instanceof s&&"string"==typeof this.typeDefault&&(this.typeDefault=this.resolvedType.values[this.typeDefault])),this.options&&(this.options.packed===rt||!this.resolvedType||this.resolvedType instanceof s||delete this.options.packed,Object.keys(this.options).length||(this.options=rt)),this.long?(this.typeDefault=o.Long.fromNumber(this.typeDefault,"u"==(this.type[0]||"")),Object.freeze&&Object.freeze(this.typeDefault)):this.bytes&&"string"==typeof this.typeDefault&&(o.base64.test(this.typeDefault)?o.base64.decode(this.typeDefault,t=o.newBuffer(o.base64.length(this.typeDefault)),0):o.utf8.write(this.typeDefault,t=o.newBuffer(o.utf8.length(this.typeDefault)),0),this.typeDefault=t),this.defaultValue=this.map?o.emptyObject:this.repeated?o.emptyArray:this.typeDefault,this.parent instanceof r&&(this.parent.ctor.prototype[this.name]=this.defaultValue),i.prototype.resolve.call(this))},c.prototype.l=function(t){var e;return"proto2"!==t&&"proto3"!==t?{}:(t={},"required"===this.rule&&(t.field_presence="LEGACY_REQUIRED"),this.parent&&a.defaults[this.type]===rt&&(e=this.parent.get(this.type.split(".").pop()))&&e instanceof r&&e.group&&(t.message_encoding="DELIMITED"),!0===this.getOption("packed")?t.repeated_field_encoding="PACKED":!1===this.getOption("packed")&&(t.repeated_field_encoding="EXPANDED"),t)},c.prototype.u=function(t){return i.prototype.u.call(this,this.f||t)},c.d=function(t,e,n,r){return"function"==typeof e?e=o.decorateType(e).name:e&&"object"==typeof e&&(e=o.decorateEnum(e).name),function(i,s){o.decorateType(i.constructor).add(new c(s,t,e,n,{default:r}))}},c.p=function(t){r=t}},{15:15,24:24,36:36,37:37}],17:[function(t,e,n){var r=e.exports=t(18);r.build="light",r.load=function(t,e,n){return(e="function"==typeof e?(n=e,new r.Root):e||new r.Root).load(t,n)},r.loadSync=function(t,e){return(e=e||new r.Root).loadSync(t)},r.encoder=t(14),r.decoder=t(13),r.verifier=t(40),r.converter=t(12),r.ReflectionObject=t(24),r.Namespace=t(23),r.Root=t(29),r.Enum=t(15),r.Type=t(35),r.Field=t(16),r.OneOf=t(25),r.MapField=t(20),r.Service=t(33),r.Method=t(22),r.Message=t(21),r.wrappers=t(41),r.types=t(36),r.util=t(37),r.ReflectionObject.p(r.Root),r.Namespace.p(r.Type,r.Service,r.Enum),r.Root.p(r.Type),r.Field.p(r.Type)},{12:12,13:13,14:14,15:15,16:16,18:18,20:20,21:21,22:22,23:23,24:24,25:25,29:29,33:33,35:35,36:36,37:37,40:40,41:41}],18:[function(t,e,n){var r=n;function i(){r.util.p(),r.Writer.p(r.BufferWriter),r.Reader.p(r.BufferReader)}r.build="minimal",r.Writer=t(42),r.BufferWriter=t(43),r.Reader=t(27),r.BufferReader=t(28),r.util=t(39),r.rpc=t(31),r.roots=t(30),r.configure=i,i()},{27:27,28:28,30:30,31:31,39:39,42:42,43:43}],19:[function(t,e,n){(e=e.exports=t(17)).build="full",e.tokenize=t(34),e.parse=t(26),e.common=t(11),e.Root.p(e.Type,e.parse,e.common)},{11:11,17:17,26:26,34:34}],20:[function(t,e,n){e.exports=a;var r=t(16),i=(((a.prototype=Object.create(r.prototype)).constructor=a).className="MapField",t(36)),s=t(37);function a(t,e,n,i,a,o){if(r.call(this,t,e,i,rt,rt,a,o),!s.isString(n))throw TypeError("keyType must be a string");this.keyType=n,this.resolvedKeyType=null,this.map=!0}a.fromJSON=function(t,e){return new a(t,e.id,e.keyType,e.type,e.options,e.comment)},a.prototype.toJSON=function(t){return s.toObject(["keyType",this.keyType,"type",this.type,"id",this.id,"extend",this.extend,"options",this.options,"comment",(t=!!t&&!!t.keepComments)?this.comment:rt])},a.prototype.resolve=function(){if(this.resolved)return this;if(i.mapKey[this.keyType]===rt)throw Error("invalid key type: "+this.keyType);return r.prototype.resolve.call(this)},a.d=function(t,e,n){return"function"==typeof n?n=s.decorateType(n).name:n&&"object"==typeof n&&(n=s.decorateEnum(n).name),function(r,i){s.decorateType(r.constructor).add(new a(i,t,e,n))}}},{16:16,36:36,37:37}],21:[function(t,e,n){e.exports=i;var r=t(39);function i(t){if(t)for(var e=Object.keys(t),n=0;n<e.length;++n)this[e[n]]=t[e[n]]}i.create=function(t){return this.$type.create(t)},i.encode=function(t,e){return this.$type.encode(t,e)},i.encodeDelimited=function(t,e){return this.$type.encodeDelimited(t,e)},i.decode=function(t){return this.$type.decode(t)},i.decodeDelimited=function(t){return this.$type.decodeDelimited(t)},i.verify=function(t){return this.$type.verify(t)},i.fromObject=function(t){return this.$type.fromObject(t)},i.toObject=function(t,e){return this.$type.toObject(t,e)},i.prototype.toJSON=function(){return this.$type.toObject(this,r.toJSONOptions)}},{39:39}],22:[function(t,e,n){e.exports=s;var r=t(24),i=(((s.prototype=Object.create(r.prototype)).constructor=s).className="Method",t(37));function s(t,e,n,s,a,o,l,c,d){if(i.isObject(a)?(l=a,a=o=rt):i.isObject(o)&&(l=o,o=rt),e!==rt&&!i.isString(e))throw TypeError("type must be a string");if(!i.isString(n))throw TypeError("requestType must be a string");if(!i.isString(s))throw TypeError("responseType must be a string");r.call(this,t,l),this.type=e||"rpc",this.requestType=n,this.requestStream=!!a||rt,this.responseType=s,this.responseStream=!!o||rt,this.resolvedRequestType=null,this.resolvedResponseType=null,this.comment=c,this.parsedOptions=d}s.fromJSON=function(t,e){return new s(t,e.type,e.requestType,e.responseType,e.requestStream,e.responseStream,e.options,e.comment,e.parsedOptions)},s.prototype.toJSON=function(t){return i.toObject(["type","rpc"!==this.type&&this.type||rt,"requestType",this.requestType,"requestStream",this.requestStream,"responseType",this.responseType,"responseStream",this.responseStream,"options",this.options,"comment",(t=!!t&&!!t.keepComments)?this.comment:rt,"parsedOptions",this.parsedOptions])},s.prototype.resolve=function(){return this.resolved?this:(this.resolvedRequestType=this.parent.lookupType(this.requestType),this.resolvedResponseType=this.parent.lookupType(this.responseType),r.prototype.resolve.call(this))}},{24:24,37:37}],23:[function(t,e,n){e.exports=h;var r,i,s,a=t(24),o=(((h.prototype=Object.create(a.prototype)).constructor=h).className="Namespace",t(16)),l=t(37),c=t(25);function d(t,e){if(!t||!t.length)return rt;for(var n={},r=0;r<t.length;++r)n[t[r].name]=t[r].toJSON(e);return n}function h(t,e){a.call(this,t,e),this.nested=rt,this.v=null,this.b={},this.w=!0,this.y=!0}function u(t){t.v=null,t.b={};for(var e=t;e=e.parent;)e.b={};return t}h.fromJSON=function(t,e){return new h(t,e.options).addJSON(e.nested)},h.arrayToJSON=d,h.isReservedId=function(t,e){if(t)for(var n=0;n<t.length;++n)if("string"!=typeof t[n]&&t[n][0]<=e&&t[n][1]>e)return!0;return!1},h.isReservedName=function(t,e){if(t)for(var n=0;n<t.length;++n)if(t[n]===e)return!0;return!1},Object.defineProperty(h.prototype,"nestedArray",{get:function(){return this.v||(this.v=l.toArray(this.nested))}}),h.prototype.toJSON=function(t){return l.toObject(["options",this.options,"nested",d(this.nestedArray,t)])},h.prototype.addJSON=function(t){if(t)for(var e,n=Object.keys(t),a=0;a<n.length;++a)this.add(((e=t[n[a]]).fields!==rt?r:e.values!==rt?s:e.methods!==rt?i:e.id!==rt?o:h).fromJSON(n[a],e));return this},h.prototype.get=function(t){return this.nested&&this.nested[t]||null},h.prototype.getEnum=function(t){if(this.nested&&this.nested[t]instanceof s)return this.nested[t].values;throw Error("no such enum: "+t)},h.prototype.add=function(t){if(!(t instanceof o&&t.extend!==rt||t instanceof r||t instanceof c||t instanceof s||t instanceof i||t instanceof h))throw TypeError("object must be a valid nested object");if(this.nested){var e=this.get(t.name);if(e){if(!(e instanceof h&&t instanceof h)||e instanceof r||e instanceof i)throw Error("duplicate name '"+t.name+"' in "+this);for(var n=e.nestedArray,a=0;a<n.length;++a)t.add(n[a]);this.remove(e),this.nested||(this.nested={}),t.setOptions(e.options,!0)}}else this.nested={};this.nested[t.name]=t,this instanceof r||this instanceof i||this instanceof s||this instanceof o||t.f||(t.f=t.a),this.w=!0,this.y=!0;for(var l=this;l=l.parent;)l.w=!0,l.y=!0;return t.onAdd(this),u(this)},h.prototype.remove=function(t){if(!(t instanceof a))throw TypeError("object must be a ReflectionObject");if(t.parent!==this)throw Error(t+" is not a member of "+this);return delete this.nested[t.name],Object.keys(this.nested).length||(this.nested=rt),t.onRemove(this),u(this)},h.prototype.define=function(t,e){if(l.isString(t))t=t.split(".");else if(!Array.isArray(t))throw TypeError("illegal path");if(t&&t.length&&""===t[0])throw Error("path must be relative");for(var n=this;0<t.length;){var r=t.shift();if(n.nested&&n.nested[r]){if(!((n=n.nested[r])instanceof h))throw Error("path conflicts with non-namespace objects")}else n.add(n=new h(r))}return e&&n.addJSON(e),n},h.prototype.resolveAll=function(){if(this.y){this.g(this.f);var t=this.nestedArray,e=0;for(this.resolve();e<t.length;)t[e]instanceof h?t[e++].resolveAll():t[e++].resolve();this.y=!1}return this},h.prototype.g=function(t){return this.w&&(this.w=!1,a.prototype.g.call(this,t=this.f||t),this.nestedArray.forEach(e=>{e.g(t)})),this},h.prototype.lookup=function(t,e,n){if("boolean"==typeof e?(n=e,e=rt):e&&!Array.isArray(e)&&(e=[e]),l.isString(t)&&t.length){if("."===t)return this.root;t=t.split(".")}else if(!t.length)return this;var r=t.join(".");if(""===t[0])return this.root.lookup(t.slice(1),e);var i=this.root.j&&this.root.j["."+r];if(i&&(!e||~e.indexOf(i.constructor)))return i;if((i=this.k(t,r))&&(!e||~e.indexOf(i.constructor)))return i;if(!n)for(var s=this;s.parent;){if((i=s.parent.k(t,r))&&(!e||~e.indexOf(i.constructor)))return i;s=s.parent}return null},h.prototype.k=function(t,e){if(Object.prototype.hasOwnProperty.call(this.b,e))return this.b[e];var n=this.get(t[0]),r=null;if(n)1===t.length?r=n:n instanceof h&&(t=t.slice(1),r=n.k(t,t.join(".")));else for(var i=0;i<this.nestedArray.length;++i)this.v[i]instanceof h&&(n=this.v[i].k(t,e))&&(r=n);return this.b[e]=r},h.prototype.lookupType=function(t){var e=this.lookup(t,[r]);if(e)return e;throw Error("no such type: "+t)},h.prototype.lookupEnum=function(t){var e=this.lookup(t,[s]);if(e)return e;throw Error("no such Enum '"+t+"' in "+this)},h.prototype.lookupTypeOrEnum=function(t){var e=this.lookup(t,[r,s]);if(e)return e;throw Error("no such Type or Enum '"+t+"' in "+this)},h.prototype.lookupService=function(t){var e=this.lookup(t,[i]);if(e)return e;throw Error("no such Service '"+t+"' in "+this)},h.p=function(t,e,n){r=t,i=e,s=n}},{16:16,24:24,25:25,37:37}],24:[function(t,e,n){(e.exports=c).className="ReflectionObject";const r=t(25);var i,s=t(37),a={enum_type:"OPEN",field_presence:"EXPLICIT",json_format:"ALLOW",message_encoding:"LENGTH_PREFIXED",repeated_field_encoding:"PACKED",utf8_validation:"VERIFY"},o={enum_type:"CLOSED",field_presence:"EXPLICIT",json_format:"LEGACY_BEST_EFFORT",message_encoding:"LENGTH_PREFIXED",repeated_field_encoding:"EXPANDED",utf8_validation:"NONE"},l={enum_type:"OPEN",field_presence:"IMPLICIT",json_format:"ALLOW",message_encoding:"LENGTH_PREFIXED",repeated_field_encoding:"PACKED",utf8_validation:"VERIFY"};function c(t,e){if(!s.isString(t))throw TypeError("name must be a string");if(e&&!s.isObject(e))throw TypeError("options must be an object");this.options=e,this.parsedOptions=null,this.name=t,this.f=null,this.a="proto2",this.h={},this.O=!1,this.parent=null,this.resolved=!1,this.comment=null,this.filename=null}Object.defineProperties(c.prototype,{root:{get:function(){for(var t=this;null!==t.parent;)t=t.parent;return t}},fullName:{get:function(){for(var t=[this.name],e=this.parent;e;)t.unshift(e.name),e=e.parent;return t.join(".")}}}),c.prototype.toJSON=function(){throw Error()},c.prototype.onAdd=function(t){this.parent&&this.parent!==t&&this.parent.remove(this),this.parent=t,this.resolved=!1,(t=t.root)instanceof i&&t.A(this)},c.prototype.onRemove=function(t){(t=t.root)instanceof i&&t.T(this),this.parent=null,this.resolved=!1},c.prototype.resolve=function(){return this.resolved||this.root instanceof i&&(this.resolved=!0),this},c.prototype.g=function(t){return this.u(this.f||t)},c.prototype.u=function(t){if(!this.O){var e={};if(!t)throw Error("Unknown edition for "+this.fullName);var n=Object.assign(this.options?Object.assign({},this.options.features):{},this.l(t));if(this.f){if("proto2"===t)e=Object.assign({},o);else if("proto3"===t)e=Object.assign({},l);else{if("2023"!==t)throw Error("Unknown edition: "+t);e=Object.assign({},a)}this.h=Object.assign(e,n||{})}else{if(this.partOf instanceof r)t=Object.assign({},this.partOf.h),this.h=Object.assign(t,n||{});else if(!this.declaringField){if(!this.parent)throw Error("Unable to find a parent for "+this.fullName);e=Object.assign({},this.parent.h),this.h=Object.assign(e,n||{})}this.extensionField&&(this.extensionField.h=this.h)}this.O=!0}},c.prototype.l=function(){return{}},c.prototype.getOption=function(t){return this.options?this.options[t]:rt},c.prototype.setOption=function(t,e,n){return this.options||(this.options={}),/^features\./.test(t)?s.setProperty(this.options,t,e,n):n&&this.options[t]!==rt||(this.getOption(t)!==e&&(this.resolved=!1),this.options[t]=e),this},c.prototype.setParsedOption=function(t,e,n){this.parsedOptions||(this.parsedOptions=[]);var r,i,a=this.parsedOptions;return n?(r=a.find(function(e){return Object.prototype.hasOwnProperty.call(e,t)}))?s.setProperty(i=r[t],n,e):((r={})[t]=s.setProperty({},n,e),a.push(r)):((i={})[t]=e,a.push(i)),this},c.prototype.setOptions=function(t,e){if(t)for(var n=Object.keys(t),r=0;r<n.length;++r)this.setOption(n[r],t[n[r]],e);return this},c.prototype.toString=function(){var t=this.constructor.className,e=this.fullName;return e.length?t+" "+e:t},c.prototype.c=function(){return this.f&&"proto3"!==this.f?this.f:rt},c.p=function(t){i=t}},{25:25,37:37}],25:[function(t,e,n){e.exports=a;var r=t(24),i=(((a.prototype=Object.create(r.prototype)).constructor=a).className="OneOf",t(16)),s=t(37);function a(t,e,n,i){if(Array.isArray(e)||(n=e,e=rt),r.call(this,t,n),e!==rt&&!Array.isArray(e))throw TypeError("fieldNames must be an Array");this.oneof=e||[],this.fieldsArray=[],this.comment=i}function o(t){if(t.parent)for(var e=0;e<t.fieldsArray.length;++e)t.fieldsArray[e].parent||t.parent.add(t.fieldsArray[e])}a.fromJSON=function(t,e){return new a(t,e.oneof,e.options,e.comment)},a.prototype.toJSON=function(t){return s.toObject(["options",this.options,"oneof",this.oneof,"comment",(t=!!t&&!!t.keepComments)?this.comment:rt])},a.prototype.add=function(t){if(t instanceof i)return t.parent&&t.parent!==this.parent&&t.parent.remove(t),this.oneof.push(t.name),this.fieldsArray.push(t),o(t.partOf=this),this;throw TypeError("field must be a Field")},a.prototype.remove=function(t){if(!(t instanceof i))throw TypeError("field must be a Field");var e=this.fieldsArray.indexOf(t);if(e<0)throw Error(t+" is not a member of "+this);return this.fieldsArray.splice(e,1),-1<(e=this.oneof.indexOf(t.name))&&this.oneof.splice(e,1),t.partOf=null,this},a.prototype.onAdd=function(t){r.prototype.onAdd.call(this,t);for(var e=0;e<this.oneof.length;++e){var n=t.get(this.oneof[e]);n&&!n.partOf&&(n.partOf=this).fieldsArray.push(n)}o(this)},a.prototype.onRemove=function(t){for(var e,n=0;n<this.fieldsArray.length;++n)(e=this.fieldsArray[n]).parent&&e.parent.remove(e);r.prototype.onRemove.call(this,t)},Object.defineProperty(a.prototype,"isProto3Optional",{get:function(){var t;return null!=this.fieldsArray&&1===this.fieldsArray.length&&null!=(t=this.fieldsArray[0]).options&&!0===t.options.proto3_optional}}),a.d=function(){for(var t=Array(arguments.length),e=0;e<arguments.length;)t[e]=arguments[e++];return function(e,n){s.decorateType(e.constructor).add(new a(n,t)),Object.defineProperty(e,n,{get:s.oneOfGetter(t),set:s.oneOfSetter(t)})}}},{16:16,24:24,37:37}],26:[function(t,e,n){(e.exports=T).filename=null,T.defaults={keepCase:!1};var r=t(34),i=t(29),s=t(35),a=t(16),o=t(20),l=t(25),c=t(15),d=t(33),h=t(22),u=t(24),p=t(36),f=t(37),m=/^[1-9][0-9]*$/,_=/^-?[1-9][0-9]*$/,g=/^0[x][0-9a-fA-F]+$/,y=/^-?0[x][0-9a-fA-F]+$/,S=/^0[0-7]+$/,A=/^-?0[0-7]+$/,v=/^(?![eE])[0-9]*(?:\.[0-9]*)?(?:[eE][+-]?[0-9]+)?$/,E=/^[a-zA-Z_][a-zA-Z_0-9]*$/,b=/^(?:\.?[a-zA-Z_][a-zA-Z_0-9]*)(?:\.[a-zA-Z_][a-zA-Z_0-9]*)*$/;function T(t,e,n){e instanceof i||(n=e,e=new i);var w,x,I,R,C,B,D=(n=n||T.defaults).preferTrailingComment||!1,P=r(t,n.alternateCommentMode||!1),k=P.next,O=P.push,U=P.peek,N=P.skip,L=P.cmnt,F=!0,M="proto2",G=e,z=[],W={},H=n.keepCase?function(t){return t}:f.camelCase;function $(t,e,n){var r=T.filename;return n||(T.filename=null),Error("illegal "+(e||"token")+" '"+t+"' ("+(r?r+", ":"")+"line "+P.line+")")}function j(){var t,e=[];do{if('"'!==(t=k())&&"'"!==t)throw $(t)}while(e.push(k()),N(t),'"'===(t=U())||"'"===t);return e.join("")}function V(t){var e=k();switch(e){case"'":case'"':return O(e),j();case"true":case"TRUE":return!0;case"false":case"FALSE":return!1}try{var n=e,r=1;switch("-"==(n[0]||"")&&(r=-1,n=n.substring(1)),n){case"inf":case"INF":case"Inf":return r*(1/0);case"nan":case"NAN":case"Nan":case"NaN":return NaN;case"0":return 0}if(m.test(n))return r*parseInt(n,10);if(g.test(n))return r*parseInt(n,16);if(S.test(n))return r*parseInt(n,8);if(v.test(n))return r*parseFloat(n);throw $(n,"number",!0)}catch(n){if(t&&b.test(e))return e;throw $(e,"value")}}function Y(t,e){var n;do{if(!e||'"'!==(r=U())&&"'"!==r)try{t.push([n=K(k()),N("to",!0)?K(k()):n])}catch(n){if(!(e&&b.test(r)&&2023<=M))throw n;t.push(r)}else{var r=j();if(t.push(r),2023<=M)throw $(r,"id")}}while(N(",",!0));var i={options:rt,setOption:function(t,e){this.options===rt&&(this.options={}),this.options[t]=e}};q(i,function(t){if("option"!==t)throw $(t);tt(i,t),N(";")},function(){nt(i)})}function K(t,e){switch(t){case"max":case"MAX":case"Max":return 536870911;case"0":return 0}if(e||"-"!=(t[0]||"")){if(_.test(t))return parseInt(t,10);if(y.test(t))return parseInt(t,16);if(A.test(t))return parseInt(t,8)}throw $(t,"id")}function X(t,e){switch(e){case"option":return tt(t,e),N(";"),1;case"message":return Z(t),1;case"enum":return Q(t),1;case"service":var n,r,i=t;if(E.test(r=k()))return q(n=new d(r),function(t){if(!X(n,t)){if("rpc"!==t)throw $(t);var e=n,r=L(),i=t;if(!E.test(t=k()))throw $(t,"name");var s,a,o,l=t;if(N("("),N("stream",!0)&&(a=!0),!b.test(t=k()))throw $(t);if(s=t,N(")"),N("returns"),N("("),N("stream",!0)&&(o=!0),!b.test(t=k()))throw $(t);N(")");var c=new h(l,i,s,t,a,o);c.comment=r,q(c,function(t){if("option"!==t)throw $(t);tt(c,t),N(";")}),e.add(c)}}),i.add(n),i===G&&z.push(n),1;throw $(r,"service name");case"extend":var s,a=t;if(i=e,b.test(i=k()))return s=i,q(null,function(t){switch(t){case"required":case"repeated":J(a,t,s);break;case"optional":J(a,"proto3"===M?"proto3_optional":"optional",s);break;default:if("proto2"===M||!b.test(t))throw $(t);O(t),J(a,"optional",s)}}),1;throw $(i,"reference")}}function q(t,e,n){var r,i=P.line;if(t&&("string"!=typeof t.comment&&(t.comment=L()),t.filename=T.filename),N("{",!0)){for(;"}"!==(r=k());)e(r);N(";",!0)}else n&&n(),N(";"),t&&("string"!=typeof t.comment||D)&&(t.comment=L(i)||t.comment)}function Z(t,e){if(!E.test(e=k()))throw $(e,"type name");var n=new s(e);q(n,function(t){if(!X(n,t))switch(t){case"map":var e=n,r=(N("<"),k());if(p.mapKey[r]===rt)throw $(r,"type");N(",");var i=k();if(!b.test(i))throw $(i,"type");N(">");var s=k();if(!E.test(s))throw $(s,"name");N("=");var a=new o(H(s),K(k()),r,i);q(a,function(t){if("option"!==t)throw $(t);tt(a,t),N(";")},function(){nt(a)}),e.add(a);break;case"required":if("proto2"!==M)throw $(t);case"repeated":J(n,t);break;case"optional":if("proto3"===M)J(n,"proto3_optional");else{if("proto2"!==M)throw $(t);J(n,"optional")}break;case"oneof":if(s=n,r=t,!E.test(r=k()))throw $(r,"name");var c=new l(H(r));q(c,function(t){"option"===t?(tt(c,t),N(";")):(O(t),J(c,"optional"))}),s.add(c);break;case"extensions":Y(n.extensions||(n.extensions=[]));break;case"reserved":Y(n.reserved||(n.reserved=[]),!0);break;default:if("proto2"===M||!b.test(t))throw $(t);O(t),J(n,"optional")}}),t.add(n),t===G&&z.push(n)}function J(t,e,n){var r=k();if("group"===r){var i=t,o=e;if(2023<=M)throw $("group");var c,d,h=k();if(E.test(h))return h===(d=f.lcFirst(h))&&(h=f.ucFirst(h)),N("="),u=K(k()),(c=new s(h)).group=!0,(d=new a(d,u,h,o)).filename=T.filename,q(c,function(t){switch(t){case"option":tt(c,t),N(";");break;case"required":case"repeated":J(c,t);break;case"optional":J(c,"proto3"===M?"proto3_optional":"optional");break;case"message":Z(c);break;case"enum":Q(c);break;case"reserved":Y(c.reserved||(c.reserved=[]),!0);break;default:throw $(t)}}),void i.add(c).add(d);throw $(h,"name")}for(;r.endsWith(".")||U().startsWith(".");)r+=k();if(!b.test(r))throw $(r,"type");var u=k();if(!E.test(u))throw $(u,"name");u=H(u),N("=");var p=new a(u,K(k()),r,e,n);q(p,function(t){if("option"!==t)throw $(t);tt(p,t),N(";")},function(){nt(p)}),"proto3_optional"===e?(o=new l("_"+u),p.setOption("proto3_optional",!0),o.add(p),t.add(o)):t.add(p),t===G&&z.push(p)}function Q(t,e){if(!E.test(e=k()))throw $(e,"name");var n=new c(e);q(n,function(t){switch(t){case"option":tt(n,t),N(";");break;case"reserved":Y(n.reserved||(n.reserved=[]),!0),n.reserved===rt&&(n.reserved=[]);break;default:var e=n,r=t;if(!E.test(r))throw $(r,"name");N("=");var i=K(k(),!0),s={options:rt,getOption:function(t){return this.options[t]},setOption:function(t,e){u.prototype.setOption.call(s,t,e)},setParsedOption:function(){return rt}};return q(s,function(t){if("option"!==t)throw $(t);tt(s,t),N(";")},function(){nt(s)}),void e.add(r,i,s.comment,s.parsedOptions||s.options)}}),t.add(n),t===G&&z.push(n)}function tt(t,e){var n=!0;for("option"===e&&(e=k());"="!==e;){if("("===e&&(r=k(),N(")"),e="("+r+")"),n){if(n=!1,e.includes(".")&&!e.includes("(")){var r=e.split("."),i=r[0]+".";e=r[1];continue}i=e}else a=a?a+e:e;e=k()}var s=function t(e,n){if(N("{",!0)){for(var r={};!N("}",!0);){if(!E.test(R=k()))throw $(R,"name");if(null===R)throw $(R,"end of input");var i,s,a=R;if(N(":",!0),"{"===U())i=t(e,n+"."+R);else if("["===U()){if(i=[],N("[",!0)){for(;s=V(!0),i.push(s),N(",",!0););N("]"),void 0!==s&&et(e,n+"."+R,s)}}else i=V(!0),et(e,n+"."+R,i);var o=r[a];o&&(i=[].concat(o).concat(i)),r[a]=i,N(",",!0),N(";",!0)}return r}var l=V(!0);return et(e,n,l),l}(t,s=a?i.concat(a):i),a=a&&"."===a[0]?a.slice(1):a;i=i&&"."===i[i.length-1]?i.slice(0,-1):i,t.setParsedOption&&t.setParsedOption(i,s,a)}function et(t,e,n){G===t&&/^features\./.test(e)?W[e]=n:t.setOption&&t.setOption(e,n)}function nt(t){if(N("[",!0)){for(;tt(t,"option"),N(",",!0););N("]")}}for(;null!==(R=k());)switch(R){case"package":if(!F)throw $(R);if(w!==rt)throw $("package");if(w=k(),!b.test(w))throw $(w,"name");G=G.define(w),N(";");break;case"import":if(!F)throw $(R);switch(B=void 0,U()){case"weak":B=I=I||[],k();break;case"public":k();default:B=x=x||[]}C=j(),N(";"),B.push(C);break;case"syntax":if(!F)throw $(R);if(N("="),(M=j())<2023)throw $(M,"syntax");N(";");break;case"edition":if(!F)throw $(R);if(N("="),M=j(),!["2023"].includes(M))throw $(M,"edition");N(";");break;case"option":tt(G,R),N(";",!0);break;default:if(X(G,R)){F=!1;continue}throw $(R)}return z.forEach(t=>{t.f=M,Object.keys(W).forEach(e=>{t.getOption(e)===rt&&t.setOption(e,W[e],!0)})}),T.filename=null,{package:w,imports:x,weakImports:I,root:e}}},{15:15,16:16,20:20,22:22,24:24,25:25,29:29,33:33,34:34,35:35,36:36,37:37}],27:[function(t,e,n){e.exports=l;var r,i=t(39),s=i.LongBits,a=i.utf8;function o(t,e){return RangeError("index out of range: "+t.pos+" + "+(e||1)+" > "+t.len)}function l(t){this.buf=t,this.pos=0,this.len=t.length}function c(){return i.Buffer?function(t){return(l.create=function(t){return i.Buffer.isBuffer(t)?new r(t):h(t)})(t)}:h}var d,h="undefined"!=typeof Uint8Array?function(t){if(t instanceof Uint8Array||Array.isArray(t))return new l(t);throw Error("illegal buffer")}:function(t){if(Array.isArray(t))return new l(t);throw Error("illegal buffer")};function u(){var t=new s(0,0),e=0;if(!(4<this.len-this.pos)){for(;e<3;++e){if(this.pos>=this.len)throw o(this);if(t.lo=(t.lo|(127&this.buf[this.pos])<<7*e)>>>0,this.buf[this.pos++]<128)return t}return t.lo=(t.lo|(127&this.buf[this.pos++])<<7*e)>>>0,t}for(;e<4;++e)if(t.lo=(t.lo|(127&this.buf[this.pos])<<7*e)>>>0,this.buf[this.pos++]<128)return t;if(t.lo=(t.lo|(127&this.buf[this.pos])<<28)>>>0,t.hi=(t.hi|(127&this.buf[this.pos])>>4)>>>0,this.buf[this.pos++]<128)return t;if(e=0,4<this.len-this.pos){for(;e<5;++e)if(t.hi=(t.hi|(127&this.buf[this.pos])<<7*e+3)>>>0,this.buf[this.pos++]<128)return t}else for(;e<5;++e){if(this.pos>=this.len)throw o(this);if(t.hi=(t.hi|(127&this.buf[this.pos])<<7*e+3)>>>0,this.buf[this.pos++]<128)return t}throw Error("invalid varint encoding")}function p(t,e){return(t[e-4]|t[e-3]<<8|t[e-2]<<16|t[e-1]<<24)>>>0}function f(){if(this.pos+8>this.len)throw o(this,8);return new s(p(this.buf,this.pos+=4),p(this.buf,this.pos+=4))}l.create=c(),l.prototype._=i.Array.prototype.subarray||i.Array.prototype.slice,l.prototype.uint32=(d=4294967295,function(){if(d=(127&this.buf[this.pos])>>>0,this.buf[this.pos++]<128||(d=(d|(127&this.buf[this.pos])<<7)>>>0,this.buf[this.pos++]<128||(d=(d|(127&this.buf[this.pos])<<14)>>>0,this.buf[this.pos++]<128||(d=(d|(127&this.buf[this.pos])<<21)>>>0,this.buf[this.pos++]<128||(d=(d|(15&this.buf[this.pos])<<28)>>>0,this.buf[this.pos++]<128||!((this.pos+=5)>this.len))))))return d;throw this.pos=this.len,o(this,10)}),l.prototype.int32=function(){return 0|this.uint32()},l.prototype.sint32=function(){var t=this.uint32();return t>>>1^-(1&t)},l.prototype.bool=function(){return 0!==this.uint32()},l.prototype.fixed32=function(){if(this.pos+4>this.len)throw o(this,4);return p(this.buf,this.pos+=4)},l.prototype.sfixed32=function(){if(this.pos+4>this.len)throw o(this,4);return 0|p(this.buf,this.pos+=4)},l.prototype.float=function(){if(this.pos+4>this.len)throw o(this,4);var t=i.float.readFloatLE(this.buf,this.pos);return this.pos+=4,t},l.prototype.double=function(){if(this.pos+8>this.len)throw o(this,4);var t=i.float.readDoubleLE(this.buf,this.pos);return this.pos+=8,t},l.prototype.bytes=function(){var t=this.uint32(),e=this.pos,n=this.pos+t;if(n>this.len)throw o(this,t);return this.pos+=t,Array.isArray(this.buf)?this.buf.slice(e,n):e===n?(t=i.Buffer)?t.alloc(0):new this.buf.constructor(0):this._.call(this.buf,e,n)},l.prototype.string=function(){var t=this.bytes();return a.read(t,0,t.length)},l.prototype.skip=function(t){if("number"==typeof t){if(this.pos+t>this.len)throw o(this,t);this.pos+=t}else do{if(this.pos>=this.len)throw o(this)}while(128&this.buf[this.pos++]);return this},l.prototype.skipType=function(t){switch(t){case 0:this.skip();break;case 1:this.skip(8);break;case 2:this.skip(this.uint32());break;case 3:for(;4!=(t=7&this.uint32());)this.skipType(t);break;case 5:this.skip(4);break;default:throw Error("invalid wire type "+t+" at offset "+this.pos)}return this},l.p=function(t){r=t,l.create=c(),r.p();var e=i.Long?"toLong":"toNumber";i.merge(l.prototype,{int64:function(){return u.call(this)[e](!1)},uint64:function(){return u.call(this)[e](!0)},sint64:function(){return u.call(this).zzDecode()[e](!1)},fixed64:function(){return f.call(this)[e](!0)},sfixed64:function(){return f.call(this)[e](!1)}})}},{39:39}],28:[function(t,e,n){e.exports=s;var r=t(27),i=((s.prototype=Object.create(r.prototype)).constructor=s,t(39));function s(t){r.call(this,t)}s.p=function(){i.Buffer&&(s.prototype._=i.Buffer.prototype.slice)},s.prototype.string=function(){var t=this.uint32();return this.buf.utf8Slice?this.buf.utf8Slice(this.pos,this.pos=Math.min(this.pos+t,this.len)):this.buf.toString("utf-8",this.pos,this.pos=Math.min(this.pos+t,this.len))},s.p()},{27:27,39:39}],29:[function(t,e,n){e.exports=h;var r,i,s,a=t(23),o=(((h.prototype=Object.create(a.prototype)).constructor=h).className="Root",t(16)),l=t(15),c=t(25),d=t(37);function h(t){a.call(this,"",t),this.deferred=[],this.files=[],this.f="proto2",this.j={}}function u(){}h.fromJSON=function(t,e){return e=e||new h,t.options&&e.setOptions(t.options),e.addJSON(t.nested).resolveAll()},h.prototype.resolvePath=d.path.resolve,h.prototype.fetch=d.fetch,h.prototype.load=function t(e,n,r){"function"==typeof n&&(r=n,n=rt);var a=this;if(!r)return d.asPromise(t,a,e,n);var o=r===u;function l(t,e){if(r){if(o)throw t;e&&e.resolveAll();var n=r;r=null,n(t,e)}}function c(t){var e=t.lastIndexOf("google/protobuf/");return-1<e&&(t=t.substring(e))in s?t:null}function h(t,e){try{if(d.isString(e)&&"{"==(e[0]||"")&&(e=JSON.parse(e)),d.isString(e)){i.filename=t;var r,s=i(e,a,n),h=0;if(s.imports)for(;h<s.imports.length;++h)(r=c(s.imports[h])||a.resolvePath(t,s.imports[h]))&&p(r);if(s.weakImports)for(h=0;h<s.weakImports.length;++h)(r=c(s.weakImports[h])||a.resolvePath(t,s.weakImports[h]))&&p(r,!0)}else a.setOptions(e.options).addJSON(e.nested)}catch(t){l(t)}o||f||l(null,a)}function p(t,e){if(t=c(t)||t,!~a.files.indexOf(t))if(a.files.push(t),t in s)o?h(t,s[t]):(++f,setTimeout(function(){--f,h(t,s[t])}));else if(o){var n;try{n=d.fs.readFileSync(t).toString("utf8")}catch(n){return void(e||l(n))}h(t,n)}else++f,a.fetch(t,function(n,i){--f,r&&(n?e?f||l(null,a):l(n):h(t,i))})}var f=0;d.isString(e)&&(e=[e]);for(var m,_=0;_<e.length;++_)(m=a.resolvePath("",e[_]))&&p(m);return o?a.resolveAll():f||l(null,a),a},h.prototype.loadSync=function(t,e){if(d.isNode)return this.load(t,e,u);throw Error("not supported")},h.prototype.resolveAll=function(){if(!this.y)return this;if(this.deferred.length)throw Error("unresolvable extensions: "+this.deferred.map(function(t){return"'extend "+t.extend+"' in "+t.parent.fullName}).join(", "));return a.prototype.resolveAll.call(this)};var p=/^[A-Z]/;function f(t,e){var n,r=e.parent.lookup(e.extend);if(r)return n=new o(e.fullName,e.id,e.type,e.rule,rt,e.options),r.get(n.name)||((n.declaringField=e).extensionField=n,r.add(n)),1}h.prototype.A=function(t){if(t instanceof o)t.extend===rt||t.extensionField||f(0,t)||this.deferred.push(t);else if(t instanceof l)p.test(t.name)&&(t.parent[t.name]=t.values);else if(!(t instanceof c)){if(t instanceof r)for(var e=0;e<this.deferred.length;)f(0,this.deferred[e])?this.deferred.splice(e,1):++e;for(var n=0;n<t.nestedArray.length;++n)this.A(t.v[n]);p.test(t.name)&&(t.parent[t.name]=t)}(t instanceof r||t instanceof l||t instanceof o)&&(this.j[t.fullName]=t)},h.prototype.T=function(t){var e;if(t instanceof o)t.extend!==rt&&(t.extensionField?(t.extensionField.parent.remove(t.extensionField),t.extensionField=null):-1<(e=this.deferred.indexOf(t))&&this.deferred.splice(e,1));else if(t instanceof l)p.test(t.name)&&delete t.parent[t.name];else if(t instanceof a){for(var n=0;n<t.nestedArray.length;++n)this.T(t.v[n]);p.test(t.name)&&delete t.parent[t.name]}delete this.j[t.fullName]},h.p=function(t,e,n){r=t,i=e,s=n}},{15:15,16:16,23:23,25:25,37:37}],30:[function(t,e,n){e.exports={}},{}],31:[function(t,e,n){n.Service=t(32)},{32:32}],32:[function(t,e,n){e.exports=i;var r=t(39);function i(t,e,n){if("function"!=typeof t)throw TypeError("rpcImpl must be a function");r.EventEmitter.call(this),this.rpcImpl=t,this.requestDelimited=!!e,this.responseDelimited=!!n}((i.prototype=Object.create(r.EventEmitter.prototype)).constructor=i).prototype.rpcCall=function t(e,n,i,s,a){if(!s)throw TypeError("request must be specified");var o=this;if(!a)return r.asPromise(t,o,e,n,i,s);if(!o.rpcImpl)return setTimeout(function(){a(Error("already ended"))},0),rt;try{return o.rpcImpl(e,n[o.requestDelimited?"encodeDelimited":"encode"](s).finish(),function(t,n){if(t)return o.emit("error",t,e),a(t);if(null===n)return o.end(!0),rt;if(!(n instanceof i))try{n=i[o.responseDelimited?"decodeDelimited":"decode"](n)}catch(t){return o.emit("error",t,e),a(t)}return o.emit("data",n,e),a(null,n)})}catch(t){return o.emit("error",t,e),setTimeout(function(){a(t)},0),rt}},i.prototype.end=function(t){return this.rpcImpl&&(t||this.rpcImpl(null,null,null),this.rpcImpl=null,this.emit("end").off()),this}},{39:39}],33:[function(t,e,n){e.exports=o;var r=t(23),i=(((o.prototype=Object.create(r.prototype)).constructor=o).className="Service",t(22)),s=t(37),a=t(31);function o(t,e){r.call(this,t,e),this.methods={},this.x=null}function l(t){return t.x=null,t}o.fromJSON=function(t,e){var n=new o(t,e.options);if(e.methods)for(var r=Object.keys(e.methods),s=0;s<r.length;++s)n.add(i.fromJSON(r[s],e.methods[r[s]]));return e.nested&&n.addJSON(e.nested),e.edition&&(n.f=e.edition),n.comment=e.comment,n.a="proto3",n},o.prototype.toJSON=function(t){var e=r.prototype.toJSON.call(this,t),n=!!t&&!!t.keepComments;return s.toObject(["edition",this.c(),"options",e&&e.options||rt,"methods",r.arrayToJSON(this.methodsArray,t)||{},"nested",e&&e.nested||rt,"comment",n?this.comment:rt])},Object.defineProperty(o.prototype,"methodsArray",{get:function(){return this.x||(this.x=s.toArray(this.methods))}}),o.prototype.get=function(t){return this.methods[t]||r.prototype.get.call(this,t)},o.prototype.resolveAll=function(){if(this.y){r.prototype.resolve.call(this);for(var t=this.methodsArray,e=0;e<t.length;++e)t[e].resolve()}return this},o.prototype.g=function(t){return this.w&&(r.prototype.g.call(this,t=this.f||t),this.methodsArray.forEach(e=>{e.g(t)})),this},o.prototype.add=function(t){if(this.get(t.name))throw Error("duplicate name '"+t.name+"' in "+this);return t instanceof i?l((this.methods[t.name]=t).parent=this):r.prototype.add.call(this,t)},o.prototype.remove=function(t){if(t instanceof i){if(this.methods[t.name]!==t)throw Error(t+" is not a member of "+this);return delete this.methods[t.name],t.parent=null,l(this)}return r.prototype.remove.call(this,t)},o.prototype.create=function(t,e,n){for(var r,i=new a.Service(t,e,n),o=0;o<this.methodsArray.length;++o){var l=s.lcFirst((r=this.x[o]).resolve().name).replace(/[^$\w_]/g,"");i[l]=s.codegen(["r","c"],s.isReserved(l)?l+"_":l)("return this.rpcCall(m,q,s,r,c)")({m:r,q:r.resolvedRequestType.ctor,s:r.resolvedResponseType.ctor})}return i}},{22:22,23:23,31:31,37:37}],34:[function(t,e,n){e.exports=p;var r=/[\s{}=;:[\],'"()<>]/g,i=/(?:"([^"\\]*(?:\\.[^"\\]*)*)")/g,s=/(?:'([^'\\]*(?:\\.[^'\\]*)*)')/g,a=/^ *[*/]+ */,o=/^\s*\*?\/*/,l=/\n/g,c=/\s/,d=/\\(.?)/g,h={0:"\0",r:"\r",n:"\n",t:"\t"};function u(t){return t.replace(d,function(t,e){switch(e){case"\\":case"":return e;default:return h[e]||""}})}function p(t,e){t=t.toString();var n=0,d=t.length,h=1,p=0,f={},m=[],_=null;function g(t){return Error("illegal "+t+" (line "+h+")")}function y(e){return t[0|e]||""}function S(n,r,i){var s,c={type:t[0|n++]||"",lineEmpty:!1,leading:i},d=n-(i=e?2:3);do{if(--d<0||"\n"==(s=t[0|d]||"")){c.lineEmpty=!0;break}}while(" "===s||"\t"===s);for(var u=t.substring(n,r).split(l),m=0;m<u.length;++m)u[m]=u[m].replace(e?o:a,"").trim();c.text=u.join("\n").trim(),f[h]=c,p=h}function A(e){var n=v(e);return e=t.substring(e,n),/^\s*\/\//.test(e)}function v(t){for(var e=t;e<d&&"\n"!==y(e);)e++;return e}function E(){if(0<m.length)return m.shift();if(_){var a="'"===_?s:i,o=(a.lastIndex=n-1,a.exec(t));if(o)return n=a.lastIndex,b(_),_=null,u(o[1]);throw g("string")}var l,p,f,E,T,w=0===n;do{if(n===d)return null;for(l=!1;c.test(f=y(n));)if("\n"===f&&(w=!0,++h),++n===d)return null;if("/"===y(n)){if(++n===d)throw g("comment");if("/"===y(n))if(e){if(T=!1,A((E=n)-1))for(T=!0;(n=v(n))!==d&&(n++,w&&A(n)););else n=Math.min(d,v(n)+1);T&&(S(E,n,w),w=!0),h++}else{for(T="/"===y(E=n+1);"\n"!==y(++n);)if(n===d)return null;++n,T&&(S(E,n-1,w),w=!0),++h}else{if("*"!==(f=y(n)))return"/";E=n+1,T=e||"*"===y(E);do{if("\n"===f&&++h,++n===d)throw g("comment")}while(p=f,f=y(n),"*"!==p||"/"!==f);++n,T&&(S(E,n-2,w),w=!0)}l=!0}}while(l);var x=n;if(r.lastIndex=0,!r.test(y(x++)))for(;x<d&&!r.test(y(x));)++x;return'"'!=(a=t.substring(n,n=x))&&"'"!=a||(_=a),a}function b(t){m.push(t)}function T(){if(!m.length){var t=E();if(null===t)return null;b(t)}return m[0]}return Object.defineProperty({next:E,peek:T,push:b,skip:function(t,e){var n=T();if(n===t)return E(),!0;if(e)return!1;throw g("token '"+n+"', '"+t+"' expected")},cmnt:function(t){var n,r=null;return t===rt?(n=f[h-1],delete f[h-1],n&&(e||"*"===n.type||n.lineEmpty)&&(r=n.leading?n.text:null)):(p<t&&T(),n=f[t],delete f[t],!n||n.lineEmpty||!e&&"/"!==n.type||(r=n.leading?null:n.text)),r}},"line",{get:function(){return h}})}p.unescape=u},{}],35:[function(t,e,n){e.exports=y;var r=t(23),i=(((y.prototype=Object.create(r.prototype)).constructor=y).className="Type",t(15)),s=t(25),a=t(16),o=t(20),l=t(33),c=t(21),d=t(27),h=t(42),u=t(37),p=t(14),f=t(13),m=t(40),_=t(12),g=t(41);function y(t,e){r.call(this,t,e),this.fields={},this.oneofs=rt,this.extensions=rt,this.reserved=rt,this.group=rt,this.S=null,this.e=null,this.I=null,this.N=null}function S(t){return t.S=t.e=t.I=null,delete t.encode,delete t.decode,delete t.verify,t}Object.defineProperties(y.prototype,{fieldsById:{get:function(){if(!this.S){this.S={};for(var t=Object.keys(this.fields),e=0;e<t.length;++e){var n=this.fields[t[e]],r=n.id;if(this.S[r])throw Error("duplicate id "+r+" in "+this);this.S[r]=n}}return this.S}},fieldsArray:{get:function(){return this.e||(this.e=u.toArray(this.fields))}},oneofsArray:{get:function(){return this.I||(this.I=u.toArray(this.oneofs))}},ctor:{get:function(){return this.N||(this.ctor=y.generateConstructor(this)())},set:function(t){for(var e=t.prototype,n=(e instanceof c||((t.prototype=new c).constructor=t,u.merge(t.prototype,e)),t.$type=t.prototype.$type=this,u.merge(t,c,!0),this.N=t,0);n<this.fieldsArray.length;++n)this.e[n].resolve();var r={};for(n=0;n<this.oneofsArray.length;++n)r[this.I[n].resolve().name]={get:u.oneOfGetter(this.I[n].oneof),set:u.oneOfSetter(this.I[n].oneof)};n&&Object.defineProperties(t.prototype,r)}}}),y.generateConstructor=function(t){for(var e,n=u.codegen(["p"],t.name),r=0;r<t.fieldsArray.length;++r)(e=t.e[r]).map?n("this%s={}",u.safeProp(e.name)):e.repeated&&n("this%s=[]",u.safeProp(e.name));return n("if(p)for(var ks=Object.keys(p),i=0;i<ks.length;++i)if(p[ks[i]]!=null)")("this[ks[i]]=p[ks[i]]")},y.fromJSON=function(t,e){for(var n=new y(t,e.options),c=(n.extensions=e.extensions,n.reserved=e.reserved,Object.keys(e.fields)),d=0;d<c.length;++d)n.add((void 0!==e.fields[c[d]].keyType?o:a).fromJSON(c[d],e.fields[c[d]]));if(e.oneofs)for(c=Object.keys(e.oneofs),d=0;d<c.length;++d)n.add(s.fromJSON(c[d],e.oneofs[c[d]]));if(e.nested)for(c=Object.keys(e.nested),d=0;d<c.length;++d){var h=e.nested[c[d]];n.add((h.id!==rt?a:h.fields!==rt?y:h.values!==rt?i:h.methods!==rt?l:r).fromJSON(c[d],h))}return e.extensions&&e.extensions.length&&(n.extensions=e.extensions),e.reserved&&e.reserved.length&&(n.reserved=e.reserved),e.group&&(n.group=!0),e.comment&&(n.comment=e.comment),e.edition&&(n.f=e.edition),n.a="proto3",n},y.prototype.toJSON=function(t){var e=r.prototype.toJSON.call(this,t),n=!!t&&!!t.keepComments;return u.toObject(["edition",this.c(),"options",e&&e.options||rt,"oneofs",r.arrayToJSON(this.oneofsArray,t),"fields",r.arrayToJSON(this.fieldsArray.filter(function(t){return!t.declaringField}),t)||{},"extensions",this.extensions&&this.extensions.length?this.extensions:rt,"reserved",this.reserved&&this.reserved.length?this.reserved:rt,"group",this.group||rt,"nested",e&&e.nested||rt,"comment",n?this.comment:rt])},y.prototype.resolveAll=function(){if(this.y){r.prototype.resolveAll.call(this);for(var t=this.oneofsArray,e=0;e<t.length;)t[e++].resolve();var n=this.fieldsArray;for(e=0;e<n.length;)n[e++].resolve()}return this},y.prototype.g=function(t){return this.w&&(r.prototype.g.call(this,t=this.f||t),this.oneofsArray.forEach(e=>{e.u(t)}),this.fieldsArray.forEach(e=>{e.u(t)})),this},y.prototype.get=function(t){return this.fields[t]||this.oneofs&&this.oneofs[t]||this.nested&&this.nested[t]||null},y.prototype.add=function(t){if(this.get(t.name))throw Error("duplicate name '"+t.name+"' in "+this);if(t instanceof a&&t.extend===rt){if((this.S||this.fieldsById)[t.id])throw Error("duplicate id "+t.id+" in "+this);if(this.isReservedId(t.id))throw Error("id "+t.id+" is reserved in "+this);if(this.isReservedName(t.name))throw Error("name '"+t.name+"' is reserved in "+this);return t.parent&&t.parent.remove(t),(this.fields[t.name]=t).message=this,t.onAdd(this),S(this)}return t instanceof s?(this.oneofs||(this.oneofs={}),(this.oneofs[t.name]=t).onAdd(this),S(this)):r.prototype.add.call(this,t)},y.prototype.remove=function(t){if(t instanceof a&&t.extend===rt){if(this.fields&&this.fields[t.name]===t)return delete this.fields[t.name],t.parent=null,t.onRemove(this),S(this);throw Error(t+" is not a member of "+this)}if(t instanceof s){if(this.oneofs&&this.oneofs[t.name]===t)return delete this.oneofs[t.name],t.parent=null,t.onRemove(this),S(this);throw Error(t+" is not a member of "+this)}return r.prototype.remove.call(this,t)},y.prototype.isReservedId=function(t){return r.isReservedId(this.reserved,t)},y.prototype.isReservedName=function(t){return r.isReservedName(this.reserved,t)},y.prototype.create=function(t){return new this.ctor(t)},y.prototype.setup=function(){for(var t=this.fullName,e=[],n=0;n<this.fieldsArray.length;++n)e.push(this.e[n].resolve().resolvedType);var r;return this.encode=p(this)({Writer:h,types:e,util:u}),this.decode=f(this)({Reader:d,types:e,util:u}),this.verify=m(this)({types:e,util:u}),this.fromObject=_.fromObject(this)({types:e,util:u}),this.toObject=_.toObject(this)({types:e,util:u}),(t=g[t])&&((r=Object.create(this)).fromObject=this.fromObject,this.fromObject=t.fromObject.bind(r),r.toObject=this.toObject,this.toObject=t.toObject.bind(r)),this},y.prototype.encode=function(t,e){return this.setup().encode(t,e)},y.prototype.encodeDelimited=function(t,e){return this.encode(t,e&&e.len?e.fork():e).ldelim()},y.prototype.decode=function(t,e){return this.setup().decode(t,e)},y.prototype.decodeDelimited=function(t){return t instanceof d||(t=d.create(t)),this.decode(t,t.uint32())},y.prototype.verify=function(t){return this.setup().verify(t)},y.prototype.fromObject=function(t){return this.setup().fromObject(t)},y.prototype.toObject=function(t,e){return this.setup().toObject(t,e)},y.d=function(t){return function(e){u.decorateType(e,t)}}},{12:12,13:13,14:14,15:15,16:16,20:20,21:21,23:23,25:25,27:27,33:33,37:37,40:40,41:41,42:42}],36:[function(t,e,n){t=t(37);var r=["double","float","int32","uint32","sint32","fixed32","sfixed32","int64","uint64","sint64","fixed64","sfixed64","bool","string","bytes"];function i(t,e){var n=0,i={};for(e|=0;n<t.length;)i[r[n+e]]=t[n++];return i}n.basic=i([1,5,0,0,0,5,5,0,0,0,1,1,0,2,2]),n.defaults=i([0,0,0,0,0,0,0,0,0,0,0,0,!1,"",t.emptyArray,null]),n.long=i([0,0,0,1,1],7),n.mapKey=i([0,0,0,5,5,0,0,0,1,1,0,2],2),n.packed=i([1,5,0,0,0,5,5,0,0,0,1,1,0])},{37:37}],37:[function(t,e,n){var r,i,s=e.exports=t(39),a=t(30),o=(s.codegen=t(3),s.fetch=t(5),s.path=t(8),s.fs=s.inquire("fs"),s.toArray=function(t){if(t){for(var e=Object.keys(t),n=Array(e.length),r=0;r<e.length;)n[r]=t[e[r++]];return n}return[]},s.toObject=function(t){for(var e={},n=0;n<t.length;){var r=t[n++],i=t[n++];i!==rt&&(e[r]=i)}return e},/\\/g),l=/"/g,c=(s.isReserved=function(t){return/^(?:do|if|in|for|let|new|try|var|case|else|enum|eval|false|null|this|true|void|with|break|catch|class|const|super|throw|while|yield|delete|export|import|public|return|static|switch|typeof|default|extends|finally|package|private|continue|debugger|function|arguments|interface|protected|implements|instanceof)$/.test(t)},s.safeProp=function(t){return!/^[$\w_]+$/.test(t)||s.isReserved(t)?'["'+t.replace(o,"\\\\").replace(l,'\\"')+'"]':"."+t},s.ucFirst=function(t){return(t[0]||"").toUpperCase()+t.substring(1)},/_([a-z])/g),d=(s.camelCase=function(t){return t.substring(0,1)+t.substring(1).replace(c,function(t,e){return e.toUpperCase()})},s.compareFieldsById=function(t,e){return t.id-e.id},s.decorateType=function(e,n){return e.$type?(n&&e.$type.name!==n&&(s.decorateRoot.remove(e.$type),e.$type.name=n,s.decorateRoot.add(e.$type)),e.$type):(n=new(r=r||t(35))(n||e.name),s.decorateRoot.add(n),n.ctor=e,Object.defineProperty(e,"$type",{value:n,enumerable:!1}),Object.defineProperty(e.prototype,"$type",{value:n,enumerable:!1}),n)},0);s.decorateEnum=function(e){var n;return e.$type||(n=new(i=i||t(15))("Enum"+d++,e),s.decorateRoot.add(n),Object.defineProperty(e,"$type",{value:n,enumerable:!1}),n)},s.setProperty=function(t,e,n,r){if("object"!=typeof t)throw TypeError("dst must be an object");if(e)return function t(e,n,i){var s=n.shift();if("__proto__"!==s&&"prototype"!==s)if(0<n.length)e[s]=t(e[s]||{},n,i);else{if((n=e[s])&&r)return e;n&&(i=[].concat(n).concat(i)),e[s]=i}return e}(t,e=e.split("."),n);throw TypeError("path must be specified")},Object.defineProperty(s,"decorateRoot",{get:function(){return a.decorated||(a.decorated=new(t(29)))}})},{15:15,29:29,3:3,30:30,35:35,39:39,5:5,8:8}],38:[function(t,e,n){e.exports=i;var r=t(39);function i(t,e){this.lo=t>>>0,this.hi=e>>>0}var s=i.zero=new i(0,0),a=(s.toNumber=function(){return 0},s.zzEncode=s.zzDecode=function(){return this},s.length=function(){return 1},i.zeroHash="\0\0\0\0\0\0\0\0",i.fromNumber=function(t){var e,n;return 0===t?s:(n=(t=(e=t<0)?-t:t)>>>0,t=(t-n)/4294967296>>>0,e&&(t=~t>>>0,n=~n>>>0,4294967295<++n&&(n=0,4294967295<++t&&(t=0))),new i(n,t))},i.from=function(t){if("number"==typeof t)return i.fromNumber(t);if(r.isString(t)){if(!r.Long)return i.fromNumber(parseInt(t,10));t=r.Long.fromString(t)}return t.low||t.high?new i(t.low>>>0,t.high>>>0):s},i.prototype.toNumber=function(t){var e;return!t&&this.hi>>>31?(e=~this.hi>>>0,-((t=1+~this.lo>>>0)+4294967296*(e=t?e:e+1>>>0))):this.lo+4294967296*this.hi},i.prototype.toLong=function(t){return r.Long?new r.Long(0|this.lo,0|this.hi,!!t):{low:0|this.lo,high:0|this.hi,unsigned:!!t}},String.prototype.charCodeAt);i.fromHash=function(t){return"\0\0\0\0\0\0\0\0"===t?s:new i((a.call(t,0)|a.call(t,1)<<8|a.call(t,2)<<16|a.call(t,3)<<24)>>>0,(a.call(t,4)|a.call(t,5)<<8|a.call(t,6)<<16|a.call(t,7)<<24)>>>0)},i.prototype.toHash=function(){return String.fromCharCode(255&this.lo,this.lo>>>8&255,this.lo>>>16&255,this.lo>>>24,255&this.hi,this.hi>>>8&255,this.hi>>>16&255,this.hi>>>24)},i.prototype.zzEncode=function(){var t=this.hi>>31;return this.hi=((this.hi<<1|this.lo>>>31)^t)>>>0,this.lo=(this.lo<<1^t)>>>0,this},i.prototype.zzDecode=function(){var t=-(1&this.lo);return this.lo=((this.lo>>>1|this.hi<<31)^t)>>>0,this.hi=(this.hi>>>1^t)>>>0,this},i.prototype.length=function(){var t=this.lo,e=(this.lo>>>28|this.hi<<4)>>>0,n=this.hi>>>24;return 0==n?0==e?t<16384?t<128?1:2:t<2097152?3:4:e<16384?e<128?5:6:e<2097152?7:8:n<128?9:10}},{39:39}],39:[function(t,e,n){var r=n;function i(t,e,n){for(var r=Object.keys(e),i=0;i<r.length;++i)t[r[i]]!==rt&&n||(t[r[i]]=e[r[i]]);return t}function s(t){function e(t,n){if(!(this instanceof e))return new e(t,n);Object.defineProperty(this,"message",{get:function(){return t}}),Error.captureStackTrace?Error.captureStackTrace(this,e):Object.defineProperty(this,"stack",{value:Error().stack||""}),n&&i(this,n)}return e.prototype=Object.create(Error.prototype,{constructor:{value:e,writable:!0,enumerable:!1,configurable:!0},name:{get:function(){return t},set:rt,enumerable:!1,configurable:!0},toString:{value:function(){return this.name+": "+this.message},writable:!0,enumerable:!1,configurable:!0}}),e}r.asPromise=t(1),r.base64=t(2),r.EventEmitter=t(4),r.float=t(6),r.inquire=t(7),r.utf8=t(10),r.pool=t(9),r.LongBits=t(38),r.isNode=!!("undefined"!=typeof global&&global&&global.process&&global.process.versions&&global.process.versions.node),r.global=r.isNode&&global||"undefined"!=typeof window&&window||"undefined"!=typeof self&&self||this,r.emptyArray=Object.freeze?Object.freeze([]):[],r.emptyObject=Object.freeze?Object.freeze({}):{},r.isInteger=Number.isInteger||function(t){return"number"==typeof t&&isFinite(t)&&Math.floor(t)===t},r.isString=function(t){return"string"==typeof t||t instanceof String},r.isObject=function(t){return t&&"object"==typeof t},r.isset=r.isSet=function(t,e){var n=t[e];return null!=n&&t.hasOwnProperty(e)&&("object"!=typeof n||0<(Array.isArray(n)?n:Object.keys(n)).length)},r.Buffer=function(){try{var t=r.inquire("buffer").Buffer;return t.prototype.utf8Write?t:null}catch(t){return null}}(),r.L=null,r.V=null,r.newBuffer=function(t){return"number"==typeof t?r.Buffer?r.V(t):new r.Array(t):r.Buffer?r.L(t):"undefined"==typeof Uint8Array?t:new Uint8Array(t)},r.Array="undefined"!=typeof Uint8Array?Uint8Array:Array,r.Long=r.global.dcodeIO&&r.global.dcodeIO.Long||r.global.Long||r.inquire("long"),r.key2Re=/^true|false|0|1$/,r.key32Re=/^-?(?:0|[1-9][0-9]*)$/,r.key64Re=/^(?:[\\x00-\\xff]{8}|-?(?:0|[1-9][0-9]*))$/,r.longToHash=function(t){return t?r.LongBits.from(t).toHash():r.LongBits.zeroHash},r.longFromHash=function(t,e){return t=r.LongBits.fromHash(t),r.Long?r.Long.fromBits(t.lo,t.hi,e):t.toNumber(!!e)},r.merge=i,r.lcFirst=function(t){return(t[0]||"").toLowerCase()+t.substring(1)},r.newError=s,r.ProtocolError=s("ProtocolError"),r.oneOfGetter=function(t){for(var e={},n=0;n<t.length;++n)e[t[n]]=1;return function(){for(var t=Object.keys(this),n=t.length-1;-1<n;--n)if(1===e[t[n]]&&this[t[n]]!==rt&&null!==this[t[n]])return t[n]}},r.oneOfSetter=function(t){return function(e){for(var n=0;n<t.length;++n)t[n]!==e&&delete this[t[n]]}},r.toJSONOptions={longs:String,enums:String,bytes:String,json:!0},r.p=function(){var t=r.Buffer;t?(r.L=t.from!==Uint8Array.from&&t.from||function(e,n){return new t(e,n)},r.V=t.allocUnsafe||function(e){return new t(e)}):r.L=r.V=null}},{1:1,10:10,2:2,38:38,4:4,6:6,7:7,9:9}],40:[function(t,e,n){e.exports=function(t){var e=i.codegen(["m"],t.name+"$verify")('if(typeof m!=="object"||m===null)')("return%j","object expected"),n={};t.oneofsArray.length&&e("var p={}");for(var r=0;r<t.fieldsArray.length;++r){var o,l=t.e[r].resolve(),c="m"+i.safeProp(l.name);l.optional&&e("if(%s!=null&&m.hasOwnProperty(%j)){",c,l.name),l.map?(e("if(!util.isObject(%s))",c)("return%j",s(l,"object"))("var k=Object.keys(%s)",c)("for(var i=0;i<k.length;++i){"),function(t,e,n){switch(e.keyType){case"int32":case"uint32":case"sint32":case"fixed32":case"sfixed32":t("if(!util.key32Re.test(%s))",n)("return%j",s(e,"integer key"));break;case"int64":case"uint64":case"sint64":case"fixed64":case"sfixed64":t("if(!util.key64Re.test(%s))",n)("return%j",s(e,"integer|Long key"));break;case"bool":t("if(!util.key2Re.test(%s))",n)("return%j",s(e,"boolean key"))}}(e,l,"k[i]"),a(e,l,r,c+"[k[i]]")("}")):l.repeated?(e("if(!Array.isArray(%s))",c)("return%j",s(l,"array"))("for(var i=0;i<%s.length;++i){",c),a(e,l,r,c+"[i]")("}")):(l.partOf&&(o=i.safeProp(l.partOf.name),1===n[l.partOf.name]&&e("if(p%s===1)",o)("return%j",l.partOf.name+": multiple values"),n[l.partOf.name]=1,e("p%s=1",o)),a(e,l,r,c)),l.optional&&e("}")}return e("return null")};var r=t(15),i=t(37);function s(t,e){return t.name+": "+e+(t.repeated&&"array"!==e?"[]":t.map&&"object"!==e?"{k:"+t.keyType+"}":"")+" expected"}function a(t,e,n,i){if(e.resolvedType)if(e.resolvedType instanceof r){t("switch(%s){",i)("default:")("return%j",s(e,"enum value"));for(var a=Object.keys(e.resolvedType.values),o=0;o<a.length;++o)t("case %i:",e.resolvedType.values[a[o]]);t("break")("}")}else t("{")("var e=types[%i].verify(%s);",n,i)("if(e)")("return%j+e",e.name+".")("}");else switch(e.type){case"int32":case"uint32":case"sint32":case"fixed32":case"sfixed32":t("if(!util.isInteger(%s))",i)("return%j",s(e,"integer"));break;case"int64":case"uint64":case"sint64":case"fixed64":case"sfixed64":t("if(!util.isInteger(%s)&&!(%s&&util.isInteger(%s.low)&&util.isInteger(%s.high)))",i,i,i,i)("return%j",s(e,"integer|Long"));break;case"float":case"double":t('if(typeof %s!=="number")',i)("return%j",s(e,"number"));break;case"bool":t('if(typeof %s!=="boolean")',i)("return%j",s(e,"boolean"));break;case"string":t("if(!util.isString(%s))",i)("return%j",s(e,"string"));break;case"bytes":t('if(!(%s&&typeof %s.length==="number"||util.isString(%s)))',i,i,i)("return%j",s(e,"buffer"))}return t}},{15:15,37:37}],41:[function(t,e,n){var r=t(21);n[".google.protobuf.Any"]={fromObject:function(t){if(t&&t["@type"]){var e,n=t["@type"].substring(1+t["@type"].lastIndexOf("/"));if(n=this.lookup(n))return~(e="."==(t["@type"][0]||"")?t["@type"].slice(1):t["@type"]).indexOf("/")||(e="/"+e),this.create({type_url:e,value:n.encode(n.fromObject(t)).finish()})}return this.fromObject(t)},toObject:function(t,e){var n,i,s="",a="";return e&&e.json&&t.type_url&&t.value&&(a=t.type_url.substring(1+t.type_url.lastIndexOf("/")),s=t.type_url.substring(0,1+t.type_url.lastIndexOf("/")),(n=this.lookup(a))&&(t=n.decode(t.value))),!(t instanceof this.ctor)&&t instanceof r?(n=t.$type.toObject(t,e),i="."===t.$type.fullName[0]?t.$type.fullName.slice(1):t.$type.fullName,n["@type"]=a=(s=""===s?"type.googleapis.com/":s)+i,n):this.toObject(t,e)}}},{21:21}],42:[function(t,e,n){e.exports=h;var r,i=t(39),s=i.LongBits,a=i.base64,o=i.utf8;function l(t,e,n){this.fn=t,this.len=e,this.next=rt,this.val=n}function c(){}function d(t){this.head=t.head,this.tail=t.tail,this.len=t.len,this.next=t.states}function h(){this.len=0,this.head=new l(c,0,0),this.tail=this.head,this.states=null}function u(){return i.Buffer?function(){return(h.create=function(){return new r})()}:function(){return new h}}function p(t,e,n){e[n]=255&t}function f(t,e){this.len=t,this.next=rt,this.val=e}function m(t,e,n){for(;t.hi;)e[n++]=127&t.lo|128,t.lo=(t.lo>>>7|t.hi<<25)>>>0,t.hi>>>=7;for(;127<t.lo;)e[n++]=127&t.lo|128,t.lo=t.lo>>>7;e[n++]=t.lo}function _(t,e,n){e[n]=255&t,e[n+1]=t>>>8&255,e[n+2]=t>>>16&255,e[n+3]=t>>>24}h.create=u(),h.alloc=function(t){return new i.Array(t)},i.Array!==Array&&(h.alloc=i.pool(h.alloc,i.Array.prototype.subarray)),h.prototype.M=function(t,e,n){return this.tail=this.tail.next=new l(t,e,n),this.len+=e,this},(f.prototype=Object.create(l.prototype)).fn=function(t,e,n){for(;127<t;)e[n++]=127&t|128,t>>>=7;e[n]=t},h.prototype.uint32=function(t){return this.len+=(this.tail=this.tail.next=new f((t>>>=0)<128?1:t<16384?2:t<2097152?3:t<268435456?4:5,t)).len,this},h.prototype.int32=function(t){return t<0?this.M(m,10,s.fromNumber(t)):this.uint32(t)},h.prototype.sint32=function(t){return this.uint32((t<<1^t>>31)>>>0)},h.prototype.int64=h.prototype.uint64=function(t){return t=s.from(t),this.M(m,t.length(),t)},h.prototype.sint64=function(t){return t=s.from(t).zzEncode(),this.M(m,t.length(),t)},h.prototype.bool=function(t){return this.M(p,1,t?1:0)},h.prototype.sfixed32=h.prototype.fixed32=function(t){return this.M(_,4,t>>>0)},h.prototype.sfixed64=h.prototype.fixed64=function(t){return t=s.from(t),this.M(_,4,t.lo).M(_,4,t.hi)},h.prototype.float=function(t){return this.M(i.float.writeFloatLE,4,t)},h.prototype.double=function(t){return this.M(i.float.writeDoubleLE,8,t)};var g=i.Array.prototype.set?function(t,e,n){e.set(t,n)}:function(t,e,n){for(var r=0;r<t.length;++r)e[n+r]=t[r]};h.prototype.bytes=function(t){var e,n=t.length>>>0;return n?(i.isString(t)&&(e=h.alloc(n=a.length(t)),a.decode(t,e,0),t=e),this.uint32(n).M(g,n,t)):this.M(p,1,0)},h.prototype.string=function(t){var e=o.length(t);return e?this.uint32(e).M(o.write,e,t):this.M(p,1,0)},h.prototype.fork=function(){return this.states=new d(this),this.head=this.tail=new l(c,0,0),this.len=0,this},h.prototype.reset=function(){return this.states?(this.head=this.states.head,this.tail=this.states.tail,this.len=this.states.len,this.states=this.states.next):(this.head=this.tail=new l(c,0,0),this.len=0),this},h.prototype.ldelim=function(){var t=this.head,e=this.tail,n=this.len;return this.reset().uint32(n),n&&(this.tail.next=t.next,this.tail=e,this.len+=n),this},h.prototype.finish=function(){for(var t=this.head.next,e=this.constructor.alloc(this.len),n=0;t;)t.fn(t.val,e,n),n+=t.len,t=t.next;return e},h.p=function(t){r=t,h.create=u(),r.p()}},{39:39}],43:[function(t,e,n){e.exports=s;var r=t(42),i=((s.prototype=Object.create(r.prototype)).constructor=s,t(39));function s(){r.call(this)}function a(t,e,n){t.length<40?i.utf8.write(t,e,n):e.utf8Write?e.utf8Write(t,n):e.write(t,n)}s.p=function(){s.alloc=i.V,s.writeBytesBuffer=i.Buffer&&i.Buffer.prototype instanceof Uint8Array&&"set"===i.Buffer.prototype.set.name?function(t,e,n){e.set(t,n)}:function(t,e,n){if(t.copy)t.copy(e,n,0,t.length);else for(var r=0;r<t.length;)e[n++]=t[r++]}},s.prototype.bytes=function(t){var e=(t=i.isString(t)?i.L(t,"base64"):t).length>>>0;return this.uint32(e),e&&this.M(s.writeBytesBuffer,e,t),this},s.prototype.string=function(t){var e=i.Buffer.byteLength(t);return this.uint32(e),e&&this.M(a,e,t),this},s.p()},{39:39,42:42}]},e={},i=function t(n){var i=e[n];return i||r[n][0].call(i=e[n]={exports:{}},t,i,i.exports),i.exports}(19),i.util.global.protobuf=i,"function"==typeof define&&define.amd&&define(["long"],function(t){return t&&t.isLong&&(i.util.Long=t,i.configure()),i}),"object"==typeof module&&module&&module.exports&&(module.exports=i)}(),$protobuf=protobuf,$Reader=$protobuf.Reader,$Writer=$protobuf.Writer,$util=$protobuf.util,$root=$protobuf.roots.default||($protobuf.roots.default={}),$root.MeshData=function(){function t(t){if(this.weights=[],t)for(var e=Object.keys(t),n=0;n<e.length;++n)null!=t[e[n]]&&(this[e[n]]=t[e[n]])}return t.prototype.index=0,t.prototype.weights=$util.emptyArray,t.create=function(e){return new t(e)},t.encode=function(t,e){if(e||(e=$Writer.create()),null!=t.index&&Object.hasOwnProperty.call(t,"index")&&e.uint32(8).int32(t.index),null!=t.weights&&t.weights.length){e.uint32(18).fork();for(var n=0;n<t.weights.length;++n)e.float(t.weights[n]);e.ldelim()}return e},t.encodeDelimited=function(t,e){return this.encode(t,e).ldelim()},t.decode=function(t,e,n){t instanceof $Reader||(t=$Reader.create(t));for(var r=void 0===e?t.len:t.pos+e,i=new $root.MeshData;t.pos<r;){var s=t.uint32();if(s===n)break;switch(s>>>3){case 1:i.index=t.int32();break;case 2:if(i.weights&&i.weights.length||(i.weights=[]),2==(7&s))for(var a=t.uint32()+t.pos;t.pos<a;)i.weights.push(t.float());else i.weights.push(t.float());break;default:t.skipType(7&s)}}return i},t.decodeDelimited=function(t){return t instanceof $Reader||(t=new $Reader(t)),this.decode(t,t.uint32())},t.verify=function(t){if("object"!=typeof t||null===t)return"object expected";if(null!=t.index&&t.hasOwnProperty("index")&&!$util.isInteger(t.index))return"index: integer expected";if(null!=t.weights&&t.hasOwnProperty("weights")){if(!Array.isArray(t.weights))return"weights: array expected";for(var e=0;e<t.weights.length;++e)if("number"!=typeof t.weights[e])return"weights: number[] expected"}return null},t.fromObject=function(t){if(t instanceof $root.MeshData)return t;var e=new $root.MeshData;if(null!=t.index&&(e.index=0|t.index),t.weights){if(!Array.isArray(t.weights))throw TypeError(".MeshData.weights: array expected");e.weights=[];for(var n=0;n<t.weights.length;++n)e.weights[n]=Number(t.weights[n])}return e},t.toObject=function(t,e){e||(e={});var n={};if((e.arrays||e.defaults)&&(n.weights=[]),e.defaults&&(n.index=0),null!=t.index&&t.hasOwnProperty("index")&&(n.index=t.index),t.weights&&t.weights.length){n.weights=[];for(var r=0;r<t.weights.length;++r)n.weights[r]=e.json&&!isFinite(t.weights[r])?String(t.weights[r]):t.weights[r]}return n},t.prototype.toJSON=function(){return this.constructor.toObject(this,$protobuf.util.toJSONOptions)},t.getTypeUrl=function(t){return void 0===t&&(t="type.googleapis.com"),t+"/MeshData"},t}(),$root.JointData=function(){function t(t){if(this.translate=[],t)for(var e=Object.keys(t),n=0;n<e.length;++n)null!=t[e[n]]&&(this[e[n]]=t[e[n]])}return t.prototype.translate=$util.emptyArray,t.prototype.rotate=$util.newBuffer([]),t.create=function(e){return new t(e)},t.encode=function(t,e){if(e||(e=$Writer.create()),null!=t.translate&&t.translate.length){e.uint32(10).fork();for(var n=0;n<t.translate.length;++n)e.float(t.translate[n]);e.ldelim()}return null!=t.rotate&&Object.hasOwnProperty.call(t,"rotate")&&e.uint32(18).bytes(t.rotate),e},t.encodeDelimited=function(t,e){return this.encode(t,e).ldelim()},t.decode=function(t,e,n){t instanceof $Reader||(t=$Reader.create(t));for(var r=void 0===e?t.len:t.pos+e,i=new $root.JointData;t.pos<r;){var s=t.uint32();if(s===n)break;switch(s>>>3){case 1:if(i.translate&&i.translate.length||(i.translate=[]),2==(7&s))for(var a=t.uint32()+t.pos;t.pos<a;)i.translate.push(t.float());else i.translate.push(t.float());break;case 2:i.rotate=t.bytes();break;default:t.skipType(7&s)}}return i},t.decodeDelimited=function(t){return t instanceof $Reader||(t=new $Reader(t)),this.decode(t,t.uint32())},t.verify=function(t){if("object"!=typeof t||null===t)return"object expected";if(null!=t.translate&&t.hasOwnProperty("translate")){if(!Array.isArray(t.translate))return"translate: array expected";for(var e=0;e<t.translate.length;++e)if("number"!=typeof t.translate[e])return"translate: number[] expected"}return null!=t.rotate&&t.hasOwnProperty("rotate")&&!(t.rotate&&"number"==typeof t.rotate.length||$util.isString(t.rotate))?"rotate: buffer expected":null},t.fromObject=function(t){if(t instanceof $root.JointData)return t;var e=new $root.JointData;if(t.translate){if(!Array.isArray(t.translate))throw TypeError(".JointData.translate: array expected");e.translate=[];for(var n=0;n<t.translate.length;++n)e.translate[n]=Number(t.translate[n])}return null!=t.rotate&&("string"==typeof t.rotate?$util.base64.decode(t.rotate,e.rotate=$util.newBuffer($util.base64.length(t.rotate)),0):t.rotate.length>=0&&(e.rotate=t.rotate)),e},t.toObject=function(t,e){e||(e={});var n={};if((e.arrays||e.defaults)&&(n.translate=[]),e.defaults&&(e.bytes===String?n.rotate="":(n.rotate=[],e.bytes!==Array&&(n.rotate=$util.newBuffer(n.rotate)))),t.translate&&t.translate.length){n.translate=[];for(var r=0;r<t.translate.length;++r)n.translate[r]=e.json&&!isFinite(t.translate[r])?String(t.translate[r]):t.translate[r]}return null!=t.rotate&&t.hasOwnProperty("rotate")&&(n.rotate=e.bytes===String?$util.base64.encode(t.rotate,0,t.rotate.length):e.bytes===Array?Array.prototype.slice.call(t.rotate):t.rotate),n},t.prototype.toJSON=function(){return this.constructor.toObject(this,$protobuf.util.toJSONOptions)},t.getTypeUrl=function(t){return void 0===t&&(t="type.googleapis.com"),t+"/JointData"},t}(),$root.FaceFrameData=function(){function t(t){if(this.js=[],this.ms=[],t)for(var e=Object.keys(t),n=0;n<e.length;++n)null!=t[e[n]]&&(this[e[n]]=t[e[n]])}return t.prototype.id=0,t.prototype.s="",t.prototype.sf=0,t.prototype.ef=0,t.prototype.bsw=$util.newBuffer([]),t.prototype.cs=$util.newBuffer([]),t.prototype.js=$util.emptyArray,t.prototype.ms=$util.emptyArray,t.prototype.bodyId=0,t.prototype.faceFrameType=0,t.prototype.asf=0,t.prototype.aef=0,t.prototype.n="",t.create=function(e){return new t(e)},t.encode=function(t,e){if(e||(e=$Writer.create()),null!=t.id&&Object.hasOwnProperty.call(t,"id")&&e.uint32(8).int32(t.id),null!=t.s&&Object.hasOwnProperty.call(t,"s")&&e.uint32(18).string(t.s),null!=t.sf&&Object.hasOwnProperty.call(t,"sf")&&e.uint32(24).int32(t.sf),null!=t.ef&&Object.hasOwnProperty.call(t,"ef")&&e.uint32(32).int32(t.ef),null!=t.bsw&&Object.hasOwnProperty.call(t,"bsw")&&e.uint32(42).bytes(t.bsw),null!=t.cs&&Object.hasOwnProperty.call(t,"cs")&&e.uint32(90).bytes(t.cs),null!=t.js&&t.js.length)for(var n=0;n<t.js.length;++n)$root.JointData.encode(t.js[n],e.uint32(98).fork()).ldelim();if(null!=t.ms&&t.ms.length)for(n=0;n<t.ms.length;++n)$root.MeshData.encode(t.ms[n],e.uint32(106).fork()).ldelim();return null!=t.bodyId&&Object.hasOwnProperty.call(t,"bodyId")&&e.uint32(112).int32(t.bodyId),null!=t.faceFrameType&&Object.hasOwnProperty.call(t,"faceFrameType")&&e.uint32(120).int32(t.faceFrameType),null!=t.asf&&Object.hasOwnProperty.call(t,"asf")&&e.uint32(128).int32(t.asf),null!=t.aef&&Object.hasOwnProperty.call(t,"aef")&&e.uint32(136).int32(t.aef),null!=t.n&&Object.hasOwnProperty.call(t,"n")&&e.uint32(146).string(t.n),e},t.encodeDelimited=function(t,e){return this.encode(t,e).ldelim()},t.decode=function(t,e,n){t instanceof $Reader||(t=$Reader.create(t));for(var r=void 0===e?t.len:t.pos+e,i=new $root.FaceFrameData;t.pos<r;){var s=t.uint32();if(s===n)break;switch(s>>>3){case 1:i.id=t.int32();break;case 2:i.s=t.string();break;case 3:i.sf=t.int32();break;case 4:i.ef=t.int32();break;case 5:i.bsw=t.bytes();break;case 11:i.cs=t.bytes();break;case 12:i.js&&i.js.length||(i.js=[]),i.js.push($root.JointData.decode(t,t.uint32()));break;case 13:i.ms&&i.ms.length||(i.ms=[]),i.ms.push($root.MeshData.decode(t,t.uint32()));break;case 14:i.bodyId=t.int32();break;case 15:i.faceFrameType=t.int32();break;case 16:i.asf=t.int32();break;case 17:i.aef=t.int32();break;case 18:i.n=t.string();break;default:t.skipType(7&s)}}return i},t.decodeDelimited=function(t){return t instanceof $Reader||(t=new $Reader(t)),this.decode(t,t.uint32())},t.verify=function(t){if("object"!=typeof t||null===t)return"object expected";if(null!=t.id&&t.hasOwnProperty("id")&&!$util.isInteger(t.id))return"id: integer expected";if(null!=t.s&&t.hasOwnProperty("s")&&!$util.isString(t.s))return"s: string expected";if(null!=t.sf&&t.hasOwnProperty("sf")&&!$util.isInteger(t.sf))return"sf: integer expected";if(null!=t.ef&&t.hasOwnProperty("ef")&&!$util.isInteger(t.ef))return"ef: integer expected";if(null!=t.bsw&&t.hasOwnProperty("bsw")&&!(t.bsw&&"number"==typeof t.bsw.length||$util.isString(t.bsw)))return"bsw: buffer expected";if(null!=t.cs&&t.hasOwnProperty("cs")&&!(t.cs&&"number"==typeof t.cs.length||$util.isString(t.cs)))return"cs: buffer expected";if(null!=t.js&&t.hasOwnProperty("js")){if(!Array.isArray(t.js))return"js: array expected";for(var e=0;e<t.js.length;++e)if(n=$root.JointData.verify(t.js[e]))return"js."+n}if(null!=t.ms&&t.hasOwnProperty("ms")){if(!Array.isArray(t.ms))return"ms: array expected";for(e=0;e<t.ms.length;++e){var n;if(n=$root.MeshData.verify(t.ms[e]))return"ms."+n}}return null!=t.bodyId&&t.hasOwnProperty("bodyId")&&!$util.isInteger(t.bodyId)?"bodyId: integer expected":null!=t.faceFrameType&&t.hasOwnProperty("faceFrameType")&&!$util.isInteger(t.faceFrameType)?"faceFrameType: integer expected":null!=t.asf&&t.hasOwnProperty("asf")&&!$util.isInteger(t.asf)?"asf: integer expected":null!=t.aef&&t.hasOwnProperty("aef")&&!$util.isInteger(t.aef)?"aef: integer expected":null!=t.n&&t.hasOwnProperty("n")&&!$util.isString(t.n)?"n: string expected":null},t.fromObject=function(t){if(t instanceof $root.FaceFrameData)return t;var e=new $root.FaceFrameData;if(null!=t.id&&(e.id=0|t.id),null!=t.s&&(e.s=String(t.s)),null!=t.sf&&(e.sf=0|t.sf),null!=t.ef&&(e.ef=0|t.ef),null!=t.bsw&&("string"==typeof t.bsw?$util.base64.decode(t.bsw,e.bsw=$util.newBuffer($util.base64.length(t.bsw)),0):t.bsw.length>=0&&(e.bsw=t.bsw)),null!=t.cs&&("string"==typeof t.cs?$util.base64.decode(t.cs,e.cs=$util.newBuffer($util.base64.length(t.cs)),0):t.cs.length>=0&&(e.cs=t.cs)),t.js){if(!Array.isArray(t.js))throw TypeError(".FaceFrameData.js: array expected");e.js=[];for(var n=0;n<t.js.length;++n){if("object"!=typeof t.js[n])throw TypeError(".FaceFrameData.js: object expected");e.js[n]=$root.JointData.fromObject(t.js[n])}}if(t.ms){if(!Array.isArray(t.ms))throw TypeError(".FaceFrameData.ms: array expected");for(e.ms=[],n=0;n<t.ms.length;++n){if("object"!=typeof t.ms[n])throw TypeError(".FaceFrameData.ms: object expected");e.ms[n]=$root.MeshData.fromObject(t.ms[n])}}return null!=t.bodyId&&(e.bodyId=0|t.bodyId),null!=t.faceFrameType&&(e.faceFrameType=0|t.faceFrameType),null!=t.asf&&(e.asf=0|t.asf),null!=t.aef&&(e.aef=0|t.aef),null!=t.n&&(e.n=String(t.n)),e},t.toObject=function(t,e){e||(e={});var n={};if((e.arrays||e.defaults)&&(n.js=[],n.ms=[]),e.defaults&&(n.id=0,n.s="",n.sf=0,n.ef=0,e.bytes===String?n.bsw="":(n.bsw=[],e.bytes!==Array&&(n.bsw=$util.newBuffer(n.bsw))),e.bytes===String?n.cs="":(n.cs=[],e.bytes!==Array&&(n.cs=$util.newBuffer(n.cs))),n.bodyId=0,n.faceFrameType=0,n.asf=0,n.aef=0,n.n=""),null!=t.id&&t.hasOwnProperty("id")&&(n.id=t.id),null!=t.s&&t.hasOwnProperty("s")&&(n.s=t.s),null!=t.sf&&t.hasOwnProperty("sf")&&(n.sf=t.sf),null!=t.ef&&t.hasOwnProperty("ef")&&(n.ef=t.ef),null!=t.bsw&&t.hasOwnProperty("bsw")&&(n.bsw=e.bytes===String?$util.base64.encode(t.bsw,0,t.bsw.length):e.bytes===Array?Array.prototype.slice.call(t.bsw):t.bsw),null!=t.cs&&t.hasOwnProperty("cs")&&(n.cs=e.bytes===String?$util.base64.encode(t.cs,0,t.cs.length):e.bytes===Array?Array.prototype.slice.call(t.cs):t.cs),t.js&&t.js.length){n.js=[];for(var r=0;r<t.js.length;++r)n.js[r]=$root.JointData.toObject(t.js[r],e)}if(t.ms&&t.ms.length)for(n.ms=[],r=0;r<t.ms.length;++r)n.ms[r]=$root.MeshData.toObject(t.ms[r],e);return null!=t.bodyId&&t.hasOwnProperty("bodyId")&&(n.bodyId=t.bodyId),null!=t.faceFrameType&&t.hasOwnProperty("faceFrameType")&&(n.faceFrameType=t.faceFrameType),null!=t.asf&&t.hasOwnProperty("asf")&&(n.asf=t.asf),null!=t.aef&&t.hasOwnProperty("aef")&&(n.aef=t.aef),null!=t.n&&t.hasOwnProperty("n")&&(n.n=t.n),n},t.prototype.toJSON=function(){return this.constructor.toObject(this,$protobuf.util.toJSONOptions)},t.getTypeUrl=function(t){return void 0===t&&(t="type.googleapis.com"),t+"/FaceFrameData"},t}(),$root.FaceFrameDataList=function(){function t(t){if(this.data=[],t)for(var e=Object.keys(t),n=0;n<e.length;++n)null!=t[e[n]]&&(this[e[n]]=t[e[n]])}return t.prototype.data=$util.emptyArray,t.create=function(e){return new t(e)},t.encode=function(t,e){if(e||(e=$Writer.create()),null!=t.data&&t.data.length)for(var n=0;n<t.data.length;++n)$root.FaceFrameData.encode(t.data[n],e.uint32(10).fork()).ldelim();return e},t.encodeDelimited=function(t,e){return this.encode(t,e).ldelim()},t.decode=function(t,e,n){t instanceof $Reader||(t=$Reader.create(t));for(var r=void 0===e?t.len:t.pos+e,i=new $root.FaceFrameDataList;t.pos<r;){var s=t.uint32();if(s===n)break;s>>>3==1?(i.data&&i.data.length||(i.data=[]),i.data.push($root.FaceFrameData.decode(t,t.uint32()))):t.skipType(7&s)}return i},t.decodeDelimited=function(t){return t instanceof $Reader||(t=new $Reader(t)),this.decode(t,t.uint32())},t.verify=function(t){if("object"!=typeof t||null===t)return"object expected";if(null!=t.data&&t.hasOwnProperty("data")){if(!Array.isArray(t.data))return"data: array expected";for(var e=0;e<t.data.length;++e){var n=$root.FaceFrameData.verify(t.data[e]);if(n)return"data."+n}}return null},t.fromObject=function(t){if(t instanceof $root.FaceFrameDataList)return t;var e=new $root.FaceFrameDataList;if(t.data){if(!Array.isArray(t.data))throw TypeError(".FaceFrameDataList.data: array expected");e.data=[];for(var n=0;n<t.data.length;++n){if("object"!=typeof t.data[n])throw TypeError(".FaceFrameDataList.data: object expected");e.data[n]=$root.FaceFrameData.fromObject(t.data[n])}}return e},t.toObject=function(t,e){e||(e={});var n={};if((e.arrays||e.defaults)&&(n.data=[]),t.data&&t.data.length){n.data=[];for(var r=0;r<t.data.length;++r)n.data[r]=$root.FaceFrameData.toObject(t.data[r],e)}return n},t.prototype.toJSON=function(){return this.constructor.toObject(this,$protobuf.util.toJSONOptions)},t.getTypeUrl=function(t){return void 0===t&&(t="type.googleapis.com"),t+"/FaceFrameDataList"},t}();const proxyProtobuf=protobuf.roots.default,CLIENT_QUIT_ACK_TIMEOUT_MS=3e3,pointNameObj={connect_sdk:"连接SDK",connect_sdk_success:"连接SDK成功",llm_text_sdk_received:"大模型输出的文本SDK前端收到",rendering_data_received:"客户端收到音频数据时间",rendering_display:"客户端播放音频数据时间",close_session:"关闭会话",audio_data_expired:"音频数据过期"};class Ttsa{clearReconnectTimer(){-1!==this.reconnectTimer&&(clearTimeout(this.reconnectTimer),this.reconnectTimer=-1),this.clearSocketReconnectTimer()}clearSocketReconnectTimer(){-1!==this.socketReconnectTimer&&(clearTimeout(this.socketReconnectTimer),this.socketReconnectTimer=-1)}startHeartbeat(){this.stopHeartbeat(),this.heartbeatTimer=window.setInterval(()=>{this.send("client_heartbeat",{timestamp:Date.now(),frame:this.getCurrentFrameIndex()})},this.HEARTBEAT_INTERVAL)}stopHeartbeat(){-1!==this.heartbeatTimer&&(clearInterval(this.heartbeatTimer),this.heartbeatTimer=-1)}constructor(t){var e=this;this.TAG="[TTSA]",this.connectedOnce=!1,this.quitRequested=!1,this.quitPromise=null,this._lastSessionId="",this.reconnectTimer=-1,this.socketReconnectTimer=-1,this.wsConnectTimer=0,this.enterOfflineFlag=!1,this.syncTimestampInterval=0,this.syncTimestampNum=5e3,this.SYNC_INTERVAL=3e5,this.lastSyncTime=Date.now(),this.heartbeatTimer=-1,this.HEARTBEAT_INTERVAL=2e3,this._isResume=!1,this.clearOldWsTimeoutTimer=()=>{this.wsConnectTimer&&(clearTimeout(this.wsConnectTimer),this.wsConnectTimer=0)},this.initWsTimeoutTimer=()=>{this.clearOldWsTimeoutTimer(),this.quitRequested||(this.wsConnectTimer=window.setTimeout(async function(){try{e.sdk.onMessage({code:EErrorCode.CONNECT_SOCKET_ERROR,message:"Error: socket长时间未下发数据"}),e.session_id&&(await e.sdk.stopSessionFromSocket("WS_NO_DATA_TIMEOUT"),e.ws.disconnect()),e.reStartSDK()}finally{e.clearOldWsTimeoutTimer()}},1e3*(this.reconnect_client_timeout+10)))},this.appInfo=t.appInfo,this.sdk=t.sdkInstance,this.room=t.room,this.session_id=t.session_id,this.token=t.token,this.framedata_proto_version=t.framedata_proto_version,this._uniqueSpeakId=0,this.runStartFrameIndex=t.runStartFrameIndex,this.ttsaStateChangeHandle=t.ttsaStateChangeHandle,this.reloadSuccess=t.reloadSuccess,this.session_speak_req_id=0,this.enterOfflineMode=t.enterOfflineMode,this.reStartSDK=t.reStartSDK,this.reconnect_client_timeout=t.reconnect_client_timeout,this.reconnect_timeout=t.reconnect_timeout,this.sendVoiceEnd=t.sendVoiceEnd,this.getCurrentFrameIndex=t.getCurrentFrameIndex;const n=lookup(t.url,{query:{token:this.token},path:t.path||"",transports:["websocket"],reconnection:!0,reconnectionAttempts:Infinity,reconnectionDelay:1e3,reconnectionDelayMax:1e3,randomizationFactor:.3});n.on("connect",()=>{if(this.quitRequested)return void n.disconnect();this.connectedOnce=!0,this.clearReconnectTimer(),this.initWsTimeoutTimer(),this.startHeartbeat(),this.enterOfflineFlag=!1,window.performanceTracker.markEnd(performanceConstant.ttsa_connect);const t={room:this.room,client_type:"web",invisible_mode:this.sdk.getPendingInvisibleMode()};this.send("enter_room",t),this.sdk.getStatus()===AvatarStatus.offline&&this.sdk.getIsInitialized()&&this.reloadSuccess()}),n.on("first_start_timestamp",e=>{this.quitRequested||(window.avatarSDKLogger.log(this.TAG,"first_start_timestamp",e),this.firstStartTimestamp(e.server_time),window.performanceTracker.markEnd(performanceConstant.ttsa_ready),window.performanceTracker.markStart(performanceConstant.ttsa_body_res),window.avatarSDKLogger.log(this.TAG,"ready"),this.reloadSuccess(),t.onReady())}),n.on("state_change",t=>{this.ttsaStateChangeHandle(t)}),n.on("tts_audio",e=>{try{const n=msgpack_min.decode(e);this.sendSdkPoint("rendering_data_received",{multi_turn_conversation_id:n[0].multi_turn_conversation_id}),window.avatarSDKLogger.log(this.TAG,"下发音频数据tts_audio",n),t.handleMessage(EFrameDataType.AUDIO,n)}catch(t){this.sdk.onMessage({code:EErrorCode.AUDIO_DECODE_ERROR,message:"Error: 音频数据解码失败",e:t})}}),n.on("face_data",async function(n){try{if(e.framedata_proto_version){let r=[];const i=new Uint8Array(n),s=pako.inflate(i);r=(proxyProtobuf.FaceFrameDataList.decode(s,void 0,()=>{}).toJSON()||{data:[]}).data.map(t=>{const e=(t.js||[]).map(t=>({translate:t.translate||[],rotate:t.rotate?scaledInt16BytesToFloat32(t.rotate):[]})),n=(t.ms||[]).map(t=>({index:t.index||0,weights:t.weights||[]}));return _extends({},t,{bsw:t.bsw?scaledInt16BytesToFloat32(t.bsw):[],js:e,ms:n,body_id:t.bodyId||0,face_frame_type:t.faceFrameType||0})}),t.handleMessage(EFrameDataType.FACE,r),"speak"!==r[0].s&&e.enterOfflineFlag&&(e.sendVoiceEnd(),e.enterOfflineFlag=!1),window.avatarSDKLogger.log(e.TAG,"face_data",r)}else{const r=msgpack_min.decode(n);window.avatarSDKLogger.log(e.TAG,"face_data",r),"speak"!==r[0].s&&e.enterOfflineFlag&&(e.sendVoiceEnd(),e.enterOfflineFlag=!1),t.handleMessage(EFrameDataType.FACE,r)}}catch(t){e.sdk.destroy(),e.sdk.onMessage({code:EErrorCode.FACE_DECODE_ERROR,message:"Error: 表情数据解码失败",e:t})}}),n.on("body_data",e=>{try{let n=msgpack_min.decode(e);window.performanceTracker.markEnd(performanceConstant.start_action_res,n[0].s);const r=n.map(t=>_extends({},t,{x_offset:[]}));window.avatarSDKLogger.log(this.TAG,"body_data",JSON.stringify(r),(new Date).getTime()),window.performanceTracker.markEnd(performanceConstant.ttsa_body_res),t.handleMessage(EFrameDataType.BODY,n)}catch(t){this.sdk.onMessage({code:EErrorCode.VIDEO_DECODE_ERROR,message:"Error: 身体数据解码失败",e:t})}}),n.on("event_data",e=>{try{const n=msgpack_min.decode(e);window.avatarSDKLogger.log(this.TAG,"event_data",JSON.stringify(n)),t.handleMessage(EFrameDataType.EVENT,n)}catch(t){this.sdk.onMessage({code:EErrorCode.EVENT_DECODE_ERROR,message:"Error: 事件数据解码失败",e:t})}}),n.on("sync_frame",e=>{t.handleMessage(EFrameDataType.SYNC_FRAME,e)}),n.on("aa_frame",e=>{window.avatarSDKLogger.log(this.TAG,"下发机器人视频帧aa_frame",e),t.handleAAFrame(e)}),n.on("error_message",t=>{this.sdk.onMessage({code:(null==t?void 0:t.error_code)||EErrorCode.TTSA_ERROR,message:(null==t?void 0:t.user_hint)||"TTSA 返回异常"})}),n.on("disconnect",r=>{this.clearOldWsTimeoutTimer(),this.stopHeartbeat(),this.quitRequested||"io client disconnect"===r||(this.enterOfflineFlag?window.avatarSDKLogger.warn(this.TAG,"已在离线处理中,忽略重复的disconnect事件"):(this.sdk.onMessage({code:EErrorCode.SOCKET_DISCONNECT,message:`client Warning: socket disconnect, ${r}`}),window.avatarSDKLogger.warn(this.TAG,`${t.url} 已断开`,"disconnect原因",r),this.enterOfflineFlag=!0,this.sdk.getStatus()===AvatarStatus.offline?this.sdk.onStatusChange(AvatarStatus.offline):this.enterOfflineMode(),-1===this.socketReconnectTimer&&this.reconnect_timeout>0&&(this.socketReconnectTimer=window.setTimeout(()=>{try{n.disconnect()}catch(t){window.avatarSDKLogger.warn(this.TAG,"disconnect error",t)}this.socketReconnectTimer=-1},1e3*this.reconnect_timeout)),-1===this.reconnectTimer&&(this.reconnectTimer=window.setTimeout(async function(){try{n.disconnect()}catch(t){window.avatarSDKLogger.warn(e.TAG,"disconnect error",t)}await e.sdk.stopSessionFromSocket("WS_TIMEOUT"),e.reStartSDK()},1e3*this.reconnect_client_timeout))))}),n.on("client_quit",t=>{window.avatarSDKLogger.warn(this.TAG,"client_quit","断开原因",t),this.quitRequested||(n.disconnect(),this.session_speak_req_id=0,Object.keys(t).length&&this.sdk.onMessage({code:EErrorCode.SOCKET_QUIT,message:`ttsa主动关闭 reason: ${JSON.stringify({e:t})}`,e:t}),["user","char_bin_load_error","admin kick","nebula admin stop","no_time"].includes(null==t?void 0:t.stop_reason)?(this.sdk.destroyClient(),this.sdk.onStatusChange(AvatarStatus.close)):(this.sdk.getStatus()===AvatarStatus.offline?this.sdk.onStatusChange(AvatarStatus.offline):this.enterOfflineMode(),this.reStartSDK()))}),n.on("connect_error",t=>{this.sdk.onMessage({code:EErrorCode.CONNECT_SOCKET_ERROR,message:"Error: socket连接失败",e:t})}),n.onAny((t,e)=>{this.ws.connected&&this.initWsTimeoutTimer()}),this.ws=n}start(){this._isResume?this._isResume=!1:this.stateChange("interactive_idle")}idle(){this.stateChange("idle")}listen(){this.stateChange("listen")}think(){this.stateChange("think")}interactiveidle(){this.stateChange("interactive_idle")}enterInvisibleMode(){this.send("switch_invisible_mode",{session_id:this.session_id,invisible_mode:!0})}exitInvisibleMode(){this.send("switch_invisible_mode",{session_id:this.session_id,invisible_mode:!1})}firstStartTimestamp(t){const e=Date.now()/1e3,n={server_time:t,client_time:e},r=this._getResumeInfo();this._isResume&&r&&r.client_frame>0?n.resume_from_offline_idle=r:this._isResume=!1,this.runStartFrameIndex(e),this.send("first_start_timestamp",n)}syncTimestamp(){this.syncTimestampInterval&&(clearInterval(this.syncTimestampInterval),this.syncTimestampInterval=0),this.syncTimestampInterval=setInterval(()=>{const t=Date.now();if(t-this.lastSyncTime>=this.SYNC_INTERVAL){const e=this.getCurrentFrameIndex();this.sendSyncTimestamp(e),this.lastSyncTime=t}},this.syncTimestampNum)}sendSyncTimestamp(t){const e=Date.now()/1e3;this.send("sync_frame",{client_time:e,source:FRAME_SOURCE_SOURCE,client_frame:t})}sendText(t,e,n,r={client_speak_id:""}){if(!this.ws.connected)return;const i=this.getUniqueSpeakId();null!=r&&r.client_speak_id||(r.client_speak_id=i);const s={ssml:t,is_start:e,is_end:n,extra:r,multi_turn_conversation_id:i,session_speak_req_id:this.session_speak_req_id,timestamp:Date.now(),sdkVersion:"2.4.0-alpha.3"};return this.sendSdkPoint("llm_text_sdk_received",_extends({},r,{is_start:e,is_end:n,content:{ssml:t},multi_turn_conversation_id:i,speak_id:this.session_speak_req_id++})),e&&(window.performanceTracker.markStart(performanceConstant.start_action_res,"speak"),window.performanceTracker.markStart(performanceConstant.start_action_render,"speak"),window.performanceTracker.markStart(performanceConstant.voice_response_play,"speak")),n&&this.updateUniqueSpeakId(),this.send("send_text",s),i}sendSdkPoint(t,e={},n){this.send("sdk_burial_point",_extends({},e,n,this.appInfo,{burial_type:1,session_id:this.session_id,event_en_name:t,event_cn_name:pointNameObj[t],device:navigator.userAgent,timestamp:e.timestamp||Date.now(),sdkVersion:"2.4.0-alpha.3"}))}stateChange(t,e){const n={state:t,params:e||{}};window.performanceTracker.markStart(performanceConstant.start_action_res,t),window.performanceTracker.markStart(performanceConstant.start_action_render,t),this.send("state_change",n)}sendPerfLog(t){}changeLayout(t){this.send("change_layout",t)}changeWalkConfig(t){this.send("walk_config",t)}send(t,e){this.ws.connected&&this.ws.emit(t,e)}sendDeviceInfo(t){this.send("stat_report",t)}getStatus(){return this.ws.connected}get hasConnected(){return this.connectedOnce}_setResumeInfoCallback(t,e){this._isResume=!0,this._lastSessionId=t,this.getResumeInfo=e}_getResumeInfo(){if(this.getResumeInfo){const t=this.getResumeInfo();return this._lastSessionId&&(t.last_session_id=this._lastSessionId),t}return null}updateUniqueSpeakId(){this._uniqueSpeakId+=1}getUniqueSpeakId(){return`${this._uniqueSpeakId}-${this.session_id}`}quit(t,e=CLIENT_QUIT_ACK_TIMEOUT_MS){return this.quitPromise||(this.quitRequested=!0,this.clearReconnectTimer(),this.clearOldWsTimeoutTimer(),this.stopHeartbeat(),this.quitPromise=this.sendClientQuit(t,e)),this.quitPromise}async sendClientQuit(t,e){this.ws.connected&&await this.ws.timeout(e).emitWithAck("client_quit",{stop_reason:t})}close(){this.ws&&this.ws.disconnect(),this.clearOldWsTimeoutTimer(),this.stopHeartbeat(),this.session_speak_req_id=0,this.clearReconnectTimer(),this.syncTimestampInterval&&(clearInterval(this.syncTimestampInterval),this.syncTimestampInterval=0)}connect(){this.ws.connect()}seekToFrame(t){this.ws.emit("seek_to_frame",{frame:t})}}function formatTimestamp(t){if(!t||"string"!=typeof t)return"N/A";try{const e=new Date(t);return isNaN(e.getTime())?"Invalid Date":`${e.getFullYear()}-${(e.getMonth()+1).toString().padStart(2,"0")}-${e.getDate().toString().padStart(2,"0")} ${e.getHours().toString().padStart(2,"0")}:${e.getMinutes().toString().padStart(2,"0")}:${e.getSeconds().toString().padStart(2,"0")}`}catch(e){return window.avatarSDKLogger.error("Error formatting timestamp:",e),t}}class DebugOverlay{constructor(t,e){this.container=null,this.sdkContainer=null,this.updateInterval=null,this.errors=[],this.fps=0,this.frameCount=0,this.lastFpsUpdate=performance.now(),this.videoInfo={name:"",body_id:0,id:0},this.audioInfo={sf:0,ef:0,ad:new Uint8Array},this.eventInfo={sf:0,ef:0,event:[]},this.memoryInfo={},this.perfMetrics={},this.currentFrameIndex=0,this.domRefs={},this.sdk=t,this.sdkContainer=t.el,this.sessionInfo=e,this.startTime=Date.now(),this.trackFPS(),this.trackMemory()}setAudioInfo(t){this.audioInfo=t}setEventData(t){this.eventInfo=t}addError(t){this.errors.unshift(t),this.errors.length>=20&&this.errors.pop()}show(){this.container||this.createOverlay(),this.container&&(this.container.style.display="block"),this.updateInterval||(this.updateInterval=window.setInterval(()=>this.updateTextOnly(),200)),this.updateTextOnly()}hide(){this.container&&(this.container.style.display="none"),this.updateInterval&&(clearInterval(this.updateInterval),this.updateInterval=null)}destroy(){var t;this.hide(),null!=(t=this.container)&&t.parentNode&&this.container.parentNode.removeChild(this.container),this.container=null}setVideoInfo(t){this.videoInfo=t}updateTextOnly(){var t,e;if(!this.container)return;this.sessionInfo.session_id=this.sdk.resourceManager.session_id,this.currentFrameIndex=null!=(t=null==(e=this.sdk.renderScheduler.frameAnimationController)?void 0:e.getCurrentFrame())?t:0,this.updatePerfMetrics(),this.updateMemory(),this.setText("look_name",this.sessionInfo.config.look_name),this.setText("video_name",`${this.videoInfo.name} - ${this.videoInfo.body_id}`),this.setText("session_id",this.sessionInfo.session_id),this.setText("frame_idx",String(this.currentFrameIndex)),this.setText("audio_info",`开始帧: ${this.audioInfo.sf} / 结束帧: ${this.audioInfo.ef} / 长度: ${this.audioInfo.ad.length}`),this.setText("event_info",`开始帧: ${this.eventInfo.sf} / 结束帧: ${this.eventInfo.ef} / 长度: ${this.eventInfo.event.length}`),this.setText("perf",this.formatPerfMetrics()),this.setText("fps",String(this.fps)),this.setText("mem",this.formatMemory());const n=((Date.now()-this.startTime)/1e3).toFixed(1);this.setText("session_start",formatTimestamp(this.sessionInfo.session_start_time)),this.setText("session_duration",`${n}s`),this.setText("network",this.getNetworkInfo()),this.setText("error_count",`(${this.errors.length})`),this.setText("error_log",this.formatErrors(!1)),this.setText("ttsa_error_log",this.formatErrors(!0))}setText(t,e){const n=this.domRefs[t];n&&(n.innerHTML=e)}copySessionId(){const t=this.sessionInfo.session_id;t&&navigator.clipboard.writeText(t).then(()=>{}).catch(t=>{console.warn("复制失败",t)})}createOverlay(){var t;this.container=document.createElement("div"),this.container.id="sdk-debug-overlay",this.applyStyles(this.container),this.container.style.userSelect="text";const e=(t,e,n="")=>{const r=document.createElement("div");r.style.marginBottom="8px",r.innerHTML=`<span style="color:#888;font-size:11px;">${e}:</span>`;const i=document.createElement("span");return i.style.color="#fff",i.style.fontSize="11px",i.style.marginLeft="4px",i.textContent=n,r.append(i),this.domRefs[t]=i,r},n=document.createElement("h3");n.textContent="🔍 调试信息",n.style.margin="0 0 12px 0",n.style.color="#00ff88",n.style.fontSize="14px";const r=document.createElement("div");r.append(n,e("look_name","角色look_name"),e("video_name","当前视频"),(()=>{const t=document.createElement("div");t.style.marginBottom="8px",t.style.display="flex",t.style.alignItems="center",t.style.gap="6px";const e=document.createElement("span");e.style.color="#888",e.style.fontSize="11px",e.textContent="会话 ID:";const n=document.createElement("span");n.style.color="#fff",n.style.fontSize="11px",n.style.wordBreak="break-all",n.style.flex="1",this.domRefs.session_id=n;const r=document.createElement("button");return r.textContent="复制",r.style.fontSize="10px",r.style.padding="2px 6px",r.style.borderRadius="3px",r.style.border="none",r.style.background="#007aff",r.style.color="#fff",r.style.cursor="pointer",r.onclick=()=>this.copySessionId(),t.append(e,n,r),t})(),e("frame_idx","当前帧"),e("audio_info","下发音频"),e("event_info","下发事件"),e("fps","FPS"));const i=document.createElement("div");i.style.marginBottom="8px",i.innerHTML='<span style="color:#888;font-size:11px;">性能耗时:</span>';const s=document.createElement("div");s.style.fontSize="11px",s.style.background="rgba(0,0,0,0.2)",s.style.padding="4px",s.style.borderRadius="4px",s.style.color="#fff",this.domRefs.perf=s,r.append(i,s);const a=document.createElement("div");a.style.borderTop="1px solid #444",a.style.paddingTop="8px",a.style.marginBottom="8px";const o=document.createElement("h4");o.style.margin="0 0 6px 0",o.style.fontSize="12px",o.style.color="#888";const l=document.createElement("span");this.domRefs.error_count=l,o.append("✅ 错误日志 ",l),a.append(o);const c=t=>{const e=document.createElement("pre");return e.style.margin="0 0 4px 0",e.style.padding="6px",e.style.background="rgba(255,255,255,0.05)",e.style.borderRadius="4px",e.style.fontSize="10px",e.style.lineHeight="1.3",e.style.color="#888",e.style.maxHeight="120px",e.style.overflowY="auto",e.style.whiteSpace="pre-wrap",this.domRefs[t]=e,e},d=c("error_log"),h=c("ttsa_error_log");a.append(d,h),r.append(a),r.append(e("mem","内存占用"),e("session_start","会话开始时间"),e("session_duration","会话时长"),e("network","网络信息")),this.container.append(r),null==(t=this.sdkContainer)||t.appendChild(this.container),this.enableDrag(this.container)}formatErrors(t){let e=this.errors;return e=e.filter(t?t=>t.code===EErrorCode.TTSA_ERROR:t=>t.code!==EErrorCode.TTSA_ERROR),0===e.length?"暂无错误":e.map(t=>`[${new Date(t.timestamp).toLocaleTimeString()}] ${t.code}: ${t.message}`).join("\n")}updatePerfMetrics(){if(!window.performanceTracker)return;const t=window.performanceTracker.getVideoMetrics();for(const[n,r]of Object.entries(t)){var e;const t=null!=(e=null==r?void 0:r.time)?e:0;this.perfMetrics[n]||(this.perfMetrics[n]={times:[],avg:0,last:0,count:0});const i=this.perfMetrics[n];i.times.push(t),i.last=t,i.count++,i.avg=i.times.reduce((t,e)=>t+e,0)/i.times.length}}formatPerfMetrics(){const t=this.perfMetrics;return Object.keys(t).length?Object.entries(t).map(([t,e])=>`${t}: 最近:${e.last.toFixed(2)}ms 平均:${e.avg.toFixed(2)}ms 次数:${e.count}`).join("<br>"):"暂无数据"}formatMemory(){const t=this.memoryInfo;return t.usedJSHeapSize?`${(t.usedJSHeapSize/1048576).toFixed(1)}MB / ${(t.totalJSHeapSize/1048576).toFixed(1)}MB / ${(t.jsHeapSizeLimit/1048576).toFixed(1)}MB`:"N/A"}trackFPS(){const t=e=>{this.frameCount++,e-this.lastFpsUpdate>=1e3&&(this.fps=this.frameCount,this.frameCount=0,this.lastFpsUpdate=e),requestAnimationFrame(t)};requestAnimationFrame(t)}updateMemory(){var t;if(null!=(t=window.performance)&&t.memory){const t=window.performance.memory;this.memoryInfo={jsHeapSizeLimit:t.jsHeapSizeLimit,totalJSHeapSize:t.totalJSHeapSize,usedJSHeapSize:t.usedJSHeapSize}}}trackMemory(){var t;null!=(t=window.performance)&&t.memory&&setInterval(()=>this.updateMemory(),1e3)}getNetworkInfo(){const t=navigator.connection;return t?`类型:${t.effectiveType} 下行:${t.downlink}Mbps 延迟:${t.rtt}ms`:"N/A"}applyStyles(t){t.style.position="fixed",t.style.bottom="50px",t.style.right="10px",t.style.width="350px",t.style.maxHeight="400px",t.style.overflowY="auto",t.style.background="rgba(0,0,0,0.8)",t.style.borderRadius="8px",t.style.padding="10px",t.style.zIndex="99999",t.style.fontSize="12px",t.style.color="#fff",t.style.textAlign="left"}enableDrag(t){let e=!1,n=0,r=0,i=0,s=0;t.style.cursor="move",t.addEventListener("mousedown",a=>{e=!0,n=a.clientX,r=a.clientY,i=t.offsetLeft,s=t.offsetTop,document.body.style.userSelect="none"}),document.addEventListener("mousemove",a=>{e&&(t.style.left=i+a.clientX-n+"px",t.style.top=s+a.clientY-r+"px",t.style.right=t.style.bottom="unset")}),document.addEventListener("mouseup",()=>{e=!1,document.body.style.userSelect=""})}}class NetworkMonitor{constructor(t){this.TAG="[NetworkMonitor]",this.retryCount=1,this.retryTimer=-1,this.options=t,this.bindHandleOnline=this._handleOnline.bind(this),this.bindHandleOffline=this._handleOffline.bind(this),this._initEventListeners()}_initEventListeners(){window.addEventListener("online",this.bindHandleOnline),window.addEventListener("offline",this.bindHandleOffline)}_handleOnline(){window.clearTimeout(this.retryTimer),NetworkMonitor.ONLINE=!0,this.options.onlineCallback("[NetworkMonitor] 网络已恢复")}_handleOffline(){NetworkMonitor.ONLINE=!1,this.options.offlineCallback("[NetworkMonitor] 网络已断开"),this._attempt()}_attempt(){let t=1e3;this.retryCount>1&&(t=1e3*Math.pow(2,this.retryCount)),this.retryTimer=window.setTimeout(()=>{},t)}setState(t){NetworkMonitor.ONLINE=t}destroy(){window.removeEventListener("online",this.bindHandleOnline),window.removeEventListener("offline",this.bindHandleOffline),this.retryTimer=-1,this.retryCount=1}}function Errors(t){var e,n;return{code:t.code,error_code:null!=(e=ERROR_CODE_MAP[t.code])?e:t.code,error_name:null!=(n=ERROR_NAME_MAP[t.code])?n:"UNKNOWN_ERROR",message:t.message,session_id:t.session_id||"",client_speak_id:t.client_speak_id,timestamp:Date.now(),originalError:t.e?JSON.stringify(t.e):null}}NetworkMonitor.ONLINE=!0;const DEBUG_BUILD$2="undefined"==typeof __SENTRY_DEBUG__||__SENTRY_DEBUG__,GLOBAL_OBJ=globalThis,SDK_VERSION="10.69.0";function getMainCarrier(){return getSentryCarrier(GLOBAL_OBJ),GLOBAL_OBJ}function getSentryCarrier(t){const e=t.__SENTRY__=t.__SENTRY__||{};return e.version=e.version||SDK_VERSION,e[SDK_VERSION]=e[SDK_VERSION]||{}}function getGlobalSingleton(t,e,n=GLOBAL_OBJ){const r=n.__SENTRY__=n.__SENTRY__||{},i=r[SDK_VERSION]=r[SDK_VERSION]||{};return i[t]||(i[t]=e())}const CONSOLE_LEVELS=["debug","info","warn","error","log","assert","trace"],PREFIX="Sentry Logger ",originalConsoleMethods={};function consoleSandbox(t){if(!("console"in GLOBAL_OBJ))return t();const e=GLOBAL_OBJ.console,n={},r=Object.keys(originalConsoleMethods);r.forEach(t=>{const r=originalConsoleMethods[t];n[t]=e[t],e[t]=r});try{return t()}finally{r.forEach(t=>{e[t]=n[t]})}}function enable(){_getLoggerSettings().enabled=!0}function disable(){_getLoggerSettings().enabled=!1}function isEnabled$1(){return _getLoggerSettings().enabled}function log(...t){_maybeLog("log",...t)}function warn(...t){_maybeLog("warn",...t)}function error(...t){_maybeLog("error",...t)}function _maybeLog(t,...e){DEBUG_BUILD$2&&isEnabled$1()&&consoleSandbox(()=>{GLOBAL_OBJ.console[t](`${PREFIX}[${t}]:`,...e)})}function _getLoggerSettings(){return DEBUG_BUILD$2?getGlobalSingleton("loggerSettings",()=>({enabled:!1})):{enabled:!1}}const debug={enable,disable,isEnabled:isEnabled$1,log,warn,error},STACKTRACE_FRAME_LIMIT=50,UNKNOWN_FUNCTION="?",WEBPACK_ERROR_REGEXP=/\(error: (.*)\)/,STRIP_FRAME_REGEXP=/captureMessage|captureException/;function createStackParser(...t){const e=t.sort((t,e)=>t[0]-e[0]).map(t=>t[1]);return(t,n=0,r=0)=>{const i=[],s=t.split("\n");for(let t=n;t<s.length;t++){let n=s[t];n.length>1024&&(n=n.slice(0,1024));const a=WEBPACK_ERROR_REGEXP.test(n)?n.replace(WEBPACK_ERROR_REGEXP,"$1"):n;if(!a.includes("Error: ")){for(const t of e){const e=t(a);if(e){i.push(e);break}}if(i.length>=STACKTRACE_FRAME_LIMIT+r)break}}return stripSentryFramesAndReverse(i.slice(r))}}function stripSentryFramesAndReverse(t){if(!t.length)return[];const e=Array.from(t);return/sentryWrapped/.test(getLastStackFrame(e).function||"")&&e.pop(),e.reverse(),STRIP_FRAME_REGEXP.test(getLastStackFrame(e).function||"")&&(e.pop(),STRIP_FRAME_REGEXP.test(getLastStackFrame(e).function||"")&&e.pop()),e.slice(0,STACKTRACE_FRAME_LIMIT).map(t=>({...t,filename:t.filename||getLastStackFrame(e).filename,function:t.function||UNKNOWN_FUNCTION}))}function getLastStackFrame(t){return t[t.length-1]||{}}const defaultFunctionName="<anonymous>";function getFunctionName(t){try{return t&&"function"==typeof t&&t.name||defaultFunctionName}catch{return defaultFunctionName}}function getFramesFromEvent(t){const e=t.exception;if(e){const t=[];try{return e.values.forEach(e=>{e.stacktrace.frames&&t.push(...e.stacktrace.frames)}),t}catch{return}}}const handlers$1={},instrumented$1={};function addHandler$1(t,e){return handlers$1[t]=handlers$1[t]||[],handlers$1[t].push(e),()=>{const n=handlers$1[t];if(n){const t=n.indexOf(e);-1!==t&&n.splice(t,1)}}}function maybeInstrument(t,e){if(!instrumented$1[t]){instrumented$1[t]=!0;try{e()}catch(e){DEBUG_BUILD$2&&debug.error(`Error while instrumenting ${t}`,e)}}}function triggerHandlers$1(t,e){const n=t&&handlers$1[t];if(n)for(const r of n)try{r(e)}catch(e){DEBUG_BUILD$2&&debug.error(`Error while triggering instrumentation handler.\nType: ${t}\nName: ${getFunctionName(r)}\nError:`,e)}}let _oldOnErrorHandler=null;function addGlobalErrorInstrumentationHandler(t){const e="error";addHandler$1(e,t),maybeInstrument(e,instrumentError)}function instrumentError(){_oldOnErrorHandler=GLOBAL_OBJ.onerror,GLOBAL_OBJ.onerror=function(t,e,n,r,i){return triggerHandlers$1("error",{column:r,error:i,line:n,msg:t,url:e}),!!_oldOnErrorHandler&&_oldOnErrorHandler.apply(this,arguments)},GLOBAL_OBJ.onerror.__SENTRY_INSTRUMENTED__=!0}let _oldOnUnhandledRejectionHandler=null;function addGlobalUnhandledRejectionInstrumentationHandler(t){const e="unhandledrejection";addHandler$1(e,t),maybeInstrument(e,instrumentUnhandledRejection)}function instrumentUnhandledRejection(){_oldOnUnhandledRejectionHandler=GLOBAL_OBJ.onunhandledrejection,GLOBAL_OBJ.onunhandledrejection=function(t){return triggerHandlers$1("unhandledrejection",t),!_oldOnUnhandledRejectionHandler||_oldOnUnhandledRejectionHandler.apply(this,arguments)},GLOBAL_OBJ.onunhandledrejection.__SENTRY_INSTRUMENTED__=!0}const objectToString=Object.prototype.toString;function isError(t){switch(objectToString.call(t)){case"[object Error]":case"[object Exception]":case"[object DOMException]":case"[object WebAssembly.Exception]":return!0;default:return isInstanceOf(t,Error)}}function isBuiltin(t,e){return objectToString.call(t)===`[object ${e}]`}function isErrorEvent$1(t){return isBuiltin(t,"ErrorEvent")}function isDOMError(t){return isBuiltin(t,"DOMError")}function isDOMException(t){return isBuiltin(t,"DOMException")}function isString(t){return isBuiltin(t,"String")}function isParameterizedString(t){return"object"==typeof t&&null!==t&&"__sentry_template_string__"in t&&"__sentry_template_values__"in t}function isPrimitive(t){return null===t||isParameterizedString(t)||"object"!=typeof t&&"function"!=typeof t}function isPlainObject(t){return isBuiltin(t,"Object")}function isObjectLike(t){return"object"==typeof t&&null!==t}function isEvent(t){return"undefined"!=typeof Event&&isInstanceOf(t,Event)}function isRegExp(t){return isBuiltin(t,"RegExp")}function isThenable(t){return Boolean(t?.then&&"function"==typeof t.then)}function isInstanceOf(t,e){try{return t instanceof e}catch{return!1}}function isRequest(t){return"undefined"!=typeof Request&&isInstanceOf(t,Request)}function fill(t,e,n){if(!(e in t))return;const r=t[e];if("function"!=typeof r)return;const i=n(r);"function"==typeof i&&markFunctionWrapped(i,r);try{t[e]=i}catch{DEBUG_BUILD$2&&debug.log(`Failed to replace method "${e}" in object`,t)}}function addNonEnumerableProperty(t,e,n){try{Object.defineProperty(t,e,{value:n,writable:!0,configurable:!0})}catch{DEBUG_BUILD$2&&debug.log(`Failed to add non-enumerable property "${String(e)}" to object`,t)}}function markFunctionWrapped(t,e){try{t.prototype=e.prototype=e.prototype||{},addNonEnumerableProperty(t,"__sentry_original__",e)}catch{}}function getOriginalFunction(t){return t.__sentry_original__}function convertToPlainObject(t){if(isError(t))return{message:t.message,name:t.name,stack:t.stack,...getOwnProperties(t)};if(isEvent(t)){const{type:e,target:n,currentTarget:r,detail:i}=t;return{type:e,target:n,currentTarget:r,...i?{detail:i}:{},...getOwnProperties(t)}}return t}function getOwnProperties(t){return isObjectLike(t)?Object.fromEntries(Object.entries(t)):{}}function extractExceptionKeysForMessage(t){const e=Object.keys(convertToPlainObject(t));return e.sort(),e[0]?e.join(", "):"[object has no keys]"}let RESOLVED_RUNNER;function withRandomSafeContext(t){if(void 0!==RESOLVED_RUNNER)return RESOLVED_RUNNER?RESOLVED_RUNNER(t):t();const e=/* @__PURE__ */Symbol.for("__SENTRY_SAFE_RANDOM_ID_WRAPPER__");return e in GLOBAL_OBJ&&"function"==typeof GLOBAL_OBJ[e]?(RESOLVED_RUNNER=GLOBAL_OBJ[e],RESOLVED_RUNNER(t)):(RESOLVED_RUNNER=null,t())}function safeMathRandom(){return withRandomSafeContext(()=>Math.random())}function safeDateNow(){return withRandomSafeContext(()=>Date.now())}const SENTRY_SKIP_NORMALIZATION=/* @__PURE__ */Symbol.for("sentry.skipNormalization"),SENTRY_OVERRIDE_NORMALIZATION_DEPTH=/* @__PURE__ */Symbol.for("sentry.overrideNormalizationDepth");function hasSkipNormalizationHint(t){return Boolean(t[SENTRY_SKIP_NORMALIZATION])}function getNormalizationDepthOverrideHint(t){const e=t[SENTRY_OVERRIDE_NORMALIZATION_DEPTH];return"number"==typeof e?e:void 0}let stringifier,emptyUuid;function normalize(t,e=100,n=Infinity){try{return visit("",t,e,n)}catch(t){return{ERROR:`**non-serializable** (${t})`}}}function normalizeToSize(t,e=3,n=102400){const r=normalize(t,e);return jsonSize(r)>n?normalizeToSize(t,e-1,n):r}function visit(t,e,n=Infinity,r=Infinity,i=memoBuilder()){const[s,a]=i;if(null==e||["boolean","string"].includes(typeof e)||"number"==typeof e&&Number.isFinite(e))return e;const o=stringifyValue(t,e);if(!o.startsWith("[object "))return o;if(hasSkipNormalizationHint(e))return e;const l=getNormalizationDepthOverrideHint(e),c=void 0!==l?l:n;if(0===c)return o.replace("object ","");if(s(e))return"[Circular ~]";const d=e;if(d&&"function"==typeof d.toJSON)try{return visit("",d.toJSON(),c-1,r,i)}catch{}const h=Array.isArray(e)?[]:{};let u=0;const p=convertToPlainObject(e);for(const t in p)if(Object.prototype.hasOwnProperty.call(p,t)){if(u>=r){h[t]="[MaxProperties ~]";break}h[t]=visit(t,p[t],c-1,r,i),u++}return a(e),h}function stringifyValue(t,e){try{return"undefined"!=typeof global&&e===global?"[Global]":"number"!=typeof e||Number.isFinite(e)?"function"==typeof e?`[Function: ${getFunctionName(e)}]`:"symbol"==typeof e?`[${String(e)}]`:"bigint"==typeof e?`[BigInt: ${String(e)}]`:`[object ${getConstructorName(e)}]`:`[${e}]`}catch(t){return`**non-serializable** (${t})`}}function getConstructorName(t){const e=Object.getPrototypeOf(t);return e?.constructor?e.constructor.name:"null prototype"}function utf8Length(t){return~-encodeURI(t).split(/%..|./).length}function jsonSize(t){return utf8Length(JSON.stringify(t))}function memoBuilder(){const t=/* @__PURE__ */new WeakSet;return[function(e){return!!t.has(e)||(t.add(e),!1)},function(e){t.delete(e)}]}function truncate(t,e=0){return"string"!=typeof t||0===e||t.length<=e?t:`${t.slice(0,e)}...`}function safeJoin(t,e){if(!Array.isArray(t))return"";const n=[];for(let e=0;e<t.length;e++){const r=t[e];isPrimitive(r)?n.push(String(r)):r instanceof Error?n.push(r.message?`${r.name}: ${r.message}`:r.name):n.push(stringifyValue(void 0,r))}return n.join(e)}function isMatchingPattern(t,e,n=!1){return!!isString(t)&&(isRegExp(e)?e.test(t):isString(e)?n?t===e:t.includes(e):"function"==typeof e&&e(t))}function stringMatchesSomePattern(t,e=[],n=!1){for(const r of e)if(isMatchingPattern(t,r,n))return!0;return!1}function getCrypto(){return GLOBAL_OBJ.crypto||GLOBAL_OBJ.msCrypto}function getRandomByte(){return 16*safeMathRandom()}function uuid4(t=getCrypto()){try{if(t?.randomUUID)return withRandomSafeContext(()=>t.randomUUID()).replace(/-/g,"")}catch{}return emptyUuid||(emptyUuid="10000000100040008000100000000000"),emptyUuid.replace(/[018]/g,t=>(t^(15&getRandomByte())>>t/4).toString(16))}function getFirstException(t){return t.exception?.values?.[0]}function getEventDescription(t){const{message:e,event_id:n}=t;if(e)return e;const r=getFirstException(t);return r?r.type&&r.value?`${r.type}: ${r.value}`:r.type||r.value||n||"<unknown>":n||"<unknown>"}function addExceptionTypeValue(t,e,n){const r=t.exception=t.exception||{},i=r.values=r.values||[],s=i[0]=i[0]||{};s.value||(s.value=e||""),s.type||(s.type=n||"Error")}function addExceptionMechanism(t,e){const n=getFirstException(t);if(!n)return;const r=n.mechanism;if(n.mechanism={type:"generic",handled:!0,...r,...e},e&&"data"in e){const t={...r?.data,...e.data};n.mechanism.data=t}}function checkOrSetAlreadyCaught(t){if(isAlreadyCaptured(t))return!0;try{addNonEnumerableProperty(t,"__sentry_captured__",!0)}catch{}return!1}function isAlreadyCaptured(t){try{return t.__sentry_captured__}catch{}}const ONE_SECOND_IN_MS=1e3;function dateTimestampInSeconds(){return safeDateNow()/ONE_SECOND_IN_MS}function createUnixTimestampInSecondsFunc(){const{performance:t}=GLOBAL_OBJ;if(!t?.now||!t.timeOrigin)return dateTimestampInSeconds;const e=t.timeOrigin;return()=>(e+withRandomSafeContext(()=>t.now()))/ONE_SECOND_IN_MS}let _cachedTimestampInSeconds;function timestampInSeconds(){return(_cachedTimestampInSeconds??(_cachedTimestampInSeconds=createUnixTimestampInSecondsFunc()))()}let cachedTimeOrigin=null;function getBrowserTimeOrigin(){const{performance:t}=GLOBAL_OBJ;if(!t?.now)return;const e=3e5,n=withRandomSafeContext(()=>t.now()),r=safeDateNow(),i=t.timeOrigin;if("number"==typeof i&&Math.abs(i+n-r)<e)return i;const s=t.timing?.navigationStart;return"number"==typeof s&&Math.abs(s+n-r)<e?s:r-n}function browserPerformanceTimeOrigin(){return null===cachedTimeOrigin&&(cachedTimeOrigin=getBrowserTimeOrigin()),cachedTimeOrigin}function makeSession(t){const e=timestampInSeconds(),n={sid:uuid4(),init:!0,timestamp:e,started:e,duration:0,status:"ok",errors:0,ignoreDuration:!1,toJSON:()=>sessionToJSON(n)};return t&&updateSession(n,t),n}function updateSession(t,e={}){if(e.user&&(!t.ipAddress&&e.user.ip_address&&(t.ipAddress=e.user.ip_address),t.did||e.did||(t.did=e.user.id||e.user.email||e.user.username)),t.timestamp=e.timestamp||timestampInSeconds(),e.abnormal_mechanism&&(t.abnormal_mechanism=e.abnormal_mechanism),e.ignoreDuration&&(t.ignoreDuration=e.ignoreDuration),e.sid&&(t.sid=32===e.sid.length?e.sid:uuid4()),void 0!==e.init&&(t.init=e.init),!t.did&&e.did&&(t.did=`${e.did}`),"number"==typeof e.started&&(t.started=e.started),t.ignoreDuration)t.duration=void 0;else if("number"==typeof e.duration)t.duration=e.duration;else{const e=t.timestamp-t.started;t.duration=e>=0?e:0}e.release&&(t.release=e.release),e.environment&&(t.environment=e.environment),!t.ipAddress&&e.ipAddress&&(t.ipAddress=e.ipAddress),!t.userAgent&&e.userAgent&&(t.userAgent=e.userAgent),"number"==typeof e.errors&&(t.errors=e.errors),e.status&&(t.status=e.status)}function closeSession(t,e){let n={};e?n={status:e}:"ok"===t.status&&(n={status:"exited"}),updateSession(t,n)}function sessionToJSON(t){return{sid:`${t.sid}`,init:t.init,started:new Date(1e3*t.started).toISOString(),timestamp:new Date(1e3*t.timestamp).toISOString(),status:t.status,errors:t.errors,did:"number"==typeof t.did||"string"==typeof t.did?`${t.did}`:void 0,duration:t.duration,abnormal_mechanism:t.abnormal_mechanism,attrs:{release:t.release,environment:t.environment,ip_address:t.ipAddress,user_agent:t.userAgent}}}function merge(t,e,n=2){if(!e||"object"!=typeof e||n<=0)return e;if(t&&0===Object.keys(e).length)return t;const r={...t};for(const t in e)Object.prototype.hasOwnProperty.call(e,t)&&(r[t]=merge(r[t],e[t],n-1));return r}function generateTraceId(){return uuid4()}function generateSpanId(){return uuid4().substring(16)}function makeWeakRef(t){try{const e=GLOBAL_OBJ.WeakRef;if("function"==typeof e)return new e(t)}catch{}return t}function derefWeakRef(t){if(t){if("object"==typeof t&&"deref"in t&&"function"==typeof t.deref)try{return t.deref()}catch{return}return t}}const SCOPE_SPAN_FIELD="_sentrySpan";function _setSpanForScope(t,e){e?addNonEnumerableProperty(t,SCOPE_SPAN_FIELD,makeWeakRef(e)):delete t[SCOPE_SPAN_FIELD]}function _getSpanForScope(t){return derefWeakRef(t[SCOPE_SPAN_FIELD])}const DEFAULT_MAX_BREADCRUMBS=100;class Scope{constructor(){this._notifyingListeners=!1,this._scopeListeners=[],this._eventProcessors=[],this._breadcrumbs=[],this._attachments=[],this._user={},this._tags={},this._attributes={},this._extra={},this._contexts={},this._sdkProcessingMetadata={},this._propagationContext={traceId:generateTraceId(),sampleRand:safeMathRandom()}}clone(){const t=new Scope;return t._breadcrumbs=[...this._breadcrumbs],t._tags={...this._tags},t._attributes={...this._attributes},t._extra={...this._extra},t._contexts={...this._contexts},this._contexts.flags&&(t._contexts.flags={values:[...this._contexts.flags.values]}),t._user=this._user,t._level=this._level,t._session=this._session,t._transactionName=this._transactionName,t._fingerprint=this._fingerprint,t._eventProcessors=[...this._eventProcessors],t._attachments=[...this._attachments],t._sdkProcessingMetadata={...this._sdkProcessingMetadata},t._propagationContext={...this._propagationContext},t._client=this._client,t._lastEventId=this._lastEventId,t._conversationId=this._conversationId,_setSpanForScope(t,_getSpanForScope(this)),t}setClient(t){this._client=t}setLastEventId(t){this._lastEventId=t}getClient(){return this._client}lastEventId(){return this._lastEventId}addScopeListener(t){this._scopeListeners.push(t)}addEventProcessor(t){return this._eventProcessors.push(t),this}setUser(t){return this._user=t||{email:void 0,id:void 0,ip_address:void 0,username:void 0},this._session&&updateSession(this._session,{user:t}),this._notifyScopeListeners(),this}getUser(){return this._user}setConversationId(t){return this._conversationId=t||void 0,this._notifyScopeListeners(),this}setTags(t){return this._tags={...this._tags,...t},this._notifyScopeListeners(),this}setTag(t,e){return this.setTags({[t]:e})}setAttributes(t){return this._attributes={...this._attributes,...t},this._notifyScopeListeners(),this}setAttribute(t,e){return this.setAttributes({[t]:e})}removeAttribute(t){return t in this._attributes&&(delete this._attributes[t],this._notifyScopeListeners()),this}setExtras(t){return this._extra={...this._extra,...t},this._notifyScopeListeners(),this}setExtra(t,e){return this._extra={...this._extra,[t]:e},this._notifyScopeListeners(),this}setFingerprint(t){return this._fingerprint=t,this._notifyScopeListeners(),this}setLevel(t){return this._level=t,this._notifyScopeListeners(),this}setTransactionName(t){return this._transactionName=t,this._notifyScopeListeners(),this}setContext(t,e){return null===e?delete this._contexts[t]:this._contexts[t]=e,this._notifyScopeListeners(),this}setSession(t){return t?this._session=t:delete this._session,this._notifyScopeListeners(),this}getSession(){return this._session}update(t){if(!t)return this;const e="function"==typeof t?t(this):t,n=e instanceof Scope?e.getScopeData():isPlainObject(e)?t:void 0,{tags:r,attributes:i,extra:s,user:a,contexts:o,level:l,fingerprint:c=[],propagationContext:d,conversationId:h}=n||{};return this._tags={...this._tags,...r},this._attributes={...this._attributes,...i},this._extra={...this._extra,...s},this._contexts={...this._contexts,...o},a&&Object.keys(a).length&&(this._user=a),l&&(this._level=l),c.length&&(this._fingerprint=c),d&&(this._propagationContext=d),h&&(this._conversationId=h),this}clear(){return this._breadcrumbs=[],this._tags={},this._attributes={},this._extra={},this._user={},this._contexts={},this._level=void 0,this._transactionName=void 0,this._fingerprint=void 0,this._session=void 0,this._conversationId=void 0,_setSpanForScope(this,void 0),this._attachments=[],this.setPropagationContext({traceId:generateTraceId(),sampleRand:safeMathRandom()}),this._notifyScopeListeners(),this}addBreadcrumb(t,e){const n="number"==typeof e?e:DEFAULT_MAX_BREADCRUMBS;if(n<=0)return this;const r={timestamp:dateTimestampInSeconds(),...t,message:t.message?truncate(t.message,2048):t.message};return this._breadcrumbs.push(r),this._breadcrumbs.length>n&&(this._breadcrumbs=this._breadcrumbs.slice(-n),this._client?.recordDroppedEvent("buffer_overflow","log_item")),this._notifyScopeListeners(),this}getLastBreadcrumb(){return this._breadcrumbs[this._breadcrumbs.length-1]}clearBreadcrumbs(){return this._breadcrumbs=[],this._notifyScopeListeners(),this}addAttachment(t){return this._attachments.push(t),this}clearAttachments(){return this._attachments=[],this}getScopeData(){return{breadcrumbs:this._breadcrumbs,attachments:this._attachments,contexts:this._contexts,tags:this._tags,attributes:this._attributes,extra:this._extra,user:this._user,level:this._level,fingerprint:this._fingerprint||[],eventProcessors:this._eventProcessors,propagationContext:this._propagationContext,sdkProcessingMetadata:this._sdkProcessingMetadata,transactionName:this._transactionName,span:_getSpanForScope(this),conversationId:this._conversationId}}setSDKProcessingMetadata(t){return this._sdkProcessingMetadata=merge(this._sdkProcessingMetadata,t,2),this}setPropagationContext(t){return this._propagationContext=t,this}getPropagationContext(){return this._propagationContext}captureException(t,e){const n=e?.event_id||uuid4();if(!this._client)return DEBUG_BUILD$2&&debug.warn("No client configured on scope - will not capture exception!"),n;const r=new Error("Sentry syntheticException");return this._client.captureException(t,{originalException:t,syntheticException:r,...e,event_id:n},this),n}captureMessage(t,e,n){const r=n?.event_id||uuid4();if(!this._client)return DEBUG_BUILD$2&&debug.warn("No client configured on scope - will not capture message!"),r;const i=n?.syntheticException??new Error(t);return this._client.captureMessage(t,e,{originalException:t,syntheticException:i,...n,event_id:r},this),r}captureEvent(t,e){const n=t.event_id||e?.event_id||uuid4();return this._client?(this._client.captureEvent(t,{...e,event_id:n},this),n):(DEBUG_BUILD$2&&debug.warn("No client configured on scope - will not capture event!"),n)}_notifyScopeListeners(){this._notifyingListeners||(this._notifyingListeners=!0,this._scopeListeners.forEach(t=>{t(this)}),this._notifyingListeners=!1)}}function getDefaultCurrentScope(){return getGlobalSingleton("defaultCurrentScope",()=>new Scope)}function getDefaultIsolationScope(){return getGlobalSingleton("defaultIsolationScope",()=>new Scope)}const isActualPromise=t=>t instanceof Promise&&!t[kChainedCopy],kChainedCopy=/* @__PURE__ */Symbol("chained PromiseLike"),chainAndCopyPromiseLike=(t,e,n)=>{const r=t.then(t=>(e(t),t),t=>{throw n(t),t});return isActualPromise(r)&&isActualPromise(t)?r:copyProps(t,r)},copyProps=(t,e)=>{if(!e)return t;let n=!1;for(const r in t){if(r in e)continue;n=!0;const i=t[r];"function"==typeof i?Object.defineProperty(e,r,{value:(...e)=>i.apply(t,e),enumerable:!0,configurable:!0,writable:!0}):e[r]=i}return n&&Object.assign(e,{[kChainedCopy]:!0}),e};class AsyncContextStack{constructor(t,e){let n,r;n=t||new Scope,r=e||new Scope,this._stack=[{scope:n}],this._isolationScope=r}withScope(t){const e=this._pushScope();let n;try{n=t(e)}catch(t){throw this._popScope(),t}return isThenable(n)?chainAndCopyPromiseLike(n,()=>this._popScope(),()=>this._popScope()):(this._popScope(),n)}getClient(){return this.getStackTop().client}getScope(){return this.getStackTop().scope}getIsolationScope(){return this._isolationScope}getStackTop(){return this._stack[this._stack.length-1]}_pushScope(){const t=this.getScope().clone();return this._stack.push({client:this.getClient(),scope:t}),t}_popScope(){return!(this._stack.length<=1||!this._stack.pop())}}function getAsyncContextStack(){const t=getSentryCarrier(getMainCarrier());return t.stack=t.stack||new AsyncContextStack(getDefaultCurrentScope(),getDefaultIsolationScope())}function withScope$1(t){return getAsyncContextStack().withScope(t)}function withSetScope(t,e){const n=getAsyncContextStack();return n.withScope(()=>(n.getStackTop().scope=t,e(t)))}function withIsolationScope(t){return getAsyncContextStack().withScope(()=>t(getAsyncContextStack().getIsolationScope()))}function getStackAsyncContextStrategy(){return{withIsolationScope,withScope:withScope$1,withSetScope,withSetIsolationScope:(t,e)=>withIsolationScope(e),getCurrentScope:()=>getAsyncContextStack().getScope(),getIsolationScope:()=>getAsyncContextStack().getIsolationScope()}}function getAsyncContextStrategy(t){const e=getSentryCarrier(t);return e.acs?e.acs:getStackAsyncContextStrategy()}function isAttributeObject(t){return"object"==typeof t&&null!=t&&!Array.isArray(t)&&Object.keys(t).includes("value")}function attributeValueToTypedAttributeValue(t,e){const{value:n,unit:r}=isAttributeObject(t)?t:{value:t,unit:void 0},i=getTypedAttributeValue(n),s=r&&"string"==typeof r?{unit:r}:{};if(i)return{...i,...s};if(!e||"skip-undefined"===e&&void 0===n)return;let a="";try{a=JSON.stringify(n)??""}catch{}return{value:a,type:"string",...s}}function serializeAttributes(t,e=!1){const n={};for(const[r,i]of Object.entries(t??{})){const t=attributeValueToTypedAttributeValue(i,e);t&&(n[r]=t)}return n}function getTypedAttributeValue(t){if(Array.isArray(t))return{value:t,type:"array"};const e="string"==typeof t?"string":"boolean"==typeof t?"boolean":"number"!=typeof t||Number.isNaN(t)?null:Number.isInteger(t)?"integer":"double";return e?{value:t,type:e}:void 0}let _externalPropagationContextProvider;function getExternalPropagationContext(){return _externalPropagationContextProvider?.()}function hasExternalPropagationContext(){return void 0!==_externalPropagationContextProvider}function getCurrentScope(){return getAsyncContextStrategy(getMainCarrier()).getCurrentScope()}function getIsolationScope(){return getAsyncContextStrategy(getMainCarrier()).getIsolationScope()}function getGlobalScope(){return getGlobalSingleton("globalScope",()=>new Scope)}function withScope(...t){const e=getAsyncContextStrategy(getMainCarrier());if(2===t.length){const[n,r]=t;return n?e.withSetScope(n,r):e.withScope(r)}return e.withScope(t[0])}function getClient(){return getCurrentScope().getClient()}function getTraceContextFromScope(t){const e=getExternalPropagationContext();if(e)return{trace_id:e.traceId,span_id:e.spanId};const n=t.getPropagationContext(),{traceId:r,parentSpanId:i,propagationSpanId:s}=n,a={trace_id:r,span_id:s||generateSpanId()};return i&&(a.parent_span_id=i),a}const SEMANTIC_ATTRIBUTE_SENTRY_SOURCE="sentry.source",SEMANTIC_ATTRIBUTE_SENTRY_SAMPLE_RATE="sentry.sample_rate",SEMANTIC_ATTRIBUTE_SENTRY_PREVIOUS_TRACE_SAMPLE_RATE="sentry.previous_trace_sample_rate",SEMANTIC_ATTRIBUTE_SENTRY_OP="sentry.op",SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN="sentry.origin",SEMANTIC_ATTRIBUTE_SENTRY_STATUS_MESSAGE="sentry.status.message",SEMANTIC_ATTRIBUTE_SENTRY_IDLE_SPAN_FINISH_REASON="sentry.idle_span_finish_reason",SEMANTIC_ATTRIBUTE_SENTRY_MEASUREMENT_UNIT="sentry.measurement_unit",SEMANTIC_ATTRIBUTE_SENTRY_MEASUREMENT_VALUE="sentry.measurement_value",SEMANTIC_ATTRIBUTE_SENTRY_CUSTOM_SPAN_NAME="sentry.custom_span_name",SEMANTIC_ATTRIBUTE_PROFILE_ID="sentry.profile_id",SEMANTIC_ATTRIBUTE_EXCLUSIVE_TIME="sentry.exclusive_time",SEMANTIC_LINK_ATTRIBUTE_LINK_TYPE="sentry.link.type",GEN_AI_CONVERSATION_ID_ATTRIBUTE="gen_ai.conversation.id",SPAN_STATUS_UNSET=0,SPAN_STATUS_OK=1,SPAN_STATUS_ERROR=2;function getSpanStatusFromHttpCode(t){if(t<400&&t>=100)return{code:SPAN_STATUS_OK};if(t>=400&&t<500)switch(t){case 401:return{code:SPAN_STATUS_ERROR,message:"unauthenticated"};case 403:return{code:SPAN_STATUS_ERROR,message:"permission_denied"};case 404:return{code:SPAN_STATUS_ERROR,message:"not_found"};case 409:return{code:SPAN_STATUS_ERROR,message:"already_exists"};case 413:return{code:SPAN_STATUS_ERROR,message:"failed_precondition"};case 429:return{code:SPAN_STATUS_ERROR,message:"resource_exhausted"};case 499:return{code:SPAN_STATUS_ERROR,message:"cancelled"};default:return{code:SPAN_STATUS_ERROR,message:"invalid_argument"}}if(t>=500&&t<600)switch(t){case 501:return{code:SPAN_STATUS_ERROR,message:"unimplemented"};case 503:return{code:SPAN_STATUS_ERROR,message:"unavailable"};case 504:return{code:SPAN_STATUS_ERROR,message:"deadline_exceeded"};default:return{code:SPAN_STATUS_ERROR,message:"internal_error"}}return{code:SPAN_STATUS_ERROR,message:"internal_error"}}function setHttpStatus(t,e){t.setAttribute("http.response.status_code",e);const n=getSpanStatusFromHttpCode(e);"unknown_error"!==n.message&&t.setStatus(n)}const SCOPE_ON_START_SPAN_FIELD="_sentryScope",ISOLATION_SCOPE_ON_START_SPAN_FIELD="_sentryIsolationScope",OTEL_SOURCE_INFERENCE_SPAN_FIELD=/* @__PURE__ */Symbol.for("sentry.otelSourceInference"),OTEL_SOURCE_EXPLICITLY_SET_SPAN_FIELD=/* @__PURE__ */Symbol.for("sentry.otelSourceExplicitlySet"),TRACER_PROVIDER_SPAN_FIELD=/* @__PURE__ */Symbol.for("sentry.tracerProviderSpan");function setCapturedScopesOnSpan(t,e,n){t&&(addNonEnumerableProperty(t,ISOLATION_SCOPE_ON_START_SPAN_FIELD,makeWeakRef(n)),addNonEnumerableProperty(t,SCOPE_ON_START_SPAN_FIELD,e))}function getCapturedScopesOnSpan(t){return{scope:t[SCOPE_ON_START_SPAN_FIELD],isolationScope:derefWeakRef(t[ISOLATION_SCOPE_ON_START_SPAN_FIELD])}}function spanShouldInferOtelSource(t){return!0===t[OTEL_SOURCE_INFERENCE_SPAN_FIELD]}function markSpanSourceAsExplicit(t){addNonEnumerableProperty(t,OTEL_SOURCE_EXPLICITLY_SET_SPAN_FIELD,!0)}function spanIsTracerProviderSpan(t){return!0===t[TRACER_PROVIDER_SPAN_FIELD]}const SENTRY_BAGGAGE_KEY_PREFIX="sentry-",MAX_BAGGAGE_STRING_LENGTH=8192;function baggageHeaderToDynamicSamplingContext(t){const e=parseBaggageHeader(t);if(!e)return;const n=Object.entries(e).reduce((t,[e,n])=>(e.startsWith(SENTRY_BAGGAGE_KEY_PREFIX)&&(t[e.slice(SENTRY_BAGGAGE_KEY_PREFIX.length)]=n),t),{});return Object.keys(n).length>0?n:void 0}function dynamicSamplingContextToSentryBaggageHeader(t){if(t)return objectToBaggageHeader(Object.entries(t).reduce((t,[e,n])=>(n&&(t[`${SENTRY_BAGGAGE_KEY_PREFIX}${e}`]=n),t),{}))}function parseBaggageHeader(t){if(t&&(isString(t)||Array.isArray(t)))return Array.isArray(t)?t.reduce((t,e)=>{const n=baggageHeaderToObject(e);return Object.entries(n).forEach(([e,n])=>{t[e]=n}),t},{}):baggageHeaderToObject(t)}function baggageHeaderToObject(t){return t.split(",").map(t=>{const e=t.indexOf("=");return-1===e?[]:[t.slice(0,e),t.slice(e+1)].map(t=>{try{return decodeURIComponent(t.trim())}catch{return}})}).reduce((t,[e,n])=>(e&&n&&(t[e]=n),t),{})}function objectToBaggageHeader(t){if(0!==Object.keys(t).length)return Object.entries(t).reduce((t,[e,n],r)=>{const i=`${encodeURIComponent(e)}=${encodeURIComponent(n)}`,s=0===r?i:`${t},${i}`;return s.length>MAX_BAGGAGE_STRING_LENGTH?(DEBUG_BUILD$2&&debug.warn(`Not adding key: ${e} with val: ${n} to baggage header due to exceeding baggage size limits.`),t):s},"")}const ORG_ID_REGEX=/^o(\d+)\./,DSN_REGEX=/^(?:(\w+):)\/\/(?:(\w+)(?::(\w+)?)?@)((?:\[[:.%\w]+\]|[\w.-]+))(?::(\d+))?\/(.+)/;function isValidProtocol(t){return"http"===t||"https"===t}function dsnToString(t,e=!1){const{host:n,path:r,pass:i,port:s,projectId:a,protocol:o,publicKey:l}=t;return`${o}://${l}${e&&i?`:${i}`:""}@${n}${s?`:${s}`:""}/${r?`${r}/`:r}${a}`}function dsnFromString(t){const e=DSN_REGEX.exec(t);if(!e)return void consoleSandbox(()=>{console.error(`Invalid Sentry Dsn: ${t}`)});const[n,r,i="",s="",a="",o=""]=e.slice(1);let l="",c=o;const d=c.split("/");if(d.length>1&&(l=d.slice(0,-1).join("/"),c=d.pop()),c){const t=c.match(/^\d+/);t&&(c=t[0])}return dsnFromComponents({host:s,pass:i,path:l,projectId:c,port:a,protocol:n,publicKey:r})}function dsnFromComponents(t){return{protocol:t.protocol,publicKey:t.publicKey||"",pass:t.pass||"",host:t.host,port:t.port||"",path:t.path||"",projectId:t.projectId}}function validateDsn(t){if(!DEBUG_BUILD$2)return!0;const{port:e,projectId:n,protocol:r}=t;return!(["protocol","publicKey","host","projectId"].find(e=>!t[e]&&(debug.error(`Invalid Sentry Dsn: ${e} missing`),!0))||(n.match(/^\d+$/)?isValidProtocol(r)?e&&isNaN(parseInt(e,10))&&(debug.error(`Invalid Sentry Dsn: Invalid port ${e}`),1):(debug.error(`Invalid Sentry Dsn: Invalid protocol ${r}`),1):(debug.error(`Invalid Sentry Dsn: Invalid projectId ${n}`),1)))}function extractOrgIdFromDsnHost(t){const e=t.match(ORG_ID_REGEX);return e?.[1]}function extractOrgIdFromClient(t){const e=t.getOptions(),{host:n}=t.getDsn()||{};let r;return e.orgId?r=String(e.orgId):n&&(r=extractOrgIdFromDsnHost(n)),r}function makeDsn(t){const e="string"==typeof t?dsnFromString(t):dsnFromComponents(t);if(e&&validateDsn(e))return e}function parseSampleRate(t){if("boolean"==typeof t)return Number(t);const e="string"==typeof t?parseFloat(t):t;return"number"!=typeof e||isNaN(e)||e<0||e>1?void 0:e}const TRACEPARENT_REGEXP=new RegExp("^[ \\t]*([0-9a-f]{32})?-?([0-9a-f]{16})?-?([01])?[ \\t]*$");function extractTraceparentData(t){if(!t)return;const e=t.match(TRACEPARENT_REGEXP);if(!e)return;let n;return"1"===e[3]?n=!0:"0"===e[3]&&(n=!1),{traceId:e[1],parentSampled:n,parentSpanId:e[2]}}function propagationContextFromHeaders(t,e){const n=extractTraceparentData(t),r=baggageHeaderToDynamicSamplingContext(e);if(!n?.traceId)return{traceId:generateTraceId(),sampleRand:safeMathRandom()};const i=getSampleRandFromTraceparentAndDsc(n,r);r&&(r.sample_rand=i.toString());const{traceId:s,parentSpanId:a,parentSampled:o}=n;return{traceId:s,parentSpanId:a,sampled:o,dsc:r||{},sampleRand:i}}function generateSentryTraceHeader(t=generateTraceId(),e=generateSpanId(),n){let r="";return void 0!==n&&(r=n?"-1":"-0"),`${t}-${e}${r}`}function generateTraceparentHeader(t=generateTraceId(),e=generateSpanId(),n){return`00-${t}-${e}-${n?"01":"00"}`}function getSampleRandFromTraceparentAndDsc(t,e){const n=parseSampleRate(e?.sample_rand);if(void 0!==n)return n;const r=parseSampleRate(e?.sample_rate);return r&&void 0!==t?.parentSampled?t.parentSampled?safeMathRandom()*r:r+safeMathRandom()*(1-r):safeMathRandom()}const TRACE_FLAG_NONE=0,TRACE_FLAG_SAMPLED=1;let hasShownSpanDropWarning=!1;function spanToTransactionTraceContext(t){const{spanId:e,traceId:n}=t.spanContext(),{data:r,op:i,parent_span_id:s,status:a,origin:o,links:l}=spanToJSON(t);return{parent_span_id:s,span_id:e,trace_id:n,data:r,op:i,status:a,origin:o,links:l}}function spanToTraceContext(t){const{spanId:e,traceId:n,isRemote:r}=t.spanContext(),i=r?e:spanToJSON(t).parent_span_id,s=getCapturedScopesOnSpan(t).scope;return{parent_span_id:i,span_id:r?s?.getPropagationContext().propagationSpanId||generateSpanId():e,trace_id:n}}function spanToTraceHeader(t){const{traceId:e,spanId:n}=t.spanContext();return generateSentryTraceHeader(e,n,spanIsSampled(t))}function spanToTraceparentHeader(t){const{traceId:e,spanId:n}=t.spanContext();return generateTraceparentHeader(e,n,spanIsSampled(t))}function convertSpanLinksForEnvelope(t){return t&&t.length>0?t.map(({context:{spanId:t,traceId:e,traceFlags:n,...r},attributes:i})=>({span_id:t,trace_id:e,sampled:n===TRACE_FLAG_SAMPLED,attributes:i,...r})):void 0}function getStreamedSpanLinks(t){return t?.length?t.map(({context:{spanId:t,traceId:e,traceFlags:n},attributes:r})=>({span_id:t,trace_id:e,sampled:n===TRACE_FLAG_SAMPLED,attributes:r})):void 0}function spanTimeInputToSeconds(t){return"number"==typeof t?ensureTimestampInSeconds(t):Array.isArray(t)?t[0]+t[1]/1e9:t instanceof Date?ensureTimestampInSeconds(t.getTime()):timestampInSeconds()}function ensureTimestampInSeconds(t){return t>9999999999?t/1e3:t}function spanToJSON(t){if(spanIsSentrySpan(t))return t.getSpanJSON();const{spanId:e,traceId:n}=t.spanContext();if(spanIsOpenTelemetrySdkTraceBaseSpan(t)){const{attributes:r,startTime:i,name:s,endTime:a,status:o,links:l}=t;return{span_id:e,trace_id:n,data:r,description:s,parent_span_id:getOtelParentSpanId(t),start_timestamp:spanTimeInputToSeconds(i),timestamp:spanTimeInputToSeconds(a)||void 0,status:getStatusMessage(o),op:r[SEMANTIC_ATTRIBUTE_SENTRY_OP],origin:r[SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN],links:convertSpanLinksForEnvelope(l)}}return{span_id:e,trace_id:n,start_timestamp:0,data:{}}}function spanToStreamedSpanJSON(t){if(spanIsSentrySpan(t))return t.getStreamedSpanJSON();const{spanId:e,traceId:n}=t.spanContext();if(spanIsOpenTelemetrySdkTraceBaseSpan(t)){const{attributes:r,startTime:i,name:s,endTime:a,status:o,links:l}=t;return{name:s,span_id:e,trace_id:n,parent_span_id:getOtelParentSpanId(t),start_timestamp:spanTimeInputToSeconds(i),end_timestamp:spanTimeInputToSeconds(a),is_segment:t===INTERNAL_getSegmentSpan(t),status:getSimpleStatus(o),attributes:addStatusMessageAttribute(r,o),links:getStreamedSpanLinks(l)}}return{span_id:e,trace_id:n,start_timestamp:0,name:"",end_timestamp:0,status:"ok",is_segment:t===INTERNAL_getSegmentSpan(t)}}function getOtelParentSpanId(t){return"parentSpanId"in t?t.parentSpanId:"parentSpanContext"in t?t.parentSpanContext?.spanId:void 0}function streamedSpanJsonToSerializedSpan(t){return{...t,attributes:serializeAttributes(t.attributes),links:t.links?.map(t=>({...t,attributes:serializeAttributes(t.attributes)}))}}function spanIsOpenTelemetrySdkTraceBaseSpan(t){return!!(t.attributes&&t.startTime&&t.name&&t.endTime&&t.status)}function spanIsSentrySpan(t){return"function"==typeof t.getSpanJSON}function spanIsSampled(t){const{traceFlags:e}=t.spanContext();return e===TRACE_FLAG_SAMPLED}function getStatusMessage(t){if(t&&t.code!==SPAN_STATUS_UNSET)return t.code===SPAN_STATUS_OK?"ok":t.message||"internal_error"}function getSimpleStatus(t){return t&&t.code!==SPAN_STATUS_OK&&t.code!==SPAN_STATUS_UNSET&&"cancelled"!==t.message?"error":"ok"}function addStatusMessageAttribute(t,e){const n="error"===getSimpleStatus(e)?e?.message:void 0;return{...n&&{[SEMANTIC_ATTRIBUTE_SENTRY_STATUS_MESSAGE]:n},...t}}const CHILD_SPANS_FIELD="_sentryChildSpans",ROOT_SPAN_FIELD="_sentryRootSpan";function addChildSpanToSpan(t,e){addNonEnumerableProperty(e,ROOT_SPAN_FIELD,t[ROOT_SPAN_FIELD]||t),t[CHILD_SPANS_FIELD]?t[CHILD_SPANS_FIELD].add(e):addNonEnumerableProperty(t,CHILD_SPANS_FIELD,/* @__PURE__ */new Set([e]))}function removeChildSpanFromSpan(t,e){t[CHILD_SPANS_FIELD]&&t[CHILD_SPANS_FIELD].delete(e)}function getSpanDescendants(t){const e=/* @__PURE__ */new Set;return function t(n){if(!e.has(n)&&spanIsSampled(n)){e.add(n);const r=n[CHILD_SPANS_FIELD]?Array.from(n[CHILD_SPANS_FIELD]):[];for(const e of r)t(e)}}(t),Array.from(e)}const getRootSpan=INTERNAL_getSegmentSpan;function INTERNAL_getSegmentSpan(t){return t[ROOT_SPAN_FIELD]||t}function getActiveSpan(){const t=getAsyncContextStrategy(getMainCarrier());return t.getActiveSpan?t.getActiveSpan():_getSpanForScope(getCurrentScope())}function showSpanDropWarning(){hasShownSpanDropWarning||(consoleSandbox(()=>{console.warn("[Sentry] Returning null from `beforeSendSpan` is disallowed. To drop certain spans, configure the respective integrations directly or use `ignoreSpans`.")}),hasShownSpanDropWarning=!0)}let errorsInstrumented=!1;function registerSpanErrorInstrumentation(){function t(){const t=getActiveSpan(),e=t&&getRootSpan(t);if(e){const t="internal_error";DEBUG_BUILD$2&&debug.log(`[Tracing] Root span: ${t} -> Global error occurred`),e.setStatus({code:SPAN_STATUS_ERROR,message:t})}}errorsInstrumented||(errorsInstrumented=!0,addGlobalErrorInstrumentationHandler(t),addGlobalUnhandledRejectionInstrumentationHandler(t))}function hasSpansEnabled(t){if("boolean"==typeof __SENTRY_TRACING__&&!__SENTRY_TRACING__)return!1;const e=t||getClient()?.getOptions();return!(!e||null==e.tracesSampleRate&&!e.tracesSampler)}function logIgnoredSpan(t){debug.log(`Ignoring span ${t.op} - ${t.description} because it matches \`ignoreSpans\`.`)}function shouldIgnoreSpan(t,e){if(!e?.length)return!1;for(const n of e){if(isStringOrRegExp(n)){if(t.description&&isMatchingPattern(t.description,n))return DEBUG_BUILD$2&&logIgnoredSpan(t),!0;continue}const e=!!n.attributes&&Object.keys(n.attributes).length>0;if(!n.name&&!n.op&&!e)continue;const r=!n.name||t.description&&isMatchingPattern(t.description,n.name),i=!n.op||t.op&&isMatchingPattern(t.op,n.op),s=!n.attributes||Object.entries(n.attributes).every(([e,n])=>_matchesAttributeValue(t.attributes?.[e],n));if(r&&i&&s)return DEBUG_BUILD$2&&logIgnoredSpan(t),!0}return!1}function _matchesAttributeValue(t,e){return"string"==typeof t&&("string"==typeof e||e instanceof RegExp)?isMatchingPattern(t,e):Array.isArray(t)&&Array.isArray(e)?t.length===e.length&&t.every((t,n)=>t===e[n]):t===e}function reparentChildSpans(t,e){const n=e.parent_span_id,r=e.span_id;if(n)for(const e of t)e.parent_span_id===r&&(e.parent_span_id=n)}function isStringOrRegExp(t){return"string"==typeof t||t instanceof RegExp}const NON_RECORDING_SPAN_FIELD=/* @__PURE__ */Symbol.for("sentry.nonRecordingSpan");class SentryNonRecordingSpan{constructor(t={}){this._traceId=t.traceId||generateTraceId(),this._spanId=t.spanId||generateSpanId(),this.dropReason=t.dropReason,addNonEnumerableProperty(this,NON_RECORDING_SPAN_FIELD,!0)}spanContext(){return{spanId:this._spanId,traceId:this._traceId,traceFlags:TRACE_FLAG_NONE}}end(t){}setAttribute(t,e){return this}setAttributes(t){return this}setStatus(t){return this}updateName(t){return this}isRecording(){return!1}addEvent(t,e,n){return this}addLink(t){return this}addLinks(t){return this}recordException(t,e){}}function spanIsNonRecordingSpan(t){return!!t&&!0===t[NON_RECORDING_SPAN_FIELD]}const DEFAULT_ENVIRONMENT="production",FROZEN_DSC_FIELD="_frozenDsc";function freezeDscOnSpan(t,e){addNonEnumerableProperty(t,FROZEN_DSC_FIELD,e)}function getDynamicSamplingContextFromClient(t,e){const n=e.getOptions(),{publicKey:r}=e.getDsn()||{},i={environment:n.environment||DEFAULT_ENVIRONMENT,release:n.release,public_key:r,trace_id:t,org_id:extractOrgIdFromClient(e)};return e.emit("createDsc",i),i}function getDynamicSamplingContextFromScope(t,e){const n=e.getPropagationContext();return n.dsc||getDynamicSamplingContextFromClient(n.traceId,t)}function getDynamicSamplingContextFromSpan(t){const e=getClient();if(!e)return{};const n=getRootSpan(t),r=spanToJSON(n),i=r.data,s=n.spanContext().traceState,a=s?.get("sentry.sample_rate")??i[SEMANTIC_ATTRIBUTE_SENTRY_SAMPLE_RATE]??i[SEMANTIC_ATTRIBUTE_SENTRY_PREVIOUS_TRACE_SAMPLE_RATE];function o(t){return"number"!=typeof a&&"string"!=typeof a||(t.sample_rate=`${a}`),t}const l=n[FROZEN_DSC_FIELD];if(l)return o(l);const c=spanIsNonRecordingSpan(n),d=c&&"ignored"===n.dropReason;if(c&&(!hasSpansEnabled(e.getOptions())||d)){const t=getCapturedScopesOnSpan(n).scope;if(t){const n={...getDynamicSamplingContextFromScope(e,t)};return d&&(n.sampled="false"),o(n)}}const h=s?.get("sentry.dsc"),u=h&&baggageHeaderToDynamicSamplingContext(h);if(u)return o(u);const p=getDynamicSamplingContextFromClient(t.spanContext().traceId,e),f=r.description;return"url"!==(i[SEMANTIC_ATTRIBUTE_SENTRY_SOURCE]??i["sentry.segment.name.source"])&&f&&(p.transaction=f),hasSpansEnabled()&&(p.sampled=String(spanIsSampled(n)),p.sample_rand=s?.get("sentry.sample_rand")??getCapturedScopesOnSpan(n).scope?.getPropagationContext().sampleRand.toString()),o(p),e.emit("createDsc",p,n),p}function isStreamedBeforeSendSpanCallback(t){return!!t&&"function"==typeof t&&"_streamed"in t&&!!t._streamed}function createEnvelope(t,e=[]){return[t,e]}function addItemToEnvelope(t,e){const[n,r]=t;return[n,[...r,e]]}function forEachEnvelopeItem(t,e){const n=t[1];for(const t of n)if(e(t,t[0].type))return!0;return!1}function envelopeContainsItemType(t,e){return forEachEnvelopeItem(t,(t,n)=>e.includes(n))}function encodeUTF8(t){const e=getSentryCarrier(GLOBAL_OBJ);return e.encodePolyfill?e.encodePolyfill(t):(new TextEncoder).encode(t)}function serializeEnvelope(t){const[e,n]=t;let r=JSON.stringify(e);function i(t){"string"==typeof r?r="string"==typeof t?r+t:[encodeUTF8(r),t]:r.push("string"==typeof t?encodeUTF8(t):t)}for(const t of n){const[e,n]=t;if(i(`\n${JSON.stringify(e)}\n`),"string"==typeof n||n instanceof Uint8Array)i(n);else{let t;try{t=JSON.stringify(n)}catch{t=JSON.stringify(normalize(n))}i(t)}}return"string"==typeof r?r:concatBuffers(r)}function concatBuffers(t){const e=t.reduce((t,e)=>t+e.length,0),n=new Uint8Array(e);let r=0;for(const e of t)n.set(e,r),r+=e.length;return n}function createSpanEnvelopeItem(t){return[{type:"span"},t]}function createAttachmentEnvelopeItem(t){const e="string"==typeof t.data?encodeUTF8(t.data):t.data;return[{type:"attachment",length:e.length,filename:t.filename,content_type:t.contentType,attachment_type:t.attachmentType},e]}const DATA_CATEGORY_OVERRIDES={sessions:"session",event:"error",client_report:"internal",user_report:"default",profile_chunk:"profile",replay_event:"replay",replay_recording:"replay",check_in:"monitor",raw_security:"security",log:"log_item",trace_metric:"metric"};function _isOverriddenType(t){return t in DATA_CATEGORY_OVERRIDES}function envelopeItemTypeToDataCategory(t){return _isOverriddenType(t)?DATA_CATEGORY_OVERRIDES[t]:t}function getSdkMetadataForEnvelopeHeader(t){if(!t?.sdk)return;const{name:e,version:n}=t.sdk;return{name:e,version:n}}function createEventEnvelopeHeaders(t,e,n,r){const i=t.sdkProcessingMetadata?.dynamicSamplingContext;return{event_id:t.event_id,sent_at:new Date(safeDateNow()).toISOString(),...e&&{sdk:e},...!!n&&r&&{dsn:dsnToString(r)},...i&&{trace:i}}}function _enhanceEventWithSdkInfo(t,e){if(!e)return t;const n=t.sdk||{};return t.sdk={...n,name:n.name||e.name,version:n.version||e.version,integrations:[...t.sdk?.integrations||[],...e.integrations||[]],packages:[...t.sdk?.packages||[],...e.packages||[]],settings:t.sdk?.settings||e.settings?{...t.sdk?.settings,...e.settings}:void 0},t}function createSessionEnvelope(t,e,n,r){const i=getSdkMetadataForEnvelopeHeader(n);return createEnvelope({sent_at:new Date(safeDateNow()).toISOString(),...i&&{sdk:i},...!!r&&e&&{dsn:dsnToString(e)}},["aggregates"in t?[{type:"sessions"},t]:[{type:"session"},t.toJSON()]])}function createEventEnvelope(t,e,n,r){const i=getSdkMetadataForEnvelopeHeader(n),s=t.type&&"replay_event"!==t.type?t.type:"event";_enhanceEventWithSdkInfo(t,n?.sdk);const a=createEventEnvelopeHeaders(t,i,r,e);return delete t.sdkProcessingMetadata,createEnvelope(a,[[{type:s},t]])}function createSpanEnvelope(t,e){const n=getDynamicSamplingContextFromSpan(t[0]),r=e?.getDsn(),i=e?.getOptions().tunnel,s={sent_at:new Date(safeDateNow()).toISOString(),...(a=n,!!a.trace_id&&!!a.public_key&&{trace:n}),...!!i&&r&&{dsn:dsnToString(r)}};var a;const{beforeSendSpan:o,ignoreSpans:l}=e?.getOptions()||{},c=l?.length?t.filter(t=>{const e=spanToJSON(t);return!shouldIgnoreSpan({description:e.description,op:e.op,attributes:e.data},l)}):t,d=t.length-c.length;d&&e?.recordDroppedEvent("before_send","span",d);const h=o?t=>{const e=spanToJSON(t);return(isStreamedBeforeSendSpanCallback(o)?e:o(e))||(showSpanDropWarning(),e)}:spanToJSON,u=[];for(const t of c){const e=h(t);e&&u.push(createSpanEnvelopeItem(e))}return createEnvelope(s,u)}function logSpanStart(t){if(!DEBUG_BUILD$2)return;const{description:e="< unknown name >",op:n="< unknown op >",parent_span_id:r}=spanToJSON(t),{spanId:i}=t.spanContext(),s=spanIsSampled(t),a=getRootSpan(t),o=a===t,l=`[Tracing] Starting ${s?"sampled":"unsampled"} ${o?"root ":""}span`,c=[`op: ${n}`,`name: ${e}`,`ID: ${i}`];if(r&&c.push(`parent ID: ${r}`),!o){const{op:t,description:e}=spanToJSON(a);c.push(`root ID: ${a.spanContext().spanId}`),t&&c.push(`root op: ${t}`),e&&c.push(`root description: ${e}`)}debug.log(`${l}\n ${c.join("\n ")}`)}function logSpanEnd(t){if(!DEBUG_BUILD$2)return;const{description:e="< unknown name >",op:n="< unknown op >"}=spanToJSON(t),{spanId:r}=t.spanContext(),i=getRootSpan(t);debug.log(`[Tracing] Finishing "${n}" ${i===t?"root ":""}span "${e}" with ID ${r}`)}function setMeasurement(t,e,n,r=getActiveSpan()){const i=r&&getRootSpan(r);i&&(DEBUG_BUILD$2&&debug.log(`[Measurement] Setting measurement on root span: ${t} = ${e} ${n}`),i.addEvent(t,{[SEMANTIC_ATTRIBUTE_SENTRY_MEASUREMENT_VALUE]:e,[SEMANTIC_ATTRIBUTE_SENTRY_MEASUREMENT_UNIT]:n}))}function timedEventsToMeasurements(t){if(!t||0===t.length)return;const e={};return t.forEach(t=>{const n=t.attributes||{},r=n[SEMANTIC_ATTRIBUTE_SENTRY_MEASUREMENT_UNIT],i=n[SEMANTIC_ATTRIBUTE_SENTRY_MEASUREMENT_VALUE];"string"==typeof r&&"number"==typeof i&&(e[t.name]={value:i,unit:r})}),e}function getSegmentSpanCaptureStrategy(){return getSentryCarrier(getMainCarrier()).segmentSpanCaptureStrategy}function hasSpanStreamingEnabled(t){return"stream"===t.getOptions().traceLifecycle}const MAX_SPAN_COUNT=1e3;class SentrySpan{constructor(t={}){this._traceId=t.traceId||generateTraceId(),this._spanId=t.spanId||generateSpanId(),this._startTime=t.startTimestamp||timestampInSeconds(),this._links=t.links,this._attributes={},this.setAttributes({[SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN]:"manual",[SEMANTIC_ATTRIBUTE_SENTRY_OP]:t.op,...t.attributes}),this._name=t.name,t.parentSpanId&&(this._parentSpanId=t.parentSpanId),"sampled"in t&&(this._sampled=t.sampled),t.endTimestamp&&(this._endTime=t.endTimestamp),this._events=[],this._isStandaloneSpan=t.isStandalone,this._endTime&&this._onSpanEnded()}addLink(t){return this._frozen||(this._links?this._links.push(t):this._links=[t]),this}addLinks(t){return this._frozen||(this._links?this._links.push(...t):this._links=t),this}recordException(t,e){}spanContext(){const{_spanId:t,_traceId:e,_sampled:n}=this;return{spanId:t,traceId:e,traceFlags:n?TRACE_FLAG_SAMPLED:TRACE_FLAG_NONE}}setAttribute(t,e){return this._frozen||(void 0===e?delete this._attributes[t]:this._attributes[t]=e,t===SEMANTIC_ATTRIBUTE_SENTRY_SOURCE&&void 0!==e&&spanShouldInferOtelSource(this)&&markSpanSourceAsExplicit(this)),this}setAttributes(t){return Object.keys(t).forEach(e=>this.setAttribute(e,t[e])),this}updateStartTime(t){this._frozen||(this._startTime=spanTimeInputToSeconds(t))}setStatus(t){return this._frozen||(this._status=t),this}updateName(t){return this._frozen||(this._name=t,spanShouldInferOtelSource(this)||this.setAttribute(SEMANTIC_ATTRIBUTE_SENTRY_SOURCE,"custom")),this}end(t){this._endTime||(this._endTime=spanTimeInputToSeconds(t),logSpanEnd(this),this._onSpanEnded()),this._frozen=spanIsTracerProviderSpan(this)}getSpanJSON(){return{data:this._attributes,description:this._name,op:this._attributes[SEMANTIC_ATTRIBUTE_SENTRY_OP],parent_span_id:this._parentSpanId,span_id:this._spanId,start_timestamp:this._startTime,status:getStatusMessage(this._status),timestamp:this._endTime,trace_id:this._traceId,origin:this._attributes[SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN],profile_id:this._attributes[SEMANTIC_ATTRIBUTE_PROFILE_ID],exclusive_time:this._attributes[SEMANTIC_ATTRIBUTE_EXCLUSIVE_TIME],measurements:timedEventsToMeasurements(this._events),is_segment:this._isStandaloneSpan&&getRootSpan(this)===this||void 0,segment_id:this._isStandaloneSpan?getRootSpan(this).spanContext().spanId:void 0,links:convertSpanLinksForEnvelope(this._links)}}getStreamedSpanJSON(){return{name:this._name??"",span_id:this._spanId,trace_id:this._traceId,parent_span_id:this._parentSpanId,start_timestamp:this._startTime,end_timestamp:this._endTime??this._startTime,is_segment:this._isStandaloneSpan||this===getRootSpan(this),status:getSimpleStatus(this._status),attributes:addStatusMessageAttribute(this._attributes,this._status),links:getStreamedSpanLinks(this._links)}}isRecording(){return!this._endTime&&!!this._sampled}addEvent(t,e,n){if(this._frozen)return this;DEBUG_BUILD$2&&debug.log("[Tracing] Adding an event to span:",t);const r=isSpanTimeInput(e)?e:n||timestampInSeconds(),i=isSpanTimeInput(e)?{}:e||{},s={name:t,time:spanTimeInputToSeconds(r),attributes:i};return this._events.push(s),this}isStandaloneSpan(){return!!this._isStandaloneSpan}_onSpanEnded(){const t=getClient();t&&(t.emit("spanEnd",this),this._isStandaloneSpan||t.emit("afterSpanEnd",this));const e=getRootSpan(this),n=this._isStandaloneSpan||this===e;if(this._isStandaloneSpan)return void(this._sampled?sendSpanEnvelope(createSpanEnvelope([this],t)):(DEBUG_BUILD$2&&debug.log("[Tracing] Discarding standalone span because its trace was not chosen to be sampled."),t&&t.recordDroppedEvent("sample_rate","span")));if(!n){const t=getSegmentSpanCaptureStrategy();if(t){const n=getCapturedScopesOnSpan(this).scope||getCurrentScope();t.onChildSpanEnded(this,e,t=>this._convertSpanToTransaction(t),n)}return}if(t&&hasSpanStreamingEnabled(t))return void t.emit("afterSegmentSpanEnd",this);const r=getCapturedScopesOnSpan(this).scope||getCurrentScope(),i=getSegmentSpanCaptureStrategy();if(i)i.onSegmentSpanEnded(t=>this._convertSpanToTransaction(t),r);else{const t=this._convertSpanToTransaction();t&&r.captureEvent(t)}}_convertSpanToTransaction(t={}){if(!isFullFinishedSpan(spanToJSON(this)))return;this._name||(DEBUG_BUILD$2&&debug.warn("Transaction has no name, falling back to `<unlabeled transaction>`."),this._name="<unlabeled transaction>");const{scope:e,isolationScope:n}=getCapturedScopesOnSpan(this),r=e?.getScopeData().sdkProcessingMetadata?.normalizedRequest;if(!0!==this._sampled)return;t.onSpanCaptured?.(this);const i=[];for(const e of getSpanDescendants(this)){if(e===this||isStandaloneSpan(e)||t.isSpanAlreadyCaptured?.(e))continue;const n=spanToJSON(e);isFullFinishedSpan(n)&&(t.onSpanCaptured?.(e),i.push(n))}const s=this._attributes[SEMANTIC_ATTRIBUTE_SENTRY_SOURCE];delete this._attributes[SEMANTIC_ATTRIBUTE_SENTRY_CUSTOM_SPAN_NAME];let a=!1;i.forEach(t=>{delete t.data[SEMANTIC_ATTRIBUTE_SENTRY_CUSTOM_SPAN_NAME],t.op?.startsWith("gen_ai.")&&(a=!0)});const o={contexts:{trace:spanToTransactionTraceContext(this)},spans:i.length>MAX_SPAN_COUNT?i.sort((t,e)=>t.start_timestamp-e.start_timestamp).slice(0,MAX_SPAN_COUNT):i,start_timestamp:this._startTime,timestamp:this._endTime,transaction:this._name,type:"transaction",sdkProcessingMetadata:{capturedSpanScope:e,capturedSpanIsolationScope:n,dynamicSamplingContext:getDynamicSamplingContextFromSpan(this),hasGenAiSpans:a},request:r,...s&&{transaction_info:{source:s}}},l=timedEventsToMeasurements(this._events);return l&&Object.keys(l).length&&(DEBUG_BUILD$2&&debug.log("[Measurements] Adding measurements to transaction event",JSON.stringify(l,void 0,2)),o.measurements=l),o}}function isSpanTimeInput(t){return t&&"number"==typeof t||t instanceof Date||Array.isArray(t)}function isFullFinishedSpan(t){return!!(t.start_timestamp&&t.timestamp&&t.span_id&&t.trace_id)}function isStandaloneSpan(t){return t instanceof SentrySpan&&t.isStandaloneSpan()}function sendSpanEnvelope(t){const e=getClient();if(!e)return;const n=t[1];n&&0!==n.length?e.sendEnvelope(t):e.recordDroppedEvent("before_send","span")}function handleCallbackErrors(t,e,n=()=>{},r=()=>{}){let i;try{i=t()}catch(t){throw e(t),n(),t}return maybeHandlePromiseRejection(i,e,n,r)}function maybeHandlePromiseRejection(t,e,n,r){return isThenable(t)?chainAndCopyPromiseLike(t,t=>{n(),r(t)},t=>{e(t),n()}):(n(),r(t),t)}function sampleSpan(t,e,n){if(!hasSpansEnabled(t))return[!1];let r,i;"function"==typeof t.tracesSampler?(i=t.tracesSampler({...e,inheritOrSampleWith:t=>"number"==typeof e.parentSampleRate?e.parentSampleRate:"boolean"==typeof e.parentSampled?Number(e.parentSampled):t}),r=!0):void 0!==e.parentSampled?i=e.parentSampled:void 0!==t.tracesSampleRate&&(i=t.tracesSampleRate,r=!0);const s=parseSampleRate(i);if(void 0===s)return DEBUG_BUILD$2&&debug.warn(`[Tracing] Discarding root span because of invalid sample rate. Sample rate must be a boolean or a number between 0 and 1. Got ${JSON.stringify(i)} of type ${JSON.stringify(typeof i)}.`),[!1];if(!s)return DEBUG_BUILD$2&&debug.log("[Tracing] Discarding transaction because "+("function"==typeof t.tracesSampler?"tracesSampler returned 0 or false":"a negative sampling decision was inherited or tracesSampleRate is set to 0")),[!1,s,r];const a=n<s;return a||DEBUG_BUILD$2&&debug.log(`[Tracing] Discarding transaction because it's not included in the random sample (sampling rate = ${Number(i)})`),[a,s,r]}const SUPPRESS_TRACING_KEY="__SENTRY_SUPPRESS_TRACING__";function startSpan(t,e){const n=getAcs();if(n.startSpan)return n.startSpan(t,e);const r=parseSentrySpanArguments(t),{forceTransaction:i,parentSpan:s,scope:a}=t,o=a?.clone();return withScope(o,()=>getActiveSpanWrapper(s)(()=>{const n=getCurrentScope(),a=getParentSpan(n,s),o=getClient(),l=t.onlyIfParent&&!a?startMissingRequiredParentSpan(n,o):createChildOrRootSpan({parentSpan:a,spanArguments:r,forceTransaction:i,scope:n});return spanIsIgnored(l)&&a||_setSpanForScope(n,l),handleCallbackErrors(()=>e(l),()=>{const{status:t}=spanToJSON(l);!l.isRecording()||t&&"ok"!==t||l.setStatus({code:SPAN_STATUS_ERROR,message:"internal_error"})},()=>{l.end()})}))}function startInactiveSpan(t){const e=getAcs();return e.startInactiveSpan?e.startInactiveSpan(t):_startInactiveSpanImpl(t)}function _startInactiveSpanImpl(t){const e=parseSentrySpanArguments(t),{forceTransaction:n,parentSpan:r}=t;return(t.scope?e=>withScope(t.scope,e):void 0!==r?t=>withActiveSpan(r,t):t=>t())(()=>{const i=getCurrentScope(),s=getParentSpan(i,r),a=getClient();return t.onlyIfParent&&!s?startMissingRequiredParentSpan(i,a):createChildOrRootSpan({parentSpan:s,spanArguments:e,forceTransaction:n,scope:i})})}function withActiveSpan(t,e){const n=getAcs();return n.withActiveSpan?n.withActiveSpan(t,e):withScope(n=>(_setSpanForScope(n,t||void 0),e(n)))}function isTracingSuppressed(t=getCurrentScope()){const e=getAcs();return e.isTracingSuppressed?e.isTracingSuppressed(t):!0===t.getScopeData().sdkProcessingMetadata[SUPPRESS_TRACING_KEY]}function startMissingRequiredParentSpan(t,e){e?.recordDroppedEvent("no_parent_span","span");const n=new SentryNonRecordingSpan({traceId:t.getPropagationContext().traceId});return setCapturedScopesOnSpan(n,t,getIsolationScope()),n}function createChildOrRootSpan({parentSpan:t,spanArguments:e,forceTransaction:n,scope:r}){const i=getIsolationScope();if(!hasSpansEnabled()){const e={...i.getPropagationContext(),...r.getPropagationContext()},s=t?t.spanContext().traceId:e.traceId,a=new SentryNonRecordingSpan({traceId:s});return t&&!n&&addChildSpanToSpan(t,a),setCapturedScopesOnSpan(a,r,i),a}const s=getClient();if(_shouldIgnoreStreamedSpan(s,e)){isTracingSuppressed(r)||s?.recordDroppedEvent("ignored","span");const e=new SentryNonRecordingSpan({dropReason:"ignored",traceId:t?.spanContext().traceId??r.getPropagationContext().traceId});return t&&!n&&addChildSpanToSpan(t,e),setCapturedScopesOnSpan(e,r,i),e}let a;if(t&&!n)a=_startChildSpan(t,r,e,i),addChildSpanToSpan(t,a);else if(t){const n=getDynamicSamplingContextFromSpan(t),{traceId:s,spanId:o}=t.spanContext(),l=spanIsSampled(t);a=_startRootSpan({traceId:s,parentSpanId:o,...e},r,i,l),freezeDscOnSpan(a,n)}else{const{traceId:t,dsc:n,parentSpanId:s,sampled:o}={...i.getPropagationContext(),...r.getPropagationContext()};a=_startRootSpan({traceId:t,parentSpanId:s,...e},r,i,o),n&&freezeDscOnSpan(a,n)}return logSpanStart(a),a}function parseSentrySpanArguments(t){const e={isStandalone:(t.experimental||{}).standalone,...t};if(t.startTime){const n={...e};return n.startTimestamp=spanTimeInputToSeconds(t.startTime),delete n.startTime,n}return e}function getAcs(){return getAsyncContextStrategy(getMainCarrier())}function _startRootSpan(t,e,n,r){const i=getClient(),s=i?.getOptions()||{},{name:a=""}=t,o={spanAttributes:{...t.attributes},spanName:a,parentSampled:r};i?.emit("beforeSampling",o,{decision:!1});const l=o.parentSampled??r,c=o.spanAttributes,d=e.getPropagationContext(),h=isTracingSuppressed(e),[u,p,f]=h?[!1]:sampleSpan(s,{name:a,parentSampled:l,attributes:c,normalizedRequest:n.getScopeData().sdkProcessingMetadata.normalizedRequest,parentSampleRate:parseSampleRate(d.dsc?.sample_rate)},d.sampleRand),m=new SentrySpan({...t,attributes:{[SEMANTIC_ATTRIBUTE_SENTRY_SOURCE]:"custom",[SEMANTIC_ATTRIBUTE_SENTRY_SAMPLE_RATE]:void 0!==p&&f?p:void 0,...c},sampled:u});return u||!i||h||(DEBUG_BUILD$2&&debug.log("[Tracing] Discarding root span because its trace was not chosen to be sampled."),i.recordDroppedEvent("sample_rate",hasSpanStreamingEnabled(i)?"span":"transaction")),setCapturedScopesOnSpan(m,e,n),i&&i.emit("spanStart",m),m}function _startChildSpan(t,e,n,r){const{spanId:i,traceId:s}=t.spanContext(),a=isTracingSuppressed(e),o=!a&&spanIsSampled(t),l=o?new SentrySpan({...n,parentSpanId:i,traceId:s,sampled:o}):new SentryNonRecordingSpan({traceId:s});addChildSpanToSpan(t,l),setCapturedScopesOnSpan(l,e,r);const c=getClient();return c?(hasSpanStreamingEnabled(c)&&spanIsNonRecordingSpan(l)&&(spanIsNonRecordingSpan(t)&&t.dropReason?(l.dropReason=t.dropReason,c.recordDroppedEvent(t.dropReason,"span")):a||(l.dropReason="sample_rate",c.recordDroppedEvent("sample_rate","span"))),c.emit("spanStart",l),n.endTimestamp&&(c.emit("spanEnd",l),c.emit("afterSpanEnd",l)),l):l}function getParentSpan(t,e){if(e)return e;if(null===e)return;const n=_getSpanForScope(t);if(!n)return;const r=getClient();return(r?r.getOptions():{}).parentSpanIsAlwaysRootSpan?getRootSpan(n):n}function getActiveSpanWrapper(t){return void 0!==t?e=>withActiveSpan(t,e):t=>t()}function _shouldIgnoreStreamedSpan(t,e){const n=t?.getOptions().ignoreSpans;return!!(t&&hasSpanStreamingEnabled(t)&&n?.length)&&shouldIgnoreSpan({description:e.name||"",op:e.attributes?.[SEMANTIC_ATTRIBUTE_SENTRY_OP]||e.op,attributes:e.attributes},n)}function spanIsIgnored(t){return spanIsNonRecordingSpan(t)&&"ignored"===t.dropReason}const TRACING_DEFAULTS={idleTimeout:1e3,finalTimeout:3e4,childSpanTimeout:15e3},FINISH_REASON_HEARTBEAT_FAILED="heartbeatFailed",FINISH_REASON_IDLE_TIMEOUT="idleTimeout",FINISH_REASON_FINAL_TIMEOUT="finalTimeout",FINISH_REASON_EXTERNAL_FINISH="externalFinish";function startIdleSpan(t,e={}){const n=/* @__PURE__ */new Map;let r,i=!1,s=FINISH_REASON_EXTERNAL_FINISH,a=!e.disableAutoFinish;const o=[],{idleTimeout:l=TRACING_DEFAULTS.idleTimeout,finalTimeout:c=TRACING_DEFAULTS.finalTimeout,childSpanTimeout:d=TRACING_DEFAULTS.childSpanTimeout,beforeSpanEnd:h,trimIdleSpanEndTimestamp:u=!0}=e,p=getClient(),f=getCurrentScope();if(!p||!hasSpansEnabled()){const t=new SentryNonRecordingSpan({traceId:f.getPropagationContext().traceId});return setCapturedScopesOnSpan(t,f,getIsolationScope()),t}const m=getActiveSpan(),_=_startIdleSpan(t);function g(){r&&(clearTimeout(r),r=void 0)}function y(t){g(),r=setTimeout(()=>{!i&&0===n.size&&a&&(s=FINISH_REASON_IDLE_TIMEOUT,_.end(t))},l)}function S(t){r=setTimeout(()=>{!i&&a&&(s=FINISH_REASON_HEARTBEAT_FAILED,_.end(t))},d)}function A(t){i=!0,n.clear(),o.forEach(t=>t()),_setSpanForScope(f,m);const e=spanToJSON(_),{start_timestamp:r}=e;if(!r)return;e.data[SEMANTIC_ATTRIBUTE_SENTRY_IDLE_SPAN_FINISH_REASON]||_.setAttribute(SEMANTIC_ATTRIBUTE_SENTRY_IDLE_SPAN_FINISH_REASON,s);const a=e.status;a&&"unknown"!==a||_.setStatus({code:SPAN_STATUS_OK}),debug.log(`[Tracing] Idle span "${e.op}" finished`);const d=getSpanDescendants(_).filter(t=>t!==_);let h=0;d.forEach(e=>{e.isRecording()&&(e.setStatus({code:SPAN_STATUS_ERROR,message:"cancelled"}),e.end(t),DEBUG_BUILD$2&&debug.log("[Tracing] Cancelling span since span ended early",JSON.stringify(e,void 0,2)));const n=spanToJSON(e),{timestamp:r=0,start_timestamp:i=0}=n,s=i<=t,a=r-i<=(c+l)/1e3;if(DEBUG_BUILD$2){const t=JSON.stringify(e,void 0,2);s?a||debug.log("[Tracing] Discarding span since it finished after idle span final timeout",t):debug.log("[Tracing] Discarding span since it happened after idle span was finished",t)}a&&s||(removeChildSpanFromSpan(_,e),h++)}),h>0&&_.setAttribute("sentry.idle_span_discarded_spans",h)}return _.end=new Proxy(_.end,{apply(t,e,n){if(h&&h(_),spanIsNonRecordingSpan(e))return;const[r,...i]=n,s=spanTimeInputToSeconds(r||timestampInSeconds()),a=getSpanDescendants(_).filter(t=>t!==_),o=spanToJSON(_);if(!a.length||!u)return A(s),Reflect.apply(t,e,[s,...i]);const l=p.getOptions().ignoreSpans,d=a?.reduce((t,e)=>{const n=spanToJSON(e);return n.timestamp?l&&shouldIgnoreSpan({description:n.description,op:n.op,attributes:n.data},l)?t:t?Math.max(t,n.timestamp):n.timestamp:t},void 0),f=o.start_timestamp,m=Math.min(f?f+c/1e3:Infinity,Math.max(f||-Infinity,Math.min(s,d||Infinity)));return A(m),Reflect.apply(t,e,[m,...i])}}),o.push(p.on("spanStart",t=>{var e;i||t===_||spanToJSON(t).timestamp||t instanceof SentrySpan&&t.isStandaloneSpan()||getSpanDescendants(_).includes(t)&&(e=t.spanContext().spanId,g(),n.set(e,!0),S(timestampInSeconds()+d/1e3))})),o.push(p.on("spanEnd",t=>{var e;i||(e=t.spanContext().spanId,n.has(e)&&n.delete(e),0===n.size&&y(timestampInSeconds()+l/1e3))})),o.push(p.on("idleSpanEnableAutoFinish",t=>{t===_&&(a=!0,y(),n.size&&S())})),e.disableAutoFinish||y(),setTimeout(()=>{i||(_.setStatus({code:SPAN_STATUS_ERROR,message:"deadline_exceeded"}),s=FINISH_REASON_FINAL_TIMEOUT,_.end())},c),_}function _startIdleSpan(t){const e=startInactiveSpan(t);return _setSpanForScope(getCurrentScope(),e),DEBUG_BUILD$2&&debug.log("[Tracing] Started span is an idle span"),e}function applyScopeDataToEvent(t,e){const{fingerprint:n,span:r,breadcrumbs:i,sdkProcessingMetadata:s}=e;applyDataToEvent(t,e),r&&applySpanToEvent(t,r),applyFingerprintToEvent(t,n),applyBreadcrumbsToEvent(t,i),applySdkMetadataToEvent(t,s)}function mergeScopeData(t,e){const{extra:n,tags:r,attributes:i,user:s,contexts:a,level:o,sdkProcessingMetadata:l,breadcrumbs:c,fingerprint:d,eventProcessors:h,attachments:u,propagationContext:p,transactionName:f,span:m}=e;mergeAndOverwriteScopeData(t,"extra",n),mergeAndOverwriteScopeData(t,"tags",r),mergeAndOverwriteScopeData(t,"attributes",i),mergeAndOverwriteScopeData(t,"user",s),mergeAndOverwriteScopeData(t,"contexts",a),t.sdkProcessingMetadata=merge(t.sdkProcessingMetadata,l,2),o&&(t.level=o),f&&(t.transactionName=f),m&&(t.span=m),c.length&&(t.breadcrumbs=[...t.breadcrumbs,...c]),d.length&&(t.fingerprint=[...t.fingerprint,...d]),h.length&&(t.eventProcessors=[...t.eventProcessors,...h]),u.length&&(t.attachments=[...t.attachments,...u]),t.propagationContext={...t.propagationContext,...p}}function mergeAndOverwriteScopeData(t,e,n){t[e]=merge(t[e],n,1)}function getCombinedScopeData(t,e){const n=getGlobalScope().getScopeData();return t&&mergeScopeData(n,t.getScopeData()),e&&mergeScopeData(n,e.getScopeData()),n}function applyDataToEvent(t,e){const{extra:n,tags:r,user:i,contexts:s,level:a,transactionName:o}=e;Object.keys(n).length&&(t.extra={...n,...t.extra}),Object.keys(r).length&&(t.tags={...r,...t.tags}),Object.keys(i).length&&(t.user={...i,...t.user}),Object.keys(s).length&&(t.contexts={...s,...t.contexts}),a&&(t.level=a),o&&"transaction"!==t.type&&(t.transaction=o)}function applyBreadcrumbsToEvent(t,e){const n=[...t.breadcrumbs||[],...e];t.breadcrumbs=n.length?n:void 0}function applySdkMetadataToEvent(t,e){t.sdkProcessingMetadata={...t.sdkProcessingMetadata,...e}}function applySpanToEvent(t,e){t.contexts={trace:spanToTraceContext(e),...t.contexts},t.sdkProcessingMetadata={dynamicSamplingContext:getDynamicSamplingContextFromSpan(e),...t.sdkProcessingMetadata};const n=spanToJSON(getRootSpan(e)).description;n&&!t.transaction&&"transaction"===t.type&&(t.transaction=n)}function applyFingerprintToEvent(t,e){t.fingerprint=t.fingerprint?Array.isArray(t.fingerprint)?t.fingerprint:[t.fingerprint]:[],e&&(t.fingerprint=t.fingerprint.concat(e)),t.fingerprint.length||delete t.fingerprint}const ws="http.url",Lc="sentry.segment.name",Xc="sentry.transaction",Yu="url.full",Vu="url.path";function safeSetSpanJSONAttributes(t,e){const n=t.attributes??(t.attributes={});Object.entries(e).forEach(([t,e])=>{null==e||t in n||(n[t]=e)})}const STATE_PENDING=0,STATE_RESOLVED=1,STATE_REJECTED=2;function resolvedSyncPromise(t){return new SyncPromise(e=>{e(t)})}function rejectedSyncPromise(t){return new SyncPromise((e,n)=>{n(t)})}class SyncPromise{constructor(t){this._state=STATE_PENDING,this._handlers=[],this._runExecutor(t)}then(t,e){return new SyncPromise((n,r)=>{this._handlers.push([!1,e=>{if(t)try{n(t(e))}catch(t){r(t)}else n(e)},t=>{if(e)try{n(e(t))}catch(t){r(t)}else r(t)}]),this._executeHandlers()})}catch(t){return this.then(t=>t,t)}finally(t){return new SyncPromise((e,n)=>{let r,i;return this.then(e=>{i=!1,r=e,t&&t()},e=>{i=!0,r=e,t&&t()}).then(()=>{i?n(r):e(r)})})}_executeHandlers(){if(this._state===STATE_PENDING)return;const t=this._handlers.slice();this._handlers=[],t.forEach(t=>{t[0]||(this._state===STATE_RESOLVED&&t[1](this._value),this._state===STATE_REJECTED&&t[2](this._value),t[0]=!0)})}_runExecutor(t){const e=(t,e)=>{this._state===STATE_PENDING&&(isThenable(e)?e.then(n,r):(this._state=t,this._value=e,this._executeHandlers()))},n=t=>{e(STATE_RESOLVED,t)},r=t=>{e(STATE_REJECTED,t)};try{t(n,r)}catch(t){r(t)}}}function notifyEventProcessors(t,e,n,r=0){try{const i=_notifyEventProcessors(e,n,t,r);return isThenable(i)?i:resolvedSyncPromise(i)}catch(t){return rejectedSyncPromise(t)}}function _notifyEventProcessors(t,e,n,r){const i=n[r];if(!t||!i)return t;const s=i({...t},e);return DEBUG_BUILD$2&&null===s&&debug.log(`Event processor "${i.id||"?"}" dropped event`),isThenable(s)?s.then(t=>_notifyEventProcessors(t,e,n,r+1)):_notifyEventProcessors(s,e,n,r+1)}let parsedStackResults,lastSentryKeysCount,lastNativeKeysCount,cachedFilenameDebugIds;function getFilenameToDebugIdMap(t){const e=GLOBAL_OBJ._sentryDebugIds,n=GLOBAL_OBJ._debugIds;if(!e&&!n)return{};const r=e?Object.keys(e):[],i=n?Object.keys(n):[];if(cachedFilenameDebugIds&&r.length===lastSentryKeysCount&&i.length===lastNativeKeysCount)return cachedFilenameDebugIds;lastSentryKeysCount=r.length,lastNativeKeysCount=i.length,cachedFilenameDebugIds={},parsedStackResults||(parsedStackResults={});const s=(e,n)=>{for(const r of e){const e=n[r],i=parsedStackResults?.[r];if(i&&cachedFilenameDebugIds&&e)cachedFilenameDebugIds[i[0]]=e,parsedStackResults&&(parsedStackResults[r]=[i[0],e]);else if(e){const n=t(r);for(let t=n.length-1;t>=0;t--){const i=n[t],s=i?.filename;if(s&&cachedFilenameDebugIds&&parsedStackResults){cachedFilenameDebugIds[s]=e,parsedStackResults[r]=[s,e];break}}}}};return e&&s(r,e),n&&s(i,n),cachedFilenameDebugIds}function prepareEvent(t,e,n,r,i,s){const{normalizeDepth:a=3,normalizeMaxBreadth:o=1e3}=t,l={...e,event_id:e.event_id||n.event_id||uuid4(),timestamp:e.timestamp||dateTimestampInSeconds()},c=n.integrations||t.integrations.map(t=>t.name);applyClientOptions(l,t),applyIntegrationsMetadata(l,c),i&&i.emit("applyFrameMetadata",e),void 0===e.type&&applyDebugIds(l,t.stackParser);const d=getFinalScope(r,n.captureContext);n.mechanism&&addExceptionMechanism(l,n.mechanism);const h=i?i.getEventProcessors():[],u=getCombinedScopeData(s,d),p=[...n.attachments||[],...u.attachments];p.length&&(n.attachments=p),applyScopeDataToEvent(l,u);const f=[...h,...u.eventProcessors];return(n.data&&!0===n.data.__sentry__?resolvedSyncPromise(l):notifyEventProcessors(f,l,n)).then(t=>(t&&applyDebugMeta(t),"number"==typeof a&&a>0?normalizeEvent(t,a,o):t))}function applyClientOptions(t,e){const{environment:n,release:r,dist:i,maxValueLength:s}=e;t.environment=t.environment||n||DEFAULT_ENVIRONMENT,!t.release&&r&&(t.release=r),!t.dist&&i&&(t.dist=i);const a=t.request;a?.url&&s&&(a.url=truncate(a.url,s)),s&&t.exception?.values?.forEach(t=>{t.value&&(t.value=truncate(t.value,s))})}function applyDebugIds(t,e){const n=getFilenameToDebugIdMap(e);t.exception?.values?.forEach(t=>{t.stacktrace?.frames?.forEach(t=>{t.filename&&(t.debug_id=n[t.filename])})})}function applyDebugMeta(t){const e={};if(t.exception?.values?.forEach(t=>{t.stacktrace?.frames?.forEach(t=>{t.debug_id&&(t.abs_path?e[t.abs_path]=t.debug_id:t.filename&&(e[t.filename]=t.debug_id),delete t.debug_id)})}),0===Object.keys(e).length)return;t.debug_meta=t.debug_meta||{},t.debug_meta.images=t.debug_meta.images||[];const n=t.debug_meta.images;Object.entries(e).forEach(([t,e])=>{n.push({type:"sourcemap",code_file:t,debug_id:e})})}function applyIntegrationsMetadata(t,e){e.length>0&&(t.sdk=t.sdk||{},t.sdk.integrations=[...t.sdk.integrations||[],...e])}function normalizeEvent(t,e,n){if(!t)return null;const r={...t,...t.breadcrumbs&&{breadcrumbs:t.breadcrumbs.map(t=>({...t,...t.data&&{data:normalize(t.data,e,n)}}))},...t.user&&{user:normalize(t.user,e,n)},...t.contexts&&{contexts:normalize(t.contexts,e,n)},...t.extra&&{extra:normalize(t.extra,e,n)}};return t.contexts?.trace&&r.contexts&&(r.contexts.trace=t.contexts.trace,t.contexts.trace.data&&(r.contexts.trace.data=normalize(t.contexts.trace.data,e,n))),t.spans&&(r.spans=t.spans.map(t=>({...t,...t.data&&{data:normalize(t.data,e,n)}}))),t.contexts?.flags&&r.contexts&&(r.contexts.flags=normalize(t.contexts.flags,3,n)),r}function getFinalScope(t,e){if(!e)return t;const n=t?t.clone():new Scope;return n.update(e),n}function parseEventHintOrCaptureContext(t){if(t)return hintIsScopeOrFunction(t)||hintIsScopeContext(t)?{captureContext:t}:t}function hintIsScopeOrFunction(t){return t instanceof Scope||"function"==typeof t}const captureContextKeys=["user","level","extra","contexts","tags","fingerprint","propagationContext"];function hintIsScopeContext(t){return Object.keys(t).some(t=>captureContextKeys.includes(t))}function captureException(t,e){return getCurrentScope().captureException(t,parseEventHintOrCaptureContext(e))}function captureEvent(t,e){return getCurrentScope().captureEvent(t,e)}function isEnabled(){const t=getClient();return!1!==t?.getOptions().enabled&&!!t?.getTransport()}function startSession(t){const e=getIsolationScope(),{user:n}=getCombinedScopeData(e,getCurrentScope()),{userAgent:r}=GLOBAL_OBJ.navigator||{},i=makeSession({user:n,...r&&{userAgent:r},...t}),s=e.getSession();return"ok"===s?.status&&updateSession(s,{status:"exited"}),endSession(),e.setSession(i),i}function endSession(){const t=getIsolationScope(),e=getCurrentScope().getSession()||t.getSession();e&&closeSession(e),_sendSessionUpdate(),t.setSession()}function _sendSessionUpdate(){const t=getIsolationScope(),e=getClient(),n=t.getSession();n&&e&&e.captureSession(n)}function captureSession(t=!1){t?endSession():_sendSessionUpdate()}function safeUnref(t){return"object"==typeof t&&"function"==typeof t.unref&&t.unref(),t}const SENTRY_API_VERSION="7";function getBaseApiEndpoint(t){return`${t.protocol?`${t.protocol}:`:""}//${t.host}${t.port?`:${t.port}`:""}${t.path?`/${t.path}`:""}/api/`}function _getIngestEndpoint(t){return`${getBaseApiEndpoint(t)}${t.projectId}/envelope/`}function _encodedAuth(t,e){const n={sentry_version:SENTRY_API_VERSION};return t.publicKey&&(n.sentry_key=t.publicKey),e&&(n.sentry_client=`${e.name}/${e.version}`),new URLSearchParams(n).toString()}function getEnvelopeEndpointWithUrlEncodedAuth(t,e,n){return e||`${_getIngestEndpoint(t)}?${_encodedAuth(t,n)}`}const installedIntegrations=[];function setupIntegrations(t,e){const n={};return e.forEach(e=>{e?.beforeSetup&&e.beforeSetup(t)}),e.forEach(e=>{e&&setupIntegration(t,e,n)}),n}function afterSetupIntegrations(t,e){for(const n of e)n?.afterAllSetup&&n.afterAllSetup(t)}function setupIntegration(t,e,n){if(n[e.name])DEBUG_BUILD$2&&debug.log(`Integration skipped because it was already installed: ${e.name}`);else{if(n[e.name]=e,installedIntegrations.includes(e.name)||"function"!=typeof e.setupOnce||(e.setupOnce(),installedIntegrations.push(e.name)),e.setup&&"function"==typeof e.setup&&e.setup(t),"function"==typeof e.preprocessEvent){const n=e.preprocessEvent.bind(e);t.on("preprocessEvent",(e,r)=>n(e,r,t))}if("function"==typeof e.processEvent){const n=e.processEvent.bind(e),r=Object.assign((e,r)=>n(e,r,t),{id:e.name});t.addEventProcessor(r)}["processSpan","processSegmentSpan"].forEach(n=>{const r=e[n];"function"==typeof r&&t.on(n,n=>r.call(e,n,t))}),DEBUG_BUILD$2&&debug.log(`Integration installed: ${e.name}`)}}function defineIntegration(t){return t}function isBrowserBundle(){return"undefined"!=typeof __SENTRY_BROWSER_BUNDLE__&&!!__SENTRY_BROWSER_BUNDLE__}function getSDKSource(){return"npm"}function isNodeEnv(){return!isBrowserBundle()&&"[object process]"===Object.prototype.toString.call("undefined"!=typeof process?process:0)}function isBrowser(){return"undefined"!=typeof window&&(!isNodeEnv()||isElectronNodeRenderer())}function isElectronNodeRenderer(){const t=GLOBAL_OBJ.process;return"renderer"===t?.type}function createLogContainerEnvelopeItem(t,e){const n=e?"auto":"never";return[{type:"log",item_count:t.length,content_type:"application/vnd.sentry.items.log+json"},{version:2,...isBrowser()&&{ingest_settings:{infer_ip:n,infer_user_agent:n}},items:t}]}function createLogEnvelope(t,e,n,r,i){const s={};return e?.sdk&&(s.sdk={name:e.sdk.name,version:e.sdk.version}),n&&r&&(s.dsn=dsnToString(r)),createEnvelope(s,[createLogContainerEnvelopeItem(t,i)])}function _INTERNAL_flushLogsBuffer(t,e){const n=e??_INTERNAL_getLogBuffer(t)??[];if(0===n.length)return;const r=t.getOptions(),i=createLogEnvelope(n,r._metadata,r.tunnel,t.getDsn(),t.getDataCollectionOptions().userInfo);_getBufferMap$1().set(t,[]),t.emit("flushLogs"),t.sendEnvelope(i)}function _INTERNAL_getLogBuffer(t){return _getBufferMap$1().get(t)}function _getBufferMap$1(){return getGlobalSingleton("clientToLogBufferMap",()=>/* @__PURE__ */new WeakMap)}function createMetricContainerEnvelopeItem(t,e){const n=e?"auto":"never";return[{type:"trace_metric",item_count:t.length,content_type:"application/vnd.sentry.items.trace-metric+json"},{version:2,...isBrowser()&&{ingest_settings:{infer_ip:n,infer_user_agent:n}},items:t}]}function createMetricEnvelope(t,e,n,r,i){const s={};return e?.sdk&&(s.sdk={name:e.sdk.name,version:e.sdk.version}),n&&r&&(s.dsn=dsnToString(r)),createEnvelope(s,[createMetricContainerEnvelopeItem(t,i)])}function _INTERNAL_flushMetricsBuffer(t,e){const n=e??_INTERNAL_getMetricBuffer(t)??[];if(0===n.length)return;const r=t.getOptions(),i=createMetricEnvelope(n,r._metadata,r.tunnel,t.getDsn(),t.getDataCollectionOptions().userInfo);_getBufferMap().set(t,[]),t.emit("flushMetrics"),t.sendEnvelope(i)}function _INTERNAL_getMetricBuffer(t){return _getBufferMap().get(t)}function _getBufferMap(){return getGlobalSingleton("clientToMetricBufferMap",()=>/* @__PURE__ */new WeakMap)}function spanJsonToSerializedStreamedSpan(t){return streamedSpanJsonToSerializedSpan({trace_id:t.trace_id,span_id:t.span_id,parent_span_id:t.parent_span_id,name:t.description||"",start_timestamp:t.start_timestamp,end_timestamp:t.timestamp||t.start_timestamp,status:t.status&&"ok"!==t.status&&"cancelled"!==t.status?"error":"ok",is_segment:!1,attributes:{...t.data},links:t.links})}function extractGenAiSpansFromEvent(t,e){if("transaction"!==t.type||!t.spans?.length||!t.sdkProcessingMetadata?.hasGenAiSpans||!1===e.getOptions().streamGenAiSpans||hasSpanStreamingEnabled(e))return;const n=[],r=[];for(const e of t.spans)e.op?.startsWith("gen_ai.")?n.push(spanJsonToSerializedStreamedSpan(e)):r.push(e);if(0===n.length)return;t.spans=r;const i=e.getDataCollectionOptions().userInfo?"auto":"never";return[{type:"span",item_count:n.length,content_type:"application/vnd.sentry.items.span.v2+json"},{version:2,...isBrowser()&&{ingest_settings:{infer_ip:i,infer_user_agent:i}},items:n}]}const SENTRY_BUFFER_FULL_ERROR=/* @__PURE__ */Symbol.for("SentryBufferFullError");function makePromiseBuffer(t=100){const e=/* @__PURE__ */new Set;function n(t){e.delete(t)}return{get $(){return Array.from(e)},add:function(r){if(!(e.size<t))return rejectedSyncPromise(SENTRY_BUFFER_FULL_ERROR);const i=r();return e.add(i),i.then(()=>n(i),()=>n(i)),i},drain:function(t){if(!e.size)return resolvedSyncPromise(!0);const n=Promise.allSettled(Array.from(e)).then(()=>!0);if(!t)return n;const r=[n,new Promise(e=>safeUnref(setTimeout(()=>e(!1),t)))];return Promise.race(r)}}}const DEFAULT_RETRY_AFTER=6e4;function parseRetryAfterHeader(t,e=safeDateNow()){const n=parseInt(`${t}`,10);if(!isNaN(n))return 1e3*n;const r=Date.parse(`${t}`);return isNaN(r)?DEFAULT_RETRY_AFTER:r-e}function disabledUntil(t,e){return t[e]||t.all||0}function isRateLimited(t,e,n=safeDateNow()){return disabledUntil(t,e)>n}function updateRateLimits(t,{statusCode:e,headers:n},r=safeDateNow()){const i={...t},s=n?.["x-sentry-rate-limits"],a=n?.["retry-after"];if(s)for(const t of s.trim().split(",")){const[e,n,,,s]=t.split(":",5),a=parseInt(e,10),o=1e3*(isNaN(a)?60:a);if(n)for(const t of n.split(";"))"metric_bucket"===t&&s&&!s.split(";").includes("custom")||(i[t]=r+o);else i.all=r+o}else a?i.all=r+parseRetryAfterHeader(a,r):429===e&&(i.all=r+6e4);return i}const DEFAULT_TRANSPORT_BUFFER_SIZE=64;function createTransport(t,e,n=makePromiseBuffer(t.bufferSize||DEFAULT_TRANSPORT_BUFFER_SIZE)){let r={};return{send:function(i){const s=[];if(forEachEnvelopeItem(i,(e,n)=>{const i=envelopeItemTypeToDataCategory(n);isRateLimited(r,i)?t.recordDroppedEvent("ratelimit_backoff",i):s.push(e)}),0===s.length)return Promise.resolve({});const a=createEnvelope(i[0],s),o=e=>{envelopeContainsItemType(a,["client_report"])?DEBUG_BUILD$2&&debug.warn(`Dropping client report. Will not send outcomes (reason: ${e}).`):forEachEnvelopeItem(a,(n,r)=>{t.recordDroppedEvent(e,envelopeItemTypeToDataCategory(r))})};return n.add(()=>e({body:serializeEnvelope(a)}).then(t=>413===t.statusCode?(DEBUG_BUILD$2&&debug.error("Sentry responded with status code 413. Envelope was discarded due to exceeding size limits."),o("send_error"),t):(DEBUG_BUILD$2&&void 0!==t.statusCode&&(t.statusCode<200||t.statusCode>=300)&&debug.warn(`Sentry responded with status code ${t.statusCode} to sent event.`),r=updateRateLimits(r,t),t),t=>{throw o("network_error"),DEBUG_BUILD$2&&debug.error("Encountered error running transport request:",t),t})).then(t=>t,t=>{if(t===SENTRY_BUFFER_FULL_ERROR)return DEBUG_BUILD$2&&debug.error("Skipped sending event because buffer is full."),o("queue_overflow"),Promise.resolve({});throw t})},flush:t=>n.drain(t)}}function createClientReportEnvelope(t,e,n){return createEnvelope(e?{dsn:e}:{},[[{type:"client_report"},{timestamp:n||dateTimestampInSeconds(),discarded_events:t}]])}function getPossibleEventMessages(t){const e=[];t.message&&e.push(t.message);try{const n=t.exception.values[t.exception.values.length-1];n?.value&&(e.push(n.value),n.type&&e.push(`${n.type}: ${n.value}`))}catch{}return e}function convertTransactionEventToSpanJson(t){const{trace_id:e,parent_span_id:n,span_id:r,status:i,origin:s,data:a,op:o}=t.contexts?.trace??{};return{data:a??{},description:t.transaction,op:o,parent_span_id:n,span_id:r??"",start_timestamp:t.start_timestamp??0,status:i,timestamp:t.timestamp,trace_id:e??"",origin:s,profile_id:a?.[SEMANTIC_ATTRIBUTE_PROFILE_ID],exclusive_time:a?.[SEMANTIC_ATTRIBUTE_EXCLUSIVE_TIME],measurements:t.measurements,is_segment:!0}}function convertSpanJsonToTransactionEvent(t){return{type:"transaction",timestamp:t.timestamp,start_timestamp:t.start_timestamp,transaction:t.description,contexts:{trace:{trace_id:t.trace_id,span_id:t.span_id,parent_span_id:t.parent_span_id,op:t.op,status:t.status,origin:t.origin,data:{...t.data,...t.profile_id&&{[SEMANTIC_ATTRIBUTE_PROFILE_ID]:t.profile_id},...t.exclusive_time&&{[SEMANTIC_ATTRIBUTE_EXCLUSIVE_TIME]:t.exclusive_time}}}},measurements:t.measurements}}const PII_HEADER_SNIPPETS=["forwarded","-ip","remote-","via","-user"];function defaultPiiToCollectionOptions(t){return!0===t?{userInfo:!0,cookies:!0,httpHeaders:{request:!0,response:!0},httpBodies:["incomingRequest","outgoingRequest","incomingResponse","outgoingResponse"],urlQueryParams:!0,graphQL:{document:!0,variables:!0},genAI:{inputs:!0,outputs:!0},databaseQueryData:!0,stackFrameVariables:!0,frameContextLines:7}:{userInfo:!1,cookies:{deny:PII_HEADER_SNIPPETS},httpHeaders:{request:{deny:PII_HEADER_SNIPPETS},response:{deny:PII_HEADER_SNIPPETS}},httpBodies:[],urlQueryParams:{deny:PII_HEADER_SNIPPETS},graphQL:{document:!0,variables:!0},genAI:{inputs:!1,outputs:!1},databaseQueryData:!1,stackFrameVariables:!0,frameContextLines:7}}const DEFAULTS={userInfo:!0,cookies:!0,httpHeaders:{request:!0,response:!0},httpBodies:["incomingRequest","outgoingRequest","incomingResponse","outgoingResponse"],urlQueryParams:!0,graphQL:{document:!0,variables:!0},genAI:{inputs:!0,outputs:!0},databaseQueryData:!0,stackFrameVariables:!0,frameContextLines:5};function resolveDataCollectionOptions(t){const e=null!=t.dataCollection?DEFAULTS:defaultPiiToCollectionOptions(t.sendDefaultPii),n=t.dataCollection??{};return{userInfo:n.userInfo??e.userInfo,cookies:n.cookies??e.cookies,httpHeaders:{request:n.httpHeaders?.request??e.httpHeaders.request,response:n.httpHeaders?.response??e.httpHeaders.response},httpBodies:n.httpBodies??e.httpBodies,urlQueryParams:n.urlQueryParams??n.queryParams??e.urlQueryParams,graphQL:{document:n.graphQL?.document??e.graphQL.document,variables:n.graphQL?.variables??e.graphQL.variables},genAI:{inputs:n.genAI?.inputs??e.genAI.inputs,outputs:n.genAI?.outputs??e.genAI.outputs},databaseQueryData:n.databaseQueryData??e.databaseQueryData,stackFrameVariables:n.stackFrameVariables??e.stackFrameVariables,frameContextLines:n.frameContextLines??e.frameContextLines}}const ALREADY_SEEN_ERROR="Not capturing exception because it's already been captured.",MISSING_RELEASE_FOR_SESSION_ERROR="Discarded session because of missing or non-string release",INTERNAL_ERROR_SYMBOL=/* @__PURE__ */Symbol.for("SentryInternalError"),DO_NOT_SEND_EVENT_SYMBOL=/* @__PURE__ */Symbol.for("SentryDoNotSendEventError"),DEFAULT_FLUSH_INTERVAL=5e3;function _makeInternalError(t){return{message:t,[INTERNAL_ERROR_SYMBOL]:!0}}function _makeDoNotSendEventError(t){return{message:t,[DO_NOT_SEND_EVENT_SYMBOL]:!0}}function _isInternalError(t){return isObjectLike(t)&&INTERNAL_ERROR_SYMBOL in t}function _isDoNotSendEventError(t){return isObjectLike(t)&&DO_NOT_SEND_EVENT_SYMBOL in t}function setupWeightBasedFlushing(t,e,n,r,i){let s,a=0,o=!1;t.on(n,()=>{a=0,clearTimeout(s),o=!1}),t.on(e,e=>{if(a+=r(e),a>=8e5)i(t);else if(!o){const e=t.getOptions()._flushInterval??DEFAULT_FLUSH_INTERVAL;e>0&&(o=!0,s=safeUnref(setTimeout(()=>{i(t)},e)))}}),t.on("flush",()=>{i(t)})}class Client{constructor(t){if(this._options=t,this._integrations={},this._numProcessing=0,this._outcomes={},this._hooks={},this._eventProcessors=[],this._promiseBuffer=makePromiseBuffer(t.transportOptions?.bufferSize??DEFAULT_TRANSPORT_BUFFER_SIZE),this._dataCollection=resolveDataCollectionOptions(t),t.dsn?this._dsn=makeDsn(t.dsn):DEBUG_BUILD$2&&debug.warn("No DSN provided, client will not send events."),this._dsn){const e=getEnvelopeEndpointWithUrlEncodedAuth(this._dsn,t.tunnel,t._metadata?t._metadata.sdk:void 0);this._transport=t.transport({tunnel:this._options.tunnel,recordDroppedEvent:this.recordDroppedEvent.bind(this),...t.transportOptions,url:e})}this._options.enableLogs=this._options.enableLogs??this._options._experiments?.enableLogs,this._options.enableLogs&&setupWeightBasedFlushing(this,"afterCaptureLog","flushLogs",estimateLogSizeInBytes,_INTERNAL_flushLogsBuffer),(this._options.enableMetrics??this._options._experiments?.enableMetrics??1)&&setupWeightBasedFlushing(this,"afterCaptureMetric","flushMetrics",estimateMetricSizeInBytes,_INTERNAL_flushMetricsBuffer)}captureException(t,e,n){const r=uuid4();if(checkOrSetAlreadyCaught(t))return DEBUG_BUILD$2&&debug.log(ALREADY_SEEN_ERROR),r;const i={event_id:r,...e};return this._process(()=>this.eventFromException(t,i).then(t=>this._captureEvent(t,i,n)).then(t=>t),"error"),i.event_id}captureMessage(t,e,n,r){const i={event_id:uuid4(),...n},s=isParameterizedString(t)?t:String(t),a=isPrimitive(t),o=a?this.eventFromMessage(s,e,i):this.eventFromException(t,i);return this._process(()=>o.then(t=>this._captureEvent(t,i,r)),a?"unknown":"error"),i.event_id}captureEvent(t,e,n){const r=uuid4();if(e?.originalException&&checkOrSetAlreadyCaught(e.originalException))return DEBUG_BUILD$2&&debug.log(ALREADY_SEEN_ERROR),r;const i={event_id:r,...e},s=t.sdkProcessingMetadata||{},a=s.capturedSpanScope,o=s.capturedSpanIsolationScope,l=getDataCategoryByType(t.type);return this._process(()=>this._captureEvent(t,i,a||n,o),l),i.event_id}captureSession(t){this.sendSession(t),updateSession(t,{init:!1})}getDsn(){return this._dsn}getOptions(){return this._options}getDataCollectionOptions(){return this._dataCollection}getSdkMetadata(){return this._options._metadata}getTransport(){return this._transport}async flush(t){const e=this._transport;if(this.emit("flush"),!e)return!0;const n=await this._isClientDoneProcessing(t),r=await e.flush(t);return n&&r}async close(t){const e=await this.flush(t);return this.getOptions().enabled=!1,this.emit("close"),e}getEventProcessors(){return this._eventProcessors}addEventProcessor(t){this._eventProcessors.push(t)}init(){(this._isEnabled()||this._options.integrations.some(({name:t})=>t.startsWith("Spotlight")))&&this._setupIntegrations()}getIntegrationByName(t){return this._integrations[t]}getIntegrationNames(){return Object.keys(this._integrations)}addIntegration(t){const e=this._integrations[t.name];!e&&t.beforeSetup&&t.beforeSetup(this),setupIntegration(this,t,this._integrations),e||afterSetupIntegrations(this,[t])}sendEvent(t,e={}){this.emit("beforeSendEvent",t,e);const n=extractGenAiSpansFromEvent(t,this);let r=createEventEnvelope(t,this._dsn,this._options._metadata,this._options.tunnel);for(const t of e.attachments||[])r=addItemToEnvelope(r,createAttachmentEnvelopeItem(t));n&&(r=addItemToEnvelope(r,n)),this.sendEnvelope(r).then(e=>this.emit("afterSendEvent",t,e))}sendSession(t){const{release:e,environment:n=DEFAULT_ENVIRONMENT}=this._options;if("aggregates"in t){const r=t.attrs||{};if(!r.release&&!e)return void(DEBUG_BUILD$2&&debug.warn(MISSING_RELEASE_FOR_SESSION_ERROR));r.release=r.release||e,r.environment=r.environment||n,t.attrs=r}else{if(!t.release&&!e)return void(DEBUG_BUILD$2&&debug.warn(MISSING_RELEASE_FOR_SESSION_ERROR));t.release=t.release||e,t.environment=t.environment||n}this.emit("beforeSendSession",t);const r=createSessionEnvelope(t,this._dsn,this._options._metadata,this._options.tunnel);this.sendEnvelope(r)}recordDroppedEvent(t,e,n=1){if(this._options.sendClientReports){const r=`${t}:${e}`;DEBUG_BUILD$2&&debug.log(`Recording outcome: "${r}"${n>1?` (${n} times)`:""}`),this._outcomes[r]=(this._outcomes[r]||0)+n}}on(t,e){const n=this._hooks[t]=this._hooks[t]||/* @__PURE__ */new Set,r=(...t)=>e(...t);return n.add(r),()=>{n.delete(r)}}emit(t,...e){const n=this._hooks[t];n&&n.forEach(t=>t(...e))}async sendEnvelope(t){if(this.emit("beforeEnvelope",t),this._isEnabled()&&this._transport)try{return await this._transport.send(t)}catch(t){return DEBUG_BUILD$2&&debug.error("Error while sending envelope:",t),{}}return DEBUG_BUILD$2&&debug.error("Transport disabled"),{}}registerCleanup(t){}dispose(){}_setupIntegrations(){const{integrations:t}=this._options;this._integrations=setupIntegrations(this,t),afterSetupIntegrations(this,t)}_updateSessionFromEvent(t,e){let n="fatal"===e.level,r=!1;const i=e.exception?.values;if(i){r=!0,n=!1;for(const t of i)if(!1===t.mechanism?.handled){n=!0;break}}const s="ok"===t.status;(s&&0===t.errors||s&&n)&&(updateSession(t,{...n&&{status:"crashed"},errors:t.errors||Number(r||n)}),this.captureSession(t))}async _isClientDoneProcessing(t){let e=0;for(;!t||e<t;){if(await new Promise(t=>setTimeout(t,1)),!this._numProcessing)return!0;e++}return!1}_isEnabled(){return!1!==this.getOptions().enabled&&void 0!==this._transport}_prepareEvent(t,e,n,r){const i=this.getOptions(),s=this.getIntegrationNames();return!e.integrations&&s.length&&(e.integrations=s),this.emit("preprocessEvent",t,e),t.type||r.setLastEventId(t.event_id||e.event_id),prepareEvent(i,t,e,n,this,r).then(t=>{if(null===t)return t;this.emit("postprocessEvent",t,e),t.contexts={trace:{...t.contexts?.trace,...getTraceContextFromScope(n)},...t.contexts};const r=getDynamicSamplingContextFromScope(this,n);return t.sdkProcessingMetadata={dynamicSamplingContext:r,...t.sdkProcessingMetadata},t})}_captureEvent(t,e={},n=getCurrentScope(),r=getIsolationScope()){return DEBUG_BUILD$2&&isErrorEvent(t)&&debug.log(`Captured error event \`${getPossibleEventMessages(t)[0]||"<unknown>"}\``),this._processEvent(t,e,n,r).then(t=>t.event_id,t=>{DEBUG_BUILD$2&&(_isDoNotSendEventError(t)?debug.log(t.message):_isInternalError(t)?debug.warn(t.message):debug.warn(t))})}_processEvent(t,e,n,r){const i=this.getOptions(),{sampleRate:s}=i,a=isTransactionEvent(t),o=isErrorEvent(t),l=`before send for type \`${t.type||"error"}\``,c=void 0===s?void 0:parseSampleRate(s);if(o&&"number"==typeof c&&safeMathRandom()>c)return this.recordDroppedEvent("sample_rate","error"),rejectedSyncPromise(_makeDoNotSendEventError(`Discarding event because it's not included in the random sample (sampling rate = ${s})`));const d=getDataCategoryByType(t.type);return this._prepareEvent(t,e,n,r).then(t=>{if(null===t)throw this.recordDroppedEvent("event_processor",d),_makeDoNotSendEventError("An event processor returned `null`, will not send event.");return!0===e.data?.__sentry__?t:_validateBeforeSendResult(processBeforeSend(this,i,t,e),l)}).then(i=>{if(null===i)throw this.recordDroppedEvent("before_send",d),a&&this.recordDroppedEvent("before_send","span",1+(t.spans||[]).length),_makeDoNotSendEventError(`${l} returned \`null\`, will not send event.`);const s=n.getSession()||r.getSession();if(o&&s&&this._updateSessionFromEvent(s,i),a){const t=(i.sdkProcessingMetadata?.spanCountBeforeProcessing||0)-(i.spans?i.spans.length:0);t>0&&this.recordDroppedEvent("before_send","span",t)}const c=i.transaction_info;if(a&&c&&i.transaction!==t.transaction){const t="custom";i.transaction_info={...c,source:t}}return this.sendEvent(i,e),i}).then(null,t=>{if(_isDoNotSendEventError(t)||_isInternalError(t))throw t;throw this.captureException(t,{mechanism:{handled:!1,type:"internal"},data:{__sentry__:!0},originalException:t}),_makeInternalError(`Event processing pipeline threw an error, original event will not be sent. Details have been sent as a new event.\nReason: ${t}`)})}_process(t,e){this._numProcessing++,this._promiseBuffer.add(t).then(t=>(this._numProcessing--,t),t=>(this._numProcessing--,t===SENTRY_BUFFER_FULL_ERROR&&this.recordDroppedEvent("queue_overflow",e),t))}_clearOutcomes(){const t=this._outcomes;return this._outcomes={},Object.entries(t).map(([t,e])=>{const[n,r]=t.split(":");return{reason:n,category:r,quantity:e}})}_flushOutcomes(){DEBUG_BUILD$2&&debug.log("Flushing outcomes...");const t=this._clearOutcomes();if(0===t.length)return void(DEBUG_BUILD$2&&debug.log("No outcomes to send"));if(!this._dsn)return void(DEBUG_BUILD$2&&debug.log("No dsn provided, will not send outcomes"));DEBUG_BUILD$2&&debug.log("Sending outcomes:",t);const e=createClientReportEnvelope(t,this._options.tunnel&&dsnToString(this._dsn));this.sendEnvelope(e)}}function getDataCategoryByType(t){return"replay_event"===t?"replay":t||"error"}function _validateBeforeSendResult(t,e){const n=`${e} must return \`null\` or a valid event.`;if(isThenable(t))return t.then(t=>{if(!isPlainObject(t)&&null!==t)throw _makeInternalError(n);return t},t=>{throw _makeInternalError(`${e} rejected with ${t}`)});if(!isPlainObject(t)&&null!==t)throw _makeInternalError(n);return t}function processBeforeSend(t,e,n,r){const{beforeSend:i,beforeSendTransaction:s,ignoreSpans:a}=e,o=!isStreamedBeforeSendSpanCallback(e.beforeSendSpan)&&e.beforeSendSpan;let l=n;if(isErrorEvent(l)&&i)return i(l,r);if(isTransactionEvent(l)){if(o||a){const e=convertTransactionEventToSpanJson(l);if(a?.length&&shouldIgnoreSpan({description:e.description,op:e.op,attributes:e.data},a))return null;if(o){const t=o(e);t?l=merge(n,convertSpanJsonToTransactionEvent(t)):showSpanDropWarning()}if(l.spans){const e=[],n=l.spans;for(const t of n)if(a?.length&&shouldIgnoreSpan({description:t.description,op:t.op,attributes:t.data},a))reparentChildSpans(n,t);else if(o){const n=o(t);n?e.push(n):(showSpanDropWarning(),e.push(t))}else e.push(t);const r=l.spans.length-e.length;r&&t.recordDroppedEvent("before_send","span",r),l.spans=e}}if(s)return l.spans&&(l.sdkProcessingMetadata={...n.sdkProcessingMetadata,spanCountBeforeProcessing:l.spans.length}),s(l,r)}return l}function isErrorEvent(t){return void 0===t.type}function isTransactionEvent(t){return"transaction"===t.type}function estimateMetricSizeInBytes(t){let e=0;return t.name&&(e+=2*t.name.length),e+=8,e+estimateAttributesSizeInBytes(t.attributes)}function estimateLogSizeInBytes(t){let e=0;return t.message&&(e+=2*t.message.length),e+estimateAttributesSizeInBytes(t.attributes)}function estimateAttributesSizeInBytes(t){if(!t)return 0;let e=0;return Object.values(t).forEach(t=>{Array.isArray(t)?e+=t.length*estimatePrimitiveSizeInBytes(t[0]):isPrimitive(t)?e+=estimatePrimitiveSizeInBytes(t):e+=100}),e}function estimatePrimitiveSizeInBytes(t){return"string"==typeof t?2*t.length:"number"==typeof t?8:"boolean"==typeof t?4:0}const DEFAULT_BASE_URL="thismessage:/";function isURLObjectRelative(t){return"isRelative"in t}function parseStringToURLObject(t,e){const n=t.indexOf("://")<=0&&0!==t.indexOf("//"),r=e??(n?DEFAULT_BASE_URL:void 0);try{if("canParse"in URL&&!URL.canParse(t,r))return;const e=new URL(t,r);return n?{isRelative:n,pathname:e.pathname,search:e.search,hash:e.hash}:e}catch{}}function getSanitizedUrlStringFromUrlObject(t){if(isURLObjectRelative(t))return t.pathname;const e=new URL(t);return e.search="",e.hash="",["80","443"].includes(e.port)&&(e.port=""),e.password&&(e.password="%filtered%"),e.username&&(e.username="%filtered%"),e.toString()}function parseUrl(t){if(!t)return{};const e=t.match(/^(([^:/?#]+):)?(\/\/([^/?#]*))?([^?#]*)(\?([^#]*))?(#(.*))?$/);if(!e)return{};const n=e[6]||"",r=e[8]||"";return{host:e[4],path:e[5],protocol:e[2],search:n,hash:r,relative:e[5]+n+r}}function stripUrlQueryAndFragment(t){return t.split(/[?#]/,1)[0]}function stripDataUrlContent(t,e=!0){if(t.startsWith("data:")){const n=t.match(/^data:([^;,]+)/),r=n?n[1]:"text/plain",i=t.includes(";base64,"),s=t.indexOf(",");let a="";if(e&&-1!==s){const e=t.slice(s+1);a=e.length>10?`${e.slice(0,10)}... [truncated]`:e}return`data:${r}${i?",base64":""}${a?`,${a}`:""}`}return t}function addAutoIpAddressToSession(t){"aggregates"in t?void 0===t.attrs?.ip_address&&(t.attrs={...t.attrs,ip_address:"{{auto}}"}):void 0===t.ipAddress&&(t.ipAddress="{{auto}}")}function applySdkMetadata(t,e,n=[e],r="npm"){const i=(t._metadata=t._metadata||{}).sdk=t._metadata.sdk||{};i.name||(i.name=`sentry.javascript.${e}`,i.packages=n.map(t=>({name:`${r}:@sentry/${t}`,version:SDK_VERSION})),i.version=SDK_VERSION)}function getTraceData(t={}){const e=t.client||getClient();if(!isEnabled()||!e)return{};const n=getAsyncContextStrategy(getMainCarrier());if(n.getTraceData)return n.getTraceData(t);const r=t.scope||getCurrentScope(),i=t.span||getActiveSpan(),s=spanIsNonRecordingSpan(i)&&!hasSpansEnabled(e.getOptions());if(!i&&hasExternalPropagationContext())return{};const a=i&&!s?spanToTraceHeader(i):scopeToTraceHeader(r),o=dynamicSamplingContextToSentryBaggageHeader(i?getDynamicSamplingContextFromSpan(i):getDynamicSamplingContextFromScope(e,r));if(!TRACEPARENT_REGEXP.test(a))return debug.warn("Invalid sentry-trace data. Cannot generate trace data"),{};const l={"sentry-trace":a,baggage:o};return t.propagateTraceparent&&(l.traceparent=i&&!s?spanToTraceparentHeader(i):scopeToTraceparentHeader(r)),l}function scopeToTraceHeader(t){const{traceId:e,sampled:n,propagationSpanId:r}=t.getPropagationContext();return generateSentryTraceHeader(e,r,n)}function scopeToTraceparentHeader(t){const{traceId:e,sampled:n,propagationSpanId:r}=t.getPropagationContext();return generateTraceparentHeader(e,r,n)}const DEFAULT_BREADCRUMBS=100;function addBreadcrumb(t,e){const n=getClient(),r=getIsolationScope();if(!n)return;const{beforeBreadcrumb:i=null,maxBreadcrumbs:s=DEFAULT_BREADCRUMBS}=n.getOptions();if(s<=0)return;const a={timestamp:dateTimestampInSeconds(),...t},o=i?consoleSandbox(()=>i(a,e)):a;null!==o&&(n.emit&&n.emit("beforeAddBreadcrumb",o,e),r.addBreadcrumb(o,s))}const INTEGRATION_NAME$8="FunctionToString",SETUP_CLIENTS=/* @__PURE__ */new WeakMap,_functionToStringIntegration=()=>({name:INTEGRATION_NAME$8,setupOnce(){const t=Function.prototype.toString;try{Function.prototype.toString=function(...e){const n=getOriginalFunction(this);let r;try{SETUP_CLIENTS.has(getClient())&&void 0!==n&&(r=n)}catch{}return t.apply(r??this,e)}}catch{}},setup(t){SETUP_CLIENTS.set(t,!0)}}),functionToStringIntegration=defineIntegration(_functionToStringIntegration),DEFAULT_IGNORE_ERRORS=[/^Script error\.?$/,/^Javascript error: Script error\.? on line 0$/,/^ResizeObserver loop completed with undelivered notifications.$/,/^Cannot redefine property: googletag$/,/^Can't find variable: gmo$/,/^undefined is not an object \(evaluating 'a\.[A-Z]'\)$/,/can't redefine non-configurable property "solana"/,/vv\(\)\.getRestrictions is not a function/,/Can't find variable: _AutofillCallbackHandler/,/Object Not Found Matching Id:\d+, MethodName:simulateEvent/,/^Java exception was raised during method invocation$/],INTEGRATION_NAME$7="EventFilters",eventFiltersIntegration=defineIntegration((t={})=>{let e;return{name:INTEGRATION_NAME$7,setup(n){const r=n.getOptions();e=_mergeOptions(t,r)},processEvent(n,r,i){if(!e){const n=i.getOptions();e=_mergeOptions(t,n)}return _shouldDropEvent$1(n,e)?null:n}}}),inboundFiltersIntegration=defineIntegration((t={})=>({...eventFiltersIntegration(t),name:"InboundFilters"}));function _mergeOptions(t={},e={}){return{allowUrls:[...t.allowUrls||[],...e.allowUrls||[]],denyUrls:[...t.denyUrls||[],...e.denyUrls||[]],ignoreErrors:[...t.ignoreErrors||[],...e.ignoreErrors||[],...t.disableErrorDefaults?[]:DEFAULT_IGNORE_ERRORS],ignoreTransactions:[...t.ignoreTransactions||[],...e.ignoreTransactions||[]]}}function _shouldDropEvent$1(t,e){if(t.type){if("transaction"===t.type&&_isIgnoredTransaction(t,e.ignoreTransactions))return DEBUG_BUILD$2&&debug.warn(`Event dropped due to being matched by \`ignoreTransactions\` option.\nEvent: ${getEventDescription(t)}`),!0}else{if(_isIgnoredError(t,e.ignoreErrors))return DEBUG_BUILD$2&&debug.warn(`Event dropped due to being matched by \`ignoreErrors\` option.\nEvent: ${getEventDescription(t)}`),!0;if(_isUselessError(t))return DEBUG_BUILD$2&&debug.warn(`Event dropped due to not having an error message, error type or stacktrace.\nEvent: ${getEventDescription(t)}`),!0;if(_isDeniedUrl(t,e.denyUrls))return DEBUG_BUILD$2&&debug.warn(`Event dropped due to being matched by \`denyUrls\` option.\nEvent: ${getEventDescription(t)}.\nUrl: ${_getEventFilterUrl(t)}`),!0;if(!_isAllowedUrl(t,e.allowUrls))return DEBUG_BUILD$2&&debug.warn(`Event dropped due to not being matched by \`allowUrls\` option.\nEvent: ${getEventDescription(t)}.\nUrl: ${_getEventFilterUrl(t)}`),!0}return!1}function _isIgnoredError(t,e){return!!e?.length&&getPossibleEventMessages(t).some(t=>stringMatchesSomePattern(t,e))}function _isIgnoredTransaction(t,e){if(!e?.length)return!1;const n=t.transaction;return!!n&&stringMatchesSomePattern(n,e)}function _isDeniedUrl(t,e){if(!e?.length)return!1;const n=_getEventFilterUrl(t);return!!n&&stringMatchesSomePattern(n,e)}function _isAllowedUrl(t,e){if(!e?.length)return!0;const n=_getEventFilterUrl(t);return!n||stringMatchesSomePattern(n,e)}function _getLastValidUrl(t=[]){for(let e=t.length-1;e>=0;e--){const n=t[e];if(n&&"<anonymous>"!==n.filename&&"[native code]"!==n.filename)return n.filename||null}return null}function _getEventFilterUrl(t){try{const e=[...t.exception?.values??[]].reverse().find(t=>void 0===t.mechanism?.parent_id&&t.stacktrace?.frames?.length),n=e?.stacktrace?.frames;return n?_getLastValidUrl(n):null}catch{return DEBUG_BUILD$2&&debug.error(`Cannot extract url for event ${getEventDescription(t)}`),null}}function _isUselessError(t){return!!t.exception?.values?.length&&!t.message&&!t.exception.values.some(t=>t.stacktrace||t.type&&"Error"!==t.type||t.value)}function applyAggregateErrorsToEvent(t,e,n,r,i,s){if(!i.exception?.values||!s||!isInstanceOf(s.originalException,Error))return;const a=i.exception.values.length>0?i.exception.values[i.exception.values.length-1]:void 0;a&&(i.exception.values=aggregateExceptionsFromError(t,e,r,s.originalException,n,i.exception.values,a,0))}function aggregateExceptionsFromError(t,e,n,r,i,s,a,o){if(s.length>=n+1)return s;let l=[...s];if(isInstanceOf(r[i],Error)){applyExceptionGroupFieldsForParentException(a,o,r);const s=t(e,r[i]),c=l.length;applyExceptionGroupFieldsForChildException(s,i,c,o),l=aggregateExceptionsFromError(t,e,n,r[i],i,[s,...l],s,c)}return isExceptionGroup(r)&&r.errors.forEach((s,c)=>{if(isInstanceOf(s,Error)){applyExceptionGroupFieldsForParentException(a,o,r);const d=t(e,s),h=l.length;applyExceptionGroupFieldsForChildException(d,`errors[${c}]`,h,o),l=aggregateExceptionsFromError(t,e,n,s,i,[d,...l],d,h)}}),l}function isExceptionGroup(t){return Array.isArray(t.errors)}function applyExceptionGroupFieldsForParentException(t,e,n){t.mechanism={handled:!0,type:"auto.core.linked_errors",...isExceptionGroup(n)&&{is_exception_group:!0},...t.mechanism,exception_id:e}}function applyExceptionGroupFieldsForChildException(t,e,n,r){t.mechanism={handled:!0,...t.mechanism,type:"chained",source:e,exception_id:n,parent_id:r}}function hasSentryFetchUrlHost(t){return isError(t)&&"__sentry_fetch_url_host__"in t&&"string"==typeof t.__sentry_fetch_url_host__}function _enhanceErrorWithSentryInfo(t){return hasSentryFetchUrlHost(t)?`${t.message} (${t.__sentry_fetch_url_host__})`:t.message}const _filter=/* @__PURE__ */new Set([]);function addConsoleInstrumentationHandler(t){const e="console",n=addHandler$1(e,t);return maybeInstrument(e,instrumentConsole),n}const instrumentedLevels=/* @__PURE__ */new Set;function instrumentConsole(){"console"in GLOBAL_OBJ&&CONSOLE_LEVELS.forEach(function(t){!instrumentedLevels.has(t)&&t in GLOBAL_OBJ.console&&(instrumentedLevels.add(t),fill(GLOBAL_OBJ.console,t,function(e){return originalConsoleMethods[t]=e,function(...e){const n=e[0],r=originalConsoleMethods[t],i=_filter.size&&"string"==typeof n&&stringMatchesSomePattern(n,_filter);i||triggerHandlers$1("console",{args:e,level:t}),(!i||DEBUG_BUILD$2&&debug.isEnabled())&&r?.apply(GLOBAL_OBJ.console,e)}}))})}function severityLevelFromString(t){return"warn"===t?"warning":["fatal","error","warning","log","info","debug"].includes(t)?t:"log"}const INTEGRATION_NAME$6="Dedupe",_dedupeIntegration=()=>{let t;return{name:INTEGRATION_NAME$6,processEvent(e){if(e.type)return e;try{if(_shouldDropEvent(e,t))return DEBUG_BUILD$2&&debug.warn("Event dropped due to being a duplicate of previously captured event."),null}catch{}return t=e}}},dedupeIntegration=defineIntegration(_dedupeIntegration);function _shouldDropEvent(t,e){return!(!e||!_isSameMessageEvent(t,e)&&!_isSameExceptionEvent(t,e))}function _isSameMessageEvent(t,e){const n=t.message,r=e.message;return!(!n&&!r||n&&!r||!n&&r||n!==r||!_isSameFingerprint(t,e)||!_isSameStacktrace(t,e))}function _isSameExceptionEvent(t,e){const n=_getExceptionFromEvent(e),r=_getExceptionFromEvent(t);return!!(n&&r&&n.type===r.type&&n.value===r.value&&_isSameFingerprint(t,e)&&_isSameStacktrace(t,e))}function _isSameStacktrace(t,e){let n=getFramesFromEvent(t),r=getFramesFromEvent(e);if(!n&&!r)return!0;if(n&&!r||!n&&r)return!1;if(r.length!==n.length)return!1;for(let t=0;t<r.length;t++){const e=r[t],i=n[t];if(e.filename!==i.filename||e.lineno!==i.lineno||e.colno!==i.colno||e.function!==i.function)return!1}return!0}function _isSameFingerprint(t,e){let n=t.fingerprint,r=e.fingerprint;if(!n&&!r)return!0;if(n&&!r||!n&&r)return!1;try{return!(n.join("")!==r.join(""))}catch{return!1}}function _getExceptionFromEvent(t){return t.exception?.values?.[0]}const INTEGRATION_NAME$5="ConversationId",_conversationIdIntegration=()=>({name:INTEGRATION_NAME$5,setup(t){t.on("spanStart",t=>{const e=getCurrentScope().getScopeData(),n=getIsolationScope().getScopeData(),r=e.conversationId||n.conversationId;if(r){const{op:e,data:n,description:i}=spanToJSON(t);if(!e?.startsWith("gen_ai.")&&!n["ai.operationId"]&&!i?.startsWith("ai."))return;t.setAttribute(GEN_AI_CONVERSATION_ID_ATTRIBUTE,r)}})}}),conversationIdIntegration=defineIntegration(_conversationIdIntegration);function instrumentFetchRequest(t,e,n,r,i){if(!t.fetchData)return;const{method:s,url:a}=t.fetchData,o=hasSpansEnabled()&&e(a);if(t.endTimestamp){const e=t.fetchData.__span;if(!e)return;const n=r[e];return void(n&&(o&&(endSpan(n,t),_callOnRequestSpanEnd(n,t,i)),delete r[e]))}const{spanOrigin:l="auto.http.browser",propagateTraceparent:c=!1}="object"==typeof i?i:{spanOrigin:i},d=getClient(),h=!!getActiveSpan(),u=h||!!d&&hasSpanStreamingEnabled(d),p=o&&u?startInactiveSpan(getSpanStartOptions(a,s,l)):new SentryNonRecordingSpan,f=spanIsIgnored(p)&&h?void 0:p;if(o&&!u&&d?.recordDroppedEvent("no_parent_span","span"),t.fetchData.__span=p.spanContext().spanId,r[p.spanContext().spanId]=p,n(t.fetchData.url)){const e={...t.args[1]||{}},n=_INTERNAL_getTracingHeadersForFetchRequest(t.args[0],e,hasSpansEnabled()&&u?f:void 0,c);n&&(t.args[1]=e,e.headers=n)}return d&&d.emit("beforeOutgoingRequestSpan",p,{input:t.args,response:t.response,startTimestamp:t.startTimestamp,endTimestamp:t.endTimestamp}),p}function _callOnRequestSpanEnd(t,e,n){const r="object"==typeof n&&null!==n?n.onRequestSpanEnd:void 0;r?.(t,{headers:e.response?.headers,error:e.error})}function _INTERNAL_getTracingHeadersForFetchRequest(t,e,n,r){const i=getTraceData({span:n,propagateTraceparent:r}),s=i["sentry-trace"],a=i.baggage,o=i.traceparent;if(!s)return;const l=e.headers||(isRequest(t)?t.headers:void 0);if(l){if(isHeaders(l)){const t=new Headers(l);if(t.get("sentry-trace")||t.set("sentry-trace",s),r&&o&&!t.get("traceparent")&&t.set("traceparent",o),a){const e=t.get("baggage");e?baggageHeaderHasSentryBaggageValues(e)||t.set("baggage",`${e},${a}`):t.set("baggage",a)}return t}if(isHeadersInitTupleArray(l)){const t=[...l];t.find(t=>"sentry-trace"===t[0])||t.push(["sentry-trace",s]),r&&o&&!t.find(t=>"traceparent"===t[0])&&t.push(["traceparent",o]);const e=l.find(t=>"baggage"===t[0]&&"string"==typeof t[1]&&baggageHeaderHasSentryBaggageValues(t[1]));return a&&!e&&t.push(["baggage",a]),t}{const t="sentry-trace"in l?l["sentry-trace"]:void 0,e="traceparent"in l?l.traceparent:void 0,n="baggage"in l?l.baggage:void 0,i=n?Array.isArray(n)?[...n]:[n]:[],c=n&&(Array.isArray(n)?n.find(t=>baggageHeaderHasSentryBaggageValues(t)):baggageHeaderHasSentryBaggageValues(n));a&&!c&&i.push(a);const d=Object.assign({},l,{"sentry-trace":t??s,...i.length>0&&{baggage:i.join(",")}});return r&&o&&!e&&(d.traceparent=o),d}}return{"sentry-trace":s,...a&&{baggage:a},...o&&{traceparent:o}}}function endSpan(t,e){if(e.response){setHttpStatus(t,e.response.status);const n=e.response?.headers?.get("content-length");if(n){const e=parseInt(n);e>0&&t.setAttribute("http.response_content_length",e)}}else e.error&&t.setStatus({code:SPAN_STATUS_ERROR,message:"internal_error"});t.end()}function baggageHeaderHasSentryBaggageValues(t){return"string"==typeof t&&t.split(",").some(t=>t.trim().startsWith(SENTRY_BAGGAGE_KEY_PREFIX))}function isHeaders(t){return"undefined"!=typeof Headers&&isInstanceOf(t,Headers)}function isHeadersInitTupleArray(t){return!!Array.isArray(t)&&t.every(t=>Array.isArray(t)&&2===t.length&&"string"==typeof t[0])}function getSpanStartOptions(t,e,n){if(t.startsWith("data:"))return{name:`${e} ${stripDataUrlContent(t)}`,attributes:getFetchSpanAttributes(t,void 0,e,n)};const r=parseStringToURLObject(t);return{name:`${e} ${r?getSanitizedUrlStringFromUrlObject(r):t}`,attributes:getFetchSpanAttributes(t,r,e,n)}}function getFetchSpanAttributes(t,e,n,r){const i={url:stripDataUrlContent(t),type:"fetch","http.method":n,[SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN]:r,[SEMANTIC_ATTRIBUTE_SENTRY_OP]:"http.client"};return e&&(isURLObjectRelative(e)||(i[ws]=stripDataUrlContent(e.href),i[Yu]=stripDataUrlContent(e.href),i["server.address"]=e.host),e.search&&(i["http.query"]=e.search),e.hash&&(i["http.fragment"]=e.hash)),i}function getBreadcrumbLogLevelFromHttpStatusCode(t){return void 0===t?void 0:t>=400&&t<500?"warning":t>=500?"error":void 0}const WINDOW$3=GLOBAL_OBJ;function supportsHistory(){return"history"in WINDOW$3&&!!WINDOW$3.history}function _isFetchSupported(){if(!("fetch"in WINDOW$3))return!1;try{return new Headers,new Request("data:,"),new Response,!0}catch{return!1}}function isNativeFunction(t){return t&&/^function\s+\w+\(\)\s+\{\s+\[native code\]\s+\}$/.test(t.toString())}function supportsNativeFetch(){if("string"==typeof EdgeRuntime)return!0;if(!_isFetchSupported())return!1;if(isNativeFunction(WINDOW$3.fetch))return!0;let t=!1;const e=WINDOW$3.document;if(e&&"function"==typeof e.createElement)try{const n=e.createElement("iframe");n.hidden=!0,e.head.appendChild(n),n.contentWindow?.fetch&&(t=isNativeFunction(n.contentWindow.fetch)),e.head.removeChild(n)}catch(t){DEBUG_BUILD$2&&debug.warn("Could not create sandbox iframe for pure fetch check, bailing to window.fetch: ",t)}return t}function addFetchInstrumentationHandler(t,e){const n="fetch",r=addHandler$1(n,t);return maybeInstrument(n,()=>instrumentFetch(void 0,e)),r}function addFetchEndInstrumentationHandler(t){const e="fetch-body-resolved",n=addHandler$1(e,t);return maybeInstrument(e,()=>instrumentFetch(streamHandler)),n}function instrumentFetch(t,e=!1){e&&!supportsNativeFetch()||fill(GLOBAL_OBJ,"fetch",function(e){return function(...n){const r=new Error,{method:i,url:s}=parseFetchArgs(n),a={args:n,fetchData:{method:i,url:s},startTimestamp:1e3*timestampInSeconds(),virtualError:r,headers:getHeadersFromFetchArgs(n)};return t||triggerHandlers$1("fetch",{...a}),e.apply(GLOBAL_OBJ,n).then(async e=>(t?t(e):triggerHandlers$1("fetch",{...a,endTimestamp:1e3*timestampInSeconds(),response:e}),e),t=>{triggerHandlers$1("fetch",{...a,endTimestamp:1e3*timestampInSeconds(),error:t}),isError(t)&&void 0===t.stack&&(t.stack=r.stack,addNonEnumerableProperty(t,"framesToPop",1));const e=getClient(),n=e?.getOptions().enhanceFetchErrorMessages??"always";if(!1!==n&&t instanceof TypeError&&("Failed to fetch"===t.message||"Load failed"===t.message||"NetworkError when attempting to fetch resource."===t.message))try{const e=new URL(a.fetchData.url).host;"always"===n?t.message=`${t.message} (${e})`:addNonEnumerableProperty(t,"__sentry_fetch_url_host__",e)}catch{}throw t})}})}async function resolveResponse(t,e){if(t?.body){const n=t.body,r=n.getReader(),i=setTimeout(()=>{n.cancel().then(null,()=>{})},9e4);let s=!0;for(;s;){let t;try{t=setTimeout(()=>{n.cancel().then(null,()=>{})},5e3);const{done:i}=await r.read();clearTimeout(t),i&&(e(),s=!1)}catch{s=!1}finally{clearTimeout(t)}}clearTimeout(i),r.releaseLock(),n.cancel().then(null,()=>{})}}function streamHandler(t){let e;try{e=t.clone()}catch{return}resolveResponse(e,()=>{triggerHandlers$1("fetch-body-resolved",{endTimestamp:1e3*timestampInSeconds(),response:t})})}function hasProp(t,e){return isObjectLike(t)&&!!t[e]}function getUrlFromResource(t){return"string"==typeof t?t:t?hasProp(t,"url")?t.url:t.toString?t.toString():"":""}function parseFetchArgs(t){if(0===t.length)return{method:"GET",url:""};if(2===t.length){const[e,n]=t;return{url:getUrlFromResource(e),method:hasProp(n,"method")?String(n.method).toUpperCase():isRequest(e)&&hasProp(e,"method")?String(e.method).toUpperCase():"GET"}}const e=t[0];return{url:getUrlFromResource(e),method:hasProp(e,"method")?String(e.method).toUpperCase():"GET"}}function getHeadersFromFetchArgs(t){const[e,n]=t;try{if("object"==typeof n&&null!==n&&"headers"in n&&n.headers)return new Headers(n.headers);if(isRequest(e))return new Headers(e.headers)}catch{}}const WINDOW$2=GLOBAL_OBJ;function getLocationHref(){try{return WINDOW$2.document.location.href}catch{return""}}function getComponentName(t,e=5){if(!WINDOW$2.HTMLElement)return null;let n=t;for(let t=0;t<e;t++){if(!n)return null;if(n instanceof HTMLElement){if(n.dataset.sentryComponent)return n.dataset.sentryComponent;if(n.dataset.sentryElement)return n.dataset.sentryElement}n=n.parentNode}return null}const WINDOW$1=GLOBAL_OBJ;let ignoreOnError=0;function shouldIgnoreOnError(){return ignoreOnError>0}function ignoreNextOnError(){ignoreOnError++,setTimeout(()=>{ignoreOnError--})}function wrap(t,e={}){if("function"!=typeof t)return t;try{if(Object.prototype.hasOwnProperty.call(t,"__sentry_wrapped__")){const e=t.__sentry_wrapped__;return"function"==typeof e?e:t}if(getOriginalFunction(t))return t}catch{return t}const n=function(...n){GLOBAL_OBJ._sentryWrappedDepth=(GLOBAL_OBJ._sentryWrappedDepth||0)+1;try{const r=n.map(t=>wrap(t,e));return t.apply(this,r)}catch(t){throw ignoreNextOnError(),withScope(r=>{r.addEventProcessor(t=>(e.mechanism&&(addExceptionTypeValue(t,void 0,void 0),addExceptionMechanism(t,e.mechanism)),t.extra={...t.extra,arguments:n},t)),captureException(t)}),t}finally{GLOBAL_OBJ._sentryWrappedDepth=(GLOBAL_OBJ._sentryWrappedDepth||0)-1}};try{for(const e in t)Object.prototype.hasOwnProperty.call(t,e)&&(n[e]=t[e])}catch{}markFunctionWrapped(n,t),addNonEnumerableProperty(t,"__sentry_wrapped__",n);try{Object.getOwnPropertyDescriptor(n,"name").configurable&&Object.defineProperty(n,"name",{get:()=>t.name})}catch{}return n}function getHttpRequestData(){const t=getLocationHref(),{referrer:e}=WINDOW$1.document||{},{userAgent:n}=WINDOW$1.navigator||{};return{url:t,headers:{...e&&{Referer:e},...n&&{"User-Agent":n}}}}function exceptionFromError(t,e){const n=parseStackFrames(t,e),r={type:extractType(e),value:extractMessage(e)};return n.length&&(r.stacktrace={frames:n}),void 0===r.type&&""===r.value&&(r.value="Unrecoverable error caught"),r}function eventFromPlainObject(t,e,n,r){const i=getClient(),s=i?.getOptions().normalizeDepth,a=getErrorPropertyFromObject(e),o={__serialized__:normalizeToSize(e,s)};if(a)return{exception:{values:[exceptionFromError(t,a)]},extra:o};const l={exception:{values:[{type:isEvent(e)?e.constructor.name:r?"UnhandledRejection":"Error",value:getNonErrorObjectExceptionValue(e,{isUnhandledRejection:r})}]},extra:o};if(n){const e=parseStackFrames(t,n);e.length&&(l.exception.values[0].stacktrace={frames:e})}return l}function eventFromError(t,e){return{exception:{values:[exceptionFromError(t,e)]}}}function parseStackFrames(t,e){const n=e.stacktrace||e.stack||"",r=getSkipFirstStackStringLines(e),i=getPopFirstTopFrames(e);try{return t(n,r,i)}catch{}return[]}const reactMinifiedRegexp=/Minified React error #\d+;/i;function getSkipFirstStackStringLines(t){return t&&reactMinifiedRegexp.test(t.message)?1:0}function getPopFirstTopFrames(t){return"number"==typeof t.framesToPop?t.framesToPop:0}function isWebAssemblyException(t){return"undefined"!=typeof WebAssembly&&void 0!==WebAssembly.Exception&&t instanceof WebAssembly.Exception}function extractType(t){const e=t?.name;return!e&&isWebAssemblyException(t)?t.message&&Array.isArray(t.message)&&2==t.message.length?t.message[0]:"WebAssembly.Exception":e}function extractMessage(t){const e=t?.message;return isWebAssemblyException(t)?Array.isArray(t.message)&&2==t.message.length?t.message[1]:"wasm exception":e?_enhanceErrorWithSentryInfo(e.error&&"string"==typeof e.error.message?e.error:t):"No error message"}function eventFromException(t,e,n,r){const i=eventFromUnknownInput(t,e,n?.syntheticException||void 0,r);return addExceptionMechanism(i),i.level="error",n?.event_id&&(i.event_id=n.event_id),resolvedSyncPromise(i)}function eventFromMessage(t,e,n="info",r,i){const s=eventFromString(t,e,r?.syntheticException||void 0,i);return s.level=n,r?.event_id&&(s.event_id=r.event_id),resolvedSyncPromise(s)}function eventFromUnknownInput(t,e,n,r,i){let s;if(isErrorEvent$1(e)&&e.error)return eventFromError(t,e.error);if(isDOMError(e)||isDOMException(e)){const i=e;if("stack"in e){s=eventFromError(t,e);const i=s.exception?.values?.[0];if(r&&n&&i&&!i.stacktrace){const e=parseStackFrames(t,n);e.length&&(i.stacktrace={frames:e},addExceptionMechanism(s,{synthetic:!0}))}}else{const e=i.name||(isDOMError(i)?"DOMError":"DOMException"),a=i.message?`${e}: ${i.message}`:e;s=eventFromString(t,a,n,r),addExceptionTypeValue(s,a)}return"code"in i&&(s.tags={...s.tags,"DOMException.code":`${i.code}`}),s}return isError(e)?eventFromError(t,e):isPlainObject(e)||isEvent(e)?(s=eventFromPlainObject(t,e,n,i),addExceptionMechanism(s,{synthetic:!0}),s):(s=eventFromString(t,e,n,r),addExceptionTypeValue(s,`${e}`,void 0),addExceptionMechanism(s,{synthetic:!0}),s)}function eventFromString(t,e,n,r){const i={};if(r&&n){const r=parseStackFrames(t,n);r.length&&(i.exception={values:[{value:e,stacktrace:{frames:r}}]}),addExceptionMechanism(i,{synthetic:!0})}if(isParameterizedString(e)){const{__sentry_template_string__:t,__sentry_template_values__:n}=e;return i.logentry={message:t,params:n},i}return i.message=e,i}function getNonErrorObjectExceptionValue(t,{isUnhandledRejection:e}){const n=extractExceptionKeysForMessage(t),r=e?"promise rejection":"exception";return isErrorEvent$1(t)?`Event \`ErrorEvent\` captured as ${r} with message \`${t.message}\``:isEvent(t)?`Event \`${getObjectClassName(t)}\` (type=${t.type}) captured as ${r}`:`Object captured as ${r} with keys: ${n}`}function getObjectClassName(t){try{const e=Object.getPrototypeOf(t);return e?e.constructor.name:void 0}catch{}}function getErrorPropertyFromObject(t){return Object.values(t).find(t=>t instanceof Error)}class BrowserClient extends Client{constructor(t){const e=applyDefaultOptions(t);applySdkMetadata(e,"browser",["browser"],WINDOW$1.SENTRY_SDK_SOURCE||getSDKSource()),super(e);const{userInfo:n}=this.getDataCollectionOptions();e._metadata?.sdk&&(e._metadata.sdk.settings={infer_ip:n?"auto":"never",...e._metadata.sdk.settings});const{sendClientReports:r}=this._options;WINDOW$1.document&&WINDOW$1.document.addEventListener("visibilitychange",()=>{"hidden"===WINDOW$1.document.visibilityState&&(r&&this._flushOutcomes(),queueMicrotask(()=>{this.flush()}))}),n&&this.on("beforeSendSession",addAutoIpAddressToSession)}eventFromException(t,e){return eventFromException(this._options.stackParser,t,e,this._options.attachStacktrace)}eventFromMessage(t,e="info",n){return eventFromMessage(this._options.stackParser,t,e,n,this._options.attachStacktrace)}_prepareEvent(t,e,n,r){return t.platform=t.platform||"javascript",super._prepareEvent(t,e,n,r)}}function applyDefaultOptions(t){return{release:"string"==typeof __SENTRY_RELEASE__?__SENTRY_RELEASE__:WINDOW$1.SENTRY_RELEASE?.id,sendClientReports:!0,parentSpanIsAlwaysRootSpan:!0,...t}}const DEBUG_BUILD$1="undefined"==typeof __SENTRY_DEBUG__||__SENTRY_DEBUG__,WINDOW=GLOBAL_OBJ,getRating=(t,e)=>t>e[1]?"poor":t>e[0]?"needs-improvement":"good",bindReporter=(t,e,n,r)=>{let i,s;return a=>{e.value>=0&&(a||r)&&(s=e.value-(i??0),(s||void 0===i)&&(i=e.value,e.delta=s,e.rating=getRating(e.value,n),t(e)))}},getNavigationEntry=(t=!0)=>{const e=WINDOW.performance?.getEntriesByType?.("navigation")[0];if(!t||e&&e.responseStart>0&&e.responseStart<performance.now())return e},getActivationStart=()=>{const t=getNavigationEntry();return t?.activationStart??0};function addPageListener(t,e,n){WINDOW.document&&WINDOW.addEventListener(t,e,n)}function removePageListener(t,e,n){WINDOW.document&&WINDOW.removeEventListener(t,e,n)}let firstHiddenTime=-1;const onHiddenFunctions=/* @__PURE__ */new Set,initHiddenTime=()=>"hidden"!==WINDOW.document?.visibilityState||WINDOW.document?.prerendering?Infinity:0,onVisibilityUpdate=t=>{if(isPageHidden(t)&&firstHiddenTime>-1){if("visibilitychange"===t.type||"pagehide"===t.type)for(const t of onHiddenFunctions)t();isFinite(firstHiddenTime)||(firstHiddenTime="visibilitychange"===t.type?t.timeStamp:0,removePageListener("prerenderingchange",onVisibilityUpdate,!0))}},getVisibilityWatcher=()=>{if(WINDOW.document&&firstHiddenTime<0){const t=getActivationStart(),e=WINDOW.document.prerendering?void 0:globalThis.performance.getEntriesByType("visibility-state").filter(e=>"hidden"===e.name&&e.startTime>t)[0]?.startTime;firstHiddenTime=e??initHiddenTime(),addPageListener("visibilitychange",onVisibilityUpdate,!0),addPageListener("pagehide",onVisibilityUpdate,!0),addPageListener("prerenderingchange",onVisibilityUpdate,!0)}return{get firstHiddenTime(){return firstHiddenTime},onHidden(t){onHiddenFunctions.add(t)}}};function isPageHidden(t){return"pagehide"===t.type||"hidden"===WINDOW.document?.visibilityState}const generateUniqueID=()=>`v5-${Date.now()}-${Math.floor(8999999999999*Math.random())+1e12}`,initMetric=(t,e=-1)=>{const n=getNavigationEntry();let r="navigate";return n&&(WINDOW.document?.prerendering||getActivationStart()>0?r="prerender":WINDOW.document?.wasDiscarded?r="restore":n.type&&(r=n.type.replace(/_/g,"-"))),{name:t,value:e,rating:"good",delta:0,entries:[],id:generateUniqueID(),navigationType:r}},instanceMap=/* @__PURE__ */new WeakMap;function initUnique(t,e){try{return instanceMap.get(t)||instanceMap.set(t,new e),instanceMap.get(t)}catch(t){return new e}}class LayoutShiftManager{constructor(){this._sessionValue=0,this._sessionEntries=[]}_processEntry(t){if(t.hadRecentInput)return;const e=this._sessionEntries[0],n=this._sessionEntries[this._sessionEntries.length-1];this._sessionValue&&e&&n&&t.startTime-n.startTime<1e3&&t.startTime-e.startTime<5e3?(this._sessionValue+=t.value,this._sessionEntries.push(t)):(this._sessionValue=t.value,this._sessionEntries=[t]),this._onAfterProcessingUnexpectedShift?.(t)}}const observe=(t,e,n={})=>{try{if(PerformanceObserver.supportedEntryTypes.includes(t)){const r=new PerformanceObserver(t=>{Promise.resolve().then(()=>{e(t.getEntries())})});return r.observe({type:t,buffered:!0,...n}),r}}catch{}},runOnce=t=>{let e=!1;return()=>{e||(t(),e=!0)}},whenActivated=t=>{WINDOW.document?.prerendering?addEventListener("prerenderingchange",()=>t(),!0):t()},FCPThresholds=[1800,3e3],onFCP=(t,e={})=>{whenActivated(()=>{const n=getVisibilityWatcher(),r=initMetric("FCP");let i;const s=observe("paint",t=>{for(const e of t)"first-contentful-paint"===e.name&&(s.disconnect(),e.startTime<n.firstHiddenTime&&(r.value=Math.max(e.startTime-getActivationStart(),0),r.entries.push(e),i(!0)))});s&&(i=bindReporter(t,r,FCPThresholds,e.reportAllChanges))})},CLSThresholds=[.1,.25],onCLS=(t,e={})=>{onFCP(runOnce(()=>{const n=initMetric("CLS",0);let r;const i=getVisibilityWatcher(),s=initUnique(e,LayoutShiftManager),a=t=>{for(const e of t)s._processEntry(e);s._sessionValue>n.value&&(n.value=s._sessionValue,n.entries=s._sessionEntries,r())},o=observe("layout-shift",a);o&&(r=bindReporter(t,n,CLSThresholds,e.reportAllChanges),i.onHidden(()=>{a(o.takeRecords()),r(!0)}),WINDOW?.setTimeout?.(r))}))};let interactionCountEstimate=0,minKnownInteractionId=Infinity,maxKnownInteractionId=0;const updateEstimate=t=>{t.forEach(t=>{t.interactionId&&(minKnownInteractionId=Math.min(minKnownInteractionId,t.interactionId),maxKnownInteractionId=Math.max(maxKnownInteractionId,t.interactionId),interactionCountEstimate=maxKnownInteractionId?(maxKnownInteractionId-minKnownInteractionId)/7+1:0)})};let po;const getInteractionCount=()=>po?interactionCountEstimate:performance.interactionCount||0,initInteractionCountPolyfill=()=>{"interactionCount"in performance||po||(po=observe("event",updateEstimate,{type:"event",buffered:!0,durationThreshold:0}))},MAX_INTERACTIONS_TO_CONSIDER=10;let prevInteractionCount=0;const getInteractionCountForNavigation=()=>getInteractionCount()-prevInteractionCount;class InteractionManager{constructor(){this._longestInteractionList=[],this._longestInteractionMap=/* @__PURE__ */new Map}_resetInteractions(){prevInteractionCount=getInteractionCount(),this._longestInteractionList.length=0,this._longestInteractionMap.clear()}_estimateP98LongestInteraction(){const t=Math.min(this._longestInteractionList.length-1,Math.floor(getInteractionCountForNavigation()/50));return this._longestInteractionList[t]}_processEntry(t){if(this._onBeforeProcessingEntry?.(t),!t.interactionId&&"first-input"!==t.entryType)return;const e=this._longestInteractionList.at(-1);let n=this._longestInteractionMap.get(t.interactionId);if(n||this._longestInteractionList.length<MAX_INTERACTIONS_TO_CONSIDER||t.duration>e._latency){if(n?t.duration>n._latency?(n.entries=[t],n._latency=t.duration):t.duration===n._latency&&t.startTime===n.entries[0].startTime&&n.entries.push(t):(n={id:t.interactionId,entries:[t],_latency:t.duration},this._longestInteractionMap.set(n.id,n),this._longestInteractionList.push(n)),this._longestInteractionList.sort((t,e)=>e._latency-t._latency),this._longestInteractionList.length>MAX_INTERACTIONS_TO_CONSIDER){const t=this._longestInteractionList.splice(MAX_INTERACTIONS_TO_CONSIDER);for(const e of t)this._longestInteractionMap.delete(e.id)}this._onAfterProcessingINPCandidate?.(n)}}}const whenIdleOrHidden=t=>{const e=WINDOW.requestIdleCallback||WINDOW.setTimeout;"hidden"===WINDOW.document?.visibilityState?t():(addPageListener("visibilitychange",t=runOnce(t),{once:!0,capture:!0}),addPageListener("pagehide",t,{once:!0,capture:!0}),e(()=>{t(),removePageListener("visibilitychange",t,{capture:!0}),removePageListener("pagehide",t,{capture:!0})}))},INPThresholds=[200,500],DEFAULT_DURATION_THRESHOLD=40,onINP=(t,e={})=>{if(!globalThis.PerformanceEventTiming||!("interactionId"in PerformanceEventTiming.prototype))return;const n=getVisibilityWatcher();whenActivated(()=>{initInteractionCountPolyfill();const r=initMetric("INP");let i;const s=initUnique(e,InteractionManager),a=t=>{whenIdleOrHidden(()=>{for(const e of t)s._processEntry(e);const e=s._estimateP98LongestInteraction();e&&e._latency!==r.value&&(r.value=e._latency,r.entries=e.entries,i())})},o=observe("event",a,{durationThreshold:e.durationThreshold??DEFAULT_DURATION_THRESHOLD});i=bindReporter(t,r,INPThresholds,e.reportAllChanges),o&&(o.observe({type:"first-input",buffered:!0}),n.onHidden(()=>{a(o.takeRecords()),i(!0)}))})};class LCPEntryManager{_processEntry(t){this._onBeforeProcessingEntry?.(t)}}const LCPThresholds=[2500,4e3],onLCP=(t,e={})=>{whenActivated(()=>{const n=getVisibilityWatcher(),r=initMetric("LCP");let i;const s=initUnique(e,LCPEntryManager),a=t=>{e.reportAllChanges||(t=t.slice(-1));for(const e of t)s._processEntry(e),e.startTime<n.firstHiddenTime&&(r.value=Math.max(e.startTime-getActivationStart(),0),r.entries=[e],i())},o=observe("largest-contentful-paint",a);if(o){i=bindReporter(t,r,LCPThresholds,e.reportAllChanges);const n=runOnce(()=>{a(o.takeRecords()),o.disconnect(),i(!0)}),s=t=>{t.isTrusted&&(whenIdleOrHidden(n),removePageListener(t.type,s,{capture:!0}))};for(const t of["keydown","click","visibilitychange"])addPageListener(t,s,{capture:!0})}})},TTFBThresholds=[800,1800],whenReady=t=>{WINDOW.document?.prerendering?whenActivated(()=>whenReady(t)):"complete"!==WINDOW.document?.readyState?addEventListener("load",()=>whenReady(t),!0):setTimeout(t)},onTTFB=(t,e={})=>{const n=initMetric("TTFB"),r=bindReporter(t,n,TTFBThresholds,e.reportAllChanges);whenReady(()=>{const t=getNavigationEntry();t&&(n.value=Math.max(t.responseStart-getActivationStart(),0),n.entries=[t],r(!0))})},handlers={},instrumented={};let _previousCls,_previousLcp,_previousTtfb,_previousInp;function addClsInstrumentationHandler(t,e=!1){return addMetricObserver("cls",t,instrumentCls,_previousCls,e)}function addLcpInstrumentationHandler(t,e=!1){return addMetricObserver("lcp",t,instrumentLcp,_previousLcp,e)}function addTtfbInstrumentationHandler(t){return addMetricObserver("ttfb",t,instrumentTtfb,_previousTtfb)}function addInpInstrumentationHandler(t){return addMetricObserver("inp",t,instrumentInp,_previousInp)}function addPerformanceInstrumentationHandler(t,e){return addHandler(t,e),instrumented[t]||(instrumentPerformanceObserver(t),instrumented[t]=!0),getCleanupCallback(t,e)}function triggerHandlers(t,e){const n=handlers[t];if(n?.length)for(const r of n)try{r(e)}catch(e){DEBUG_BUILD$1&&debug.error(`Error while triggering instrumentation handler.\nType: ${t}\nName: ${getFunctionName(r)}\nError:`,e)}}function instrumentCls(){return onCLS(t=>{triggerHandlers("cls",{metric:t}),_previousCls=t},{reportAllChanges:!0})}function instrumentLcp(){return onLCP(t=>{triggerHandlers("lcp",{metric:t}),_previousLcp=t},{reportAllChanges:!0})}function instrumentTtfb(){return onTTFB(t=>{triggerHandlers("ttfb",{metric:t}),_previousTtfb=t})}function instrumentInp(){return onINP(t=>{triggerHandlers("inp",{metric:t}),_previousInp=t})}function addMetricObserver(t,e,n,r,i=!1){let s;return addHandler(t,e),instrumented[t]||(s=n(),instrumented[t]=!0),r&&e({metric:r}),getCleanupCallback(t,e,i?s:void 0)}function instrumentPerformanceObserver(t){const e={};"event"===t&&(e.durationThreshold=0),observe(t,e=>{triggerHandlers(t,{entries:e})},e)}function addHandler(t,e){handlers[t]=handlers[t]||[],handlers[t].push(e)}function getCleanupCallback(t,e,n){return()=>{n&&n();const r=handlers[t];if(!r)return;const i=r.indexOf(e);-1!==i&&r.splice(i,1)}}function isPerformanceEventTiming(t){return"duration"in t}const DEFAULT_MAX_STRING_LENGTH=80,accessors={};try{"undefined"!=typeof Node&&(accessors.parentNode=Object.getOwnPropertyDescriptor(Node.prototype,"parentNode").get),"undefined"!=typeof Element&&(accessors.tagName=Object.getOwnPropertyDescriptor(Element.prototype,"tagName").get,accessors.id=Object.getOwnPropertyDescriptor(Element.prototype,"id").get,accessors.className=Object.getOwnPropertyDescriptor(Element.prototype,"className").get,accessors.getAttribute=Element.prototype.getAttribute),"undefined"!=typeof HTMLElement&&(accessors.dataset=Object.getOwnPropertyDescriptor(HTMLElement.prototype,"dataset").get)}catch{}function _safeRead(t,e,n){const r=accessors[e];if(r)try{return r.call(t,n)}catch{}const i=t[e];return"function"==typeof i?i.call(t,n):i}function htmlTreeAsString(t,e={}){if(!t)return"<unknown>";try{let n=t;const r=5,i=[];let s=0,a=0;const o=" > ",l=o.length;let c;const d=Array.isArray(e)?e:e.keyAttrs,h=!Array.isArray(e)&&e.maxStringLength||DEFAULT_MAX_STRING_LENGTH;for(;n&&s++<r&&(c=_htmlElementAsString(n,d),!("html"===c||s>1&&a+i.length*l+c.length>=h));)i.push(c),a+=c.length,n=_safeRead(n,"parentNode");return i.reverse().join(o)}catch{return"<unknown>"}}function _htmlElementAsString(t,e){const n=[],r=_safeRead(t,"tagName");if(!r)return"";if("undefined"!=typeof HTMLElement&&t instanceof HTMLElement){const e=_safeRead(t,"dataset");if(e){if(e.sentryComponent)return e.sentryComponent;if(e.sentryElement)return e.sentryElement}}n.push(r.toLowerCase());const i=e?.length?e.filter(e=>_safeRead(t,"getAttribute",e)).map(e=>[e,_safeRead(t,"getAttribute",e)]):null;if(i?.length)i.forEach(t=>{n.push(`[${t[0]}="${t[1]}"]`)});else{const e=_safeRead(t,"id");e&&n.push(`#${e}`);const r=_safeRead(t,"className");if(r&&isString(r)){const t=r.split(/\s+/);for(const e of t)n.push(`.${e}`)}}for(const e of["aria-label","type","name","title","alt"]){const r=_safeRead(t,"getAttribute",e);r&&n.push(`[${e}="${r}"]`)}return n.join("")}const onHidden=t=>{const e=e=>{"pagehide"!==e.type&&"hidden"!==WINDOW.document?.visibilityState||t(e)};addPageListener("visibilitychange",e,{capture:!0,once:!0}),addPageListener("pagehide",e,{capture:!0,once:!0})};function isMeasurementValue(t){return"number"==typeof t&&isFinite(t)}function startAndEndSpan(t,e,n,{...r}){const i=spanToJSON(t).start_timestamp;return i&&i>e&&"function"==typeof t.updateStartTime&&t.updateStartTime(e),withActiveSpan(t,()=>{const t=startInactiveSpan({startTime:e,...r});return t&&t.end(n),t})}function startStandaloneWebVitalSpan(t){const e=getClient();if(!e)return;const{name:n,transaction:r,attributes:i,startTime:s}=t,{release:a,environment:o}=e.getOptions(),{userInfo:l}=e.getDataCollectionOptions(),c=e.getIntegrationByName("Replay"),d=c?.getReplayId(),h=getCurrentScope(),u=h.getUser(),p=void 0!==u?u.email||u.id||u.ip_address:void 0;let f;try{f=h.getScopeData().contexts.profile.profile_id}catch{}return startInactiveSpan({name:n,attributes:{release:a,environment:o,user:p||void 0,profile_id:f||void 0,replay_id:d||void 0,transaction:r,"user_agent.original":WINDOW.navigator?.userAgent,"client.address":l?"{{auto}}":void 0,...i},startTime:s,experimental:{standalone:!0}})}function getBrowserPerformanceAPI(){return WINDOW.addEventListener&&WINDOW.performance}function msToSec(t){return t/1e3}function extractNetworkProtocol(t){let e="unknown",n="unknown",r="";for(const i of t){if("/"===i){[e,n]=t.split("/");break}if(!isNaN(Number(i))){e="h"===r?"http":r,n=t.split(r)[1];break}r+=i}return r===t&&(e=r),{name:e,version:n}}function supportsWebVital(t){try{return PerformanceObserver.supportedEntryTypes.includes(t)}catch{return!1}}function listenForWebVitalReportEvents(t,e){let n,r=!1;function i(t){!r&&n&&e(t,n.spanContext().spanId,n),r=!0}onHidden(()=>{i("pagehide")});const s=t.on("beforeStartNavigationSpan",(t,e)=>{e?.isRedirect||(i("navigation"),s(),a())}),a=t.on("afterStartPageLoadSpan",t=>{n=t,a()})}function trackClsAsStandaloneSpan(t){let e,n=0;if(!supportsWebVital("layout-shift"))return;const r=addClsInstrumentationHandler(({metric:t})=>{const r=t.entries[t.entries.length-1];r&&(n=t.value,e=r)},!0);listenForWebVitalReportEvents(t,(t,i)=>{_sendStandaloneClsSpan(n,e,i,t),r()})}function _sendStandaloneClsSpan(t,e,n,r){DEBUG_BUILD$1&&debug.log(`Sending CLS span (${t})`);const i=e?msToSec((browserPerformanceTimeOrigin()||0)+e.startTime):timestampInSeconds(),s=getCurrentScope().getScopeData().transactionName,a=e?htmlTreeAsString(e.sources[0]?.node):"Layout shift",o={[SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN]:"auto.http.browser.cls",[SEMANTIC_ATTRIBUTE_SENTRY_OP]:"ui.webvital.cls",[SEMANTIC_ATTRIBUTE_EXCLUSIVE_TIME]:0,"sentry.pageload.span_id":n,"sentry.report_event":r};e?.sources&&e.sources.forEach((t,e)=>{o[`cls.source.${e+1}`]=htmlTreeAsString(t.node)});const l=startStandaloneWebVitalSpan({name:a,transaction:s,attributes:o,startTime:i});l&&(l.addEvent("cls",{[SEMANTIC_ATTRIBUTE_SENTRY_MEASUREMENT_UNIT]:"",[SEMANTIC_ATTRIBUTE_SENTRY_MEASUREMENT_VALUE]:t}),l.end(i))}const MAX_PLAUSIBLE_LCP_DURATION=6e4;function isValidLcpMetric(t){return null!=t&&t>0&&t<=MAX_PLAUSIBLE_LCP_DURATION}function trackLcpAsStandaloneSpan(t){let e,n=0;if(!supportsWebVital("largest-contentful-paint"))return;const r=addLcpInstrumentationHandler(({metric:t})=>{const r=t.entries[t.entries.length-1];r&&isValidLcpMetric(t.value)&&(n=t.value,e=r)},!0);listenForWebVitalReportEvents(t,(t,i)=>{_sendStandaloneLcpSpan(n,e,i,t),r()})}function _sendStandaloneLcpSpan(t,e,n,r){if(!isValidLcpMetric(t))return;DEBUG_BUILD$1&&debug.log(`Sending LCP span (${t})`);const i=msToSec((browserPerformanceTimeOrigin()||0)+(e?.startTime||0)),s=getCurrentScope().getScopeData().transactionName,a=e?htmlTreeAsString(e.element):"Largest contentful paint",o={[SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN]:"auto.http.browser.lcp",[SEMANTIC_ATTRIBUTE_SENTRY_OP]:"ui.webvital.lcp",[SEMANTIC_ATTRIBUTE_EXCLUSIVE_TIME]:0,"sentry.pageload.span_id":n,"sentry.report_event":r};e&&(e.element&&(o["lcp.element"]=htmlTreeAsString(e.element)),e.id&&(o["lcp.id"]=e.id),e.url&&(o["lcp.url"]=e.url),null!=e.loadTime&&(o["lcp.loadTime"]=e.loadTime),null!=e.renderTime&&(o["lcp.renderTime"]=e.renderTime),null!=e.size&&(o["lcp.size"]=e.size));const l=startStandaloneWebVitalSpan({name:a,transaction:s,attributes:o,startTime:i});l&&(l.addEvent("lcp",{[SEMANTIC_ATTRIBUTE_SENTRY_MEASUREMENT_UNIT]:"millisecond",[SEMANTIC_ATTRIBUTE_SENTRY_MEASUREMENT_VALUE]:t}),l.end(i))}function getAbsoluteTime(t){return t?((browserPerformanceTimeOrigin()||performance.timeOrigin)+t)/1e3:t}function resourceTimingToSpanAttributes(t){const e={};if(null!=t.nextHopProtocol){const{name:n,version:r}=extractNetworkProtocol(t.nextHopProtocol);e["network.protocol.version"]=r,e["network.protocol.name"]=n}return browserPerformanceTimeOrigin()||getBrowserPerformanceAPI()?.timeOrigin?dropUndefinedKeysFromObject({...e,"http.request.redirect_start":getAbsoluteTime(t.redirectStart),"http.request.redirect_end":getAbsoluteTime(t.redirectEnd),"http.request.worker_start":getAbsoluteTime(t.workerStart),"http.request.fetch_start":getAbsoluteTime(t.fetchStart),"http.request.domain_lookup_start":getAbsoluteTime(t.domainLookupStart),"http.request.domain_lookup_end":getAbsoluteTime(t.domainLookupEnd),"http.request.connect_start":getAbsoluteTime(t.connectStart),"http.request.secure_connection_start":getAbsoluteTime(t.secureConnectionStart),"http.request.connection_end":getAbsoluteTime(t.connectEnd),"http.request.request_start":getAbsoluteTime(t.requestStart),"http.request.response_start":getAbsoluteTime(t.responseStart),"http.request.response_end":getAbsoluteTime(t.responseEnd),"http.request.time_to_first_byte":null!=t.responseStart?t.responseStart/1e3:void 0}):e}function dropUndefinedKeysFromObject(t){return Object.fromEntries(Object.entries(t).filter(([,t])=>null!=t))}const MAX_INT_AS_BYTES=2147483647;let _performanceCursor=0,_measurements={},_lcpEntry,_clsEntry;function startTrackingWebVitals({recordClsStandaloneSpans:t,recordLcpStandaloneSpans:e,client:n}){const r=getBrowserPerformanceAPI();if(r&&browserPerformanceTimeOrigin()){r.mark&&WINDOW.performance.mark("sentry-tracing-init");const i=e?trackLcpAsStandaloneSpan(n):!1===e?_trackLCP():void 0,s=t?trackClsAsStandaloneSpan(n):!1===t?_trackCLS():void 0,a=_trackTtfb(),o=_trackFpFcp();return()=>{a(),o(),i?.(),s?.()}}return()=>{}}function startTrackingLongTasks(){addPerformanceInstrumentationHandler("longtask",({entries:t})=>{const e=getActiveSpan();if(!e)return;const{op:n,start_timestamp:r}=spanToJSON(e);for(const i of t){const t=msToSec(browserPerformanceTimeOrigin()+i.startTime),s=msToSec(i.duration);"navigation"===n&&r&&t<r||startAndEndSpan(e,t,t+s,{name:"Main UI thread blocked",op:"ui.long-task",attributes:{[SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN]:"auto.ui.browser.metrics"}})}})}function startTrackingLongAnimationFrames(){new PerformanceObserver(t=>{const e=getActiveSpan();if(e)for(const n of t.getEntries()){if(!n.scripts[0])continue;const t=msToSec(browserPerformanceTimeOrigin()+n.startTime),{start_timestamp:r,op:i}=spanToJSON(e);if("navigation"===i&&r&&t<r)continue;const s=msToSec(n.duration),a={[SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN]:"auto.ui.browser.metrics"},o=n.scripts[0],{invoker:l,invokerType:c,sourceURL:d,sourceFunctionName:h,sourceCharPosition:u}=o;a["browser.script.invoker"]=l,a["browser.script.invoker_type"]=c,d&&(a["code.filepath"]=d),h&&(a["code.function"]=h),-1!==u&&(a["browser.script.source_char_position"]=u),startAndEndSpan(e,t,t+s,{name:"Main UI thread blocked",op:"ui.long-animation-frame",attributes:a})}}).observe({type:"long-animation-frame",buffered:!0})}function startTrackingInteractions(){addPerformanceInstrumentationHandler("event",({entries:t})=>{const e=getActiveSpan();if(e)for(const n of t)if("click"===n.name){const t=msToSec(browserPerformanceTimeOrigin()+n.startTime),r=msToSec(n.duration),i={name:htmlTreeAsString(n.target),op:`ui.interaction.${n.name}`,startTime:t,attributes:{[SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN]:"auto.ui.browser.metrics"}},s=getComponentName(n.target);s&&(i.attributes["ui.component_name"]=s),startAndEndSpan(e,t,t+r,i)}})}function _trackCLS(){return addClsInstrumentationHandler(({metric:t})=>{const e=t.entries[t.entries.length-1];e&&(_measurements.cls={value:t.value,unit:""},_clsEntry=e)},!0)}function _trackLCP(){return addLcpInstrumentationHandler(({metric:t})=>{const e=t.entries[t.entries.length-1];e&&isValidLcpMetric(t.value)&&(_measurements.lcp={value:t.value,unit:"millisecond"},_lcpEntry=e)},!0)}function _trackTtfb(){return addTtfbInstrumentationHandler(({metric:t})=>{t.entries[t.entries.length-1]&&(_measurements.ttfb={value:t.value,unit:"millisecond"})})}function _trackFpFcp(){return addPerformanceInstrumentationHandler("paint",({entries:t})=>{const e=getVisibilityWatcher();for(const n of t){const t=n.startTime<e.firstHiddenTime;"first-paint"===n.name&&t&&(_measurements.fp={value:n.startTime,unit:"millisecond"}),"first-contentful-paint"===n.name&&t&&(_measurements.fcp={value:n.startTime,unit:"millisecond"})}})}function addPerformanceEntries(t,e){const n=getBrowserPerformanceAPI(),r=browserPerformanceTimeOrigin();if(!n?.getEntries||!r)return;const{spanStreamingEnabled:i,ignorePerformanceApiSpans:s,ignoreResourceSpans:a}=e,o=msToSec(r),l=n.getEntries(),{op:c,start_timestamp:d}=spanToJSON(t);l.slice(_performanceCursor).forEach(e=>{const n=msToSec(e.startTime),r=msToSec(Math.max(0,e.duration));if(!("navigation"===c&&d&&o+n<d))switch(e.entryType){case"navigation":_addNavigationSpans(t,e,o);break;case"mark":case"paint":case"measure":_addMeasureSpans(t,e,n,r,o,s);break;case"resource":_addResourceSpans(t,e,e.name,n,r,o,a)}}),_performanceCursor=Math.max(l.length-1,0),_trackNavigator(t,i)}function addWebVitalsToSpan(t,e){const n=browserPerformanceTimeOrigin();if(!getBrowserPerformanceAPI()?.getEntries||!n)return void resetWebVitalState();const{spanStreamingEnabled:r,recordClsOnPageloadSpan:i,recordLcpOnPageloadSpan:s}=e,a=msToSec(n);if("pageload"===spanToJSON(t).op){if(_addTtfbRequestTimeToMeasurements(_measurements),r){const e=(e,n,r)=>{const i=r??`browser.web_vital.${e}.value`;t.setAttribute(i,n),DEBUG_BUILD$1&&debug.log("Setting web vital attribute",{[i]:n},"on pageload span")};["ttfb","fp","fcp"].forEach(t=>{_measurements[t]&&e(t,_measurements[t].value)}),_measurements["ttfb.requestTime"]&&e("ttfb.requestTime",_measurements["ttfb.requestTime"].value,"browser.web_vital.ttfb.request_time")}else i||delete _measurements.cls,s||delete _measurements.lcp,Object.entries(_measurements).forEach(([e,n])=>{setMeasurement(e,n.value,n.unit,t)}),_setWebVitalAttributes(t,e);t.setAttribute(r?"browser.performance.time_origin":"performance.timeOrigin",a),t.setAttribute(r?"browser.performance.navigation.activation_start":"performance.activationStart",getActivationStart())}resetWebVitalState()}function resetWebVitalState(){_lcpEntry=void 0,_clsEntry=void 0,_measurements={}}function isReact19MeasureEntry(t){if("measure"===t?.entryType)try{return"Components ⚛"===t.detail.devtools.track}catch{return}}function _addMeasureSpans(t,e,n,r,i,s){if(isReact19MeasureEntry(e))return;if(["mark","measure"].includes(e.entryType)&&stringMatchesSomePattern(e.name,s))return;const a=getNavigationEntry(!1),o=msToSec(a?a.requestStart:0),l=i+Math.max(n,o),c=i+n,d=c+r,h={[SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN]:"auto.resource.browser.metrics"};l!==c&&(h["sentry.browser.measure_happened_before_request"]=!0,h["sentry.browser.measure_start_time"]=l),_addDetailToSpanAttributes(h,e),l<=d&&startAndEndSpan(t,l,d,{name:e.name,op:e.entryType,attributes:h})}function _addDetailToSpanAttributes(t,e){try{const n=e.detail;if(!n)return;if("object"==typeof n){for(const[e,r]of Object.entries(n))if(r&&isPrimitive(r))t[`sentry.browser.measure.detail.${e}`]=r;else if(void 0!==r)try{t[`sentry.browser.measure.detail.${e}`]=JSON.stringify(r)}catch{}return}if(isPrimitive(n))return void(t["sentry.browser.measure.detail"]=n);try{t["sentry.browser.measure.detail"]=JSON.stringify(n)}catch{}}catch{}}function _addNavigationSpans(t,e,n){["unloadEvent","redirect","domContentLoadedEvent","loadEvent","connect"].forEach(r=>{_addPerformanceNavigationTiming(t,e,r,n)}),_addPerformanceNavigationTiming(t,e,"secureConnection",n,"TLS/SSL"),_addPerformanceNavigationTiming(t,e,"fetch",n,"cache"),_addPerformanceNavigationTiming(t,e,"domainLookup",n,"DNS"),_addRequest(t,e,n)}function _addPerformanceNavigationTiming(t,e,n,r,i=n){const s=e[_getEndPropertyNameForNavigationTiming(n)],a=e[`${n}Start`];a&&s&&startAndEndSpan(t,r+msToSec(a),r+msToSec(s),{op:`browser.${i}`,name:e.name,attributes:{[SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN]:"auto.ui.browser.metrics",..."redirect"===n&&null!=e.redirectCount?{"http.redirect_count":e.redirectCount}:{}}})}function _getEndPropertyNameForNavigationTiming(t){return"secureConnection"===t?"connectEnd":"fetch"===t?"domainLookupStart":`${t}End`}function _addRequest(t,e,n){const r=n+msToSec(e.requestStart),i=n+msToSec(e.responseEnd),s=n+msToSec(e.responseStart);e.responseEnd&&(startAndEndSpan(t,r,i,{op:"browser.request",name:e.name,attributes:{[SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN]:"auto.ui.browser.metrics"}}),startAndEndSpan(t,s,i,{op:"browser.response",name:e.name,attributes:{[SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN]:"auto.ui.browser.metrics"}}))}function _addResourceSpans(t,e,n,r,i,s,a){if("xmlhttprequest"===e.initiatorType||"fetch"===e.initiatorType)return;const o=e.initiatorType?`resource.${e.initiatorType}`:"resource.other";if(a?.includes(o))return;const l={[SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN]:"auto.resource.browser.metrics"},c=parseUrl(n);c.protocol&&(l["url.scheme"]=c.protocol.split(":").pop()),c.host&&(l["server.address"]=c.host),l["url.same_origin"]=n.includes(WINDOW.location.origin),l[Yu]=n,_setResourceRequestAttributes(e,l,[["responseStatus","http.response.status_code"],["transferSize","http.response_transfer_size"],["encodedBodySize","http.response_content_length"],["decodedBodySize","http.decoded_response_content_length"],["renderBlockingStatus","resource.render_blocking_status"],["deliveryType","http.response_delivery_type"]]);const d={...l,...resourceTimingToSpanAttributes(e)},h=s+r;startAndEndSpan(t,h,h+i,{name:n.replace(WINDOW.location.origin,""),op:o,attributes:d})}function _trackNavigator(t,e){const n=WINDOW.navigator;if(!n)return;const r=n.connection;r&&(r.effectiveType&&t.setAttribute(e?"network.connection.effective_type":"effectiveConnectionType",r.effectiveType),r.type&&t.setAttribute(e?"network.connection.type":"connectionType",r.type),isMeasurementValue(r.rtt)&&(e?t.setAttribute("network.connection.rtt",r.rtt):"pageload"===spanToJSON(t).op&&setMeasurement("connection.rtt",r.rtt,"millisecond"))),isMeasurementValue(n.deviceMemory)&&(e?t.setAttribute("device.memory.estimated_capacity",n.deviceMemory):t.setAttribute("deviceMemory",`${n.deviceMemory} GB`)),isMeasurementValue(n.hardwareConcurrency)&&(e?t.setAttribute("device.processor_count",n.hardwareConcurrency):t.setAttribute("hardwareConcurrency",String(n.hardwareConcurrency)))}function _setWebVitalAttributes(t,e){_lcpEntry&&e.recordLcpOnPageloadSpan&&(_lcpEntry.element&&t.setAttribute("lcp.element",htmlTreeAsString(_lcpEntry.element)),_lcpEntry.id&&t.setAttribute("lcp.id",_lcpEntry.id),_lcpEntry.url&&t.setAttribute("lcp.url",_lcpEntry.url.trim().slice(0,200)),null!=_lcpEntry.loadTime&&t.setAttribute("lcp.loadTime",_lcpEntry.loadTime),null!=_lcpEntry.renderTime&&t.setAttribute("lcp.renderTime",_lcpEntry.renderTime),t.setAttribute("lcp.size",_lcpEntry.size)),_clsEntry?.sources&&e.recordClsOnPageloadSpan&&_clsEntry.sources.forEach((e,n)=>t.setAttribute(`cls.source.${n+1}`,htmlTreeAsString(e.node)))}function _setResourceRequestAttributes(t,e,n){n.forEach(([n,r])=>{const i=t[n];null!=i&&("number"==typeof i&&i<MAX_INT_AS_BYTES||"string"==typeof i)&&(e[r]=i)})}function _addTtfbRequestTimeToMeasurements(t){const e=getNavigationEntry(!1);if(!e)return;const{responseStart:n,requestStart:r}=e;r<=n&&(t["ttfb.requestTime"]={value:n-r,unit:"millisecond"})}const LAST_INTERACTIONS=[],INTERACTIONS_SPAN_MAP=/* @__PURE__ */new Map,ELEMENT_NAME_TIMESTAMP_MAP=/* @__PURE__ */new Map,MAX_PLAUSIBLE_INP_DURATION=60;function startTrackingINP(){if(getBrowserPerformanceAPI()&&browserPerformanceTimeOrigin()){const t=_trackINP();return()=>{t()}}return()=>{}}const INP_ENTRY_MAP={click:"click",pointerdown:"click",pointerup:"click",mousedown:"click",mouseup:"click",touchstart:"click",touchend:"click",mouseover:"hover",mouseout:"hover",mouseenter:"hover",mouseleave:"hover",pointerover:"hover",pointerout:"hover",pointerenter:"hover",pointerleave:"hover",dragstart:"drag",dragend:"drag",drag:"drag",dragenter:"drag",dragleave:"drag",dragover:"drag",drop:"drag",keydown:"press",keyup:"press",keypress:"press",input:"press"};function _trackINP(){return addInpInstrumentationHandler(_onInp)}const _onInp=({metric:t})=>{if(null==t.value)return;const e=msToSec(t.value);if(e>MAX_PLAUSIBLE_INP_DURATION)return;const n=t.entries.find(e=>e.duration===t.value&&INP_ENTRY_MAP[e.name]);if(!n)return;const{interactionId:r}=n,i=INP_ENTRY_MAP[n.name],s=msToSec(browserPerformanceTimeOrigin()+n.startTime),a=getActiveSpan(),o=a?getRootSpan(a):void 0,l=null!=r?INTERACTIONS_SPAN_MAP.get(r):void 0,c=l?.span||o,d=c?spanToJSON(c).description:getCurrentScope().getScopeData().transactionName,h=startStandaloneWebVitalSpan({name:l?.elementName||htmlTreeAsString(n.target),transaction:d,attributes:{[SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN]:"auto.http.browser.inp",[SEMANTIC_ATTRIBUTE_SENTRY_OP]:`ui.interaction.${i}`,[SEMANTIC_ATTRIBUTE_EXCLUSIVE_TIME]:n.duration},startTime:s});h&&(h.addEvent("inp",{[SEMANTIC_ATTRIBUTE_SENTRY_MEASUREMENT_UNIT]:"millisecond",[SEMANTIC_ATTRIBUTE_SENTRY_MEASUREMENT_VALUE]:t.value}),h.end(s+e))};function getCachedInteractionContext(t){return null!=t?INTERACTIONS_SPAN_MAP.get(t):void 0}function registerInpInteractionListener(){const t=Object.keys(INP_ENTRY_MAP);function e(t){const e=t.target;if(!e)return;const n=htmlTreeAsString(e),r=Math.round(t.timeStamp);if(ELEMENT_NAME_TIMESTAMP_MAP.set(r,n),ELEMENT_NAME_TIMESTAMP_MAP.size>50){const t=ELEMENT_NAME_TIMESTAMP_MAP.keys().next().value;void 0!==t&&ELEMENT_NAME_TIMESTAMP_MAP.delete(t)}}isBrowser()&&t.forEach(t=>{WINDOW.addEventListener(t,e,{capture:!0,passive:!0})});const n=({entries:t})=>{const e=getActiveSpan(),n=e&&getRootSpan(e);t.forEach(t=>{if(!isPerformanceEventTiming(t))return;const e=t.interactionId;if(null==e)return;if(INTERACTIONS_SPAN_MAP.has(e))return;const r=t.target?htmlTreeAsString(t.target):function(t){const e=Math.round(t.startTime);let n=ELEMENT_NAME_TIMESTAMP_MAP.get(e);if(!n)for(let t=-5;t<=5;t++){const r=ELEMENT_NAME_TIMESTAMP_MAP.get(e+t);if(r){n=r;break}}return n||"<unknown>"}(t);if(LAST_INTERACTIONS.length>10){const t=LAST_INTERACTIONS.shift();INTERACTIONS_SPAN_MAP.delete(t)}LAST_INTERACTIONS.push(e),INTERACTIONS_SPAN_MAP.set(e,{span:n,elementName:r})})};addPerformanceInstrumentationHandler("event",n),addPerformanceInstrumentationHandler("first-input",n)}function _emitWebVitalSpan(t){const{name:e,op:n,origin:r,metricName:i,value:s,attributes:a,parentSpan:o,reportEvent:l,startTime:c,endTime:d}=t,h=getCurrentScope().getScopeData().transactionName,u={[SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN]:r,[SEMANTIC_ATTRIBUTE_SENTRY_OP]:n,[SEMANTIC_ATTRIBUTE_EXCLUSIVE_TIME]:0,[`browser.web_vital.${i}.value`]:s,[Xc]:h,[Lc]:h,"user_agent.original":WINDOW.navigator?.userAgent,...a};o&&"pageload"===spanToStreamedSpanJSON(o).attributes?.[SEMANTIC_ATTRIBUTE_SENTRY_OP]&&(u["sentry.pageload.span_id"]=o.spanContext().spanId),l&&(u[`browser.web_vital.${i}.report_event`]=l);const p=startInactiveSpan({name:e,attributes:u,startTime:c,parentSpan:o});p&&p.end(d??c)}function trackLcpAsSpan(t){let e,n=0;if(!supportsWebVital("largest-contentful-paint"))return;const r=addLcpInstrumentationHandler(({metric:t})=>{const r=t.entries[t.entries.length-1];r&&isValidLcpMetric(t.value)&&(n=t.value,e=r)},!0);listenForWebVitalReportEvents(t,(t,i,s)=>{_sendLcpSpan(n,e,s,t),r()})}function _sendLcpSpan(t,e,n,r){if(!isValidLcpMetric(t))return;DEBUG_BUILD$1&&debug.log(`Sending LCP span (${t})`);const i=browserPerformanceTimeOrigin()||0,s=msToSec(i),a=msToSec(i+(e?.startTime||0)),o=e?htmlTreeAsString(e.element):"Largest contentful paint",l={};e?.element&&(l["browser.web_vital.lcp.element"]=htmlTreeAsString(e.element)),e?.id&&(l["browser.web_vital.lcp.id"]=e.id),e?.url&&(l["browser.web_vital.lcp.url"]=e.url),null!=e?.loadTime&&(l["browser.web_vital.lcp.load_time"]=e.loadTime),null!=e?.renderTime&&(l["browser.web_vital.lcp.render_time"]=e.renderTime),null!=e?.size&&(l["browser.web_vital.lcp.size"]=e.size),_emitWebVitalSpan({name:o,op:"ui.webvital.lcp",origin:"auto.http.browser.lcp",metricName:"lcp",value:t,attributes:l,parentSpan:n,reportEvent:r,startTime:s,endTime:a})}function trackClsAsSpan(t){let e,n=0;if(!supportsWebVital("layout-shift"))return;const r=addClsInstrumentationHandler(({metric:t})=>{const r=t.entries[t.entries.length-1];r&&(n=t.value,e=r)},!0);listenForWebVitalReportEvents(t,(t,i,s)=>{_sendClsSpan(n,e,s,t),r()})}function _sendClsSpan(t,e,n,r){DEBUG_BUILD$1&&debug.log(`Sending CLS span (${t})`);const i=e?msToSec((browserPerformanceTimeOrigin()||0)+e.startTime):timestampInSeconds(),s=e?htmlTreeAsString(e.sources[0]?.node):"Layout shift",a={};e?.sources&&e.sources.forEach((t,e)=>{a[`browser.web_vital.cls.source.${e+1}`]=htmlTreeAsString(t.node)}),_emitWebVitalSpan({name:s,op:"ui.webvital.cls",origin:"auto.http.browser.cls",metricName:"cls",value:t,attributes:a,parentSpan:n,reportEvent:r,startTime:i})}function trackInpAsSpan(){getBrowserPerformanceAPI()&&browserPerformanceTimeOrigin()&&addInpInstrumentationHandler(({metric:t})=>{if(null==t.value)return;if(msToSec(t.value)>MAX_PLAUSIBLE_INP_DURATION)return;const e=t.entries.find(e=>e.duration===t.value&&INP_ENTRY_MAP[e.name]);e&&_sendInpSpan(t.value,e)})}function _sendInpSpan(t,e){DEBUG_BUILD$1&&debug.log(`Sending INP span (${t})`);const n=msToSec(browserPerformanceTimeOrigin()+e.startTime),r=msToSec(t),i=INP_ENTRY_MAP[e.name],s=getCachedInteractionContext(e.interactionId),a=getActiveSpan(),o=a?getRootSpan(a):void 0,l=s?.span||o,c=l?spanToStreamedSpanJSON(l).name:getCurrentScope().getScopeData().transactionName;_emitWebVitalSpan({name:s?.elementName||htmlTreeAsString(e.target),op:`ui.interaction.${i}`,origin:"auto.http.browser.inp",metricName:"inp",value:t,attributes:{[SEMANTIC_ATTRIBUTE_EXCLUSIVE_TIME]:e.duration,[Xc]:c,[Lc]:c},startTime:n,endTime:n+r,parentSpan:l})}const DEBOUNCE_DURATION=1e3;let debounceTimerID,lastCapturedEventType,lastCapturedEventTargetId,lastHref;function addClickKeypressInstrumentationHandler(t){addHandler$1("dom",t),maybeInstrument("dom",instrumentDOM)}function instrumentDOM(){if(!WINDOW.document)return;const t=triggerHandlers$1.bind(null,"dom"),e=makeDOMEventHandler(t,!0);WINDOW.document.addEventListener("click",e,!1),WINDOW.document.addEventListener("keypress",e,!1),["EventTarget","Node"].forEach(e=>{const n=WINDOW,r=n[e]?.prototype;r?.hasOwnProperty?.("addEventListener")&&(fill(r,"addEventListener",function(e){return function(n,r,i){if("click"===n||"keypress"==n)try{const r=this.__sentry_instrumentation_handlers__=this.__sentry_instrumentation_handlers__||{},s=r[n]=r[n]||{refCount:0};if(!s.handler){const r=makeDOMEventHandler(t);s.handler=r,e.call(this,n,r,i)}s.refCount++}catch{}return e.call(this,n,r,i)}}),fill(r,"removeEventListener",function(t){return function(e,n,r){if("click"===e||"keypress"==e)try{const n=this.__sentry_instrumentation_handlers__||{},i=n[e];i&&(i.refCount--,i.refCount<=0&&(t.call(this,e,i.handler,r),i.handler=void 0,delete n[e]),0===Object.keys(n).length&&delete this.__sentry_instrumentation_handlers__)}catch{}return t.call(this,e,n,r)}}))})}function isSimilarToLastCapturedEvent(t){if(t.type!==lastCapturedEventType)return!1;try{if(!t.target||t.target._sentryId!==lastCapturedEventTargetId)return!1}catch{}return!0}function shouldSkipDOMEvent(t,e){return"keypress"===t&&(!e?.tagName||"INPUT"!==e.tagName&&"TEXTAREA"!==e.tagName&&!e.isContentEditable)}function makeDOMEventHandler(t,e=!1){return n=>{if(!n||n._sentryCaptured)return;const r=getEventTarget(n);if(shouldSkipDOMEvent(n.type,r))return;addNonEnumerableProperty(n,"_sentryCaptured",!0),r&&!r._sentryId&&addNonEnumerableProperty(r,"_sentryId",uuid4());const i="keypress"===n.type?"input":n.type;isSimilarToLastCapturedEvent(n)||(t({event:n,name:i,global:e}),lastCapturedEventType=n.type,lastCapturedEventTargetId=r?r._sentryId:void 0),clearTimeout(debounceTimerID),debounceTimerID=WINDOW.setTimeout(()=>{lastCapturedEventTargetId=void 0,lastCapturedEventType=void 0},DEBOUNCE_DURATION)}}function getEventTarget(t){try{return t.target}catch{return null}}function addHistoryInstrumentationHandler(t){const e="history";addHandler$1(e,t),maybeInstrument(e,instrumentHistory)}function instrumentHistory(){function t(t){return function(...e){const n=e.length>2?e[2]:void 0;if(n){const r=lastHref,i=getAbsoluteUrl(String(n));if(lastHref=i,r===i)return t.apply(this,e);triggerHandlers$1("history",{from:r,to:i})}return t.apply(this,e)}}WINDOW.addEventListener("popstate",()=>{const t=WINDOW.location.href,e=lastHref;lastHref=t,e!==t&&triggerHandlers$1("history",{from:e,to:t})}),supportsHistory()&&(fill(WINDOW.history,"pushState",t),fill(WINDOW.history,"replaceState",t))}function getAbsoluteUrl(t){try{return new URL(t,WINDOW.location.origin).toString()}catch{return t}}const cachedImplementations={};function getNativeImplementation(t){const e=cachedImplementations[t];if(e)return e;let n=WINDOW[t];if(isNativeFunction(n))return cachedImplementations[t]=n.bind(WINDOW);const r=WINDOW.document;if(r&&"function"==typeof r.createElement)try{const e=r.createElement("iframe");e.hidden=!0,r.head.appendChild(e);const i=e.contentWindow;i?.[t]&&(n=i[t]),r.head.removeChild(e)}catch(e){DEBUG_BUILD$1&&debug.warn(`Could not create sandbox iframe for ${t} check, bailing to window.${t}: `,e)}return n?cachedImplementations[t]=n.bind(WINDOW):n}function clearCachedImplementation(t){cachedImplementations[t]=void 0}const SENTRY_XHR_DATA_KEY="__sentry_xhr_v3__";function addXhrInstrumentationHandler(t){addHandler$1("xhr",t),maybeInstrument("xhr",instrumentXHR)}function instrumentXHR(){if(!WINDOW.XMLHttpRequest)return;const t=XMLHttpRequest.prototype;t.open=new Proxy(t.open,{apply(t,e,n){const r=new Error,i=1e3*timestampInSeconds(),s=isString(n[0])?n[0].toUpperCase():void 0,a=parseXhrUrlArg(n[1]);if(!s||!a)return t.apply(e,n);e[SENTRY_XHR_DATA_KEY]={method:s,url:a,request_headers:{}},"POST"===s&&a.match(/sentry_key/)&&(e.__sentry_own_request__=!0);const o=()=>{const t=e[SENTRY_XHR_DATA_KEY];if(t&&4===e.readyState){try{t.status_code=e.status}catch{}triggerHandlers$1("xhr",{endTimestamp:1e3*timestampInSeconds(),startTimestamp:i,xhr:e,virtualError:r}),e.removeEventListener("readystatechange",o)}};return"onreadystatechange"in e&&"function"==typeof e.onreadystatechange?e.onreadystatechange=new Proxy(e.onreadystatechange,{apply:(t,e,n)=>(o(),t.apply(e,n))}):e.addEventListener("readystatechange",o),e.setRequestHeader=new Proxy(e.setRequestHeader,{apply(t,e,n){const[r,i]=n,s=e[SENTRY_XHR_DATA_KEY];return s&&isString(r)&&isString(i)&&(s.request_headers[r.toLowerCase()]=i),t.apply(e,n)}}),t.apply(e,n)}}),t.send=new Proxy(t.send,{apply(t,e,n){const r=e[SENTRY_XHR_DATA_KEY];return r?(void 0!==n[0]&&(r.body=n[0]),triggerHandlers$1("xhr",{startTimestamp:1e3*timestampInSeconds(),xhr:e}),t.apply(e,n)):t.apply(e,n)}})}function parseXhrUrlArg(t){if(isString(t))return t;try{return t.toString()}catch{}}function parseXhrResponseHeaders(t){let e;try{e=t.getAllResponseHeaders()}catch(e){return DEBUG_BUILD$1&&debug.error(e,"Failed to get xhr response headers",t),{}}return e?e.split("\r\n").reduce((t,e)=>{const[n,r]=e.split(": ");return r&&(t[n.toLowerCase()]=r),t},{}):{}}const DEFAULT_BROWSER_TRANSPORT_BUFFER_SIZE=40;function makeFetchTransport(t,e=getNativeImplementation("fetch")){let n=0,r=0;return createTransport(t,async function(i){const s=i.body.length;n+=s,r++;const a={body:i.body,method:"POST",referrerPolicy:"strict-origin",headers:t.headers,keepalive:n<=6e4&&r<15,...t.fetchOptions};try{const n=await e(t.url,a);return{statusCode:n.status,headers:{"x-sentry-rate-limits":n.headers.get("X-Sentry-Rate-Limits"),"retry-after":n.headers.get("Retry-After")}}}catch(t){throw clearCachedImplementation("fetch"),t}finally{n-=s,r--}},makePromiseBuffer(t.bufferSize||DEFAULT_BROWSER_TRANSPORT_BUFFER_SIZE))}const DEBUG_BUILD="undefined"==typeof __SENTRY_DEBUG__||__SENTRY_DEBUG__,CHROME_PRIORITY=30,GECKO_PRIORITY=50;function createFrame(t,e,n,r){const i={filename:t,function:"<anonymous>"===e?UNKNOWN_FUNCTION:e,in_app:!0};return void 0!==n&&(i.lineno=n),void 0!==r&&(i.colno=r),i}const chromeRegexNoFnName=/^\s*at (\S+?)(?::(\d+))(?::(\d+))\s*$/i,chromeRegex=/^\s*at (?:(.+?\)(?: \[.+\])?|.*?) ?\((?:address at )?)?(?:async )?((?:<anonymous>|[-a-z]+:|.*bundle|\/)?.*?)(?::(\d+))?(?::(\d+))?\)?\s*$/i,chromeEvalRegex=/\((\S*)(?::(\d+))(?::(\d+))\)/,chromeDataUriRegex=/at (.+?) ?\(data:(.+?),/,chromeStackParserFn=t=>{const e=t.match(chromeDataUriRegex);if(e)return{filename:`<data:${e[2]}>`,function:e[1]};const n=chromeRegexNoFnName.exec(t);if(n){const[,t,e,r]=n;return createFrame(t,UNKNOWN_FUNCTION,+e,+r)}const r=chromeRegex.exec(t);if(r){if(0===r[2]?.indexOf("eval")){const t=chromeEvalRegex.exec(r[2]);t&&(r[2]=t[1],r[3]=t[2],r[4]=t[3])}const[t,e]=extractSafariExtensionDetails(r[1]||UNKNOWN_FUNCTION,r[2]);return createFrame(e,t,r[3]?+r[3]:void 0,r[4]?+r[4]:void 0)}},chromeStackLineParser=[CHROME_PRIORITY,chromeStackParserFn],geckoREgex=/^\s*(.*?)(?:\((.*?)\))?(?:^|@)?((?:[-a-z]+)?:\/.*?|\[native code\]|[^@]*(?:bundle|\d+\.js)|\/[\w\-. /=]+)(?::(\d+))?(?::(\d+))?\s*$/i,geckoEvalRegex=/(\S+) line (\d+)(?: > eval line \d+)* > eval/i,gecko=t=>{const e=geckoREgex.exec(t);if(e){if(e[3]&&e[3].indexOf(" > eval")>-1){const t=geckoEvalRegex.exec(e[3]);t&&(e[1]=e[1]||"eval",e[3]=t[1],e[4]=t[2],e[5]="")}let t=e[3],n=e[1]||UNKNOWN_FUNCTION;return[n,t]=extractSafariExtensionDetails(n,t),createFrame(t,n,e[4]?+e[4]:void 0,e[5]?+e[5]:void 0)}},geckoStackLineParser=[GECKO_PRIORITY,gecko],defaultStackLineParsers=[chromeStackLineParser,geckoStackLineParser],defaultStackParser=createStackParser(...defaultStackLineParsers),extractSafariExtensionDetails=(t,e)=>{const n=-1!==t.indexOf("safari-extension"),r=-1!==t.indexOf("safari-web-extension");return n||r?[-1!==t.indexOf("@")?t.split("@")[0]:UNKNOWN_FUNCTION,n?`safari-extension:${e}`:`safari-web-extension:${e}`]:[t,e]},MAX_ALLOWED_STRING_LENGTH=1024,INTEGRATION_NAME$4="Breadcrumbs",_breadcrumbsIntegration=(t={})=>{const e={console:!0,dom:!0,fetch:!0,history:!0,sentry:!0,xhr:!0,...t};return{name:INTEGRATION_NAME$4,setup(t){e.console&&addConsoleInstrumentationHandler(_getConsoleBreadcrumbHandler(t)),e.dom&&addClickKeypressInstrumentationHandler(_getDomBreadcrumbHandler(t,e.dom)),e.xhr&&addXhrInstrumentationHandler(_getXhrBreadcrumbHandler(t)),e.fetch&&addFetchInstrumentationHandler(_getFetchBreadcrumbHandler(t)),e.history&&addHistoryInstrumentationHandler(_getHistoryBreadcrumbHandler(t)),e.sentry&&t.on("beforeSendEvent",_getSentryBreadcrumbHandler(t))}}},breadcrumbsIntegration=defineIntegration(_breadcrumbsIntegration);function _getSentryBreadcrumbHandler(t){return function(e){getClient()===t&&addBreadcrumb({category:"sentry."+("transaction"===e.type?"transaction":"event"),event_id:e.event_id,level:e.level,message:getEventDescription(e)},{event:e})}}function _getDomBreadcrumbHandler(t,e){return function(n){if(getClient()!==t)return;let r,i,s="object"==typeof e?e.serializeAttribute:void 0,a="object"==typeof e&&"number"==typeof e.maxStringLength?e.maxStringLength:void 0;a&&a>MAX_ALLOWED_STRING_LENGTH&&(DEBUG_BUILD&&debug.warn(`\`dom.maxStringLength\` cannot exceed ${MAX_ALLOWED_STRING_LENGTH}, but a value of ${a} was configured. Sentry will use ${MAX_ALLOWED_STRING_LENGTH} instead.`),a=MAX_ALLOWED_STRING_LENGTH),"string"==typeof s&&(s=[s]);try{const t=n.event,e=_isEvent(t)?t.target:t;r=htmlTreeAsString(e,{keyAttrs:s,maxStringLength:a}),i=getComponentName(e)}catch{r="<unknown>"}if(0===r.length)return;const o={category:`ui.${n.name}`,message:r};i&&(o.data={"ui.component_name":i}),addBreadcrumb(o,{event:n.event,name:n.name,global:n.global})}}function _getConsoleBreadcrumbHandler(t){return function(e){if(getClient()!==t)return;const n={category:"console",data:{arguments:e.args,logger:"console"},level:severityLevelFromString(e.level),message:safeJoin(e.args," ")};if("assert"===e.level){if(!1!==e.args[0])return;n.message=`Assertion failed: ${safeJoin(e.args.slice(1)," ")||"console.assert"}`,n.data.arguments=e.args.slice(1)}addBreadcrumb(n,{input:e.args,level:e.level})}}function _getXhrBreadcrumbHandler(t){return function(e){if(getClient()!==t)return;const{startTimestamp:n,endTimestamp:r}=e,i=e.xhr[SENTRY_XHR_DATA_KEY];if(!n||!r||!i)return;const{method:s,url:a,status_code:o,body:l}=i,c={xhr:e.xhr,input:l,startTimestamp:n,endTimestamp:r},d={category:"xhr",data:{method:s,url:a,status_code:o},type:"http",level:getBreadcrumbLogLevelFromHttpStatusCode(o)};t.emit("beforeOutgoingRequestBreadcrumb",d,c),addBreadcrumb(d,c)}}function _getFetchBreadcrumbHandler(t){return function(e){if(getClient()!==t)return;const{startTimestamp:n,endTimestamp:r}=e;if(r&&(!e.fetchData.url.match(/sentry_key/)||"POST"!==e.fetchData.method))if(e.error){const i={data:e.error,input:e.args,startTimestamp:n,endTimestamp:r},s={category:"fetch",data:e.fetchData,level:"error",type:"http"};t.emit("beforeOutgoingRequestBreadcrumb",s,i),addBreadcrumb(s,i)}else{const i=e.response,s={...e.fetchData,status_code:i?.status},a={input:e.args,response:i,startTimestamp:n,endTimestamp:r},o={category:"fetch",data:s,type:"http",level:getBreadcrumbLogLevelFromHttpStatusCode(s.status_code)};t.emit("beforeOutgoingRequestBreadcrumb",o,a),addBreadcrumb(o,a)}}}function _getHistoryBreadcrumbHandler(t){return function(e){if(getClient()!==t)return;let n=e.from,r=e.to;const i=parseUrl(WINDOW$1.location.href);let s=n?parseUrl(n):void 0;const a=parseUrl(r);s?.path||(s=i),i.protocol===a.protocol&&i.host===a.host&&(r=a.relative),i.protocol===s.protocol&&i.host===s.host&&(n=s.relative),addBreadcrumb({category:"navigation",data:{from:n,to:r}})}}function _isEvent(t){return!!t&&!!t.target}const DEFAULT_EVENT_TARGET="EventTarget,Window,Node,ApplicationCache,AudioTrackList,BroadcastChannel,ChannelMergerNode,CryptoOperation,EventSource,FileReader,HTMLUnknownElement,IDBDatabase,IDBRequest,IDBTransaction,KeyOperation,MediaController,MessagePort,ModalWindow,Notification,SVGElementInstance,Screen,SharedWorker,TextTrack,TextTrackCue,TextTrackList,WebSocket,WebSocketWorker,Worker,XMLHttpRequest,XMLHttpRequestEventTarget,XMLHttpRequestUpload".split(","),INTEGRATION_NAME$3="BrowserApiErrors",_browserApiErrorsIntegration=(t={})=>{const e={XMLHttpRequest:!0,eventTarget:!0,requestAnimationFrame:!0,setInterval:!0,setTimeout:!0,unregisterOriginalCallbacks:!1,...t};return{name:INTEGRATION_NAME$3,setupOnce(){e.setTimeout&&fill(WINDOW$1,"setTimeout",_wrapTimeFunction),e.setInterval&&fill(WINDOW$1,"setInterval",_wrapTimeFunction),e.requestAnimationFrame&&fill(WINDOW$1,"requestAnimationFrame",_wrapRAF),e.XMLHttpRequest&&"XMLHttpRequest"in WINDOW$1&&fill(XMLHttpRequest.prototype,"send",_wrapXHR);const t=e.eventTarget;t&&(Array.isArray(t)?t:DEFAULT_EVENT_TARGET).forEach(t=>_wrapEventTarget(t,e))}}},browserApiErrorsIntegration=defineIntegration(_browserApiErrorsIntegration);function _wrapTimeFunction(t){return function(...e){return e[0]=wrap(e[0],{mechanism:{handled:!1,type:`auto.browser.browserapierrors.${getFunctionName(t)}`}}),t.apply(this,e)}}function _wrapRAF(t){return function(e){return t.apply(this,[wrap(e,{mechanism:{data:{handler:getFunctionName(t)},handled:!1,type:"auto.browser.browserapierrors.requestAnimationFrame"}})])}}function _wrapXHR(t){return function(...e){const n=this;return["onload","onerror","onprogress","onreadystatechange"].forEach(t=>{t in n&&"function"==typeof n[t]&&fill(n,t,function(e){const n={mechanism:{data:{handler:getFunctionName(e)},handled:!1,type:`auto.browser.browserapierrors.xhr.${t}`}},r=getOriginalFunction(e);return r&&(n.mechanism.data.handler=getFunctionName(r)),wrap(e,n)})}),t.apply(this,e)}}function _wrapEventTarget(t,e){const n=WINDOW$1,r=n[t]?.prototype;r?.hasOwnProperty?.("addEventListener")&&(fill(r,"addEventListener",function(n){return function(r,i,s){try{isEventListenerObject(i)&&(i.handleEvent=wrap(i.handleEvent,{mechanism:{data:{handler:getFunctionName(i),target:t},handled:!1,type:"auto.browser.browserapierrors.handleEvent"}}))}catch{}return e.unregisterOriginalCallbacks&&unregisterOriginalCallback(this,r,i),n.apply(this,[r,wrap(i,{mechanism:{data:{handler:getFunctionName(i),target:t},handled:!1,type:"auto.browser.browserapierrors.addEventListener"}}),s])}}),fill(r,"removeEventListener",function(t){return function(e,n,r){try{if(Object.prototype.hasOwnProperty.call(n,"__sentry_wrapped__")){const i=n.__sentry_wrapped__;i&&t.call(this,e,i,r)}}catch{}return t.call(this,e,n,r)}}))}function isEventListenerObject(t){return"function"==typeof t.handleEvent}function unregisterOriginalCallback(t,e,n){t&&"object"==typeof t&&"removeEventListener"in t&&"function"==typeof t.removeEventListener&&t.removeEventListener(e,n)}const browserSessionIntegration=defineIntegration((t={})=>{const e=t.lifecycle??"route";return{name:"BrowserSession",setupOnce(){if(void 0===WINDOW$1.document)return void(DEBUG_BUILD&&debug.warn("Using the `browserSessionIntegration` in non-browser environments is not supported."));startSession({ignoreDuration:!0});let t=!1;whenIdleOrHidden(()=>{t||(captureSession(),t=!0)});const n=getIsolationScope();let r=n.getUser();n.addScopeListener(e=>{const n=e.getUser();r?.id===n?.id&&r?.ip_address===n?.ip_address||(r=n,t&&captureSession())}),"route"===e&&addHistoryInstrumentationHandler(({from:e,to:n})=>{e!==n&&(startSession({ignoreDuration:!0}),captureSession(),t=!0)})}}}),INTEGRATION_NAME$2="CultureContext",_cultureContextIntegration=()=>({name:INTEGRATION_NAME$2,preprocessEvent(t){const e=getCultureContext();e&&(t.contexts={...t.contexts,culture:{...e,...t.contexts?.culture}})},processSegmentSpan(t){const e=getCultureContext();e&&safeSetSpanJSONAttributes(t,{"culture.locale":e.locale,"culture.timezone":e.timezone,"culture.calendar":e.calendar})}}),cultureContextIntegration=defineIntegration(_cultureContextIntegration);function getCultureContext(){try{const t=WINDOW$1.Intl;if(!t)return;const e=t.DateTimeFormat().resolvedOptions();return{locale:e.locale,timezone:e.timeZone,calendar:e.calendar}}catch{return}}const INTEGRATION_NAME$1="GlobalHandlers",_globalHandlersIntegration=(t={})=>{const e={onerror:!0,onunhandledrejection:!0,...t};return{name:INTEGRATION_NAME$1,setupOnce(){Error.stackTraceLimit=50},setup(t){e.onerror&&(_installGlobalOnErrorHandler(t),globalHandlerLog("onerror")),e.onunhandledrejection&&(_installGlobalOnUnhandledRejectionHandler(t),globalHandlerLog("onunhandledrejection"))}}},globalHandlersIntegration=defineIntegration(_globalHandlersIntegration);function _installGlobalOnErrorHandler(t){addGlobalErrorInstrumentationHandler(e=>{const{stackParser:n,attachStacktrace:r}=getOptions();if(getClient()!==t||shouldIgnoreOnError())return;const{msg:i,url:s,line:a,column:o,error:l}=e,c=_enhanceEventWithInitialFrame(eventFromUnknownInput(n,l||i,void 0,r,!1),s,a,o);c.level="error",captureEvent(c,{originalException:l,mechanism:{handled:!1,type:"auto.browser.global_handlers.onerror"}})})}function _installGlobalOnUnhandledRejectionHandler(t){addGlobalUnhandledRejectionInstrumentationHandler(e=>{const{stackParser:n,attachStacktrace:r}=getOptions();if(getClient()!==t||shouldIgnoreOnError())return;const i=_getUnhandledRejectionError(e),s=isPrimitive(i)?_eventFromRejectionWithPrimitive(i):eventFromUnknownInput(n,i,void 0,r,!0);s.level="error",captureEvent(s,{originalException:i,mechanism:{handled:!1,type:"auto.browser.global_handlers.onunhandledrejection"}})})}function _getUnhandledRejectionError(t){if(isPrimitive(t))return t;try{if("reason"in t)return t.reason;if("detail"in t&&"reason"in t.detail)return t.detail.reason}catch{}return t}function _eventFromRejectionWithPrimitive(t){return{exception:{values:[{type:"UnhandledRejection",value:`Non-Error promise rejection captured with value: ${String(t)}`}]}}}function _enhanceEventWithInitialFrame(t,e,n,r){const i=t.exception=t.exception||{},s=i.values=i.values||[],a=s[0]=s[0]||{},o=a.stacktrace=a.stacktrace||{},l=o.frames=o.frames||[];return 0===l.length&&l.push({colno:r,lineno:n,filename:getFilenameFromUrl(e)??getLocationHref(),function:UNKNOWN_FUNCTION,in_app:!0}),t}function globalHandlerLog(t){DEBUG_BUILD&&debug.log(`Global Handler attached: ${t}`)}function getOptions(){const t=getClient();return t?.getOptions()||{stackParser:()=>[],attachStacktrace:!1}}function getFilenameFromUrl(t){if(isString(t)&&0!==t.length)return t.startsWith("data:")?`<${stripDataUrlContent(t,!1)}>`:t}const httpContextIntegration=defineIntegration(()=>({name:"HttpContext",preprocessEvent(t){if(!WINDOW$1.navigator&&!WINDOW$1.location&&!WINDOW$1.document)return;const e=getHttpRequestData(),n={...e.headers,...t.request?.headers};t.request={...e,...t.request,headers:n}},processSegmentSpan(t){const e=t.attributes?.[SEMANTIC_ATTRIBUTE_SENTRY_OP];if(!WINDOW$1.navigator&&!WINDOW$1.location&&!WINDOW$1.document)return;const n=getHttpRequestData();safeSetSpanJSONAttributes(t,{[Yu]:"http.client"!==e?n.url:void 0,"http.request.header.user_agent":n.headers["User-Agent"],"http.request.header.referer":n.headers.Referer})}})),DEFAULT_KEY="cause",DEFAULT_LIMIT=5,INTEGRATION_NAME="LinkedErrors",_linkedErrorsIntegration=(t={})=>{const e=t.limit||DEFAULT_LIMIT,n=t.key||DEFAULT_KEY;return{name:INTEGRATION_NAME,preprocessEvent(t,r,i){applyAggregateErrorsToEvent(exceptionFromError,i.getOptions().stackParser,n,e,t,r)}}},linkedErrorsIntegration=defineIntegration(_linkedErrorsIntegration);function getDefaultIntegrations(t){return[inboundFiltersIntegration(),functionToStringIntegration(),conversationIdIntegration(),browserApiErrorsIntegration(),breadcrumbsIntegration(),globalHandlersIntegration(),linkedErrorsIntegration(),dedupeIntegration(),httpContextIntegration(),cultureContextIntegration(),browserSessionIntegration()]}function baggageHeaderHasSentryValues(t){return t.split(",").some(t=>t.trim().startsWith("sentry-"))}function getFullURL(t){try{return new URL(t,WINDOW$1.location.origin).href}catch{return}}function isPerformanceResourceTiming(t){return"resource"===t.entryType&&"initiatorType"in t&&"string"==typeof t.nextHopProtocol&&("fetch"===t.initiatorType||"xmlhttprequest"===t.initiatorType)}function createHeadersSafely(t){try{return new Headers(t)}catch{return}}const defaultRequestInstrumentationOptions={traceFetch:!0,traceXHR:!0,enableHTTPTimings:!0,trackFetchStreamPerformance:!1};function instrumentOutgoingRequests(t,e){const{traceFetch:n,traceXHR:r,shouldCreateSpanForRequest:i,enableHTTPTimings:s,tracePropagationTargets:a,onRequestSpanStart:o,onRequestSpanEnd:l}={...defaultRequestInstrumentationOptions,...e},c="function"==typeof i?i:t=>!0,d=t=>shouldAttachHeaders(t,a),h={},u=t.getOptions().propagateTraceparent;n&&addFetchInstrumentationHandler(e=>{const n=instrumentFetchRequest(e,c,d,h,{propagateTraceparent:u,onRequestSpanEnd:l});if(n){const r=getFullURL(e.fetchData.url),i=r?parseUrl(r).host:void 0,a=r?stripDataUrlContent(r):void 0;n.setAttributes({[ws]:a,[Yu]:a,"server.address":i}),s&&addHTTPTimings(n,t),o?.(n,{headers:e.headers})}}),r&&addXhrInstrumentationHandler(e=>{const n=xhrCallback(e,c,d,h,u,l);n&&(s&&addHTTPTimings(n,t),o?.(n,{headers:createHeadersSafely(e.xhr.__sentry_xhr_v3__?.request_headers)}))})}const HTTP_TIMING_WAIT_MS=300;function addHTTPTimings(t,e){const{url:n}=spanToJSON(t).data;if(!n||"string"!=typeof n)return;let r=()=>{setTimeout(i)};if(hasSpanStreamingEnabled(e)){const e=t.end.bind(t);t.end=t=>{const n=t??timestampInSeconds();let s=!1;const a=()=>{s||(s=!0,setTimeout(i),e(n),clearTimeout(o))};r=a;const o=setTimeout(a,HTTP_TIMING_WAIT_MS)}}const i=addPerformanceInstrumentationHandler("resource",({entries:e})=>{e.forEach(e=>{isPerformanceResourceTiming(e)&&e.name.endsWith(n)&&(t.setAttributes(resourceTimingToSpanAttributes(e)),r())})})}function shouldAttachHeaders(t,e){const n=getLocationHref();if(n){let r,i;try{r=new URL(t,n),i=new URL(n).origin}catch{return!1}const s=r.origin===i;return e?stringMatchesSomePattern(r.toString(),e)||s&&stringMatchesSomePattern(r.pathname,e):s}{const n=!!t.match(/^\/(?!\/)/);return e?stringMatchesSomePattern(t,e):n}}function xhrCallback(t,e,n,r,i,s){const a=t.xhr,o=a?.[SENTRY_XHR_DATA_KEY];if(!a||a.__sentry_own_request__||!o)return;const{url:l,method:c}=o,d=hasSpansEnabled()&&e(l);if(t.endTimestamp){const e=a.__sentry_xhr_span_id__;if(!e)return;const n=r[e];return void(n&&(d&&void 0!==o.status_code&&(setHttpStatus(n,o.status_code),n.end(),s?.(n,{headers:createHeadersSafely(parseXhrResponseHeaders(a)),error:t.error})),delete r[e]))}const h=getFullURL(l),u=parseUrl(h||l),p=h?stripDataUrlContent(h):void 0,f=stripDataUrlContent(stripUrlQueryAndFragment(l)),m=getClient(),_=!!getActiveSpan(),g=_||!!m&&hasSpanStreamingEnabled(m),y=d&&g?startInactiveSpan({name:`${c} ${f}`,attributes:{url:stripDataUrlContent(l),type:"xhr","http.method":c,"http.url":p,[Yu]:p,"server.address":u?.host,[SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN]:"auto.http.browser",[SEMANTIC_ATTRIBUTE_SENTRY_OP]:"http.client",...u?.search&&{"http.query":u?.search},...u?.hash&&{"http.fragment":u?.hash}}}):new SentryNonRecordingSpan,S=spanIsIgnored(y)&&_?void 0:y;return d&&!g&&m?.recordDroppedEvent("no_parent_span","span"),a.__sentry_xhr_span_id__=y.spanContext().spanId,r[a.__sentry_xhr_span_id__]=y,n(l)&&addTracingHeadersToXhrRequest(a,hasSpansEnabled()&&g?S:void 0,i),m&&m.emit("beforeOutgoingRequestSpan",y,t),y}function addTracingHeadersToXhrRequest(t,e,n){const{"sentry-trace":r,baggage:i,traceparent:s}=getTraceData({span:e,propagateTraceparent:n});r&&setHeaderOnXhr(t,r,i,s)}function setHeaderOnXhr(t,e,n,r){const i=t.__sentry_xhr_v3__?.request_headers;if(!i?.["sentry-trace"]&&t.setRequestHeader)try{if(t.setRequestHeader("sentry-trace",e),r&&!i?.traceparent&&t.setRequestHeader("traceparent",r),n){const e=i?.baggage;e&&baggageHeaderHasSentryValues(e)||t.setRequestHeader("baggage",n)}}catch{}}const responseToStreamSpan=/* @__PURE__ */new WeakMap,responseToFallbackTimeout=/* @__PURE__ */new WeakMap,STREAM_RESOLVE_FALLBACK_MS=9e4,STREAMING_CONTENT_TYPES=["text/event-stream","application/x-ndjson","application/stream+json"],fetchStreamPerformanceIntegration=defineIntegration(()=>({name:"FetchStreamPerformance",setup(){addFetchEndInstrumentationHandler(t=>{if(t.response){const e=responseToStreamSpan.get(t.response);if(e&&t.endTimestamp){e.end(t.endTimestamp);const n=responseToFallbackTimeout.get(t.response);n&&clearTimeout(n)}}}),addFetchInstrumentationHandler(t=>{if(t.endTimestamp&&t.response){const e=t.response.headers?.get("content-type")||"";if(t.response.headers?.get("content-length")||!STREAMING_CONTENT_TYPES.some(t=>e.startsWith(t)))return;const n=t.fetchData?.url||"",r=t.fetchData?.method||"GET",i=parseStringToURLObject(n),s=startInactiveSpan({name:`${r} ${n.startsWith("data:")?stripDataUrlContent(n):i?getSanitizedUrlStringFromUrlObject(i):n}`,startTime:t.endTimestamp,attributes:{url:stripDataUrlContent(n),"http.method":r,type:"fetch",[SEMANTIC_ATTRIBUTE_SENTRY_OP]:"http.client.stream",[SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN]:"auto.http.browser.stream"}});responseToStreamSpan.set(t.response,s);const a=setTimeout(()=>{s.isRecording()&&s.end()},STREAM_RESOLVE_FALLBACK_MS);responseToFallbackTimeout.set(t.response,a)}})}})),WEB_VITALS_INTEGRATION_NAME="WebVitals",webVitalsIntegration=defineIntegration((t={})=>{const e=new Set(t.ignore??[]);return{name:WEB_VITALS_INTEGRATION_NAME,setup(n){const r=hasSpanStreamingEnabled(n),{enableStandaloneClsSpans:i,enableStandaloneLcpSpans:s}=t._experiments??{},a=r||e.has("cls")?void 0:i||!1,o=r||e.has("lcp")?void 0:s||!1,l=startTrackingWebVitals({recordClsStandaloneSpans:a,recordLcpStandaloneSpans:o,client:n}),c=/* @__PURE__ */new WeakSet;n.on("afterStartPageLoadSpan",t=>{c.add(t)}),n.on("spanEnd",t=>{c.delete(t)&&(l(),addWebVitalsToSpan(t,{recordClsOnPageloadSpan:!1===a,recordLcpOnPageloadSpan:!1===o,spanStreamingEnabled:r}))}),r?(e.has("lcp")||trackLcpAsSpan(n),e.has("cls")||trackClsAsSpan(n),e.has("inp")||trackInpAsSpan()):e.has("inp")||startTrackingINP()},afterAllSetup(){e.has("inp")||registerInpInteractionListener()}}});function registerBackgroundTabDetection(){WINDOW$1.document?WINDOW$1.document.addEventListener("visibilitychange",()=>{const t=getActiveSpan();if(!t)return;const e=getRootSpan(t);if(WINDOW$1.document.hidden&&e){const t="cancelled",{op:n,status:r}=spanToJSON(e);DEBUG_BUILD&&debug.log(`[Tracing] Transaction: ${t} -> since tab moved to the background, op: ${n}`),r||e.setStatus({code:SPAN_STATUS_ERROR,message:t}),e.setAttribute("sentry.cancellation_reason","document.hidden"),e.end()}}):DEBUG_BUILD&&debug.warn("[Tracing] Could not set up background tab detection due to lack of global document")}const PREVIOUS_TRACE_MAX_DURATION=3600,PREVIOUS_TRACE_KEY="sentry_previous_trace",PREVIOUS_TRACE_TMP_SPAN_ATTRIBUTE="sentry.previous_trace";function linkTraces(t,{linkPreviousTrace:e,consistentTraceSampling:n}){const r="session-storage"===e;let i=r?getPreviousTraceFromSessionStorage():void 0;t.on("spanStart",t=>{if(getRootSpan(t)!==t)return;const e=getCurrentScope().getPropagationContext();i=addPreviousTraceSpanLink(i,t,e),r&&storePreviousTraceInSessionStorage(i)});let s=!0;n&&t.on("beforeSampling",t=>{if(!i)return;const e=getCurrentScope(),n=e.getPropagationContext();s&&n.parentSpanId?s=!1:(e.setPropagationContext({...n,dsc:{...n.dsc,sample_rate:String(i.sampleRate),sampled:String(spanContextSampled(i.spanContext))},sampleRand:i.sampleRand}),t.parentSampled=spanContextSampled(i.spanContext),t.parentSampleRate=i.sampleRate,t.spanAttributes={...t.spanAttributes,[SEMANTIC_ATTRIBUTE_SENTRY_PREVIOUS_TRACE_SAMPLE_RATE]:i.sampleRate})})}function addPreviousTraceSpanLink(t,e,n){const r=spanToJSON(e),i={spanContext:e.spanContext(),startTimestamp:r.start_timestamp,sampleRate:function(){try{const t=Number(r.data?.[SEMANTIC_ATTRIBUTE_SENTRY_SAMPLE_RATE]??n.dsc?.sample_rate);return Number.isNaN(t)?0:t}catch{return 0}}(),sampleRand:n.sampleRand};if(!t)return i;const s=t.spanContext;return s.traceId===r.trace_id?t:(Date.now()/1e3-t.startTimestamp<=PREVIOUS_TRACE_MAX_DURATION&&(DEBUG_BUILD&&debug.log(`Adding previous_trace \`${JSON.stringify(s)}\` link to span \`${JSON.stringify({op:r.op,...e.spanContext()})}\``),e.addLink({context:s,attributes:{[SEMANTIC_LINK_ATTRIBUTE_LINK_TYPE]:"previous_trace"}}),e.setAttribute(PREVIOUS_TRACE_TMP_SPAN_ATTRIBUTE,`${s.traceId}-${s.spanId}-${spanContextSampled(s)?1:0}`)),i)}function storePreviousTraceInSessionStorage(t){try{WINDOW$1.sessionStorage.setItem(PREVIOUS_TRACE_KEY,JSON.stringify(t))}catch(t){DEBUG_BUILD&&debug.warn("Could not store previous trace in sessionStorage",t)}}function getPreviousTraceFromSessionStorage(){try{const t=WINDOW$1.sessionStorage?.getItem(PREVIOUS_TRACE_KEY);return JSON.parse(t)}catch{return}}function spanContextSampled(t){return 1===t.traceFlags}const BROWSER_TRACING_INTEGRATION_ID="BrowserTracing",BOT_USER_AGENT_RE=/Googlebot|Google-InspectionTool|Storebot-Google|Bingbot|Slurp|DuckDuckBot|Baiduspider|YandexBot|Facebot|facebookexternalhit|LinkedInBot|Twitterbot|Applebot/i;function isBotUserAgent(){const t=WINDOW$1.navigator;return!!t?.userAgent&&BOT_USER_AGENT_RE.test(t.userAgent)}const DEFAULT_BROWSER_TRACING_OPTIONS={...TRACING_DEFAULTS,instrumentNavigation:!0,instrumentPageLoad:!0,markBackgroundSpan:!0,enableLongTask:!0,enableLongAnimationFrame:!0,enableInp:!0,ignoreResourceSpans:[],ignorePerformanceApiSpans:[],detectRedirects:!0,linkPreviousTrace:"in-memory",consistentTraceSampling:!1,enableReportPageLoaded:!1,_experiments:{},...defaultRequestInstrumentationOptions},browserTracingIntegration=(t={})=>{"enableElementTiming"in t&&consoleSandbox(()=>{console.warn("[Sentry] `enableElementTiming` is deprecated and no longer has any effect. Use the standalone `elementTimingIntegration` instead.")});const e={name:void 0,source:void 0},n=WINDOW$1.document,{enableInp:r,enableLongTask:i,enableLongAnimationFrame:s,_experiments:{enableInteractions:a,enableStandaloneClsSpans:o,enableStandaloneLcpSpans:l},beforeStartSpan:c,idleTimeout:d,finalTimeout:h,childSpanTimeout:u,markBackgroundSpan:p,traceFetch:f,traceXHR:m,trackFetchStreamPerformance:_,shouldCreateSpanForRequest:g,enableHTTPTimings:y,ignoreResourceSpans:S,ignorePerformanceApiSpans:A,instrumentPageLoad:v,instrumentNavigation:E,detectRedirects:b,linkPreviousTrace:T,consistentTraceSampling:w,enableReportPageLoaded:x,onRequestSpanStart:I,onRequestSpanEnd:R}={...DEFAULT_BROWSER_TRACING_OPTIONS,...t},C=isBotUserAgent();let B,D;function P(t,r,i=!0,s){const a="pageload"===r.op,o=r.name,l=c?c(r):r,p=parseStringToURLObject(s||getLocationHref()),f={...p?.pathname&&{[Vu]:p.pathname},...p&&!isURLObjectRelative(p)&&{[Yu]:p.href},...l.attributes};if(o!==l.name&&(f[SEMANTIC_ATTRIBUTE_SENTRY_SOURCE]="custom"),l.attributes=f,!i){const t=dateTimestampInSeconds();return void startInactiveSpan({...l,startTime:t}).end(t)}e.name=l.name,e.source=f[SEMANTIC_ATTRIBUTE_SENTRY_SOURCE];const m=startIdleSpan(l,{idleTimeout:d,finalTimeout:h,childSpanTimeout:u,disableAutoFinish:a,beforeSpanEnd:e=>{addPerformanceEntries(e,{ignoreResourceSpans:S,ignorePerformanceApiSpans:A,spanStreamingEnabled:hasSpanStreamingEnabled(t)}),setActiveIdleSpan(t,void 0);const n=getCurrentScope(),r=n.getPropagationContext();n.setPropagationContext({...r,traceId:m.spanContext().traceId,sampled:spanIsSampled(m),dsc:getDynamicSamplingContextFromSpan(e)}),a&&(D=void 0)},trimIdleSpanEndTimestamp:!x});function _(){n&&["interactive","complete"].includes(n.readyState)&&(t.emit("idleSpanEnableAutoFinish",m),n.removeEventListener("readystatechange",_))}a&&x&&(D=m),setActiveIdleSpan(t,m),a&&!x&&n&&(n.addEventListener("readystatechange",_),_())}return{name:BROWSER_TRACING_INTEGRATION_ID,setup(t){if(C)DEBUG_BUILD&&debug.log("[Tracing] Skipping browserTracingIntegration setup for bot user agent.");else{if(registerSpanErrorInstrumentation(),s&&GLOBAL_OBJ.PerformanceObserver&&PerformanceObserver.supportedEntryTypes?.includes("long-animation-frame")?startTrackingLongAnimationFrames():i&&startTrackingLongTasks(),a&&startTrackingInteractions(),b&&n){const t=()=>{B=timestampInSeconds()};addEventListener("click",t,{capture:!0}),addEventListener("keydown",t,{capture:!0,passive:!0})}t.on("startNavigationSpan",(n,r)=>{if(getClient()!==t)return;if(r?.isRedirect)return DEBUG_BUILD&&debug.warn("[Tracing] Detected redirect, navigation span will not be the root span, but a child span."),void P(t,{op:"navigation.redirect",...n},!1,r.url);B=void 0,e(),getIsolationScope().setPropagationContext({traceId:generateTraceId(),sampleRand:Math.random(),propagationSpanId:hasSpansEnabled()?void 0:generateSpanId()});const i=getCurrentScope();i.setPropagationContext({traceId:generateTraceId(),sampleRand:Math.random(),propagationSpanId:hasSpansEnabled()?void 0:generateSpanId()}),i.setSDKProcessingMetadata({normalizedRequest:void 0}),P(t,{op:"navigation",...n,parentSpan:null,forceTransaction:!0},!0,r?.url)}),t.on("startPageLoadSpan",(n,r={})=>{if(getClient()!==t)return;e();const i=propagationContextFromHeaders(r.sentryTrace||getMetaContent("sentry-trace")||getServerTiming("sentry-trace"),r.baggage||getMetaContent("baggage")||getServerTiming("baggage")),s=getCurrentScope();s.setPropagationContext(i),hasSpansEnabled()||(s.getPropagationContext().propagationSpanId=generateSpanId()),s.setSDKProcessingMetadata({normalizedRequest:getHttpRequestData()}),P(t,{op:"pageload",...n})}),t.on("endPageloadSpan",()=>{x&&D&&(D.setAttribute(SEMANTIC_ATTRIBUTE_SENTRY_IDLE_SPAN_FINISH_REASON,"reportPageLoaded"),D.end())})}function e(){const e=getActiveIdleSpan(t);e&&!spanToJSON(e).timestamp&&(DEBUG_BUILD&&debug.log(`[Tracing] Finishing current active span with op: ${spanToJSON(e).op}`),e.setAttribute(SEMANTIC_ATTRIBUTE_SENTRY_IDLE_SPAN_FINISH_REASON,"cancelled"),e.end())}},afterAllSetup(t){if(C)return;t.addIntegration&&!t.getIntegrationByName?.(WEB_VITALS_INTEGRATION_NAME)&&t.addIntegration(webVitalsIntegration({ignore:r?[]:["inp"],_experiments:{enableStandaloneClsSpans:o,enableStandaloneLcpSpans:l}}));let n=getLocationHref();if("off"!==T&&linkTraces(t,{linkPreviousTrace:T,consistentTraceSampling:w}),WINDOW$1.location){if(v){const e=browserPerformanceTimeOrigin();startBrowserTracingPageLoadSpan(t,{name:WINDOW$1.location.pathname,startTime:e?e/1e3:void 0,attributes:{[SEMANTIC_ATTRIBUTE_SENTRY_SOURCE]:"url",[SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN]:"auto.pageload.browser"}})}E&&addHistoryInstrumentationHandler(({to:e,from:r})=>{if(void 0===r&&-1!==n?.indexOf(e))return void(n=void 0);n=void 0;const i=parseStringToURLObject(e),s=getActiveIdleSpan(t),a=s&&b&&isRedirect(s,B);startBrowserTracingNavigationSpan(t,{name:i?.pathname||WINDOW$1.location.pathname,attributes:{[SEMANTIC_ATTRIBUTE_SENTRY_SOURCE]:"url",[SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN]:"auto.navigation.browser"}},{url:e,isRedirect:a})})}p&&registerBackgroundTabDetection(),a&&registerInteractionListener(t,d,h,u,e),instrumentOutgoingRequests(t,{traceFetch:f,traceXHR:m,tracePropagationTargets:t.getOptions().tracePropagationTargets,shouldCreateSpanForRequest:g,enableHTTPTimings:y,onRequestSpanStart:I,onRequestSpanEnd:R}),_&&t.addIntegration(fetchStreamPerformanceIntegration())}}};function startBrowserTracingPageLoadSpan(t,e,n){t.emit("startPageLoadSpan",e,n),getCurrentScope().setTransactionName(e.name);const r=getActiveIdleSpan(t);return r&&t.emit("afterStartPageLoadSpan",r),r}function startBrowserTracingNavigationSpan(t,e,n){const{url:r,isRedirect:i}=n||{};t.emit("beforeStartNavigationSpan",e,{isRedirect:i,url:r}),t.emit("startNavigationSpan",e,{isRedirect:i,url:r});const s=getCurrentScope();return s.setTransactionName(e.name),r&&!i&&s.setSDKProcessingMetadata({normalizedRequest:{...getHttpRequestData(),url:r}}),getActiveIdleSpan(t)}function getMetaContent(t){const e=WINDOW$1.document,n=e?.querySelector(`meta[name=${t}]`);return n?.getAttribute("content")||void 0}function getServerTiming(t){const e=WINDOW$1.performance?.getEntriesByType?.("navigation")[0],n=e?.serverTiming?.find(e=>e.name===t);return n?.description}function registerInteractionListener(t,e,n,r,i){let s;WINDOW$1.document&&addEventListener("click",()=>{const a="ui.action.click",o=getActiveIdleSpan(t);if(o){const t=spanToJSON(o).op;if(["navigation","pageload"].includes(t))return void(DEBUG_BUILD&&debug.warn(`[Tracing] Did not create ${a} span because a pageload or navigation span is in progress.`))}s&&(s.setAttribute(SEMANTIC_ATTRIBUTE_SENTRY_IDLE_SPAN_FINISH_REASON,"interactionInterrupted"),s.end(),s=void 0),i.name?s=startIdleSpan({name:i.name,op:a,attributes:{[SEMANTIC_ATTRIBUTE_SENTRY_SOURCE]:i.source||"url"}},{idleTimeout:e,finalTimeout:n,childSpanTimeout:r}):DEBUG_BUILD&&debug.warn(`[Tracing] Did not create ${a} transaction because _latestRouteName is missing.`)},{capture:!0})}const ACTIVE_IDLE_SPAN_PROPERTY="_sentry_idleSpan";function getActiveIdleSpan(t){return t[ACTIVE_IDLE_SPAN_PROPERTY]}function setActiveIdleSpan(t,e){addNonEnumerableProperty(t,ACTIVE_IDLE_SPAN_PROPERTY,e)}const REDIRECT_THRESHOLD=1.5;function isRedirect(t,e){const n=spanToJSON(t),r=dateTimestampInSeconds();return!(r-n.start_timestamp>REDIRECT_THRESHOLD||e&&r-e<=REDIRECT_THRESHOLD)}const NOISE_ERROR_CODES=["3205","3206","3305","30005"];class SentryReporter{constructor(t,e={}){var n;this.tracesSampleRate=null!=(n=e.tracesSampleRate)?n:1;const r=getDefaultIntegrations().filter(t=>!["BrowserApiErrors","BrowserSession","Breadcrumbs","GlobalHandlers","FunctionToString","Dedupe"].includes(t.name));r.push(browserTracingIntegration({instrumentPageLoad:!1,instrumentNavigation:!1,traceFetch:!1,traceXHR:!1})),this.client=new BrowserClient({dsn:t,transport:makeFetchTransport,stackParser:defaultStackParser,integrations:r,release:"xmov-avatar@2.4.0-alpha.3",tracesSampleRate:this.tracesSampleRate,beforeSend(t){var e,n,r,i,s;if("xmov-avatar-sdk"!==(null==(e=t.tags)?void 0:e.source))return null;const a=String(null!=(n=null==(r=t.tags)?void 0:r.error_code)?n:"");return NOISE_ERROR_CODES.includes(a)?null:(t.fingerprint=[a||"unknown",String(null!=(i=t.message)?i:"").slice(0,64)],t.contexts=_extends({},null!=(s=t.contexts)?s:{},{browser:{name:navigator.userAgent.slice(0,200)}}),t)}}),this.scope=new Scope,this.scope.setClient(this.client),this.scope.setTag("sdk_version","2.4.0-alpha.3"),this.scope.setTag("source","xmov-avatar-sdk"),this.client.init()}captureError(t){this.scope.setTag("error_code",String(t.error_code)),this.scope.setTag("error_name",t.error_name),this.scope.setTag("session_id",t.session_id),this.scope.setExtra("code",t.code),this.scope.setExtra("client_speak_id",t.client_speak_id),this.scope.setExtra("timestamp",t.timestamp),t.originalError&&this.scope.setExtra("originalError",t.originalError),this.scope.captureException(new Error(t.message))}startSpan(t,e,n){return startSpan({name:t,op:e.op,scope:this.scope,attributes:e.data},()=>n())}startInactiveSpan(t,e){const n=startInactiveSpan({name:t,op:e.op,scope:this.scope,attributes:e.data});return{end:()=>null==n?void 0:n.end()}}setTag(t,e){this.scope.setTag(t,e)}setUser(t){this.scope.setUser(t)}async destroy(){await this.client.close(2e3)}}let isLoggingEnabled=!1;function executeLog(t,...e){isLoggingEnabled&&"function"==typeof t&&t(...e)}const sdkLog={log:(...t)=>executeLog(console.log,...t),info:(...t)=>executeLog(console.info,...t),warn:(...t)=>executeLog(console.warn,...t),error:(...t)=>executeLog(console.error,...t)};function setLoggingEnabled(t){isLoggingEnabled=t,t?console.log("[AVATAR SDK] version:","2.4.0-alpha.3","日志已启用"):console.log("[AVATAR SDK] version:","2.4.0-alpha.3","日志已禁用")}function sampleUniformTensor(t,e){return Float16Array===t.constructor||Float32Array===t.constructor||Float64Array===t.constructor?t[e]:Uint8Array===t.constructor?t[e]/255:Int8Array===t.constructor?(t[e]+128)/255*2-1:Uint16Array===t.constructor?t[e]/65535:Int16Array===t.constructor?(t[e]+32768)/65535*2-1:Uint32Array===t.constructor?t[e]/4294967295:Int32Array===t.constructor?(t[e]+2147483648)/4294967295*2-1:BigUint64Array===t.constructor?Number(t[e]>>32n)/4294967295:BigInt64Array===t.constructor?(Number(t[e]>>32n)+2147483648)/4294967295*2-1:0}function sampleUniformPCATensor(t,e){return Float16Array===t.constructor||Float32Array===t.constructor||Float64Array===t.constructor?t[e]:Uint8Array===t.constructor?t[e]/255*2-1:Int8Array===t.constructor?(t[e]+128)/255*2-1:Uint16Array===t.constructor?t[e]/65535*2-1:Int16Array===t.constructor?(t[e]+32768)/65535*2-1:Uint32Array===t.constructor?t[e]/4294967295*2-1:Int32Array===t.constructor?(t[e]+2147483648)/4294967295*2-1:BigUint64Array===t.constructor?Number(t[e]>>32n)/4294967295*2-1:BigInt64Array===t.constructor?(Number(t[e]>>32n)+2147483648)/4294967295*2-1:0}function getVertices(t,e){let n=t.char,r=n.evalSkeleton(),i=n.evalSkeletonFromMovable(e.movableJointTransforms),s=Array(n.skeleton.length);for(let t=0;t<n.skeleton.length;t++){const e=i[t].apply(r[t].inv());s[t]=e.homogeneous_matrix()}let a=[];for(let t=0;t<n.mesh.length;t++){let r=[];for(let i=0;i<n.mesh[t].blendshapes.size[0];i++){let a=[],o=n.mesh[t].vertices,l=n.mesh[t].blendshapes,c=e.blendshapeWeights;for(let t=0;t<3;t++)a.push(o.data[i*o.size[1]+t]);for(let e=0;e<n.mesh[t].blendshapeIndices.length;e++)for(let r=0;r<3;r++)a[r]+=c[n.mesh[t].blendshapeIndices[e]]*Number(l.data[(i*l.size[1]+r)*l.size[2]+e]);a.push(1);let d=[0,0,0,0],h=n.mesh[t].jointIndex,u=n.mesh[t].jointWeight;for(let t=0;t<n.maxJointsPerVertex;t++){let e=h[i*n.maxJointsPerVertex+t];if(e<n.skeleton.length){let r=mvmul(s[e],a);for(let e=0;e<4;e++)d[e]+=u[i*n.maxJointsPerVertex+t]*r[e]}}for(let t=0;t<3;t++)d[t]/=d[3];r.push([d[0],d[1],d[2]])}a.push(r)}return a}function getPCATextures(t,e){let n=t.char,r=[];for(let t=0;t<n.mesh.length;t++){let i=n.mesh[t].textureModels[e.mesh[t].textureModelIndex],s=[],a=new Uint8ClampedArray(i.data.size[1]*i.data.size[2]*4),o=1;i.scalingFactor&&(o*=Number(i.scalingFactor.data[0]));for(let t=0;t<i.data.size[1];t++){let e=[];for(let n=0;n<i.data.size[2];n++){let r=[];for(let e=0;e<3;e++)r.push(o*sampleUniformPCATensor(i.data.data,3*(t*i.data.size[2]+n)+e));e.push(r)}s.push(e)}for(let n=1;n<i.data.size[0];n++){let r=e.mesh[t].texturePCAWeights[n-1];i.scalingFactor&&(r*=Number(i.scalingFactor.data[n]));for(let t=0;t<i.data.size[1];t++)for(let e=0;e<i.data.size[2];e++)for(let a=0;a<3;a++)s[t][e][a]+=r*sampleUniformPCATensor(i.data.data,3*((n*i.data.size[1]+t)*i.data.size[2]+e)+a)}for(let t=0;t<i.data.size[1];t++)for(let e=0;e<i.data.size[2];e++){for(let n=0;n<3;n++)a[4*(t*i.data.size[2]+e)+n]=Math.round(255*s[i.data.size[1]-1-t][e][2-n]);a[4*(t*i.data.size[2]+e)+3]=255}r.push(new ImageData(a,i.data.size[1],i.data.size[2]))}return r}function exportAsWavefrontObj(t){let e="",n="",r=1,i=0;for(const s of t){for(const t of s.vertices)e+=`v ${t[0]} ${t[1]} ${t[2]}\n`;for(const t of s.uv)e+=`vt ${t[0]} ${t[1]}}\n`;n+=`g Obj${i}\n`;for(const t of s.polygons)n+=`f ${t.map(t=>(t+r).toString()).map(t=>`${t}/${t}`).join(" ")}\n`;r+=s.vertices.length,i+=1}return e+n}function getWavefrontObjFromVertices(t,e){function n(t,e){let n=[];for(let r=0;r<t.length;r++)0==r%e&&n.push([]),n[n.length-1].push(sampleUniformTensor(t,r));return n}function r(t,e){let n=[];for(let r=0;r<t.length;r++)0==r%e&&n.push([]),n[n.length-1].push(Number(t[r]));return n}let i=t.char,s=[];for(let t=0;t<i.mesh.length;t++)s.push({vertices:e[t],uv:n(i.mesh[t].UVCoord.data,2),polygons:r(i.mesh[t].triangles.data,3)});return exportAsWavefrontObj(s)}window.avatarSDKLogger=_extends({},sdkLog,{setEnabled:setLoggingEnabled});class StreamingClient{constructor(t){this.ws=null,this.retryCount=0,this.maxRetry=27,this.retryTimer=-1,this.destroyed=!1,this.connected=!1,this.options=t}connect(){if(!this.destroyed){try{this.ws=new WebSocket(this.options.url)}catch(t){return console.error("[StreamingClient] 创建 WebSocket 失败:",t),void this.scheduleRetry()}this.ws.onopen=()=>{this.connected=!0,this.retryCount=0,console.log("[StreamingClient] 已连接"),this.send({type:"join",role:"client"})},this.ws.onmessage=t=>{let e;try{e=JSON.parse(t.data)}catch(t){return}this.handleMessage(e)},this.ws.onclose=()=>{var t,e;this.connected=!1,this.destroyed||(null==(t=(e=this.options).onDisconnect)||t.call(e),this.scheduleRetry())},this.ws.onerror=()=>{var t,e;null==(t=(e=this.options).onError)||t.call(e,"WebSocket 连接错误")}}}handleMessage(t){var e,n,r,i,s,a,o,l,c,d;switch(t.type){case"ready":null==(e=(n=this.options).onReady)||e.call(n);break;case"offer":null==(r=(i=this.options).onOffer)||r.call(i,t.sdp);break;case"answer":break;case"ice":null==(s=(a=this.options).onIce)||s.call(a,t.candidate);break;case"event_proxy":null==(o=(l=this.options).onEventProxy)||o.call(l,t.event_type,t.data,t.server_frame);break;case"error":null==(c=(d=this.options).onError)||c.call(d,t.message||"未知错误")}}send(t){this.ws&&this.ws.readyState===WebSocket.OPEN&&this.ws.send(JSON.stringify(t))}sendApiCall(t,e=[]){this.send({type:"api_call",method:t,params:e})}scheduleRetry(){if(this.destroyed)return;var t,e;if(this.retryCount>=this.maxRetry)return console.warn("[StreamingClient] 重试次数已达上限"),void(null==(t=(e=this.options).onError)||t.call(e,"连接重试次数已达上限"));const n=0===this.retryCount?1e3:1e3*Math.pow(2,Math.min(this.retryCount,6));this.retryCount++,this.retryTimer=window.setTimeout(()=>{this.connect()},n)}isConnected(){return this.connected}destroy(){this.destroyed=!0,-1!==this.retryTimer&&(clearTimeout(this.retryTimer),this.retryTimer=-1),this.ws&&(this.ws.close(),this.ws=null),this.connected=!1}}class VideoPlayer{constructor(t){this.video=null,this.canvas=null,this.canvasCtx=null,this.pc=null,this.stream=null,this.destroyed=!1,this.animFrameId=0,this.tempCanvas=null,this.tempCtx=null,this.options=t,t.useAlphaMask?this.createCanvasElement():this.createVideoElement()}createVideoElement(){const t=document.createElement("video");t.autoplay=!0,t.playsInline=!0,t.muted=!0,t.style.width="100%",t.style.height="100%",t.style.objectFit="contain",t.style.background="transparent",this.video=t,this.options.container.appendChild(t)}createCanvasElement(){const t=document.createElement("canvas");t.style.width="100%",t.style.height="100%",t.style.objectFit="contain",t.style.background="transparent",this.canvas=t,this.canvasCtx=t.getContext("2d",{willReadFrequently:!0}),this.tempCanvas=document.createElement("canvas"),this.tempCtx=this.tempCanvas.getContext("2d",{willReadFrequently:!0}),this.options.container.appendChild(t);const e=document.createElement("video");e.autoplay=!0,e.playsInline=!0,e.muted=!0,e.style.position="absolute",e.style.width="1px",e.style.height="1px",e.style.opacity="0",e.style.pointerEvents="none",e.style.zIndex="-1",this.video=e,this.options.container.appendChild(e)}async handleOffer(t){this.destroyPeer(),this.pc=new RTCPeerConnection({iceServers:[{urls:"stun:stun.l.google.com:19302"},{urls:"stun:stun1.l.google.com:19302"},{urls:"turn:openrelay.metered.ca:80",username:"openrelayproject",credential:"openrelayproject"},{urls:"turn:openrelay.metered.ca:443",username:"openrelayproject",credential:"openrelayproject"},{urls:"turns:openrelay.metered.ca:443",username:"openrelayproject",credential:"openrelayproject"}]}),this.pc.onicecandidate=t=>{t.candidate&&this.options.streamingClient.send({type:"ice",candidate:t.candidate.toJSON()})},this.pc.ontrack=t=>{console.log("[VideoPlayer] 收到轨道:",t.track.kind,t.track.id),this.stream||(this.stream=new MediaStream,this.video&&(this.video.srcObject=this.stream)),this.stream.addTrack(t.track),"audio"===t.track.kind&&this.video&&(this.video.muted=!1,this.video.play().catch(()=>{})),"video"===t.track.kind&&this.options.useAlphaMask&&(console.log("[VideoPlayer] Alpha Mask 模式:启动 canvas 渲染循环"),this.startAlphaRendering())},this.pc.onconnectionstatechange=()=>{var t,e;if(this.pc)if(console.log("[VideoPlayer] WebRTC 状态:",this.pc.connectionState),"connected"===this.pc.connectionState)null==(t=(e=this.options).onConnected)||t.call(e);else if("disconnected"===this.pc.connectionState||"failed"===this.pc.connectionState){var n,r;null==(n=(r=this.options).onDisconnected)||n.call(r)}},await this.pc.setRemoteDescription(new RTCSessionDescription({type:"offer",sdp:t}));const e=await this.pc.createAnswer();await this.pc.setLocalDescription(e),this.options.streamingClient.send({type:"answer",sdp:e.sdp})}startAlphaRendering(){if(!(this.video&&this.canvas&&this.canvasCtx&&this.tempCanvas&&this.tempCtx))return;const t=this.video,e=this.canvas,n=this.canvasCtx,r=this.tempCanvas,i=this.tempCtx;let s=0,a=0,o=0,l=null;l=setInterval(()=>{this.destroyed?l&&clearInterval(l):console.log(`[VideoPlayer] Alpha 渲染调试: frames=${o}, videoReadyState=${t.readyState}, videoSize=${t.videoWidth}x${t.videoHeight}, currentTime=${t.currentTime.toFixed(2)}s, paused=${t.paused}`)},2e3);const c=()=>{if(this.destroyed)l&&clearInterval(l);else{if(t.readyState>=2&&t.videoWidth>0){const l=t.videoWidth,c=t.videoHeight,d=l/2,h=c;l===s&&c===a||(e.width=d,e.height=h,r.width=l,r.height=h,s=l,a=c,console.log(`[VideoPlayer] Alpha Mask: 检测到双流 ${l}x${c} → 原始 ${d}x${h}`)),i.clearRect(0,0,2*d,h),i.drawImage(t,0,0),n.clearRect(0,0,d,h),n.drawImage(r,0,0,d,h,0,0,d,h);try{const t=n.getImageData(0,0,d,h),e=i.getImageData(d,0,d,h),r=t.data,s=e.data;if(0===o){let t=0,e=0;const n=Math.min(1e3,r.length/4);for(let i=0;i<4*n;i+=4)(r[i]>0||r[i+1]>0||r[i+2]>0)&&t++,s[i]>0&&e++;console.log(`[VideoPlayer] 首帧像素检查: RGB非零=${t}/${n}, Alpha非零=${e}/${n}`),0===t&&console.warn("[VideoPlayer] 警告: RGB 全黑!视频可能没有内容")}for(let t=0;t<r.length;t+=4)r[t+3]=s[t];n.putImageData(t,0,0),o++}catch(e){console.warn("[VideoPlayer] Alpha 合成失败,降级为直接绘制:",e),n.drawImage(t,0,0,d,h,0,0,d,h),o++}}this.animFrameId=requestAnimationFrame(c)}};this.animFrameId=requestAnimationFrame(c)}async addIceCandidate(t){this.pc&&await this.pc.addIceCandidate(t).catch(t=>{console.warn("[VideoPlayer] addIceCandidate 失败:",t)})}getVideoElement(){return this.video}getCanvasElement(){return this.canvas}isConnected(){var t;return"connected"===(null==(t=this.pc)?void 0:t.connectionState)}destroyPeer(){this.pc&&(this.pc.close(),this.pc=null),this.stream=null,this.animFrameId&&(cancelAnimationFrame(this.animFrameId),this.animFrameId=0)}destroy(){this.destroyed=!0,this.destroyPeer(),this.video&&this.video.parentNode&&this.video.parentNode.removeChild(this.video),this.canvas&&this.canvas.parentNode&&this.canvas.parentNode.removeChild(this.canvas),this.video=null,this.canvas=null,this.canvasCtx=null,this.tempCanvas=null,this.tempCtx=null}}class EventDispatcher{constructor(t){this.subtitleText="",this.subtitleVisible=!1,this.callbacks=t}dispatch(t,e,n){var r,i,s,a,o,l,c,d,h,u,p,f,m,_,g,y,S,A,v,E,b,T,w,x,I,R;switch(t){case"state_change":null==(r=(i=this.callbacks).onStateChange)||r.call(i,e.state||e);break;case"speak_state_change":null==(s=(a=this.callbacks).onSpeakStateChange)||s.call(a,e.state,e.client_speak_id);break;case"voice_state_change":null==(o=(l=this.callbacks).onVoiceStateChange)||o.call(l,e.state,e.duration,e.client_speak_id||"");break;case"status_change":null==(c=(d=this.callbacks).onStatusChange)||c.call(d,e.status);break;case"render_change":null==(h=(u=this.callbacks).onRenderChange)||h.call(u,e.state);break;case"walk_state_change":null==(p=(f=this.callbacks).onWalkStateChange)||p.call(f,e.state||e);break;case"widget_event":null==(m=(_=this.callbacks).onWidgetEvent)||m.call(_,e);break;case"message":case"error":null==(g=(y=this.callbacks).onMessage)||g.call(y,e);break;case"network_info":null==(S=(A=this.callbacks).onNetworkInfo)||S.call(A,e);break;case"fps_update":null==(v=(E=this.callbacks).onFPSUpdate)||v.call(E,e);break;case"download_progress":null==(b=(T=this.callbacks).onDownloadProgress)||b.call(T,e.progress);break;case"session_id":null==(w=(x=this.callbacks).onSessionId)||w.call(x,e.session_id);break;case"frame_data_update":null==(I=(R=this.callbacks).onFrameDataUpdate)||I.call(R,e);break;default:console.log("[EventDispatcher] 未处理的事件类型:",t,e)}}getSubtitleText(){return this.subtitleText}isSubtitleVisible(){return this.subtitleVisible}}class APIForwarder{constructor(t){this.client=t}speak(t,e=!0,n=!0,r={}){this.client.sendApiCall("speak",[t,e,n,r])}idle(){this.client.sendApiCall("idle",[])}listen(){this.client.sendApiCall("listen",[])}think(){this.client.sendApiCall("think",[])}interactiveidle(){this.client.sendApiCall("interactiveidle",[])}interrupt(t){this.client.sendApiCall("interrupt",[t])}changeLayout(t){this.client.sendApiCall("changeLayout",[t])}changeWalkConfig(t){this.client.sendApiCall("changeWalkConfig",[t])}setVolume(t){this.client.sendApiCall("setVolume",[t])}changeAvatarVisible(t){this.client.sendApiCall("changeAvatarVisible",[t])}switchInvisibleMode(){this.client.sendApiCall("switchInvisibleMode",[])}destroy(t="user"){this.client.sendApiCall("destroy",[t])}init(t){this.client.send({type:"init",config:t})}}const VIDEO_PROBE_BASE64=["AAAAIGZ0eXBpc29tAAACAGlzb21pc28yYXZjMW1wNDEAAAO5bW9vdgAAAGxtdmhkAAAAAAAAAAAAAAAAAAAD6AAAAaEAAQAAAQAAAAAAAAAAAAAAAAEAAAAAAAAAAAAAAAAAAAABAAAAAAAAAAAAAAAAAABAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAgAA","AuR0cmFrAAAAXHRraGQAAAADAAAAAAAAAAAAAAABAAAAAAAAAaEAAAAAAAAAAAAAAAAAAAAAAAEAAAAAAAAAAAAAAAAAAAABAAAAAAAAAAAAAAAAAABAAAAACHAAAAeAAAAAAAAkZWR0cwAAABxlbHN0AAAAAAAAAAEAAAGhAAAEAAABAAAAAAJcbWRpYQAAACBtZGhk","AAAAAAAAAAAAAAAAAAAwAAAAFABVxAAAAAAALWhkbHIAAAAAAAAAAHZpZGUAAAAAAAAAAAAAAABWaWRlb0hhbmRsZXIAAAACB21pbmYAAAAUdm1oZAAAAAEAAAAAAAAAAAAAACRkaW5mAAAAHGRyZWYAAAAAAAAAAQAAAAx1cmwgAAAAAQAAAcdzdGJsAAAAx3N0c2QA","AAAAAAAAAQAAALdhdmMxAAAAAAAAAAEAAAAAAAAAAAAAAAAAAAAACHAHgABIAAAASAAAAAAAAAABFUxhdmM2Mi4xMS4xMDAgbGlieDI2NAAAAAAAAAAAAAAAGP//AAAAOmF2Y0MBZAAy/+EAHWdkADKs2YAhwPGmoCAgKAAAAwAIAAADAYB4wYzQAQAGaOl4GXLA/fj4","AAAAABNjb2xybmNseAABAAEAAQAAAAAUYnRydAAAAAAAAsOgAAAAAAAAABhzdHRzAAAAAAAAAAEAAAAKAAACAAAAABRzdHNzAAAAAAAAAAEAAAABAAAAYGN0dHMAAAAAAAAACgAAAAEAAAQAAAAAAQAACgAAAAABAAAEAAAAAAEAAAAAAAAAAQAAAgAAAAABAAAKAAAA","AAEAAAQAAAAAAQAAAAAAAAABAAACAAAAAAEAAAQAAAAAHHN0c2MAAAAAAAAAAQAAAAEAAAAKAAAAAQAAADxzdHN6AAAAAAAAAAAAAAAKAAAdhgAAAMQAAACAAAAAfAAAAHwAAAJ1AAAAkAAAAH8AAAB/AAABFgAAABRzdGNvAAAAAAAAAAEAAAPpAAAAYXVkdGEAAABZ","bWV0YQAAAAAAAAAhaGRscgAAAAAAAAAAbWRpcmFwcGwAAAAAAAAAAAAAAAAsaWxzdAAAACSpdG9vAAAAHGRhdGEAAAABAAAAAExhdmY2Mi4zLjEwMAAAAAhmcmVlAAAk421kYXQAAAKuBgX//6rcRem95tlIt5Ys2CDZI+7veDI2NCAtIGNvcmUgMTY1IHIzMjIzIDA0","ODBjYjAgLSBILjI2NC9NUEVHLTQgQVZDIGNvZGVjIC0gQ29weWxlZnQgMjAwMy0yMDI1IC0gaHR0cDovL3d3dy52aWRlb2xhbi5vcmcveDI2NC5odG1sIC0gb3B0aW9uczogY2FiYWM9MSByZWY9NSBkZWJsb2NrPTE6MDowIGFuYWx5c2U9MHgzOjB4MTEzIG1lPWhl","eCBzdWJtZT0yIHBzeT0xIHBzeV9yZD0xLjAwOjAuMDAgbWl4ZWRfcmVmPTAgbWVfcmFuZ2U9MTYgY2hyb21hX21lPTEgdHJlbGxpcz0wIDh4OGRjdD0xIGNxbT0wIGRlYWR6b25lPTIxLDExIGZhc3RfcHNraXA9MSBjaHJvbWFfcXBfb2Zmc2V0PTAgdGhyZWFkcz0y","NCBsb29rYWhlYWRfdGhyZWFkcz04IHNsaWNlZF90aHJlYWRzPTAgbnI9MCBkZWNpbWF0ZT0xIGludGVybGFjZWQ9MCBibHVyYXlfY29tcGF0PTAgY29uc3RyYWluZWRfaW50cmE9MCBiZnJhbWVzPTMgYl9weXJhbWlkPTIgYl9hZGFwdD0xIGJfYmlhcz0wIGRpcmVj","dD0xIHdlaWdodGI9MSBvcGVuX2dvcD0wIHdlaWdodHA9MSBrZXlpbnQ9MjUwIGtleWludF9taW49MjQgc2NlbmVjdXQ9NDAgaW50cmFfcmVmcmVzaD0wIHJjX2xvb2thaGVhZD0xMCByYz1jcmYgbWJ0cmVlPTEgY3JmPTUxLjAgcWNvbXA9MC42MCBxcG1pbj0wIHFw","bWF4PTY5IHFwc3RlcD00IGlwX3JhdGlvPTEuNDAgYXE9MToxLjAwAIAAABrQZYiEACP/HVX/9Jx4AAADAAADAAADAAADAAKaAAADAAADABxIAAADAAADAgYAAAMAAAMAQbAAAAMAAApAAAADAAADAAADAAADAAADAAADAAADAAADAAADAAADAAADAAADAAADAAADAAAD","AAADAAADAAADAAADAAADAAADAAADAAADAAADAAADAAADAAADAAADAAADAABkEOXuPain0AAAAwADGOAAAnCVwB1gdgBRBxsFDAAJAA7Qgk1QAGJjj41H24u2v8L16bzd9WExiOcxt+AAACJuiPKnTkt78W9x4i/HpVtT4CHi0/B5P9UbeT6Ch3AAACy1IAfB6jJ4OCUy","vWkkgY/9Pd3lpe+hgFs/QHKAAEBUWPNT0PT7mqhPbBxPneArf6l9nliw3C1hP9VHPSLIkpWKAAADAAADAUuWqxALGzu0x4wENnFvB3t7P2SgAABEs/f207h8TR9hmOTgJwdWW3G3KatCQ9OKr2AABFeZoAPm9/U2M1dgVHD1FF2ZLwAABT2bNKSNBIFgw6sgqSj/POdR","GDLAS5cGEmvjIJofyPoAAq9DaiAFmRSe+IV0AYKa53ZjdWLpKjHPAAB77BxY3rbtRM+3PspjmQptJfGNMlT5zAAAdHQBg3JsUaqvPYJjTvAl2UNE+AzZnI0FchAACc462IcigQCR4n588pQvKSyxIjKmhgAAKScBMTqA/vaR9AmI960pgXsjMif0im3QQrZb4AFgkekG","SL7sXSNGpOX5i1s4AAADAPM4J9FjROm3ojTv93j45exr6P8McNiE2Wub48FOuj7PGGgABJ4Q5/vSjqKp7T8hQkUXxuF92M6AAABkQW/6EYT4W8E2EYnseyzTyRluE+GWcO40gks7Qo85SAlsxccwlBSncvI23YphxaSPTpTcLSTHOFzs4FngqucCjc2du4fjHZjvdPkf","A8/AAB7vGWAal52iRxkJv1WI+T7QPgdfP4UKs2bODUQUllX267IAAAMAAoEgTp8hTTPkX48zokAEI1xzu5WWnq/pKO8HKfagrb1y87zfMgACbpL9k9/xEKKGwasRDhLRRFSAABe5bhCWksSXC6ybByEROkYfxaEjlnVUyj22ABMcKYAAAG9DIXUBzyBJBZ2cjvMBi82G","7fe8rg7eAH4o2QutgB8fibV9+M7KdqMG38MJjYOnvEqO9ZqQfAAAEZ9pF7o3U7yOB7TBzcTl0a4THE/9QDUfagFSToXQwgEbUaiBm+HHiwAAibulH4B2S/F0TwMzwGPT88gn0xPamCxaUbJ3a83C3R/de6UKzd/hNTtcETMsjyo0fIYfR0I/tDx5MmWq2JLXzetFB0Qi","8egJ/33RIth2bpx/yDbQAA0ju5HFEfgmJ2vXU7Nj7lVE7GE6qBDmpVl9sThGHyzfUHYACLuzUkdYpokOeiqsYOTBvPMhXUMJB9Lgw7LXLhkEGJH4QY5wcqAAAASAz8Kwvkv75GR3OQcG14zOFM6vLCxUc/FuGN+nNMxbiPOYyY6SO1gBEL4o6b+igz+6Zq52a9FINl+8","8KfM8Pe0gwHi4P9dBoCYlOoKJ6n6uikxM+5lf1mvgjgdnlpcrae74z0jZQ94TrV69I371UOoFqRktFHRTdAAEiv8jpMAzdPh39MKGoN4bOTndd5Hr/B9QAoob6svdC8wPElCer0m+QQmYADAlry3suadFguRKHNz4/nk/AuSezsZ5EntL4+pl8Qf5FusbKf+NAk7pv/6","tKuK/edu4XUAAGCGjjjNk7pwX7gpZ2j8Gblg3hW1G8NrGxod+kuAAAhF9/cab1rG0Gxsrwtay1k3AkPyz5eoA875OKffOBw2YlLAAL019ghZ3WXpUU8Irt70/6bXzgEYd3jOjhkaWECMaDN3wc+krxGXAsvAKNanKCvOCpGCMfby/A1x6CUZ1jrLSKlakAAIZ4aCpLPI","BbM+XOQLVso7wFO+QAK2xqO27z8VW/8aN6tmK4XKq6qhch8mvLO99RH3VPrcDuHBJ/ikxOssjS8f/ZYHTTZDxY+NgSEp46AAAWKEpcPzJ+mf3WrElkVCPvDZ6oAAawUG1Wfa4+ftGkc299KaOkEdvWgRlAGrGUmQKuDCY9Df5u6bBfgABD28kDZRVXvPQQNTzCdMPwrA","rVQwmVD5v5/OPeaQd5rBupmDrMBk4f2YKIKMMmZUs9DgCmBp3ypejO22QkMREpQkwAAHJR+5LPkfHTjRtERikfI5KkAWVMKCDHm60OpYv0MO9kDHBSl0fIGR6FP6PZNQn1OTKSuxkwAOKIRcInPLYeAziAWlkQfG30Azl0tLvkY530imR/3zZLgL/auuI6xivm02jZw9","HMxagAkYY2r9sEcgAQkuAa5aV1IZtOasC6HNdAcn7yD1+sCag1aqOMBxb4ftI9GkrPIxBqO4QyatWXmnUIAAfAwMY3QLD9xOyNsH/gPKPb2GN4bb+HOGiyQ5IoUDN0XfLcQoN4ts5AB6wRwCufuaYBuf7KScvdThTABYsWmWg6MIoLhfOPWC0iDn2WqABmEjZgApOsdt","SxkbgN0L8wSjCYNWg0L3HQYYAASldcHRBvmS95//m6y6idyJ+EjGneRsKlPMVMnNyyEA2xJRFdIvCgAAVRV9xOHpKzbhiyEaxSLA7UErEeAFAD5QVYayP47Vmkpy0X10kaeZ/VL/PBimNL9i2GnlRDEFAE6gWLnXSkUdNEN+44++N3IKaHUWXOeR8KZ0IAsOKh2erntR","e1GiOBv7bb4GpXSUfYlEESDYG93j5dQb6DBRYGPjqUMZytBAdL68qPNG0/dMxNSSmUC0dAgGGARCiFyrdUjWLikujLzsUE+TqBbuZ54jlG4amIcPStPy1nw5AADT1Sjq/no95ZGjszXjhGNclUM1eJvLYAOQzfMjFXtDv3H5mkeiS5zE565LzH9dvjiLO+eBoVGtPznU","UAwtXP/UPxP3w/4+AEX4nQ5qH3uSjdhic71oXogEji69DwotyO/5/woZF3yonfFgBNlm0ueG9N3eCHDeW3N/d4Ru7NDA5KvqVbvZKmFG3j/lIw/gYKmm4RGMcR7LX1V08B+Pq4ACTGN1er7/wIoHogrDkQEIy8vvT7hEkOyedFGLAeiYdI1VtqVm4cevbmyCANQ4AAnu","64Nw5kUJ7ra/lmmA65WpsPXqaY6ejJ9qwqU67GUq2lekapQqRG7vUrd/VhSavytuZoG5EgAACuTCVlqr0YrjWWdChZnPCeAc6FnDdorJbsmI7qzuPrt4+AoAFMSIBwSg/NUC579QZNa5t1A6sOOU43E8peL6YodhifylgbhvTvzUFz+xJkk9hPAAAXpAoUIwuR991FMQ","LcBpxQt9EQbN8NYixYNO6kM6zAD5DU9vH2OiBU2CEMaWKKVgCgk7LyB6/4jiSqrSmMMkMzmtr2Ku8kearYX4wh2p5OYYAAKqhVI+NHKeeSnHE7kn7eSmfy5zByV+f5iXX/hTM0Yst5YcuTatzS65vxw/nTaVlFAk28lbUSYQGXXmQ9eC9OfKJpG9//fDdo8I8eWtLU71","tyvprE1iHazeOk0lrDJgAAAZwH2MkGICOKptWDE/t9pciEN+8GL8YZsfZK7cyUDkqp+vLljDCWrgEomORu1KREe9fY/hYki9ix/voLyyi7Zj6UOKCIxeHZggkTZqfx6UP1e2a23ZVXGAAACdDKGn4J1wlZVewql/WWeHbNApHXsa7dAx6C5WgAl4HjMpAAmlfJRyOevE","wVf0oZjpHxd5WM5P9m//by3bfphoZ6TXI0Vw33EU/HExV+qgx9YAABi5ERRDSeHcZkXPh9CvYfb7HvZ6wg/93XG7dDECTtYk661jUUhoGP1LY08KyNhSTwISSkLODdDD381QlKT2kvXOhMZsCprC8LBv3wDv1GMwg3ZwAAAFQSCh8jlPrXAJmDF4HIlxHUjuxkgkJdei","cS1iabx/xSAQophqjhEK/cW6L4Z7KrVSRuTOCTdm3GXnpH876L2ctr9+hn1L4cs5XfvlhMgAAFTc9PmKLeJhws4y+CZFHr770jYObO5szKiNaQtbYA2Z1ADVlT1gdh7KS/19fyfkhstiIFD3CXyJCFpGQeuC79i5/KSUienXQ3z1fTtVJCO1YrgAeSiCdg+rLLpHhkHn","g2gkRry8T91t87lHklCkPXl/JW7wwW3kxrjOk4GORcukFlg/wKtwF9TJZubscnmjUFt5L+UO3QRDw2+RQO2jcPtg7WJaexDb+bKLpsSuyAABLGxLzlBupAGJuyXq9RQGJ75yG/EcSzDCTNvaGS03qKa1F3VwDDKI6Alnqi9+0uAAYnGG+0E6UC+FniWah6s3tGi8Kyj1","wL50anznYbpIicpKEIh7VJud5231ZyVyTJKCCoEAAY5f2m7QxQd+o8NElsgg8F6kBtSRgeV/MSJYWF2o1SGTIfrHSNygAAeNupbd0vcywt0zMqSkiIDuAY9JybhMCw+rl9tfHAKQ63x9mEtywoKs3hh5gAO35wyIdXkD7JDV/CWKMSFwP9RpIGOkggSP+QgCVXh/Sedj","wJ9a9qAAr8ZmE10M2aHjjLyFJTQS7geuFHnj8ZD3wL6Yl24fH9f29qJQ9hNVhKyuaXggAAKqB9h791oBa8AxtsB8qjZgUFRjR49vt+eIcgBBozt7xwUCgUAAej+cp/reCIR1Fa19qFlgUM7UQGURldAASkIbfzAk6BpCg7G8zGjoPghwKnlWKWb3jHJWBrIcDWRj4Egl","CgCe2HwYZ4WC/TtaargTsEf8nvvHsg1h5cEIlJmMwItooRktPCo6uxcVQ2OG71PxbIAABFzJ6ld3r2sn59LfZcaSQNMQ/34p2A6uAbANgilIiv9zkZKvvd4R9DgAxiCPQXy4QTXjEkYwlIScuDlqZ264XR8XuA0kaYzvdrAN5zOqqTFyAGzJgAe0eKCdoddnZ0g0AAAn","69CDaOZ1ksreJ2QP0gciKe2w++YGDb5iBRWp+EVxaAcZ64PBbwUgLyNl7WeS2LnCDzd0EedwOJwrYRx7fZ3a1HZNbzBtLtBWKU4EwWAACcoouqPbYNFH61K4grSUGi86W/42NsCAXOayOJVWrjPbw0WAA9UQcR9iLFE5RJRzJ2CqSEcUsk+5pQv5LkWcIuB4oc+7mnwp","JV8F7ffg/NYgAIPB7jlSGtNVPqgGhnN0WmDqpAy5eQLCCPl0ZWMeTxwCtkSb82WAAkM+cDV59zTTSFLC0aVeSqi1qO+YvK/kNBYdFwFe8+KeTIQAXxXarEkWADMUy4yeN7IQJbibWnGtqm6B+mFIFKsgsGFdT7Te6aUK9UZFEb3Do53sAAQrEYcmmTBcvWbPbeX+96Gq","cRnlT/WeuezL/e8g0LTZbSy8VmYEVHtAADRYGcjVAsVDPfqpJX5pxPzcwGBsXyiVQe0JuBT+sMvCwQmWvXZuwBCbKurXo0sdUUexp7fNd5ZrTcojj2LkqgNhSrPrei6odRJS/jQAAD82aVmqD4/tEdFkbismt77uF58PCh3NhTKCBe6z9hbHdXLWpjoZFD83K6QHj5r2","1Iu3gSpAAAjvTvaSBaFzSmSjNRZK0x8WNuZF1hfS6rIfcx2l+g/LEsvAAACq/QPvNe1o9CasI+JZqYQxEIpXxoS78WIZaVNB+UTNo4CUC9pmmmIUoZ6ap8M8YlgroAQIME+AAAtunynbGeLJmZDHXRPJxAvv9HhdNoAKnAVpeLCA2PHpNk+istp+xjyIQiWhV5oATi4X","cnSyBXYX6I8O1aT4CfwAfugtyAGYvY4g2aVdzeCU7l/17AAEzdKoq0U74eT1mto+xMzrV5AG9wm8TbZxKOmzh2hO0YSYcFKQ+nRAjzePV8IABkfE4Eo/rnJ7Td5W/qs9ILfsinAL1MWXiOAXLBAyGBeETZ0hJWt/HtyWVUWAABs/g6q4lK1LJ0iIMLr0nA9i/AESH8XT","1+7jEcAdTNcWaScL8u37enZBAFSP9rKlRX2brKAAUuNwu+oiTJBASqVVAd1EpO1Aho5bgAW1n/xpQdTxFVU3ulFnT/wWXpYzqstiQztQABOXTaO9Eciin9J0YVSBrDckxjdby0NZrfqNegABSpQaSasAxfI1l3GJ/i5M0rJLPXRI74oTKakD6WbfMGDtSP5qzf9V7vFA","Y1UKDyC+NRPdd3S0b+rhf87dbAAASpMWkrjpajxSXuOsyCBgJ2kLhnA3Xa2G3Lue2AG3R4NgSTZRgCR5LTVLVqPyscnkwXDQkAEgASN6DP2R80rN0mvi8V/D1AcP1ePS4uAGTfHrwB9n9JjltiYLZP1yCk/7nVEkDmAd454g2M8xPscYU3py/HSetBe7X7evW9f+4gPC","9e4LUABZbrGzGcUvzotdb832Uzu0Q1xytj7nWJdY7L0KJOXVaABqUr2qG2th43i9OUECJy8ONoBpVmGa920C/AA7PH4am1DvXVvyLo3ix5/atW+FdwAAcbZ5/hxMAU+3cYwB1bY1vk6RZTQnLNzKHQABuiP1JbfOy9NFxdyEPqdjox9W5ktALJfcOcAQeEoXfmzs9N4+","TH+OLaIlr282zEGvoDBQaYcnuNYAAOyW/TstWHU5UyDs9raILV0FhjrAK+Rruqrjj2bTtFfTSyo0LUHsDm5HlKp4DXzG/9/1DRcNRAE1Wxl1dTa6HAAY5Yv4oeqf03tIH1GpXVlRgRBExnd7iADTLh3vVMU91xVYmhdy4xQFaki3Fk6Zdtbk38v8kdqAmOvGvS4wAAfW","0eXvxxYFDGF0WS2Riv6/JsKF0UnMq467S5y8rGczMwACIriauafKIwVTZ6Oi8f22uv5x5Tl3SE72Kl1xKAYTU+itbCIN8xTZhJdZf0rTuLo6uLkCpkrXNEknimnQI0m/wACfbJs6xneGaEmad7RjmA2AZ8DPVWY4o/6G3QAAAwHbyKgKPaSE3laBe86egCcCJvPj10LS","oaXfVzRnVUvBJn0N5AdqyK1gA7ecpdAXKzyhwd7azcXJQQQTADWJggTjPFT9wD7oIb8Xo0sGkrI9k6lSuDUKgB2KIVBMMwYecMD1JJ24JTmIVzuOjABjFLPS5JWrwpv4pnUlgXLtL25pDg8WAAL9QT+ba5hqXlx3qDzNw75ffP4hz94B9/3aJ7whvhjM6bv/mOziv//+","G1+aAkn0qZwAA2hGrpR9TYtSFPi+krphtyWMQAAE/z7Szty1w8wuX6f2mSjvC6Mip/MCG6HzzOTm9bSGzC3QvlwRtQMADZNhtMHuqfxNJ8lpEDdzKWNO8hRb/4nVRLYAAIeRcUP1Pza39r7snbxMRFAZAVp9KdqADiGw9MF1moq4Tns3lkf+3i1ddREGFLhfQT+asAAE","HbOaAmamxLHLfIxfAMhBqMvvmnziZAAlLyptJkG6v0KLbmMeiIs6rrpdjUGHTKgkzvRMG8NNZFJRp69d69mudUQd/GEQs4ADkNoKQOn3/9zt744FijS0Z17uz2guy7wABInf9ERhsdKQV0FJvkKNdMryzbKwK5mnakAtzNitRJa/9upagVo9HkuKQmHE54EZWLUBYGQA","BQPiMhOZOhtobNy7e/bJOP8J/mW54hWSzHKXAAIqIFI/VCYpAB75PRYWVewfLQtPXwvj+6UhuZQMcyDI5bS36a3ICOZnBWk9j8IJaUzljK2Dt3fAANsmr6YWnclVKK5o1j+nRLxGDpBAY2SZPtwXF+LpJ0oAABUlWPoxC2dpTVYSvFSTGXUAIAg6sHJOjLnrmAlxS1eP","xdcaOD4pC0R9lltDuOeQSQpZx7YAAAMBwhQoCki/3JMK+AVEtuCcIp0tVUI13CQJRGrxmK5eVgAB4T9fWchKHk+XEgUZkOu7ef9ZE8UVxM4nzmLuKUACaGgA5QVcGVq3EnoLKzFILaNa2hRJ8e72egAAEjT49Nl8bg7QItJWA3ylklVBlZiVqamCoQGVoQAAGwL6qbrm","ymv1mdN6UmoTtCYVYn1nWnWIB+gx9AAAAwJqXWE2NZnHtxHTxN6qmfvgsxV6X5V3lxVmFlJLKGsSfPvgAAGl4K/ak6NpVXN3TOg7kwdAS/pQ2+pYAAADAo6ZzhmltQYbFBR2k25g6N/e0bInvsVRWgoYGgZhK7wBcnn/aafImfm0l+3iI5hbJuRopkeJiMLRrgAAAwBo","hmqkVx0KNOb4qVZSHmEqDYpI3H6z0Zgrl9ykjXi9tdYgAAAakZWBUlk7QCaV8znUeVMXYmA4j6QAACXpbb5PxTbkpkFIVqz9XI9U+W2YEPLctPRsAXBgAAXO9wTAYAxi1E9joczpYplbAAAGgzTAFovrYu2XTtWfPay9f3ChgNpHTbqGF0W9eIcQqQEHgBBrJ3c1oxcy","ZHiZ99s37xMueRukd7AAABAP25WReHwv2YUOOkVSUEyG+Vi2lSQrQnFI8tAD/JAAAFZSGzDixx/k81yCC/p12uiQ5dqxcY3OcwXtN0a5gAABBxbZHPSZPMM25fBXNonhEF+H61l1fTv+zh/yeAUCaDE4MmM/U3KJWtQ+gsQTdI4TBgAAAwEEJxYz6NhkqZPBrEIYqXgi","Qgn82rqA4MAAAAmlw7m8NGqWGaa3rsfgRaGYS/Q022vRgyVSmfzH5wAVVDlwxUmJSW0KJ7LJlvYARyZZOi3gQjE363bsBYql2V/604y5QHkkyXbAfMLqIm3cr6J6gcvx9T2uf/cAAAMAAAMAoLTggjJCl6ZfP+GSCCLMESY06TFLs1Ocq9n/9HS9XjyUGrIjqiVcDTy7","+fVDMVrEtgKO/HfAAACSrLxGaaTGqL0vmQkOG3H/Ecu3y2Kd8CR+A37rOM2jO2L5rFsAAAMAAAMBODYHof2+xChTk2F1T95hlGsKrhfF5gFDiA+P0pYsFYhLhMxyIwACXcstK+FFdo3+4YJc/MaI0R43OfmAnbUc2dRX/dwAOYYui/tptTcafY8B10kjWBoAAAMA6hx8","/8pkpHguZnOIb/CGJuS5QBLTOMG0ZGMf9ZJPQDsogAGLVecrjuOxZ4zFBmzarqvTs5q0xDigunmUkBo3nuMFTXGR+cdVkM+M2AAAAwGLPwktiudEcFI6PSeBs8Z2kpvY277jVAAAAwH/uoOBn/n++0usA3Zxuc416ugy4NHoHm72rShRkuESu3aAAAADAAiuk9Q6FbVo","AAFl/pyEboOvAAAAwEGaJGxCPwAAAwAAAwAAAwAAAwAAAwAAC1V0Dm3MAAADAAGKVPoDdcEwImbhwAAIincfaIP5JBZqnQ035V7HU70SvyUQbDOaqwAFEGgTbHFrB4If711OAAADACs5nS7Q+a9yV7E4h0Ez1uBP3EfsAkhQH0/6NXQtgACBym+P6AAKGKRlAAGhLAPY","bXgwjYYLPdAAADZY0AH6akAAAAMAAAMAAAMAAAMAAAMAAL3zUpNAAA5q0b2AAAADAAADAABXwAAAAHxBnkJ4jf8AAAMAAAMAAAMAAAMAAAMAAAMAAAMAAAMAAAMAAAMAAAMAAAMAAAMAAAMAAAMAAAMAAAMAAAMAAAMAAAMAAAMAAAMAAAMAAAMAAAMAaH9F8l9fAAAD","AAADAAADAAADAAADAAADAAADAAADAAADAAADAAADABZRAAAAeAGeYXRF/wAAAwAAAwAAAwAAAwAAAwAAAwAAAwAAAwAAAwAAAwAAAwAAAwAAAwAAAwAAAwAAAwAAAwAAAwAAAwAAAwAAAwAAAwAAAwAAAwAAAwAAAwAAAwAAAwAAAwAAAwAAAwAAAwAAAwAAAwAAAwAA","AwAAAwDpgAAAAHgBnmNqRf8AAAMAAAMAAAMAAAMAAAMAAAMAAAMAAAMAAAMAAAMAAAMAAAMAAAMAAAMAAAMAAAMAAAMAAAMAAAMAAAMAAAMAAAMAAAMAAAMAAAMAAAMAAAMAAAMAAAMAAAMAAAMAAAMAAAMAAAMAAAMAAAMAAAMA6YEAAAJxQZpoXpaJgI3/AAADAAAD","AAADAAADAAADAEK7uW0HwlxaLod+8n9y2dE25CO0wjUkJGVbDJkwS8LCJUO7zdUKaJbTaq9M7+8ELtuVY1lZ/btIu3li6IjY+Ov66jvRBrqSFDjfbyhKleZR+9UlVZZpse5gdDl8MHUwwfzGYregw2423ZUw7Sn97g8RMf7SHQTXwRF7j/fkwGYUSkpmG9qWg1wS5TUK","VFk5M0SKYRgM8CySrhljPGdo9wvkw7uTbVjt2sKEXEIW8MI2esm0VrD+S7cJXtCVWSMO8IXxanrG5COpq6ZBzvfJ6ymDX6iDoAobTICelsgb2WAIHUtlm1f3rGKuyef0Yf94xekDEmlqqRdsZCYl/hAPZll1awBIKvHqkOOaNHoUQ62/emowbfJvP8fe2zjtdnDey1cs","pjpqOFSbjASkUO83ddc9652op2XltZTWa56Wr2cwUBxIx4W+ad6vdIGrwb1hZS1r65BGAzj+/F6uKOyG4RGC0lLE3NetVXhrogaPBoQwSdt89QFY3qGVAIgFqvucRcWLey4lhk557q2MjSz9jcPjGiw9PzwRTa30dLDkktwSEI/ZwQCZfi/acZFD8yunv14AYtypuBoY","vVceexnkeMEiRBFm0DIKp82mnZe1zehd/WlQSVJSqovoFvqZHgb07LtiLneXBF53QZEMxH0jfBCj/H90s/rz1CVEvjKAc/kdkjmmhr3ASGRcfBtqVn44UEkIzM/fO6Chqxv7ZW+Ig1jla7pjCRmOE12qPIXGW74zBcIRSpdqo+3cseFFrvQFFcPwAAADAAADAAADAAAD","AAADAAADAAAl4QAAAIxBnoZuUTG/AAADAAADAAADAAADAAADAAAdTB+gAAADAAAGx/ThJHkg+TwAAAMAAAMAAAMABuNmEeAGAA4H75AAwkuAAAAHMY3sAtntw3YegAAAAwAAAwAAAwBbO3gyAzAAAAMAAAMAAAMAAAMAAAMAAAMAAAMAAAMAAAMAAAMAAAMAAAMAAAMA","AAMCTwAAAHsBnqVpEX8AAAMAAAMAAAMAAAMAAAMAAAMAAAMAAAMAAAMAAAMAAAMAAAMAAAMAAAMAAAMAAAMAAAMAAhyDSQqCJgAAAwAAAwAAAwAAAwAAAwAAAwAAAwAAAwAAAwAAAwAAAwAAAwAAAwAAAwAAAwAAAwAAAwAAAwAAD/EAAAB7AZ6nbkX/AAADAAADAAAD","AAADAAADAAADAAADAAADAAADAAADAAADAAADAAADAAADAAADAAADAAADAEO2/cAPCTpcAAADAAADAAADAAADAAADAAADAAADAAADAAADAAADAAADAAADAAADAAADAAADAAADAAADAAADAAG9AAABEkGaqUmltSYAi/8AAAMAAAMAAAMAAAMAAAMAU1eb25GTW/axz5g6","EYyReAAAK0G/1DwhHeAA5o1vLjsc2UIAFfG3Z3xdmYOiZZV+6V+frSCRE4N7MdfTkM8mKNUaQ7EmcIWLwnNbMLbV6AFLHIFO35ifNoCOrdZoAB1drW6Gb1R/Z/IBXyR0svRZbRI3eud6M2QYuh05mAR8pwtlg09krtIl6gBwCymZNCRhJGaUUWgQYKTJ0LXNGiHgHsdp","vA4X3aZpTFo2nCabF49whgE0JXAAAAMAAAMAAB490CVcyvQos44EACAVEU28wX7/HBFRAAeQWxupPrMDRdBQAVFFMctkYAAAAwAAAwAAAwAAAwAABBw="].join("");function isAndroidPlatform(){const t=(navigator.userAgent||"").toLowerCase();return/android/.test(t)||/openharmony|arkweb/.test(t)}function checkSecureContextSync(){const t=window.isSecureContext;return{name:"secureContext",supported:t,severity:"fatal",reason:t?void 0:"当前环境不是安全上下文,请使用 HTTPS 或 localhost"}}function checkWebGL2Sync(){try{const t=document.createElement("canvas").getContext("webgl2",{failIfMajorPerformanceCaveat:!0});if(!t)return{name:"webgl2",supported:!1,severity:"fatal",reason:"浏览器不支持 WebGL2"};const e=t.getExtension("WEBGL_debug_renderer_info");return{name:"webgl2",supported:!0,severity:"fatal",detail:{version:t.getParameter(t.VERSION),vendor:t.getParameter(t.VENDOR),renderer:t.getParameter(t.RENDERER),gpuVendor:e?t.getParameter(e.UNMASKED_VENDOR_WEBGL):void 0,gpuRenderer:e?t.getParameter(e.UNMASKED_RENDERER_WEBGL):void 0}}}catch(t){return{name:"webgl2",supported:!1,severity:"fatal",reason:"WebGL2 初始化失败",detail:t}}}function checkAudioSystemSync(){const t=void 0!==window.AudioContext||void 0!==window.webkitAudioContext,e=void 0!==window.AudioWorkletNode,n=t&&e,r=void 0!==window.MediaSource,i={pcm:{supported:n,hasAudioContext:t,hasAudioWorklet:e},mse:{supported:r,hasMediaSource:r}};return n||r?{name:"audio",supported:!0,severity:"fatal",detail:i}:{name:"audio",supported:!1,severity:"fatal",reason:"音频播放能力不可用:PCM(AudioWorklet)和 MSE(MediaSource)均不支持",detail:i}}function checkWebCodecsSync(){const t=void 0!==window.VideoDecoder,e=isAndroidPlatform();return{name:"webcodecs",supported:t,severity:"fatal",reason:t?void 0:"浏览器不支持 WebCodecs VideoDecoder API",detail:{hasVideoDecoder:t,isAndroid:e,hardwareAcceleration:e?"prefer-software":"default"}}}function checkVideoDecodeSync(){const t=void 0!==window.VideoDecoder;return{name:"videoDecode",supported:t,severity:"fatal",reason:t?void 0:"浏览器不支持 WebCodecs VideoDecoder API"}}function checkWorkerSync(){const t="undefined"!=typeof Worker;return{name:"worker",supported:t,severity:"fatal",reason:t?void 0:"浏览器不支持 Web Worker"}}function checkCapabilitySync(t=!1){const e=[checkSecureContextSync()];t?(e.push(checkAudioSystemSync()),e.push(checkWorkerSync())):e.push(checkWebGL2Sync(),checkAudioSystemSync(),checkWebCodecsSync(),checkVideoDecodeSync(),checkWorkerSync());const n=e.filter(t=>"fatal"===t.severity&&!t.supported).length;return{supported:0===n,fatalCount:n,warnCount:e.filter(t=>"warn"===t.severity&&!t.supported).length,items:e}}async function checkWebCodecsDetailed(){try{const t=void 0!==window.VideoDecoder;if(!t)return{name:"webcodecs",supported:!1,severity:"warn",reason:"浏览器不支持 WebCodecs VideoDecoder API",detail:{hasVideoDecoder:t}};const e=isAndroidPlatform(),n=2160,r=1920;let i={};const s=["avc1.42E01E","avc1.4D001F","avc1.64001F"];let a=!1,o=!1,l=!1;for(const t of s)try{const s=await window.VideoDecoder.isConfigSupported({codec:t,codedWidth:n,codedHeight:r}),l=!(null==s||!s.supported);l&&(o=!0);let c=null;if(e){try{const e=await window.VideoDecoder.isConfigSupported({codec:t,codedWidth:n,codedHeight:r,hardwareAcceleration:"prefer-software"});c=!(null==e||!e.supported)}catch(t){c=!1}c&&(a=!0)}else l&&(a=!0);i[t]={default:l,software:c}}catch(e){l=!0,i[t]={default:!1,software:null,error:"probe-failed"}}const c=e?a:a||o;return{name:"webcodecs",supported:c,severity:"warn",reason:c?void 0:l?"WebCodecs 声明支持度探测异常(运行时将以实际视频配置二次确认)":e?"Android 不支持软解码(prefer-software 声明不可用)":"WebCodecs 声明不支持 H.264(默认/软解配置均不可用)",detail:{hasVideoDecoder:t,isAndroid:e,hardwareAcceleration:e?"prefer-software":"default",codecSupport:i}}}catch(t){return{name:"webcodecs",supported:!1,severity:"warn",reason:"WebCodecs 声明支持度探测失败",detail:t}}}const VIDEO_PROBE_TIMEOUT_MS=2e3,VIDEO_PROBE_MIN_FRAMES=2,VIDEO_PROBE_LAST_FRAME_INDEX=9;function base64ToArrayBuffer(t){const e=atob(t),n=new Uint8Array(e.length);for(let t=0;t<e.length;t+=1)n[t]=e.charCodeAt(t);return n.buffer}function probeVideoDecode(t,e){return new Promise(n=>{let r,i,s,a,o=null,l=!1,c=null,d=0;const h=Date.now(),u=()=>Date.now()-h,p=t=>{var e;l||(l=!0,null!==c&&clearTimeout(c),null==(e=o)||e.terminate(),n(_extends({},t,{primaryConfig:i})))};try{o=new Worker(t)}catch(t){return void p({supported:!1,reason:"视频解码探测 Worker 创建失败",frames:d,duration:u(),detail:t})}let f;o.onerror=t=>{p({supported:!1,reason:"视频解码探测 Worker 运行时错误",frames:d,duration:u(),detail:t})},o.onmessage=t=>{var e;const n=null!=(e=t.data)?e:{};var o,l,c,h,f,m,_,g,y,S,A;if("frame"===n.type)return d+=1,(null==s||null==a)&&(s=null!=(l=null==(c=n.frame)?void 0:c.codedWidth)?l:null==(h=n.frame)?void 0:h.displayWidth,a=null!=(f=null==(m=n.frame)?void 0:m.codedHeight)?f:null==(_=n.frame)?void 0:_.displayHeight),null==(o=n.frame)||null==o.close||o.close(),void(d>=VIDEO_PROBE_MIN_FRAMES&&p({supported:!0,frames:d,duration:u(),codec:r,width:s,height:a}));"configSupport"!==n.type?"error"!==n.type?"done"===n.type&&d<VIDEO_PROBE_MIN_FRAMES&&p({supported:!1,reason:`视频解码未输出足够帧(${d}/${VIDEO_PROBE_MIN_FRAMES})`,frames:d,duration:u(),codec:r,detail:{done:!0}}):p({supported:!1,reason:n.error||"视频解码失败",frames:d,duration:u(),codec:r,detail:n}):(r=null!=(g=null==(y=n.configSupport)||null==(y=y.config)?void 0:y.codec)?g:r,void 0===i&&(i={hardwareAcceleration:null==(S=n.configSupport)||null==(S=S.config)?void 0:S.hardwareAcceleration,supported:!(null==(A=n.configSupport)||null==(A=A.configSupport)||!A.supported)}))};try{f=base64ToArrayBuffer(VIDEO_PROBE_BASE64)}catch(t){return void p({supported:!1,reason:"视频解码探测片解析失败",frames:d,duration:u(),detail:t})}o.postMessage({type:"decode",file:{data:f},start:0,end:VIDEO_PROBE_LAST_FRAME_INDEX,hardwareAcceleration:e},[f]),c=setTimeout(()=>{p({supported:!1,reason:`视频解码探测超时(${VIDEO_PROBE_TIMEOUT_MS}ms)`,frames:d,duration:u(),codec:r})},VIDEO_PROBE_TIMEOUT_MS)})}async function checkVideoDecodeDetailed(t){const e=isAndroidPlatform(),n=t||"default";if(void 0===window.VideoDecoder)return{name:"videoDecode",supported:!1,severity:"fatal",reason:"浏览器不支持 WebCodecs VideoDecoder API",detail:{isAndroid:e,hardwareAcceleration:e?"prefer-software":n}};const r=e?"fatal":"warn";let i;try{i=(await Promise.resolve().then(function(){return streamingVideo})).workerURL}catch(t){return{name:"videoDecode",supported:!1,severity:r,reason:"视频解码探测模块加载失败",detail:{isAndroid:e,hardwareAcceleration:n,error:t}}}const s=await probeVideoDecode(i,n),a=s.primaryConfig,o=e&&void 0!==a&&("prefer-software"!==a.hardwareAcceleration||!a.supported),l=s.supported&&!o;return{name:"videoDecode",supported:l,severity:r,reason:l?void 0:o?"Android 不支持软解码(prefer-software 声明不可用)":s.reason,detail:{isAndroid:e,hardwareAcceleration:e?"prefer-software":n,declaredSoftwareSupported:null==a?void 0:a.supported,probeCodec:s.codec,outputFrames:s.frames,outputSize:null!=s.width&&null!=s.height?`${s.width}x${s.height}`:void 0,duration:s.duration,cause:s.detail}}}const WORKER_CHECK_TIMEOUT_MS=3e3,WORKER_CHECK_MAX_ATTEMPTS=2;function probeWorkerExecution(){return new Promise(t=>{let e=null,n=null,r=!1,i=null;const s=s=>{var a;r||(r=!0,null!==i&&clearTimeout(i),null==(a=e)||a.terminate(),n&&URL.revokeObjectURL(n),t(s))};try{const t=new Blob(['self.postMessage("ok");'],{type:"application/javascript"});n=URL.createObjectURL(t),e=new Worker(n),e.onmessage=t=>{s("ok"===t.data?{status:"supported"}:{status:"failed",reason:"Web Worker 执行异常"})},e.onerror=t=>{s({status:"failed",reason:"Web Worker 创建失败",detail:t})},i=setTimeout(()=>{s({status:"timeout"})},WORKER_CHECK_TIMEOUT_MS)}catch(t){s({status:"failed",reason:"Web Worker 异常",detail:t})}})}async function checkWorkerDetailed(){if("undefined"==typeof Worker)return{name:"worker",supported:!1,severity:"fatal",reason:"浏览器不支持 Web Worker"};for(let t=1;t<=WORKER_CHECK_MAX_ATTEMPTS;t+=1){const e=await probeWorkerExecution();if("supported"===e.status)return{name:"worker",supported:!0,severity:"fatal",detail:{attempts:t}};if("failed"===e.status)return{name:"worker",supported:!1,severity:"fatal",reason:e.reason,detail:e.detail}}return{name:"worker",supported:!1,severity:"warn",reason:`Web Worker 创建超时(已重试 ${WORKER_CHECK_MAX_ATTEMPTS} 次)`,detail:{attempts:WORKER_CHECK_MAX_ATTEMPTS}}}async function checkCapability(t=!1,e="default"){const n=checkCapabilitySync(t);if(t){const t=await Promise.all([Promise.resolve(n.items.find(t=>"secureContext"===t.name)),Promise.resolve(n.items.find(t=>"audio"===t.name)),checkWorkerDetailed()]),e=t.filter(t=>"fatal"===t.severity&&!t.supported).length;return{supported:0===e,fatalCount:e,warnCount:t.filter(t=>"warn"===t.severity&&!t.supported).length,items:t}}const r=await Promise.all([Promise.resolve(n.items.find(t=>"secureContext"===t.name)),Promise.resolve(n.items.find(t=>"webgl2"===t.name)),Promise.resolve(n.items.find(t=>"audio"===t.name)),checkWebCodecsDetailed(),checkVideoDecodeDetailed(e),checkWorkerDetailed()]),i=r.filter(t=>"fatal"===t.severity&&!t.supported).length;return{supported:0===i,fatalCount:i,warnCount:r.filter(t=>"warn"===t.severity&&!t.supported).length,items:r}}const OPUS_FRAME_DURATION_US=2e4,ENCODE_TIMEOUT_MS=2e3;function buildAudioEncoderConfig(t){return{codec:"opus",sampleRate:t.sampleRate,numberOfChannels:t.channels,bitrate:t.bitrate,opus:{format:"opus",frameDuration:OPUS_FRAME_DURATION_US}}}class WebCodecOpusEncoder{constructor(t={}){this.encoder=null,this.isInitialized=!1,this.pendingEncode=null,this.timestamp=0,this.config=_extends({sampleRate:16e3,channels:1,bitrate:24e3,frameSize:1600},t)}static async isSupported(){if("undefined"==typeof AudioEncoder)return!1;try{var t;const e=await AudioEncoder.isConfigSupported(buildAudioEncoderConfig({sampleRate:16e3,channels:1,bitrate:24e3,frameSize:1600}));return!0===e.supported&&(null==(t=e.config)||null==(t=t.opus)?void 0:t.frameDuration)===OPUS_FRAME_DURATION_US}catch(t){return!1}}async init(){this.isInitialized||(this.encoder=this.createEncoder(),this.isInitialized=!0)}async encode(t){if(!this.isInitialized||!this.encoder)return Promise.reject(new Error("WebCodecOpusEncoder 未初始化"));if(this.pendingEncode)return Promise.reject(new Error("WebCodecs Opus 编码器仍在处理上一音频块"));const e=new Int16Array(t),n=this.timestamp,r=Math.round(1e6*t.length/this.config.sampleRate),i=n+r,s=r/OPUS_FRAME_DURATION_US;if(!Number.isInteger(s))return Promise.reject(new Error("PCM 音频块无法按 20ms Opus packet 完整分包"));const a=new AudioData({format:"s16",sampleRate:this.config.sampleRate,numberOfFrames:e.length,numberOfChannels:this.config.channels,timestamp:n,data:e}),o=new Promise((t,e)=>{const r=globalThis.setTimeout(()=>{this.failPending(new Error("WebCodecs Opus 编码输出超过 2 秒"))},ENCODE_TIMEOUT_MS);this.pendingEncode={startTimestampUs:n,endTimestampUs:i,expectedFrameCount:s,chunks:[],resolve:t,reject:e,timeoutId:r}});try{this.encoder.encode(a),this.timestamp=i}catch(t){this.failPending(t instanceof Error?t:new Error("WebCodecs Opus 编码失败"))}finally{a.close()}return o}reset(){if(this.timestamp=0,this.failPending(new Error("WebCodecs Opus 编码已重置")),this.encoder){try{this.encoder.close()}catch(t){}this.encoder=this.createEncoder()}}async destroy(){const t=this.encoder;if(t){try{await t.flush()}catch(t){}this.failPending(new Error("WebCodecs Opus 编码器已销毁"));try{t.close()}catch(t){}}this.encoder=null,this.isInitialized=!1}createEncoder(){let t;return t=new AudioEncoder({output:e=>{this.encoder===t&&this.handleOutput(e)},error:e=>{if(this.encoder!==t)return;const n=e instanceof Error?e:new Error("WebCodecs Opus 编码失败");(globalThis.avatarSDKLogger||console).error("[WebCodecOpusEncoder] 编码错误:",n),this.failPending(n)}}),t.configure(buildAudioEncoderConfig(this.config)),t}handleOutput(t){const e=this.pendingEncode;if(!e)return;if(t.timestamp<e.startTimestampUs||t.timestamp>=e.endTimestampUs||null!==t.duration&&t.duration!==OPUS_FRAME_DURATION_US)return void this.failPending(new Error("WebCodecs Opus 未按 20ms 分包,无法生成固定 100ms AU 音频"));if(e.chunks.push(t),e.chunks.length>e.expectedFrameCount)return void this.failPending(new Error("WebCodecs Opus 未按 20ms 分包,无法生成固定 100ms AU 音频"));if(e.chunks.length<e.expectedFrameCount)return;const n=e.chunks.map((t,n)=>{var r,i;const s=new Uint8Array(t.byteLength);t.copyTo(s);const a=null!=(r=null==(i=e.chunks[n+1])?void 0:i.timestamp)?r:e.endTimestampUs;return{data:s,durationMs:(t.duration&&t.duration>0?t.duration:Math.max(1,a-t.timestamp))/1e3}}),r=n.reduce((t,e)=>t+e.durationMs,0);n.some(t=>t.durationMs!==OPUS_FRAME_DURATION_US/1e3)||r!==(e.endTimestampUs-e.startTimestampUs)/1e3?this.failPending(new Error("WebCodecs Opus 未按 20ms 分包,无法生成固定 100ms AU 音频")):(globalThis.clearTimeout(e.timeoutId),this.pendingEncode=null,e.resolve(n))}failPending(t){const e=this.pendingEncode;e&&(globalThis.clearTimeout(e.timeoutId),this.pendingEncode=null,e.reject(t))}}const EBML_ID={EBML:440786851,EBMLVersion:17030,EBMLReadVersion:17143,EBMLMaxIDLength:17138,EBMLMaxSizeLength:17139,DocType:17026,DocTypeVersion:17031,DocTypeReadVersion:17029,Segment:408125543,SegmentInfo:357149030,TimecodeScale:2807729,MuxingApp:19840,WritingApp:22337,Tracks:374648427,TrackEntry:174,TrackNumber:215,TrackUID:29637,TrackType:131,FlagLacing:156,Language:2274716,CodecID:134,CodecPrivate:25506,CodecDelay:22186,SeekPreRoll:22203,Audio:225,SamplingFrequency:181,Channels:159,Cluster:524531317,Timecode:231,SimpleBlock:163};class WebMMuxer{constructor(t=16e3){this.chunks=[],this.hasHeader=!1,this.clusterTimestamp=0,this.frameDuration=100,this.sampleRate=t}writeHeader(){if(this.hasHeader)return;const t=this.buildEBMLHeader(),e=this.buildSegmentInfo(),n=this.buildOpusTracks();this.chunks.push(t),this.chunks.push(new Uint8Array([24,83,128,103,1,255,255,255,255,255,255,255])),this.chunks.push(e),this.chunks.push(n),this.hasHeader=!0,this.clusterTimestamp=0}feedOpusFrame(t,e=this.frameDuration){this.hasHeader||this.writeHeader();const n=this.buildCluster(Math.round(this.clusterTimestamp),t);this.chunks.push(n),this.clusterTimestamp+=e}flush(){if(0===this.chunks.length)return new ArrayBuffer(0);const t=this.chunks.reduce((t,e)=>t+e.length,0),e=new Uint8Array(t);let n=0;for(const t of this.chunks)e.set(t,n),n+=t.length;return this.chunks=[],e.buffer}reset(){this.chunks=[],this.hasHeader=!1,this.clusterTimestamp=0}encodeVINT(t,e){if(void 0!==e){const n=new Uint8Array(e);for(let r=e-1;r>=0;r--)n[r]=255&t,t>>>=8;return n[0]|=1<<8-e,n}if(t<127)return new Uint8Array([128|t]);if(t<16383)return new Uint8Array([64|t>>8,255&t]);if(t<2097151)return new Uint8Array([32|t>>16,t>>8&255,255&t]);if(t<268435455)return new Uint8Array([16|t>>24,t>>16&255,t>>8&255,255&t]);throw new Error(`VINT value too large: ${t}`)}encodeID(t){return t<=255?new Uint8Array([t]):t<=65535?new Uint8Array([t>>8,255&t]):t<=16777215?new Uint8Array([t>>16,t>>8&255,255&t]):new Uint8Array([t>>>24,t>>16&255,t>>8&255,255&t])}encodeUint(t){if(0===t)return new Uint8Array([0]);const e=[];let n=t;for(;n>0;)e.unshift(255&n),n=Math.floor(n/256);return new Uint8Array(e)}encodeString(t){return(new TextEncoder).encode(t)}encodeFloat32(t){const e=new ArrayBuffer(4);return new DataView(e).setFloat32(0,t,!1),new Uint8Array(e)}encodeElement(t,e){const n=this.encodeID(t),r=this.encodeVINT(e.length),i=new Uint8Array(n.length+r.length+e.length);return i.set(n,0),i.set(r,n.length),i.set(e,n.length+r.length),i}encodeUintElement(t,e){return this.encodeElement(t,this.encodeUint(e))}encodeStringElement(t,e){return this.encodeElement(t,this.encodeString(e))}encodeFloat32Element(t,e){return this.encodeElement(t,this.encodeFloat32(e))}concatArrays(t){const e=t.reduce((t,e)=>t+e.length,0),n=new Uint8Array(e);let r=0;for(const e of t)n.set(e,r),r+=e.length;return n}buildEBMLHeader(){const t=this.concatArrays([this.encodeUintElement(EBML_ID.EBMLVersion,1),this.encodeUintElement(EBML_ID.EBMLReadVersion,1),this.encodeUintElement(EBML_ID.EBMLMaxIDLength,4),this.encodeUintElement(EBML_ID.EBMLMaxSizeLength,8),this.encodeStringElement(EBML_ID.DocType,"webm"),this.encodeUintElement(EBML_ID.DocTypeVersion,4),this.encodeUintElement(EBML_ID.DocTypeReadVersion,2)]);return this.encodeElement(EBML_ID.EBML,t)}buildSegmentInfo(){const t=this.concatArrays([this.encodeUintElement(EBML_ID.TimecodeScale,1e6),this.encodeStringElement(EBML_ID.MuxingApp,"xmov-avatar-sdk"),this.encodeStringElement(EBML_ID.WritingApp,"xmov-avatar-sdk")]);return this.encodeElement(EBML_ID.SegmentInfo,t)}buildOpusTracks(){const t=new Uint8Array([79,112,117,115,72,101,97,100,1,1,0,0,128,62,0,0,0,0,0]),e=this.concatArrays([this.encodeFloat32Element(EBML_ID.SamplingFrequency,this.sampleRate),this.encodeUintElement(EBML_ID.Channels,1)]),n=this.concatArrays([this.encodeUintElement(EBML_ID.TrackNumber,1),this.encodeUintElement(EBML_ID.TrackUID,1),this.encodeUintElement(EBML_ID.TrackType,2),this.encodeUintElement(EBML_ID.FlagLacing,0),this.encodeStringElement(EBML_ID.Language,"und"),this.encodeStringElement(EBML_ID.CodecID,"A_OPUS"),this.encodeElement(EBML_ID.CodecPrivate,t),this.encodeUintElement(EBML_ID.CodecDelay,0),this.encodeUintElement(EBML_ID.SeekPreRoll,8e7),this.encodeElement(EBML_ID.Audio,e)]),r=this.encodeElement(EBML_ID.TrackEntry,n);return this.encodeElement(EBML_ID.Tracks,r)}buildCluster(t,e){const n=this.encodeUintElement(EBML_ID.Timecode,t),r=this.encodeVINT(1),i=new Uint8Array([0,0]),s=new Uint8Array([128]),a=this.concatArrays([r,i,s,e]),o=this.encodeElement(EBML_ID.SimpleBlock,a),l=this.concatArrays([n,o]);return this.encodeElement(EBML_ID.Cluster,l)}}class PcmWebMEncoder{constructor(){this.opusEncoder=new WebCodecOpusEncoder({sampleRate:16e3,channels:1,bitrate:24e3,frameSize:1600}),this.muxer=new WebMMuxer(16e3),this.queue=Promise.resolve(),this.generation=0,this.destroyed=!1,this.pendingBlocks=0}static isSupported(){return WebCodecOpusEncoder.isSupported()}async init(){await this.opusEncoder.init()}async encode(t){var e=this;if(1600!==t.length)throw new Error(`PCM 音频块必须为 1600 samples,实际为 ${t.length}`);if(this.pendingBlocks>=20)throw new Error("PCM/Opus 编码队列超过 2 秒");this.pendingBlocks+=1;const n=this.generation,r=new Int16Array(t),i=this.queue.then(async function(){if(e.destroyed||n!==e.generation)return new ArrayBuffer(0);const t=await e.opusEncoder.encode(r);if(e.destroyed||n!==e.generation)return new ArrayBuffer(0);for(const n of t)e.muxer.feedOpusFrame(n.data,n.durationMs);return e.muxer.flush()}).finally(()=>{this.pendingBlocks-=1});return this.queue=i.then(()=>{},()=>{}),i}reset(){const t=++this.generation;this.queue=this.queue.then(()=>{this.destroyed||t!==this.generation||(this.opusEncoder.reset(),this.muxer.reset())})}async destroy(){this.destroyed=!0,this.generation+=1,await this.opusEncoder.destroy(),await this.queue,this.muxer.reset()}}class MediaRecorderEncoder{constructor(){this.audioCtx=null,this.workletNode=null,this.destination=null,this.recorder=null,this.isRecording=!1,this.nextResolve=null,this.dataQueue=[]}static isSupported(){return"undefined"!=typeof MediaRecorder&&MediaRecorder.isTypeSupported("audio/webm;codecs=opus")}async init(){const t=window.AudioContext||window.webkitAudioContext;this.audioCtx=new t({sampleRate:16e3});const e=new Blob(["\n class PCMInjectorProcessor extends AudioWorkletProcessor {\n constructor() {\n super();\n this.buffer = new Float32Array(0);\n this.port.onmessage = (e) => {\n if (e.data.type === 'pcm') {\n const int16 = new Int16Array(e.data.pcm);\n const float32 = new Float32Array(int16.length);\n for (let i = 0; i < int16.length; i++) {\n float32[i] = int16[i] / 32768;\n }\n const newBuffer = new Float32Array(this.buffer.length + float32.length);\n newBuffer.set(this.buffer);\n newBuffer.set(float32, this.buffer.length);\n this.buffer = newBuffer;\n }\n };\n }\n process(inputs, outputs) {\n const output = outputs[0][0];\n if (!output) return true;\n const len = Math.min(output.length, this.buffer.length);\n for (let i = 0; i < len; i++) {\n output[i] = this.buffer[i];\n }\n this.buffer = this.buffer.slice(len);\n for (let i = len; i < output.length; i++) {\n output[i] = 0;\n }\n return true;\n }\n }\n registerProcessor('pcm-injector-processor', PCMInjectorProcessor);\n "],{type:"application/javascript"}),n=URL.createObjectURL(e);await this.audioCtx.audioWorklet.addModule(n),URL.revokeObjectURL(n),this.workletNode=new AudioWorkletNode(this.audioCtx,"pcm-injector-processor"),this.destination=this.audioCtx.createMediaStreamDestination(),this.workletNode.connect(this.destination);const r=MediaRecorder.isTypeSupported("audio/webm;codecs=opus")?"audio/webm;codecs=opus":"audio/webm";this.recorder=new MediaRecorder(this.destination.stream,{mimeType:r,audioBitsPerSecond:24e3}),this.recorder.ondataavailable=t=>{t.data&&t.data.size>0&&t.data.arrayBuffer().then(t=>{if(this.nextResolve){const e=this.nextResolve;this.nextResolve=null,e(t)}else this.dataQueue.push(t)})},"suspended"===this.audioCtx.state&&await this.audioCtx.resume()}async feedPCM(t){return this.workletNode&&this.recorder?(this.isRecording||(this.recorder.start(100),this.isRecording=!0),this.workletNode.port.postMessage({type:"pcm",pcm:t},[t]),this.dataQueue.length>0?this.dataQueue.shift():new Promise(t=>{const e=setTimeout(()=>{this.nextResolve=null,t(null)},200);this.nextResolve=n=>{clearTimeout(e),t(n)}})):null}reset(){this.recorder&&"inactive"!==this.recorder.state&&this.recorder.stop(),this.isRecording=!1,this.nextResolve=null,this.dataQueue=[]}destroy(){var t,e;if(this.nextResolve=null,this.dataQueue=[],this.recorder)try{"inactive"!==this.recorder.state&&this.recorder.stop()}catch(t){}null==(t=this.workletNode)||t.disconnect(),null==(e=this.destination)||e.disconnect();try{var n;null==(n=this.audioCtx)||n.close()}catch(t){}this.recorder=null,this.workletNode=null,this.destination=null,this.audioCtx=null}}class XmovAvatar{constructor(t){if(this.TAG="[XMOV AVATAR]",this.el=null,this.status=-1,this.networkMonitor=null,this.ttsa=null,this.debugOverlay=null,this.sentryReporter=null,this.firstFrameSpan=null,this._offlineTimer=-1,this._offlineInterval=300,this._env="production",this.avatarCanvasVisible=!0,this.pendingInvisibleMode=!1,this.isInitialized=!1,this.onStateChange=()=>{},this.onDownloadProgress=null,this.replayData=null,this.startConnectTime=0,this.connectSuccessTime=0,this.sessionResTime=0,this.charbinResTime=0,this.isfirstReceive=!0,this.enableClientInterrupt=!1,this.retryCount=1,this.retryTimer=-1,this.maxRetryCount=9,this.retryRound=1,this.maxRetryRound=3,this.isRetrying=!1,this.isStartRetry=!1,this.destroyed=!1,this.incompleteInitializationCleanupPromise=null,this.captureAudioCtx=null,this.captureWorklet=null,this.captureSource=null,this.captureSetupPromise=null,this.captureLastSpeechId=-2,this.restartPlaybackCaptureImpl=null,this.captureEncodeQueue=Promise.resolve(),this.captureGeneration=0,this.pcmCaptureLastSpeechId=-2,this.pcmCaptureFirstChunk=!0,this.pcmWebMEncoder=null,this.mediaRecorderEncoder=null,this.pcmCaptureMode="none",this.pcmEncodeId=0,this.networkInfo={rtt:0,downlink:0,networkStatus:!1},this.mediaRecorder=null,this.recordedChunks=[],this.stream=null,this._isClientMode=!1,this._streamingClient=null,this._videoPlayer=null,this._eventDispatcher=null,this._apiForwarder=null,this._clientOnDownloadProgress=null,this._pendingInit=!1,this._pendingInitConfig=null,this._clientSessionId="",this.handleBeforeUnload=()=>{this.destroy("beforeunload")},window.avatarSDKLogger.setEnabled(t.enableLogger),this.options=t,this._env=t.env||"production",this.enableClientInterrupt=t.enableClientInterrupt||!1,this.boundVisibilityChange=this.visibilitychange.bind(this),"client"===t.renderMode)return this._isClientMode=!0,void this.initializeClient(t);this.initializeSDK(t),this.networkMonitor=new NetworkMonitor({offlineCallback:t=>{if(this.onMessage({code:EErrorCode.NETWORK_DOWN,message:t||"网络断开"}),console.log("网络断开(network off)",t),!this.isInitialized)return window.avatarSDKLogger.warn(this.TAG,"初始化未完成时断网,清除所有资源并断开连接"),void this.cleanupBeforeInitComplete("network_offline_before_init");this.status!==AvatarStatus.offline&&this.offlineHandle()},onlineCallback:t=>{var e;if(this.onMessage({code:EErrorCode.NETWORK_UP,message:t||"网络恢复"}),!this.isInitialized)return window.avatarSDKLogger.warn(this.TAG,"网络恢复但初始化未完成,清除所有资源并断开连接"),void this.cleanupBeforeInitComplete("network_online_before_init");null==(e=this.ttsa)||e.clearReconnectTimer(),this.isStartRetry&&this.triggerReconnect()}})}getStatus(){return this.status}getIsInitialized(){return this.isInitialized}get businessENV(){return this._env}getUniqueSpeakId(){var t;return(null==(t=this.ttsa)?void 0:t.getUniqueSpeakId())||`0-${this.getSessionId()}`}async initializeSDK(t){var e,n,r;if(!navigator.onLine)return void this.onMessage({code:EErrorCode.NETWORK_BREAK,message:"没有网络,请联网后重试"});const i=this,s=t,{containerId:a,container:o,appId:l,appSecret:c,gatewayServer:d,cacheServer:h,config:u}=t,{scale:p=1}=null!=(e=null==u||null==(n=u.layout)?void 0:n.avatar)?e:{};null!=u&&null!=(r=u.layout)&&null!=(r=r.avatar)&&r.scale&&(u.layout.avatar.scale=validateScaleWithDecimal(p,"initializeSDK"));const f=_extends({},u||{},{raw_audio:!isSupportMES()});if(o&&o instanceof HTMLElement)this.el=o;else{const t=document.querySelector(a);if(!t)return void this.onMessage({code:EErrorCode.CONTAINER_NOT_FOUND,message:`containerId: ${a} 不存在`});this.el=t}const m=document.createElement("div");m.setAttribute("id","avatar-bg-container"),m.setAttribute("style","position:absolute;top:0;left:0;width:100%;height:100%;z-index:0;opacity:0;"),this.el.appendChild(m);const _=this.el.getAttribute("style");this.el.setAttribute("style",_?`position:relative;overflow:hidden;${_}`:"position:relative;overflow:hidden;"),this.resourceManager=new ResourceManager({sdkInstance:this,headers:t.headers,tag:t.tag,gateway_type:t.gateway_type||"default",asr_id:t.asr_id,llm_id:t.llm_id,session_speak_req_id:t.session_speak_req_id,sessionRequestData:s.sessionRequestData,appId:l,appSecret:c,gatewayServer:d,cacheServer:h,config:f,audioOnlyMode:t.audioOnlyMode||!1,onNetworkInfo(e){i.networkInfo=e,null==t.onNetworkInfo||t.onNetworkInfo(e)},onStartSessionWarning:t=>{var e,n;null==(e=(n=this.options).onStartSessionWarning)||e.call(n,t)}}),this.renderScheduler=new RenderScheduler({sdkInstance:this,container:this.el,resourceManager:this.resourceManager,enableDebugger:t.enableDebugger,hardwareAcceleration:t.hardwareAcceleration||"default",enableClientInterrupt:this.enableClientInterrupt,audioOnlyMode:t.audioOnlyMode||!1,onDownloadProgress:t=>{var e,n,r,s;null==(e=this.onDownloadProgress)||e.call(this,t),null==(n=this.el)||n.setAttribute("style",(null==(r=this.el)?void 0:r.style.cssText)+`opacity:${100===t?"1":"0"};`),this.isInitialized=100===t,100===t&&(this.pendingInvisibleMode||this.status===AvatarStatus.online||this.status===AvatarStatus.invisible||this.onStatusChange(AvatarStatus.online),this.resourceManager._setOfflineCache(),null==(s=this.ttsa)||s.sendSdkPoint("loadvideo_decode_time",{timestamp:Date.now()}),setTimeout(()=>{var t,e;null==(t=this.ttsa)||t.sendDeviceInfo(_extends({},getDeviceInfo(),window.performanceTracker.getFirstInfo(),{sdk_version:"2.4.0-alpha.3",resolution:null==(e=this.resourceManager.getConfig())?void 0:e.resolution,download_speed:i.networkInfo.downlink||0}))},20),this.enableAudioPlaybackCapture())},onStateChange:e=>{this.getStatus()===AvatarStatus.offline&&"idle"!==e||""===e||null==t.onStateChange||t.onStateChange(e)},onRenderChange:(e,n)=>{null==t.onRenderChange||t.onRenderChange(e),e!==RenderState.rendering||n!==RenderState.resumed&&this.getStatus()!==AvatarStatus.online||!this.isInitialized||(window.avatarSDKLogger.log(this.TAG,"Status:===== 渲染中,状态: rendering",this.getSessionId()),this.onStatusChange(AvatarStatus.visible))},onVoiceStateChange:(e,n,r)=>{null==t.onVoiceStateChange||t.onVoiceStateChange(e,n,r)},onWalkStateChange:e=>{null==t.onWalkStateChange||t.onWalkStateChange(e)},sendVideoInfo:t=>{var e;null==(e=this.debugOverlay)||e.setVideoInfo(t)},onSpeakStateChange:(e,n)=>{null==t.onSpeakStateChange||t.onSpeakStateChange(e,n)},setAudioInfo:t=>{var e;null==(e=this.debugOverlay)||e.setAudioInfo(t)},setEventData:t=>{var e;null==(e=this.debugOverlay)||e.setEventData(t)},renderFrameCallback:t=>{this.renderFrameCallback(t),this.handleReplaySend(t)},reportMessage:t=>{this.onMessage(t)},sendSdkPoint:(t,e,n)=>{var r;null==(r=this.ttsa)||r.sendSdkPoint(t,e,n)},sendMessage:(t,e)=>{var n;null==(n=this.ttsa)||n.send(t,e)},onFPSUpdate:e=>{null==t.onFPSUpdate||t.onFPSUpdate(e)},onFrameDataUpdate:e=>{null==t.onFrameDataUpdate||t.onFrameDataUpdate(e)}}),t.onStateRenderChange&&window.performanceTracker.setOnStateRenderChange(t.onStateRenderChange),null!=u&&u.walk_config&&this.changeWalkConfig(u.walk_config),null!=u&&u.layout&&this.changeLayout(u.layout),WidgetDefaultRenderer.CUSTOM_WIDGET=t.onWidgetEvent,WidgetDefaultRenderer.PROXY_WIDGET=t.proxyWidget||{}}initializeClient(t){const{containerId:e,container:n}=t;if(n&&n instanceof HTMLElement)this.el=n;else{const t=document.querySelector(e);var r,i;if(!t)return void(null==(r=(i=this.options).onMessage)||r.call(i,{code:EErrorCode.CONTAINER_NOT_FOUND,message:`containerId: ${e} 不存在`}));this.el=t}const s=this.el.getAttribute("style");this.el.setAttribute("style",s?`position:relative;overflow:hidden;${s}`:"position:relative;overflow:hidden;"),this._eventDispatcher=new EventDispatcher({onStateChange:t.onStateChange,onSpeakStateChange:t.onSpeakStateChange,onVoiceStateChange:t.onVoiceStateChange,onStatusChange:t.onStatusChange,onRenderChange:t.onRenderChange,onWalkStateChange:t.onWalkStateChange,onWidgetEvent:t.onWidgetEvent,onMessage:t.onMessage,onNetworkInfo:t.onNetworkInfo,onFPSUpdate:t.onFPSUpdate,onFrameDataUpdate:t.onFrameDataUpdate,onDownloadProgress:t=>{var e;null==(e=this._clientOnDownloadProgress)||e.call(this,t),t>=100&&!this.isInitialized&&(this.isInitialized=!0)},onSessionId:t=>{this._clientSessionId=t,window.avatarSDKLogger.log(this.TAG,"[client] 收到 session_id:",t)}});const a=t.streamingServer||`ws://${location.hostname}:8080`;this._streamingClient=new StreamingClient({url:a,onReady:()=>{if(window.avatarSDKLogger.log(this.TAG,"[client] 双方就绪,等待 Server 推流..."),this._pendingInit){var t;this._pendingInit=!1;const e=this._pendingInitConfig;this._pendingInitConfig=null,window.avatarSDKLogger.log(this.TAG,"[client] 补发 init 命令"),null==(t=this._apiForwarder)||t.init(e)}},onOffer:t=>{var e;null==(e=this._videoPlayer)||e.handleOffer(t)},onIce:t=>{var e;null==(e=this._videoPlayer)||e.addIceCandidate(t)},onEventProxy:(t,e,n)=>{var r;null==(r=this._eventDispatcher)||r.dispatch(t,e,n)},onError:t=>{var e,n;null==(e=(n=this.options).onMessage)||e.call(n,{code:EErrorCode.NETWORK_DOWN,message:t})},onDisconnect:()=>{this.onStatusChange(AvatarStatus.offline)}}),this._videoPlayer=new VideoPlayer({container:this.el,streamingClient:this._streamingClient,useAlphaMask:t.useAlphaMask,onConnected:()=>{window.avatarSDKLogger.log(this.TAG,"[client] WebRTC 已连接"),this.onStatusChange(AvatarStatus.online)},onDisconnected:()=>{this.onStatusChange(AvatarStatus.offline)}}),this._apiForwarder=new APIForwarder(this._streamingClient),this._streamingClient.connect(),window.addEventListener("beforeunload",this.handleBeforeUnload)}renderFrameCallback(t){var e;null!=(e=this.ttsa)&&e.getStatus()||[AvatarStatus.offline].includes(this.status)||t%24!=0||this.offlineHandle()}async init(t){await this.initializeSession(t)}async initializeSession(t){var e,n,r,i;const s=await checkCapability(this.options.audioOnlyMode,this.options.hardwareAcceleration);if(!s.supported){const t=`浏览器能力检查失败: ${s.items.filter(t=>"fatal"===t.severity&&!t.supported).map(t=>t.reason).join("; ")}`;return void this.onMessage({code:EErrorCode.INIT_ERROR,message:t})}if(this.destroyed=!1,this.isInitialized=!1,this.incompleteInitializationCleanupPromise=null,this.startConnectTime=Date.now(),this._isClientMode){var a;this._clientOnDownloadProgress=t.onDownloadProgress||null;const e={appId:this.options.appId,appSecret:this.options.appSecret,gatewayServer:this.options.gatewayServer,cacheServer:this.options.cacheServer,headers:this.options.headers,tag:this.options.tag,gateway_type:this.options.gateway_type,env:this.options.env,config:this.options.config,hardwareAcceleration:this.options.hardwareAcceleration,enableDebugger:this.options.enableDebugger,initModel:t.initModel,scaleDownBy:this.options.scaleDownBy||1,useAlphaMask:this.options.useAlphaMask};var o;return void(null!=(a=this._streamingClient)&&a.isConnected()?null==(o=this._apiForwarder)||o.init(e):(this._pendingInit=!0,this._pendingInitConfig=e,window.avatarSDKLogger.log(this.TAG,"[client] WebSocket 未连接,init 命令暂存")))}if(null!=(e=this.options.sentry)&&e.enabled)try{var l;this.sentryReporter=new SentryReporter("https://aabed165326fc7a2a276b49aa4043be3@xmovsentry.xmov.ai/32",{tracesSampleRate:null==(l=this.options.sentry)?void 0:l.tracesSampleRate}),this.sentryReporter.setTag("app_id",this.options.appId||""),this.sentryReporter.setTag("env",this._env)}catch(t){window.avatarSDKLogger.warn(this.TAG,"Sentry 初始化失败",t)}const c=null==(n=this.sentryReporter)?void 0:n.startInactiveSpan("sdk.init",{op:"init"});this.firstFrameSpan=null!=(r=null==(i=this.sentryReporter)?void 0:i.startInactiveSpan("sdk.first_frame",{op:"render"}))?r:null;const{onDownloadProgress:d,initModel:h}=t;this.onDownloadProgress=t=>{15===t&&(this.sessionResTime=Date.now()),80===t&&(this.charbinResTime=Date.now()),d(t)},h===InitModel.invisible&&(this.pendingInvisibleMode=!0),window.performanceTracker.markStart(performanceConstant.load_resource),window.performanceTracker.markStart(performanceConstant.first_avatar_render),window.performanceTracker.markStart(performanceConstant.first_webgl_render);const u=this.onDownloadProgress,p=this.sentryReporter?await this.sentryReporter.startSpan("sdk.resource_load",{op:"resource.load"},()=>this.resourceManager.load(u.bind(this))):await this.resourceManager.load(u.bind(this));return this.destroyed?(null==c||c.end(),void window.avatarSDKLogger.warn(this.TAG,"sdk destroyed during load, aborting after resourceManager load")):null!=p&&p.socket_io_url&&null!=p&&p.token?(this.connectSuccessTime=Date.now(),window.performanceTracker.markEnd(performanceConstant.load_resource),this.debugOverlay=new DebugOverlay(this,p),this.ttsa=this.connectTtsa(p),this.renderScheduler.init(),this.renderScheduler.setAvatarCanvasVisible(this.avatarCanvasVisible),window.performanceTracker.setReportFunc(this.ttsa),window.addEventListener("beforeunload",this.handleBeforeUnload),document.addEventListener("visibilitychange",this.boundVisibilityChange),null==c||c.end(),p):(null==c||c.end(),void window.avatarSDKLogger.error(this.TAG,"init error, socket_io_url or token is empty reload"))}setAudioPlaybackDataHandler(t){this.options.onAudioPlaybackData=t}restartAudioPlaybackCapture(){var t;null==(t=this.restartPlaybackCaptureImpl)||t.call(this)}enableAudioPlaybackCapture(){return this.options.onAudioPlaybackData?(this.captureSetupPromise||(this.captureSetupPromise=null!=(t=this.resourceManager)&&t.config.raw_audio?this.setupPCMCapture().finally(()=>{this.captureSetupPromise=null}):this.setupAudioCapture().finally(()=>{this.captureSetupPromise=null})),this.captureSetupPromise):Promise.resolve();var t}async setupAudioCapture(){var t=this;const e=document.getElementById("xmov-avatar-audio");if(e&&this.options.onAudioPlaybackData&&!this.captureAudioCtx&&!this.captureSource)if(void 0!==window.AudioWorkletNode)try{var n;if(!await PcmWebMEncoder.isSupported())return void this.onMessage({code:EErrorCode.INIT_ERROR,message:"当前浏览器不支持 WebCodecs AudioEncoder Opus,无法启用 100ms 双路音频"});if(this.pcmWebMEncoder=new PcmWebMEncoder,await this.pcmWebMEncoder.init(),this.captureAudioCtx=new AudioContext({sampleRate:16e3}),16e3!==this.captureAudioCtx.sampleRate)throw new Error(`浏览器无法创建 16000 Hz AudioContext: ${this.captureAudioCtx.sampleRate}`);this.captureSource=this.captureAudioCtx.createMediaElementSource(e),this.captureSource.connect(this.captureAudioCtx.destination);let r=!1,i=!0,s=0,a=0;const o=t=>{const e=++this.captureGeneration;r=!0,i=!0,s=Date.now()-100,a=0,this.captureLastSpeechId=t,this.captureEncodeQueue=this.captureEncodeQueue.then(()=>{var t;e===this.captureGeneration&&(null==(t=this.pcmWebMEncoder)||t.reset())})},l=()=>{const t=++this.captureGeneration;r=!1,this.captureLastSpeechId=-2,this.captureEncodeQueue=this.captureEncodeQueue.then(()=>{var e;t===this.captureGeneration&&(null==(e=this.pcmWebMEncoder)||e.reset())})};this.restartPlaybackCaptureImpl=()=>{r&&o(this.renderScheduler.getSpeechId())};const c=new Blob(["\n class AudioCaptureProcessor extends AudioWorkletProcessor {\n constructor() {\n super();\n this.buffer = new Float32Array(1600); // 100ms @ 16kHz\n this.bufferIndex = 0;\n }\n\n process(inputs, outputs) {\n for (const output of outputs) {\n for (const channel of output) channel.fill(0);\n }\n const input = inputs[0];\n if (input && input.length > 0 && input[0] && input[0].length > 0) {\n const frameCount = input[0].length;\n\n for (let i = 0; i < frameCount; i++) {\n let sample = 0;\n for (let channel = 0; channel < input.length; channel++) {\n sample += input[channel][i] || 0;\n }\n this.buffer[this.bufferIndex++] = sample / input.length;\n\n // 缓冲区满 1600 采样点时,检测静音并发送到主线程\n if (this.bufferIndex >= 1600) {\n // 检测是否全是静音(全零或极低值)\n let hasAudio = false;\n for (let j = 0; j < 1600; j++) {\n if (Math.abs(this.buffer[j]) > 0.0001) {\n hasAudio = true;\n break;\n }\n }\n\n const pcm = new Int16Array(1600);\n for (let j = 0; j < 1600; j++) {\n const value = Math.max(-1, Math.min(1, this.buffer[j]));\n pcm[j] = value < 0 ? value * 0x8000 : value * 0x7fff;\n }\n this.port.postMessage(\n { hasAudio: hasAudio, pcmData: pcm.buffer },\n [pcm.buffer]\n );\n this.bufferIndex = 0;\n }\n }\n }\n return true;\n }\n }\n registerProcessor('audio-capture-processor', AudioCaptureProcessor);\n "],{type:"application/javascript"}),d=URL.createObjectURL(c);if(await this.captureAudioCtx.audioWorklet.addModule(d),URL.revokeObjectURL(d),this.captureWorklet=new AudioWorkletNode(this.captureAudioCtx,"audio-capture-processor"),this.captureSource.connect(this.captureWorklet),this.captureWorklet.connect(this.captureAudioCtx.destination),this.captureEncodeQueue=Promise.resolve(),this.captureWorklet.port.onmessage=e=>{if(!this.options.onAudioPlaybackData)return;const{hasAudio:n,pcmData:c}=e.data,d=this.renderScheduler.getSpeechId();if(n&&!r||n&&r&&d!==this.captureLastSpeechId?o(d):!n&&r&&l(),!(n&&r&&c instanceof ArrayBuffer))return;const h=this.captureGeneration,u=i;i=!1;const p=s+100*a;a+=1,this.captureEncodeQueue=this.captureEncodeQueue.then(async function(){var e;const n=await(null==(e=t.pcmWebMEncoder)?void 0:e.encode(new Int16Array(c)));n&&0!==n.byteLength&&h===t.captureGeneration&&(null==t.options.onAudioPlaybackData||t.options.onAudioPlaybackData({data:n,codec:"opus",isFirstChunk:u,sampleRate:16e3,samples:1600,timestamp:p,speech_id:d}))}).catch(t=>{var e;null==(e=window.avatarSDKLogger)||e.error(this.TAG,"[AudioCapture] PCM/WebCodecs 编码失败:",t)})},"suspended"===this.captureAudioCtx.state&&await this.captureAudioCtx.resume(),"running"!==this.captureAudioCtx.state)throw new Error("AudioContext 未运行,无法启动 farend PCM 捕获");null==(n=window.avatarSDKLogger)||n.log(this.TAG,"[AudioCapture] 初始化成功,采样率:",this.captureAudioCtx.sampleRate,"Hz,opus 编码 (WebM 容器)")}catch(t){var r,i;if(this.captureGeneration++,this.restartPlaybackCaptureImpl=null,this.captureWorklet){try{this.captureWorklet.port.onmessage=null,this.captureWorklet.disconnect()}catch(t){}this.captureWorklet=null}try{var s;null==(s=this.captureSource)||s.disconnect()}catch(t){}this.captureSource=null,this.captureAudioCtx&&"closed"!==this.captureAudioCtx.state&&await this.captureAudioCtx.close().catch(()=>{}),this.captureAudioCtx=null,null==(r=this.pcmWebMEncoder)||r.destroy(),this.pcmWebMEncoder=null,null==(i=window.avatarSDKLogger)||i.error(this.TAG,"[AudioCapture] 初始化失败:",t)}else this.onMessage({code:EErrorCode.INIT_ERROR,message:"当前浏览器不支持 AudioWorkletNode,无法启用音频捕获(ASR 回声消除)"})}async setupPCMCapture(){var t,e=this;if(!this.options.onAudioPlaybackData)return;const n=null==(t=this.renderScheduler.getAudioRenderer())?void 0:t.getAudioPlayer();var r;if(!n)return void(null==(r=window.avatarSDKLogger)||r.error(this.TAG,"[PCMCapture] PCMAudioPlayer 未就绪"));const i=await PcmWebMEncoder.isSupported(),s=MediaRecorderEncoder.isSupported();var a;if(!i&&!s)return null==(a=window.avatarSDKLogger)||a.warn(this.TAG,"[PCMCapture] 当前浏览器不支持 Opus 编码(WebCodecs 和 MediaRecorder 均不可用),跳过 PCM 捕获"),void this.onMessage({code:EErrorCode.INIT_ERROR,message:"当前浏览器不支持 Opus 编码,PCM 模式下无法启用音频捕获(ASR 回声消除)"});try{var o;i?(this.pcmWebMEncoder=new PcmWebMEncoder,await this.pcmWebMEncoder.init(),this.pcmCaptureMode="webcodec"):(this.mediaRecorderEncoder=new MediaRecorderEncoder,await this.mediaRecorderEncoder.init(),this.pcmCaptureMode="mediarecorder"),this.restartPlaybackCaptureImpl=()=>{var t,e;this.pcmCaptureFirstChunk=!0,this.pcmCaptureLastSpeechId=this.renderScheduler.getSpeechId(),this.pcmEncodeId++,null==(t=this.pcmWebMEncoder)||t.reset(),null==(e=this.mediaRecorderEncoder)||e.reset(),n.resetCaptureBuffer()},await n.attachCapture(async function({pcmData:t,hasAudio:r}){try{if(!e.options.onAudioPlaybackData)return;const d=Date.now()-100;if(!n.isPlaying)return void n.resetCaptureBuffer();const h=e.renderScheduler.getSpeechId();var i,s;if(h!==e.pcmCaptureLastSpeechId&&(e.pcmCaptureFirstChunk=!0,e.pcmCaptureLastSpeechId=h,e.pcmEncodeId++,null==(i=e.pcmWebMEncoder)||i.reset(),null==(s=e.mediaRecorderEncoder)||s.reset(),n.resetCaptureBuffer()),!r)return;const u=e.pcmEncodeId;let p=null;const f=performance.now();if("webcodec"===e.pcmCaptureMode&&e.pcmWebMEncoder){const n=new Int16Array(t);var a;if(p=await e.pcmWebMEncoder.encode(n),u!==e.pcmEncodeId)return void(null==(a=window.avatarSDKLogger)||a.log(e.TAG,"[PCMCapture] 丢弃过期编码数据(编码会话已重置)"));if(0===p.byteLength)return;const r=performance.now()-f;var o;r>10&&(null==(o=window.avatarSDKLogger)||o.warn(e.TAG,`[PCMCapture] WebCodecs 编码耗时过长: ${r.toFixed(2)}ms`))}else if("mediarecorder"===e.pcmCaptureMode&&e.mediaRecorderEncoder){var l;if(p=await e.mediaRecorderEncoder.feedPCM(t),u!==e.pcmEncodeId)return void(null==(l=window.avatarSDKLogger)||l.log(e.TAG,"[PCMCapture] 丢弃过期编码数据(编码会话已重置)"));if(!p)return;const n=performance.now()-f;var c;n>10&&(null==(c=window.avatarSDKLogger)||c.warn(e.TAG,`[PCMCapture] MediaRecorder 编码耗时过长: ${n.toFixed(2)}ms`))}if(!p)return;const m=e.pcmCaptureFirstChunk;e.pcmCaptureFirstChunk=!1,e.options.onAudioPlaybackData({data:p,codec:"opus",isFirstChunk:m,sampleRate:16e3,samples:1600,timestamp:d,speech_id:h})}catch(t){var d;null==(d=window.avatarSDKLogger)||d.error(e.TAG,"[PCMCapture] 捕获回调错误:",t)}}),null==(o=window.avatarSDKLogger)||o.log(this.TAG,`[PCMCapture] PCM 捕获初始化成功,编码路径: ${this.pcmCaptureMode}`)}catch(t){var l,c,d;null==(l=window.avatarSDKLogger)||l.error(this.TAG,"[PCMCapture] PCM 捕获初始化失败:",t),null==(c=this.pcmWebMEncoder)||c.destroy(),this.pcmWebMEncoder=null,null==(d=this.mediaRecorderEncoder)||d.destroy(),this.mediaRecorderEncoder=null,this.pcmCaptureMode="none"}}visibilitychange(){var t,e,n;document.hidden?this.setVolume(0):(null!=(t=this.ttsa)&&t.getStatus()&&(null==(n=this.renderScheduler)||n.forceSyncDecoder(),this.setVolume(1)),null!=(e=this.ttsa)&&e.getStatus()||this.status!==AvatarStatus.offline||!NetworkMonitor.ONLINE||(window.avatarSDKLogger.warn(this.TAG,"切回前台发现连接已断开,主动触发重连"),this.onlineMode(),this.setVolume(1)),this.captureAudioCtx&&"suspended"===this.captureAudioCtx.state&&this.captureAudioCtx.resume().catch(()=>{}))}setReplayData(t){this.replayData=t}handleReplaySend(t){if(!this.replayData)return;const e=this.replayData.filter(e=>Number(e.client_frame_number)===t&&"sdk_burial_point"!==e.event_type);for(const t of e){var n;"state_change"===t.event_type?null==(n=this.ttsa)||n.stateChange(t.event_data.state,t.event_data.params):"send_text"===t.event_type?this.speak(t.event_data.ssml,t.event_data.is_start,t.event_data.is_end,t.event_data.extra):window.avatarSDKLogger.log(this.TAG,`[handleReplaySend] 未知事件类型: ${t}`)}}connectTtsa(t){return window.performanceTracker.markStart(performanceConstant.ttsa_connect),window.performanceTracker.markStart(performanceConstant.ttsa_ready),new Ttsa({sdkInstance:this,url:t.socket_io_url,path:(null==t?void 0:t.socket_io_path)||"",room:t.room,session_id:t.session_id,token:t.token,framedata_proto_version:this.resourceManager.getConfig().framedata_proto_version,reconnect_client_timeout:(null==t?void 0:t.reconnect_client_timeout)||0,reconnect_timeout:(null==t?void 0:t.reconnect_timeout)||0,appInfo:_extends({},this.resourceManager.getAppInfo(),{env:this._env}),onReady:()=>{var e,n,r,i,s,a;null==(e=this.ttsa)||e.sendSdkPoint("connect_sdk",{timestamp:this.startConnectTime}),null==(n=this.ttsa)||n.sendSdkPoint("connect_sdk_success",{timestamp:this.connectSuccessTime}),null==(r=this.ttsa)||r.sendSdkPoint("session_processing_time",{timestamp:this.sessionResTime}),null==(i=this.ttsa)||i.sendSdkPoint("Char_bin_download_time",{timestamp:this.charbinResTime}),null==(s=this.ttsa)||s.sendSdkPoint("socket_connect_time",{timestamp:Date.now()}),this.onTtsaReady(t),null==(a=this.ttsa)||a.syncTimestamp()},handleMessage:(t,e)=>{var n,r;this.isfirstReceive&&t===EFrameDataType.BODY&&(null==(n=this.ttsa)||n.sendSdkPoint("body_completed_first_time",{timestamp:Date.now()}),this.isfirstReceive=!1,null==(r=this.firstFrameSpan)||r.end(),this.firstFrameSpan=null),this.renderScheduler.handleData(t,e)},handleAAFrame:t=>{var e,n;null==(e=(n=this.options).onAAFrameHandle)||e.call(n,t)},runStartFrameIndex:t=>{this.renderScheduler.runStartFrameIndex()},ttsaStateChangeHandle:t=>{this.renderScheduler.ttsaStateChangeHandle(t)},reloadSuccess:()=>{this.reloadSuccess()},enterOfflineMode:()=>{this.offlineHandle()},reStartSDK:()=>{this.reStartSession()},sendVoiceEnd:()=>{var t;null==(t=this.renderScheduler)||t.sendVoiceEnd()},getCurrentFrameIndex:()=>{var t,e;return null!=(t=null==(e=this.renderScheduler)?void 0:e.getCurrentFrameIndex())?t:0}})}start(){var t;this.renderScheduler.render(),null==(t=this.ttsa)||t.start(),this.pendingInvisibleMode?(this.pendingInvisibleMode=!1,this.setInvisibleMode()):this.isInitialized&&this.onStatusChange(AvatarStatus.online)}onTtsaReady(t){this.start()}async _reload(){const t=await this.resourceManager._reload();if(t&&!this.destroyed){if(await this.onSessionReloaded(t),this.destroyed)return null;this.ttsa=this.connectTtsa(t),this.ttsa._setResumeInfoCallback(this.resourceManager._getSessionId(),this.renderScheduler._getResumeInfo.bind(this.renderScheduler))}return t}async onSessionReloaded(t){}onSessionReloadExhausted(t){}async restartSessionForTransport(t){var e;this.renderScheduler.interrupt("in_offline_mode"),await this.resourceManager.stopSession(t),this.destroyed||(null==(e=this.ttsa)||e.close(),this.status!==AvatarStatus.offline&&this.offlineHandle(),this.reStartSession())}cancelSessionRestart(){this.resetRetryState(),this.clearAllRetryTimers()}reloadSuccess(){var t;null==(t=this.renderScheduler)||t.markReconnectRecover(),this.isInitialized&&this.onStatusChange(AvatarStatus.online),setTimeout(()=>{window.clearInterval(this._offlineTimer)},1e3)}async stop(){await this.renderScheduler.stop()}isDestroyed(){return this.destroyed}async destroyClient(){var t,e,n;if(this.destroyed)return void window.avatarSDKLogger.warn(this.TAG,"SDK 已销毁,忽略重复销毁请求");if(this.destroyed=!0,this._isClientMode)return this._streamingClient&&(this._streamingClient.destroy(),this._streamingClient=null),this._videoPlayer&&(this._videoPlayer.destroy(),this._videoPlayer=null),this._eventDispatcher=null,this._apiForwarder=null,this.el=null,window.removeEventListener("beforeunload",this.handleBeforeUnload),void window.avatarSDKLogger.log(this.TAG,"薄客户端 SDK 已销毁");if(this.cancelSessionRestart(),-1!==this._offlineTimer&&(clearInterval(this._offlineTimer),this._offlineTimer=-1),this.ttsa&&(this.ttsa.close(),this.ttsa=null),this.renderScheduler&&this.renderScheduler.destroy(),this.resourceManager&&this.resourceManager.destroy(),this.debugOverlay&&(this.debugOverlay.destroy(),this.debugOverlay=null),this.networkMonitor)try{this.networkMonitor.destroy(),this.networkMonitor=null}catch(t){window.avatarSDKLogger.warn(this.TAG,"销毁 networkMonitor 时出错",t)}if(this.pcmEncodeId++,this.captureGeneration++,this.restartPlaybackCaptureImpl=null,this.captureWorklet){try{this.captureWorklet.port.onmessage=null,this.captureWorklet.disconnect()}catch(t){}this.captureWorklet=null}if(this.captureSource){try{this.captureSource.disconnect()}catch(t){}this.captureSource=null}if(this.captureAudioCtx){try{this.captureAudioCtx.close()}catch(t){}this.captureAudioCtx=null}const r=null==(t=this.renderScheduler)||null==(t=t.getAudioRenderer())?void 0:t.getAudioPlayer();if(r&&r.detachCapture(),null==(e=this.pcmWebMEncoder)||e.destroy(),this.pcmWebMEncoder=null,null==(n=this.mediaRecorderEncoder)||n.destroy(),this.mediaRecorderEncoder=null,this.pcmCaptureLastSpeechId=-2,this.pcmCaptureFirstChunk=!0,this.pcmCaptureMode="none",this.el=null,this.startConnectTime=0,this.connectSuccessTime=0,this.sessionResTime=0,this.charbinResTime=0,this.isfirstReceive=!0,this.networkInfo={rtt:0,downlink:0,networkStatus:!1},window.removeEventListener("beforeunload",this.handleBeforeUnload),document.removeEventListener("visibilitychange",this.boundVisibilityChange),this.sentryReporter){try{this.sentryReporter.destroy()}catch(t){}this.sentryReporter=null}window.avatarSDKLogger.log(this.TAG,"SDK 已销毁")}async destroy(t="user"){var e;if(this.replayData=null,this._isClientMode)return void await this.disconnectClientForDestroy(t);null==(e=this.ttsa)||e.sendSdkPoint("close_session",{reason:t});const n=await this.resourceManager.stopSession(t);return await this.destroyClient(),n&&this.onStatusChange(AvatarStatus.close),n}async disconnectClientForDestroy(t){this.replayData=null;try{var e,n;if(this._isClientMode)null==(n=this._apiForwarder)||n.destroy(t);else if(null!=(e=this.ttsa)&&e.hasConnected)this.ttsa.sendSdkPoint("close_session",{reason:t}),await this.ttsa.quit(t);else{var r;await(null==(r=this.ttsa)?void 0:r.quit(t)),await this.resourceManager.stopSession(t)}}catch(t){window.avatarSDKLogger.warn(this.TAG,"TTSA client_quit 未确认,继续释放本地资源",t)}finally{await this.destroyClient(),this.onStatusChange(AvatarStatus.close)}}idle(){var t,e;this._isClientMode?null==(e=this._apiForwarder)||e.idle():(this.enableClientInterrupt&&this.renderScheduler.interrupt("idle"),null==(t=this.ttsa)||t.idle())}listen(){var t,e;this._isClientMode?null==(e=this._apiForwarder)||e.listen():(this.enableClientInterrupt&&this.renderScheduler.interrupt("listen"),null==(t=this.ttsa)||t.listen())}think(){var t,e;this._isClientMode?null==(e=this._apiForwarder)||e.think():(this.enableClientInterrupt&&this.renderScheduler.interrupt("think"),null==(t=this.ttsa)||t.think())}interactiveidle(){var t,e;this._isClientMode?null==(e=this._apiForwarder)||e.interactiveidle():(this.enableClientInterrupt&&this.renderScheduler.interrupt("interactiveidle"),null==(t=this.ttsa)||t.interactiveidle())}speak(t,e=!0,n=!0,r={client_speak_id:"",client_frame:0}){if(!this._isClientMode)return this.sentryReporter?this.sentryReporter.startSpan("sdk.speak",{op:"speak",data:{client_speak_id:r.client_speak_id}},()=>this.speakInternal(t,e,n,r)):this.speakInternal(t,e,n,r);var i;null==(i=this._apiForwarder)||i.speak(t,e,n,r)}speakInternal(t,e=!0,n=!0,r={client_speak_id:"",client_frame:0}){var i,s,a;this.enableClientInterrupt&&e&&this.renderScheduler.interrupt("speak"),r.client_frame=null!=(i=null==(s=this.renderScheduler)?void 0:s.getCurrentFrameIndex())?i:0;const o=null==(a=this.ttsa)?void 0:a.sendText(t,e,n,r);return this.renderScheduler.resume(),o}setOffsetFrame(t){this.renderScheduler.setOffsetFrame(t)}syncTimestamp(){var t,e,n;null==(t=this.ttsa)||t.sendSyncTimestamp(null!=(e=null==(n=this.renderScheduler)?void 0:n.getCurrentFrameIndex())?e:0)}notifyEnterInvisibleMode(){var t;null==(t=this.ttsa)||t.enterInvisibleMode()}notifyExitInvisibleMode(){var t;null==(t=this.ttsa)||t.exitInvisibleMode()}setVolume(t){var e;this._isClientMode?null==(e=this._apiForwarder)||e.setVolume(t):this.renderScheduler.setVolume(t)}getSessionId(){var t;return this._isClientMode?this._clientSessionId:null==(t=this.resourceManager)?void 0:t.session_id}showDebugInfo(){var t;this.debugOverlay&&(null==(t=this.debugOverlay)||t.show())}hideDebugInfo(){var t;null==(t=this.debugOverlay)||t.hide()}changeAvatarVisible(t){var e,n;this.avatarCanvasVisible=t,this._isClientMode?null==(n=this._apiForwarder)||n.changeAvatarVisible(t):null==(e=this.renderScheduler)||e.setAvatarCanvasVisible(t)}cleanupBeforeInitComplete(t){var e,n=this;if(this.incompleteInitializationCleanupPromise)return this.incompleteInitializationCleanupPromise;window.avatarSDKLogger.warn(this.TAG,`清理初始化未完成的资源,原因: ${t}`),this.isInitialized=!1;const r=null==(e=this.resourceManager)?void 0:e.stopSession(t);return null==r||r.catch(t=>{window.avatarSDKLogger.warn(this.TAG,"停止初始化未完成的会话时出错",t)}),this.incompleteInitializationCleanupPromise=async function(){try{await r,await n.destroyClient()}catch(t){window.avatarSDKLogger.warn(n.TAG,"清理初始化未完成的本地资源时出错",t)}}(),this.incompleteInitializationCleanupPromise}reportInitializationFailure(t,e){this.onMessage({code:EErrorCode.INIT_ERROR,message:t,e})}offlineHandle(){this.onStatusChange(AvatarStatus.offline),this.renderScheduler._offlineMode(),this._offlineTimer=window.setInterval(()=>{if(this.status!==AvatarStatus.offline)return clearInterval(this._offlineTimer),void(this._offlineTimer=-1);this.renderScheduler._offlineRun()},this._offlineInterval)}async stopSessionFromSocket(t){await this.resourceManager.stopSession(t)}offlineMode(){var t;this.renderScheduler.interrupt("in_offline_mode"),this.resourceManager.stopSession("offline_mode"),null==(t=this.ttsa)||t.close(),this.offlineHandle()}onlineMode(){NetworkMonitor.ONLINE&&this._reload()}onMessage(t){var e,n;try{"object"==typeof t.e&&null!==t.e||(t.e={msg:t.e}),t.session_id=this.getSessionId()}catch(r){window.avatarSDKLogger.warn(this.TAG,"获取 session_id 时出错",r)}const r=Errors(t);if(t.code!==EErrorCode.RENDER_BODY_ERROR&&t.code!==EErrorCode.RENDER_FACE_ERROR&&t.code!==EErrorCode.BODY_DATA_EXPIRED&&(this.options.onMessage(r),this.sentryReporter))try{this.sentryReporter.captureError(r)}catch(t){window.avatarSDKLogger.warn(this.TAG,"Sentry 上报失败",t)}null==(e=this.ttsa)||e.send("client_error",t),null==(n=this.debugOverlay)||n.addError(r)}onStatusChange(t){var e,n;t!==this.status&&(this.status=t,null==(e=(n=this.options).onStatusChange)||e.call(n,t))}switchInvisibleMode(){var t,e;this._isClientMode?null==(t=this._apiForwarder)||t.switchInvisibleMode():this.renderScheduler?this.status===AvatarStatus.visible||this.status===AvatarStatus.online?this.setInvisibleMode():(this.notifyExitInvisibleMode(),this.renderScheduler.switchInvisibleMode(),this.listen()):null==(e=window.avatarSDKLogger)||e.warn(this.TAG,"RenderScheduler 未初始化,无法切换隐身模式")}setInvisibleMode(){this.interactiveidle(),this.renderScheduler.switchInvisibleMode(),this.notifyEnterInvisibleMode(),this.onStatusChange(AvatarStatus.invisible)}getPendingInvisibleMode(){return this.pendingInvisibleMode||!1}getRenderState(){return this.renderScheduler?this.renderScheduler.getRenderState():RenderState.init}changeLayout(t){var e,n;if(this._isClientMode)return void(null==(n=this._apiForwarder)||n.changeLayout(t));const{scale:r=1}=t.avatar||{};t.avatar.scale=validateScaleWithDecimal(r,"changeLayout"),null==(e=this.ttsa)||e.changeLayout(t),this.renderScheduler.setCharacterCanvasLayout(t)}changeWalkConfig(t){var e,n;this._isClientMode?null==(n=this._apiForwarder)||n.changeWalkConfig(t):(null==(e=this.ttsa)||e.changeWalkConfig(t),this.renderScheduler.setWalkConfig(t))}interrupt(t){var e;return this._isClientMode?(null==(e=this._apiForwarder)||e.interrupt(t),0):this.renderScheduler.interrupt(t)}triggerReconnect(){this.clearAllRetryTimers(),this.isRetrying=!1,this.retryCount=1,this.retryRound=1,this.reStartSession()}reStartSession(){this.isRetrying||this.retryRound>this.maxRetryRound||(this.clearAllRetryTimers(),this.isStartRetry=!0,this.isRetrying=!0,this._retryImpl())}async _retryImpl(){var t=this;if(this.retryRound>this.maxRetryRound||!this.isRetrying)return;let e=1e3;this.retryCount>1&&(e=1e3*Math.pow(2,this.retryCount)),this.retryTimer=window.setTimeout(async function(){if(t.retryTimer=-1,t.isRetrying&&!t.destroyed)try{const e=t.sentryReporter?await t.sentryReporter.startSpan("sdk.reconnect",{op:"reconnect",data:{round:t.retryRound,count:t.retryCount}},()=>t._reload()):await t._reload();if(!t.isRetrying||t.destroyed)return;if(null===e){if(t.retryCount>=t.maxRetryCount){if(t.retryRound>=t.maxRetryRound)return window.avatarSDKLogger.warn(t.TAG,`重试达最大轮次(${t.maxRetryRound})+每轮最大次数(${t.maxRetryCount}),总次数=${t.maxRetryRound*t.maxRetryCount},停止重试`),t.onSessionReloadExhausted(),void t.resetRetryState();window.avatarSDKLogger.warn(t.TAG,`第${t.retryRound}轮重试次数达上限(${t.maxRetryCount}),进入第${t.retryRound+1}轮重试`),t.retryCount=1,t.retryRound+=1}else t.retryCount+=1;t._retryImpl()}else t.renderScheduler.stopAudio(-1),window.avatarSDKLogger.log(t.TAG,`第${t.retryRound}轮第${t.retryCount}次重试成功,停止重试`),t.resetRetryState()}catch(e){if(window.avatarSDKLogger.error(t.TAG,"重试过程异常",e),t.retryCount>=t.maxRetryCount){if(t.retryRound>=t.maxRetryRound)return window.avatarSDKLogger.warn(t.TAG,`重试异常且达总次数上限(${t.maxRetryRound*t.maxRetryCount}),停止重试`),t.onSessionReloadExhausted(e),void t.resetRetryState();t.retryCount=1,t.retryRound+=1}else t.retryCount+=1;t.retryRound<=t.maxRetryRound&&t.isRetrying?t._retryImpl():t.resetRetryState()}},e)}clearAllRetryTimers(){-1!==this.retryTimer&&(clearTimeout(this.retryTimer),this.retryTimer=-1)}resetRetryState(){this.isRetrying=!1,this.isStartRetry=!1,this.retryCount=1,this.retryRound=1}seekToFrame(t){var e;this.renderScheduler.seekToFrame(t),null==(e=this.ttsa)||e.seekToFrame(t)}async startRecoder(){try{var t,e;const n=null==(t=this.el)?void 0:t.querySelector("canvas"),r=null==(e=this.el)?void 0:e.querySelector("audio");if(!n||!r)return void console.error("找不到 canvas 或 audio 元素");const i=n.captureStream(60);let s=[];if(this.captureSource&&this.captureAudioCtx){const t=this.captureAudioCtx.createMediaStreamDestination();this.captureSource.connect(t),s=t.stream.getAudioTracks()}else if("function"==typeof r.captureStream)s=r.captureStream().getAudioTracks();else{if("function"!=typeof r.mozCaptureStream)return void window.avatarSDKLogger.error("❌ 当前浏览器不支持 captureStream,无法录制音频");s=r.mozCaptureStream().getAudioTracks()}this.stream=new MediaStream([...i.getVideoTracks(),...s]),this.recordedChunks=[],this.mediaRecorder=new MediaRecorder(this.stream,{mimeType:"video/mp4",videoBitsPerSecond:12582912}),this.mediaRecorder.ondataavailable=t=>{t.data&&t.data.size>0&&this.recordedChunks.push(t.data)},this.mediaRecorder.start(100),window.avatarSDKLogger.log("✅ 开始录制")}catch(t){window.avatarSDKLogger.error("❌ 录制失败:",t)}}stopRecoder(){var t;this.mediaRecorder&&(this.mediaRecorder.stop(),null==(t=this.stream)||t.getTracks().forEach(t=>t.stop()),window.avatarSDKLogger.log("⏹ 停止录制"))}exportVideo(){if(!this.recordedChunks.length)return void window.avatarSDKLogger.error("没有录制到数据");const t=new Blob(this.recordedChunks,{type:"video/mp4"}),e=URL.createObjectURL(t),n=document.createElement("a");n.href=e,n.download=`录制_${(new Date).getTime()}.mp4`,n.click(),window.avatarSDKLogger.log("✅ 下载成功,大小:",t.size)}getOptions(){return this.options}simulateContextLoss(t=5e3,e=!1){this.renderScheduler?this.renderScheduler.simulateContextLoss(t,e):window.avatarSDKLogger.warn("[Test] renderScheduler not initialized")}getRecoveryStatus(){return this.renderScheduler?this.renderScheduler.getRecoveryStatus():null}async testStagedRecovery(){if(this.renderScheduler)return this.renderScheduler.testStagedRecovery();window.avatarSDKLogger.warn("[Test] renderScheduler not initialized")}restartWebGL(){return this.renderScheduler?this.renderScheduler.restartWebGL():(window.avatarSDKLogger.warn("[restartWebGL] renderScheduler not initialized"),!1)}}XmovAvatar.IBRAnimationGeneratorCharInfo_NN=IBRAnimationGeneratorCharInfo_NN,XmovAvatar.unpackIBRAnimation=unpackIBRAnimation,XmovAvatar.formatMJT=formatMJT,XmovAvatar.getVertices=getVertices,XmovAvatar.getPCATextures=getPCATextures,XmovAvatar.getWavefrontObjFromVertices=getWavefrontObjFromVertices,XmovAvatar.GLDevice=GLDevice,XmovAvatar.GLPipeline=GLPipeline,XmovAvatar.checkCapability=checkCapability;export{XmovAvatar as default};
1
+ function _extends(){return _extends=Object.assign?Object.assign.bind():function(t){for(var e=1;e<arguments.length;e++){var n=arguments[e];for(var r in n)({}).hasOwnProperty.call(n,r)&&(t[r]=n[r])}return t},_extends.apply(null,arguments)}var EErrorCode;!function(t){t[t.CONTAINER_NOT_FOUND=10001]="CONTAINER_NOT_FOUND",t[t.CONNECT_SOCKET_ERROR=10002]="CONNECT_SOCKET_ERROR",t[t.START_SESSION_ERROR=10003]="START_SESSION_ERROR",t[t.STOP_SESSION_ERROR=10004]="STOP_SESSION_ERROR",t[t.INIT_ERROR=10005]="INIT_ERROR",t[t.SOCKET_QUIT=10006]="SOCKET_QUIT",t[t.SOCKET_DISCONNECT=10007]="SOCKET_DISCONNECT",t[t.VIDEO_FRAME_EXTRACT_ERROR=20001]="VIDEO_FRAME_EXTRACT_ERROR",t[t.INIT_WORKER_ERROR=20002]="INIT_WORKER_ERROR",t[t.PROCESS_VIDEO_STREAM_ERROR=20003]="PROCESS_VIDEO_STREAM_ERROR",t[t.FACE_PROCESSING_ERROR=20004]="FACE_PROCESSING_ERROR",t[t.RENDER_BODY_ERROR=20005]="RENDER_BODY_ERROR",t[t.RENDER_FACE_ERROR=20006]="RENDER_FACE_ERROR",t[t.WebGL_RENDER_ERROR=20007]="WebGL_RENDER_ERROR",t[t.RENDER_DATA_MISSING=20008]="RENDER_DATA_MISSING",t[t.RENDER_FACE_DATA_MISSING=20009]="RENDER_FACE_DATA_MISSING",t[t.EVENT_WITHOUT_SPEECH_ID=20010]="EVENT_WITHOUT_SPEECH_ID",t[t.EVENT_TRIGGERED=20011]="EVENT_TRIGGERED",t[t.BACKGROUND_IMAGE_LOAD_ERROR=30001]="BACKGROUND_IMAGE_LOAD_ERROR",t[t.FACE_BIN_LOAD_ERROR=30002]="FACE_BIN_LOAD_ERROR",t[t.INVALID_BODY_NAME=30003]="INVALID_BODY_NAME",t[t.VIDEO_DOWNLOAD_ERROR=30004]="VIDEO_DOWNLOAD_ERROR",t[t.BODY_DATA_EXPIRED=30005]="BODY_DATA_EXPIRED",t[t.EVENT_SPEAK_START_EXPIRED=30006]="EVENT_SPEAK_START_EXPIRED",t[t.EVENT_VOICE_START_EXPIRED=30007]="EVENT_VOICE_START_EXPIRED",t[t.AUDIO_DECODE_ERROR=40001]="AUDIO_DECODE_ERROR",t[t.FACE_DECODE_ERROR=40002]="FACE_DECODE_ERROR",t[t.VIDEO_DECODE_ERROR=40003]="VIDEO_DECODE_ERROR",t[t.EVENT_DECODE_ERROR=40004]="EVENT_DECODE_ERROR",t[t.INVALID_DATA_STRUCTURE=40005]="INVALID_DATA_STRUCTURE",t[t.TTSA_ERROR=40006]="TTSA_ERROR",t[t.AUDIO_DATA_EXPIRED=40007]="AUDIO_DATA_EXPIRED",t[t.NETWORK_DOWN=50001]="NETWORK_DOWN",t[t.NETWORK_UP=50002]="NETWORK_UP",t[t.NETWORK_RETRY=50003]="NETWORK_RETRY",t[t.NETWORK_BREAK=50004]="NETWORK_BREAK",t[t.WEBGL_CONTEXT_LOST=60001]="WEBGL_CONTEXT_LOST",t[t.WEBGL_CONTEXT_RESTORED=60002]="WEBGL_CONTEXT_RESTORED",t[t.WEBGL_CONTEXT_RESTORE_TIMEOUT=60003]="WEBGL_CONTEXT_RESTORE_TIMEOUT",t[t.WEBGL_CONTEXT_RECOVERED=60004]="WEBGL_CONTEXT_RECOVERED",t[t.WEBGL_CONTEXT_RECOVERY_FAILED=60005]="WEBGL_CONTEXT_RECOVERY_FAILED",t[t.WEBGL_CONTEXT_RECOVERY_MAX_ATTEMPTS=60006]="WEBGL_CONTEXT_RECOVERY_MAX_ATTEMPTS",t[t.WEBGL_RESOLUTION_RESTORED=60007]="WEBGL_RESOLUTION_RESTORED",t[t.WEBGL_CONTEXT_MANUAL_RESTARTED=60008]="WEBGL_CONTEXT_MANUAL_RESTARTED"}(EErrorCode||(EErrorCode={}));const ERROR_CODE_MAP={10001:3101,10002:3102,10003:3103,10004:3104,10005:3105,10006:3106,10007:3107,20001:3201,20002:3202,20003:3203,20004:3204,20005:3205,20006:3206,20007:3207,20008:3208,20009:3209,20010:3210,20011:3211,30001:3301,30002:3302,30003:3303,30004:3304,30005:3305,30006:3306,30007:3307,40001:3401,40002:3402,40003:3403,40004:3404,40005:3405,40006:3406,40007:3407,50001:3501,50002:3502,50003:3503,50004:3504,60001:3601,60002:3602,60003:3603,60004:3604,60005:3605,60006:3606,60007:3607,60008:3608},ERROR_NAME_MAP={10001:"CONTAINER_NOT_FOUND",10002:"CONNECT_SOCKET_ERROR",10003:"START_SESSION_ERROR",10004:"STOP_SESSION_ERROR",10005:"INIT_ERROR",10006:"SOCKET_QUIT",10007:"SOCKET_DISCONNECT",20001:"VIDEO_FRAME_EXTRACT_ERROR",20002:"INIT_WORKER_ERROR",20003:"PROCESS_VIDEO_STREAM_ERROR",20004:"FACE_PROCESSING_ERROR",20005:"RENDER_BODY_ERROR",20006:"RENDER_FACE_ERROR",20007:"WebGL_RENDER_ERROR",20008:"RENDER_DATA_MISSING",20009:"RENDER_FACE_DATA_MISSING",20010:"EVENT_WITHOUT_SPEECH_ID",20011:"EVENT_TRIGGERED",30001:"BACKGROUND_IMAGE_LOAD_ERROR",30002:"FACE_BIN_LOAD_ERROR",30003:"INVALID_BODY_NAME",30004:"VIDEO_DOWNLOAD_ERROR",30005:"BODY_DATA_EXPIRED",30006:"EVENT_SPEAK_START_EXPIRED",30007:"EVENT_VOICE_START_EXPIRED",40001:"AUDIO_DECODE_ERROR",40002:"FACE_DECODE_ERROR",40003:"VIDEO_DECODE_ERROR",40004:"EVENT_DECODE_ERROR",40005:"INVALID_DATA_STRUCTURE",40006:"TTSA_ERROR",40007:"AUDIO_DATA_EXPIRED",50001:"NETWORK_DOWN",50002:"NETWORK_UP",50003:"NETWORK_RETRY",50004:"NETWORK_BREAK",60001:"WEBGL_CONTEXT_LOST",60002:"WEBGL_CONTEXT_RESTORED",60003:"WEBGL_CONTEXT_RESTORE_TIMEOUT",60004:"WEBGL_CONTEXT_RECOVERED",60005:"WEBGL_CONTEXT_RECOVERY_FAILED",60006:"WEBGL_CONTEXT_RECOVERY_MAX_ATTEMPTS",60007:"WEBGL_RESOLUTION_RESTORED",60008:"WEBGL_CONTEXT_MANUAL_RESTARTED"};var AvatarStatus,RenderState,InitModel,EFrameDataType;!function(t){t[t.online=0]="online",t[t.offline=1]="offline",t[t.network_on=2]="network_on",t[t.network_off=3]="network_off",t[t.close=4]="close",t[t.visible=5]="visible",t[t.invisible=6]="invisible",t[t.stopped=7]="stopped"}(AvatarStatus||(AvatarStatus={})),function(t){t.init="init",t.rendering="rendering",t.pausing="pausing",t.paused="paused",t.resumed="resumed",t.stopped="stopped"}(RenderState||(RenderState={})),function(t){t.normal="normal",t.invisible="invisible"}(InitModel||(InitModel={})),function(t){t.AUDIO="tts_audio",t.BODY="body_data",t.FACE="face_data",t.EVENT="event_data",t.AA_FRAME="aa_frame",t.SYNC_FRAME="sync_frame"}(EFrameDataType||(EFrameDataType={}));const FRAME_SOURCE_SOURCE="xmov_avatar_js_sdk";class DataCacheQueue{constructor(){this.TAG="[DataCacheQueue]",this._bodyQueue=new Map,this._facialQueue=[],this._realFacialQueue=[],this.audioQueue=[],this.eventQueue=[],this.videoIdList=[],this._currentPlayState="idle",this._currentTtsaState=null,window.__dev_event_queue__=this.eventQueue}set currentPlayState(t){this._currentPlayState=t}get currentPlayState(){return this._currentPlayState}set currentTtsaState(t){this._currentTtsaState=t}get currentTtsaState(){return this._currentTtsaState}get bodyQueue(){return Array.from(this._bodyQueue.values())}_updateBodyImageBitmap(t){const e=this._bodyQueue.get(t.frameIndex);e&&e.frame&&"function"==typeof e.frame.close&&e.frame.close();for(const[e,n]of this._bodyQueue.entries())n.body_id<t.body_id&&n.frameIndex>=t.frameIndex&&(n.frame.close(),this._bodyQueue.delete(e));this._bodyQueue.set(t.frameIndex,t)}clearOldFrames(t){for(const[e,n]of this._bodyQueue.entries())e>=t&&(n.frame.close(),this._bodyQueue.delete(e))}clearOldFaceData(t){this._facialQueue=this._facialQueue.filter(e=>e.frameIndex>=t),this._realFacialQueue=this._realFacialQueue.filter(e=>e.frameIndex>=t)}setVideoIdList(t){this.videoIdList.includes(t)||this.videoIdList.push(t)}getVideoIdList(){return this.videoIdList}_getBodyImageBitmap(t){const e=this._bodyQueue.get(t);for(const[e,n]of this._bodyQueue.entries())e<t&&(n.frame.close(),this._bodyQueue.delete(e));if(e)return e}getBodyVideoNameListLength(){const t=[];return this.bodyQueue.forEach(e=>{t.includes(e.name)||t.push(e.name)}),t.length}_getFaceImageBitmap(t,e){let n=null;for(let r=this._facialQueue.length-1;r>=0;r--){const i=this._facialQueue[r];if(i.frameIndex===t&&i.body_id===e){n=i;break}}return this._facialQueue=this._facialQueue.filter(e=>e.frameIndex>=t),n}_updateFacial(t){this._facialQueue.push(...t)}get facialQueue(){return this._facialQueue}_getRealFaceImageBitmap(t,e){let n=null;for(let r=this._realFacialQueue.length-1;r>=0;r--){const i=this._realFacialQueue[r];if((null==i?void 0:i.frameIndex)===t&&(null==i?void 0:i.body_id)===e){n=i;break}}return this._realFacialQueue=this._realFacialQueue.filter(e=>(null==e?void 0:e.frameIndex)>=t),n}_updateRealFacial(t){this._realFacialQueue.push(...t)}get realFacialQueue(){return this._realFacialQueue}clearAllFaceData(){var t;this._facialQueue=[],this._realFacialQueue=[],null==(t=window.avatarSDKLogger)||t.log(this.TAG,"已清空所有表情数据")}_updateAudio(t){this.audioQueue.push(...t)}_clearAudio(t){this.audioQueue=-1!==t?this.audioQueue.filter(e=>e.sid!==t):[]}_getAudio(t){const e=this.audioQueue.findIndex(e=>e.sf===t);if(-1===e)return;const[n]=this.audioQueue.splice(e,1);return n}_getAudioInterval(t,e){const n=this.audioQueue.filter(n=>n.sf>=t&&n.sf<=e);if(0===n.length)return;const r=n[n.length-1],i=this.audioQueue.findIndex(t=>t.id===r.id);return this.audioQueue.splice(i,1),r}_updateUiEvent(t){this.eventQueue.push(...t)}clearOldEvent(t){this.eventQueue=this.eventQueue.filter(e=>e.sf>=t)}clearSubtitleOn(t){this.eventQueue=this.eventQueue.map(e=>{var n;return _extends({},e,{e:null==(n=e.e)?void 0:n.filter(e=>e.speech_id>t||"subtitle_on"!==e.type)})})}_clearEvent(){this.eventQueue=[]}_getEvent(t){const e=this.eventQueue.filter(e=>e.sf===t);if(0!==e.length)return this.eventQueue=this.eventQueue.filter(e=>e.sf!==t),this._mergeEventsBySf(e)}_getEventInterval(t,e){const n=this.eventQueue.filter(n=>n.sf>=t&&n.sf<=e);if(0!==n.length)return this.eventQueue=this.eventQueue.filter(n=>!(n.sf>=t&&n.sf<=e)),this._mergeEventsBySf(n)}_mergeEventsBySf(t){const e={};for(const n of t){const t=n.sf;e[t]||(e[t]=_extends({},n,{e:[]})),e[t].e.push(...n.e)}const n=Object.values(e);if(0===n.length)return null;if(n.length>1){const t=[];return n.forEach(e=>t.push(...e.e)),_extends({},n[0],{mergeFrameFlag:1,e:t})}return n[0]}checkValidData(t,e){switch(e){case EFrameDataType.BODY:case EFrameDataType.FACE:break;case EFrameDataType.AUDIO:var n,r;if(0===this.audioQueue.length||0===t.length)return;if((null==(n=this.audioQueue[this.audioQueue.length-1])?void 0:n.ef)<t[0].sf||t[0].sf<(null==(r=this.audioQueue[0])?void 0:r.sf)){const e=this.audioQueue.findIndex(e=>e.sf>=t[0].sf);-1!==e&&(this.audioQueue.length=e)}}}destroy(){this._bodyQueue.forEach(t=>{t.frame&&"function"==typeof t.frame.close&&t.frame.close()}),this._bodyQueue.clear(),this._facialQueue=[],this.audioQueue=[],this.eventQueue=[]}}class GLDevice{constructor(t){this.running=!0,this.syncMedia=null,this.syncMediaTime=null,this._lost_context_sim=null,this._isDestroyed=!1,this.canvas=t,this.frameID=null;const e=()=>{const t=this.canvas.getContext("webgl2",{antialias:!1,premultipliedAlpha:!0,preserveDrawingBuffer:!0});if(!t)throw Error("WebGL context cannot be created.");this.gl=t,this._lost_context_sim=this.gl.getExtension("WEBGL_lose_context"),this.shaderStage={vertex:this.gl.VERTEX_SHADER,fragment:this.gl.FRAGMENT_SHADER},this._ElementTypeMap_JS2GL={Uint8Array:this.gl.UNSIGNED_BYTE,Uint8ClampedArray:this.gl.UNSIGNED_BYTE,Int8Array:this.gl.BYTE,Uint16Array:this.gl.UNSIGNED_SHORT,Int16Array:this.gl.SHORT,Uint32Array:this.gl.UNSIGNED_INT,Int32Array:this.gl.INT,Float16Array:this.gl.HALF_FLOAT,Float32Array:this.gl.FLOAT};const e=[[this.gl.UNSIGNED_BYTE,[[this.gl.RED,this.gl.R8],[this.gl.RED_INTEGER,this.gl.R8UI],[this.gl.RG,this.gl.RG8],[this.gl.RG_INTEGER,this.gl.RG8UI],[this.gl.RGB,this.gl.RGB8],[this.gl.RGB_INTEGER,this.gl.RGB8UI],[this.gl.RGBA,this.gl.RGBA8],[this.gl.RGBA_INTEGER,this.gl.RGBA8UI]]],[this.gl.BYTE,[[this.gl.RED,this.gl.R8_SNORM],[this.gl.RED_INTEGER,this.gl.R8I],[this.gl.RG,this.gl.RG8_SNORM],[this.gl.RG_INTEGER,this.gl.RG8I],[this.gl.RGB,this.gl.RGB8_SNORM],[this.gl.RGB_INTEGER,this.gl.RGB8I],[this.gl.RGBA,this.gl.RGBA8_SNORM],[this.gl.RGBA_INTEGER,this.gl.RGBA8I]]],[this.gl.UNSIGNED_SHORT,[[this.gl.RED_INTEGER,this.gl.R16UI],[this.gl.RG_INTEGER,this.gl.RG16UI],[this.gl.RGB_INTEGER,this.gl.RGB16UI],[this.gl.RGBA_INTEGER,this.gl.RGBA16UI],[this.gl.DEPTH_COMPONENT,this.gl.DEPTH_COMPONENT16]]],[this.gl.SHORT,[[this.gl.RED_INTEGER,this.gl.R16I],[this.gl.RG_INTEGER,this.gl.RG16I],[this.gl.RGB_INTEGER,this.gl.RGB16I],[this.gl.RGBA_INTEGER,this.gl.RGBA16I]]],[this.gl.UNSIGNED_INT,[[this.gl.RED_INTEGER,this.gl.R32UI],[this.gl.RG_INTEGER,this.gl.RG32UI],[this.gl.RGB_INTEGER,this.gl.RGB32UI],[this.gl.RGBA_INTEGER,this.gl.RGBA32UI],[this.gl.DEPTH_COMPONENT,this.gl.DEPTH_COMPONENT24]]],[this.gl.INT,[[this.gl.RED_INTEGER,this.gl.R32I],[this.gl.RG_INTEGER,this.gl.RG32I],[this.gl.RGB_INTEGER,this.gl.RGB32I],[this.gl.RGBA_INTEGER,this.gl.RGBA32I]]],[this.gl.HALF_FLOAT,[[this.gl.RED,this.gl.R16F],[this.gl.RG,this.gl.RG16F],[this.gl.RGB,this.gl.RGB16F],[this.gl.RGBA,this.gl.RGBA16F]]],[this.gl.FLOAT,[[this.gl.RED,this.gl.R32F],[this.gl.RG,this.gl.RG32F],[this.gl.RGB,this.gl.RGB32F],[this.gl.RGBA,this.gl.RGBA32F],[this.gl.DEPTH_COMPONENT,this.gl.DEPTH_COMPONENT32F]]],[this.gl.UNSIGNED_SHORT_5_6_5,[[this.gl.RGB,this.gl.RGB565]]],[this.gl.UNSIGNED_SHORT_4_4_4_4,[[this.gl.RGBA,this.gl.RGBA4]]],[this.gl.UNSIGNED_SHORT_5_5_5_1,[[this.gl.RGBA,this.gl.RGB5_A1]]],[this.gl.UNSIGNED_INT_2_10_10_10_REV,[[this.gl.RGBA,this.gl.RGB10_A2]]],[this.gl.UNSIGNED_INT_10F_11F_11F_REV,[[this.gl.RGB,this.gl.R11F_G11F_B10F]]],[this.gl.UNSIGNED_INT_5_9_9_9_REV,[[this.gl.RGB,this.gl.RGB9_E5]]],[this.gl.UNSIGNED_INT_24_8,[[this.gl.DEPTH_STENCIL,this.gl.DEPTH24_STENCIL8]]],[this.gl.FLOAT_32_UNSIGNED_INT_24_8_REV,[[this.gl.DEPTH_STENCIL,this.gl.DEPTH32F_STENCIL8]]]];this._FormatTypeMap_Ext2Int=new Map;for(const[t,n]of e){const e=new Map;for(const[t,r]of n)e.set(t,r);this._FormatTypeMap_Ext2Int.set(t,e)}const n={GL_RED:this.gl.RED,GL_RED_INTEGER:this.gl.RED_INTEGER,GL_RG:this.gl.RG,GL_RG_INTEGER:this.gl.RG_INTEGER,GL_RGB:this.gl.RGB,GL_RGB_INTEGER:this.gl.RGB_INTEGER,GL_RGBA:this.gl.RGBA,GL_RGBA_INTEGER:this.gl.RGBA_INTEGER,GL_DEPTH_COMPONENT:this.gl.DEPTH_COMPONENT,GL_DEPTH_STENCIL:this.gl.DEPTH_STENCIL};this._FormatTypeMap_Ext2Str=new Map;for(const[t,e]of Object.entries(n))this._FormatTypeMap_Ext2Str.set(e,t)};this.frameID=null,this.cbRender=()=>{},this._onContextLost=t=>{t.preventDefault(),this.stop()},this._onContextRestored=e,this._onContextCreationError=t=>{console.error(t.statusMessage||"WebGL context creation error: unknown error.")},this.canvas.addEventListener("webglcontextlost",this._onContextLost,!1),this.canvas.addEventListener("webglcontextrestored",this._onContextRestored,!1),this.canvas.addEventListener("webglcontextcreationerror",this._onContextCreationError,!1),e()}compileShaderProgram(t){let e=this.gl.createProgram();if(!e)throw new Error("WebGL shader program creation failed.");for(const[n,r]of Object.entries(t)){const t=this.gl.createShader(this.shaderStage[n]);if(!t)throw new Error("WebGL shader creation failed.");if(this.gl.shaderSource(t,r),this.gl.compileShader(t),!this.gl.getShaderParameter(t,this.gl.COMPILE_STATUS)){const e=this.gl.getShaderInfoLog(t);throw this.gl.deleteShader(t),new Error("WebGL shader compile failed:"+e)}this.gl.attachShader(e,t)}if(this.gl.linkProgram(e),!this.gl.getProgramParameter(e,this.gl.LINK_STATUS)){const t=this.gl.getProgramInfoLog(e);throw this.gl.deleteProgram(e),new Error("WebGL shader compile failed:"+t)}return e}getShaderProgramUniformLocation(t,e){let n={};for(const r of e)n[r]=this.gl.getUniformLocation(t,r);return n}getShaderProgramUniformBlockLocation(t,e){let n={};for(const r of e)n[r]=this.gl.getUniformBlockIndex(t,r);return n}getShaderProgramAttribLocation(t,e){let n={};for(const r of e)n[r]=this.gl.getAttribLocation(t,r);return n}getGLArrayElementType(t){const e=t[Symbol.toStringTag];return e in this._ElementTypeMap_JS2GL?this._ElementTypeMap_JS2GL[e]:null}getGLTexInternalFormat(t,e){const n=this._FormatTypeMap_Ext2Int.get(e);if(n){const e=n.get(t);if(e)return e}return null}texImage2D(t,e,n,r,i,s){var a;const o=this.getGLArrayElementType(s);if(!o)throw new Error(`Unsupported data format: ${s[Symbol.toStringTag]}`);const l=this.getGLTexInternalFormat(i,o);if(!l)throw new Error(`No available internal format for ${s[Symbol.toStringTag]} and ${null!=(a=this._FormatTypeMap_Ext2Str.get(i))?a:"unknown"}.`);this.gl.HALF_FLOAT==o&&(s=new Uint16Array(s.buffer)),this.gl.texImage2D(t,e,l,n,r,0,i,o,s)}texImage3D(t,e,n,r,i,s,a){var o;const l=this.getGLArrayElementType(a);if(!l)throw new Error("Unsupported data format: "+a[Symbol.toStringTag]);const c=this.getGLTexInternalFormat(s,l);if(!c)throw new Error(`No available internal format for ${a[Symbol.toStringTag]} and ${null!=(o=this._FormatTypeMap_Ext2Str.get(s))?o:"unknown"}.`);this.gl.HALF_FLOAT==l&&(a=new Uint16Array(a.buffer)),this.gl.texImage3D(t,e,c,n,r,i,0,s,l,a)}run(t,e){if(this.running=!0,this.cbRender=t,e&&e instanceof HTMLVideoElement){this.syncMedia=e;const t=(n,r)=>{this.running&&(this.syncMediaTime=r.mediaTime,this.cbRender(this),this.frameID=e.requestVideoFrameCallback(t))};this.syncMediaTime=e.currentTime,this.cbRender(this),e.requestVideoFrameCallback(t)}else{const t=()=>{this.running&&(this.cbRender(this),this.frameID=requestAnimationFrame(t))};t()}}refresh(){this.cbRender(this)}getSyncMediaTime(){return this.syncMediaTime}stop(){null!==this.frameID&&(this.syncMedia?(this.syncMedia.cancelVideoFrameCallback(this.frameID),this.syncMedia=null,this.syncMediaTime=null):cancelAnimationFrame(this.frameID),this.frameID=null),this.running=!1}simulateContextFault(t){this._lost_context_sim&&(t?this._lost_context_sim.restoreContext():this._lost_context_sim.loseContext())}captureFrame(){const t=this.canvas.width,e=this.canvas.height,n=new Uint8ClampedArray(t*e*4);return this.gl.readPixels(0,0,t,e,this.gl.RGBA,this.gl.UNSIGNED_BYTE,n),{width:t,height:e,data:n}}destroy(){if(this._isDestroyed||!this.gl)return;const t=this.gl;try{const e=t.getExtension("WEBGL_lose_context");if(e&&e.loseContext(),t.clear(t.COLOR_BUFFER_BIT|t.DEPTH_BUFFER_BIT|t.STENCIL_BUFFER_BIT),t.flush(),this.canvas){const t=this.canvas.getContext("2d");t&&t.clearRect(0,0,this.canvas.width,this.canvas.height)}this.canvas&&(this.canvas.removeEventListener("webglcontextlost",this._onContextLost,!1),this.canvas.removeEventListener("webglcontextrestored",this._onContextRestored,!1),this.canvas.removeEventListener("webglcontextcreationerror",this._onContextCreationError,!1)),this.gl=null,this._isDestroyed=!0}catch(t){this._isDestroyed=!0}}}function length(t){return Math.sqrt(t.reduce((t,e)=>t+e*e,0))}function normalize$1(t){let e=length(t);return t.map(t=>t/e)}function mvmul(t,e){const n=t.length,r=e.length;let i=Array(n);for(let s=0;s<n;s++){i[s]=0;for(let n=0;n<r;n++)i[s]+=t[s][n]*e[n]}return i}function mmul(t,e){const n=t.length,r=e.length,i=e[0].length;let s=Array(n);for(let a=0;a<n;a++){let n=Array(i);for(let s=0;s<i;s++){n[s]=0;for(let i=0;i<r;i++)n[s]+=t[a][i]*e[i][s]}s[a]=n}return s}function transpose(t){const e=t.length,n=t[0].length;let r=Array(n);for(let i=0;i<n;i++){let n=Array(e);for(let r=0;r<e;r++)n[r]=t[r][i];r[i]=n}return r}function identity(t){let e=Array(t);for(let n=0;n<t;n++){let r=Array(t);for(let e=0;e<t;e++)r[e]=n==e?1:0;e[n]=r}return e}function det3(t){let e=0;return e+=t[0][0]*t[1][1]*t[2][2],e+=t[0][1]*t[1][2]*t[2][0],e+=t[0][2]*t[1][0]*t[2][1],e-=t[0][2]*t[1][1]*t[2][0],e-=t[0][1]*t[1][0]*t[2][2],e-=t[0][0]*t[1][2]*t[2][1],e}function inv3(t){const e=1/det3(t);return[[(t[1][1]*t[2][2]-t[2][1]*t[1][2])*e,(t[0][2]*t[2][1]-t[0][1]*t[2][2])*e,(t[0][1]*t[1][2]-t[0][2]*t[1][1])*e],[(t[1][2]*t[2][0]-t[1][0]*t[2][2])*e,(t[0][0]*t[2][2]-t[0][2]*t[2][0])*e,(t[1][0]*t[0][2]-t[0][0]*t[1][2])*e],[(t[1][0]*t[2][1]-t[2][0]*t[1][1])*e,(t[2][0]*t[0][1]-t[0][0]*t[2][1])*e,(t[0][0]*t[1][1]-t[1][0]*t[0][1])*e]]}function inv4(t){let e=[[...t[0]],[...t[1]],[...t[2]],[...t[3]]],n=[0,0,0,0],r=[0,0,0,0],i=0;for(let t=0;t<4;t++){let s=0;for(let i=t;i<4;i++)for(let a=t;a<4;a++)Math.abs(e[i][a])>s&&(s=Math.abs(e[i][a]),n[t]=i,r[t]=a);if(s<Number.EPSILON)return new Array(4).fill(new Array(4).fill(NaN));if(n[t]!=t)for(let r=0;r<4;r++)i=e[t][r],e[t][r]=e[n[t]][r],e[n[t]][r]=i;if(r[t]!=t)for(let n=0;n<4;n++)i=e[n][t],e[n][t]=e[n][r[t]],e[n][r[t]]=i;e[t][t]=1/e[t][t];for(let n=0;n<4;n++)n!=t&&(e[t][n]*=e[t][t]);for(let n=0;n<4;n++)if(n!=t)for(let r=0;r<4;r++)r!=t&&(e[n][r]-=e[n][t]*e[t][r]);for(let n=0;n<4;n++)n!=t&&(e[n][t]*=-e[t][t])}for(let t=3;t>=0;t--){if(r[t]!=t)for(let n=0;n<4;n++)i=e[t][n],e[t][n]=e[r[t]][n],e[r[t]][n]=i;if(n[t]!=t)for(let r=0;r<4;r++)i=e[r][t],e[r][t]=e[r][n[t]],e[r][n[t]]=i}return e}function quaternion_conj(t){return[t[0],-t[1],-t[2],-t[3]]}function quaternion_mul(t,e){return[t[0]*e[0]-t[1]*e[1]-t[2]*e[2]-t[3]*e[3],t[0]*e[1]+t[1]*e[0]+t[2]*e[3]-t[3]*e[2],t[0]*e[2]-t[1]*e[3]+t[2]*e[0]+t[3]*e[1],t[0]*e[3]+t[1]*e[2]-t[2]*e[1]+t[3]*e[0]]}function quaternion_to_mat(t){const[e,n,r,i]=t;return[[e*e+n*n-r*r-i*i,2*(n*r-i*e),2*(n*i+r*e)],[2*(n*r+i*e),e*e-n*n+r*r-i*i,2*(r*i-n*e)],[2*(n*i-r*e),2*(r*i+n*e),e*e-n*n-r*r+i*i]]}function GivensTransform(t,e,n,r){const i=Math.sin(r),s=Math.cos(r),a=t[0].length;for(let r=0;r<a;r++){const a=i*t[e][r]+s*t[n][r];t[e][r]=s*t[e][r]-i*t[n][r],t[n][r]=a}}function Euler_to_mat(t,e="xyz"){let n=identity(3);switch(e){case"xyz":case"zxy":GivensTransform(n,1,2,t[0]),GivensTransform(n,2,0,t[1]),GivensTransform(n,0,1,t[2]);break;case"yzx":GivensTransform(n,0,1,t[2]),GivensTransform(n,1,2,t[0]),GivensTransform(n,2,0,t[1]);break;case"xzy":GivensTransform(n,1,2,t[0]),GivensTransform(n,0,1,t[2]),GivensTransform(n,2,0,t[1]);break;case"yxz":GivensTransform(n,2,0,t[1]),GivensTransform(n,1,2,t[0]),GivensTransform(n,0,1,t[2]);break;case"zyx":GivensTransform(n,0,1,t[2]),GivensTransform(n,2,0,t[1]),GivensTransform(n,1,2,t[0]);break;default:throw Error("Unrecognizable rotation order.")}return n}function make_homogeneous(t,e){return[[t[0][0],t[0][1],t[0][2],e[0]],[t[1][0],t[1][1],t[1][2],e[1]],[t[2][0],t[2][1],t[2][2],e[2]],[0,0,0,1]]}function flatten(t){const e=t.length,n=t[0].length;let r=Array(e*n);for(let i=0;i<e;i++)for(let e=0;e<n;e++)r[i*n+e]=t[i][e];return r}const performanceConstant={load_resource:"load_resource",ttsa_connect:"ttsa_connect",ttsa_ready:"ttsa_ready",first_avatar_render:"first_avatar_render",first_webgl_render:"first_webgl_render",ttsa_body_res:"ttsa_body_res",start_action_res:"start_action_res",start_action_render:"start_action_render",load_video:"load_video",decode_video:"decode_video",voice_response_play:"voice_response_play",first_decode_video:"first_decode_video",first_render:"first_render"};class PerformanceTracker{constructor(){this.marks=new Map,this.measures=new Map,this.reportFunc=null,this.onStateRenderChange=()=>{},this.firstDecodeTime=0,this.firstRenderTime=0,this.marks=new Map,this.measures=new Map}getFirstInfo(){return{decode_speed:this.firstDecodeTime,render_speed:this.firstRenderTime}}markStart(t,e){this.marks.set(t,{state:e,time:performance.now()})}markEnd(t,e){const n=this.marks.get(t);if(!n)return;if(e&&"string"==typeof e&&e!==(null==n?void 0:n.state))return;const r=performance.now()-n.time;return this.measures.set(t,{state:null==n?void 0:n.state,time:r}),n.state&&t===performanceConstant.start_action_render&&this.onStateRenderChange(n.state,r),this.reportMetric(),t!==performanceConstant.load_video&&t!==performanceConstant.decode_video&&this.marks.delete(t),t===performanceConstant.first_decode_video&&(this.firstDecodeTime=r),t===performanceConstant.first_render&&(this.firstRenderTime=r),r}getAllMetrics(){return Object.fromEntries(this.measures.entries())}getVideoMetrics(){const t=this.getAllMetrics();return Object.fromEntries(Object.entries(t).filter(([t])=>[performanceConstant.decode_video,performanceConstant.load_video].includes(t)))}setReportFunc(t){this.reportFunc=t}reportMetric(){var t;const e=this.getAllMetrics();if(Object.keys(e).length>0&&null!=(t=this.reportFunc)&&t.getStatus()){const t=Object.fromEntries(Object.entries(e).filter(([t])=>![performanceConstant.load_video,performanceConstant.decode_video].includes(t)));var n;Object.keys(t).length>0&&(null==(n=this.reportFunc)||n.sendPerfLog(t));for(const e in t)e!==performanceConstant.decode_video&&e!==performanceConstant.load_video&&this.measures.delete(e)}}setOnStateRenderChange(t){this.onStateRenderChange=t}}window.performanceTracker=new PerformanceTracker;const shadow_sample_count=4,shader_common="\n float randFloat(vec2 p) {\n // generate a uniformely distributed float in [0, 1).\n return fract(sin(dot(p, vec2(127.1, 311.7))) * 43758.5453);\n }\n bool isMaskedBitSet(uint value, uint mask){\n return bool(value & mask);\n }\n vec4 RGB2sRGB(vec4 color){\n for(uint i = 0u; i < 4u; i++){\n if(color[i] <= 0.0031308)color[i] *= 12.92;\n else color[i] = 1.055 * pow(color[i], 1.0 / 2.4) - 0.055;\n }\n return color;\n }\n vec4 sRGB2RGB(vec4 color){\n for(uint i = 0u; i < 4u; i++){\n if(color[i] <= 0.04045)color[i] /= 12.92;\n else color[i] = pow((color[i] + 0.055) / 1.055, 2.4);\n }\n return color;\n }\n",vs_background="#version 300 es\n layout(location = 0) in vec2 pos;\n layout(location = 1) in vec2 texCoord;\n out vec2 v_texCoord;\n void main() {\n gl_Position = vec4(pos, 0, 1);\n v_texCoord = texCoord;\n }\n",fs_background=`#version 300 es\n precision mediump float;\n uniform sampler2D u_image_bg, u_image_char_body, u_image_mesh_color, u_image_mesh_alpha;\n uniform mat2 u_transform_2d; // mat2[0] = scale, mat2[1] = translation\n uniform uint flags; // 1 - has background, 2 - with multisample coverage, 4 - shadow fx\n\n layout (std140) uniform ub_shadow_fx_info {\n mat3 transform[2];\n vec4 color;\n vec4 sampleParams; // sample radius, unused, unused, unused \n } ub_shadow_fx;\n\n in vec2 v_texCoord;\n out vec4 fragColor;\n\n ${shader_common}\n\n vec2 tex2scr(vec2 coord){\n return vec2(coord.x * 2.0 - 1.0, 1.0 - coord.y * 2.0);\n }\n vec2 scr2tex(vec2 coord){\n return vec2(coord.x * 0.5 + 0.5, 0.5 - coord.y * 0.5);\n }\n vec2 randomUnitVec2D(float seed) {\n float theta = seed * 2.0 * 3.14159265359;\n return vec2(cos(theta), sin(theta));\n }\n float sampleOpacity(vec2 texCoord, mat2 u_transform_2d){\n float result = texture(u_image_mesh_color, vec2(texCoord.x, 1.0 - texCoord.y)).a;\n texCoord = texCoord * u_transform_2d[0] + u_transform_2d[1];\n texCoord.x = texCoord.x * 0.5 + 0.5;\n result += (1.0 - result) * texture(u_image_char_body, texCoord).r;\n return result;\n }\n float PI = 3.14159265359;\n\n void main() {\n float randSeed = randFloat(vec2(gl_FragCoord.xy));\n\n vec2 texcoord_transformed = v_texCoord * u_transform_2d[0] + u_transform_2d[1];\n texcoord_transformed = clamp(texcoord_transformed, 0.0, 1.0);\n vec2 texCoord_char_color = vec2(texcoord_transformed.x * 0.5, texcoord_transformed.y);\n vec2 texCoord_char_alpha = vec2(texcoord_transformed.x * 0.5 + 0.5, texcoord_transformed.y);\n vec2 texCoord_mesh = vec2(v_texCoord.x, 1.0 - v_texCoord.y);\n\n vec4 char_color = texture(u_image_char_body, texCoord_char_color);\n vec4 char_alpha = texture(u_image_char_body, texCoord_char_alpha);\n char_color = sRGB2RGB(char_color);\n char_alpha = sRGB2RGB(char_alpha);\n float char_alpha_back = char_alpha.r;\n float char_alpha_front = max(char_alpha.r - char_alpha.b, 0.0);\n\n vec4 mesh_color_srgb = texture(u_image_mesh_color, texCoord_mesh);\n float mesh_alpha = mesh_color_srgb.a;\n if(isMaskedBitSet(flags, 2u)){\n float mesh_coverage = texture(u_image_mesh_alpha, texCoord_mesh).r;\n mesh_color_srgb.rgb /= max(mesh_coverage, 9e-5); // epsilon for float16\n }\n\n vec3 final_rgb = char_alpha_back * char_color.rgb;\n float final_alpha = char_alpha_back;\n\n if(isMaskedBitSet(flags, 4u)){ // fake shadow\n vec3 pos_shadow = vec3(tex2scr(v_texCoord), 1.0);\n pos_shadow = ub_shadow_fx.transform[1] * pos_shadow;\n if(pos_shadow.z > 0.0 && pos_shadow.y > 0.0){\n // simple and noisy blur\n pos_shadow /= pos_shadow.z;\n float radius = ub_shadow_fx.sampleParams.x * pos_shadow.y;\n vec2 randVec = randomUnitVec2D(randSeed);\n mat2 randMat = mat2(randVec.x, randVec.y, -randVec.y, randVec.x);\n float shadow_opacity = 0.0;\n\n int sampleCount = radius > 0.0 ? ${shadow_sample_count} : 1;\n for(int i=0;i<sampleCount;i++){\n float sampleDist = (float(i) + 0.5) / float(sampleCount);\n float angle = 26.0 * PI * sampleDist; // prime number * 2pi\n sampleDist = radius * sqrt(sampleDist);\n vec2 sampleVec = sampleDist * randMat * vec2(cos(angle), sin(angle));\n\n vec3 pos_shadow_proj = ub_shadow_fx.transform[0] * (pos_shadow + vec3(sampleVec, 0.0));\n vec2 texCoord_shadow = clamp(pos_shadow_proj.xy / pos_shadow_proj.z, -1.0, 1.0);\n texCoord_shadow = scr2tex(texCoord_shadow);\n shadow_opacity += sampleOpacity(texCoord_shadow, u_transform_2d);\n }\n shadow_opacity /= float(sampleCount);\n float shadow_alpha = shadow_opacity * ub_shadow_fx.color.a;\n\n final_rgb = final_rgb + (1.0 - final_alpha) * shadow_alpha * ub_shadow_fx.color.rgb;\n final_alpha = final_alpha + (1.0 - final_alpha) * shadow_alpha;\n }\n }\n final_rgb = mesh_alpha * mesh_color_srgb.rgb + (1.0 - mesh_alpha) * final_rgb;\n final_alpha = mesh_alpha + (1.0 - mesh_alpha) * final_alpha;\n final_rgb = char_alpha_front * char_color.rgb + (1.0 - char_alpha_front) * final_rgb;\n final_alpha = char_alpha_front + (1.0 - char_alpha_front) * final_alpha;\n\n if(isMaskedBitSet(flags, 1u)){\n vec4 bg_color = sRGB2RGB(texture(u_image_bg, v_texCoord));\n final_rgb += bg_color.rgb * (1.0 - final_alpha);\n final_alpha = 1.0;\n }\n final_rgb = RGB2sRGB(vec4(final_rgb, 1.0)).rgb;\n fragColor = vec4(final_rgb, final_alpha);\n }\n`,uniform_var_list_bg=["u_image_bg","u_image_char_body","u_image_mesh_color","u_image_mesh_alpha","u_transform_2d","flags"],uniform_block_list_bg=["ub_shadow_fx_info"];function generateMeshPipelineShader(t){return{vertex:`#version 300 es\n precision highp float;\n\n layout (std140) uniform ub_rig_info {\n mat4 joint_matrices[${t.max_bones}];\n vec4 bs_weights[${t.max_bs_count/4}];\n } ub_rig;\n \n uniform sampler2D u_image_bs; // used for blendshape deformation\n uniform mat4 u_proj_mat;\n uniform mat2 u_transform_2d; // mat2[0] = scale, mat2[1] = translation\n uniform uint u_bs_count; // number of bs weight vectors (divided by 4)\n uniform uint flags; // 1 - has opacity\n\n layout(location = 0) in vec3 pos;\n layout(location = 1) in vec2 tex_coord;\n layout(location = 2) in float opacity;\n layout(location = 3) in uvec4 bone_index_0_4;\n layout(location = 4) in uvec4 bone_index_4_8;\n layout(location = 5) in vec4 bone_weight_0_4;\n layout(location = 6) in vec4 bone_weight_4_8;\n\n out vec4 v_pos;\n out vec2 v_tex_coord;\n out float v_opacity;\n\n ${shader_common}\n\n vec4 lbs_transform(vec3 pos){\n float total_weight = 0.0;\n vec4 aug_pos = vec4(pos, 1.0);\n vec4 result = vec4(0.0);\n uint index;\n for(index = 0u;index < 8u;index++){\n uint joint_index;\n float joint_weight;\n if(index < 4u) {\n joint_index = bone_index_0_4[index];\n joint_weight = bone_weight_0_4[index];\n }\n else {\n joint_index = bone_index_4_8[index - 4u];\n joint_weight = bone_weight_4_8[index - 4u];\n }\n if(255u == joint_index)break;\n else result += joint_weight * (ub_rig.joint_matrices[joint_index] * aug_pos);\n }\n result /= result.w;\n return vec4(result.xyz, 1.0);\n }\n\n vec3 bs_accumulate(uint vertex_id){\n uint texWidth = uint(textureSize(u_image_bs, 0).x);\n vec3 pos = vec3(0.0);\n\n uint vertex_offset = vertex_id * u_bs_count * 3u;\n for(uint i = 0u; i < u_bs_count; i++){\n vec4 bs_weight_vec = ub_rig.bs_weights[i];\n for (uint j = 0u; j < 3u; j++){\n uint texel_offset = j * u_bs_count + vertex_offset + i;\n uint texel_x = texel_offset % texWidth;\n uint texel_y = texel_offset / texWidth;\n vec4 data = texelFetch(u_image_bs, ivec2(texel_x, texel_y), 0);\n pos[j] += dot(data, bs_weight_vec);\n }\n }\n return pos;\n }\n \n void main() {\n if(isMaskedBitSet(flags, 1u))v_opacity = opacity; else v_opacity = 1.0;\n \n vec3 bs_pos = vec3(0.0);\n if(u_bs_count > 0u)bs_pos = bs_accumulate(uint(gl_VertexID)) * v_opacity;\n v_pos = u_proj_mat * lbs_transform(pos + bs_pos);\n v_pos /= v_pos.w;\n v_pos.xy = u_transform_2d[0] * v_pos.xy + u_transform_2d[1];\n v_tex_coord = tex_coord;\n gl_Position = v_pos;\n }\n`,fragment_mask:"#version 300 es\n precision highp float;\n \n in vec4 v_pos;\n in float v_opacity;\n in vec2 v_tex_coord;\n\n out vec4 fragColor;\n\n void main() {\n if(gl_FrontFacing)fragColor = vec4(1.0);\n else fragColor = vec4(0.0);\n }\n",fragment:`#version 300 es\n precision highp int;\n precision highp float;\n precision highp sampler2DArray;\n precision highp sampler3D;\n layout (std140) uniform ub_pca_info {\n vec4 weights[${t.max_pca_component_count/4}];\n } ub_pca;\n uniform sampler2DArray u_image_pca;\n uniform sampler3D u_image_lut;\n uniform uint flags; // 2 - has LUT, 4 - unsigned PCA component\n uniform vec3 u_gamma;\n uniform vec3 u_color_balance; // r/c, g/m, b/y\n\n ${shader_common}\n \n vec4 pca_accumulate(vec2 tex_coord, bool _unsigned){\n ivec3 texSize = textureSize(u_image_pca, 0);\n vec4 result = vec4(0.0);\n for(int i = 0; i < texSize.z; i++){\n int vec_index = i / 4;\n int elem_index = i % 4;\n vec4 pca_sample = texture(u_image_pca, vec3(tex_coord, float(i)));\n if(_unsigned)pca_sample = 2.0 * pca_sample - 1.0;\n result += ub_pca.weights[vec_index][elem_index] * pca_sample;\n }\n return result;\n }\n \n in vec4 v_pos;\n in float v_opacity;\n in vec2 v_tex_coord;\n\n out vec4 fragColor;\n\n void main() {\n if(gl_FrontFacing){\n vec2 fragTexCoord = v_tex_coord;\n vec4 sample_color = pca_accumulate(v_tex_coord, isMaskedBitSet(flags, 4u));\n if(isMaskedBitSet(flags, 2u))sample_color = texture(u_image_lut, sample_color.rgb);\n // Apply gamma correction\n vec3 final_color = pow(sample_color.rgb, u_gamma);\n\n // Apply color balance\n // Convert -100 to 100 range to -0.5 to 0.5 range\n vec3 balance_adjusted = u_color_balance / 200.0; // Map -100..100 to -0.5..0.5\n\n // Red/Cyan adjustment\n final_color.r += balance_adjusted.x;\n final_color.g -= balance_adjusted.x; // Cyan is opposite of Red\n\n // Green/Magenta adjustment\n final_color.g += balance_adjusted.y;\n final_color.b -= balance_adjusted.y; // Magenta is opposite of Green\n\n // Blue/Yellow adjustment\n final_color.b += balance_adjusted.z;\n final_color.r -= balance_adjusted.z; // Yellow is opposite of Blue\n\n // Clamp values to [0, 1]\n final_color = clamp(final_color, 0.0, 1.0);\n fragColor = sRGB2RGB(vec4(final_color.bgr, v_opacity));\n }\n else fragColor = vec4(0.0);\n }\n`}}const uniform_var_list_mesh=["u_proj_mat","u_transform_2d","u_image","u_image_bs","u_image_pca","u_image_lut","u_bs_count","flags","u_gamma","u_color_balance"],uniform_block_list_mesh=["ub_pca_info","ub_rig_info"];class GLPipeline{assembleBackgroundPipeline(){this._ub_shadow_fx_data=new Float32Array(32);const t=this.device.compileShaderProgram({vertex:vs_background,fragment:fs_background}),e=this.device.getShaderProgramUniformLocation(t,uniform_var_list_bg),n=this.device.getShaderProgramUniformBlockLocation(t,uniform_block_list_bg);this.backgroundPipelineInfo={program:t,progUniforms:e,progUniformBlocks:n},this.device.gl.uniformBlockBinding(this.backgroundPipelineInfo.program,this.backgroundPipelineInfo.progUniformBlocks.ub_shadow_fx_info,0),this.backgroundVAO=this.device.gl.createVertexArray(),this.device.gl.bindVertexArray(this.backgroundVAO);const r=this.device.gl.createBuffer();this.device.gl.bindBuffer(this.device.gl.ARRAY_BUFFER,r),this.device.gl.bufferData(this.device.gl.ARRAY_BUFFER,new Float32Array([-1,-1,0,1,1,-1,1,1,-1,1,0,0,-1,1,0,0,1,-1,1,1,1,1,1,0]),this.device.gl.STATIC_DRAW),this.device.gl.enableVertexAttribArray(0),this.device.gl.vertexAttribPointer(0,2,this.device.gl.FLOAT,!1,16,0),this.device.gl.enableVertexAttribArray(1),this.device.gl.vertexAttribPointer(1,2,this.device.gl.FLOAT,!1,16,8),this.device.gl.bindBuffer(this.device.gl.ARRAY_BUFFER,null);let i={};i.ub_shadow_fx_info=this.device.gl.createBuffer(),this.device.gl.bindBuffer(this.device.gl.UNIFORM_BUFFER,i.ub_shadow_fx_info),this.device.gl.bufferData(this.device.gl.UNIFORM_BUFFER,this._ub_shadow_fx_data,this.device.gl.DYNAMIC_DRAW),this.backgroundBuffers=i,this.device.gl.bindVertexArray(null);let s={};if(s.u_image_bg=this.device.gl.createTexture(),!s.u_image_bg)throw new Error("WebGL texture creation failed.");if(this.device.gl.bindTexture(this.device.gl.TEXTURE_2D,s.u_image_bg),this.device.gl.texParameteri(this.device.gl.TEXTURE_2D,this.device.gl.TEXTURE_WRAP_S,this.device.gl.CLAMP_TO_EDGE),this.device.gl.texParameteri(this.device.gl.TEXTURE_2D,this.device.gl.TEXTURE_WRAP_T,this.device.gl.CLAMP_TO_EDGE),this.device.gl.texParameteri(this.device.gl.TEXTURE_2D,this.device.gl.TEXTURE_MIN_FILTER,this.device.gl.LINEAR),s.u_image_char_body=this.device.gl.createTexture(),!s.u_image_char_body)throw new Error("WebGL texture creation failed.");this.device.gl.bindTexture(this.device.gl.TEXTURE_2D,s.u_image_char_body),this.device.gl.texParameteri(this.device.gl.TEXTURE_2D,this.device.gl.TEXTURE_WRAP_S,this.device.gl.CLAMP_TO_EDGE),this.device.gl.texParameteri(this.device.gl.TEXTURE_2D,this.device.gl.TEXTURE_WRAP_T,this.device.gl.CLAMP_TO_EDGE),this.device.gl.texParameteri(this.device.gl.TEXTURE_2D,this.device.gl.TEXTURE_MIN_FILTER,this.device.gl.LINEAR),this.backgroundTextures=s}assembleMeshPipelines(t){if(t.char){const e=t.char;let n={max_pca_component_count:4,max_bs_count:4,max_bones:Math.max(e.skeleton.length,1)};for(let t=0;t<e.mesh.length;t++){const r=e.mesh[t].textureModels;let i=0;for(let t of r){let e=t.data.size[0]+3;e-=e%4,i=Math.max(i,e)}n.max_pca_component_count=Math.max(n.max_pca_component_count,i);let s=e.mesh[t].blendshapes.size[2]+3;s-=s%4,n.max_bs_count=Math.max(n.max_bs_count,s)}this.meshStatistics=n,this._ub_rig_info_data=new Float32Array(16*this.meshStatistics.max_bones+this.meshStatistics.max_bs_count),this._ub_pca_info_data=new Float32Array(this.meshStatistics.max_pca_component_count);const r=generateMeshPipelineShader(this.meshStatistics);let i=this.device.compileShaderProgram({vertex:r.vertex,fragment:r.fragment}),s=this.device.getShaderProgramUniformLocation(i,uniform_var_list_mesh),a=this.device.getShaderProgramUniformBlockLocation(i,uniform_block_list_mesh);this.meshPipelineInfo={program:i,progUniforms:s,progUniformBlocks:a},this.device.gl.uniformBlockBinding(this.meshPipelineInfo.program,this.meshPipelineInfo.progUniformBlocks.ub_rig_info,0),this.device.gl.uniformBlockBinding(this.meshPipelineInfo.program,this.meshPipelineInfo.progUniformBlocks.ub_pca_info,1),i=this.device.compileShaderProgram({vertex:r.vertex,fragment:r.fragment_mask}),s=this.device.getShaderProgramUniformLocation(i,uniform_var_list_mesh),a=this.device.getShaderProgramUniformBlockLocation(i,uniform_block_list_mesh),this.maskPipelineInfo={program:i,progUniforms:s,progUniformBlocks:a},this.device.gl.uniformBlockBinding(this.maskPipelineInfo.program,this.maskPipelineInfo.progUniformBlocks.ub_rig_info,0),this.meshInfos=[];for(let t=0;t<e.mesh.length;t++){let r={VAO:this.device.gl.createVertexArray(),buffers:{},textures:{},texturePCAModels:[],uniformUInts:{}};if(this.device.gl.bindVertexArray(r.VAO),null===this.device.getGLArrayElementType(e.mesh[t].blendshapes.data))throw new Error(`Data type unsupported by WebGL: ${e.mesh[t].blendshapes.data}`);if(r.buffers.pos=this.device.gl.createBuffer(),this.device.gl.bindBuffer(this.device.gl.ARRAY_BUFFER,r.buffers.pos),this.device.gl.bufferData(this.device.gl.ARRAY_BUFFER,e.mesh[t].vertices.data,this.device.gl.STATIC_DRAW),this.device.gl.enableVertexAttribArray(0),this.device.gl.vertexAttribPointer(0,3,this.device.getGLArrayElementType(e.mesh[t].blendshapes.data),!1,0,0),null===this.device.getGLArrayElementType(e.mesh[t].UVCoord.data))throw new Error(`Data type unsupported by WebGL: ${e.mesh[t].UVCoord.data}`);if(r.buffers.tex_coord=this.device.gl.createBuffer(),this.device.gl.bindBuffer(this.device.gl.ARRAY_BUFFER,r.buffers.tex_coord),this.device.gl.bufferData(this.device.gl.ARRAY_BUFFER,e.mesh[t].UVCoord.data,this.device.gl.STATIC_DRAW),this.device.gl.enableVertexAttribArray(1),this.device.gl.vertexAttribPointer(1,2,this.device.getGLArrayElementType(e.mesh[t].UVCoord.data),!0,0,0),e.mesh[t].opacity){if(null===this.device.getGLArrayElementType(e.mesh[t].opacity.data))throw new Error(`Data type unsupported by WebGL: ${e.mesh[t].opacity.data}`);r.buffers.opacity=this.device.gl.createBuffer(),this.device.gl.bindBuffer(this.device.gl.ARRAY_BUFFER,r.buffers.opacity),this.device.gl.bufferData(this.device.gl.ARRAY_BUFFER,e.mesh[t].opacity.data,this.device.gl.STATIC_DRAW),this.device.gl.enableVertexAttribArray(2),this.device.gl.vertexAttribPointer(2,1,this.device.getGLArrayElementType(e.mesh[t].opacity.data),!0,0,0)}if(r.buffers.bone_indices=this.device.gl.createBuffer(),this.device.gl.bindBuffer(this.device.gl.ARRAY_BUFFER,r.buffers.bone_indices),this.device.gl.bufferData(this.device.gl.ARRAY_BUFFER,e.mesh[t].jointIndex,this.device.gl.STATIC_DRAW),this.device.gl.enableVertexAttribArray(3),this.device.gl.vertexAttribIPointer(3,4,this.device.gl.UNSIGNED_BYTE,8,0),this.device.gl.enableVertexAttribArray(4),this.device.gl.vertexAttribIPointer(4,4,this.device.gl.UNSIGNED_BYTE,8,4),r.buffers.bone_weight=this.device.gl.createBuffer(),this.device.gl.bindBuffer(this.device.gl.ARRAY_BUFFER,r.buffers.bone_weight),this.device.gl.bufferData(this.device.gl.ARRAY_BUFFER,e.mesh[t].jointWeight,this.device.gl.STATIC_DRAW),this.device.gl.enableVertexAttribArray(5),this.device.gl.vertexAttribPointer(5,4,this.device.gl.FLOAT,!1,32,0),this.device.gl.enableVertexAttribArray(6),this.device.gl.vertexAttribPointer(6,4,this.device.gl.FLOAT,!1,32,16),this.device.gl.bindBuffer(this.device.gl.ARRAY_BUFFER,null),null===this.device.getGLArrayElementType(e.mesh[t].triangles.data))throw new Error(`Data type unsupported by WebGL: ${e.mesh[t].triangles.data}`);if(r.buffers.indices=this.device.gl.createBuffer(),this.device.gl.bindBuffer(this.device.gl.ELEMENT_ARRAY_BUFFER,r.buffers.indices),this.device.gl.bufferData(this.device.gl.ELEMENT_ARRAY_BUFFER,e.mesh[t].triangles.data,this.device.gl.STATIC_DRAW),r.buffers.ub_pca_info=this.device.gl.createBuffer(),this.device.gl.bindBuffer(this.device.gl.UNIFORM_BUFFER,r.buffers.ub_pca_info),this.device.gl.bufferData(this.device.gl.UNIFORM_BUFFER,new Float32Array(n.max_pca_component_count),this.device.gl.DYNAMIC_DRAW),r.buffers.ub_rig_info=this.device.gl.createBuffer(),this.device.gl.bindBuffer(this.device.gl.UNIFORM_BUFFER,r.buffers.ub_rig_info),this.device.gl.bufferData(this.device.gl.UNIFORM_BUFFER,new Float32Array(16*n.max_bones+n.max_bs_count),this.device.gl.DYNAMIC_DRAW),this.device.gl.bindVertexArray(null),e.mesh[t].blendshapes.size[2]>0){let n=[Math.ceil(e.mesh[t].blendshapes.size[2]/4),e.mesh[t].blendshapes.size[0]*e.mesh[t].blendshapes.size[1]],i=Math.ceil(Math.sqrt(n[0]*n[1])),s=4*n[0],a=new Float32Array(i*i*4);for(let r=0;r<n[1];r++){for(let n=0;n<e.mesh[t].blendshapes.size[2];n++)a[r*s+n]=e.mesh[t].blendshapes.data[r*e.mesh[t].blendshapes.size[2]+n];for(let n=e.mesh[t].blendshapes.size[2];n<s;n++)a[r*s+n]=0}if(r.textures.u_image_bs=this.device.gl.createTexture(),!r.textures.u_image_bs)throw new Error("WebGL texture creation failed.");this.device.gl.bindTexture(this.device.gl.TEXTURE_2D,r.textures.u_image_bs),this.device.gl.texParameteri(this.device.gl.TEXTURE_2D,this.device.gl.TEXTURE_WRAP_S,this.device.gl.CLAMP_TO_EDGE),this.device.gl.texParameteri(this.device.gl.TEXTURE_2D,this.device.gl.TEXTURE_WRAP_T,this.device.gl.CLAMP_TO_EDGE),this.device.gl.texParameteri(this.device.gl.TEXTURE_2D,this.device.gl.TEXTURE_MIN_FILTER,this.device.gl.NEAREST),this.device.gl.texParameteri(this.device.gl.TEXTURE_2D,this.device.gl.TEXTURE_MAG_FILTER,this.device.gl.NEAREST),this.device.texImage2D(this.device.gl.TEXTURE_2D,0,i,i,this.device.gl.RGBA,a),r.uniformUInts.u_bs_count=n[0]}else r.uniformUInts.u_bs_count=0;for(let n of e.mesh[t].textureModels){let t=this.device.gl.createTexture();if(!t)throw new Error("WebGL texture creation failed.");this.device.gl.bindTexture(this.device.gl.TEXTURE_2D_ARRAY,t),this.device.gl.texParameteri(this.device.gl.TEXTURE_2D_ARRAY,this.device.gl.TEXTURE_WRAP_R,this.device.gl.CLAMP_TO_EDGE),this.device.gl.texParameteri(this.device.gl.TEXTURE_2D_ARRAY,this.device.gl.TEXTURE_WRAP_S,this.device.gl.CLAMP_TO_EDGE),this.device.gl.texParameteri(this.device.gl.TEXTURE_2D_ARRAY,this.device.gl.TEXTURE_WRAP_T,this.device.gl.CLAMP_TO_EDGE),this.device.gl.texParameteri(this.device.gl.TEXTURE_2D_ARRAY,this.device.gl.TEXTURE_MIN_FILTER,this.device.gl.LINEAR),this.device.gl.texParameteri(this.device.gl.TEXTURE_2D_ARRAY,this.device.gl.TEXTURE_MAG_FILTER,this.device.gl.LINEAR);let e=this.device.getGLArrayElementType(n.data.data),i={texture:t,unsigned:this.device.gl.UNSIGNED_BYTE===e||this.device.gl.UNSIGNED_SHORT===e||this.device.gl.UNSIGNED_INT===e},s=n.data.data;if("Float64Array"===n.data.data[Symbol.toStringTag]||this.device.gl.FLOAT===e&&!this.compat_features.OES_texture_float_linear||this.device.gl.HALF_FLOAT===e&&!this.compat_features.OES_texture_half_float_linear){const t=n.data.size[1]*n.data.size[2]*3,e=new Uint8Array(n.data.size[0]*t);let r=new Float32Array(n.data.size[0]);for(let i=0;i<n.data.size[0];i++){let s=1e-6;for(let e=0;e<t;e++)s=Math.max(s,Math.abs(n.data.data[i*t+e]));let a=1/s;for(let r=0;r<t;r++)e[i*t+r]=Math.round(255*(n.data.data[i*t+r]*a*.5+.5));r[i]=s}s=e,i.unsigned=!0,i.scalingFactor=r}n.scalingFactor&&(i.scalingFactor=n.scalingFactor.data),this.device.texImage3D(this.device.gl.TEXTURE_2D_ARRAY,0,n.data.size[1],n.data.size[2],n.data.size[0],this.device.gl.RGB,s),this.device.gl.bindTexture(this.device.gl.TEXTURE_2D_ARRAY,null),r.texturePCAModels.push(i)}this.meshInfos.push(r)}this.initSkeletonStatus=e.evalSkeleton()}if(this.FrameTexture_meshColor=this.device.gl.createTexture(),!this.FrameTexture_meshColor)throw Error("WebGL texture creation failed.");if(this.device.gl.bindTexture(this.device.gl.TEXTURE_2D,this.FrameTexture_meshColor),this.device.gl.texParameteri(this.device.gl.TEXTURE_2D,this.device.gl.TEXTURE_WRAP_S,this.device.gl.CLAMP_TO_EDGE),this.device.gl.texParameteri(this.device.gl.TEXTURE_2D,this.device.gl.TEXTURE_WRAP_T,this.device.gl.CLAMP_TO_EDGE),this.device.gl.texParameteri(this.device.gl.TEXTURE_2D,this.device.gl.TEXTURE_MIN_FILTER,this.device.gl.NEAREST),this.device.gl.texParameteri(this.device.gl.TEXTURE_2D,this.device.gl.TEXTURE_MAG_FILTER,this.device.gl.NEAREST),this.device.gl.texImage2D(this.device.gl.TEXTURE_2D,0,this.device.gl.RGBA8,this.device.canvas.width,this.device.canvas.height,0,this.device.gl.RGBA,this.device.gl.UNSIGNED_BYTE,null),t.multisample){if(this.FrameTexture_meshAlpha=this.device.gl.createTexture(),!this.FrameTexture_meshAlpha)throw Error("WebGL texture creation failed.");this.device.gl.bindTexture(this.device.gl.TEXTURE_2D,this.FrameTexture_meshAlpha),this.device.gl.texParameteri(this.device.gl.TEXTURE_2D,this.device.gl.TEXTURE_WRAP_S,this.device.gl.CLAMP_TO_EDGE),this.device.gl.texParameteri(this.device.gl.TEXTURE_2D,this.device.gl.TEXTURE_WRAP_T,this.device.gl.CLAMP_TO_EDGE),this.device.gl.texParameteri(this.device.gl.TEXTURE_2D,this.device.gl.TEXTURE_MIN_FILTER,this.device.gl.NEAREST),this.device.gl.texParameteri(this.device.gl.TEXTURE_2D,this.device.gl.TEXTURE_MAG_FILTER,this.device.gl.NEAREST),this.device.gl.texImage2D(this.device.gl.TEXTURE_2D,0,this.device.gl.RGBA8,this.device.canvas.width,this.device.canvas.height,0,this.device.gl.RGBA,this.device.gl.UNSIGNED_BYTE,null),this.FrameBuffer_meshColor=this.device.gl.createFramebuffer(),this.device.gl.bindFramebuffer(this.device.gl.FRAMEBUFFER,this.FrameBuffer_meshColor),this.device.gl.framebufferTexture2D(this.device.gl.FRAMEBUFFER,this.device.gl.COLOR_ATTACHMENT0,this.device.gl.TEXTURE_2D,this.FrameTexture_meshColor,0),this.FrameBuffer_meshAlpha=this.device.gl.createFramebuffer(),this.device.gl.bindFramebuffer(this.device.gl.FRAMEBUFFER,this.FrameBuffer_meshAlpha),this.device.gl.framebufferTexture2D(this.device.gl.FRAMEBUFFER,this.device.gl.COLOR_ATTACHMENT0,this.device.gl.TEXTURE_2D,this.FrameTexture_meshAlpha,0);const e=this.device.gl.createRenderbuffer();this.device.gl.bindRenderbuffer(this.device.gl.RENDERBUFFER,e),this.device.gl.renderbufferStorageMultisample(this.device.gl.RENDERBUFFER,t.multisample,this.device.gl.DEPTH_COMPONENT16,this.device.canvas.width,this.device.canvas.height);const n=this.device.gl.createRenderbuffer();this.device.gl.bindRenderbuffer(this.device.gl.RENDERBUFFER,n),this.device.gl.renderbufferStorageMultisample(this.device.gl.RENDERBUFFER,t.multisample,this.device.gl.RGBA8,this.device.canvas.width,this.device.canvas.height);const r=this.device.gl.createRenderbuffer();this.device.gl.bindRenderbuffer(this.device.gl.RENDERBUFFER,r),this.device.gl.renderbufferStorageMultisample(this.device.gl.RENDERBUFFER,t.multisample,this.device.gl.R8,this.device.canvas.width,this.device.canvas.height),this.FrameBuffer_mesh=this.device.gl.createFramebuffer(),this.device.gl.bindFramebuffer(this.device.gl.FRAMEBUFFER,this.FrameBuffer_mesh),this.device.gl.framebufferRenderbuffer(this.device.gl.FRAMEBUFFER,this.device.gl.COLOR_ATTACHMENT0,this.device.gl.RENDERBUFFER,n),this.device.gl.framebufferRenderbuffer(this.device.gl.FRAMEBUFFER,this.device.gl.COLOR_ATTACHMENT1,this.device.gl.RENDERBUFFER,r),this.device.gl.framebufferRenderbuffer(this.device.gl.FRAMEBUFFER,this.device.gl.DEPTH_ATTACHMENT,this.device.gl.RENDERBUFFER,e)}else{this.FrameTexture_meshAlpha=null,this.FrameBuffer_meshColor=null,this.FrameBuffer_meshAlpha=null;const t=this.device.gl.createRenderbuffer();this.device.gl.bindRenderbuffer(this.device.gl.RENDERBUFFER,t),this.device.gl.renderbufferStorage(this.device.gl.RENDERBUFFER,this.device.gl.DEPTH_COMPONENT16,this.device.canvas.width,this.device.canvas.height),this.FrameBuffer_mesh=this.device.gl.createFramebuffer(),this.device.gl.bindFramebuffer(this.device.gl.FRAMEBUFFER,this.FrameBuffer_mesh),this.device.gl.framebufferTexture2D(this.device.gl.FRAMEBUFFER,this.device.gl.COLOR_ATTACHMENT0,this.device.gl.TEXTURE_2D,this.FrameTexture_meshColor,0),this.device.gl.framebufferRenderbuffer(this.device.gl.FRAMEBUFFER,this.device.gl.DEPTH_ATTACHMENT,this.device.gl.RENDERBUFFER,t)}if(this.device.gl.bindFramebuffer(this.device.gl.FRAMEBUFFER,null),null===t.LUT)this.LUTTexture=null;else{if(this.LUTTexture=this.device.gl.createTexture(),!this.LUTTexture)throw new Error("WebGL texture creation failed.");if(this.device.gl.bindTexture(this.device.gl.TEXTURE_3D,this.LUTTexture),this.device.gl.texParameteri(this.device.gl.TEXTURE_3D,this.device.gl.TEXTURE_WRAP_R,this.device.gl.CLAMP_TO_EDGE),this.device.gl.texParameteri(this.device.gl.TEXTURE_3D,this.device.gl.TEXTURE_WRAP_S,this.device.gl.CLAMP_TO_EDGE),this.device.gl.texParameteri(this.device.gl.TEXTURE_3D,this.device.gl.TEXTURE_WRAP_T,this.device.gl.CLAMP_TO_EDGE),this.device.gl.texParameteri(this.device.gl.TEXTURE_3D,this.device.gl.TEXTURE_MIN_FILTER,this.device.gl.LINEAR),this.device.gl.texParameteri(this.device.gl.TEXTURE_3D,this.device.gl.TEXTURE_MAG_FILTER,this.device.gl.LINEAR),this.compat_features.OES_texture_float_linear)this.device.texImage3D(this.device.gl.TEXTURE_3D,0,t.LUT.size[1],t.LUT.size[2],t.LUT.size[0],this.device.gl.RGB,t.LUT.data);else{const e=new Uint8Array(t.LUT.size[0]*t.LUT.size[1]*t.LUT.size[2]*3);for(let n=0;n<e.length;n++)e[n]=Math.round(255*t.LUT.data[n]);this.device.texImage3D(this.device.gl.TEXTURE_3D,0,t.LUT.size[1],t.LUT.size[2],t.LUT.size[0],this.device.gl.RGB,e)}this.device.gl.bindTexture(this.device.gl.TEXTURE_3D,null)}this.backgroundTextureSrc=null}getProjMat(t){return mmul(t.getProjMatrix([this.device.canvas.width,this.device.canvas.height],200,800),t.getExtrinsicMatrix())}initFrame(){this.device.gl.viewport(0,0,this.device.gl.drawingBufferWidth,this.device.gl.drawingBufferHeight),this.device.gl.clearColor(0,0,0,0),this.device.gl.clearDepth(1),this.charData&&(this.charData.multisample?(this.device.gl.bindFramebuffer(this.device.gl.FRAMEBUFFER,this.FrameBuffer_meshColor),this.device.gl.clear(this.device.gl.COLOR_BUFFER_BIT),this.device.gl.bindFramebuffer(this.device.gl.FRAMEBUFFER,this.FrameBuffer_meshAlpha),this.device.gl.clear(this.device.gl.COLOR_BUFFER_BIT)):(this.device.gl.bindFramebuffer(this.device.gl.FRAMEBUFFER,this.FrameBuffer_mesh),this.device.gl.clear(this.device.gl.COLOR_BUFFER_BIT))),this.device.gl.bindFramebuffer(this.device.gl.FRAMEBUFFER,null),this.device.gl.clear(this.device.gl.COLOR_BUFFER_BIT|this.device.gl.DEPTH_BUFFER_BIT)}renderBackground(t){this.device.gl.disable(this.device.gl.DEPTH_TEST),this.device.gl.disable(this.device.gl.CULL_FACE),this.device.gl.disable(this.device.gl.BLEND);let e=0;t.backgroundTexture&&(e+=1),this.charData.multisample&&(e+=2),this.device.gl.useProgram(this.backgroundPipelineInfo.program);let n=this.charData?this.charData.transform:null;if(t.fx&&(t.fx.transform&&(n=t.fx.transform),t.fx.shadow)){const n=t.fx.shadow,r=this.getBillboardShadowGeometryInfo(n.refPos,n.light,"point"===n.lightType);e+=4;for(let t=0;t<3;t++)for(let e=0;e<3;e++)this._ub_shadow_fx_data[4*t+e]=r.Mat_World2ObjImage[e][t];for(let t=0;t<3;t++)for(let e=0;e<3;e++)this._ub_shadow_fx_data[4*t+e+12]=r.Mat_ShadowImage2World[e][t];for(let t=0;t<3;t++)this._ub_shadow_fx_data[24+t]=n.tint[t];this._ub_shadow_fx_data[27]=n.intensity,this._ub_shadow_fx_data[28]=n.blurRadius,this.device.gl.bindBuffer(this.device.gl.UNIFORM_BUFFER,this.backgroundBuffers.ub_shadow_fx_info),this.device.gl.bufferData(this.device.gl.UNIFORM_BUFFER,this._ub_shadow_fx_data,this.device.gl.DYNAMIC_DRAW)}this.device.gl.bindBufferBase(this.device.gl.UNIFORM_BUFFER,0,this.backgroundBuffers.ub_shadow_fx_info),this.device.gl.uniformMatrix2fv(this.backgroundPipelineInfo.progUniforms.u_transform_2d,!1,n?new Float32Array([1/n.scaleX,1/n.scaleY,-n.offsetX/n.scaleX,-n.offsetY/n.scaleY]):new Float32Array([1,1,0,0])),this.device.gl.uniform1ui(this.backgroundPipelineInfo.progUniforms.flags,e),this.device.gl.bindVertexArray(this.backgroundVAO),this.device.gl.uniform1i(this.backgroundPipelineInfo.progUniforms.u_image_bg,0),null!==t.backgroundTexture&&(this.device.gl.activeTexture(this.device.gl.TEXTURE0+0),this.device.gl.bindTexture(this.device.gl.TEXTURE_2D,this.backgroundTextures.u_image_bg),this.backgroundTextureSrc!==t.backgroundTexture&&(this.device.gl.texImage2D(this.device.gl.TEXTURE_2D,0,this.device.gl.RGB,this.device.gl.RGB,this.device.gl.UNSIGNED_BYTE,t.backgroundTexture),this.backgroundTextureSrc=t.backgroundTexture)),this.device.gl.uniform1i(this.backgroundPipelineInfo.progUniforms.u_image_char_body,1),this.device.gl.activeTexture(this.device.gl.TEXTURE0+1),this.device.gl.bindTexture(this.device.gl.TEXTURE_2D,this.backgroundTextures.u_image_char_body),this.device.gl.texImage2D(this.device.gl.TEXTURE_2D,0,this.device.gl.RGB,this.device.gl.RGB,this.device.gl.UNSIGNED_BYTE,t.charBodyTexture),this.charData&&(this.device.gl.uniform1i(this.backgroundPipelineInfo.progUniforms.u_image_mesh_color,2),this.device.gl.activeTexture(this.device.gl.TEXTURE0+2),this.device.gl.bindTexture(this.device.gl.TEXTURE_2D,this.FrameTexture_meshColor),this.device.gl.uniform1i(this.backgroundPipelineInfo.progUniforms.u_image_mesh_alpha,3),this.charData.multisample&&(this.device.gl.activeTexture(this.device.gl.TEXTURE0+3),this.device.gl.bindTexture(this.device.gl.TEXTURE_2D,this.FrameTexture_meshAlpha))),this.device.gl.drawArrays(this.device.gl.TRIANGLES,0,6)}renderMesh(t,e){this.device.gl.enable(this.device.gl.DEPTH_TEST),this.device.gl.disable(this.device.gl.CULL_FACE),this.device.gl.disable(this.device.gl.BLEND);const n=t.char;let r,i=new Float32Array(flatten(this.getProjMat(n.cameraConfig))),s=this.charData?this.charData.transform:null;e.fx&&e.fx.transform&&(s=e.fx.transform),r=s?new Float32Array([s.scaleX,s.scaleY,s.scaleX-1+2*s.offsetX,1-s.scaleY-2*s.offsetY]):new Float32Array([1,1,0,0]);let a=n.evalSkeletonFromMovable(e.data.movableJointTransforms),o=Array(n.skeleton.length);for(let t=0;t<n.skeleton.length;t++){const e=a[t].apply(this.initSkeletonStatus[t].inv());o[t]=e.homogeneous_matrix()}let l=0;for(let t=0;t<Math.min(this.meshStatistics.max_bones,n.skeleton.length);t++){for(let e=0;e<4;e++)for(let n=0;n<4;n++)this._ub_rig_info_data[l+4*e+n]=o[t][n][e];l+=16}if(this.device.gl.clearColor(0,0,0,0),this.device.gl.clearDepth(1),this.charData.multisample){this.device.gl.bindFramebuffer(this.device.gl.FRAMEBUFFER,this.FrameBuffer_mesh),this.device.gl.clear(this.device.gl.COLOR_BUFFER_BIT|this.device.gl.DEPTH_BUFFER_BIT),this.device.gl.useProgram(this.maskPipelineInfo.program),this.device.gl.uniformMatrix4fv(this.maskPipelineInfo.progUniforms.u_proj_mat,!0,i),this.device.gl.uniformMatrix2fv(this.maskPipelineInfo.progUniforms.u_transform_2d,!1,r);for(let t=0;t<n.mesh.length;t++)if(n.mesh[t].genMask){const r=this.meshInfos[t];if(n.mesh[t].blendshapes.size[2]>0){l=16*this.meshStatistics.max_bones;let r=Math.min(n.mesh[t].blendshapeIndices.length,this.meshStatistics.max_bs_count);for(let i=0;i<r;i++)this._ub_rig_info_data[l+i]=e.data.blendshapeWeights[n.mesh[t].blendshapeIndices[i]];for(let t=r;t<this.meshStatistics.max_bs_count;t++)this._ub_rig_info_data[l+t]=0}let i=0;n.mesh[t].opacity&&(i+=1);for(const t in r.uniformUInts)this.device.gl.uniform1ui(this.maskPipelineInfo.progUniforms[t],r.uniformUInts[t]);this.device.gl.uniform1ui(this.maskPipelineInfo.progUniforms.flags,i),this.device.gl.bindBuffer(this.device.gl.UNIFORM_BUFFER,r.buffers.ub_rig_info),this.device.gl.bufferData(this.device.gl.UNIFORM_BUFFER,this._ub_rig_info_data,this.device.gl.DYNAMIC_DRAW),this.device.gl.bindBufferBase(this.device.gl.UNIFORM_BUFFER,0,r.buffers.ub_rig_info),this.device.gl.bindVertexArray(r.VAO),this.device.gl.bindBuffer(this.device.gl.ELEMENT_ARRAY_BUFFER,r.buffers.indices),this.device.gl.uniform1i(this.maskPipelineInfo.progUniforms.u_image_bs,0),this.device.gl.activeTexture(this.device.gl.TEXTURE0+0),this.device.gl.bindTexture(this.device.gl.TEXTURE_2D,r.textures.u_image_bs),this.device.gl.drawElements(this.device.gl.TRIANGLES,n.mesh[t].triangles.itemSize(),this.device.getGLArrayElementType(n.mesh[t].triangles.data),0)}this.device.gl.bindFramebuffer(this.device.gl.DRAW_FRAMEBUFFER,this.FrameBuffer_meshAlpha),this.device.gl.blitFramebuffer(0,0,this.device.canvas.width,this.device.canvas.height,0,0,this.device.canvas.width,this.device.canvas.height,this.device.gl.COLOR_BUFFER_BIT,this.device.gl.NEAREST)}this.device.gl.bindFramebuffer(this.device.gl.FRAMEBUFFER,this.FrameBuffer_mesh),this.device.gl.clear(this.device.gl.COLOR_BUFFER_BIT|this.device.gl.DEPTH_BUFFER_BIT),this.device.gl.useProgram(this.meshPipelineInfo.program),this.device.gl.uniformMatrix4fv(this.meshPipelineInfo.progUniforms.u_proj_mat,!0,i),this.device.gl.uniformMatrix2fv(this.meshPipelineInfo.progUniforms.u_transform_2d,!1,r);let c=!0;for(let t=0;t<n.mesh.length;t++){const r=this.meshInfos[t];let i=r.texturePCAModels[e.data.mesh[t].textureModelIndex];if(n.mesh[t].blendshapes.size[0]>0){l=16*this.meshStatistics.max_bones;let r=Math.min(n.mesh[t].blendshapeIndices.length,this.meshStatistics.max_bs_count);for(let i=0;i<r;i++)this._ub_rig_info_data[l+i]=e.data.blendshapeWeights[n.mesh[t].blendshapeIndices[i]];for(let t=r;t<this.meshStatistics.max_bs_count;t++)this._ub_rig_info_data[l+t]=0}let s=0;n.mesh[t].opacity&&(s+=1),null!==this.LUTTexture&&(s+=2),i.unsigned&&(s+=4),c!=n.mesh[t].genMask&&(this.device.gl.colorMask(!0,!0,!0,!!n.mesh[t].genMask),c=n.mesh[t].genMask);for(const t in r.uniformUInts)this.device.gl.uniform1ui(this.meshPipelineInfo.progUniforms[t],r.uniformUInts[t]);this.device.gl.uniform1ui(this.meshPipelineInfo.progUniforms.flags,s),this.device.gl.uniform3f(this.meshPipelineInfo.progUniforms.u_gamma,this.currentGamma.r,this.currentGamma.g,this.currentGamma.b),this.device.gl.uniform3f(this.meshPipelineInfo.progUniforms.u_color_balance,this.currentColorBalance.rc,this.currentColorBalance.gm,this.currentColorBalance.by),this.device.gl.bindBuffer(this.device.gl.UNIFORM_BUFFER,r.buffers.ub_rig_info),this.device.gl.bufferData(this.device.gl.UNIFORM_BUFFER,this._ub_rig_info_data,this.device.gl.DYNAMIC_DRAW),this.device.gl.bindBufferBase(this.device.gl.UNIFORM_BUFFER,0,r.buffers.ub_rig_info);let a=Math.min(e.data.mesh[t].texturePCAWeights.length+1,this._ub_pca_info_data.length);this._ub_pca_info_data[0]=1;for(let n=1;n<a;n++)this._ub_pca_info_data[n]=e.data.mesh[t].texturePCAWeights[n-1];if(i.scalingFactor)for(let t=0;t<a;t++)this._ub_pca_info_data[t]*=i.scalingFactor[t];for(let t=a;t<this.meshStatistics.max_pca_component_count;t++)this._ub_pca_info_data[t]=0;this.device.gl.bindBuffer(this.device.gl.UNIFORM_BUFFER,r.buffers.ub_pca_info),this.device.gl.bufferData(this.device.gl.UNIFORM_BUFFER,this._ub_pca_info_data,this.device.gl.DYNAMIC_DRAW),this.device.gl.bindBufferBase(this.device.gl.UNIFORM_BUFFER,1,r.buffers.ub_pca_info),this.device.gl.bindVertexArray(r.VAO),this.device.gl.bindBuffer(this.device.gl.ELEMENT_ARRAY_BUFFER,r.buffers.indices),this.device.gl.uniform1i(this.meshPipelineInfo.progUniforms.u_image_bs,0),this.device.gl.activeTexture(this.device.gl.TEXTURE0+0),this.device.gl.bindTexture(this.device.gl.TEXTURE_2D,r.textures.u_image_bs),this.device.gl.uniform1i(this.meshPipelineInfo.progUniforms.u_image_pca,1),this.device.gl.activeTexture(this.device.gl.TEXTURE0+1),i.texture&&this.device.gl.bindTexture(this.device.gl.TEXTURE_2D_ARRAY,i.texture),this.device.gl.uniform1i(this.meshPipelineInfo.progUniforms.u_image_lut,2),this.LUTTexture&&(this.device.gl.activeTexture(this.device.gl.TEXTURE0+2),this.device.gl.bindTexture(this.device.gl.TEXTURE_3D,this.LUTTexture)),this.device.gl.drawElements(this.device.gl.TRIANGLES,n.mesh[t].triangles.itemSize(),this.device.getGLArrayElementType(n.mesh[t].triangles.data),0)}c||this.device.gl.colorMask(!0,!0,!0,!0),this.charData.multisample&&(this.device.gl.bindFramebuffer(this.device.gl.DRAW_FRAMEBUFFER,this.FrameBuffer_meshColor),this.device.gl.blitFramebuffer(0,0,this.device.canvas.width,this.device.canvas.height,0,0,this.device.canvas.width,this.device.canvas.height,this.device.gl.COLOR_BUFFER_BIT,this.device.gl.NEAREST)),this.device.gl.bindFramebuffer(this.device.gl.FRAMEBUFFER,null)}constructor(t,e){this.compat_features={},this.charData=null,this.backgroundBuffers={},this.backgroundTextures={},this.backgroundTextureSrc=null,this.meshPipelineInfo=null,this.maskPipelineInfo=null,this.meshInfos=[],this.meshStatistics={max_pca_component_count:4,max_bs_count:4,max_bones:1},this.FrameTexture_meshColor=null,this.FrameTexture_meshAlpha=null,this.LUTTexture=null,this.FrameBuffer_mesh=null,this.FrameBuffer_meshColor=null,this.FrameBuffer_meshAlpha=null,this.initSkeletonStatus=[],this.frameDataCallback=()=>null,this.currentGamma={r:1,g:1,b:1},this.currentColorBalance={rc:0,gm:0,by:0},this._ub_shadow_fx_data=null,this._ub_rig_info_data=null,this._ub_pca_info_data=null,this.first_webgl_render=!0,this.sendSdkPoint=()=>{},this.device=t,this.sendSdkPoint=e,this.reinitialize()}reinitialize(){this.compat_features={},this.compat_features.OES_texture_float_linear=this.device.gl.getExtension("OES_texture_float_linear"),this.compat_features.OES_texture_half_float_linear=this.device.gl.getExtension("OES_texture_half_float_linear"),this.assembleBackgroundPipeline(),this.charData&&this.assembleMeshPipelines(this.charData)}setSyncMedia(t){this.device.run(t=>this.render(),t)}setCharData(t){t?(this.charData=_extends({},t),this.charData.multisample=null,this.assembleMeshPipelines(this.charData)):this.charData=null}setFrameDataCallback(t){this.frameDataCallback=t}setGamma(t,e,n){this.currentGamma={r:t,g:e,b:n}}setColorBalance(t,e,n){this.currentColorBalance={rc:t,gm:e,by:n}}getBillboardTransform2D(t,e){if(null==this.charData||null==this.charData.char)return{offsetX:0,offsetY:0,scaleX:1,scaleY:1};{const n=this.getProjMat(this.charData.char.cameraConfig),r=inv4(n),i=mmul(n,[[t[0],e[0]],[t[1],e[1]],[t[2],e[2]],[1,1]]),s=i[3][0]/i[3][1],a=[r[0][0]-e[0]*r[3][0],r[1][0]-e[1]*r[3][0],r[2][0]-e[2]*r[3][0]],o=[r[0][1]-t[0]*r[3][1],r[1][1]-t[1]*r[3][1],r[2][1]-t[2]*r[3][1]],l=[r[0][1]-e[0]*r[3][1],r[1][1]-e[1]*r[3][1],r[2][1]-e[2]*r[3][1]],c=s*Math.sqrt([r[0][0]-t[0]*r[3][0],r[1][0]-t[1]*r[3][0],r[2][0]-t[2]*r[3][0]].reduce((t,e)=>t+e*e,0)/a.reduce((t,e)=>t+e*e,0)),d=s*Math.sqrt(o.reduce((t,e)=>t+e*e,0)/l.reduce((t,e)=>t+e*e,0));return{offsetX:.5*(i[0][1]/i[3][1]-i[0][0]/i[3][0]-(c-1)),offsetY:.5*(1-d-(i[1][1]/i[3][1]-i[1][0]/i[3][0])),scaleX:c,scaleY:d}}}getBillboardShadowGeometryInfo(t,e,n){if(null==this.charData||null==this.charData.char)return{Mat_ShadowImage2World:identity(3),Mat_World2ObjImage:identity(3)};{const r=this.getProjMat(this.charData.char.cameraConfig),i=inv4(r),s=[[1,0,0],[0,t[1],1],[0,0,0]],a=[[1,0,0],[0,t[2],1],[0,0,0]];n?(s[2]=[e[0],e[1],1],a[2]=[t[0],-e[2],0]):(s[2]=[e[0],e[1],0],a[2]=[0,-e[2],0]);const o=transpose(mmul(inv3(a),s)),l=mvmul(r,[t[0],t[1],t[2],1]),c=l[2]/l[3];return{Mat_ShadowImage2World:mmul(o,inv3([[r[0][0],r[0][2],r[0][1]*t[1]+r[0][3]],[r[1][0],r[1][2],r[1][1]*t[1]+r[1][3]],[r[3][0],r[3][2],r[3][1]*t[1]+r[3][3]]])),Mat_World2ObjImage:inv3([[i[0][0],i[0][1],i[0][2]*c+i[0][3]],[i[1][0],i[1][1],i[1][2]*c+i[1][3]],[i[3][0],i[3][1],i[3][2]*c+i[3][3]]])}}}render(){var t;const e=this.frameDataCallback();null!==e&&(this.initFrame(),null!==this.charData&&null!==this.charData.char&&null!==e.data?this.renderMesh(this.charData,e):(this.device.gl.bindFramebuffer(this.device.gl.FRAMEBUFFER,this.FrameBuffer_mesh),this.device.gl.clear(this.device.gl.COLOR_BUFFER_BIT|this.device.gl.DEPTH_BUFFER_BIT),this.device.gl.bindFramebuffer(this.device.gl.FRAMEBUFFER,null)),this.renderBackground(e),null!==e.onPostRender&&e.onPostRender(this)),null==(t=this.device.gl)||t.flush()}renderFrame(t){this.initFrame(),null!==this.charData&&null!==this.charData.char&&null!==t.data&&this.renderMesh(this.charData,t),this.renderBackground(t),this.first_webgl_render&&(window.performanceTracker.markEnd(performanceConstant.first_render),window.performanceTracker.markEnd(performanceConstant.first_webgl_render),this.first_webgl_render=!1,this.sendSdkPoint("render_success_time",{timestamp:Date.now()})),this.device.gl.flush()}destroy(){var t,e,n,r;this.device.gl&&(this.meshInfos&&(this.meshInfos.forEach(t=>{t.VAO&&this.device.gl.deleteVertexArray(t.VAO),Object.values(t.buffers).forEach(t=>{t&&this.device.gl.deleteBuffer(t)}),Object.values(t.textures).forEach(t=>{t&&this.device.gl.deleteTexture(t)}),t.texturePCAModels.forEach(t=>{t.texture&&this.device.gl.deleteTexture(t.texture)})}),this.meshInfos=[]),this.FrameBuffer_MSAA&&(this.device.gl.deleteFramebuffer(this.FrameBuffer_MSAA),this.FrameBuffer_MSAA=null),this.FrameBuffer_meshColor&&(this.device.gl.deleteFramebuffer(this.FrameBuffer_meshColor),this.FrameBuffer_meshColor=null),this.FrameBuffer_meshAlpha&&(this.device.gl.deleteFramebuffer(this.FrameBuffer_meshAlpha),this.FrameBuffer_meshAlpha=null),this.FrameTexture_meshColor&&(this.device.gl.deleteTexture(this.FrameTexture_meshColor),this.FrameTexture_meshColor=null),this.FrameTexture_meshAlpha&&(this.device.gl.deleteTexture(this.FrameTexture_meshAlpha),this.FrameTexture_meshAlpha=null),this.LUTTexture&&(this.device.gl.deleteTexture(this.LUTTexture),this.LUTTexture=null),null!=(n=this.meshPipelineInfo)&&n.program&&(this.device.gl.deleteProgram(this.meshPipelineInfo.program),this.meshPipelineInfo.program=null),null!=(r=this.maskPipelineInfo)&&r.program&&(this.device.gl.deleteProgram(this.maskPipelineInfo.program),this.maskPipelineInfo.program=null)),this._ub_rig_info_data=null,this._ub_pca_info_data=null,this.first_webgl_render=!0,null==(t=(e=this.device).destroy)||t.call(e)}}const containerWidgetMaps=new Map;let containerIdCounter=0;function getContainerElement(t){return t&&t.el&&t.el instanceof HTMLElement?t.el:null}function getContainerId(t){if(t.id)return t.id;const e=t.getAttribute("data-widget-container-id");if(e)return e;const n="widget-container-"+ ++containerIdCounter;return t.setAttribute("data-widget-container-id",n),n}function getContainerWidgetMap(t){const e=getContainerId(t);return containerWidgetMaps.has(e)||containerWidgetMaps.set(e,new Map),containerWidgetMaps.get(e)}const subtitleStyle="bottom: 50px;\nleft: 50%;\ntransform: translateX(-50%);\nbackground: rgba(0, 0, 0, 0.8);\ncolor: white;\npadding: 12px 20px;\nborder-radius: 8px;\nfont-size: 16px;\nfont-weight: 500;\nz-index: 1000;\nmax-width: 80%;\nmin-width: 200px;\nword-break: break-word;\nbox-shadow: 0 4px 12px rgba(0, 0, 0, 0.3);\ntext-align: center;",WidgetDefaultRenderer={_el(t){const{axis_id:e,x_location:n,y_location:r,width:i,height:s}=t,a=document.createElement("div");a.setAttribute("class","avatar-sdk-widget-container");let o="position:absolute;";return o+=void 0!==e?`z-index:${e};`:"z-index:1;",void 0!==n&&void 0!==r&&(o+=`top:${100*r}%;left:${100*n}%;`),void 0!==i&&void 0!==s&&(o+=`width:${100*i}%;height:${100*s}%;`),a.setAttribute("style",o),a},_getWidgetKey:(t,e)=>`${t}-${null!=e?e:"default"}`,_replaceWidget(t,e,n,r){const i=this._getWidgetKey(t,e),s=getContainerElement(r||this._currentInstance);if(!s)return;const a=getContainerWidgetMap(s);if(a.has(i)){const t=a.get(i);t&&t.parentNode&&t.remove()}a.set(i,n)},WIDGET_PIC(t,e){const n=this._el(t),r=document.createElement("img");return r.crossOrigin="anonymous",r.setAttribute("style","width:100%;height:100%;"),r.src=t.image,n.appendChild(r),this._replaceWidget("WIDGET_PIC",t.axis_id,n,e),n},WIDGET_SUBTITLE(t,e){const{type:n,text:r,axis_id:i}=t,s=getContainerElement(e||this._currentInstance);if("subtitle_off"===n){if(s){const t=getContainerWidgetMap(s),e=this._getWidgetKey("WIDGET_SUBTITLE",i);if(t.has(e)){const n=t.get(e);n&&n.parentNode&&n.remove(),t.delete(e)}}return null}const a=this._el(t);return a.innerHTML=r,a.setAttribute("style",a.style.cssText+subtitleStyle),this._replaceWidget("WIDGET_SUBTITLE",i,a,e),a},destroy(t){const e=getContainerElement(t||this._currentInstance);if(e){const t=getContainerId(e);if(containerWidgetMaps.has(t)){const e=containerWidgetMaps.get(t);e.forEach((t,e)=>{(e.startsWith("WIDGET_SUBTITLE")||e.startsWith("WIDGET_PIC"))&&t&&t.parentNode&&t.remove()}),e.clear(),containerWidgetMaps.delete(t)}else e.querySelectorAll(".avatar-sdk-widget-container").forEach(t=>{t.remove()})}}},__version__="3.0.0";function checkVersion(t,e){t instanceof ArrayBuffer&&(t={offset:0,dataview:new DataView(t)});const n=[0,0,0];for(let e=0;e<3;e++)n[e]=t.dataview.getUint8(t.offset),t.offset+=1;const r=e.split(".").map(t=>parseInt(t));if(r[0]<n[0])throw new Error(`Data version (${n[0]}.${n[1]}.${n[2]}) is incompatible with the version of current data interface (${r[0]}.${r[1]}.${r[2]}).`);return n}function decodeStr(t){t instanceof ArrayBuffer&&(t={offset:0,dataview:new DataView(t)});const e=new Uint8Array(t.dataview.buffer,t.offset,t.dataview.byteLength-t.offset);let n=0;for(;n<e.byteLength&&e[n]>0;)n++;t.offset+=n+1;const r=e.slice(0,n);return new TextDecoder("utf-8").decode(r)}function decodeLongInt(t){t instanceof ArrayBuffer&&(t={offset:0,dataview:new DataView(t)});let e=0,n=0;for(;;){let r=t.dataview.getUint8(t.offset);t.offset++;let i=e|(127&r)<<n;if(i<e)throw new Error("Integer too large to decode.");if(e=i,!(128&r))break;n+=7}return e}const TensorDataTypeMap={B:Uint8Array,b:Int8Array,H:Uint16Array,h:Int16Array,I:Uint32Array,i:Int32Array,L:BigUint64Array,l:BigInt64Array,f:Float32Array,d:Float64Array};"undefined"!=typeof Float16Array&&(TensorDataTypeMap.e=Float16Array);class Tensor{constructor(t,e){this.size=t,this.data=e}itemSize(){let t=1;for(let e of this.size)t*=e;return t}byteSize(){return this.itemSize()*this.data.BYTES_PER_ELEMENT}static zeros(t,e=Float32Array){let n=1;for(let e=0;e<t.length;e++)n*=t[e];const r=new e(n);for(let t=0;t<n;t++)r[t]=0;return new Tensor(t,r)}part(...t){if(t.length>this.size.length)throw new Error("Subtensor index length larger than tensor dimension.");let e=[],n=1;for(let r=t.length;r<this.size.length;r++)e.push(this.size[r]),n*=this.size[r];let r=0;t.length>0&&(r+=t[0]);for(let e=1;e<t.length;e++)r*=this.size[e],r+=t[e];return r*=n,new Tensor(e,this.data.slice(r,r+n))}static deserialize(t){t instanceof ArrayBuffer&&(t={offset:0,dataview:new DataView(t)});const e=t.dataview.getUint8(t.offset);t.offset++;const n=new Array(e);let r=1;for(let i=0;i<e;i++)n[i]=decodeLongInt(t),r*=n[i];const i=String.fromCodePoint(t.dataview.getUint8(t.offset));t.offset++;const s=TensorDataTypeMap[i];if(void 0===s)throw new Error(`Unsupported tensor element type "${i}".`);const a=r*s.BYTES_PER_ELEMENT,o=new s(t.dataview.buffer.slice(t.offset,t.offset+a));return t.offset+=a,new Tensor(n,o)}}function loadArchives(t){t instanceof ArrayBuffer&&(t={offset:0,dataview:new DataView(t)});let e=[null];for(;;){const n=decodeStr(t);if(""==n)break;{let r=null;if("text/plain;charset=UTF-8"===n){const e=decodeLongInt(t),n=new Uint8Array(t.dataview.buffer,t.offset,e);t.offset+=e,r=new TextDecoder("utf-8").decode(n)}else if("application/json;charset=UTF-8"==n){const e=decodeLongInt(t),n=new Uint8Array(t.dataview.buffer,t.offset,e);t.offset+=e;const i=new TextDecoder("utf-8");r=JSON.parse(i.decode(n))}else if("application/octet-stream"===n)r=Tensor.deserialize(t);else{const e=decodeLongInt(t),i=t.dataview.buffer.slice(t.offset,t.offset+e);t.offset+=e,r=new Blob([i],{type:n})}e.push(r)}}return e}class CameraConfig{constructor(){this.focalLength=75,this.filmAperture=[1,1],this.translation=[0,0,0],this.rotation=[0,0,0]}getIntrinsicMatrix(t){const[e,n]=t;let r=25.4*this.filmAperture[0];return[[this.focalLength/(r/e),0,t[0]/2],[0,this.focalLength/(r*t[1]/t[0]/n),t[1]/2],[0,0,1]]}getProjMatrix(t,e=.01,n=Infinity){const[r,i]=t,s=this.getIntrinsicMatrix(t);let a,o;return Infinity===n?(a=-1,o=-2*e):(a=-(n+e)/(n-e),o=-2*n*e/(n-e)),[[2*s[0][0]/r,0,(r-2*s[0][2])/r,0],[0,2*s[1][1]/i,(i-2*s[1][2])/i,0],[0,0,a,o],[0,0,-1,0]]}getExtrinsicMatrix(){const t=Math.PI/180,e=inv3(Euler_to_mat(this.rotation.map(e=>e*t),"xyz"));return make_homogeneous(e,mvmul(e,this.translation.map(t=>-t)))}static deserialize(t){t instanceof ArrayBuffer&&(t={offset:0,dataview:new DataView(t)});let e=new CameraConfig;e.focalLength=t.dataview.getFloat32(t.offset,!0);for(let n=0;n<2;n++)e.filmAperture[n]=t.dataview.getFloat32(t.offset+4*(n+1),!0);for(let n=0;n<3;n++)e.translation[n]=t.dataview.getFloat32(t.offset+4*(n+3),!0);for(let n=0;n<3;n++)e.rotation[n]=t.dataview.getFloat32(t.offset+4*(n+6),!0);return t.offset+=36,e}}class RigidTransform{constructor(t=[0,0,0],e=[1,0,0,0]){this.translation=t,this.rotQuaternion=e}apply(t){if(t instanceof RigidTransform){let e=quaternion_mul(this.rotQuaternion,t.rotQuaternion);e=normalize$1(e);let n=mvmul(quaternion_to_mat(this.rotQuaternion),t.translation);for(let t=0;t<3;t++)n[t]+=this.translation[t];return new RigidTransform(n,e)}{let e=mvmul(this.matrix(),t);for(let t=0;t<3;t++)e[t]+=this.translation[t];return e}}inv(){let t=quaternion_conj(this.rotQuaternion),e=mvmul(quaternion_to_mat(t),this.translation.map(t=>-t));return new RigidTransform(e,t)}matrix(){return quaternion_to_mat(this.rotQuaternion)}homogeneous_matrix(){return make_homogeneous(this.matrix(),this.translation)}static deserialize(t){t instanceof ArrayBuffer&&(t={offset:0,dataview:new DataView(t)});let e=[0,0,0],n=[1,0,0,0];for(let n=0;n<3;n++)e[n]=t.dataview.getFloat32(t.offset+4*n,!0);let r=0;for(let e=0;e<3;e++)n[e+1]=t.dataview.getFloat32(t.offset+4*(e+3),!0),r+=n[e+1]*n[e+1];return n[0]=Math.sqrt(Math.max(1-r,0)),t.offset+=24,new RigidTransform(e,n)}}class IBRMeshInfo{constructor(t,e){if(t instanceof ArrayBuffer&&(t={offset:0,dataview:new DataView(t)}),e.version[0]>2){let n=t.dataview.getUint8(t.offset);t.offset+=1,this.genMask=(1&n)>0;let r=[],i=[],s=!0;for(;;){let e=decodeLongInt(t);if(0===e){if(!s)break}else r.push(e-1);s=!1;let n=[],a=!0,o=0;for(;;){let e=decodeLongInt(t);if(a)for(let t=0;t<e;t++)n.push(o+t);if(a=!a,o+=e,0===e&&o>0)break}i.push(n)}let a=i[0].length;this.blendshapeIndices=r;let o=e.archivedItems[decodeLongInt(t)],l=Tensor.zeros([a,o.size[1]],o.data.constructor),c=Tensor.zeros([a,o.size[1],this.blendshapeIndices.length],o.data.constructor),d=0;const h=i[0];for(let t of h){for(let e=0;e<o.size[1];e++)l.data[t*o.size[1]+e]=o.data[d*o.size[1]+e];d++}const u=this.blendshapeIndices.length;for(let t=1;t<i.length;t++){const e=i[t];for(let n of e){for(let e=0;e<o.size[1];e++)c.data[(n*o.size[1]+e)*u+t-1]=o.data[d*o.size[1]+e];d++}}this.vertices=l,this.blendshapes=c,this.triangles=e.archivedItems[decodeLongInt(t)],this.opacity=e.archivedItems[decodeLongInt(t)],this.UVCoord=e.archivedItems[decodeLongInt(t)],this.jointIndex=new Uint8Array(a*e.maxJointsPerVertex),this.jointWeight=new Float32Array(a*e.maxJointsPerVertex);for(let n=0;n<a;n++){for(let r=0;r<e.maxJointsPerVertex;r++)this.jointIndex[n*e.maxJointsPerVertex+r]=t.dataview.getUint8(t.offset),t.offset+=1;for(let r=0;r<e.maxJointsPerVertex;r++)this.jointWeight[n*e.maxJointsPerVertex+r]=t.dataview.getFloat32(t.offset,!0),t.offset+=4}const p=t.dataview.getUint8(t.offset);t.offset+=1,this.textureModels=new Array(p);for(let n=0;n<p;n++)this.textureModels[n]={data:e.archivedItems[decodeLongInt(t)],scalingFactor:e.archivedItems[decodeLongInt(t)]}}else{this.genMask=!0;let n=t.dataview.getUint16(t.offset,!0);t.offset+=2;const r=new Float32Array(n);for(let e=0;e<n;e++)r[e]=t.dataview.getFloat32(t.offset,!0),t.offset+=4;this.opacity=new Tensor([n],r);let i=t.dataview.getUint16(t.offset,!0);t.offset+=2;const s=new Uint16Array(3*i);for(let e=0;e<i;e++)for(let n=0;n<3;n++)s[3*e+n]=t.dataview.getUint16(t.offset,!0),t.offset+=2;this.triangles=new Tensor([i,3],s);const a=new Float32Array(2*n);for(let e=0;e<n;e++)for(let n=0;n<2;n++)a[2*e+n]=t.dataview.getFloat32(t.offset,!0),t.offset+=4;this.UVCoord=new Tensor([n,2],a);const o=t.dataview.getUint16(t.offset,!0);t.offset+=2;const l=new Float32Array(3*n);for(let e=0;e<3*n;e++)l[e]=t.dataview.getFloat32(t.offset,!0),t.offset+=4;const c=new Float32Array((o-1)*n*3);for(let e=0;e<o-1;e++)for(let r=0;r<3*n;r++)c[r*(o-1)+e]=t.dataview.getFloat32(t.offset,!0),t.offset+=4;this.vertices=new Tensor([n,3],l),this.blendshapes=new Tensor([n,3,o-1],c),this.blendshapeIndices=[];for(let t of e.blendshapeIndices)this.blendshapeIndices.push(t);this.jointIndex=new Uint8Array(n*e.maxJointsPerVertex),this.jointWeight=new Float32Array(n*e.maxJointsPerVertex);for(let r=0;r<n;r++){for(let n=0;n<e.maxJointsPerVertex;n++)this.jointIndex[r*e.maxJointsPerVertex+n]=t.dataview.getUint8(t.offset),t.offset+=1;for(let n=0;n<e.maxJointsPerVertex;n++)this.jointWeight[r*e.maxJointsPerVertex+n]=t.dataview.getFloat32(t.offset,!0),t.offset+=4}const d=t.dataview.getUint8(t.offset);t.offset+=1,this.textureModels=new Array(d);for(let e=0;e<d;e++){const n=[0,0,0,3];for(let e=0;e<3;e++)n[e]=t.dataview.getUint16(t.offset,!0),t.offset+=2;const r=new Float32Array(n[0]*n[1]*n[2]*3);for(let e=0;e<r.length;e++)r[e]=t.dataview.getFloat32(t.offset,!0),t.offset+=4;this.textureModels[e]={data:new Tensor(n,r)}}}}}class IBRMeshFrameInfo{constructor(t,e){this.textureModelIndex=t,this.texturePCAWeights=e}static deserialize(t,e){t instanceof ArrayBuffer&&(t={offset:0,dataview:new DataView(t)});let n=t.dataview.getUint8(t.offset);t.offset+=1;let r=new Float32Array(e.textureModels[n].data.size[0]-1);for(let e=0;e<r.length;e++)r[e]=t.dataview.getFloat32(t.offset,!0),t.offset+=4;return new IBRMeshFrameInfo(n,r)}}class IBRAnimationGeneratorCharInfo_NN{constructor(t,e={}){t instanceof ArrayBuffer&&(t={offset:0,dataview:new DataView(t)});const n=checkVersion(t,__version__);let r=[];if(n[0]>2&&(r=loadArchives(t)),this.cameraConfig=CameraConfig.deserialize(t),n[0]>2)this.blendshapeCount=decodeLongInt(t);else{if(!e.blendshapeMap)throw new Error("A blendshape map is required to load the character information of v2.0 format.");let t=new Set;for(const n of e.blendshapeMap)for(const e of n)t.add(e);this.blendshapeCount=t.size}let i=t.dataview.getUint8(t.offset);t.offset+=1,this.maxJointsPerVertex=t.dataview.getUint8(t.offset),t.offset+=1;let s=t.dataview.getUint8(t.offset);t.offset+=1;let a=new Array(s);for(let e=0;e<s;e++)a[e]=t.dataview.getUint8(t.offset),t.offset+=1;this.movableJoints=a,this.skeleton=new Array(i);for(let e=0;e<i;e++){let n=t.dataview.getUint8(t.offset);n>=this.skeleton.length&&(n=null),t.offset+=1;let r=RigidTransform.deserialize(t);this.skeleton[e]={parent:n,local_transform:r}}this.jointEvalOrder=new Array(i);for(let e=0;e<i;e++)this.jointEvalOrder[e]=t.dataview.getUint8(t.offset),t.offset+=1;let o={version:n,maxJointsPerVertex:this.maxJointsPerVertex};n[0]>2&&(o.archivedItems=r);let l=t.dataview.getUint8(t.offset);t.offset+=1,this.mesh=new Array(l);for(let r=0;r<l;r++)n[0]<=2&&(o.blendshapeIndices=e.blendshapeMap[r]),this.mesh[r]=new IBRMeshInfo(t,o)}evalSkeleton(){let t=Array(this.skeleton.length);for(let e of this.jointEvalOrder)t[e]=null==this.skeleton[e].parent?this.skeleton[e].local_transform:t[this.skeleton[e].parent].apply(this.skeleton[e].local_transform);return t}evalSkeletonFromMovable(t){let e=Array(this.skeleton.length);for(let n=0;n<t.length;n++)e[this.movableJoints[n]]=t[n];for(let t of this.jointEvalOrder)null!=this.skeleton[t].parent&&(e[t]=e[this.skeleton[t].parent].apply(this.skeleton[t].local_transform));return e}}class IBRAnimationFrameData_NN{constructor(){this.mesh=[],this.blendshapeWeights=new Float32Array,this.movableJointTransforms=[]}static deserialize(t,e,n){t instanceof ArrayBuffer&&(t={offset:0,dataview:new DataView(t)});let r=new IBRAnimationFrameData_NN;const i=e.mesh.length;if(r.mesh=new Array(i),r.blendshapeWeights=new Float32Array(e.blendshapeCount),n[0]>2){for(let n=0;n<i;n++)r.mesh[n]=IBRMeshFrameInfo.deserialize(t,e.mesh[n]);for(let e=0;e<r.blendshapeWeights.length;e++)r.blendshapeWeights[e]=t.dataview.getFloat32(t.offset,!0),t.offset+=4}else for(let n=0;n<i;n++){const i=e.mesh[n].blendshapeIndices;for(let e=0;e+1<i.length;e++)r.blendshapeWeights[i[e+1]-1]=t.dataview.getFloat32(t.offset,!0),t.offset+=4;let s=t.dataview.getUint8(t.offset);t.offset+=1;let a=new Float32Array(e.mesh[n].textureModels[s].data.size[0]-1);for(let e=0;e<a.length;e++)a[e]=t.dataview.getFloat32(t.offset,!0),t.offset+=4;r.mesh[n]=new IBRMeshFrameInfo(s,a)}r.movableJointTransforms=new Array(e.movableJoints.length);for(let n=0;n<e.movableJoints.length;n++)r.movableJointTransforms[n]=RigidTransform.deserialize(t);return r}static interp(t,e,n,r,i){let s=new IBRAnimationFrameData_NN;s.blendshapeWeights=new Float32Array(t.blendshapeWeights.length);for(let n=0;n<s.blendshapeWeights.length;n++)s.blendshapeWeights[n]=r*e.blendshapeWeights[n]+(1-r)*t.blendshapeWeights[n];s.mesh=[];for(let n=0;n<t.mesh.length;n++){let i=new IBRMeshFrameInfo(t.mesh[n].textureModelIndex,new Float32Array(t.mesh[n].texturePCAWeights.length));for(let s=0;s<t.mesh[n].texturePCAWeights.length;s++)i.texturePCAWeights[s]=r*e.mesh[n].texturePCAWeights[s]+(1-r)*t.mesh[n].texturePCAWeights[s];s.mesh.push(i)}s.movableJointTransforms=new Array(n.movableJointTransforms.length);for(let t=0;t<n.movableJointTransforms.length;t++){let e=!0;for(let[n,r]of i)if(n===t){e=!1;break}e&&(s.movableJointTransforms[t]=n.movableJointTransforms[t])}for(let[a,o]of i){let i=t.movableJointTransforms[o].inv().apply(t.movableJointTransforms[a]),l=e.movableJointTransforms[o].inv().apply(e.movableJointTransforms[a]),c=[],d=[];for(let t=0;t<3;t++)c.push(r*l.translation[t]+(1-r)*i.translation[t]);for(let t=0;t<4;t++)d.push(r*l.rotQuaternion[t]+(1-r)*i.rotQuaternion[t]);d=normalize$1(d);let h=new RigidTransform(c,d);h=n.movableJointTransforms[o].apply(h),s.movableJointTransforms[a]=h}return s}}function unpackIBRAnimation(t,e){t instanceof ArrayBuffer&&(t={offset:0,dataview:new DataView(t)});const n=checkVersion(t,__version__),r=t.dataview.getUint32(t.offset,!0);t.offset+=4;let i=Array(r);for(let s=0;s<r;s++)i[s]=IBRAnimationFrameData_NN.deserialize(t,e,n);return i}function formatMJT(t,e){return new RigidTransform(t,e)}function isSupportMES(){const t=navigator.userAgent,e=navigator.vendor,n=/Chrome/.test(t),r=/Google Inc/.test(e),i=/Edg/.test(t),s=void 0!==window.MediaSource;return n&&(r||i)&&s}function getStyleStr(t){return Object.entries(t).map(([t,e])=>{const n="number"==typeof e?e.toString():e;return`${t.replace(/[A-Z]/g,t=>`-${t.toLowerCase()}`)}:${n};`}).join("")}function updateCanvasXOffset(t,e){const n=(t.style.transform||"").replace(/translateX\((-?\d+(\.\d+)?)px\)/,"").trim()+` translateX(${e}px)`;t.style.transform=n.replace(/\s+/g," ").trim()}function generateFingerprint(){const t=`${screen.width}x${screen.height}`,e=navigator.userAgent,n=navigator.language,r=Intl.DateTimeFormat().resolvedOptions().timeZone,i=encodeURIComponent(`${t}|${e}|${n}|${r}`);return btoa(i)}function getDeviceInfo(){const t=navigator.userAgent;let e="Unknown Brand",n="Unknown Model",r="Unknown Version",i="Unknown Browser",s="Unknown Version";const a=t.match(/Windows NT (\d+\.\d+)/),o=t.match(/Android (\d+\.\d+(\.\d+)?)/),l=t.match(/OS (\d+_\d+(\._\d+)?) like Mac OS X/);a?r=`Windows NT ${a[1]}`:o?r=`Android ${o[1]}`:l?r=`iOS ${l[1].replace(/_/g,".")}`:t.includes("Macintosh")?r="Macintosh":t.includes("Linux")&&(r="Linux"),t.includes("iPhone")||t.includes("iPad")||t.includes("iPod")?(e="Apple",t.includes("iPhone")?n="iPhone":t.includes("iPad")?n="iPad":t.includes("iPod")&&(n="iPod")):t.includes("Android")?(e="Android",n="Android"):t.includes("Windows")?(e="Windows",n=t.includes("Windows Phone")?"Windows Phone":"Windows Desktop"):t.includes("Linux")&&(e="Linux",n="Linux");const c=t.match(/Chrome\/(\d+\.\d+\.\d+\.\d+)/),d=t.match(/Version\/(\d+\.\d+(\.\d+)?) Safari/),h=t.match(/Firefox\/(\d+\.\d+(\.\d+)?)\b/),u=t.match(/Edg\/(\d+\.\d+\.\d+\.\d+)/),p=t.match(/Opera\/(\d+\.\d+)/),f=t.match(/MSIE (\d+\.\d+)/);return c?(i="Chrome",s=c[1]):d?(i="Safari",s=d[1]):h?(i="Firefox",s=h[1]):u?(i="Edge",s=u[1]):p?(i="Opera",s=p[1]):f&&(i="IE",s=f[1]),{device_id:generateFingerprint(),device_brand:e,device_model:n,os_version:r,browser:i,browser_version:s,browser_ua:t}}function validateScaleWithDecimal(t,e){var n;return"number"==typeof t||"string"==typeof t&&(/^\d+(\.\d+)?vh$/.test(t)||/^\d+(\.\d+)?$/.test(t))?t:(null==(n=window.avatarSDKLogger)||n.warn(e,'scale 必须是数字、带小数的数字字符串或者"xxxvh"格式(xxx为数字/小数)'),1)}function isharmony(){const t=(navigator.userAgent||"").toLowerCase();return/openharmony|arkweb/.test(t)}class AvatarRender{constructor(t){this.TAG="[AvatarRender]",this.canvas=document.createElement("canvas"),this.currentBodyFrame=null,this.lastFaceFrame=null,this.isInit=!1,this.isFirstRender=!0,this.lastFrameState="",this.lastRenderState=RenderState.init,this.onStateChange=()=>{},this.onRenderChange=()=>{},this.sendVideoInfo=()=>{},this.lostHandler=()=>{},this.restoreHandler=()=>{},this.avatarCanvasVisible=!0,this.lastRealFaceFrameData=null,this.lastRealFaceFrame=-1,this.lastWeight=0,this.lastFrameIndex=-1,this.canvasOffsetX=-1,this.baseWalkOffset=0,this.lastBodyOffset=0,this.pendingCharData=null,this.interrupt=!1,this.walkConfig=null,this.layout=null,this.allLostFrameCount=0,this.allLostFaceFrameCount=0,this.maxLostFrameCount=300,this.forceSyncDecoder=()=>{},this.createPipelineLock=!1,this.restoreTimeout=null,this.isRecovering=!1,this.recoverStartTime=0,this.recoveryStage="light",this.recoveryMaxAttempts={light:2,medium:3,full:2},this.recoveryBaseDelays={light:300,medium:4e3,full:5e3},this.recoveryMaxDelay=3e4,this.currentStageAttempts=0,this.isUsingReducedResolution=!1,this.resolutionRestoreTimer=null,this.RESOLUTION_RESTORE_DELAY=3e4,this.scale=1,this.sendSdkPoint=()=>{},this.options=t,this.onDownloadProgress=t.onDownloadProgress,this.onStateChange=t.onStateChange,this.onRenderChange=t.onRenderChange,this.sendVideoInfo=t.sendVideoInfo,this.saveAndDownload=t.saveAndDownload,this.forceSyncDecoder=t.forceSyncDecoder,this.lostHandler=this._lostHandler.bind(this),this.restoreHandler=this._restoreHandler.bind(this),this.setCanvasVisibility(this.avatarCanvasVisible),this.sendSdkPoint=t.sendSdkPoint,this.device=null,this.pipeline=null,this.copyCanvas=document.createElement("canvas"),this.copyCtx=this.copyCanvas.getContext("2d")}resetFaceFrameState(){var t;this.lastRealFaceFrame=-1,this.lastRealFaceFrameData=null,this.lastWeight=0,null==(t=window.avatarSDKLogger)||t.log(this.TAG,"重置表情状态(从隐身模式恢复)")}createPipeline(){this.pipeline||!this.device||this.createPipelineLock||(this.createPipelineLock=!0,this.pipeline=new GLPipeline(this.device,this.sendSdkPoint),this.createPipelineLock=!1,this.pendingCharData&&(this.pipeline.setCharData(this.pendingCharData),this.pipeline.setSyncMedia()))}_lostHandler(t){if(t.preventDefault(),window.avatarSDKLogger.error("Context lost.",t),this.device)try{this.device.canvas.removeEventListener("webglcontextlost",this.lostHandler),this.device.canvas.removeEventListener("webglcontextrestored",this.restoreHandler)}catch(t){}if(this.device)try{this.device.destroy()}catch(t){}if(this.pipeline)try{this.pipeline.destroy()}catch(t){}this.device=null,this.pipeline=null,this.options.reportMessage({code:EErrorCode.WEBGL_CONTEXT_LOST,message:"Context lost.",e:{event:t,timestamp:Date.now()}}),this.isRecovering?window.avatarSDKLogger.warn("Context recovery already in progress, skipping."):(this.resolutionRestoreTimer&&(clearTimeout(this.resolutionRestoreTimer),this.resolutionRestoreTimer=null,window.avatarSDKLogger.log("[Recovery] Cancelled resolution restore due to context loss")),this.isRecovering=!0,this.recoverStartTime=Date.now(),this.recoveryStage="light",this.currentStageAttempts=0,this._scheduleNextAttempt())}_restoreHandler(t){this.restoreTimeout&&(clearTimeout(this.restoreTimeout),this.restoreTimeout=null),this.isRecovering?window.avatarSDKLogger.warn("Context restore event received during recovery, skipping duplicate recovery."):(this.options.reportMessage({code:EErrorCode.WEBGL_CONTEXT_RESTORED,message:"Context restored event received.",e:{event:t,timestamp:Date.now()}}),this.isRecovering=!0,this.recoveryStage="light",this.currentStageAttempts=0,this._recoverContext())}_recoverContext(){if(this.device&&this.pipeline&&this.device.gl&&!this.device.gl.isContextLost())return window.avatarSDKLogger.log("[Recovery] Already recovered, skipping."),void(this.isRecovering=!1);window.avatarSDKLogger.log(`[Recovery] stage=${this.recoveryStage}, attempt=${this.currentStageAttempts+1}/${this.recoveryMaxAttempts[this.recoveryStage]}`),this.restoreTimeout&&(clearTimeout(this.restoreTimeout),this.restoreTimeout=null);let t=!1;try{switch(this.recoveryStage){case"light":t=this._tryLightRecovery();break;case"medium":t=this._tryMediumRecovery();break;case"full":t=this._tryFullRecovery()}}catch(t){window.avatarSDKLogger.error(`[Recovery] stage=${this.recoveryStage} threw:`,t)}t?this._onRecoverySuccess():(this.currentStageAttempts++,this.isRecovering=!1,this.currentStageAttempts<this.recoveryMaxAttempts[this.recoveryStage]?this._scheduleNextAttempt():this._advanceStage())}_tryLightRecovery(){try{if(window.avatarSDKLogger.log("[Recovery] Trying light recovery (reuse canvas)..."),this.device){try{this.device.canvas.removeEventListener("webglcontextlost",this.lostHandler),this.device.canvas.removeEventListener("webglcontextrestored",this.restoreHandler),this.device.destroy()}catch(t){}this.device=null}if(this.device=new GLDevice(this.canvas),this.device.canvas.addEventListener("webglcontextlost",this.lostHandler,!1),this.device.canvas.addEventListener("webglcontextrestored",this.restoreHandler,!1),!this.device.gl||this.device.gl.isContextLost())throw new Error("WebGL context still lost after light recovery");return this.createPipelineLock=!0,this.pipeline=new GLPipeline(this.device,this.sendSdkPoint),this.createPipelineLock=!1,this.pendingCharData&&(this.pipeline.setCharData(this.pendingCharData),this.pipeline.setSyncMedia()),this.pipeline.reinitialize(),this.pipeline.setSyncMedia(),this.isInit=!0,!0}catch(t){return window.avatarSDKLogger.warn("[Recovery] Light recovery failed:",t),this._reportRecoveryFailure("light",t),!1}}_tryMediumRecovery(){try{var t;if(window.avatarSDKLogger.log("[Recovery] Trying medium recovery (replace canvas)..."),this.device){try{this.device.canvas.removeEventListener("webglcontextlost",this.lostHandler),this.device.canvas.removeEventListener("webglcontextrestored",this.restoreHandler),this.device.destroy()}catch(t){}this.device=null}if(this.pipeline){try{this.pipeline.destroy()}catch(t){}this.pipeline=null}const r=this.canvas,i=r.style.cssText,s=r.parentNode,a=document.createElement("canvas"),o=null==(t=this.options.resourceManager.getConfig())?void 0:t.resolution;var e,n;if(o&&(a.width=null!=(e=o.width)?e:1080,a.height=null!=(n=o.height)?n:1920),a.setAttribute("style",i),s&&s.replaceChild(a,r),this.canvas=a,this.device=new GLDevice(this.canvas),this.device.canvas.addEventListener("webglcontextlost",this.lostHandler,!1),this.device.canvas.addEventListener("webglcontextrestored",this.restoreHandler,!1),!this.device.gl||this.device.gl.isContextLost())throw new Error("WebGL context lost after medium recovery");return this.createPipelineLock=!0,this.pipeline=new GLPipeline(this.device,this.sendSdkPoint),this.createPipelineLock=!1,this.pendingCharData&&(this.pipeline.setCharData(this.pendingCharData),this.pipeline.setSyncMedia()),this.pipeline.reinitialize(),this.pipeline.setSyncMedia(),this.isInit=!0,!0}catch(t){return window.avatarSDKLogger.warn("[Recovery] Medium recovery failed:",t),this._reportRecoveryFailure("medium",t),!1}}_tryFullRecovery(){try{var t,e,n;if(window.avatarSDKLogger.log("[Recovery] Trying full recovery (reduced resolution)..."),this.device){try{this.device.canvas.removeEventListener("webglcontextlost",this.lostHandler),this.device.canvas.removeEventListener("webglcontextrestored",this.restoreHandler),this.device.destroy()}catch(t){}this.device=null}if(this.pipeline){try{this.pipeline.destroy()}catch(t){}this.pipeline=null}const r=this.canvas,i=r.style.cssText,s=r.parentNode,a=document.createElement("canvas"),o=null==(t=this.options.resourceManager.getConfig())?void 0:t.resolution,l=.75,c=Math.round((null!=(e=null==o?void 0:o.width)?e:1080)*l),d=Math.round((null!=(n=null==o?void 0:o.height)?n:1920)*l);if(a.width=c,a.height=d,a.setAttribute("style",i),s&&s.replaceChild(a,r),this.canvas=a,window.avatarSDKLogger.log(`[Recovery] Using reduced resolution: ${c}x${d} (scale=${l})`),this.device=new GLDevice(this.canvas),this.device.canvas.addEventListener("webglcontextlost",this.lostHandler,!1),this.device.canvas.addEventListener("webglcontextrestored",this.restoreHandler,!1),!this.device.gl||this.device.gl.isContextLost())throw new Error("WebGL context lost after full recovery");return this.createPipelineLock=!0,this.pipeline=new GLPipeline(this.device,this.sendSdkPoint),this.createPipelineLock=!1,this.pendingCharData&&(this.pipeline.setCharData(this.pendingCharData),this.pipeline.setSyncMedia()),this.pipeline.reinitialize(),this.pipeline.setSyncMedia(),this.isInit=!0,!0}catch(t){return window.avatarSDKLogger.warn("[Recovery] Full recovery failed:",t),this._reportRecoveryFailure("full",t),!1}}_onRecoverySuccess(){const t=Date.now()-this.recoverStartTime,e="full"===this.recoveryStage;window.avatarSDKLogger.log(`[Recovery] Success! stage=${this.recoveryStage}, time=${t}ms${e?" (reduced resolution)":""}`),this.options.reportMessage({code:EErrorCode.WEBGL_CONTEXT_RECOVERED,message:`Context recovered via ${this.recoveryStage} recovery in ${t}ms.`,e:{timestamp:Date.now(),recoveryTime:t,stage:this.recoveryStage,attempts:this.currentStageAttempts+1,reducedResolution:e}}),e&&(this.isUsingReducedResolution=!0,this._scheduleResolutionRestore()),this.isRecovering=!1,this.recoveryStage="light",this.currentStageAttempts=0}_scheduleResolutionRestore(){this.resolutionRestoreTimer&&clearTimeout(this.resolutionRestoreTimer),window.avatarSDKLogger.log(`[Recovery] Scheduling resolution restore in ${this.RESOLUTION_RESTORE_DELAY}ms`),this.resolutionRestoreTimer=setTimeout(()=>{this._restoreOriginalResolution()},this.RESOLUTION_RESTORE_DELAY)}_restoreOriginalResolution(){if(this.isUsingReducedResolution&&this.device&&!this.device.gl.isContextLost())try{var t,e,n;window.avatarSDKLogger.log("[Recovery] Attempting to restore original resolution...");const r=null==(t=this.options.resourceManager.getConfig())?void 0:t.resolution,i=null!=(e=null==r?void 0:r.width)?e:1080,s=null!=(n=null==r?void 0:r.height)?n:1920,a=this.canvas.style.cssText,o=this.canvas.parentNode,l=document.createElement("canvas");if(l.width=i,l.height=s,l.setAttribute("style",a),o&&o.replaceChild(l,this.canvas),this.canvas=l,this.device){try{this.device.canvas.removeEventListener("webglcontextlost",this.lostHandler),this.device.canvas.removeEventListener("webglcontextrestored",this.restoreHandler),this.device.destroy()}catch(t){}this.device=null}if(this.pipeline){try{this.pipeline.destroy()}catch(t){}this.pipeline=null}if(this.device=new GLDevice(this.canvas),this.device.canvas.addEventListener("webglcontextlost",this.lostHandler,!1),this.device.canvas.addEventListener("webglcontextrestored",this.restoreHandler,!1),!this.device.gl||this.device.gl.isContextLost())throw new Error("Context lost after resolution restore");this.createPipelineLock=!0,this.pipeline=new GLPipeline(this.device,this.sendSdkPoint),this.createPipelineLock=!1,this.pendingCharData&&(this.pipeline.setCharData(this.pendingCharData),this.pipeline.setSyncMedia()),this.pipeline.reinitialize(),this.pipeline.setSyncMedia(),this.isUsingReducedResolution=!1,window.avatarSDKLogger.log(`[Recovery] Resolution restored to ${i}x${s}`),this.options.reportMessage({code:EErrorCode.WEBGL_RESOLUTION_RESTORED,message:`Resolution restored to ${i}x${s}.`,e:{timestamp:Date.now(),resolution:{width:i,height:s}}})}catch(t){window.avatarSDKLogger.warn("[Recovery] Failed to restore resolution, keeping reduced:",t)}finally{this.resolutionRestoreTimer=null}else window.avatarSDKLogger.warn("[Recovery] Cannot restore resolution: not in reduced mode or context lost")}_advanceStage(){const t=["light","medium","full"],e=t.indexOf(this.recoveryStage);if(e<t.length-1){const n=t[e+1];window.avatarSDKLogger.log(`[Recovery] Stage "${this.recoveryStage}" exhausted, upgrading to "${n}"`),this.recoveryStage=n,this.currentStageAttempts=0,this._scheduleNextAttempt()}else window.avatarSDKLogger.error("[Recovery] All recovery stages exhausted. Giving up."),this.options.reportMessage({code:EErrorCode.WEBGL_CONTEXT_RECOVERY_MAX_ATTEMPTS,message:"All WebGL recovery stages exhausted. SDK restart required.",e:{timestamp:Date.now(),elapsedTime:Date.now()-this.recoverStartTime,stagesAttempted:{light:this.recoveryMaxAttempts.light,medium:this.recoveryMaxAttempts.medium,full:this.recoveryMaxAttempts.full}}}),this.isRecovering=!1}_scheduleNextAttempt(){const t=this.recoveryBaseDelays[this.recoveryStage],e=this.recoveryMaxAttempts[this.recoveryStage],n=t*Math.pow(2,this.currentStageAttempts),r=Math.min(n,this.recoveryMaxDelay);window.avatarSDKLogger.log(`[Recovery] Scheduling ${this.recoveryStage} attempt ${this.currentStageAttempts+1}/${e} in ${r}ms (base=${t}ms, exp=${n}ms)`),this.restoreTimeout=setTimeout(()=>{this.isRecovering=!0,this._recoverContext()},r)}_reportRecoveryFailure(t,e){this.options.reportMessage({code:EErrorCode.WEBGL_CONTEXT_RECOVERY_FAILED,message:`[${t}] recovery attempt ${this.currentStageAttempts+1}/${this.recoveryMaxAttempts[t]} failed.`,e:{error:e,stage:t,attempt:this.currentStageAttempts+1,timestamp:Date.now()}})}init(t){var e,n,r,i,s;let a=t;this.style(null!=(e=null==(n=this.options.resourceManager.getConfig())||null==(n=n.resolution)?void 0:n.width)?e:1080,null!=(r=null==(i=this.options.resourceManager.getConfig())||null==(i=i.resolution)?void 0:i.height)?r:1920),this.setCharacterCanvasAnchor(),null!=(s=a)&&s.char||(a={char:this.options.resourceManager.getMouthShapeLib().char_info,LUT:null,transform:{offsetX:0,offsetY:0,scaleX:1,scaleY:1},multisample:4}),this.pendingCharData=a,this.isInit=!0,this.device=new GLDevice(this.canvas),this.device.canvas.addEventListener("webglcontextlost",this.lostHandler,!1),this.device.canvas.addEventListener("webglcontextrestored",this.restoreHandler,!1),this.createPipeline()}style(t=0,e=0){t>0&&e>0&&(this.canvas.width=t,this.canvas.height=e)}setCanvasStyle(t){var e,n,r,i,s,a,o,l;this.layout=t,this.canvasOffsetX=-1;const c=null!=(e=null!=(n=null==(r=this.walkConfig)?void 0:r.init_point)?n:null==(i=this.options.resourceManager.getConfig())||null==(i=i.walk_config)?void 0:i.init_point)?e:null,{width:d=1080,height:h=1920}=null!=(s=null==(a=this.options.resourceManager.getConfig())?void 0:a.resolution)?s:{width:1080,height:1920},[u,p]=null!=(o=null==(l=t.container)?void 0:l.size)?o:[d,h];let{v_align:f="center",h_align:m="center",scale:_=1,offset_x:g=0,offset_y:y=0}=t.avatar||{};if(null!=c&&(m="left",g=0),"string"==typeof _&&_.includes("vh")){const t=parseFloat(_.replace("vh",""));_=isNaN(t)?1:t/100*p/h}this.scale=Number(_);const S=h*Number(_),A=d*Number(_),v=A/2,E=S/2,b={position:"absolute",zIndex:100,height:`${S}px`,width:`${A}px`,objectFit:"contain",top:"auto",right:"auto",bottom:"auto",left:"auto",marginLeft:"0",marginTop:"0",willChange:"transform",transform:"translateZ(0)"};switch(m){case"left":b.left=null!=c?c-v+"px":"0",b.marginLeft=`${g}px`;break;case"right":b.right=`-${v}px`,b.marginLeft=`${g}px`;break;default:b.position="absolute",b.left="50%",b.marginLeft=`${-v+g}px`}switch(f){case"top":b.top="0",b.marginTop=`${y}px`;break;case"bottom":b.bottom="0",b.marginTop=`${y}px`;break;default:b.position="absolute",b.top="50%",b.marginTop=`${-E+y}px`}const T=getStyleStr(b);this.canvas.setAttribute("style",T)}setWalkConfig(t){this.walkConfig=t,this.baseWalkOffset=this.lastBodyOffset,null!=t.init_point&&this.layout&&this.setCanvasStyle(this.layout)}setCharacterCanvasAnchor(t){var e;if(null!=t&&t.avatar)this.setCanvasStyle(t);else if(null!=(e=this.options.resourceManager.getConfig())&&e.layout){var n;const t=(null==(n=this.options.resourceManager.getConfig())?void 0:n.layout)||{avatar:{v_align:"default",h_align:"default",scale:1,offset_x:0,offset_y:0}};this.setCanvasStyle(t)}else{var r;const t=getStyleStr({position:"absolute",zIndex:100,height:"100%",objectFit:"contain",top:"auto",right:"auto",bottom:"auto",left:"auto",marginLeft:"0",marginTop:"0"});this.canvas.setAttribute("style",t);const e=(null==(r=this.options.resourceManager.getConfig())||null==(r=r.init_events)?void 0:r.find(t=>"SetCharacterCanvasAnchor"===t.type))||{type:"SetCharacterCanvasAnchor",x_location:0,y_location:0,width:1,height:1},{x_location:n,y_location:i,width:s,height:a}=e;this.canvas.setAttribute("style",this.canvas.style.cssText+`left: calc(${n} * 100%); top: calc(${i} * 100%); transform: scale(${s}, ${a}); transform-origin: top left;`)}}computeWeight(t){const e=t-this.lastFrameIndex;return this.lastWeight=t>this.lastRealFaceFrame?Math.min(this.lastWeight+e,12):Math.max(this.lastWeight-e,0),this.lastWeight/12}render(t){var e,n,r,i,s,a,o;if(this.options.dataCacheQueue.clearOldFaceData(t),!this.isInit)return{canvas:this.canvas,rendered:!1};const l=this.options.dataCacheQueue._getBodyImageBitmap(t);let c=this.options.dataCacheQueue._getFaceImageBitmap(t,null!=(e=null!=(n=null==l?void 0:l.body_id)?n:null==l?void 0:l.id)?e:0),d=this.options.dataCacheQueue._getRealFaceImageBitmap(t,null!=(r=null!=(i=null==l?void 0:l.body_id)?i:null==l?void 0:l.id)?r:0);if("speak"===this.lastFrameState&&"speak"!==(null==l?void 0:l.frameState)&&(this.lastRealFaceFrame=-1,this.lastRealFaceFrameData=null,this.lastWeight=0),this.interrupt)c=d;else if(null!=(s=c)&&s.FaceFrameData&&null!=(a=c)&&a.face_frame_type){if(this.lastRealFaceFrameData=c.FaceFrameData,this.lastRealFaceFrame=t,-1!==this.lastRealFaceFrame&&this.lastWeight>0&&d){var h,u;const e=this.computeWeight(t);c={frameIndex:t,state:(null==l?void 0:l.frameState)||"idle",body_id:(null==l?void 0:l.body_id)||-1,sf:t,ef:t,cs:(null==(h=c)?void 0:h.cs)||"",face_frame_type:0,id:(null==l?void 0:l.body_id)||-1,FaceFrameData:IBRAnimationFrameData_NN.interp(this.lastRealFaceFrameData,d.FaceFrameData,d.FaceFrameData,e,(null==(u=this.options.resourceManager.resource_pack)?void 0:u.interpolate_joints)||[])}}}else if(-1===this.lastRealFaceFrame)c=d;else if(null!=d&&d.FaceFrameData)if(null===this.lastRealFaceFrameData)c=d;else{var p,f;const e=this.computeWeight(t);c={frameIndex:t,state:(null==l?void 0:l.frameState)||"idle",body_id:(null==l?void 0:l.body_id)||-1,sf:t,ef:t,cs:(null==(p=c)?void 0:p.cs)||"",face_frame_type:0,id:(null==l?void 0:l.body_id)||-1,FaceFrameData:IBRAnimationFrameData_NN.interp(this.lastRealFaceFrameData,d.FaceFrameData,d.FaceFrameData,e,(null==(f=this.options.resourceManager.resource_pack)?void 0:f.interpolate_joints)||[])}}if(this._setCurrentBodyFrame(l),!(l&&c||null==l)&&l.hfd||!(null!=l&&l.hfd||null!=l&&l.frame))return l?c||(this.allLostFaceFrameCount++,this.options.reportMessage({code:EErrorCode.RENDER_FACE_ERROR,message:`Error: 第${t}帧 faceFrame为空`,e:{bodyFrame:l,faceFrame:c}})):(this.allLostFrameCount++,this.options.reportMessage({code:EErrorCode.RENDER_BODY_ERROR,message:`Error: 第${t}帧 bodyFrame为空`,e:{bodyFrame:l,faceFrame:c}})),this.allLostFrameCount===this.maxLostFrameCount&&(this.options.reportMessage({code:EErrorCode.RENDER_DATA_MISSING,message:`连续${this.maxLostFrameCount}帧 身体渲染数据缺失`,e:{bodyFrame:l,faceFrame:c}}),this.forceSyncDecoder(),this.allLostFrameCount=0),this.allLostFaceFrameCount===this.maxLostFrameCount&&this.options.reportMessage({code:EErrorCode.RENDER_FACE_DATA_MISSING,message:`连续${this.maxLostFrameCount}帧 渲染表情数据缺失.`,e:{bodyFrame:l,frameIndex:t}}),window.avatarSDKLogger.log(this.TAG,"render第",t,"丢帧,bodyFrame",l,"faceFrame",c),{canvas:this.canvas,rendered:!1};if(this.allLostFrameCount=0,this.allLostFaceFrameCount=0,(l&&null!=(o=c)&&o.FaceFrameData&&null!=l&&l.hfd||(null==l||!l.hfd)&&null!=l&&l.frame)&&this.device){var m,_;this.sendVideoInfo({name:l.name,body_id:l.body_id,id:l.id}),(null==l?void 0:l.frameState)!==this.lastFrameState&&(null==(m=this.onStateChange)||m.call(this,null==l?void 0:l.frameState),"speak"!==l.frameState&&window.performanceTracker.markEnd(performanceConstant.start_action_render,l.frameState),this.lastFrameState=null==l?void 0:l.frameState),this.isFirstRender&&(window.performanceTracker.markEnd(performanceConstant.first_avatar_render),this.isFirstRender=!1,this.renderBackground(),window.performanceTracker.markStart(performanceConstant.first_render),null==(_=this.onDownloadProgress)||_.call(this,100));let e=!1;if(this.pipeline){var g;try{var y,S,A,v,E,b,T;const n=this.options.resourceManager.getIsEnableRobotExpression()?null!=(y=null==(S=c)?void 0:S.FaceFrameData)?y:null:null!=l&&l.hfd&&null!=(A=null==(v=c)?void 0:v.FaceFrameData)?A:null;n&&this.saveAndDownload.appendMultipleToArray("render_faceData",[c]),this.lastFaceFrame=c;let r=l.frame;var w;isharmony()&&(this.copyCanvas.width=l.frame.displayWidth,this.copyCanvas.height=l.frame.displayHeight,null==(w=this.copyCtx)||w.drawImage(l.frame,0,0),r=this.copyCanvas),this.pipeline.renderFrame({charBodyTexture:r,data:n,backgroundTexture:null,fx:null!=(E=null==(b=this.options.resourceManager.getConfig())?void 0:b.fx)?E:{},onPostRender:()=>null});let i=[0,0,0],s=[...i];const a=null!=(T=null==l?void 0:l.offset)?T:0;this.lastBodyOffset=a,s[0]+=a-this.baseWalkOffset;const o=this.pipeline.getBillboardTransform2D([i[0],i[1],i[2]],[s[0],s[1],s[2]]).offsetX*this.canvas.width*this.scale;o!==this.canvasOffsetX&&(this.canvasOffsetX=o,WidgetDefaultRenderer.CUSTOM_WIDGET?WidgetDefaultRenderer.CUSTOM_WIDGET({type:"set_character_canvas_offset",data:o}):WidgetDefaultRenderer.PROXY_WIDGET&&WidgetDefaultRenderer.PROXY_WIDGET.set_character_canvas_offset?WidgetDefaultRenderer.PROXY_WIDGET.set_character_canvas_offset(o):updateCanvasXOffset(this.canvas,o)),this.lastFrameIndex=t,e=!0}catch(e){window.avatarSDKLogger.error(this.TAG,"渲染帧失败:",e),this.options.reportMessage({code:EErrorCode.WebGL_RENDER_ERROR,message:`Error: 第${t}帧 webgl渲染异常`,e:{bodyFrame:l,faceFrame:c,error:e}})}finally{l.frame&&"function"==typeof l.frame.close&&l.frame.close()}null==(g=this.onRenderChange)||g.call(this,RenderState.rendering)}else null!=l&&l.frame&&"function"==typeof l.frame.close&&l.frame.close();return{canvas:this.canvas,rendered:e}}return{canvas:this.canvas,rendered:!1}}renderBackground(){const t=this.options.resourceManager.getBackgroundImageElement();if(!t)return;const e=document.getElementById("avatar-bg-container");e&&(e.style.backgroundImage=`url(${t.src})`,e.style.backgroundSize="cover",e.style.backgroundPosition="center")}_setCurrentBodyFrame(t){t&&(this.currentBodyFrame=t)}_getCurrentBodyFrameInfo(t){return this.currentBodyFrame&&t>0?{client_frame:t,current_ani:this.currentBodyFrame.name,current_ani_frame:this.currentBodyFrame.frameIndex-this.currentBodyFrame.sf,next_state:this.lastFrameState||"idle"}:{client_frame:0,current_ani:"",current_ani_frame:0,next_state:"idle"}}_getCurrentFrameData(t){var e,n,r,i,s;const a=this.currentBodyFrame,o=this.lastFaceFrame;return{body:a?{body_id:null!=(e=null!=(n=a.body_id)?n:a.id)?e:0,name:a.name,video_frame:a.frameIndex-a.sf,sf:a.sf,state:a.frameState}:null,face:o?{body_id:null!=(r=null!=(i=o.body_id)?i:o.id)?r:0,sf:o.sf,ef:o.ef,state:o.state,face_frame_type:null!=(s=o.face_frame_type)?s:0}:null}}setCanvasVisibility(t){this.avatarCanvasVisible=t,this.canvas&&(this.canvas.style.display=t?"":"none")}getCanvasVisibility(){return this.avatarCanvasVisible}destroy(){if(this.allLostFrameCount=0,this.allLostFaceFrameCount=0,this.restoreTimeout&&(clearTimeout(this.restoreTimeout),this.restoreTimeout=null),this.isRecovering=!1,this.recoveryStage="light",this.currentStageAttempts=0,this.device)if(this.device.canvas.removeEventListener("webglcontextlost",this.lostHandler),this.device.canvas.removeEventListener("webglcontextrestored",this.restoreHandler),this.pipeline&&(this.pipeline.destroy(),this.pipeline=null),this.device.gl){const t=this.device;this.device=null,requestAnimationFrame(()=>{try{t&&t.destroy()}catch(t){var e;null==(e=window.avatarSDKLogger)||null==e.warn||e.warn("[AvatarRenderer] 销毁 device 时出错:",t)}})}else this.device=null;this.isInit=!1,this.isFirstRender=!0,this.lastRealFaceFrame=-1,this.lastRealFaceFrameData=null,this.lastWeight=0,this.onStateChange=void 0,this.lastFrameState="",this.pipeline=null,this.pendingCharData=null,this.scale=1;const t=document.getElementById("avatar-bg-container");t&&t.parentNode&&t.parentNode.removeChild(t),this.canvas&&this.canvas.parentNode&&this.canvas.remove()}setInterrupt(t){var e;"speak"!==(null==(e=this.lastFaceFrame)?void 0:e.state)&&t||(this.interrupt=t)}simulateContextLoss(t=5e3,e=!1){if(!this.device||!this.device.gl)return void window.avatarSDKLogger.warn("[Test] No WebGL device available for testing");const n=this.device.gl.getExtension("WEBGL_lose_context");n?(window.avatarSDKLogger.log("[Test] Simulating WebGL context loss..."),e&&window.avatarSDKLogger.warn("[Test] Force fail mode enabled - will not auto-restore"),n.loseContext(),t>0&&!e&&setTimeout(()=>{window.avatarSDKLogger.log(`[Test] Auto-restoring context after ${t}ms...`),n.restoreContext()},t)):window.avatarSDKLogger.error("[Test] WEBGL_lose_context extension not available")}getRecoveryStatus(){return{isRecovering:this.isRecovering,stage:this.recoveryStage,attempts:this.currentStageAttempts,maxAttempts:this.recoveryMaxAttempts[this.recoveryStage]||0,isUsingReducedResolution:this.isUsingReducedResolution}}async testStagedRecovery(){window.avatarSDKLogger.log("[Test] Starting staged recovery test...");const t=[{desc:"Light recovery (should succeed)",delay:1e3,forceFail:!1},{desc:"Context loss again (may upgrade to medium)",delay:8e3,forceFail:!1}];for(let e=0;e<t.length;e++){const n=t[e];window.avatarSDKLogger.log(`[Test] Step ${e+1}: ${n.desc}`),await new Promise(t=>{setTimeout(()=>{this.simulateContextLoss(n.delay,n.forceFail),t()},n.delay)}),await new Promise(t=>setTimeout(t,n.delay+2e3));const r=this.getRecoveryStatus();window.avatarSDKLogger.log(`[Test] After step ${e+1}:`,r)}window.avatarSDKLogger.log("[Test] Staged recovery test completed!")}restartWebGL(){window.avatarSDKLogger.log("[restartWebGL] Starting manual WebGL restart..."),this.restoreTimeout&&(clearTimeout(this.restoreTimeout),this.restoreTimeout=null),this.resolutionRestoreTimer&&(clearTimeout(this.resolutionRestoreTimer),this.resolutionRestoreTimer=null),this.isRecovering=!1,this.recoveryStage="light",this.currentStageAttempts=0;try{var t;if(this.device){try{this.device.canvas.removeEventListener("webglcontextlost",this.lostHandler),this.device.canvas.removeEventListener("webglcontextrestored",this.restoreHandler),this.device.destroy()}catch(t){}this.device=null}if(this.pipeline){try{this.pipeline.destroy()}catch(t){}this.pipeline=null}const r=this.canvas,i=r.style.cssText,s=r.parentNode,a=document.createElement("canvas"),o=null==(t=this.options.resourceManager.getConfig())?void 0:t.resolution;var e,n;if(o&&(a.width=null!=(e=o.width)?e:1080,a.height=null!=(n=o.height)?n:1920),a.setAttribute("style",i),s&&s.replaceChild(a,r),this.canvas=a,this.device=new GLDevice(this.canvas),this.device.canvas.addEventListener("webglcontextlost",this.lostHandler,!1),this.device.canvas.addEventListener("webglcontextrestored",this.restoreHandler,!1),!this.device.gl||this.device.gl.isContextLost())throw new Error("WebGL context still lost after creating new canvas");return this.createPipelineLock=!0,this.pipeline=new GLPipeline(this.device,this.sendSdkPoint),this.createPipelineLock=!1,this.pendingCharData&&(this.pipeline.setCharData(this.pendingCharData),this.pipeline.setSyncMedia()),this.pipeline.reinitialize(),this.pipeline.setSyncMedia(),this.isInit=!0,window.avatarSDKLogger.log("[restartWebGL] WebGL restart successful!"),this.options.reportMessage({code:EErrorCode.WEBGL_CONTEXT_MANUAL_RESTARTED,message:"WebGL context recovered via manual restart.",e:{timestamp:Date.now(),method:"manual_restart"}}),!0}catch(t){return window.avatarSDKLogger.error("[restartWebGL] Failed:",t),this._reportRecoveryFailure("manual",t),!1}}}class BaseTrack{render(){}stop(){}}class ImageTrack extends BaseTrack{constructor(t,e){super(),this.data=t,this.instance=e}render(){var t;return null!=(t=this.data)&&t.image?WidgetDefaultRenderer.WIDGET_PIC(this.data,this.instance):null}}class SubtitleTrack extends BaseTrack{constructor(t,e){super(),this.data=t,this.instance=e}render(){return WidgetDefaultRenderer.WIDGET_SUBTITLE(this.data,this.instance)}}class TrackRenderer{constructor(t,e){this.TAG="[TrackRenderer]",this.instance=e;const{type:n,data:r,text:i=""}=t;var s;"widget_pic"===n&&(this.tracker=new ImageTrack(r,e)),("subtitle_on"===n||"subtitle_off"===n)&&(this.tracker=new SubtitleTrack({type:n,text:i,axis_id:null!=(s=null==r?void 0:r.axis_id)?s:1e3},e))}render(){var t;return null==(t=this.tracker)?void 0:t.render()}stop(){this.tracker.stop()}destroy(){WidgetDefaultRenderer.destroy(this.instance)}}class UIRenderer{constructor(t){this.TAG="[UIRenderer]",this.trackerRenderer=[],this.root=document.createElement("div"),this.lastFrameIndex=-1,this.initEventsRendered=!1,this.lastSpeechId=-1,this.interruptSpeechId=-1,this.enableClientInterrupt=!1,this.options=t,this.root.setAttribute("style","position:absolute;"),this.onVoiceStart=t.onVoiceStart,this.onVoiceEnd=t.onVoiceEnd,this.initEventsRendered=!1,this.onWalkStateChange=t.onWalkStateChange,this.enableClientInterrupt=t.enableClientInterrupt,this.onSpeakStateChange=t.onSpeakStateChange}render(t){var e,n,r,i,s,a,o,l,c;let d=[];if(-1===this.lastFrameIndex){const t=this.options.resourceManager.getConfig();t.init_events&&t.init_events.length>0&&(d=t.init_events.map(t=>_extends({},t,{speech_id:0})))}let h=null;if(h=t-this.lastFrameIndex>1?this.options.dataCacheQueue._getEventInterval(this.lastFrameIndex,t):this.options.dataCacheQueue._getEvent(t),this.lastFrameIndex=t,this.initEventsRendered||(this.initEventsRendered=!0,h?h.e=h.e.concat(d):h={e:d}),null==(e=h)||!e.e)return;window.avatarSDKLogger.log("当前帧",t,"获取到的事件",JSON.stringify(h));const u=null==(n=h.e)?void 0:n.filter(t=>null==(null==t?void 0:t.speech_id));if(null!=u&&u.length){const t=u.map(t=>t.type).join(",");this.options.sdk.onMessage({code:EErrorCode.EVENT_WITHOUT_SPEECH_ID,message:`Error: 事件中存在不包含speech_id的事件${t}`,e:u})}var p,f;if(this.enableClientInterrupt&&(h.e=null==(p=h.e)?void 0:p.filter(t=>t.speech_id>this.interruptSpeechId||null==t.speech_id||t.type.endsWith("_end")||"subtitle_off"===t.type)),-1!==this.lastSpeechId&&this.lastSpeechId&&(h.e=null==(f=h.e)?void 0:f.filter(t=>(null==t?void 0:t.speech_id)>=this.lastSpeechId)),null!=(r=h.e)&&r.some(t=>"speak_start"===t.type)){const t=h.e.find(t=>"speak_start"===t.type);this.lastSpeechId=null==t?void 0:t.speech_id,this.onSpeakStateChange("speak_start",t.client_speak_id,(null==t?void 0:t.speech_id)||0)}if((null!=(i=h.e)&&i.some(t=>"walk_start"===t.type)||null!=(s=h.e)&&s.some(t=>"speak_walk_start"===t.type))&&this.onWalkStateChange("walk_start"),null!=(a=h.e)&&a.some(t=>"voice_start"===t.type)){const t=h.e.find(t=>"voice_start"===t.type),e=window.performanceTracker.markEnd(performanceConstant.voice_response_play,"speak");this.options.sendSdkPoint("rendering_display",{multi_turn_conversation_id:null==t?void 0:t.multi_turn_conversation_id}),this.onVoiceStart(e,null==t?void 0:t.client_speak_id)}if((null!=(o=h.e)&&o.some(t=>"walk_end"===t.type)||null!=(l=h.e)&&l.some(t=>"speak_walk_end"===t.type))&&this.onWalkStateChange("walk_end"),null!=(c=h.e)&&c.some(t=>"voice_end"===t.type)){const t=h.e.find(t=>"voice_end"===t.type);this.onVoiceEnd((null==t?void 0:t.client_speak_id)||"",(null==t?void 0:t.speech_id)||0)}["speak_end","speak_error"].forEach(t=>{const e=h.e.find(e=>e.type===t);e&&this.onSpeakStateChange(t,e.client_speak_id,(null==e?void 0:e.speech_id)||0)});const m=[...h.e];for(let t=0;t<h.e.length;t++){const e=h.e[t];if(!Object.prototype.hasOwnProperty.call(e,"event_type"))if(WidgetDefaultRenderer.CUSTOM_WIDGET){WidgetDefaultRenderer.CUSTOM_WIDGET(e);const t=m.indexOf(e);t>-1&&m.splice(t,1)}else if(WidgetDefaultRenderer.PROXY_WIDGET&&WidgetDefaultRenderer.PROXY_WIDGET[e.type]){WidgetDefaultRenderer.PROXY_WIDGET[e.type](e);const t=m.indexOf(e);t>-1&&m.splice(t,1)}}if(m.length>0)for(const t of m){const e=new TrackRenderer(t,this.options.sdk);this.trackerRenderer.push(e)}return this.trackerRenderer}clearTrackerRenderer(){this.trackerRenderer=[]}setInterrupt(t){this.interruptSpeechId=t}destroy(){this.lastSpeechId=-1,this.interruptSpeechId=-1,this.lastFrameIndex=-1,this.initEventsRendered=!1,WidgetDefaultRenderer.destroy(this.options.sdk),this.trackerRenderer.forEach(t=>t.destroy())}}class FPSTracker{constructor(t=60){this.frameTimestamps=[],this.lastFrameTime=0,this.frameCount=0,this.lastUpdateTime=0,this.currentFPS=0,this.totalFrames=0,this.totalTime=0,this.droppedFrames=0,this.totalRenderedFrames=0,this.maxSamples=t}tick(t=!0){const e=performance.now();if(this.lastFrameTime>0){const n=e-this.lastFrameTime;this.frameTimestamps.push(n),this.frameTimestamps.length>this.maxSamples&&this.frameTimestamps.shift(),this.totalFrames++,this.totalTime+=n,t?(this.frameCount++,this.totalRenderedFrames++):this.droppedFrames++,e-this.lastUpdateTime>=1e3&&(this.currentFPS=Math.round(1e3*this.frameCount/(e-this.lastUpdateTime)),this.frameCount=0,this.lastUpdateTime=e)}this.lastFrameTime=e}getStats(){if(0===this.frameTimestamps.length)return{current:0,average:0,min:0,max:0,droppedFrames:0,totalFrames:0};const t=this.frameTimestamps.reduce((t,e)=>t+e,0)/this.frameTimestamps.length,e=Math.min(...this.frameTimestamps),n=Math.max(...this.frameTimestamps);return{current:this.currentFPS,average:this.frameTimestamps.length>0?Math.round(1e3/t):0,min:e>0?Math.round(1e3/n):0,max:n>0?Math.round(1e3/e):0,droppedFrames:this.droppedFrames,totalFrames:this.totalFrames}}getCurrentFPS(){return this.currentFPS}getAverageFPS(){return 0===this.totalTime?0:Math.round(1e3*this.totalFrames/this.totalTime)}reset(){this.frameTimestamps=[],this.lastFrameTime=0,this.frameCount=0,this.lastUpdateTime=0,this.currentFPS=0,this.totalFrames=0,this.totalTime=0,this.droppedFrames=0,this.totalRenderedFrames=0}getDroppedFrames(){return this.droppedFrames}}class Composition{constructor(t){this.TAG="[Composition]",this.container=t.container,this.avatarRenderer=t.avatarRenderer,this.restRenderers=t.restRenderers,this.audioRenderer=t.audioRenderer,this.onFPSUpdate=t.onFPSUpdate,this.audioOnlyMode=t.audioOnlyMode||!1,this.fpsTracker=new FPSTracker,this.audioOnlyMode||this.container.appendChild(t.avatarRenderer.canvas)}compose(t){if(!this.audioOnlyMode){const e=this.avatarRenderer.render(t);this.fpsTracker.tick(e.rendered);const n=this.fpsTracker.getStats();this.onFPSUpdate&&n.current>0&&this.onFPSUpdate(n)}this.audioRenderer.render(t);for(const e of this.restRenderers){const n=e.render(t);if(e.clearTrackerRenderer(),n)for(const t of n){const e=null==t?void 0:t.render();e&&this.container.appendChild(e)}}}getFPSStats(){return this.fpsTracker.getStats()}stop(){this.audioRenderer.stop(-1)}destroy(){this.avatarRenderer.destroy(),this.audioRenderer.destroy(),this.restRenderers.forEach(t=>t.destroy())}}const mp4boxSource='\nvar Log = function() {\n\tvar i = new Date,\n\tr = 4;\n\treturn {\n\t\tsetLogLevel: function(t) {\n\t\t\tr = t == this.debug ? 1 : t == this.info ? 2 : t == this.warn ? 3 : (this.error, 4)\n\t\t},\n\t\tdebug: function(t, e) {\n\t\t\tvoid 0 === console.debug && (console.debug = console.log),\n\t\t\tr <= 1 && console.debug("[" + Log.getDurationString(new Date - i, 1e3) + "]", "[" + t + "]", e)\n\t\t},\n\t\tlog: function(t, e) {\n\t\t\tthis.debug(t.msg)\n\t\t},\n\t\tinfo: function(t, e) {\n\t\t\tr <= 2 && console.info("[" + Log.getDurationString(new Date - i, 1e3) + "]", "[" + t + "]", e)\n\t\t},\n\t\twarn: function(t, e) {\n\t\t\tr <= 3 && console.warn("[" + Log.getDurationString(new Date - i, 1e3) + "]", "[" + t + "]", e)\n\t\t},\n\t\terror: function(t, e) {\n\t\t\tr <= 4 && console.error("[" + Log.getDurationString(new Date - i, 1e3) + "]", "[" + t + "]", e)\n\t\t}\n\t}\n} ();\nLog.getDurationString = function(t, e) {\n\tvar i;\n\tfunction r(t, e) {\n\t\tfor (var i = ("" + t).split("."); i[0].length < e;) i[0] = "0" + i[0];\n\t\treturn i.join(".")\n\t}\n\tt < 0 ? (i = !0, t = -t) : i = !1;\n\tvar s = t / (e || 1),\n\ta = Math.floor(s / 3600);\n\ts -= 3600 * a;\n\tt = Math.floor(s / 60),\n\te = 1e3 * (s -= 60 * t);\n\treturn e -= 1e3 * (s = Math.floor(s)),\n\te = Math.floor(e),\n\t(i ? "-": "") + a + ":" + r(t, 2) + ":" + r(s, 2) + "." + r(e, 3)\n},\nLog.printRanges = function(t) {\n\tvar e = t.length;\n\tif (0 < e) {\n\t\tfor (var i = "",\n\t\tr = 0; r < e; r++) 0 < r && (i += ","),\n\t\ti += "[" + Log.getDurationString(t.start(r)) + "," + Log.getDurationString(t.end(r)) + "]";\n\t\treturn i\n\t}\n\treturn "(empty)"\n},\n"undefined" != typeof exports && (exports.Log = Log);\nvar MP4BoxStream = function(t) {\n\tif (! (t instanceof ArrayBuffer)) throw "Needs an array buffer";\n\tthis.buffer = t,\n\tthis.dataview = new DataView(t),\n\tthis.position = 0\n};\nMP4BoxStream.prototype.getPosition = function() {\n\treturn this.position\n},\nMP4BoxStream.prototype.getEndPosition = function() {\n\treturn this.buffer.byteLength\n},\nMP4BoxStream.prototype.getLength = function() {\n\treturn this.buffer.byteLength\n},\nMP4BoxStream.prototype.seek = function(t) {\n\tt = Math.max(0, Math.min(this.buffer.byteLength, t));\n\treturn this.position = isNaN(t) || !isFinite(t) ? 0 : t,\n\t!0\n},\nMP4BoxStream.prototype.isEos = function() {\n\treturn this.getPosition() >= this.getEndPosition()\n},\nMP4BoxStream.prototype.readAnyInt = function(t, e) {\n\tvar i = 0;\n\tif (this.position + t <= this.buffer.byteLength) {\n\t\tswitch (t) {\n\t\tcase 1:\n\t\t\ti = e ? this.dataview.getInt8(this.position) : this.dataview.getUint8(this.position);\n\t\t\tbreak;\n\t\tcase 2:\n\t\t\ti = e ? this.dataview.getInt16(this.position) : this.dataview.getUint16(this.position);\n\t\t\tbreak;\n\t\tcase 3:\n\t\t\tif (e) throw "No method for reading signed 24 bits values";\n\t\t\ti = this.dataview.getUint8(this.position) << 16,\n\t\t\ti |= this.dataview.getUint8(this.position + 1) << 8,\n\t\t\ti |= this.dataview.getUint8(this.position + 2);\n\t\t\tbreak;\n\t\tcase 4:\n\t\t\ti = e ? this.dataview.getInt32(this.position) : this.dataview.getUint32(this.position);\n\t\t\tbreak;\n\t\tcase 8:\n\t\t\tif (e) throw "No method for reading signed 64 bits values";\n\t\t\ti = this.dataview.getUint32(this.position) << 32,\n\t\t\ti |= this.dataview.getUint32(this.position + 4);\n\t\t\tbreak;\n\t\tdefault:\n\t\t\tthrow "readInt method not implemented for size: " + t\n\t\t}\n\t\treturn this.position += t,\n\t\ti\n\t}\n\tthrow "Not enough bytes in buffer"\n},\nMP4BoxStream.prototype.readUint8 = function() {\n\treturn this.readAnyInt(1, !1)\n},\nMP4BoxStream.prototype.readUint16 = function() {\n\treturn this.readAnyInt(2, !1)\n},\nMP4BoxStream.prototype.readUint24 = function() {\n\treturn this.readAnyInt(3, !1)\n},\nMP4BoxStream.prototype.readUint32 = function() {\n\treturn this.readAnyInt(4, !1)\n},\nMP4BoxStream.prototype.readUint64 = function() {\n\treturn this.readAnyInt(8, !1)\n},\nMP4BoxStream.prototype.readString = function(t) {\n\tif (this.position + t <= this.buffer.byteLength) {\n\t\tfor (var e = "",\n\t\ti = 0; i < t; i++) e += String.fromCharCode(this.readUint8());\n\t\treturn e\n\t}\n\tthrow "Not enough bytes in buffer"\n},\nMP4BoxStream.prototype.readCString = function() {\n\tfor (var t = [];;) {\n\t\tvar e = this.readUint8();\n\t\tif (0 === e) break;\n\t\tt.push(e)\n\t}\n\treturn String.fromCharCode.apply(null, t)\n},\nMP4BoxStream.prototype.readInt8 = function() {\n\treturn this.readAnyInt(1, !0)\n},\nMP4BoxStream.prototype.readInt16 = function() {\n\treturn this.readAnyInt(2, !0)\n},\nMP4BoxStream.prototype.readInt32 = function() {\n\treturn this.readAnyInt(4, !0)\n},\nMP4BoxStream.prototype.readInt64 = function() {\n\treturn this.readAnyInt(8, !1)\n},\nMP4BoxStream.prototype.readUint8Array = function(t) {\n\tfor (var e = new Uint8Array(t), i = 0; i < t; i++) e[i] = this.readUint8();\n\treturn e\n},\nMP4BoxStream.prototype.readInt16Array = function(t) {\n\tfor (var e = new Int16Array(t), i = 0; i < t; i++) e[i] = this.readInt16();\n\treturn e\n},\nMP4BoxStream.prototype.readUint16Array = function(t) {\n\tfor (var e = new Int16Array(t), i = 0; i < t; i++) e[i] = this.readUint16();\n\treturn e\n},\nMP4BoxStream.prototype.readUint32Array = function(t) {\n\tfor (var e = new Uint32Array(t), i = 0; i < t; i++) e[i] = this.readUint32();\n\treturn e\n},\nMP4BoxStream.prototype.readInt32Array = function(t) {\n\tfor (var e = new Int32Array(t), i = 0; i < t; i++) e[i] = this.readInt32();\n\treturn e\n},\n"undefined" != typeof exports && (exports.MP4BoxStream = MP4BoxStream);\nvar DataStream = function(t, e, i) {\n\tthis._byteOffset = e || 0,\n\tt instanceof ArrayBuffer ? this.buffer = t: "object" == typeof t ? (this.dataView = t, e && (this._byteOffset += e)) : this.buffer = new ArrayBuffer(t || 0),\n\tthis.position = 0,\n\tthis.endianness = null == i ? DataStream.LITTLE_ENDIAN: i\n};\nDataStream.prototype = {},\nDataStream.prototype.getPosition = function() {\n\treturn this.position\n},\nDataStream.prototype._realloc = function(t) {\n\tif (this._dynamicSize) {\n\t\tvar e = this._byteOffset + this.position + t,\n\t\ti = this._buffer.byteLength;\n\t\tif (e <= i) e > this._byteLength && (this._byteLength = e);\n\t\telse {\n\t\t\tfor (i < 1 && (i = 1); i < e;) i *= 2;\n\t\t\tvar r = new ArrayBuffer(i),\n\t\t\tt = new Uint8Array(this._buffer);\n\t\t\tnew Uint8Array(r, 0, t.length).set(t),\n\t\t\tthis.buffer = r,\n\t\t\tthis._byteLength = e\n\t\t}\n\t}\n},\nDataStream.prototype._trimAlloc = function() {\n\tvar t, e, i;\n\tthis._byteLength != this._buffer.byteLength && (t = new ArrayBuffer(this._byteLength), e = new Uint8Array(t), i = new Uint8Array(this._buffer, 0, e.length), e.set(i), this.buffer = t)\n},\nDataStream.BIG_ENDIAN = !1,\nDataStream.LITTLE_ENDIAN = !0,\nDataStream.prototype._byteLength = 0,\nObject.defineProperty(DataStream.prototype, "byteLength", {\n\tget: function() {\n\t\treturn this._byteLength - this._byteOffset\n\t}\n}),\nObject.defineProperty(DataStream.prototype, "buffer", {\n\tget: function() {\n\t\treturn this._trimAlloc(),\n\t\tthis._buffer\n\t},\n\tset: function(t) {\n\t\tthis._buffer = t,\n\t\tthis._dataView = new DataView(this._buffer, this._byteOffset),\n\t\tthis._byteLength = this._buffer.byteLength\n\t}\n}),\nObject.defineProperty(DataStream.prototype, "byteOffset", {\n\tget: function() {\n\t\treturn this._byteOffset\n\t},\n\tset: function(t) {\n\t\tthis._byteOffset = t,\n\t\tthis._dataView = new DataView(this._buffer, this._byteOffset),\n\t\tthis._byteLength = this._buffer.byteLength\n\t}\n}),\nObject.defineProperty(DataStream.prototype, "dataView", {\n\tget: function() {\n\t\treturn this._dataView\n\t},\n\tset: function(t) {\n\t\tthis._byteOffset = t.byteOffset,\n\t\tthis._buffer = t.buffer,\n\t\tthis._dataView = new DataView(this._buffer, this._byteOffset),\n\t\tthis._byteLength = this._byteOffset + t.byteLength\n\t}\n}),\nDataStream.prototype.seek = function(t) {\n\tt = Math.max(0, Math.min(this.byteLength, t));\n\tthis.position = isNaN(t) || !isFinite(t) ? 0 : t\n},\nDataStream.prototype.isEof = function() {\n\treturn this.position >= this._byteLength\n},\nDataStream.prototype.mapUint8Array = function(t) {\n\tthis._realloc( + t);\n\tvar e = new Uint8Array(this._buffer, this.byteOffset + this.position, t);\n\treturn this.position += +t,\n\te\n},\nDataStream.prototype.readInt32Array = function(t, e) {\n\tt = null == t ? this.byteLength - this.position / 4 : t;\n\tvar i = new Int32Array(t);\n\treturn DataStream.memcpy(i.buffer, 0, this.buffer, this.byteOffset + this.position, t * i.BYTES_PER_ELEMENT),\n\tDataStream.arrayToNative(i, null == e ? this.endianness: e),\n\tthis.position += i.byteLength,\n\ti\n},\nDataStream.prototype.readInt16Array = function(t, e) {\n\tt = null == t ? this.byteLength - this.position / 2 : t;\n\tvar i = new Int16Array(t);\n\treturn DataStream.memcpy(i.buffer, 0, this.buffer, this.byteOffset + this.position, t * i.BYTES_PER_ELEMENT),\n\tDataStream.arrayToNative(i, null == e ? this.endianness: e),\n\tthis.position += i.byteLength,\n\ti\n},\nDataStream.prototype.readInt8Array = function(t) {\n\tt = null == t ? this.byteLength - this.position: t;\n\tvar e = new Int8Array(t);\n\treturn DataStream.memcpy(e.buffer, 0, this.buffer, this.byteOffset + this.position, t * e.BYTES_PER_ELEMENT),\n\tthis.position += e.byteLength,\n\te\n},\nDataStream.prototype.readUint32Array = function(t, e) {\n\tt = null == t ? this.byteLength - this.position / 4 : t;\n\tvar i = new Uint32Array(t);\n\treturn DataStream.memcpy(i.buffer, 0, this.buffer, this.byteOffset + this.position, t * i.BYTES_PER_ELEMENT),\n\tDataStream.arrayToNative(i, null == e ? this.endianness: e),\n\tthis.position += i.byteLength,\n\ti\n},\nDataStream.prototype.readUint16Array = function(t, e) {\n\tt = null == t ? this.byteLength - this.position / 2 : t;\n\tvar i = new Uint16Array(t);\n\treturn DataStream.memcpy(i.buffer, 0, this.buffer, this.byteOffset + this.position, t * i.BYTES_PER_ELEMENT),\n\tDataStream.arrayToNative(i, null == e ? this.endianness: e),\n\tthis.position += i.byteLength,\n\ti\n},\nDataStream.prototype.readUint8Array = function(t) {\n\tt = null == t ? this.byteLength - this.position: t;\n\tvar e = new Uint8Array(t);\n\treturn DataStream.memcpy(e.buffer, 0, this.buffer, this.byteOffset + this.position, t * e.BYTES_PER_ELEMENT),\n\tthis.position += e.byteLength,\n\te\n},\nDataStream.prototype.readFloat64Array = function(t, e) {\n\tt = null == t ? this.byteLength - this.position / 8 : t;\n\tvar i = new Float64Array(t);\n\treturn DataStream.memcpy(i.buffer, 0, this.buffer, this.byteOffset + this.position, t * i.BYTES_PER_ELEMENT),\n\tDataStream.arrayToNative(i, null == e ? this.endianness: e),\n\tthis.position += i.byteLength,\n\ti\n},\nDataStream.prototype.readFloat32Array = function(t, e) {\n\tt = null == t ? this.byteLength - this.position / 4 : t;\n\tvar i = new Float32Array(t);\n\treturn DataStream.memcpy(i.buffer, 0, this.buffer, this.byteOffset + this.position, t * i.BYTES_PER_ELEMENT),\n\tDataStream.arrayToNative(i, null == e ? this.endianness: e),\n\tthis.position += i.byteLength,\n\ti\n},\nDataStream.prototype.readInt32 = function(t) {\n\tt = this._dataView.getInt32(this.position, null == t ? this.endianness: t);\n\treturn this.position += 4,\n\tt\n},\nDataStream.prototype.readInt16 = function(t) {\n\tt = this._dataView.getInt16(this.position, null == t ? this.endianness: t);\n\treturn this.position += 2,\n\tt\n},\nDataStream.prototype.readInt8 = function() {\n\tvar t = this._dataView.getInt8(this.position);\n\treturn this.position += 1,\n\tt\n},\nDataStream.prototype.readUint32 = function(t) {\n\tt = this._dataView.getUint32(this.position, null == t ? this.endianness: t);\n\treturn this.position += 4,\n\tt\n},\nDataStream.prototype.readUint16 = function(t) {\n\tt = this._dataView.getUint16(this.position, null == t ? this.endianness: t);\n\treturn this.position += 2,\n\tt\n},\nDataStream.prototype.readUint8 = function() {\n\tvar t = this._dataView.getUint8(this.position);\n\treturn this.position += 1,\n\tt\n},\nDataStream.prototype.readFloat32 = function(t) {\n\tt = this._dataView.getFloat32(this.position, null == t ? this.endianness: t);\n\treturn this.position += 4,\n\tt\n},\nDataStream.prototype.readFloat64 = function(t) {\n\tt = this._dataView.getFloat64(this.position, null == t ? this.endianness: t);\n\treturn this.position += 8,\n\tt\n},\nDataStream.endianness = 0 < new Int8Array(new Int16Array([1]).buffer)[0],\nDataStream.memcpy = function(t, e, i, r, s) {\n\te = new Uint8Array(t, e, s),\n\ts = new Uint8Array(i, r, s);\n\te.set(s)\n},\nDataStream.arrayToNative = function(t, e) {\n\treturn e == this.endianness ? t: this.flipArrayEndianness(t)\n},\nDataStream.nativeToEndian = function(t, e) {\n\treturn this.endianness == e ? t: this.flipArrayEndianness(t)\n},\nDataStream.flipArrayEndianness = function(t) {\n\tfor (var e = new Uint8Array(t.buffer, t.byteOffset, t.byteLength), i = 0; i < t.byteLength; i += t.BYTES_PER_ELEMENT) for (var r = i + t.BYTES_PER_ELEMENT - 1,\n\ts = i; s < r; r--, s++) {\n\t\tvar a = e[s];\n\t\te[s] = e[r],\n\t\te[r] = a\n\t}\n\treturn t\n},\nDataStream.prototype.failurePosition = 0,\nString.fromCharCodeUint8 = function(t) {\n\tfor (var e = [], i = 0; i < t.length; i++) e[i] = t[i];\n\treturn String.fromCharCode.apply(null, e)\n},\nDataStream.prototype.readString = function(t, e) {\n\treturn null == e || "ASCII" == e ? String.fromCharCodeUint8.apply(null, [this.mapUint8Array(null == t ? this.byteLength - this.position: t)]) : new TextDecoder(e).decode(this.mapUint8Array(t))\n},\nDataStream.prototype.readCString = function(t) {\n\tvar e = this.byteLength - this.position,\n\ti = new Uint8Array(this._buffer, this._byteOffset + this.position),\n\tr = e;\n\tnull != t && (r = Math.min(t, e));\n\tfor (var s = 0; s < r && 0 !== i[s]; s++);\n\tvar a = String.fromCharCodeUint8.apply(null, [this.mapUint8Array(s)]);\n\treturn null != t ? this.position += r - s: s != e && (this.position += 1),\n\ta\n};\nvar MAX_SIZE = Math.pow(2, 32);\nDataStream.prototype.readInt64 = function() {\n\treturn this.readInt32() * MAX_SIZE + this.readUint32()\n},\nDataStream.prototype.readUint64 = function() {\n\treturn this.readUint32() * MAX_SIZE + this.readUint32()\n},\nDataStream.prototype.readInt64 = function() {\n\treturn this.readUint32() * MAX_SIZE + this.readUint32()\n},\nDataStream.prototype.readUint24 = function() {\n\treturn (this.readUint8() << 16) + (this.readUint8() << 8) + this.readUint8()\n},\n"undefined" != typeof exports && (exports.DataStream = DataStream),\nDataStream.prototype.save = function(t) {\n\tvar e = new Blob([this.buffer]);\n\tif (!window.URL || !URL.createObjectURL) throw "DataStream.save: Can\'t create object URL.";\n\tvar i = window.URL.createObjectURL(e),\n\te = document.createElement("a");\n\tdocument.body.appendChild(e),\n\te.setAttribute("href", i),\n\te.setAttribute("download", t),\n\te.setAttribute("target", "_self"),\n\te.click(),\n\twindow.URL.revokeObjectURL(i)\n},\nDataStream.prototype._dynamicSize = !0,\nObject.defineProperty(DataStream.prototype, "dynamicSize", {\n\tget: function() {\n\t\treturn this._dynamicSize\n\t},\n\tset: function(t) {\n\t\tt || this._trimAlloc(),\n\t\tthis._dynamicSize = t\n\t}\n}),\nDataStream.prototype.shift = function(t) {\n\tvar e = new ArrayBuffer(this._byteLength - t),\n\ti = new Uint8Array(e),\n\tr = new Uint8Array(this._buffer, t, i.length);\n\ti.set(r),\n\tthis.buffer = e,\n\tthis.position -= t\n},\nDataStream.prototype.writeInt32Array = function(t, e) {\n\tif (this._realloc(4 * t.length), t instanceof Int32Array && this.byteOffset + this.position % t.BYTES_PER_ELEMENT === 0) DataStream.memcpy(this._buffer, this.byteOffset + this.position, t.buffer, 0, t.byteLength),\n\tthis.mapInt32Array(t.length, e);\n\telse for (var i = 0; i < t.length; i++) this.writeInt32(t[i], e)\n},\nDataStream.prototype.writeInt16Array = function(t, e) {\n\tif (this._realloc(2 * t.length), t instanceof Int16Array && this.byteOffset + this.position % t.BYTES_PER_ELEMENT === 0) DataStream.memcpy(this._buffer, this.byteOffset + this.position, t.buffer, 0, t.byteLength),\n\tthis.mapInt16Array(t.length, e);\n\telse for (var i = 0; i < t.length; i++) this.writeInt16(t[i], e)\n},\nDataStream.prototype.writeInt8Array = function(t) {\n\tif (this._realloc( + t.length), t instanceof Int8Array && this.byteOffset + this.position % t.BYTES_PER_ELEMENT === 0) DataStream.memcpy(this._buffer, this.byteOffset + this.position, t.buffer, 0, t.byteLength),\n\tthis.mapInt8Array(t.length);\n\telse for (var e = 0; e < t.length; e++) this.writeInt8(t[e])\n},\nDataStream.prototype.writeUint32Array = function(t, e) {\n\tif (this._realloc(4 * t.length), t instanceof Uint32Array && this.byteOffset + this.position % t.BYTES_PER_ELEMENT === 0) DataStream.memcpy(this._buffer, this.byteOffset + this.position, t.buffer, 0, t.byteLength),\n\tthis.mapUint32Array(t.length, e);\n\telse for (var i = 0; i < t.length; i++) this.writeUint32(t[i], e)\n},\nDataStream.prototype.writeUint16Array = function(t, e) {\n\tif (this._realloc(2 * t.length), t instanceof Uint16Array && this.byteOffset + this.position % t.BYTES_PER_ELEMENT === 0) DataStream.memcpy(this._buffer, this.byteOffset + this.position, t.buffer, 0, t.byteLength),\n\tthis.mapUint16Array(t.length, e);\n\telse for (var i = 0; i < t.length; i++) this.writeUint16(t[i], e)\n},\nDataStream.prototype.writeUint8Array = function(t) {\n\tif (this._realloc( + t.length), t instanceof Uint8Array && this.byteOffset + this.position % t.BYTES_PER_ELEMENT === 0) DataStream.memcpy(this._buffer, this.byteOffset + this.position, t.buffer, 0, t.byteLength),\n\tthis.mapUint8Array(t.length);\n\telse for (var e = 0; e < t.length; e++) this.writeUint8(t[e])\n},\nDataStream.prototype.writeFloat64Array = function(t, e) {\n\tif (this._realloc(8 * t.length), t instanceof Float64Array && this.byteOffset + this.position % t.BYTES_PER_ELEMENT === 0) DataStream.memcpy(this._buffer, this.byteOffset + this.position, t.buffer, 0, t.byteLength),\n\tthis.mapFloat64Array(t.length, e);\n\telse for (var i = 0; i < t.length; i++) this.writeFloat64(t[i], e)\n},\nDataStream.prototype.writeFloat32Array = function(t, e) {\n\tif (this._realloc(4 * t.length), t instanceof Float32Array && this.byteOffset + this.position % t.BYTES_PER_ELEMENT === 0) DataStream.memcpy(this._buffer, this.byteOffset + this.position, t.buffer, 0, t.byteLength),\n\tthis.mapFloat32Array(t.length, e);\n\telse for (var i = 0; i < t.length; i++) this.writeFloat32(t[i], e)\n},\nDataStream.prototype.writeInt32 = function(t, e) {\n\tthis._realloc(4),\n\tthis._dataView.setInt32(this.position, t, null == e ? this.endianness: e),\n\tthis.position += 4\n},\nDataStream.prototype.writeInt16 = function(t, e) {\n\tthis._realloc(2),\n\tthis._dataView.setInt16(this.position, t, null == e ? this.endianness: e),\n\tthis.position += 2\n},\nDataStream.prototype.writeInt8 = function(t) {\n\tthis._realloc(1),\n\tthis._dataView.setInt8(this.position, t),\n\tthis.position += 1\n},\nDataStream.prototype.writeUint32 = function(t, e) {\n\tthis._realloc(4),\n\tthis._dataView.setUint32(this.position, t, null == e ? this.endianness: e),\n\tthis.position += 4\n},\nDataStream.prototype.writeUint16 = function(t, e) {\n\tthis._realloc(2),\n\tthis._dataView.setUint16(this.position, t, null == e ? this.endianness: e),\n\tthis.position += 2\n},\nDataStream.prototype.writeUint8 = function(t) {\n\tthis._realloc(1),\n\tthis._dataView.setUint8(this.position, t),\n\tthis.position += 1\n},\nDataStream.prototype.writeFloat32 = function(t, e) {\n\tthis._realloc(4),\n\tthis._dataView.setFloat32(this.position, t, null == e ? this.endianness: e),\n\tthis.position += 4\n},\nDataStream.prototype.writeFloat64 = function(t, e) {\n\tthis._realloc(8),\n\tthis._dataView.setFloat64(this.position, t, null == e ? this.endianness: e),\n\tthis.position += 8\n},\nDataStream.prototype.writeUCS2String = function(t, e, i) {\n\tnull == i && (i = t.length);\n\tfor (var r = 0; r < t.length && r < i; r++) this.writeUint16(t.charCodeAt(r), e);\n\tfor (; r < i; r++) this.writeUint16(0)\n},\nDataStream.prototype.writeString = function(t, e, i) {\n\tvar r = 0;\n\tif (null == e || "ASCII" == e) if (null != i) {\n\t\tfor (var s = Math.min(t.length, i), r = 0; r < s; r++) this.writeUint8(t.charCodeAt(r));\n\t\tfor (; r < i; r++) this.writeUint8(0)\n\t} else for (r = 0; r < t.length; r++) this.writeUint8(t.charCodeAt(r));\n\telse this.writeUint8Array(new TextEncoder(e).encode(t.substring(0, i)))\n},\nDataStream.prototype.writeCString = function(t, e) {\n\tvar i = 0;\n\tif (null != e) {\n\t\tfor (var r = Math.min(t.length, e), i = 0; i < r; i++) this.writeUint8(t.charCodeAt(i));\n\t\tfor (; i < e; i++) this.writeUint8(0)\n\t} else {\n\t\tfor (i = 0; i < t.length; i++) this.writeUint8(t.charCodeAt(i));\n\t\tthis.writeUint8(0)\n\t}\n},\nDataStream.prototype.writeStruct = function(t, e) {\n\tfor (var i = 0; i < t.length; i += 2) {\n\t\tvar r = t[i + 1];\n\t\tthis.writeType(r, e[t[i]], e)\n\t}\n},\nDataStream.prototype.writeType = function(t, e, i) {\n\tvar r;\n\tif ("function" == typeof t) return t(this, e);\n\tif ("object" == typeof t && !(t instanceof Array)) return t.set(this, e, i);\n\tvar s = null,\n\ta = "ASCII",\n\ti = this.position;\n\tswitch ("string" == typeof t && /:/.test(t) && (t = (r = t.split(":"))[0], s = parseInt(r[1])), "string" == typeof t && /,/.test(t) && (t = (r = t.split(","))[0], a = parseInt(r[1])), t) {\n\tcase "uint8":\n\t\tthis.writeUint8(e);\n\t\tbreak;\n\tcase "int8":\n\t\tthis.writeInt8(e);\n\t\tbreak;\n\tcase "uint16":\n\t\tthis.writeUint16(e, this.endianness);\n\t\tbreak;\n\tcase "int16":\n\t\tthis.writeInt16(e, this.endianness);\n\t\tbreak;\n\tcase "uint32":\n\t\tthis.writeUint32(e, this.endianness);\n\t\tbreak;\n\tcase "int32":\n\t\tthis.writeInt32(e, this.endianness);\n\t\tbreak;\n\tcase "float32":\n\t\tthis.writeFloat32(e, this.endianness);\n\t\tbreak;\n\tcase "float64":\n\t\tthis.writeFloat64(e, this.endianness);\n\t\tbreak;\n\tcase "uint16be":\n\t\tthis.writeUint16(e, DataStream.BIG_ENDIAN);\n\t\tbreak;\n\tcase "int16be":\n\t\tthis.writeInt16(e, DataStream.BIG_ENDIAN);\n\t\tbreak;\n\tcase "uint32be":\n\t\tthis.writeUint32(e, DataStream.BIG_ENDIAN);\n\t\tbreak;\n\tcase "int32be":\n\t\tthis.writeInt32(e, DataStream.BIG_ENDIAN);\n\t\tbreak;\n\tcase "float32be":\n\t\tthis.writeFloat32(e, DataStream.BIG_ENDIAN);\n\t\tbreak;\n\tcase "float64be":\n\t\tthis.writeFloat64(e, DataStream.BIG_ENDIAN);\n\t\tbreak;\n\tcase "uint16le":\n\t\tthis.writeUint16(e, DataStream.LITTLE_ENDIAN);\n\t\tbreak;\n\tcase "int16le":\n\t\tthis.writeInt16(e, DataStream.LITTLE_ENDIAN);\n\t\tbreak;\n\tcase "uint32le":\n\t\tthis.writeUint32(e, DataStream.LITTLE_ENDIAN);\n\t\tbreak;\n\tcase "int32le":\n\t\tthis.writeInt32(e, DataStream.LITTLE_ENDIAN);\n\t\tbreak;\n\tcase "float32le":\n\t\tthis.writeFloat32(e, DataStream.LITTLE_ENDIAN);\n\t\tbreak;\n\tcase "float64le":\n\t\tthis.writeFloat64(e, DataStream.LITTLE_ENDIAN);\n\t\tbreak;\n\tcase "cstring":\n\t\tthis.writeCString(e, s);\n\t\tbreak;\n\tcase "string":\n\t\tthis.writeString(e, a, s);\n\t\tbreak;\n\tcase "u16string":\n\t\tthis.writeUCS2String(e, this.endianness, s);\n\t\tbreak;\n\tcase "u16stringle":\n\t\tthis.writeUCS2String(e, DataStream.LITTLE_ENDIAN, s);\n\t\tbreak;\n\tcase "u16stringbe":\n\t\tthis.writeUCS2String(e, DataStream.BIG_ENDIAN, s);\n\t\tbreak;\n\tdefault:\n\t\tif (3 == t.length) {\n\t\t\tfor (var n = t[1], o = 0; o < e.length; o++) this.writeType(n, e[o]);\n\t\t\tbreak\n\t\t}\n\t\tthis.writeStruct(t, e)\n\t}\n\tnull != s && (this.position = i, this._realloc(s), this.position = i + s)\n},\nDataStream.prototype.writeUint64 = function(t) {\n\tvar e = Math.floor(t / MAX_SIZE);\n\tthis.writeUint32(e),\n\tthis.writeUint32(4294967295 & t)\n},\nDataStream.prototype.writeUint24 = function(t) {\n\tthis.writeUint8((16711680 & t) >> 16),\n\tthis.writeUint8((65280 & t) >> 8),\n\tthis.writeUint8(255 & t)\n},\nDataStream.prototype.adjustUint32 = function(t, e) {\n\tvar i = this.position;\n\tthis.seek(t),\n\tthis.writeUint32(e),\n\tthis.seek(i)\n},\nDataStream.prototype.mapInt32Array = function(t, e) {\n\tthis._realloc(4 * t);\n\tvar i = new Int32Array(this._buffer, this.byteOffset + this.position, t);\n\treturn DataStream.arrayToNative(i, null == e ? this.endianness: e),\n\tthis.position += 4 * t,\n\ti\n},\nDataStream.prototype.mapInt16Array = function(t, e) {\n\tthis._realloc(2 * t);\n\tvar i = new Int16Array(this._buffer, this.byteOffset + this.position, t);\n\treturn DataStream.arrayToNative(i, null == e ? this.endianness: e),\n\tthis.position += 2 * t,\n\ti\n},\nDataStream.prototype.mapInt8Array = function(t) {\n\tthis._realloc( + t);\n\tvar e = new Int8Array(this._buffer, this.byteOffset + this.position, t);\n\treturn this.position += +t,\n\te\n},\nDataStream.prototype.mapUint32Array = function(t, e) {\n\tthis._realloc(4 * t);\n\tvar i = new Uint32Array(this._buffer, this.byteOffset + this.position, t);\n\treturn DataStream.arrayToNative(i, null == e ? this.endianness: e),\n\tthis.position += 4 * t,\n\ti\n},\nDataStream.prototype.mapUint16Array = function(t, e) {\n\tthis._realloc(2 * t);\n\tvar i = new Uint16Array(this._buffer, this.byteOffset + this.position, t);\n\treturn DataStream.arrayToNative(i, null == e ? this.endianness: e),\n\tthis.position += 2 * t,\n\ti\n},\nDataStream.prototype.mapFloat64Array = function(t, e) {\n\tthis._realloc(8 * t);\n\tvar i = new Float64Array(this._buffer, this.byteOffset + this.position, t);\n\treturn DataStream.arrayToNative(i, null == e ? this.endianness: e),\n\tthis.position += 8 * t,\n\ti\n},\nDataStream.prototype.mapFloat32Array = function(t, e) {\n\tthis._realloc(4 * t);\n\tvar i = new Float32Array(this._buffer, this.byteOffset + this.position, t);\n\treturn DataStream.arrayToNative(i, null == e ? this.endianness: e),\n\tthis.position += 4 * t,\n\ti\n};\nvar MultiBufferStream = function(t) {\n\tthis.buffers = [],\n\tthis.bufferIndex = -1,\n\tt && (this.insertBuffer(t), this.bufferIndex = 0)\n};\nMultiBufferStream.prototype = new DataStream(new ArrayBuffer, 0, DataStream.BIG_ENDIAN),\nMultiBufferStream.prototype.initialized = function() {\n\tvar t;\n\treturn - 1 < this.bufferIndex || (0 < this.buffers.length ? 0 === (t = this.buffers[0]).fileStart ? (this.buffer = t, this.bufferIndex = 0, Log.debug("MultiBufferStream", "Stream ready for parsing"), !0) : (Log.warn("MultiBufferStream", "The first buffer should have a fileStart of 0"), this.logBufferLevel(), !1) : (Log.warn("MultiBufferStream", "No buffer to start parsing from"), this.logBufferLevel(), !1))\n},\nArrayBuffer.concat = function(t, e) {\n\tLog.debug("ArrayBuffer", "Trying to create a new buffer of size: " + (t.byteLength + e.byteLength));\n\tvar i = new Uint8Array(t.byteLength + e.byteLength);\n\treturn i.set(new Uint8Array(t), 0),\n\ti.set(new Uint8Array(e), t.byteLength),\n\ti.buffer\n},\nMultiBufferStream.prototype.reduceBuffer = function(t, e, i) {\n\tvar r = new Uint8Array(i);\n\treturn r.set(new Uint8Array(t, e, i)),\n\tr.buffer.fileStart = t.fileStart + e,\n\tr.buffer.usedBytes = 0,\n\tr.buffer\n},\nMultiBufferStream.prototype.insertBuffer = function(t) {\n\tfor (var e = !0,\n\ti = 0; i < this.buffers.length; i++) {\n\t\tvar r = this.buffers[i];\n\t\tif (t.fileStart <= r.fileStart) {\n\t\t\tif (t.fileStart === r.fileStart) {\n\t\t\t\tif (t.byteLength > r.byteLength) {\n\t\t\t\t\tthis.buffers.splice(i, 1),\n\t\t\t\t\ti--;\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\t\t\t\tLog.warn("MultiBufferStream", "Buffer (fileStart: " + t.fileStart + " - Length: " + t.byteLength + ") already appended, ignoring")\n\t\t\t} else t.fileStart + t.byteLength <= r.fileStart || (t = this.reduceBuffer(t, 0, r.fileStart - t.fileStart)),\n\t\t\tLog.debug("MultiBufferStream", "Appending new buffer (fileStart: " + t.fileStart + " - Length: " + t.byteLength + ")"),\n\t\t\tthis.buffers.splice(i, 0, t),\n\t\t\t0 === i && (this.buffer = t);\n\t\t\te = !1;\n\t\t\tbreak\n\t\t}\n\t\tif (t.fileStart < r.fileStart + r.byteLength) {\n\t\t\tvar s = r.fileStart + r.byteLength - t.fileStart,\n\t\t\tr = t.byteLength - s;\n\t\t\tif (! (0 < r)) {\n\t\t\t\te = !1;\n\t\t\t\tbreak\n\t\t\t}\n\t\t\tt = this.reduceBuffer(t, s, r)\n\t\t}\n\t}\n\te && (Log.debug("MultiBufferStream", "Appending new buffer (fileStart: " + t.fileStart + " - Length: " + t.byteLength + ")"), this.buffers.push(t), 0 === i && (this.buffer = t))\n},\nMultiBufferStream.prototype.logBufferLevel = function(t) {\n\tfor (var e, i, r = [], s = "", a = 0, n = 0, o = 0; o < this.buffers.length; o++) e = this.buffers[o],\n\t0 === o ? (i = {},\n\tr.push(i), i.start = e.fileStart, i.end = e.fileStart + e.byteLength, s += "[" + i.start + "-") : i.end === e.fileStart ? i.end = e.fileStart + e.byteLength: ((i = {}).start = e.fileStart, s += r[r.length - 1].end - 1 + "], [" + i.start + "-", i.end = e.fileStart + e.byteLength, r.push(i)),\n\ta += e.usedBytes,\n\tn += e.byteLength;\n\t0 < r.length && (s += i.end - 1 + "]");\n\tt = t ? Log.info: Log.debug;\n\t0 === this.buffers.length ? t("MultiBufferStream", "No more buffer in memory") : t("MultiBufferStream", this.buffers.length + " stored buffer(s) (" + a + "/" + n + " bytes), continuous ranges: " + s)\n},\nMultiBufferStream.prototype.cleanBuffers = function() {\n\tfor (var t, e = 0; e < this.buffers.length; e++)(t = this.buffers[e]).usedBytes === t.byteLength && (Log.debug("MultiBufferStream", "Removing buffer #" + e), this.buffers.splice(e, 1), e--)\n},\nMultiBufferStream.prototype.mergeNextBuffer = function() {\n\tvar t;\n\tif (this.bufferIndex + 1 < this.buffers.length) {\n\t\tif ((t = this.buffers[this.bufferIndex + 1]).fileStart !== this.buffer.fileStart + this.buffer.byteLength) return ! 1;\n\t\tvar e = this.buffer.byteLength,\n\t\ti = this.buffer.usedBytes,\n\t\tr = this.buffer.fileStart;\n\t\treturn this.buffers[this.bufferIndex] = ArrayBuffer.concat(this.buffer, t),\n\t\tthis.buffer = this.buffers[this.bufferIndex],\n\t\tthis.buffers.splice(this.bufferIndex + 1, 1),\n\t\tthis.buffer.usedBytes = i,\n\t\tthis.buffer.fileStart = r,\n\t\tLog.debug("ISOFile", "Concatenating buffer for box parsing (length: " + e + "->" + this.buffer.byteLength + ")"),\n\t\t!0\n\t}\n\treturn ! 1\n},\nMultiBufferStream.prototype.findPosition = function(t, e, i) {\n\tfor (var r = null,\n\ts = -1,\n\ta = !0 === t ? 0 : this.bufferIndex; a < this.buffers.length && (r = this.buffers[a]).fileStart <= e;) s = a,\n\ti && (r.fileStart + r.byteLength <= e ? r.usedBytes = r.byteLength: r.usedBytes = e - r.fileStart, this.logBufferLevel()),\n\ta++;\n\treturn - 1 !== s && (r = this.buffers[s]).fileStart + r.byteLength >= e ? (Log.debug("MultiBufferStream", "Found position in existing buffer #" + s), s) : -1\n},\nMultiBufferStream.prototype.findEndContiguousBuf = function(t) {\n\tvar e, i, t = void 0 !== t ? t: this.bufferIndex,\n\tr = this.buffers[t];\n\tif (this.buffers.length > t + 1) for (e = t + 1; e < this.buffers.length && (i = this.buffers[e]).fileStart === r.fileStart + r.byteLength; e++) r = i;\n\treturn r.fileStart + r.byteLength\n},\nMultiBufferStream.prototype.getEndFilePositionAfter = function(t) {\n\tvar e = this.findPosition(!0, t, !1);\n\treturn - 1 !== e ? this.findEndContiguousBuf(e) : t\n},\nMultiBufferStream.prototype.addUsedBytes = function(t) {\n\tthis.buffer.usedBytes += t,\n\tthis.logBufferLevel()\n},\nMultiBufferStream.prototype.setAllUsedBytes = function() {\n\tthis.buffer.usedBytes = this.buffer.byteLength,\n\tthis.logBufferLevel()\n},\nMultiBufferStream.prototype.seek = function(t, e, i) {\n\ti = this.findPosition(e, t, i);\n\treturn - 1 !== i ? (this.buffer = this.buffers[i], this.bufferIndex = i, this.position = t - this.buffer.fileStart, Log.debug("MultiBufferStream", "Repositioning parser at buffer position: " + this.position), !0) : (Log.debug("MultiBufferStream", "Position " + t + " not found in buffered data"), !1)\n},\nMultiBufferStream.prototype.getPosition = function() {\n\tif (-1 === this.bufferIndex || null === this.buffers[this.bufferIndex]) throw "Error accessing position in the MultiBufferStream";\n\treturn this.buffers[this.bufferIndex].fileStart + this.position\n},\nMultiBufferStream.prototype.getLength = function() {\n\treturn this.byteLength\n},\nMultiBufferStream.prototype.getEndPosition = function() {\n\tif (-1 === this.bufferIndex || null === this.buffers[this.bufferIndex]) throw "Error accessing position in the MultiBufferStream";\n\treturn this.buffers[this.bufferIndex].fileStart + this.byteLength\n},\n"undefined" != typeof exports && (exports.MultiBufferStream = MultiBufferStream);\nvar MPEG4DescriptorParser = function() {\n\tvar s = [];\n\ts[3] = "ES_Descriptor",\n\ts[4] = "DecoderConfigDescriptor",\n\ts[5] = "DecoderSpecificInfo",\n\ts[6] = "SLConfigDescriptor",\n\tthis.getDescriptorName = function(t) {\n\t\treturn s[t]\n\t};\n\tvar r = this,\n\ta = {};\n\treturn this.parseOneDescriptor = function(t) {\n\t\tvar e, i = 0,\n\t\tr = t.readUint8();\n\t\tfor (e = t.readUint8(), 0; 128 & e;) i = (i << 7) + (127 & e),\n\t\te = t.readUint8(),\n\t\t0;\n\t\treturn i = (i << 7) + (127 & e),\n\t\tLog.debug("MPEG4DescriptorParser", "Found " + (s[r] || "Descriptor " + r) + ", size " + i + " at position " + t.getPosition()),\n\t\t(r = new(s[r] ? a[s[r]] : a.Descriptor)(i)).parse(t),\n\t\tr\n\t},\n\ta.Descriptor = function(t, e) {\n\t\tthis.tag = t,\n\t\tthis.size = e,\n\t\tthis.descs = []\n\t},\n\ta.Descriptor.prototype.parse = function(t) {\n\t\tthis.data = t.readUint8Array(this.size)\n\t},\n\ta.Descriptor.prototype.findDescriptor = function(t) {\n\t\tfor (var e = 0; e < this.descs.length; e++) if (this.descs[e].tag == t) return this.descs[e];\n\t\treturn null\n\t},\n\ta.Descriptor.prototype.parseRemainingDescriptors = function(t) {\n\t\tfor (var e = t.position; t.position < e + this.size;) {\n\t\t\tvar i = r.parseOneDescriptor(t);\n\t\t\tthis.descs.push(i)\n\t\t}\n\t},\n\ta.ES_Descriptor = function(t) {\n\t\ta.Descriptor.call(this, 3, t)\n\t},\n\ta.ES_Descriptor.prototype = new a.Descriptor,\n\ta.ES_Descriptor.prototype.parse = function(t) {\n\t\tvar e;\n\t\tthis.ES_ID = t.readUint16(),\n\t\tthis.flags = t.readUint8(),\n\t\tthis.size -= 3,\n\t\t128 & this.flags ? (this.dependsOn_ES_ID = t.readUint16(), this.size -= 2) : this.dependsOn_ES_ID = 0,\n\t\t64 & this.flags ? (e = t.readUint8(), this.URL = t.readString(e), this.size -= e + 1) : this.URL = "",\n\t\t32 & this.flags ? (this.OCR_ES_ID = t.readUint16(), this.size -= 2) : this.OCR_ES_ID = 0,\n\t\tthis.parseRemainingDescriptors(t)\n\t},\n\ta.ES_Descriptor.prototype.getOTI = function(t) {\n\t\tvar e = this.findDescriptor(4);\n\t\treturn e ? e.oti: 0\n\t},\n\ta.ES_Descriptor.prototype.getAudioConfig = function(t) {\n\t\tvar e = this.findDescriptor(4);\n\t\tif (!e) return null;\n\t\tvar i = e.findDescriptor(5);\n\t\tif (i && i.data) {\n\t\t\te = (248 & i.data[0]) >> 3;\n\t\t\treturn 31 === e && 2 <= i.data.length && (e = 32 + ((7 & i.data[0]) << 3) + ((224 & i.data[1]) >> 5)),\n\t\t\te\n\t\t}\n\t\treturn null\n\t},\n\ta.DecoderConfigDescriptor = function(t) {\n\t\ta.Descriptor.call(this, 4, t)\n\t},\n\ta.DecoderConfigDescriptor.prototype = new a.Descriptor,\n\ta.DecoderConfigDescriptor.prototype.parse = function(t) {\n\t\tthis.oti = t.readUint8(),\n\t\tthis.streamType = t.readUint8(),\n\t\tthis.upStream = 0 != (this.streamType >> 1 & 1),\n\t\tthis.streamType = this.streamType >>> 2,\n\t\tthis.bufferSize = t.readUint24(),\n\t\tthis.maxBitrate = t.readUint32(),\n\t\tthis.avgBitrate = t.readUint32(),\n\t\tthis.size -= 13,\n\t\tthis.parseRemainingDescriptors(t)\n\t},\n\ta.DecoderSpecificInfo = function(t) {\n\t\ta.Descriptor.call(this, 5, t)\n\t},\n\ta.DecoderSpecificInfo.prototype = new a.Descriptor,\n\ta.SLConfigDescriptor = function(t) {\n\t\ta.Descriptor.call(this, 6, t)\n\t},\n\ta.SLConfigDescriptor.prototype = new a.Descriptor,\n\tthis\n};\n"undefined" != typeof exports && (exports.MPEG4DescriptorParser = MPEG4DescriptorParser);\nvar BoxParser = {\n\tERR_INVALID_DATA: -1,\n\tERR_NOT_ENOUGH_DATA: 0,\n\tOK: 1,\n\tBASIC_BOXES: [{\n\t\ttype: "mdat",\n\t\tname: "MediaDataBox"\n\t},\n\t{\n\t\ttype: "idat",\n\t\tname: "ItemDataBox"\n\t},\n\t{\n\t\ttype: "free",\n\t\tname: "FreeSpaceBox"\n\t},\n\t{\n\t\ttype: "skip",\n\t\tname: "FreeSpaceBox"\n\t},\n\t{\n\t\ttype: "meco",\n\t\tname: "AdditionalMetadataContainerBox"\n\t},\n\t{\n\t\ttype: "strk",\n\t\tname: "SubTrackBox"\n\t}],\n\tFULL_BOXES: [{\n\t\ttype: "hmhd",\n\t\tname: "HintMediaHeaderBox"\n\t},\n\t{\n\t\ttype: "nmhd",\n\t\tname: "NullMediaHeaderBox"\n\t},\n\t{\n\t\ttype: "iods",\n\t\tname: "ObjectDescriptorBox"\n\t},\n\t{\n\t\ttype: "xml ",\n\t\tname: "XMLBox"\n\t},\n\t{\n\t\ttype: "bxml",\n\t\tname: "BinaryXMLBox"\n\t},\n\t{\n\t\ttype: "ipro",\n\t\tname: "ItemProtectionBox"\n\t},\n\t{\n\t\ttype: "mere",\n\t\tname: "MetaboxRelationBox"\n\t}],\n\tCONTAINER_BOXES: [[{\n\t\ttype: "moov",\n\t\tname: "CompressedMovieBox"\n\t},\n\t["trak", "pssh"]], [{\n\t\ttype: "trak",\n\t\tname: "TrackBox"\n\t}], [{\n\t\ttype: "edts",\n\t\tname: "EditBox"\n\t}], [{\n\t\ttype: "mdia",\n\t\tname: "MediaBox"\n\t}], [{\n\t\ttype: "minf",\n\t\tname: "MediaInformationBox"\n\t}], [{\n\t\ttype: "dinf",\n\t\tname: "DataInformationBox"\n\t}], [{\n\t\ttype: "stbl",\n\t\tname: "SampleTableBox"\n\t},\n\t["sgpd", "sbgp"]], [{\n\t\ttype: "mvex",\n\t\tname: "MovieExtendsBox"\n\t},\n\t["trex"]], [{\n\t\ttype: "moof",\n\t\tname: "CompressedMovieFragmentBox"\n\t},\n\t["traf"]], [{\n\t\ttype: "traf",\n\t\tname: "TrackFragmentBox"\n\t},\n\t["trun", "sgpd", "sbgp"]], [{\n\t\ttype: "vttc",\n\t\tname: "VTTCueBox"\n\t}], [{\n\t\ttype: "tref",\n\t\tname: "TrackReferenceBox"\n\t}], [{\n\t\ttype: "iref",\n\t\tname: "ItemReferenceBox"\n\t}], [{\n\t\ttype: "mfra",\n\t\tname: "MovieFragmentRandomAccessBox"\n\t},\n\t["tfra"]], [{\n\t\ttype: "meco",\n\t\tname: "AdditionalMetadataContainerBox"\n\t}], [{\n\t\ttype: "hnti",\n\t\tname: "trackhintinformation"\n\t}], [{\n\t\ttype: "hinf",\n\t\tname: "hintstatisticsbox"\n\t}], [{\n\t\ttype: "strk",\n\t\tname: "SubTrackBox"\n\t}], [{\n\t\ttype: "strd",\n\t\tname: "SubTrackDefinitionBox"\n\t}], [{\n\t\ttype: "sinf",\n\t\tname: "ProtectionSchemeInfoBox"\n\t}], [{\n\t\ttype: "rinf",\n\t\tname: "RestrictedSchemeInfoBox"\n\t}], [{\n\t\ttype: "schi",\n\t\tname: "SchemeInformationBox"\n\t}], [{\n\t\ttype: "trgr",\n\t\tname: "TrackGroupBox"\n\t}], [{\n\t\ttype: "udta",\n\t\tname: "UserDataBox"\n\t},\n\t["kind"]], [{\n\t\ttype: "iprp",\n\t\tname: "ItemPropertiesBox"\n\t},\n\t["ipma"]], [{\n\t\ttype: "ipco",\n\t\tname: "ItemPropertyContainerBox"\n\t}], [{\n\t\ttype: "grpl",\n\t\tname: "GroupsListBox"\n\t}], [{\n\t\ttype: "j2kH",\n\t\tname: "J2KHeaderInfoBox"\n\t}], [{\n\t\ttype: "etyp",\n\t\tname: "ExtendedTypeBox"\n\t},\n\t["tyco"]]],\n\tboxCodes: [],\n\tfullBoxCodes: [],\n\tcontainerBoxCodes: [],\n\tsampleEntryCodes: {},\n\tsampleGroupEntryCodes: [],\n\ttrackGroupTypes: [],\n\tUUIDBoxes: {},\n\tUUIDs: [],\n\tinitialize: function() {\n\t\tBoxParser.FullBox.prototype = new BoxParser.Box,\n\t\tBoxParser.ContainerBox.prototype = new BoxParser.Box,\n\t\tBoxParser.SampleEntry.prototype = new BoxParser.Box,\n\t\tBoxParser.TrackGroupTypeBox.prototype = new BoxParser.FullBox,\n\t\tBoxParser.BASIC_BOXES.forEach(function(t) {\n\t\t\tBoxParser.createBoxCtor(t.type, t.name)\n\t\t}),\n\t\tBoxParser.FULL_BOXES.forEach(function(t) {\n\t\t\tBoxParser.createFullBoxCtor(t.type, t.name)\n\t\t}),\n\t\tBoxParser.CONTAINER_BOXES.forEach(function(t) {\n\t\t\tBoxParser.createContainerBoxCtor(t[0].type, t[0].name, null, t[1])\n\t\t})\n\t},\n\tBox: function(t, e, i, r) {\n\t\tthis.type = t,\n\t\tthis.box_name = i,\n\t\tthis.size = e,\n\t\tthis.uuid = r\n\t},\n\tFullBox: function(t, e, i, r) {\n\t\tBoxParser.Box.call(this, t, e, i, r),\n\t\tthis.flags = 0,\n\t\tthis.version = 0\n\t},\n\tContainerBox: function(t, e, i, r) {\n\t\tBoxParser.Box.call(this, t, e, i, r),\n\t\tthis.boxes = []\n\t},\n\tSampleEntry: function(t, e, i, r) {\n\t\tBoxParser.ContainerBox.call(this, t, e),\n\t\tthis.hdr_size = i,\n\t\tthis.start = r\n\t},\n\tSampleGroupEntry: function(t) {\n\t\tthis.grouping_type = t\n\t},\n\tTrackGroupTypeBox: function(t, e) {\n\t\tBoxParser.FullBox.call(this, t, e)\n\t},\n\tcreateBoxCtor: function(e, i, t) {\n\t\tBoxParser.boxCodes.push(e),\n\t\tBoxParser[e + "Box"] = function(t) {\n\t\t\tBoxParser.Box.call(this, e, t, i)\n\t\t},\n\t\tBoxParser[e + "Box"].prototype = new BoxParser.Box,\n\t\tt && (BoxParser[e + "Box"].prototype.parse = t)\n\t},\n\tcreateFullBoxCtor: function(e, i, r) {\n\t\tBoxParser[e + "Box"] = function(t) {\n\t\t\tBoxParser.FullBox.call(this, e, t, i)\n\t\t},\n\t\tBoxParser[e + "Box"].prototype = new BoxParser.FullBox,\n\t\tBoxParser[e + "Box"].prototype.parse = function(t) {\n\t\t\tthis.parseFullHeader(t),\n\t\t\tr && r.call(this, t)\n\t\t}\n\t},\n\taddSubBoxArrays: function(t) {\n\t\tif (t) for (var e = (this.subBoxNames = t).length, i = 0; i < e; i++) this[t[i] + "s"] = []\n\t},\n\tcreateContainerBoxCtor: function(e, i, t, r) {\n\t\tBoxParser[e + "Box"] = function(t) {\n\t\t\tBoxParser.ContainerBox.call(this, e, t, i),\n\t\t\tBoxParser.addSubBoxArrays.call(this, r)\n\t\t},\n\t\tBoxParser[e + "Box"].prototype = new BoxParser.ContainerBox,\n\t\tt && (BoxParser[e + "Box"].prototype.parse = t)\n\t},\n\tcreateMediaSampleEntryCtor: function(t, e, i) {\n\t\tBoxParser.sampleEntryCodes[t] = [],\n\t\tBoxParser[t + "SampleEntry"] = function(t, e) {\n\t\t\tBoxParser.SampleEntry.call(this, t, e),\n\t\t\tBoxParser.addSubBoxArrays.call(this, i)\n\t\t},\n\t\tBoxParser[t + "SampleEntry"].prototype = new BoxParser.SampleEntry,\n\t\te && (BoxParser[t + "SampleEntry"].prototype.parse = e)\n\t},\n\tcreateSampleEntryCtor: function(e, i, t, r) {\n\t\tBoxParser.sampleEntryCodes[e].push(i),\n\t\tBoxParser[i + "SampleEntry"] = function(t) {\n\t\t\tBoxParser[e + "SampleEntry"].call(this, i, t),\n\t\t\tBoxParser.addSubBoxArrays.call(this, r)\n\t\t},\n\t\tBoxParser[i + "SampleEntry"].prototype = new BoxParser[e + "SampleEntry"],\n\t\tt && (BoxParser[i + "SampleEntry"].prototype.parse = t)\n\t},\n\tcreateEncryptedSampleEntryCtor: function(t, e, i) {\n\t\tBoxParser.createSampleEntryCtor.call(this, t, e, i, ["sinf"])\n\t},\n\tcreateSampleGroupCtor: function(e, t) {\n\t\tBoxParser[e + "SampleGroupEntry"] = function(t) {\n\t\t\tBoxParser.SampleGroupEntry.call(this, e, t)\n\t\t},\n\t\tBoxParser[e + "SampleGroupEntry"].prototype = new BoxParser.SampleGroupEntry,\n\t\tt && (BoxParser[e + "SampleGroupEntry"].prototype.parse = t)\n\t},\n\tcreateTrackGroupCtor: function(e, t) {\n\t\tBoxParser[e + "TrackGroupTypeBox"] = function(t) {\n\t\t\tBoxParser.TrackGroupTypeBox.call(this, e, t)\n\t\t},\n\t\tBoxParser[e + "TrackGroupTypeBox"].prototype = new BoxParser.TrackGroupTypeBox,\n\t\tt && (BoxParser[e + "TrackGroupTypeBox"].prototype.parse = t)\n\t},\n\tcreateUUIDBox: function(e, i, r, s, a) {\n\t\tBoxParser.UUIDs.push(e),\n\t\tBoxParser.UUIDBoxes[e] = function(t) { (r ? BoxParser.FullBox: s ? BoxParser.ContainerBox: BoxParser.Box).call(this, "uuid", t, i, e)\n\t\t},\n\t\tBoxParser.UUIDBoxes[e].prototype = new(r ? BoxParser.FullBox: s ? BoxParser.ContainerBox: BoxParser.Box),\n\t\ta && (BoxParser.UUIDBoxes[e].prototype.parse = r ?\n\t\tfunction(t) {\n\t\t\tthis.parseFullHeader(t),\n\t\t\ta && a.call(this, t)\n\t\t}: a)\n\t}\n};\nfunction printPS(t) {\n\tvar e = "<table class=\'inner-table\'>";\n\te += "<thead><tr><th>length</th><th>nalu_data</th></tr></thead>",\n\te += "<tbody>";\n\tfor (var i = 0; i < t.length; i++) {\n\t\tvar r = t[i];\n\t\te += "<tr>",\n\t\te += "<td>" + r.length + "</td>",\n\t\te += "<td>",\n\t\te += r.nalu.reduce(function(t, e) {\n\t\t\treturn t + e.toString(16).padStart(2, "0")\n\t\t},\n\t\t"0x"),\n\t\te += "</td></tr>"\n\t}\n\treturn e += "</tbody></table>"\n}\nfunction ColorPoint(t, e) {\n\tthis.x = t,\n\tthis.y = e\n}\nfunction Pixel(t, e) {\n\tthis.bad_pixel_row = t,\n\tthis.bad_pixel_column = e\n}\nBoxParser.initialize(),\nBoxParser.TKHD_FLAG_ENABLED = 1,\nBoxParser.TKHD_FLAG_IN_MOVIE = 2,\nBoxParser.TKHD_FLAG_IN_PREVIEW = 4,\nBoxParser.TFHD_FLAG_BASE_DATA_OFFSET = 1,\nBoxParser.TFHD_FLAG_SAMPLE_DESC = 2,\nBoxParser.TFHD_FLAG_SAMPLE_DUR = 8,\nBoxParser.TFHD_FLAG_SAMPLE_SIZE = 16,\nBoxParser.TFHD_FLAG_SAMPLE_FLAGS = 32,\nBoxParser.TFHD_FLAG_DUR_EMPTY = 65536,\nBoxParser.TFHD_FLAG_DEFAULT_BASE_IS_MOOF = 131072,\nBoxParser.TRUN_FLAGS_DATA_OFFSET = 1,\nBoxParser.TRUN_FLAGS_FIRST_FLAG = 4,\nBoxParser.TRUN_FLAGS_DURATION = 256,\nBoxParser.TRUN_FLAGS_SIZE = 512,\nBoxParser.TRUN_FLAGS_FLAGS = 1024,\nBoxParser.TRUN_FLAGS_CTS_OFFSET = 2048,\nBoxParser.Box.prototype.add = function(t) {\n\treturn this.addBox(new BoxParser[t + "Box"])\n},\nBoxParser.Box.prototype.addBox = function(t) {\n\treturn this.boxes.push(t),\n\tthis[t.type + "s"] ? this[t.type + "s"].push(t) : this[t.type] = t,\n\tt\n},\nBoxParser.Box.prototype.set = function(t, e) {\n\treturn this[t] = e,\n\tthis\n},\nBoxParser.Box.prototype.addEntry = function(t, e) {\n\te = e || "entries";\n\treturn this[e] || (this[e] = []),\n\tthis[e].push(t),\n\tthis\n},\n"undefined" != typeof exports && (exports.BoxParser = BoxParser),\nBoxParser.parseUUID = function(t) {\n\treturn BoxParser.parseHex16(t)\n},\nBoxParser.parseHex16 = function(t) {\n\tfor (var e = "",\n\ti = 0; i < 16; i++) {\n\t\tvar r = t.readUint8().toString(16);\n\t\te += 1 === r.length ? "0" + r: r\n\t}\n\treturn e\n},\nBoxParser.parseOneBox = function(t, e, i) {\n\tvar r, s, a = t.getPosition(),\n\tn = 0;\n\tif (t.getEndPosition() - a < 8) return Log.debug("BoxParser", "Not enough data in stream to parse the type and size of the box"),\n\t{\n\t\tcode: BoxParser.ERR_NOT_ENOUGH_DATA\n\t};\n\tif (i && i < 8) return Log.debug("BoxParser", "Not enough bytes left in the parent box to parse a new box"),\n\t{\n\t\tcode: BoxParser.ERR_NOT_ENOUGH_DATA\n\t};\n\tvar o = t.readUint32(),\n\th = t.readString(4),\n\td = h;\n\tif (Log.debug("BoxParser", "Found box of type \'" + h + "\' and size " + o + " at position " + a), n = 8, "uuid" == h) {\n\t\tif (t.getEndPosition() - t.getPosition() < 16 || i - n < 16) return t.seek(a),\n\t\tLog.debug("BoxParser", "Not enough bytes left in the parent box to parse a UUID box"),\n\t\t{\n\t\t\tcode: BoxParser.ERR_NOT_ENOUGH_DATA\n\t\t};\n\t\tn += 16,\n\t\td = s = BoxParser.parseUUID(t)\n\t}\n\tif (1 == o) {\n\t\tif (t.getEndPosition() - t.getPosition() < 8 || i && i - n < 8) return t.seek(a),\n\t\tLog.warn("BoxParser", \'Not enough data in stream to parse the extended size of the "\' + h + \'" box\'),\n\t\t{\n\t\t\tcode: BoxParser.ERR_NOT_ENOUGH_DATA\n\t\t};\n\t\to = t.readUint64(),\n\t\tn += 8\n\t} else if (0 === o) if (i) o = i;\n\telse if ("mdat" !== h) return Log.error("BoxParser", "Unlimited box size not supported for type: \'" + h + "\'"),\n\tr = new BoxParser.Box(h, o),\n\t{\n\t\tcode: BoxParser.OK,\n\t\tbox: r,\n\t\tsize: r.size\n\t};\n\treturn 0 !== o && o < n ? (Log.error("BoxParser", "Box of type " + h + " has an invalid size " + o + " (too small to be a box)"), {\n\t\tcode: BoxParser.ERR_NOT_ENOUGH_DATA,\n\t\ttype: h,\n\t\tsize: o,\n\t\thdr_size: n,\n\t\tstart: a\n\t}) : 0 !== o && i && i < o ? (Log.error("BoxParser", "Box of type \'" + h + "\' has a size " + o + " greater than its container size " + i), {\n\t\tcode: BoxParser.ERR_NOT_ENOUGH_DATA,\n\t\ttype: h,\n\t\tsize: o,\n\t\thdr_size: n,\n\t\tstart: a\n\t}) : 0 !== o && a + o > t.getEndPosition() ? (t.seek(a), Log.info("BoxParser", "Not enough data in stream to parse the entire \'" + h + "\' box"), {\n\t\tcode: BoxParser.ERR_NOT_ENOUGH_DATA,\n\t\ttype: h,\n\t\tsize: o,\n\t\thdr_size: n,\n\t\tstart: a\n\t}) : e ? {\n\t\tcode: BoxParser.OK,\n\t\ttype: h,\n\t\tsize: o,\n\t\thdr_size: n,\n\t\tstart: a\n\t}: (BoxParser[h + "Box"] ? r = new BoxParser[h + "Box"](o) : "uuid" !== h ? (Log.warn("BoxParser", "Unknown box type: \'" + h + "\'"), (r = new BoxParser.Box(h, o)).has_unparsed_data = !0) : BoxParser.UUIDBoxes[s] ? r = new BoxParser.UUIDBoxes[s](o) : (Log.warn("BoxParser", "Unknown uuid type: \'" + s + "\'"), (r = new BoxParser.Box(h, o)).uuid = s, r.has_unparsed_data = !0), r.hdr_size = n, r.start = a, r.write === BoxParser.Box.prototype.write && "mdat" !== r.type && (Log.info("BoxParser", "\'" + d + "\' box writing not yet implemented, keeping unparsed data in memory for later write"), r.parseDataAndRewind(t)), r.parse(t), (a = t.getPosition() - (r.start + r.size)) < 0 ? (Log.warn("BoxParser", "Parsing of box \'" + d + "\' did not read the entire indicated box data size (missing " + -a + " bytes), seeking forward"), t.seek(r.start + r.size)) : 0 < a && (Log.error("BoxParser", "Parsing of box \'" + d + "\' read " + a + " more bytes than the indicated box data size, seeking backwards"), 0 !== r.size && t.seek(r.start + r.size)), {\n\t\tcode: BoxParser.OK,\n\t\tbox: r,\n\t\tsize: r.size\n\t})\n},\nBoxParser.Box.prototype.parse = function(t) {\n\t"mdat" != this.type ? this.data = t.readUint8Array(this.size - this.hdr_size) : 0 === this.size ? t.seek(t.getEndPosition()) : t.seek(this.start + this.size)\n},\nBoxParser.Box.prototype.parseDataAndRewind = function(t) {\n\tthis.data = t.readUint8Array(this.size - this.hdr_size),\n\tt.position -= this.size - this.hdr_size\n},\nBoxParser.FullBox.prototype.parseDataAndRewind = function(t) {\n\tthis.parseFullHeader(t),\n\tthis.data = t.readUint8Array(this.size - this.hdr_size),\n\tthis.hdr_size -= 4,\n\tt.position -= this.size - this.hdr_size\n},\nBoxParser.FullBox.prototype.parseFullHeader = function(t) {\n\tthis.version = t.readUint8(),\n\tthis.flags = t.readUint24(),\n\tthis.hdr_size += 4\n},\nBoxParser.FullBox.prototype.parse = function(t) {\n\tthis.parseFullHeader(t),\n\tthis.data = t.readUint8Array(this.size - this.hdr_size)\n},\nBoxParser.ContainerBox.prototype.parse = function(t) {\n\tfor (; t.getPosition() < this.start + this.size;) {\n\t\tif ((e = BoxParser.parseOneBox(t, !1, this.size - (t.getPosition() - this.start))).code !== BoxParser.OK) return;\n\t\tvar e, i = e.box;\n\t\tthis.boxes.push(i),\n\t\tthis.subBoxNames && -1 != this.subBoxNames.indexOf(i.type) ? this[this.subBoxNames[this.subBoxNames.indexOf(i.type)] + "s"].push(i) : this[e = "uuid" !== i.type ? i.type: i.uuid] ? Log.warn("Box of type " + e + " already stored in field of this type") : this[e] = i\n\t}\n},\nBoxParser.Box.prototype.parseLanguage = function(t) {\n\tthis.language = t.readUint16();\n\tt = [];\n\tt[0] = this.language >> 10 & 31,\n\tt[1] = this.language >> 5 & 31,\n\tt[2] = 31 & this.language,\n\tthis.languageString = String.fromCharCode(t[0] + 96, t[1] + 96, t[2] + 96)\n},\nBoxParser.SAMPLE_ENTRY_TYPE_VISUAL = "Visual",\nBoxParser.SAMPLE_ENTRY_TYPE_AUDIO = "Audio",\nBoxParser.SAMPLE_ENTRY_TYPE_HINT = "Hint",\nBoxParser.SAMPLE_ENTRY_TYPE_METADATA = "Metadata",\nBoxParser.SAMPLE_ENTRY_TYPE_SUBTITLE = "Subtitle",\nBoxParser.SAMPLE_ENTRY_TYPE_SYSTEM = "System",\nBoxParser.SAMPLE_ENTRY_TYPE_TEXT = "Text",\nBoxParser.SampleEntry.prototype.parseHeader = function(t) {\n\tt.readUint8Array(6),\n\tthis.data_reference_index = t.readUint16(),\n\tthis.hdr_size += 8\n},\nBoxParser.SampleEntry.prototype.parse = function(t) {\n\tthis.parseHeader(t),\n\tthis.data = t.readUint8Array(this.size - this.hdr_size)\n},\nBoxParser.SampleEntry.prototype.parseDataAndRewind = function(t) {\n\tthis.parseHeader(t),\n\tthis.data = t.readUint8Array(this.size - this.hdr_size),\n\tthis.hdr_size -= 8,\n\tt.position -= this.size - this.hdr_size\n},\nBoxParser.SampleEntry.prototype.parseFooter = function(t) {\n\tBoxParser.ContainerBox.prototype.parse.call(this, t)\n},\nBoxParser.createMediaSampleEntryCtor(BoxParser.SAMPLE_ENTRY_TYPE_HINT),\nBoxParser.createMediaSampleEntryCtor(BoxParser.SAMPLE_ENTRY_TYPE_METADATA),\nBoxParser.createMediaSampleEntryCtor(BoxParser.SAMPLE_ENTRY_TYPE_SUBTITLE),\nBoxParser.createMediaSampleEntryCtor(BoxParser.SAMPLE_ENTRY_TYPE_SYSTEM),\nBoxParser.createMediaSampleEntryCtor(BoxParser.SAMPLE_ENTRY_TYPE_TEXT),\nBoxParser.createMediaSampleEntryCtor(BoxParser.SAMPLE_ENTRY_TYPE_VISUAL,\nfunction(t) {\n\tvar e;\n\tthis.parseHeader(t),\n\tt.readUint16(),\n\tt.readUint16(),\n\tt.readUint32Array(3),\n\tthis.width = t.readUint16(),\n\tthis.height = t.readUint16(),\n\tthis.horizresolution = t.readUint32(),\n\tthis.vertresolution = t.readUint32(),\n\tt.readUint32(),\n\tthis.frame_count = t.readUint16(),\n\te = Math.min(31, t.readUint8()),\n\tthis.compressorname = t.readString(e),\n\te < 31 && t.readString(31 - e),\n\tthis.depth = t.readUint16(),\n\tt.readUint16(),\n\tthis.parseFooter(t)\n}),\nBoxParser.createMediaSampleEntryCtor(BoxParser.SAMPLE_ENTRY_TYPE_AUDIO,\nfunction(t) {\n\tthis.parseHeader(t),\n\tt.readUint32Array(2),\n\tthis.channel_count = t.readUint16(),\n\tthis.samplesize = t.readUint16(),\n\tt.readUint16(),\n\tt.readUint16(),\n\tthis.samplerate = t.readUint32() / 65536,\n\tthis.parseFooter(t)\n}),\nBoxParser.createSampleEntryCtor(BoxParser.SAMPLE_ENTRY_TYPE_VISUAL, "avc1"),\nBoxParser.createSampleEntryCtor(BoxParser.SAMPLE_ENTRY_TYPE_VISUAL, "avc2"),\nBoxParser.createSampleEntryCtor(BoxParser.SAMPLE_ENTRY_TYPE_VISUAL, "avc3"),\nBoxParser.createSampleEntryCtor(BoxParser.SAMPLE_ENTRY_TYPE_VISUAL, "avc4"),\nBoxParser.createSampleEntryCtor(BoxParser.SAMPLE_ENTRY_TYPE_VISUAL, "av01"),\nBoxParser.createSampleEntryCtor(BoxParser.SAMPLE_ENTRY_TYPE_VISUAL, "dav1"),\nBoxParser.createSampleEntryCtor(BoxParser.SAMPLE_ENTRY_TYPE_VISUAL, "hvc1"),\nBoxParser.createSampleEntryCtor(BoxParser.SAMPLE_ENTRY_TYPE_VISUAL, "hev1"),\nBoxParser.createSampleEntryCtor(BoxParser.SAMPLE_ENTRY_TYPE_VISUAL, "hvt1"),\nBoxParser.createSampleEntryCtor(BoxParser.SAMPLE_ENTRY_TYPE_VISUAL, "lhe1"),\nBoxParser.createSampleEntryCtor(BoxParser.SAMPLE_ENTRY_TYPE_VISUAL, "dvh1"),\nBoxParser.createSampleEntryCtor(BoxParser.SAMPLE_ENTRY_TYPE_VISUAL, "dvhe"),\nBoxParser.createSampleEntryCtor(BoxParser.SAMPLE_ENTRY_TYPE_VISUAL, "vvc1"),\nBoxParser.createSampleEntryCtor(BoxParser.SAMPLE_ENTRY_TYPE_VISUAL, "vvi1"),\nBoxParser.createSampleEntryCtor(BoxParser.SAMPLE_ENTRY_TYPE_VISUAL, "vvs1"),\nBoxParser.createSampleEntryCtor(BoxParser.SAMPLE_ENTRY_TYPE_VISUAL, "vvcN"),\nBoxParser.createSampleEntryCtor(BoxParser.SAMPLE_ENTRY_TYPE_VISUAL, "vp08"),\nBoxParser.createSampleEntryCtor(BoxParser.SAMPLE_ENTRY_TYPE_VISUAL, "vp09"),\nBoxParser.createSampleEntryCtor(BoxParser.SAMPLE_ENTRY_TYPE_VISUAL, "avs3"),\nBoxParser.createSampleEntryCtor(BoxParser.SAMPLE_ENTRY_TYPE_VISUAL, "j2ki"),\nBoxParser.createSampleEntryCtor(BoxParser.SAMPLE_ENTRY_TYPE_VISUAL, "mjp2"),\nBoxParser.createSampleEntryCtor(BoxParser.SAMPLE_ENTRY_TYPE_VISUAL, "mjpg"),\nBoxParser.createSampleEntryCtor(BoxParser.SAMPLE_ENTRY_TYPE_VISUAL, "uncv"),\nBoxParser.createSampleEntryCtor(BoxParser.SAMPLE_ENTRY_TYPE_AUDIO, "mp4a"),\nBoxParser.createSampleEntryCtor(BoxParser.SAMPLE_ENTRY_TYPE_AUDIO, "ac-3"),\nBoxParser.createSampleEntryCtor(BoxParser.SAMPLE_ENTRY_TYPE_AUDIO, "ac-4"),\nBoxParser.createSampleEntryCtor(BoxParser.SAMPLE_ENTRY_TYPE_AUDIO, "ec-3"),\nBoxParser.createSampleEntryCtor(BoxParser.SAMPLE_ENTRY_TYPE_AUDIO, "Opus"),\nBoxParser.createSampleEntryCtor(BoxParser.SAMPLE_ENTRY_TYPE_AUDIO, "mha1"),\nBoxParser.createSampleEntryCtor(BoxParser.SAMPLE_ENTRY_TYPE_AUDIO, "mha2"),\nBoxParser.createSampleEntryCtor(BoxParser.SAMPLE_ENTRY_TYPE_AUDIO, "mhm1"),\nBoxParser.createSampleEntryCtor(BoxParser.SAMPLE_ENTRY_TYPE_AUDIO, "mhm2"),\nBoxParser.createSampleEntryCtor(BoxParser.SAMPLE_ENTRY_TYPE_AUDIO, "fLaC"),\nBoxParser.createEncryptedSampleEntryCtor(BoxParser.SAMPLE_ENTRY_TYPE_VISUAL, "encv"),\nBoxParser.createEncryptedSampleEntryCtor(BoxParser.SAMPLE_ENTRY_TYPE_AUDIO, "enca"),\nBoxParser.createEncryptedSampleEntryCtor(BoxParser.SAMPLE_ENTRY_TYPE_SUBTITLE, "encu"),\nBoxParser.createEncryptedSampleEntryCtor(BoxParser.SAMPLE_ENTRY_TYPE_SYSTEM, "encs"),\nBoxParser.createEncryptedSampleEntryCtor(BoxParser.SAMPLE_ENTRY_TYPE_TEXT, "enct"),\nBoxParser.createEncryptedSampleEntryCtor(BoxParser.SAMPLE_ENTRY_TYPE_METADATA, "encm"),\nBoxParser.createBoxCtor("a1lx", "AV1LayeredImageIndexingProperty",\nfunction(t) {\n\tvar e = 16 * (1 + (1 & (1 & t.readUint8())));\n\tthis.layer_size = [];\n\tfor (var i = 0; i < 3; i++) this.layer_size[i] = 16 == e ? t.readUint16() : t.readUint32()\n}),\nBoxParser.createBoxCtor("a1op", "OperatingPointSelectorProperty",\nfunction(t) {\n\tthis.op_index = t.readUint8()\n}),\nBoxParser.createFullBoxCtor("auxC", "AuxiliaryTypeProperty",\nfunction(t) {\n\tthis.aux_type = t.readCString();\n\tvar e = this.size - this.hdr_size - (this.aux_type.length + 1);\n\tthis.aux_subtype = t.readUint8Array(e)\n}),\nBoxParser.createBoxCtor("av1C", "AV1CodecConfigurationBox",\nfunction(t) {\n\tvar e = t.readUint8();\n\tif (1 == (e >> 7 & 1)) if (this.version = 127 & e, 1 === this.version) if (e = t.readUint8(), this.seq_profile = e >> 5 & 7, this.seq_level_idx_0 = 31 & e, e = t.readUint8(), this.seq_tier_0 = e >> 7 & 1, this.high_bitdepth = e >> 6 & 1, this.twelve_bit = e >> 5 & 1, this.monochrome = e >> 4 & 1, this.chroma_subsampling_x = e >> 3 & 1, this.chroma_subsampling_y = e >> 2 & 1, this.chroma_sample_position = 3 & e, e = t.readUint8(), this.reserved_1 = e >> 5 & 7, 0 === this.reserved_1) {\n\t\tif (this.initial_presentation_delay_present = e >> 4 & 1, 1 === this.initial_presentation_delay_present) this.initial_presentation_delay_minus_one = 15 & e;\n\t\telse if (this.reserved_2 = 15 & e, 0 !== this.reserved_2) return void Log.error("av1C reserved_2 parsing problem");\n\t\te = this.size - this.hdr_size - 4;\n\t\tthis.configOBUs = t.readUint8Array(e)\n\t} else Log.error("av1C reserved_1 parsing problem");\n\telse Log.error("av1C version " + this.version + " not supported");\n\telse Log.error("av1C marker problem")\n}),\nBoxParser.createBoxCtor("avcC", "AVCConfigurationBox",\nfunction(t) {\n\tvar e, i;\n\tfor (this.configurationVersion = t.readUint8(), this.AVCProfileIndication = t.readUint8(), this.profile_compatibility = t.readUint8(), this.AVCLevelIndication = t.readUint8(), this.lengthSizeMinusOne = 3 & t.readUint8(), this.nb_SPS_nalus = 31 & t.readUint8(), i = this.size - this.hdr_size - 6, this.SPS = [], this.SPS.toString = function() {\n\t\treturn printPS(this)\n\t},\n\te = 0; e < this.nb_SPS_nalus; e++) this.SPS[e] = {},\n\tthis.SPS[e].length = t.readUint16(),\n\tthis.SPS[e].nalu = t.readUint8Array(this.SPS[e].length),\n\ti -= 2 + this.SPS[e].length;\n\tfor (this.nb_PPS_nalus = t.readUint8(), i--, this.PPS = [], this.PPS.toString = function() {\n\t\treturn printPS(this)\n\t},\n\te = 0; e < this.nb_PPS_nalus; e++) this.PPS[e] = {},\n\tthis.PPS[e].length = t.readUint16(),\n\tthis.PPS[e].nalu = t.readUint8Array(this.PPS[e].length),\n\ti -= 2 + this.PPS[e].length;\n\t0 < i && (this.ext = t.readUint8Array(i))\n}),\nBoxParser.createBoxCtor("btrt", "BitRateBox",\nfunction(t) {\n\tthis.bufferSizeDB = t.readUint32(),\n\tthis.maxBitrate = t.readUint32(),\n\tthis.avgBitrate = t.readUint32()\n}),\nBoxParser.createFullBoxCtor("ccst", "CodingConstraintsBox",\nfunction(t) {\n\tvar e = t.readUint8();\n\tthis.all_ref_pics_intra = 128 == (128 & e),\n\tthis.intra_pred_used = 64 == (64 & e),\n\tthis.max_ref_per_pic = (63 & e) >> 2,\n\tt.readUint24()\n}),\nBoxParser.createBoxCtor("cdef", "ComponentDefinitionBox",\nfunction(t) {\n\tvar e;\n\tfor (this.channel_count = t.readUint16(), this.channel_indexes = [], this.channel_types = [], this.channel_associations = [], e = 0; e < this.channel_count; e++) this.channel_indexes.push(t.readUint16()),\n\tthis.channel_types.push(t.readUint16()),\n\tthis.channel_associations.push(t.readUint16())\n}),\nBoxParser.createBoxCtor("clap", "CleanApertureBox",\nfunction(t) {\n\tthis.cleanApertureWidthN = t.readUint32(),\n\tthis.cleanApertureWidthD = t.readUint32(),\n\tthis.cleanApertureHeightN = t.readUint32(),\n\tthis.cleanApertureHeightD = t.readUint32(),\n\tthis.horizOffN = t.readUint32(),\n\tthis.horizOffD = t.readUint32(),\n\tthis.vertOffN = t.readUint32(),\n\tthis.vertOffD = t.readUint32()\n}),\nBoxParser.createBoxCtor("clli", "ContentLightLevelBox",\nfunction(t) {\n\tthis.max_content_light_level = t.readUint16(),\n\tthis.max_pic_average_light_level = t.readUint16()\n}),\nBoxParser.createFullBoxCtor("cmex", "CameraExtrinsicMatrixProperty",\nfunction(t) {\n\t1 & this.flags && (this.pos_x = t.readInt32()),\n\t2 & this.flags && (this.pos_y = t.readInt32()),\n\t4 & this.flags && (this.pos_z = t.readInt32()),\n\t8 & this.flags && (0 == this.version ? 16 & this.flags ? (this.quat_x = t.readInt32(), this.quat_y = t.readInt32(), this.quat_z = t.readInt32()) : (this.quat_x = t.readInt16(), this.quat_y = t.readInt16(), this.quat_z = t.readInt16()) : this.version),\n\t32 & this.flags && (this.id = t.readUint32())\n}),\nBoxParser.createFullBoxCtor("cmin", "CameraIntrinsicMatrixProperty",\nfunction(t) {\n\tthis.focal_length_x = t.readInt32(),\n\tthis.principal_point_x = t.readInt32(),\n\tthis.principal_point_y = t.readInt32(),\n\t1 & this.flags && (this.focal_length_y = t.readInt32(), this.skew_factor = t.readInt32())\n}),\nBoxParser.createBoxCtor("cmpd", "ComponentDefinitionBox",\nfunction(t) {\n\tfor (this.component_count = t.readUint32(), this.component_types = [], this.component_type_urls = [], i = 0; i < this.component_count; i++) {\n\t\tvar e = t.readUint16();\n\t\tthis.component_types.push(e),\n\t\t32768 <= e && this.component_type_urls.push(t.readCString())\n\t}\n}),\nBoxParser.createFullBoxCtor("co64", "ChunkLargeOffsetBox",\nfunction(t) {\n\tvar e, i = t.readUint32();\n\tif (this.chunk_offsets = [], 0 === this.version) for (e = 0; e < i; e++) this.chunk_offsets.push(t.readUint64())\n}),\nBoxParser.createFullBoxCtor("CoLL", "ContentLightLevelBox",\nfunction(t) {\n\tthis.maxCLL = t.readUint16(),\n\tthis.maxFALL = t.readUint16()\n}),\nBoxParser.createBoxCtor("colr", "ColourInformationBox",\nfunction(t) {\n\tvar e;\n\tthis.colour_type = t.readString(4),\n\t"nclx" === this.colour_type ? (this.colour_primaries = t.readUint16(), this.transfer_characteristics = t.readUint16(), this.matrix_coefficients = t.readUint16(), e = t.readUint8(), this.full_range_flag = e >> 7) : "rICC" !== this.colour_type && "prof" !== this.colour_type || (this.ICC_profile = t.readUint8Array(this.size - 4))\n}),\nBoxParser.createFullBoxCtor("cprt", "CopyrightBox",\nfunction(t) {\n\tthis.parseLanguage(t),\n\tthis.notice = t.readCString()\n}),\nBoxParser.createFullBoxCtor("cslg", "CompositionToDecodeBox",\nfunction(t) {\n\t0 === this.version && (this.compositionToDTSShift = t.readInt32(), this.leastDecodeToDisplayDelta = t.readInt32(), this.greatestDecodeToDisplayDelta = t.readInt32(), this.compositionStartTime = t.readInt32(), this.compositionEndTime = t.readInt32())\n}),\nBoxParser.createFullBoxCtor("ctts", "CompositionOffsetBox",\nfunction(t) {\n\tvar e, i = t.readUint32();\n\tif (this.sample_counts = [], this.sample_offsets = [], 0 === this.version) for (e = 0; e < i; e++) {\n\t\tthis.sample_counts.push(t.readUint32());\n\t\tvar r = t.readInt32();\n\t\tr < 0 && Log.warn("BoxParser", "ctts box uses negative values without using version 1"),\n\t\tthis.sample_offsets.push(r)\n\t} else if (1 == this.version) for (e = 0; e < i; e++) this.sample_counts.push(t.readUint32()),\n\tthis.sample_offsets.push(t.readInt32())\n}),\nBoxParser.createBoxCtor("dac3", "AC3SpecificBox",\nfunction(t) {\n\tvar e = t.readUint8(),\n\ti = t.readUint8(),\n\tt = t.readUint8();\n\tthis.fscod = e >> 6,\n\tthis.bsid = e >> 1 & 31,\n\tthis.bsmod = (1 & e) << 2 | i >> 6 & 3,\n\tthis.acmod = i >> 3 & 7,\n\tthis.lfeon = i >> 2 & 1,\n\tthis.bit_rate_code = 3 & i | t >> 5 & 7\n}),\nBoxParser.createBoxCtor("dec3", "EC3SpecificBox",\nfunction(t) {\n\tvar e = t.readUint16();\n\tthis.data_rate = e >> 3,\n\tthis.num_ind_sub = 7 & e,\n\tthis.ind_subs = [];\n\tfor (var i = 0; i < this.num_ind_sub + 1; i++) {\n\t\tvar r = {};\n\t\tthis.ind_subs.push(r);\n\t\tvar s = t.readUint8(),\n\t\ta = t.readUint8(),\n\t\tn = t.readUint8();\n\t\tr.fscod = s >> 6,\n\t\tr.bsid = s >> 1 & 31,\n\t\tr.bsmod = (1 & s) << 4 | a >> 4 & 15,\n\t\tr.acmod = a >> 1 & 7,\n\t\tr.lfeon = 1 & a,\n\t\tr.num_dep_sub = n >> 1 & 15,\n\t\t0 < r.num_dep_sub && (r.chan_loc = (1 & n) << 8 | t.readUint8())\n\t}\n}),\nBoxParser.createFullBoxCtor("dfLa", "FLACSpecificBox",\nfunction(t) {\n\tfor (var e = [], i = ["STREAMINFO", "PADDING", "APPLICATION", "SEEKTABLE", "VORBIS_COMMENT", "CUESHEET", "PICTURE", "RESERVED"];;) {\n\t\tvar r = t.readUint8(),\n\t\ts = Math.min(127 & r, i.length - 1);\n\t\tif (s ? t.readUint8Array(t.readUint24()) : (t.readUint8Array(13), this.samplerate = t.readUint32() >> 12, t.readUint8Array(20)), e.push(i[s]), 128 & r) break\n\t}\n\tthis.numMetadataBlocks = e.length + " (" + e.join(", ") + ")"\n}),\nBoxParser.createBoxCtor("dimm", "hintimmediateBytesSent",\nfunction(t) {\n\tthis.bytessent = t.readUint64()\n}),\nBoxParser.createBoxCtor("dmax", "hintlongestpacket",\nfunction(t) {\n\tthis.time = t.readUint32()\n}),\nBoxParser.createBoxCtor("dmed", "hintmediaBytesSent",\nfunction(t) {\n\tthis.bytessent = t.readUint64()\n}),\nBoxParser.createBoxCtor("dOps", "OpusSpecificBox",\nfunction(t) {\n\tif (this.Version = t.readUint8(), this.OutputChannelCount = t.readUint8(), this.PreSkip = t.readUint16(), this.InputSampleRate = t.readUint32(), this.OutputGain = t.readInt16(), this.ChannelMappingFamily = t.readUint8(), 0 !== this.ChannelMappingFamily) {\n\t\tthis.StreamCount = t.readUint8(),\n\t\tthis.CoupledCount = t.readUint8(),\n\t\tthis.ChannelMapping = [];\n\t\tfor (var e = 0; e < this.OutputChannelCount; e++) this.ChannelMapping[e] = t.readUint8()\n\t}\n}),\nBoxParser.createFullBoxCtor("dref", "DataReferenceBox",\nfunction(t) {\n\tvar e;\n\tthis.entries = [];\n\tfor (var i = t.readUint32(), r = 0; r < i; r++) {\n\t\tif ((e = BoxParser.parseOneBox(t, !1, this.size - (t.getPosition() - this.start))).code !== BoxParser.OK) return;\n\t\te = e.box,\n\t\tthis.entries.push(e)\n\t}\n}),\nBoxParser.createBoxCtor("drep", "hintrepeatedBytesSent",\nfunction(t) {\n\tthis.bytessent = t.readUint64()\n}),\nBoxParser.createFullBoxCtor("elng", "ExtendedLanguageBox",\nfunction(t) {\n\tthis.extended_language = t.readString(this.size - this.hdr_size)\n}),\nBoxParser.createFullBoxCtor("elst", "EditListBox",\nfunction(t) {\n\tthis.entries = [];\n\tfor (var e = t.readUint32(), i = 0; i < e; i++) {\n\t\tvar r = {};\n\t\tthis.entries.push(r),\n\t\t1 === this.version ? (r.segment_duration = t.readUint64(), r.media_time = t.readInt64()) : (r.segment_duration = t.readUint32(), r.media_time = t.readInt32()),\n\t\tr.media_rate_integer = t.readInt16(),\n\t\tr.media_rate_fraction = t.readInt16()\n\t}\n}),\nBoxParser.createFullBoxCtor("emsg", "EventMessageBox",\nfunction(t) {\n\t1 == this.version ? (this.timescale = t.readUint32(), this.presentation_time = t.readUint64(), this.event_duration = t.readUint32(), this.id = t.readUint32(), this.scheme_id_uri = t.readCString(), this.value = t.readCString()) : (this.scheme_id_uri = t.readCString(), this.value = t.readCString(), this.timescale = t.readUint32(), this.presentation_time_delta = t.readUint32(), this.event_duration = t.readUint32(), this.id = t.readUint32());\n\tvar e = this.size - this.hdr_size - (16 + (this.scheme_id_uri.length + 1) + (this.value.length + 1));\n\t1 == this.version && (e -= 4),\n\tthis.message_data = t.readUint8Array(e)\n}),\nBoxParser.createEntityToGroupCtor = function(e, r) {\n\tBoxParser[e + "Box"] = function(t) {\n\t\tBoxParser.FullBox.call(this, e, t)\n\t},\n\tBoxParser[e + "Box"].prototype = new BoxParser.FullBox,\n\tBoxParser[e + "Box"].prototype.parse = function(t) {\n\t\tif (this.parseFullHeader(t), r) r.call(this, t);\n\t\telse for (this.group_id = t.readUint32(), this.num_entities_in_group = t.readUint32(), this.entity_ids = [], i = 0; i < this.num_entities_in_group; i++) {\n\t\t\tvar e = t.readUint32();\n\t\t\tthis.entity_ids.push(e)\n\t\t}\n\t}\n},\nBoxParser.createEntityToGroupCtor("aebr"),\nBoxParser.createEntityToGroupCtor("afbr"),\nBoxParser.createEntityToGroupCtor("albc"),\nBoxParser.createEntityToGroupCtor("altr"),\nBoxParser.createEntityToGroupCtor("brst"),\nBoxParser.createEntityToGroupCtor("dobr"),\nBoxParser.createEntityToGroupCtor("eqiv"),\nBoxParser.createEntityToGroupCtor("favc"),\nBoxParser.createEntityToGroupCtor("fobr"),\nBoxParser.createEntityToGroupCtor("iaug"),\nBoxParser.createEntityToGroupCtor("pano"),\nBoxParser.createEntityToGroupCtor("slid"),\nBoxParser.createEntityToGroupCtor("ster"),\nBoxParser.createEntityToGroupCtor("tsyn"),\nBoxParser.createEntityToGroupCtor("wbbr"),\nBoxParser.createEntityToGroupCtor("prgr"),\nBoxParser.createEntityToGroupCtor("pymd",\nfunction(t) {\n\tthis.group_id = t.readUint32(),\n\tthis.num_entities_in_group = t.readUint32(),\n\tthis.entity_ids = [];\n\tfor (var e = 0; e < this.num_entities_in_group; e++) {\n\t\tvar i = t.readUint32();\n\t\tthis.entity_ids.push(i)\n\t}\n\tfor (this.tile_size_x = t.readUint16(), this.tile_size_y = t.readUint16(), this.layer_binning = [], this.tiles_in_layer_column_minus1 = [], this.tiles_in_layer_row_minus1 = [], e = 0; e < this.num_entities_in_group; e++) this.layer_binning[e] = t.readUint16(),\n\tthis.tiles_in_layer_row_minus1[e] = t.readUint16(),\n\tthis.tiles_in_layer_column_minus1[e] = t.readUint16()\n}),\nBoxParser.createFullBoxCtor("esds", "ElementaryStreamDescriptorBox",\nfunction(t) {\n\tvar e = t.readUint8Array(this.size - this.hdr_size);\n\tvoid 0 !== MPEG4DescriptorParser && (t = new MPEG4DescriptorParser, this.esd = t.parseOneDescriptor(new DataStream(e.buffer, 0, DataStream.BIG_ENDIAN)))\n}),\nBoxParser.createBoxCtor("fiel", "FieldHandlingBox",\nfunction(t) {\n\tthis.fieldCount = t.readUint8(),\n\tthis.fieldOrdering = t.readUint8()\n}),\nBoxParser.createBoxCtor("frma", "OriginalFormatBox",\nfunction(t) {\n\tthis.data_format = t.readString(4)\n}),\nBoxParser.createBoxCtor("ftyp", "FileTypeBox",\nfunction(t) {\n\tvar e = this.size - this.hdr_size;\n\tthis.major_brand = t.readString(4),\n\tthis.minor_version = t.readUint32(),\n\te -= 8,\n\tthis.compatible_brands = [];\n\tfor (var i = 0; 4 <= e;) this.compatible_brands[i] = t.readString(4),\n\te -= 4,\n\ti++\n}),\nBoxParser.createFullBoxCtor("hdlr", "HandlerBox",\nfunction(t) {\n\t0 === this.version && (t.readUint32(), this.handler = t.readString(4), t.readUint32Array(3), this.name = t.readString(this.size - this.hdr_size - 20), "\0" === this.name[this.name.length - 1] && (this.name = this.name.slice(0, -1)))\n}),\nBoxParser.createBoxCtor("hvcC", "HEVCConfigurationBox",\nfunction(t) {\n\tvar e, i;\n\tthis.configurationVersion = t.readUint8(),\n\ti = t.readUint8(),\n\tthis.general_profile_space = i >> 6,\n\tthis.general_tier_flag = (32 & i) >> 5,\n\tthis.general_profile_idc = 31 & i,\n\tthis.general_profile_compatibility = t.readUint32(),\n\tthis.general_constraint_indicator = t.readUint8Array(6),\n\tthis.general_level_idc = t.readUint8(),\n\tthis.min_spatial_segmentation_idc = 4095 & t.readUint16(),\n\tthis.parallelismType = 3 & t.readUint8(),\n\tthis.chroma_format_idc = 3 & t.readUint8(),\n\tthis.bit_depth_luma_minus8 = 7 & t.readUint8(),\n\tthis.bit_depth_chroma_minus8 = 7 & t.readUint8(),\n\tthis.avgFrameRate = t.readUint16(),\n\ti = t.readUint8(),\n\tthis.constantFrameRate = i >> 6,\n\tthis.numTemporalLayers = (13 & i) >> 3,\n\tthis.temporalIdNested = (4 & i) >> 2,\n\tthis.lengthSizeMinusOne = 3 & i,\n\tthis.nalu_arrays = [],\n\tthis.nalu_arrays.toString = function() {\n\t\tvar t = "<table class=\'inner-table\'>";\n\t\tt += "<thead><tr><th>completeness</th><th>nalu_type</th><th>nalu_data</th></tr></thead>",\n\t\tt += "<tbody>";\n\t\tfor (var e = 0; e < this.length; e++) {\n\t\t\tvar i = this[e];\n\t\t\tt += "<tr>",\n\t\t\tt += "<td rowspan=\'" + i.length + "\'>" + i.completeness + "</td>",\n\t\t\tt += "<td rowspan=\'" + i.length + "\'>" + i.nalu_type + "</td>";\n\t\t\tfor (var r = 0; r < i.length; r++) 0 !== r && (t += "<tr>"),\n\t\t\tt += "<td>",\n\t\t\tt += i[r].data.reduce(function(t, e) {\n\t\t\t\treturn t + e.toString(16).padStart(2, "0")\n\t\t\t},\n\t\t\t"0x"),\n\t\t\tt += "</td></tr>"\n\t\t}\n\t\treturn t += "</tbody></table>"\n\t};\n\tfor (var r = t.readUint8(), s = 0; s < r; s++) {\n\t\tvar a = [];\n\t\tthis.nalu_arrays.push(a),\n\t\ti = t.readUint8(),\n\t\ta.completeness = (128 & i) >> 7,\n\t\ta.nalu_type = 63 & i;\n\t\tfor (var n = t.readUint16(), o = 0; o < n; o++) {\n\t\t\tvar h = {};\n\t\t\ta.push(h),\n\t\t\te = t.readUint16(),\n\t\t\th.data = t.readUint8Array(e)\n\t\t}\n\t}\n}),\nBoxParser.createFullBoxCtor("iinf", "ItemInfoBox",\nfunction(t) {\n\tvar e;\n\t0 === this.version ? this.entry_count = t.readUint16() : this.entry_count = t.readUint32(),\n\tthis.item_infos = [];\n\tfor (var i = 0; i < this.entry_count; i++) {\n\t\tif ((e = BoxParser.parseOneBox(t, !1, this.size - (t.getPosition() - this.start))).code !== BoxParser.OK) return;\n\t\t"infe" !== e.box.type && Log.error("BoxParser", "Expected \'infe\' box, got " + e.box.type),\n\t\tthis.item_infos[i] = e.box\n\t}\n}),\nBoxParser.createFullBoxCtor("iloc", "ItemLocationBox",\nfunction(t) {\n\tvar e = t.readUint8();\n\tthis.offset_size = e >> 4 & 15,\n\tthis.length_size = 15 & e,\n\te = t.readUint8(),\n\tthis.base_offset_size = e >> 4 & 15,\n\t1 === this.version || 2 === this.version ? this.index_size = 15 & e: this.index_size = 0,\n\tthis.items = [];\n\tvar i = 0;\n\tif (this.version < 2) i = t.readUint16();\n\telse {\n\t\tif (2 !== this.version) throw "version of iloc box not supported";\n\t\ti = t.readUint32()\n\t}\n\tfor (var r = 0; r < i; r++) {\n\t\tvar s = {};\n\t\tif (this.items.push(s), this.version < 2) s.item_ID = t.readUint16();\n\t\telse {\n\t\t\tif (2 !== this.version) throw "version of iloc box not supported";\n\t\t\ts.item_ID = t.readUint32()\n\t\t}\n\t\tswitch (1 === this.version || 2 === this.version ? s.construction_method = 15 & t.readUint16() : s.construction_method = 0, s.data_reference_index = t.readUint16(), this.base_offset_size) {\n\t\tcase 0:\n\t\t\ts.base_offset = 0;\n\t\t\tbreak;\n\t\tcase 4:\n\t\t\ts.base_offset = t.readUint32();\n\t\t\tbreak;\n\t\tcase 8:\n\t\t\ts.base_offset = t.readUint64();\n\t\t\tbreak;\n\t\tdefault:\n\t\t\tthrow "Error reading base offset size"\n\t\t}\n\t\tvar a = t.readUint16();\n\t\ts.extents = [];\n\t\tfor (var n = 0; n < a; n++) {\n\t\t\tvar o = {};\n\t\t\tif (s.extents.push(o), 1 === this.version || 2 === this.version) switch (this.index_size) {\n\t\t\tcase 0:\n\t\t\t\to.extent_index = 0;\n\t\t\t\tbreak;\n\t\t\tcase 4:\n\t\t\t\to.extent_index = t.readUint32();\n\t\t\t\tbreak;\n\t\t\tcase 8:\n\t\t\t\to.extent_index = t.readUint64();\n\t\t\t\tbreak;\n\t\t\tdefault:\n\t\t\t\tthrow "Error reading extent index"\n\t\t\t}\n\t\t\tswitch (this.offset_size) {\n\t\t\tcase 0:\n\t\t\t\to.extent_offset = 0;\n\t\t\t\tbreak;\n\t\t\tcase 4:\n\t\t\t\to.extent_offset = t.readUint32();\n\t\t\t\tbreak;\n\t\t\tcase 8:\n\t\t\t\to.extent_offset = t.readUint64();\n\t\t\t\tbreak;\n\t\t\tdefault:\n\t\t\t\tthrow "Error reading extent index"\n\t\t\t}\n\t\t\tswitch (this.length_size) {\n\t\t\tcase 0:\n\t\t\t\to.extent_length = 0;\n\t\t\t\tbreak;\n\t\t\tcase 4:\n\t\t\t\to.extent_length = t.readUint32();\n\t\t\t\tbreak;\n\t\t\tcase 8:\n\t\t\t\to.extent_length = t.readUint64();\n\t\t\t\tbreak;\n\t\t\tdefault:\n\t\t\t\tthrow "Error reading extent index"\n\t\t\t}\n\t\t}\n\t}\n}),\nBoxParser.createBoxCtor("imir", "ImageMirror",\nfunction(t) {\n\tt = t.readUint8();\n\tthis.reserved = t >> 7,\n\tthis.axis = 1 & t\n}),\nBoxParser.createFullBoxCtor("infe", "ItemInfoEntry",\nfunction(t) {\n\treturn 0 !== this.version && 1 !== this.version || (this.item_ID = t.readUint16(), this.item_protection_index = t.readUint16(), this.item_name = t.readCString(), this.content_type = t.readCString(), this.content_encoding = t.readCString()),\n\t1 === this.version ? (this.extension_type = t.readString(4), Log.warn("BoxParser", "Cannot parse extension type"), void t.seek(this.start + this.size)) : void(2 <= this.version && (2 === this.version ? this.item_ID = t.readUint16() : 3 === this.version && (this.item_ID = t.readUint32()), this.item_protection_index = t.readUint16(), this.item_type = t.readString(4), this.item_name = t.readCString(), "mime" === this.item_type ? (this.content_type = t.readCString(), this.content_encoding = t.readCString()) : "uri " === this.item_type && (this.item_uri_type = t.readCString())))\n}),\nBoxParser.createFullBoxCtor("ipma", "ItemPropertyAssociationBox",\nfunction(t) {\n\tvar e, i;\n\tfor (entry_count = t.readUint32(), this.associations = [], e = 0; e < entry_count; e++) {\n\t\tvar r = {};\n\t\tthis.associations.push(r),\n\t\tthis.version < 1 ? r.id = t.readUint16() : r.id = t.readUint32();\n\t\tvar s = t.readUint8();\n\t\tfor (r.props = [], i = 0; i < s; i++) {\n\t\t\tvar a = t.readUint8(),\n\t\t\tn = {};\n\t\t\tr.props.push(n),\n\t\t\tn.essential = (128 & a) >> 7 == 1,\n\t\t\t1 & this.flags ? n.property_index = (127 & a) << 8 | t.readUint8() : n.property_index = 127 & a\n\t\t}\n\t}\n}),\nBoxParser.createFullBoxCtor("iref", "ItemReferenceBox",\nfunction(t) {\n\tvar e;\n\tfor (this.references = []; t.getPosition() < this.start + this.size;) {\n\t\tif ((e = BoxParser.parseOneBox(t, !0, this.size - (t.getPosition() - this.start))).code !== BoxParser.OK) return; (e = new(0 === this.version ? BoxParser.SingleItemTypeReferenceBox: BoxParser.SingleItemTypeReferenceBoxLarge)(e.type, e.size, e.hdr_size, e.start)).write === BoxParser.Box.prototype.write && "mdat" !== e.type && (Log.warn("BoxParser", e.type + " box writing not yet implemented, keeping unparsed data in memory for later write"), e.parseDataAndRewind(t)),\n\t\te.parse(t),\n\t\tthis.references.push(e)\n\t}\n}),\nBoxParser.createBoxCtor("irot", "ImageRotation",\nfunction(t) {\n\tthis.angle = 3 & t.readUint8()\n}),\nBoxParser.createFullBoxCtor("ispe", "ImageSpatialExtentsProperty",\nfunction(t) {\n\tthis.image_width = t.readUint32(),\n\tthis.image_height = t.readUint32()\n}),\nBoxParser.createFullBoxCtor("kind", "KindBox",\nfunction(t) {\n\tthis.schemeURI = t.readCString(),\n\tthis.value = t.readCString()\n}),\nBoxParser.createFullBoxCtor("leva", "LevelAssignmentBox",\nfunction(t) {\n\tvar e = t.readUint8();\n\tthis.levels = [];\n\tfor (var i = 0; i < e; i++) {\n\t\tvar r = {}; (this.levels[i] = r).track_ID = t.readUint32();\n\t\tvar s = t.readUint8();\n\t\tswitch (r.padding_flag = s >> 7, r.assignment_type = 127 & s, r.assignment_type) {\n\t\tcase 0:\n\t\t\tr.grouping_type = t.readString(4);\n\t\t\tbreak;\n\t\tcase 1:\n\t\t\tr.grouping_type = t.readString(4),\n\t\t\tr.grouping_type_parameter = t.readUint32();\n\t\t\tbreak;\n\t\tcase 2:\n\t\tcase 3:\n\t\t\tbreak;\n\t\tcase 4:\n\t\t\tr.sub_track_id = t.readUint32();\n\t\t\tbreak;\n\t\tdefault:\n\t\t\tLog.warn("BoxParser", "Unknown leva assignement type")\n\t\t}\n\t}\n}),\nBoxParser.createBoxCtor("lhvC", "LHEVCConfigurationBox",\nfunction(t) {\n\tvar e;\n\tthis.configurationVersion = t.readUint8(),\n\tthis.min_spatial_segmentation_idc = 4095 & t.readUint16(),\n\tthis.parallelismType = 3 & t.readUint8(),\n\te = t.readUint8(),\n\tthis.numTemporalLayers = (13 & e) >> 3,\n\tthis.temporalIdNested = (4 & e) >> 2,\n\tthis.lengthSizeMinusOne = 3 & e,\n\tthis.nalu_arrays = [],\n\tthis.nalu_arrays.toString = function() {\n\t\tvar t = "<table class=\'inner-table\'>";\n\t\tt += "<thead><tr><th>completeness</th><th>nalu_type</th><th>nalu_data</th></tr></thead>",\n\t\tt += "<tbody>";\n\t\tfor (var e = 0; e < this.length; e++) {\n\t\t\tvar i = this[e];\n\t\t\tt += "<tr>",\n\t\t\tt += "<td rowspan=\'" + i.length + "\'>" + i.completeness + "</td>",\n\t\t\tt += "<td rowspan=\'" + i.length + "\'>" + i.nalu_type + "</td>";\n\t\t\tfor (var r = 0; r < i.length; r++) 0 !== r && (t += "<tr>"),\n\t\t\tt += "<td>",\n\t\t\tt += i[r].data.reduce(function(t, e) {\n\t\t\t\treturn t + e.toString(16).padStart(2, "0")\n\t\t\t},\n\t\t\t"0x"),\n\t\t\tt += "</td></tr>"\n\t\t}\n\t\treturn t += "</tbody></table>"\n\t};\n\tfor (var i = t.readUint8(), r = 0; r < i; r++) {\n\t\tvar s = [];\n\t\tthis.nalu_arrays.push(s),\n\t\te = t.readUint8(),\n\t\ts.completeness = (128 & e) >> 7,\n\t\ts.nalu_type = 63 & e;\n\t\tfor (var a = t.readUint16(), n = 0; n < a; n++) {\n\t\t\tvar o = {};\n\t\t\ts.push(o);\n\t\t\tvar h = t.readUint16();\n\t\t\to.data = t.readUint8Array(h)\n\t\t}\n\t}\n}),\nBoxParser.createBoxCtor("lsel", "LayerSelectorProperty",\nfunction(t) {\n\tthis.layer_id = t.readUint16()\n}),\nBoxParser.createBoxCtor("maxr", "hintmaxrate",\nfunction(t) {\n\tthis.period = t.readUint32(),\n\tthis.bytes = t.readUint32()\n}),\nColorPoint.prototype.toString = function() {\n\treturn "(" + this.x + "," + this.y + ")"\n},\nBoxParser.createBoxCtor("mdcv", "MasteringDisplayColourVolumeBox",\nfunction(t) {\n\tthis.display_primaries = [],\n\tthis.display_primaries[0] = new ColorPoint(t.readUint16(), t.readUint16()),\n\tthis.display_primaries[1] = new ColorPoint(t.readUint16(), t.readUint16()),\n\tthis.display_primaries[2] = new ColorPoint(t.readUint16(), t.readUint16()),\n\tthis.white_point = new ColorPoint(t.readUint16(), t.readUint16()),\n\tthis.max_display_mastering_luminance = t.readUint32(),\n\tthis.min_display_mastering_luminance = t.readUint32()\n}),\nBoxParser.createFullBoxCtor("mdhd", "MediaHeaderBox",\nfunction(t) {\n\t1 == this.version ? (this.creation_time = t.readUint64(), this.modification_time = t.readUint64(), this.timescale = t.readUint32(), this.duration = t.readUint64()) : (this.creation_time = t.readUint32(), this.modification_time = t.readUint32(), this.timescale = t.readUint32(), this.duration = t.readUint32()),\n\tthis.parseLanguage(t),\n\tt.readUint16()\n}),\nBoxParser.createFullBoxCtor("mehd", "MovieExtendsHeaderBox",\nfunction(t) {\n\t1 & this.flags && (Log.warn("BoxParser", "mehd box incorrectly uses flags set to 1, converting version to 1"), this.version = 1),\n\t1 == this.version ? this.fragment_duration = t.readUint64() : this.fragment_duration = t.readUint32()\n}),\nBoxParser.createFullBoxCtor("meta", "MetaBox",\nfunction(t) {\n\tthis.boxes = [],\n\tBoxParser.ContainerBox.prototype.parse.call(this, t)\n}),\nBoxParser.createFullBoxCtor("mfhd", "MovieFragmentHeaderBox",\nfunction(t) {\n\tthis.sequence_number = t.readUint32()\n}),\nBoxParser.createFullBoxCtor("mfro", "MovieFragmentRandomAccessOffsetBox",\nfunction(t) {\n\tthis._size = t.readUint32()\n}),\nBoxParser.createFullBoxCtor("mskC", "MaskConfigurationProperty",\nfunction(t) {\n\tthis.bits_per_pixel = t.readUint8()\n}),\nBoxParser.createFullBoxCtor("mvhd", "MovieHeaderBox",\nfunction(t) {\n\t1 == this.version ? (this.creation_time = t.readUint64(), this.modification_time = t.readUint64(), this.timescale = t.readUint32(), this.duration = t.readUint64()) : (this.creation_time = t.readUint32(), this.modification_time = t.readUint32(), this.timescale = t.readUint32(), this.duration = t.readUint32()),\n\tthis.rate = t.readUint32(),\n\tthis.volume = t.readUint16() >> 8,\n\tt.readUint16(),\n\tt.readUint32Array(2),\n\tthis.matrix = t.readUint32Array(9),\n\tt.readUint32Array(6),\n\tthis.next_track_id = t.readUint32()\n}),\nBoxParser.createBoxCtor("npck", "hintPacketsSent",\nfunction(t) {\n\tthis.packetssent = t.readUint32()\n}),\nBoxParser.createBoxCtor("nump", "hintPacketsSent",\nfunction(t) {\n\tthis.packetssent = t.readUint64()\n}),\nBoxParser.createFullBoxCtor("padb", "PaddingBitsBox",\nfunction(t) {\n\tvar e = t.readUint32();\n\tthis.padbits = [];\n\tfor (var i = 0; i < Math.floor((e + 1) / 2); i++) this.padbits = t.readUint8()\n}),\nBoxParser.createBoxCtor("pasp", "PixelAspectRatioBox",\nfunction(t) {\n\tthis.hSpacing = t.readUint32(),\n\tthis.vSpacing = t.readUint32()\n}),\nBoxParser.createBoxCtor("payl", "CuePayloadBox",\nfunction(t) {\n\tthis.text = t.readString(this.size - this.hdr_size)\n}),\nBoxParser.createBoxCtor("payt", "hintpayloadID",\nfunction(t) {\n\tthis.payloadID = t.readUint32();\n\tvar e = t.readUint8();\n\tthis.rtpmap_string = t.readString(e)\n}),\nBoxParser.createFullBoxCtor("pdin", "ProgressiveDownloadInfoBox",\nfunction(t) {\n\tvar e = (this.size - this.hdr_size) / 8;\n\tthis.rate = [],\n\tthis.initial_delay = [];\n\tfor (var i = 0; i < e; i++) this.rate[i] = t.readUint32(),\n\tthis.initial_delay[i] = t.readUint32()\n}),\nBoxParser.createFullBoxCtor("pitm", "PrimaryItemBox",\nfunction(t) {\n\t0 === this.version ? this.item_id = t.readUint16() : this.item_id = t.readUint32()\n}),\nBoxParser.createFullBoxCtor("pixi", "PixelInformationProperty",\nfunction(t) {\n\tvar e;\n\tfor (this.num_channels = t.readUint8(), this.bits_per_channels = [], e = 0; e < this.num_channels; e++) this.bits_per_channels[e] = t.readUint8()\n}),\nBoxParser.createBoxCtor("pmax", "hintlargestpacket",\nfunction(t) {\n\tthis.bytes = t.readUint32()\n}),\nBoxParser.createFullBoxCtor("prdi", "ProgressiveDerivedImageItemInformationProperty",\nfunction(t) {\n\tif (this.step_count = t.readUint16(), this.item_count = [], 2 & this.flags) for (var e = 0; e < this.step_count; e++) this.item_count[e] = t.readUint16()\n}),\nBoxParser.createFullBoxCtor("prft", "ProducerReferenceTimeBox",\nfunction(t) {\n\tthis.ref_track_id = t.readUint32(),\n\tthis.ntp_timestamp = t.readUint64(),\n\t0 === this.version ? this.media_time = t.readUint32() : this.media_time = t.readUint64()\n}),\nBoxParser.createFullBoxCtor("pssh", "ProtectionSystemSpecificHeaderBox",\nfunction(t) {\n\tif (this.system_id = BoxParser.parseHex16(t), 0 < this.version) {\n\t\tvar e = t.readUint32();\n\t\tthis.kid = [];\n\t\tfor (var i = 0; i < e; i++) this.kid[i] = BoxParser.parseHex16(t)\n\t}\n\tvar r = t.readUint32();\n\t0 < r && (this.data = t.readUint8Array(r))\n}),\nBoxParser.createFullBoxCtor("clef", "TrackCleanApertureDimensionsBox",\nfunction(t) {\n\tthis.width = t.readUint32(),\n\tthis.height = t.readUint32()\n}),\nBoxParser.createFullBoxCtor("enof", "TrackEncodedPixelsDimensionsBox",\nfunction(t) {\n\tthis.width = t.readUint32(),\n\tthis.height = t.readUint32()\n}),\nBoxParser.createFullBoxCtor("prof", "TrackProductionApertureDimensionsBox",\nfunction(t) {\n\tthis.width = t.readUint32(),\n\tthis.height = t.readUint32()\n}),\nBoxParser.createContainerBoxCtor("tapt", "TrackApertureModeDimensionsBox", null, ["clef", "prof", "enof"]),\nBoxParser.createBoxCtor("rtp ", "rtpmoviehintinformation",\nfunction(t) {\n\tthis.descriptionformat = t.readString(4),\n\tthis.sdptext = t.readString(this.size - this.hdr_size - 4)\n}),\nBoxParser.createFullBoxCtor("saio", "SampleAuxiliaryInformationOffsetsBox",\nfunction(t) {\n\t1 & this.flags && (this.aux_info_type = t.readString(4), this.aux_info_type_parameter = t.readUint32());\n\tvar e = t.readUint32();\n\tthis.offset = [];\n\tfor (var i = 0; i < e; i++) 0 === this.version ? this.offset[i] = t.readUint32() : this.offset[i] = t.readUint64()\n}),\nBoxParser.createFullBoxCtor("saiz", "SampleAuxiliaryInformationSizesBox",\nfunction(t) {\n\tif (1 & this.flags && (this.aux_info_type = t.readString(4), this.aux_info_type_parameter = t.readUint32()), this.default_sample_info_size = t.readUint8(), this.sample_count = t.readUint32(), this.sample_info_size = [], 0 === this.default_sample_info_size) for (var e = 0; e < this.sample_count; e++) this.sample_info_size[e] = t.readUint8()\n}),\nBoxParser.createSampleEntryCtor(BoxParser.SAMPLE_ENTRY_TYPE_METADATA, "mett",\nfunction(t) {\n\tthis.parseHeader(t),\n\tthis.content_encoding = t.readCString(),\n\tthis.mime_format = t.readCString(),\n\tthis.parseFooter(t)\n}),\nBoxParser.createSampleEntryCtor(BoxParser.SAMPLE_ENTRY_TYPE_METADATA, "metx",\nfunction(t) {\n\tthis.parseHeader(t),\n\tthis.content_encoding = t.readCString(),\n\tthis.namespace = t.readCString(),\n\tthis.schema_location = t.readCString(),\n\tthis.parseFooter(t)\n}),\nBoxParser.createSampleEntryCtor(BoxParser.SAMPLE_ENTRY_TYPE_SUBTITLE, "sbtt",\nfunction(t) {\n\tthis.parseHeader(t),\n\tthis.content_encoding = t.readCString(),\n\tthis.mime_format = t.readCString(),\n\tthis.parseFooter(t)\n}),\nBoxParser.createSampleEntryCtor(BoxParser.SAMPLE_ENTRY_TYPE_SUBTITLE, "stpp",\nfunction(t) {\n\tthis.parseHeader(t),\n\tthis.namespace = t.readCString(),\n\tthis.schema_location = t.readCString(),\n\tthis.auxiliary_mime_types = t.readCString(),\n\tthis.parseFooter(t)\n}),\nBoxParser.createSampleEntryCtor(BoxParser.SAMPLE_ENTRY_TYPE_SUBTITLE, "stxt",\nfunction(t) {\n\tthis.parseHeader(t),\n\tthis.content_encoding = t.readCString(),\n\tthis.mime_format = t.readCString(),\n\tthis.parseFooter(t)\n}),\nBoxParser.createSampleEntryCtor(BoxParser.SAMPLE_ENTRY_TYPE_SUBTITLE, "tx3g",\nfunction(t) {\n\tthis.parseHeader(t),\n\tthis.displayFlags = t.readUint32(),\n\tthis.horizontal_justification = t.readInt8(),\n\tthis.vertical_justification = t.readInt8(),\n\tthis.bg_color_rgba = t.readUint8Array(4),\n\tthis.box_record = t.readInt16Array(4),\n\tthis.style_record = t.readUint8Array(12),\n\tthis.parseFooter(t)\n}),\nBoxParser.createSampleEntryCtor(BoxParser.SAMPLE_ENTRY_TYPE_METADATA, "wvtt",\nfunction(t) {\n\tthis.parseHeader(t),\n\tthis.parseFooter(t)\n}),\nBoxParser.createSampleGroupCtor("alst",\nfunction(t) {\n\tvar e, i = t.readUint16();\n\tfor (this.first_output_sample = t.readUint16(), this.sample_offset = [], e = 0; e < i; e++) this.sample_offset[e] = t.readUint32();\n\tvar r = this.description_length - 4 - 4 * i;\n\tfor (this.num_output_samples = [], this.num_total_samples = [], e = 0; e < r / 4; e++) this.num_output_samples[e] = t.readUint16(),\n\tthis.num_total_samples[e] = t.readUint16()\n}),\nBoxParser.createSampleGroupCtor("avll",\nfunction(t) {\n\tthis.layerNumber = t.readUint8(),\n\tthis.accurateStatisticsFlag = t.readUint8(),\n\tthis.avgBitRate = t.readUint16(),\n\tthis.avgFrameRate = t.readUint16()\n}),\nBoxParser.createSampleGroupCtor("avss",\nfunction(t) {\n\tthis.subSequenceIdentifier = t.readUint16(),\n\tthis.layerNumber = t.readUint8();\n\tvar e = t.readUint8();\n\tthis.durationFlag = e >> 7,\n\tthis.avgRateFlag = e >> 6 & 1,\n\tthis.durationFlag && (this.duration = t.readUint32()),\n\tthis.avgRateFlag && (this.accurateStatisticsFlag = t.readUint8(), this.avgBitRate = t.readUint16(), this.avgFrameRate = t.readUint16()),\n\tthis.dependency = [];\n\tfor (var i = t.readUint8(), r = 0; r < i; r++) {\n\t\tvar s = {};\n\t\tthis.dependency.push(s),\n\t\ts.subSeqDirectionFlag = t.readUint8(),\n\t\ts.layerNumber = t.readUint8(),\n\t\ts.subSequenceIdentifier = t.readUint16()\n\t}\n}),\nBoxParser.createSampleGroupCtor("dtrt",\nfunction(t) {\n\tLog.warn("BoxParser", "Sample Group type: " + this.grouping_type + " not fully parsed")\n}),\nBoxParser.createSampleGroupCtor("mvif",\nfunction(t) {\n\tLog.warn("BoxParser", "Sample Group type: " + this.grouping_type + " not fully parsed")\n}),\nBoxParser.createSampleGroupCtor("prol",\nfunction(t) {\n\tthis.roll_distance = t.readInt16()\n}),\nBoxParser.createSampleGroupCtor("rap ",\nfunction(t) {\n\tt = t.readUint8();\n\tthis.num_leading_samples_known = t >> 7,\n\tthis.num_leading_samples = 127 & t\n}),\nBoxParser.createSampleGroupCtor("rash",\nfunction(t) {\n\tif (this.operation_point_count = t.readUint16(), this.description_length !== 2 + (1 === this.operation_point_count ? 2 : 6 * this.operation_point_count) + 9) Log.warn("BoxParser", "Mismatch in " + this.grouping_type + " sample group length"),\n\tthis.data = t.readUint8Array(this.description_length - 2);\n\telse {\n\t\tif (1 === this.operation_point_count) this.target_rate_share = t.readUint16();\n\t\telse {\n\t\t\tthis.target_rate_share = [],\n\t\t\tthis.available_bitrate = [];\n\t\t\tfor (var e = 0; e < this.operation_point_count; e++) this.available_bitrate[e] = t.readUint32(),\n\t\t\tthis.target_rate_share[e] = t.readUint16()\n\t\t}\n\t\tthis.maximum_bitrate = t.readUint32(),\n\t\tthis.minimum_bitrate = t.readUint32(),\n\t\tthis.discard_priority = t.readUint8()\n\t}\n}),\nBoxParser.createSampleGroupCtor("roll",\nfunction(t) {\n\tthis.roll_distance = t.readInt16()\n}),\nBoxParser.SampleGroupEntry.prototype.parse = function(t) {\n\tLog.warn("BoxParser", "Unknown Sample Group type: " + this.grouping_type),\n\tthis.data = t.readUint8Array(this.description_length)\n},\nBoxParser.createSampleGroupCtor("scif",\nfunction(t) {\n\tLog.warn("BoxParser", "Sample Group type: " + this.grouping_type + " not fully parsed")\n}),\nBoxParser.createSampleGroupCtor("scnm",\nfunction(t) {\n\tLog.warn("BoxParser", "Sample Group type: " + this.grouping_type + " not fully parsed")\n}),\nBoxParser.createSampleGroupCtor("seig",\nfunction(t) {\n\tthis.reserved = t.readUint8();\n\tvar e = t.readUint8();\n\tthis.crypt_byte_block = e >> 4,\n\tthis.skip_byte_block = 15 & e,\n\tthis.isProtected = t.readUint8(),\n\tthis.Per_Sample_IV_Size = t.readUint8(),\n\tthis.KID = BoxParser.parseHex16(t),\n\tthis.constant_IV_size = 0,\n\tthis.constant_IV = 0,\n\t1 === this.isProtected && 0 === this.Per_Sample_IV_Size && (this.constant_IV_size = t.readUint8(), this.constant_IV = t.readUint8Array(this.constant_IV_size))\n}),\nBoxParser.createSampleGroupCtor("stsa",\nfunction(t) {\n\tLog.warn("BoxParser", "Sample Group type: " + this.grouping_type + " not fully parsed")\n}),\nBoxParser.createSampleGroupCtor("sync",\nfunction(t) {\n\tt = t.readUint8();\n\tthis.NAL_unit_type = 63 & t\n}),\nBoxParser.createSampleGroupCtor("tele",\nfunction(t) {\n\tt = t.readUint8();\n\tthis.level_independently_decodable = t >> 7\n}),\nBoxParser.createSampleGroupCtor("tsas",\nfunction(t) {\n\tLog.warn("BoxParser", "Sample Group type: " + this.grouping_type + " not fully parsed")\n}),\nBoxParser.createSampleGroupCtor("tscl",\nfunction(t) {\n\tLog.warn("BoxParser", "Sample Group type: " + this.grouping_type + " not fully parsed")\n}),\nBoxParser.createSampleGroupCtor("vipr",\nfunction(t) {\n\tLog.warn("BoxParser", "Sample Group type: " + this.grouping_type + " not fully parsed")\n}),\nBoxParser.createFullBoxCtor("sbgp", "SampleToGroupBox",\nfunction(t) {\n\tthis.grouping_type = t.readString(4),\n\t1 === this.version ? this.grouping_type_parameter = t.readUint32() : this.grouping_type_parameter = 0,\n\tthis.entries = [];\n\tfor (var e = t.readUint32(), i = 0; i < e; i++) {\n\t\tvar r = {};\n\t\tthis.entries.push(r),\n\t\tr.sample_count = t.readInt32(),\n\t\tr.group_description_index = t.readInt32()\n\t}\n}),\nPixel.prototype.toString = function() {\n\treturn "[row: " + this.bad_pixel_row + ", column: " + this.bad_pixel_column + "]"\n},\nBoxParser.createFullBoxCtor("sbpm", "SensorBadPixelsMapBox",\nfunction(t) {\n\tvar e;\n\tfor (this.component_count = t.readUint16(), this.component_index = [], e = 0; e < this.component_count; e++) this.component_index.push(t.readUint16());\n\tvar i = t.readUint8();\n\tfor (this.correction_applied = 128 == (128 & i), this.num_bad_rows = t.readUint32(), this.num_bad_cols = t.readUint32(), this.num_bad_pixels = t.readUint32(), this.bad_rows = [], this.bad_columns = [], this.bad_pixels = [], e = 0; e < this.num_bad_rows; e++) this.bad_rows.push(t.readUint32());\n\tfor (e = 0; e < this.num_bad_cols; e++) this.bad_columns.push(t.readUint32());\n\tfor (e = 0; e < this.num_bad_pixels; e++) {\n\t\tvar r = t.readUint32(),\n\t\ts = t.readUint32();\n\t\tthis.bad_pixels.push(new Pixel(r, s))\n\t}\n}),\nBoxParser.createFullBoxCtor("schm", "SchemeTypeBox",\nfunction(t) {\n\tthis.scheme_type = t.readString(4),\n\tthis.scheme_version = t.readUint32(),\n\t1 & this.flags && (this.scheme_uri = t.readString(this.size - this.hdr_size - 8))\n}),\nBoxParser.createBoxCtor("sdp ", "rtptracksdphintinformation",\nfunction(t) {\n\tthis.sdptext = t.readString(this.size - this.hdr_size)\n}),\nBoxParser.createFullBoxCtor("sdtp", "SampleDependencyTypeBox",\nfunction(t) {\n\tvar e, i = this.size - this.hdr_size;\n\tthis.is_leading = [],\n\tthis.sample_depends_on = [],\n\tthis.sample_is_depended_on = [],\n\tthis.sample_has_redundancy = [];\n\tfor (var r = 0; r < i; r++) e = t.readUint8(),\n\tthis.is_leading[r] = e >> 6,\n\tthis.sample_depends_on[r] = e >> 4 & 3,\n\tthis.sample_is_depended_on[r] = e >> 2 & 3,\n\tthis.sample_has_redundancy[r] = 3 & e\n}),\nBoxParser.createFullBoxCtor("senc", "SampleEncryptionBox"),\nBoxParser.createFullBoxCtor("sgpd", "SampleGroupDescriptionBox",\nfunction(t) {\n\tthis.grouping_type = t.readString(4),\n\tLog.debug("BoxParser", "Found Sample Groups of type " + this.grouping_type),\n\t1 === this.version ? this.default_length = t.readUint32() : this.default_length = 0,\n\t2 <= this.version && (this.default_group_description_index = t.readUint32()),\n\tthis.entries = [];\n\tfor (var e = t.readUint32(), i = 0; i < e; i++) {\n\t\tvar r = new(BoxParser[this.grouping_type + "SampleGroupEntry"] ? BoxParser[this.grouping_type + "SampleGroupEntry"] : BoxParser.SampleGroupEntry)(this.grouping_type);\n\t\tthis.entries.push(r),\n\t\t1 === this.version && 0 === this.default_length ? r.description_length = t.readUint32() : r.description_length = this.default_length,\n\t\tr.write === BoxParser.SampleGroupEntry.prototype.write && (Log.info("BoxParser", "SampleGroup for type " + this.grouping_type + " writing not yet implemented, keeping unparsed data in memory for later write"), r.data = t.readUint8Array(r.description_length), t.position -= r.description_length),\n\t\tr.parse(t)\n\t}\n}),\nBoxParser.createFullBoxCtor("sidx", "CompressedSegmentIndexBox",\nfunction(t) {\n\tthis.reference_ID = t.readUint32(),\n\tthis.timescale = t.readUint32(),\n\t0 === this.version ? (this.earliest_presentation_time = t.readUint32(), this.first_offset = t.readUint32()) : (this.earliest_presentation_time = t.readUint64(), this.first_offset = t.readUint64()),\n\tt.readUint16(),\n\tthis.references = [];\n\tfor (var e = t.readUint16(), i = 0; i < e; i++) {\n\t\tvar r = {};\n\t\tthis.references.push(r);\n\t\tvar s = t.readUint32();\n\t\tr.reference_type = s >> 31 & 1,\n\t\tr.referenced_size = 2147483647 & s,\n\t\tr.subsegment_duration = t.readUint32(),\n\t\ts = t.readUint32(),\n\t\tr.starts_with_SAP = s >> 31 & 1,\n\t\tr.SAP_type = s >> 28 & 7,\n\t\tr.SAP_delta_time = 268435455 & s\n\t}\n}),\nBoxParser.SingleItemTypeReferenceBox = function(t, e, i, r) {\n\tBoxParser.Box.call(this, t, e),\n\tthis.hdr_size = i,\n\tthis.start = r\n},\nBoxParser.SingleItemTypeReferenceBox.prototype = new BoxParser.Box,\nBoxParser.SingleItemTypeReferenceBox.prototype.parse = function(t) {\n\tthis.from_item_ID = t.readUint16();\n\tvar e = t.readUint16();\n\tthis.references = [];\n\tfor (var i = 0; i < e; i++) this.references[i] = {},\n\tthis.references[i].to_item_ID = t.readUint16()\n},\nBoxParser.SingleItemTypeReferenceBoxLarge = function(t, e, i, r) {\n\tBoxParser.Box.call(this, t, e),\n\tthis.hdr_size = i,\n\tthis.start = r\n},\nBoxParser.SingleItemTypeReferenceBoxLarge.prototype = new BoxParser.Box,\nBoxParser.SingleItemTypeReferenceBoxLarge.prototype.parse = function(t) {\n\tthis.from_item_ID = t.readUint32();\n\tvar e = t.readUint16();\n\tthis.references = [];\n\tfor (var i = 0; i < e; i++) this.references[i] = {},\n\tthis.references[i].to_item_ID = t.readUint32()\n},\nBoxParser.createFullBoxCtor("SmDm", "SMPTE2086MasteringDisplayMetadataBox",\nfunction(t) {\n\tthis.primaryRChromaticity_x = t.readUint16(),\n\tthis.primaryRChromaticity_y = t.readUint16(),\n\tthis.primaryGChromaticity_x = t.readUint16(),\n\tthis.primaryGChromaticity_y = t.readUint16(),\n\tthis.primaryBChromaticity_x = t.readUint16(),\n\tthis.primaryBChromaticity_y = t.readUint16(),\n\tthis.whitePointChromaticity_x = t.readUint16(),\n\tthis.whitePointChromaticity_y = t.readUint16(),\n\tthis.luminanceMax = t.readUint32(),\n\tthis.luminanceMin = t.readUint32()\n}),\nBoxParser.createFullBoxCtor("smhd", "SoundMediaHeaderBox",\nfunction(t) {\n\tthis.balance = t.readUint16(),\n\tt.readUint16()\n}),\nBoxParser.createFullBoxCtor("ssix", "CompressedSubsegmentIndexBox",\nfunction(t) {\n\tthis.subsegments = [];\n\tfor (var e = t.readUint32(), i = 0; i < e; i++) {\n\t\tvar r = {};\n\t\tthis.subsegments.push(r),\n\t\tr.ranges = [];\n\t\tfor (var s = t.readUint32(), a = 0; a < s; a++) {\n\t\t\tvar n = {};\n\t\t\tr.ranges.push(n),\n\t\t\tn.level = t.readUint8(),\n\t\t\tn.range_size = t.readUint24()\n\t\t}\n\t}\n}),\nBoxParser.createFullBoxCtor("stco", "ChunkOffsetBox",\nfunction(t) {\n\tvar e = t.readUint32();\n\tif (this.chunk_offsets = [], 0 === this.version) for (var i = 0; i < e; i++) this.chunk_offsets.push(t.readUint32())\n}),\nBoxParser.createFullBoxCtor("stdp", "DegradationPriorityBox",\nfunction(t) {\n\tvar e = (this.size - this.hdr_size) / 2;\n\tthis.priority = [];\n\tfor (var i = 0; i < e; i++) this.priority[i] = t.readUint16()\n}),\nBoxParser.createFullBoxCtor("sthd", "SubtitleMediaHeaderBox"),\nBoxParser.createFullBoxCtor("stri", "SubTrackInformationBox",\nfunction(t) {\n\tthis.switch_group = t.readUint16(),\n\tthis.alternate_group = t.readUint16(),\n\tthis.sub_track_id = t.readUint32();\n\tvar e = (this.size - this.hdr_size - 8) / 4;\n\tthis.attribute_list = [];\n\tfor (var i = 0; i < e; i++) this.attribute_list[i] = t.readUint32()\n}),\nBoxParser.createFullBoxCtor("stsc", "SampleToChunkBox",\nfunction(t) {\n\tvar e, i = t.readUint32();\n\tif (this.first_chunk = [], this.samples_per_chunk = [], this.sample_description_index = [], 0 === this.version) for (e = 0; e < i; e++) this.first_chunk.push(t.readUint32()),\n\tthis.samples_per_chunk.push(t.readUint32()),\n\tthis.sample_description_index.push(t.readUint32())\n}),\nBoxParser.createFullBoxCtor("stsd", "SampleDescriptionBox",\nfunction(t) {\n\tvar e, i, r, s;\n\tfor (this.entries = [], r = t.readUint32(), e = 1; e <= r; e++) {\n\t\tif ((i = BoxParser.parseOneBox(t, !0, this.size - (t.getPosition() - this.start))).code !== BoxParser.OK) return;\n\t\tBoxParser[i.type + "SampleEntry"] ? ((s = new BoxParser[i.type + "SampleEntry"](i.size)).hdr_size = i.hdr_size, s.start = i.start) : (Log.warn("BoxParser", "Unknown sample entry type: " + i.type), s = new BoxParser.SampleEntry(i.type, i.size, i.hdr_size, i.start)),\n\t\ts.write === BoxParser.SampleEntry.prototype.write && (Log.info("BoxParser", "SampleEntry " + s.type + " box writing not yet implemented, keeping unparsed data in memory for later write"), s.parseDataAndRewind(t)),\n\t\ts.parse(t),\n\t\tthis.entries.push(s)\n\t}\n}),\nBoxParser.createFullBoxCtor("stsg", "SubTrackSampleGroupBox",\nfunction(t) {\n\tthis.grouping_type = t.readUint32();\n\tvar e = t.readUint16();\n\tthis.group_description_index = [];\n\tfor (var i = 0; i < e; i++) this.group_description_index[i] = t.readUint32()\n}),\nBoxParser.createFullBoxCtor("stsh", "ShadowSyncSampleBox",\nfunction(t) {\n\tvar e, i = t.readUint32();\n\tif (this.shadowed_sample_numbers = [], this.sync_sample_numbers = [], 0 === this.version) for (e = 0; e < i; e++) this.shadowed_sample_numbers.push(t.readUint32()),\n\tthis.sync_sample_numbers.push(t.readUint32())\n}),\nBoxParser.createFullBoxCtor("stss", "SyncSampleBox",\nfunction(t) {\n\tvar e, i = t.readUint32();\n\tif (0 === this.version) for (this.sample_numbers = [], e = 0; e < i; e++) this.sample_numbers.push(t.readUint32())\n}),\nBoxParser.createFullBoxCtor("stsz", "SampleSizeBox",\nfunction(t) {\n\tvar e;\n\tif (this.sample_sizes = [], 0 === this.version) for (this.sample_size = t.readUint32(), this.sample_count = t.readUint32(), e = 0; e < this.sample_count; e++) 0 === this.sample_size ? this.sample_sizes.push(t.readUint32()) : this.sample_sizes[e] = this.sample_size\n}),\nBoxParser.createFullBoxCtor("stts", "TimeToSampleBox",\nfunction(t) {\n\tvar e, i, r = t.readUint32();\n\tif (this.sample_counts = [], this.sample_deltas = [], 0 === this.version) for (e = 0; e < r; e++) this.sample_counts.push(t.readUint32()),\n\t(i = t.readInt32()) < 0 && (Log.warn("BoxParser", "File uses negative stts sample delta, using value 1 instead, sync may be lost!"), i = 1),\n\tthis.sample_deltas.push(i)\n}),\nBoxParser.createFullBoxCtor("stvi", "StereoVideoBox",\nfunction(t) {\n\tvar e = t.readUint32();\n\tthis.single_view_allowed = 3 & e,\n\tthis.stereo_scheme = t.readUint32();\n\tvar i, e = t.readUint32();\n\tfor (this.stereo_indication_type = t.readString(e), this.boxes = []; t.getPosition() < this.start + this.size;) {\n\t\tif ((i = BoxParser.parseOneBox(t, !1, this.size - (t.getPosition() - this.start))).code !== BoxParser.OK) return;\n\t\ti = i.box,\n\t\tthis.boxes.push(i),\n\t\tthis[i.type] = i\n\t}\n}),\nBoxParser.createBoxCtor("styp", "SegmentTypeBox",\nfunction(t) {\n\tBoxParser.ftypBox.prototype.parse.call(this, t)\n}),\nBoxParser.createFullBoxCtor("stz2", "CompactSampleSizeBox",\nfunction(t) {\n\tvar e, i;\n\tif (this.sample_sizes = [], 0 === this.version) if (this.reserved = t.readUint24(), this.field_size = t.readUint8(), i = t.readUint32(), 4 === this.field_size) for (e = 0; e < i; e += 2) {\n\t\tvar r = t.readUint8();\n\t\tthis.sample_sizes[e] = r >> 4 & 15,\n\t\tthis.sample_sizes[e + 1] = 15 & r\n\t} else if (8 === this.field_size) for (e = 0; e < i; e++) this.sample_sizes[e] = t.readUint8();\n\telse if (16 === this.field_size) for (e = 0; e < i; e++) this.sample_sizes[e] = t.readUint16();\n\telse Log.error("BoxParser", "Error in length field in stz2 box")\n}),\nBoxParser.createFullBoxCtor("subs", "SubSampleInformationBox",\nfunction(t) {\n\tvar e, i, r, s = t.readUint32();\n\tfor (this.entries = [], e = 0; e < s; e++) {\n\t\tvar a = {};\n\t\tif ((this.entries[e] = a).sample_delta = t.readUint32(), a.subsamples = [], 0 < (r = t.readUint16())) for (i = 0; i < r; i++) {\n\t\t\tvar n = {};\n\t\t\ta.subsamples.push(n),\n\t\t\t1 == this.version ? n.size = t.readUint32() : n.size = t.readUint16(),\n\t\t\tn.priority = t.readUint8(),\n\t\t\tn.discardable = t.readUint8(),\n\t\t\tn.codec_specific_parameters = t.readUint32()\n\t\t}\n\t}\n}),\nBoxParser.createFullBoxCtor("tenc", "TrackEncryptionBox",\nfunction(t) {\n\tvar e;\n\tt.readUint8(),\n\t0 === this.version ? t.readUint8() : (e = t.readUint8(), this.default_crypt_byte_block = e >> 4 & 15, this.default_skip_byte_block = 15 & e),\n\tthis.default_isProtected = t.readUint8(),\n\tthis.default_Per_Sample_IV_Size = t.readUint8(),\n\tthis.default_KID = BoxParser.parseHex16(t),\n\t1 === this.default_isProtected && 0 === this.default_Per_Sample_IV_Size && (this.default_constant_IV_size = t.readUint8(), this.default_constant_IV = t.readUint8Array(this.default_constant_IV_size))\n}),\nBoxParser.createFullBoxCtor("tfdt", "TrackFragmentBaseMediaDecodeTimeBox",\nfunction(t) {\n\t1 == this.version ? this.baseMediaDecodeTime = t.readUint64() : this.baseMediaDecodeTime = t.readUint32()\n}),\nBoxParser.createFullBoxCtor("tfhd", "TrackFragmentHeaderBox",\nfunction(t) {\n\tvar e = 0;\n\tthis.track_id = t.readUint32(),\n\tthis.size - this.hdr_size > e && this.flags & BoxParser.TFHD_FLAG_BASE_DATA_OFFSET ? (this.base_data_offset = t.readUint64(), e += 8) : this.base_data_offset = 0,\n\tthis.size - this.hdr_size > e && this.flags & BoxParser.TFHD_FLAG_SAMPLE_DESC ? (this.default_sample_description_index = t.readUint32(), e += 4) : this.default_sample_description_index = 0,\n\tthis.size - this.hdr_size > e && this.flags & BoxParser.TFHD_FLAG_SAMPLE_DUR ? (this.default_sample_duration = t.readUint32(), e += 4) : this.default_sample_duration = 0,\n\tthis.size - this.hdr_size > e && this.flags & BoxParser.TFHD_FLAG_SAMPLE_SIZE ? (this.default_sample_size = t.readUint32(), e += 4) : this.default_sample_size = 0,\n\tthis.size - this.hdr_size > e && this.flags & BoxParser.TFHD_FLAG_SAMPLE_FLAGS ? (this.default_sample_flags = t.readUint32(), e += 4) : this.default_sample_flags = 0\n}),\nBoxParser.createFullBoxCtor("tfra", "TrackFragmentRandomAccessBox",\nfunction(t) {\n\tthis.track_ID = t.readUint32(),\n\tt.readUint24();\n\tvar e = t.readUint8();\n\tthis.length_size_of_traf_num = e >> 4 & 3,\n\tthis.length_size_of_trun_num = e >> 2 & 3,\n\tthis.length_size_of_sample_num = 3 & e,\n\tthis.entries = [];\n\tfor (var i = t.readUint32(), r = 0; r < i; r++) 1 === this.version ? (this.time = t.readUint64(), this.moof_offset = t.readUint64()) : (this.time = t.readUint32(), this.moof_offset = t.readUint32()),\n\tthis.traf_number = t["readUint" + 8 * (this.length_size_of_traf_num + 1)](),\n\tthis.trun_number = t["readUint" + 8 * (this.length_size_of_trun_num + 1)](),\n\tthis.sample_number = t["readUint" + 8 * (this.length_size_of_sample_num + 1)]()\n}),\nBoxParser.createFullBoxCtor("tkhd", "TrackHeaderBox",\nfunction(t) {\n\t1 == this.version ? (this.creation_time = t.readUint64(), this.modification_time = t.readUint64(), this.track_id = t.readUint32(), t.readUint32(), this.duration = t.readUint64()) : (this.creation_time = t.readUint32(), this.modification_time = t.readUint32(), this.track_id = t.readUint32(), t.readUint32(), this.duration = t.readUint32()),\n\tt.readUint32Array(2),\n\tthis.layer = t.readInt16(),\n\tthis.alternate_group = t.readInt16(),\n\tthis.volume = t.readInt16() >> 8,\n\tt.readUint16(),\n\tthis.matrix = t.readInt32Array(9),\n\tthis.width = t.readUint32(),\n\tthis.height = t.readUint32()\n}),\nBoxParser.createBoxCtor("tmax", "hintmaxrelativetime",\nfunction(t) {\n\tthis.time = t.readUint32()\n}),\nBoxParser.createBoxCtor("tmin", "hintminrelativetime",\nfunction(t) {\n\tthis.time = t.readUint32()\n}),\nBoxParser.createBoxCtor("totl", "hintBytesSent",\nfunction(t) {\n\tthis.bytessent = t.readUint32()\n}),\nBoxParser.createBoxCtor("tpay", "hintBytesSent",\nfunction(t) {\n\tthis.bytessent = t.readUint32()\n}),\nBoxParser.createBoxCtor("tpyl", "hintBytesSent",\nfunction(t) {\n\tthis.bytessent = t.readUint64()\n}),\nBoxParser.TrackGroupTypeBox.prototype.parse = function(t) {\n\tthis.parseFullHeader(t),\n\tthis.track_group_id = t.readUint32()\n},\nBoxParser.createTrackGroupCtor("msrc"),\nBoxParser.TrackReferenceTypeBox = function(t, e, i, r) {\n\tBoxParser.Box.call(this, t, e),\n\tthis.hdr_size = i,\n\tthis.start = r\n},\nBoxParser.TrackReferenceTypeBox.prototype = new BoxParser.Box,\nBoxParser.TrackReferenceTypeBox.prototype.parse = function(t) {\n\tthis.track_ids = t.readUint32Array((this.size - this.hdr_size) / 4)\n},\nBoxParser.trefBox.prototype.parse = function(t) {\n\tfor (var e; t.getPosition() < this.start + this.size;) {\n\t\tif ((e = BoxParser.parseOneBox(t, !0, this.size - (t.getPosition() - this.start))).code !== BoxParser.OK) return; (e = new BoxParser.TrackReferenceTypeBox(e.type, e.size, e.hdr_size, e.start)).write === BoxParser.Box.prototype.write && "mdat" !== e.type && (Log.info("BoxParser", "TrackReference " + e.type + " box writing not yet implemented, keeping unparsed data in memory for later write"), e.parseDataAndRewind(t)),\n\t\te.parse(t),\n\t\tthis.boxes.push(e)\n\t}\n},\nBoxParser.createFullBoxCtor("trep", "TrackExtensionPropertiesBox",\nfunction(t) {\n\tfor (this.track_ID = t.readUint32(), this.boxes = []; t.getPosition() < this.start + this.size;) {\n\t\tif (ret = BoxParser.parseOneBox(t, !1, this.size - (t.getPosition() - this.start)), ret.code !== BoxParser.OK) return;\n\t\tbox = ret.box,\n\t\tthis.boxes.push(box)\n\t}\n}),\nBoxParser.createFullBoxCtor("trex", "TrackExtendsBox",\nfunction(t) {\n\tthis.track_id = t.readUint32(),\n\tthis.default_sample_description_index = t.readUint32(),\n\tthis.default_sample_duration = t.readUint32(),\n\tthis.default_sample_size = t.readUint32(),\n\tthis.default_sample_flags = t.readUint32()\n}),\nBoxParser.createBoxCtor("trpy", "hintBytesSent",\nfunction(t) {\n\tthis.bytessent = t.readUint64()\n}),\nBoxParser.createFullBoxCtor("trun", "TrackRunBox",\nfunction(t) {\n\tvar e = 0;\n\tif (this.sample_count = t.readUint32(), e += 4, this.size - this.hdr_size > e && this.flags & BoxParser.TRUN_FLAGS_DATA_OFFSET ? (this.data_offset = t.readInt32(), e += 4) : this.data_offset = 0, this.size - this.hdr_size > e && this.flags & BoxParser.TRUN_FLAGS_FIRST_FLAG ? (this.first_sample_flags = t.readUint32(), e += 4) : this.first_sample_flags = 0, this.sample_duration = [], this.sample_size = [], this.sample_flags = [], this.sample_composition_time_offset = [], this.size - this.hdr_size > e) for (var i = 0; i < this.sample_count; i++) this.flags & BoxParser.TRUN_FLAGS_DURATION && (this.sample_duration[i] = t.readUint32()),\n\tthis.flags & BoxParser.TRUN_FLAGS_SIZE && (this.sample_size[i] = t.readUint32()),\n\tthis.flags & BoxParser.TRUN_FLAGS_FLAGS && (this.sample_flags[i] = t.readUint32()),\n\tthis.flags & BoxParser.TRUN_FLAGS_CTS_OFFSET && (0 === this.version ? this.sample_composition_time_offset[i] = t.readUint32() : this.sample_composition_time_offset[i] = t.readInt32())\n}),\nBoxParser.createFullBoxCtor("tsel", "TrackSelectionBox",\nfunction(t) {\n\tthis.switch_group = t.readUint32();\n\tvar e = (this.size - this.hdr_size - 4) / 4;\n\tthis.attribute_list = [];\n\tfor (var i = 0; i < e; i++) this.attribute_list[i] = t.readUint32()\n}),\nBoxParser.createFullBoxCtor("txtC", "TextConfigBox",\nfunction(t) {\n\tthis.config = t.readCString()\n}),\nBoxParser.createBoxCtor("tyco", "TypeCombinationBox",\nfunction(t) {\n\tvar e = (this.size - this.hdr_size) / 4;\n\tthis.compatible_brands = [];\n\tfor (var i = 0; i < e; i++) this.compatible_brands[i] = t.readString(4)\n}),\nBoxParser.createFullBoxCtor("udes", "UserDescriptionProperty",\nfunction(t) {\n\tthis.lang = t.readCString(),\n\tthis.name = t.readCString(),\n\tthis.description = t.readCString(),\n\tthis.tags = t.readCString()\n}),\nBoxParser.createFullBoxCtor("uncC", "UncompressedFrameConfigBox",\nfunction(t) {\n\tvar e;\n\tif (this.profile = t.readString(4), 1 != this.version && 0 == this.version) {\n\t\tfor (this.component_count = t.readUint32(), this.component_index = [], this.component_bit_depth_minus_one = [], this.component_format = [], this.component_align_size = [], e = 0; e < this.component_count; e++) this.component_index.push(t.readUint16()),\n\t\tthis.component_bit_depth_minus_one.push(t.readUint8()),\n\t\tthis.component_format.push(t.readUint8()),\n\t\tthis.component_align_size.push(t.readUint8());\n\t\tthis.sampling_type = t.readUint8(),\n\t\tthis.interleave_type = t.readUint8(),\n\t\tthis.block_size = t.readUint8();\n\t\tvar i = t.readUint8();\n\t\tthis.component_little_endian = i >> 7 & 1,\n\t\tthis.block_pad_lsb = i >> 6 & 1,\n\t\tthis.block_little_endian = i >> 5 & 1,\n\t\tthis.block_reversed = i >> 4 & 1,\n\t\tthis.pad_unknown = i >> 3 & 1,\n\t\tthis.pixel_size = t.readUint32(),\n\t\tthis.row_align_size = t.readUint32(),\n\t\tthis.tile_align_size = t.readUint32(),\n\t\tthis.num_tile_cols_minus_one = t.readUint32(),\n\t\tthis.num_tile_rows_minus_one = t.readUint32()\n\t}\n}),\nBoxParser.createFullBoxCtor("url ", "DataEntryUrlBox",\nfunction(t) {\n\t1 !== this.flags && (this.location = t.readCString())\n}),\nBoxParser.createFullBoxCtor("urn ", "DataEntryUrnBox",\nfunction(t) {\n\tthis.name = t.readCString(),\n\t0 < this.size - this.hdr_size - this.name.length - 1 && (this.location = t.readCString())\n}),\nBoxParser.createUUIDBox("a5d40b30e81411ddba2f0800200c9a66", "LiveServerManifestBox", !0, !1,\nfunction(t) {\n\tthis.LiveServerManifest = t.readString(this.size - this.hdr_size).replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;").replace(/"/g, "&quot;").replace(/\'/g, "&#039;")\n}),\nBoxParser.createUUIDBox("d08a4f1810f34a82b6c832d8aba183d3", "PiffProtectionSystemSpecificHeaderBox", !0, !1,\nfunction(t) {\n\tthis.system_id = BoxParser.parseHex16(t);\n\tvar e = t.readUint32();\n\t0 < e && (this.data = t.readUint8Array(e))\n}),\nBoxParser.createUUIDBox("a2394f525a9b4f14a2446c427c648df4", "PiffSampleEncryptionBox", !0, !1),\nBoxParser.createUUIDBox("8974dbce7be74c5184f97148f9882554", "PiffTrackEncryptionBox", !0, !1,\nfunction(t) {\n\tthis.default_AlgorithmID = t.readUint24(),\n\tthis.default_IV_size = t.readUint8(),\n\tthis.default_KID = BoxParser.parseHex16(t)\n}),\nBoxParser.createUUIDBox("d4807ef2ca3946958e5426cb9e46a79f", "TfrfBox", !0, !1,\nfunction(t) {\n\tthis.fragment_count = t.readUint8(),\n\tthis.entries = [];\n\tfor (var e = 0; e < this.fragment_count; e++) {\n\t\tvar i = {},\n\t\tr = 0,\n\t\ts = 0,\n\t\ts = 1 === this.version ? (r = t.readUint64(), t.readUint64()) : (r = t.readUint32(), t.readUint32());\n\t\ti.absolute_time = r,\n\t\ti.absolute_duration = s,\n\t\tthis.entries.push(i)\n\t}\n}),\nBoxParser.createUUIDBox("6d1d9b0542d544e680e2141daff757b2", "TfxdBox", !0, !1,\nfunction(t) {\n\t1 === this.version ? (this.absolute_time = t.readUint64(), this.duration = t.readUint64()) : (this.absolute_time = t.readUint32(), this.duration = t.readUint32())\n}),\nBoxParser.createFullBoxCtor("vmhd", "VideoMediaHeaderBox",\nfunction(t) {\n\tthis.graphicsmode = t.readUint16(),\n\tthis.opcolor = t.readUint16Array(3)\n}),\nBoxParser.createFullBoxCtor("vpcC", "VPCodecConfigurationRecord",\nfunction(t) {\n\tvar e;\n\t1 === this.version ? (this.profile = t.readUint8(), this.level = t.readUint8(), e = t.readUint8(), this.bitDepth = e >> 4, this.chromaSubsampling = e >> 1 & 7, this.videoFullRangeFlag = 1 & e, this.colourPrimaries = t.readUint8(), this.transferCharacteristics = t.readUint8(), this.matrixCoefficients = t.readUint8()) : (this.profile = t.readUint8(), this.level = t.readUint8(), e = t.readUint8(), this.bitDepth = e >> 4 & 15, this.colorSpace = 15 & e, e = t.readUint8(), this.chromaSubsampling = e >> 4 & 15, this.transferFunction = e >> 1 & 7, this.videoFullRangeFlag = 1 & e),\n\tthis.codecIntializationDataSize = t.readUint16(),\n\tthis.codecIntializationData = t.readUint8Array(this.codecIntializationDataSize)\n}),\nBoxParser.createBoxCtor("vttC", "WebVTTConfigurationBox",\nfunction(t) {\n\tthis.text = t.readString(this.size - this.hdr_size)\n}),\nBoxParser.createFullBoxCtor("vvcC", "VvcConfigurationBox",\nfunction(t) {\n\tvar e, i = {\n\t\theld_bits: void 0,\n\t\tnum_held_bits: 0,\n\t\tstream_read_1_bytes: function(t) {\n\t\t\tthis.held_bits = t.readUint8(),\n\t\t\tthis.num_held_bits = 8\n\t\t},\n\t\tstream_read_2_bytes: function(t) {\n\t\t\tthis.held_bits = t.readUint16(),\n\t\t\tthis.num_held_bits = 16\n\t\t},\n\t\textract_bits: function(t) {\n\t\t\tvar e = this.held_bits >> this.num_held_bits - t & (1 << t) - 1;\n\t\t\treturn this.num_held_bits -= t,\n\t\t\te\n\t\t}\n\t};\n\tif (i.stream_read_1_bytes(t), i.extract_bits(5), this.lengthSizeMinusOne = i.extract_bits(2), this.ptl_present_flag = i.extract_bits(1), this.ptl_present_flag) {\n\t\tif (i.stream_read_2_bytes(t), this.ols_idx = i.extract_bits(9), this.num_sublayers = i.extract_bits(3), this.constant_frame_rate = i.extract_bits(2), this.chroma_format_idc = i.extract_bits(2), i.stream_read_1_bytes(t), this.bit_depth_minus8 = i.extract_bits(3), i.extract_bits(5), i.stream_read_2_bytes(t), i.extract_bits(2), this.num_bytes_constraint_info = i.extract_bits(6), this.general_profile_idc = i.extract_bits(7), this.general_tier_flag = i.extract_bits(1), this.general_level_idc = t.readUint8(), i.stream_read_1_bytes(t), this.ptl_frame_only_constraint_flag = i.extract_bits(1), this.ptl_multilayer_enabled_flag = i.extract_bits(1), this.general_constraint_info = new Uint8Array(this.num_bytes_constraint_info), this.num_bytes_constraint_info) {\n\t\t\tfor (o = 0; o < this.num_bytes_constraint_info - 1; o++) {\n\t\t\t\tvar r = i.extract_bits(6);\n\t\t\t\ti.stream_read_1_bytes(t);\n\t\t\t\tvar s = i.extract_bits(2);\n\t\t\t\tthis.general_constraint_info[o] = r << 2 | s\n\t\t\t}\n\t\t\tthis.general_constraint_info[this.num_bytes_constraint_info - 1] = i.extract_bits(6)\n\t\t} else i.extract_bits(6);\n\t\tif (1 < this.num_sublayers) {\n\t\t\tfor (i.stream_read_1_bytes(t), this.ptl_sublayer_present_mask = 0, e = this.num_sublayers - 2; 0 <= e; --e) {\n\t\t\t\tvar a = i.extract_bits(1);\n\t\t\t\tthis.ptl_sublayer_present_mask |= a << e\n\t\t\t}\n\t\t\tfor (e = this.num_sublayers; e <= 8 && 1 < this.num_sublayers; ++e) i.extract_bits(1);\n\t\t\tfor (this.sublayer_level_idc = [], e = this.num_sublayers - 2; 0 <= e; --e) this.ptl_sublayer_present_mask & 1 << e && (this.sublayer_level_idc[e] = t.readUint8())\n\t\t}\n\t\tif (this.ptl_num_sub_profiles = t.readUint8(), this.general_sub_profile_idc = [], this.ptl_num_sub_profiles) for (o = 0; o < this.ptl_num_sub_profiles; o++) this.general_sub_profile_idc.push(t.readUint32());\n\t\tthis.max_picture_width = t.readUint16(),\n\t\tthis.max_picture_height = t.readUint16(),\n\t\tthis.avg_frame_rate = t.readUint16()\n\t}\n\tthis.nalu_arrays = [];\n\tfor (var n = t.readUint8(), o = 0; o < n; o++) {\n\t\tvar h = [];\n\t\tthis.nalu_arrays.push(h),\n\t\ti.stream_read_1_bytes(t),\n\t\th.completeness = i.extract_bits(1),\n\t\ti.extract_bits(2),\n\t\th.nalu_type = i.extract_bits(5);\n\t\tvar d = 1;\n\t\tfor (13 != h.nalu_type && 12 != h.nalu_type && (d = t.readUint16()), e = 0; e < d; e++) {\n\t\t\tvar l = t.readUint16();\n\t\t\th.push({\n\t\t\t\tdata: t.readUint8Array(l),\n\t\t\t\tlength: l\n\t\t\t})\n\t\t}\n\t}\n}),\nBoxParser.createFullBoxCtor("vvnC", "VvcNALUConfigBox",\nfunction(t) {\n\tvar e = strm.readUint8();\n\tthis.lengthSizeMinusOne = 3 & e\n}),\nBoxParser.SampleEntry.prototype.isVideo = function() {\n\treturn ! 1\n},\nBoxParser.SampleEntry.prototype.isAudio = function() {\n\treturn ! 1\n},\nBoxParser.SampleEntry.prototype.isSubtitle = function() {\n\treturn ! 1\n},\nBoxParser.SampleEntry.prototype.isMetadata = function() {\n\treturn ! 1\n},\nBoxParser.SampleEntry.prototype.isHint = function() {\n\treturn ! 1\n},\nBoxParser.SampleEntry.prototype.getCodec = function() {\n\treturn this.type.replace(".", "")\n},\nBoxParser.SampleEntry.prototype.getWidth = function() {\n\treturn ""\n},\nBoxParser.SampleEntry.prototype.getHeight = function() {\n\treturn ""\n},\nBoxParser.SampleEntry.prototype.getChannelCount = function() {\n\treturn ""\n},\nBoxParser.SampleEntry.prototype.getSampleRate = function() {\n\treturn ""\n},\nBoxParser.SampleEntry.prototype.getSampleSize = function() {\n\treturn ""\n},\nBoxParser.VisualSampleEntry.prototype.isVideo = function() {\n\treturn ! 0\n},\nBoxParser.VisualSampleEntry.prototype.getWidth = function() {\n\treturn this.width\n},\nBoxParser.VisualSampleEntry.prototype.getHeight = function() {\n\treturn this.height\n},\nBoxParser.AudioSampleEntry.prototype.isAudio = function() {\n\treturn ! 0\n},\nBoxParser.AudioSampleEntry.prototype.getChannelCount = function() {\n\treturn this.channel_count\n},\nBoxParser.AudioSampleEntry.prototype.getSampleRate = function() {\n\treturn this.samplerate\n},\nBoxParser.AudioSampleEntry.prototype.getSampleSize = function() {\n\treturn this.samplesize\n},\nBoxParser.SubtitleSampleEntry.prototype.isSubtitle = function() {\n\treturn ! 0\n},\nBoxParser.MetadataSampleEntry.prototype.isMetadata = function() {\n\treturn ! 0\n},\nBoxParser.decimalToHex = function(t, e) {\n\tvar i = Number(t).toString(16);\n\tfor (e = null == e ? e = 2 : e; i.length < e;) i = "0" + i;\n\treturn i\n},\nBoxParser.avc1SampleEntry.prototype.getCodec = BoxParser.avc2SampleEntry.prototype.getCodec = BoxParser.avc3SampleEntry.prototype.getCodec = BoxParser.avc4SampleEntry.prototype.getCodec = function() {\n\tvar t = BoxParser.SampleEntry.prototype.getCodec.call(this);\n\treturn this.avcC ? t + "." + BoxParser.decimalToHex(this.avcC.AVCProfileIndication) + BoxParser.decimalToHex(this.avcC.profile_compatibility) + BoxParser.decimalToHex(this.avcC.AVCLevelIndication) : t\n},\nBoxParser.hev1SampleEntry.prototype.getCodec = BoxParser.hvc1SampleEntry.prototype.getCodec = function() {\n\tvar t = BoxParser.SampleEntry.prototype.getCodec.call(this);\n\tif (this.hvcC) {\n\t\tswitch (t += ".", this.hvcC.general_profile_space) {\n\t\tcase 0:\n\t\t\tt += "";\n\t\t\tbreak;\n\t\tcase 1:\n\t\t\tt += "A";\n\t\t\tbreak;\n\t\tcase 2:\n\t\t\tt += "B";\n\t\t\tbreak;\n\t\tcase 3:\n\t\t\tt += "C"\n\t\t}\n\t\tt += this.hvcC.general_profile_idc,\n\t\tt += ".";\n\t\tfor (var e = this.hvcC.general_profile_compatibility,\n\t\ti = 0,\n\t\tr = 0; r < 32 && (i |= 1 & e, 31 != r); r++) i <<= 1,\n\t\te >>= 1;\n\t\tt += BoxParser.decimalToHex(i, 0),\n\t\tt += ".",\n\t\t0 === this.hvcC.general_tier_flag ? t += "L": t += "H",\n\t\tt += this.hvcC.general_level_idc;\n\t\tvar s = !1,\n\t\ta = "";\n\t\tfor (r = 5; 0 <= r; r--)(this.hvcC.general_constraint_indicator[r] || s) && (a = "." + BoxParser.decimalToHex(this.hvcC.general_constraint_indicator[r], 0) + a, s = !0);\n\t\tt += a\n\t}\n\treturn t\n},\nBoxParser.vvc1SampleEntry.prototype.getCodec = BoxParser.vvi1SampleEntry.prototype.getCodec = function() {\n\tvar t = BoxParser.SampleEntry.prototype.getCodec.call(this);\n\tif (this.vvcC) {\n\t\tt += "." + this.vvcC.general_profile_idc,\n\t\tthis.vvcC.general_tier_flag ? t += ".H": t += ".L",\n\t\tt += this.vvcC.general_level_idc;\n\t\tvar e = "";\n\t\tif (this.vvcC.general_constraint_info) {\n\t\t\tvar i, r = [],\n\t\t\ts = 0;\n\t\t\tfor (s |= this.vvcC.ptl_frame_only_constraint << 7, s |= this.vvcC.ptl_multilayer_enabled << 6, h = 0; h < this.vvcC.general_constraint_info.length; ++h) s |= this.vvcC.general_constraint_info[h] >> 2 & 63,\n\t\t\tr.push(s),\n\t\t\ts && (i = h),\n\t\t\ts = this.vvcC.general_constraint_info[h] >> 2 & 3;\n\t\t\tif (void 0 === i) e = ".CA";\n\t\t\telse {\n\t\t\t\te = ".C";\n\t\t\t\tfor (var a = "ABCDEFGHIJKLMNOPQRSTUVWXYZ234567",\n\t\t\t\tn = 0,\n\t\t\t\to = 0,\n\t\t\t\th = 0; h <= i; ++h) for (n = n << 8 | r[h], o += 8; 5 <= o;) e += a[n >> o - 5 & 31],\n\t\t\t\tn &= (1 << (o -= 5)) - 1;\n\t\t\t\to && (e += a[31 & (n <<= 5 - o)])\n\t\t\t}\n\t\t}\n\t\tt += e\n\t}\n\treturn t\n},\nBoxParser.mp4aSampleEntry.prototype.getCodec = function() {\n\tvar t = BoxParser.SampleEntry.prototype.getCodec.call(this);\n\tif (this.esds && this.esds.esd) {\n\t\tvar e = this.esds.esd.getOTI(),\n\t\ti = this.esds.esd.getAudioConfig();\n\t\treturn t + "." + BoxParser.decimalToHex(e) + (i ? "." + i: "")\n\t}\n\treturn t\n},\nBoxParser.stxtSampleEntry.prototype.getCodec = function() {\n\tvar t = BoxParser.SampleEntry.prototype.getCodec.call(this);\n\treturn this.mime_format ? t + "." + this.mime_format: t\n},\nBoxParser.vp08SampleEntry.prototype.getCodec = BoxParser.vp09SampleEntry.prototype.getCodec = function() {\n\tvar t = BoxParser.SampleEntry.prototype.getCodec.call(this),\n\te = this.vpcC.level;\n\t0 == e && (e = "00");\n\tvar i = this.vpcC.bitDepth;\n\treturn 8 == i && (i = "08"),\n\tt + ".0" + this.vpcC.profile + "." + e + "." + i\n},\nBoxParser.av01SampleEntry.prototype.getCodec = function() {\n\tvar t, e = BoxParser.SampleEntry.prototype.getCodec.call(this),\n\ti = this.av1C.seq_level_idx_0;\n\treturn i < 10 && (i = "0" + i),\n\t2 === this.av1C.seq_profile && 1 === this.av1C.high_bitdepth ? t = 1 === this.av1C.twelve_bit ? "12": "10": this.av1C.seq_profile <= 2 && (t = 1 === this.av1C.high_bitdepth ? "10": "08"),\n\te + "." + this.av1C.seq_profile + "." + i + (this.av1C.seq_tier_0 ? "H": "M") + "." + t\n},\nBoxParser.Box.prototype.writeHeader = function(t, e) {\n\tthis.size += 8,\n\tthis.size > MAX_SIZE && (this.size += 8),\n\t"uuid" === this.type && (this.size += 16),\n\tLog.debug("BoxWriter", "Writing box " + this.type + " of size: " + this.size + " at position " + t.getPosition() + (e || "")),\n\tthis.size > MAX_SIZE ? t.writeUint32(1) : (this.sizePosition = t.getPosition(), t.writeUint32(this.size)),\n\tt.writeString(this.type, null, 4),\n\t"uuid" === this.type && t.writeUint8Array(this.uuid),\n\tthis.size > MAX_SIZE && t.writeUint64(this.size)\n},\nBoxParser.FullBox.prototype.writeHeader = function(t) {\n\tthis.size += 4,\n\tBoxParser.Box.prototype.writeHeader.call(this, t, " v=" + this.version + " f=" + this.flags),\n\tt.writeUint8(this.version),\n\tt.writeUint24(this.flags)\n},\nBoxParser.Box.prototype.write = function(t) {\n\t"mdat" === this.type ? this.data && (this.size = this.data.length, this.writeHeader(t), t.writeUint8Array(this.data)) : (this.size = this.data ? this.data.length: 0, this.writeHeader(t), this.data && t.writeUint8Array(this.data))\n},\nBoxParser.ContainerBox.prototype.write = function(t) {\n\tthis.size = 0,\n\tthis.writeHeader(t);\n\tfor (var e = 0; e < this.boxes.length; e++) this.boxes[e] && (this.boxes[e].write(t), this.size += this.boxes[e].size);\n\tLog.debug("BoxWriter", "Adjusting box " + this.type + " with new size " + this.size),\n\tt.adjustUint32(this.sizePosition, this.size)\n},\nBoxParser.TrackReferenceTypeBox.prototype.write = function(t) {\n\tthis.size = 4 * this.track_ids.length,\n\tthis.writeHeader(t),\n\tt.writeUint32Array(this.track_ids)\n},\nBoxParser.avcCBox.prototype.write = function(t) {\n\tvar e;\n\tfor (this.size = 7, e = 0; e < this.SPS.length; e++) this.size += 2 + this.SPS[e].length;\n\tfor (e = 0; e < this.PPS.length; e++) this.size += 2 + this.PPS[e].length;\n\tfor (this.ext && (this.size += this.ext.length), this.writeHeader(t), t.writeUint8(this.configurationVersion), t.writeUint8(this.AVCProfileIndication), t.writeUint8(this.profile_compatibility), t.writeUint8(this.AVCLevelIndication), t.writeUint8(this.lengthSizeMinusOne + 252), t.writeUint8(this.SPS.length + 224), e = 0; e < this.SPS.length; e++) t.writeUint16(this.SPS[e].length),\n\tt.writeUint8Array(this.SPS[e].nalu);\n\tfor (t.writeUint8(this.PPS.length), e = 0; e < this.PPS.length; e++) t.writeUint16(this.PPS[e].length),\n\tt.writeUint8Array(this.PPS[e].nalu);\n\tthis.ext && t.writeUint8Array(this.ext)\n},\nBoxParser.co64Box.prototype.write = function(t) {\n\tvar e;\n\tfor (this.version = 0, this.flags = 0, this.size = 4 + 8 * this.chunk_offsets.length, this.writeHeader(t), t.writeUint32(this.chunk_offsets.length), e = 0; e < this.chunk_offsets.length; e++) t.writeUint64(this.chunk_offsets[e])\n},\nBoxParser.cslgBox.prototype.write = function(t) {\n\tthis.version = 0,\n\tthis.flags = 0,\n\tthis.size = 20,\n\tthis.writeHeader(t),\n\tt.writeInt32(this.compositionToDTSShift),\n\tt.writeInt32(this.leastDecodeToDisplayDelta),\n\tt.writeInt32(this.greatestDecodeToDisplayDelta),\n\tt.writeInt32(this.compositionStartTime),\n\tt.writeInt32(this.compositionEndTime)\n},\nBoxParser.cttsBox.prototype.write = function(t) {\n\tvar e;\n\tfor (this.version = 0, this.flags = 0, this.size = 4 + 8 * this.sample_counts.length, this.writeHeader(t), t.writeUint32(this.sample_counts.length), e = 0; e < this.sample_counts.length; e++) t.writeUint32(this.sample_counts[e]),\n\t1 === this.version ? t.writeInt32(this.sample_offsets[e]) : t.writeUint32(this.sample_offsets[e])\n},\nBoxParser.drefBox.prototype.write = function(t) {\n\tthis.version = 0,\n\tthis.flags = 0,\n\tthis.size = 4,\n\tthis.writeHeader(t),\n\tt.writeUint32(this.entries.length);\n\tfor (var e = 0; e < this.entries.length; e++) this.entries[e].write(t),\n\tthis.size += this.entries[e].size;\n\tLog.debug("BoxWriter", "Adjusting box " + this.type + " with new size " + this.size),\n\tt.adjustUint32(this.sizePosition, this.size)\n},\nBoxParser.elngBox.prototype.write = function(t) {\n\tthis.version = 0,\n\tthis.flags = 0,\n\tthis.size = this.extended_language.length,\n\tthis.writeHeader(t),\n\tt.writeString(this.extended_language)\n},\nBoxParser.elstBox.prototype.write = function(t) {\n\tthis.version = 0,\n\tthis.flags = 0,\n\tthis.size = 4 + 12 * this.entries.length,\n\tthis.writeHeader(t),\n\tt.writeUint32(this.entries.length);\n\tfor (var e = 0; e < this.entries.length; e++) {\n\t\tvar i = this.entries[e];\n\t\tt.writeUint32(i.segment_duration),\n\t\tt.writeInt32(i.media_time),\n\t\tt.writeInt16(i.media_rate_integer),\n\t\tt.writeInt16(i.media_rate_fraction)\n\t}\n},\nBoxParser.emsgBox.prototype.write = function(t) {\n\tthis.version = 0,\n\tthis.flags = 0,\n\tthis.size = 16 + this.message_data.length + (this.scheme_id_uri.length + 1) + (this.value.length + 1),\n\tthis.writeHeader(t),\n\tt.writeCString(this.scheme_id_uri),\n\tt.writeCString(this.value),\n\tt.writeUint32(this.timescale),\n\tt.writeUint32(this.presentation_time_delta),\n\tt.writeUint32(this.event_duration),\n\tt.writeUint32(this.id),\n\tt.writeUint8Array(this.message_data)\n},\nBoxParser.ftypBox.prototype.write = function(t) {\n\tthis.size = 8 + 4 * this.compatible_brands.length,\n\tthis.writeHeader(t),\n\tt.writeString(this.major_brand, null, 4),\n\tt.writeUint32(this.minor_version);\n\tfor (var e = 0; e < this.compatible_brands.length; e++) t.writeString(this.compatible_brands[e], null, 4)\n},\nBoxParser.hdlrBox.prototype.write = function(t) {\n\tthis.size = 20 + this.name.length + 1,\n\tthis.version = 0,\n\tthis.flags = 0,\n\tthis.writeHeader(t),\n\tt.writeUint32(0),\n\tt.writeString(this.handler, null, 4),\n\tt.writeUint32(0),\n\tt.writeUint32(0),\n\tt.writeUint32(0),\n\tt.writeCString(this.name)\n},\nBoxParser.hvcCBox.prototype.write = function(t) {\n\tvar e, i;\n\tfor (this.size = 23, e = 0; e < this.nalu_arrays.length; e++) for (this.size += 3, i = 0; i < this.nalu_arrays[e].length; i++) this.size += 2 + this.nalu_arrays[e][i].data.length;\n\tfor (this.writeHeader(t), t.writeUint8(this.configurationVersion), t.writeUint8((this.general_profile_space << 6) + (this.general_tier_flag << 5) + this.general_profile_idc), t.writeUint32(this.general_profile_compatibility), t.writeUint8Array(this.general_constraint_indicator), t.writeUint8(this.general_level_idc), t.writeUint16(this.min_spatial_segmentation_idc + (15 << 24)), t.writeUint8(this.parallelismType + 252), t.writeUint8(this.chroma_format_idc + 252), t.writeUint8(this.bit_depth_luma_minus8 + 248), t.writeUint8(this.bit_depth_chroma_minus8 + 248), t.writeUint16(this.avgFrameRate), t.writeUint8((this.constantFrameRate << 6) + (this.numTemporalLayers << 3) + (this.temporalIdNested << 2) + this.lengthSizeMinusOne), t.writeUint8(this.nalu_arrays.length), e = 0; e < this.nalu_arrays.length; e++) for (t.writeUint8((this.nalu_arrays[e].completeness << 7) + this.nalu_arrays[e].nalu_type), t.writeUint16(this.nalu_arrays[e].length), i = 0; i < this.nalu_arrays[e].length; i++) t.writeUint16(this.nalu_arrays[e][i].data.length),\n\tt.writeUint8Array(this.nalu_arrays[e][i].data)\n},\nBoxParser.kindBox.prototype.write = function(t) {\n\tthis.version = 0,\n\tthis.flags = 0,\n\tthis.size = this.schemeURI.length + 1 + (this.value.length + 1),\n\tthis.writeHeader(t),\n\tt.writeCString(this.schemeURI),\n\tt.writeCString(this.value)\n},\nBoxParser.mdhdBox.prototype.write = function(t) {\n\tthis.size = 20,\n\tthis.flags = 0,\n\tthis.version = 0,\n\tthis.writeHeader(t),\n\tt.writeUint32(this.creation_time),\n\tt.writeUint32(this.modification_time),\n\tt.writeUint32(this.timescale),\n\tt.writeUint32(this.duration),\n\tt.writeUint16(this.language),\n\tt.writeUint16(0)\n},\nBoxParser.mehdBox.prototype.write = function(t) {\n\tthis.version = 0,\n\tthis.flags = 0,\n\tthis.size = 4,\n\tthis.writeHeader(t),\n\tt.writeUint32(this.fragment_duration)\n},\nBoxParser.mfhdBox.prototype.write = function(t) {\n\tthis.version = 0,\n\tthis.flags = 0,\n\tthis.size = 4,\n\tthis.writeHeader(t),\n\tt.writeUint32(this.sequence_number)\n},\nBoxParser.mvhdBox.prototype.write = function(t) {\n\tthis.version = 0,\n\tthis.flags = 0,\n\tthis.size = 96,\n\tthis.writeHeader(t),\n\tt.writeUint32(this.creation_time),\n\tt.writeUint32(this.modification_time),\n\tt.writeUint32(this.timescale),\n\tt.writeUint32(this.duration),\n\tt.writeUint32(this.rate),\n\tt.writeUint16(this.volume << 8),\n\tt.writeUint16(0),\n\tt.writeUint32(0),\n\tt.writeUint32(0),\n\tt.writeUint32Array(this.matrix),\n\tt.writeUint32(0),\n\tt.writeUint32(0),\n\tt.writeUint32(0),\n\tt.writeUint32(0),\n\tt.writeUint32(0),\n\tt.writeUint32(0),\n\tt.writeUint32(this.next_track_id)\n},\nBoxParser.SampleEntry.prototype.writeHeader = function(t) {\n\tthis.size = 8,\n\tBoxParser.Box.prototype.writeHeader.call(this, t),\n\tt.writeUint8(0),\n\tt.writeUint8(0),\n\tt.writeUint8(0),\n\tt.writeUint8(0),\n\tt.writeUint8(0),\n\tt.writeUint8(0),\n\tt.writeUint16(this.data_reference_index)\n},\nBoxParser.SampleEntry.prototype.writeFooter = function(t) {\n\tfor (var e = 0; e < this.boxes.length; e++) this.boxes[e].write(t),\n\tthis.size += this.boxes[e].size;\n\tLog.debug("BoxWriter", "Adjusting box " + this.type + " with new size " + this.size),\n\tt.adjustUint32(this.sizePosition, this.size)\n},\nBoxParser.SampleEntry.prototype.write = function(t) {\n\tthis.writeHeader(t),\n\tt.writeUint8Array(this.data),\n\tthis.size += this.data.length,\n\tLog.debug("BoxWriter", "Adjusting box " + this.type + " with new size " + this.size),\n\tt.adjustUint32(this.sizePosition, this.size)\n},\nBoxParser.VisualSampleEntry.prototype.write = function(t) {\n\tthis.writeHeader(t),\n\tthis.size += 70,\n\tt.writeUint16(0),\n\tt.writeUint16(0),\n\tt.writeUint32(0),\n\tt.writeUint32(0),\n\tt.writeUint32(0),\n\tt.writeUint16(this.width),\n\tt.writeUint16(this.height),\n\tt.writeUint32(this.horizresolution),\n\tt.writeUint32(this.vertresolution),\n\tt.writeUint32(0),\n\tt.writeUint16(this.frame_count),\n\tt.writeUint8(Math.min(31, this.compressorname.length)),\n\tt.writeString(this.compressorname, null, 31),\n\tt.writeUint16(this.depth),\n\tt.writeInt16(-1),\n\tthis.writeFooter(t)\n},\nBoxParser.AudioSampleEntry.prototype.write = function(t) {\n\tthis.writeHeader(t),\n\tthis.size += 20,\n\tt.writeUint32(0),\n\tt.writeUint32(0),\n\tt.writeUint16(this.channel_count),\n\tt.writeUint16(this.samplesize),\n\tt.writeUint16(0),\n\tt.writeUint16(0),\n\tt.writeUint32(this.samplerate << 16),\n\tthis.writeFooter(t)\n},\nBoxParser.stppSampleEntry.prototype.write = function(t) {\n\tthis.writeHeader(t),\n\tthis.size += this.namespace.length + 1 + this.schema_location.length + 1 + this.auxiliary_mime_types.length + 1,\n\tt.writeCString(this.namespace),\n\tt.writeCString(this.schema_location),\n\tt.writeCString(this.auxiliary_mime_types),\n\tthis.writeFooter(t)\n},\nBoxParser.SampleGroupEntry.prototype.write = function(t) {\n\tt.writeUint8Array(this.data)\n},\nBoxParser.sbgpBox.prototype.write = function(t) {\n\tthis.version = 1,\n\tthis.flags = 0,\n\tthis.size = 12 + 8 * this.entries.length,\n\tthis.writeHeader(t),\n\tt.writeString(this.grouping_type, null, 4),\n\tt.writeUint32(this.grouping_type_parameter),\n\tt.writeUint32(this.entries.length);\n\tfor (var e = 0; e < this.entries.length; e++) {\n\t\tvar i = this.entries[e];\n\t\tt.writeInt32(i.sample_count),\n\t\tt.writeInt32(i.group_description_index)\n\t}\n},\nBoxParser.sgpdBox.prototype.write = function(t) {\n\tvar e, i;\n\tfor (this.flags = 0, this.size = 12, e = 0; e < this.entries.length; e++) i = this.entries[e],\n\t1 === this.version && (0 === this.default_length && (this.size += 4), this.size += i.data.length);\n\tfor (this.writeHeader(t), t.writeString(this.grouping_type, null, 4), 1 === this.version && t.writeUint32(this.default_length), 2 <= this.version && t.writeUint32(this.default_sample_description_index), t.writeUint32(this.entries.length), e = 0; e < this.entries.length; e++) i = this.entries[e],\n\t1 === this.version && 0 === this.default_length && t.writeUint32(i.description_length),\n\ti.write(t)\n},\nBoxParser.sidxBox.prototype.write = function(t) {\n\tthis.version = 0,\n\tthis.flags = 0,\n\tthis.size = 20 + 12 * this.references.length,\n\tthis.writeHeader(t),\n\tt.writeUint32(this.reference_ID),\n\tt.writeUint32(this.timescale),\n\tt.writeUint32(this.earliest_presentation_time),\n\tt.writeUint32(this.first_offset),\n\tt.writeUint16(0),\n\tt.writeUint16(this.references.length);\n\tfor (var e = 0; e < this.references.length; e++) {\n\t\tvar i = this.references[e];\n\t\tt.writeUint32(i.reference_type << 31 | i.referenced_size),\n\t\tt.writeUint32(i.subsegment_duration),\n\t\tt.writeUint32(i.starts_with_SAP << 31 | i.SAP_type << 28 | i.SAP_delta_time)\n\t}\n},\nBoxParser.smhdBox.prototype.write = function(t) {\n\tthis.version = 0,\n\tthis.flags = 1,\n\tthis.size = 4,\n\tthis.writeHeader(t),\n\tt.writeUint16(this.balance),\n\tt.writeUint16(0)\n},\nBoxParser.stcoBox.prototype.write = function(t) {\n\tthis.version = 0,\n\tthis.flags = 0,\n\tthis.size = 4 + 4 * this.chunk_offsets.length,\n\tthis.writeHeader(t),\n\tt.writeUint32(this.chunk_offsets.length),\n\tt.writeUint32Array(this.chunk_offsets)\n},\nBoxParser.stscBox.prototype.write = function(t) {\n\tvar e;\n\tfor (this.version = 0, this.flags = 0, this.size = 4 + 12 * this.first_chunk.length, this.writeHeader(t), t.writeUint32(this.first_chunk.length), e = 0; e < this.first_chunk.length; e++) t.writeUint32(this.first_chunk[e]),\n\tt.writeUint32(this.samples_per_chunk[e]),\n\tt.writeUint32(this.sample_description_index[e])\n},\nBoxParser.stsdBox.prototype.write = function(t) {\n\tvar e;\n\tfor (this.version = 0, this.flags = 0, this.size = 0, this.writeHeader(t), t.writeUint32(this.entries.length), this.size += 4, e = 0; e < this.entries.length; e++) this.entries[e].write(t),\n\tthis.size += this.entries[e].size;\n\tLog.debug("BoxWriter", "Adjusting box " + this.type + " with new size " + this.size),\n\tt.adjustUint32(this.sizePosition, this.size)\n},\nBoxParser.stshBox.prototype.write = function(t) {\n\tvar e;\n\tfor (this.version = 0, this.flags = 0, this.size = 4 + 8 * this.shadowed_sample_numbers.length, this.writeHeader(t), t.writeUint32(this.shadowed_sample_numbers.length), e = 0; e < this.shadowed_sample_numbers.length; e++) t.writeUint32(this.shadowed_sample_numbers[e]),\n\tt.writeUint32(this.sync_sample_numbers[e])\n},\nBoxParser.stssBox.prototype.write = function(t) {\n\tthis.version = 0,\n\tthis.flags = 0,\n\tthis.size = 4 + 4 * this.sample_numbers.length,\n\tthis.writeHeader(t),\n\tt.writeUint32(this.sample_numbers.length),\n\tt.writeUint32Array(this.sample_numbers)\n},\nBoxParser.stszBox.prototype.write = function(t) {\n\tvar e, i = !0;\n\tif (this.version = 0, (this.flags = 0) < this.sample_sizes.length) for (e = 0; e + 1 < this.sample_sizes.length;) {\n\t\tif (this.sample_sizes[e + 1] !== this.sample_sizes[0]) {\n\t\t\ti = !1;\n\t\t\tbreak\n\t\t}\n\t\te++\n\t} else i = !1;\n\tthis.size = 8,\n\ti || (this.size += 4 * this.sample_sizes.length),\n\tthis.writeHeader(t),\n\ti ? t.writeUint32(this.sample_sizes[0]) : t.writeUint32(0),\n\tt.writeUint32(this.sample_sizes.length),\n\ti || t.writeUint32Array(this.sample_sizes)\n},\nBoxParser.sttsBox.prototype.write = function(t) {\n\tvar e;\n\tfor (this.version = 0, this.flags = 0, this.size = 4 + 8 * this.sample_counts.length, this.writeHeader(t), t.writeUint32(this.sample_counts.length), e = 0; e < this.sample_counts.length; e++) t.writeUint32(this.sample_counts[e]),\n\tt.writeUint32(this.sample_deltas[e])\n},\nBoxParser.tfdtBox.prototype.write = function(t) {\n\tvar e = Math.pow(2, 32) - 1;\n\tthis.version = this.baseMediaDecodeTime > e ? 1 : 0,\n\tthis.flags = 0,\n\tthis.size = 4,\n\t1 === this.version && (this.size += 4),\n\tthis.writeHeader(t),\n\t1 === this.version ? t.writeUint64(this.baseMediaDecodeTime) : t.writeUint32(this.baseMediaDecodeTime)\n},\nBoxParser.tfhdBox.prototype.write = function(t) {\n\tthis.version = 0,\n\tthis.size = 4,\n\tthis.flags & BoxParser.TFHD_FLAG_BASE_DATA_OFFSET && (this.size += 8),\n\tthis.flags & BoxParser.TFHD_FLAG_SAMPLE_DESC && (this.size += 4),\n\tthis.flags & BoxParser.TFHD_FLAG_SAMPLE_DUR && (this.size += 4),\n\tthis.flags & BoxParser.TFHD_FLAG_SAMPLE_SIZE && (this.size += 4),\n\tthis.flags & BoxParser.TFHD_FLAG_SAMPLE_FLAGS && (this.size += 4),\n\tthis.writeHeader(t),\n\tt.writeUint32(this.track_id),\n\tthis.flags & BoxParser.TFHD_FLAG_BASE_DATA_OFFSET && t.writeUint64(this.base_data_offset),\n\tthis.flags & BoxParser.TFHD_FLAG_SAMPLE_DESC && t.writeUint32(this.default_sample_description_index),\n\tthis.flags & BoxParser.TFHD_FLAG_SAMPLE_DUR && t.writeUint32(this.default_sample_duration),\n\tthis.flags & BoxParser.TFHD_FLAG_SAMPLE_SIZE && t.writeUint32(this.default_sample_size),\n\tthis.flags & BoxParser.TFHD_FLAG_SAMPLE_FLAGS && t.writeUint32(this.default_sample_flags)\n},\nBoxParser.tkhdBox.prototype.write = function(t) {\n\tthis.version = 0,\n\tthis.size = 80,\n\tthis.writeHeader(t),\n\tt.writeUint32(this.creation_time),\n\tt.writeUint32(this.modification_time),\n\tt.writeUint32(this.track_id),\n\tt.writeUint32(0),\n\tt.writeUint32(this.duration),\n\tt.writeUint32(0),\n\tt.writeUint32(0),\n\tt.writeInt16(this.layer),\n\tt.writeInt16(this.alternate_group),\n\tt.writeInt16(this.volume << 8),\n\tt.writeUint16(0),\n\tt.writeInt32Array(this.matrix),\n\tt.writeUint32(this.width),\n\tt.writeUint32(this.height)\n},\nBoxParser.trexBox.prototype.write = function(t) {\n\tthis.version = 0,\n\tthis.flags = 0,\n\tthis.size = 20,\n\tthis.writeHeader(t),\n\tt.writeUint32(this.track_id),\n\tt.writeUint32(this.default_sample_description_index),\n\tt.writeUint32(this.default_sample_duration),\n\tt.writeUint32(this.default_sample_size),\n\tt.writeUint32(this.default_sample_flags)\n},\nBoxParser.trunBox.prototype.write = function(t) {\n\tthis.version = 0,\n\tthis.size = 4,\n\tthis.flags & BoxParser.TRUN_FLAGS_DATA_OFFSET && (this.size += 4),\n\tthis.flags & BoxParser.TRUN_FLAGS_FIRST_FLAG && (this.size += 4),\n\tthis.flags & BoxParser.TRUN_FLAGS_DURATION && (this.size += 4 * this.sample_duration.length),\n\tthis.flags & BoxParser.TRUN_FLAGS_SIZE && (this.size += 4 * this.sample_size.length),\n\tthis.flags & BoxParser.TRUN_FLAGS_FLAGS && (this.size += 4 * this.sample_flags.length),\n\tthis.flags & BoxParser.TRUN_FLAGS_CTS_OFFSET && (this.size += 4 * this.sample_composition_time_offset.length),\n\tthis.writeHeader(t),\n\tt.writeUint32(this.sample_count),\n\tthis.flags & BoxParser.TRUN_FLAGS_DATA_OFFSET && (this.data_offset_position = t.getPosition(), t.writeInt32(this.data_offset)),\n\tthis.flags & BoxParser.TRUN_FLAGS_FIRST_FLAG && t.writeUint32(this.first_sample_flags);\n\tfor (var e = 0; e < this.sample_count; e++) this.flags & BoxParser.TRUN_FLAGS_DURATION && t.writeUint32(this.sample_duration[e]),\n\tthis.flags & BoxParser.TRUN_FLAGS_SIZE && t.writeUint32(this.sample_size[e]),\n\tthis.flags & BoxParser.TRUN_FLAGS_FLAGS && t.writeUint32(this.sample_flags[e]),\n\tthis.flags & BoxParser.TRUN_FLAGS_CTS_OFFSET && (0 === this.version ? t.writeUint32(this.sample_composition_time_offset[e]) : t.writeInt32(this.sample_composition_time_offset[e]))\n},\nBoxParser["url Box"].prototype.write = function(t) {\n\tthis.version = 0,\n\tthis.location ? (this.flags = 0, this.size = this.location.length + 1) : (this.flags = 1, this.size = 0),\n\tthis.writeHeader(t),\n\tthis.location && t.writeCString(this.location)\n},\nBoxParser["urn Box"].prototype.write = function(t) {\n\tthis.version = 0,\n\tthis.flags = 0,\n\tthis.size = this.name.length + 1 + (this.location ? this.location.length + 1 : 0),\n\tthis.writeHeader(t),\n\tt.writeCString(this.name),\n\tthis.location && t.writeCString(this.location)\n},\nBoxParser.vmhdBox.prototype.write = function(t) {\n\tthis.version = 0,\n\tthis.flags = 1,\n\tthis.size = 8,\n\tthis.writeHeader(t),\n\tt.writeUint16(this.graphicsmode),\n\tt.writeUint16Array(this.opcolor)\n},\nBoxParser.cttsBox.prototype.unpack = function(t) {\n\tfor (var e, i = 0,\n\tr = 0; r < this.sample_counts.length; r++) for (e = 0; e < this.sample_counts[r]; e++) t[i].pts = t[i].dts + this.sample_offsets[r],\n\ti++\n},\nBoxParser.sttsBox.prototype.unpack = function(t) {\n\tfor (var e, i = 0,\n\tr = 0; r < this.sample_counts.length; r++) for (e = 0; e < this.sample_counts[r]; e++) t[i].dts = 0 === i ? 0 : t[i - 1].dts + this.sample_deltas[r],\n\ti++\n},\nBoxParser.stcoBox.prototype.unpack = function(t) {\n\tfor (var e = 0; e < this.chunk_offsets.length; e++) t[e].offset = this.chunk_offsets[e]\n},\nBoxParser.stscBox.prototype.unpack = function(t) {\n\tfor (var e, i, r = 0,\n\ts = 0,\n\ta = 0; a < this.first_chunk.length; a++) for (e = 0; e < (a + 1 < this.first_chunk.length ? this.first_chunk[a + 1] : 1 / 0); e++) for (s++, i = 0; i < this.samples_per_chunk[a]; i++) {\n\t\tif (!t[r]) return;\n\t\tt[r].description_index = this.sample_description_index[a],\n\t\tt[r].chunk_index = s,\n\t\tr++\n\t}\n},\nBoxParser.stszBox.prototype.unpack = function(t) {\n\tfor (var e = 0; e < this.sample_sizes.length; e++) t[e].size = this.sample_sizes[e]\n},\nBoxParser.DIFF_BOXES_PROP_NAMES = ["boxes", "entries", "references", "subsamples", "items", "item_infos", "extents", "associations", "subsegments", "ranges", "seekLists", "seekPoints", "esd", "levels"],\nBoxParser.DIFF_PRIMITIVE_ARRAY_PROP_NAMES = ["compatible_brands", "matrix", "opcolor", "sample_counts", "sample_deltas", "first_chunk", "samples_per_chunk", "sample_sizes", "chunk_offsets", "sample_offsets", "sample_description_index", "sample_duration"],\nBoxParser.boxEqualFields = function(t, e) {\n\tif (t && !e) return ! 1;\n\tfor (var i in t) if (! (-1 < BoxParser.DIFF_BOXES_PROP_NAMES.indexOf(i) || t[i] instanceof BoxParser.Box || e[i] instanceof BoxParser.Box || void 0 === t[i] || void 0 === e[i] || "function" == typeof t[i] || "function" == typeof e[i] || t.subBoxNames && -1 < t.subBoxNames.indexOf(i.slice(0, 4)) || e.subBoxNames && -1 < e.subBoxNames.indexOf(i.slice(0, 4)) || "data" === i || "start" === i || "size" === i || "creation_time" === i || "modification_time" === i || -1 < BoxParser.DIFF_PRIMITIVE_ARRAY_PROP_NAMES.indexOf(i) || t[i] === e[i])) return ! 1;\n\treturn ! 0\n},\nBoxParser.boxEqual = function(t, e) {\n\tif (!BoxParser.boxEqualFields(t, e)) return ! 1;\n\tfor (var i = 0; i < BoxParser.DIFF_BOXES_PROP_NAMES.length; i++) {\n\t\tvar r = BoxParser.DIFF_BOXES_PROP_NAMES[i];\n\t\tif (t[r] && e[r] && !BoxParser.boxEqual(t[r], e[r])) return ! 1\n\t}\n\treturn ! 0\n};\nvar VTTin4Parser = function() {};\nVTTin4Parser.prototype.parseSample = function(t) {\n\tfor (var e, i = new MP4BoxStream(t.buffer), r = []; ! i.isEos();)(e = BoxParser.parseOneBox(i, !1)).code === BoxParser.OK && "vttc" === e.box.type && r.push(e.box);\n\treturn r\n},\nVTTin4Parser.prototype.getText = function(t, e, i) {\n\tfunction s(t, e, i) {\n\t\treturn i = i || "0",\n\t\t(t += "").length >= e ? t: new Array(e - t.length + 1).join(i) + t\n\t}\n\tfunction r(t) {\n\t\tvar e = Math.floor(t / 3600),\n\t\ti = Math.floor((t - 3600 * e) / 60),\n\t\tr = Math.floor(t - 3600 * e - 60 * i),\n\t\tt = Math.floor(1e3 * (t - 3600 * e - 60 * i - r));\n\t\treturn s(e, 2) + ":" + s(i, 2) + ":" + s(r, 2) + "." + s(t, 3)\n\t}\n\tfor (var a = this.parseSample(i), n = "", o = 0; o < a.length; o++) {\n\t\tvar h = a[o];\n\t\tn += r(t) + " --\\x3e " + r(e) + "\\r\\n",\n\t\tn += h.payl.text\n\t}\n\treturn n\n};\nvar XMLSubtitlein4Parser = function() {};\nXMLSubtitlein4Parser.prototype.parseSample = function(t) {\n\tvar e, i = {\n\t\tresources: []\n\t},\n\tr = new MP4BoxStream(t.data.buffer);\n\tif (t.subsamples && 0 !== t.subsamples.length) {\n\t\tif (i.documentString = r.readString(t.subsamples[0].size), 1 < t.subsamples.length) for (e = 1; e < t.subsamples.length; e++) i.resources[e] = r.readUint8Array(t.subsamples[e].size)\n\t} else i.documentString = r.readString(t.data.length);\n\treturn "undefined" != typeof DOMParser && (i.document = (new DOMParser).parseFromString(i.documentString, "application/xml")),\n\ti\n};\nvar Textin4Parser = function() {};\nTextin4Parser.prototype.parseSample = function(t) {\n\treturn new MP4BoxStream(t.data.buffer).readString(t.data.length)\n},\nTextin4Parser.prototype.parseConfig = function(t) {\n\tt = new MP4BoxStream(t.buffer);\n\treturn t.readUint32(),\n\tt.readCString()\n},\n"undefined" != typeof exports && (exports.VTTin4Parser = VTTin4Parser, exports.XMLSubtitlein4Parser = XMLSubtitlein4Parser, exports.Textin4Parser = Textin4Parser);\nvar ISOFile = function(t) {\n\tthis.stream = t || new MultiBufferStream,\n\tthis.boxes = [],\n\tthis.mdats = [],\n\tthis.moofs = [],\n\tthis.isProgressive = !1,\n\tthis.moovStartFound = !1,\n\tthis.onMoovStart = null,\n\tthis.moovStartSent = !1,\n\tthis.onReady = null,\n\tthis.readySent = !1,\n\tthis.onSegment = null,\n\tthis.onSamples = null,\n\tthis.onError = null,\n\tthis.sampleListBuilt = !1,\n\tthis.fragmentedTracks = [],\n\tthis.extractedTracks = [],\n\tthis.isFragmentationInitialized = !1,\n\tthis.sampleProcessingStarted = !1,\n\tthis.nextMoofNumber = 0,\n\tthis.itemListBuilt = !1,\n\tthis.items = [],\n\tthis.entity_groups = [],\n\tthis.onSidx = null,\n\tthis.sidxSent = !1\n};\nISOFile.prototype.setSegmentOptions = function(t, e, i) {\n\tvar r, s = this.getTrackById(t);\n\ts && (r = {},\n\tthis.fragmentedTracks.push(r), r.id = t, r.user = e, (r.trak = s).nextSample = 0, r.segmentStream = null, r.nb_samples = 1e3, r.rapAlignement = !0, i && (i.nbSamples && (r.nb_samples = i.nbSamples), i.rapAlignement && (r.rapAlignement = i.rapAlignement)))\n},\nISOFile.prototype.unsetSegmentOptions = function(t) {\n\tfor (var e = -1,\n\ti = 0; i < this.fragmentedTracks.length; i++) this.fragmentedTracks[i].id == t && (e = i); - 1 < e && this.fragmentedTracks.splice(e, 1)\n},\nISOFile.prototype.setExtractionOptions = function(t, e, i) {\n\tvar r, s = this.getTrackById(t);\n\ts && (r = {},\n\tthis.extractedTracks.push(r), r.id = t, r.user = e, (r.trak = s).nextSample = 0, r.nb_samples = 1e3, r.samples = [], i && i.nbSamples && (r.nb_samples = i.nbSamples))\n},\nISOFile.prototype.unsetExtractionOptions = function(t) {\n\tfor (var e = -1,\n\ti = 0; i < this.extractedTracks.length; i++) this.extractedTracks[i].id == t && (e = i); - 1 < e && this.extractedTracks.splice(e, 1)\n},\nISOFile.prototype.parse = function() {\n\tvar t;\n\tif (!this.restoreParsePosition || this.restoreParsePosition()) for (;;) if (this.hasIncompleteMdat && this.hasIncompleteMdat()) {\n\t\tif (!this.processIncompleteMdat()) return\n\t} else if (this.saveParsePosition && this.saveParsePosition(), (t = BoxParser.parseOneBox(this.stream, !1)).code === BoxParser.ERR_NOT_ENOUGH_DATA) {\n\t\tif (!this.processIncompleteBox) return;\n\t\tif (!this.processIncompleteBox(t)) return\n\t} else {\n\t\tvar e, i = "uuid" !== (e = t.box).type ? e.type: e.uuid;\n\t\tswitch (this.boxes.push(e), i) {\n\t\tcase "mdat":\n\t\t\tthis.mdats.push(e);\n\t\t\tbreak;\n\t\tcase "moof":\n\t\t\tthis.moofs.push(e);\n\t\t\tbreak;\n\t\tcase "moov":\n\t\t\tthis.moovStartFound = !0,\n\t\t\t0 === this.mdats.length && (this.isProgressive = !0);\n\t\tdefault:\n\t\t\tvoid 0 !== this[i] && Log.warn("ISOFile", "Duplicate Box of type: " + i + ", overriding previous occurrence"),\n\t\t\tthis[i] = e\n\t\t}\n\t\tthis.updateUsedBytes && this.updateUsedBytes(e, t)\n\t}\n},\nISOFile.prototype.checkBuffer = function(t) {\n\tif (null == t) throw "Buffer must be defined and non empty";\n\tif (void 0 === t.fileStart) throw "Buffer must have a fileStart property";\n\treturn 0 === t.byteLength ? (Log.warn("ISOFile", "Ignoring empty buffer (fileStart: " + t.fileStart + ")"), this.stream.logBufferLevel(), !1) : (Log.info("ISOFile", "Processing buffer (fileStart: " + t.fileStart + ")"), t.usedBytes = 0, this.stream.insertBuffer(t), this.stream.logBufferLevel(), !!this.stream.initialized() || (Log.warn("ISOFile", "Not ready to start parsing"), !1))\n},\nISOFile.prototype.appendBuffer = function(t, e) {\n\tvar i;\n\tif (this.checkBuffer(t)) return this.parse(),\n\tthis.moovStartFound && !this.moovStartSent && (this.moovStartSent = !0, this.onMoovStart && this.onMoovStart()),\n\tthis.moov ? (this.sampleListBuilt || (this.buildSampleLists(), this.sampleListBuilt = !0), this.updateSampleLists(), this.onReady && !this.readySent && (this.readySent = !0, this.onReady(this.getInfo())), this.processSamples(e), this.nextSeekPosition ? (i = this.nextSeekPosition, this.nextSeekPosition = void 0) : i = this.nextParsePosition, this.stream.getEndFilePositionAfter && (i = this.stream.getEndFilePositionAfter(i))) : i = this.nextParsePosition || 0,\n\tthis.sidx && this.onSidx && !this.sidxSent && (this.onSidx(this.sidx), this.sidxSent = !0),\n\tthis.meta && (this.flattenItemInfo && !this.itemListBuilt && (this.flattenItemInfo(), this.itemListBuilt = !0), this.processItems && this.processItems(this.onItem)),\n\tthis.stream.cleanBuffers && (Log.info("ISOFile", "Done processing buffer (fileStart: " + t.fileStart + ") - next buffer to fetch should have a fileStart position of " + i), this.stream.logBufferLevel(), this.stream.cleanBuffers(), this.stream.logBufferLevel(!0), Log.info("ISOFile", "Sample data size in memory: " + this.getAllocatedSampleDataSize())),\n\ti\n},\nISOFile.prototype.getInfo = function() {\n\tvar t, e, i, r, s, a, n = {},\n\to = new Date("1904-01-01T00:00:00Z").getTime();\n\tif (this.moov) for (n.hasMoov = !0, n.duration = this.moov.mvhd.duration, n.timescale = this.moov.mvhd.timescale, n.isFragmented = null != this.moov.mvex, n.isFragmented && this.moov.mvex.mehd && (n.fragment_duration = this.moov.mvex.mehd.fragment_duration), n.isProgressive = this.isProgressive, n.hasIOD = null != this.moov.iods, n.brands = [], n.brands.push(this.ftyp.major_brand), n.brands = n.brands.concat(this.ftyp.compatible_brands), n.created = new Date(o + 1e3 * this.moov.mvhd.creation_time), n.modified = new Date(o + 1e3 * this.moov.mvhd.modification_time), n.tracks = [], n.audioTracks = [], n.videoTracks = [], n.subtitleTracks = [], n.metadataTracks = [], n.hintTracks = [], n.otherTracks = [], t = 0; t < this.moov.traks.length; t++) {\n\t\tif (a = (i = this.moov.traks[t]).mdia.minf.stbl.stsd.entries[0], r = {},\n\t\tn.tracks.push(r), r.id = i.tkhd.track_id, r.name = i.mdia.hdlr.name, r.references = [], i.tref) for (e = 0; e < i.tref.boxes.length; e++) s = {},\n\t\tr.references.push(s),\n\t\ts.type = i.tref.boxes[e].type,\n\t\ts.track_ids = i.tref.boxes[e].track_ids;\n\t\ti.edts && (r.edits = i.edts.elst.entries),\n\t\tr.created = new Date(o + 1e3 * i.tkhd.creation_time),\n\t\tr.modified = new Date(o + 1e3 * i.tkhd.modification_time),\n\t\tr.movie_duration = i.tkhd.duration,\n\t\tr.movie_timescale = n.timescale,\n\t\tr.layer = i.tkhd.layer,\n\t\tr.alternate_group = i.tkhd.alternate_group,\n\t\tr.volume = i.tkhd.volume,\n\t\tr.matrix = i.tkhd.matrix,\n\t\tr.track_width = i.tkhd.width / 65536,\n\t\tr.track_height = i.tkhd.height / 65536,\n\t\tr.timescale = i.mdia.mdhd.timescale,\n\t\tr.cts_shift = i.mdia.minf.stbl.cslg,\n\t\tr.duration = i.mdia.mdhd.duration,\n\t\tr.samples_duration = i.samples_duration,\n\t\tr.codec = a.getCodec(),\n\t\tr.kind = i.udta && i.udta.kinds.length ? i.udta.kinds[0] : {\n\t\t\tschemeURI: "",\n\t\t\tvalue: ""\n\t\t},\n\t\tr.language = i.mdia.elng ? i.mdia.elng.extended_language: i.mdia.mdhd.languageString,\n\t\tr.nb_samples = i.samples.length,\n\t\tr.size = i.samples_size,\n\t\tr.bitrate = 8 * r.size * r.timescale / r.samples_duration,\n\t\ta.isAudio() ? (r.type = "audio", n.audioTracks.push(r), r.audio = {},\n\t\tr.audio.sample_rate = a.getSampleRate(), r.audio.channel_count = a.getChannelCount(), r.audio.sample_size = a.getSampleSize()) : a.isVideo() ? (r.type = "video", n.videoTracks.push(r), r.video = {},\n\t\tr.video.width = a.getWidth(), r.video.height = a.getHeight()) : a.isSubtitle() ? (r.type = "subtitles", n.subtitleTracks.push(r)) : a.isHint() ? (r.type = "metadata", n.hintTracks.push(r)) : a.isMetadata() ? (r.type = "metadata", n.metadataTracks.push(r)) : (r.type = "metadata", n.otherTracks.push(r))\n\t} else n.hasMoov = !1;\n\tif (n.mime = "", n.hasMoov && n.tracks) {\n\t\tfor (n.videoTracks && 0 < n.videoTracks.length ? n.mime += \'video/mp4; codecs="\': n.audioTracks && 0 < n.audioTracks.length ? n.mime += \'audio/mp4; codecs="\': n.mime += \'application/mp4; codecs="\', t = 0; t < n.tracks.length; t++) 0 !== t && (n.mime += ","),\n\t\tn.mime += n.tracks[t].codec;\n\t\tn.mime += \'"; profiles="\',\n\t\tn.mime += this.ftyp.compatible_brands.join(),\n\t\tn.mime += \'"\'\n\t}\n\treturn n\n},\nISOFile.prototype.setNextSeekPositionFromSample = function(t) {\n\tt && (this.nextSeekPosition ? this.nextSeekPosition = Math.min(t.offset + t.alreadyRead, this.nextSeekPosition) : this.nextSeekPosition = t.offset + t.alreadyRead)\n},\nISOFile.prototype.processSamples = function(t) {\n\tvar e;\n\tif (this.sampleProcessingStarted) {\n\t\tif (this.isFragmentationInitialized && null !== this.onSegment) for (e = 0; e < this.fragmentedTracks.length; e++) for (var i = this.fragmentedTracks[e], r = i.trak; r.nextSample < r.samples.length && this.sampleProcessingStarted;) {\n\t\t\tLog.debug("ISOFile", "Creating media fragment on track #" + i.id + " for sample " + r.nextSample);\n\t\t\tvar s = this.createFragment(i.id, r.nextSample, i.segmentStream);\n\t\t\tif (!s) break;\n\t\t\tif (i.segmentStream = s, r.nextSample++, (r.nextSample % i.nb_samples == 0 || t || r.nextSample >= r.samples.length) && (Log.info("ISOFile", "Sending fragmented data on track #" + i.id + " for samples [" + Math.max(0, r.nextSample - i.nb_samples) + "," + (r.nextSample - 1) + "]"), Log.info("ISOFile", "Sample data size in memory: " + this.getAllocatedSampleDataSize()), this.onSegment && this.onSegment(i.id, i.user, i.segmentStream.buffer, r.nextSample, t || r.nextSample >= r.samples.length), i.segmentStream = null, i !== this.fragmentedTracks[e])) break\n\t\t}\n\t\tif (null !== this.onSamples) for (e = 0; e < this.extractedTracks.length; e++) {\n\t\t\tvar a = this.extractedTracks[e];\n\t\t\tfor (r = a.trak; r.nextSample < r.samples.length && this.sampleProcessingStarted;) {\n\t\t\t\tLog.debug("ISOFile", "Exporting on track #" + a.id + " sample #" + r.nextSample);\n\t\t\t\tvar n = this.getSample(r, r.nextSample);\n\t\t\t\tif (!n) {\n\t\t\t\t\tthis.setNextSeekPositionFromSample(r.samples[r.nextSample]);\n\t\t\t\t\tbreak\n\t\t\t\t}\n\t\t\t\tif (r.nextSample++, a.samples.push(n), (r.nextSample % a.nb_samples == 0 || r.nextSample >= r.samples.length) && (Log.debug("ISOFile", "Sending samples on track #" + a.id + " for sample " + r.nextSample), this.onSamples && this.onSamples(a.id, a.user, a.samples), a.samples = [], a !== this.extractedTracks[e])) break\n\t\t\t}\n\t\t}\n\t}\n},\nISOFile.prototype.getBox = function(t) {\n\tt = this.getBoxes(t, !0);\n\treturn t.length ? t[0] : null\n},\nISOFile.prototype.getBoxes = function(t, e) {\n\tvar i = [];\n\treturn ISOFile._sweep.call(this, t, i, e),\n\ti\n},\nISOFile._sweep = function(t, e, i) {\n\tfor (var r in this.type && this.type == t && e.push(this), this.boxes) {\n\t\tif (e.length && i) return;\n\t\tISOFile._sweep.call(this.boxes[r], t, e, i)\n\t}\n},\nISOFile.prototype.getTrackSamplesInfo = function(t) {\n\tt = this.getTrackById(t);\n\tif (t) return t.samples\n},\nISOFile.prototype.getTrackSample = function(t, e) {\n\tt = this.getTrackById(t);\n\treturn this.getSample(t, e)\n},\nISOFile.prototype.releaseUsedSamples = function(t, e) {\n\tvar i = 0,\n\tr = this.getTrackById(t);\n\tr.lastValidSample || (r.lastValidSample = 0);\n\tfor (var s = r.lastValidSample; s < e; s++) i += this.releaseSample(r, s);\n\tLog.info("ISOFile", "Track #" + t + " released samples up to " + e + " (released size: " + i + ", remaining: " + this.samplesDataSize + ")"),\n\tr.lastValidSample = e\n},\nISOFile.prototype.start = function() {\n\tthis.sampleProcessingStarted = !0,\n\tthis.processSamples(!1)\n},\nISOFile.prototype.stop = function() {\n\tthis.sampleProcessingStarted = !1\n},\nISOFile.prototype.flush = function() {\n\tLog.info("ISOFile", "Flushing remaining samples"),\n\tthis.updateSampleLists(),\n\tthis.processSamples(!0),\n\tthis.stream.cleanBuffers(),\n\tthis.stream.logBufferLevel(!0)\n},\nISOFile.prototype.seekTrack = function(t, e, i) {\n\tvar r, s, a, n, o = 0,\n\th = 0;\n\tif (0 === i.samples.length) return Log.info("ISOFile", "No sample in track, cannot seek! Using time " + Log.getDurationString(0, 1) + " and offset: 0"),\n\t{\n\t\toffset: 0,\n\t\ttime: 0\n\t};\n\tfor (r = 0; r < i.samples.length; r++) {\n\t\tif (s = i.samples[r], 0 === r) h = 0,\n\t\tn = s.timescale;\n\t\telse if (s.cts > t * s.timescale) {\n\t\t\th = r - 1;\n\t\t\tbreak\n\t\t}\n\t\te && s.is_sync && (o = r)\n\t}\n\tfor (e && (h = o), t = i.samples[h].cts, i.nextSample = h; i.samples[h].alreadyRead === i.samples[h].size && i.samples[h + 1];) h++;\n\treturn a = i.samples[h].offset + i.samples[h].alreadyRead,\n\tLog.info("ISOFile", "Seeking to " + (e ? "RAP": "") + " sample #" + i.nextSample + " on track " + i.tkhd.track_id + ", time " + Log.getDurationString(t, n) + " and offset: " + a),\n\t{\n\t\toffset: a,\n\t\ttime: t / n\n\t}\n},\nISOFile.prototype.getTrackDuration = function(t) {\n\treturn t.samples ? ((t = t.samples[t.samples.length - 1]).cts + t.duration) / t.timescale: 1 / 0\n},\nISOFile.prototype.seek = function(t, e) {\n\tvar i, r, s = this.moov,\n\ta = {\n\t\toffset: 1 / 0,\n\t\ttime: 1 / 0\n\t};\n\tif (this.moov) {\n\t\tfor (r = 0; r < s.traks.length; r++) i = s.traks[r],\n\t\tt > this.getTrackDuration(i) || ((i = this.seekTrack(t, e, i)).offset < a.offset && (a.offset = i.offset), i.time < a.time && (a.time = i.time));\n\t\treturn Log.info("ISOFile", "Seeking at time " + Log.getDurationString(a.time, 1) + " needs a buffer with a fileStart position of " + a.offset),\n\t\ta.offset === 1 / 0 ? a = {\n\t\t\toffset: this.nextParsePosition,\n\t\t\ttime: 0\n\t\t}: a.offset = this.stream.getEndFilePositionAfter(a.offset),\n\t\tLog.info("ISOFile", "Adjusted seek position (after checking data already in buffer): " + a.offset),\n\t\ta\n\t}\n\tthrow "Cannot seek: moov not received!"\n},\nISOFile.prototype.equal = function(t) {\n\tfor (var e = 0; e < this.boxes.length && e < t.boxes.length;) {\n\t\tvar i = this.boxes[e],\n\t\tr = t.boxes[e];\n\t\tif (!BoxParser.boxEqual(i, r)) return ! 1;\n\t\te++\n\t}\n\treturn ! 0\n},\n"undefined" != typeof exports && (exports.ISOFile = ISOFile),\nISOFile.prototype.lastBoxStartPosition = 0,\nISOFile.prototype.parsingMdat = null,\nISOFile.prototype.nextParsePosition = 0,\nISOFile.prototype.discardMdatData = !1,\nISOFile.prototype.processIncompleteBox = function(t) {\n\tvar e;\n\treturn "mdat" === t.type ? (e = new BoxParser[t.type + "Box"](t.size), this.parsingMdat = e, this.boxes.push(e), this.mdats.push(e), e.start = t.start, e.hdr_size = t.hdr_size, this.stream.addUsedBytes(e.hdr_size), this.lastBoxStartPosition = e.start + e.size, this.stream.seek(e.start + e.size, !1, this.discardMdatData) ? !(this.parsingMdat = null) : (this.moovStartFound ? this.nextParsePosition = this.stream.findEndContiguousBuf() : this.nextParsePosition = e.start + e.size, !1)) : ("moov" === t.type && (this.moovStartFound = !0, 0 === this.mdats.length && (this.isProgressive = !0)), !!this.stream.mergeNextBuffer && this.stream.mergeNextBuffer() ? (this.nextParsePosition = this.stream.getEndPosition(), !0) : (!t.type || this.moovStartFound ? this.nextParsePosition = this.stream.getEndPosition() : this.nextParsePosition = this.stream.getPosition() + t.size, !1))\n},\nISOFile.prototype.hasIncompleteMdat = function() {\n\treturn null !== this.parsingMdat\n},\nISOFile.prototype.processIncompleteMdat = function() {\n\tvar t = this.parsingMdat;\n\treturn this.stream.seek(t.start + t.size, !1, this.discardMdatData) ? (Log.debug("ISOFile", "Found \'mdat\' end in buffered data"), !(this.parsingMdat = null)) : (this.nextParsePosition = this.stream.findEndContiguousBuf(), !1)\n},\nISOFile.prototype.restoreParsePosition = function() {\n\treturn this.stream.seek(this.lastBoxStartPosition, !0, this.discardMdatData)\n},\nISOFile.prototype.saveParsePosition = function() {\n\tthis.lastBoxStartPosition = this.stream.getPosition()\n},\nISOFile.prototype.updateUsedBytes = function(t, e) {\n\tthis.stream.addUsedBytes && ("mdat" === t.type ? (this.stream.addUsedBytes(t.hdr_size), this.discardMdatData && this.stream.addUsedBytes(t.size - t.hdr_size)) : this.stream.addUsedBytes(t.size))\n},\nISOFile.prototype.add = BoxParser.Box.prototype.add,\nISOFile.prototype.addBox = BoxParser.Box.prototype.addBox,\nISOFile.prototype.init = function(t) {\n\tvar e = t || {},\n\tt = (this.add("ftyp").set("major_brand", e.brands && e.brands[0] || "iso4").set("minor_version", 0).set("compatible_brands", e.brands || ["iso4"]), this.add("moov"));\n\treturn t.add("mvhd").set("timescale", e.timescale || 600).set("rate", e.rate || 65536).set("creation_time", 0).set("modification_time", 0).set("duration", e.duration || 0).set("volume", e.width ? 0 : 256).set("matrix", [65536, 0, 0, 0, 65536, 0, 0, 0, 1073741824]).set("next_track_id", 1),\n\tt.add("mvex"),\n\tthis\n},\nISOFile.prototype.addTrack = function(t) {\n\tthis.moov || this.init(t);\n\tvar e = t || {};\n\te.width = e.width || 320,\n\te.height = e.height || 320,\n\te.id = e.id || this.moov.mvhd.next_track_id,\n\te.type = e.type || "avc1";\n\tvar i = this.moov.add("trak");\n\tthis.moov.mvhd.next_track_id = e.id + 1,\n\ti.add("tkhd").set("flags", BoxParser.TKHD_FLAG_ENABLED | BoxParser.TKHD_FLAG_IN_MOVIE | BoxParser.TKHD_FLAG_IN_PREVIEW).set("creation_time", 0).set("modification_time", 0).set("track_id", e.id).set("duration", e.duration || 0).set("layer", e.layer || 0).set("alternate_group", 0).set("volume", 1).set("matrix", [65536, 0, 0, 0, 65536, 0, 0, 0, 1073741824]).set("width", e.width << 16).set("height", e.height << 16);\n\tt = i.add("mdia");\n\tt.add("mdhd").set("creation_time", 0).set("modification_time", 0).set("timescale", e.timescale || 1).set("duration", e.media_duration || 0).set("language", e.language || "und"),\n\tt.add("hdlr").set("handler", e.hdlr || "vide").set("name", e.name || "Track created with MP4Box.js"),\n\tt.add("elng").set("extended_language", e.language || "fr-FR");\n\tvar r = t.add("minf");\n\tif (void 0 !== BoxParser[e.type + "SampleEntry"]) {\n\t\tvar s = new BoxParser[e.type + "SampleEntry"];\n\t\ts.data_reference_index = 1;\n\t\tvar a, n, o = "";\n\t\tfor (a in BoxParser.sampleEntryCodes) for (var h = BoxParser.sampleEntryCodes[a], d = 0; d < h.length; d++) if (-1 < h.indexOf(e.type)) {\n\t\t\to = a;\n\t\t\tbreak\n\t\t}\n\t\tswitch (o) {\n\t\tcase "Visual":\n\t\t\tr.add("vmhd").set("graphicsmode", 0).set("opcolor", [0, 0, 0]),\n\t\t\ts.set("width", e.width).set("height", e.height).set("horizresolution", 72 << 16).set("vertresolution", 72 << 16).set("frame_count", 1).set("compressorname", e.type + " Compressor").set("depth", 24),\n\t\t\te.avcDecoderConfigRecord ? ((n = new BoxParser.avcCBox).parse(new MP4BoxStream(e.avcDecoderConfigRecord)), s.addBox(n)) : e.hevcDecoderConfigRecord && ((n = new BoxParser.hvcCBox).parse(new MP4BoxStream(e.hevcDecoderConfigRecord)), s.addBox(n));\n\t\t\tbreak;\n\t\tcase "Audio":\n\t\t\tr.add("smhd").set("balance", e.balance || 0),\n\t\t\ts.set("channel_count", e.channel_count || 2).set("samplesize", e.samplesize || 16).set("samplerate", e.samplerate || 65536);\n\t\t\tbreak;\n\t\tcase "Hint":\n\t\t\tr.add("hmhd");\n\t\t\tbreak;\n\t\tcase "Subtitle":\n\t\t\tr.add("sthd"),\n\t\t\t"stpp" === e.type && s.set("namespace", e.namespace || "nonamespace").set("schema_location", e.schema_location || "").set("auxiliary_mime_types", e.auxiliary_mime_types || "");\n\t\t\tbreak;\n\t\tcase "Metadata":\n\t\tcase "System":\n\t\tdefault:\n\t\t\tr.add("nmhd")\n\t\t}\n\t\te.description && s.addBox(e.description),\n\t\te.description_boxes && e.description_boxes.forEach(function(t) {\n\t\t\ts.addBox(t)\n\t\t}),\n\t\tr.add("dinf").add("dref").addEntry((new BoxParser["url Box"]).set("flags", 1));\n\t\tt = r.add("stbl");\n\t\treturn t.add("stsd").addEntry(s),\n\t\tt.add("stts").set("sample_counts", []).set("sample_deltas", []),\n\t\tt.add("stsc").set("first_chunk", []).set("samples_per_chunk", []).set("sample_description_index", []),\n\t\tt.add("stco").set("chunk_offsets", []),\n\t\tt.add("stsz").set("sample_sizes", []),\n\t\tthis.moov.mvex.add("trex").set("track_id", e.id).set("default_sample_description_index", e.default_sample_description_index || 1).set("default_sample_duration", e.default_sample_duration || 0).set("default_sample_size", e.default_sample_size || 0).set("default_sample_flags", e.default_sample_flags || 0),\n\t\tthis.buildTrakSampleLists(i),\n\t\te.id\n\t}\n},\nBoxParser.Box.prototype.computeSize = function(t) {\n\tt = t || new DataStream;\n\tt.endianness = DataStream.BIG_ENDIAN,\n\tthis.write(t)\n},\nISOFile.prototype.addSample = function(t, e, i) {\n\tvar r = i || {},\n\ti = {},\n\tt = this.getTrackById(t);\n\tif (null !== t) {\n\t\ti.number = t.samples.length,\n\t\ti.track_id = t.tkhd.track_id,\n\t\ti.timescale = t.mdia.mdhd.timescale,\n\t\ti.description_index = r.sample_description_index ? r.sample_description_index - 1 : 0,\n\t\ti.description = t.mdia.minf.stbl.stsd.entries[i.description_index],\n\t\ti.data = e,\n\t\ti.size = e.byteLength,\n\t\ti.alreadyRead = i.size,\n\t\ti.duration = r.duration || 1,\n\t\ti.cts = r.cts || 0,\n\t\ti.dts = r.dts || 0,\n\t\ti.is_sync = r.is_sync || !1,\n\t\ti.is_leading = r.is_leading || 0,\n\t\ti.depends_on = r.depends_on || 0,\n\t\ti.is_depended_on = r.is_depended_on || 0,\n\t\ti.has_redundancy = r.has_redundancy || 0,\n\t\ti.degradation_priority = r.degradation_priority || 0,\n\t\ti.offset = 0,\n\t\ti.subsamples = r.subsamples,\n\t\tt.samples.push(i),\n\t\tt.samples_size += i.size,\n\t\tt.samples_duration += i.duration,\n\t\tvoid 0 === t.first_dts && (t.first_dts = r.dts),\n\t\tthis.processSamples();\n\t\tr = this.createSingleSampleMoof(i);\n\t\treturn this.addBox(r),\n\t\tr.computeSize(),\n\t\tr.trafs[0].truns[0].data_offset = r.size + 8,\n\t\tthis.add("mdat").data = new Uint8Array(e),\n\t\ti\n\t}\n},\nISOFile.prototype.createSingleSampleMoof = function(t) {\n\tvar e = 0,\n\te = t.is_sync ? 1 << 25 : 65536,\n\ti = new BoxParser.moofBox;\n\ti.add("mfhd").set("sequence_number", this.nextMoofNumber),\n\tthis.nextMoofNumber++;\n\tvar r = i.add("traf"),\n\ts = this.getTrackById(t.track_id);\n\treturn r.add("tfhd").set("track_id", t.track_id).set("flags", BoxParser.TFHD_FLAG_DEFAULT_BASE_IS_MOOF),\n\tr.add("tfdt").set("baseMediaDecodeTime", t.dts - (s.first_dts || 0)),\n\tr.add("trun").set("flags", BoxParser.TRUN_FLAGS_DATA_OFFSET | BoxParser.TRUN_FLAGS_DURATION | BoxParser.TRUN_FLAGS_SIZE | BoxParser.TRUN_FLAGS_FLAGS | BoxParser.TRUN_FLAGS_CTS_OFFSET).set("data_offset", 0).set("first_sample_flags", 0).set("sample_count", 1).set("sample_duration", [t.duration]).set("sample_size", [t.size]).set("sample_flags", [e]).set("sample_composition_time_offset", [t.cts - t.dts]),\n\ti\n},\nISOFile.prototype.lastMoofIndex = 0,\nISOFile.prototype.samplesDataSize = 0,\nISOFile.prototype.resetTables = function() {\n\tvar t, e;\n\tfor (this.initial_duration = this.moov.mvhd.duration, t = this.moov.mvhd.duration = 0; t < this.moov.traks.length; t++) { (e = this.moov.traks[t]).tkhd.duration = 0,\n\t\te.mdia.mdhd.duration = 0,\n\t\t(e.mdia.minf.stbl.stco || e.mdia.minf.stbl.co64).chunk_offsets = [],\n\t\t(i = e.mdia.minf.stbl.stsc).first_chunk = [],\n\t\ti.samples_per_chunk = [],\n\t\ti.sample_description_index = [],\n\t\t(e.mdia.minf.stbl.stsz || e.mdia.minf.stbl.stz2).sample_sizes = [],\n\t\t(i = e.mdia.minf.stbl.stts).sample_counts = [],\n\t\ti.sample_deltas = [],\n\t\t(i = e.mdia.minf.stbl.ctts) && (i.sample_counts = [], i.sample_offsets = []),\n\t\ti = e.mdia.minf.stbl.stss;\n\t\tvar i = e.mdia.minf.stbl.boxes.indexOf(i); - 1 != i && (e.mdia.minf.stbl.boxes[i] = null)\n\t}\n},\nISOFile.initSampleGroups = function(t, e, i, r, s) {\n\tvar a, n, o, h;\n\tfunction d(t, e, i) {\n\t\tthis.grouping_type = t,\n\t\tthis.grouping_type_parameter = e,\n\t\tthis.sbgp = i,\n\t\tthis.last_sample_in_run = -1,\n\t\tthis.entry_index = -1\n\t}\n\tfor (e && (e.sample_groups_info = []), t.sample_groups_info || (t.sample_groups_info = []), n = 0; n < i.length; n++) {\n\t\tfor (h = i[n].grouping_type + "/" + i[n].grouping_type_parameter, o = new d(i[n].grouping_type, i[n].grouping_type_parameter, i[n]), e && (e.sample_groups_info[h] = o), t.sample_groups_info[h] || (t.sample_groups_info[h] = o), a = 0; a < r.length; a++) r[a].grouping_type === i[n].grouping_type && (o.description = r[a], o.description.used = !0);\n\t\tif (s) for (a = 0; a < s.length; a++) s[a].grouping_type === i[n].grouping_type && (o.fragment_description = s[a], o.fragment_description.used = !0, o.is_fragment = !0)\n\t}\n\tif (e) {\n\t\tif (s) for (n = 0; n < s.length; n++) ! s[n].used && 2 <= s[n].version && (h = s[n].grouping_type + "/0", (o = new d(s[n].grouping_type, 0)).is_fragment = !0, e.sample_groups_info[h] || (e.sample_groups_info[h] = o))\n\t} else for (n = 0; n < r.length; n++) ! r[n].used && 2 <= r[n].version && (h = r[n].grouping_type + "/0", o = new d(r[n].grouping_type, 0), t.sample_groups_info[h] || (t.sample_groups_info[h] = o))\n},\nISOFile.setSampleGroupProperties = function(t, e, i, r) {\n\tvar s, a, n;\n\tfor (s in e.sample_groups = [], r) e.sample_groups[s] = {},\n\te.sample_groups[s].grouping_type = r[s].grouping_type,\n\te.sample_groups[s].grouping_type_parameter = r[s].grouping_type_parameter,\n\ti >= r[s].last_sample_in_run && (r[s].last_sample_in_run < 0 && (r[s].last_sample_in_run = 0), r[s].entry_index++, r[s].entry_index <= r[s].sbgp.entries.length - 1 && (r[s].last_sample_in_run += r[s].sbgp.entries[r[s].entry_index].sample_count)),\n\tr[s].entry_index <= r[s].sbgp.entries.length - 1 ? e.sample_groups[s].group_description_index = r[s].sbgp.entries[r[s].entry_index].group_description_index: e.sample_groups[s].group_description_index = -1,\n\t0 !== e.sample_groups[s].group_description_index && (n = r[s].fragment_description || r[s].description, 0 < e.sample_groups[s].group_description_index ? (a = 65535 < e.sample_groups[s].group_description_index ? (e.sample_groups[s].group_description_index >> 16) - 1 : e.sample_groups[s].group_description_index - 1, n && 0 <= a && (e.sample_groups[s].description = n.entries[a])) : n && 2 <= n.version && 0 < n.default_group_description_index && (e.sample_groups[s].description = n.entries[n.default_group_description_index - 1]))\n},\nISOFile.process_sdtp = function(t, e, i) {\n\te && (t ? (e.is_leading = t.is_leading[i], e.depends_on = t.sample_depends_on[i], e.is_depended_on = t.sample_is_depended_on[i], e.has_redundancy = t.sample_has_redundancy[i]) : (e.is_leading = 0, e.depends_on = 0, e.is_depended_on = 0, e.has_redundancy = 0))\n},\nISOFile.prototype.buildSampleLists = function() {\n\tfor (var t, e = 0; e < this.moov.traks.length; e++) t = this.moov.traks[e],\n\tthis.buildTrakSampleLists(t)\n},\nISOFile.prototype.buildTrakSampleLists = function(t) {\n\tvar e, i, r, s, a, n, o, h, d, l, p, f, u, _, c, m, x, g, y, B, S, P, U, b;\n\tif (t.samples = [], t.samples_duration = 0, t.samples_size = 0, i = t.mdia.minf.stbl.stco || t.mdia.minf.stbl.co64, r = t.mdia.minf.stbl.stsc, s = t.mdia.minf.stbl.stsz || t.mdia.minf.stbl.stz2, a = t.mdia.minf.stbl.stts, n = t.mdia.minf.stbl.ctts, o = t.mdia.minf.stbl.stss, h = t.mdia.minf.stbl.stsd, d = t.mdia.minf.stbl.subs, f = t.mdia.minf.stbl.stdp, l = t.mdia.minf.stbl.sbgps, p = t.mdia.minf.stbl.sgpds, S = B = y = g = -1, b = U = P = 0, ISOFile.initSampleGroups(t, null, l, p), void 0 !== s) {\n\t\tfor (e = 0; e < s.sample_sizes.length; e++) {\n\t\t\tvar v = {};\n\t\t\tv.number = e,\n\t\t\tv.track_id = t.tkhd.track_id,\n\t\t\tv.timescale = t.mdia.mdhd.timescale,\n\t\t\tv.alreadyRead = 0,\n\t\t\t(t.samples[e] = v).size = s.sample_sizes[e],\n\t\t\tt.samples_size += v.size,\n\t\t\t0 === e ? (_ = 1, u = 0, v.chunk_index = _, v.chunk_run_index = u, x = r.samples_per_chunk[u], m = 0, c = u + 1 < r.first_chunk.length ? r.first_chunk[u + 1] - 1 : 1 / 0) : e < x ? (v.chunk_index = _, v.chunk_run_index = u) : (_++, m = 0, (v.chunk_index = _) <= c || (c = ++u + 1 < r.first_chunk.length ? r.first_chunk[u + 1] - 1 : 1 / 0), v.chunk_run_index = u, x += r.samples_per_chunk[u]),\n\t\t\tv.description_index = r.sample_description_index[v.chunk_run_index] - 1,\n\t\t\tv.description = h.entries[v.description_index],\n\t\t\tv.offset = i.chunk_offsets[v.chunk_index - 1] + m,\n\t\t\tm += v.size,\n\t\t\tg < e && (y++, g < 0 && (g = 0), g += a.sample_counts[y]),\n\t\t\t0 < e ? (t.samples[e - 1].duration = a.sample_deltas[y], t.samples_duration += t.samples[e - 1].duration, v.dts = t.samples[e - 1].dts + t.samples[e - 1].duration) : v.dts = 0,\n\t\t\tn ? (B <= e && (S++, B < 0 && (B = 0), B += n.sample_counts[S]), v.cts = t.samples[e].dts + n.sample_offsets[S]) : v.cts = v.dts,\n\t\t\to ? (e == o.sample_numbers[P] - 1 ? (v.is_sync = !0, P++) : (v.is_sync = !1, v.degradation_priority = 0), d && d.entries[U].sample_delta + b == e + 1 && (v.subsamples = d.entries[U].subsamples, b += d.entries[U].sample_delta, U++)) : v.is_sync = !0,\n\t\t\tISOFile.process_sdtp(t.mdia.minf.stbl.sdtp, v, v.number),\n\t\t\tv.degradation_priority = f ? f.priority[e] : 0,\n\t\t\td && d.entries[U].sample_delta + b == e && (v.subsamples = d.entries[U].subsamples, b += d.entries[U].sample_delta),\n\t\t\t(0 < l.length || 0 < p.length) && ISOFile.setSampleGroupProperties(t, v, e, t.sample_groups_info)\n\t\t}\n\t\t0 < e && (t.samples[e - 1].duration = Math.max(t.mdia.mdhd.duration - t.samples[e - 1].dts, 0), t.samples_duration += t.samples[e - 1].duration)\n\t}\n},\nISOFile.prototype.updateSampleLists = function() {\n\tvar t, e, i, r, s, a, n, o, h, d, l, p;\n\tif (void 0 !== this.moov) for (; this.lastMoofIndex < this.moofs.length;) if (n = this.moofs[this.lastMoofIndex], this.lastMoofIndex++, "moof" == n.type) for (o = n, t = 0; t < o.trafs.length; t++) {\n\t\tfor (h = o.trafs[t], d = this.getTrackById(h.tfhd.track_id), l = this.getTrexById(h.tfhd.track_id), e = h.tfhd.flags & BoxParser.TFHD_FLAG_SAMPLE_DESC ? h.tfhd.default_sample_description_index: l ? l.default_sample_description_index: 1, i = h.tfhd.flags & BoxParser.TFHD_FLAG_SAMPLE_DUR ? h.tfhd.default_sample_duration: l ? l.default_sample_duration: 0, r = h.tfhd.flags & BoxParser.TFHD_FLAG_SAMPLE_SIZE ? h.tfhd.default_sample_size: l ? l.default_sample_size: 0, s = h.tfhd.flags & BoxParser.TFHD_FLAG_SAMPLE_FLAGS ? h.tfhd.default_sample_flags: l ? l.default_sample_flags: 0, (h.sample_number = 0) < h.sbgps.length && ISOFile.initSampleGroups(d, h, h.sbgps, d.mdia.minf.stbl.sgpds, h.sgpds), y = 0; y < h.truns.length; y++) for (var f = h.truns[y], u = 0; u < f.sample_count; u++) { (p = {}).moof_number = this.lastMoofIndex,\n\t\t\tp.number_in_traf = h.sample_number,\n\t\t\th.sample_number++,\n\t\t\tp.number = d.samples.length,\n\t\t\th.first_sample_index = d.samples.length,\n\t\t\td.samples.push(p),\n\t\t\tp.track_id = d.tkhd.track_id,\n\t\t\tp.timescale = d.mdia.mdhd.timescale,\n\t\t\tp.description_index = e - 1,\n\t\t\tp.description = d.mdia.minf.stbl.stsd.entries[p.description_index],\n\t\t\tp.size = r,\n\t\t\tf.flags & BoxParser.TRUN_FLAGS_SIZE && (p.size = f.sample_size[u]),\n\t\t\td.samples_size += p.size,\n\t\t\tp.duration = i,\n\t\t\tf.flags & BoxParser.TRUN_FLAGS_DURATION && (p.duration = f.sample_duration[u]),\n\t\t\td.samples_duration += p.duration,\n\t\t\td.first_traf_merged || 0 < u ? p.dts = d.samples[d.samples.length - 2].dts + d.samples[d.samples.length - 2].duration: (h.tfdt ? p.dts = h.tfdt.baseMediaDecodeTime: p.dts = 0, d.first_traf_merged = !0),\n\t\t\tp.cts = p.dts,\n\t\t\tf.flags & BoxParser.TRUN_FLAGS_CTS_OFFSET && (p.cts = p.dts + f.sample_composition_time_offset[u]),\n\t\t\tx = s,\n\t\t\tf.flags & BoxParser.TRUN_FLAGS_FLAGS ? x = f.sample_flags[u] : 0 === u && f.flags & BoxParser.TRUN_FLAGS_FIRST_FLAG && (x = f.first_sample_flags),\n\t\t\tp.is_sync = !(x >> 16 & 1),\n\t\t\tp.is_leading = x >> 26 & 3,\n\t\t\tp.depends_on = x >> 24 & 3,\n\t\t\tp.is_depended_on = x >> 22 & 3,\n\t\t\tp.has_redundancy = x >> 20 & 3,\n\t\t\tp.degradation_priority = 65535 & x;\n\t\t\tvar _ = !!(h.tfhd.flags & BoxParser.TFHD_FLAG_BASE_DATA_OFFSET),\n\t\t\tc = !!(h.tfhd.flags & BoxParser.TFHD_FLAG_DEFAULT_BASE_IS_MOOF),\n\t\t\tm = !!(f.flags & BoxParser.TRUN_FLAGS_DATA_OFFSET),\n\t\t\tx = 0,\n\t\t\tx = _ ? h.tfhd.base_data_offset: c || 0 === y ? o.start: a;\n\t\t\tp.offset = 0 === y && 0 === u ? m ? x + f.data_offset: x: a,\n\t\t\ta = p.offset + p.size,\n\t\t\t(0 < h.sbgps.length || 0 < h.sgpds.length || 0 < d.mdia.minf.stbl.sbgps.length || 0 < d.mdia.minf.stbl.sgpds.length) && ISOFile.setSampleGroupProperties(d, p, p.number_in_traf, h.sample_groups_info)\n\t\t}\n\t\tif (h.subs) {\n\t\t\td.has_fragment_subsamples = !0;\n\t\t\tfor (var g = h.first_sample_index,\n\t\t\ty = 0; y < h.subs.entries.length; y++) g += h.subs.entries[y].sample_delta,\n\t\t\t(p = d.samples[g - 1]).subsamples = h.subs.entries[y].subsamples\n\t\t}\n\t}\n},\nISOFile.prototype.getSample = function(t, e) {\n\tvar i, r = t.samples[e];\n\tif (!this.moov) return null;\n\tif (r.data) {\n\t\tif (r.alreadyRead == r.size) return r\n\t} else r.data = new Uint8Array(r.size),\n\tr.alreadyRead = 0,\n\tthis.samplesDataSize += r.size,\n\tLog.debug("ISOFile", "Allocating sample #" + e + " on track #" + t.tkhd.track_id + " of size " + r.size + " (total: " + this.samplesDataSize + ")");\n\tfor (;;) {\n\t\tvar s = this.stream.findPosition(!0, r.offset + r.alreadyRead, !1);\n\t\tif (! (-1 < s)) return null;\n\t\ts = (i = this.stream.buffers[s]).byteLength - (r.offset + r.alreadyRead - i.fileStart);\n\t\tif (r.size - r.alreadyRead <= s) return Log.debug("ISOFile", "Getting sample #" + e + " data (alreadyRead: " + r.alreadyRead + " offset: " + (r.offset + r.alreadyRead - i.fileStart) + " read size: " + (r.size - r.alreadyRead) + " full size: " + r.size + ")"),\n\t\tDataStream.memcpy(r.data.buffer, r.alreadyRead, i, r.offset + r.alreadyRead - i.fileStart, r.size - r.alreadyRead),\n\t\ti.usedBytes += r.size - r.alreadyRead,\n\t\tthis.stream.logBufferLevel(),\n\t\tr.alreadyRead = r.size,\n\t\tr;\n\t\tif (0 == s) return null;\n\t\tLog.debug("ISOFile", "Getting sample #" + e + " partial data (alreadyRead: " + r.alreadyRead + " offset: " + (r.offset + r.alreadyRead - i.fileStart) + " read size: " + s + " full size: " + r.size + ")"),\n\t\tDataStream.memcpy(r.data.buffer, r.alreadyRead, i, r.offset + r.alreadyRead - i.fileStart, s),\n\t\tr.alreadyRead += s,\n\t\ti.usedBytes += s,\n\t\tthis.stream.logBufferLevel()\n\t}\n},\nISOFile.prototype.releaseSample = function(t, e) {\n\te = t.samples[e];\n\treturn e.data ? (this.samplesDataSize -= e.size, e.data = null, e.alreadyRead = 0, e.size) : 0\n},\nISOFile.prototype.getAllocatedSampleDataSize = function() {\n\treturn this.samplesDataSize\n},\nISOFile.prototype.getCodecs = function() {\n\tfor (var t = "",\n\te = 0; e < this.moov.traks.length; e++) 0 < e && (t += ","),\n\tt += this.moov.traks[e].mdia.minf.stbl.stsd.entries[0].getCodec();\n\treturn t\n},\nISOFile.prototype.getTrexById = function(t) {\n\tvar e;\n\tif (!this.moov || !this.moov.mvex) return null;\n\tfor (e = 0; e < this.moov.mvex.trexs.length; e++) {\n\t\tvar i = this.moov.mvex.trexs[e];\n\t\tif (i.track_id == t) return i\n\t}\n\treturn null\n},\nISOFile.prototype.getTrackById = function(t) {\n\tif (void 0 === this.moov) return null;\n\tfor (var e = 0; e < this.moov.traks.length; e++) {\n\t\tvar i = this.moov.traks[e];\n\t\tif (i.tkhd.track_id == t) return i\n\t}\n\treturn null\n},\nISOFile.prototype.itemsDataSize = 0,\nISOFile.prototype.flattenItemInfo = function() {\n\tvar t = this.items,\n\te = this.entity_groups,\n\ti = this.meta;\n\tif (null != i && void 0 !== i.hdlr && void 0 !== i.iinf) {\n\t\tfor (d = 0; d < i.iinf.item_infos.length; d++)(s = {}).id = i.iinf.item_infos[d].item_ID,\n\t\t(t[s.id] = s).ref_to = [],\n\t\ts.name = i.iinf.item_infos[d].item_name,\n\t\t0 < i.iinf.item_infos[d].protection_index && (s.protection = i.ipro.protections[i.iinf.item_infos[d].protection_index - 1]),\n\t\ti.iinf.item_infos[d].item_type ? s.type = i.iinf.item_infos[d].item_type: s.type = "mime",\n\t\ts.content_type = i.iinf.item_infos[d].content_type,\n\t\ts.content_encoding = i.iinf.item_infos[d].content_encoding,\n\t\ts.item_uri_type = i.iinf.item_infos[d].item_uri_type;\n\t\tif (i.grpl) for (d = 0; d < i.grpl.boxes.length; d++) entity_group = {},\n\t\tentity_group.id = i.grpl.boxes[d].group_id,\n\t\tentity_group.entity_ids = i.grpl.boxes[d].entity_ids,\n\t\tentity_group.type = i.grpl.boxes[d].type,\n\t\te[entity_group.id] = entity_group;\n\t\tif (i.iloc) for (d = 0; d < i.iloc.items.length; d++) {\n\t\t\tvar r = i.iloc.items[d],\n\t\t\ts = t[r.item_ID];\n\t\t\tswitch (0 !== r.data_reference_index && (Log.warn("Item storage with reference to other files: not supported"), s.source = i.dinf.boxes[r.data_reference_index - 1]), r.construction_method) {\n\t\t\tcase 0:\n\t\t\tcase 1:\n\t\t\t\tbreak;\n\t\t\tcase 2:\n\t\t\t\tLog.warn("Item storage with construction_method : not supported")\n\t\t\t}\n\t\t\tfor (s.extents = [], n = s.size = 0; n < r.extents.length; n++) s.extents[n] = {},\n\t\t\ts.extents[n].offset = r.extents[n].extent_offset + r.base_offset,\n\t\t\t1 == r.construction_method && (s.extents[n].offset += i.idat.start + i.idat.hdr_size),\n\t\t\ts.extents[n].length = r.extents[n].extent_length,\n\t\t\ts.extents[n].alreadyRead = 0,\n\t\t\ts.size += s.extents[n].length\n\t\t}\n\t\tif (i.pitm && (t[i.pitm.item_id].primary = !0), i.iref) for (d = 0; d < i.iref.references.length; d++) for (var a = i.iref.references[d], n = 0; n < a.references.length; n++) t[a.from_item_ID].ref_to.push({\n\t\t\ttype: a.type,\n\t\t\tid: a.references[n]\n\t\t});\n\t\tif (i.iprp) for (var o = 0; o < i.iprp.ipmas.length; o++) for (var h = i.iprp.ipmas[o], d = 0; d < h.associations.length; d++) {\n\t\t\tvar l = h.associations[d];\n\t\t\tif (s = (s = t[l.id]) || e[l.id]) for (void 0 === s.properties && (s.properties = {},\n\t\t\ts.properties.boxes = []), n = 0; n < l.props.length; n++) {\n\t\t\t\tvar p = l.props[n];\n\t\t\t\t0 < p.property_index && p.property_index - 1 < i.iprp.ipco.boxes.length && (p = i.iprp.ipco.boxes[p.property_index - 1], s.properties[p.type] = p, s.properties.boxes.push(p))\n\t\t\t}\n\t\t}\n\t}\n},\nISOFile.prototype.getItem = function(t) {\n\tvar e, i;\n\tif (!this.meta) return null;\n\tif (! (i = this.items[t]).data && i.size) i.data = new Uint8Array(i.size),\n\ti.alreadyRead = 0,\n\tthis.itemsDataSize += i.size,\n\tLog.debug("ISOFile", "Allocating item #" + t + " of size " + i.size + " (total: " + this.itemsDataSize + ")");\n\telse if (i.alreadyRead === i.size) return i;\n\tfor (var r = 0; r < i.extents.length; r++) {\n\t\tvar s = i.extents[r];\n\t\tif (s.alreadyRead !== s.length) {\n\t\t\tvar a = this.stream.findPosition(!0, s.offset + s.alreadyRead, !1);\n\t\t\tif (! (-1 < a)) return null;\n\t\t\ta = (e = this.stream.buffers[a]).byteLength - (s.offset + s.alreadyRead - e.fileStart);\n\t\t\tif (! (s.length - s.alreadyRead <= a)) return Log.debug("ISOFile", "Getting item #" + t + " extent #" + r + " partial data (alreadyRead: " + s.alreadyRead + " offset: " + (s.offset + s.alreadyRead - e.fileStart) + " read size: " + a + " full extent size: " + s.length + " full item size: " + i.size + ")"),\n\t\t\tDataStream.memcpy(i.data.buffer, i.alreadyRead, e, s.offset + s.alreadyRead - e.fileStart, a),\n\t\t\ts.alreadyRead += a,\n\t\t\ti.alreadyRead += a,\n\t\t\te.usedBytes += a,\n\t\t\tthis.stream.logBufferLevel(),\n\t\t\tnull;\n\t\t\tLog.debug("ISOFile", "Getting item #" + t + " extent #" + r + " data (alreadyRead: " + s.alreadyRead + " offset: " + (s.offset + s.alreadyRead - e.fileStart) + " read size: " + (s.length - s.alreadyRead) + " full extent size: " + s.length + " full item size: " + i.size + ")"),\n\t\t\tDataStream.memcpy(i.data.buffer, i.alreadyRead, e, s.offset + s.alreadyRead - e.fileStart, s.length - s.alreadyRead),\n\t\t\te.usedBytes += s.length - s.alreadyRead,\n\t\t\tthis.stream.logBufferLevel(),\n\t\t\ti.alreadyRead += s.length - s.alreadyRead,\n\t\t\ts.alreadyRead = s.length\n\t\t}\n\t}\n\treturn i.alreadyRead === i.size ? i: null\n},\nISOFile.prototype.releaseItem = function(t) {\n\tvar e = this.items[t];\n\tif (e.data) {\n\t\tthis.itemsDataSize -= e.size,\n\t\te.data = null;\n\t\tfor (var i = e.alreadyRead = 0; i < e.extents.length; i++) e.extents[i].alreadyRead = 0;\n\t\treturn e.size\n\t}\n\treturn 0\n},\nISOFile.prototype.processItems = function(t) {\n\tfor (var e in this.items) {\n\t\tvar i = this.items[e];\n\t\tthis.getItem(i.id),\n\t\tt && !i.sent && (t(i), i.sent = !0, i.data = null)\n\t}\n},\nISOFile.prototype.hasItem = function(t) {\n\tfor (var e in this.items) {\n\t\tvar i = this.items[e];\n\t\tif (i.name === t) return i.id\n\t}\n\treturn - 1\n},\nISOFile.prototype.getMetaHandler = function() {\n\treturn this.meta ? this.meta.hdlr.handler: null\n},\nISOFile.prototype.getPrimaryItem = function() {\n\treturn this.meta && this.meta.pitm ? this.getItem(this.meta.pitm.item_id) : null\n},\nISOFile.prototype.itemToFragmentedTrackFile = function(t) {\n\tvar e = t || {},\n\ti = null;\n\tif (null == (i = e.itemId ? this.getItem(e.itemId) : this.getPrimaryItem())) return null;\n\tt = new ISOFile;\n\tt.discardMdatData = !1;\n\te = {\n\t\ttype: i.type,\n\t\tdescription_boxes: i.properties.boxes\n\t};\n\ti.properties.ispe && (e.width = i.properties.ispe.image_width, e.height = i.properties.ispe.image_height);\n\te = t.addTrack(e);\n\treturn e ? (t.addSample(e, i.data), t) : null\n},\nISOFile.prototype.write = function(t) {\n\tfor (var e = 0; e < this.boxes.length; e++) this.boxes[e].write(t)\n},\nISOFile.prototype.createFragment = function(t, e, i) {\n\tvar r = this.getTrackById(t),\n\tt = this.getSample(r, e);\n\tif (null == t) return this.setNextSeekPositionFromSample(r.samples[e]),\n\tnull;\n\te = i || new DataStream;\n\te.endianness = DataStream.BIG_ENDIAN;\n\ti = this.createSingleSampleMoof(t);\n\ti.write(e),\n\ti.trafs[0].truns[0].data_offset = i.size + 8,\n\tLog.debug("MP4Box", "Adjusting data_offset with new value " + i.trafs[0].truns[0].data_offset),\n\te.adjustUint32(i.trafs[0].truns[0].data_offset_position, i.trafs[0].truns[0].data_offset);\n\ti = new BoxParser.mdatBox;\n\treturn i.data = t.data,\n\ti.write(e),\n\te\n},\nISOFile.writeInitializationSegment = function(t, e, i, r) {\n\tvar s;\n\tLog.debug("ISOFile", "Generating initialization segment");\n\tvar a = new DataStream;\n\ta.endianness = DataStream.BIG_ENDIAN,\n\tt.write(a);\n\tvar n = e.add("mvex");\n\tfor (i && n.add("mehd").set("fragment_duration", i), s = 0; s < e.traks.length; s++) n.add("trex").set("track_id", e.traks[s].tkhd.track_id).set("default_sample_description_index", 1).set("default_sample_duration", r).set("default_sample_size", 0).set("default_sample_flags", 65536);\n\treturn e.write(a),\n\ta.buffer\n},\nISOFile.prototype.save = function(t) {\n\tvar e = new DataStream;\n\te.endianness = DataStream.BIG_ENDIAN,\n\tthis.write(e),\n\te.save(t)\n},\nISOFile.prototype.getBuffer = function() {\n\tvar t = new DataStream;\n\treturn t.endianness = DataStream.BIG_ENDIAN,\n\tthis.write(t),\n\tt.buffer\n},\nISOFile.prototype.initializeSegmentation = function() {\n\tvar t, e, i, r;\n\tfor (null === this.onSegment && Log.warn("MP4Box", "No segmentation callback set!"), this.isFragmentationInitialized || (this.isFragmentationInitialized = !0, this.nextMoofNumber = 0, this.resetTables()), e = [], t = 0; t < this.fragmentedTracks.length; t++) {\n\t\tvar s = new BoxParser.moovBox;\n\t\ts.mvhd = this.moov.mvhd,\n\t\ts.boxes.push(s.mvhd),\n\t\ti = this.getTrackById(this.fragmentedTracks[t].id),\n\t\ts.boxes.push(i),\n\t\ts.traks.push(i),\n\t\t(r = {}).id = i.tkhd.track_id,\n\t\tr.user = this.fragmentedTracks[t].user,\n\t\tr.buffer = ISOFile.writeInitializationSegment(this.ftyp, s, this.moov.mvex && this.moov.mvex.mehd ? this.moov.mvex.mehd.fragment_duration: void 0, 0 < this.moov.traks[t].samples.length ? this.moov.traks[t].samples[0].duration: 0),\n\t\te.push(r)\n\t}\n\treturn e\n},\nBoxParser.Box.prototype.printHeader = function(t) {\n\tthis.size += 8,\n\tthis.size > MAX_SIZE && (this.size += 8),\n\t"uuid" === this.type && (this.size += 16),\n\tt.log(t.indent + "size:" + this.size),\n\tt.log(t.indent + "type:" + this.type)\n},\nBoxParser.FullBox.prototype.printHeader = function(t) {\n\tthis.size += 4,\n\tBoxParser.Box.prototype.printHeader.call(this, t),\n\tt.log(t.indent + "version:" + this.version),\n\tt.log(t.indent + "flags:" + this.flags)\n},\nBoxParser.Box.prototype.print = function(t) {\n\tthis.printHeader(t)\n},\nBoxParser.ContainerBox.prototype.print = function(t) {\n\tthis.printHeader(t);\n\tfor (var e, i = 0; i < this.boxes.length; i++) this.boxes[i] && (e = t.indent, t.indent += " ", this.boxes[i].print(t), t.indent = e)\n},\nISOFile.prototype.print = function(t) {\n\tt.indent = "";\n\tfor (var e = 0; e < this.boxes.length; e++) this.boxes[e] && this.boxes[e].print(t)\n},\nBoxParser.mvhdBox.prototype.print = function(t) {\n\tBoxParser.FullBox.prototype.printHeader.call(this, t),\n\tt.log(t.indent + "creation_time: " + this.creation_time),\n\tt.log(t.indent + "modification_time: " + this.modification_time),\n\tt.log(t.indent + "timescale: " + this.timescale),\n\tt.log(t.indent + "duration: " + this.duration),\n\tt.log(t.indent + "rate: " + this.rate),\n\tt.log(t.indent + "volume: " + (this.volume >> 8)),\n\tt.log(t.indent + "matrix: " + this.matrix.join(", ")),\n\tt.log(t.indent + "next_track_id: " + this.next_track_id)\n},\nBoxParser.tkhdBox.prototype.print = function(t) {\n\tBoxParser.FullBox.prototype.printHeader.call(this, t),\n\tt.log(t.indent + "creation_time: " + this.creation_time),\n\tt.log(t.indent + "modification_time: " + this.modification_time),\n\tt.log(t.indent + "track_id: " + this.track_id),\n\tt.log(t.indent + "duration: " + this.duration),\n\tt.log(t.indent + "volume: " + (this.volume >> 8)),\n\tt.log(t.indent + "matrix: " + this.matrix.join(", ")),\n\tt.log(t.indent + "layer: " + this.layer),\n\tt.log(t.indent + "alternate_group: " + this.alternate_group),\n\tt.log(t.indent + "width: " + this.width),\n\tt.log(t.indent + "height: " + this.height)\n};\nvar MP4Box = {\n\tcreateFile: function(t, e) {\n\t\tt = void 0 === t || t,\n\t\te = new ISOFile(e);\n\t\treturn e.discardMdatData = !t,\n\t\te\n\t}\n};\n"undefined" != typeof exports && (exports.createFile = MP4Box.createFile);\n',workerLogic="\n// 显式将变量绑定到self上,确保全局可访问\nself.abortFlag = false;\nself.mp4boxfile = null;\nself.videoDecoder = null;\nself.samplesInRange = [];\nself.videoTrack = null;\nself.arrayBuffer = null;\n\nonmessage = function(e) {\n if (e.data.type === 'decode') {\n self.abortFlag = false;\n decodeFile(e.data.file, e.data.start, e.data.end, e.data.hardwareAcceleration);\n } else if (e.data.type === 'abort') {\n self.abortFlag = true;\n // 主动销毁所有大对象和引用\n if (self.videoDecoder) {\n try {\n self.videoDecoder.flush();\n self.videoDecoder.reset();\n self.videoDecoder.close();\n } catch (err) {}\n self.videoDecoder = null;\n }\n if (self.mp4boxfile) {\n try { self.mp4boxfile.flush(); } catch (err) {}\n self.mp4boxfile = null;\n }\n self.samplesInRange = [];\n self.videoTrack = null;\n self.arrayBuffer = null;\n // 关闭worker\n self.close();\n }\n};\n\nfunction decodeFile(file, startFrame, endFrame, hardwareAcceleration) {\n self.arrayBuffer = file.data;\n self.mp4boxfile = MP4Box.createFile();\n self.videoTrack = null;\n let nbSampleTotal = 0;\n self.samplesInRange = [];\n self.videoDecoder = null;\n let frameIndex = 0;\n let totalFrames = 0;\n self.mp4boxfile.onReady = function(info) {\n self.videoTrack = info.videoTracks[0];\n nbSampleTotal = self.videoTrack.nb_samples;\n self.mp4boxfile.setExtractionOptions(self.videoTrack.id, null, {\n nbSamples: nbSampleTotal,\n rapAlignement: true\n });\n self.mp4boxfile.start();\n };\n self.mp4boxfile.onSamples = async function(trackId, ref, samples) {\n if (self.abortFlag) return; // 确保使用self访问\n // 自动对齐到区间内第一个关键帧\n let startIdx = Math.min(0, startFrame); // 修复Math.min, 因为仅有第一帧是关键帧\n let endIdx = Math.min(samples.length - 1, endFrame);\n while (startIdx <= endIdx && !samples[startIdx].is_sync) {\n startIdx++;\n }\n if (startIdx > endIdx) {\n // 区间内没有关键帧,直接done\n postMessage({ type: 'done' });\n return;\n }\n self.samplesInRange = samples.slice(0, endIdx + 1);\n totalFrames = self.samplesInRange.length;\n if (!self.videoDecoder) {\n self.videoDecoder = new VideoDecoder({\n output: handleFrame,\n error: err => {\n postMessage({ type: 'error', error: err.message })\n }\n });\n const entry = self.mp4boxfile.moov.traks[0].mdia.minf.stbl.stsd.entries[0];\n const box = entry.avcC ?? entry.hvcC ?? entry.vpcC;\n let description = undefined;\n if (box) {\n const stream = new DataStream(undefined, 0, DataStream.BIG_ENDIAN);\n box.write(stream);\n description = new Uint8Array(stream.buffer.slice(8));\n }\n\t\tconst isIOS = /(iPhone|iPad|iPod|iOS)/i.test(navigator.userAgent);\n \tconst userAgent = (navigator.userAgent || \"\").toLowerCase();\n\t const isAndroid = /android/.test(userAgent) || /openharmony|arkweb/.test(userAgent);\n\t\tconst defaultConfig = {\n\t\t\tcodec: self.videoTrack.codec,\n\t\t\tcodedWidth: self.videoTrack.track_width,\n\t\t\tcodedHeight: self.videoTrack.track_height,\n\t\t\tdescription,\n\t\t}\n\t\t// Android 系统下,默认配置为 prefer-software 以避免硬件解码问题\n\t\tlet config = isAndroid ? { ...defaultConfig, hardwareAcceleration: 'prefer-software' } : hardwareAcceleration === 'default' ? defaultConfig\t: {\n\t\t\t...defaultConfig,\n\t\t\thardwareAcceleration: hardwareAcceleration,\n\t\t}\n\t\t// let config = hardwareAcceleration === 'default' ? defaultConfig\t: {\n\t\t// \t...defaultConfig,\n\t\t// \thardwareAcceleration: hardwareAcceleration,\n\t\t// }\n\t\tconst configSupport = (await VideoDecoder.isConfigSupported(config));\n\t\tconst isConfigSupported = configSupport.supported;\n\t\tpostMessage({ type: 'configSupport', configSupport: { config, configSupport}});\n\t\tlet isDefaultConfigSupported = false;\n\t\tif(!isConfigSupported) {\n\t\t\tconst defaultConfigSupport = await VideoDecoder.isConfigSupported(defaultConfig);\n\t\t\tpostMessage({ type: 'configSupport', configSupport: { defaultConfig, configSupport: defaultConfigSupport}});\n\t\t\tisDefaultConfigSupported = defaultConfigSupport.supported;\n\t\t}\n\t\tif(isConfigSupported) {\n\t\t\tself.videoDecoder.configure(config);\n\t\t} else if(isDefaultConfigSupported) {\n\t\t\tself.videoDecoder.configure(defaultConfig);\n\t\t} else {\n\t\t\tpostMessage({ type: 'error', error: '不支持的视频解码配置' });\n\t\t}\n }\n for (let i = 0; i < self.samplesInRange.length; i++) {\n if (self.abortFlag) break; // 确保使用self访问\n \n const sample = self.samplesInRange[i];\n const chunk = new EncodedVideoChunk({\n type: sample.is_sync ? 'key' : 'delta',\n timestamp: sample.cts,\n duration: sample.duration,\n data: sample.data\n });\n self.videoDecoder.decode(chunk);\n }\n self.videoDecoder.flush().then(() => {\n postMessage({ type: 'done' });\n });\n };\n function handleFrame(videoFrame) {\n if (self.abortFlag) { // 确保使用self访问\n videoFrame.close();\n return;\n }\n postMessage({ type: 'frame', frame: videoFrame, index: frameIndex++, total: totalFrames }, [videoFrame]);\n }\n self.arrayBuffer.fileStart = 0;\n self.mp4boxfile.appendBuffer(self.arrayBuffer);\n self.mp4boxfile.flush();\n}\n",fullWorkerScript=`\ntry {\n ${mp4boxSource}\n self.MP4Box = MP4Box;\n ${workerLogic}\n} catch (error) {\n console.error('Worker初始化失败:', error);\n throw error;\n}\n`,blob=new Blob([fullWorkerScript],{type:"application/javascript"}),workerURL=URL.createObjectURL(blob);var streamingVideo={__proto__:null,workerURL};function base64ToUint8Array(t){if(!t||""===t.trim())return new Uint8Array(0);const e=atob(t),n=new Uint8Array(e.length);for(let t=0;t<e.length;t++)n[t]=e.charCodeAt(t);return n}function twoByteToInt16(t,e){const n=t|e<<8;return Math.max(-32767,Math.min(32767,n>32767?n-65536:n))}function scaledInt16BytesToFloat32(t){const e=base64ToUint8Array(t);if(0===e.length||e.length%2!=0)return[];const n=e.length/2,r=new ArrayBuffer(4*n),i=new Float32Array(r);for(let t=0;t<n;t++){const n=2*t,r=twoByteToInt16(e[n],e[n+1]);i[t]=r/32767}return Array.from(i)}function parseUint8ToFloat32(t){if(!t||0===t.length)return[];if(t.length%4!=0)return window.avatarSDKLogger.error("Uint8Array长度不是4的倍数,无法解析为float32数组"),[];const e=new ArrayBuffer(t.length);new Uint8Array(e).set(t);const n=new Float32Array(e);return Array.from(n)}class ParallelDecoder{constructor(t){this.pendingAbort=!1,this.abortAfterEf=null,this.pendingNewQueue=null,this.currentDecodedFrameIndex=null,this.abortAfterFrame=null,this.cacheVideoCount=5,this.maxVideoCount=2,this.hardwareAcceleration="default",this.MAX_LOAD_VIDEO_TIMEOUT_MS=2e3,this._offlineLastFrame=0,this._offlineIdle=[],this._offlineIdleIndex=0,this.firstDecodeFrame=!0,this.tasks=new Map,this.queue=[],this.maxParallel=1,this.currentParallel=0,this._locked=!1,this.currentTaskId=null,this.resourceManager=t.resourceManager,this.onFrame=()=>{},this.onDone=()=>{},this.isFirstDecode=!0,this.saveAndDownload=t.saveAndDownload,this.dataCacheQueue=t.dataCacheQueue,this.bodyFrameCountMap=new Map,this.hardwareAcceleration=t.hardwareAcceleration,this.reportMessage=t.reportMessage}getRandomTaskId(){return Date.now()+"_"+Math.random().toString(36).slice(2,10)}decode(t,e){if(this.isFirstDecode){if(this._locked)return;this.abort(),this._locked=!0,this.queue=t,this.onFrame=(t,n,r)=>{this.currentDecodedFrameIndex=t.startFrameIndex+r,this._handlePendingAbort(t,r),e(t,n,r)},this.currentParallel=0,this.currentTaskId=this.getRandomTaskId(),this.isFirstDecode=!1}else this.updateQueue(t)}clearOldQueue(t){this.queue=this.queue.filter(e=>e.sf>=t)}updateQueue(t){if(this.abortAfterFrame=null,0===this.queue.length)return void this.queue.push(...t);const e=this.queue[0].sf,n=t[0].sf;if(n>=this.queue[this.queue.length-1].ef)this.queue.push(...t);else if(n<e){if(null!==this.currentDecodedFrameIndex&&n>this.currentDecodedFrameIndex+1){this.abortAfterFrame=n-1;const e=this.queue.filter(t=>t.ef<n);return void(this.queue=e.concat(t))}this.abort(),this.queue=t.slice(),this._locked=!0,this.currentTaskId=this.getRandomTaskId(),this.dataCacheQueue.clearOldFrames(this.queue[0].sf)}else if(n===e)this.queue=t.slice(),this.dataCacheQueue.clearOldFrames(this.queue[0].sf);else{const e=this.queue.findIndex(t=>t.sf>=n);-1!==e&&(this.queue.length=e),this.abortAfterFrame=n-1,this.queue.push(...t)}}_isIOS(){return/iPad|iPhone|iPod|iOS/.test(navigator.userAgent)}getQueue(){return this.queue.map(t=>_extends({},t,{x_offset:[]}))}timeoutPromise(t,e="请求超时"){return new Promise((e,n)=>{setTimeout(()=>{n()},t)})}async loadVideoWithTimeout(t){try{return await Promise.race([this.resourceManager.loadVideo(t),this.timeoutPromise(this.MAX_LOAD_VIDEO_TIMEOUT_MS,`视频 ${t} 加载超时(${this.MAX_LOAD_VIDEO_TIMEOUT_MS}ms)`)])}catch(t){return null}}async _tryStartNext(){var t;let e;if(e=(null==(t=this.queue)?void 0:t.some(t=>null!==this.currentDecodedFrameIndex&&t.sf<this.currentDecodedFrameIndex))?this._isIOS()?this.maxVideoCount:this.maxVideoCount+1:this._isIOS()?1:this.maxVideoCount,!(this.dataCacheQueue.getBodyVideoNameListLength()>=e)&&this.currentParallel<this.maxParallel&&this.queue.length>0){var n,r;const t=this.queue.shift();if(this.saveAndDownload.appendMultipleToArray("videoData",[_extends({},t,{x_offset:parseUint8ToFloat32(t.x_offset)||[]})]),this._cleanupOldWorkers(null!=(n=null!=(r=t.body_id)?r:t.id)?n:0),this.currentParallel++,window.performanceTracker.markStart(performanceConstant.load_video,t),!t.n)return this.currentParallel--,this._tryStartNext(),void this.reportMessage({code:EErrorCode.INVALID_BODY_NAME,message:`body数据无Name: ${JSON.stringify(t)}`});const e=await this.loadVideoWithTimeout(t.n);if(!e)return this.currentParallel--,void this._tryStartNext();window.performanceTracker.markEnd(performanceConstant.load_video,t),window.performanceTracker.markStart(performanceConstant.decode_video,t),window.performanceTracker.markStart(performanceConstant.first_decode_video,t),this._startWorker({name:t.n,id:t.id,frameState:t.s,start:t.asf,end:t.aef,hfd:t.hfd,data:e,startFrameIndex:t.sf,endFrameIndex:t.ef,body_id:t.body_id,x_offset:parseUint8ToFloat32(t.x_offset)||[]})}}_startWorker(t){var e,n;const r=this.currentTaskId;let i;try{i=new Worker(workerURL)}catch(t){return void this.reportMessage({code:EErrorCode.INIT_WORKER_ERROR,message:"初始化视频抽帧Worker失败",e:t})}const s=`${null!=(e=null!=(n=t.body_id)?n:t.id)?e:0}_${t.name}`,a=t.data,o=new ArrayBuffer(a.byteLength);new Uint8Array(o).set(new Uint8Array(a)),i.addEventListener("error",t=>{r===this.currentTaskId&&this.reportMessage({code:EErrorCode.INIT_WORKER_ERROR,message:"视频抽帧Worker运行时错误",e:t})});const l=e=>{if(r===this.currentTaskId)if("frame"===e.data.type)if(this.firstDecodeFrame&&(this.firstDecodeFrame=!1,window.performanceTracker.markEnd(performanceConstant.first_decode_video,t)),e.data.index<t.start||e.data.index>t.end)e.data.frame.close();else{var n;this.cacheVideo(),this.onFrame(t,e.data.frame,e.data.index);const r=null!=(n=this.bodyFrameCountMap.get(t.name))?n:0;this.bodyFrameCountMap.set(t.name,r+1),this.abortAfterFrame&&e.data.index+t.startFrameIndex>=this.abortAfterFrame&&(window.avatarSDKLogger.log("abortAfterFrame",this.abortAfterFrame,t),this.abortOne(s),this.abortAfterFrame=null,this._tryStartNext())}else if("configSupport"===e.data.type)window.avatarSDKLogger.log("configSupport",e.data);else if("done"===e.data.type){var a;window.performanceTracker.markEnd(performanceConstant.decode_video,t),(null!=(a=this.bodyFrameCountMap.get(t.name))?a:0)<t.end-t.start-1&&this.bodyFrameCountMap.delete(t.name);const e=this.tasks.get(s);e&&(e.status="done",e.worker.postMessage({type:"abort"})),this.currentParallel--,this.onDone&&this.onDone(t,s),i.removeEventListener("message",l),i.terminate(),this.tasks.delete(s),0===this.currentParallel&&0===this.queue.length&&(this._locked=!1),this._tryStartNext()}else if("error"===e.data.type){var o;const n=null!=(o=e.data.error)?o:"",r=n.includes("不支持")?EErrorCode.PROCESS_VIDEO_STREAM_ERROR:EErrorCode.VIDEO_FRAME_EXTRACT_ERROR;this.reportMessage({code:r,message:n||"视频解码错误",e:{fileName:t.name,error:n}});const a=this.tasks.get(s);a&&(a.status="error",a.worker.postMessage({type:"abort"})),this.currentParallel--,this.onDone&&this.onDone(t,s),i.removeEventListener("message",l),i.terminate(),this.tasks.delete(s),0===this.currentParallel&&0===this.queue.length&&(this._locked=!1)}};i.addEventListener("message",l),this.tasks.set(s,{worker:i,status:"decoding",onMessage:l,ef:t.endFrameIndex}),window.avatarSDKLogger.log("start decode",t.name,t.startFrameIndex,t.endFrameIndex),i.postMessage({type:"decode",file:{data:o},start:t.start,end:t.end,hardwareAcceleration:this.hardwareAcceleration,taskId:r},[o])}cacheVideo(){const t=this.queue.slice(0,this.cacheVideoCount);for(const e of t)this.resourceManager.preloadVideo(e.n)}abort(){this.tasks.forEach(({worker:t,status:e,onMessage:n})=>{"decoding"===e&&(t.postMessage({type:"abort"}),n&&t.removeEventListener("message",n),t.terminate())}),this.tasks.clear(),this.queue=[],this.currentParallel=0,this._locked=!1,this.currentTaskId=null}abortOne(t){const e=this.tasks.get(t);e&&"decoding"===e.status&&(null==e||e.worker.postMessage({type:"abort"}),null!=e&&e.onMessage&&e.worker.removeEventListener("message",e.onMessage),null==e||e.worker.terminate(),this.tasks.delete(t),this.currentParallel--,0===this.currentParallel&&0===this.queue.length&&(this._locked=!1))}destroy(){this.abort(),this.queue=[],this.currentParallel=0,this._locked=!1,this.currentTaskId=null,this.pendingAbort=!1,this.abortAfterEf=null,this.pendingNewQueue=null,this.abortAfterFrame=null,this.currentDecodedFrameIndex=null,this.firstDecodeFrame=!0}_handlePendingAbort(t,e){this.pendingAbort&&null!==this.abortAfterEf&&t.startFrameIndex+e>=this.abortAfterEf&&(this.abort(),this.queue=this.pendingNewQueue,this._locked=!0,this.currentTaskId=this.getRandomTaskId(),this.pendingAbort=!1,this.abortAfterEf=null,this.pendingNewQueue=null)}_cleanupOldWorkers(t){for(const[e,n]of this.tasks){const[r]=e.split("_"),i=parseInt(r,10);!isNaN(i)&&i<t&&(n.worker.postMessage({type:"abort"}),n.onMessage&&n.worker.removeEventListener("message",n.onMessage),n.worker.terminate(),this.tasks.delete(e))}}syncDecode(t){const e=this.queue.filter(e=>e.ef>t);0!==e.length&&(this.abort(),this.queue=e,this._locked=!0,this.currentTaskId=this.getRandomTaskId(),this._tryStartNext())}_reload(){this._offlineLastFrame=0,this.queue=[]}_offLineMode(t,e){this.abort(),this._offlineLastFrame=e,this._offlineIdle=t,this.currentParallel-=1,this.queue=[],this._offlineRun()}_offlineRun(){const t=this._offlineIdle[this._offlineIdleIndex];t?(this._offlineIdleIndex+=1,this._putOfflineBodyData(t)):this._offlineIdleIndex=0}_putOfflineBodyData(t){const e={id:-1,n:t.n,s:"idle",hfd:!1,body_id:-1,asf:t.asf,aef:t.aef,sf:this._offlineLastFrame,ef:this._offlineLastFrame+(t.aef-t.asf),x_offset:new Uint8Array};this.queue.push(e),this._offlineLastFrame=e.ef}}class FrameAnimationController{constructor({defaultSpeed:t=1,frameRate:e=24,frameCallback:n}={}){this.startTime=null,this.currentFrame=1,this.speed=t,this.frameCallback=n||null,this.frameRate=e,this.isPlaying=!1,this.animationId=null,this.startTimeFromDate=null,this.currentFrameFromDate=null}get playing(){return this.isPlaying}play(){this.isPlaying||(this.isPlaying=!0,window.avatarSDKLogger.log("开始时间",this.startTime),null===this.startTime&&(window.avatarSDKLogger.log("当前时间",performance.now()),this.startTime=performance.now(),this.startTimeFromDate=Date.now()),this.animationId=requestAnimationFrame(this._animate.bind(this)))}pause(){this.isPlaying=!1,this.animationId&&(cancelAnimationFrame(this.animationId),this.animationId=null)}reset(){this.pause(),this.startTime=null,this.currentFrame=1,this._updateFrame(),this.startTimeFromDate=null,this.currentFrameFromDate=null}setSpeed(t){this.speed=t}gotoFrame(t){t<1&&(t=1),this.currentFrame=t,this._updateFrame()}nextFrame(){this.currentFrame++,this._updateFrame()}prevFrame(){this.gotoFrame(this.currentFrame-1)}destroy(){this.pause(),this.frameCallback=null,this.startTime=null,this.startTimeFromDate=null,this.currentFrame=1,this.currentFrameFromDate=null,this.speed=1}_animate(t){let e=performance.now();if(Math.abs(t-e)<100&&(e=t),this.currentFrame<50&&window.avatarSDKLogger.log("animate时间",t,"开始时间",this.startTime,"performance",performance.now()),this.isPlaying){if(null!==this.startTime){const t=Math.floor(Math.floor((e-this.startTime)/(1e3/(2*this.frameRate)))/2)+1;t!==this.currentFrame&&(this.currentFrame=t,this._updateFrame());const n=Date.now()-this.startTimeFromDate,r=Math.floor(Math.floor(n/(1e3/(2*this.frameRate)))/2)+1;this.currentFrameFromDate=r}this.isPlaying&&(this.animationId=requestAnimationFrame(this._animate.bind(this)))}}_updateFrame(){let t=null;this.frameCallback&&(this.currentFrameFromDate!==this.currentFrame&&null!==this.currentFrameFromDate&&(t={key:"frame_number_error",Date帧号:this.currentFrameFromDate,performance帧号:this.currentFrame,开始时间:this.startTime,开始时间日期:this.startTimeFromDate,当前时间:Date.now(),"performance.now()":performance.now()}),this.frameCallback(this.currentFrame,t))}getCurrentFrame(){if(null!==this.startTime){const t=performance.now()-this.startTime;return Math.floor(Math.floor(t/(1e3/(2*this.frameRate)))/2)+1}return this.currentFrame}updateStartTime(t){this.startTime=performance.now()-1e3/this.frameRate*(t-1),this.startTimeFromDate=Date.now()-1e3/this.frameRate*(t-1)}}const captureStates=new WeakMap,playbackSessionRestoredListeners=new WeakMap;function configureWebAudioPlaybackSession(t=navigator){const e=getAudioSession(t);if(!e)return!1;const n=captureStates.get(e);return setAudioSessionType(e,null!=n&&n.count||"play-and-record"===e.type?"play-and-record":"playback")}function subscribeWebAudioPlaybackSessionRestored(t,e=navigator){const n=getAudioSession(e);if(!n)return()=>{};let r=playbackSessionRestoredListeners.get(n);return r||(r=new Set,playbackSessionRestoredListeners.set(n,r)),r.add(t),()=>{var e,i;null==(e=r)||e.delete(t),0===(null==(i=r)?void 0:i.size)&&playbackSessionRestoredListeners.delete(n)}}function getAudioSession(t){return t.audioSession}function setAudioSessionType(t,e){try{return t.type=e,t.type===e}catch(t){return!1}}const pcm_audio_script="// pcm-audio-processor.js - 运行在音频线程的Worklet处理器\nclass PCMAudioProcessor extends AudioWorkletProcessor {\n // 音量配置(与主线程保持一致)\n static get parameterDescriptors() {\n return [\n {\n name: 'volume',\n defaultValue: 1.0,\n minValue: 0.0,\n maxValue: 1.0,\n automationRate: 'a-rate' // 支持音频速率自动化\n }\n ];\n }\n\n constructor() {\n super();\n this.config = {\n sampleRate: 24000, // 固定24kHz采样率\n bytesPerSample: 2, // S16LE=2字节/采样点\n };\n this.pcmCache = new Uint8Array(0); // Worklet内的PCM缓存\n this.isActive = false; // 播放音频状态(控制是否生成声音)\n this.isDestroyed = false;\n this.fadeState = {\n // 淡入淡出状态(避免片段切换爆音)\n phase: 'idle', // idle/fadeIn/fadeOut/steady\n currentGain: 0,\n fadeTime: 0.01, // 淡入淡出时间(秒,建议最小0.01s避免爆音)\n fadeSamples: Math.floor(0.01 * 24000), // 淡入淡出样本数(24000Hz下为240样本)\n };\n this.currentSegment = null; // 当前处理的音频段(float32数组)\n this.segmentOffset = 0; // 当前音频段的播放偏移量\n \n // 监听主线程消息(接收PCM数据、状态控制等)\n this.port.onmessage = (e) => this.handleMainThreadMessage(e.data);\n \n // 初始化淡入淡出样本数\n this.fadeState.fadeSamples = Math.floor(this.fadeState.fadeTime * this.config.sampleRate);\n }\n\n /**\n * 处理主线程发来的消息(PCM数据/状态控制等)\n * @param {Object} data - 消息数据\n * @param {string} data.type - 消息类型:'pcm'/'start'/'pause'/'stop'/'config'/'destroy'/'volume'\n * @param {Uint8Array} [data.pcmData] - PCM数据(仅type='pcm'时存在)\n * @param {Object} [data.config] - 配置更新(仅type='config'时存在)\n * @param {number} [data.volume] - 音量值(仅type='volume'时存在)\n */\n handleMainThreadMessage(data) {\n switch (data.type) {\n // 接收主线程下发的PCM流数据\n case 'pcm':\n if (data.pcmData instanceof Uint8Array && data.pcmData.length > 0) {\n // 确保PCM数据字节数为2的整数倍(S16LE要求)\n const validLength = data.pcmData.length - (data.pcmData.length % this.config.bytesPerSample);\n if (validLength <= 0) break;\n \n // 合并到Worklet缓存\n const newCache = new Uint8Array(this.pcmCache.length + validLength);\n newCache.set(this.pcmCache, 0);\n newCache.set(data.pcmData.subarray(0, validLength), this.pcmCache.length);\n this.pcmCache = newCache;\n \n // 向主线程发送缓存状态\n this.port.postMessage({\n type: 'cacheStatus',\n size: this.pcmCache.length,\n sampleCount: this.pcmCache.length / this.config.bytesPerSample\n });\n }\n break;\n\n // 启动播放(继续音频生成)\n case 'start':\n this.isActive = true;\n break;\n\n // 暂停播放(停止音频生成,保留缓存)\n case 'pause':\n this.isActive = false;\n this.resetSegmentState();\n break;\n\n // 停止播放(清空缓存+重置状态)\n case 'stop':\n this.isActive = false;\n this.pcmCache = new Uint8Array(0);\n this.resetSegmentState();\n break;\n\n // 更新配置(如采样率/淡入淡出时间)\n case 'config':\n if (data.config.sampleRate) {\n this.config.sampleRate = data.config.sampleRate;\n // 重新计算淡入淡出样本数\n this.fadeState.fadeSamples = Math.floor(this.fadeState.fadeTime * this.config.sampleRate);\n }\n if (data.config.fadeTime) {\n this.fadeState.fadeTime = data.config.fadeTime;\n this.fadeState.fadeSamples = Math.floor(this.fadeState.fadeTime * this.config.sampleRate);\n }\n break;\n\n // 单独更新音量(可选,也可通过参数自动化控制)\n case 'volume':\n this.volume = Number(data.volume);\n // 通知主线程同步AudioWorkletNode的parameters\n this.port.postMessage({\n type: 'syncVolume',\n volume: this.volume\n });\n break;\n\n // 单独更新播放速率(可选,也可通过参数自动化控制)\n case 'speed':\n this.speed = Number(data.speed);\n // 通知主线程同步AudioWorkletNode的parameters\n this.port.postMessage({\n type: 'syncSpeed',\n speed: this.speed\n });\n break;\n\n // 销毁处理器\n case 'destroy':\n this.isDestroyed = true;\n this.isActive = false;\n this.pcmCache = new Uint8Array(0);\n this.resetSegmentState();\n this.port.postMessage({ type: 'destroyConfirmed' });\n break;\n \n default:\n console.warn('[PCMAudioProcessor] 未知消息类型:', data.type);\n }\n }\n\n /**\n * 重置当前音频段状态(暂停/停止时调用)\n */\n resetSegmentState() {\n this.currentSegment = null;\n this.segmentOffset = 0;\n this.fadeState.phase = 'idle';\n this.fadeState.currentGain = 0;\n }\n\n /**\n * S16LE Uint8Array 转 Float32Array(-1~1范围)\n * @param {Uint8Array} pcmData - PCM数据\n * @returns {Float32Array} 转换后的音频样本\n */\n pcmToFloat32(pcmData) {\n const sampleCount = pcmData.length / this.config.bytesPerSample;\n const floatData = new Float32Array(sampleCount);\n const dataView = new DataView(pcmData.buffer);\n\n for (let i = 0; i < sampleCount; i++) {\n // S16LE格式:小端序解析,范围-32768~32767 归一化到-1~1\n floatData[i] = dataView.getInt16(i * this.config.bytesPerSample, true) / 32768;\n }\n return floatData;\n }\n\n /**\n * 计算当前样本的增益(淡入淡出)\n * @param {number} segmentLength - 当前音频段的总样本数\n * @returns {number} 增益值(0~1)\n */\n calculateGain(segmentLength) {\n const { phase, fadeSamples } = this.fadeState;\n const { segmentOffset } = this;\n\n // 边界保护:防止无效值导致的NaN\n if (typeof segmentOffset !== 'number' || typeof segmentLength !== 'number' || segmentLength <= 0) {\n return 0;\n }\n\n switch (phase) {\n // 淡入阶段:从0线性增加到1\n case 'fadeIn':\n if (segmentOffset >= fadeSamples) {\n this.fadeState.phase = 'steady';\n return 1;\n }\n return segmentOffset / fadeSamples;\n\n // 稳定阶段:增益保持1\n case 'steady':\n // 检测是否进入淡出阶段(接近段尾)\n if (segmentOffset >= segmentLength - fadeSamples) {\n this.fadeState.phase = 'fadeOut';\n }\n return 1;\n\n // 淡出阶段:从1线性降低到0.0001(避免分音)\n case 'fadeOut':\n const fadeStart = Math.max(segmentLength - fadeSamples, 0);\n const fadeProgress = (segmentOffset - fadeStart) / fadeSamples;\n return Math.max(1 - fadeProgress, 0.0001);\n\n // 空闲阶段:增益0\n case 'idle':\n default:\n return 0;\n }\n }\n\n /**\n * AudioWorklet核心方法:实时生成音频样本(音频线程调用)\n * @param {Float32Array[][]} inputs - 输入样本\n * @param {Float32Array[][]} outputs - 输出样本(单声道)\n * @param {Object} parameters - 音频参数\n * @returns {boolean} 是否继续运行\n */\n process(inputs, outputs, parameters) {\n // 销毁状态:终止处理\n if (this.isDestroyed) {\n if (outputs.length > 0 && outputs[0].length > 0) {\n outputs[0][0].fill(0);\n }\n return false;\n }\n\n // 未激活或无输出:返回静音\n if (!this.isActive || outputs.length === 0 || outputs[0].length === 0) {\n outputs[0][0].fill(0);\n return true;\n }\n\n const outputBuffer = outputs[0][0];\n const bufferLength = outputBuffer.length;\n // 获取音量参数(支持自动化)\n const volume = parameters.volume.length > 1 \n ? parameters.volume // 自动化模式:每个样本点可能有不同值\n : parameters.volume[0]; // 控制模式:整个缓冲区使用相同值\n\n // 生成输出样本\n for (let i = 0; i < bufferLength; i++) {\n // 如当前无音频段且缓存有数据,创建新段\n if (!this.currentSegment && this.pcmCache.length > 0) {\n // 使用缓存中的所有数据创建新段\n this.currentSegment = this.pcmToFloat32(this.pcmCache);\n // 清空缓存(已处理)\n this.pcmCache = new Uint8Array(0);\n this.segmentOffset = 0;\n // 根据前一段状态决定是否淡入\n this.fadeState.phase = this.fadeState.phase === 'fadeOut' ? 'steady' : 'fadeIn';\n }\n\n // 生成当前样本\n let sample = 0;\n if (this.currentSegment) {\n const segmentLength = this.currentSegment.length;\n // 确保偏移量有效\n if (this.segmentOffset < segmentLength) {\n const gain = this.calculateGain(segmentLength);\n // 应用淡入淡出增益和音量控制\n sample = this.currentSegment[this.segmentOffset] * gain * volume;\n this.segmentOffset++;\n } else {\n // 当前段处理完毕,重置\n this.currentSegment = null;\n this.segmentOffset = 0;\n this.fadeState.phase = 'idle';\n }\n }\n\n outputBuffer[i] = sample;\n }\n\n return true;\n }\n}\n\n// 注册Worklet处理器\nregisterProcessor('pcm-audio-processor', PCMAudioProcessor);\n",pcm_capture_script="// pcm-capture-processor.js - 运行在音频线程的捕获处理器\nclass PCMCaptureProcessor extends AudioWorkletProcessor {\n constructor() {\n super();\n this.inputSampleRate = 24000; // PCM 播放器采样率\n this.outputSampleRate = 16000; // Opus 编码要求采样率\n this.bufferSize = 2400; // 100ms @ 24kHz\n this.buffer = new Float32Array(this.bufferSize);\n this.bufferIndex = 0;\n\n // 监听主线程的 reset 消息,清空内部缓冲区(打断/会话切换时使用)\n this.port.onmessage = (e) => {\n if (e.data && e.data.type === 'reset') {\n this.bufferIndex = 0;\n this.buffer.fill(0);\n }\n };\n }\n\n process(inputs) {\n const input = inputs[0];\n if (!input || !input[0] || input[0].length === 0) return true;\n\n const chunk = input[0];\n for (let i = 0; i < chunk.length; i++) {\n this.buffer[this.bufferIndex++] = chunk[i];\n\n if (this.bufferIndex >= this.bufferSize) {\n // 重采样 24kHz → 16kHz\n const resampled = this.resample(this.buffer);\n // Float32 → S16LE\n const pcmBuffer = this.float32ToS16LE(resampled);\n // 静音检测\n const hasAudio = this.detectAudio(this.buffer);\n // 回传主线程(Transferable,避免拷贝)\n this.port.postMessage(\n { pcmData: pcmBuffer.buffer, hasAudio: hasAudio },\n [pcmBuffer.buffer]\n );\n this.bufferIndex = 0;\n }\n }\n return true;\n }\n\n // 线性插值重采样 24kHz → 16kHz (3:2 比率)\n resample(input) {\n const ratio = this.outputSampleRate / this.inputSampleRate; // 2/3\n const outputLength = Math.floor(input.length * ratio); // 1600\n const output = new Float32Array(outputLength);\n for (let i = 0; i < outputLength; i++) {\n const srcIndex = i / ratio;\n const srcIndexFloor = Math.floor(srcIndex);\n const frac = srcIndex - srcIndexFloor;\n const s1 = input[srcIndexFloor] || 0;\n const s2 = input[srcIndexFloor + 1] || 0;\n output[i] = s1 + (s2 - s1) * frac;\n }\n return output;\n }\n\n // Float32 → S16LE Int16Array\n float32ToS16LE(float32) {\n const int16 = new Int16Array(float32.length);\n for (let i = 0; i < float32.length; i++) {\n let s = Math.max(-1, Math.min(1, float32[i]));\n int16[i] = s < 0 ? s * 0x8000 : s * 0x7FFF;\n }\n return int16;\n }\n\n // 静音检测\n detectAudio(buffer) {\n for (let i = 0; i < buffer.length; i++) {\n if (Math.abs(buffer[i]) > 0.0001) return true;\n }\n return false;\n }\n}\nregisterProcessor('pcm-capture-processor', PCMCaptureProcessor);\n",workletBlob=new Blob([pcm_audio_script],{type:"application/javascript"}),workletUrl=URL.createObjectURL(workletBlob),captureWorkletBlob=new Blob([pcm_capture_script],{type:"application/javascript"}),captureWorkletUrl=URL.createObjectURL(captureWorkletBlob);class PCMAudioPlayer{constructor(){this.SAMPLE_RATE=24e3,this.FRAME_ALIGNMENT=2e3,this.WORKLET_SCRIPT_URL=workletUrl,this.audioCtx=null,this.audioWorkletNode=null,this.isInitialized=!1,this.isPlaying=!1,this.destroyResolve=null,this.unsubscribePlaybackSessionRestored=null,this.captureWorklet=null,this.captureCallback=null}async init(){if(this.isInitialized)return;configureWebAudioPlaybackSession();const t=window.AudioContext||window.webkitAudioContext;if(!t||!window.AudioWorklet)throw new Error("当前浏览器不支持Web Audio Worklet,无法实现流式播放");this.audioCtx=new t({sampleRate:this.SAMPLE_RATE});const e=window.avatarSDKLogger||console;try{await this.audioCtx.audioWorklet.addModule(this.WORKLET_SCRIPT_URL),e.log(`[PCMAudioPlayer] Worklet脚本加载完成: ${this.WORKLET_SCRIPT_URL}`),this.audioWorkletNode=new AudioWorkletNode(this.audioCtx,"pcm-audio-processor"),this.audioWorkletNode.connect(this.audioCtx.destination),e.log("[PCMAudioPlayer] Worklet节点已连接到扬声器"),this.audioWorkletNode.port.onmessage=t=>{var n,r,i;switch(t.data.type){case"cacheStatus":e.log(`[PCMAudioPlayer] Worklet缓存状态: ${t.data.size}字节`);break;case"error":e.error("[PCMAudioPlayer] Worklet错误:",t.data.detail);break;case"destroyConfirmed":e.log("[PCMAudioPlayer] Worklet已确认销毁"),null==(n=this.destroyResolve)||n.call(this);break;case"syncVolume":void 0!==(null==(r=this.audioWorkletNode)||null==(r=r.parameters)||null==(r=r.get("volume"))?void 0:r.value)&&(this.audioWorkletNode.parameters.get("volume").value=t.data.volume);break;case"syncSpeed":void 0!==(null==(i=this.audioWorkletNode)||null==(i=i.parameters)||null==(i=i.get("speed"))?void 0:i.value)&&(this.audioWorkletNode.parameters.get("speed").value=t.data.speed);break;default:e.log("[PCMAudioPlayer] Worklet消息:",t.data)}},this.isInitialized=!0,this.unsubscribePlaybackSessionRestored=subscribeWebAudioPlaybackSessionRestored(()=>{this.refreshPlaybackRoute()}),e.log("[PCMAudioPlayer] 播放器初始化完成(Worklet就绪)")}catch(t){throw e.error("[PCMAudioPlayer] 初始化失败:",t),t}}refreshPlaybackRoute(){if(!(this.isInitialized&&this.isPlaying&&this.audioCtx&&this.audioWorkletNode))return!1;const t=window.avatarSDKLogger||console;try{return this.audioWorkletNode.disconnect(),this.audioWorkletNode.connect(this.audioCtx.destination),this.captureWorklet&&this.audioWorkletNode.connect(this.captureWorklet),"running"!==this.audioCtx.state&&this.audioCtx.resume().catch(e=>{t.warn("[PCMAudioPlayer] 刷新路由后恢复 AudioContext 失败:",e)}),t.log("[PCMAudioPlayer] 已刷新 playback 音频路由"),!0}catch(e){return t.warn("[PCMAudioPlayer] 刷新 playback 音频路由失败:",e),!1}}receivePCMStream(t){const e=window.avatarSDKLogger||console;if(this.isInitialized&&this.audioWorkletNode)if(t instanceof Uint8Array){e.log(`[PCMAudioPlayer] 已下发PCM数据: ${t.length}字节`);try{this.audioWorkletNode.port.postMessage({type:"pcm",pcmData:t},[t.buffer])}catch(t){e.error("[PCMAudioPlayer] 下发PCM数据到Worklet失败:",t)}}else e.error("[PCMAudioPlayer] 输入PCM数据必须是非空的Uint8Array");else e.error("[PCMAudioPlayer] 播放器未初始化,无法接收PCM数据")}async start(){if(!this.isInitialized||!this.audioCtx||!this.audioWorkletNode)throw new Error("[PCMAudioPlayer] 请先调用init()初始化播放器");const t=window.avatarSDKLogger||console;"running"!==this.audioCtx.state&&(await this.audioCtx.resume(),t.log("[PCMAudioPlayer] AudioContext已恢复运行")),this.audioWorkletNode.port.postMessage({type:"start"}),this.isPlaying=!0,t.log("[PCMAudioPlayer] 已启动播放(Worklet激活)")}pause(){if(!this.isInitialized||!this.audioWorkletNode)return;const t=window.avatarSDKLogger||console;this.audioWorkletNode.port.postMessage({type:"pause"}),this.isPlaying=!1,t.log("[PCMAudioPlayer] 已暂停播放(Worklet暂停)")}stop(){if(!this.isInitialized||!this.audioWorkletNode)return;const t=window.avatarSDKLogger||console;this.audioWorkletNode.port.postMessage({type:"stop"}),this.isPlaying=!1,t.log("[PCMAudioPlayer] 已停止播放(Worklet缓存清空)")}async destroy(){var t;const e=window.avatarSDKLogger||console;null==(t=this.unsubscribePlaybackSessionRestored)||t.call(this),this.unsubscribePlaybackSessionRestored=null,this.detachCapture(),this.isInitialized&&this.audioCtx&&this.audioWorkletNode?(await new Promise(t=>{var n;this.destroyResolve=t,null==(n=this.audioWorkletNode)||n.port.postMessage({type:"destroy"});const r=setTimeout(()=>{var t;e.warn("[PCMAudioPlayer] Worklet销毁超时,强制释放资源"),null==(t=this.destroyResolve)||t.call(this)},300);this.audioWorkletNode&&(this.audioWorkletNode.port.onmessage=t=>{var e;"destroyConfirmed"===t.data.type&&(clearTimeout(r),null==(e=this.destroyResolve)||e.call(this))})}),this.audioWorkletNode.disconnect(),this.audioWorkletNode.port.close(),this.audioWorkletNode=null,"closed"!==this.audioCtx.state&&await this.audioCtx.close(),this.audioCtx=null,e.log("[PCMAudioPlayer] AudioContext已关闭"),this.isInitialized=!1,this.isPlaying=!1,this.destroyResolve=null,e.log("[PCMAudioPlayer] 播放器已完全销毁,所有资源释放完成")):e.log("[PCMAudioPlayer] 播放器未初始化或已销毁")}async attachCapture(t){if(!this.isInitialized||!this.audioCtx||!this.audioWorkletNode)throw new Error("[PCMAudioPlayer] 播放器未初始化,无法挂载捕获");if(!this.captureWorklet){this.captureCallback=t;try{var e;await this.audioCtx.audioWorklet.addModule(captureWorkletUrl),this.captureWorklet=new AudioWorkletNode(this.audioCtx,"pcm-capture-processor"),this.audioWorkletNode.connect(this.captureWorklet),this.captureWorklet.port.onmessage=t=>{this.captureCallback&&t.data.pcmData&&this.captureCallback({pcmData:t.data.pcmData,hasAudio:t.data.hasAudio})},null==(e=window.avatarSDKLogger)||e.log("[PCMAudioPlayer] 捕获节点已挂载")}catch(t){var n;throw null==(n=window.avatarSDKLogger)||n.error("[PCMAudioPlayer] 挂载捕获节点失败:",t),t}}}detachCapture(){if(this.captureWorklet){try{var t;this.captureWorklet.port.onmessage=null,null==(t=this.audioWorkletNode)||t.disconnect(this.captureWorklet),this.captureWorklet.disconnect()}catch(t){}this.captureWorklet=null}this.captureCallback=null}resetCaptureBuffer(){this.captureWorklet&&this.captureWorklet.port.postMessage({type:"reset"})}getStatus(){return{isInitialized:this.isInitialized,isPlaying:this.isPlaying,isWorkletReady:!!this.audioWorkletNode}}setVolume(t){this.isInitialized&&this.audioWorkletNode&&this.audioWorkletNode.port.postMessage({type:"volume",volume:t})}setSpeed(t){this.isInitialized&&this.audioWorkletNode&&this.audioWorkletNode.port.postMessage({type:"speed",speed:t})}async resume(){const t=window.avatarSDKLogger||console;try{var e;"suspended"===(null==(e=this.audioCtx)?void 0:e.state)&&this.audioCtx.resume().then(()=>{window.avatarSDKLogger.info("worklet音频上下文恢复成功")}).catch(t=>{window.avatarSDKLogger.error("worklet音频上下文恢复失败:",t)})}catch(e){throw t.error("[PCMAudioPlayer] worklet恢复播放失败:",e),e}}}class MediaSourceAudioPlayer{static getInstance(t){return MediaSourceAudioPlayer.instance||(MediaSourceAudioPlayer.instance=new MediaSourceAudioPlayer(t)),MediaSourceAudioPlayer.instance}constructor(t){this.mediaSource=null,this.audioElement=null,this.sourceBuffer=null,this.isInitialized=!1,this.isPlaying=!1,this.volume=1,this.MIME_TYPE="audio/webm;codecs=opus",this.queue=[],this.isUpdating=!1,this.currentObjectURL=null,this.isDestroyed=!1,this.playbackRate=1,this.firstFrameIndex=-1,this.createAudioElement(t),this.createNewMediaSource()}createAudioElement(t){if(this.audioElement)return;const e=document.getElementById("xmov-avatar-audio");if(e)return void(this.audioElement=e);const n=document.createElement("audio");n.id="xmov-avatar-audio",n.preload="auto",n.style.position="absolute",n.style.width="1px",n.style.height="1px",n.style.opacity="0",n.style.pointerEvents="none",n.style.zIndex="-9999",t.el.appendChild(n),this.audioElement=n}createNewMediaSource(){return new Promise((t,e)=>{try{if(!this.audioElement)return;this.mediaSource=new MediaSource,this.currentObjectURL=URL.createObjectURL(this.mediaSource),this.audioElement.src=this.currentObjectURL,this.mediaSource.addEventListener("sourceopen",()=>{try{if(!this.mediaSource)return;this.sourceBuffer=this.mediaSource.addSourceBuffer(this.MIME_TYPE),this.sourceBuffer.mode="sequence",this.sourceBuffer.addEventListener("updateend",()=>{this.isUpdating=!1,this.processQueue()}),this.isInitialized=!0,t()}catch(t){e(t)}}),this.mediaSource.addEventListener("sourceclose",()=>{this.isInitialized=!1})}catch(t){e(t)}})}async destroyCurrentMediaSource(t){try{this.audioElement&&(this.audioElement.pause(),this.audioElement.removeAttribute("src"),this.audioElement.load())}catch(t){}try{this.currentObjectURL&&(URL.revokeObjectURL(this.currentObjectURL),this.currentObjectURL=null)}catch(t){}this.mediaSource=null,this.sourceBuffer=null,this.isInitialized=!1,this.isPlaying=!1,this.queue=[],this.isUpdating=!1,await this.createNewMediaSource(),t()}stop(t){this.destroyCurrentMediaSource(t)}async addAudioSegment(t){this.isDestroyed||(this.queue.push({data:t}),this.processQueue())}processQueue(){if(this.isDestroyed)return;if(!this.sourceBuffer||!this.mediaSource)return;if(this.isUpdating||0===this.queue.length)return;if(this.sourceBuffer.updating||"open"!==this.mediaSource.readyState)return;this.isUpdating=!0;const t=this.queue.shift();try{this.sourceBuffer.appendBuffer(t.data)}catch(t){this.isUpdating=!1}}async start(){if(!this.isDestroyed&&this.audioElement&&!this.isPlaying)try{this.audioElement.currentTime=0,this.isPlaying=!0,await this.audioElement.play(),window.avatarSDKLogger.log("mseAudioPlayer开始播放",this.getStats(),Date.now())}catch(t){}}getStats(){var t;return{isPlaying:this.isPlaying,isInitialized:this.isInitialized,queueLength:this.queue.length,bufferedRanges:this.getBufferedRanges(),mediaSourceReadyState:(null==(t=this.mediaSource)?void 0:t.readyState)||"null"}}setSpeed(t){this.setPlaybackRate(t)}getBufferedRanges(){try{var t;if(this.sourceBuffer&&"open"===(null==(t=this.mediaSource)?void 0:t.readyState)&&this.sourceBuffer.buffered.length>0){const t=[];for(let e=0;e<this.sourceBuffer.buffered.length;e++){const n=this.sourceBuffer.buffered.start(e).toFixed(2),r=this.sourceBuffer.buffered.end(e).toFixed(2);t.push(`[${n}-${r}]`)}return t.join(", ")}}catch(t){return"-"}return"-"}setVolume(t){this.volume=Math.max(0,Math.min(1,t)),this.audioElement&&(this.audioElement.volume=this.volume)}setPlaybackRate(t){this.playbackRate=Math.max(.5,Math.min(4,t)),this.audioElement&&(this.audioElement.playbackRate=this.playbackRate)}destroy(){if(this.isDestroyed=!0,this.audioElement&&(this.audioElement.pause(),this.audioElement.removeAttribute("src"),this.audioElement.load()),this.currentObjectURL){try{URL.revokeObjectURL(this.currentObjectURL)}catch(t){}this.currentObjectURL=null}this.audioElement&&(this.audioElement.remove(),this.audioElement=null),this.mediaSource=null,this.sourceBuffer=null,this.isInitialized=!1,this.isPlaying=!1,this.queue=[],this.isUpdating=!1,MediaSourceAudioPlayer.instance=null}}class AudioRender{constructor(t){this.TAG="[AudioRenderer]",this.isPlaying=!1,this.lastFrameIndex=-1,this.audio=null,this.firstFrameIndex=-1,this.valume=1,this.speech_id=-1,this.cacheFirstFrameIndex=-1,this.cacheAudioData=[],this.oldSpeechId=-1,this.mseCacheAudioData=[],this.mseAudioPlayer=null,this.options=t,this.resourceManager=t.resourceManager,this.resourceManager.config.raw_audio?(this.audio=new PCMAudioPlayer,this.audio.init()):this.mseAudioPlayer=MediaSourceAudioPlayer.getInstance(t.sdk)}updateAudioData(t){if(!this.resourceManager.config.raw_audio||t[0].sid===this.oldSpeechId)return;-1===this.firstFrameIndex&&(this.firstFrameIndex=t[0].sf);let e=0;for(const r of t){var n;e+=(null==(n=r.ad)?void 0:n.length)||0}const r=new Uint8Array(e);let i=0;for(const e of t)e.ad&&(r.set(new Uint8Array(e.ad),i),i+=e.ad.length);var s,a;-1===this.speech_id?(this.speech_id=t[0].sid,null==(s=this.audio)||s.receivePCMStream(r)):this.speech_id!==t[0].sid?(-1===this.cacheFirstFrameIndex&&(this.cacheFirstFrameIndex=t[0].sf),this.cacheAudioData.push(r)):null==(a=this.audio)||a.receivePCMStream(r)}_updateAudio(t){if(!this.mseAudioPlayer||0===t.length)return;const e=t[0];if(e.sid!==this.oldSpeechId)if(-1!==this.speech_id&&e.sid!==this.speech_id){var n;null==(n=window.avatarSDKLogger)||n.log(this.TAG,`检测到新的 speech_id: ${e.sid}, 当前 WebM 播放 (旧: ${this.speech_id}), 新: ${e.sid}, 缓存数据长度: ${this.mseCacheAudioData.length}`),-1===this.cacheFirstFrameIndex&&(this.cacheFirstFrameIndex=e.sf);for(const e of t)this.mseCacheAudioData.push({data:e.ad,frameIndex:e.sf,speechId:e.sid})}else{-1===this.firstFrameIndex&&(this.firstFrameIndex=e.sf),(-1===this.speech_id||this.speech_id!==e.sid)&&(this.speech_id=e.sid);for(const e of t)if(e.ad){const t=e.ad instanceof ArrayBuffer?e.ad:e.ad.buffer.slice(e.ad.byteOffset,e.ad.byteOffset+e.ad.byteLength);this.mseAudioPlayer.addAudioSegment(t)}}}async render(t){if(window.avatarSDKLogger.log("当前帧索引:",t,"音频开始播放帧:",this.firstFrameIndex),-1===this.lastFrameIndex&&(this.lastFrameIndex=t),this.options.sdk.getStatus()!==AvatarStatus.offline){var e;if(t>=this.firstFrameIndex&&-1!=this.firstFrameIndex&&!this.isPlaying&&this.resourceManager.config.raw_audio)return window.performanceTracker.markEnd(performanceConstant.start_action_render,"speak"),this.isPlaying=!0,void(null==(e=this.audio)||e.start());if(this.resourceManager.config.raw_audio||!this.mseAudioPlayer);else if(-1!==this.firstFrameIndex&&t>=this.firstFrameIndex&&!this.mseAudioPlayer.isPlaying&&!this.isPlaying){const e=this.mseAudioPlayer.getStats();if(e.queueLength>0||"-"!==e.bufferedRanges)try{window.avatarSDKLogger.log("开始播放",t),this.isPlaying=!0,await this.mseAudioPlayer.start(),window.performanceTracker.markEnd(performanceConstant.start_action_render,"speak")}catch(n){window.avatarSDKLogger.error("[AudioRenderer] WebM 音频播放失败:",{error:n,frameIndex:t,firstFrameIndex:this.firstFrameIndex,queueLength:e.queueLength})}else null==window.avatarSDKLogger.debug||window.avatarSDKLogger.debug("[AudioRenderer]",`等待更多 WebM 音频数据 (frameIndex: ${t}, queueLength: ${e.queueLength})`)}}}resume(){var t;this.audio&&this.resourceManager.config.raw_audio&&(null==(t=this.audio)||t.resume())}pause(){var t,e;this.isPlaying=!1,this.options.dataCacheQueue._clearAudio(this.speech_id),this.lastFrameIndex=-1,this.firstFrameIndex=-1,this.cacheFirstFrameIndex=-1,this.cacheAudioData=[],this.mseCacheAudioData=[],this.oldSpeechId=-1,null==(t=this.audio)||t.stop(),null==(e=this.mseAudioPlayer)||e.stop(this.addNewAudioSegment.bind(this)),this.speech_id=-1}stop(t){var e,n,r;if(!(-1!==t&&this.oldSpeechId>=t))if(this.isPlaying=!1,this.options.dataCacheQueue._clearAudio(t),this.firstFrameIndex=-1,null==(e=window.avatarSDKLogger)||e.log(this.TAG,`清除缓存数据 (speech_id: ${this.speech_id}, PCM缓存数据长度: ${this.cacheAudioData.length}, WebM缓存数据长度: ${this.mseCacheAudioData.length})`),this.resourceManager.config.raw_audio?null==(n=this.audio)||n.stop():null==(r=this.mseAudioPlayer)||r.stop(this.addNewAudioSegment.bind(this)),this.oldSpeechId=t,this.speech_id=-1,-1===t)this.cacheFirstFrameIndex=-1,this.cacheAudioData=[],this.mseCacheAudioData=[];else if(this.cacheAudioData.length>0){this.firstFrameIndex=this.cacheFirstFrameIndex,this.cacheFirstFrameIndex=-1;for(const t of this.cacheAudioData){var i;null==(i=this.audio)||i.receivePCMStream(t)}this.cacheAudioData=[]}}addNewAudioSegment(){if(this.mseCacheAudioData.length>0){this.firstFrameIndex=this.cacheFirstFrameIndex,this.cacheFirstFrameIndex=-1;for(const e of this.mseCacheAudioData){var t;e.data&&(null==(t=this.mseAudioPlayer)||t.addAudioSegment(e.data))}this.mseCacheAudioData=[]}}setVolume(t){var e,n;this.valume=t,this.resourceManager.config.raw_audio?null==(e=this.audio)||e.setVolume(t):null==(n=this.mseAudioPlayer)||n.setVolume(t)}setSpeed(t){var e,n;this.resourceManager.config.raw_audio?null==(e=this.audio)||e.setSpeed(t):null==(n=this.mseAudioPlayer)||n.setSpeed(t)}getAudioPlayer(){return this.audio}destroy(){var t,e;this.stop(-1),this.cacheAudioData=[],this.mseCacheAudioData=[],null==(t=this.audio)||t.destroy(),null==(e=this.mseAudioPlayer)||e.destroy(),this.mseAudioPlayer=null}}class SaveAndDownload{constructor(t="avatarData.json",e=!1){this.fileName=t,this.enabled=e,this.data={},this.downloadButton=null,e&&this.initDownloadButton()}initDownloadButton(){this.enabled&&(this.downloadButton=document.createElement("a"),this.downloadButton.style.position="absolute",this.downloadButton.style.left="0",this.downloadButton.style.bottom="30px",this.downloadButton.style.background="#4CAF50",this.downloadButton.style.color="white",this.downloadButton.style.fontSize="12px",this.downloadButton.style.padding="10px",this.downloadButton.style.borderRadius="4px",this.downloadButton.style.textDecoration="none",this.downloadButton.style.zIndex="1000",this.downloadButton.style.cursor="pointer",this.downloadButton.innerHTML="下载数据提交开发回放",this.downloadButton.addEventListener("click",()=>{this.download()}),document.body.appendChild(this.downloadButton))}writeFields(t){this.enabled&&Object.assign(this.data,t)}appendMultipleToArray(t,e){this.enabled&&(this.data[t]||(this.data[t]=[]),this.data[t].push(...e))}download(){if(!this.enabled)return;const t=this.generateJSONContent();this.downloadFile(t,this.fileName,"application/json")}generateJSONContent(){return JSON.stringify(this.data,null,2)}downloadFile(t,e,n){if(!this.enabled)return;const r=new Blob([t],{type:n}),i=URL.createObjectURL(r);this.downloadButton.href=i,this.downloadButton.download=e,this.downloadButton.scrollIntoView({behavior:"smooth",block:"center"}),this.downloadButton.dataset.objectUrl=i}}class RenderScheduler{constructor(t){this.TAG="[RenderScheduler]",this.currentSpeechId=-1,this.isStartPlay=!1,this.renderState=RenderState.init,this.lastSpeechId=-1,this.enableClientInterrupt=!1,this.audioOnlyMode=!1,this._speedResetTimer=null,this.offsetFrame=0,this.hasSendTimeJson=!1,this.config=t,this.setAudioInfo=t.setAudioInfo,this.setEventData=t.setEventData,this.reportMessage=t.reportMessage,this.sendSdkPoint=t.sendSdkPoint,this.onRenderChange=t.onRenderChange,this.sendMessage=t.sendMessage,this.enableClientInterrupt=t.enableClientInterrupt||!1,this.audioOnlyMode=t.audioOnlyMode||!1,this.saveAndDownload=new SaveAndDownload("avatarData.js",t.enableDebugger),this.resourceManager=t.resourceManager,this.sdk=t.sdkInstance,this.onDownloadProgress=t.onDownloadProgress,this.onFPSUpdate=t.onFPSUpdate,this.dataCacheQueue=new DataCacheQueue,this.decoder=new ParallelDecoder({hardwareAcceleration:t.hardwareAcceleration,resourceManager:this.resourceManager,saveAndDownload:this.saveAndDownload,dataCacheQueue:this.dataCacheQueue,reportMessage:this.reportMessage}),this.avatarRenderer=new AvatarRender({dataCacheQueue:this.dataCacheQueue,resourceManager:this.resourceManager,saveAndDownload:this.saveAndDownload,forceSyncDecoder:this.forceSyncDecoder.bind(this),reportMessage:this.reportMessage,sendSdkPoint:this.sendSdkPoint,onDownloadProgress:t=>{this.onDownloadProgress(t)},onStateChange:e=>{t.onStateChange(e)},onRenderChange:e=>{t.onRenderChange(e,this.renderState),this.renderState=e},sendVideoInfo:t.sendVideoInfo}),this.uiRenderer=new UIRenderer({sdk:this.sdk,dataCacheQueue:this.dataCacheQueue,resourceManager:this.resourceManager,enableClientInterrupt:this.enableClientInterrupt,onWalkStateChange:e=>{t.onWalkStateChange(e)},onVoiceStart:(e,n)=>{t.onVoiceStateChange("start",e,n)},onVoiceEnd:(e,n)=>{this.stopAudio(n),t.onVoiceStateChange("end",void 0,e)},onSpeakStateChange:(e,n,r)=>{"speak_start"===e?(this.currentSpeechId=r,this.avatarRenderer.setInterrupt(!1)):"speak_end"===e&&(this.dataCacheQueue.clearSubtitleOn(r),r>=this.currentSpeechId&&this.avatarRenderer.setInterrupt(!0)),t.onSpeakStateChange(e,n)},sendSdkPoint:(e,n,r)=>{t.sendSdkPoint(e,n,r)}}),this.audioRenderer=new AudioRender({sdk:this.sdk,dataCacheQueue:this.dataCacheQueue,resourceManager:this.resourceManager}),this.composition=new Composition({container:t.container,avatarRenderer:this.avatarRenderer,restRenderers:[this.uiRenderer],audioRenderer:this.audioRenderer,audioOnlyMode:this.audioOnlyMode,onFPSUpdate:t=>{this.onFPSUpdate(t)}}),this.frameAnimationController=new FrameAnimationController({defaultSpeed:1,frameRate:24,frameCallback:(e,n)=>{if(!this.hasSendTimeJson&&n&&(window.avatarSDKLogger.error("当前帧日期与当前帧不一致:",n),this.sendMessage("client_error",n),this.hasSendTimeJson=!0),t.renderFrameCallback(e+=this.offsetFrame),this.isStartPlay&&(this.composition.compose(e),this.decoder._tryStartNext(),t.onFrameDataUpdate)){const n=this.avatarRenderer._getCurrentFrameData(e);t.onFrameDataUpdate({frameIndex:e,body:n.body,face:n.face})}}})}init(){if(this.audioOnlyMode)return;const t=this.resourceManager.getMouthShapeLib();this.saveAndDownload.writeFields({resource_pack:this.resourceManager.resource_pack}),this.avatarRenderer.init({char:t.char_info,LUT:null,transform:{offsetX:0,offsetY:0,scaleX:1,scaleY:1},multisample:4})}async handleData(t,e){var n,r,i;if(this.audioOnlyMode&&(t===EFrameDataType.BODY||t===EFrameDataType.FACE||t===EFrameDataType.AA_FRAME))return;const s=this.getCurrentFrameIndex();switch(t){case EFrameDataType.BODY:{this.decoder.clearOldQueue(s);const t=s;let n=[...e].filter(e=>e.ef>t);window.avatarSDKLogger.log(n,"mp4List"),n.length>0&&(this.renderState!==RenderState.paused&&s&&s>e[0].sf&&s>10&&this.sdk.onMessage({code:EErrorCode.BODY_DATA_EXPIRED,message:`Error: 身体数据过期 cur:${s}-sf:${e[0].sf}`,e}),this.decoder.decode(n,(t,e,n)=>{var r,i;t.start<=n&&t.end>=n&&(this.dataCacheQueue._updateBodyImageBitmap({frame:e,frameIndex:t.startFrameIndex+n,frameState:t.frameState,id:t.id,body_id:t.body_id,name:t.name,hfd:t.hfd,sf:t.startFrameIndex,offset:(null==t?void 0:t.x_offset[n])||0}),t.endFrameIndex<=t.startFrameIndex+n&&this.decoder.abortOne(`${null!=(r=null!=(i=t.body_id)?i:t.id)?r:0}_${t.name}`))}));break}case EFrameDataType.FACE:this.dataCacheQueue.clearOldFaceData(s);const _=this.handleFaceData(e);_.length>0&&this.saveAndDownload.appendMultipleToArray("faceData",_),this.dataCacheQueue.checkValidData(_,t);let g=[],y=[];for(let t=0;t<_.length;t++){var a;null!=(a=_[t])&&a.face_frame_type?y.push(_[t]):g.push(_[t])}y.length&&this.dataCacheQueue._updateFacial(y),g.length&&this.dataCacheQueue._updateRealFacial(g);break;case EFrameDataType.AUDIO:if(this.setAudioInfo({sf:e[0].sf,ef:e[0].ef,ad:e[0].ad}),this.renderState!==RenderState.paused&&s>e[0].sf){const t=s?s-e[0].sf:0;this.reportMessage({code:EErrorCode.AUDIO_DATA_EXPIRED,message:`Error: 音频数据过期 cur:${s}-sf:${e[0].sf}`,e:{currentFrame:s,sf:e[0].sf,ef:t,timestamp:Date.now()}}),this.sendSdkPoint("audio_data_expired",{currentFrame:s,sf:e[0].sf,ef:t,timestamp:Date.now()})}const S=1e3/24,{sf:A,ef:v}=e[0],E=v-A;if(E<=0)return;const b=(s||0)-A;if(b>E)return;let T=1;if(b>0&&(T=E/Math.max(E-b,.1)),this._speedResetTimer&&clearTimeout(this._speedResetTimer),T>4)return;this.audioRenderer.setSpeed(T),this._speedResetTimer=setTimeout(()=>{this.audioRenderer.setSpeed(1),this._speedResetTimer=null},E*S/T),this.dataCacheQueue.checkValidData(e,t);const w=e.map(t=>this.resourceManager.config.raw_audio?t:_extends({},t,{ad:t.ad.buffer.slice(t.ad.byteOffset,t.ad.byteOffset+t.ad.byteLength)}));if(w[0].sid<=this.lastSpeechId)return;var o;this.resourceManager.config.raw_audio?(null==(o=window.avatarSDKLogger)||o.log(this.TAG,"processedAudioData[0].sid",w[0].sid,this.currentSpeechId,this.renderState),this.audioRenderer.updateAudioData(w)):this.audioRenderer._updateAudio(w);break;case EFrameDataType.EVENT:this.dataCacheQueue.clearOldEvent(s);const x=e;this.setEventData({sf:x[0].sf,ef:x[0].ef,event:x[0].e});let I=!1,R=null,C=null;for(const t of x){var l;const e=null!=(l=t.e)?l:[];if(e.some(t=>"speak_start"===t.type)&&(I=!0),t.sf<s&&(R||(R=e.find(t=>"speak_start"===t.type)||null),C||(C=e.find(t=>"voice_start"===t.type)||null),R&&C))break}if(I&&this.audioRenderer.isPlaying){var c;this.reportMessage({code:EErrorCode.EVENT_TRIGGERED,message:"WARNING: 有新的speak_start事件,但是上一轮仍未结束,触发兜底结束"});const t=x.flatMap(t=>{var e;return null!=(e=t.e)?e:[]}).find(t=>"speak_start"===t.type),e=null!=(c=null==t?void 0:t.speech_id)?c:0,n=this.audioRenderer.speech_id;var d,h;-1!==n&&n<e&&(this.interrupt("new_speak_start",n),-1!==this.audioRenderer.speech_id&&this.audioRenderer.pause()),t&&(this.currentSpeechId=null!=(d=t.speech_id)?d:0,this.avatarRenderer.setInterrupt(!1),this.uiRenderer.lastSpeechId=null!=(h=t.speech_id)?h:0)}if(R){const{speech_id:t,client_speak_id:e}=R;this.reportMessage({code:EErrorCode.EVENT_SPEAK_START_EXPIRED,message:"WARNING: 收到speak_start过期,主动重置avatarRender,调用onSpeakStateChange"}),this.currentSpeechId=null!=t?t:0,this.avatarRenderer.setInterrupt(!1),this.uiRenderer.lastSpeechId=null!=t?t:0,this.config.onSpeakStateChange("speak_start",null!=e?e:0)}if(C){var u,p;this.reportMessage({code:EErrorCode.EVENT_VOICE_START_EXPIRED,message:"WARNING: 收到voice_start过期,主动调用onVoiceStateChange"});const t=window.performanceTracker.markEnd(performanceConstant.voice_response_play,"speak");this.config.onVoiceStateChange("start",t,null!=(u=null==(p=C)?void 0:p.client_speak_id)?u:"")}const B=x.filter(t=>-1===t.sf&&-1===t.ef);for(const t of B)for(let e=0;e<t.e.length;e++){const n=t.e[e];if(WidgetDefaultRenderer.CUSTOM_WIDGET)WidgetDefaultRenderer.CUSTOM_WIDGET(n);else if(WidgetDefaultRenderer.PROXY_WIDGET){var f,m;null==(f=WidgetDefaultRenderer.PROXY_WIDGET)||null==(m=f[n.type])||m.call(f,n)}}const D=x.filter(t=>-1!==t.sf);this.dataCacheQueue._updateUiEvent(D);break;case EFrameDataType.SYNC_FRAME:const P=e;if(null!=(n=this.sdk.getOptions().config)&&n.replay||(null==P?void 0:P.source)!==FRAME_SOURCE_SOURCE)return;const k=Date.now()/1e3,O=null!=(r=P.client_time)?r:0,U=((null!=(i=P.server_client_frame)?i:0)+(k-O)/2*24).toFixed(0);this.offsetFrame+=Number(U)-Number(null!=s?s:0);break;default:this.sdk.onMessage({code:EErrorCode.INVALID_DATA_STRUCTURE,message:"Error: 数据类型错误",e:_extends({},e,{type:t})})}}setOffsetFrame(t){this.offsetFrame+=t}setVolume(t){this.audioRenderer.setVolume(t)}runStartFrameIndex(){var t;null==(t=this.frameAnimationController)||t.play()}stateChangeHandle(t){this.dataCacheQueue.currentPlayState=t}stopAudio(t){this.audioRenderer.stop(t)}render(){if(this.audioOnlyMode)return this.isStartPlay=!0,this.renderState=RenderState.rendering,this.onRenderChange(this.renderState),void this.onDownloadProgress(100);this.avatarRenderer.createPipeline(),this.isStartPlay=!0,this.renderState=RenderState.rendering,this.onRenderChange(this.renderState)}stop(){this.isStartPlay=!1,this.renderState=RenderState.stopped,this.onRenderChange(this.renderState),this.composition.stop()}pauseRender(){var t,e;this.renderState!==RenderState.paused&&(null==(t=this.frameAnimationController)||t.pause(),this.audioRenderer.stop(-1),this.dataCacheQueue.clearAllFaceData(),this.renderState=RenderState.paused,this.onRenderChange(this.renderState),null==(e=window.avatarSDKLogger)||e.log(this.TAG,`渲染已暂停(已清空表情数据,等待恢复): ${this.renderState}`))}resumeRender(){var t,e;this.renderState===RenderState.paused&&(this.avatarRenderer.createPipeline(),this.avatarRenderer.resetFaceFrameState(),null==(t=this.frameAnimationController)||t.play(),this.isStartPlay=!0,this.forceSyncDecoder(),this.renderState=RenderState.resumed,this.onRenderChange(this.renderState),null==(e=window.avatarSDKLogger)||e.log(this.TAG," 渲染已恢复,状态: this.currentSpeechId==="+this.currentSpeechId))}switchInvisibleMode(){var t;if(this.renderState===RenderState.rendering||this.renderState===RenderState.resumed)null==(t=window.avatarSDKLogger)||t.log(this.TAG,"switchInvisibleMode: rendering to paused"),this.pauseRender();else if(this.renderState===RenderState.paused){var e;null==(e=window.avatarSDKLogger)||e.log(this.TAG,"switchInvisibleMode: paused to rendering"),this.resumeRender()}else{var n;null==(n=window.avatarSDKLogger)||n.warn(this.TAG,`渲染状态为 ${this.renderState},无法切换隐身模式`)}}getRenderState(){var t;return null==(t=window.avatarSDKLogger)||t.log(this.TAG,`getRenderState: ${this.renderState}`),this.renderState}destroy(){var t;this.isStartPlay=!1,this.hasSendTimeJson=!1,this.offsetFrame=0,this._speedResetTimer=null,null==(t=this.frameAnimationController)||t.destroy(),this.frameAnimationController=void 0,this.dataCacheQueue.destroy(),this.composition.destroy(),this.decoder.destroy()}handleFaceData(t){try{var e;const n=this.resourceManager.resource_pack,r=this.resourceManager.getConfig().framedata_proto_version,i=[...null!=(e=n.blendshape_map)?e:[]];return t.map(t=>{let e=[];const{body_id:n,sf:s,ef:a,s:o,id:l,js:c,bsw:d,ms:h,face_frame_type:u,asf:p,aef:f,n:m,cs:_}=t;let g=[];if((null==i?void 0:i.length)>0){for(let t=0;t<i.length;t++){const n=i[t];if((null==n?void 0:n.length)>0)for(let r=0;r<n.length;r++)e[t]||(e[t]=[]),e[t][r]=d[n[r]]}g=Array.from({length:h.length},r?(t,n)=>{var r,i,s,a;return{blendshapeWeights:e[n],textureModelIndex:null!=(r=null==(i=h[n])?void 0:i.index)?r:0,texturePCAWeights:null!=(s=null==(a=h[n])?void 0:a.weights)?s:[]}}:(t,n)=>{var r,i,s,a;return{blendshapeWeights:e[n],textureModelIndex:null!=(r=null==(i=h[n])?void 0:i[0])?r:0,texturePCAWeights:null!=(s=null==(a=h[n])?void 0:a[1])?s:[]}})}else g=Array.from({length:h.length},r?(t,e)=>{var n,r,i,s;return{blendshapeWeights:0===e?d:[],textureModelIndex:null!=(n=null==(r=h[e])?void 0:r.index)?n:0,texturePCAWeights:null!=(i=null==(s=h[e])?void 0:s.weights)?i:[]}}:(t,e)=>{var n,r,i,s;return{blendshapeWeights:0===e?d:[],textureModelIndex:null!=(n=null==(r=h[e])?void 0:r[0])?n:0,texturePCAWeights:null!=(i=null==(s=h[e])?void 0:s[1])?i:[]}});let y=[];return y=c.map(r?t=>formatMJT(t.translate,t.rotate):t=>formatMJT(t[0],t[1])),{body_id:n,frameIndex:s,sf:s,ef:a,asf:p,aef:f,n:m,cs:_,state:o,id:l,face_frame_type:u,FaceFrameData:{mesh:g,movableJointTransforms:y,blendshapeWeights:d}}})}catch(t){return this.sdk.onMessage({code:EErrorCode.FACE_PROCESSING_ERROR,message:"Error: 表情数据处理失败",e:t}),[]}}forceSyncDecoder(){const t=this.getCurrentFrameIndex();t&&this.decoder.syncDecode(t)}_reload(){this.decoder._reload()}_getResumeInfo(){const t=this.getCurrentFrameIndex();return this.avatarRenderer._getCurrentBodyFrameInfo(t||0)}sendVoiceEnd(){var t,e,n;const r=(null!=(t=this.getCurrentFrameIndex())?t:0)+1;this.dataCacheQueue._updateUiEvent([{id:0,s:"",sf:r,ef:r+1,e:[{type:"speak_end",speech_id:null!=(e=this.uiRenderer.lastSpeechId)?e:-1},{type:"voice_end",speech_id:null!=(n=this.uiRenderer.lastSpeechId)?n:-1}]}])}markReconnectRecover(){this.audioRenderer.resume(),this.decoder._reload()}_offlineMode(){var t,e;this.dataCacheQueue._clearEvent();const n=null!=(t=this.getCurrentFrameIndex())?t:0;this.dataCacheQueue._updateUiEvent([{id:0,s:"",sf:n+1,ef:n+2,e:[{type:"subtitle_off",speech_id:null!=(e=this.uiRenderer.lastSpeechId)?e:-1}]}]),this.audioRenderer.pause();const r=this.getCurrentFrameIndex();r&&this.decoder._offLineMode(this.resourceManager._getOfflineIdle(),r),this.lastSpeechId=-1,this.currentSpeechId=-1,this.uiRenderer.lastSpeechId=-1}_offlineRun(){this.decoder._offlineRun(),this.dataCacheQueue.clearAllFaceData()}ttsaStateChangeHandle(t){this.dataCacheQueue.currentTtsaState=t}resume(){this.audioRenderer.resume()}setAvatarCanvasVisible(t){this.avatarRenderer.setCanvasVisibility(t)}setCharacterCanvasLayout(t){this.avatarRenderer.setCharacterCanvasAnchor(t)}setWalkConfig(t){this.avatarRenderer.setWalkConfig(t)}interrupt(t,e){var n;const r=Date.now(),i=null!=e?e:this.audioRenderer.speech_id;this.lastSpeechId="in_offline_mode"===t?-1:i,"in_offline_mode"!==t&&this.avatarRenderer.setInterrupt(!0),this.dataCacheQueue._clearAudio(i),this.dataCacheQueue.clearSubtitleOn(i);const s=null!=(n=this.getCurrentFrameIndex())?n:0;return this.dataCacheQueue._updateUiEvent([{id:0,s:"",sf:s+1,ef:s+2,e:[{type:"subtitle_off",speech_id:null!=i?i:-1}]}]),"in_offline_mode"!==t&&this.audioRenderer.stop(i),this.uiRenderer.setInterrupt(i),Date.now()-r}seekToFrame(t){var e;null==(e=this.frameAnimationController)||e.updateStartTime(t)}getCurrentFrameIndex(){var t,e;return(null!=(t=null==(e=this.frameAnimationController)?void 0:e.getCurrentFrame())?t:0)+this.offsetFrame}getSpeechId(){return this.audioRenderer.speech_id}getAudioRenderer(){return this.audioRenderer}simulateContextLoss(t=5e3,e=!1){this.avatarRenderer.simulateContextLoss(t,e)}getRecoveryStatus(){return this.avatarRenderer.getRecoveryStatus()}async testStagedRecovery(){return this.avatarRenderer.testStagedRecovery()}restartWebGL(){return this.avatarRenderer.restartWebGL()}}const Z_FIXED$1=4,Z_BINARY=0,Z_TEXT=1,Z_UNKNOWN$1=2;function zero$1(t){let e=t.length;for(;--e>=0;)t[e]=0}const STORED_BLOCK=0,STATIC_TREES=1,DYN_TREES=2,MIN_MATCH$1=3,MAX_MATCH$1=258,LENGTH_CODES$1=29,LITERALS$1=256,L_CODES$1=LITERALS$1+1+LENGTH_CODES$1,D_CODES$1=30,BL_CODES$1=19,HEAP_SIZE$1=2*L_CODES$1+1,MAX_BITS$1=15,Buf_size=16,MAX_BL_BITS=7,END_BLOCK=256,REP_3_6=16,REPZ_3_10=17,REPZ_11_138=18,extra_lbits=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]),extra_dbits=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]),extra_blbits=new Uint8Array([0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,2,3,7]),bl_order=new Uint8Array([16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15]),DIST_CODE_LEN=512,static_ltree=new Array(2*(L_CODES$1+2));zero$1(static_ltree);const static_dtree=new Array(2*D_CODES$1);zero$1(static_dtree);const _dist_code=new Array(DIST_CODE_LEN);zero$1(_dist_code);const _length_code=new Array(MAX_MATCH$1-MIN_MATCH$1+1);zero$1(_length_code);const base_length=new Array(LENGTH_CODES$1);zero$1(base_length);const base_dist=new Array(D_CODES$1);function StaticTreeDesc(t,e,n,r,i){this.static_tree=t,this.extra_bits=e,this.extra_base=n,this.elems=r,this.max_length=i,this.has_stree=t&&t.length}let static_l_desc,static_d_desc,static_bl_desc;function TreeDesc(t,e){this.dyn_tree=t,this.max_code=0,this.stat_desc=e}zero$1(base_dist);const d_code=t=>t<256?_dist_code[t]:_dist_code[256+(t>>>7)],put_short=(t,e)=>{t.pending_buf[t.pending++]=255&e,t.pending_buf[t.pending++]=e>>>8&255},send_bits=(t,e,n)=>{t.bi_valid>Buf_size-n?(t.bi_buf|=e<<t.bi_valid&65535,put_short(t,t.bi_buf),t.bi_buf=e>>Buf_size-t.bi_valid,t.bi_valid+=n-Buf_size):(t.bi_buf|=e<<t.bi_valid&65535,t.bi_valid+=n)},send_code=(t,e,n)=>{send_bits(t,n[2*e],n[2*e+1])},bi_reverse=(t,e)=>{let n=0;do{n|=1&t,t>>>=1,n<<=1}while(--e>0);return n>>>1},bi_flush=t=>{16===t.bi_valid?(put_short(t,t.bi_buf),t.bi_buf=0,t.bi_valid=0):t.bi_valid>=8&&(t.pending_buf[t.pending++]=255&t.bi_buf,t.bi_buf>>=8,t.bi_valid-=8)},gen_bitlen=(t,e)=>{const n=e.dyn_tree,r=e.max_code,i=e.stat_desc.static_tree,s=e.stat_desc.has_stree,a=e.stat_desc.extra_bits,o=e.stat_desc.extra_base,l=e.stat_desc.max_length;let c,d,h,u,p,f,m=0;for(u=0;u<=MAX_BITS$1;u++)t.bl_count[u]=0;for(n[2*t.heap[t.heap_max]+1]=0,c=t.heap_max+1;c<HEAP_SIZE$1;c++)d=t.heap[c],u=n[2*n[2*d+1]+1]+1,u>l&&(u=l,m++),n[2*d+1]=u,d>r||(t.bl_count[u]++,p=0,d>=o&&(p=a[d-o]),f=n[2*d],t.opt_len+=f*(u+p),s&&(t.static_len+=f*(i[2*d+1]+p)));if(0!==m){do{for(u=l-1;0===t.bl_count[u];)u--;t.bl_count[u]--,t.bl_count[u+1]+=2,t.bl_count[l]--,m-=2}while(m>0);for(u=l;0!==u;u--)for(d=t.bl_count[u];0!==d;)h=t.heap[--c],h>r||(n[2*h+1]!==u&&(t.opt_len+=(u-n[2*h+1])*n[2*h],n[2*h+1]=u),d--)}},gen_codes=(t,e,n)=>{const r=new Array(MAX_BITS$1+1);let i,s,a=0;for(i=1;i<=MAX_BITS$1;i++)a=a+n[i-1]<<1,r[i]=a;for(s=0;s<=e;s++){let e=t[2*s+1];0!==e&&(t[2*s]=bi_reverse(r[e]++,e))}},tr_static_init=()=>{let t,e,n,r,i;const s=new Array(MAX_BITS$1+1);for(n=0,r=0;r<LENGTH_CODES$1-1;r++)for(base_length[r]=n,t=0;t<1<<extra_lbits[r];t++)_length_code[n++]=r;for(_length_code[n-1]=r,i=0,r=0;r<16;r++)for(base_dist[r]=i,t=0;t<1<<extra_dbits[r];t++)_dist_code[i++]=r;for(i>>=7;r<D_CODES$1;r++)for(base_dist[r]=i<<7,t=0;t<1<<extra_dbits[r]-7;t++)_dist_code[256+i++]=r;for(e=0;e<=MAX_BITS$1;e++)s[e]=0;for(t=0;t<=143;)static_ltree[2*t+1]=8,t++,s[8]++;for(;t<=255;)static_ltree[2*t+1]=9,t++,s[9]++;for(;t<=279;)static_ltree[2*t+1]=7,t++,s[7]++;for(;t<=287;)static_ltree[2*t+1]=8,t++,s[8]++;for(gen_codes(static_ltree,L_CODES$1+1,s),t=0;t<D_CODES$1;t++)static_dtree[2*t+1]=5,static_dtree[2*t]=bi_reverse(t,5);static_l_desc=new StaticTreeDesc(static_ltree,extra_lbits,LITERALS$1+1,L_CODES$1,MAX_BITS$1),static_d_desc=new StaticTreeDesc(static_dtree,extra_dbits,0,D_CODES$1,MAX_BITS$1),static_bl_desc=new StaticTreeDesc(new Array(0),extra_blbits,0,BL_CODES$1,MAX_BL_BITS)},init_block=t=>{let e;for(e=0;e<L_CODES$1;e++)t.dyn_ltree[2*e]=0;for(e=0;e<D_CODES$1;e++)t.dyn_dtree[2*e]=0;for(e=0;e<BL_CODES$1;e++)t.bl_tree[2*e]=0;t.dyn_ltree[2*END_BLOCK]=1,t.opt_len=t.static_len=0,t.sym_next=t.matches=0},bi_windup=t=>{t.bi_valid>8?put_short(t,t.bi_buf):t.bi_valid>0&&(t.pending_buf[t.pending++]=t.bi_buf),t.bi_buf=0,t.bi_valid=0},smaller=(t,e,n,r)=>{const i=2*e,s=2*n;return t[i]<t[s]||t[i]===t[s]&&r[e]<=r[n]},pqdownheap=(t,e,n)=>{const r=t.heap[n];let i=n<<1;for(;i<=t.heap_len&&(i<t.heap_len&&smaller(e,t.heap[i+1],t.heap[i],t.depth)&&i++,!smaller(e,r,t.heap[i],t.depth));)t.heap[n]=t.heap[i],n=i,i<<=1;t.heap[n]=r},compress_block=(t,e,n)=>{let r,i,s,a,o=0;if(0!==t.sym_next)do{r=255&t.pending_buf[t.sym_buf+o++],r+=(255&t.pending_buf[t.sym_buf+o++])<<8,i=t.pending_buf[t.sym_buf+o++],0===r?send_code(t,i,e):(s=_length_code[i],send_code(t,s+LITERALS$1+1,e),a=extra_lbits[s],0!==a&&(i-=base_length[s],send_bits(t,i,a)),r--,s=d_code(r),send_code(t,s,n),a=extra_dbits[s],0!==a&&(r-=base_dist[s],send_bits(t,r,a)))}while(o<t.sym_next);send_code(t,END_BLOCK,e)},build_tree=(t,e)=>{const n=e.dyn_tree,r=e.stat_desc.static_tree,i=e.stat_desc.has_stree,s=e.stat_desc.elems;let a,o,l,c=-1;for(t.heap_len=0,t.heap_max=HEAP_SIZE$1,a=0;a<s;a++)0!==n[2*a]?(t.heap[++t.heap_len]=c=a,t.depth[a]=0):n[2*a+1]=0;for(;t.heap_len<2;)l=t.heap[++t.heap_len]=c<2?++c:0,n[2*l]=1,t.depth[l]=0,t.opt_len--,i&&(t.static_len-=r[2*l+1]);for(e.max_code=c,a=t.heap_len>>1;a>=1;a--)pqdownheap(t,n,a);l=s;do{a=t.heap[1],t.heap[1]=t.heap[t.heap_len--],pqdownheap(t,n,1),o=t.heap[1],t.heap[--t.heap_max]=a,t.heap[--t.heap_max]=o,n[2*l]=n[2*a]+n[2*o],t.depth[l]=(t.depth[a]>=t.depth[o]?t.depth[a]:t.depth[o])+1,n[2*a+1]=n[2*o+1]=l,t.heap[1]=l++,pqdownheap(t,n,1)}while(t.heap_len>=2);t.heap[--t.heap_max]=t.heap[1],gen_bitlen(t,e),gen_codes(n,c,t.bl_count)},scan_tree=(t,e,n)=>{let r,i,s=-1,a=e[1],o=0,l=7,c=4;for(0===a&&(l=138,c=3),e[2*(n+1)+1]=65535,r=0;r<=n;r++)i=a,a=e[2*(r+1)+1],++o<l&&i===a||(o<c?t.bl_tree[2*i]+=o:0!==i?(i!==s&&t.bl_tree[2*i]++,t.bl_tree[2*REP_3_6]++):o<=10?t.bl_tree[2*REPZ_3_10]++:t.bl_tree[2*REPZ_11_138]++,o=0,s=i,0===a?(l=138,c=3):i===a?(l=6,c=3):(l=7,c=4))},send_tree=(t,e,n)=>{let r,i,s=-1,a=e[1],o=0,l=7,c=4;for(0===a&&(l=138,c=3),r=0;r<=n;r++)if(i=a,a=e[2*(r+1)+1],!(++o<l&&i===a)){if(o<c)do{send_code(t,i,t.bl_tree)}while(0!==--o);else 0!==i?(i!==s&&(send_code(t,i,t.bl_tree),o--),send_code(t,REP_3_6,t.bl_tree),send_bits(t,o-3,2)):o<=10?(send_code(t,REPZ_3_10,t.bl_tree),send_bits(t,o-3,3)):(send_code(t,REPZ_11_138,t.bl_tree),send_bits(t,o-11,7));o=0,s=i,0===a?(l=138,c=3):i===a?(l=6,c=3):(l=7,c=4)}},build_bl_tree=t=>{let e;for(scan_tree(t,t.dyn_ltree,t.l_desc.max_code),scan_tree(t,t.dyn_dtree,t.d_desc.max_code),build_tree(t,t.bl_desc),e=BL_CODES$1-1;e>=3&&0===t.bl_tree[2*bl_order[e]+1];e--);return t.opt_len+=3*(e+1)+5+5+4,e},send_all_trees=(t,e,n,r)=>{let i;for(send_bits(t,e-257,5),send_bits(t,n-1,5),send_bits(t,r-4,4),i=0;i<r;i++)send_bits(t,t.bl_tree[2*bl_order[i]+1],3);send_tree(t,t.dyn_ltree,e-1),send_tree(t,t.dyn_dtree,n-1)},detect_data_type=t=>{let e,n=4093624447;for(e=0;e<=31;e++,n>>>=1)if(1&n&&0!==t.dyn_ltree[2*e])return Z_BINARY;if(0!==t.dyn_ltree[18]||0!==t.dyn_ltree[20]||0!==t.dyn_ltree[26])return Z_TEXT;for(e=32;e<LITERALS$1;e++)if(0!==t.dyn_ltree[2*e])return Z_TEXT;return Z_BINARY};let static_init_done=!1;const _tr_init$1=t=>{static_init_done||(tr_static_init(),static_init_done=!0),t.l_desc=new TreeDesc(t.dyn_ltree,static_l_desc),t.d_desc=new TreeDesc(t.dyn_dtree,static_d_desc),t.bl_desc=new TreeDesc(t.bl_tree,static_bl_desc),t.bi_buf=0,t.bi_valid=0,init_block(t)},_tr_stored_block$1=(t,e,n,r)=>{send_bits(t,(STORED_BLOCK<<1)+(r?1:0),3),bi_windup(t),put_short(t,n),put_short(t,~n),n&&t.pending_buf.set(t.window.subarray(e,e+n),t.pending),t.pending+=n},_tr_align$1=t=>{send_bits(t,STATIC_TREES<<1,3),send_code(t,END_BLOCK,static_ltree),bi_flush(t)},_tr_flush_block$1=(t,e,n,r)=>{let i,s,a=0;t.level>0?(t.strm.data_type===Z_UNKNOWN$1&&(t.strm.data_type=detect_data_type(t)),build_tree(t,t.l_desc),build_tree(t,t.d_desc),a=build_bl_tree(t),i=t.opt_len+3+7>>>3,s=t.static_len+3+7>>>3,s<=i&&(i=s)):i=s=n+5,n+4<=i&&-1!==e?_tr_stored_block$1(t,e,n,r):t.strategy===Z_FIXED$1||s===i?(send_bits(t,(STATIC_TREES<<1)+(r?1:0),3),compress_block(t,static_ltree,static_dtree)):(send_bits(t,(DYN_TREES<<1)+(r?1:0),3),send_all_trees(t,t.l_desc.max_code+1,t.d_desc.max_code+1,a+1),compress_block(t,t.dyn_ltree,t.dyn_dtree)),init_block(t),r&&bi_windup(t)},_tr_tally$1=(t,e,n)=>(t.pending_buf[t.sym_buf+t.sym_next++]=e,t.pending_buf[t.sym_buf+t.sym_next++]=e>>8,t.pending_buf[t.sym_buf+t.sym_next++]=n,0===e?t.dyn_ltree[2*n]++:(t.matches++,e--,t.dyn_ltree[2*(_length_code[n]+LITERALS$1+1)]++,t.dyn_dtree[2*d_code(e)]++),t.sym_next===t.sym_end);var _tr_init_1=_tr_init$1,_tr_stored_block_1=_tr_stored_block$1,_tr_flush_block_1=_tr_flush_block$1,_tr_tally_1=_tr_tally$1,_tr_align_1=_tr_align$1,trees={_tr_init:_tr_init_1,_tr_stored_block:_tr_stored_block_1,_tr_flush_block:_tr_flush_block_1,_tr_tally:_tr_tally_1,_tr_align:_tr_align_1};const adler32=(t,e,n,r)=>{let i=65535&t,s=t>>>16&65535,a=0;for(;0!==n;){a=n>2e3?2e3:n,n-=a;do{i=i+e[r++]|0,s=s+i|0}while(--a);i%=65521,s%=65521}return i|s<<16};var adler32_1=adler32;const makeTable=()=>{let t,e=[];for(var n=0;n<256;n++){t=n;for(var r=0;r<8;r++)t=1&t?3988292384^t>>>1:t>>>1;e[n]=t}return e},crcTable=new Uint32Array(makeTable()),crc32=(t,e,n,r)=>{const i=crcTable,s=r+n;t^=-1;for(let n=r;n<s;n++)t=t>>>8^i[255&(t^e[n])];return-1^t};var crc32_1=crc32,messages={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"},constants$2={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,_tr_stored_block,_tr_flush_block,_tr_tally,_tr_align}=trees,{Z_NO_FLUSH:Z_NO_FLUSH$2,Z_PARTIAL_FLUSH,Z_FULL_FLUSH:Z_FULL_FLUSH$1,Z_FINISH:Z_FINISH$3,Z_BLOCK:Z_BLOCK$1,Z_OK:Z_OK$3,Z_STREAM_END:Z_STREAM_END$3,Z_STREAM_ERROR:Z_STREAM_ERROR$2,Z_DATA_ERROR:Z_DATA_ERROR$2,Z_BUF_ERROR:Z_BUF_ERROR$1,Z_DEFAULT_COMPRESSION:Z_DEFAULT_COMPRESSION$1,Z_FILTERED,Z_HUFFMAN_ONLY,Z_RLE,Z_FIXED,Z_DEFAULT_STRATEGY:Z_DEFAULT_STRATEGY$1,Z_UNKNOWN,Z_DEFLATED:Z_DEFLATED$2}=constants$2,MAX_MEM_LEVEL=9,MAX_WBITS$1=15,DEF_MEM_LEVEL=8,LENGTH_CODES=29,LITERALS=256,L_CODES=LITERALS+1+LENGTH_CODES,D_CODES=30,BL_CODES=19,HEAP_SIZE=2*L_CODES+1,MAX_BITS=15,MIN_MATCH=3,MAX_MATCH=258,MIN_LOOKAHEAD=MAX_MATCH+MIN_MATCH+1,PRESET_DICT=32,INIT_STATE=42,GZIP_STATE=57,EXTRA_STATE=69,NAME_STATE=73,COMMENT_STATE=91,HCRC_STATE=103,BUSY_STATE=113,FINISH_STATE=666,BS_NEED_MORE=1,BS_BLOCK_DONE=2,BS_FINISH_STARTED=3,BS_FINISH_DONE=4,OS_CODE=3,err=(t,e)=>(t.msg=messages[e],e),rank=t=>2*t-(t>4?9:0),zero=t=>{let e=t.length;for(;--e>=0;)t[e]=0},slide_hash=t=>{let e,n,r,i=t.w_size;e=t.hash_size,r=e;do{n=t.head[--r],t.head[r]=n>=i?n-i:0}while(--e);e=i,r=e;do{n=t.prev[--r],t.prev[r]=n>=i?n-i:0}while(--e)};let HASH_ZLIB=(t,e,n)=>(e<<t.hash_shift^n)&t.hash_mask,HASH=HASH_ZLIB;const flush_pending=t=>{const e=t.state;let n=e.pending;n>t.avail_out&&(n=t.avail_out),0!==n&&(t.output.set(e.pending_buf.subarray(e.pending_out,e.pending_out+n),t.next_out),t.next_out+=n,e.pending_out+=n,t.total_out+=n,t.avail_out-=n,e.pending-=n,0===e.pending&&(e.pending_out=0))},flush_block_only=(t,e)=>{_tr_flush_block(t,t.block_start>=0?t.block_start:-1,t.strstart-t.block_start,e),t.block_start=t.strstart,flush_pending(t.strm)},put_byte=(t,e)=>{t.pending_buf[t.pending++]=e},putShortMSB=(t,e)=>{t.pending_buf[t.pending++]=e>>>8&255,t.pending_buf[t.pending++]=255&e},read_buf=(t,e,n,r)=>{let i=t.avail_in;return i>r&&(i=r),0===i?0:(t.avail_in-=i,e.set(t.input.subarray(t.next_in,t.next_in+i),n),1===t.state.wrap?t.adler=adler32_1(t.adler,e,i,n):2===t.state.wrap&&(t.adler=crc32_1(t.adler,e,i,n)),t.next_in+=i,t.total_in+=i,i)},longest_match=(t,e)=>{let n,r,i=t.max_chain_length,s=t.strstart,a=t.prev_length,o=t.nice_match;const l=t.strstart>t.w_size-MIN_LOOKAHEAD?t.strstart-(t.w_size-MIN_LOOKAHEAD):0,c=t.window,d=t.w_mask,h=t.prev,u=t.strstart+MAX_MATCH;let p=c[s+a-1],f=c[s+a];t.prev_length>=t.good_match&&(i>>=2),o>t.lookahead&&(o=t.lookahead);do{if(n=e,c[n+a]===f&&c[n+a-1]===p&&c[n]===c[s]&&c[++n]===c[s+1]){s+=2,n++;do{}while(c[++s]===c[++n]&&c[++s]===c[++n]&&c[++s]===c[++n]&&c[++s]===c[++n]&&c[++s]===c[++n]&&c[++s]===c[++n]&&c[++s]===c[++n]&&c[++s]===c[++n]&&s<u);if(r=MAX_MATCH-(u-s),s=u-MAX_MATCH,r>a){if(t.match_start=e,a=r,r>=o)break;p=c[s+a-1],f=c[s+a]}}}while((e=h[e&d])>l&&0!==--i);return a<=t.lookahead?a:t.lookahead},fill_window=t=>{const e=t.w_size;let n,r,i;do{if(r=t.window_size-t.lookahead-t.strstart,t.strstart>=e+(e-MIN_LOOKAHEAD)&&(t.window.set(t.window.subarray(e,e+e-r),0),t.match_start-=e,t.strstart-=e,t.block_start-=e,t.insert>t.strstart&&(t.insert=t.strstart),slide_hash(t),r+=e),0===t.strm.avail_in)break;if(n=read_buf(t.strm,t.window,t.strstart+t.lookahead,r),t.lookahead+=n,t.lookahead+t.insert>=MIN_MATCH)for(i=t.strstart-t.insert,t.ins_h=t.window[i],t.ins_h=HASH(t,t.ins_h,t.window[i+1]);t.insert&&(t.ins_h=HASH(t,t.ins_h,t.window[i+MIN_MATCH-1]),t.prev[i&t.w_mask]=t.head[t.ins_h],t.head[t.ins_h]=i,i++,t.insert--,!(t.lookahead+t.insert<MIN_MATCH)););}while(t.lookahead<MIN_LOOKAHEAD&&0!==t.strm.avail_in)},deflate_stored=(t,e)=>{let n,r,i,s=t.pending_buf_size-5>t.w_size?t.w_size:t.pending_buf_size-5,a=0,o=t.strm.avail_in;do{if(n=65535,i=t.bi_valid+42>>3,t.strm.avail_out<i)break;if(i=t.strm.avail_out-i,r=t.strstart-t.block_start,n>r+t.strm.avail_in&&(n=r+t.strm.avail_in),n>i&&(n=i),n<s&&(0===n&&e!==Z_FINISH$3||e===Z_NO_FLUSH$2||n!==r+t.strm.avail_in))break;a=e===Z_FINISH$3&&n===r+t.strm.avail_in?1:0,_tr_stored_block(t,0,0,a),t.pending_buf[t.pending-4]=n,t.pending_buf[t.pending-3]=n>>8,t.pending_buf[t.pending-2]=~n,t.pending_buf[t.pending-1]=~n>>8,flush_pending(t.strm),r&&(r>n&&(r=n),t.strm.output.set(t.window.subarray(t.block_start,t.block_start+r),t.strm.next_out),t.strm.next_out+=r,t.strm.avail_out-=r,t.strm.total_out+=r,t.block_start+=r,n-=r),n&&(read_buf(t.strm,t.strm.output,t.strm.next_out,n),t.strm.next_out+=n,t.strm.avail_out-=n,t.strm.total_out+=n)}while(0===a);return o-=t.strm.avail_in,o&&(o>=t.w_size?(t.matches=2,t.window.set(t.strm.input.subarray(t.strm.next_in-t.w_size,t.strm.next_in),0),t.strstart=t.w_size,t.insert=t.strstart):(t.window_size-t.strstart<=o&&(t.strstart-=t.w_size,t.window.set(t.window.subarray(t.w_size,t.w_size+t.strstart),0),t.matches<2&&t.matches++,t.insert>t.strstart&&(t.insert=t.strstart)),t.window.set(t.strm.input.subarray(t.strm.next_in-o,t.strm.next_in),t.strstart),t.strstart+=o,t.insert+=o>t.w_size-t.insert?t.w_size-t.insert:o),t.block_start=t.strstart),t.high_water<t.strstart&&(t.high_water=t.strstart),a?BS_FINISH_DONE:e!==Z_NO_FLUSH$2&&e!==Z_FINISH$3&&0===t.strm.avail_in&&t.strstart===t.block_start?BS_BLOCK_DONE:(i=t.window_size-t.strstart,t.strm.avail_in>i&&t.block_start>=t.w_size&&(t.block_start-=t.w_size,t.strstart-=t.w_size,t.window.set(t.window.subarray(t.w_size,t.w_size+t.strstart),0),t.matches<2&&t.matches++,i+=t.w_size,t.insert>t.strstart&&(t.insert=t.strstart)),i>t.strm.avail_in&&(i=t.strm.avail_in),i&&(read_buf(t.strm,t.window,t.strstart,i),t.strstart+=i,t.insert+=i>t.w_size-t.insert?t.w_size-t.insert:i),t.high_water<t.strstart&&(t.high_water=t.strstart),i=t.bi_valid+42>>3,i=t.pending_buf_size-i>65535?65535:t.pending_buf_size-i,s=i>t.w_size?t.w_size:i,r=t.strstart-t.block_start,(r>=s||(r||e===Z_FINISH$3)&&e!==Z_NO_FLUSH$2&&0===t.strm.avail_in&&r<=i)&&(n=r>i?i:r,a=e===Z_FINISH$3&&0===t.strm.avail_in&&n===r?1:0,_tr_stored_block(t,t.block_start,n,a),t.block_start+=n,flush_pending(t.strm)),a?BS_FINISH_STARTED:BS_NEED_MORE)},deflate_fast=(t,e)=>{let n,r;for(;;){if(t.lookahead<MIN_LOOKAHEAD){if(fill_window(t),t.lookahead<MIN_LOOKAHEAD&&e===Z_NO_FLUSH$2)return BS_NEED_MORE;if(0===t.lookahead)break}if(n=0,t.lookahead>=MIN_MATCH&&(t.ins_h=HASH(t,t.ins_h,t.window[t.strstart+MIN_MATCH-1]),n=t.prev[t.strstart&t.w_mask]=t.head[t.ins_h],t.head[t.ins_h]=t.strstart),0!==n&&t.strstart-n<=t.w_size-MIN_LOOKAHEAD&&(t.match_length=longest_match(t,n)),t.match_length>=MIN_MATCH)if(r=_tr_tally(t,t.strstart-t.match_start,t.match_length-MIN_MATCH),t.lookahead-=t.match_length,t.match_length<=t.max_lazy_match&&t.lookahead>=MIN_MATCH){t.match_length--;do{t.strstart++,t.ins_h=HASH(t,t.ins_h,t.window[t.strstart+MIN_MATCH-1]),n=t.prev[t.strstart&t.w_mask]=t.head[t.ins_h],t.head[t.ins_h]=t.strstart}while(0!==--t.match_length);t.strstart++}else t.strstart+=t.match_length,t.match_length=0,t.ins_h=t.window[t.strstart],t.ins_h=HASH(t,t.ins_h,t.window[t.strstart+1]);else r=_tr_tally(t,0,t.window[t.strstart]),t.lookahead--,t.strstart++;if(r&&(flush_block_only(t,!1),0===t.strm.avail_out))return BS_NEED_MORE}return t.insert=t.strstart<MIN_MATCH-1?t.strstart:MIN_MATCH-1,e===Z_FINISH$3?(flush_block_only(t,!0),0===t.strm.avail_out?BS_FINISH_STARTED:BS_FINISH_DONE):t.sym_next&&(flush_block_only(t,!1),0===t.strm.avail_out)?BS_NEED_MORE:BS_BLOCK_DONE},deflate_slow=(t,e)=>{let n,r,i;for(;;){if(t.lookahead<MIN_LOOKAHEAD){if(fill_window(t),t.lookahead<MIN_LOOKAHEAD&&e===Z_NO_FLUSH$2)return BS_NEED_MORE;if(0===t.lookahead)break}if(n=0,t.lookahead>=MIN_MATCH&&(t.ins_h=HASH(t,t.ins_h,t.window[t.strstart+MIN_MATCH-1]),n=t.prev[t.strstart&t.w_mask]=t.head[t.ins_h],t.head[t.ins_h]=t.strstart),t.prev_length=t.match_length,t.prev_match=t.match_start,t.match_length=MIN_MATCH-1,0!==n&&t.prev_length<t.max_lazy_match&&t.strstart-n<=t.w_size-MIN_LOOKAHEAD&&(t.match_length=longest_match(t,n),t.match_length<=5&&(t.strategy===Z_FILTERED||t.match_length===MIN_MATCH&&t.strstart-t.match_start>4096)&&(t.match_length=MIN_MATCH-1)),t.prev_length>=MIN_MATCH&&t.match_length<=t.prev_length){i=t.strstart+t.lookahead-MIN_MATCH,r=_tr_tally(t,t.strstart-1-t.prev_match,t.prev_length-MIN_MATCH),t.lookahead-=t.prev_length-1,t.prev_length-=2;do{++t.strstart<=i&&(t.ins_h=HASH(t,t.ins_h,t.window[t.strstart+MIN_MATCH-1]),n=t.prev[t.strstart&t.w_mask]=t.head[t.ins_h],t.head[t.ins_h]=t.strstart)}while(0!==--t.prev_length);if(t.match_available=0,t.match_length=MIN_MATCH-1,t.strstart++,r&&(flush_block_only(t,!1),0===t.strm.avail_out))return BS_NEED_MORE}else if(t.match_available){if(r=_tr_tally(t,0,t.window[t.strstart-1]),r&&flush_block_only(t,!1),t.strstart++,t.lookahead--,0===t.strm.avail_out)return BS_NEED_MORE}else t.match_available=1,t.strstart++,t.lookahead--}return t.match_available&&(r=_tr_tally(t,0,t.window[t.strstart-1]),t.match_available=0),t.insert=t.strstart<MIN_MATCH-1?t.strstart:MIN_MATCH-1,e===Z_FINISH$3?(flush_block_only(t,!0),0===t.strm.avail_out?BS_FINISH_STARTED:BS_FINISH_DONE):t.sym_next&&(flush_block_only(t,!1),0===t.strm.avail_out)?BS_NEED_MORE:BS_BLOCK_DONE},deflate_rle=(t,e)=>{let n,r,i,s;const a=t.window;for(;;){if(t.lookahead<=MAX_MATCH){if(fill_window(t),t.lookahead<=MAX_MATCH&&e===Z_NO_FLUSH$2)return BS_NEED_MORE;if(0===t.lookahead)break}if(t.match_length=0,t.lookahead>=MIN_MATCH&&t.strstart>0&&(i=t.strstart-1,r=a[i],r===a[++i]&&r===a[++i]&&r===a[++i])){s=t.strstart+MAX_MATCH;do{}while(r===a[++i]&&r===a[++i]&&r===a[++i]&&r===a[++i]&&r===a[++i]&&r===a[++i]&&r===a[++i]&&r===a[++i]&&i<s);t.match_length=MAX_MATCH-(s-i),t.match_length>t.lookahead&&(t.match_length=t.lookahead)}if(t.match_length>=MIN_MATCH?(n=_tr_tally(t,1,t.match_length-MIN_MATCH),t.lookahead-=t.match_length,t.strstart+=t.match_length,t.match_length=0):(n=_tr_tally(t,0,t.window[t.strstart]),t.lookahead--,t.strstart++),n&&(flush_block_only(t,!1),0===t.strm.avail_out))return BS_NEED_MORE}return t.insert=0,e===Z_FINISH$3?(flush_block_only(t,!0),0===t.strm.avail_out?BS_FINISH_STARTED:BS_FINISH_DONE):t.sym_next&&(flush_block_only(t,!1),0===t.strm.avail_out)?BS_NEED_MORE:BS_BLOCK_DONE},deflate_huff=(t,e)=>{let n;for(;;){if(0===t.lookahead&&(fill_window(t),0===t.lookahead)){if(e===Z_NO_FLUSH$2)return BS_NEED_MORE;break}if(t.match_length=0,n=_tr_tally(t,0,t.window[t.strstart]),t.lookahead--,t.strstart++,n&&(flush_block_only(t,!1),0===t.strm.avail_out))return BS_NEED_MORE}return t.insert=0,e===Z_FINISH$3?(flush_block_only(t,!0),0===t.strm.avail_out?BS_FINISH_STARTED:BS_FINISH_DONE):t.sym_next&&(flush_block_only(t,!1),0===t.strm.avail_out)?BS_NEED_MORE:BS_BLOCK_DONE};function Config(t,e,n,r,i){this.good_length=t,this.max_lazy=e,this.nice_length=n,this.max_chain=r,this.func=i}const configuration_table=[new Config(0,0,0,0,deflate_stored),new Config(4,4,8,4,deflate_fast),new Config(4,5,16,8,deflate_fast),new Config(4,6,32,32,deflate_fast),new Config(4,4,16,16,deflate_slow),new Config(8,16,32,32,deflate_slow),new Config(8,16,128,128,deflate_slow),new Config(8,32,128,256,deflate_slow),new Config(32,128,258,1024,deflate_slow),new Config(32,258,258,4096,deflate_slow)],lm_init=t=>{t.window_size=2*t.w_size,zero(t.head),t.max_lazy_match=configuration_table[t.level].max_lazy,t.good_match=configuration_table[t.level].good_length,t.nice_match=configuration_table[t.level].nice_length,t.max_chain_length=configuration_table[t.level].max_chain,t.strstart=0,t.block_start=0,t.lookahead=0,t.insert=0,t.match_length=t.prev_length=MIN_MATCH-1,t.match_available=0,t.ins_h=0};function DeflateState(){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=Z_DEFLATED$2,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(2*HEAP_SIZE),this.dyn_dtree=new Uint16Array(2*(2*D_CODES+1)),this.bl_tree=new Uint16Array(2*(2*BL_CODES+1)),zero(this.dyn_ltree),zero(this.dyn_dtree),zero(this.bl_tree),this.l_desc=null,this.d_desc=null,this.bl_desc=null,this.bl_count=new Uint16Array(MAX_BITS+1),this.heap=new Uint16Array(2*L_CODES+1),zero(this.heap),this.heap_len=0,this.heap_max=0,this.depth=new Uint16Array(2*L_CODES+1),zero(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 deflateStateCheck=t=>{if(!t)return 1;const e=t.state;return!e||e.strm!==t||e.status!==INIT_STATE&&e.status!==GZIP_STATE&&e.status!==EXTRA_STATE&&e.status!==NAME_STATE&&e.status!==COMMENT_STATE&&e.status!==HCRC_STATE&&e.status!==BUSY_STATE&&e.status!==FINISH_STATE?1:0},deflateResetKeep=t=>{if(deflateStateCheck(t))return err(t,Z_STREAM_ERROR$2);t.total_in=t.total_out=0,t.data_type=Z_UNKNOWN;const e=t.state;return e.pending=0,e.pending_out=0,e.wrap<0&&(e.wrap=-e.wrap),e.status=2===e.wrap?GZIP_STATE:e.wrap?INIT_STATE:BUSY_STATE,t.adler=2===e.wrap?0:1,e.last_flush=-2,_tr_init(e),Z_OK$3},deflateReset=t=>{const e=deflateResetKeep(t);return e===Z_OK$3&&lm_init(t.state),e},deflateSetHeader=(t,e)=>deflateStateCheck(t)||2!==t.state.wrap?Z_STREAM_ERROR$2:(t.state.gzhead=e,Z_OK$3),deflateInit2=(t,e,n,r,i,s)=>{if(!t)return Z_STREAM_ERROR$2;let a=1;if(e===Z_DEFAULT_COMPRESSION$1&&(e=6),r<0?(a=0,r=-r):r>15&&(a=2,r-=16),i<1||i>MAX_MEM_LEVEL||n!==Z_DEFLATED$2||r<8||r>15||e<0||e>9||s<0||s>Z_FIXED||8===r&&1!==a)return err(t,Z_STREAM_ERROR$2);8===r&&(r=9);const o=new DeflateState;return t.state=o,o.strm=t,o.status=INIT_STATE,o.wrap=a,o.gzhead=null,o.w_bits=r,o.w_size=1<<o.w_bits,o.w_mask=o.w_size-1,o.hash_bits=i+7,o.hash_size=1<<o.hash_bits,o.hash_mask=o.hash_size-1,o.hash_shift=~~((o.hash_bits+MIN_MATCH-1)/MIN_MATCH),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<<i+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=e,o.strategy=s,o.method=n,deflateReset(t)},deflateInit=(t,e)=>deflateInit2(t,e,Z_DEFLATED$2,MAX_WBITS$1,DEF_MEM_LEVEL,Z_DEFAULT_STRATEGY$1),deflate$2=(t,e)=>{if(deflateStateCheck(t)||e>Z_BLOCK$1||e<0)return t?err(t,Z_STREAM_ERROR$2):Z_STREAM_ERROR$2;const n=t.state;if(!t.output||0!==t.avail_in&&!t.input||n.status===FINISH_STATE&&e!==Z_FINISH$3)return err(t,0===t.avail_out?Z_BUF_ERROR$1:Z_STREAM_ERROR$2);const r=n.last_flush;if(n.last_flush=e,0!==n.pending){if(flush_pending(t),0===t.avail_out)return n.last_flush=-1,Z_OK$3}else if(0===t.avail_in&&rank(e)<=rank(r)&&e!==Z_FINISH$3)return err(t,Z_BUF_ERROR$1);if(n.status===FINISH_STATE&&0!==t.avail_in)return err(t,Z_BUF_ERROR$1);if(n.status===INIT_STATE&&0===n.wrap&&(n.status=BUSY_STATE),n.status===INIT_STATE){let e=Z_DEFLATED$2+(n.w_bits-8<<4)<<8,r=-1;if(r=n.strategy>=Z_HUFFMAN_ONLY||n.level<2?0:n.level<6?1:6===n.level?2:3,e|=r<<6,0!==n.strstart&&(e|=PRESET_DICT),e+=31-e%31,putShortMSB(n,e),0!==n.strstart&&(putShortMSB(n,t.adler>>>16),putShortMSB(n,65535&t.adler)),t.adler=1,n.status=BUSY_STATE,flush_pending(t),0!==n.pending)return n.last_flush=-1,Z_OK$3}if(n.status===GZIP_STATE)if(t.adler=0,put_byte(n,31),put_byte(n,139),put_byte(n,8),n.gzhead)put_byte(n,(n.gzhead.text?1:0)+(n.gzhead.hcrc?2:0)+(n.gzhead.extra?4:0)+(n.gzhead.name?8:0)+(n.gzhead.comment?16:0)),put_byte(n,255&n.gzhead.time),put_byte(n,n.gzhead.time>>8&255),put_byte(n,n.gzhead.time>>16&255),put_byte(n,n.gzhead.time>>24&255),put_byte(n,9===n.level?2:n.strategy>=Z_HUFFMAN_ONLY||n.level<2?4:0),put_byte(n,255&n.gzhead.os),n.gzhead.extra&&n.gzhead.extra.length&&(put_byte(n,255&n.gzhead.extra.length),put_byte(n,n.gzhead.extra.length>>8&255)),n.gzhead.hcrc&&(t.adler=crc32_1(t.adler,n.pending_buf,n.pending,0)),n.gzindex=0,n.status=EXTRA_STATE;else if(put_byte(n,0),put_byte(n,0),put_byte(n,0),put_byte(n,0),put_byte(n,0),put_byte(n,9===n.level?2:n.strategy>=Z_HUFFMAN_ONLY||n.level<2?4:0),put_byte(n,OS_CODE),n.status=BUSY_STATE,flush_pending(t),0!==n.pending)return n.last_flush=-1,Z_OK$3;if(n.status===EXTRA_STATE){if(n.gzhead.extra){let e=n.pending,r=(65535&n.gzhead.extra.length)-n.gzindex;for(;n.pending+r>n.pending_buf_size;){let i=n.pending_buf_size-n.pending;if(n.pending_buf.set(n.gzhead.extra.subarray(n.gzindex,n.gzindex+i),n.pending),n.pending=n.pending_buf_size,n.gzhead.hcrc&&n.pending>e&&(t.adler=crc32_1(t.adler,n.pending_buf,n.pending-e,e)),n.gzindex+=i,flush_pending(t),0!==n.pending)return n.last_flush=-1,Z_OK$3;e=0,r-=i}let i=new Uint8Array(n.gzhead.extra);n.pending_buf.set(i.subarray(n.gzindex,n.gzindex+r),n.pending),n.pending+=r,n.gzhead.hcrc&&n.pending>e&&(t.adler=crc32_1(t.adler,n.pending_buf,n.pending-e,e)),n.gzindex=0}n.status=NAME_STATE}if(n.status===NAME_STATE){if(n.gzhead.name){let e,r=n.pending;do{if(n.pending===n.pending_buf_size){if(n.gzhead.hcrc&&n.pending>r&&(t.adler=crc32_1(t.adler,n.pending_buf,n.pending-r,r)),flush_pending(t),0!==n.pending)return n.last_flush=-1,Z_OK$3;r=0}e=n.gzindex<n.gzhead.name.length?255&n.gzhead.name.charCodeAt(n.gzindex++):0,put_byte(n,e)}while(0!==e);n.gzhead.hcrc&&n.pending>r&&(t.adler=crc32_1(t.adler,n.pending_buf,n.pending-r,r)),n.gzindex=0}n.status=COMMENT_STATE}if(n.status===COMMENT_STATE){if(n.gzhead.comment){let e,r=n.pending;do{if(n.pending===n.pending_buf_size){if(n.gzhead.hcrc&&n.pending>r&&(t.adler=crc32_1(t.adler,n.pending_buf,n.pending-r,r)),flush_pending(t),0!==n.pending)return n.last_flush=-1,Z_OK$3;r=0}e=n.gzindex<n.gzhead.comment.length?255&n.gzhead.comment.charCodeAt(n.gzindex++):0,put_byte(n,e)}while(0!==e);n.gzhead.hcrc&&n.pending>r&&(t.adler=crc32_1(t.adler,n.pending_buf,n.pending-r,r))}n.status=HCRC_STATE}if(n.status===HCRC_STATE){if(n.gzhead.hcrc){if(n.pending+2>n.pending_buf_size&&(flush_pending(t),0!==n.pending))return n.last_flush=-1,Z_OK$3;put_byte(n,255&t.adler),put_byte(n,t.adler>>8&255),t.adler=0}if(n.status=BUSY_STATE,flush_pending(t),0!==n.pending)return n.last_flush=-1,Z_OK$3}if(0!==t.avail_in||0!==n.lookahead||e!==Z_NO_FLUSH$2&&n.status!==FINISH_STATE){let r=0===n.level?deflate_stored(n,e):n.strategy===Z_HUFFMAN_ONLY?deflate_huff(n,e):n.strategy===Z_RLE?deflate_rle(n,e):configuration_table[n.level].func(n,e);if(r!==BS_FINISH_STARTED&&r!==BS_FINISH_DONE||(n.status=FINISH_STATE),r===BS_NEED_MORE||r===BS_FINISH_STARTED)return 0===t.avail_out&&(n.last_flush=-1),Z_OK$3;if(r===BS_BLOCK_DONE&&(e===Z_PARTIAL_FLUSH?_tr_align(n):e!==Z_BLOCK$1&&(_tr_stored_block(n,0,0,!1),e===Z_FULL_FLUSH$1&&(zero(n.head),0===n.lookahead&&(n.strstart=0,n.block_start=0,n.insert=0))),flush_pending(t),0===t.avail_out))return n.last_flush=-1,Z_OK$3}return e!==Z_FINISH$3?Z_OK$3:n.wrap<=0?Z_STREAM_END$3:(2===n.wrap?(put_byte(n,255&t.adler),put_byte(n,t.adler>>8&255),put_byte(n,t.adler>>16&255),put_byte(n,t.adler>>24&255),put_byte(n,255&t.total_in),put_byte(n,t.total_in>>8&255),put_byte(n,t.total_in>>16&255),put_byte(n,t.total_in>>24&255)):(putShortMSB(n,t.adler>>>16),putShortMSB(n,65535&t.adler)),flush_pending(t),n.wrap>0&&(n.wrap=-n.wrap),0!==n.pending?Z_OK$3:Z_STREAM_END$3)},deflateEnd=t=>{if(deflateStateCheck(t))return Z_STREAM_ERROR$2;const e=t.state.status;return t.state=null,e===BUSY_STATE?err(t,Z_DATA_ERROR$2):Z_OK$3},deflateSetDictionary=(t,e)=>{let n=e.length;if(deflateStateCheck(t))return Z_STREAM_ERROR$2;const r=t.state,i=r.wrap;if(2===i||1===i&&r.status!==INIT_STATE||r.lookahead)return Z_STREAM_ERROR$2;if(1===i&&(t.adler=adler32_1(t.adler,e,n,0)),r.wrap=0,n>=r.w_size){0===i&&(zero(r.head),r.strstart=0,r.block_start=0,r.insert=0);let t=new Uint8Array(r.w_size);t.set(e.subarray(n-r.w_size,n),0),e=t,n=r.w_size}const s=t.avail_in,a=t.next_in,o=t.input;for(t.avail_in=n,t.next_in=0,t.input=e,fill_window(r);r.lookahead>=MIN_MATCH;){let t=r.strstart,e=r.lookahead-(MIN_MATCH-1);do{r.ins_h=HASH(r,r.ins_h,r.window[t+MIN_MATCH-1]),r.prev[t&r.w_mask]=r.head[r.ins_h],r.head[r.ins_h]=t,t++}while(--e);r.strstart=t,r.lookahead=MIN_MATCH-1,fill_window(r)}return r.strstart+=r.lookahead,r.block_start=r.strstart,r.insert=r.lookahead,r.lookahead=0,r.match_length=r.prev_length=MIN_MATCH-1,r.match_available=0,t.next_in=a,t.input=o,t.avail_in=s,r.wrap=i,Z_OK$3};var deflateInit_1=deflateInit,deflateInit2_1=deflateInit2,deflateReset_1=deflateReset,deflateResetKeep_1=deflateResetKeep,deflateSetHeader_1=deflateSetHeader,deflate_2$1=deflate$2,deflateEnd_1=deflateEnd,deflateSetDictionary_1=deflateSetDictionary,deflateInfo="pako deflate (from Nodeca project)",deflate_1$2={deflateInit:deflateInit_1,deflateInit2:deflateInit2_1,deflateReset:deflateReset_1,deflateResetKeep:deflateResetKeep_1,deflateSetHeader:deflateSetHeader_1,deflate:deflate_2$1,deflateEnd:deflateEnd_1,deflateSetDictionary:deflateSetDictionary_1,deflateInfo};const _has=(t,e)=>Object.prototype.hasOwnProperty.call(t,e);var assign=function(t){const e=Array.prototype.slice.call(arguments,1);for(;e.length;){const n=e.shift();if(n){if("object"!=typeof n)throw new TypeError(n+"must be non-object");for(const e in n)_has(n,e)&&(t[e]=n[e])}}return t},flattenChunks=t=>{let e=0;for(let n=0,r=t.length;n<r;n++)e+=t[n].length;const n=new Uint8Array(e);for(let e=0,r=0,i=t.length;e<i;e++){let i=t[e];n.set(i,r),r+=i.length}return n},common={assign,flattenChunks};let STR_APPLY_UIA_OK=!0;try{String.fromCharCode.apply(null,new Uint8Array(1))}catch(t){STR_APPLY_UIA_OK=!1}const _utf8len=new Uint8Array(256);for(let t=0;t<256;t++)_utf8len[t]=t>=252?6:t>=248?5:t>=240?4:t>=224?3:t>=192?2:1;_utf8len[254]=_utf8len[254]=1;var string2buf=t=>{if("function"==typeof TextEncoder&&TextEncoder.prototype.encode)return(new TextEncoder).encode(t);let e,n,r,i,s,a=t.length,o=0;for(i=0;i<a;i++)n=t.charCodeAt(i),55296==(64512&n)&&i+1<a&&(r=t.charCodeAt(i+1),56320==(64512&r)&&(n=65536+(n-55296<<10)+(r-56320),i++)),o+=n<128?1:n<2048?2:n<65536?3:4;for(e=new Uint8Array(o),s=0,i=0;s<o;i++)n=t.charCodeAt(i),55296==(64512&n)&&i+1<a&&(r=t.charCodeAt(i+1),56320==(64512&r)&&(n=65536+(n-55296<<10)+(r-56320),i++)),n<128?e[s++]=n:n<2048?(e[s++]=192|n>>>6,e[s++]=128|63&n):n<65536?(e[s++]=224|n>>>12,e[s++]=128|n>>>6&63,e[s++]=128|63&n):(e[s++]=240|n>>>18,e[s++]=128|n>>>12&63,e[s++]=128|n>>>6&63,e[s++]=128|63&n);return e};const buf2binstring=(t,e)=>{if(e<65534&&t.subarray&&STR_APPLY_UIA_OK)return String.fromCharCode.apply(null,t.length===e?t:t.subarray(0,e));let n="";for(let r=0;r<e;r++)n+=String.fromCharCode(t[r]);return n};var buf2string=(t,e)=>{const n=e||t.length;if("function"==typeof TextDecoder&&TextDecoder.prototype.decode)return(new TextDecoder).decode(t.subarray(0,e));let r,i;const s=new Array(2*n);for(i=0,r=0;r<n;){let e=t[r++];if(e<128){s[i++]=e;continue}let a=_utf8len[e];if(a>4)s[i++]=65533,r+=a-1;else{for(e&=2===a?31:3===a?15:7;a>1&&r<n;)e=e<<6|63&t[r++],a--;a>1?s[i++]=65533:e<65536?s[i++]=e:(e-=65536,s[i++]=55296|e>>10&1023,s[i++]=56320|1023&e)}}return buf2binstring(s,i)},utf8border=(t,e)=>{(e=e||t.length)>t.length&&(e=t.length);let n=e-1;for(;n>=0&&128==(192&t[n]);)n--;return n<0||0===n?e:n+_utf8len[t[n]]>e?n:e},strings={string2buf,buf2string,utf8border};function ZStream(){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}var zstream=ZStream;const toString$1=Object.prototype.toString,{Z_NO_FLUSH:Z_NO_FLUSH$1,Z_SYNC_FLUSH,Z_FULL_FLUSH,Z_FINISH:Z_FINISH$2,Z_OK:Z_OK$2,Z_STREAM_END:Z_STREAM_END$2,Z_DEFAULT_COMPRESSION,Z_DEFAULT_STRATEGY,Z_DEFLATED:Z_DEFLATED$1}=constants$2;function Deflate$1(t){this.options=common.assign({level:Z_DEFAULT_COMPRESSION,method:Z_DEFLATED$1,chunkSize:16384,windowBits:15,memLevel:8,strategy:Z_DEFAULT_STRATEGY},t||{});let e=this.options;e.raw&&e.windowBits>0?e.windowBits=-e.windowBits:e.gzip&&e.windowBits>0&&e.windowBits<16&&(e.windowBits+=16),this.err=0,this.msg="",this.ended=!1,this.chunks=[],this.strm=new zstream,this.strm.avail_out=0;let n=deflate_1$2.deflateInit2(this.strm,e.level,e.method,e.windowBits,e.memLevel,e.strategy);if(n!==Z_OK$2)throw new Error(messages[n]);if(e.header&&deflate_1$2.deflateSetHeader(this.strm,e.header),e.dictionary){let t;if(t="string"==typeof e.dictionary?strings.string2buf(e.dictionary):"[object ArrayBuffer]"===toString$1.call(e.dictionary)?new Uint8Array(e.dictionary):e.dictionary,n=deflate_1$2.deflateSetDictionary(this.strm,t),n!==Z_OK$2)throw new Error(messages[n]);this._dict_set=!0}}function deflate$1(t,e){const n=new Deflate$1(e);if(n.push(t,!0),n.err)throw n.msg||messages[n.err];return n.result}function deflateRaw$1(t,e){return(e=e||{}).raw=!0,deflate$1(t,e)}function gzip$1(t,e){return(e=e||{}).gzip=!0,deflate$1(t,e)}Deflate$1.prototype.push=function(t,e){const n=this.strm,r=this.options.chunkSize;let i,s;if(this.ended)return!1;for(s=e===~~e?e:!0===e?Z_FINISH$2:Z_NO_FLUSH$1,n.input="string"==typeof t?strings.string2buf(t):"[object ArrayBuffer]"===toString$1.call(t)?new Uint8Array(t):t,n.next_in=0,n.avail_in=n.input.length;;)if(0===n.avail_out&&(n.output=new Uint8Array(r),n.next_out=0,n.avail_out=r),(s===Z_SYNC_FLUSH||s===Z_FULL_FLUSH)&&n.avail_out<=6)this.onData(n.output.subarray(0,n.next_out)),n.avail_out=0;else{if(i=deflate_1$2.deflate(n,s),i===Z_STREAM_END$2)return n.next_out>0&&this.onData(n.output.subarray(0,n.next_out)),i=deflate_1$2.deflateEnd(this.strm),this.onEnd(i),this.ended=!0,i===Z_OK$2;if(0!==n.avail_out){if(s>0&&n.next_out>0)this.onData(n.output.subarray(0,n.next_out)),n.avail_out=0;else if(0===n.avail_in)break}else this.onData(n.output)}return!0},Deflate$1.prototype.onData=function(t){this.chunks.push(t)},Deflate$1.prototype.onEnd=function(t){t===Z_OK$2&&(this.result=common.flattenChunks(this.chunks)),this.chunks=[],this.err=t,this.msg=this.strm.msg};var Deflate_1$1=Deflate$1,deflate_2=deflate$1,deflateRaw_1$1=deflateRaw$1,gzip_1$1=gzip$1,constants$1=constants$2,deflate_1$1={Deflate:Deflate_1$1,deflate:deflate_2,deflateRaw:deflateRaw_1$1,gzip:gzip_1$1,constants:constants$1};const BAD$1=16209,TYPE$1=16191;var inffast=function(t,e){let n,r,i,s,a,o,l,c,d,h,u,p,f,m,_,g,y,S,A,v,E,b,T,w;const x=t.state;n=t.next_in,T=t.input,r=n+(t.avail_in-5),i=t.next_out,w=t.output,s=i-(e-t.avail_out),a=i+(t.avail_out-257),o=x.dmax,l=x.wsize,c=x.whave,d=x.wnext,h=x.window,u=x.hold,p=x.bits,f=x.lencode,m=x.distcode,_=(1<<x.lenbits)-1,g=(1<<x.distbits)-1;t:do{p<15&&(u+=T[n++]<<p,p+=8,u+=T[n++]<<p,p+=8),y=f[u&_];e:for(;;){if(S=y>>>24,u>>>=S,p-=S,S=y>>>16&255,0===S)w[i++]=65535&y;else{if(!(16&S)){if(64&S){if(32&S){x.mode=TYPE$1;break t}t.msg="invalid literal/length code",x.mode=BAD$1;break t}y=f[(65535&y)+(u&(1<<S)-1)];continue e}for(A=65535&y,S&=15,S&&(p<S&&(u+=T[n++]<<p,p+=8),A+=u&(1<<S)-1,u>>>=S,p-=S),p<15&&(u+=T[n++]<<p,p+=8,u+=T[n++]<<p,p+=8),y=m[u&g];;){if(S=y>>>24,u>>>=S,p-=S,S=y>>>16&255,16&S){if(v=65535&y,S&=15,p<S&&(u+=T[n++]<<p,p+=8,p<S&&(u+=T[n++]<<p,p+=8)),v+=u&(1<<S)-1,v>o){t.msg="invalid distance too far back",x.mode=BAD$1;break t}if(u>>>=S,p-=S,S=i-s,v>S){if(S=v-S,S>c&&x.sane){t.msg="invalid distance too far back",x.mode=BAD$1;break t}if(E=0,b=h,0===d){if(E+=l-S,S<A){A-=S;do{w[i++]=h[E++]}while(--S);E=i-v,b=w}}else if(d<S){if(E+=l+d-S,S-=d,S<A){A-=S;do{w[i++]=h[E++]}while(--S);if(E=0,d<A){S=d,A-=S;do{w[i++]=h[E++]}while(--S);E=i-v,b=w}}}else if(E+=d-S,S<A){A-=S;do{w[i++]=h[E++]}while(--S);E=i-v,b=w}for(;A>2;)w[i++]=b[E++],w[i++]=b[E++],w[i++]=b[E++],A-=3;A&&(w[i++]=b[E++],A>1&&(w[i++]=b[E++]))}else{E=i-v;do{w[i++]=w[E++],w[i++]=w[E++],w[i++]=w[E++],A-=3}while(A>2);A&&(w[i++]=w[E++],A>1&&(w[i++]=w[E++]))}break}if(64&S){t.msg="invalid distance code",x.mode=BAD$1;break t}y=m[(65535&y)+(u&(1<<S)-1)]}}break}}while(n<r&&i<a);A=p>>3,n-=A,p-=A<<3,u&=(1<<p)-1,t.next_in=n,t.next_out=i,t.avail_in=n<r?r-n+5:5-(n-r),t.avail_out=i<a?a-i+257:257-(i-a),x.hold=u,x.bits=p};const MAXBITS=15,ENOUGH_LENS$1=852,ENOUGH_DISTS$1=592,CODES$1=0,LENS$1=1,DISTS$1=2,lbase=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]),lext=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]),dbase=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]),dext=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]),inflate_table=(t,e,n,r,i,s,a,o)=>{const l=o.bits;let c,d,h,u,p,f,m=0,_=0,g=0,y=0,S=0,A=0,v=0,E=0,b=0,T=0,w=null;const x=new Uint16Array(MAXBITS+1),I=new Uint16Array(MAXBITS+1);let R,C,B,D=null;for(m=0;m<=MAXBITS;m++)x[m]=0;for(_=0;_<r;_++)x[e[n+_]]++;for(S=l,y=MAXBITS;y>=1&&0===x[y];y--);if(S>y&&(S=y),0===y)return i[s++]=20971520,i[s++]=20971520,o.bits=1,0;for(g=1;g<y&&0===x[g];g++);for(S<g&&(S=g),E=1,m=1;m<=MAXBITS;m++)if(E<<=1,E-=x[m],E<0)return-1;if(E>0&&(t===CODES$1||1!==y))return-1;for(I[1]=0,m=1;m<MAXBITS;m++)I[m+1]=I[m]+x[m];for(_=0;_<r;_++)0!==e[n+_]&&(a[I[e[n+_]]++]=_);if(t===CODES$1?(w=D=a,f=20):t===LENS$1?(w=lbase,D=lext,f=257):(w=dbase,D=dext,f=0),T=0,_=0,m=g,p=s,A=S,v=0,h=-1,b=1<<S,u=b-1,t===LENS$1&&b>ENOUGH_LENS$1||t===DISTS$1&&b>ENOUGH_DISTS$1)return 1;for(;;){R=m-v,a[_]+1<f?(C=0,B=a[_]):a[_]>=f?(C=D[a[_]-f],B=w[a[_]-f]):(C=96,B=0),c=1<<m-v,d=1<<A,g=d;do{d-=c,i[p+(T>>v)+d]=R<<24|C<<16|B}while(0!==d);for(c=1<<m-1;T&c;)c>>=1;if(0!==c?(T&=c-1,T+=c):T=0,_++,0===--x[m]){if(m===y)break;m=e[n+a[_]]}if(m>S&&(T&u)!==h){for(0===v&&(v=S),p+=g,A=m-v,E=1<<A;A+v<y&&(E-=x[A+v],!(E<=0));)A++,E<<=1;if(b+=1<<A,t===LENS$1&&b>ENOUGH_LENS$1||t===DISTS$1&&b>ENOUGH_DISTS$1)return 1;h=T&u,i[h]=S<<24|A<<16|p-s}}return 0!==T&&(i[p+T]=m-v<<24|64<<16),o.bits=S,0};var inftrees=inflate_table;const CODES=0,LENS=1,DISTS=2,{Z_FINISH:Z_FINISH$1,Z_BLOCK,Z_TREES,Z_OK:Z_OK$1,Z_STREAM_END:Z_STREAM_END$1,Z_NEED_DICT:Z_NEED_DICT$1,Z_STREAM_ERROR:Z_STREAM_ERROR$1,Z_DATA_ERROR:Z_DATA_ERROR$1,Z_MEM_ERROR:Z_MEM_ERROR$1,Z_BUF_ERROR,Z_DEFLATED}=constants$2,HEAD=16180,FLAGS=16181,TIME=16182,OS=16183,EXLEN=16184,EXTRA=16185,NAME=16186,COMMENT=16187,HCRC=16188,DICTID=16189,DICT=16190,TYPE=16191,TYPEDO=16192,STORED=16193,COPY_=16194,COPY=16195,TABLE=16196,LENLENS=16197,CODELENS=16198,LEN_=16199,LEN=16200,LENEXT=16201,DIST=16202,DISTEXT=16203,MATCH=16204,LIT=16205,CHECK=16206,LENGTH=16207,DONE=16208,BAD=16209,MEM=16210,SYNC=16211,ENOUGH_LENS=852,ENOUGH_DISTS=592,MAX_WBITS=15,DEF_WBITS=MAX_WBITS,zswap32=t=>(t>>>24&255)+(t>>>8&65280)+((65280&t)<<8)+((255&t)<<24);function InflateState(){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 inflateStateCheck=t=>{if(!t)return 1;const e=t.state;return!e||e.strm!==t||e.mode<HEAD||e.mode>SYNC?1:0},inflateResetKeep=t=>{if(inflateStateCheck(t))return Z_STREAM_ERROR$1;const e=t.state;return t.total_in=t.total_out=e.total=0,t.msg="",e.wrap&&(t.adler=1&e.wrap),e.mode=HEAD,e.last=0,e.havedict=0,e.flags=-1,e.dmax=32768,e.head=null,e.hold=0,e.bits=0,e.lencode=e.lendyn=new Int32Array(ENOUGH_LENS),e.distcode=e.distdyn=new Int32Array(ENOUGH_DISTS),e.sane=1,e.back=-1,Z_OK$1},inflateReset=t=>{if(inflateStateCheck(t))return Z_STREAM_ERROR$1;const e=t.state;return e.wsize=0,e.whave=0,e.wnext=0,inflateResetKeep(t)},inflateReset2=(t,e)=>{let n;if(inflateStateCheck(t))return Z_STREAM_ERROR$1;const r=t.state;return e<0?(n=0,e=-e):(n=5+(e>>4),e<48&&(e&=15)),e&&(e<8||e>15)?Z_STREAM_ERROR$1:(null!==r.window&&r.wbits!==e&&(r.window=null),r.wrap=n,r.wbits=e,inflateReset(t))},inflateInit2=(t,e)=>{if(!t)return Z_STREAM_ERROR$1;const n=new InflateState;t.state=n,n.strm=t,n.window=null,n.mode=HEAD;const r=inflateReset2(t,e);return r!==Z_OK$1&&(t.state=null),r},inflateInit=t=>inflateInit2(t,DEF_WBITS);let virgin=!0,lenfix,distfix;const fixedtables=t=>{if(virgin){lenfix=new Int32Array(512),distfix=new Int32Array(32);let e=0;for(;e<144;)t.lens[e++]=8;for(;e<256;)t.lens[e++]=9;for(;e<280;)t.lens[e++]=7;for(;e<288;)t.lens[e++]=8;for(inftrees(LENS,t.lens,0,288,lenfix,0,t.work,{bits:9}),e=0;e<32;)t.lens[e++]=5;inftrees(DISTS,t.lens,0,32,distfix,0,t.work,{bits:5}),virgin=!1}t.lencode=lenfix,t.lenbits=9,t.distcode=distfix,t.distbits=5},updatewindow=(t,e,n,r)=>{let i;const s=t.state;return null===s.window&&(s.wsize=1<<s.wbits,s.wnext=0,s.whave=0,s.window=new Uint8Array(s.wsize)),r>=s.wsize?(s.window.set(e.subarray(n-s.wsize,n),0),s.wnext=0,s.whave=s.wsize):(i=s.wsize-s.wnext,i>r&&(i=r),s.window.set(e.subarray(n-r,n-r+i),s.wnext),(r-=i)?(s.window.set(e.subarray(n-r,n),0),s.wnext=r,s.whave=s.wsize):(s.wnext+=i,s.wnext===s.wsize&&(s.wnext=0),s.whave<s.wsize&&(s.whave+=i))),0},inflate$2=(t,e)=>{let n,r,i,s,a,o,l,c,d,h,u,p,f,m,_,g,y,S,A,v,E,b,T=0;const w=new Uint8Array(4);let x,I;const R=new Uint8Array([16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15]);if(inflateStateCheck(t)||!t.output||!t.input&&0!==t.avail_in)return Z_STREAM_ERROR$1;n=t.state,n.mode===TYPE&&(n.mode=TYPEDO),a=t.next_out,i=t.output,l=t.avail_out,s=t.next_in,r=t.input,o=t.avail_in,c=n.hold,d=n.bits,h=o,u=l,b=Z_OK$1;t:for(;;)switch(n.mode){case HEAD:if(0===n.wrap){n.mode=TYPEDO;break}for(;d<16;){if(0===o)break t;o--,c+=r[s++]<<d,d+=8}if(2&n.wrap&&35615===c){0===n.wbits&&(n.wbits=15),n.check=0,w[0]=255&c,w[1]=c>>>8&255,n.check=crc32_1(n.check,w,2,0),c=0,d=0,n.mode=FLAGS;break}if(n.head&&(n.head.done=!1),!(1&n.wrap)||(((255&c)<<8)+(c>>8))%31){t.msg="incorrect header check",n.mode=BAD;break}if((15&c)!==Z_DEFLATED){t.msg="unknown compression method",n.mode=BAD;break}if(c>>>=4,d-=4,E=8+(15&c),0===n.wbits&&(n.wbits=E),E>15||E>n.wbits){t.msg="invalid window size",n.mode=BAD;break}n.dmax=1<<n.wbits,n.flags=0,t.adler=n.check=1,n.mode=512&c?DICTID:TYPE,c=0,d=0;break;case FLAGS:for(;d<16;){if(0===o)break t;o--,c+=r[s++]<<d,d+=8}if(n.flags=c,(255&n.flags)!==Z_DEFLATED){t.msg="unknown compression method",n.mode=BAD;break}if(57344&n.flags){t.msg="unknown header flags set",n.mode=BAD;break}n.head&&(n.head.text=c>>8&1),512&n.flags&&4&n.wrap&&(w[0]=255&c,w[1]=c>>>8&255,n.check=crc32_1(n.check,w,2,0)),c=0,d=0,n.mode=TIME;case TIME:for(;d<32;){if(0===o)break t;o--,c+=r[s++]<<d,d+=8}n.head&&(n.head.time=c),512&n.flags&&4&n.wrap&&(w[0]=255&c,w[1]=c>>>8&255,w[2]=c>>>16&255,w[3]=c>>>24&255,n.check=crc32_1(n.check,w,4,0)),c=0,d=0,n.mode=OS;case OS:for(;d<16;){if(0===o)break t;o--,c+=r[s++]<<d,d+=8}n.head&&(n.head.xflags=255&c,n.head.os=c>>8),512&n.flags&&4&n.wrap&&(w[0]=255&c,w[1]=c>>>8&255,n.check=crc32_1(n.check,w,2,0)),c=0,d=0,n.mode=EXLEN;case EXLEN:if(1024&n.flags){for(;d<16;){if(0===o)break t;o--,c+=r[s++]<<d,d+=8}n.length=c,n.head&&(n.head.extra_len=c),512&n.flags&&4&n.wrap&&(w[0]=255&c,w[1]=c>>>8&255,n.check=crc32_1(n.check,w,2,0)),c=0,d=0}else n.head&&(n.head.extra=null);n.mode=EXTRA;case EXTRA:if(1024&n.flags&&(p=n.length,p>o&&(p=o),p&&(n.head&&(E=n.head.extra_len-n.length,n.head.extra||(n.head.extra=new Uint8Array(n.head.extra_len)),n.head.extra.set(r.subarray(s,s+p),E)),512&n.flags&&4&n.wrap&&(n.check=crc32_1(n.check,r,p,s)),o-=p,s+=p,n.length-=p),n.length))break t;n.length=0,n.mode=NAME;case NAME:if(2048&n.flags){if(0===o)break t;p=0;do{E=r[s+p++],n.head&&E&&n.length<65536&&(n.head.name+=String.fromCharCode(E))}while(E&&p<o);if(512&n.flags&&4&n.wrap&&(n.check=crc32_1(n.check,r,p,s)),o-=p,s+=p,E)break t}else n.head&&(n.head.name=null);n.length=0,n.mode=COMMENT;case COMMENT:if(4096&n.flags){if(0===o)break t;p=0;do{E=r[s+p++],n.head&&E&&n.length<65536&&(n.head.comment+=String.fromCharCode(E))}while(E&&p<o);if(512&n.flags&&4&n.wrap&&(n.check=crc32_1(n.check,r,p,s)),o-=p,s+=p,E)break t}else n.head&&(n.head.comment=null);n.mode=HCRC;case HCRC:if(512&n.flags){for(;d<16;){if(0===o)break t;o--,c+=r[s++]<<d,d+=8}if(4&n.wrap&&c!==(65535&n.check)){t.msg="header crc mismatch",n.mode=BAD;break}c=0,d=0}n.head&&(n.head.hcrc=n.flags>>9&1,n.head.done=!0),t.adler=n.check=0,n.mode=TYPE;break;case DICTID:for(;d<32;){if(0===o)break t;o--,c+=r[s++]<<d,d+=8}t.adler=n.check=zswap32(c),c=0,d=0,n.mode=DICT;case DICT:if(0===n.havedict)return t.next_out=a,t.avail_out=l,t.next_in=s,t.avail_in=o,n.hold=c,n.bits=d,Z_NEED_DICT$1;t.adler=n.check=1,n.mode=TYPE;case TYPE:if(e===Z_BLOCK||e===Z_TREES)break t;case TYPEDO:if(n.last){c>>>=7&d,d-=7&d,n.mode=CHECK;break}for(;d<3;){if(0===o)break t;o--,c+=r[s++]<<d,d+=8}switch(n.last=1&c,c>>>=1,d-=1,3&c){case 0:n.mode=STORED;break;case 1:if(fixedtables(n),n.mode=LEN_,e===Z_TREES){c>>>=2,d-=2;break t}break;case 2:n.mode=TABLE;break;case 3:t.msg="invalid block type",n.mode=BAD}c>>>=2,d-=2;break;case STORED:for(c>>>=7&d,d-=7&d;d<32;){if(0===o)break t;o--,c+=r[s++]<<d,d+=8}if((65535&c)!=(c>>>16^65535)){t.msg="invalid stored block lengths",n.mode=BAD;break}if(n.length=65535&c,c=0,d=0,n.mode=COPY_,e===Z_TREES)break t;case COPY_:n.mode=COPY;case COPY:if(p=n.length,p){if(p>o&&(p=o),p>l&&(p=l),0===p)break t;i.set(r.subarray(s,s+p),a),o-=p,s+=p,l-=p,a+=p,n.length-=p;break}n.mode=TYPE;break;case TABLE:for(;d<14;){if(0===o)break t;o--,c+=r[s++]<<d,d+=8}if(n.nlen=257+(31&c),c>>>=5,d-=5,n.ndist=1+(31&c),c>>>=5,d-=5,n.ncode=4+(15&c),c>>>=4,d-=4,n.nlen>286||n.ndist>30){t.msg="too many length or distance symbols",n.mode=BAD;break}n.have=0,n.mode=LENLENS;case LENLENS:for(;n.have<n.ncode;){for(;d<3;){if(0===o)break t;o--,c+=r[s++]<<d,d+=8}n.lens[R[n.have++]]=7&c,c>>>=3,d-=3}for(;n.have<19;)n.lens[R[n.have++]]=0;if(n.lencode=n.lendyn,n.lenbits=7,x={bits:n.lenbits},b=inftrees(CODES,n.lens,0,19,n.lencode,0,n.work,x),n.lenbits=x.bits,b){t.msg="invalid code lengths set",n.mode=BAD;break}n.have=0,n.mode=CODELENS;case CODELENS:for(;n.have<n.nlen+n.ndist;){for(;T=n.lencode[c&(1<<n.lenbits)-1],_=T>>>24,g=T>>>16&255,y=65535&T,!(_<=d);){if(0===o)break t;o--,c+=r[s++]<<d,d+=8}if(y<16)c>>>=_,d-=_,n.lens[n.have++]=y;else{if(16===y){for(I=_+2;d<I;){if(0===o)break t;o--,c+=r[s++]<<d,d+=8}if(c>>>=_,d-=_,0===n.have){t.msg="invalid bit length repeat",n.mode=BAD;break}E=n.lens[n.have-1],p=3+(3&c),c>>>=2,d-=2}else if(17===y){for(I=_+3;d<I;){if(0===o)break t;o--,c+=r[s++]<<d,d+=8}c>>>=_,d-=_,E=0,p=3+(7&c),c>>>=3,d-=3}else{for(I=_+7;d<I;){if(0===o)break t;o--,c+=r[s++]<<d,d+=8}c>>>=_,d-=_,E=0,p=11+(127&c),c>>>=7,d-=7}if(n.have+p>n.nlen+n.ndist){t.msg="invalid bit length repeat",n.mode=BAD;break}for(;p--;)n.lens[n.have++]=E}}if(n.mode===BAD)break;if(0===n.lens[256]){t.msg="invalid code -- missing end-of-block",n.mode=BAD;break}if(n.lenbits=9,x={bits:n.lenbits},b=inftrees(LENS,n.lens,0,n.nlen,n.lencode,0,n.work,x),n.lenbits=x.bits,b){t.msg="invalid literal/lengths set",n.mode=BAD;break}if(n.distbits=6,n.distcode=n.distdyn,x={bits:n.distbits},b=inftrees(DISTS,n.lens,n.nlen,n.ndist,n.distcode,0,n.work,x),n.distbits=x.bits,b){t.msg="invalid distances set",n.mode=BAD;break}if(n.mode=LEN_,e===Z_TREES)break t;case LEN_:n.mode=LEN;case LEN:if(o>=6&&l>=258){t.next_out=a,t.avail_out=l,t.next_in=s,t.avail_in=o,n.hold=c,n.bits=d,inffast(t,u),a=t.next_out,i=t.output,l=t.avail_out,s=t.next_in,r=t.input,o=t.avail_in,c=n.hold,d=n.bits,n.mode===TYPE&&(n.back=-1);break}for(n.back=0;T=n.lencode[c&(1<<n.lenbits)-1],_=T>>>24,g=T>>>16&255,y=65535&T,!(_<=d);){if(0===o)break t;o--,c+=r[s++]<<d,d+=8}if(g&&!(240&g)){for(S=_,A=g,v=y;T=n.lencode[v+((c&(1<<S+A)-1)>>S)],_=T>>>24,g=T>>>16&255,y=65535&T,!(S+_<=d);){if(0===o)break t;o--,c+=r[s++]<<d,d+=8}c>>>=S,d-=S,n.back+=S}if(c>>>=_,d-=_,n.back+=_,n.length=y,0===g){n.mode=LIT;break}if(32&g){n.back=-1,n.mode=TYPE;break}if(64&g){t.msg="invalid literal/length code",n.mode=BAD;break}n.extra=15&g,n.mode=LENEXT;case LENEXT:if(n.extra){for(I=n.extra;d<I;){if(0===o)break t;o--,c+=r[s++]<<d,d+=8}n.length+=c&(1<<n.extra)-1,c>>>=n.extra,d-=n.extra,n.back+=n.extra}n.was=n.length,n.mode=DIST;case DIST:for(;T=n.distcode[c&(1<<n.distbits)-1],_=T>>>24,g=T>>>16&255,y=65535&T,!(_<=d);){if(0===o)break t;o--,c+=r[s++]<<d,d+=8}if(!(240&g)){for(S=_,A=g,v=y;T=n.distcode[v+((c&(1<<S+A)-1)>>S)],_=T>>>24,g=T>>>16&255,y=65535&T,!(S+_<=d);){if(0===o)break t;o--,c+=r[s++]<<d,d+=8}c>>>=S,d-=S,n.back+=S}if(c>>>=_,d-=_,n.back+=_,64&g){t.msg="invalid distance code",n.mode=BAD;break}n.offset=y,n.extra=15&g,n.mode=DISTEXT;case DISTEXT:if(n.extra){for(I=n.extra;d<I;){if(0===o)break t;o--,c+=r[s++]<<d,d+=8}n.offset+=c&(1<<n.extra)-1,c>>>=n.extra,d-=n.extra,n.back+=n.extra}if(n.offset>n.dmax){t.msg="invalid distance too far back",n.mode=BAD;break}n.mode=MATCH;case MATCH:if(0===l)break t;if(p=u-l,n.offset>p){if(p=n.offset-p,p>n.whave&&n.sane){t.msg="invalid distance too far back",n.mode=BAD;break}p>n.wnext?(p-=n.wnext,f=n.wsize-p):f=n.wnext-p,p>n.length&&(p=n.length),m=n.window}else m=i,f=a-n.offset,p=n.length;p>l&&(p=l),l-=p,n.length-=p;do{i[a++]=m[f++]}while(--p);0===n.length&&(n.mode=LEN);break;case LIT:if(0===l)break t;i[a++]=n.length,l--,n.mode=LEN;break;case CHECK:if(n.wrap){for(;d<32;){if(0===o)break t;o--,c|=r[s++]<<d,d+=8}if(u-=l,t.total_out+=u,n.total+=u,4&n.wrap&&u&&(t.adler=n.check=n.flags?crc32_1(n.check,i,u,a-u):adler32_1(n.check,i,u,a-u)),u=l,4&n.wrap&&(n.flags?c:zswap32(c))!==n.check){t.msg="incorrect data check",n.mode=BAD;break}c=0,d=0}n.mode=LENGTH;case LENGTH:if(n.wrap&&n.flags){for(;d<32;){if(0===o)break t;o--,c+=r[s++]<<d,d+=8}if(4&n.wrap&&c!==(4294967295&n.total)){t.msg="incorrect length check",n.mode=BAD;break}c=0,d=0}n.mode=DONE;case DONE:b=Z_STREAM_END$1;break t;case BAD:b=Z_DATA_ERROR$1;break t;case MEM:return Z_MEM_ERROR$1;default:return Z_STREAM_ERROR$1}return t.next_out=a,t.avail_out=l,t.next_in=s,t.avail_in=o,n.hold=c,n.bits=d,(n.wsize||u!==t.avail_out&&n.mode<BAD&&(n.mode<CHECK||e!==Z_FINISH$1))&&updatewindow(t,t.output,t.next_out,u-t.avail_out),h-=t.avail_in,u-=t.avail_out,t.total_in+=h,t.total_out+=u,n.total+=u,4&n.wrap&&u&&(t.adler=n.check=n.flags?crc32_1(n.check,i,u,t.next_out-u):adler32_1(n.check,i,u,t.next_out-u)),t.data_type=n.bits+(n.last?64:0)+(n.mode===TYPE?128:0)+(n.mode===LEN_||n.mode===COPY_?256:0),(0===h&&0===u||e===Z_FINISH$1)&&b===Z_OK$1&&(b=Z_BUF_ERROR),b},inflateEnd=t=>{if(inflateStateCheck(t))return Z_STREAM_ERROR$1;let e=t.state;return e.window&&(e.window=null),t.state=null,Z_OK$1},inflateGetHeader=(t,e)=>{if(inflateStateCheck(t))return Z_STREAM_ERROR$1;const n=t.state;return 2&n.wrap?(n.head=e,e.done=!1,Z_OK$1):Z_STREAM_ERROR$1},inflateSetDictionary=(t,e)=>{const n=e.length;let r,i,s;return inflateStateCheck(t)?Z_STREAM_ERROR$1:(r=t.state,0!==r.wrap&&r.mode!==DICT?Z_STREAM_ERROR$1:r.mode===DICT&&(i=1,i=adler32_1(i,e,n,0),i!==r.check)?Z_DATA_ERROR$1:(s=updatewindow(t,e,n,n),s?(r.mode=MEM,Z_MEM_ERROR$1):(r.havedict=1,Z_OK$1)))};var inflateReset_1=inflateReset,inflateReset2_1=inflateReset2,inflateResetKeep_1=inflateResetKeep,inflateInit_1=inflateInit,inflateInit2_1=inflateInit2,inflate_2$1=inflate$2,inflateEnd_1=inflateEnd,inflateGetHeader_1=inflateGetHeader,inflateSetDictionary_1=inflateSetDictionary,inflateInfo="pako inflate (from Nodeca project)",inflate_1$2={inflateReset:inflateReset_1,inflateReset2:inflateReset2_1,inflateResetKeep:inflateResetKeep_1,inflateInit:inflateInit_1,inflateInit2:inflateInit2_1,inflate:inflate_2$1,inflateEnd:inflateEnd_1,inflateGetHeader:inflateGetHeader_1,inflateSetDictionary:inflateSetDictionary_1,inflateInfo};function GZheader(){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}var gzheader=GZheader;const toString$2=Object.prototype.toString,{Z_NO_FLUSH,Z_FINISH,Z_OK,Z_STREAM_END,Z_NEED_DICT,Z_STREAM_ERROR,Z_DATA_ERROR,Z_MEM_ERROR}=constants$2;function Inflate$1(t){this.options=common.assign({chunkSize:65536,windowBits:15,to:""},t||{});const e=this.options;e.raw&&e.windowBits>=0&&e.windowBits<16&&(e.windowBits=-e.windowBits,0===e.windowBits&&(e.windowBits=-15)),!(e.windowBits>=0&&e.windowBits<16)||t&&t.windowBits||(e.windowBits+=32),e.windowBits>15&&e.windowBits<48&&(15&e.windowBits||(e.windowBits|=15)),this.err=0,this.msg="",this.ended=!1,this.chunks=[],this.strm=new zstream,this.strm.avail_out=0;let n=inflate_1$2.inflateInit2(this.strm,e.windowBits);if(n!==Z_OK)throw new Error(messages[n]);if(this.header=new gzheader,inflate_1$2.inflateGetHeader(this.strm,this.header),e.dictionary&&("string"==typeof e.dictionary?e.dictionary=strings.string2buf(e.dictionary):"[object ArrayBuffer]"===toString$2.call(e.dictionary)&&(e.dictionary=new Uint8Array(e.dictionary)),e.raw&&(n=inflate_1$2.inflateSetDictionary(this.strm,e.dictionary),n!==Z_OK)))throw new Error(messages[n])}function inflate$1(t,e){const n=new Inflate$1(e);if(n.push(t),n.err)throw n.msg||messages[n.err];return n.result}function inflateRaw$1(t,e){return(e=e||{}).raw=!0,inflate$1(t,e)}Inflate$1.prototype.push=function(t,e){const n=this.strm,r=this.options.chunkSize,i=this.options.dictionary;let s,a,o;if(this.ended)return!1;for(a=e===~~e?e:!0===e?Z_FINISH:Z_NO_FLUSH,n.input="[object ArrayBuffer]"===toString$2.call(t)?new Uint8Array(t):t,n.next_in=0,n.avail_in=n.input.length;;){for(0===n.avail_out&&(n.output=new Uint8Array(r),n.next_out=0,n.avail_out=r),s=inflate_1$2.inflate(n,a),s===Z_NEED_DICT&&i&&(s=inflate_1$2.inflateSetDictionary(n,i),s===Z_OK?s=inflate_1$2.inflate(n,a):s===Z_DATA_ERROR&&(s=Z_NEED_DICT));n.avail_in>0&&s===Z_STREAM_END&&n.state.wrap>0&&0!==t[n.next_in];)inflate_1$2.inflateReset(n),s=inflate_1$2.inflate(n,a);switch(s){case Z_STREAM_ERROR:case Z_DATA_ERROR:case Z_NEED_DICT:case Z_MEM_ERROR:return this.onEnd(s),this.ended=!0,!1}if(o=n.avail_out,n.next_out&&(0===n.avail_out||s===Z_STREAM_END))if("string"===this.options.to){let t=strings.utf8border(n.output,n.next_out),e=n.next_out-t,i=strings.buf2string(n.output,t);n.next_out=e,n.avail_out=r-e,e&&n.output.set(n.output.subarray(t,t+e),0),this.onData(i)}else this.onData(n.output.length===n.next_out?n.output:n.output.subarray(0,n.next_out));if(s!==Z_OK||0!==o){if(s===Z_STREAM_END)return s=inflate_1$2.inflateEnd(this.strm),this.onEnd(s),this.ended=!0,!0;if(0===n.avail_in)break}}return!0},Inflate$1.prototype.onData=function(t){this.chunks.push(t)},Inflate$1.prototype.onEnd=function(t){t===Z_OK&&(this.result="string"===this.options.to?this.chunks.join(""):common.flattenChunks(this.chunks)),this.chunks=[],this.err=t,this.msg=this.strm.msg};var Inflate_1$1=Inflate$1,inflate_2=inflate$1,inflateRaw_1$1=inflateRaw$1,ungzip$1=inflate$1,constants=constants$2,inflate_1$1={Inflate:Inflate_1$1,inflate:inflate_2,inflateRaw:inflateRaw_1$1,ungzip:ungzip$1,constants};const{Deflate,deflate,deflateRaw,gzip}=deflate_1$1,{Inflate,inflate,inflateRaw,ungzip}=inflate_1$1;var Deflate_1=Deflate,deflate_1=deflate,deflateRaw_1=deflateRaw,gzip_1=gzip,Inflate_1=Inflate,inflate_1=inflate,inflateRaw_1=inflateRaw,ungzip_1=ungzip,constants_1=constants$2,pako={Deflate:Deflate_1,deflate:deflate_1,deflateRaw:deflateRaw_1,gzip:gzip_1,Inflate:Inflate_1,inflate:inflate_1,inflateRaw:inflateRaw_1,ungzip:ungzip_1,constants:constants_1};async function request(t,e={}){const{method:n="GET",data:r,headers:i={}}=e,s={method:n,headers:_extends({"Content-Type":"application/json"},i)};if("GET"===n&&r){const e=new URLSearchParams(r).toString();t+=`${t.includes("?")?"&":"?"}${e}`}"GET"!==n&&r&&(s.body=JSON.stringify(r));try{const e=await fetch(t,s);if(!e.ok)throw{status:e.status,statusText:e.statusText,message:`HTTP error! status: ${e.status}`};return e}catch(t){if(t instanceof Error)throw{message:t.message,status:500,statusText:"Client Error"};throw t}}function XMLRequest(t){return new Promise((e,n)=>{var r;const i=new XMLHttpRequest;i.open("GET",t.url),i.responseType="arraybuffer",i.timeout=null!=(r=t.timeout)?r:6e4,i.onload=function(){4===i.readyState&&200===i.status?e([!1,i.response]):n([!0,`HTTP ${i.status} ${i.statusText}`])},i.onerror=function(){n([!0,"network error"])},i.ontimeout=function(){n([!0,`timeout after ${i.timeout}ms`])},i.onabort=function(){n([!0,"aborted"])},i.onprogress=e=>{if(e.lengthComputable){const n=Math.round(e.loaded/e.total*100);t.onProgress(n,e)}},i.send()})}var commonjsGlobal="undefined"!=typeof globalThis?globalThis:"undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof self?self:{};function createCommonjsModule(t){var e={exports:{}};return t(e,e.exports),e.exports}var md5=createCommonjsModule(function(t){!function(e){function n(t,e){var n=(65535&t)+(65535&e);return(t>>16)+(e>>16)+(n>>16)<<16|65535&n}function r(t,e,r,i,s,a){return n((o=n(n(e,t),n(i,a)))<<(l=s)|o>>>32-l,r);var o,l}function i(t,e,n,i,s,a,o){return r(e&n|~e&i,t,e,s,a,o)}function s(t,e,n,i,s,a,o){return r(e&i|n&~i,t,e,s,a,o)}function a(t,e,n,i,s,a,o){return r(e^n^i,t,e,s,a,o)}function o(t,e,n,i,s,a,o){return r(n^(e|~i),t,e,s,a,o)}function l(t,e){var r,l,c,d,h;t[e>>5]|=128<<e%32,t[14+(e+64>>>9<<4)]=e;var u=1732584193,p=-271733879,f=-1732584194,m=271733878;for(r=0;r<t.length;r+=16)l=u,c=p,d=f,h=m,u=i(u,p,f,m,t[r],7,-680876936),m=i(m,u,p,f,t[r+1],12,-389564586),f=i(f,m,u,p,t[r+2],17,606105819),p=i(p,f,m,u,t[r+3],22,-1044525330),u=i(u,p,f,m,t[r+4],7,-176418897),m=i(m,u,p,f,t[r+5],12,1200080426),f=i(f,m,u,p,t[r+6],17,-1473231341),p=i(p,f,m,u,t[r+7],22,-45705983),u=i(u,p,f,m,t[r+8],7,1770035416),m=i(m,u,p,f,t[r+9],12,-1958414417),f=i(f,m,u,p,t[r+10],17,-42063),p=i(p,f,m,u,t[r+11],22,-1990404162),u=i(u,p,f,m,t[r+12],7,1804603682),m=i(m,u,p,f,t[r+13],12,-40341101),f=i(f,m,u,p,t[r+14],17,-1502002290),u=s(u,p=i(p,f,m,u,t[r+15],22,1236535329),f,m,t[r+1],5,-165796510),m=s(m,u,p,f,t[r+6],9,-1069501632),f=s(f,m,u,p,t[r+11],14,643717713),p=s(p,f,m,u,t[r],20,-373897302),u=s(u,p,f,m,t[r+5],5,-701558691),m=s(m,u,p,f,t[r+10],9,38016083),f=s(f,m,u,p,t[r+15],14,-660478335),p=s(p,f,m,u,t[r+4],20,-405537848),u=s(u,p,f,m,t[r+9],5,568446438),m=s(m,u,p,f,t[r+14],9,-1019803690),f=s(f,m,u,p,t[r+3],14,-187363961),p=s(p,f,m,u,t[r+8],20,1163531501),u=s(u,p,f,m,t[r+13],5,-1444681467),m=s(m,u,p,f,t[r+2],9,-51403784),f=s(f,m,u,p,t[r+7],14,1735328473),u=a(u,p=s(p,f,m,u,t[r+12],20,-1926607734),f,m,t[r+5],4,-378558),m=a(m,u,p,f,t[r+8],11,-2022574463),f=a(f,m,u,p,t[r+11],16,1839030562),p=a(p,f,m,u,t[r+14],23,-35309556),u=a(u,p,f,m,t[r+1],4,-1530992060),m=a(m,u,p,f,t[r+4],11,1272893353),f=a(f,m,u,p,t[r+7],16,-155497632),p=a(p,f,m,u,t[r+10],23,-1094730640),u=a(u,p,f,m,t[r+13],4,681279174),m=a(m,u,p,f,t[r],11,-358537222),f=a(f,m,u,p,t[r+3],16,-722521979),p=a(p,f,m,u,t[r+6],23,76029189),u=a(u,p,f,m,t[r+9],4,-640364487),m=a(m,u,p,f,t[r+12],11,-421815835),f=a(f,m,u,p,t[r+15],16,530742520),u=o(u,p=a(p,f,m,u,t[r+2],23,-995338651),f,m,t[r],6,-198630844),m=o(m,u,p,f,t[r+7],10,1126891415),f=o(f,m,u,p,t[r+14],15,-1416354905),p=o(p,f,m,u,t[r+5],21,-57434055),u=o(u,p,f,m,t[r+12],6,1700485571),m=o(m,u,p,f,t[r+3],10,-1894986606),f=o(f,m,u,p,t[r+10],15,-1051523),p=o(p,f,m,u,t[r+1],21,-2054922799),u=o(u,p,f,m,t[r+8],6,1873313359),m=o(m,u,p,f,t[r+15],10,-30611744),f=o(f,m,u,p,t[r+6],15,-1560198380),p=o(p,f,m,u,t[r+13],21,1309151649),u=o(u,p,f,m,t[r+4],6,-145523070),m=o(m,u,p,f,t[r+11],10,-1120210379),f=o(f,m,u,p,t[r+2],15,718787259),p=o(p,f,m,u,t[r+9],21,-343485551),u=n(u,l),p=n(p,c),f=n(f,d),m=n(m,h);return[u,p,f,m]}function c(t){var e,n="",r=32*t.length;for(e=0;e<r;e+=8)n+=String.fromCharCode(t[e>>5]>>>e%32&255);return n}function d(t){var e,n=[];for(n[(t.length>>2)-1]=void 0,e=0;e<n.length;e+=1)n[e]=0;var r=8*t.length;for(e=0;e<r;e+=8)n[e>>5]|=(255&t.charCodeAt(e/8))<<e%32;return n}function h(t){var e,n,r="0123456789abcdef",i="";for(n=0;n<t.length;n+=1)e=t.charCodeAt(n),i+=r.charAt(e>>>4&15)+r.charAt(15&e);return i}function u(t){return unescape(encodeURIComponent(t))}function p(t){return function(t){return c(l(d(t),8*t.length))}(u(t))}function f(t,e){return function(t,e){var n,r,i=d(t),s=[],a=[];for(s[15]=a[15]=void 0,i.length>16&&(i=l(i,8*t.length)),n=0;n<16;n+=1)s[n]=909522486^i[n],a[n]=1549556828^i[n];return r=l(s.concat(d(e)),512+8*e.length),c(l(a.concat(r),640))}(u(t),u(e))}function m(t,e,n){return e?n?f(e,t):h(f(e,t)):n?p(t):h(p(t))}t.exports?t.exports=m:e.md5=m}(commonjsGlobal)});function encodeWithMd5(t){return md5(t)}function generateRequestId(t){const e=`${(()=>{try{return generateFingerprint()}catch(t){return"unknown"}})()}|${Date.now()}|${t}`;return md5(e)}function escapeNonAsciiForPythonJson(t){return t.replace(/[^\u0000-\u007E]/g,t=>`\\u${t.charCodeAt(0).toString(16).padStart(4,"0")}`)}function compareUnicodeCodePoints(t,e){const n=Array.from(t,t=>t.codePointAt(0)),r=Array.from(e,t=>t.codePointAt(0)),i=Math.min(n.length,r.length);for(let t=0;t<i;t+=1)if(n[t]!==r[t])return n[t]-r[t];return n.length-r.length}function parseUrlWithoutBase(t){try{const e=new URL(t);return{isAbsolute:!0,pathWithQuery:e.pathname+e.search}}catch(e){let n=t.trim();return n.startsWith("/")||(n="/"+n),{isAbsolute:!1,pathWithQuery:n}}}function headersNeedSign(t,e,n,r,i){const s={},a=Math.floor(Date.now()/1e3),o=parseUrlWithoutBase(r).pathWithQuery,l=function t(e){if(null==e)return e;if(Array.isArray(e))return e.map(e=>t(e));if("object"!=typeof e)return e;const n=Object.keys(e).sort(compareUnicodeCodePoints),r={};for(const i of n)r[i]=t(e[i]);return r}(i),c=escapeNonAsciiForPythonJson(JSON.stringify(l)).replace(/ /g,""),d=encodeWithMd5(`${o.toLowerCase()}${n.toLowerCase()}${c}${e}${a}`);return s["X-APP-ID"]=t,s["X-TOKEN"]=d,s["X-TIMESTAMP"]=a.toString(),{headers:s,data:l}}class CacheManager{constructor(t){this.cacheServer=t}getVideo(t){return`${this.cacheServer}/get_video?url=${encodeURIComponent(t)}`}}class ResourceManager{constructor(t){this.TAG="[ResourceManager]",this.offlineIdle=[],this.offlineCache=new Map,this.networkInfos=[],this.bg=null,this.destroyed=!1,this.progress=0,this.videoCache=new Map,this.maxCacheSize=10485760,this.maxCacheEntries=20,this.cacheCleanupInterval=null,this.isProcessingVideo=!1,this.startSessionTimer=null,this.audioOnlyMode=!1,this.downloadingVideos=new Map,this.first_load=!0,this.options=t,this.audioOnlyMode=t.audioOnlyMode||!1,this.sdk=t.sdkInstance,this.mouthShapeLib={char_info:null},this.config=t.config||{},this.resource_pack={enable_robot_expression:!1,body_data_dir:"",face_ani_char_data:"",face_ani_preload_data:"",interpolate_joints:[[4,3]]},t.cacheServer&&(this.cacheServer=new CacheManager(t.cacheServer)),this.startCacheCleanup()}getAppInfo(){return{appId:this.options.appId}}getBackgroundImage(){return new Promise((t,e)=>{try{var n,r;const e=new Image;if(e.crossOrigin="anonymous",e.src=(null==(n=this.config)?void 0:n.background_img)||"",null==(r=this.config)||!r.background_img)return;e.onload=()=>{this.bg=e,t()},e.onerror=n=>{this.sdk.onMessage({code:EErrorCode.BACKGROUND_IMAGE_LOAD_ERROR,message:"Error: 背景图片加载失败",e:{error:n,img:e}}),this.bg=null,t()}}catch(t){}})}getIsEnableRobotExpression(){var t;return null==(t=this.resource_pack)?void 0:t.enable_robot_expression}getBackgroundImageElement(){return this.bg}getConfig(){return this.config}async load(t){var e;this.destroyed=!1,null==t||t(this.progress),this.startSessionTimer&&(clearInterval(this.startSessionTimer),this.startSessionTimer=null),this.startSessionTimer=setInterval(()=>{if(this.destroyed||this.progress>=14)return clearInterval(this.startSessionTimer),void(this.startSessionTimer=null);this.progress+=1,null==t||t(this.progress)},100),this.session_request_id=generateRequestId(this.options.appId);const n=await this.startSession(),r=n;return null!=r&&r.session_id&&(this.session_id=r.session_id),this.destroyed?(window.avatarSDKLogger.warn(this.TAG,"sdk destroyed during load, aborting after startSession"),await this.stopSession("destroy_during_init"),null):n?(clearInterval(this.startSessionTimer),this.startSessionTimer=null,this.progress=15,null==t||t(this.progress),this.resource_pack=r.resource_pack,this.config=r.config,this.offlineIdle=(null==(e=r.resource_pack)?void 0:e.offline_idle)||[],!this.resource_pack||(this.audioOnlyMode||await this.loadMouthShapeLib(t),this.getBackgroundImage(),null!=(i=this.mouthShapeLib)&&i.char_info||null==r||null==(s=r.resource_pack)||!s.face_ani_char_data||this.audioOnlyMode)?r:null):(clearInterval(this.startSessionTimer),this.startSessionTimer=null,null);var i,s}async startSession(){try{const n=await this._startSession();var t,e;return null!=n&&n.verify_res&&(null==(t=(e=this.options).onStartSessionWarning)||t.call(e,n.verify_res)),n}catch(t){return null}}_startSession(){var t;if(!navigator.onLine)return this.sdk.onMessage({code:EErrorCode.NETWORK_BREAK,message:"没有网络,请联网后重试~"}),null;const e=`${this.options.gatewayServer}`,n=_extends({request_id:this.session_request_id,tag:this.options.tag,gateway_type:this.options.gateway_type},void 0!==this.options.asr_id?{asr_id:this.options.asr_id}:{},void 0!==this.options.llm_id?{llm_id:this.options.llm_id}:{},void 0!==this.options.session_speak_req_id?{session_speak_req_id:this.options.session_speak_req_id}:{},null!=(t=this.options.sessionRequestData)?t:{},{config:_extends({},this.config,{framedata_proto_version:2,walk_version:3})}),{headers:r,data:i}=headersNeedSign(this.options.appId,this.options.appSecret,"POST",e,n);return request(e,{method:"POST",data:i,headers:_extends({},r,this.options.headers)}).then(t=>t.json()).then(t=>{var e;return null!=t&&null!=(e=t.data)&&e.resource_pack?null==t?void 0:t.data:(this.sdk.onMessage({code:null==t?void 0:t.error_code,message:`Error: ${null==t?void 0:t.error_code}, ${null==t?void 0:t.error_reason}`}),null)}).catch(t=>(this.sdk.onMessage({code:EErrorCode.START_SESSION_ERROR,message:"Error: 启动会话失败",e:t}),null))}async stopSession(t){try{const e=`${this.options.gatewayServer}`;if(!this.session_id&&!this.session_request_id)return;const n={stop_reason:t};this.session_id&&(n.session_id=this.session_id),this.session_request_id&&(n.request_id=this.session_request_id);const{headers:r,data:i}=headersNeedSign(this.options.appId,this.options.appSecret,"DELETE",e,n),s=await request(e,{method:"DELETE",data:i,headers:_extends({},r,this.options.headers)});return await s.json()}catch(t){this.sdk.onMessage({code:EErrorCode.STOP_SESSION_ERROR,message:"Error: 停止会话失败",e:t})}}async loadMouthShapeLib(t){try{var e,n;if(!this.resource_pack.face_ani_char_data)return this.progress+=60,void(null==t||t(this.progress));let s=null,a=null,o="",l=0,c=0,d=0,h=0;const u=()=>(e,n)=>{var r,i;if(!n)return;const s=performance.now(),a=s-d,o=n.loaded-h;null==(r=(i=this.options).onNetworkInfo)||r.call(i,{rtt:a,downlink:a>0&&o>0?8*o/(a/1e3)/1e6:0,networkStatus:navigator.onLine}),h=n.loaded,d=s,null==t||t(this.progress+.65*e)};try{const t=`${this.resource_pack.face_ani_char_data}.gz`;o=t,c=performance.now(),d=c,h=0;const[,e]=await XMLRequest({url:t,onProgress:u()}),n=pako.ungzip(new Uint8Array(e)),r=new ArrayBuffer(n.byteLength);new Uint8Array(r).set(n),s=r}catch(t){a=t,s=null}if(!s)try{const t=this.resource_pack.face_ani_char_data;o=t,c=performance.now(),d=c,h=0;const[,e]=await XMLRequest({url:t,onProgress:u()});s=e}catch(t){var r,i;return this.first_load&&(this.first_load=!1,this.stopSession("char_bin_load_error")),void(null==(r=(i=this.sdk).onMessage)||r.call(i,{code:EErrorCode.FACE_BIN_LOAD_ERROR,message:"表情数据加载失败(.gz 和 bin 均失败)",e:{gzError:a,binError:t}}))}const p=performance.now()-c;null==(e=(n=this.options).onNetworkInfo)||e.call(n,{rtt:p,downlink:l>0&&p>0?8*l/(p/1e3)/1e6:0,networkStatus:navigator.onLine}),this.mouthShapeLib={char_info:new IBRAnimationGeneratorCharInfo_NN(s,{blendshapeMap:this.resource_pack.blendshape_map||[]})},this.progress+=65,null==t||t(this.progress)}catch(t){var s,a;this.first_load&&(this.first_load=!1,this.stopSession("char_bin_load_error")),null==(s=(a=this.sdk).onMessage)||s.call(a,{code:EErrorCode.FACE_BIN_LOAD_ERROR,message:"表情数据加载失败,请检查文件是否正确",e:t})}}getMouthShapeLib(){return this.mouthShapeLib}getVideoUrl(t){if(!this.resource_pack.body_data_dir)return"";if(!t)return this.first_load&&(this.first_load=!1,this.stopSession("no_video_name_error")),this.sdk.onMessage({code:EErrorCode.INVALID_BODY_NAME,message:"Error: 视频地址获取失败",e:t}),"";const e=`${this.resource_pack.body_data_dir}${t}.mp4`;var n;return this.cacheServer?null==(n=this.cacheServer)?void 0:n.getVideo(e):e}async preloadVideo(t){if(!this.videoCache.has(t))return this.loadVideo(t)}async loadVideo(t){const e=this.videoCache.get(t)||this.offlineCache.get(t);if(e){if(e.data)return this.updateCacheAccess(t),e.data;window.avatarSDKLogger.warn(this.TAG,`发现无效缓存条目: ${t},正在删除`),this.videoCache.delete(t)}if(this.downloadingVideos.has(t))try{return await this.downloadingVideos.get(t)}catch(e){throw this.downloadingVideos.delete(t),window.avatarSDKLogger.warn(this.TAG,`${t} 视频下载失败,从下载列表移除`),e}this.isProcessingVideo=!0;const n=this.downloadVideo(t);this.downloadingVideos.set(t,n);try{return await n}finally{this.downloadingVideos.delete(t),this.isProcessingVideo=!1}}async downloadVideo(t){const e=this.getVideoUrl(t);if(e)try{const{response:n,arrayBuffer:r}=await this._fetchVideo(e);return n.ok?(this.addToCache(t,r),r):(this.first_load&&(this.first_load=!1,this.stopSession("load_video_error")),void this.sdk.onMessage({code:EErrorCode.VIDEO_DOWNLOAD_ERROR,message:`Error: ${t} 视频下载失败`,e:{name:t,url:e,res:n}}))}catch(n){return void this.sdk.onMessage({code:EErrorCode.VIDEO_DOWNLOAD_ERROR,message:`Error: ${t} 视频下载失败`,e:{name:t,url:e,error:n}})}}async _fetchVideo(t){if(this.networkInfos.length>=4){var e,n;const t=this.networkInfos.reduce((t,e)=>t+e.rtt,0)/this.networkInfos.length,r=this.networkInfos.reduce((t,e)=>t+e.downlink,0)/this.networkInfos.length;null==(e=(n=this.options).onNetworkInfo)||e.call(n,{rtt:t,downlink:r,networkStatus:navigator.onLine}),this.networkInfos.length=0}const r=performance.now(),i=await fetch(t),s=parseFloat(i.headers.get("Content-Length")||"0"),a=performance.now(),o=await i.arrayBuffer(),l=a-r,c={rtt:l,downlink:8*s/(l/1e3*1e6),networkStatus:navigator.onLine};return this.networkInfos.push(c),{response:i,arrayBuffer:o}}addToCache(t,e){const n=Date.now();let r=0;for(const t of this.videoCache.values())r+=t.data.byteLength;if(r+e.byteLength>this.maxCacheSize||this.videoCache.size>=this.maxCacheEntries){this.cleanupCache(),r=0;for(const t of this.videoCache.values())r+=t.data.byteLength;if(r+e.byteLength>this.maxCacheSize&&e.byteLength>.5*this.maxCacheSize)return void window.avatarSDKLogger.warn(this.TAG,`视频文件过大(${(e.byteLength/1024/1024).toFixed(2)}MB),跳过缓存: ${t}`);if(r+e.byteLength>this.maxCacheSize){const t=.5*this.maxCacheSize,e=Array.from(this.videoCache.entries()).sort((t,e)=>t[1].lastAccessTime-e[1].lastAccessTime);for(const[n,i]of e){if(r<=t)break;this.videoCache.delete(n),r-=i.data.byteLength}}}this.videoCache.set(t,{data:e,lastAccessTime:n,accessCount:1})}startCacheCleanup(){this.cacheCleanupInterval=setInterval(()=>{this.cleanupCache()},3e5)}cleanupCache(){if(this.isProcessingVideo)return;const t=Date.now(),e=Array.from(this.videoCache.entries()).sort((t,e)=>t[1].lastAccessTime-e[1].lastAccessTime);let n=0;const r=[];for(const[t,e]of this.videoCache.entries())n+=e.data.byteLength;for(const[i,s]of e)t-s.lastAccessTime>6e5&&(r.push(i),n-=s.data.byteLength);if(n>this.maxCacheSize||this.videoCache.size>this.maxCacheEntries)for(const[t,i]of e)if(!r.includes(t)&&(r.push(t),n-=i.data.byteLength,this.videoCache.size-r.length<=2||n<=.8*this.maxCacheSize&&this.videoCache.size-r.length<=.8*this.maxCacheEntries))break;for(const t of r)this.videoCache.delete(t)}updateCacheAccess(t){const e=this.videoCache.get(t);e&&(e.lastAccessTime=Date.now(),e.accessCount++)}clearAllCache(){this.videoCache.clear()}_getOfflineIdle(){return this.offlineIdle}_getSessionId(){return this.session_id||""}async _reload(){var t;const e=await this.startSession();if(!e)return null;const n=e;return this.session_id=null==n?void 0:n.session_id,this.destroyed?(await this.stopSession("destroy_during_reload"),null):(this.resource_pack=n.resource_pack,this.config=n.config,this.offlineIdle=(null==(t=n.resource_pack)?void 0:t.offline_idle)||[],this.resource_pack&&this.getBackgroundImage(),n)}async _setOfflineCache(){if(!this.offlineIdle||0===this.offlineIdle.length)return;this.offlineCache.clear();const t=this.offlineIdle.map(t=>t.n);for(const e of t)try{await this._runOfflineCache(e)}catch(t){}}async _runOfflineCache(t){const e=this.getVideoUrl(t);if(e)return this._fetchVideo(e).then(({arrayBuffer:e})=>{this.offlineCache.set(t,{data:e})})}destroy(){this.destroyed=!0,this.cacheCleanupInterval&&(clearInterval(this.cacheCleanupInterval),this.cacheCleanupInterval=null),this.clearAllCache(),this.downloadingVideos.clear(),this.bg&&(this.bg=null),this.progress=0,this.session_id=void 0,this.session_request_id=void 0}}var msgpack_min=createCommonjsModule(function(t,e){t.exports=function(t){var e={};function n(r){if(e[r])return e[r].exports;var i=e[r]={i:r,l:!1,exports:{}};return t[r].call(i.exports,i,i.exports,n),i.l=!0,i.exports}return n.m=t,n.c=e,n.d=function(t,e,r){n.o(t,e)||Object.defineProperty(t,e,{enumerable:!0,get:r})},n.r=function(t){"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(t,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(t,"__esModule",{value:!0})},n.t=function(t,e){if(1&e&&(t=n(t)),8&e)return t;if(4&e&&"object"==typeof t&&t&&t.__esModule)return t;var r=Object.create(null);if(n.r(r),Object.defineProperty(r,"default",{enumerable:!0,value:t}),2&e&&"string"!=typeof t)for(var i in t)n.d(r,i,function(e){return t[e]}.bind(null,i));return r},n.n=function(t){var e=t&&t.__esModule?function(){return t.default}:function(){return t};return n.d(e,"a",e),e},n.o=function(t,e){return Object.prototype.hasOwnProperty.call(t,e)},n.p="",n(n.s=0)}([function(t,e,n){n.r(e),n.d(e,"encode",function(){return R}),n.d(e,"decode",function(){return z}),n.d(e,"decodeAsync",function(){return K}),n.d(e,"decodeArrayStream",function(){return X}),n.d(e,"decodeStream",function(){return q}),n.d(e,"Decoder",function(){return M}),n.d(e,"Encoder",function(){return x}),n.d(e,"ExtensionCodec",function(){return b}),n.d(e,"ExtData",function(){return p}),n.d(e,"EXT_TIMESTAMP",function(){return _}),n.d(e,"encodeDateToTimeSpec",function(){return y}),n.d(e,"encodeTimeSpecToTimestamp",function(){return g}),n.d(e,"decodeTimestampToTimeSpec",function(){return A}),n.d(e,"encodeTimestampExtension",function(){return S}),n.d(e,"decodeTimestampExtension",function(){return v});var r=function(t,e){var n="function"==typeof Symbol&&t[Symbol.iterator];if(!n)return t;var r,i,s=n.call(t),a=[];try{for(;(void 0===e||e-- >0)&&!(r=s.next()).done;)a.push(r.value)}catch(t){i={error:t}}finally{try{r&&!r.done&&(n=s.return)&&n.call(s)}finally{if(i)throw i.error}}return a},i=function(){for(var t=[],e=0;e<arguments.length;e++)t=t.concat(r(arguments[e]));return t},s="undefined"!=typeof process&&"undefined"!=typeof TextEncoder&&"undefined"!=typeof TextDecoder;function a(t){for(var e=t.length,n=0,r=0;r<e;){var i=t.charCodeAt(r++);if(4294967168&i)if(4294965248&i){if(i>=55296&&i<=56319&&r<e){var s=t.charCodeAt(r);56320==(64512&s)&&(++r,i=((1023&i)<<10)+(1023&s)+65536)}n+=4294901760&i?4:3}else n+=2;else n++}return n}var o=s?new TextEncoder:void 0,l="undefined"!=typeof process?200:0,c=(null==o?void 0:o.encodeInto)?function(t,e,n){o.encodeInto(t,e.subarray(n))}:function(t,e,n){e.set(o.encode(t),n)};function d(t,e,n){for(var r=e,s=r+n,a=[],o="";r<s;){var l=t[r++];if(128&l)if(192==(224&l)){var c=63&t[r++];a.push((31&l)<<6|c)}else if(224==(240&l)){c=63&t[r++];var d=63&t[r++];a.push((31&l)<<12|c<<6|d)}else if(240==(248&l)){var h=(7&l)<<18|(c=63&t[r++])<<12|(d=63&t[r++])<<6|63&t[r++];h>65535&&(a.push((h-=65536)>>>10&1023|55296),h=56320|1023&h),a.push(h)}else a.push(l);else a.push(l);a.length>=4096&&(o+=String.fromCharCode.apply(String,i(a)),a.length=0)}return a.length>0&&(o+=String.fromCharCode.apply(String,i(a))),o}var h=s?new TextDecoder:null,u="undefined"!=typeof process?200:0,p=function(t,e){this.type=t,this.data=e};function f(t,e,n){var r=Math.floor(n/4294967296),i=n;t.setUint32(e,r),t.setUint32(e+4,i)}function m(t,e){return 4294967296*t.getInt32(e)+t.getUint32(e+4)}var _=-1;function g(t){var e,n=t.sec,r=t.nsec;if(n>=0&&r>=0&&n<=17179869183){if(0===r&&n<=4294967295){var i=new Uint8Array(4);return(e=new DataView(i.buffer)).setUint32(0,n),i}var s=n/4294967296,a=4294967295&n;return i=new Uint8Array(8),(e=new DataView(i.buffer)).setUint32(0,r<<2|3&s),e.setUint32(4,a),i}return i=new Uint8Array(12),(e=new DataView(i.buffer)).setUint32(0,r),f(e,4,n),i}function y(t){var e=t.getTime(),n=Math.floor(e/1e3),r=1e6*(e-1e3*n),i=Math.floor(r/1e9);return{sec:n+i,nsec:r-1e9*i}}function S(t){return t instanceof Date?g(y(t)):null}function A(t){var e=new DataView(t.buffer,t.byteOffset,t.byteLength);switch(t.byteLength){case 4:return{sec:e.getUint32(0),nsec:0};case 8:var n=e.getUint32(0);return{sec:4294967296*(3&n)+e.getUint32(4),nsec:n>>>2};case 12:return{sec:m(e,4),nsec:e.getUint32(0)};default:throw new Error("Unrecognized data size for timestamp: "+t.length)}}function v(t){var e=A(t);return new Date(1e3*e.sec+e.nsec/1e6)}var E={type:_,encode:S,decode:v},b=function(){function t(){this.builtInEncoders=[],this.builtInDecoders=[],this.encoders=[],this.decoders=[],this.register(E)}return t.prototype.register=function(t){var e=t.type,n=t.encode,r=t.decode;if(e>=0)this.encoders[e]=n,this.decoders[e]=r;else{var i=1+e;this.builtInEncoders[i]=n,this.builtInDecoders[i]=r}},t.prototype.tryToEncode=function(t,e){for(var n=0;n<this.builtInEncoders.length;n++)if(null!=(r=this.builtInEncoders[n])&&null!=(i=r(t,e)))return new p(-1-n,i);for(n=0;n<this.encoders.length;n++){var r,i;if(null!=(r=this.encoders[n])&&null!=(i=r(t,e)))return new p(n,i)}return t instanceof p?t:null},t.prototype.decode=function(t,e,n){var r=e<0?this.builtInDecoders[-1-e]:this.decoders[e];return r?r(t,e,n):new p(e,t)},t.defaultCodec=new t,t}();function T(t){return t instanceof Uint8Array?t:ArrayBuffer.isView(t)?new Uint8Array(t.buffer,t.byteOffset,t.byteLength):t instanceof ArrayBuffer?new Uint8Array(t):Uint8Array.from(t)}var w=function(t){var e="function"==typeof Symbol&&Symbol.iterator,n=e&&t[e],r=0;if(n)return n.call(t);if(t&&"number"==typeof t.length)return{next:function(){return t&&r>=t.length&&(t=void 0),{value:t&&t[r++],done:!t}}};throw new TypeError(e?"Object is not iterable.":"Symbol.iterator is not defined.")},x=function(){function t(t,e,n,r,i,s,a){void 0===t&&(t=b.defaultCodec),void 0===n&&(n=100),void 0===r&&(r=2048),void 0===i&&(i=!1),void 0===s&&(s=!1),void 0===a&&(a=!1),this.extensionCodec=t,this.context=e,this.maxDepth=n,this.initialBufferSize=r,this.sortKeys=i,this.forceFloat32=s,this.ignoreUndefined=a,this.pos=0,this.view=new DataView(new ArrayBuffer(this.initialBufferSize)),this.bytes=new Uint8Array(this.view.buffer)}return t.prototype.encode=function(t,e){if(e>this.maxDepth)throw new Error("Too deep objects in depth "+e);null==t?this.encodeNil():"boolean"==typeof t?this.encodeBoolean(t):"number"==typeof t?this.encodeNumber(t):"string"==typeof t?this.encodeString(t):this.encodeObject(t,e)},t.prototype.getUint8Array=function(){return this.bytes.subarray(0,this.pos)},t.prototype.ensureBufferSizeToWrite=function(t){var e=this.pos+t;this.view.byteLength<e&&this.resizeBuffer(2*e)},t.prototype.resizeBuffer=function(t){var e=new ArrayBuffer(t),n=new Uint8Array(e),r=new DataView(e);n.set(this.bytes),this.view=r,this.bytes=n},t.prototype.encodeNil=function(){this.writeU8(192)},t.prototype.encodeBoolean=function(t){this.writeU8(!1===t?194:195)},t.prototype.encodeNumber=function(t){Number.isSafeInteger(t)?t>=0?t<128?this.writeU8(t):t<256?(this.writeU8(204),this.writeU8(t)):t<65536?(this.writeU8(205),this.writeU16(t)):t<4294967296?(this.writeU8(206),this.writeU32(t)):(this.writeU8(207),this.writeU64(t)):t>=-32?this.writeU8(224|t+32):t>=-128?(this.writeU8(208),this.writeI8(t)):t>=-32768?(this.writeU8(209),this.writeI16(t)):t>=-2147483648?(this.writeU8(210),this.writeI32(t)):(this.writeU8(211),this.writeI64(t)):this.forceFloat32?(this.writeU8(202),this.writeF32(t)):(this.writeU8(203),this.writeF64(t))},t.prototype.writeStringHeader=function(t){if(t<32)this.writeU8(160+t);else if(t<256)this.writeU8(217),this.writeU8(t);else if(t<65536)this.writeU8(218),this.writeU16(t);else{if(!(t<4294967296))throw new Error("Too long string: "+t+" bytes in UTF-8");this.writeU8(219),this.writeU32(t)}},t.prototype.encodeString=function(t){if(s&&t.length>l){var e=a(t);this.ensureBufferSizeToWrite(5+e),this.writeStringHeader(e),c(t,this.bytes,this.pos),this.pos+=e}else e=a(t),this.ensureBufferSizeToWrite(5+e),this.writeStringHeader(e),function(t,e,n){for(var r=t.length,i=n,s=0;s<r;){var a=t.charCodeAt(s++);if(4294967168&a){if(4294965248&a){if(a>=55296&&a<=56319&&s<r){var o=t.charCodeAt(s);56320==(64512&o)&&(++s,a=((1023&a)<<10)+(1023&o)+65536)}4294901760&a?(e[i++]=a>>18&7|240,e[i++]=a>>12&63|128,e[i++]=a>>6&63|128):(e[i++]=a>>12&15|224,e[i++]=a>>6&63|128)}else e[i++]=a>>6&31|192;e[i++]=63&a|128}else e[i++]=a}}(t,this.bytes,this.pos),this.pos+=e},t.prototype.encodeObject=function(t,e){var n=this.extensionCodec.tryToEncode(t,this.context);if(null!=n)this.encodeExtension(n);else if(Array.isArray(t))this.encodeArray(t,e);else if(ArrayBuffer.isView(t))this.encodeBinary(t);else{if("object"!=typeof t)throw new Error("Unrecognized object: "+Object.prototype.toString.apply(t));this.encodeMap(t,e)}},t.prototype.encodeBinary=function(t){var e=t.byteLength;if(e<256)this.writeU8(196),this.writeU8(e);else if(e<65536)this.writeU8(197),this.writeU16(e);else{if(!(e<4294967296))throw new Error("Too large binary: "+e);this.writeU8(198),this.writeU32(e)}var n=T(t);this.writeU8a(n)},t.prototype.encodeArray=function(t,e){var n,r,i=t.length;if(i<16)this.writeU8(144+i);else if(i<65536)this.writeU8(220),this.writeU16(i);else{if(!(i<4294967296))throw new Error("Too large array: "+i);this.writeU8(221),this.writeU32(i)}try{for(var s=w(t),a=s.next();!a.done;a=s.next())this.encode(a.value,e+1)}catch(t){n={error:t}}finally{try{a&&!a.done&&(r=s.return)&&r.call(s)}finally{if(n)throw n.error}}},t.prototype.countWithoutUndefined=function(t,e){var n,r,i=0;try{for(var s=w(e),a=s.next();!a.done;a=s.next())void 0!==t[a.value]&&i++}catch(t){n={error:t}}finally{try{a&&!a.done&&(r=s.return)&&r.call(s)}finally{if(n)throw n.error}}return i},t.prototype.encodeMap=function(t,e){var n,r,i=Object.keys(t);this.sortKeys&&i.sort();var s=this.ignoreUndefined?this.countWithoutUndefined(t,i):i.length;if(s<16)this.writeU8(128+s);else if(s<65536)this.writeU8(222),this.writeU16(s);else{if(!(s<4294967296))throw new Error("Too large map object: "+s);this.writeU8(223),this.writeU32(s)}try{for(var a=w(i),o=a.next();!o.done;o=a.next()){var l=o.value,c=t[l];this.ignoreUndefined&&void 0===c||(this.encodeString(l),this.encode(c,e+1))}}catch(t){n={error:t}}finally{try{o&&!o.done&&(r=a.return)&&r.call(a)}finally{if(n)throw n.error}}},t.prototype.encodeExtension=function(t){var e=t.data.length;if(1===e)this.writeU8(212);else if(2===e)this.writeU8(213);else if(4===e)this.writeU8(214);else if(8===e)this.writeU8(215);else if(16===e)this.writeU8(216);else if(e<256)this.writeU8(199),this.writeU8(e);else if(e<65536)this.writeU8(200),this.writeU16(e);else{if(!(e<4294967296))throw new Error("Too large extension object: "+e);this.writeU8(201),this.writeU32(e)}this.writeI8(t.type),this.writeU8a(t.data)},t.prototype.writeU8=function(t){this.ensureBufferSizeToWrite(1),this.view.setUint8(this.pos,t),this.pos++},t.prototype.writeU8a=function(t){var e=t.length;this.ensureBufferSizeToWrite(e),this.bytes.set(t,this.pos),this.pos+=e},t.prototype.writeI8=function(t){this.ensureBufferSizeToWrite(1),this.view.setInt8(this.pos,t),this.pos++},t.prototype.writeU16=function(t){this.ensureBufferSizeToWrite(2),this.view.setUint16(this.pos,t),this.pos+=2},t.prototype.writeI16=function(t){this.ensureBufferSizeToWrite(2),this.view.setInt16(this.pos,t),this.pos+=2},t.prototype.writeU32=function(t){this.ensureBufferSizeToWrite(4),this.view.setUint32(this.pos,t),this.pos+=4},t.prototype.writeI32=function(t){this.ensureBufferSizeToWrite(4),this.view.setInt32(this.pos,t),this.pos+=4},t.prototype.writeF32=function(t){this.ensureBufferSizeToWrite(4),this.view.setFloat32(this.pos,t),this.pos+=4},t.prototype.writeF64=function(t){this.ensureBufferSizeToWrite(8),this.view.setFloat64(this.pos,t),this.pos+=8},t.prototype.writeU64=function(t){this.ensureBufferSizeToWrite(8),function(t,e,n){var r=n;t.setUint32(e,n/4294967296),t.setUint32(e+4,r)}(this.view,this.pos,t),this.pos+=8},t.prototype.writeI64=function(t){this.ensureBufferSizeToWrite(8),f(this.view,this.pos,t),this.pos+=8},t}(),I={};function R(t,e){void 0===e&&(e=I);var n=new x(e.extensionCodec,e.context,e.maxDepth,e.initialBufferSize,e.sortKeys,e.forceFloat32,e.ignoreUndefined);return n.encode(t,1),n.getUint8Array()}function C(t){return(t<0?"-":"")+"0x"+Math.abs(t).toString(16).padStart(2,"0")}var B=function(){function t(t,e){void 0===t&&(t=16),void 0===e&&(e=16),this.maxKeyLength=t,this.maxLengthPerKey=e,this.caches=[];for(var n=0;n<this.maxKeyLength;n++)this.caches.push([])}return t.prototype.canBeCached=function(t){return t>0&&t<=this.maxKeyLength},t.prototype.get=function(t,e,n){var r=this.caches[n-1],i=r.length;t:for(var s=0;s<i;s++){for(var a=r[s],o=a.bytes,l=0;l<n;l++)if(o[l]!==t[e+l])continue t;return a.value}return null},t.prototype.store=function(t,e){var n=this.caches[t.length-1],r={bytes:t,value:e};n.length>=this.maxLengthPerKey?n[Math.random()*n.length|0]=r:n.push(r)},t.prototype.decode=function(t,e,n){var r=this.get(t,e,n);if(null!=r)return r;var i=d(t,e,n),s=Uint8Array.prototype.slice.call(t,e,e+n);return this.store(s,i),i},t}(),D=function(t,e){var n,r,i,s,a={label:0,sent:function(){if(1&i[0])throw i[1];return i[1]},trys:[],ops:[]};return s={next:o(0),throw:o(1),return:o(2)},"function"==typeof Symbol&&(s[Symbol.iterator]=function(){return this}),s;function o(s){return function(o){return function(s){if(n)throw new TypeError("Generator is already executing.");for(;a;)try{if(n=1,r&&(i=2&s[0]?r.return:s[0]?r.throw||((i=r.return)&&i.call(r),0):r.next)&&!(i=i.call(r,s[1])).done)return i;switch(r=0,i&&(s=[2&s[0],i.value]),s[0]){case 0:case 1:i=s;break;case 4:return a.label++,{value:s[1],done:!1};case 5:a.label++,r=s[1],s=[0];continue;case 7:s=a.ops.pop(),a.trys.pop();continue;default:if(!((i=(i=a.trys).length>0&&i[i.length-1])||6!==s[0]&&2!==s[0])){a=0;continue}if(3===s[0]&&(!i||s[1]>i[0]&&s[1]<i[3])){a.label=s[1];break}if(6===s[0]&&a.label<i[1]){a.label=i[1],i=s;break}if(i&&a.label<i[2]){a.label=i[2],a.ops.push(s);break}i[2]&&a.ops.pop(),a.trys.pop();continue}s=e.call(t,a)}catch(t){s=[6,t],r=0}finally{n=i=0}if(5&s[0])throw s[1];return{value:s[0]?s[1]:void 0,done:!0}}([s,o])}}},P=function(t){if(!Symbol.asyncIterator)throw new TypeError("Symbol.asyncIterator is not defined.");var e,n=t[Symbol.asyncIterator];return n?n.call(t):(t="function"==typeof __values?__values(t):t[Symbol.iterator](),e={},r("next"),r("throw"),r("return"),e[Symbol.asyncIterator]=function(){return this},e);function r(n){e[n]=t[n]&&function(e){return new Promise(function(r,i){!function(t,e,n,r){Promise.resolve(r).then(function(e){t({value:e,done:n})},e)}(r,i,(e=t[n](e)).done,e.value)})}}},k=function(t){return this instanceof k?(this.v=t,this):new k(t)},O=new DataView(new ArrayBuffer(0)),U=new Uint8Array(O.buffer),N=function(){try{O.getInt8(0)}catch(t){return t.constructor}throw new Error("never reached")}(),L=new N("Insufficient data"),F=new B,M=function(){function t(t,e,n,r,i,s,a,o){void 0===t&&(t=b.defaultCodec),void 0===n&&(n=4294967295),void 0===r&&(r=4294967295),void 0===i&&(i=4294967295),void 0===s&&(s=4294967295),void 0===a&&(a=4294967295),void 0===o&&(o=F),this.extensionCodec=t,this.context=e,this.maxStrLength=n,this.maxBinLength=r,this.maxArrayLength=i,this.maxMapLength=s,this.maxExtLength=a,this.cachedKeyDecoder=o,this.totalPos=0,this.pos=0,this.view=O,this.bytes=U,this.headByte=-1,this.stack=[]}return t.prototype.setBuffer=function(t){this.bytes=T(t),this.view=function(t){if(t instanceof ArrayBuffer)return new DataView(t);var e=T(t);return new DataView(e.buffer,e.byteOffset,e.byteLength)}(this.bytes),this.pos=0},t.prototype.appendBuffer=function(t){if(-1!==this.headByte||this.hasRemaining()){var e=this.bytes.subarray(this.pos),n=T(t),r=new Uint8Array(e.length+n.length);r.set(e),r.set(n,e.length),this.setBuffer(r)}else this.setBuffer(t)},t.prototype.hasRemaining=function(t){return void 0===t&&(t=1),this.view.byteLength-this.pos>=t},t.prototype.createNoExtraBytesError=function(t){return new RangeError("Extra "+(this.view.byteLength-this.pos)+" byte(s) found at buffer["+t+"]")},t.prototype.decodeSingleSync=function(){var t=this.decodeSync();if(this.hasRemaining())throw this.createNoExtraBytesError(this.pos);return t},t.prototype.decodeSingleAsync=function(t){var e,n,r,i;return function(t,e,n,r){return new(n||(n=Promise))(function(e,i){function s(t){try{o(r.next(t))}catch(t){i(t)}}function a(t){try{o(r.throw(t))}catch(t){i(t)}}function o(t){var r;t.done?e(t.value):(r=t.value,r instanceof n?r:new n(function(t){t(r)})).then(s,a)}o((r=r.apply(t,[])).next())})}(this,0,void 0,function(){var s,a,o,l,c,d,h,u;return D(this,function(p){switch(p.label){case 0:s=!1,p.label=1;case 1:p.trys.push([1,6,7,12]),e=P(t),p.label=2;case 2:return[4,e.next()];case 3:if((n=p.sent()).done)return[3,5];if(o=n.value,s)throw this.createNoExtraBytesError(this.totalPos);this.appendBuffer(o);try{a=this.decodeSync(),s=!0}catch(t){if(!(t instanceof N))throw t}this.totalPos+=this.pos,p.label=4;case 4:return[3,2];case 5:return[3,12];case 6:return l=p.sent(),r={error:l},[3,12];case 7:return p.trys.push([7,,10,11]),n&&!n.done&&(i=e.return)?[4,i.call(e)]:[3,9];case 8:p.sent(),p.label=9;case 9:return[3,11];case 10:if(r)throw r.error;return[7];case 11:return[7];case 12:if(s){if(this.hasRemaining())throw this.createNoExtraBytesError(this.totalPos);return[2,a]}throw d=(c=this).headByte,h=c.pos,u=c.totalPos,new RangeError("Insufficient data in parcing "+C(d)+" at "+u+" ("+h+" in the current buffer)")}})})},t.prototype.decodeArrayStream=function(t){return this.decodeMultiAsync(t,!0)},t.prototype.decodeStream=function(t){return this.decodeMultiAsync(t,!1)},t.prototype.decodeMultiAsync=function(t,e){return function(t,e,n){if(!Symbol.asyncIterator)throw new TypeError("Symbol.asyncIterator is not defined.");var r,i=n.apply(t,e||[]),s=[];return r={},a("next"),a("throw"),a("return"),r[Symbol.asyncIterator]=function(){return this},r;function a(t){i[t]&&(r[t]=function(e){return new Promise(function(n,r){s.push([t,e,n,r])>1||o(t,e)})})}function o(t,e){try{(n=i[t](e)).value instanceof k?Promise.resolve(n.value.v).then(l,c):d(s[0][2],n)}catch(t){d(s[0][3],t)}var n}function l(t){o("next",t)}function c(t){o("throw",t)}function d(t,e){t(e),s.shift(),s.length&&o(s[0][0],s[0][1])}}(this,arguments,function(){var n,r,i,s,a,o,l,c,d;return D(this,function(h){switch(h.label){case 0:n=e,r=-1,h.label=1;case 1:h.trys.push([1,13,14,19]),i=P(t),h.label=2;case 2:return[4,k(i.next())];case 3:if((s=h.sent()).done)return[3,12];if(a=s.value,e&&0===r)throw this.createNoExtraBytesError(this.totalPos);this.appendBuffer(a),n&&(r=this.readArraySize(),n=!1,this.complete()),h.label=4;case 4:h.trys.push([4,9,,10]),h.label=5;case 5:return[4,k(this.decodeSync())];case 6:return[4,h.sent()];case 7:return h.sent(),0==--r?[3,8]:[3,5];case 8:return[3,10];case 9:if(!((o=h.sent())instanceof N))throw o;return[3,10];case 10:this.totalPos+=this.pos,h.label=11;case 11:return[3,2];case 12:return[3,19];case 13:return l=h.sent(),c={error:l},[3,19];case 14:return h.trys.push([14,,17,18]),s&&!s.done&&(d=i.return)?[4,k(d.call(i))]:[3,16];case 15:h.sent(),h.label=16;case 16:return[3,18];case 17:if(c)throw c.error;return[7];case 18:return[7];case 19:return[2]}})})},t.prototype.decodeSync=function(){t:for(;;){var t=this.readHeadByte(),e=void 0;if(t>=224)e=t-256;else if(t<192)if(t<128)e=t;else if(t<144){if(0!=(r=t-128)){this.pushMapState(r),this.complete();continue t}e={}}else if(t<160){if(0!=(r=t-144)){this.pushArrayState(r),this.complete();continue t}e=[]}else{var n=t-160;e=this.decodeUtf8String(n,0)}else if(192===t)e=null;else if(194===t)e=!1;else if(195===t)e=!0;else if(202===t)e=this.readF32();else if(203===t)e=this.readF64();else if(204===t)e=this.readU8();else if(205===t)e=this.readU16();else if(206===t)e=this.readU32();else if(207===t)e=this.readU64();else if(208===t)e=this.readI8();else if(209===t)e=this.readI16();else if(210===t)e=this.readI32();else if(211===t)e=this.readI64();else if(217===t)n=this.lookU8(),e=this.decodeUtf8String(n,1);else if(218===t)n=this.lookU16(),e=this.decodeUtf8String(n,2);else if(219===t)n=this.lookU32(),e=this.decodeUtf8String(n,4);else if(220===t){if(0!==(r=this.readU16())){this.pushArrayState(r),this.complete();continue t}e=[]}else if(221===t){if(0!==(r=this.readU32())){this.pushArrayState(r),this.complete();continue t}e=[]}else if(222===t){if(0!==(r=this.readU16())){this.pushMapState(r),this.complete();continue t}e={}}else if(223===t){if(0!==(r=this.readU32())){this.pushMapState(r),this.complete();continue t}e={}}else if(196===t){var r=this.lookU8();e=this.decodeBinary(r,1)}else if(197===t)r=this.lookU16(),e=this.decodeBinary(r,2);else if(198===t)r=this.lookU32(),e=this.decodeBinary(r,4);else if(212===t)e=this.decodeExtension(1,0);else if(213===t)e=this.decodeExtension(2,0);else if(214===t)e=this.decodeExtension(4,0);else if(215===t)e=this.decodeExtension(8,0);else if(216===t)e=this.decodeExtension(16,0);else if(199===t)r=this.lookU8(),e=this.decodeExtension(r,1);else if(200===t)r=this.lookU16(),e=this.decodeExtension(r,2);else{if(201!==t)throw new Error("Unrecognized type byte: "+C(t));r=this.lookU32(),e=this.decodeExtension(r,4)}this.complete();for(var i=this.stack;i.length>0;){var s=i[i.length-1];if(0===s.type){if(s.array[s.position]=e,s.position++,s.position!==s.size)continue t;i.pop(),e=s.array}else{if(1===s.type){if("string"!=(a=typeof e)&&"number"!==a)throw new Error("The type of key must be string or number but "+typeof e);s.key=e,s.type=2;continue t}if(s.map[s.key]=e,s.readCount++,s.readCount!==s.size){s.key=null,s.type=1;continue t}i.pop(),e=s.map}}return e}var a},t.prototype.readHeadByte=function(){return-1===this.headByte&&(this.headByte=this.readU8()),this.headByte},t.prototype.complete=function(){this.headByte=-1},t.prototype.readArraySize=function(){var t=this.readHeadByte();switch(t){case 220:return this.readU16();case 221:return this.readU32();default:if(t<160)return t-144;throw new Error("Unrecognized array type byte: "+C(t))}},t.prototype.pushMapState=function(t){if(t>this.maxMapLength)throw new Error("Max length exceeded: map length ("+t+") > maxMapLengthLength ("+this.maxMapLength+")");this.stack.push({type:1,size:t,key:null,readCount:0,map:{}})},t.prototype.pushArrayState=function(t){if(t>this.maxArrayLength)throw new Error("Max length exceeded: array length ("+t+") > maxArrayLength ("+this.maxArrayLength+")");this.stack.push({type:0,size:t,array:new Array(t),position:0})},t.prototype.decodeUtf8String=function(t,e){var n;if(t>this.maxStrLength)throw new Error("Max length exceeded: UTF-8 byte length ("+t+") > maxStrLength ("+this.maxStrLength+")");if(this.bytes.byteLength<this.pos+e+t)throw L;var r,i=this.pos+e;return r=this.stateIsMapKey()&&(null===(n=this.cachedKeyDecoder)||void 0===n?void 0:n.canBeCached(t))?this.cachedKeyDecoder.decode(this.bytes,i,t):s&&t>u?function(t,e,n){var r=t.subarray(e,e+n);return h.decode(r)}(this.bytes,i,t):d(this.bytes,i,t),this.pos+=e+t,r},t.prototype.stateIsMapKey=function(){return this.stack.length>0&&1===this.stack[this.stack.length-1].type},t.prototype.decodeBinary=function(t,e){if(t>this.maxBinLength)throw new Error("Max length exceeded: bin length ("+t+") > maxBinLength ("+this.maxBinLength+")");if(!this.hasRemaining(t+e))throw L;var n=this.pos+e,r=this.bytes.subarray(n,n+t);return this.pos+=e+t,r},t.prototype.decodeExtension=function(t,e){if(t>this.maxExtLength)throw new Error("Max length exceeded: ext length ("+t+") > maxExtLength ("+this.maxExtLength+")");var n=this.view.getInt8(this.pos+e),r=this.decodeBinary(t,e+1);return this.extensionCodec.decode(r,n,this.context)},t.prototype.lookU8=function(){return this.view.getUint8(this.pos)},t.prototype.lookU16=function(){return this.view.getUint16(this.pos)},t.prototype.lookU32=function(){return this.view.getUint32(this.pos)},t.prototype.readU8=function(){var t=this.view.getUint8(this.pos);return this.pos++,t},t.prototype.readI8=function(){var t=this.view.getInt8(this.pos);return this.pos++,t},t.prototype.readU16=function(){var t=this.view.getUint16(this.pos);return this.pos+=2,t},t.prototype.readI16=function(){var t=this.view.getInt16(this.pos);return this.pos+=2,t},t.prototype.readU32=function(){var t=this.view.getUint32(this.pos);return this.pos+=4,t},t.prototype.readI32=function(){var t=this.view.getInt32(this.pos);return this.pos+=4,t},t.prototype.readU64=function(){var t,e,n=4294967296*(t=this.view).getUint32(e=this.pos)+t.getUint32(e+4);return this.pos+=8,n},t.prototype.readI64=function(){var t=m(this.view,this.pos);return this.pos+=8,t},t.prototype.readF32=function(){var t=this.view.getFloat32(this.pos);return this.pos+=4,t},t.prototype.readF64=function(){var t=this.view.getFloat64(this.pos);return this.pos+=8,t},t}(),G={};function z(t,e){void 0===e&&(e=G);var n=new M(e.extensionCodec,e.context,e.maxStrLength,e.maxBinLength,e.maxArrayLength,e.maxMapLength,e.maxExtLength);return n.setBuffer(t),n.decodeSingleSync()}var W=function(t,e){var n,r,i,s,a={label:0,sent:function(){if(1&i[0])throw i[1];return i[1]},trys:[],ops:[]};return s={next:o(0),throw:o(1),return:o(2)},"function"==typeof Symbol&&(s[Symbol.iterator]=function(){return this}),s;function o(s){return function(o){return function(s){if(n)throw new TypeError("Generator is already executing.");for(;a;)try{if(n=1,r&&(i=2&s[0]?r.return:s[0]?r.throw||((i=r.return)&&i.call(r),0):r.next)&&!(i=i.call(r,s[1])).done)return i;switch(r=0,i&&(s=[2&s[0],i.value]),s[0]){case 0:case 1:i=s;break;case 4:return a.label++,{value:s[1],done:!1};case 5:a.label++,r=s[1],s=[0];continue;case 7:s=a.ops.pop(),a.trys.pop();continue;default:if(!((i=(i=a.trys).length>0&&i[i.length-1])||6!==s[0]&&2!==s[0])){a=0;continue}if(3===s[0]&&(!i||s[1]>i[0]&&s[1]<i[3])){a.label=s[1];break}if(6===s[0]&&a.label<i[1]){a.label=i[1],i=s;break}if(i&&a.label<i[2]){a.label=i[2],a.ops.push(s);break}i[2]&&a.ops.pop(),a.trys.pop();continue}s=e.call(t,a)}catch(t){s=[6,t],r=0}finally{n=i=0}if(5&s[0])throw s[1];return{value:s[0]?s[1]:void 0,done:!0}}([s,o])}}},H=function(t){return this instanceof H?(this.v=t,this):new H(t)},$=function(t,e,n){if(!Symbol.asyncIterator)throw new TypeError("Symbol.asyncIterator is not defined.");var r,i=n.apply(t,e||[]),s=[];return r={},a("next"),a("throw"),a("return"),r[Symbol.asyncIterator]=function(){return this},r;function a(t){i[t]&&(r[t]=function(e){return new Promise(function(n,r){s.push([t,e,n,r])>1||o(t,e)})})}function o(t,e){try{(n=i[t](e)).value instanceof H?Promise.resolve(n.value.v).then(l,c):d(s[0][2],n)}catch(t){d(s[0][3],t)}var n}function l(t){o("next",t)}function c(t){o("throw",t)}function d(t,e){t(e),s.shift(),s.length&&o(s[0][0],s[0][1])}};function j(t){return null!=t[Symbol.asyncIterator]?t:function(t){return $(this,arguments,function(){var e,n,r;return W(this,function(i){switch(i.label){case 0:e=t.getReader(),i.label=1;case 1:i.trys.push([1,,9,10]),i.label=2;case 2:return[4,H(e.read())];case 3:return n=i.sent(),r=n.value,n.done?[4,H(void 0)]:[3,5];case 4:return[2,i.sent()];case 5:return function(t){if(null==t)throw new Error("Assertion Failure: value must not be null nor undefined")}(r),[4,H(r)];case 6:return[4,i.sent()];case 7:return i.sent(),[3,2];case 8:return[3,10];case 9:return e.releaseLock(),[7];case 10:return[2]}})})}(t)}var V=function(t,e,n,r){return new(n||(n=Promise))(function(i,s){function a(t){try{l(r.next(t))}catch(t){s(t)}}function o(t){try{l(r.throw(t))}catch(t){s(t)}}function l(t){var e;t.done?i(t.value):(e=t.value,e instanceof n?e:new n(function(t){t(e)})).then(a,o)}l((r=r.apply(t,e||[])).next())})},Y=function(t,e){var n,r,i,s,a={label:0,sent:function(){if(1&i[0])throw i[1];return i[1]},trys:[],ops:[]};return s={next:o(0),throw:o(1),return:o(2)},"function"==typeof Symbol&&(s[Symbol.iterator]=function(){return this}),s;function o(s){return function(o){return function(s){if(n)throw new TypeError("Generator is already executing.");for(;a;)try{if(n=1,r&&(i=2&s[0]?r.return:s[0]?r.throw||((i=r.return)&&i.call(r),0):r.next)&&!(i=i.call(r,s[1])).done)return i;switch(r=0,i&&(s=[2&s[0],i.value]),s[0]){case 0:case 1:i=s;break;case 4:return a.label++,{value:s[1],done:!1};case 5:a.label++,r=s[1],s=[0];continue;case 7:s=a.ops.pop(),a.trys.pop();continue;default:if(!((i=(i=a.trys).length>0&&i[i.length-1])||6!==s[0]&&2!==s[0])){a=0;continue}if(3===s[0]&&(!i||s[1]>i[0]&&s[1]<i[3])){a.label=s[1];break}if(6===s[0]&&a.label<i[1]){a.label=i[1],i=s;break}if(i&&a.label<i[2]){a.label=i[2],a.ops.push(s);break}i[2]&&a.ops.pop(),a.trys.pop();continue}s=e.call(t,a)}catch(t){s=[6,t],r=0}finally{n=i=0}if(5&s[0])throw s[1];return{value:s[0]?s[1]:void 0,done:!0}}([s,o])}}};function K(t,e){return void 0===e&&(e=G),V(this,void 0,void 0,function(){var n;return Y(this,function(r){return n=j(t),[2,new M(e.extensionCodec,e.context,e.maxStrLength,e.maxBinLength,e.maxArrayLength,e.maxMapLength,e.maxExtLength).decodeSingleAsync(n)]})})}function X(t,e){void 0===e&&(e=G);var n=j(t);return new M(e.extensionCodec,e.context,e.maxStrLength,e.maxBinLength,e.maxArrayLength,e.maxMapLength,e.maxExtLength).decodeArrayStream(n)}function q(t,e){void 0===e&&(e=G);var n=j(t);return new M(e.extensionCodec,e.context,e.maxStrLength,e.maxBinLength,e.maxArrayLength,e.maxMapLength,e.maxExtLength).decodeStream(n)}}])});const PACKET_TYPES=Object.create(null);PACKET_TYPES.open="0",PACKET_TYPES.close="1",PACKET_TYPES.ping="2",PACKET_TYPES.pong="3",PACKET_TYPES.message="4",PACKET_TYPES.upgrade="5",PACKET_TYPES.noop="6";const PACKET_TYPES_REVERSE=Object.create(null);Object.keys(PACKET_TYPES).forEach(t=>{PACKET_TYPES_REVERSE[PACKET_TYPES[t]]=t});const ERROR_PACKET={type:"error",data:"parser error"},withNativeBlob$1="function"==typeof Blob||"undefined"!=typeof Blob&&"[object BlobConstructor]"===Object.prototype.toString.call(Blob),withNativeArrayBuffer$2="function"==typeof ArrayBuffer,isView$1=t=>"function"==typeof ArrayBuffer.isView?ArrayBuffer.isView(t):t&&t.buffer instanceof ArrayBuffer,encodePacket=({type:t,data:e},n,r)=>withNativeBlob$1&&e instanceof Blob?n?r(e):encodeBlobAsBase64(e,r):withNativeArrayBuffer$2&&(e instanceof ArrayBuffer||isView$1(e))?n?r(e):encodeBlobAsBase64(new Blob([e]),r):r(PACKET_TYPES[t]+(e||"")),encodeBlobAsBase64=(t,e)=>{const n=new FileReader;return n.onload=function(){const t=n.result.split(",")[1];e("b"+(t||""))},n.readAsDataURL(t)};function toArray(t){return t instanceof Uint8Array?t:t instanceof ArrayBuffer?new Uint8Array(t):new Uint8Array(t.buffer,t.byteOffset,t.byteLength)}let TEXT_ENCODER;function encodePacketToBinary(t,e){return withNativeBlob$1&&t.data instanceof Blob?t.data.arrayBuffer().then(toArray).then(e):withNativeArrayBuffer$2&&(t.data instanceof ArrayBuffer||isView$1(t.data))?e(toArray(t.data)):void encodePacket(t,!1,t=>{TEXT_ENCODER||(TEXT_ENCODER=new TextEncoder),e(TEXT_ENCODER.encode(t))})}const chars="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",lookup$1="undefined"==typeof Uint8Array?[]:new Uint8Array(256);for(let t=0;t<chars.length;t++)lookup$1[chars.charCodeAt(t)]=t;const decode$1=t=>{let e,n,r,i,s,a=.75*t.length,o=t.length,l=0;"="===t[t.length-1]&&(a--,"="===t[t.length-2]&&a--);const c=new ArrayBuffer(a),d=new Uint8Array(c);for(e=0;e<o;e+=4)n=lookup$1[t.charCodeAt(e)],r=lookup$1[t.charCodeAt(e+1)],i=lookup$1[t.charCodeAt(e+2)],s=lookup$1[t.charCodeAt(e+3)],d[l++]=n<<2|r>>4,d[l++]=(15&r)<<4|i>>2,d[l++]=(3&i)<<6|63&s;return c},withNativeArrayBuffer$1="function"==typeof ArrayBuffer,decodePacket=(t,e)=>{if("string"!=typeof t)return{type:"message",data:mapBinary(t,e)};const n=t.charAt(0);return"b"===n?{type:"message",data:decodeBase64Packet(t.substring(1),e)}:PACKET_TYPES_REVERSE[n]?t.length>1?{type:PACKET_TYPES_REVERSE[n],data:t.substring(1)}:{type:PACKET_TYPES_REVERSE[n]}:ERROR_PACKET},decodeBase64Packet=(t,e)=>{if(withNativeArrayBuffer$1){const n=decode$1(t);return mapBinary(n,e)}return{base64:!0,data:t}},mapBinary=(t,e)=>"blob"===e?t instanceof Blob?t:new Blob([t]):t instanceof ArrayBuffer?t:t.buffer,SEPARATOR=String.fromCharCode(30),encodePayload=(t,e)=>{const n=t.length,r=new Array(n);let i=0;t.forEach((t,s)=>{encodePacket(t,!1,t=>{r[s]=t,++i===n&&e(r.join(SEPARATOR))})})},decodePayload=(t,e)=>{const n=t.split(SEPARATOR),r=[];for(let t=0;t<n.length;t++){const i=decodePacket(n[t],e);if(r.push(i),"error"===i.type)break}return r};function createPacketEncoderStream(){return new TransformStream({transform(t,e){encodePacketToBinary(t,n=>{const r=n.length;let i;if(r<126)i=new Uint8Array(1),new DataView(i.buffer).setUint8(0,r);else if(r<65536){i=new Uint8Array(3);const t=new DataView(i.buffer);t.setUint8(0,126),t.setUint16(1,r)}else{i=new Uint8Array(9);const t=new DataView(i.buffer);t.setUint8(0,127),t.setBigUint64(1,BigInt(r))}t.data&&"string"!=typeof t.data&&(i[0]|=128),e.enqueue(i),e.enqueue(n)})}})}let TEXT_DECODER;function totalLength(t){return t.reduce((t,e)=>t+e.length,0)}function concatChunks(t,e){if(t[0].length===e)return t.shift();const n=new Uint8Array(e);let r=0;for(let i=0;i<e;i++)n[i]=t[0][r++],r===t[0].length&&(t.shift(),r=0);return t.length&&r<t[0].length&&(t[0]=t[0].slice(r)),n}function createPacketDecoderStream(t,e){TEXT_DECODER||(TEXT_DECODER=new TextDecoder);const n=[];let r=0,i=-1,s=!1;return new TransformStream({transform(a,o){for(n.push(a);;){if(0===r){if(totalLength(n)<1)break;const t=concatChunks(n,1);s=!(128&~t[0]),i=127&t[0],r=i<126?3:126===i?1:2}else if(1===r){if(totalLength(n)<2)break;const t=concatChunks(n,2);i=new DataView(t.buffer,t.byteOffset,t.length).getUint16(0),r=3}else if(2===r){if(totalLength(n)<8)break;const t=concatChunks(n,8),e=new DataView(t.buffer,t.byteOffset,t.length),s=e.getUint32(0);if(s>Math.pow(2,21)-1){o.enqueue(ERROR_PACKET);break}i=s*Math.pow(2,32)+e.getUint32(4),r=3}else{if(totalLength(n)<i)break;const t=concatChunks(n,i);o.enqueue(decodePacket(s?t:TEXT_DECODER.decode(t),e)),r=0}if(0===i||i>t){o.enqueue(ERROR_PACKET);break}}}})}const protocol$1=4;function Emitter(t){if(t)return mixin(t)}function mixin(t){for(var e in Emitter.prototype)t[e]=Emitter.prototype[e];return t}Emitter.prototype.on=Emitter.prototype.addEventListener=function(t,e){return this._callbacks=this._callbacks||{},(this._callbacks["$"+t]=this._callbacks["$"+t]||[]).push(e),this},Emitter.prototype.once=function(t,e){function n(){this.off(t,n),e.apply(this,arguments)}return n.fn=e,this.on(t,n),this},Emitter.prototype.off=Emitter.prototype.removeListener=Emitter.prototype.removeAllListeners=Emitter.prototype.removeEventListener=function(t,e){if(this._callbacks=this._callbacks||{},0==arguments.length)return this._callbacks={},this;var n,r=this._callbacks["$"+t];if(!r)return this;if(1==arguments.length)return delete this._callbacks["$"+t],this;for(var i=0;i<r.length;i++)if((n=r[i])===e||n.fn===e){r.splice(i,1);break}return 0===r.length&&delete this._callbacks["$"+t],this},Emitter.prototype.emit=function(t){this._callbacks=this._callbacks||{};for(var e=new Array(arguments.length-1),n=this._callbacks["$"+t],r=1;r<arguments.length;r++)e[r-1]=arguments[r];if(n){r=0;for(var i=(n=n.slice(0)).length;r<i;++r)n[r].apply(this,e)}return this},Emitter.prototype.emitReserved=Emitter.prototype.emit,Emitter.prototype.listeners=function(t){return this._callbacks=this._callbacks||{},this._callbacks["$"+t]||[]},Emitter.prototype.hasListeners=function(t){return!!this.listeners(t).length};const nextTick="function"==typeof Promise&&"function"==typeof Promise.resolve?t=>Promise.resolve().then(t):(t,e)=>e(t,0),globalThisShim="undefined"!=typeof self?self:"undefined"!=typeof window?window:Function("return this")(),defaultBinaryType="arraybuffer";function createCookieJar(){}function pick(t,...e){return e.reduce((e,n)=>(t.hasOwnProperty(n)&&(e[n]=t[n]),e),{})}const NATIVE_SET_TIMEOUT=globalThisShim.setTimeout,NATIVE_CLEAR_TIMEOUT=globalThisShim.clearTimeout;function installTimerFunctions(t,e){e.useNativeTimers?(t.setTimeoutFn=NATIVE_SET_TIMEOUT.bind(globalThisShim),t.clearTimeoutFn=NATIVE_CLEAR_TIMEOUT.bind(globalThisShim)):(t.setTimeoutFn=globalThisShim.setTimeout.bind(globalThisShim),t.clearTimeoutFn=globalThisShim.clearTimeout.bind(globalThisShim))}const BASE64_OVERHEAD=1.33;function byteLength(t){return"string"==typeof t?utf8Length$1(t):Math.ceil((t.byteLength||t.size)*BASE64_OVERHEAD)}function utf8Length$1(t){let e=0,n=0;for(let r=0,i=t.length;r<i;r++)e=t.charCodeAt(r),e<128?n+=1:e<2048?n+=2:e<55296||e>=57344?n+=3:(r++,n+=4);return n}function randomString(){return Date.now().toString(36).substring(3)+Math.random().toString(36).substring(2,5)}function encode(t){let e="";for(let n in t)t.hasOwnProperty(n)&&(e.length&&(e+="&"),e+=encodeURIComponent(n)+"="+encodeURIComponent(t[n]));return e}function decode(t){let e={},n=t.split("&");for(let t=0,r=n.length;t<r;t++){let r=n[t].split("=");e[decodeURIComponent(r[0])]=decodeURIComponent(r[1])}return e}class TransportError extends Error{constructor(t,e,n){super(t),this.description=e,this.context=n,this.type="TransportError"}}class Transport extends Emitter{constructor(t){super(),this.writable=!1,installTimerFunctions(this,t),this.opts=t,this.query=t.query,this.socket=t.socket,this.supportsBinary=!t.forceBase64}onError(t,e,n){return super.emitReserved("error",new TransportError(t,e,n)),this}open(){return this.readyState="opening",this.doOpen(),this}close(){return"opening"!==this.readyState&&"open"!==this.readyState||(this.doClose(),this.onClose()),this}send(t){"open"===this.readyState&&this.write(t)}onOpen(){this.readyState="open",this.writable=!0,super.emitReserved("open")}onData(t){const e=decodePacket(t,this.socket.binaryType);this.onPacket(e)}onPacket(t){super.emitReserved("packet",t)}onClose(t){this.readyState="closed",super.emitReserved("close",t)}pause(t){}createUri(t,e={}){return t+"://"+this._hostname()+this._port()+this.opts.path+this._query(e)}_hostname(){const t=this.opts.hostname;return-1===t.indexOf(":")?t:"["+t+"]"}_port(){return this.opts.port&&(this.opts.secure&&Number(443!==this.opts.port)||!this.opts.secure&&80!==Number(this.opts.port))?":"+this.opts.port:""}_query(t){const e=encode(t);return e.length?"?"+e:""}}class Polling extends Transport{constructor(){super(...arguments),this._polling=!1}get name(){return"polling"}doOpen(){this._poll()}pause(t){this.readyState="pausing";const e=()=>{this.readyState="paused",t()};if(this._polling||!this.writable){let t=0;this._polling&&(t++,this.once("pollComplete",function(){--t||e()})),this.writable||(t++,this.once("drain",function(){--t||e()}))}else e()}_poll(){this._polling=!0,this.doPoll(),this.emitReserved("poll")}onData(t){decodePayload(t,this.socket.binaryType).forEach(t=>{if("opening"===this.readyState&&"open"===t.type&&this.onOpen(),"close"===t.type)return this.onClose({description:"transport closed by the server"}),!1;this.onPacket(t)}),"closed"!==this.readyState&&(this._polling=!1,this.emitReserved("pollComplete"),"open"===this.readyState&&this._poll())}doClose(){const t=()=>{this.write([{type:"close"}])};"open"===this.readyState?t():this.once("open",t)}write(t){this.writable=!1,encodePayload(t,t=>{this.doWrite(t,()=>{this.writable=!0,this.emitReserved("drain")})})}uri(){const t=this.opts.secure?"https":"http",e=this.query||{};return!1!==this.opts.timestampRequests&&(e[this.opts.timestampParam]=randomString()),this.supportsBinary||e.sid||(e.b64=1),this.createUri(t,e)}}let value=!1;try{value="undefined"!=typeof XMLHttpRequest&&"withCredentials"in new XMLHttpRequest}catch(err){}const hasCORS=value;function empty(){}class BaseXHR extends Polling{constructor(t){if(super(t),"undefined"!=typeof location){const e="https:"===location.protocol;let n=location.port;n||(n=e?"443":"80"),this.xd="undefined"!=typeof location&&t.hostname!==location.hostname||n!==t.port}}doWrite(t,e){const n=this.request({method:"POST",data:t});n.on("success",e),n.on("error",(t,e)=>{this.onError("xhr post error",t,e)})}doPoll(){const t=this.request();t.on("data",this.onData.bind(this)),t.on("error",(t,e)=>{this.onError("xhr poll error",t,e)}),this.pollXhr=t}}class Request$1 extends Emitter{constructor(t,e,n){super(),this.createRequest=t,installTimerFunctions(this,n),this._opts=n,this._method=n.method||"GET",this._uri=e,this._data=void 0!==n.data?n.data:null,this._create()}_create(){var t;const e=pick(this._opts,"agent","pfx","key","passphrase","cert","ca","ciphers","rejectUnauthorized","autoUnref");e.xdomain=!!this._opts.xd;const n=this._xhr=this.createRequest(e);try{n.open(this._method,this._uri,!0);try{if(this._opts.extraHeaders){n.setDisableHeaderCheck&&n.setDisableHeaderCheck(!0);for(let t in this._opts.extraHeaders)this._opts.extraHeaders.hasOwnProperty(t)&&n.setRequestHeader(t,this._opts.extraHeaders[t])}}catch(t){}if("POST"===this._method)try{n.setRequestHeader("Content-type","text/plain;charset=UTF-8")}catch(t){}try{n.setRequestHeader("Accept","*/*")}catch(t){}null===(t=this._opts.cookieJar)||void 0===t||t.addCookies(n),"withCredentials"in n&&(n.withCredentials=this._opts.withCredentials),this._opts.requestTimeout&&(n.timeout=this._opts.requestTimeout),n.onreadystatechange=()=>{var t;3===n.readyState&&(null===(t=this._opts.cookieJar)||void 0===t||t.parseCookies(n.getResponseHeader("set-cookie"))),4===n.readyState&&(200===n.status||1223===n.status?this._onLoad():this.setTimeoutFn(()=>{this._onError("number"==typeof n.status?n.status:0)},0))},n.send(this._data)}catch(t){return void this.setTimeoutFn(()=>{this._onError(t)},0)}"undefined"!=typeof document&&(this._index=Request$1.requestsCount++,Request$1.requests[this._index]=this)}_onError(t){this.emitReserved("error",t,this._xhr),this._cleanup(!0)}_cleanup(t){if(null!=this._xhr){if(this._xhr.onreadystatechange=empty,t)try{this._xhr.abort()}catch(t){}"undefined"!=typeof document&&delete Request$1.requests[this._index],this._xhr=null}}_onLoad(){const t=this._xhr.responseText;null!==t&&(this.emitReserved("data",t),this.emitReserved("success"),this._cleanup())}abort(){this._cleanup()}}if(Request$1.requestsCount=0,Request$1.requests={},"undefined"!=typeof document)if("function"==typeof attachEvent)attachEvent("onunload",unloadHandler);else if("function"==typeof addEventListener){const t="onpagehide"in globalThisShim?"pagehide":"unload";addEventListener(t,unloadHandler,!1)}function unloadHandler(){for(let t in Request$1.requests)Request$1.requests.hasOwnProperty(t)&&Request$1.requests[t].abort()}const hasXHR2=function(){const t=newRequest({xdomain:!1});return t&&null!==t.responseType}();class XHR extends BaseXHR{constructor(t){super(t),this.supportsBinary=hasXHR2&&!(t&&t.forceBase64)}request(t={}){return Object.assign(t,{xd:this.xd},this.opts),new Request$1(newRequest,this.uri(),t)}}function newRequest(t){const e=t.xdomain;try{if("undefined"!=typeof XMLHttpRequest&&(!e||hasCORS))return new XMLHttpRequest}catch(t){}if(!e)try{return new(globalThisShim[["Active"].concat("Object").join("X")])("Microsoft.XMLHTTP")}catch(t){}}const isReactNative="undefined"!=typeof navigator&&"string"==typeof navigator.product&&"reactnative"===navigator.product.toLowerCase();class BaseWS extends Transport{get name(){return"websocket"}doOpen(){const t=this.uri(),e=this.opts.protocols,n=isReactNative?{}:pick(this.opts,"agent","perMessageDeflate","pfx","key","passphrase","cert","ca","ciphers","rejectUnauthorized","localAddress","protocolVersion","origin","maxPayload","family","checkServerIdentity");this.opts.extraHeaders&&(n.headers=this.opts.extraHeaders);try{this.ws=this.createSocket(t,e,n)}catch(t){return this.emitReserved("error",t)}this.ws.binaryType=this.socket.binaryType,this.addEventListeners()}addEventListeners(){this.ws.onopen=()=>{this.opts.autoUnref&&this.ws._socket.unref(),this.onOpen()},this.ws.onclose=t=>this.onClose({description:"websocket connection closed",context:t}),this.ws.onmessage=t=>this.onData(t.data),this.ws.onerror=t=>this.onError("websocket error",t)}write(t){this.writable=!1;for(let e=0;e<t.length;e++){const n=t[e],r=e===t.length-1;encodePacket(n,this.supportsBinary,t=>{try{this.doWrite(n,t)}catch(t){}r&&nextTick(()=>{this.writable=!0,this.emitReserved("drain")},this.setTimeoutFn)})}}doClose(){void 0!==this.ws&&(this.ws.onerror=()=>{},this.ws.close(),this.ws=null)}uri(){const t=this.opts.secure?"wss":"ws",e=this.query||{};return this.opts.timestampRequests&&(e[this.opts.timestampParam]=randomString()),this.supportsBinary||(e.b64=1),this.createUri(t,e)}}const WebSocketCtor=globalThisShim.WebSocket||globalThisShim.MozWebSocket;class WS extends BaseWS{createSocket(t,e,n){return isReactNative?new WebSocketCtor(t,e,n):e?new WebSocketCtor(t,e):new WebSocketCtor(t)}doWrite(t,e){this.ws.send(e)}}class WT extends Transport{get name(){return"webtransport"}doOpen(){try{this._transport=new WebTransport(this.createUri("https"),this.opts.transportOptions[this.name])}catch(t){return this.emitReserved("error",t)}this._transport.closed.then(()=>{this.onClose()}).catch(t=>{this.onError("webtransport error",t)}),this._transport.ready.then(()=>{this._transport.createBidirectionalStream().then(t=>{const e=createPacketDecoderStream(Number.MAX_SAFE_INTEGER,this.socket.binaryType),n=t.readable.pipeThrough(e).getReader(),r=createPacketEncoderStream();r.readable.pipeTo(t.writable),this._writer=r.writable.getWriter();const i=()=>{n.read().then(({done:t,value:e})=>{t||(this.onPacket(e),i())}).catch(t=>{})};i();const s={type:"open"};this.query.sid&&(s.data=`{"sid":"${this.query.sid}"}`),this._writer.write(s).then(()=>this.onOpen())})})}write(t){this.writable=!1;for(let e=0;e<t.length;e++){const n=e===t.length-1;this._writer.write(t[e]).then(()=>{n&&nextTick(()=>{this.writable=!0,this.emitReserved("drain")},this.setTimeoutFn)})}}doClose(){var t;null===(t=this._transport)||void 0===t||t.close()}}const transports={websocket:WS,webtransport:WT,polling:XHR},re=/^(?:(?![^:@\/?#]+:[^:@\/]*@)(http|https|ws|wss):\/\/)?((?:(([^:@\/?#]*)(?::([^:@\/?#]*))?)?@)?((?:[a-f0-9]{0,4}:){2,7}[a-f0-9]{0,4}|[^:\/?#]*)(?::(\d*))?)(((\/(?:[^?#](?![^?#\/]*\.[^?#\/.]+(?:[?#]|$)))*\/?)?([^?#\/]*))(?:\?([^#]*))?(?:#(.*))?)/,parts=["source","protocol","authority","userInfo","user","password","host","port","relative","path","directory","file","query","anchor"];function parse(t){if(t.length>8e3)throw"URI too long";const e=t,n=t.indexOf("["),r=t.indexOf("]");-1!=n&&-1!=r&&(t=t.substring(0,n)+t.substring(n,r).replace(/:/g,";")+t.substring(r,t.length));let i=re.exec(t||""),s={},a=14;for(;a--;)s[parts[a]]=i[a]||"";return-1!=n&&-1!=r&&(s.source=e,s.host=s.host.substring(1,s.host.length-1).replace(/;/g,":"),s.authority=s.authority.replace("[","").replace("]","").replace(/;/g,":"),s.ipv6uri=!0),s.pathNames=pathNames(s,s.path),s.queryKey=queryKey(s,s.query),s}function pathNames(t,e){const n=e.replace(/\/{2,9}/g,"/").split("/");return"/"!=e.slice(0,1)&&0!==e.length||n.splice(0,1),"/"==e.slice(-1)&&n.splice(n.length-1,1),n}function queryKey(t,e){const n={};return e.replace(/(?:^|&)([^&=]*)=?([^&]*)/g,function(t,e,r){e&&(n[e]=r)}),n}const withEventListeners="function"==typeof addEventListener&&"function"==typeof removeEventListener,OFFLINE_EVENT_LISTENERS=[];withEventListeners&&addEventListener("offline",()=>{OFFLINE_EVENT_LISTENERS.forEach(t=>t())},!1);class SocketWithoutUpgrade extends Emitter{constructor(t,e){if(super(),this.binaryType=defaultBinaryType,this.writeBuffer=[],this._prevBufferLen=0,this._pingInterval=-1,this._pingTimeout=-1,this._maxPayload=-1,this._pingTimeoutTime=Infinity,t&&"object"==typeof t&&(e=t,t=null),t){const n=parse(t);e.hostname=n.host,e.secure="https"===n.protocol||"wss"===n.protocol,e.port=n.port,n.query&&(e.query=n.query)}else e.host&&(e.hostname=parse(e.host).host);installTimerFunctions(this,e),this.secure=null!=e.secure?e.secure:"undefined"!=typeof location&&"https:"===location.protocol,e.hostname&&!e.port&&(e.port=this.secure?"443":"80"),this.hostname=e.hostname||("undefined"!=typeof location?location.hostname:"localhost"),this.port=e.port||("undefined"!=typeof location&&location.port?location.port:this.secure?"443":"80"),this.transports=[],this._transportsByName={},e.transports.forEach(t=>{const e=t.prototype.name;this.transports.push(e),this._transportsByName[e]=t}),this.opts=Object.assign({path:"/engine.io",agent:!1,withCredentials:!1,upgrade:!0,timestampParam:"t",rememberUpgrade:!1,addTrailingSlash:!0,rejectUnauthorized:!0,perMessageDeflate:{threshold:1024},transportOptions:{},closeOnBeforeunload:!1},e),this.opts.path=this.opts.path.replace(/\/$/,"")+(this.opts.addTrailingSlash?"/":""),"string"==typeof this.opts.query&&(this.opts.query=decode(this.opts.query)),withEventListeners&&(this.opts.closeOnBeforeunload&&(this._beforeunloadEventListener=()=>{this.transport&&(this.transport.removeAllListeners(),this.transport.close())},addEventListener("beforeunload",this._beforeunloadEventListener,!1)),"localhost"!==this.hostname&&(this._offlineEventListener=()=>{this._onClose("transport close",{description:"network connection lost"})},OFFLINE_EVENT_LISTENERS.push(this._offlineEventListener))),this.opts.withCredentials&&(this._cookieJar=createCookieJar()),this._open()}createTransport(t){const e=Object.assign({},this.opts.query);e.EIO=protocol$1,e.transport=t,this.id&&(e.sid=this.id);const n=Object.assign({},this.opts,{query:e,socket:this,hostname:this.hostname,secure:this.secure,port:this.port},this.opts.transportOptions[t]);return new this._transportsByName[t](n)}_open(){if(0===this.transports.length)return void this.setTimeoutFn(()=>{this.emitReserved("error","No transports available")},0);const t=this.opts.rememberUpgrade&&SocketWithoutUpgrade.priorWebsocketSuccess&&-1!==this.transports.indexOf("websocket")?"websocket":this.transports[0];this.readyState="opening";const e=this.createTransport(t);e.open(),this.setTransport(e)}setTransport(t){this.transport&&this.transport.removeAllListeners(),this.transport=t,t.on("drain",this._onDrain.bind(this)).on("packet",this._onPacket.bind(this)).on("error",this._onError.bind(this)).on("close",t=>this._onClose("transport close",t))}onOpen(){this.readyState="open",SocketWithoutUpgrade.priorWebsocketSuccess="websocket"===this.transport.name,this.emitReserved("open"),this.flush()}_onPacket(t){if("opening"===this.readyState||"open"===this.readyState||"closing"===this.readyState)switch(this.emitReserved("packet",t),this.emitReserved("heartbeat"),t.type){case"open":this.onHandshake(JSON.parse(t.data));break;case"ping":this._sendPacket("pong"),this.emitReserved("ping"),this.emitReserved("pong"),this._resetPingTimeout();break;case"error":const e=new Error("server error");e.code=t.data,this._onError(e);break;case"message":this.emitReserved("data",t.data),this.emitReserved("message",t.data)}}onHandshake(t){this.emitReserved("handshake",t),this.id=t.sid,this.transport.query.sid=t.sid,this._pingInterval=t.pingInterval,this._pingTimeout=t.pingTimeout,this._maxPayload=t.maxPayload,this.onOpen(),"closed"!==this.readyState&&this._resetPingTimeout()}_resetPingTimeout(){this.clearTimeoutFn(this._pingTimeoutTimer);const t=this._pingInterval+this._pingTimeout;this._pingTimeoutTime=Date.now()+t,this._pingTimeoutTimer=this.setTimeoutFn(()=>{this._onClose("ping timeout")},t),this.opts.autoUnref&&this._pingTimeoutTimer.unref()}_onDrain(){this.writeBuffer.splice(0,this._prevBufferLen),this._prevBufferLen=0,0===this.writeBuffer.length?this.emitReserved("drain"):this.flush()}flush(){if("closed"!==this.readyState&&this.transport.writable&&!this.upgrading&&this.writeBuffer.length){const t=this._getWritablePackets();this.transport.send(t),this._prevBufferLen=t.length,this.emitReserved("flush")}}_getWritablePackets(){if(!(this._maxPayload&&"polling"===this.transport.name&&this.writeBuffer.length>1))return this.writeBuffer;let t=1;for(let e=0;e<this.writeBuffer.length;e++){const n=this.writeBuffer[e].data;if(n&&(t+=byteLength(n)),e>0&&t>this._maxPayload)return this.writeBuffer.slice(0,e);t+=2}return this.writeBuffer}_hasPingExpired(){if(!this._pingTimeoutTime)return!0;const t=Date.now()>this._pingTimeoutTime;return t&&(this._pingTimeoutTime=0,nextTick(()=>{this._onClose("ping timeout")},this.setTimeoutFn)),t}write(t,e,n){return this._sendPacket("message",t,e,n),this}send(t,e,n){return this._sendPacket("message",t,e,n),this}_sendPacket(t,e,n,r){if("function"==typeof e&&(r=e,e=void 0),"function"==typeof n&&(r=n,n=null),"closing"===this.readyState||"closed"===this.readyState)return;(n=n||{}).compress=!1!==n.compress;const i={type:t,data:e,options:n};this.emitReserved("packetCreate",i),this.writeBuffer.push(i),r&&this.once("flush",r),this.flush()}close(){const t=()=>{this._onClose("forced close"),this.transport.close()},e=()=>{this.off("upgrade",e),this.off("upgradeError",e),t()},n=()=>{this.once("upgrade",e),this.once("upgradeError",e)};return"opening"!==this.readyState&&"open"!==this.readyState||(this.readyState="closing",this.writeBuffer.length?this.once("drain",()=>{this.upgrading?n():t()}):this.upgrading?n():t()),this}_onError(t){if(SocketWithoutUpgrade.priorWebsocketSuccess=!1,this.opts.tryAllTransports&&this.transports.length>1&&"opening"===this.readyState)return this.transports.shift(),this._open();this.emitReserved("error",t),this._onClose("transport error",t)}_onClose(t,e){if("opening"===this.readyState||"open"===this.readyState||"closing"===this.readyState){if(this.clearTimeoutFn(this._pingTimeoutTimer),this.transport.removeAllListeners("close"),this.transport.close(),this.transport.removeAllListeners(),withEventListeners&&(this._beforeunloadEventListener&&removeEventListener("beforeunload",this._beforeunloadEventListener,!1),this._offlineEventListener)){const t=OFFLINE_EVENT_LISTENERS.indexOf(this._offlineEventListener);-1!==t&&OFFLINE_EVENT_LISTENERS.splice(t,1)}this.readyState="closed",this.id=null,this.emitReserved("close",t,e),this.writeBuffer=[],this._prevBufferLen=0}}}SocketWithoutUpgrade.protocol=protocol$1;class SocketWithUpgrade extends SocketWithoutUpgrade{constructor(){super(...arguments),this._upgrades=[]}onOpen(){if(super.onOpen(),"open"===this.readyState&&this.opts.upgrade)for(let t=0;t<this._upgrades.length;t++)this._probe(this._upgrades[t])}_probe(t){let e=this.createTransport(t),n=!1;SocketWithoutUpgrade.priorWebsocketSuccess=!1;const r=()=>{n||(e.send([{type:"ping",data:"probe"}]),e.once("packet",t=>{if(!n)if("pong"===t.type&&"probe"===t.data){if(this.upgrading=!0,this.emitReserved("upgrading",e),!e)return;SocketWithoutUpgrade.priorWebsocketSuccess="websocket"===e.name,this.transport.pause(()=>{n||"closed"!==this.readyState&&(c(),this.setTransport(e),e.send([{type:"upgrade"}]),this.emitReserved("upgrade",e),e=null,this.upgrading=!1,this.flush())})}else{const t=new Error("probe error");t.transport=e.name,this.emitReserved("upgradeError",t)}}))};function i(){n||(n=!0,c(),e.close(),e=null)}const s=t=>{const n=new Error("probe error: "+t);n.transport=e.name,i(),this.emitReserved("upgradeError",n)};function a(){s("transport closed")}function o(){s("socket closed")}function l(t){e&&t.name!==e.name&&i()}const c=()=>{e.removeListener("open",r),e.removeListener("error",s),e.removeListener("close",a),this.off("close",o),this.off("upgrading",l)};e.once("open",r),e.once("error",s),e.once("close",a),this.once("close",o),this.once("upgrading",l),-1!==this._upgrades.indexOf("webtransport")&&"webtransport"!==t?this.setTimeoutFn(()=>{n||e.open()},200):e.open()}onHandshake(t){this._upgrades=this._filterUpgrades(t.upgrades),super.onHandshake(t)}_filterUpgrades(t){const e=[];for(let n=0;n<t.length;n++)~this.transports.indexOf(t[n])&&e.push(t[n]);return e}}class Socket$1 extends SocketWithUpgrade{constructor(t,e={}){const n="object"==typeof t?t:e;(!n.transports||n.transports&&"string"==typeof n.transports[0])&&(n.transports=(n.transports||["polling","websocket","webtransport"]).map(t=>transports[t]).filter(t=>!!t)),super(t,n)}}function url(t,e="",n){let r=t;n=n||"undefined"!=typeof location&&location,null==t&&(t=n.protocol+"//"+n.host),"string"==typeof t&&("/"===t.charAt(0)&&(t="/"===t.charAt(1)?n.protocol+t:n.host+t),/^(https?|wss?):\/\//.test(t)||(t=void 0!==n?n.protocol+"//"+t:"https://"+t),r=parse(t)),r.port||(/^(http|ws)$/.test(r.protocol)?r.port="80":/^(http|ws)s$/.test(r.protocol)&&(r.port="443")),r.path=r.path||"/";const i=-1!==r.host.indexOf(":")?"["+r.host+"]":r.host;return r.id=r.protocol+"://"+i+":"+r.port+e,r.href=r.protocol+"://"+i+(n&&n.port===r.port?"":":"+r.port),r}const withNativeArrayBuffer="function"==typeof ArrayBuffer,isView=t=>"function"==typeof ArrayBuffer.isView?ArrayBuffer.isView(t):t.buffer instanceof ArrayBuffer,toString=Object.prototype.toString,withNativeBlob="function"==typeof Blob||"undefined"!=typeof Blob&&"[object BlobConstructor]"===toString.call(Blob),withNativeFile="function"==typeof File||"undefined"!=typeof File&&"[object FileConstructor]"===toString.call(File);function isBinary(t){return withNativeArrayBuffer&&(t instanceof ArrayBuffer||isView(t))||withNativeBlob&&t instanceof Blob||withNativeFile&&t instanceof File}function hasBinary(t,e){if(!t||"object"!=typeof t)return!1;if(Array.isArray(t)){for(let e=0,n=t.length;e<n;e++)if(hasBinary(t[e]))return!0;return!1}if(isBinary(t))return!0;if(t.toJSON&&"function"==typeof t.toJSON&&1===arguments.length)return hasBinary(t.toJSON(),!0);for(const e in t)if(Object.prototype.hasOwnProperty.call(t,e)&&hasBinary(t[e]))return!0;return!1}function deconstructPacket(t){const e=[],n=t;return n.data=_deconstructPacket(t.data,e),n.attachments=e.length,{packet:n,buffers:e}}function _deconstructPacket(t,e){if(!t)return t;if(isBinary(t)){const n={_placeholder:!0,num:e.length};return e.push(t),n}if(Array.isArray(t)){const n=new Array(t.length);for(let r=0;r<t.length;r++)n[r]=_deconstructPacket(t[r],e);return n}if("object"==typeof t&&!(t instanceof Date)){const n={};for(const r in t)Object.prototype.hasOwnProperty.call(t,r)&&(n[r]=_deconstructPacket(t[r],e));return n}return t}function reconstructPacket(t,e){return t.data=_reconstructPacket(t.data,e),delete t.attachments,t}function _reconstructPacket(t,e){if(!t)return t;if(t&&!0===t._placeholder){if("number"==typeof t.num&&t.num>=0&&t.num<e.length)return e[t.num];throw new Error("illegal attachments")}if(Array.isArray(t))for(let n=0;n<t.length;n++)t[n]=_reconstructPacket(t[n],e);else if("object"==typeof t)for(const n in t)Object.prototype.hasOwnProperty.call(t,n)&&(t[n]=_reconstructPacket(t[n],e));return t}const RESERVED_EVENTS$1=["connect","connect_error","disconnect","disconnecting","newListener","removeListener"],protocol=5;var PacketType;!function(t){t[t.CONNECT=0]="CONNECT",t[t.DISCONNECT=1]="DISCONNECT",t[t.EVENT=2]="EVENT",t[t.ACK=3]="ACK",t[t.CONNECT_ERROR=4]="CONNECT_ERROR",t[t.BINARY_EVENT=5]="BINARY_EVENT",t[t.BINARY_ACK=6]="BINARY_ACK"}(PacketType||(PacketType={}));class Encoder{constructor(t){this.replacer=t}encode(t){return t.type!==PacketType.EVENT&&t.type!==PacketType.ACK||!hasBinary(t)?[this.encodeAsString(t)]:this.encodeAsBinary({type:t.type===PacketType.EVENT?PacketType.BINARY_EVENT:PacketType.BINARY_ACK,nsp:t.nsp,data:t.data,id:t.id})}encodeAsString(t){let e=""+t.type;return t.type!==PacketType.BINARY_EVENT&&t.type!==PacketType.BINARY_ACK||(e+=t.attachments+"-"),t.nsp&&"/"!==t.nsp&&(e+=t.nsp+","),null!=t.id&&(e+=t.id),null!=t.data&&(e+=JSON.stringify(t.data,this.replacer)),e}encodeAsBinary(t){const e=deconstructPacket(t),n=this.encodeAsString(e.packet),r=e.buffers;return r.unshift(n),r}}function isObject(t){return"[object Object]"===Object.prototype.toString.call(t)}class Decoder extends Emitter{constructor(t){super(),this.reviver=t}add(t){let e;if("string"==typeof t){if(this.reconstructor)throw new Error("got plaintext data when reconstructing a packet");e=this.decodeString(t);const n=e.type===PacketType.BINARY_EVENT;n||e.type===PacketType.BINARY_ACK?(e.type=n?PacketType.EVENT:PacketType.ACK,this.reconstructor=new BinaryReconstructor(e),0===e.attachments&&super.emitReserved("decoded",e)):super.emitReserved("decoded",e)}else{if(!isBinary(t)&&!t.base64)throw new Error("Unknown type: "+t);if(!this.reconstructor)throw new Error("got binary data when not reconstructing a packet");e=this.reconstructor.takeBinaryData(t),e&&(this.reconstructor=null,super.emitReserved("decoded",e))}}decodeString(t){let e=0;const n={type:Number(t.charAt(0))};if(void 0===PacketType[n.type])throw new Error("unknown packet type "+n.type);if(n.type===PacketType.BINARY_EVENT||n.type===PacketType.BINARY_ACK){const r=e+1;for(;"-"!==t.charAt(++e)&&e!=t.length;);const i=t.substring(r,e);if(i!=Number(i)||"-"!==t.charAt(e))throw new Error("Illegal attachments");n.attachments=Number(i)}if("/"===t.charAt(e+1)){const r=e+1;for(;++e&&","!==t.charAt(e)&&e!==t.length;);n.nsp=t.substring(r,e)}else n.nsp="/";const r=t.charAt(e+1);if(""!==r&&Number(r)==r){const r=e+1;for(;++e;){const n=t.charAt(e);if(null==n||Number(n)!=n){--e;break}if(e===t.length)break}n.id=Number(t.substring(r,e+1))}if(t.charAt(++e)){const r=this.tryParse(t.substr(e));if(!Decoder.isPayloadValid(n.type,r))throw new Error("invalid payload");n.data=r}return n}tryParse(t){try{return JSON.parse(t,this.reviver)}catch(t){return!1}}static isPayloadValid(t,e){switch(t){case PacketType.CONNECT:return isObject(e);case PacketType.DISCONNECT:return void 0===e;case PacketType.CONNECT_ERROR:return"string"==typeof e||isObject(e);case PacketType.EVENT:case PacketType.BINARY_EVENT:return Array.isArray(e)&&("number"==typeof e[0]||"string"==typeof e[0]&&-1===RESERVED_EVENTS$1.indexOf(e[0]));case PacketType.ACK:case PacketType.BINARY_ACK:return Array.isArray(e)}}destroy(){this.reconstructor&&(this.reconstructor.finishedReconstruction(),this.reconstructor=null)}}class BinaryReconstructor{constructor(t){this.packet=t,this.buffers=[],this.reconPack=t}takeBinaryData(t){if(this.buffers.push(t),this.buffers.length===this.reconPack.attachments){const t=reconstructPacket(this.reconPack,this.buffers);return this.finishedReconstruction(),t}return null}finishedReconstruction(){this.reconPack=null,this.buffers=[]}}var parser={__proto__:null,protocol,get PacketType(){return PacketType},Encoder,Decoder};function on(t,e,n){return t.on(e,n),function(){t.off(e,n)}}const RESERVED_EVENTS=Object.freeze({connect:1,connect_error:1,disconnect:1,disconnecting:1,newListener:1,removeListener:1});class Socket extends Emitter{constructor(t,e,n){super(),this.connected=!1,this.recovered=!1,this.receiveBuffer=[],this.sendBuffer=[],this._queue=[],this._queueSeq=0,this.ids=0,this.acks={},this.flags={},this.io=t,this.nsp=e,n&&n.auth&&(this.auth=n.auth),this._opts=Object.assign({},n),this.io._autoConnect&&this.open()}get disconnected(){return!this.connected}subEvents(){if(this.subs)return;const t=this.io;this.subs=[on(t,"open",this.onopen.bind(this)),on(t,"packet",this.onpacket.bind(this)),on(t,"error",this.onerror.bind(this)),on(t,"close",this.onclose.bind(this))]}get active(){return!!this.subs}connect(){return this.connected||(this.subEvents(),this.io._reconnecting||this.io.open(),"open"===this.io._readyState&&this.onopen()),this}open(){return this.connect()}send(...t){return t.unshift("message"),this.emit.apply(this,t),this}emit(t,...e){var n,r,i;if(RESERVED_EVENTS.hasOwnProperty(t))throw new Error('"'+t.toString()+'" is a reserved event name');if(e.unshift(t),this._opts.retries&&!this.flags.fromQueue&&!this.flags.volatile)return this._addToQueue(e),this;const s={type:PacketType.EVENT,data:e,options:{}};if(s.options.compress=!1!==this.flags.compress,"function"==typeof e[e.length-1]){const t=this.ids++,n=e.pop();this._registerAckCallback(t,n),s.id=t}const a=null===(r=null===(n=this.io.engine)||void 0===n?void 0:n.transport)||void 0===r?void 0:r.writable,o=this.connected&&!(null===(i=this.io.engine)||void 0===i?void 0:i._hasPingExpired());return this.flags.volatile&&!a||(o?(this.notifyOutgoingListeners(s),this.packet(s)):this.sendBuffer.push(s)),this.flags={},this}_registerAckCallback(t,e){var n;const r=null!==(n=this.flags.timeout)&&void 0!==n?n:this._opts.ackTimeout;if(void 0===r)return void(this.acks[t]=e);const i=this.io.setTimeoutFn(()=>{delete this.acks[t];for(let e=0;e<this.sendBuffer.length;e++)this.sendBuffer[e].id===t&&this.sendBuffer.splice(e,1);e.call(this,new Error("operation has timed out"))},r),s=(...t)=>{this.io.clearTimeoutFn(i),e.apply(this,t)};s.withError=!0,this.acks[t]=s}emitWithAck(t,...e){return new Promise((n,r)=>{const i=(t,e)=>t?r(t):n(e);i.withError=!0,e.push(i),this.emit(t,...e)})}_addToQueue(t){let e;"function"==typeof t[t.length-1]&&(e=t.pop());const n={id:this._queueSeq++,tryCount:0,pending:!1,args:t,flags:Object.assign({fromQueue:!0},this.flags)};t.push((t,...r)=>{if(n===this._queue[0])return null!==t?n.tryCount>this._opts.retries&&(this._queue.shift(),e&&e(t)):(this._queue.shift(),e&&e(null,...r)),n.pending=!1,this._drainQueue()}),this._queue.push(n),this._drainQueue()}_drainQueue(t=!1){if(!this.connected||0===this._queue.length)return;const e=this._queue[0];e.pending&&!t||(e.pending=!0,e.tryCount++,this.flags=e.flags,this.emit.apply(this,e.args))}packet(t){t.nsp=this.nsp,this.io._packet(t)}onopen(){"function"==typeof this.auth?this.auth(t=>{this._sendConnectPacket(t)}):this._sendConnectPacket(this.auth)}_sendConnectPacket(t){this.packet({type:PacketType.CONNECT,data:this._pid?Object.assign({pid:this._pid,offset:this._lastOffset},t):t})}onerror(t){this.connected||this.emitReserved("connect_error",t)}onclose(t,e){this.connected=!1,delete this.id,this.emitReserved("disconnect",t,e),this._clearAcks()}_clearAcks(){Object.keys(this.acks).forEach(t=>{if(!this.sendBuffer.some(e=>String(e.id)===t)){const e=this.acks[t];delete this.acks[t],e.withError&&e.call(this,new Error("socket has been disconnected"))}})}onpacket(t){if(t.nsp===this.nsp)switch(t.type){case PacketType.CONNECT:t.data&&t.data.sid?this.onconnect(t.data.sid,t.data.pid):this.emitReserved("connect_error",new Error("It seems you are trying to reach a Socket.IO server in v2.x with a v3.x client, but they are not compatible (more information here: https://socket.io/docs/v3/migrating-from-2-x-to-3-0/)"));break;case PacketType.EVENT:case PacketType.BINARY_EVENT:this.onevent(t);break;case PacketType.ACK:case PacketType.BINARY_ACK:this.onack(t);break;case PacketType.DISCONNECT:this.ondisconnect();break;case PacketType.CONNECT_ERROR:this.destroy();const e=new Error(t.data.message);e.data=t.data.data,this.emitReserved("connect_error",e)}}onevent(t){const e=t.data||[];null!=t.id&&e.push(this.ack(t.id)),this.connected?this.emitEvent(e):this.receiveBuffer.push(Object.freeze(e))}emitEvent(t){if(this._anyListeners&&this._anyListeners.length){const e=this._anyListeners.slice();for(const n of e)n.apply(this,t)}super.emit.apply(this,t),this._pid&&t.length&&"string"==typeof t[t.length-1]&&(this._lastOffset=t[t.length-1])}ack(t){const e=this;let n=!1;return function(...r){n||(n=!0,e.packet({type:PacketType.ACK,id:t,data:r}))}}onack(t){const e=this.acks[t.id];"function"==typeof e&&(delete this.acks[t.id],e.withError&&t.data.unshift(null),e.apply(this,t.data))}onconnect(t,e){this.id=t,this.recovered=e&&this._pid===e,this._pid=e,this.connected=!0,this.emitBuffered(),this.emitReserved("connect"),this._drainQueue(!0)}emitBuffered(){this.receiveBuffer.forEach(t=>this.emitEvent(t)),this.receiveBuffer=[],this.sendBuffer.forEach(t=>{this.notifyOutgoingListeners(t),this.packet(t)}),this.sendBuffer=[]}ondisconnect(){this.destroy(),this.onclose("io server disconnect")}destroy(){this.subs&&(this.subs.forEach(t=>t()),this.subs=void 0),this.io._destroy(this)}disconnect(){return this.connected&&this.packet({type:PacketType.DISCONNECT}),this.destroy(),this.connected&&this.onclose("io client disconnect"),this}close(){return this.disconnect()}compress(t){return this.flags.compress=t,this}get volatile(){return this.flags.volatile=!0,this}timeout(t){return this.flags.timeout=t,this}onAny(t){return this._anyListeners=this._anyListeners||[],this._anyListeners.push(t),this}prependAny(t){return this._anyListeners=this._anyListeners||[],this._anyListeners.unshift(t),this}offAny(t){if(!this._anyListeners)return this;if(t){const e=this._anyListeners;for(let n=0;n<e.length;n++)if(t===e[n])return e.splice(n,1),this}else this._anyListeners=[];return this}listenersAny(){return this._anyListeners||[]}onAnyOutgoing(t){return this._anyOutgoingListeners=this._anyOutgoingListeners||[],this._anyOutgoingListeners.push(t),this}prependAnyOutgoing(t){return this._anyOutgoingListeners=this._anyOutgoingListeners||[],this._anyOutgoingListeners.unshift(t),this}offAnyOutgoing(t){if(!this._anyOutgoingListeners)return this;if(t){const e=this._anyOutgoingListeners;for(let n=0;n<e.length;n++)if(t===e[n])return e.splice(n,1),this}else this._anyOutgoingListeners=[];return this}listenersAnyOutgoing(){return this._anyOutgoingListeners||[]}notifyOutgoingListeners(t){if(this._anyOutgoingListeners&&this._anyOutgoingListeners.length){const e=this._anyOutgoingListeners.slice();for(const n of e)n.apply(this,t.data)}}}function Backoff(t){this.ms=(t=t||{}).min||100,this.max=t.max||1e4,this.factor=t.factor||2,this.jitter=t.jitter>0&&t.jitter<=1?t.jitter:0,this.attempts=0}Backoff.prototype.duration=function(){var t=this.ms*Math.pow(this.factor,this.attempts++);if(this.jitter){var e=Math.random(),n=Math.floor(e*this.jitter*t);t=1&Math.floor(10*e)?t+n:t-n}return 0|Math.min(t,this.max)},Backoff.prototype.reset=function(){this.attempts=0},Backoff.prototype.setMin=function(t){this.ms=t},Backoff.prototype.setMax=function(t){this.max=t},Backoff.prototype.setJitter=function(t){this.jitter=t};class Manager extends Emitter{constructor(t,e){var n;super(),this.nsps={},this.subs=[],t&&"object"==typeof t&&(e=t,t=void 0),(e=e||{}).path=e.path||"/socket.io",this.opts=e,installTimerFunctions(this,e),this.reconnection(!1!==e.reconnection),this.reconnectionAttempts(e.reconnectionAttempts||Infinity),this.reconnectionDelay(e.reconnectionDelay||1e3),this.reconnectionDelayMax(e.reconnectionDelayMax||5e3),this.randomizationFactor(null!==(n=e.randomizationFactor)&&void 0!==n?n:.5),this.backoff=new Backoff({min:this.reconnectionDelay(),max:this.reconnectionDelayMax(),jitter:this.randomizationFactor()}),this.timeout(null==e.timeout?2e4:e.timeout),this._readyState="closed",this.uri=t;const r=e.parser||parser;this.encoder=new r.Encoder,this.decoder=new r.Decoder,this._autoConnect=!1!==e.autoConnect,this._autoConnect&&this.open()}reconnection(t){return arguments.length?(this._reconnection=!!t,t||(this.skipReconnect=!0),this):this._reconnection}reconnectionAttempts(t){return void 0===t?this._reconnectionAttempts:(this._reconnectionAttempts=t,this)}reconnectionDelay(t){var e;return void 0===t?this._reconnectionDelay:(this._reconnectionDelay=t,null===(e=this.backoff)||void 0===e||e.setMin(t),this)}randomizationFactor(t){var e;return void 0===t?this._randomizationFactor:(this._randomizationFactor=t,null===(e=this.backoff)||void 0===e||e.setJitter(t),this)}reconnectionDelayMax(t){var e;return void 0===t?this._reconnectionDelayMax:(this._reconnectionDelayMax=t,null===(e=this.backoff)||void 0===e||e.setMax(t),this)}timeout(t){return arguments.length?(this._timeout=t,this):this._timeout}maybeReconnectOnOpen(){!this._reconnecting&&this._reconnection&&0===this.backoff.attempts&&this.reconnect()}open(t){if(~this._readyState.indexOf("open"))return this;this.engine=new Socket$1(this.uri,this.opts);const e=this.engine,n=this;this._readyState="opening",this.skipReconnect=!1;const r=on(e,"open",function(){n.onopen(),t&&t()}),i=e=>{this.cleanup(),this._readyState="closed",this.emitReserved("error",e),t?t(e):this.maybeReconnectOnOpen()},s=on(e,"error",i);if(!1!==this._timeout){const t=this.setTimeoutFn(()=>{r(),i(new Error("timeout")),e.close()},this._timeout);this.opts.autoUnref&&t.unref(),this.subs.push(()=>{this.clearTimeoutFn(t)})}return this.subs.push(r),this.subs.push(s),this}connect(t){return this.open(t)}onopen(){this.cleanup(),this._readyState="open",this.emitReserved("open");const t=this.engine;this.subs.push(on(t,"ping",this.onping.bind(this)),on(t,"data",this.ondata.bind(this)),on(t,"error",this.onerror.bind(this)),on(t,"close",this.onclose.bind(this)),on(this.decoder,"decoded",this.ondecoded.bind(this)))}onping(){this.emitReserved("ping")}ondata(t){try{this.decoder.add(t)}catch(t){this.onclose("parse error",t)}}ondecoded(t){nextTick(()=>{this.emitReserved("packet",t)},this.setTimeoutFn)}onerror(t){this.emitReserved("error",t)}socket(t,e){let n=this.nsps[t];return n?this._autoConnect&&!n.active&&n.connect():(n=new Socket(this,t,e),this.nsps[t]=n),n}_destroy(t){const e=Object.keys(this.nsps);for(const t of e)if(this.nsps[t].active)return;this._close()}_packet(t){const e=this.encoder.encode(t);for(let n=0;n<e.length;n++)this.engine.write(e[n],t.options)}cleanup(){this.subs.forEach(t=>t()),this.subs.length=0,this.decoder.destroy()}_close(){this.skipReconnect=!0,this._reconnecting=!1,this.onclose("forced close")}disconnect(){return this._close()}onclose(t,e){var n;this.cleanup(),null===(n=this.engine)||void 0===n||n.close(),this.backoff.reset(),this._readyState="closed",this.emitReserved("close",t,e),this._reconnection&&!this.skipReconnect&&this.reconnect()}reconnect(){if(this._reconnecting||this.skipReconnect)return this;const t=this;if(this.backoff.attempts>=this._reconnectionAttempts)this.backoff.reset(),this.emitReserved("reconnect_failed"),this._reconnecting=!1;else{const e=this.backoff.duration();this._reconnecting=!0;const n=this.setTimeoutFn(()=>{t.skipReconnect||(this.emitReserved("reconnect_attempt",t.backoff.attempts),t.skipReconnect||t.open(e=>{e?(t._reconnecting=!1,t.reconnect(),this.emitReserved("reconnect_error",e)):t.onreconnect()}))},e);this.opts.autoUnref&&n.unref(),this.subs.push(()=>{this.clearTimeoutFn(n)})}}onreconnect(){const t=this.backoff.attempts;this._reconnecting=!1,this.backoff.reset(),this.emitReserved("reconnect",t)}}const cache={};function lookup(t,e){"object"==typeof t&&(e=t,t=void 0);const n=url(t,(e=e||{}).path||"/socket.io"),r=n.source,i=n.id;let s;return e.forceNew||e["force new connection"]||!1===e.multiplex||cache[i]&&n.path in cache[i].nsps?s=new Manager(r,e):(cache[i]||(cache[i]=new Manager(r,e)),s=cache[i]),n.query&&!e.query&&(e.query=n.queryKey),s.socket(n.path,e)}var $protobuf,$Reader,$Writer,$util,$root;Object.assign(lookup,{Manager,Socket,io:lookup,connect:lookup}),function(rt){var r,e,i;r={1:[function(t,e,n){e.exports=function(t,e){for(var n=Array(arguments.length-1),r=0,i=2,s=!0;i<arguments.length;)n[r++]=arguments[i++];return new Promise(function(i,a){n[r]=function(t){if(s)if(s=!1,t)a(t);else{for(var e=Array(arguments.length-1),n=0;n<e.length;)e[n++]=arguments[n];i.apply(null,e)}};try{t.apply(e||null,n)}catch(t){s&&(s=!1,a(t))}})}},{}],2:[function(t,e,n){n.length=function(t){var e=t.length;if(!e)return 0;for(var n=0;1<--e%4&&"="==(t[0|e]||"");)++n;return Math.ceil(3*t.length)/4-n};for(var r=Array(64),i=Array(123),s=0;s<64;)i[r[s]=s<26?s+65:s<52?s+71:s<62?s-4:s-59|43]=s++;n.encode=function(t,e,n){for(var i,s=null,a=[],o=0,l=0;e<n;){var c=t[e++];switch(l){case 0:a[o++]=r[c>>2],i=(3&c)<<4,l=1;break;case 1:a[o++]=r[i|c>>4],i=(15&c)<<2,l=2;break;case 2:a[o++]=r[i|c>>6],a[o++]=r[63&c],l=0}8191<o&&((s=s||[]).push(String.fromCharCode.apply(String,a)),o=0)}return l&&(a[o++]=r[i],a[o++]=61,1===l&&(a[o++]=61)),s?(o&&s.push(String.fromCharCode.apply(String,a.slice(0,o))),s.join("")):String.fromCharCode.apply(String,a.slice(0,o))};var a="invalid encoding";n.decode=function(t,e,n){for(var r,s=n,o=0,l=0;l<t.length;){var c=t.charCodeAt(l++);if(61==c&&1<o)break;if((c=i[c])===rt)throw Error(a);switch(o){case 0:r=c,o=1;break;case 1:e[n++]=r<<2|(48&c)>>4,r=c,o=2;break;case 2:e[n++]=(15&r)<<4|(60&c)>>2,r=c,o=3;break;case 3:e[n++]=(3&r)<<6|c,o=0}}if(1===o)throw Error(a);return n-s},n.test=function(t){return/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/.test(t)}},{}],3:[function(t,e,n){(e.exports=function t(e,n){"string"==typeof e&&(n=e,e=rt);var r=[];function i(e){if("string"!=typeof e){var n=s();if(t.verbose&&console.log("codegen: "+n),n="return "+n,e){for(var a=Object.keys(e),o=Array(a.length+1),l=Array(a.length),c=0;c<a.length;)o[c]=a[c],l[c]=e[a[c++]];return o[c]=n,Function.apply(null,o).apply(null,l)}return Function(n)()}for(var d=Array(arguments.length-1),h=0;h<d.length;)d[h]=arguments[++h];if(h=0,e=e.replace(/%([%dfijs])/g,function(t,e){var n=d[h++];switch(e){case"d":case"f":return""+ +(""+n);case"i":return""+Math.floor(n);case"j":return JSON.stringify(n);case"s":return""+n}return"%"}),h!==d.length)throw Error("parameter count mismatch");return r.push(e),i}function s(t){return"function "+(t||n||"")+"("+(e&&e.join(",")||"")+"){\n "+r.join("\n ")+"\n}"}return i.toString=s,i}).verbose=!1},{}],4:[function(t,e,n){function r(){this.i={}}(e.exports=r).prototype.on=function(t,e,n){return(this.i[t]||(this.i[t]=[])).push({fn:e,ctx:n||this}),this},r.prototype.off=function(t,e){if(t===rt)this.i={};else if(e===rt)this.i[t]=[];else for(var n=this.i[t],r=0;r<n.length;)n[r].fn===e?n.splice(r,1):++r;return this},r.prototype.emit=function(t){var e=this.i[t];if(e){for(var n=[],r=1;r<arguments.length;)n.push(arguments[r++]);for(r=0;r<e.length;)e[r].fn.apply(e[r++].ctx,n)}return this}},{}],5:[function(t,e,n){e.exports=s;var r=t(1),i=t(7)("fs");function s(t,e,n){return e="function"==typeof e?(n=e,{}):e||{},n?!e.xhr&&i&&i.readFile?i.readFile(t,function(r,i){return r&&"undefined"!=typeof XMLHttpRequest?s.xhr(t,e,n):r?n(r):n(null,e.binary?i:i.toString("utf8"))}):s.xhr(t,e,n):r(s,this,t,e)}s.xhr=function(t,e,n){var r=new XMLHttpRequest;r.onreadystatechange=function(){if(4!==r.readyState)return rt;if(0!==r.status&&200!==r.status)return n(Error("status "+r.status));if(e.binary){if(!(t=r.response))for(var t=[],i=0;i<r.responseText.length;++i)t.push(255&r.responseText.charCodeAt(i));return n(null,"undefined"!=typeof Uint8Array?new Uint8Array(t):t)}return n(null,r.responseText)},e.binary&&("overrideMimeType"in r&&r.overrideMimeType("text/plain; charset=x-user-defined"),r.responseType="arraybuffer"),r.open("GET",t),r.send()}},{1:1,7:7}],6:[function(t,e,n){function r(t){function e(t,e,n,r){var i=e<0?1:0;t(0===(e=i?-e:e)?0<1/e?0:2147483648:isNaN(e)?2143289344:34028234663852886e22<e?(i<<31|2139095040)>>>0:e<11754943508222875e-54?(i<<31|Math.round(e/1401298464324817e-60))>>>0:(i<<31|127+(t=Math.floor(Math.log(e)/Math.LN2))<<23|8388607&Math.round(e*Math.pow(2,-t)*8388608))>>>0,n,r)}function n(t,e,n){return e=2*((t=t(e,n))>>31)+1,n=t>>>23&255,t&=8388607,255==n?t?NaN:1/0*e:0==n?1401298464324817e-60*e*t:e*Math.pow(2,n-150)*(8388608+t)}function r(t,e,n){h[0]=t,e[n]=u[0],e[n+1]=u[1],e[n+2]=u[2],e[n+3]=u[3]}function l(t,e,n){h[0]=t,e[n]=u[3],e[n+1]=u[2],e[n+2]=u[1],e[n+3]=u[0]}function c(t,e){return u[0]=t[e],u[1]=t[e+1],u[2]=t[e+2],u[3]=t[e+3],h[0]}function d(t,e){return u[3]=t[e],u[2]=t[e+1],u[1]=t[e+2],u[0]=t[e+3],h[0]}var h,u,p,f,m;function _(t,e,n,r,i,s){var a,o=r<0?1:0;0===(r=o?-r:r)?(t(0,i,s+e),t(0<1/r?0:2147483648,i,s+n)):isNaN(r)?(t(0,i,s+e),t(2146959360,i,s+n)):17976931348623157e292<r?(t(0,i,s+e),t((o<<31|2146435072)>>>0,i,s+n)):r<22250738585072014e-324?(t((a=r/5e-324)>>>0,i,s+e),t((o<<31|a/4294967296)>>>0,i,s+n)):(t(4503599627370496*(a=r*Math.pow(2,-(r=1024===(r=Math.floor(Math.log(r)/Math.LN2))?1023:r)))>>>0,i,s+e),t((o<<31|r+1023<<20|1048576*a&1048575)>>>0,i,s+n))}function g(t,e,n,r,i){return e=t(r,i+e),r=2*((t=t(r,i+n))>>31)+1,n=4294967296*(1048575&t)+e,2047==(i=t>>>20&2047)?n?NaN:1/0*r:0==i?5e-324*r*n:r*Math.pow(2,i-1075)*(n+4503599627370496)}function y(t,e,n){p[0]=t,e[n]=f[0],e[n+1]=f[1],e[n+2]=f[2],e[n+3]=f[3],e[n+4]=f[4],e[n+5]=f[5],e[n+6]=f[6],e[n+7]=f[7]}function S(t,e,n){p[0]=t,e[n]=f[7],e[n+1]=f[6],e[n+2]=f[5],e[n+3]=f[4],e[n+4]=f[3],e[n+5]=f[2],e[n+6]=f[1],e[n+7]=f[0]}function A(t,e){return f[0]=t[e],f[1]=t[e+1],f[2]=t[e+2],f[3]=t[e+3],f[4]=t[e+4],f[5]=t[e+5],f[6]=t[e+6],f[7]=t[e+7],p[0]}function v(t,e){return f[7]=t[e],f[6]=t[e+1],f[5]=t[e+2],f[4]=t[e+3],f[3]=t[e+4],f[2]=t[e+5],f[1]=t[e+6],f[0]=t[e+7],p[0]}return"undefined"!=typeof Float32Array?(h=new Float32Array([-0]),u=new Uint8Array(h.buffer),t.writeFloatLE=(m=128===u[3])?r:l,t.writeFloatBE=m?l:r,t.readFloatLE=m?c:d,t.readFloatBE=m?d:c):(t.writeFloatLE=e.bind(null,i),t.writeFloatBE=e.bind(null,s),t.readFloatLE=n.bind(null,a),t.readFloatBE=n.bind(null,o)),"undefined"!=typeof Float64Array?(p=new Float64Array([-0]),f=new Uint8Array(p.buffer),t.writeDoubleLE=(m=128===f[7])?y:S,t.writeDoubleBE=m?S:y,t.readDoubleLE=m?A:v,t.readDoubleBE=m?v:A):(t.writeDoubleLE=_.bind(null,i,0,4),t.writeDoubleBE=_.bind(null,s,4,0),t.readDoubleLE=g.bind(null,a,0,4),t.readDoubleBE=g.bind(null,o,4,0)),t}function i(t,e,n){e[n]=255&t,e[n+1]=t>>>8&255,e[n+2]=t>>>16&255,e[n+3]=t>>>24}function s(t,e,n){e[n]=t>>>24,e[n+1]=t>>>16&255,e[n+2]=t>>>8&255,e[n+3]=255&t}function a(t,e){return(t[e]|t[e+1]<<8|t[e+2]<<16|t[e+3]<<24)>>>0}function o(t,e){return(t[e]<<24|t[e+1]<<16|t[e+2]<<8|t[e+3])>>>0}e.exports=r(r)},{}],7:[function(t,i,n){function r(t){try{var i=eval("require")(t);if(i&&(i.length||Object.keys(i).length))return i}catch(t){}return null}i.exports=r},{}],8:[function(t,e,n){var r=n.isAbsolute=function(t){return/^(?:\/|\w+:)/.test(t)},i=n.normalize=function(t){var e=(t=t.replace(/\\/g,"/").replace(/\/{2,}/g,"/")).split("/"),n=r(t);t="",n&&(t=e.shift()+"/");for(var i=0;i<e.length;)".."===e[i]?0<i&&".."!==e[i-1]?e.splice(--i,2):n?e.splice(i,1):++i:"."===e[i]?e.splice(i,1):++i;return t+e.join("/")};n.resolve=function(t,e,n){return n||(e=i(e)),!r(e)&&(t=(t=n?t:i(t)).replace(/(?:\/|^)[^/]+$/,"")).length?i(t+"/"+e):e}},{}],9:[function(t,e,n){e.exports=function(t,e,n){var r=n||8192,i=r>>>1,s=null,a=r;return function(n){return n<1||i<n?t(n):(r<a+n&&(s=t(r),a=0),n=e.call(s,a,a+=n),7&a&&(a=1+(7|a)),n)}}},{}],10:[function(t,e,n){n.length=function(t){for(var e,n=0,r=0;r<t.length;++r)(e=t.charCodeAt(r))<128?n+=1:e<2048?n+=2:55296==(64512&e)&&56320==(64512&t.charCodeAt(r+1))?(++r,n+=4):n+=3;return n},n.read=function(t,e,n){if(n-e<1)return"";for(var r,i=null,s=[],a=0;e<n;)(r=t[e++])<128?s[a++]=r:191<r&&r<224?s[a++]=(31&r)<<6|63&t[e++]:239<r&&r<365?(r=((7&r)<<18|(63&t[e++])<<12|(63&t[e++])<<6|63&t[e++])-65536,s[a++]=55296+(r>>10),s[a++]=56320+(1023&r)):s[a++]=(15&r)<<12|(63&t[e++])<<6|63&t[e++],8191<a&&((i=i||[]).push(String.fromCharCode.apply(String,s)),a=0);return i?(a&&i.push(String.fromCharCode.apply(String,s.slice(0,a))),i.join("")):String.fromCharCode.apply(String,s.slice(0,a))},n.write=function(t,e,n){for(var r,i,s=n,a=0;a<t.length;++a)(r=t.charCodeAt(a))<128?e[n++]=r:(r<2048?e[n++]=r>>6|192:(55296==(64512&r)&&56320==(64512&(i=t.charCodeAt(a+1)))?(++a,e[n++]=(r=65536+((1023&r)<<10)+(1023&i))>>18|240,e[n++]=r>>12&63|128):e[n++]=r>>12|224,e[n++]=r>>6&63|128),e[n++]=63&r|128);return n-s}},{}],11:[function(t,e,n){e.exports=i;var r=/\/|\./;function i(t,e){r.test(t)||(t="google/protobuf/"+t+".proto",e={nested:{google:{nested:{protobuf:{nested:e}}}}}),i[t]=e}i("any",{Any:{fields:{type_url:{type:"string",id:1},value:{type:"bytes",id:2}}}}),i("duration",{Duration:e={fields:{seconds:{type:"int64",id:1},nanos:{type:"int32",id:2}}}}),i("timestamp",{Timestamp:e}),i("empty",{Empty:{fields:{}}}),i("struct",{Struct:{fields:{fields:{keyType:"string",type:"Value",id:1}}},Value:{oneofs:{kind:{oneof:["nullValue","numberValue","stringValue","boolValue","structValue","listValue"]}},fields:{nullValue:{type:"NullValue",id:1},numberValue:{type:"double",id:2},stringValue:{type:"string",id:3},boolValue:{type:"bool",id:4},structValue:{type:"Struct",id:5},listValue:{type:"ListValue",id:6}}},NullValue:{values:{NULL_VALUE:0}},ListValue:{fields:{values:{rule:"repeated",type:"Value",id:1}}}}),i("wrappers",{DoubleValue:{fields:{value:{type:"double",id:1}}},FloatValue:{fields:{value:{type:"float",id:1}}},Int64Value:{fields:{value:{type:"int64",id:1}}},UInt64Value:{fields:{value:{type:"uint64",id:1}}},Int32Value:{fields:{value:{type:"int32",id:1}}},UInt32Value:{fields:{value:{type:"uint32",id:1}}},BoolValue:{fields:{value:{type:"bool",id:1}}},StringValue:{fields:{value:{type:"string",id:1}}},BytesValue:{fields:{value:{type:"bytes",id:1}}}}),i("field_mask",{FieldMask:{fields:{paths:{rule:"repeated",type:"string",id:1}}}}),i.get=function(t){return i[t]||null}},{}],12:[function(t,e,n){var r=t(15),i=t(37);function s(t,e,n,i){var s=!1;if(e.resolvedType)if(e.resolvedType instanceof r){t("switch(d%s){",i);for(var a=e.resolvedType.values,o=Object.keys(a),l=0;l<o.length;++l)a[o[l]]!==e.typeDefault||s||(t("default:")('if(typeof(d%s)==="number"){m%s=d%s;break}',i,i,i),e.repeated||t("break"),s=!0),t("case%j:",o[l])("case %i:",a[o[l]])("m%s=%j",i,a[o[l]])("break");t("}")}else t('if(typeof d%s!=="object")',i)("throw TypeError(%j)",e.fullName+": object expected")("m%s=types[%i].fromObject(d%s)",i,n,i);else{var c=!1;switch(e.type){case"double":case"float":t("m%s=Number(d%s)",i,i);break;case"uint32":case"fixed32":t("m%s=d%s>>>0",i,i);break;case"int32":case"sint32":case"sfixed32":t("m%s=d%s|0",i,i);break;case"uint64":c=!0;case"int64":case"sint64":case"fixed64":case"sfixed64":t("if(util.Long)")("(m%s=util.Long.fromValue(d%s)).unsigned=%j",i,i,c)('else if(typeof d%s==="string")',i)("m%s=parseInt(d%s,10)",i,i)('else if(typeof d%s==="number")',i)("m%s=d%s",i,i)('else if(typeof d%s==="object")',i)("m%s=new util.LongBits(d%s.low>>>0,d%s.high>>>0).toNumber(%s)",i,i,i,c?"true":"");break;case"bytes":t('if(typeof d%s==="string")',i)("util.base64.decode(d%s,m%s=util.newBuffer(util.base64.length(d%s)),0)",i,i,i)("else if(d%s.length >= 0)",i)("m%s=d%s",i,i);break;case"string":t("m%s=String(d%s)",i,i);break;case"bool":t("m%s=Boolean(d%s)",i,i)}}return t}function a(t,e,n,i){if(e.resolvedType)e.resolvedType instanceof r?t("d%s=o.enums===String?(types[%i].values[m%s]===undefined?m%s:types[%i].values[m%s]):m%s",i,n,i,i,n,i,i):t("d%s=types[%i].toObject(m%s,o)",i,n,i);else{var s=!1;switch(e.type){case"double":case"float":t("d%s=o.json&&!isFinite(m%s)?String(m%s):m%s",i,i,i,i);break;case"uint64":s=!0;case"int64":case"sint64":case"fixed64":case"sfixed64":t('if(typeof m%s==="number")',i)("d%s=o.longs===String?String(m%s):m%s",i,i,i)("else")("d%s=o.longs===String?util.Long.prototype.toString.call(m%s):o.longs===Number?new util.LongBits(m%s.low>>>0,m%s.high>>>0).toNumber(%s):m%s",i,i,i,i,s?"true":"",i);break;case"bytes":t("d%s=o.bytes===String?util.base64.encode(m%s,0,m%s.length):o.bytes===Array?Array.prototype.slice.call(m%s):m%s",i,i,i,i,i);break;default:t("d%s=m%s",i,i)}}return t}n.fromObject=function(t){var e=t.fieldsArray,n=i.codegen(["d"],t.name+"$fromObject")("if(d instanceof this.ctor)")("return d");if(!e.length)return n("return new this.ctor");n("var m=new this.ctor");for(var a=0;a<e.length;++a){var o=e[a].resolve(),l=i.safeProp(o.name);o.map?(n("if(d%s){",l)('if(typeof d%s!=="object")',l)("throw TypeError(%j)",o.fullName+": object expected")("m%s={}",l)("for(var ks=Object.keys(d%s),i=0;i<ks.length;++i){",l),s(n,o,a,l+"[ks[i]]")("}")("}")):o.repeated?(n("if(d%s){",l)("if(!Array.isArray(d%s))",l)("throw TypeError(%j)",o.fullName+": array expected")("m%s=[]",l)("for(var i=0;i<d%s.length;++i){",l),s(n,o,a,l+"[i]")("}")("}")):(o.resolvedType instanceof r||n("if(d%s!=null){",l),s(n,o,a,l),o.resolvedType instanceof r||n("}"))}return n("return m")},n.toObject=function(t){var e=t.fieldsArray.slice().sort(i.compareFieldsById);if(!e.length)return i.codegen()("return {}");for(var n=i.codegen(["m","o"],t.name+"$toObject")("if(!o)")("o={}")("var d={}"),s=[],o=[],l=[],c=0;c<e.length;++c)e[c].partOf||(e[c].resolve().repeated?s:e[c].map?o:l).push(e[c]);if(s.length){for(n("if(o.arrays||o.defaults){"),c=0;c<s.length;++c)n("d%s=[]",i.safeProp(s[c].name));n("}")}if(o.length){for(n("if(o.objects||o.defaults){"),c=0;c<o.length;++c)n("d%s={}",i.safeProp(o[c].name));n("}")}if(l.length){for(n("if(o.defaults){"),c=0;c<l.length;++c){var d,h=i.safeProp((p=l[c]).name);p.resolvedType instanceof r?n("d%s=o.enums===String?%j:%j",h,p.resolvedType.valuesById[p.typeDefault],p.typeDefault):p.long?n("if(util.Long){")("var n=new util.Long(%i,%i,%j)",p.typeDefault.low,p.typeDefault.high,p.typeDefault.unsigned)("d%s=o.longs===String?n.toString():o.longs===Number?n.toNumber():n",h)("}else")("d%s=o.longs===String?%j:%i",h,p.typeDefault.toString(),p.typeDefault.toNumber()):p.bytes?(d="["+Array.prototype.slice.call(p.typeDefault).join(",")+"]",n("if(o.bytes===String)d%s=%j",h,String.fromCharCode.apply(String,p.typeDefault))("else{")("d%s=%s",h,d)("if(o.bytes!==Array)d%s=util.newBuffer(d%s)",h,h)("}")):n("d%s=%j",h,p.typeDefault)}n("}")}var u=!1;for(c=0;c<e.length;++c){var p,f=t.e.indexOf(p=e[c]);h=i.safeProp(p.name),p.map?(u||(u=!0,n("var ks2")),n("if(m%s&&(ks2=Object.keys(m%s)).length){",h,h)("d%s={}",h)("for(var j=0;j<ks2.length;++j){"),a(n,p,f,h+"[ks2[j]]")("}")):p.repeated?(n("if(m%s&&m%s.length){",h,h)("d%s=[]",h)("for(var j=0;j<m%s.length;++j){",h),a(n,p,f,h+"[j]")("}")):(n("if(m%s!=null&&m.hasOwnProperty(%j)){",h,p.name),a(n,p,f,h),p.partOf&&n("if(o.oneofs)")("d%s=%j",i.safeProp(p.partOf.name),p.name)),n("}")}return n("return d")}},{15:15,37:37}],13:[function(t,e,n){e.exports=function(t){for(var e=s.codegen(["r","l","e"],t.name+"$decode")("if(!(r instanceof Reader))")("r=Reader.create(r)")("var c=l===undefined?r.len:r.pos+l,m=new this.ctor"+(t.fieldsArray.filter(function(t){return t.map}).length?",k,value":""))("while(r.pos<c){")("var t=r.uint32()")("if(t===e)")("break")("switch(t>>>3){"),n=0;n<t.fieldsArray.length;++n){var a=t.e[n].resolve(),o=a.resolvedType instanceof r?"int32":a.type,l="m"+s.safeProp(a.name);e("case %i: {",a.id),a.map?(e("if(%s===util.emptyObject)",l)("%s={}",l)("var c2 = r.uint32()+r.pos"),i.defaults[a.keyType]!==rt?e("k=%j",i.defaults[a.keyType]):e("k=null"),i.defaults[o]!==rt?e("value=%j",i.defaults[o]):e("value=null"),e("while(r.pos<c2){")("var tag2=r.uint32()")("switch(tag2>>>3){")("case 1: k=r.%s(); break",a.keyType)("case 2:"),i.basic[o]===rt?e("value=types[%i].decode(r,r.uint32())",n):e("value=r.%s()",o),e("break")("default:")("r.skipType(tag2&7)")("break")("}")("}"),e(i.long[a.keyType]!==rt?'%s[typeof k==="object"?util.longToHash(k):k]=value':"%s[k]=value",l)):a.repeated?(e("if(!(%s&&%s.length))",l,l)("%s=[]",l),i.packed[o]!==rt&&e("if((t&7)===2){")("var c2=r.uint32()+r.pos")("while(r.pos<c2)")("%s.push(r.%s())",l,o)("}else"),i.basic[o]===rt?e(a.delimited?"%s.push(types[%i].decode(r,undefined,((t&~7)|4)))":"%s.push(types[%i].decode(r,r.uint32()))",l,n):e("%s.push(r.%s())",l,o)):i.basic[o]===rt?e(a.delimited?"%s=types[%i].decode(r,undefined,((t&~7)|4))":"%s=types[%i].decode(r,r.uint32())",l,n):e("%s=r.%s()",l,o),e("break")("}")}for(e("default:")("r.skipType(t&7)")("break")("}")("}"),n=0;n<t.e.length;++n){var c=t.e[n];c.required&&e("if(!m.hasOwnProperty(%j))",c.name)("throw util.ProtocolError(%j,{instance:m})","missing required '"+c.name+"'")}return e("return m")};var r=t(15),i=t(36),s=t(37)},{15:15,36:36,37:37}],14:[function(t,e,n){e.exports=function(t){for(var e,n=s.codegen(["m","w"],t.name+"$encode")("if(!w)")("w=Writer.create()"),o=t.fieldsArray.slice().sort(s.compareFieldsById),l=0;l<o.length;++l){var c=o[l].resolve(),d=t.e.indexOf(c),h=c.resolvedType instanceof r?"int32":c.type,u=i.basic[h];e="m"+s.safeProp(c.name),c.map?(n("if(%s!=null&&Object.hasOwnProperty.call(m,%j)){",e,c.name)("for(var ks=Object.keys(%s),i=0;i<ks.length;++i){",e)("w.uint32(%i).fork().uint32(%i).%s(ks[i])",(c.id<<3|2)>>>0,8|i.mapKey[c.keyType],c.keyType),u===rt?n("types[%i].encode(%s[ks[i]],w.uint32(18).fork()).ldelim().ldelim()",d,e):n(".uint32(%i).%s(%s[ks[i]]).ldelim()",16|u,h,e),n("}")("}")):c.repeated?(n("if(%s!=null&&%s.length){",e,e),c.packed&&i.packed[h]!==rt?n("w.uint32(%i).fork()",(c.id<<3|2)>>>0)("for(var i=0;i<%s.length;++i)",e)("w.%s(%s[i])",h,e)("w.ldelim()"):(n("for(var i=0;i<%s.length;++i)",e),u===rt?a(n,c,d,e+"[i]"):n("w.uint32(%i).%s(%s[i])",(c.id<<3|u)>>>0,h,e)),n("}")):(c.optional&&n("if(%s!=null&&Object.hasOwnProperty.call(m,%j))",e,c.name),u===rt?a(n,c,d,e):n("w.uint32(%i).%s(%s)",(c.id<<3|u)>>>0,h,e))}return n("return w")};var r=t(15),i=t(36),s=t(37);function a(t,e,n,r){e.delimited?t("types[%i].encode(%s,w.uint32(%i)).uint32(%i)",n,r,(e.id<<3|3)>>>0,(e.id<<3|4)>>>0):t("types[%i].encode(%s,w.uint32(%i).fork()).ldelim()",n,r,(e.id<<3|2)>>>0)}},{15:15,36:36,37:37}],15:[function(t,e,n){e.exports=a;var r=t(24),i=(((a.prototype=Object.create(r.prototype)).constructor=a).className="Enum",t(23)),s=t(37);function a(t,e,n,i,s,a){if(r.call(this,t,n),e&&"object"!=typeof e)throw TypeError("values must be an object");if(this.valuesById={},this.values=Object.create(this.valuesById),this.comment=i,this.comments=s||{},this.valuesOptions=a,this.o={},this.reserved=rt,e)for(var o=Object.keys(e),l=0;l<o.length;++l)"number"==typeof e[o[l]]&&(this.valuesById[this.values[o[l]]=e[o[l]]]=o[l])}a.prototype.u=function(t){return r.prototype.u.call(this,t=this.f||t),Object.keys(this.values).forEach(t=>{var e=Object.assign({},this.h);this.o[t]=Object.assign(e,this.valuesOptions&&this.valuesOptions[t]&&this.valuesOptions[t].features)}),this},a.fromJSON=function(t,e){return(t=new a(t,e.values,e.options,e.comment,e.comments)).reserved=e.reserved,e.edition&&(t.f=e.edition),t.a="proto3",t},a.prototype.toJSON=function(t){return t=!!t&&!!t.keepComments,s.toObject(["edition",this.c(),"options",this.options,"valuesOptions",this.valuesOptions,"values",this.values,"reserved",this.reserved&&this.reserved.length?this.reserved:rt,"comment",t?this.comment:rt,"comments",t?this.comments:rt])},a.prototype.add=function(t,e,n,r){if(!s.isString(t))throw TypeError("name must be a string");if(!s.isInteger(e))throw TypeError("id must be an integer");if(this.values[t]!==rt)throw Error("duplicate name '"+t+"' in "+this);if(this.isReservedId(e))throw Error("id "+e+" is reserved in "+this);if(this.isReservedName(t))throw Error("name '"+t+"' is reserved in "+this);if(this.valuesById[e]!==rt){if(!this.options||!this.options.allow_alias)throw Error("duplicate id "+e+" in "+this);this.values[t]=e}else this.valuesById[this.values[t]=e]=t;return r&&(this.valuesOptions===rt&&(this.valuesOptions={}),this.valuesOptions[t]=r||null),this.comments[t]=n||null,this},a.prototype.remove=function(t){if(!s.isString(t))throw TypeError("name must be a string");var e=this.values[t];if(null==e)throw Error("name '"+t+"' does not exist in "+this);return delete this.valuesById[e],delete this.values[t],delete this.comments[t],this.valuesOptions&&delete this.valuesOptions[t],this},a.prototype.isReservedId=function(t){return i.isReservedId(this.reserved,t)},a.prototype.isReservedName=function(t){return i.isReservedName(this.reserved,t)}},{23:23,24:24,37:37}],16:[function(t,e,n){e.exports=c;var r,i=t(24),s=(((c.prototype=Object.create(i.prototype)).constructor=c).className="Field",t(15)),a=t(36),o=t(37),l=/^required|optional|repeated$/;function c(t,e,n,r,s,c,d){if(o.isObject(r)?(d=s,c=r,r=s=rt):o.isObject(s)&&(d=c,c=s,s=rt),i.call(this,t,c),!o.isInteger(e)||e<0)throw TypeError("id must be a non-negative integer");if(!o.isString(n))throw TypeError("type must be a string");if(r!==rt&&!l.test(r=r.toString().toLowerCase()))throw TypeError("rule must be a string rule");if(s!==rt&&!o.isString(s))throw TypeError("extend must be a string");this.rule=(r="proto3_optional"===r?"optional":r)&&"optional"!==r?r:rt,this.type=n,this.id=e,this.extend=s||rt,this.repeated="repeated"===r,this.map=!1,this.message=null,this.partOf=null,this.typeDefault=null,this.defaultValue=null,this.long=!!o.Long&&a.long[n]!==rt,this.bytes="bytes"===n,this.resolvedType=null,this.extensionField=null,this.declaringField=null,this.comment=d}c.fromJSON=function(t,e){return t=new c(t,e.id,e.type,e.rule,e.extend,e.options,e.comment),e.edition&&(t.f=e.edition),t.a="proto3",t},Object.defineProperty(c.prototype,"required",{get:function(){return"LEGACY_REQUIRED"===this.h.field_presence}}),Object.defineProperty(c.prototype,"optional",{get:function(){return!this.required}}),Object.defineProperty(c.prototype,"delimited",{get:function(){return this.resolvedType instanceof r&&"DELIMITED"===this.h.message_encoding}}),Object.defineProperty(c.prototype,"packed",{get:function(){return"PACKED"===this.h.repeated_field_encoding}}),Object.defineProperty(c.prototype,"hasPresence",{get:function(){return!this.repeated&&!this.map&&(this.partOf||this.declaringField||this.extensionField||"IMPLICIT"!==this.h.field_presence)}}),c.prototype.setOption=function(t,e,n){return i.prototype.setOption.call(this,t,e,n)},c.prototype.toJSON=function(t){return t=!!t&&!!t.keepComments,o.toObject(["edition",this.c(),"rule","optional"!==this.rule&&this.rule||rt,"type",this.type,"id",this.id,"extend",this.extend,"options",this.options,"comment",t?this.comment:rt])},c.prototype.resolve=function(){var t;return this.resolved?this:((this.typeDefault=a.defaults[this.type])===rt?(this.resolvedType=(this.declaringField||this).parent.lookupTypeOrEnum(this.type),this.typeDefault=this.resolvedType instanceof r?null:this.resolvedType.values[Object.keys(this.resolvedType.values)[0]]):this.options&&this.options.proto3_optional&&(this.typeDefault=null),this.options&&null!=this.options.default&&(this.typeDefault=this.options.default,this.resolvedType instanceof s&&"string"==typeof this.typeDefault&&(this.typeDefault=this.resolvedType.values[this.typeDefault])),this.options&&(this.options.packed===rt||!this.resolvedType||this.resolvedType instanceof s||delete this.options.packed,Object.keys(this.options).length||(this.options=rt)),this.long?(this.typeDefault=o.Long.fromNumber(this.typeDefault,"u"==(this.type[0]||"")),Object.freeze&&Object.freeze(this.typeDefault)):this.bytes&&"string"==typeof this.typeDefault&&(o.base64.test(this.typeDefault)?o.base64.decode(this.typeDefault,t=o.newBuffer(o.base64.length(this.typeDefault)),0):o.utf8.write(this.typeDefault,t=o.newBuffer(o.utf8.length(this.typeDefault)),0),this.typeDefault=t),this.defaultValue=this.map?o.emptyObject:this.repeated?o.emptyArray:this.typeDefault,this.parent instanceof r&&(this.parent.ctor.prototype[this.name]=this.defaultValue),i.prototype.resolve.call(this))},c.prototype.l=function(t){var e;return"proto2"!==t&&"proto3"!==t?{}:(t={},"required"===this.rule&&(t.field_presence="LEGACY_REQUIRED"),this.parent&&a.defaults[this.type]===rt&&(e=this.parent.get(this.type.split(".").pop()))&&e instanceof r&&e.group&&(t.message_encoding="DELIMITED"),!0===this.getOption("packed")?t.repeated_field_encoding="PACKED":!1===this.getOption("packed")&&(t.repeated_field_encoding="EXPANDED"),t)},c.prototype.u=function(t){return i.prototype.u.call(this,this.f||t)},c.d=function(t,e,n,r){return"function"==typeof e?e=o.decorateType(e).name:e&&"object"==typeof e&&(e=o.decorateEnum(e).name),function(i,s){o.decorateType(i.constructor).add(new c(s,t,e,n,{default:r}))}},c.p=function(t){r=t}},{15:15,24:24,36:36,37:37}],17:[function(t,e,n){var r=e.exports=t(18);r.build="light",r.load=function(t,e,n){return(e="function"==typeof e?(n=e,new r.Root):e||new r.Root).load(t,n)},r.loadSync=function(t,e){return(e=e||new r.Root).loadSync(t)},r.encoder=t(14),r.decoder=t(13),r.verifier=t(40),r.converter=t(12),r.ReflectionObject=t(24),r.Namespace=t(23),r.Root=t(29),r.Enum=t(15),r.Type=t(35),r.Field=t(16),r.OneOf=t(25),r.MapField=t(20),r.Service=t(33),r.Method=t(22),r.Message=t(21),r.wrappers=t(41),r.types=t(36),r.util=t(37),r.ReflectionObject.p(r.Root),r.Namespace.p(r.Type,r.Service,r.Enum),r.Root.p(r.Type),r.Field.p(r.Type)},{12:12,13:13,14:14,15:15,16:16,18:18,20:20,21:21,22:22,23:23,24:24,25:25,29:29,33:33,35:35,36:36,37:37,40:40,41:41}],18:[function(t,e,n){var r=n;function i(){r.util.p(),r.Writer.p(r.BufferWriter),r.Reader.p(r.BufferReader)}r.build="minimal",r.Writer=t(42),r.BufferWriter=t(43),r.Reader=t(27),r.BufferReader=t(28),r.util=t(39),r.rpc=t(31),r.roots=t(30),r.configure=i,i()},{27:27,28:28,30:30,31:31,39:39,42:42,43:43}],19:[function(t,e,n){(e=e.exports=t(17)).build="full",e.tokenize=t(34),e.parse=t(26),e.common=t(11),e.Root.p(e.Type,e.parse,e.common)},{11:11,17:17,26:26,34:34}],20:[function(t,e,n){e.exports=a;var r=t(16),i=(((a.prototype=Object.create(r.prototype)).constructor=a).className="MapField",t(36)),s=t(37);function a(t,e,n,i,a,o){if(r.call(this,t,e,i,rt,rt,a,o),!s.isString(n))throw TypeError("keyType must be a string");this.keyType=n,this.resolvedKeyType=null,this.map=!0}a.fromJSON=function(t,e){return new a(t,e.id,e.keyType,e.type,e.options,e.comment)},a.prototype.toJSON=function(t){return s.toObject(["keyType",this.keyType,"type",this.type,"id",this.id,"extend",this.extend,"options",this.options,"comment",(t=!!t&&!!t.keepComments)?this.comment:rt])},a.prototype.resolve=function(){if(this.resolved)return this;if(i.mapKey[this.keyType]===rt)throw Error("invalid key type: "+this.keyType);return r.prototype.resolve.call(this)},a.d=function(t,e,n){return"function"==typeof n?n=s.decorateType(n).name:n&&"object"==typeof n&&(n=s.decorateEnum(n).name),function(r,i){s.decorateType(r.constructor).add(new a(i,t,e,n))}}},{16:16,36:36,37:37}],21:[function(t,e,n){e.exports=i;var r=t(39);function i(t){if(t)for(var e=Object.keys(t),n=0;n<e.length;++n)this[e[n]]=t[e[n]]}i.create=function(t){return this.$type.create(t)},i.encode=function(t,e){return this.$type.encode(t,e)},i.encodeDelimited=function(t,e){return this.$type.encodeDelimited(t,e)},i.decode=function(t){return this.$type.decode(t)},i.decodeDelimited=function(t){return this.$type.decodeDelimited(t)},i.verify=function(t){return this.$type.verify(t)},i.fromObject=function(t){return this.$type.fromObject(t)},i.toObject=function(t,e){return this.$type.toObject(t,e)},i.prototype.toJSON=function(){return this.$type.toObject(this,r.toJSONOptions)}},{39:39}],22:[function(t,e,n){e.exports=s;var r=t(24),i=(((s.prototype=Object.create(r.prototype)).constructor=s).className="Method",t(37));function s(t,e,n,s,a,o,l,c,d){if(i.isObject(a)?(l=a,a=o=rt):i.isObject(o)&&(l=o,o=rt),e!==rt&&!i.isString(e))throw TypeError("type must be a string");if(!i.isString(n))throw TypeError("requestType must be a string");if(!i.isString(s))throw TypeError("responseType must be a string");r.call(this,t,l),this.type=e||"rpc",this.requestType=n,this.requestStream=!!a||rt,this.responseType=s,this.responseStream=!!o||rt,this.resolvedRequestType=null,this.resolvedResponseType=null,this.comment=c,this.parsedOptions=d}s.fromJSON=function(t,e){return new s(t,e.type,e.requestType,e.responseType,e.requestStream,e.responseStream,e.options,e.comment,e.parsedOptions)},s.prototype.toJSON=function(t){return i.toObject(["type","rpc"!==this.type&&this.type||rt,"requestType",this.requestType,"requestStream",this.requestStream,"responseType",this.responseType,"responseStream",this.responseStream,"options",this.options,"comment",(t=!!t&&!!t.keepComments)?this.comment:rt,"parsedOptions",this.parsedOptions])},s.prototype.resolve=function(){return this.resolved?this:(this.resolvedRequestType=this.parent.lookupType(this.requestType),this.resolvedResponseType=this.parent.lookupType(this.responseType),r.prototype.resolve.call(this))}},{24:24,37:37}],23:[function(t,e,n){e.exports=h;var r,i,s,a=t(24),o=(((h.prototype=Object.create(a.prototype)).constructor=h).className="Namespace",t(16)),l=t(37),c=t(25);function d(t,e){if(!t||!t.length)return rt;for(var n={},r=0;r<t.length;++r)n[t[r].name]=t[r].toJSON(e);return n}function h(t,e){a.call(this,t,e),this.nested=rt,this.v=null,this.b={},this.w=!0,this.y=!0}function u(t){t.v=null,t.b={};for(var e=t;e=e.parent;)e.b={};return t}h.fromJSON=function(t,e){return new h(t,e.options).addJSON(e.nested)},h.arrayToJSON=d,h.isReservedId=function(t,e){if(t)for(var n=0;n<t.length;++n)if("string"!=typeof t[n]&&t[n][0]<=e&&t[n][1]>e)return!0;return!1},h.isReservedName=function(t,e){if(t)for(var n=0;n<t.length;++n)if(t[n]===e)return!0;return!1},Object.defineProperty(h.prototype,"nestedArray",{get:function(){return this.v||(this.v=l.toArray(this.nested))}}),h.prototype.toJSON=function(t){return l.toObject(["options",this.options,"nested",d(this.nestedArray,t)])},h.prototype.addJSON=function(t){if(t)for(var e,n=Object.keys(t),a=0;a<n.length;++a)this.add(((e=t[n[a]]).fields!==rt?r:e.values!==rt?s:e.methods!==rt?i:e.id!==rt?o:h).fromJSON(n[a],e));return this},h.prototype.get=function(t){return this.nested&&this.nested[t]||null},h.prototype.getEnum=function(t){if(this.nested&&this.nested[t]instanceof s)return this.nested[t].values;throw Error("no such enum: "+t)},h.prototype.add=function(t){if(!(t instanceof o&&t.extend!==rt||t instanceof r||t instanceof c||t instanceof s||t instanceof i||t instanceof h))throw TypeError("object must be a valid nested object");if(this.nested){var e=this.get(t.name);if(e){if(!(e instanceof h&&t instanceof h)||e instanceof r||e instanceof i)throw Error("duplicate name '"+t.name+"' in "+this);for(var n=e.nestedArray,a=0;a<n.length;++a)t.add(n[a]);this.remove(e),this.nested||(this.nested={}),t.setOptions(e.options,!0)}}else this.nested={};this.nested[t.name]=t,this instanceof r||this instanceof i||this instanceof s||this instanceof o||t.f||(t.f=t.a),this.w=!0,this.y=!0;for(var l=this;l=l.parent;)l.w=!0,l.y=!0;return t.onAdd(this),u(this)},h.prototype.remove=function(t){if(!(t instanceof a))throw TypeError("object must be a ReflectionObject");if(t.parent!==this)throw Error(t+" is not a member of "+this);return delete this.nested[t.name],Object.keys(this.nested).length||(this.nested=rt),t.onRemove(this),u(this)},h.prototype.define=function(t,e){if(l.isString(t))t=t.split(".");else if(!Array.isArray(t))throw TypeError("illegal path");if(t&&t.length&&""===t[0])throw Error("path must be relative");for(var n=this;0<t.length;){var r=t.shift();if(n.nested&&n.nested[r]){if(!((n=n.nested[r])instanceof h))throw Error("path conflicts with non-namespace objects")}else n.add(n=new h(r))}return e&&n.addJSON(e),n},h.prototype.resolveAll=function(){if(this.y){this.g(this.f);var t=this.nestedArray,e=0;for(this.resolve();e<t.length;)t[e]instanceof h?t[e++].resolveAll():t[e++].resolve();this.y=!1}return this},h.prototype.g=function(t){return this.w&&(this.w=!1,a.prototype.g.call(this,t=this.f||t),this.nestedArray.forEach(e=>{e.g(t)})),this},h.prototype.lookup=function(t,e,n){if("boolean"==typeof e?(n=e,e=rt):e&&!Array.isArray(e)&&(e=[e]),l.isString(t)&&t.length){if("."===t)return this.root;t=t.split(".")}else if(!t.length)return this;var r=t.join(".");if(""===t[0])return this.root.lookup(t.slice(1),e);var i=this.root.j&&this.root.j["."+r];if(i&&(!e||~e.indexOf(i.constructor)))return i;if((i=this.k(t,r))&&(!e||~e.indexOf(i.constructor)))return i;if(!n)for(var s=this;s.parent;){if((i=s.parent.k(t,r))&&(!e||~e.indexOf(i.constructor)))return i;s=s.parent}return null},h.prototype.k=function(t,e){if(Object.prototype.hasOwnProperty.call(this.b,e))return this.b[e];var n=this.get(t[0]),r=null;if(n)1===t.length?r=n:n instanceof h&&(t=t.slice(1),r=n.k(t,t.join(".")));else for(var i=0;i<this.nestedArray.length;++i)this.v[i]instanceof h&&(n=this.v[i].k(t,e))&&(r=n);return this.b[e]=r},h.prototype.lookupType=function(t){var e=this.lookup(t,[r]);if(e)return e;throw Error("no such type: "+t)},h.prototype.lookupEnum=function(t){var e=this.lookup(t,[s]);if(e)return e;throw Error("no such Enum '"+t+"' in "+this)},h.prototype.lookupTypeOrEnum=function(t){var e=this.lookup(t,[r,s]);if(e)return e;throw Error("no such Type or Enum '"+t+"' in "+this)},h.prototype.lookupService=function(t){var e=this.lookup(t,[i]);if(e)return e;throw Error("no such Service '"+t+"' in "+this)},h.p=function(t,e,n){r=t,i=e,s=n}},{16:16,24:24,25:25,37:37}],24:[function(t,e,n){(e.exports=c).className="ReflectionObject";const r=t(25);var i,s=t(37),a={enum_type:"OPEN",field_presence:"EXPLICIT",json_format:"ALLOW",message_encoding:"LENGTH_PREFIXED",repeated_field_encoding:"PACKED",utf8_validation:"VERIFY"},o={enum_type:"CLOSED",field_presence:"EXPLICIT",json_format:"LEGACY_BEST_EFFORT",message_encoding:"LENGTH_PREFIXED",repeated_field_encoding:"EXPANDED",utf8_validation:"NONE"},l={enum_type:"OPEN",field_presence:"IMPLICIT",json_format:"ALLOW",message_encoding:"LENGTH_PREFIXED",repeated_field_encoding:"PACKED",utf8_validation:"VERIFY"};function c(t,e){if(!s.isString(t))throw TypeError("name must be a string");if(e&&!s.isObject(e))throw TypeError("options must be an object");this.options=e,this.parsedOptions=null,this.name=t,this.f=null,this.a="proto2",this.h={},this.O=!1,this.parent=null,this.resolved=!1,this.comment=null,this.filename=null}Object.defineProperties(c.prototype,{root:{get:function(){for(var t=this;null!==t.parent;)t=t.parent;return t}},fullName:{get:function(){for(var t=[this.name],e=this.parent;e;)t.unshift(e.name),e=e.parent;return t.join(".")}}}),c.prototype.toJSON=function(){throw Error()},c.prototype.onAdd=function(t){this.parent&&this.parent!==t&&this.parent.remove(this),this.parent=t,this.resolved=!1,(t=t.root)instanceof i&&t.A(this)},c.prototype.onRemove=function(t){(t=t.root)instanceof i&&t.T(this),this.parent=null,this.resolved=!1},c.prototype.resolve=function(){return this.resolved||this.root instanceof i&&(this.resolved=!0),this},c.prototype.g=function(t){return this.u(this.f||t)},c.prototype.u=function(t){if(!this.O){var e={};if(!t)throw Error("Unknown edition for "+this.fullName);var n=Object.assign(this.options?Object.assign({},this.options.features):{},this.l(t));if(this.f){if("proto2"===t)e=Object.assign({},o);else if("proto3"===t)e=Object.assign({},l);else{if("2023"!==t)throw Error("Unknown edition: "+t);e=Object.assign({},a)}this.h=Object.assign(e,n||{})}else{if(this.partOf instanceof r)t=Object.assign({},this.partOf.h),this.h=Object.assign(t,n||{});else if(!this.declaringField){if(!this.parent)throw Error("Unable to find a parent for "+this.fullName);e=Object.assign({},this.parent.h),this.h=Object.assign(e,n||{})}this.extensionField&&(this.extensionField.h=this.h)}this.O=!0}},c.prototype.l=function(){return{}},c.prototype.getOption=function(t){return this.options?this.options[t]:rt},c.prototype.setOption=function(t,e,n){return this.options||(this.options={}),/^features\./.test(t)?s.setProperty(this.options,t,e,n):n&&this.options[t]!==rt||(this.getOption(t)!==e&&(this.resolved=!1),this.options[t]=e),this},c.prototype.setParsedOption=function(t,e,n){this.parsedOptions||(this.parsedOptions=[]);var r,i,a=this.parsedOptions;return n?(r=a.find(function(e){return Object.prototype.hasOwnProperty.call(e,t)}))?s.setProperty(i=r[t],n,e):((r={})[t]=s.setProperty({},n,e),a.push(r)):((i={})[t]=e,a.push(i)),this},c.prototype.setOptions=function(t,e){if(t)for(var n=Object.keys(t),r=0;r<n.length;++r)this.setOption(n[r],t[n[r]],e);return this},c.prototype.toString=function(){var t=this.constructor.className,e=this.fullName;return e.length?t+" "+e:t},c.prototype.c=function(){return this.f&&"proto3"!==this.f?this.f:rt},c.p=function(t){i=t}},{25:25,37:37}],25:[function(t,e,n){e.exports=a;var r=t(24),i=(((a.prototype=Object.create(r.prototype)).constructor=a).className="OneOf",t(16)),s=t(37);function a(t,e,n,i){if(Array.isArray(e)||(n=e,e=rt),r.call(this,t,n),e!==rt&&!Array.isArray(e))throw TypeError("fieldNames must be an Array");this.oneof=e||[],this.fieldsArray=[],this.comment=i}function o(t){if(t.parent)for(var e=0;e<t.fieldsArray.length;++e)t.fieldsArray[e].parent||t.parent.add(t.fieldsArray[e])}a.fromJSON=function(t,e){return new a(t,e.oneof,e.options,e.comment)},a.prototype.toJSON=function(t){return s.toObject(["options",this.options,"oneof",this.oneof,"comment",(t=!!t&&!!t.keepComments)?this.comment:rt])},a.prototype.add=function(t){if(t instanceof i)return t.parent&&t.parent!==this.parent&&t.parent.remove(t),this.oneof.push(t.name),this.fieldsArray.push(t),o(t.partOf=this),this;throw TypeError("field must be a Field")},a.prototype.remove=function(t){if(!(t instanceof i))throw TypeError("field must be a Field");var e=this.fieldsArray.indexOf(t);if(e<0)throw Error(t+" is not a member of "+this);return this.fieldsArray.splice(e,1),-1<(e=this.oneof.indexOf(t.name))&&this.oneof.splice(e,1),t.partOf=null,this},a.prototype.onAdd=function(t){r.prototype.onAdd.call(this,t);for(var e=0;e<this.oneof.length;++e){var n=t.get(this.oneof[e]);n&&!n.partOf&&(n.partOf=this).fieldsArray.push(n)}o(this)},a.prototype.onRemove=function(t){for(var e,n=0;n<this.fieldsArray.length;++n)(e=this.fieldsArray[n]).parent&&e.parent.remove(e);r.prototype.onRemove.call(this,t)},Object.defineProperty(a.prototype,"isProto3Optional",{get:function(){var t;return null!=this.fieldsArray&&1===this.fieldsArray.length&&null!=(t=this.fieldsArray[0]).options&&!0===t.options.proto3_optional}}),a.d=function(){for(var t=Array(arguments.length),e=0;e<arguments.length;)t[e]=arguments[e++];return function(e,n){s.decorateType(e.constructor).add(new a(n,t)),Object.defineProperty(e,n,{get:s.oneOfGetter(t),set:s.oneOfSetter(t)})}}},{16:16,24:24,37:37}],26:[function(t,e,n){(e.exports=T).filename=null,T.defaults={keepCase:!1};var r=t(34),i=t(29),s=t(35),a=t(16),o=t(20),l=t(25),c=t(15),d=t(33),h=t(22),u=t(24),p=t(36),f=t(37),m=/^[1-9][0-9]*$/,_=/^-?[1-9][0-9]*$/,g=/^0[x][0-9a-fA-F]+$/,y=/^-?0[x][0-9a-fA-F]+$/,S=/^0[0-7]+$/,A=/^-?0[0-7]+$/,v=/^(?![eE])[0-9]*(?:\.[0-9]*)?(?:[eE][+-]?[0-9]+)?$/,E=/^[a-zA-Z_][a-zA-Z_0-9]*$/,b=/^(?:\.?[a-zA-Z_][a-zA-Z_0-9]*)(?:\.[a-zA-Z_][a-zA-Z_0-9]*)*$/;function T(t,e,n){e instanceof i||(n=e,e=new i);var w,x,I,R,C,B,D=(n=n||T.defaults).preferTrailingComment||!1,P=r(t,n.alternateCommentMode||!1),k=P.next,O=P.push,U=P.peek,N=P.skip,L=P.cmnt,F=!0,M="proto2",G=e,z=[],W={},H=n.keepCase?function(t){return t}:f.camelCase;function $(t,e,n){var r=T.filename;return n||(T.filename=null),Error("illegal "+(e||"token")+" '"+t+"' ("+(r?r+", ":"")+"line "+P.line+")")}function j(){var t,e=[];do{if('"'!==(t=k())&&"'"!==t)throw $(t)}while(e.push(k()),N(t),'"'===(t=U())||"'"===t);return e.join("")}function V(t){var e=k();switch(e){case"'":case'"':return O(e),j();case"true":case"TRUE":return!0;case"false":case"FALSE":return!1}try{var n=e,r=1;switch("-"==(n[0]||"")&&(r=-1,n=n.substring(1)),n){case"inf":case"INF":case"Inf":return r*(1/0);case"nan":case"NAN":case"Nan":case"NaN":return NaN;case"0":return 0}if(m.test(n))return r*parseInt(n,10);if(g.test(n))return r*parseInt(n,16);if(S.test(n))return r*parseInt(n,8);if(v.test(n))return r*parseFloat(n);throw $(n,"number",!0)}catch(n){if(t&&b.test(e))return e;throw $(e,"value")}}function Y(t,e){var n;do{if(!e||'"'!==(r=U())&&"'"!==r)try{t.push([n=K(k()),N("to",!0)?K(k()):n])}catch(n){if(!(e&&b.test(r)&&2023<=M))throw n;t.push(r)}else{var r=j();if(t.push(r),2023<=M)throw $(r,"id")}}while(N(",",!0));var i={options:rt,setOption:function(t,e){this.options===rt&&(this.options={}),this.options[t]=e}};q(i,function(t){if("option"!==t)throw $(t);tt(i,t),N(";")},function(){nt(i)})}function K(t,e){switch(t){case"max":case"MAX":case"Max":return 536870911;case"0":return 0}if(e||"-"!=(t[0]||"")){if(_.test(t))return parseInt(t,10);if(y.test(t))return parseInt(t,16);if(A.test(t))return parseInt(t,8)}throw $(t,"id")}function X(t,e){switch(e){case"option":return tt(t,e),N(";"),1;case"message":return Z(t),1;case"enum":return Q(t),1;case"service":var n,r,i=t;if(E.test(r=k()))return q(n=new d(r),function(t){if(!X(n,t)){if("rpc"!==t)throw $(t);var e=n,r=L(),i=t;if(!E.test(t=k()))throw $(t,"name");var s,a,o,l=t;if(N("("),N("stream",!0)&&(a=!0),!b.test(t=k()))throw $(t);if(s=t,N(")"),N("returns"),N("("),N("stream",!0)&&(o=!0),!b.test(t=k()))throw $(t);N(")");var c=new h(l,i,s,t,a,o);c.comment=r,q(c,function(t){if("option"!==t)throw $(t);tt(c,t),N(";")}),e.add(c)}}),i.add(n),i===G&&z.push(n),1;throw $(r,"service name");case"extend":var s,a=t;if(i=e,b.test(i=k()))return s=i,q(null,function(t){switch(t){case"required":case"repeated":J(a,t,s);break;case"optional":J(a,"proto3"===M?"proto3_optional":"optional",s);break;default:if("proto2"===M||!b.test(t))throw $(t);O(t),J(a,"optional",s)}}),1;throw $(i,"reference")}}function q(t,e,n){var r,i=P.line;if(t&&("string"!=typeof t.comment&&(t.comment=L()),t.filename=T.filename),N("{",!0)){for(;"}"!==(r=k());)e(r);N(";",!0)}else n&&n(),N(";"),t&&("string"!=typeof t.comment||D)&&(t.comment=L(i)||t.comment)}function Z(t,e){if(!E.test(e=k()))throw $(e,"type name");var n=new s(e);q(n,function(t){if(!X(n,t))switch(t){case"map":var e=n,r=(N("<"),k());if(p.mapKey[r]===rt)throw $(r,"type");N(",");var i=k();if(!b.test(i))throw $(i,"type");N(">");var s=k();if(!E.test(s))throw $(s,"name");N("=");var a=new o(H(s),K(k()),r,i);q(a,function(t){if("option"!==t)throw $(t);tt(a,t),N(";")},function(){nt(a)}),e.add(a);break;case"required":if("proto2"!==M)throw $(t);case"repeated":J(n,t);break;case"optional":if("proto3"===M)J(n,"proto3_optional");else{if("proto2"!==M)throw $(t);J(n,"optional")}break;case"oneof":if(s=n,r=t,!E.test(r=k()))throw $(r,"name");var c=new l(H(r));q(c,function(t){"option"===t?(tt(c,t),N(";")):(O(t),J(c,"optional"))}),s.add(c);break;case"extensions":Y(n.extensions||(n.extensions=[]));break;case"reserved":Y(n.reserved||(n.reserved=[]),!0);break;default:if("proto2"===M||!b.test(t))throw $(t);O(t),J(n,"optional")}}),t.add(n),t===G&&z.push(n)}function J(t,e,n){var r=k();if("group"===r){var i=t,o=e;if(2023<=M)throw $("group");var c,d,h=k();if(E.test(h))return h===(d=f.lcFirst(h))&&(h=f.ucFirst(h)),N("="),u=K(k()),(c=new s(h)).group=!0,(d=new a(d,u,h,o)).filename=T.filename,q(c,function(t){switch(t){case"option":tt(c,t),N(";");break;case"required":case"repeated":J(c,t);break;case"optional":J(c,"proto3"===M?"proto3_optional":"optional");break;case"message":Z(c);break;case"enum":Q(c);break;case"reserved":Y(c.reserved||(c.reserved=[]),!0);break;default:throw $(t)}}),void i.add(c).add(d);throw $(h,"name")}for(;r.endsWith(".")||U().startsWith(".");)r+=k();if(!b.test(r))throw $(r,"type");var u=k();if(!E.test(u))throw $(u,"name");u=H(u),N("=");var p=new a(u,K(k()),r,e,n);q(p,function(t){if("option"!==t)throw $(t);tt(p,t),N(";")},function(){nt(p)}),"proto3_optional"===e?(o=new l("_"+u),p.setOption("proto3_optional",!0),o.add(p),t.add(o)):t.add(p),t===G&&z.push(p)}function Q(t,e){if(!E.test(e=k()))throw $(e,"name");var n=new c(e);q(n,function(t){switch(t){case"option":tt(n,t),N(";");break;case"reserved":Y(n.reserved||(n.reserved=[]),!0),n.reserved===rt&&(n.reserved=[]);break;default:var e=n,r=t;if(!E.test(r))throw $(r,"name");N("=");var i=K(k(),!0),s={options:rt,getOption:function(t){return this.options[t]},setOption:function(t,e){u.prototype.setOption.call(s,t,e)},setParsedOption:function(){return rt}};return q(s,function(t){if("option"!==t)throw $(t);tt(s,t),N(";")},function(){nt(s)}),void e.add(r,i,s.comment,s.parsedOptions||s.options)}}),t.add(n),t===G&&z.push(n)}function tt(t,e){var n=!0;for("option"===e&&(e=k());"="!==e;){if("("===e&&(r=k(),N(")"),e="("+r+")"),n){if(n=!1,e.includes(".")&&!e.includes("(")){var r=e.split("."),i=r[0]+".";e=r[1];continue}i=e}else a=a?a+e:e;e=k()}var s=function t(e,n){if(N("{",!0)){for(var r={};!N("}",!0);){if(!E.test(R=k()))throw $(R,"name");if(null===R)throw $(R,"end of input");var i,s,a=R;if(N(":",!0),"{"===U())i=t(e,n+"."+R);else if("["===U()){if(i=[],N("[",!0)){for(;s=V(!0),i.push(s),N(",",!0););N("]"),void 0!==s&&et(e,n+"."+R,s)}}else i=V(!0),et(e,n+"."+R,i);var o=r[a];o&&(i=[].concat(o).concat(i)),r[a]=i,N(",",!0),N(";",!0)}return r}var l=V(!0);return et(e,n,l),l}(t,s=a?i.concat(a):i),a=a&&"."===a[0]?a.slice(1):a;i=i&&"."===i[i.length-1]?i.slice(0,-1):i,t.setParsedOption&&t.setParsedOption(i,s,a)}function et(t,e,n){G===t&&/^features\./.test(e)?W[e]=n:t.setOption&&t.setOption(e,n)}function nt(t){if(N("[",!0)){for(;tt(t,"option"),N(",",!0););N("]")}}for(;null!==(R=k());)switch(R){case"package":if(!F)throw $(R);if(w!==rt)throw $("package");if(w=k(),!b.test(w))throw $(w,"name");G=G.define(w),N(";");break;case"import":if(!F)throw $(R);switch(B=void 0,U()){case"weak":B=I=I||[],k();break;case"public":k();default:B=x=x||[]}C=j(),N(";"),B.push(C);break;case"syntax":if(!F)throw $(R);if(N("="),(M=j())<2023)throw $(M,"syntax");N(";");break;case"edition":if(!F)throw $(R);if(N("="),M=j(),!["2023"].includes(M))throw $(M,"edition");N(";");break;case"option":tt(G,R),N(";",!0);break;default:if(X(G,R)){F=!1;continue}throw $(R)}return z.forEach(t=>{t.f=M,Object.keys(W).forEach(e=>{t.getOption(e)===rt&&t.setOption(e,W[e],!0)})}),T.filename=null,{package:w,imports:x,weakImports:I,root:e}}},{15:15,16:16,20:20,22:22,24:24,25:25,29:29,33:33,34:34,35:35,36:36,37:37}],27:[function(t,e,n){e.exports=l;var r,i=t(39),s=i.LongBits,a=i.utf8;function o(t,e){return RangeError("index out of range: "+t.pos+" + "+(e||1)+" > "+t.len)}function l(t){this.buf=t,this.pos=0,this.len=t.length}function c(){return i.Buffer?function(t){return(l.create=function(t){return i.Buffer.isBuffer(t)?new r(t):h(t)})(t)}:h}var d,h="undefined"!=typeof Uint8Array?function(t){if(t instanceof Uint8Array||Array.isArray(t))return new l(t);throw Error("illegal buffer")}:function(t){if(Array.isArray(t))return new l(t);throw Error("illegal buffer")};function u(){var t=new s(0,0),e=0;if(!(4<this.len-this.pos)){for(;e<3;++e){if(this.pos>=this.len)throw o(this);if(t.lo=(t.lo|(127&this.buf[this.pos])<<7*e)>>>0,this.buf[this.pos++]<128)return t}return t.lo=(t.lo|(127&this.buf[this.pos++])<<7*e)>>>0,t}for(;e<4;++e)if(t.lo=(t.lo|(127&this.buf[this.pos])<<7*e)>>>0,this.buf[this.pos++]<128)return t;if(t.lo=(t.lo|(127&this.buf[this.pos])<<28)>>>0,t.hi=(t.hi|(127&this.buf[this.pos])>>4)>>>0,this.buf[this.pos++]<128)return t;if(e=0,4<this.len-this.pos){for(;e<5;++e)if(t.hi=(t.hi|(127&this.buf[this.pos])<<7*e+3)>>>0,this.buf[this.pos++]<128)return t}else for(;e<5;++e){if(this.pos>=this.len)throw o(this);if(t.hi=(t.hi|(127&this.buf[this.pos])<<7*e+3)>>>0,this.buf[this.pos++]<128)return t}throw Error("invalid varint encoding")}function p(t,e){return(t[e-4]|t[e-3]<<8|t[e-2]<<16|t[e-1]<<24)>>>0}function f(){if(this.pos+8>this.len)throw o(this,8);return new s(p(this.buf,this.pos+=4),p(this.buf,this.pos+=4))}l.create=c(),l.prototype._=i.Array.prototype.subarray||i.Array.prototype.slice,l.prototype.uint32=(d=4294967295,function(){if(d=(127&this.buf[this.pos])>>>0,this.buf[this.pos++]<128||(d=(d|(127&this.buf[this.pos])<<7)>>>0,this.buf[this.pos++]<128||(d=(d|(127&this.buf[this.pos])<<14)>>>0,this.buf[this.pos++]<128||(d=(d|(127&this.buf[this.pos])<<21)>>>0,this.buf[this.pos++]<128||(d=(d|(15&this.buf[this.pos])<<28)>>>0,this.buf[this.pos++]<128||!((this.pos+=5)>this.len))))))return d;throw this.pos=this.len,o(this,10)}),l.prototype.int32=function(){return 0|this.uint32()},l.prototype.sint32=function(){var t=this.uint32();return t>>>1^-(1&t)},l.prototype.bool=function(){return 0!==this.uint32()},l.prototype.fixed32=function(){if(this.pos+4>this.len)throw o(this,4);return p(this.buf,this.pos+=4)},l.prototype.sfixed32=function(){if(this.pos+4>this.len)throw o(this,4);return 0|p(this.buf,this.pos+=4)},l.prototype.float=function(){if(this.pos+4>this.len)throw o(this,4);var t=i.float.readFloatLE(this.buf,this.pos);return this.pos+=4,t},l.prototype.double=function(){if(this.pos+8>this.len)throw o(this,4);var t=i.float.readDoubleLE(this.buf,this.pos);return this.pos+=8,t},l.prototype.bytes=function(){var t=this.uint32(),e=this.pos,n=this.pos+t;if(n>this.len)throw o(this,t);return this.pos+=t,Array.isArray(this.buf)?this.buf.slice(e,n):e===n?(t=i.Buffer)?t.alloc(0):new this.buf.constructor(0):this._.call(this.buf,e,n)},l.prototype.string=function(){var t=this.bytes();return a.read(t,0,t.length)},l.prototype.skip=function(t){if("number"==typeof t){if(this.pos+t>this.len)throw o(this,t);this.pos+=t}else do{if(this.pos>=this.len)throw o(this)}while(128&this.buf[this.pos++]);return this},l.prototype.skipType=function(t){switch(t){case 0:this.skip();break;case 1:this.skip(8);break;case 2:this.skip(this.uint32());break;case 3:for(;4!=(t=7&this.uint32());)this.skipType(t);break;case 5:this.skip(4);break;default:throw Error("invalid wire type "+t+" at offset "+this.pos)}return this},l.p=function(t){r=t,l.create=c(),r.p();var e=i.Long?"toLong":"toNumber";i.merge(l.prototype,{int64:function(){return u.call(this)[e](!1)},uint64:function(){return u.call(this)[e](!0)},sint64:function(){return u.call(this).zzDecode()[e](!1)},fixed64:function(){return f.call(this)[e](!0)},sfixed64:function(){return f.call(this)[e](!1)}})}},{39:39}],28:[function(t,e,n){e.exports=s;var r=t(27),i=((s.prototype=Object.create(r.prototype)).constructor=s,t(39));function s(t){r.call(this,t)}s.p=function(){i.Buffer&&(s.prototype._=i.Buffer.prototype.slice)},s.prototype.string=function(){var t=this.uint32();return this.buf.utf8Slice?this.buf.utf8Slice(this.pos,this.pos=Math.min(this.pos+t,this.len)):this.buf.toString("utf-8",this.pos,this.pos=Math.min(this.pos+t,this.len))},s.p()},{27:27,39:39}],29:[function(t,e,n){e.exports=h;var r,i,s,a=t(23),o=(((h.prototype=Object.create(a.prototype)).constructor=h).className="Root",t(16)),l=t(15),c=t(25),d=t(37);function h(t){a.call(this,"",t),this.deferred=[],this.files=[],this.f="proto2",this.j={}}function u(){}h.fromJSON=function(t,e){return e=e||new h,t.options&&e.setOptions(t.options),e.addJSON(t.nested).resolveAll()},h.prototype.resolvePath=d.path.resolve,h.prototype.fetch=d.fetch,h.prototype.load=function t(e,n,r){"function"==typeof n&&(r=n,n=rt);var a=this;if(!r)return d.asPromise(t,a,e,n);var o=r===u;function l(t,e){if(r){if(o)throw t;e&&e.resolveAll();var n=r;r=null,n(t,e)}}function c(t){var e=t.lastIndexOf("google/protobuf/");return-1<e&&(t=t.substring(e))in s?t:null}function h(t,e){try{if(d.isString(e)&&"{"==(e[0]||"")&&(e=JSON.parse(e)),d.isString(e)){i.filename=t;var r,s=i(e,a,n),h=0;if(s.imports)for(;h<s.imports.length;++h)(r=c(s.imports[h])||a.resolvePath(t,s.imports[h]))&&p(r);if(s.weakImports)for(h=0;h<s.weakImports.length;++h)(r=c(s.weakImports[h])||a.resolvePath(t,s.weakImports[h]))&&p(r,!0)}else a.setOptions(e.options).addJSON(e.nested)}catch(t){l(t)}o||f||l(null,a)}function p(t,e){if(t=c(t)||t,!~a.files.indexOf(t))if(a.files.push(t),t in s)o?h(t,s[t]):(++f,setTimeout(function(){--f,h(t,s[t])}));else if(o){var n;try{n=d.fs.readFileSync(t).toString("utf8")}catch(n){return void(e||l(n))}h(t,n)}else++f,a.fetch(t,function(n,i){--f,r&&(n?e?f||l(null,a):l(n):h(t,i))})}var f=0;d.isString(e)&&(e=[e]);for(var m,_=0;_<e.length;++_)(m=a.resolvePath("",e[_]))&&p(m);return o?a.resolveAll():f||l(null,a),a},h.prototype.loadSync=function(t,e){if(d.isNode)return this.load(t,e,u);throw Error("not supported")},h.prototype.resolveAll=function(){if(!this.y)return this;if(this.deferred.length)throw Error("unresolvable extensions: "+this.deferred.map(function(t){return"'extend "+t.extend+"' in "+t.parent.fullName}).join(", "));return a.prototype.resolveAll.call(this)};var p=/^[A-Z]/;function f(t,e){var n,r=e.parent.lookup(e.extend);if(r)return n=new o(e.fullName,e.id,e.type,e.rule,rt,e.options),r.get(n.name)||((n.declaringField=e).extensionField=n,r.add(n)),1}h.prototype.A=function(t){if(t instanceof o)t.extend===rt||t.extensionField||f(0,t)||this.deferred.push(t);else if(t instanceof l)p.test(t.name)&&(t.parent[t.name]=t.values);else if(!(t instanceof c)){if(t instanceof r)for(var e=0;e<this.deferred.length;)f(0,this.deferred[e])?this.deferred.splice(e,1):++e;for(var n=0;n<t.nestedArray.length;++n)this.A(t.v[n]);p.test(t.name)&&(t.parent[t.name]=t)}(t instanceof r||t instanceof l||t instanceof o)&&(this.j[t.fullName]=t)},h.prototype.T=function(t){var e;if(t instanceof o)t.extend!==rt&&(t.extensionField?(t.extensionField.parent.remove(t.extensionField),t.extensionField=null):-1<(e=this.deferred.indexOf(t))&&this.deferred.splice(e,1));else if(t instanceof l)p.test(t.name)&&delete t.parent[t.name];else if(t instanceof a){for(var n=0;n<t.nestedArray.length;++n)this.T(t.v[n]);p.test(t.name)&&delete t.parent[t.name]}delete this.j[t.fullName]},h.p=function(t,e,n){r=t,i=e,s=n}},{15:15,16:16,23:23,25:25,37:37}],30:[function(t,e,n){e.exports={}},{}],31:[function(t,e,n){n.Service=t(32)},{32:32}],32:[function(t,e,n){e.exports=i;var r=t(39);function i(t,e,n){if("function"!=typeof t)throw TypeError("rpcImpl must be a function");r.EventEmitter.call(this),this.rpcImpl=t,this.requestDelimited=!!e,this.responseDelimited=!!n}((i.prototype=Object.create(r.EventEmitter.prototype)).constructor=i).prototype.rpcCall=function t(e,n,i,s,a){if(!s)throw TypeError("request must be specified");var o=this;if(!a)return r.asPromise(t,o,e,n,i,s);if(!o.rpcImpl)return setTimeout(function(){a(Error("already ended"))},0),rt;try{return o.rpcImpl(e,n[o.requestDelimited?"encodeDelimited":"encode"](s).finish(),function(t,n){if(t)return o.emit("error",t,e),a(t);if(null===n)return o.end(!0),rt;if(!(n instanceof i))try{n=i[o.responseDelimited?"decodeDelimited":"decode"](n)}catch(t){return o.emit("error",t,e),a(t)}return o.emit("data",n,e),a(null,n)})}catch(t){return o.emit("error",t,e),setTimeout(function(){a(t)},0),rt}},i.prototype.end=function(t){return this.rpcImpl&&(t||this.rpcImpl(null,null,null),this.rpcImpl=null,this.emit("end").off()),this}},{39:39}],33:[function(t,e,n){e.exports=o;var r=t(23),i=(((o.prototype=Object.create(r.prototype)).constructor=o).className="Service",t(22)),s=t(37),a=t(31);function o(t,e){r.call(this,t,e),this.methods={},this.x=null}function l(t){return t.x=null,t}o.fromJSON=function(t,e){var n=new o(t,e.options);if(e.methods)for(var r=Object.keys(e.methods),s=0;s<r.length;++s)n.add(i.fromJSON(r[s],e.methods[r[s]]));return e.nested&&n.addJSON(e.nested),e.edition&&(n.f=e.edition),n.comment=e.comment,n.a="proto3",n},o.prototype.toJSON=function(t){var e=r.prototype.toJSON.call(this,t),n=!!t&&!!t.keepComments;return s.toObject(["edition",this.c(),"options",e&&e.options||rt,"methods",r.arrayToJSON(this.methodsArray,t)||{},"nested",e&&e.nested||rt,"comment",n?this.comment:rt])},Object.defineProperty(o.prototype,"methodsArray",{get:function(){return this.x||(this.x=s.toArray(this.methods))}}),o.prototype.get=function(t){return this.methods[t]||r.prototype.get.call(this,t)},o.prototype.resolveAll=function(){if(this.y){r.prototype.resolve.call(this);for(var t=this.methodsArray,e=0;e<t.length;++e)t[e].resolve()}return this},o.prototype.g=function(t){return this.w&&(r.prototype.g.call(this,t=this.f||t),this.methodsArray.forEach(e=>{e.g(t)})),this},o.prototype.add=function(t){if(this.get(t.name))throw Error("duplicate name '"+t.name+"' in "+this);return t instanceof i?l((this.methods[t.name]=t).parent=this):r.prototype.add.call(this,t)},o.prototype.remove=function(t){if(t instanceof i){if(this.methods[t.name]!==t)throw Error(t+" is not a member of "+this);return delete this.methods[t.name],t.parent=null,l(this)}return r.prototype.remove.call(this,t)},o.prototype.create=function(t,e,n){for(var r,i=new a.Service(t,e,n),o=0;o<this.methodsArray.length;++o){var l=s.lcFirst((r=this.x[o]).resolve().name).replace(/[^$\w_]/g,"");i[l]=s.codegen(["r","c"],s.isReserved(l)?l+"_":l)("return this.rpcCall(m,q,s,r,c)")({m:r,q:r.resolvedRequestType.ctor,s:r.resolvedResponseType.ctor})}return i}},{22:22,23:23,31:31,37:37}],34:[function(t,e,n){e.exports=p;var r=/[\s{}=;:[\],'"()<>]/g,i=/(?:"([^"\\]*(?:\\.[^"\\]*)*)")/g,s=/(?:'([^'\\]*(?:\\.[^'\\]*)*)')/g,a=/^ *[*/]+ */,o=/^\s*\*?\/*/,l=/\n/g,c=/\s/,d=/\\(.?)/g,h={0:"\0",r:"\r",n:"\n",t:"\t"};function u(t){return t.replace(d,function(t,e){switch(e){case"\\":case"":return e;default:return h[e]||""}})}function p(t,e){t=t.toString();var n=0,d=t.length,h=1,p=0,f={},m=[],_=null;function g(t){return Error("illegal "+t+" (line "+h+")")}function y(e){return t[0|e]||""}function S(n,r,i){var s,c={type:t[0|n++]||"",lineEmpty:!1,leading:i},d=n-(i=e?2:3);do{if(--d<0||"\n"==(s=t[0|d]||"")){c.lineEmpty=!0;break}}while(" "===s||"\t"===s);for(var u=t.substring(n,r).split(l),m=0;m<u.length;++m)u[m]=u[m].replace(e?o:a,"").trim();c.text=u.join("\n").trim(),f[h]=c,p=h}function A(e){var n=v(e);return e=t.substring(e,n),/^\s*\/\//.test(e)}function v(t){for(var e=t;e<d&&"\n"!==y(e);)e++;return e}function E(){if(0<m.length)return m.shift();if(_){var a="'"===_?s:i,o=(a.lastIndex=n-1,a.exec(t));if(o)return n=a.lastIndex,b(_),_=null,u(o[1]);throw g("string")}var l,p,f,E,T,w=0===n;do{if(n===d)return null;for(l=!1;c.test(f=y(n));)if("\n"===f&&(w=!0,++h),++n===d)return null;if("/"===y(n)){if(++n===d)throw g("comment");if("/"===y(n))if(e){if(T=!1,A((E=n)-1))for(T=!0;(n=v(n))!==d&&(n++,w&&A(n)););else n=Math.min(d,v(n)+1);T&&(S(E,n,w),w=!0),h++}else{for(T="/"===y(E=n+1);"\n"!==y(++n);)if(n===d)return null;++n,T&&(S(E,n-1,w),w=!0),++h}else{if("*"!==(f=y(n)))return"/";E=n+1,T=e||"*"===y(E);do{if("\n"===f&&++h,++n===d)throw g("comment")}while(p=f,f=y(n),"*"!==p||"/"!==f);++n,T&&(S(E,n-2,w),w=!0)}l=!0}}while(l);var x=n;if(r.lastIndex=0,!r.test(y(x++)))for(;x<d&&!r.test(y(x));)++x;return'"'!=(a=t.substring(n,n=x))&&"'"!=a||(_=a),a}function b(t){m.push(t)}function T(){if(!m.length){var t=E();if(null===t)return null;b(t)}return m[0]}return Object.defineProperty({next:E,peek:T,push:b,skip:function(t,e){var n=T();if(n===t)return E(),!0;if(e)return!1;throw g("token '"+n+"', '"+t+"' expected")},cmnt:function(t){var n,r=null;return t===rt?(n=f[h-1],delete f[h-1],n&&(e||"*"===n.type||n.lineEmpty)&&(r=n.leading?n.text:null)):(p<t&&T(),n=f[t],delete f[t],!n||n.lineEmpty||!e&&"/"!==n.type||(r=n.leading?null:n.text)),r}},"line",{get:function(){return h}})}p.unescape=u},{}],35:[function(t,e,n){e.exports=y;var r=t(23),i=(((y.prototype=Object.create(r.prototype)).constructor=y).className="Type",t(15)),s=t(25),a=t(16),o=t(20),l=t(33),c=t(21),d=t(27),h=t(42),u=t(37),p=t(14),f=t(13),m=t(40),_=t(12),g=t(41);function y(t,e){r.call(this,t,e),this.fields={},this.oneofs=rt,this.extensions=rt,this.reserved=rt,this.group=rt,this.S=null,this.e=null,this.I=null,this.N=null}function S(t){return t.S=t.e=t.I=null,delete t.encode,delete t.decode,delete t.verify,t}Object.defineProperties(y.prototype,{fieldsById:{get:function(){if(!this.S){this.S={};for(var t=Object.keys(this.fields),e=0;e<t.length;++e){var n=this.fields[t[e]],r=n.id;if(this.S[r])throw Error("duplicate id "+r+" in "+this);this.S[r]=n}}return this.S}},fieldsArray:{get:function(){return this.e||(this.e=u.toArray(this.fields))}},oneofsArray:{get:function(){return this.I||(this.I=u.toArray(this.oneofs))}},ctor:{get:function(){return this.N||(this.ctor=y.generateConstructor(this)())},set:function(t){for(var e=t.prototype,n=(e instanceof c||((t.prototype=new c).constructor=t,u.merge(t.prototype,e)),t.$type=t.prototype.$type=this,u.merge(t,c,!0),this.N=t,0);n<this.fieldsArray.length;++n)this.e[n].resolve();var r={};for(n=0;n<this.oneofsArray.length;++n)r[this.I[n].resolve().name]={get:u.oneOfGetter(this.I[n].oneof),set:u.oneOfSetter(this.I[n].oneof)};n&&Object.defineProperties(t.prototype,r)}}}),y.generateConstructor=function(t){for(var e,n=u.codegen(["p"],t.name),r=0;r<t.fieldsArray.length;++r)(e=t.e[r]).map?n("this%s={}",u.safeProp(e.name)):e.repeated&&n("this%s=[]",u.safeProp(e.name));return n("if(p)for(var ks=Object.keys(p),i=0;i<ks.length;++i)if(p[ks[i]]!=null)")("this[ks[i]]=p[ks[i]]")},y.fromJSON=function(t,e){for(var n=new y(t,e.options),c=(n.extensions=e.extensions,n.reserved=e.reserved,Object.keys(e.fields)),d=0;d<c.length;++d)n.add((void 0!==e.fields[c[d]].keyType?o:a).fromJSON(c[d],e.fields[c[d]]));if(e.oneofs)for(c=Object.keys(e.oneofs),d=0;d<c.length;++d)n.add(s.fromJSON(c[d],e.oneofs[c[d]]));if(e.nested)for(c=Object.keys(e.nested),d=0;d<c.length;++d){var h=e.nested[c[d]];n.add((h.id!==rt?a:h.fields!==rt?y:h.values!==rt?i:h.methods!==rt?l:r).fromJSON(c[d],h))}return e.extensions&&e.extensions.length&&(n.extensions=e.extensions),e.reserved&&e.reserved.length&&(n.reserved=e.reserved),e.group&&(n.group=!0),e.comment&&(n.comment=e.comment),e.edition&&(n.f=e.edition),n.a="proto3",n},y.prototype.toJSON=function(t){var e=r.prototype.toJSON.call(this,t),n=!!t&&!!t.keepComments;return u.toObject(["edition",this.c(),"options",e&&e.options||rt,"oneofs",r.arrayToJSON(this.oneofsArray,t),"fields",r.arrayToJSON(this.fieldsArray.filter(function(t){return!t.declaringField}),t)||{},"extensions",this.extensions&&this.extensions.length?this.extensions:rt,"reserved",this.reserved&&this.reserved.length?this.reserved:rt,"group",this.group||rt,"nested",e&&e.nested||rt,"comment",n?this.comment:rt])},y.prototype.resolveAll=function(){if(this.y){r.prototype.resolveAll.call(this);for(var t=this.oneofsArray,e=0;e<t.length;)t[e++].resolve();var n=this.fieldsArray;for(e=0;e<n.length;)n[e++].resolve()}return this},y.prototype.g=function(t){return this.w&&(r.prototype.g.call(this,t=this.f||t),this.oneofsArray.forEach(e=>{e.u(t)}),this.fieldsArray.forEach(e=>{e.u(t)})),this},y.prototype.get=function(t){return this.fields[t]||this.oneofs&&this.oneofs[t]||this.nested&&this.nested[t]||null},y.prototype.add=function(t){if(this.get(t.name))throw Error("duplicate name '"+t.name+"' in "+this);if(t instanceof a&&t.extend===rt){if((this.S||this.fieldsById)[t.id])throw Error("duplicate id "+t.id+" in "+this);if(this.isReservedId(t.id))throw Error("id "+t.id+" is reserved in "+this);if(this.isReservedName(t.name))throw Error("name '"+t.name+"' is reserved in "+this);return t.parent&&t.parent.remove(t),(this.fields[t.name]=t).message=this,t.onAdd(this),S(this)}return t instanceof s?(this.oneofs||(this.oneofs={}),(this.oneofs[t.name]=t).onAdd(this),S(this)):r.prototype.add.call(this,t)},y.prototype.remove=function(t){if(t instanceof a&&t.extend===rt){if(this.fields&&this.fields[t.name]===t)return delete this.fields[t.name],t.parent=null,t.onRemove(this),S(this);throw Error(t+" is not a member of "+this)}if(t instanceof s){if(this.oneofs&&this.oneofs[t.name]===t)return delete this.oneofs[t.name],t.parent=null,t.onRemove(this),S(this);throw Error(t+" is not a member of "+this)}return r.prototype.remove.call(this,t)},y.prototype.isReservedId=function(t){return r.isReservedId(this.reserved,t)},y.prototype.isReservedName=function(t){return r.isReservedName(this.reserved,t)},y.prototype.create=function(t){return new this.ctor(t)},y.prototype.setup=function(){for(var t=this.fullName,e=[],n=0;n<this.fieldsArray.length;++n)e.push(this.e[n].resolve().resolvedType);var r;return this.encode=p(this)({Writer:h,types:e,util:u}),this.decode=f(this)({Reader:d,types:e,util:u}),this.verify=m(this)({types:e,util:u}),this.fromObject=_.fromObject(this)({types:e,util:u}),this.toObject=_.toObject(this)({types:e,util:u}),(t=g[t])&&((r=Object.create(this)).fromObject=this.fromObject,this.fromObject=t.fromObject.bind(r),r.toObject=this.toObject,this.toObject=t.toObject.bind(r)),this},y.prototype.encode=function(t,e){return this.setup().encode(t,e)},y.prototype.encodeDelimited=function(t,e){return this.encode(t,e&&e.len?e.fork():e).ldelim()},y.prototype.decode=function(t,e){return this.setup().decode(t,e)},y.prototype.decodeDelimited=function(t){return t instanceof d||(t=d.create(t)),this.decode(t,t.uint32())},y.prototype.verify=function(t){return this.setup().verify(t)},y.prototype.fromObject=function(t){return this.setup().fromObject(t)},y.prototype.toObject=function(t,e){return this.setup().toObject(t,e)},y.d=function(t){return function(e){u.decorateType(e,t)}}},{12:12,13:13,14:14,15:15,16:16,20:20,21:21,23:23,25:25,27:27,33:33,37:37,40:40,41:41,42:42}],36:[function(t,e,n){t=t(37);var r=["double","float","int32","uint32","sint32","fixed32","sfixed32","int64","uint64","sint64","fixed64","sfixed64","bool","string","bytes"];function i(t,e){var n=0,i={};for(e|=0;n<t.length;)i[r[n+e]]=t[n++];return i}n.basic=i([1,5,0,0,0,5,5,0,0,0,1,1,0,2,2]),n.defaults=i([0,0,0,0,0,0,0,0,0,0,0,0,!1,"",t.emptyArray,null]),n.long=i([0,0,0,1,1],7),n.mapKey=i([0,0,0,5,5,0,0,0,1,1,0,2],2),n.packed=i([1,5,0,0,0,5,5,0,0,0,1,1,0])},{37:37}],37:[function(t,e,n){var r,i,s=e.exports=t(39),a=t(30),o=(s.codegen=t(3),s.fetch=t(5),s.path=t(8),s.fs=s.inquire("fs"),s.toArray=function(t){if(t){for(var e=Object.keys(t),n=Array(e.length),r=0;r<e.length;)n[r]=t[e[r++]];return n}return[]},s.toObject=function(t){for(var e={},n=0;n<t.length;){var r=t[n++],i=t[n++];i!==rt&&(e[r]=i)}return e},/\\/g),l=/"/g,c=(s.isReserved=function(t){return/^(?:do|if|in|for|let|new|try|var|case|else|enum|eval|false|null|this|true|void|with|break|catch|class|const|super|throw|while|yield|delete|export|import|public|return|static|switch|typeof|default|extends|finally|package|private|continue|debugger|function|arguments|interface|protected|implements|instanceof)$/.test(t)},s.safeProp=function(t){return!/^[$\w_]+$/.test(t)||s.isReserved(t)?'["'+t.replace(o,"\\\\").replace(l,'\\"')+'"]':"."+t},s.ucFirst=function(t){return(t[0]||"").toUpperCase()+t.substring(1)},/_([a-z])/g),d=(s.camelCase=function(t){return t.substring(0,1)+t.substring(1).replace(c,function(t,e){return e.toUpperCase()})},s.compareFieldsById=function(t,e){return t.id-e.id},s.decorateType=function(e,n){return e.$type?(n&&e.$type.name!==n&&(s.decorateRoot.remove(e.$type),e.$type.name=n,s.decorateRoot.add(e.$type)),e.$type):(n=new(r=r||t(35))(n||e.name),s.decorateRoot.add(n),n.ctor=e,Object.defineProperty(e,"$type",{value:n,enumerable:!1}),Object.defineProperty(e.prototype,"$type",{value:n,enumerable:!1}),n)},0);s.decorateEnum=function(e){var n;return e.$type||(n=new(i=i||t(15))("Enum"+d++,e),s.decorateRoot.add(n),Object.defineProperty(e,"$type",{value:n,enumerable:!1}),n)},s.setProperty=function(t,e,n,r){if("object"!=typeof t)throw TypeError("dst must be an object");if(e)return function t(e,n,i){var s=n.shift();if("__proto__"!==s&&"prototype"!==s)if(0<n.length)e[s]=t(e[s]||{},n,i);else{if((n=e[s])&&r)return e;n&&(i=[].concat(n).concat(i)),e[s]=i}return e}(t,e=e.split("."),n);throw TypeError("path must be specified")},Object.defineProperty(s,"decorateRoot",{get:function(){return a.decorated||(a.decorated=new(t(29)))}})},{15:15,29:29,3:3,30:30,35:35,39:39,5:5,8:8}],38:[function(t,e,n){e.exports=i;var r=t(39);function i(t,e){this.lo=t>>>0,this.hi=e>>>0}var s=i.zero=new i(0,0),a=(s.toNumber=function(){return 0},s.zzEncode=s.zzDecode=function(){return this},s.length=function(){return 1},i.zeroHash="\0\0\0\0\0\0\0\0",i.fromNumber=function(t){var e,n;return 0===t?s:(n=(t=(e=t<0)?-t:t)>>>0,t=(t-n)/4294967296>>>0,e&&(t=~t>>>0,n=~n>>>0,4294967295<++n&&(n=0,4294967295<++t&&(t=0))),new i(n,t))},i.from=function(t){if("number"==typeof t)return i.fromNumber(t);if(r.isString(t)){if(!r.Long)return i.fromNumber(parseInt(t,10));t=r.Long.fromString(t)}return t.low||t.high?new i(t.low>>>0,t.high>>>0):s},i.prototype.toNumber=function(t){var e;return!t&&this.hi>>>31?(e=~this.hi>>>0,-((t=1+~this.lo>>>0)+4294967296*(e=t?e:e+1>>>0))):this.lo+4294967296*this.hi},i.prototype.toLong=function(t){return r.Long?new r.Long(0|this.lo,0|this.hi,!!t):{low:0|this.lo,high:0|this.hi,unsigned:!!t}},String.prototype.charCodeAt);i.fromHash=function(t){return"\0\0\0\0\0\0\0\0"===t?s:new i((a.call(t,0)|a.call(t,1)<<8|a.call(t,2)<<16|a.call(t,3)<<24)>>>0,(a.call(t,4)|a.call(t,5)<<8|a.call(t,6)<<16|a.call(t,7)<<24)>>>0)},i.prototype.toHash=function(){return String.fromCharCode(255&this.lo,this.lo>>>8&255,this.lo>>>16&255,this.lo>>>24,255&this.hi,this.hi>>>8&255,this.hi>>>16&255,this.hi>>>24)},i.prototype.zzEncode=function(){var t=this.hi>>31;return this.hi=((this.hi<<1|this.lo>>>31)^t)>>>0,this.lo=(this.lo<<1^t)>>>0,this},i.prototype.zzDecode=function(){var t=-(1&this.lo);return this.lo=((this.lo>>>1|this.hi<<31)^t)>>>0,this.hi=(this.hi>>>1^t)>>>0,this},i.prototype.length=function(){var t=this.lo,e=(this.lo>>>28|this.hi<<4)>>>0,n=this.hi>>>24;return 0==n?0==e?t<16384?t<128?1:2:t<2097152?3:4:e<16384?e<128?5:6:e<2097152?7:8:n<128?9:10}},{39:39}],39:[function(t,e,n){var r=n;function i(t,e,n){for(var r=Object.keys(e),i=0;i<r.length;++i)t[r[i]]!==rt&&n||(t[r[i]]=e[r[i]]);return t}function s(t){function e(t,n){if(!(this instanceof e))return new e(t,n);Object.defineProperty(this,"message",{get:function(){return t}}),Error.captureStackTrace?Error.captureStackTrace(this,e):Object.defineProperty(this,"stack",{value:Error().stack||""}),n&&i(this,n)}return e.prototype=Object.create(Error.prototype,{constructor:{value:e,writable:!0,enumerable:!1,configurable:!0},name:{get:function(){return t},set:rt,enumerable:!1,configurable:!0},toString:{value:function(){return this.name+": "+this.message},writable:!0,enumerable:!1,configurable:!0}}),e}r.asPromise=t(1),r.base64=t(2),r.EventEmitter=t(4),r.float=t(6),r.inquire=t(7),r.utf8=t(10),r.pool=t(9),r.LongBits=t(38),r.isNode=!!("undefined"!=typeof global&&global&&global.process&&global.process.versions&&global.process.versions.node),r.global=r.isNode&&global||"undefined"!=typeof window&&window||"undefined"!=typeof self&&self||this,r.emptyArray=Object.freeze?Object.freeze([]):[],r.emptyObject=Object.freeze?Object.freeze({}):{},r.isInteger=Number.isInteger||function(t){return"number"==typeof t&&isFinite(t)&&Math.floor(t)===t},r.isString=function(t){return"string"==typeof t||t instanceof String},r.isObject=function(t){return t&&"object"==typeof t},r.isset=r.isSet=function(t,e){var n=t[e];return null!=n&&t.hasOwnProperty(e)&&("object"!=typeof n||0<(Array.isArray(n)?n:Object.keys(n)).length)},r.Buffer=function(){try{var t=r.inquire("buffer").Buffer;return t.prototype.utf8Write?t:null}catch(t){return null}}(),r.L=null,r.V=null,r.newBuffer=function(t){return"number"==typeof t?r.Buffer?r.V(t):new r.Array(t):r.Buffer?r.L(t):"undefined"==typeof Uint8Array?t:new Uint8Array(t)},r.Array="undefined"!=typeof Uint8Array?Uint8Array:Array,r.Long=r.global.dcodeIO&&r.global.dcodeIO.Long||r.global.Long||r.inquire("long"),r.key2Re=/^true|false|0|1$/,r.key32Re=/^-?(?:0|[1-9][0-9]*)$/,r.key64Re=/^(?:[\\x00-\\xff]{8}|-?(?:0|[1-9][0-9]*))$/,r.longToHash=function(t){return t?r.LongBits.from(t).toHash():r.LongBits.zeroHash},r.longFromHash=function(t,e){return t=r.LongBits.fromHash(t),r.Long?r.Long.fromBits(t.lo,t.hi,e):t.toNumber(!!e)},r.merge=i,r.lcFirst=function(t){return(t[0]||"").toLowerCase()+t.substring(1)},r.newError=s,r.ProtocolError=s("ProtocolError"),r.oneOfGetter=function(t){for(var e={},n=0;n<t.length;++n)e[t[n]]=1;return function(){for(var t=Object.keys(this),n=t.length-1;-1<n;--n)if(1===e[t[n]]&&this[t[n]]!==rt&&null!==this[t[n]])return t[n]}},r.oneOfSetter=function(t){return function(e){for(var n=0;n<t.length;++n)t[n]!==e&&delete this[t[n]]}},r.toJSONOptions={longs:String,enums:String,bytes:String,json:!0},r.p=function(){var t=r.Buffer;t?(r.L=t.from!==Uint8Array.from&&t.from||function(e,n){return new t(e,n)},r.V=t.allocUnsafe||function(e){return new t(e)}):r.L=r.V=null}},{1:1,10:10,2:2,38:38,4:4,6:6,7:7,9:9}],40:[function(t,e,n){e.exports=function(t){var e=i.codegen(["m"],t.name+"$verify")('if(typeof m!=="object"||m===null)')("return%j","object expected"),n={};t.oneofsArray.length&&e("var p={}");for(var r=0;r<t.fieldsArray.length;++r){var o,l=t.e[r].resolve(),c="m"+i.safeProp(l.name);l.optional&&e("if(%s!=null&&m.hasOwnProperty(%j)){",c,l.name),l.map?(e("if(!util.isObject(%s))",c)("return%j",s(l,"object"))("var k=Object.keys(%s)",c)("for(var i=0;i<k.length;++i){"),function(t,e,n){switch(e.keyType){case"int32":case"uint32":case"sint32":case"fixed32":case"sfixed32":t("if(!util.key32Re.test(%s))",n)("return%j",s(e,"integer key"));break;case"int64":case"uint64":case"sint64":case"fixed64":case"sfixed64":t("if(!util.key64Re.test(%s))",n)("return%j",s(e,"integer|Long key"));break;case"bool":t("if(!util.key2Re.test(%s))",n)("return%j",s(e,"boolean key"))}}(e,l,"k[i]"),a(e,l,r,c+"[k[i]]")("}")):l.repeated?(e("if(!Array.isArray(%s))",c)("return%j",s(l,"array"))("for(var i=0;i<%s.length;++i){",c),a(e,l,r,c+"[i]")("}")):(l.partOf&&(o=i.safeProp(l.partOf.name),1===n[l.partOf.name]&&e("if(p%s===1)",o)("return%j",l.partOf.name+": multiple values"),n[l.partOf.name]=1,e("p%s=1",o)),a(e,l,r,c)),l.optional&&e("}")}return e("return null")};var r=t(15),i=t(37);function s(t,e){return t.name+": "+e+(t.repeated&&"array"!==e?"[]":t.map&&"object"!==e?"{k:"+t.keyType+"}":"")+" expected"}function a(t,e,n,i){if(e.resolvedType)if(e.resolvedType instanceof r){t("switch(%s){",i)("default:")("return%j",s(e,"enum value"));for(var a=Object.keys(e.resolvedType.values),o=0;o<a.length;++o)t("case %i:",e.resolvedType.values[a[o]]);t("break")("}")}else t("{")("var e=types[%i].verify(%s);",n,i)("if(e)")("return%j+e",e.name+".")("}");else switch(e.type){case"int32":case"uint32":case"sint32":case"fixed32":case"sfixed32":t("if(!util.isInteger(%s))",i)("return%j",s(e,"integer"));break;case"int64":case"uint64":case"sint64":case"fixed64":case"sfixed64":t("if(!util.isInteger(%s)&&!(%s&&util.isInteger(%s.low)&&util.isInteger(%s.high)))",i,i,i,i)("return%j",s(e,"integer|Long"));break;case"float":case"double":t('if(typeof %s!=="number")',i)("return%j",s(e,"number"));break;case"bool":t('if(typeof %s!=="boolean")',i)("return%j",s(e,"boolean"));break;case"string":t("if(!util.isString(%s))",i)("return%j",s(e,"string"));break;case"bytes":t('if(!(%s&&typeof %s.length==="number"||util.isString(%s)))',i,i,i)("return%j",s(e,"buffer"))}return t}},{15:15,37:37}],41:[function(t,e,n){var r=t(21);n[".google.protobuf.Any"]={fromObject:function(t){if(t&&t["@type"]){var e,n=t["@type"].substring(1+t["@type"].lastIndexOf("/"));if(n=this.lookup(n))return~(e="."==(t["@type"][0]||"")?t["@type"].slice(1):t["@type"]).indexOf("/")||(e="/"+e),this.create({type_url:e,value:n.encode(n.fromObject(t)).finish()})}return this.fromObject(t)},toObject:function(t,e){var n,i,s="",a="";return e&&e.json&&t.type_url&&t.value&&(a=t.type_url.substring(1+t.type_url.lastIndexOf("/")),s=t.type_url.substring(0,1+t.type_url.lastIndexOf("/")),(n=this.lookup(a))&&(t=n.decode(t.value))),!(t instanceof this.ctor)&&t instanceof r?(n=t.$type.toObject(t,e),i="."===t.$type.fullName[0]?t.$type.fullName.slice(1):t.$type.fullName,n["@type"]=a=(s=""===s?"type.googleapis.com/":s)+i,n):this.toObject(t,e)}}},{21:21}],42:[function(t,e,n){e.exports=h;var r,i=t(39),s=i.LongBits,a=i.base64,o=i.utf8;function l(t,e,n){this.fn=t,this.len=e,this.next=rt,this.val=n}function c(){}function d(t){this.head=t.head,this.tail=t.tail,this.len=t.len,this.next=t.states}function h(){this.len=0,this.head=new l(c,0,0),this.tail=this.head,this.states=null}function u(){return i.Buffer?function(){return(h.create=function(){return new r})()}:function(){return new h}}function p(t,e,n){e[n]=255&t}function f(t,e){this.len=t,this.next=rt,this.val=e}function m(t,e,n){for(;t.hi;)e[n++]=127&t.lo|128,t.lo=(t.lo>>>7|t.hi<<25)>>>0,t.hi>>>=7;for(;127<t.lo;)e[n++]=127&t.lo|128,t.lo=t.lo>>>7;e[n++]=t.lo}function _(t,e,n){e[n]=255&t,e[n+1]=t>>>8&255,e[n+2]=t>>>16&255,e[n+3]=t>>>24}h.create=u(),h.alloc=function(t){return new i.Array(t)},i.Array!==Array&&(h.alloc=i.pool(h.alloc,i.Array.prototype.subarray)),h.prototype.M=function(t,e,n){return this.tail=this.tail.next=new l(t,e,n),this.len+=e,this},(f.prototype=Object.create(l.prototype)).fn=function(t,e,n){for(;127<t;)e[n++]=127&t|128,t>>>=7;e[n]=t},h.prototype.uint32=function(t){return this.len+=(this.tail=this.tail.next=new f((t>>>=0)<128?1:t<16384?2:t<2097152?3:t<268435456?4:5,t)).len,this},h.prototype.int32=function(t){return t<0?this.M(m,10,s.fromNumber(t)):this.uint32(t)},h.prototype.sint32=function(t){return this.uint32((t<<1^t>>31)>>>0)},h.prototype.int64=h.prototype.uint64=function(t){return t=s.from(t),this.M(m,t.length(),t)},h.prototype.sint64=function(t){return t=s.from(t).zzEncode(),this.M(m,t.length(),t)},h.prototype.bool=function(t){return this.M(p,1,t?1:0)},h.prototype.sfixed32=h.prototype.fixed32=function(t){return this.M(_,4,t>>>0)},h.prototype.sfixed64=h.prototype.fixed64=function(t){return t=s.from(t),this.M(_,4,t.lo).M(_,4,t.hi)},h.prototype.float=function(t){return this.M(i.float.writeFloatLE,4,t)},h.prototype.double=function(t){return this.M(i.float.writeDoubleLE,8,t)};var g=i.Array.prototype.set?function(t,e,n){e.set(t,n)}:function(t,e,n){for(var r=0;r<t.length;++r)e[n+r]=t[r]};h.prototype.bytes=function(t){var e,n=t.length>>>0;return n?(i.isString(t)&&(e=h.alloc(n=a.length(t)),a.decode(t,e,0),t=e),this.uint32(n).M(g,n,t)):this.M(p,1,0)},h.prototype.string=function(t){var e=o.length(t);return e?this.uint32(e).M(o.write,e,t):this.M(p,1,0)},h.prototype.fork=function(){return this.states=new d(this),this.head=this.tail=new l(c,0,0),this.len=0,this},h.prototype.reset=function(){return this.states?(this.head=this.states.head,this.tail=this.states.tail,this.len=this.states.len,this.states=this.states.next):(this.head=this.tail=new l(c,0,0),this.len=0),this},h.prototype.ldelim=function(){var t=this.head,e=this.tail,n=this.len;return this.reset().uint32(n),n&&(this.tail.next=t.next,this.tail=e,this.len+=n),this},h.prototype.finish=function(){for(var t=this.head.next,e=this.constructor.alloc(this.len),n=0;t;)t.fn(t.val,e,n),n+=t.len,t=t.next;return e},h.p=function(t){r=t,h.create=u(),r.p()}},{39:39}],43:[function(t,e,n){e.exports=s;var r=t(42),i=((s.prototype=Object.create(r.prototype)).constructor=s,t(39));function s(){r.call(this)}function a(t,e,n){t.length<40?i.utf8.write(t,e,n):e.utf8Write?e.utf8Write(t,n):e.write(t,n)}s.p=function(){s.alloc=i.V,s.writeBytesBuffer=i.Buffer&&i.Buffer.prototype instanceof Uint8Array&&"set"===i.Buffer.prototype.set.name?function(t,e,n){e.set(t,n)}:function(t,e,n){if(t.copy)t.copy(e,n,0,t.length);else for(var r=0;r<t.length;)e[n++]=t[r++]}},s.prototype.bytes=function(t){var e=(t=i.isString(t)?i.L(t,"base64"):t).length>>>0;return this.uint32(e),e&&this.M(s.writeBytesBuffer,e,t),this},s.prototype.string=function(t){var e=i.Buffer.byteLength(t);return this.uint32(e),e&&this.M(a,e,t),this},s.p()},{39:39,42:42}]},e={},i=function t(n){var i=e[n];return i||r[n][0].call(i=e[n]={exports:{}},t,i,i.exports),i.exports}(19),i.util.global.protobuf=i,"function"==typeof define&&define.amd&&define(["long"],function(t){return t&&t.isLong&&(i.util.Long=t,i.configure()),i}),"object"==typeof module&&module&&module.exports&&(module.exports=i)}(),$protobuf=protobuf,$Reader=$protobuf.Reader,$Writer=$protobuf.Writer,$util=$protobuf.util,$root=$protobuf.roots.default||($protobuf.roots.default={}),$root.MeshData=function(){function t(t){if(this.weights=[],t)for(var e=Object.keys(t),n=0;n<e.length;++n)null!=t[e[n]]&&(this[e[n]]=t[e[n]])}return t.prototype.index=0,t.prototype.weights=$util.emptyArray,t.create=function(e){return new t(e)},t.encode=function(t,e){if(e||(e=$Writer.create()),null!=t.index&&Object.hasOwnProperty.call(t,"index")&&e.uint32(8).int32(t.index),null!=t.weights&&t.weights.length){e.uint32(18).fork();for(var n=0;n<t.weights.length;++n)e.float(t.weights[n]);e.ldelim()}return e},t.encodeDelimited=function(t,e){return this.encode(t,e).ldelim()},t.decode=function(t,e,n){t instanceof $Reader||(t=$Reader.create(t));for(var r=void 0===e?t.len:t.pos+e,i=new $root.MeshData;t.pos<r;){var s=t.uint32();if(s===n)break;switch(s>>>3){case 1:i.index=t.int32();break;case 2:if(i.weights&&i.weights.length||(i.weights=[]),2==(7&s))for(var a=t.uint32()+t.pos;t.pos<a;)i.weights.push(t.float());else i.weights.push(t.float());break;default:t.skipType(7&s)}}return i},t.decodeDelimited=function(t){return t instanceof $Reader||(t=new $Reader(t)),this.decode(t,t.uint32())},t.verify=function(t){if("object"!=typeof t||null===t)return"object expected";if(null!=t.index&&t.hasOwnProperty("index")&&!$util.isInteger(t.index))return"index: integer expected";if(null!=t.weights&&t.hasOwnProperty("weights")){if(!Array.isArray(t.weights))return"weights: array expected";for(var e=0;e<t.weights.length;++e)if("number"!=typeof t.weights[e])return"weights: number[] expected"}return null},t.fromObject=function(t){if(t instanceof $root.MeshData)return t;var e=new $root.MeshData;if(null!=t.index&&(e.index=0|t.index),t.weights){if(!Array.isArray(t.weights))throw TypeError(".MeshData.weights: array expected");e.weights=[];for(var n=0;n<t.weights.length;++n)e.weights[n]=Number(t.weights[n])}return e},t.toObject=function(t,e){e||(e={});var n={};if((e.arrays||e.defaults)&&(n.weights=[]),e.defaults&&(n.index=0),null!=t.index&&t.hasOwnProperty("index")&&(n.index=t.index),t.weights&&t.weights.length){n.weights=[];for(var r=0;r<t.weights.length;++r)n.weights[r]=e.json&&!isFinite(t.weights[r])?String(t.weights[r]):t.weights[r]}return n},t.prototype.toJSON=function(){return this.constructor.toObject(this,$protobuf.util.toJSONOptions)},t.getTypeUrl=function(t){return void 0===t&&(t="type.googleapis.com"),t+"/MeshData"},t}(),$root.JointData=function(){function t(t){if(this.translate=[],t)for(var e=Object.keys(t),n=0;n<e.length;++n)null!=t[e[n]]&&(this[e[n]]=t[e[n]])}return t.prototype.translate=$util.emptyArray,t.prototype.rotate=$util.newBuffer([]),t.create=function(e){return new t(e)},t.encode=function(t,e){if(e||(e=$Writer.create()),null!=t.translate&&t.translate.length){e.uint32(10).fork();for(var n=0;n<t.translate.length;++n)e.float(t.translate[n]);e.ldelim()}return null!=t.rotate&&Object.hasOwnProperty.call(t,"rotate")&&e.uint32(18).bytes(t.rotate),e},t.encodeDelimited=function(t,e){return this.encode(t,e).ldelim()},t.decode=function(t,e,n){t instanceof $Reader||(t=$Reader.create(t));for(var r=void 0===e?t.len:t.pos+e,i=new $root.JointData;t.pos<r;){var s=t.uint32();if(s===n)break;switch(s>>>3){case 1:if(i.translate&&i.translate.length||(i.translate=[]),2==(7&s))for(var a=t.uint32()+t.pos;t.pos<a;)i.translate.push(t.float());else i.translate.push(t.float());break;case 2:i.rotate=t.bytes();break;default:t.skipType(7&s)}}return i},t.decodeDelimited=function(t){return t instanceof $Reader||(t=new $Reader(t)),this.decode(t,t.uint32())},t.verify=function(t){if("object"!=typeof t||null===t)return"object expected";if(null!=t.translate&&t.hasOwnProperty("translate")){if(!Array.isArray(t.translate))return"translate: array expected";for(var e=0;e<t.translate.length;++e)if("number"!=typeof t.translate[e])return"translate: number[] expected"}return null!=t.rotate&&t.hasOwnProperty("rotate")&&!(t.rotate&&"number"==typeof t.rotate.length||$util.isString(t.rotate))?"rotate: buffer expected":null},t.fromObject=function(t){if(t instanceof $root.JointData)return t;var e=new $root.JointData;if(t.translate){if(!Array.isArray(t.translate))throw TypeError(".JointData.translate: array expected");e.translate=[];for(var n=0;n<t.translate.length;++n)e.translate[n]=Number(t.translate[n])}return null!=t.rotate&&("string"==typeof t.rotate?$util.base64.decode(t.rotate,e.rotate=$util.newBuffer($util.base64.length(t.rotate)),0):t.rotate.length>=0&&(e.rotate=t.rotate)),e},t.toObject=function(t,e){e||(e={});var n={};if((e.arrays||e.defaults)&&(n.translate=[]),e.defaults&&(e.bytes===String?n.rotate="":(n.rotate=[],e.bytes!==Array&&(n.rotate=$util.newBuffer(n.rotate)))),t.translate&&t.translate.length){n.translate=[];for(var r=0;r<t.translate.length;++r)n.translate[r]=e.json&&!isFinite(t.translate[r])?String(t.translate[r]):t.translate[r]}return null!=t.rotate&&t.hasOwnProperty("rotate")&&(n.rotate=e.bytes===String?$util.base64.encode(t.rotate,0,t.rotate.length):e.bytes===Array?Array.prototype.slice.call(t.rotate):t.rotate),n},t.prototype.toJSON=function(){return this.constructor.toObject(this,$protobuf.util.toJSONOptions)},t.getTypeUrl=function(t){return void 0===t&&(t="type.googleapis.com"),t+"/JointData"},t}(),$root.FaceFrameData=function(){function t(t){if(this.js=[],this.ms=[],t)for(var e=Object.keys(t),n=0;n<e.length;++n)null!=t[e[n]]&&(this[e[n]]=t[e[n]])}return t.prototype.id=0,t.prototype.s="",t.prototype.sf=0,t.prototype.ef=0,t.prototype.bsw=$util.newBuffer([]),t.prototype.cs=$util.newBuffer([]),t.prototype.js=$util.emptyArray,t.prototype.ms=$util.emptyArray,t.prototype.bodyId=0,t.prototype.faceFrameType=0,t.prototype.asf=0,t.prototype.aef=0,t.prototype.n="",t.create=function(e){return new t(e)},t.encode=function(t,e){if(e||(e=$Writer.create()),null!=t.id&&Object.hasOwnProperty.call(t,"id")&&e.uint32(8).int32(t.id),null!=t.s&&Object.hasOwnProperty.call(t,"s")&&e.uint32(18).string(t.s),null!=t.sf&&Object.hasOwnProperty.call(t,"sf")&&e.uint32(24).int32(t.sf),null!=t.ef&&Object.hasOwnProperty.call(t,"ef")&&e.uint32(32).int32(t.ef),null!=t.bsw&&Object.hasOwnProperty.call(t,"bsw")&&e.uint32(42).bytes(t.bsw),null!=t.cs&&Object.hasOwnProperty.call(t,"cs")&&e.uint32(90).bytes(t.cs),null!=t.js&&t.js.length)for(var n=0;n<t.js.length;++n)$root.JointData.encode(t.js[n],e.uint32(98).fork()).ldelim();if(null!=t.ms&&t.ms.length)for(n=0;n<t.ms.length;++n)$root.MeshData.encode(t.ms[n],e.uint32(106).fork()).ldelim();return null!=t.bodyId&&Object.hasOwnProperty.call(t,"bodyId")&&e.uint32(112).int32(t.bodyId),null!=t.faceFrameType&&Object.hasOwnProperty.call(t,"faceFrameType")&&e.uint32(120).int32(t.faceFrameType),null!=t.asf&&Object.hasOwnProperty.call(t,"asf")&&e.uint32(128).int32(t.asf),null!=t.aef&&Object.hasOwnProperty.call(t,"aef")&&e.uint32(136).int32(t.aef),null!=t.n&&Object.hasOwnProperty.call(t,"n")&&e.uint32(146).string(t.n),e},t.encodeDelimited=function(t,e){return this.encode(t,e).ldelim()},t.decode=function(t,e,n){t instanceof $Reader||(t=$Reader.create(t));for(var r=void 0===e?t.len:t.pos+e,i=new $root.FaceFrameData;t.pos<r;){var s=t.uint32();if(s===n)break;switch(s>>>3){case 1:i.id=t.int32();break;case 2:i.s=t.string();break;case 3:i.sf=t.int32();break;case 4:i.ef=t.int32();break;case 5:i.bsw=t.bytes();break;case 11:i.cs=t.bytes();break;case 12:i.js&&i.js.length||(i.js=[]),i.js.push($root.JointData.decode(t,t.uint32()));break;case 13:i.ms&&i.ms.length||(i.ms=[]),i.ms.push($root.MeshData.decode(t,t.uint32()));break;case 14:i.bodyId=t.int32();break;case 15:i.faceFrameType=t.int32();break;case 16:i.asf=t.int32();break;case 17:i.aef=t.int32();break;case 18:i.n=t.string();break;default:t.skipType(7&s)}}return i},t.decodeDelimited=function(t){return t instanceof $Reader||(t=new $Reader(t)),this.decode(t,t.uint32())},t.verify=function(t){if("object"!=typeof t||null===t)return"object expected";if(null!=t.id&&t.hasOwnProperty("id")&&!$util.isInteger(t.id))return"id: integer expected";if(null!=t.s&&t.hasOwnProperty("s")&&!$util.isString(t.s))return"s: string expected";if(null!=t.sf&&t.hasOwnProperty("sf")&&!$util.isInteger(t.sf))return"sf: integer expected";if(null!=t.ef&&t.hasOwnProperty("ef")&&!$util.isInteger(t.ef))return"ef: integer expected";if(null!=t.bsw&&t.hasOwnProperty("bsw")&&!(t.bsw&&"number"==typeof t.bsw.length||$util.isString(t.bsw)))return"bsw: buffer expected";if(null!=t.cs&&t.hasOwnProperty("cs")&&!(t.cs&&"number"==typeof t.cs.length||$util.isString(t.cs)))return"cs: buffer expected";if(null!=t.js&&t.hasOwnProperty("js")){if(!Array.isArray(t.js))return"js: array expected";for(var e=0;e<t.js.length;++e)if(n=$root.JointData.verify(t.js[e]))return"js."+n}if(null!=t.ms&&t.hasOwnProperty("ms")){if(!Array.isArray(t.ms))return"ms: array expected";for(e=0;e<t.ms.length;++e){var n;if(n=$root.MeshData.verify(t.ms[e]))return"ms."+n}}return null!=t.bodyId&&t.hasOwnProperty("bodyId")&&!$util.isInteger(t.bodyId)?"bodyId: integer expected":null!=t.faceFrameType&&t.hasOwnProperty("faceFrameType")&&!$util.isInteger(t.faceFrameType)?"faceFrameType: integer expected":null!=t.asf&&t.hasOwnProperty("asf")&&!$util.isInteger(t.asf)?"asf: integer expected":null!=t.aef&&t.hasOwnProperty("aef")&&!$util.isInteger(t.aef)?"aef: integer expected":null!=t.n&&t.hasOwnProperty("n")&&!$util.isString(t.n)?"n: string expected":null},t.fromObject=function(t){if(t instanceof $root.FaceFrameData)return t;var e=new $root.FaceFrameData;if(null!=t.id&&(e.id=0|t.id),null!=t.s&&(e.s=String(t.s)),null!=t.sf&&(e.sf=0|t.sf),null!=t.ef&&(e.ef=0|t.ef),null!=t.bsw&&("string"==typeof t.bsw?$util.base64.decode(t.bsw,e.bsw=$util.newBuffer($util.base64.length(t.bsw)),0):t.bsw.length>=0&&(e.bsw=t.bsw)),null!=t.cs&&("string"==typeof t.cs?$util.base64.decode(t.cs,e.cs=$util.newBuffer($util.base64.length(t.cs)),0):t.cs.length>=0&&(e.cs=t.cs)),t.js){if(!Array.isArray(t.js))throw TypeError(".FaceFrameData.js: array expected");e.js=[];for(var n=0;n<t.js.length;++n){if("object"!=typeof t.js[n])throw TypeError(".FaceFrameData.js: object expected");e.js[n]=$root.JointData.fromObject(t.js[n])}}if(t.ms){if(!Array.isArray(t.ms))throw TypeError(".FaceFrameData.ms: array expected");for(e.ms=[],n=0;n<t.ms.length;++n){if("object"!=typeof t.ms[n])throw TypeError(".FaceFrameData.ms: object expected");e.ms[n]=$root.MeshData.fromObject(t.ms[n])}}return null!=t.bodyId&&(e.bodyId=0|t.bodyId),null!=t.faceFrameType&&(e.faceFrameType=0|t.faceFrameType),null!=t.asf&&(e.asf=0|t.asf),null!=t.aef&&(e.aef=0|t.aef),null!=t.n&&(e.n=String(t.n)),e},t.toObject=function(t,e){e||(e={});var n={};if((e.arrays||e.defaults)&&(n.js=[],n.ms=[]),e.defaults&&(n.id=0,n.s="",n.sf=0,n.ef=0,e.bytes===String?n.bsw="":(n.bsw=[],e.bytes!==Array&&(n.bsw=$util.newBuffer(n.bsw))),e.bytes===String?n.cs="":(n.cs=[],e.bytes!==Array&&(n.cs=$util.newBuffer(n.cs))),n.bodyId=0,n.faceFrameType=0,n.asf=0,n.aef=0,n.n=""),null!=t.id&&t.hasOwnProperty("id")&&(n.id=t.id),null!=t.s&&t.hasOwnProperty("s")&&(n.s=t.s),null!=t.sf&&t.hasOwnProperty("sf")&&(n.sf=t.sf),null!=t.ef&&t.hasOwnProperty("ef")&&(n.ef=t.ef),null!=t.bsw&&t.hasOwnProperty("bsw")&&(n.bsw=e.bytes===String?$util.base64.encode(t.bsw,0,t.bsw.length):e.bytes===Array?Array.prototype.slice.call(t.bsw):t.bsw),null!=t.cs&&t.hasOwnProperty("cs")&&(n.cs=e.bytes===String?$util.base64.encode(t.cs,0,t.cs.length):e.bytes===Array?Array.prototype.slice.call(t.cs):t.cs),t.js&&t.js.length){n.js=[];for(var r=0;r<t.js.length;++r)n.js[r]=$root.JointData.toObject(t.js[r],e)}if(t.ms&&t.ms.length)for(n.ms=[],r=0;r<t.ms.length;++r)n.ms[r]=$root.MeshData.toObject(t.ms[r],e);return null!=t.bodyId&&t.hasOwnProperty("bodyId")&&(n.bodyId=t.bodyId),null!=t.faceFrameType&&t.hasOwnProperty("faceFrameType")&&(n.faceFrameType=t.faceFrameType),null!=t.asf&&t.hasOwnProperty("asf")&&(n.asf=t.asf),null!=t.aef&&t.hasOwnProperty("aef")&&(n.aef=t.aef),null!=t.n&&t.hasOwnProperty("n")&&(n.n=t.n),n},t.prototype.toJSON=function(){return this.constructor.toObject(this,$protobuf.util.toJSONOptions)},t.getTypeUrl=function(t){return void 0===t&&(t="type.googleapis.com"),t+"/FaceFrameData"},t}(),$root.FaceFrameDataList=function(){function t(t){if(this.data=[],t)for(var e=Object.keys(t),n=0;n<e.length;++n)null!=t[e[n]]&&(this[e[n]]=t[e[n]])}return t.prototype.data=$util.emptyArray,t.create=function(e){return new t(e)},t.encode=function(t,e){if(e||(e=$Writer.create()),null!=t.data&&t.data.length)for(var n=0;n<t.data.length;++n)$root.FaceFrameData.encode(t.data[n],e.uint32(10).fork()).ldelim();return e},t.encodeDelimited=function(t,e){return this.encode(t,e).ldelim()},t.decode=function(t,e,n){t instanceof $Reader||(t=$Reader.create(t));for(var r=void 0===e?t.len:t.pos+e,i=new $root.FaceFrameDataList;t.pos<r;){var s=t.uint32();if(s===n)break;s>>>3==1?(i.data&&i.data.length||(i.data=[]),i.data.push($root.FaceFrameData.decode(t,t.uint32()))):t.skipType(7&s)}return i},t.decodeDelimited=function(t){return t instanceof $Reader||(t=new $Reader(t)),this.decode(t,t.uint32())},t.verify=function(t){if("object"!=typeof t||null===t)return"object expected";if(null!=t.data&&t.hasOwnProperty("data")){if(!Array.isArray(t.data))return"data: array expected";for(var e=0;e<t.data.length;++e){var n=$root.FaceFrameData.verify(t.data[e]);if(n)return"data."+n}}return null},t.fromObject=function(t){if(t instanceof $root.FaceFrameDataList)return t;var e=new $root.FaceFrameDataList;if(t.data){if(!Array.isArray(t.data))throw TypeError(".FaceFrameDataList.data: array expected");e.data=[];for(var n=0;n<t.data.length;++n){if("object"!=typeof t.data[n])throw TypeError(".FaceFrameDataList.data: object expected");e.data[n]=$root.FaceFrameData.fromObject(t.data[n])}}return e},t.toObject=function(t,e){e||(e={});var n={};if((e.arrays||e.defaults)&&(n.data=[]),t.data&&t.data.length){n.data=[];for(var r=0;r<t.data.length;++r)n.data[r]=$root.FaceFrameData.toObject(t.data[r],e)}return n},t.prototype.toJSON=function(){return this.constructor.toObject(this,$protobuf.util.toJSONOptions)},t.getTypeUrl=function(t){return void 0===t&&(t="type.googleapis.com"),t+"/FaceFrameDataList"},t}();const proxyProtobuf=protobuf.roots.default,CLIENT_QUIT_ACK_TIMEOUT_MS=3e3,pointNameObj={connect_sdk:"连接SDK",connect_sdk_success:"连接SDK成功",llm_text_sdk_received:"大模型输出的文本SDK前端收到",rendering_data_received:"客户端收到音频数据时间",rendering_display:"客户端播放音频数据时间",close_session:"关闭会话",audio_data_expired:"音频数据过期"};class Ttsa{clearReconnectTimer(){-1!==this.reconnectTimer&&(clearTimeout(this.reconnectTimer),this.reconnectTimer=-1),this.clearSocketReconnectTimer()}clearSocketReconnectTimer(){-1!==this.socketReconnectTimer&&(clearTimeout(this.socketReconnectTimer),this.socketReconnectTimer=-1)}startHeartbeat(){this.stopHeartbeat(),this.heartbeatTimer=window.setInterval(()=>{this.send("client_heartbeat",{timestamp:Date.now(),frame:this.getCurrentFrameIndex()})},this.HEARTBEAT_INTERVAL)}stopHeartbeat(){-1!==this.heartbeatTimer&&(clearInterval(this.heartbeatTimer),this.heartbeatTimer=-1)}constructor(t){var e=this;this.TAG="[TTSA]",this.connectedOnce=!1,this.quitRequested=!1,this.quitPromise=null,this._lastSessionId="",this.reconnectTimer=-1,this.socketReconnectTimer=-1,this.wsConnectTimer=0,this.enterOfflineFlag=!1,this.syncTimestampInterval=0,this.syncTimestampNum=5e3,this.SYNC_INTERVAL=3e5,this.lastSyncTime=Date.now(),this.heartbeatTimer=-1,this.HEARTBEAT_INTERVAL=2e3,this._isResume=!1,this.clearOldWsTimeoutTimer=()=>{this.wsConnectTimer&&(clearTimeout(this.wsConnectTimer),this.wsConnectTimer=0)},this.initWsTimeoutTimer=()=>{this.clearOldWsTimeoutTimer(),this.quitRequested||(this.wsConnectTimer=window.setTimeout(async function(){try{e.sdk.onMessage({code:EErrorCode.CONNECT_SOCKET_ERROR,message:"Error: socket长时间未下发数据"}),e.session_id&&(await e.sdk.stopSessionFromSocket("WS_NO_DATA_TIMEOUT"),e.ws.disconnect()),e.reStartSDK()}finally{e.clearOldWsTimeoutTimer()}},1e3*(this.reconnect_client_timeout+10)))},this.appInfo=t.appInfo,this.sdk=t.sdkInstance,this.room=t.room,this.session_id=t.session_id,this.token=t.token,this.framedata_proto_version=t.framedata_proto_version,this._uniqueSpeakId=0,this.runStartFrameIndex=t.runStartFrameIndex,this.ttsaStateChangeHandle=t.ttsaStateChangeHandle,this.reloadSuccess=t.reloadSuccess,this.session_speak_req_id=0,this.enterOfflineMode=t.enterOfflineMode,this.reStartSDK=t.reStartSDK,this.reconnect_client_timeout=t.reconnect_client_timeout,this.reconnect_timeout=t.reconnect_timeout,this.sendVoiceEnd=t.sendVoiceEnd,this.getCurrentFrameIndex=t.getCurrentFrameIndex;const n=lookup(t.url,{query:{token:this.token},path:t.path||"",transports:["websocket"],reconnection:!0,reconnectionAttempts:Infinity,reconnectionDelay:1e3,reconnectionDelayMax:1e3,randomizationFactor:.3});n.on("connect",()=>{if(this.quitRequested)return void n.disconnect();this.connectedOnce=!0,this.clearReconnectTimer(),this.initWsTimeoutTimer(),this.startHeartbeat(),this.enterOfflineFlag=!1,window.performanceTracker.markEnd(performanceConstant.ttsa_connect);const t={room:this.room,client_type:"web",invisible_mode:this.sdk.getPendingInvisibleMode()};this.send("enter_room",t),this.sdk.getStatus()===AvatarStatus.offline&&this.sdk.getIsInitialized()&&this.reloadSuccess()}),n.on("first_start_timestamp",e=>{this.quitRequested||(window.avatarSDKLogger.log(this.TAG,"first_start_timestamp",e),this.firstStartTimestamp(e.server_time),window.performanceTracker.markEnd(performanceConstant.ttsa_ready),window.performanceTracker.markStart(performanceConstant.ttsa_body_res),window.avatarSDKLogger.log(this.TAG,"ready"),this.reloadSuccess(),t.onReady())}),n.on("state_change",t=>{this.ttsaStateChangeHandle(t)}),n.on("tts_audio",e=>{try{const n=msgpack_min.decode(e);this.sendSdkPoint("rendering_data_received",{multi_turn_conversation_id:n[0].multi_turn_conversation_id}),window.avatarSDKLogger.log(this.TAG,"下发音频数据tts_audio",n),t.handleMessage(EFrameDataType.AUDIO,n)}catch(t){this.sdk.onMessage({code:EErrorCode.AUDIO_DECODE_ERROR,message:"Error: 音频数据解码失败",e:t})}}),n.on("face_data",async function(n){try{if(e.framedata_proto_version){let r=[];const i=new Uint8Array(n),s=pako.inflate(i);r=(proxyProtobuf.FaceFrameDataList.decode(s,void 0,()=>{}).toJSON()||{data:[]}).data.map(t=>{const e=(t.js||[]).map(t=>({translate:t.translate||[],rotate:t.rotate?scaledInt16BytesToFloat32(t.rotate):[]})),n=(t.ms||[]).map(t=>({index:t.index||0,weights:t.weights||[]}));return _extends({},t,{bsw:t.bsw?scaledInt16BytesToFloat32(t.bsw):[],js:e,ms:n,body_id:t.bodyId||0,face_frame_type:t.faceFrameType||0})}),t.handleMessage(EFrameDataType.FACE,r),"speak"!==r[0].s&&e.enterOfflineFlag&&(e.sendVoiceEnd(),e.enterOfflineFlag=!1),window.avatarSDKLogger.log(e.TAG,"face_data",r)}else{const r=msgpack_min.decode(n);window.avatarSDKLogger.log(e.TAG,"face_data",r),"speak"!==r[0].s&&e.enterOfflineFlag&&(e.sendVoiceEnd(),e.enterOfflineFlag=!1),t.handleMessage(EFrameDataType.FACE,r)}}catch(t){e.sdk.destroy(),e.sdk.onMessage({code:EErrorCode.FACE_DECODE_ERROR,message:"Error: 表情数据解码失败",e:t})}}),n.on("body_data",e=>{try{let n=msgpack_min.decode(e);window.performanceTracker.markEnd(performanceConstant.start_action_res,n[0].s);const r=n.map(t=>_extends({},t,{x_offset:[]}));window.avatarSDKLogger.log(this.TAG,"body_data",JSON.stringify(r),(new Date).getTime()),window.performanceTracker.markEnd(performanceConstant.ttsa_body_res),t.handleMessage(EFrameDataType.BODY,n)}catch(t){this.sdk.onMessage({code:EErrorCode.VIDEO_DECODE_ERROR,message:"Error: 身体数据解码失败",e:t})}}),n.on("event_data",e=>{try{const n=msgpack_min.decode(e);window.avatarSDKLogger.log(this.TAG,"event_data",JSON.stringify(n)),t.handleMessage(EFrameDataType.EVENT,n)}catch(t){this.sdk.onMessage({code:EErrorCode.EVENT_DECODE_ERROR,message:"Error: 事件数据解码失败",e:t})}}),n.on("sync_frame",e=>{t.handleMessage(EFrameDataType.SYNC_FRAME,e)}),n.on("aa_frame",e=>{window.avatarSDKLogger.log(this.TAG,"下发机器人视频帧aa_frame",e),t.handleAAFrame(e)}),n.on("error_message",t=>{this.sdk.onMessage({code:(null==t?void 0:t.error_code)||EErrorCode.TTSA_ERROR,message:(null==t?void 0:t.user_hint)||"TTSA 返回异常"})}),n.on("disconnect",r=>{this.clearOldWsTimeoutTimer(),this.stopHeartbeat(),this.quitRequested||"io client disconnect"===r||(this.enterOfflineFlag?window.avatarSDKLogger.warn(this.TAG,"已在离线处理中,忽略重复的disconnect事件"):(this.sdk.onMessage({code:EErrorCode.SOCKET_DISCONNECT,message:`client Warning: socket disconnect, ${r}`}),window.avatarSDKLogger.warn(this.TAG,`${t.url} 已断开`,"disconnect原因",r),this.enterOfflineFlag=!0,this.sdk.getStatus()===AvatarStatus.offline?this.sdk.onStatusChange(AvatarStatus.offline):this.enterOfflineMode(),-1===this.socketReconnectTimer&&this.reconnect_timeout>0&&(this.socketReconnectTimer=window.setTimeout(()=>{try{n.disconnect()}catch(t){window.avatarSDKLogger.warn(this.TAG,"disconnect error",t)}this.socketReconnectTimer=-1},1e3*this.reconnect_timeout)),-1===this.reconnectTimer&&(this.reconnectTimer=window.setTimeout(async function(){try{n.disconnect()}catch(t){window.avatarSDKLogger.warn(e.TAG,"disconnect error",t)}await e.sdk.stopSessionFromSocket("WS_TIMEOUT"),e.reStartSDK()},1e3*this.reconnect_client_timeout))))}),n.on("client_quit",t=>{window.avatarSDKLogger.warn(this.TAG,"client_quit","断开原因",t),this.quitRequested||(n.disconnect(),this.session_speak_req_id=0,Object.keys(t).length&&this.sdk.onMessage({code:EErrorCode.SOCKET_QUIT,message:`ttsa主动关闭 reason: ${JSON.stringify({e:t})}`,e:t}),["user","char_bin_load_error","admin kick","nebula admin stop","no_time"].includes(null==t?void 0:t.stop_reason)?(this.sdk.destroyClient(),this.sdk.onStatusChange(AvatarStatus.close)):(this.sdk.getStatus()===AvatarStatus.offline?this.sdk.onStatusChange(AvatarStatus.offline):this.enterOfflineMode(),this.reStartSDK()))}),n.on("connect_error",t=>{this.sdk.onMessage({code:EErrorCode.CONNECT_SOCKET_ERROR,message:"Error: socket连接失败",e:t})}),n.onAny((t,e)=>{this.ws.connected&&this.initWsTimeoutTimer()}),this.ws=n}start(){this._isResume?this._isResume=!1:this.stateChange("interactive_idle")}idle(){this.stateChange("idle")}listen(){this.stateChange("listen")}think(){this.stateChange("think")}interactiveidle(){this.stateChange("interactive_idle")}enterInvisibleMode(){this.send("switch_invisible_mode",{session_id:this.session_id,invisible_mode:!0})}exitInvisibleMode(){this.send("switch_invisible_mode",{session_id:this.session_id,invisible_mode:!1})}firstStartTimestamp(t){const e=Date.now()/1e3,n={server_time:t,client_time:e},r=this._getResumeInfo();this._isResume&&r&&r.client_frame>0?n.resume_from_offline_idle=r:this._isResume=!1,this.runStartFrameIndex(e),this.send("first_start_timestamp",n)}syncTimestamp(){this.syncTimestampInterval&&(clearInterval(this.syncTimestampInterval),this.syncTimestampInterval=0),this.syncTimestampInterval=setInterval(()=>{const t=Date.now();if(t-this.lastSyncTime>=this.SYNC_INTERVAL){const e=this.getCurrentFrameIndex();this.sendSyncTimestamp(e),this.lastSyncTime=t}},this.syncTimestampNum)}sendSyncTimestamp(t){const e=Date.now()/1e3;this.send("sync_frame",{client_time:e,source:FRAME_SOURCE_SOURCE,client_frame:t})}sendText(t,e,n,r={client_speak_id:""}){if(!this.ws.connected)return;const i=this.getUniqueSpeakId();null!=r&&r.client_speak_id||(r.client_speak_id=i);const s={ssml:t,is_start:e,is_end:n,extra:r,multi_turn_conversation_id:i,session_speak_req_id:this.session_speak_req_id,timestamp:Date.now(),sdkVersion:"2.4.0-alpha.4"};return this.sendSdkPoint("llm_text_sdk_received",_extends({},r,{is_start:e,is_end:n,content:{ssml:t},multi_turn_conversation_id:i,speak_id:this.session_speak_req_id++})),e&&(window.performanceTracker.markStart(performanceConstant.start_action_res,"speak"),window.performanceTracker.markStart(performanceConstant.start_action_render,"speak"),window.performanceTracker.markStart(performanceConstant.voice_response_play,"speak")),n&&this.updateUniqueSpeakId(),this.send("send_text",s),i}sendSdkPoint(t,e={},n){this.send("sdk_burial_point",_extends({},e,n,this.appInfo,{burial_type:1,session_id:this.session_id,event_en_name:t,event_cn_name:pointNameObj[t],device:navigator.userAgent,timestamp:e.timestamp||Date.now(),sdkVersion:"2.4.0-alpha.4"}))}stateChange(t,e){const n={state:t,params:e||{}};window.performanceTracker.markStart(performanceConstant.start_action_res,t),window.performanceTracker.markStart(performanceConstant.start_action_render,t),this.send("state_change",n)}sendPerfLog(t){}changeLayout(t){this.send("change_layout",t)}changeWalkConfig(t){this.send("walk_config",t)}send(t,e){this.ws.connected&&this.ws.emit(t,e)}sendDeviceInfo(t){this.send("stat_report",t)}getStatus(){return this.ws.connected}get hasConnected(){return this.connectedOnce}_setResumeInfoCallback(t,e){this._isResume=!0,this._lastSessionId=t,this.getResumeInfo=e}_getResumeInfo(){if(this.getResumeInfo){const t=this.getResumeInfo();return this._lastSessionId&&(t.last_session_id=this._lastSessionId),t}return null}updateUniqueSpeakId(){this._uniqueSpeakId+=1}getUniqueSpeakId(){return`${this._uniqueSpeakId}-${this.session_id}`}quit(t,e=CLIENT_QUIT_ACK_TIMEOUT_MS){return this.quitPromise||(this.quitRequested=!0,this.clearReconnectTimer(),this.clearOldWsTimeoutTimer(),this.stopHeartbeat(),this.quitPromise=this.sendClientQuit(t,e)),this.quitPromise}async sendClientQuit(t,e){this.ws.connected&&await this.ws.timeout(e).emitWithAck("client_quit",{stop_reason:t})}close(){this.ws&&this.ws.disconnect(),this.clearOldWsTimeoutTimer(),this.stopHeartbeat(),this.session_speak_req_id=0,this.clearReconnectTimer(),this.syncTimestampInterval&&(clearInterval(this.syncTimestampInterval),this.syncTimestampInterval=0)}connect(){this.ws.connect()}seekToFrame(t){this.ws.emit("seek_to_frame",{frame:t})}}function formatTimestamp(t){if(!t||"string"!=typeof t)return"N/A";try{const e=new Date(t);return isNaN(e.getTime())?"Invalid Date":`${e.getFullYear()}-${(e.getMonth()+1).toString().padStart(2,"0")}-${e.getDate().toString().padStart(2,"0")} ${e.getHours().toString().padStart(2,"0")}:${e.getMinutes().toString().padStart(2,"0")}:${e.getSeconds().toString().padStart(2,"0")}`}catch(e){return window.avatarSDKLogger.error("Error formatting timestamp:",e),t}}class DebugOverlay{constructor(t,e){this.container=null,this.sdkContainer=null,this.updateInterval=null,this.errors=[],this.fps=0,this.frameCount=0,this.lastFpsUpdate=performance.now(),this.videoInfo={name:"",body_id:0,id:0},this.audioInfo={sf:0,ef:0,ad:new Uint8Array},this.eventInfo={sf:0,ef:0,event:[]},this.memoryInfo={},this.perfMetrics={},this.currentFrameIndex=0,this.domRefs={},this.sdk=t,this.sdkContainer=t.el,this.sessionInfo=e,this.startTime=Date.now(),this.trackFPS(),this.trackMemory()}setAudioInfo(t){this.audioInfo=t}setEventData(t){this.eventInfo=t}addError(t){this.errors.unshift(t),this.errors.length>=20&&this.errors.pop()}show(){this.container||this.createOverlay(),this.container&&(this.container.style.display="block"),this.updateInterval||(this.updateInterval=window.setInterval(()=>this.updateTextOnly(),200)),this.updateTextOnly()}hide(){this.container&&(this.container.style.display="none"),this.updateInterval&&(clearInterval(this.updateInterval),this.updateInterval=null)}destroy(){var t;this.hide(),null!=(t=this.container)&&t.parentNode&&this.container.parentNode.removeChild(this.container),this.container=null}setVideoInfo(t){this.videoInfo=t}updateTextOnly(){var t,e;if(!this.container)return;this.sessionInfo.session_id=this.sdk.resourceManager.session_id,this.currentFrameIndex=null!=(t=null==(e=this.sdk.renderScheduler.frameAnimationController)?void 0:e.getCurrentFrame())?t:0,this.updatePerfMetrics(),this.updateMemory(),this.setText("look_name",this.sessionInfo.config.look_name),this.setText("video_name",`${this.videoInfo.name} - ${this.videoInfo.body_id}`),this.setText("session_id",this.sessionInfo.session_id),this.setText("frame_idx",String(this.currentFrameIndex)),this.setText("audio_info",`开始帧: ${this.audioInfo.sf} / 结束帧: ${this.audioInfo.ef} / 长度: ${this.audioInfo.ad.length}`),this.setText("event_info",`开始帧: ${this.eventInfo.sf} / 结束帧: ${this.eventInfo.ef} / 长度: ${this.eventInfo.event.length}`),this.setText("perf",this.formatPerfMetrics()),this.setText("fps",String(this.fps)),this.setText("mem",this.formatMemory());const n=((Date.now()-this.startTime)/1e3).toFixed(1);this.setText("session_start",formatTimestamp(this.sessionInfo.session_start_time)),this.setText("session_duration",`${n}s`),this.setText("network",this.getNetworkInfo()),this.setText("error_count",`(${this.errors.length})`),this.setText("error_log",this.formatErrors(!1)),this.setText("ttsa_error_log",this.formatErrors(!0))}setText(t,e){const n=this.domRefs[t];n&&(n.innerHTML=e)}copySessionId(){const t=this.sessionInfo.session_id;t&&navigator.clipboard.writeText(t).then(()=>{}).catch(t=>{console.warn("复制失败",t)})}createOverlay(){var t;this.container=document.createElement("div"),this.container.id="sdk-debug-overlay",this.applyStyles(this.container),this.container.style.userSelect="text";const e=(t,e,n="")=>{const r=document.createElement("div");r.style.marginBottom="8px",r.innerHTML=`<span style="color:#888;font-size:11px;">${e}:</span>`;const i=document.createElement("span");return i.style.color="#fff",i.style.fontSize="11px",i.style.marginLeft="4px",i.textContent=n,r.append(i),this.domRefs[t]=i,r},n=document.createElement("h3");n.textContent="🔍 调试信息",n.style.margin="0 0 12px 0",n.style.color="#00ff88",n.style.fontSize="14px";const r=document.createElement("div");r.append(n,e("look_name","角色look_name"),e("video_name","当前视频"),(()=>{const t=document.createElement("div");t.style.marginBottom="8px",t.style.display="flex",t.style.alignItems="center",t.style.gap="6px";const e=document.createElement("span");e.style.color="#888",e.style.fontSize="11px",e.textContent="会话 ID:";const n=document.createElement("span");n.style.color="#fff",n.style.fontSize="11px",n.style.wordBreak="break-all",n.style.flex="1",this.domRefs.session_id=n;const r=document.createElement("button");return r.textContent="复制",r.style.fontSize="10px",r.style.padding="2px 6px",r.style.borderRadius="3px",r.style.border="none",r.style.background="#007aff",r.style.color="#fff",r.style.cursor="pointer",r.onclick=()=>this.copySessionId(),t.append(e,n,r),t})(),e("frame_idx","当前帧"),e("audio_info","下发音频"),e("event_info","下发事件"),e("fps","FPS"));const i=document.createElement("div");i.style.marginBottom="8px",i.innerHTML='<span style="color:#888;font-size:11px;">性能耗时:</span>';const s=document.createElement("div");s.style.fontSize="11px",s.style.background="rgba(0,0,0,0.2)",s.style.padding="4px",s.style.borderRadius="4px",s.style.color="#fff",this.domRefs.perf=s,r.append(i,s);const a=document.createElement("div");a.style.borderTop="1px solid #444",a.style.paddingTop="8px",a.style.marginBottom="8px";const o=document.createElement("h4");o.style.margin="0 0 6px 0",o.style.fontSize="12px",o.style.color="#888";const l=document.createElement("span");this.domRefs.error_count=l,o.append("✅ 错误日志 ",l),a.append(o);const c=t=>{const e=document.createElement("pre");return e.style.margin="0 0 4px 0",e.style.padding="6px",e.style.background="rgba(255,255,255,0.05)",e.style.borderRadius="4px",e.style.fontSize="10px",e.style.lineHeight="1.3",e.style.color="#888",e.style.maxHeight="120px",e.style.overflowY="auto",e.style.whiteSpace="pre-wrap",this.domRefs[t]=e,e},d=c("error_log"),h=c("ttsa_error_log");a.append(d,h),r.append(a),r.append(e("mem","内存占用"),e("session_start","会话开始时间"),e("session_duration","会话时长"),e("network","网络信息")),this.container.append(r),null==(t=this.sdkContainer)||t.appendChild(this.container),this.enableDrag(this.container)}formatErrors(t){let e=this.errors;return e=e.filter(t?t=>t.code===EErrorCode.TTSA_ERROR:t=>t.code!==EErrorCode.TTSA_ERROR),0===e.length?"暂无错误":e.map(t=>`[${new Date(t.timestamp).toLocaleTimeString()}] ${t.code}: ${t.message}`).join("\n")}updatePerfMetrics(){if(!window.performanceTracker)return;const t=window.performanceTracker.getVideoMetrics();for(const[n,r]of Object.entries(t)){var e;const t=null!=(e=null==r?void 0:r.time)?e:0;this.perfMetrics[n]||(this.perfMetrics[n]={times:[],avg:0,last:0,count:0});const i=this.perfMetrics[n];i.times.push(t),i.last=t,i.count++,i.avg=i.times.reduce((t,e)=>t+e,0)/i.times.length}}formatPerfMetrics(){const t=this.perfMetrics;return Object.keys(t).length?Object.entries(t).map(([t,e])=>`${t}: 最近:${e.last.toFixed(2)}ms 平均:${e.avg.toFixed(2)}ms 次数:${e.count}`).join("<br>"):"暂无数据"}formatMemory(){const t=this.memoryInfo;return t.usedJSHeapSize?`${(t.usedJSHeapSize/1048576).toFixed(1)}MB / ${(t.totalJSHeapSize/1048576).toFixed(1)}MB / ${(t.jsHeapSizeLimit/1048576).toFixed(1)}MB`:"N/A"}trackFPS(){const t=e=>{this.frameCount++,e-this.lastFpsUpdate>=1e3&&(this.fps=this.frameCount,this.frameCount=0,this.lastFpsUpdate=e),requestAnimationFrame(t)};requestAnimationFrame(t)}updateMemory(){var t;if(null!=(t=window.performance)&&t.memory){const t=window.performance.memory;this.memoryInfo={jsHeapSizeLimit:t.jsHeapSizeLimit,totalJSHeapSize:t.totalJSHeapSize,usedJSHeapSize:t.usedJSHeapSize}}}trackMemory(){var t;null!=(t=window.performance)&&t.memory&&setInterval(()=>this.updateMemory(),1e3)}getNetworkInfo(){const t=navigator.connection;return t?`类型:${t.effectiveType} 下行:${t.downlink}Mbps 延迟:${t.rtt}ms`:"N/A"}applyStyles(t){t.style.position="fixed",t.style.bottom="50px",t.style.right="10px",t.style.width="350px",t.style.maxHeight="400px",t.style.overflowY="auto",t.style.background="rgba(0,0,0,0.8)",t.style.borderRadius="8px",t.style.padding="10px",t.style.zIndex="99999",t.style.fontSize="12px",t.style.color="#fff",t.style.textAlign="left"}enableDrag(t){let e=!1,n=0,r=0,i=0,s=0;t.style.cursor="move",t.addEventListener("mousedown",a=>{e=!0,n=a.clientX,r=a.clientY,i=t.offsetLeft,s=t.offsetTop,document.body.style.userSelect="none"}),document.addEventListener("mousemove",a=>{e&&(t.style.left=i+a.clientX-n+"px",t.style.top=s+a.clientY-r+"px",t.style.right=t.style.bottom="unset")}),document.addEventListener("mouseup",()=>{e=!1,document.body.style.userSelect=""})}}class NetworkMonitor{constructor(t){this.TAG="[NetworkMonitor]",this.retryCount=1,this.retryTimer=-1,this.options=t,this.bindHandleOnline=this._handleOnline.bind(this),this.bindHandleOffline=this._handleOffline.bind(this),this._initEventListeners()}_initEventListeners(){window.addEventListener("online",this.bindHandleOnline),window.addEventListener("offline",this.bindHandleOffline)}_handleOnline(){window.clearTimeout(this.retryTimer),NetworkMonitor.ONLINE=!0,this.options.onlineCallback("[NetworkMonitor] 网络已恢复")}_handleOffline(){NetworkMonitor.ONLINE=!1,this.options.offlineCallback("[NetworkMonitor] 网络已断开"),this._attempt()}_attempt(){let t=1e3;this.retryCount>1&&(t=1e3*Math.pow(2,this.retryCount)),this.retryTimer=window.setTimeout(()=>{},t)}setState(t){NetworkMonitor.ONLINE=t}destroy(){window.removeEventListener("online",this.bindHandleOnline),window.removeEventListener("offline",this.bindHandleOffline),this.retryTimer=-1,this.retryCount=1}}function Errors(t){var e,n;return{code:t.code,error_code:null!=(e=ERROR_CODE_MAP[t.code])?e:t.code,error_name:null!=(n=ERROR_NAME_MAP[t.code])?n:"UNKNOWN_ERROR",message:t.message,session_id:t.session_id||"",client_speak_id:t.client_speak_id,timestamp:Date.now(),originalError:t.e?JSON.stringify(t.e):null}}NetworkMonitor.ONLINE=!0;const DEBUG_BUILD$2="undefined"==typeof __SENTRY_DEBUG__||__SENTRY_DEBUG__,GLOBAL_OBJ=globalThis,SDK_VERSION="10.69.0";function getMainCarrier(){return getSentryCarrier(GLOBAL_OBJ),GLOBAL_OBJ}function getSentryCarrier(t){const e=t.__SENTRY__=t.__SENTRY__||{};return e.version=e.version||SDK_VERSION,e[SDK_VERSION]=e[SDK_VERSION]||{}}function getGlobalSingleton(t,e,n=GLOBAL_OBJ){const r=n.__SENTRY__=n.__SENTRY__||{},i=r[SDK_VERSION]=r[SDK_VERSION]||{};return i[t]||(i[t]=e())}const CONSOLE_LEVELS=["debug","info","warn","error","log","assert","trace"],PREFIX="Sentry Logger ",originalConsoleMethods={};function consoleSandbox(t){if(!("console"in GLOBAL_OBJ))return t();const e=GLOBAL_OBJ.console,n={},r=Object.keys(originalConsoleMethods);r.forEach(t=>{const r=originalConsoleMethods[t];n[t]=e[t],e[t]=r});try{return t()}finally{r.forEach(t=>{e[t]=n[t]})}}function enable(){_getLoggerSettings().enabled=!0}function disable(){_getLoggerSettings().enabled=!1}function isEnabled$1(){return _getLoggerSettings().enabled}function log(...t){_maybeLog("log",...t)}function warn(...t){_maybeLog("warn",...t)}function error(...t){_maybeLog("error",...t)}function _maybeLog(t,...e){DEBUG_BUILD$2&&isEnabled$1()&&consoleSandbox(()=>{GLOBAL_OBJ.console[t](`${PREFIX}[${t}]:`,...e)})}function _getLoggerSettings(){return DEBUG_BUILD$2?getGlobalSingleton("loggerSettings",()=>({enabled:!1})):{enabled:!1}}const debug={enable,disable,isEnabled:isEnabled$1,log,warn,error},STACKTRACE_FRAME_LIMIT=50,UNKNOWN_FUNCTION="?",WEBPACK_ERROR_REGEXP=/\(error: (.*)\)/,STRIP_FRAME_REGEXP=/captureMessage|captureException/;function createStackParser(...t){const e=t.sort((t,e)=>t[0]-e[0]).map(t=>t[1]);return(t,n=0,r=0)=>{const i=[],s=t.split("\n");for(let t=n;t<s.length;t++){let n=s[t];n.length>1024&&(n=n.slice(0,1024));const a=WEBPACK_ERROR_REGEXP.test(n)?n.replace(WEBPACK_ERROR_REGEXP,"$1"):n;if(!a.includes("Error: ")){for(const t of e){const e=t(a);if(e){i.push(e);break}}if(i.length>=STACKTRACE_FRAME_LIMIT+r)break}}return stripSentryFramesAndReverse(i.slice(r))}}function stripSentryFramesAndReverse(t){if(!t.length)return[];const e=Array.from(t);return/sentryWrapped/.test(getLastStackFrame(e).function||"")&&e.pop(),e.reverse(),STRIP_FRAME_REGEXP.test(getLastStackFrame(e).function||"")&&(e.pop(),STRIP_FRAME_REGEXP.test(getLastStackFrame(e).function||"")&&e.pop()),e.slice(0,STACKTRACE_FRAME_LIMIT).map(t=>({...t,filename:t.filename||getLastStackFrame(e).filename,function:t.function||UNKNOWN_FUNCTION}))}function getLastStackFrame(t){return t[t.length-1]||{}}const defaultFunctionName="<anonymous>";function getFunctionName(t){try{return t&&"function"==typeof t&&t.name||defaultFunctionName}catch{return defaultFunctionName}}function getFramesFromEvent(t){const e=t.exception;if(e){const t=[];try{return e.values.forEach(e=>{e.stacktrace.frames&&t.push(...e.stacktrace.frames)}),t}catch{return}}}const handlers$1={},instrumented$1={};function addHandler$1(t,e){return handlers$1[t]=handlers$1[t]||[],handlers$1[t].push(e),()=>{const n=handlers$1[t];if(n){const t=n.indexOf(e);-1!==t&&n.splice(t,1)}}}function maybeInstrument(t,e){if(!instrumented$1[t]){instrumented$1[t]=!0;try{e()}catch(e){DEBUG_BUILD$2&&debug.error(`Error while instrumenting ${t}`,e)}}}function triggerHandlers$1(t,e){const n=t&&handlers$1[t];if(n)for(const r of n)try{r(e)}catch(e){DEBUG_BUILD$2&&debug.error(`Error while triggering instrumentation handler.\nType: ${t}\nName: ${getFunctionName(r)}\nError:`,e)}}let _oldOnErrorHandler=null;function addGlobalErrorInstrumentationHandler(t){const e="error";addHandler$1(e,t),maybeInstrument(e,instrumentError)}function instrumentError(){_oldOnErrorHandler=GLOBAL_OBJ.onerror,GLOBAL_OBJ.onerror=function(t,e,n,r,i){return triggerHandlers$1("error",{column:r,error:i,line:n,msg:t,url:e}),!!_oldOnErrorHandler&&_oldOnErrorHandler.apply(this,arguments)},GLOBAL_OBJ.onerror.__SENTRY_INSTRUMENTED__=!0}let _oldOnUnhandledRejectionHandler=null;function addGlobalUnhandledRejectionInstrumentationHandler(t){const e="unhandledrejection";addHandler$1(e,t),maybeInstrument(e,instrumentUnhandledRejection)}function instrumentUnhandledRejection(){_oldOnUnhandledRejectionHandler=GLOBAL_OBJ.onunhandledrejection,GLOBAL_OBJ.onunhandledrejection=function(t){return triggerHandlers$1("unhandledrejection",t),!_oldOnUnhandledRejectionHandler||_oldOnUnhandledRejectionHandler.apply(this,arguments)},GLOBAL_OBJ.onunhandledrejection.__SENTRY_INSTRUMENTED__=!0}const objectToString=Object.prototype.toString;function isError(t){switch(objectToString.call(t)){case"[object Error]":case"[object Exception]":case"[object DOMException]":case"[object WebAssembly.Exception]":return!0;default:return isInstanceOf(t,Error)}}function isBuiltin(t,e){return objectToString.call(t)===`[object ${e}]`}function isErrorEvent$1(t){return isBuiltin(t,"ErrorEvent")}function isDOMError(t){return isBuiltin(t,"DOMError")}function isDOMException(t){return isBuiltin(t,"DOMException")}function isString(t){return isBuiltin(t,"String")}function isParameterizedString(t){return"object"==typeof t&&null!==t&&"__sentry_template_string__"in t&&"__sentry_template_values__"in t}function isPrimitive(t){return null===t||isParameterizedString(t)||"object"!=typeof t&&"function"!=typeof t}function isPlainObject(t){return isBuiltin(t,"Object")}function isObjectLike(t){return"object"==typeof t&&null!==t}function isEvent(t){return"undefined"!=typeof Event&&isInstanceOf(t,Event)}function isRegExp(t){return isBuiltin(t,"RegExp")}function isThenable(t){return Boolean(t?.then&&"function"==typeof t.then)}function isInstanceOf(t,e){try{return t instanceof e}catch{return!1}}function isRequest(t){return"undefined"!=typeof Request&&isInstanceOf(t,Request)}function fill(t,e,n){if(!(e in t))return;const r=t[e];if("function"!=typeof r)return;const i=n(r);"function"==typeof i&&markFunctionWrapped(i,r);try{t[e]=i}catch{DEBUG_BUILD$2&&debug.log(`Failed to replace method "${e}" in object`,t)}}function addNonEnumerableProperty(t,e,n){try{Object.defineProperty(t,e,{value:n,writable:!0,configurable:!0})}catch{DEBUG_BUILD$2&&debug.log(`Failed to add non-enumerable property "${String(e)}" to object`,t)}}function markFunctionWrapped(t,e){try{t.prototype=e.prototype=e.prototype||{},addNonEnumerableProperty(t,"__sentry_original__",e)}catch{}}function getOriginalFunction(t){return t.__sentry_original__}function convertToPlainObject(t){if(isError(t))return{message:t.message,name:t.name,stack:t.stack,...getOwnProperties(t)};if(isEvent(t)){const{type:e,target:n,currentTarget:r,detail:i}=t;return{type:e,target:n,currentTarget:r,...i?{detail:i}:{},...getOwnProperties(t)}}return t}function getOwnProperties(t){return isObjectLike(t)?Object.fromEntries(Object.entries(t)):{}}function extractExceptionKeysForMessage(t){const e=Object.keys(convertToPlainObject(t));return e.sort(),e[0]?e.join(", "):"[object has no keys]"}let RESOLVED_RUNNER;function withRandomSafeContext(t){if(void 0!==RESOLVED_RUNNER)return RESOLVED_RUNNER?RESOLVED_RUNNER(t):t();const e=/* @__PURE__ */Symbol.for("__SENTRY_SAFE_RANDOM_ID_WRAPPER__");return e in GLOBAL_OBJ&&"function"==typeof GLOBAL_OBJ[e]?(RESOLVED_RUNNER=GLOBAL_OBJ[e],RESOLVED_RUNNER(t)):(RESOLVED_RUNNER=null,t())}function safeMathRandom(){return withRandomSafeContext(()=>Math.random())}function safeDateNow(){return withRandomSafeContext(()=>Date.now())}const SENTRY_SKIP_NORMALIZATION=/* @__PURE__ */Symbol.for("sentry.skipNormalization"),SENTRY_OVERRIDE_NORMALIZATION_DEPTH=/* @__PURE__ */Symbol.for("sentry.overrideNormalizationDepth");function hasSkipNormalizationHint(t){return Boolean(t[SENTRY_SKIP_NORMALIZATION])}function getNormalizationDepthOverrideHint(t){const e=t[SENTRY_OVERRIDE_NORMALIZATION_DEPTH];return"number"==typeof e?e:void 0}let stringifier,emptyUuid;function normalize(t,e=100,n=Infinity){try{return visit("",t,e,n)}catch(t){return{ERROR:`**non-serializable** (${t})`}}}function normalizeToSize(t,e=3,n=102400){const r=normalize(t,e);return jsonSize(r)>n?normalizeToSize(t,e-1,n):r}function visit(t,e,n=Infinity,r=Infinity,i=memoBuilder()){const[s,a]=i;if(null==e||["boolean","string"].includes(typeof e)||"number"==typeof e&&Number.isFinite(e))return e;const o=stringifyValue(t,e);if(!o.startsWith("[object "))return o;if(hasSkipNormalizationHint(e))return e;const l=getNormalizationDepthOverrideHint(e),c=void 0!==l?l:n;if(0===c)return o.replace("object ","");if(s(e))return"[Circular ~]";const d=e;if(d&&"function"==typeof d.toJSON)try{return visit("",d.toJSON(),c-1,r,i)}catch{}const h=Array.isArray(e)?[]:{};let u=0;const p=convertToPlainObject(e);for(const t in p)if(Object.prototype.hasOwnProperty.call(p,t)){if(u>=r){h[t]="[MaxProperties ~]";break}h[t]=visit(t,p[t],c-1,r,i),u++}return a(e),h}function stringifyValue(t,e){try{return"undefined"!=typeof global&&e===global?"[Global]":"number"!=typeof e||Number.isFinite(e)?"function"==typeof e?`[Function: ${getFunctionName(e)}]`:"symbol"==typeof e?`[${String(e)}]`:"bigint"==typeof e?`[BigInt: ${String(e)}]`:`[object ${getConstructorName(e)}]`:`[${e}]`}catch(t){return`**non-serializable** (${t})`}}function getConstructorName(t){const e=Object.getPrototypeOf(t);return e?.constructor?e.constructor.name:"null prototype"}function utf8Length(t){return~-encodeURI(t).split(/%..|./).length}function jsonSize(t){return utf8Length(JSON.stringify(t))}function memoBuilder(){const t=/* @__PURE__ */new WeakSet;return[function(e){return!!t.has(e)||(t.add(e),!1)},function(e){t.delete(e)}]}function truncate(t,e=0){return"string"!=typeof t||0===e||t.length<=e?t:`${t.slice(0,e)}...`}function safeJoin(t,e){if(!Array.isArray(t))return"";const n=[];for(let e=0;e<t.length;e++){const r=t[e];isPrimitive(r)?n.push(String(r)):r instanceof Error?n.push(r.message?`${r.name}: ${r.message}`:r.name):n.push(stringifyValue(void 0,r))}return n.join(e)}function isMatchingPattern(t,e,n=!1){return!!isString(t)&&(isRegExp(e)?e.test(t):isString(e)?n?t===e:t.includes(e):"function"==typeof e&&e(t))}function stringMatchesSomePattern(t,e=[],n=!1){for(const r of e)if(isMatchingPattern(t,r,n))return!0;return!1}function getCrypto(){return GLOBAL_OBJ.crypto||GLOBAL_OBJ.msCrypto}function getRandomByte(){return 16*safeMathRandom()}function uuid4(t=getCrypto()){try{if(t?.randomUUID)return withRandomSafeContext(()=>t.randomUUID()).replace(/-/g,"")}catch{}return emptyUuid||(emptyUuid="10000000100040008000100000000000"),emptyUuid.replace(/[018]/g,t=>(t^(15&getRandomByte())>>t/4).toString(16))}function getFirstException(t){return t.exception?.values?.[0]}function getEventDescription(t){const{message:e,event_id:n}=t;if(e)return e;const r=getFirstException(t);return r?r.type&&r.value?`${r.type}: ${r.value}`:r.type||r.value||n||"<unknown>":n||"<unknown>"}function addExceptionTypeValue(t,e,n){const r=t.exception=t.exception||{},i=r.values=r.values||[],s=i[0]=i[0]||{};s.value||(s.value=e||""),s.type||(s.type=n||"Error")}function addExceptionMechanism(t,e){const n=getFirstException(t);if(!n)return;const r=n.mechanism;if(n.mechanism={type:"generic",handled:!0,...r,...e},e&&"data"in e){const t={...r?.data,...e.data};n.mechanism.data=t}}function checkOrSetAlreadyCaught(t){if(isAlreadyCaptured(t))return!0;try{addNonEnumerableProperty(t,"__sentry_captured__",!0)}catch{}return!1}function isAlreadyCaptured(t){try{return t.__sentry_captured__}catch{}}const ONE_SECOND_IN_MS=1e3;function dateTimestampInSeconds(){return safeDateNow()/ONE_SECOND_IN_MS}function createUnixTimestampInSecondsFunc(){const{performance:t}=GLOBAL_OBJ;if(!t?.now||!t.timeOrigin)return dateTimestampInSeconds;const e=t.timeOrigin;return()=>(e+withRandomSafeContext(()=>t.now()))/ONE_SECOND_IN_MS}let _cachedTimestampInSeconds;function timestampInSeconds(){return(_cachedTimestampInSeconds??(_cachedTimestampInSeconds=createUnixTimestampInSecondsFunc()))()}let cachedTimeOrigin=null;function getBrowserTimeOrigin(){const{performance:t}=GLOBAL_OBJ;if(!t?.now)return;const e=3e5,n=withRandomSafeContext(()=>t.now()),r=safeDateNow(),i=t.timeOrigin;if("number"==typeof i&&Math.abs(i+n-r)<e)return i;const s=t.timing?.navigationStart;return"number"==typeof s&&Math.abs(s+n-r)<e?s:r-n}function browserPerformanceTimeOrigin(){return null===cachedTimeOrigin&&(cachedTimeOrigin=getBrowserTimeOrigin()),cachedTimeOrigin}function makeSession(t){const e=timestampInSeconds(),n={sid:uuid4(),init:!0,timestamp:e,started:e,duration:0,status:"ok",errors:0,ignoreDuration:!1,toJSON:()=>sessionToJSON(n)};return t&&updateSession(n,t),n}function updateSession(t,e={}){if(e.user&&(!t.ipAddress&&e.user.ip_address&&(t.ipAddress=e.user.ip_address),t.did||e.did||(t.did=e.user.id||e.user.email||e.user.username)),t.timestamp=e.timestamp||timestampInSeconds(),e.abnormal_mechanism&&(t.abnormal_mechanism=e.abnormal_mechanism),e.ignoreDuration&&(t.ignoreDuration=e.ignoreDuration),e.sid&&(t.sid=32===e.sid.length?e.sid:uuid4()),void 0!==e.init&&(t.init=e.init),!t.did&&e.did&&(t.did=`${e.did}`),"number"==typeof e.started&&(t.started=e.started),t.ignoreDuration)t.duration=void 0;else if("number"==typeof e.duration)t.duration=e.duration;else{const e=t.timestamp-t.started;t.duration=e>=0?e:0}e.release&&(t.release=e.release),e.environment&&(t.environment=e.environment),!t.ipAddress&&e.ipAddress&&(t.ipAddress=e.ipAddress),!t.userAgent&&e.userAgent&&(t.userAgent=e.userAgent),"number"==typeof e.errors&&(t.errors=e.errors),e.status&&(t.status=e.status)}function closeSession(t,e){let n={};e?n={status:e}:"ok"===t.status&&(n={status:"exited"}),updateSession(t,n)}function sessionToJSON(t){return{sid:`${t.sid}`,init:t.init,started:new Date(1e3*t.started).toISOString(),timestamp:new Date(1e3*t.timestamp).toISOString(),status:t.status,errors:t.errors,did:"number"==typeof t.did||"string"==typeof t.did?`${t.did}`:void 0,duration:t.duration,abnormal_mechanism:t.abnormal_mechanism,attrs:{release:t.release,environment:t.environment,ip_address:t.ipAddress,user_agent:t.userAgent}}}function merge(t,e,n=2){if(!e||"object"!=typeof e||n<=0)return e;if(t&&0===Object.keys(e).length)return t;const r={...t};for(const t in e)Object.prototype.hasOwnProperty.call(e,t)&&(r[t]=merge(r[t],e[t],n-1));return r}function generateTraceId(){return uuid4()}function generateSpanId(){return uuid4().substring(16)}function makeWeakRef(t){try{const e=GLOBAL_OBJ.WeakRef;if("function"==typeof e)return new e(t)}catch{}return t}function derefWeakRef(t){if(t){if("object"==typeof t&&"deref"in t&&"function"==typeof t.deref)try{return t.deref()}catch{return}return t}}const SCOPE_SPAN_FIELD="_sentrySpan";function _setSpanForScope(t,e){e?addNonEnumerableProperty(t,SCOPE_SPAN_FIELD,makeWeakRef(e)):delete t[SCOPE_SPAN_FIELD]}function _getSpanForScope(t){return derefWeakRef(t[SCOPE_SPAN_FIELD])}const DEFAULT_MAX_BREADCRUMBS=100;class Scope{constructor(){this._notifyingListeners=!1,this._scopeListeners=[],this._eventProcessors=[],this._breadcrumbs=[],this._attachments=[],this._user={},this._tags={},this._attributes={},this._extra={},this._contexts={},this._sdkProcessingMetadata={},this._propagationContext={traceId:generateTraceId(),sampleRand:safeMathRandom()}}clone(){const t=new Scope;return t._breadcrumbs=[...this._breadcrumbs],t._tags={...this._tags},t._attributes={...this._attributes},t._extra={...this._extra},t._contexts={...this._contexts},this._contexts.flags&&(t._contexts.flags={values:[...this._contexts.flags.values]}),t._user=this._user,t._level=this._level,t._session=this._session,t._transactionName=this._transactionName,t._fingerprint=this._fingerprint,t._eventProcessors=[...this._eventProcessors],t._attachments=[...this._attachments],t._sdkProcessingMetadata={...this._sdkProcessingMetadata},t._propagationContext={...this._propagationContext},t._client=this._client,t._lastEventId=this._lastEventId,t._conversationId=this._conversationId,_setSpanForScope(t,_getSpanForScope(this)),t}setClient(t){this._client=t}setLastEventId(t){this._lastEventId=t}getClient(){return this._client}lastEventId(){return this._lastEventId}addScopeListener(t){this._scopeListeners.push(t)}addEventProcessor(t){return this._eventProcessors.push(t),this}setUser(t){return this._user=t||{email:void 0,id:void 0,ip_address:void 0,username:void 0},this._session&&updateSession(this._session,{user:t}),this._notifyScopeListeners(),this}getUser(){return this._user}setConversationId(t){return this._conversationId=t||void 0,this._notifyScopeListeners(),this}setTags(t){return this._tags={...this._tags,...t},this._notifyScopeListeners(),this}setTag(t,e){return this.setTags({[t]:e})}setAttributes(t){return this._attributes={...this._attributes,...t},this._notifyScopeListeners(),this}setAttribute(t,e){return this.setAttributes({[t]:e})}removeAttribute(t){return t in this._attributes&&(delete this._attributes[t],this._notifyScopeListeners()),this}setExtras(t){return this._extra={...this._extra,...t},this._notifyScopeListeners(),this}setExtra(t,e){return this._extra={...this._extra,[t]:e},this._notifyScopeListeners(),this}setFingerprint(t){return this._fingerprint=t,this._notifyScopeListeners(),this}setLevel(t){return this._level=t,this._notifyScopeListeners(),this}setTransactionName(t){return this._transactionName=t,this._notifyScopeListeners(),this}setContext(t,e){return null===e?delete this._contexts[t]:this._contexts[t]=e,this._notifyScopeListeners(),this}setSession(t){return t?this._session=t:delete this._session,this._notifyScopeListeners(),this}getSession(){return this._session}update(t){if(!t)return this;const e="function"==typeof t?t(this):t,n=e instanceof Scope?e.getScopeData():isPlainObject(e)?t:void 0,{tags:r,attributes:i,extra:s,user:a,contexts:o,level:l,fingerprint:c=[],propagationContext:d,conversationId:h}=n||{};return this._tags={...this._tags,...r},this._attributes={...this._attributes,...i},this._extra={...this._extra,...s},this._contexts={...this._contexts,...o},a&&Object.keys(a).length&&(this._user=a),l&&(this._level=l),c.length&&(this._fingerprint=c),d&&(this._propagationContext=d),h&&(this._conversationId=h),this}clear(){return this._breadcrumbs=[],this._tags={},this._attributes={},this._extra={},this._user={},this._contexts={},this._level=void 0,this._transactionName=void 0,this._fingerprint=void 0,this._session=void 0,this._conversationId=void 0,_setSpanForScope(this,void 0),this._attachments=[],this.setPropagationContext({traceId:generateTraceId(),sampleRand:safeMathRandom()}),this._notifyScopeListeners(),this}addBreadcrumb(t,e){const n="number"==typeof e?e:DEFAULT_MAX_BREADCRUMBS;if(n<=0)return this;const r={timestamp:dateTimestampInSeconds(),...t,message:t.message?truncate(t.message,2048):t.message};return this._breadcrumbs.push(r),this._breadcrumbs.length>n&&(this._breadcrumbs=this._breadcrumbs.slice(-n),this._client?.recordDroppedEvent("buffer_overflow","log_item")),this._notifyScopeListeners(),this}getLastBreadcrumb(){return this._breadcrumbs[this._breadcrumbs.length-1]}clearBreadcrumbs(){return this._breadcrumbs=[],this._notifyScopeListeners(),this}addAttachment(t){return this._attachments.push(t),this}clearAttachments(){return this._attachments=[],this}getScopeData(){return{breadcrumbs:this._breadcrumbs,attachments:this._attachments,contexts:this._contexts,tags:this._tags,attributes:this._attributes,extra:this._extra,user:this._user,level:this._level,fingerprint:this._fingerprint||[],eventProcessors:this._eventProcessors,propagationContext:this._propagationContext,sdkProcessingMetadata:this._sdkProcessingMetadata,transactionName:this._transactionName,span:_getSpanForScope(this),conversationId:this._conversationId}}setSDKProcessingMetadata(t){return this._sdkProcessingMetadata=merge(this._sdkProcessingMetadata,t,2),this}setPropagationContext(t){return this._propagationContext=t,this}getPropagationContext(){return this._propagationContext}captureException(t,e){const n=e?.event_id||uuid4();if(!this._client)return DEBUG_BUILD$2&&debug.warn("No client configured on scope - will not capture exception!"),n;const r=new Error("Sentry syntheticException");return this._client.captureException(t,{originalException:t,syntheticException:r,...e,event_id:n},this),n}captureMessage(t,e,n){const r=n?.event_id||uuid4();if(!this._client)return DEBUG_BUILD$2&&debug.warn("No client configured on scope - will not capture message!"),r;const i=n?.syntheticException??new Error(t);return this._client.captureMessage(t,e,{originalException:t,syntheticException:i,...n,event_id:r},this),r}captureEvent(t,e){const n=t.event_id||e?.event_id||uuid4();return this._client?(this._client.captureEvent(t,{...e,event_id:n},this),n):(DEBUG_BUILD$2&&debug.warn("No client configured on scope - will not capture event!"),n)}_notifyScopeListeners(){this._notifyingListeners||(this._notifyingListeners=!0,this._scopeListeners.forEach(t=>{t(this)}),this._notifyingListeners=!1)}}function getDefaultCurrentScope(){return getGlobalSingleton("defaultCurrentScope",()=>new Scope)}function getDefaultIsolationScope(){return getGlobalSingleton("defaultIsolationScope",()=>new Scope)}const isActualPromise=t=>t instanceof Promise&&!t[kChainedCopy],kChainedCopy=/* @__PURE__ */Symbol("chained PromiseLike"),chainAndCopyPromiseLike=(t,e,n)=>{const r=t.then(t=>(e(t),t),t=>{throw n(t),t});return isActualPromise(r)&&isActualPromise(t)?r:copyProps(t,r)},copyProps=(t,e)=>{if(!e)return t;let n=!1;for(const r in t){if(r in e)continue;n=!0;const i=t[r];"function"==typeof i?Object.defineProperty(e,r,{value:(...e)=>i.apply(t,e),enumerable:!0,configurable:!0,writable:!0}):e[r]=i}return n&&Object.assign(e,{[kChainedCopy]:!0}),e};class AsyncContextStack{constructor(t,e){let n,r;n=t||new Scope,r=e||new Scope,this._stack=[{scope:n}],this._isolationScope=r}withScope(t){const e=this._pushScope();let n;try{n=t(e)}catch(t){throw this._popScope(),t}return isThenable(n)?chainAndCopyPromiseLike(n,()=>this._popScope(),()=>this._popScope()):(this._popScope(),n)}getClient(){return this.getStackTop().client}getScope(){return this.getStackTop().scope}getIsolationScope(){return this._isolationScope}getStackTop(){return this._stack[this._stack.length-1]}_pushScope(){const t=this.getScope().clone();return this._stack.push({client:this.getClient(),scope:t}),t}_popScope(){return!(this._stack.length<=1||!this._stack.pop())}}function getAsyncContextStack(){const t=getSentryCarrier(getMainCarrier());return t.stack=t.stack||new AsyncContextStack(getDefaultCurrentScope(),getDefaultIsolationScope())}function withScope$1(t){return getAsyncContextStack().withScope(t)}function withSetScope(t,e){const n=getAsyncContextStack();return n.withScope(()=>(n.getStackTop().scope=t,e(t)))}function withIsolationScope(t){return getAsyncContextStack().withScope(()=>t(getAsyncContextStack().getIsolationScope()))}function getStackAsyncContextStrategy(){return{withIsolationScope,withScope:withScope$1,withSetScope,withSetIsolationScope:(t,e)=>withIsolationScope(e),getCurrentScope:()=>getAsyncContextStack().getScope(),getIsolationScope:()=>getAsyncContextStack().getIsolationScope()}}function getAsyncContextStrategy(t){const e=getSentryCarrier(t);return e.acs?e.acs:getStackAsyncContextStrategy()}function isAttributeObject(t){return"object"==typeof t&&null!=t&&!Array.isArray(t)&&Object.keys(t).includes("value")}function attributeValueToTypedAttributeValue(t,e){const{value:n,unit:r}=isAttributeObject(t)?t:{value:t,unit:void 0},i=getTypedAttributeValue(n),s=r&&"string"==typeof r?{unit:r}:{};if(i)return{...i,...s};if(!e||"skip-undefined"===e&&void 0===n)return;let a="";try{a=JSON.stringify(n)??""}catch{}return{value:a,type:"string",...s}}function serializeAttributes(t,e=!1){const n={};for(const[r,i]of Object.entries(t??{})){const t=attributeValueToTypedAttributeValue(i,e);t&&(n[r]=t)}return n}function getTypedAttributeValue(t){if(Array.isArray(t))return{value:t,type:"array"};const e="string"==typeof t?"string":"boolean"==typeof t?"boolean":"number"!=typeof t||Number.isNaN(t)?null:Number.isInteger(t)?"integer":"double";return e?{value:t,type:e}:void 0}let _externalPropagationContextProvider;function getExternalPropagationContext(){return _externalPropagationContextProvider?.()}function hasExternalPropagationContext(){return void 0!==_externalPropagationContextProvider}function getCurrentScope(){return getAsyncContextStrategy(getMainCarrier()).getCurrentScope()}function getIsolationScope(){return getAsyncContextStrategy(getMainCarrier()).getIsolationScope()}function getGlobalScope(){return getGlobalSingleton("globalScope",()=>new Scope)}function withScope(...t){const e=getAsyncContextStrategy(getMainCarrier());if(2===t.length){const[n,r]=t;return n?e.withSetScope(n,r):e.withScope(r)}return e.withScope(t[0])}function getClient(){return getCurrentScope().getClient()}function getTraceContextFromScope(t){const e=getExternalPropagationContext();if(e)return{trace_id:e.traceId,span_id:e.spanId};const n=t.getPropagationContext(),{traceId:r,parentSpanId:i,propagationSpanId:s}=n,a={trace_id:r,span_id:s||generateSpanId()};return i&&(a.parent_span_id=i),a}const SEMANTIC_ATTRIBUTE_SENTRY_SOURCE="sentry.source",SEMANTIC_ATTRIBUTE_SENTRY_SAMPLE_RATE="sentry.sample_rate",SEMANTIC_ATTRIBUTE_SENTRY_PREVIOUS_TRACE_SAMPLE_RATE="sentry.previous_trace_sample_rate",SEMANTIC_ATTRIBUTE_SENTRY_OP="sentry.op",SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN="sentry.origin",SEMANTIC_ATTRIBUTE_SENTRY_STATUS_MESSAGE="sentry.status.message",SEMANTIC_ATTRIBUTE_SENTRY_IDLE_SPAN_FINISH_REASON="sentry.idle_span_finish_reason",SEMANTIC_ATTRIBUTE_SENTRY_MEASUREMENT_UNIT="sentry.measurement_unit",SEMANTIC_ATTRIBUTE_SENTRY_MEASUREMENT_VALUE="sentry.measurement_value",SEMANTIC_ATTRIBUTE_SENTRY_CUSTOM_SPAN_NAME="sentry.custom_span_name",SEMANTIC_ATTRIBUTE_PROFILE_ID="sentry.profile_id",SEMANTIC_ATTRIBUTE_EXCLUSIVE_TIME="sentry.exclusive_time",SEMANTIC_LINK_ATTRIBUTE_LINK_TYPE="sentry.link.type",GEN_AI_CONVERSATION_ID_ATTRIBUTE="gen_ai.conversation.id",SPAN_STATUS_UNSET=0,SPAN_STATUS_OK=1,SPAN_STATUS_ERROR=2;function getSpanStatusFromHttpCode(t){if(t<400&&t>=100)return{code:SPAN_STATUS_OK};if(t>=400&&t<500)switch(t){case 401:return{code:SPAN_STATUS_ERROR,message:"unauthenticated"};case 403:return{code:SPAN_STATUS_ERROR,message:"permission_denied"};case 404:return{code:SPAN_STATUS_ERROR,message:"not_found"};case 409:return{code:SPAN_STATUS_ERROR,message:"already_exists"};case 413:return{code:SPAN_STATUS_ERROR,message:"failed_precondition"};case 429:return{code:SPAN_STATUS_ERROR,message:"resource_exhausted"};case 499:return{code:SPAN_STATUS_ERROR,message:"cancelled"};default:return{code:SPAN_STATUS_ERROR,message:"invalid_argument"}}if(t>=500&&t<600)switch(t){case 501:return{code:SPAN_STATUS_ERROR,message:"unimplemented"};case 503:return{code:SPAN_STATUS_ERROR,message:"unavailable"};case 504:return{code:SPAN_STATUS_ERROR,message:"deadline_exceeded"};default:return{code:SPAN_STATUS_ERROR,message:"internal_error"}}return{code:SPAN_STATUS_ERROR,message:"internal_error"}}function setHttpStatus(t,e){t.setAttribute("http.response.status_code",e);const n=getSpanStatusFromHttpCode(e);"unknown_error"!==n.message&&t.setStatus(n)}const SCOPE_ON_START_SPAN_FIELD="_sentryScope",ISOLATION_SCOPE_ON_START_SPAN_FIELD="_sentryIsolationScope",OTEL_SOURCE_INFERENCE_SPAN_FIELD=/* @__PURE__ */Symbol.for("sentry.otelSourceInference"),OTEL_SOURCE_EXPLICITLY_SET_SPAN_FIELD=/* @__PURE__ */Symbol.for("sentry.otelSourceExplicitlySet"),TRACER_PROVIDER_SPAN_FIELD=/* @__PURE__ */Symbol.for("sentry.tracerProviderSpan");function setCapturedScopesOnSpan(t,e,n){t&&(addNonEnumerableProperty(t,ISOLATION_SCOPE_ON_START_SPAN_FIELD,makeWeakRef(n)),addNonEnumerableProperty(t,SCOPE_ON_START_SPAN_FIELD,e))}function getCapturedScopesOnSpan(t){return{scope:t[SCOPE_ON_START_SPAN_FIELD],isolationScope:derefWeakRef(t[ISOLATION_SCOPE_ON_START_SPAN_FIELD])}}function spanShouldInferOtelSource(t){return!0===t[OTEL_SOURCE_INFERENCE_SPAN_FIELD]}function markSpanSourceAsExplicit(t){addNonEnumerableProperty(t,OTEL_SOURCE_EXPLICITLY_SET_SPAN_FIELD,!0)}function spanIsTracerProviderSpan(t){return!0===t[TRACER_PROVIDER_SPAN_FIELD]}const SENTRY_BAGGAGE_KEY_PREFIX="sentry-",MAX_BAGGAGE_STRING_LENGTH=8192;function baggageHeaderToDynamicSamplingContext(t){const e=parseBaggageHeader(t);if(!e)return;const n=Object.entries(e).reduce((t,[e,n])=>(e.startsWith(SENTRY_BAGGAGE_KEY_PREFIX)&&(t[e.slice(SENTRY_BAGGAGE_KEY_PREFIX.length)]=n),t),{});return Object.keys(n).length>0?n:void 0}function dynamicSamplingContextToSentryBaggageHeader(t){if(t)return objectToBaggageHeader(Object.entries(t).reduce((t,[e,n])=>(n&&(t[`${SENTRY_BAGGAGE_KEY_PREFIX}${e}`]=n),t),{}))}function parseBaggageHeader(t){if(t&&(isString(t)||Array.isArray(t)))return Array.isArray(t)?t.reduce((t,e)=>{const n=baggageHeaderToObject(e);return Object.entries(n).forEach(([e,n])=>{t[e]=n}),t},{}):baggageHeaderToObject(t)}function baggageHeaderToObject(t){return t.split(",").map(t=>{const e=t.indexOf("=");return-1===e?[]:[t.slice(0,e),t.slice(e+1)].map(t=>{try{return decodeURIComponent(t.trim())}catch{return}})}).reduce((t,[e,n])=>(e&&n&&(t[e]=n),t),{})}function objectToBaggageHeader(t){if(0!==Object.keys(t).length)return Object.entries(t).reduce((t,[e,n],r)=>{const i=`${encodeURIComponent(e)}=${encodeURIComponent(n)}`,s=0===r?i:`${t},${i}`;return s.length>MAX_BAGGAGE_STRING_LENGTH?(DEBUG_BUILD$2&&debug.warn(`Not adding key: ${e} with val: ${n} to baggage header due to exceeding baggage size limits.`),t):s},"")}const ORG_ID_REGEX=/^o(\d+)\./,DSN_REGEX=/^(?:(\w+):)\/\/(?:(\w+)(?::(\w+)?)?@)((?:\[[:.%\w]+\]|[\w.-]+))(?::(\d+))?\/(.+)/;function isValidProtocol(t){return"http"===t||"https"===t}function dsnToString(t,e=!1){const{host:n,path:r,pass:i,port:s,projectId:a,protocol:o,publicKey:l}=t;return`${o}://${l}${e&&i?`:${i}`:""}@${n}${s?`:${s}`:""}/${r?`${r}/`:r}${a}`}function dsnFromString(t){const e=DSN_REGEX.exec(t);if(!e)return void consoleSandbox(()=>{console.error(`Invalid Sentry Dsn: ${t}`)});const[n,r,i="",s="",a="",o=""]=e.slice(1);let l="",c=o;const d=c.split("/");if(d.length>1&&(l=d.slice(0,-1).join("/"),c=d.pop()),c){const t=c.match(/^\d+/);t&&(c=t[0])}return dsnFromComponents({host:s,pass:i,path:l,projectId:c,port:a,protocol:n,publicKey:r})}function dsnFromComponents(t){return{protocol:t.protocol,publicKey:t.publicKey||"",pass:t.pass||"",host:t.host,port:t.port||"",path:t.path||"",projectId:t.projectId}}function validateDsn(t){if(!DEBUG_BUILD$2)return!0;const{port:e,projectId:n,protocol:r}=t;return!(["protocol","publicKey","host","projectId"].find(e=>!t[e]&&(debug.error(`Invalid Sentry Dsn: ${e} missing`),!0))||(n.match(/^\d+$/)?isValidProtocol(r)?e&&isNaN(parseInt(e,10))&&(debug.error(`Invalid Sentry Dsn: Invalid port ${e}`),1):(debug.error(`Invalid Sentry Dsn: Invalid protocol ${r}`),1):(debug.error(`Invalid Sentry Dsn: Invalid projectId ${n}`),1)))}function extractOrgIdFromDsnHost(t){const e=t.match(ORG_ID_REGEX);return e?.[1]}function extractOrgIdFromClient(t){const e=t.getOptions(),{host:n}=t.getDsn()||{};let r;return e.orgId?r=String(e.orgId):n&&(r=extractOrgIdFromDsnHost(n)),r}function makeDsn(t){const e="string"==typeof t?dsnFromString(t):dsnFromComponents(t);if(e&&validateDsn(e))return e}function parseSampleRate(t){if("boolean"==typeof t)return Number(t);const e="string"==typeof t?parseFloat(t):t;return"number"!=typeof e||isNaN(e)||e<0||e>1?void 0:e}const TRACEPARENT_REGEXP=new RegExp("^[ \\t]*([0-9a-f]{32})?-?([0-9a-f]{16})?-?([01])?[ \\t]*$");function extractTraceparentData(t){if(!t)return;const e=t.match(TRACEPARENT_REGEXP);if(!e)return;let n;return"1"===e[3]?n=!0:"0"===e[3]&&(n=!1),{traceId:e[1],parentSampled:n,parentSpanId:e[2]}}function propagationContextFromHeaders(t,e){const n=extractTraceparentData(t),r=baggageHeaderToDynamicSamplingContext(e);if(!n?.traceId)return{traceId:generateTraceId(),sampleRand:safeMathRandom()};const i=getSampleRandFromTraceparentAndDsc(n,r);r&&(r.sample_rand=i.toString());const{traceId:s,parentSpanId:a,parentSampled:o}=n;return{traceId:s,parentSpanId:a,sampled:o,dsc:r||{},sampleRand:i}}function generateSentryTraceHeader(t=generateTraceId(),e=generateSpanId(),n){let r="";return void 0!==n&&(r=n?"-1":"-0"),`${t}-${e}${r}`}function generateTraceparentHeader(t=generateTraceId(),e=generateSpanId(),n){return`00-${t}-${e}-${n?"01":"00"}`}function getSampleRandFromTraceparentAndDsc(t,e){const n=parseSampleRate(e?.sample_rand);if(void 0!==n)return n;const r=parseSampleRate(e?.sample_rate);return r&&void 0!==t?.parentSampled?t.parentSampled?safeMathRandom()*r:r+safeMathRandom()*(1-r):safeMathRandom()}const TRACE_FLAG_NONE=0,TRACE_FLAG_SAMPLED=1;let hasShownSpanDropWarning=!1;function spanToTransactionTraceContext(t){const{spanId:e,traceId:n}=t.spanContext(),{data:r,op:i,parent_span_id:s,status:a,origin:o,links:l}=spanToJSON(t);return{parent_span_id:s,span_id:e,trace_id:n,data:r,op:i,status:a,origin:o,links:l}}function spanToTraceContext(t){const{spanId:e,traceId:n,isRemote:r}=t.spanContext(),i=r?e:spanToJSON(t).parent_span_id,s=getCapturedScopesOnSpan(t).scope;return{parent_span_id:i,span_id:r?s?.getPropagationContext().propagationSpanId||generateSpanId():e,trace_id:n}}function spanToTraceHeader(t){const{traceId:e,spanId:n}=t.spanContext();return generateSentryTraceHeader(e,n,spanIsSampled(t))}function spanToTraceparentHeader(t){const{traceId:e,spanId:n}=t.spanContext();return generateTraceparentHeader(e,n,spanIsSampled(t))}function convertSpanLinksForEnvelope(t){return t&&t.length>0?t.map(({context:{spanId:t,traceId:e,traceFlags:n,...r},attributes:i})=>({span_id:t,trace_id:e,sampled:n===TRACE_FLAG_SAMPLED,attributes:i,...r})):void 0}function getStreamedSpanLinks(t){return t?.length?t.map(({context:{spanId:t,traceId:e,traceFlags:n},attributes:r})=>({span_id:t,trace_id:e,sampled:n===TRACE_FLAG_SAMPLED,attributes:r})):void 0}function spanTimeInputToSeconds(t){return"number"==typeof t?ensureTimestampInSeconds(t):Array.isArray(t)?t[0]+t[1]/1e9:t instanceof Date?ensureTimestampInSeconds(t.getTime()):timestampInSeconds()}function ensureTimestampInSeconds(t){return t>9999999999?t/1e3:t}function spanToJSON(t){if(spanIsSentrySpan(t))return t.getSpanJSON();const{spanId:e,traceId:n}=t.spanContext();if(spanIsOpenTelemetrySdkTraceBaseSpan(t)){const{attributes:r,startTime:i,name:s,endTime:a,status:o,links:l}=t;return{span_id:e,trace_id:n,data:r,description:s,parent_span_id:getOtelParentSpanId(t),start_timestamp:spanTimeInputToSeconds(i),timestamp:spanTimeInputToSeconds(a)||void 0,status:getStatusMessage(o),op:r[SEMANTIC_ATTRIBUTE_SENTRY_OP],origin:r[SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN],links:convertSpanLinksForEnvelope(l)}}return{span_id:e,trace_id:n,start_timestamp:0,data:{}}}function spanToStreamedSpanJSON(t){if(spanIsSentrySpan(t))return t.getStreamedSpanJSON();const{spanId:e,traceId:n}=t.spanContext();if(spanIsOpenTelemetrySdkTraceBaseSpan(t)){const{attributes:r,startTime:i,name:s,endTime:a,status:o,links:l}=t;return{name:s,span_id:e,trace_id:n,parent_span_id:getOtelParentSpanId(t),start_timestamp:spanTimeInputToSeconds(i),end_timestamp:spanTimeInputToSeconds(a),is_segment:t===INTERNAL_getSegmentSpan(t),status:getSimpleStatus(o),attributes:addStatusMessageAttribute(r,o),links:getStreamedSpanLinks(l)}}return{span_id:e,trace_id:n,start_timestamp:0,name:"",end_timestamp:0,status:"ok",is_segment:t===INTERNAL_getSegmentSpan(t)}}function getOtelParentSpanId(t){return"parentSpanId"in t?t.parentSpanId:"parentSpanContext"in t?t.parentSpanContext?.spanId:void 0}function streamedSpanJsonToSerializedSpan(t){return{...t,attributes:serializeAttributes(t.attributes),links:t.links?.map(t=>({...t,attributes:serializeAttributes(t.attributes)}))}}function spanIsOpenTelemetrySdkTraceBaseSpan(t){return!!(t.attributes&&t.startTime&&t.name&&t.endTime&&t.status)}function spanIsSentrySpan(t){return"function"==typeof t.getSpanJSON}function spanIsSampled(t){const{traceFlags:e}=t.spanContext();return e===TRACE_FLAG_SAMPLED}function getStatusMessage(t){if(t&&t.code!==SPAN_STATUS_UNSET)return t.code===SPAN_STATUS_OK?"ok":t.message||"internal_error"}function getSimpleStatus(t){return t&&t.code!==SPAN_STATUS_OK&&t.code!==SPAN_STATUS_UNSET&&"cancelled"!==t.message?"error":"ok"}function addStatusMessageAttribute(t,e){const n="error"===getSimpleStatus(e)?e?.message:void 0;return{...n&&{[SEMANTIC_ATTRIBUTE_SENTRY_STATUS_MESSAGE]:n},...t}}const CHILD_SPANS_FIELD="_sentryChildSpans",ROOT_SPAN_FIELD="_sentryRootSpan";function addChildSpanToSpan(t,e){addNonEnumerableProperty(e,ROOT_SPAN_FIELD,t[ROOT_SPAN_FIELD]||t),t[CHILD_SPANS_FIELD]?t[CHILD_SPANS_FIELD].add(e):addNonEnumerableProperty(t,CHILD_SPANS_FIELD,/* @__PURE__ */new Set([e]))}function removeChildSpanFromSpan(t,e){t[CHILD_SPANS_FIELD]&&t[CHILD_SPANS_FIELD].delete(e)}function getSpanDescendants(t){const e=/* @__PURE__ */new Set;return function t(n){if(!e.has(n)&&spanIsSampled(n)){e.add(n);const r=n[CHILD_SPANS_FIELD]?Array.from(n[CHILD_SPANS_FIELD]):[];for(const e of r)t(e)}}(t),Array.from(e)}const getRootSpan=INTERNAL_getSegmentSpan;function INTERNAL_getSegmentSpan(t){return t[ROOT_SPAN_FIELD]||t}function getActiveSpan(){const t=getAsyncContextStrategy(getMainCarrier());return t.getActiveSpan?t.getActiveSpan():_getSpanForScope(getCurrentScope())}function showSpanDropWarning(){hasShownSpanDropWarning||(consoleSandbox(()=>{console.warn("[Sentry] Returning null from `beforeSendSpan` is disallowed. To drop certain spans, configure the respective integrations directly or use `ignoreSpans`.")}),hasShownSpanDropWarning=!0)}let errorsInstrumented=!1;function registerSpanErrorInstrumentation(){function t(){const t=getActiveSpan(),e=t&&getRootSpan(t);if(e){const t="internal_error";DEBUG_BUILD$2&&debug.log(`[Tracing] Root span: ${t} -> Global error occurred`),e.setStatus({code:SPAN_STATUS_ERROR,message:t})}}errorsInstrumented||(errorsInstrumented=!0,addGlobalErrorInstrumentationHandler(t),addGlobalUnhandledRejectionInstrumentationHandler(t))}function hasSpansEnabled(t){if("boolean"==typeof __SENTRY_TRACING__&&!__SENTRY_TRACING__)return!1;const e=t||getClient()?.getOptions();return!(!e||null==e.tracesSampleRate&&!e.tracesSampler)}function logIgnoredSpan(t){debug.log(`Ignoring span ${t.op} - ${t.description} because it matches \`ignoreSpans\`.`)}function shouldIgnoreSpan(t,e){if(!e?.length)return!1;for(const n of e){if(isStringOrRegExp(n)){if(t.description&&isMatchingPattern(t.description,n))return DEBUG_BUILD$2&&logIgnoredSpan(t),!0;continue}const e=!!n.attributes&&Object.keys(n.attributes).length>0;if(!n.name&&!n.op&&!e)continue;const r=!n.name||t.description&&isMatchingPattern(t.description,n.name),i=!n.op||t.op&&isMatchingPattern(t.op,n.op),s=!n.attributes||Object.entries(n.attributes).every(([e,n])=>_matchesAttributeValue(t.attributes?.[e],n));if(r&&i&&s)return DEBUG_BUILD$2&&logIgnoredSpan(t),!0}return!1}function _matchesAttributeValue(t,e){return"string"==typeof t&&("string"==typeof e||e instanceof RegExp)?isMatchingPattern(t,e):Array.isArray(t)&&Array.isArray(e)?t.length===e.length&&t.every((t,n)=>t===e[n]):t===e}function reparentChildSpans(t,e){const n=e.parent_span_id,r=e.span_id;if(n)for(const e of t)e.parent_span_id===r&&(e.parent_span_id=n)}function isStringOrRegExp(t){return"string"==typeof t||t instanceof RegExp}const NON_RECORDING_SPAN_FIELD=/* @__PURE__ */Symbol.for("sentry.nonRecordingSpan");class SentryNonRecordingSpan{constructor(t={}){this._traceId=t.traceId||generateTraceId(),this._spanId=t.spanId||generateSpanId(),this.dropReason=t.dropReason,addNonEnumerableProperty(this,NON_RECORDING_SPAN_FIELD,!0)}spanContext(){return{spanId:this._spanId,traceId:this._traceId,traceFlags:TRACE_FLAG_NONE}}end(t){}setAttribute(t,e){return this}setAttributes(t){return this}setStatus(t){return this}updateName(t){return this}isRecording(){return!1}addEvent(t,e,n){return this}addLink(t){return this}addLinks(t){return this}recordException(t,e){}}function spanIsNonRecordingSpan(t){return!!t&&!0===t[NON_RECORDING_SPAN_FIELD]}const DEFAULT_ENVIRONMENT="production",FROZEN_DSC_FIELD="_frozenDsc";function freezeDscOnSpan(t,e){addNonEnumerableProperty(t,FROZEN_DSC_FIELD,e)}function getDynamicSamplingContextFromClient(t,e){const n=e.getOptions(),{publicKey:r}=e.getDsn()||{},i={environment:n.environment||DEFAULT_ENVIRONMENT,release:n.release,public_key:r,trace_id:t,org_id:extractOrgIdFromClient(e)};return e.emit("createDsc",i),i}function getDynamicSamplingContextFromScope(t,e){const n=e.getPropagationContext();return n.dsc||getDynamicSamplingContextFromClient(n.traceId,t)}function getDynamicSamplingContextFromSpan(t){const e=getClient();if(!e)return{};const n=getRootSpan(t),r=spanToJSON(n),i=r.data,s=n.spanContext().traceState,a=s?.get("sentry.sample_rate")??i[SEMANTIC_ATTRIBUTE_SENTRY_SAMPLE_RATE]??i[SEMANTIC_ATTRIBUTE_SENTRY_PREVIOUS_TRACE_SAMPLE_RATE];function o(t){return"number"!=typeof a&&"string"!=typeof a||(t.sample_rate=`${a}`),t}const l=n[FROZEN_DSC_FIELD];if(l)return o(l);const c=spanIsNonRecordingSpan(n),d=c&&"ignored"===n.dropReason;if(c&&(!hasSpansEnabled(e.getOptions())||d)){const t=getCapturedScopesOnSpan(n).scope;if(t){const n={...getDynamicSamplingContextFromScope(e,t)};return d&&(n.sampled="false"),o(n)}}const h=s?.get("sentry.dsc"),u=h&&baggageHeaderToDynamicSamplingContext(h);if(u)return o(u);const p=getDynamicSamplingContextFromClient(t.spanContext().traceId,e),f=r.description;return"url"!==(i[SEMANTIC_ATTRIBUTE_SENTRY_SOURCE]??i["sentry.segment.name.source"])&&f&&(p.transaction=f),hasSpansEnabled()&&(p.sampled=String(spanIsSampled(n)),p.sample_rand=s?.get("sentry.sample_rand")??getCapturedScopesOnSpan(n).scope?.getPropagationContext().sampleRand.toString()),o(p),e.emit("createDsc",p,n),p}function isStreamedBeforeSendSpanCallback(t){return!!t&&"function"==typeof t&&"_streamed"in t&&!!t._streamed}function createEnvelope(t,e=[]){return[t,e]}function addItemToEnvelope(t,e){const[n,r]=t;return[n,[...r,e]]}function forEachEnvelopeItem(t,e){const n=t[1];for(const t of n)if(e(t,t[0].type))return!0;return!1}function envelopeContainsItemType(t,e){return forEachEnvelopeItem(t,(t,n)=>e.includes(n))}function encodeUTF8(t){const e=getSentryCarrier(GLOBAL_OBJ);return e.encodePolyfill?e.encodePolyfill(t):(new TextEncoder).encode(t)}function serializeEnvelope(t){const[e,n]=t;let r=JSON.stringify(e);function i(t){"string"==typeof r?r="string"==typeof t?r+t:[encodeUTF8(r),t]:r.push("string"==typeof t?encodeUTF8(t):t)}for(const t of n){const[e,n]=t;if(i(`\n${JSON.stringify(e)}\n`),"string"==typeof n||n instanceof Uint8Array)i(n);else{let t;try{t=JSON.stringify(n)}catch{t=JSON.stringify(normalize(n))}i(t)}}return"string"==typeof r?r:concatBuffers(r)}function concatBuffers(t){const e=t.reduce((t,e)=>t+e.length,0),n=new Uint8Array(e);let r=0;for(const e of t)n.set(e,r),r+=e.length;return n}function createSpanEnvelopeItem(t){return[{type:"span"},t]}function createAttachmentEnvelopeItem(t){const e="string"==typeof t.data?encodeUTF8(t.data):t.data;return[{type:"attachment",length:e.length,filename:t.filename,content_type:t.contentType,attachment_type:t.attachmentType},e]}const DATA_CATEGORY_OVERRIDES={sessions:"session",event:"error",client_report:"internal",user_report:"default",profile_chunk:"profile",replay_event:"replay",replay_recording:"replay",check_in:"monitor",raw_security:"security",log:"log_item",trace_metric:"metric"};function _isOverriddenType(t){return t in DATA_CATEGORY_OVERRIDES}function envelopeItemTypeToDataCategory(t){return _isOverriddenType(t)?DATA_CATEGORY_OVERRIDES[t]:t}function getSdkMetadataForEnvelopeHeader(t){if(!t?.sdk)return;const{name:e,version:n}=t.sdk;return{name:e,version:n}}function createEventEnvelopeHeaders(t,e,n,r){const i=t.sdkProcessingMetadata?.dynamicSamplingContext;return{event_id:t.event_id,sent_at:new Date(safeDateNow()).toISOString(),...e&&{sdk:e},...!!n&&r&&{dsn:dsnToString(r)},...i&&{trace:i}}}function _enhanceEventWithSdkInfo(t,e){if(!e)return t;const n=t.sdk||{};return t.sdk={...n,name:n.name||e.name,version:n.version||e.version,integrations:[...t.sdk?.integrations||[],...e.integrations||[]],packages:[...t.sdk?.packages||[],...e.packages||[]],settings:t.sdk?.settings||e.settings?{...t.sdk?.settings,...e.settings}:void 0},t}function createSessionEnvelope(t,e,n,r){const i=getSdkMetadataForEnvelopeHeader(n);return createEnvelope({sent_at:new Date(safeDateNow()).toISOString(),...i&&{sdk:i},...!!r&&e&&{dsn:dsnToString(e)}},["aggregates"in t?[{type:"sessions"},t]:[{type:"session"},t.toJSON()]])}function createEventEnvelope(t,e,n,r){const i=getSdkMetadataForEnvelopeHeader(n),s=t.type&&"replay_event"!==t.type?t.type:"event";_enhanceEventWithSdkInfo(t,n?.sdk);const a=createEventEnvelopeHeaders(t,i,r,e);return delete t.sdkProcessingMetadata,createEnvelope(a,[[{type:s},t]])}function createSpanEnvelope(t,e){const n=getDynamicSamplingContextFromSpan(t[0]),r=e?.getDsn(),i=e?.getOptions().tunnel,s={sent_at:new Date(safeDateNow()).toISOString(),...(a=n,!!a.trace_id&&!!a.public_key&&{trace:n}),...!!i&&r&&{dsn:dsnToString(r)}};var a;const{beforeSendSpan:o,ignoreSpans:l}=e?.getOptions()||{},c=l?.length?t.filter(t=>{const e=spanToJSON(t);return!shouldIgnoreSpan({description:e.description,op:e.op,attributes:e.data},l)}):t,d=t.length-c.length;d&&e?.recordDroppedEvent("before_send","span",d);const h=o?t=>{const e=spanToJSON(t);return(isStreamedBeforeSendSpanCallback(o)?e:o(e))||(showSpanDropWarning(),e)}:spanToJSON,u=[];for(const t of c){const e=h(t);e&&u.push(createSpanEnvelopeItem(e))}return createEnvelope(s,u)}function logSpanStart(t){if(!DEBUG_BUILD$2)return;const{description:e="< unknown name >",op:n="< unknown op >",parent_span_id:r}=spanToJSON(t),{spanId:i}=t.spanContext(),s=spanIsSampled(t),a=getRootSpan(t),o=a===t,l=`[Tracing] Starting ${s?"sampled":"unsampled"} ${o?"root ":""}span`,c=[`op: ${n}`,`name: ${e}`,`ID: ${i}`];if(r&&c.push(`parent ID: ${r}`),!o){const{op:t,description:e}=spanToJSON(a);c.push(`root ID: ${a.spanContext().spanId}`),t&&c.push(`root op: ${t}`),e&&c.push(`root description: ${e}`)}debug.log(`${l}\n ${c.join("\n ")}`)}function logSpanEnd(t){if(!DEBUG_BUILD$2)return;const{description:e="< unknown name >",op:n="< unknown op >"}=spanToJSON(t),{spanId:r}=t.spanContext(),i=getRootSpan(t);debug.log(`[Tracing] Finishing "${n}" ${i===t?"root ":""}span "${e}" with ID ${r}`)}function setMeasurement(t,e,n,r=getActiveSpan()){const i=r&&getRootSpan(r);i&&(DEBUG_BUILD$2&&debug.log(`[Measurement] Setting measurement on root span: ${t} = ${e} ${n}`),i.addEvent(t,{[SEMANTIC_ATTRIBUTE_SENTRY_MEASUREMENT_VALUE]:e,[SEMANTIC_ATTRIBUTE_SENTRY_MEASUREMENT_UNIT]:n}))}function timedEventsToMeasurements(t){if(!t||0===t.length)return;const e={};return t.forEach(t=>{const n=t.attributes||{},r=n[SEMANTIC_ATTRIBUTE_SENTRY_MEASUREMENT_UNIT],i=n[SEMANTIC_ATTRIBUTE_SENTRY_MEASUREMENT_VALUE];"string"==typeof r&&"number"==typeof i&&(e[t.name]={value:i,unit:r})}),e}function getSegmentSpanCaptureStrategy(){return getSentryCarrier(getMainCarrier()).segmentSpanCaptureStrategy}function hasSpanStreamingEnabled(t){return"stream"===t.getOptions().traceLifecycle}const MAX_SPAN_COUNT=1e3;class SentrySpan{constructor(t={}){this._traceId=t.traceId||generateTraceId(),this._spanId=t.spanId||generateSpanId(),this._startTime=t.startTimestamp||timestampInSeconds(),this._links=t.links,this._attributes={},this.setAttributes({[SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN]:"manual",[SEMANTIC_ATTRIBUTE_SENTRY_OP]:t.op,...t.attributes}),this._name=t.name,t.parentSpanId&&(this._parentSpanId=t.parentSpanId),"sampled"in t&&(this._sampled=t.sampled),t.endTimestamp&&(this._endTime=t.endTimestamp),this._events=[],this._isStandaloneSpan=t.isStandalone,this._endTime&&this._onSpanEnded()}addLink(t){return this._frozen||(this._links?this._links.push(t):this._links=[t]),this}addLinks(t){return this._frozen||(this._links?this._links.push(...t):this._links=t),this}recordException(t,e){}spanContext(){const{_spanId:t,_traceId:e,_sampled:n}=this;return{spanId:t,traceId:e,traceFlags:n?TRACE_FLAG_SAMPLED:TRACE_FLAG_NONE}}setAttribute(t,e){return this._frozen||(void 0===e?delete this._attributes[t]:this._attributes[t]=e,t===SEMANTIC_ATTRIBUTE_SENTRY_SOURCE&&void 0!==e&&spanShouldInferOtelSource(this)&&markSpanSourceAsExplicit(this)),this}setAttributes(t){return Object.keys(t).forEach(e=>this.setAttribute(e,t[e])),this}updateStartTime(t){this._frozen||(this._startTime=spanTimeInputToSeconds(t))}setStatus(t){return this._frozen||(this._status=t),this}updateName(t){return this._frozen||(this._name=t,spanShouldInferOtelSource(this)||this.setAttribute(SEMANTIC_ATTRIBUTE_SENTRY_SOURCE,"custom")),this}end(t){this._endTime||(this._endTime=spanTimeInputToSeconds(t),logSpanEnd(this),this._onSpanEnded()),this._frozen=spanIsTracerProviderSpan(this)}getSpanJSON(){return{data:this._attributes,description:this._name,op:this._attributes[SEMANTIC_ATTRIBUTE_SENTRY_OP],parent_span_id:this._parentSpanId,span_id:this._spanId,start_timestamp:this._startTime,status:getStatusMessage(this._status),timestamp:this._endTime,trace_id:this._traceId,origin:this._attributes[SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN],profile_id:this._attributes[SEMANTIC_ATTRIBUTE_PROFILE_ID],exclusive_time:this._attributes[SEMANTIC_ATTRIBUTE_EXCLUSIVE_TIME],measurements:timedEventsToMeasurements(this._events),is_segment:this._isStandaloneSpan&&getRootSpan(this)===this||void 0,segment_id:this._isStandaloneSpan?getRootSpan(this).spanContext().spanId:void 0,links:convertSpanLinksForEnvelope(this._links)}}getStreamedSpanJSON(){return{name:this._name??"",span_id:this._spanId,trace_id:this._traceId,parent_span_id:this._parentSpanId,start_timestamp:this._startTime,end_timestamp:this._endTime??this._startTime,is_segment:this._isStandaloneSpan||this===getRootSpan(this),status:getSimpleStatus(this._status),attributes:addStatusMessageAttribute(this._attributes,this._status),links:getStreamedSpanLinks(this._links)}}isRecording(){return!this._endTime&&!!this._sampled}addEvent(t,e,n){if(this._frozen)return this;DEBUG_BUILD$2&&debug.log("[Tracing] Adding an event to span:",t);const r=isSpanTimeInput(e)?e:n||timestampInSeconds(),i=isSpanTimeInput(e)?{}:e||{},s={name:t,time:spanTimeInputToSeconds(r),attributes:i};return this._events.push(s),this}isStandaloneSpan(){return!!this._isStandaloneSpan}_onSpanEnded(){const t=getClient();t&&(t.emit("spanEnd",this),this._isStandaloneSpan||t.emit("afterSpanEnd",this));const e=getRootSpan(this),n=this._isStandaloneSpan||this===e;if(this._isStandaloneSpan)return void(this._sampled?sendSpanEnvelope(createSpanEnvelope([this],t)):(DEBUG_BUILD$2&&debug.log("[Tracing] Discarding standalone span because its trace was not chosen to be sampled."),t&&t.recordDroppedEvent("sample_rate","span")));if(!n){const t=getSegmentSpanCaptureStrategy();if(t){const n=getCapturedScopesOnSpan(this).scope||getCurrentScope();t.onChildSpanEnded(this,e,t=>this._convertSpanToTransaction(t),n)}return}if(t&&hasSpanStreamingEnabled(t))return void t.emit("afterSegmentSpanEnd",this);const r=getCapturedScopesOnSpan(this).scope||getCurrentScope(),i=getSegmentSpanCaptureStrategy();if(i)i.onSegmentSpanEnded(t=>this._convertSpanToTransaction(t),r);else{const t=this._convertSpanToTransaction();t&&r.captureEvent(t)}}_convertSpanToTransaction(t={}){if(!isFullFinishedSpan(spanToJSON(this)))return;this._name||(DEBUG_BUILD$2&&debug.warn("Transaction has no name, falling back to `<unlabeled transaction>`."),this._name="<unlabeled transaction>");const{scope:e,isolationScope:n}=getCapturedScopesOnSpan(this),r=e?.getScopeData().sdkProcessingMetadata?.normalizedRequest;if(!0!==this._sampled)return;t.onSpanCaptured?.(this);const i=[];for(const e of getSpanDescendants(this)){if(e===this||isStandaloneSpan(e)||t.isSpanAlreadyCaptured?.(e))continue;const n=spanToJSON(e);isFullFinishedSpan(n)&&(t.onSpanCaptured?.(e),i.push(n))}const s=this._attributes[SEMANTIC_ATTRIBUTE_SENTRY_SOURCE];delete this._attributes[SEMANTIC_ATTRIBUTE_SENTRY_CUSTOM_SPAN_NAME];let a=!1;i.forEach(t=>{delete t.data[SEMANTIC_ATTRIBUTE_SENTRY_CUSTOM_SPAN_NAME],t.op?.startsWith("gen_ai.")&&(a=!0)});const o={contexts:{trace:spanToTransactionTraceContext(this)},spans:i.length>MAX_SPAN_COUNT?i.sort((t,e)=>t.start_timestamp-e.start_timestamp).slice(0,MAX_SPAN_COUNT):i,start_timestamp:this._startTime,timestamp:this._endTime,transaction:this._name,type:"transaction",sdkProcessingMetadata:{capturedSpanScope:e,capturedSpanIsolationScope:n,dynamicSamplingContext:getDynamicSamplingContextFromSpan(this),hasGenAiSpans:a},request:r,...s&&{transaction_info:{source:s}}},l=timedEventsToMeasurements(this._events);return l&&Object.keys(l).length&&(DEBUG_BUILD$2&&debug.log("[Measurements] Adding measurements to transaction event",JSON.stringify(l,void 0,2)),o.measurements=l),o}}function isSpanTimeInput(t){return t&&"number"==typeof t||t instanceof Date||Array.isArray(t)}function isFullFinishedSpan(t){return!!(t.start_timestamp&&t.timestamp&&t.span_id&&t.trace_id)}function isStandaloneSpan(t){return t instanceof SentrySpan&&t.isStandaloneSpan()}function sendSpanEnvelope(t){const e=getClient();if(!e)return;const n=t[1];n&&0!==n.length?e.sendEnvelope(t):e.recordDroppedEvent("before_send","span")}function handleCallbackErrors(t,e,n=()=>{},r=()=>{}){let i;try{i=t()}catch(t){throw e(t),n(),t}return maybeHandlePromiseRejection(i,e,n,r)}function maybeHandlePromiseRejection(t,e,n,r){return isThenable(t)?chainAndCopyPromiseLike(t,t=>{n(),r(t)},t=>{e(t),n()}):(n(),r(t),t)}function sampleSpan(t,e,n){if(!hasSpansEnabled(t))return[!1];let r,i;"function"==typeof t.tracesSampler?(i=t.tracesSampler({...e,inheritOrSampleWith:t=>"number"==typeof e.parentSampleRate?e.parentSampleRate:"boolean"==typeof e.parentSampled?Number(e.parentSampled):t}),r=!0):void 0!==e.parentSampled?i=e.parentSampled:void 0!==t.tracesSampleRate&&(i=t.tracesSampleRate,r=!0);const s=parseSampleRate(i);if(void 0===s)return DEBUG_BUILD$2&&debug.warn(`[Tracing] Discarding root span because of invalid sample rate. Sample rate must be a boolean or a number between 0 and 1. Got ${JSON.stringify(i)} of type ${JSON.stringify(typeof i)}.`),[!1];if(!s)return DEBUG_BUILD$2&&debug.log("[Tracing] Discarding transaction because "+("function"==typeof t.tracesSampler?"tracesSampler returned 0 or false":"a negative sampling decision was inherited or tracesSampleRate is set to 0")),[!1,s,r];const a=n<s;return a||DEBUG_BUILD$2&&debug.log(`[Tracing] Discarding transaction because it's not included in the random sample (sampling rate = ${Number(i)})`),[a,s,r]}const SUPPRESS_TRACING_KEY="__SENTRY_SUPPRESS_TRACING__";function startSpan(t,e){const n=getAcs();if(n.startSpan)return n.startSpan(t,e);const r=parseSentrySpanArguments(t),{forceTransaction:i,parentSpan:s,scope:a}=t,o=a?.clone();return withScope(o,()=>getActiveSpanWrapper(s)(()=>{const n=getCurrentScope(),a=getParentSpan(n,s),o=getClient(),l=t.onlyIfParent&&!a?startMissingRequiredParentSpan(n,o):createChildOrRootSpan({parentSpan:a,spanArguments:r,forceTransaction:i,scope:n});return spanIsIgnored(l)&&a||_setSpanForScope(n,l),handleCallbackErrors(()=>e(l),()=>{const{status:t}=spanToJSON(l);!l.isRecording()||t&&"ok"!==t||l.setStatus({code:SPAN_STATUS_ERROR,message:"internal_error"})},()=>{l.end()})}))}function startInactiveSpan(t){const e=getAcs();return e.startInactiveSpan?e.startInactiveSpan(t):_startInactiveSpanImpl(t)}function _startInactiveSpanImpl(t){const e=parseSentrySpanArguments(t),{forceTransaction:n,parentSpan:r}=t;return(t.scope?e=>withScope(t.scope,e):void 0!==r?t=>withActiveSpan(r,t):t=>t())(()=>{const i=getCurrentScope(),s=getParentSpan(i,r),a=getClient();return t.onlyIfParent&&!s?startMissingRequiredParentSpan(i,a):createChildOrRootSpan({parentSpan:s,spanArguments:e,forceTransaction:n,scope:i})})}function withActiveSpan(t,e){const n=getAcs();return n.withActiveSpan?n.withActiveSpan(t,e):withScope(n=>(_setSpanForScope(n,t||void 0),e(n)))}function isTracingSuppressed(t=getCurrentScope()){const e=getAcs();return e.isTracingSuppressed?e.isTracingSuppressed(t):!0===t.getScopeData().sdkProcessingMetadata[SUPPRESS_TRACING_KEY]}function startMissingRequiredParentSpan(t,e){e?.recordDroppedEvent("no_parent_span","span");const n=new SentryNonRecordingSpan({traceId:t.getPropagationContext().traceId});return setCapturedScopesOnSpan(n,t,getIsolationScope()),n}function createChildOrRootSpan({parentSpan:t,spanArguments:e,forceTransaction:n,scope:r}){const i=getIsolationScope();if(!hasSpansEnabled()){const e={...i.getPropagationContext(),...r.getPropagationContext()},s=t?t.spanContext().traceId:e.traceId,a=new SentryNonRecordingSpan({traceId:s});return t&&!n&&addChildSpanToSpan(t,a),setCapturedScopesOnSpan(a,r,i),a}const s=getClient();if(_shouldIgnoreStreamedSpan(s,e)){isTracingSuppressed(r)||s?.recordDroppedEvent("ignored","span");const e=new SentryNonRecordingSpan({dropReason:"ignored",traceId:t?.spanContext().traceId??r.getPropagationContext().traceId});return t&&!n&&addChildSpanToSpan(t,e),setCapturedScopesOnSpan(e,r,i),e}let a;if(t&&!n)a=_startChildSpan(t,r,e,i),addChildSpanToSpan(t,a);else if(t){const n=getDynamicSamplingContextFromSpan(t),{traceId:s,spanId:o}=t.spanContext(),l=spanIsSampled(t);a=_startRootSpan({traceId:s,parentSpanId:o,...e},r,i,l),freezeDscOnSpan(a,n)}else{const{traceId:t,dsc:n,parentSpanId:s,sampled:o}={...i.getPropagationContext(),...r.getPropagationContext()};a=_startRootSpan({traceId:t,parentSpanId:s,...e},r,i,o),n&&freezeDscOnSpan(a,n)}return logSpanStart(a),a}function parseSentrySpanArguments(t){const e={isStandalone:(t.experimental||{}).standalone,...t};if(t.startTime){const n={...e};return n.startTimestamp=spanTimeInputToSeconds(t.startTime),delete n.startTime,n}return e}function getAcs(){return getAsyncContextStrategy(getMainCarrier())}function _startRootSpan(t,e,n,r){const i=getClient(),s=i?.getOptions()||{},{name:a=""}=t,o={spanAttributes:{...t.attributes},spanName:a,parentSampled:r};i?.emit("beforeSampling",o,{decision:!1});const l=o.parentSampled??r,c=o.spanAttributes,d=e.getPropagationContext(),h=isTracingSuppressed(e),[u,p,f]=h?[!1]:sampleSpan(s,{name:a,parentSampled:l,attributes:c,normalizedRequest:n.getScopeData().sdkProcessingMetadata.normalizedRequest,parentSampleRate:parseSampleRate(d.dsc?.sample_rate)},d.sampleRand),m=new SentrySpan({...t,attributes:{[SEMANTIC_ATTRIBUTE_SENTRY_SOURCE]:"custom",[SEMANTIC_ATTRIBUTE_SENTRY_SAMPLE_RATE]:void 0!==p&&f?p:void 0,...c},sampled:u});return u||!i||h||(DEBUG_BUILD$2&&debug.log("[Tracing] Discarding root span because its trace was not chosen to be sampled."),i.recordDroppedEvent("sample_rate",hasSpanStreamingEnabled(i)?"span":"transaction")),setCapturedScopesOnSpan(m,e,n),i&&i.emit("spanStart",m),m}function _startChildSpan(t,e,n,r){const{spanId:i,traceId:s}=t.spanContext(),a=isTracingSuppressed(e),o=!a&&spanIsSampled(t),l=o?new SentrySpan({...n,parentSpanId:i,traceId:s,sampled:o}):new SentryNonRecordingSpan({traceId:s});addChildSpanToSpan(t,l),setCapturedScopesOnSpan(l,e,r);const c=getClient();return c?(hasSpanStreamingEnabled(c)&&spanIsNonRecordingSpan(l)&&(spanIsNonRecordingSpan(t)&&t.dropReason?(l.dropReason=t.dropReason,c.recordDroppedEvent(t.dropReason,"span")):a||(l.dropReason="sample_rate",c.recordDroppedEvent("sample_rate","span"))),c.emit("spanStart",l),n.endTimestamp&&(c.emit("spanEnd",l),c.emit("afterSpanEnd",l)),l):l}function getParentSpan(t,e){if(e)return e;if(null===e)return;const n=_getSpanForScope(t);if(!n)return;const r=getClient();return(r?r.getOptions():{}).parentSpanIsAlwaysRootSpan?getRootSpan(n):n}function getActiveSpanWrapper(t){return void 0!==t?e=>withActiveSpan(t,e):t=>t()}function _shouldIgnoreStreamedSpan(t,e){const n=t?.getOptions().ignoreSpans;return!!(t&&hasSpanStreamingEnabled(t)&&n?.length)&&shouldIgnoreSpan({description:e.name||"",op:e.attributes?.[SEMANTIC_ATTRIBUTE_SENTRY_OP]||e.op,attributes:e.attributes},n)}function spanIsIgnored(t){return spanIsNonRecordingSpan(t)&&"ignored"===t.dropReason}const TRACING_DEFAULTS={idleTimeout:1e3,finalTimeout:3e4,childSpanTimeout:15e3},FINISH_REASON_HEARTBEAT_FAILED="heartbeatFailed",FINISH_REASON_IDLE_TIMEOUT="idleTimeout",FINISH_REASON_FINAL_TIMEOUT="finalTimeout",FINISH_REASON_EXTERNAL_FINISH="externalFinish";function startIdleSpan(t,e={}){const n=/* @__PURE__ */new Map;let r,i=!1,s=FINISH_REASON_EXTERNAL_FINISH,a=!e.disableAutoFinish;const o=[],{idleTimeout:l=TRACING_DEFAULTS.idleTimeout,finalTimeout:c=TRACING_DEFAULTS.finalTimeout,childSpanTimeout:d=TRACING_DEFAULTS.childSpanTimeout,beforeSpanEnd:h,trimIdleSpanEndTimestamp:u=!0}=e,p=getClient(),f=getCurrentScope();if(!p||!hasSpansEnabled()){const t=new SentryNonRecordingSpan({traceId:f.getPropagationContext().traceId});return setCapturedScopesOnSpan(t,f,getIsolationScope()),t}const m=getActiveSpan(),_=_startIdleSpan(t);function g(){r&&(clearTimeout(r),r=void 0)}function y(t){g(),r=setTimeout(()=>{!i&&0===n.size&&a&&(s=FINISH_REASON_IDLE_TIMEOUT,_.end(t))},l)}function S(t){r=setTimeout(()=>{!i&&a&&(s=FINISH_REASON_HEARTBEAT_FAILED,_.end(t))},d)}function A(t){i=!0,n.clear(),o.forEach(t=>t()),_setSpanForScope(f,m);const e=spanToJSON(_),{start_timestamp:r}=e;if(!r)return;e.data[SEMANTIC_ATTRIBUTE_SENTRY_IDLE_SPAN_FINISH_REASON]||_.setAttribute(SEMANTIC_ATTRIBUTE_SENTRY_IDLE_SPAN_FINISH_REASON,s);const a=e.status;a&&"unknown"!==a||_.setStatus({code:SPAN_STATUS_OK}),debug.log(`[Tracing] Idle span "${e.op}" finished`);const d=getSpanDescendants(_).filter(t=>t!==_);let h=0;d.forEach(e=>{e.isRecording()&&(e.setStatus({code:SPAN_STATUS_ERROR,message:"cancelled"}),e.end(t),DEBUG_BUILD$2&&debug.log("[Tracing] Cancelling span since span ended early",JSON.stringify(e,void 0,2)));const n=spanToJSON(e),{timestamp:r=0,start_timestamp:i=0}=n,s=i<=t,a=r-i<=(c+l)/1e3;if(DEBUG_BUILD$2){const t=JSON.stringify(e,void 0,2);s?a||debug.log("[Tracing] Discarding span since it finished after idle span final timeout",t):debug.log("[Tracing] Discarding span since it happened after idle span was finished",t)}a&&s||(removeChildSpanFromSpan(_,e),h++)}),h>0&&_.setAttribute("sentry.idle_span_discarded_spans",h)}return _.end=new Proxy(_.end,{apply(t,e,n){if(h&&h(_),spanIsNonRecordingSpan(e))return;const[r,...i]=n,s=spanTimeInputToSeconds(r||timestampInSeconds()),a=getSpanDescendants(_).filter(t=>t!==_),o=spanToJSON(_);if(!a.length||!u)return A(s),Reflect.apply(t,e,[s,...i]);const l=p.getOptions().ignoreSpans,d=a?.reduce((t,e)=>{const n=spanToJSON(e);return n.timestamp?l&&shouldIgnoreSpan({description:n.description,op:n.op,attributes:n.data},l)?t:t?Math.max(t,n.timestamp):n.timestamp:t},void 0),f=o.start_timestamp,m=Math.min(f?f+c/1e3:Infinity,Math.max(f||-Infinity,Math.min(s,d||Infinity)));return A(m),Reflect.apply(t,e,[m,...i])}}),o.push(p.on("spanStart",t=>{var e;i||t===_||spanToJSON(t).timestamp||t instanceof SentrySpan&&t.isStandaloneSpan()||getSpanDescendants(_).includes(t)&&(e=t.spanContext().spanId,g(),n.set(e,!0),S(timestampInSeconds()+d/1e3))})),o.push(p.on("spanEnd",t=>{var e;i||(e=t.spanContext().spanId,n.has(e)&&n.delete(e),0===n.size&&y(timestampInSeconds()+l/1e3))})),o.push(p.on("idleSpanEnableAutoFinish",t=>{t===_&&(a=!0,y(),n.size&&S())})),e.disableAutoFinish||y(),setTimeout(()=>{i||(_.setStatus({code:SPAN_STATUS_ERROR,message:"deadline_exceeded"}),s=FINISH_REASON_FINAL_TIMEOUT,_.end())},c),_}function _startIdleSpan(t){const e=startInactiveSpan(t);return _setSpanForScope(getCurrentScope(),e),DEBUG_BUILD$2&&debug.log("[Tracing] Started span is an idle span"),e}function applyScopeDataToEvent(t,e){const{fingerprint:n,span:r,breadcrumbs:i,sdkProcessingMetadata:s}=e;applyDataToEvent(t,e),r&&applySpanToEvent(t,r),applyFingerprintToEvent(t,n),applyBreadcrumbsToEvent(t,i),applySdkMetadataToEvent(t,s)}function mergeScopeData(t,e){const{extra:n,tags:r,attributes:i,user:s,contexts:a,level:o,sdkProcessingMetadata:l,breadcrumbs:c,fingerprint:d,eventProcessors:h,attachments:u,propagationContext:p,transactionName:f,span:m}=e;mergeAndOverwriteScopeData(t,"extra",n),mergeAndOverwriteScopeData(t,"tags",r),mergeAndOverwriteScopeData(t,"attributes",i),mergeAndOverwriteScopeData(t,"user",s),mergeAndOverwriteScopeData(t,"contexts",a),t.sdkProcessingMetadata=merge(t.sdkProcessingMetadata,l,2),o&&(t.level=o),f&&(t.transactionName=f),m&&(t.span=m),c.length&&(t.breadcrumbs=[...t.breadcrumbs,...c]),d.length&&(t.fingerprint=[...t.fingerprint,...d]),h.length&&(t.eventProcessors=[...t.eventProcessors,...h]),u.length&&(t.attachments=[...t.attachments,...u]),t.propagationContext={...t.propagationContext,...p}}function mergeAndOverwriteScopeData(t,e,n){t[e]=merge(t[e],n,1)}function getCombinedScopeData(t,e){const n=getGlobalScope().getScopeData();return t&&mergeScopeData(n,t.getScopeData()),e&&mergeScopeData(n,e.getScopeData()),n}function applyDataToEvent(t,e){const{extra:n,tags:r,user:i,contexts:s,level:a,transactionName:o}=e;Object.keys(n).length&&(t.extra={...n,...t.extra}),Object.keys(r).length&&(t.tags={...r,...t.tags}),Object.keys(i).length&&(t.user={...i,...t.user}),Object.keys(s).length&&(t.contexts={...s,...t.contexts}),a&&(t.level=a),o&&"transaction"!==t.type&&(t.transaction=o)}function applyBreadcrumbsToEvent(t,e){const n=[...t.breadcrumbs||[],...e];t.breadcrumbs=n.length?n:void 0}function applySdkMetadataToEvent(t,e){t.sdkProcessingMetadata={...t.sdkProcessingMetadata,...e}}function applySpanToEvent(t,e){t.contexts={trace:spanToTraceContext(e),...t.contexts},t.sdkProcessingMetadata={dynamicSamplingContext:getDynamicSamplingContextFromSpan(e),...t.sdkProcessingMetadata};const n=spanToJSON(getRootSpan(e)).description;n&&!t.transaction&&"transaction"===t.type&&(t.transaction=n)}function applyFingerprintToEvent(t,e){t.fingerprint=t.fingerprint?Array.isArray(t.fingerprint)?t.fingerprint:[t.fingerprint]:[],e&&(t.fingerprint=t.fingerprint.concat(e)),t.fingerprint.length||delete t.fingerprint}const ws="http.url",Lc="sentry.segment.name",Xc="sentry.transaction",Yu="url.full",Vu="url.path";function safeSetSpanJSONAttributes(t,e){const n=t.attributes??(t.attributes={});Object.entries(e).forEach(([t,e])=>{null==e||t in n||(n[t]=e)})}const STATE_PENDING=0,STATE_RESOLVED=1,STATE_REJECTED=2;function resolvedSyncPromise(t){return new SyncPromise(e=>{e(t)})}function rejectedSyncPromise(t){return new SyncPromise((e,n)=>{n(t)})}class SyncPromise{constructor(t){this._state=STATE_PENDING,this._handlers=[],this._runExecutor(t)}then(t,e){return new SyncPromise((n,r)=>{this._handlers.push([!1,e=>{if(t)try{n(t(e))}catch(t){r(t)}else n(e)},t=>{if(e)try{n(e(t))}catch(t){r(t)}else r(t)}]),this._executeHandlers()})}catch(t){return this.then(t=>t,t)}finally(t){return new SyncPromise((e,n)=>{let r,i;return this.then(e=>{i=!1,r=e,t&&t()},e=>{i=!0,r=e,t&&t()}).then(()=>{i?n(r):e(r)})})}_executeHandlers(){if(this._state===STATE_PENDING)return;const t=this._handlers.slice();this._handlers=[],t.forEach(t=>{t[0]||(this._state===STATE_RESOLVED&&t[1](this._value),this._state===STATE_REJECTED&&t[2](this._value),t[0]=!0)})}_runExecutor(t){const e=(t,e)=>{this._state===STATE_PENDING&&(isThenable(e)?e.then(n,r):(this._state=t,this._value=e,this._executeHandlers()))},n=t=>{e(STATE_RESOLVED,t)},r=t=>{e(STATE_REJECTED,t)};try{t(n,r)}catch(t){r(t)}}}function notifyEventProcessors(t,e,n,r=0){try{const i=_notifyEventProcessors(e,n,t,r);return isThenable(i)?i:resolvedSyncPromise(i)}catch(t){return rejectedSyncPromise(t)}}function _notifyEventProcessors(t,e,n,r){const i=n[r];if(!t||!i)return t;const s=i({...t},e);return DEBUG_BUILD$2&&null===s&&debug.log(`Event processor "${i.id||"?"}" dropped event`),isThenable(s)?s.then(t=>_notifyEventProcessors(t,e,n,r+1)):_notifyEventProcessors(s,e,n,r+1)}let parsedStackResults,lastSentryKeysCount,lastNativeKeysCount,cachedFilenameDebugIds;function getFilenameToDebugIdMap(t){const e=GLOBAL_OBJ._sentryDebugIds,n=GLOBAL_OBJ._debugIds;if(!e&&!n)return{};const r=e?Object.keys(e):[],i=n?Object.keys(n):[];if(cachedFilenameDebugIds&&r.length===lastSentryKeysCount&&i.length===lastNativeKeysCount)return cachedFilenameDebugIds;lastSentryKeysCount=r.length,lastNativeKeysCount=i.length,cachedFilenameDebugIds={},parsedStackResults||(parsedStackResults={});const s=(e,n)=>{for(const r of e){const e=n[r],i=parsedStackResults?.[r];if(i&&cachedFilenameDebugIds&&e)cachedFilenameDebugIds[i[0]]=e,parsedStackResults&&(parsedStackResults[r]=[i[0],e]);else if(e){const n=t(r);for(let t=n.length-1;t>=0;t--){const i=n[t],s=i?.filename;if(s&&cachedFilenameDebugIds&&parsedStackResults){cachedFilenameDebugIds[s]=e,parsedStackResults[r]=[s,e];break}}}}};return e&&s(r,e),n&&s(i,n),cachedFilenameDebugIds}function prepareEvent(t,e,n,r,i,s){const{normalizeDepth:a=3,normalizeMaxBreadth:o=1e3}=t,l={...e,event_id:e.event_id||n.event_id||uuid4(),timestamp:e.timestamp||dateTimestampInSeconds()},c=n.integrations||t.integrations.map(t=>t.name);applyClientOptions(l,t),applyIntegrationsMetadata(l,c),i&&i.emit("applyFrameMetadata",e),void 0===e.type&&applyDebugIds(l,t.stackParser);const d=getFinalScope(r,n.captureContext);n.mechanism&&addExceptionMechanism(l,n.mechanism);const h=i?i.getEventProcessors():[],u=getCombinedScopeData(s,d),p=[...n.attachments||[],...u.attachments];p.length&&(n.attachments=p),applyScopeDataToEvent(l,u);const f=[...h,...u.eventProcessors];return(n.data&&!0===n.data.__sentry__?resolvedSyncPromise(l):notifyEventProcessors(f,l,n)).then(t=>(t&&applyDebugMeta(t),"number"==typeof a&&a>0?normalizeEvent(t,a,o):t))}function applyClientOptions(t,e){const{environment:n,release:r,dist:i,maxValueLength:s}=e;t.environment=t.environment||n||DEFAULT_ENVIRONMENT,!t.release&&r&&(t.release=r),!t.dist&&i&&(t.dist=i);const a=t.request;a?.url&&s&&(a.url=truncate(a.url,s)),s&&t.exception?.values?.forEach(t=>{t.value&&(t.value=truncate(t.value,s))})}function applyDebugIds(t,e){const n=getFilenameToDebugIdMap(e);t.exception?.values?.forEach(t=>{t.stacktrace?.frames?.forEach(t=>{t.filename&&(t.debug_id=n[t.filename])})})}function applyDebugMeta(t){const e={};if(t.exception?.values?.forEach(t=>{t.stacktrace?.frames?.forEach(t=>{t.debug_id&&(t.abs_path?e[t.abs_path]=t.debug_id:t.filename&&(e[t.filename]=t.debug_id),delete t.debug_id)})}),0===Object.keys(e).length)return;t.debug_meta=t.debug_meta||{},t.debug_meta.images=t.debug_meta.images||[];const n=t.debug_meta.images;Object.entries(e).forEach(([t,e])=>{n.push({type:"sourcemap",code_file:t,debug_id:e})})}function applyIntegrationsMetadata(t,e){e.length>0&&(t.sdk=t.sdk||{},t.sdk.integrations=[...t.sdk.integrations||[],...e])}function normalizeEvent(t,e,n){if(!t)return null;const r={...t,...t.breadcrumbs&&{breadcrumbs:t.breadcrumbs.map(t=>({...t,...t.data&&{data:normalize(t.data,e,n)}}))},...t.user&&{user:normalize(t.user,e,n)},...t.contexts&&{contexts:normalize(t.contexts,e,n)},...t.extra&&{extra:normalize(t.extra,e,n)}};return t.contexts?.trace&&r.contexts&&(r.contexts.trace=t.contexts.trace,t.contexts.trace.data&&(r.contexts.trace.data=normalize(t.contexts.trace.data,e,n))),t.spans&&(r.spans=t.spans.map(t=>({...t,...t.data&&{data:normalize(t.data,e,n)}}))),t.contexts?.flags&&r.contexts&&(r.contexts.flags=normalize(t.contexts.flags,3,n)),r}function getFinalScope(t,e){if(!e)return t;const n=t?t.clone():new Scope;return n.update(e),n}function parseEventHintOrCaptureContext(t){if(t)return hintIsScopeOrFunction(t)||hintIsScopeContext(t)?{captureContext:t}:t}function hintIsScopeOrFunction(t){return t instanceof Scope||"function"==typeof t}const captureContextKeys=["user","level","extra","contexts","tags","fingerprint","propagationContext"];function hintIsScopeContext(t){return Object.keys(t).some(t=>captureContextKeys.includes(t))}function captureException(t,e){return getCurrentScope().captureException(t,parseEventHintOrCaptureContext(e))}function captureEvent(t,e){return getCurrentScope().captureEvent(t,e)}function isEnabled(){const t=getClient();return!1!==t?.getOptions().enabled&&!!t?.getTransport()}function startSession(t){const e=getIsolationScope(),{user:n}=getCombinedScopeData(e,getCurrentScope()),{userAgent:r}=GLOBAL_OBJ.navigator||{},i=makeSession({user:n,...r&&{userAgent:r},...t}),s=e.getSession();return"ok"===s?.status&&updateSession(s,{status:"exited"}),endSession(),e.setSession(i),i}function endSession(){const t=getIsolationScope(),e=getCurrentScope().getSession()||t.getSession();e&&closeSession(e),_sendSessionUpdate(),t.setSession()}function _sendSessionUpdate(){const t=getIsolationScope(),e=getClient(),n=t.getSession();n&&e&&e.captureSession(n)}function captureSession(t=!1){t?endSession():_sendSessionUpdate()}function safeUnref(t){return"object"==typeof t&&"function"==typeof t.unref&&t.unref(),t}const SENTRY_API_VERSION="7";function getBaseApiEndpoint(t){return`${t.protocol?`${t.protocol}:`:""}//${t.host}${t.port?`:${t.port}`:""}${t.path?`/${t.path}`:""}/api/`}function _getIngestEndpoint(t){return`${getBaseApiEndpoint(t)}${t.projectId}/envelope/`}function _encodedAuth(t,e){const n={sentry_version:SENTRY_API_VERSION};return t.publicKey&&(n.sentry_key=t.publicKey),e&&(n.sentry_client=`${e.name}/${e.version}`),new URLSearchParams(n).toString()}function getEnvelopeEndpointWithUrlEncodedAuth(t,e,n){return e||`${_getIngestEndpoint(t)}?${_encodedAuth(t,n)}`}const installedIntegrations=[];function setupIntegrations(t,e){const n={};return e.forEach(e=>{e?.beforeSetup&&e.beforeSetup(t)}),e.forEach(e=>{e&&setupIntegration(t,e,n)}),n}function afterSetupIntegrations(t,e){for(const n of e)n?.afterAllSetup&&n.afterAllSetup(t)}function setupIntegration(t,e,n){if(n[e.name])DEBUG_BUILD$2&&debug.log(`Integration skipped because it was already installed: ${e.name}`);else{if(n[e.name]=e,installedIntegrations.includes(e.name)||"function"!=typeof e.setupOnce||(e.setupOnce(),installedIntegrations.push(e.name)),e.setup&&"function"==typeof e.setup&&e.setup(t),"function"==typeof e.preprocessEvent){const n=e.preprocessEvent.bind(e);t.on("preprocessEvent",(e,r)=>n(e,r,t))}if("function"==typeof e.processEvent){const n=e.processEvent.bind(e),r=Object.assign((e,r)=>n(e,r,t),{id:e.name});t.addEventProcessor(r)}["processSpan","processSegmentSpan"].forEach(n=>{const r=e[n];"function"==typeof r&&t.on(n,n=>r.call(e,n,t))}),DEBUG_BUILD$2&&debug.log(`Integration installed: ${e.name}`)}}function defineIntegration(t){return t}function isBrowserBundle(){return"undefined"!=typeof __SENTRY_BROWSER_BUNDLE__&&!!__SENTRY_BROWSER_BUNDLE__}function getSDKSource(){return"npm"}function isNodeEnv(){return!isBrowserBundle()&&"[object process]"===Object.prototype.toString.call("undefined"!=typeof process?process:0)}function isBrowser(){return"undefined"!=typeof window&&(!isNodeEnv()||isElectronNodeRenderer())}function isElectronNodeRenderer(){const t=GLOBAL_OBJ.process;return"renderer"===t?.type}function createLogContainerEnvelopeItem(t,e){const n=e?"auto":"never";return[{type:"log",item_count:t.length,content_type:"application/vnd.sentry.items.log+json"},{version:2,...isBrowser()&&{ingest_settings:{infer_ip:n,infer_user_agent:n}},items:t}]}function createLogEnvelope(t,e,n,r,i){const s={};return e?.sdk&&(s.sdk={name:e.sdk.name,version:e.sdk.version}),n&&r&&(s.dsn=dsnToString(r)),createEnvelope(s,[createLogContainerEnvelopeItem(t,i)])}function _INTERNAL_flushLogsBuffer(t,e){const n=e??_INTERNAL_getLogBuffer(t)??[];if(0===n.length)return;const r=t.getOptions(),i=createLogEnvelope(n,r._metadata,r.tunnel,t.getDsn(),t.getDataCollectionOptions().userInfo);_getBufferMap$1().set(t,[]),t.emit("flushLogs"),t.sendEnvelope(i)}function _INTERNAL_getLogBuffer(t){return _getBufferMap$1().get(t)}function _getBufferMap$1(){return getGlobalSingleton("clientToLogBufferMap",()=>/* @__PURE__ */new WeakMap)}function createMetricContainerEnvelopeItem(t,e){const n=e?"auto":"never";return[{type:"trace_metric",item_count:t.length,content_type:"application/vnd.sentry.items.trace-metric+json"},{version:2,...isBrowser()&&{ingest_settings:{infer_ip:n,infer_user_agent:n}},items:t}]}function createMetricEnvelope(t,e,n,r,i){const s={};return e?.sdk&&(s.sdk={name:e.sdk.name,version:e.sdk.version}),n&&r&&(s.dsn=dsnToString(r)),createEnvelope(s,[createMetricContainerEnvelopeItem(t,i)])}function _INTERNAL_flushMetricsBuffer(t,e){const n=e??_INTERNAL_getMetricBuffer(t)??[];if(0===n.length)return;const r=t.getOptions(),i=createMetricEnvelope(n,r._metadata,r.tunnel,t.getDsn(),t.getDataCollectionOptions().userInfo);_getBufferMap().set(t,[]),t.emit("flushMetrics"),t.sendEnvelope(i)}function _INTERNAL_getMetricBuffer(t){return _getBufferMap().get(t)}function _getBufferMap(){return getGlobalSingleton("clientToMetricBufferMap",()=>/* @__PURE__ */new WeakMap)}function spanJsonToSerializedStreamedSpan(t){return streamedSpanJsonToSerializedSpan({trace_id:t.trace_id,span_id:t.span_id,parent_span_id:t.parent_span_id,name:t.description||"",start_timestamp:t.start_timestamp,end_timestamp:t.timestamp||t.start_timestamp,status:t.status&&"ok"!==t.status&&"cancelled"!==t.status?"error":"ok",is_segment:!1,attributes:{...t.data},links:t.links})}function extractGenAiSpansFromEvent(t,e){if("transaction"!==t.type||!t.spans?.length||!t.sdkProcessingMetadata?.hasGenAiSpans||!1===e.getOptions().streamGenAiSpans||hasSpanStreamingEnabled(e))return;const n=[],r=[];for(const e of t.spans)e.op?.startsWith("gen_ai.")?n.push(spanJsonToSerializedStreamedSpan(e)):r.push(e);if(0===n.length)return;t.spans=r;const i=e.getDataCollectionOptions().userInfo?"auto":"never";return[{type:"span",item_count:n.length,content_type:"application/vnd.sentry.items.span.v2+json"},{version:2,...isBrowser()&&{ingest_settings:{infer_ip:i,infer_user_agent:i}},items:n}]}const SENTRY_BUFFER_FULL_ERROR=/* @__PURE__ */Symbol.for("SentryBufferFullError");function makePromiseBuffer(t=100){const e=/* @__PURE__ */new Set;function n(t){e.delete(t)}return{get $(){return Array.from(e)},add:function(r){if(!(e.size<t))return rejectedSyncPromise(SENTRY_BUFFER_FULL_ERROR);const i=r();return e.add(i),i.then(()=>n(i),()=>n(i)),i},drain:function(t){if(!e.size)return resolvedSyncPromise(!0);const n=Promise.allSettled(Array.from(e)).then(()=>!0);if(!t)return n;const r=[n,new Promise(e=>safeUnref(setTimeout(()=>e(!1),t)))];return Promise.race(r)}}}const DEFAULT_RETRY_AFTER=6e4;function parseRetryAfterHeader(t,e=safeDateNow()){const n=parseInt(`${t}`,10);if(!isNaN(n))return 1e3*n;const r=Date.parse(`${t}`);return isNaN(r)?DEFAULT_RETRY_AFTER:r-e}function disabledUntil(t,e){return t[e]||t.all||0}function isRateLimited(t,e,n=safeDateNow()){return disabledUntil(t,e)>n}function updateRateLimits(t,{statusCode:e,headers:n},r=safeDateNow()){const i={...t},s=n?.["x-sentry-rate-limits"],a=n?.["retry-after"];if(s)for(const t of s.trim().split(",")){const[e,n,,,s]=t.split(":",5),a=parseInt(e,10),o=1e3*(isNaN(a)?60:a);if(n)for(const t of n.split(";"))"metric_bucket"===t&&s&&!s.split(";").includes("custom")||(i[t]=r+o);else i.all=r+o}else a?i.all=r+parseRetryAfterHeader(a,r):429===e&&(i.all=r+6e4);return i}const DEFAULT_TRANSPORT_BUFFER_SIZE=64;function createTransport(t,e,n=makePromiseBuffer(t.bufferSize||DEFAULT_TRANSPORT_BUFFER_SIZE)){let r={};return{send:function(i){const s=[];if(forEachEnvelopeItem(i,(e,n)=>{const i=envelopeItemTypeToDataCategory(n);isRateLimited(r,i)?t.recordDroppedEvent("ratelimit_backoff",i):s.push(e)}),0===s.length)return Promise.resolve({});const a=createEnvelope(i[0],s),o=e=>{envelopeContainsItemType(a,["client_report"])?DEBUG_BUILD$2&&debug.warn(`Dropping client report. Will not send outcomes (reason: ${e}).`):forEachEnvelopeItem(a,(n,r)=>{t.recordDroppedEvent(e,envelopeItemTypeToDataCategory(r))})};return n.add(()=>e({body:serializeEnvelope(a)}).then(t=>413===t.statusCode?(DEBUG_BUILD$2&&debug.error("Sentry responded with status code 413. Envelope was discarded due to exceeding size limits."),o("send_error"),t):(DEBUG_BUILD$2&&void 0!==t.statusCode&&(t.statusCode<200||t.statusCode>=300)&&debug.warn(`Sentry responded with status code ${t.statusCode} to sent event.`),r=updateRateLimits(r,t),t),t=>{throw o("network_error"),DEBUG_BUILD$2&&debug.error("Encountered error running transport request:",t),t})).then(t=>t,t=>{if(t===SENTRY_BUFFER_FULL_ERROR)return DEBUG_BUILD$2&&debug.error("Skipped sending event because buffer is full."),o("queue_overflow"),Promise.resolve({});throw t})},flush:t=>n.drain(t)}}function createClientReportEnvelope(t,e,n){return createEnvelope(e?{dsn:e}:{},[[{type:"client_report"},{timestamp:n||dateTimestampInSeconds(),discarded_events:t}]])}function getPossibleEventMessages(t){const e=[];t.message&&e.push(t.message);try{const n=t.exception.values[t.exception.values.length-1];n?.value&&(e.push(n.value),n.type&&e.push(`${n.type}: ${n.value}`))}catch{}return e}function convertTransactionEventToSpanJson(t){const{trace_id:e,parent_span_id:n,span_id:r,status:i,origin:s,data:a,op:o}=t.contexts?.trace??{};return{data:a??{},description:t.transaction,op:o,parent_span_id:n,span_id:r??"",start_timestamp:t.start_timestamp??0,status:i,timestamp:t.timestamp,trace_id:e??"",origin:s,profile_id:a?.[SEMANTIC_ATTRIBUTE_PROFILE_ID],exclusive_time:a?.[SEMANTIC_ATTRIBUTE_EXCLUSIVE_TIME],measurements:t.measurements,is_segment:!0}}function convertSpanJsonToTransactionEvent(t){return{type:"transaction",timestamp:t.timestamp,start_timestamp:t.start_timestamp,transaction:t.description,contexts:{trace:{trace_id:t.trace_id,span_id:t.span_id,parent_span_id:t.parent_span_id,op:t.op,status:t.status,origin:t.origin,data:{...t.data,...t.profile_id&&{[SEMANTIC_ATTRIBUTE_PROFILE_ID]:t.profile_id},...t.exclusive_time&&{[SEMANTIC_ATTRIBUTE_EXCLUSIVE_TIME]:t.exclusive_time}}}},measurements:t.measurements}}const PII_HEADER_SNIPPETS=["forwarded","-ip","remote-","via","-user"];function defaultPiiToCollectionOptions(t){return!0===t?{userInfo:!0,cookies:!0,httpHeaders:{request:!0,response:!0},httpBodies:["incomingRequest","outgoingRequest","incomingResponse","outgoingResponse"],urlQueryParams:!0,graphQL:{document:!0,variables:!0},genAI:{inputs:!0,outputs:!0},databaseQueryData:!0,stackFrameVariables:!0,frameContextLines:7}:{userInfo:!1,cookies:{deny:PII_HEADER_SNIPPETS},httpHeaders:{request:{deny:PII_HEADER_SNIPPETS},response:{deny:PII_HEADER_SNIPPETS}},httpBodies:[],urlQueryParams:{deny:PII_HEADER_SNIPPETS},graphQL:{document:!0,variables:!0},genAI:{inputs:!1,outputs:!1},databaseQueryData:!1,stackFrameVariables:!0,frameContextLines:7}}const DEFAULTS={userInfo:!0,cookies:!0,httpHeaders:{request:!0,response:!0},httpBodies:["incomingRequest","outgoingRequest","incomingResponse","outgoingResponse"],urlQueryParams:!0,graphQL:{document:!0,variables:!0},genAI:{inputs:!0,outputs:!0},databaseQueryData:!0,stackFrameVariables:!0,frameContextLines:5};function resolveDataCollectionOptions(t){const e=null!=t.dataCollection?DEFAULTS:defaultPiiToCollectionOptions(t.sendDefaultPii),n=t.dataCollection??{};return{userInfo:n.userInfo??e.userInfo,cookies:n.cookies??e.cookies,httpHeaders:{request:n.httpHeaders?.request??e.httpHeaders.request,response:n.httpHeaders?.response??e.httpHeaders.response},httpBodies:n.httpBodies??e.httpBodies,urlQueryParams:n.urlQueryParams??n.queryParams??e.urlQueryParams,graphQL:{document:n.graphQL?.document??e.graphQL.document,variables:n.graphQL?.variables??e.graphQL.variables},genAI:{inputs:n.genAI?.inputs??e.genAI.inputs,outputs:n.genAI?.outputs??e.genAI.outputs},databaseQueryData:n.databaseQueryData??e.databaseQueryData,stackFrameVariables:n.stackFrameVariables??e.stackFrameVariables,frameContextLines:n.frameContextLines??e.frameContextLines}}const ALREADY_SEEN_ERROR="Not capturing exception because it's already been captured.",MISSING_RELEASE_FOR_SESSION_ERROR="Discarded session because of missing or non-string release",INTERNAL_ERROR_SYMBOL=/* @__PURE__ */Symbol.for("SentryInternalError"),DO_NOT_SEND_EVENT_SYMBOL=/* @__PURE__ */Symbol.for("SentryDoNotSendEventError"),DEFAULT_FLUSH_INTERVAL=5e3;function _makeInternalError(t){return{message:t,[INTERNAL_ERROR_SYMBOL]:!0}}function _makeDoNotSendEventError(t){return{message:t,[DO_NOT_SEND_EVENT_SYMBOL]:!0}}function _isInternalError(t){return isObjectLike(t)&&INTERNAL_ERROR_SYMBOL in t}function _isDoNotSendEventError(t){return isObjectLike(t)&&DO_NOT_SEND_EVENT_SYMBOL in t}function setupWeightBasedFlushing(t,e,n,r,i){let s,a=0,o=!1;t.on(n,()=>{a=0,clearTimeout(s),o=!1}),t.on(e,e=>{if(a+=r(e),a>=8e5)i(t);else if(!o){const e=t.getOptions()._flushInterval??DEFAULT_FLUSH_INTERVAL;e>0&&(o=!0,s=safeUnref(setTimeout(()=>{i(t)},e)))}}),t.on("flush",()=>{i(t)})}class Client{constructor(t){if(this._options=t,this._integrations={},this._numProcessing=0,this._outcomes={},this._hooks={},this._eventProcessors=[],this._promiseBuffer=makePromiseBuffer(t.transportOptions?.bufferSize??DEFAULT_TRANSPORT_BUFFER_SIZE),this._dataCollection=resolveDataCollectionOptions(t),t.dsn?this._dsn=makeDsn(t.dsn):DEBUG_BUILD$2&&debug.warn("No DSN provided, client will not send events."),this._dsn){const e=getEnvelopeEndpointWithUrlEncodedAuth(this._dsn,t.tunnel,t._metadata?t._metadata.sdk:void 0);this._transport=t.transport({tunnel:this._options.tunnel,recordDroppedEvent:this.recordDroppedEvent.bind(this),...t.transportOptions,url:e})}this._options.enableLogs=this._options.enableLogs??this._options._experiments?.enableLogs,this._options.enableLogs&&setupWeightBasedFlushing(this,"afterCaptureLog","flushLogs",estimateLogSizeInBytes,_INTERNAL_flushLogsBuffer),(this._options.enableMetrics??this._options._experiments?.enableMetrics??1)&&setupWeightBasedFlushing(this,"afterCaptureMetric","flushMetrics",estimateMetricSizeInBytes,_INTERNAL_flushMetricsBuffer)}captureException(t,e,n){const r=uuid4();if(checkOrSetAlreadyCaught(t))return DEBUG_BUILD$2&&debug.log(ALREADY_SEEN_ERROR),r;const i={event_id:r,...e};return this._process(()=>this.eventFromException(t,i).then(t=>this._captureEvent(t,i,n)).then(t=>t),"error"),i.event_id}captureMessage(t,e,n,r){const i={event_id:uuid4(),...n},s=isParameterizedString(t)?t:String(t),a=isPrimitive(t),o=a?this.eventFromMessage(s,e,i):this.eventFromException(t,i);return this._process(()=>o.then(t=>this._captureEvent(t,i,r)),a?"unknown":"error"),i.event_id}captureEvent(t,e,n){const r=uuid4();if(e?.originalException&&checkOrSetAlreadyCaught(e.originalException))return DEBUG_BUILD$2&&debug.log(ALREADY_SEEN_ERROR),r;const i={event_id:r,...e},s=t.sdkProcessingMetadata||{},a=s.capturedSpanScope,o=s.capturedSpanIsolationScope,l=getDataCategoryByType(t.type);return this._process(()=>this._captureEvent(t,i,a||n,o),l),i.event_id}captureSession(t){this.sendSession(t),updateSession(t,{init:!1})}getDsn(){return this._dsn}getOptions(){return this._options}getDataCollectionOptions(){return this._dataCollection}getSdkMetadata(){return this._options._metadata}getTransport(){return this._transport}async flush(t){const e=this._transport;if(this.emit("flush"),!e)return!0;const n=await this._isClientDoneProcessing(t),r=await e.flush(t);return n&&r}async close(t){const e=await this.flush(t);return this.getOptions().enabled=!1,this.emit("close"),e}getEventProcessors(){return this._eventProcessors}addEventProcessor(t){this._eventProcessors.push(t)}init(){(this._isEnabled()||this._options.integrations.some(({name:t})=>t.startsWith("Spotlight")))&&this._setupIntegrations()}getIntegrationByName(t){return this._integrations[t]}getIntegrationNames(){return Object.keys(this._integrations)}addIntegration(t){const e=this._integrations[t.name];!e&&t.beforeSetup&&t.beforeSetup(this),setupIntegration(this,t,this._integrations),e||afterSetupIntegrations(this,[t])}sendEvent(t,e={}){this.emit("beforeSendEvent",t,e);const n=extractGenAiSpansFromEvent(t,this);let r=createEventEnvelope(t,this._dsn,this._options._metadata,this._options.tunnel);for(const t of e.attachments||[])r=addItemToEnvelope(r,createAttachmentEnvelopeItem(t));n&&(r=addItemToEnvelope(r,n)),this.sendEnvelope(r).then(e=>this.emit("afterSendEvent",t,e))}sendSession(t){const{release:e,environment:n=DEFAULT_ENVIRONMENT}=this._options;if("aggregates"in t){const r=t.attrs||{};if(!r.release&&!e)return void(DEBUG_BUILD$2&&debug.warn(MISSING_RELEASE_FOR_SESSION_ERROR));r.release=r.release||e,r.environment=r.environment||n,t.attrs=r}else{if(!t.release&&!e)return void(DEBUG_BUILD$2&&debug.warn(MISSING_RELEASE_FOR_SESSION_ERROR));t.release=t.release||e,t.environment=t.environment||n}this.emit("beforeSendSession",t);const r=createSessionEnvelope(t,this._dsn,this._options._metadata,this._options.tunnel);this.sendEnvelope(r)}recordDroppedEvent(t,e,n=1){if(this._options.sendClientReports){const r=`${t}:${e}`;DEBUG_BUILD$2&&debug.log(`Recording outcome: "${r}"${n>1?` (${n} times)`:""}`),this._outcomes[r]=(this._outcomes[r]||0)+n}}on(t,e){const n=this._hooks[t]=this._hooks[t]||/* @__PURE__ */new Set,r=(...t)=>e(...t);return n.add(r),()=>{n.delete(r)}}emit(t,...e){const n=this._hooks[t];n&&n.forEach(t=>t(...e))}async sendEnvelope(t){if(this.emit("beforeEnvelope",t),this._isEnabled()&&this._transport)try{return await this._transport.send(t)}catch(t){return DEBUG_BUILD$2&&debug.error("Error while sending envelope:",t),{}}return DEBUG_BUILD$2&&debug.error("Transport disabled"),{}}registerCleanup(t){}dispose(){}_setupIntegrations(){const{integrations:t}=this._options;this._integrations=setupIntegrations(this,t),afterSetupIntegrations(this,t)}_updateSessionFromEvent(t,e){let n="fatal"===e.level,r=!1;const i=e.exception?.values;if(i){r=!0,n=!1;for(const t of i)if(!1===t.mechanism?.handled){n=!0;break}}const s="ok"===t.status;(s&&0===t.errors||s&&n)&&(updateSession(t,{...n&&{status:"crashed"},errors:t.errors||Number(r||n)}),this.captureSession(t))}async _isClientDoneProcessing(t){let e=0;for(;!t||e<t;){if(await new Promise(t=>setTimeout(t,1)),!this._numProcessing)return!0;e++}return!1}_isEnabled(){return!1!==this.getOptions().enabled&&void 0!==this._transport}_prepareEvent(t,e,n,r){const i=this.getOptions(),s=this.getIntegrationNames();return!e.integrations&&s.length&&(e.integrations=s),this.emit("preprocessEvent",t,e),t.type||r.setLastEventId(t.event_id||e.event_id),prepareEvent(i,t,e,n,this,r).then(t=>{if(null===t)return t;this.emit("postprocessEvent",t,e),t.contexts={trace:{...t.contexts?.trace,...getTraceContextFromScope(n)},...t.contexts};const r=getDynamicSamplingContextFromScope(this,n);return t.sdkProcessingMetadata={dynamicSamplingContext:r,...t.sdkProcessingMetadata},t})}_captureEvent(t,e={},n=getCurrentScope(),r=getIsolationScope()){return DEBUG_BUILD$2&&isErrorEvent(t)&&debug.log(`Captured error event \`${getPossibleEventMessages(t)[0]||"<unknown>"}\``),this._processEvent(t,e,n,r).then(t=>t.event_id,t=>{DEBUG_BUILD$2&&(_isDoNotSendEventError(t)?debug.log(t.message):_isInternalError(t)?debug.warn(t.message):debug.warn(t))})}_processEvent(t,e,n,r){const i=this.getOptions(),{sampleRate:s}=i,a=isTransactionEvent(t),o=isErrorEvent(t),l=`before send for type \`${t.type||"error"}\``,c=void 0===s?void 0:parseSampleRate(s);if(o&&"number"==typeof c&&safeMathRandom()>c)return this.recordDroppedEvent("sample_rate","error"),rejectedSyncPromise(_makeDoNotSendEventError(`Discarding event because it's not included in the random sample (sampling rate = ${s})`));const d=getDataCategoryByType(t.type);return this._prepareEvent(t,e,n,r).then(t=>{if(null===t)throw this.recordDroppedEvent("event_processor",d),_makeDoNotSendEventError("An event processor returned `null`, will not send event.");return!0===e.data?.__sentry__?t:_validateBeforeSendResult(processBeforeSend(this,i,t,e),l)}).then(i=>{if(null===i)throw this.recordDroppedEvent("before_send",d),a&&this.recordDroppedEvent("before_send","span",1+(t.spans||[]).length),_makeDoNotSendEventError(`${l} returned \`null\`, will not send event.`);const s=n.getSession()||r.getSession();if(o&&s&&this._updateSessionFromEvent(s,i),a){const t=(i.sdkProcessingMetadata?.spanCountBeforeProcessing||0)-(i.spans?i.spans.length:0);t>0&&this.recordDroppedEvent("before_send","span",t)}const c=i.transaction_info;if(a&&c&&i.transaction!==t.transaction){const t="custom";i.transaction_info={...c,source:t}}return this.sendEvent(i,e),i}).then(null,t=>{if(_isDoNotSendEventError(t)||_isInternalError(t))throw t;throw this.captureException(t,{mechanism:{handled:!1,type:"internal"},data:{__sentry__:!0},originalException:t}),_makeInternalError(`Event processing pipeline threw an error, original event will not be sent. Details have been sent as a new event.\nReason: ${t}`)})}_process(t,e){this._numProcessing++,this._promiseBuffer.add(t).then(t=>(this._numProcessing--,t),t=>(this._numProcessing--,t===SENTRY_BUFFER_FULL_ERROR&&this.recordDroppedEvent("queue_overflow",e),t))}_clearOutcomes(){const t=this._outcomes;return this._outcomes={},Object.entries(t).map(([t,e])=>{const[n,r]=t.split(":");return{reason:n,category:r,quantity:e}})}_flushOutcomes(){DEBUG_BUILD$2&&debug.log("Flushing outcomes...");const t=this._clearOutcomes();if(0===t.length)return void(DEBUG_BUILD$2&&debug.log("No outcomes to send"));if(!this._dsn)return void(DEBUG_BUILD$2&&debug.log("No dsn provided, will not send outcomes"));DEBUG_BUILD$2&&debug.log("Sending outcomes:",t);const e=createClientReportEnvelope(t,this._options.tunnel&&dsnToString(this._dsn));this.sendEnvelope(e)}}function getDataCategoryByType(t){return"replay_event"===t?"replay":t||"error"}function _validateBeforeSendResult(t,e){const n=`${e} must return \`null\` or a valid event.`;if(isThenable(t))return t.then(t=>{if(!isPlainObject(t)&&null!==t)throw _makeInternalError(n);return t},t=>{throw _makeInternalError(`${e} rejected with ${t}`)});if(!isPlainObject(t)&&null!==t)throw _makeInternalError(n);return t}function processBeforeSend(t,e,n,r){const{beforeSend:i,beforeSendTransaction:s,ignoreSpans:a}=e,o=!isStreamedBeforeSendSpanCallback(e.beforeSendSpan)&&e.beforeSendSpan;let l=n;if(isErrorEvent(l)&&i)return i(l,r);if(isTransactionEvent(l)){if(o||a){const e=convertTransactionEventToSpanJson(l);if(a?.length&&shouldIgnoreSpan({description:e.description,op:e.op,attributes:e.data},a))return null;if(o){const t=o(e);t?l=merge(n,convertSpanJsonToTransactionEvent(t)):showSpanDropWarning()}if(l.spans){const e=[],n=l.spans;for(const t of n)if(a?.length&&shouldIgnoreSpan({description:t.description,op:t.op,attributes:t.data},a))reparentChildSpans(n,t);else if(o){const n=o(t);n?e.push(n):(showSpanDropWarning(),e.push(t))}else e.push(t);const r=l.spans.length-e.length;r&&t.recordDroppedEvent("before_send","span",r),l.spans=e}}if(s)return l.spans&&(l.sdkProcessingMetadata={...n.sdkProcessingMetadata,spanCountBeforeProcessing:l.spans.length}),s(l,r)}return l}function isErrorEvent(t){return void 0===t.type}function isTransactionEvent(t){return"transaction"===t.type}function estimateMetricSizeInBytes(t){let e=0;return t.name&&(e+=2*t.name.length),e+=8,e+estimateAttributesSizeInBytes(t.attributes)}function estimateLogSizeInBytes(t){let e=0;return t.message&&(e+=2*t.message.length),e+estimateAttributesSizeInBytes(t.attributes)}function estimateAttributesSizeInBytes(t){if(!t)return 0;let e=0;return Object.values(t).forEach(t=>{Array.isArray(t)?e+=t.length*estimatePrimitiveSizeInBytes(t[0]):isPrimitive(t)?e+=estimatePrimitiveSizeInBytes(t):e+=100}),e}function estimatePrimitiveSizeInBytes(t){return"string"==typeof t?2*t.length:"number"==typeof t?8:"boolean"==typeof t?4:0}const DEFAULT_BASE_URL="thismessage:/";function isURLObjectRelative(t){return"isRelative"in t}function parseStringToURLObject(t,e){const n=t.indexOf("://")<=0&&0!==t.indexOf("//"),r=e??(n?DEFAULT_BASE_URL:void 0);try{if("canParse"in URL&&!URL.canParse(t,r))return;const e=new URL(t,r);return n?{isRelative:n,pathname:e.pathname,search:e.search,hash:e.hash}:e}catch{}}function getSanitizedUrlStringFromUrlObject(t){if(isURLObjectRelative(t))return t.pathname;const e=new URL(t);return e.search="",e.hash="",["80","443"].includes(e.port)&&(e.port=""),e.password&&(e.password="%filtered%"),e.username&&(e.username="%filtered%"),e.toString()}function parseUrl(t){if(!t)return{};const e=t.match(/^(([^:/?#]+):)?(\/\/([^/?#]*))?([^?#]*)(\?([^#]*))?(#(.*))?$/);if(!e)return{};const n=e[6]||"",r=e[8]||"";return{host:e[4],path:e[5],protocol:e[2],search:n,hash:r,relative:e[5]+n+r}}function stripUrlQueryAndFragment(t){return t.split(/[?#]/,1)[0]}function stripDataUrlContent(t,e=!0){if(t.startsWith("data:")){const n=t.match(/^data:([^;,]+)/),r=n?n[1]:"text/plain",i=t.includes(";base64,"),s=t.indexOf(",");let a="";if(e&&-1!==s){const e=t.slice(s+1);a=e.length>10?`${e.slice(0,10)}... [truncated]`:e}return`data:${r}${i?",base64":""}${a?`,${a}`:""}`}return t}function addAutoIpAddressToSession(t){"aggregates"in t?void 0===t.attrs?.ip_address&&(t.attrs={...t.attrs,ip_address:"{{auto}}"}):void 0===t.ipAddress&&(t.ipAddress="{{auto}}")}function applySdkMetadata(t,e,n=[e],r="npm"){const i=(t._metadata=t._metadata||{}).sdk=t._metadata.sdk||{};i.name||(i.name=`sentry.javascript.${e}`,i.packages=n.map(t=>({name:`${r}:@sentry/${t}`,version:SDK_VERSION})),i.version=SDK_VERSION)}function getTraceData(t={}){const e=t.client||getClient();if(!isEnabled()||!e)return{};const n=getAsyncContextStrategy(getMainCarrier());if(n.getTraceData)return n.getTraceData(t);const r=t.scope||getCurrentScope(),i=t.span||getActiveSpan(),s=spanIsNonRecordingSpan(i)&&!hasSpansEnabled(e.getOptions());if(!i&&hasExternalPropagationContext())return{};const a=i&&!s?spanToTraceHeader(i):scopeToTraceHeader(r),o=dynamicSamplingContextToSentryBaggageHeader(i?getDynamicSamplingContextFromSpan(i):getDynamicSamplingContextFromScope(e,r));if(!TRACEPARENT_REGEXP.test(a))return debug.warn("Invalid sentry-trace data. Cannot generate trace data"),{};const l={"sentry-trace":a,baggage:o};return t.propagateTraceparent&&(l.traceparent=i&&!s?spanToTraceparentHeader(i):scopeToTraceparentHeader(r)),l}function scopeToTraceHeader(t){const{traceId:e,sampled:n,propagationSpanId:r}=t.getPropagationContext();return generateSentryTraceHeader(e,r,n)}function scopeToTraceparentHeader(t){const{traceId:e,sampled:n,propagationSpanId:r}=t.getPropagationContext();return generateTraceparentHeader(e,r,n)}const DEFAULT_BREADCRUMBS=100;function addBreadcrumb(t,e){const n=getClient(),r=getIsolationScope();if(!n)return;const{beforeBreadcrumb:i=null,maxBreadcrumbs:s=DEFAULT_BREADCRUMBS}=n.getOptions();if(s<=0)return;const a={timestamp:dateTimestampInSeconds(),...t},o=i?consoleSandbox(()=>i(a,e)):a;null!==o&&(n.emit&&n.emit("beforeAddBreadcrumb",o,e),r.addBreadcrumb(o,s))}const INTEGRATION_NAME$8="FunctionToString",SETUP_CLIENTS=/* @__PURE__ */new WeakMap,_functionToStringIntegration=()=>({name:INTEGRATION_NAME$8,setupOnce(){const t=Function.prototype.toString;try{Function.prototype.toString=function(...e){const n=getOriginalFunction(this);let r;try{SETUP_CLIENTS.has(getClient())&&void 0!==n&&(r=n)}catch{}return t.apply(r??this,e)}}catch{}},setup(t){SETUP_CLIENTS.set(t,!0)}}),functionToStringIntegration=defineIntegration(_functionToStringIntegration),DEFAULT_IGNORE_ERRORS=[/^Script error\.?$/,/^Javascript error: Script error\.? on line 0$/,/^ResizeObserver loop completed with undelivered notifications.$/,/^Cannot redefine property: googletag$/,/^Can't find variable: gmo$/,/^undefined is not an object \(evaluating 'a\.[A-Z]'\)$/,/can't redefine non-configurable property "solana"/,/vv\(\)\.getRestrictions is not a function/,/Can't find variable: _AutofillCallbackHandler/,/Object Not Found Matching Id:\d+, MethodName:simulateEvent/,/^Java exception was raised during method invocation$/],INTEGRATION_NAME$7="EventFilters",eventFiltersIntegration=defineIntegration((t={})=>{let e;return{name:INTEGRATION_NAME$7,setup(n){const r=n.getOptions();e=_mergeOptions(t,r)},processEvent(n,r,i){if(!e){const n=i.getOptions();e=_mergeOptions(t,n)}return _shouldDropEvent$1(n,e)?null:n}}}),inboundFiltersIntegration=defineIntegration((t={})=>({...eventFiltersIntegration(t),name:"InboundFilters"}));function _mergeOptions(t={},e={}){return{allowUrls:[...t.allowUrls||[],...e.allowUrls||[]],denyUrls:[...t.denyUrls||[],...e.denyUrls||[]],ignoreErrors:[...t.ignoreErrors||[],...e.ignoreErrors||[],...t.disableErrorDefaults?[]:DEFAULT_IGNORE_ERRORS],ignoreTransactions:[...t.ignoreTransactions||[],...e.ignoreTransactions||[]]}}function _shouldDropEvent$1(t,e){if(t.type){if("transaction"===t.type&&_isIgnoredTransaction(t,e.ignoreTransactions))return DEBUG_BUILD$2&&debug.warn(`Event dropped due to being matched by \`ignoreTransactions\` option.\nEvent: ${getEventDescription(t)}`),!0}else{if(_isIgnoredError(t,e.ignoreErrors))return DEBUG_BUILD$2&&debug.warn(`Event dropped due to being matched by \`ignoreErrors\` option.\nEvent: ${getEventDescription(t)}`),!0;if(_isUselessError(t))return DEBUG_BUILD$2&&debug.warn(`Event dropped due to not having an error message, error type or stacktrace.\nEvent: ${getEventDescription(t)}`),!0;if(_isDeniedUrl(t,e.denyUrls))return DEBUG_BUILD$2&&debug.warn(`Event dropped due to being matched by \`denyUrls\` option.\nEvent: ${getEventDescription(t)}.\nUrl: ${_getEventFilterUrl(t)}`),!0;if(!_isAllowedUrl(t,e.allowUrls))return DEBUG_BUILD$2&&debug.warn(`Event dropped due to not being matched by \`allowUrls\` option.\nEvent: ${getEventDescription(t)}.\nUrl: ${_getEventFilterUrl(t)}`),!0}return!1}function _isIgnoredError(t,e){return!!e?.length&&getPossibleEventMessages(t).some(t=>stringMatchesSomePattern(t,e))}function _isIgnoredTransaction(t,e){if(!e?.length)return!1;const n=t.transaction;return!!n&&stringMatchesSomePattern(n,e)}function _isDeniedUrl(t,e){if(!e?.length)return!1;const n=_getEventFilterUrl(t);return!!n&&stringMatchesSomePattern(n,e)}function _isAllowedUrl(t,e){if(!e?.length)return!0;const n=_getEventFilterUrl(t);return!n||stringMatchesSomePattern(n,e)}function _getLastValidUrl(t=[]){for(let e=t.length-1;e>=0;e--){const n=t[e];if(n&&"<anonymous>"!==n.filename&&"[native code]"!==n.filename)return n.filename||null}return null}function _getEventFilterUrl(t){try{const e=[...t.exception?.values??[]].reverse().find(t=>void 0===t.mechanism?.parent_id&&t.stacktrace?.frames?.length),n=e?.stacktrace?.frames;return n?_getLastValidUrl(n):null}catch{return DEBUG_BUILD$2&&debug.error(`Cannot extract url for event ${getEventDescription(t)}`),null}}function _isUselessError(t){return!!t.exception?.values?.length&&!t.message&&!t.exception.values.some(t=>t.stacktrace||t.type&&"Error"!==t.type||t.value)}function applyAggregateErrorsToEvent(t,e,n,r,i,s){if(!i.exception?.values||!s||!isInstanceOf(s.originalException,Error))return;const a=i.exception.values.length>0?i.exception.values[i.exception.values.length-1]:void 0;a&&(i.exception.values=aggregateExceptionsFromError(t,e,r,s.originalException,n,i.exception.values,a,0))}function aggregateExceptionsFromError(t,e,n,r,i,s,a,o){if(s.length>=n+1)return s;let l=[...s];if(isInstanceOf(r[i],Error)){applyExceptionGroupFieldsForParentException(a,o,r);const s=t(e,r[i]),c=l.length;applyExceptionGroupFieldsForChildException(s,i,c,o),l=aggregateExceptionsFromError(t,e,n,r[i],i,[s,...l],s,c)}return isExceptionGroup(r)&&r.errors.forEach((s,c)=>{if(isInstanceOf(s,Error)){applyExceptionGroupFieldsForParentException(a,o,r);const d=t(e,s),h=l.length;applyExceptionGroupFieldsForChildException(d,`errors[${c}]`,h,o),l=aggregateExceptionsFromError(t,e,n,s,i,[d,...l],d,h)}}),l}function isExceptionGroup(t){return Array.isArray(t.errors)}function applyExceptionGroupFieldsForParentException(t,e,n){t.mechanism={handled:!0,type:"auto.core.linked_errors",...isExceptionGroup(n)&&{is_exception_group:!0},...t.mechanism,exception_id:e}}function applyExceptionGroupFieldsForChildException(t,e,n,r){t.mechanism={handled:!0,...t.mechanism,type:"chained",source:e,exception_id:n,parent_id:r}}function hasSentryFetchUrlHost(t){return isError(t)&&"__sentry_fetch_url_host__"in t&&"string"==typeof t.__sentry_fetch_url_host__}function _enhanceErrorWithSentryInfo(t){return hasSentryFetchUrlHost(t)?`${t.message} (${t.__sentry_fetch_url_host__})`:t.message}const _filter=/* @__PURE__ */new Set([]);function addConsoleInstrumentationHandler(t){const e="console",n=addHandler$1(e,t);return maybeInstrument(e,instrumentConsole),n}const instrumentedLevels=/* @__PURE__ */new Set;function instrumentConsole(){"console"in GLOBAL_OBJ&&CONSOLE_LEVELS.forEach(function(t){!instrumentedLevels.has(t)&&t in GLOBAL_OBJ.console&&(instrumentedLevels.add(t),fill(GLOBAL_OBJ.console,t,function(e){return originalConsoleMethods[t]=e,function(...e){const n=e[0],r=originalConsoleMethods[t],i=_filter.size&&"string"==typeof n&&stringMatchesSomePattern(n,_filter);i||triggerHandlers$1("console",{args:e,level:t}),(!i||DEBUG_BUILD$2&&debug.isEnabled())&&r?.apply(GLOBAL_OBJ.console,e)}}))})}function severityLevelFromString(t){return"warn"===t?"warning":["fatal","error","warning","log","info","debug"].includes(t)?t:"log"}const INTEGRATION_NAME$6="Dedupe",_dedupeIntegration=()=>{let t;return{name:INTEGRATION_NAME$6,processEvent(e){if(e.type)return e;try{if(_shouldDropEvent(e,t))return DEBUG_BUILD$2&&debug.warn("Event dropped due to being a duplicate of previously captured event."),null}catch{}return t=e}}},dedupeIntegration=defineIntegration(_dedupeIntegration);function _shouldDropEvent(t,e){return!(!e||!_isSameMessageEvent(t,e)&&!_isSameExceptionEvent(t,e))}function _isSameMessageEvent(t,e){const n=t.message,r=e.message;return!(!n&&!r||n&&!r||!n&&r||n!==r||!_isSameFingerprint(t,e)||!_isSameStacktrace(t,e))}function _isSameExceptionEvent(t,e){const n=_getExceptionFromEvent(e),r=_getExceptionFromEvent(t);return!!(n&&r&&n.type===r.type&&n.value===r.value&&_isSameFingerprint(t,e)&&_isSameStacktrace(t,e))}function _isSameStacktrace(t,e){let n=getFramesFromEvent(t),r=getFramesFromEvent(e);if(!n&&!r)return!0;if(n&&!r||!n&&r)return!1;if(r.length!==n.length)return!1;for(let t=0;t<r.length;t++){const e=r[t],i=n[t];if(e.filename!==i.filename||e.lineno!==i.lineno||e.colno!==i.colno||e.function!==i.function)return!1}return!0}function _isSameFingerprint(t,e){let n=t.fingerprint,r=e.fingerprint;if(!n&&!r)return!0;if(n&&!r||!n&&r)return!1;try{return!(n.join("")!==r.join(""))}catch{return!1}}function _getExceptionFromEvent(t){return t.exception?.values?.[0]}const INTEGRATION_NAME$5="ConversationId",_conversationIdIntegration=()=>({name:INTEGRATION_NAME$5,setup(t){t.on("spanStart",t=>{const e=getCurrentScope().getScopeData(),n=getIsolationScope().getScopeData(),r=e.conversationId||n.conversationId;if(r){const{op:e,data:n,description:i}=spanToJSON(t);if(!e?.startsWith("gen_ai.")&&!n["ai.operationId"]&&!i?.startsWith("ai."))return;t.setAttribute(GEN_AI_CONVERSATION_ID_ATTRIBUTE,r)}})}}),conversationIdIntegration=defineIntegration(_conversationIdIntegration);function instrumentFetchRequest(t,e,n,r,i){if(!t.fetchData)return;const{method:s,url:a}=t.fetchData,o=hasSpansEnabled()&&e(a);if(t.endTimestamp){const e=t.fetchData.__span;if(!e)return;const n=r[e];return void(n&&(o&&(endSpan(n,t),_callOnRequestSpanEnd(n,t,i)),delete r[e]))}const{spanOrigin:l="auto.http.browser",propagateTraceparent:c=!1}="object"==typeof i?i:{spanOrigin:i},d=getClient(),h=!!getActiveSpan(),u=h||!!d&&hasSpanStreamingEnabled(d),p=o&&u?startInactiveSpan(getSpanStartOptions(a,s,l)):new SentryNonRecordingSpan,f=spanIsIgnored(p)&&h?void 0:p;if(o&&!u&&d?.recordDroppedEvent("no_parent_span","span"),t.fetchData.__span=p.spanContext().spanId,r[p.spanContext().spanId]=p,n(t.fetchData.url)){const e={...t.args[1]||{}},n=_INTERNAL_getTracingHeadersForFetchRequest(t.args[0],e,hasSpansEnabled()&&u?f:void 0,c);n&&(t.args[1]=e,e.headers=n)}return d&&d.emit("beforeOutgoingRequestSpan",p,{input:t.args,response:t.response,startTimestamp:t.startTimestamp,endTimestamp:t.endTimestamp}),p}function _callOnRequestSpanEnd(t,e,n){const r="object"==typeof n&&null!==n?n.onRequestSpanEnd:void 0;r?.(t,{headers:e.response?.headers,error:e.error})}function _INTERNAL_getTracingHeadersForFetchRequest(t,e,n,r){const i=getTraceData({span:n,propagateTraceparent:r}),s=i["sentry-trace"],a=i.baggage,o=i.traceparent;if(!s)return;const l=e.headers||(isRequest(t)?t.headers:void 0);if(l){if(isHeaders(l)){const t=new Headers(l);if(t.get("sentry-trace")||t.set("sentry-trace",s),r&&o&&!t.get("traceparent")&&t.set("traceparent",o),a){const e=t.get("baggage");e?baggageHeaderHasSentryBaggageValues(e)||t.set("baggage",`${e},${a}`):t.set("baggage",a)}return t}if(isHeadersInitTupleArray(l)){const t=[...l];t.find(t=>"sentry-trace"===t[0])||t.push(["sentry-trace",s]),r&&o&&!t.find(t=>"traceparent"===t[0])&&t.push(["traceparent",o]);const e=l.find(t=>"baggage"===t[0]&&"string"==typeof t[1]&&baggageHeaderHasSentryBaggageValues(t[1]));return a&&!e&&t.push(["baggage",a]),t}{const t="sentry-trace"in l?l["sentry-trace"]:void 0,e="traceparent"in l?l.traceparent:void 0,n="baggage"in l?l.baggage:void 0,i=n?Array.isArray(n)?[...n]:[n]:[],c=n&&(Array.isArray(n)?n.find(t=>baggageHeaderHasSentryBaggageValues(t)):baggageHeaderHasSentryBaggageValues(n));a&&!c&&i.push(a);const d=Object.assign({},l,{"sentry-trace":t??s,...i.length>0&&{baggage:i.join(",")}});return r&&o&&!e&&(d.traceparent=o),d}}return{"sentry-trace":s,...a&&{baggage:a},...o&&{traceparent:o}}}function endSpan(t,e){if(e.response){setHttpStatus(t,e.response.status);const n=e.response?.headers?.get("content-length");if(n){const e=parseInt(n);e>0&&t.setAttribute("http.response_content_length",e)}}else e.error&&t.setStatus({code:SPAN_STATUS_ERROR,message:"internal_error"});t.end()}function baggageHeaderHasSentryBaggageValues(t){return"string"==typeof t&&t.split(",").some(t=>t.trim().startsWith(SENTRY_BAGGAGE_KEY_PREFIX))}function isHeaders(t){return"undefined"!=typeof Headers&&isInstanceOf(t,Headers)}function isHeadersInitTupleArray(t){return!!Array.isArray(t)&&t.every(t=>Array.isArray(t)&&2===t.length&&"string"==typeof t[0])}function getSpanStartOptions(t,e,n){if(t.startsWith("data:"))return{name:`${e} ${stripDataUrlContent(t)}`,attributes:getFetchSpanAttributes(t,void 0,e,n)};const r=parseStringToURLObject(t);return{name:`${e} ${r?getSanitizedUrlStringFromUrlObject(r):t}`,attributes:getFetchSpanAttributes(t,r,e,n)}}function getFetchSpanAttributes(t,e,n,r){const i={url:stripDataUrlContent(t),type:"fetch","http.method":n,[SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN]:r,[SEMANTIC_ATTRIBUTE_SENTRY_OP]:"http.client"};return e&&(isURLObjectRelative(e)||(i[ws]=stripDataUrlContent(e.href),i[Yu]=stripDataUrlContent(e.href),i["server.address"]=e.host),e.search&&(i["http.query"]=e.search),e.hash&&(i["http.fragment"]=e.hash)),i}function getBreadcrumbLogLevelFromHttpStatusCode(t){return void 0===t?void 0:t>=400&&t<500?"warning":t>=500?"error":void 0}const WINDOW$3=GLOBAL_OBJ;function supportsHistory(){return"history"in WINDOW$3&&!!WINDOW$3.history}function _isFetchSupported(){if(!("fetch"in WINDOW$3))return!1;try{return new Headers,new Request("data:,"),new Response,!0}catch{return!1}}function isNativeFunction(t){return t&&/^function\s+\w+\(\)\s+\{\s+\[native code\]\s+\}$/.test(t.toString())}function supportsNativeFetch(){if("string"==typeof EdgeRuntime)return!0;if(!_isFetchSupported())return!1;if(isNativeFunction(WINDOW$3.fetch))return!0;let t=!1;const e=WINDOW$3.document;if(e&&"function"==typeof e.createElement)try{const n=e.createElement("iframe");n.hidden=!0,e.head.appendChild(n),n.contentWindow?.fetch&&(t=isNativeFunction(n.contentWindow.fetch)),e.head.removeChild(n)}catch(t){DEBUG_BUILD$2&&debug.warn("Could not create sandbox iframe for pure fetch check, bailing to window.fetch: ",t)}return t}function addFetchInstrumentationHandler(t,e){const n="fetch",r=addHandler$1(n,t);return maybeInstrument(n,()=>instrumentFetch(void 0,e)),r}function addFetchEndInstrumentationHandler(t){const e="fetch-body-resolved",n=addHandler$1(e,t);return maybeInstrument(e,()=>instrumentFetch(streamHandler)),n}function instrumentFetch(t,e=!1){e&&!supportsNativeFetch()||fill(GLOBAL_OBJ,"fetch",function(e){return function(...n){const r=new Error,{method:i,url:s}=parseFetchArgs(n),a={args:n,fetchData:{method:i,url:s},startTimestamp:1e3*timestampInSeconds(),virtualError:r,headers:getHeadersFromFetchArgs(n)};return t||triggerHandlers$1("fetch",{...a}),e.apply(GLOBAL_OBJ,n).then(async e=>(t?t(e):triggerHandlers$1("fetch",{...a,endTimestamp:1e3*timestampInSeconds(),response:e}),e),t=>{triggerHandlers$1("fetch",{...a,endTimestamp:1e3*timestampInSeconds(),error:t}),isError(t)&&void 0===t.stack&&(t.stack=r.stack,addNonEnumerableProperty(t,"framesToPop",1));const e=getClient(),n=e?.getOptions().enhanceFetchErrorMessages??"always";if(!1!==n&&t instanceof TypeError&&("Failed to fetch"===t.message||"Load failed"===t.message||"NetworkError when attempting to fetch resource."===t.message))try{const e=new URL(a.fetchData.url).host;"always"===n?t.message=`${t.message} (${e})`:addNonEnumerableProperty(t,"__sentry_fetch_url_host__",e)}catch{}throw t})}})}async function resolveResponse(t,e){if(t?.body){const n=t.body,r=n.getReader(),i=setTimeout(()=>{n.cancel().then(null,()=>{})},9e4);let s=!0;for(;s;){let t;try{t=setTimeout(()=>{n.cancel().then(null,()=>{})},5e3);const{done:i}=await r.read();clearTimeout(t),i&&(e(),s=!1)}catch{s=!1}finally{clearTimeout(t)}}clearTimeout(i),r.releaseLock(),n.cancel().then(null,()=>{})}}function streamHandler(t){let e;try{e=t.clone()}catch{return}resolveResponse(e,()=>{triggerHandlers$1("fetch-body-resolved",{endTimestamp:1e3*timestampInSeconds(),response:t})})}function hasProp(t,e){return isObjectLike(t)&&!!t[e]}function getUrlFromResource(t){return"string"==typeof t?t:t?hasProp(t,"url")?t.url:t.toString?t.toString():"":""}function parseFetchArgs(t){if(0===t.length)return{method:"GET",url:""};if(2===t.length){const[e,n]=t;return{url:getUrlFromResource(e),method:hasProp(n,"method")?String(n.method).toUpperCase():isRequest(e)&&hasProp(e,"method")?String(e.method).toUpperCase():"GET"}}const e=t[0];return{url:getUrlFromResource(e),method:hasProp(e,"method")?String(e.method).toUpperCase():"GET"}}function getHeadersFromFetchArgs(t){const[e,n]=t;try{if("object"==typeof n&&null!==n&&"headers"in n&&n.headers)return new Headers(n.headers);if(isRequest(e))return new Headers(e.headers)}catch{}}const WINDOW$2=GLOBAL_OBJ;function getLocationHref(){try{return WINDOW$2.document.location.href}catch{return""}}function getComponentName(t,e=5){if(!WINDOW$2.HTMLElement)return null;let n=t;for(let t=0;t<e;t++){if(!n)return null;if(n instanceof HTMLElement){if(n.dataset.sentryComponent)return n.dataset.sentryComponent;if(n.dataset.sentryElement)return n.dataset.sentryElement}n=n.parentNode}return null}const WINDOW$1=GLOBAL_OBJ;let ignoreOnError=0;function shouldIgnoreOnError(){return ignoreOnError>0}function ignoreNextOnError(){ignoreOnError++,setTimeout(()=>{ignoreOnError--})}function wrap(t,e={}){if("function"!=typeof t)return t;try{if(Object.prototype.hasOwnProperty.call(t,"__sentry_wrapped__")){const e=t.__sentry_wrapped__;return"function"==typeof e?e:t}if(getOriginalFunction(t))return t}catch{return t}const n=function(...n){GLOBAL_OBJ._sentryWrappedDepth=(GLOBAL_OBJ._sentryWrappedDepth||0)+1;try{const r=n.map(t=>wrap(t,e));return t.apply(this,r)}catch(t){throw ignoreNextOnError(),withScope(r=>{r.addEventProcessor(t=>(e.mechanism&&(addExceptionTypeValue(t,void 0,void 0),addExceptionMechanism(t,e.mechanism)),t.extra={...t.extra,arguments:n},t)),captureException(t)}),t}finally{GLOBAL_OBJ._sentryWrappedDepth=(GLOBAL_OBJ._sentryWrappedDepth||0)-1}};try{for(const e in t)Object.prototype.hasOwnProperty.call(t,e)&&(n[e]=t[e])}catch{}markFunctionWrapped(n,t),addNonEnumerableProperty(t,"__sentry_wrapped__",n);try{Object.getOwnPropertyDescriptor(n,"name").configurable&&Object.defineProperty(n,"name",{get:()=>t.name})}catch{}return n}function getHttpRequestData(){const t=getLocationHref(),{referrer:e}=WINDOW$1.document||{},{userAgent:n}=WINDOW$1.navigator||{};return{url:t,headers:{...e&&{Referer:e},...n&&{"User-Agent":n}}}}function exceptionFromError(t,e){const n=parseStackFrames(t,e),r={type:extractType(e),value:extractMessage(e)};return n.length&&(r.stacktrace={frames:n}),void 0===r.type&&""===r.value&&(r.value="Unrecoverable error caught"),r}function eventFromPlainObject(t,e,n,r){const i=getClient(),s=i?.getOptions().normalizeDepth,a=getErrorPropertyFromObject(e),o={__serialized__:normalizeToSize(e,s)};if(a)return{exception:{values:[exceptionFromError(t,a)]},extra:o};const l={exception:{values:[{type:isEvent(e)?e.constructor.name:r?"UnhandledRejection":"Error",value:getNonErrorObjectExceptionValue(e,{isUnhandledRejection:r})}]},extra:o};if(n){const e=parseStackFrames(t,n);e.length&&(l.exception.values[0].stacktrace={frames:e})}return l}function eventFromError(t,e){return{exception:{values:[exceptionFromError(t,e)]}}}function parseStackFrames(t,e){const n=e.stacktrace||e.stack||"",r=getSkipFirstStackStringLines(e),i=getPopFirstTopFrames(e);try{return t(n,r,i)}catch{}return[]}const reactMinifiedRegexp=/Minified React error #\d+;/i;function getSkipFirstStackStringLines(t){return t&&reactMinifiedRegexp.test(t.message)?1:0}function getPopFirstTopFrames(t){return"number"==typeof t.framesToPop?t.framesToPop:0}function isWebAssemblyException(t){return"undefined"!=typeof WebAssembly&&void 0!==WebAssembly.Exception&&t instanceof WebAssembly.Exception}function extractType(t){const e=t?.name;return!e&&isWebAssemblyException(t)?t.message&&Array.isArray(t.message)&&2==t.message.length?t.message[0]:"WebAssembly.Exception":e}function extractMessage(t){const e=t?.message;return isWebAssemblyException(t)?Array.isArray(t.message)&&2==t.message.length?t.message[1]:"wasm exception":e?_enhanceErrorWithSentryInfo(e.error&&"string"==typeof e.error.message?e.error:t):"No error message"}function eventFromException(t,e,n,r){const i=eventFromUnknownInput(t,e,n?.syntheticException||void 0,r);return addExceptionMechanism(i),i.level="error",n?.event_id&&(i.event_id=n.event_id),resolvedSyncPromise(i)}function eventFromMessage(t,e,n="info",r,i){const s=eventFromString(t,e,r?.syntheticException||void 0,i);return s.level=n,r?.event_id&&(s.event_id=r.event_id),resolvedSyncPromise(s)}function eventFromUnknownInput(t,e,n,r,i){let s;if(isErrorEvent$1(e)&&e.error)return eventFromError(t,e.error);if(isDOMError(e)||isDOMException(e)){const i=e;if("stack"in e){s=eventFromError(t,e);const i=s.exception?.values?.[0];if(r&&n&&i&&!i.stacktrace){const e=parseStackFrames(t,n);e.length&&(i.stacktrace={frames:e},addExceptionMechanism(s,{synthetic:!0}))}}else{const e=i.name||(isDOMError(i)?"DOMError":"DOMException"),a=i.message?`${e}: ${i.message}`:e;s=eventFromString(t,a,n,r),addExceptionTypeValue(s,a)}return"code"in i&&(s.tags={...s.tags,"DOMException.code":`${i.code}`}),s}return isError(e)?eventFromError(t,e):isPlainObject(e)||isEvent(e)?(s=eventFromPlainObject(t,e,n,i),addExceptionMechanism(s,{synthetic:!0}),s):(s=eventFromString(t,e,n,r),addExceptionTypeValue(s,`${e}`,void 0),addExceptionMechanism(s,{synthetic:!0}),s)}function eventFromString(t,e,n,r){const i={};if(r&&n){const r=parseStackFrames(t,n);r.length&&(i.exception={values:[{value:e,stacktrace:{frames:r}}]}),addExceptionMechanism(i,{synthetic:!0})}if(isParameterizedString(e)){const{__sentry_template_string__:t,__sentry_template_values__:n}=e;return i.logentry={message:t,params:n},i}return i.message=e,i}function getNonErrorObjectExceptionValue(t,{isUnhandledRejection:e}){const n=extractExceptionKeysForMessage(t),r=e?"promise rejection":"exception";return isErrorEvent$1(t)?`Event \`ErrorEvent\` captured as ${r} with message \`${t.message}\``:isEvent(t)?`Event \`${getObjectClassName(t)}\` (type=${t.type}) captured as ${r}`:`Object captured as ${r} with keys: ${n}`}function getObjectClassName(t){try{const e=Object.getPrototypeOf(t);return e?e.constructor.name:void 0}catch{}}function getErrorPropertyFromObject(t){return Object.values(t).find(t=>t instanceof Error)}class BrowserClient extends Client{constructor(t){const e=applyDefaultOptions(t);applySdkMetadata(e,"browser",["browser"],WINDOW$1.SENTRY_SDK_SOURCE||getSDKSource()),super(e);const{userInfo:n}=this.getDataCollectionOptions();e._metadata?.sdk&&(e._metadata.sdk.settings={infer_ip:n?"auto":"never",...e._metadata.sdk.settings});const{sendClientReports:r}=this._options;WINDOW$1.document&&WINDOW$1.document.addEventListener("visibilitychange",()=>{"hidden"===WINDOW$1.document.visibilityState&&(r&&this._flushOutcomes(),queueMicrotask(()=>{this.flush()}))}),n&&this.on("beforeSendSession",addAutoIpAddressToSession)}eventFromException(t,e){return eventFromException(this._options.stackParser,t,e,this._options.attachStacktrace)}eventFromMessage(t,e="info",n){return eventFromMessage(this._options.stackParser,t,e,n,this._options.attachStacktrace)}_prepareEvent(t,e,n,r){return t.platform=t.platform||"javascript",super._prepareEvent(t,e,n,r)}}function applyDefaultOptions(t){return{release:"string"==typeof __SENTRY_RELEASE__?__SENTRY_RELEASE__:WINDOW$1.SENTRY_RELEASE?.id,sendClientReports:!0,parentSpanIsAlwaysRootSpan:!0,...t}}const DEBUG_BUILD$1="undefined"==typeof __SENTRY_DEBUG__||__SENTRY_DEBUG__,WINDOW=GLOBAL_OBJ,getRating=(t,e)=>t>e[1]?"poor":t>e[0]?"needs-improvement":"good",bindReporter=(t,e,n,r)=>{let i,s;return a=>{e.value>=0&&(a||r)&&(s=e.value-(i??0),(s||void 0===i)&&(i=e.value,e.delta=s,e.rating=getRating(e.value,n),t(e)))}},getNavigationEntry=(t=!0)=>{const e=WINDOW.performance?.getEntriesByType?.("navigation")[0];if(!t||e&&e.responseStart>0&&e.responseStart<performance.now())return e},getActivationStart=()=>{const t=getNavigationEntry();return t?.activationStart??0};function addPageListener(t,e,n){WINDOW.document&&WINDOW.addEventListener(t,e,n)}function removePageListener(t,e,n){WINDOW.document&&WINDOW.removeEventListener(t,e,n)}let firstHiddenTime=-1;const onHiddenFunctions=/* @__PURE__ */new Set,initHiddenTime=()=>"hidden"!==WINDOW.document?.visibilityState||WINDOW.document?.prerendering?Infinity:0,onVisibilityUpdate=t=>{if(isPageHidden(t)&&firstHiddenTime>-1){if("visibilitychange"===t.type||"pagehide"===t.type)for(const t of onHiddenFunctions)t();isFinite(firstHiddenTime)||(firstHiddenTime="visibilitychange"===t.type?t.timeStamp:0,removePageListener("prerenderingchange",onVisibilityUpdate,!0))}},getVisibilityWatcher=()=>{if(WINDOW.document&&firstHiddenTime<0){const t=getActivationStart(),e=WINDOW.document.prerendering?void 0:globalThis.performance.getEntriesByType("visibility-state").filter(e=>"hidden"===e.name&&e.startTime>t)[0]?.startTime;firstHiddenTime=e??initHiddenTime(),addPageListener("visibilitychange",onVisibilityUpdate,!0),addPageListener("pagehide",onVisibilityUpdate,!0),addPageListener("prerenderingchange",onVisibilityUpdate,!0)}return{get firstHiddenTime(){return firstHiddenTime},onHidden(t){onHiddenFunctions.add(t)}}};function isPageHidden(t){return"pagehide"===t.type||"hidden"===WINDOW.document?.visibilityState}const generateUniqueID=()=>`v5-${Date.now()}-${Math.floor(8999999999999*Math.random())+1e12}`,initMetric=(t,e=-1)=>{const n=getNavigationEntry();let r="navigate";return n&&(WINDOW.document?.prerendering||getActivationStart()>0?r="prerender":WINDOW.document?.wasDiscarded?r="restore":n.type&&(r=n.type.replace(/_/g,"-"))),{name:t,value:e,rating:"good",delta:0,entries:[],id:generateUniqueID(),navigationType:r}},instanceMap=/* @__PURE__ */new WeakMap;function initUnique(t,e){try{return instanceMap.get(t)||instanceMap.set(t,new e),instanceMap.get(t)}catch(t){return new e}}class LayoutShiftManager{constructor(){this._sessionValue=0,this._sessionEntries=[]}_processEntry(t){if(t.hadRecentInput)return;const e=this._sessionEntries[0],n=this._sessionEntries[this._sessionEntries.length-1];this._sessionValue&&e&&n&&t.startTime-n.startTime<1e3&&t.startTime-e.startTime<5e3?(this._sessionValue+=t.value,this._sessionEntries.push(t)):(this._sessionValue=t.value,this._sessionEntries=[t]),this._onAfterProcessingUnexpectedShift?.(t)}}const observe=(t,e,n={})=>{try{if(PerformanceObserver.supportedEntryTypes.includes(t)){const r=new PerformanceObserver(t=>{Promise.resolve().then(()=>{e(t.getEntries())})});return r.observe({type:t,buffered:!0,...n}),r}}catch{}},runOnce=t=>{let e=!1;return()=>{e||(t(),e=!0)}},whenActivated=t=>{WINDOW.document?.prerendering?addEventListener("prerenderingchange",()=>t(),!0):t()},FCPThresholds=[1800,3e3],onFCP=(t,e={})=>{whenActivated(()=>{const n=getVisibilityWatcher(),r=initMetric("FCP");let i;const s=observe("paint",t=>{for(const e of t)"first-contentful-paint"===e.name&&(s.disconnect(),e.startTime<n.firstHiddenTime&&(r.value=Math.max(e.startTime-getActivationStart(),0),r.entries.push(e),i(!0)))});s&&(i=bindReporter(t,r,FCPThresholds,e.reportAllChanges))})},CLSThresholds=[.1,.25],onCLS=(t,e={})=>{onFCP(runOnce(()=>{const n=initMetric("CLS",0);let r;const i=getVisibilityWatcher(),s=initUnique(e,LayoutShiftManager),a=t=>{for(const e of t)s._processEntry(e);s._sessionValue>n.value&&(n.value=s._sessionValue,n.entries=s._sessionEntries,r())},o=observe("layout-shift",a);o&&(r=bindReporter(t,n,CLSThresholds,e.reportAllChanges),i.onHidden(()=>{a(o.takeRecords()),r(!0)}),WINDOW?.setTimeout?.(r))}))};let interactionCountEstimate=0,minKnownInteractionId=Infinity,maxKnownInteractionId=0;const updateEstimate=t=>{t.forEach(t=>{t.interactionId&&(minKnownInteractionId=Math.min(minKnownInteractionId,t.interactionId),maxKnownInteractionId=Math.max(maxKnownInteractionId,t.interactionId),interactionCountEstimate=maxKnownInteractionId?(maxKnownInteractionId-minKnownInteractionId)/7+1:0)})};let po;const getInteractionCount=()=>po?interactionCountEstimate:performance.interactionCount||0,initInteractionCountPolyfill=()=>{"interactionCount"in performance||po||(po=observe("event",updateEstimate,{type:"event",buffered:!0,durationThreshold:0}))},MAX_INTERACTIONS_TO_CONSIDER=10;let prevInteractionCount=0;const getInteractionCountForNavigation=()=>getInteractionCount()-prevInteractionCount;class InteractionManager{constructor(){this._longestInteractionList=[],this._longestInteractionMap=/* @__PURE__ */new Map}_resetInteractions(){prevInteractionCount=getInteractionCount(),this._longestInteractionList.length=0,this._longestInteractionMap.clear()}_estimateP98LongestInteraction(){const t=Math.min(this._longestInteractionList.length-1,Math.floor(getInteractionCountForNavigation()/50));return this._longestInteractionList[t]}_processEntry(t){if(this._onBeforeProcessingEntry?.(t),!t.interactionId&&"first-input"!==t.entryType)return;const e=this._longestInteractionList.at(-1);let n=this._longestInteractionMap.get(t.interactionId);if(n||this._longestInteractionList.length<MAX_INTERACTIONS_TO_CONSIDER||t.duration>e._latency){if(n?t.duration>n._latency?(n.entries=[t],n._latency=t.duration):t.duration===n._latency&&t.startTime===n.entries[0].startTime&&n.entries.push(t):(n={id:t.interactionId,entries:[t],_latency:t.duration},this._longestInteractionMap.set(n.id,n),this._longestInteractionList.push(n)),this._longestInteractionList.sort((t,e)=>e._latency-t._latency),this._longestInteractionList.length>MAX_INTERACTIONS_TO_CONSIDER){const t=this._longestInteractionList.splice(MAX_INTERACTIONS_TO_CONSIDER);for(const e of t)this._longestInteractionMap.delete(e.id)}this._onAfterProcessingINPCandidate?.(n)}}}const whenIdleOrHidden=t=>{const e=WINDOW.requestIdleCallback||WINDOW.setTimeout;"hidden"===WINDOW.document?.visibilityState?t():(addPageListener("visibilitychange",t=runOnce(t),{once:!0,capture:!0}),addPageListener("pagehide",t,{once:!0,capture:!0}),e(()=>{t(),removePageListener("visibilitychange",t,{capture:!0}),removePageListener("pagehide",t,{capture:!0})}))},INPThresholds=[200,500],DEFAULT_DURATION_THRESHOLD=40,onINP=(t,e={})=>{if(!globalThis.PerformanceEventTiming||!("interactionId"in PerformanceEventTiming.prototype))return;const n=getVisibilityWatcher();whenActivated(()=>{initInteractionCountPolyfill();const r=initMetric("INP");let i;const s=initUnique(e,InteractionManager),a=t=>{whenIdleOrHidden(()=>{for(const e of t)s._processEntry(e);const e=s._estimateP98LongestInteraction();e&&e._latency!==r.value&&(r.value=e._latency,r.entries=e.entries,i())})},o=observe("event",a,{durationThreshold:e.durationThreshold??DEFAULT_DURATION_THRESHOLD});i=bindReporter(t,r,INPThresholds,e.reportAllChanges),o&&(o.observe({type:"first-input",buffered:!0}),n.onHidden(()=>{a(o.takeRecords()),i(!0)}))})};class LCPEntryManager{_processEntry(t){this._onBeforeProcessingEntry?.(t)}}const LCPThresholds=[2500,4e3],onLCP=(t,e={})=>{whenActivated(()=>{const n=getVisibilityWatcher(),r=initMetric("LCP");let i;const s=initUnique(e,LCPEntryManager),a=t=>{e.reportAllChanges||(t=t.slice(-1));for(const e of t)s._processEntry(e),e.startTime<n.firstHiddenTime&&(r.value=Math.max(e.startTime-getActivationStart(),0),r.entries=[e],i())},o=observe("largest-contentful-paint",a);if(o){i=bindReporter(t,r,LCPThresholds,e.reportAllChanges);const n=runOnce(()=>{a(o.takeRecords()),o.disconnect(),i(!0)}),s=t=>{t.isTrusted&&(whenIdleOrHidden(n),removePageListener(t.type,s,{capture:!0}))};for(const t of["keydown","click","visibilitychange"])addPageListener(t,s,{capture:!0})}})},TTFBThresholds=[800,1800],whenReady=t=>{WINDOW.document?.prerendering?whenActivated(()=>whenReady(t)):"complete"!==WINDOW.document?.readyState?addEventListener("load",()=>whenReady(t),!0):setTimeout(t)},onTTFB=(t,e={})=>{const n=initMetric("TTFB"),r=bindReporter(t,n,TTFBThresholds,e.reportAllChanges);whenReady(()=>{const t=getNavigationEntry();t&&(n.value=Math.max(t.responseStart-getActivationStart(),0),n.entries=[t],r(!0))})},handlers={},instrumented={};let _previousCls,_previousLcp,_previousTtfb,_previousInp;function addClsInstrumentationHandler(t,e=!1){return addMetricObserver("cls",t,instrumentCls,_previousCls,e)}function addLcpInstrumentationHandler(t,e=!1){return addMetricObserver("lcp",t,instrumentLcp,_previousLcp,e)}function addTtfbInstrumentationHandler(t){return addMetricObserver("ttfb",t,instrumentTtfb,_previousTtfb)}function addInpInstrumentationHandler(t){return addMetricObserver("inp",t,instrumentInp,_previousInp)}function addPerformanceInstrumentationHandler(t,e){return addHandler(t,e),instrumented[t]||(instrumentPerformanceObserver(t),instrumented[t]=!0),getCleanupCallback(t,e)}function triggerHandlers(t,e){const n=handlers[t];if(n?.length)for(const r of n)try{r(e)}catch(e){DEBUG_BUILD$1&&debug.error(`Error while triggering instrumentation handler.\nType: ${t}\nName: ${getFunctionName(r)}\nError:`,e)}}function instrumentCls(){return onCLS(t=>{triggerHandlers("cls",{metric:t}),_previousCls=t},{reportAllChanges:!0})}function instrumentLcp(){return onLCP(t=>{triggerHandlers("lcp",{metric:t}),_previousLcp=t},{reportAllChanges:!0})}function instrumentTtfb(){return onTTFB(t=>{triggerHandlers("ttfb",{metric:t}),_previousTtfb=t})}function instrumentInp(){return onINP(t=>{triggerHandlers("inp",{metric:t}),_previousInp=t})}function addMetricObserver(t,e,n,r,i=!1){let s;return addHandler(t,e),instrumented[t]||(s=n(),instrumented[t]=!0),r&&e({metric:r}),getCleanupCallback(t,e,i?s:void 0)}function instrumentPerformanceObserver(t){const e={};"event"===t&&(e.durationThreshold=0),observe(t,e=>{triggerHandlers(t,{entries:e})},e)}function addHandler(t,e){handlers[t]=handlers[t]||[],handlers[t].push(e)}function getCleanupCallback(t,e,n){return()=>{n&&n();const r=handlers[t];if(!r)return;const i=r.indexOf(e);-1!==i&&r.splice(i,1)}}function isPerformanceEventTiming(t){return"duration"in t}const DEFAULT_MAX_STRING_LENGTH=80,accessors={};try{"undefined"!=typeof Node&&(accessors.parentNode=Object.getOwnPropertyDescriptor(Node.prototype,"parentNode").get),"undefined"!=typeof Element&&(accessors.tagName=Object.getOwnPropertyDescriptor(Element.prototype,"tagName").get,accessors.id=Object.getOwnPropertyDescriptor(Element.prototype,"id").get,accessors.className=Object.getOwnPropertyDescriptor(Element.prototype,"className").get,accessors.getAttribute=Element.prototype.getAttribute),"undefined"!=typeof HTMLElement&&(accessors.dataset=Object.getOwnPropertyDescriptor(HTMLElement.prototype,"dataset").get)}catch{}function _safeRead(t,e,n){const r=accessors[e];if(r)try{return r.call(t,n)}catch{}const i=t[e];return"function"==typeof i?i.call(t,n):i}function htmlTreeAsString(t,e={}){if(!t)return"<unknown>";try{let n=t;const r=5,i=[];let s=0,a=0;const o=" > ",l=o.length;let c;const d=Array.isArray(e)?e:e.keyAttrs,h=!Array.isArray(e)&&e.maxStringLength||DEFAULT_MAX_STRING_LENGTH;for(;n&&s++<r&&(c=_htmlElementAsString(n,d),!("html"===c||s>1&&a+i.length*l+c.length>=h));)i.push(c),a+=c.length,n=_safeRead(n,"parentNode");return i.reverse().join(o)}catch{return"<unknown>"}}function _htmlElementAsString(t,e){const n=[],r=_safeRead(t,"tagName");if(!r)return"";if("undefined"!=typeof HTMLElement&&t instanceof HTMLElement){const e=_safeRead(t,"dataset");if(e){if(e.sentryComponent)return e.sentryComponent;if(e.sentryElement)return e.sentryElement}}n.push(r.toLowerCase());const i=e?.length?e.filter(e=>_safeRead(t,"getAttribute",e)).map(e=>[e,_safeRead(t,"getAttribute",e)]):null;if(i?.length)i.forEach(t=>{n.push(`[${t[0]}="${t[1]}"]`)});else{const e=_safeRead(t,"id");e&&n.push(`#${e}`);const r=_safeRead(t,"className");if(r&&isString(r)){const t=r.split(/\s+/);for(const e of t)n.push(`.${e}`)}}for(const e of["aria-label","type","name","title","alt"]){const r=_safeRead(t,"getAttribute",e);r&&n.push(`[${e}="${r}"]`)}return n.join("")}const onHidden=t=>{const e=e=>{"pagehide"!==e.type&&"hidden"!==WINDOW.document?.visibilityState||t(e)};addPageListener("visibilitychange",e,{capture:!0,once:!0}),addPageListener("pagehide",e,{capture:!0,once:!0})};function isMeasurementValue(t){return"number"==typeof t&&isFinite(t)}function startAndEndSpan(t,e,n,{...r}){const i=spanToJSON(t).start_timestamp;return i&&i>e&&"function"==typeof t.updateStartTime&&t.updateStartTime(e),withActiveSpan(t,()=>{const t=startInactiveSpan({startTime:e,...r});return t&&t.end(n),t})}function startStandaloneWebVitalSpan(t){const e=getClient();if(!e)return;const{name:n,transaction:r,attributes:i,startTime:s}=t,{release:a,environment:o}=e.getOptions(),{userInfo:l}=e.getDataCollectionOptions(),c=e.getIntegrationByName("Replay"),d=c?.getReplayId(),h=getCurrentScope(),u=h.getUser(),p=void 0!==u?u.email||u.id||u.ip_address:void 0;let f;try{f=h.getScopeData().contexts.profile.profile_id}catch{}return startInactiveSpan({name:n,attributes:{release:a,environment:o,user:p||void 0,profile_id:f||void 0,replay_id:d||void 0,transaction:r,"user_agent.original":WINDOW.navigator?.userAgent,"client.address":l?"{{auto}}":void 0,...i},startTime:s,experimental:{standalone:!0}})}function getBrowserPerformanceAPI(){return WINDOW.addEventListener&&WINDOW.performance}function msToSec(t){return t/1e3}function extractNetworkProtocol(t){let e="unknown",n="unknown",r="";for(const i of t){if("/"===i){[e,n]=t.split("/");break}if(!isNaN(Number(i))){e="h"===r?"http":r,n=t.split(r)[1];break}r+=i}return r===t&&(e=r),{name:e,version:n}}function supportsWebVital(t){try{return PerformanceObserver.supportedEntryTypes.includes(t)}catch{return!1}}function listenForWebVitalReportEvents(t,e){let n,r=!1;function i(t){!r&&n&&e(t,n.spanContext().spanId,n),r=!0}onHidden(()=>{i("pagehide")});const s=t.on("beforeStartNavigationSpan",(t,e)=>{e?.isRedirect||(i("navigation"),s(),a())}),a=t.on("afterStartPageLoadSpan",t=>{n=t,a()})}function trackClsAsStandaloneSpan(t){let e,n=0;if(!supportsWebVital("layout-shift"))return;const r=addClsInstrumentationHandler(({metric:t})=>{const r=t.entries[t.entries.length-1];r&&(n=t.value,e=r)},!0);listenForWebVitalReportEvents(t,(t,i)=>{_sendStandaloneClsSpan(n,e,i,t),r()})}function _sendStandaloneClsSpan(t,e,n,r){DEBUG_BUILD$1&&debug.log(`Sending CLS span (${t})`);const i=e?msToSec((browserPerformanceTimeOrigin()||0)+e.startTime):timestampInSeconds(),s=getCurrentScope().getScopeData().transactionName,a=e?htmlTreeAsString(e.sources[0]?.node):"Layout shift",o={[SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN]:"auto.http.browser.cls",[SEMANTIC_ATTRIBUTE_SENTRY_OP]:"ui.webvital.cls",[SEMANTIC_ATTRIBUTE_EXCLUSIVE_TIME]:0,"sentry.pageload.span_id":n,"sentry.report_event":r};e?.sources&&e.sources.forEach((t,e)=>{o[`cls.source.${e+1}`]=htmlTreeAsString(t.node)});const l=startStandaloneWebVitalSpan({name:a,transaction:s,attributes:o,startTime:i});l&&(l.addEvent("cls",{[SEMANTIC_ATTRIBUTE_SENTRY_MEASUREMENT_UNIT]:"",[SEMANTIC_ATTRIBUTE_SENTRY_MEASUREMENT_VALUE]:t}),l.end(i))}const MAX_PLAUSIBLE_LCP_DURATION=6e4;function isValidLcpMetric(t){return null!=t&&t>0&&t<=MAX_PLAUSIBLE_LCP_DURATION}function trackLcpAsStandaloneSpan(t){let e,n=0;if(!supportsWebVital("largest-contentful-paint"))return;const r=addLcpInstrumentationHandler(({metric:t})=>{const r=t.entries[t.entries.length-1];r&&isValidLcpMetric(t.value)&&(n=t.value,e=r)},!0);listenForWebVitalReportEvents(t,(t,i)=>{_sendStandaloneLcpSpan(n,e,i,t),r()})}function _sendStandaloneLcpSpan(t,e,n,r){if(!isValidLcpMetric(t))return;DEBUG_BUILD$1&&debug.log(`Sending LCP span (${t})`);const i=msToSec((browserPerformanceTimeOrigin()||0)+(e?.startTime||0)),s=getCurrentScope().getScopeData().transactionName,a=e?htmlTreeAsString(e.element):"Largest contentful paint",o={[SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN]:"auto.http.browser.lcp",[SEMANTIC_ATTRIBUTE_SENTRY_OP]:"ui.webvital.lcp",[SEMANTIC_ATTRIBUTE_EXCLUSIVE_TIME]:0,"sentry.pageload.span_id":n,"sentry.report_event":r};e&&(e.element&&(o["lcp.element"]=htmlTreeAsString(e.element)),e.id&&(o["lcp.id"]=e.id),e.url&&(o["lcp.url"]=e.url),null!=e.loadTime&&(o["lcp.loadTime"]=e.loadTime),null!=e.renderTime&&(o["lcp.renderTime"]=e.renderTime),null!=e.size&&(o["lcp.size"]=e.size));const l=startStandaloneWebVitalSpan({name:a,transaction:s,attributes:o,startTime:i});l&&(l.addEvent("lcp",{[SEMANTIC_ATTRIBUTE_SENTRY_MEASUREMENT_UNIT]:"millisecond",[SEMANTIC_ATTRIBUTE_SENTRY_MEASUREMENT_VALUE]:t}),l.end(i))}function getAbsoluteTime(t){return t?((browserPerformanceTimeOrigin()||performance.timeOrigin)+t)/1e3:t}function resourceTimingToSpanAttributes(t){const e={};if(null!=t.nextHopProtocol){const{name:n,version:r}=extractNetworkProtocol(t.nextHopProtocol);e["network.protocol.version"]=r,e["network.protocol.name"]=n}return browserPerformanceTimeOrigin()||getBrowserPerformanceAPI()?.timeOrigin?dropUndefinedKeysFromObject({...e,"http.request.redirect_start":getAbsoluteTime(t.redirectStart),"http.request.redirect_end":getAbsoluteTime(t.redirectEnd),"http.request.worker_start":getAbsoluteTime(t.workerStart),"http.request.fetch_start":getAbsoluteTime(t.fetchStart),"http.request.domain_lookup_start":getAbsoluteTime(t.domainLookupStart),"http.request.domain_lookup_end":getAbsoluteTime(t.domainLookupEnd),"http.request.connect_start":getAbsoluteTime(t.connectStart),"http.request.secure_connection_start":getAbsoluteTime(t.secureConnectionStart),"http.request.connection_end":getAbsoluteTime(t.connectEnd),"http.request.request_start":getAbsoluteTime(t.requestStart),"http.request.response_start":getAbsoluteTime(t.responseStart),"http.request.response_end":getAbsoluteTime(t.responseEnd),"http.request.time_to_first_byte":null!=t.responseStart?t.responseStart/1e3:void 0}):e}function dropUndefinedKeysFromObject(t){return Object.fromEntries(Object.entries(t).filter(([,t])=>null!=t))}const MAX_INT_AS_BYTES=2147483647;let _performanceCursor=0,_measurements={},_lcpEntry,_clsEntry;function startTrackingWebVitals({recordClsStandaloneSpans:t,recordLcpStandaloneSpans:e,client:n}){const r=getBrowserPerformanceAPI();if(r&&browserPerformanceTimeOrigin()){r.mark&&WINDOW.performance.mark("sentry-tracing-init");const i=e?trackLcpAsStandaloneSpan(n):!1===e?_trackLCP():void 0,s=t?trackClsAsStandaloneSpan(n):!1===t?_trackCLS():void 0,a=_trackTtfb(),o=_trackFpFcp();return()=>{a(),o(),i?.(),s?.()}}return()=>{}}function startTrackingLongTasks(){addPerformanceInstrumentationHandler("longtask",({entries:t})=>{const e=getActiveSpan();if(!e)return;const{op:n,start_timestamp:r}=spanToJSON(e);for(const i of t){const t=msToSec(browserPerformanceTimeOrigin()+i.startTime),s=msToSec(i.duration);"navigation"===n&&r&&t<r||startAndEndSpan(e,t,t+s,{name:"Main UI thread blocked",op:"ui.long-task",attributes:{[SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN]:"auto.ui.browser.metrics"}})}})}function startTrackingLongAnimationFrames(){new PerformanceObserver(t=>{const e=getActiveSpan();if(e)for(const n of t.getEntries()){if(!n.scripts[0])continue;const t=msToSec(browserPerformanceTimeOrigin()+n.startTime),{start_timestamp:r,op:i}=spanToJSON(e);if("navigation"===i&&r&&t<r)continue;const s=msToSec(n.duration),a={[SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN]:"auto.ui.browser.metrics"},o=n.scripts[0],{invoker:l,invokerType:c,sourceURL:d,sourceFunctionName:h,sourceCharPosition:u}=o;a["browser.script.invoker"]=l,a["browser.script.invoker_type"]=c,d&&(a["code.filepath"]=d),h&&(a["code.function"]=h),-1!==u&&(a["browser.script.source_char_position"]=u),startAndEndSpan(e,t,t+s,{name:"Main UI thread blocked",op:"ui.long-animation-frame",attributes:a})}}).observe({type:"long-animation-frame",buffered:!0})}function startTrackingInteractions(){addPerformanceInstrumentationHandler("event",({entries:t})=>{const e=getActiveSpan();if(e)for(const n of t)if("click"===n.name){const t=msToSec(browserPerformanceTimeOrigin()+n.startTime),r=msToSec(n.duration),i={name:htmlTreeAsString(n.target),op:`ui.interaction.${n.name}`,startTime:t,attributes:{[SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN]:"auto.ui.browser.metrics"}},s=getComponentName(n.target);s&&(i.attributes["ui.component_name"]=s),startAndEndSpan(e,t,t+r,i)}})}function _trackCLS(){return addClsInstrumentationHandler(({metric:t})=>{const e=t.entries[t.entries.length-1];e&&(_measurements.cls={value:t.value,unit:""},_clsEntry=e)},!0)}function _trackLCP(){return addLcpInstrumentationHandler(({metric:t})=>{const e=t.entries[t.entries.length-1];e&&isValidLcpMetric(t.value)&&(_measurements.lcp={value:t.value,unit:"millisecond"},_lcpEntry=e)},!0)}function _trackTtfb(){return addTtfbInstrumentationHandler(({metric:t})=>{t.entries[t.entries.length-1]&&(_measurements.ttfb={value:t.value,unit:"millisecond"})})}function _trackFpFcp(){return addPerformanceInstrumentationHandler("paint",({entries:t})=>{const e=getVisibilityWatcher();for(const n of t){const t=n.startTime<e.firstHiddenTime;"first-paint"===n.name&&t&&(_measurements.fp={value:n.startTime,unit:"millisecond"}),"first-contentful-paint"===n.name&&t&&(_measurements.fcp={value:n.startTime,unit:"millisecond"})}})}function addPerformanceEntries(t,e){const n=getBrowserPerformanceAPI(),r=browserPerformanceTimeOrigin();if(!n?.getEntries||!r)return;const{spanStreamingEnabled:i,ignorePerformanceApiSpans:s,ignoreResourceSpans:a}=e,o=msToSec(r),l=n.getEntries(),{op:c,start_timestamp:d}=spanToJSON(t);l.slice(_performanceCursor).forEach(e=>{const n=msToSec(e.startTime),r=msToSec(Math.max(0,e.duration));if(!("navigation"===c&&d&&o+n<d))switch(e.entryType){case"navigation":_addNavigationSpans(t,e,o);break;case"mark":case"paint":case"measure":_addMeasureSpans(t,e,n,r,o,s);break;case"resource":_addResourceSpans(t,e,e.name,n,r,o,a)}}),_performanceCursor=Math.max(l.length-1,0),_trackNavigator(t,i)}function addWebVitalsToSpan(t,e){const n=browserPerformanceTimeOrigin();if(!getBrowserPerformanceAPI()?.getEntries||!n)return void resetWebVitalState();const{spanStreamingEnabled:r,recordClsOnPageloadSpan:i,recordLcpOnPageloadSpan:s}=e,a=msToSec(n);if("pageload"===spanToJSON(t).op){if(_addTtfbRequestTimeToMeasurements(_measurements),r){const e=(e,n,r)=>{const i=r??`browser.web_vital.${e}.value`;t.setAttribute(i,n),DEBUG_BUILD$1&&debug.log("Setting web vital attribute",{[i]:n},"on pageload span")};["ttfb","fp","fcp"].forEach(t=>{_measurements[t]&&e(t,_measurements[t].value)}),_measurements["ttfb.requestTime"]&&e("ttfb.requestTime",_measurements["ttfb.requestTime"].value,"browser.web_vital.ttfb.request_time")}else i||delete _measurements.cls,s||delete _measurements.lcp,Object.entries(_measurements).forEach(([e,n])=>{setMeasurement(e,n.value,n.unit,t)}),_setWebVitalAttributes(t,e);t.setAttribute(r?"browser.performance.time_origin":"performance.timeOrigin",a),t.setAttribute(r?"browser.performance.navigation.activation_start":"performance.activationStart",getActivationStart())}resetWebVitalState()}function resetWebVitalState(){_lcpEntry=void 0,_clsEntry=void 0,_measurements={}}function isReact19MeasureEntry(t){if("measure"===t?.entryType)try{return"Components ⚛"===t.detail.devtools.track}catch{return}}function _addMeasureSpans(t,e,n,r,i,s){if(isReact19MeasureEntry(e))return;if(["mark","measure"].includes(e.entryType)&&stringMatchesSomePattern(e.name,s))return;const a=getNavigationEntry(!1),o=msToSec(a?a.requestStart:0),l=i+Math.max(n,o),c=i+n,d=c+r,h={[SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN]:"auto.resource.browser.metrics"};l!==c&&(h["sentry.browser.measure_happened_before_request"]=!0,h["sentry.browser.measure_start_time"]=l),_addDetailToSpanAttributes(h,e),l<=d&&startAndEndSpan(t,l,d,{name:e.name,op:e.entryType,attributes:h})}function _addDetailToSpanAttributes(t,e){try{const n=e.detail;if(!n)return;if("object"==typeof n){for(const[e,r]of Object.entries(n))if(r&&isPrimitive(r))t[`sentry.browser.measure.detail.${e}`]=r;else if(void 0!==r)try{t[`sentry.browser.measure.detail.${e}`]=JSON.stringify(r)}catch{}return}if(isPrimitive(n))return void(t["sentry.browser.measure.detail"]=n);try{t["sentry.browser.measure.detail"]=JSON.stringify(n)}catch{}}catch{}}function _addNavigationSpans(t,e,n){["unloadEvent","redirect","domContentLoadedEvent","loadEvent","connect"].forEach(r=>{_addPerformanceNavigationTiming(t,e,r,n)}),_addPerformanceNavigationTiming(t,e,"secureConnection",n,"TLS/SSL"),_addPerformanceNavigationTiming(t,e,"fetch",n,"cache"),_addPerformanceNavigationTiming(t,e,"domainLookup",n,"DNS"),_addRequest(t,e,n)}function _addPerformanceNavigationTiming(t,e,n,r,i=n){const s=e[_getEndPropertyNameForNavigationTiming(n)],a=e[`${n}Start`];a&&s&&startAndEndSpan(t,r+msToSec(a),r+msToSec(s),{op:`browser.${i}`,name:e.name,attributes:{[SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN]:"auto.ui.browser.metrics",..."redirect"===n&&null!=e.redirectCount?{"http.redirect_count":e.redirectCount}:{}}})}function _getEndPropertyNameForNavigationTiming(t){return"secureConnection"===t?"connectEnd":"fetch"===t?"domainLookupStart":`${t}End`}function _addRequest(t,e,n){const r=n+msToSec(e.requestStart),i=n+msToSec(e.responseEnd),s=n+msToSec(e.responseStart);e.responseEnd&&(startAndEndSpan(t,r,i,{op:"browser.request",name:e.name,attributes:{[SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN]:"auto.ui.browser.metrics"}}),startAndEndSpan(t,s,i,{op:"browser.response",name:e.name,attributes:{[SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN]:"auto.ui.browser.metrics"}}))}function _addResourceSpans(t,e,n,r,i,s,a){if("xmlhttprequest"===e.initiatorType||"fetch"===e.initiatorType)return;const o=e.initiatorType?`resource.${e.initiatorType}`:"resource.other";if(a?.includes(o))return;const l={[SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN]:"auto.resource.browser.metrics"},c=parseUrl(n);c.protocol&&(l["url.scheme"]=c.protocol.split(":").pop()),c.host&&(l["server.address"]=c.host),l["url.same_origin"]=n.includes(WINDOW.location.origin),l[Yu]=n,_setResourceRequestAttributes(e,l,[["responseStatus","http.response.status_code"],["transferSize","http.response_transfer_size"],["encodedBodySize","http.response_content_length"],["decodedBodySize","http.decoded_response_content_length"],["renderBlockingStatus","resource.render_blocking_status"],["deliveryType","http.response_delivery_type"]]);const d={...l,...resourceTimingToSpanAttributes(e)},h=s+r;startAndEndSpan(t,h,h+i,{name:n.replace(WINDOW.location.origin,""),op:o,attributes:d})}function _trackNavigator(t,e){const n=WINDOW.navigator;if(!n)return;const r=n.connection;r&&(r.effectiveType&&t.setAttribute(e?"network.connection.effective_type":"effectiveConnectionType",r.effectiveType),r.type&&t.setAttribute(e?"network.connection.type":"connectionType",r.type),isMeasurementValue(r.rtt)&&(e?t.setAttribute("network.connection.rtt",r.rtt):"pageload"===spanToJSON(t).op&&setMeasurement("connection.rtt",r.rtt,"millisecond"))),isMeasurementValue(n.deviceMemory)&&(e?t.setAttribute("device.memory.estimated_capacity",n.deviceMemory):t.setAttribute("deviceMemory",`${n.deviceMemory} GB`)),isMeasurementValue(n.hardwareConcurrency)&&(e?t.setAttribute("device.processor_count",n.hardwareConcurrency):t.setAttribute("hardwareConcurrency",String(n.hardwareConcurrency)))}function _setWebVitalAttributes(t,e){_lcpEntry&&e.recordLcpOnPageloadSpan&&(_lcpEntry.element&&t.setAttribute("lcp.element",htmlTreeAsString(_lcpEntry.element)),_lcpEntry.id&&t.setAttribute("lcp.id",_lcpEntry.id),_lcpEntry.url&&t.setAttribute("lcp.url",_lcpEntry.url.trim().slice(0,200)),null!=_lcpEntry.loadTime&&t.setAttribute("lcp.loadTime",_lcpEntry.loadTime),null!=_lcpEntry.renderTime&&t.setAttribute("lcp.renderTime",_lcpEntry.renderTime),t.setAttribute("lcp.size",_lcpEntry.size)),_clsEntry?.sources&&e.recordClsOnPageloadSpan&&_clsEntry.sources.forEach((e,n)=>t.setAttribute(`cls.source.${n+1}`,htmlTreeAsString(e.node)))}function _setResourceRequestAttributes(t,e,n){n.forEach(([n,r])=>{const i=t[n];null!=i&&("number"==typeof i&&i<MAX_INT_AS_BYTES||"string"==typeof i)&&(e[r]=i)})}function _addTtfbRequestTimeToMeasurements(t){const e=getNavigationEntry(!1);if(!e)return;const{responseStart:n,requestStart:r}=e;r<=n&&(t["ttfb.requestTime"]={value:n-r,unit:"millisecond"})}const LAST_INTERACTIONS=[],INTERACTIONS_SPAN_MAP=/* @__PURE__ */new Map,ELEMENT_NAME_TIMESTAMP_MAP=/* @__PURE__ */new Map,MAX_PLAUSIBLE_INP_DURATION=60;function startTrackingINP(){if(getBrowserPerformanceAPI()&&browserPerformanceTimeOrigin()){const t=_trackINP();return()=>{t()}}return()=>{}}const INP_ENTRY_MAP={click:"click",pointerdown:"click",pointerup:"click",mousedown:"click",mouseup:"click",touchstart:"click",touchend:"click",mouseover:"hover",mouseout:"hover",mouseenter:"hover",mouseleave:"hover",pointerover:"hover",pointerout:"hover",pointerenter:"hover",pointerleave:"hover",dragstart:"drag",dragend:"drag",drag:"drag",dragenter:"drag",dragleave:"drag",dragover:"drag",drop:"drag",keydown:"press",keyup:"press",keypress:"press",input:"press"};function _trackINP(){return addInpInstrumentationHandler(_onInp)}const _onInp=({metric:t})=>{if(null==t.value)return;const e=msToSec(t.value);if(e>MAX_PLAUSIBLE_INP_DURATION)return;const n=t.entries.find(e=>e.duration===t.value&&INP_ENTRY_MAP[e.name]);if(!n)return;const{interactionId:r}=n,i=INP_ENTRY_MAP[n.name],s=msToSec(browserPerformanceTimeOrigin()+n.startTime),a=getActiveSpan(),o=a?getRootSpan(a):void 0,l=null!=r?INTERACTIONS_SPAN_MAP.get(r):void 0,c=l?.span||o,d=c?spanToJSON(c).description:getCurrentScope().getScopeData().transactionName,h=startStandaloneWebVitalSpan({name:l?.elementName||htmlTreeAsString(n.target),transaction:d,attributes:{[SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN]:"auto.http.browser.inp",[SEMANTIC_ATTRIBUTE_SENTRY_OP]:`ui.interaction.${i}`,[SEMANTIC_ATTRIBUTE_EXCLUSIVE_TIME]:n.duration},startTime:s});h&&(h.addEvent("inp",{[SEMANTIC_ATTRIBUTE_SENTRY_MEASUREMENT_UNIT]:"millisecond",[SEMANTIC_ATTRIBUTE_SENTRY_MEASUREMENT_VALUE]:t.value}),h.end(s+e))};function getCachedInteractionContext(t){return null!=t?INTERACTIONS_SPAN_MAP.get(t):void 0}function registerInpInteractionListener(){const t=Object.keys(INP_ENTRY_MAP);function e(t){const e=t.target;if(!e)return;const n=htmlTreeAsString(e),r=Math.round(t.timeStamp);if(ELEMENT_NAME_TIMESTAMP_MAP.set(r,n),ELEMENT_NAME_TIMESTAMP_MAP.size>50){const t=ELEMENT_NAME_TIMESTAMP_MAP.keys().next().value;void 0!==t&&ELEMENT_NAME_TIMESTAMP_MAP.delete(t)}}isBrowser()&&t.forEach(t=>{WINDOW.addEventListener(t,e,{capture:!0,passive:!0})});const n=({entries:t})=>{const e=getActiveSpan(),n=e&&getRootSpan(e);t.forEach(t=>{if(!isPerformanceEventTiming(t))return;const e=t.interactionId;if(null==e)return;if(INTERACTIONS_SPAN_MAP.has(e))return;const r=t.target?htmlTreeAsString(t.target):function(t){const e=Math.round(t.startTime);let n=ELEMENT_NAME_TIMESTAMP_MAP.get(e);if(!n)for(let t=-5;t<=5;t++){const r=ELEMENT_NAME_TIMESTAMP_MAP.get(e+t);if(r){n=r;break}}return n||"<unknown>"}(t);if(LAST_INTERACTIONS.length>10){const t=LAST_INTERACTIONS.shift();INTERACTIONS_SPAN_MAP.delete(t)}LAST_INTERACTIONS.push(e),INTERACTIONS_SPAN_MAP.set(e,{span:n,elementName:r})})};addPerformanceInstrumentationHandler("event",n),addPerformanceInstrumentationHandler("first-input",n)}function _emitWebVitalSpan(t){const{name:e,op:n,origin:r,metricName:i,value:s,attributes:a,parentSpan:o,reportEvent:l,startTime:c,endTime:d}=t,h=getCurrentScope().getScopeData().transactionName,u={[SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN]:r,[SEMANTIC_ATTRIBUTE_SENTRY_OP]:n,[SEMANTIC_ATTRIBUTE_EXCLUSIVE_TIME]:0,[`browser.web_vital.${i}.value`]:s,[Xc]:h,[Lc]:h,"user_agent.original":WINDOW.navigator?.userAgent,...a};o&&"pageload"===spanToStreamedSpanJSON(o).attributes?.[SEMANTIC_ATTRIBUTE_SENTRY_OP]&&(u["sentry.pageload.span_id"]=o.spanContext().spanId),l&&(u[`browser.web_vital.${i}.report_event`]=l);const p=startInactiveSpan({name:e,attributes:u,startTime:c,parentSpan:o});p&&p.end(d??c)}function trackLcpAsSpan(t){let e,n=0;if(!supportsWebVital("largest-contentful-paint"))return;const r=addLcpInstrumentationHandler(({metric:t})=>{const r=t.entries[t.entries.length-1];r&&isValidLcpMetric(t.value)&&(n=t.value,e=r)},!0);listenForWebVitalReportEvents(t,(t,i,s)=>{_sendLcpSpan(n,e,s,t),r()})}function _sendLcpSpan(t,e,n,r){if(!isValidLcpMetric(t))return;DEBUG_BUILD$1&&debug.log(`Sending LCP span (${t})`);const i=browserPerformanceTimeOrigin()||0,s=msToSec(i),a=msToSec(i+(e?.startTime||0)),o=e?htmlTreeAsString(e.element):"Largest contentful paint",l={};e?.element&&(l["browser.web_vital.lcp.element"]=htmlTreeAsString(e.element)),e?.id&&(l["browser.web_vital.lcp.id"]=e.id),e?.url&&(l["browser.web_vital.lcp.url"]=e.url),null!=e?.loadTime&&(l["browser.web_vital.lcp.load_time"]=e.loadTime),null!=e?.renderTime&&(l["browser.web_vital.lcp.render_time"]=e.renderTime),null!=e?.size&&(l["browser.web_vital.lcp.size"]=e.size),_emitWebVitalSpan({name:o,op:"ui.webvital.lcp",origin:"auto.http.browser.lcp",metricName:"lcp",value:t,attributes:l,parentSpan:n,reportEvent:r,startTime:s,endTime:a})}function trackClsAsSpan(t){let e,n=0;if(!supportsWebVital("layout-shift"))return;const r=addClsInstrumentationHandler(({metric:t})=>{const r=t.entries[t.entries.length-1];r&&(n=t.value,e=r)},!0);listenForWebVitalReportEvents(t,(t,i,s)=>{_sendClsSpan(n,e,s,t),r()})}function _sendClsSpan(t,e,n,r){DEBUG_BUILD$1&&debug.log(`Sending CLS span (${t})`);const i=e?msToSec((browserPerformanceTimeOrigin()||0)+e.startTime):timestampInSeconds(),s=e?htmlTreeAsString(e.sources[0]?.node):"Layout shift",a={};e?.sources&&e.sources.forEach((t,e)=>{a[`browser.web_vital.cls.source.${e+1}`]=htmlTreeAsString(t.node)}),_emitWebVitalSpan({name:s,op:"ui.webvital.cls",origin:"auto.http.browser.cls",metricName:"cls",value:t,attributes:a,parentSpan:n,reportEvent:r,startTime:i})}function trackInpAsSpan(){getBrowserPerformanceAPI()&&browserPerformanceTimeOrigin()&&addInpInstrumentationHandler(({metric:t})=>{if(null==t.value)return;if(msToSec(t.value)>MAX_PLAUSIBLE_INP_DURATION)return;const e=t.entries.find(e=>e.duration===t.value&&INP_ENTRY_MAP[e.name]);e&&_sendInpSpan(t.value,e)})}function _sendInpSpan(t,e){DEBUG_BUILD$1&&debug.log(`Sending INP span (${t})`);const n=msToSec(browserPerformanceTimeOrigin()+e.startTime),r=msToSec(t),i=INP_ENTRY_MAP[e.name],s=getCachedInteractionContext(e.interactionId),a=getActiveSpan(),o=a?getRootSpan(a):void 0,l=s?.span||o,c=l?spanToStreamedSpanJSON(l).name:getCurrentScope().getScopeData().transactionName;_emitWebVitalSpan({name:s?.elementName||htmlTreeAsString(e.target),op:`ui.interaction.${i}`,origin:"auto.http.browser.inp",metricName:"inp",value:t,attributes:{[SEMANTIC_ATTRIBUTE_EXCLUSIVE_TIME]:e.duration,[Xc]:c,[Lc]:c},startTime:n,endTime:n+r,parentSpan:l})}const DEBOUNCE_DURATION=1e3;let debounceTimerID,lastCapturedEventType,lastCapturedEventTargetId,lastHref;function addClickKeypressInstrumentationHandler(t){addHandler$1("dom",t),maybeInstrument("dom",instrumentDOM)}function instrumentDOM(){if(!WINDOW.document)return;const t=triggerHandlers$1.bind(null,"dom"),e=makeDOMEventHandler(t,!0);WINDOW.document.addEventListener("click",e,!1),WINDOW.document.addEventListener("keypress",e,!1),["EventTarget","Node"].forEach(e=>{const n=WINDOW,r=n[e]?.prototype;r?.hasOwnProperty?.("addEventListener")&&(fill(r,"addEventListener",function(e){return function(n,r,i){if("click"===n||"keypress"==n)try{const r=this.__sentry_instrumentation_handlers__=this.__sentry_instrumentation_handlers__||{},s=r[n]=r[n]||{refCount:0};if(!s.handler){const r=makeDOMEventHandler(t);s.handler=r,e.call(this,n,r,i)}s.refCount++}catch{}return e.call(this,n,r,i)}}),fill(r,"removeEventListener",function(t){return function(e,n,r){if("click"===e||"keypress"==e)try{const n=this.__sentry_instrumentation_handlers__||{},i=n[e];i&&(i.refCount--,i.refCount<=0&&(t.call(this,e,i.handler,r),i.handler=void 0,delete n[e]),0===Object.keys(n).length&&delete this.__sentry_instrumentation_handlers__)}catch{}return t.call(this,e,n,r)}}))})}function isSimilarToLastCapturedEvent(t){if(t.type!==lastCapturedEventType)return!1;try{if(!t.target||t.target._sentryId!==lastCapturedEventTargetId)return!1}catch{}return!0}function shouldSkipDOMEvent(t,e){return"keypress"===t&&(!e?.tagName||"INPUT"!==e.tagName&&"TEXTAREA"!==e.tagName&&!e.isContentEditable)}function makeDOMEventHandler(t,e=!1){return n=>{if(!n||n._sentryCaptured)return;const r=getEventTarget(n);if(shouldSkipDOMEvent(n.type,r))return;addNonEnumerableProperty(n,"_sentryCaptured",!0),r&&!r._sentryId&&addNonEnumerableProperty(r,"_sentryId",uuid4());const i="keypress"===n.type?"input":n.type;isSimilarToLastCapturedEvent(n)||(t({event:n,name:i,global:e}),lastCapturedEventType=n.type,lastCapturedEventTargetId=r?r._sentryId:void 0),clearTimeout(debounceTimerID),debounceTimerID=WINDOW.setTimeout(()=>{lastCapturedEventTargetId=void 0,lastCapturedEventType=void 0},DEBOUNCE_DURATION)}}function getEventTarget(t){try{return t.target}catch{return null}}function addHistoryInstrumentationHandler(t){const e="history";addHandler$1(e,t),maybeInstrument(e,instrumentHistory)}function instrumentHistory(){function t(t){return function(...e){const n=e.length>2?e[2]:void 0;if(n){const r=lastHref,i=getAbsoluteUrl(String(n));if(lastHref=i,r===i)return t.apply(this,e);triggerHandlers$1("history",{from:r,to:i})}return t.apply(this,e)}}WINDOW.addEventListener("popstate",()=>{const t=WINDOW.location.href,e=lastHref;lastHref=t,e!==t&&triggerHandlers$1("history",{from:e,to:t})}),supportsHistory()&&(fill(WINDOW.history,"pushState",t),fill(WINDOW.history,"replaceState",t))}function getAbsoluteUrl(t){try{return new URL(t,WINDOW.location.origin).toString()}catch{return t}}const cachedImplementations={};function getNativeImplementation(t){const e=cachedImplementations[t];if(e)return e;let n=WINDOW[t];if(isNativeFunction(n))return cachedImplementations[t]=n.bind(WINDOW);const r=WINDOW.document;if(r&&"function"==typeof r.createElement)try{const e=r.createElement("iframe");e.hidden=!0,r.head.appendChild(e);const i=e.contentWindow;i?.[t]&&(n=i[t]),r.head.removeChild(e)}catch(e){DEBUG_BUILD$1&&debug.warn(`Could not create sandbox iframe for ${t} check, bailing to window.${t}: `,e)}return n?cachedImplementations[t]=n.bind(WINDOW):n}function clearCachedImplementation(t){cachedImplementations[t]=void 0}const SENTRY_XHR_DATA_KEY="__sentry_xhr_v3__";function addXhrInstrumentationHandler(t){addHandler$1("xhr",t),maybeInstrument("xhr",instrumentXHR)}function instrumentXHR(){if(!WINDOW.XMLHttpRequest)return;const t=XMLHttpRequest.prototype;t.open=new Proxy(t.open,{apply(t,e,n){const r=new Error,i=1e3*timestampInSeconds(),s=isString(n[0])?n[0].toUpperCase():void 0,a=parseXhrUrlArg(n[1]);if(!s||!a)return t.apply(e,n);e[SENTRY_XHR_DATA_KEY]={method:s,url:a,request_headers:{}},"POST"===s&&a.match(/sentry_key/)&&(e.__sentry_own_request__=!0);const o=()=>{const t=e[SENTRY_XHR_DATA_KEY];if(t&&4===e.readyState){try{t.status_code=e.status}catch{}triggerHandlers$1("xhr",{endTimestamp:1e3*timestampInSeconds(),startTimestamp:i,xhr:e,virtualError:r}),e.removeEventListener("readystatechange",o)}};return"onreadystatechange"in e&&"function"==typeof e.onreadystatechange?e.onreadystatechange=new Proxy(e.onreadystatechange,{apply:(t,e,n)=>(o(),t.apply(e,n))}):e.addEventListener("readystatechange",o),e.setRequestHeader=new Proxy(e.setRequestHeader,{apply(t,e,n){const[r,i]=n,s=e[SENTRY_XHR_DATA_KEY];return s&&isString(r)&&isString(i)&&(s.request_headers[r.toLowerCase()]=i),t.apply(e,n)}}),t.apply(e,n)}}),t.send=new Proxy(t.send,{apply(t,e,n){const r=e[SENTRY_XHR_DATA_KEY];return r?(void 0!==n[0]&&(r.body=n[0]),triggerHandlers$1("xhr",{startTimestamp:1e3*timestampInSeconds(),xhr:e}),t.apply(e,n)):t.apply(e,n)}})}function parseXhrUrlArg(t){if(isString(t))return t;try{return t.toString()}catch{}}function parseXhrResponseHeaders(t){let e;try{e=t.getAllResponseHeaders()}catch(e){return DEBUG_BUILD$1&&debug.error(e,"Failed to get xhr response headers",t),{}}return e?e.split("\r\n").reduce((t,e)=>{const[n,r]=e.split(": ");return r&&(t[n.toLowerCase()]=r),t},{}):{}}const DEFAULT_BROWSER_TRANSPORT_BUFFER_SIZE=40;function makeFetchTransport(t,e=getNativeImplementation("fetch")){let n=0,r=0;return createTransport(t,async function(i){const s=i.body.length;n+=s,r++;const a={body:i.body,method:"POST",referrerPolicy:"strict-origin",headers:t.headers,keepalive:n<=6e4&&r<15,...t.fetchOptions};try{const n=await e(t.url,a);return{statusCode:n.status,headers:{"x-sentry-rate-limits":n.headers.get("X-Sentry-Rate-Limits"),"retry-after":n.headers.get("Retry-After")}}}catch(t){throw clearCachedImplementation("fetch"),t}finally{n-=s,r--}},makePromiseBuffer(t.bufferSize||DEFAULT_BROWSER_TRANSPORT_BUFFER_SIZE))}const DEBUG_BUILD="undefined"==typeof __SENTRY_DEBUG__||__SENTRY_DEBUG__,CHROME_PRIORITY=30,GECKO_PRIORITY=50;function createFrame(t,e,n,r){const i={filename:t,function:"<anonymous>"===e?UNKNOWN_FUNCTION:e,in_app:!0};return void 0!==n&&(i.lineno=n),void 0!==r&&(i.colno=r),i}const chromeRegexNoFnName=/^\s*at (\S+?)(?::(\d+))(?::(\d+))\s*$/i,chromeRegex=/^\s*at (?:(.+?\)(?: \[.+\])?|.*?) ?\((?:address at )?)?(?:async )?((?:<anonymous>|[-a-z]+:|.*bundle|\/)?.*?)(?::(\d+))?(?::(\d+))?\)?\s*$/i,chromeEvalRegex=/\((\S*)(?::(\d+))(?::(\d+))\)/,chromeDataUriRegex=/at (.+?) ?\(data:(.+?),/,chromeStackParserFn=t=>{const e=t.match(chromeDataUriRegex);if(e)return{filename:`<data:${e[2]}>`,function:e[1]};const n=chromeRegexNoFnName.exec(t);if(n){const[,t,e,r]=n;return createFrame(t,UNKNOWN_FUNCTION,+e,+r)}const r=chromeRegex.exec(t);if(r){if(0===r[2]?.indexOf("eval")){const t=chromeEvalRegex.exec(r[2]);t&&(r[2]=t[1],r[3]=t[2],r[4]=t[3])}const[t,e]=extractSafariExtensionDetails(r[1]||UNKNOWN_FUNCTION,r[2]);return createFrame(e,t,r[3]?+r[3]:void 0,r[4]?+r[4]:void 0)}},chromeStackLineParser=[CHROME_PRIORITY,chromeStackParserFn],geckoREgex=/^\s*(.*?)(?:\((.*?)\))?(?:^|@)?((?:[-a-z]+)?:\/.*?|\[native code\]|[^@]*(?:bundle|\d+\.js)|\/[\w\-. /=]+)(?::(\d+))?(?::(\d+))?\s*$/i,geckoEvalRegex=/(\S+) line (\d+)(?: > eval line \d+)* > eval/i,gecko=t=>{const e=geckoREgex.exec(t);if(e){if(e[3]&&e[3].indexOf(" > eval")>-1){const t=geckoEvalRegex.exec(e[3]);t&&(e[1]=e[1]||"eval",e[3]=t[1],e[4]=t[2],e[5]="")}let t=e[3],n=e[1]||UNKNOWN_FUNCTION;return[n,t]=extractSafariExtensionDetails(n,t),createFrame(t,n,e[4]?+e[4]:void 0,e[5]?+e[5]:void 0)}},geckoStackLineParser=[GECKO_PRIORITY,gecko],defaultStackLineParsers=[chromeStackLineParser,geckoStackLineParser],defaultStackParser=createStackParser(...defaultStackLineParsers),extractSafariExtensionDetails=(t,e)=>{const n=-1!==t.indexOf("safari-extension"),r=-1!==t.indexOf("safari-web-extension");return n||r?[-1!==t.indexOf("@")?t.split("@")[0]:UNKNOWN_FUNCTION,n?`safari-extension:${e}`:`safari-web-extension:${e}`]:[t,e]},MAX_ALLOWED_STRING_LENGTH=1024,INTEGRATION_NAME$4="Breadcrumbs",_breadcrumbsIntegration=(t={})=>{const e={console:!0,dom:!0,fetch:!0,history:!0,sentry:!0,xhr:!0,...t};return{name:INTEGRATION_NAME$4,setup(t){e.console&&addConsoleInstrumentationHandler(_getConsoleBreadcrumbHandler(t)),e.dom&&addClickKeypressInstrumentationHandler(_getDomBreadcrumbHandler(t,e.dom)),e.xhr&&addXhrInstrumentationHandler(_getXhrBreadcrumbHandler(t)),e.fetch&&addFetchInstrumentationHandler(_getFetchBreadcrumbHandler(t)),e.history&&addHistoryInstrumentationHandler(_getHistoryBreadcrumbHandler(t)),e.sentry&&t.on("beforeSendEvent",_getSentryBreadcrumbHandler(t))}}},breadcrumbsIntegration=defineIntegration(_breadcrumbsIntegration);function _getSentryBreadcrumbHandler(t){return function(e){getClient()===t&&addBreadcrumb({category:"sentry."+("transaction"===e.type?"transaction":"event"),event_id:e.event_id,level:e.level,message:getEventDescription(e)},{event:e})}}function _getDomBreadcrumbHandler(t,e){return function(n){if(getClient()!==t)return;let r,i,s="object"==typeof e?e.serializeAttribute:void 0,a="object"==typeof e&&"number"==typeof e.maxStringLength?e.maxStringLength:void 0;a&&a>MAX_ALLOWED_STRING_LENGTH&&(DEBUG_BUILD&&debug.warn(`\`dom.maxStringLength\` cannot exceed ${MAX_ALLOWED_STRING_LENGTH}, but a value of ${a} was configured. Sentry will use ${MAX_ALLOWED_STRING_LENGTH} instead.`),a=MAX_ALLOWED_STRING_LENGTH),"string"==typeof s&&(s=[s]);try{const t=n.event,e=_isEvent(t)?t.target:t;r=htmlTreeAsString(e,{keyAttrs:s,maxStringLength:a}),i=getComponentName(e)}catch{r="<unknown>"}if(0===r.length)return;const o={category:`ui.${n.name}`,message:r};i&&(o.data={"ui.component_name":i}),addBreadcrumb(o,{event:n.event,name:n.name,global:n.global})}}function _getConsoleBreadcrumbHandler(t){return function(e){if(getClient()!==t)return;const n={category:"console",data:{arguments:e.args,logger:"console"},level:severityLevelFromString(e.level),message:safeJoin(e.args," ")};if("assert"===e.level){if(!1!==e.args[0])return;n.message=`Assertion failed: ${safeJoin(e.args.slice(1)," ")||"console.assert"}`,n.data.arguments=e.args.slice(1)}addBreadcrumb(n,{input:e.args,level:e.level})}}function _getXhrBreadcrumbHandler(t){return function(e){if(getClient()!==t)return;const{startTimestamp:n,endTimestamp:r}=e,i=e.xhr[SENTRY_XHR_DATA_KEY];if(!n||!r||!i)return;const{method:s,url:a,status_code:o,body:l}=i,c={xhr:e.xhr,input:l,startTimestamp:n,endTimestamp:r},d={category:"xhr",data:{method:s,url:a,status_code:o},type:"http",level:getBreadcrumbLogLevelFromHttpStatusCode(o)};t.emit("beforeOutgoingRequestBreadcrumb",d,c),addBreadcrumb(d,c)}}function _getFetchBreadcrumbHandler(t){return function(e){if(getClient()!==t)return;const{startTimestamp:n,endTimestamp:r}=e;if(r&&(!e.fetchData.url.match(/sentry_key/)||"POST"!==e.fetchData.method))if(e.error){const i={data:e.error,input:e.args,startTimestamp:n,endTimestamp:r},s={category:"fetch",data:e.fetchData,level:"error",type:"http"};t.emit("beforeOutgoingRequestBreadcrumb",s,i),addBreadcrumb(s,i)}else{const i=e.response,s={...e.fetchData,status_code:i?.status},a={input:e.args,response:i,startTimestamp:n,endTimestamp:r},o={category:"fetch",data:s,type:"http",level:getBreadcrumbLogLevelFromHttpStatusCode(s.status_code)};t.emit("beforeOutgoingRequestBreadcrumb",o,a),addBreadcrumb(o,a)}}}function _getHistoryBreadcrumbHandler(t){return function(e){if(getClient()!==t)return;let n=e.from,r=e.to;const i=parseUrl(WINDOW$1.location.href);let s=n?parseUrl(n):void 0;const a=parseUrl(r);s?.path||(s=i),i.protocol===a.protocol&&i.host===a.host&&(r=a.relative),i.protocol===s.protocol&&i.host===s.host&&(n=s.relative),addBreadcrumb({category:"navigation",data:{from:n,to:r}})}}function _isEvent(t){return!!t&&!!t.target}const DEFAULT_EVENT_TARGET="EventTarget,Window,Node,ApplicationCache,AudioTrackList,BroadcastChannel,ChannelMergerNode,CryptoOperation,EventSource,FileReader,HTMLUnknownElement,IDBDatabase,IDBRequest,IDBTransaction,KeyOperation,MediaController,MessagePort,ModalWindow,Notification,SVGElementInstance,Screen,SharedWorker,TextTrack,TextTrackCue,TextTrackList,WebSocket,WebSocketWorker,Worker,XMLHttpRequest,XMLHttpRequestEventTarget,XMLHttpRequestUpload".split(","),INTEGRATION_NAME$3="BrowserApiErrors",_browserApiErrorsIntegration=(t={})=>{const e={XMLHttpRequest:!0,eventTarget:!0,requestAnimationFrame:!0,setInterval:!0,setTimeout:!0,unregisterOriginalCallbacks:!1,...t};return{name:INTEGRATION_NAME$3,setupOnce(){e.setTimeout&&fill(WINDOW$1,"setTimeout",_wrapTimeFunction),e.setInterval&&fill(WINDOW$1,"setInterval",_wrapTimeFunction),e.requestAnimationFrame&&fill(WINDOW$1,"requestAnimationFrame",_wrapRAF),e.XMLHttpRequest&&"XMLHttpRequest"in WINDOW$1&&fill(XMLHttpRequest.prototype,"send",_wrapXHR);const t=e.eventTarget;t&&(Array.isArray(t)?t:DEFAULT_EVENT_TARGET).forEach(t=>_wrapEventTarget(t,e))}}},browserApiErrorsIntegration=defineIntegration(_browserApiErrorsIntegration);function _wrapTimeFunction(t){return function(...e){return e[0]=wrap(e[0],{mechanism:{handled:!1,type:`auto.browser.browserapierrors.${getFunctionName(t)}`}}),t.apply(this,e)}}function _wrapRAF(t){return function(e){return t.apply(this,[wrap(e,{mechanism:{data:{handler:getFunctionName(t)},handled:!1,type:"auto.browser.browserapierrors.requestAnimationFrame"}})])}}function _wrapXHR(t){return function(...e){const n=this;return["onload","onerror","onprogress","onreadystatechange"].forEach(t=>{t in n&&"function"==typeof n[t]&&fill(n,t,function(e){const n={mechanism:{data:{handler:getFunctionName(e)},handled:!1,type:`auto.browser.browserapierrors.xhr.${t}`}},r=getOriginalFunction(e);return r&&(n.mechanism.data.handler=getFunctionName(r)),wrap(e,n)})}),t.apply(this,e)}}function _wrapEventTarget(t,e){const n=WINDOW$1,r=n[t]?.prototype;r?.hasOwnProperty?.("addEventListener")&&(fill(r,"addEventListener",function(n){return function(r,i,s){try{isEventListenerObject(i)&&(i.handleEvent=wrap(i.handleEvent,{mechanism:{data:{handler:getFunctionName(i),target:t},handled:!1,type:"auto.browser.browserapierrors.handleEvent"}}))}catch{}return e.unregisterOriginalCallbacks&&unregisterOriginalCallback(this,r,i),n.apply(this,[r,wrap(i,{mechanism:{data:{handler:getFunctionName(i),target:t},handled:!1,type:"auto.browser.browserapierrors.addEventListener"}}),s])}}),fill(r,"removeEventListener",function(t){return function(e,n,r){try{if(Object.prototype.hasOwnProperty.call(n,"__sentry_wrapped__")){const i=n.__sentry_wrapped__;i&&t.call(this,e,i,r)}}catch{}return t.call(this,e,n,r)}}))}function isEventListenerObject(t){return"function"==typeof t.handleEvent}function unregisterOriginalCallback(t,e,n){t&&"object"==typeof t&&"removeEventListener"in t&&"function"==typeof t.removeEventListener&&t.removeEventListener(e,n)}const browserSessionIntegration=defineIntegration((t={})=>{const e=t.lifecycle??"route";return{name:"BrowserSession",setupOnce(){if(void 0===WINDOW$1.document)return void(DEBUG_BUILD&&debug.warn("Using the `browserSessionIntegration` in non-browser environments is not supported."));startSession({ignoreDuration:!0});let t=!1;whenIdleOrHidden(()=>{t||(captureSession(),t=!0)});const n=getIsolationScope();let r=n.getUser();n.addScopeListener(e=>{const n=e.getUser();r?.id===n?.id&&r?.ip_address===n?.ip_address||(r=n,t&&captureSession())}),"route"===e&&addHistoryInstrumentationHandler(({from:e,to:n})=>{e!==n&&(startSession({ignoreDuration:!0}),captureSession(),t=!0)})}}}),INTEGRATION_NAME$2="CultureContext",_cultureContextIntegration=()=>({name:INTEGRATION_NAME$2,preprocessEvent(t){const e=getCultureContext();e&&(t.contexts={...t.contexts,culture:{...e,...t.contexts?.culture}})},processSegmentSpan(t){const e=getCultureContext();e&&safeSetSpanJSONAttributes(t,{"culture.locale":e.locale,"culture.timezone":e.timezone,"culture.calendar":e.calendar})}}),cultureContextIntegration=defineIntegration(_cultureContextIntegration);function getCultureContext(){try{const t=WINDOW$1.Intl;if(!t)return;const e=t.DateTimeFormat().resolvedOptions();return{locale:e.locale,timezone:e.timeZone,calendar:e.calendar}}catch{return}}const INTEGRATION_NAME$1="GlobalHandlers",_globalHandlersIntegration=(t={})=>{const e={onerror:!0,onunhandledrejection:!0,...t};return{name:INTEGRATION_NAME$1,setupOnce(){Error.stackTraceLimit=50},setup(t){e.onerror&&(_installGlobalOnErrorHandler(t),globalHandlerLog("onerror")),e.onunhandledrejection&&(_installGlobalOnUnhandledRejectionHandler(t),globalHandlerLog("onunhandledrejection"))}}},globalHandlersIntegration=defineIntegration(_globalHandlersIntegration);function _installGlobalOnErrorHandler(t){addGlobalErrorInstrumentationHandler(e=>{const{stackParser:n,attachStacktrace:r}=getOptions();if(getClient()!==t||shouldIgnoreOnError())return;const{msg:i,url:s,line:a,column:o,error:l}=e,c=_enhanceEventWithInitialFrame(eventFromUnknownInput(n,l||i,void 0,r,!1),s,a,o);c.level="error",captureEvent(c,{originalException:l,mechanism:{handled:!1,type:"auto.browser.global_handlers.onerror"}})})}function _installGlobalOnUnhandledRejectionHandler(t){addGlobalUnhandledRejectionInstrumentationHandler(e=>{const{stackParser:n,attachStacktrace:r}=getOptions();if(getClient()!==t||shouldIgnoreOnError())return;const i=_getUnhandledRejectionError(e),s=isPrimitive(i)?_eventFromRejectionWithPrimitive(i):eventFromUnknownInput(n,i,void 0,r,!0);s.level="error",captureEvent(s,{originalException:i,mechanism:{handled:!1,type:"auto.browser.global_handlers.onunhandledrejection"}})})}function _getUnhandledRejectionError(t){if(isPrimitive(t))return t;try{if("reason"in t)return t.reason;if("detail"in t&&"reason"in t.detail)return t.detail.reason}catch{}return t}function _eventFromRejectionWithPrimitive(t){return{exception:{values:[{type:"UnhandledRejection",value:`Non-Error promise rejection captured with value: ${String(t)}`}]}}}function _enhanceEventWithInitialFrame(t,e,n,r){const i=t.exception=t.exception||{},s=i.values=i.values||[],a=s[0]=s[0]||{},o=a.stacktrace=a.stacktrace||{},l=o.frames=o.frames||[];return 0===l.length&&l.push({colno:r,lineno:n,filename:getFilenameFromUrl(e)??getLocationHref(),function:UNKNOWN_FUNCTION,in_app:!0}),t}function globalHandlerLog(t){DEBUG_BUILD&&debug.log(`Global Handler attached: ${t}`)}function getOptions(){const t=getClient();return t?.getOptions()||{stackParser:()=>[],attachStacktrace:!1}}function getFilenameFromUrl(t){if(isString(t)&&0!==t.length)return t.startsWith("data:")?`<${stripDataUrlContent(t,!1)}>`:t}const httpContextIntegration=defineIntegration(()=>({name:"HttpContext",preprocessEvent(t){if(!WINDOW$1.navigator&&!WINDOW$1.location&&!WINDOW$1.document)return;const e=getHttpRequestData(),n={...e.headers,...t.request?.headers};t.request={...e,...t.request,headers:n}},processSegmentSpan(t){const e=t.attributes?.[SEMANTIC_ATTRIBUTE_SENTRY_OP];if(!WINDOW$1.navigator&&!WINDOW$1.location&&!WINDOW$1.document)return;const n=getHttpRequestData();safeSetSpanJSONAttributes(t,{[Yu]:"http.client"!==e?n.url:void 0,"http.request.header.user_agent":n.headers["User-Agent"],"http.request.header.referer":n.headers.Referer})}})),DEFAULT_KEY="cause",DEFAULT_LIMIT=5,INTEGRATION_NAME="LinkedErrors",_linkedErrorsIntegration=(t={})=>{const e=t.limit||DEFAULT_LIMIT,n=t.key||DEFAULT_KEY;return{name:INTEGRATION_NAME,preprocessEvent(t,r,i){applyAggregateErrorsToEvent(exceptionFromError,i.getOptions().stackParser,n,e,t,r)}}},linkedErrorsIntegration=defineIntegration(_linkedErrorsIntegration);function getDefaultIntegrations(t){return[inboundFiltersIntegration(),functionToStringIntegration(),conversationIdIntegration(),browserApiErrorsIntegration(),breadcrumbsIntegration(),globalHandlersIntegration(),linkedErrorsIntegration(),dedupeIntegration(),httpContextIntegration(),cultureContextIntegration(),browserSessionIntegration()]}function baggageHeaderHasSentryValues(t){return t.split(",").some(t=>t.trim().startsWith("sentry-"))}function getFullURL(t){try{return new URL(t,WINDOW$1.location.origin).href}catch{return}}function isPerformanceResourceTiming(t){return"resource"===t.entryType&&"initiatorType"in t&&"string"==typeof t.nextHopProtocol&&("fetch"===t.initiatorType||"xmlhttprequest"===t.initiatorType)}function createHeadersSafely(t){try{return new Headers(t)}catch{return}}const defaultRequestInstrumentationOptions={traceFetch:!0,traceXHR:!0,enableHTTPTimings:!0,trackFetchStreamPerformance:!1};function instrumentOutgoingRequests(t,e){const{traceFetch:n,traceXHR:r,shouldCreateSpanForRequest:i,enableHTTPTimings:s,tracePropagationTargets:a,onRequestSpanStart:o,onRequestSpanEnd:l}={...defaultRequestInstrumentationOptions,...e},c="function"==typeof i?i:t=>!0,d=t=>shouldAttachHeaders(t,a),h={},u=t.getOptions().propagateTraceparent;n&&addFetchInstrumentationHandler(e=>{const n=instrumentFetchRequest(e,c,d,h,{propagateTraceparent:u,onRequestSpanEnd:l});if(n){const r=getFullURL(e.fetchData.url),i=r?parseUrl(r).host:void 0,a=r?stripDataUrlContent(r):void 0;n.setAttributes({[ws]:a,[Yu]:a,"server.address":i}),s&&addHTTPTimings(n,t),o?.(n,{headers:e.headers})}}),r&&addXhrInstrumentationHandler(e=>{const n=xhrCallback(e,c,d,h,u,l);n&&(s&&addHTTPTimings(n,t),o?.(n,{headers:createHeadersSafely(e.xhr.__sentry_xhr_v3__?.request_headers)}))})}const HTTP_TIMING_WAIT_MS=300;function addHTTPTimings(t,e){const{url:n}=spanToJSON(t).data;if(!n||"string"!=typeof n)return;let r=()=>{setTimeout(i)};if(hasSpanStreamingEnabled(e)){const e=t.end.bind(t);t.end=t=>{const n=t??timestampInSeconds();let s=!1;const a=()=>{s||(s=!0,setTimeout(i),e(n),clearTimeout(o))};r=a;const o=setTimeout(a,HTTP_TIMING_WAIT_MS)}}const i=addPerformanceInstrumentationHandler("resource",({entries:e})=>{e.forEach(e=>{isPerformanceResourceTiming(e)&&e.name.endsWith(n)&&(t.setAttributes(resourceTimingToSpanAttributes(e)),r())})})}function shouldAttachHeaders(t,e){const n=getLocationHref();if(n){let r,i;try{r=new URL(t,n),i=new URL(n).origin}catch{return!1}const s=r.origin===i;return e?stringMatchesSomePattern(r.toString(),e)||s&&stringMatchesSomePattern(r.pathname,e):s}{const n=!!t.match(/^\/(?!\/)/);return e?stringMatchesSomePattern(t,e):n}}function xhrCallback(t,e,n,r,i,s){const a=t.xhr,o=a?.[SENTRY_XHR_DATA_KEY];if(!a||a.__sentry_own_request__||!o)return;const{url:l,method:c}=o,d=hasSpansEnabled()&&e(l);if(t.endTimestamp){const e=a.__sentry_xhr_span_id__;if(!e)return;const n=r[e];return void(n&&(d&&void 0!==o.status_code&&(setHttpStatus(n,o.status_code),n.end(),s?.(n,{headers:createHeadersSafely(parseXhrResponseHeaders(a)),error:t.error})),delete r[e]))}const h=getFullURL(l),u=parseUrl(h||l),p=h?stripDataUrlContent(h):void 0,f=stripDataUrlContent(stripUrlQueryAndFragment(l)),m=getClient(),_=!!getActiveSpan(),g=_||!!m&&hasSpanStreamingEnabled(m),y=d&&g?startInactiveSpan({name:`${c} ${f}`,attributes:{url:stripDataUrlContent(l),type:"xhr","http.method":c,"http.url":p,[Yu]:p,"server.address":u?.host,[SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN]:"auto.http.browser",[SEMANTIC_ATTRIBUTE_SENTRY_OP]:"http.client",...u?.search&&{"http.query":u?.search},...u?.hash&&{"http.fragment":u?.hash}}}):new SentryNonRecordingSpan,S=spanIsIgnored(y)&&_?void 0:y;return d&&!g&&m?.recordDroppedEvent("no_parent_span","span"),a.__sentry_xhr_span_id__=y.spanContext().spanId,r[a.__sentry_xhr_span_id__]=y,n(l)&&addTracingHeadersToXhrRequest(a,hasSpansEnabled()&&g?S:void 0,i),m&&m.emit("beforeOutgoingRequestSpan",y,t),y}function addTracingHeadersToXhrRequest(t,e,n){const{"sentry-trace":r,baggage:i,traceparent:s}=getTraceData({span:e,propagateTraceparent:n});r&&setHeaderOnXhr(t,r,i,s)}function setHeaderOnXhr(t,e,n,r){const i=t.__sentry_xhr_v3__?.request_headers;if(!i?.["sentry-trace"]&&t.setRequestHeader)try{if(t.setRequestHeader("sentry-trace",e),r&&!i?.traceparent&&t.setRequestHeader("traceparent",r),n){const e=i?.baggage;e&&baggageHeaderHasSentryValues(e)||t.setRequestHeader("baggage",n)}}catch{}}const responseToStreamSpan=/* @__PURE__ */new WeakMap,responseToFallbackTimeout=/* @__PURE__ */new WeakMap,STREAM_RESOLVE_FALLBACK_MS=9e4,STREAMING_CONTENT_TYPES=["text/event-stream","application/x-ndjson","application/stream+json"],fetchStreamPerformanceIntegration=defineIntegration(()=>({name:"FetchStreamPerformance",setup(){addFetchEndInstrumentationHandler(t=>{if(t.response){const e=responseToStreamSpan.get(t.response);if(e&&t.endTimestamp){e.end(t.endTimestamp);const n=responseToFallbackTimeout.get(t.response);n&&clearTimeout(n)}}}),addFetchInstrumentationHandler(t=>{if(t.endTimestamp&&t.response){const e=t.response.headers?.get("content-type")||"";if(t.response.headers?.get("content-length")||!STREAMING_CONTENT_TYPES.some(t=>e.startsWith(t)))return;const n=t.fetchData?.url||"",r=t.fetchData?.method||"GET",i=parseStringToURLObject(n),s=startInactiveSpan({name:`${r} ${n.startsWith("data:")?stripDataUrlContent(n):i?getSanitizedUrlStringFromUrlObject(i):n}`,startTime:t.endTimestamp,attributes:{url:stripDataUrlContent(n),"http.method":r,type:"fetch",[SEMANTIC_ATTRIBUTE_SENTRY_OP]:"http.client.stream",[SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN]:"auto.http.browser.stream"}});responseToStreamSpan.set(t.response,s);const a=setTimeout(()=>{s.isRecording()&&s.end()},STREAM_RESOLVE_FALLBACK_MS);responseToFallbackTimeout.set(t.response,a)}})}})),WEB_VITALS_INTEGRATION_NAME="WebVitals",webVitalsIntegration=defineIntegration((t={})=>{const e=new Set(t.ignore??[]);return{name:WEB_VITALS_INTEGRATION_NAME,setup(n){const r=hasSpanStreamingEnabled(n),{enableStandaloneClsSpans:i,enableStandaloneLcpSpans:s}=t._experiments??{},a=r||e.has("cls")?void 0:i||!1,o=r||e.has("lcp")?void 0:s||!1,l=startTrackingWebVitals({recordClsStandaloneSpans:a,recordLcpStandaloneSpans:o,client:n}),c=/* @__PURE__ */new WeakSet;n.on("afterStartPageLoadSpan",t=>{c.add(t)}),n.on("spanEnd",t=>{c.delete(t)&&(l(),addWebVitalsToSpan(t,{recordClsOnPageloadSpan:!1===a,recordLcpOnPageloadSpan:!1===o,spanStreamingEnabled:r}))}),r?(e.has("lcp")||trackLcpAsSpan(n),e.has("cls")||trackClsAsSpan(n),e.has("inp")||trackInpAsSpan()):e.has("inp")||startTrackingINP()},afterAllSetup(){e.has("inp")||registerInpInteractionListener()}}});function registerBackgroundTabDetection(){WINDOW$1.document?WINDOW$1.document.addEventListener("visibilitychange",()=>{const t=getActiveSpan();if(!t)return;const e=getRootSpan(t);if(WINDOW$1.document.hidden&&e){const t="cancelled",{op:n,status:r}=spanToJSON(e);DEBUG_BUILD&&debug.log(`[Tracing] Transaction: ${t} -> since tab moved to the background, op: ${n}`),r||e.setStatus({code:SPAN_STATUS_ERROR,message:t}),e.setAttribute("sentry.cancellation_reason","document.hidden"),e.end()}}):DEBUG_BUILD&&debug.warn("[Tracing] Could not set up background tab detection due to lack of global document")}const PREVIOUS_TRACE_MAX_DURATION=3600,PREVIOUS_TRACE_KEY="sentry_previous_trace",PREVIOUS_TRACE_TMP_SPAN_ATTRIBUTE="sentry.previous_trace";function linkTraces(t,{linkPreviousTrace:e,consistentTraceSampling:n}){const r="session-storage"===e;let i=r?getPreviousTraceFromSessionStorage():void 0;t.on("spanStart",t=>{if(getRootSpan(t)!==t)return;const e=getCurrentScope().getPropagationContext();i=addPreviousTraceSpanLink(i,t,e),r&&storePreviousTraceInSessionStorage(i)});let s=!0;n&&t.on("beforeSampling",t=>{if(!i)return;const e=getCurrentScope(),n=e.getPropagationContext();s&&n.parentSpanId?s=!1:(e.setPropagationContext({...n,dsc:{...n.dsc,sample_rate:String(i.sampleRate),sampled:String(spanContextSampled(i.spanContext))},sampleRand:i.sampleRand}),t.parentSampled=spanContextSampled(i.spanContext),t.parentSampleRate=i.sampleRate,t.spanAttributes={...t.spanAttributes,[SEMANTIC_ATTRIBUTE_SENTRY_PREVIOUS_TRACE_SAMPLE_RATE]:i.sampleRate})})}function addPreviousTraceSpanLink(t,e,n){const r=spanToJSON(e),i={spanContext:e.spanContext(),startTimestamp:r.start_timestamp,sampleRate:function(){try{const t=Number(r.data?.[SEMANTIC_ATTRIBUTE_SENTRY_SAMPLE_RATE]??n.dsc?.sample_rate);return Number.isNaN(t)?0:t}catch{return 0}}(),sampleRand:n.sampleRand};if(!t)return i;const s=t.spanContext;return s.traceId===r.trace_id?t:(Date.now()/1e3-t.startTimestamp<=PREVIOUS_TRACE_MAX_DURATION&&(DEBUG_BUILD&&debug.log(`Adding previous_trace \`${JSON.stringify(s)}\` link to span \`${JSON.stringify({op:r.op,...e.spanContext()})}\``),e.addLink({context:s,attributes:{[SEMANTIC_LINK_ATTRIBUTE_LINK_TYPE]:"previous_trace"}}),e.setAttribute(PREVIOUS_TRACE_TMP_SPAN_ATTRIBUTE,`${s.traceId}-${s.spanId}-${spanContextSampled(s)?1:0}`)),i)}function storePreviousTraceInSessionStorage(t){try{WINDOW$1.sessionStorage.setItem(PREVIOUS_TRACE_KEY,JSON.stringify(t))}catch(t){DEBUG_BUILD&&debug.warn("Could not store previous trace in sessionStorage",t)}}function getPreviousTraceFromSessionStorage(){try{const t=WINDOW$1.sessionStorage?.getItem(PREVIOUS_TRACE_KEY);return JSON.parse(t)}catch{return}}function spanContextSampled(t){return 1===t.traceFlags}const BROWSER_TRACING_INTEGRATION_ID="BrowserTracing",BOT_USER_AGENT_RE=/Googlebot|Google-InspectionTool|Storebot-Google|Bingbot|Slurp|DuckDuckBot|Baiduspider|YandexBot|Facebot|facebookexternalhit|LinkedInBot|Twitterbot|Applebot/i;function isBotUserAgent(){const t=WINDOW$1.navigator;return!!t?.userAgent&&BOT_USER_AGENT_RE.test(t.userAgent)}const DEFAULT_BROWSER_TRACING_OPTIONS={...TRACING_DEFAULTS,instrumentNavigation:!0,instrumentPageLoad:!0,markBackgroundSpan:!0,enableLongTask:!0,enableLongAnimationFrame:!0,enableInp:!0,ignoreResourceSpans:[],ignorePerformanceApiSpans:[],detectRedirects:!0,linkPreviousTrace:"in-memory",consistentTraceSampling:!1,enableReportPageLoaded:!1,_experiments:{},...defaultRequestInstrumentationOptions},browserTracingIntegration=(t={})=>{"enableElementTiming"in t&&consoleSandbox(()=>{console.warn("[Sentry] `enableElementTiming` is deprecated and no longer has any effect. Use the standalone `elementTimingIntegration` instead.")});const e={name:void 0,source:void 0},n=WINDOW$1.document,{enableInp:r,enableLongTask:i,enableLongAnimationFrame:s,_experiments:{enableInteractions:a,enableStandaloneClsSpans:o,enableStandaloneLcpSpans:l},beforeStartSpan:c,idleTimeout:d,finalTimeout:h,childSpanTimeout:u,markBackgroundSpan:p,traceFetch:f,traceXHR:m,trackFetchStreamPerformance:_,shouldCreateSpanForRequest:g,enableHTTPTimings:y,ignoreResourceSpans:S,ignorePerformanceApiSpans:A,instrumentPageLoad:v,instrumentNavigation:E,detectRedirects:b,linkPreviousTrace:T,consistentTraceSampling:w,enableReportPageLoaded:x,onRequestSpanStart:I,onRequestSpanEnd:R}={...DEFAULT_BROWSER_TRACING_OPTIONS,...t},C=isBotUserAgent();let B,D;function P(t,r,i=!0,s){const a="pageload"===r.op,o=r.name,l=c?c(r):r,p=parseStringToURLObject(s||getLocationHref()),f={...p?.pathname&&{[Vu]:p.pathname},...p&&!isURLObjectRelative(p)&&{[Yu]:p.href},...l.attributes};if(o!==l.name&&(f[SEMANTIC_ATTRIBUTE_SENTRY_SOURCE]="custom"),l.attributes=f,!i){const t=dateTimestampInSeconds();return void startInactiveSpan({...l,startTime:t}).end(t)}e.name=l.name,e.source=f[SEMANTIC_ATTRIBUTE_SENTRY_SOURCE];const m=startIdleSpan(l,{idleTimeout:d,finalTimeout:h,childSpanTimeout:u,disableAutoFinish:a,beforeSpanEnd:e=>{addPerformanceEntries(e,{ignoreResourceSpans:S,ignorePerformanceApiSpans:A,spanStreamingEnabled:hasSpanStreamingEnabled(t)}),setActiveIdleSpan(t,void 0);const n=getCurrentScope(),r=n.getPropagationContext();n.setPropagationContext({...r,traceId:m.spanContext().traceId,sampled:spanIsSampled(m),dsc:getDynamicSamplingContextFromSpan(e)}),a&&(D=void 0)},trimIdleSpanEndTimestamp:!x});function _(){n&&["interactive","complete"].includes(n.readyState)&&(t.emit("idleSpanEnableAutoFinish",m),n.removeEventListener("readystatechange",_))}a&&x&&(D=m),setActiveIdleSpan(t,m),a&&!x&&n&&(n.addEventListener("readystatechange",_),_())}return{name:BROWSER_TRACING_INTEGRATION_ID,setup(t){if(C)DEBUG_BUILD&&debug.log("[Tracing] Skipping browserTracingIntegration setup for bot user agent.");else{if(registerSpanErrorInstrumentation(),s&&GLOBAL_OBJ.PerformanceObserver&&PerformanceObserver.supportedEntryTypes?.includes("long-animation-frame")?startTrackingLongAnimationFrames():i&&startTrackingLongTasks(),a&&startTrackingInteractions(),b&&n){const t=()=>{B=timestampInSeconds()};addEventListener("click",t,{capture:!0}),addEventListener("keydown",t,{capture:!0,passive:!0})}t.on("startNavigationSpan",(n,r)=>{if(getClient()!==t)return;if(r?.isRedirect)return DEBUG_BUILD&&debug.warn("[Tracing] Detected redirect, navigation span will not be the root span, but a child span."),void P(t,{op:"navigation.redirect",...n},!1,r.url);B=void 0,e(),getIsolationScope().setPropagationContext({traceId:generateTraceId(),sampleRand:Math.random(),propagationSpanId:hasSpansEnabled()?void 0:generateSpanId()});const i=getCurrentScope();i.setPropagationContext({traceId:generateTraceId(),sampleRand:Math.random(),propagationSpanId:hasSpansEnabled()?void 0:generateSpanId()}),i.setSDKProcessingMetadata({normalizedRequest:void 0}),P(t,{op:"navigation",...n,parentSpan:null,forceTransaction:!0},!0,r?.url)}),t.on("startPageLoadSpan",(n,r={})=>{if(getClient()!==t)return;e();const i=propagationContextFromHeaders(r.sentryTrace||getMetaContent("sentry-trace")||getServerTiming("sentry-trace"),r.baggage||getMetaContent("baggage")||getServerTiming("baggage")),s=getCurrentScope();s.setPropagationContext(i),hasSpansEnabled()||(s.getPropagationContext().propagationSpanId=generateSpanId()),s.setSDKProcessingMetadata({normalizedRequest:getHttpRequestData()}),P(t,{op:"pageload",...n})}),t.on("endPageloadSpan",()=>{x&&D&&(D.setAttribute(SEMANTIC_ATTRIBUTE_SENTRY_IDLE_SPAN_FINISH_REASON,"reportPageLoaded"),D.end())})}function e(){const e=getActiveIdleSpan(t);e&&!spanToJSON(e).timestamp&&(DEBUG_BUILD&&debug.log(`[Tracing] Finishing current active span with op: ${spanToJSON(e).op}`),e.setAttribute(SEMANTIC_ATTRIBUTE_SENTRY_IDLE_SPAN_FINISH_REASON,"cancelled"),e.end())}},afterAllSetup(t){if(C)return;t.addIntegration&&!t.getIntegrationByName?.(WEB_VITALS_INTEGRATION_NAME)&&t.addIntegration(webVitalsIntegration({ignore:r?[]:["inp"],_experiments:{enableStandaloneClsSpans:o,enableStandaloneLcpSpans:l}}));let n=getLocationHref();if("off"!==T&&linkTraces(t,{linkPreviousTrace:T,consistentTraceSampling:w}),WINDOW$1.location){if(v){const e=browserPerformanceTimeOrigin();startBrowserTracingPageLoadSpan(t,{name:WINDOW$1.location.pathname,startTime:e?e/1e3:void 0,attributes:{[SEMANTIC_ATTRIBUTE_SENTRY_SOURCE]:"url",[SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN]:"auto.pageload.browser"}})}E&&addHistoryInstrumentationHandler(({to:e,from:r})=>{if(void 0===r&&-1!==n?.indexOf(e))return void(n=void 0);n=void 0;const i=parseStringToURLObject(e),s=getActiveIdleSpan(t),a=s&&b&&isRedirect(s,B);startBrowserTracingNavigationSpan(t,{name:i?.pathname||WINDOW$1.location.pathname,attributes:{[SEMANTIC_ATTRIBUTE_SENTRY_SOURCE]:"url",[SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN]:"auto.navigation.browser"}},{url:e,isRedirect:a})})}p&&registerBackgroundTabDetection(),a&&registerInteractionListener(t,d,h,u,e),instrumentOutgoingRequests(t,{traceFetch:f,traceXHR:m,tracePropagationTargets:t.getOptions().tracePropagationTargets,shouldCreateSpanForRequest:g,enableHTTPTimings:y,onRequestSpanStart:I,onRequestSpanEnd:R}),_&&t.addIntegration(fetchStreamPerformanceIntegration())}}};function startBrowserTracingPageLoadSpan(t,e,n){t.emit("startPageLoadSpan",e,n),getCurrentScope().setTransactionName(e.name);const r=getActiveIdleSpan(t);return r&&t.emit("afterStartPageLoadSpan",r),r}function startBrowserTracingNavigationSpan(t,e,n){const{url:r,isRedirect:i}=n||{};t.emit("beforeStartNavigationSpan",e,{isRedirect:i,url:r}),t.emit("startNavigationSpan",e,{isRedirect:i,url:r});const s=getCurrentScope();return s.setTransactionName(e.name),r&&!i&&s.setSDKProcessingMetadata({normalizedRequest:{...getHttpRequestData(),url:r}}),getActiveIdleSpan(t)}function getMetaContent(t){const e=WINDOW$1.document,n=e?.querySelector(`meta[name=${t}]`);return n?.getAttribute("content")||void 0}function getServerTiming(t){const e=WINDOW$1.performance?.getEntriesByType?.("navigation")[0],n=e?.serverTiming?.find(e=>e.name===t);return n?.description}function registerInteractionListener(t,e,n,r,i){let s;WINDOW$1.document&&addEventListener("click",()=>{const a="ui.action.click",o=getActiveIdleSpan(t);if(o){const t=spanToJSON(o).op;if(["navigation","pageload"].includes(t))return void(DEBUG_BUILD&&debug.warn(`[Tracing] Did not create ${a} span because a pageload or navigation span is in progress.`))}s&&(s.setAttribute(SEMANTIC_ATTRIBUTE_SENTRY_IDLE_SPAN_FINISH_REASON,"interactionInterrupted"),s.end(),s=void 0),i.name?s=startIdleSpan({name:i.name,op:a,attributes:{[SEMANTIC_ATTRIBUTE_SENTRY_SOURCE]:i.source||"url"}},{idleTimeout:e,finalTimeout:n,childSpanTimeout:r}):DEBUG_BUILD&&debug.warn(`[Tracing] Did not create ${a} transaction because _latestRouteName is missing.`)},{capture:!0})}const ACTIVE_IDLE_SPAN_PROPERTY="_sentry_idleSpan";function getActiveIdleSpan(t){return t[ACTIVE_IDLE_SPAN_PROPERTY]}function setActiveIdleSpan(t,e){addNonEnumerableProperty(t,ACTIVE_IDLE_SPAN_PROPERTY,e)}const REDIRECT_THRESHOLD=1.5;function isRedirect(t,e){const n=spanToJSON(t),r=dateTimestampInSeconds();return!(r-n.start_timestamp>REDIRECT_THRESHOLD||e&&r-e<=REDIRECT_THRESHOLD)}const NOISE_ERROR_CODES=["3205","3206","3305","30005"];class SentryReporter{constructor(t,e={}){var n;this.tracesSampleRate=null!=(n=e.tracesSampleRate)?n:1;const r=getDefaultIntegrations().filter(t=>!["BrowserApiErrors","BrowserSession","Breadcrumbs","GlobalHandlers","FunctionToString","Dedupe"].includes(t.name));r.push(browserTracingIntegration({instrumentPageLoad:!1,instrumentNavigation:!1,traceFetch:!1,traceXHR:!1})),this.client=new BrowserClient({dsn:t,transport:makeFetchTransport,stackParser:defaultStackParser,integrations:r,release:"xmov-avatar@2.4.0-alpha.4",tracesSampleRate:this.tracesSampleRate,beforeSend(t){var e,n,r,i,s;if("xmov-avatar-sdk"!==(null==(e=t.tags)?void 0:e.source))return null;const a=String(null!=(n=null==(r=t.tags)?void 0:r.error_code)?n:"");return NOISE_ERROR_CODES.includes(a)?null:(t.fingerprint=[a||"unknown",String(null!=(i=t.message)?i:"").slice(0,64)],t.contexts=_extends({},null!=(s=t.contexts)?s:{},{browser:{name:navigator.userAgent.slice(0,200)}}),t)}}),this.scope=new Scope,this.scope.setClient(this.client),this.scope.setTag("sdk_version","2.4.0-alpha.4"),this.scope.setTag("source","xmov-avatar-sdk"),this.client.init()}captureError(t){this.scope.setTag("error_code",String(t.error_code)),this.scope.setTag("error_name",t.error_name),this.scope.setTag("session_id",t.session_id),this.scope.setExtra("code",t.code),this.scope.setExtra("client_speak_id",t.client_speak_id),this.scope.setExtra("timestamp",t.timestamp),t.originalError&&this.scope.setExtra("originalError",t.originalError),this.scope.captureException(new Error(t.message))}startSpan(t,e,n){return startSpan({name:t,op:e.op,scope:this.scope,attributes:e.data},()=>n())}startInactiveSpan(t,e){const n=startInactiveSpan({name:t,op:e.op,scope:this.scope,attributes:e.data});return{end:()=>null==n?void 0:n.end()}}setTag(t,e){this.scope.setTag(t,e)}setUser(t){this.scope.setUser(t)}async destroy(){await this.client.close(2e3)}}let isLoggingEnabled=!1;function executeLog(t,...e){isLoggingEnabled&&"function"==typeof t&&t(...e)}const sdkLog={log:(...t)=>executeLog(console.log,...t),info:(...t)=>executeLog(console.info,...t),warn:(...t)=>executeLog(console.warn,...t),error:(...t)=>executeLog(console.error,...t)};function setLoggingEnabled(t){isLoggingEnabled=t,t?console.log("[AVATAR SDK] version:","2.4.0-alpha.4","日志已启用"):console.log("[AVATAR SDK] version:","2.4.0-alpha.4","日志已禁用")}function sampleUniformTensor(t,e){return Float16Array===t.constructor||Float32Array===t.constructor||Float64Array===t.constructor?t[e]:Uint8Array===t.constructor?t[e]/255:Int8Array===t.constructor?(t[e]+128)/255*2-1:Uint16Array===t.constructor?t[e]/65535:Int16Array===t.constructor?(t[e]+32768)/65535*2-1:Uint32Array===t.constructor?t[e]/4294967295:Int32Array===t.constructor?(t[e]+2147483648)/4294967295*2-1:BigUint64Array===t.constructor?Number(t[e]>>32n)/4294967295:BigInt64Array===t.constructor?(Number(t[e]>>32n)+2147483648)/4294967295*2-1:0}function sampleUniformPCATensor(t,e){return Float16Array===t.constructor||Float32Array===t.constructor||Float64Array===t.constructor?t[e]:Uint8Array===t.constructor?t[e]/255*2-1:Int8Array===t.constructor?(t[e]+128)/255*2-1:Uint16Array===t.constructor?t[e]/65535*2-1:Int16Array===t.constructor?(t[e]+32768)/65535*2-1:Uint32Array===t.constructor?t[e]/4294967295*2-1:Int32Array===t.constructor?(t[e]+2147483648)/4294967295*2-1:BigUint64Array===t.constructor?Number(t[e]>>32n)/4294967295*2-1:BigInt64Array===t.constructor?(Number(t[e]>>32n)+2147483648)/4294967295*2-1:0}function getVertices(t,e){let n=t.char,r=n.evalSkeleton(),i=n.evalSkeletonFromMovable(e.movableJointTransforms),s=Array(n.skeleton.length);for(let t=0;t<n.skeleton.length;t++){const e=i[t].apply(r[t].inv());s[t]=e.homogeneous_matrix()}let a=[];for(let t=0;t<n.mesh.length;t++){let r=[];for(let i=0;i<n.mesh[t].blendshapes.size[0];i++){let a=[],o=n.mesh[t].vertices,l=n.mesh[t].blendshapes,c=e.blendshapeWeights;for(let t=0;t<3;t++)a.push(o.data[i*o.size[1]+t]);for(let e=0;e<n.mesh[t].blendshapeIndices.length;e++)for(let r=0;r<3;r++)a[r]+=c[n.mesh[t].blendshapeIndices[e]]*Number(l.data[(i*l.size[1]+r)*l.size[2]+e]);a.push(1);let d=[0,0,0,0],h=n.mesh[t].jointIndex,u=n.mesh[t].jointWeight;for(let t=0;t<n.maxJointsPerVertex;t++){let e=h[i*n.maxJointsPerVertex+t];if(e<n.skeleton.length){let r=mvmul(s[e],a);for(let e=0;e<4;e++)d[e]+=u[i*n.maxJointsPerVertex+t]*r[e]}}for(let t=0;t<3;t++)d[t]/=d[3];r.push([d[0],d[1],d[2]])}a.push(r)}return a}function getPCATextures(t,e){let n=t.char,r=[];for(let t=0;t<n.mesh.length;t++){let i=n.mesh[t].textureModels[e.mesh[t].textureModelIndex],s=[],a=new Uint8ClampedArray(i.data.size[1]*i.data.size[2]*4),o=1;i.scalingFactor&&(o*=Number(i.scalingFactor.data[0]));for(let t=0;t<i.data.size[1];t++){let e=[];for(let n=0;n<i.data.size[2];n++){let r=[];for(let e=0;e<3;e++)r.push(o*sampleUniformPCATensor(i.data.data,3*(t*i.data.size[2]+n)+e));e.push(r)}s.push(e)}for(let n=1;n<i.data.size[0];n++){let r=e.mesh[t].texturePCAWeights[n-1];i.scalingFactor&&(r*=Number(i.scalingFactor.data[n]));for(let t=0;t<i.data.size[1];t++)for(let e=0;e<i.data.size[2];e++)for(let a=0;a<3;a++)s[t][e][a]+=r*sampleUniformPCATensor(i.data.data,3*((n*i.data.size[1]+t)*i.data.size[2]+e)+a)}for(let t=0;t<i.data.size[1];t++)for(let e=0;e<i.data.size[2];e++){for(let n=0;n<3;n++)a[4*(t*i.data.size[2]+e)+n]=Math.round(255*s[i.data.size[1]-1-t][e][2-n]);a[4*(t*i.data.size[2]+e)+3]=255}r.push(new ImageData(a,i.data.size[1],i.data.size[2]))}return r}function exportAsWavefrontObj(t){let e="",n="",r=1,i=0;for(const s of t){for(const t of s.vertices)e+=`v ${t[0]} ${t[1]} ${t[2]}\n`;for(const t of s.uv)e+=`vt ${t[0]} ${t[1]}}\n`;n+=`g Obj${i}\n`;for(const t of s.polygons)n+=`f ${t.map(t=>(t+r).toString()).map(t=>`${t}/${t}`).join(" ")}\n`;r+=s.vertices.length,i+=1}return e+n}function getWavefrontObjFromVertices(t,e){function n(t,e){let n=[];for(let r=0;r<t.length;r++)0==r%e&&n.push([]),n[n.length-1].push(sampleUniformTensor(t,r));return n}function r(t,e){let n=[];for(let r=0;r<t.length;r++)0==r%e&&n.push([]),n[n.length-1].push(Number(t[r]));return n}let i=t.char,s=[];for(let t=0;t<i.mesh.length;t++)s.push({vertices:e[t],uv:n(i.mesh[t].UVCoord.data,2),polygons:r(i.mesh[t].triangles.data,3)});return exportAsWavefrontObj(s)}window.avatarSDKLogger=_extends({},sdkLog,{setEnabled:setLoggingEnabled});class StreamingClient{constructor(t){this.ws=null,this.retryCount=0,this.maxRetry=27,this.retryTimer=-1,this.destroyed=!1,this.connected=!1,this.options=t}connect(){if(!this.destroyed){try{this.ws=new WebSocket(this.options.url)}catch(t){return console.error("[StreamingClient] 创建 WebSocket 失败:",t),void this.scheduleRetry()}this.ws.onopen=()=>{this.connected=!0,this.retryCount=0,console.log("[StreamingClient] 已连接"),this.send({type:"join",role:"client"})},this.ws.onmessage=t=>{let e;try{e=JSON.parse(t.data)}catch(t){return}this.handleMessage(e)},this.ws.onclose=()=>{var t,e;this.connected=!1,this.destroyed||(null==(t=(e=this.options).onDisconnect)||t.call(e),this.scheduleRetry())},this.ws.onerror=()=>{var t,e;null==(t=(e=this.options).onError)||t.call(e,"WebSocket 连接错误")}}}handleMessage(t){var e,n,r,i,s,a,o,l,c,d;switch(t.type){case"ready":null==(e=(n=this.options).onReady)||e.call(n);break;case"offer":null==(r=(i=this.options).onOffer)||r.call(i,t.sdp);break;case"answer":break;case"ice":null==(s=(a=this.options).onIce)||s.call(a,t.candidate);break;case"event_proxy":null==(o=(l=this.options).onEventProxy)||o.call(l,t.event_type,t.data,t.server_frame);break;case"error":null==(c=(d=this.options).onError)||c.call(d,t.message||"未知错误")}}send(t){this.ws&&this.ws.readyState===WebSocket.OPEN&&this.ws.send(JSON.stringify(t))}sendApiCall(t,e=[]){this.send({type:"api_call",method:t,params:e})}scheduleRetry(){if(this.destroyed)return;var t,e;if(this.retryCount>=this.maxRetry)return console.warn("[StreamingClient] 重试次数已达上限"),void(null==(t=(e=this.options).onError)||t.call(e,"连接重试次数已达上限"));const n=0===this.retryCount?1e3:1e3*Math.pow(2,Math.min(this.retryCount,6));this.retryCount++,this.retryTimer=window.setTimeout(()=>{this.connect()},n)}isConnected(){return this.connected}destroy(){this.destroyed=!0,-1!==this.retryTimer&&(clearTimeout(this.retryTimer),this.retryTimer=-1),this.ws&&(this.ws.close(),this.ws=null),this.connected=!1}}class VideoPlayer{constructor(t){this.video=null,this.canvas=null,this.canvasCtx=null,this.pc=null,this.stream=null,this.destroyed=!1,this.animFrameId=0,this.tempCanvas=null,this.tempCtx=null,this.options=t,t.useAlphaMask?this.createCanvasElement():this.createVideoElement()}createVideoElement(){const t=document.createElement("video");t.autoplay=!0,t.playsInline=!0,t.muted=!0,t.style.width="100%",t.style.height="100%",t.style.objectFit="contain",t.style.background="transparent",this.video=t,this.options.container.appendChild(t)}createCanvasElement(){const t=document.createElement("canvas");t.style.width="100%",t.style.height="100%",t.style.objectFit="contain",t.style.background="transparent",this.canvas=t,this.canvasCtx=t.getContext("2d",{willReadFrequently:!0}),this.tempCanvas=document.createElement("canvas"),this.tempCtx=this.tempCanvas.getContext("2d",{willReadFrequently:!0}),this.options.container.appendChild(t);const e=document.createElement("video");e.autoplay=!0,e.playsInline=!0,e.muted=!0,e.style.position="absolute",e.style.width="1px",e.style.height="1px",e.style.opacity="0",e.style.pointerEvents="none",e.style.zIndex="-1",this.video=e,this.options.container.appendChild(e)}async handleOffer(t){this.destroyPeer(),this.pc=new RTCPeerConnection({iceServers:[{urls:"stun:stun.l.google.com:19302"},{urls:"stun:stun1.l.google.com:19302"},{urls:"turn:openrelay.metered.ca:80",username:"openrelayproject",credential:"openrelayproject"},{urls:"turn:openrelay.metered.ca:443",username:"openrelayproject",credential:"openrelayproject"},{urls:"turns:openrelay.metered.ca:443",username:"openrelayproject",credential:"openrelayproject"}]}),this.pc.onicecandidate=t=>{t.candidate&&this.options.streamingClient.send({type:"ice",candidate:t.candidate.toJSON()})},this.pc.ontrack=t=>{console.log("[VideoPlayer] 收到轨道:",t.track.kind,t.track.id),this.stream||(this.stream=new MediaStream,this.video&&(this.video.srcObject=this.stream)),this.stream.addTrack(t.track),"audio"===t.track.kind&&this.video&&(this.video.muted=!1,this.video.play().catch(()=>{})),"video"===t.track.kind&&this.options.useAlphaMask&&(console.log("[VideoPlayer] Alpha Mask 模式:启动 canvas 渲染循环"),this.startAlphaRendering())},this.pc.onconnectionstatechange=()=>{var t,e;if(this.pc)if(console.log("[VideoPlayer] WebRTC 状态:",this.pc.connectionState),"connected"===this.pc.connectionState)null==(t=(e=this.options).onConnected)||t.call(e);else if("disconnected"===this.pc.connectionState||"failed"===this.pc.connectionState){var n,r;null==(n=(r=this.options).onDisconnected)||n.call(r)}},await this.pc.setRemoteDescription(new RTCSessionDescription({type:"offer",sdp:t}));const e=await this.pc.createAnswer();await this.pc.setLocalDescription(e),this.options.streamingClient.send({type:"answer",sdp:e.sdp})}startAlphaRendering(){if(!(this.video&&this.canvas&&this.canvasCtx&&this.tempCanvas&&this.tempCtx))return;const t=this.video,e=this.canvas,n=this.canvasCtx,r=this.tempCanvas,i=this.tempCtx;let s=0,a=0,o=0,l=null;l=setInterval(()=>{this.destroyed?l&&clearInterval(l):console.log(`[VideoPlayer] Alpha 渲染调试: frames=${o}, videoReadyState=${t.readyState}, videoSize=${t.videoWidth}x${t.videoHeight}, currentTime=${t.currentTime.toFixed(2)}s, paused=${t.paused}`)},2e3);const c=()=>{if(this.destroyed)l&&clearInterval(l);else{if(t.readyState>=2&&t.videoWidth>0){const l=t.videoWidth,c=t.videoHeight,d=l/2,h=c;l===s&&c===a||(e.width=d,e.height=h,r.width=l,r.height=h,s=l,a=c,console.log(`[VideoPlayer] Alpha Mask: 检测到双流 ${l}x${c} → 原始 ${d}x${h}`)),i.clearRect(0,0,2*d,h),i.drawImage(t,0,0),n.clearRect(0,0,d,h),n.drawImage(r,0,0,d,h,0,0,d,h);try{const t=n.getImageData(0,0,d,h),e=i.getImageData(d,0,d,h),r=t.data,s=e.data;if(0===o){let t=0,e=0;const n=Math.min(1e3,r.length/4);for(let i=0;i<4*n;i+=4)(r[i]>0||r[i+1]>0||r[i+2]>0)&&t++,s[i]>0&&e++;console.log(`[VideoPlayer] 首帧像素检查: RGB非零=${t}/${n}, Alpha非零=${e}/${n}`),0===t&&console.warn("[VideoPlayer] 警告: RGB 全黑!视频可能没有内容")}for(let t=0;t<r.length;t+=4)r[t+3]=s[t];n.putImageData(t,0,0),o++}catch(e){console.warn("[VideoPlayer] Alpha 合成失败,降级为直接绘制:",e),n.drawImage(t,0,0,d,h,0,0,d,h),o++}}this.animFrameId=requestAnimationFrame(c)}};this.animFrameId=requestAnimationFrame(c)}async addIceCandidate(t){this.pc&&await this.pc.addIceCandidate(t).catch(t=>{console.warn("[VideoPlayer] addIceCandidate 失败:",t)})}getVideoElement(){return this.video}getCanvasElement(){return this.canvas}isConnected(){var t;return"connected"===(null==(t=this.pc)?void 0:t.connectionState)}destroyPeer(){this.pc&&(this.pc.close(),this.pc=null),this.stream=null,this.animFrameId&&(cancelAnimationFrame(this.animFrameId),this.animFrameId=0)}destroy(){this.destroyed=!0,this.destroyPeer(),this.video&&this.video.parentNode&&this.video.parentNode.removeChild(this.video),this.canvas&&this.canvas.parentNode&&this.canvas.parentNode.removeChild(this.canvas),this.video=null,this.canvas=null,this.canvasCtx=null,this.tempCanvas=null,this.tempCtx=null}}class EventDispatcher{constructor(t){this.subtitleText="",this.subtitleVisible=!1,this.callbacks=t}dispatch(t,e,n){var r,i,s,a,o,l,c,d,h,u,p,f,m,_,g,y,S,A,v,E,b,T,w,x,I,R;switch(t){case"state_change":null==(r=(i=this.callbacks).onStateChange)||r.call(i,e.state||e);break;case"speak_state_change":null==(s=(a=this.callbacks).onSpeakStateChange)||s.call(a,e.state,e.client_speak_id);break;case"voice_state_change":null==(o=(l=this.callbacks).onVoiceStateChange)||o.call(l,e.state,e.duration,e.client_speak_id||"");break;case"status_change":null==(c=(d=this.callbacks).onStatusChange)||c.call(d,e.status);break;case"render_change":null==(h=(u=this.callbacks).onRenderChange)||h.call(u,e.state);break;case"walk_state_change":null==(p=(f=this.callbacks).onWalkStateChange)||p.call(f,e.state||e);break;case"widget_event":null==(m=(_=this.callbacks).onWidgetEvent)||m.call(_,e);break;case"message":case"error":null==(g=(y=this.callbacks).onMessage)||g.call(y,e);break;case"network_info":null==(S=(A=this.callbacks).onNetworkInfo)||S.call(A,e);break;case"fps_update":null==(v=(E=this.callbacks).onFPSUpdate)||v.call(E,e);break;case"download_progress":null==(b=(T=this.callbacks).onDownloadProgress)||b.call(T,e.progress);break;case"session_id":null==(w=(x=this.callbacks).onSessionId)||w.call(x,e.session_id);break;case"frame_data_update":null==(I=(R=this.callbacks).onFrameDataUpdate)||I.call(R,e);break;default:console.log("[EventDispatcher] 未处理的事件类型:",t,e)}}getSubtitleText(){return this.subtitleText}isSubtitleVisible(){return this.subtitleVisible}}class APIForwarder{constructor(t){this.client=t}speak(t,e=!0,n=!0,r={}){this.client.sendApiCall("speak",[t,e,n,r])}idle(){this.client.sendApiCall("idle",[])}listen(){this.client.sendApiCall("listen",[])}think(){this.client.sendApiCall("think",[])}interactiveidle(){this.client.sendApiCall("interactiveidle",[])}interrupt(t){this.client.sendApiCall("interrupt",[t])}changeLayout(t){this.client.sendApiCall("changeLayout",[t])}changeWalkConfig(t){this.client.sendApiCall("changeWalkConfig",[t])}setVolume(t){this.client.sendApiCall("setVolume",[t])}changeAvatarVisible(t){this.client.sendApiCall("changeAvatarVisible",[t])}switchInvisibleMode(){this.client.sendApiCall("switchInvisibleMode",[])}destroy(t="user"){this.client.sendApiCall("destroy",[t])}init(t){this.client.send({type:"init",config:t})}}const VIDEO_PROBE_BASE64=["AAAAIGZ0eXBpc29tAAACAGlzb21pc28yYXZjMW1wNDEAAAO5bW9vdgAAAGxtdmhkAAAAAAAAAAAAAAAAAAAD6AAAAaEAAQAAAQAAAAAAAAAAAAAAAAEAAAAAAAAAAAAAAAAAAAABAAAAAAAAAAAAAAAAAABAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAgAA","AuR0cmFrAAAAXHRraGQAAAADAAAAAAAAAAAAAAABAAAAAAAAAaEAAAAAAAAAAAAAAAAAAAAAAAEAAAAAAAAAAAAAAAAAAAABAAAAAAAAAAAAAAAAAABAAAAACHAAAAeAAAAAAAAkZWR0cwAAABxlbHN0AAAAAAAAAAEAAAGhAAAEAAABAAAAAAJcbWRpYQAAACBtZGhk","AAAAAAAAAAAAAAAAAAAwAAAAFABVxAAAAAAALWhkbHIAAAAAAAAAAHZpZGUAAAAAAAAAAAAAAABWaWRlb0hhbmRsZXIAAAACB21pbmYAAAAUdm1oZAAAAAEAAAAAAAAAAAAAACRkaW5mAAAAHGRyZWYAAAAAAAAAAQAAAAx1cmwgAAAAAQAAAcdzdGJsAAAAx3N0c2QA","AAAAAAAAAQAAALdhdmMxAAAAAAAAAAEAAAAAAAAAAAAAAAAAAAAACHAHgABIAAAASAAAAAAAAAABFUxhdmM2Mi4xMS4xMDAgbGlieDI2NAAAAAAAAAAAAAAAGP//AAAAOmF2Y0MBZAAy/+EAHWdkADKs2YAhwPGmoCAgKAAAAwAIAAADAYB4wYzQAQAGaOl4GXLA/fj4","AAAAABNjb2xybmNseAABAAEAAQAAAAAUYnRydAAAAAAAAsOgAAAAAAAAABhzdHRzAAAAAAAAAAEAAAAKAAACAAAAABRzdHNzAAAAAAAAAAEAAAABAAAAYGN0dHMAAAAAAAAACgAAAAEAAAQAAAAAAQAACgAAAAABAAAEAAAAAAEAAAAAAAAAAQAAAgAAAAABAAAKAAAA","AAEAAAQAAAAAAQAAAAAAAAABAAACAAAAAAEAAAQAAAAAHHN0c2MAAAAAAAAAAQAAAAEAAAAKAAAAAQAAADxzdHN6AAAAAAAAAAAAAAAKAAAdhgAAAMQAAACAAAAAfAAAAHwAAAJ1AAAAkAAAAH8AAAB/AAABFgAAABRzdGNvAAAAAAAAAAEAAAPpAAAAYXVkdGEAAABZ","bWV0YQAAAAAAAAAhaGRscgAAAAAAAAAAbWRpcmFwcGwAAAAAAAAAAAAAAAAsaWxzdAAAACSpdG9vAAAAHGRhdGEAAAABAAAAAExhdmY2Mi4zLjEwMAAAAAhmcmVlAAAk421kYXQAAAKuBgX//6rcRem95tlIt5Ys2CDZI+7veDI2NCAtIGNvcmUgMTY1IHIzMjIzIDA0","ODBjYjAgLSBILjI2NC9NUEVHLTQgQVZDIGNvZGVjIC0gQ29weWxlZnQgMjAwMy0yMDI1IC0gaHR0cDovL3d3dy52aWRlb2xhbi5vcmcveDI2NC5odG1sIC0gb3B0aW9uczogY2FiYWM9MSByZWY9NSBkZWJsb2NrPTE6MDowIGFuYWx5c2U9MHgzOjB4MTEzIG1lPWhl","eCBzdWJtZT0yIHBzeT0xIHBzeV9yZD0xLjAwOjAuMDAgbWl4ZWRfcmVmPTAgbWVfcmFuZ2U9MTYgY2hyb21hX21lPTEgdHJlbGxpcz0wIDh4OGRjdD0xIGNxbT0wIGRlYWR6b25lPTIxLDExIGZhc3RfcHNraXA9MSBjaHJvbWFfcXBfb2Zmc2V0PTAgdGhyZWFkcz0y","NCBsb29rYWhlYWRfdGhyZWFkcz04IHNsaWNlZF90aHJlYWRzPTAgbnI9MCBkZWNpbWF0ZT0xIGludGVybGFjZWQ9MCBibHVyYXlfY29tcGF0PTAgY29uc3RyYWluZWRfaW50cmE9MCBiZnJhbWVzPTMgYl9weXJhbWlkPTIgYl9hZGFwdD0xIGJfYmlhcz0wIGRpcmVj","dD0xIHdlaWdodGI9MSBvcGVuX2dvcD0wIHdlaWdodHA9MSBrZXlpbnQ9MjUwIGtleWludF9taW49MjQgc2NlbmVjdXQ9NDAgaW50cmFfcmVmcmVzaD0wIHJjX2xvb2thaGVhZD0xMCByYz1jcmYgbWJ0cmVlPTEgY3JmPTUxLjAgcWNvbXA9MC42MCBxcG1pbj0wIHFw","bWF4PTY5IHFwc3RlcD00IGlwX3JhdGlvPTEuNDAgYXE9MToxLjAwAIAAABrQZYiEACP/HVX/9Jx4AAADAAADAAADAAADAAKaAAADAAADABxIAAADAAADAgYAAAMAAAMAQbAAAAMAAApAAAADAAADAAADAAADAAADAAADAAADAAADAAADAAADAAADAAADAAADAAADAAAD","AAADAAADAAADAAADAAADAAADAAADAAADAAADAAADAAADAAADAAADAAADAABkEOXuPain0AAAAwADGOAAAnCVwB1gdgBRBxsFDAAJAA7Qgk1QAGJjj41H24u2v8L16bzd9WExiOcxt+AAACJuiPKnTkt78W9x4i/HpVtT4CHi0/B5P9UbeT6Ch3AAACy1IAfB6jJ4OCUy","vWkkgY/9Pd3lpe+hgFs/QHKAAEBUWPNT0PT7mqhPbBxPneArf6l9nliw3C1hP9VHPSLIkpWKAAADAAADAUuWqxALGzu0x4wENnFvB3t7P2SgAABEs/f207h8TR9hmOTgJwdWW3G3KatCQ9OKr2AABFeZoAPm9/U2M1dgVHD1FF2ZLwAABT2bNKSNBIFgw6sgqSj/POdR","GDLAS5cGEmvjIJofyPoAAq9DaiAFmRSe+IV0AYKa53ZjdWLpKjHPAAB77BxY3rbtRM+3PspjmQptJfGNMlT5zAAAdHQBg3JsUaqvPYJjTvAl2UNE+AzZnI0FchAACc462IcigQCR4n588pQvKSyxIjKmhgAAKScBMTqA/vaR9AmI960pgXsjMif0im3QQrZb4AFgkekG","SL7sXSNGpOX5i1s4AAADAPM4J9FjROm3ojTv93j45exr6P8McNiE2Wub48FOuj7PGGgABJ4Q5/vSjqKp7T8hQkUXxuF92M6AAABkQW/6EYT4W8E2EYnseyzTyRluE+GWcO40gks7Qo85SAlsxccwlBSncvI23YphxaSPTpTcLSTHOFzs4FngqucCjc2du4fjHZjvdPkf","A8/AAB7vGWAal52iRxkJv1WI+T7QPgdfP4UKs2bODUQUllX267IAAAMAAoEgTp8hTTPkX48zokAEI1xzu5WWnq/pKO8HKfagrb1y87zfMgACbpL9k9/xEKKGwasRDhLRRFSAABe5bhCWksSXC6ybByEROkYfxaEjlnVUyj22ABMcKYAAAG9DIXUBzyBJBZ2cjvMBi82G","7fe8rg7eAH4o2QutgB8fibV9+M7KdqMG38MJjYOnvEqO9ZqQfAAAEZ9pF7o3U7yOB7TBzcTl0a4THE/9QDUfagFSToXQwgEbUaiBm+HHiwAAibulH4B2S/F0TwMzwGPT88gn0xPamCxaUbJ3a83C3R/de6UKzd/hNTtcETMsjyo0fIYfR0I/tDx5MmWq2JLXzetFB0Qi","8egJ/33RIth2bpx/yDbQAA0ju5HFEfgmJ2vXU7Nj7lVE7GE6qBDmpVl9sThGHyzfUHYACLuzUkdYpokOeiqsYOTBvPMhXUMJB9Lgw7LXLhkEGJH4QY5wcqAAAASAz8Kwvkv75GR3OQcG14zOFM6vLCxUc/FuGN+nNMxbiPOYyY6SO1gBEL4o6b+igz+6Zq52a9FINl+8","8KfM8Pe0gwHi4P9dBoCYlOoKJ6n6uikxM+5lf1mvgjgdnlpcrae74z0jZQ94TrV69I371UOoFqRktFHRTdAAEiv8jpMAzdPh39MKGoN4bOTndd5Hr/B9QAoob6svdC8wPElCer0m+QQmYADAlry3suadFguRKHNz4/nk/AuSezsZ5EntL4+pl8Qf5FusbKf+NAk7pv/6","tKuK/edu4XUAAGCGjjjNk7pwX7gpZ2j8Gblg3hW1G8NrGxod+kuAAAhF9/cab1rG0Gxsrwtay1k3AkPyz5eoA875OKffOBw2YlLAAL019ghZ3WXpUU8Irt70/6bXzgEYd3jOjhkaWECMaDN3wc+krxGXAsvAKNanKCvOCpGCMfby/A1x6CUZ1jrLSKlakAAIZ4aCpLPI","BbM+XOQLVso7wFO+QAK2xqO27z8VW/8aN6tmK4XKq6qhch8mvLO99RH3VPrcDuHBJ/ikxOssjS8f/ZYHTTZDxY+NgSEp46AAAWKEpcPzJ+mf3WrElkVCPvDZ6oAAawUG1Wfa4+ftGkc299KaOkEdvWgRlAGrGUmQKuDCY9Df5u6bBfgABD28kDZRVXvPQQNTzCdMPwrA","rVQwmVD5v5/OPeaQd5rBupmDrMBk4f2YKIKMMmZUs9DgCmBp3ypejO22QkMREpQkwAAHJR+5LPkfHTjRtERikfI5KkAWVMKCDHm60OpYv0MO9kDHBSl0fIGR6FP6PZNQn1OTKSuxkwAOKIRcInPLYeAziAWlkQfG30Azl0tLvkY530imR/3zZLgL/auuI6xivm02jZw9","HMxagAkYY2r9sEcgAQkuAa5aV1IZtOasC6HNdAcn7yD1+sCag1aqOMBxb4ftI9GkrPIxBqO4QyatWXmnUIAAfAwMY3QLD9xOyNsH/gPKPb2GN4bb+HOGiyQ5IoUDN0XfLcQoN4ts5AB6wRwCufuaYBuf7KScvdThTABYsWmWg6MIoLhfOPWC0iDn2WqABmEjZgApOsdt","SxkbgN0L8wSjCYNWg0L3HQYYAASldcHRBvmS95//m6y6idyJ+EjGneRsKlPMVMnNyyEA2xJRFdIvCgAAVRV9xOHpKzbhiyEaxSLA7UErEeAFAD5QVYayP47Vmkpy0X10kaeZ/VL/PBimNL9i2GnlRDEFAE6gWLnXSkUdNEN+44++N3IKaHUWXOeR8KZ0IAsOKh2erntR","e1GiOBv7bb4GpXSUfYlEESDYG93j5dQb6DBRYGPjqUMZytBAdL68qPNG0/dMxNSSmUC0dAgGGARCiFyrdUjWLikujLzsUE+TqBbuZ54jlG4amIcPStPy1nw5AADT1Sjq/no95ZGjszXjhGNclUM1eJvLYAOQzfMjFXtDv3H5mkeiS5zE565LzH9dvjiLO+eBoVGtPznU","UAwtXP/UPxP3w/4+AEX4nQ5qH3uSjdhic71oXogEji69DwotyO/5/woZF3yonfFgBNlm0ueG9N3eCHDeW3N/d4Ru7NDA5KvqVbvZKmFG3j/lIw/gYKmm4RGMcR7LX1V08B+Pq4ACTGN1er7/wIoHogrDkQEIy8vvT7hEkOyedFGLAeiYdI1VtqVm4cevbmyCANQ4AAnu","64Nw5kUJ7ra/lmmA65WpsPXqaY6ejJ9qwqU67GUq2lekapQqRG7vUrd/VhSavytuZoG5EgAACuTCVlqr0YrjWWdChZnPCeAc6FnDdorJbsmI7qzuPrt4+AoAFMSIBwSg/NUC579QZNa5t1A6sOOU43E8peL6YodhifylgbhvTvzUFz+xJkk9hPAAAXpAoUIwuR991FMQ","LcBpxQt9EQbN8NYixYNO6kM6zAD5DU9vH2OiBU2CEMaWKKVgCgk7LyB6/4jiSqrSmMMkMzmtr2Ku8kearYX4wh2p5OYYAAKqhVI+NHKeeSnHE7kn7eSmfy5zByV+f5iXX/hTM0Yst5YcuTatzS65vxw/nTaVlFAk28lbUSYQGXXmQ9eC9OfKJpG9//fDdo8I8eWtLU71","tyvprE1iHazeOk0lrDJgAAAZwH2MkGICOKptWDE/t9pciEN+8GL8YZsfZK7cyUDkqp+vLljDCWrgEomORu1KREe9fY/hYki9ix/voLyyi7Zj6UOKCIxeHZggkTZqfx6UP1e2a23ZVXGAAACdDKGn4J1wlZVewql/WWeHbNApHXsa7dAx6C5WgAl4HjMpAAmlfJRyOevE","wVf0oZjpHxd5WM5P9m//by3bfphoZ6TXI0Vw33EU/HExV+qgx9YAABi5ERRDSeHcZkXPh9CvYfb7HvZ6wg/93XG7dDECTtYk661jUUhoGP1LY08KyNhSTwISSkLODdDD381QlKT2kvXOhMZsCprC8LBv3wDv1GMwg3ZwAAAFQSCh8jlPrXAJmDF4HIlxHUjuxkgkJdei","cS1iabx/xSAQophqjhEK/cW6L4Z7KrVSRuTOCTdm3GXnpH876L2ctr9+hn1L4cs5XfvlhMgAAFTc9PmKLeJhws4y+CZFHr770jYObO5szKiNaQtbYA2Z1ADVlT1gdh7KS/19fyfkhstiIFD3CXyJCFpGQeuC79i5/KSUienXQ3z1fTtVJCO1YrgAeSiCdg+rLLpHhkHn","g2gkRry8T91t87lHklCkPXl/JW7wwW3kxrjOk4GORcukFlg/wKtwF9TJZubscnmjUFt5L+UO3QRDw2+RQO2jcPtg7WJaexDb+bKLpsSuyAABLGxLzlBupAGJuyXq9RQGJ75yG/EcSzDCTNvaGS03qKa1F3VwDDKI6Alnqi9+0uAAYnGG+0E6UC+FniWah6s3tGi8Kyj1","wL50anznYbpIicpKEIh7VJud5231ZyVyTJKCCoEAAY5f2m7QxQd+o8NElsgg8F6kBtSRgeV/MSJYWF2o1SGTIfrHSNygAAeNupbd0vcywt0zMqSkiIDuAY9JybhMCw+rl9tfHAKQ63x9mEtywoKs3hh5gAO35wyIdXkD7JDV/CWKMSFwP9RpIGOkggSP+QgCVXh/Sedj","wJ9a9qAAr8ZmE10M2aHjjLyFJTQS7geuFHnj8ZD3wL6Yl24fH9f29qJQ9hNVhKyuaXggAAKqB9h791oBa8AxtsB8qjZgUFRjR49vt+eIcgBBozt7xwUCgUAAej+cp/reCIR1Fa19qFlgUM7UQGURldAASkIbfzAk6BpCg7G8zGjoPghwKnlWKWb3jHJWBrIcDWRj4Egl","CgCe2HwYZ4WC/TtaargTsEf8nvvHsg1h5cEIlJmMwItooRktPCo6uxcVQ2OG71PxbIAABFzJ6ld3r2sn59LfZcaSQNMQ/34p2A6uAbANgilIiv9zkZKvvd4R9DgAxiCPQXy4QTXjEkYwlIScuDlqZ264XR8XuA0kaYzvdrAN5zOqqTFyAGzJgAe0eKCdoddnZ0g0AAAn","69CDaOZ1ksreJ2QP0gciKe2w++YGDb5iBRWp+EVxaAcZ64PBbwUgLyNl7WeS2LnCDzd0EedwOJwrYRx7fZ3a1HZNbzBtLtBWKU4EwWAACcoouqPbYNFH61K4grSUGi86W/42NsCAXOayOJVWrjPbw0WAA9UQcR9iLFE5RJRzJ2CqSEcUsk+5pQv5LkWcIuB4oc+7mnwp","JV8F7ffg/NYgAIPB7jlSGtNVPqgGhnN0WmDqpAy5eQLCCPl0ZWMeTxwCtkSb82WAAkM+cDV59zTTSFLC0aVeSqi1qO+YvK/kNBYdFwFe8+KeTIQAXxXarEkWADMUy4yeN7IQJbibWnGtqm6B+mFIFKsgsGFdT7Te6aUK9UZFEb3Do53sAAQrEYcmmTBcvWbPbeX+96Gq","cRnlT/WeuezL/e8g0LTZbSy8VmYEVHtAADRYGcjVAsVDPfqpJX5pxPzcwGBsXyiVQe0JuBT+sMvCwQmWvXZuwBCbKurXo0sdUUexp7fNd5ZrTcojj2LkqgNhSrPrei6odRJS/jQAAD82aVmqD4/tEdFkbismt77uF58PCh3NhTKCBe6z9hbHdXLWpjoZFD83K6QHj5r2","1Iu3gSpAAAjvTvaSBaFzSmSjNRZK0x8WNuZF1hfS6rIfcx2l+g/LEsvAAACq/QPvNe1o9CasI+JZqYQxEIpXxoS78WIZaVNB+UTNo4CUC9pmmmIUoZ6ap8M8YlgroAQIME+AAAtunynbGeLJmZDHXRPJxAvv9HhdNoAKnAVpeLCA2PHpNk+istp+xjyIQiWhV5oATi4X","cnSyBXYX6I8O1aT4CfwAfugtyAGYvY4g2aVdzeCU7l/17AAEzdKoq0U74eT1mto+xMzrV5AG9wm8TbZxKOmzh2hO0YSYcFKQ+nRAjzePV8IABkfE4Eo/rnJ7Td5W/qs9ILfsinAL1MWXiOAXLBAyGBeETZ0hJWt/HtyWVUWAABs/g6q4lK1LJ0iIMLr0nA9i/AESH8XT","1+7jEcAdTNcWaScL8u37enZBAFSP9rKlRX2brKAAUuNwu+oiTJBASqVVAd1EpO1Aho5bgAW1n/xpQdTxFVU3ulFnT/wWXpYzqstiQztQABOXTaO9Eciin9J0YVSBrDckxjdby0NZrfqNegABSpQaSasAxfI1l3GJ/i5M0rJLPXRI74oTKakD6WbfMGDtSP5qzf9V7vFA","Y1UKDyC+NRPdd3S0b+rhf87dbAAASpMWkrjpajxSXuOsyCBgJ2kLhnA3Xa2G3Lue2AG3R4NgSTZRgCR5LTVLVqPyscnkwXDQkAEgASN6DP2R80rN0mvi8V/D1AcP1ePS4uAGTfHrwB9n9JjltiYLZP1yCk/7nVEkDmAd454g2M8xPscYU3py/HSetBe7X7evW9f+4gPC","9e4LUABZbrGzGcUvzotdb832Uzu0Q1xytj7nWJdY7L0KJOXVaABqUr2qG2th43i9OUECJy8ONoBpVmGa920C/AA7PH4am1DvXVvyLo3ix5/atW+FdwAAcbZ5/hxMAU+3cYwB1bY1vk6RZTQnLNzKHQABuiP1JbfOy9NFxdyEPqdjox9W5ktALJfcOcAQeEoXfmzs9N4+","TH+OLaIlr282zEGvoDBQaYcnuNYAAOyW/TstWHU5UyDs9raILV0FhjrAK+Rruqrjj2bTtFfTSyo0LUHsDm5HlKp4DXzG/9/1DRcNRAE1Wxl1dTa6HAAY5Yv4oeqf03tIH1GpXVlRgRBExnd7iADTLh3vVMU91xVYmhdy4xQFaki3Fk6Zdtbk38v8kdqAmOvGvS4wAAfW","0eXvxxYFDGF0WS2Riv6/JsKF0UnMq467S5y8rGczMwACIriauafKIwVTZ6Oi8f22uv5x5Tl3SE72Kl1xKAYTU+itbCIN8xTZhJdZf0rTuLo6uLkCpkrXNEknimnQI0m/wACfbJs6xneGaEmad7RjmA2AZ8DPVWY4o/6G3QAAAwHbyKgKPaSE3laBe86egCcCJvPj10LS","oaXfVzRnVUvBJn0N5AdqyK1gA7ecpdAXKzyhwd7azcXJQQQTADWJggTjPFT9wD7oIb8Xo0sGkrI9k6lSuDUKgB2KIVBMMwYecMD1JJ24JTmIVzuOjABjFLPS5JWrwpv4pnUlgXLtL25pDg8WAAL9QT+ba5hqXlx3qDzNw75ffP4hz94B9/3aJ7whvhjM6bv/mOziv//+","G1+aAkn0qZwAA2hGrpR9TYtSFPi+krphtyWMQAAE/z7Szty1w8wuX6f2mSjvC6Mip/MCG6HzzOTm9bSGzC3QvlwRtQMADZNhtMHuqfxNJ8lpEDdzKWNO8hRb/4nVRLYAAIeRcUP1Pza39r7snbxMRFAZAVp9KdqADiGw9MF1moq4Tns3lkf+3i1ddREGFLhfQT+asAAE","HbOaAmamxLHLfIxfAMhBqMvvmnziZAAlLyptJkG6v0KLbmMeiIs6rrpdjUGHTKgkzvRMG8NNZFJRp69d69mudUQd/GEQs4ADkNoKQOn3/9zt744FijS0Z17uz2guy7wABInf9ERhsdKQV0FJvkKNdMryzbKwK5mnakAtzNitRJa/9upagVo9HkuKQmHE54EZWLUBYGQA","BQPiMhOZOhtobNy7e/bJOP8J/mW54hWSzHKXAAIqIFI/VCYpAB75PRYWVewfLQtPXwvj+6UhuZQMcyDI5bS36a3ICOZnBWk9j8IJaUzljK2Dt3fAANsmr6YWnclVKK5o1j+nRLxGDpBAY2SZPtwXF+LpJ0oAABUlWPoxC2dpTVYSvFSTGXUAIAg6sHJOjLnrmAlxS1eP","xdcaOD4pC0R9lltDuOeQSQpZx7YAAAMBwhQoCki/3JMK+AVEtuCcIp0tVUI13CQJRGrxmK5eVgAB4T9fWchKHk+XEgUZkOu7ef9ZE8UVxM4nzmLuKUACaGgA5QVcGVq3EnoLKzFILaNa2hRJ8e72egAAEjT49Nl8bg7QItJWA3ylklVBlZiVqamCoQGVoQAAGwL6qbrm","ymv1mdN6UmoTtCYVYn1nWnWIB+gx9AAAAwJqXWE2NZnHtxHTxN6qmfvgsxV6X5V3lxVmFlJLKGsSfPvgAAGl4K/ak6NpVXN3TOg7kwdAS/pQ2+pYAAADAo6ZzhmltQYbFBR2k25g6N/e0bInvsVRWgoYGgZhK7wBcnn/aafImfm0l+3iI5hbJuRopkeJiMLRrgAAAwBo","hmqkVx0KNOb4qVZSHmEqDYpI3H6z0Zgrl9ykjXi9tdYgAAAakZWBUlk7QCaV8znUeVMXYmA4j6QAACXpbb5PxTbkpkFIVqz9XI9U+W2YEPLctPRsAXBgAAXO9wTAYAxi1E9joczpYplbAAAGgzTAFovrYu2XTtWfPay9f3ChgNpHTbqGF0W9eIcQqQEHgBBrJ3c1oxcy","ZHiZ99s37xMueRukd7AAABAP25WReHwv2YUOOkVSUEyG+Vi2lSQrQnFI8tAD/JAAAFZSGzDixx/k81yCC/p12uiQ5dqxcY3OcwXtN0a5gAABBxbZHPSZPMM25fBXNonhEF+H61l1fTv+zh/yeAUCaDE4MmM/U3KJWtQ+gsQTdI4TBgAAAwEEJxYz6NhkqZPBrEIYqXgi","Qgn82rqA4MAAAAmlw7m8NGqWGaa3rsfgRaGYS/Q022vRgyVSmfzH5wAVVDlwxUmJSW0KJ7LJlvYARyZZOi3gQjE363bsBYql2V/604y5QHkkyXbAfMLqIm3cr6J6gcvx9T2uf/cAAAMAAAMAoLTggjJCl6ZfP+GSCCLMESY06TFLs1Ocq9n/9HS9XjyUGrIjqiVcDTy7","+fVDMVrEtgKO/HfAAACSrLxGaaTGqL0vmQkOG3H/Ecu3y2Kd8CR+A37rOM2jO2L5rFsAAAMAAAMBODYHof2+xChTk2F1T95hlGsKrhfF5gFDiA+P0pYsFYhLhMxyIwACXcstK+FFdo3+4YJc/MaI0R43OfmAnbUc2dRX/dwAOYYui/tptTcafY8B10kjWBoAAAMA6hx8","/8pkpHguZnOIb/CGJuS5QBLTOMG0ZGMf9ZJPQDsogAGLVecrjuOxZ4zFBmzarqvTs5q0xDigunmUkBo3nuMFTXGR+cdVkM+M2AAAAwGLPwktiudEcFI6PSeBs8Z2kpvY277jVAAAAwH/uoOBn/n++0usA3Zxuc416ugy4NHoHm72rShRkuESu3aAAAADAAiuk9Q6FbVo","AAFl/pyEboOvAAAAwEGaJGxCPwAAAwAAAwAAAwAAAwAAAwAAC1V0Dm3MAAADAAGKVPoDdcEwImbhwAAIincfaIP5JBZqnQ035V7HU70SvyUQbDOaqwAFEGgTbHFrB4If711OAAADACs5nS7Q+a9yV7E4h0Ez1uBP3EfsAkhQH0/6NXQtgACBym+P6AAKGKRlAAGhLAPY","bXgwjYYLPdAAADZY0AH6akAAAAMAAAMAAAMAAAMAAAMAAL3zUpNAAA5q0b2AAAADAAADAABXwAAAAHxBnkJ4jf8AAAMAAAMAAAMAAAMAAAMAAAMAAAMAAAMAAAMAAAMAAAMAAAMAAAMAAAMAAAMAAAMAAAMAAAMAAAMAAAMAAAMAAAMAAAMAAAMAAAMAaH9F8l9fAAAD","AAADAAADAAADAAADAAADAAADAAADAAADAAADAAADABZRAAAAeAGeYXRF/wAAAwAAAwAAAwAAAwAAAwAAAwAAAwAAAwAAAwAAAwAAAwAAAwAAAwAAAwAAAwAAAwAAAwAAAwAAAwAAAwAAAwAAAwAAAwAAAwAAAwAAAwAAAwAAAwAAAwAAAwAAAwAAAwAAAwAAAwAAAwAA","AwAAAwDpgAAAAHgBnmNqRf8AAAMAAAMAAAMAAAMAAAMAAAMAAAMAAAMAAAMAAAMAAAMAAAMAAAMAAAMAAAMAAAMAAAMAAAMAAAMAAAMAAAMAAAMAAAMAAAMAAAMAAAMAAAMAAAMAAAMAAAMAAAMAAAMAAAMAAAMAAAMAAAMAAAMA6YEAAAJxQZpoXpaJgI3/AAADAAAD","AAADAAADAAADAEK7uW0HwlxaLod+8n9y2dE25CO0wjUkJGVbDJkwS8LCJUO7zdUKaJbTaq9M7+8ELtuVY1lZ/btIu3li6IjY+Ov66jvRBrqSFDjfbyhKleZR+9UlVZZpse5gdDl8MHUwwfzGYregw2423ZUw7Sn97g8RMf7SHQTXwRF7j/fkwGYUSkpmG9qWg1wS5TUK","VFk5M0SKYRgM8CySrhljPGdo9wvkw7uTbVjt2sKEXEIW8MI2esm0VrD+S7cJXtCVWSMO8IXxanrG5COpq6ZBzvfJ6ymDX6iDoAobTICelsgb2WAIHUtlm1f3rGKuyef0Yf94xekDEmlqqRdsZCYl/hAPZll1awBIKvHqkOOaNHoUQ62/emowbfJvP8fe2zjtdnDey1cs","pjpqOFSbjASkUO83ddc9652op2XltZTWa56Wr2cwUBxIx4W+ad6vdIGrwb1hZS1r65BGAzj+/F6uKOyG4RGC0lLE3NetVXhrogaPBoQwSdt89QFY3qGVAIgFqvucRcWLey4lhk557q2MjSz9jcPjGiw9PzwRTa30dLDkktwSEI/ZwQCZfi/acZFD8yunv14AYtypuBoY","vVceexnkeMEiRBFm0DIKp82mnZe1zehd/WlQSVJSqovoFvqZHgb07LtiLneXBF53QZEMxH0jfBCj/H90s/rz1CVEvjKAc/kdkjmmhr3ASGRcfBtqVn44UEkIzM/fO6Chqxv7ZW+Ig1jla7pjCRmOE12qPIXGW74zBcIRSpdqo+3cseFFrvQFFcPwAAADAAADAAADAAAD","AAADAAADAAAl4QAAAIxBnoZuUTG/AAADAAADAAADAAADAAADAAAdTB+gAAADAAAGx/ThJHkg+TwAAAMAAAMAAAMABuNmEeAGAA4H75AAwkuAAAAHMY3sAtntw3YegAAAAwAAAwAAAwBbO3gyAzAAAAMAAAMAAAMAAAMAAAMAAAMAAAMAAAMAAAMAAAMAAAMAAAMAAAMA","AAMCTwAAAHsBnqVpEX8AAAMAAAMAAAMAAAMAAAMAAAMAAAMAAAMAAAMAAAMAAAMAAAMAAAMAAAMAAAMAAAMAAAMAAhyDSQqCJgAAAwAAAwAAAwAAAwAAAwAAAwAAAwAAAwAAAwAAAwAAAwAAAwAAAwAAAwAAAwAAAwAAAwAAAwAAD/EAAAB7AZ6nbkX/AAADAAADAAAD","AAADAAADAAADAAADAAADAAADAAADAAADAAADAAADAAADAAADAAADAAADAEO2/cAPCTpcAAADAAADAAADAAADAAADAAADAAADAAADAAADAAADAAADAAADAAADAAADAAADAAADAAADAAADAAG9AAABEkGaqUmltSYAi/8AAAMAAAMAAAMAAAMAAAMAU1eb25GTW/axz5g6","EYyReAAAK0G/1DwhHeAA5o1vLjsc2UIAFfG3Z3xdmYOiZZV+6V+frSCRE4N7MdfTkM8mKNUaQ7EmcIWLwnNbMLbV6AFLHIFO35ifNoCOrdZoAB1drW6Gb1R/Z/IBXyR0svRZbRI3eud6M2QYuh05mAR8pwtlg09krtIl6gBwCymZNCRhJGaUUWgQYKTJ0LXNGiHgHsdp","vA4X3aZpTFo2nCabF49whgE0JXAAAAMAAAMAAB490CVcyvQos44EACAVEU28wX7/HBFRAAeQWxupPrMDRdBQAVFFMctkYAAAAwAAAwAAAwAAAwAABBw="].join("");function isAndroidPlatform(){const t=(navigator.userAgent||"").toLowerCase();return/android/.test(t)||/openharmony|arkweb/.test(t)}function checkSecureContextSync(){const t=window.isSecureContext;return{name:"secureContext",supported:t,severity:"fatal",reason:t?void 0:"当前环境不是安全上下文,请使用 HTTPS 或 localhost"}}function checkWebGL2Sync(){try{const t=document.createElement("canvas").getContext("webgl2",{failIfMajorPerformanceCaveat:!0});if(!t)return{name:"webgl2",supported:!1,severity:"fatal",reason:"浏览器不支持 WebGL2"};const e=t.getExtension("WEBGL_debug_renderer_info");return{name:"webgl2",supported:!0,severity:"fatal",detail:{version:t.getParameter(t.VERSION),vendor:t.getParameter(t.VENDOR),renderer:t.getParameter(t.RENDERER),gpuVendor:e?t.getParameter(e.UNMASKED_VENDOR_WEBGL):void 0,gpuRenderer:e?t.getParameter(e.UNMASKED_RENDERER_WEBGL):void 0}}}catch(t){return{name:"webgl2",supported:!1,severity:"fatal",reason:"WebGL2 初始化失败",detail:t}}}function checkAudioSystemSync(){const t=void 0!==window.AudioContext||void 0!==window.webkitAudioContext,e=void 0!==window.AudioWorkletNode,n=t&&e,r=void 0!==window.MediaSource,i={pcm:{supported:n,hasAudioContext:t,hasAudioWorklet:e},mse:{supported:r,hasMediaSource:r}};return n||r?{name:"audio",supported:!0,severity:"fatal",detail:i}:{name:"audio",supported:!1,severity:"fatal",reason:"音频播放能力不可用:PCM(AudioWorklet)和 MSE(MediaSource)均不支持",detail:i}}function checkWebCodecsSync(){const t=void 0!==window.VideoDecoder,e=isAndroidPlatform();return{name:"webcodecs",supported:t,severity:"fatal",reason:t?void 0:"浏览器不支持 WebCodecs VideoDecoder API",detail:{hasVideoDecoder:t,isAndroid:e,hardwareAcceleration:e?"prefer-software":"default"}}}function checkVideoDecodeSync(){const t=void 0!==window.VideoDecoder;return{name:"videoDecode",supported:t,severity:"fatal",reason:t?void 0:"浏览器不支持 WebCodecs VideoDecoder API"}}function checkWorkerSync(){const t="undefined"!=typeof Worker;return{name:"worker",supported:t,severity:"fatal",reason:t?void 0:"浏览器不支持 Web Worker"}}function checkCapabilitySync(t=!1){const e=[checkSecureContextSync()];t?(e.push(checkAudioSystemSync()),e.push(checkWorkerSync())):e.push(checkWebGL2Sync(),checkAudioSystemSync(),checkWebCodecsSync(),checkVideoDecodeSync(),checkWorkerSync());const n=e.filter(t=>"fatal"===t.severity&&!t.supported).length;return{supported:0===n,fatalCount:n,warnCount:e.filter(t=>"warn"===t.severity&&!t.supported).length,items:e}}async function checkWebCodecsDetailed(){try{const t=void 0!==window.VideoDecoder;if(!t)return{name:"webcodecs",supported:!1,severity:"warn",reason:"浏览器不支持 WebCodecs VideoDecoder API",detail:{hasVideoDecoder:t}};const e=isAndroidPlatform(),n=2160,r=1920;let i={};const s=["avc1.42E01E","avc1.4D001F","avc1.64001F"];let a=!1,o=!1,l=!1;for(const t of s)try{const s=await window.VideoDecoder.isConfigSupported({codec:t,codedWidth:n,codedHeight:r}),l=!(null==s||!s.supported);l&&(o=!0);let c=null;if(e){try{const e=await window.VideoDecoder.isConfigSupported({codec:t,codedWidth:n,codedHeight:r,hardwareAcceleration:"prefer-software"});c=!(null==e||!e.supported)}catch(t){c=!1}c&&(a=!0)}else l&&(a=!0);i[t]={default:l,software:c}}catch(e){l=!0,i[t]={default:!1,software:null,error:"probe-failed"}}const c=e?a:a||o;return{name:"webcodecs",supported:c,severity:"warn",reason:c?void 0:l?"WebCodecs 声明支持度探测异常(运行时将以实际视频配置二次确认)":e?"Android 不支持软解码(prefer-software 声明不可用)":"WebCodecs 声明不支持 H.264(默认/软解配置均不可用)",detail:{hasVideoDecoder:t,isAndroid:e,hardwareAcceleration:e?"prefer-software":"default",codecSupport:i}}}catch(t){return{name:"webcodecs",supported:!1,severity:"warn",reason:"WebCodecs 声明支持度探测失败",detail:t}}}const VIDEO_PROBE_TIMEOUT_MS=2e3,VIDEO_PROBE_MIN_FRAMES=2,VIDEO_PROBE_LAST_FRAME_INDEX=9;function base64ToArrayBuffer(t){const e=atob(t),n=new Uint8Array(e.length);for(let t=0;t<e.length;t+=1)n[t]=e.charCodeAt(t);return n.buffer}function probeVideoDecode(t,e){return new Promise(n=>{let r,i,s,a,o=null,l=!1,c=null,d=0;const h=Date.now(),u=()=>Date.now()-h,p=t=>{var e;l||(l=!0,null!==c&&clearTimeout(c),null==(e=o)||e.terminate(),n(_extends({},t,{primaryConfig:i})))};try{o=new Worker(t)}catch(t){return void p({supported:!1,reason:"视频解码探测 Worker 创建失败",frames:d,duration:u(),detail:t})}let f;o.onerror=t=>{p({supported:!1,reason:"视频解码探测 Worker 运行时错误",frames:d,duration:u(),detail:t})},o.onmessage=t=>{var e;const n=null!=(e=t.data)?e:{};var o,l,c,h,f,m,_,g,y,S,A;if("frame"===n.type)return d+=1,(null==s||null==a)&&(s=null!=(l=null==(c=n.frame)?void 0:c.codedWidth)?l:null==(h=n.frame)?void 0:h.displayWidth,a=null!=(f=null==(m=n.frame)?void 0:m.codedHeight)?f:null==(_=n.frame)?void 0:_.displayHeight),null==(o=n.frame)||null==o.close||o.close(),void(d>=VIDEO_PROBE_MIN_FRAMES&&p({supported:!0,frames:d,duration:u(),codec:r,width:s,height:a}));"configSupport"!==n.type?"error"!==n.type?"done"===n.type&&d<VIDEO_PROBE_MIN_FRAMES&&p({supported:!1,reason:`视频解码未输出足够帧(${d}/${VIDEO_PROBE_MIN_FRAMES})`,frames:d,duration:u(),codec:r,detail:{done:!0}}):p({supported:!1,reason:n.error||"视频解码失败",frames:d,duration:u(),codec:r,detail:n}):(r=null!=(g=null==(y=n.configSupport)||null==(y=y.config)?void 0:y.codec)?g:r,void 0===i&&(i={hardwareAcceleration:null==(S=n.configSupport)||null==(S=S.config)?void 0:S.hardwareAcceleration,supported:!(null==(A=n.configSupport)||null==(A=A.configSupport)||!A.supported)}))};try{f=base64ToArrayBuffer(VIDEO_PROBE_BASE64)}catch(t){return void p({supported:!1,reason:"视频解码探测片解析失败",frames:d,duration:u(),detail:t})}o.postMessage({type:"decode",file:{data:f},start:0,end:VIDEO_PROBE_LAST_FRAME_INDEX,hardwareAcceleration:e},[f]),c=setTimeout(()=>{p({supported:!1,reason:`视频解码探测超时(${VIDEO_PROBE_TIMEOUT_MS}ms)`,frames:d,duration:u(),codec:r})},VIDEO_PROBE_TIMEOUT_MS)})}async function checkVideoDecodeDetailed(t){const e=isAndroidPlatform(),n=t||"default";if(void 0===window.VideoDecoder)return{name:"videoDecode",supported:!1,severity:"fatal",reason:"浏览器不支持 WebCodecs VideoDecoder API",detail:{isAndroid:e,hardwareAcceleration:e?"prefer-software":n}};const r=e?"fatal":"warn";let i;try{i=(await Promise.resolve().then(function(){return streamingVideo})).workerURL}catch(t){return{name:"videoDecode",supported:!1,severity:r,reason:"视频解码探测模块加载失败",detail:{isAndroid:e,hardwareAcceleration:n,error:t}}}const s=await probeVideoDecode(i,n),a=s.primaryConfig,o=e&&void 0!==a&&("prefer-software"!==a.hardwareAcceleration||!a.supported),l=s.supported&&!o;return{name:"videoDecode",supported:l,severity:r,reason:l?void 0:o?"Android 不支持软解码(prefer-software 声明不可用)":s.reason,detail:{isAndroid:e,hardwareAcceleration:e?"prefer-software":n,declaredSoftwareSupported:null==a?void 0:a.supported,probeCodec:s.codec,outputFrames:s.frames,outputSize:null!=s.width&&null!=s.height?`${s.width}x${s.height}`:void 0,duration:s.duration,cause:s.detail}}}const WORKER_CHECK_TIMEOUT_MS=3e3,WORKER_CHECK_MAX_ATTEMPTS=2;function probeWorkerExecution(){return new Promise(t=>{let e=null,n=null,r=!1,i=null;const s=s=>{var a;r||(r=!0,null!==i&&clearTimeout(i),null==(a=e)||a.terminate(),n&&URL.revokeObjectURL(n),t(s))};try{const t=new Blob(['self.postMessage("ok");'],{type:"application/javascript"});n=URL.createObjectURL(t),e=new Worker(n),e.onmessage=t=>{s("ok"===t.data?{status:"supported"}:{status:"failed",reason:"Web Worker 执行异常"})},e.onerror=t=>{s({status:"failed",reason:"Web Worker 创建失败",detail:t})},i=setTimeout(()=>{s({status:"timeout"})},WORKER_CHECK_TIMEOUT_MS)}catch(t){s({status:"failed",reason:"Web Worker 异常",detail:t})}})}async function checkWorkerDetailed(){if("undefined"==typeof Worker)return{name:"worker",supported:!1,severity:"fatal",reason:"浏览器不支持 Web Worker"};for(let t=1;t<=WORKER_CHECK_MAX_ATTEMPTS;t+=1){const e=await probeWorkerExecution();if("supported"===e.status)return{name:"worker",supported:!0,severity:"fatal",detail:{attempts:t}};if("failed"===e.status)return{name:"worker",supported:!1,severity:"fatal",reason:e.reason,detail:e.detail}}return{name:"worker",supported:!1,severity:"warn",reason:`Web Worker 创建超时(已重试 ${WORKER_CHECK_MAX_ATTEMPTS} 次)`,detail:{attempts:WORKER_CHECK_MAX_ATTEMPTS}}}async function checkCapability(t=!1,e="default"){const n=checkCapabilitySync(t);if(t){const t=await Promise.all([Promise.resolve(n.items.find(t=>"secureContext"===t.name)),Promise.resolve(n.items.find(t=>"audio"===t.name)),checkWorkerDetailed()]),e=t.filter(t=>"fatal"===t.severity&&!t.supported).length;return{supported:0===e,fatalCount:e,warnCount:t.filter(t=>"warn"===t.severity&&!t.supported).length,items:t}}const r=await Promise.all([Promise.resolve(n.items.find(t=>"secureContext"===t.name)),Promise.resolve(n.items.find(t=>"webgl2"===t.name)),Promise.resolve(n.items.find(t=>"audio"===t.name)),checkWebCodecsDetailed(),checkVideoDecodeDetailed(e),checkWorkerDetailed()]),i=r.filter(t=>"fatal"===t.severity&&!t.supported).length;return{supported:0===i,fatalCount:i,warnCount:r.filter(t=>"warn"===t.severity&&!t.supported).length,items:r}}const OPUS_FRAME_DURATION_US=2e4,ENCODE_TIMEOUT_MS=2e3;function buildAudioEncoderConfig(t){return{codec:"opus",sampleRate:t.sampleRate,numberOfChannels:t.channels,bitrate:t.bitrate,opus:{format:"opus",frameDuration:OPUS_FRAME_DURATION_US}}}class WebCodecOpusEncoder{constructor(t={}){this.encoder=null,this.isInitialized=!1,this.pendingEncode=null,this.timestamp=0,this.config=_extends({sampleRate:16e3,channels:1,bitrate:24e3,frameSize:1600},t)}static async isSupported(){if("undefined"==typeof AudioEncoder)return!1;try{var t;const e=await AudioEncoder.isConfigSupported(buildAudioEncoderConfig({sampleRate:16e3,channels:1,bitrate:24e3,frameSize:1600}));return!0===e.supported&&(null==(t=e.config)||null==(t=t.opus)?void 0:t.frameDuration)===OPUS_FRAME_DURATION_US}catch(t){return!1}}async init(){this.isInitialized||(this.encoder=this.createEncoder(),this.isInitialized=!0)}async encode(t){if(!this.isInitialized||!this.encoder)return Promise.reject(new Error("WebCodecOpusEncoder 未初始化"));if(this.pendingEncode)return Promise.reject(new Error("WebCodecs Opus 编码器仍在处理上一音频块"));const e=new Int16Array(t),n=this.timestamp,r=Math.round(1e6*t.length/this.config.sampleRate),i=n+r,s=r/OPUS_FRAME_DURATION_US;if(!Number.isInteger(s))return Promise.reject(new Error("PCM 音频块无法按 20ms Opus packet 完整分包"));const a=new AudioData({format:"s16",sampleRate:this.config.sampleRate,numberOfFrames:e.length,numberOfChannels:this.config.channels,timestamp:n,data:e}),o=new Promise((t,e)=>{const r=globalThis.setTimeout(()=>{this.failPending(new Error("WebCodecs Opus 编码输出超过 2 秒"))},ENCODE_TIMEOUT_MS);this.pendingEncode={startTimestampUs:n,endTimestampUs:i,expectedFrameCount:s,chunks:[],resolve:t,reject:e,timeoutId:r}});try{this.encoder.encode(a),this.timestamp=i}catch(t){this.failPending(t instanceof Error?t:new Error("WebCodecs Opus 编码失败"))}finally{a.close()}return o}reset(){if(this.timestamp=0,this.failPending(new Error("WebCodecs Opus 编码已重置")),this.encoder){try{this.encoder.close()}catch(t){}this.encoder=this.createEncoder()}}async destroy(){const t=this.encoder;if(t){try{await t.flush()}catch(t){}this.failPending(new Error("WebCodecs Opus 编码器已销毁"));try{t.close()}catch(t){}}this.encoder=null,this.isInitialized=!1}createEncoder(){let t;return t=new AudioEncoder({output:e=>{this.encoder===t&&this.handleOutput(e)},error:e=>{if(this.encoder!==t)return;const n=e instanceof Error?e:new Error("WebCodecs Opus 编码失败");(globalThis.avatarSDKLogger||console).error("[WebCodecOpusEncoder] 编码错误:",n),this.failPending(n)}}),t.configure(buildAudioEncoderConfig(this.config)),t}handleOutput(t){const e=this.pendingEncode;if(!e)return;if(t.timestamp<e.startTimestampUs||t.timestamp>=e.endTimestampUs||null!==t.duration&&t.duration!==OPUS_FRAME_DURATION_US)return void this.failPending(new Error("WebCodecs Opus 未按 20ms 分包,无法生成固定 100ms AU 音频"));if(e.chunks.push(t),e.chunks.length>e.expectedFrameCount)return void this.failPending(new Error("WebCodecs Opus 未按 20ms 分包,无法生成固定 100ms AU 音频"));if(e.chunks.length<e.expectedFrameCount)return;const n=e.chunks.map((t,n)=>{var r,i;const s=new Uint8Array(t.byteLength);t.copyTo(s);const a=null!=(r=null==(i=e.chunks[n+1])?void 0:i.timestamp)?r:e.endTimestampUs;return{data:s,durationMs:(t.duration&&t.duration>0?t.duration:Math.max(1,a-t.timestamp))/1e3}}),r=n.reduce((t,e)=>t+e.durationMs,0);n.some(t=>t.durationMs!==OPUS_FRAME_DURATION_US/1e3)||r!==(e.endTimestampUs-e.startTimestampUs)/1e3?this.failPending(new Error("WebCodecs Opus 未按 20ms 分包,无法生成固定 100ms AU 音频")):(globalThis.clearTimeout(e.timeoutId),this.pendingEncode=null,e.resolve(n))}failPending(t){const e=this.pendingEncode;e&&(globalThis.clearTimeout(e.timeoutId),this.pendingEncode=null,e.reject(t))}}const EBML_ID={EBML:440786851,EBMLVersion:17030,EBMLReadVersion:17143,EBMLMaxIDLength:17138,EBMLMaxSizeLength:17139,DocType:17026,DocTypeVersion:17031,DocTypeReadVersion:17029,Segment:408125543,SegmentInfo:357149030,TimecodeScale:2807729,MuxingApp:19840,WritingApp:22337,Tracks:374648427,TrackEntry:174,TrackNumber:215,TrackUID:29637,TrackType:131,FlagLacing:156,Language:2274716,CodecID:134,CodecPrivate:25506,CodecDelay:22186,SeekPreRoll:22203,Audio:225,SamplingFrequency:181,Channels:159,Cluster:524531317,Timecode:231,SimpleBlock:163};class WebMMuxer{constructor(t=16e3){this.chunks=[],this.hasHeader=!1,this.clusterTimestamp=0,this.frameDuration=100,this.sampleRate=t}writeHeader(){if(this.hasHeader)return;const t=this.buildEBMLHeader(),e=this.buildSegmentInfo(),n=this.buildOpusTracks();this.chunks.push(t),this.chunks.push(new Uint8Array([24,83,128,103,1,255,255,255,255,255,255,255])),this.chunks.push(e),this.chunks.push(n),this.hasHeader=!0,this.clusterTimestamp=0}feedOpusFrame(t,e=this.frameDuration){this.hasHeader||this.writeHeader();const n=this.buildCluster(Math.round(this.clusterTimestamp),t);this.chunks.push(n),this.clusterTimestamp+=e}flush(){if(0===this.chunks.length)return new ArrayBuffer(0);const t=this.chunks.reduce((t,e)=>t+e.length,0),e=new Uint8Array(t);let n=0;for(const t of this.chunks)e.set(t,n),n+=t.length;return this.chunks=[],e.buffer}reset(){this.chunks=[],this.hasHeader=!1,this.clusterTimestamp=0}encodeVINT(t,e){if(void 0!==e){const n=new Uint8Array(e);for(let r=e-1;r>=0;r--)n[r]=255&t,t>>>=8;return n[0]|=1<<8-e,n}if(t<127)return new Uint8Array([128|t]);if(t<16383)return new Uint8Array([64|t>>8,255&t]);if(t<2097151)return new Uint8Array([32|t>>16,t>>8&255,255&t]);if(t<268435455)return new Uint8Array([16|t>>24,t>>16&255,t>>8&255,255&t]);throw new Error(`VINT value too large: ${t}`)}encodeID(t){return t<=255?new Uint8Array([t]):t<=65535?new Uint8Array([t>>8,255&t]):t<=16777215?new Uint8Array([t>>16,t>>8&255,255&t]):new Uint8Array([t>>>24,t>>16&255,t>>8&255,255&t])}encodeUint(t){if(0===t)return new Uint8Array([0]);const e=[];let n=t;for(;n>0;)e.unshift(255&n),n=Math.floor(n/256);return new Uint8Array(e)}encodeString(t){return(new TextEncoder).encode(t)}encodeFloat32(t){const e=new ArrayBuffer(4);return new DataView(e).setFloat32(0,t,!1),new Uint8Array(e)}encodeElement(t,e){const n=this.encodeID(t),r=this.encodeVINT(e.length),i=new Uint8Array(n.length+r.length+e.length);return i.set(n,0),i.set(r,n.length),i.set(e,n.length+r.length),i}encodeUintElement(t,e){return this.encodeElement(t,this.encodeUint(e))}encodeStringElement(t,e){return this.encodeElement(t,this.encodeString(e))}encodeFloat32Element(t,e){return this.encodeElement(t,this.encodeFloat32(e))}concatArrays(t){const e=t.reduce((t,e)=>t+e.length,0),n=new Uint8Array(e);let r=0;for(const e of t)n.set(e,r),r+=e.length;return n}buildEBMLHeader(){const t=this.concatArrays([this.encodeUintElement(EBML_ID.EBMLVersion,1),this.encodeUintElement(EBML_ID.EBMLReadVersion,1),this.encodeUintElement(EBML_ID.EBMLMaxIDLength,4),this.encodeUintElement(EBML_ID.EBMLMaxSizeLength,8),this.encodeStringElement(EBML_ID.DocType,"webm"),this.encodeUintElement(EBML_ID.DocTypeVersion,4),this.encodeUintElement(EBML_ID.DocTypeReadVersion,2)]);return this.encodeElement(EBML_ID.EBML,t)}buildSegmentInfo(){const t=this.concatArrays([this.encodeUintElement(EBML_ID.TimecodeScale,1e6),this.encodeStringElement(EBML_ID.MuxingApp,"xmov-avatar-sdk"),this.encodeStringElement(EBML_ID.WritingApp,"xmov-avatar-sdk")]);return this.encodeElement(EBML_ID.SegmentInfo,t)}buildOpusTracks(){const t=new Uint8Array([79,112,117,115,72,101,97,100,1,1,0,0,128,62,0,0,0,0,0]),e=this.concatArrays([this.encodeFloat32Element(EBML_ID.SamplingFrequency,this.sampleRate),this.encodeUintElement(EBML_ID.Channels,1)]),n=this.concatArrays([this.encodeUintElement(EBML_ID.TrackNumber,1),this.encodeUintElement(EBML_ID.TrackUID,1),this.encodeUintElement(EBML_ID.TrackType,2),this.encodeUintElement(EBML_ID.FlagLacing,0),this.encodeStringElement(EBML_ID.Language,"und"),this.encodeStringElement(EBML_ID.CodecID,"A_OPUS"),this.encodeElement(EBML_ID.CodecPrivate,t),this.encodeUintElement(EBML_ID.CodecDelay,0),this.encodeUintElement(EBML_ID.SeekPreRoll,8e7),this.encodeElement(EBML_ID.Audio,e)]),r=this.encodeElement(EBML_ID.TrackEntry,n);return this.encodeElement(EBML_ID.Tracks,r)}buildCluster(t,e){const n=this.encodeUintElement(EBML_ID.Timecode,t),r=this.encodeVINT(1),i=new Uint8Array([0,0]),s=new Uint8Array([128]),a=this.concatArrays([r,i,s,e]),o=this.encodeElement(EBML_ID.SimpleBlock,a),l=this.concatArrays([n,o]);return this.encodeElement(EBML_ID.Cluster,l)}}class PcmWebMEncoder{constructor(){this.opusEncoder=new WebCodecOpusEncoder({sampleRate:16e3,channels:1,bitrate:24e3,frameSize:1600}),this.muxer=new WebMMuxer(16e3),this.queue=Promise.resolve(),this.generation=0,this.destroyed=!1,this.pendingBlocks=0}static isSupported(){return WebCodecOpusEncoder.isSupported()}async init(){await this.opusEncoder.init()}async encode(t){var e=this;if(1600!==t.length)throw new Error(`PCM 音频块必须为 1600 samples,实际为 ${t.length}`);if(this.pendingBlocks>=20)throw new Error("PCM/Opus 编码队列超过 2 秒");this.pendingBlocks+=1;const n=this.generation,r=new Int16Array(t),i=this.queue.then(async function(){if(e.destroyed||n!==e.generation)return new ArrayBuffer(0);const t=await e.opusEncoder.encode(r);if(e.destroyed||n!==e.generation)return new ArrayBuffer(0);for(const n of t)e.muxer.feedOpusFrame(n.data,n.durationMs);return e.muxer.flush()}).finally(()=>{this.pendingBlocks-=1});return this.queue=i.then(()=>{},()=>{}),i}reset(){const t=++this.generation;this.queue=this.queue.then(()=>{this.destroyed||t!==this.generation||(this.opusEncoder.reset(),this.muxer.reset())})}async destroy(){this.destroyed=!0,this.generation+=1,await this.opusEncoder.destroy(),await this.queue,this.muxer.reset()}}class MediaRecorderEncoder{constructor(){this.audioCtx=null,this.workletNode=null,this.destination=null,this.recorder=null,this.isRecording=!1,this.nextResolve=null,this.dataQueue=[]}static isSupported(){return"undefined"!=typeof MediaRecorder&&MediaRecorder.isTypeSupported("audio/webm;codecs=opus")}async init(){const t=window.AudioContext||window.webkitAudioContext;this.audioCtx=new t({sampleRate:16e3});const e=new Blob(["\n class PCMInjectorProcessor extends AudioWorkletProcessor {\n constructor() {\n super();\n this.buffer = new Float32Array(0);\n this.port.onmessage = (e) => {\n if (e.data.type === 'pcm') {\n const int16 = new Int16Array(e.data.pcm);\n const float32 = new Float32Array(int16.length);\n for (let i = 0; i < int16.length; i++) {\n float32[i] = int16[i] / 32768;\n }\n const newBuffer = new Float32Array(this.buffer.length + float32.length);\n newBuffer.set(this.buffer);\n newBuffer.set(float32, this.buffer.length);\n this.buffer = newBuffer;\n }\n };\n }\n process(inputs, outputs) {\n const output = outputs[0][0];\n if (!output) return true;\n const len = Math.min(output.length, this.buffer.length);\n for (let i = 0; i < len; i++) {\n output[i] = this.buffer[i];\n }\n this.buffer = this.buffer.slice(len);\n for (let i = len; i < output.length; i++) {\n output[i] = 0;\n }\n return true;\n }\n }\n registerProcessor('pcm-injector-processor', PCMInjectorProcessor);\n "],{type:"application/javascript"}),n=URL.createObjectURL(e);await this.audioCtx.audioWorklet.addModule(n),URL.revokeObjectURL(n),this.workletNode=new AudioWorkletNode(this.audioCtx,"pcm-injector-processor"),this.destination=this.audioCtx.createMediaStreamDestination(),this.workletNode.connect(this.destination);const r=MediaRecorder.isTypeSupported("audio/webm;codecs=opus")?"audio/webm;codecs=opus":"audio/webm";this.recorder=new MediaRecorder(this.destination.stream,{mimeType:r,audioBitsPerSecond:24e3}),this.recorder.ondataavailable=t=>{t.data&&t.data.size>0&&t.data.arrayBuffer().then(t=>{if(this.nextResolve){const e=this.nextResolve;this.nextResolve=null,e(t)}else this.dataQueue.push(t)})},"suspended"===this.audioCtx.state&&await this.audioCtx.resume()}async feedPCM(t){return this.workletNode&&this.recorder?(this.isRecording||(this.recorder.start(100),this.isRecording=!0),this.workletNode.port.postMessage({type:"pcm",pcm:t},[t]),this.dataQueue.length>0?this.dataQueue.shift():new Promise(t=>{const e=setTimeout(()=>{this.nextResolve=null,t(null)},200);this.nextResolve=n=>{clearTimeout(e),t(n)}})):null}reset(){this.recorder&&"inactive"!==this.recorder.state&&this.recorder.stop(),this.isRecording=!1,this.nextResolve=null,this.dataQueue=[]}destroy(){var t,e;if(this.nextResolve=null,this.dataQueue=[],this.recorder)try{"inactive"!==this.recorder.state&&this.recorder.stop()}catch(t){}null==(t=this.workletNode)||t.disconnect(),null==(e=this.destination)||e.disconnect();try{var n;null==(n=this.audioCtx)||n.close()}catch(t){}this.recorder=null,this.workletNode=null,this.destination=null,this.audioCtx=null}}class XmovAvatar{constructor(t){if(this.TAG="[XMOV AVATAR]",this.el=null,this.status=-1,this.networkMonitor=null,this.ttsa=null,this.debugOverlay=null,this.sentryReporter=null,this.firstFrameSpan=null,this._offlineTimer=-1,this._offlineInterval=300,this._env="production",this.avatarCanvasVisible=!0,this.pendingInvisibleMode=!1,this.isInitialized=!1,this.onStateChange=()=>{},this.onDownloadProgress=null,this.replayData=null,this.startConnectTime=0,this.connectSuccessTime=0,this.sessionResTime=0,this.charbinResTime=0,this.isfirstReceive=!0,this.enableClientInterrupt=!1,this.retryCount=1,this.retryTimer=-1,this.maxRetryCount=9,this.retryRound=1,this.maxRetryRound=3,this.isRetrying=!1,this.isStartRetry=!1,this.destroyed=!1,this.incompleteInitializationCleanupPromise=null,this.captureAudioCtx=null,this.captureWorklet=null,this.captureSource=null,this.captureSetupPromise=null,this.captureLastSpeechId=-2,this.restartPlaybackCaptureImpl=null,this.captureEncodeQueue=Promise.resolve(),this.captureGeneration=0,this.pcmCaptureLastSpeechId=-2,this.pcmCaptureFirstChunk=!0,this.pcmWebMEncoder=null,this.mediaRecorderEncoder=null,this.pcmCaptureMode="none",this.pcmEncodeId=0,this.networkInfo={rtt:0,downlink:0,networkStatus:!1},this.mediaRecorder=null,this.recordedChunks=[],this.stream=null,this._isClientMode=!1,this._streamingClient=null,this._videoPlayer=null,this._eventDispatcher=null,this._apiForwarder=null,this._clientOnDownloadProgress=null,this._pendingInit=!1,this._pendingInitConfig=null,this._clientSessionId="",this.handleBeforeUnload=()=>{this.destroy("beforeunload")},window.avatarSDKLogger.setEnabled(t.enableLogger),this.options=t,this._env=t.env||"production",this.enableClientInterrupt=t.enableClientInterrupt||!1,this.boundVisibilityChange=this.visibilitychange.bind(this),"client"===t.renderMode)return this._isClientMode=!0,void this.initializeClient(t);this.initializeSDK(t),this.networkMonitor=new NetworkMonitor({offlineCallback:t=>{if(this.onMessage({code:EErrorCode.NETWORK_DOWN,message:t||"网络断开"}),console.log("网络断开(network off)",t),!this.isInitialized)return window.avatarSDKLogger.warn(this.TAG,"初始化未完成时断网,清除所有资源并断开连接"),void this.cleanupBeforeInitComplete("network_offline_before_init");this.status!==AvatarStatus.offline&&this.offlineHandle()},onlineCallback:t=>{var e;if(this.onMessage({code:EErrorCode.NETWORK_UP,message:t||"网络恢复"}),!this.isInitialized)return window.avatarSDKLogger.warn(this.TAG,"网络恢复但初始化未完成,清除所有资源并断开连接"),void this.cleanupBeforeInitComplete("network_online_before_init");null==(e=this.ttsa)||e.clearReconnectTimer(),this.isStartRetry&&this.triggerReconnect()}})}getStatus(){return this.status}getIsInitialized(){return this.isInitialized}get businessENV(){return this._env}getUniqueSpeakId(){var t;return(null==(t=this.ttsa)?void 0:t.getUniqueSpeakId())||`0-${this.getSessionId()}`}async initializeSDK(t){var e,n,r;if(!navigator.onLine)return void this.onMessage({code:EErrorCode.NETWORK_BREAK,message:"没有网络,请联网后重试"});const i=this,s=t,{containerId:a,container:o,appId:l,appSecret:c,gatewayServer:d,cacheServer:h,config:u}=t,{scale:p=1}=null!=(e=null==u||null==(n=u.layout)?void 0:n.avatar)?e:{};null!=u&&null!=(r=u.layout)&&null!=(r=r.avatar)&&r.scale&&(u.layout.avatar.scale=validateScaleWithDecimal(p,"initializeSDK"));const f=_extends({},u||{},{raw_audio:!isSupportMES()});if(o&&o instanceof HTMLElement)this.el=o;else{const t=document.querySelector(a);if(!t)return void this.onMessage({code:EErrorCode.CONTAINER_NOT_FOUND,message:`containerId: ${a} 不存在`});this.el=t}const m=document.createElement("div");m.setAttribute("id","avatar-bg-container"),m.setAttribute("style","position:absolute;top:0;left:0;width:100%;height:100%;z-index:0;opacity:0;"),this.el.appendChild(m);const _=this.el.getAttribute("style");this.el.setAttribute("style",_?`position:relative;overflow:hidden;${_}`:"position:relative;overflow:hidden;"),this.resourceManager=new ResourceManager({sdkInstance:this,headers:t.headers,tag:t.tag,gateway_type:t.gateway_type||"default",asr_id:t.asr_id,llm_id:t.llm_id,session_speak_req_id:t.session_speak_req_id,sessionRequestData:s.sessionRequestData,appId:l,appSecret:c,gatewayServer:d,cacheServer:h,config:f,audioOnlyMode:t.audioOnlyMode||!1,onNetworkInfo(e){i.networkInfo=e,null==t.onNetworkInfo||t.onNetworkInfo(e)},onStartSessionWarning:t=>{var e,n;null==(e=(n=this.options).onStartSessionWarning)||e.call(n,t)}}),this.renderScheduler=new RenderScheduler({sdkInstance:this,container:this.el,resourceManager:this.resourceManager,enableDebugger:t.enableDebugger,hardwareAcceleration:t.hardwareAcceleration||"default",enableClientInterrupt:this.enableClientInterrupt,audioOnlyMode:t.audioOnlyMode||!1,onDownloadProgress:t=>{var e,n,r,s;null==(e=this.onDownloadProgress)||e.call(this,t),null==(n=this.el)||n.setAttribute("style",(null==(r=this.el)?void 0:r.style.cssText)+`opacity:${100===t?"1":"0"};`),this.isInitialized=100===t,100===t&&(this.pendingInvisibleMode||this.status===AvatarStatus.online||this.status===AvatarStatus.invisible||this.onStatusChange(AvatarStatus.online),this.resourceManager._setOfflineCache(),null==(s=this.ttsa)||s.sendSdkPoint("loadvideo_decode_time",{timestamp:Date.now()}),setTimeout(()=>{var t,e;null==(t=this.ttsa)||t.sendDeviceInfo(_extends({},getDeviceInfo(),window.performanceTracker.getFirstInfo(),{sdk_version:"2.4.0-alpha.4",resolution:null==(e=this.resourceManager.getConfig())?void 0:e.resolution,download_speed:i.networkInfo.downlink||0}))},20),this.enableAudioPlaybackCapture())},onStateChange:e=>{this.getStatus()===AvatarStatus.offline&&"idle"!==e||""===e||null==t.onStateChange||t.onStateChange(e)},onRenderChange:(e,n)=>{null==t.onRenderChange||t.onRenderChange(e),e!==RenderState.rendering||n!==RenderState.resumed&&this.getStatus()!==AvatarStatus.online||!this.isInitialized||(window.avatarSDKLogger.log(this.TAG,"Status:===== 渲染中,状态: rendering",this.getSessionId()),this.onStatusChange(AvatarStatus.visible))},onVoiceStateChange:(e,n,r)=>{null==t.onVoiceStateChange||t.onVoiceStateChange(e,n,r)},onWalkStateChange:e=>{null==t.onWalkStateChange||t.onWalkStateChange(e)},sendVideoInfo:t=>{var e;null==(e=this.debugOverlay)||e.setVideoInfo(t)},onSpeakStateChange:(e,n)=>{null==t.onSpeakStateChange||t.onSpeakStateChange(e,n)},setAudioInfo:t=>{var e;null==(e=this.debugOverlay)||e.setAudioInfo(t)},setEventData:t=>{var e;null==(e=this.debugOverlay)||e.setEventData(t)},renderFrameCallback:t=>{this.renderFrameCallback(t),this.handleReplaySend(t)},reportMessage:t=>{this.onMessage(t)},sendSdkPoint:(t,e,n)=>{var r;null==(r=this.ttsa)||r.sendSdkPoint(t,e,n)},sendMessage:(t,e)=>{var n;null==(n=this.ttsa)||n.send(t,e)},onFPSUpdate:e=>{null==t.onFPSUpdate||t.onFPSUpdate(e)},onFrameDataUpdate:e=>{null==t.onFrameDataUpdate||t.onFrameDataUpdate(e)}}),t.onStateRenderChange&&window.performanceTracker.setOnStateRenderChange(t.onStateRenderChange),null!=u&&u.walk_config&&this.changeWalkConfig(u.walk_config),null!=u&&u.layout&&this.changeLayout(u.layout),WidgetDefaultRenderer.CUSTOM_WIDGET=t.onWidgetEvent,WidgetDefaultRenderer.PROXY_WIDGET=t.proxyWidget||{}}initializeClient(t){const{containerId:e,container:n}=t;if(n&&n instanceof HTMLElement)this.el=n;else{const t=document.querySelector(e);var r,i;if(!t)return void(null==(r=(i=this.options).onMessage)||r.call(i,{code:EErrorCode.CONTAINER_NOT_FOUND,message:`containerId: ${e} 不存在`}));this.el=t}const s=this.el.getAttribute("style");this.el.setAttribute("style",s?`position:relative;overflow:hidden;${s}`:"position:relative;overflow:hidden;"),this._eventDispatcher=new EventDispatcher({onStateChange:t.onStateChange,onSpeakStateChange:t.onSpeakStateChange,onVoiceStateChange:t.onVoiceStateChange,onStatusChange:t.onStatusChange,onRenderChange:t.onRenderChange,onWalkStateChange:t.onWalkStateChange,onWidgetEvent:t.onWidgetEvent,onMessage:t.onMessage,onNetworkInfo:t.onNetworkInfo,onFPSUpdate:t.onFPSUpdate,onFrameDataUpdate:t.onFrameDataUpdate,onDownloadProgress:t=>{var e;null==(e=this._clientOnDownloadProgress)||e.call(this,t),t>=100&&!this.isInitialized&&(this.isInitialized=!0)},onSessionId:t=>{this._clientSessionId=t,window.avatarSDKLogger.log(this.TAG,"[client] 收到 session_id:",t)}});const a=t.streamingServer||`ws://${location.hostname}:8080`;this._streamingClient=new StreamingClient({url:a,onReady:()=>{if(window.avatarSDKLogger.log(this.TAG,"[client] 双方就绪,等待 Server 推流..."),this._pendingInit){var t;this._pendingInit=!1;const e=this._pendingInitConfig;this._pendingInitConfig=null,window.avatarSDKLogger.log(this.TAG,"[client] 补发 init 命令"),null==(t=this._apiForwarder)||t.init(e)}},onOffer:t=>{var e;null==(e=this._videoPlayer)||e.handleOffer(t)},onIce:t=>{var e;null==(e=this._videoPlayer)||e.addIceCandidate(t)},onEventProxy:(t,e,n)=>{var r;null==(r=this._eventDispatcher)||r.dispatch(t,e,n)},onError:t=>{var e,n;null==(e=(n=this.options).onMessage)||e.call(n,{code:EErrorCode.NETWORK_DOWN,message:t})},onDisconnect:()=>{this.onStatusChange(AvatarStatus.offline)}}),this._videoPlayer=new VideoPlayer({container:this.el,streamingClient:this._streamingClient,useAlphaMask:t.useAlphaMask,onConnected:()=>{window.avatarSDKLogger.log(this.TAG,"[client] WebRTC 已连接"),this.onStatusChange(AvatarStatus.online)},onDisconnected:()=>{this.onStatusChange(AvatarStatus.offline)}}),this._apiForwarder=new APIForwarder(this._streamingClient),this._streamingClient.connect(),window.addEventListener("beforeunload",this.handleBeforeUnload)}renderFrameCallback(t){var e;null!=(e=this.ttsa)&&e.getStatus()||[AvatarStatus.offline].includes(this.status)||t%24!=0||this.offlineHandle()}async init(t){await this.initializeSession(t)}async initializeSession(t){var e,n,r,i;const s=await checkCapability(this.options.audioOnlyMode,this.options.hardwareAcceleration);if(!s.supported){const t=`浏览器能力检查失败: ${s.items.filter(t=>"fatal"===t.severity&&!t.supported).map(t=>t.reason).join("; ")}`;return void this.onMessage({code:EErrorCode.INIT_ERROR,message:t})}if(this.destroyed=!1,this.isInitialized=!1,this.incompleteInitializationCleanupPromise=null,this.startConnectTime=Date.now(),this._isClientMode){var a;this._clientOnDownloadProgress=t.onDownloadProgress||null;const e={appId:this.options.appId,appSecret:this.options.appSecret,gatewayServer:this.options.gatewayServer,cacheServer:this.options.cacheServer,headers:this.options.headers,tag:this.options.tag,gateway_type:this.options.gateway_type,env:this.options.env,config:this.options.config,hardwareAcceleration:this.options.hardwareAcceleration,enableDebugger:this.options.enableDebugger,initModel:t.initModel,scaleDownBy:this.options.scaleDownBy||1,useAlphaMask:this.options.useAlphaMask};var o;return void(null!=(a=this._streamingClient)&&a.isConnected()?null==(o=this._apiForwarder)||o.init(e):(this._pendingInit=!0,this._pendingInitConfig=e,window.avatarSDKLogger.log(this.TAG,"[client] WebSocket 未连接,init 命令暂存")))}if(null!=(e=this.options.sentry)&&e.enabled)try{var l;this.sentryReporter=new SentryReporter("https://aabed165326fc7a2a276b49aa4043be3@xmovsentry.xmov.ai/32",{tracesSampleRate:null==(l=this.options.sentry)?void 0:l.tracesSampleRate}),this.sentryReporter.setTag("app_id",this.options.appId||""),this.sentryReporter.setTag("env",this._env)}catch(t){window.avatarSDKLogger.warn(this.TAG,"Sentry 初始化失败",t)}const c=null==(n=this.sentryReporter)?void 0:n.startInactiveSpan("sdk.init",{op:"init"});this.firstFrameSpan=null!=(r=null==(i=this.sentryReporter)?void 0:i.startInactiveSpan("sdk.first_frame",{op:"render"}))?r:null;const{onDownloadProgress:d,initModel:h}=t;this.onDownloadProgress=t=>{15===t&&(this.sessionResTime=Date.now()),80===t&&(this.charbinResTime=Date.now()),d(t)},h===InitModel.invisible&&(this.pendingInvisibleMode=!0),window.performanceTracker.markStart(performanceConstant.load_resource),window.performanceTracker.markStart(performanceConstant.first_avatar_render),window.performanceTracker.markStart(performanceConstant.first_webgl_render);const u=this.onDownloadProgress,p=this.sentryReporter?await this.sentryReporter.startSpan("sdk.resource_load",{op:"resource.load"},()=>this.resourceManager.load(u.bind(this))):await this.resourceManager.load(u.bind(this));return this.destroyed?(null==c||c.end(),void window.avatarSDKLogger.warn(this.TAG,"sdk destroyed during load, aborting after resourceManager load")):null!=p&&p.socket_io_url&&null!=p&&p.token?(this.connectSuccessTime=Date.now(),window.performanceTracker.markEnd(performanceConstant.load_resource),this.debugOverlay=new DebugOverlay(this,p),this.ttsa=this.connectTtsa(p),this.renderScheduler.init(),this.renderScheduler.setAvatarCanvasVisible(this.avatarCanvasVisible),window.performanceTracker.setReportFunc(this.ttsa),window.addEventListener("beforeunload",this.handleBeforeUnload),document.addEventListener("visibilitychange",this.boundVisibilityChange),null==c||c.end(),p):(null==c||c.end(),void window.avatarSDKLogger.error(this.TAG,"init error, socket_io_url or token is empty reload"))}setAudioPlaybackDataHandler(t){this.options.onAudioPlaybackData=t}restartAudioPlaybackCapture(){var t;null==(t=this.restartPlaybackCaptureImpl)||t.call(this)}enableAudioPlaybackCapture(){return this.options.onAudioPlaybackData?(this.captureSetupPromise||(this.captureSetupPromise=null!=(t=this.resourceManager)&&t.config.raw_audio?this.setupPCMCapture().finally(()=>{this.captureSetupPromise=null}):this.setupAudioCapture().finally(()=>{this.captureSetupPromise=null})),this.captureSetupPromise):Promise.resolve();var t}async setupAudioCapture(){var t=this;const e=document.getElementById("xmov-avatar-audio");if(e&&this.options.onAudioPlaybackData&&!this.captureAudioCtx&&!this.captureSource)if(void 0!==window.AudioWorkletNode)try{var n;if(!await PcmWebMEncoder.isSupported())return void this.onMessage({code:EErrorCode.INIT_ERROR,message:"当前浏览器不支持 WebCodecs AudioEncoder Opus,无法启用 100ms 双路音频"});if(this.pcmWebMEncoder=new PcmWebMEncoder,await this.pcmWebMEncoder.init(),this.captureAudioCtx=new AudioContext({sampleRate:16e3}),16e3!==this.captureAudioCtx.sampleRate)throw new Error(`浏览器无法创建 16000 Hz AudioContext: ${this.captureAudioCtx.sampleRate}`);this.captureSource=this.captureAudioCtx.createMediaElementSource(e),this.captureSource.connect(this.captureAudioCtx.destination);let r=!1,i=!0,s=0,a=0;const o=t=>{const e=++this.captureGeneration;r=!0,i=!0,s=Date.now()-100,a=0,this.captureLastSpeechId=t,this.captureEncodeQueue=this.captureEncodeQueue.then(()=>{var t;e===this.captureGeneration&&(null==(t=this.pcmWebMEncoder)||t.reset())})},l=()=>{const t=++this.captureGeneration;r=!1,this.captureLastSpeechId=-2,this.captureEncodeQueue=this.captureEncodeQueue.then(()=>{var e;t===this.captureGeneration&&(null==(e=this.pcmWebMEncoder)||e.reset())})};this.restartPlaybackCaptureImpl=()=>{r&&o(this.renderScheduler.getSpeechId())};const c=new Blob(["\n class AudioCaptureProcessor extends AudioWorkletProcessor {\n constructor() {\n super();\n this.buffer = new Float32Array(1600); // 100ms @ 16kHz\n this.bufferIndex = 0;\n }\n\n process(inputs, outputs) {\n for (const output of outputs) {\n for (const channel of output) channel.fill(0);\n }\n const input = inputs[0];\n if (input && input.length > 0 && input[0] && input[0].length > 0) {\n const frameCount = input[0].length;\n\n for (let i = 0; i < frameCount; i++) {\n let sample = 0;\n for (let channel = 0; channel < input.length; channel++) {\n sample += input[channel][i] || 0;\n }\n this.buffer[this.bufferIndex++] = sample / input.length;\n\n // 缓冲区满 1600 采样点时,检测静音并发送到主线程\n if (this.bufferIndex >= 1600) {\n // 检测是否全是静音(全零或极低值)\n let hasAudio = false;\n for (let j = 0; j < 1600; j++) {\n if (Math.abs(this.buffer[j]) > 0.0001) {\n hasAudio = true;\n break;\n }\n }\n\n const pcm = new Int16Array(1600);\n for (let j = 0; j < 1600; j++) {\n const value = Math.max(-1, Math.min(1, this.buffer[j]));\n pcm[j] = value < 0 ? value * 0x8000 : value * 0x7fff;\n }\n this.port.postMessage(\n { hasAudio: hasAudio, pcmData: pcm.buffer },\n [pcm.buffer]\n );\n this.bufferIndex = 0;\n }\n }\n }\n return true;\n }\n }\n registerProcessor('audio-capture-processor', AudioCaptureProcessor);\n "],{type:"application/javascript"}),d=URL.createObjectURL(c);if(await this.captureAudioCtx.audioWorklet.addModule(d),URL.revokeObjectURL(d),this.captureWorklet=new AudioWorkletNode(this.captureAudioCtx,"audio-capture-processor"),this.captureSource.connect(this.captureWorklet),this.captureWorklet.connect(this.captureAudioCtx.destination),this.captureEncodeQueue=Promise.resolve(),this.captureWorklet.port.onmessage=e=>{if(!this.options.onAudioPlaybackData)return;const{hasAudio:n,pcmData:c}=e.data,d=this.renderScheduler.getSpeechId();if(n&&!r||n&&r&&d!==this.captureLastSpeechId?o(d):!n&&r&&l(),!(n&&r&&c instanceof ArrayBuffer))return;const h=this.captureGeneration,u=i;i=!1;const p=s+100*a;a+=1,this.captureEncodeQueue=this.captureEncodeQueue.then(async function(){var e;const n=await(null==(e=t.pcmWebMEncoder)?void 0:e.encode(new Int16Array(c)));n&&0!==n.byteLength&&h===t.captureGeneration&&(null==t.options.onAudioPlaybackData||t.options.onAudioPlaybackData({data:n,codec:"opus",isFirstChunk:u,sampleRate:16e3,samples:1600,timestamp:p,speech_id:d}))}).catch(t=>{var e;null==(e=window.avatarSDKLogger)||e.error(this.TAG,"[AudioCapture] PCM/WebCodecs 编码失败:",t)})},"suspended"===this.captureAudioCtx.state&&await this.captureAudioCtx.resume(),"running"!==this.captureAudioCtx.state)throw new Error("AudioContext 未运行,无法启动 farend PCM 捕获");null==(n=window.avatarSDKLogger)||n.log(this.TAG,"[AudioCapture] 初始化成功,采样率:",this.captureAudioCtx.sampleRate,"Hz,opus 编码 (WebM 容器)")}catch(t){var r,i;if(this.captureGeneration++,this.restartPlaybackCaptureImpl=null,this.captureWorklet){try{this.captureWorklet.port.onmessage=null,this.captureWorklet.disconnect()}catch(t){}this.captureWorklet=null}try{var s;null==(s=this.captureSource)||s.disconnect()}catch(t){}this.captureSource=null,this.captureAudioCtx&&"closed"!==this.captureAudioCtx.state&&await this.captureAudioCtx.close().catch(()=>{}),this.captureAudioCtx=null,null==(r=this.pcmWebMEncoder)||r.destroy(),this.pcmWebMEncoder=null,null==(i=window.avatarSDKLogger)||i.error(this.TAG,"[AudioCapture] 初始化失败:",t)}else this.onMessage({code:EErrorCode.INIT_ERROR,message:"当前浏览器不支持 AudioWorkletNode,无法启用音频捕获(ASR 回声消除)"})}async setupPCMCapture(){var t,e=this;if(!this.options.onAudioPlaybackData)return;const n=null==(t=this.renderScheduler.getAudioRenderer())?void 0:t.getAudioPlayer();var r;if(!n)return void(null==(r=window.avatarSDKLogger)||r.error(this.TAG,"[PCMCapture] PCMAudioPlayer 未就绪"));const i=await PcmWebMEncoder.isSupported(),s=MediaRecorderEncoder.isSupported();var a;if(!i&&!s)return null==(a=window.avatarSDKLogger)||a.warn(this.TAG,"[PCMCapture] 当前浏览器不支持 Opus 编码(WebCodecs 和 MediaRecorder 均不可用),跳过 PCM 捕获"),void this.onMessage({code:EErrorCode.INIT_ERROR,message:"当前浏览器不支持 Opus 编码,PCM 模式下无法启用音频捕获(ASR 回声消除)"});try{var o;i?(this.pcmWebMEncoder=new PcmWebMEncoder,await this.pcmWebMEncoder.init(),this.pcmCaptureMode="webcodec"):(this.mediaRecorderEncoder=new MediaRecorderEncoder,await this.mediaRecorderEncoder.init(),this.pcmCaptureMode="mediarecorder"),this.restartPlaybackCaptureImpl=()=>{var t,e;this.pcmCaptureFirstChunk=!0,this.pcmCaptureLastSpeechId=this.renderScheduler.getSpeechId(),this.pcmEncodeId++,null==(t=this.pcmWebMEncoder)||t.reset(),null==(e=this.mediaRecorderEncoder)||e.reset(),n.resetCaptureBuffer()},await n.attachCapture(async function({pcmData:t,hasAudio:r}){try{if(!e.options.onAudioPlaybackData)return;const d=Date.now()-100;if(!n.isPlaying)return void n.resetCaptureBuffer();const h=e.renderScheduler.getSpeechId();var i,s;if(h!==e.pcmCaptureLastSpeechId&&(e.pcmCaptureFirstChunk=!0,e.pcmCaptureLastSpeechId=h,e.pcmEncodeId++,null==(i=e.pcmWebMEncoder)||i.reset(),null==(s=e.mediaRecorderEncoder)||s.reset(),n.resetCaptureBuffer()),!r)return;const u=e.pcmEncodeId;let p=null;const f=performance.now();if("webcodec"===e.pcmCaptureMode&&e.pcmWebMEncoder){const n=new Int16Array(t);var a;if(p=await e.pcmWebMEncoder.encode(n),u!==e.pcmEncodeId)return void(null==(a=window.avatarSDKLogger)||a.log(e.TAG,"[PCMCapture] 丢弃过期编码数据(编码会话已重置)"));if(0===p.byteLength)return;const r=performance.now()-f;var o;r>10&&(null==(o=window.avatarSDKLogger)||o.warn(e.TAG,`[PCMCapture] WebCodecs 编码耗时过长: ${r.toFixed(2)}ms`))}else if("mediarecorder"===e.pcmCaptureMode&&e.mediaRecorderEncoder){var l;if(p=await e.mediaRecorderEncoder.feedPCM(t),u!==e.pcmEncodeId)return void(null==(l=window.avatarSDKLogger)||l.log(e.TAG,"[PCMCapture] 丢弃过期编码数据(编码会话已重置)"));if(!p)return;const n=performance.now()-f;var c;n>10&&(null==(c=window.avatarSDKLogger)||c.warn(e.TAG,`[PCMCapture] MediaRecorder 编码耗时过长: ${n.toFixed(2)}ms`))}if(!p)return;const m=e.pcmCaptureFirstChunk;e.pcmCaptureFirstChunk=!1,e.options.onAudioPlaybackData({data:p,codec:"opus",isFirstChunk:m,sampleRate:16e3,samples:1600,timestamp:d,speech_id:h})}catch(t){var d;null==(d=window.avatarSDKLogger)||d.error(e.TAG,"[PCMCapture] 捕获回调错误:",t)}}),null==(o=window.avatarSDKLogger)||o.log(this.TAG,`[PCMCapture] PCM 捕获初始化成功,编码路径: ${this.pcmCaptureMode}`)}catch(t){var l,c,d;null==(l=window.avatarSDKLogger)||l.error(this.TAG,"[PCMCapture] PCM 捕获初始化失败:",t),null==(c=this.pcmWebMEncoder)||c.destroy(),this.pcmWebMEncoder=null,null==(d=this.mediaRecorderEncoder)||d.destroy(),this.mediaRecorderEncoder=null,this.pcmCaptureMode="none"}}visibilitychange(){var t,e,n;document.hidden?this.setVolume(0):(null!=(t=this.ttsa)&&t.getStatus()&&(null==(n=this.renderScheduler)||n.forceSyncDecoder(),this.setVolume(1)),null!=(e=this.ttsa)&&e.getStatus()||this.status!==AvatarStatus.offline||!NetworkMonitor.ONLINE||(window.avatarSDKLogger.warn(this.TAG,"切回前台发现连接已断开,主动触发重连"),this.onlineMode(),this.setVolume(1)),this.captureAudioCtx&&"suspended"===this.captureAudioCtx.state&&this.captureAudioCtx.resume().catch(()=>{}))}setReplayData(t){this.replayData=t}handleReplaySend(t){if(!this.replayData)return;const e=this.replayData.filter(e=>Number(e.client_frame_number)===t&&"sdk_burial_point"!==e.event_type);for(const t of e){var n;"state_change"===t.event_type?null==(n=this.ttsa)||n.stateChange(t.event_data.state,t.event_data.params):"send_text"===t.event_type?this.speak(t.event_data.ssml,t.event_data.is_start,t.event_data.is_end,t.event_data.extra):window.avatarSDKLogger.log(this.TAG,`[handleReplaySend] 未知事件类型: ${t}`)}}connectTtsa(t){return window.performanceTracker.markStart(performanceConstant.ttsa_connect),window.performanceTracker.markStart(performanceConstant.ttsa_ready),new Ttsa({sdkInstance:this,url:t.socket_io_url,path:(null==t?void 0:t.socket_io_path)||"",room:t.room,session_id:t.session_id,token:t.token,framedata_proto_version:this.resourceManager.getConfig().framedata_proto_version,reconnect_client_timeout:(null==t?void 0:t.reconnect_client_timeout)||0,reconnect_timeout:(null==t?void 0:t.reconnect_timeout)||0,appInfo:_extends({},this.resourceManager.getAppInfo(),{env:this._env}),onReady:()=>{var e,n,r,i,s,a;null==(e=this.ttsa)||e.sendSdkPoint("connect_sdk",{timestamp:this.startConnectTime}),null==(n=this.ttsa)||n.sendSdkPoint("connect_sdk_success",{timestamp:this.connectSuccessTime}),null==(r=this.ttsa)||r.sendSdkPoint("session_processing_time",{timestamp:this.sessionResTime}),null==(i=this.ttsa)||i.sendSdkPoint("Char_bin_download_time",{timestamp:this.charbinResTime}),null==(s=this.ttsa)||s.sendSdkPoint("socket_connect_time",{timestamp:Date.now()}),this.onTtsaReady(t),null==(a=this.ttsa)||a.syncTimestamp()},handleMessage:(t,e)=>{var n,r;this.isfirstReceive&&t===EFrameDataType.BODY&&(null==(n=this.ttsa)||n.sendSdkPoint("body_completed_first_time",{timestamp:Date.now()}),this.isfirstReceive=!1,null==(r=this.firstFrameSpan)||r.end(),this.firstFrameSpan=null),this.renderScheduler.handleData(t,e)},handleAAFrame:t=>{var e,n;null==(e=(n=this.options).onAAFrameHandle)||e.call(n,t)},runStartFrameIndex:t=>{this.renderScheduler.runStartFrameIndex()},ttsaStateChangeHandle:t=>{this.renderScheduler.ttsaStateChangeHandle(t)},reloadSuccess:()=>{this.reloadSuccess()},enterOfflineMode:()=>{this.offlineHandle()},reStartSDK:()=>{this.reStartSession()},sendVoiceEnd:()=>{var t;null==(t=this.renderScheduler)||t.sendVoiceEnd()},getCurrentFrameIndex:()=>{var t,e;return null!=(t=null==(e=this.renderScheduler)?void 0:e.getCurrentFrameIndex())?t:0}})}start(){var t;this.renderScheduler.render(),null==(t=this.ttsa)||t.start(),this.pendingInvisibleMode?(this.pendingInvisibleMode=!1,this.setInvisibleMode()):this.isInitialized&&this.onStatusChange(AvatarStatus.online)}onTtsaReady(t){this.start()}async _reload(){const t=await this.resourceManager._reload();if(t&&!this.destroyed){if(await this.onSessionReloaded(t),this.destroyed)return null;this.ttsa=this.connectTtsa(t),this.ttsa._setResumeInfoCallback(this.resourceManager._getSessionId(),this.renderScheduler._getResumeInfo.bind(this.renderScheduler))}return t}async onSessionReloaded(t){}onSessionReloadExhausted(t){}async restartSessionForTransport(t){var e;this.renderScheduler.interrupt("in_offline_mode"),await this.resourceManager.stopSession(t),this.destroyed||(null==(e=this.ttsa)||e.close(),this.status!==AvatarStatus.offline&&this.offlineHandle(),this.reStartSession())}cancelSessionRestart(){this.resetRetryState(),this.clearAllRetryTimers()}reloadSuccess(){var t;null==(t=this.renderScheduler)||t.markReconnectRecover(),this.isInitialized&&this.onStatusChange(AvatarStatus.online),setTimeout(()=>{window.clearInterval(this._offlineTimer)},1e3)}async stop(){await this.renderScheduler.stop()}isDestroyed(){return this.destroyed}async destroyClient(){var t,e,n;if(this.destroyed)return void window.avatarSDKLogger.warn(this.TAG,"SDK 已销毁,忽略重复销毁请求");if(this.destroyed=!0,this._isClientMode)return this._streamingClient&&(this._streamingClient.destroy(),this._streamingClient=null),this._videoPlayer&&(this._videoPlayer.destroy(),this._videoPlayer=null),this._eventDispatcher=null,this._apiForwarder=null,this.el=null,window.removeEventListener("beforeunload",this.handleBeforeUnload),void window.avatarSDKLogger.log(this.TAG,"薄客户端 SDK 已销毁");if(this.cancelSessionRestart(),-1!==this._offlineTimer&&(clearInterval(this._offlineTimer),this._offlineTimer=-1),this.ttsa&&(this.ttsa.close(),this.ttsa=null),this.renderScheduler&&this.renderScheduler.destroy(),this.resourceManager&&this.resourceManager.destroy(),this.debugOverlay&&(this.debugOverlay.destroy(),this.debugOverlay=null),this.networkMonitor)try{this.networkMonitor.destroy(),this.networkMonitor=null}catch(t){window.avatarSDKLogger.warn(this.TAG,"销毁 networkMonitor 时出错",t)}if(this.pcmEncodeId++,this.captureGeneration++,this.restartPlaybackCaptureImpl=null,this.captureWorklet){try{this.captureWorklet.port.onmessage=null,this.captureWorklet.disconnect()}catch(t){}this.captureWorklet=null}if(this.captureSource){try{this.captureSource.disconnect()}catch(t){}this.captureSource=null}if(this.captureAudioCtx){try{this.captureAudioCtx.close()}catch(t){}this.captureAudioCtx=null}const r=null==(t=this.renderScheduler)||null==(t=t.getAudioRenderer())?void 0:t.getAudioPlayer();if(r&&r.detachCapture(),null==(e=this.pcmWebMEncoder)||e.destroy(),this.pcmWebMEncoder=null,null==(n=this.mediaRecorderEncoder)||n.destroy(),this.mediaRecorderEncoder=null,this.pcmCaptureLastSpeechId=-2,this.pcmCaptureFirstChunk=!0,this.pcmCaptureMode="none",this.el=null,this.startConnectTime=0,this.connectSuccessTime=0,this.sessionResTime=0,this.charbinResTime=0,this.isfirstReceive=!0,this.networkInfo={rtt:0,downlink:0,networkStatus:!1},window.removeEventListener("beforeunload",this.handleBeforeUnload),document.removeEventListener("visibilitychange",this.boundVisibilityChange),this.sentryReporter){try{this.sentryReporter.destroy()}catch(t){}this.sentryReporter=null}window.avatarSDKLogger.log(this.TAG,"SDK 已销毁")}async destroy(t="user"){var e;if(this.replayData=null,this._isClientMode)return void await this.disconnectClientForDestroy(t);null==(e=this.ttsa)||e.sendSdkPoint("close_session",{reason:t});const n=await this.resourceManager.stopSession(t);return await this.destroyClient(),n&&this.onStatusChange(AvatarStatus.close),n}async disconnectClientForDestroy(t){this.replayData=null;try{var e,n;if(this._isClientMode)null==(n=this._apiForwarder)||n.destroy(t);else if(null!=(e=this.ttsa)&&e.hasConnected)this.ttsa.sendSdkPoint("close_session",{reason:t}),await this.ttsa.quit(t);else{var r;await(null==(r=this.ttsa)?void 0:r.quit(t)),await this.resourceManager.stopSession(t)}}catch(t){window.avatarSDKLogger.warn(this.TAG,"TTSA client_quit 未确认,继续释放本地资源",t)}finally{await this.destroyClient(),this.onStatusChange(AvatarStatus.close)}}idle(){var t,e;this._isClientMode?null==(e=this._apiForwarder)||e.idle():(this.enableClientInterrupt&&this.renderScheduler.interrupt("idle"),null==(t=this.ttsa)||t.idle())}listen(){var t,e;this._isClientMode?null==(e=this._apiForwarder)||e.listen():(this.enableClientInterrupt&&this.renderScheduler.interrupt("listen"),null==(t=this.ttsa)||t.listen())}think(){var t,e;this._isClientMode?null==(e=this._apiForwarder)||e.think():(this.enableClientInterrupt&&this.renderScheduler.interrupt("think"),null==(t=this.ttsa)||t.think())}interactiveidle(){var t,e;this._isClientMode?null==(e=this._apiForwarder)||e.interactiveidle():(this.enableClientInterrupt&&this.renderScheduler.interrupt("interactiveidle"),null==(t=this.ttsa)||t.interactiveidle())}speak(t,e=!0,n=!0,r={client_speak_id:"",client_frame:0}){if(!this._isClientMode)return this.sentryReporter?this.sentryReporter.startSpan("sdk.speak",{op:"speak",data:{client_speak_id:r.client_speak_id}},()=>this.speakInternal(t,e,n,r)):this.speakInternal(t,e,n,r);var i;null==(i=this._apiForwarder)||i.speak(t,e,n,r)}speakInternal(t,e=!0,n=!0,r={client_speak_id:"",client_frame:0}){var i,s,a;this.enableClientInterrupt&&e&&this.renderScheduler.interrupt("speak"),r.client_frame=null!=(i=null==(s=this.renderScheduler)?void 0:s.getCurrentFrameIndex())?i:0;const o=null==(a=this.ttsa)?void 0:a.sendText(t,e,n,r);return this.renderScheduler.resume(),o}setOffsetFrame(t){this.renderScheduler.setOffsetFrame(t)}syncTimestamp(){var t,e,n;null==(t=this.ttsa)||t.sendSyncTimestamp(null!=(e=null==(n=this.renderScheduler)?void 0:n.getCurrentFrameIndex())?e:0)}notifyEnterInvisibleMode(){var t;null==(t=this.ttsa)||t.enterInvisibleMode()}notifyExitInvisibleMode(){var t;null==(t=this.ttsa)||t.exitInvisibleMode()}setVolume(t){var e;this._isClientMode?null==(e=this._apiForwarder)||e.setVolume(t):this.renderScheduler.setVolume(t)}getSessionId(){var t;return this._isClientMode?this._clientSessionId:null==(t=this.resourceManager)?void 0:t.session_id}showDebugInfo(){var t;this.debugOverlay&&(null==(t=this.debugOverlay)||t.show())}hideDebugInfo(){var t;null==(t=this.debugOverlay)||t.hide()}changeAvatarVisible(t){var e,n;this.avatarCanvasVisible=t,this._isClientMode?null==(n=this._apiForwarder)||n.changeAvatarVisible(t):null==(e=this.renderScheduler)||e.setAvatarCanvasVisible(t)}cleanupBeforeInitComplete(t){var e,n=this;if(this.incompleteInitializationCleanupPromise)return this.incompleteInitializationCleanupPromise;window.avatarSDKLogger.warn(this.TAG,`清理初始化未完成的资源,原因: ${t}`),this.isInitialized=!1;const r=null==(e=this.resourceManager)?void 0:e.stopSession(t);return null==r||r.catch(t=>{window.avatarSDKLogger.warn(this.TAG,"停止初始化未完成的会话时出错",t)}),this.incompleteInitializationCleanupPromise=async function(){try{await r,await n.destroyClient()}catch(t){window.avatarSDKLogger.warn(n.TAG,"清理初始化未完成的本地资源时出错",t)}}(),this.incompleteInitializationCleanupPromise}reportInitializationFailure(t,e){this.onMessage({code:EErrorCode.INIT_ERROR,message:t,e})}offlineHandle(){this.onStatusChange(AvatarStatus.offline),this.renderScheduler._offlineMode(),this._offlineTimer=window.setInterval(()=>{if(this.status!==AvatarStatus.offline)return clearInterval(this._offlineTimer),void(this._offlineTimer=-1);this.renderScheduler._offlineRun()},this._offlineInterval)}async stopSessionFromSocket(t){await this.resourceManager.stopSession(t)}offlineMode(){var t;this.renderScheduler.interrupt("in_offline_mode"),this.resourceManager.stopSession("offline_mode"),null==(t=this.ttsa)||t.close(),this.offlineHandle()}onlineMode(){NetworkMonitor.ONLINE&&this._reload()}onMessage(t){var e,n;try{"object"==typeof t.e&&null!==t.e||(t.e={msg:t.e}),t.session_id=this.getSessionId()}catch(r){window.avatarSDKLogger.warn(this.TAG,"获取 session_id 时出错",r)}const r=Errors(t);if(t.code!==EErrorCode.RENDER_BODY_ERROR&&t.code!==EErrorCode.RENDER_FACE_ERROR&&t.code!==EErrorCode.BODY_DATA_EXPIRED&&(this.options.onMessage(r),this.sentryReporter))try{this.sentryReporter.captureError(r)}catch(t){window.avatarSDKLogger.warn(this.TAG,"Sentry 上报失败",t)}null==(e=this.ttsa)||e.send("client_error",t),null==(n=this.debugOverlay)||n.addError(r)}onStatusChange(t){var e,n;t!==this.status&&(this.status=t,null==(e=(n=this.options).onStatusChange)||e.call(n,t))}switchInvisibleMode(){var t,e;this._isClientMode?null==(t=this._apiForwarder)||t.switchInvisibleMode():this.renderScheduler?this.status===AvatarStatus.visible||this.status===AvatarStatus.online?this.setInvisibleMode():(this.notifyExitInvisibleMode(),this.renderScheduler.switchInvisibleMode(),this.listen()):null==(e=window.avatarSDKLogger)||e.warn(this.TAG,"RenderScheduler 未初始化,无法切换隐身模式")}setInvisibleMode(){this.interactiveidle(),this.renderScheduler.switchInvisibleMode(),this.notifyEnterInvisibleMode(),this.onStatusChange(AvatarStatus.invisible)}getPendingInvisibleMode(){return this.pendingInvisibleMode||!1}getRenderState(){return this.renderScheduler?this.renderScheduler.getRenderState():RenderState.init}changeLayout(t){var e,n;if(this._isClientMode)return void(null==(n=this._apiForwarder)||n.changeLayout(t));const{scale:r=1}=t.avatar||{};t.avatar.scale=validateScaleWithDecimal(r,"changeLayout"),null==(e=this.ttsa)||e.changeLayout(t),this.renderScheduler.setCharacterCanvasLayout(t)}changeWalkConfig(t){var e,n;this._isClientMode?null==(n=this._apiForwarder)||n.changeWalkConfig(t):(null==(e=this.ttsa)||e.changeWalkConfig(t),this.renderScheduler.setWalkConfig(t))}interrupt(t){var e;return this._isClientMode?(null==(e=this._apiForwarder)||e.interrupt(t),0):this.renderScheduler.interrupt(t)}triggerReconnect(){this.clearAllRetryTimers(),this.isRetrying=!1,this.retryCount=1,this.retryRound=1,this.reStartSession()}reStartSession(){this.isRetrying||this.retryRound>this.maxRetryRound||(this.clearAllRetryTimers(),this.isStartRetry=!0,this.isRetrying=!0,this._retryImpl())}async _retryImpl(){var t=this;if(this.retryRound>this.maxRetryRound||!this.isRetrying)return;let e=1e3;this.retryCount>1&&(e=1e3*Math.pow(2,this.retryCount)),this.retryTimer=window.setTimeout(async function(){if(t.retryTimer=-1,t.isRetrying&&!t.destroyed)try{const e=t.sentryReporter?await t.sentryReporter.startSpan("sdk.reconnect",{op:"reconnect",data:{round:t.retryRound,count:t.retryCount}},()=>t._reload()):await t._reload();if(!t.isRetrying||t.destroyed)return;if(null===e){if(t.retryCount>=t.maxRetryCount){if(t.retryRound>=t.maxRetryRound)return window.avatarSDKLogger.warn(t.TAG,`重试达最大轮次(${t.maxRetryRound})+每轮最大次数(${t.maxRetryCount}),总次数=${t.maxRetryRound*t.maxRetryCount},停止重试`),t.onSessionReloadExhausted(),void t.resetRetryState();window.avatarSDKLogger.warn(t.TAG,`第${t.retryRound}轮重试次数达上限(${t.maxRetryCount}),进入第${t.retryRound+1}轮重试`),t.retryCount=1,t.retryRound+=1}else t.retryCount+=1;t._retryImpl()}else t.renderScheduler.stopAudio(-1),window.avatarSDKLogger.log(t.TAG,`第${t.retryRound}轮第${t.retryCount}次重试成功,停止重试`),t.resetRetryState()}catch(e){if(window.avatarSDKLogger.error(t.TAG,"重试过程异常",e),t.retryCount>=t.maxRetryCount){if(t.retryRound>=t.maxRetryRound)return window.avatarSDKLogger.warn(t.TAG,`重试异常且达总次数上限(${t.maxRetryRound*t.maxRetryCount}),停止重试`),t.onSessionReloadExhausted(e),void t.resetRetryState();t.retryCount=1,t.retryRound+=1}else t.retryCount+=1;t.retryRound<=t.maxRetryRound&&t.isRetrying?t._retryImpl():t.resetRetryState()}},e)}clearAllRetryTimers(){-1!==this.retryTimer&&(clearTimeout(this.retryTimer),this.retryTimer=-1)}resetRetryState(){this.isRetrying=!1,this.isStartRetry=!1,this.retryCount=1,this.retryRound=1}seekToFrame(t){var e;this.renderScheduler.seekToFrame(t),null==(e=this.ttsa)||e.seekToFrame(t)}async startRecoder(){try{var t,e;const n=null==(t=this.el)?void 0:t.querySelector("canvas"),r=null==(e=this.el)?void 0:e.querySelector("audio");if(!n||!r)return void console.error("找不到 canvas 或 audio 元素");const i=n.captureStream(60);let s=[];if(this.captureSource&&this.captureAudioCtx){const t=this.captureAudioCtx.createMediaStreamDestination();this.captureSource.connect(t),s=t.stream.getAudioTracks()}else if("function"==typeof r.captureStream)s=r.captureStream().getAudioTracks();else{if("function"!=typeof r.mozCaptureStream)return void window.avatarSDKLogger.error("❌ 当前浏览器不支持 captureStream,无法录制音频");s=r.mozCaptureStream().getAudioTracks()}this.stream=new MediaStream([...i.getVideoTracks(),...s]),this.recordedChunks=[],this.mediaRecorder=new MediaRecorder(this.stream,{mimeType:"video/mp4",videoBitsPerSecond:12582912}),this.mediaRecorder.ondataavailable=t=>{t.data&&t.data.size>0&&this.recordedChunks.push(t.data)},this.mediaRecorder.start(100),window.avatarSDKLogger.log("✅ 开始录制")}catch(t){window.avatarSDKLogger.error("❌ 录制失败:",t)}}stopRecoder(){var t;this.mediaRecorder&&(this.mediaRecorder.stop(),null==(t=this.stream)||t.getTracks().forEach(t=>t.stop()),window.avatarSDKLogger.log("⏹ 停止录制"))}exportVideo(){if(!this.recordedChunks.length)return void window.avatarSDKLogger.error("没有录制到数据");const t=new Blob(this.recordedChunks,{type:"video/mp4"}),e=URL.createObjectURL(t),n=document.createElement("a");n.href=e,n.download=`录制_${(new Date).getTime()}.mp4`,n.click(),window.avatarSDKLogger.log("✅ 下载成功,大小:",t.size)}getOptions(){return this.options}simulateContextLoss(t=5e3,e=!1){this.renderScheduler?this.renderScheduler.simulateContextLoss(t,e):window.avatarSDKLogger.warn("[Test] renderScheduler not initialized")}getRecoveryStatus(){return this.renderScheduler?this.renderScheduler.getRecoveryStatus():null}async testStagedRecovery(){if(this.renderScheduler)return this.renderScheduler.testStagedRecovery();window.avatarSDKLogger.warn("[Test] renderScheduler not initialized")}restartWebGL(){return this.renderScheduler?this.renderScheduler.restartWebGL():(window.avatarSDKLogger.warn("[restartWebGL] renderScheduler not initialized"),!1)}}XmovAvatar.IBRAnimationGeneratorCharInfo_NN=IBRAnimationGeneratorCharInfo_NN,XmovAvatar.unpackIBRAnimation=unpackIBRAnimation,XmovAvatar.formatMJT=formatMJT,XmovAvatar.getVertices=getVertices,XmovAvatar.getPCATextures=getPCATextures,XmovAvatar.getWavefrontObjFromVertices=getWavefrontObjFromVertices,XmovAvatar.GLDevice=GLDevice,XmovAvatar.GLPipeline=GLPipeline,XmovAvatar.checkCapability=checkCapability;export{XmovAvatar as default};
2
2
  //# sourceMappingURL=index.modern.js.map