@rqmii_immersive/agent-react-sdk 5.6.5 → 5.6.6
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.
- package/dist/Orb-B1DErA0O.cjs +4517 -0
- package/dist/Orb-B1DErA0O.cjs.map +1 -0
- package/dist/RqmiiAgentChat-C0ymqkkq.cjs +2 -0
- package/dist/RqmiiAgentChat-C0ymqkkq.cjs.map +1 -0
- package/dist/RqmiiCloudAvatarPlayer-CmovoCKk.cjs +2918 -0
- package/dist/RqmiiCloudAvatarPlayer-CmovoCKk.cjs.map +1 -0
- package/dist/RqmiiErrorBoundary-Byif85f5.cjs +2 -0
- package/dist/RqmiiErrorBoundary-Byif85f5.cjs.map +1 -0
- package/dist/embed/chunks/Orb-CBt2svdc.js +40903 -0
- package/dist/embed/chunks/Orb-CBt2svdc.js.map +1 -0
- package/dist/embed/chunks/RqmiiCloudAvatarPlayer-DpvI9bmI.js +3357 -0
- package/dist/embed/chunks/RqmiiCloudAvatarPlayer-DpvI9bmI.js.map +1 -0
- package/dist/embed/chunks/chat-box-avatar-DlUI3fDi.js +10 -0
- package/dist/embed/chunks/chat-box-avatar-DlUI3fDi.js.map +1 -0
- package/dist/embed/chunks/chat-box-text-and-voice-BgdFP0_P.js +112 -0
- package/dist/embed/chunks/chat-box-text-and-voice-BgdFP0_P.js.map +1 -0
- package/dist/embed/chunks/chat-box-voice-D0gPyOVt.js +74 -0
- package/dist/embed/chunks/chat-box-voice-D0gPyOVt.js.map +1 -0
- package/dist/embed/chunks/embed-core-B3d4u3wf.js +12623 -0
- package/dist/embed/chunks/embed-core-B3d4u3wf.js.map +1 -0
- package/dist/embed/chunks/highlighted-body-KPVGNVTW-CJl4AHHd.js +19 -0
- package/dist/embed/chunks/highlighted-body-KPVGNVTW-CJl4AHHd.js.map +1 -0
- package/dist/embed/chunks/mermaid-HWGCJPDP-DD9SRoUR.js +22773 -0
- package/dist/embed/chunks/mermaid-HWGCJPDP-DD9SRoUR.js.map +1 -0
- package/dist/embed/chunks/use-rqmii-vad-COqAsQsT.js +10225 -0
- package/dist/embed/chunks/use-rqmii-vad-COqAsQsT.js.map +1 -0
- package/dist/embed/core.js +6 -0
- package/dist/embed/core.js.map +1 -0
- package/dist/embed.js +2 -0
- package/dist/embed.js.map +1 -0
- package/dist/highlighted-body-KPVGNVTW-CSL27xRm.cjs +2 -0
- package/dist/highlighted-body-KPVGNVTW-CSL27xRm.cjs.map +1 -0
- package/dist/index.cjs +50 -0
- package/dist/index.cjs.map +1 -0
- package/dist/lazy.cjs +2 -0
- package/dist/lazy.cjs.map +1 -0
- package/dist/mermaid-HWGCJPDP-CssnmrD3.cjs +2 -0
- package/dist/mermaid-HWGCJPDP-CssnmrD3.cjs.map +1 -0
- package/dist/schedule-load-DbAlv7OH.cjs +2 -0
- package/dist/schedule-load-DbAlv7OH.cjs.map +1 -0
- package/dist/ui-1UzY5QCI.cjs +251 -0
- package/dist/ui-1UzY5QCI.cjs.map +1 -0
- package/dist/ui.cjs +2 -0
- package/dist/ui.cjs.map +1 -0
- package/package.json +1 -1
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
"use strict";const U=require("react/jsx-runtime"),u=require("react");function ct(){if(typeof window>"u")return;const s=window;s.__rqmii_orig_console||(s.__rqmii_orig_console={error:console.error,warn:console.warn,log:console.log,debug:console.debug});const e=s.__rqmii_orig_console,t=i=>{if(i.length===0)return!1;const o=String(i[0]);return o.includes("reading 'S'")||o.includes("reading 'state'")||o.includes("MicVAD has null stream")||o.includes("VAD |")||o.includes("audioCtx.state")||o.includes("using default audio context")};console.error=(...i)=>{t(i)||e.error.apply(console,i)},console.warn=(...i)=>{t(i)||e.warn.apply(console,i)},console.log=(...i)=>{t(i)||e.log.apply(console,i)},console.debug=(...i)=>{t(i)||e.debug.apply(console,i)};const n=s.onerror;s.onerror=function(i,o,l,f,E){const d=String(i);return d.includes("reading 'state'")||d.includes("reading 'S'")||d.includes("MicVAD has null stream")?!0:n?n(i,o,l,f,E):!1};const r=s.onunhandledrejection;s.onunhandledrejection=function(i){const o=String(i.reason&&i.reason.message?i.reason.message:i.reason);return o.includes("reading 'state'")||o.includes("reading 'S'")||o.includes("MicVAD has null stream")?(i.preventDefault(),!0):r?r.call(s,i):!1}}const _e={TEXT:"text",VOICE:"voice",TEXT_AND_VOICE:"text_and_voice",CLOUD_AVATAR:"cloud_avatar",DESKTOP_AVATAR:"desktop_avatar"},k={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",PING:"ping",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",LEAD_FORM_SUBMITTED:"lead_form_submitted"},S={IDLE:"idle",INITIALIZING:"initializing",CONNECTING:"connecting",CONNECTED:"connected",FAILED:"failed",ENDED:"ended"},Z={IDLE:"idle",CONNECTING:"connecting",LOADING:"loading",CONNECTED:"connected",DISCONNECTED:"disconnected",ERROR:"error"},j={IDLE:"idle",USER_SPEAKING:"user_speaking",AGENT_THINKING:"agent_thinking",AGENT_SPEAKING:"agent_speaking",TOOL_EXECUTING:"tool_executing",TERMINATING:"terminating",TERMINATED:"terminated"},ut={encoding:"16bitInt",channels:1,sampleRate:16e3},ge={connectionState:S.IDLE,isConnected:!1,isSessionReady:!1,error:null,isAudioPlaying:!1,isAvatarSpeaking:!1,sessionState:j.IDLE,cloudStream:{state:Z.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 st(s,e){switch(e.type){case"SET_CONNECTION_STATE":return{...s,connectionState:e.payload,isConnected:e.payload===S.CONNECTED};case"SET_ERROR":return{...s,error:e.payload};case"SET_CLOUD_STREAM_STATE":return{...s,cloudStream:e.payload};case"SET_SESSION_STATE":return{...s,sessionState:e.payload};case"UPDATE_SESSION":return{...s,session:{...s.session,...e.payload}};case"ADD_MESSAGE":return{...s,messages:[...s.messages,e.payload]};case"SET_AUDIO_PLAYING":return{...s,isAudioPlaying:e.payload};case"SET_AVATAR_SPEAKING":return{...s,isAvatarSpeaking:e.payload};case"SET_CREDIT_EXHAUSTED":return{...s,creditExhausted:e.payload.exhausted,creditError:e.payload.error};case"SET_TRANSCRIPT":return{...s,transcript:e.payload};case"SET_PARTIAL_TRANSCRIPT":return{...s,partialTranscript:e.payload};case"SET_MESSAGES":return{...s,messages:e.payload};case"SET_SESSION_READY":return{...s,isSessionReady:e.payload};case"SET_AGENT_CONFIG":return{...s,agentConfig:e.payload};case"HARD_RESET":return ge;case"REPLACE_STATE":return e.payload;default:return s}}function vt(s){return{isSessionTerminated:s===j.TERMINATED,isSessionTerminating:s===j.TERMINATING,isAgentThinking:s===j.AGENT_THINKING,isAgentSpeaking:s===j.AGENT_SPEAKING,isToolExecuting:s===j.TOOL_EXECUTING}}function Dt(){const s=new Map;return{addChunk(e,t){const n=e||`request-${Date.now()}`,i=`${s.get(n)||""}${t||""}`;return s.set(n,i),{id:n,text:i}},consume(e,t=""){const n=e||`request-${Date.now()}`,r=s.get(n)||t||"";return s.delete(n),{id:n,text:r}},clear(){s.clear()}}}function xt(){try{const s=Intl.DateTimeFormat().resolvedOptions().timeZone;return typeof s=="string"&&s.trim()?s.trim():void 0}catch{return}}async function W(s){if(!s?.ok){const t=(await s.json().catch(()=>null))?.error,n=t?.message||`HTTP ${s.status}`,r=new Error(n);throw r.status=s.status,t?.code&&(r.code=t.code),t?.category&&(r.category=t.category),r}return s.json()}function Lt({restUrl:s,log:e,withCredentials:t}){function n(){if(!s)throw new Error("Missing restUrl in RqmiiAgentProvider")}async function r({apiKey:E,agentId:d,userId:y,language:T="en",timezone:R,config:a,promptOverrides:_}={}){n();const c=_?{...a??{},prompt_overrides:_}:a,p={...E?{api_key:E}:{},...d?{agent_id:d}:{},...y?{user_id:y}:{},language:T,...R?{timezone:R}:{},...c?{config:c}:{}};e("initializeSession — POST /sessions/init",p);const A=await fetch(`${s}/sessions/init`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(p),...t?{credentials:"include"}:{}}),b=await W(A);if(!b?.session_id||!b?.session_token)throw new Error("Invalid initialize session response");return b}async function i({uniqueId:E}){n(),e("joinDesktopSession — POST /sessions/join",{uniqueId:E});const d=await fetch(`${s}/sessions/join`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({unique_id:E}),...t?{credentials:"include"}:{}}),y=await W(d);if(!y?.session_id||!y?.session_token)throw new Error("Invalid join session response");return y}async function o(E){if(!s)throw new Error("SessionManager: restUrl missing");e("fetchAgentConfig — GET /agents/{agentId}",{agentId:E});const d=await fetch(`${s}/agents/${encodeURIComponent(E)}/customization`,{method:"GET",headers:{"Content-Type":"application/json"},...t?{credentials:"include"}:{}});return W(d)}async function l({sessionId:E,rating:d,feedback:y,endedBy:T}){if(n(),!E)throw new Error("sessionId is required");const R={...typeof d=="number"?{rating:d}:{},...y?{feedback:y}:{},...T?{ended_by:T}:{}};e("submitFeedback — PATCH /conversations/{sessionId}/feedback",{sessionId:E,payload:R});const a=await fetch(`${s}/conversations/${encodeURIComponent(E)}/feedback`,{method:"PATCH",headers:{"Content-Type":"application/json"},body:JSON.stringify(R),...t?{credentials:"include"}:{}});return W(a)}async function f({agentId:E,sessionId:d,collectedData:y}){if(n(),!E)throw new Error("agentId is required");if(!d)throw new Error("sessionId is required");e("submitLead — POST /public/agents/{agentId}/lead-capture/leads",{agentId:E,sessionId:d});const T=await fetch(`${s}/public/agents/${encodeURIComponent(E)}/lead-capture/leads`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({session_id:d,collected_data:y}),...t?{credentials:"include"}:{}});return W(T)}return{initializeSession:r,joinDesktopSession:i,fetchAgentConfig:o,submitFeedback:l,submitLead:f}}const P=Object.create(null);P.open="0";P.close="1";P.ping="2";P.pong="3";P.message="4";P.upgrade="5";P.noop="6";const oe=Object.create(null);Object.keys(P).forEach(s=>{oe[P[s]]=s});const me={type:"error",data:"parser error"},lt=typeof Blob=="function"||typeof Blob<"u"&&Object.prototype.toString.call(Blob)==="[object BlobConstructor]",ht=typeof ArrayBuffer=="function",ft=s=>typeof ArrayBuffer.isView=="function"?ArrayBuffer.isView(s):s&&s.buffer instanceof ArrayBuffer,Ce=({type:s,data:e},t,n)=>lt&&e instanceof Blob?t?n(e):nt(e,n):ht&&(e instanceof ArrayBuffer||ft(e))?t?n(e):nt(new Blob([e]),n):n(P[s]+(e||"")),nt=(s,e)=>{const t=new FileReader;return t.onload=function(){const n=t.result.split(",")[1];e("b"+(n||""))},t.readAsDataURL(s)};function rt(s){return s instanceof Uint8Array?s:s instanceof ArrayBuffer?new Uint8Array(s):new Uint8Array(s.buffer,s.byteOffset,s.byteLength)}let de;function Pt(s,e){if(lt&&s.data instanceof Blob)return s.data.arrayBuffer().then(rt).then(e);if(ht&&(s.data instanceof ArrayBuffer||ft(s.data)))return e(rt(s.data));Ce(s,!1,t=>{de||(de=new TextEncoder),e(de.encode(t))})}const it="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",Q=typeof Uint8Array>"u"?[]:new Uint8Array(256);for(let s=0;s<it.length;s++)Q[it.charCodeAt(s)]=s;const Bt=s=>{let e=s.length*.75,t=s.length,n,r=0,i,o,l,f;s[s.length-1]==="="&&(e--,s[s.length-2]==="="&&e--);const E=new ArrayBuffer(e),d=new Uint8Array(E);for(n=0;n<t;n+=4)i=Q[s.charCodeAt(n)],o=Q[s.charCodeAt(n+1)],l=Q[s.charCodeAt(n+2)],f=Q[s.charCodeAt(n+3)],d[r++]=i<<2|o>>4,d[r++]=(o&15)<<4|l>>2,d[r++]=(l&3)<<6|f&63;return E},Ut=typeof ArrayBuffer=="function",be=(s,e)=>{if(typeof s!="string")return{type:"message",data:dt(s,e)};const t=s.charAt(0);return t==="b"?{type:"message",data:qt(s.substring(1),e)}:oe[t]?s.length>1?{type:oe[t],data:s.substring(1)}:{type:oe[t]}:me},qt=(s,e)=>{if(Ut){const t=Bt(s);return dt(t,e)}else return{base64:!0,data:s}},dt=(s,e)=>{switch(e){case"blob":return s instanceof Blob?s:new Blob([s]);case"arraybuffer":default:return s instanceof ArrayBuffer?s:s.buffer}},pt="",Mt=(s,e)=>{const t=s.length,n=new Array(t);let r=0;s.forEach((i,o)=>{Ce(i,!1,l=>{n[o]=l,++r===t&&e(n.join(pt))})})},Ft=(s,e)=>{const t=s.split(pt),n=[];for(let r=0;r<t.length;r++){const i=be(t[r],e);if(n.push(i),i.type==="error")break}return n};function Gt(){return new TransformStream({transform(s,e){Pt(s,t=>{const n=t.length;let r;if(n<126)r=new Uint8Array(1),new DataView(r.buffer).setUint8(0,n);else if(n<65536){r=new Uint8Array(3);const i=new DataView(r.buffer);i.setUint8(0,126),i.setUint16(1,n)}else{r=new Uint8Array(9);const i=new DataView(r.buffer);i.setUint8(0,127),i.setBigUint64(1,BigInt(n))}s.data&&typeof s.data!="string"&&(r[0]|=128),e.enqueue(r),e.enqueue(t)})}})}let pe;function re(s){return s.reduce((e,t)=>e+t.length,0)}function ie(s,e){if(s[0].length===e)return s.shift();const t=new Uint8Array(e);let n=0;for(let r=0;r<e;r++)t[r]=s[0][n++],n===s[0].length&&(s.shift(),n=0);return s.length&&n<s[0].length&&(s[0]=s[0].slice(n)),t}function Vt(s,e){pe||(pe=new TextDecoder);const t=[];let n=0,r=-1,i=!1;return new TransformStream({transform(o,l){for(t.push(o);;){if(n===0){if(re(t)<1)break;const f=ie(t,1);i=(f[0]&128)===128,r=f[0]&127,r<126?n=3:r===126?n=1:n=2}else if(n===1){if(re(t)<2)break;const f=ie(t,2);r=new DataView(f.buffer,f.byteOffset,f.length).getUint16(0),n=3}else if(n===2){if(re(t)<8)break;const f=ie(t,8),E=new DataView(f.buffer,f.byteOffset,f.length),d=E.getUint32(0);if(d>Math.pow(2,21)-1){l.enqueue(me);break}r=d*Math.pow(2,32)+E.getUint32(4),n=3}else{if(re(t)<r)break;const f=ie(t,r);l.enqueue(be(i?f:pe.decode(f),e)),n=0}if(r===0||r>s){l.enqueue(me);break}}}})}const yt=4;function C(s){if(s)return Ht(s)}function Ht(s){for(var e in C.prototype)s[e]=C.prototype[e];return s}C.prototype.on=C.prototype.addEventListener=function(s,e){return this._callbacks=this._callbacks||{},(this._callbacks["$"+s]=this._callbacks["$"+s]||[]).push(e),this};C.prototype.once=function(s,e){function t(){this.off(s,t),e.apply(this,arguments)}return t.fn=e,this.on(s,t),this};C.prototype.off=C.prototype.removeListener=C.prototype.removeAllListeners=C.prototype.removeEventListener=function(s,e){if(this._callbacks=this._callbacks||{},arguments.length==0)return this._callbacks={},this;var t=this._callbacks["$"+s];if(!t)return this;if(arguments.length==1)return delete this._callbacks["$"+s],this;for(var n,r=0;r<t.length;r++)if(n=t[r],n===e||n.fn===e){t.splice(r,1);break}return t.length===0&&delete this._callbacks["$"+s],this};C.prototype.emit=function(s){this._callbacks=this._callbacks||{};for(var e=new Array(arguments.length-1),t=this._callbacks["$"+s],n=1;n<arguments.length;n++)e[n-1]=arguments[n];if(t){t=t.slice(0);for(var n=0,r=t.length;n<r;++n)t[n].apply(this,e)}return this};C.prototype.emitReserved=C.prototype.emit;C.prototype.listeners=function(s){return this._callbacks=this._callbacks||{},this._callbacks["$"+s]||[]};C.prototype.hasListeners=function(s){return!!this.listeners(s).length};const le=typeof Promise=="function"&&typeof Promise.resolve=="function"?e=>Promise.resolve().then(e):(e,t)=>t(e,0),D=typeof self<"u"?self:typeof window<"u"?window:Function("return this")(),Kt="arraybuffer";function Et(s,...e){return e.reduce((t,n)=>(s.hasOwnProperty(n)&&(t[n]=s[n]),t),{})}const jt=D.setTimeout,Yt=D.clearTimeout;function he(s,e){e.useNativeTimers?(s.setTimeoutFn=jt.bind(D),s.clearTimeoutFn=Yt.bind(D)):(s.setTimeoutFn=D.setTimeout.bind(D),s.clearTimeoutFn=D.clearTimeout.bind(D))}const zt=1.33;function $t(s){return typeof s=="string"?Xt(s):Math.ceil((s.byteLength||s.size)*zt)}function Xt(s){let e=0,t=0;for(let n=0,r=s.length;n<r;n++)e=s.charCodeAt(n),e<128?t+=1:e<2048?t+=2:e<55296||e>=57344?t+=3:(n++,t+=4);return t}function _t(){return Date.now().toString(36).substring(3)+Math.random().toString(36).substring(2,5)}function Wt(s){let e="";for(let t in s)s.hasOwnProperty(t)&&(e.length&&(e+="&"),e+=encodeURIComponent(t)+"="+encodeURIComponent(s[t]));return e}function Jt(s){let e={},t=s.split("&");for(let n=0,r=t.length;n<r;n++){let i=t[n].split("=");e[decodeURIComponent(i[0])]=decodeURIComponent(i[1])}return e}class Qt extends Error{constructor(e,t,n){super(e),this.description=t,this.context=n,this.type="TransportError"}}class Oe extends C{constructor(e){super(),this.writable=!1,he(this,e),this.opts=e,this.query=e.query,this.socket=e.socket,this.supportsBinary=!e.forceBase64}onError(e,t,n){return super.emitReserved("error",new Qt(e,t,n)),this}open(){return this.readyState="opening",this.doOpen(),this}close(){return(this.readyState==="opening"||this.readyState==="open")&&(this.doClose(),this.onClose()),this}send(e){this.readyState==="open"&&this.write(e)}onOpen(){this.readyState="open",this.writable=!0,super.emitReserved("open")}onData(e){const t=be(e,this.socket.binaryType);this.onPacket(t)}onPacket(e){super.emitReserved("packet",e)}onClose(e){this.readyState="closed",super.emitReserved("close",e)}pause(e){}createUri(e,t={}){return e+"://"+this._hostname()+this._port()+this.opts.path+this._query(t)}_hostname(){const e=this.opts.hostname;return e.indexOf(":")===-1?e:"["+e+"]"}_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(e){const t=Wt(e);return t.length?"?"+t:""}}class Zt extends Oe{constructor(){super(...arguments),this._polling=!1}get name(){return"polling"}doOpen(){this._poll()}pause(e){this.readyState="pausing";const t=()=>{this.readyState="paused",e()};if(this._polling||!this.writable){let n=0;this._polling&&(n++,this.once("pollComplete",function(){--n||t()})),this.writable||(n++,this.once("drain",function(){--n||t()}))}else t()}_poll(){this._polling=!0,this.doPoll(),this.emitReserved("poll")}onData(e){const t=n=>{if(this.readyState==="opening"&&n.type==="open"&&this.onOpen(),n.type==="close")return this.onClose({description:"transport closed by the server"}),!1;this.onPacket(n)};Ft(e,this.socket.binaryType).forEach(t),this.readyState!=="closed"&&(this._polling=!1,this.emitReserved("pollComplete"),this.readyState==="open"&&this._poll())}doClose(){const e=()=>{this.write([{type:"close"}])};this.readyState==="open"?e():this.once("open",e)}write(e){this.writable=!1,Mt(e,t=>{this.doWrite(t,()=>{this.writable=!0,this.emitReserved("drain")})})}uri(){const e=this.opts.secure?"https":"http",t=this.query||{};return this.opts.timestampRequests!==!1&&(t[this.opts.timestampParam]=_t()),!this.supportsBinary&&!t.sid&&(t.b64=1),this.createUri(e,t)}}let gt=!1;try{gt=typeof XMLHttpRequest<"u"&&"withCredentials"in new XMLHttpRequest}catch{}const es=gt;function ts(){}class ss extends Zt{constructor(e){if(super(e),typeof location<"u"){const t=location.protocol==="https:";let n=location.port;n||(n=t?"443":"80"),this.xd=typeof location<"u"&&e.hostname!==location.hostname||n!==e.port}}doWrite(e,t){const n=this.request({method:"POST",data:e});n.on("success",t),n.on("error",(r,i)=>{this.onError("xhr post error",r,i)})}doPoll(){const e=this.request();e.on("data",this.onData.bind(this)),e.on("error",(t,n)=>{this.onError("xhr poll error",t,n)}),this.pollXhr=e}}class L extends C{constructor(e,t,n){super(),this.createRequest=e,he(this,n),this._opts=n,this._method=n.method||"GET",this._uri=t,this._data=n.data!==void 0?n.data:null,this._create()}_create(){var e;const t=Et(this._opts,"agent","pfx","key","passphrase","cert","ca","ciphers","rejectUnauthorized","autoUnref");t.xdomain=!!this._opts.xd;const n=this._xhr=this.createRequest(t);try{n.open(this._method,this._uri,!0);try{if(this._opts.extraHeaders){n.setDisableHeaderCheck&&n.setDisableHeaderCheck(!0);for(let r in this._opts.extraHeaders)this._opts.extraHeaders.hasOwnProperty(r)&&n.setRequestHeader(r,this._opts.extraHeaders[r])}}catch{}if(this._method==="POST")try{n.setRequestHeader("Content-type","text/plain;charset=UTF-8")}catch{}try{n.setRequestHeader("Accept","*/*")}catch{}(e=this._opts.cookieJar)===null||e===void 0||e.addCookies(n),"withCredentials"in n&&(n.withCredentials=this._opts.withCredentials),this._opts.requestTimeout&&(n.timeout=this._opts.requestTimeout),n.onreadystatechange=()=>{var r;n.readyState===3&&((r=this._opts.cookieJar)===null||r===void 0||r.parseCookies(n.getResponseHeader("set-cookie"))),n.readyState===4&&(n.status===200||n.status===1223?this._onLoad():this.setTimeoutFn(()=>{this._onError(typeof n.status=="number"?n.status:0)},0))},n.send(this._data)}catch(r){this.setTimeoutFn(()=>{this._onError(r)},0);return}typeof document<"u"&&(this._index=L.requestsCount++,L.requests[this._index]=this)}_onError(e){this.emitReserved("error",e,this._xhr),this._cleanup(!0)}_cleanup(e){if(!(typeof this._xhr>"u"||this._xhr===null)){if(this._xhr.onreadystatechange=ts,e)try{this._xhr.abort()}catch{}typeof document<"u"&&delete L.requests[this._index],this._xhr=null}}_onLoad(){const e=this._xhr.responseText;e!==null&&(this.emitReserved("data",e),this.emitReserved("success"),this._cleanup())}abort(){this._cleanup()}}L.requestsCount=0;L.requests={};if(typeof document<"u"){if(typeof attachEvent=="function")attachEvent("onunload",ot);else if(typeof addEventListener=="function"){const s="onpagehide"in D?"pagehide":"unload";addEventListener(s,ot,!1)}}function ot(){for(let s in L.requests)L.requests.hasOwnProperty(s)&&L.requests[s].abort()}const ns=(function(){const s=mt({xdomain:!1});return s&&s.responseType!==null})();class rs extends ss{constructor(e){super(e);const t=e&&e.forceBase64;this.supportsBinary=ns&&!t}request(e={}){return Object.assign(e,{xd:this.xd},this.opts),new L(mt,this.uri(),e)}}function mt(s){const e=s.xdomain;try{if(typeof XMLHttpRequest<"u"&&(!e||es))return new XMLHttpRequest}catch{}if(!e)try{return new D[["Active"].concat("Object").join("X")]("Microsoft.XMLHTTP")}catch{}}const Tt=typeof navigator<"u"&&typeof navigator.product=="string"&&navigator.product.toLowerCase()==="reactnative";class is extends Oe{get name(){return"websocket"}doOpen(){const e=this.uri(),t=this.opts.protocols,n=Tt?{}:Et(this.opts,"agent","perMessageDeflate","pfx","key","passphrase","cert","ca","ciphers","rejectUnauthorized","localAddress","protocolVersion","origin","maxPayload","family","checkServerIdentity");this.opts.extraHeaders&&(n.headers=this.opts.extraHeaders);try{this.ws=this.createSocket(e,t,n)}catch(r){return this.emitReserved("error",r)}this.ws.binaryType=this.socket.binaryType,this.addEventListeners()}addEventListeners(){this.ws.onopen=()=>{this.opts.autoUnref&&this.ws._socket.unref(),this.onOpen()},this.ws.onclose=e=>this.onClose({description:"websocket connection closed",context:e}),this.ws.onmessage=e=>this.onData(e.data),this.ws.onerror=e=>this.onError("websocket error",e)}write(e){this.writable=!1;for(let t=0;t<e.length;t++){const n=e[t],r=t===e.length-1;Ce(n,this.supportsBinary,i=>{try{this.doWrite(n,i)}catch{}r&&le(()=>{this.writable=!0,this.emitReserved("drain")},this.setTimeoutFn)})}}doClose(){typeof this.ws<"u"&&(this.ws.onerror=()=>{},this.ws.close(),this.ws=null)}uri(){const e=this.opts.secure?"wss":"ws",t=this.query||{};return this.opts.timestampRequests&&(t[this.opts.timestampParam]=_t()),this.supportsBinary||(t.b64=1),this.createUri(e,t)}}const ye=D.WebSocket||D.MozWebSocket;class os extends is{createSocket(e,t,n){return Tt?new ye(e,t,n):t?new ye(e,t):new ye(e)}doWrite(e,t){this.ws.send(t)}}class as extends Oe{get name(){return"webtransport"}doOpen(){try{this._transport=new WebTransport(this.createUri("https"),this.opts.transportOptions[this.name])}catch(e){return this.emitReserved("error",e)}this._transport.closed.then(()=>{this.onClose()}).catch(e=>{this.onError("webtransport error",e)}),this._transport.ready.then(()=>{this._transport.createBidirectionalStream().then(e=>{const t=Vt(Number.MAX_SAFE_INTEGER,this.socket.binaryType),n=e.readable.pipeThrough(t).getReader(),r=Gt();r.readable.pipeTo(e.writable),this._writer=r.writable.getWriter();const i=()=>{n.read().then(({done:l,value:f})=>{l||(this.onPacket(f),i())}).catch(l=>{})};i();const o={type:"open"};this.query.sid&&(o.data=`{"sid":"${this.query.sid}"}`),this._writer.write(o).then(()=>this.onOpen())})})}write(e){this.writable=!1;for(let t=0;t<e.length;t++){const n=e[t],r=t===e.length-1;this._writer.write(n).then(()=>{r&&le(()=>{this.writable=!0,this.emitReserved("drain")},this.setTimeoutFn)})}}doClose(){var e;(e=this._transport)===null||e===void 0||e.close()}}const cs={websocket:os,webtransport:as,polling:rs},us=/^(?:(?![^:@\/?#]+:[^:@\/]*@)(http|https|ws|wss):\/\/)?((?:(([^:@\/?#]*)(?::([^:@\/?#]*))?)?@)?((?:[a-f0-9]{0,4}:){2,7}[a-f0-9]{0,4}|[^:\/?#]*)(?::(\d*))?)(((\/(?:[^?#](?![^?#\/]*\.[^?#\/.]+(?:[?#]|$)))*\/?)?([^?#\/]*))(?:\?([^#]*))?(?:#(.*))?)/,ls=["source","protocol","authority","userInfo","user","password","host","port","relative","path","directory","file","query","anchor"];function Te(s){if(s.length>8e3)throw"URI too long";const e=s,t=s.indexOf("["),n=s.indexOf("]");t!=-1&&n!=-1&&(s=s.substring(0,t)+s.substring(t,n).replace(/:/g,";")+s.substring(n,s.length));let r=us.exec(s||""),i={},o=14;for(;o--;)i[ls[o]]=r[o]||"";return t!=-1&&n!=-1&&(i.source=e,i.host=i.host.substring(1,i.host.length-1).replace(/;/g,":"),i.authority=i.authority.replace("[","").replace("]","").replace(/;/g,":"),i.ipv6uri=!0),i.pathNames=hs(i,i.path),i.queryKey=fs(i,i.query),i}function hs(s,e){const t=/\/{2,9}/g,n=e.replace(t,"/").split("/");return(e.slice(0,1)=="/"||e.length===0)&&n.splice(0,1),e.slice(-1)=="/"&&n.splice(n.length-1,1),n}function fs(s,e){const t={};return e.replace(/(?:^|&)([^&=]*)=?([^&]*)/g,function(n,r,i){r&&(t[r]=i)}),t}const Se=typeof addEventListener=="function"&&typeof removeEventListener=="function",ae=[];Se&&addEventListener("offline",()=>{ae.forEach(s=>s())},!1);class G extends C{constructor(e,t){if(super(),this.binaryType=Kt,this.writeBuffer=[],this._prevBufferLen=0,this._pingInterval=-1,this._pingTimeout=-1,this._maxPayload=-1,this._pingTimeoutTime=1/0,e&&typeof e=="object"&&(t=e,e=null),e){const n=Te(e);t.hostname=n.host,t.secure=n.protocol==="https"||n.protocol==="wss",t.port=n.port,n.query&&(t.query=n.query)}else t.host&&(t.hostname=Te(t.host).host);he(this,t),this.secure=t.secure!=null?t.secure:typeof location<"u"&&location.protocol==="https:",t.hostname&&!t.port&&(t.port=this.secure?"443":"80"),this.hostname=t.hostname||(typeof location<"u"?location.hostname:"localhost"),this.port=t.port||(typeof location<"u"&&location.port?location.port:this.secure?"443":"80"),this.transports=[],this._transportsByName={},t.transports.forEach(n=>{const r=n.prototype.name;this.transports.push(r),this._transportsByName[r]=n}),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},t),this.opts.path=this.opts.path.replace(/\/$/,"")+(this.opts.addTrailingSlash?"/":""),typeof this.opts.query=="string"&&(this.opts.query=Jt(this.opts.query)),Se&&(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"})},ae.push(this._offlineEventListener))),this.opts.withCredentials&&(this._cookieJar=void 0),this._open()}createTransport(e){const t=Object.assign({},this.opts.query);t.EIO=yt,t.transport=e,this.id&&(t.sid=this.id);const n=Object.assign({},this.opts,{query:t,socket:this,hostname:this.hostname,secure:this.secure,port:this.port},this.opts.transportOptions[e]);return new this._transportsByName[e](n)}_open(){if(this.transports.length===0){this.setTimeoutFn(()=>{this.emitReserved("error","No transports available")},0);return}const e=this.opts.rememberUpgrade&&G.priorWebsocketSuccess&&this.transports.indexOf("websocket")!==-1?"websocket":this.transports[0];this.readyState="opening";const t=this.createTransport(e);t.open(),this.setTransport(t)}setTransport(e){this.transport&&this.transport.removeAllListeners(),this.transport=e,e.on("drain",this._onDrain.bind(this)).on("packet",this._onPacket.bind(this)).on("error",this._onError.bind(this)).on("close",t=>this._onClose("transport close",t))}onOpen(){this.readyState="open",G.priorWebsocketSuccess=this.transport.name==="websocket",this.emitReserved("open"),this.flush()}_onPacket(e){if(this.readyState==="opening"||this.readyState==="open"||this.readyState==="closing")switch(this.emitReserved("packet",e),this.emitReserved("heartbeat"),e.type){case"open":this.onHandshake(JSON.parse(e.data));break;case"ping":this._sendPacket("pong"),this.emitReserved("ping"),this.emitReserved("pong"),this._resetPingTimeout();break;case"error":const t=new Error("server error");t.code=e.data,this._onError(t);break;case"message":this.emitReserved("data",e.data),this.emitReserved("message",e.data);break}}onHandshake(e){this.emitReserved("handshake",e),this.id=e.sid,this.transport.query.sid=e.sid,this._pingInterval=e.pingInterval,this._pingTimeout=e.pingTimeout,this._maxPayload=e.maxPayload,this.onOpen(),this.readyState!=="closed"&&this._resetPingTimeout()}_resetPingTimeout(){this.clearTimeoutFn(this._pingTimeoutTimer);const e=this._pingInterval+this._pingTimeout;this._pingTimeoutTime=Date.now()+e,this._pingTimeoutTimer=this.setTimeoutFn(()=>{this._onClose("ping timeout")},e),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 e=this._getWritablePackets();this.transport.send(e),this._prevBufferLen=e.length,this.emitReserved("flush")}}_getWritablePackets(){if(!(this._maxPayload&&this.transport.name==="polling"&&this.writeBuffer.length>1))return this.writeBuffer;let t=1;for(let n=0;n<this.writeBuffer.length;n++){const r=this.writeBuffer[n].data;if(r&&(t+=$t(r)),n>0&&t>this._maxPayload)return this.writeBuffer.slice(0,n);t+=2}return this.writeBuffer}_hasPingExpired(){if(!this._pingTimeoutTime)return!0;const e=Date.now()>this._pingTimeoutTime;return e&&(this._pingTimeoutTime=0,le(()=>{this._onClose("ping timeout")},this.setTimeoutFn)),e}write(e,t,n){return this._sendPacket("message",e,t,n),this}send(e,t,n){return this._sendPacket("message",e,t,n),this}_sendPacket(e,t,n,r){if(typeof t=="function"&&(r=t,t=void 0),typeof n=="function"&&(r=n,n=null),this.readyState==="closing"||this.readyState==="closed")return;n=n||{},n.compress=n.compress!==!1;const i={type:e,data:t,options:n};this.emitReserved("packetCreate",i),this.writeBuffer.push(i),r&&this.once("flush",r),this.flush()}close(){const e=()=>{this._onClose("forced close"),this.transport.close()},t=()=>{this.off("upgrade",t),this.off("upgradeError",t),e()},n=()=>{this.once("upgrade",t),this.once("upgradeError",t)};return(this.readyState==="opening"||this.readyState==="open")&&(this.readyState="closing",this.writeBuffer.length?this.once("drain",()=>{this.upgrading?n():e()}):this.upgrading?n():e()),this}_onError(e){if(G.priorWebsocketSuccess=!1,this.opts.tryAllTransports&&this.transports.length>1&&this.readyState==="opening")return this.transports.shift(),this._open();this.emitReserved("error",e),this._onClose("transport error",e)}_onClose(e,t){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(),Se&&(this._beforeunloadEventListener&&removeEventListener("beforeunload",this._beforeunloadEventListener,!1),this._offlineEventListener)){const n=ae.indexOf(this._offlineEventListener);n!==-1&&ae.splice(n,1)}this.readyState="closed",this.id=null,this.emitReserved("close",e,t),this.writeBuffer=[],this._prevBufferLen=0}}}G.protocol=yt;class ds extends G{constructor(){super(...arguments),this._upgrades=[]}onOpen(){if(super.onOpen(),this.readyState==="open"&&this.opts.upgrade)for(let e=0;e<this._upgrades.length;e++)this._probe(this._upgrades[e])}_probe(e){let t=this.createTransport(e),n=!1;G.priorWebsocketSuccess=!1;const r=()=>{n||(t.send([{type:"ping",data:"probe"}]),t.once("packet",y=>{if(!n)if(y.type==="pong"&&y.data==="probe"){if(this.upgrading=!0,this.emitReserved("upgrading",t),!t)return;G.priorWebsocketSuccess=t.name==="websocket",this.transport.pause(()=>{n||this.readyState!=="closed"&&(d(),this.setTransport(t),t.send([{type:"upgrade"}]),this.emitReserved("upgrade",t),t=null,this.upgrading=!1,this.flush())})}else{const T=new Error("probe error");T.transport=t.name,this.emitReserved("upgradeError",T)}}))};function i(){n||(n=!0,d(),t.close(),t=null)}const o=y=>{const T=new Error("probe error: "+y);T.transport=t.name,i(),this.emitReserved("upgradeError",T)};function l(){o("transport closed")}function f(){o("socket closed")}function E(y){t&&y.name!==t.name&&i()}const d=()=>{t.removeListener("open",r),t.removeListener("error",o),t.removeListener("close",l),this.off("close",f),this.off("upgrading",E)};t.once("open",r),t.once("error",o),t.once("close",l),this.once("close",f),this.once("upgrading",E),this._upgrades.indexOf("webtransport")!==-1&&e!=="webtransport"?this.setTimeoutFn(()=>{n||t.open()},200):t.open()}onHandshake(e){this._upgrades=this._filterUpgrades(e.upgrades),super.onHandshake(e)}_filterUpgrades(e){const t=[];for(let n=0;n<e.length;n++)~this.transports.indexOf(e[n])&&t.push(e[n]);return t}}let ps=class extends ds{constructor(e,t={}){const n=typeof e=="object"?e:t;(!n.transports||n.transports&&typeof n.transports[0]=="string")&&(n.transports=(n.transports||["polling","websocket","webtransport"]).map(r=>cs[r]).filter(r=>!!r)),super(e,n)}};function ys(s,e="",t){let n=s;t=t||typeof location<"u"&&location,s==null&&(s=t.protocol+"//"+t.host),typeof s=="string"&&(s.charAt(0)==="/"&&(s.charAt(1)==="/"?s=t.protocol+s:s=t.host+s),/^(https?|wss?):\/\//.test(s)||(typeof t<"u"?s=t.protocol+"//"+s:s="https://"+s),n=Te(s)),n.port||(/^(http|ws)$/.test(n.protocol)?n.port="80":/^(http|ws)s$/.test(n.protocol)&&(n.port="443")),n.path=n.path||"/";const i=n.host.indexOf(":")!==-1?"["+n.host+"]":n.host;return n.id=n.protocol+"://"+i+":"+n.port+e,n.href=n.protocol+"://"+i+(t&&t.port===n.port?"":":"+n.port),n}const Es=typeof ArrayBuffer=="function",_s=s=>typeof ArrayBuffer.isView=="function"?ArrayBuffer.isView(s):s.buffer instanceof ArrayBuffer,St=Object.prototype.toString,gs=typeof Blob=="function"||typeof Blob<"u"&&St.call(Blob)==="[object BlobConstructor]",ms=typeof File=="function"||typeof File<"u"&&St.call(File)==="[object FileConstructor]";function we(s){return Es&&(s instanceof ArrayBuffer||_s(s))||gs&&s instanceof Blob||ms&&s instanceof File}function ce(s,e){if(!s||typeof s!="object")return!1;if(Array.isArray(s)){for(let t=0,n=s.length;t<n;t++)if(ce(s[t]))return!0;return!1}if(we(s))return!0;if(s.toJSON&&typeof s.toJSON=="function"&&arguments.length===1)return ce(s.toJSON(),!0);for(const t in s)if(Object.prototype.hasOwnProperty.call(s,t)&&ce(s[t]))return!0;return!1}function Ts(s){const e=[],t=s.data,n=s;return n.data=Ae(t,e),n.attachments=e.length,{packet:n,buffers:e}}function Ae(s,e){if(!s)return s;if(we(s)){const t={_placeholder:!0,num:e.length};return e.push(s),t}else if(Array.isArray(s)){const t=new Array(s.length);for(let n=0;n<s.length;n++)t[n]=Ae(s[n],e);return t}else if(typeof s=="object"&&!(s instanceof Date)){const t={};for(const n in s)Object.prototype.hasOwnProperty.call(s,n)&&(t[n]=Ae(s[n],e));return t}return s}function Ss(s,e){return s.data=Re(s.data,e),delete s.attachments,s}function Re(s,e){if(!s)return s;if(s&&s._placeholder===!0){if(typeof s.num=="number"&&s.num>=0&&s.num<e.length)return e[s.num];throw new Error("illegal attachments")}else if(Array.isArray(s))for(let t=0;t<s.length;t++)s[t]=Re(s[t],e);else if(typeof s=="object")for(const t in s)Object.prototype.hasOwnProperty.call(s,t)&&(s[t]=Re(s[t],e));return s}const As=["connect","connect_error","disconnect","disconnecting","newListener","removeListener"];var g;(function(s){s[s.CONNECT=0]="CONNECT",s[s.DISCONNECT=1]="DISCONNECT",s[s.EVENT=2]="EVENT",s[s.ACK=3]="ACK",s[s.CONNECT_ERROR=4]="CONNECT_ERROR",s[s.BINARY_EVENT=5]="BINARY_EVENT",s[s.BINARY_ACK=6]="BINARY_ACK"})(g||(g={}));class Rs{constructor(e){this.replacer=e}encode(e){return(e.type===g.EVENT||e.type===g.ACK)&&ce(e)?this.encodeAsBinary({type:e.type===g.EVENT?g.BINARY_EVENT:g.BINARY_ACK,nsp:e.nsp,data:e.data,id:e.id}):[this.encodeAsString(e)]}encodeAsString(e){let t=""+e.type;return(e.type===g.BINARY_EVENT||e.type===g.BINARY_ACK)&&(t+=e.attachments+"-"),e.nsp&&e.nsp!=="/"&&(t+=e.nsp+","),e.id!=null&&(t+=e.id),e.data!=null&&(t+=JSON.stringify(e.data,this.replacer)),t}encodeAsBinary(e){const t=Ts(e),n=this.encodeAsString(t.packet),r=t.buffers;return r.unshift(n),r}}class Ie extends C{constructor(e){super(),this.opts=Object.assign({reviver:void 0,maxAttachments:10},typeof e=="function"?{reviver:e}:e)}add(e){let t;if(typeof e=="string"){if(this.reconstructor)throw new Error("got plaintext data when reconstructing a packet");t=this.decodeString(e);const n=t.type===g.BINARY_EVENT;n||t.type===g.BINARY_ACK?(t.type=n?g.EVENT:g.ACK,this.reconstructor=new Ns(t),t.attachments===0&&super.emitReserved("decoded",t)):super.emitReserved("decoded",t)}else if(we(e)||e.base64)if(this.reconstructor)t=this.reconstructor.takeBinaryData(e),t&&(this.reconstructor=null,super.emitReserved("decoded",t));else throw new Error("got binary data when not reconstructing a packet");else throw new Error("Unknown type: "+e)}decodeString(e){let t=0;const n={type:Number(e.charAt(0))};if(g[n.type]===void 0)throw new Error("unknown packet type "+n.type);if(n.type===g.BINARY_EVENT||n.type===g.BINARY_ACK){const i=t+1;for(;e.charAt(++t)!=="-"&&t!=e.length;);const o=e.substring(i,t);if(o!=Number(o)||e.charAt(t)!=="-")throw new Error("Illegal attachments");const l=Number(o);if(!Cs(l)||l<0)throw new Error("Illegal attachments");if(l>this.opts.maxAttachments)throw new Error("too many attachments");n.attachments=l}if(e.charAt(t+1)==="/"){const i=t+1;for(;++t&&!(e.charAt(t)===","||t===e.length););n.nsp=e.substring(i,t)}else n.nsp="/";const r=e.charAt(t+1);if(r!==""&&Number(r)==r){const i=t+1;for(;++t;){const o=e.charAt(t);if(o==null||Number(o)!=o){--t;break}if(t===e.length)break}n.id=Number(e.substring(i,t+1))}if(e.charAt(++t)){const i=this.tryParse(e.substr(t));if(Ie.isPayloadValid(n.type,i))n.data=i;else throw new Error("invalid payload")}return n}tryParse(e){try{return JSON.parse(e,this.opts.reviver)}catch{return!1}}static isPayloadValid(e,t){switch(e){case g.CONNECT:return at(t);case g.DISCONNECT:return t===void 0;case g.CONNECT_ERROR:return typeof t=="string"||at(t);case g.EVENT:case g.BINARY_EVENT:return Array.isArray(t)&&(typeof t[0]=="number"||typeof t[0]=="string"&&As.indexOf(t[0])===-1);case g.ACK:case g.BINARY_ACK:return Array.isArray(t)}}destroy(){this.reconstructor&&(this.reconstructor.finishedReconstruction(),this.reconstructor=null)}}class Ns{constructor(e){this.packet=e,this.buffers=[],this.reconPack=e}takeBinaryData(e){if(this.buffers.push(e),this.buffers.length===this.reconPack.attachments){const t=Ss(this.reconPack,this.buffers);return this.finishedReconstruction(),t}return null}finishedReconstruction(){this.reconPack=null,this.buffers=[]}}const Cs=Number.isInteger||function(s){return typeof s=="number"&&isFinite(s)&&Math.floor(s)===s};function at(s){return Object.prototype.toString.call(s)==="[object Object]"}const bs=Object.freeze(Object.defineProperty({__proto__:null,Decoder:Ie,Encoder:Rs,get PacketType(){return g}},Symbol.toStringTag,{value:"Module"}));function x(s,e,t){return s.on(e,t),function(){s.off(e,t)}}const Os=Object.freeze({connect:1,connect_error:1,disconnect:1,disconnecting:1,newListener:1,removeListener:1});class At extends C{constructor(e,t,n){super(),this.connected=!1,this.recovered=!1,this.receiveBuffer=[],this.sendBuffer=[],this._queue=[],this._queueSeq=0,this.ids=0,this.acks={},this.flags={},this.io=e,this.nsp=t,n&&n.auth&&(this.auth=n.auth),this._opts=Object.assign({},n),this.io._autoConnect&&this.open()}get disconnected(){return!this.connected}subEvents(){if(this.subs)return;const e=this.io;this.subs=[x(e,"open",this.onopen.bind(this)),x(e,"packet",this.onpacket.bind(this)),x(e,"error",this.onerror.bind(this)),x(e,"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(...e){return e.unshift("message"),this.emit.apply(this,e),this}emit(e,...t){var n,r,i;if(Os.hasOwnProperty(e))throw new Error('"'+e.toString()+'" is a reserved event name');if(t.unshift(e),this._opts.retries&&!this.flags.fromQueue&&!this.flags.volatile)return this._addToQueue(t),this;const o={type:g.EVENT,data:t};if(o.options={},o.options.compress=this.flags.compress!==!1,typeof t[t.length-1]=="function"){const d=this.ids++,y=t.pop();this._registerAckCallback(d,y),o.id=d}const l=(r=(n=this.io.engine)===null||n===void 0?void 0:n.transport)===null||r===void 0?void 0:r.writable,f=this.connected&&!(!((i=this.io.engine)===null||i===void 0)&&i._hasPingExpired());return this.flags.volatile&&!l||(f?(this.notifyOutgoingListeners(o),this.packet(o)):this.sendBuffer.push(o)),this.flags={},this}_registerAckCallback(e,t){var n;const r=(n=this.flags.timeout)!==null&&n!==void 0?n:this._opts.ackTimeout;if(r===void 0){this.acks[e]=t;return}const i=this.io.setTimeoutFn(()=>{delete this.acks[e];for(let l=0;l<this.sendBuffer.length;l++)this.sendBuffer[l].id===e&&this.sendBuffer.splice(l,1);t.call(this,new Error("operation has timed out"))},r),o=(...l)=>{this.io.clearTimeoutFn(i),t.apply(this,l)};o.withError=!0,this.acks[e]=o}emitWithAck(e,...t){return new Promise((n,r)=>{const i=(o,l)=>o?r(o):n(l);i.withError=!0,t.push(i),this.emit(e,...t)})}_addToQueue(e){let t;typeof e[e.length-1]=="function"&&(t=e.pop());const n={id:this._queueSeq++,tryCount:0,pending:!1,args:e,flags:Object.assign({fromQueue:!0},this.flags)};e.push((r,...i)=>(this._queue[0],r!==null?n.tryCount>this._opts.retries&&(this._queue.shift(),t&&t(r)):(this._queue.shift(),t&&t(null,...i)),n.pending=!1,this._drainQueue())),this._queue.push(n),this._drainQueue()}_drainQueue(e=!1){if(!this.connected||this._queue.length===0)return;const t=this._queue[0];t.pending&&!e||(t.pending=!0,t.tryCount++,this.flags=t.flags,this.emit.apply(this,t.args))}packet(e){e.nsp=this.nsp,this.io._packet(e)}onopen(){typeof this.auth=="function"?this.auth(e=>{this._sendConnectPacket(e)}):this._sendConnectPacket(this.auth)}_sendConnectPacket(e){this.packet({type:g.CONNECT,data:this._pid?Object.assign({pid:this._pid,offset:this._lastOffset},e):e})}onerror(e){this.connected||this.emitReserved("connect_error",e)}onclose(e,t){this.connected=!1,delete this.id,this.emitReserved("disconnect",e,t),this._clearAcks()}_clearAcks(){Object.keys(this.acks).forEach(e=>{if(!this.sendBuffer.some(n=>String(n.id)===e)){const n=this.acks[e];delete this.acks[e],n.withError&&n.call(this,new Error("socket has been disconnected"))}})}onpacket(e){if(e.nsp===this.nsp)switch(e.type){case g.CONNECT:e.data&&e.data.sid?this.onconnect(e.data.sid,e.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 g.EVENT:case g.BINARY_EVENT:this.onevent(e);break;case g.ACK:case g.BINARY_ACK:this.onack(e);break;case g.DISCONNECT:this.ondisconnect();break;case g.CONNECT_ERROR:this.destroy();const n=new Error(e.data.message);n.data=e.data.data,this.emitReserved("connect_error",n);break}}onevent(e){const t=e.data||[];e.id!=null&&t.push(this.ack(e.id)),this.connected?this.emitEvent(t):this.receiveBuffer.push(Object.freeze(t))}emitEvent(e){if(this._anyListeners&&this._anyListeners.length){const t=this._anyListeners.slice();for(const n of t)n.apply(this,e)}super.emit.apply(this,e),this._pid&&e.length&&typeof e[e.length-1]=="string"&&(this._lastOffset=e[e.length-1])}ack(e){const t=this;let n=!1;return function(...r){n||(n=!0,t.packet({type:g.ACK,id:e,data:r}))}}onack(e){const t=this.acks[e.id];typeof t=="function"&&(delete this.acks[e.id],t.withError&&e.data.unshift(null),t.apply(this,e.data))}onconnect(e,t){this.id=e,this.recovered=t&&this._pid===t,this._pid=t,this.connected=!0,this.emitBuffered(),this._drainQueue(!0),this.emitReserved("connect")}emitBuffered(){this.receiveBuffer.forEach(e=>this.emitEvent(e)),this.receiveBuffer=[],this.sendBuffer.forEach(e=>{this.notifyOutgoingListeners(e),this.packet(e)}),this.sendBuffer=[]}ondisconnect(){this.destroy(),this.onclose("io server disconnect")}destroy(){this.subs&&(this.subs.forEach(e=>e()),this.subs=void 0),this.io._destroy(this)}disconnect(){return this.connected&&this.packet({type:g.DISCONNECT}),this.destroy(),this.connected&&this.onclose("io client disconnect"),this}close(){return this.disconnect()}compress(e){return this.flags.compress=e,this}get volatile(){return this.flags.volatile=!0,this}timeout(e){return this.flags.timeout=e,this}onAny(e){return this._anyListeners=this._anyListeners||[],this._anyListeners.push(e),this}prependAny(e){return this._anyListeners=this._anyListeners||[],this._anyListeners.unshift(e),this}offAny(e){if(!this._anyListeners)return this;if(e){const t=this._anyListeners;for(let n=0;n<t.length;n++)if(e===t[n])return t.splice(n,1),this}else this._anyListeners=[];return this}listenersAny(){return this._anyListeners||[]}onAnyOutgoing(e){return this._anyOutgoingListeners=this._anyOutgoingListeners||[],this._anyOutgoingListeners.push(e),this}prependAnyOutgoing(e){return this._anyOutgoingListeners=this._anyOutgoingListeners||[],this._anyOutgoingListeners.unshift(e),this}offAnyOutgoing(e){if(!this._anyOutgoingListeners)return this;if(e){const t=this._anyOutgoingListeners;for(let n=0;n<t.length;n++)if(e===t[n])return t.splice(n,1),this}else this._anyOutgoingListeners=[];return this}listenersAnyOutgoing(){return this._anyOutgoingListeners||[]}notifyOutgoingListeners(e){if(this._anyOutgoingListeners&&this._anyOutgoingListeners.length){const t=this._anyOutgoingListeners.slice();for(const n of t)n.apply(this,e.data)}}}function z(s){s=s||{},this.ms=s.min||100,this.max=s.max||1e4,this.factor=s.factor||2,this.jitter=s.jitter>0&&s.jitter<=1?s.jitter:0,this.attempts=0}z.prototype.duration=function(){var s=this.ms*Math.pow(this.factor,this.attempts++);if(this.jitter){var e=Math.random(),t=Math.floor(e*this.jitter*s);s=(Math.floor(e*10)&1)==0?s-t:s+t}return Math.min(s,this.max)|0};z.prototype.reset=function(){this.attempts=0};z.prototype.setMin=function(s){this.ms=s};z.prototype.setMax=function(s){this.max=s};z.prototype.setJitter=function(s){this.jitter=s};class Ne extends C{constructor(e,t){var n;super(),this.nsps={},this.subs=[],e&&typeof e=="object"&&(t=e,e=void 0),t=t||{},t.path=t.path||"/socket.io",this.opts=t,he(this,t),this.reconnection(t.reconnection!==!1),this.reconnectionAttempts(t.reconnectionAttempts||1/0),this.reconnectionDelay(t.reconnectionDelay||1e3),this.reconnectionDelayMax(t.reconnectionDelayMax||5e3),this.randomizationFactor((n=t.randomizationFactor)!==null&&n!==void 0?n:.5),this.backoff=new z({min:this.reconnectionDelay(),max:this.reconnectionDelayMax(),jitter:this.randomizationFactor()}),this.timeout(t.timeout==null?2e4:t.timeout),this._readyState="closed",this.uri=e;const r=t.parser||bs;this.encoder=new r.Encoder,this.decoder=new r.Decoder,this._autoConnect=t.autoConnect!==!1,this._autoConnect&&this.open()}reconnection(e){return arguments.length?(this._reconnection=!!e,e||(this.skipReconnect=!0),this):this._reconnection}reconnectionAttempts(e){return e===void 0?this._reconnectionAttempts:(this._reconnectionAttempts=e,this)}reconnectionDelay(e){var t;return e===void 0?this._reconnectionDelay:(this._reconnectionDelay=e,(t=this.backoff)===null||t===void 0||t.setMin(e),this)}randomizationFactor(e){var t;return e===void 0?this._randomizationFactor:(this._randomizationFactor=e,(t=this.backoff)===null||t===void 0||t.setJitter(e),this)}reconnectionDelayMax(e){var t;return e===void 0?this._reconnectionDelayMax:(this._reconnectionDelayMax=e,(t=this.backoff)===null||t===void 0||t.setMax(e),this)}timeout(e){return arguments.length?(this._timeout=e,this):this._timeout}maybeReconnectOnOpen(){!this._reconnecting&&this._reconnection&&this.backoff.attempts===0&&this.reconnect()}open(e){if(~this._readyState.indexOf("open"))return this;this.engine=new ps(this.uri,this.opts);const t=this.engine,n=this;this._readyState="opening",this.skipReconnect=!1;const r=x(t,"open",function(){n.onopen(),e&&e()}),i=l=>{this.cleanup(),this._readyState="closed",this.emitReserved("error",l),e?e(l):this.maybeReconnectOnOpen()},o=x(t,"error",i);if(this._timeout!==!1){const l=this._timeout,f=this.setTimeoutFn(()=>{r(),i(new Error("timeout")),t.close()},l);this.opts.autoUnref&&f.unref(),this.subs.push(()=>{this.clearTimeoutFn(f)})}return this.subs.push(r),this.subs.push(o),this}connect(e){return this.open(e)}onopen(){this.cleanup(),this._readyState="open",this.emitReserved("open");const e=this.engine;this.subs.push(x(e,"ping",this.onping.bind(this)),x(e,"data",this.ondata.bind(this)),x(e,"error",this.onerror.bind(this)),x(e,"close",this.onclose.bind(this)),x(this.decoder,"decoded",this.ondecoded.bind(this)))}onping(){this.emitReserved("ping")}ondata(e){try{this.decoder.add(e)}catch(t){this.onclose("parse error",t)}}ondecoded(e){le(()=>{this.emitReserved("packet",e)},this.setTimeoutFn)}onerror(e){this.emitReserved("error",e)}socket(e,t){let n=this.nsps[e];return n?this._autoConnect&&!n.active&&n.connect():(n=new At(this,e,t),this.nsps[e]=n),n}_destroy(e){const t=Object.keys(this.nsps);for(const n of t)if(this.nsps[n].active)return;this._close()}_packet(e){const t=this.encoder.encode(e);for(let n=0;n<t.length;n++)this.engine.write(t[n],e.options)}cleanup(){this.subs.forEach(e=>e()),this.subs.length=0,this.decoder.destroy()}_close(){this.skipReconnect=!0,this._reconnecting=!1,this.onclose("forced close")}disconnect(){return this._close()}onclose(e,t){var n;this.cleanup(),(n=this.engine)===null||n===void 0||n.close(),this.backoff.reset(),this._readyState="closed",this.emitReserved("close",e,t),this._reconnection&&!this.skipReconnect&&this.reconnect()}reconnect(){if(this._reconnecting||this.skipReconnect)return this;const e=this;if(this.backoff.attempts>=this._reconnectionAttempts)this.backoff.reset(),this.emitReserved("reconnect_failed"),this._reconnecting=!1;else{const t=this.backoff.duration();this._reconnecting=!0;const n=this.setTimeoutFn(()=>{e.skipReconnect||(this.emitReserved("reconnect_attempt",e.backoff.attempts),!e.skipReconnect&&e.open(r=>{r?(e._reconnecting=!1,e.reconnect(),this.emitReserved("reconnect_error",r)):e.onreconnect()}))},t);this.opts.autoUnref&&n.unref(),this.subs.push(()=>{this.clearTimeoutFn(n)})}}onreconnect(){const e=this.backoff.attempts;this._reconnecting=!1,this.backoff.reset(),this.emitReserved("reconnect",e)}}const J={};function ue(s,e){typeof s=="object"&&(e=s,s=void 0),e=e||{};const t=ys(s,e.path||"/socket.io"),n=t.source,r=t.id,i=t.path,o=J[r]&&i in J[r].nsps,l=e.forceNew||e["force new connection"]||e.multiplex===!1||o;let f;return l?f=new Ne(n,e):(J[r]||(J[r]=new Ne(n,e)),f=J[r]),t.query&&!e.query&&(e.query=t.queryKey),f.socket(t.path,e)}Object.assign(ue,{Manager:Ne,Socket:At,io:ue,connect:ue});function ws({wsUrl:s,log:e}){let t=null;function n({authPayload:o,queryToken:l}){const f=ue(s,{transports:["polling"],timeout:2e4,reconnection:!1,auth:o,query:l?{token:l}:void 0});return t=f,f}function r(){if(t){try{t.removeAllListeners(),t.connected?t.disconnect():t.close()}catch{}t=null}}function i(){return t}return{connectSocketRaw:n,cleanupSocket:r,getSocket:i}}const Is=s=>{if(window.audioCtx=s,s.state!=="suspended")return;const e=document.body,t=["touchstart","touchend","mousedown","keydown"];t.forEach(i=>e.addEventListener(i,n,!1));function n(){s.resume().then(r)}function r(){t.forEach(i=>e.removeEventListener(i,n))}};function O(s){this.init(s)}O.prototype.init=function(s){var e={encoding:"16bitInt",channels:1,sampleRate:16e3};this.option=Object.assign({},e,s),this.flush=this.flush.bind(this),this.maxValue=this.getMaxValue(),this.typedArray=this.getTypedArray(),this.playingBufferNode=null,this.scheduledBufferNode=null,this.createContext(),this.resetState()};O.prototype.getMaxValue=function(){var s={"8bitInt":128,"16bitInt":32768,"32bitInt":2147483648,"32bitFloat":1};return s[this.option.encoding]?s[this.option.encoding]:s["16bitInt"]};O.prototype.getTypedArray=function(){var s={"8bitInt":Int8Array,"16bitInt":Int16Array,"32bitInt":Int32Array,"32bitFloat":Float32Array};return s[this.option.encoding]?s[this.option.encoding]:s["16bitInt"]};O.prototype.createContext=function(){this.audioCtx=new(window.AudioContext||window.webkitAudioContext),this.audioCtx.resume(),this.audioCtx.onstatechange=()=>console.log("audioCtx.state",this.audioCtx.state),Is(this.audioCtx),this.gainNode=this.audioCtx.createGain(),this.gainNode.gain.value=1,this.gainNode.connect(this.audioCtx.destination),this.startTime=this.audioCtx.currentTime};O.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};O.prototype.isTypedArray=function(s){return s.byteLength&&s.buffer&&s.buffer.constructor==ArrayBuffer};O.prototype.feed=function(s){if(this.isTypedArray(s)){s=this.getFormatedValue(s);var e=new Float32Array(this.samples.length+s.length);e.set(this.samples,0),e.set(s,this.samples.length),this.samples=e,this.timeout||this.flush()}};O.prototype.getFormatedValue=function(e){var e=new this.typedArray(e.buffer),t=new Float32Array(e.length),n;for(n=0;n<e.length;n++)t[n]=e[n]/this.maxValue;return t};O.prototype.volume=function(s){this.gainNode.gain.value=s};O.prototype.destroy=function(){this.interval&&clearInterval(this.interval),this.samples=null,this.audioCtx.close(),this.audioCtx=null};O.prototype.getTimestamp=function(s){if(this.playingStartTime>=0){if(!s)return this.audioCtx.currentTime-this.playingStartTime;const e=this.lastGotTimestamp;return this.lastGotTimestamp+=s/1e3,e}return 0};O.prototype.setRequestStop=function(){this.flag_request_stop=!0};O.prototype.setOnEnd=function(s){this.onEnd=s};O.prototype.interrupt=function(s){this.scheduledBufferNode&&this.scheduledBufferNode.stop(0),this.playingBufferNode&&this.playingBufferNode.stop(0),this.ensuredClearTimeout(),this.resetState(),this.flag_request_stop=!1};O.prototype.ensuredSetTimeout=(function(){let s;return function(e,t){s=performance.now();const n=r=>{r-s>=t?(this.timeout=void 0,e()):this.timeout=requestAnimationFrame(n)};this.timeout=requestAnimationFrame(n)}})();O.prototype.ensuredClearTimeout=function(){this.timeout&&(cancelAnimationFrame(this.timeout),this.timeout=void 0)};O.prototype.flush=function(){if(this.samples.length){var s=this.audioCtx.createBufferSource(),e=this.samples.length/this.option.channels,t=this.audioCtx.createBuffer(this.option.channels,e,this.option.sampleRate),n,r,i,o,l;for(r=0;r<this.option.channels;r++)for(n=t.getChannelData(r),i=r,l=50,o=0;o<e;o++)n[o]=this.samples[i],o<50&&(n[o]=n[o]*o/50),o>=e-51&&(n[o]=n[o]*l--/50),i+=this.option.channels;if(this.startTime<this.audioCtx.currentTime&&(this.startTime=this.audioCtx.currentTime),this.samples=new Float32Array,s.buffer=t,s.connect(this.gainNode),s.start(this.startTime),this.playingBufferNode=this.scheduledBufferNode,this.scheduledBufferNode=s,this.playingStartTime<0&&(this.playingStartTime=this.startTime),this.startTime+=t.duration,this.flag_request_stop)this.flag_request_stop=!1,s.onended=()=>{this.resetState(),this.onEnd&&this.onEnd()};else{const f=(this.startTime-this.audioCtx.currentTime)*1e3;this.ensuredSetTimeout(this.flush,f-50)}}};function ks(s){const e=new O(ut),t=e.destroy.bind(e);let n=!1;return e.destroy=()=>{if(!n){n=!0;try{t()}catch{}}},e.setOnEnd(()=>{n||s()}),e._isDestroyed=()=>n,e}function vs({enableAudio:s,log:e,onPlaybackComplete:t}){let n=null,r=null;function i(){return!s||n||(n=ks(()=>{t()})),n}function o(){if(n){try{n.interrupt?.(),n.destroy?.()}catch{}n=null}}function l(_){const c=i();if(c)try{c.feed(_)}catch(p){e("feedAudio: player.feed() failed",p),t()}}function f(){if(!n){t();return}try{n.setRequestStop(),n.playingBufferNode||n.scheduledBufferNode||t()}catch(_){e("requestStop: setRequestStop() failed",_),t()}}function E(){o()}function d(){if(n)try{const _=n.audioCtx;_?.state==="running"&&_.suspend()}catch(_){e("pauseAudioPlayback: audioCtx.suspend() failed",_)}}async function y(){const _=i();if(_)try{const c=_.audioCtx;c?.state==="suspended"&&await c.resume()}catch(c){e("resumeAudioPlayback: audioCtx.resume() failed",c)}}function T(_){r=_||null}function R(){return r}function a(){return n?n._isDestroyed?.()??!0:!0}return{ensurePcmPlayer:i,destroyPcmPlayer:o,feedAudio:l,requestStop:f,interruptPlayback:E,pauseAudioPlayback:d,resumeAudioPlayback:y,attachAudioElement:T,getAudioElement:R,isDestroyed:a}}function Ds(s){const{wsUrl:e,restUrl:t,enableAudio:n,debug:r,withCredentials:i,onPlaybackComplete:o}=s,l=u.useCallback((...y)=>{r&&console.log("[RqmiiSDK]",...y)},[r]),f=u.useRef(null),E=u.useRef(null),d=u.useRef(null);return f.current||(f.current=ws({wsUrl:e,log:l})),E.current||(E.current=vs({enableAudio:n,log:l,onPlaybackComplete:o})),d.current||(d.current=Lt({restUrl:t,log:l,withCredentials:i})),u.useEffect(()=>()=>{f.current?.cleanupSocket(),E.current?.destroyPcmPlayer()},[]),{socketMgrRef:f,audioMgrRef:E,sessionMgrRef:d,log:l}}function Ee(s){return String(s||"").toLowerCase().replaceAll("-","_")}function xs(s){if(!s)return null;if(s instanceof Uint8Array)return s;if(s instanceof ArrayBuffer)return new Uint8Array(s);if(typeof s=="object"&&s!==null){const e=s;if(e.buffer instanceof ArrayBuffer){const t=s,n=Number.isInteger(t.byteOffset)?t.byteOffset:0,r=Number.isInteger(t.byteLength)?t.byteLength:t.buffer.byteLength-n;return new Uint8Array(t.buffer,n,r)}if(e.type==="Buffer"&&Array.isArray(e.data))return new Uint8Array(e.data)}try{return new Uint8Array(s)}catch{return null}}function Ls(s){const{socket:e,dispatch:t,stateRef:n,sessionIdRef:r,sessionAgentTypeRef:i,interruptedRef:o,manualDisconnectRef:l,chunkAccumulatorRef:f,clientToolsRef:E,audioMgrRef:d,enableAudio:y,cbRefs:T,eventsEmitter:R}=s,a=k,_=d.current;e.on(a.DISCONNECT,c=>{if(t({type:"SET_CONNECTION_STATE",payload:S.IDLE}),t({type:"SET_SESSION_READY",payload:!1}),T.current.onDisconnect?.(c),c==="io server disconnect"||c==="io client disconnect"||l.current){t({type:"SET_CONNECTION_STATE",payload:S.ENDED});return}t({type:"SET_CONNECTION_STATE",payload:S.FAILED}),t({type:"SET_ERROR",payload:"Connection lost"})}),e.on(a.SESSION_READY,c=>{t({type:"SET_SESSION_READY",payload:!0}),t({type:"SET_ERROR",payload:null}),c?.agentType&&t({type:"UPDATE_SESSION",payload:{agentType:Ee(c.agentType)}})}),e.on(a.SESSION_JOINED,()=>{t({type:"SET_SESSION_READY",payload:!0}),t({type:"SET_ERROR",payload:null})}),e.on(a.SESSION_TERMINATED,()=>{_.interruptPlayback(),t({type:"SET_AUDIO_PLAYING",payload:!1}),t({type:"SET_CONNECTION_STATE",payload:S.ENDED}),t({type:"SET_SESSION_READY",payload:!1}),T.current.onSessionTerminated?.(),e.disconnect()}),e.on(a.TRANSCRIPT,c=>{const p=c||null;t({type:"SET_TRANSCRIPT",payload:p}),p?.is_final&&p?.text?.trim()&&(t({type:"ADD_MESSAGE",payload:{id:`transcript-${Date.now()}`,role:"user",text:p.text.trim(),timestamp:new Date().toISOString()}}),t({type:"SET_PARTIAL_TRANSCRIPT",payload:null})),R.emit("transcript",p??void 0),R.emit("partial_transcript",void 0)}),e.on(a.PARTIAL_TRANSCRIPT,c=>{const p=typeof c=="string"?c:c?.text;if(typeof p=="string"&&p.length===0)return;const A=c||null;t({type:"SET_PARTIAL_TRANSCRIPT",payload:A}),R.emit("partial_transcript",A??void 0)}),e.on(a.AGENT_RESPONSE_CHUNK,c=>{const{id:p,text:A}=f.current.addChunk(c?.requestId,c?.text);t({type:"SET_MESSAGES",payload:[...n.current.messages.filter(b=>b.id!==p),{id:p,role:"assistant",text:A,streaming:!0,timestamp:new Date().toISOString()}]})}),e.on(a.AGENT_RESPONSE,c=>{const{id:p,text:A}=f.current.consume(c?.requestId,c?.text);t({type:"SET_MESSAGES",payload:[...n.current.messages.filter(b=>b.id!==p),{id:p,role:"assistant",text:A,streaming:!1,timestamp:new Date().toISOString()}]})}),e.on(a.AVATAR_SPEAKING,()=>{t({type:"SET_AVATAR_SPEAKING",payload:!0})}),e.on(a.AVATAR_SPEAKING_DONE,()=>{t({type:"SET_AVATAR_SPEAKING",payload:!1})}),e.on(a.AGENT_AUDIO_CHUNK,c=>{if(!y||o.current)return;const p=Ee(i.current);if(p==="cloud_avatar"||p==="desktop_avatar"||p==="text")return;const A=xs(c?.audio);A&&(_.feedAudio(A),t({type:"SET_AUDIO_PLAYING",payload:!0}))}),e.on(a.AGENT_AUDIO_COMPLETE,()=>{if(!y)return;const c=Ee(i.current);c==="cloud_avatar"||c==="desktop_avatar"||c==="text"||_.requestStop()}),e.on(a.INTERRUPTED,()=>{const c=!_.isDestroyed();o.current=!1,_.interruptPlayback(),t({type:"SET_AUDIO_PLAYING",payload:!1}),c&&e.connected&&e.emit(a.AUDIO_PLAYBACK_COMPLETE,{session_id:r.current})}),e.on(a.AUTH_ERROR,c=>{t({type:"SET_CONNECTION_STATE",payload:S.FAILED}),t({type:"SET_ERROR",payload:c?.message||"Authentication error"})}),e.on(a.ERROR,c=>{const p=c?.code;if(!(p==="TTS_ERROR"||p==="STT_ERROR"||p==="LLM_ERROR")){if(p==="INSUFFICIENT_CREDITS"){t({type:"SET_CREDIT_EXHAUSTED",payload:{exhausted:!0,error:c?.message||"Insufficient credits to process this request."}}),T.current.onError?.(c);return}t({type:"SET_ERROR",payload:c?.message||c?.detail||"Server error"}),T.current.onError?.(c)}}),e.on(a.SESSION_EXPIRED,c=>{t({type:"SET_CONNECTION_STATE",payload:S.ENDED}),t({type:"SET_SESSION_READY",payload:!1}),T.current.onSessionExpired?.(c)}),e.on(a.CREDITS_EXHAUSTED,()=>{t({type:"SET_CREDIT_EXHAUSTED",payload:{exhausted:!0,error:"This project has run out of credits."}}),t({type:"SET_CONNECTION_STATE",payload:S.ENDED}),t({type:"SET_SESSION_READY",payload:!1}),l.current=!0;try{e.disconnect()}catch{}}),e.on(a.SESSION_STATE_CHANGED,c=>{c?.state&&t({type:"SET_SESSION_STATE",payload:c.state})}),e.on(a.LANGUAGE_CHANGED,c=>{const p=c?.language;p&&R.emit("language_changed",{language:p})}),e.on(a.SHOW_LEAD_CAPTURE_FORM,c=>{const p=Array.isArray(c?.fields)?c.fields:[],A=c?.agentId;!A||p.length===0||t({type:"ADD_MESSAGE",payload:{id:`lead-form-${Date.now()}`,role:"lead_form",text:"",form:{agentId:A,title:c?.title,fields:p},timestamp:new Date().toISOString()}})}),e.on(a.MESSAGE_RATE_LIMITED,c=>{R.emit("message_rate_limited",c)}),e.on(a.CLIENT_TOOL_REQUEST,c=>{const p=c?.executionId,A=c?.toolName,b=c?.parameters??{},$=c?.waitForResponse!==!1;if(!A)return;const w=E.current[A];if(!w)return;const V={minimize:()=>R.emit("minimize_chat"),maximize:()=>R.emit("maximize_chat")};$&&p?w(b,V).then(B=>{e.emit(a.CLIENT_TOOL_RESULT,{executionId:p,result:B})}).catch(B=>{e.emit(a.CLIENT_TOOL_RESULT,{executionId:p,result:{error:B instanceof Error?B.message:String(B)}})}):w(b,V).catch(()=>{})})}class Rt{listeners=new Map;on(e,t){return this.listeners.has(e)||this.listeners.set(e,new Set),this.listeners.get(e).add(t),()=>this.off(e,t)}once(e,t){const n=((...r)=>{this.off(e,n),t(...r)});return this.on(e,n)}off(e,t){this.listeners.get(e)?.delete(t)}emit(e,t){const n=this.listeners.get(e);if(n)for(const r of n)try{r(t)}catch{}}removeAllListeners(){this.listeners.clear()}}const Nt=u.createContext(null);function Ct({children:s,wsUrl:e="wss://ws.rqmii.com",restUrl:t="https://api.rqmii.com/api/v1",enableAudio:n=!0,debug:r=!1,heartbeatIntervalSeconds:i=15,withCredentials:o=!1,onSessionExpired:l,onSessionTerminated:f,onError:E,onDisconnect:d}){const[y,T]=u.useReducer(st,ge),R=u.useRef(y),a=u.useCallback(h=>{R.current=st(R.current,h),T(h)},[]),_=u.useRef(!1),c=u.useRef(Dt()),p=u.useRef(null),A=u.useRef(ge.session.agentType),b=u.useRef(!1),$=u.useRef(new Rt),w=u.useRef({}),V=u.useRef({onSessionExpired:l,onSessionTerminated:f,onError:E,onDisconnect:d});u.useEffect(()=>{ct(),V.current={onSessionExpired:l,onSessionTerminated:f,onError:E,onDisconnect:d}},[l,f,E,d]),u.useEffect(()=>{A.current=y.session.agentType},[y.session.agentType]),u.useEffect(()=>{p.current=y.session.sessionId},[y.session.sessionId]);const B=u.useCallback(()=>{a({type:"SET_AUDIO_PLAYING",payload:!1});const h=q.current?.getSocket();h?.connected&&h.emit(k.AUDIO_PLAYBACK_COMPLETE,{session_id:p.current})},[]),{socketMgrRef:q,audioMgrRef:H,sessionMgrRef:X}=Ds({wsUrl:e,restUrl:t,enableAudio:n,debug:r,withCredentials:o,onPlaybackComplete:B}),ve=u.useCallback(h=>{Ls({socket:h,dispatch:a,stateRef:R,sessionIdRef:p,sessionAgentTypeRef:A,interruptedRef:b,manualDisconnectRef:_,chunkAccumulatorRef:c,clientToolsRef:w,audioMgrRef:{current:H.current},enableAudio:n,cbRefs:V,eventsEmitter:$.current})},[n]),ee=u.useCallback(({authPayload:h,queryToken:m})=>new Promise((v,M)=>{q.current?.cleanupSocket();const I=q.current.connectSocketRaw({authPayload:h,queryToken:m});ve(I),I.once("connect",()=>{a({type:"SET_CONNECTION_STATE",payload:S.CONNECTED}),a({type:"SET_ERROR",payload:null}),v(I)}),I.once("connect_error",se=>{a({type:"SET_CONNECTION_STATE",payload:S.FAILED}),a({type:"SET_ERROR",payload:se?.message||"Connection error"}),M(se)})}),[ve]),Y=u.useCallback(({keepManualDisconnect:h=!1}={})=>{_.current=!0,b.current=!1,c.current.clear(),H.current.destroyPcmPlayer(),q.current.cleanupSocket(),h||(_.current=!1),a({type:"HARD_RESET"})},[]),De=u.useCallback(async({apiKey:h,agentId:m,userId:v,language:M="en",clientTools:I,config:se,promptOverrides:It}={})=>{if(!h&&!m)throw new Error("Provide one of apiKey or agentId");Y(),w.current=I??{},a({type:"SET_CONNECTION_STATE",payload:S.INITIALIZING}),a({type:"SET_ERROR",payload:null});const kt=xt();let fe;try{fe=await X.current.initializeSession({apiKey:h,agentId:m,userId:v,language:M,timezone:kt,config:se,promptOverrides:It})}catch(ne){const F=ne;throw F.status===401||F.status===403?(a({type:"SET_CONNECTION_STATE",payload:S.FAILED}),a({type:"SET_ERROR",payload:F.message||"Authentication failed"})):F.status===402?(a({type:"SET_CREDIT_EXHAUSTED",payload:{exhausted:!0,error:F.message||"Insufficient credits"}}),a({type:"SET_CONNECTION_STATE",payload:S.FAILED})):F.status===429?(a({type:"SET_CONNECTION_STATE",payload:S.FAILED}),a({type:"SET_ERROR",payload:F.message||"Too many requests. Please try again later."})):(a({type:"SET_CONNECTION_STATE",payload:S.FAILED}),a({type:"SET_ERROR",payload:F.message||"Failed to initialize session"})),ne}const K=fe;a({type:"UPDATE_SESSION",payload:{sessionId:K.session_id,agentType:K.streaming_url?_e.CLOUD_AVATAR:y.session.agentType,streamingUrl:K.streaming_url||null,uniqueId:K.unique_id||null}}),a({type:"SET_CONNECTION_STATE",payload:S.CONNECTING}),a({type:"SET_CLOUD_STREAM_STATE",payload:{state:K.streaming_url?Z.CONNECTING:Z.IDLE,error:null}}),_.current=!0;try{await ee({authPayload:{token:K.session_token},queryToken:K.session_token}),_.current=!1}catch(ne){throw _.current=!1,ne}return fe},[ee,Y,e,y.session.agentType]),xe=u.useCallback(async({uniqueId:h})=>{if(!h)throw new Error("uniqueId is required");Y(),a({type:"SET_CONNECTION_STATE",payload:S.INITIALIZING}),a({type:"SET_ERROR",payload:null});let m;try{m=await X.current.joinDesktopSession({uniqueId:h})}catch(M){const I=M;throw(I.status===401||I.status===403)&&(a({type:"SET_CONNECTION_STATE",payload:S.FAILED}),a({type:"SET_ERROR",payload:I.message||"Authentication failed"})),I.status===402&&(a({type:"SET_CREDIT_EXHAUSTED",payload:{exhausted:!0,error:I.message||"Insufficient credits"}}),a({type:"SET_CONNECTION_STATE",payload:S.FAILED})),I.status===429&&(a({type:"SET_CONNECTION_STATE",payload:S.FAILED}),a({type:"SET_ERROR",payload:I.message||"Too many requests. Please try again later."})),M}const v=m;a({type:"UPDATE_SESSION",payload:{sessionId:v.session_id,uniqueId:h,role:"user",agentType:_e.DESKTOP_AVATAR}}),a({type:"SET_CONNECTION_STATE",payload:S.CONNECTING}),a({type:"SET_CLOUD_STREAM_STATE",payload:{state:Z.IDLE,error:null}}),_.current=!0;try{await ee({authPayload:{token:v.session_token},queryToken:v.session_token}),_.current=!1}catch(M){throw _.current=!1,M}return m},[ee,Y,e]),te=u.useCallback(()=>Y({keepManualDisconnect:!0}),[Y]),Le=u.useCallback(async()=>{const h=q.current?.getSocket();return h&&y.isConnected&&(h.emit("end_session"),await new Promise(m=>setTimeout(m,150))),te(),{success:!0}},[te,y.isConnected]),Pe=u.useCallback(()=>{const h=q.current?.getSocket();h?.connected?h.emit("end_session"):(a({type:"SET_CONNECTION_STATE",payload:S.ENDED}),a({type:"SET_SESSION_READY",payload:!1}))},[]),N=u.useCallback((h,m={})=>{const v=q.current?.getSocket();return!v||!y.isConnected?!1:(v.emit(h,m),!0)},[y.isConnected]),Be=u.useCallback(h=>!h||!String(h).trim()?!1:(a({type:"ADD_MESSAGE",payload:{id:`user-${Date.now()}`,role:"user",text:String(h),timestamp:new Date().toISOString()}}),N(k.USER_MESSAGE,{message:String(h)})),[N]),Ue=u.useCallback((h,m)=>{!m||!String(m).trim()||a({type:"ADD_MESSAGE",payload:{id:`${h}-${Date.now()}`,role:h,text:String(m),timestamp:new Date().toISOString()}})},[]),qe=u.useCallback(h=>!h||!String(h).trim()?!1:N(k.USER_MESSAGE,{message:String(h)}),[N]),Me=u.useCallback(h=>N(k.AUDIO_CHUNK,{audio:h}),[N]),Fe=u.useCallback(()=>N(k.AUDIO_END,{}),[N]),Ge=u.useCallback(()=>(b.current=!0,H.current.interruptPlayback(),a({type:"SET_AUDIO_PLAYING",payload:!1}),N(k.INTERRUPT,{})),[N]),Ve=u.useCallback(()=>N(k.CLEAR_SESSION_HISTORY,{}),[N]),He=u.useCallback(h=>h?N(k.CHANGE_SESSION_LANGUAGE,{language:h}):!1,[N]),Ke=u.useCallback((h={})=>N(k.CLIENT_READY,h),[N]),je=u.useCallback(()=>N(k.PING,{}),[N]),Ye=u.useCallback(()=>{c.current.clear(),a({type:"SET_MESSAGES",payload:[]})},[]),ze=u.useCallback(h=>{a({type:"SET_MESSAGES",payload:h})},[]),$e=u.useCallback(()=>H.current.resumeAudioPlayback(),[]),Xe=u.useCallback(()=>H.current.pauseAudioPlayback(),[]),We=u.useCallback(h=>H.current.attachAudioElement(h),[]),Je=u.useCallback((h,m=null)=>{a({type:"SET_CLOUD_STREAM_STATE",payload:{state:h,error:m?String(m):null}})},[]),Ot=u.useCallback(async h=>{try{const m=await X.current.fetchAgentConfig(h);return a({type:"SET_AGENT_CONFIG",payload:m}),m}catch(m){throw a({type:"SET_AGENT_CONFIG",payload:null}),m}},[t]),Qe=u.useCallback(h=>{Object.keys(w.current).length===0?w.current=h:Object.assign(w.current,h)},[]),Ze=u.useCallback(h=>{const m=h.sessionId||p.current;return m?X.current.submitFeedback({sessionId:m,rating:h.rating,feedback:h.feedback,endedBy:h.endedBy}):Promise.reject(new Error("No session id available for feedback"))},[]),et=u.useCallback(async h=>{const m=h.sessionId||p.current;if(!m)return Promise.reject(new Error("No session id available for lead capture"));const v=await X.current.submitLead({agentId:h.agentId,sessionId:m,collectedData:h.collectedData});return N(k.LEAD_FORM_SUBMITTED),v},[N]),tt=u.useMemo(()=>vt(y.sessionState),[y.sessionState]),wt=u.useMemo(()=>({...y,...tt,initializeSession:De,joinDesktopSession:xe,disconnect:te,terminateSession:Le,endSession:Pe,emit:N,sendTextMessage:Be,addLocalMessage:Ue,emitUserMessage:qe,sendAudioChunk:Me,endAudioStream:Fe,interrupt:Ge,clearSessionHistory:Ve,changeSessionLanguage:He,signalClientReady:Ke,sendPing:je,clearMessages:Ye,setMessages:ze,resumeAudioPlayback:$e,pauseAudioPlayback:Xe,attachAudioElement:We,fetchAgentConfig:Ot,submitFeedback:Ze,submitLead:et,setCloudStreamState:Je,registerClientTools:Qe,events:$.current,audioElement:H.current?.getAudioElement()??null,socket:q.current?.getSocket()??null}),[y,tt,De,xe,te,Le,Pe,N,Be,Ue,qe,Me,Fe,Ge,Ve,He,Ke,je,Ye,ze,$e,Xe,We,Je,Qe,Ze,et]);return U.jsx(Nt.Provider,{value:wt,children:s})}function ke(){const s=u.useContext(Nt);if(!s)throw new Error("useRqmiiAgentContext must be used inside <RqmiiAgentProvider>");return s}function bt(){const s=ke();return{connectionState:s.connectionState,isConnected:s.isConnected,isSessionReady:s.isSessionReady,error:s.error,session:s.session,creditExhausted:s.creditExhausted,creditError:s.creditError,sessionState:s.sessionState,isSessionTerminated:s.isSessionTerminated,isSessionTerminating:s.isSessionTerminating,isAgentThinking:s.isAgentThinking,isAgentSpeaking:s.isAgentSpeaking,isToolExecuting:s.isToolExecuting,agentConfig:s.agentConfig,initializeSession:s.initializeSession,joinDesktopSession:s.joinDesktopSession,disconnect:s.disconnect,terminateSession:s.terminateSession,endSession:s.endSession,interrupt:s.interrupt,clearSessionHistory:s.clearSessionHistory,changeSessionLanguage:s.changeSessionLanguage,signalClientReady:s.signalClientReady,fetchAgentConfig:s.fetchAgentConfig,submitFeedback:s.submitFeedback,registerClientTools:s.registerClientTools,events:s.events}}function Ps(){const s=ke();return{messages:s.messages,sendTextMessage:s.sendTextMessage,addLocalMessage:s.addLocalMessage,emitUserMessage:s.emitUserMessage,clearMessages:s.clearMessages}}function Bs({connect:s=!0,session:e,onError:t,onInitialized:n,clientTools:r,children:i}){const{initializeSession:o,joinDesktopSession:l,disconnect:f,registerClientTools:E}=bt(),d=u.useRef(!1),y=u.useRef(!1),T=u.useRef(o),R=u.useRef(l),a=u.useRef(f),_=u.useRef(t),c=u.useRef(n),p=u.useRef(E),A=u.useRef(r);return u.useEffect(()=>{T.current=o}),u.useEffect(()=>{R.current=l}),u.useEffect(()=>{a.current=f}),u.useEffect(()=>{_.current=t}),u.useEffect(()=>{c.current=n}),u.useEffect(()=>{p.current=E}),u.useEffect(()=>{A.current=r}),u.useEffect(()=>{if(!s||d.current)return;d.current=!0,y.current=!1;let b=!1;return(async()=>{try{const w=A.current;if(e?.mode==="join_desktop"){const B=await R.current({uniqueId:e.uniqueId});b||(w&&p.current(w),c.current?.(B));return}const V=await T.current({apiKey:e?.apiKey,agentId:e?.agentId,language:e?.language||"en",config:e?.config,promptOverrides:e?.promptOverrides,clientTools:w});b||c.current?.(V)}catch(w){b||(y.current=!0,_.current?.(w))}})(),()=>{b=!0,!y.current&&(a.current(),d.current=!1)}},[s,e]),U.jsx(U.Fragment,{children:i})}function Us({children:s,wsUrl:e,restUrl:t,session:n,connect:r=!0,enableAudio:i=!0,debug:o=!1,withCredentials:l=!1,onError:f,onInitialized:E,clientTools:d}){return U.jsx(Ct,{wsUrl:e,restUrl:t,enableAudio:i,debug:o,withCredentials:l,children:U.jsx(Bs,{connect:r,session:n,onError:f,onInitialized:E,clientTools:d,children:s})})}class qs extends u.Component{constructor(e){super(e),this.state={hasError:!1,error:null}}static getDerivedStateFromError(e){return{hasError:!0,error:e}}componentDidCatch(e,t){this.props.onError?.(e,t)}reset=()=>{this.setState({hasError:!1,error:null})};render(){if(this.state.hasError){const{fallback:e}=this.props;return e?typeof e=="function"?this.state.error?e(this.state.error,this.reset):null:e:U.jsxs("div",{style:{padding:"24px",textAlign:"center",color:"#ef4444"},children:[U.jsx("h3",{children:"Something went wrong"}),U.jsx("p",{children:this.state.error?.message||"An unexpected error occurred"}),U.jsx("button",{onClick:this.reset,style:{marginTop:"12px",padding:"8px 16px",cursor:"pointer"},children:"Try again"})]})}return this.props.children}}exports.AGENT_TYPES=_e;exports.CLOUD_STREAM_STATE=Z;exports.CONNECTION_STATE=S;exports.DEFAULT_PCM_OPTIONS=ut;exports.EventEmitter=Rt;exports.RqmiiAgentProvider=Ct;exports.RqmiiAgentRoom=Us;exports.RqmiiErrorBoundary=qs;exports.SESSION_STATE=j;exports.SOCKET_EVENTS=k;exports.suppressNoisyLogs=ct;exports.useRqmiiAgentContext=ke;exports.useRqmiiConnection=bt;exports.useRqmiiMessages=Ps;
|
|
2
|
+
//# sourceMappingURL=RqmiiErrorBoundary-Byif85f5.cjs.map
|