@rqmii_immersive/agent-react-sdk 5.1.0 → 5.1.1

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,4 +1,4 @@
1
- "use strict";const ae=require("react"),Jt=require("react/jsx-runtime");function Gp(){if(typeof window>"u")return;const d=window;d.__rqmii_orig_console||(d.__rqmii_orig_console={error:console.error,warn:console.warn,log:console.log,debug:console.debug});const r=d.__rqmii_orig_console,s=a=>{if(a.length===0)return!1;const p=String(a[0]);return p.includes("reading 'S'")||p.includes("reading 'state'")||p.includes("MicVAD has null stream")||p.includes("VAD |")||p.includes("audioCtx.state")||p.includes("using default audio context")};console.error=(...a)=>{s(a)||r.error.apply(console,a)},console.warn=(...a)=>{s(a)||r.warn.apply(console,a)},console.log=(...a)=>{s(a)||r.log.apply(console,a)},console.debug=(...a)=>{s(a)||r.debug.apply(console,a)}}const hi={TEXT:"text",VOICE:"voice",TEXT_AND_VOICE:"text_and_voice",CLOUD_AVATAR:"cloud_avatar",DESKTOP_AVATAR:"desktop_avatar"},br={CONNECT:"connect",DISCONNECT:"disconnect",CONNECT_ERROR:"connect_error",SESSION_READY:"session_ready",SESSION_JOINED:"session_joined",SESSION_TERMINATED:"session_terminated",USER_MESSAGE:"user_message",AUDIO_CHUNK:"audio_chunk",AUDIO_END:"audio_end",INTERRUPT:"interrupt",CHANGE_SESSION_LANGUAGE:"change_session_language",LANGUAGE_CHANGED:"language_changed",CLIENT_READY:"client_ready",CLIENT_TOOL_REQUEST:"client_tool_request",CLIENT_TOOL_RESULT:"client_tool_result",CLEAR_SESSION_HISTORY:"clear_session_history",TRANSCRIPT:"transcript",PARTIAL_TRANSCRIPT:"partial_transcript",AGENT_RESPONSE_CHUNK:"agent_response_chunk",AGENT_RESPONSE:"agent_response",AGENT_AUDIO_CHUNK:"agent_audio_chunk",AGENT_AUDIO_COMPLETE:"agent_audio_complete",AVATAR_SPEAKING:"avatar_speaking",AVATAR_SPEAKING_DONE:"avatar_speaking_done",INTERRUPTED:"interrupted",ERROR:"error",AUTH_ERROR:"auth_error",SESSION_EXPIRED:"session_expired",CREDITS_EXHAUSTED:"credits_exhausted",SESSION_STATE_CHANGED:"session:state_changed",AUDIO_PLAYBACK_COMPLETE:"audio:playback_complete",MESSAGE_RATE_LIMITED:"message_rate_limited",SHOW_LEAD_CAPTURE_FORM:"show_lead_capture_form"},pt={IDLE:"idle",INITIALIZING:"initializing",CONNECTING:"connecting",CONNECTED:"connected",FAILED:"failed",ENDED:"ended"},Zt={IDLE:"idle",CONNECTING:"connecting",LOADING:"loading",CONNECTED:"connected",DISCONNECTED:"disconnected",ERROR:"error"},Ns={IDLE:"idle",USER_SPEAKING:"user_speaking",AGENT_THINKING:"agent_thinking",AGENT_SPEAKING:"agent_speaking",TOOL_EXECUTING:"tool_executing",TERMINATING:"terminating",TERMINATED:"terminated"},qp={encoding:"16bitInt",channels:1,sampleRate:16e3},po={connectionState:pt.IDLE,isConnected:!1,isSessionReady:!1,error:null,isAudioPlaying:!1,isAvatarSpeaking:!1,sessionState:Ns.IDLE,cloudStream:{state:Zt.IDLE,error:null},transcript:null,partialTranscript:null,session:{sessionId:null,role:null,agentType:null,streamingUrl:null,uniqueId:null},messages:[],creditExhausted:!1,creditError:null,agentConfig:null};function hp(d,r){switch(r.type){case"SET_CONNECTION_STATE":return{...d,connectionState:r.payload,isConnected:r.payload===pt.CONNECTED};case"SET_ERROR":return{...d,error:r.payload};case"SET_CLOUD_STREAM_STATE":return{...d,cloudStream:r.payload};case"SET_SESSION_STATE":return{...d,sessionState:r.payload};case"UPDATE_SESSION":return{...d,session:{...d.session,...r.payload}};case"ADD_MESSAGE":return{...d,messages:[...d.messages,r.payload]};case"SET_AUDIO_PLAYING":return{...d,isAudioPlaying:r.payload};case"SET_AVATAR_SPEAKING":return{...d,isAvatarSpeaking:r.payload};case"SET_CREDIT_EXHAUSTED":return{...d,creditExhausted:r.payload.exhausted,creditError:r.payload.error};case"SET_TRANSCRIPT":return{...d,transcript:r.payload};case"SET_PARTIAL_TRANSCRIPT":return{...d,partialTranscript:r.payload};case"SET_MESSAGES":return{...d,messages:r.payload};case"SET_SESSION_READY":return{...d,isSessionReady:r.payload};case"SET_AGENT_CONFIG":return{...d,agentConfig:r.payload};case"HARD_RESET":return po;case"REPLACE_STATE":return r.payload;default:return d}}function pg(d){return{isSessionTerminated:d===Ns.TERMINATED,isSessionTerminating:d===Ns.TERMINATING,isAgentThinking:d===Ns.AGENT_THINKING,isAgentSpeaking:d===Ns.AGENT_SPEAKING,isToolExecuting:d===Ns.TOOL_EXECUTING}}function fg(){const d=new Map;return{addChunk(r,s){const a=r||`request-${Date.now()}`,_=`${d.get(a)||""}${s||""}`;return d.set(a,_),{id:a,text:_}},consume(r,s=""){const a=r||`request-${Date.now()}`,p=d.get(a)||s||"";return d.delete(a),{id:a,text:p}},clear(){d.clear()}}}function mg(){try{const d=Intl.DateTimeFormat().resolvedOptions().timeZone;return typeof d=="string"&&d.trim()?d.trim():void 0}catch{return}}async function ei(d){if(!d?.ok){let r=`HTTP ${d.status}`;try{const p=await d.json();r=p?.detail||p?.message||r}catch{}const s=new Error(r);throw s.status=d.status,s}return d.json()}function gg({restUrl:d,log:r,withCredentials:s}){function a(){if(!d)throw new Error("Missing restUrl in RqmiiAgentProvider")}async function p({apiKey:N,publicChatId:z,agentId:te,userId:j,language:se="en",timezone:J,config:Y}={}){a();const W={...N?{api_key:N}:{},...z?{public_chat_id:z}:{},...te?{agent_id:te}:{},...j?{user_id:j}:{},language:se,...J?{timezone:J}:{},...Y?{config:Y}:{}};r("initializeSession — POST /sessions/init",W);const ne=await fetch(`${d}/sessions/init`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(W),...s?{credentials:"include"}:{}}),fe=await ei(ne);if(!fe?.session_id||!fe?.session_token)throw new Error("Invalid initialize session response");return fe}async function _({uniqueId:N}){a(),r("joinDesktopSession — POST /sessions/join",{uniqueId:N});const z=await fetch(`${d}/sessions/join`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({unique_id:N}),...s?{credentials:"include"}:{}}),te=await ei(z);if(!te?.session_id||!te?.session_token)throw new Error("Invalid join session response");return te}async function C(N){a(),r("fetchAgentConfig — GET /agent/{publicChatId}",{publicChatId:N});const z=await fetch(`${d}/agent/${encodeURIComponent(N)}`,{method:"GET",headers:{"Content-Type":"application/json"},...s?{credentials:"include"}:{}});return ei(z)}async function R({sessionId:N,rating:z,feedback:te,endedBy:j}){if(a(),!N)throw new Error("sessionId is required");const se={...typeof z=="number"?{rating:z}:{},...te?{feedback:te}:{},...j?{ended_by:j}:{}};r("submitFeedback — PATCH /conversations/{sessionId}/feedback",{sessionId:N,payload:se});const J=await fetch(`${d}/conversations/${encodeURIComponent(N)}/feedback`,{method:"PATCH",headers:{"Content-Type":"application/json"},body:JSON.stringify(se),...s?{credentials:"include"}:{}});return ei(J)}async function S({agentId:N,sessionId:z,collectedData:te}){if(a(),!N)throw new Error("agentId is required");if(!z)throw new Error("sessionId is required");r("submitLead — POST /public/agent/{agentId}/lead-capture/leads",{agentId:N,sessionId:z});const j=await fetch(`${d}/public/agent/${encodeURIComponent(N)}/lead-capture/leads`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({session_id:z,collected_data:te}),...s?{credentials:"include"}:{}});return ei(j)}return{initializeSession:p,joinDesktopSession:_,fetchAgentConfig:C,submitFeedback:R,submitLead:S}}const Dr=Object.create(null);Dr.open="0";Dr.close="1";Dr.ping="2";Dr.pong="3";Dr.message="4";Dr.upgrade="5";Dr.noop="6";const Di=Object.create(null);Object.keys(Dr).forEach(d=>{Di[Dr[d]]=d});const fo={type:"error",data:"parser error"},Wp=typeof Blob=="function"||typeof Blob<"u"&&Object.prototype.toString.call(Blob)==="[object BlobConstructor]",Hp=typeof ArrayBuffer=="function",jp=d=>typeof ArrayBuffer.isView=="function"?ArrayBuffer.isView(d):d&&d.buffer instanceof ArrayBuffer,xo=({type:d,data:r},s,a)=>Wp&&r instanceof Blob?s?a(r):pp(r,a):Hp&&(r instanceof ArrayBuffer||jp(r))?s?a(r):pp(new Blob([r]),a):a(Dr[d]+(r||"")),pp=(d,r)=>{const s=new FileReader;return s.onload=function(){const a=s.result.split(",")[1];r("b"+(a||""))},s.readAsDataURL(d)};function fp(d){return d instanceof Uint8Array?d:d instanceof ArrayBuffer?new Uint8Array(d):new Uint8Array(d.buffer,d.byteOffset,d.byteLength)}let Ya;function yg(d,r){if(Wp&&d.data instanceof Blob)return d.data.arrayBuffer().then(fp).then(r);if(Hp&&(d.data instanceof ArrayBuffer||jp(d.data)))return r(fp(d.data));xo(d,!1,s=>{Ya||(Ya=new TextEncoder),r(Ya.encode(s))})}const mp="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",ui=typeof Uint8Array>"u"?[]:new Uint8Array(256);for(let d=0;d<mp.length;d++)ui[mp.charCodeAt(d)]=d;const wg=d=>{let r=d.length*.75,s=d.length,a,p=0,_,C,R,S;d[d.length-1]==="="&&(r--,d[d.length-2]==="="&&r--);const N=new ArrayBuffer(r),z=new Uint8Array(N);for(a=0;a<s;a+=4)_=ui[d.charCodeAt(a)],C=ui[d.charCodeAt(a+1)],R=ui[d.charCodeAt(a+2)],S=ui[d.charCodeAt(a+3)],z[p++]=_<<2|C>>4,z[p++]=(C&15)<<4|R>>2,z[p++]=(R&3)<<6|S&63;return N},vg=typeof ArrayBuffer=="function",Co=(d,r)=>{if(typeof d!="string")return{type:"message",data:Kp(d,r)};const s=d.charAt(0);return s==="b"?{type:"message",data:_g(d.substring(1),r)}:Di[s]?d.length>1?{type:Di[s],data:d.substring(1)}:{type:Di[s]}:fo},_g=(d,r)=>{if(vg){const s=wg(d);return Kp(s,r)}else return{base64:!0,data:d}},Kp=(d,r)=>{switch(r){case"blob":return d instanceof Blob?d:new Blob([d]);case"arraybuffer":default:return d instanceof ArrayBuffer?d:d.buffer}},Qp="",bg=(d,r)=>{const s=d.length,a=new Array(s);let p=0;d.forEach((_,C)=>{xo(_,!1,R=>{a[C]=R,++p===s&&r(a.join(Qp))})})},Sg=(d,r)=>{const s=d.split(Qp),a=[];for(let p=0;p<s.length;p++){const _=Co(s[p],r);if(a.push(_),_.type==="error")break}return a};function Tg(){return new TransformStream({transform(d,r){yg(d,s=>{const a=s.length;let p;if(a<126)p=new Uint8Array(1),new DataView(p.buffer).setUint8(0,a);else if(a<65536){p=new Uint8Array(3);const _=new DataView(p.buffer);_.setUint8(0,126),_.setUint16(1,a)}else{p=new Uint8Array(9);const _=new DataView(p.buffer);_.setUint8(0,127),_.setBigUint64(1,BigInt(a))}d.data&&typeof d.data!="string"&&(p[0]|=128),r.enqueue(p),r.enqueue(s)})}})}let Ja;function Mi(d){return d.reduce((r,s)=>r+s.length,0)}function Oi(d,r){if(d[0].length===r)return d.shift();const s=new Uint8Array(r);let a=0;for(let p=0;p<r;p++)s[p]=d[0][a++],a===d[0].length&&(d.shift(),a=0);return d.length&&a<d[0].length&&(d[0]=d[0].slice(a)),s}function Eg(d,r){Ja||(Ja=new TextDecoder);const s=[];let a=0,p=-1,_=!1;return new TransformStream({transform(C,R){for(s.push(C);;){if(a===0){if(Mi(s)<1)break;const S=Oi(s,1);_=(S[0]&128)===128,p=S[0]&127,p<126?a=3:p===126?a=1:a=2}else if(a===1){if(Mi(s)<2)break;const S=Oi(s,2);p=new DataView(S.buffer,S.byteOffset,S.length).getUint16(0),a=3}else if(a===2){if(Mi(s)<8)break;const S=Oi(s,8),N=new DataView(S.buffer,S.byteOffset,S.length),z=N.getUint32(0);if(z>Math.pow(2,21)-1){R.enqueue(fo);break}p=z*Math.pow(2,32)+N.getUint32(4),a=3}else{if(Mi(s)<p)break;const S=Oi(s,p);R.enqueue(Co(_?S:Ja.decode(S),r)),a=0}if(p===0||p>d){R.enqueue(fo);break}}}})}const Xp=4;function $t(d){if(d)return $g(d)}function $g(d){for(var r in $t.prototype)d[r]=$t.prototype[r];return d}$t.prototype.on=$t.prototype.addEventListener=function(d,r){return this._callbacks=this._callbacks||{},(this._callbacks["$"+d]=this._callbacks["$"+d]||[]).push(r),this};$t.prototype.once=function(d,r){function s(){this.off(d,s),r.apply(this,arguments)}return s.fn=r,this.on(d,s),this};$t.prototype.off=$t.prototype.removeListener=$t.prototype.removeAllListeners=$t.prototype.removeEventListener=function(d,r){if(this._callbacks=this._callbacks||{},arguments.length==0)return this._callbacks={},this;var s=this._callbacks["$"+d];if(!s)return this;if(arguments.length==1)return delete this._callbacks["$"+d],this;for(var a,p=0;p<s.length;p++)if(a=s[p],a===r||a.fn===r){s.splice(p,1);break}return s.length===0&&delete this._callbacks["$"+d],this};$t.prototype.emit=function(d){this._callbacks=this._callbacks||{};for(var r=new Array(arguments.length-1),s=this._callbacks["$"+d],a=1;a<arguments.length;a++)r[a-1]=arguments[a];if(s){s=s.slice(0);for(var a=0,p=s.length;a<p;++a)s[a].apply(this,r)}return this};$t.prototype.emitReserved=$t.prototype.emit;$t.prototype.listeners=function(d){return this._callbacks=this._callbacks||{},this._callbacks["$"+d]||[]};$t.prototype.hasListeners=function(d){return!!this.listeners(d).length};const Vi=typeof Promise=="function"&&typeof Promise.resolve=="function"?r=>Promise.resolve().then(r):(r,s)=>s(r,0),ur=typeof self<"u"?self:typeof window<"u"?window:Function("return this")(),xg="arraybuffer";function Yp(d,...r){return r.reduce((s,a)=>(d.hasOwnProperty(a)&&(s[a]=d[a]),s),{})}const Cg=ur.setTimeout,kg=ur.clearTimeout;function Gi(d,r){r.useNativeTimers?(d.setTimeoutFn=Cg.bind(ur),d.clearTimeoutFn=kg.bind(ur)):(d.setTimeoutFn=ur.setTimeout.bind(ur),d.clearTimeoutFn=ur.clearTimeout.bind(ur))}const Rg=1.33;function Ag(d){return typeof d=="string"?Ig(d):Math.ceil((d.byteLength||d.size)*Rg)}function Ig(d){let r=0,s=0;for(let a=0,p=d.length;a<p;a++)r=d.charCodeAt(a),r<128?s+=1:r<2048?s+=2:r<55296||r>=57344?s+=3:(a++,s+=4);return s}function Jp(){return Date.now().toString(36).substring(3)+Math.random().toString(36).substring(2,5)}function Mg(d){let r="";for(let s in d)d.hasOwnProperty(s)&&(r.length&&(r+="&"),r+=encodeURIComponent(s)+"="+encodeURIComponent(d[s]));return r}function Og(d){let r={},s=d.split("&");for(let a=0,p=s.length;a<p;a++){let _=s[a].split("=");r[decodeURIComponent(_[0])]=decodeURIComponent(_[1])}return r}class Pg extends Error{constructor(r,s,a){super(r),this.description=s,this.context=a,this.type="TransportError"}}class ko extends $t{constructor(r){super(),this.writable=!1,Gi(this,r),this.opts=r,this.query=r.query,this.socket=r.socket,this.supportsBinary=!r.forceBase64}onError(r,s,a){return super.emitReserved("error",new Pg(r,s,a)),this}open(){return this.readyState="opening",this.doOpen(),this}close(){return(this.readyState==="opening"||this.readyState==="open")&&(this.doClose(),this.onClose()),this}send(r){this.readyState==="open"&&this.write(r)}onOpen(){this.readyState="open",this.writable=!0,super.emitReserved("open")}onData(r){const s=Co(r,this.socket.binaryType);this.onPacket(s)}onPacket(r){super.emitReserved("packet",r)}onClose(r){this.readyState="closed",super.emitReserved("close",r)}pause(r){}createUri(r,s={}){return r+"://"+this._hostname()+this._port()+this.opts.path+this._query(s)}_hostname(){const r=this.opts.hostname;return r.indexOf(":")===-1?r:"["+r+"]"}_port(){return this.opts.port&&(this.opts.secure&&Number(this.opts.port)!==443||!this.opts.secure&&Number(this.opts.port)!==80)?":"+this.opts.port:""}_query(r){const s=Mg(r);return s.length?"?"+s:""}}class Dg extends ko{constructor(){super(...arguments),this._polling=!1}get name(){return"polling"}doOpen(){this._poll()}pause(r){this.readyState="pausing";const s=()=>{this.readyState="paused",r()};if(this._polling||!this.writable){let a=0;this._polling&&(a++,this.once("pollComplete",function(){--a||s()})),this.writable||(a++,this.once("drain",function(){--a||s()}))}else s()}_poll(){this._polling=!0,this.doPoll(),this.emitReserved("poll")}onData(r){const s=a=>{if(this.readyState==="opening"&&a.type==="open"&&this.onOpen(),a.type==="close")return this.onClose({description:"transport closed by the server"}),!1;this.onPacket(a)};Sg(r,this.socket.binaryType).forEach(s),this.readyState!=="closed"&&(this._polling=!1,this.emitReserved("pollComplete"),this.readyState==="open"&&this._poll())}doClose(){const r=()=>{this.write([{type:"close"}])};this.readyState==="open"?r():this.once("open",r)}write(r){this.writable=!1,bg(r,s=>{this.doWrite(s,()=>{this.writable=!0,this.emitReserved("drain")})})}uri(){const r=this.opts.secure?"https":"http",s=this.query||{};return this.opts.timestampRequests!==!1&&(s[this.opts.timestampParam]=Jp()),!this.supportsBinary&&!s.sid&&(s.b64=1),this.createUri(r,s)}}let Zp=!1;try{Zp=typeof XMLHttpRequest<"u"&&"withCredentials"in new XMLHttpRequest}catch{}const zg=Zp;function Lg(){}class Bg extends Dg{constructor(r){if(super(r),typeof location<"u"){const s=location.protocol==="https:";let a=location.port;a||(a=s?"443":"80"),this.xd=typeof location<"u"&&r.hostname!==location.hostname||a!==r.port}}doWrite(r,s){const a=this.request({method:"POST",data:r});a.on("success",s),a.on("error",(p,_)=>{this.onError("xhr post error",p,_)})}doPoll(){const r=this.request();r.on("data",this.onData.bind(this)),r.on("error",(s,a)=>{this.onError("xhr poll error",s,a)}),this.pollXhr=r}}class Pr extends $t{constructor(r,s,a){super(),this.createRequest=r,Gi(this,a),this._opts=a,this._method=a.method||"GET",this._uri=s,this._data=a.data!==void 0?a.data:null,this._create()}_create(){var r;const s=Yp(this._opts,"agent","pfx","key","passphrase","cert","ca","ciphers","rejectUnauthorized","autoUnref");s.xdomain=!!this._opts.xd;const a=this._xhr=this.createRequest(s);try{a.open(this._method,this._uri,!0);try{if(this._opts.extraHeaders){a.setDisableHeaderCheck&&a.setDisableHeaderCheck(!0);for(let p in this._opts.extraHeaders)this._opts.extraHeaders.hasOwnProperty(p)&&a.setRequestHeader(p,this._opts.extraHeaders[p])}}catch{}if(this._method==="POST")try{a.setRequestHeader("Content-type","text/plain;charset=UTF-8")}catch{}try{a.setRequestHeader("Accept","*/*")}catch{}(r=this._opts.cookieJar)===null||r===void 0||r.addCookies(a),"withCredentials"in a&&(a.withCredentials=this._opts.withCredentials),this._opts.requestTimeout&&(a.timeout=this._opts.requestTimeout),a.onreadystatechange=()=>{var p;a.readyState===3&&((p=this._opts.cookieJar)===null||p===void 0||p.parseCookies(a.getResponseHeader("set-cookie"))),a.readyState===4&&(a.status===200||a.status===1223?this._onLoad():this.setTimeoutFn(()=>{this._onError(typeof a.status=="number"?a.status:0)},0))},a.send(this._data)}catch(p){this.setTimeoutFn(()=>{this._onError(p)},0);return}typeof document<"u"&&(this._index=Pr.requestsCount++,Pr.requests[this._index]=this)}_onError(r){this.emitReserved("error",r,this._xhr),this._cleanup(!0)}_cleanup(r){if(!(typeof this._xhr>"u"||this._xhr===null)){if(this._xhr.onreadystatechange=Lg,r)try{this._xhr.abort()}catch{}typeof document<"u"&&delete Pr.requests[this._index],this._xhr=null}}_onLoad(){const r=this._xhr.responseText;r!==null&&(this.emitReserved("data",r),this.emitReserved("success"),this._cleanup())}abort(){this._cleanup()}}Pr.requestsCount=0;Pr.requests={};if(typeof document<"u"){if(typeof attachEvent=="function")attachEvent("onunload",gp);else if(typeof addEventListener=="function"){const d="onpagehide"in ur?"pagehide":"unload";addEventListener(d,gp,!1)}}function gp(){for(let d in Pr.requests)Pr.requests.hasOwnProperty(d)&&Pr.requests[d].abort()}const Ng=(function(){const d=ef({xdomain:!1});return d&&d.responseType!==null})();class Ug extends Bg{constructor(r){super(r);const s=r&&r.forceBase64;this.supportsBinary=Ng&&!s}request(r={}){return Object.assign(r,{xd:this.xd},this.opts),new Pr(ef,this.uri(),r)}}function ef(d){const r=d.xdomain;try{if(typeof XMLHttpRequest<"u"&&(!r||zg))return new XMLHttpRequest}catch{}if(!r)try{return new ur[["Active"].concat("Object").join("X")]("Microsoft.XMLHTTP")}catch{}}const tf=typeof navigator<"u"&&typeof navigator.product=="string"&&navigator.product.toLowerCase()==="reactnative";class Fg extends ko{get name(){return"websocket"}doOpen(){const r=this.uri(),s=this.opts.protocols,a=tf?{}:Yp(this.opts,"agent","perMessageDeflate","pfx","key","passphrase","cert","ca","ciphers","rejectUnauthorized","localAddress","protocolVersion","origin","maxPayload","family","checkServerIdentity");this.opts.extraHeaders&&(a.headers=this.opts.extraHeaders);try{this.ws=this.createSocket(r,s,a)}catch(p){return this.emitReserved("error",p)}this.ws.binaryType=this.socket.binaryType,this.addEventListeners()}addEventListeners(){this.ws.onopen=()=>{this.opts.autoUnref&&this.ws._socket.unref(),this.onOpen()},this.ws.onclose=r=>this.onClose({description:"websocket connection closed",context:r}),this.ws.onmessage=r=>this.onData(r.data),this.ws.onerror=r=>this.onError("websocket error",r)}write(r){this.writable=!1;for(let s=0;s<r.length;s++){const a=r[s],p=s===r.length-1;xo(a,this.supportsBinary,_=>{try{this.doWrite(a,_)}catch{}p&&Vi(()=>{this.writable=!0,this.emitReserved("drain")},this.setTimeoutFn)})}}doClose(){typeof this.ws<"u"&&(this.ws.onerror=()=>{},this.ws.close(),this.ws=null)}uri(){const r=this.opts.secure?"wss":"ws",s=this.query||{};return this.opts.timestampRequests&&(s[this.opts.timestampParam]=Jp()),this.supportsBinary||(s.b64=1),this.createUri(r,s)}}const Za=ur.WebSocket||ur.MozWebSocket;class Vg extends Fg{createSocket(r,s,a){return tf?new Za(r,s,a):s?new Za(r,s):new Za(r)}doWrite(r,s){this.ws.send(s)}}class Gg extends ko{get name(){return"webtransport"}doOpen(){try{this._transport=new WebTransport(this.createUri("https"),this.opts.transportOptions[this.name])}catch(r){return this.emitReserved("error",r)}this._transport.closed.then(()=>{this.onClose()}).catch(r=>{this.onError("webtransport error",r)}),this._transport.ready.then(()=>{this._transport.createBidirectionalStream().then(r=>{const s=Eg(Number.MAX_SAFE_INTEGER,this.socket.binaryType),a=r.readable.pipeThrough(s).getReader(),p=Tg();p.readable.pipeTo(r.writable),this._writer=p.writable.getWriter();const _=()=>{a.read().then(({done:R,value:S})=>{R||(this.onPacket(S),_())}).catch(R=>{})};_();const C={type:"open"};this.query.sid&&(C.data=`{"sid":"${this.query.sid}"}`),this._writer.write(C).then(()=>this.onOpen())})})}write(r){this.writable=!1;for(let s=0;s<r.length;s++){const a=r[s],p=s===r.length-1;this._writer.write(a).then(()=>{p&&Vi(()=>{this.writable=!0,this.emitReserved("drain")},this.setTimeoutFn)})}}doClose(){var r;(r=this._transport)===null||r===void 0||r.close()}}const qg={websocket:Vg,webtransport:Gg,polling:Ug},Wg=/^(?:(?![^:@\/?#]+:[^:@\/]*@)(http|https|ws|wss):\/\/)?((?:(([^:@\/?#]*)(?::([^:@\/?#]*))?)?@)?((?:[a-f0-9]{0,4}:){2,7}[a-f0-9]{0,4}|[^:\/?#]*)(?::(\d*))?)(((\/(?:[^?#](?![^?#\/]*\.[^?#\/.]+(?:[?#]|$)))*\/?)?([^?#\/]*))(?:\?([^#]*))?(?:#(.*))?)/,Hg=["source","protocol","authority","userInfo","user","password","host","port","relative","path","directory","file","query","anchor"];function mo(d){if(d.length>8e3)throw"URI too long";const r=d,s=d.indexOf("["),a=d.indexOf("]");s!=-1&&a!=-1&&(d=d.substring(0,s)+d.substring(s,a).replace(/:/g,";")+d.substring(a,d.length));let p=Wg.exec(d||""),_={},C=14;for(;C--;)_[Hg[C]]=p[C]||"";return s!=-1&&a!=-1&&(_.source=r,_.host=_.host.substring(1,_.host.length-1).replace(/;/g,":"),_.authority=_.authority.replace("[","").replace("]","").replace(/;/g,":"),_.ipv6uri=!0),_.pathNames=jg(_,_.path),_.queryKey=Kg(_,_.query),_}function jg(d,r){const s=/\/{2,9}/g,a=r.replace(s,"/").split("/");return(r.slice(0,1)=="/"||r.length===0)&&a.splice(0,1),r.slice(-1)=="/"&&a.splice(a.length-1,1),a}function Kg(d,r){const s={};return r.replace(/(?:^|&)([^&=]*)=?([^&]*)/g,function(a,p,_){p&&(s[p]=_)}),s}const go=typeof addEventListener=="function"&&typeof removeEventListener=="function",zi=[];go&&addEventListener("offline",()=>{zi.forEach(d=>d())},!1);class ds extends $t{constructor(r,s){if(super(),this.binaryType=xg,this.writeBuffer=[],this._prevBufferLen=0,this._pingInterval=-1,this._pingTimeout=-1,this._maxPayload=-1,this._pingTimeoutTime=1/0,r&&typeof r=="object"&&(s=r,r=null),r){const a=mo(r);s.hostname=a.host,s.secure=a.protocol==="https"||a.protocol==="wss",s.port=a.port,a.query&&(s.query=a.query)}else s.host&&(s.hostname=mo(s.host).host);Gi(this,s),this.secure=s.secure!=null?s.secure:typeof location<"u"&&location.protocol==="https:",s.hostname&&!s.port&&(s.port=this.secure?"443":"80"),this.hostname=s.hostname||(typeof location<"u"?location.hostname:"localhost"),this.port=s.port||(typeof location<"u"&&location.port?location.port:this.secure?"443":"80"),this.transports=[],this._transportsByName={},s.transports.forEach(a=>{const p=a.prototype.name;this.transports.push(p),this._transportsByName[p]=a}),this.opts=Object.assign({path:"/engine.io",agent:!1,withCredentials:!1,upgrade:!0,timestampParam:"t",rememberUpgrade:!1,addTrailingSlash:!0,rejectUnauthorized:!0,perMessageDeflate:{threshold:1024},transportOptions:{},closeOnBeforeunload:!1},s),this.opts.path=this.opts.path.replace(/\/$/,"")+(this.opts.addTrailingSlash?"/":""),typeof this.opts.query=="string"&&(this.opts.query=Og(this.opts.query)),go&&(this.opts.closeOnBeforeunload&&(this._beforeunloadEventListener=()=>{this.transport&&(this.transport.removeAllListeners(),this.transport.close())},addEventListener("beforeunload",this._beforeunloadEventListener,!1)),this.hostname!=="localhost"&&(this._offlineEventListener=()=>{this._onClose("transport close",{description:"network connection lost"})},zi.push(this._offlineEventListener))),this.opts.withCredentials&&(this._cookieJar=void 0),this._open()}createTransport(r){const s=Object.assign({},this.opts.query);s.EIO=Xp,s.transport=r,this.id&&(s.sid=this.id);const a=Object.assign({},this.opts,{query:s,socket:this,hostname:this.hostname,secure:this.secure,port:this.port},this.opts.transportOptions[r]);return new this._transportsByName[r](a)}_open(){if(this.transports.length===0){this.setTimeoutFn(()=>{this.emitReserved("error","No transports available")},0);return}const r=this.opts.rememberUpgrade&&ds.priorWebsocketSuccess&&this.transports.indexOf("websocket")!==-1?"websocket":this.transports[0];this.readyState="opening";const s=this.createTransport(r);s.open(),this.setTransport(s)}setTransport(r){this.transport&&this.transport.removeAllListeners(),this.transport=r,r.on("drain",this._onDrain.bind(this)).on("packet",this._onPacket.bind(this)).on("error",this._onError.bind(this)).on("close",s=>this._onClose("transport close",s))}onOpen(){this.readyState="open",ds.priorWebsocketSuccess=this.transport.name==="websocket",this.emitReserved("open"),this.flush()}_onPacket(r){if(this.readyState==="opening"||this.readyState==="open"||this.readyState==="closing")switch(this.emitReserved("packet",r),this.emitReserved("heartbeat"),r.type){case"open":this.onHandshake(JSON.parse(r.data));break;case"ping":this._sendPacket("pong"),this.emitReserved("ping"),this.emitReserved("pong"),this._resetPingTimeout();break;case"error":const s=new Error("server error");s.code=r.data,this._onError(s);break;case"message":this.emitReserved("data",r.data),this.emitReserved("message",r.data);break}}onHandshake(r){this.emitReserved("handshake",r),this.id=r.sid,this.transport.query.sid=r.sid,this._pingInterval=r.pingInterval,this._pingTimeout=r.pingTimeout,this._maxPayload=r.maxPayload,this.onOpen(),this.readyState!=="closed"&&this._resetPingTimeout()}_resetPingTimeout(){this.clearTimeoutFn(this._pingTimeoutTimer);const r=this._pingInterval+this._pingTimeout;this._pingTimeoutTime=Date.now()+r,this._pingTimeoutTimer=this.setTimeoutFn(()=>{this._onClose("ping timeout")},r),this.opts.autoUnref&&this._pingTimeoutTimer.unref()}_onDrain(){this.writeBuffer.splice(0,this._prevBufferLen),this._prevBufferLen=0,this.writeBuffer.length===0?this.emitReserved("drain"):this.flush()}flush(){if(this.readyState!=="closed"&&this.transport.writable&&!this.upgrading&&this.writeBuffer.length){const r=this._getWritablePackets();this.transport.send(r),this._prevBufferLen=r.length,this.emitReserved("flush")}}_getWritablePackets(){if(!(this._maxPayload&&this.transport.name==="polling"&&this.writeBuffer.length>1))return this.writeBuffer;let s=1;for(let a=0;a<this.writeBuffer.length;a++){const p=this.writeBuffer[a].data;if(p&&(s+=Ag(p)),a>0&&s>this._maxPayload)return this.writeBuffer.slice(0,a);s+=2}return this.writeBuffer}_hasPingExpired(){if(!this._pingTimeoutTime)return!0;const r=Date.now()>this._pingTimeoutTime;return r&&(this._pingTimeoutTime=0,Vi(()=>{this._onClose("ping timeout")},this.setTimeoutFn)),r}write(r,s,a){return this._sendPacket("message",r,s,a),this}send(r,s,a){return this._sendPacket("message",r,s,a),this}_sendPacket(r,s,a,p){if(typeof s=="function"&&(p=s,s=void 0),typeof a=="function"&&(p=a,a=null),this.readyState==="closing"||this.readyState==="closed")return;a=a||{},a.compress=a.compress!==!1;const _={type:r,data:s,options:a};this.emitReserved("packetCreate",_),this.writeBuffer.push(_),p&&this.once("flush",p),this.flush()}close(){const r=()=>{this._onClose("forced close"),this.transport.close()},s=()=>{this.off("upgrade",s),this.off("upgradeError",s),r()},a=()=>{this.once("upgrade",s),this.once("upgradeError",s)};return(this.readyState==="opening"||this.readyState==="open")&&(this.readyState="closing",this.writeBuffer.length?this.once("drain",()=>{this.upgrading?a():r()}):this.upgrading?a():r()),this}_onError(r){if(ds.priorWebsocketSuccess=!1,this.opts.tryAllTransports&&this.transports.length>1&&this.readyState==="opening")return this.transports.shift(),this._open();this.emitReserved("error",r),this._onClose("transport error",r)}_onClose(r,s){if(this.readyState==="opening"||this.readyState==="open"||this.readyState==="closing"){if(this.clearTimeoutFn(this._pingTimeoutTimer),this.transport.removeAllListeners("close"),this.transport.close(),this.transport.removeAllListeners(),go&&(this._beforeunloadEventListener&&removeEventListener("beforeunload",this._beforeunloadEventListener,!1),this._offlineEventListener)){const a=zi.indexOf(this._offlineEventListener);a!==-1&&zi.splice(a,1)}this.readyState="closed",this.id=null,this.emitReserved("close",r,s),this.writeBuffer=[],this._prevBufferLen=0}}}ds.protocol=Xp;class Qg extends ds{constructor(){super(...arguments),this._upgrades=[]}onOpen(){if(super.onOpen(),this.readyState==="open"&&this.opts.upgrade)for(let r=0;r<this._upgrades.length;r++)this._probe(this._upgrades[r])}_probe(r){let s=this.createTransport(r),a=!1;ds.priorWebsocketSuccess=!1;const p=()=>{a||(s.send([{type:"ping",data:"probe"}]),s.once("packet",te=>{if(!a)if(te.type==="pong"&&te.data==="probe"){if(this.upgrading=!0,this.emitReserved("upgrading",s),!s)return;ds.priorWebsocketSuccess=s.name==="websocket",this.transport.pause(()=>{a||this.readyState!=="closed"&&(z(),this.setTransport(s),s.send([{type:"upgrade"}]),this.emitReserved("upgrade",s),s=null,this.upgrading=!1,this.flush())})}else{const j=new Error("probe error");j.transport=s.name,this.emitReserved("upgradeError",j)}}))};function _(){a||(a=!0,z(),s.close(),s=null)}const C=te=>{const j=new Error("probe error: "+te);j.transport=s.name,_(),this.emitReserved("upgradeError",j)};function R(){C("transport closed")}function S(){C("socket closed")}function N(te){s&&te.name!==s.name&&_()}const z=()=>{s.removeListener("open",p),s.removeListener("error",C),s.removeListener("close",R),this.off("close",S),this.off("upgrading",N)};s.once("open",p),s.once("error",C),s.once("close",R),this.once("close",S),this.once("upgrading",N),this._upgrades.indexOf("webtransport")!==-1&&r!=="webtransport"?this.setTimeoutFn(()=>{a||s.open()},200):s.open()}onHandshake(r){this._upgrades=this._filterUpgrades(r.upgrades),super.onHandshake(r)}_filterUpgrades(r){const s=[];for(let a=0;a<r.length;a++)~this.transports.indexOf(r[a])&&s.push(r[a]);return s}}let Xg=class extends Qg{constructor(r,s={}){const a=typeof r=="object"?r:s;(!a.transports||a.transports&&typeof a.transports[0]=="string")&&(a.transports=(a.transports||["polling","websocket","webtransport"]).map(p=>qg[p]).filter(p=>!!p)),super(r,a)}};function Yg(d,r="",s){let a=d;s=s||typeof location<"u"&&location,d==null&&(d=s.protocol+"//"+s.host),typeof d=="string"&&(d.charAt(0)==="/"&&(d.charAt(1)==="/"?d=s.protocol+d:d=s.host+d),/^(https?|wss?):\/\//.test(d)||(typeof s<"u"?d=s.protocol+"//"+d:d="https://"+d),a=mo(d)),a.port||(/^(http|ws)$/.test(a.protocol)?a.port="80":/^(http|ws)s$/.test(a.protocol)&&(a.port="443")),a.path=a.path||"/";const _=a.host.indexOf(":")!==-1?"["+a.host+"]":a.host;return a.id=a.protocol+"://"+_+":"+a.port+r,a.href=a.protocol+"://"+_+(s&&s.port===a.port?"":":"+a.port),a}const Jg=typeof ArrayBuffer=="function",Zg=d=>typeof ArrayBuffer.isView=="function"?ArrayBuffer.isView(d):d.buffer instanceof ArrayBuffer,rf=Object.prototype.toString,ey=typeof Blob=="function"||typeof Blob<"u"&&rf.call(Blob)==="[object BlobConstructor]",ty=typeof File=="function"||typeof File<"u"&&rf.call(File)==="[object FileConstructor]";function Ro(d){return Jg&&(d instanceof ArrayBuffer||Zg(d))||ey&&d instanceof Blob||ty&&d instanceof File}function Li(d,r){if(!d||typeof d!="object")return!1;if(Array.isArray(d)){for(let s=0,a=d.length;s<a;s++)if(Li(d[s]))return!0;return!1}if(Ro(d))return!0;if(d.toJSON&&typeof d.toJSON=="function"&&arguments.length===1)return Li(d.toJSON(),!0);for(const s in d)if(Object.prototype.hasOwnProperty.call(d,s)&&Li(d[s]))return!0;return!1}function ry(d){const r=[],s=d.data,a=d;return a.data=yo(s,r),a.attachments=r.length,{packet:a,buffers:r}}function yo(d,r){if(!d)return d;if(Ro(d)){const s={_placeholder:!0,num:r.length};return r.push(d),s}else if(Array.isArray(d)){const s=new Array(d.length);for(let a=0;a<d.length;a++)s[a]=yo(d[a],r);return s}else if(typeof d=="object"&&!(d instanceof Date)){const s={};for(const a in d)Object.prototype.hasOwnProperty.call(d,a)&&(s[a]=yo(d[a],r));return s}return d}function sy(d,r){return d.data=wo(d.data,r),delete d.attachments,d}function wo(d,r){if(!d)return d;if(d&&d._placeholder===!0){if(typeof d.num=="number"&&d.num>=0&&d.num<r.length)return r[d.num];throw new Error("illegal attachments")}else if(Array.isArray(d))for(let s=0;s<d.length;s++)d[s]=wo(d[s],r);else if(typeof d=="object")for(const s in d)Object.prototype.hasOwnProperty.call(d,s)&&(d[s]=wo(d[s],r));return d}const ny=["connect","connect_error","disconnect","disconnecting","newListener","removeListener"];var Xe;(function(d){d[d.CONNECT=0]="CONNECT",d[d.DISCONNECT=1]="DISCONNECT",d[d.EVENT=2]="EVENT",d[d.ACK=3]="ACK",d[d.CONNECT_ERROR=4]="CONNECT_ERROR",d[d.BINARY_EVENT=5]="BINARY_EVENT",d[d.BINARY_ACK=6]="BINARY_ACK"})(Xe||(Xe={}));class iy{constructor(r){this.replacer=r}encode(r){return(r.type===Xe.EVENT||r.type===Xe.ACK)&&Li(r)?this.encodeAsBinary({type:r.type===Xe.EVENT?Xe.BINARY_EVENT:Xe.BINARY_ACK,nsp:r.nsp,data:r.data,id:r.id}):[this.encodeAsString(r)]}encodeAsString(r){let s=""+r.type;return(r.type===Xe.BINARY_EVENT||r.type===Xe.BINARY_ACK)&&(s+=r.attachments+"-"),r.nsp&&r.nsp!=="/"&&(s+=r.nsp+","),r.id!=null&&(s+=r.id),r.data!=null&&(s+=JSON.stringify(r.data,this.replacer)),s}encodeAsBinary(r){const s=ry(r),a=this.encodeAsString(s.packet),p=s.buffers;return p.unshift(a),p}}class Ao extends $t{constructor(r){super(),this.opts=Object.assign({reviver:void 0,maxAttachments:10},typeof r=="function"?{reviver:r}:r)}add(r){let s;if(typeof r=="string"){if(this.reconstructor)throw new Error("got plaintext data when reconstructing a packet");s=this.decodeString(r);const a=s.type===Xe.BINARY_EVENT;a||s.type===Xe.BINARY_ACK?(s.type=a?Xe.EVENT:Xe.ACK,this.reconstructor=new ay(s),s.attachments===0&&super.emitReserved("decoded",s)):super.emitReserved("decoded",s)}else if(Ro(r)||r.base64)if(this.reconstructor)s=this.reconstructor.takeBinaryData(r),s&&(this.reconstructor=null,super.emitReserved("decoded",s));else throw new Error("got binary data when not reconstructing a packet");else throw new Error("Unknown type: "+r)}decodeString(r){let s=0;const a={type:Number(r.charAt(0))};if(Xe[a.type]===void 0)throw new Error("unknown packet type "+a.type);if(a.type===Xe.BINARY_EVENT||a.type===Xe.BINARY_ACK){const _=s+1;for(;r.charAt(++s)!=="-"&&s!=r.length;);const C=r.substring(_,s);if(C!=Number(C)||r.charAt(s)!=="-")throw new Error("Illegal attachments");const R=Number(C);if(!oy(R)||R<0)throw new Error("Illegal attachments");if(R>this.opts.maxAttachments)throw new Error("too many attachments");a.attachments=R}if(r.charAt(s+1)==="/"){const _=s+1;for(;++s&&!(r.charAt(s)===","||s===r.length););a.nsp=r.substring(_,s)}else a.nsp="/";const p=r.charAt(s+1);if(p!==""&&Number(p)==p){const _=s+1;for(;++s;){const C=r.charAt(s);if(C==null||Number(C)!=C){--s;break}if(s===r.length)break}a.id=Number(r.substring(_,s+1))}if(r.charAt(++s)){const _=this.tryParse(r.substr(s));if(Ao.isPayloadValid(a.type,_))a.data=_;else throw new Error("invalid payload")}return a}tryParse(r){try{return JSON.parse(r,this.opts.reviver)}catch{return!1}}static isPayloadValid(r,s){switch(r){case Xe.CONNECT:return yp(s);case Xe.DISCONNECT:return s===void 0;case Xe.CONNECT_ERROR:return typeof s=="string"||yp(s);case Xe.EVENT:case Xe.BINARY_EVENT:return Array.isArray(s)&&(typeof s[0]=="number"||typeof s[0]=="string"&&ny.indexOf(s[0])===-1);case Xe.ACK:case Xe.BINARY_ACK:return Array.isArray(s)}}destroy(){this.reconstructor&&(this.reconstructor.finishedReconstruction(),this.reconstructor=null)}}class ay{constructor(r){this.packet=r,this.buffers=[],this.reconPack=r}takeBinaryData(r){if(this.buffers.push(r),this.buffers.length===this.reconPack.attachments){const s=sy(this.reconPack,this.buffers);return this.finishedReconstruction(),s}return null}finishedReconstruction(){this.reconPack=null,this.buffers=[]}}const oy=Number.isInteger||function(d){return typeof d=="number"&&isFinite(d)&&Math.floor(d)===d};function yp(d){return Object.prototype.toString.call(d)==="[object Object]"}const ly=Object.freeze(Object.defineProperty({__proto__:null,Decoder:Ao,Encoder:iy,get PacketType(){return Xe}},Symbol.toStringTag,{value:"Module"}));function Sr(d,r,s){return d.on(r,s),function(){d.off(r,s)}}const uy=Object.freeze({connect:1,connect_error:1,disconnect:1,disconnecting:1,newListener:1,removeListener:1});class sf extends $t{constructor(r,s,a){super(),this.connected=!1,this.recovered=!1,this.receiveBuffer=[],this.sendBuffer=[],this._queue=[],this._queueSeq=0,this.ids=0,this.acks={},this.flags={},this.io=r,this.nsp=s,a&&a.auth&&(this.auth=a.auth),this._opts=Object.assign({},a),this.io._autoConnect&&this.open()}get disconnected(){return!this.connected}subEvents(){if(this.subs)return;const r=this.io;this.subs=[Sr(r,"open",this.onopen.bind(this)),Sr(r,"packet",this.onpacket.bind(this)),Sr(r,"error",this.onerror.bind(this)),Sr(r,"close",this.onclose.bind(this))]}get active(){return!!this.subs}connect(){return this.connected?this:(this.subEvents(),this.io._reconnecting||this.io.open(),this.io._readyState==="open"&&this.onopen(),this)}open(){return this.connect()}send(...r){return r.unshift("message"),this.emit.apply(this,r),this}emit(r,...s){var a,p,_;if(uy.hasOwnProperty(r))throw new Error('"'+r.toString()+'" is a reserved event name');if(s.unshift(r),this._opts.retries&&!this.flags.fromQueue&&!this.flags.volatile)return this._addToQueue(s),this;const C={type:Xe.EVENT,data:s};if(C.options={},C.options.compress=this.flags.compress!==!1,typeof s[s.length-1]=="function"){const z=this.ids++,te=s.pop();this._registerAckCallback(z,te),C.id=z}const R=(p=(a=this.io.engine)===null||a===void 0?void 0:a.transport)===null||p===void 0?void 0:p.writable,S=this.connected&&!(!((_=this.io.engine)===null||_===void 0)&&_._hasPingExpired());return this.flags.volatile&&!R||(S?(this.notifyOutgoingListeners(C),this.packet(C)):this.sendBuffer.push(C)),this.flags={},this}_registerAckCallback(r,s){var a;const p=(a=this.flags.timeout)!==null&&a!==void 0?a:this._opts.ackTimeout;if(p===void 0){this.acks[r]=s;return}const _=this.io.setTimeoutFn(()=>{delete this.acks[r];for(let R=0;R<this.sendBuffer.length;R++)this.sendBuffer[R].id===r&&this.sendBuffer.splice(R,1);s.call(this,new Error("operation has timed out"))},p),C=(...R)=>{this.io.clearTimeoutFn(_),s.apply(this,R)};C.withError=!0,this.acks[r]=C}emitWithAck(r,...s){return new Promise((a,p)=>{const _=(C,R)=>C?p(C):a(R);_.withError=!0,s.push(_),this.emit(r,...s)})}_addToQueue(r){let s;typeof r[r.length-1]=="function"&&(s=r.pop());const a={id:this._queueSeq++,tryCount:0,pending:!1,args:r,flags:Object.assign({fromQueue:!0},this.flags)};r.push((p,..._)=>(this._queue[0],p!==null?a.tryCount>this._opts.retries&&(this._queue.shift(),s&&s(p)):(this._queue.shift(),s&&s(null,..._)),a.pending=!1,this._drainQueue())),this._queue.push(a),this._drainQueue()}_drainQueue(r=!1){if(!this.connected||this._queue.length===0)return;const s=this._queue[0];s.pending&&!r||(s.pending=!0,s.tryCount++,this.flags=s.flags,this.emit.apply(this,s.args))}packet(r){r.nsp=this.nsp,this.io._packet(r)}onopen(){typeof this.auth=="function"?this.auth(r=>{this._sendConnectPacket(r)}):this._sendConnectPacket(this.auth)}_sendConnectPacket(r){this.packet({type:Xe.CONNECT,data:this._pid?Object.assign({pid:this._pid,offset:this._lastOffset},r):r})}onerror(r){this.connected||this.emitReserved("connect_error",r)}onclose(r,s){this.connected=!1,delete this.id,this.emitReserved("disconnect",r,s),this._clearAcks()}_clearAcks(){Object.keys(this.acks).forEach(r=>{if(!this.sendBuffer.some(a=>String(a.id)===r)){const a=this.acks[r];delete this.acks[r],a.withError&&a.call(this,new Error("socket has been disconnected"))}})}onpacket(r){if(r.nsp===this.nsp)switch(r.type){case Xe.CONNECT:r.data&&r.data.sid?this.onconnect(r.data.sid,r.data.pid):this.emitReserved("connect_error",new Error("It seems you are trying to reach a Socket.IO server in v2.x with a v3.x client, but they are not compatible (more information here: https://socket.io/docs/v3/migrating-from-2-x-to-3-0/)"));break;case Xe.EVENT:case Xe.BINARY_EVENT:this.onevent(r);break;case Xe.ACK:case Xe.BINARY_ACK:this.onack(r);break;case Xe.DISCONNECT:this.ondisconnect();break;case Xe.CONNECT_ERROR:this.destroy();const a=new Error(r.data.message);a.data=r.data.data,this.emitReserved("connect_error",a);break}}onevent(r){const s=r.data||[];r.id!=null&&s.push(this.ack(r.id)),this.connected?this.emitEvent(s):this.receiveBuffer.push(Object.freeze(s))}emitEvent(r){if(this._anyListeners&&this._anyListeners.length){const s=this._anyListeners.slice();for(const a of s)a.apply(this,r)}super.emit.apply(this,r),this._pid&&r.length&&typeof r[r.length-1]=="string"&&(this._lastOffset=r[r.length-1])}ack(r){const s=this;let a=!1;return function(...p){a||(a=!0,s.packet({type:Xe.ACK,id:r,data:p}))}}onack(r){const s=this.acks[r.id];typeof s=="function"&&(delete this.acks[r.id],s.withError&&r.data.unshift(null),s.apply(this,r.data))}onconnect(r,s){this.id=r,this.recovered=s&&this._pid===s,this._pid=s,this.connected=!0,this.emitBuffered(),this._drainQueue(!0),this.emitReserved("connect")}emitBuffered(){this.receiveBuffer.forEach(r=>this.emitEvent(r)),this.receiveBuffer=[],this.sendBuffer.forEach(r=>{this.notifyOutgoingListeners(r),this.packet(r)}),this.sendBuffer=[]}ondisconnect(){this.destroy(),this.onclose("io server disconnect")}destroy(){this.subs&&(this.subs.forEach(r=>r()),this.subs=void 0),this.io._destroy(this)}disconnect(){return this.connected&&this.packet({type:Xe.DISCONNECT}),this.destroy(),this.connected&&this.onclose("io client disconnect"),this}close(){return this.disconnect()}compress(r){return this.flags.compress=r,this}get volatile(){return this.flags.volatile=!0,this}timeout(r){return this.flags.timeout=r,this}onAny(r){return this._anyListeners=this._anyListeners||[],this._anyListeners.push(r),this}prependAny(r){return this._anyListeners=this._anyListeners||[],this._anyListeners.unshift(r),this}offAny(r){if(!this._anyListeners)return this;if(r){const s=this._anyListeners;for(let a=0;a<s.length;a++)if(r===s[a])return s.splice(a,1),this}else this._anyListeners=[];return this}listenersAny(){return this._anyListeners||[]}onAnyOutgoing(r){return this._anyOutgoingListeners=this._anyOutgoingListeners||[],this._anyOutgoingListeners.push(r),this}prependAnyOutgoing(r){return this._anyOutgoingListeners=this._anyOutgoingListeners||[],this._anyOutgoingListeners.unshift(r),this}offAnyOutgoing(r){if(!this._anyOutgoingListeners)return this;if(r){const s=this._anyOutgoingListeners;for(let a=0;a<s.length;a++)if(r===s[a])return s.splice(a,1),this}else this._anyOutgoingListeners=[];return this}listenersAnyOutgoing(){return this._anyOutgoingListeners||[]}notifyOutgoingListeners(r){if(this._anyOutgoingListeners&&this._anyOutgoingListeners.length){const s=this._anyOutgoingListeners.slice();for(const a of s)a.apply(this,r.data)}}}function hn(d){d=d||{},this.ms=d.min||100,this.max=d.max||1e4,this.factor=d.factor||2,this.jitter=d.jitter>0&&d.jitter<=1?d.jitter:0,this.attempts=0}hn.prototype.duration=function(){var d=this.ms*Math.pow(this.factor,this.attempts++);if(this.jitter){var r=Math.random(),s=Math.floor(r*this.jitter*d);d=(Math.floor(r*10)&1)==0?d-s:d+s}return Math.min(d,this.max)|0};hn.prototype.reset=function(){this.attempts=0};hn.prototype.setMin=function(d){this.ms=d};hn.prototype.setMax=function(d){this.max=d};hn.prototype.setJitter=function(d){this.jitter=d};class vo extends $t{constructor(r,s){var a;super(),this.nsps={},this.subs=[],r&&typeof r=="object"&&(s=r,r=void 0),s=s||{},s.path=s.path||"/socket.io",this.opts=s,Gi(this,s),this.reconnection(s.reconnection!==!1),this.reconnectionAttempts(s.reconnectionAttempts||1/0),this.reconnectionDelay(s.reconnectionDelay||1e3),this.reconnectionDelayMax(s.reconnectionDelayMax||5e3),this.randomizationFactor((a=s.randomizationFactor)!==null&&a!==void 0?a:.5),this.backoff=new hn({min:this.reconnectionDelay(),max:this.reconnectionDelayMax(),jitter:this.randomizationFactor()}),this.timeout(s.timeout==null?2e4:s.timeout),this._readyState="closed",this.uri=r;const p=s.parser||ly;this.encoder=new p.Encoder,this.decoder=new p.Decoder,this._autoConnect=s.autoConnect!==!1,this._autoConnect&&this.open()}reconnection(r){return arguments.length?(this._reconnection=!!r,r||(this.skipReconnect=!0),this):this._reconnection}reconnectionAttempts(r){return r===void 0?this._reconnectionAttempts:(this._reconnectionAttempts=r,this)}reconnectionDelay(r){var s;return r===void 0?this._reconnectionDelay:(this._reconnectionDelay=r,(s=this.backoff)===null||s===void 0||s.setMin(r),this)}randomizationFactor(r){var s;return r===void 0?this._randomizationFactor:(this._randomizationFactor=r,(s=this.backoff)===null||s===void 0||s.setJitter(r),this)}reconnectionDelayMax(r){var s;return r===void 0?this._reconnectionDelayMax:(this._reconnectionDelayMax=r,(s=this.backoff)===null||s===void 0||s.setMax(r),this)}timeout(r){return arguments.length?(this._timeout=r,this):this._timeout}maybeReconnectOnOpen(){!this._reconnecting&&this._reconnection&&this.backoff.attempts===0&&this.reconnect()}open(r){if(~this._readyState.indexOf("open"))return this;this.engine=new Xg(this.uri,this.opts);const s=this.engine,a=this;this._readyState="opening",this.skipReconnect=!1;const p=Sr(s,"open",function(){a.onopen(),r&&r()}),_=R=>{this.cleanup(),this._readyState="closed",this.emitReserved("error",R),r?r(R):this.maybeReconnectOnOpen()},C=Sr(s,"error",_);if(this._timeout!==!1){const R=this._timeout,S=this.setTimeoutFn(()=>{p(),_(new Error("timeout")),s.close()},R);this.opts.autoUnref&&S.unref(),this.subs.push(()=>{this.clearTimeoutFn(S)})}return this.subs.push(p),this.subs.push(C),this}connect(r){return this.open(r)}onopen(){this.cleanup(),this._readyState="open",this.emitReserved("open");const r=this.engine;this.subs.push(Sr(r,"ping",this.onping.bind(this)),Sr(r,"data",this.ondata.bind(this)),Sr(r,"error",this.onerror.bind(this)),Sr(r,"close",this.onclose.bind(this)),Sr(this.decoder,"decoded",this.ondecoded.bind(this)))}onping(){this.emitReserved("ping")}ondata(r){try{this.decoder.add(r)}catch(s){this.onclose("parse error",s)}}ondecoded(r){Vi(()=>{this.emitReserved("packet",r)},this.setTimeoutFn)}onerror(r){this.emitReserved("error",r)}socket(r,s){let a=this.nsps[r];return a?this._autoConnect&&!a.active&&a.connect():(a=new sf(this,r,s),this.nsps[r]=a),a}_destroy(r){const s=Object.keys(this.nsps);for(const a of s)if(this.nsps[a].active)return;this._close()}_packet(r){const s=this.encoder.encode(r);for(let a=0;a<s.length;a++)this.engine.write(s[a],r.options)}cleanup(){this.subs.forEach(r=>r()),this.subs.length=0,this.decoder.destroy()}_close(){this.skipReconnect=!0,this._reconnecting=!1,this.onclose("forced close")}disconnect(){return this._close()}onclose(r,s){var a;this.cleanup(),(a=this.engine)===null||a===void 0||a.close(),this.backoff.reset(),this._readyState="closed",this.emitReserved("close",r,s),this._reconnection&&!this.skipReconnect&&this.reconnect()}reconnect(){if(this._reconnecting||this.skipReconnect)return this;const r=this;if(this.backoff.attempts>=this._reconnectionAttempts)this.backoff.reset(),this.emitReserved("reconnect_failed"),this._reconnecting=!1;else{const s=this.backoff.duration();this._reconnecting=!0;const a=this.setTimeoutFn(()=>{r.skipReconnect||(this.emitReserved("reconnect_attempt",r.backoff.attempts),!r.skipReconnect&&r.open(p=>{p?(r._reconnecting=!1,r.reconnect(),this.emitReserved("reconnect_error",p)):r.onreconnect()}))},s);this.opts.autoUnref&&a.unref(),this.subs.push(()=>{this.clearTimeoutFn(a)})}}onreconnect(){const r=this.backoff.attempts;this._reconnecting=!1,this.backoff.reset(),this.emitReserved("reconnect",r)}}const ti={};function Bi(d,r){typeof d=="object"&&(r=d,d=void 0),r=r||{};const s=Yg(d,r.path||"/socket.io"),a=s.source,p=s.id,_=s.path,C=ti[p]&&_ in ti[p].nsps,R=r.forceNew||r["force new connection"]||r.multiplex===!1||C;let S;return R?S=new vo(a,r):(ti[p]||(ti[p]=new vo(a,r)),S=ti[p]),s.query&&!r.query&&(r.query=s.queryKey),S.socket(s.path,r)}Object.assign(Bi,{Manager:vo,Socket:sf,io:Bi,connect:Bi});function dy({wsUrl:d,log:r}){let s=null;function a({authPayload:C,queryToken:R}){const S=Bi(d,{transports:["polling"],timeout:2e4,reconnection:!1,auth:C,query:R?{token:R}:void 0});return s=S,S}function p(){if(s){try{s.removeAllListeners(),s.connected?s.disconnect():s.close()}catch{}s=null}}function _(){return s}return{connectSocketRaw:a,cleanupSocket:p,getSocket:_}}const cy=d=>{if(window.audioCtx=d,d.state!=="suspended")return;const r=document.body,s=["touchstart","touchend","mousedown","keydown"];s.forEach(_=>r.addEventListener(_,a,!1));function a(){d.resume().then(p)}function p(){s.forEach(_=>r.removeEventListener(_,a))}};function Pt(d){this.init(d)}Pt.prototype.init=function(d){var r={encoding:"16bitInt",channels:1,sampleRate:16e3};this.option=Object.assign({},r,d),this.flush=this.flush.bind(this),this.maxValue=this.getMaxValue(),this.typedArray=this.getTypedArray(),this.playingBufferNode=null,this.scheduledBufferNode=null,this.createContext(),this.resetState()};Pt.prototype.getMaxValue=function(){var d={"8bitInt":128,"16bitInt":32768,"32bitInt":2147483648,"32bitFloat":1};return d[this.option.encoding]?d[this.option.encoding]:d["16bitInt"]};Pt.prototype.getTypedArray=function(){var d={"8bitInt":Int8Array,"16bitInt":Int16Array,"32bitInt":Int32Array,"32bitFloat":Float32Array};return d[this.option.encoding]?d[this.option.encoding]:d["16bitInt"]};Pt.prototype.createContext=function(){this.audioCtx=new(window.AudioContext||window.webkitAudioContext),this.audioCtx.resume(),this.audioCtx.onstatechange=()=>console.log("audioCtx.state",this.audioCtx.state),cy(this.audioCtx),this.gainNode=this.audioCtx.createGain(),this.gainNode.gain.value=1,this.gainNode.connect(this.audioCtx.destination),this.startTime=this.audioCtx.currentTime};Pt.prototype.resetState=function(){this.playingStartTime=-1,this.lastGotTimestamp=0,this.samples=new Float32Array,this.timeout=void 0,this.flag_request_stop=!1,this.startTime=0};Pt.prototype.isTypedArray=function(d){return d.byteLength&&d.buffer&&d.buffer.constructor==ArrayBuffer};Pt.prototype.feed=function(d){if(this.isTypedArray(d)){d=this.getFormatedValue(d);var r=new Float32Array(this.samples.length+d.length);r.set(this.samples,0),r.set(d,this.samples.length),this.samples=r,this.timeout||this.flush()}};Pt.prototype.getFormatedValue=function(r){var r=new this.typedArray(r.buffer),s=new Float32Array(r.length),a;for(a=0;a<r.length;a++)s[a]=r[a]/this.maxValue;return s};Pt.prototype.volume=function(d){this.gainNode.gain.value=d};Pt.prototype.destroy=function(){this.interval&&clearInterval(this.interval),this.samples=null,this.audioCtx.close(),this.audioCtx=null};Pt.prototype.getTimestamp=function(d){if(this.playingStartTime>=0){if(!d)return this.audioCtx.currentTime-this.playingStartTime;const r=this.lastGotTimestamp;return this.lastGotTimestamp+=d/1e3,r}return 0};Pt.prototype.setRequestStop=function(){this.flag_request_stop=!0};Pt.prototype.setOnEnd=function(d){this.onEnd=d};Pt.prototype.interrupt=function(d){this.scheduledBufferNode&&this.scheduledBufferNode.stop(0),this.playingBufferNode&&this.playingBufferNode.stop(0),this.ensuredClearTimeout(),this.resetState(),this.flag_request_stop=!1};Pt.prototype.ensuredSetTimeout=(function(){let d;return function(r,s){d=performance.now();const a=p=>{p-d>=s?(this.timeout=void 0,r()):this.timeout=requestAnimationFrame(a)};this.timeout=requestAnimationFrame(a)}})();Pt.prototype.ensuredClearTimeout=function(){this.timeout&&(cancelAnimationFrame(this.timeout),this.timeout=void 0)};Pt.prototype.flush=function(){if(this.samples.length){var d=this.audioCtx.createBufferSource(),r=this.samples.length/this.option.channels,s=this.audioCtx.createBuffer(this.option.channels,r,this.option.sampleRate),a,p,_,C,R;for(p=0;p<this.option.channels;p++)for(a=s.getChannelData(p),_=p,R=50,C=0;C<r;C++)a[C]=this.samples[_],C<50&&(a[C]=a[C]*C/50),C>=r-51&&(a[C]=a[C]*R--/50),_+=this.option.channels;if(this.startTime<this.audioCtx.currentTime&&(this.startTime=this.audioCtx.currentTime),this.samples=new Float32Array,d.buffer=s,d.connect(this.gainNode),d.start(this.startTime),this.playingBufferNode=this.scheduledBufferNode,this.scheduledBufferNode=d,this.playingStartTime<0&&(this.playingStartTime=this.startTime),this.startTime+=s.duration,this.flag_request_stop)this.flag_request_stop=!1,d.onended=()=>{this.resetState(),this.onEnd&&this.onEnd()};else{const S=(this.startTime-this.audioCtx.currentTime)*1e3;this.ensuredSetTimeout(this.flush,S-50)}}};function hy(d,r){const s=new Pt(d),a=s.destroy.bind(s);let p=!1;return s.destroy=()=>{if(!p){p=!0;try{a()}catch{}}},s.setOnEnd(()=>{p||r()}),s._isDestroyed=()=>p,s}function py({enableAudio:d,pcmOptions:r,log:s,onPlaybackComplete:a}){let p=null,_=null;function C(){if(!d||p)return p;const W={...qp,...r||{}};return p=hy(W,()=>{a()}),p}function R(){if(p){try{p.interrupt?.(),p.destroy?.()}catch{}p=null}}function S(W){const ne=C();if(ne)try{ne.feed(W)}catch(fe){s("feedAudio: player.feed() failed",fe),a()}}function N(){if(!p){a();return}try{p.setRequestStop(),p.playingBufferNode||p.scheduledBufferNode||a()}catch(W){s("requestStop: setRequestStop() failed",W),a()}}function z(){R()}function te(){if(p)try{const W=p.audioCtx;W?.state==="running"&&W.suspend()}catch(W){s("pauseAudioPlayback: audioCtx.suspend() failed",W)}}async function j(){const W=C();if(W)try{const ne=W.audioCtx;ne?.state==="suspended"&&await ne.resume()}catch(ne){s("resumeAudioPlayback: audioCtx.resume() failed",ne)}}function se(W){_=W||null}function J(){return _}function Y(){return p?p._isDestroyed?.()??!0:!0}return{ensurePcmPlayer:C,destroyPcmPlayer:R,feedAudio:S,requestStop:N,interruptPlayback:z,pauseAudioPlayback:te,resumeAudioPlayback:j,attachAudioElement:se,getAudioElement:J,isDestroyed:Y}}function fy(d){const{wsUrl:r,restUrl:s,enableAudio:a,pcmOptions:p,debug:_,withCredentials:C,onPlaybackComplete:R}=d,S=ae.useCallback((...j)=>{_&&console.log("[RqmiiSDK]",...j)},[_]),N=ae.useRef(null),z=ae.useRef(null),te=ae.useRef(null);return N.current||(N.current=dy({wsUrl:r,log:S})),z.current||(z.current=py({enableAudio:a,pcmOptions:p,log:S,onPlaybackComplete:R})),te.current||(te.current=gg({restUrl:s,log:S,withCredentials:C})),ae.useEffect(()=>()=>{N.current?.cleanupSocket(),z.current?.destroyPcmPlayer()},[]),{socketMgrRef:N,audioMgrRef:z,sessionMgrRef:te,log:S}}function eo(d){return String(d||"").toLowerCase().replaceAll("-","_")}function my(d){if(!d)return null;if(d instanceof Uint8Array)return d;if(d instanceof ArrayBuffer)return new Uint8Array(d);if(typeof d=="object"&&d!==null){const r=d;if(r.buffer instanceof ArrayBuffer){const s=d,a=Number.isInteger(s.byteOffset)?s.byteOffset:0,p=Number.isInteger(s.byteLength)?s.byteLength:s.buffer.byteLength-a;return new Uint8Array(s.buffer,a,p)}if(r.type==="Buffer"&&Array.isArray(r.data))return new Uint8Array(r.data)}try{return new Uint8Array(d)}catch{return null}}function gy(d){const{socket:r,dispatch:s,stateRef:a,sessionIdRef:p,sessionAgentTypeRef:_,interruptedRef:C,manualDisconnectRef:R,chunkAccumulatorRef:S,clientToolsRef:N,audioMgrRef:z,enableAudio:te,cbRefs:j,eventsEmitter:se}=d,J=br,Y=z.current;r.on(J.DISCONNECT,W=>{if(s({type:"SET_CONNECTION_STATE",payload:pt.IDLE}),s({type:"SET_SESSION_READY",payload:!1}),j.current.onDisconnect?.(W),W==="io server disconnect"||W==="io client disconnect"||R.current){s({type:"SET_CONNECTION_STATE",payload:pt.ENDED});return}s({type:"SET_CONNECTION_STATE",payload:pt.FAILED}),s({type:"SET_ERROR",payload:"Connection lost"})}),r.on(J.SESSION_READY,W=>{s({type:"SET_SESSION_READY",payload:!0}),s({type:"SET_ERROR",payload:null}),W?.agentType&&s({type:"UPDATE_SESSION",payload:{agentType:eo(W.agentType)}})}),r.on(J.SESSION_JOINED,()=>{s({type:"SET_SESSION_READY",payload:!0}),s({type:"SET_ERROR",payload:null})}),r.on(J.SESSION_TERMINATED,()=>{Y.interruptPlayback(),s({type:"SET_AUDIO_PLAYING",payload:!1}),s({type:"SET_CONNECTION_STATE",payload:pt.ENDED}),s({type:"SET_SESSION_READY",payload:!1}),j.current.onSessionTerminated?.(),r.disconnect()}),r.on(J.TRANSCRIPT,W=>{const ne=W||null;s({type:"SET_TRANSCRIPT",payload:ne}),ne?.is_final&&ne?.text?.trim()&&(s({type:"ADD_MESSAGE",payload:{id:`transcript-${Date.now()}`,role:"user",text:ne.text.trim(),timestamp:new Date().toISOString()}}),s({type:"SET_PARTIAL_TRANSCRIPT",payload:null})),se.emit("transcript",ne??void 0),se.emit("partial_transcript",void 0)}),r.on(J.PARTIAL_TRANSCRIPT,W=>{const ne=typeof W=="string"?W:W?.text;if(typeof ne=="string"&&ne.length===0)return;const fe=W||null;s({type:"SET_PARTIAL_TRANSCRIPT",payload:fe}),se.emit("partial_transcript",fe??void 0)}),r.on(J.AGENT_RESPONSE_CHUNK,W=>{const{id:ne,text:fe}=S.current.addChunk(W?.requestId,W?.text);s({type:"SET_MESSAGES",payload:[...a.current.messages.filter(de=>de.id!==ne),{id:ne,role:"assistant",text:fe,streaming:!0,timestamp:new Date().toISOString()}]})}),r.on(J.AGENT_RESPONSE,W=>{const{id:ne,text:fe}=S.current.consume(W?.requestId,W?.text);s({type:"SET_MESSAGES",payload:[...a.current.messages.filter(de=>de.id!==ne),{id:ne,role:"assistant",text:fe,streaming:!1,timestamp:new Date().toISOString()}]})}),r.on(J.AVATAR_SPEAKING,()=>{s({type:"SET_AVATAR_SPEAKING",payload:!0})}),r.on(J.AVATAR_SPEAKING_DONE,()=>{s({type:"SET_AVATAR_SPEAKING",payload:!1})}),r.on(J.AGENT_AUDIO_CHUNK,W=>{if(!te||C.current)return;const ne=eo(_.current);if(ne==="cloud_avatar"||ne==="desktop_avatar"||ne==="text")return;const fe=my(W?.audio);fe&&(Y.feedAudio(fe),s({type:"SET_AUDIO_PLAYING",payload:!0}))}),r.on(J.AGENT_AUDIO_COMPLETE,()=>{if(!te)return;const W=eo(_.current);W==="cloud_avatar"||W==="desktop_avatar"||W==="text"||Y.requestStop()}),r.on(J.INTERRUPTED,()=>{const W=!Y.isDestroyed();C.current=!1,Y.interruptPlayback(),s({type:"SET_AUDIO_PLAYING",payload:!1}),W&&r.connected&&r.emit(J.AUDIO_PLAYBACK_COMPLETE,{session_id:p.current})}),r.on(J.AUTH_ERROR,W=>{s({type:"SET_CONNECTION_STATE",payload:pt.FAILED}),s({type:"SET_ERROR",payload:W?.message||"Authentication error"})}),r.on(J.ERROR,W=>{const ne=W?.code;if(!(ne==="TTS_ERROR"||ne==="STT_ERROR"||ne==="LLM_ERROR")){if(ne==="INSUFFICIENT_CREDITS"){s({type:"SET_CREDIT_EXHAUSTED",payload:{exhausted:!0,error:W?.message||"Insufficient credits to process this request."}}),j.current.onError?.(W);return}s({type:"SET_ERROR",payload:W?.message||W?.detail||"Server error"}),j.current.onError?.(W)}}),r.on(J.SESSION_EXPIRED,W=>{s({type:"SET_CONNECTION_STATE",payload:pt.ENDED}),s({type:"SET_SESSION_READY",payload:!1}),j.current.onSessionExpired?.(W)}),r.on(J.CREDITS_EXHAUSTED,()=>{s({type:"SET_CREDIT_EXHAUSTED",payload:{exhausted:!0,error:"This project has run out of credits."}}),s({type:"SET_CONNECTION_STATE",payload:pt.ENDED}),s({type:"SET_SESSION_READY",payload:!1}),R.current=!0;try{r.disconnect()}catch{}}),r.on(J.SESSION_STATE_CHANGED,W=>{W?.state&&s({type:"SET_SESSION_STATE",payload:W.state})}),r.on(J.LANGUAGE_CHANGED,W=>{const ne=W?.language;ne&&se.emit("language_changed",{language:ne})}),r.on(J.SHOW_LEAD_CAPTURE_FORM,W=>{const ne=Array.isArray(W?.fields)?W.fields:[],fe=W?.agentId;!fe||ne.length===0||s({type:"ADD_MESSAGE",payload:{id:`lead-form-${Date.now()}`,role:"lead_form",text:"",form:{agentId:fe,title:W?.title,fields:ne},timestamp:new Date().toISOString()}})}),r.on(J.MESSAGE_RATE_LIMITED,W=>{se.emit("message_rate_limited",W)}),r.on(J.CLIENT_TOOL_REQUEST,W=>{const ne=W?.executionId,fe=W?.toolName,de=W?.parameters??{},he=W?.waitForResponse!==!1;if(!fe)return;const pe=N.current[fe];if(!pe)return;const ce={minimize:()=>se.emit("minimize_chat"),maximize:()=>se.emit("maximize_chat")};he&&ne?pe(de,ce).then(Ve=>{r.emit(J.CLIENT_TOOL_RESULT,{executionId:ne,result:Ve})}).catch(Ve=>{r.emit(J.CLIENT_TOOL_RESULT,{executionId:ne,result:{error:Ve instanceof Error?Ve.message:String(Ve)}})}):pe(de,ce).catch(()=>{})})}class nf{listeners=new Map;on(r,s){return this.listeners.has(r)||this.listeners.set(r,new Set),this.listeners.get(r).add(s),()=>this.off(r,s)}once(r,s){const a=((...p)=>{this.off(r,a),s(...p)});return this.on(r,a)}off(r,s){this.listeners.get(r)?.delete(s)}emit(r,s){const a=this.listeners.get(r);if(a)for(const p of a)try{p(s)}catch{}}removeAllListeners(){this.listeners.clear()}}const af=ae.createContext(null);function of({children:d,wsUrl:r,restUrl:s,enableAudio:a=!0,pcmOptions:p,debug:_=!1,heartbeatIntervalSeconds:C=15,withCredentials:R=!1,onSessionExpired:S,onSessionTerminated:N,onError:z,onDisconnect:te}){const[j,se]=ae.useReducer(hp,po),J=ae.useRef(j),Y=ae.useCallback(be=>{J.current=hp(J.current,be),se(be)},[]),W=ae.useRef(!1),ne=ae.useRef(fg()),fe=ae.useRef(null),de=ae.useRef(po.session.agentType),he=ae.useRef(!1),pe=ae.useRef(new nf),ce=ae.useRef({}),Ve=ae.useRef({onSessionExpired:S,onSessionTerminated:N,onError:z,onDisconnect:te});ae.useEffect(()=>{Gp(),Ve.current={onSessionExpired:S,onSessionTerminated:N,onError:z,onDisconnect:te}},[S,N,z,te]),ae.useEffect(()=>{de.current=j.session.agentType},[j.session.agentType]),ae.useEffect(()=>{fe.current=j.session.sessionId},[j.session.sessionId]);const me=ae.useCallback(()=>{Y({type:"SET_AUDIO_PLAYING",payload:!1});const be=Ye.current?.getSocket();be?.connected&&be.emit(br.AUDIO_PLAYBACK_COMPLETE,{session_id:fe.current})},[]),{socketMgrRef:Ye,audioMgrRef:qe,sessionMgrRef:it}=fy({wsUrl:r,restUrl:s,enableAudio:a,pcmOptions:p,debug:_,withCredentials:R,onPlaybackComplete:me}),Je=ae.useCallback(be=>{gy({socket:be,dispatch:Y,stateRef:J,sessionIdRef:fe,sessionAgentTypeRef:de,interruptedRef:he,manualDisconnectRef:W,chunkAccumulatorRef:ne,clientToolsRef:ce,audioMgrRef:{current:qe.current},enableAudio:a,cbRefs:Ve,eventsEmitter:pe.current})},[a]),at=ae.useCallback(({authPayload:be,queryToken:Ze})=>new Promise((Bt,nr)=>{Ye.current?.cleanupSocket();const It=Ye.current.connectSocketRaw({authPayload:be,queryToken:Ze});Je(It),It.once("connect",()=>{Y({type:"SET_CONNECTION_STATE",payload:pt.CONNECTED}),Y({type:"SET_ERROR",payload:null}),Bt(It)}),It.once("connect_error",xr=>{Y({type:"SET_CONNECTION_STATE",payload:pt.FAILED}),Y({type:"SET_ERROR",payload:xr?.message||"Connection error"}),nr(xr)})}),[Je]),tt=ae.useCallback(({keepManualDisconnect:be=!1}={})=>{W.current=!0,he.current=!1,ne.current.clear(),qe.current.destroyPcmPlayer(),Ye.current.cleanupSocket(),be||(W.current=!1),Y({type:"HARD_RESET"})},[]),qt=ae.useCallback(async({apiKey:be,publicChatId:Ze,agentId:Bt,userId:nr,language:It="en",clientTools:xr,config:yt}={})=>{if(!r)throw new Error("Missing wsUrl in RqmiiAgentProvider");if(!be&&!Ze&&!Bt)throw new Error("Provide one of apiKey, publicChatId, or agentId");tt(),ce.current=xr??{},Y({type:"SET_CONNECTION_STATE",payload:pt.INITIALIZING}),Y({type:"SET_ERROR",payload:null});const Lr=mg();let Br;try{Br=await it.current.initializeSession({apiKey:be,publicChatId:Ze,agentId:Bt,userId:nr,language:It,timezone:Lr,config:yt})}catch(ir){const Wt=ir;throw Wt.status===401||Wt.status===403?(Y({type:"SET_CONNECTION_STATE",payload:pt.FAILED}),Y({type:"SET_ERROR",payload:Wt.message||"Authentication failed"})):Wt.status===402?(Y({type:"SET_CREDIT_EXHAUSTED",payload:{exhausted:!0,error:Wt.message||"Insufficient credits"}}),Y({type:"SET_CONNECTION_STATE",payload:pt.FAILED})):Wt.status===429?(Y({type:"SET_CONNECTION_STATE",payload:pt.FAILED}),Y({type:"SET_ERROR",payload:Wt.message||"Too many requests. Please try again later."})):(Y({type:"SET_CONNECTION_STATE",payload:pt.FAILED}),Y({type:"SET_ERROR",payload:Wt.message||"Failed to initialize session"})),ir}const Nt=Br;Y({type:"UPDATE_SESSION",payload:{sessionId:Nt.session_id,agentType:Nt.streaming_url?hi.CLOUD_AVATAR:j.session.agentType,streamingUrl:Nt.streaming_url||null,uniqueId:Nt.unique_id||null}}),Y({type:"SET_CONNECTION_STATE",payload:pt.CONNECTING}),Y({type:"SET_CLOUD_STREAM_STATE",payload:{state:Nt.streaming_url?Zt.CONNECTING:Zt.IDLE,error:null}}),W.current=!0;try{await at({authPayload:{token:Nt.session_token},queryToken:Nt.session_token}),W.current=!1}catch(ir){throw W.current=!1,ir}return Br},[at,tt,r,j.session.agentType]),xt=ae.useCallback(async({uniqueId:be})=>{if(!r)throw new Error("Missing wsUrl in RqmiiAgentProvider");if(!be)throw new Error("uniqueId is required");tt(),Y({type:"SET_CONNECTION_STATE",payload:pt.INITIALIZING}),Y({type:"SET_ERROR",payload:null});let Ze;try{Ze=await it.current.joinDesktopSession({uniqueId:be})}catch(nr){const It=nr;throw(It.status===401||It.status===403)&&(Y({type:"SET_CONNECTION_STATE",payload:pt.FAILED}),Y({type:"SET_ERROR",payload:It.message||"Authentication failed"})),It.status===402&&(Y({type:"SET_CREDIT_EXHAUSTED",payload:{exhausted:!0,error:It.message||"Insufficient credits"}}),Y({type:"SET_CONNECTION_STATE",payload:pt.FAILED})),It.status===429&&(Y({type:"SET_CONNECTION_STATE",payload:pt.FAILED}),Y({type:"SET_ERROR",payload:It.message||"Too many requests. Please try again later."})),nr}const Bt=Ze;Y({type:"UPDATE_SESSION",payload:{sessionId:Bt.session_id,uniqueId:be,role:"user",agentType:hi.DESKTOP_AVATAR}}),Y({type:"SET_CONNECTION_STATE",payload:pt.CONNECTING}),Y({type:"SET_CLOUD_STREAM_STATE",payload:{state:Zt.IDLE,error:null}}),W.current=!0;try{await at({authPayload:{token:Bt.session_token},queryToken:Bt.session_token}),W.current=!1}catch(nr){throw W.current=!1,nr}return Ze},[at,tt,r]),Ke=ae.useCallback(()=>tt({keepManualDisconnect:!0}),[tt]),We=ae.useCallback(async()=>{const be=Ye.current?.getSocket();return be&&j.isConnected&&(be.emit("end_session"),await new Promise(Ze=>setTimeout(Ze,150))),Ke(),{success:!0}},[Ke,j.isConnected]),st=ae.useCallback(()=>{const be=Ye.current?.getSocket();be?.connected?be.emit("end_session"):(Y({type:"SET_CONNECTION_STATE",payload:pt.ENDED}),Y({type:"SET_SESSION_READY",payload:!1}))},[]),ze=ae.useCallback((be,Ze={})=>{const Bt=Ye.current?.getSocket();return!Bt||!j.isConnected?!1:(Bt.emit(be,Ze),!0)},[j.isConnected]),Rt=ae.useCallback(be=>!be||!String(be).trim()?!1:(Y({type:"ADD_MESSAGE",payload:{id:`user-${Date.now()}`,role:"user",text:String(be),timestamp:new Date().toISOString()}}),ze(br.USER_MESSAGE,{message:String(be)})),[ze]),sr=ae.useCallback((be,Ze)=>{!Ze||!String(Ze).trim()||Y({type:"ADD_MESSAGE",payload:{id:`${be}-${Date.now()}`,role:be,text:String(Ze),timestamp:new Date().toISOString()}})},[]),Xr=ae.useCallback(be=>!be||!String(be).trim()?!1:ze(br.USER_MESSAGE,{message:String(be)}),[ze]),Vs=ae.useCallback(be=>ze(br.AUDIO_CHUNK,{audio:be}),[ze]),Yr=ae.useCallback(()=>ze(br.AUDIO_END,{}),[ze]),Jr=ae.useCallback(()=>(he.current=!0,qe.current.interruptPlayback(),Y({type:"SET_AUDIO_PLAYING",payload:!1}),ze(br.INTERRUPT,{})),[ze]),Gs=ae.useCallback(()=>ze(br.CLEAR_SESSION_HISTORY,{}),[ze]),rt=ae.useCallback(be=>be?ze(br.CHANGE_SESSION_LANGUAGE,{language:be}):!1,[ze]),Er=ae.useCallback((be={})=>ze(br.CLIENT_READY,be),[ze]),lt=ae.useCallback(()=>{ne.current.clear(),Y({type:"SET_MESSAGES",payload:[]})},[]),Zr=ae.useCallback(be=>{Y({type:"SET_MESSAGES",payload:be})},[]),er=ae.useCallback(()=>qe.current.resumeAudioPlayback(),[]),$r=ae.useCallback(()=>qe.current.pauseAudioPlayback(),[]),gt=ae.useCallback(be=>qe.current.attachAudioElement(be),[]),ft=ae.useCallback((be,Ze=null)=>{Y({type:"SET_CLOUD_STREAM_STATE",payload:{state:be,error:Ze?String(Ze):null}})},[]),At=ae.useCallback(async be=>{if(!s)throw new Error("Missing restUrl in RqmiiAgentProvider");try{const Ze=await it.current.fetchAgentConfig(be);return Y({type:"SET_AGENT_CONFIG",payload:Ze}),Ze}catch(Ze){throw Y({type:"SET_AGENT_CONFIG",payload:null}),Ze}},[s]),Ct=ae.useCallback(be=>{Object.keys(ce.current).length===0?ce.current=be:Object.assign(ce.current,be)},[]),es=ae.useCallback(be=>{const Ze=be.sessionId||fe.current;return Ze?it.current.submitFeedback({sessionId:Ze,rating:be.rating,feedback:be.feedback,endedBy:be.endedBy}):Promise.reject(new Error("No session id available for feedback"))},[]),ts=ae.useCallback(be=>{const Ze=be.sessionId||fe.current;return Ze?it.current.submitLead({agentId:be.agentId,sessionId:Ze,collectedData:be.collectedData}):Promise.reject(new Error("No session id available for lead capture"))},[]),qs=ae.useMemo(()=>pg(j.sessionState),[j.sessionState]),zr=ae.useMemo(()=>({...j,...qs,initializeSession:qt,joinDesktopSession:xt,disconnect:Ke,terminateSession:We,endSession:st,emit:ze,sendTextMessage:Rt,addLocalMessage:sr,emitUserMessage:Xr,sendAudioChunk:Vs,endAudioStream:Yr,interrupt:Jr,clearSessionHistory:Gs,changeSessionLanguage:rt,signalClientReady:Er,clearMessages:lt,setMessages:Zr,resumeAudioPlayback:er,pauseAudioPlayback:$r,attachAudioElement:gt,fetchAgentConfig:At,submitFeedback:es,submitLead:ts,setCloudStreamState:ft,registerClientTools:Ct,events:pe.current,audioElement:qe.current?.getAudioElement()??null,socket:Ye.current?.getSocket()??null}),[j,qs,qt,xt,Ke,We,st,ze,Rt,sr,Xr,Vs,Yr,Jr,Gs,rt,Er,lt,Zr,er,$r,gt,ft,Ct,es,ts]);return Jt.jsx(af.Provider,{value:zr,children:d})}function Fs(){const d=ae.useContext(af);if(!d)throw new Error("useRqmiiAgentContext must be used inside <RqmiiAgentProvider>");return d}function lf(){const d=Fs();return{connectionState:d.connectionState,isConnected:d.isConnected,isSessionReady:d.isSessionReady,error:d.error,session:d.session,creditExhausted:d.creditExhausted,creditError:d.creditError,sessionState:d.sessionState,isSessionTerminated:d.isSessionTerminated,isSessionTerminating:d.isSessionTerminating,isAgentThinking:d.isAgentThinking,isAgentSpeaking:d.isAgentSpeaking,isToolExecuting:d.isToolExecuting,agentConfig:d.agentConfig,initializeSession:d.initializeSession,joinDesktopSession:d.joinDesktopSession,disconnect:d.disconnect,terminateSession:d.terminateSession,endSession:d.endSession,interrupt:d.interrupt,clearSessionHistory:d.clearSessionHistory,changeSessionLanguage:d.changeSessionLanguage,signalClientReady:d.signalClientReady,fetchAgentConfig:d.fetchAgentConfig,submitFeedback:d.submitFeedback,registerClientTools:d.registerClientTools,events:d.events}}function yy(){const d=Fs();return{messages:d.messages,sendTextMessage:d.sendTextMessage,addLocalMessage:d.addLocalMessage,emitUserMessage:d.emitUserMessage,clearMessages:d.clearMessages}}function wy(){const d=Fs();return{sendAudioChunk:d.sendAudioChunk,endAudioStream:d.endAudioStream,isAudioPlaying:d.isAudioPlaying,transcript:d.transcript,partialTranscript:d.partialTranscript,interrupt:d.interrupt,resumeAudioPlayback:d.resumeAudioPlayback,pauseAudioPlayback:d.pauseAudioPlayback,attachAudioElement:d.attachAudioElement}}function uf(){const d=Fs(),r=d.cloudStream?.state||Zt.IDLE;return{streamingUrl:d.session.streamingUrl,isAvatarSpeaking:d.isAvatarSpeaking,speakingSource:"avatar_events",isCloudAvatar:d.session.agentType===hi.CLOUD_AVATAR,isDesktopAvatar:d.session.agentType===hi.DESKTOP_AVATAR,cloudStreamState:r,cloudStreamError:d.cloudStream?.error||null,isCloudStreamConnected:r===Zt.CONNECTED,isCloudStreamLoading:r===Zt.CONNECTING||r===Zt.LOADING,setCloudStreamState:d.setCloudStreamState}}var to={},ro={},ri={},wp;function df(){if(wp)return ri;wp=1,Object.defineProperty(ri,"__esModule",{value:!0}),ri.baseAssetPath=void 0;const r=typeof window<"u"&&typeof window.document<"u"?window.document.currentScript:null;let s="/";return r&&(s=r.src.replace(/#.*$/,"").replace(/\?.*$/,"").replace(/\/[^/]+$/,"/")),ri.baseAssetPath=s,ri}var si={},vp;function Io(){if(vp)return si;vp=1,Object.defineProperty(si,"__esModule",{value:!0}),si.defaultModelFetcher=void 0;const d=r=>fetch(r).then(s=>s.arrayBuffer());return si.defaultModelFetcher=d,si}var Wr={},ni={},_p;function pn(){if(_p)return ni;_p=1,Object.defineProperty(ni,"__esModule",{value:!0}),ni.log=void 0;const d=r=>s=>{console.log(`VAD | ${r} >`,s)};return ni.log={error:d("error"),debug:d("debug"),warn:d("warn")},ni}var ii={},bp;function qi(){if(bp)return ii;bp=1,Object.defineProperty(ii,"__esModule",{value:!0}),ii.Message=void 0;var d;return(function(r){r.AudioFrame="AUDIO_FRAME",r.SpeechStart="SPEECH_START",r.VADMisfire="VAD_MISFIRE",r.SpeechEnd="SPEECH_END",r.SpeechStop="SPEECH_STOP",r.SpeechRealStart="SPEECH_REAL_START",r.FrameProcessed="FRAME_PROCESSED"})(d||(ii.Message=d={})),ii}var Sp;function Mo(){if(Sp)return Wr;Sp=1,Object.defineProperty(Wr,"__esModule",{value:!0}),Wr.FrameProcessor=Wr.validateOptions=Wr.defaultFrameProcessorOptions=void 0;const d=pn(),r=qi();Wr.defaultFrameProcessorOptions={positiveSpeechThreshold:.3,negativeSpeechThreshold:.25,preSpeechPadMs:800,redemptionMs:1400,minSpeechMs:400,submitUserSpeechOnPause:!1};function s(C){(C.positiveSpeechThreshold<0||C.positiveSpeechThreshold>1)&&d.log.error("positiveSpeechThreshold should be a number between 0 and 1"),(C.negativeSpeechThreshold<0||C.negativeSpeechThreshold>C.positiveSpeechThreshold)&&d.log.error("negativeSpeechThreshold should be between 0 and positiveSpeechThreshold"),C.preSpeechPadMs<0&&d.log.error("preSpeechPadMs should be positive"),C.redemptionMs<0&&d.log.error("redemptionMs should be positive"),C.minSpeechMs<0&&d.log.error("minSpeechMs should be positive")}Wr.validateOptions=s;const a=C=>{const R=C.reduce((N,z)=>(N.push(N.at(-1)+z.length),N),[0]),S=new Float32Array(R.at(-1));return C.forEach((N,z)=>{const te=R[z];S.set(N,te)}),S};function p(C,R){const S=Math.floor(C.redemptionMs/R),N=Math.floor(C.preSpeechPadMs/R),z=Math.floor(C.minSpeechMs/R);return{redemptionFrames:S,preSpeechPadFrames:N,minSpeechFrames:z}}class _{constructor(R,S,N,z){this.modelProcessFunc=R,this.modelResetFunc=S,this.options=N,this.msPerFrame=z,this.speaking=!1,this.redemptionCounter=0,this.speechFrameCount=0,this.active=!1,this.speechRealStartFired=!1,this.setOptions=J=>{this.options={...this.options,...J};const{redemptionFrames:Y,preSpeechPadFrames:W,minSpeechFrames:ne}=p(this.options,this.msPerFrame);this.redemptionFrames=Y,this.preSpeechPadFrames=W,this.minSpeechFrames=ne},this.reset=()=>{this.speaking=!1,this.speechRealStartFired=!1,this.audioBuffer=[],this.modelResetFunc(),this.redemptionCounter=0,this.speechFrameCount=0},this.pause=J=>{this.active=!1,this.options.submitUserSpeechOnPause?this.endSegment(J):this.reset()},this.resume=()=>{this.active=!0},this.endSegment=J=>{const Y=this.audioBuffer;this.audioBuffer=[];const W=this.speaking;if(this.reset(),W)if(Y.reduce((fe,de)=>de.isSpeech?fe+1:fe,0)>=this.minSpeechFrames){const fe=a(Y.map(de=>de.frame));J({msg:r.Message.SpeechEnd,audio:fe})}else J({msg:r.Message.VADMisfire});return{}},this.process=async(J,Y)=>{if(!this.active)return;const W=await this.modelProcessFunc(J),ne=W.isSpeech>=this.options.positiveSpeechThreshold;if(Y({probs:W,msg:r.Message.FrameProcessed,frame:J}),this.audioBuffer.push({frame:J,isSpeech:ne}),ne&&(this.speechFrameCount++,this.redemptionCounter=0),ne&&!this.speaking&&(this.speaking=!0,Y({msg:r.Message.SpeechStart})),this.speaking&&this.speechFrameCount===this.minSpeechFrames&&!this.speechRealStartFired&&(this.speechRealStartFired=!0,Y({msg:r.Message.SpeechRealStart})),W.isSpeech<this.options.negativeSpeechThreshold&&this.speaking&&++this.redemptionCounter>=this.redemptionFrames){this.redemptionCounter=0,this.speechFrameCount=0,this.speaking=!1,this.speechRealStartFired=!1;const fe=this.audioBuffer;if(this.audioBuffer=[],fe.reduce((he,pe)=>pe.isSpeech?he+1:he,0)>=this.minSpeechFrames){const he=a(fe.map(pe=>pe.frame));Y({msg:r.Message.SpeechEnd,audio:he})}else Y({msg:r.Message.VADMisfire})}if(!this.speaking){for(;this.audioBuffer.length>this.preSpeechPadFrames;)this.audioBuffer.shift();this.speechFrameCount=0}},this.audioBuffer=[];const{redemptionFrames:te,preSpeechPadFrames:j,minSpeechFrames:se}=p(this.options,this.msPerFrame);this.redemptionFrames=te,this.preSpeechPadFrames=j,this.minSpeechFrames=se,this.reset()}}return Wr.FrameProcessor=_,Wr}var Hr={};function dr(d){throw new Error('Could not dynamically require "'+d+'". Please configure the dynamicRequireTargets or/and ignoreDynamicRequires option of @rollup/plugin-commonjs appropriately for this require call to work.')}var so={exports:{}};/*!
1
+ "use strict";const ae=require("react"),Jt=require("react/jsx-runtime");function Gp(){if(typeof window>"u")return;const d=window;d.__rqmii_orig_console||(d.__rqmii_orig_console={error:console.error,warn:console.warn,log:console.log,debug:console.debug});const r=d.__rqmii_orig_console,s=a=>{if(a.length===0)return!1;const p=String(a[0]);return p.includes("reading 'S'")||p.includes("reading 'state'")||p.includes("MicVAD has null stream")||p.includes("VAD |")||p.includes("audioCtx.state")||p.includes("using default audio context")};console.error=(...a)=>{s(a)||r.error.apply(console,a)},console.warn=(...a)=>{s(a)||r.warn.apply(console,a)},console.log=(...a)=>{s(a)||r.log.apply(console,a)},console.debug=(...a)=>{s(a)||r.debug.apply(console,a)}}const hi={TEXT:"text",VOICE:"voice",TEXT_AND_VOICE:"text_and_voice",CLOUD_AVATAR:"cloud_avatar",DESKTOP_AVATAR:"desktop_avatar"},br={CONNECT:"connect",DISCONNECT:"disconnect",CONNECT_ERROR:"connect_error",SESSION_READY:"session_ready",SESSION_JOINED:"session_joined",SESSION_TERMINATED:"session_terminated",USER_MESSAGE:"user_message",AUDIO_CHUNK:"audio_chunk",AUDIO_END:"audio_end",INTERRUPT:"interrupt",CHANGE_SESSION_LANGUAGE:"change_session_language",LANGUAGE_CHANGED:"language_changed",CLIENT_READY:"client_ready",CLIENT_TOOL_REQUEST:"client_tool_request",CLIENT_TOOL_RESULT:"client_tool_result",CLEAR_SESSION_HISTORY:"clear_session_history",TRANSCRIPT:"transcript",PARTIAL_TRANSCRIPT:"partial_transcript",AGENT_RESPONSE_CHUNK:"agent_response_chunk",AGENT_RESPONSE:"agent_response",AGENT_AUDIO_CHUNK:"agent_audio_chunk",AGENT_AUDIO_COMPLETE:"agent_audio_complete",AVATAR_SPEAKING:"avatar_speaking",AVATAR_SPEAKING_DONE:"avatar_speaking_done",INTERRUPTED:"interrupted",ERROR:"error",AUTH_ERROR:"auth_error",SESSION_EXPIRED:"session_expired",CREDITS_EXHAUSTED:"credits_exhausted",SESSION_STATE_CHANGED:"session:state_changed",AUDIO_PLAYBACK_COMPLETE:"audio:playback_complete",MESSAGE_RATE_LIMITED:"message_rate_limited",SHOW_LEAD_CAPTURE_FORM:"show_lead_capture_form"},pt={IDLE:"idle",INITIALIZING:"initializing",CONNECTING:"connecting",CONNECTED:"connected",FAILED:"failed",ENDED:"ended"},Zt={IDLE:"idle",CONNECTING:"connecting",LOADING:"loading",CONNECTED:"connected",DISCONNECTED:"disconnected",ERROR:"error"},Ns={IDLE:"idle",USER_SPEAKING:"user_speaking",AGENT_THINKING:"agent_thinking",AGENT_SPEAKING:"agent_speaking",TOOL_EXECUTING:"tool_executing",TERMINATING:"terminating",TERMINATED:"terminated"},qp={encoding:"16bitInt",channels:1,sampleRate:16e3},po={connectionState:pt.IDLE,isConnected:!1,isSessionReady:!1,error:null,isAudioPlaying:!1,isAvatarSpeaking:!1,sessionState:Ns.IDLE,cloudStream:{state:Zt.IDLE,error:null},transcript:null,partialTranscript:null,session:{sessionId:null,role:null,agentType:null,streamingUrl:null,uniqueId:null},messages:[],creditExhausted:!1,creditError:null,agentConfig:null};function hp(d,r){switch(r.type){case"SET_CONNECTION_STATE":return{...d,connectionState:r.payload,isConnected:r.payload===pt.CONNECTED};case"SET_ERROR":return{...d,error:r.payload};case"SET_CLOUD_STREAM_STATE":return{...d,cloudStream:r.payload};case"SET_SESSION_STATE":return{...d,sessionState:r.payload};case"UPDATE_SESSION":return{...d,session:{...d.session,...r.payload}};case"ADD_MESSAGE":return{...d,messages:[...d.messages,r.payload]};case"SET_AUDIO_PLAYING":return{...d,isAudioPlaying:r.payload};case"SET_AVATAR_SPEAKING":return{...d,isAvatarSpeaking:r.payload};case"SET_CREDIT_EXHAUSTED":return{...d,creditExhausted:r.payload.exhausted,creditError:r.payload.error};case"SET_TRANSCRIPT":return{...d,transcript:r.payload};case"SET_PARTIAL_TRANSCRIPT":return{...d,partialTranscript:r.payload};case"SET_MESSAGES":return{...d,messages:r.payload};case"SET_SESSION_READY":return{...d,isSessionReady:r.payload};case"SET_AGENT_CONFIG":return{...d,agentConfig:r.payload};case"HARD_RESET":return po;case"REPLACE_STATE":return r.payload;default:return d}}function pg(d){return{isSessionTerminated:d===Ns.TERMINATED,isSessionTerminating:d===Ns.TERMINATING,isAgentThinking:d===Ns.AGENT_THINKING,isAgentSpeaking:d===Ns.AGENT_SPEAKING,isToolExecuting:d===Ns.TOOL_EXECUTING}}function fg(){const d=new Map;return{addChunk(r,s){const a=r||`request-${Date.now()}`,_=`${d.get(a)||""}${s||""}`;return d.set(a,_),{id:a,text:_}},consume(r,s=""){const a=r||`request-${Date.now()}`,p=d.get(a)||s||"";return d.delete(a),{id:a,text:p}},clear(){d.clear()}}}function mg(){try{const d=Intl.DateTimeFormat().resolvedOptions().timeZone;return typeof d=="string"&&d.trim()?d.trim():void 0}catch{return}}async function ei(d){if(!d?.ok){let r=`HTTP ${d.status}`;try{const p=await d.json();r=p?.detail||p?.message||r}catch{}const s=new Error(r);throw s.status=d.status,s}return d.json()}function gg({restUrl:d,log:r,withCredentials:s}){function a(){if(!d)throw new Error("Missing restUrl in RqmiiAgentProvider")}async function p({apiKey:N,publicChatId:z,agentId:te,userId:j,language:se="en",timezone:J,config:Y}={}){a();const W={...N?{api_key:N}:{},...z?{public_chat_id:z}:{},...te?{agent_id:te}:{},...j?{user_id:j}:{},language:se,...J?{timezone:J}:{},...Y?{config:Y}:{}};r("initializeSession — POST /sessions/init",W);const ne=await fetch(`${d}/sessions/init`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(W),...s?{credentials:"include"}:{}}),fe=await ei(ne);if(!fe?.session_id||!fe?.session_token)throw new Error("Invalid initialize session response");return fe}async function _({uniqueId:N}){a(),r("joinDesktopSession — POST /sessions/join",{uniqueId:N});const z=await fetch(`${d}/sessions/join`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({unique_id:N}),...s?{credentials:"include"}:{}}),te=await ei(z);if(!te?.session_id||!te?.session_token)throw new Error("Invalid join session response");return te}async function C(N){a(),r("fetchAgentConfig — GET /agent/{publicChatId}",{publicChatId:N});const z=await fetch(`${d}/agent/${encodeURIComponent(N)}`,{method:"GET",headers:{"Content-Type":"application/json"},...s?{credentials:"include"}:{}});return ei(z)}async function R({sessionId:N,rating:z,feedback:te,endedBy:j}){if(a(),!N)throw new Error("sessionId is required");const se={...typeof z=="number"?{rating:z}:{},...te?{feedback:te}:{},...j?{ended_by:j}:{}};r("submitFeedback — PATCH /conversations/{sessionId}/feedback",{sessionId:N,payload:se});const J=await fetch(`${d}/conversations/${encodeURIComponent(N)}/feedback`,{method:"PATCH",headers:{"Content-Type":"application/json"},body:JSON.stringify(se),...s?{credentials:"include"}:{}});return ei(J)}async function S({agentId:N,sessionId:z,collectedData:te}){if(a(),!N)throw new Error("agentId is required");if(!z)throw new Error("sessionId is required");r("submitLead — POST /public/agent/{agentId}/lead-capture/leads",{agentId:N,sessionId:z});const j=await fetch(`${d}/public/agent/${encodeURIComponent(N)}/lead-capture/leads`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({session_id:z,collected_data:te}),...s?{credentials:"include"}:{}});return ei(j)}return{initializeSession:p,joinDesktopSession:_,fetchAgentConfig:C,submitFeedback:R,submitLead:S}}const Dr=Object.create(null);Dr.open="0";Dr.close="1";Dr.ping="2";Dr.pong="3";Dr.message="4";Dr.upgrade="5";Dr.noop="6";const Di=Object.create(null);Object.keys(Dr).forEach(d=>{Di[Dr[d]]=d});const fo={type:"error",data:"parser error"},Wp=typeof Blob=="function"||typeof Blob<"u"&&Object.prototype.toString.call(Blob)==="[object BlobConstructor]",Hp=typeof ArrayBuffer=="function",jp=d=>typeof ArrayBuffer.isView=="function"?ArrayBuffer.isView(d):d&&d.buffer instanceof ArrayBuffer,xo=({type:d,data:r},s,a)=>Wp&&r instanceof Blob?s?a(r):pp(r,a):Hp&&(r instanceof ArrayBuffer||jp(r))?s?a(r):pp(new Blob([r]),a):a(Dr[d]+(r||"")),pp=(d,r)=>{const s=new FileReader;return s.onload=function(){const a=s.result.split(",")[1];r("b"+(a||""))},s.readAsDataURL(d)};function fp(d){return d instanceof Uint8Array?d:d instanceof ArrayBuffer?new Uint8Array(d):new Uint8Array(d.buffer,d.byteOffset,d.byteLength)}let Ya;function yg(d,r){if(Wp&&d.data instanceof Blob)return d.data.arrayBuffer().then(fp).then(r);if(Hp&&(d.data instanceof ArrayBuffer||jp(d.data)))return r(fp(d.data));xo(d,!1,s=>{Ya||(Ya=new TextEncoder),r(Ya.encode(s))})}const mp="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",ui=typeof Uint8Array>"u"?[]:new Uint8Array(256);for(let d=0;d<mp.length;d++)ui[mp.charCodeAt(d)]=d;const wg=d=>{let r=d.length*.75,s=d.length,a,p=0,_,C,R,S;d[d.length-1]==="="&&(r--,d[d.length-2]==="="&&r--);const N=new ArrayBuffer(r),z=new Uint8Array(N);for(a=0;a<s;a+=4)_=ui[d.charCodeAt(a)],C=ui[d.charCodeAt(a+1)],R=ui[d.charCodeAt(a+2)],S=ui[d.charCodeAt(a+3)],z[p++]=_<<2|C>>4,z[p++]=(C&15)<<4|R>>2,z[p++]=(R&3)<<6|S&63;return N},vg=typeof ArrayBuffer=="function",Co=(d,r)=>{if(typeof d!="string")return{type:"message",data:Kp(d,r)};const s=d.charAt(0);return s==="b"?{type:"message",data:_g(d.substring(1),r)}:Di[s]?d.length>1?{type:Di[s],data:d.substring(1)}:{type:Di[s]}:fo},_g=(d,r)=>{if(vg){const s=wg(d);return Kp(s,r)}else return{base64:!0,data:d}},Kp=(d,r)=>{switch(r){case"blob":return d instanceof Blob?d:new Blob([d]);case"arraybuffer":default:return d instanceof ArrayBuffer?d:d.buffer}},Qp="",bg=(d,r)=>{const s=d.length,a=new Array(s);let p=0;d.forEach((_,C)=>{xo(_,!1,R=>{a[C]=R,++p===s&&r(a.join(Qp))})})},Sg=(d,r)=>{const s=d.split(Qp),a=[];for(let p=0;p<s.length;p++){const _=Co(s[p],r);if(a.push(_),_.type==="error")break}return a};function Tg(){return new TransformStream({transform(d,r){yg(d,s=>{const a=s.length;let p;if(a<126)p=new Uint8Array(1),new DataView(p.buffer).setUint8(0,a);else if(a<65536){p=new Uint8Array(3);const _=new DataView(p.buffer);_.setUint8(0,126),_.setUint16(1,a)}else{p=new Uint8Array(9);const _=new DataView(p.buffer);_.setUint8(0,127),_.setBigUint64(1,BigInt(a))}d.data&&typeof d.data!="string"&&(p[0]|=128),r.enqueue(p),r.enqueue(s)})}})}let Ja;function Mi(d){return d.reduce((r,s)=>r+s.length,0)}function Oi(d,r){if(d[0].length===r)return d.shift();const s=new Uint8Array(r);let a=0;for(let p=0;p<r;p++)s[p]=d[0][a++],a===d[0].length&&(d.shift(),a=0);return d.length&&a<d[0].length&&(d[0]=d[0].slice(a)),s}function Eg(d,r){Ja||(Ja=new TextDecoder);const s=[];let a=0,p=-1,_=!1;return new TransformStream({transform(C,R){for(s.push(C);;){if(a===0){if(Mi(s)<1)break;const S=Oi(s,1);_=(S[0]&128)===128,p=S[0]&127,p<126?a=3:p===126?a=1:a=2}else if(a===1){if(Mi(s)<2)break;const S=Oi(s,2);p=new DataView(S.buffer,S.byteOffset,S.length).getUint16(0),a=3}else if(a===2){if(Mi(s)<8)break;const S=Oi(s,8),N=new DataView(S.buffer,S.byteOffset,S.length),z=N.getUint32(0);if(z>Math.pow(2,21)-1){R.enqueue(fo);break}p=z*Math.pow(2,32)+N.getUint32(4),a=3}else{if(Mi(s)<p)break;const S=Oi(s,p);R.enqueue(Co(_?S:Ja.decode(S),r)),a=0}if(p===0||p>d){R.enqueue(fo);break}}}})}const Xp=4;function $t(d){if(d)return $g(d)}function $g(d){for(var r in $t.prototype)d[r]=$t.prototype[r];return d}$t.prototype.on=$t.prototype.addEventListener=function(d,r){return this._callbacks=this._callbacks||{},(this._callbacks["$"+d]=this._callbacks["$"+d]||[]).push(r),this};$t.prototype.once=function(d,r){function s(){this.off(d,s),r.apply(this,arguments)}return s.fn=r,this.on(d,s),this};$t.prototype.off=$t.prototype.removeListener=$t.prototype.removeAllListeners=$t.prototype.removeEventListener=function(d,r){if(this._callbacks=this._callbacks||{},arguments.length==0)return this._callbacks={},this;var s=this._callbacks["$"+d];if(!s)return this;if(arguments.length==1)return delete this._callbacks["$"+d],this;for(var a,p=0;p<s.length;p++)if(a=s[p],a===r||a.fn===r){s.splice(p,1);break}return s.length===0&&delete this._callbacks["$"+d],this};$t.prototype.emit=function(d){this._callbacks=this._callbacks||{};for(var r=new Array(arguments.length-1),s=this._callbacks["$"+d],a=1;a<arguments.length;a++)r[a-1]=arguments[a];if(s){s=s.slice(0);for(var a=0,p=s.length;a<p;++a)s[a].apply(this,r)}return this};$t.prototype.emitReserved=$t.prototype.emit;$t.prototype.listeners=function(d){return this._callbacks=this._callbacks||{},this._callbacks["$"+d]||[]};$t.prototype.hasListeners=function(d){return!!this.listeners(d).length};const Vi=typeof Promise=="function"&&typeof Promise.resolve=="function"?r=>Promise.resolve().then(r):(r,s)=>s(r,0),ur=typeof self<"u"?self:typeof window<"u"?window:Function("return this")(),xg="arraybuffer";function Yp(d,...r){return r.reduce((s,a)=>(d.hasOwnProperty(a)&&(s[a]=d[a]),s),{})}const Cg=ur.setTimeout,kg=ur.clearTimeout;function Gi(d,r){r.useNativeTimers?(d.setTimeoutFn=Cg.bind(ur),d.clearTimeoutFn=kg.bind(ur)):(d.setTimeoutFn=ur.setTimeout.bind(ur),d.clearTimeoutFn=ur.clearTimeout.bind(ur))}const Rg=1.33;function Ag(d){return typeof d=="string"?Ig(d):Math.ceil((d.byteLength||d.size)*Rg)}function Ig(d){let r=0,s=0;for(let a=0,p=d.length;a<p;a++)r=d.charCodeAt(a),r<128?s+=1:r<2048?s+=2:r<55296||r>=57344?s+=3:(a++,s+=4);return s}function Jp(){return Date.now().toString(36).substring(3)+Math.random().toString(36).substring(2,5)}function Mg(d){let r="";for(let s in d)d.hasOwnProperty(s)&&(r.length&&(r+="&"),r+=encodeURIComponent(s)+"="+encodeURIComponent(d[s]));return r}function Og(d){let r={},s=d.split("&");for(let a=0,p=s.length;a<p;a++){let _=s[a].split("=");r[decodeURIComponent(_[0])]=decodeURIComponent(_[1])}return r}class Pg extends Error{constructor(r,s,a){super(r),this.description=s,this.context=a,this.type="TransportError"}}class ko extends $t{constructor(r){super(),this.writable=!1,Gi(this,r),this.opts=r,this.query=r.query,this.socket=r.socket,this.supportsBinary=!r.forceBase64}onError(r,s,a){return super.emitReserved("error",new Pg(r,s,a)),this}open(){return this.readyState="opening",this.doOpen(),this}close(){return(this.readyState==="opening"||this.readyState==="open")&&(this.doClose(),this.onClose()),this}send(r){this.readyState==="open"&&this.write(r)}onOpen(){this.readyState="open",this.writable=!0,super.emitReserved("open")}onData(r){const s=Co(r,this.socket.binaryType);this.onPacket(s)}onPacket(r){super.emitReserved("packet",r)}onClose(r){this.readyState="closed",super.emitReserved("close",r)}pause(r){}createUri(r,s={}){return r+"://"+this._hostname()+this._port()+this.opts.path+this._query(s)}_hostname(){const r=this.opts.hostname;return r.indexOf(":")===-1?r:"["+r+"]"}_port(){return this.opts.port&&(this.opts.secure&&Number(this.opts.port)!==443||!this.opts.secure&&Number(this.opts.port)!==80)?":"+this.opts.port:""}_query(r){const s=Mg(r);return s.length?"?"+s:""}}class Dg extends ko{constructor(){super(...arguments),this._polling=!1}get name(){return"polling"}doOpen(){this._poll()}pause(r){this.readyState="pausing";const s=()=>{this.readyState="paused",r()};if(this._polling||!this.writable){let a=0;this._polling&&(a++,this.once("pollComplete",function(){--a||s()})),this.writable||(a++,this.once("drain",function(){--a||s()}))}else s()}_poll(){this._polling=!0,this.doPoll(),this.emitReserved("poll")}onData(r){const s=a=>{if(this.readyState==="opening"&&a.type==="open"&&this.onOpen(),a.type==="close")return this.onClose({description:"transport closed by the server"}),!1;this.onPacket(a)};Sg(r,this.socket.binaryType).forEach(s),this.readyState!=="closed"&&(this._polling=!1,this.emitReserved("pollComplete"),this.readyState==="open"&&this._poll())}doClose(){const r=()=>{this.write([{type:"close"}])};this.readyState==="open"?r():this.once("open",r)}write(r){this.writable=!1,bg(r,s=>{this.doWrite(s,()=>{this.writable=!0,this.emitReserved("drain")})})}uri(){const r=this.opts.secure?"https":"http",s=this.query||{};return this.opts.timestampRequests!==!1&&(s[this.opts.timestampParam]=Jp()),!this.supportsBinary&&!s.sid&&(s.b64=1),this.createUri(r,s)}}let Zp=!1;try{Zp=typeof XMLHttpRequest<"u"&&"withCredentials"in new XMLHttpRequest}catch{}const zg=Zp;function Lg(){}class Bg extends Dg{constructor(r){if(super(r),typeof location<"u"){const s=location.protocol==="https:";let a=location.port;a||(a=s?"443":"80"),this.xd=typeof location<"u"&&r.hostname!==location.hostname||a!==r.port}}doWrite(r,s){const a=this.request({method:"POST",data:r});a.on("success",s),a.on("error",(p,_)=>{this.onError("xhr post error",p,_)})}doPoll(){const r=this.request();r.on("data",this.onData.bind(this)),r.on("error",(s,a)=>{this.onError("xhr poll error",s,a)}),this.pollXhr=r}}class Pr extends $t{constructor(r,s,a){super(),this.createRequest=r,Gi(this,a),this._opts=a,this._method=a.method||"GET",this._uri=s,this._data=a.data!==void 0?a.data:null,this._create()}_create(){var r;const s=Yp(this._opts,"agent","pfx","key","passphrase","cert","ca","ciphers","rejectUnauthorized","autoUnref");s.xdomain=!!this._opts.xd;const a=this._xhr=this.createRequest(s);try{a.open(this._method,this._uri,!0);try{if(this._opts.extraHeaders){a.setDisableHeaderCheck&&a.setDisableHeaderCheck(!0);for(let p in this._opts.extraHeaders)this._opts.extraHeaders.hasOwnProperty(p)&&a.setRequestHeader(p,this._opts.extraHeaders[p])}}catch{}if(this._method==="POST")try{a.setRequestHeader("Content-type","text/plain;charset=UTF-8")}catch{}try{a.setRequestHeader("Accept","*/*")}catch{}(r=this._opts.cookieJar)===null||r===void 0||r.addCookies(a),"withCredentials"in a&&(a.withCredentials=this._opts.withCredentials),this._opts.requestTimeout&&(a.timeout=this._opts.requestTimeout),a.onreadystatechange=()=>{var p;a.readyState===3&&((p=this._opts.cookieJar)===null||p===void 0||p.parseCookies(a.getResponseHeader("set-cookie"))),a.readyState===4&&(a.status===200||a.status===1223?this._onLoad():this.setTimeoutFn(()=>{this._onError(typeof a.status=="number"?a.status:0)},0))},a.send(this._data)}catch(p){this.setTimeoutFn(()=>{this._onError(p)},0);return}typeof document<"u"&&(this._index=Pr.requestsCount++,Pr.requests[this._index]=this)}_onError(r){this.emitReserved("error",r,this._xhr),this._cleanup(!0)}_cleanup(r){if(!(typeof this._xhr>"u"||this._xhr===null)){if(this._xhr.onreadystatechange=Lg,r)try{this._xhr.abort()}catch{}typeof document<"u"&&delete Pr.requests[this._index],this._xhr=null}}_onLoad(){const r=this._xhr.responseText;r!==null&&(this.emitReserved("data",r),this.emitReserved("success"),this._cleanup())}abort(){this._cleanup()}}Pr.requestsCount=0;Pr.requests={};if(typeof document<"u"){if(typeof attachEvent=="function")attachEvent("onunload",gp);else if(typeof addEventListener=="function"){const d="onpagehide"in ur?"pagehide":"unload";addEventListener(d,gp,!1)}}function gp(){for(let d in Pr.requests)Pr.requests.hasOwnProperty(d)&&Pr.requests[d].abort()}const Ng=(function(){const d=ef({xdomain:!1});return d&&d.responseType!==null})();class Ug extends Bg{constructor(r){super(r);const s=r&&r.forceBase64;this.supportsBinary=Ng&&!s}request(r={}){return Object.assign(r,{xd:this.xd},this.opts),new Pr(ef,this.uri(),r)}}function ef(d){const r=d.xdomain;try{if(typeof XMLHttpRequest<"u"&&(!r||zg))return new XMLHttpRequest}catch{}if(!r)try{return new ur[["Active"].concat("Object").join("X")]("Microsoft.XMLHTTP")}catch{}}const tf=typeof navigator<"u"&&typeof navigator.product=="string"&&navigator.product.toLowerCase()==="reactnative";class Fg extends ko{get name(){return"websocket"}doOpen(){const r=this.uri(),s=this.opts.protocols,a=tf?{}:Yp(this.opts,"agent","perMessageDeflate","pfx","key","passphrase","cert","ca","ciphers","rejectUnauthorized","localAddress","protocolVersion","origin","maxPayload","family","checkServerIdentity");this.opts.extraHeaders&&(a.headers=this.opts.extraHeaders);try{this.ws=this.createSocket(r,s,a)}catch(p){return this.emitReserved("error",p)}this.ws.binaryType=this.socket.binaryType,this.addEventListeners()}addEventListeners(){this.ws.onopen=()=>{this.opts.autoUnref&&this.ws._socket.unref(),this.onOpen()},this.ws.onclose=r=>this.onClose({description:"websocket connection closed",context:r}),this.ws.onmessage=r=>this.onData(r.data),this.ws.onerror=r=>this.onError("websocket error",r)}write(r){this.writable=!1;for(let s=0;s<r.length;s++){const a=r[s],p=s===r.length-1;xo(a,this.supportsBinary,_=>{try{this.doWrite(a,_)}catch{}p&&Vi(()=>{this.writable=!0,this.emitReserved("drain")},this.setTimeoutFn)})}}doClose(){typeof this.ws<"u"&&(this.ws.onerror=()=>{},this.ws.close(),this.ws=null)}uri(){const r=this.opts.secure?"wss":"ws",s=this.query||{};return this.opts.timestampRequests&&(s[this.opts.timestampParam]=Jp()),this.supportsBinary||(s.b64=1),this.createUri(r,s)}}const Za=ur.WebSocket||ur.MozWebSocket;class Vg extends Fg{createSocket(r,s,a){return tf?new Za(r,s,a):s?new Za(r,s):new Za(r)}doWrite(r,s){this.ws.send(s)}}class Gg extends ko{get name(){return"webtransport"}doOpen(){try{this._transport=new WebTransport(this.createUri("https"),this.opts.transportOptions[this.name])}catch(r){return this.emitReserved("error",r)}this._transport.closed.then(()=>{this.onClose()}).catch(r=>{this.onError("webtransport error",r)}),this._transport.ready.then(()=>{this._transport.createBidirectionalStream().then(r=>{const s=Eg(Number.MAX_SAFE_INTEGER,this.socket.binaryType),a=r.readable.pipeThrough(s).getReader(),p=Tg();p.readable.pipeTo(r.writable),this._writer=p.writable.getWriter();const _=()=>{a.read().then(({done:R,value:S})=>{R||(this.onPacket(S),_())}).catch(R=>{})};_();const C={type:"open"};this.query.sid&&(C.data=`{"sid":"${this.query.sid}"}`),this._writer.write(C).then(()=>this.onOpen())})})}write(r){this.writable=!1;for(let s=0;s<r.length;s++){const a=r[s],p=s===r.length-1;this._writer.write(a).then(()=>{p&&Vi(()=>{this.writable=!0,this.emitReserved("drain")},this.setTimeoutFn)})}}doClose(){var r;(r=this._transport)===null||r===void 0||r.close()}}const qg={websocket:Vg,webtransport:Gg,polling:Ug},Wg=/^(?:(?![^:@\/?#]+:[^:@\/]*@)(http|https|ws|wss):\/\/)?((?:(([^:@\/?#]*)(?::([^:@\/?#]*))?)?@)?((?:[a-f0-9]{0,4}:){2,7}[a-f0-9]{0,4}|[^:\/?#]*)(?::(\d*))?)(((\/(?:[^?#](?![^?#\/]*\.[^?#\/.]+(?:[?#]|$)))*\/?)?([^?#\/]*))(?:\?([^#]*))?(?:#(.*))?)/,Hg=["source","protocol","authority","userInfo","user","password","host","port","relative","path","directory","file","query","anchor"];function mo(d){if(d.length>8e3)throw"URI too long";const r=d,s=d.indexOf("["),a=d.indexOf("]");s!=-1&&a!=-1&&(d=d.substring(0,s)+d.substring(s,a).replace(/:/g,";")+d.substring(a,d.length));let p=Wg.exec(d||""),_={},C=14;for(;C--;)_[Hg[C]]=p[C]||"";return s!=-1&&a!=-1&&(_.source=r,_.host=_.host.substring(1,_.host.length-1).replace(/;/g,":"),_.authority=_.authority.replace("[","").replace("]","").replace(/;/g,":"),_.ipv6uri=!0),_.pathNames=jg(_,_.path),_.queryKey=Kg(_,_.query),_}function jg(d,r){const s=/\/{2,9}/g,a=r.replace(s,"/").split("/");return(r.slice(0,1)=="/"||r.length===0)&&a.splice(0,1),r.slice(-1)=="/"&&a.splice(a.length-1,1),a}function Kg(d,r){const s={};return r.replace(/(?:^|&)([^&=]*)=?([^&]*)/g,function(a,p,_){p&&(s[p]=_)}),s}const go=typeof addEventListener=="function"&&typeof removeEventListener=="function",zi=[];go&&addEventListener("offline",()=>{zi.forEach(d=>d())},!1);class ds extends $t{constructor(r,s){if(super(),this.binaryType=xg,this.writeBuffer=[],this._prevBufferLen=0,this._pingInterval=-1,this._pingTimeout=-1,this._maxPayload=-1,this._pingTimeoutTime=1/0,r&&typeof r=="object"&&(s=r,r=null),r){const a=mo(r);s.hostname=a.host,s.secure=a.protocol==="https"||a.protocol==="wss",s.port=a.port,a.query&&(s.query=a.query)}else s.host&&(s.hostname=mo(s.host).host);Gi(this,s),this.secure=s.secure!=null?s.secure:typeof location<"u"&&location.protocol==="https:",s.hostname&&!s.port&&(s.port=this.secure?"443":"80"),this.hostname=s.hostname||(typeof location<"u"?location.hostname:"localhost"),this.port=s.port||(typeof location<"u"&&location.port?location.port:this.secure?"443":"80"),this.transports=[],this._transportsByName={},s.transports.forEach(a=>{const p=a.prototype.name;this.transports.push(p),this._transportsByName[p]=a}),this.opts=Object.assign({path:"/engine.io",agent:!1,withCredentials:!1,upgrade:!0,timestampParam:"t",rememberUpgrade:!1,addTrailingSlash:!0,rejectUnauthorized:!0,perMessageDeflate:{threshold:1024},transportOptions:{},closeOnBeforeunload:!1},s),this.opts.path=this.opts.path.replace(/\/$/,"")+(this.opts.addTrailingSlash?"/":""),typeof this.opts.query=="string"&&(this.opts.query=Og(this.opts.query)),go&&(this.opts.closeOnBeforeunload&&(this._beforeunloadEventListener=()=>{this.transport&&(this.transport.removeAllListeners(),this.transport.close())},addEventListener("beforeunload",this._beforeunloadEventListener,!1)),this.hostname!=="localhost"&&(this._offlineEventListener=()=>{this._onClose("transport close",{description:"network connection lost"})},zi.push(this._offlineEventListener))),this.opts.withCredentials&&(this._cookieJar=void 0),this._open()}createTransport(r){const s=Object.assign({},this.opts.query);s.EIO=Xp,s.transport=r,this.id&&(s.sid=this.id);const a=Object.assign({},this.opts,{query:s,socket:this,hostname:this.hostname,secure:this.secure,port:this.port},this.opts.transportOptions[r]);return new this._transportsByName[r](a)}_open(){if(this.transports.length===0){this.setTimeoutFn(()=>{this.emitReserved("error","No transports available")},0);return}const r=this.opts.rememberUpgrade&&ds.priorWebsocketSuccess&&this.transports.indexOf("websocket")!==-1?"websocket":this.transports[0];this.readyState="opening";const s=this.createTransport(r);s.open(),this.setTransport(s)}setTransport(r){this.transport&&this.transport.removeAllListeners(),this.transport=r,r.on("drain",this._onDrain.bind(this)).on("packet",this._onPacket.bind(this)).on("error",this._onError.bind(this)).on("close",s=>this._onClose("transport close",s))}onOpen(){this.readyState="open",ds.priorWebsocketSuccess=this.transport.name==="websocket",this.emitReserved("open"),this.flush()}_onPacket(r){if(this.readyState==="opening"||this.readyState==="open"||this.readyState==="closing")switch(this.emitReserved("packet",r),this.emitReserved("heartbeat"),r.type){case"open":this.onHandshake(JSON.parse(r.data));break;case"ping":this._sendPacket("pong"),this.emitReserved("ping"),this.emitReserved("pong"),this._resetPingTimeout();break;case"error":const s=new Error("server error");s.code=r.data,this._onError(s);break;case"message":this.emitReserved("data",r.data),this.emitReserved("message",r.data);break}}onHandshake(r){this.emitReserved("handshake",r),this.id=r.sid,this.transport.query.sid=r.sid,this._pingInterval=r.pingInterval,this._pingTimeout=r.pingTimeout,this._maxPayload=r.maxPayload,this.onOpen(),this.readyState!=="closed"&&this._resetPingTimeout()}_resetPingTimeout(){this.clearTimeoutFn(this._pingTimeoutTimer);const r=this._pingInterval+this._pingTimeout;this._pingTimeoutTime=Date.now()+r,this._pingTimeoutTimer=this.setTimeoutFn(()=>{this._onClose("ping timeout")},r),this.opts.autoUnref&&this._pingTimeoutTimer.unref()}_onDrain(){this.writeBuffer.splice(0,this._prevBufferLen),this._prevBufferLen=0,this.writeBuffer.length===0?this.emitReserved("drain"):this.flush()}flush(){if(this.readyState!=="closed"&&this.transport.writable&&!this.upgrading&&this.writeBuffer.length){const r=this._getWritablePackets();this.transport.send(r),this._prevBufferLen=r.length,this.emitReserved("flush")}}_getWritablePackets(){if(!(this._maxPayload&&this.transport.name==="polling"&&this.writeBuffer.length>1))return this.writeBuffer;let s=1;for(let a=0;a<this.writeBuffer.length;a++){const p=this.writeBuffer[a].data;if(p&&(s+=Ag(p)),a>0&&s>this._maxPayload)return this.writeBuffer.slice(0,a);s+=2}return this.writeBuffer}_hasPingExpired(){if(!this._pingTimeoutTime)return!0;const r=Date.now()>this._pingTimeoutTime;return r&&(this._pingTimeoutTime=0,Vi(()=>{this._onClose("ping timeout")},this.setTimeoutFn)),r}write(r,s,a){return this._sendPacket("message",r,s,a),this}send(r,s,a){return this._sendPacket("message",r,s,a),this}_sendPacket(r,s,a,p){if(typeof s=="function"&&(p=s,s=void 0),typeof a=="function"&&(p=a,a=null),this.readyState==="closing"||this.readyState==="closed")return;a=a||{},a.compress=a.compress!==!1;const _={type:r,data:s,options:a};this.emitReserved("packetCreate",_),this.writeBuffer.push(_),p&&this.once("flush",p),this.flush()}close(){const r=()=>{this._onClose("forced close"),this.transport.close()},s=()=>{this.off("upgrade",s),this.off("upgradeError",s),r()},a=()=>{this.once("upgrade",s),this.once("upgradeError",s)};return(this.readyState==="opening"||this.readyState==="open")&&(this.readyState="closing",this.writeBuffer.length?this.once("drain",()=>{this.upgrading?a():r()}):this.upgrading?a():r()),this}_onError(r){if(ds.priorWebsocketSuccess=!1,this.opts.tryAllTransports&&this.transports.length>1&&this.readyState==="opening")return this.transports.shift(),this._open();this.emitReserved("error",r),this._onClose("transport error",r)}_onClose(r,s){if(this.readyState==="opening"||this.readyState==="open"||this.readyState==="closing"){if(this.clearTimeoutFn(this._pingTimeoutTimer),this.transport.removeAllListeners("close"),this.transport.close(),this.transport.removeAllListeners(),go&&(this._beforeunloadEventListener&&removeEventListener("beforeunload",this._beforeunloadEventListener,!1),this._offlineEventListener)){const a=zi.indexOf(this._offlineEventListener);a!==-1&&zi.splice(a,1)}this.readyState="closed",this.id=null,this.emitReserved("close",r,s),this.writeBuffer=[],this._prevBufferLen=0}}}ds.protocol=Xp;class Qg extends ds{constructor(){super(...arguments),this._upgrades=[]}onOpen(){if(super.onOpen(),this.readyState==="open"&&this.opts.upgrade)for(let r=0;r<this._upgrades.length;r++)this._probe(this._upgrades[r])}_probe(r){let s=this.createTransport(r),a=!1;ds.priorWebsocketSuccess=!1;const p=()=>{a||(s.send([{type:"ping",data:"probe"}]),s.once("packet",te=>{if(!a)if(te.type==="pong"&&te.data==="probe"){if(this.upgrading=!0,this.emitReserved("upgrading",s),!s)return;ds.priorWebsocketSuccess=s.name==="websocket",this.transport.pause(()=>{a||this.readyState!=="closed"&&(z(),this.setTransport(s),s.send([{type:"upgrade"}]),this.emitReserved("upgrade",s),s=null,this.upgrading=!1,this.flush())})}else{const j=new Error("probe error");j.transport=s.name,this.emitReserved("upgradeError",j)}}))};function _(){a||(a=!0,z(),s.close(),s=null)}const C=te=>{const j=new Error("probe error: "+te);j.transport=s.name,_(),this.emitReserved("upgradeError",j)};function R(){C("transport closed")}function S(){C("socket closed")}function N(te){s&&te.name!==s.name&&_()}const z=()=>{s.removeListener("open",p),s.removeListener("error",C),s.removeListener("close",R),this.off("close",S),this.off("upgrading",N)};s.once("open",p),s.once("error",C),s.once("close",R),this.once("close",S),this.once("upgrading",N),this._upgrades.indexOf("webtransport")!==-1&&r!=="webtransport"?this.setTimeoutFn(()=>{a||s.open()},200):s.open()}onHandshake(r){this._upgrades=this._filterUpgrades(r.upgrades),super.onHandshake(r)}_filterUpgrades(r){const s=[];for(let a=0;a<r.length;a++)~this.transports.indexOf(r[a])&&s.push(r[a]);return s}}let Xg=class extends Qg{constructor(r,s={}){const a=typeof r=="object"?r:s;(!a.transports||a.transports&&typeof a.transports[0]=="string")&&(a.transports=(a.transports||["polling","websocket","webtransport"]).map(p=>qg[p]).filter(p=>!!p)),super(r,a)}};function Yg(d,r="",s){let a=d;s=s||typeof location<"u"&&location,d==null&&(d=s.protocol+"//"+s.host),typeof d=="string"&&(d.charAt(0)==="/"&&(d.charAt(1)==="/"?d=s.protocol+d:d=s.host+d),/^(https?|wss?):\/\//.test(d)||(typeof s<"u"?d=s.protocol+"//"+d:d="https://"+d),a=mo(d)),a.port||(/^(http|ws)$/.test(a.protocol)?a.port="80":/^(http|ws)s$/.test(a.protocol)&&(a.port="443")),a.path=a.path||"/";const _=a.host.indexOf(":")!==-1?"["+a.host+"]":a.host;return a.id=a.protocol+"://"+_+":"+a.port+r,a.href=a.protocol+"://"+_+(s&&s.port===a.port?"":":"+a.port),a}const Jg=typeof ArrayBuffer=="function",Zg=d=>typeof ArrayBuffer.isView=="function"?ArrayBuffer.isView(d):d.buffer instanceof ArrayBuffer,rf=Object.prototype.toString,ey=typeof Blob=="function"||typeof Blob<"u"&&rf.call(Blob)==="[object BlobConstructor]",ty=typeof File=="function"||typeof File<"u"&&rf.call(File)==="[object FileConstructor]";function Ro(d){return Jg&&(d instanceof ArrayBuffer||Zg(d))||ey&&d instanceof Blob||ty&&d instanceof File}function Li(d,r){if(!d||typeof d!="object")return!1;if(Array.isArray(d)){for(let s=0,a=d.length;s<a;s++)if(Li(d[s]))return!0;return!1}if(Ro(d))return!0;if(d.toJSON&&typeof d.toJSON=="function"&&arguments.length===1)return Li(d.toJSON(),!0);for(const s in d)if(Object.prototype.hasOwnProperty.call(d,s)&&Li(d[s]))return!0;return!1}function ry(d){const r=[],s=d.data,a=d;return a.data=yo(s,r),a.attachments=r.length,{packet:a,buffers:r}}function yo(d,r){if(!d)return d;if(Ro(d)){const s={_placeholder:!0,num:r.length};return r.push(d),s}else if(Array.isArray(d)){const s=new Array(d.length);for(let a=0;a<d.length;a++)s[a]=yo(d[a],r);return s}else if(typeof d=="object"&&!(d instanceof Date)){const s={};for(const a in d)Object.prototype.hasOwnProperty.call(d,a)&&(s[a]=yo(d[a],r));return s}return d}function sy(d,r){return d.data=wo(d.data,r),delete d.attachments,d}function wo(d,r){if(!d)return d;if(d&&d._placeholder===!0){if(typeof d.num=="number"&&d.num>=0&&d.num<r.length)return r[d.num];throw new Error("illegal attachments")}else if(Array.isArray(d))for(let s=0;s<d.length;s++)d[s]=wo(d[s],r);else if(typeof d=="object")for(const s in d)Object.prototype.hasOwnProperty.call(d,s)&&(d[s]=wo(d[s],r));return d}const ny=["connect","connect_error","disconnect","disconnecting","newListener","removeListener"];var Xe;(function(d){d[d.CONNECT=0]="CONNECT",d[d.DISCONNECT=1]="DISCONNECT",d[d.EVENT=2]="EVENT",d[d.ACK=3]="ACK",d[d.CONNECT_ERROR=4]="CONNECT_ERROR",d[d.BINARY_EVENT=5]="BINARY_EVENT",d[d.BINARY_ACK=6]="BINARY_ACK"})(Xe||(Xe={}));class iy{constructor(r){this.replacer=r}encode(r){return(r.type===Xe.EVENT||r.type===Xe.ACK)&&Li(r)?this.encodeAsBinary({type:r.type===Xe.EVENT?Xe.BINARY_EVENT:Xe.BINARY_ACK,nsp:r.nsp,data:r.data,id:r.id}):[this.encodeAsString(r)]}encodeAsString(r){let s=""+r.type;return(r.type===Xe.BINARY_EVENT||r.type===Xe.BINARY_ACK)&&(s+=r.attachments+"-"),r.nsp&&r.nsp!=="/"&&(s+=r.nsp+","),r.id!=null&&(s+=r.id),r.data!=null&&(s+=JSON.stringify(r.data,this.replacer)),s}encodeAsBinary(r){const s=ry(r),a=this.encodeAsString(s.packet),p=s.buffers;return p.unshift(a),p}}class Ao extends $t{constructor(r){super(),this.opts=Object.assign({reviver:void 0,maxAttachments:10},typeof r=="function"?{reviver:r}:r)}add(r){let s;if(typeof r=="string"){if(this.reconstructor)throw new Error("got plaintext data when reconstructing a packet");s=this.decodeString(r);const a=s.type===Xe.BINARY_EVENT;a||s.type===Xe.BINARY_ACK?(s.type=a?Xe.EVENT:Xe.ACK,this.reconstructor=new ay(s),s.attachments===0&&super.emitReserved("decoded",s)):super.emitReserved("decoded",s)}else if(Ro(r)||r.base64)if(this.reconstructor)s=this.reconstructor.takeBinaryData(r),s&&(this.reconstructor=null,super.emitReserved("decoded",s));else throw new Error("got binary data when not reconstructing a packet");else throw new Error("Unknown type: "+r)}decodeString(r){let s=0;const a={type:Number(r.charAt(0))};if(Xe[a.type]===void 0)throw new Error("unknown packet type "+a.type);if(a.type===Xe.BINARY_EVENT||a.type===Xe.BINARY_ACK){const _=s+1;for(;r.charAt(++s)!=="-"&&s!=r.length;);const C=r.substring(_,s);if(C!=Number(C)||r.charAt(s)!=="-")throw new Error("Illegal attachments");const R=Number(C);if(!oy(R)||R<0)throw new Error("Illegal attachments");if(R>this.opts.maxAttachments)throw new Error("too many attachments");a.attachments=R}if(r.charAt(s+1)==="/"){const _=s+1;for(;++s&&!(r.charAt(s)===","||s===r.length););a.nsp=r.substring(_,s)}else a.nsp="/";const p=r.charAt(s+1);if(p!==""&&Number(p)==p){const _=s+1;for(;++s;){const C=r.charAt(s);if(C==null||Number(C)!=C){--s;break}if(s===r.length)break}a.id=Number(r.substring(_,s+1))}if(r.charAt(++s)){const _=this.tryParse(r.substr(s));if(Ao.isPayloadValid(a.type,_))a.data=_;else throw new Error("invalid payload")}return a}tryParse(r){try{return JSON.parse(r,this.opts.reviver)}catch{return!1}}static isPayloadValid(r,s){switch(r){case Xe.CONNECT:return yp(s);case Xe.DISCONNECT:return s===void 0;case Xe.CONNECT_ERROR:return typeof s=="string"||yp(s);case Xe.EVENT:case Xe.BINARY_EVENT:return Array.isArray(s)&&(typeof s[0]=="number"||typeof s[0]=="string"&&ny.indexOf(s[0])===-1);case Xe.ACK:case Xe.BINARY_ACK:return Array.isArray(s)}}destroy(){this.reconstructor&&(this.reconstructor.finishedReconstruction(),this.reconstructor=null)}}class ay{constructor(r){this.packet=r,this.buffers=[],this.reconPack=r}takeBinaryData(r){if(this.buffers.push(r),this.buffers.length===this.reconPack.attachments){const s=sy(this.reconPack,this.buffers);return this.finishedReconstruction(),s}return null}finishedReconstruction(){this.reconPack=null,this.buffers=[]}}const oy=Number.isInteger||function(d){return typeof d=="number"&&isFinite(d)&&Math.floor(d)===d};function yp(d){return Object.prototype.toString.call(d)==="[object Object]"}const ly=Object.freeze(Object.defineProperty({__proto__:null,Decoder:Ao,Encoder:iy,get PacketType(){return Xe}},Symbol.toStringTag,{value:"Module"}));function Sr(d,r,s){return d.on(r,s),function(){d.off(r,s)}}const uy=Object.freeze({connect:1,connect_error:1,disconnect:1,disconnecting:1,newListener:1,removeListener:1});class sf extends $t{constructor(r,s,a){super(),this.connected=!1,this.recovered=!1,this.receiveBuffer=[],this.sendBuffer=[],this._queue=[],this._queueSeq=0,this.ids=0,this.acks={},this.flags={},this.io=r,this.nsp=s,a&&a.auth&&(this.auth=a.auth),this._opts=Object.assign({},a),this.io._autoConnect&&this.open()}get disconnected(){return!this.connected}subEvents(){if(this.subs)return;const r=this.io;this.subs=[Sr(r,"open",this.onopen.bind(this)),Sr(r,"packet",this.onpacket.bind(this)),Sr(r,"error",this.onerror.bind(this)),Sr(r,"close",this.onclose.bind(this))]}get active(){return!!this.subs}connect(){return this.connected?this:(this.subEvents(),this.io._reconnecting||this.io.open(),this.io._readyState==="open"&&this.onopen(),this)}open(){return this.connect()}send(...r){return r.unshift("message"),this.emit.apply(this,r),this}emit(r,...s){var a,p,_;if(uy.hasOwnProperty(r))throw new Error('"'+r.toString()+'" is a reserved event name');if(s.unshift(r),this._opts.retries&&!this.flags.fromQueue&&!this.flags.volatile)return this._addToQueue(s),this;const C={type:Xe.EVENT,data:s};if(C.options={},C.options.compress=this.flags.compress!==!1,typeof s[s.length-1]=="function"){const z=this.ids++,te=s.pop();this._registerAckCallback(z,te),C.id=z}const R=(p=(a=this.io.engine)===null||a===void 0?void 0:a.transport)===null||p===void 0?void 0:p.writable,S=this.connected&&!(!((_=this.io.engine)===null||_===void 0)&&_._hasPingExpired());return this.flags.volatile&&!R||(S?(this.notifyOutgoingListeners(C),this.packet(C)):this.sendBuffer.push(C)),this.flags={},this}_registerAckCallback(r,s){var a;const p=(a=this.flags.timeout)!==null&&a!==void 0?a:this._opts.ackTimeout;if(p===void 0){this.acks[r]=s;return}const _=this.io.setTimeoutFn(()=>{delete this.acks[r];for(let R=0;R<this.sendBuffer.length;R++)this.sendBuffer[R].id===r&&this.sendBuffer.splice(R,1);s.call(this,new Error("operation has timed out"))},p),C=(...R)=>{this.io.clearTimeoutFn(_),s.apply(this,R)};C.withError=!0,this.acks[r]=C}emitWithAck(r,...s){return new Promise((a,p)=>{const _=(C,R)=>C?p(C):a(R);_.withError=!0,s.push(_),this.emit(r,...s)})}_addToQueue(r){let s;typeof r[r.length-1]=="function"&&(s=r.pop());const a={id:this._queueSeq++,tryCount:0,pending:!1,args:r,flags:Object.assign({fromQueue:!0},this.flags)};r.push((p,..._)=>(this._queue[0],p!==null?a.tryCount>this._opts.retries&&(this._queue.shift(),s&&s(p)):(this._queue.shift(),s&&s(null,..._)),a.pending=!1,this._drainQueue())),this._queue.push(a),this._drainQueue()}_drainQueue(r=!1){if(!this.connected||this._queue.length===0)return;const s=this._queue[0];s.pending&&!r||(s.pending=!0,s.tryCount++,this.flags=s.flags,this.emit.apply(this,s.args))}packet(r){r.nsp=this.nsp,this.io._packet(r)}onopen(){typeof this.auth=="function"?this.auth(r=>{this._sendConnectPacket(r)}):this._sendConnectPacket(this.auth)}_sendConnectPacket(r){this.packet({type:Xe.CONNECT,data:this._pid?Object.assign({pid:this._pid,offset:this._lastOffset},r):r})}onerror(r){this.connected||this.emitReserved("connect_error",r)}onclose(r,s){this.connected=!1,delete this.id,this.emitReserved("disconnect",r,s),this._clearAcks()}_clearAcks(){Object.keys(this.acks).forEach(r=>{if(!this.sendBuffer.some(a=>String(a.id)===r)){const a=this.acks[r];delete this.acks[r],a.withError&&a.call(this,new Error("socket has been disconnected"))}})}onpacket(r){if(r.nsp===this.nsp)switch(r.type){case Xe.CONNECT:r.data&&r.data.sid?this.onconnect(r.data.sid,r.data.pid):this.emitReserved("connect_error",new Error("It seems you are trying to reach a Socket.IO server in v2.x with a v3.x client, but they are not compatible (more information here: https://socket.io/docs/v3/migrating-from-2-x-to-3-0/)"));break;case Xe.EVENT:case Xe.BINARY_EVENT:this.onevent(r);break;case Xe.ACK:case Xe.BINARY_ACK:this.onack(r);break;case Xe.DISCONNECT:this.ondisconnect();break;case Xe.CONNECT_ERROR:this.destroy();const a=new Error(r.data.message);a.data=r.data.data,this.emitReserved("connect_error",a);break}}onevent(r){const s=r.data||[];r.id!=null&&s.push(this.ack(r.id)),this.connected?this.emitEvent(s):this.receiveBuffer.push(Object.freeze(s))}emitEvent(r){if(this._anyListeners&&this._anyListeners.length){const s=this._anyListeners.slice();for(const a of s)a.apply(this,r)}super.emit.apply(this,r),this._pid&&r.length&&typeof r[r.length-1]=="string"&&(this._lastOffset=r[r.length-1])}ack(r){const s=this;let a=!1;return function(...p){a||(a=!0,s.packet({type:Xe.ACK,id:r,data:p}))}}onack(r){const s=this.acks[r.id];typeof s=="function"&&(delete this.acks[r.id],s.withError&&r.data.unshift(null),s.apply(this,r.data))}onconnect(r,s){this.id=r,this.recovered=s&&this._pid===s,this._pid=s,this.connected=!0,this.emitBuffered(),this._drainQueue(!0),this.emitReserved("connect")}emitBuffered(){this.receiveBuffer.forEach(r=>this.emitEvent(r)),this.receiveBuffer=[],this.sendBuffer.forEach(r=>{this.notifyOutgoingListeners(r),this.packet(r)}),this.sendBuffer=[]}ondisconnect(){this.destroy(),this.onclose("io server disconnect")}destroy(){this.subs&&(this.subs.forEach(r=>r()),this.subs=void 0),this.io._destroy(this)}disconnect(){return this.connected&&this.packet({type:Xe.DISCONNECT}),this.destroy(),this.connected&&this.onclose("io client disconnect"),this}close(){return this.disconnect()}compress(r){return this.flags.compress=r,this}get volatile(){return this.flags.volatile=!0,this}timeout(r){return this.flags.timeout=r,this}onAny(r){return this._anyListeners=this._anyListeners||[],this._anyListeners.push(r),this}prependAny(r){return this._anyListeners=this._anyListeners||[],this._anyListeners.unshift(r),this}offAny(r){if(!this._anyListeners)return this;if(r){const s=this._anyListeners;for(let a=0;a<s.length;a++)if(r===s[a])return s.splice(a,1),this}else this._anyListeners=[];return this}listenersAny(){return this._anyListeners||[]}onAnyOutgoing(r){return this._anyOutgoingListeners=this._anyOutgoingListeners||[],this._anyOutgoingListeners.push(r),this}prependAnyOutgoing(r){return this._anyOutgoingListeners=this._anyOutgoingListeners||[],this._anyOutgoingListeners.unshift(r),this}offAnyOutgoing(r){if(!this._anyOutgoingListeners)return this;if(r){const s=this._anyOutgoingListeners;for(let a=0;a<s.length;a++)if(r===s[a])return s.splice(a,1),this}else this._anyOutgoingListeners=[];return this}listenersAnyOutgoing(){return this._anyOutgoingListeners||[]}notifyOutgoingListeners(r){if(this._anyOutgoingListeners&&this._anyOutgoingListeners.length){const s=this._anyOutgoingListeners.slice();for(const a of s)a.apply(this,r.data)}}}function hn(d){d=d||{},this.ms=d.min||100,this.max=d.max||1e4,this.factor=d.factor||2,this.jitter=d.jitter>0&&d.jitter<=1?d.jitter:0,this.attempts=0}hn.prototype.duration=function(){var d=this.ms*Math.pow(this.factor,this.attempts++);if(this.jitter){var r=Math.random(),s=Math.floor(r*this.jitter*d);d=(Math.floor(r*10)&1)==0?d-s:d+s}return Math.min(d,this.max)|0};hn.prototype.reset=function(){this.attempts=0};hn.prototype.setMin=function(d){this.ms=d};hn.prototype.setMax=function(d){this.max=d};hn.prototype.setJitter=function(d){this.jitter=d};class vo extends $t{constructor(r,s){var a;super(),this.nsps={},this.subs=[],r&&typeof r=="object"&&(s=r,r=void 0),s=s||{},s.path=s.path||"/socket.io",this.opts=s,Gi(this,s),this.reconnection(s.reconnection!==!1),this.reconnectionAttempts(s.reconnectionAttempts||1/0),this.reconnectionDelay(s.reconnectionDelay||1e3),this.reconnectionDelayMax(s.reconnectionDelayMax||5e3),this.randomizationFactor((a=s.randomizationFactor)!==null&&a!==void 0?a:.5),this.backoff=new hn({min:this.reconnectionDelay(),max:this.reconnectionDelayMax(),jitter:this.randomizationFactor()}),this.timeout(s.timeout==null?2e4:s.timeout),this._readyState="closed",this.uri=r;const p=s.parser||ly;this.encoder=new p.Encoder,this.decoder=new p.Decoder,this._autoConnect=s.autoConnect!==!1,this._autoConnect&&this.open()}reconnection(r){return arguments.length?(this._reconnection=!!r,r||(this.skipReconnect=!0),this):this._reconnection}reconnectionAttempts(r){return r===void 0?this._reconnectionAttempts:(this._reconnectionAttempts=r,this)}reconnectionDelay(r){var s;return r===void 0?this._reconnectionDelay:(this._reconnectionDelay=r,(s=this.backoff)===null||s===void 0||s.setMin(r),this)}randomizationFactor(r){var s;return r===void 0?this._randomizationFactor:(this._randomizationFactor=r,(s=this.backoff)===null||s===void 0||s.setJitter(r),this)}reconnectionDelayMax(r){var s;return r===void 0?this._reconnectionDelayMax:(this._reconnectionDelayMax=r,(s=this.backoff)===null||s===void 0||s.setMax(r),this)}timeout(r){return arguments.length?(this._timeout=r,this):this._timeout}maybeReconnectOnOpen(){!this._reconnecting&&this._reconnection&&this.backoff.attempts===0&&this.reconnect()}open(r){if(~this._readyState.indexOf("open"))return this;this.engine=new Xg(this.uri,this.opts);const s=this.engine,a=this;this._readyState="opening",this.skipReconnect=!1;const p=Sr(s,"open",function(){a.onopen(),r&&r()}),_=R=>{this.cleanup(),this._readyState="closed",this.emitReserved("error",R),r?r(R):this.maybeReconnectOnOpen()},C=Sr(s,"error",_);if(this._timeout!==!1){const R=this._timeout,S=this.setTimeoutFn(()=>{p(),_(new Error("timeout")),s.close()},R);this.opts.autoUnref&&S.unref(),this.subs.push(()=>{this.clearTimeoutFn(S)})}return this.subs.push(p),this.subs.push(C),this}connect(r){return this.open(r)}onopen(){this.cleanup(),this._readyState="open",this.emitReserved("open");const r=this.engine;this.subs.push(Sr(r,"ping",this.onping.bind(this)),Sr(r,"data",this.ondata.bind(this)),Sr(r,"error",this.onerror.bind(this)),Sr(r,"close",this.onclose.bind(this)),Sr(this.decoder,"decoded",this.ondecoded.bind(this)))}onping(){this.emitReserved("ping")}ondata(r){try{this.decoder.add(r)}catch(s){this.onclose("parse error",s)}}ondecoded(r){Vi(()=>{this.emitReserved("packet",r)},this.setTimeoutFn)}onerror(r){this.emitReserved("error",r)}socket(r,s){let a=this.nsps[r];return a?this._autoConnect&&!a.active&&a.connect():(a=new sf(this,r,s),this.nsps[r]=a),a}_destroy(r){const s=Object.keys(this.nsps);for(const a of s)if(this.nsps[a].active)return;this._close()}_packet(r){const s=this.encoder.encode(r);for(let a=0;a<s.length;a++)this.engine.write(s[a],r.options)}cleanup(){this.subs.forEach(r=>r()),this.subs.length=0,this.decoder.destroy()}_close(){this.skipReconnect=!0,this._reconnecting=!1,this.onclose("forced close")}disconnect(){return this._close()}onclose(r,s){var a;this.cleanup(),(a=this.engine)===null||a===void 0||a.close(),this.backoff.reset(),this._readyState="closed",this.emitReserved("close",r,s),this._reconnection&&!this.skipReconnect&&this.reconnect()}reconnect(){if(this._reconnecting||this.skipReconnect)return this;const r=this;if(this.backoff.attempts>=this._reconnectionAttempts)this.backoff.reset(),this.emitReserved("reconnect_failed"),this._reconnecting=!1;else{const s=this.backoff.duration();this._reconnecting=!0;const a=this.setTimeoutFn(()=>{r.skipReconnect||(this.emitReserved("reconnect_attempt",r.backoff.attempts),!r.skipReconnect&&r.open(p=>{p?(r._reconnecting=!1,r.reconnect(),this.emitReserved("reconnect_error",p)):r.onreconnect()}))},s);this.opts.autoUnref&&a.unref(),this.subs.push(()=>{this.clearTimeoutFn(a)})}}onreconnect(){const r=this.backoff.attempts;this._reconnecting=!1,this.backoff.reset(),this.emitReserved("reconnect",r)}}const ti={};function Bi(d,r){typeof d=="object"&&(r=d,d=void 0),r=r||{};const s=Yg(d,r.path||"/socket.io"),a=s.source,p=s.id,_=s.path,C=ti[p]&&_ in ti[p].nsps,R=r.forceNew||r["force new connection"]||r.multiplex===!1||C;let S;return R?S=new vo(a,r):(ti[p]||(ti[p]=new vo(a,r)),S=ti[p]),s.query&&!r.query&&(r.query=s.queryKey),S.socket(s.path,r)}Object.assign(Bi,{Manager:vo,Socket:sf,io:Bi,connect:Bi});function dy({wsUrl:d,log:r}){let s=null;function a({authPayload:C,queryToken:R}){const S=Bi(d,{transports:["polling"],timeout:2e4,reconnection:!1,auth:C,query:R?{token:R}:void 0});return s=S,S}function p(){if(s){try{s.removeAllListeners(),s.connected?s.disconnect():s.close()}catch{}s=null}}function _(){return s}return{connectSocketRaw:a,cleanupSocket:p,getSocket:_}}const cy=d=>{if(window.audioCtx=d,d.state!=="suspended")return;const r=document.body,s=["touchstart","touchend","mousedown","keydown"];s.forEach(_=>r.addEventListener(_,a,!1));function a(){d.resume().then(p)}function p(){s.forEach(_=>r.removeEventListener(_,a))}};function Pt(d){this.init(d)}Pt.prototype.init=function(d){var r={encoding:"16bitInt",channels:1,sampleRate:16e3};this.option=Object.assign({},r,d),this.flush=this.flush.bind(this),this.maxValue=this.getMaxValue(),this.typedArray=this.getTypedArray(),this.playingBufferNode=null,this.scheduledBufferNode=null,this.createContext(),this.resetState()};Pt.prototype.getMaxValue=function(){var d={"8bitInt":128,"16bitInt":32768,"32bitInt":2147483648,"32bitFloat":1};return d[this.option.encoding]?d[this.option.encoding]:d["16bitInt"]};Pt.prototype.getTypedArray=function(){var d={"8bitInt":Int8Array,"16bitInt":Int16Array,"32bitInt":Int32Array,"32bitFloat":Float32Array};return d[this.option.encoding]?d[this.option.encoding]:d["16bitInt"]};Pt.prototype.createContext=function(){this.audioCtx=new(window.AudioContext||window.webkitAudioContext),this.audioCtx.resume(),this.audioCtx.onstatechange=()=>console.log("audioCtx.state",this.audioCtx.state),cy(this.audioCtx),this.gainNode=this.audioCtx.createGain(),this.gainNode.gain.value=1,this.gainNode.connect(this.audioCtx.destination),this.startTime=this.audioCtx.currentTime};Pt.prototype.resetState=function(){this.playingStartTime=-1,this.lastGotTimestamp=0,this.samples=new Float32Array,this.timeout=void 0,this.flag_request_stop=!1,this.startTime=0};Pt.prototype.isTypedArray=function(d){return d.byteLength&&d.buffer&&d.buffer.constructor==ArrayBuffer};Pt.prototype.feed=function(d){if(this.isTypedArray(d)){d=this.getFormatedValue(d);var r=new Float32Array(this.samples.length+d.length);r.set(this.samples,0),r.set(d,this.samples.length),this.samples=r,this.timeout||this.flush()}};Pt.prototype.getFormatedValue=function(r){var r=new this.typedArray(r.buffer),s=new Float32Array(r.length),a;for(a=0;a<r.length;a++)s[a]=r[a]/this.maxValue;return s};Pt.prototype.volume=function(d){this.gainNode.gain.value=d};Pt.prototype.destroy=function(){this.interval&&clearInterval(this.interval),this.samples=null,this.audioCtx.close(),this.audioCtx=null};Pt.prototype.getTimestamp=function(d){if(this.playingStartTime>=0){if(!d)return this.audioCtx.currentTime-this.playingStartTime;const r=this.lastGotTimestamp;return this.lastGotTimestamp+=d/1e3,r}return 0};Pt.prototype.setRequestStop=function(){this.flag_request_stop=!0};Pt.prototype.setOnEnd=function(d){this.onEnd=d};Pt.prototype.interrupt=function(d){this.scheduledBufferNode&&this.scheduledBufferNode.stop(0),this.playingBufferNode&&this.playingBufferNode.stop(0),this.ensuredClearTimeout(),this.resetState(),this.flag_request_stop=!1};Pt.prototype.ensuredSetTimeout=(function(){let d;return function(r,s){d=performance.now();const a=p=>{p-d>=s?(this.timeout=void 0,r()):this.timeout=requestAnimationFrame(a)};this.timeout=requestAnimationFrame(a)}})();Pt.prototype.ensuredClearTimeout=function(){this.timeout&&(cancelAnimationFrame(this.timeout),this.timeout=void 0)};Pt.prototype.flush=function(){if(this.samples.length){var d=this.audioCtx.createBufferSource(),r=this.samples.length/this.option.channels,s=this.audioCtx.createBuffer(this.option.channels,r,this.option.sampleRate),a,p,_,C,R;for(p=0;p<this.option.channels;p++)for(a=s.getChannelData(p),_=p,R=50,C=0;C<r;C++)a[C]=this.samples[_],C<50&&(a[C]=a[C]*C/50),C>=r-51&&(a[C]=a[C]*R--/50),_+=this.option.channels;if(this.startTime<this.audioCtx.currentTime&&(this.startTime=this.audioCtx.currentTime),this.samples=new Float32Array,d.buffer=s,d.connect(this.gainNode),d.start(this.startTime),this.playingBufferNode=this.scheduledBufferNode,this.scheduledBufferNode=d,this.playingStartTime<0&&(this.playingStartTime=this.startTime),this.startTime+=s.duration,this.flag_request_stop)this.flag_request_stop=!1,d.onended=()=>{this.resetState(),this.onEnd&&this.onEnd()};else{const S=(this.startTime-this.audioCtx.currentTime)*1e3;this.ensuredSetTimeout(this.flush,S-50)}}};function hy(d,r){const s=new Pt(d),a=s.destroy.bind(s);let p=!1;return s.destroy=()=>{if(!p){p=!0;try{a()}catch{}}},s.setOnEnd(()=>{p||r()}),s._isDestroyed=()=>p,s}function py({enableAudio:d,pcmOptions:r,log:s,onPlaybackComplete:a}){let p=null,_=null;function C(){if(!d||p)return p;const W={...qp,...r||{}};return p=hy(W,()=>{a()}),p}function R(){if(p){try{p.interrupt?.(),p.destroy?.()}catch{}p=null}}function S(W){const ne=C();if(ne)try{ne.feed(W)}catch(fe){s("feedAudio: player.feed() failed",fe),a()}}function N(){if(!p){a();return}try{p.setRequestStop(),p.playingBufferNode||p.scheduledBufferNode||a()}catch(W){s("requestStop: setRequestStop() failed",W),a()}}function z(){R()}function te(){if(p)try{const W=p.audioCtx;W?.state==="running"&&W.suspend()}catch(W){s("pauseAudioPlayback: audioCtx.suspend() failed",W)}}async function j(){const W=C();if(W)try{const ne=W.audioCtx;ne?.state==="suspended"&&await ne.resume()}catch(ne){s("resumeAudioPlayback: audioCtx.resume() failed",ne)}}function se(W){_=W||null}function J(){return _}function Y(){return p?p._isDestroyed?.()??!0:!0}return{ensurePcmPlayer:C,destroyPcmPlayer:R,feedAudio:S,requestStop:N,interruptPlayback:z,pauseAudioPlayback:te,resumeAudioPlayback:j,attachAudioElement:se,getAudioElement:J,isDestroyed:Y}}function fy(d){const{wsUrl:r,restUrl:s,enableAudio:a,pcmOptions:p,debug:_,withCredentials:C,onPlaybackComplete:R}=d,S=ae.useCallback((...j)=>{_&&console.log("[RqmiiSDK]",...j)},[_]),N=ae.useRef(null),z=ae.useRef(null),te=ae.useRef(null);return N.current||(N.current=dy({wsUrl:r,log:S})),z.current||(z.current=py({enableAudio:a,pcmOptions:p,log:S,onPlaybackComplete:R})),te.current||(te.current=gg({restUrl:s,log:S,withCredentials:C})),ae.useEffect(()=>()=>{N.current?.cleanupSocket(),z.current?.destroyPcmPlayer()},[]),{socketMgrRef:N,audioMgrRef:z,sessionMgrRef:te,log:S}}function eo(d){return String(d||"").toLowerCase().replaceAll("-","_")}function my(d){if(!d)return null;if(d instanceof Uint8Array)return d;if(d instanceof ArrayBuffer)return new Uint8Array(d);if(typeof d=="object"&&d!==null){const r=d;if(r.buffer instanceof ArrayBuffer){const s=d,a=Number.isInteger(s.byteOffset)?s.byteOffset:0,p=Number.isInteger(s.byteLength)?s.byteLength:s.buffer.byteLength-a;return new Uint8Array(s.buffer,a,p)}if(r.type==="Buffer"&&Array.isArray(r.data))return new Uint8Array(r.data)}try{return new Uint8Array(d)}catch{return null}}function gy(d){const{socket:r,dispatch:s,stateRef:a,sessionIdRef:p,sessionAgentTypeRef:_,interruptedRef:C,manualDisconnectRef:R,chunkAccumulatorRef:S,clientToolsRef:N,audioMgrRef:z,enableAudio:te,cbRefs:j,eventsEmitter:se}=d,J=br,Y=z.current;r.on(J.DISCONNECT,W=>{if(s({type:"SET_CONNECTION_STATE",payload:pt.IDLE}),s({type:"SET_SESSION_READY",payload:!1}),j.current.onDisconnect?.(W),W==="io server disconnect"||W==="io client disconnect"||R.current){s({type:"SET_CONNECTION_STATE",payload:pt.ENDED});return}s({type:"SET_CONNECTION_STATE",payload:pt.FAILED}),s({type:"SET_ERROR",payload:"Connection lost"})}),r.on(J.SESSION_READY,W=>{s({type:"SET_SESSION_READY",payload:!0}),s({type:"SET_ERROR",payload:null}),W?.agentType&&s({type:"UPDATE_SESSION",payload:{agentType:eo(W.agentType)}})}),r.on(J.SESSION_JOINED,()=>{s({type:"SET_SESSION_READY",payload:!0}),s({type:"SET_ERROR",payload:null})}),r.on(J.SESSION_TERMINATED,()=>{Y.interruptPlayback(),s({type:"SET_AUDIO_PLAYING",payload:!1}),s({type:"SET_CONNECTION_STATE",payload:pt.ENDED}),s({type:"SET_SESSION_READY",payload:!1}),j.current.onSessionTerminated?.(),r.disconnect()}),r.on(J.TRANSCRIPT,W=>{const ne=W||null;s({type:"SET_TRANSCRIPT",payload:ne}),ne?.is_final&&ne?.text?.trim()&&(s({type:"ADD_MESSAGE",payload:{id:`transcript-${Date.now()}`,role:"user",text:ne.text.trim(),timestamp:new Date().toISOString()}}),s({type:"SET_PARTIAL_TRANSCRIPT",payload:null})),se.emit("transcript",ne??void 0),se.emit("partial_transcript",void 0)}),r.on(J.PARTIAL_TRANSCRIPT,W=>{const ne=typeof W=="string"?W:W?.text;if(typeof ne=="string"&&ne.length===0)return;const fe=W||null;s({type:"SET_PARTIAL_TRANSCRIPT",payload:fe}),se.emit("partial_transcript",fe??void 0)}),r.on(J.AGENT_RESPONSE_CHUNK,W=>{const{id:ne,text:fe}=S.current.addChunk(W?.requestId,W?.text);s({type:"SET_MESSAGES",payload:[...a.current.messages.filter(de=>de.id!==ne),{id:ne,role:"assistant",text:fe,streaming:!0,timestamp:new Date().toISOString()}]})}),r.on(J.AGENT_RESPONSE,W=>{const{id:ne,text:fe}=S.current.consume(W?.requestId,W?.text);s({type:"SET_MESSAGES",payload:[...a.current.messages.filter(de=>de.id!==ne),{id:ne,role:"assistant",text:fe,streaming:!1,timestamp:new Date().toISOString()}]})}),r.on(J.AVATAR_SPEAKING,()=>{s({type:"SET_AVATAR_SPEAKING",payload:!0})}),r.on(J.AVATAR_SPEAKING_DONE,()=>{s({type:"SET_AVATAR_SPEAKING",payload:!1})}),r.on(J.AGENT_AUDIO_CHUNK,W=>{if(!te||C.current)return;const ne=eo(_.current);if(ne==="cloud_avatar"||ne==="desktop_avatar"||ne==="text")return;const fe=my(W?.audio);fe&&(Y.feedAudio(fe),s({type:"SET_AUDIO_PLAYING",payload:!0}))}),r.on(J.AGENT_AUDIO_COMPLETE,()=>{if(!te)return;const W=eo(_.current);W==="cloud_avatar"||W==="desktop_avatar"||W==="text"||Y.requestStop()}),r.on(J.INTERRUPTED,()=>{const W=!Y.isDestroyed();C.current=!1,Y.interruptPlayback(),s({type:"SET_AUDIO_PLAYING",payload:!1}),W&&r.connected&&r.emit(J.AUDIO_PLAYBACK_COMPLETE,{session_id:p.current})}),r.on(J.AUTH_ERROR,W=>{s({type:"SET_CONNECTION_STATE",payload:pt.FAILED}),s({type:"SET_ERROR",payload:W?.message||"Authentication error"})}),r.on(J.ERROR,W=>{const ne=W?.code;if(!(ne==="TTS_ERROR"||ne==="STT_ERROR"||ne==="LLM_ERROR")){if(ne==="INSUFFICIENT_CREDITS"){s({type:"SET_CREDIT_EXHAUSTED",payload:{exhausted:!0,error:W?.message||"Insufficient credits to process this request."}}),j.current.onError?.(W);return}s({type:"SET_ERROR",payload:W?.message||W?.detail||"Server error"}),j.current.onError?.(W)}}),r.on(J.SESSION_EXPIRED,W=>{s({type:"SET_CONNECTION_STATE",payload:pt.ENDED}),s({type:"SET_SESSION_READY",payload:!1}),j.current.onSessionExpired?.(W)}),r.on(J.CREDITS_EXHAUSTED,()=>{s({type:"SET_CREDIT_EXHAUSTED",payload:{exhausted:!0,error:"This project has run out of credits."}}),s({type:"SET_CONNECTION_STATE",payload:pt.ENDED}),s({type:"SET_SESSION_READY",payload:!1}),R.current=!0;try{r.disconnect()}catch{}}),r.on(J.SESSION_STATE_CHANGED,W=>{W?.state&&s({type:"SET_SESSION_STATE",payload:W.state})}),r.on(J.LANGUAGE_CHANGED,W=>{const ne=W?.language;ne&&se.emit("language_changed",{language:ne})}),r.on(J.SHOW_LEAD_CAPTURE_FORM,W=>{const ne=Array.isArray(W?.fields)?W.fields:[],fe=W?.agentId;!fe||ne.length===0||s({type:"ADD_MESSAGE",payload:{id:`lead-form-${Date.now()}`,role:"lead_form",text:"",form:{agentId:fe,title:W?.title,fields:ne},timestamp:new Date().toISOString()}})}),r.on(J.MESSAGE_RATE_LIMITED,W=>{se.emit("message_rate_limited",W)}),r.on(J.CLIENT_TOOL_REQUEST,W=>{const ne=W?.executionId,fe=W?.toolName,de=W?.parameters??{},he=W?.waitForResponse!==!1;if(!fe)return;const pe=N.current[fe];if(!pe)return;const ce={minimize:()=>se.emit("minimize_chat"),maximize:()=>se.emit("maximize_chat")};he&&ne?pe(de,ce).then(Ve=>{r.emit(J.CLIENT_TOOL_RESULT,{executionId:ne,result:Ve})}).catch(Ve=>{r.emit(J.CLIENT_TOOL_RESULT,{executionId:ne,result:{error:Ve instanceof Error?Ve.message:String(Ve)}})}):pe(de,ce).catch(()=>{})})}class nf{listeners=new Map;on(r,s){return this.listeners.has(r)||this.listeners.set(r,new Set),this.listeners.get(r).add(s),()=>this.off(r,s)}once(r,s){const a=((...p)=>{this.off(r,a),s(...p)});return this.on(r,a)}off(r,s){this.listeners.get(r)?.delete(s)}emit(r,s){const a=this.listeners.get(r);if(a)for(const p of a)try{p(s)}catch{}}removeAllListeners(){this.listeners.clear()}}const af=ae.createContext(null);function of({children:d,wsUrl:r="wss://ws.rqmii.com",restUrl:s="https://api.rqmii.com",enableAudio:a=!0,pcmOptions:p,debug:_=!1,heartbeatIntervalSeconds:C=15,withCredentials:R=!1,onSessionExpired:S,onSessionTerminated:N,onError:z,onDisconnect:te}){const[j,se]=ae.useReducer(hp,po),J=ae.useRef(j),Y=ae.useCallback(be=>{J.current=hp(J.current,be),se(be)},[]),W=ae.useRef(!1),ne=ae.useRef(fg()),fe=ae.useRef(null),de=ae.useRef(po.session.agentType),he=ae.useRef(!1),pe=ae.useRef(new nf),ce=ae.useRef({}),Ve=ae.useRef({onSessionExpired:S,onSessionTerminated:N,onError:z,onDisconnect:te});ae.useEffect(()=>{Gp(),Ve.current={onSessionExpired:S,onSessionTerminated:N,onError:z,onDisconnect:te}},[S,N,z,te]),ae.useEffect(()=>{de.current=j.session.agentType},[j.session.agentType]),ae.useEffect(()=>{fe.current=j.session.sessionId},[j.session.sessionId]);const me=ae.useCallback(()=>{Y({type:"SET_AUDIO_PLAYING",payload:!1});const be=Ye.current?.getSocket();be?.connected&&be.emit(br.AUDIO_PLAYBACK_COMPLETE,{session_id:fe.current})},[]),{socketMgrRef:Ye,audioMgrRef:qe,sessionMgrRef:it}=fy({wsUrl:r,restUrl:s,enableAudio:a,pcmOptions:p,debug:_,withCredentials:R,onPlaybackComplete:me}),Je=ae.useCallback(be=>{gy({socket:be,dispatch:Y,stateRef:J,sessionIdRef:fe,sessionAgentTypeRef:de,interruptedRef:he,manualDisconnectRef:W,chunkAccumulatorRef:ne,clientToolsRef:ce,audioMgrRef:{current:qe.current},enableAudio:a,cbRefs:Ve,eventsEmitter:pe.current})},[a]),at=ae.useCallback(({authPayload:be,queryToken:Ze})=>new Promise((Bt,nr)=>{Ye.current?.cleanupSocket();const It=Ye.current.connectSocketRaw({authPayload:be,queryToken:Ze});Je(It),It.once("connect",()=>{Y({type:"SET_CONNECTION_STATE",payload:pt.CONNECTED}),Y({type:"SET_ERROR",payload:null}),Bt(It)}),It.once("connect_error",xr=>{Y({type:"SET_CONNECTION_STATE",payload:pt.FAILED}),Y({type:"SET_ERROR",payload:xr?.message||"Connection error"}),nr(xr)})}),[Je]),tt=ae.useCallback(({keepManualDisconnect:be=!1}={})=>{W.current=!0,he.current=!1,ne.current.clear(),qe.current.destroyPcmPlayer(),Ye.current.cleanupSocket(),be||(W.current=!1),Y({type:"HARD_RESET"})},[]),qt=ae.useCallback(async({apiKey:be,publicChatId:Ze,agentId:Bt,userId:nr,language:It="en",clientTools:xr,config:yt}={})=>{if(!be&&!Ze&&!Bt)throw new Error("Provide one of apiKey, publicChatId, or agentId");tt(),ce.current=xr??{},Y({type:"SET_CONNECTION_STATE",payload:pt.INITIALIZING}),Y({type:"SET_ERROR",payload:null});const Lr=mg();let Br;try{Br=await it.current.initializeSession({apiKey:be,publicChatId:Ze,agentId:Bt,userId:nr,language:It,timezone:Lr,config:yt})}catch(ir){const Wt=ir;throw Wt.status===401||Wt.status===403?(Y({type:"SET_CONNECTION_STATE",payload:pt.FAILED}),Y({type:"SET_ERROR",payload:Wt.message||"Authentication failed"})):Wt.status===402?(Y({type:"SET_CREDIT_EXHAUSTED",payload:{exhausted:!0,error:Wt.message||"Insufficient credits"}}),Y({type:"SET_CONNECTION_STATE",payload:pt.FAILED})):Wt.status===429?(Y({type:"SET_CONNECTION_STATE",payload:pt.FAILED}),Y({type:"SET_ERROR",payload:Wt.message||"Too many requests. Please try again later."})):(Y({type:"SET_CONNECTION_STATE",payload:pt.FAILED}),Y({type:"SET_ERROR",payload:Wt.message||"Failed to initialize session"})),ir}const Nt=Br;Y({type:"UPDATE_SESSION",payload:{sessionId:Nt.session_id,agentType:Nt.streaming_url?hi.CLOUD_AVATAR:j.session.agentType,streamingUrl:Nt.streaming_url||null,uniqueId:Nt.unique_id||null}}),Y({type:"SET_CONNECTION_STATE",payload:pt.CONNECTING}),Y({type:"SET_CLOUD_STREAM_STATE",payload:{state:Nt.streaming_url?Zt.CONNECTING:Zt.IDLE,error:null}}),W.current=!0;try{await at({authPayload:{token:Nt.session_token},queryToken:Nt.session_token}),W.current=!1}catch(ir){throw W.current=!1,ir}return Br},[at,tt,r,j.session.agentType]),xt=ae.useCallback(async({uniqueId:be})=>{if(!be)throw new Error("uniqueId is required");tt(),Y({type:"SET_CONNECTION_STATE",payload:pt.INITIALIZING}),Y({type:"SET_ERROR",payload:null});let Ze;try{Ze=await it.current.joinDesktopSession({uniqueId:be})}catch(nr){const It=nr;throw(It.status===401||It.status===403)&&(Y({type:"SET_CONNECTION_STATE",payload:pt.FAILED}),Y({type:"SET_ERROR",payload:It.message||"Authentication failed"})),It.status===402&&(Y({type:"SET_CREDIT_EXHAUSTED",payload:{exhausted:!0,error:It.message||"Insufficient credits"}}),Y({type:"SET_CONNECTION_STATE",payload:pt.FAILED})),It.status===429&&(Y({type:"SET_CONNECTION_STATE",payload:pt.FAILED}),Y({type:"SET_ERROR",payload:It.message||"Too many requests. Please try again later."})),nr}const Bt=Ze;Y({type:"UPDATE_SESSION",payload:{sessionId:Bt.session_id,uniqueId:be,role:"user",agentType:hi.DESKTOP_AVATAR}}),Y({type:"SET_CONNECTION_STATE",payload:pt.CONNECTING}),Y({type:"SET_CLOUD_STREAM_STATE",payload:{state:Zt.IDLE,error:null}}),W.current=!0;try{await at({authPayload:{token:Bt.session_token},queryToken:Bt.session_token}),W.current=!1}catch(nr){throw W.current=!1,nr}return Ze},[at,tt,r]),Ke=ae.useCallback(()=>tt({keepManualDisconnect:!0}),[tt]),We=ae.useCallback(async()=>{const be=Ye.current?.getSocket();return be&&j.isConnected&&(be.emit("end_session"),await new Promise(Ze=>setTimeout(Ze,150))),Ke(),{success:!0}},[Ke,j.isConnected]),st=ae.useCallback(()=>{const be=Ye.current?.getSocket();be?.connected?be.emit("end_session"):(Y({type:"SET_CONNECTION_STATE",payload:pt.ENDED}),Y({type:"SET_SESSION_READY",payload:!1}))},[]),ze=ae.useCallback((be,Ze={})=>{const Bt=Ye.current?.getSocket();return!Bt||!j.isConnected?!1:(Bt.emit(be,Ze),!0)},[j.isConnected]),Rt=ae.useCallback(be=>!be||!String(be).trim()?!1:(Y({type:"ADD_MESSAGE",payload:{id:`user-${Date.now()}`,role:"user",text:String(be),timestamp:new Date().toISOString()}}),ze(br.USER_MESSAGE,{message:String(be)})),[ze]),sr=ae.useCallback((be,Ze)=>{!Ze||!String(Ze).trim()||Y({type:"ADD_MESSAGE",payload:{id:`${be}-${Date.now()}`,role:be,text:String(Ze),timestamp:new Date().toISOString()}})},[]),Xr=ae.useCallback(be=>!be||!String(be).trim()?!1:ze(br.USER_MESSAGE,{message:String(be)}),[ze]),Vs=ae.useCallback(be=>ze(br.AUDIO_CHUNK,{audio:be}),[ze]),Yr=ae.useCallback(()=>ze(br.AUDIO_END,{}),[ze]),Jr=ae.useCallback(()=>(he.current=!0,qe.current.interruptPlayback(),Y({type:"SET_AUDIO_PLAYING",payload:!1}),ze(br.INTERRUPT,{})),[ze]),Gs=ae.useCallback(()=>ze(br.CLEAR_SESSION_HISTORY,{}),[ze]),rt=ae.useCallback(be=>be?ze(br.CHANGE_SESSION_LANGUAGE,{language:be}):!1,[ze]),Er=ae.useCallback((be={})=>ze(br.CLIENT_READY,be),[ze]),lt=ae.useCallback(()=>{ne.current.clear(),Y({type:"SET_MESSAGES",payload:[]})},[]),Zr=ae.useCallback(be=>{Y({type:"SET_MESSAGES",payload:be})},[]),er=ae.useCallback(()=>qe.current.resumeAudioPlayback(),[]),$r=ae.useCallback(()=>qe.current.pauseAudioPlayback(),[]),gt=ae.useCallback(be=>qe.current.attachAudioElement(be),[]),ft=ae.useCallback((be,Ze=null)=>{Y({type:"SET_CLOUD_STREAM_STATE",payload:{state:be,error:Ze?String(Ze):null}})},[]),At=ae.useCallback(async be=>{try{const Ze=await it.current.fetchAgentConfig(be);return Y({type:"SET_AGENT_CONFIG",payload:Ze}),Ze}catch(Ze){throw Y({type:"SET_AGENT_CONFIG",payload:null}),Ze}},[s]),Ct=ae.useCallback(be=>{Object.keys(ce.current).length===0?ce.current=be:Object.assign(ce.current,be)},[]),es=ae.useCallback(be=>{const Ze=be.sessionId||fe.current;return Ze?it.current.submitFeedback({sessionId:Ze,rating:be.rating,feedback:be.feedback,endedBy:be.endedBy}):Promise.reject(new Error("No session id available for feedback"))},[]),ts=ae.useCallback(be=>{const Ze=be.sessionId||fe.current;return Ze?it.current.submitLead({agentId:be.agentId,sessionId:Ze,collectedData:be.collectedData}):Promise.reject(new Error("No session id available for lead capture"))},[]),qs=ae.useMemo(()=>pg(j.sessionState),[j.sessionState]),zr=ae.useMemo(()=>({...j,...qs,initializeSession:qt,joinDesktopSession:xt,disconnect:Ke,terminateSession:We,endSession:st,emit:ze,sendTextMessage:Rt,addLocalMessage:sr,emitUserMessage:Xr,sendAudioChunk:Vs,endAudioStream:Yr,interrupt:Jr,clearSessionHistory:Gs,changeSessionLanguage:rt,signalClientReady:Er,clearMessages:lt,setMessages:Zr,resumeAudioPlayback:er,pauseAudioPlayback:$r,attachAudioElement:gt,fetchAgentConfig:At,submitFeedback:es,submitLead:ts,setCloudStreamState:ft,registerClientTools:Ct,events:pe.current,audioElement:qe.current?.getAudioElement()??null,socket:Ye.current?.getSocket()??null}),[j,qs,qt,xt,Ke,We,st,ze,Rt,sr,Xr,Vs,Yr,Jr,Gs,rt,Er,lt,Zr,er,$r,gt,ft,Ct,es,ts]);return Jt.jsx(af.Provider,{value:zr,children:d})}function Fs(){const d=ae.useContext(af);if(!d)throw new Error("useRqmiiAgentContext must be used inside <RqmiiAgentProvider>");return d}function lf(){const d=Fs();return{connectionState:d.connectionState,isConnected:d.isConnected,isSessionReady:d.isSessionReady,error:d.error,session:d.session,creditExhausted:d.creditExhausted,creditError:d.creditError,sessionState:d.sessionState,isSessionTerminated:d.isSessionTerminated,isSessionTerminating:d.isSessionTerminating,isAgentThinking:d.isAgentThinking,isAgentSpeaking:d.isAgentSpeaking,isToolExecuting:d.isToolExecuting,agentConfig:d.agentConfig,initializeSession:d.initializeSession,joinDesktopSession:d.joinDesktopSession,disconnect:d.disconnect,terminateSession:d.terminateSession,endSession:d.endSession,interrupt:d.interrupt,clearSessionHistory:d.clearSessionHistory,changeSessionLanguage:d.changeSessionLanguage,signalClientReady:d.signalClientReady,fetchAgentConfig:d.fetchAgentConfig,submitFeedback:d.submitFeedback,registerClientTools:d.registerClientTools,events:d.events}}function yy(){const d=Fs();return{messages:d.messages,sendTextMessage:d.sendTextMessage,addLocalMessage:d.addLocalMessage,emitUserMessage:d.emitUserMessage,clearMessages:d.clearMessages}}function wy(){const d=Fs();return{sendAudioChunk:d.sendAudioChunk,endAudioStream:d.endAudioStream,isAudioPlaying:d.isAudioPlaying,transcript:d.transcript,partialTranscript:d.partialTranscript,interrupt:d.interrupt,resumeAudioPlayback:d.resumeAudioPlayback,pauseAudioPlayback:d.pauseAudioPlayback,attachAudioElement:d.attachAudioElement}}function uf(){const d=Fs(),r=d.cloudStream?.state||Zt.IDLE;return{streamingUrl:d.session.streamingUrl,isAvatarSpeaking:d.isAvatarSpeaking,speakingSource:"avatar_events",isCloudAvatar:d.session.agentType===hi.CLOUD_AVATAR,isDesktopAvatar:d.session.agentType===hi.DESKTOP_AVATAR,cloudStreamState:r,cloudStreamError:d.cloudStream?.error||null,isCloudStreamConnected:r===Zt.CONNECTED,isCloudStreamLoading:r===Zt.CONNECTING||r===Zt.LOADING,setCloudStreamState:d.setCloudStreamState}}var to={},ro={},ri={},wp;function df(){if(wp)return ri;wp=1,Object.defineProperty(ri,"__esModule",{value:!0}),ri.baseAssetPath=void 0;const r=typeof window<"u"&&typeof window.document<"u"?window.document.currentScript:null;let s="/";return r&&(s=r.src.replace(/#.*$/,"").replace(/\?.*$/,"").replace(/\/[^/]+$/,"/")),ri.baseAssetPath=s,ri}var si={},vp;function Io(){if(vp)return si;vp=1,Object.defineProperty(si,"__esModule",{value:!0}),si.defaultModelFetcher=void 0;const d=r=>fetch(r).then(s=>s.arrayBuffer());return si.defaultModelFetcher=d,si}var Wr={},ni={},_p;function pn(){if(_p)return ni;_p=1,Object.defineProperty(ni,"__esModule",{value:!0}),ni.log=void 0;const d=r=>s=>{console.log(`VAD | ${r} >`,s)};return ni.log={error:d("error"),debug:d("debug"),warn:d("warn")},ni}var ii={},bp;function qi(){if(bp)return ii;bp=1,Object.defineProperty(ii,"__esModule",{value:!0}),ii.Message=void 0;var d;return(function(r){r.AudioFrame="AUDIO_FRAME",r.SpeechStart="SPEECH_START",r.VADMisfire="VAD_MISFIRE",r.SpeechEnd="SPEECH_END",r.SpeechStop="SPEECH_STOP",r.SpeechRealStart="SPEECH_REAL_START",r.FrameProcessed="FRAME_PROCESSED"})(d||(ii.Message=d={})),ii}var Sp;function Mo(){if(Sp)return Wr;Sp=1,Object.defineProperty(Wr,"__esModule",{value:!0}),Wr.FrameProcessor=Wr.validateOptions=Wr.defaultFrameProcessorOptions=void 0;const d=pn(),r=qi();Wr.defaultFrameProcessorOptions={positiveSpeechThreshold:.3,negativeSpeechThreshold:.25,preSpeechPadMs:800,redemptionMs:1400,minSpeechMs:400,submitUserSpeechOnPause:!1};function s(C){(C.positiveSpeechThreshold<0||C.positiveSpeechThreshold>1)&&d.log.error("positiveSpeechThreshold should be a number between 0 and 1"),(C.negativeSpeechThreshold<0||C.negativeSpeechThreshold>C.positiveSpeechThreshold)&&d.log.error("negativeSpeechThreshold should be between 0 and positiveSpeechThreshold"),C.preSpeechPadMs<0&&d.log.error("preSpeechPadMs should be positive"),C.redemptionMs<0&&d.log.error("redemptionMs should be positive"),C.minSpeechMs<0&&d.log.error("minSpeechMs should be positive")}Wr.validateOptions=s;const a=C=>{const R=C.reduce((N,z)=>(N.push(N.at(-1)+z.length),N),[0]),S=new Float32Array(R.at(-1));return C.forEach((N,z)=>{const te=R[z];S.set(N,te)}),S};function p(C,R){const S=Math.floor(C.redemptionMs/R),N=Math.floor(C.preSpeechPadMs/R),z=Math.floor(C.minSpeechMs/R);return{redemptionFrames:S,preSpeechPadFrames:N,minSpeechFrames:z}}class _{constructor(R,S,N,z){this.modelProcessFunc=R,this.modelResetFunc=S,this.options=N,this.msPerFrame=z,this.speaking=!1,this.redemptionCounter=0,this.speechFrameCount=0,this.active=!1,this.speechRealStartFired=!1,this.setOptions=J=>{this.options={...this.options,...J};const{redemptionFrames:Y,preSpeechPadFrames:W,minSpeechFrames:ne}=p(this.options,this.msPerFrame);this.redemptionFrames=Y,this.preSpeechPadFrames=W,this.minSpeechFrames=ne},this.reset=()=>{this.speaking=!1,this.speechRealStartFired=!1,this.audioBuffer=[],this.modelResetFunc(),this.redemptionCounter=0,this.speechFrameCount=0},this.pause=J=>{this.active=!1,this.options.submitUserSpeechOnPause?this.endSegment(J):this.reset()},this.resume=()=>{this.active=!0},this.endSegment=J=>{const Y=this.audioBuffer;this.audioBuffer=[];const W=this.speaking;if(this.reset(),W)if(Y.reduce((fe,de)=>de.isSpeech?fe+1:fe,0)>=this.minSpeechFrames){const fe=a(Y.map(de=>de.frame));J({msg:r.Message.SpeechEnd,audio:fe})}else J({msg:r.Message.VADMisfire});return{}},this.process=async(J,Y)=>{if(!this.active)return;const W=await this.modelProcessFunc(J),ne=W.isSpeech>=this.options.positiveSpeechThreshold;if(Y({probs:W,msg:r.Message.FrameProcessed,frame:J}),this.audioBuffer.push({frame:J,isSpeech:ne}),ne&&(this.speechFrameCount++,this.redemptionCounter=0),ne&&!this.speaking&&(this.speaking=!0,Y({msg:r.Message.SpeechStart})),this.speaking&&this.speechFrameCount===this.minSpeechFrames&&!this.speechRealStartFired&&(this.speechRealStartFired=!0,Y({msg:r.Message.SpeechRealStart})),W.isSpeech<this.options.negativeSpeechThreshold&&this.speaking&&++this.redemptionCounter>=this.redemptionFrames){this.redemptionCounter=0,this.speechFrameCount=0,this.speaking=!1,this.speechRealStartFired=!1;const fe=this.audioBuffer;if(this.audioBuffer=[],fe.reduce((he,pe)=>pe.isSpeech?he+1:he,0)>=this.minSpeechFrames){const he=a(fe.map(pe=>pe.frame));Y({msg:r.Message.SpeechEnd,audio:he})}else Y({msg:r.Message.VADMisfire})}if(!this.speaking){for(;this.audioBuffer.length>this.preSpeechPadFrames;)this.audioBuffer.shift();this.speechFrameCount=0}},this.audioBuffer=[];const{redemptionFrames:te,preSpeechPadFrames:j,minSpeechFrames:se}=p(this.options,this.msPerFrame);this.redemptionFrames=te,this.preSpeechPadFrames=j,this.minSpeechFrames=se,this.reset()}}return Wr.FrameProcessor=_,Wr}var Hr={};function dr(d){throw new Error('Could not dynamically require "'+d+'". Please configure the dynamicRequireTargets or/and ignoreDynamicRequires option of @rollup/plugin-commonjs appropriately for this require call to work.')}var so={exports:{}};/*!
2
2
  * ONNX Runtime Web v1.26.0
3
3
  * Copyright (c) Microsoft Corporation. All rights reserved.
4
4
  * Licensed under the MIT License.
@@ -2915,4 +2915,4 @@ Msg: ${s}`;console.warn(a)}}T.verboseLogLevel=5,(function(d){d.LIST_STREAMERS="l
2915
2915
  `),this.gl.compileShader(s);const a=this.gl.createProgram();this.gl.attachShader(a,r),this.gl.attachShader(a,s),this.gl.linkProgram(a),this.gl.useProgram(a),this.positionLocation=this.gl.getAttribLocation(a,"a_position"),this.texcoordLocation=this.gl.getAttribLocation(a,"a_texCoord")}updateVideoTexture(){this.videoTexture||(this.videoTexture=this.gl.createTexture(),this.gl.bindTexture(this.gl.TEXTURE_2D,this.videoTexture),this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_WRAP_S,this.gl.CLAMP_TO_EDGE),this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_WRAP_T,this.gl.CLAMP_TO_EDGE),this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_MIN_FILTER,this.gl.LINEAR),this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_MAG_FILTER,this.gl.LINEAR));let r=this.webRtcController.videoPlayer.getVideoElement().videoHeight,s=this.webRtcController.videoPlayer.getVideoElement().videoWidth;this.prevVideoHeight!=r||this.prevVideoWidth!=s?this.gl.texImage2D(this.gl.TEXTURE_2D,0,this.gl.RGBA,s,r,0,this.gl.RGBA,this.gl.UNSIGNED_BYTE,this.webRtcController.videoPlayer.getVideoElement()):this.gl.texSubImage2D(this.gl.TEXTURE_2D,0,0,0,s,r,this.gl.RGBA,this.gl.UNSIGNED_BYTE,this.webRtcController.videoPlayer.getVideoElement()),this.prevVideoHeight=r,this.prevVideoWidth=s}initBuffers(){this.positionBuffer=this.gl.createBuffer(),this.gl.bindBuffer(this.gl.ARRAY_BUFFER,this.positionBuffer),this.gl.enableVertexAttribArray(this.positionLocation),this.gl.bufferData(this.gl.ARRAY_BUFFER,new Float32Array([-1,1,1,1,-1,-1,-1,-1,1,1,1,-1]),this.gl.STATIC_DRAW),this.gl.vertexAttribPointer(this.positionLocation,2,this.gl.FLOAT,!1,0,0),this.texcoordBuffer=this.gl.createBuffer(),this.gl.bindBuffer(this.gl.ARRAY_BUFFER,this.texcoordBuffer),this.gl.enableVertexAttribArray(this.texcoordLocation),this.gl.bufferData(this.gl.ARRAY_BUFFER,new Float32Array([0,0,1,0,0,1,0,1,1,0,1,1]),this.gl.STATIC_DRAW),this.gl.vertexAttribPointer(this.texcoordLocation,2,this.gl.FLOAT,!1,0,0)}onXrSessionStarted(r){T.Log(T.GetStackTrace(),"XR Session started"),this.xrSession=r,this.xrSession.addEventListener("end",(()=>{this.onXrSessionEnded()})),this.initGL(),this.initShaders(),this.initBuffers(),r.requestReferenceSpace("local").then((s=>{if(this.xrRefSpace=s,this.xrSession.updateRenderState({baseLayer:new XRWebGLLayer(this.xrSession,this.gl)}),this.xrSession.supportedFrameRates)for(let a of this.xrSession.supportedFrameRates)a==90&&r.updateTargetFrameRate(90);this.xrSession.requestAnimationFrame(this.onXrFrame.bind(this))})),this.onSessionStarted.dispatchEvent(new Event("xrSessionStarted"))}sendXRDataToUE(){if(this.leftView==null||this.rightView==null)return;const r=this.leftView.transform.matrix,s=this.leftView.projectionMatrix,a=this.rightView.transform.matrix,p=this.rightView.projectionMatrix;this.webRtcController.streamMessageController.toStreamerHandlers.get("XREyeViews")([r[0],r[4],r[8],r[12],r[1],r[5],r[9],r[13],r[2],r[6],r[10],r[14],r[3],r[7],r[11],r[15],s[0],s[4],s[8],s[12],s[1],s[5],s[9],s[13],s[2],s[6],s[10],s[14],s[3],s[7],s[11],s[15],a[0],a[4],a[8],a[12],a[1],a[5],a[9],a[13],a[2],a[6],a[10],a[14],a[3],a[7],a[11],a[15],p[0],p[4],p[8],p[12],p[1],p[5],p[9],p[13],p[2],p[6],p[10],p[14],p[3],p[7],p[11],p[15]])}onXrFrame(r,s){if(this.xrViewerPose=s.getViewerPose(this.xrRefSpace),this.xrViewerPose){if(this.updateViews(),this.leftView==null||this.rightView==null)return;this.sendXRDataToUE(),this.updateVideoTexture(),this.render()}this.webRtcController.config.isFlagEnabled(X.XRControllerInput)&&this.xrSession.inputSources.forEach(((a,p,_)=>{this.xrGamepadController.updateStatus(a,s,this.xrRefSpace)}),this),this.xrSession.requestAnimationFrame(((a,p)=>this.onXrFrame(a,p))),this.onFrame.dispatchEvent(new Yf({time:r,frame:s}))}updateViews(){if(this.xrViewerPose)for(const r of this.xrViewerPose.views)r.eye==="left"?this.leftView=r:r.eye==="right"&&(this.rightView=r)}render(){if(!this.gl)return;const r=this.xrSession.renderState.baseLayer;this.gl.bindFramebuffer(this.gl.FRAMEBUFFER,r.framebuffer),this.gl.viewport(0,0,r.framebufferWidth,r.framebufferHeight),this.gl.drawArrays(this.gl.TRIANGLES,0,6)}static isSessionSupported(r){return location.protocol!=="https:"&&T.Info(null,"WebXR requires https, if you want WebXR use https."),navigator.xr?navigator.xr.isSessionSupported(r):new Promise((()=>!1))}}class xw{constructor(r){this.editTextButton=null,this.hiddenInput=null,"ontouchstart"in document.documentElement&&this.createOnScreenKeyboardHelpers(r)}unquantizeAndDenormalizeUnsigned(r,s){return null}createOnScreenKeyboardHelpers(r){this.hiddenInput||(this.hiddenInput=document.createElement("input"),this.hiddenInput.id="hiddenInput",this.hiddenInput.maxLength=0,this.hiddenInput.style.position="absolute",this.hiddenInput.style.left="-10%",this.hiddenInput.style.width="0px",this.hiddenInput.style.opacity="0",r.appendChild(this.hiddenInput)),this.editTextButton||(this.editTextButton=document.createElement("button"),this.editTextButton.id="editTextButton",this.editTextButton.innerHTML="edit text",r.appendChild(this.editTextButton),this.editTextButton.style.display="none",this.editTextButton.addEventListener("touchend",(s=>{this.hiddenInput.focus(),s.preventDefault()})))}showOnScreenKeyboard(r){if(r.showOnScreenKeyboard){this.editTextButton.style.display="default";const s=this.unquantizeAndDenormalizeUnsigned(r.x,r.y);this.editTextButton.style.top=s.y.toString()+"px",this.editTextButton.style.left=(s.x-40).toString()+"px"}else this.editTextButton.style.display="none",this.hiddenInput.blur()}}class Cw{constructor(r){this.seq=r.Seq,this.playerSentTimestamp=Date.now(),this.requestFillerSize=r.Filler?r.Filler.length:0}update(r){this.playerReceivedTimestamp=Date.now(),this.streamerReceivedTimestamp=r.ReceivedTimestamp,this.streamerSentTimestamp=r.SentTimestamp,this.responseFillerSize=r.Filler?r.Filler.length:0}}class kw{constructor(r,s){this.sink=r,this.callback=s,this.records=new Map,this.seq=0}start(r){return!this.isRunning()&&(this.startTime=Date.now(),this.records.clear(),this.interval=setInterval((()=>{Date.now()-this.startTime>=r.duration?this.stop():this.sendRequest(r.requestSize,r.responseSize)}).bind(this),Math.floor(1e3/r.rps)),!0)}stop(){this.interval&&(clearInterval(this.interval),this.interval=void 0,this.callback(this.produceResult()))}produceResult(){const r=new Map(this.records);return{records:r,dataChannelRtt:Math.ceil(Array.from(this.records.values()).reduce(((s,a)=>s+(a.playerReceivedTimestamp-a.playerSentTimestamp)),0)/this.records.size),playerToStreamerTime:Math.ceil(Array.from(this.records.values()).reduce(((s,a)=>s+(a.streamerReceivedTimestamp-a.playerSentTimestamp)),0)/this.records.size),streamerToPlayerTime:Math.ceil(Array.from(this.records.values()).reduce(((s,a)=>s+(a.playerReceivedTimestamp-a.streamerSentTimestamp)),0)/this.records.size),exportLatencyAsCSV:()=>{let s=`Timestamp;RTT;PlayerToStreamer;StreamerToPlayer;
2916
2916
  `;return r.forEach((a=>{s+=a.playerSentTimestamp+";",s+=a.playerReceivedTimestamp-a.playerSentTimestamp+";",s+=a.streamerReceivedTimestamp-a.playerSentTimestamp+";",s+=a.playerReceivedTimestamp-a.streamerSentTimestamp+";",s+=`
2917
2917
  `})),s}}}isRunning(){return!!this.interval}receive(r){if(!this.isRunning())return;if(!r)return void T.Error(T.GetStackTrace(),"Undefined response from server");let s=this.records.get(r.Seq);s&&s.update(r)}sendRequest(r,s){let a=this.createRequest(r,s),p=new Cw(a);this.records.set(p.seq,p),this.sink(a)}createRequest(r,s){return{Seq:this.seq++,FillResponseSize:s,Filler:r?"A".repeat(r):""}}}class Rw{constructor(r,s){this.allowConsoleCommands=!1,this.config=r,s?.videoElementParent&&(this._videoElementParent=s.videoElementParent),this._eventEmitter=new em,this.configureSettings(),this.setWebRtcPlayerController(new hm(this.config,this)),this.onScreenKeyboardHelper=new xw(this.videoElementParent),this.onScreenKeyboardHelper.unquantizeAndDenormalizeUnsigned=(a,p)=>this._webRtcController.requestUnquantizedAndDenormalizeUnsigned(a,p),this._activateOnScreenKeyboard=a=>this.onScreenKeyboardHelper.showOnScreenKeyboard(a),this._webXrController=new pm(this._webRtcController),this._setupWebRtcTCPRelayDetection=this._setupWebRtcTCPRelayDetection.bind(this),this._eventEmitter.addEventListener("webRtcConnected",(a=>{this._eventEmitter.addEventListener("statsReceived",this._setupWebRtcTCPRelayDetection)}))}get videoElementParent(){return this._videoElementParent||(this._videoElementParent=document.createElement("div"),this._videoElementParent.id="videoElementParent"),this._videoElementParent}configureSettings(){this.config._addOnSettingChangedListener(X.IsQualityController,(r=>{r!==!0||this._webRtcController.isQualityController||this._webRtcController.sendRequestQualityControlOwnership()})),this.config._addOnSettingChangedListener(X.AFKDetection,(r=>{this._webRtcController.setAfkEnabled(r)})),this.config._addOnSettingChangedListener(X.MatchViewportResolution,(()=>{this._webRtcController.videoPlayer.updateVideoStreamSize()})),this.config._addOnSettingChangedListener(X.HoveringMouseMode,(r=>{this.config.setFlagLabel(X.HoveringMouseMode,`Control Scheme: ${r?"Hovering":"Locked"} Mouse`),this._webRtcController.setMouseInputEnabled(this.config.isFlagEnabled(X.MouseInput))})),this.config._addOnSettingChangedListener(X.KeyboardInput,(r=>{this._webRtcController.setKeyboardInputEnabled(r)})),this.config._addOnSettingChangedListener(X.MouseInput,(r=>{this._webRtcController.setMouseInputEnabled(r)})),this.config._addOnSettingChangedListener(X.FakeMouseWithTouches,(r=>{this._webRtcController.setTouchInputEnabled(this.config.isFlagEnabled(X.TouchInput))})),this.config._addOnSettingChangedListener(X.TouchInput,(r=>{this._webRtcController.setTouchInputEnabled(r)})),this.config._addOnSettingChangedListener(X.GamepadInput,(r=>{this._webRtcController.setGamePadInputEnabled(r)})),this.config._addOnNumericSettingChangedListener(ge.MinQP,(r=>{T.Log(T.GetStackTrace(),"-------- Sending MinQP --------",7),this._webRtcController.sendEncoderMinQP(r),T.Log(T.GetStackTrace(),"-------------------------------------------",7)})),this.config._addOnNumericSettingChangedListener(ge.MaxQP,(r=>{T.Log(T.GetStackTrace(),"-------- Sending encoder settings --------",7),this._webRtcController.sendEncoderMaxQP(r),T.Log(T.GetStackTrace(),"-------------------------------------------",7)})),this.config._addOnNumericSettingChangedListener(ge.WebRTCMinBitrate,(r=>{T.Log(T.GetStackTrace(),"-------- Sending web rtc settings --------",7),this._webRtcController.sendWebRTCMinBitrate(1e3*r),T.Log(T.GetStackTrace(),"-------------------------------------------",7)})),this.config._addOnNumericSettingChangedListener(ge.WebRTCMaxBitrate,(r=>{T.Log(T.GetStackTrace(),"-------- Sending web rtc settings --------",7),this._webRtcController.sendWebRTCMaxBitrate(1e3*r),T.Log(T.GetStackTrace(),"-------------------------------------------",7)})),this.config._addOnNumericSettingChangedListener(ge.WebRTCFPS,(r=>{T.Log(T.GetStackTrace(),"-------- Sending web rtc settings --------",7),this._webRtcController.sendWebRTCFps(r),T.Log(T.GetStackTrace(),"-------------------------------------------",7)})),this.config._addOnOptionSettingChangedListener(dt.PreferredCodec,(r=>{this._webRtcController&&this._webRtcController.setPreferredCodec(r)})),this.config._registerOnChangeEvents(this._eventEmitter)}_activateOnScreenKeyboard(r){throw new Error("Method not implemented.")}_onInputControlOwnership(r){this._inputController=r}setWebRtcPlayerController(r){this._webRtcController=r,this._webRtcController.setPreferredCodec(this.config.getSettingOption(dt.PreferredCodec).selected),this._webRtcController.resizePlayerStyle(),this.checkForAutoConnect()}connect(){this._eventEmitter.dispatchEvent(new Lf),this._webRtcController.connectToSignallingServer()}reconnect(){this._eventEmitter.dispatchEvent(new Nf),this._webRtcController.tryReconnect("Reconnecting...")}disconnect(){this._eventEmitter.dispatchEvent(new Bf),this._webRtcController.close()}play(){this._onStreamLoading(),this._webRtcController.playStream()}checkForAutoConnect(){this.config.isFlagEnabled(X.AutoConnect)&&(this._onWebRtcAutoConnect(),this._webRtcController.connectToSignallingServer())}unmuteMicrophone(r=!1){if(!this.config.isFlagEnabled("UseMic"))return r?(this.config.setFlagEnabled("UseMic",!0),void this.reconnect()):void T.Warning(T.GetStackTrace(),"Trying to unmute mic, but PixelStreaming was initialized with no microphone track. Call with forceEnable == true to re-connect with a mic track.");this.setMicrophoneMuted(!1)}muteMicrophone(){this.config.isFlagEnabled("UseMic")?this.setMicrophoneMuted(!0):T.Info(T.GetStackTrace(),"Trying to mute mic, but PixelStreaming has no microphone track, so sending sound is already disabled.")}setMicrophoneMuted(r){var s,a,p,_;for(const C of(_=(p=(a=(s=this._webRtcController)===null||s===void 0?void 0:s.peerConnectionController)===null||a===void 0?void 0:a.peerConnection)===null||p===void 0?void 0:p.getTransceivers())!==null&&_!==void 0?_:[])om.canTransceiverSendAudio(C)&&(C.sender.track.enabled=!r)}_onWebRtcAutoConnect(){this._eventEmitter.dispatchEvent(new Cf)}_onWebRtcSdp(){this._eventEmitter.dispatchEvent(new xf)}_onStreamLoading(){this._eventEmitter.dispatchEvent(new zf)}_onDisconnect(r,s){this._eventEmitter.dispatchEvent(new If({eventString:r,allowClickToReconnect:s}))}_onWebRtcConnecting(){this._eventEmitter.dispatchEvent(new kf)}_onWebRtcConnected(){this._eventEmitter.dispatchEvent(new Rf)}_onWebRtcFailed(){this._eventEmitter.dispatchEvent(new Af)}_onVideoInitialized(){this._eventEmitter.dispatchEvent(new Df),this._videoStartTime=Date.now()}_onLatencyTestResult(r){this._eventEmitter.dispatchEvent(new jf({latencyTimings:r}))}_onDataChannelLatencyTestResponse(r){this._eventEmitter.dispatchEvent(new Kf({response:r}))}_onVideoStats(r){this._videoStartTime&&this._videoStartTime!==void 0||(this._videoStartTime=Date.now()),r.handleSessionStatistics(this._videoStartTime,this._inputController,this._webRtcController.videoAvgQp),this._eventEmitter.dispatchEvent(new qf({aggregatedStats:r}))}_onVideoEncoderAvgQP(r){this._eventEmitter.dispatchEvent(new $f({avgQP:r}))}_onInitialSettings(r){var s;this._eventEmitter.dispatchEvent(new Xf({settings:r})),r.PixelStreamingSettings&&(this.allowConsoleCommands=(s=r.PixelStreamingSettings.AllowPixelStreamingCommands)!==null&&s!==void 0&&s,this.allowConsoleCommands===!1&&T.Info(T.GetStackTrace(),"-AllowPixelStreamingCommands=false, sending arbitrary console commands from browser to UE is disabled."));const a=this.config.useUrlParams,p=new URLSearchParams(window.location.search);T.Info(T.GetStackTrace(),`using URL parameters ${a}`),r.EncoderSettings&&(this.config.setNumericSetting(ge.MinQP,a&&p.has(ge.MinQP)?Number.parseFloat(p.get(ge.MinQP)):r.EncoderSettings.MinQP),this.config.setNumericSetting(ge.MaxQP,a&&p.has(ge.MaxQP)?Number.parseFloat(p.get(ge.MaxQP)):r.EncoderSettings.MaxQP)),r.WebRTCSettings&&(this.config.setNumericSetting(ge.WebRTCMinBitrate,a&&p.has(ge.WebRTCMinBitrate)?Number.parseFloat(p.get(ge.WebRTCMinBitrate)):r.WebRTCSettings.MinBitrate/1e3),this.config.setNumericSetting(ge.WebRTCMaxBitrate,a&&p.has(ge.WebRTCMaxBitrate)?Number.parseFloat(p.get(ge.WebRTCMaxBitrate)):r.WebRTCSettings.MaxBitrate/1e3),this.config.setNumericSetting(ge.WebRTCFPS,a&&p.has(ge.WebRTCFPS)?Number.parseFloat(p.get(ge.WebRTCFPS)):r.WebRTCSettings.FPS))}_onQualityControlOwnership(r){this.config.setFlagEnabled(X.IsQualityController,r)}_onPlayerCount(r){this._eventEmitter.dispatchEvent(new Jf({count:r}))}_setupWebRtcTCPRelayDetection(r){let s=r.data.aggregatedStats.getActiveCandidatePair();if(s!=null){let a=r.data.aggregatedStats.localCandidates.find((p=>p.id==s.localCandidateId),null);a!=null&&a.candidateType=="relay"&&a.relayProtocol=="tcp"&&this._eventEmitter.dispatchEvent(new Zf),this._eventEmitter.removeEventListener("statsReceived",this._setupWebRtcTCPRelayDetection)}}requestLatencyTest(){return!!this._webRtcController.videoPlayer.isVideoReady()&&(this._webRtcController.sendLatencyTest(),!0)}requestDataChannelLatencyTest(r){return!!this._webRtcController.videoPlayer.isVideoReady()&&(this._dataChannelLatencyTestController||(this._dataChannelLatencyTestController=new kw(this._webRtcController.sendDataChannelLatencyTest.bind(this._webRtcController),(s=>{this._eventEmitter.dispatchEvent(new Qf({result:s}))})),this.addEventListener("dataChannelLatencyTestResponse",(({data:{response:s}})=>{this._dataChannelLatencyTestController.receive(s)}))),this._dataChannelLatencyTestController.start(r))}requestShowFps(){return!!this._webRtcController.videoPlayer.isVideoReady()&&(this._webRtcController.sendShowFps(),!0)}requestIframe(){return!!this._webRtcController.videoPlayer.isVideoReady()&&(this._webRtcController.sendIframeRequest(),!0)}emitUIInteraction(r){return!!this._webRtcController.videoPlayer.isVideoReady()&&(this._webRtcController.emitUIInteraction(r),!0)}emitCommand(r){return!(!this._webRtcController.videoPlayer.isVideoReady()||!this.allowConsoleCommands&&"ConsoleCommand"in r||(this._webRtcController.emitCommand(r),0))}emitConsoleCommand(r){return!(!this.allowConsoleCommands||!this._webRtcController.videoPlayer.isVideoReady()||(this._webRtcController.emitConsoleCommand(r),0))}addResponseEventListener(r,s){this._webRtcController.responseController.addResponseEventListener(r,s)}removeResponseEventListener(r){this._webRtcController.responseController.removeResponseEventListener(r)}dispatchEvent(r){return this._eventEmitter.dispatchEvent(r)}addEventListener(r,s){this._eventEmitter.addEventListener(r,s)}removeEventListener(r,s){this._eventEmitter.removeEventListener(r,s)}toggleXR(){this.webXrController.xrClicked()}setSignallingUrlBuilder(r){this._webRtcController.signallingUrlBuilder=r}get webSocketController(){return this._webRtcController.webSocketController}get webXrController(){return this._webXrController}registerMessageHandler(r,s,a){s!==Se.FromStreamer||a!==void 0?s===Se.ToStreamer&&a===void 0?this._webRtcController.streamMessageController.registerMessageHandler(s,r,(p=>this._webRtcController.sendMessageController.sendMessageToStreamer(r,p))):this._webRtcController.streamMessageController.registerMessageHandler(s,r,(p=>a(p))):T.Warning(T.GetStackTrace(),`Unable to register an undefined handler for ${r}`)}get toStreamerHandlers(){return this._webRtcController.streamMessageController.toStreamerHandlers}isReconnecting(){return this._webRtcController.isReconnecting}}class Aw{}ve.Dz;ve.g$;ve.Lt;ve.Q9;ve.qf;ve.hV;ve.z$;ve.J0;var Iw=ve.De;ve.$C;ve.al;ve._W;ve.Gv;ve.m;ve.tz;ve.Nu;ve.zg;ve.vp;ve.vU;ve.wF;ve.rv;ve.Nh;ve.ss;ve.qW;ve.QL;ve.cf;ve.eM;ve.Yd;ve.Tk;ve.iM;ve.qy;ve.ce;ve.sK;ve.Ok;ve.q5;var Mw=ve.g;ve.xl;ve.I;ve.bx;ve.dD;ve.Ib;ve.Az;ve.Iw;ve.qY;ve.db;ve.mR;ve.Tn;ve.rV;ve.gh;ve.Mi;ve.j;ve.YB;ve.Yt;ve.i5;ve.x_;ve.Am;ve.eR;ve.r8;ve.u3;ve.vd;ve.iV;ve.jZ;ve.SW;ve.ZH;ve.Ni;ve.lh;ve.ZP;ve.bq;ve.$f;ve.eu;ve.Ax;ve.Mc;const fm=({signallingUrl:d,autoConnect:r=!0,width:s,height:a,onConnecting:p,onLoading:_,onConnected:C,onDisconnected:R,onError:S,muted:N=!1})=>{const z=ae.useRef(null),te=ae.useRef(null),j=ae.useRef(!1),[se,J]=ae.useState(!1),[Y,W]=ae.useState(!1),[ne,fe]=ae.useState(null);return ae.useEffect(()=>{if(!(!z.current||!d)){p&&p(),process.env.NODE_ENV==="development"&&console.log("Initializing Epic Pixel Streaming with URL:",d),"mediaDevices"in navigator||Object.defineProperty(navigator,"mediaDevices",{value:{}}),navigator.mediaDevices.getUserMedia||(navigator.mediaDevices.getUserMedia=function(){return Promise.reject(new Error("getUserMedia is not supported"))});try{const de=new Iw({useUrlParams:!1,initialSettings:{ss:d,AutoConnect:r,AutoPlayVideo:!0,StartVideoMuted:N,UseMic:!1,HoveringMouse:!1,FakeMouseWithTouches:!0,TouchInput:!1,MouseInput:!1,KeyboardInput:!1,WaitForStreamer:!0}}),he=new Mw(de,{videoElementParent:z.current});he.addEventListener("webRtcConnected",()=>{j.current=!0,J(!0),W(!1),fe(null),C?.()}),he.addEventListener("webRtcDisconnected",()=>{j.current=!1,J(!1),R?.()}),he.addEventListener("streamLoading",()=>{W(!0),_?.()}),he.addEventListener("playStreamError",()=>{fe("Failed to play stream"),W(!1),S?.("Failed to play stream")}),he.addEventListener("playStream",()=>{W(!1),j.current||(j.current=!0,J(!0),C?.())}),he.addEventListener("videoInitialized",()=>{W(!1)}),te.current=he}catch(de){process.env.NODE_ENV==="development"&&console.error("Failed to initialize Pixel Streaming:",de),fe("Failed to initialize streaming: "+de.message),W(!1),S?.(de.message)}return()=>{if(te.current){try{const de=te.current;de._webSocketController&&de._webSocketController.close(),te.current.disconnect()}catch(de){process.env.NODE_ENV==="development"&&console.error("Error during cleanup:",de)}te.current=null}}}},[d,r,p,_,C,R,S]),ae.useEffect(()=>{if(te.current)try{const he=te.current._webRtcController?.videoPlayer;if(!he)return;let pe=!1;if(he.audioElement){const Ve=he.audioElement.srcObject;if(Ve){const me=Ve.getAudioTracks();me.length>0&&(me.forEach(Ye=>{Ye.enabled=!N}),pe=!0)}}const ce=he.getVideoElement();if(ce&&ce.srcObject&&ce.srcObject instanceof MediaStream){const me=ce.srcObject.getAudioTracks();me.length>0&&(me.forEach(Ye=>{Ye.enabled=!N}),pe=!0)}!pe&&ce&&(ce.muted=N)}catch(de){process.env.NODE_ENV==="development"&&console.error("Error controlling audio:",de)}},[N]),Jt.jsxs("div",{className:"pixel-streaming-container",style:{width:s||"100%",height:a||"100%",position:"relative",display:"flex",flexDirection:"column",touchAction:"none",WebkitTouchCallout:"none",WebkitUserSelect:"none",userSelect:"none"},children:[Jt.jsx("div",{ref:z,className:"player-container",style:{position:"absolute",top:0,left:0,width:"100%",height:"100%",overflow:"hidden",touchAction:"none"}}),Y&&Jt.jsxs("div",{className:"loading-overlay",children:[Jt.jsx("div",{className:"loading-spinner"}),Jt.jsx("div",{className:"loading-text",children:"Connecting to stream..."})]}),!se&&!Y&&ne&&Jt.jsx("div",{className:"connection-overlay",children:Jt.jsx("div",{className:"error-message",children:ne})})]})};function mm({className:d,style:r,autoConnect:s=!0,muted:a=!1,onConnected:p,onDisconnected:_,onError:C}){const{streamingUrl:R,setCloudStreamState:S}=uf();if(!R)return null;const N=()=>{S(Zt.CONNECTING)},z=()=>{S(Zt.LOADING)},te=()=>{S(Zt.CONNECTED),p?.()},j=()=>{S(Zt.DISCONNECTED),_?.()},se=J=>{S(Zt.ERROR,J),C?.(J)};return Jt.jsx("div",{className:d,style:r,children:Jt.jsx(fm,{signallingUrl:R,autoConnect:s,muted:a,onConnecting:N,onLoading:z,onConnected:te,onDisconnected:j,onError:se})})}const Ow=Object.freeze(Object.defineProperty({__proto__:null,RqmiiCloudAvatarPlayer:mm},Symbol.toStringTag,{value:"Module"}));exports.AGENT_TYPES=hi;exports.CLOUD_STREAM_STATE=Zt;exports.CONNECTION_STATE=pt;exports.DEFAULT_PCM_OPTIONS=qp;exports.EpicPixelStreamingPlayer=fm;exports.EventEmitter=nf;exports.RqmiiAgentProvider=of;exports.RqmiiAgentRoom=zy;exports.RqmiiCloudAvatarPlayer=mm;exports.RqmiiCloudAvatarPlayer$1=Ow;exports.SESSION_STATE=Ns;exports.SOCKET_EVENTS=br;exports.suppressNoisyLogs=Gp;exports.useRqmiiAgentContext=Fs;exports.useRqmiiAvatar=uf;exports.useRqmiiConnection=lf;exports.useRqmiiEvents=Py;exports.useRqmiiMessages=yy;exports.useRqmiiVAD=Oy;exports.useRqmiiVoice=wy;
2918
- //# sourceMappingURL=RqmiiCloudAvatarPlayer-DnDpxEag.cjs.map
2918
+ //# sourceMappingURL=RqmiiCloudAvatarPlayer-C2bz7pkW.cjs.map