@flowengage/react-chatbot 1.2.9 → 1.3.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/flowengage-embed.js +21 -21
- package/dist/flowengage-react-chatbot.cjs +16 -16
- package/dist/flowengage-react-chatbot.mjs +2743 -2727
- package/package.json +1 -1
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`});var e=Object.create,t=Object.defineProperty,n=Object.getOwnPropertyDescriptor,r=Object.getOwnPropertyNames,i=Object.getPrototypeOf,a=Object.prototype.hasOwnProperty,o=(e,n)=>{let r={};for(var i in e)t(r,i,{get:e[i],enumerable:!0});return n||t(r,Symbol.toStringTag,{value:`Module`}),r},s=(e,i,o,s)=>{if(i&&typeof i==`object`||typeof i==`function`)for(var c=r(i),l=0,u=c.length,d;l<u;l++)d=c[l],!a.call(e,d)&&d!==o&&t(e,d,{get:(e=>i[e]).bind(null,d),enumerable:!(s=n(i,d))||s.enumerable});return e},c=(n,r,a)=>(a=n==null?{}:e(i(n)),s(r||!n||!n.__esModule?t(a,`default`,{value:n,enumerable:!0}):a,n));let l=require(`react`);l=c(l);let u=require(`react/jsx-runtime`);var d=e=>{if(!e||typeof e!=`object`)throw Error(`FlowEngage config is required`);if(!e.siteId||typeof e.siteId!=`string`)throw Error(`[FlowEngage] config.siteId is required. Pass it as <FlowEngageProvider siteId="your-site-id" /> or config={{ siteId: 'your-site-id' }}.`);let t=(e.apiBaseUrl||`https://be-flowengage.oslabs.app`).replace(/\/+$/,``);return{siteId:e.siteId.trim(),apiBaseUrl:t}},f={chatId:`flowengage.chatId`,isOpen:`flowengage.isOpen`,activeScreen:`flowengage.activeScreen`,isHumanHandled:`flowengage.isHumanHandled`,agentName:`flowengage.agentName`,agentHeadshot:`flowengage.agentHeadshot`,visitorEmail:`flowengage.visitorEmail`},p=1e4,m=6e4,ee=480*60,h=3e4,g=typeof window<`u`,_=e=>e?`flowengage.visitorEmail.${e}`:null,te=()=>{if(!g)return`server-chat-id`;let e=window.localStorage.getItem(f.chatId);if(e)return e;let t=typeof crypto<`u`&&crypto.randomUUID?crypto.randomUUID():`${Date.now()}-${Math.random().toString(16).slice(2)}`;return window.localStorage.setItem(f.chatId,t),t},ne=()=>g?{isOpen:!1,activeScreen:window.sessionStorage.getItem(f.activeScreen)||`ai`,isHumanHandled:window.sessionStorage.getItem(f.isHumanHandled)===`true`,agentName:window.sessionStorage.getItem(f.agentName),agentHeadshot:window.sessionStorage.getItem(f.agentHeadshot),visitorEmail:``}:{isOpen:!1,activeScreen:`ai`,isHumanHandled:!1,agentName:null,agentHeadshot:null,visitorEmail:``},re=e=>{g&&Object.entries(e).forEach(([e,t])=>{let n=f[e];if(n){if(t==null||t===!1){window.sessionStorage.removeItem(n);return}window.sessionStorage.setItem(n,String(t))}})},ie=e=>{if(!g||!e)return``;let t=_(e),n=window.localStorage.getItem(t);if(!n){let e=window.sessionStorage.getItem(f.visitorEmail);e&&(window.localStorage.setItem(t,e),window.sessionStorage.removeItem(f.visitorEmail),n=e)}return n||``},ae=(e,t)=>{if(!g)return;let n=_(t);if(!n)return;let r=typeof e==`string`?e.trim():``;if(!r){window.localStorage.removeItem(n),window.sessionStorage.removeItem(f.visitorEmail);return}window.localStorage.setItem(n,r),window.sessionStorage.removeItem(f.visitorEmail)},oe=async e=>{let t=await e.json().catch(()=>({}));if(!e.ok){let n=Error(t.message||t.error||`Request failed with status ${e.status}`);throw n.status=e.status,n}return t},v=async(e,t={})=>{try{return await fetch(e,{mode:`cors`,...t})}catch(t){let n=Error(`Network error reaching ${e}. Check: (1) backend is running, (2) CORS allows this origin, (3) siteId is correct. Original: ${t.message}`);throw n.status=0,n.cause=t,n}},se=async({apiBaseUrl:e,siteId:t})=>{let n=typeof window<`u`?window.location.origin:`http://localhost`,r=`${e}/api/widget/chatbot-loader?${new URLSearchParams({siteId:t,origin:n}).toString()}`;console.log(`[FlowEngageAPI] bootstrap request`,{apiBaseUrl:e,siteId:t,origin:n,url:r});let i=await oe(await v(r,{method:`GET`}));return console.log(`[FlowEngageAPI] bootstrap success`,i),i.data},ce=({apiBaseUrl:e,userId:t,siteId:n})=>{let r=(t,n)=>{let r=`${e}${t}`,i=JSON.stringify(n);if(typeof navigator<`u`&&navigator.sendBeacon)try{let e=new Blob([i],{type:`application/json`});return navigator.sendBeacon(r,e)}catch{}return typeof fetch<`u`?(fetch(r,{method:`POST`,mode:`cors`,keepalive:!0,headers:{"Content-Type":`application/json`},body:i}).catch(()=>{}),!0):!1},i=async(r,i={})=>oe(await v(`${e}${r}`,{...i,headers:{"Content-Type":`application/json`,"x-user-id":t,...n?{"x-site-id":n}:{},...i.headers||{}}}));return{async loadHistory(e,t=`en`,n=``){return i(`/api/ai/chat`,{method:`POST`,body:JSON.stringify({session_id:e,user_query:``,lang:t,category:n})})},async sendAiMessage(e,t,n=`en`,r=``,a=null){return i(`/api/ai/chat`,{method:`POST`,body:JSON.stringify({session_id:e,user_query:t,lang:n,category:r,...a||{}})})},async checkHumanHandled(e){return i(`/api/ai/check_human_handled`,{method:`POST`,body:JSON.stringify({session_id:e})})},async setChatMode(e,t){return i(`/api/ai/set_chat_mode`,{method:`POST`,body:JSON.stringify({session_id:e,mode:t})})},async toggleVoice(e){return i(`/api/ai/voice/toggle`,{method:`POST`,body:JSON.stringify({session_id:e})})},async syncVoice(e,r){return i(`/api/ai/voice/sync`,{method:`POST`,body:JSON.stringify({session_id:e,messages:r,...t?{userId:String(t)}:{},...n?{siteId:String(n)}:{}})})},async trackVisitor(e){return i(`/api/visitors/track`,{method:`POST`,body:JSON.stringify(e)})},async updateChatStatus(e,t){return i(`/api/chat/status`,{method:`POST`,body:JSON.stringify({chatId:e,type:t})})},async startConversation(e,t=`en`){return i(`/api/chat/status`,{method:`POST`,body:JSON.stringify({chatId:e,type:`open`,lang:t})})},async endConversation(e){return i(`/api/chat/status`,{method:`POST`,body:JSON.stringify({chatId:e,type:`closed`})})},async acceptCall(e,t){return i(`/api/calls/${e}/accept`,{method:`POST`,body:JSON.stringify({session_id:t,site_id:n})})},async rejectCall(e,t){return i(`/api/calls/${e}/reject`,{method:`POST`,body:JSON.stringify({session_id:t,site_id:n})})},async endWebRTCCall(e,t){return i(`/api/calls/${e}/end`,{method:`POST`,body:JSON.stringify({session_id:t,site_id:n,endedBy:`customer`})})},async markCustomerUnavailable(e,t){return i(`/api/calls/${e}/customer-unavailable`,{method:`POST`,body:JSON.stringify({session_id:t,site_id:n})})},beaconEndWebRTCCall(e,t){return r(`/api/calls/${e}/end`,{session_id:t,site_id:n,endedBy:`customer`})},beaconCustomerUnavailable(e,t){return r(`/api/calls/${e}/customer-unavailable`,{session_id:t,site_id:n})},beaconSyncVoice(r,i){if(typeof navigator>`u`||!navigator.sendBeacon)return!1;let a={session_id:r,messages:i,...t?{userId:String(t)}:{},...n?{siteId:String(n)}:{}},o=new Blob([JSON.stringify(a)],{type:`application/json`});return navigator.sendBeacon(`${e}/api/ai/voice/sync`,o)}}},y=Object.create(null);y.open=`0`,y.close=`1`,y.ping=`2`,y.pong=`3`,y.message=`4`,y.upgrade=`5`,y.noop=`6`;var le=Object.create(null);Object.keys(y).forEach(e=>{le[y[e]]=e});var ue={type:`error`,data:`parser error`},de=typeof Blob==`function`||typeof Blob<`u`&&Object.prototype.toString.call(Blob)===`[object BlobConstructor]`,fe=typeof ArrayBuffer==`function`,pe=e=>typeof ArrayBuffer.isView==`function`?ArrayBuffer.isView(e):e&&e.buffer instanceof ArrayBuffer,me=({type:e,data:t},n,r)=>de&&t instanceof Blob?n?r(t):he(t,r):fe&&(t instanceof ArrayBuffer||pe(t))?n?r(t):he(new Blob([t]),r):r(y[e]+(t||``)),he=(e,t)=>{let n=new FileReader;return n.onload=function(){let e=n.result.split(`,`)[1];t(`b`+(e||``))},n.readAsDataURL(e)};function ge(e){return e instanceof Uint8Array?e:e instanceof ArrayBuffer?new Uint8Array(e):new Uint8Array(e.buffer,e.byteOffset,e.byteLength)}var _e;function ve(e,t){if(de&&e.data instanceof Blob)return e.data.arrayBuffer().then(ge).then(t);if(fe&&(e.data instanceof ArrayBuffer||pe(e.data)))return t(ge(e.data));me(e,!1,e=>{_e||=new TextEncoder,t(_e.encode(e))})}var ye=`ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/`,be=typeof Uint8Array>`u`?[]:new Uint8Array(256);for(let e=0;e<64;e++)be[ye.charCodeAt(e)]=e;var xe=e=>{let t=e.length*.75,n=e.length,r,i=0,a,o,s,c;e[e.length-1]===`=`&&(t--,e[e.length-2]===`=`&&t--);let l=new ArrayBuffer(t),u=new Uint8Array(l);for(r=0;r<n;r+=4)a=be[e.charCodeAt(r)],o=be[e.charCodeAt(r+1)],s=be[e.charCodeAt(r+2)],c=be[e.charCodeAt(r+3)],u[i++]=a<<2|o>>4,u[i++]=(o&15)<<4|s>>2,u[i++]=(s&3)<<6|c&63;return l},Se=typeof ArrayBuffer==`function`,Ce=(e,t)=>{if(typeof e!=`string`)return{type:`message`,data:Te(e,t)};let n=e.charAt(0);return n===`b`?{type:`message`,data:we(e.substring(1),t)}:le[n]?e.length>1?{type:le[n],data:e.substring(1)}:{type:le[n]}:ue},we=(e,t)=>Se?Te(xe(e),t):{base64:!0,data:e},Te=(e,t)=>{switch(t){case`blob`:return e instanceof Blob?e:new Blob([e]);default:return e instanceof ArrayBuffer?e:e.buffer}},Ee=``,De=(e,t)=>{let n=e.length,r=Array(n),i=0;e.forEach((e,a)=>{me(e,!1,e=>{r[a]=e,++i===n&&t(r.join(Ee))})})},Oe=(e,t)=>{let n=e.split(Ee),r=[];for(let e=0;e<n.length;e++){let i=Ce(n[e],t);if(r.push(i),i.type===`error`)break}return r};function ke(){return new TransformStream({transform(e,t){ve(e,n=>{let r=n.length,i;if(r<126)i=new Uint8Array(1),new DataView(i.buffer).setUint8(0,r);else if(r<65536){i=new Uint8Array(3);let e=new DataView(i.buffer);e.setUint8(0,126),e.setUint16(1,r)}else{i=new Uint8Array(9);let e=new DataView(i.buffer);e.setUint8(0,127),e.setBigUint64(1,BigInt(r))}e.data&&typeof e.data!=`string`&&(i[0]|=128),t.enqueue(i),t.enqueue(n)})}})}var Ae;function je(e){return e.reduce((e,t)=>e+t.length,0)}function Me(e,t){if(e[0].length===t)return e.shift();let n=new Uint8Array(t),r=0;for(let i=0;i<t;i++)n[i]=e[0][r++],r===e[0].length&&(e.shift(),r=0);return e.length&&r<e[0].length&&(e[0]=e[0].slice(r)),n}function Ne(e,t){Ae||=new TextDecoder;let n=[],r=0,i=-1,a=!1;return new TransformStream({transform(o,s){for(n.push(o);;){if(r===0){if(je(n)<1)break;let e=Me(n,1);a=(e[0]&128)==128,i=e[0]&127,r=i<126?3:i===126?1:2}else if(r===1){if(je(n)<2)break;let e=Me(n,2);i=new DataView(e.buffer,e.byteOffset,e.length).getUint16(0),r=3}else if(r===2){if(je(n)<8)break;let e=Me(n,8),t=new DataView(e.buffer,e.byteOffset,e.length),a=t.getUint32(0);if(a>2**21-1){s.enqueue(ue);break}i=a*2**32+t.getUint32(4),r=3}else{if(je(n)<i)break;let e=Me(n,i);s.enqueue(Ce(a?e:Ae.decode(e),t)),r=0}if(i===0||i>e){s.enqueue(ue);break}}}})}function b(e){if(e)return Pe(e)}function Pe(e){for(var t in b.prototype)e[t]=b.prototype[t];return e}b.prototype.on=b.prototype.addEventListener=function(e,t){return this._callbacks=this._callbacks||{},(this._callbacks[`$`+e]=this._callbacks[`$`+e]||[]).push(t),this},b.prototype.once=function(e,t){function n(){this.off(e,n),t.apply(this,arguments)}return n.fn=t,this.on(e,n),this},b.prototype.off=b.prototype.removeListener=b.prototype.removeAllListeners=b.prototype.removeEventListener=function(e,t){if(this._callbacks=this._callbacks||{},arguments.length==0)return this._callbacks={},this;var n=this._callbacks[`$`+e];if(!n)return this;if(arguments.length==1)return delete this._callbacks[`$`+e],this;for(var r,i=0;i<n.length;i++)if(r=n[i],r===t||r.fn===t){n.splice(i,1);break}return n.length===0&&delete this._callbacks[`$`+e],this},b.prototype.emit=function(e){this._callbacks=this._callbacks||{};for(var t=Array(arguments.length-1),n=this._callbacks[`$`+e],r=1;r<arguments.length;r++)t[r-1]=arguments[r];if(n){n=n.slice(0);for(var r=0,i=n.length;r<i;++r)n[r].apply(this,t)}return this},b.prototype.emitReserved=b.prototype.emit,b.prototype.listeners=function(e){return this._callbacks=this._callbacks||{},this._callbacks[`$`+e]||[]},b.prototype.hasListeners=function(e){return!!this.listeners(e).length};var Fe=typeof Promise==`function`&&typeof Promise.resolve==`function`?e=>Promise.resolve().then(e):(e,t)=>t(e,0),x=typeof self<`u`?self:typeof window<`u`?window:Function(`return this`)(),Ie=`arraybuffer`;function Le(e,...t){return t.reduce((t,n)=>(e.hasOwnProperty(n)&&(t[n]=e[n]),t),{})}var Re=x.setTimeout,ze=x.clearTimeout;function Be(e,t){t.useNativeTimers?(e.setTimeoutFn=Re.bind(x),e.clearTimeoutFn=ze.bind(x)):(e.setTimeoutFn=x.setTimeout.bind(x),e.clearTimeoutFn=x.clearTimeout.bind(x))}var Ve=1.33;function He(e){return typeof e==`string`?Ue(e):Math.ceil((e.byteLength||e.size)*Ve)}function Ue(e){let t=0,n=0;for(let r=0,i=e.length;r<i;r++)t=e.charCodeAt(r),t<128?n+=1:t<2048?n+=2:t<55296||t>=57344?n+=3:(r++,n+=4);return n}function We(){return Date.now().toString(36).substring(3)+Math.random().toString(36).substring(2,5)}function Ge(e){let t=``;for(let n in e)e.hasOwnProperty(n)&&(t.length&&(t+=`&`),t+=encodeURIComponent(n)+`=`+encodeURIComponent(e[n]));return t}function Ke(e){let t={},n=e.split(`&`);for(let e=0,r=n.length;e<r;e++){let r=n[e].split(`=`);t[decodeURIComponent(r[0])]=decodeURIComponent(r[1])}return t}var S=class extends Error{constructor(e,t,n){super(e),this.description=t,this.context=n,this.type=`TransportError`}},C=class extends b{constructor(e){super(),this.writable=!1,Be(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 S(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){let t=Ce(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(){let 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){let t=Ge(e);return t.length?`?`+t:``}},w=class extends C{constructor(){super(...arguments),this._polling=!1}get name(){return`polling`}doOpen(){this._poll()}pause(e){this.readyState=`pausing`;let t=()=>{this.readyState=`paused`,e()};if(this._polling||!this.writable){let e=0;this._polling&&(e++,this.once(`pollComplete`,function(){--e||t()})),this.writable||(e++,this.once(`drain`,function(){--e||t()}))}else t()}_poll(){this._polling=!0,this.doPoll(),this.emitReserved(`poll`)}onData(e){Oe(e,this.socket.binaryType).forEach(e=>{if(this.readyState===`opening`&&e.type===`open`&&this.onOpen(),e.type===`close`)return this.onClose({description:`transport closed by the server`}),!1;this.onPacket(e)}),this.readyState!==`closed`&&(this._polling=!1,this.emitReserved(`pollComplete`),this.readyState===`open`&&this._poll())}doClose(){let e=()=>{this.write([{type:`close`}])};this.readyState===`open`?e():this.once(`open`,e)}write(e){this.writable=!1,De(e,e=>{this.doWrite(e,()=>{this.writable=!0,this.emitReserved(`drain`)})})}uri(){let e=this.opts.secure?`https`:`http`,t=this.query||{};return!1!==this.opts.timestampRequests&&(t[this.opts.timestampParam]=We()),!this.supportsBinary&&!t.sid&&(t.b64=1),this.createUri(e,t)}},qe=!1;try{qe=typeof XMLHttpRequest<`u`&&`withCredentials`in new XMLHttpRequest}catch{}var Je=qe;function Ye(){}var Xe=class extends w{constructor(e){if(super(e),typeof location<`u`){let t=location.protocol===`https:`,n=location.port;n||=t?`443`:`80`,this.xd=typeof location<`u`&&e.hostname!==location.hostname||n!==e.port}}doWrite(e,t){let n=this.request({method:`POST`,data:e});n.on(`success`,t),n.on(`error`,(e,t)=>{this.onError(`xhr post error`,e,t)})}doPoll(){let e=this.request();e.on(`data`,this.onData.bind(this)),e.on(`error`,(e,t)=>{this.onError(`xhr poll error`,e,t)}),this.pollXhr=e}},Ze=class e extends b{constructor(e,t,n){super(),this.createRequest=e,Be(this,n),this._opts=n,this._method=n.method||`GET`,this._uri=t,this._data=n.data===void 0?null:n.data,this._create()}_create(){var t;let n=Le(this._opts,`agent`,`pfx`,`key`,`passphrase`,`cert`,`ca`,`ciphers`,`rejectUnauthorized`,`autoUnref`);n.xdomain=!!this._opts.xd;let r=this._xhr=this.createRequest(n);try{r.open(this._method,this._uri,!0);try{if(this._opts.extraHeaders){r.setDisableHeaderCheck&&r.setDisableHeaderCheck(!0);for(let e in this._opts.extraHeaders)this._opts.extraHeaders.hasOwnProperty(e)&&r.setRequestHeader(e,this._opts.extraHeaders[e])}}catch{}if(this._method===`POST`)try{r.setRequestHeader(`Content-type`,`text/plain;charset=UTF-8`)}catch{}try{r.setRequestHeader(`Accept`,`*/*`)}catch{}(t=this._opts.cookieJar)==null||t.addCookies(r),`withCredentials`in r&&(r.withCredentials=this._opts.withCredentials),this._opts.requestTimeout&&(r.timeout=this._opts.requestTimeout),r.onreadystatechange=()=>{var e;r.readyState===3&&((e=this._opts.cookieJar)==null||e.parseCookies(r.getResponseHeader(`set-cookie`))),r.readyState===4&&(r.status===200||r.status===1223?this._onLoad():this.setTimeoutFn(()=>{this._onError(typeof r.status==`number`?r.status:0)},0))},r.send(this._data)}catch(e){this.setTimeoutFn(()=>{this._onError(e)},0);return}typeof document<`u`&&(this._index=e.requestsCount++,e.requests[this._index]=this)}_onError(e){this.emitReserved(`error`,e,this._xhr),this._cleanup(!0)}_cleanup(t){if(!(this._xhr===void 0||this._xhr===null)){if(this._xhr.onreadystatechange=Ye,t)try{this._xhr.abort()}catch{}typeof document<`u`&&delete e.requests[this._index],this._xhr=null}}_onLoad(){let e=this._xhr.responseText;e!==null&&(this.emitReserved(`data`,e),this.emitReserved(`success`),this._cleanup())}abort(){this._cleanup()}};if(Ze.requestsCount=0,Ze.requests={},typeof document<`u`){if(typeof attachEvent==`function`)attachEvent(`onunload`,Qe);else if(typeof addEventListener==`function`){let e=`onpagehide`in x?`pagehide`:`unload`;addEventListener(e,Qe,!1)}}function Qe(){for(let e in Ze.requests)Ze.requests.hasOwnProperty(e)&&Ze.requests[e].abort()}var $e=(function(){let e=tt({xdomain:!1});return e&&e.responseType!==null})(),et=class extends Xe{constructor(e){super(e);let t=e&&e.forceBase64;this.supportsBinary=$e&&!t}request(e={}){return Object.assign(e,{xd:this.xd},this.opts),new Ze(tt,this.uri(),e)}};function tt(e){let t=e.xdomain;try{if(typeof XMLHttpRequest<`u`&&(!t||Je))return new XMLHttpRequest}catch{}if(!t)try{return new x[[`Active`,`Object`].join(`X`)](`Microsoft.XMLHTTP`)}catch{}}var nt=typeof navigator<`u`&&typeof navigator.product==`string`&&navigator.product.toLowerCase()===`reactnative`,rt=class extends C{get name(){return`websocket`}doOpen(){let e=this.uri(),t=this.opts.protocols,n=nt?{}:Le(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(e){return this.emitReserved(`error`,e)}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++){let n=e[t],r=t===e.length-1;me(n,this.supportsBinary,e=>{try{this.doWrite(n,e)}catch{}r&&Fe(()=>{this.writable=!0,this.emitReserved(`drain`)},this.setTimeoutFn)})}}doClose(){this.ws!==void 0&&(this.ws.onerror=()=>{},this.ws.close(),this.ws=null)}uri(){let e=this.opts.secure?`wss`:`ws`,t=this.query||{};return this.opts.timestampRequests&&(t[this.opts.timestampParam]=We()),this.supportsBinary||(t.b64=1),this.createUri(e,t)}},it=x.WebSocket||x.MozWebSocket,at={websocket:class extends rt{createSocket(e,t,n){return nt?new it(e,t,n):t?new it(e,t):new it(e)}doWrite(e,t){this.ws.send(t)}},webtransport:class extends C{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=>{let t=Ne(2**53-1,this.socket.binaryType),n=e.readable.pipeThrough(t).getReader(),r=ke();r.readable.pipeTo(e.writable),this._writer=r.writable.getWriter();let i=()=>{n.read().then(({done:e,value:t})=>{e||(this.onPacket(t),i())}).catch(e=>{})};i();let a={type:`open`};this.query.sid&&(a.data=`{"sid":"${this.query.sid}"}`),this._writer.write(a).then(()=>this.onOpen())})})}write(e){this.writable=!1;for(let t=0;t<e.length;t++){let n=e[t],r=t===e.length-1;this._writer.write(n).then(()=>{r&&Fe(()=>{this.writable=!0,this.emitReserved(`drain`)},this.setTimeoutFn)})}}doClose(){var e;(e=this._transport)==null||e.close()}},polling:et},ot=/^(?:(?![^:@\/?#]+:[^:@\/]*@)(http|https|ws|wss):\/\/)?((?:(([^:@\/?#]*)(?::([^:@\/?#]*))?)?@)?((?:[a-f0-9]{0,4}:){2,7}[a-f0-9]{0,4}|[^:\/?#]*)(?::(\d*))?)(((\/(?:[^?#](?![^?#\/]*\.[^?#\/.]+(?:[?#]|$)))*\/?)?([^?#\/]*))(?:\?([^#]*))?(?:#(.*))?)/,st=[`source`,`protocol`,`authority`,`userInfo`,`user`,`password`,`host`,`port`,`relative`,`path`,`directory`,`file`,`query`,`anchor`];function ct(e){if(e.length>8e3)throw`URI too long`;let t=e,n=e.indexOf(`[`),r=e.indexOf(`]`);n!=-1&&r!=-1&&(e=e.substring(0,n)+e.substring(n,r).replace(/:/g,`;`)+e.substring(r,e.length));let i=ot.exec(e||``),a={},o=14;for(;o--;)a[st[o]]=i[o]||``;return n!=-1&&r!=-1&&(a.source=t,a.host=a.host.substring(1,a.host.length-1).replace(/;/g,`:`),a.authority=a.authority.replace(`[`,``).replace(`]`,``).replace(/;/g,`:`),a.ipv6uri=!0),a.pathNames=lt(a,a.path),a.queryKey=ut(a,a.query),a}function lt(e,t){let n=t.replace(/\/{2,9}/g,`/`).split(`/`);return(t.slice(0,1)==`/`||t.length===0)&&n.splice(0,1),t.slice(-1)==`/`&&n.splice(n.length-1,1),n}function ut(e,t){let n={};return t.replace(/(?:^|&)([^&=]*)=?([^&]*)/g,function(e,t,r){t&&(n[t]=r)}),n}var dt=typeof addEventListener==`function`&&typeof removeEventListener==`function`,ft=[];dt&&addEventListener(`offline`,()=>{ft.forEach(e=>e())},!1);var pt=class e extends b{constructor(e,t){if(super(),this.binaryType=Ie,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){let n=ct(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=ct(t.host).host);Be(this,t),this.secure=t.secure==null?typeof location<`u`&&location.protocol===`https:`:t.secure,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(e=>{let t=e.prototype.name;this.transports.push(t),this._transportsByName[t]=e}),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=Ke(this.opts.query)),dt&&(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`})},ft.push(this._offlineEventListener))),this.opts.withCredentials&&(this._cookieJar=void 0),this._open()}createTransport(e){let t=Object.assign({},this.opts.query);t.EIO=4,t.transport=e,this.id&&(t.sid=this.id);let 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}let t=this.opts.rememberUpgrade&&e.priorWebsocketSuccess&&this.transports.indexOf(`websocket`)!==-1?`websocket`:this.transports[0];this.readyState=`opening`;let n=this.createTransport(t);n.open(),this.setTransport(n)}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`,e=>this._onClose(`transport close`,e))}onOpen(){this.readyState=`open`,e.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`:let t=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);let 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){let 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 e=1;for(let t=0;t<this.writeBuffer.length;t++){let n=this.writeBuffer[t].data;if(n&&(e+=He(n)),t>0&&e>this._maxPayload)return this.writeBuffer.slice(0,t);e+=2}return this.writeBuffer}_hasPingExpired(){if(!this._pingTimeoutTime)return!0;let e=Date.now()>this._pingTimeoutTime;return e&&(this._pingTimeoutTime=0,Fe(()=>{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.compress=!1!==n.compress;let i={type:e,data:t,options:n};this.emitReserved(`packetCreate`,i),this.writeBuffer.push(i),r&&this.once(`flush`,r),this.flush()}close(){let 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(t){if(e.priorWebsocketSuccess=!1,this.opts.tryAllTransports&&this.transports.length>1&&this.readyState===`opening`)return this.transports.shift(),this._open();this.emitReserved(`error`,t),this._onClose(`transport error`,t)}_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(),dt&&(this._beforeunloadEventListener&&removeEventListener(`beforeunload`,this._beforeunloadEventListener,!1),this._offlineEventListener)){let e=ft.indexOf(this._offlineEventListener);e!==-1&&ft.splice(e,1)}this.readyState=`closed`,this.id=null,this.emitReserved(`close`,e,t),this.writeBuffer=[],this._prevBufferLen=0}}};pt.protocol=4;var mt=class extends pt{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;pt.priorWebsocketSuccess=!1;let r=()=>{n||(t.send([{type:`ping`,data:`probe`}]),t.once(`packet`,e=>{if(!n)if(e.type===`pong`&&e.data===`probe`){if(this.upgrading=!0,this.emitReserved(`upgrading`,t),!t)return;pt.priorWebsocketSuccess=t.name===`websocket`,this.transport.pause(()=>{n||this.readyState!==`closed`&&(l(),this.setTransport(t),t.send([{type:`upgrade`}]),this.emitReserved(`upgrade`,t),t=null,this.upgrading=!1,this.flush())})}else{let e=Error(`probe error`);e.transport=t.name,this.emitReserved(`upgradeError`,e)}}))};function i(){n||(n=!0,l(),t.close(),t=null)}let a=e=>{let n=Error(`probe error: `+e);n.transport=t.name,i(),this.emitReserved(`upgradeError`,n)};function o(){a(`transport closed`)}function s(){a(`socket closed`)}function c(e){t&&e.name!==t.name&&i()}let l=()=>{t.removeListener(`open`,r),t.removeListener(`error`,a),t.removeListener(`close`,o),this.off(`close`,s),this.off(`upgrading`,c)};t.once(`open`,r),t.once(`error`,a),t.once(`close`,o),this.once(`close`,s),this.once(`upgrading`,c),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){let t=[];for(let n=0;n<e.length;n++)~this.transports.indexOf(e[n])&&t.push(e[n]);return t}},ht=class extends mt{constructor(e,t={}){let n=typeof e==`object`?e:t;(!n.transports||n.transports&&typeof n.transports[0]==`string`)&&(n.transports=(n.transports||[`polling`,`websocket`,`webtransport`]).map(e=>at[e]).filter(e=>!!e)),super(e,n)}};ht.protocol;function gt(e,t=``,n){let r=e;n||=typeof location<`u`&&location,e??=n.protocol+`//`+n.host,typeof e==`string`&&(e.charAt(0)===`/`&&(e=e.charAt(1)===`/`?n.protocol+e:n.host+e),/^(https?|wss?):\/\//.test(e)||(e=n===void 0?`https://`+e:n.protocol+`//`+e),r=ct(e)),r.port||(/^(http|ws)$/.test(r.protocol)?r.port=`80`:/^(http|ws)s$/.test(r.protocol)&&(r.port=`443`)),r.path=r.path||`/`;let i=r.host.indexOf(`:`)===-1?r.host:`[`+r.host+`]`;return r.id=r.protocol+`://`+i+`:`+r.port+t,r.href=r.protocol+`://`+i+(n&&n.port===r.port?``:`:`+r.port),r}var _t=typeof ArrayBuffer==`function`,vt=e=>typeof ArrayBuffer.isView==`function`?ArrayBuffer.isView(e):e.buffer instanceof ArrayBuffer,yt=Object.prototype.toString,bt=typeof Blob==`function`||typeof Blob<`u`&&yt.call(Blob)===`[object BlobConstructor]`,xt=typeof File==`function`||typeof File<`u`&&yt.call(File)===`[object FileConstructor]`;function St(e){return _t&&(e instanceof ArrayBuffer||vt(e))||bt&&e instanceof Blob||xt&&e instanceof File}function Ct(e,t){if(!e||typeof e!=`object`)return!1;if(Array.isArray(e)){for(let t=0,n=e.length;t<n;t++)if(Ct(e[t]))return!0;return!1}if(St(e))return!0;if(e.toJSON&&typeof e.toJSON==`function`&&arguments.length===1)return Ct(e.toJSON(),!0);for(let t in e)if(Object.prototype.hasOwnProperty.call(e,t)&&Ct(e[t]))return!0;return!1}function wt(e){let t=[],n=e.data,r=e;return r.data=Tt(n,t),r.attachments=t.length,{packet:r,buffers:t}}function Tt(e,t){if(!e)return e;if(St(e)){let n={_placeholder:!0,num:t.length};return t.push(e),n}else if(Array.isArray(e)){let n=Array(e.length);for(let r=0;r<e.length;r++)n[r]=Tt(e[r],t);return n}else if(typeof e==`object`&&!(e instanceof Date)){let n={};for(let r in e)Object.prototype.hasOwnProperty.call(e,r)&&(n[r]=Tt(e[r],t));return n}return e}function Et(e,t){return e.data=Dt(e.data,t),delete e.attachments,e}function Dt(e,t){if(!e)return e;if(e&&e._placeholder===!0){if(typeof e.num==`number`&&e.num>=0&&e.num<t.length)return t[e.num];throw Error(`illegal attachments`)}else if(Array.isArray(e))for(let n=0;n<e.length;n++)e[n]=Dt(e[n],t);else if(typeof e==`object`)for(let n in e)Object.prototype.hasOwnProperty.call(e,n)&&(e[n]=Dt(e[n],t));return e}var Ot=o({Decoder:()=>jt,Encoder:()=>At,PacketType:()=>T,isPacketValid:()=>Rt,protocol:()=>5}),kt=[`connect`,`connect_error`,`disconnect`,`disconnecting`,`newListener`,`removeListener`],T;(function(e){e[e.CONNECT=0]=`CONNECT`,e[e.DISCONNECT=1]=`DISCONNECT`,e[e.EVENT=2]=`EVENT`,e[e.ACK=3]=`ACK`,e[e.CONNECT_ERROR=4]=`CONNECT_ERROR`,e[e.BINARY_EVENT=5]=`BINARY_EVENT`,e[e.BINARY_ACK=6]=`BINARY_ACK`})(T||={});var At=class{constructor(e){this.replacer=e}encode(e){return(e.type===T.EVENT||e.type===T.ACK)&&Ct(e)?this.encodeAsBinary({type:e.type===T.EVENT?T.BINARY_EVENT:T.BINARY_ACK,nsp:e.nsp,data:e.data,id:e.id}):[this.encodeAsString(e)]}encodeAsString(e){let t=``+e.type;return(e.type===T.BINARY_EVENT||e.type===T.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){let t=wt(e),n=this.encodeAsString(t.packet),r=t.buffers;return r.unshift(n),r}},jt=class e extends b{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 Error(`got plaintext data when reconstructing a packet`);t=this.decodeString(e);let n=t.type===T.BINARY_EVENT;n||t.type===T.BINARY_ACK?(t.type=n?T.EVENT:T.ACK,this.reconstructor=new Mt(t),t.attachments===0&&super.emitReserved(`decoded`,t)):super.emitReserved(`decoded`,t)}else if(St(e)||e.base64)if(this.reconstructor)t=this.reconstructor.takeBinaryData(e),t&&(this.reconstructor=null,super.emitReserved(`decoded`,t));else throw Error(`got binary data when not reconstructing a packet`);else throw Error(`Unknown type: `+e)}decodeString(t){let n=0,r={type:Number(t.charAt(0))};if(T[r.type]===void 0)throw Error(`unknown packet type `+r.type);if(r.type===T.BINARY_EVENT||r.type===T.BINARY_ACK){let e=n+1;for(;t.charAt(++n)!==`-`&&n!=t.length;);let i=t.substring(e,n);if(i!=Number(i)||t.charAt(n)!==`-`)throw Error(`Illegal attachments`);let a=Number(i);if(!Pt(a)||a<0)throw Error(`Illegal attachments`);if(a>this.opts.maxAttachments)throw Error(`too many attachments`);r.attachments=a}if(t.charAt(n+1)===`/`){let e=n+1;for(;++n&&!(t.charAt(n)===`,`||n===t.length););r.nsp=t.substring(e,n)}else r.nsp=`/`;let i=t.charAt(n+1);if(i!==``&&Number(i)==i){let e=n+1;for(;++n;){let e=t.charAt(n);if(e==null||Number(e)!=e){--n;break}if(n===t.length)break}r.id=Number(t.substring(e,n+1))}if(t.charAt(++n)){let i=this.tryParse(t.substr(n));if(e.isPayloadValid(r.type,i))r.data=i;else throw Error(`invalid payload`)}return r}tryParse(e){try{return JSON.parse(e,this.opts.reviver)}catch{return!1}}static isPayloadValid(e,t){switch(e){case T.CONNECT:return It(t);case T.DISCONNECT:return t===void 0;case T.CONNECT_ERROR:return typeof t==`string`||It(t);case T.EVENT:case T.BINARY_EVENT:return Array.isArray(t)&&(typeof t[0]==`number`||typeof t[0]==`string`&&kt.indexOf(t[0])===-1);case T.ACK:case T.BINARY_ACK:return Array.isArray(t)}}destroy(){this.reconstructor&&=(this.reconstructor.finishedReconstruction(),null)}},Mt=class{constructor(e){this.packet=e,this.buffers=[],this.reconPack=e}takeBinaryData(e){if(this.buffers.push(e),this.buffers.length===this.reconPack.attachments){let e=Et(this.reconPack,this.buffers);return this.finishedReconstruction(),e}return null}finishedReconstruction(){this.reconPack=null,this.buffers=[]}};function Nt(e){return typeof e==`string`}var Pt=Number.isInteger||function(e){return typeof e==`number`&&isFinite(e)&&Math.floor(e)===e};function Ft(e){return e===void 0||Pt(e)}function It(e){return Object.prototype.toString.call(e)===`[object Object]`}function Lt(e,t){switch(e){case T.CONNECT:return t===void 0||It(t);case T.DISCONNECT:return t===void 0;case T.EVENT:return Array.isArray(t)&&(typeof t[0]==`number`||typeof t[0]==`string`&&kt.indexOf(t[0])===-1);case T.ACK:return Array.isArray(t);case T.CONNECT_ERROR:return typeof t==`string`||It(t);default:return!1}}function Rt(e){return Nt(e.nsp)&&Ft(e.id)&&Lt(e.type,e.data)}function zt(e,t,n){return e.on(t,n),function(){e.off(t,n)}}var Bt=Object.freeze({connect:1,connect_error:1,disconnect:1,disconnecting:1,newListener:1,removeListener:1}),Vt=class extends b{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;let e=this.io;this.subs=[zt(e,`open`,this.onopen.bind(this)),zt(e,`packet`,this.onpacket.bind(this)),zt(e,`error`,this.onerror.bind(this)),zt(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){if(Bt.hasOwnProperty(e))throw 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;let n={type:T.EVENT,data:t};if(n.options={},n.options.compress=this.flags.compress!==!1,typeof t[t.length-1]==`function`){let e=this.ids++,r=t.pop();this._registerAckCallback(e,r),n.id=e}let r=this.io.engine?.transport?.writable,i=this.connected&&!this.io.engine?._hasPingExpired();return this.flags.volatile&&!r||(i?(this.notifyOutgoingListeners(n),this.packet(n)):this.sendBuffer.push(n)),this.flags={},this}_registerAckCallback(e,t){let n=this.flags.timeout??this._opts.ackTimeout;if(n===void 0){this.acks[e]=t;return}let r=this.io.setTimeoutFn(()=>{delete this.acks[e];for(let t=0;t<this.sendBuffer.length;t++)this.sendBuffer[t].id===e&&this.sendBuffer.splice(t,1);t.call(this,Error(`operation has timed out`))},n),i=(...e)=>{this.io.clearTimeoutFn(r),t.apply(this,e)};i.withError=!0,this.acks[e]=i}emitWithAck(e,...t){return new Promise((n,r)=>{let i=(e,t)=>e?r(e):n(t);i.withError=!0,t.push(i),this.emit(e,...t)})}_addToQueue(e){let t;typeof e[e.length-1]==`function`&&(t=e.pop());let n={id:this._queueSeq++,tryCount:0,pending:!1,args:e,flags:Object.assign({fromQueue:!0},this.flags)};e.push((e,...r)=>(this._queue[0],e===null?(this._queue.shift(),t&&t(null,...r)):n.tryCount>this._opts.retries&&(this._queue.shift(),t&&t(e)),n.pending=!1,this._drainQueue())),this._queue.push(n),this._drainQueue()}_drainQueue(e=!1){if(!this.connected||this._queue.length===0)return;let 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:T.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(t=>String(t.id)===e)){let t=this.acks[e];delete this.acks[e],t.withError&&t.call(this,Error(`socket has been disconnected`))}})}onpacket(e){if(e.nsp===this.nsp)switch(e.type){case T.CONNECT:e.data&&e.data.sid?this.onconnect(e.data.sid,e.data.pid):this.emitReserved(`connect_error`,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 T.EVENT:case T.BINARY_EVENT:this.onevent(e);break;case T.ACK:case T.BINARY_ACK:this.onack(e);break;case T.DISCONNECT:this.ondisconnect();break;case T.CONNECT_ERROR:this.destroy();let t=Error(e.data.message);t.data=e.data.data,this.emitReserved(`connect_error`,t);break}}onevent(e){let 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){let t=this._anyListeners.slice();for(let 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){let t=this,n=!1;return function(...r){n||(n=!0,t.packet({type:T.ACK,id:e,data:r}))}}onack(e){let 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()),void 0),this.io._destroy(this)}disconnect(){return this.connected&&this.packet({type:T.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){let 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){let 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){let t=this._anyOutgoingListeners.slice();for(let n of t)n.apply(this,e.data)}}};function Ht(e){e||={},this.ms=e.min||100,this.max=e.max||1e4,this.factor=e.factor||2,this.jitter=e.jitter>0&&e.jitter<=1?e.jitter:0,this.attempts=0}Ht.prototype.duration=function(){var e=this.ms*this.factor**+ this.attempts++;if(this.jitter){var t=Math.random(),n=Math.floor(t*this.jitter*e);e=Math.floor(t*10)&1?e+n:e-n}return Math.min(e,this.max)|0},Ht.prototype.reset=function(){this.attempts=0},Ht.prototype.setMin=function(e){this.ms=e},Ht.prototype.setMax=function(e){this.max=e},Ht.prototype.setJitter=function(e){this.jitter=e};var Ut=class extends b{constructor(e,t){super(),this.nsps={},this.subs=[],e&&typeof e==`object`&&(t=e,e=void 0),t||={},t.path=t.path||`/socket.io`,this.opts=t,Be(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(t.randomizationFactor??.5),this.backoff=new Ht({min:this.reconnectionDelay(),max:this.reconnectionDelayMax(),jitter:this.randomizationFactor()}),this.timeout(t.timeout==null?2e4:t.timeout),this._readyState=`closed`,this.uri=e;let n=t.parser||Ot;this.encoder=new n.Encoder,this.decoder=new n.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.setMin(e),this)}randomizationFactor(e){var t;return e===void 0?this._randomizationFactor:(this._randomizationFactor=e,(t=this.backoff)==null||t.setJitter(e),this)}reconnectionDelayMax(e){var t;return e===void 0?this._reconnectionDelayMax:(this._reconnectionDelayMax=e,(t=this.backoff)==null||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 ht(this.uri,this.opts);let t=this.engine,n=this;this._readyState=`opening`,this.skipReconnect=!1;let r=zt(t,`open`,function(){n.onopen(),e&&e()}),i=t=>{this.cleanup(),this._readyState=`closed`,this.emitReserved(`error`,t),e?e(t):this.maybeReconnectOnOpen()},a=zt(t,`error`,i);if(!1!==this._timeout){let e=this._timeout,n=this.setTimeoutFn(()=>{r(),i(Error(`timeout`)),t.close()},e);this.opts.autoUnref&&n.unref(),this.subs.push(()=>{this.clearTimeoutFn(n)})}return this.subs.push(r),this.subs.push(a),this}connect(e){return this.open(e)}onopen(){this.cleanup(),this._readyState=`open`,this.emitReserved(`open`);let e=this.engine;this.subs.push(zt(e,`ping`,this.onping.bind(this)),zt(e,`data`,this.ondata.bind(this)),zt(e,`error`,this.onerror.bind(this)),zt(e,`close`,this.onclose.bind(this)),zt(this.decoder,`decoded`,this.ondecoded.bind(this)))}onping(){this.emitReserved(`ping`)}ondata(e){try{this.decoder.add(e)}catch(e){this.onclose(`parse error`,e)}}ondecoded(e){Fe(()=>{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 Vt(this,e,t),this.nsps[e]=n),n}_destroy(e){let t=Object.keys(this.nsps);for(let e of t)if(this.nsps[e].active)return;this._close()}_packet(e){let 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.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;let e=this;if(this.backoff.attempts>=this._reconnectionAttempts)this.backoff.reset(),this.emitReserved(`reconnect_failed`),this._reconnecting=!1;else{let t=this.backoff.duration();this._reconnecting=!0;let n=this.setTimeoutFn(()=>{e.skipReconnect||(this.emitReserved(`reconnect_attempt`,e.backoff.attempts),!e.skipReconnect&&e.open(t=>{t?(e._reconnecting=!1,e.reconnect(),this.emitReserved(`reconnect_error`,t)):e.onreconnect()}))},t);this.opts.autoUnref&&n.unref(),this.subs.push(()=>{this.clearTimeoutFn(n)})}}onreconnect(){let e=this.backoff.attempts;this._reconnecting=!1,this.backoff.reset(),this.emitReserved(`reconnect`,e)}},Wt={};function Gt(e,t){typeof e==`object`&&(t=e,e=void 0),t||={};let n=gt(e,t.path||`/socket.io`),r=n.source,i=n.id,a=n.path,o=Wt[i]&&a in Wt[i].nsps,s=t.forceNew||t[`force new connection`]||!1===t.multiplex||o,c;return s?c=new Ut(r,t):(Wt[i]||(Wt[i]=new Ut(r,t)),c=Wt[i]),n.query&&!t.query&&(t.query=n.queryKey),c.socket(n.path,t)}Object.assign(Gt,{Manager:Ut,Socket:Vt,io:Gt,connect:Gt});var Kt=({apiBaseUrl:e,userId:t,chatId:n,siteId:r})=>Gt(e,{transports:[`polling`,`websocket`],upgrade:!0,rememberUpgrade:!1,auth:{userId:t,chatId:n,siteId:r},query:{chatId:n,siteId:r}}),qt=({socket:e,chatId:t})=>{if(!e||!t||typeof window>`u`)return()=>{};let n=window.location.pathname+window.location.search,r=Date.now(),i=()=>{console.log(`[FlowEngageTracking] visitor:session_start`,{chatId:t,path:n}),e.emit(`visitor:session_start`,{chatId:t,path:n,title:document.title,referrer:document.referrer,userAgent:navigator.userAgent,timestamp:Date.now()})},a=()=>{console.log(`[FlowEngageTracking] visitor:page_enter`,{chatId:t,path:n}),e.emit(`visitor:page_enter`,{chatId:t,path:n,title:document.title,timestamp:Date.now()})},o=(n,r)=>{console.log(`[FlowEngageTracking] visitor:page_leave`,{chatId:t,path:n,duration:Math.max(0,Math.floor((Date.now()-r)/1e3))}),e.emit(`visitor:page_leave`,{chatId:t,path:n,duration:Math.max(0,Math.floor((Date.now()-r)/1e3)),timestamp:Date.now()})},s=()=>{console.log(`[FlowEngageTracking] visitor:heartbeat`,{chatId:t,path:n}),e.emit(`visitor:heartbeat`,{chatId:t,timestamp:Date.now()})},c=()=>{let e=window.location.pathname+window.location.search;if(e===n){console.log(`[FlowEngageTracking] route unchanged`,{currentPath:n});return}console.log(`[FlowEngageTracking] route changed`,{from:n,to:e}),o(n,r),n=e,r=Date.now(),a()},l=window.history.pushState.bind(window.history),u=window.history.replaceState.bind(window.history);window.history.pushState=(...e)=>{l(...e),c()},window.history.replaceState=(...e)=>{u(...e),c()};let d=window.setInterval(s,p),f=()=>{o(n,r),e.emit(`visitor:session_end`,{chatId:t,timestamp:Date.now()})};return window.addEventListener(`popstate`,c),window.addEventListener(`hashchange`,c),window.addEventListener(`beforeunload`,f),i(),s(),{notifyRouteChange:c,cleanup:()=>{window.clearInterval(d),window.history.pushState=l,window.history.replaceState=u,window.removeEventListener(`popstate`,c),window.removeEventListener(`hashchange`,c),window.removeEventListener(`beforeunload`,f)}}},Jt=(0,l.createContext)(null),Yt=()=>{let e=(0,l.useContext)(Jt);if(!e)throw Error(`useFlowEngage must be used inside FlowEngageProvider`);return e};function Xt(){if(typeof window>`u`)return!1;try{let e=window.localStorage?.getItem(`FE_DEBUG_VOICE`);if(e===`0`||e===`false`)return!1;if(e===`1`||e===`true`)return!0}catch{}return window.__FE_DEBUG_VOICE_TOOLS__===!1?!1:window.__FE_DEBUG_VOICE_TOOLS__===!0}function Zt(e){if(!e||typeof e.closest!=`function`)return!1;try{return!!e.closest(`#flowengage-root, .flowengage-shell`)}catch{return!1}}function Qt(...e){Xt()&&console.log(`[FlowEngage:shadowNavigate]`,...e)}var $t=`fe_pending_nav_section`,en=15e3;function tn(){if(typeof window>`u`||typeof document>`u`)return;let e;try{e=JSON.parse(sessionStorage.getItem($t)||`null`)}catch{return}if(!e)return;try{sessionStorage.removeItem($t)}catch{}let{sectionText:t,ts:n}=e;if(!t)return;if(Date.now()-n>en){Qt(`initNavigationHighlight: pending section expired, skipping:`,t);return}Qt(`initNavigationHighlight: replaying section highlight:`,t);let r=0,i=()=>{r+=1;let e=rn(null,t);if(e){gn(e),Qt(`initNavigationHighlight: highlighted on attempt`,r);return}r<8?setTimeout(i,300):Qt(`initNavigationHighlight: could not find element after 8 attempts:`,t)};setTimeout(i,250)}var nn=()=>{if(typeof document>`u`||document.getElementById(`fe-highlight-styles`))return;let e=document.createElement(`style`);e.id=`fe-highlight-styles`,e.textContent=`
|
|
1
|
+
Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`});var e=Object.create,t=Object.defineProperty,n=Object.getOwnPropertyDescriptor,r=Object.getOwnPropertyNames,i=Object.getPrototypeOf,a=Object.prototype.hasOwnProperty,o=(e,n)=>{let r={};for(var i in e)t(r,i,{get:e[i],enumerable:!0});return n||t(r,Symbol.toStringTag,{value:`Module`}),r},s=(e,i,o,s)=>{if(i&&typeof i==`object`||typeof i==`function`)for(var c=r(i),l=0,u=c.length,d;l<u;l++)d=c[l],!a.call(e,d)&&d!==o&&t(e,d,{get:(e=>i[e]).bind(null,d),enumerable:!(s=n(i,d))||s.enumerable});return e},c=(n,r,a)=>(a=n==null?{}:e(i(n)),s(r||!n||!n.__esModule?t(a,`default`,{value:n,enumerable:!0}):a,n));let l=require(`react`);l=c(l);let u=require(`react/jsx-runtime`);var d=e=>{if(!e||typeof e!=`object`)throw Error(`FlowEngage config is required`);if(!e.siteId||typeof e.siteId!=`string`)throw Error(`[FlowEngage] config.siteId is required. Pass it as <FlowEngageProvider siteId="your-site-id" /> or config={{ siteId: 'your-site-id' }}.`);let t=(e.apiBaseUrl||`https://be-flowengage.oslabs.app`).replace(/\/+$/,``);return{siteId:e.siteId.trim(),apiBaseUrl:t}},f={chatId:`flowengage.chatId`,isOpen:`flowengage.isOpen`,activeScreen:`flowengage.activeScreen`,isHumanHandled:`flowengage.isHumanHandled`,agentName:`flowengage.agentName`,agentHeadshot:`flowengage.agentHeadshot`,visitorEmail:`flowengage.visitorEmail`},p=1e4,m=6e4,ee=480*60,h=3e4,g=typeof window<`u`,te=e=>e?`flowengage.visitorEmail.${e}`:null,ne=()=>{if(!g)return`server-chat-id`;let e=window.localStorage.getItem(f.chatId);if(e)return e;let t=typeof crypto<`u`&&crypto.randomUUID?crypto.randomUUID():`${Date.now()}-${Math.random().toString(16).slice(2)}`;return window.localStorage.setItem(f.chatId,t),t},re=()=>g?{isOpen:!1,activeScreen:window.sessionStorage.getItem(f.activeScreen)||`ai`,isHumanHandled:window.sessionStorage.getItem(f.isHumanHandled)===`true`,agentName:window.sessionStorage.getItem(f.agentName),agentHeadshot:window.sessionStorage.getItem(f.agentHeadshot),visitorEmail:``}:{isOpen:!1,activeScreen:`ai`,isHumanHandled:!1,agentName:null,agentHeadshot:null,visitorEmail:``},ie=e=>{g&&Object.entries(e).forEach(([e,t])=>{let n=f[e];if(n){if(t==null||t===!1){window.sessionStorage.removeItem(n);return}window.sessionStorage.setItem(n,String(t))}})},ae=e=>{if(!g||!e)return``;let t=te(e),n=window.localStorage.getItem(t);if(!n){let e=window.sessionStorage.getItem(f.visitorEmail);e&&(window.localStorage.setItem(t,e),window.sessionStorage.removeItem(f.visitorEmail),n=e)}return n||``},oe=(e,t)=>{if(!g)return;let n=te(t);if(!n)return;let r=typeof e==`string`?e.trim():``;if(!r){window.localStorage.removeItem(n),window.sessionStorage.removeItem(f.visitorEmail);return}window.localStorage.setItem(n,r),window.sessionStorage.removeItem(f.visitorEmail)},_=async e=>{let t=await e.json().catch(()=>({}));if(!e.ok){let n=Error(t.message||t.error||`Request failed with status ${e.status}`);throw n.status=e.status,n}return t},v=async(e,t={})=>{try{return await fetch(e,{mode:`cors`,...t})}catch(t){let n=Error(`Network error reaching ${e}. Check: (1) backend is running, (2) CORS allows this origin, (3) siteId is correct. Original: ${t.message}`);throw n.status=0,n.cause=t,n}},se=async({apiBaseUrl:e,siteId:t})=>{let n=typeof window<`u`?window.location.origin:`http://localhost`,r=`${e}/api/widget/chatbot-loader?${new URLSearchParams({siteId:t,origin:n}).toString()}`;console.log(`[FlowEngageAPI] bootstrap request`,{apiBaseUrl:e,siteId:t,origin:n,url:r});let i=await _(await v(r,{method:`GET`}));return console.log(`[FlowEngageAPI] bootstrap success`,i),i.data},ce=({apiBaseUrl:e,userId:t,siteId:n})=>{let r=(t,n)=>{let r=`${e}${t}`,i=JSON.stringify(n);if(typeof navigator<`u`&&navigator.sendBeacon)try{let e=new Blob([i],{type:`application/json`});return navigator.sendBeacon(r,e)}catch{}return typeof fetch<`u`?(fetch(r,{method:`POST`,mode:`cors`,keepalive:!0,headers:{"Content-Type":`application/json`},body:i}).catch(()=>{}),!0):!1},i=async(r,i={})=>_(await v(`${e}${r}`,{...i,headers:{"Content-Type":`application/json`,"x-user-id":t,...n?{"x-site-id":n}:{},...i.headers||{}}}));return{async loadHistory(e,t=`en`,n=``){return i(`/api/ai/chat`,{method:`POST`,body:JSON.stringify({session_id:e,user_query:``,lang:t,category:n})})},async sendAiMessage(e,t,n=`en`,r=``,a=null){return i(`/api/ai/chat`,{method:`POST`,body:JSON.stringify({session_id:e,user_query:t,lang:n,category:r,...a||{}})})},async checkHumanHandled(e){return i(`/api/ai/check_human_handled`,{method:`POST`,body:JSON.stringify({session_id:e})})},async setChatMode(e,t){return i(`/api/ai/set_chat_mode`,{method:`POST`,body:JSON.stringify({session_id:e,mode:t})})},async toggleVoice(e){return i(`/api/ai/voice/toggle`,{method:`POST`,body:JSON.stringify({session_id:e})})},async syncVoice(e,r){return i(`/api/ai/voice/sync`,{method:`POST`,body:JSON.stringify({session_id:e,messages:r,...t?{userId:String(t)}:{},...n?{siteId:String(n)}:{}})})},async trackVisitor(e){return i(`/api/visitors/track`,{method:`POST`,body:JSON.stringify(e)})},async updateChatStatus(e,t){return i(`/api/chat/status`,{method:`POST`,body:JSON.stringify({chatId:e,type:t})})},async startConversation(e,t=`en`){return i(`/api/chat/status`,{method:`POST`,body:JSON.stringify({chatId:e,type:`open`,lang:t})})},async endConversation(e){return i(`/api/chat/status`,{method:`POST`,body:JSON.stringify({chatId:e,type:`closed`})})},async acceptCall(e,t){return i(`/api/calls/${e}/accept`,{method:`POST`,body:JSON.stringify({session_id:t,site_id:n})})},async rejectCall(e,t){return i(`/api/calls/${e}/reject`,{method:`POST`,body:JSON.stringify({session_id:t,site_id:n})})},async endWebRTCCall(e,t){return i(`/api/calls/${e}/end`,{method:`POST`,body:JSON.stringify({session_id:t,site_id:n,endedBy:`customer`})})},async markCustomerUnavailable(e,t){return i(`/api/calls/${e}/customer-unavailable`,{method:`POST`,body:JSON.stringify({session_id:t,site_id:n})})},beaconEndWebRTCCall(e,t){return r(`/api/calls/${e}/end`,{session_id:t,site_id:n,endedBy:`customer`})},beaconCustomerUnavailable(e,t){return r(`/api/calls/${e}/customer-unavailable`,{session_id:t,site_id:n})},beaconSyncVoice(r,i){if(typeof navigator>`u`||!navigator.sendBeacon)return!1;let a={session_id:r,messages:i,...t?{userId:String(t)}:{},...n?{siteId:String(n)}:{}},o=new Blob([JSON.stringify(a)],{type:`application/json`});return navigator.sendBeacon(`${e}/api/ai/voice/sync`,o)}}},le=Object.create(null);le.open=`0`,le.close=`1`,le.ping=`2`,le.pong=`3`,le.message=`4`,le.upgrade=`5`,le.noop=`6`;var y=Object.create(null);Object.keys(le).forEach(e=>{y[le[e]]=e});var ue={type:`error`,data:`parser error`},de=typeof Blob==`function`||typeof Blob<`u`&&Object.prototype.toString.call(Blob)===`[object BlobConstructor]`,fe=typeof ArrayBuffer==`function`,pe=e=>typeof ArrayBuffer.isView==`function`?ArrayBuffer.isView(e):e&&e.buffer instanceof ArrayBuffer,me=({type:e,data:t},n,r)=>de&&t instanceof Blob?n?r(t):he(t,r):fe&&(t instanceof ArrayBuffer||pe(t))?n?r(t):he(new Blob([t]),r):r(le[e]+(t||``)),he=(e,t)=>{let n=new FileReader;return n.onload=function(){let e=n.result.split(`,`)[1];t(`b`+(e||``))},n.readAsDataURL(e)};function ge(e){return e instanceof Uint8Array?e:e instanceof ArrayBuffer?new Uint8Array(e):new Uint8Array(e.buffer,e.byteOffset,e.byteLength)}var _e;function ve(e,t){if(de&&e.data instanceof Blob)return e.data.arrayBuffer().then(ge).then(t);if(fe&&(e.data instanceof ArrayBuffer||pe(e.data)))return t(ge(e.data));me(e,!1,e=>{_e||=new TextEncoder,t(_e.encode(e))})}var ye=`ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/`,be=typeof Uint8Array>`u`?[]:new Uint8Array(256);for(let e=0;e<64;e++)be[ye.charCodeAt(e)]=e;var xe=e=>{let t=e.length*.75,n=e.length,r,i=0,a,o,s,c;e[e.length-1]===`=`&&(t--,e[e.length-2]===`=`&&t--);let l=new ArrayBuffer(t),u=new Uint8Array(l);for(r=0;r<n;r+=4)a=be[e.charCodeAt(r)],o=be[e.charCodeAt(r+1)],s=be[e.charCodeAt(r+2)],c=be[e.charCodeAt(r+3)],u[i++]=a<<2|o>>4,u[i++]=(o&15)<<4|s>>2,u[i++]=(s&3)<<6|c&63;return l},Se=typeof ArrayBuffer==`function`,Ce=(e,t)=>{if(typeof e!=`string`)return{type:`message`,data:Te(e,t)};let n=e.charAt(0);return n===`b`?{type:`message`,data:we(e.substring(1),t)}:y[n]?e.length>1?{type:y[n],data:e.substring(1)}:{type:y[n]}:ue},we=(e,t)=>Se?Te(xe(e),t):{base64:!0,data:e},Te=(e,t)=>{switch(t){case`blob`:return e instanceof Blob?e:new Blob([e]);default:return e instanceof ArrayBuffer?e:e.buffer}},Ee=``,De=(e,t)=>{let n=e.length,r=Array(n),i=0;e.forEach((e,a)=>{me(e,!1,e=>{r[a]=e,++i===n&&t(r.join(Ee))})})},Oe=(e,t)=>{let n=e.split(Ee),r=[];for(let e=0;e<n.length;e++){let i=Ce(n[e],t);if(r.push(i),i.type===`error`)break}return r};function ke(){return new TransformStream({transform(e,t){ve(e,n=>{let r=n.length,i;if(r<126)i=new Uint8Array(1),new DataView(i.buffer).setUint8(0,r);else if(r<65536){i=new Uint8Array(3);let e=new DataView(i.buffer);e.setUint8(0,126),e.setUint16(1,r)}else{i=new Uint8Array(9);let e=new DataView(i.buffer);e.setUint8(0,127),e.setBigUint64(1,BigInt(r))}e.data&&typeof e.data!=`string`&&(i[0]|=128),t.enqueue(i),t.enqueue(n)})}})}var Ae;function je(e){return e.reduce((e,t)=>e+t.length,0)}function Me(e,t){if(e[0].length===t)return e.shift();let n=new Uint8Array(t),r=0;for(let i=0;i<t;i++)n[i]=e[0][r++],r===e[0].length&&(e.shift(),r=0);return e.length&&r<e[0].length&&(e[0]=e[0].slice(r)),n}function Ne(e,t){Ae||=new TextDecoder;let n=[],r=0,i=-1,a=!1;return new TransformStream({transform(o,s){for(n.push(o);;){if(r===0){if(je(n)<1)break;let e=Me(n,1);a=(e[0]&128)==128,i=e[0]&127,r=i<126?3:i===126?1:2}else if(r===1){if(je(n)<2)break;let e=Me(n,2);i=new DataView(e.buffer,e.byteOffset,e.length).getUint16(0),r=3}else if(r===2){if(je(n)<8)break;let e=Me(n,8),t=new DataView(e.buffer,e.byteOffset,e.length),a=t.getUint32(0);if(a>2**21-1){s.enqueue(ue);break}i=a*2**32+t.getUint32(4),r=3}else{if(je(n)<i)break;let e=Me(n,i);s.enqueue(Ce(a?e:Ae.decode(e),t)),r=0}if(i===0||i>e){s.enqueue(ue);break}}}})}function b(e){if(e)return Pe(e)}function Pe(e){for(var t in b.prototype)e[t]=b.prototype[t];return e}b.prototype.on=b.prototype.addEventListener=function(e,t){return this._callbacks=this._callbacks||{},(this._callbacks[`$`+e]=this._callbacks[`$`+e]||[]).push(t),this},b.prototype.once=function(e,t){function n(){this.off(e,n),t.apply(this,arguments)}return n.fn=t,this.on(e,n),this},b.prototype.off=b.prototype.removeListener=b.prototype.removeAllListeners=b.prototype.removeEventListener=function(e,t){if(this._callbacks=this._callbacks||{},arguments.length==0)return this._callbacks={},this;var n=this._callbacks[`$`+e];if(!n)return this;if(arguments.length==1)return delete this._callbacks[`$`+e],this;for(var r,i=0;i<n.length;i++)if(r=n[i],r===t||r.fn===t){n.splice(i,1);break}return n.length===0&&delete this._callbacks[`$`+e],this},b.prototype.emit=function(e){this._callbacks=this._callbacks||{};for(var t=Array(arguments.length-1),n=this._callbacks[`$`+e],r=1;r<arguments.length;r++)t[r-1]=arguments[r];if(n){n=n.slice(0);for(var r=0,i=n.length;r<i;++r)n[r].apply(this,t)}return this},b.prototype.emitReserved=b.prototype.emit,b.prototype.listeners=function(e){return this._callbacks=this._callbacks||{},this._callbacks[`$`+e]||[]},b.prototype.hasListeners=function(e){return!!this.listeners(e).length};var Fe=typeof Promise==`function`&&typeof Promise.resolve==`function`?e=>Promise.resolve().then(e):(e,t)=>t(e,0),Ie=typeof self<`u`?self:typeof window<`u`?window:Function(`return this`)(),x=`arraybuffer`;function S(e,...t){return t.reduce((t,n)=>(e.hasOwnProperty(n)&&(t[n]=e[n]),t),{})}var Le=Ie.setTimeout,Re=Ie.clearTimeout;function ze(e,t){t.useNativeTimers?(e.setTimeoutFn=Le.bind(Ie),e.clearTimeoutFn=Re.bind(Ie)):(e.setTimeoutFn=Ie.setTimeout.bind(Ie),e.clearTimeoutFn=Ie.clearTimeout.bind(Ie))}var Be=1.33;function Ve(e){return typeof e==`string`?He(e):Math.ceil((e.byteLength||e.size)*Be)}function He(e){let t=0,n=0;for(let r=0,i=e.length;r<i;r++)t=e.charCodeAt(r),t<128?n+=1:t<2048?n+=2:t<55296||t>=57344?n+=3:(r++,n+=4);return n}function Ue(){return Date.now().toString(36).substring(3)+Math.random().toString(36).substring(2,5)}function We(e){let t=``;for(let n in e)e.hasOwnProperty(n)&&(t.length&&(t+=`&`),t+=encodeURIComponent(n)+`=`+encodeURIComponent(e[n]));return t}function Ge(e){let t={},n=e.split(`&`);for(let e=0,r=n.length;e<r;e++){let r=n[e].split(`=`);t[decodeURIComponent(r[0])]=decodeURIComponent(r[1])}return t}var Ke=class extends Error{constructor(e,t,n){super(e),this.description=t,this.context=n,this.type=`TransportError`}},C=class extends b{constructor(e){super(),this.writable=!1,ze(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 Ke(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){let t=Ce(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(){let 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){let t=We(e);return t.length?`?`+t:``}},w=class extends C{constructor(){super(...arguments),this._polling=!1}get name(){return`polling`}doOpen(){this._poll()}pause(e){this.readyState=`pausing`;let t=()=>{this.readyState=`paused`,e()};if(this._polling||!this.writable){let e=0;this._polling&&(e++,this.once(`pollComplete`,function(){--e||t()})),this.writable||(e++,this.once(`drain`,function(){--e||t()}))}else t()}_poll(){this._polling=!0,this.doPoll(),this.emitReserved(`poll`)}onData(e){Oe(e,this.socket.binaryType).forEach(e=>{if(this.readyState===`opening`&&e.type===`open`&&this.onOpen(),e.type===`close`)return this.onClose({description:`transport closed by the server`}),!1;this.onPacket(e)}),this.readyState!==`closed`&&(this._polling=!1,this.emitReserved(`pollComplete`),this.readyState===`open`&&this._poll())}doClose(){let e=()=>{this.write([{type:`close`}])};this.readyState===`open`?e():this.once(`open`,e)}write(e){this.writable=!1,De(e,e=>{this.doWrite(e,()=>{this.writable=!0,this.emitReserved(`drain`)})})}uri(){let e=this.opts.secure?`https`:`http`,t=this.query||{};return!1!==this.opts.timestampRequests&&(t[this.opts.timestampParam]=Ue()),!this.supportsBinary&&!t.sid&&(t.b64=1),this.createUri(e,t)}},T=!1;try{T=typeof XMLHttpRequest<`u`&&`withCredentials`in new XMLHttpRequest}catch{}var qe=T;function Je(){}var Ye=class extends w{constructor(e){if(super(e),typeof location<`u`){let t=location.protocol===`https:`,n=location.port;n||=t?`443`:`80`,this.xd=typeof location<`u`&&e.hostname!==location.hostname||n!==e.port}}doWrite(e,t){let n=this.request({method:`POST`,data:e});n.on(`success`,t),n.on(`error`,(e,t)=>{this.onError(`xhr post error`,e,t)})}doPoll(){let e=this.request();e.on(`data`,this.onData.bind(this)),e.on(`error`,(e,t)=>{this.onError(`xhr poll error`,e,t)}),this.pollXhr=e}},Xe=class e extends b{constructor(e,t,n){super(),this.createRequest=e,ze(this,n),this._opts=n,this._method=n.method||`GET`,this._uri=t,this._data=n.data===void 0?null:n.data,this._create()}_create(){var t;let n=S(this._opts,`agent`,`pfx`,`key`,`passphrase`,`cert`,`ca`,`ciphers`,`rejectUnauthorized`,`autoUnref`);n.xdomain=!!this._opts.xd;let r=this._xhr=this.createRequest(n);try{r.open(this._method,this._uri,!0);try{if(this._opts.extraHeaders){r.setDisableHeaderCheck&&r.setDisableHeaderCheck(!0);for(let e in this._opts.extraHeaders)this._opts.extraHeaders.hasOwnProperty(e)&&r.setRequestHeader(e,this._opts.extraHeaders[e])}}catch{}if(this._method===`POST`)try{r.setRequestHeader(`Content-type`,`text/plain;charset=UTF-8`)}catch{}try{r.setRequestHeader(`Accept`,`*/*`)}catch{}(t=this._opts.cookieJar)==null||t.addCookies(r),`withCredentials`in r&&(r.withCredentials=this._opts.withCredentials),this._opts.requestTimeout&&(r.timeout=this._opts.requestTimeout),r.onreadystatechange=()=>{var e;r.readyState===3&&((e=this._opts.cookieJar)==null||e.parseCookies(r.getResponseHeader(`set-cookie`))),r.readyState===4&&(r.status===200||r.status===1223?this._onLoad():this.setTimeoutFn(()=>{this._onError(typeof r.status==`number`?r.status:0)},0))},r.send(this._data)}catch(e){this.setTimeoutFn(()=>{this._onError(e)},0);return}typeof document<`u`&&(this._index=e.requestsCount++,e.requests[this._index]=this)}_onError(e){this.emitReserved(`error`,e,this._xhr),this._cleanup(!0)}_cleanup(t){if(!(this._xhr===void 0||this._xhr===null)){if(this._xhr.onreadystatechange=Je,t)try{this._xhr.abort()}catch{}typeof document<`u`&&delete e.requests[this._index],this._xhr=null}}_onLoad(){let e=this._xhr.responseText;e!==null&&(this.emitReserved(`data`,e),this.emitReserved(`success`),this._cleanup())}abort(){this._cleanup()}};if(Xe.requestsCount=0,Xe.requests={},typeof document<`u`){if(typeof attachEvent==`function`)attachEvent(`onunload`,Ze);else if(typeof addEventListener==`function`){let e=`onpagehide`in Ie?`pagehide`:`unload`;addEventListener(e,Ze,!1)}}function Ze(){for(let e in Xe.requests)Xe.requests.hasOwnProperty(e)&&Xe.requests[e].abort()}var Qe=(function(){let e=et({xdomain:!1});return e&&e.responseType!==null})(),$e=class extends Ye{constructor(e){super(e);let t=e&&e.forceBase64;this.supportsBinary=Qe&&!t}request(e={}){return Object.assign(e,{xd:this.xd},this.opts),new Xe(et,this.uri(),e)}};function et(e){let t=e.xdomain;try{if(typeof XMLHttpRequest<`u`&&(!t||qe))return new XMLHttpRequest}catch{}if(!t)try{return new Ie[[`Active`,`Object`].join(`X`)](`Microsoft.XMLHTTP`)}catch{}}var tt=typeof navigator<`u`&&typeof navigator.product==`string`&&navigator.product.toLowerCase()===`reactnative`,nt=class extends C{get name(){return`websocket`}doOpen(){let e=this.uri(),t=this.opts.protocols,n=tt?{}:S(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(e){return this.emitReserved(`error`,e)}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++){let n=e[t],r=t===e.length-1;me(n,this.supportsBinary,e=>{try{this.doWrite(n,e)}catch{}r&&Fe(()=>{this.writable=!0,this.emitReserved(`drain`)},this.setTimeoutFn)})}}doClose(){this.ws!==void 0&&(this.ws.onerror=()=>{},this.ws.close(),this.ws=null)}uri(){let e=this.opts.secure?`wss`:`ws`,t=this.query||{};return this.opts.timestampRequests&&(t[this.opts.timestampParam]=Ue()),this.supportsBinary||(t.b64=1),this.createUri(e,t)}},rt=Ie.WebSocket||Ie.MozWebSocket,it={websocket:class extends nt{createSocket(e,t,n){return tt?new rt(e,t,n):t?new rt(e,t):new rt(e)}doWrite(e,t){this.ws.send(t)}},webtransport:class extends C{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=>{let t=Ne(2**53-1,this.socket.binaryType),n=e.readable.pipeThrough(t).getReader(),r=ke();r.readable.pipeTo(e.writable),this._writer=r.writable.getWriter();let i=()=>{n.read().then(({done:e,value:t})=>{e||(this.onPacket(t),i())}).catch(e=>{})};i();let a={type:`open`};this.query.sid&&(a.data=`{"sid":"${this.query.sid}"}`),this._writer.write(a).then(()=>this.onOpen())})})}write(e){this.writable=!1;for(let t=0;t<e.length;t++){let n=e[t],r=t===e.length-1;this._writer.write(n).then(()=>{r&&Fe(()=>{this.writable=!0,this.emitReserved(`drain`)},this.setTimeoutFn)})}}doClose(){var e;(e=this._transport)==null||e.close()}},polling:$e},at=/^(?:(?![^:@\/?#]+:[^:@\/]*@)(http|https|ws|wss):\/\/)?((?:(([^:@\/?#]*)(?::([^:@\/?#]*))?)?@)?((?:[a-f0-9]{0,4}:){2,7}[a-f0-9]{0,4}|[^:\/?#]*)(?::(\d*))?)(((\/(?:[^?#](?![^?#\/]*\.[^?#\/.]+(?:[?#]|$)))*\/?)?([^?#\/]*))(?:\?([^#]*))?(?:#(.*))?)/,ot=[`source`,`protocol`,`authority`,`userInfo`,`user`,`password`,`host`,`port`,`relative`,`path`,`directory`,`file`,`query`,`anchor`];function st(e){if(e.length>8e3)throw`URI too long`;let t=e,n=e.indexOf(`[`),r=e.indexOf(`]`);n!=-1&&r!=-1&&(e=e.substring(0,n)+e.substring(n,r).replace(/:/g,`;`)+e.substring(r,e.length));let i=at.exec(e||``),a={},o=14;for(;o--;)a[ot[o]]=i[o]||``;return n!=-1&&r!=-1&&(a.source=t,a.host=a.host.substring(1,a.host.length-1).replace(/;/g,`:`),a.authority=a.authority.replace(`[`,``).replace(`]`,``).replace(/;/g,`:`),a.ipv6uri=!0),a.pathNames=ct(a,a.path),a.queryKey=lt(a,a.query),a}function ct(e,t){let n=t.replace(/\/{2,9}/g,`/`).split(`/`);return(t.slice(0,1)==`/`||t.length===0)&&n.splice(0,1),t.slice(-1)==`/`&&n.splice(n.length-1,1),n}function lt(e,t){let n={};return t.replace(/(?:^|&)([^&=]*)=?([^&]*)/g,function(e,t,r){t&&(n[t]=r)}),n}var ut=typeof addEventListener==`function`&&typeof removeEventListener==`function`,dt=[];ut&&addEventListener(`offline`,()=>{dt.forEach(e=>e())},!1);var ft=class e extends b{constructor(e,t){if(super(),this.binaryType=x,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){let n=st(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=st(t.host).host);ze(this,t),this.secure=t.secure==null?typeof location<`u`&&location.protocol===`https:`:t.secure,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(e=>{let t=e.prototype.name;this.transports.push(t),this._transportsByName[t]=e}),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=Ge(this.opts.query)),ut&&(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`})},dt.push(this._offlineEventListener))),this.opts.withCredentials&&(this._cookieJar=void 0),this._open()}createTransport(e){let t=Object.assign({},this.opts.query);t.EIO=4,t.transport=e,this.id&&(t.sid=this.id);let 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}let t=this.opts.rememberUpgrade&&e.priorWebsocketSuccess&&this.transports.indexOf(`websocket`)!==-1?`websocket`:this.transports[0];this.readyState=`opening`;let n=this.createTransport(t);n.open(),this.setTransport(n)}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`,e=>this._onClose(`transport close`,e))}onOpen(){this.readyState=`open`,e.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`:let t=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);let 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){let 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 e=1;for(let t=0;t<this.writeBuffer.length;t++){let n=this.writeBuffer[t].data;if(n&&(e+=Ve(n)),t>0&&e>this._maxPayload)return this.writeBuffer.slice(0,t);e+=2}return this.writeBuffer}_hasPingExpired(){if(!this._pingTimeoutTime)return!0;let e=Date.now()>this._pingTimeoutTime;return e&&(this._pingTimeoutTime=0,Fe(()=>{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.compress=!1!==n.compress;let i={type:e,data:t,options:n};this.emitReserved(`packetCreate`,i),this.writeBuffer.push(i),r&&this.once(`flush`,r),this.flush()}close(){let 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(t){if(e.priorWebsocketSuccess=!1,this.opts.tryAllTransports&&this.transports.length>1&&this.readyState===`opening`)return this.transports.shift(),this._open();this.emitReserved(`error`,t),this._onClose(`transport error`,t)}_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(),ut&&(this._beforeunloadEventListener&&removeEventListener(`beforeunload`,this._beforeunloadEventListener,!1),this._offlineEventListener)){let e=dt.indexOf(this._offlineEventListener);e!==-1&&dt.splice(e,1)}this.readyState=`closed`,this.id=null,this.emitReserved(`close`,e,t),this.writeBuffer=[],this._prevBufferLen=0}}};ft.protocol=4;var pt=class extends ft{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;ft.priorWebsocketSuccess=!1;let r=()=>{n||(t.send([{type:`ping`,data:`probe`}]),t.once(`packet`,e=>{if(!n)if(e.type===`pong`&&e.data===`probe`){if(this.upgrading=!0,this.emitReserved(`upgrading`,t),!t)return;ft.priorWebsocketSuccess=t.name===`websocket`,this.transport.pause(()=>{n||this.readyState!==`closed`&&(l(),this.setTransport(t),t.send([{type:`upgrade`}]),this.emitReserved(`upgrade`,t),t=null,this.upgrading=!1,this.flush())})}else{let e=Error(`probe error`);e.transport=t.name,this.emitReserved(`upgradeError`,e)}}))};function i(){n||(n=!0,l(),t.close(),t=null)}let a=e=>{let n=Error(`probe error: `+e);n.transport=t.name,i(),this.emitReserved(`upgradeError`,n)};function o(){a(`transport closed`)}function s(){a(`socket closed`)}function c(e){t&&e.name!==t.name&&i()}let l=()=>{t.removeListener(`open`,r),t.removeListener(`error`,a),t.removeListener(`close`,o),this.off(`close`,s),this.off(`upgrading`,c)};t.once(`open`,r),t.once(`error`,a),t.once(`close`,o),this.once(`close`,s),this.once(`upgrading`,c),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){let t=[];for(let n=0;n<e.length;n++)~this.transports.indexOf(e[n])&&t.push(e[n]);return t}},mt=class extends pt{constructor(e,t={}){let n=typeof e==`object`?e:t;(!n.transports||n.transports&&typeof n.transports[0]==`string`)&&(n.transports=(n.transports||[`polling`,`websocket`,`webtransport`]).map(e=>it[e]).filter(e=>!!e)),super(e,n)}};mt.protocol;function ht(e,t=``,n){let r=e;n||=typeof location<`u`&&location,e??=n.protocol+`//`+n.host,typeof e==`string`&&(e.charAt(0)===`/`&&(e=e.charAt(1)===`/`?n.protocol+e:n.host+e),/^(https?|wss?):\/\//.test(e)||(e=n===void 0?`https://`+e:n.protocol+`//`+e),r=st(e)),r.port||(/^(http|ws)$/.test(r.protocol)?r.port=`80`:/^(http|ws)s$/.test(r.protocol)&&(r.port=`443`)),r.path=r.path||`/`;let i=r.host.indexOf(`:`)===-1?r.host:`[`+r.host+`]`;return r.id=r.protocol+`://`+i+`:`+r.port+t,r.href=r.protocol+`://`+i+(n&&n.port===r.port?``:`:`+r.port),r}var gt=typeof ArrayBuffer==`function`,_t=e=>typeof ArrayBuffer.isView==`function`?ArrayBuffer.isView(e):e.buffer instanceof ArrayBuffer,vt=Object.prototype.toString,yt=typeof Blob==`function`||typeof Blob<`u`&&vt.call(Blob)===`[object BlobConstructor]`,bt=typeof File==`function`||typeof File<`u`&&vt.call(File)===`[object FileConstructor]`;function xt(e){return gt&&(e instanceof ArrayBuffer||_t(e))||yt&&e instanceof Blob||bt&&e instanceof File}function St(e,t){if(!e||typeof e!=`object`)return!1;if(Array.isArray(e)){for(let t=0,n=e.length;t<n;t++)if(St(e[t]))return!0;return!1}if(xt(e))return!0;if(e.toJSON&&typeof e.toJSON==`function`&&arguments.length===1)return St(e.toJSON(),!0);for(let t in e)if(Object.prototype.hasOwnProperty.call(e,t)&&St(e[t]))return!0;return!1}function Ct(e){let t=[],n=e.data,r=e;return r.data=wt(n,t),r.attachments=t.length,{packet:r,buffers:t}}function wt(e,t){if(!e)return e;if(xt(e)){let n={_placeholder:!0,num:t.length};return t.push(e),n}else if(Array.isArray(e)){let n=Array(e.length);for(let r=0;r<e.length;r++)n[r]=wt(e[r],t);return n}else if(typeof e==`object`&&!(e instanceof Date)){let n={};for(let r in e)Object.prototype.hasOwnProperty.call(e,r)&&(n[r]=wt(e[r],t));return n}return e}function Tt(e,t){return e.data=Et(e.data,t),delete e.attachments,e}function Et(e,t){if(!e)return e;if(e&&e._placeholder===!0){if(typeof e.num==`number`&&e.num>=0&&e.num<t.length)return t[e.num];throw Error(`illegal attachments`)}else if(Array.isArray(e))for(let n=0;n<e.length;n++)e[n]=Et(e[n],t);else if(typeof e==`object`)for(let n in e)Object.prototype.hasOwnProperty.call(e,n)&&(e[n]=Et(e[n],t));return e}var Dt=o({Decoder:()=>At,Encoder:()=>kt,PacketType:()=>E,isPacketValid:()=>Lt,protocol:()=>5}),Ot=[`connect`,`connect_error`,`disconnect`,`disconnecting`,`newListener`,`removeListener`],E;(function(e){e[e.CONNECT=0]=`CONNECT`,e[e.DISCONNECT=1]=`DISCONNECT`,e[e.EVENT=2]=`EVENT`,e[e.ACK=3]=`ACK`,e[e.CONNECT_ERROR=4]=`CONNECT_ERROR`,e[e.BINARY_EVENT=5]=`BINARY_EVENT`,e[e.BINARY_ACK=6]=`BINARY_ACK`})(E||={});var kt=class{constructor(e){this.replacer=e}encode(e){return(e.type===E.EVENT||e.type===E.ACK)&&St(e)?this.encodeAsBinary({type:e.type===E.EVENT?E.BINARY_EVENT:E.BINARY_ACK,nsp:e.nsp,data:e.data,id:e.id}):[this.encodeAsString(e)]}encodeAsString(e){let t=``+e.type;return(e.type===E.BINARY_EVENT||e.type===E.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){let t=Ct(e),n=this.encodeAsString(t.packet),r=t.buffers;return r.unshift(n),r}},At=class e extends b{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 Error(`got plaintext data when reconstructing a packet`);t=this.decodeString(e);let n=t.type===E.BINARY_EVENT;n||t.type===E.BINARY_ACK?(t.type=n?E.EVENT:E.ACK,this.reconstructor=new jt(t),t.attachments===0&&super.emitReserved(`decoded`,t)):super.emitReserved(`decoded`,t)}else if(xt(e)||e.base64)if(this.reconstructor)t=this.reconstructor.takeBinaryData(e),t&&(this.reconstructor=null,super.emitReserved(`decoded`,t));else throw Error(`got binary data when not reconstructing a packet`);else throw Error(`Unknown type: `+e)}decodeString(t){let n=0,r={type:Number(t.charAt(0))};if(E[r.type]===void 0)throw Error(`unknown packet type `+r.type);if(r.type===E.BINARY_EVENT||r.type===E.BINARY_ACK){let e=n+1;for(;t.charAt(++n)!==`-`&&n!=t.length;);let i=t.substring(e,n);if(i!=Number(i)||t.charAt(n)!==`-`)throw Error(`Illegal attachments`);let a=Number(i);if(!Nt(a)||a<0)throw Error(`Illegal attachments`);if(a>this.opts.maxAttachments)throw Error(`too many attachments`);r.attachments=a}if(t.charAt(n+1)===`/`){let e=n+1;for(;++n&&!(t.charAt(n)===`,`||n===t.length););r.nsp=t.substring(e,n)}else r.nsp=`/`;let i=t.charAt(n+1);if(i!==``&&Number(i)==i){let e=n+1;for(;++n;){let e=t.charAt(n);if(e==null||Number(e)!=e){--n;break}if(n===t.length)break}r.id=Number(t.substring(e,n+1))}if(t.charAt(++n)){let i=this.tryParse(t.substr(n));if(e.isPayloadValid(r.type,i))r.data=i;else throw Error(`invalid payload`)}return r}tryParse(e){try{return JSON.parse(e,this.opts.reviver)}catch{return!1}}static isPayloadValid(e,t){switch(e){case E.CONNECT:return Ft(t);case E.DISCONNECT:return t===void 0;case E.CONNECT_ERROR:return typeof t==`string`||Ft(t);case E.EVENT:case E.BINARY_EVENT:return Array.isArray(t)&&(typeof t[0]==`number`||typeof t[0]==`string`&&Ot.indexOf(t[0])===-1);case E.ACK:case E.BINARY_ACK:return Array.isArray(t)}}destroy(){this.reconstructor&&=(this.reconstructor.finishedReconstruction(),null)}},jt=class{constructor(e){this.packet=e,this.buffers=[],this.reconPack=e}takeBinaryData(e){if(this.buffers.push(e),this.buffers.length===this.reconPack.attachments){let e=Tt(this.reconPack,this.buffers);return this.finishedReconstruction(),e}return null}finishedReconstruction(){this.reconPack=null,this.buffers=[]}};function Mt(e){return typeof e==`string`}var Nt=Number.isInteger||function(e){return typeof e==`number`&&isFinite(e)&&Math.floor(e)===e};function Pt(e){return e===void 0||Nt(e)}function Ft(e){return Object.prototype.toString.call(e)===`[object Object]`}function It(e,t){switch(e){case E.CONNECT:return t===void 0||Ft(t);case E.DISCONNECT:return t===void 0;case E.EVENT:return Array.isArray(t)&&(typeof t[0]==`number`||typeof t[0]==`string`&&Ot.indexOf(t[0])===-1);case E.ACK:return Array.isArray(t);case E.CONNECT_ERROR:return typeof t==`string`||Ft(t);default:return!1}}function Lt(e){return Mt(e.nsp)&&Pt(e.id)&&It(e.type,e.data)}function Rt(e,t,n){return e.on(t,n),function(){e.off(t,n)}}var zt=Object.freeze({connect:1,connect_error:1,disconnect:1,disconnecting:1,newListener:1,removeListener:1}),Bt=class extends b{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;let e=this.io;this.subs=[Rt(e,`open`,this.onopen.bind(this)),Rt(e,`packet`,this.onpacket.bind(this)),Rt(e,`error`,this.onerror.bind(this)),Rt(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){if(zt.hasOwnProperty(e))throw 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;let n={type:E.EVENT,data:t};if(n.options={},n.options.compress=this.flags.compress!==!1,typeof t[t.length-1]==`function`){let e=this.ids++,r=t.pop();this._registerAckCallback(e,r),n.id=e}let r=this.io.engine?.transport?.writable,i=this.connected&&!this.io.engine?._hasPingExpired();return this.flags.volatile&&!r||(i?(this.notifyOutgoingListeners(n),this.packet(n)):this.sendBuffer.push(n)),this.flags={},this}_registerAckCallback(e,t){let n=this.flags.timeout??this._opts.ackTimeout;if(n===void 0){this.acks[e]=t;return}let r=this.io.setTimeoutFn(()=>{delete this.acks[e];for(let t=0;t<this.sendBuffer.length;t++)this.sendBuffer[t].id===e&&this.sendBuffer.splice(t,1);t.call(this,Error(`operation has timed out`))},n),i=(...e)=>{this.io.clearTimeoutFn(r),t.apply(this,e)};i.withError=!0,this.acks[e]=i}emitWithAck(e,...t){return new Promise((n,r)=>{let i=(e,t)=>e?r(e):n(t);i.withError=!0,t.push(i),this.emit(e,...t)})}_addToQueue(e){let t;typeof e[e.length-1]==`function`&&(t=e.pop());let n={id:this._queueSeq++,tryCount:0,pending:!1,args:e,flags:Object.assign({fromQueue:!0},this.flags)};e.push((e,...r)=>(this._queue[0],e===null?(this._queue.shift(),t&&t(null,...r)):n.tryCount>this._opts.retries&&(this._queue.shift(),t&&t(e)),n.pending=!1,this._drainQueue())),this._queue.push(n),this._drainQueue()}_drainQueue(e=!1){if(!this.connected||this._queue.length===0)return;let 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:E.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(t=>String(t.id)===e)){let t=this.acks[e];delete this.acks[e],t.withError&&t.call(this,Error(`socket has been disconnected`))}})}onpacket(e){if(e.nsp===this.nsp)switch(e.type){case E.CONNECT:e.data&&e.data.sid?this.onconnect(e.data.sid,e.data.pid):this.emitReserved(`connect_error`,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 E.EVENT:case E.BINARY_EVENT:this.onevent(e);break;case E.ACK:case E.BINARY_ACK:this.onack(e);break;case E.DISCONNECT:this.ondisconnect();break;case E.CONNECT_ERROR:this.destroy();let t=Error(e.data.message);t.data=e.data.data,this.emitReserved(`connect_error`,t);break}}onevent(e){let 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){let t=this._anyListeners.slice();for(let 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){let t=this,n=!1;return function(...r){n||(n=!0,t.packet({type:E.ACK,id:e,data:r}))}}onack(e){let 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()),void 0),this.io._destroy(this)}disconnect(){return this.connected&&this.packet({type:E.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){let 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){let 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){let t=this._anyOutgoingListeners.slice();for(let n of t)n.apply(this,e.data)}}};function Vt(e){e||={},this.ms=e.min||100,this.max=e.max||1e4,this.factor=e.factor||2,this.jitter=e.jitter>0&&e.jitter<=1?e.jitter:0,this.attempts=0}Vt.prototype.duration=function(){var e=this.ms*this.factor**+ this.attempts++;if(this.jitter){var t=Math.random(),n=Math.floor(t*this.jitter*e);e=Math.floor(t*10)&1?e+n:e-n}return Math.min(e,this.max)|0},Vt.prototype.reset=function(){this.attempts=0},Vt.prototype.setMin=function(e){this.ms=e},Vt.prototype.setMax=function(e){this.max=e},Vt.prototype.setJitter=function(e){this.jitter=e};var Ht=class extends b{constructor(e,t){super(),this.nsps={},this.subs=[],e&&typeof e==`object`&&(t=e,e=void 0),t||={},t.path=t.path||`/socket.io`,this.opts=t,ze(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(t.randomizationFactor??.5),this.backoff=new Vt({min:this.reconnectionDelay(),max:this.reconnectionDelayMax(),jitter:this.randomizationFactor()}),this.timeout(t.timeout==null?2e4:t.timeout),this._readyState=`closed`,this.uri=e;let n=t.parser||Dt;this.encoder=new n.Encoder,this.decoder=new n.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.setMin(e),this)}randomizationFactor(e){var t;return e===void 0?this._randomizationFactor:(this._randomizationFactor=e,(t=this.backoff)==null||t.setJitter(e),this)}reconnectionDelayMax(e){var t;return e===void 0?this._reconnectionDelayMax:(this._reconnectionDelayMax=e,(t=this.backoff)==null||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 mt(this.uri,this.opts);let t=this.engine,n=this;this._readyState=`opening`,this.skipReconnect=!1;let r=Rt(t,`open`,function(){n.onopen(),e&&e()}),i=t=>{this.cleanup(),this._readyState=`closed`,this.emitReserved(`error`,t),e?e(t):this.maybeReconnectOnOpen()},a=Rt(t,`error`,i);if(!1!==this._timeout){let e=this._timeout,n=this.setTimeoutFn(()=>{r(),i(Error(`timeout`)),t.close()},e);this.opts.autoUnref&&n.unref(),this.subs.push(()=>{this.clearTimeoutFn(n)})}return this.subs.push(r),this.subs.push(a),this}connect(e){return this.open(e)}onopen(){this.cleanup(),this._readyState=`open`,this.emitReserved(`open`);let e=this.engine;this.subs.push(Rt(e,`ping`,this.onping.bind(this)),Rt(e,`data`,this.ondata.bind(this)),Rt(e,`error`,this.onerror.bind(this)),Rt(e,`close`,this.onclose.bind(this)),Rt(this.decoder,`decoded`,this.ondecoded.bind(this)))}onping(){this.emitReserved(`ping`)}ondata(e){try{this.decoder.add(e)}catch(e){this.onclose(`parse error`,e)}}ondecoded(e){Fe(()=>{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 Bt(this,e,t),this.nsps[e]=n),n}_destroy(e){let t=Object.keys(this.nsps);for(let e of t)if(this.nsps[e].active)return;this._close()}_packet(e){let 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.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;let e=this;if(this.backoff.attempts>=this._reconnectionAttempts)this.backoff.reset(),this.emitReserved(`reconnect_failed`),this._reconnecting=!1;else{let t=this.backoff.duration();this._reconnecting=!0;let n=this.setTimeoutFn(()=>{e.skipReconnect||(this.emitReserved(`reconnect_attempt`,e.backoff.attempts),!e.skipReconnect&&e.open(t=>{t?(e._reconnecting=!1,e.reconnect(),this.emitReserved(`reconnect_error`,t)):e.onreconnect()}))},t);this.opts.autoUnref&&n.unref(),this.subs.push(()=>{this.clearTimeoutFn(n)})}}onreconnect(){let e=this.backoff.attempts;this._reconnecting=!1,this.backoff.reset(),this.emitReserved(`reconnect`,e)}},Ut={};function Wt(e,t){typeof e==`object`&&(t=e,e=void 0),t||={};let n=ht(e,t.path||`/socket.io`),r=n.source,i=n.id,a=n.path,o=Ut[i]&&a in Ut[i].nsps,s=t.forceNew||t[`force new connection`]||!1===t.multiplex||o,c;return s?c=new Ht(r,t):(Ut[i]||(Ut[i]=new Ht(r,t)),c=Ut[i]),n.query&&!t.query&&(t.query=n.queryKey),c.socket(n.path,t)}Object.assign(Wt,{Manager:Ht,Socket:Bt,io:Wt,connect:Wt});var Gt=({apiBaseUrl:e,userId:t,chatId:n,siteId:r})=>Wt(e,{transports:[`polling`,`websocket`],upgrade:!0,rememberUpgrade:!1,auth:{userId:t,chatId:n,siteId:r},query:{chatId:n,siteId:r}}),Kt=({socket:e,chatId:t})=>{if(!e||!t||typeof window>`u`)return()=>{};let n=window.location.pathname+window.location.search,r=Date.now(),i=()=>{console.log(`[FlowEngageTracking] visitor:session_start`,{chatId:t,path:n}),e.emit(`visitor:session_start`,{chatId:t,path:n,title:document.title,referrer:document.referrer,userAgent:navigator.userAgent,timestamp:Date.now()})},a=()=>{console.log(`[FlowEngageTracking] visitor:page_enter`,{chatId:t,path:n}),e.emit(`visitor:page_enter`,{chatId:t,path:n,title:document.title,timestamp:Date.now()})},o=(n,r)=>{console.log(`[FlowEngageTracking] visitor:page_leave`,{chatId:t,path:n,duration:Math.max(0,Math.floor((Date.now()-r)/1e3))}),e.emit(`visitor:page_leave`,{chatId:t,path:n,duration:Math.max(0,Math.floor((Date.now()-r)/1e3)),timestamp:Date.now()})},s=()=>{console.log(`[FlowEngageTracking] visitor:heartbeat`,{chatId:t,path:n}),e.emit(`visitor:heartbeat`,{chatId:t,timestamp:Date.now()})},c=()=>{let e=window.location.pathname+window.location.search;if(e===n){console.log(`[FlowEngageTracking] route unchanged`,{currentPath:n});return}console.log(`[FlowEngageTracking] route changed`,{from:n,to:e}),o(n,r),n=e,r=Date.now(),a()},l=window.history.pushState.bind(window.history),u=window.history.replaceState.bind(window.history);window.history.pushState=(...e)=>{l(...e),c()},window.history.replaceState=(...e)=>{u(...e),c()};let d=window.setInterval(s,p),f=()=>{o(n,r),e.emit(`visitor:session_end`,{chatId:t,timestamp:Date.now()})};return window.addEventListener(`popstate`,c),window.addEventListener(`hashchange`,c),window.addEventListener(`beforeunload`,f),i(),s(),{notifyRouteChange:c,cleanup:()=>{window.clearInterval(d),window.history.pushState=l,window.history.replaceState=u,window.removeEventListener(`popstate`,c),window.removeEventListener(`hashchange`,c),window.removeEventListener(`beforeunload`,f)}}},qt=(0,l.createContext)(null),Jt=()=>{let e=(0,l.useContext)(qt);if(!e)throw Error(`useFlowEngage must be used inside FlowEngageProvider`);return e};function Yt(){if(typeof window>`u`)return!1;try{let e=window.localStorage?.getItem(`FE_DEBUG_VOICE`);if(e===`0`||e===`false`)return!1;if(e===`1`||e===`true`)return!0}catch{}return window.__FE_DEBUG_VOICE_TOOLS__===!1?!1:window.__FE_DEBUG_VOICE_TOOLS__===!0}function Xt(e){if(!e||typeof e.closest!=`function`)return!1;try{return!!e.closest(`#flowengage-root, .flowengage-shell`)}catch{return!1}}function Zt(...e){Yt()&&console.log(`[FlowEngage:shadowNavigate]`,...e)}var Qt=`fe_pending_nav_section`,$t=15e3;function en(){if(typeof window>`u`||typeof document>`u`)return;let e;try{e=JSON.parse(sessionStorage.getItem(Qt)||`null`)}catch{return}if(!e)return;try{sessionStorage.removeItem(Qt)}catch{}let{sectionText:t,ts:n}=e;if(!t)return;if(Date.now()-n>$t){Zt(`initNavigationHighlight: pending section expired, skipping:`,t);return}Zt(`initNavigationHighlight: replaying section highlight:`,t);let r=0,i=()=>{r+=1;let e=nn(null,t);if(e){hn(e),Zt(`initNavigationHighlight: highlighted on attempt`,r);return}r<8?setTimeout(i,300):Zt(`initNavigationHighlight: could not find element after 8 attempts:`,t)};setTimeout(i,250)}var tn=()=>{if(typeof document>`u`||document.getElementById(`fe-highlight-styles`))return;let e=document.createElement(`style`);e.id=`fe-highlight-styles`,e.textContent=`
|
|
2
2
|
.fe-highlight-section {
|
|
3
3
|
outline: 3px solid #7c3aed !important;
|
|
4
4
|
box-shadow: 0 0 15px rgba(124, 58, 237, 0.6) !important;
|
|
@@ -22,13 +22,13 @@ Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`});var e=Object.
|
|
|
22
22
|
box-shadow: none !important;
|
|
23
23
|
transition: outline-color 0.25s ease, box-shadow 0.25s ease !important;
|
|
24
24
|
}
|
|
25
|
-
`,document.head.appendChild(e)};function rn(e,t){if(typeof document>`u`)return null;if(e){let n=document.getElementById(e)||document.querySelector(`[data-section="${e}"]`);if(n)return n;t||=e.replace(/[-_]+/g,` `).trim()}if(!t)return null;let n=t.toLowerCase().trim(),r=n.split(/\s+/).filter(e=>e.length>2),i=Array.from(document.querySelectorAll(`h1, h2, h3, h4, h5, h6, [data-section]`)).filter(e=>!Zt(e));for(let e of i)if(e.textContent.replace(/\s+/g,` `).toLowerCase().trim()===n)return e;for(let e of i){let t=e.textContent.replace(/\s+/g,` `).toLowerCase().trim();if(t.startsWith(n)||t.endsWith(n))return e}let a=[];for(let e of i){let t=e.textContent.replace(/\s+/g,` `).toLowerCase().trim();t.includes(n)&&a.push({el:e,len:t.length})}if(a.length)return a.sort((e,t)=>e.len-t.len),a[0].el;for(let e of i){let t=e.textContent.replace(/\s+/g,` `).toLowerCase().trim();if(t.length>3&&n.includes(t))return e}if(r.length>0){let e=null,t=0;for(let n of i){let i=n.textContent.replace(/\s+/g,` `).toLowerCase(),a=0;for(let e of r)i.includes(e)&&a++;let o=a/r.length;o>t&&o>=.6&&(t=o,e=n)}if(e)return e}let o=Array.from(document.querySelectorAll(`main [role='group']`)).filter(e=>!Zt(e)),s=[];for(let e of o){let t=e.textContent.replace(/\s+/g,` `).toLowerCase().trim();t.length<15||t.length>8e3||t.includes(n)&&s.push({el:e,len:t.length})}if(s.length)return s.sort((e,t)=>e.len-t.len),s[0].el;if(r.length>0){let e=Array.from(document.querySelectorAll(`main a[href], article a[href], .views-row a[href], h2 a[href], h3 a[href], .card a[href], [class*='teaser'] a[href]`)).filter(e=>{if(Zt(e))return!1;try{let t=e.getAttribute(`href`)||``;if(!t||t===`#`||t.startsWith(`javascript:`))return!1}catch{return!1}let t=e.textContent.replace(/\s+/g,` `).trim();return t.length>=3&&t.length<=220}),t=null,n=0;for(let i of e){let e=i.textContent.replace(/\s+/g,` `).toLowerCase(),a=0;for(let t of r)e.includes(t)&&a++;let o=a/r.length;o>n&&o>=.5&&(n=o,t=i)}if(t)return t.closest(`article`)||t.closest(`.views-row`)||t}let c=document.querySelectorAll(`section, article, .card, [class*='feature'], [class*='service']`);for(let e of c){if(Zt(e))continue;let t=e.querySelector(`h1, h2, h3, h4, h5, h6`);if(t){let r=t.textContent.replace(/\s+/g,` `).toLowerCase().trim();if(r.includes(n)||n.includes(r))return e}}let l=document.querySelectorAll(`li, strong, blockquote, dt`);for(let e of l){if(Zt(e))continue;let t=e.textContent.replace(/\s+/g,` `).toLowerCase().trim();if(t.includes(n)&&t.length<500)return e.tagName===`STRONG`&&e.parentElement?.tagName===`LI`?e.parentElement:e}let u=Array.from(document.querySelectorAll(`a[href]`)).filter(e=>!Zt(e));u.sort((e,t)=>(e.textContent||``).trim().length-(t.textContent||``).trim().length);for(let e of u){let t=e.textContent.replace(/\s+/g,` `).toLowerCase().trim();if(t.includes(n)&&t.length<500)return e}let d=document.querySelectorAll(`p`);for(let e of d){if(Zt(e))continue;let t=e.textContent.replace(/\s+/g,` `).toLowerCase().trim();if(t.includes(n)&&t.length<800)return e}return null}function an(){return document.querySelector(`[itemprop='articleBody'], .article-body, .post-content, .entry-content, .field--name-body, .field--body, .node__content, article .content, .prose, article .prose`)||document.querySelector(`main article, main, [role='main'], article`)||document.body}var on=new Set(`the.and.for.are.but.not.you.all.can.her.was.one.our.out.day.get.has.him.his.how.its.may.new.now.old.see.two.way.who.did.let.put.say.she.too.use.has.have.this.that.with.from.they.will.your.about.into.than.then.some.very.when.come.here.just.like.also.back.after.over.such.take.only.know.think.each.made.look.more.most.other.well`.split(`.`));function sn(e){return String(e||``).toLowerCase().replace(/[^\w\s'-]/g,` `).split(/\s+/).filter(e=>e.length>0)}function cn(e,t){let n=sn(e).slice(-Math.min(t,28)),r=n.filter(e=>e.length>2&&!on.has(e));return r.length>=2?r:n.filter(e=>e.length>2).slice(-12)}function ln(e,t,{strict:n=!1}={}){if(!e||!t?.length)return null;let r=e.querySelectorAll([`h1, h2, h3, h4, h5, h6, p, li, blockquote`,`main h2, main h3, main h4, article h2, article h3, article h4`,`section h2, section h3, section h4`].join(`, `)),i=null,a=0;for(let e of r){if(Zt(e))continue;try{if(e.closest(`aside, nav, [role='navigation'], [role='banner'], footer`))continue}catch{}let n=e.textContent.replace(/\s+/g,` `).toLowerCase();if(n.length<3||n.length>6e3)continue;let r=0;for(let e of t)n.includes(e)&&r++;let o=r/t.length;if(o<.2)continue;let s=o,c=e.tagName;(c===`H2`||c===`H3`||c===`H4`)&&(s*=1.35),(c===`P`||c===`BLOCKQUOTE`)&&(s*=1.15),c?.startsWith(`H`)&&n.length<80&&(s*=1.2),n.length>400&&(s*=.65),s>a&&(a=s,i=e)}let o=n?t.length<=1?.62:.5:t.length<=1?.55:.35;return a>=o?i:null}function un(e,t,{strict:n=!1}={}){if(!e||!t?.length)return null;let r=e.querySelectorAll([`main [role='group']`,`[class*='card']`,`[class*='Card']`,`[class*='column']`,`[class*='grid'] > div`,`[class*='grid'] > article`,`[data-section]`].join(`, `)),i=null,a=0;for(let e of r){if(Zt(e))continue;try{if(e.closest(`aside, nav, [role='navigation'], [role='banner'], footer`))continue}catch{}let n=e.textContent.replace(/\s+/g,` `).toLowerCase();if(n.length<10||n.length>9e3)continue;let r=0;for(let e of t)e.length>1&&n.includes(e)&&r++;let o=r/t.length;if(o<.12)continue;let s=o,c=e.tagName;(c===`ARTICLE`||c===`SECTION`)&&(s*=1.05),n.length<900&&(s*=1.18),n.length<420&&(s*=1.12),n.length>2600?s*=.28:n.length>1400&&(s*=.45);try{e.querySelectorAll(`:scope > [role='group'], :scope > article, :scope > section`).length>=3&&n.length>1200&&(s*=.3)}catch{}s>a&&(a=s,i=e)}let o=n?t.length<=1?.48:.34:t.length<=1?.38:.2;return a>=o?i:null}function dn(e){return/^H[1-6]$/i.test(e?.tagName||``)}function fn(e,t,n=!1){if(!e||!t)return null;let r=t.replace(/\s+/g,` `).trim();if(r.length<14)return null;let i=n?.34:.24,a=r.toLowerCase(),o=cn(r,24);if(o.length<3&&(o=a.replace(/[^\w\s'-]/g,` `).split(/\s+/).filter(e=>e.length>2).slice(-18)),o.length<3)return null;let s=e.querySelectorAll(`p, blockquote`),c=null,l=0;for(let e of s){if(Zt(e))continue;let t=e.textContent.replace(/\s+/g,` `).toLowerCase();if(t.length<24)continue;let n=0;for(let e of o)t.includes(e)&&n++;let r=n/o.length,s=0;for(let e=Math.min(90,a.length);e>=22;e-=6){let n=a.slice(-e).trim();if(n.length>=22&&t.includes(n)){s=.28;break}}let u=r+s;u>l&&r>=i&&(l=u,c=e)}return c}function pn(e,t={}){if(typeof document>`u`||!e||!String(e).trim())return null;let n=t.strict===!0,r=String(e).trim(),i=r.length>450?r.slice(-450).trim():r,a=an(),o=cn(r,26);if(o.length>=1&&(o.length>=2||o.length===1&&o[0].length>=3)){let e=un(a,o,{strict:n});if(e)return e}if(r.length>=(n?55:42)){let e=fn(a,i,n);if(e)return e}if((!n||o.length>=3||o.length===2&&o.every(e=>e.length>=5))&&(o.length>=2||o.length===1&&o[0].length>=5)){let e=ln(a,o,{strict:n});if(e)return e}let s=i.split(/(?<=[.!?])\s+/).filter(e=>e.trim().length>0),c=s[s.length-1]||i,l=c.toLowerCase().replace(/[^\w\s'-]/g,` `).split(/\s+/).filter(e=>e.length>2),u=[];c.length>=10&&(u.push(c.slice(-220).trim()),c.length>220&&u.push(c.slice(0,120).trim()));for(let e=4;e<=Math.min(10,l.length);e++)u.push(l.slice(-e).join(` `));for(let e=Math.min(14,l.length);e>=11;e--)u.push(l.slice(-e).join(` `));for(let e=Math.min(8,l.length);e>=3;e--)u.push(l.slice(-e).join(` `));let d=n?14:6,f=new Set;for(let e of u){let t=e.trim();if(t.length<d||f.has(t))continue;f.add(t);let n=rn(null,t);if(n&&!Zt(n)){if(dn(n)&&r.length>140){let e=(a.querySelector?.(`[itemprop='articleBody'], .article-body, .post-content, .entry-content`)||a).querySelectorAll?.(`p, blockquote`)||[];for(let n of e)if(!Zt(n)&&n.textContent.toLowerCase().includes(t.toLowerCase().slice(0,Math.min(48,t.length))))return n}return n}}let p=o.length>=3?o:l.slice(-22);if(p.length===0)return null;let m=null,ee=-1,h=a.querySelectorAll(`h1, h2, h3, h4, h5, h6, p, li, blockquote, article`);for(let e of h){if(Zt(e))continue;try{if(e.closest(`aside, nav, [role='navigation'], footer`))continue}catch{}let t=e.textContent.toLowerCase();if(t.length<12)continue;let i=0;for(let e of p)e.length>2&&t.includes(e)&&i++;let a=i/p.length,o=e.tagName;(o===`P`||o===`BLOCKQUOTE`||o===`LI`)&&(a*=1.22),dn(e)&&(r.length>110?a*=.48:a*=.92),o===`ARTICLE`&&r.length>80&&(a*=.55),a>ee&&a>=(n?.42:.28)&&(ee=a,m=e)}return m}function mn(e){if(!e||typeof document>`u`)return null;try{if(Zt(e))return e;let t=e.closest?.([`[role='group']`,`[class*='card']`,`[class*='Card']`,`[data-section]`,`[class*='grid'] > div`,`[class*='grid'] > article`].join(`, `)),n=t?.textContent?.replace(/\s+/g,` `)||``;if(t&&!Zt(t)&&n.length>20&&n.length<=5200)return t;let r=e.closest?.(`p, li, blockquote, td, th, dd, figcaption, pre`);if(r&&!Zt(r))return r;let i=e.closest?.(`section`),a=i?.textContent?.replace(/\s+/g,` `)||``;return i&&a.length>48&&a.length<=4e3&&!Zt(i)?i:e}catch{return e}}function hn(e){if(!e||typeof e.getBoundingClientRect!=`function`)return!0;try{let t=e.getBoundingClientRect(),n=window.innerHeight||800;if(t.bottom<=72||t.top>=n-72)return!0;let r=Math.max(0,t.top),i=Math.min(n,t.bottom),a=Math.max(0,i-r),o=Math.min(120,Math.max(40,t.height*.28));return t.height>24&&a<o}catch{return!0}}function gn(e,{speaking:t=!1,scroll:n=!0}={}){if(!e||typeof document>`u`)return;nn();let r=document.querySelectorAll(`.fe-highlight-section`);for(let t of r)t!==e&&(t.classList.remove(`fe-highlight-section`,`fe-highlight-speaking`),t.classList.add(`fe-highlight-exiting`),setTimeout(()=>t.classList.remove(`fe-highlight-exiting`),300));if(e.classList.remove(`fe-highlight-exiting`),e.classList.add(`fe-highlight-section`),t?e.classList.add(`fe-highlight-speaking`):e.classList.remove(`fe-highlight-speaking`),n)try{e.scrollIntoView({behavior:`smooth`,block:`center`})}catch{try{e.scrollIntoView(!0)}catch{}}}function _n(){typeof document>`u`||document.querySelectorAll(`.fe-highlight-section, .fe-highlight-exiting`).forEach(e=>e.classList.remove(`fe-highlight-section`,`fe-highlight-speaking`,`fe-highlight-exiting`))}function vn(e){if(typeof window>`u`)return e;try{let t=new URL(String(e).trim(),window.location.href);return!/^https?:$/i.test(t.protocol)||t.origin===window.location.origin?t.href:new URL(t.pathname+t.search+t.hash,window.location.origin).href}catch{return e}}async function yn(e){if(typeof window>`u`)return!1;try{let t=new URL(String(e).trim(),window.location.href);return t.origin===window.location.origin?(await fetch(t.href,{method:`HEAD`,mode:`same-origin`,cache:`no-store`})).ok:!1}catch{return!1}}async function bn(e,{siteId:t,apiBaseUrl:n}){if(!e)return!1;if(!t||!n)return console.warn(`[FlowEngage] shouldProceedWithNavigation: missing siteId or apiBaseUrl`),!1;let r=String(n).replace(/\/$/,``),i=new URLSearchParams({siteId:String(t),url:String(e).trim()});try{let t=await(await fetch(`${r}/api/widget/navigate-allowed?${i.toString()}`)).json().catch(()=>({}));return t.success?t.allowed?!0:t.hasIndex===!1?yn(e):!1:!1}catch(e){return console.warn(`[FlowEngage] navigate-allowed check failed:`,e?.message),!1}}function xn(e){if(!(!e||typeof sessionStorage>`u`))try{sessionStorage.setItem($t,JSON.stringify({sectionText:e,ts:Date.now()}))}catch{}}async function Sn(e,t={}){if(typeof window>`u`)return!1;let{sectionText:n}=t;try{let t=vn(e),r=new URL(t,window.location.origin);if(Qt(`input:`,e,`→ normalized:`,t,`href:`,r.href),r.hash&&r.pathname===window.location.pathname){let e=r.hash.slice(1),t=document.getElementById(e);if(t)return Qt(`branch: hash scroll (same path)`),t.scrollIntoView({behavior:`smooth`,block:`start`}),!0}if(r.pathname===window.location.pathname&&r.search===window.location.search&&!r.hash)return Qt(`branch: already on page (no nav)`),!1;let i=r.pathname+r.search+r.hash,a=window.next?.router;if(a?.push)return Qt(`branch: Next.js Pages router.push`,i),new Promise(e=>{let t=()=>{a.events?.off(`routeChangeComplete`,t),e(!0)};a.events?.on(`routeChangeComplete`,t),a.push(i),setTimeout(t,5e3)});let o=window.__NEXT_ROUTER__;return o?.push?(Qt(`branch: __NEXT_ROUTER__.push`,i),o.push(i),!0):(n?(xn(n),Qt(`branch: location.assign (full navigation, section stored):`,n)):Qt(`branch: location.assign (full navigation)`,r.href),window.location.assign(r.href),!0)}catch(t){console.warn(`[FlowEngage] shadowNavigate error:`,t),n&&xn(n);try{window.location.href=vn(e)}catch{window.location.href=e}return!0}}var Cn=e=>!e||typeof e!=`string`?e:e.replace(/<human_assistance_request>[\s\S]*?<\/human_assistance_request>/gi,``).replace(/<human_assistance_request>/gi,``).replace(/<\/human_assistance_request>/gi,``).replace(/<navigate[^>]*\/>/gi,``).replace(/<navigate[^>]*>[\s\S]*?<\/navigate>/gi,``).replace(/<[a-z]+(?:_[a-z]+)+[^>]*>[\s\S]*?<\/[a-z]+(?:_[a-z]+)+>/gi,``).replace(/<[a-z]+(?:_[a-z]+)+[^>]*\/>/gi,``).trim(),wn=(e=[])=>e.map(e=>({...e,message:Cn(e.message),isPending:!1,id:e.messageId||`${e.sender}-${e.timestamp||Date.now()}-${Math.random()}`})),Tn=(e,t)=>e?typeof e==`string`?e:e.message||e.error||e.reason||t:t,En=(e={})=>{if(!e?.candidate)return null;if(typeof e.candidate==`object`)return e.candidate;let t=e.sdpMid!==void 0&&e.sdpMid!==null&&e.sdpMid!==``,n=e.sdpMLineIndex!==void 0&&e.sdpMLineIndex!==null;return!t&&!n?null:{candidate:e.candidate,...t?{sdpMid:e.sdpMid}:{},...n?{sdpMLineIndex:e.sdpMLineIndex}:{}}},Dn=e=>{if(!e)return null;let t=typeof e==`object`?e:{candidate:e};return{hasCandidate:!!t.candidate,sdpMid:t.sdpMid??null,sdpMLineIndex:t.sdpMLineIndex??null,candidatePreview:typeof t.candidate==`string`?t.candidate.slice(0,80):null}},On=(e=[],t=`Agent`)=>{for(let t of e)if(typeof t==`string`&&t.trim())return t.trim();return t},kn=(e=[],t)=>typeof t==`string`&&t.trim()?t.trim():On(e,`Agent`);function An({siteId:e,config:t,children:n,language:r=`en`}){let i=(0,l.useMemo)(()=>e?{...t||{},siteId:e}:t||null,[e,t]),a=(0,l.useMemo)(()=>{let e=i?.widgetSettings?.branding?.fallbackAgentName;return typeof e==`string`&&e.trim()?e.trim():null},[i]),[o,s]=(0,l.useState)(`booting`),[c,f]=(0,l.useState)(null),[p,g]=(0,l.useState)(null),[_,oe]=(0,l.useState)(``),[v,y]=(0,l.useState)([]),[le,ue]=(0,l.useState)(ne().isOpen),[de,fe]=(0,l.useState)(ne().activeScreen),[pe,me]=(0,l.useState)(ne().isHumanHandled),[he,ge]=(0,l.useState)(ne().agentName),[_e,ve]=(0,l.useState)(ne().agentHeadshot),[ye,be]=(0,l.useState)(()=>ie(i?.siteId)),[xe,Se]=(0,l.useState)(!1),[Ce,we]=(0,l.useState)(!1),[Te,Ee]=(0,l.useState)(`idle`),[De,Oe]=(0,l.useState)(!1),[ke,Ae]=(0,l.useState)(!1),[je,Me]=(0,l.useState)(``),[Ne,b]=(0,l.useState)(!1),[Pe,Fe]=(0,l.useState)(!1),[x,Ie]=(0,l.useState)(null),[Le,Re]=(0,l.useState)(null),[ze,Be]=(0,l.useState)(`idle`),[Ve,He]=(0,l.useState)(null),[Ue,We]=(0,l.useState)(!1),[Ge,Ke]=(0,l.useState)(``),S=(0,l.useRef)(null),C=(0,l.useRef)(null),w=(0,l.useRef)(``),qe=(0,l.useRef)(null),Je=(0,l.useRef)(null),Ye=(0,l.useRef)(null),Xe=(0,l.useRef)(null),Ze=(0,l.useRef)(null),Qe=(0,l.useRef)([]),$e=(0,l.useRef)(null),et=(0,l.useRef)(null),tt=(0,l.useRef)(!1),nt=(0,l.useRef)(!1),rt=(0,l.useRef)(``),it=(0,l.useRef)(he),at=(0,l.useRef)([]),ot=(0,l.useRef)(!1),st=(0,l.useRef)({notifyRouteChange:()=>{},cleanup:()=>{}}),ct=(0,l.useMemo)(()=>{let e=p?.widgetSettings?.call?.maxDurationSeconds??i?.widgetSettings?.call?.maxDurationSeconds??i?.callMaxDurationSeconds,t=Number(e);return Number.isFinite(t)&&t>0?t:ee},[i,p]);(0,l.useEffect)(()=>{qe.current=x},[x]),(0,l.useEffect)(()=>{it.current=he},[he]);let lt=()=>{Ke(``)},ut=e=>{let t=typeof e==`string`?e.trim().toLowerCase():``;return be(t),ae(t,i?.siteId),t};(0,l.useEffect)(()=>{let e=i?.siteId;e&&be(ie(e))},[i?.siteId]);let dt=()=>{Je.current&&=(Je.current.close(),null),Ye.current&&=(Ye.current.getTracks().forEach(e=>e.stop()),null),Xe.current&&=(Xe.current.srcObject=null,Xe.current.remove(),null),Ze.current=null,Qe.current=[],$e.current=null,et.current=null,tt.current=!1,We(!1),Ie(null),Re(null),Be(`idle`),He(null)},ft=(e=new Date().toISOString())=>{let t=S.current,n=$e.current||Ze.current?.callId;if(!t?.connected||!n||tt.current){console.log(`[FlowEngageProvider] skipping call:connected emit`,{callId:n,chatId:w.current,socketConnected:!!t?.connected,alreadyReported:tt.current});return}console.log(`[FlowEngageProvider] emitting call:connected`,{callId:n,chatId:w.current,connectedAt:e}),tt.current=!0,t.emit(`call:connected`,{callId:n,chatId:w.current,connectedAt:e})},pt=(e={})=>{if(!e.callId)return;let t=et.current===e.callId,n=$e.current===e.callId,r=qe.current?.callId===e.callId;if(!(!t&&!n&&!r)){if(console.log(`[FlowEngageProvider] syncing accepted call state`,{callId:e.callId,chatId:e.chatId||w.current,isAcceptingHere:t,isAlreadyActive:n,isIncomingHere:r}),Ie(null),t||n){$e.current=e.callId,Re(e.callId),Be(e=>e===`connected`?e:`connecting`),ue(!0);return}Be(`idle`)}},mt=(e={})=>{if(!e.callId)return;let t=et.current===e.callId,n=$e.current===e.callId,r=qe.current?.callId===e.callId;if(!(!t&&!n&&!r)){if(console.log(`[FlowEngageProvider] syncing ended incoming call state`,{callId:e.callId,chatId:e.chatId||w.current,isAcceptingHere:t,isAlreadyActive:n,isIncomingHere:r,reason:e.reason||e.status||null}),n){dt();return}et.current=null,Ze.current=null,Qe.current=[],Ie(null),Be(`idle`)}},ht=async(e={})=>{let t=Je.current,n=S.current,r=e.sdpOffer||e.offer?.sdp;if(!t||!n?.connected||!r||!e.callId){console.log(`[FlowEngageProvider] deferring remote offer until peer/socket ready`,{callId:e.callId,chatId:w.current,hasPeerConnection:!!t,socketConnected:!!n?.connected,hasOffer:!!r}),Ze.current=e;return}if(console.log(`[FlowEngageProvider] applying remote offer`,{callId:e.callId,chatId:w.current,offerLength:r.length,signalingState:t.signalingState}),await t.setRemoteDescription(new RTCSessionDescription({type:`offer`,sdp:r})),Qe.current.length>0){console.log(`[FlowEngageProvider] flushing queued agent ICE candidates after remote offer`,{callId:e.callId,chatId:w.current,queuedCount:Qe.current.length});for(let e of Qe.current)await t.addIceCandidate(new RTCIceCandidate(e));Qe.current=[]}let i=await t.createAnswer();await t.setLocalDescription(i),console.log(`[FlowEngageProvider] created local answer`,{callId:e.callId,chatId:w.current,answerLength:i.sdp?.length||0,signalingState:t.signalingState}),n.emit(`call:answer`,{callId:e.callId,sdpAnswer:i.sdp,chatId:w.current})};(0,l.useEffect)(()=>{re({isOpen:le,activeScreen:de,isHumanHandled:pe,agentName:he,agentHeadshot:_e})},[le,de,pe,he,_e]),(0,l.useEffect)(()=>{let e=!0;return(async()=>{try{console.log(`[FlowEngageProvider] boot start`,{resolvedConfig:i,language:r});let t=d(i);console.log(`[FlowEngageProvider] config validated`,t);let n=await se(t);if(!e)return;let o=te();w.current=o;let c=ce({apiBaseUrl:t.apiBaseUrl,userId:n.userId,siteId:t.siteId});C.current=c,g({...n,apiBaseUrl:t.apiBaseUrl}),oe(o),console.log(`[FlowEngageProvider] bootstrap resolved`,{bootstrapData:n,resolvedChatId:o});let l=Kt({apiBaseUrl:t.apiBaseUrl,userId:n.userId,chatId:o,siteId:t.siteId});S.current=l,l.on(`connect`,()=>{console.log(`[FlowEngageProvider] socket connected`),Ee(`connected`)}),l.on(`disconnect`,()=>{console.log(`[FlowEngageProvider] socket disconnected`),Ee(`disconnected`)}),l.on(`aiTyping`,()=>{console.log(`[FlowEngageProvider] received aiTyping`,{chatId:w.current}),we(!0)}),l.on(`ai:typing`,()=>{console.log(`[FlowEngageProvider] received ai:typing`,{chatId:w.current}),we(!0)}),l.on(`messageReceived`,e=>{let t=e.message||e,n={...t,message:Cn(t.message)};we(!1),Se(!1),y(e=>[...e.filter(e=>!e.isPending),{...n,isPending:!1,id:n.messageId||`${n.sender}-${Date.now()}-${Math.random()}`}])}),l.on(`conversationStarted`,e=>{console.log(`[FlowEngageProvider] conversationStarted`,e),e?.message&&y(t=>[...t,{id:`system-start-${Date.now()}`,sender:`system`,message:e.message,timestamp:new Date().toISOString(),isPending:!1}])}),l.on(`message:new`,e=>{let t=e.message||e,n={...t,message:Cn(t.message)};we(!1),(n.sender===`agent`||n.agent_name||n.sender===`ai`||n.sender===`bot`)&&Se(!1),y(e=>n.sender===`bot`||n.sender===`ai`?[...e,{...n,isPending:!1,id:n.messageId||`${n.sender}-${Date.now()}-${Math.random()}`}]:e.some(e=>e.id===n.messageId||e.sender===n.sender&&e.message===n.message&&e.isPending)?e.map(e=>e.sender===n.sender&&e.message===n.message&&e.isPending?{...n,isPending:!1,id:n.messageId||e.id}:e):[...e,{...n,isPending:!1,id:n.messageId||`${n.sender}-${Date.now()}-${Math.random()}`}]),(n.sender===`agent`||n.agent_name)&&(me(!0),fe(`agent`),ge(kn([n.agent_name,n.agentName,n.metadata?.agentName],a)),n.sender_headshot&&ve(n.sender_headshot),ue(!0))}),l.on(`agent:joined`,e=>{let t=kn([e.agent?.name,e.agentName],a);me(!0),fe(`agent`),ge(t),ve(e.agent?.headshot||null),ue(!0),y(e=>[...e,{id:`agent-joined-${Date.now()}`,sender:`system`,message:`${t} has joined the chat.`,timestamp:new Date().toISOString(),isPending:!1}])}),l.on(`agentJoined`,e=>{let t=kn([e.agent?.name,e.agentName],a);me(!0),fe(`agent`),ge(t),ve(e.agent?.headshot||null),ue(!0),y(e=>[...e,{id:`agent-joined-${Date.now()}`,sender:`system`,message:`${t} has joined the chat.`,timestamp:new Date().toISOString(),isPending:!1}])}),l.on(`agent:left`,(e={})=>{let t=kn([e.agent?.name,e.agentName,it.current],a);me(!1),fe(`ai`),y(e=>[...e,{id:`agent-left-${Date.now()}`,sender:`system`,message:`${t} has left the chat.`,timestamp:new Date().toISOString(),isPending:!1}])}),l.on(`agentLeft`,(e={})=>{let t=kn([e.agent?.name,e.agentName,it.current],a);me(!1),fe(`ai`),y(e=>[...e,{id:`agent-left-${Date.now()}`,sender:`system`,message:`${t} has left the chat.`,timestamp:new Date().toISOString(),isPending:!1}])}),l.on(`conversationEnded`,e=>{Fe(!0);let t=e?.message||`This conversation has ended. Thank you for reaching out!`;y(e=>[...e,{id:`conversation-ended-${Date.now()}`,sender:`system`,message:t,timestamp:new Date().toISOString(),isPending:!1}])}),l.on(`chat:history_update`,e=>{y(wn(e.chat_history||[]))}),l.on(`typing:start`,e=>{console.log(`[FlowEngageProvider] received typing:start`,{chatId:e?.chatId||w.current,sender:e?.sender}),e.sender===`agent`&&Se(!0)}),l.on(`typing:stop`,e=>{console.log(`[FlowEngageProvider] received typing:stop`,{chatId:e?.chatId||w.current,sender:e?.sender}),e.sender===`agent`&&Se(!1)}),l.on(`call:incoming`,(e={})=>{let t=kn([e.agentName,e.ownerName,e.agent?.name,he],a);console.log(`[FlowEngageProvider] received call:incoming`,{callId:e.callId,chatId:w.current,agentName:t}),lt(),tt.current=!1,Ie({callId:e.callId,from:e.from||`owner`,agentId:e.agentId||null,agentName:t}),ge(e=>kn([t,e],a)),Be(`incoming`),He(null),ue(!0)}),l.on(`call:offer`,async(e={})=>{console.log(`[FlowEngageProvider] received call:offer`,{callId:e.callId,chatId:e.chatId||w.current,offerLength:(e.sdpOffer||e.offer?.sdp||``).length}),Ze.current=e;try{await ht(e)}catch(e){console.error(`[FlowEngageProvider] failed to apply remote offer`,e)}}),l.on(`call:ice-candidate-from-agent`,async(e={})=>{if(!e.candidate){console.log(`[FlowEngageProvider] skipping agent ICE candidate`,{callId:e.callId,chatId:e.chatId||w.current,hasPeerConnection:!!Je.current,hasCandidate:!!e.candidate});return}try{let t=En(e);if(!t){console.warn(`[FlowEngageProvider] ignoring invalid ICE candidate payload`,e);return}if(console.log(`[FlowEngageProvider] adding agent ICE candidate`,{callId:e.callId,chatId:e.chatId||w.current,candidate:Dn(t),hasRemoteDescription:!!Je.current?.remoteDescription}),!Je.current||!Je.current.remoteDescription){console.log(`[FlowEngageProvider] queueing agent ICE candidate until peer/remote description is ready`,{callId:e.callId,chatId:e.chatId||w.current,queueSize:Qe.current.length+1}),Qe.current.push(t);return}await Je.current.addIceCandidate(new RTCIceCandidate(t))}catch(e){console.error(`[FlowEngageProvider] failed to add ICE candidate`,e)}}),l.on(`call:ended`,()=>{lt(),dt()}),l.on(`call:accepted`,(e={})=>{console.log(`[FlowEngageProvider] received call:accepted`,{callId:e.callId,chatId:e.chatId||w.current}),pt(e)}),l.on(`call:accepted_by_other`,(e={})=>{console.log(`[FlowEngageProvider] received call:accepted_by_other`,{callId:e.callId,chatId:e.chatId||w.current}),pt(e)}),l.on(`call:rejected`,(e={})=>{console.log(`[FlowEngageProvider] received call:rejected`,{callId:e.callId,chatId:e.chatId||w.current,reason:e.reason}),mt(e)}),l.on(`call:missed`,(e={})=>{console.log(`[FlowEngageProvider] received call:missed`,{callId:e.callId,chatId:e.chatId||w.current,reason:e.reason}),mt(e)}),l.on(`call:failed`,(e={})=>{console.log(`[FlowEngageProvider] received call:failed`,{callId:e.callId,chatId:e.chatId||w.current,reason:e.reason}),mt(e)}),l.on(`call:connected`,(e={})=>{if(!e.callId)return;let t=et.current===e.callId,n=$e.current===e.callId,r=Ze.current?.callId===e.callId,i=qe.current?.callId===e.callId;if(console.log(`[FlowEngageProvider] received call:connected`,{callId:e.callId,chatId:e.chatId||w.current,connectedAt:e.connectedAt,status:e.status,isAcceptingHere:t,isAlreadyActive:n,isPendingOfferHere:r,isIncomingHere:i}),!t&&!n&&!r){i&&(Ie(null),Be(`idle`));return}tt.current=!0,et.current=null,$e.current=e.callId,Re(e.callId),Ie(null),Be(`connected`),He(e.connectedAt||new Date().toISOString()),ue(!0)}),l.on(`call:unavailable`,(e={})=>{dt(),Ke(Tn(e,`This visitor is not available for a call right now.`)),ue(!0)}),l.on(`call:error`,(e={})=>{dt(),Ke(Tn(e,`We couldn't connect the call right now.`)),ue(!0)}),l.on(`visitor:navigate`,async({url:e,section:n,highlight:r}={})=>{if(e){if(console.log(`[FlowEngageProvider] visitor:navigate`,{url:e,section:n,highlight:r}),!await bn(e,{siteId:t.siteId,apiBaseUrl:t.apiBaseUrl})){console.warn(`[FlowEngageProvider] visitor:navigate blocked (not indexed)`,e);return}Sn(e).then(e=>{let t=n||r;t&&setTimeout(()=>{let e=rn(null,t);e&&gn(e)},e?300:150)})}}),l.on(`visitor:highlight`,({sectionId:e,sectionText:t}={})=>{if(!e&&!t)return;console.log(`[FlowEngageProvider] visitor:highlight`,{sectionId:e,sectionText:t});let n=rn(e||null,t||null);n&&gn(n)}),l.on(`visitor:clear_highlight`,()=>{_n()}),st.current=qt({socket:l,chatId:o}),console.log(`[FlowEngageProvider] tracking started`,{chatId:o});let u=await c.loadHistory(o,r);if(console.log(`[FlowEngageProvider] history loaded`,u),!e||(y(wn(u.chat_history||[])),me(!!u.is_human_handled),fe(u.is_human_handled?`agent`:de),await new Promise(e=>setTimeout(e,500)),!e))return;s(`ready`),console.log(`[FlowEngageProvider] status ready`)}catch(t){if(!e)return;console.error(`[FlowEngageProvider] boot failed`,t),f(t),s(`error`)}})(),()=>{e=!1,st.current?.cleanup?.(),dt(),S.current?.disconnect()}},[i,r,a]),(0,l.useEffect)(()=>()=>{if(Ne&&!ot.current&&at.current.length>0){let e=w.current,t=at.current,n=C.current;n&&e&&t.length>0&&(console.log(`[FlowEngageProvider] safety-net: syncing voice transcript on unmount`),n.beaconSyncVoice(e,t)||n.syncVoice(e,t).catch(()=>{}),ot.current=!0)}},[Ne,p]),(0,l.useEffect)(()=>{if(!C.current||!_||o!==`ready`||pe)return;let e=window.setInterval(async()=>{try{let e=await C.current.checkHumanHandled(_);me(!!e.is_human_handled),e.is_human_handled&&(fe(`agent`),e.agent_info?.name&&ge(kn([e.agent_info.name],a)),e.agent_info?.headshot&&ve(e.agent_info.headshot))}catch{}},1e4);return()=>window.clearInterval(e)},[_,o,pe,a]);let gt=async()=>{if(!(!x?.callId||!C.current||!S.current||!_)){lt(),et.current=x.callId,console.log(`[FlowEngageProvider] acceptCall started`,{callId:x?.callId,chatId:_,socketConnected:!!S.current?.connected,hasPendingOffer:!!Ze.current});try{let e=await navigator.mediaDevices.getUserMedia({audio:!0});console.log(`[FlowEngageProvider] microphone stream acquired`,{callId:x.callId,chatId:_,trackCount:e.getTracks().length}),Ye.current=e;let t=new RTCPeerConnection({iceServers:[{urls:`stun:stun.l.google.com:19302`}]});Je.current=t,t.onconnectionstatechange=()=>{let e=t.connectionState;if(console.log(`[FlowEngageProvider] peer connection state changed`,{callId:x.callId,chatId:_,connectionState:e,iceConnectionState:t.iceConnectionState,signalingState:t.signalingState}),e===`connected`){let e=new Date().toISOString();Be(`connected`),He(t=>t||e),ft(e);return}e===`connecting`&&Be(e=>e===`connected`?e:`connecting`)},t.oniceconnectionstatechange=()=>{let e=t.iceConnectionState;if(console.log(`[FlowEngageProvider] ICE connection state changed`,{callId:x.callId,chatId:_,iceConnectionState:e,connectionState:t.connectionState,signalingState:t.signalingState}),e===`connected`||e===`completed`){let e=new Date().toISOString();Be(`connected`),He(t=>t||e),ft(e);return}(e===`checking`||e===`new`)&&Be(e=>e===`connected`?e:`connecting`)},e.getTracks().forEach(n=>{t.addTrack(n,e)}),t.onicecandidate=e=>{if(!e.candidate||!S.current?.connected){console.log(`[FlowEngageProvider] local ICE candidate skipped`,{callId:x.callId,chatId:_,hasCandidate:!!e.candidate,socketConnected:!!S.current?.connected});return}console.log(`[FlowEngageProvider] emitting local ICE candidate`,{callId:x.callId,chatId:_,candidate:Dn(e.candidate)}),S.current.emit(`call:ice-candidate`,{callId:x.callId,candidate:e.candidate,chatId:_,from:`customer`})},t.ontrack=e=>{if(console.log(`[FlowEngageProvider] remote audio track received`,{callId:x.callId,chatId:_,streamCount:e.streams?.length||0}),!Xe.current){let e=document.createElement(`audio`);e.id=`flowengage-remote-audio`,e.autoplay=!0,Xe.current=e,document.body.appendChild(e)}Xe.current.srcObject=e.streams[0];let t=x?.callId,n=t&&(et.current===t||$e.current===t);if(!tt.current&&n){let e=new Date().toISOString();Be(`connected`),He(t=>t||e),$e.current=t,Re(t),ft(e)}};let n=Ze.current;n&&(console.log(`[FlowEngageProvider] found pending remote offer during accept`,{callId:n.callId||x.callId,chatId:_}),await ht({...n,callId:n.callId||x.callId})),await C.current.acceptCall(x.callId,_),console.log(`[FlowEngageProvider] acceptCall API succeeded`,{callId:x.callId,chatId:_}),$e.current=x.callId,Re(x.callId),Be(e=>e===`connected`||tt.current?`connected`:`connecting`),Ie(null),ue(!0)}catch(e){if(console.error(`[FlowEngageProvider] acceptCall failed`,e),et.current=null,dt(),e?.status===404||e?.status===409||e?.status===422){Ke(Tn(e,`This visitor call is no longer available.`));return}if(e?.name===`NotAllowedError`||e?.name===`PermissionDeniedError`){try{await C.current.rejectCall(x.callId,_)}catch(e){console.error(`[FlowEngageProvider] failed to reject call after microphone denial`,e)}Ke(`Microphone access was denied. Please allow microphone access to accept the call.`);return}Ke(`We couldn't connect the call right now. Please try again.`)}}},_t=async()=>{if(!x?.callId||!C.current||!_){dt();return}lt();try{await C.current.rejectCall(x.callId,_)}catch(e){console.error(`[FlowEngageProvider] rejectCall failed`,e),Ke(Tn(e,`We couldn't decline the call cleanly.`))}finally{dt()}},vt=(0,l.useRef)(_t);vt.current=_t,(0,l.useEffect)(()=>{if(!x?.callId||Le)return;let e=x.callId,t=window.setTimeout(()=>{qe.current?.callId===e&&vt.current()},h);return()=>window.clearTimeout(t)},[x?.callId,Le]);let yt=async()=>{if(!Le||!C.current||!_){dt();return}lt();try{await C.current.endWebRTCCall(Le,_)}catch(e){console.error(`[FlowEngageProvider] endWebRTCCall failed`,e),Ke(Tn(e,`The call ended locally, but the server could not be updated.`))}finally{dt()}},bt=()=>{let e=Ye.current?.getAudioTracks?.()||[],t=Je.current?.getSenders?.().map(e=>e.track).filter(e=>e?.kind===`audio`)||[],n=[...e,...t].filter(Boolean);if(n.length===0){console.warn(`[FlowEngageProvider] no local audio tracks available for mute`);return}let r=!Ue;n.forEach(e=>{e.enabled=!r}),console.log(`[FlowEngageProvider] toggled local mute`,{nextMuted:r,trackCount:n.length}),We(r)},xt=async(e={})=>{let t=e.notifyChatInitiated===!0;if(ue(!0),!(!t||!C.current||!_||typeof window>`u`)){try{await C.current.trackVisitor({chatId:_,currentPagePath:window.location.pathname||`/`})}catch{}try{await C.current.updateChatStatus(_,`open`)}catch{}}},St=async e=>{let t=ut(e);if(!t||!C.current||!w.current)return t;try{await C.current.trackVisitor({chatId:w.current,currentPagePath:typeof window<`u`&&window.location.pathname||`/`,email:t})}catch(e){console.error(`[FlowEngageProvider] failed to persist visitor email`,e)}return t},Ct=()=>{if(!_||!S.current?.connected||nt.current){console.log(`[FlowEngageProvider] skipped typing:start emit`,{chatId:_,socketConnected:!!S.current?.connected,alreadyTyping:nt.current});return}nt.current=!0,console.log(`[FlowEngageProvider] emitting typing:start`,{chatId:_,sender:`user`}),S.current.emit(`typing:start`,{chatId:_,sender:`user`})},wt=()=>{if(!_||!S.current?.connected||!nt.current){console.log(`[FlowEngageProvider] skipped typing:stop emit`,{chatId:_,socketConnected:!!S.current?.connected,wasTyping:nt.current});return}nt.current=!1,console.log(`[FlowEngageProvider] emitting typing:stop`,{chatId:_,sender:`user`}),S.current.emit(`typing:stop`,{chatId:_,sender:`user`})},Tt=(e=``)=>{let t=typeof e==`string`?e:``;if(!_||!S.current?.connected){console.log(`[FlowEngageProvider] skipped typing:update emit`,{chatId:_,socketConnected:!!S.current?.connected,textLength:t.length});return}rt.current!==t&&(rt.current=t,console.log(`[FlowEngageProvider] emitting typing:update`,{chatId:_,sender:`user`,textLength:t.length}),S.current.emit(`typing:update`,{chatId:_,sender:`user`,text:t}))},Et=async(e,t=``,n=null)=>{if(!e.trim()||!C.current||!_||o!==`ready`||Pe)return;wt();let i=`pending-user-${Date.now()}`,a={id:i,sender:`user`,message:e,timestamp:new Date().toISOString(),isPending:!0,...n||{}};if(y(e=>[...e,a]),pe&&S.current?.connected){S.current.emit(`customer:message`,{chatId:_,content:e,sender:`user`,email:ye||void 0,...n||{}});return}Oe(!0);try{let i=await C.current.sendAiMessage(_,e,r,t,{...n||{},...ye?{email:ye}:{}});y(wn(i.chat_history||[])),me(!!i.is_human_handled),fe(i.is_human_handled?`agent`:`ai`),we(!1),await C.current.updateChatStatus(_,`messageSent`)}catch(e){y(e=>e.filter(e=>e.id!==i)),we(!1),e.status===429?(Ae(!0),Me(e.message),window.setTimeout(()=>{Ae(!1),Me(``)},m)):f(e)}finally{Oe(!1)}},Dt=async e=>{if(!(!C.current||!_)){try{let t=e?`voice`:`text`;await C.current.setChatMode(_,t)}catch(e){console.error(`[FlowEngageProvider] setVoiceMode failed`,e)}b(e),e&&(ot.current=!1)}},Ot=async e=>{if(!ot.current){if(ot.current=!0,!C.current||!_||!e?.length){b(!1);return}try{let t=await C.current.syncVoice(_,e);if(t?.chat_history?.length)y(wn(t.chat_history));else if(t?.success)try{let e=await C.current.loadHistory(_,r);e?.chat_history?.length&&y(wn(e.chat_history))}catch{}}catch{}finally{b(!1)}}},kt=async()=>{if(!(!C.current||!_)){Ne&&!ot.current&&at.current.length>0&&await Ot(at.current);try{await C.current.endConversation(_)}catch{try{await C.current.updateChatStatus(_,`ended`)}catch{}}Fe(!0),y(e=>[...e,{id:`conversation-ended-${Date.now()}`,sender:`system`,message:`This conversation has ended. Thank you for reaching out!`,timestamp:new Date().toISOString(),isPending:!1}])}};(0,l.useEffect)(()=>{if(ze!==`connected`||!Le||!_||!Ve||!ct)return;let e=new Date(Ve).getTime(),t=Number.isFinite(e)?Date.now()-e:0,n=Math.max(0,ct*1e3-t),r=window.setTimeout(()=>{Ke(`The call ended because it reached the time limit.`),yt()},n);return()=>window.clearTimeout(r)},[Le,Ve,ze,_,yt,ct]),(0,l.useEffect)(()=>{let e=()=>{let e=w.current,t=C.current;if(!t||!e)return;if($e.current){t.beaconEndWebRTCCall($e.current,e);return}let n=et.current||qe.current?.callId;n&&t.beaconCustomerUnavailable(n,e)};return window.addEventListener(`pagehide`,e),window.addEventListener(`beforeunload`,e),()=>{window.removeEventListener(`pagehide`,e),window.removeEventListener(`beforeunload`,e)}},[]);let T=(0,l.useMemo)(()=>({status:o,error:c,runtimeConfig:p,resolvedConfig:i,chatId:_,chatHistory:v,isOpen:le,activeScreen:de,isHumanHandled:pe,agentName:he,agentHeadshot:_e,visitorEmail:ye,isAgentTyping:xe,isAiTyping:Ce,connectionStatus:Te,isLoading:De,isVoiceMode:Ne,isRateLimited:ke,rateLimitMessage:je,isConversationEnded:Pe,incomingCall:x,activeCallId:Le,callConnectionState:ze,callConnectedAt:Ve,isCallMuted:Ue,webRTCError:Ge,language:r,historyRef:at,hasSyncedRef:ot,dismissCallError:lt,captureVisitorEmail:St,startTyping:Ct,stopTyping:wt,updateTypingDraft:Tt,notifyRouteChange:()=>st.current?.notifyRouteChange?.(),openWidget:xt,closeWidget:()=>ue(!1),toggleWidget:()=>{if(le){ue(!1);return}xt({notifyChatInitiated:!0})},sendMessage:Et,setVoiceMode:Dt,onMessageSync:Ot,endConversation:kt,acceptCall:gt,rejectCall:_t,endWebRTCCall:yt,toggleCallMute:bt,startTyping:Ct,stopTyping:wt,updateTypingDraft:Tt}),[o,c,p,i,_,v,le,de,pe,he,_e,ye,xe,Ce,Te,De,Ne,ke,je,Pe,x,Le,ze,Ve,Ue,Ge,r,St,Ct,wt,Tt,gt,_t,yt,bt,xt,Et,Dt,Ot,kt,lt]);return(0,u.jsx)(Jt.Provider,{value:T,children:n})}var jn=({color:e=`#3888FF`})=>(0,u.jsxs)(`svg`,{width:`40`,height:`40`,viewBox:`0 0 40 40`,fill:`none`,xmlns:`http://www.w3.org/2000/svg`,children:[(0,u.jsx)(`rect`,{width:`40`,height:`40`,rx:`20`,fill:e}),(0,u.jsx)(`path`,{d:`M26 8H14C12.3431 8 11 9.34315 11 11V23C11 24.6569 12.3431 26 14 26H26C27.6569 26 29 24.6569 29 23V11C29 9.34315 27.6569 8 26 8Z`,fill:`#ECF0F0`}),(0,u.jsx)(`path`,{d:`M18 32L18 26L24 26L18 32Z`,fill:`#ECF0F0`}),(0,u.jsx)(`path`,{d:`M16.4067 20.5924C16.182 20.3674 16.1822 20.003 16.407 19.7783L22.7805 13.4068C23.0051 13.1821 23.3694 13.1823 23.5939 13.4071V13.4071C23.8182 13.6317 23.8181 13.9956 23.5936 14.2201L17.2212 20.5926C16.9962 20.8176 16.6315 20.8174 16.4067 20.5924V20.5924Z`,fill:`#3E87C8`})]}),Mn=()=>(0,u.jsx)(`svg`,{width:`18`,height:`18`,viewBox:`0 0 24 24`,fill:`none`,xmlns:`http://www.w3.org/2000/svg`,children:(0,u.jsx)(`path`,{d:`M2.01 21L23 12 2.01 3 2 10l15 2-15 2z`,fill:`currentColor`})}),Nn=({size:e=18,color:t=`currentColor`})=>(0,u.jsxs)(`svg`,{width:e,height:e,viewBox:`0 0 24 24`,fill:`none`,xmlns:`http://www.w3.org/2000/svg`,children:[(0,u.jsx)(`path`,{d:`M12 1a4 4 0 014 4v6a4 4 0 01-8 0V5a4 4 0 014-4z`,fill:t}),(0,u.jsx)(`path`,{d:`M19 10a7 7 0 01-14 0M12 19v4M8 23h8`,stroke:t,strokeWidth:`2`,strokeLinecap:`round`,strokeLinejoin:`round`})]}),Pn=({size:e=20})=>(0,u.jsxs)(`svg`,{width:e,height:e,viewBox:`0 0 24 24`,fill:`none`,stroke:`currentColor`,strokeWidth:`2`,strokeLinecap:`round`,strokeLinejoin:`round`,children:[(0,u.jsx)(`path`,{d:`M10.68 13.31a16 16 0 003.41 2.6l1.27-1.27a2 2 0 012.11-.45 12.84 12.84 0 002.81.7 2 2 0 011.72 2v3a2 2 0 01-2.18 2 19.79 19.79 0 01-8.63-3.07A19.42 19.42 0 013.07 8.62 19.79 19.79 0 01.1 2 2 2 0 012.11 0h3a2 2 0 012 1.72c.127.96.361 1.903.7 2.81a2 2 0 01-.45 2.11L6.18 7.84`}),(0,u.jsx)(`line`,{x1:`23`,y1:`1`,x2:`1`,y2:`23`})]}),Fn=()=>(0,u.jsxs)(`svg`,{width:`18`,height:`18`,viewBox:`0 0 24 24`,fill:`none`,stroke:`currentColor`,strokeWidth:`2`,strokeLinecap:`round`,strokeLinejoin:`round`,children:[(0,u.jsx)(`line`,{x1:`12`,y1:`19`,x2:`12`,y2:`5`}),(0,u.jsx)(`polyline`,{points:`5 12 12 5 19 12`})]}),In=()=>(0,u.jsxs)(`svg`,{width:`14`,height:`14`,viewBox:`0 0 24 24`,fill:`none`,stroke:`currentColor`,strokeWidth:`2`,strokeLinecap:`round`,strokeLinejoin:`round`,children:[(0,u.jsx)(`polyline`,{points:`9 17 4 12 9 7`}),(0,u.jsx)(`path`,{d:`M20 18v-2a4 4 0 00-4-4H4`})]}),Ln=()=>(0,u.jsx)(`svg`,{width:`18`,height:`18`,viewBox:`0 0 24 24`,fill:`none`,stroke:`currentColor`,strokeWidth:`2`,strokeLinecap:`round`,strokeLinejoin:`round`,children:(0,u.jsx)(`path`,{d:`M22 16.92v3a2 2 0 01-2.18 2 19.79 19.79 0 01-8.63-3.07 19.42 19.42 0 01-6.12-6.11A19.79 19.79 0 012 4.11 2 2 0 014.11 2h3a2 2 0 012 1.72c.13.96.37 1.91.71 2.81a2 2 0 01-.45 2.11L8.09 9.91a16 16 0 006 6l1.27-1.27a2 2 0 012.11-.45c.9.34 1.85.58 2.81.71A2 2 0 0122 16.92z`})}),Rn=({className:e=``})=>(0,u.jsxs)(`svg`,{className:e,width:`14`,height:`14`,viewBox:`0 0 24 24`,fill:`none`,stroke:`currentColor`,strokeWidth:`2`,strokeLinecap:`round`,strokeLinejoin:`round`,children:[(0,u.jsx)(`circle`,{cx:`12`,cy:`12`,r:`10`}),(0,u.jsx)(`line`,{x1:`12`,y1:`8`,x2:`12`,y2:`12`}),(0,u.jsx)(`line`,{x1:`12`,y1:`16`,x2:`12.01`,y2:`16`})]}),zn=({size:e=18,strokeWidth:t=2.5})=>(0,u.jsxs)(`svg`,{width:e,height:e,viewBox:`0 0 24 24`,fill:`none`,stroke:`currentColor`,strokeWidth:t,strokeLinecap:`round`,strokeLinejoin:`round`,children:[(0,u.jsx)(`line`,{x1:`18`,y1:`6`,x2:`6`,y2:`18`}),(0,u.jsx)(`line`,{x1:`6`,y1:`6`,x2:`18`,y2:`18`})]}),Bn=({size:e=14})=>(0,u.jsxs)(`svg`,{width:e,height:e,viewBox:`0 0 24 24`,fill:`none`,stroke:`currentColor`,strokeWidth:`2`,strokeLinecap:`round`,strokeLinejoin:`round`,children:[(0,u.jsx)(`path`,{d:`M12 8V4H8`}),(0,u.jsx)(`rect`,{width:`16`,height:`12`,x:`4`,y:`8`,rx:`2`}),(0,u.jsx)(`path`,{d:`M2 14h2`}),(0,u.jsx)(`path`,{d:`M20 14h2`}),(0,u.jsx)(`path`,{d:`M15 13v2`}),(0,u.jsx)(`path`,{d:`M9 13v2`})]});function Vn({isOpen:e,openWidget:t,launcherText:n,primaryColor:r,posInline:i}){let[a,o]=(0,l.useState)(!1);return(0,l.useEffect)(()=>{if(typeof window>`u`)return;let e=window.matchMedia(`(max-width: 640px)`),t=e=>{o(e.matches)};return o(e.matches),typeof e.addEventListener==`function`?(e.addEventListener(`change`,t),()=>e.removeEventListener(`change`,t)):(e.addListener(t),()=>e.removeListener(t))},[]),e?null:(0,u.jsxs)(`button`,{type:`button`,onClick:()=>t({notifyChatInitiated:!0}),"aria-label":n,style:{position:`fixed`,...i,zIndex:999999,display:`flex`,alignItems:`center`,justifyContent:`center`,gap:a?`0`:`14px`,width:a?`60px`:`auto`,minWidth:a?`60px`:`unset`,height:a?`60px`:`auto`,padding:a?`0`:`14px 24px`,border:`none`,borderRadius:`9999px`,background:r,color:`#fff`,fontSize:`16px`,fontWeight:`600`,fontFamily:`ui-sans-serif, system-ui, sans-serif`,cursor:`pointer`,boxShadow:`0 8px 24px rgba(0,0,0,0.18)`,transition:`transform 0.2s ease, box-shadow 0.2s ease`,outline:`none`,whiteSpace:`nowrap`},onMouseEnter:e=>{e.currentTarget.style.transform=`translateY(-2px)`,e.currentTarget.style.boxShadow=`0 12px 28px rgba(0,0,0,0.22)`},onMouseLeave:e=>{e.currentTarget.style.transform=`translateY(0)`,e.currentTarget.style.boxShadow=`0 8px 24px rgba(0,0,0,0.18)`},children:[a?null:(0,u.jsx)(`span`,{children:n}),a?(0,u.jsx)(jn,{color:`#fff`}):(0,u.jsx)(`span`,{style:{width:`42px`,height:`42px`,borderRadius:`9999px`,background:`#fff`,color:r,display:`inline-flex`,alignItems:`center`,justifyContent:`center`,flexShrink:0},children:(0,u.jsx)(Mn,{})})]})}function Hn(e){if(!e||typeof e!=`string`)return`?`;let t=e.trim();if(!t)return`?`;let n=t.split(/\s+/).filter(Boolean);return n.length>=2?`${n[0][0]}${n[n.length-1][0]}`.toUpperCase():t.slice(0,2).toUpperCase()}function Un({src:e,name:t,imgStyle:n,initialsSpanStyle:r}){let[i,a]=(0,l.useState)(!1),o=typeof e==`string`?e.trim():``;return(0,l.useEffect)(()=>{a(!1)},[o]),o&&!i?(0,u.jsx)(`img`,{src:o,alt:``,onError:()=>a(!0),style:n}):(0,u.jsx)(`span`,{style:r,children:Hn(t)})}function Wn(e){return typeof e==`string`?e.trim():e&&typeof e==`object`&&typeof e.src==`string`?e.src.trim():``}function Gn(e){let[t,n]=(0,l.useState)(`loading`),r=Wn(e);return(0,l.useEffect)(()=>{if(l.default.isValidElement(e)||typeof e==`function`){n(`square`);return}if(!r){n(`error`);return}n(`loading`);let t=new Image,i=!1;return t.onload=()=>{i||n(t.naturalWidth/t.naturalHeight>1.3?`wide`:`square`)},t.onerror=()=>{i||n(`error`)},t.src=r,()=>{i=!0}},[e,r]),{state:t,resolvedLogoUrl:r}}function Kn({logoUrl:e,brandName:t,agentName:n,fallbackAgentName:r,activeScreen:i,branding:a,isConversationEnded:o,closeWidget:s,isInitial:c,botLabel:d=`AI`,agentAvatarUrl:f=null,primaryColor:p=`#3B82F6`}){let{state:m,resolvedLogoUrl:ee}=Gn(e),h=i===`agent`,g=a?.fallbackAgentName&&String(a.fallbackAgentName).trim()||n||r||`Agent`;return(0,u.jsxs)(`div`,{style:{display:`flex`,justifyContent:`space-between`,alignItems:`center`,padding:`16px 20px`,borderTopLeftRadius:`inherit`,borderTopRightRadius:`inherit`,border:`none`,transition:`all 0.3s ease`,background:c?`transparent`:`#fff`,color:c?`#fff`:`#111827`,boxShadow:c?`none`:`0 1px 0 rgba(0,0,0,0.05), 0 10px 24px rgba(0,0,0,0.04)`,borderBottom:c?`none`:`1px solid rgba(0,0,0,0.05)`},children:[(0,u.jsxs)(`div`,{style:{display:`flex`,alignItems:`center`,gap:`12px`},children:[h?(0,u.jsx)(`div`,{style:{width:`44px`,height:`44px`,borderRadius:`9999px`,flexShrink:0,overflow:`hidden`,display:`flex`,alignItems:`center`,justifyContent:`center`,background:c?`rgba(255,255,255,0.2)`:`#f3f4f6`,color:c?`#fff`:p,fontWeight:800,fontSize:`15px`,border:c?`2px solid rgba(255,255,255,0.35)`:`1px solid rgba(0,0,0,0.06)`},children:(0,u.jsx)(Un,{src:typeof f==`string`?f:``,name:g,imgStyle:{width:`100%`,height:`100%`,objectFit:`cover`},initialsSpanStyle:{lineHeight:1}})}):(0,u.jsxs)(u.Fragment,{children:[m!==`loading`&&(m===`error`||!ee&&!e?(0,u.jsx)(`div`,{className:`flowengage-logo-fallback`,style:{width:`44px`,height:`44px`,borderRadius:`9999px`,flexShrink:0,display:`flex`,alignItems:`center`,justifyContent:`center`,fontWeight:800,fontSize:`15px`,color:`#fff`,border:c?`2px solid rgba(255,255,255,0.35)`:`1px solid rgba(0,0,0,0.06)`},"aria-hidden":!0,children:Hn(t)}):l.default.isValidElement(e)?(0,u.jsx)(`div`,{style:{width:`44px`,height:`44px`,borderRadius:`9999px`,flexShrink:0,overflow:`hidden`,display:`flex`,alignItems:`center`,justifyContent:`center`,background:`#fff`},children:e}):typeof e==`function`?(0,u.jsx)(`div`,{style:{width:`44px`,height:`44px`,borderRadius:`9999px`,flexShrink:0,overflow:`hidden`,display:`flex`,alignItems:`center`,justifyContent:`center`,background:`#fff`},children:(0,u.jsx)(e,{})}):m===`wide`?(0,u.jsx)(`div`,{style:{height:`36px`,maxWidth:`88px`,flexShrink:0,display:`flex`,alignItems:`center`,justifyContent:`center`,borderRadius:`12px`,padding:`4px 8px`,background:c?`rgba(255,255,255,0.15)`:`#f9fafb`,backdropFilter:c?`blur(12px)`:`none`,border:c?`none`:`1px solid rgba(0,0,0,0.05)`},children:(0,u.jsx)(`img`,{src:ee,alt:`Logo`,style:{height:`100%`,width:`auto`,maxWidth:`100%`,objectFit:`contain`}})}):(0,u.jsx)(`div`,{style:{width:`44px`,height:`44px`,borderRadius:`9999px`,flexShrink:0,overflow:`hidden`,display:`flex`,alignItems:`center`,justifyContent:`center`,background:`#fff`},children:(0,u.jsx)(`img`,{src:ee,alt:`Logo`,style:{width:`100%`,height:`100%`,objectFit:`contain`,padding:ee.toLowerCase().includes(`.svg`)||ee.startsWith(`data:image/svg`)?0:`2px`}})})),m===`loading`&&(0,u.jsx)(`div`,{style:{width:`44px`,height:`44px`,borderRadius:`9999px`,background:`rgba(255,255,255,0.2)`,flexShrink:0}})]}),(0,u.jsxs)(`div`,{children:[(0,u.jsxs)(`div`,{style:{display:`flex`,alignItems:`center`,gap:`8px`},children:[(0,u.jsx)(`div`,{style:{fontSize:`16px`,fontWeight:700},children:i===`agent`?g:t}),i!==`agent`&&(0,u.jsxs)(`div`,{style:{display:`flex`,alignItems:`center`,gap:`4px`,borderRadius:`6px`,background:`rgba(255,255,255,0.95)`,padding:`3px 6px`,fontSize:`10px`,fontWeight:800,letterSpacing:`0.5px`,color:`var(--flowengage-primary)`,maxWidth:`140px`,minWidth:0},children:[(0,u.jsx)(`span`,{style:{flexShrink:0,display:`inline-flex`},children:(0,u.jsx)(Bn,{size:11})}),(0,u.jsx)(`span`,{style:{overflow:`hidden`,textOverflow:`ellipsis`,whiteSpace:`nowrap`},children:d})]})]}),(0,u.jsxs)(`div`,{style:{fontSize:`13px`,opacity:.95,marginTop:`2px`},children:[i===`agent`?`Live support`:`Usually replies `,i!==`agent`&&(0,u.jsx)(`span`,{style:{color:`#10b981`,fontWeight:600},children:`instantly`})]})]})]}),(0,u.jsx)(`div`,{style:{display:`flex`,alignItems:`center`,gap:`4px`},children:(0,u.jsx)(`button`,{style:{width:`36px`,height:`36px`,borderRadius:`9999px`,background:`transparent`,display:`flex`,alignItems:`center`,justifyContent:`center`,transition:`all 0.2s ease`,border:0,cursor:`pointer`,color:c?`#fff`:`#000`},onClick:s,"aria-label":`Close chat`,onMouseEnter:e=>{e.currentTarget.style.background=c?`rgba(255,255,255,0.1)`:`rgba(0,0,0,0.05)`},onMouseLeave:e=>{e.currentTarget.style.background=`transparent`},children:(0,u.jsx)(zn,{})})})]})}var qn=(e=``)=>String(e).replace(/<[^>]+>/g,``).replace(/\s+/g,` `).trim(),Jn=(e=``)=>String(e).replace(/&/g,`&`).replace(/</g,`<`).replace(/>/g,`>`).replace(/"/g,`"`).replace(/'/g,`'`);function Yn(e){let t=String(e||``).trim();if(!t)return t;let n=/^<p>\s*<strong>([\s\S]*?)<\/strong>\s*<\/p>$/i.exec(t);if(n&&!/<\/?strong\b/i.test(n[1]))return`<p>${n[1]}</p>`;let r=/^<strong>([\s\S]*?)<\/strong>$/i.exec(t);if(r&&!/<\/?strong\b/i.test(r[1])){let e=r[1].trim();return/^<(?:p|ul|ol)\b/i.test(e)?e:`<p>${e}</p>`}return e}var Xn=(e=``)=>{let t=String(e||``).trim();if(!t)return``;if(/<(p|br|ul|ol|li|strong|em|a)\b/i.test(t))return Yn(t);let n=t.replace(/\r\n/g,`
|
|
25
|
+
`,document.head.appendChild(e)};function nn(e,t){if(typeof document>`u`)return null;if(e){let n=document.getElementById(e)||document.querySelector(`[data-section="${e}"]`);if(n)return n;t||=e.replace(/[-_]+/g,` `).trim()}if(!t)return null;let n=t.toLowerCase().trim(),r=n.split(/\s+/).filter(e=>e.length>2),i=Array.from(document.querySelectorAll(`h1, h2, h3, h4, h5, h6, [data-section]`)).filter(e=>!Xt(e));for(let e of i)if(e.textContent.replace(/\s+/g,` `).toLowerCase().trim()===n)return e;for(let e of i){let t=e.textContent.replace(/\s+/g,` `).toLowerCase().trim();if(t.startsWith(n)||t.endsWith(n))return e}let a=[];for(let e of i){let t=e.textContent.replace(/\s+/g,` `).toLowerCase().trim();t.includes(n)&&a.push({el:e,len:t.length})}if(a.length)return a.sort((e,t)=>e.len-t.len),a[0].el;for(let e of i){let t=e.textContent.replace(/\s+/g,` `).toLowerCase().trim();if(t.length>3&&n.includes(t))return e}if(r.length>0){let e=null,t=0;for(let n of i){let i=n.textContent.replace(/\s+/g,` `).toLowerCase(),a=0;for(let e of r)i.includes(e)&&a++;let o=a/r.length;o>t&&o>=.6&&(t=o,e=n)}if(e)return e}let o=Array.from(document.querySelectorAll(`main [role='group']`)).filter(e=>!Xt(e)),s=[];for(let e of o){let t=e.textContent.replace(/\s+/g,` `).toLowerCase().trim();t.length<15||t.length>8e3||t.includes(n)&&s.push({el:e,len:t.length})}if(s.length)return s.sort((e,t)=>e.len-t.len),s[0].el;if(r.length>0){let e=Array.from(document.querySelectorAll(`main a[href], article a[href], .views-row a[href], h2 a[href], h3 a[href], .card a[href], [class*='teaser'] a[href]`)).filter(e=>{if(Xt(e))return!1;try{let t=e.getAttribute(`href`)||``;if(!t||t===`#`||t.startsWith(`javascript:`))return!1}catch{return!1}let t=e.textContent.replace(/\s+/g,` `).trim();return t.length>=3&&t.length<=220}),t=null,n=0;for(let i of e){let e=i.textContent.replace(/\s+/g,` `).toLowerCase(),a=0;for(let t of r)e.includes(t)&&a++;let o=a/r.length;o>n&&o>=.5&&(n=o,t=i)}if(t)return t.closest(`article`)||t.closest(`.views-row`)||t}let c=document.querySelectorAll(`section, article, .card, [class*='feature'], [class*='service']`);for(let e of c){if(Xt(e))continue;let t=e.querySelector(`h1, h2, h3, h4, h5, h6`);if(t){let r=t.textContent.replace(/\s+/g,` `).toLowerCase().trim();if(r.includes(n)||n.includes(r))return e}}let l=document.querySelectorAll(`li, strong, blockquote, dt`);for(let e of l){if(Xt(e))continue;let t=e.textContent.replace(/\s+/g,` `).toLowerCase().trim();if(t.includes(n)&&t.length<500)return e.tagName===`STRONG`&&e.parentElement?.tagName===`LI`?e.parentElement:e}let u=Array.from(document.querySelectorAll(`a[href]`)).filter(e=>!Xt(e));u.sort((e,t)=>(e.textContent||``).trim().length-(t.textContent||``).trim().length);for(let e of u){let t=e.textContent.replace(/\s+/g,` `).toLowerCase().trim();if(t.includes(n)&&t.length<500)return e}let d=document.querySelectorAll(`p`);for(let e of d){if(Xt(e))continue;let t=e.textContent.replace(/\s+/g,` `).toLowerCase().trim();if(t.includes(n)&&t.length<800)return e}return null}function rn(){return document.querySelector(`[itemprop='articleBody'], .article-body, .post-content, .entry-content, .field--name-body, .field--body, .node__content, article .content, .prose, article .prose`)||document.querySelector(`main article, main, [role='main'], article`)||document.body}var an=new Set(`the.and.for.are.but.not.you.all.can.her.was.one.our.out.day.get.has.him.his.how.its.may.new.now.old.see.two.way.who.did.let.put.say.she.too.use.has.have.this.that.with.from.they.will.your.about.into.than.then.some.very.when.come.here.just.like.also.back.after.over.such.take.only.know.think.each.made.look.more.most.other.well`.split(`.`));function on(e){return String(e||``).toLowerCase().replace(/[^\w\s'-]/g,` `).split(/\s+/).filter(e=>e.length>0)}function sn(e,t){let n=on(e).slice(-Math.min(t,28)),r=n.filter(e=>e.length>2&&!an.has(e));return r.length>=2?r:n.filter(e=>e.length>2).slice(-12)}function cn(e,t,{strict:n=!1}={}){if(!e||!t?.length)return null;let r=e.querySelectorAll([`h1, h2, h3, h4, h5, h6, p, li, blockquote`,`main h2, main h3, main h4, article h2, article h3, article h4`,`section h2, section h3, section h4`].join(`, `)),i=null,a=0;for(let e of r){if(Xt(e))continue;try{if(e.closest(`aside, nav, [role='navigation'], [role='banner'], footer`))continue}catch{}let n=e.textContent.replace(/\s+/g,` `).toLowerCase();if(n.length<3||n.length>6e3)continue;let r=0;for(let e of t)n.includes(e)&&r++;let o=r/t.length;if(o<.2)continue;let s=o,c=e.tagName;(c===`H2`||c===`H3`||c===`H4`)&&(s*=1.35),(c===`P`||c===`BLOCKQUOTE`)&&(s*=1.15),c?.startsWith(`H`)&&n.length<80&&(s*=1.2),n.length>400&&(s*=.65),s>a&&(a=s,i=e)}let o=n?t.length<=1?.62:.5:t.length<=1?.55:.35;return a>=o?i:null}function ln(e,t,{strict:n=!1}={}){if(!e||!t?.length)return null;let r=e.querySelectorAll([`main [role='group']`,`[class*='card']`,`[class*='Card']`,`[class*='column']`,`[class*='grid'] > div`,`[class*='grid'] > article`,`[data-section]`].join(`, `)),i=null,a=0;for(let e of r){if(Xt(e))continue;try{if(e.closest(`aside, nav, [role='navigation'], [role='banner'], footer`))continue}catch{}let n=e.textContent.replace(/\s+/g,` `).toLowerCase();if(n.length<10||n.length>9e3)continue;let r=0;for(let e of t)e.length>1&&n.includes(e)&&r++;let o=r/t.length;if(o<.12)continue;let s=o,c=e.tagName;(c===`ARTICLE`||c===`SECTION`)&&(s*=1.05),n.length<900&&(s*=1.18),n.length<420&&(s*=1.12),n.length>2600?s*=.28:n.length>1400&&(s*=.45);try{e.querySelectorAll(`:scope > [role='group'], :scope > article, :scope > section`).length>=3&&n.length>1200&&(s*=.3)}catch{}s>a&&(a=s,i=e)}let o=n?t.length<=1?.48:.34:t.length<=1?.38:.2;return a>=o?i:null}function un(e){return/^H[1-6]$/i.test(e?.tagName||``)}function dn(e,t,n=!1){if(!e||!t)return null;let r=t.replace(/\s+/g,` `).trim();if(r.length<14)return null;let i=n?.34:.24,a=r.toLowerCase(),o=sn(r,24);if(o.length<3&&(o=a.replace(/[^\w\s'-]/g,` `).split(/\s+/).filter(e=>e.length>2).slice(-18)),o.length<3)return null;let s=e.querySelectorAll(`p, blockquote`),c=null,l=0;for(let e of s){if(Xt(e))continue;let t=e.textContent.replace(/\s+/g,` `).toLowerCase();if(t.length<24)continue;let n=0;for(let e of o)t.includes(e)&&n++;let r=n/o.length,s=0;for(let e=Math.min(90,a.length);e>=22;e-=6){let n=a.slice(-e).trim();if(n.length>=22&&t.includes(n)){s=.28;break}}let u=r+s;u>l&&r>=i&&(l=u,c=e)}return c}function fn(e,t={}){if(typeof document>`u`||!e||!String(e).trim())return null;let n=t.strict===!0,r=String(e).trim(),i=r.length>450?r.slice(-450).trim():r,a=rn(),o=sn(r,26);if(o.length>=1&&(o.length>=2||o.length===1&&o[0].length>=3)){let e=ln(a,o,{strict:n});if(e)return e}if(r.length>=(n?55:42)){let e=dn(a,i,n);if(e)return e}if((!n||o.length>=3||o.length===2&&o.every(e=>e.length>=5))&&(o.length>=2||o.length===1&&o[0].length>=5)){let e=cn(a,o,{strict:n});if(e)return e}let s=i.split(/(?<=[.!?])\s+/).filter(e=>e.trim().length>0),c=s[s.length-1]||i,l=c.toLowerCase().replace(/[^\w\s'-]/g,` `).split(/\s+/).filter(e=>e.length>2),u=[];c.length>=10&&(u.push(c.slice(-220).trim()),c.length>220&&u.push(c.slice(0,120).trim()));for(let e=4;e<=Math.min(10,l.length);e++)u.push(l.slice(-e).join(` `));for(let e=Math.min(14,l.length);e>=11;e--)u.push(l.slice(-e).join(` `));for(let e=Math.min(8,l.length);e>=3;e--)u.push(l.slice(-e).join(` `));let d=n?14:6,f=new Set;for(let e of u){let t=e.trim();if(t.length<d||f.has(t))continue;f.add(t);let n=nn(null,t);if(n&&!Xt(n)){if(un(n)&&r.length>140){let e=(a.querySelector?.(`[itemprop='articleBody'], .article-body, .post-content, .entry-content`)||a).querySelectorAll?.(`p, blockquote`)||[];for(let n of e)if(!Xt(n)&&n.textContent.toLowerCase().includes(t.toLowerCase().slice(0,Math.min(48,t.length))))return n}return n}}let p=o.length>=3?o:l.slice(-22);if(p.length===0)return null;let m=null,ee=-1,h=a.querySelectorAll(`h1, h2, h3, h4, h5, h6, p, li, blockquote, article`);for(let e of h){if(Xt(e))continue;try{if(e.closest(`aside, nav, [role='navigation'], footer`))continue}catch{}let t=e.textContent.toLowerCase();if(t.length<12)continue;let i=0;for(let e of p)e.length>2&&t.includes(e)&&i++;let a=i/p.length,o=e.tagName;(o===`P`||o===`BLOCKQUOTE`||o===`LI`)&&(a*=1.22),un(e)&&(r.length>110?a*=.48:a*=.92),o===`ARTICLE`&&r.length>80&&(a*=.55),a>ee&&a>=(n?.42:.28)&&(ee=a,m=e)}return m}function pn(e){if(!e||typeof document>`u`)return null;try{if(Xt(e))return e;let t=e.closest?.([`[role='group']`,`[class*='card']`,`[class*='Card']`,`[data-section]`,`[class*='grid'] > div`,`[class*='grid'] > article`].join(`, `)),n=t?.textContent?.replace(/\s+/g,` `)||``;if(t&&!Xt(t)&&n.length>20&&n.length<=5200)return t;let r=e.closest?.(`p, li, blockquote, td, th, dd, figcaption, pre`);if(r&&!Xt(r))return r;let i=e.closest?.(`section`),a=i?.textContent?.replace(/\s+/g,` `)||``;return i&&a.length>48&&a.length<=4e3&&!Xt(i)?i:e}catch{return e}}function mn(e){if(!e||typeof e.getBoundingClientRect!=`function`)return!0;try{let t=e.getBoundingClientRect(),n=window.innerHeight||800;if(t.bottom<=72||t.top>=n-72)return!0;let r=Math.max(0,t.top),i=Math.min(n,t.bottom),a=Math.max(0,i-r),o=Math.min(120,Math.max(40,t.height*.28));return t.height>24&&a<o}catch{return!0}}function hn(e,{speaking:t=!1,scroll:n=!0}={}){if(!e||typeof document>`u`)return;tn();let r=document.querySelectorAll(`.fe-highlight-section`);for(let t of r)t!==e&&(t.classList.remove(`fe-highlight-section`,`fe-highlight-speaking`),t.classList.add(`fe-highlight-exiting`),setTimeout(()=>t.classList.remove(`fe-highlight-exiting`),300));if(e.classList.remove(`fe-highlight-exiting`),e.classList.add(`fe-highlight-section`),t?e.classList.add(`fe-highlight-speaking`):e.classList.remove(`fe-highlight-speaking`),n)try{e.scrollIntoView({behavior:`smooth`,block:`center`})}catch{try{e.scrollIntoView(!0)}catch{}}}function gn(){typeof document>`u`||document.querySelectorAll(`.fe-highlight-section, .fe-highlight-exiting`).forEach(e=>e.classList.remove(`fe-highlight-section`,`fe-highlight-speaking`,`fe-highlight-exiting`))}function _n(e){if(typeof window>`u`)return e;try{let t=new URL(String(e).trim(),window.location.href);return!/^https?:$/i.test(t.protocol)||t.origin===window.location.origin?t.href:new URL(t.pathname+t.search+t.hash,window.location.origin).href}catch{return e}}async function vn(e){if(typeof window>`u`)return!1;try{let t=new URL(String(e).trim(),window.location.href);return t.origin===window.location.origin?(await fetch(t.href,{method:`HEAD`,mode:`same-origin`,cache:`no-store`})).ok:!1}catch{return!1}}async function yn(e,{siteId:t,apiBaseUrl:n}){if(!e)return!1;if(!t||!n)return console.warn(`[FlowEngage] shouldProceedWithNavigation: missing siteId or apiBaseUrl`),!1;let r=String(n).replace(/\/$/,``),i=new URLSearchParams({siteId:String(t),url:String(e).trim()});try{let t=await(await fetch(`${r}/api/widget/navigate-allowed?${i.toString()}`)).json().catch(()=>({}));return t.success?t.allowed?!0:t.hasIndex===!1?vn(e):!1:!1}catch(e){return console.warn(`[FlowEngage] navigate-allowed check failed:`,e?.message),!1}}function bn(e){if(!(!e||typeof sessionStorage>`u`))try{sessionStorage.setItem(Qt,JSON.stringify({sectionText:e,ts:Date.now()}))}catch{}}async function xn(e,t={}){if(typeof window>`u`)return!1;let{sectionText:n}=t;try{let t=_n(e),r=new URL(t,window.location.origin);if(Zt(`input:`,e,`→ normalized:`,t,`href:`,r.href),r.hash&&r.pathname===window.location.pathname){let e=r.hash.slice(1),t=document.getElementById(e);if(t)return Zt(`branch: hash scroll (same path)`),t.scrollIntoView({behavior:`smooth`,block:`start`}),!0}if(r.pathname===window.location.pathname&&r.search===window.location.search&&!r.hash)return Zt(`branch: already on page (no nav)`),!1;let i=r.pathname+r.search+r.hash,a=window.next?.router;if(a?.push)return Zt(`branch: Next.js Pages router.push`,i),new Promise(e=>{let t=()=>{a.events?.off(`routeChangeComplete`,t),e(!0)};a.events?.on(`routeChangeComplete`,t),a.push(i),setTimeout(t,5e3)});let o=window.__NEXT_ROUTER__;return o?.push?(Zt(`branch: __NEXT_ROUTER__.push`,i),o.push(i),!0):(n?(bn(n),Zt(`branch: location.assign (full navigation, section stored):`,n)):Zt(`branch: location.assign (full navigation)`,r.href),window.location.assign(r.href),!0)}catch(t){console.warn(`[FlowEngage] shadowNavigate error:`,t),n&&bn(n);try{window.location.href=_n(e)}catch{window.location.href=e}return!0}}var Sn=e=>!e||typeof e!=`string`?e:e.replace(/<human_assistance_request>[\s\S]*?<\/human_assistance_request>/gi,``).replace(/<human_assistance_request>/gi,``).replace(/<\/human_assistance_request>/gi,``).replace(/<navigate[^>]*\/>/gi,``).replace(/<navigate[^>]*>[\s\S]*?<\/navigate>/gi,``).replace(/<[a-z]+(?:_[a-z]+)+[^>]*>[\s\S]*?<\/[a-z]+(?:_[a-z]+)+>/gi,``).replace(/<[a-z]+(?:_[a-z]+)+[^>]*\/>/gi,``).trim(),Cn=(e,t)=>!t||e.sender!==`bot`&&e.sender!==`ai`?e:{...e,sender:`agent`,agent_name:e.agent_name||e.agentName||e.metadata?.agentName||void 0},wn=(e=[],t=!1)=>e.map(e=>Cn({...e,message:Sn(e.message),isPending:!1,id:e.messageId||`${e.sender}-${e.timestamp||Date.now()}-${Math.random()}`},t)),Tn=(e,t)=>e?typeof e==`string`?e:e.message||e.error||e.reason||t:t,En=(e={})=>{if(!e?.candidate)return null;if(typeof e.candidate==`object`)return e.candidate;let t=e.sdpMid!==void 0&&e.sdpMid!==null&&e.sdpMid!==``,n=e.sdpMLineIndex!==void 0&&e.sdpMLineIndex!==null;return!t&&!n?null:{candidate:e.candidate,...t?{sdpMid:e.sdpMid}:{},...n?{sdpMLineIndex:e.sdpMLineIndex}:{}}},Dn=e=>{if(!e)return null;let t=typeof e==`object`?e:{candidate:e};return{hasCandidate:!!t.candidate,sdpMid:t.sdpMid??null,sdpMLineIndex:t.sdpMLineIndex??null,candidatePreview:typeof t.candidate==`string`?t.candidate.slice(0,80):null}},On=(e=[],t=`Agent`)=>{for(let t of e)if(typeof t==`string`&&t.trim())return t.trim();return t},kn=(e=[],t)=>typeof t==`string`&&t.trim()?t.trim():On(e,`Agent`);function An({siteId:e,config:t,children:n,language:r=`en`}){let i=(0,l.useMemo)(()=>e?{...t||{},siteId:e}:t||null,[e,t]),[a,o]=(0,l.useState)(`booting`),[s,c]=(0,l.useState)(null),[f,p]=(0,l.useState)(null),g=(0,l.useMemo)(()=>{let e=f?.widgetSettings?.branding?.fallbackAgentName??i?.widgetSettings?.branding?.fallbackAgentName;return typeof e==`string`&&e.trim()?e.trim():null},[i,f]),te=(0,l.useRef)(null);(0,l.useEffect)(()=>{te.current=g},[g]);let[_,v]=(0,l.useState)(``),[le,y]=(0,l.useState)([]),[ue,de]=(0,l.useState)(re().isOpen),[fe,pe]=(0,l.useState)(re().activeScreen),[me,he]=(0,l.useState)(re().isHumanHandled),[ge,_e]=(0,l.useState)(re().agentName),[ve,ye]=(0,l.useState)(re().agentHeadshot),[be,xe]=(0,l.useState)(()=>ae(i?.siteId)),[Se,Ce]=(0,l.useState)(!1),[we,Te]=(0,l.useState)(!1),[Ee,De]=(0,l.useState)(`idle`),[Oe,ke]=(0,l.useState)(!1),[Ae,je]=(0,l.useState)(!1),[Me,Ne]=(0,l.useState)(``),[b,Pe]=(0,l.useState)(!1),[Fe,Ie]=(0,l.useState)(!1),[x,S]=(0,l.useState)(null),[Le,Re]=(0,l.useState)(null),[ze,Be]=(0,l.useState)(`idle`),[Ve,He]=(0,l.useState)(null),[Ue,We]=(0,l.useState)(!1),[Ge,Ke]=(0,l.useState)(``),C=(0,l.useRef)(null),w=(0,l.useRef)(null),T=(0,l.useRef)(``),qe=(0,l.useRef)(null),Je=(0,l.useRef)(null),Ye=(0,l.useRef)(null),Xe=(0,l.useRef)(null),Ze=(0,l.useRef)(null),Qe=(0,l.useRef)([]),$e=(0,l.useRef)(null),et=(0,l.useRef)(null),tt=(0,l.useRef)(!1),nt=(0,l.useRef)(!1),rt=(0,l.useRef)(``),it=(0,l.useRef)(ge),at=(0,l.useRef)(me),ot=(0,l.useRef)([]),st=(0,l.useRef)(!1),ct=(0,l.useRef)({notifyRouteChange:()=>{},cleanup:()=>{}}),lt=(0,l.useMemo)(()=>{let e=f?.widgetSettings?.call?.maxDurationSeconds??i?.widgetSettings?.call?.maxDurationSeconds??i?.callMaxDurationSeconds,t=Number(e);return Number.isFinite(t)&&t>0?t:ee},[i,f]);(0,l.useEffect)(()=>{qe.current=x},[x]),(0,l.useEffect)(()=>{it.current=ge},[ge]),(0,l.useEffect)(()=>{at.current=me},[me]);let ut=()=>{Ke(``)},dt=e=>{let t=typeof e==`string`?e.trim().toLowerCase():``;return xe(t),oe(t,i?.siteId),t};(0,l.useEffect)(()=>{let e=i?.siteId;e&&xe(ae(e))},[i?.siteId]);let ft=()=>{Je.current&&=(Je.current.close(),null),Ye.current&&=(Ye.current.getTracks().forEach(e=>e.stop()),null),Xe.current&&=(Xe.current.srcObject=null,Xe.current.remove(),null),Ze.current=null,Qe.current=[],$e.current=null,et.current=null,tt.current=!1,We(!1),S(null),Re(null),Be(`idle`),He(null)},pt=(e=new Date().toISOString())=>{let t=C.current,n=$e.current||Ze.current?.callId;if(!t?.connected||!n||tt.current){console.log(`[FlowEngageProvider] skipping call:connected emit`,{callId:n,chatId:T.current,socketConnected:!!t?.connected,alreadyReported:tt.current});return}console.log(`[FlowEngageProvider] emitting call:connected`,{callId:n,chatId:T.current,connectedAt:e}),tt.current=!0,t.emit(`call:connected`,{callId:n,chatId:T.current,connectedAt:e})},mt=(e={})=>{if(!e.callId)return;let t=et.current===e.callId,n=$e.current===e.callId,r=qe.current?.callId===e.callId;if(!(!t&&!n&&!r)){if(console.log(`[FlowEngageProvider] syncing accepted call state`,{callId:e.callId,chatId:e.chatId||T.current,isAcceptingHere:t,isAlreadyActive:n,isIncomingHere:r}),S(null),t||n){$e.current=e.callId,Re(e.callId),Be(e=>e===`connected`?e:`connecting`),de(!0);return}Be(`idle`)}},ht=(e={})=>{if(!e.callId)return;let t=et.current===e.callId,n=$e.current===e.callId,r=qe.current?.callId===e.callId;if(!(!t&&!n&&!r)){if(console.log(`[FlowEngageProvider] syncing ended incoming call state`,{callId:e.callId,chatId:e.chatId||T.current,isAcceptingHere:t,isAlreadyActive:n,isIncomingHere:r,reason:e.reason||e.status||null}),n){ft();return}et.current=null,Ze.current=null,Qe.current=[],S(null),Be(`idle`)}},gt=async(e={})=>{let t=Je.current,n=C.current,r=e.sdpOffer||e.offer?.sdp;if(!t||!n?.connected||!r||!e.callId){console.log(`[FlowEngageProvider] deferring remote offer until peer/socket ready`,{callId:e.callId,chatId:T.current,hasPeerConnection:!!t,socketConnected:!!n?.connected,hasOffer:!!r}),Ze.current=e;return}if(console.log(`[FlowEngageProvider] applying remote offer`,{callId:e.callId,chatId:T.current,offerLength:r.length,signalingState:t.signalingState}),await t.setRemoteDescription(new RTCSessionDescription({type:`offer`,sdp:r})),Qe.current.length>0){console.log(`[FlowEngageProvider] flushing queued agent ICE candidates after remote offer`,{callId:e.callId,chatId:T.current,queuedCount:Qe.current.length});for(let e of Qe.current)await t.addIceCandidate(new RTCIceCandidate(e));Qe.current=[]}let i=await t.createAnswer();await t.setLocalDescription(i),console.log(`[FlowEngageProvider] created local answer`,{callId:e.callId,chatId:T.current,answerLength:i.sdp?.length||0,signalingState:t.signalingState}),n.emit(`call:answer`,{callId:e.callId,sdpAnswer:i.sdp,chatId:T.current})};(0,l.useEffect)(()=>{ie({isOpen:ue,activeScreen:fe,isHumanHandled:me,agentName:ge,agentHeadshot:ve})},[ue,fe,me,ge,ve]),(0,l.useEffect)(()=>{let e=!0;return(async()=>{try{console.log(`[FlowEngageProvider] boot start`,{resolvedConfig:i,language:r});let t=d(i);console.log(`[FlowEngageProvider] config validated`,t);let n=await se(t);if(!e)return;let a=ne();T.current=a;let s=ce({apiBaseUrl:t.apiBaseUrl,userId:n.userId,siteId:t.siteId});w.current=s,p({...n,apiBaseUrl:t.apiBaseUrl}),v(a),console.log(`[FlowEngageProvider] bootstrap resolved`,{bootstrapData:n,resolvedChatId:a});let c=Gt({apiBaseUrl:t.apiBaseUrl,userId:n.userId,chatId:a,siteId:t.siteId});C.current=c,c.on(`connect`,()=>{console.log(`[FlowEngageProvider] socket connected`),De(`connected`)}),c.on(`disconnect`,()=>{console.log(`[FlowEngageProvider] socket disconnected`),De(`disconnected`)}),c.on(`aiTyping`,()=>{console.log(`[FlowEngageProvider] received aiTyping`,{chatId:T.current}),Te(!0)}),c.on(`ai:typing`,()=>{console.log(`[FlowEngageProvider] received ai:typing`,{chatId:T.current}),Te(!0)}),c.on(`messageReceived`,e=>{let t=e.message||e,n={...t,message:Sn(t.message)};(n.sender===`bot`||n.sender===`ai`)&&(at.current||typeof n.agent_name==`string`&&n.agent_name.trim()||typeof n.agentName==`string`&&n.agentName.trim())&&(n={...n,sender:`agent`,agent_name:n.agent_name||n.agentName||it.current||void 0}),Te(!1),Ce(!1),y(e=>[...e.filter(e=>!e.isPending),{...n,isPending:!1,id:n.messageId||`${n.sender}-${Date.now()}-${Math.random()}`}])}),c.on(`conversationStarted`,e=>{console.log(`[FlowEngageProvider] conversationStarted`,e),e?.message&&y(t=>[...t,{id:`system-start-${Date.now()}`,sender:`system`,message:e.message,timestamp:new Date().toISOString(),isPending:!1}])}),c.on(`message:new`,e=>{let t=e.message||e,n={...t,message:Sn(t.message)};(n.sender===`bot`||n.sender===`ai`)&&(at.current||typeof n.agent_name==`string`&&n.agent_name.trim()||typeof n.agentName==`string`&&n.agentName.trim())&&(n={...n,sender:`agent`,agent_name:n.agent_name||n.agentName||it.current||void 0}),Te(!1),(n.sender===`agent`||n.agent_name||n.sender===`ai`||n.sender===`bot`)&&Ce(!1),y(e=>n.sender===`bot`||n.sender===`ai`?[...e,{...n,isPending:!1,id:n.messageId||`${n.sender}-${Date.now()}-${Math.random()}`}]:e.some(e=>e.id===n.messageId||e.sender===n.sender&&e.message===n.message&&e.isPending)?e.map(e=>e.sender===n.sender&&e.message===n.message&&e.isPending?{...n,isPending:!1,id:n.messageId||e.id}:e):[...e,{...n,isPending:!1,id:n.messageId||`${n.sender}-${Date.now()}-${Math.random()}`}]),(n.sender===`agent`||n.agent_name)&&(he(!0),pe(`agent`),_e(kn([n.agent_name,n.agentName,n.metadata?.agentName],te.current)),n.sender_headshot&&ye(n.sender_headshot),de(!0))}),c.on(`agent:joined`,e=>{let t=kn([e.agent?.name,e.agentName],te.current);he(!0),pe(`agent`),_e(t),ye(e.agent?.headshot||null),de(!0),y(e=>[...e,{id:`agent-joined-${Date.now()}`,sender:`system`,message:`${t} has joined the chat.`,timestamp:new Date().toISOString(),isPending:!1}])}),c.on(`agentJoined`,e=>{let t=kn([e.agent?.name,e.agentName],te.current);he(!0),pe(`agent`),_e(t),ye(e.agent?.headshot||null),de(!0),y(e=>[...e,{id:`agent-joined-${Date.now()}`,sender:`system`,message:`${t} has joined the chat.`,timestamp:new Date().toISOString(),isPending:!1}])}),c.on(`agent:left`,(e={})=>{let t=kn([e.agent?.name,e.agentName,it.current],te.current);he(!1),pe(`ai`),y(e=>[...e,{id:`agent-left-${Date.now()}`,sender:`system`,message:`${t} has left the chat.`,timestamp:new Date().toISOString(),isPending:!1}])}),c.on(`agentLeft`,(e={})=>{let t=kn([e.agent?.name,e.agentName,it.current],te.current);he(!1),pe(`ai`),y(e=>[...e,{id:`agent-left-${Date.now()}`,sender:`system`,message:`${t} has left the chat.`,timestamp:new Date().toISOString(),isPending:!1}])}),c.on(`conversationEnded`,e=>{Ie(!0);let t=e?.message||`This conversation has ended. Thank you for reaching out!`;y(e=>[...e,{id:`conversation-ended-${Date.now()}`,sender:`system`,message:t,timestamp:new Date().toISOString(),isPending:!1}])}),c.on(`chat:history_update`,e=>{y(wn(e.chat_history||[],at.current))}),c.on(`typing:start`,e=>{console.log(`[FlowEngageProvider] received typing:start`,{chatId:e?.chatId||T.current,sender:e?.sender}),e.sender===`agent`&&Ce(!0)}),c.on(`typing:stop`,e=>{console.log(`[FlowEngageProvider] received typing:stop`,{chatId:e?.chatId||T.current,sender:e?.sender}),e.sender===`agent`&&Ce(!1)}),c.on(`call:incoming`,(e={})=>{let t=kn([e.agentName,e.ownerName,e.agent?.name,it.current],te.current);console.log(`[FlowEngageProvider] received call:incoming`,{callId:e.callId,chatId:T.current,agentName:t}),ut(),tt.current=!1,S({callId:e.callId,from:e.from||`owner`,agentId:e.agentId||null,agentName:t}),_e(e=>kn([t,e],te.current)),Be(`incoming`),He(null),de(!0)}),c.on(`call:offer`,async(e={})=>{console.log(`[FlowEngageProvider] received call:offer`,{callId:e.callId,chatId:e.chatId||T.current,offerLength:(e.sdpOffer||e.offer?.sdp||``).length}),Ze.current=e;try{await gt(e)}catch(e){console.error(`[FlowEngageProvider] failed to apply remote offer`,e)}}),c.on(`call:ice-candidate-from-agent`,async(e={})=>{if(!e.candidate){console.log(`[FlowEngageProvider] skipping agent ICE candidate`,{callId:e.callId,chatId:e.chatId||T.current,hasPeerConnection:!!Je.current,hasCandidate:!!e.candidate});return}try{let t=En(e);if(!t){console.warn(`[FlowEngageProvider] ignoring invalid ICE candidate payload`,e);return}if(console.log(`[FlowEngageProvider] adding agent ICE candidate`,{callId:e.callId,chatId:e.chatId||T.current,candidate:Dn(t),hasRemoteDescription:!!Je.current?.remoteDescription}),!Je.current||!Je.current.remoteDescription){console.log(`[FlowEngageProvider] queueing agent ICE candidate until peer/remote description is ready`,{callId:e.callId,chatId:e.chatId||T.current,queueSize:Qe.current.length+1}),Qe.current.push(t);return}await Je.current.addIceCandidate(new RTCIceCandidate(t))}catch(e){console.error(`[FlowEngageProvider] failed to add ICE candidate`,e)}}),c.on(`call:ended`,()=>{ut(),ft()}),c.on(`call:accepted`,(e={})=>{console.log(`[FlowEngageProvider] received call:accepted`,{callId:e.callId,chatId:e.chatId||T.current}),mt(e)}),c.on(`call:accepted_by_other`,(e={})=>{console.log(`[FlowEngageProvider] received call:accepted_by_other`,{callId:e.callId,chatId:e.chatId||T.current}),mt(e)}),c.on(`call:rejected`,(e={})=>{console.log(`[FlowEngageProvider] received call:rejected`,{callId:e.callId,chatId:e.chatId||T.current,reason:e.reason}),ht(e)}),c.on(`call:missed`,(e={})=>{console.log(`[FlowEngageProvider] received call:missed`,{callId:e.callId,chatId:e.chatId||T.current,reason:e.reason}),ht(e)}),c.on(`call:failed`,(e={})=>{console.log(`[FlowEngageProvider] received call:failed`,{callId:e.callId,chatId:e.chatId||T.current,reason:e.reason}),ht(e)}),c.on(`call:connected`,(e={})=>{if(!e.callId)return;let t=et.current===e.callId,n=$e.current===e.callId,r=Ze.current?.callId===e.callId,i=qe.current?.callId===e.callId;if(console.log(`[FlowEngageProvider] received call:connected`,{callId:e.callId,chatId:e.chatId||T.current,connectedAt:e.connectedAt,status:e.status,isAcceptingHere:t,isAlreadyActive:n,isPendingOfferHere:r,isIncomingHere:i}),!t&&!n&&!r){i&&(S(null),Be(`idle`));return}tt.current=!0,et.current=null,$e.current=e.callId,Re(e.callId),S(null),Be(`connected`),He(e.connectedAt||new Date().toISOString()),de(!0)}),c.on(`call:unavailable`,(e={})=>{ft(),Ke(Tn(e,`This visitor is not available for a call right now.`)),de(!0)}),c.on(`call:error`,(e={})=>{ft(),Ke(Tn(e,`We couldn't connect the call right now.`)),de(!0)}),c.on(`visitor:navigate`,async({url:e,section:n,highlight:r}={})=>{if(e){if(console.log(`[FlowEngageProvider] visitor:navigate`,{url:e,section:n,highlight:r}),!await yn(e,{siteId:t.siteId,apiBaseUrl:t.apiBaseUrl})){console.warn(`[FlowEngageProvider] visitor:navigate blocked (not indexed)`,e);return}xn(e).then(e=>{let t=n||r;t&&setTimeout(()=>{let e=nn(null,t);e&&hn(e)},e?300:150)})}}),c.on(`visitor:highlight`,({sectionId:e,sectionText:t}={})=>{if(!e&&!t)return;console.log(`[FlowEngageProvider] visitor:highlight`,{sectionId:e,sectionText:t});let n=nn(e||null,t||null);n&&hn(n)}),c.on(`visitor:clear_highlight`,()=>{gn()}),ct.current=Kt({socket:c,chatId:a}),console.log(`[FlowEngageProvider] tracking started`,{chatId:a});let l=await s.loadHistory(a,r);if(console.log(`[FlowEngageProvider] history loaded`,l),!e||(y(wn(l.chat_history||[],!!l.is_human_handled)),he(!!l.is_human_handled),pe(l.is_human_handled?`agent`:fe),await new Promise(e=>setTimeout(e,500)),!e))return;o(`ready`),console.log(`[FlowEngageProvider] status ready`)}catch(t){if(!e)return;console.error(`[FlowEngageProvider] boot failed`,t),c(t),o(`error`)}})(),()=>{e=!1,ct.current?.cleanup?.(),ft(),C.current?.disconnect()}},[i,r]),(0,l.useEffect)(()=>()=>{if(b&&!st.current&&ot.current.length>0){let e=T.current,t=ot.current,n=w.current;n&&e&&t.length>0&&(console.log(`[FlowEngageProvider] safety-net: syncing voice transcript on unmount`),n.beaconSyncVoice(e,t)||n.syncVoice(e,t).catch(()=>{}),st.current=!0)}},[b,f]),(0,l.useEffect)(()=>{if(!w.current||!_||a!==`ready`||me)return;let e=window.setInterval(async()=>{try{let e=await w.current.checkHumanHandled(_);he(!!e.is_human_handled),e.is_human_handled&&(pe(`agent`),e.agent_info?.name&&_e(kn([e.agent_info.name],g)),e.agent_info?.headshot&&ye(e.agent_info.headshot))}catch{}},1e4);return()=>window.clearInterval(e)},[_,a,me,g]),(0,l.useEffect)(()=>{!g||!me||_e(e=>kn([e],g))},[g,me]);let _t=async()=>{if(!(!x?.callId||!w.current||!C.current||!_)){ut(),et.current=x.callId,console.log(`[FlowEngageProvider] acceptCall started`,{callId:x?.callId,chatId:_,socketConnected:!!C.current?.connected,hasPendingOffer:!!Ze.current});try{let e=await navigator.mediaDevices.getUserMedia({audio:!0});console.log(`[FlowEngageProvider] microphone stream acquired`,{callId:x.callId,chatId:_,trackCount:e.getTracks().length}),Ye.current=e;let t=new RTCPeerConnection({iceServers:[{urls:`stun:stun.l.google.com:19302`}]});Je.current=t,t.onconnectionstatechange=()=>{let e=t.connectionState;if(console.log(`[FlowEngageProvider] peer connection state changed`,{callId:x.callId,chatId:_,connectionState:e,iceConnectionState:t.iceConnectionState,signalingState:t.signalingState}),e===`connected`){let e=new Date().toISOString();Be(`connected`),He(t=>t||e),pt(e);return}e===`connecting`&&Be(e=>e===`connected`?e:`connecting`)},t.oniceconnectionstatechange=()=>{let e=t.iceConnectionState;if(console.log(`[FlowEngageProvider] ICE connection state changed`,{callId:x.callId,chatId:_,iceConnectionState:e,connectionState:t.connectionState,signalingState:t.signalingState}),e===`connected`||e===`completed`){let e=new Date().toISOString();Be(`connected`),He(t=>t||e),pt(e);return}(e===`checking`||e===`new`)&&Be(e=>e===`connected`?e:`connecting`)},e.getTracks().forEach(n=>{t.addTrack(n,e)}),t.onicecandidate=e=>{if(!e.candidate||!C.current?.connected){console.log(`[FlowEngageProvider] local ICE candidate skipped`,{callId:x.callId,chatId:_,hasCandidate:!!e.candidate,socketConnected:!!C.current?.connected});return}console.log(`[FlowEngageProvider] emitting local ICE candidate`,{callId:x.callId,chatId:_,candidate:Dn(e.candidate)}),C.current.emit(`call:ice-candidate`,{callId:x.callId,candidate:e.candidate,chatId:_,from:`customer`})},t.ontrack=e=>{if(console.log(`[FlowEngageProvider] remote audio track received`,{callId:x.callId,chatId:_,streamCount:e.streams?.length||0}),!Xe.current){let e=document.createElement(`audio`);e.id=`flowengage-remote-audio`,e.autoplay=!0,Xe.current=e,document.body.appendChild(e)}Xe.current.srcObject=e.streams[0];let t=x?.callId,n=t&&(et.current===t||$e.current===t);if(!tt.current&&n){let e=new Date().toISOString();Be(`connected`),He(t=>t||e),$e.current=t,Re(t),pt(e)}};let n=Ze.current;n&&(console.log(`[FlowEngageProvider] found pending remote offer during accept`,{callId:n.callId||x.callId,chatId:_}),await gt({...n,callId:n.callId||x.callId})),await w.current.acceptCall(x.callId,_),console.log(`[FlowEngageProvider] acceptCall API succeeded`,{callId:x.callId,chatId:_}),$e.current=x.callId,Re(x.callId),Be(e=>e===`connected`||tt.current?`connected`:`connecting`),S(null),de(!0)}catch(e){if(console.error(`[FlowEngageProvider] acceptCall failed`,e),et.current=null,ft(),e?.status===404||e?.status===409||e?.status===422){Ke(Tn(e,`This visitor call is no longer available.`));return}if(e?.name===`NotAllowedError`||e?.name===`PermissionDeniedError`){try{await w.current.rejectCall(x.callId,_)}catch(e){console.error(`[FlowEngageProvider] failed to reject call after microphone denial`,e)}Ke(`Microphone access was denied. Please allow microphone access to accept the call.`);return}Ke(`We couldn't connect the call right now. Please try again.`)}}},vt=async()=>{if(!x?.callId||!w.current||!_){ft();return}ut();try{await w.current.rejectCall(x.callId,_)}catch(e){console.error(`[FlowEngageProvider] rejectCall failed`,e),Ke(Tn(e,`We couldn't decline the call cleanly.`))}finally{ft()}},yt=(0,l.useRef)(vt);yt.current=vt,(0,l.useEffect)(()=>{if(!x?.callId||Le)return;let e=x.callId,t=window.setTimeout(()=>{qe.current?.callId===e&&yt.current()},h);return()=>window.clearTimeout(t)},[x?.callId,Le]);let bt=async()=>{if(!Le||!w.current||!_){ft();return}ut();try{await w.current.endWebRTCCall(Le,_)}catch(e){console.error(`[FlowEngageProvider] endWebRTCCall failed`,e),Ke(Tn(e,`The call ended locally, but the server could not be updated.`))}finally{ft()}},xt=()=>{let e=Ye.current?.getAudioTracks?.()||[],t=Je.current?.getSenders?.().map(e=>e.track).filter(e=>e?.kind===`audio`)||[],n=[...e,...t].filter(Boolean);if(n.length===0){console.warn(`[FlowEngageProvider] no local audio tracks available for mute`);return}let r=!Ue;n.forEach(e=>{e.enabled=!r}),console.log(`[FlowEngageProvider] toggled local mute`,{nextMuted:r,trackCount:n.length}),We(r)},St=async(e={})=>{let t=e.notifyChatInitiated===!0;if(de(!0),!(!t||!w.current||!_||typeof window>`u`)){try{await w.current.trackVisitor({chatId:_,currentPagePath:window.location.pathname||`/`})}catch{}try{await w.current.updateChatStatus(_,`open`)}catch{}}},Ct=async e=>{let t=dt(e);if(!t||!w.current||!T.current)return t;try{await w.current.trackVisitor({chatId:T.current,currentPagePath:typeof window<`u`&&window.location.pathname||`/`,email:t})}catch(e){console.error(`[FlowEngageProvider] failed to persist visitor email`,e)}return t},wt=()=>{if(!_||!C.current?.connected||nt.current){console.log(`[FlowEngageProvider] skipped typing:start emit`,{chatId:_,socketConnected:!!C.current?.connected,alreadyTyping:nt.current});return}nt.current=!0,console.log(`[FlowEngageProvider] emitting typing:start`,{chatId:_,sender:`user`}),C.current.emit(`typing:start`,{chatId:_,sender:`user`})},Tt=()=>{if(!_||!C.current?.connected||!nt.current){console.log(`[FlowEngageProvider] skipped typing:stop emit`,{chatId:_,socketConnected:!!C.current?.connected,wasTyping:nt.current});return}nt.current=!1,console.log(`[FlowEngageProvider] emitting typing:stop`,{chatId:_,sender:`user`}),C.current.emit(`typing:stop`,{chatId:_,sender:`user`})},Et=(e=``)=>{let t=typeof e==`string`?e:``;if(!_||!C.current?.connected){console.log(`[FlowEngageProvider] skipped typing:update emit`,{chatId:_,socketConnected:!!C.current?.connected,textLength:t.length});return}rt.current!==t&&(rt.current=t,console.log(`[FlowEngageProvider] emitting typing:update`,{chatId:_,sender:`user`,textLength:t.length}),C.current.emit(`typing:update`,{chatId:_,sender:`user`,text:t}))},Dt=async(e,t=``,n=null)=>{if(!e.trim()||!w.current||!_||a!==`ready`||Fe)return;Tt();let i=`pending-user-${Date.now()}`,o={id:i,sender:`user`,message:e,timestamp:new Date().toISOString(),isPending:!0,...n||{}};if(y(e=>[...e,o]),me&&C.current?.connected){C.current.emit(`customer:message`,{chatId:_,content:e,sender:`user`,email:be||void 0,...n||{}});return}ke(!0);try{let i=await w.current.sendAiMessage(_,e,r,t,{...n||{},...be?{email:be}:{}});y(wn(i.chat_history||[],!!i.is_human_handled)),he(!!i.is_human_handled),pe(i.is_human_handled?`agent`:`ai`),Te(!1),await w.current.updateChatStatus(_,`messageSent`)}catch(e){y(e=>e.filter(e=>e.id!==i)),Te(!1),e.status===429?(je(!0),Ne(e.message),window.setTimeout(()=>{je(!1),Ne(``)},m)):c(e)}finally{ke(!1)}},Ot=async e=>{if(!(!w.current||!_)){try{let t=e?`voice`:`text`;await w.current.setChatMode(_,t)}catch(e){console.error(`[FlowEngageProvider] setVoiceMode failed`,e)}Pe(e),e&&(st.current=!1)}},E=async e=>{if(!st.current){if(st.current=!0,!w.current||!_||!e?.length){Pe(!1);return}try{let t=await w.current.syncVoice(_,e);if(t?.chat_history?.length)y(wn(t.chat_history,!!t.is_human_handled));else if(t?.success)try{let e=await w.current.loadHistory(_,r);e?.chat_history?.length&&y(wn(e.chat_history,!!e.is_human_handled))}catch{}}catch{}finally{Pe(!1)}}},kt=async()=>{if(!(!w.current||!_)){b&&!st.current&&ot.current.length>0&&await E(ot.current);try{await w.current.endConversation(_)}catch{try{await w.current.updateChatStatus(_,`ended`)}catch{}}Ie(!0),y(e=>[...e,{id:`conversation-ended-${Date.now()}`,sender:`system`,message:`This conversation has ended. Thank you for reaching out!`,timestamp:new Date().toISOString(),isPending:!1}])}};(0,l.useEffect)(()=>{if(ze!==`connected`||!Le||!_||!Ve||!lt)return;let e=new Date(Ve).getTime(),t=Number.isFinite(e)?Date.now()-e:0,n=Math.max(0,lt*1e3-t),r=window.setTimeout(()=>{Ke(`The call ended because it reached the time limit.`),bt()},n);return()=>window.clearTimeout(r)},[Le,Ve,ze,_,bt,lt]),(0,l.useEffect)(()=>{let e=()=>{let e=T.current,t=w.current;if(!t||!e)return;if($e.current){t.beaconEndWebRTCCall($e.current,e);return}let n=et.current||qe.current?.callId;n&&t.beaconCustomerUnavailable(n,e)};return window.addEventListener(`pagehide`,e),window.addEventListener(`beforeunload`,e),()=>{window.removeEventListener(`pagehide`,e),window.removeEventListener(`beforeunload`,e)}},[]);let At=(0,l.useMemo)(()=>({status:a,error:s,runtimeConfig:f,resolvedConfig:i,chatId:_,chatHistory:le,isOpen:ue,activeScreen:fe,isHumanHandled:me,agentName:ge,agentHeadshot:ve,visitorEmail:be,isAgentTyping:Se,isAiTyping:we,connectionStatus:Ee,isLoading:Oe,isVoiceMode:b,isRateLimited:Ae,rateLimitMessage:Me,isConversationEnded:Fe,incomingCall:x,activeCallId:Le,callConnectionState:ze,callConnectedAt:Ve,isCallMuted:Ue,webRTCError:Ge,language:r,historyRef:ot,hasSyncedRef:st,dismissCallError:ut,captureVisitorEmail:Ct,startTyping:wt,stopTyping:Tt,updateTypingDraft:Et,notifyRouteChange:()=>ct.current?.notifyRouteChange?.(),openWidget:St,closeWidget:()=>de(!1),toggleWidget:()=>{if(ue){de(!1);return}St({notifyChatInitiated:!0})},sendMessage:Dt,setVoiceMode:Ot,onMessageSync:E,endConversation:kt,acceptCall:_t,rejectCall:vt,endWebRTCCall:bt,toggleCallMute:xt,startTyping:wt,stopTyping:Tt,updateTypingDraft:Et}),[a,s,f,i,_,le,ue,fe,me,ge,ve,be,Se,we,Ee,Oe,b,Ae,Me,Fe,x,Le,ze,Ve,Ue,Ge,r,Ct,wt,Tt,Et,_t,vt,bt,xt,St,Dt,Ot,E,kt,ut]);return(0,u.jsx)(qt.Provider,{value:At,children:n})}var jn=({color:e=`#3888FF`})=>(0,u.jsxs)(`svg`,{width:`40`,height:`40`,viewBox:`0 0 40 40`,fill:`none`,xmlns:`http://www.w3.org/2000/svg`,children:[(0,u.jsx)(`rect`,{width:`40`,height:`40`,rx:`20`,fill:e}),(0,u.jsx)(`path`,{d:`M26 8H14C12.3431 8 11 9.34315 11 11V23C11 24.6569 12.3431 26 14 26H26C27.6569 26 29 24.6569 29 23V11C29 9.34315 27.6569 8 26 8Z`,fill:`#ECF0F0`}),(0,u.jsx)(`path`,{d:`M18 32L18 26L24 26L18 32Z`,fill:`#ECF0F0`}),(0,u.jsx)(`path`,{d:`M16.4067 20.5924C16.182 20.3674 16.1822 20.003 16.407 19.7783L22.7805 13.4068C23.0051 13.1821 23.3694 13.1823 23.5939 13.4071V13.4071C23.8182 13.6317 23.8181 13.9956 23.5936 14.2201L17.2212 20.5926C16.9962 20.8176 16.6315 20.8174 16.4067 20.5924V20.5924Z`,fill:`#3E87C8`})]}),Mn=()=>(0,u.jsx)(`svg`,{width:`18`,height:`18`,viewBox:`0 0 24 24`,fill:`none`,xmlns:`http://www.w3.org/2000/svg`,children:(0,u.jsx)(`path`,{d:`M2.01 21L23 12 2.01 3 2 10l15 2-15 2z`,fill:`currentColor`})}),Nn=({size:e=18,color:t=`currentColor`})=>(0,u.jsxs)(`svg`,{width:e,height:e,viewBox:`0 0 24 24`,fill:`none`,xmlns:`http://www.w3.org/2000/svg`,children:[(0,u.jsx)(`path`,{d:`M12 1a4 4 0 014 4v6a4 4 0 01-8 0V5a4 4 0 014-4z`,fill:t}),(0,u.jsx)(`path`,{d:`M19 10a7 7 0 01-14 0M12 19v4M8 23h8`,stroke:t,strokeWidth:`2`,strokeLinecap:`round`,strokeLinejoin:`round`})]}),Pn=({size:e=20})=>(0,u.jsxs)(`svg`,{width:e,height:e,viewBox:`0 0 24 24`,fill:`none`,stroke:`currentColor`,strokeWidth:`2`,strokeLinecap:`round`,strokeLinejoin:`round`,children:[(0,u.jsx)(`path`,{d:`M10.68 13.31a16 16 0 003.41 2.6l1.27-1.27a2 2 0 012.11-.45 12.84 12.84 0 002.81.7 2 2 0 011.72 2v3a2 2 0 01-2.18 2 19.79 19.79 0 01-8.63-3.07A19.42 19.42 0 013.07 8.62 19.79 19.79 0 01.1 2 2 2 0 012.11 0h3a2 2 0 012 1.72c.127.96.361 1.903.7 2.81a2 2 0 01-.45 2.11L6.18 7.84`}),(0,u.jsx)(`line`,{x1:`23`,y1:`1`,x2:`1`,y2:`23`})]}),Fn=()=>(0,u.jsxs)(`svg`,{width:`18`,height:`18`,viewBox:`0 0 24 24`,fill:`none`,stroke:`currentColor`,strokeWidth:`2`,strokeLinecap:`round`,strokeLinejoin:`round`,children:[(0,u.jsx)(`line`,{x1:`12`,y1:`19`,x2:`12`,y2:`5`}),(0,u.jsx)(`polyline`,{points:`5 12 12 5 19 12`})]}),In=()=>(0,u.jsxs)(`svg`,{width:`14`,height:`14`,viewBox:`0 0 24 24`,fill:`none`,stroke:`currentColor`,strokeWidth:`2`,strokeLinecap:`round`,strokeLinejoin:`round`,children:[(0,u.jsx)(`polyline`,{points:`9 17 4 12 9 7`}),(0,u.jsx)(`path`,{d:`M20 18v-2a4 4 0 00-4-4H4`})]}),Ln=()=>(0,u.jsx)(`svg`,{width:`18`,height:`18`,viewBox:`0 0 24 24`,fill:`none`,stroke:`currentColor`,strokeWidth:`2`,strokeLinecap:`round`,strokeLinejoin:`round`,children:(0,u.jsx)(`path`,{d:`M22 16.92v3a2 2 0 01-2.18 2 19.79 19.79 0 01-8.63-3.07 19.42 19.42 0 01-6.12-6.11A19.79 19.79 0 012 4.11 2 2 0 014.11 2h3a2 2 0 012 1.72c.13.96.37 1.91.71 2.81a2 2 0 01-.45 2.11L8.09 9.91a16 16 0 006 6l1.27-1.27a2 2 0 012.11-.45c.9.34 1.85.58 2.81.71A2 2 0 0122 16.92z`})}),Rn=({className:e=``})=>(0,u.jsxs)(`svg`,{className:e,width:`14`,height:`14`,viewBox:`0 0 24 24`,fill:`none`,stroke:`currentColor`,strokeWidth:`2`,strokeLinecap:`round`,strokeLinejoin:`round`,children:[(0,u.jsx)(`circle`,{cx:`12`,cy:`12`,r:`10`}),(0,u.jsx)(`line`,{x1:`12`,y1:`8`,x2:`12`,y2:`12`}),(0,u.jsx)(`line`,{x1:`12`,y1:`16`,x2:`12.01`,y2:`16`})]}),zn=({size:e=18,strokeWidth:t=2.5})=>(0,u.jsxs)(`svg`,{width:e,height:e,viewBox:`0 0 24 24`,fill:`none`,stroke:`currentColor`,strokeWidth:t,strokeLinecap:`round`,strokeLinejoin:`round`,children:[(0,u.jsx)(`line`,{x1:`18`,y1:`6`,x2:`6`,y2:`18`}),(0,u.jsx)(`line`,{x1:`6`,y1:`6`,x2:`18`,y2:`18`})]}),Bn=({size:e=14})=>(0,u.jsxs)(`svg`,{width:e,height:e,viewBox:`0 0 24 24`,fill:`none`,stroke:`currentColor`,strokeWidth:`2`,strokeLinecap:`round`,strokeLinejoin:`round`,children:[(0,u.jsx)(`path`,{d:`M12 8V4H8`}),(0,u.jsx)(`rect`,{width:`16`,height:`12`,x:`4`,y:`8`,rx:`2`}),(0,u.jsx)(`path`,{d:`M2 14h2`}),(0,u.jsx)(`path`,{d:`M20 14h2`}),(0,u.jsx)(`path`,{d:`M15 13v2`}),(0,u.jsx)(`path`,{d:`M9 13v2`})]});function Vn({isOpen:e,openWidget:t,launcherText:n,primaryColor:r,posInline:i}){let[a,o]=(0,l.useState)(!1);return(0,l.useEffect)(()=>{if(typeof window>`u`)return;let e=window.matchMedia(`(max-width: 640px)`),t=e=>{o(e.matches)};return o(e.matches),typeof e.addEventListener==`function`?(e.addEventListener(`change`,t),()=>e.removeEventListener(`change`,t)):(e.addListener(t),()=>e.removeListener(t))},[]),e?null:(0,u.jsxs)(`button`,{type:`button`,onClick:()=>t({notifyChatInitiated:!0}),"aria-label":n,style:{position:`fixed`,...i,zIndex:999999,display:`flex`,alignItems:`center`,justifyContent:`center`,gap:a?`0`:`14px`,width:a?`60px`:`auto`,minWidth:a?`60px`:`unset`,height:a?`60px`:`auto`,padding:a?`0`:`14px 24px`,border:`none`,borderRadius:`9999px`,background:r,color:`#fff`,fontSize:`16px`,fontWeight:`600`,fontFamily:`ui-sans-serif, system-ui, sans-serif`,cursor:`pointer`,boxShadow:`0 8px 24px rgba(0,0,0,0.18)`,transition:`transform 0.2s ease, box-shadow 0.2s ease`,outline:`none`,whiteSpace:`nowrap`},onMouseEnter:e=>{e.currentTarget.style.transform=`translateY(-2px)`,e.currentTarget.style.boxShadow=`0 12px 28px rgba(0,0,0,0.22)`},onMouseLeave:e=>{e.currentTarget.style.transform=`translateY(0)`,e.currentTarget.style.boxShadow=`0 8px 24px rgba(0,0,0,0.18)`},children:[a?null:(0,u.jsx)(`span`,{children:n}),a?(0,u.jsx)(jn,{color:`#fff`}):(0,u.jsx)(`span`,{style:{width:`42px`,height:`42px`,borderRadius:`9999px`,background:`#fff`,color:r,display:`inline-flex`,alignItems:`center`,justifyContent:`center`,flexShrink:0},children:(0,u.jsx)(Mn,{})})]})}function Hn(e){if(!e||typeof e!=`string`)return`?`;let t=e.trim();if(!t)return`?`;let n=t.split(/\s+/).filter(Boolean);return n.length>=2?`${n[0][0]}${n[n.length-1][0]}`.toUpperCase():t.slice(0,2).toUpperCase()}function Un({src:e,name:t,imgStyle:n,initialsSpanStyle:r}){let[i,a]=(0,l.useState)(!1),o=typeof e==`string`?e.trim():``;return(0,l.useEffect)(()=>{a(!1)},[o,t]),o&&!i?(0,u.jsx)(`img`,{src:o,alt:``,onError:()=>a(!0),style:n}):(0,u.jsx)(`span`,{style:r,children:Hn(t)})}function Wn(e){return typeof e==`string`?e.trim():e&&typeof e==`object`&&typeof e.src==`string`?e.src.trim():``}function Gn(e){let[t,n]=(0,l.useState)(`loading`),r=Wn(e);return(0,l.useEffect)(()=>{if(l.default.isValidElement(e)||typeof e==`function`){n(`square`);return}if(!r){n(`error`);return}n(`loading`);let t=new Image,i=!1;return t.onload=()=>{i||n(t.naturalWidth/t.naturalHeight>1.3?`wide`:`square`)},t.onerror=()=>{i||n(`error`)},t.src=r,()=>{i=!0}},[e,r]),{state:t,resolvedLogoUrl:r}}function Kn({logoUrl:e,brandName:t,agentName:n,fallbackAgentName:r,activeScreen:i,branding:a,isConversationEnded:o,closeWidget:s,isInitial:c,botLabel:d=`AI`,agentAvatarUrl:f=null,primaryColor:p=`#3B82F6`}){let{state:m,resolvedLogoUrl:ee}=Gn(e),h=i===`agent`,g=a?.fallbackAgentName&&String(a.fallbackAgentName).trim()||n||r||`Agent`;return(0,u.jsxs)(`div`,{style:{display:`flex`,justifyContent:`space-between`,alignItems:`center`,padding:`16px 20px`,borderTopLeftRadius:`inherit`,borderTopRightRadius:`inherit`,border:`none`,transition:`all 0.3s ease`,background:c?`transparent`:`#fff`,color:c?`#fff`:`#111827`,boxShadow:c?`none`:`0 1px 0 rgba(0,0,0,0.05), 0 10px 24px rgba(0,0,0,0.04)`,borderBottom:c?`none`:`1px solid rgba(0,0,0,0.05)`},children:[(0,u.jsxs)(`div`,{style:{display:`flex`,alignItems:`center`,gap:`12px`},children:[h?(0,u.jsx)(`div`,{style:{width:`44px`,height:`44px`,borderRadius:`9999px`,flexShrink:0,overflow:`hidden`,display:`flex`,alignItems:`center`,justifyContent:`center`,background:c?`rgba(255,255,255,0.2)`:`#f3f4f6`,color:c?`#fff`:p,fontWeight:800,fontSize:`15px`,border:c?`2px solid rgba(255,255,255,0.35)`:`1px solid rgba(0,0,0,0.06)`},children:(0,u.jsx)(Un,{src:typeof f==`string`?f:``,name:g,imgStyle:{width:`100%`,height:`100%`,objectFit:`cover`},initialsSpanStyle:{lineHeight:1}})}):(0,u.jsxs)(u.Fragment,{children:[m!==`loading`&&(m===`error`||!ee&&!e?(0,u.jsx)(`div`,{className:`flowengage-logo-fallback`,style:{width:`44px`,height:`44px`,borderRadius:`9999px`,flexShrink:0,display:`flex`,alignItems:`center`,justifyContent:`center`,fontWeight:800,fontSize:`15px`,color:`#fff`,border:c?`2px solid rgba(255,255,255,0.35)`:`1px solid rgba(0,0,0,0.06)`},"aria-hidden":!0,children:Hn(t)}):l.default.isValidElement(e)?(0,u.jsx)(`div`,{style:{width:`44px`,height:`44px`,borderRadius:`9999px`,flexShrink:0,overflow:`hidden`,display:`flex`,alignItems:`center`,justifyContent:`center`,background:`#fff`},children:e}):typeof e==`function`?(0,u.jsx)(`div`,{style:{width:`44px`,height:`44px`,borderRadius:`9999px`,flexShrink:0,overflow:`hidden`,display:`flex`,alignItems:`center`,justifyContent:`center`,background:`#fff`},children:(0,u.jsx)(e,{})}):m===`wide`?(0,u.jsx)(`div`,{style:{height:`36px`,maxWidth:`88px`,flexShrink:0,display:`flex`,alignItems:`center`,justifyContent:`center`,borderRadius:`12px`,padding:`4px 8px`,background:c?`rgba(255,255,255,0.15)`:`#f9fafb`,backdropFilter:c?`blur(12px)`:`none`,border:c?`none`:`1px solid rgba(0,0,0,0.05)`},children:(0,u.jsx)(`img`,{src:ee,alt:`Logo`,style:{height:`100%`,width:`auto`,maxWidth:`100%`,objectFit:`contain`}})}):(0,u.jsx)(`div`,{style:{width:`44px`,height:`44px`,borderRadius:`9999px`,flexShrink:0,overflow:`hidden`,display:`flex`,alignItems:`center`,justifyContent:`center`,background:`#fff`},children:(0,u.jsx)(`img`,{src:ee,alt:`Logo`,style:{width:`100%`,height:`100%`,objectFit:`contain`,padding:ee.toLowerCase().includes(`.svg`)||ee.startsWith(`data:image/svg`)?0:`2px`}})})),m===`loading`&&(0,u.jsx)(`div`,{style:{width:`44px`,height:`44px`,borderRadius:`9999px`,background:`rgba(255,255,255,0.2)`,flexShrink:0}})]}),(0,u.jsxs)(`div`,{children:[(0,u.jsxs)(`div`,{style:{display:`flex`,alignItems:`center`,gap:`8px`},children:[(0,u.jsx)(`div`,{style:{fontSize:`16px`,fontWeight:700},children:i===`agent`?g:t}),i!==`agent`&&(0,u.jsxs)(`div`,{style:{display:`flex`,alignItems:`center`,gap:`4px`,borderRadius:`6px`,background:`rgba(255,255,255,0.95)`,padding:`3px 6px`,fontSize:`10px`,fontWeight:800,letterSpacing:`0.5px`,color:`var(--flowengage-primary)`,maxWidth:`140px`,minWidth:0},children:[(0,u.jsx)(`span`,{style:{flexShrink:0,display:`inline-flex`},children:(0,u.jsx)(Bn,{size:11})}),(0,u.jsx)(`span`,{style:{overflow:`hidden`,textOverflow:`ellipsis`,whiteSpace:`nowrap`},children:d})]})]}),(0,u.jsxs)(`div`,{style:{fontSize:`13px`,opacity:.95,marginTop:`2px`},children:[i===`agent`?`Live support`:`Usually replies `,i!==`agent`&&(0,u.jsx)(`span`,{style:{color:`#10b981`,fontWeight:600},children:`instantly`})]})]})]}),(0,u.jsx)(`div`,{style:{display:`flex`,alignItems:`center`,gap:`4px`},children:(0,u.jsx)(`button`,{style:{width:`36px`,height:`36px`,borderRadius:`9999px`,background:`transparent`,display:`flex`,alignItems:`center`,justifyContent:`center`,transition:`all 0.2s ease`,border:0,cursor:`pointer`,color:c?`#fff`:`#000`},onClick:s,"aria-label":`Close chat`,onMouseEnter:e=>{e.currentTarget.style.background=c?`rgba(255,255,255,0.1)`:`rgba(0,0,0,0.05)`},onMouseLeave:e=>{e.currentTarget.style.background=`transparent`},children:(0,u.jsx)(zn,{})})})]})}var qn=(e=``)=>String(e).replace(/<[^>]+>/g,``).replace(/\s+/g,` `).trim(),Jn=(e=``)=>String(e).replace(/&/g,`&`).replace(/</g,`<`).replace(/>/g,`>`).replace(/"/g,`"`).replace(/'/g,`'`);function Yn(e){let t=String(e||``).trim();if(!t)return t;let n=/^<p>\s*<strong>([\s\S]*?)<\/strong>\s*<\/p>$/i.exec(t);if(n&&!/<\/?strong\b/i.test(n[1]))return`<p>${n[1]}</p>`;let r=/^<strong>([\s\S]*?)<\/strong>$/i.exec(t);if(r&&!/<\/?strong\b/i.test(r[1])){let e=r[1].trim();return/^<(?:p|ul|ol)\b/i.test(e)?e:`<p>${e}</p>`}return e}var Xn=(e=``)=>{let t=String(e||``).trim();if(!t)return``;if(/<(p|br|ul|ol|li|strong|em|a)\b/i.test(t))return Yn(t);let n=t.replace(/\r\n/g,`
|
|
26
26
|
`).replace(/\n{3,}/g,`
|
|
27
27
|
|
|
28
28
|
`).split(/\n\s*\n/).map(e=>e.trim()).filter(Boolean),r=e=>Jn(e).replace(/\[([^\]]+)\]\((https?:\/\/[^\s)]+)\)/g,`<a href="$2" target="_blank" rel="noopener noreferrer">$1</a>`).replace(/\*\*([^*]+)\*\*/g,`<strong>$1</strong>`).replace(/\*([^*\n]+)\*/g,`<em>$1</em>`);return Yn(n.map(e=>{let t=e.split(`
|
|
29
29
|
`).map(e=>e.trim()).filter(Boolean),n=t.filter(e=>/^[-*]\s+/.test(e));if(n.length>=2&&n.length===t.length)return`<ul>${n.map(e=>`<li>${r(e.replace(/^[-*]\s+/,``))}</li>`).join(``)}</ul>`;let i=e.split(/\s+(?=[-*]\s+\*\*?)/).map(e=>e.trim()).filter(Boolean);return i.length>=2&&i.every(e=>/^[-*]\s+/.test(e))?`<ul>${i.map(e=>`<li>${r(e.replace(/^[-*]\s+/,``))}</li>`).join(``)}</ul>`:`<p>${r(e).replace(/\n/g,`<br />`)}</p>`}).join(``))};function Zn({chatHistory:e,isAiTyping:t,isAgentTyping:n,setReplyContext:r,TypingDots:i,primaryColor:a=`#3B82F6`,agentHeadshot:o=null,agentDisplayName:s=`Agent`}){let c=(0,l.useRef)(null),d=e=>{if(!e)return`just now`;let t=new Date,n=new Date(e),r=Math.max(0,Math.floor((t-n)/1e3));if(r<60)return`just now`;let i=Math.floor(r/60);if(i<60)return`${i} min${i>1?`s`:``} ago`;let a=Math.floor(i/60);if(a<24)return`${a} hr${a>1?`s`:``} ago`;let o=Math.floor(a/24);return`${o} day${o>1?`s`:``} ago`};return(0,l.useEffect)(()=>{c.current&&c.current.scrollIntoView({behavior:`smooth`})},[e.length,t,n]),(0,u.jsxs)(`div`,{style:{flex:1,overflowY:`auto`,padding:`10px 20px 20px`,display:`flex`,flexDirection:`column`},children:[e.map(e=>{let t=e.sender===`system`,n=e.sender===`user`,i=e.sender===`ai`||e.sender===`bot`,c=e.sender===`agent`,l=e.isPending,f=e.agent_name||e.agentName||e.metadata?.agentName||s,p=typeof e.sender_headshot==`string`&&e.sender_headshot.trim()||typeof o==`string`&&o.trim()||null,m=qn(e.replyToContent||e.replyContext?.message||``),ee=e.replyToSender===`user`?`You`:e.replyToSender===`agent`?`Agent`:e.replyToSender===`ai`||e.replyToSender===`bot`?`AI Assistant`:`Message`;return t?(0,u.jsx)(`div`,{style:{display:`flex`,justifyContent:`center`,margin:`8px 0`},children:(0,u.jsx)(`div`,{style:{padding:`6px 12px`,borderRadius:`9999px`,background:`#f3f4f6`,color:`#6b7280`,fontSize:`12px`,fontWeight:500},children:e.message})},e.id):(0,u.jsxs)(`div`,{style:{display:`flex`,justifyContent:n?`flex-end`:`flex-start`,marginBottom:`12px`,position:`relative`},children:[!n&&(i||c)&&(0,u.jsx)(`div`,{style:{marginRight:`10px`,marginTop:`34px`,width:`36px`,height:`36px`,flexShrink:0,display:`flex`,alignItems:`center`,justifyContent:`center`,borderRadius:`9999px`,background:c?`#f3f4f6`:`var(--flowengage-primary)`,color:c?a:`#fff`,boxShadow:c?`0 2px 8px rgba(0,0,0,0.06)`:`0 8px 20px rgba(59,130,246,0.24)`,overflow:`hidden`,border:c?`1px solid ${a}22`:`none`,fontSize:`12px`,fontWeight:800},children:i?(0,u.jsx)(Bn,{size:16}):(0,u.jsx)(Un,{src:p||``,name:f,imgStyle:{width:`100%`,height:`100%`,objectFit:`cover`},initialsSpanStyle:{lineHeight:1}})}),(0,u.jsxs)(`div`,{style:{display:`flex`,flexDirection:`column`,alignItems:n?`flex-end`:`flex-start`,maxWidth:`85%`},children:[!l&&c&&(0,u.jsxs)(`button`,{type:`button`,onClick:()=>r(e),style:{opacity:1,marginBottom:`6px`,display:`flex`,alignItems:`center`,gap:`4px`,fontSize:`11px`,color:`#9ca3af`,background:`transparent`,border:0,cursor:`pointer`,padding:0,marginLeft:`2px`},onMouseEnter:e=>{e.currentTarget.style.color=`#4b5563`},onMouseLeave:e=>{e.currentTarget.style.color=`#9ca3af`},children:[(0,u.jsx)(In,{}),`Reply`]}),(0,u.jsxs)(`div`,{style:{padding:`12px 16px`,borderRadius:`18px`,lineHeight:1.5,boxShadow:`0 2px 6px rgba(0,0,0,0.04)`,background:n?`var(--flowengage-primary)`:`#fff`,color:n?`#fff`:`#111827`,whiteSpace:n?`pre-wrap`:`normal`,wordBreak:n?`break-word`:`normal`,overflowWrap:n?`anywhere`:`break-word`,maxWidth:`100%`,opacity:l?.55:1,transition:`opacity 0.3s ease`},children:[m&&(0,u.jsxs)(`div`,{style:{marginBottom:`8px`,borderRadius:`14px`,borderLeft:n?`2px solid rgba(255,255,255,0.8)`:`2px solid var(--flowengage-primary)`,padding:`8px 12px`,fontSize:`12px`,background:n?`rgba(255,255,255,0.15)`:`#f9fafb`,color:n?`rgba(255,255,255,0.9)`:`#6b7280`},children:[(0,u.jsx)(`div`,{style:{marginBottom:`2px`,fontWeight:600},children:ee}),(0,u.jsx)(`div`,{style:{display:`-webkit-box`,WebkitLineClamp:2,WebkitBoxOrient:`vertical`,overflow:`hidden`},children:m})]}),i?(0,u.jsx)(`div`,{className:`flowengage-message-content fe-bot-message`,dangerouslySetInnerHTML:{__html:Xn(e.message)}}):(0,u.jsx)(`div`,{style:{whiteSpace:n||c?`normal`:`pre-wrap`},children:e.message}),l&&(0,u.jsx)(`span`,{style:{fontSize:`10px`,marginLeft:`6px`,opacity:.7,whiteSpace:`nowrap`},children:`sending…`})]}),(0,u.jsxs)(`div`,{style:{display:`flex`,alignItems:`center`,gap:`4px`,marginTop:`4px`,padding:`0 4px`,justifyContent:n?`flex-end`:`flex-start`,marginLeft:n?0:`2px`},children:[(0,u.jsx)(`span`,{style:{fontSize:`10px`,color:`#9ca3af`,fontWeight:500,whiteSpace:`nowrap`},children:d(e.timestamp||e.createdAt||Date.now())}),(0,u.jsx)(`span`,{style:{fontSize:`10px`,fontWeight:700,color:n?`var(--flowengage-primary)`:`#9ca3af`},children:l?`○`:`✓`})]})]})]},e.id)}),t&&(0,u.jsxs)(`div`,{style:{marginBottom:`12px`,display:`flex`,justifyContent:`flex-start`},children:[(0,u.jsx)(`div`,{style:{marginRight:`8px`,marginTop:`auto`,width:`36px`,height:`36px`,flexShrink:0,display:`flex`,alignItems:`center`,justifyContent:`center`,borderRadius:`9999px`,background:`var(--flowengage-primary)`,color:`#fff`,boxShadow:`0 8px 20px rgba(59,130,246,0.24)`},children:(0,u.jsx)(Bn,{size:16})}),(0,u.jsx)(`div`,{style:{display:`flex`,alignItems:`center`,gap:`5px`,borderRadius:`18px`,background:`#fff`,padding:`12px 16px`,color:`#111827`,boxShadow:`0 2px 6px rgba(0,0,0,0.04)`},children:[0,1,2].map(e=>(0,u.jsx)(`span`,{style:{width:`7px`,height:`7px`,borderRadius:`50%`,background:`#9ca3af`,animation:`fe-dot-bounce 1.2s ease-in-out ${e*.2}s infinite`,display:`inline-block`}},e))})]}),n&&(0,u.jsx)(i,{}),(0,u.jsx)(`div`,{ref:c})]})}function Qn(e){if(!e?.length)return[];let t=[];for(let n=0;n<e.length;n+=2)t.push(e.slice(n,n+2));return t}var $n={flex:`0 1 auto`,maxWidth:`100%`,padding:`12px 22px`,borderRadius:`9999px`,background:`#fff`,color:`#111827`,fontWeight:500,fontSize:`14px`,lineHeight:1.35,boxShadow:`0 4px 12px rgba(0,0,0,0.06)`,border:`1px solid rgba(0,0,0,0.06)`,transition:`transform 0.2s ease, box-shadow 0.2s ease`,cursor:`pointer`,textAlign:`left`,whiteSpace:`normal`};function er(e){return(e||[]).filter(e=>String(e?.label??``).trim().length>0)}function tr({greetings:e,recommendations:t,onSendMessage:n}){let r=(0,l.useMemo)(()=>Qn(er(t)),[t]);return(0,u.jsxs)(`div`,{style:{display:`flex`,flexDirection:`column`,flex:1,minHeight:0,justifyContent:`space-between`},children:[(0,u.jsx)(`div`,{style:{padding:`24px 20px 16px`},children:(0,u.jsx)(`div`,{style:{fontSize:`28px`,fontWeight:700,color:`#fff`,lineHeight:1.2},children:e?.split(`
|
|
30
|
-
`).map((e,t)=>(0,u.jsx)(`div`,{children:e},t))||(0,u.jsxs)(u.Fragment,{children:[(0,u.jsx)(`div`,{children:`Hi there 👋`}),(0,u.jsx)(`div`,{children:`How can we help?`})]})})}),(0,u.jsx)(`div`,{style:{display:`flex`,flexDirection:`column`,alignItems:`stretch`,gap:`10px`,padding:`8px 20px 24px`,width:`100%`,boxSizing:`border-box`},children:r.map((e,t)=>(0,u.jsx)(`div`,{style:{display:`flex`,flexDirection:`row`,justifyContent:`flex-end`,alignItems:`center`,flexWrap:`wrap`,gap:`10px`,width:`100%`},children:e.map(e=>(0,u.jsx)(`button`,{type:`button`,style:{...$n},onClick:()=>n(e.label,e.key),onMouseEnter:e=>{e.currentTarget.style.transform=`translateY(-1px)`,e.currentTarget.style.boxShadow=`0 6px 16px rgba(0,0,0,0.1)`},onMouseLeave:e=>{e.currentTarget.style.transform=`translateY(0)`,e.currentTarget.style.boxShadow=`0 4px 12px rgba(0,0,0,0.06)`},children:e.label},e.key))},`row-${t}`))})]})}function nr({input:e,setInput:t,onSubmit:n,isConversationEnded:r,callUiActive:i,handleToggleVoice:a,activeScreen:o,inputDisabled:s,replyContext:c,clearReplyContext:l,requiresEmail:d,emailInput:f,setEmailInput:p,emailError:m}){let ee=c?.sender===`user`?`You`:c?.sender===`agent`?`Agent`:`AI Assistant`,h=d?!!f?.trim():!!e?.trim(),g=s||!h;return(0,u.jsxs)(`div`,{style:{padding:`0 20px 4px`,background:`transparent`},children:[r&&(0,u.jsx)(`div`,{style:{marginBottom:`8px`,padding:`8px 16px`,borderRadius:`12px`,background:`#f3f4f6`,color:`#6b7280`,fontSize:`12px`,textAlign:`center`,fontWeight:500},children:`This conversation has ended.`}),c&&(0,u.jsxs)(`div`,{style:{marginBottom:`8px`,display:`flex`,alignItems:`flex-start`,justifyContent:`space-between`,gap:`12px`,borderRadius:`16px`,border:`1px solid rgba(0,0,0,0.05)`,background:`#fff`,padding:`12px 16px`,boxShadow:`0 8px 24px rgba(0,0,0,0.05)`},children:[(0,u.jsxs)(`div`,{style:{minWidth:0,flex:1,borderLeft:`2px solid var(--flowengage-primary)`,paddingLeft:`12px`},children:[(0,u.jsxs)(`div`,{style:{fontSize:`12px`,fontWeight:600,color:`var(--flowengage-primary)`},children:[`Replying to `,ee]}),(0,u.jsx)(`div`,{style:{overflow:`hidden`,textOverflow:`ellipsis`,whiteSpace:`nowrap`,fontSize:`12px`,color:`#6b7280`},children:c.replyToContent||c.message})]}),(0,u.jsx)(`button`,{type:`button`,style:{width:`28px`,height:`28px`,borderRadius:`9999px`,border:0,background:`#f3f4f6`,color:`#6b7280`,transition:`color 0.2s ease, background 0.2s ease`,cursor:`pointer`},onClick:l,"aria-label":`Cancel reply`,onMouseEnter:e=>{e.currentTarget.style.background=`#e5e7eb`,e.currentTarget.style.color=`#374151`},onMouseLeave:e=>{e.currentTarget.style.background=`#f3f4f6`,e.currentTarget.style.color=`#6b7280`},children:`×`})]}),d&&(0,u.jsx)(`div`,{style:{marginBottom:`14px`,padding:`0 8px`},children:(0,u.jsxs)(`div`,{style:{display:`flex`,alignItems:`center`,justifyContent:`center`,gap:`8px`,color:`#111827`,fontSize:`14px`,fontWeight:500,textAlign:`center`},children:[(0,u.jsx)(`span`,{style:{display:`inline-flex`,width:`22px`,height:`22px`,borderRadius:`9999px`,alignItems:`center`,justifyContent:`center`,background:`rgba(59,130,246,0.08)`,color:`var(--flowengage-primary)`},children:(0,u.jsx)(Bn,{size:13})}),(0,u.jsx)(`span`,{children:`Please provide your email address so we can help you.`})]})}),(0,u.jsxs)(`form`,{style:{display:`flex`,alignItems:`center`,gap:`8px`,padding:`6px 10px`,border:`1px solid rgba(0,0,0,0.05)`,borderRadius:`9999px`,background:`#fff`,boxShadow:`0 8px 24px rgba(0,0,0,0.05)`,opacity:r?.5:1},onSubmit:n,children:[d?(0,u.jsx)(`span`,{style:{width:`32px`,flexShrink:0},"aria-hidden":!0}):(0,u.jsx)(`button`,{type:`button`,style:{width:`32px`,height:`32px`,borderRadius:`9999px`,background:`transparent`,color:`#9ca3af`,display:`flex`,alignItems:`center`,justifyContent:`center`,transition:`background 0.2s ease, color 0.2s ease`,border:0,cursor:`pointer`},onClick:a,title:`Voice assistant`,"aria-label":`Voice assistant`,disabled:r||i,onMouseEnter:e=>{e.currentTarget.style.background=`#f3f4f6`},onMouseLeave:e=>{e.currentTarget.style.background=`transparent`},children:(0,u.jsx)(Nn,{size:18,color:`currentColor`})}),(0,u.jsx)(`input`,{style:{flex:1,minWidth:0,border:`none`,fontFamily:`inherit`,fontSize:`14px`,outline:`none`,padding:`6px 0`,color:`#111827`,background:`transparent`},value:d?f:e,onChange:e=>{if(d){p(e.target.value);return}t(e.target.value)},placeholder:r?`Conversation ended`:d?`Your email address`:o===`agent`?`Message the agent…`:`Type a reply…`,disabled:s,type:d?`email`:`text`,autoComplete:d?`email`:`off`}),(0,u.jsx)(`button`,{type:`submit`,style:{width:`34px`,height:`34px`,borderRadius:`9999px`,background:`transparent`,color:`var(--flowengage-primary)`,border:`1px solid var(--flowengage-primary)`,display:`flex`,alignItems:`center`,justifyContent:`center`,transition:`all 0.2s ease`,cursor:g?`not-allowed`:`pointer`,marginLeft:`4px`,opacity:g?.45:1},disabled:g,onMouseEnter:e=>{g||(e.currentTarget.style.background=`linear-gradient(135deg, var(--flowengage-primary), var(--flowengage-accent))`,e.currentTarget.style.borderColor=`transparent`,e.currentTarget.style.color=`#fff`)},onMouseLeave:e=>{e.currentTarget.style.background=`transparent`,e.currentTarget.style.borderColor=`var(--flowengage-primary)`,e.currentTarget.style.color=g?`#d1d5db`:`var(--flowengage-primary)`},children:(0,u.jsx)(Fn,{})})]}),d&&m&&(0,u.jsx)(`div`,{style:{padding:`8px 16px 0`,fontSize:`12px`,fontWeight:500,color:`#f43f5e`},children:m})]})}var rr=({muted:e=!1})=>(0,u.jsxs)(`svg`,{width:`16`,height:`16`,viewBox:`0 0 24 24`,fill:`none`,stroke:`currentColor`,strokeWidth:`2`,strokeLinecap:`round`,strokeLinejoin:`round`,children:[(0,u.jsx)(`path`,{d:`M12 1a4 4 0 014 4v6a4 4 0 01-6.83 2.83`}),(0,u.jsx)(`path`,{d:`M19 10a7 7 0 01-1.62 4.49M5 10a7 7 0 008.79 6.77`}),(0,u.jsx)(`path`,{d:`M12 19v4M8 23h8`}),e&&(0,u.jsx)(`line`,{x1:`2`,y1:`2`,x2:`22`,y2:`22`})]}),ir=({variant:e,onClick:t,children:n,icon:r,compact:i=!1,iconOnly:a=!1,active:o=!1,ariaLabel:s})=>(0,u.jsxs)(`button`,{type:`button`,className:[`flowengage-call-btn`,`flowengage-call-btn-${e}`,i?`compact`:``,a?`icon-only`:``,o?`active`:``].filter(Boolean).join(` `),onClick:t,"aria-label":s||n,title:s||n,children:[r,!a&&(0,u.jsx)(`span`,{children:n})]});function ar({webRTCError:e,micError:t,setMicError:n,dismissCallError:r,incomingCall:i,rejectCall:a,acceptCall:o,activeCallId:s,callConnectionState:c,formatCallDuration:d,callDurationSeconds:f,endWebRTCCall:p,isCallMuted:m,toggleCallMute:ee,isAIVoiceActive:h,currentCallAgentName:g,isRateLimited:_,rateLimitMessage:te}){let ne=(0,l.useRef)(null),re=(0,l.useCallback)(()=>{if(!ne.current)return;let{audioContext:e,oscillator:t,interval:n,toneTimeout:r}=ne.current;window.clearInterval(n),window.clearTimeout(r);try{t.stop()}catch{}try{e.close()}catch{}ne.current=null},[]),ie=(0,l.useCallback)(()=>{if(ne.current||typeof window>`u`)return;let e=window.AudioContext||window.webkitAudioContext||null;if(e)try{let t=new e,n=t.createOscillator(),r=t.createGain();n.connect(r),r.connect(t.destination),n.frequency.value=0,n.type=`sine`,r.gain.value=.3;let i=()=>{ne.current&&(window.clearTimeout(ne.current.toneTimeout),n.frequency.value=440,ne.current.toneTimeout=window.setTimeout(()=>{n.frequency.value=0},400))};t.state===`suspended`&&t.resume().catch(e=>{console.warn(`[FlowEngage] ringtone autoplay blocked`,e)}),n.start(),ne.current={audioContext:t,oscillator:n,interval:null,toneTimeout:null},i(),ne.current.interval=window.setInterval(i,1e3)}catch(e){console.warn(`[FlowEngage] failed to start ringtone`,e)}},[]);(0,l.useEffect)(()=>{if(i){ie();return}re()},[i,ie,re]),(0,l.useEffect)(()=>()=>re(),[re]);let ae=h?`header-mode`:`bottom-mode`,oe=!!(i||s),v=i?`incoming`:c===`connected`?`connected`:`connecting`,se=(0,l.useMemo)(()=>v===`incoming`?`Incoming Call`:v===`connected`?`Voice Call Active`:`Connecting Call`,[v]),ce=(0,l.useMemo)(()=>v===`incoming`?`${g} wants to join a voice call`:v===`connected`?`You are connected to ${g} from this conversation.`:`Please wait while ${g}'s voice connection finishes setting up.`,[g,v]);return(0,u.jsxs)(u.Fragment,{children:[(e||t)&&(0,u.jsxs)(`div`,{style:{margin:`0 20px 10px`,padding:`12px 16px`,borderRadius:`12px`,background:`#fef2f2`,border:`1px solid #fee2e2`,display:`flex`,alignItems:`flex-start`,gap:`10px`},children:[(0,u.jsx)(Rn,{className:``}),(0,u.jsx)(`span`,{style:{fontSize:`12px`,color:`#b91c1c`,lineHeight:1.5,flex:1},children:e||t}),(0,u.jsx)(`button`,{style:{flexShrink:0,background:`transparent`,border:0,color:`#f87171`,cursor:`pointer`,fontSize:`18px`,lineHeight:1},onClick:()=>{n(null),r()},onMouseEnter:e=>{e.currentTarget.style.color=`#dc2626`},onMouseLeave:e=>{e.currentTarget.style.color=`#f87171`},children:`×`})]}),oe&&(0,u.jsx)(`div`,{className:`incoming-call-overlay ${ae}`,children:(0,u.jsx)(`div`,{className:[`incoming-call-container`,v===`connected`?`connected-layout`:``].filter(Boolean).join(` `),children:v===`connected`?(0,u.jsxs)(u.Fragment,{children:[(0,u.jsxs)(`div`,{className:`call-connected-top`,children:[(0,u.jsxs)(`div`,{className:`call-connected-identity`,children:[(0,u.jsx)(`div`,{className:`call-icon-wrapper ${v}`,children:(0,u.jsx)(Pn,{size:20})}),(0,u.jsxs)(`div`,{className:`call-info-group`,children:[(0,u.jsx)(`h3`,{className:`call-title`,children:se}),(0,u.jsx)(`p`,{className:`call-subtitle`,children:ce})]})]}),(0,u.jsx)(`div`,{className:`call-timer`,children:d(f)})]}),(0,u.jsxs)(`div`,{className:`call-actions connected`,children:[(0,u.jsx)(ir,{variant:`mute`,onClick:ee,compact:h,active:m,icon:(0,u.jsx)(rr,{muted:m}),children:m?`Unmute`:`Mute`}),(0,u.jsx)(ir,{variant:`end`,onClick:p,compact:h,icon:(0,u.jsx)(Pn,{size:14}),children:`End`})]})]}):(0,u.jsxs)(u.Fragment,{children:[(0,u.jsxs)(`div`,{className:`call-icon-wrapper ${v}`,children:[(0,u.jsx)(Ln,{}),v===`incoming`&&(0,u.jsx)(`div`,{className:`call-pulse-animation`}),v===`connecting`&&(0,u.jsx)(`div`,{className:`call-connecting-animation`})]}),(0,u.jsxs)(`div`,{className:`call-info-group`,children:[(0,u.jsx)(`h3`,{className:`call-title`,children:se}),(0,u.jsx)(`p`,{className:`call-subtitle`,children:ce})]}),(0,u.jsx)(`div`,{className:`call-actions`,children:v===`incoming`&&(0,u.jsxs)(u.Fragment,{children:[(0,u.jsx)(ir,{variant:`reject`,onClick:async()=>{re(),await a()},iconOnly:!0,icon:(0,u.jsx)(Pn,{size:14}),ariaLabel:`Decline call`,children:`Decline`}),(0,u.jsx)(ir,{variant:`accept`,onClick:async()=>{re(),await o()},iconOnly:!0,icon:(0,u.jsx)(Ln,{}),ariaLabel:`Accept call`,children:`Accept`})]})})]})})}),_&&(0,u.jsx)(`div`,{style:{margin:`0 20px 10px`,padding:`12px 16px`,fontSize:`13px`,borderRadius:`12px`,background:`#fee2e2`,color:`#991b1b`},children:te})]})}function or(e,t){return t.forEach(function(t){t&&typeof t!=`string`&&!Array.isArray(t)&&Object.keys(t).forEach(function(n){if(n!==`default`&&!(n in e)){var r=Object.getOwnPropertyDescriptor(t,n);Object.defineProperty(e,n,r.get?r:{enumerable:!0,get:function(){return t[n]}})}})}),Object.freeze(e)}var sr=Object.defineProperty,cr=(e,t,n)=>t in e?sr(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n,lr=(e,t,n)=>cr(e,typeof t==`symbol`?t:t+``,n),ur=class{constructor(){lr(this,`_locking`),lr(this,`_locks`),this._locking=Promise.resolve(),this._locks=0}isLocked(){return this._locks>0}lock(){this._locks+=1;let e,t=new Promise(t=>e=()=>{--this._locks,t()}),n=this._locking.then(()=>e);return this._locking=this._locking.then(()=>t),n}};function E(e,t){if(!e)throw Error(t)}var dr=34028234663852886e22,fr=-34028234663852886e22,pr=4294967295,mr=2147483647,hr=-2147483648;function gr(e){if(typeof e!=`number`)throw Error(`invalid int 32: `+typeof e);if(!Number.isInteger(e)||e>mr||e<hr)throw Error(`invalid int 32: `+e)}function _r(e){if(typeof e!=`number`)throw Error(`invalid uint 32: `+typeof e);if(!Number.isInteger(e)||e>pr||e<0)throw Error(`invalid uint 32: `+e)}function vr(e){if(typeof e!=`number`)throw Error(`invalid float 32: `+typeof e);if(Number.isFinite(e)&&(e>dr||e<fr))throw Error(`invalid float 32: `+e)}var yr=Symbol(`@bufbuild/protobuf/enum-type`);function br(e){let t=e[yr];return E(t,`missing enum type on enum object`),t}function xr(e,t,n,r){e[yr]=Sr(t,n.map(t=>({no:t.no,name:t.name,localName:e[t.no]})))}function Sr(e,t,n){let r=Object.create(null),i=Object.create(null),a=[];for(let e of t){let t=wr(e);a.push(t),r[e.name]=t,i[e.no]=t}return{typeName:e,values:a,findName(e){return r[e]},findNumber(e){return i[e]}}}function Cr(e,t,n){let r={};for(let e of t){let t=wr(e);r[t.localName]=t.no,r[t.no]=t.localName}return xr(r,e,t),r}function wr(e){return`localName`in e?e:Object.assign(Object.assign({},e),{localName:e.name})}var Tr=class{equals(e){return this.getType().runtime.util.equals(this.getType(),this,e)}clone(){return this.getType().runtime.util.clone(this)}fromBinary(e,t){let n=this.getType().runtime.bin,r=n.makeReadOptions(t);return n.readMessage(this,r.readerFactory(e),e.byteLength,r),this}fromJson(e,t){let n=this.getType(),r=n.runtime.json,i=r.makeReadOptions(t);return r.readMessage(n,e,i,this),this}fromJsonString(e,t){let n;try{n=JSON.parse(e)}catch(e){throw Error(`cannot decode ${this.getType().typeName} from JSON: ${e instanceof Error?e.message:String(e)}`)}return this.fromJson(n,t)}toBinary(e){let t=this.getType().runtime.bin,n=t.makeWriteOptions(e),r=n.writerFactory();return t.writeMessage(this,r,n),r.finish()}toJson(e){let t=this.getType().runtime.json,n=t.makeWriteOptions(e);return t.writeMessage(this,n)}toJsonString(e){let t=this.toJson(e);return JSON.stringify(t,null,e?.prettySpaces??0)}toJSON(){return this.toJson({emitDefaultValues:!0})}getType(){return Object.getPrototypeOf(this).constructor}};function Er(e,t,n,r){let i=r?.localName??t.substring(t.lastIndexOf(`.`)+1),a={[i]:function(t){e.util.initFields(this),e.util.initPartial(t,this)}}[i];return Object.setPrototypeOf(a.prototype,new Tr),Object.assign(a,{runtime:e,typeName:t,fields:e.util.newFieldList(n),fromBinary(e,t){return new a().fromBinary(e,t)},fromJson(e,t){return new a().fromJson(e,t)},fromJsonString(e,t){return new a().fromJsonString(e,t)},equals(t,n){return e.util.equals(a,t,n)}}),a}function Dr(){let e=0,t=0;for(let n=0;n<28;n+=7){let r=this.buf[this.pos++];if(e|=(r&127)<<n,!(r&128))return this.assertBounds(),[e,t]}let n=this.buf[this.pos++];if(e|=(n&15)<<28,t=(n&112)>>4,!(n&128))return this.assertBounds(),[e,t];for(let n=3;n<=31;n+=7){let r=this.buf[this.pos++];if(t|=(r&127)<<n,!(r&128))return this.assertBounds(),[e,t]}throw Error(`invalid varint`)}function Or(e,t,n){for(let r=0;r<28;r+=7){let i=e>>>r,a=!(!(i>>>7)&&t==0),o=(a?i|128:i)&255;if(n.push(o),!a)return}let r=e>>>28&15|(t&7)<<4,i=!!(t>>3);if(n.push((i?r|128:r)&255),i){for(let e=3;e<31;e+=7){let r=t>>>e,i=!!(r>>>7),a=(i?r|128:r)&255;if(n.push(a),!i)return}n.push(t>>>31&1)}}var kr=4294967296;function Ar(e){let t=e[0]===`-`;t&&(e=e.slice(1));let n=1e6,r=0,i=0;function a(t,a){let o=Number(e.slice(t,a));i*=n,r=r*n+o,r>=kr&&(i+=r/kr|0,r%=kr)}return a(-24,-18),a(-18,-12),a(-12,-6),a(-6),t?Fr(r,i):Pr(r,i)}function jr(e,t){let n=Pr(e,t),r=n.hi&2147483648;r&&(n=Fr(n.lo,n.hi));let i=Mr(n.lo,n.hi);return r?`-`+i:i}function Mr(e,t){if({lo:e,hi:t}=Nr(e,t),t<=2097151)return String(kr*t+e);let n=e&16777215,r=(e>>>24|t<<8)&16777215,i=t>>16&65535,a=n+r*6777216+i*6710656,o=r+i*8147497,s=i*2,c=1e7;return a>=c&&(o+=Math.floor(a/c),a%=c),o>=c&&(s+=Math.floor(o/c),o%=c),s.toString()+Ir(o)+Ir(a)}function Nr(e,t){return{lo:e>>>0,hi:t>>>0}}function Pr(e,t){return{lo:e|0,hi:t|0}}function Fr(e,t){return t=~t,e?e=~e+1:t+=1,Pr(e,t)}var Ir=e=>{let t=String(e);return`0000000`.slice(t.length)+t};function Lr(e,t){if(e>=0){for(;e>127;)t.push(e&127|128),e>>>=7;t.push(e)}else{for(let n=0;n<9;n++)t.push(e&127|128),e>>=7;t.push(1)}}function Rr(){let e=this.buf[this.pos++],t=e&127;if(!(e&128)||(e=this.buf[this.pos++],t|=(e&127)<<7,!(e&128))||(e=this.buf[this.pos++],t|=(e&127)<<14,!(e&128))||(e=this.buf[this.pos++],t|=(e&127)<<21,!(e&128)))return this.assertBounds(),t;e=this.buf[this.pos++],t|=(e&15)<<28;for(let t=5;e&128&&t<10;t++)e=this.buf[this.pos++];if(e&128)throw Error(`invalid varint`);return this.assertBounds(),t>>>0}function zr(){let e=new DataView(new ArrayBuffer(8));if(typeof BigInt==`function`&&typeof e.getBigInt64==`function`&&typeof e.getBigUint64==`function`&&typeof e.setBigInt64==`function`&&typeof e.setBigUint64==`function`&&(typeof process!=`object`||typeof process.env!=`object`||process.env.BUF_BIGINT_DISABLE!==`1`)){let t=BigInt(`-9223372036854775808`),n=BigInt(`9223372036854775807`),r=BigInt(`0`),i=BigInt(`18446744073709551615`);return{zero:BigInt(0),supported:!0,parse(e){let r=typeof e==`bigint`?e:BigInt(e);if(r>n||r<t)throw Error(`int64 invalid: ${e}`);return r},uParse(e){let t=typeof e==`bigint`?e:BigInt(e);if(t>i||t<r)throw Error(`uint64 invalid: ${e}`);return t},enc(t){return e.setBigInt64(0,this.parse(t),!0),{lo:e.getInt32(0,!0),hi:e.getInt32(4,!0)}},uEnc(t){return e.setBigInt64(0,this.uParse(t),!0),{lo:e.getInt32(0,!0),hi:e.getInt32(4,!0)}},dec(t,n){return e.setInt32(0,t,!0),e.setInt32(4,n,!0),e.getBigInt64(0,!0)},uDec(t,n){return e.setInt32(0,t,!0),e.setInt32(4,n,!0),e.getBigUint64(0,!0)}}}let t=e=>E(/^-?[0-9]+$/.test(e),`int64 invalid: ${e}`),n=e=>E(/^[0-9]+$/.test(e),`uint64 invalid: ${e}`);return{zero:`0`,supported:!1,parse(e){return typeof e!=`string`&&(e=e.toString()),t(e),e},uParse(e){return typeof e!=`string`&&(e=e.toString()),n(e),e},enc(e){return typeof e!=`string`&&(e=e.toString()),t(e),Ar(e)},uEnc(e){return typeof e!=`string`&&(e=e.toString()),n(e),Ar(e)},dec(e,t){return jr(e,t)},uDec(e,t){return Mr(e,t)}}}var D=zr(),O;(function(e){e[e.DOUBLE=1]=`DOUBLE`,e[e.FLOAT=2]=`FLOAT`,e[e.INT64=3]=`INT64`,e[e.UINT64=4]=`UINT64`,e[e.INT32=5]=`INT32`,e[e.FIXED64=6]=`FIXED64`,e[e.FIXED32=7]=`FIXED32`,e[e.BOOL=8]=`BOOL`,e[e.STRING=9]=`STRING`,e[e.BYTES=12]=`BYTES`,e[e.UINT32=13]=`UINT32`,e[e.SFIXED32=15]=`SFIXED32`,e[e.SFIXED64=16]=`SFIXED64`,e[e.SINT32=17]=`SINT32`,e[e.SINT64=18]=`SINT64`})(O||={});var Br;(function(e){e[e.BIGINT=0]=`BIGINT`,e[e.STRING=1]=`STRING`})(Br||={});function Vr(e,t,n){if(t===n)return!0;if(e==O.BYTES){if(!(t instanceof Uint8Array)||!(n instanceof Uint8Array)||t.length!==n.length)return!1;for(let e=0;e<t.length;e++)if(t[e]!==n[e])return!1;return!0}switch(e){case O.UINT64:case O.FIXED64:case O.INT64:case O.SFIXED64:case O.SINT64:return t==n}return!1}function Hr(e,t){switch(e){case O.BOOL:return!1;case O.UINT64:case O.FIXED64:case O.INT64:case O.SFIXED64:case O.SINT64:return t==0?D.zero:`0`;case O.DOUBLE:case O.FLOAT:return 0;case O.BYTES:return new Uint8Array;case O.STRING:return``;default:return 0}}function Ur(e,t){switch(e){case O.BOOL:return t===!1;case O.STRING:return t===``;case O.BYTES:return t instanceof Uint8Array&&!t.byteLength;default:return t==0}}var Wr;(function(e){e[e.Varint=0]=`Varint`,e[e.Bit64=1]=`Bit64`,e[e.LengthDelimited=2]=`LengthDelimited`,e[e.StartGroup=3]=`StartGroup`,e[e.EndGroup=4]=`EndGroup`,e[e.Bit32=5]=`Bit32`})(Wr||={});var Gr=class{constructor(e){this.stack=[],this.textEncoder=e??new TextEncoder,this.chunks=[],this.buf=[]}finish(){this.chunks.push(new Uint8Array(this.buf));let e=0;for(let t=0;t<this.chunks.length;t++)e+=this.chunks[t].length;let t=new Uint8Array(e),n=0;for(let e=0;e<this.chunks.length;e++)t.set(this.chunks[e],n),n+=this.chunks[e].length;return this.chunks=[],t}fork(){return this.stack.push({chunks:this.chunks,buf:this.buf}),this.chunks=[],this.buf=[],this}join(){let e=this.finish(),t=this.stack.pop();if(!t)throw Error(`invalid state, fork stack empty`);return this.chunks=t.chunks,this.buf=t.buf,this.uint32(e.byteLength),this.raw(e)}tag(e,t){return this.uint32((e<<3|t)>>>0)}raw(e){return this.buf.length&&(this.chunks.push(new Uint8Array(this.buf)),this.buf=[]),this.chunks.push(e),this}uint32(e){for(_r(e);e>127;)this.buf.push(e&127|128),e>>>=7;return this.buf.push(e),this}int32(e){return gr(e),Lr(e,this.buf),this}bool(e){return this.buf.push(e?1:0),this}bytes(e){return this.uint32(e.byteLength),this.raw(e)}string(e){let t=this.textEncoder.encode(e);return this.uint32(t.byteLength),this.raw(t)}float(e){vr(e);let t=new Uint8Array(4);return new DataView(t.buffer).setFloat32(0,e,!0),this.raw(t)}double(e){let t=new Uint8Array(8);return new DataView(t.buffer).setFloat64(0,e,!0),this.raw(t)}fixed32(e){_r(e);let t=new Uint8Array(4);return new DataView(t.buffer).setUint32(0,e,!0),this.raw(t)}sfixed32(e){gr(e);let t=new Uint8Array(4);return new DataView(t.buffer).setInt32(0,e,!0),this.raw(t)}sint32(e){return gr(e),e=(e<<1^e>>31)>>>0,Lr(e,this.buf),this}sfixed64(e){let t=new Uint8Array(8),n=new DataView(t.buffer),r=D.enc(e);return n.setInt32(0,r.lo,!0),n.setInt32(4,r.hi,!0),this.raw(t)}fixed64(e){let t=new Uint8Array(8),n=new DataView(t.buffer),r=D.uEnc(e);return n.setInt32(0,r.lo,!0),n.setInt32(4,r.hi,!0),this.raw(t)}int64(e){let t=D.enc(e);return Or(t.lo,t.hi,this.buf),this}sint64(e){let t=D.enc(e),n=t.hi>>31;return Or(t.lo<<1^n,(t.hi<<1|t.lo>>>31)^n,this.buf),this}uint64(e){let t=D.uEnc(e);return Or(t.lo,t.hi,this.buf),this}},Kr=class{constructor(e,t){this.varint64=Dr,this.uint32=Rr,this.buf=e,this.len=e.length,this.pos=0,this.view=new DataView(e.buffer,e.byteOffset,e.byteLength),this.textDecoder=t??new TextDecoder}tag(){let e=this.uint32(),t=e>>>3,n=e&7;if(t<=0||n<0||n>5)throw Error(`illegal tag: field no `+t+` wire type `+n);return[t,n]}skip(e,t){let n=this.pos;switch(e){case Wr.Varint:for(;this.buf[this.pos++]&128;);break;case Wr.Bit64:this.pos+=4;case Wr.Bit32:this.pos+=4;break;case Wr.LengthDelimited:let n=this.uint32();this.pos+=n;break;case Wr.StartGroup:for(;;){let[e,n]=this.tag();if(n===Wr.EndGroup){if(t!==void 0&&e!==t)throw Error(`invalid end group tag`);break}this.skip(n,e)}break;default:throw Error(`cant skip wire type `+e)}return this.assertBounds(),this.buf.subarray(n,this.pos)}assertBounds(){if(this.pos>this.len)throw RangeError(`premature EOF`)}int32(){return this.uint32()|0}sint32(){let e=this.uint32();return e>>>1^-(e&1)}int64(){return D.dec(...this.varint64())}uint64(){return D.uDec(...this.varint64())}sint64(){let[e,t]=this.varint64(),n=-(e&1);return e=(e>>>1|(t&1)<<31)^n,t=t>>>1^n,D.dec(e,t)}bool(){let[e,t]=this.varint64();return e!==0||t!==0}fixed32(){return this.view.getUint32((this.pos+=4)-4,!0)}sfixed32(){return this.view.getInt32((this.pos+=4)-4,!0)}fixed64(){return D.uDec(this.sfixed32(),this.sfixed32())}sfixed64(){return D.dec(this.sfixed32(),this.sfixed32())}float(){return this.view.getFloat32((this.pos+=4)-4,!0)}double(){return this.view.getFloat64((this.pos+=8)-8,!0)}bytes(){let e=this.uint32(),t=this.pos;return this.pos+=e,this.assertBounds(),this.buf.subarray(t,t+e)}string(){return this.textDecoder.decode(this.bytes())}};function qr(e,t,n,r){let i;return{typeName:t,extendee:n,get field(){if(!i){let n=typeof r==`function`?r():r;n.name=t.split(`.`).pop(),n.jsonName=`[${t}]`,i=e.util.newFieldList([n]).list()[0]}return i},runtime:e}}function Jr(e){let t=e.field.localName,n=Object.create(null);return n[t]=Yr(e),[n,()=>n[t]]}function Yr(e){let t=e.field;if(t.repeated)return[];if(t.default!==void 0)return t.default;switch(t.kind){case`enum`:return t.T.values[0].no;case`scalar`:return Hr(t.T,t.L);case`message`:let e=t.T,n=new e;return e.fieldWrapper?e.fieldWrapper.unwrapField(n):n;case`map`:throw`map fields are not allowed to be extensions`}}function Xr(e,t){if(!t.repeated&&(t.kind==`enum`||t.kind==`scalar`)){for(let n=e.length-1;n>=0;--n)if(e[n].no==t.no)return[e[n]];return[]}return e.filter(e=>e.no===t.no)}var Zr=`ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/`.split(``),Qr=[];for(let e=0;e<Zr.length;e++)Qr[Zr[e].charCodeAt(0)]=e;Qr[45]=Zr.indexOf(`+`),Qr[95]=Zr.indexOf(`/`);var $r={dec(e){let t=e.length*3/4;e[e.length-2]==`=`?t-=2:e[e.length-1]==`=`&&--t;let n=new Uint8Array(t),r=0,i=0,a,o=0;for(let t=0;t<e.length;t++){if(a=Qr[e.charCodeAt(t)],a===void 0)switch(e[t]){case`=`:i=0;case`
|
|
31
|
-
`:case`\r`:case` `:case` `:continue;default:throw Error(`invalid base64 string.`)}switch(i){case 0:o=a,i=1;break;case 1:n[r++]=o<<2|(a&48)>>4,o=a,i=2;break;case 2:n[r++]=(o&15)<<4|(a&60)>>2,o=a,i=3;break;case 3:n[r++]=(o&3)<<6|a,i=0;break}}if(i==1)throw Error(`invalid base64 string.`);return n.subarray(0,r)},enc(e){let t=``,n=0,r,i=0;for(let a=0;a<e.length;a++)switch(r=e[a],n){case 0:t+=Zr[r>>2],i=(r&3)<<4,n=1;break;case 1:t+=Zr[i|r>>4],i=(r&15)<<2,n=2;break;case 2:t+=Zr[i|r>>6],t+=Zr[r&63],n=0;break}return n&&(t+=Zr[i],t+=`=`,n==1&&(t+=`=`)),t}};function ei(e,t,n){ri(t,e);let r=t.runtime.bin.makeReadOptions(n),i=Xr(e.getType().runtime.bin.listUnknownFields(e),t.field),[a,o]=Jr(t);for(let e of i)t.runtime.bin.readField(a,r.readerFactory(e.data),t.field,e.wireType,r);return o()}function ti(e,t,n,r){ri(t,e);let i=t.runtime.bin.makeReadOptions(r),a=t.runtime.bin.makeWriteOptions(r);if(ni(e,t)){let n=e.getType().runtime.bin.listUnknownFields(e).filter(e=>e.no!=t.field.no);e.getType().runtime.bin.discardUnknownFields(e);for(let t of n)e.getType().runtime.bin.onUnknownField(e,t.no,t.wireType,t.data)}let o=a.writerFactory(),s=t.field;!s.opt&&!s.repeated&&(s.kind==`enum`||s.kind==`scalar`)&&(s=Object.assign(Object.assign({},t.field),{opt:!0})),t.runtime.bin.writeField(s,n,o,a);let c=i.readerFactory(o.finish());for(;c.pos<c.len;){let[t,n]=c.tag(),r=c.skip(n,t);e.getType().runtime.bin.onUnknownField(e,t,n,r)}}function ni(e,t){let n=e.getType();return t.extendee.typeName===n.typeName&&!!n.runtime.bin.listUnknownFields(e).find(e=>e.no==t.field.no)}function ri(e,t){E(e.extendee.typeName==t.getType().typeName,`extension ${e.typeName} can only be applied to message ${e.extendee.typeName}`)}function ii(e,t){let n=e.localName;if(e.repeated)return t[n].length>0;if(e.oneof)return t[e.oneof.localName].case===n;switch(e.kind){case`enum`:case`scalar`:return e.opt||e.req?t[n]!==void 0:e.kind==`enum`?t[n]!==e.T.values[0].no:!Ur(e.T,t[n]);case`message`:return t[n]!==void 0;case`map`:return Object.keys(t[n]).length>0}}function ai(e,t){let n=e.localName,r=!e.opt&&!e.req;if(e.repeated)t[n]=[];else if(e.oneof)t[e.oneof.localName]={case:void 0};else switch(e.kind){case`map`:t[n]={};break;case`enum`:t[n]=r?e.T.values[0].no:void 0;break;case`scalar`:t[n]=r?Hr(e.T,e.L):void 0;break;case`message`:t[n]=void 0;break}}function oi(e,t){if(typeof e!=`object`||!e||!Object.getOwnPropertyNames(Tr.prototype).every(t=>t in e&&typeof e[t]==`function`))return!1;let n=e.getType();return n===null||typeof n!=`function`||!(`typeName`in n)||typeof n.typeName!=`string`?!1:t===void 0?!0:n.typeName==t.typeName}function si(e,t){return oi(t)||!e.fieldWrapper?t:e.fieldWrapper.wrapField(t)}O.DOUBLE,O.FLOAT,O.INT64,O.UINT64,O.INT32,O.UINT32,O.BOOL,O.STRING,O.BYTES;var ci={ignoreUnknownFields:!1},li={emitDefaultValues:!1,enumAsInteger:!1,useProtoFieldName:!1,prettySpaces:0};function ui(e){return e?Object.assign(Object.assign({},ci),e):ci}function di(e){return e?Object.assign(Object.assign({},li),e):li}var fi=Symbol(),pi=Symbol();function mi(){return{makeReadOptions:ui,makeWriteOptions:di,readMessage(e,t,n,r){if(t==null||Array.isArray(t)||typeof t!=`object`)throw Error(`cannot decode message ${e.typeName} from JSON: ${hi(t)}`);r??=new e;let i=new Map,a=n.typeRegistry;for(let[o,s]of Object.entries(t)){let t=e.fields.findJsonName(o);if(t){if(t.oneof){if(s===null&&t.kind==`scalar`)continue;let n=i.get(t.oneof);if(n!==void 0)throw Error(`cannot decode message ${e.typeName} from JSON: multiple keys for oneof "${t.oneof.name}" present: "${n}", "${o}"`);i.set(t.oneof,o)}gi(r,s,t,n,e)}else{let t=!1;if(a?.findExtension&&o.startsWith(`[`)&&o.endsWith(`]`)){let i=a.findExtension(o.substring(1,o.length-1));if(i&&i.extendee.typeName==e.typeName){t=!0;let[e,a]=Jr(i);gi(e,s,i.field,n,i),ti(r,i,a(),n)}}if(!t&&!n.ignoreUnknownFields)throw Error(`cannot decode message ${e.typeName} from JSON: key "${o}" is unknown`)}}return r},writeMessage(e,t){let n=e.getType(),r={},i;try{for(i of n.fields.byNumber()){if(!ii(i,e)){if(i.req)throw`required field not set`;if(!t.emitDefaultValues||!bi(i))continue}let n=i.oneof?e[i.oneof.localName].value:e[i.localName],a=xi(i,n,t);a!==void 0&&(r[t.useProtoFieldName?i.name:i.jsonName]=a)}let a=t.typeRegistry;if(a?.findExtensionFor)for(let i of n.runtime.bin.listUnknownFields(e)){let o=a.findExtensionFor(n.typeName,i.no);if(o&&ni(e,o)){let n=ei(e,o,t),i=xi(o.field,n,t);i!==void 0&&(r[o.field.jsonName]=i)}}}catch(e){let t=i?`cannot encode field ${n.typeName}.${i.name} to JSON`:`cannot encode message ${n.typeName} to JSON`,r=e instanceof Error?e.message:String(e);throw Error(t+(r.length>0?`: ${r}`:``))}return r},readScalar(e,t,n){return vi(e,t,n??Br.BIGINT,!0)},writeScalar(e,t,n){if(t!==void 0&&(n||Ur(e,t)))return Ci(e,t)},debug:hi}}function hi(e){if(e===null)return`null`;switch(typeof e){case`object`:return Array.isArray(e)?`array`:`object`;case`string`:return e.length>100?`string`:`"${e.split(`"`).join(`\\"`)}"`;default:return String(e)}}function gi(e,t,n,r,i){let a=n.localName;if(n.repeated){if(E(n.kind!=`map`),t===null)return;if(!Array.isArray(t))throw Error(`cannot decode field ${i.typeName}.${n.name} from JSON: ${hi(t)}`);let o=e[a];for(let e of t){if(e===null)throw Error(`cannot decode field ${i.typeName}.${n.name} from JSON: ${hi(e)}`);switch(n.kind){case`message`:o.push(n.T.fromJson(e,r));break;case`enum`:let t=yi(n.T,e,r.ignoreUnknownFields,!0);t!==pi&&o.push(t);break;case`scalar`:try{o.push(vi(n.T,e,n.L,!0))}catch(t){let r=`cannot decode field ${i.typeName}.${n.name} from JSON: ${hi(e)}`;throw t instanceof Error&&t.message.length>0&&(r+=`: ${t.message}`),Error(r)}break}}}else if(n.kind==`map`){if(t===null)return;if(typeof t!=`object`||Array.isArray(t))throw Error(`cannot decode field ${i.typeName}.${n.name} from JSON: ${hi(t)}`);let o=e[a];for(let[e,a]of Object.entries(t)){if(a===null)throw Error(`cannot decode field ${i.typeName}.${n.name} from JSON: map value null`);let s;try{s=_i(n.K,e)}catch(e){let r=`cannot decode map key for field ${i.typeName}.${n.name} from JSON: ${hi(t)}`;throw e instanceof Error&&e.message.length>0&&(r+=`: ${e.message}`),Error(r)}switch(n.V.kind){case`message`:o[s]=n.V.T.fromJson(a,r);break;case`enum`:let e=yi(n.V.T,a,r.ignoreUnknownFields,!0);e!==pi&&(o[s]=e);break;case`scalar`:try{o[s]=vi(n.V.T,a,Br.BIGINT,!0)}catch(e){let r=`cannot decode map value for field ${i.typeName}.${n.name} from JSON: ${hi(t)}`;throw e instanceof Error&&e.message.length>0&&(r+=`: ${e.message}`),Error(r)}break}}}else switch(n.oneof&&(e=e[n.oneof.localName]={case:a},a=`value`),n.kind){case`message`:let o=n.T;if(t===null&&o.typeName!=`google.protobuf.Value`)return;let s=e[a];oi(s)?s.fromJson(t,r):(e[a]=s=o.fromJson(t,r),o.fieldWrapper&&!n.oneof&&(e[a]=o.fieldWrapper.unwrapField(s)));break;case`enum`:let c=yi(n.T,t,r.ignoreUnknownFields,!1);switch(c){case fi:ai(n,e);break;case pi:break;default:e[a]=c;break}break;case`scalar`:try{let r=vi(n.T,t,n.L,!1);switch(r){case fi:ai(n,e);break;default:e[a]=r;break}}catch(e){let r=`cannot decode field ${i.typeName}.${n.name} from JSON: ${hi(t)}`;throw e instanceof Error&&e.message.length>0&&(r+=`: ${e.message}`),Error(r)}break}}function _i(e,t){if(e===O.BOOL)switch(t){case`true`:t=!0;break;case`false`:t=!1;break}return vi(e,t,Br.BIGINT,!0).toString()}function vi(e,t,n,r){if(t===null)return r?Hr(e,n):fi;switch(e){case O.DOUBLE:case O.FLOAT:if(t===`NaN`)return NaN;if(t===`Infinity`)return 1/0;if(t===`-Infinity`)return-1/0;if(t===``||typeof t==`string`&&t.trim().length!==t.length||typeof t!=`string`&&typeof t!=`number`)break;let r=Number(t);if(Number.isNaN(r)||!Number.isFinite(r))break;return e==O.FLOAT&&vr(r),r;case O.INT32:case O.FIXED32:case O.SFIXED32:case O.SINT32:case O.UINT32:let i;if(typeof t==`number`?i=t:typeof t==`string`&&t.length>0&&t.trim().length===t.length&&(i=Number(t)),i===void 0)break;return e==O.UINT32||e==O.FIXED32?_r(i):gr(i),i;case O.INT64:case O.SFIXED64:case O.SINT64:if(typeof t!=`number`&&typeof t!=`string`)break;let a=D.parse(t);return n?a.toString():a;case O.FIXED64:case O.UINT64:if(typeof t!=`number`&&typeof t!=`string`)break;let o=D.uParse(t);return n?o.toString():o;case O.BOOL:if(typeof t!=`boolean`)break;return t;case O.STRING:if(typeof t!=`string`)break;return t;case O.BYTES:if(t===``)return new Uint8Array;if(typeof t!=`string`)break;return $r.dec(t)}throw Error()}function yi(e,t,n,r){if(t===null)return e.typeName==`google.protobuf.NullValue`?0:r?e.values[0].no:fi;switch(typeof t){case`number`:if(Number.isInteger(t))return t;break;case`string`:let r=e.findName(t);if(r!==void 0)return r.no;if(n)return pi;break}throw Error(`cannot decode enum ${e.typeName} from JSON: ${hi(t)}`)}function bi(e){return e.repeated||e.kind==`map`?!0:!(e.oneof||e.kind==`message`||e.opt||e.req)}function xi(e,t,n){if(e.kind==`map`){E(typeof t==`object`&&!!t);let r={},i=Object.entries(t);switch(e.V.kind){case`scalar`:for(let[t,n]of i)r[t.toString()]=Ci(e.V.T,n);break;case`message`:for(let[e,t]of i)r[e.toString()]=t.toJson(n);break;case`enum`:let t=e.V.T;for(let[e,a]of i)r[e.toString()]=Si(t,a,n.enumAsInteger);break}return n.emitDefaultValues||i.length>0?r:void 0}if(e.repeated){E(Array.isArray(t));let r=[];switch(e.kind){case`scalar`:for(let n=0;n<t.length;n++)r.push(Ci(e.T,t[n]));break;case`enum`:for(let i=0;i<t.length;i++)r.push(Si(e.T,t[i],n.enumAsInteger));break;case`message`:for(let e=0;e<t.length;e++)r.push(t[e].toJson(n));break}return n.emitDefaultValues||r.length>0?r:void 0}switch(e.kind){case`scalar`:return Ci(e.T,t);case`enum`:return Si(e.T,t,n.enumAsInteger);case`message`:return si(e.T,t).toJson(n)}}function Si(e,t,n){return E(typeof t==`number`),e.typeName==`google.protobuf.NullValue`?null:n?t:e.findNumber(t)?.name??t}function Ci(e,t){switch(e){case O.INT32:case O.SFIXED32:case O.SINT32:case O.FIXED32:case O.UINT32:return E(typeof t==`number`),t;case O.FLOAT:case O.DOUBLE:return E(typeof t==`number`),Number.isNaN(t)?`NaN`:t===1/0?`Infinity`:t===-1/0?`-Infinity`:t;case O.STRING:return E(typeof t==`string`),t;case O.BOOL:return E(typeof t==`boolean`),t;case O.UINT64:case O.FIXED64:case O.INT64:case O.SFIXED64:case O.SINT64:return E(typeof t==`bigint`||typeof t==`string`||typeof t==`number`),t.toString();case O.BYTES:return E(t instanceof Uint8Array),$r.enc(t)}}var wi=Symbol(`@bufbuild/protobuf/unknown-fields`),Ti={readUnknownFields:!0,readerFactory:e=>new Kr(e)},Ei={writeUnknownFields:!0,writerFactory:()=>new Gr};function Di(e){return e?Object.assign(Object.assign({},Ti),e):Ti}function Oi(e){return e?Object.assign(Object.assign({},Ei),e):Ei}function ki(){return{makeReadOptions:Di,makeWriteOptions:Oi,listUnknownFields(e){return e[wi]??[]},discardUnknownFields(e){delete e[wi]},writeUnknownFields(e,t){let n=e[wi];if(n)for(let e of n)t.tag(e.no,e.wireType).raw(e.data)},onUnknownField(e,t,n,r){let i=e;Array.isArray(i[wi])||(i[wi]=[]),i[wi].push({no:t,wireType:n,data:r})},readMessage(e,t,n,r,i){let a=e.getType(),o=i?t.len:t.pos+n,s,c;for(;t.pos<o&&([s,c]=t.tag(),!(i===!0&&c==Wr.EndGroup));){let n=a.fields.find(s);if(!n){let n=t.skip(c,s);r.readUnknownFields&&this.onUnknownField(e,s,c,n);continue}Ai(e,t,n,c,r)}if(i&&(c!=Wr.EndGroup||s!==n))throw Error(`invalid end group tag`)},readField:Ai,writeMessage(e,t,n){let r=e.getType();for(let i of r.fields.byNumber()){if(!ii(i,e)){if(i.req)throw Error(`cannot encode field ${r.typeName}.${i.name} to binary: required field not set`);continue}Fi(i,i.oneof?e[i.oneof.localName].value:e[i.localName],t,n)}return n.writeUnknownFields&&this.writeUnknownFields(e,t),t},writeField(e,t,n,r){t!==void 0&&Fi(e,t,n,r)}}}function Ai(e,t,n,r,i){let{repeated:a,localName:o}=n;switch(n.oneof&&(e=e[n.oneof.localName],e.case!=o&&delete e.value,e.case=o,o=`value`),n.kind){case`scalar`:case`enum`:let s=n.kind==`enum`?O.INT32:n.T,c=Pi;if(n.kind==`scalar`&&n.L>0&&(c=Ni),a){let n=e[o];if(r==Wr.LengthDelimited&&s!=O.STRING&&s!=O.BYTES){let e=t.uint32()+t.pos;for(;t.pos<e;)n.push(c(t,s))}else n.push(c(t,s))}else e[o]=c(t,s);break;case`message`:let l=n.T;a?e[o].push(ji(t,new l,i,n)):oi(e[o])?ji(t,e[o],i,n):(e[o]=ji(t,new l,i,n),l.fieldWrapper&&!n.oneof&&!n.repeated&&(e[o]=l.fieldWrapper.unwrapField(e[o])));break;case`map`:let[u,d]=Mi(n,t,i);e[o][u]=d;break}}function ji(e,t,n,r){let i=t.getType().runtime.bin,a=r?.delimited;return i.readMessage(t,e,a?r.no:e.uint32(),n,a),t}function Mi(e,t,n){let r=t.uint32(),i=t.pos+r,a,o;for(;t.pos<i;){let[r]=t.tag();switch(r){case 1:a=Pi(t,e.K);break;case 2:switch(e.V.kind){case`scalar`:o=Pi(t,e.V.T);break;case`enum`:o=t.int32();break;case`message`:o=ji(t,new e.V.T,n,void 0);break}break}}if(a===void 0&&(a=Hr(e.K,Br.BIGINT)),typeof a!=`string`&&typeof a!=`number`&&(a=a.toString()),o===void 0)switch(e.V.kind){case`scalar`:o=Hr(e.V.T,Br.BIGINT);break;case`enum`:o=e.V.T.values[0].no;break;case`message`:o=new e.V.T;break}return[a,o]}function Ni(e,t){let n=Pi(e,t);return typeof n==`bigint`?n.toString():n}function Pi(e,t){switch(t){case O.STRING:return e.string();case O.BOOL:return e.bool();case O.DOUBLE:return e.double();case O.FLOAT:return e.float();case O.INT32:return e.int32();case O.INT64:return e.int64();case O.UINT64:return e.uint64();case O.FIXED64:return e.fixed64();case O.BYTES:return e.bytes();case O.FIXED32:return e.fixed32();case O.SFIXED32:return e.sfixed32();case O.SFIXED64:return e.sfixed64();case O.SINT64:return e.sint64();case O.UINT32:return e.uint32();case O.SINT32:return e.sint32()}}function Fi(e,t,n,r){E(t!==void 0);let i=e.repeated;switch(e.kind){case`scalar`:case`enum`:let a=e.kind==`enum`?O.INT32:e.T;if(i)if(E(Array.isArray(t)),e.packed)zi(n,a,e.no,t);else for(let r of t)Ri(n,a,e.no,r);else Ri(n,a,e.no,t);break;case`message`:if(i){E(Array.isArray(t));for(let i of t)Li(n,r,e,i)}else Li(n,r,e,t);break;case`map`:E(typeof t==`object`&&!!t);for(let[i,a]of Object.entries(t))Ii(n,r,e,i,a);break}}function Ii(e,t,n,r,i){e.tag(n.no,Wr.LengthDelimited),e.fork();let a=r;switch(n.K){case O.INT32:case O.FIXED32:case O.UINT32:case O.SFIXED32:case O.SINT32:a=Number.parseInt(r);break;case O.BOOL:E(r==`true`||r==`false`),a=r==`true`;break}switch(Ri(e,n.K,1,a),n.V.kind){case`scalar`:Ri(e,n.V.T,2,i);break;case`enum`:Ri(e,O.INT32,2,i);break;case`message`:E(i!==void 0),e.tag(2,Wr.LengthDelimited).bytes(i.toBinary(t));break}e.join()}function Li(e,t,n,r){let i=si(n.T,r);n.delimited?e.tag(n.no,Wr.StartGroup).raw(i.toBinary(t)).tag(n.no,Wr.EndGroup):e.tag(n.no,Wr.LengthDelimited).bytes(i.toBinary(t))}function Ri(e,t,n,r){E(r!==void 0);let[i,a]=Bi(t);e.tag(n,i)[a](r)}function zi(e,t,n,r){if(!r.length)return;e.tag(n,Wr.LengthDelimited).fork();let[,i]=Bi(t);for(let t=0;t<r.length;t++)e[i](r[t]);e.join()}function Bi(e){let t=Wr.Varint;switch(e){case O.BYTES:case O.STRING:t=Wr.LengthDelimited;break;case O.DOUBLE:case O.FIXED64:case O.SFIXED64:t=Wr.Bit64;break;case O.FIXED32:case O.SFIXED32:case O.FLOAT:t=Wr.Bit32;break}let n=O[e].toLowerCase();return[t,n]}function Vi(){return{setEnumType:xr,initPartial(e,t){if(e===void 0)return;let n=t.getType();for(let r of n.fields.byMember()){let n=r.localName,i=t,a=e;if(a[n]!=null)switch(r.kind){case`oneof`:let e=a[n].case;if(e===void 0)continue;let t=r.findField(e),o=a[n].value;t&&t.kind==`message`&&!oi(o,t.T)?o=new t.T(o):t&&t.kind===`scalar`&&t.T===O.BYTES&&(o=Ui(o)),i[n]={case:e,value:o};break;case`scalar`:case`enum`:let s=a[n];r.T===O.BYTES&&(s=r.repeated?s.map(Ui):Ui(s)),i[n]=s;break;case`map`:switch(r.V.kind){case`scalar`:case`enum`:if(r.V.T===O.BYTES)for(let[e,t]of Object.entries(a[n]))i[n][e]=Ui(t);else Object.assign(i[n],a[n]);break;case`message`:let e=r.V.T;for(let t of Object.keys(a[n])){let r=a[n][t];e.fieldWrapper||(r=new e(r)),i[n][t]=r}break}break;case`message`:let c=r.T;if(r.repeated)i[n]=a[n].map(e=>oi(e,c)?e:new c(e));else{let e=a[n];c.fieldWrapper?c.typeName===`google.protobuf.BytesValue`?i[n]=Ui(e):i[n]=e:i[n]=oi(e,c)?e:new c(e)}break}}},equals(e,t,n){return t===n?!0:!t||!n?!1:e.fields.byMember().every(e=>{let r=t[e.localName],i=n[e.localName];if(e.repeated){if(r.length!==i.length)return!1;switch(e.kind){case`message`:return r.every((t,n)=>e.T.equals(t,i[n]));case`scalar`:return r.every((t,n)=>Vr(e.T,t,i[n]));case`enum`:return r.every((e,t)=>Vr(O.INT32,e,i[t]))}throw Error(`repeated cannot contain ${e.kind}`)}switch(e.kind){case`message`:let t=r,n=i;return e.T.fieldWrapper&&(t!==void 0&&!oi(t)&&(t=e.T.fieldWrapper.wrapField(t)),n!==void 0&&!oi(n)&&(n=e.T.fieldWrapper.wrapField(n))),e.T.equals(t,n);case`enum`:return Vr(O.INT32,r,i);case`scalar`:return Vr(e.T,r,i);case`oneof`:if(r.case!==i.case)return!1;let a=e.findField(r.case);if(a===void 0)return!0;switch(a.kind){case`message`:return a.T.equals(r.value,i.value);case`enum`:return Vr(O.INT32,r.value,i.value);case`scalar`:return Vr(a.T,r.value,i.value)}throw Error(`oneof cannot contain ${a.kind}`);case`map`:let o=Object.keys(r).concat(Object.keys(i));switch(e.V.kind){case`message`:let t=e.V.T;return o.every(e=>t.equals(r[e],i[e]));case`enum`:return o.every(e=>Vr(O.INT32,r[e],i[e]));case`scalar`:let n=e.V.T;return o.every(e=>Vr(n,r[e],i[e]))}break}})},clone(e){let t=e.getType(),n=new t,r=n;for(let n of t.fields.byMember()){let t=e[n.localName],i;if(n.repeated)i=t.map(Hi);else if(n.kind==`map`){i=r[n.localName];for(let[e,n]of Object.entries(t))i[e]=Hi(n)}else i=n.kind==`oneof`?n.findField(t.case)?{case:t.case,value:Hi(t.value)}:{case:void 0}:Hi(t);r[n.localName]=i}for(let n of t.runtime.bin.listUnknownFields(e))t.runtime.bin.onUnknownField(r,n.no,n.wireType,n.data);return n}}}function Hi(e){if(e===void 0)return e;if(oi(e))return e.clone();if(e instanceof Uint8Array){let t=new Uint8Array(e.byteLength);return t.set(e),t}return e}function Ui(e){return e instanceof Uint8Array?e:new Uint8Array(e)}function Wi(e,t,n){return{syntax:e,json:mi(),bin:ki(),util:Object.assign(Object.assign({},Vi()),{newFieldList:t,initFields:n}),makeMessageType(e,t,n){return Er(this,e,t,n)},makeEnum:Cr,makeEnumType:Sr,getEnumType:br,makeExtension(e,t,n){return qr(this,e,t,n)}}}var Gi=class{constructor(e,t){this._fields=e,this._normalizer=t}findJsonName(e){if(!this.jsonNames){let e={};for(let t of this.list())e[t.jsonName]=e[t.name]=t;this.jsonNames=e}return this.jsonNames[e]}find(e){if(!this.numbers){let e={};for(let t of this.list())e[t.no]=t;this.numbers=e}return this.numbers[e]}list(){return this.all||=this._normalizer(this._fields),this.all}byNumber(){return this.numbersAsc||=this.list().concat().sort((e,t)=>e.no-t.no),this.numbersAsc}byMember(){if(!this.members){this.members=[];let e=this.members,t;for(let n of this.list())n.oneof?n.oneof!==t&&(t=n.oneof,e.push(t)):e.push(n)}return this.members}};function Ki(e,t){let n=Yi(e);return t?n:ea($i(n))}function qi(e){return Ki(e,!1)}var Ji=Yi;function Yi(e){let t=!1,n=[];for(let r=0;r<e.length;r++){let i=e.charAt(r);switch(i){case`_`:t=!0;break;case`0`:case`1`:case`2`:case`3`:case`4`:case`5`:case`6`:case`7`:case`8`:case`9`:n.push(i),t=!1;break;default:t&&(t=!1,i=i.toUpperCase()),n.push(i);break}}return n.join(``)}var Xi=new Set([`constructor`,`toString`,`toJSON`,`valueOf`]),Zi=new Set([`getType`,`clone`,`equals`,`fromBinary`,`fromJson`,`fromJsonString`,`toBinary`,`toJson`,`toJsonString`,`toObject`]),Qi=e=>`${e}\$`,$i=e=>Zi.has(e)?Qi(e):e,ea=e=>Xi.has(e)?Qi(e):e,ta=class{constructor(e){this.kind=`oneof`,this.repeated=!1,this.packed=!1,this.opt=!1,this.req=!1,this.default=void 0,this.fields=[],this.name=e,this.localName=qi(e)}addField(e){E(e.oneof===this,`field ${e.name} not one of ${this.name}`),this.fields.push(e)}findField(e){if(!this._lookup){this._lookup=Object.create(null);for(let e=0;e<this.fields.length;e++)this._lookup[this.fields[e].localName]=this.fields[e]}return this._lookup[e]}};function na(e,t){let n=[],r;for(let t of typeof e==`function`?e():e){let e=t;if(e.localName=Ki(t.name,t.oneof!==void 0),e.jsonName=t.jsonName??Ji(t.name),e.repeated=t.repeated??!1,t.kind==`scalar`&&(e.L=t.L??Br.BIGINT),e.delimited=t.delimited??!1,e.req=t.req??!1,e.opt=t.opt??!1,t.packed===void 0&&(e.packed=t.kind==`enum`||t.kind==`scalar`&&t.T!=O.BYTES&&t.T!=O.STRING),t.oneof!==void 0){let n=typeof t.oneof==`string`?t.oneof:t.oneof.name;(!r||r.name!=n)&&(r=new ta(n)),e.oneof=r,r.addField(e)}n.push(e)}return n}var k=Wi(`proto3`,e=>new Gi(e,e=>na(e)),e=>{for(let t of e.getType().fields.byMember()){if(t.opt)continue;let n=t.localName,r=e;if(t.repeated){r[n]=[];continue}switch(t.kind){case`oneof`:r[n]={case:void 0};break;case`enum`:r[n]=0;break;case`map`:r[n]={};break;case`scalar`:r[n]=Hr(t.T,t.L);break}}}),ra=class e extends Tr{constructor(e){super(),this.seconds=D.zero,this.nanos=0,k.util.initPartial(e,this)}fromJson(e,t){if(typeof e!=`string`)throw Error(`cannot decode google.protobuf.Timestamp from JSON: ${k.json.debug(e)}`);let n=e.match(/^([0-9]{4})-([0-9]{2})-([0-9]{2})T([0-9]{2}):([0-9]{2}):([0-9]{2})(?:Z|\.([0-9]{3,9})Z|([+-][0-9][0-9]:[0-9][0-9]))$/);if(!n)throw Error(`cannot decode google.protobuf.Timestamp from JSON: invalid RFC 3339 string`);let r=Date.parse(n[1]+`-`+n[2]+`-`+n[3]+`T`+n[4]+`:`+n[5]+`:`+n[6]+(n[8]?n[8]:`Z`));if(Number.isNaN(r))throw Error(`cannot decode google.protobuf.Timestamp from JSON: invalid RFC 3339 string`);if(r<Date.parse(`0001-01-01T00:00:00Z`)||r>Date.parse(`9999-12-31T23:59:59Z`))throw Error(`cannot decode message google.protobuf.Timestamp from JSON: must be from 0001-01-01T00:00:00Z to 9999-12-31T23:59:59Z inclusive`);return this.seconds=D.parse(r/1e3),this.nanos=0,n[7]&&(this.nanos=parseInt(`1`+n[7]+`0`.repeat(9-n[7].length))-1e9),this}toJson(e){let t=Number(this.seconds)*1e3;if(t<Date.parse(`0001-01-01T00:00:00Z`)||t>Date.parse(`9999-12-31T23:59:59Z`))throw Error(`cannot encode google.protobuf.Timestamp to JSON: must be from 0001-01-01T00:00:00Z to 9999-12-31T23:59:59Z inclusive`);if(this.nanos<0)throw Error(`cannot encode google.protobuf.Timestamp to JSON: nanos must not be negative`);let n=`Z`;if(this.nanos>0){let e=(this.nanos+1e9).toString().substring(1);n=e.substring(3)===`000000`?`.`+e.substring(0,3)+`Z`:e.substring(6)===`000`?`.`+e.substring(0,6)+`Z`:`.`+e+`Z`}return new Date(t).toISOString().replace(`.000Z`,n)}toDate(){return new Date(Number(this.seconds)*1e3+Math.ceil(this.nanos/1e6))}static now(){return e.fromDate(new Date)}static fromDate(t){let n=t.getTime();return new e({seconds:D.parse(Math.floor(n/1e3)),nanos:n%1e3*1e6})}static fromBinary(t,n){return new e().fromBinary(t,n)}static fromJson(t,n){return new e().fromJson(t,n)}static fromJsonString(t,n){return new e().fromJsonString(t,n)}static equals(t,n){return k.util.equals(e,t,n)}};ra.runtime=k,ra.typeName=`google.protobuf.Timestamp`,ra.fields=k.util.newFieldList(()=>[{no:1,name:`seconds`,kind:`scalar`,T:3},{no:2,name:`nanos`,kind:`scalar`,T:5}]);var ia=k.makeMessageType(`livekit.MetricsBatch`,()=>[{no:1,name:`timestamp_ms`,kind:`scalar`,T:3},{no:2,name:`normalized_timestamp`,kind:`message`,T:ra},{no:3,name:`str_data`,kind:`scalar`,T:9,repeated:!0},{no:4,name:`time_series`,kind:`message`,T:aa,repeated:!0},{no:5,name:`events`,kind:`message`,T:sa,repeated:!0}]),aa=k.makeMessageType(`livekit.TimeSeriesMetric`,()=>[{no:1,name:`label`,kind:`scalar`,T:13},{no:2,name:`participant_identity`,kind:`scalar`,T:13},{no:3,name:`track_sid`,kind:`scalar`,T:13},{no:4,name:`samples`,kind:`message`,T:oa,repeated:!0},{no:5,name:`rid`,kind:`scalar`,T:13}]),oa=k.makeMessageType(`livekit.MetricSample`,()=>[{no:1,name:`timestamp_ms`,kind:`scalar`,T:3},{no:2,name:`normalized_timestamp`,kind:`message`,T:ra},{no:3,name:`value`,kind:`scalar`,T:2}]),sa=k.makeMessageType(`livekit.EventMetric`,()=>[{no:1,name:`label`,kind:`scalar`,T:13},{no:2,name:`participant_identity`,kind:`scalar`,T:13},{no:3,name:`track_sid`,kind:`scalar`,T:13},{no:4,name:`start_timestamp_ms`,kind:`scalar`,T:3},{no:5,name:`end_timestamp_ms`,kind:`scalar`,T:3,opt:!0},{no:6,name:`normalized_start_timestamp`,kind:`message`,T:ra},{no:7,name:`normalized_end_timestamp`,kind:`message`,T:ra,opt:!0},{no:8,name:`metadata`,kind:`scalar`,T:9},{no:9,name:`rid`,kind:`scalar`,T:13}]),ca=k.makeEnum(`livekit.BackupCodecPolicy`,[{no:0,name:`PREFER_REGRESSION`},{no:1,name:`SIMULCAST`},{no:2,name:`REGRESSION`}]),la=k.makeEnum(`livekit.TrackType`,[{no:0,name:`AUDIO`},{no:1,name:`VIDEO`},{no:2,name:`DATA`}]),A=k.makeEnum(`livekit.TrackSource`,[{no:0,name:`UNKNOWN`},{no:1,name:`CAMERA`},{no:2,name:`MICROPHONE`},{no:3,name:`SCREEN_SHARE`},{no:4,name:`SCREEN_SHARE_AUDIO`}]),ua=k.makeEnum(`livekit.VideoQuality`,[{no:0,name:`LOW`},{no:1,name:`MEDIUM`},{no:2,name:`HIGH`},{no:3,name:`OFF`}]),da=k.makeEnum(`livekit.ConnectionQuality`,[{no:0,name:`POOR`},{no:1,name:`GOOD`},{no:2,name:`EXCELLENT`},{no:3,name:`LOST`}]),fa=k.makeEnum(`livekit.ClientConfigSetting`,[{no:0,name:`UNSET`},{no:1,name:`DISABLED`},{no:2,name:`ENABLED`}]),pa=k.makeEnum(`livekit.DisconnectReason`,[{no:0,name:`UNKNOWN_REASON`},{no:1,name:`CLIENT_INITIATED`},{no:2,name:`DUPLICATE_IDENTITY`},{no:3,name:`SERVER_SHUTDOWN`},{no:4,name:`PARTICIPANT_REMOVED`},{no:5,name:`ROOM_DELETED`},{no:6,name:`STATE_MISMATCH`},{no:7,name:`JOIN_FAILURE`},{no:8,name:`MIGRATION`},{no:9,name:`SIGNAL_CLOSE`},{no:10,name:`ROOM_CLOSED`},{no:11,name:`USER_UNAVAILABLE`},{no:12,name:`USER_REJECTED`},{no:13,name:`SIP_TRUNK_FAILURE`},{no:14,name:`CONNECTION_TIMEOUT`},{no:15,name:`MEDIA_FAILURE`}]),ma=k.makeEnum(`livekit.ReconnectReason`,[{no:0,name:`RR_UNKNOWN`},{no:1,name:`RR_SIGNAL_DISCONNECTED`},{no:2,name:`RR_PUBLISHER_FAILED`},{no:3,name:`RR_SUBSCRIBER_FAILED`},{no:4,name:`RR_SWITCH_CANDIDATE`}]),ha=k.makeEnum(`livekit.SubscriptionError`,[{no:0,name:`SE_UNKNOWN`},{no:1,name:`SE_CODEC_UNSUPPORTED`},{no:2,name:`SE_TRACK_NOTFOUND`}]),ga=k.makeEnum(`livekit.AudioTrackFeature`,[{no:0,name:`TF_STEREO`},{no:1,name:`TF_NO_DTX`},{no:2,name:`TF_AUTO_GAIN_CONTROL`},{no:3,name:`TF_ECHO_CANCELLATION`},{no:4,name:`TF_NOISE_SUPPRESSION`},{no:5,name:`TF_ENHANCED_NOISE_CANCELLATION`},{no:6,name:`TF_PRECONNECT_BUFFER`}]),_a=k.makeMessageType(`livekit.Room`,()=>[{no:1,name:`sid`,kind:`scalar`,T:9},{no:2,name:`name`,kind:`scalar`,T:9},{no:3,name:`empty_timeout`,kind:`scalar`,T:13},{no:14,name:`departure_timeout`,kind:`scalar`,T:13},{no:4,name:`max_participants`,kind:`scalar`,T:13},{no:5,name:`creation_time`,kind:`scalar`,T:3},{no:15,name:`creation_time_ms`,kind:`scalar`,T:3},{no:6,name:`turn_password`,kind:`scalar`,T:9},{no:7,name:`enabled_codecs`,kind:`message`,T:va,repeated:!0},{no:8,name:`metadata`,kind:`scalar`,T:9},{no:9,name:`num_participants`,kind:`scalar`,T:13},{no:11,name:`num_publishers`,kind:`scalar`,T:13},{no:10,name:`active_recording`,kind:`scalar`,T:8},{no:13,name:`version`,kind:`message`,T:$a}]),va=k.makeMessageType(`livekit.Codec`,()=>[{no:1,name:`mime`,kind:`scalar`,T:9},{no:2,name:`fmtp_line`,kind:`scalar`,T:9}]),ya=k.makeMessageType(`livekit.ParticipantPermission`,()=>[{no:1,name:`can_subscribe`,kind:`scalar`,T:8},{no:2,name:`can_publish`,kind:`scalar`,T:8},{no:3,name:`can_publish_data`,kind:`scalar`,T:8},{no:9,name:`can_publish_sources`,kind:`enum`,T:k.getEnumType(A),repeated:!0},{no:7,name:`hidden`,kind:`scalar`,T:8},{no:8,name:`recorder`,kind:`scalar`,T:8},{no:10,name:`can_update_metadata`,kind:`scalar`,T:8},{no:11,name:`agent`,kind:`scalar`,T:8},{no:12,name:`can_subscribe_metrics`,kind:`scalar`,T:8}]),ba=k.makeMessageType(`livekit.ParticipantInfo`,()=>[{no:1,name:`sid`,kind:`scalar`,T:9},{no:2,name:`identity`,kind:`scalar`,T:9},{no:3,name:`state`,kind:`enum`,T:k.getEnumType(xa)},{no:4,name:`tracks`,kind:`message`,T:Ta,repeated:!0},{no:5,name:`metadata`,kind:`scalar`,T:9},{no:6,name:`joined_at`,kind:`scalar`,T:3},{no:17,name:`joined_at_ms`,kind:`scalar`,T:3},{no:9,name:`name`,kind:`scalar`,T:9},{no:10,name:`version`,kind:`scalar`,T:13},{no:11,name:`permission`,kind:`message`,T:ya},{no:12,name:`region`,kind:`scalar`,T:9},{no:13,name:`is_publisher`,kind:`scalar`,T:8},{no:14,name:`kind`,kind:`enum`,T:k.getEnumType(Sa)},{no:15,name:`attributes`,kind:`map`,K:9,V:{kind:`scalar`,T:9}},{no:16,name:`disconnect_reason`,kind:`enum`,T:k.getEnumType(pa)},{no:18,name:`kind_details`,kind:`enum`,T:k.getEnumType(Ca),repeated:!0},{no:19,name:`data_tracks`,kind:`message`,T:Ea,repeated:!0}]),xa=k.makeEnum(`livekit.ParticipantInfo.State`,[{no:0,name:`JOINING`},{no:1,name:`JOINED`},{no:2,name:`ACTIVE`},{no:3,name:`DISCONNECTED`}]),Sa=k.makeEnum(`livekit.ParticipantInfo.Kind`,[{no:0,name:`STANDARD`},{no:1,name:`INGRESS`},{no:2,name:`EGRESS`},{no:3,name:`SIP`},{no:4,name:`AGENT`},{no:7,name:`CONNECTOR`},{no:8,name:`BRIDGE`}]),Ca=k.makeEnum(`livekit.ParticipantInfo.KindDetail`,[{no:0,name:`CLOUD_AGENT`},{no:1,name:`FORWARDED`},{no:2,name:`CONNECTOR_WHATSAPP`},{no:3,name:`CONNECTOR_TWILIO`},{no:4,name:`BRIDGE_RTSP`}]),j=k.makeEnum(`livekit.Encryption.Type`,[{no:0,name:`NONE`},{no:1,name:`GCM`},{no:2,name:`CUSTOM`}]),wa=k.makeMessageType(`livekit.SimulcastCodecInfo`,()=>[{no:1,name:`mime_type`,kind:`scalar`,T:9},{no:2,name:`mid`,kind:`scalar`,T:9},{no:3,name:`cid`,kind:`scalar`,T:9},{no:4,name:`layers`,kind:`message`,T:Oa,repeated:!0},{no:5,name:`video_layer_mode`,kind:`enum`,T:k.getEnumType(ka)},{no:6,name:`sdp_cid`,kind:`scalar`,T:9}]),Ta=k.makeMessageType(`livekit.TrackInfo`,()=>[{no:1,name:`sid`,kind:`scalar`,T:9},{no:2,name:`type`,kind:`enum`,T:k.getEnumType(la)},{no:3,name:`name`,kind:`scalar`,T:9},{no:4,name:`muted`,kind:`scalar`,T:8},{no:5,name:`width`,kind:`scalar`,T:13},{no:6,name:`height`,kind:`scalar`,T:13},{no:7,name:`simulcast`,kind:`scalar`,T:8},{no:8,name:`disable_dtx`,kind:`scalar`,T:8},{no:9,name:`source`,kind:`enum`,T:k.getEnumType(A)},{no:10,name:`layers`,kind:`message`,T:Oa,repeated:!0},{no:11,name:`mime_type`,kind:`scalar`,T:9},{no:12,name:`mid`,kind:`scalar`,T:9},{no:13,name:`codecs`,kind:`message`,T:wa,repeated:!0},{no:14,name:`stereo`,kind:`scalar`,T:8},{no:15,name:`disable_red`,kind:`scalar`,T:8},{no:16,name:`encryption`,kind:`enum`,T:k.getEnumType(j)},{no:17,name:`stream`,kind:`scalar`,T:9},{no:18,name:`version`,kind:`message`,T:$a},{no:19,name:`audio_features`,kind:`enum`,T:k.getEnumType(ga),repeated:!0},{no:20,name:`backup_codec_policy`,kind:`enum`,T:k.getEnumType(ca)}]),Ea=k.makeMessageType(`livekit.DataTrackInfo`,()=>[{no:1,name:`pub_handle`,kind:`scalar`,T:13},{no:2,name:`sid`,kind:`scalar`,T:9},{no:3,name:`name`,kind:`scalar`,T:9},{no:4,name:`encryption`,kind:`enum`,T:k.getEnumType(j)}]),Da=k.makeMessageType(`livekit.DataTrackSubscriptionOptions`,()=>[{no:1,name:`target_fps`,kind:`scalar`,T:13,opt:!0}]),Oa=k.makeMessageType(`livekit.VideoLayer`,()=>[{no:1,name:`quality`,kind:`enum`,T:k.getEnumType(ua)},{no:2,name:`width`,kind:`scalar`,T:13},{no:3,name:`height`,kind:`scalar`,T:13},{no:4,name:`bitrate`,kind:`scalar`,T:13},{no:5,name:`ssrc`,kind:`scalar`,T:13},{no:6,name:`spatial_layer`,kind:`scalar`,T:5},{no:7,name:`rid`,kind:`scalar`,T:9},{no:8,name:`repair_ssrc`,kind:`scalar`,T:13}]),ka=k.makeEnum(`livekit.VideoLayer.Mode`,[{no:0,name:`MODE_UNUSED`},{no:1,name:`ONE_SPATIAL_LAYER_PER_STREAM`},{no:2,name:`MULTIPLE_SPATIAL_LAYERS_PER_STREAM`},{no:3,name:`ONE_SPATIAL_LAYER_PER_STREAM_INCOMPLETE_RTCP_SR`}]),Aa=k.makeMessageType(`livekit.DataPacket`,()=>[{no:1,name:`kind`,kind:`enum`,T:k.getEnumType(ja)},{no:4,name:`participant_identity`,kind:`scalar`,T:9},{no:5,name:`destination_identities`,kind:`scalar`,T:9,repeated:!0},{no:2,name:`user`,kind:`message`,T:Ia,oneof:`value`},{no:3,name:`speaker`,kind:`message`,T:Pa,oneof:`value`},{no:6,name:`sip_dtmf`,kind:`message`,T:La,oneof:`value`},{no:7,name:`transcription`,kind:`message`,T:Ra,oneof:`value`},{no:8,name:`metrics`,kind:`message`,T:ia,oneof:`value`},{no:9,name:`chat_message`,kind:`message`,T:Ba,oneof:`value`},{no:10,name:`rpc_request`,kind:`message`,T:Va,oneof:`value`},{no:11,name:`rpc_ack`,kind:`message`,T:Ha,oneof:`value`},{no:12,name:`rpc_response`,kind:`message`,T:Ua,oneof:`value`},{no:13,name:`stream_header`,kind:`message`,T:ro,oneof:`value`},{no:14,name:`stream_chunk`,kind:`message`,T:io,oneof:`value`},{no:15,name:`stream_trailer`,kind:`message`,T:ao,oneof:`value`},{no:18,name:`encrypted_packet`,kind:`message`,T:Ma,oneof:`value`},{no:16,name:`sequence`,kind:`scalar`,T:13},{no:17,name:`participant_sid`,kind:`scalar`,T:9}]),ja=k.makeEnum(`livekit.DataPacket.Kind`,[{no:0,name:`RELIABLE`},{no:1,name:`LOSSY`}]),Ma=k.makeMessageType(`livekit.EncryptedPacket`,()=>[{no:1,name:`encryption_type`,kind:`enum`,T:k.getEnumType(j)},{no:2,name:`iv`,kind:`scalar`,T:12},{no:3,name:`key_index`,kind:`scalar`,T:13},{no:4,name:`encrypted_value`,kind:`scalar`,T:12}]),Na=k.makeMessageType(`livekit.EncryptedPacketPayload`,()=>[{no:1,name:`user`,kind:`message`,T:Ia,oneof:`value`},{no:3,name:`chat_message`,kind:`message`,T:Ba,oneof:`value`},{no:4,name:`rpc_request`,kind:`message`,T:Va,oneof:`value`},{no:5,name:`rpc_ack`,kind:`message`,T:Ha,oneof:`value`},{no:6,name:`rpc_response`,kind:`message`,T:Ua,oneof:`value`},{no:7,name:`stream_header`,kind:`message`,T:ro,oneof:`value`},{no:8,name:`stream_chunk`,kind:`message`,T:io,oneof:`value`},{no:9,name:`stream_trailer`,kind:`message`,T:ao,oneof:`value`}]),Pa=k.makeMessageType(`livekit.ActiveSpeakerUpdate`,()=>[{no:1,name:`speakers`,kind:`message`,T:Fa,repeated:!0}]),Fa=k.makeMessageType(`livekit.SpeakerInfo`,()=>[{no:1,name:`sid`,kind:`scalar`,T:9},{no:2,name:`level`,kind:`scalar`,T:2},{no:3,name:`active`,kind:`scalar`,T:8}]),Ia=k.makeMessageType(`livekit.UserPacket`,()=>[{no:1,name:`participant_sid`,kind:`scalar`,T:9},{no:5,name:`participant_identity`,kind:`scalar`,T:9},{no:2,name:`payload`,kind:`scalar`,T:12},{no:3,name:`destination_sids`,kind:`scalar`,T:9,repeated:!0},{no:6,name:`destination_identities`,kind:`scalar`,T:9,repeated:!0},{no:4,name:`topic`,kind:`scalar`,T:9,opt:!0},{no:8,name:`id`,kind:`scalar`,T:9,opt:!0},{no:9,name:`start_time`,kind:`scalar`,T:4,opt:!0},{no:10,name:`end_time`,kind:`scalar`,T:4,opt:!0},{no:11,name:`nonce`,kind:`scalar`,T:12}]),La=k.makeMessageType(`livekit.SipDTMF`,()=>[{no:3,name:`code`,kind:`scalar`,T:13},{no:4,name:`digit`,kind:`scalar`,T:9}]),Ra=k.makeMessageType(`livekit.Transcription`,()=>[{no:2,name:`transcribed_participant_identity`,kind:`scalar`,T:9},{no:3,name:`track_id`,kind:`scalar`,T:9},{no:4,name:`segments`,kind:`message`,T:za,repeated:!0}]),za=k.makeMessageType(`livekit.TranscriptionSegment`,()=>[{no:1,name:`id`,kind:`scalar`,T:9},{no:2,name:`text`,kind:`scalar`,T:9},{no:3,name:`start_time`,kind:`scalar`,T:4},{no:4,name:`end_time`,kind:`scalar`,T:4},{no:5,name:`final`,kind:`scalar`,T:8},{no:6,name:`language`,kind:`scalar`,T:9}]),Ba=k.makeMessageType(`livekit.ChatMessage`,()=>[{no:1,name:`id`,kind:`scalar`,T:9},{no:2,name:`timestamp`,kind:`scalar`,T:3},{no:3,name:`edit_timestamp`,kind:`scalar`,T:3,opt:!0},{no:4,name:`message`,kind:`scalar`,T:9},{no:5,name:`deleted`,kind:`scalar`,T:8},{no:6,name:`generated`,kind:`scalar`,T:8}]),Va=k.makeMessageType(`livekit.RpcRequest`,()=>[{no:1,name:`id`,kind:`scalar`,T:9},{no:2,name:`method`,kind:`scalar`,T:9},{no:3,name:`payload`,kind:`scalar`,T:9},{no:4,name:`response_timeout_ms`,kind:`scalar`,T:13},{no:5,name:`version`,kind:`scalar`,T:13}]),Ha=k.makeMessageType(`livekit.RpcAck`,()=>[{no:1,name:`request_id`,kind:`scalar`,T:9}]),Ua=k.makeMessageType(`livekit.RpcResponse`,()=>[{no:1,name:`request_id`,kind:`scalar`,T:9},{no:2,name:`payload`,kind:`scalar`,T:9,oneof:`value`},{no:3,name:`error`,kind:`message`,T:Wa,oneof:`value`}]),Wa=k.makeMessageType(`livekit.RpcError`,()=>[{no:1,name:`code`,kind:`scalar`,T:13},{no:2,name:`message`,kind:`scalar`,T:9},{no:3,name:`data`,kind:`scalar`,T:9}]),Ga=k.makeMessageType(`livekit.ParticipantTracks`,()=>[{no:1,name:`participant_sid`,kind:`scalar`,T:9},{no:2,name:`track_sids`,kind:`scalar`,T:9,repeated:!0}]),Ka=k.makeMessageType(`livekit.ServerInfo`,()=>[{no:1,name:`edition`,kind:`enum`,T:k.getEnumType(qa)},{no:2,name:`version`,kind:`scalar`,T:9},{no:3,name:`protocol`,kind:`scalar`,T:5},{no:4,name:`region`,kind:`scalar`,T:9},{no:5,name:`node_id`,kind:`scalar`,T:9},{no:6,name:`debug_info`,kind:`scalar`,T:9},{no:7,name:`agent_protocol`,kind:`scalar`,T:5}]),qa=k.makeEnum(`livekit.ServerInfo.Edition`,[{no:0,name:`Standard`},{no:1,name:`Cloud`}]),Ja=k.makeMessageType(`livekit.ClientInfo`,()=>[{no:1,name:`sdk`,kind:`enum`,T:k.getEnumType(Ya)},{no:2,name:`version`,kind:`scalar`,T:9},{no:3,name:`protocol`,kind:`scalar`,T:5},{no:4,name:`os`,kind:`scalar`,T:9},{no:5,name:`os_version`,kind:`scalar`,T:9},{no:6,name:`device_model`,kind:`scalar`,T:9},{no:7,name:`browser`,kind:`scalar`,T:9},{no:8,name:`browser_version`,kind:`scalar`,T:9},{no:9,name:`address`,kind:`scalar`,T:9},{no:10,name:`network`,kind:`scalar`,T:9},{no:11,name:`other_sdks`,kind:`scalar`,T:9}]),Ya=k.makeEnum(`livekit.ClientInfo.SDK`,[{no:0,name:`UNKNOWN`},{no:1,name:`JS`},{no:2,name:`SWIFT`},{no:3,name:`ANDROID`},{no:4,name:`FLUTTER`},{no:5,name:`GO`},{no:6,name:`UNITY`},{no:7,name:`REACT_NATIVE`},{no:8,name:`RUST`},{no:9,name:`PYTHON`},{no:10,name:`CPP`},{no:11,name:`UNITY_WEB`},{no:12,name:`NODE`},{no:13,name:`UNREAL`},{no:14,name:`ESP32`}]),Xa=k.makeMessageType(`livekit.ClientConfiguration`,()=>[{no:1,name:`video`,kind:`message`,T:Za},{no:2,name:`screen`,kind:`message`,T:Za},{no:3,name:`resume_connection`,kind:`enum`,T:k.getEnumType(fa)},{no:4,name:`disabled_codecs`,kind:`message`,T:Qa},{no:5,name:`force_relay`,kind:`enum`,T:k.getEnumType(fa)}]),Za=k.makeMessageType(`livekit.VideoConfiguration`,()=>[{no:1,name:`hardware_encoder`,kind:`enum`,T:k.getEnumType(fa)}]),Qa=k.makeMessageType(`livekit.DisabledCodecs`,()=>[{no:1,name:`codecs`,kind:`message`,T:va,repeated:!0},{no:2,name:`publish`,kind:`message`,T:va,repeated:!0}]),$a=k.makeMessageType(`livekit.TimedVersion`,()=>[{no:1,name:`unix_micro`,kind:`scalar`,T:3},{no:2,name:`ticks`,kind:`scalar`,T:5}]),eo=k.makeEnum(`livekit.DataStream.OperationType`,[{no:0,name:`CREATE`},{no:1,name:`UPDATE`},{no:2,name:`DELETE`},{no:3,name:`REACTION`}]),to=k.makeMessageType(`livekit.DataStream.TextHeader`,()=>[{no:1,name:`operation_type`,kind:`enum`,T:k.getEnumType(eo)},{no:2,name:`version`,kind:`scalar`,T:5},{no:3,name:`reply_to_stream_id`,kind:`scalar`,T:9},{no:4,name:`attached_stream_ids`,kind:`scalar`,T:9,repeated:!0},{no:5,name:`generated`,kind:`scalar`,T:8}],{localName:`DataStream_TextHeader`}),no=k.makeMessageType(`livekit.DataStream.ByteHeader`,()=>[{no:1,name:`name`,kind:`scalar`,T:9}],{localName:`DataStream_ByteHeader`}),ro=k.makeMessageType(`livekit.DataStream.Header`,()=>[{no:1,name:`stream_id`,kind:`scalar`,T:9},{no:2,name:`timestamp`,kind:`scalar`,T:3},{no:3,name:`topic`,kind:`scalar`,T:9},{no:4,name:`mime_type`,kind:`scalar`,T:9},{no:5,name:`total_length`,kind:`scalar`,T:4,opt:!0},{no:7,name:`encryption_type`,kind:`enum`,T:k.getEnumType(j)},{no:8,name:`attributes`,kind:`map`,K:9,V:{kind:`scalar`,T:9}},{no:9,name:`text_header`,kind:`message`,T:to,oneof:`content_header`},{no:10,name:`byte_header`,kind:`message`,T:no,oneof:`content_header`}],{localName:`DataStream_Header`}),io=k.makeMessageType(`livekit.DataStream.Chunk`,()=>[{no:1,name:`stream_id`,kind:`scalar`,T:9},{no:2,name:`chunk_index`,kind:`scalar`,T:4},{no:3,name:`content`,kind:`scalar`,T:12},{no:4,name:`version`,kind:`scalar`,T:5},{no:5,name:`iv`,kind:`scalar`,T:12,opt:!0}],{localName:`DataStream_Chunk`}),ao=k.makeMessageType(`livekit.DataStream.Trailer`,()=>[{no:1,name:`stream_id`,kind:`scalar`,T:9},{no:2,name:`reason`,kind:`scalar`,T:9},{no:3,name:`attributes`,kind:`map`,K:9,V:{kind:`scalar`,T:9}}],{localName:`DataStream_Trailer`}),oo=k.makeMessageType(`livekit.SubscribedAudioCodec`,()=>[{no:1,name:`codec`,kind:`scalar`,T:9},{no:2,name:`enabled`,kind:`scalar`,T:8}]),so=k.makeEnum(`livekit.SignalTarget`,[{no:0,name:`PUBLISHER`},{no:1,name:`SUBSCRIBER`}]),co=k.makeEnum(`livekit.StreamState`,[{no:0,name:`ACTIVE`},{no:1,name:`PAUSED`}]),lo=k.makeEnum(`livekit.CandidateProtocol`,[{no:0,name:`UDP`},{no:1,name:`TCP`},{no:2,name:`TLS`}]),uo=k.makeMessageType(`livekit.SignalRequest`,()=>[{no:1,name:`offer`,kind:`message`,T:Do,oneof:`message`},{no:2,name:`answer`,kind:`message`,T:Do,oneof:`message`},{no:3,name:`trickle`,kind:`message`,T:xo,oneof:`message`},{no:4,name:`add_track`,kind:`message`,T:mo,oneof:`message`},{no:5,name:`mute`,kind:`message`,T:So,oneof:`message`},{no:6,name:`subscription`,kind:`message`,T:ko,oneof:`message`},{no:7,name:`track_setting`,kind:`message`,T:Mo,oneof:`message`},{no:8,name:`leave`,kind:`message`,T:Fo,oneof:`message`},{no:10,name:`update_layers`,kind:`message`,T:Lo,oneof:`message`},{no:11,name:`subscription_permission`,kind:`message`,T:Zo,oneof:`message`},{no:12,name:`sync_state`,kind:`message`,T:es,oneof:`message`},{no:13,name:`simulate`,kind:`message`,T:rs,oneof:`message`},{no:14,name:`ping`,kind:`scalar`,T:3,oneof:`message`},{no:15,name:`update_metadata`,kind:`message`,T:Ro,oneof:`message`},{no:16,name:`ping_req`,kind:`message`,T:is,oneof:`message`},{no:17,name:`update_audio_track`,kind:`message`,T:No,oneof:`message`},{no:18,name:`update_video_track`,kind:`message`,T:Po,oneof:`message`},{no:19,name:`publish_data_track_request`,kind:`message`,T:ho,oneof:`message`},{no:20,name:`unpublish_data_track_request`,kind:`message`,T:_o,oneof:`message`},{no:21,name:`update_data_subscription`,kind:`message`,T:Ao,oneof:`message`}]),fo=k.makeMessageType(`livekit.SignalResponse`,()=>[{no:1,name:`join`,kind:`message`,T:Co,oneof:`message`},{no:2,name:`answer`,kind:`message`,T:Do,oneof:`message`},{no:3,name:`offer`,kind:`message`,T:Do,oneof:`message`},{no:4,name:`trickle`,kind:`message`,T:xo,oneof:`message`},{no:5,name:`update`,kind:`message`,T:Oo,oneof:`message`},{no:6,name:`track_published`,kind:`message`,T:To,oneof:`message`},{no:8,name:`leave`,kind:`message`,T:Fo,oneof:`message`},{no:9,name:`mute`,kind:`message`,T:So,oneof:`message`},{no:10,name:`speakers_changed`,kind:`message`,T:Bo,oneof:`message`},{no:11,name:`room_update`,kind:`message`,T:Vo,oneof:`message`},{no:12,name:`connection_quality`,kind:`message`,T:Uo,oneof:`message`},{no:13,name:`stream_state_update`,kind:`message`,T:Go,oneof:`message`},{no:14,name:`subscribed_quality_update`,kind:`message`,T:Jo,oneof:`message`},{no:15,name:`subscription_permission_update`,kind:`message`,T:Qo,oneof:`message`},{no:16,name:`refresh_token`,kind:`scalar`,T:9,oneof:`message`},{no:17,name:`track_unpublished`,kind:`message`,T:Eo,oneof:`message`},{no:18,name:`pong`,kind:`scalar`,T:3,oneof:`message`},{no:19,name:`reconnect`,kind:`message`,T:wo,oneof:`message`},{no:20,name:`pong_resp`,kind:`message`,T:as,oneof:`message`},{no:21,name:`subscription_response`,kind:`message`,T:cs,oneof:`message`},{no:22,name:`request_response`,kind:`message`,T:ls,oneof:`message`},{no:23,name:`track_subscribed`,kind:`message`,T:ds,oneof:`message`},{no:24,name:`room_moved`,kind:`message`,T:$o,oneof:`message`},{no:25,name:`media_sections_requirement`,kind:`message`,T:gs,oneof:`message`},{no:26,name:`subscribed_audio_codec_update`,kind:`message`,T:Yo,oneof:`message`},{no:27,name:`publish_data_track_response`,kind:`message`,T:go,oneof:`message`},{no:28,name:`unpublish_data_track_response`,kind:`message`,T:vo,oneof:`message`},{no:29,name:`data_track_subscriber_handles`,kind:`message`,T:yo,oneof:`message`}]),po=k.makeMessageType(`livekit.SimulcastCodec`,()=>[{no:1,name:`codec`,kind:`scalar`,T:9},{no:2,name:`cid`,kind:`scalar`,T:9},{no:4,name:`layers`,kind:`message`,T:Oa,repeated:!0},{no:5,name:`video_layer_mode`,kind:`enum`,T:k.getEnumType(ka)}]),mo=k.makeMessageType(`livekit.AddTrackRequest`,()=>[{no:1,name:`cid`,kind:`scalar`,T:9},{no:2,name:`name`,kind:`scalar`,T:9},{no:3,name:`type`,kind:`enum`,T:k.getEnumType(la)},{no:4,name:`width`,kind:`scalar`,T:13},{no:5,name:`height`,kind:`scalar`,T:13},{no:6,name:`muted`,kind:`scalar`,T:8},{no:7,name:`disable_dtx`,kind:`scalar`,T:8},{no:8,name:`source`,kind:`enum`,T:k.getEnumType(A)},{no:9,name:`layers`,kind:`message`,T:Oa,repeated:!0},{no:10,name:`simulcast_codecs`,kind:`message`,T:po,repeated:!0},{no:11,name:`sid`,kind:`scalar`,T:9},{no:12,name:`stereo`,kind:`scalar`,T:8},{no:13,name:`disable_red`,kind:`scalar`,T:8},{no:14,name:`encryption`,kind:`enum`,T:k.getEnumType(j)},{no:15,name:`stream`,kind:`scalar`,T:9},{no:16,name:`backup_codec_policy`,kind:`enum`,T:k.getEnumType(ca)},{no:17,name:`audio_features`,kind:`enum`,T:k.getEnumType(ga),repeated:!0}]),ho=k.makeMessageType(`livekit.PublishDataTrackRequest`,()=>[{no:1,name:`pub_handle`,kind:`scalar`,T:13},{no:2,name:`name`,kind:`scalar`,T:9},{no:3,name:`encryption`,kind:`enum`,T:k.getEnumType(j)}]),go=k.makeMessageType(`livekit.PublishDataTrackResponse`,()=>[{no:1,name:`info`,kind:`message`,T:Ea}]),_o=k.makeMessageType(`livekit.UnpublishDataTrackRequest`,()=>[{no:1,name:`pub_handle`,kind:`scalar`,T:13}]),vo=k.makeMessageType(`livekit.UnpublishDataTrackResponse`,()=>[{no:1,name:`info`,kind:`message`,T:Ea}]),yo=k.makeMessageType(`livekit.DataTrackSubscriberHandles`,()=>[{no:1,name:`sub_handles`,kind:`map`,K:13,V:{kind:`message`,T:bo}}]),bo=k.makeMessageType(`livekit.DataTrackSubscriberHandles.PublishedDataTrack`,()=>[{no:1,name:`publisher_identity`,kind:`scalar`,T:9},{no:2,name:`publisher_sid`,kind:`scalar`,T:9},{no:3,name:`track_sid`,kind:`scalar`,T:9}],{localName:`DataTrackSubscriberHandles_PublishedDataTrack`}),xo=k.makeMessageType(`livekit.TrickleRequest`,()=>[{no:1,name:`candidateInit`,kind:`scalar`,T:9},{no:2,name:`target`,kind:`enum`,T:k.getEnumType(so)},{no:3,name:`final`,kind:`scalar`,T:8}]),So=k.makeMessageType(`livekit.MuteTrackRequest`,()=>[{no:1,name:`sid`,kind:`scalar`,T:9},{no:2,name:`muted`,kind:`scalar`,T:8}]),Co=k.makeMessageType(`livekit.JoinResponse`,()=>[{no:1,name:`room`,kind:`message`,T:_a},{no:2,name:`participant`,kind:`message`,T:ba},{no:3,name:`other_participants`,kind:`message`,T:ba,repeated:!0},{no:4,name:`server_version`,kind:`scalar`,T:9},{no:5,name:`ice_servers`,kind:`message`,T:zo,repeated:!0},{no:6,name:`subscriber_primary`,kind:`scalar`,T:8},{no:7,name:`alternative_url`,kind:`scalar`,T:9},{no:8,name:`client_configuration`,kind:`message`,T:Xa},{no:9,name:`server_region`,kind:`scalar`,T:9},{no:10,name:`ping_timeout`,kind:`scalar`,T:5},{no:11,name:`ping_interval`,kind:`scalar`,T:5},{no:12,name:`server_info`,kind:`message`,T:Ka},{no:13,name:`sif_trailer`,kind:`scalar`,T:12},{no:14,name:`enabled_publish_codecs`,kind:`message`,T:va,repeated:!0},{no:15,name:`fast_publish`,kind:`scalar`,T:8}]),wo=k.makeMessageType(`livekit.ReconnectResponse`,()=>[{no:1,name:`ice_servers`,kind:`message`,T:zo,repeated:!0},{no:2,name:`client_configuration`,kind:`message`,T:Xa},{no:3,name:`server_info`,kind:`message`,T:Ka},{no:4,name:`last_message_seq`,kind:`scalar`,T:13}]),To=k.makeMessageType(`livekit.TrackPublishedResponse`,()=>[{no:1,name:`cid`,kind:`scalar`,T:9},{no:2,name:`track`,kind:`message`,T:Ta}]),Eo=k.makeMessageType(`livekit.TrackUnpublishedResponse`,()=>[{no:1,name:`track_sid`,kind:`scalar`,T:9}]),Do=k.makeMessageType(`livekit.SessionDescription`,()=>[{no:1,name:`type`,kind:`scalar`,T:9},{no:2,name:`sdp`,kind:`scalar`,T:9},{no:3,name:`id`,kind:`scalar`,T:13},{no:4,name:`mid_to_track_id`,kind:`map`,K:9,V:{kind:`scalar`,T:9}}]),Oo=k.makeMessageType(`livekit.ParticipantUpdate`,()=>[{no:1,name:`participants`,kind:`message`,T:ba,repeated:!0}]),ko=k.makeMessageType(`livekit.UpdateSubscription`,()=>[{no:1,name:`track_sids`,kind:`scalar`,T:9,repeated:!0},{no:2,name:`subscribe`,kind:`scalar`,T:8},{no:3,name:`participant_tracks`,kind:`message`,T:Ga,repeated:!0}]),Ao=k.makeMessageType(`livekit.UpdateDataSubscription`,()=>[{no:1,name:`updates`,kind:`message`,T:jo,repeated:!0}]),jo=k.makeMessageType(`livekit.UpdateDataSubscription.Update`,()=>[{no:1,name:`track_sid`,kind:`scalar`,T:9},{no:2,name:`subscribe`,kind:`scalar`,T:8},{no:3,name:`options`,kind:`message`,T:Da}],{localName:`UpdateDataSubscription_Update`}),Mo=k.makeMessageType(`livekit.UpdateTrackSettings`,()=>[{no:1,name:`track_sids`,kind:`scalar`,T:9,repeated:!0},{no:3,name:`disabled`,kind:`scalar`,T:8},{no:4,name:`quality`,kind:`enum`,T:k.getEnumType(ua)},{no:5,name:`width`,kind:`scalar`,T:13},{no:6,name:`height`,kind:`scalar`,T:13},{no:7,name:`fps`,kind:`scalar`,T:13},{no:8,name:`priority`,kind:`scalar`,T:13}]),No=k.makeMessageType(`livekit.UpdateLocalAudioTrack`,()=>[{no:1,name:`track_sid`,kind:`scalar`,T:9},{no:2,name:`features`,kind:`enum`,T:k.getEnumType(ga),repeated:!0}]),Po=k.makeMessageType(`livekit.UpdateLocalVideoTrack`,()=>[{no:1,name:`track_sid`,kind:`scalar`,T:9},{no:2,name:`width`,kind:`scalar`,T:13},{no:3,name:`height`,kind:`scalar`,T:13}]),Fo=k.makeMessageType(`livekit.LeaveRequest`,()=>[{no:1,name:`can_reconnect`,kind:`scalar`,T:8},{no:2,name:`reason`,kind:`enum`,T:k.getEnumType(pa)},{no:3,name:`action`,kind:`enum`,T:k.getEnumType(Io)},{no:4,name:`regions`,kind:`message`,T:os}]),Io=k.makeEnum(`livekit.LeaveRequest.Action`,[{no:0,name:`DISCONNECT`},{no:1,name:`RESUME`},{no:2,name:`RECONNECT`}]),Lo=k.makeMessageType(`livekit.UpdateVideoLayers`,()=>[{no:1,name:`track_sid`,kind:`scalar`,T:9},{no:2,name:`layers`,kind:`message`,T:Oa,repeated:!0}]),Ro=k.makeMessageType(`livekit.UpdateParticipantMetadata`,()=>[{no:1,name:`metadata`,kind:`scalar`,T:9},{no:2,name:`name`,kind:`scalar`,T:9},{no:3,name:`attributes`,kind:`map`,K:9,V:{kind:`scalar`,T:9}},{no:4,name:`request_id`,kind:`scalar`,T:13}]),zo=k.makeMessageType(`livekit.ICEServer`,()=>[{no:1,name:`urls`,kind:`scalar`,T:9,repeated:!0},{no:2,name:`username`,kind:`scalar`,T:9},{no:3,name:`credential`,kind:`scalar`,T:9}]),Bo=k.makeMessageType(`livekit.SpeakersChanged`,()=>[{no:1,name:`speakers`,kind:`message`,T:Fa,repeated:!0}]),Vo=k.makeMessageType(`livekit.RoomUpdate`,()=>[{no:1,name:`room`,kind:`message`,T:_a}]),Ho=k.makeMessageType(`livekit.ConnectionQualityInfo`,()=>[{no:1,name:`participant_sid`,kind:`scalar`,T:9},{no:2,name:`quality`,kind:`enum`,T:k.getEnumType(da)},{no:3,name:`score`,kind:`scalar`,T:2}]),Uo=k.makeMessageType(`livekit.ConnectionQualityUpdate`,()=>[{no:1,name:`updates`,kind:`message`,T:Ho,repeated:!0}]),Wo=k.makeMessageType(`livekit.StreamStateInfo`,()=>[{no:1,name:`participant_sid`,kind:`scalar`,T:9},{no:2,name:`track_sid`,kind:`scalar`,T:9},{no:3,name:`state`,kind:`enum`,T:k.getEnumType(co)}]),Go=k.makeMessageType(`livekit.StreamStateUpdate`,()=>[{no:1,name:`stream_states`,kind:`message`,T:Wo,repeated:!0}]),Ko=k.makeMessageType(`livekit.SubscribedQuality`,()=>[{no:1,name:`quality`,kind:`enum`,T:k.getEnumType(ua)},{no:2,name:`enabled`,kind:`scalar`,T:8}]),qo=k.makeMessageType(`livekit.SubscribedCodec`,()=>[{no:1,name:`codec`,kind:`scalar`,T:9},{no:2,name:`qualities`,kind:`message`,T:Ko,repeated:!0}]),Jo=k.makeMessageType(`livekit.SubscribedQualityUpdate`,()=>[{no:1,name:`track_sid`,kind:`scalar`,T:9},{no:2,name:`subscribed_qualities`,kind:`message`,T:Ko,repeated:!0},{no:3,name:`subscribed_codecs`,kind:`message`,T:qo,repeated:!0}]),Yo=k.makeMessageType(`livekit.SubscribedAudioCodecUpdate`,()=>[{no:1,name:`track_sid`,kind:`scalar`,T:9},{no:2,name:`subscribed_audio_codecs`,kind:`message`,T:oo,repeated:!0}]),Xo=k.makeMessageType(`livekit.TrackPermission`,()=>[{no:1,name:`participant_sid`,kind:`scalar`,T:9},{no:2,name:`all_tracks`,kind:`scalar`,T:8},{no:3,name:`track_sids`,kind:`scalar`,T:9,repeated:!0},{no:4,name:`participant_identity`,kind:`scalar`,T:9}]),Zo=k.makeMessageType(`livekit.SubscriptionPermission`,()=>[{no:1,name:`all_participants`,kind:`scalar`,T:8},{no:2,name:`track_permissions`,kind:`message`,T:Xo,repeated:!0}]),Qo=k.makeMessageType(`livekit.SubscriptionPermissionUpdate`,()=>[{no:1,name:`participant_sid`,kind:`scalar`,T:9},{no:2,name:`track_sid`,kind:`scalar`,T:9},{no:3,name:`allowed`,kind:`scalar`,T:8}]),$o=k.makeMessageType(`livekit.RoomMovedResponse`,()=>[{no:1,name:`room`,kind:`message`,T:_a},{no:2,name:`token`,kind:`scalar`,T:9},{no:3,name:`participant`,kind:`message`,T:ba},{no:4,name:`other_participants`,kind:`message`,T:ba,repeated:!0}]),es=k.makeMessageType(`livekit.SyncState`,()=>[{no:1,name:`answer`,kind:`message`,T:Do},{no:2,name:`subscription`,kind:`message`,T:ko},{no:3,name:`publish_tracks`,kind:`message`,T:To,repeated:!0},{no:4,name:`data_channels`,kind:`message`,T:ns,repeated:!0},{no:5,name:`offer`,kind:`message`,T:Do},{no:6,name:`track_sids_disabled`,kind:`scalar`,T:9,repeated:!0},{no:7,name:`datachannel_receive_states`,kind:`message`,T:ts,repeated:!0},{no:8,name:`publish_data_tracks`,kind:`message`,T:go,repeated:!0}]),ts=k.makeMessageType(`livekit.DataChannelReceiveState`,()=>[{no:1,name:`publisher_sid`,kind:`scalar`,T:9},{no:2,name:`last_seq`,kind:`scalar`,T:13}]),ns=k.makeMessageType(`livekit.DataChannelInfo`,()=>[{no:1,name:`label`,kind:`scalar`,T:9},{no:2,name:`id`,kind:`scalar`,T:13},{no:3,name:`target`,kind:`enum`,T:k.getEnumType(so)}]),rs=k.makeMessageType(`livekit.SimulateScenario`,()=>[{no:1,name:`speaker_update`,kind:`scalar`,T:5,oneof:`scenario`},{no:2,name:`node_failure`,kind:`scalar`,T:8,oneof:`scenario`},{no:3,name:`migration`,kind:`scalar`,T:8,oneof:`scenario`},{no:4,name:`server_leave`,kind:`scalar`,T:8,oneof:`scenario`},{no:5,name:`switch_candidate_protocol`,kind:`enum`,T:k.getEnumType(lo),oneof:`scenario`},{no:6,name:`subscriber_bandwidth`,kind:`scalar`,T:3,oneof:`scenario`},{no:7,name:`disconnect_signal_on_resume`,kind:`scalar`,T:8,oneof:`scenario`},{no:8,name:`disconnect_signal_on_resume_no_messages`,kind:`scalar`,T:8,oneof:`scenario`},{no:9,name:`leave_request_full_reconnect`,kind:`scalar`,T:8,oneof:`scenario`}]),is=k.makeMessageType(`livekit.Ping`,()=>[{no:1,name:`timestamp`,kind:`scalar`,T:3},{no:2,name:`rtt`,kind:`scalar`,T:3}]),as=k.makeMessageType(`livekit.Pong`,()=>[{no:1,name:`last_ping_timestamp`,kind:`scalar`,T:3},{no:2,name:`timestamp`,kind:`scalar`,T:3}]),os=k.makeMessageType(`livekit.RegionSettings`,()=>[{no:1,name:`regions`,kind:`message`,T:ss,repeated:!0}]),ss=k.makeMessageType(`livekit.RegionInfo`,()=>[{no:1,name:`region`,kind:`scalar`,T:9},{no:2,name:`url`,kind:`scalar`,T:9},{no:3,name:`distance`,kind:`scalar`,T:3}]),cs=k.makeMessageType(`livekit.SubscriptionResponse`,()=>[{no:1,name:`track_sid`,kind:`scalar`,T:9},{no:2,name:`err`,kind:`enum`,T:k.getEnumType(ha)}]),ls=k.makeMessageType(`livekit.RequestResponse`,()=>[{no:1,name:`request_id`,kind:`scalar`,T:13},{no:2,name:`reason`,kind:`enum`,T:k.getEnumType(us)},{no:3,name:`message`,kind:`scalar`,T:9},{no:4,name:`trickle`,kind:`message`,T:xo,oneof:`request`},{no:5,name:`add_track`,kind:`message`,T:mo,oneof:`request`},{no:6,name:`mute`,kind:`message`,T:So,oneof:`request`},{no:7,name:`update_metadata`,kind:`message`,T:Ro,oneof:`request`},{no:8,name:`update_audio_track`,kind:`message`,T:No,oneof:`request`},{no:9,name:`update_video_track`,kind:`message`,T:Po,oneof:`request`},{no:10,name:`publish_data_track`,kind:`message`,T:ho,oneof:`request`},{no:11,name:`unpublish_data_track`,kind:`message`,T:_o,oneof:`request`}]),us=k.makeEnum(`livekit.RequestResponse.Reason`,[{no:0,name:`OK`},{no:1,name:`NOT_FOUND`},{no:2,name:`NOT_ALLOWED`},{no:3,name:`LIMIT_EXCEEDED`},{no:4,name:`QUEUED`},{no:5,name:`UNSUPPORTED_TYPE`},{no:6,name:`UNCLASSIFIED_ERROR`},{no:7,name:`INVALID_HANDLE`},{no:8,name:`INVALID_NAME`},{no:9,name:`DUPLICATE_HANDLE`},{no:10,name:`DUPLICATE_NAME`}]),ds=k.makeMessageType(`livekit.TrackSubscribed`,()=>[{no:1,name:`track_sid`,kind:`scalar`,T:9}]),fs=k.makeMessageType(`livekit.ConnectionSettings`,()=>[{no:1,name:`auto_subscribe`,kind:`scalar`,T:8},{no:2,name:`adaptive_stream`,kind:`scalar`,T:8},{no:3,name:`subscriber_allow_pause`,kind:`scalar`,T:8,opt:!0},{no:4,name:`disable_ice_lite`,kind:`scalar`,T:8},{no:5,name:`auto_subscribe_data_track`,kind:`scalar`,T:8,opt:!0}]),ps=k.makeMessageType(`livekit.JoinRequest`,()=>[{no:1,name:`client_info`,kind:`message`,T:Ja},{no:2,name:`connection_settings`,kind:`message`,T:fs},{no:3,name:`metadata`,kind:`scalar`,T:9},{no:4,name:`participant_attributes`,kind:`map`,K:9,V:{kind:`scalar`,T:9}},{no:5,name:`add_track_requests`,kind:`message`,T:mo,repeated:!0},{no:6,name:`publisher_offer`,kind:`message`,T:Do},{no:7,name:`reconnect`,kind:`scalar`,T:8},{no:8,name:`reconnect_reason`,kind:`enum`,T:k.getEnumType(ma)},{no:9,name:`participant_sid`,kind:`scalar`,T:9},{no:10,name:`sync_state`,kind:`message`,T:es}]),ms=k.makeMessageType(`livekit.WrappedJoinRequest`,()=>[{no:1,name:`compression`,kind:`enum`,T:k.getEnumType(hs)},{no:2,name:`join_request`,kind:`scalar`,T:12}]),hs=k.makeEnum(`livekit.WrappedJoinRequest.Compression`,[{no:0,name:`NONE`},{no:1,name:`GZIP`}]),gs=k.makeMessageType(`livekit.MediaSectionsRequirement`,()=>[{no:1,name:`num_audios`,kind:`scalar`,T:13},{no:2,name:`num_videos`,kind:`scalar`,T:13}]);function _s(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,`default`)?e.default:e}var vs={exports:{}},ys=vs.exports,bs;function xs(){return bs?vs.exports:(bs=1,(function(e){(function(t,n){e.exports?e.exports=n():t.log=n()})(ys,function(){var e=function(){},t=`undefined`,n=typeof window!==t&&typeof window.navigator!==t&&/Trident\/|MSIE /.test(window.navigator.userAgent),r=[`trace`,`debug`,`info`,`warn`,`error`],i={},a=null;function o(e,t){var n=e[t];if(typeof n.bind==`function`)return n.bind(e);try{return Function.prototype.bind.call(n,e)}catch{return function(){return Function.prototype.apply.apply(n,[e,arguments])}}}function s(){console.log&&(console.log.apply?console.log.apply(console,arguments):Function.prototype.apply.apply(console.log,[console,arguments])),console.trace&&console.trace()}function c(r){return r===`debug`&&(r=`log`),typeof console===t?!1:r===`trace`&&n?s:console[r]===void 0?console.log===void 0?e:o(console,`log`):o(console,r)}function l(){for(var n=this.getLevel(),i=0;i<r.length;i++){var a=r[i];this[a]=i<n?e:this.methodFactory(a,n,this.name)}if(this.log=this.debug,typeof console===t&&n<this.levels.SILENT)return`No console available for logging`}function u(e){return function(){typeof console!==t&&(l.call(this),this[e].apply(this,arguments))}}function d(e,t,n){return c(e)||u.apply(this,arguments)}function f(e,n){var o=this,s,c,u,f=`loglevel`;typeof e==`string`?f+=`:`+e:typeof e==`symbol`&&(f=void 0);function p(e){var n=(r[e]||`silent`).toUpperCase();if(!(typeof window===t||!f)){try{window.localStorage[f]=n;return}catch{}try{window.document.cookie=encodeURIComponent(f)+`=`+n+`;`}catch{}}}function m(){var e;if(!(typeof window===t||!f)){try{e=window.localStorage[f]}catch{}if(typeof e===t)try{var n=window.document.cookie,r=encodeURIComponent(f),i=n.indexOf(r+`=`);i!==-1&&(e=/^([^;]+)/.exec(n.slice(i+r.length+1))[1])}catch{}return o.levels[e]===void 0&&(e=void 0),e}}function ee(){if(!(typeof window===t||!f)){try{window.localStorage.removeItem(f)}catch{}try{window.document.cookie=encodeURIComponent(f)+`=; expires=Thu, 01 Jan 1970 00:00:00 UTC`}catch{}}}function h(e){var t=e;if(typeof t==`string`&&o.levels[t.toUpperCase()]!==void 0&&(t=o.levels[t.toUpperCase()]),typeof t==`number`&&t>=0&&t<=o.levels.SILENT)return t;throw TypeError(`log.setLevel() called with invalid level: `+e)}o.name=e,o.levels={TRACE:0,DEBUG:1,INFO:2,WARN:3,ERROR:4,SILENT:5},o.methodFactory=n||d,o.getLevel=function(){return u??c??s},o.setLevel=function(e,t){return u=h(e),t!==!1&&p(u),l.call(o)},o.setDefaultLevel=function(e){c=h(e),m()||o.setLevel(e,!1)},o.resetLevel=function(){u=null,ee(),l.call(o)},o.enableAll=function(e){o.setLevel(o.levels.TRACE,e)},o.disableAll=function(e){o.setLevel(o.levels.SILENT,e)},o.rebuild=function(){if(a!==o&&(s=h(a.getLevel())),l.call(o),a===o)for(var e in i)i[e].rebuild()},s=h(a?a.getLevel():`WARN`);var g=m();g!=null&&(u=h(g)),l.call(o)}a=new f,a.getLogger=function(e){if(typeof e!=`symbol`&&typeof e!=`string`||e===``)throw TypeError(`You must supply a name when creating a logger.`);var t=i[e];return t||=i[e]=new f(e,a.methodFactory),t};var p=typeof window===t?void 0:window.log;return a.noConflict=function(){return typeof window!==t&&window.log===a&&(window.log=p),a},a.getLoggers=function(){return i},a.default=a,a})})(vs),vs.exports)}var Ss=xs(),Cs;(function(e){e[e.trace=0]=`trace`,e[e.debug=1]=`debug`,e[e.info=2]=`info`,e[e.warn=3]=`warn`,e[e.error=4]=`error`,e[e.silent=5]=`silent`})(Cs||={});var ws;(function(e){e.Default=`livekit`,e.Room=`livekit-room`,e.TokenSource=`livekit-token-source`,e.Participant=`livekit-participant`,e.Track=`livekit-track`,e.Publication=`livekit-track-publication`,e.Engine=`livekit-engine`,e.Signal=`livekit-signal`,e.PCManager=`livekit-pc-manager`,e.PCTransport=`livekit-pc-transport`,e.E2EE=`lk-e2ee`,e.DataTracks=`livekit-data-tracks`})(ws||={});var M=Ss.getLogger(`livekit`);Object.values(ws).map(e=>Ss.getLogger(e)),M.setDefaultLevel(Cs.info);function Ts(e){let t=Ss.getLogger(e);return t.setDefaultLevel(M.getLevel()),t}var Es=Ss.getLogger(`lk-e2ee`),Ds=7e3,Os=[0,300,4*300,9*300,16*300,Ds,Ds,Ds,Ds,Ds],ks=class{constructor(e){this._retryDelays=e===void 0?Os:[...e]}nextRetryDelayInMs(e){if(e.retryCount>=this._retryDelays.length)return null;let t=this._retryDelays[e.retryCount];return e.retryCount<=1?t:t+Math.random()*1e3}};function As(e,t){var n={};for(var r in e)Object.prototype.hasOwnProperty.call(e,r)&&t.indexOf(r)<0&&(n[r]=e[r]);if(e!=null&&typeof Object.getOwnPropertySymbols==`function`)for(var i=0,r=Object.getOwnPropertySymbols(e);i<r.length;i++)t.indexOf(r[i])<0&&Object.prototype.propertyIsEnumerable.call(e,r[i])&&(n[r[i]]=e[r[i]]);return n}function N(e,t,n,r){function i(e){return e instanceof n?e:new n(function(t){t(e)})}return new(n||=Promise)(function(n,a){function o(e){try{c(r.next(e))}catch(e){a(e)}}function s(e){try{c(r.throw(e))}catch(e){a(e)}}function c(e){e.done?n(e.value):i(e.value).then(o,s)}c((r=r.apply(e,t||[])).next())})}function js(e){var t=typeof Symbol==`function`&&Symbol.iterator,n=t&&e[t],r=0;if(n)return n.call(e);if(e&&typeof e.length==`number`)return{next:function(){return e&&r>=e.length&&(e=void 0),{value:e&&e[r++],done:!e}}};throw TypeError(t?`Object is not iterable.`:`Symbol.iterator is not defined.`)}function Ms(e){return this instanceof Ms?(this.v=e,this):new Ms(e)}function Ns(e,t,n){if(!Symbol.asyncIterator)throw TypeError(`Symbol.asyncIterator is not defined.`);var r=n.apply(e,t||[]),i,a=[];return i=Object.create((typeof AsyncIterator==`function`?AsyncIterator:Object).prototype),s(`next`),s(`throw`),s(`return`,o),i[Symbol.asyncIterator]=function(){return this},i;function o(e){return function(t){return Promise.resolve(t).then(e,d)}}function s(e,t){r[e]&&(i[e]=function(t){return new Promise(function(n,r){a.push([e,t,n,r])>1||c(e,t)})},t&&(i[e]=t(i[e])))}function c(e,t){try{l(r[e](t))}catch(e){f(a[0][3],e)}}function l(e){e.value instanceof Ms?Promise.resolve(e.value.v).then(u,d):f(a[0][2],e)}function u(e){c(`next`,e)}function d(e){c(`throw`,e)}function f(e,t){e(t),a.shift(),a.length&&c(a[0][0],a[0][1])}}function Ps(e){var t,n;return t={},r(`next`),r(`throw`,function(e){throw e}),r(`return`),t[Symbol.iterator]=function(){return this},t;function r(r,i){t[r]=e[r]?function(t){return(n=!n)?{value:Ms(e[r](t)),done:!1}:i?i(t):t}:i}}function Fs(e){if(!Symbol.asyncIterator)throw TypeError(`Symbol.asyncIterator is not defined.`);var t=e[Symbol.asyncIterator],n;return t?t.call(e):(e=typeof js==`function`?js(e):e[Symbol.iterator](),n={},r(`next`),r(`throw`),r(`return`),n[Symbol.asyncIterator]=function(){return this},n);function r(t){n[t]=e[t]&&function(n){return new Promise(function(r,a){n=e[t](n),i(r,a,n.done,n.value)})}}function i(e,t,n,r){Promise.resolve(r).then(function(t){e({value:t,done:n})},t)}}var Is={exports:{}},Ls;function Rs(){if(Ls)return Is.exports;Ls=1;var e=typeof Reflect==`object`?Reflect:null,t=e&&typeof e.apply==`function`?e.apply:function(e,t,n){return Function.prototype.apply.call(e,t,n)},n=e&&typeof e.ownKeys==`function`?e.ownKeys:Object.getOwnPropertySymbols?function(e){return Object.getOwnPropertyNames(e).concat(Object.getOwnPropertySymbols(e))}:function(e){return Object.getOwnPropertyNames(e)};function r(e){console&&console.warn&&console.warn(e)}var i=Number.isNaN||function(e){return e!==e};function a(){a.init.call(this)}Is.exports=a,Is.exports.once=g,a.EventEmitter=a,a.prototype._events=void 0,a.prototype._eventsCount=0,a.prototype._maxListeners=void 0;var o=10;function s(e){if(typeof e!=`function`)throw TypeError(`The "listener" argument must be of type Function. Received type `+typeof e)}Object.defineProperty(a,`defaultMaxListeners`,{enumerable:!0,get:function(){return o},set:function(e){if(typeof e!=`number`||e<0||i(e))throw RangeError(`The value of "defaultMaxListeners" is out of range. It must be a non-negative number. Received `+e+`.`);o=e}}),a.init=function(){(this._events===void 0||this._events===Object.getPrototypeOf(this)._events)&&(this._events=Object.create(null),this._eventsCount=0),this._maxListeners=this._maxListeners||void 0},a.prototype.setMaxListeners=function(e){if(typeof e!=`number`||e<0||i(e))throw RangeError(`The value of "n" is out of range. It must be a non-negative number. Received `+e+`.`);return this._maxListeners=e,this};function c(e){return e._maxListeners===void 0?a.defaultMaxListeners:e._maxListeners}a.prototype.getMaxListeners=function(){return c(this)},a.prototype.emit=function(e){for(var n=[],r=1;r<arguments.length;r++)n.push(arguments[r]);var i=e===`error`,a=this._events;if(a!==void 0)i&&=a.error===void 0;else if(!i)return!1;if(i){var o;if(n.length>0&&(o=n[0]),o instanceof Error)throw o;var s=Error(`Unhandled error.`+(o?` (`+o.message+`)`:``));throw s.context=o,s}var c=a[e];if(c===void 0)return!1;if(typeof c==`function`)t(c,this,n);else for(var l=c.length,u=m(c,l),r=0;r<l;++r)t(u[r],this,n);return!0};function l(e,t,n,i){var a,o,l;if(s(n),o=e._events,o===void 0?(o=e._events=Object.create(null),e._eventsCount=0):(o.newListener!==void 0&&(e.emit(`newListener`,t,n.listener?n.listener:n),o=e._events),l=o[t]),l===void 0)l=o[t]=n,++e._eventsCount;else if(typeof l==`function`?l=o[t]=i?[n,l]:[l,n]:i?l.unshift(n):l.push(n),a=c(e),a>0&&l.length>a&&!l.warned){l.warned=!0;var u=Error(`Possible EventEmitter memory leak detected. `+l.length+` `+String(t)+` listeners added. Use emitter.setMaxListeners() to increase limit`);u.name=`MaxListenersExceededWarning`,u.emitter=e,u.type=t,u.count=l.length,r(u)}return e}a.prototype.addListener=function(e,t){return l(this,e,t,!1)},a.prototype.on=a.prototype.addListener,a.prototype.prependListener=function(e,t){return l(this,e,t,!0)};function u(){if(!this.fired)return this.target.removeListener(this.type,this.wrapFn),this.fired=!0,arguments.length===0?this.listener.call(this.target):this.listener.apply(this.target,arguments)}function d(e,t,n){var r={fired:!1,wrapFn:void 0,target:e,type:t,listener:n},i=u.bind(r);return i.listener=n,r.wrapFn=i,i}a.prototype.once=function(e,t){return s(t),this.on(e,d(this,e,t)),this},a.prototype.prependOnceListener=function(e,t){return s(t),this.prependListener(e,d(this,e,t)),this},a.prototype.removeListener=function(e,t){var n,r,i,a,o;if(s(t),r=this._events,r===void 0||(n=r[e],n===void 0))return this;if(n===t||n.listener===t)--this._eventsCount===0?this._events=Object.create(null):(delete r[e],r.removeListener&&this.emit(`removeListener`,e,n.listener||t));else if(typeof n!=`function`){for(i=-1,a=n.length-1;a>=0;a--)if(n[a]===t||n[a].listener===t){o=n[a].listener,i=a;break}if(i<0)return this;i===0?n.shift():ee(n,i),n.length===1&&(r[e]=n[0]),r.removeListener!==void 0&&this.emit(`removeListener`,e,o||t)}return this},a.prototype.off=a.prototype.removeListener,a.prototype.removeAllListeners=function(e){var t,n=this._events,r;if(n===void 0)return this;if(n.removeListener===void 0)return arguments.length===0?(this._events=Object.create(null),this._eventsCount=0):n[e]!==void 0&&(--this._eventsCount===0?this._events=Object.create(null):delete n[e]),this;if(arguments.length===0){var i=Object.keys(n),a;for(r=0;r<i.length;++r)a=i[r],a!==`removeListener`&&this.removeAllListeners(a);return this.removeAllListeners(`removeListener`),this._events=Object.create(null),this._eventsCount=0,this}if(t=n[e],typeof t==`function`)this.removeListener(e,t);else if(t!==void 0)for(r=t.length-1;r>=0;r--)this.removeListener(e,t[r]);return this};function f(e,t,n){var r=e._events;if(r===void 0)return[];var i=r[t];return i===void 0?[]:typeof i==`function`?n?[i.listener||i]:[i]:n?h(i):m(i,i.length)}a.prototype.listeners=function(e){return f(this,e,!0)},a.prototype.rawListeners=function(e){return f(this,e,!1)},a.listenerCount=function(e,t){return typeof e.listenerCount==`function`?e.listenerCount(t):p.call(e,t)},a.prototype.listenerCount=p;function p(e){var t=this._events;if(t!==void 0){var n=t[e];if(typeof n==`function`)return 1;if(n!==void 0)return n.length}return 0}a.prototype.eventNames=function(){return this._eventsCount>0?n(this._events):[]};function m(e,t){for(var n=Array(t),r=0;r<t;++r)n[r]=e[r];return n}function ee(e,t){for(;t+1<e.length;t++)e[t]=e[t+1];e.pop()}function h(e){for(var t=Array(e.length),n=0;n<t.length;++n)t[n]=e[n].listener||e[n];return t}function g(e,t){return new Promise(function(n,r){function i(n){e.removeListener(t,a),r(n)}function a(){typeof e.removeListener==`function`&&e.removeListener(`error`,i),n([].slice.call(arguments))}te(e,t,a,{once:!0}),t!==`error`&&_(e,i,{once:!0})})}function _(e,t,n){typeof e.on==`function`&&te(e,`error`,t,n)}function te(e,t,n,r){if(typeof e.on==`function`)r.once?e.once(t,n):e.on(t,n);else if(typeof e.addEventListener==`function`)e.addEventListener(t,function i(a){r.once&&e.removeEventListener(t,i),n(a)});else throw TypeError(`The "emitter" argument must be of type EventEmitter. Received type `+typeof e)}return Is.exports}var zs=Rs(),Bs=!0,Vs=!0;function Hs(e,t,n){let r=e.match(t);return r&&r.length>=n&&parseFloat(r[n],10)}function Us(e,t,n){if(!e.RTCPeerConnection)return;let r=e.RTCPeerConnection.prototype,i=r.addEventListener;r.addEventListener=function(e,r){if(e!==t)return i.apply(this,arguments);let a=e=>{let t=n(e);t&&(r.handleEvent?r.handleEvent(t):r(t))};return this._eventMap=this._eventMap||{},this._eventMap[t]||(this._eventMap[t]=new Map),this._eventMap[t].set(r,a),i.apply(this,[e,a])};let a=r.removeEventListener;r.removeEventListener=function(e,n){if(e!==t||!this._eventMap||!this._eventMap[t]||!this._eventMap[t].has(n))return a.apply(this,arguments);let r=this._eventMap[t].get(n);return this._eventMap[t].delete(n),this._eventMap[t].size===0&&delete this._eventMap[t],Object.keys(this._eventMap).length===0&&delete this._eventMap,a.apply(this,[e,r])},Object.defineProperty(r,`on`+t,{get(){return this[`_on`+t]},set(e){this[`_on`+t]&&(this.removeEventListener(t,this[`_on`+t]),delete this[`_on`+t]),e&&this.addEventListener(t,this[`_on`+t]=e)},enumerable:!0,configurable:!0})}function Ws(e){return typeof e==`boolean`?(Bs=e,e?`adapter.js logging disabled`:`adapter.js logging enabled`):Error(`Argument type: `+typeof e+`. Please use a boolean.`)}function Gs(e){return typeof e==`boolean`?(Vs=!e,`adapter.js deprecation warnings `+(e?`disabled`:`enabled`)):Error(`Argument type: `+typeof e+`. Please use a boolean.`)}function Ks(){if(typeof window==`object`){if(Bs)return;typeof console<`u`&&typeof console.log==`function`&&console.log.apply(console,arguments)}}function qs(e,t){Vs&&console.warn(e+` is deprecated, please use `+t+` instead.`)}function Js(e){let t={browser:null,version:null};if(e===void 0||!e.navigator||!e.navigator.userAgent)return t.browser=`Not a browser.`,t;let{navigator:n}=e;if(n.userAgentData&&n.userAgentData.brands){let e=n.userAgentData.brands.find(e=>e.brand===`Chromium`);if(e)return{browser:`chrome`,version:parseInt(e.version,10)}}if(n.mozGetUserMedia)t.browser=`firefox`,t.version=parseInt(Hs(n.userAgent,/Firefox\/(\d+)\./,1));else if(n.webkitGetUserMedia||e.isSecureContext===!1&&e.webkitRTCPeerConnection)t.browser=`chrome`,t.version=parseInt(Hs(n.userAgent,/Chrom(e|ium)\/(\d+)\./,2));else if(e.RTCPeerConnection&&n.userAgent.match(/AppleWebKit\/(\d+)\./))t.browser=`safari`,t.version=parseInt(Hs(n.userAgent,/AppleWebKit\/(\d+)\./,1)),t.supportsUnifiedPlan=e.RTCRtpTransceiver&&`currentDirection`in e.RTCRtpTransceiver.prototype,t._safariVersion=Hs(n.userAgent,/Version\/(\d+(\.?\d+))/,1);else return t.browser=`Not a supported browser.`,t;return t}function Ys(e){return Object.prototype.toString.call(e)===`[object Object]`}function Xs(e){return Ys(e)?Object.keys(e).reduce(function(t,n){let r=Ys(e[n]),i=r?Xs(e[n]):e[n],a=r&&!Object.keys(i).length;return i===void 0||a?t:Object.assign(t,{[n]:i})},{}):e}function Zs(e,t,n){!t||n.has(t.id)||(n.set(t.id,t),Object.keys(t).forEach(r=>{r.endsWith(`Id`)?Zs(e,e.get(t[r]),n):r.endsWith(`Ids`)&&t[r].forEach(t=>{Zs(e,e.get(t),n)})}))}function Qs(e,t,n){let r=n?`outbound-rtp`:`inbound-rtp`,i=new Map;if(t===null)return i;let a=[];return e.forEach(e=>{e.type===`track`&&e.trackIdentifier===t.id&&a.push(e)}),a.forEach(t=>{e.forEach(n=>{n.type===r&&n.trackId===t.id&&Zs(e,n,i)})}),i}var $s=Ks;function ec(e,t){let n=e&&e.navigator;if(!n.mediaDevices)return;let r=function(e){if(typeof e!=`object`||e.mandatory||e.optional)return e;let t={};return Object.keys(e).forEach(n=>{if(n===`require`||n===`advanced`||n===`mediaSource`)return;let r=typeof e[n]==`object`?e[n]:{ideal:e[n]};r.exact!==void 0&&typeof r.exact==`number`&&(r.min=r.max=r.exact);let i=function(e,t){return e?e+t.charAt(0).toUpperCase()+t.slice(1):t===`deviceId`?`sourceId`:t};if(r.ideal!==void 0){t.optional=t.optional||[];let e={};typeof r.ideal==`number`?(e[i(`min`,n)]=r.ideal,t.optional.push(e),e={},e[i(`max`,n)]=r.ideal,t.optional.push(e)):(e[i(``,n)]=r.ideal,t.optional.push(e))}r.exact!==void 0&&typeof r.exact!=`number`?(t.mandatory=t.mandatory||{},t.mandatory[i(``,n)]=r.exact):[`min`,`max`].forEach(e=>{r[e]!==void 0&&(t.mandatory=t.mandatory||{},t.mandatory[i(e,n)]=r[e])})}),e.advanced&&(t.optional=(t.optional||[]).concat(e.advanced)),t},i=function(e,i){if(t.version>=61)return i(e);if(e=JSON.parse(JSON.stringify(e)),e&&typeof e.audio==`object`){let t=function(e,t,n){t in e&&!(n in e)&&(e[n]=e[t],delete e[t])};e=JSON.parse(JSON.stringify(e)),t(e.audio,`autoGainControl`,`googAutoGainControl`),t(e.audio,`noiseSuppression`,`googNoiseSuppression`),e.audio=r(e.audio)}if(e&&typeof e.video==`object`){let a=e.video.facingMode;a&&=typeof a==`object`?a:{ideal:a};let o=t.version<66;if(a&&(a.exact===`user`||a.exact===`environment`||a.ideal===`user`||a.ideal===`environment`)&&!(n.mediaDevices.getSupportedConstraints&&n.mediaDevices.getSupportedConstraints().facingMode&&!o)){delete e.video.facingMode;let t;if(a.exact===`environment`||a.ideal===`environment`?t=[`back`,`rear`]:(a.exact===`user`||a.ideal===`user`)&&(t=[`front`]),t)return n.mediaDevices.enumerateDevices().then(n=>{n=n.filter(e=>e.kind===`videoinput`);let o=n.find(e=>t.some(t=>e.label.toLowerCase().includes(t)));return!o&&n.length&&t.includes(`back`)&&(o=n[n.length-1]),o&&(e.video.deviceId=a.exact?{exact:o.deviceId}:{ideal:o.deviceId}),e.video=r(e.video),$s(`chrome: `+JSON.stringify(e)),i(e)})}e.video=r(e.video)}return $s(`chrome: `+JSON.stringify(e)),i(e)},a=function(e){return t.version>=64?e:{name:{PermissionDeniedError:`NotAllowedError`,PermissionDismissedError:`NotAllowedError`,InvalidStateError:`NotAllowedError`,DevicesNotFoundError:`NotFoundError`,ConstraintNotSatisfiedError:`OverconstrainedError`,TrackStartError:`NotReadableError`,MediaDeviceFailedDueToShutdown:`NotAllowedError`,MediaDeviceKillSwitchOn:`NotAllowedError`,TabCaptureError:`AbortError`,ScreenCaptureError:`AbortError`,DeviceCaptureError:`AbortError`}[e.name]||e.name,message:e.message,constraint:e.constraint||e.constraintName,toString(){return this.name+(this.message&&`: `)+this.message}}};if(n.getUserMedia=function(e,t,r){i(e,e=>{n.webkitGetUserMedia(e,t,e=>{r&&r(a(e))})})}.bind(n),n.mediaDevices.getUserMedia){let e=n.mediaDevices.getUserMedia.bind(n.mediaDevices);n.mediaDevices.getUserMedia=function(t){return i(t,t=>e(t).then(e=>{if(t.audio&&!e.getAudioTracks().length||t.video&&!e.getVideoTracks().length)throw e.getTracks().forEach(e=>{e.stop()}),new DOMException(``,`NotFoundError`);return e},e=>Promise.reject(a(e))))}}}function tc(e){e.MediaStream=e.MediaStream||e.webkitMediaStream}function nc(e){if(typeof e==`object`&&e.RTCPeerConnection&&!(`ontrack`in e.RTCPeerConnection.prototype)){Object.defineProperty(e.RTCPeerConnection.prototype,`ontrack`,{get(){return this._ontrack},set(e){this._ontrack&&this.removeEventListener(`track`,this._ontrack),this.addEventListener(`track`,this._ontrack=e)},enumerable:!0,configurable:!0});let t=e.RTCPeerConnection.prototype.setRemoteDescription;e.RTCPeerConnection.prototype.setRemoteDescription=function(){return this._ontrackpoly||(this._ontrackpoly=t=>{t.stream.addEventListener(`addtrack`,n=>{let r;r=e.RTCPeerConnection.prototype.getReceivers?this.getReceivers().find(e=>e.track&&e.track.id===n.track.id):{track:n.track};let i=new Event(`track`);i.track=n.track,i.receiver=r,i.transceiver={receiver:r},i.streams=[t.stream],this.dispatchEvent(i)}),t.stream.getTracks().forEach(n=>{let r;r=e.RTCPeerConnection.prototype.getReceivers?this.getReceivers().find(e=>e.track&&e.track.id===n.id):{track:n};let i=new Event(`track`);i.track=n,i.receiver=r,i.transceiver={receiver:r},i.streams=[t.stream],this.dispatchEvent(i)})},this.addEventListener(`addstream`,this._ontrackpoly)),t.apply(this,arguments)}}else Us(e,`track`,e=>(e.transceiver||Object.defineProperty(e,`transceiver`,{value:{receiver:e.receiver}}),e))}function rc(e){if(typeof e==`object`&&e.RTCPeerConnection&&!(`getSenders`in e.RTCPeerConnection.prototype)&&`createDTMFSender`in e.RTCPeerConnection.prototype){let t=function(e,t){return{track:t,get dtmf(){return this._dtmf===void 0&&(t.kind===`audio`?this._dtmf=e.createDTMFSender(t):this._dtmf=null),this._dtmf},_pc:e}};if(!e.RTCPeerConnection.prototype.getSenders){e.RTCPeerConnection.prototype.getSenders=function(){return this._senders=this._senders||[],this._senders.slice()};let n=e.RTCPeerConnection.prototype.addTrack;e.RTCPeerConnection.prototype.addTrack=function(e,r){let i=n.apply(this,arguments);return i||(i=t(this,e),this._senders.push(i)),i};let r=e.RTCPeerConnection.prototype.removeTrack;e.RTCPeerConnection.prototype.removeTrack=function(e){r.apply(this,arguments);let t=this._senders.indexOf(e);t!==-1&&this._senders.splice(t,1)}}let n=e.RTCPeerConnection.prototype.addStream;e.RTCPeerConnection.prototype.addStream=function(e){this._senders=this._senders||[],n.apply(this,[e]),e.getTracks().forEach(e=>{this._senders.push(t(this,e))})};let r=e.RTCPeerConnection.prototype.removeStream;e.RTCPeerConnection.prototype.removeStream=function(e){this._senders=this._senders||[],r.apply(this,[e]),e.getTracks().forEach(e=>{let t=this._senders.find(t=>t.track===e);t&&this._senders.splice(this._senders.indexOf(t),1)})}}else if(typeof e==`object`&&e.RTCPeerConnection&&`getSenders`in e.RTCPeerConnection.prototype&&`createDTMFSender`in e.RTCPeerConnection.prototype&&e.RTCRtpSender&&!(`dtmf`in e.RTCRtpSender.prototype)){let t=e.RTCPeerConnection.prototype.getSenders;e.RTCPeerConnection.prototype.getSenders=function(){let e=t.apply(this,[]);return e.forEach(e=>e._pc=this),e},Object.defineProperty(e.RTCRtpSender.prototype,`dtmf`,{get(){return this._dtmf===void 0&&(this.track.kind===`audio`?this._dtmf=this._pc.createDTMFSender(this.track):this._dtmf=null),this._dtmf}})}}function ic(e){if(!(typeof e==`object`&&e.RTCPeerConnection&&e.RTCRtpSender&&e.RTCRtpReceiver))return;if(!(`getStats`in e.RTCRtpSender.prototype)){let t=e.RTCPeerConnection.prototype.getSenders;t&&(e.RTCPeerConnection.prototype.getSenders=function(){let e=t.apply(this,[]);return e.forEach(e=>e._pc=this),e});let n=e.RTCPeerConnection.prototype.addTrack;n&&(e.RTCPeerConnection.prototype.addTrack=function(){let e=n.apply(this,arguments);return e._pc=this,e}),e.RTCRtpSender.prototype.getStats=function(){let e=this;return this._pc.getStats().then(t=>Qs(t,e.track,!0))}}if(!(`getStats`in e.RTCRtpReceiver.prototype)){let t=e.RTCPeerConnection.prototype.getReceivers;t&&(e.RTCPeerConnection.prototype.getReceivers=function(){let e=t.apply(this,[]);return e.forEach(e=>e._pc=this),e}),Us(e,`track`,e=>(e.receiver._pc=e.srcElement,e)),e.RTCRtpReceiver.prototype.getStats=function(){let e=this;return this._pc.getStats().then(t=>Qs(t,e.track,!1))}}if(!(`getStats`in e.RTCRtpSender.prototype&&`getStats`in e.RTCRtpReceiver.prototype))return;let t=e.RTCPeerConnection.prototype.getStats;e.RTCPeerConnection.prototype.getStats=function(){if(arguments.length>0&&arguments[0]instanceof e.MediaStreamTrack){let e=arguments[0],t,n,r;return this.getSenders().forEach(n=>{n.track===e&&(t?r=!0:t=n)}),this.getReceivers().forEach(t=>(t.track===e&&(n?r=!0:n=t),t.track===e)),r||t&&n?Promise.reject(new DOMException(`There are more than one sender or receiver for the track.`,`InvalidAccessError`)):t?t.getStats():n?n.getStats():Promise.reject(new DOMException(`There is no sender or receiver for the track.`,`InvalidAccessError`))}return t.apply(this,arguments)}}function ac(e){e.RTCPeerConnection.prototype.getLocalStreams=function(){return this._shimmedLocalStreams=this._shimmedLocalStreams||{},Object.keys(this._shimmedLocalStreams).map(e=>this._shimmedLocalStreams[e][0])};let t=e.RTCPeerConnection.prototype.addTrack;e.RTCPeerConnection.prototype.addTrack=function(e,n){if(!n)return t.apply(this,arguments);this._shimmedLocalStreams=this._shimmedLocalStreams||{};let r=t.apply(this,arguments);return this._shimmedLocalStreams[n.id]?this._shimmedLocalStreams[n.id].indexOf(r)===-1&&this._shimmedLocalStreams[n.id].push(r):this._shimmedLocalStreams[n.id]=[n,r],r};let n=e.RTCPeerConnection.prototype.addStream;e.RTCPeerConnection.prototype.addStream=function(e){this._shimmedLocalStreams=this._shimmedLocalStreams||{},e.getTracks().forEach(e=>{if(this.getSenders().find(t=>t.track===e))throw new DOMException(`Track already exists.`,`InvalidAccessError`)});let t=this.getSenders();n.apply(this,arguments);let r=this.getSenders().filter(e=>t.indexOf(e)===-1);this._shimmedLocalStreams[e.id]=[e].concat(r)};let r=e.RTCPeerConnection.prototype.removeStream;e.RTCPeerConnection.prototype.removeStream=function(e){return this._shimmedLocalStreams=this._shimmedLocalStreams||{},delete this._shimmedLocalStreams[e.id],r.apply(this,arguments)};let i=e.RTCPeerConnection.prototype.removeTrack;e.RTCPeerConnection.prototype.removeTrack=function(e){return this._shimmedLocalStreams=this._shimmedLocalStreams||{},e&&Object.keys(this._shimmedLocalStreams).forEach(t=>{let n=this._shimmedLocalStreams[t].indexOf(e);n!==-1&&this._shimmedLocalStreams[t].splice(n,1),this._shimmedLocalStreams[t].length===1&&delete this._shimmedLocalStreams[t]}),i.apply(this,arguments)}}function oc(e,t){if(!e.RTCPeerConnection)return;if(e.RTCPeerConnection.prototype.addTrack&&t.version>=65)return ac(e);let n=e.RTCPeerConnection.prototype.getLocalStreams;e.RTCPeerConnection.prototype.getLocalStreams=function(){let e=n.apply(this);return this._reverseStreams=this._reverseStreams||{},e.map(e=>this._reverseStreams[e.id])};let r=e.RTCPeerConnection.prototype.addStream;e.RTCPeerConnection.prototype.addStream=function(t){if(this._streams=this._streams||{},this._reverseStreams=this._reverseStreams||{},t.getTracks().forEach(e=>{if(this.getSenders().find(t=>t.track===e))throw new DOMException(`Track already exists.`,`InvalidAccessError`)}),!this._reverseStreams[t.id]){let n=new e.MediaStream(t.getTracks());this._streams[t.id]=n,this._reverseStreams[n.id]=t,t=n}r.apply(this,[t])};let i=e.RTCPeerConnection.prototype.removeStream;e.RTCPeerConnection.prototype.removeStream=function(e){this._streams=this._streams||{},this._reverseStreams=this._reverseStreams||{},i.apply(this,[this._streams[e.id]||e]),delete this._reverseStreams[this._streams[e.id]?this._streams[e.id].id:e.id],delete this._streams[e.id]},e.RTCPeerConnection.prototype.addTrack=function(t,n){if(this.signalingState===`closed`)throw new DOMException(`The RTCPeerConnection's signalingState is 'closed'.`,`InvalidStateError`);let r=[].slice.call(arguments,1);if(r.length!==1||!r[0].getTracks().find(e=>e===t))throw new DOMException(`The adapter.js addTrack polyfill only supports a single stream which is associated with the specified track.`,`NotSupportedError`);if(this.getSenders().find(e=>e.track===t))throw new DOMException(`Track already exists.`,`InvalidAccessError`);this._streams=this._streams||{},this._reverseStreams=this._reverseStreams||{};let i=this._streams[n.id];if(i)i.addTrack(t),Promise.resolve().then(()=>{this.dispatchEvent(new Event(`negotiationneeded`))});else{let r=new e.MediaStream([t]);this._streams[n.id]=r,this._reverseStreams[r.id]=n,this.addStream(r)}return this.getSenders().find(e=>e.track===t)};function a(e,t){let n=t.sdp;return Object.keys(e._reverseStreams||[]).forEach(t=>{let r=e._reverseStreams[t],i=e._streams[r.id];n=n.replace(new RegExp(i.id,`g`),r.id)}),new RTCSessionDescription({type:t.type,sdp:n})}function o(e,t){let n=t.sdp;return Object.keys(e._reverseStreams||[]).forEach(t=>{let r=e._reverseStreams[t],i=e._streams[r.id];n=n.replace(new RegExp(r.id,`g`),i.id)}),new RTCSessionDescription({type:t.type,sdp:n})}[`createOffer`,`createAnswer`].forEach(function(t){let n=e.RTCPeerConnection.prototype[t],r={[t](){let e=arguments;return arguments.length&&typeof arguments[0]==`function`?n.apply(this,[t=>{let n=a(this,t);e[0].apply(null,[n])},t=>{e[1]&&e[1].apply(null,t)},arguments[2]]):n.apply(this,arguments).then(e=>a(this,e))}};e.RTCPeerConnection.prototype[t]=r[t]});let s=e.RTCPeerConnection.prototype.setLocalDescription;e.RTCPeerConnection.prototype.setLocalDescription=function(){return!arguments.length||!arguments[0].type||(arguments[0]=o(this,arguments[0])),s.apply(this,arguments)};let c=Object.getOwnPropertyDescriptor(e.RTCPeerConnection.prototype,`localDescription`);Object.defineProperty(e.RTCPeerConnection.prototype,`localDescription`,{get(){let e=c.get.apply(this);return e.type===``?e:a(this,e)}}),e.RTCPeerConnection.prototype.removeTrack=function(e){if(this.signalingState===`closed`)throw new DOMException(`The RTCPeerConnection's signalingState is 'closed'.`,`InvalidStateError`);if(!e._pc)throw new DOMException(`Argument 1 of RTCPeerConnection.removeTrack does not implement interface RTCRtpSender.`,`TypeError`);if(e._pc!==this)throw new DOMException(`Sender was not created by this connection.`,`InvalidAccessError`);this._streams=this._streams||{};let t;Object.keys(this._streams).forEach(n=>{this._streams[n].getTracks().find(t=>e.track===t)&&(t=this._streams[n])}),t&&(t.getTracks().length===1?this.removeStream(this._reverseStreams[t.id]):t.removeTrack(e.track),this.dispatchEvent(new Event(`negotiationneeded`)))}}function sc(e,t){!e.RTCPeerConnection&&e.webkitRTCPeerConnection&&(e.RTCPeerConnection=e.webkitRTCPeerConnection),e.RTCPeerConnection&&t.version<53&&[`setLocalDescription`,`setRemoteDescription`,`addIceCandidate`].forEach(function(t){let n=e.RTCPeerConnection.prototype[t],r={[t](){return arguments[0]=new(t===`addIceCandidate`?e.RTCIceCandidate:e.RTCSessionDescription)(arguments[0]),n.apply(this,arguments)}};e.RTCPeerConnection.prototype[t]=r[t]})}function cc(e,t){Us(e,`negotiationneeded`,e=>{let n=e.target;if(!((t.version<72||n.getConfiguration&&n.getConfiguration().sdpSemantics===`plan-b`)&&n.signalingState!==`stable`))return e})}var lc=Object.freeze({__proto__:null,fixNegotiationNeeded:cc,shimAddTrackRemoveTrack:oc,shimAddTrackRemoveTrackWithNative:ac,shimGetSendersWithDtmf:rc,shimGetUserMedia:ec,shimMediaStream:tc,shimOnTrack:nc,shimPeerConnection:sc,shimSenderReceiverGetStats:ic});function uc(e,t){let n=e&&e.navigator,r=e&&e.MediaStreamTrack;if(n.getUserMedia=function(e,t,r){qs(`navigator.getUserMedia`,`navigator.mediaDevices.getUserMedia`),n.mediaDevices.getUserMedia(e).then(t,r)},!(t.version>55&&`autoGainControl`in n.mediaDevices.getSupportedConstraints())){let e=function(e,t,n){t in e&&!(n in e)&&(e[n]=e[t],delete e[t])},t=n.mediaDevices.getUserMedia.bind(n.mediaDevices);if(n.mediaDevices.getUserMedia=function(n){return typeof n==`object`&&typeof n.audio==`object`&&(n=JSON.parse(JSON.stringify(n)),e(n.audio,`autoGainControl`,`mozAutoGainControl`),e(n.audio,`noiseSuppression`,`mozNoiseSuppression`)),t(n)},r&&r.prototype.getSettings){let t=r.prototype.getSettings;r.prototype.getSettings=function(){let n=t.apply(this,arguments);return e(n,`mozAutoGainControl`,`autoGainControl`),e(n,`mozNoiseSuppression`,`noiseSuppression`),n}}if(r&&r.prototype.applyConstraints){let t=r.prototype.applyConstraints;r.prototype.applyConstraints=function(n){return this.kind===`audio`&&typeof n==`object`&&(n=JSON.parse(JSON.stringify(n)),e(n,`autoGainControl`,`mozAutoGainControl`),e(n,`noiseSuppression`,`mozNoiseSuppression`)),t.apply(this,[n])}}}}function dc(e,t){e.navigator.mediaDevices&&`getDisplayMedia`in e.navigator.mediaDevices||e.navigator.mediaDevices&&(e.navigator.mediaDevices.getDisplayMedia=function(n){if(!(n&&n.video)){let e=new DOMException(`getDisplayMedia without video constraints is undefined`);return e.name=`NotFoundError`,e.code=8,Promise.reject(e)}return n.video===!0?n.video={mediaSource:t}:n.video.mediaSource=t,e.navigator.mediaDevices.getUserMedia(n)})}function fc(e){typeof e==`object`&&e.RTCTrackEvent&&`receiver`in e.RTCTrackEvent.prototype&&!(`transceiver`in e.RTCTrackEvent.prototype)&&Object.defineProperty(e.RTCTrackEvent.prototype,`transceiver`,{get(){return{receiver:this.receiver}}})}function pc(e,t){if(typeof e!=`object`||!(e.RTCPeerConnection||e.mozRTCPeerConnection))return;!e.RTCPeerConnection&&e.mozRTCPeerConnection&&(e.RTCPeerConnection=e.mozRTCPeerConnection),t.version<53&&[`setLocalDescription`,`setRemoteDescription`,`addIceCandidate`].forEach(function(t){let n=e.RTCPeerConnection.prototype[t],r={[t](){return arguments[0]=new(t===`addIceCandidate`?e.RTCIceCandidate:e.RTCSessionDescription)(arguments[0]),n.apply(this,arguments)}};e.RTCPeerConnection.prototype[t]=r[t]});let n={inboundrtp:`inbound-rtp`,outboundrtp:`outbound-rtp`,candidatepair:`candidate-pair`,localcandidate:`local-candidate`,remotecandidate:`remote-candidate`},r=e.RTCPeerConnection.prototype.getStats;e.RTCPeerConnection.prototype.getStats=function(){let[e,i,a]=arguments;return r.apply(this,[e||null]).then(e=>{if(t.version<53&&!i)try{e.forEach(e=>{e.type=n[e.type]||e.type})}catch(t){if(t.name!==`TypeError`)throw t;e.forEach((t,r)=>{e.set(r,Object.assign({},t,{type:n[t.type]||t.type}))})}return e}).then(i,a)}}function mc(e){if(!(typeof e==`object`&&e.RTCPeerConnection&&e.RTCRtpSender)||e.RTCRtpSender&&`getStats`in e.RTCRtpSender.prototype)return;let t=e.RTCPeerConnection.prototype.getSenders;t&&(e.RTCPeerConnection.prototype.getSenders=function(){let e=t.apply(this,[]);return e.forEach(e=>e._pc=this),e});let n=e.RTCPeerConnection.prototype.addTrack;n&&(e.RTCPeerConnection.prototype.addTrack=function(){let e=n.apply(this,arguments);return e._pc=this,e}),e.RTCRtpSender.prototype.getStats=function(){return this.track?this._pc.getStats(this.track):Promise.resolve(new Map)}}function hc(e){if(!(typeof e==`object`&&e.RTCPeerConnection&&e.RTCRtpSender)||e.RTCRtpSender&&`getStats`in e.RTCRtpReceiver.prototype)return;let t=e.RTCPeerConnection.prototype.getReceivers;t&&(e.RTCPeerConnection.prototype.getReceivers=function(){let e=t.apply(this,[]);return e.forEach(e=>e._pc=this),e}),Us(e,`track`,e=>(e.receiver._pc=e.srcElement,e)),e.RTCRtpReceiver.prototype.getStats=function(){return this._pc.getStats(this.track)}}function gc(e){!e.RTCPeerConnection||`removeStream`in e.RTCPeerConnection.prototype||(e.RTCPeerConnection.prototype.removeStream=function(e){qs(`removeStream`,`removeTrack`),this.getSenders().forEach(t=>{t.track&&e.getTracks().includes(t.track)&&this.removeTrack(t)})})}function _c(e){e.DataChannel&&!e.RTCDataChannel&&(e.RTCDataChannel=e.DataChannel)}function vc(e){if(!(typeof e==`object`&&e.RTCPeerConnection))return;let t=e.RTCPeerConnection.prototype.addTransceiver;t&&(e.RTCPeerConnection.prototype.addTransceiver=function(){this.setParametersPromises=[];let e=arguments[1]&&arguments[1].sendEncodings;e===void 0&&(e=[]),e=[...e];let n=e.length>0;n&&e.forEach(e=>{if(`rid`in e&&!/^[a-z0-9]{0,16}$/i.test(e.rid))throw TypeError(`Invalid RID value provided.`);if(`scaleResolutionDownBy`in e&&!(parseFloat(e.scaleResolutionDownBy)>=1))throw RangeError(`scale_resolution_down_by must be >= 1.0`);if(`maxFramerate`in e&&!(parseFloat(e.maxFramerate)>=0))throw RangeError(`max_framerate must be >= 0.0`)});let r=t.apply(this,arguments);if(n){let{sender:t}=r,n=t.getParameters();(!(`encodings`in n)||n.encodings.length===1&&Object.keys(n.encodings[0]).length===0)&&(n.encodings=e,t.sendEncodings=e,this.setParametersPromises.push(t.setParameters(n).then(()=>{delete t.sendEncodings}).catch(()=>{delete t.sendEncodings})))}return r})}function yc(e){if(!(typeof e==`object`&&e.RTCRtpSender))return;let t=e.RTCRtpSender.prototype.getParameters;t&&(e.RTCRtpSender.prototype.getParameters=function(){let e=t.apply(this,arguments);return`encodings`in e||(e.encodings=[].concat(this.sendEncodings||[{}])),e})}function bc(e){if(!(typeof e==`object`&&e.RTCPeerConnection))return;let t=e.RTCPeerConnection.prototype.createOffer;e.RTCPeerConnection.prototype.createOffer=function(){return this.setParametersPromises&&this.setParametersPromises.length?Promise.all(this.setParametersPromises).then(()=>t.apply(this,arguments)).finally(()=>{this.setParametersPromises=[]}):t.apply(this,arguments)}}function xc(e){if(!(typeof e==`object`&&e.RTCPeerConnection))return;let t=e.RTCPeerConnection.prototype.createAnswer;e.RTCPeerConnection.prototype.createAnswer=function(){return this.setParametersPromises&&this.setParametersPromises.length?Promise.all(this.setParametersPromises).then(()=>t.apply(this,arguments)).finally(()=>{this.setParametersPromises=[]}):t.apply(this,arguments)}}var Sc=Object.freeze({__proto__:null,shimAddTransceiver:vc,shimCreateAnswer:xc,shimCreateOffer:bc,shimGetDisplayMedia:dc,shimGetParameters:yc,shimGetUserMedia:uc,shimOnTrack:fc,shimPeerConnection:pc,shimRTCDataChannel:_c,shimReceiverGetStats:hc,shimRemoveStream:gc,shimSenderGetStats:mc});function Cc(e){if(!(typeof e!=`object`||!e.RTCPeerConnection)){if(`getLocalStreams`in e.RTCPeerConnection.prototype||(e.RTCPeerConnection.prototype.getLocalStreams=function(){return this._localStreams||=[],this._localStreams}),!(`addStream`in e.RTCPeerConnection.prototype)){let t=e.RTCPeerConnection.prototype.addTrack;e.RTCPeerConnection.prototype.addStream=function(e){this._localStreams||=[],this._localStreams.includes(e)||this._localStreams.push(e),e.getAudioTracks().forEach(n=>t.call(this,n,e)),e.getVideoTracks().forEach(n=>t.call(this,n,e))},e.RTCPeerConnection.prototype.addTrack=function(e){for(var n=arguments.length,r=Array(n>1?n-1:0),i=1;i<n;i++)r[i-1]=arguments[i];return r&&r.forEach(e=>{this._localStreams?this._localStreams.includes(e)||this._localStreams.push(e):this._localStreams=[e]}),t.apply(this,arguments)}}`removeStream`in e.RTCPeerConnection.prototype||(e.RTCPeerConnection.prototype.removeStream=function(e){this._localStreams||=[];let t=this._localStreams.indexOf(e);if(t===-1)return;this._localStreams.splice(t,1);let n=e.getTracks();this.getSenders().forEach(e=>{n.includes(e.track)&&this.removeTrack(e)})})}}function wc(e){if(!(typeof e!=`object`||!e.RTCPeerConnection)&&(`getRemoteStreams`in e.RTCPeerConnection.prototype||(e.RTCPeerConnection.prototype.getRemoteStreams=function(){return this._remoteStreams?this._remoteStreams:[]}),!(`onaddstream`in e.RTCPeerConnection.prototype))){Object.defineProperty(e.RTCPeerConnection.prototype,`onaddstream`,{get(){return this._onaddstream},set(e){this._onaddstream&&(this.removeEventListener(`addstream`,this._onaddstream),this.removeEventListener(`track`,this._onaddstreampoly)),this.addEventListener(`addstream`,this._onaddstream=e),this.addEventListener(`track`,this._onaddstreampoly=e=>{e.streams.forEach(e=>{if(this._remoteStreams||=[],this._remoteStreams.includes(e))return;this._remoteStreams.push(e);let t=new Event(`addstream`);t.stream=e,this.dispatchEvent(t)})})}});let t=e.RTCPeerConnection.prototype.setRemoteDescription;e.RTCPeerConnection.prototype.setRemoteDescription=function(){let e=this;return this._onaddstreampoly||this.addEventListener(`track`,this._onaddstreampoly=function(t){t.streams.forEach(t=>{if(e._remoteStreams||=[],e._remoteStreams.indexOf(t)>=0)return;e._remoteStreams.push(t);let n=new Event(`addstream`);n.stream=t,e.dispatchEvent(n)})}),t.apply(e,arguments)}}}function Tc(e){if(typeof e!=`object`||!e.RTCPeerConnection)return;let t=e.RTCPeerConnection.prototype,n=t.createOffer,r=t.createAnswer,i=t.setLocalDescription,a=t.setRemoteDescription,o=t.addIceCandidate;t.createOffer=function(e,t){let r=arguments.length>=2?arguments[2]:arguments[0],i=n.apply(this,[r]);return t?(i.then(e,t),Promise.resolve()):i},t.createAnswer=function(e,t){let n=arguments.length>=2?arguments[2]:arguments[0],i=r.apply(this,[n]);return t?(i.then(e,t),Promise.resolve()):i};let s=function(e,t,n){let r=i.apply(this,[e]);return n?(r.then(t,n),Promise.resolve()):r};t.setLocalDescription=s,s=function(e,t,n){let r=a.apply(this,[e]);return n?(r.then(t,n),Promise.resolve()):r},t.setRemoteDescription=s,s=function(e,t,n){let r=o.apply(this,[e]);return n?(r.then(t,n),Promise.resolve()):r},t.addIceCandidate=s}function Ec(e){let t=e&&e.navigator;if(t.mediaDevices&&t.mediaDevices.getUserMedia){let e=t.mediaDevices,n=e.getUserMedia.bind(e);t.mediaDevices.getUserMedia=e=>n(Dc(e))}!t.getUserMedia&&t.mediaDevices&&t.mediaDevices.getUserMedia&&(t.getUserMedia=function(e,n,r){t.mediaDevices.getUserMedia(e).then(n,r)}.bind(t))}function Dc(e){return e&&e.video!==void 0?Object.assign({},e,{video:Xs(e.video)}):e}function Oc(e){if(!e.RTCPeerConnection)return;let t=e.RTCPeerConnection;e.RTCPeerConnection=function(e,n){if(e&&e.iceServers){let t=[];for(let n=0;n<e.iceServers.length;n++){let r=e.iceServers[n];r.urls===void 0&&r.url?(qs(`RTCIceServer.url`,`RTCIceServer.urls`),r=JSON.parse(JSON.stringify(r)),r.urls=r.url,delete r.url,t.push(r)):t.push(e.iceServers[n])}e.iceServers=t}return new t(e,n)},e.RTCPeerConnection.prototype=t.prototype,`generateCertificate`in t&&Object.defineProperty(e.RTCPeerConnection,`generateCertificate`,{get(){return t.generateCertificate}})}function kc(e){typeof e==`object`&&e.RTCTrackEvent&&`receiver`in e.RTCTrackEvent.prototype&&!(`transceiver`in e.RTCTrackEvent.prototype)&&Object.defineProperty(e.RTCTrackEvent.prototype,`transceiver`,{get(){return{receiver:this.receiver}}})}function Ac(e){let t=e.RTCPeerConnection.prototype.createOffer;e.RTCPeerConnection.prototype.createOffer=function(e){if(e){e.offerToReceiveAudio!==void 0&&(e.offerToReceiveAudio=!!e.offerToReceiveAudio);let t=this.getTransceivers().find(e=>e.receiver.track.kind===`audio`);e.offerToReceiveAudio===!1&&t?t.direction===`sendrecv`?t.setDirection?t.setDirection(`sendonly`):t.direction=`sendonly`:t.direction===`recvonly`&&(t.setDirection?t.setDirection(`inactive`):t.direction=`inactive`):e.offerToReceiveAudio===!0&&!t&&this.addTransceiver(`audio`,{direction:`recvonly`}),e.offerToReceiveVideo!==void 0&&(e.offerToReceiveVideo=!!e.offerToReceiveVideo);let n=this.getTransceivers().find(e=>e.receiver.track.kind===`video`);e.offerToReceiveVideo===!1&&n?n.direction===`sendrecv`?n.setDirection?n.setDirection(`sendonly`):n.direction=`sendonly`:n.direction===`recvonly`&&(n.setDirection?n.setDirection(`inactive`):n.direction=`inactive`):e.offerToReceiveVideo===!0&&!n&&this.addTransceiver(`video`,{direction:`recvonly`})}return t.apply(this,arguments)}}function jc(e){typeof e!=`object`||e.AudioContext||(e.AudioContext=e.webkitAudioContext)}var Mc=Object.freeze({__proto__:null,shimAudioContext:jc,shimCallbacksAPI:Tc,shimConstraints:Dc,shimCreateOfferLegacy:Ac,shimGetUserMedia:Ec,shimLocalStreamsAPI:Cc,shimRTCIceServerUrls:Oc,shimRemoteStreamsAPI:wc,shimTrackEventTransceiver:kc}),Nc={exports:{}},Pc;function Fc(){return Pc?Nc.exports:(Pc=1,(function(e){let t={};t.generateIdentifier=function(){return Math.random().toString(36).substring(2,12)},t.localCName=t.generateIdentifier(),t.splitLines=function(e){return e.trim().split(`
|
|
30
|
+
`).map((e,t)=>(0,u.jsx)(`div`,{children:e},t))||(0,u.jsxs)(u.Fragment,{children:[(0,u.jsx)(`div`,{children:`Hi there 👋`}),(0,u.jsx)(`div`,{children:`How can we help?`})]})})}),(0,u.jsx)(`div`,{style:{display:`flex`,flexDirection:`column`,alignItems:`stretch`,gap:`10px`,padding:`8px 20px 24px`,width:`100%`,boxSizing:`border-box`},children:r.map((e,t)=>(0,u.jsx)(`div`,{style:{display:`flex`,flexDirection:`row`,justifyContent:`flex-end`,alignItems:`center`,flexWrap:`wrap`,gap:`10px`,width:`100%`},children:e.map(e=>(0,u.jsx)(`button`,{type:`button`,style:{...$n},onClick:()=>n(e.label,e.key),onMouseEnter:e=>{e.currentTarget.style.transform=`translateY(-1px)`,e.currentTarget.style.boxShadow=`0 6px 16px rgba(0,0,0,0.1)`},onMouseLeave:e=>{e.currentTarget.style.transform=`translateY(0)`,e.currentTarget.style.boxShadow=`0 4px 12px rgba(0,0,0,0.06)`},children:e.label},e.key))},`row-${t}`))})]})}function nr({input:e,setInput:t,onSubmit:n,isConversationEnded:r,callUiActive:i,handleToggleVoice:a,activeScreen:o,inputDisabled:s,replyContext:c,clearReplyContext:l,requiresEmail:d,emailInput:f,setEmailInput:p,emailError:m}){let ee=c?.sender===`user`?`You`:c?.sender===`agent`?`Agent`:`AI Assistant`,h=d?!!f?.trim():!!e?.trim(),g=s||!h;return(0,u.jsxs)(`div`,{style:{padding:`0 20px 4px`,background:`transparent`},children:[r&&(0,u.jsx)(`div`,{style:{marginBottom:`8px`,padding:`8px 16px`,borderRadius:`12px`,background:`#f3f4f6`,color:`#6b7280`,fontSize:`12px`,textAlign:`center`,fontWeight:500},children:`This conversation has ended.`}),c&&(0,u.jsxs)(`div`,{style:{marginBottom:`8px`,display:`flex`,alignItems:`flex-start`,justifyContent:`space-between`,gap:`12px`,borderRadius:`16px`,border:`1px solid rgba(0,0,0,0.05)`,background:`#fff`,padding:`12px 16px`,boxShadow:`0 8px 24px rgba(0,0,0,0.05)`},children:[(0,u.jsxs)(`div`,{style:{minWidth:0,flex:1,borderLeft:`2px solid var(--flowengage-primary)`,paddingLeft:`12px`},children:[(0,u.jsxs)(`div`,{style:{fontSize:`12px`,fontWeight:600,color:`var(--flowengage-primary)`},children:[`Replying to `,ee]}),(0,u.jsx)(`div`,{style:{overflow:`hidden`,textOverflow:`ellipsis`,whiteSpace:`nowrap`,fontSize:`12px`,color:`#6b7280`},children:c.replyToContent||c.message})]}),(0,u.jsx)(`button`,{type:`button`,style:{width:`28px`,height:`28px`,borderRadius:`9999px`,border:0,background:`#f3f4f6`,color:`#6b7280`,transition:`color 0.2s ease, background 0.2s ease`,cursor:`pointer`},onClick:l,"aria-label":`Cancel reply`,onMouseEnter:e=>{e.currentTarget.style.background=`#e5e7eb`,e.currentTarget.style.color=`#374151`},onMouseLeave:e=>{e.currentTarget.style.background=`#f3f4f6`,e.currentTarget.style.color=`#6b7280`},children:`×`})]}),d&&(0,u.jsx)(`div`,{style:{marginBottom:`14px`,padding:`0 8px`},children:(0,u.jsxs)(`div`,{style:{display:`flex`,alignItems:`center`,justifyContent:`center`,gap:`8px`,color:`#111827`,fontSize:`14px`,fontWeight:500,textAlign:`center`},children:[(0,u.jsx)(`span`,{style:{display:`inline-flex`,width:`22px`,height:`22px`,borderRadius:`9999px`,alignItems:`center`,justifyContent:`center`,background:`rgba(59,130,246,0.08)`,color:`var(--flowengage-primary)`},children:(0,u.jsx)(Bn,{size:13})}),(0,u.jsx)(`span`,{children:`Please provide your email address so we can help you.`})]})}),(0,u.jsxs)(`form`,{style:{display:`flex`,alignItems:`center`,gap:`8px`,padding:`6px 10px`,border:`1px solid rgba(0,0,0,0.05)`,borderRadius:`9999px`,background:`#fff`,boxShadow:`0 8px 24px rgba(0,0,0,0.05)`,opacity:r?.5:1},onSubmit:n,children:[d?(0,u.jsx)(`span`,{style:{width:`32px`,flexShrink:0},"aria-hidden":!0}):(0,u.jsx)(`button`,{type:`button`,style:{width:`32px`,height:`32px`,borderRadius:`9999px`,background:`transparent`,color:`#9ca3af`,display:`flex`,alignItems:`center`,justifyContent:`center`,transition:`background 0.2s ease, color 0.2s ease`,border:0,cursor:`pointer`},onClick:a,title:`Voice assistant`,"aria-label":`Voice assistant`,disabled:r||i,onMouseEnter:e=>{e.currentTarget.style.background=`#f3f4f6`},onMouseLeave:e=>{e.currentTarget.style.background=`transparent`},children:(0,u.jsx)(Nn,{size:18,color:`currentColor`})}),(0,u.jsx)(`input`,{style:{flex:1,minWidth:0,border:`none`,fontFamily:`inherit`,fontSize:`14px`,outline:`none`,padding:`6px 0`,color:`#111827`,background:`transparent`},value:d?f:e,onChange:e=>{if(d){p(e.target.value);return}t(e.target.value)},placeholder:r?`Conversation ended`:d?`Your email address`:o===`agent`?`Message the agent…`:`Type a reply…`,disabled:s,type:d?`email`:`text`,autoComplete:d?`email`:`off`}),(0,u.jsx)(`button`,{type:`submit`,style:{width:`34px`,height:`34px`,borderRadius:`9999px`,background:`transparent`,color:`var(--flowengage-primary)`,border:`1px solid var(--flowengage-primary)`,display:`flex`,alignItems:`center`,justifyContent:`center`,transition:`all 0.2s ease`,cursor:g?`not-allowed`:`pointer`,marginLeft:`4px`,opacity:g?.45:1},disabled:g,onMouseEnter:e=>{g||(e.currentTarget.style.background=`linear-gradient(135deg, var(--flowengage-primary), var(--flowengage-accent))`,e.currentTarget.style.borderColor=`transparent`,e.currentTarget.style.color=`#fff`)},onMouseLeave:e=>{e.currentTarget.style.background=`transparent`,e.currentTarget.style.borderColor=`var(--flowengage-primary)`,e.currentTarget.style.color=g?`#d1d5db`:`var(--flowengage-primary)`},children:(0,u.jsx)(Fn,{})})]}),d&&m&&(0,u.jsx)(`div`,{style:{padding:`8px 16px 0`,fontSize:`12px`,fontWeight:500,color:`#f43f5e`},children:m})]})}var rr=({muted:e=!1})=>(0,u.jsxs)(`svg`,{width:`16`,height:`16`,viewBox:`0 0 24 24`,fill:`none`,stroke:`currentColor`,strokeWidth:`2`,strokeLinecap:`round`,strokeLinejoin:`round`,children:[(0,u.jsx)(`path`,{d:`M12 1a4 4 0 014 4v6a4 4 0 01-6.83 2.83`}),(0,u.jsx)(`path`,{d:`M19 10a7 7 0 01-1.62 4.49M5 10a7 7 0 008.79 6.77`}),(0,u.jsx)(`path`,{d:`M12 19v4M8 23h8`}),e&&(0,u.jsx)(`line`,{x1:`2`,y1:`2`,x2:`22`,y2:`22`})]}),ir=({variant:e,onClick:t,children:n,icon:r,compact:i=!1,iconOnly:a=!1,active:o=!1,ariaLabel:s})=>(0,u.jsxs)(`button`,{type:`button`,className:[`flowengage-call-btn`,`flowengage-call-btn-${e}`,i?`compact`:``,a?`icon-only`:``,o?`active`:``].filter(Boolean).join(` `),onClick:t,"aria-label":s||n,title:s||n,children:[r,!a&&(0,u.jsx)(`span`,{children:n})]});function ar({webRTCError:e,micError:t,setMicError:n,dismissCallError:r,incomingCall:i,rejectCall:a,acceptCall:o,activeCallId:s,callConnectionState:c,formatCallDuration:d,callDurationSeconds:f,endWebRTCCall:p,isCallMuted:m,toggleCallMute:ee,isAIVoiceActive:h,currentCallAgentName:g,isRateLimited:te,rateLimitMessage:ne}){let re=(0,l.useRef)(null),ie=(0,l.useCallback)(()=>{if(!re.current)return;let{audioContext:e,oscillator:t,interval:n,toneTimeout:r}=re.current;window.clearInterval(n),window.clearTimeout(r);try{t.stop()}catch{}try{e.close()}catch{}re.current=null},[]),ae=(0,l.useCallback)(()=>{if(re.current||typeof window>`u`)return;let e=window.AudioContext||window.webkitAudioContext||null;if(e)try{let t=new e,n=t.createOscillator(),r=t.createGain();n.connect(r),r.connect(t.destination),n.frequency.value=0,n.type=`sine`,r.gain.value=.3;let i=()=>{re.current&&(window.clearTimeout(re.current.toneTimeout),n.frequency.value=440,re.current.toneTimeout=window.setTimeout(()=>{n.frequency.value=0},400))};t.state===`suspended`&&t.resume().catch(e=>{console.warn(`[FlowEngage] ringtone autoplay blocked`,e)}),n.start(),re.current={audioContext:t,oscillator:n,interval:null,toneTimeout:null},i(),re.current.interval=window.setInterval(i,1e3)}catch(e){console.warn(`[FlowEngage] failed to start ringtone`,e)}},[]);(0,l.useEffect)(()=>{if(i){ae();return}ie()},[i,ae,ie]),(0,l.useEffect)(()=>()=>ie(),[ie]);let oe=h?`header-mode`:`bottom-mode`,_=!!(i||s),v=i?`incoming`:c===`connected`?`connected`:`connecting`,se=(0,l.useMemo)(()=>v===`incoming`?`Incoming Call`:v===`connected`?`Voice Call Active`:`Connecting Call`,[v]),ce=(0,l.useMemo)(()=>v===`incoming`?`${g} wants to join a voice call`:v===`connected`?`You are connected to ${g} from this conversation.`:`Please wait while ${g}'s voice connection finishes setting up.`,[g,v]);return(0,u.jsxs)(u.Fragment,{children:[(e||t)&&(0,u.jsxs)(`div`,{style:{margin:`0 20px 10px`,padding:`12px 16px`,borderRadius:`12px`,background:`#fef2f2`,border:`1px solid #fee2e2`,display:`flex`,alignItems:`flex-start`,gap:`10px`},children:[(0,u.jsx)(Rn,{className:``}),(0,u.jsx)(`span`,{style:{fontSize:`12px`,color:`#b91c1c`,lineHeight:1.5,flex:1},children:e||t}),(0,u.jsx)(`button`,{style:{flexShrink:0,background:`transparent`,border:0,color:`#f87171`,cursor:`pointer`,fontSize:`18px`,lineHeight:1},onClick:()=>{n(null),r()},onMouseEnter:e=>{e.currentTarget.style.color=`#dc2626`},onMouseLeave:e=>{e.currentTarget.style.color=`#f87171`},children:`×`})]}),_&&(0,u.jsx)(`div`,{className:`incoming-call-overlay ${oe}`,children:(0,u.jsx)(`div`,{className:[`incoming-call-container`,v===`connected`?`connected-layout`:``].filter(Boolean).join(` `),children:v===`connected`?(0,u.jsxs)(u.Fragment,{children:[(0,u.jsxs)(`div`,{className:`call-connected-top`,children:[(0,u.jsxs)(`div`,{className:`call-connected-identity`,children:[(0,u.jsx)(`div`,{className:`call-icon-wrapper ${v}`,children:(0,u.jsx)(Pn,{size:20})}),(0,u.jsxs)(`div`,{className:`call-info-group`,children:[(0,u.jsx)(`h3`,{className:`call-title`,children:se}),(0,u.jsx)(`p`,{className:`call-subtitle`,children:ce})]})]}),(0,u.jsx)(`div`,{className:`call-timer`,children:d(f)})]}),(0,u.jsxs)(`div`,{className:`call-actions connected`,children:[(0,u.jsx)(ir,{variant:`mute`,onClick:ee,compact:h,active:m,icon:(0,u.jsx)(rr,{muted:m}),children:m?`Unmute`:`Mute`}),(0,u.jsx)(ir,{variant:`end`,onClick:p,compact:h,icon:(0,u.jsx)(Pn,{size:14}),children:`End`})]})]}):(0,u.jsxs)(u.Fragment,{children:[(0,u.jsxs)(`div`,{className:`call-icon-wrapper ${v}`,children:[(0,u.jsx)(Ln,{}),v===`incoming`&&(0,u.jsx)(`div`,{className:`call-pulse-animation`}),v===`connecting`&&(0,u.jsx)(`div`,{className:`call-connecting-animation`})]}),(0,u.jsxs)(`div`,{className:`call-info-group`,children:[(0,u.jsx)(`h3`,{className:`call-title`,children:se}),(0,u.jsx)(`p`,{className:`call-subtitle`,children:ce})]}),(0,u.jsx)(`div`,{className:`call-actions`,children:v===`incoming`&&(0,u.jsxs)(u.Fragment,{children:[(0,u.jsx)(ir,{variant:`reject`,onClick:async()=>{ie(),await a()},iconOnly:!0,icon:(0,u.jsx)(Pn,{size:14}),ariaLabel:`Decline call`,children:`Decline`}),(0,u.jsx)(ir,{variant:`accept`,onClick:async()=>{ie(),await o()},iconOnly:!0,icon:(0,u.jsx)(Ln,{}),ariaLabel:`Accept call`,children:`Accept`})]})})]})})}),te&&(0,u.jsx)(`div`,{style:{margin:`0 20px 10px`,padding:`12px 16px`,fontSize:`13px`,borderRadius:`12px`,background:`#fee2e2`,color:`#991b1b`},children:ne})]})}function or(e,t){return t.forEach(function(t){t&&typeof t!=`string`&&!Array.isArray(t)&&Object.keys(t).forEach(function(n){if(n!==`default`&&!(n in e)){var r=Object.getOwnPropertyDescriptor(t,n);Object.defineProperty(e,n,r.get?r:{enumerable:!0,get:function(){return t[n]}})}})}),Object.freeze(e)}var sr=Object.defineProperty,cr=(e,t,n)=>t in e?sr(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n,lr=(e,t,n)=>cr(e,typeof t==`symbol`?t:t+``,n),ur=class{constructor(){lr(this,`_locking`),lr(this,`_locks`),this._locking=Promise.resolve(),this._locks=0}isLocked(){return this._locks>0}lock(){this._locks+=1;let e,t=new Promise(t=>e=()=>{--this._locks,t()}),n=this._locking.then(()=>e);return this._locking=this._locking.then(()=>t),n}};function D(e,t){if(!e)throw Error(t)}var dr=34028234663852886e22,fr=-34028234663852886e22,pr=4294967295,mr=2147483647,hr=-2147483648;function gr(e){if(typeof e!=`number`)throw Error(`invalid int 32: `+typeof e);if(!Number.isInteger(e)||e>mr||e<hr)throw Error(`invalid int 32: `+e)}function _r(e){if(typeof e!=`number`)throw Error(`invalid uint 32: `+typeof e);if(!Number.isInteger(e)||e>pr||e<0)throw Error(`invalid uint 32: `+e)}function vr(e){if(typeof e!=`number`)throw Error(`invalid float 32: `+typeof e);if(Number.isFinite(e)&&(e>dr||e<fr))throw Error(`invalid float 32: `+e)}var yr=Symbol(`@bufbuild/protobuf/enum-type`);function br(e){let t=e[yr];return D(t,`missing enum type on enum object`),t}function xr(e,t,n,r){e[yr]=Sr(t,n.map(t=>({no:t.no,name:t.name,localName:e[t.no]})))}function Sr(e,t,n){let r=Object.create(null),i=Object.create(null),a=[];for(let e of t){let t=wr(e);a.push(t),r[e.name]=t,i[e.no]=t}return{typeName:e,values:a,findName(e){return r[e]},findNumber(e){return i[e]}}}function Cr(e,t,n){let r={};for(let e of t){let t=wr(e);r[t.localName]=t.no,r[t.no]=t.localName}return xr(r,e,t),r}function wr(e){return`localName`in e?e:Object.assign(Object.assign({},e),{localName:e.name})}var Tr=class{equals(e){return this.getType().runtime.util.equals(this.getType(),this,e)}clone(){return this.getType().runtime.util.clone(this)}fromBinary(e,t){let n=this.getType().runtime.bin,r=n.makeReadOptions(t);return n.readMessage(this,r.readerFactory(e),e.byteLength,r),this}fromJson(e,t){let n=this.getType(),r=n.runtime.json,i=r.makeReadOptions(t);return r.readMessage(n,e,i,this),this}fromJsonString(e,t){let n;try{n=JSON.parse(e)}catch(e){throw Error(`cannot decode ${this.getType().typeName} from JSON: ${e instanceof Error?e.message:String(e)}`)}return this.fromJson(n,t)}toBinary(e){let t=this.getType().runtime.bin,n=t.makeWriteOptions(e),r=n.writerFactory();return t.writeMessage(this,r,n),r.finish()}toJson(e){let t=this.getType().runtime.json,n=t.makeWriteOptions(e);return t.writeMessage(this,n)}toJsonString(e){let t=this.toJson(e);return JSON.stringify(t,null,e?.prettySpaces??0)}toJSON(){return this.toJson({emitDefaultValues:!0})}getType(){return Object.getPrototypeOf(this).constructor}};function Er(e,t,n,r){let i=r?.localName??t.substring(t.lastIndexOf(`.`)+1),a={[i]:function(t){e.util.initFields(this),e.util.initPartial(t,this)}}[i];return Object.setPrototypeOf(a.prototype,new Tr),Object.assign(a,{runtime:e,typeName:t,fields:e.util.newFieldList(n),fromBinary(e,t){return new a().fromBinary(e,t)},fromJson(e,t){return new a().fromJson(e,t)},fromJsonString(e,t){return new a().fromJsonString(e,t)},equals(t,n){return e.util.equals(a,t,n)}}),a}function Dr(){let e=0,t=0;for(let n=0;n<28;n+=7){let r=this.buf[this.pos++];if(e|=(r&127)<<n,!(r&128))return this.assertBounds(),[e,t]}let n=this.buf[this.pos++];if(e|=(n&15)<<28,t=(n&112)>>4,!(n&128))return this.assertBounds(),[e,t];for(let n=3;n<=31;n+=7){let r=this.buf[this.pos++];if(t|=(r&127)<<n,!(r&128))return this.assertBounds(),[e,t]}throw Error(`invalid varint`)}function Or(e,t,n){for(let r=0;r<28;r+=7){let i=e>>>r,a=!(!(i>>>7)&&t==0),o=(a?i|128:i)&255;if(n.push(o),!a)return}let r=e>>>28&15|(t&7)<<4,i=!!(t>>3);if(n.push((i?r|128:r)&255),i){for(let e=3;e<31;e+=7){let r=t>>>e,i=!!(r>>>7),a=(i?r|128:r)&255;if(n.push(a),!i)return}n.push(t>>>31&1)}}var kr=4294967296;function Ar(e){let t=e[0]===`-`;t&&(e=e.slice(1));let n=1e6,r=0,i=0;function a(t,a){let o=Number(e.slice(t,a));i*=n,r=r*n+o,r>=kr&&(i+=r/kr|0,r%=kr)}return a(-24,-18),a(-18,-12),a(-12,-6),a(-6),t?Fr(r,i):Pr(r,i)}function jr(e,t){let n=Pr(e,t),r=n.hi&2147483648;r&&(n=Fr(n.lo,n.hi));let i=Mr(n.lo,n.hi);return r?`-`+i:i}function Mr(e,t){if({lo:e,hi:t}=Nr(e,t),t<=2097151)return String(kr*t+e);let n=e&16777215,r=(e>>>24|t<<8)&16777215,i=t>>16&65535,a=n+r*6777216+i*6710656,o=r+i*8147497,s=i*2,c=1e7;return a>=c&&(o+=Math.floor(a/c),a%=c),o>=c&&(s+=Math.floor(o/c),o%=c),s.toString()+Ir(o)+Ir(a)}function Nr(e,t){return{lo:e>>>0,hi:t>>>0}}function Pr(e,t){return{lo:e|0,hi:t|0}}function Fr(e,t){return t=~t,e?e=~e+1:t+=1,Pr(e,t)}var Ir=e=>{let t=String(e);return`0000000`.slice(t.length)+t};function Lr(e,t){if(e>=0){for(;e>127;)t.push(e&127|128),e>>>=7;t.push(e)}else{for(let n=0;n<9;n++)t.push(e&127|128),e>>=7;t.push(1)}}function Rr(){let e=this.buf[this.pos++],t=e&127;if(!(e&128)||(e=this.buf[this.pos++],t|=(e&127)<<7,!(e&128))||(e=this.buf[this.pos++],t|=(e&127)<<14,!(e&128))||(e=this.buf[this.pos++],t|=(e&127)<<21,!(e&128)))return this.assertBounds(),t;e=this.buf[this.pos++],t|=(e&15)<<28;for(let t=5;e&128&&t<10;t++)e=this.buf[this.pos++];if(e&128)throw Error(`invalid varint`);return this.assertBounds(),t>>>0}function zr(){let e=new DataView(new ArrayBuffer(8));if(typeof BigInt==`function`&&typeof e.getBigInt64==`function`&&typeof e.getBigUint64==`function`&&typeof e.setBigInt64==`function`&&typeof e.setBigUint64==`function`&&(typeof process!=`object`||typeof process.env!=`object`||process.env.BUF_BIGINT_DISABLE!==`1`)){let t=BigInt(`-9223372036854775808`),n=BigInt(`9223372036854775807`),r=BigInt(`0`),i=BigInt(`18446744073709551615`);return{zero:BigInt(0),supported:!0,parse(e){let r=typeof e==`bigint`?e:BigInt(e);if(r>n||r<t)throw Error(`int64 invalid: ${e}`);return r},uParse(e){let t=typeof e==`bigint`?e:BigInt(e);if(t>i||t<r)throw Error(`uint64 invalid: ${e}`);return t},enc(t){return e.setBigInt64(0,this.parse(t),!0),{lo:e.getInt32(0,!0),hi:e.getInt32(4,!0)}},uEnc(t){return e.setBigInt64(0,this.uParse(t),!0),{lo:e.getInt32(0,!0),hi:e.getInt32(4,!0)}},dec(t,n){return e.setInt32(0,t,!0),e.setInt32(4,n,!0),e.getBigInt64(0,!0)},uDec(t,n){return e.setInt32(0,t,!0),e.setInt32(4,n,!0),e.getBigUint64(0,!0)}}}let t=e=>D(/^-?[0-9]+$/.test(e),`int64 invalid: ${e}`),n=e=>D(/^[0-9]+$/.test(e),`uint64 invalid: ${e}`);return{zero:`0`,supported:!1,parse(e){return typeof e!=`string`&&(e=e.toString()),t(e),e},uParse(e){return typeof e!=`string`&&(e=e.toString()),n(e),e},enc(e){return typeof e!=`string`&&(e=e.toString()),t(e),Ar(e)},uEnc(e){return typeof e!=`string`&&(e=e.toString()),n(e),Ar(e)},dec(e,t){return jr(e,t)},uDec(e,t){return Mr(e,t)}}}var O=zr(),k;(function(e){e[e.DOUBLE=1]=`DOUBLE`,e[e.FLOAT=2]=`FLOAT`,e[e.INT64=3]=`INT64`,e[e.UINT64=4]=`UINT64`,e[e.INT32=5]=`INT32`,e[e.FIXED64=6]=`FIXED64`,e[e.FIXED32=7]=`FIXED32`,e[e.BOOL=8]=`BOOL`,e[e.STRING=9]=`STRING`,e[e.BYTES=12]=`BYTES`,e[e.UINT32=13]=`UINT32`,e[e.SFIXED32=15]=`SFIXED32`,e[e.SFIXED64=16]=`SFIXED64`,e[e.SINT32=17]=`SINT32`,e[e.SINT64=18]=`SINT64`})(k||={});var Br;(function(e){e[e.BIGINT=0]=`BIGINT`,e[e.STRING=1]=`STRING`})(Br||={});function Vr(e,t,n){if(t===n)return!0;if(e==k.BYTES){if(!(t instanceof Uint8Array)||!(n instanceof Uint8Array)||t.length!==n.length)return!1;for(let e=0;e<t.length;e++)if(t[e]!==n[e])return!1;return!0}switch(e){case k.UINT64:case k.FIXED64:case k.INT64:case k.SFIXED64:case k.SINT64:return t==n}return!1}function Hr(e,t){switch(e){case k.BOOL:return!1;case k.UINT64:case k.FIXED64:case k.INT64:case k.SFIXED64:case k.SINT64:return t==0?O.zero:`0`;case k.DOUBLE:case k.FLOAT:return 0;case k.BYTES:return new Uint8Array;case k.STRING:return``;default:return 0}}function Ur(e,t){switch(e){case k.BOOL:return t===!1;case k.STRING:return t===``;case k.BYTES:return t instanceof Uint8Array&&!t.byteLength;default:return t==0}}var Wr;(function(e){e[e.Varint=0]=`Varint`,e[e.Bit64=1]=`Bit64`,e[e.LengthDelimited=2]=`LengthDelimited`,e[e.StartGroup=3]=`StartGroup`,e[e.EndGroup=4]=`EndGroup`,e[e.Bit32=5]=`Bit32`})(Wr||={});var Gr=class{constructor(e){this.stack=[],this.textEncoder=e??new TextEncoder,this.chunks=[],this.buf=[]}finish(){this.chunks.push(new Uint8Array(this.buf));let e=0;for(let t=0;t<this.chunks.length;t++)e+=this.chunks[t].length;let t=new Uint8Array(e),n=0;for(let e=0;e<this.chunks.length;e++)t.set(this.chunks[e],n),n+=this.chunks[e].length;return this.chunks=[],t}fork(){return this.stack.push({chunks:this.chunks,buf:this.buf}),this.chunks=[],this.buf=[],this}join(){let e=this.finish(),t=this.stack.pop();if(!t)throw Error(`invalid state, fork stack empty`);return this.chunks=t.chunks,this.buf=t.buf,this.uint32(e.byteLength),this.raw(e)}tag(e,t){return this.uint32((e<<3|t)>>>0)}raw(e){return this.buf.length&&(this.chunks.push(new Uint8Array(this.buf)),this.buf=[]),this.chunks.push(e),this}uint32(e){for(_r(e);e>127;)this.buf.push(e&127|128),e>>>=7;return this.buf.push(e),this}int32(e){return gr(e),Lr(e,this.buf),this}bool(e){return this.buf.push(e?1:0),this}bytes(e){return this.uint32(e.byteLength),this.raw(e)}string(e){let t=this.textEncoder.encode(e);return this.uint32(t.byteLength),this.raw(t)}float(e){vr(e);let t=new Uint8Array(4);return new DataView(t.buffer).setFloat32(0,e,!0),this.raw(t)}double(e){let t=new Uint8Array(8);return new DataView(t.buffer).setFloat64(0,e,!0),this.raw(t)}fixed32(e){_r(e);let t=new Uint8Array(4);return new DataView(t.buffer).setUint32(0,e,!0),this.raw(t)}sfixed32(e){gr(e);let t=new Uint8Array(4);return new DataView(t.buffer).setInt32(0,e,!0),this.raw(t)}sint32(e){return gr(e),e=(e<<1^e>>31)>>>0,Lr(e,this.buf),this}sfixed64(e){let t=new Uint8Array(8),n=new DataView(t.buffer),r=O.enc(e);return n.setInt32(0,r.lo,!0),n.setInt32(4,r.hi,!0),this.raw(t)}fixed64(e){let t=new Uint8Array(8),n=new DataView(t.buffer),r=O.uEnc(e);return n.setInt32(0,r.lo,!0),n.setInt32(4,r.hi,!0),this.raw(t)}int64(e){let t=O.enc(e);return Or(t.lo,t.hi,this.buf),this}sint64(e){let t=O.enc(e),n=t.hi>>31;return Or(t.lo<<1^n,(t.hi<<1|t.lo>>>31)^n,this.buf),this}uint64(e){let t=O.uEnc(e);return Or(t.lo,t.hi,this.buf),this}},Kr=class{constructor(e,t){this.varint64=Dr,this.uint32=Rr,this.buf=e,this.len=e.length,this.pos=0,this.view=new DataView(e.buffer,e.byteOffset,e.byteLength),this.textDecoder=t??new TextDecoder}tag(){let e=this.uint32(),t=e>>>3,n=e&7;if(t<=0||n<0||n>5)throw Error(`illegal tag: field no `+t+` wire type `+n);return[t,n]}skip(e,t){let n=this.pos;switch(e){case Wr.Varint:for(;this.buf[this.pos++]&128;);break;case Wr.Bit64:this.pos+=4;case Wr.Bit32:this.pos+=4;break;case Wr.LengthDelimited:let n=this.uint32();this.pos+=n;break;case Wr.StartGroup:for(;;){let[e,n]=this.tag();if(n===Wr.EndGroup){if(t!==void 0&&e!==t)throw Error(`invalid end group tag`);break}this.skip(n,e)}break;default:throw Error(`cant skip wire type `+e)}return this.assertBounds(),this.buf.subarray(n,this.pos)}assertBounds(){if(this.pos>this.len)throw RangeError(`premature EOF`)}int32(){return this.uint32()|0}sint32(){let e=this.uint32();return e>>>1^-(e&1)}int64(){return O.dec(...this.varint64())}uint64(){return O.uDec(...this.varint64())}sint64(){let[e,t]=this.varint64(),n=-(e&1);return e=(e>>>1|(t&1)<<31)^n,t=t>>>1^n,O.dec(e,t)}bool(){let[e,t]=this.varint64();return e!==0||t!==0}fixed32(){return this.view.getUint32((this.pos+=4)-4,!0)}sfixed32(){return this.view.getInt32((this.pos+=4)-4,!0)}fixed64(){return O.uDec(this.sfixed32(),this.sfixed32())}sfixed64(){return O.dec(this.sfixed32(),this.sfixed32())}float(){return this.view.getFloat32((this.pos+=4)-4,!0)}double(){return this.view.getFloat64((this.pos+=8)-8,!0)}bytes(){let e=this.uint32(),t=this.pos;return this.pos+=e,this.assertBounds(),this.buf.subarray(t,t+e)}string(){return this.textDecoder.decode(this.bytes())}};function qr(e,t,n,r){let i;return{typeName:t,extendee:n,get field(){if(!i){let n=typeof r==`function`?r():r;n.name=t.split(`.`).pop(),n.jsonName=`[${t}]`,i=e.util.newFieldList([n]).list()[0]}return i},runtime:e}}function Jr(e){let t=e.field.localName,n=Object.create(null);return n[t]=Yr(e),[n,()=>n[t]]}function Yr(e){let t=e.field;if(t.repeated)return[];if(t.default!==void 0)return t.default;switch(t.kind){case`enum`:return t.T.values[0].no;case`scalar`:return Hr(t.T,t.L);case`message`:let e=t.T,n=new e;return e.fieldWrapper?e.fieldWrapper.unwrapField(n):n;case`map`:throw`map fields are not allowed to be extensions`}}function Xr(e,t){if(!t.repeated&&(t.kind==`enum`||t.kind==`scalar`)){for(let n=e.length-1;n>=0;--n)if(e[n].no==t.no)return[e[n]];return[]}return e.filter(e=>e.no===t.no)}var Zr=`ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/`.split(``),Qr=[];for(let e=0;e<Zr.length;e++)Qr[Zr[e].charCodeAt(0)]=e;Qr[45]=Zr.indexOf(`+`),Qr[95]=Zr.indexOf(`/`);var $r={dec(e){let t=e.length*3/4;e[e.length-2]==`=`?t-=2:e[e.length-1]==`=`&&--t;let n=new Uint8Array(t),r=0,i=0,a,o=0;for(let t=0;t<e.length;t++){if(a=Qr[e.charCodeAt(t)],a===void 0)switch(e[t]){case`=`:i=0;case`
|
|
31
|
+
`:case`\r`:case` `:case` `:continue;default:throw Error(`invalid base64 string.`)}switch(i){case 0:o=a,i=1;break;case 1:n[r++]=o<<2|(a&48)>>4,o=a,i=2;break;case 2:n[r++]=(o&15)<<4|(a&60)>>2,o=a,i=3;break;case 3:n[r++]=(o&3)<<6|a,i=0;break}}if(i==1)throw Error(`invalid base64 string.`);return n.subarray(0,r)},enc(e){let t=``,n=0,r,i=0;for(let a=0;a<e.length;a++)switch(r=e[a],n){case 0:t+=Zr[r>>2],i=(r&3)<<4,n=1;break;case 1:t+=Zr[i|r>>4],i=(r&15)<<2,n=2;break;case 2:t+=Zr[i|r>>6],t+=Zr[r&63],n=0;break}return n&&(t+=Zr[i],t+=`=`,n==1&&(t+=`=`)),t}};function ei(e,t,n){ri(t,e);let r=t.runtime.bin.makeReadOptions(n),i=Xr(e.getType().runtime.bin.listUnknownFields(e),t.field),[a,o]=Jr(t);for(let e of i)t.runtime.bin.readField(a,r.readerFactory(e.data),t.field,e.wireType,r);return o()}function ti(e,t,n,r){ri(t,e);let i=t.runtime.bin.makeReadOptions(r),a=t.runtime.bin.makeWriteOptions(r);if(ni(e,t)){let n=e.getType().runtime.bin.listUnknownFields(e).filter(e=>e.no!=t.field.no);e.getType().runtime.bin.discardUnknownFields(e);for(let t of n)e.getType().runtime.bin.onUnknownField(e,t.no,t.wireType,t.data)}let o=a.writerFactory(),s=t.field;!s.opt&&!s.repeated&&(s.kind==`enum`||s.kind==`scalar`)&&(s=Object.assign(Object.assign({},t.field),{opt:!0})),t.runtime.bin.writeField(s,n,o,a);let c=i.readerFactory(o.finish());for(;c.pos<c.len;){let[t,n]=c.tag(),r=c.skip(n,t);e.getType().runtime.bin.onUnknownField(e,t,n,r)}}function ni(e,t){let n=e.getType();return t.extendee.typeName===n.typeName&&!!n.runtime.bin.listUnknownFields(e).find(e=>e.no==t.field.no)}function ri(e,t){D(e.extendee.typeName==t.getType().typeName,`extension ${e.typeName} can only be applied to message ${e.extendee.typeName}`)}function ii(e,t){let n=e.localName;if(e.repeated)return t[n].length>0;if(e.oneof)return t[e.oneof.localName].case===n;switch(e.kind){case`enum`:case`scalar`:return e.opt||e.req?t[n]!==void 0:e.kind==`enum`?t[n]!==e.T.values[0].no:!Ur(e.T,t[n]);case`message`:return t[n]!==void 0;case`map`:return Object.keys(t[n]).length>0}}function ai(e,t){let n=e.localName,r=!e.opt&&!e.req;if(e.repeated)t[n]=[];else if(e.oneof)t[e.oneof.localName]={case:void 0};else switch(e.kind){case`map`:t[n]={};break;case`enum`:t[n]=r?e.T.values[0].no:void 0;break;case`scalar`:t[n]=r?Hr(e.T,e.L):void 0;break;case`message`:t[n]=void 0;break}}function oi(e,t){if(typeof e!=`object`||!e||!Object.getOwnPropertyNames(Tr.prototype).every(t=>t in e&&typeof e[t]==`function`))return!1;let n=e.getType();return n===null||typeof n!=`function`||!(`typeName`in n)||typeof n.typeName!=`string`?!1:t===void 0?!0:n.typeName==t.typeName}function si(e,t){return oi(t)||!e.fieldWrapper?t:e.fieldWrapper.wrapField(t)}k.DOUBLE,k.FLOAT,k.INT64,k.UINT64,k.INT32,k.UINT32,k.BOOL,k.STRING,k.BYTES;var ci={ignoreUnknownFields:!1},li={emitDefaultValues:!1,enumAsInteger:!1,useProtoFieldName:!1,prettySpaces:0};function ui(e){return e?Object.assign(Object.assign({},ci),e):ci}function di(e){return e?Object.assign(Object.assign({},li),e):li}var fi=Symbol(),pi=Symbol();function mi(){return{makeReadOptions:ui,makeWriteOptions:di,readMessage(e,t,n,r){if(t==null||Array.isArray(t)||typeof t!=`object`)throw Error(`cannot decode message ${e.typeName} from JSON: ${hi(t)}`);r??=new e;let i=new Map,a=n.typeRegistry;for(let[o,s]of Object.entries(t)){let t=e.fields.findJsonName(o);if(t){if(t.oneof){if(s===null&&t.kind==`scalar`)continue;let n=i.get(t.oneof);if(n!==void 0)throw Error(`cannot decode message ${e.typeName} from JSON: multiple keys for oneof "${t.oneof.name}" present: "${n}", "${o}"`);i.set(t.oneof,o)}gi(r,s,t,n,e)}else{let t=!1;if(a?.findExtension&&o.startsWith(`[`)&&o.endsWith(`]`)){let i=a.findExtension(o.substring(1,o.length-1));if(i&&i.extendee.typeName==e.typeName){t=!0;let[e,a]=Jr(i);gi(e,s,i.field,n,i),ti(r,i,a(),n)}}if(!t&&!n.ignoreUnknownFields)throw Error(`cannot decode message ${e.typeName} from JSON: key "${o}" is unknown`)}}return r},writeMessage(e,t){let n=e.getType(),r={},i;try{for(i of n.fields.byNumber()){if(!ii(i,e)){if(i.req)throw`required field not set`;if(!t.emitDefaultValues||!bi(i))continue}let n=i.oneof?e[i.oneof.localName].value:e[i.localName],a=xi(i,n,t);a!==void 0&&(r[t.useProtoFieldName?i.name:i.jsonName]=a)}let a=t.typeRegistry;if(a?.findExtensionFor)for(let i of n.runtime.bin.listUnknownFields(e)){let o=a.findExtensionFor(n.typeName,i.no);if(o&&ni(e,o)){let n=ei(e,o,t),i=xi(o.field,n,t);i!==void 0&&(r[o.field.jsonName]=i)}}}catch(e){let t=i?`cannot encode field ${n.typeName}.${i.name} to JSON`:`cannot encode message ${n.typeName} to JSON`,r=e instanceof Error?e.message:String(e);throw Error(t+(r.length>0?`: ${r}`:``))}return r},readScalar(e,t,n){return vi(e,t,n??Br.BIGINT,!0)},writeScalar(e,t,n){if(t!==void 0&&(n||Ur(e,t)))return Ci(e,t)},debug:hi}}function hi(e){if(e===null)return`null`;switch(typeof e){case`object`:return Array.isArray(e)?`array`:`object`;case`string`:return e.length>100?`string`:`"${e.split(`"`).join(`\\"`)}"`;default:return String(e)}}function gi(e,t,n,r,i){let a=n.localName;if(n.repeated){if(D(n.kind!=`map`),t===null)return;if(!Array.isArray(t))throw Error(`cannot decode field ${i.typeName}.${n.name} from JSON: ${hi(t)}`);let o=e[a];for(let e of t){if(e===null)throw Error(`cannot decode field ${i.typeName}.${n.name} from JSON: ${hi(e)}`);switch(n.kind){case`message`:o.push(n.T.fromJson(e,r));break;case`enum`:let t=yi(n.T,e,r.ignoreUnknownFields,!0);t!==pi&&o.push(t);break;case`scalar`:try{o.push(vi(n.T,e,n.L,!0))}catch(t){let r=`cannot decode field ${i.typeName}.${n.name} from JSON: ${hi(e)}`;throw t instanceof Error&&t.message.length>0&&(r+=`: ${t.message}`),Error(r)}break}}}else if(n.kind==`map`){if(t===null)return;if(typeof t!=`object`||Array.isArray(t))throw Error(`cannot decode field ${i.typeName}.${n.name} from JSON: ${hi(t)}`);let o=e[a];for(let[e,a]of Object.entries(t)){if(a===null)throw Error(`cannot decode field ${i.typeName}.${n.name} from JSON: map value null`);let s;try{s=_i(n.K,e)}catch(e){let r=`cannot decode map key for field ${i.typeName}.${n.name} from JSON: ${hi(t)}`;throw e instanceof Error&&e.message.length>0&&(r+=`: ${e.message}`),Error(r)}switch(n.V.kind){case`message`:o[s]=n.V.T.fromJson(a,r);break;case`enum`:let e=yi(n.V.T,a,r.ignoreUnknownFields,!0);e!==pi&&(o[s]=e);break;case`scalar`:try{o[s]=vi(n.V.T,a,Br.BIGINT,!0)}catch(e){let r=`cannot decode map value for field ${i.typeName}.${n.name} from JSON: ${hi(t)}`;throw e instanceof Error&&e.message.length>0&&(r+=`: ${e.message}`),Error(r)}break}}}else switch(n.oneof&&(e=e[n.oneof.localName]={case:a},a=`value`),n.kind){case`message`:let o=n.T;if(t===null&&o.typeName!=`google.protobuf.Value`)return;let s=e[a];oi(s)?s.fromJson(t,r):(e[a]=s=o.fromJson(t,r),o.fieldWrapper&&!n.oneof&&(e[a]=o.fieldWrapper.unwrapField(s)));break;case`enum`:let c=yi(n.T,t,r.ignoreUnknownFields,!1);switch(c){case fi:ai(n,e);break;case pi:break;default:e[a]=c;break}break;case`scalar`:try{let r=vi(n.T,t,n.L,!1);switch(r){case fi:ai(n,e);break;default:e[a]=r;break}}catch(e){let r=`cannot decode field ${i.typeName}.${n.name} from JSON: ${hi(t)}`;throw e instanceof Error&&e.message.length>0&&(r+=`: ${e.message}`),Error(r)}break}}function _i(e,t){if(e===k.BOOL)switch(t){case`true`:t=!0;break;case`false`:t=!1;break}return vi(e,t,Br.BIGINT,!0).toString()}function vi(e,t,n,r){if(t===null)return r?Hr(e,n):fi;switch(e){case k.DOUBLE:case k.FLOAT:if(t===`NaN`)return NaN;if(t===`Infinity`)return 1/0;if(t===`-Infinity`)return-1/0;if(t===``||typeof t==`string`&&t.trim().length!==t.length||typeof t!=`string`&&typeof t!=`number`)break;let r=Number(t);if(Number.isNaN(r)||!Number.isFinite(r))break;return e==k.FLOAT&&vr(r),r;case k.INT32:case k.FIXED32:case k.SFIXED32:case k.SINT32:case k.UINT32:let i;if(typeof t==`number`?i=t:typeof t==`string`&&t.length>0&&t.trim().length===t.length&&(i=Number(t)),i===void 0)break;return e==k.UINT32||e==k.FIXED32?_r(i):gr(i),i;case k.INT64:case k.SFIXED64:case k.SINT64:if(typeof t!=`number`&&typeof t!=`string`)break;let a=O.parse(t);return n?a.toString():a;case k.FIXED64:case k.UINT64:if(typeof t!=`number`&&typeof t!=`string`)break;let o=O.uParse(t);return n?o.toString():o;case k.BOOL:if(typeof t!=`boolean`)break;return t;case k.STRING:if(typeof t!=`string`)break;return t;case k.BYTES:if(t===``)return new Uint8Array;if(typeof t!=`string`)break;return $r.dec(t)}throw Error()}function yi(e,t,n,r){if(t===null)return e.typeName==`google.protobuf.NullValue`?0:r?e.values[0].no:fi;switch(typeof t){case`number`:if(Number.isInteger(t))return t;break;case`string`:let r=e.findName(t);if(r!==void 0)return r.no;if(n)return pi;break}throw Error(`cannot decode enum ${e.typeName} from JSON: ${hi(t)}`)}function bi(e){return e.repeated||e.kind==`map`?!0:!(e.oneof||e.kind==`message`||e.opt||e.req)}function xi(e,t,n){if(e.kind==`map`){D(typeof t==`object`&&!!t);let r={},i=Object.entries(t);switch(e.V.kind){case`scalar`:for(let[t,n]of i)r[t.toString()]=Ci(e.V.T,n);break;case`message`:for(let[e,t]of i)r[e.toString()]=t.toJson(n);break;case`enum`:let t=e.V.T;for(let[e,a]of i)r[e.toString()]=Si(t,a,n.enumAsInteger);break}return n.emitDefaultValues||i.length>0?r:void 0}if(e.repeated){D(Array.isArray(t));let r=[];switch(e.kind){case`scalar`:for(let n=0;n<t.length;n++)r.push(Ci(e.T,t[n]));break;case`enum`:for(let i=0;i<t.length;i++)r.push(Si(e.T,t[i],n.enumAsInteger));break;case`message`:for(let e=0;e<t.length;e++)r.push(t[e].toJson(n));break}return n.emitDefaultValues||r.length>0?r:void 0}switch(e.kind){case`scalar`:return Ci(e.T,t);case`enum`:return Si(e.T,t,n.enumAsInteger);case`message`:return si(e.T,t).toJson(n)}}function Si(e,t,n){return D(typeof t==`number`),e.typeName==`google.protobuf.NullValue`?null:n?t:e.findNumber(t)?.name??t}function Ci(e,t){switch(e){case k.INT32:case k.SFIXED32:case k.SINT32:case k.FIXED32:case k.UINT32:return D(typeof t==`number`),t;case k.FLOAT:case k.DOUBLE:return D(typeof t==`number`),Number.isNaN(t)?`NaN`:t===1/0?`Infinity`:t===-1/0?`-Infinity`:t;case k.STRING:return D(typeof t==`string`),t;case k.BOOL:return D(typeof t==`boolean`),t;case k.UINT64:case k.FIXED64:case k.INT64:case k.SFIXED64:case k.SINT64:return D(typeof t==`bigint`||typeof t==`string`||typeof t==`number`),t.toString();case k.BYTES:return D(t instanceof Uint8Array),$r.enc(t)}}var wi=Symbol(`@bufbuild/protobuf/unknown-fields`),Ti={readUnknownFields:!0,readerFactory:e=>new Kr(e)},Ei={writeUnknownFields:!0,writerFactory:()=>new Gr};function Di(e){return e?Object.assign(Object.assign({},Ti),e):Ti}function Oi(e){return e?Object.assign(Object.assign({},Ei),e):Ei}function ki(){return{makeReadOptions:Di,makeWriteOptions:Oi,listUnknownFields(e){return e[wi]??[]},discardUnknownFields(e){delete e[wi]},writeUnknownFields(e,t){let n=e[wi];if(n)for(let e of n)t.tag(e.no,e.wireType).raw(e.data)},onUnknownField(e,t,n,r){let i=e;Array.isArray(i[wi])||(i[wi]=[]),i[wi].push({no:t,wireType:n,data:r})},readMessage(e,t,n,r,i){let a=e.getType(),o=i?t.len:t.pos+n,s,c;for(;t.pos<o&&([s,c]=t.tag(),!(i===!0&&c==Wr.EndGroup));){let n=a.fields.find(s);if(!n){let n=t.skip(c,s);r.readUnknownFields&&this.onUnknownField(e,s,c,n);continue}Ai(e,t,n,c,r)}if(i&&(c!=Wr.EndGroup||s!==n))throw Error(`invalid end group tag`)},readField:Ai,writeMessage(e,t,n){let r=e.getType();for(let i of r.fields.byNumber()){if(!ii(i,e)){if(i.req)throw Error(`cannot encode field ${r.typeName}.${i.name} to binary: required field not set`);continue}Fi(i,i.oneof?e[i.oneof.localName].value:e[i.localName],t,n)}return n.writeUnknownFields&&this.writeUnknownFields(e,t),t},writeField(e,t,n,r){t!==void 0&&Fi(e,t,n,r)}}}function Ai(e,t,n,r,i){let{repeated:a,localName:o}=n;switch(n.oneof&&(e=e[n.oneof.localName],e.case!=o&&delete e.value,e.case=o,o=`value`),n.kind){case`scalar`:case`enum`:let s=n.kind==`enum`?k.INT32:n.T,c=Pi;if(n.kind==`scalar`&&n.L>0&&(c=Ni),a){let n=e[o];if(r==Wr.LengthDelimited&&s!=k.STRING&&s!=k.BYTES){let e=t.uint32()+t.pos;for(;t.pos<e;)n.push(c(t,s))}else n.push(c(t,s))}else e[o]=c(t,s);break;case`message`:let l=n.T;a?e[o].push(ji(t,new l,i,n)):oi(e[o])?ji(t,e[o],i,n):(e[o]=ji(t,new l,i,n),l.fieldWrapper&&!n.oneof&&!n.repeated&&(e[o]=l.fieldWrapper.unwrapField(e[o])));break;case`map`:let[u,d]=Mi(n,t,i);e[o][u]=d;break}}function ji(e,t,n,r){let i=t.getType().runtime.bin,a=r?.delimited;return i.readMessage(t,e,a?r.no:e.uint32(),n,a),t}function Mi(e,t,n){let r=t.uint32(),i=t.pos+r,a,o;for(;t.pos<i;){let[r]=t.tag();switch(r){case 1:a=Pi(t,e.K);break;case 2:switch(e.V.kind){case`scalar`:o=Pi(t,e.V.T);break;case`enum`:o=t.int32();break;case`message`:o=ji(t,new e.V.T,n,void 0);break}break}}if(a===void 0&&(a=Hr(e.K,Br.BIGINT)),typeof a!=`string`&&typeof a!=`number`&&(a=a.toString()),o===void 0)switch(e.V.kind){case`scalar`:o=Hr(e.V.T,Br.BIGINT);break;case`enum`:o=e.V.T.values[0].no;break;case`message`:o=new e.V.T;break}return[a,o]}function Ni(e,t){let n=Pi(e,t);return typeof n==`bigint`?n.toString():n}function Pi(e,t){switch(t){case k.STRING:return e.string();case k.BOOL:return e.bool();case k.DOUBLE:return e.double();case k.FLOAT:return e.float();case k.INT32:return e.int32();case k.INT64:return e.int64();case k.UINT64:return e.uint64();case k.FIXED64:return e.fixed64();case k.BYTES:return e.bytes();case k.FIXED32:return e.fixed32();case k.SFIXED32:return e.sfixed32();case k.SFIXED64:return e.sfixed64();case k.SINT64:return e.sint64();case k.UINT32:return e.uint32();case k.SINT32:return e.sint32()}}function Fi(e,t,n,r){D(t!==void 0);let i=e.repeated;switch(e.kind){case`scalar`:case`enum`:let a=e.kind==`enum`?k.INT32:e.T;if(i)if(D(Array.isArray(t)),e.packed)zi(n,a,e.no,t);else for(let r of t)Ri(n,a,e.no,r);else Ri(n,a,e.no,t);break;case`message`:if(i){D(Array.isArray(t));for(let i of t)Li(n,r,e,i)}else Li(n,r,e,t);break;case`map`:D(typeof t==`object`&&!!t);for(let[i,a]of Object.entries(t))Ii(n,r,e,i,a);break}}function Ii(e,t,n,r,i){e.tag(n.no,Wr.LengthDelimited),e.fork();let a=r;switch(n.K){case k.INT32:case k.FIXED32:case k.UINT32:case k.SFIXED32:case k.SINT32:a=Number.parseInt(r);break;case k.BOOL:D(r==`true`||r==`false`),a=r==`true`;break}switch(Ri(e,n.K,1,a),n.V.kind){case`scalar`:Ri(e,n.V.T,2,i);break;case`enum`:Ri(e,k.INT32,2,i);break;case`message`:D(i!==void 0),e.tag(2,Wr.LengthDelimited).bytes(i.toBinary(t));break}e.join()}function Li(e,t,n,r){let i=si(n.T,r);n.delimited?e.tag(n.no,Wr.StartGroup).raw(i.toBinary(t)).tag(n.no,Wr.EndGroup):e.tag(n.no,Wr.LengthDelimited).bytes(i.toBinary(t))}function Ri(e,t,n,r){D(r!==void 0);let[i,a]=Bi(t);e.tag(n,i)[a](r)}function zi(e,t,n,r){if(!r.length)return;e.tag(n,Wr.LengthDelimited).fork();let[,i]=Bi(t);for(let t=0;t<r.length;t++)e[i](r[t]);e.join()}function Bi(e){let t=Wr.Varint;switch(e){case k.BYTES:case k.STRING:t=Wr.LengthDelimited;break;case k.DOUBLE:case k.FIXED64:case k.SFIXED64:t=Wr.Bit64;break;case k.FIXED32:case k.SFIXED32:case k.FLOAT:t=Wr.Bit32;break}let n=k[e].toLowerCase();return[t,n]}function Vi(){return{setEnumType:xr,initPartial(e,t){if(e===void 0)return;let n=t.getType();for(let r of n.fields.byMember()){let n=r.localName,i=t,a=e;if(a[n]!=null)switch(r.kind){case`oneof`:let e=a[n].case;if(e===void 0)continue;let t=r.findField(e),o=a[n].value;t&&t.kind==`message`&&!oi(o,t.T)?o=new t.T(o):t&&t.kind===`scalar`&&t.T===k.BYTES&&(o=Ui(o)),i[n]={case:e,value:o};break;case`scalar`:case`enum`:let s=a[n];r.T===k.BYTES&&(s=r.repeated?s.map(Ui):Ui(s)),i[n]=s;break;case`map`:switch(r.V.kind){case`scalar`:case`enum`:if(r.V.T===k.BYTES)for(let[e,t]of Object.entries(a[n]))i[n][e]=Ui(t);else Object.assign(i[n],a[n]);break;case`message`:let e=r.V.T;for(let t of Object.keys(a[n])){let r=a[n][t];e.fieldWrapper||(r=new e(r)),i[n][t]=r}break}break;case`message`:let c=r.T;if(r.repeated)i[n]=a[n].map(e=>oi(e,c)?e:new c(e));else{let e=a[n];c.fieldWrapper?c.typeName===`google.protobuf.BytesValue`?i[n]=Ui(e):i[n]=e:i[n]=oi(e,c)?e:new c(e)}break}}},equals(e,t,n){return t===n?!0:!t||!n?!1:e.fields.byMember().every(e=>{let r=t[e.localName],i=n[e.localName];if(e.repeated){if(r.length!==i.length)return!1;switch(e.kind){case`message`:return r.every((t,n)=>e.T.equals(t,i[n]));case`scalar`:return r.every((t,n)=>Vr(e.T,t,i[n]));case`enum`:return r.every((e,t)=>Vr(k.INT32,e,i[t]))}throw Error(`repeated cannot contain ${e.kind}`)}switch(e.kind){case`message`:let t=r,n=i;return e.T.fieldWrapper&&(t!==void 0&&!oi(t)&&(t=e.T.fieldWrapper.wrapField(t)),n!==void 0&&!oi(n)&&(n=e.T.fieldWrapper.wrapField(n))),e.T.equals(t,n);case`enum`:return Vr(k.INT32,r,i);case`scalar`:return Vr(e.T,r,i);case`oneof`:if(r.case!==i.case)return!1;let a=e.findField(r.case);if(a===void 0)return!0;switch(a.kind){case`message`:return a.T.equals(r.value,i.value);case`enum`:return Vr(k.INT32,r.value,i.value);case`scalar`:return Vr(a.T,r.value,i.value)}throw Error(`oneof cannot contain ${a.kind}`);case`map`:let o=Object.keys(r).concat(Object.keys(i));switch(e.V.kind){case`message`:let t=e.V.T;return o.every(e=>t.equals(r[e],i[e]));case`enum`:return o.every(e=>Vr(k.INT32,r[e],i[e]));case`scalar`:let n=e.V.T;return o.every(e=>Vr(n,r[e],i[e]))}break}})},clone(e){let t=e.getType(),n=new t,r=n;for(let n of t.fields.byMember()){let t=e[n.localName],i;if(n.repeated)i=t.map(Hi);else if(n.kind==`map`){i=r[n.localName];for(let[e,n]of Object.entries(t))i[e]=Hi(n)}else i=n.kind==`oneof`?n.findField(t.case)?{case:t.case,value:Hi(t.value)}:{case:void 0}:Hi(t);r[n.localName]=i}for(let n of t.runtime.bin.listUnknownFields(e))t.runtime.bin.onUnknownField(r,n.no,n.wireType,n.data);return n}}}function Hi(e){if(e===void 0)return e;if(oi(e))return e.clone();if(e instanceof Uint8Array){let t=new Uint8Array(e.byteLength);return t.set(e),t}return e}function Ui(e){return e instanceof Uint8Array?e:new Uint8Array(e)}function Wi(e,t,n){return{syntax:e,json:mi(),bin:ki(),util:Object.assign(Object.assign({},Vi()),{newFieldList:t,initFields:n}),makeMessageType(e,t,n){return Er(this,e,t,n)},makeEnum:Cr,makeEnumType:Sr,getEnumType:br,makeExtension(e,t,n){return qr(this,e,t,n)}}}var Gi=class{constructor(e,t){this._fields=e,this._normalizer=t}findJsonName(e){if(!this.jsonNames){let e={};for(let t of this.list())e[t.jsonName]=e[t.name]=t;this.jsonNames=e}return this.jsonNames[e]}find(e){if(!this.numbers){let e={};for(let t of this.list())e[t.no]=t;this.numbers=e}return this.numbers[e]}list(){return this.all||=this._normalizer(this._fields),this.all}byNumber(){return this.numbersAsc||=this.list().concat().sort((e,t)=>e.no-t.no),this.numbersAsc}byMember(){if(!this.members){this.members=[];let e=this.members,t;for(let n of this.list())n.oneof?n.oneof!==t&&(t=n.oneof,e.push(t)):e.push(n)}return this.members}};function Ki(e,t){let n=Yi(e);return t?n:ea($i(n))}function qi(e){return Ki(e,!1)}var Ji=Yi;function Yi(e){let t=!1,n=[];for(let r=0;r<e.length;r++){let i=e.charAt(r);switch(i){case`_`:t=!0;break;case`0`:case`1`:case`2`:case`3`:case`4`:case`5`:case`6`:case`7`:case`8`:case`9`:n.push(i),t=!1;break;default:t&&(t=!1,i=i.toUpperCase()),n.push(i);break}}return n.join(``)}var Xi=new Set([`constructor`,`toString`,`toJSON`,`valueOf`]),Zi=new Set([`getType`,`clone`,`equals`,`fromBinary`,`fromJson`,`fromJsonString`,`toBinary`,`toJson`,`toJsonString`,`toObject`]),Qi=e=>`${e}\$`,$i=e=>Zi.has(e)?Qi(e):e,ea=e=>Xi.has(e)?Qi(e):e,ta=class{constructor(e){this.kind=`oneof`,this.repeated=!1,this.packed=!1,this.opt=!1,this.req=!1,this.default=void 0,this.fields=[],this.name=e,this.localName=qi(e)}addField(e){D(e.oneof===this,`field ${e.name} not one of ${this.name}`),this.fields.push(e)}findField(e){if(!this._lookup){this._lookup=Object.create(null);for(let e=0;e<this.fields.length;e++)this._lookup[this.fields[e].localName]=this.fields[e]}return this._lookup[e]}};function na(e,t){let n=[],r;for(let t of typeof e==`function`?e():e){let e=t;if(e.localName=Ki(t.name,t.oneof!==void 0),e.jsonName=t.jsonName??Ji(t.name),e.repeated=t.repeated??!1,t.kind==`scalar`&&(e.L=t.L??Br.BIGINT),e.delimited=t.delimited??!1,e.req=t.req??!1,e.opt=t.opt??!1,t.packed===void 0&&(e.packed=t.kind==`enum`||t.kind==`scalar`&&t.T!=k.BYTES&&t.T!=k.STRING),t.oneof!==void 0){let n=typeof t.oneof==`string`?t.oneof:t.oneof.name;(!r||r.name!=n)&&(r=new ta(n)),e.oneof=r,r.addField(e)}n.push(e)}return n}var A=Wi(`proto3`,e=>new Gi(e,e=>na(e)),e=>{for(let t of e.getType().fields.byMember()){if(t.opt)continue;let n=t.localName,r=e;if(t.repeated){r[n]=[];continue}switch(t.kind){case`oneof`:r[n]={case:void 0};break;case`enum`:r[n]=0;break;case`map`:r[n]={};break;case`scalar`:r[n]=Hr(t.T,t.L);break}}}),ra=class e extends Tr{constructor(e){super(),this.seconds=O.zero,this.nanos=0,A.util.initPartial(e,this)}fromJson(e,t){if(typeof e!=`string`)throw Error(`cannot decode google.protobuf.Timestamp from JSON: ${A.json.debug(e)}`);let n=e.match(/^([0-9]{4})-([0-9]{2})-([0-9]{2})T([0-9]{2}):([0-9]{2}):([0-9]{2})(?:Z|\.([0-9]{3,9})Z|([+-][0-9][0-9]:[0-9][0-9]))$/);if(!n)throw Error(`cannot decode google.protobuf.Timestamp from JSON: invalid RFC 3339 string`);let r=Date.parse(n[1]+`-`+n[2]+`-`+n[3]+`T`+n[4]+`:`+n[5]+`:`+n[6]+(n[8]?n[8]:`Z`));if(Number.isNaN(r))throw Error(`cannot decode google.protobuf.Timestamp from JSON: invalid RFC 3339 string`);if(r<Date.parse(`0001-01-01T00:00:00Z`)||r>Date.parse(`9999-12-31T23:59:59Z`))throw Error(`cannot decode message google.protobuf.Timestamp from JSON: must be from 0001-01-01T00:00:00Z to 9999-12-31T23:59:59Z inclusive`);return this.seconds=O.parse(r/1e3),this.nanos=0,n[7]&&(this.nanos=parseInt(`1`+n[7]+`0`.repeat(9-n[7].length))-1e9),this}toJson(e){let t=Number(this.seconds)*1e3;if(t<Date.parse(`0001-01-01T00:00:00Z`)||t>Date.parse(`9999-12-31T23:59:59Z`))throw Error(`cannot encode google.protobuf.Timestamp to JSON: must be from 0001-01-01T00:00:00Z to 9999-12-31T23:59:59Z inclusive`);if(this.nanos<0)throw Error(`cannot encode google.protobuf.Timestamp to JSON: nanos must not be negative`);let n=`Z`;if(this.nanos>0){let e=(this.nanos+1e9).toString().substring(1);n=e.substring(3)===`000000`?`.`+e.substring(0,3)+`Z`:e.substring(6)===`000`?`.`+e.substring(0,6)+`Z`:`.`+e+`Z`}return new Date(t).toISOString().replace(`.000Z`,n)}toDate(){return new Date(Number(this.seconds)*1e3+Math.ceil(this.nanos/1e6))}static now(){return e.fromDate(new Date)}static fromDate(t){let n=t.getTime();return new e({seconds:O.parse(Math.floor(n/1e3)),nanos:n%1e3*1e6})}static fromBinary(t,n){return new e().fromBinary(t,n)}static fromJson(t,n){return new e().fromJson(t,n)}static fromJsonString(t,n){return new e().fromJsonString(t,n)}static equals(t,n){return A.util.equals(e,t,n)}};ra.runtime=A,ra.typeName=`google.protobuf.Timestamp`,ra.fields=A.util.newFieldList(()=>[{no:1,name:`seconds`,kind:`scalar`,T:3},{no:2,name:`nanos`,kind:`scalar`,T:5}]);var ia=A.makeMessageType(`livekit.MetricsBatch`,()=>[{no:1,name:`timestamp_ms`,kind:`scalar`,T:3},{no:2,name:`normalized_timestamp`,kind:`message`,T:ra},{no:3,name:`str_data`,kind:`scalar`,T:9,repeated:!0},{no:4,name:`time_series`,kind:`message`,T:aa,repeated:!0},{no:5,name:`events`,kind:`message`,T:sa,repeated:!0}]),aa=A.makeMessageType(`livekit.TimeSeriesMetric`,()=>[{no:1,name:`label`,kind:`scalar`,T:13},{no:2,name:`participant_identity`,kind:`scalar`,T:13},{no:3,name:`track_sid`,kind:`scalar`,T:13},{no:4,name:`samples`,kind:`message`,T:oa,repeated:!0},{no:5,name:`rid`,kind:`scalar`,T:13}]),oa=A.makeMessageType(`livekit.MetricSample`,()=>[{no:1,name:`timestamp_ms`,kind:`scalar`,T:3},{no:2,name:`normalized_timestamp`,kind:`message`,T:ra},{no:3,name:`value`,kind:`scalar`,T:2}]),sa=A.makeMessageType(`livekit.EventMetric`,()=>[{no:1,name:`label`,kind:`scalar`,T:13},{no:2,name:`participant_identity`,kind:`scalar`,T:13},{no:3,name:`track_sid`,kind:`scalar`,T:13},{no:4,name:`start_timestamp_ms`,kind:`scalar`,T:3},{no:5,name:`end_timestamp_ms`,kind:`scalar`,T:3,opt:!0},{no:6,name:`normalized_start_timestamp`,kind:`message`,T:ra},{no:7,name:`normalized_end_timestamp`,kind:`message`,T:ra,opt:!0},{no:8,name:`metadata`,kind:`scalar`,T:9},{no:9,name:`rid`,kind:`scalar`,T:13}]),ca=A.makeEnum(`livekit.BackupCodecPolicy`,[{no:0,name:`PREFER_REGRESSION`},{no:1,name:`SIMULCAST`},{no:2,name:`REGRESSION`}]),la=A.makeEnum(`livekit.TrackType`,[{no:0,name:`AUDIO`},{no:1,name:`VIDEO`},{no:2,name:`DATA`}]),ua=A.makeEnum(`livekit.TrackSource`,[{no:0,name:`UNKNOWN`},{no:1,name:`CAMERA`},{no:2,name:`MICROPHONE`},{no:3,name:`SCREEN_SHARE`},{no:4,name:`SCREEN_SHARE_AUDIO`}]),da=A.makeEnum(`livekit.VideoQuality`,[{no:0,name:`LOW`},{no:1,name:`MEDIUM`},{no:2,name:`HIGH`},{no:3,name:`OFF`}]),fa=A.makeEnum(`livekit.ConnectionQuality`,[{no:0,name:`POOR`},{no:1,name:`GOOD`},{no:2,name:`EXCELLENT`},{no:3,name:`LOST`}]),pa=A.makeEnum(`livekit.ClientConfigSetting`,[{no:0,name:`UNSET`},{no:1,name:`DISABLED`},{no:2,name:`ENABLED`}]),ma=A.makeEnum(`livekit.DisconnectReason`,[{no:0,name:`UNKNOWN_REASON`},{no:1,name:`CLIENT_INITIATED`},{no:2,name:`DUPLICATE_IDENTITY`},{no:3,name:`SERVER_SHUTDOWN`},{no:4,name:`PARTICIPANT_REMOVED`},{no:5,name:`ROOM_DELETED`},{no:6,name:`STATE_MISMATCH`},{no:7,name:`JOIN_FAILURE`},{no:8,name:`MIGRATION`},{no:9,name:`SIGNAL_CLOSE`},{no:10,name:`ROOM_CLOSED`},{no:11,name:`USER_UNAVAILABLE`},{no:12,name:`USER_REJECTED`},{no:13,name:`SIP_TRUNK_FAILURE`},{no:14,name:`CONNECTION_TIMEOUT`},{no:15,name:`MEDIA_FAILURE`}]),ha=A.makeEnum(`livekit.ReconnectReason`,[{no:0,name:`RR_UNKNOWN`},{no:1,name:`RR_SIGNAL_DISCONNECTED`},{no:2,name:`RR_PUBLISHER_FAILED`},{no:3,name:`RR_SUBSCRIBER_FAILED`},{no:4,name:`RR_SWITCH_CANDIDATE`}]),ga=A.makeEnum(`livekit.SubscriptionError`,[{no:0,name:`SE_UNKNOWN`},{no:1,name:`SE_CODEC_UNSUPPORTED`},{no:2,name:`SE_TRACK_NOTFOUND`}]),_a=A.makeEnum(`livekit.AudioTrackFeature`,[{no:0,name:`TF_STEREO`},{no:1,name:`TF_NO_DTX`},{no:2,name:`TF_AUTO_GAIN_CONTROL`},{no:3,name:`TF_ECHO_CANCELLATION`},{no:4,name:`TF_NOISE_SUPPRESSION`},{no:5,name:`TF_ENHANCED_NOISE_CANCELLATION`},{no:6,name:`TF_PRECONNECT_BUFFER`}]),va=A.makeMessageType(`livekit.Room`,()=>[{no:1,name:`sid`,kind:`scalar`,T:9},{no:2,name:`name`,kind:`scalar`,T:9},{no:3,name:`empty_timeout`,kind:`scalar`,T:13},{no:14,name:`departure_timeout`,kind:`scalar`,T:13},{no:4,name:`max_participants`,kind:`scalar`,T:13},{no:5,name:`creation_time`,kind:`scalar`,T:3},{no:15,name:`creation_time_ms`,kind:`scalar`,T:3},{no:6,name:`turn_password`,kind:`scalar`,T:9},{no:7,name:`enabled_codecs`,kind:`message`,T:ya,repeated:!0},{no:8,name:`metadata`,kind:`scalar`,T:9},{no:9,name:`num_participants`,kind:`scalar`,T:13},{no:11,name:`num_publishers`,kind:`scalar`,T:13},{no:10,name:`active_recording`,kind:`scalar`,T:8},{no:13,name:`version`,kind:`message`,T:eo}]),ya=A.makeMessageType(`livekit.Codec`,()=>[{no:1,name:`mime`,kind:`scalar`,T:9},{no:2,name:`fmtp_line`,kind:`scalar`,T:9}]),ba=A.makeMessageType(`livekit.ParticipantPermission`,()=>[{no:1,name:`can_subscribe`,kind:`scalar`,T:8},{no:2,name:`can_publish`,kind:`scalar`,T:8},{no:3,name:`can_publish_data`,kind:`scalar`,T:8},{no:9,name:`can_publish_sources`,kind:`enum`,T:A.getEnumType(ua),repeated:!0},{no:7,name:`hidden`,kind:`scalar`,T:8},{no:8,name:`recorder`,kind:`scalar`,T:8},{no:10,name:`can_update_metadata`,kind:`scalar`,T:8},{no:11,name:`agent`,kind:`scalar`,T:8},{no:12,name:`can_subscribe_metrics`,kind:`scalar`,T:8}]),xa=A.makeMessageType(`livekit.ParticipantInfo`,()=>[{no:1,name:`sid`,kind:`scalar`,T:9},{no:2,name:`identity`,kind:`scalar`,T:9},{no:3,name:`state`,kind:`enum`,T:A.getEnumType(Sa)},{no:4,name:`tracks`,kind:`message`,T:Ea,repeated:!0},{no:5,name:`metadata`,kind:`scalar`,T:9},{no:6,name:`joined_at`,kind:`scalar`,T:3},{no:17,name:`joined_at_ms`,kind:`scalar`,T:3},{no:9,name:`name`,kind:`scalar`,T:9},{no:10,name:`version`,kind:`scalar`,T:13},{no:11,name:`permission`,kind:`message`,T:ba},{no:12,name:`region`,kind:`scalar`,T:9},{no:13,name:`is_publisher`,kind:`scalar`,T:8},{no:14,name:`kind`,kind:`enum`,T:A.getEnumType(Ca)},{no:15,name:`attributes`,kind:`map`,K:9,V:{kind:`scalar`,T:9}},{no:16,name:`disconnect_reason`,kind:`enum`,T:A.getEnumType(ma)},{no:18,name:`kind_details`,kind:`enum`,T:A.getEnumType(wa),repeated:!0},{no:19,name:`data_tracks`,kind:`message`,T:Da,repeated:!0}]),Sa=A.makeEnum(`livekit.ParticipantInfo.State`,[{no:0,name:`JOINING`},{no:1,name:`JOINED`},{no:2,name:`ACTIVE`},{no:3,name:`DISCONNECTED`}]),Ca=A.makeEnum(`livekit.ParticipantInfo.Kind`,[{no:0,name:`STANDARD`},{no:1,name:`INGRESS`},{no:2,name:`EGRESS`},{no:3,name:`SIP`},{no:4,name:`AGENT`},{no:7,name:`CONNECTOR`},{no:8,name:`BRIDGE`}]),wa=A.makeEnum(`livekit.ParticipantInfo.KindDetail`,[{no:0,name:`CLOUD_AGENT`},{no:1,name:`FORWARDED`},{no:2,name:`CONNECTOR_WHATSAPP`},{no:3,name:`CONNECTOR_TWILIO`},{no:4,name:`BRIDGE_RTSP`}]),j=A.makeEnum(`livekit.Encryption.Type`,[{no:0,name:`NONE`},{no:1,name:`GCM`},{no:2,name:`CUSTOM`}]),Ta=A.makeMessageType(`livekit.SimulcastCodecInfo`,()=>[{no:1,name:`mime_type`,kind:`scalar`,T:9},{no:2,name:`mid`,kind:`scalar`,T:9},{no:3,name:`cid`,kind:`scalar`,T:9},{no:4,name:`layers`,kind:`message`,T:ka,repeated:!0},{no:5,name:`video_layer_mode`,kind:`enum`,T:A.getEnumType(Aa)},{no:6,name:`sdp_cid`,kind:`scalar`,T:9}]),Ea=A.makeMessageType(`livekit.TrackInfo`,()=>[{no:1,name:`sid`,kind:`scalar`,T:9},{no:2,name:`type`,kind:`enum`,T:A.getEnumType(la)},{no:3,name:`name`,kind:`scalar`,T:9},{no:4,name:`muted`,kind:`scalar`,T:8},{no:5,name:`width`,kind:`scalar`,T:13},{no:6,name:`height`,kind:`scalar`,T:13},{no:7,name:`simulcast`,kind:`scalar`,T:8},{no:8,name:`disable_dtx`,kind:`scalar`,T:8},{no:9,name:`source`,kind:`enum`,T:A.getEnumType(ua)},{no:10,name:`layers`,kind:`message`,T:ka,repeated:!0},{no:11,name:`mime_type`,kind:`scalar`,T:9},{no:12,name:`mid`,kind:`scalar`,T:9},{no:13,name:`codecs`,kind:`message`,T:Ta,repeated:!0},{no:14,name:`stereo`,kind:`scalar`,T:8},{no:15,name:`disable_red`,kind:`scalar`,T:8},{no:16,name:`encryption`,kind:`enum`,T:A.getEnumType(j)},{no:17,name:`stream`,kind:`scalar`,T:9},{no:18,name:`version`,kind:`message`,T:eo},{no:19,name:`audio_features`,kind:`enum`,T:A.getEnumType(_a),repeated:!0},{no:20,name:`backup_codec_policy`,kind:`enum`,T:A.getEnumType(ca)}]),Da=A.makeMessageType(`livekit.DataTrackInfo`,()=>[{no:1,name:`pub_handle`,kind:`scalar`,T:13},{no:2,name:`sid`,kind:`scalar`,T:9},{no:3,name:`name`,kind:`scalar`,T:9},{no:4,name:`encryption`,kind:`enum`,T:A.getEnumType(j)}]),Oa=A.makeMessageType(`livekit.DataTrackSubscriptionOptions`,()=>[{no:1,name:`target_fps`,kind:`scalar`,T:13,opt:!0}]),ka=A.makeMessageType(`livekit.VideoLayer`,()=>[{no:1,name:`quality`,kind:`enum`,T:A.getEnumType(da)},{no:2,name:`width`,kind:`scalar`,T:13},{no:3,name:`height`,kind:`scalar`,T:13},{no:4,name:`bitrate`,kind:`scalar`,T:13},{no:5,name:`ssrc`,kind:`scalar`,T:13},{no:6,name:`spatial_layer`,kind:`scalar`,T:5},{no:7,name:`rid`,kind:`scalar`,T:9},{no:8,name:`repair_ssrc`,kind:`scalar`,T:13}]),Aa=A.makeEnum(`livekit.VideoLayer.Mode`,[{no:0,name:`MODE_UNUSED`},{no:1,name:`ONE_SPATIAL_LAYER_PER_STREAM`},{no:2,name:`MULTIPLE_SPATIAL_LAYERS_PER_STREAM`},{no:3,name:`ONE_SPATIAL_LAYER_PER_STREAM_INCOMPLETE_RTCP_SR`}]),ja=A.makeMessageType(`livekit.DataPacket`,()=>[{no:1,name:`kind`,kind:`enum`,T:A.getEnumType(Ma)},{no:4,name:`participant_identity`,kind:`scalar`,T:9},{no:5,name:`destination_identities`,kind:`scalar`,T:9,repeated:!0},{no:2,name:`user`,kind:`message`,T:La,oneof:`value`},{no:3,name:`speaker`,kind:`message`,T:Fa,oneof:`value`},{no:6,name:`sip_dtmf`,kind:`message`,T:Ra,oneof:`value`},{no:7,name:`transcription`,kind:`message`,T:za,oneof:`value`},{no:8,name:`metrics`,kind:`message`,T:ia,oneof:`value`},{no:9,name:`chat_message`,kind:`message`,T:Va,oneof:`value`},{no:10,name:`rpc_request`,kind:`message`,T:Ha,oneof:`value`},{no:11,name:`rpc_ack`,kind:`message`,T:Ua,oneof:`value`},{no:12,name:`rpc_response`,kind:`message`,T:Wa,oneof:`value`},{no:13,name:`stream_header`,kind:`message`,T:io,oneof:`value`},{no:14,name:`stream_chunk`,kind:`message`,T:ao,oneof:`value`},{no:15,name:`stream_trailer`,kind:`message`,T:oo,oneof:`value`},{no:18,name:`encrypted_packet`,kind:`message`,T:Na,oneof:`value`},{no:16,name:`sequence`,kind:`scalar`,T:13},{no:17,name:`participant_sid`,kind:`scalar`,T:9}]),Ma=A.makeEnum(`livekit.DataPacket.Kind`,[{no:0,name:`RELIABLE`},{no:1,name:`LOSSY`}]),Na=A.makeMessageType(`livekit.EncryptedPacket`,()=>[{no:1,name:`encryption_type`,kind:`enum`,T:A.getEnumType(j)},{no:2,name:`iv`,kind:`scalar`,T:12},{no:3,name:`key_index`,kind:`scalar`,T:13},{no:4,name:`encrypted_value`,kind:`scalar`,T:12}]),Pa=A.makeMessageType(`livekit.EncryptedPacketPayload`,()=>[{no:1,name:`user`,kind:`message`,T:La,oneof:`value`},{no:3,name:`chat_message`,kind:`message`,T:Va,oneof:`value`},{no:4,name:`rpc_request`,kind:`message`,T:Ha,oneof:`value`},{no:5,name:`rpc_ack`,kind:`message`,T:Ua,oneof:`value`},{no:6,name:`rpc_response`,kind:`message`,T:Wa,oneof:`value`},{no:7,name:`stream_header`,kind:`message`,T:io,oneof:`value`},{no:8,name:`stream_chunk`,kind:`message`,T:ao,oneof:`value`},{no:9,name:`stream_trailer`,kind:`message`,T:oo,oneof:`value`}]),Fa=A.makeMessageType(`livekit.ActiveSpeakerUpdate`,()=>[{no:1,name:`speakers`,kind:`message`,T:Ia,repeated:!0}]),Ia=A.makeMessageType(`livekit.SpeakerInfo`,()=>[{no:1,name:`sid`,kind:`scalar`,T:9},{no:2,name:`level`,kind:`scalar`,T:2},{no:3,name:`active`,kind:`scalar`,T:8}]),La=A.makeMessageType(`livekit.UserPacket`,()=>[{no:1,name:`participant_sid`,kind:`scalar`,T:9},{no:5,name:`participant_identity`,kind:`scalar`,T:9},{no:2,name:`payload`,kind:`scalar`,T:12},{no:3,name:`destination_sids`,kind:`scalar`,T:9,repeated:!0},{no:6,name:`destination_identities`,kind:`scalar`,T:9,repeated:!0},{no:4,name:`topic`,kind:`scalar`,T:9,opt:!0},{no:8,name:`id`,kind:`scalar`,T:9,opt:!0},{no:9,name:`start_time`,kind:`scalar`,T:4,opt:!0},{no:10,name:`end_time`,kind:`scalar`,T:4,opt:!0},{no:11,name:`nonce`,kind:`scalar`,T:12}]),Ra=A.makeMessageType(`livekit.SipDTMF`,()=>[{no:3,name:`code`,kind:`scalar`,T:13},{no:4,name:`digit`,kind:`scalar`,T:9}]),za=A.makeMessageType(`livekit.Transcription`,()=>[{no:2,name:`transcribed_participant_identity`,kind:`scalar`,T:9},{no:3,name:`track_id`,kind:`scalar`,T:9},{no:4,name:`segments`,kind:`message`,T:Ba,repeated:!0}]),Ba=A.makeMessageType(`livekit.TranscriptionSegment`,()=>[{no:1,name:`id`,kind:`scalar`,T:9},{no:2,name:`text`,kind:`scalar`,T:9},{no:3,name:`start_time`,kind:`scalar`,T:4},{no:4,name:`end_time`,kind:`scalar`,T:4},{no:5,name:`final`,kind:`scalar`,T:8},{no:6,name:`language`,kind:`scalar`,T:9}]),Va=A.makeMessageType(`livekit.ChatMessage`,()=>[{no:1,name:`id`,kind:`scalar`,T:9},{no:2,name:`timestamp`,kind:`scalar`,T:3},{no:3,name:`edit_timestamp`,kind:`scalar`,T:3,opt:!0},{no:4,name:`message`,kind:`scalar`,T:9},{no:5,name:`deleted`,kind:`scalar`,T:8},{no:6,name:`generated`,kind:`scalar`,T:8}]),Ha=A.makeMessageType(`livekit.RpcRequest`,()=>[{no:1,name:`id`,kind:`scalar`,T:9},{no:2,name:`method`,kind:`scalar`,T:9},{no:3,name:`payload`,kind:`scalar`,T:9},{no:4,name:`response_timeout_ms`,kind:`scalar`,T:13},{no:5,name:`version`,kind:`scalar`,T:13}]),Ua=A.makeMessageType(`livekit.RpcAck`,()=>[{no:1,name:`request_id`,kind:`scalar`,T:9}]),Wa=A.makeMessageType(`livekit.RpcResponse`,()=>[{no:1,name:`request_id`,kind:`scalar`,T:9},{no:2,name:`payload`,kind:`scalar`,T:9,oneof:`value`},{no:3,name:`error`,kind:`message`,T:Ga,oneof:`value`}]),Ga=A.makeMessageType(`livekit.RpcError`,()=>[{no:1,name:`code`,kind:`scalar`,T:13},{no:2,name:`message`,kind:`scalar`,T:9},{no:3,name:`data`,kind:`scalar`,T:9}]),Ka=A.makeMessageType(`livekit.ParticipantTracks`,()=>[{no:1,name:`participant_sid`,kind:`scalar`,T:9},{no:2,name:`track_sids`,kind:`scalar`,T:9,repeated:!0}]),qa=A.makeMessageType(`livekit.ServerInfo`,()=>[{no:1,name:`edition`,kind:`enum`,T:A.getEnumType(Ja)},{no:2,name:`version`,kind:`scalar`,T:9},{no:3,name:`protocol`,kind:`scalar`,T:5},{no:4,name:`region`,kind:`scalar`,T:9},{no:5,name:`node_id`,kind:`scalar`,T:9},{no:6,name:`debug_info`,kind:`scalar`,T:9},{no:7,name:`agent_protocol`,kind:`scalar`,T:5}]),Ja=A.makeEnum(`livekit.ServerInfo.Edition`,[{no:0,name:`Standard`},{no:1,name:`Cloud`}]),Ya=A.makeMessageType(`livekit.ClientInfo`,()=>[{no:1,name:`sdk`,kind:`enum`,T:A.getEnumType(Xa)},{no:2,name:`version`,kind:`scalar`,T:9},{no:3,name:`protocol`,kind:`scalar`,T:5},{no:4,name:`os`,kind:`scalar`,T:9},{no:5,name:`os_version`,kind:`scalar`,T:9},{no:6,name:`device_model`,kind:`scalar`,T:9},{no:7,name:`browser`,kind:`scalar`,T:9},{no:8,name:`browser_version`,kind:`scalar`,T:9},{no:9,name:`address`,kind:`scalar`,T:9},{no:10,name:`network`,kind:`scalar`,T:9},{no:11,name:`other_sdks`,kind:`scalar`,T:9}]),Xa=A.makeEnum(`livekit.ClientInfo.SDK`,[{no:0,name:`UNKNOWN`},{no:1,name:`JS`},{no:2,name:`SWIFT`},{no:3,name:`ANDROID`},{no:4,name:`FLUTTER`},{no:5,name:`GO`},{no:6,name:`UNITY`},{no:7,name:`REACT_NATIVE`},{no:8,name:`RUST`},{no:9,name:`PYTHON`},{no:10,name:`CPP`},{no:11,name:`UNITY_WEB`},{no:12,name:`NODE`},{no:13,name:`UNREAL`},{no:14,name:`ESP32`}]),Za=A.makeMessageType(`livekit.ClientConfiguration`,()=>[{no:1,name:`video`,kind:`message`,T:Qa},{no:2,name:`screen`,kind:`message`,T:Qa},{no:3,name:`resume_connection`,kind:`enum`,T:A.getEnumType(pa)},{no:4,name:`disabled_codecs`,kind:`message`,T:$a},{no:5,name:`force_relay`,kind:`enum`,T:A.getEnumType(pa)}]),Qa=A.makeMessageType(`livekit.VideoConfiguration`,()=>[{no:1,name:`hardware_encoder`,kind:`enum`,T:A.getEnumType(pa)}]),$a=A.makeMessageType(`livekit.DisabledCodecs`,()=>[{no:1,name:`codecs`,kind:`message`,T:ya,repeated:!0},{no:2,name:`publish`,kind:`message`,T:ya,repeated:!0}]),eo=A.makeMessageType(`livekit.TimedVersion`,()=>[{no:1,name:`unix_micro`,kind:`scalar`,T:3},{no:2,name:`ticks`,kind:`scalar`,T:5}]),to=A.makeEnum(`livekit.DataStream.OperationType`,[{no:0,name:`CREATE`},{no:1,name:`UPDATE`},{no:2,name:`DELETE`},{no:3,name:`REACTION`}]),no=A.makeMessageType(`livekit.DataStream.TextHeader`,()=>[{no:1,name:`operation_type`,kind:`enum`,T:A.getEnumType(to)},{no:2,name:`version`,kind:`scalar`,T:5},{no:3,name:`reply_to_stream_id`,kind:`scalar`,T:9},{no:4,name:`attached_stream_ids`,kind:`scalar`,T:9,repeated:!0},{no:5,name:`generated`,kind:`scalar`,T:8}],{localName:`DataStream_TextHeader`}),ro=A.makeMessageType(`livekit.DataStream.ByteHeader`,()=>[{no:1,name:`name`,kind:`scalar`,T:9}],{localName:`DataStream_ByteHeader`}),io=A.makeMessageType(`livekit.DataStream.Header`,()=>[{no:1,name:`stream_id`,kind:`scalar`,T:9},{no:2,name:`timestamp`,kind:`scalar`,T:3},{no:3,name:`topic`,kind:`scalar`,T:9},{no:4,name:`mime_type`,kind:`scalar`,T:9},{no:5,name:`total_length`,kind:`scalar`,T:4,opt:!0},{no:7,name:`encryption_type`,kind:`enum`,T:A.getEnumType(j)},{no:8,name:`attributes`,kind:`map`,K:9,V:{kind:`scalar`,T:9}},{no:9,name:`text_header`,kind:`message`,T:no,oneof:`content_header`},{no:10,name:`byte_header`,kind:`message`,T:ro,oneof:`content_header`}],{localName:`DataStream_Header`}),ao=A.makeMessageType(`livekit.DataStream.Chunk`,()=>[{no:1,name:`stream_id`,kind:`scalar`,T:9},{no:2,name:`chunk_index`,kind:`scalar`,T:4},{no:3,name:`content`,kind:`scalar`,T:12},{no:4,name:`version`,kind:`scalar`,T:5},{no:5,name:`iv`,kind:`scalar`,T:12,opt:!0}],{localName:`DataStream_Chunk`}),oo=A.makeMessageType(`livekit.DataStream.Trailer`,()=>[{no:1,name:`stream_id`,kind:`scalar`,T:9},{no:2,name:`reason`,kind:`scalar`,T:9},{no:3,name:`attributes`,kind:`map`,K:9,V:{kind:`scalar`,T:9}}],{localName:`DataStream_Trailer`}),so=A.makeMessageType(`livekit.SubscribedAudioCodec`,()=>[{no:1,name:`codec`,kind:`scalar`,T:9},{no:2,name:`enabled`,kind:`scalar`,T:8}]),co=A.makeEnum(`livekit.SignalTarget`,[{no:0,name:`PUBLISHER`},{no:1,name:`SUBSCRIBER`}]),lo=A.makeEnum(`livekit.StreamState`,[{no:0,name:`ACTIVE`},{no:1,name:`PAUSED`}]),uo=A.makeEnum(`livekit.CandidateProtocol`,[{no:0,name:`UDP`},{no:1,name:`TCP`},{no:2,name:`TLS`}]),fo=A.makeMessageType(`livekit.SignalRequest`,()=>[{no:1,name:`offer`,kind:`message`,T:Oo,oneof:`message`},{no:2,name:`answer`,kind:`message`,T:Oo,oneof:`message`},{no:3,name:`trickle`,kind:`message`,T:So,oneof:`message`},{no:4,name:`add_track`,kind:`message`,T:ho,oneof:`message`},{no:5,name:`mute`,kind:`message`,T:Co,oneof:`message`},{no:6,name:`subscription`,kind:`message`,T:Ao,oneof:`message`},{no:7,name:`track_setting`,kind:`message`,T:No,oneof:`message`},{no:8,name:`leave`,kind:`message`,T:Io,oneof:`message`},{no:10,name:`update_layers`,kind:`message`,T:Ro,oneof:`message`},{no:11,name:`subscription_permission`,kind:`message`,T:Qo,oneof:`message`},{no:12,name:`sync_state`,kind:`message`,T:ts,oneof:`message`},{no:13,name:`simulate`,kind:`message`,T:is,oneof:`message`},{no:14,name:`ping`,kind:`scalar`,T:3,oneof:`message`},{no:15,name:`update_metadata`,kind:`message`,T:zo,oneof:`message`},{no:16,name:`ping_req`,kind:`message`,T:as,oneof:`message`},{no:17,name:`update_audio_track`,kind:`message`,T:Po,oneof:`message`},{no:18,name:`update_video_track`,kind:`message`,T:Fo,oneof:`message`},{no:19,name:`publish_data_track_request`,kind:`message`,T:go,oneof:`message`},{no:20,name:`unpublish_data_track_request`,kind:`message`,T:vo,oneof:`message`},{no:21,name:`update_data_subscription`,kind:`message`,T:jo,oneof:`message`}]),po=A.makeMessageType(`livekit.SignalResponse`,()=>[{no:1,name:`join`,kind:`message`,T:wo,oneof:`message`},{no:2,name:`answer`,kind:`message`,T:Oo,oneof:`message`},{no:3,name:`offer`,kind:`message`,T:Oo,oneof:`message`},{no:4,name:`trickle`,kind:`message`,T:So,oneof:`message`},{no:5,name:`update`,kind:`message`,T:ko,oneof:`message`},{no:6,name:`track_published`,kind:`message`,T:Eo,oneof:`message`},{no:8,name:`leave`,kind:`message`,T:Io,oneof:`message`},{no:9,name:`mute`,kind:`message`,T:Co,oneof:`message`},{no:10,name:`speakers_changed`,kind:`message`,T:Vo,oneof:`message`},{no:11,name:`room_update`,kind:`message`,T:Ho,oneof:`message`},{no:12,name:`connection_quality`,kind:`message`,T:Wo,oneof:`message`},{no:13,name:`stream_state_update`,kind:`message`,T:Ko,oneof:`message`},{no:14,name:`subscribed_quality_update`,kind:`message`,T:Yo,oneof:`message`},{no:15,name:`subscription_permission_update`,kind:`message`,T:$o,oneof:`message`},{no:16,name:`refresh_token`,kind:`scalar`,T:9,oneof:`message`},{no:17,name:`track_unpublished`,kind:`message`,T:Do,oneof:`message`},{no:18,name:`pong`,kind:`scalar`,T:3,oneof:`message`},{no:19,name:`reconnect`,kind:`message`,T:To,oneof:`message`},{no:20,name:`pong_resp`,kind:`message`,T:os,oneof:`message`},{no:21,name:`subscription_response`,kind:`message`,T:ls,oneof:`message`},{no:22,name:`request_response`,kind:`message`,T:us,oneof:`message`},{no:23,name:`track_subscribed`,kind:`message`,T:fs,oneof:`message`},{no:24,name:`room_moved`,kind:`message`,T:es,oneof:`message`},{no:25,name:`media_sections_requirement`,kind:`message`,T:_s,oneof:`message`},{no:26,name:`subscribed_audio_codec_update`,kind:`message`,T:Xo,oneof:`message`},{no:27,name:`publish_data_track_response`,kind:`message`,T:_o,oneof:`message`},{no:28,name:`unpublish_data_track_response`,kind:`message`,T:yo,oneof:`message`},{no:29,name:`data_track_subscriber_handles`,kind:`message`,T:bo,oneof:`message`}]),mo=A.makeMessageType(`livekit.SimulcastCodec`,()=>[{no:1,name:`codec`,kind:`scalar`,T:9},{no:2,name:`cid`,kind:`scalar`,T:9},{no:4,name:`layers`,kind:`message`,T:ka,repeated:!0},{no:5,name:`video_layer_mode`,kind:`enum`,T:A.getEnumType(Aa)}]),ho=A.makeMessageType(`livekit.AddTrackRequest`,()=>[{no:1,name:`cid`,kind:`scalar`,T:9},{no:2,name:`name`,kind:`scalar`,T:9},{no:3,name:`type`,kind:`enum`,T:A.getEnumType(la)},{no:4,name:`width`,kind:`scalar`,T:13},{no:5,name:`height`,kind:`scalar`,T:13},{no:6,name:`muted`,kind:`scalar`,T:8},{no:7,name:`disable_dtx`,kind:`scalar`,T:8},{no:8,name:`source`,kind:`enum`,T:A.getEnumType(ua)},{no:9,name:`layers`,kind:`message`,T:ka,repeated:!0},{no:10,name:`simulcast_codecs`,kind:`message`,T:mo,repeated:!0},{no:11,name:`sid`,kind:`scalar`,T:9},{no:12,name:`stereo`,kind:`scalar`,T:8},{no:13,name:`disable_red`,kind:`scalar`,T:8},{no:14,name:`encryption`,kind:`enum`,T:A.getEnumType(j)},{no:15,name:`stream`,kind:`scalar`,T:9},{no:16,name:`backup_codec_policy`,kind:`enum`,T:A.getEnumType(ca)},{no:17,name:`audio_features`,kind:`enum`,T:A.getEnumType(_a),repeated:!0}]),go=A.makeMessageType(`livekit.PublishDataTrackRequest`,()=>[{no:1,name:`pub_handle`,kind:`scalar`,T:13},{no:2,name:`name`,kind:`scalar`,T:9},{no:3,name:`encryption`,kind:`enum`,T:A.getEnumType(j)}]),_o=A.makeMessageType(`livekit.PublishDataTrackResponse`,()=>[{no:1,name:`info`,kind:`message`,T:Da}]),vo=A.makeMessageType(`livekit.UnpublishDataTrackRequest`,()=>[{no:1,name:`pub_handle`,kind:`scalar`,T:13}]),yo=A.makeMessageType(`livekit.UnpublishDataTrackResponse`,()=>[{no:1,name:`info`,kind:`message`,T:Da}]),bo=A.makeMessageType(`livekit.DataTrackSubscriberHandles`,()=>[{no:1,name:`sub_handles`,kind:`map`,K:13,V:{kind:`message`,T:xo}}]),xo=A.makeMessageType(`livekit.DataTrackSubscriberHandles.PublishedDataTrack`,()=>[{no:1,name:`publisher_identity`,kind:`scalar`,T:9},{no:2,name:`publisher_sid`,kind:`scalar`,T:9},{no:3,name:`track_sid`,kind:`scalar`,T:9}],{localName:`DataTrackSubscriberHandles_PublishedDataTrack`}),So=A.makeMessageType(`livekit.TrickleRequest`,()=>[{no:1,name:`candidateInit`,kind:`scalar`,T:9},{no:2,name:`target`,kind:`enum`,T:A.getEnumType(co)},{no:3,name:`final`,kind:`scalar`,T:8}]),Co=A.makeMessageType(`livekit.MuteTrackRequest`,()=>[{no:1,name:`sid`,kind:`scalar`,T:9},{no:2,name:`muted`,kind:`scalar`,T:8}]),wo=A.makeMessageType(`livekit.JoinResponse`,()=>[{no:1,name:`room`,kind:`message`,T:va},{no:2,name:`participant`,kind:`message`,T:xa},{no:3,name:`other_participants`,kind:`message`,T:xa,repeated:!0},{no:4,name:`server_version`,kind:`scalar`,T:9},{no:5,name:`ice_servers`,kind:`message`,T:Bo,repeated:!0},{no:6,name:`subscriber_primary`,kind:`scalar`,T:8},{no:7,name:`alternative_url`,kind:`scalar`,T:9},{no:8,name:`client_configuration`,kind:`message`,T:Za},{no:9,name:`server_region`,kind:`scalar`,T:9},{no:10,name:`ping_timeout`,kind:`scalar`,T:5},{no:11,name:`ping_interval`,kind:`scalar`,T:5},{no:12,name:`server_info`,kind:`message`,T:qa},{no:13,name:`sif_trailer`,kind:`scalar`,T:12},{no:14,name:`enabled_publish_codecs`,kind:`message`,T:ya,repeated:!0},{no:15,name:`fast_publish`,kind:`scalar`,T:8}]),To=A.makeMessageType(`livekit.ReconnectResponse`,()=>[{no:1,name:`ice_servers`,kind:`message`,T:Bo,repeated:!0},{no:2,name:`client_configuration`,kind:`message`,T:Za},{no:3,name:`server_info`,kind:`message`,T:qa},{no:4,name:`last_message_seq`,kind:`scalar`,T:13}]),Eo=A.makeMessageType(`livekit.TrackPublishedResponse`,()=>[{no:1,name:`cid`,kind:`scalar`,T:9},{no:2,name:`track`,kind:`message`,T:Ea}]),Do=A.makeMessageType(`livekit.TrackUnpublishedResponse`,()=>[{no:1,name:`track_sid`,kind:`scalar`,T:9}]),Oo=A.makeMessageType(`livekit.SessionDescription`,()=>[{no:1,name:`type`,kind:`scalar`,T:9},{no:2,name:`sdp`,kind:`scalar`,T:9},{no:3,name:`id`,kind:`scalar`,T:13},{no:4,name:`mid_to_track_id`,kind:`map`,K:9,V:{kind:`scalar`,T:9}}]),ko=A.makeMessageType(`livekit.ParticipantUpdate`,()=>[{no:1,name:`participants`,kind:`message`,T:xa,repeated:!0}]),Ao=A.makeMessageType(`livekit.UpdateSubscription`,()=>[{no:1,name:`track_sids`,kind:`scalar`,T:9,repeated:!0},{no:2,name:`subscribe`,kind:`scalar`,T:8},{no:3,name:`participant_tracks`,kind:`message`,T:Ka,repeated:!0}]),jo=A.makeMessageType(`livekit.UpdateDataSubscription`,()=>[{no:1,name:`updates`,kind:`message`,T:Mo,repeated:!0}]),Mo=A.makeMessageType(`livekit.UpdateDataSubscription.Update`,()=>[{no:1,name:`track_sid`,kind:`scalar`,T:9},{no:2,name:`subscribe`,kind:`scalar`,T:8},{no:3,name:`options`,kind:`message`,T:Oa}],{localName:`UpdateDataSubscription_Update`}),No=A.makeMessageType(`livekit.UpdateTrackSettings`,()=>[{no:1,name:`track_sids`,kind:`scalar`,T:9,repeated:!0},{no:3,name:`disabled`,kind:`scalar`,T:8},{no:4,name:`quality`,kind:`enum`,T:A.getEnumType(da)},{no:5,name:`width`,kind:`scalar`,T:13},{no:6,name:`height`,kind:`scalar`,T:13},{no:7,name:`fps`,kind:`scalar`,T:13},{no:8,name:`priority`,kind:`scalar`,T:13}]),Po=A.makeMessageType(`livekit.UpdateLocalAudioTrack`,()=>[{no:1,name:`track_sid`,kind:`scalar`,T:9},{no:2,name:`features`,kind:`enum`,T:A.getEnumType(_a),repeated:!0}]),Fo=A.makeMessageType(`livekit.UpdateLocalVideoTrack`,()=>[{no:1,name:`track_sid`,kind:`scalar`,T:9},{no:2,name:`width`,kind:`scalar`,T:13},{no:3,name:`height`,kind:`scalar`,T:13}]),Io=A.makeMessageType(`livekit.LeaveRequest`,()=>[{no:1,name:`can_reconnect`,kind:`scalar`,T:8},{no:2,name:`reason`,kind:`enum`,T:A.getEnumType(ma)},{no:3,name:`action`,kind:`enum`,T:A.getEnumType(Lo)},{no:4,name:`regions`,kind:`message`,T:ss}]),Lo=A.makeEnum(`livekit.LeaveRequest.Action`,[{no:0,name:`DISCONNECT`},{no:1,name:`RESUME`},{no:2,name:`RECONNECT`}]),Ro=A.makeMessageType(`livekit.UpdateVideoLayers`,()=>[{no:1,name:`track_sid`,kind:`scalar`,T:9},{no:2,name:`layers`,kind:`message`,T:ka,repeated:!0}]),zo=A.makeMessageType(`livekit.UpdateParticipantMetadata`,()=>[{no:1,name:`metadata`,kind:`scalar`,T:9},{no:2,name:`name`,kind:`scalar`,T:9},{no:3,name:`attributes`,kind:`map`,K:9,V:{kind:`scalar`,T:9}},{no:4,name:`request_id`,kind:`scalar`,T:13}]),Bo=A.makeMessageType(`livekit.ICEServer`,()=>[{no:1,name:`urls`,kind:`scalar`,T:9,repeated:!0},{no:2,name:`username`,kind:`scalar`,T:9},{no:3,name:`credential`,kind:`scalar`,T:9}]),Vo=A.makeMessageType(`livekit.SpeakersChanged`,()=>[{no:1,name:`speakers`,kind:`message`,T:Ia,repeated:!0}]),Ho=A.makeMessageType(`livekit.RoomUpdate`,()=>[{no:1,name:`room`,kind:`message`,T:va}]),Uo=A.makeMessageType(`livekit.ConnectionQualityInfo`,()=>[{no:1,name:`participant_sid`,kind:`scalar`,T:9},{no:2,name:`quality`,kind:`enum`,T:A.getEnumType(fa)},{no:3,name:`score`,kind:`scalar`,T:2}]),Wo=A.makeMessageType(`livekit.ConnectionQualityUpdate`,()=>[{no:1,name:`updates`,kind:`message`,T:Uo,repeated:!0}]),Go=A.makeMessageType(`livekit.StreamStateInfo`,()=>[{no:1,name:`participant_sid`,kind:`scalar`,T:9},{no:2,name:`track_sid`,kind:`scalar`,T:9},{no:3,name:`state`,kind:`enum`,T:A.getEnumType(lo)}]),Ko=A.makeMessageType(`livekit.StreamStateUpdate`,()=>[{no:1,name:`stream_states`,kind:`message`,T:Go,repeated:!0}]),qo=A.makeMessageType(`livekit.SubscribedQuality`,()=>[{no:1,name:`quality`,kind:`enum`,T:A.getEnumType(da)},{no:2,name:`enabled`,kind:`scalar`,T:8}]),Jo=A.makeMessageType(`livekit.SubscribedCodec`,()=>[{no:1,name:`codec`,kind:`scalar`,T:9},{no:2,name:`qualities`,kind:`message`,T:qo,repeated:!0}]),Yo=A.makeMessageType(`livekit.SubscribedQualityUpdate`,()=>[{no:1,name:`track_sid`,kind:`scalar`,T:9},{no:2,name:`subscribed_qualities`,kind:`message`,T:qo,repeated:!0},{no:3,name:`subscribed_codecs`,kind:`message`,T:Jo,repeated:!0}]),Xo=A.makeMessageType(`livekit.SubscribedAudioCodecUpdate`,()=>[{no:1,name:`track_sid`,kind:`scalar`,T:9},{no:2,name:`subscribed_audio_codecs`,kind:`message`,T:so,repeated:!0}]),Zo=A.makeMessageType(`livekit.TrackPermission`,()=>[{no:1,name:`participant_sid`,kind:`scalar`,T:9},{no:2,name:`all_tracks`,kind:`scalar`,T:8},{no:3,name:`track_sids`,kind:`scalar`,T:9,repeated:!0},{no:4,name:`participant_identity`,kind:`scalar`,T:9}]),Qo=A.makeMessageType(`livekit.SubscriptionPermission`,()=>[{no:1,name:`all_participants`,kind:`scalar`,T:8},{no:2,name:`track_permissions`,kind:`message`,T:Zo,repeated:!0}]),$o=A.makeMessageType(`livekit.SubscriptionPermissionUpdate`,()=>[{no:1,name:`participant_sid`,kind:`scalar`,T:9},{no:2,name:`track_sid`,kind:`scalar`,T:9},{no:3,name:`allowed`,kind:`scalar`,T:8}]),es=A.makeMessageType(`livekit.RoomMovedResponse`,()=>[{no:1,name:`room`,kind:`message`,T:va},{no:2,name:`token`,kind:`scalar`,T:9},{no:3,name:`participant`,kind:`message`,T:xa},{no:4,name:`other_participants`,kind:`message`,T:xa,repeated:!0}]),ts=A.makeMessageType(`livekit.SyncState`,()=>[{no:1,name:`answer`,kind:`message`,T:Oo},{no:2,name:`subscription`,kind:`message`,T:Ao},{no:3,name:`publish_tracks`,kind:`message`,T:Eo,repeated:!0},{no:4,name:`data_channels`,kind:`message`,T:rs,repeated:!0},{no:5,name:`offer`,kind:`message`,T:Oo},{no:6,name:`track_sids_disabled`,kind:`scalar`,T:9,repeated:!0},{no:7,name:`datachannel_receive_states`,kind:`message`,T:ns,repeated:!0},{no:8,name:`publish_data_tracks`,kind:`message`,T:_o,repeated:!0}]),ns=A.makeMessageType(`livekit.DataChannelReceiveState`,()=>[{no:1,name:`publisher_sid`,kind:`scalar`,T:9},{no:2,name:`last_seq`,kind:`scalar`,T:13}]),rs=A.makeMessageType(`livekit.DataChannelInfo`,()=>[{no:1,name:`label`,kind:`scalar`,T:9},{no:2,name:`id`,kind:`scalar`,T:13},{no:3,name:`target`,kind:`enum`,T:A.getEnumType(co)}]),is=A.makeMessageType(`livekit.SimulateScenario`,()=>[{no:1,name:`speaker_update`,kind:`scalar`,T:5,oneof:`scenario`},{no:2,name:`node_failure`,kind:`scalar`,T:8,oneof:`scenario`},{no:3,name:`migration`,kind:`scalar`,T:8,oneof:`scenario`},{no:4,name:`server_leave`,kind:`scalar`,T:8,oneof:`scenario`},{no:5,name:`switch_candidate_protocol`,kind:`enum`,T:A.getEnumType(uo),oneof:`scenario`},{no:6,name:`subscriber_bandwidth`,kind:`scalar`,T:3,oneof:`scenario`},{no:7,name:`disconnect_signal_on_resume`,kind:`scalar`,T:8,oneof:`scenario`},{no:8,name:`disconnect_signal_on_resume_no_messages`,kind:`scalar`,T:8,oneof:`scenario`},{no:9,name:`leave_request_full_reconnect`,kind:`scalar`,T:8,oneof:`scenario`}]),as=A.makeMessageType(`livekit.Ping`,()=>[{no:1,name:`timestamp`,kind:`scalar`,T:3},{no:2,name:`rtt`,kind:`scalar`,T:3}]),os=A.makeMessageType(`livekit.Pong`,()=>[{no:1,name:`last_ping_timestamp`,kind:`scalar`,T:3},{no:2,name:`timestamp`,kind:`scalar`,T:3}]),ss=A.makeMessageType(`livekit.RegionSettings`,()=>[{no:1,name:`regions`,kind:`message`,T:cs,repeated:!0}]),cs=A.makeMessageType(`livekit.RegionInfo`,()=>[{no:1,name:`region`,kind:`scalar`,T:9},{no:2,name:`url`,kind:`scalar`,T:9},{no:3,name:`distance`,kind:`scalar`,T:3}]),ls=A.makeMessageType(`livekit.SubscriptionResponse`,()=>[{no:1,name:`track_sid`,kind:`scalar`,T:9},{no:2,name:`err`,kind:`enum`,T:A.getEnumType(ga)}]),us=A.makeMessageType(`livekit.RequestResponse`,()=>[{no:1,name:`request_id`,kind:`scalar`,T:13},{no:2,name:`reason`,kind:`enum`,T:A.getEnumType(ds)},{no:3,name:`message`,kind:`scalar`,T:9},{no:4,name:`trickle`,kind:`message`,T:So,oneof:`request`},{no:5,name:`add_track`,kind:`message`,T:ho,oneof:`request`},{no:6,name:`mute`,kind:`message`,T:Co,oneof:`request`},{no:7,name:`update_metadata`,kind:`message`,T:zo,oneof:`request`},{no:8,name:`update_audio_track`,kind:`message`,T:Po,oneof:`request`},{no:9,name:`update_video_track`,kind:`message`,T:Fo,oneof:`request`},{no:10,name:`publish_data_track`,kind:`message`,T:go,oneof:`request`},{no:11,name:`unpublish_data_track`,kind:`message`,T:vo,oneof:`request`}]),ds=A.makeEnum(`livekit.RequestResponse.Reason`,[{no:0,name:`OK`},{no:1,name:`NOT_FOUND`},{no:2,name:`NOT_ALLOWED`},{no:3,name:`LIMIT_EXCEEDED`},{no:4,name:`QUEUED`},{no:5,name:`UNSUPPORTED_TYPE`},{no:6,name:`UNCLASSIFIED_ERROR`},{no:7,name:`INVALID_HANDLE`},{no:8,name:`INVALID_NAME`},{no:9,name:`DUPLICATE_HANDLE`},{no:10,name:`DUPLICATE_NAME`}]),fs=A.makeMessageType(`livekit.TrackSubscribed`,()=>[{no:1,name:`track_sid`,kind:`scalar`,T:9}]),ps=A.makeMessageType(`livekit.ConnectionSettings`,()=>[{no:1,name:`auto_subscribe`,kind:`scalar`,T:8},{no:2,name:`adaptive_stream`,kind:`scalar`,T:8},{no:3,name:`subscriber_allow_pause`,kind:`scalar`,T:8,opt:!0},{no:4,name:`disable_ice_lite`,kind:`scalar`,T:8},{no:5,name:`auto_subscribe_data_track`,kind:`scalar`,T:8,opt:!0}]),ms=A.makeMessageType(`livekit.JoinRequest`,()=>[{no:1,name:`client_info`,kind:`message`,T:Ya},{no:2,name:`connection_settings`,kind:`message`,T:ps},{no:3,name:`metadata`,kind:`scalar`,T:9},{no:4,name:`participant_attributes`,kind:`map`,K:9,V:{kind:`scalar`,T:9}},{no:5,name:`add_track_requests`,kind:`message`,T:ho,repeated:!0},{no:6,name:`publisher_offer`,kind:`message`,T:Oo},{no:7,name:`reconnect`,kind:`scalar`,T:8},{no:8,name:`reconnect_reason`,kind:`enum`,T:A.getEnumType(ha)},{no:9,name:`participant_sid`,kind:`scalar`,T:9},{no:10,name:`sync_state`,kind:`message`,T:ts}]),hs=A.makeMessageType(`livekit.WrappedJoinRequest`,()=>[{no:1,name:`compression`,kind:`enum`,T:A.getEnumType(gs)},{no:2,name:`join_request`,kind:`scalar`,T:12}]),gs=A.makeEnum(`livekit.WrappedJoinRequest.Compression`,[{no:0,name:`NONE`},{no:1,name:`GZIP`}]),_s=A.makeMessageType(`livekit.MediaSectionsRequirement`,()=>[{no:1,name:`num_audios`,kind:`scalar`,T:13},{no:2,name:`num_videos`,kind:`scalar`,T:13}]);function vs(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,`default`)?e.default:e}var ys={exports:{}},bs=ys.exports,xs;function Ss(){return xs?ys.exports:(xs=1,(function(e){(function(t,n){e.exports?e.exports=n():t.log=n()})(bs,function(){var e=function(){},t=`undefined`,n=typeof window!==t&&typeof window.navigator!==t&&/Trident\/|MSIE /.test(window.navigator.userAgent),r=[`trace`,`debug`,`info`,`warn`,`error`],i={},a=null;function o(e,t){var n=e[t];if(typeof n.bind==`function`)return n.bind(e);try{return Function.prototype.bind.call(n,e)}catch{return function(){return Function.prototype.apply.apply(n,[e,arguments])}}}function s(){console.log&&(console.log.apply?console.log.apply(console,arguments):Function.prototype.apply.apply(console.log,[console,arguments])),console.trace&&console.trace()}function c(r){return r===`debug`&&(r=`log`),typeof console===t?!1:r===`trace`&&n?s:console[r]===void 0?console.log===void 0?e:o(console,`log`):o(console,r)}function l(){for(var n=this.getLevel(),i=0;i<r.length;i++){var a=r[i];this[a]=i<n?e:this.methodFactory(a,n,this.name)}if(this.log=this.debug,typeof console===t&&n<this.levels.SILENT)return`No console available for logging`}function u(e){return function(){typeof console!==t&&(l.call(this),this[e].apply(this,arguments))}}function d(e,t,n){return c(e)||u.apply(this,arguments)}function f(e,n){var o=this,s,c,u,f=`loglevel`;typeof e==`string`?f+=`:`+e:typeof e==`symbol`&&(f=void 0);function p(e){var n=(r[e]||`silent`).toUpperCase();if(!(typeof window===t||!f)){try{window.localStorage[f]=n;return}catch{}try{window.document.cookie=encodeURIComponent(f)+`=`+n+`;`}catch{}}}function m(){var e;if(!(typeof window===t||!f)){try{e=window.localStorage[f]}catch{}if(typeof e===t)try{var n=window.document.cookie,r=encodeURIComponent(f),i=n.indexOf(r+`=`);i!==-1&&(e=/^([^;]+)/.exec(n.slice(i+r.length+1))[1])}catch{}return o.levels[e]===void 0&&(e=void 0),e}}function ee(){if(!(typeof window===t||!f)){try{window.localStorage.removeItem(f)}catch{}try{window.document.cookie=encodeURIComponent(f)+`=; expires=Thu, 01 Jan 1970 00:00:00 UTC`}catch{}}}function h(e){var t=e;if(typeof t==`string`&&o.levels[t.toUpperCase()]!==void 0&&(t=o.levels[t.toUpperCase()]),typeof t==`number`&&t>=0&&t<=o.levels.SILENT)return t;throw TypeError(`log.setLevel() called with invalid level: `+e)}o.name=e,o.levels={TRACE:0,DEBUG:1,INFO:2,WARN:3,ERROR:4,SILENT:5},o.methodFactory=n||d,o.getLevel=function(){return u??c??s},o.setLevel=function(e,t){return u=h(e),t!==!1&&p(u),l.call(o)},o.setDefaultLevel=function(e){c=h(e),m()||o.setLevel(e,!1)},o.resetLevel=function(){u=null,ee(),l.call(o)},o.enableAll=function(e){o.setLevel(o.levels.TRACE,e)},o.disableAll=function(e){o.setLevel(o.levels.SILENT,e)},o.rebuild=function(){if(a!==o&&(s=h(a.getLevel())),l.call(o),a===o)for(var e in i)i[e].rebuild()},s=h(a?a.getLevel():`WARN`);var g=m();g!=null&&(u=h(g)),l.call(o)}a=new f,a.getLogger=function(e){if(typeof e!=`symbol`&&typeof e!=`string`||e===``)throw TypeError(`You must supply a name when creating a logger.`);var t=i[e];return t||=i[e]=new f(e,a.methodFactory),t};var p=typeof window===t?void 0:window.log;return a.noConflict=function(){return typeof window!==t&&window.log===a&&(window.log=p),a},a.getLoggers=function(){return i},a.default=a,a})})(ys),ys.exports)}var Cs=Ss(),ws;(function(e){e[e.trace=0]=`trace`,e[e.debug=1]=`debug`,e[e.info=2]=`info`,e[e.warn=3]=`warn`,e[e.error=4]=`error`,e[e.silent=5]=`silent`})(ws||={});var Ts;(function(e){e.Default=`livekit`,e.Room=`livekit-room`,e.TokenSource=`livekit-token-source`,e.Participant=`livekit-participant`,e.Track=`livekit-track`,e.Publication=`livekit-track-publication`,e.Engine=`livekit-engine`,e.Signal=`livekit-signal`,e.PCManager=`livekit-pc-manager`,e.PCTransport=`livekit-pc-transport`,e.E2EE=`lk-e2ee`,e.DataTracks=`livekit-data-tracks`})(Ts||={});var M=Cs.getLogger(`livekit`);Object.values(Ts).map(e=>Cs.getLogger(e)),M.setDefaultLevel(ws.info);function Es(e){let t=Cs.getLogger(e);return t.setDefaultLevel(M.getLevel()),t}var Ds=Cs.getLogger(`lk-e2ee`),Os=7e3,ks=[0,300,4*300,9*300,16*300,Os,Os,Os,Os,Os],As=class{constructor(e){this._retryDelays=e===void 0?ks:[...e]}nextRetryDelayInMs(e){if(e.retryCount>=this._retryDelays.length)return null;let t=this._retryDelays[e.retryCount];return e.retryCount<=1?t:t+Math.random()*1e3}};function js(e,t){var n={};for(var r in e)Object.prototype.hasOwnProperty.call(e,r)&&t.indexOf(r)<0&&(n[r]=e[r]);if(e!=null&&typeof Object.getOwnPropertySymbols==`function`)for(var i=0,r=Object.getOwnPropertySymbols(e);i<r.length;i++)t.indexOf(r[i])<0&&Object.prototype.propertyIsEnumerable.call(e,r[i])&&(n[r[i]]=e[r[i]]);return n}function N(e,t,n,r){function i(e){return e instanceof n?e:new n(function(t){t(e)})}return new(n||=Promise)(function(n,a){function o(e){try{c(r.next(e))}catch(e){a(e)}}function s(e){try{c(r.throw(e))}catch(e){a(e)}}function c(e){e.done?n(e.value):i(e.value).then(o,s)}c((r=r.apply(e,t||[])).next())})}function Ms(e){var t=typeof Symbol==`function`&&Symbol.iterator,n=t&&e[t],r=0;if(n)return n.call(e);if(e&&typeof e.length==`number`)return{next:function(){return e&&r>=e.length&&(e=void 0),{value:e&&e[r++],done:!e}}};throw TypeError(t?`Object is not iterable.`:`Symbol.iterator is not defined.`)}function Ns(e){return this instanceof Ns?(this.v=e,this):new Ns(e)}function Ps(e,t,n){if(!Symbol.asyncIterator)throw TypeError(`Symbol.asyncIterator is not defined.`);var r=n.apply(e,t||[]),i,a=[];return i=Object.create((typeof AsyncIterator==`function`?AsyncIterator:Object).prototype),s(`next`),s(`throw`),s(`return`,o),i[Symbol.asyncIterator]=function(){return this},i;function o(e){return function(t){return Promise.resolve(t).then(e,d)}}function s(e,t){r[e]&&(i[e]=function(t){return new Promise(function(n,r){a.push([e,t,n,r])>1||c(e,t)})},t&&(i[e]=t(i[e])))}function c(e,t){try{l(r[e](t))}catch(e){f(a[0][3],e)}}function l(e){e.value instanceof Ns?Promise.resolve(e.value.v).then(u,d):f(a[0][2],e)}function u(e){c(`next`,e)}function d(e){c(`throw`,e)}function f(e,t){e(t),a.shift(),a.length&&c(a[0][0],a[0][1])}}function Fs(e){var t,n;return t={},r(`next`),r(`throw`,function(e){throw e}),r(`return`),t[Symbol.iterator]=function(){return this},t;function r(r,i){t[r]=e[r]?function(t){return(n=!n)?{value:Ns(e[r](t)),done:!1}:i?i(t):t}:i}}function Is(e){if(!Symbol.asyncIterator)throw TypeError(`Symbol.asyncIterator is not defined.`);var t=e[Symbol.asyncIterator],n;return t?t.call(e):(e=typeof Ms==`function`?Ms(e):e[Symbol.iterator](),n={},r(`next`),r(`throw`),r(`return`),n[Symbol.asyncIterator]=function(){return this},n);function r(t){n[t]=e[t]&&function(n){return new Promise(function(r,a){n=e[t](n),i(r,a,n.done,n.value)})}}function i(e,t,n,r){Promise.resolve(r).then(function(t){e({value:t,done:n})},t)}}var Ls={exports:{}},Rs;function zs(){if(Rs)return Ls.exports;Rs=1;var e=typeof Reflect==`object`?Reflect:null,t=e&&typeof e.apply==`function`?e.apply:function(e,t,n){return Function.prototype.apply.call(e,t,n)},n=e&&typeof e.ownKeys==`function`?e.ownKeys:Object.getOwnPropertySymbols?function(e){return Object.getOwnPropertyNames(e).concat(Object.getOwnPropertySymbols(e))}:function(e){return Object.getOwnPropertyNames(e)};function r(e){console&&console.warn&&console.warn(e)}var i=Number.isNaN||function(e){return e!==e};function a(){a.init.call(this)}Ls.exports=a,Ls.exports.once=g,a.EventEmitter=a,a.prototype._events=void 0,a.prototype._eventsCount=0,a.prototype._maxListeners=void 0;var o=10;function s(e){if(typeof e!=`function`)throw TypeError(`The "listener" argument must be of type Function. Received type `+typeof e)}Object.defineProperty(a,`defaultMaxListeners`,{enumerable:!0,get:function(){return o},set:function(e){if(typeof e!=`number`||e<0||i(e))throw RangeError(`The value of "defaultMaxListeners" is out of range. It must be a non-negative number. Received `+e+`.`);o=e}}),a.init=function(){(this._events===void 0||this._events===Object.getPrototypeOf(this)._events)&&(this._events=Object.create(null),this._eventsCount=0),this._maxListeners=this._maxListeners||void 0},a.prototype.setMaxListeners=function(e){if(typeof e!=`number`||e<0||i(e))throw RangeError(`The value of "n" is out of range. It must be a non-negative number. Received `+e+`.`);return this._maxListeners=e,this};function c(e){return e._maxListeners===void 0?a.defaultMaxListeners:e._maxListeners}a.prototype.getMaxListeners=function(){return c(this)},a.prototype.emit=function(e){for(var n=[],r=1;r<arguments.length;r++)n.push(arguments[r]);var i=e===`error`,a=this._events;if(a!==void 0)i&&=a.error===void 0;else if(!i)return!1;if(i){var o;if(n.length>0&&(o=n[0]),o instanceof Error)throw o;var s=Error(`Unhandled error.`+(o?` (`+o.message+`)`:``));throw s.context=o,s}var c=a[e];if(c===void 0)return!1;if(typeof c==`function`)t(c,this,n);else for(var l=c.length,u=m(c,l),r=0;r<l;++r)t(u[r],this,n);return!0};function l(e,t,n,i){var a,o,l;if(s(n),o=e._events,o===void 0?(o=e._events=Object.create(null),e._eventsCount=0):(o.newListener!==void 0&&(e.emit(`newListener`,t,n.listener?n.listener:n),o=e._events),l=o[t]),l===void 0)l=o[t]=n,++e._eventsCount;else if(typeof l==`function`?l=o[t]=i?[n,l]:[l,n]:i?l.unshift(n):l.push(n),a=c(e),a>0&&l.length>a&&!l.warned){l.warned=!0;var u=Error(`Possible EventEmitter memory leak detected. `+l.length+` `+String(t)+` listeners added. Use emitter.setMaxListeners() to increase limit`);u.name=`MaxListenersExceededWarning`,u.emitter=e,u.type=t,u.count=l.length,r(u)}return e}a.prototype.addListener=function(e,t){return l(this,e,t,!1)},a.prototype.on=a.prototype.addListener,a.prototype.prependListener=function(e,t){return l(this,e,t,!0)};function u(){if(!this.fired)return this.target.removeListener(this.type,this.wrapFn),this.fired=!0,arguments.length===0?this.listener.call(this.target):this.listener.apply(this.target,arguments)}function d(e,t,n){var r={fired:!1,wrapFn:void 0,target:e,type:t,listener:n},i=u.bind(r);return i.listener=n,r.wrapFn=i,i}a.prototype.once=function(e,t){return s(t),this.on(e,d(this,e,t)),this},a.prototype.prependOnceListener=function(e,t){return s(t),this.prependListener(e,d(this,e,t)),this},a.prototype.removeListener=function(e,t){var n,r,i,a,o;if(s(t),r=this._events,r===void 0||(n=r[e],n===void 0))return this;if(n===t||n.listener===t)--this._eventsCount===0?this._events=Object.create(null):(delete r[e],r.removeListener&&this.emit(`removeListener`,e,n.listener||t));else if(typeof n!=`function`){for(i=-1,a=n.length-1;a>=0;a--)if(n[a]===t||n[a].listener===t){o=n[a].listener,i=a;break}if(i<0)return this;i===0?n.shift():ee(n,i),n.length===1&&(r[e]=n[0]),r.removeListener!==void 0&&this.emit(`removeListener`,e,o||t)}return this},a.prototype.off=a.prototype.removeListener,a.prototype.removeAllListeners=function(e){var t,n=this._events,r;if(n===void 0)return this;if(n.removeListener===void 0)return arguments.length===0?(this._events=Object.create(null),this._eventsCount=0):n[e]!==void 0&&(--this._eventsCount===0?this._events=Object.create(null):delete n[e]),this;if(arguments.length===0){var i=Object.keys(n),a;for(r=0;r<i.length;++r)a=i[r],a!==`removeListener`&&this.removeAllListeners(a);return this.removeAllListeners(`removeListener`),this._events=Object.create(null),this._eventsCount=0,this}if(t=n[e],typeof t==`function`)this.removeListener(e,t);else if(t!==void 0)for(r=t.length-1;r>=0;r--)this.removeListener(e,t[r]);return this};function f(e,t,n){var r=e._events;if(r===void 0)return[];var i=r[t];return i===void 0?[]:typeof i==`function`?n?[i.listener||i]:[i]:n?h(i):m(i,i.length)}a.prototype.listeners=function(e){return f(this,e,!0)},a.prototype.rawListeners=function(e){return f(this,e,!1)},a.listenerCount=function(e,t){return typeof e.listenerCount==`function`?e.listenerCount(t):p.call(e,t)},a.prototype.listenerCount=p;function p(e){var t=this._events;if(t!==void 0){var n=t[e];if(typeof n==`function`)return 1;if(n!==void 0)return n.length}return 0}a.prototype.eventNames=function(){return this._eventsCount>0?n(this._events):[]};function m(e,t){for(var n=Array(t),r=0;r<t;++r)n[r]=e[r];return n}function ee(e,t){for(;t+1<e.length;t++)e[t]=e[t+1];e.pop()}function h(e){for(var t=Array(e.length),n=0;n<t.length;++n)t[n]=e[n].listener||e[n];return t}function g(e,t){return new Promise(function(n,r){function i(n){e.removeListener(t,a),r(n)}function a(){typeof e.removeListener==`function`&&e.removeListener(`error`,i),n([].slice.call(arguments))}ne(e,t,a,{once:!0}),t!==`error`&&te(e,i,{once:!0})})}function te(e,t,n){typeof e.on==`function`&&ne(e,`error`,t,n)}function ne(e,t,n,r){if(typeof e.on==`function`)r.once?e.once(t,n):e.on(t,n);else if(typeof e.addEventListener==`function`)e.addEventListener(t,function i(a){r.once&&e.removeEventListener(t,i),n(a)});else throw TypeError(`The "emitter" argument must be of type EventEmitter. Received type `+typeof e)}return Ls.exports}var Bs=zs(),Vs=!0,Hs=!0;function Us(e,t,n){let r=e.match(t);return r&&r.length>=n&&parseFloat(r[n],10)}function Ws(e,t,n){if(!e.RTCPeerConnection)return;let r=e.RTCPeerConnection.prototype,i=r.addEventListener;r.addEventListener=function(e,r){if(e!==t)return i.apply(this,arguments);let a=e=>{let t=n(e);t&&(r.handleEvent?r.handleEvent(t):r(t))};return this._eventMap=this._eventMap||{},this._eventMap[t]||(this._eventMap[t]=new Map),this._eventMap[t].set(r,a),i.apply(this,[e,a])};let a=r.removeEventListener;r.removeEventListener=function(e,n){if(e!==t||!this._eventMap||!this._eventMap[t]||!this._eventMap[t].has(n))return a.apply(this,arguments);let r=this._eventMap[t].get(n);return this._eventMap[t].delete(n),this._eventMap[t].size===0&&delete this._eventMap[t],Object.keys(this._eventMap).length===0&&delete this._eventMap,a.apply(this,[e,r])},Object.defineProperty(r,`on`+t,{get(){return this[`_on`+t]},set(e){this[`_on`+t]&&(this.removeEventListener(t,this[`_on`+t]),delete this[`_on`+t]),e&&this.addEventListener(t,this[`_on`+t]=e)},enumerable:!0,configurable:!0})}function Gs(e){return typeof e==`boolean`?(Vs=e,e?`adapter.js logging disabled`:`adapter.js logging enabled`):Error(`Argument type: `+typeof e+`. Please use a boolean.`)}function Ks(e){return typeof e==`boolean`?(Hs=!e,`adapter.js deprecation warnings `+(e?`disabled`:`enabled`)):Error(`Argument type: `+typeof e+`. Please use a boolean.`)}function qs(){if(typeof window==`object`){if(Vs)return;typeof console<`u`&&typeof console.log==`function`&&console.log.apply(console,arguments)}}function Js(e,t){Hs&&console.warn(e+` is deprecated, please use `+t+` instead.`)}function Ys(e){let t={browser:null,version:null};if(e===void 0||!e.navigator||!e.navigator.userAgent)return t.browser=`Not a browser.`,t;let{navigator:n}=e;if(n.userAgentData&&n.userAgentData.brands){let e=n.userAgentData.brands.find(e=>e.brand===`Chromium`);if(e)return{browser:`chrome`,version:parseInt(e.version,10)}}if(n.mozGetUserMedia)t.browser=`firefox`,t.version=parseInt(Us(n.userAgent,/Firefox\/(\d+)\./,1));else if(n.webkitGetUserMedia||e.isSecureContext===!1&&e.webkitRTCPeerConnection)t.browser=`chrome`,t.version=parseInt(Us(n.userAgent,/Chrom(e|ium)\/(\d+)\./,2));else if(e.RTCPeerConnection&&n.userAgent.match(/AppleWebKit\/(\d+)\./))t.browser=`safari`,t.version=parseInt(Us(n.userAgent,/AppleWebKit\/(\d+)\./,1)),t.supportsUnifiedPlan=e.RTCRtpTransceiver&&`currentDirection`in e.RTCRtpTransceiver.prototype,t._safariVersion=Us(n.userAgent,/Version\/(\d+(\.?\d+))/,1);else return t.browser=`Not a supported browser.`,t;return t}function Xs(e){return Object.prototype.toString.call(e)===`[object Object]`}function Zs(e){return Xs(e)?Object.keys(e).reduce(function(t,n){let r=Xs(e[n]),i=r?Zs(e[n]):e[n],a=r&&!Object.keys(i).length;return i===void 0||a?t:Object.assign(t,{[n]:i})},{}):e}function Qs(e,t,n){!t||n.has(t.id)||(n.set(t.id,t),Object.keys(t).forEach(r=>{r.endsWith(`Id`)?Qs(e,e.get(t[r]),n):r.endsWith(`Ids`)&&t[r].forEach(t=>{Qs(e,e.get(t),n)})}))}function $s(e,t,n){let r=n?`outbound-rtp`:`inbound-rtp`,i=new Map;if(t===null)return i;let a=[];return e.forEach(e=>{e.type===`track`&&e.trackIdentifier===t.id&&a.push(e)}),a.forEach(t=>{e.forEach(n=>{n.type===r&&n.trackId===t.id&&Qs(e,n,i)})}),i}var ec=qs;function tc(e,t){let n=e&&e.navigator;if(!n.mediaDevices)return;let r=function(e){if(typeof e!=`object`||e.mandatory||e.optional)return e;let t={};return Object.keys(e).forEach(n=>{if(n===`require`||n===`advanced`||n===`mediaSource`)return;let r=typeof e[n]==`object`?e[n]:{ideal:e[n]};r.exact!==void 0&&typeof r.exact==`number`&&(r.min=r.max=r.exact);let i=function(e,t){return e?e+t.charAt(0).toUpperCase()+t.slice(1):t===`deviceId`?`sourceId`:t};if(r.ideal!==void 0){t.optional=t.optional||[];let e={};typeof r.ideal==`number`?(e[i(`min`,n)]=r.ideal,t.optional.push(e),e={},e[i(`max`,n)]=r.ideal,t.optional.push(e)):(e[i(``,n)]=r.ideal,t.optional.push(e))}r.exact!==void 0&&typeof r.exact!=`number`?(t.mandatory=t.mandatory||{},t.mandatory[i(``,n)]=r.exact):[`min`,`max`].forEach(e=>{r[e]!==void 0&&(t.mandatory=t.mandatory||{},t.mandatory[i(e,n)]=r[e])})}),e.advanced&&(t.optional=(t.optional||[]).concat(e.advanced)),t},i=function(e,i){if(t.version>=61)return i(e);if(e=JSON.parse(JSON.stringify(e)),e&&typeof e.audio==`object`){let t=function(e,t,n){t in e&&!(n in e)&&(e[n]=e[t],delete e[t])};e=JSON.parse(JSON.stringify(e)),t(e.audio,`autoGainControl`,`googAutoGainControl`),t(e.audio,`noiseSuppression`,`googNoiseSuppression`),e.audio=r(e.audio)}if(e&&typeof e.video==`object`){let a=e.video.facingMode;a&&=typeof a==`object`?a:{ideal:a};let o=t.version<66;if(a&&(a.exact===`user`||a.exact===`environment`||a.ideal===`user`||a.ideal===`environment`)&&!(n.mediaDevices.getSupportedConstraints&&n.mediaDevices.getSupportedConstraints().facingMode&&!o)){delete e.video.facingMode;let t;if(a.exact===`environment`||a.ideal===`environment`?t=[`back`,`rear`]:(a.exact===`user`||a.ideal===`user`)&&(t=[`front`]),t)return n.mediaDevices.enumerateDevices().then(n=>{n=n.filter(e=>e.kind===`videoinput`);let o=n.find(e=>t.some(t=>e.label.toLowerCase().includes(t)));return!o&&n.length&&t.includes(`back`)&&(o=n[n.length-1]),o&&(e.video.deviceId=a.exact?{exact:o.deviceId}:{ideal:o.deviceId}),e.video=r(e.video),ec(`chrome: `+JSON.stringify(e)),i(e)})}e.video=r(e.video)}return ec(`chrome: `+JSON.stringify(e)),i(e)},a=function(e){return t.version>=64?e:{name:{PermissionDeniedError:`NotAllowedError`,PermissionDismissedError:`NotAllowedError`,InvalidStateError:`NotAllowedError`,DevicesNotFoundError:`NotFoundError`,ConstraintNotSatisfiedError:`OverconstrainedError`,TrackStartError:`NotReadableError`,MediaDeviceFailedDueToShutdown:`NotAllowedError`,MediaDeviceKillSwitchOn:`NotAllowedError`,TabCaptureError:`AbortError`,ScreenCaptureError:`AbortError`,DeviceCaptureError:`AbortError`}[e.name]||e.name,message:e.message,constraint:e.constraint||e.constraintName,toString(){return this.name+(this.message&&`: `)+this.message}}};if(n.getUserMedia=function(e,t,r){i(e,e=>{n.webkitGetUserMedia(e,t,e=>{r&&r(a(e))})})}.bind(n),n.mediaDevices.getUserMedia){let e=n.mediaDevices.getUserMedia.bind(n.mediaDevices);n.mediaDevices.getUserMedia=function(t){return i(t,t=>e(t).then(e=>{if(t.audio&&!e.getAudioTracks().length||t.video&&!e.getVideoTracks().length)throw e.getTracks().forEach(e=>{e.stop()}),new DOMException(``,`NotFoundError`);return e},e=>Promise.reject(a(e))))}}}function nc(e){e.MediaStream=e.MediaStream||e.webkitMediaStream}function rc(e){if(typeof e==`object`&&e.RTCPeerConnection&&!(`ontrack`in e.RTCPeerConnection.prototype)){Object.defineProperty(e.RTCPeerConnection.prototype,`ontrack`,{get(){return this._ontrack},set(e){this._ontrack&&this.removeEventListener(`track`,this._ontrack),this.addEventListener(`track`,this._ontrack=e)},enumerable:!0,configurable:!0});let t=e.RTCPeerConnection.prototype.setRemoteDescription;e.RTCPeerConnection.prototype.setRemoteDescription=function(){return this._ontrackpoly||(this._ontrackpoly=t=>{t.stream.addEventListener(`addtrack`,n=>{let r;r=e.RTCPeerConnection.prototype.getReceivers?this.getReceivers().find(e=>e.track&&e.track.id===n.track.id):{track:n.track};let i=new Event(`track`);i.track=n.track,i.receiver=r,i.transceiver={receiver:r},i.streams=[t.stream],this.dispatchEvent(i)}),t.stream.getTracks().forEach(n=>{let r;r=e.RTCPeerConnection.prototype.getReceivers?this.getReceivers().find(e=>e.track&&e.track.id===n.id):{track:n};let i=new Event(`track`);i.track=n,i.receiver=r,i.transceiver={receiver:r},i.streams=[t.stream],this.dispatchEvent(i)})},this.addEventListener(`addstream`,this._ontrackpoly)),t.apply(this,arguments)}}else Ws(e,`track`,e=>(e.transceiver||Object.defineProperty(e,`transceiver`,{value:{receiver:e.receiver}}),e))}function ic(e){if(typeof e==`object`&&e.RTCPeerConnection&&!(`getSenders`in e.RTCPeerConnection.prototype)&&`createDTMFSender`in e.RTCPeerConnection.prototype){let t=function(e,t){return{track:t,get dtmf(){return this._dtmf===void 0&&(t.kind===`audio`?this._dtmf=e.createDTMFSender(t):this._dtmf=null),this._dtmf},_pc:e}};if(!e.RTCPeerConnection.prototype.getSenders){e.RTCPeerConnection.prototype.getSenders=function(){return this._senders=this._senders||[],this._senders.slice()};let n=e.RTCPeerConnection.prototype.addTrack;e.RTCPeerConnection.prototype.addTrack=function(e,r){let i=n.apply(this,arguments);return i||(i=t(this,e),this._senders.push(i)),i};let r=e.RTCPeerConnection.prototype.removeTrack;e.RTCPeerConnection.prototype.removeTrack=function(e){r.apply(this,arguments);let t=this._senders.indexOf(e);t!==-1&&this._senders.splice(t,1)}}let n=e.RTCPeerConnection.prototype.addStream;e.RTCPeerConnection.prototype.addStream=function(e){this._senders=this._senders||[],n.apply(this,[e]),e.getTracks().forEach(e=>{this._senders.push(t(this,e))})};let r=e.RTCPeerConnection.prototype.removeStream;e.RTCPeerConnection.prototype.removeStream=function(e){this._senders=this._senders||[],r.apply(this,[e]),e.getTracks().forEach(e=>{let t=this._senders.find(t=>t.track===e);t&&this._senders.splice(this._senders.indexOf(t),1)})}}else if(typeof e==`object`&&e.RTCPeerConnection&&`getSenders`in e.RTCPeerConnection.prototype&&`createDTMFSender`in e.RTCPeerConnection.prototype&&e.RTCRtpSender&&!(`dtmf`in e.RTCRtpSender.prototype)){let t=e.RTCPeerConnection.prototype.getSenders;e.RTCPeerConnection.prototype.getSenders=function(){let e=t.apply(this,[]);return e.forEach(e=>e._pc=this),e},Object.defineProperty(e.RTCRtpSender.prototype,`dtmf`,{get(){return this._dtmf===void 0&&(this.track.kind===`audio`?this._dtmf=this._pc.createDTMFSender(this.track):this._dtmf=null),this._dtmf}})}}function ac(e){if(!(typeof e==`object`&&e.RTCPeerConnection&&e.RTCRtpSender&&e.RTCRtpReceiver))return;if(!(`getStats`in e.RTCRtpSender.prototype)){let t=e.RTCPeerConnection.prototype.getSenders;t&&(e.RTCPeerConnection.prototype.getSenders=function(){let e=t.apply(this,[]);return e.forEach(e=>e._pc=this),e});let n=e.RTCPeerConnection.prototype.addTrack;n&&(e.RTCPeerConnection.prototype.addTrack=function(){let e=n.apply(this,arguments);return e._pc=this,e}),e.RTCRtpSender.prototype.getStats=function(){let e=this;return this._pc.getStats().then(t=>$s(t,e.track,!0))}}if(!(`getStats`in e.RTCRtpReceiver.prototype)){let t=e.RTCPeerConnection.prototype.getReceivers;t&&(e.RTCPeerConnection.prototype.getReceivers=function(){let e=t.apply(this,[]);return e.forEach(e=>e._pc=this),e}),Ws(e,`track`,e=>(e.receiver._pc=e.srcElement,e)),e.RTCRtpReceiver.prototype.getStats=function(){let e=this;return this._pc.getStats().then(t=>$s(t,e.track,!1))}}if(!(`getStats`in e.RTCRtpSender.prototype&&`getStats`in e.RTCRtpReceiver.prototype))return;let t=e.RTCPeerConnection.prototype.getStats;e.RTCPeerConnection.prototype.getStats=function(){if(arguments.length>0&&arguments[0]instanceof e.MediaStreamTrack){let e=arguments[0],t,n,r;return this.getSenders().forEach(n=>{n.track===e&&(t?r=!0:t=n)}),this.getReceivers().forEach(t=>(t.track===e&&(n?r=!0:n=t),t.track===e)),r||t&&n?Promise.reject(new DOMException(`There are more than one sender or receiver for the track.`,`InvalidAccessError`)):t?t.getStats():n?n.getStats():Promise.reject(new DOMException(`There is no sender or receiver for the track.`,`InvalidAccessError`))}return t.apply(this,arguments)}}function oc(e){e.RTCPeerConnection.prototype.getLocalStreams=function(){return this._shimmedLocalStreams=this._shimmedLocalStreams||{},Object.keys(this._shimmedLocalStreams).map(e=>this._shimmedLocalStreams[e][0])};let t=e.RTCPeerConnection.prototype.addTrack;e.RTCPeerConnection.prototype.addTrack=function(e,n){if(!n)return t.apply(this,arguments);this._shimmedLocalStreams=this._shimmedLocalStreams||{};let r=t.apply(this,arguments);return this._shimmedLocalStreams[n.id]?this._shimmedLocalStreams[n.id].indexOf(r)===-1&&this._shimmedLocalStreams[n.id].push(r):this._shimmedLocalStreams[n.id]=[n,r],r};let n=e.RTCPeerConnection.prototype.addStream;e.RTCPeerConnection.prototype.addStream=function(e){this._shimmedLocalStreams=this._shimmedLocalStreams||{},e.getTracks().forEach(e=>{if(this.getSenders().find(t=>t.track===e))throw new DOMException(`Track already exists.`,`InvalidAccessError`)});let t=this.getSenders();n.apply(this,arguments);let r=this.getSenders().filter(e=>t.indexOf(e)===-1);this._shimmedLocalStreams[e.id]=[e].concat(r)};let r=e.RTCPeerConnection.prototype.removeStream;e.RTCPeerConnection.prototype.removeStream=function(e){return this._shimmedLocalStreams=this._shimmedLocalStreams||{},delete this._shimmedLocalStreams[e.id],r.apply(this,arguments)};let i=e.RTCPeerConnection.prototype.removeTrack;e.RTCPeerConnection.prototype.removeTrack=function(e){return this._shimmedLocalStreams=this._shimmedLocalStreams||{},e&&Object.keys(this._shimmedLocalStreams).forEach(t=>{let n=this._shimmedLocalStreams[t].indexOf(e);n!==-1&&this._shimmedLocalStreams[t].splice(n,1),this._shimmedLocalStreams[t].length===1&&delete this._shimmedLocalStreams[t]}),i.apply(this,arguments)}}function sc(e,t){if(!e.RTCPeerConnection)return;if(e.RTCPeerConnection.prototype.addTrack&&t.version>=65)return oc(e);let n=e.RTCPeerConnection.prototype.getLocalStreams;e.RTCPeerConnection.prototype.getLocalStreams=function(){let e=n.apply(this);return this._reverseStreams=this._reverseStreams||{},e.map(e=>this._reverseStreams[e.id])};let r=e.RTCPeerConnection.prototype.addStream;e.RTCPeerConnection.prototype.addStream=function(t){if(this._streams=this._streams||{},this._reverseStreams=this._reverseStreams||{},t.getTracks().forEach(e=>{if(this.getSenders().find(t=>t.track===e))throw new DOMException(`Track already exists.`,`InvalidAccessError`)}),!this._reverseStreams[t.id]){let n=new e.MediaStream(t.getTracks());this._streams[t.id]=n,this._reverseStreams[n.id]=t,t=n}r.apply(this,[t])};let i=e.RTCPeerConnection.prototype.removeStream;e.RTCPeerConnection.prototype.removeStream=function(e){this._streams=this._streams||{},this._reverseStreams=this._reverseStreams||{},i.apply(this,[this._streams[e.id]||e]),delete this._reverseStreams[this._streams[e.id]?this._streams[e.id].id:e.id],delete this._streams[e.id]},e.RTCPeerConnection.prototype.addTrack=function(t,n){if(this.signalingState===`closed`)throw new DOMException(`The RTCPeerConnection's signalingState is 'closed'.`,`InvalidStateError`);let r=[].slice.call(arguments,1);if(r.length!==1||!r[0].getTracks().find(e=>e===t))throw new DOMException(`The adapter.js addTrack polyfill only supports a single stream which is associated with the specified track.`,`NotSupportedError`);if(this.getSenders().find(e=>e.track===t))throw new DOMException(`Track already exists.`,`InvalidAccessError`);this._streams=this._streams||{},this._reverseStreams=this._reverseStreams||{};let i=this._streams[n.id];if(i)i.addTrack(t),Promise.resolve().then(()=>{this.dispatchEvent(new Event(`negotiationneeded`))});else{let r=new e.MediaStream([t]);this._streams[n.id]=r,this._reverseStreams[r.id]=n,this.addStream(r)}return this.getSenders().find(e=>e.track===t)};function a(e,t){let n=t.sdp;return Object.keys(e._reverseStreams||[]).forEach(t=>{let r=e._reverseStreams[t],i=e._streams[r.id];n=n.replace(new RegExp(i.id,`g`),r.id)}),new RTCSessionDescription({type:t.type,sdp:n})}function o(e,t){let n=t.sdp;return Object.keys(e._reverseStreams||[]).forEach(t=>{let r=e._reverseStreams[t],i=e._streams[r.id];n=n.replace(new RegExp(r.id,`g`),i.id)}),new RTCSessionDescription({type:t.type,sdp:n})}[`createOffer`,`createAnswer`].forEach(function(t){let n=e.RTCPeerConnection.prototype[t],r={[t](){let e=arguments;return arguments.length&&typeof arguments[0]==`function`?n.apply(this,[t=>{let n=a(this,t);e[0].apply(null,[n])},t=>{e[1]&&e[1].apply(null,t)},arguments[2]]):n.apply(this,arguments).then(e=>a(this,e))}};e.RTCPeerConnection.prototype[t]=r[t]});let s=e.RTCPeerConnection.prototype.setLocalDescription;e.RTCPeerConnection.prototype.setLocalDescription=function(){return!arguments.length||!arguments[0].type||(arguments[0]=o(this,arguments[0])),s.apply(this,arguments)};let c=Object.getOwnPropertyDescriptor(e.RTCPeerConnection.prototype,`localDescription`);Object.defineProperty(e.RTCPeerConnection.prototype,`localDescription`,{get(){let e=c.get.apply(this);return e.type===``?e:a(this,e)}}),e.RTCPeerConnection.prototype.removeTrack=function(e){if(this.signalingState===`closed`)throw new DOMException(`The RTCPeerConnection's signalingState is 'closed'.`,`InvalidStateError`);if(!e._pc)throw new DOMException(`Argument 1 of RTCPeerConnection.removeTrack does not implement interface RTCRtpSender.`,`TypeError`);if(e._pc!==this)throw new DOMException(`Sender was not created by this connection.`,`InvalidAccessError`);this._streams=this._streams||{};let t;Object.keys(this._streams).forEach(n=>{this._streams[n].getTracks().find(t=>e.track===t)&&(t=this._streams[n])}),t&&(t.getTracks().length===1?this.removeStream(this._reverseStreams[t.id]):t.removeTrack(e.track),this.dispatchEvent(new Event(`negotiationneeded`)))}}function cc(e,t){!e.RTCPeerConnection&&e.webkitRTCPeerConnection&&(e.RTCPeerConnection=e.webkitRTCPeerConnection),e.RTCPeerConnection&&t.version<53&&[`setLocalDescription`,`setRemoteDescription`,`addIceCandidate`].forEach(function(t){let n=e.RTCPeerConnection.prototype[t],r={[t](){return arguments[0]=new(t===`addIceCandidate`?e.RTCIceCandidate:e.RTCSessionDescription)(arguments[0]),n.apply(this,arguments)}};e.RTCPeerConnection.prototype[t]=r[t]})}function lc(e,t){Ws(e,`negotiationneeded`,e=>{let n=e.target;if(!((t.version<72||n.getConfiguration&&n.getConfiguration().sdpSemantics===`plan-b`)&&n.signalingState!==`stable`))return e})}var uc=Object.freeze({__proto__:null,fixNegotiationNeeded:lc,shimAddTrackRemoveTrack:sc,shimAddTrackRemoveTrackWithNative:oc,shimGetSendersWithDtmf:ic,shimGetUserMedia:tc,shimMediaStream:nc,shimOnTrack:rc,shimPeerConnection:cc,shimSenderReceiverGetStats:ac});function dc(e,t){let n=e&&e.navigator,r=e&&e.MediaStreamTrack;if(n.getUserMedia=function(e,t,r){Js(`navigator.getUserMedia`,`navigator.mediaDevices.getUserMedia`),n.mediaDevices.getUserMedia(e).then(t,r)},!(t.version>55&&`autoGainControl`in n.mediaDevices.getSupportedConstraints())){let e=function(e,t,n){t in e&&!(n in e)&&(e[n]=e[t],delete e[t])},t=n.mediaDevices.getUserMedia.bind(n.mediaDevices);if(n.mediaDevices.getUserMedia=function(n){return typeof n==`object`&&typeof n.audio==`object`&&(n=JSON.parse(JSON.stringify(n)),e(n.audio,`autoGainControl`,`mozAutoGainControl`),e(n.audio,`noiseSuppression`,`mozNoiseSuppression`)),t(n)},r&&r.prototype.getSettings){let t=r.prototype.getSettings;r.prototype.getSettings=function(){let n=t.apply(this,arguments);return e(n,`mozAutoGainControl`,`autoGainControl`),e(n,`mozNoiseSuppression`,`noiseSuppression`),n}}if(r&&r.prototype.applyConstraints){let t=r.prototype.applyConstraints;r.prototype.applyConstraints=function(n){return this.kind===`audio`&&typeof n==`object`&&(n=JSON.parse(JSON.stringify(n)),e(n,`autoGainControl`,`mozAutoGainControl`),e(n,`noiseSuppression`,`mozNoiseSuppression`)),t.apply(this,[n])}}}}function fc(e,t){e.navigator.mediaDevices&&`getDisplayMedia`in e.navigator.mediaDevices||e.navigator.mediaDevices&&(e.navigator.mediaDevices.getDisplayMedia=function(n){if(!(n&&n.video)){let e=new DOMException(`getDisplayMedia without video constraints is undefined`);return e.name=`NotFoundError`,e.code=8,Promise.reject(e)}return n.video===!0?n.video={mediaSource:t}:n.video.mediaSource=t,e.navigator.mediaDevices.getUserMedia(n)})}function pc(e){typeof e==`object`&&e.RTCTrackEvent&&`receiver`in e.RTCTrackEvent.prototype&&!(`transceiver`in e.RTCTrackEvent.prototype)&&Object.defineProperty(e.RTCTrackEvent.prototype,`transceiver`,{get(){return{receiver:this.receiver}}})}function mc(e,t){if(typeof e!=`object`||!(e.RTCPeerConnection||e.mozRTCPeerConnection))return;!e.RTCPeerConnection&&e.mozRTCPeerConnection&&(e.RTCPeerConnection=e.mozRTCPeerConnection),t.version<53&&[`setLocalDescription`,`setRemoteDescription`,`addIceCandidate`].forEach(function(t){let n=e.RTCPeerConnection.prototype[t],r={[t](){return arguments[0]=new(t===`addIceCandidate`?e.RTCIceCandidate:e.RTCSessionDescription)(arguments[0]),n.apply(this,arguments)}};e.RTCPeerConnection.prototype[t]=r[t]});let n={inboundrtp:`inbound-rtp`,outboundrtp:`outbound-rtp`,candidatepair:`candidate-pair`,localcandidate:`local-candidate`,remotecandidate:`remote-candidate`},r=e.RTCPeerConnection.prototype.getStats;e.RTCPeerConnection.prototype.getStats=function(){let[e,i,a]=arguments;return r.apply(this,[e||null]).then(e=>{if(t.version<53&&!i)try{e.forEach(e=>{e.type=n[e.type]||e.type})}catch(t){if(t.name!==`TypeError`)throw t;e.forEach((t,r)=>{e.set(r,Object.assign({},t,{type:n[t.type]||t.type}))})}return e}).then(i,a)}}function hc(e){if(!(typeof e==`object`&&e.RTCPeerConnection&&e.RTCRtpSender)||e.RTCRtpSender&&`getStats`in e.RTCRtpSender.prototype)return;let t=e.RTCPeerConnection.prototype.getSenders;t&&(e.RTCPeerConnection.prototype.getSenders=function(){let e=t.apply(this,[]);return e.forEach(e=>e._pc=this),e});let n=e.RTCPeerConnection.prototype.addTrack;n&&(e.RTCPeerConnection.prototype.addTrack=function(){let e=n.apply(this,arguments);return e._pc=this,e}),e.RTCRtpSender.prototype.getStats=function(){return this.track?this._pc.getStats(this.track):Promise.resolve(new Map)}}function gc(e){if(!(typeof e==`object`&&e.RTCPeerConnection&&e.RTCRtpSender)||e.RTCRtpSender&&`getStats`in e.RTCRtpReceiver.prototype)return;let t=e.RTCPeerConnection.prototype.getReceivers;t&&(e.RTCPeerConnection.prototype.getReceivers=function(){let e=t.apply(this,[]);return e.forEach(e=>e._pc=this),e}),Ws(e,`track`,e=>(e.receiver._pc=e.srcElement,e)),e.RTCRtpReceiver.prototype.getStats=function(){return this._pc.getStats(this.track)}}function _c(e){!e.RTCPeerConnection||`removeStream`in e.RTCPeerConnection.prototype||(e.RTCPeerConnection.prototype.removeStream=function(e){Js(`removeStream`,`removeTrack`),this.getSenders().forEach(t=>{t.track&&e.getTracks().includes(t.track)&&this.removeTrack(t)})})}function vc(e){e.DataChannel&&!e.RTCDataChannel&&(e.RTCDataChannel=e.DataChannel)}function yc(e){if(!(typeof e==`object`&&e.RTCPeerConnection))return;let t=e.RTCPeerConnection.prototype.addTransceiver;t&&(e.RTCPeerConnection.prototype.addTransceiver=function(){this.setParametersPromises=[];let e=arguments[1]&&arguments[1].sendEncodings;e===void 0&&(e=[]),e=[...e];let n=e.length>0;n&&e.forEach(e=>{if(`rid`in e&&!/^[a-z0-9]{0,16}$/i.test(e.rid))throw TypeError(`Invalid RID value provided.`);if(`scaleResolutionDownBy`in e&&!(parseFloat(e.scaleResolutionDownBy)>=1))throw RangeError(`scale_resolution_down_by must be >= 1.0`);if(`maxFramerate`in e&&!(parseFloat(e.maxFramerate)>=0))throw RangeError(`max_framerate must be >= 0.0`)});let r=t.apply(this,arguments);if(n){let{sender:t}=r,n=t.getParameters();(!(`encodings`in n)||n.encodings.length===1&&Object.keys(n.encodings[0]).length===0)&&(n.encodings=e,t.sendEncodings=e,this.setParametersPromises.push(t.setParameters(n).then(()=>{delete t.sendEncodings}).catch(()=>{delete t.sendEncodings})))}return r})}function bc(e){if(!(typeof e==`object`&&e.RTCRtpSender))return;let t=e.RTCRtpSender.prototype.getParameters;t&&(e.RTCRtpSender.prototype.getParameters=function(){let e=t.apply(this,arguments);return`encodings`in e||(e.encodings=[].concat(this.sendEncodings||[{}])),e})}function xc(e){if(!(typeof e==`object`&&e.RTCPeerConnection))return;let t=e.RTCPeerConnection.prototype.createOffer;e.RTCPeerConnection.prototype.createOffer=function(){return this.setParametersPromises&&this.setParametersPromises.length?Promise.all(this.setParametersPromises).then(()=>t.apply(this,arguments)).finally(()=>{this.setParametersPromises=[]}):t.apply(this,arguments)}}function Sc(e){if(!(typeof e==`object`&&e.RTCPeerConnection))return;let t=e.RTCPeerConnection.prototype.createAnswer;e.RTCPeerConnection.prototype.createAnswer=function(){return this.setParametersPromises&&this.setParametersPromises.length?Promise.all(this.setParametersPromises).then(()=>t.apply(this,arguments)).finally(()=>{this.setParametersPromises=[]}):t.apply(this,arguments)}}var Cc=Object.freeze({__proto__:null,shimAddTransceiver:yc,shimCreateAnswer:Sc,shimCreateOffer:xc,shimGetDisplayMedia:fc,shimGetParameters:bc,shimGetUserMedia:dc,shimOnTrack:pc,shimPeerConnection:mc,shimRTCDataChannel:vc,shimReceiverGetStats:gc,shimRemoveStream:_c,shimSenderGetStats:hc});function wc(e){if(!(typeof e!=`object`||!e.RTCPeerConnection)){if(`getLocalStreams`in e.RTCPeerConnection.prototype||(e.RTCPeerConnection.prototype.getLocalStreams=function(){return this._localStreams||=[],this._localStreams}),!(`addStream`in e.RTCPeerConnection.prototype)){let t=e.RTCPeerConnection.prototype.addTrack;e.RTCPeerConnection.prototype.addStream=function(e){this._localStreams||=[],this._localStreams.includes(e)||this._localStreams.push(e),e.getAudioTracks().forEach(n=>t.call(this,n,e)),e.getVideoTracks().forEach(n=>t.call(this,n,e))},e.RTCPeerConnection.prototype.addTrack=function(e){for(var n=arguments.length,r=Array(n>1?n-1:0),i=1;i<n;i++)r[i-1]=arguments[i];return r&&r.forEach(e=>{this._localStreams?this._localStreams.includes(e)||this._localStreams.push(e):this._localStreams=[e]}),t.apply(this,arguments)}}`removeStream`in e.RTCPeerConnection.prototype||(e.RTCPeerConnection.prototype.removeStream=function(e){this._localStreams||=[];let t=this._localStreams.indexOf(e);if(t===-1)return;this._localStreams.splice(t,1);let n=e.getTracks();this.getSenders().forEach(e=>{n.includes(e.track)&&this.removeTrack(e)})})}}function Tc(e){if(!(typeof e!=`object`||!e.RTCPeerConnection)&&(`getRemoteStreams`in e.RTCPeerConnection.prototype||(e.RTCPeerConnection.prototype.getRemoteStreams=function(){return this._remoteStreams?this._remoteStreams:[]}),!(`onaddstream`in e.RTCPeerConnection.prototype))){Object.defineProperty(e.RTCPeerConnection.prototype,`onaddstream`,{get(){return this._onaddstream},set(e){this._onaddstream&&(this.removeEventListener(`addstream`,this._onaddstream),this.removeEventListener(`track`,this._onaddstreampoly)),this.addEventListener(`addstream`,this._onaddstream=e),this.addEventListener(`track`,this._onaddstreampoly=e=>{e.streams.forEach(e=>{if(this._remoteStreams||=[],this._remoteStreams.includes(e))return;this._remoteStreams.push(e);let t=new Event(`addstream`);t.stream=e,this.dispatchEvent(t)})})}});let t=e.RTCPeerConnection.prototype.setRemoteDescription;e.RTCPeerConnection.prototype.setRemoteDescription=function(){let e=this;return this._onaddstreampoly||this.addEventListener(`track`,this._onaddstreampoly=function(t){t.streams.forEach(t=>{if(e._remoteStreams||=[],e._remoteStreams.indexOf(t)>=0)return;e._remoteStreams.push(t);let n=new Event(`addstream`);n.stream=t,e.dispatchEvent(n)})}),t.apply(e,arguments)}}}function Ec(e){if(typeof e!=`object`||!e.RTCPeerConnection)return;let t=e.RTCPeerConnection.prototype,n=t.createOffer,r=t.createAnswer,i=t.setLocalDescription,a=t.setRemoteDescription,o=t.addIceCandidate;t.createOffer=function(e,t){let r=arguments.length>=2?arguments[2]:arguments[0],i=n.apply(this,[r]);return t?(i.then(e,t),Promise.resolve()):i},t.createAnswer=function(e,t){let n=arguments.length>=2?arguments[2]:arguments[0],i=r.apply(this,[n]);return t?(i.then(e,t),Promise.resolve()):i};let s=function(e,t,n){let r=i.apply(this,[e]);return n?(r.then(t,n),Promise.resolve()):r};t.setLocalDescription=s,s=function(e,t,n){let r=a.apply(this,[e]);return n?(r.then(t,n),Promise.resolve()):r},t.setRemoteDescription=s,s=function(e,t,n){let r=o.apply(this,[e]);return n?(r.then(t,n),Promise.resolve()):r},t.addIceCandidate=s}function Dc(e){let t=e&&e.navigator;if(t.mediaDevices&&t.mediaDevices.getUserMedia){let e=t.mediaDevices,n=e.getUserMedia.bind(e);t.mediaDevices.getUserMedia=e=>n(Oc(e))}!t.getUserMedia&&t.mediaDevices&&t.mediaDevices.getUserMedia&&(t.getUserMedia=function(e,n,r){t.mediaDevices.getUserMedia(e).then(n,r)}.bind(t))}function Oc(e){return e&&e.video!==void 0?Object.assign({},e,{video:Zs(e.video)}):e}function kc(e){if(!e.RTCPeerConnection)return;let t=e.RTCPeerConnection;e.RTCPeerConnection=function(e,n){if(e&&e.iceServers){let t=[];for(let n=0;n<e.iceServers.length;n++){let r=e.iceServers[n];r.urls===void 0&&r.url?(Js(`RTCIceServer.url`,`RTCIceServer.urls`),r=JSON.parse(JSON.stringify(r)),r.urls=r.url,delete r.url,t.push(r)):t.push(e.iceServers[n])}e.iceServers=t}return new t(e,n)},e.RTCPeerConnection.prototype=t.prototype,`generateCertificate`in t&&Object.defineProperty(e.RTCPeerConnection,`generateCertificate`,{get(){return t.generateCertificate}})}function Ac(e){typeof e==`object`&&e.RTCTrackEvent&&`receiver`in e.RTCTrackEvent.prototype&&!(`transceiver`in e.RTCTrackEvent.prototype)&&Object.defineProperty(e.RTCTrackEvent.prototype,`transceiver`,{get(){return{receiver:this.receiver}}})}function jc(e){let t=e.RTCPeerConnection.prototype.createOffer;e.RTCPeerConnection.prototype.createOffer=function(e){if(e){e.offerToReceiveAudio!==void 0&&(e.offerToReceiveAudio=!!e.offerToReceiveAudio);let t=this.getTransceivers().find(e=>e.receiver.track.kind===`audio`);e.offerToReceiveAudio===!1&&t?t.direction===`sendrecv`?t.setDirection?t.setDirection(`sendonly`):t.direction=`sendonly`:t.direction===`recvonly`&&(t.setDirection?t.setDirection(`inactive`):t.direction=`inactive`):e.offerToReceiveAudio===!0&&!t&&this.addTransceiver(`audio`,{direction:`recvonly`}),e.offerToReceiveVideo!==void 0&&(e.offerToReceiveVideo=!!e.offerToReceiveVideo);let n=this.getTransceivers().find(e=>e.receiver.track.kind===`video`);e.offerToReceiveVideo===!1&&n?n.direction===`sendrecv`?n.setDirection?n.setDirection(`sendonly`):n.direction=`sendonly`:n.direction===`recvonly`&&(n.setDirection?n.setDirection(`inactive`):n.direction=`inactive`):e.offerToReceiveVideo===!0&&!n&&this.addTransceiver(`video`,{direction:`recvonly`})}return t.apply(this,arguments)}}function Mc(e){typeof e!=`object`||e.AudioContext||(e.AudioContext=e.webkitAudioContext)}var Nc=Object.freeze({__proto__:null,shimAudioContext:Mc,shimCallbacksAPI:Ec,shimConstraints:Oc,shimCreateOfferLegacy:jc,shimGetUserMedia:Dc,shimLocalStreamsAPI:wc,shimRTCIceServerUrls:kc,shimRemoteStreamsAPI:Tc,shimTrackEventTransceiver:Ac}),Pc={exports:{}},Fc;function Ic(){return Fc?Pc.exports:(Fc=1,(function(e){let t={};t.generateIdentifier=function(){return Math.random().toString(36).substring(2,12)},t.localCName=t.generateIdentifier(),t.splitLines=function(e){return e.trim().split(`
|
|
32
32
|
`).map(e=>e.trim())},t.splitSections=function(e){return e.split(`
|
|
33
33
|
m=`).map((e,t)=>(t>0?`m=`+e:e).trim()+`\r
|
|
34
34
|
`)},t.getDescription=function(e){let n=t.splitSections(e);return n&&n[0]},t.getMediaSections=function(e){let n=t.splitSections(e);return n.shift(),n},t.matchPrefix=function(e,n){return t.splitLines(e).filter(e=>e.indexOf(n)===0)},t.parseCandidate=function(e){let t;t=e.indexOf(`a=candidate:`)===0?e.substring(12).split(` `):e.substring(10).split(` `);let n={foundation:t[0],component:{1:`rtp`,2:`rtcp`}[t[1]]||t[1],protocol:t[2].toLowerCase(),priority:parseInt(t[3],10),ip:t[4],address:t[4],port:parseInt(t[5],10),type:t[7]};for(let e=8;e<t.length;e+=2)switch(t[e]){case`raddr`:n.relatedAddress=t[e+1];break;case`rport`:n.relatedPort=parseInt(t[e+1],10);break;case`tcptype`:n.tcpType=t[e+1];break;case`ufrag`:n.ufrag=t[e+1],n.usernameFragment=t[e+1];break;default:n[t[e]]===void 0&&(n[t[e]]=t[e+1]);break}return n},t.writeCandidate=function(e){let t=[];t.push(e.foundation);let n=e.component;n===`rtp`?t.push(1):n===`rtcp`?t.push(2):t.push(n),t.push(e.protocol.toUpperCase()),t.push(e.priority),t.push(e.address||e.ip),t.push(e.port);let r=e.type;return t.push(`typ`),t.push(r),r!==`host`&&e.relatedAddress&&e.relatedPort&&(t.push(`raddr`),t.push(e.relatedAddress),t.push(`rport`),t.push(e.relatedPort)),e.tcpType&&e.protocol.toLowerCase()===`tcp`&&(t.push(`tcptype`),t.push(e.tcpType)),(e.usernameFragment||e.ufrag)&&(t.push(`ufrag`),t.push(e.usernameFragment||e.ufrag)),`candidate:`+t.join(` `)},t.parseIceOptions=function(e){return e.substring(14).split(` `)},t.parseRtpMap=function(e){let t=e.substring(9).split(` `),n={payloadType:parseInt(t.shift(),10)};return t=t[0].split(`/`),n.name=t[0],n.clockRate=parseInt(t[1],10),n.channels=t.length===3?parseInt(t[2],10):1,n.numChannels=n.channels,n},t.writeRtpMap=function(e){let t=e.payloadType;e.preferredPayloadType!==void 0&&(t=e.preferredPayloadType);let n=e.channels||e.numChannels||1;return`a=rtpmap:`+t+` `+e.name+`/`+e.clockRate+(n===1?``:`/`+n)+`\r
|
|
@@ -59,12 +59,12 @@ a=ice-pwd:`+e.password+`\r
|
|
|
59
59
|
o=`+(r||`thisisadapterortc`)+` `+i+` `+a+` IN IP4 127.0.0.1\r
|
|
60
60
|
s=-\r
|
|
61
61
|
t=0 0\r
|
|
62
|
-
`},t.getDirection=function(e,n){let r=t.splitLines(e);for(let e=0;e<r.length;e++)switch(r[e]){case`a=sendrecv`:case`a=sendonly`:case`a=recvonly`:case`a=inactive`:return r[e].substring(2)}return n?t.getDirection(n):`sendrecv`},t.getKind=function(e){return t.splitLines(e)[0].split(` `)[0].substring(2)},t.isRejected=function(e){return e.split(` `,2)[1]===`0`},t.parseMLine=function(e){let n=t.splitLines(e)[0].substring(2).split(` `);return{kind:n[0],port:parseInt(n[1],10),protocol:n[2],fmt:n.slice(3).join(` `)}},t.parseOLine=function(e){let n=t.matchPrefix(e,`o=`)[0].substring(2).split(` `);return{username:n[0],sessionId:n[1],sessionVersion:parseInt(n[2],10),netType:n[3],addressType:n[4],address:n[5]}},t.isValidSDP=function(e){if(typeof e!=`string`||e.length===0)return!1;let n=t.splitLines(e);for(let e=0;e<n.length;e++)if(n[e].length<2||n[e].charAt(1)!==`=`)return!1;return!0},e.exports=t})(
|
|
62
|
+
`},t.getDirection=function(e,n){let r=t.splitLines(e);for(let e=0;e<r.length;e++)switch(r[e]){case`a=sendrecv`:case`a=sendonly`:case`a=recvonly`:case`a=inactive`:return r[e].substring(2)}return n?t.getDirection(n):`sendrecv`},t.getKind=function(e){return t.splitLines(e)[0].split(` `)[0].substring(2)},t.isRejected=function(e){return e.split(` `,2)[1]===`0`},t.parseMLine=function(e){let n=t.splitLines(e)[0].substring(2).split(` `);return{kind:n[0],port:parseInt(n[1],10),protocol:n[2],fmt:n.slice(3).join(` `)}},t.parseOLine=function(e){let n=t.matchPrefix(e,`o=`)[0].substring(2).split(` `);return{username:n[0],sessionId:n[1],sessionVersion:parseInt(n[2],10),netType:n[3],addressType:n[4],address:n[5]}},t.isValidSDP=function(e){if(typeof e!=`string`||e.length===0)return!1;let n=t.splitLines(e);for(let e=0;e<n.length;e++)if(n[e].length<2||n[e].charAt(1)!==`=`)return!1;return!0},e.exports=t})(Pc),Pc.exports)}var Lc=Ic(),Rc=vs(Lc),zc=or({__proto__:null,default:Rc},[Lc]);function Bc(e){if(!e.RTCIceCandidate||e.RTCIceCandidate&&`foundation`in e.RTCIceCandidate.prototype)return;let t=e.RTCIceCandidate;e.RTCIceCandidate=function(e){if(typeof e==`object`&&e.candidate&&e.candidate.indexOf(`a=`)===0&&(e=JSON.parse(JSON.stringify(e)),e.candidate=e.candidate.substring(2)),e.candidate&&e.candidate.length){let n=new t(e),r=Rc.parseCandidate(e.candidate);for(let e in r)e in n||Object.defineProperty(n,e,{value:r[e]});return n.toJSON=function(){return{candidate:n.candidate,sdpMid:n.sdpMid,sdpMLineIndex:n.sdpMLineIndex,usernameFragment:n.usernameFragment}},n}return new t(e)},e.RTCIceCandidate.prototype=t.prototype,Ws(e,`icecandidate`,t=>(t.candidate&&Object.defineProperty(t,`candidate`,{value:new e.RTCIceCandidate(t.candidate),writable:`false`}),t))}function Vc(e){!e.RTCIceCandidate||e.RTCIceCandidate&&`relayProtocol`in e.RTCIceCandidate.prototype||Ws(e,`icecandidate`,e=>{if(e.candidate){let t=Rc.parseCandidate(e.candidate.candidate);t.type===`relay`&&(e.candidate.relayProtocol={0:`tls`,1:`tcp`,2:`udp`}[t.priority>>24])}return e})}function Hc(e,t){if(!e.RTCPeerConnection)return;`sctp`in e.RTCPeerConnection.prototype||Object.defineProperty(e.RTCPeerConnection.prototype,`sctp`,{get(){return this._sctp===void 0?null:this._sctp}});let n=function(e){if(!e||!e.sdp)return!1;let t=Rc.splitSections(e.sdp);return t.shift(),t.some(e=>{let t=Rc.parseMLine(e);return t&&t.kind===`application`&&t.protocol.indexOf(`SCTP`)!==-1})},r=function(e){let t=e.sdp.match(/mozilla...THIS_IS_SDPARTA-(\d+)/);if(t===null||t.length<2)return-1;let n=parseInt(t[1],10);return n===n?n:-1},i=function(e){let n=65536;return t.browser===`firefox`&&(n=t.version<57?e===-1?16384:2147483637:t.version<60?t.version===57?65535:65536:2147483637),n},a=function(e,n){let r=65536;t.browser===`firefox`&&t.version===57&&(r=65535);let i=Rc.matchPrefix(e.sdp,`a=max-message-size:`);return i.length>0?r=parseInt(i[0].substring(19),10):t.browser===`firefox`&&n!==-1&&(r=2147483637),r},o=e.RTCPeerConnection.prototype.setRemoteDescription;e.RTCPeerConnection.prototype.setRemoteDescription=function(){if(this._sctp=null,t.browser===`chrome`&&t.version>=76){let{sdpSemantics:e}=this.getConfiguration();e===`plan-b`&&Object.defineProperty(this,`sctp`,{get(){return this._sctp===void 0?null:this._sctp},enumerable:!0,configurable:!0})}if(n(arguments[0])){let e=r(arguments[0]),t=i(e),n=a(arguments[0],e),o;o=t===0&&n===0?1/0:t===0||n===0?Math.max(t,n):Math.min(t,n);let s={};Object.defineProperty(s,`maxMessageSize`,{get(){return o}}),this._sctp=s}return o.apply(this,arguments)}}function Uc(e){if(!(e.RTCPeerConnection&&`createDataChannel`in e.RTCPeerConnection.prototype))return;function t(e,t){let n=e.send;e.send=function(){let r=arguments[0],i=r.length||r.size||r.byteLength;if(e.readyState===`open`&&t.sctp&&i>t.sctp.maxMessageSize)throw TypeError(`Message too large (can send a maximum of `+t.sctp.maxMessageSize+` bytes)`);return n.apply(e,arguments)}}let n=e.RTCPeerConnection.prototype.createDataChannel;e.RTCPeerConnection.prototype.createDataChannel=function(){let e=n.apply(this,arguments);return t(e,this),e},Ws(e,`datachannel`,e=>(t(e.channel,e.target),e))}function Wc(e){if(!e.RTCPeerConnection||`connectionState`in e.RTCPeerConnection.prototype)return;let t=e.RTCPeerConnection.prototype;Object.defineProperty(t,`connectionState`,{get(){return{completed:`connected`,checking:`connecting`}[this.iceConnectionState]||this.iceConnectionState},enumerable:!0,configurable:!0}),Object.defineProperty(t,`onconnectionstatechange`,{get(){return this._onconnectionstatechange||null},set(e){this._onconnectionstatechange&&(this.removeEventListener(`connectionstatechange`,this._onconnectionstatechange),delete this._onconnectionstatechange),e&&this.addEventListener(`connectionstatechange`,this._onconnectionstatechange=e)},enumerable:!0,configurable:!0}),[`setLocalDescription`,`setRemoteDescription`].forEach(e=>{let n=t[e];t[e]=function(){return this._connectionstatechangepoly||(this._connectionstatechangepoly=e=>{let t=e.target;if(t._lastConnectionState!==t.connectionState){t._lastConnectionState=t.connectionState;let n=new Event(`connectionstatechange`,e);t.dispatchEvent(n)}return e},this.addEventListener(`iceconnectionstatechange`,this._connectionstatechangepoly)),n.apply(this,arguments)}})}function Gc(e,t){if(!e.RTCPeerConnection||t.browser===`chrome`&&t.version>=71||t.browser===`safari`&&t._safariVersion>=13.1)return;let n=e.RTCPeerConnection.prototype.setRemoteDescription;e.RTCPeerConnection.prototype.setRemoteDescription=function(t){if(t&&t.sdp&&t.sdp.indexOf(`
|
|
63
63
|
a=extmap-allow-mixed`)!==-1){let n=t.sdp.split(`
|
|
64
64
|
`).filter(e=>e.trim()!==`a=extmap-allow-mixed`).join(`
|
|
65
|
-
`);e.RTCSessionDescription&&t instanceof e.RTCSessionDescription?arguments[0]=new e.RTCSessionDescription({type:t.type,sdp:n}):t.sdp=n}return n.apply(this,arguments)}}function Gc(e,t){if(!(e.RTCPeerConnection&&e.RTCPeerConnection.prototype))return;let n=e.RTCPeerConnection.prototype.addIceCandidate;!n||n.length===0||(e.RTCPeerConnection.prototype.addIceCandidate=function(){return arguments[0]?(t.browser===`chrome`&&t.version<78||t.browser===`firefox`&&t.version<68||t.browser===`safari`)&&arguments[0]&&arguments[0].candidate===``?Promise.resolve():n.apply(this,arguments):(arguments[1]&&arguments[1].apply(null),Promise.resolve())})}function Kc(e,t){if(!(e.RTCPeerConnection&&e.RTCPeerConnection.prototype))return;let n=e.RTCPeerConnection.prototype.setLocalDescription;!n||n.length===0||(e.RTCPeerConnection.prototype.setLocalDescription=function(){let e=arguments[0]||{};if(typeof e!=`object`||e.type&&e.sdp)return n.apply(this,arguments);if(e={type:e.type,sdp:e.sdp},!e.type)switch(this.signalingState){case`stable`:case`have-local-offer`:case`have-remote-pranswer`:e.type=`offer`;break;default:e.type=`answer`;break}return e.sdp||e.type!==`offer`&&e.type!==`answer`?n.apply(this,[e]):(e.type===`offer`?this.createOffer:this.createAnswer).apply(this).then(e=>n.apply(this,[e]))})}var qc=Object.freeze({__proto__:null,removeExtmapAllowMixed:Wc,shimAddIceCandidateNullOrEmpty:Gc,shimConnectionState:Uc,shimMaxMessageSize:Vc,shimParameterlessSetLocalDescription:Kc,shimRTCIceCandidate:zc,shimRTCIceCandidateRelayProtocol:Bc,shimSendThrowTypeError:Hc});function Jc(){let{window:e}=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{},t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{shimChrome:!0,shimFirefox:!0,shimSafari:!0},n=Ks,r=Js(e),i={browserDetails:r,commonShim:qc,extractVersion:Hs,disableLog:Ws,disableWarnings:Gs,sdp:Rc};switch(r.browser){case`chrome`:if(!lc||!sc||!t.shimChrome)return n(`Chrome shim is not included in this adapter release.`),i;if(r.version===null)return n(`Chrome shim can not determine version, not shimming.`),i;n(`adapter.js shimming chrome.`),i.browserShim=lc,Gc(e,r),Kc(e),ec(e,r),tc(e),sc(e,r),nc(e),oc(e,r),rc(e),ic(e),cc(e,r),zc(e),Bc(e),Uc(e),Vc(e,r),Hc(e),Wc(e,r);break;case`firefox`:if(!Sc||!pc||!t.shimFirefox)return n(`Firefox shim is not included in this adapter release.`),i;n(`adapter.js shimming firefox.`),i.browserShim=Sc,Gc(e,r),Kc(e),uc(e,r),pc(e,r),fc(e),gc(e),mc(e),hc(e),_c(e),vc(e),yc(e),bc(e),xc(e),zc(e),Uc(e),Vc(e,r),Hc(e);break;case`safari`:if(!Mc||!t.shimSafari)return n(`Safari shim is not included in this adapter release.`),i;n(`adapter.js shimming safari.`),i.browserShim=Mc,Gc(e,r),Kc(e),Oc(e),Ac(e),Tc(e),Cc(e),wc(e),kc(e),Ec(e),jc(e),zc(e),Bc(e),Vc(e,r),Hc(e),Wc(e,r);break;default:n(`Unsupported browser!`);break}return i}Jc({window:typeof window>`u`?void 0:window});var Yc,Xc,Zc=class extends (Xc=Promise){constructor(e){super(e)}catch(e){return super.catch(e)}static reject(e){return super.reject(e)}static all(e){return super.all(e)}static race(e){return super.race(e)}};Yc=Zc,Zc.resolve=e=>Reflect.get(Xc,`resolve`,Yc).call(Yc,e);var Qc=/version\/(\d+(\.?_?\d+)+)/i,$c;function el(e){let t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:!0;if(e===void 0&&typeof navigator>`u`)return;let n=(e??navigator.userAgent).toLowerCase();return($c===void 0||t)&&($c=tl.find(e=>{let{test:t}=e;return t.test(n)})?.describe(n)),$c}var tl=[{test:/firefox|iceweasel|fxios/i,describe(e){return{name:`Firefox`,version:nl(/(?:firefox|iceweasel|fxios)[\s/](\d+(\.?_?\d+)+)/i,e),os:e.toLowerCase().includes(`fxios`)?`iOS`:void 0,osVersion:rl(e)}}},{test:/chrom|crios|crmo/i,describe(e){return{name:`Chrome`,version:nl(/(?:chrome|chromium|crios|crmo)\/(\d+(\.?_?\d+)+)/i,e),os:e.toLowerCase().includes(`crios`)?`iOS`:void 0,osVersion:rl(e)}}},{test:/safari|applewebkit/i,describe(e){return{name:`Safari`,version:nl(Qc,e),os:e.includes(`mobile/`)?`iOS`:`macOS`,osVersion:rl(e)}}}];function nl(e,t){let n=arguments.length>2&&arguments[2]!==void 0?arguments[2]:1,r=t.match(e);return r&&r.length>=n&&r[n]||``}function rl(e){return e.includes(`mac os`)?nl(/\(.+?(\d+_\d+(:?_\d+)?)/,e,1).replace(/_/g,`.`):void 0}var il=`2.18.1`,al=class extends Error{constructor(e,t,n){super(t||`an error has occurred`),this.name=`LiveKitError`,this.code=e,n?.cause!==void 0&&(this.cause=n?.cause)}},ol=class extends al{},P;(function(e){e[e.NotAllowed=0]=`NotAllowed`,e[e.ServerUnreachable=1]=`ServerUnreachable`,e[e.InternalError=2]=`InternalError`,e[e.Cancelled=3]=`Cancelled`,e[e.LeaveRequest=4]=`LeaveRequest`,e[e.Timeout=5]=`Timeout`,e[e.WebSocket=6]=`WebSocket`,e[e.ServiceNotFound=7]=`ServiceNotFound`})(P||={});var F=class e extends ol{constructor(e,t,n,r){super(1,e),this.name=`ConnectionError`,this.status=n,this.reason=t,this.context=r,this.reasonName=P[t]}static notAllowed(t,n,r){return new e(t,P.NotAllowed,n,r)}static timeout(t){return new e(t,P.Timeout)}static leaveRequest(t,n){return new e(t,P.LeaveRequest,void 0,n)}static internal(t,n){return new e(t,P.InternalError,void 0,n)}static cancelled(t){return new e(t,P.Cancelled)}static serverUnreachable(t,n){return new e(t,P.ServerUnreachable,n)}static websocket(t,n,r){return new e(t,P.WebSocket,n,r)}static serviceNotFound(t,n){return new e(t,P.ServiceNotFound,void 0,n)}},sl=class extends al{constructor(e){super(21,e??`device is unsupported`),this.name=`DeviceUnsupportedError`}},cl=class extends al{constructor(e){super(20,e??`track is invalid`),this.name=`TrackInvalidError`}},ll=class extends al{constructor(e){super(10,e??`unsupported server`),this.name=`UnsupportedServer`}},I=class extends al{constructor(e){super(12,e??`unexpected connection state`),this.name=`UnexpectedConnectionState`}},ul=class extends al{constructor(e){super(13,e??`unable to negotiate`),this.name=`NegotiationError`}},dl=class extends al{constructor(e,t){super(15,e),this.name=`PublishTrackError`,this.status=t}},fl=class extends ol{constructor(e,t){super(15,e),this.name=`SignalRequestError`,this.reason=t,this.reasonName=typeof t==`string`?t:us[t]}},pl;(function(e){e[e.AlreadyOpened=0]=`AlreadyOpened`,e[e.AbnormalEnd=1]=`AbnormalEnd`,e[e.DecodeFailed=2]=`DecodeFailed`,e[e.LengthExceeded=3]=`LengthExceeded`,e[e.Incomplete=4]=`Incomplete`,e[e.HandlerAlreadyRegistered=7]=`HandlerAlreadyRegistered`,e[e.EncryptionTypeMismatch=8]=`EncryptionTypeMismatch`})(pl||={});var ml=class extends ol{constructor(e,t){super(16,e),this.name=`DataStreamError`,this.reason=t,this.reasonName=pl[t]}},hl=class extends al{constructor(e){super(18,e),this.name=`SignalReconnectError`}},gl;(function(e){e.PermissionDenied=`PermissionDenied`,e.NotFound=`NotFound`,e.DeviceInUse=`DeviceInUse`,e.Other=`Other`})(gl||={}),(function(e){function t(t){if(t&&`name`in t)return t.name===`NotFoundError`||t.name===`DevicesNotFoundError`?e.NotFound:t.name===`NotAllowedError`||t.name===`PermissionDeniedError`?e.PermissionDenied:t.name===`NotReadableError`||t.name===`TrackStartError`?e.DeviceInUse:e.Other}e.getFailure=t})(gl||={});var _l=class{};_l.setTimeout=function(){return setTimeout(...arguments)},_l.setInterval=function(){return setInterval(...arguments)},_l.clearTimeout=function(){return clearTimeout(...arguments)},_l.clearInterval=function(){return clearInterval(...arguments)};var L;(function(e){e.Connected=`connected`,e.Reconnecting=`reconnecting`,e.SignalReconnecting=`signalReconnecting`,e.Reconnected=`reconnected`,e.Disconnected=`disconnected`,e.ConnectionStateChanged=`connectionStateChanged`,e.Moved=`moved`,e.MediaDevicesChanged=`mediaDevicesChanged`,e.ParticipantConnected=`participantConnected`,e.ParticipantDisconnected=`participantDisconnected`,e.TrackPublished=`trackPublished`,e.TrackSubscribed=`trackSubscribed`,e.TrackSubscriptionFailed=`trackSubscriptionFailed`,e.TrackUnpublished=`trackUnpublished`,e.TrackUnsubscribed=`trackUnsubscribed`,e.TrackMuted=`trackMuted`,e.TrackUnmuted=`trackUnmuted`,e.LocalTrackPublished=`localTrackPublished`,e.LocalTrackUnpublished=`localTrackUnpublished`,e.LocalAudioSilenceDetected=`localAudioSilenceDetected`,e.ActiveSpeakersChanged=`activeSpeakersChanged`,e.ParticipantMetadataChanged=`participantMetadataChanged`,e.ParticipantNameChanged=`participantNameChanged`,e.ParticipantAttributesChanged=`participantAttributesChanged`,e.ParticipantActive=`participantActive`,e.RoomMetadataChanged=`roomMetadataChanged`,e.DataReceived=`dataReceived`,e.SipDTMFReceived=`sipDTMFReceived`,e.TranscriptionReceived=`transcriptionReceived`,e.ConnectionQualityChanged=`connectionQualityChanged`,e.TrackStreamStateChanged=`trackStreamStateChanged`,e.TrackSubscriptionPermissionChanged=`trackSubscriptionPermissionChanged`,e.TrackSubscriptionStatusChanged=`trackSubscriptionStatusChanged`,e.AudioPlaybackStatusChanged=`audioPlaybackChanged`,e.VideoPlaybackStatusChanged=`videoPlaybackChanged`,e.MediaDevicesError=`mediaDevicesError`,e.ParticipantPermissionsChanged=`participantPermissionsChanged`,e.SignalConnected=`signalConnected`,e.RecordingStatusChanged=`recordingStatusChanged`,e.ParticipantEncryptionStatusChanged=`participantEncryptionStatusChanged`,e.EncryptionError=`encryptionError`,e.DCBufferStatusChanged=`dcBufferStatusChanged`,e.ActiveDeviceChanged=`activeDeviceChanged`,e.ChatMessage=`chatMessage`,e.LocalTrackSubscribed=`localTrackSubscribed`,e.MetricsReceived=`metricsReceived`,e.DataTrackPublished=`dataTrackPublished`,e.DataTrackUnpublished=`dataTrackUnpublished`,e.LocalDataTrackPublished=`localDataTrackPublished`,e.LocalDataTrackUnpublished=`localDataTrackUnpublished`})(L||={});var R;(function(e){e.TrackPublished=`trackPublished`,e.TrackSubscribed=`trackSubscribed`,e.TrackSubscriptionFailed=`trackSubscriptionFailed`,e.TrackUnpublished=`trackUnpublished`,e.TrackUnsubscribed=`trackUnsubscribed`,e.TrackMuted=`trackMuted`,e.TrackUnmuted=`trackUnmuted`,e.LocalTrackPublished=`localTrackPublished`,e.LocalTrackUnpublished=`localTrackUnpublished`,e.LocalTrackCpuConstrained=`localTrackCpuConstrained`,e.LocalSenderCreated=`localSenderCreated`,e.ParticipantMetadataChanged=`participantMetadataChanged`,e.ParticipantNameChanged=`participantNameChanged`,e.DataReceived=`dataReceived`,e.SipDTMFReceived=`sipDTMFReceived`,e.TranscriptionReceived=`transcriptionReceived`,e.IsSpeakingChanged=`isSpeakingChanged`,e.ConnectionQualityChanged=`connectionQualityChanged`,e.TrackStreamStateChanged=`trackStreamStateChanged`,e.TrackSubscriptionPermissionChanged=`trackSubscriptionPermissionChanged`,e.TrackSubscriptionStatusChanged=`trackSubscriptionStatusChanged`,e.TrackCpuConstrained=`trackCpuConstrained`,e.MediaDevicesError=`mediaDevicesError`,e.AudioStreamAcquired=`audioStreamAcquired`,e.ParticipantPermissionsChanged=`participantPermissionsChanged`,e.PCTrackAdded=`pcTrackAdded`,e.AttributesChanged=`attributesChanged`,e.LocalTrackSubscribed=`localTrackSubscribed`,e.ChatMessage=`chatMessage`,e.Active=`active`})(R||={});var z;(function(e){e.TransportsCreated=`transportsCreated`,e.Connected=`connected`,e.Disconnected=`disconnected`,e.Resuming=`resuming`,e.Resumed=`resumed`,e.Restarting=`restarting`,e.Restarted=`restarted`,e.SignalResumed=`signalResumed`,e.SignalRestarted=`signalRestarted`,e.Closing=`closing`,e.MediaTrackAdded=`mediaTrackAdded`,e.ActiveSpeakersUpdate=`activeSpeakersUpdate`,e.DataPacketReceived=`dataPacketReceived`,e.RTPVideoMapUpdate=`rtpVideoMapUpdate`,e.DCBufferStatusChanged=`dcBufferStatusChanged`,e.ParticipantUpdate=`participantUpdate`,e.RoomUpdate=`roomUpdate`,e.SpeakersChanged=`speakersChanged`,e.StreamStateChanged=`streamStateChanged`,e.ConnectionQualityUpdate=`connectionQualityUpdate`,e.SubscriptionError=`subscriptionError`,e.SubscriptionPermissionUpdate=`subscriptionPermissionUpdate`,e.RemoteMute=`remoteMute`,e.SubscribedQualityUpdate=`subscribedQualityUpdate`,e.LocalTrackUnpublished=`localTrackUnpublished`,e.LocalTrackSubscribed=`localTrackSubscribed`,e.Offline=`offline`,e.SignalRequestResponse=`signalRequestResponse`,e.SignalConnected=`signalConnected`,e.RoomMoved=`roomMoved`,e.PublishDataTrackResponse=`publishDataTrackResponse`,e.UnPublishDataTrackResponse=`unPublishDataTrackResponse`,e.DataTrackSubscriberHandles=`dataTrackSubscriberHandles`,e.DataTrackPacketReceived=`dataTrackPacketReceived`,e.Joined=`joined`})(z||={});var B;(function(e){e.Message=`message`,e.Muted=`muted`,e.Unmuted=`unmuted`,e.Restarted=`restarted`,e.Ended=`ended`,e.Subscribed=`subscribed`,e.Unsubscribed=`unsubscribed`,e.CpuConstrained=`cpuConstrained`,e.UpdateSettings=`updateSettings`,e.UpdateSubscription=`updateSubscription`,e.AudioPlaybackStarted=`audioPlaybackStarted`,e.AudioPlaybackFailed=`audioPlaybackFailed`,e.AudioSilenceDetected=`audioSilenceDetected`,e.VisibilityChanged=`visibilityChanged`,e.VideoDimensionsChanged=`videoDimensionsChanged`,e.VideoPlaybackStarted=`videoPlaybackStarted`,e.VideoPlaybackFailed=`videoPlaybackFailed`,e.ElementAttached=`elementAttached`,e.ElementDetached=`elementDetached`,e.UpstreamPaused=`upstreamPaused`,e.UpstreamResumed=`upstreamResumed`,e.SubscriptionPermissionChanged=`subscriptionPermissionChanged`,e.SubscriptionStatusChanged=`subscriptionStatusChanged`,e.SubscriptionFailed=`subscriptionFailed`,e.TrackProcessorUpdate=`trackProcessorUpdate`,e.AudioTrackFeatureUpdate=`audioTrackFeatureUpdate`,e.TranscriptionReceived=`transcriptionReceived`,e.TimeSyncUpdate=`timeSyncUpdate`,e.PreConnectBufferFlushed=`preConnectBufferFlushed`})(B||={});function vl(e){return e===void 0?e:typeof structuredClone==`function`?typeof e==`object`&&e?structuredClone(Object.assign({},e)):structuredClone(e):JSON.parse(JSON.stringify(e))}var V=class{constructor(e,t,n,r,i){if(typeof e==`object`)this.width=e.width,this.height=e.height,this.aspectRatio=e.aspectRatio,this.encoding={maxBitrate:e.maxBitrate,maxFramerate:e.maxFramerate,priority:e.priority};else if(t!==void 0&&n!==void 0)this.width=e,this.height=t,this.aspectRatio=e/t,this.encoding={maxBitrate:n,maxFramerate:r,priority:i};else throw TypeError(`Unsupported options: provide at least width, height and maxBitrate`)}get resolution(){return{width:this.width,height:this.height,frameRate:this.encoding.maxFramerate,aspectRatio:this.aspectRatio}}},yl=[`vp8`,`h264`],bl=[`vp8`,`h264`,`vp9`,`av1`,`h265`];function xl(e){return!!yl.find(t=>t===e)}var Sl=xl,Cl;(function(e){e[e.PREFER_REGRESSION=0]=`PREFER_REGRESSION`,e[e.SIMULCAST=1]=`SIMULCAST`,e[e.REGRESSION=2]=`REGRESSION`})(Cl||={});var wl;(function(e){e.telephone={maxBitrate:12e3},e.speech={maxBitrate:24e3},e.music={maxBitrate:48e3},e.musicStereo={maxBitrate:64e3},e.musicHighQuality={maxBitrate:96e3},e.musicHighQualityStereo={maxBitrate:128e3}})(wl||={});var Tl={h90:new V(160,90,9e4,20),h180:new V(320,180,16e4,20),h216:new V(384,216,18e4,20),h360:new V(640,360,45e4,20),h540:new V(960,540,8e5,25),h720:new V(1280,720,17e5,30),h1080:new V(1920,1080,3e6,30),h1440:new V(2560,1440,5e6,30),h2160:new V(3840,2160,8e6,30)},El={h120:new V(160,120,7e4,20),h180:new V(240,180,125e3,20),h240:new V(320,240,14e4,20),h360:new V(480,360,33e4,20),h480:new V(640,480,5e5,20),h540:new V(720,540,6e5,25),h720:new V(960,720,13e5,30),h1080:new V(1440,1080,23e5,30),h1440:new V(1920,1440,38e5,30)},Dl={h360fps3:new V(640,360,2e5,3,`medium`),h360fps15:new V(640,360,4e5,15,`medium`),h720fps5:new V(1280,720,8e5,5,`medium`),h720fps15:new V(1280,720,15e5,15,`medium`),h720fps30:new V(1280,720,2e6,30,`medium`),h1080fps15:new V(1920,1080,25e5,15,`medium`),h1080fps30:new V(1920,1080,5e6,30,`medium`),original:new V(0,0,7e6,30,`medium`)};function Ol(e,t,n){var r,i;let{optionsWithoutProcessor:a,audioProcessor:o,videoProcessor:s}=Bl(e??{}),c=t?.processor,l=n?.processor,u=a??{};return u.audio===!0&&(u.audio={}),u.video===!0&&(u.video={}),u.audio&&(kl(u.audio,t),(r=u.audio).deviceId??(r.deviceId={ideal:`default`}),(o||c)&&(u.audio.processor=o??c)),u.video&&(kl(u.video,n),(i=u.video).deviceId??(i.deviceId={ideal:`default`}),(s||l)&&(u.video.processor=s??l)),u}function kl(e,t){return Object.keys(t).forEach(n=>{e[n]===void 0&&(e[n]=t[n])}),e}function Al(e){var t,n;let r={};if(e.video)if(typeof e.video==`object`){let n={},i=n,a=e.video;Object.keys(a).forEach(e=>{switch(e){case`resolution`:kl(i,a.resolution);break;default:i[e]=a[e]}}),r.video=n,(t=r.video).deviceId??(t.deviceId={ideal:`default`})}else r.video=e.video?{deviceId:{ideal:`default`}}:!1;else r.video=!1;return e.audio?typeof e.audio==`object`?(r.audio=e.audio,(n=r.audio).deviceId??(n.deviceId={ideal:`default`})):r.audio={deviceId:{ideal:`default`}}:r.audio=!1,r}function jl(e){return N(this,arguments,void 0,function(e){let t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:200;return function*(){let n=Ml();if(n){let r=n.createAnalyser();r.fftSize=2048;let i=r.frequencyBinCount,a=new Uint8Array(i);n.createMediaStreamSource(new MediaStream([e.mediaStreamTrack])).connect(r),yield Ql(t),r.getByteTimeDomainData(a);let o=a.some(e=>e!==128&&e!==0);return n.close(),!o}return!1}()})}function Ml(){let e=typeof window<`u`&&(window.AudioContext||window.webkitAudioContext);if(e){let t=new e({latencyHint:`interactive`});if(t.state===`suspended`&&typeof window<`u`&&window.document?.body){let e=()=>N(this,void 0,void 0,function*(){var n;try{t.state===`suspended`&&(yield t.resume())}catch(e){console.warn(`Error trying to auto-resume audio context`,e)}finally{(n=window.document.body)==null||n.removeEventListener(`click`,e)}});t.addEventListener(`statechange`,()=>{var n;t.state===`closed`&&((n=window.document.body)==null||n.removeEventListener(`click`,e))}),window.document.body.addEventListener(`click`,e)}return t}}function Nl(e){return e===`audioinput`?U.Source.Microphone:e===`videoinput`?U.Source.Camera:U.Source.Unknown}function Pl(e){if(e===U.Source.Microphone)return`audioinput`;if(e===U.Source.Camera)return`videoinput`}function Fl(e){let t=e.video??!0;return e.resolution&&e.resolution.width>0&&e.resolution.height>0&&(t=typeof t==`boolean`?{}:t,t=cu()?Object.assign(Object.assign({},t),{width:{max:e.resolution.width},height:{max:e.resolution.height},frameRate:e.resolution.frameRate}):Object.assign(Object.assign({},t),{width:{ideal:e.resolution.width},height:{ideal:e.resolution.height},frameRate:e.resolution.frameRate})),{audio:e.audio??!1,video:t,controller:e.controller,selfBrowserSurface:e.selfBrowserSurface,surfaceSwitching:e.surfaceSwitching,systemAudio:e.systemAudio,preferCurrentTab:e.preferCurrentTab}}function Il(e){return e.split(`/`)[1].toLowerCase()}function Ll(e){let t=[];return e.forEach(e=>{e.track!==void 0&&t.push(new To({cid:e.track.mediaStreamID,track:e.trackInfo}))}),t}function H(e){return`mediaStreamTrack`in e?{trackID:e.sid,source:e.source,muted:e.isMuted,enabled:e.mediaStreamTrack.enabled,kind:e.kind,streamID:e.mediaStreamID,streamTrackID:e.mediaStreamTrack.id}:{trackID:e.trackSid,enabled:e.isEnabled,muted:e.isMuted,trackInfo:Object.assign({mimeType:e.mimeType,name:e.trackName,encrypted:e.isEncrypted,kind:e.kind,source:e.source},e.track?H(e.track):{})}}function Rl(){return typeof RTCRtpReceiver<`u`&&`getSynchronizationSources`in RTCRtpReceiver}function zl(e,t){e===void 0&&(e={}),t===void 0&&(t={});let n=[...Object.keys(t),...Object.keys(e)],r={};for(let i of n)e[i]!==t[i]&&(r[i]=t[i]??``);return r}function Bl(e){let t=Object.assign({},e),n,r;return typeof t.audio==`object`&&t.audio.processor&&(n=t.audio.processor,t.audio=Object.assign(Object.assign({},t.audio),{processor:void 0})),typeof t.video==`object`&&t.video.processor&&(r=t.video.processor,t.video=Object.assign(Object.assign({},t.video),{processor:void 0})),{audioProcessor:n,videoProcessor:r,optionsWithoutProcessor:vl(t)}}function Vl(e){switch(e){case A.CAMERA:return U.Source.Camera;case A.MICROPHONE:return U.Source.Microphone;case A.SCREEN_SHARE:return U.Source.ScreenShare;case A.SCREEN_SHARE_AUDIO:return U.Source.ScreenShareAudio;default:return U.Source.Unknown}}function Hl(e,t){return e.width*e.height<t.width*t.height}function Ul(e,t){return e.layers?.find(e=>e.quality===t)}var Wl=5e3,Gl=[],Kl;(function(e){e[e.LOW=0]=`LOW`,e[e.MEDIUM=1]=`MEDIUM`,e[e.HIGH=2]=`HIGH`})(Kl||={});var U=class e extends zs.EventEmitter{get streamState(){return this._streamState}setStreamState(e){this._streamState=e}constructor(t,n){let r=arguments.length>2&&arguments[2]!==void 0?arguments[2]:{};super(),this.attachedElements=[],this.isMuted=!1,this._streamState=e.StreamState.Active,this.isInBackground=!1,this._currentBitrate=0,this.log=M,this.appVisibilityChangedListener=()=>{this.backgroundTimeout&&clearTimeout(this.backgroundTimeout),document.visibilityState===`hidden`?this.backgroundTimeout=setTimeout(()=>this.handleAppVisibilityChanged(),Wl):this.handleAppVisibilityChanged()},this.log=Ts(r.loggerName??ws.Track),this.loggerContextCb=r.loggerContextCb,this.setMaxListeners(100),this.kind=n,this._mediaStreamTrack=t,this._mediaStreamID=t.id,this.source=e.Source.Unknown}get logContext(){return Object.assign(Object.assign({},this.loggerContextCb?.call(this)),H(this))}get currentBitrate(){return this._currentBitrate}get mediaStreamTrack(){return this._mediaStreamTrack}get mediaStreamID(){return this._mediaStreamID}attach(t){let n=`audio`;this.kind===e.Kind.Video&&(n=`video`),this.attachedElements.length===0&&this.kind===e.Kind.Video&&this.addAppVisibilityListener(),t||(n===`audio`&&(Gl.forEach(e=>{e.parentElement===null&&!t&&(t=e)}),t&&Gl.splice(Gl.indexOf(t),1)),t||=document.createElement(n)),this.attachedElements.includes(t)||this.attachedElements.push(t),ql(this.mediaStreamTrack,t);let r=t.srcObject.getTracks(),i=r.some(e=>e.kind===`audio`);return t.play().then(()=>{this.emit(i?B.AudioPlaybackStarted:B.VideoPlaybackStarted)}).catch(e=>{e.name===`NotAllowedError`?this.emit(i?B.AudioPlaybackFailed:B.VideoPlaybackFailed,e):e.name===`AbortError`?M.debug(`${i?`audio`:`video`} playback aborted, likely due to new play request`):M.warn(`could not playback ${i?`audio`:`video`}`,e),i&&t&&r.some(e=>e.kind===`video`)&&e.name===`NotAllowedError`&&(t.muted=!0,t.play().catch(()=>{}))}),this.emit(B.ElementAttached,t),t}detach(e){try{if(e){Jl(this.mediaStreamTrack,e);let t=this.attachedElements.indexOf(e);return t>=0&&(this.attachedElements.splice(t,1),this.recycleElement(e),this.emit(B.ElementDetached,e)),e}let t=[];return this.attachedElements.forEach(e=>{Jl(this.mediaStreamTrack,e),t.push(e),this.recycleElement(e),this.emit(B.ElementDetached,e)}),this.attachedElements=[],t}finally{this.attachedElements.length===0&&this.removeAppVisibilityListener()}}stop(){this.stopMonitor(),this._mediaStreamTrack.stop()}enable(){this._mediaStreamTrack.enabled=!0}disable(){this._mediaStreamTrack.enabled=!1}stopMonitor(){this.monitorInterval&&clearInterval(this.monitorInterval),this.timeSyncHandle&&cancelAnimationFrame(this.timeSyncHandle)}updateLoggerOptions(e){e.loggerName&&(this.log=Ts(e.loggerName)),e.loggerContextCb&&(this.loggerContextCb=e.loggerContextCb)}recycleElement(e){if(e instanceof HTMLAudioElement){let t=!0;e.pause(),Gl.forEach(e=>{e.parentElement||(t=!1)}),t&&Gl.push(e)}}handleAppVisibilityChanged(){return N(this,void 0,void 0,function*(){this.isInBackground=document.visibilityState===`hidden`,!this.isInBackground&&this.kind===e.Kind.Video&&setTimeout(()=>this.attachedElements.forEach(e=>e.play().catch(()=>{})),0)})}addAppVisibilityListener(){mu()?(this.isInBackground=document.visibilityState===`hidden`,document.addEventListener(`visibilitychange`,this.appVisibilityChangedListener)):this.isInBackground=!1}removeAppVisibilityListener(){mu()&&document.removeEventListener(`visibilitychange`,this.appVisibilityChangedListener)}};function ql(e,t){let n;n=t.srcObject instanceof MediaStream?t.srcObject:new MediaStream;let r;r=e.kind===`audio`?n.getAudioTracks():n.getVideoTracks(),r.includes(e)||(r.forEach(e=>{n.removeTrack(e)}),n.addTrack(e)),(!cu()||!(t instanceof HTMLVideoElement))&&(t.autoplay=!0),t.muted=n.getAudioTracks().length===0,t instanceof HTMLVideoElement&&(t.playsInline=!0),t.srcObject!==n&&(t.srcObject=n,(cu()||ou())&&t instanceof HTMLVideoElement&&setTimeout(()=>{t.srcObject=n,t.play().catch(()=>{})},0))}function Jl(e,t){if(t.srcObject instanceof MediaStream){let n=t.srcObject;n.removeTrack(e),n.getTracks().length>0?t.srcObject=n:t.srcObject=null}}(function(e){let t;(function(e){e.Audio=`audio`,e.Video=`video`,e.Unknown=`unknown`})(t=e.Kind||={});let n;(function(e){e.Camera=`camera`,e.Microphone=`microphone`,e.ScreenShare=`screen_share`,e.ScreenShareAudio=`screen_share_audio`,e.Unknown=`unknown`})(n=e.Source||={});let r;(function(e){e.Active=`active`,e.Paused=`paused`,e.Unknown=`unknown`})(r=e.StreamState||={});function i(e){switch(e){case t.Audio:return la.AUDIO;case t.Video:return la.VIDEO;default:return la.DATA}}e.kindToProto=i;function a(e){switch(e){case la.AUDIO:return t.Audio;case la.VIDEO:return t.Video;default:return t.Unknown}}e.kindFromProto=a;function o(e){switch(e){case n.Camera:return A.CAMERA;case n.Microphone:return A.MICROPHONE;case n.ScreenShare:return A.SCREEN_SHARE;case n.ScreenShareAudio:return A.SCREEN_SHARE_AUDIO;default:return A.UNKNOWN}}e.sourceToProto=o;function s(e){switch(e){case A.CAMERA:return n.Camera;case A.MICROPHONE:return n.Microphone;case A.SCREEN_SHARE:return n.ScreenShare;case A.SCREEN_SHARE_AUDIO:return n.ScreenShareAudio;default:return n.Unknown}}e.sourceFromProto=s;function c(e){switch(e){case co.ACTIVE:return r.Active;case co.PAUSED:return r.Paused;default:return r.Unknown}}e.streamStateFromProto=c})(U||={});var Yl=`|`,Xl=`https://aomediacodec.github.io/av1-rtp-spec/#dependency-descriptor-rtp-header-extension`;function Zl(e){let t=e.split(Yl);return t.length>1?[t[0],e.substr(t[0].length+1)]:[e,``]}function Ql(e){return new Zc(t=>_l.setTimeout(t,e))}function $l(){return`addTransceiver`in RTCPeerConnection.prototype}function eu(){return`addTrack`in RTCPeerConnection.prototype}function tu(){if(!(`getCapabilities`in RTCRtpSender)||cu()||ou())return!1;let e=RTCRtpSender.getCapabilities(`video`),t=!1;if(e){for(let n of e.codecs)if(n.mimeType.toLowerCase()===`video/av1`){t=!0;break}}return t}function nu(){if(!(`getCapabilities`in RTCRtpSender)||ou())return!1;if(cu()){let e=el();if(e?.version&&xu(e.version,`16`)<0||e?.os===`iOS`&&e?.osVersion&&xu(e.osVersion,`16`)<0)return!1}let e=RTCRtpSender.getCapabilities(`video`),t=!1;if(e){for(let n of e.codecs)if(n.mimeType.toLowerCase()===`video/vp9`){t=!0;break}}return t}function ru(e){return e===`av1`||e===`vp9`}function iu(e){return!document||lu()?!1:(e||=document.createElement(`audio`),`setSinkId`in e)}function au(){return typeof RTCPeerConnection>`u`?!1:$l()||eu()}function ou(){return el()?.name===`Firefox`}function su(){let e=el();return!!e&&e.name===`Chrome`&&e.os!==`iOS`}function cu(){return el()?.name===`Safari`}function lu(){let e=el();return e?.name===`Safari`||e?.os===`iOS`}function uu(){let e=el();return e?.name===`Safari`&&e.version.startsWith(`17.`)||e?.os===`iOS`&&!!e?.osVersion&&xu(e.osVersion,`17`)>=0}function du(e){return e||=el(),e?.name===`Safari`&&xu(e.version,`18.3`)>0||e?.os===`iOS`&&!!e?.osVersion&&xu(e.osVersion,`18.3`)>0}function fu(){return mu()?navigator.userAgentData?.mobile??/Tablet|iPad|Mobile|Android|BlackBerry/.test(navigator.userAgent):!1}function pu(){let e=el(),t=`17.2`;if(e)return e.name!==`Safari`&&e.os!==`iOS`||e.os===`iOS`&&e.osVersion&&xu(e.osVersion,t)>=0?!0:e.name===`Safari`&&xu(e.version,t)>=0}function mu(){return typeof document<`u`}function hu(){return navigator.product==`ReactNative`}function gu(e){return e.hostname.endsWith(`.livekit.cloud`)||e.hostname.endsWith(`.livekit.run`)}function _u(e){return gu(e)?e.hostname.split(`.`)[0]:null}function vu(){if(global&&global.LiveKitReactNativeGlobal)return global.LiveKitReactNativeGlobal}function yu(){if(!hu())return;let e=vu();if(e)return e.platform}function bu(){if(mu())return window.devicePixelRatio;if(hu()){let e=vu();if(e)return e.devicePixelRatio}return 1}function xu(e,t){let n=e.split(`.`),r=t.split(`.`),i=Math.min(n.length,r.length);for(let e=0;e<i;++e){let t=parseInt(n[e],10),a=parseInt(r[e],10);if(t>a)return 1;if(t<a)return-1;if(e===i-1&&t===a)return 0}return e===``&&t!==``?-1:t===``?1:n.length==r.length?0:n.length<r.length?-1:1}function Su(e){for(let t of e)t.target.handleResize(t)}function Cu(e){for(let t of e)t.target.handleVisibilityChanged(t)}var wu=null,Tu=()=>(wu||=new ResizeObserver(Su),wu),Eu=null,Du=()=>(Eu||=new IntersectionObserver(Cu,{root:null,rootMargin:`0px`}),Eu);function Ou(){let e=new Ja({sdk:Ya.JS,protocol:16,version:il});return hu()&&(e.os=yu()??``),e}function ku(){let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:16,t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:16,n=arguments.length>2&&arguments[2]!==void 0?arguments[2]:!1,r=arguments.length>3&&arguments[3]!==void 0?arguments[3]:!1,i=document.createElement(`canvas`);i.width=e,i.height=t;let a=i.getContext(`2d`);a?.fillRect(0,0,i.width,i.height),r&&a&&(a.beginPath(),a.arc(e/2,t/2,50,0,Math.PI*2,!0),a.closePath(),a.fillStyle=`grey`,a.fill());let[o]=i.captureStream().getTracks();if(!o)throw Error(`Could not get empty media stream video track`);return o.enabled=n,o}var Au;function ju(){if(!Au){let e=new AudioContext,t=e.createOscillator(),n=e.createGain();n.gain.setValueAtTime(0,0);let r=e.createMediaStreamDestination();if(t.connect(n),n.connect(r),t.start(),[Au]=r.stream.getAudioTracks(),!Au)throw Error(`Could not get empty media stream audio track`);Au.enabled=!1}return Au.clone()}var Mu=class{get isResolved(){return this._isResolved}constructor(e,t){this._isResolved=!1,this.onFinally=t,this.promise=new Promise((t,n)=>N(this,void 0,void 0,function*(){this.resolve=t,this.reject=n,e&&(yield e(t,n))})).finally(()=>{var e;this._isResolved=!0,(e=this.onFinally)==null||e.call(this)})}};function Nu(e){return bl.includes(e)}function Pu(e){if(typeof e==`string`||typeof e==`number`)return e;if(Array.isArray(e))return e[0];if(e.exact!==void 0)return Array.isArray(e.exact)?e.exact[0]:e.exact;if(e.ideal!==void 0)return Array.isArray(e.ideal)?e.ideal[0]:e.ideal;throw Error(`could not unwrap constraint`)}function Fu(e){return e.startsWith(`http`)?e.replace(/^(http)/,`ws`):e}function Iu(e){return e.startsWith(`ws`)?e.replace(/^(ws)/,`http`):e}function Lu(e,t){return e.segments.map(e=>{let{id:n,text:r,language:i,startTime:a,endTime:o,final:s}=e,c=t.get(n)??Date.now(),l=Date.now();return s?t.delete(n):t.set(n,c),{id:n,text:r,startTime:Number.parseInt(a.toString()),endTime:Number.parseInt(o.toString()),final:s,language:i,firstReceivedTime:c,lastReceivedTime:l}})}function Ru(e){let{id:t,timestamp:n,message:r,editTimestamp:i}=e;return{id:t,timestamp:Number.parseInt(n.toString()),editTimestamp:i?Number.parseInt(i.toString()):void 0,message:r}}function zu(e){switch(e.reason){case P.LeaveRequest:return e.context;case P.Cancelled:return pa.CLIENT_INITIATED;case P.NotAllowed:return pa.USER_REJECTED;case P.ServerUnreachable:return pa.JOIN_FAILURE;default:return pa.UNKNOWN_REASON}}function Bu(e){return e===void 0?void 0:Number(e)}function Vu(e){return e===void 0?void 0:BigInt(e)}function Hu(e){return!!e&&!(e instanceof MediaStreamTrack)&&e.isLocal}function Uu(e){return!!e&&e.kind==U.Kind.Audio}function Wu(e){return!!e&&e.kind==U.Kind.Video}function Gu(e){return Hu(e)&&Wu(e)}function Ku(e){return Hu(e)&&Uu(e)}function qu(e){return!!e&&!e.isLocal}function Ju(e){return!!e&&!e.isLocal}function Yu(e){return qu(e)&&Wu(e)}function Xu(e){return e.isLocal}function Zu(e,t){let n=[],r=new TextEncoder().encode(e);for(;r.length>t;){let e=t;for(;e>0;){let t=r[e];if(t!==void 0&&(t&192)!=128)break;e--}n.push(r.slice(0,e)),r=r.slice(e)}return r.length>0&&n.push(r),n}function Qu(e){let t=e.get(`Cache-Control`);if(t){let e=t.match(/(?:^|[,\s])max-age=(\d+)/)?.[1];if(e)return parseInt(e,10)}}function $u(){return typeof CompressionStream<`u`}function ed(e,t){let n=arguments.length>2&&arguments[2]!==void 0?arguments[2]:!1,r=td(e,t);return n?r:id(r,`v1`)}function td(e,t){let n=new URL(Fu(e));return t.forEach((e,t)=>{n.searchParams.set(t,e)}),id(n,`rtc`)}function nd(e){return id(new URL(Iu(e)),`validate`)}function rd(e){return e.endsWith(`/`)?e:`${e}/`}function id(e,t){return e.pathname=`${rd(e.pathname)}${t}`,e}function ad(e){if(typeof e==`string`)return fo.fromJson(JSON.parse(e),{ignoreUnknownFields:!0});if(e instanceof ArrayBuffer)return fo.fromBinary(new Uint8Array(e));throw Error(`could not decode websocket message: ${typeof e}`)}function od(e){let t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:`Unknown reason`;if(!(e instanceof AbortSignal))return t;let n=e.reason;switch(typeof n){case`string`:return n;case`object`:return n instanceof Error?n.message:t;default:return`toString`in n?n.toString():t}}var sd=`lk_e2ee`,cd;(function(e){e.SetKey=`setKey`,e.RatchetRequest=`ratchetRequest`,e.KeyRatcheted=`keyRatcheted`})(cd||={});var ld;(function(e){e.KeyRatcheted=`keyRatcheted`})(ld||={});var ud;(function(e){e.ParticipantEncryptionStatusChanged=`participantEncryptionStatusChanged`,e.EncryptionError=`encryptionError`})(ud||={});var dd;(function(e){e.Error=`cryptorError`})(dd||={});function fd(){return md()||pd()}function pd(){return window.RTCRtpScriptTransform!==void 0}function md(){return window.RTCRtpSender!==void 0&&window.RTCRtpSender.prototype.createEncodedStreams!==void 0}function hd(e){if(e.value?.case!==`sipDtmf`&&e.value?.case!==`metrics`&&e.value?.case!==`speaker`&&e.value?.case!==`transcription`&&e.value?.case!==`encryptedPacket`)return new Na({value:e.value})}zs.EventEmitter;var gd;(function(e){e[e.InvalidKey=0]=`InvalidKey`,e[e.MissingKey=1]=`MissingKey`,e[e.InternalError=2]=`InternalError`})(gd||={});var _d=class extends zs.EventEmitter{constructor(e,t){super(),this.decryptDataRequests=new Map,this.encryptDataRequests=new Map,this.onWorkerMessage=e=>{let{kind:t,data:n}=e.data;switch(t){case`error`:if(M.error(n.error.message),n.uuid){let e=this.decryptDataRequests.get(n.uuid);if(e?.reject){e.reject(n.error);break}let t=this.encryptDataRequests.get(n.uuid);if(t?.reject){t.reject(n.error);break}}this.emit(ud.EncryptionError,n.error,n.participantIdentity);break;case`initAck`:n.enabled&&this.keyProvider.getKeys().forEach(e=>{this.postKey(e,!1)});break;case`enable`:if(n.enabled&&this.keyProvider.getKeys().forEach(e=>{this.postKey(e,!1)}),this.encryptionEnabled!==n.enabled&&n.participantIdentity===this.room?.localParticipant.identity)this.emit(ud.ParticipantEncryptionStatusChanged,n.enabled,this.room.localParticipant),this.encryptionEnabled=n.enabled;else if(n.participantIdentity){let e=this.room?.getParticipantByIdentity(n.participantIdentity);if(!e)throw TypeError(`couldn't set encryption status, participant not found${n.participantIdentity}`);this.emit(ud.ParticipantEncryptionStatusChanged,n.enabled,e)}break;case`ratchetKey`:this.keyProvider.emit(cd.KeyRatcheted,n.ratchetResult,n.participantIdentity,n.keyIndex);break;case`decryptDataResponse`:let e=this.decryptDataRequests.get(n.uuid);e?.resolve&&e.resolve(n);break;case`encryptDataResponse`:let t=this.encryptDataRequests.get(n.uuid);t?.resolve&&t.resolve(n);break}},this.onWorkerError=e=>{M.error(`e2ee worker encountered an error:`,{error:e.error}),this.emit(ud.EncryptionError,e.error,void 0)},this.keyProvider=e.keyProvider,this.worker=e.worker,this.encryptionEnabled=!1,this.dataChannelEncryptionEnabled=t}get isEnabled(){return this.encryptionEnabled}get isDataChannelEncryptionEnabled(){return this.isEnabled&&this.dataChannelEncryptionEnabled}setup(e){if(!fd())throw new sl(`tried to setup end-to-end encryption on an unsupported browser`);if(M.info(`setting up e2ee`),e!==this.room){this.room=e,this.setupEventListeners(e,this.keyProvider);let t={kind:`init`,data:{keyProviderOptions:this.keyProvider.getOptions(),loglevel:Es.getLevel()}};this.worker&&(M.info(`initializing worker`,{worker:this.worker}),this.worker.onmessage=this.onWorkerMessage,this.worker.onerror=this.onWorkerError,this.worker.postMessage(t))}}setParticipantCryptorEnabled(e,t){M.debug(`set e2ee to ${e} for participant ${t}`),this.postEnable(e,t)}setSifTrailer(e){!e||e.length===0?M.warn(`ignoring server sent trailer as it's empty`):this.postSifTrailer(e)}setupEngine(e){e.on(z.RTPVideoMapUpdate,e=>{this.postRTPMap(e)})}setupEventListeners(e,t){e.on(L.TrackPublished,(e,t)=>this.setParticipantCryptorEnabled(e.trackInfo.encryption!==j.NONE,t.identity)),e.on(L.ConnectionStateChanged,t=>{t===Y.Connected&&e.remoteParticipants.forEach(e=>{e.trackPublications.forEach(t=>{this.setParticipantCryptorEnabled(t.trackInfo.encryption!==j.NONE,e.identity)})})}).on(L.TrackUnsubscribed,(e,t,n)=>{var r;let i={kind:`removeTransform`,data:{participantIdentity:n.identity,trackId:e.mediaStreamID}};(r=this.worker)==null||r.postMessage(i)}).on(L.TrackSubscribed,(e,t,n)=>{this.setupE2EEReceiver(e,n.identity,t.trackInfo)}).on(L.SignalConnected,()=>{if(!this.room)throw TypeError(`expected room to be present on signal connect`);let e=t.getLatestManuallySetKeyIndex();t.getKeys().forEach(t=>{this.postKey(t,e===(t.keyIndex??0))}),this.setParticipantCryptorEnabled(this.room.localParticipant.isE2EEEnabled,this.room.localParticipant.identity)}),e.localParticipant.on(R.LocalSenderCreated,(e,t)=>N(this,void 0,void 0,function*(){this.setupE2EESender(t,e)})),e.localParticipant.on(R.LocalTrackPublished,e=>{if(!Wu(e.track)||!lu())return;let t={kind:`updateCodec`,data:{trackId:e.track.mediaStreamID,codec:Il(e.trackInfo.codecs[0].mimeType),participantIdentity:this.room.localParticipant.identity}};this.worker.postMessage(t)}),t.on(cd.SetKey,(e,t)=>this.postKey(e,t??!0)).on(cd.RatchetRequest,(e,t)=>this.postRatchetRequest(e,t))}encryptData(e){return N(this,void 0,void 0,function*(){if(!this.worker)throw Error(`could not encrypt data, worker is missing`);let t=crypto.randomUUID(),n={kind:`encryptDataRequest`,data:{uuid:t,payload:e,participantIdentity:this.room.localParticipant.identity}},r=new Mu;return r.onFinally=()=>{this.encryptDataRequests.delete(t)},this.encryptDataRequests.set(t,r),this.worker.postMessage(n),r.promise})}handleEncryptedData(e,t,n,r){if(!this.worker)throw Error(`could not handle encrypted data, worker is missing`);let i=crypto.randomUUID(),a={kind:`decryptDataRequest`,data:{uuid:i,payload:e,iv:t,participantIdentity:n,keyIndex:r}},o=new Mu;return o.onFinally=()=>{this.decryptDataRequests.delete(i)},this.decryptDataRequests.set(i,o),this.worker.postMessage(a),o.promise}postRatchetRequest(e,t){if(!this.worker)throw Error(`could not ratchet key, worker is missing`);let n={kind:`ratchetRequest`,data:{participantIdentity:e,keyIndex:t}};this.worker.postMessage(n)}postKey(e,t){let{key:n,participantIdentity:r,keyIndex:i}=e;if(!this.worker)throw Error(`could not set key, worker is missing`);let a={kind:`setKey`,data:{participantIdentity:r,isPublisher:r===this.room?.localParticipant.identity,key:n,keyIndex:i,updateCurrentKeyIndex:t}};this.worker.postMessage(a)}postEnable(e,t){if(this.worker){let n={kind:`enable`,data:{enabled:e,participantIdentity:t}};this.worker.postMessage(n)}else throw ReferenceError(`failed to enable e2ee, worker is not ready`)}postRTPMap(e){if(!this.worker)throw TypeError(`could not post rtp map, worker is missing`);if(!this.room?.localParticipant.identity)throw TypeError(`could not post rtp map, local participant identity is missing`);let t={kind:`setRTPMap`,data:{map:e,participantIdentity:this.room.localParticipant.identity}};this.worker.postMessage(t)}postSifTrailer(e){if(!this.worker)throw Error(`could not post SIF trailer, worker is missing`);let t={kind:`setSifTrailer`,data:{trailer:e}};this.worker.postMessage(t)}setupE2EEReceiver(e,t,n){if(e.receiver){if(!n?.mimeType||n.mimeType===``)throw TypeError(`MimeType missing from trackInfo, cannot set up E2EE cryptor`);this.handleReceiver(e.receiver,e.mediaStreamID,t,e.kind===`video`?Il(n.mimeType):void 0)}}setupE2EESender(e,t){if(!Hu(e)||!t){t||M.warn(`early return because sender is not ready`);return}this.handleSender(t,e.mediaStreamID,void 0)}handleReceiver(e,t,n,r){return N(this,void 0,void 0,function*(){if(this.worker){if(pd()&&!su()){let i={kind:`decode`,participantIdentity:n,trackId:t,codec:r};e.transform=new RTCRtpScriptTransform(this.worker,i)}else{if(sd in e&&r){let e={kind:`updateCodec`,data:{trackId:t,codec:r,participantIdentity:n}};this.worker.postMessage(e);return}let i=e.writableStream,a=e.readableStream;if(!i||!a){let t=e.createEncodedStreams();e.writableStream=t.writable,i=t.writable,e.readableStream=t.readable,a=t.readable}let o={kind:`decode`,data:{readableStream:a,writableStream:i,trackId:t,codec:r,participantIdentity:n,isReuse:sd in e}};this.worker.postMessage(o,[a,i])}e[sd]=!0}})}handleSender(e,t,n){if(!(sd in e||!this.worker)){if(!this.room?.localParticipant.identity||this.room.localParticipant.identity===``)throw TypeError(`local identity needs to be known in order to set up encrypted sender`);if(pd()&&!su()){M.info(`initialize script transform`);let r={kind:`encode`,participantIdentity:this.room.localParticipant.identity,trackId:t,codec:n};e.transform=new RTCRtpScriptTransform(this.worker,r)}else{M.info(`initialize encoded streams`);let r=e.createEncodedStreams(),i={kind:`encode`,data:{readableStream:r.readable,writableStream:r.writable,codec:n,trackId:t,participantIdentity:this.room.localParticipant.identity,isReuse:!1}};this.worker.postMessage(i,[r.readable,r.writable])}e[sd]=!0}}},vd=500,yd=15e3,bd=class e{constructor(){this.failedConnectionAttempts=new Map,this.backOffPromises=new Map}static getInstance(){return this._instance||=new e,this._instance}addFailedConnectionAttempt(e){let t=_u(new URL(e));if(!t)return;let n=this.failedConnectionAttempts.get(t)??0;this.failedConnectionAttempts.set(t,n+1),this.backOffPromises.set(t,Ql(Math.min(vd*2**n,yd)))}getBackOffPromise(e){let t=new URL(e),n=t&&_u(t);return n&&this.backOffPromises.get(n)||Promise.resolve()}resetFailedConnectionAttempts(e){let t=new URL(e),n=t&&_u(t);n&&(this.failedConnectionAttempts.set(n,0),this.backOffPromises.set(n,Promise.resolve()))}resetAll(){this.backOffPromises.clear(),this.failedConnectionAttempts.clear()}};bd._instance=null;var xd=`default`,Sd=class e{constructor(){this._previousDevices=[]}static getInstance(){return this.instance===void 0&&(this.instance=new e),this.instance}get previousDevices(){return this._previousDevices}getDevices(t){return N(this,arguments,void 0,function(t){var n=this;let r=arguments.length>1&&arguments[1]!==void 0?arguments[1]:!0;return function*(){if(e.userMediaPromiseMap?.size>0){M.debug(`awaiting getUserMedia promise`);try{t?yield e.userMediaPromiseMap.get(t):yield Promise.all(e.userMediaPromiseMap.values())}catch{M.warn(`error waiting for media permissons`)}}let i=yield navigator.mediaDevices.enumerateDevices();if(r&&!(cu()&&n.hasDeviceInUse(t))&&(i.filter(e=>e.kind===t).length===0||i.some(e=>{let n=e.label===``,r=t?e.kind===t:!0;return n&&r}))){let e={video:t!==`audioinput`&&t!==`audiooutput`,audio:t!==`videoinput`&&{deviceId:{ideal:`default`}}},n=yield navigator.mediaDevices.getUserMedia(e);i=yield navigator.mediaDevices.enumerateDevices(),n.getTracks().forEach(e=>{e.stop()})}return n._previousDevices=i,t&&(i=i.filter(e=>e.kind===t)),i}()})}normalizeDeviceId(e,t,n){return N(this,void 0,void 0,function*(){if(t!==xd)return t;let r=yield this.getDevices(e),i=r.find(e=>e.deviceId===xd);if(!i){M.warn(`could not reliably determine default device`);return}let a=r.find(e=>e.deviceId!==xd&&e.groupId===(n??i.groupId));if(!a){M.warn(`could not reliably determine default device`);return}return a?.deviceId})}hasDeviceInUse(t){return t?e.userMediaPromiseMap.has(t):e.userMediaPromiseMap.size>0}};Sd.mediaDeviceKinds=[`audioinput`,`audiooutput`,`videoinput`],Sd.userMediaPromiseMap=new Map;var Cd=65535,wd=4294967295,Td=class e{static u16(t){return new e(t,Cd)}static u32(t){return new e(t,wd)}constructor(e,t){if(this.value=e,e<0)throw Error(`WrapAroundUnsignedInt: cannot faithfully represent an integer smaller than 0`);if(t>2**53-1)throw Error(`WrapAroundUnsignedInt: cannot faithfully represent an integer bigger than MAX_SAFE_INTEGER.`);this.maxSize=t,this.clamp()}clamp(){for(;this.value>this.maxSize;)this.value-=this.maxSize+1;for(;this.value<0;)this.value+=this.maxSize+1}clone(){return new e(this.value,this.maxSize)}update(e){this.value=e(this.value),this.clamp()}increment(){let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:1;this.update(t=>t+e)}decrement(){let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:1;this.update(t=>t-e)}getThenIncrement(){let t=this.value;return this.increment(),new e(t,this.maxSize)}isBefore(e){let t=this.value>>>0,n=(e.value>>>0)-t>>>0;return n!==0&&n<this.maxSize+1}},Ed=class e{static fromRtpTicks(t){return new e(t,9e4)}static rtpRandom(){let t=Math.round(Math.random()*wd);return e.fromRtpTicks(t)}constructor(e,t){this.timestamp=Td.u32(e),this.rateInHz=t}asTicks(){return this.timestamp.value}clone(){return new e(this.timestamp.value,this.rateInHz)}wrappingAdd(e){this.timestamp.increment(e)}isBefore(e){return this.timestamp.isBefore(e.timestamp)}},Dd=class e{constructor(e,t,n){this.epoch=t,this.base=n,this.previous=n.clone(),this.rateInHz=e}static startingNow(t,n){return new e(n,new Date,t)}static startingAtTime(t,n,r){return new e(r,t,n)}static rtpStartingNow(t){return e.startingNow(t,9e4)}static rtpStartingAtTime(t,n){return e.startingAtTime(t,n,9e4)}now(){return this.at(new Date)}at(t){let n=t.getTime()-this.epoch.getTime(),r=e.durationInMsToTicks(n,this.rateInHz),i=this.base.clone();return i.wrappingAdd(r),i.isBefore(this.previous)&&(i=this.previous),this.previous=i.clone(),i.clone()}static durationInMsToTicks(e,t){let n=(e*1e6*t+5e8)/1e9;return Math.round(n)}};function Od(e){if(e instanceof DataView)return e;if(e instanceof ArrayBuffer)return new DataView(e);if(e instanceof Uint8Array)return new DataView(e.buffer,e.byteOffset,e.byteLength);throw Error(`Error coercing ${e} to DataView - input was not DataView, ArrayBuffer, or Uint8Array.`)}var kd;(function(e){e[e.Reserved=0]=`Reserved`,e[e.TooLarge=1]=`TooLarge`})(kd||={});var Ad=class e extends ol{constructor(e,t){super(19,e),this.name=`DataTrackHandleError`,this.reason=t,this.reasonName=kd[t]}isReason(e){return this.reason===e}static tooLarge(){return new e(`Value too large to be a valid track handle`,kd.TooLarge)}static reserved(t){return new e(`0x${t.toString(16)} is a reserved value.`,kd.Reserved)}},jd={fromNumber(e){if(e===0)throw Ad.reserved(e);if(e>Cd)throw Ad.tooLarge();return e}},Md=class{constructor(){this.value=0}get(){return this.value+=1,this.value>Cd?null:this.value}},Nd={from(e){return{sid:e.sid,pubHandle:e.pubHandle,name:e.name,usesE2ee:e.encryption!==j.NONE}},toProtobuf(e){return new Ea({sid:e.sid,pubHandle:e.pubHandle,name:e.name,encryption:e.usesE2ee?j.GCM:j.NONE})}},Pd;(function(e){e[e.WAITING=0]=`WAITING`,e[e.RUNNING=1]=`RUNNING`,e[e.COMPLETED=2]=`COMPLETED`})(Pd||={});var Fd=class{constructor(){this.pendingTasks=new Map,this.taskMutex=new ur,this.nextTaskIndex=0}run(e){return N(this,void 0,void 0,function*(){let t={id:this.nextTaskIndex++,enqueuedAt:Date.now(),status:Pd.WAITING};this.pendingTasks.set(t.id,t);let n=yield this.taskMutex.lock();try{return t.executedAt=Date.now(),t.status=Pd.RUNNING,yield e()}finally{t.status=Pd.COMPLETED,this.pendingTasks.delete(t.id),n()}})}flush(){return N(this,void 0,void 0,function*(){return this.run(()=>N(this,void 0,void 0,function*(){}))})}snapshot(){return Array.from(this.pendingTasks.values())}},Id=class{get readyState(){return this.ws.readyState}constructor(e){let t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{};if(t.signal?.aborted)throw new DOMException(`This operation was aborted`,`AbortError`);this.url=e;let n=new WebSocket(e,t.protocols??[]);n.binaryType=`arraybuffer`,this.ws=n;let r=function(){let{closeCode:e,reason:t}=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};return n.close(e,t)};this.opened=new Zc((e,t)=>{let i=()=>{t(F.websocket(`Encountered websocket error during connection establishment`))};n.onopen=()=>{e({readable:new ReadableStream({start(e){n.onmessage=t=>{let{data:n}=t;return e.enqueue(n)},n.onerror=t=>e.error(t)},cancel:r}),writable:new WritableStream({write(e){n.send(e)},abort(){n.close()},close:r}),protocol:n.protocol,extensions:n.extensions}),n.removeEventListener(`error`,i)},n.addEventListener(`error`,i)}),this.closed=new Zc((e,t)=>{let r=()=>N(this,void 0,void 0,function*(){let r=new Zc(e=>{n.readyState!==WebSocket.CLOSED&&n.addEventListener(`close`,t=>{e(t)},{once:!0})}),i=yield Zc.race([Ql(250),r]);i?e(i):t(F.websocket(`Encountered unspecified websocket error without a timely close event`))});n.onclose=t=>{let{code:i,reason:a}=t;e({closeCode:i,reason:a}),n.removeEventListener(`error`,r)},n.addEventListener(`error`,r)}),t.signal&&(t.signal.onabort=()=>n.close()),this.close=r}},Ld=[`syncState`,`trickle`,`offer`,`answer`,`simulate`,`leave`];function Rd(e){let t=Ld.indexOf(e.case)>=0;return M.trace(`request allowed to bypass queue:`,{canPass:t,req:e}),t}var W;(function(e){e[e.CONNECTING=0]=`CONNECTING`,e[e.CONNECTED=1]=`CONNECTED`,e[e.RECONNECTING=2]=`RECONNECTING`,e[e.DISCONNECTING=3]=`DISCONNECTING`,e[e.DISCONNECTED=4]=`DISCONNECTED`})(W||={});var zd=250,Bd=class{get currentState(){return this.state}get isDisconnected(){return this.state===W.DISCONNECTING||this.state===W.DISCONNECTED}get isEstablishingConnection(){return this.state===W.CONNECTING||this.state===W.RECONNECTING}getNextRequestId(){return this._requestId+=1,this._requestId}constructor(){let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:!1,t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{};this.rtt=0,this.state=W.DISCONNECTED,this.log=M,this._requestId=0,this.useV0SignalPath=!1,this.resetCallbacks=()=>{this.onAnswer=void 0,this.onLeave=void 0,this.onLocalTrackPublished=void 0,this.onLocalTrackUnpublished=void 0,this.onNegotiateRequested=void 0,this.onOffer=void 0,this.onRemoteMuteChanged=void 0,this.onSubscribedQualityUpdate=void 0,this.onTokenRefresh=void 0,this.onTrickle=void 0,this.onClose=void 0,this.onMediaSectionsRequirement=void 0},this.log=Ts(t.loggerName??ws.Signal),this.loggerContextCb=t.loggerContextCb,this.useJSON=e,this.requestQueue=new Fd,this.queuedRequests=[],this.closingLock=new ur,this.connectionLock=new ur,this.state=W.DISCONNECTED}get logContext(){return this.loggerContextCb?.call(this)??{}}join(e,t,n,r){return N(this,arguments,void 0,function(e,t,n,r){var i=this;let a=arguments.length>4&&arguments[4]!==void 0?arguments[4]:!1,o=arguments.length>5?arguments[5]:void 0;return function*(){return i.state=W.CONNECTING,i.options=n,yield i.connect(e,t,n,r,a,o)}()})}reconnect(e,t,n,r){return N(this,void 0,void 0,function*(){if(!this.options){this.log.warn(`attempted to reconnect without signal options being set, ignoring`,this.logContext);return}return this.state=W.RECONNECTING,this.clearPingInterval(),yield this.connect(e,t,Object.assign(Object.assign({},this.options),{reconnect:!0,sid:n,reconnectReason:r}),void 0,this.useV0SignalPath)})}connect(e,t,n,r){return N(this,arguments,void 0,function(e,t,n,r){var i=this;let a=arguments.length>4&&arguments[4]!==void 0?arguments[4]:!1,o=arguments.length>5?arguments[5]:void 0;return function*(){let s=yield i.connectionLock.lock();i.connectOptions=n,i.useV0SignalPath=a;let c=Ou(),l=ed(e,a?Ud(t,c,n):yield Wd(t,c,n,o),a).toString(),u=nd(l).toString();return new Promise((e,t)=>N(i,void 0,void 0,function*(){try{let i=!1,a=e=>N(this,void 0,void 0,function*(){if(i)return;i=!0;let n=od(e instanceof Event?e.currentTarget:e,`Abort handler called`);this.streamWriter&&!this.isDisconnected?this.sendLeave().then(()=>this.close(n)).catch(e=>{this.log.error(e),this.close()}):this.close(),o(),t(F.cancelled(n))});r?.addEventListener(`abort`,a);let o=()=>{clearTimeout(s),r?.removeEventListener(`abort`,a)},s=setTimeout(()=>{a(F.timeout(`room connection has timed out (signal)`))},n.websocketTimeout),c=(e,t)=>{this.handleSignalConnected(e,s,t)},d=new URL(l);d.searchParams.has(`access_token`)&&d.searchParams.set(`access_token`,`<redacted>`),this.log.debug(`connecting to ${d}`,Object.assign({reconnect:n.reconnect,reconnectReason:n.reconnectReason},this.logContext)),this.ws&&(yield this.close(!1)),this.ws=new Id(l);try{this.ws.closed.then(e=>{this.isEstablishingConnection&&t(F.internal(`Websocket got closed during a (re)connection attempt: ${e.reason}`)),e.closeCode!==1e3&&(this.log.warn(`websocket closed`,Object.assign(Object.assign({},this.logContext),{reason:e.reason,code:e.closeCode,wasClean:e.closeCode===1e3,state:this.state})),this.state===W.CONNECTED&&this.handleOnClose(e.reason??`Unexpected WS error`))}).catch(e=>{this.isEstablishingConnection&&t(F.internal(`Websocket error during a (re)connection attempt: ${e}`))});let r=yield this.ws.opened.catch(e=>N(this,void 0,void 0,function*(){if(this.state!==W.CONNECTED){this.state=W.DISCONNECTED,clearTimeout(s),t(yield this.handleConnectionError(e,u));return}this.handleWSError(e),t(e)}));if(clearTimeout(s),!r)return;let i=r.readable.getReader();this.streamWriter=r.writable.getWriter();let a=yield i.read();if(i.releaseLock(),!a.value)throw F.internal(`no message received as first message`);let o=ad(a.value),l=this.validateFirstMessage(o,n.reconnect??!1);if(!l.isValid){t(l.error);return}o.message?.case===`join`&&(this.pingTimeoutDuration=o.message.value.pingTimeout,this.pingIntervalDuration=o.message.value.pingInterval,this.pingTimeoutDuration&&this.pingTimeoutDuration>0&&this.log.debug(`ping config`,Object.assign(Object.assign({},this.logContext),{timeout:this.pingTimeoutDuration,interval:this.pingIntervalDuration})),this.onJoined&&this.onJoined(o.message.value)),c(r,l.shouldProcessFirstMessage?o:void 0),e(l.response)}catch(e){t(e)}finally{o()}}finally{s()}}))}()})}startReadingLoop(e,t){return N(this,void 0,void 0,function*(){for(t&&this.handleSignalResponse(t);;){this.signalLatency&&(yield Ql(this.signalLatency));let{done:t,value:n}=yield e.read();if(t)break;let r=ad(n);this.handleSignalResponse(r)}})}close(){return N(this,arguments,void 0,function(){var e=this;let t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:!0,n=arguments.length>1&&arguments[1]!==void 0?arguments[1]:`Close method called on signal client`;return function*(){if([W.DISCONNECTING||W.DISCONNECTED].includes(e.state)){e.log.debug(`ignoring signal close as it's already in disconnecting state`);return}let r=yield e.closingLock.lock();try{if(e.clearPingInterval(),t&&(e.state=W.DISCONNECTING),e.ws){e.ws.close({closeCode:1e3,reason:n});let t=e.ws.closed;e.ws=void 0,e.streamWriter=void 0,yield Promise.race([t,Ql(zd)])}}catch(t){e.log.debug(`websocket error while closing`,Object.assign(Object.assign({},e.logContext),{error:t}))}finally{t&&(e.state=W.DISCONNECTED),r()}}()})}sendOffer(e,t){this.log.debug(`sending offer`,Object.assign(Object.assign({},this.logContext),{offerSdp:e.sdp})),this.sendRequest({case:`offer`,value:Hd(e,t)})}sendAnswer(e,t){return this.log.debug(`sending answer`,Object.assign(Object.assign({},this.logContext),{answerSdp:e.sdp})),this.sendRequest({case:`answer`,value:Hd(e,t)})}sendIceCandidate(e,t){return this.log.debug(`sending ice candidate`,Object.assign(Object.assign({},this.logContext),{candidate:e})),this.sendRequest({case:`trickle`,value:new xo({candidateInit:JSON.stringify(e),target:t})})}sendMuteTrack(e,t){return this.sendRequest({case:`mute`,value:new So({sid:e,muted:t})})}sendAddTrack(e){return this.sendRequest({case:`addTrack`,value:e})}sendUpdateLocalMetadata(e,t){return N(this,arguments,void 0,function(e,t){var n=this;let r=arguments.length>2&&arguments[2]!==void 0?arguments[2]:{};return function*(){let i=n.getNextRequestId();return yield n.sendRequest({case:`updateMetadata`,value:new Ro({requestId:i,metadata:e,name:t,attributes:r})}),i}()})}sendUpdateTrackSettings(e){this.sendRequest({case:`trackSetting`,value:e})}sendUpdateSubscription(e){return this.sendRequest({case:`subscription`,value:e})}sendSyncState(e){return this.sendRequest({case:`syncState`,value:e})}sendUpdateVideoLayers(e,t){return this.sendRequest({case:`updateLayers`,value:new Lo({trackSid:e,layers:t})})}sendUpdateSubscriptionPermissions(e,t){return this.sendRequest({case:`subscriptionPermission`,value:new Zo({allParticipants:e,trackPermissions:t})})}sendSimulateScenario(e){return this.sendRequest({case:`simulate`,value:e})}sendPing(){return Promise.all([this.sendRequest({case:`ping`,value:D.parse(Date.now())}),this.sendRequest({case:`pingReq`,value:new is({timestamp:D.parse(Date.now()),rtt:D.parse(this.rtt)})})])}sendUpdateLocalAudioTrack(e,t){return this.sendRequest({case:`updateAudioTrack`,value:new No({trackSid:e,features:t})})}sendLeave(){return this.sendRequest({case:`leave`,value:new Fo({reason:pa.CLIENT_INITIATED,action:Io.DISCONNECT})})}sendPublishDataTrackRequest(e,t,n){return this.sendRequest({case:`publishDataTrackRequest`,value:new ho({pubHandle:e,name:t,encryption:n?j.GCM:j.NONE})})}sendUnPublishDataTrackRequest(e){return this.sendRequest({case:`unpublishDataTrackRequest`,value:new _o({pubHandle:e})})}sendUpdateDataSubscription(e,t){return this.sendRequest({case:`updateDataSubscription`,value:new Ao({updates:[new jo({trackSid:e,subscribe:t})]})})}sendRequest(e){return N(this,arguments,void 0,function(e){var t=this;let n=arguments.length>1&&arguments[1]!==void 0?arguments[1]:!1;return function*(){if(!n&&!Rd(e)&&t.state===W.RECONNECTING){t.queuedRequests.push(()=>N(t,void 0,void 0,function*(){yield this.sendRequest(e,!0)}));return}if(n||(yield t.requestQueue.flush()),t.signalLatency&&(yield Ql(t.signalLatency)),t.isDisconnected){t.log.debug(`skipping signal request (type: ${e.case}) - SignalClient disconnected`);return}if(!t.streamWriter){t.log.error(`cannot send signal request before connected, type: ${e?.case}`,t.logContext);return}let r=new uo({message:e});try{t.useJSON?yield t.streamWriter.write(r.toJsonString()):yield t.streamWriter.write(r.toBinary())}catch(e){t.log.error(`error sending signal message`,Object.assign(Object.assign({},t.logContext),{error:e}))}}()})}handleSignalResponse(e){let t=e.message;if(t==null){this.log.debug(`received unsupported message`,this.logContext);return}let n=!1;if(t.case===`answer`){let e=Vd(t.value);this.onAnswer&&this.onAnswer(e,t.value.id,t.value.midToTrackId)}else if(t.case===`offer`){let e=Vd(t.value);this.onOffer&&this.onOffer(e,t.value.id,t.value.midToTrackId)}else if(t.case===`trickle`){let e=JSON.parse(t.value.candidateInit);this.onTrickle&&this.onTrickle(e,t.value.target)}else t.case===`update`?this.onParticipantUpdate&&this.onParticipantUpdate(t.value.participants??[]):t.case===`trackPublished`?this.onLocalTrackPublished&&this.onLocalTrackPublished(t.value):t.case===`speakersChanged`?this.onSpeakersChanged&&this.onSpeakersChanged(t.value.speakers??[]):t.case===`leave`?this.onLeave&&this.onLeave(t.value):t.case===`mute`?this.onRemoteMuteChanged&&this.onRemoteMuteChanged(t.value.sid,t.value.muted):t.case===`roomUpdate`?this.onRoomUpdate&&t.value.room&&this.onRoomUpdate(t.value.room):t.case===`connectionQuality`?this.onConnectionQuality&&this.onConnectionQuality(t.value):t.case===`streamStateUpdate`?this.onStreamStateUpdate&&this.onStreamStateUpdate(t.value):t.case===`subscribedQualityUpdate`?this.onSubscribedQualityUpdate&&this.onSubscribedQualityUpdate(t.value):t.case===`subscriptionPermissionUpdate`?this.onSubscriptionPermissionUpdate&&this.onSubscriptionPermissionUpdate(t.value):t.case===`refreshToken`?this.onTokenRefresh&&this.onTokenRefresh(t.value):t.case===`trackUnpublished`?this.onLocalTrackUnpublished&&this.onLocalTrackUnpublished(t.value):t.case===`subscriptionResponse`?this.onSubscriptionError&&this.onSubscriptionError(t.value):t.case===`pong`||(t.case===`pongResp`?(this.rtt=Date.now()-Number.parseInt(t.value.lastPingTimestamp.toString()),this.resetPingTimeout(),n=!0):t.case===`requestResponse`?this.onRequestResponse&&this.onRequestResponse(t.value):t.case===`trackSubscribed`?this.onLocalTrackSubscribed&&this.onLocalTrackSubscribed(t.value.trackSid):t.case===`roomMoved`?(this.onTokenRefresh&&this.onTokenRefresh(t.value.token),this.onRoomMoved&&this.onRoomMoved(t.value)):t.case===`mediaSectionsRequirement`?this.onMediaSectionsRequirement&&this.onMediaSectionsRequirement(t.value):t.case===`publishDataTrackResponse`?this.onPublishDataTrackResponse&&this.onPublishDataTrackResponse(t.value):t.case===`unpublishDataTrackResponse`?this.onUnPublishDataTrackResponse&&this.onUnPublishDataTrackResponse(t.value):t.case===`dataTrackSubscriberHandles`?this.onDataTrackSubscriberHandles&&this.onDataTrackSubscriberHandles(t.value):this.log.debug(`unsupported message`,Object.assign(Object.assign({},this.logContext),{msgCase:t.case})));n||this.resetPingTimeout()}setReconnected(){for(;this.queuedRequests.length>0;){let e=this.queuedRequests.shift();e&&this.requestQueue.run(e)}}handleOnClose(e){return N(this,void 0,void 0,function*(){if(this.state===W.DISCONNECTED)return;let t=this.onClose;yield this.close(void 0,e),this.log.debug(`websocket connection closed: ${e}`,Object.assign(Object.assign({},this.logContext),{reason:e})),t&&t(e)})}handleWSError(e){this.log.error(`websocket error`,Object.assign(Object.assign({},this.logContext),{error:e}))}resetPingTimeout(){if(this.clearPingTimeout(),!this.pingTimeoutDuration){this.log.warn(`ping timeout duration not set`,this.logContext);return}this.pingTimeout=_l.setTimeout(()=>{this.log.warn(`ping timeout triggered. last pong received at: ${new Date(Date.now()-this.pingTimeoutDuration*1e3).toUTCString()}`,this.logContext),this.handleOnClose(`ping timeout`)},this.pingTimeoutDuration*1e3)}clearPingTimeout(){this.pingTimeout&&_l.clearTimeout(this.pingTimeout)}startPingInterval(){if(this.clearPingInterval(),this.resetPingTimeout(),!this.pingIntervalDuration){this.log.warn(`ping interval duration not set`,this.logContext);return}this.log.debug(`start ping interval`,this.logContext),this.pingInterval=_l.setInterval(()=>{this.sendPing()},this.pingIntervalDuration*1e3)}clearPingInterval(){this.log.debug(`clearing ping interval`,this.logContext),this.clearPingTimeout(),this.pingInterval&&_l.clearInterval(this.pingInterval)}handleSignalConnected(e,t,n){this.state=W.CONNECTED,clearTimeout(t),this.startPingInterval(),this.startReadingLoop(e.readable.getReader(),n)}validateFirstMessage(e,t){return e.message?.case===`join`?{isValid:!0,response:e.message.value}:this.state===W.RECONNECTING&&e.message?.case!==`leave`?e.message?.case===`reconnect`?{isValid:!0,response:e.message.value}:(this.log.debug(`declaring signal reconnected without reconnect response received`,this.logContext),{isValid:!0,response:void 0,shouldProcessFirstMessage:!0}):this.isEstablishingConnection&&e.message?.case===`leave`?{isValid:!1,error:F.leaveRequest(`Received leave request while trying to (re)connect`,e.message.value.reason)}:t?{isValid:!1,error:F.internal(`Unexpected first message`)}:{isValid:!1,error:F.internal(`did not receive join response, got ${e.message?.case} instead`)}}handleConnectionError(e,t){return N(this,void 0,void 0,function*(){try{let n=yield fetch(t);switch(n.status){case 404:return F.serviceNotFound(`v1 RTC path not found. Consider upgrading your LiveKit server version`,`v0-rtc`);case 401:case 403:let e=yield n.text();return F.notAllowed(e,n.status);default:break}return e instanceof F?e:F.internal(`Encountered unknown websocket error during connection: ${e}`,{status:n.status,statusText:n.statusText})}catch(e){return e instanceof F?e:F.serverUnreachable(e instanceof Error?e.message:`server was not reachable`)}})}};function Vd(e){let t={type:`offer`,sdp:e.sdp};switch(e.type){case`answer`:case`offer`:case`pranswer`:case`rollback`:t.type=e.type;break}return t}function Hd(e,t){return new Do({sdp:e.sdp,type:e.type,id:t})}function Ud(e,t,n){let r=new URLSearchParams;return r.set(`access_token`,e),n.reconnect&&(r.set(`reconnect`,`1`),n.sid&&r.set(`sid`,n.sid)),r.set(`auto_subscribe`,n.autoSubscribe?`1`:`0`),r.set(`sdk`,hu()?`reactnative`:`js`),r.set(`version`,t.version),r.set(`protocol`,t.protocol.toString()),t.deviceModel&&r.set(`device_model`,t.deviceModel),t.os&&r.set(`os`,t.os),t.osVersion&&r.set(`os_version`,t.osVersion),t.browser&&r.set(`browser`,t.browser),t.browserVersion&&r.set(`browser_version`,t.browserVersion),n.adaptiveStream&&r.set(`adaptive_stream`,`1`),n.reconnectReason&&r.set(`reconnect_reason`,n.reconnectReason.toString()),navigator.connection?.type&&r.set(`network`,navigator.connection.type),r}function Wd(e,t,n,r){return N(this,void 0,void 0,function*(){let i=new URLSearchParams;i.set(`access_token`,e);let a=new ps({clientInfo:t,connectionSettings:new fs({autoSubscribe:!!n.autoSubscribe,adaptiveStream:!!n.adaptiveStream}),reconnect:!!n.reconnect,participantSid:n.sid?n.sid:void 0,publisherOffer:r});n.reconnectReason&&(a.reconnectReason=n.reconnectReason);let o=a.toBinary(),s,c;if($u()){let e=new CompressionStream(`gzip`),t=e.writable.getWriter();t.write(new Uint8Array(o)),t.close();let n=[],r=e.readable.getReader();for(;;){let{done:e,value:t}=yield r.read();if(e)break;n.push(t)}let i=n.reduce((e,t)=>e+t.length,0),a=new Uint8Array(i),l=0;for(let e of n)a.set(e,l),l+=e.length;s=a,c=hs.GZIP}else s=o,c=hs.NONE;let l=new ms({joinRequest:s,compression:c}).toBinary();return i.set(`join_request`,(e=>{let t=Array.from(e,e=>String.fromCodePoint(e)).join(``);return btoa(t)})(l).replace(/\+/g,`-`).replace(/\//g,`_`)),i})}var Gd=class{constructor(){this.buffer=[],this._totalSize=0}push(e){this.buffer.push(e),this._totalSize+=e.data.byteLength}pop(){let e=this.buffer.shift();return e&&(this._totalSize-=e.data.byteLength),e}getAll(){return this.buffer.slice()}popToSequence(e){for(;this.buffer.length>0&&this.buffer[0].sequence<=e;)this.pop()}alignBufferedAmount(e){for(;this.buffer.length>0;){let t=this.buffer[0];if(this._totalSize-t.data.byteLength<=e)break;this.pop()}}get length(){return this.buffer.length}},Kd=class{constructor(e){this._map=new Map,this._lastCleanup=0,this.ttl=e}set(e,t){let n=Date.now();n-this._lastCleanup>this.ttl/2&&this.cleanup();let r=n+this.ttl;return this._map.set(e,{value:t,expiresAt:r}),this}get(e){let t=this._map.get(e);if(t){if(t.expiresAt<Date.now()){this._map.delete(e);return}return t.value}}has(e){let t=this._map.get(e);return t?t.expiresAt<Date.now()?(this._map.delete(e),!1):!0:!1}delete(e){return this._map.delete(e)}clear(){this._map.clear()}cleanup(){let e=Date.now();for(let[t,n]of this._map.entries())n.expiresAt<e&&this._map.delete(t);this._lastCleanup=e}get size(){return this.cleanup(),this._map.size}forEach(e){this.cleanup();for(let[t,n]of this._map.entries())n.expiresAt>=Date.now()&&e(n.value,t,this.asValueMap())}map(e){this.cleanup();let t=[],n=this.asValueMap();for(let[r,i]of n.entries())t.push(e(i,r,n));return t}asValueMap(){let e=new Map;for(let[t,n]of this._map.entries())n.expiresAt>=Date.now()&&e.set(t,n.value);return e}},qd={},Jd={},Yd={exports:{}},Xd;function Zd(){if(Xd)return Yd.exports;Xd=1;var e=Yd.exports={v:[{name:`version`,reg:/^(\d*)$/}],o:[{name:`origin`,reg:/^(\S*) (\d*) (\d*) (\S*) IP(\d) (\S*)/,names:[`username`,`sessionId`,`sessionVersion`,`netType`,`ipVer`,`address`],format:`%s %s %d %s IP%d %s`}],s:[{name:`name`}],i:[{name:`description`}],u:[{name:`uri`}],e:[{name:`email`}],p:[{name:`phone`}],z:[{name:`timezones`}],r:[{name:`repeats`}],t:[{name:`timing`,reg:/^(\d*) (\d*)/,names:[`start`,`stop`],format:`%d %d`}],c:[{name:`connection`,reg:/^IN IP(\d) (\S*)/,names:[`version`,`ip`],format:`IN IP%d %s`}],b:[{push:`bandwidth`,reg:/^(TIAS|AS|CT|RR|RS):(\d*)/,names:[`type`,`limit`],format:`%s:%s`}],m:[{reg:/^(\w*) (\d*) ([\w/]*)(?: (.*))?/,names:[`type`,`port`,`protocol`,`payloads`],format:`%s %d %s %s`}],a:[{push:`rtp`,reg:/^rtpmap:(\d*) ([\w\-.]*)(?:\s*\/(\d*)(?:\s*\/(\S*))?)?/,names:[`payload`,`codec`,`rate`,`encoding`],format:function(e){return e.encoding?`rtpmap:%d %s/%s/%s`:e.rate?`rtpmap:%d %s/%s`:`rtpmap:%d %s`}},{push:`fmtp`,reg:/^fmtp:(\d*) ([\S| ]*)/,names:[`payload`,`config`],format:`fmtp:%d %s`},{name:`control`,reg:/^control:(.*)/,format:`control:%s`},{name:`rtcp`,reg:/^rtcp:(\d*)(?: (\S*) IP(\d) (\S*))?/,names:[`port`,`netType`,`ipVer`,`address`],format:function(e){return e.address==null?`rtcp:%d`:`rtcp:%d %s IP%d %s`}},{push:`rtcpFbTrrInt`,reg:/^rtcp-fb:(\*|\d*) trr-int (\d*)/,names:[`payload`,`value`],format:`rtcp-fb:%s trr-int %d`},{push:`rtcpFb`,reg:/^rtcp-fb:(\*|\d*) ([\w-_]*)(?: ([\w-_]*))?/,names:[`payload`,`type`,`subtype`],format:function(e){return e.subtype==null?`rtcp-fb:%s %s`:`rtcp-fb:%s %s %s`}},{push:`ext`,reg:/^extmap:(\d+)(?:\/(\w+))?(?: (urn:ietf:params:rtp-hdrext:encrypt))? (\S*)(?: (\S*))?/,names:[`value`,`direction`,`encrypt-uri`,`uri`,`config`],format:function(e){return`extmap:%d`+(e.direction?`/%s`:`%v`)+(e[`encrypt-uri`]?` %s`:`%v`)+` %s`+(e.config?` %s`:``)}},{name:`extmapAllowMixed`,reg:/^(extmap-allow-mixed)/},{push:`crypto`,reg:/^crypto:(\d*) ([\w_]*) (\S*)(?: (\S*))?/,names:[`id`,`suite`,`config`,`sessionConfig`],format:function(e){return e.sessionConfig==null?`crypto:%d %s %s`:`crypto:%d %s %s %s`}},{name:`setup`,reg:/^setup:(\w*)/,format:`setup:%s`},{name:`connectionType`,reg:/^connection:(new|existing)/,format:`connection:%s`},{name:`mid`,reg:/^mid:([^\s]*)/,format:`mid:%s`},{name:`msid`,reg:/^msid:(.*)/,format:`msid:%s`},{name:`ptime`,reg:/^ptime:(\d*(?:\.\d*)*)/,format:`ptime:%d`},{name:`maxptime`,reg:/^maxptime:(\d*(?:\.\d*)*)/,format:`maxptime:%d`},{name:`direction`,reg:/^(sendrecv|recvonly|sendonly|inactive)/},{name:`icelite`,reg:/^(ice-lite)/},{name:`iceUfrag`,reg:/^ice-ufrag:(\S*)/,format:`ice-ufrag:%s`},{name:`icePwd`,reg:/^ice-pwd:(\S*)/,format:`ice-pwd:%s`},{name:`fingerprint`,reg:/^fingerprint:(\S*) (\S*)/,names:[`type`,`hash`],format:`fingerprint:%s %s`},{push:`candidates`,reg:/^candidate:(\S*) (\d*) (\S*) (\d*) (\S*) (\d*) typ (\S*)(?: raddr (\S*) rport (\d*))?(?: tcptype (\S*))?(?: generation (\d*))?(?: network-id (\d*))?(?: network-cost (\d*))?/,names:[`foundation`,`component`,`transport`,`priority`,`ip`,`port`,`type`,`raddr`,`rport`,`tcptype`,`generation`,`network-id`,`network-cost`],format:function(e){var t=`candidate:%s %d %s %d %s %d typ %s`;return t+=e.raddr==null?`%v%v`:` raddr %s rport %d`,t+=e.tcptype==null?`%v`:` tcptype %s`,e.generation!=null&&(t+=` generation %d`),t+=e[`network-id`]==null?`%v`:` network-id %d`,t+=e[`network-cost`]==null?`%v`:` network-cost %d`,t}},{name:`endOfCandidates`,reg:/^(end-of-candidates)/},{name:`remoteCandidates`,reg:/^remote-candidates:(.*)/,format:`remote-candidates:%s`},{name:`iceOptions`,reg:/^ice-options:(\S*)/,format:`ice-options:%s`},{push:`ssrcs`,reg:/^ssrc:(\d*) ([\w_-]*)(?::(.*))?/,names:[`id`,`attribute`,`value`],format:function(e){var t=`ssrc:%d`;return e.attribute!=null&&(t+=` %s`,e.value!=null&&(t+=`:%s`)),t}},{push:`ssrcGroups`,reg:/^ssrc-group:([\x21\x23\x24\x25\x26\x27\x2A\x2B\x2D\x2E\w]*) (.*)/,names:[`semantics`,`ssrcs`],format:`ssrc-group:%s %s`},{name:`msidSemantic`,reg:/^msid-semantic:\s?(\w*) (\S*)/,names:[`semantic`,`token`],format:`msid-semantic: %s %s`},{push:`groups`,reg:/^group:(\w*) (.*)/,names:[`type`,`mids`],format:`group:%s %s`},{name:`rtcpMux`,reg:/^(rtcp-mux)/},{name:`rtcpRsize`,reg:/^(rtcp-rsize)/},{name:`sctpmap`,reg:/^sctpmap:([\w_/]*) (\S*)(?: (\S*))?/,names:[`sctpmapNumber`,`app`,`maxMessageSize`],format:function(e){return e.maxMessageSize==null?`sctpmap:%s %s`:`sctpmap:%s %s %s`}},{name:`xGoogleFlag`,reg:/^x-google-flag:([^\s]*)/,format:`x-google-flag:%s`},{push:`rids`,reg:/^rid:([\d\w]+) (\w+)(?: ([\S| ]*))?/,names:[`id`,`direction`,`params`],format:function(e){return e.params?`rid:%s %s %s`:`rid:%s %s`}},{push:`imageattrs`,reg:RegExp(`^imageattr:(\\d+|\\*)[\\s\\t]+(send|recv)[\\s\\t]+(\\*|\\[\\S+\\](?:[\\s\\t]+\\[\\S+\\])*)(?:[\\s\\t]+(recv|send)[\\s\\t]+(\\*|\\[\\S+\\](?:[\\s\\t]+\\[\\S+\\])*))?`),names:[`pt`,`dir1`,`attrs1`,`dir2`,`attrs2`],format:function(e){return`imageattr:%s %s %s`+(e.dir2?` %s %s`:``)}},{name:`simulcast`,reg:RegExp(`^simulcast:(send|recv) ([a-zA-Z0-9\\-_~;,]+)(?:\\s?(send|recv) ([a-zA-Z0-9\\-_~;,]+))?$`),names:[`dir1`,`list1`,`dir2`,`list2`],format:function(e){return`simulcast:%s %s`+(e.dir2?` %s %s`:``)}},{name:`simulcast_03`,reg:/^simulcast:[\s\t]+([\S+\s\t]+)$/,names:[`value`],format:`simulcast: %s`},{name:`framerate`,reg:/^framerate:(\d+(?:$|\.\d+))/,format:`framerate:%s`},{name:`sourceFilter`,reg:/^source-filter: *(excl|incl) (\S*) (IP4|IP6|\*) (\S*) (.*)/,names:[`filterMode`,`netType`,`addressTypes`,`destAddress`,`srcList`],format:`source-filter: %s %s %s %s %s`},{name:`bundleOnly`,reg:/^(bundle-only)/},{name:`label`,reg:/^label:(.+)/,format:`label:%s`},{name:`sctpPort`,reg:/^sctp-port:(\d+)$/,format:`sctp-port:%s`},{name:`maxMessageSize`,reg:/^max-message-size:(\d+)$/,format:`max-message-size:%s`},{push:`tsRefClocks`,reg:/^ts-refclk:([^\s=]*)(?:=(\S*))?/,names:[`clksrc`,`clksrcExt`],format:function(e){return`ts-refclk:%s`+(e.clksrcExt==null?``:`=%s`)}},{name:`mediaClk`,reg:/^mediaclk:(?:id=(\S*))? *([^\s=]*)(?:=(\S*))?(?: *rate=(\d+)\/(\d+))?/,names:[`id`,`mediaClockName`,`mediaClockValue`,`rateNumerator`,`rateDenominator`],format:function(e){var t=`mediaclk:`;return t+=e.id==null?`%v%s`:`id=%s %s`,t+=e.mediaClockValue==null?``:`=%s`,t+=e.rateNumerator==null?``:` rate=%s`,t+=e.rateDenominator==null?``:`/%s`,t}},{name:`keywords`,reg:/^keywds:(.+)$/,format:`keywds:%s`},{name:`content`,reg:/^content:(.+)/,format:`content:%s`},{name:`bfcpFloorCtrl`,reg:/^floorctrl:(c-only|s-only|c-s)/,format:`floorctrl:%s`},{name:`bfcpConfId`,reg:/^confid:(\d+)/,format:`confid:%s`},{name:`bfcpUserId`,reg:/^userid:(\d+)/,format:`userid:%s`},{name:`bfcpFloorId`,reg:/^floorid:(.+) (?:m-stream|mstrm):(.+)/,names:[`id`,`mStream`],format:`floorid:%s mstrm:%s`},{push:`invalid`,names:[`value`]}]};return Object.keys(e).forEach(function(t){e[t].forEach(function(e){e.reg||=/(.*)/,e.format||=`%s`})}),Yd.exports}var Qd;function $d(){return Qd?Jd:(Qd=1,(function(e){var t=function(e){return String(Number(e))===e?Number(e):e},n=function(e,n,r,i){if(i&&!r)n[i]=t(e[1]);else for(var a=0;a<r.length;a+=1)e[a+1]!=null&&(n[r[a]]=t(e[a+1]))},r=function(e,t,r){var i=e.name&&e.names;e.push&&!t[e.push]?t[e.push]=[]:i&&!t[e.name]&&(t[e.name]={});var a=e.push?{}:i?t[e.name]:t;n(r.match(e.reg),a,e.names,e.name),e.push&&t[e.push].push(a)},i=Zd(),a=RegExp.prototype.test.bind(/^([a-z])=(.*)/);e.parse=function(e){var t={},n=[],o=t;return e.split(/(\r\n|\r|\n)/).filter(a).forEach(function(e){var t=e[0],a=e.slice(2);t===`m`&&(n.push({rtp:[],fmtp:[]}),o=n[n.length-1]);for(var s=0;s<(i[t]||[]).length;s+=1){var c=i[t][s];if(c.reg.test(a))return r(c,o,a)}}),t.media=n,t};var o=function(e,n){var r=n.split(/=(.+)/,2);return r.length===2?e[r[0]]=t(r[1]):r.length===1&&n.length>1&&(e[r[0]]=void 0),e};e.parseParams=function(e){return e.split(/;\s?/).reduce(o,{})},e.parseFmtpConfig=e.parseParams,e.parsePayloads=function(e){return e.toString().split(` `).map(Number)},e.parseRemoteCandidates=function(e){for(var n=[],r=e.split(` `).map(t),i=0;i<r.length;i+=3)n.push({component:r[i],ip:r[i+1],port:r[i+2]});return n},e.parseImageAttributes=function(e){return e.split(` `).map(function(e){return e.substring(1,e.length-1).split(`,`).reduce(o,{})})},e.parseSimulcastStreamList=function(e){return e.split(`;`).map(function(e){return e.split(`,`).map(function(e){var n,r=!1;return e[0]===`~`?(n=t(e.substring(1,e.length)),r=!0):n=t(e),{scid:n,paused:r}})})}})(Jd),Jd)}var ef,tf;function nf(){if(tf)return ef;tf=1;var e=Zd(),t=/%[sdv%]/g,n=function(e){var n=1,r=arguments,i=r.length;return e.replace(t,function(e){if(n>=i)return e;var t=r[n];switch(n+=1,e){case`%%`:return`%`;case`%s`:return String(t);case`%d`:return Number(t);case`%v`:return``}})},r=function(e,t,r){var i=t.format instanceof Function?t.format(t.push?r:r[t.name]):t.format,a=[e+`=`+i];if(t.names)for(var o=0;o<t.names.length;o+=1){var s=t.names[o];t.name?a.push(r[t.name][s]):a.push(r[t.names[o]])}else a.push(r[t.name]);return n.apply(null,a)},i=[`v`,`o`,`s`,`i`,`u`,`e`,`p`,`c`,`b`,`t`,`r`,`z`,`a`],a=[`i`,`c`,`b`,`a`];return ef=function(t,n){n||={},t.version??=0,t.name??=` `,t.media.forEach(function(e){e.payloads??=``});var o=n.outerOrder||i,s=n.innerOrder||a,c=[];return o.forEach(function(n){e[n].forEach(function(e){e.name in t&&t[e.name]!=null?c.push(r(n,e,t)):e.push in t&&t[e.push]!=null&&t[e.push].forEach(function(t){c.push(r(n,e,t))})})}),t.media.forEach(function(t){c.push(r(`m`,e.m[0],t)),s.forEach(function(n){e[n].forEach(function(e){e.name in t&&t[e.name]!=null?c.push(r(n,e,t)):e.push in t&&t[e.push]!=null&&t[e.push].forEach(function(t){c.push(r(n,e,t))})})})}),c.join(`\r
|
|
65
|
+
`);e.RTCSessionDescription&&t instanceof e.RTCSessionDescription?arguments[0]=new e.RTCSessionDescription({type:t.type,sdp:n}):t.sdp=n}return n.apply(this,arguments)}}function Kc(e,t){if(!(e.RTCPeerConnection&&e.RTCPeerConnection.prototype))return;let n=e.RTCPeerConnection.prototype.addIceCandidate;!n||n.length===0||(e.RTCPeerConnection.prototype.addIceCandidate=function(){return arguments[0]?(t.browser===`chrome`&&t.version<78||t.browser===`firefox`&&t.version<68||t.browser===`safari`)&&arguments[0]&&arguments[0].candidate===``?Promise.resolve():n.apply(this,arguments):(arguments[1]&&arguments[1].apply(null),Promise.resolve())})}function qc(e,t){if(!(e.RTCPeerConnection&&e.RTCPeerConnection.prototype))return;let n=e.RTCPeerConnection.prototype.setLocalDescription;!n||n.length===0||(e.RTCPeerConnection.prototype.setLocalDescription=function(){let e=arguments[0]||{};if(typeof e!=`object`||e.type&&e.sdp)return n.apply(this,arguments);if(e={type:e.type,sdp:e.sdp},!e.type)switch(this.signalingState){case`stable`:case`have-local-offer`:case`have-remote-pranswer`:e.type=`offer`;break;default:e.type=`answer`;break}return e.sdp||e.type!==`offer`&&e.type!==`answer`?n.apply(this,[e]):(e.type===`offer`?this.createOffer:this.createAnswer).apply(this).then(e=>n.apply(this,[e]))})}var Jc=Object.freeze({__proto__:null,removeExtmapAllowMixed:Gc,shimAddIceCandidateNullOrEmpty:Kc,shimConnectionState:Wc,shimMaxMessageSize:Hc,shimParameterlessSetLocalDescription:qc,shimRTCIceCandidate:Bc,shimRTCIceCandidateRelayProtocol:Vc,shimSendThrowTypeError:Uc});function Yc(){let{window:e}=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{},t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{shimChrome:!0,shimFirefox:!0,shimSafari:!0},n=qs,r=Ys(e),i={browserDetails:r,commonShim:Jc,extractVersion:Us,disableLog:Gs,disableWarnings:Ks,sdp:zc};switch(r.browser){case`chrome`:if(!uc||!cc||!t.shimChrome)return n(`Chrome shim is not included in this adapter release.`),i;if(r.version===null)return n(`Chrome shim can not determine version, not shimming.`),i;n(`adapter.js shimming chrome.`),i.browserShim=uc,Kc(e,r),qc(e),tc(e,r),nc(e),cc(e,r),rc(e),sc(e,r),ic(e),ac(e),lc(e,r),Bc(e),Vc(e),Wc(e),Hc(e,r),Uc(e),Gc(e,r);break;case`firefox`:if(!Cc||!mc||!t.shimFirefox)return n(`Firefox shim is not included in this adapter release.`),i;n(`adapter.js shimming firefox.`),i.browserShim=Cc,Kc(e,r),qc(e),dc(e,r),mc(e,r),pc(e),_c(e),hc(e),gc(e),vc(e),yc(e),bc(e),xc(e),Sc(e),Bc(e),Wc(e),Hc(e,r),Uc(e);break;case`safari`:if(!Nc||!t.shimSafari)return n(`Safari shim is not included in this adapter release.`),i;n(`adapter.js shimming safari.`),i.browserShim=Nc,Kc(e,r),qc(e),kc(e),jc(e),Ec(e),wc(e),Tc(e),Ac(e),Dc(e),Mc(e),Bc(e),Vc(e),Hc(e,r),Uc(e),Gc(e,r);break;default:n(`Unsupported browser!`);break}return i}Yc({window:typeof window>`u`?void 0:window});var Xc,Zc,Qc=class extends (Zc=Promise){constructor(e){super(e)}catch(e){return super.catch(e)}static reject(e){return super.reject(e)}static all(e){return super.all(e)}static race(e){return super.race(e)}};Xc=Qc,Qc.resolve=e=>Reflect.get(Zc,`resolve`,Xc).call(Xc,e);var $c=/version\/(\d+(\.?_?\d+)+)/i,el;function tl(e){let t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:!0;if(e===void 0&&typeof navigator>`u`)return;let n=(e??navigator.userAgent).toLowerCase();return(el===void 0||t)&&(el=nl.find(e=>{let{test:t}=e;return t.test(n)})?.describe(n)),el}var nl=[{test:/firefox|iceweasel|fxios/i,describe(e){return{name:`Firefox`,version:rl(/(?:firefox|iceweasel|fxios)[\s/](\d+(\.?_?\d+)+)/i,e),os:e.toLowerCase().includes(`fxios`)?`iOS`:void 0,osVersion:il(e)}}},{test:/chrom|crios|crmo/i,describe(e){return{name:`Chrome`,version:rl(/(?:chrome|chromium|crios|crmo)\/(\d+(\.?_?\d+)+)/i,e),os:e.toLowerCase().includes(`crios`)?`iOS`:void 0,osVersion:il(e)}}},{test:/safari|applewebkit/i,describe(e){return{name:`Safari`,version:rl($c,e),os:e.includes(`mobile/`)?`iOS`:`macOS`,osVersion:il(e)}}}];function rl(e,t){let n=arguments.length>2&&arguments[2]!==void 0?arguments[2]:1,r=t.match(e);return r&&r.length>=n&&r[n]||``}function il(e){return e.includes(`mac os`)?rl(/\(.+?(\d+_\d+(:?_\d+)?)/,e,1).replace(/_/g,`.`):void 0}var al=`2.18.1`,ol=class extends Error{constructor(e,t,n){super(t||`an error has occurred`),this.name=`LiveKitError`,this.code=e,n?.cause!==void 0&&(this.cause=n?.cause)}},sl=class extends ol{},P;(function(e){e[e.NotAllowed=0]=`NotAllowed`,e[e.ServerUnreachable=1]=`ServerUnreachable`,e[e.InternalError=2]=`InternalError`,e[e.Cancelled=3]=`Cancelled`,e[e.LeaveRequest=4]=`LeaveRequest`,e[e.Timeout=5]=`Timeout`,e[e.WebSocket=6]=`WebSocket`,e[e.ServiceNotFound=7]=`ServiceNotFound`})(P||={});var F=class e extends sl{constructor(e,t,n,r){super(1,e),this.name=`ConnectionError`,this.status=n,this.reason=t,this.context=r,this.reasonName=P[t]}static notAllowed(t,n,r){return new e(t,P.NotAllowed,n,r)}static timeout(t){return new e(t,P.Timeout)}static leaveRequest(t,n){return new e(t,P.LeaveRequest,void 0,n)}static internal(t,n){return new e(t,P.InternalError,void 0,n)}static cancelled(t){return new e(t,P.Cancelled)}static serverUnreachable(t,n){return new e(t,P.ServerUnreachable,n)}static websocket(t,n,r){return new e(t,P.WebSocket,n,r)}static serviceNotFound(t,n){return new e(t,P.ServiceNotFound,void 0,n)}},cl=class extends ol{constructor(e){super(21,e??`device is unsupported`),this.name=`DeviceUnsupportedError`}},ll=class extends ol{constructor(e){super(20,e??`track is invalid`),this.name=`TrackInvalidError`}},ul=class extends ol{constructor(e){super(10,e??`unsupported server`),this.name=`UnsupportedServer`}},I=class extends ol{constructor(e){super(12,e??`unexpected connection state`),this.name=`UnexpectedConnectionState`}},dl=class extends ol{constructor(e){super(13,e??`unable to negotiate`),this.name=`NegotiationError`}},fl=class extends ol{constructor(e,t){super(15,e),this.name=`PublishTrackError`,this.status=t}},pl=class extends sl{constructor(e,t){super(15,e),this.name=`SignalRequestError`,this.reason=t,this.reasonName=typeof t==`string`?t:ds[t]}},ml;(function(e){e[e.AlreadyOpened=0]=`AlreadyOpened`,e[e.AbnormalEnd=1]=`AbnormalEnd`,e[e.DecodeFailed=2]=`DecodeFailed`,e[e.LengthExceeded=3]=`LengthExceeded`,e[e.Incomplete=4]=`Incomplete`,e[e.HandlerAlreadyRegistered=7]=`HandlerAlreadyRegistered`,e[e.EncryptionTypeMismatch=8]=`EncryptionTypeMismatch`})(ml||={});var hl=class extends sl{constructor(e,t){super(16,e),this.name=`DataStreamError`,this.reason=t,this.reasonName=ml[t]}},gl=class extends ol{constructor(e){super(18,e),this.name=`SignalReconnectError`}},_l;(function(e){e.PermissionDenied=`PermissionDenied`,e.NotFound=`NotFound`,e.DeviceInUse=`DeviceInUse`,e.Other=`Other`})(_l||={}),(function(e){function t(t){if(t&&`name`in t)return t.name===`NotFoundError`||t.name===`DevicesNotFoundError`?e.NotFound:t.name===`NotAllowedError`||t.name===`PermissionDeniedError`?e.PermissionDenied:t.name===`NotReadableError`||t.name===`TrackStartError`?e.DeviceInUse:e.Other}e.getFailure=t})(_l||={});var vl=class{};vl.setTimeout=function(){return setTimeout(...arguments)},vl.setInterval=function(){return setInterval(...arguments)},vl.clearTimeout=function(){return clearTimeout(...arguments)},vl.clearInterval=function(){return clearInterval(...arguments)};var L;(function(e){e.Connected=`connected`,e.Reconnecting=`reconnecting`,e.SignalReconnecting=`signalReconnecting`,e.Reconnected=`reconnected`,e.Disconnected=`disconnected`,e.ConnectionStateChanged=`connectionStateChanged`,e.Moved=`moved`,e.MediaDevicesChanged=`mediaDevicesChanged`,e.ParticipantConnected=`participantConnected`,e.ParticipantDisconnected=`participantDisconnected`,e.TrackPublished=`trackPublished`,e.TrackSubscribed=`trackSubscribed`,e.TrackSubscriptionFailed=`trackSubscriptionFailed`,e.TrackUnpublished=`trackUnpublished`,e.TrackUnsubscribed=`trackUnsubscribed`,e.TrackMuted=`trackMuted`,e.TrackUnmuted=`trackUnmuted`,e.LocalTrackPublished=`localTrackPublished`,e.LocalTrackUnpublished=`localTrackUnpublished`,e.LocalAudioSilenceDetected=`localAudioSilenceDetected`,e.ActiveSpeakersChanged=`activeSpeakersChanged`,e.ParticipantMetadataChanged=`participantMetadataChanged`,e.ParticipantNameChanged=`participantNameChanged`,e.ParticipantAttributesChanged=`participantAttributesChanged`,e.ParticipantActive=`participantActive`,e.RoomMetadataChanged=`roomMetadataChanged`,e.DataReceived=`dataReceived`,e.SipDTMFReceived=`sipDTMFReceived`,e.TranscriptionReceived=`transcriptionReceived`,e.ConnectionQualityChanged=`connectionQualityChanged`,e.TrackStreamStateChanged=`trackStreamStateChanged`,e.TrackSubscriptionPermissionChanged=`trackSubscriptionPermissionChanged`,e.TrackSubscriptionStatusChanged=`trackSubscriptionStatusChanged`,e.AudioPlaybackStatusChanged=`audioPlaybackChanged`,e.VideoPlaybackStatusChanged=`videoPlaybackChanged`,e.MediaDevicesError=`mediaDevicesError`,e.ParticipantPermissionsChanged=`participantPermissionsChanged`,e.SignalConnected=`signalConnected`,e.RecordingStatusChanged=`recordingStatusChanged`,e.ParticipantEncryptionStatusChanged=`participantEncryptionStatusChanged`,e.EncryptionError=`encryptionError`,e.DCBufferStatusChanged=`dcBufferStatusChanged`,e.ActiveDeviceChanged=`activeDeviceChanged`,e.ChatMessage=`chatMessage`,e.LocalTrackSubscribed=`localTrackSubscribed`,e.MetricsReceived=`metricsReceived`,e.DataTrackPublished=`dataTrackPublished`,e.DataTrackUnpublished=`dataTrackUnpublished`,e.LocalDataTrackPublished=`localDataTrackPublished`,e.LocalDataTrackUnpublished=`localDataTrackUnpublished`})(L||={});var R;(function(e){e.TrackPublished=`trackPublished`,e.TrackSubscribed=`trackSubscribed`,e.TrackSubscriptionFailed=`trackSubscriptionFailed`,e.TrackUnpublished=`trackUnpublished`,e.TrackUnsubscribed=`trackUnsubscribed`,e.TrackMuted=`trackMuted`,e.TrackUnmuted=`trackUnmuted`,e.LocalTrackPublished=`localTrackPublished`,e.LocalTrackUnpublished=`localTrackUnpublished`,e.LocalTrackCpuConstrained=`localTrackCpuConstrained`,e.LocalSenderCreated=`localSenderCreated`,e.ParticipantMetadataChanged=`participantMetadataChanged`,e.ParticipantNameChanged=`participantNameChanged`,e.DataReceived=`dataReceived`,e.SipDTMFReceived=`sipDTMFReceived`,e.TranscriptionReceived=`transcriptionReceived`,e.IsSpeakingChanged=`isSpeakingChanged`,e.ConnectionQualityChanged=`connectionQualityChanged`,e.TrackStreamStateChanged=`trackStreamStateChanged`,e.TrackSubscriptionPermissionChanged=`trackSubscriptionPermissionChanged`,e.TrackSubscriptionStatusChanged=`trackSubscriptionStatusChanged`,e.TrackCpuConstrained=`trackCpuConstrained`,e.MediaDevicesError=`mediaDevicesError`,e.AudioStreamAcquired=`audioStreamAcquired`,e.ParticipantPermissionsChanged=`participantPermissionsChanged`,e.PCTrackAdded=`pcTrackAdded`,e.AttributesChanged=`attributesChanged`,e.LocalTrackSubscribed=`localTrackSubscribed`,e.ChatMessage=`chatMessage`,e.Active=`active`})(R||={});var z;(function(e){e.TransportsCreated=`transportsCreated`,e.Connected=`connected`,e.Disconnected=`disconnected`,e.Resuming=`resuming`,e.Resumed=`resumed`,e.Restarting=`restarting`,e.Restarted=`restarted`,e.SignalResumed=`signalResumed`,e.SignalRestarted=`signalRestarted`,e.Closing=`closing`,e.MediaTrackAdded=`mediaTrackAdded`,e.ActiveSpeakersUpdate=`activeSpeakersUpdate`,e.DataPacketReceived=`dataPacketReceived`,e.RTPVideoMapUpdate=`rtpVideoMapUpdate`,e.DCBufferStatusChanged=`dcBufferStatusChanged`,e.ParticipantUpdate=`participantUpdate`,e.RoomUpdate=`roomUpdate`,e.SpeakersChanged=`speakersChanged`,e.StreamStateChanged=`streamStateChanged`,e.ConnectionQualityUpdate=`connectionQualityUpdate`,e.SubscriptionError=`subscriptionError`,e.SubscriptionPermissionUpdate=`subscriptionPermissionUpdate`,e.RemoteMute=`remoteMute`,e.SubscribedQualityUpdate=`subscribedQualityUpdate`,e.LocalTrackUnpublished=`localTrackUnpublished`,e.LocalTrackSubscribed=`localTrackSubscribed`,e.Offline=`offline`,e.SignalRequestResponse=`signalRequestResponse`,e.SignalConnected=`signalConnected`,e.RoomMoved=`roomMoved`,e.PublishDataTrackResponse=`publishDataTrackResponse`,e.UnPublishDataTrackResponse=`unPublishDataTrackResponse`,e.DataTrackSubscriberHandles=`dataTrackSubscriberHandles`,e.DataTrackPacketReceived=`dataTrackPacketReceived`,e.Joined=`joined`})(z||={});var B;(function(e){e.Message=`message`,e.Muted=`muted`,e.Unmuted=`unmuted`,e.Restarted=`restarted`,e.Ended=`ended`,e.Subscribed=`subscribed`,e.Unsubscribed=`unsubscribed`,e.CpuConstrained=`cpuConstrained`,e.UpdateSettings=`updateSettings`,e.UpdateSubscription=`updateSubscription`,e.AudioPlaybackStarted=`audioPlaybackStarted`,e.AudioPlaybackFailed=`audioPlaybackFailed`,e.AudioSilenceDetected=`audioSilenceDetected`,e.VisibilityChanged=`visibilityChanged`,e.VideoDimensionsChanged=`videoDimensionsChanged`,e.VideoPlaybackStarted=`videoPlaybackStarted`,e.VideoPlaybackFailed=`videoPlaybackFailed`,e.ElementAttached=`elementAttached`,e.ElementDetached=`elementDetached`,e.UpstreamPaused=`upstreamPaused`,e.UpstreamResumed=`upstreamResumed`,e.SubscriptionPermissionChanged=`subscriptionPermissionChanged`,e.SubscriptionStatusChanged=`subscriptionStatusChanged`,e.SubscriptionFailed=`subscriptionFailed`,e.TrackProcessorUpdate=`trackProcessorUpdate`,e.AudioTrackFeatureUpdate=`audioTrackFeatureUpdate`,e.TranscriptionReceived=`transcriptionReceived`,e.TimeSyncUpdate=`timeSyncUpdate`,e.PreConnectBufferFlushed=`preConnectBufferFlushed`})(B||={});function yl(e){return e===void 0?e:typeof structuredClone==`function`?typeof e==`object`&&e?structuredClone(Object.assign({},e)):structuredClone(e):JSON.parse(JSON.stringify(e))}var V=class{constructor(e,t,n,r,i){if(typeof e==`object`)this.width=e.width,this.height=e.height,this.aspectRatio=e.aspectRatio,this.encoding={maxBitrate:e.maxBitrate,maxFramerate:e.maxFramerate,priority:e.priority};else if(t!==void 0&&n!==void 0)this.width=e,this.height=t,this.aspectRatio=e/t,this.encoding={maxBitrate:n,maxFramerate:r,priority:i};else throw TypeError(`Unsupported options: provide at least width, height and maxBitrate`)}get resolution(){return{width:this.width,height:this.height,frameRate:this.encoding.maxFramerate,aspectRatio:this.aspectRatio}}},bl=[`vp8`,`h264`],xl=[`vp8`,`h264`,`vp9`,`av1`,`h265`];function Sl(e){return!!bl.find(t=>t===e)}var Cl=Sl,wl;(function(e){e[e.PREFER_REGRESSION=0]=`PREFER_REGRESSION`,e[e.SIMULCAST=1]=`SIMULCAST`,e[e.REGRESSION=2]=`REGRESSION`})(wl||={});var Tl;(function(e){e.telephone={maxBitrate:12e3},e.speech={maxBitrate:24e3},e.music={maxBitrate:48e3},e.musicStereo={maxBitrate:64e3},e.musicHighQuality={maxBitrate:96e3},e.musicHighQualityStereo={maxBitrate:128e3}})(Tl||={});var El={h90:new V(160,90,9e4,20),h180:new V(320,180,16e4,20),h216:new V(384,216,18e4,20),h360:new V(640,360,45e4,20),h540:new V(960,540,8e5,25),h720:new V(1280,720,17e5,30),h1080:new V(1920,1080,3e6,30),h1440:new V(2560,1440,5e6,30),h2160:new V(3840,2160,8e6,30)},Dl={h120:new V(160,120,7e4,20),h180:new V(240,180,125e3,20),h240:new V(320,240,14e4,20),h360:new V(480,360,33e4,20),h480:new V(640,480,5e5,20),h540:new V(720,540,6e5,25),h720:new V(960,720,13e5,30),h1080:new V(1440,1080,23e5,30),h1440:new V(1920,1440,38e5,30)},Ol={h360fps3:new V(640,360,2e5,3,`medium`),h360fps15:new V(640,360,4e5,15,`medium`),h720fps5:new V(1280,720,8e5,5,`medium`),h720fps15:new V(1280,720,15e5,15,`medium`),h720fps30:new V(1280,720,2e6,30,`medium`),h1080fps15:new V(1920,1080,25e5,15,`medium`),h1080fps30:new V(1920,1080,5e6,30,`medium`),original:new V(0,0,7e6,30,`medium`)};function kl(e,t,n){var r,i;let{optionsWithoutProcessor:a,audioProcessor:o,videoProcessor:s}=Vl(e??{}),c=t?.processor,l=n?.processor,u=a??{};return u.audio===!0&&(u.audio={}),u.video===!0&&(u.video={}),u.audio&&(Al(u.audio,t),(r=u.audio).deviceId??(r.deviceId={ideal:`default`}),(o||c)&&(u.audio.processor=o??c)),u.video&&(Al(u.video,n),(i=u.video).deviceId??(i.deviceId={ideal:`default`}),(s||l)&&(u.video.processor=s??l)),u}function Al(e,t){return Object.keys(t).forEach(n=>{e[n]===void 0&&(e[n]=t[n])}),e}function jl(e){var t,n;let r={};if(e.video)if(typeof e.video==`object`){let n={},i=n,a=e.video;Object.keys(a).forEach(e=>{switch(e){case`resolution`:Al(i,a.resolution);break;default:i[e]=a[e]}}),r.video=n,(t=r.video).deviceId??(t.deviceId={ideal:`default`})}else r.video=e.video?{deviceId:{ideal:`default`}}:!1;else r.video=!1;return e.audio?typeof e.audio==`object`?(r.audio=e.audio,(n=r.audio).deviceId??(n.deviceId={ideal:`default`})):r.audio={deviceId:{ideal:`default`}}:r.audio=!1,r}function Ml(e){return N(this,arguments,void 0,function(e){let t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:200;return function*(){let n=Nl();if(n){let r=n.createAnalyser();r.fftSize=2048;let i=r.frequencyBinCount,a=new Uint8Array(i);n.createMediaStreamSource(new MediaStream([e.mediaStreamTrack])).connect(r),yield $l(t),r.getByteTimeDomainData(a);let o=a.some(e=>e!==128&&e!==0);return n.close(),!o}return!1}()})}function Nl(){let e=typeof window<`u`&&(window.AudioContext||window.webkitAudioContext);if(e){let t=new e({latencyHint:`interactive`});if(t.state===`suspended`&&typeof window<`u`&&window.document?.body){let e=()=>N(this,void 0,void 0,function*(){var n;try{t.state===`suspended`&&(yield t.resume())}catch(e){console.warn(`Error trying to auto-resume audio context`,e)}finally{(n=window.document.body)==null||n.removeEventListener(`click`,e)}});t.addEventListener(`statechange`,()=>{var n;t.state===`closed`&&((n=window.document.body)==null||n.removeEventListener(`click`,e))}),window.document.body.addEventListener(`click`,e)}return t}}function Pl(e){return e===`audioinput`?U.Source.Microphone:e===`videoinput`?U.Source.Camera:U.Source.Unknown}function Fl(e){if(e===U.Source.Microphone)return`audioinput`;if(e===U.Source.Camera)return`videoinput`}function Il(e){let t=e.video??!0;return e.resolution&&e.resolution.width>0&&e.resolution.height>0&&(t=typeof t==`boolean`?{}:t,t=lu()?Object.assign(Object.assign({},t),{width:{max:e.resolution.width},height:{max:e.resolution.height},frameRate:e.resolution.frameRate}):Object.assign(Object.assign({},t),{width:{ideal:e.resolution.width},height:{ideal:e.resolution.height},frameRate:e.resolution.frameRate})),{audio:e.audio??!1,video:t,controller:e.controller,selfBrowserSurface:e.selfBrowserSurface,surfaceSwitching:e.surfaceSwitching,systemAudio:e.systemAudio,preferCurrentTab:e.preferCurrentTab}}function Ll(e){return e.split(`/`)[1].toLowerCase()}function Rl(e){let t=[];return e.forEach(e=>{e.track!==void 0&&t.push(new Eo({cid:e.track.mediaStreamID,track:e.trackInfo}))}),t}function H(e){return`mediaStreamTrack`in e?{trackID:e.sid,source:e.source,muted:e.isMuted,enabled:e.mediaStreamTrack.enabled,kind:e.kind,streamID:e.mediaStreamID,streamTrackID:e.mediaStreamTrack.id}:{trackID:e.trackSid,enabled:e.isEnabled,muted:e.isMuted,trackInfo:Object.assign({mimeType:e.mimeType,name:e.trackName,encrypted:e.isEncrypted,kind:e.kind,source:e.source},e.track?H(e.track):{})}}function zl(){return typeof RTCRtpReceiver<`u`&&`getSynchronizationSources`in RTCRtpReceiver}function Bl(e,t){e===void 0&&(e={}),t===void 0&&(t={});let n=[...Object.keys(t),...Object.keys(e)],r={};for(let i of n)e[i]!==t[i]&&(r[i]=t[i]??``);return r}function Vl(e){let t=Object.assign({},e),n,r;return typeof t.audio==`object`&&t.audio.processor&&(n=t.audio.processor,t.audio=Object.assign(Object.assign({},t.audio),{processor:void 0})),typeof t.video==`object`&&t.video.processor&&(r=t.video.processor,t.video=Object.assign(Object.assign({},t.video),{processor:void 0})),{audioProcessor:n,videoProcessor:r,optionsWithoutProcessor:yl(t)}}function Hl(e){switch(e){case ua.CAMERA:return U.Source.Camera;case ua.MICROPHONE:return U.Source.Microphone;case ua.SCREEN_SHARE:return U.Source.ScreenShare;case ua.SCREEN_SHARE_AUDIO:return U.Source.ScreenShareAudio;default:return U.Source.Unknown}}function Ul(e,t){return e.width*e.height<t.width*t.height}function Wl(e,t){return e.layers?.find(e=>e.quality===t)}var Gl=5e3,Kl=[],ql;(function(e){e[e.LOW=0]=`LOW`,e[e.MEDIUM=1]=`MEDIUM`,e[e.HIGH=2]=`HIGH`})(ql||={});var U=class e extends Bs.EventEmitter{get streamState(){return this._streamState}setStreamState(e){this._streamState=e}constructor(t,n){let r=arguments.length>2&&arguments[2]!==void 0?arguments[2]:{};super(),this.attachedElements=[],this.isMuted=!1,this._streamState=e.StreamState.Active,this.isInBackground=!1,this._currentBitrate=0,this.log=M,this.appVisibilityChangedListener=()=>{this.backgroundTimeout&&clearTimeout(this.backgroundTimeout),document.visibilityState===`hidden`?this.backgroundTimeout=setTimeout(()=>this.handleAppVisibilityChanged(),Gl):this.handleAppVisibilityChanged()},this.log=Es(r.loggerName??Ts.Track),this.loggerContextCb=r.loggerContextCb,this.setMaxListeners(100),this.kind=n,this._mediaStreamTrack=t,this._mediaStreamID=t.id,this.source=e.Source.Unknown}get logContext(){return Object.assign(Object.assign({},this.loggerContextCb?.call(this)),H(this))}get currentBitrate(){return this._currentBitrate}get mediaStreamTrack(){return this._mediaStreamTrack}get mediaStreamID(){return this._mediaStreamID}attach(t){let n=`audio`;this.kind===e.Kind.Video&&(n=`video`),this.attachedElements.length===0&&this.kind===e.Kind.Video&&this.addAppVisibilityListener(),t||(n===`audio`&&(Kl.forEach(e=>{e.parentElement===null&&!t&&(t=e)}),t&&Kl.splice(Kl.indexOf(t),1)),t||=document.createElement(n)),this.attachedElements.includes(t)||this.attachedElements.push(t),Jl(this.mediaStreamTrack,t);let r=t.srcObject.getTracks(),i=r.some(e=>e.kind===`audio`);return t.play().then(()=>{this.emit(i?B.AudioPlaybackStarted:B.VideoPlaybackStarted)}).catch(e=>{e.name===`NotAllowedError`?this.emit(i?B.AudioPlaybackFailed:B.VideoPlaybackFailed,e):e.name===`AbortError`?M.debug(`${i?`audio`:`video`} playback aborted, likely due to new play request`):M.warn(`could not playback ${i?`audio`:`video`}`,e),i&&t&&r.some(e=>e.kind===`video`)&&e.name===`NotAllowedError`&&(t.muted=!0,t.play().catch(()=>{}))}),this.emit(B.ElementAttached,t),t}detach(e){try{if(e){Yl(this.mediaStreamTrack,e);let t=this.attachedElements.indexOf(e);return t>=0&&(this.attachedElements.splice(t,1),this.recycleElement(e),this.emit(B.ElementDetached,e)),e}let t=[];return this.attachedElements.forEach(e=>{Yl(this.mediaStreamTrack,e),t.push(e),this.recycleElement(e),this.emit(B.ElementDetached,e)}),this.attachedElements=[],t}finally{this.attachedElements.length===0&&this.removeAppVisibilityListener()}}stop(){this.stopMonitor(),this._mediaStreamTrack.stop()}enable(){this._mediaStreamTrack.enabled=!0}disable(){this._mediaStreamTrack.enabled=!1}stopMonitor(){this.monitorInterval&&clearInterval(this.monitorInterval),this.timeSyncHandle&&cancelAnimationFrame(this.timeSyncHandle)}updateLoggerOptions(e){e.loggerName&&(this.log=Es(e.loggerName)),e.loggerContextCb&&(this.loggerContextCb=e.loggerContextCb)}recycleElement(e){if(e instanceof HTMLAudioElement){let t=!0;e.pause(),Kl.forEach(e=>{e.parentElement||(t=!1)}),t&&Kl.push(e)}}handleAppVisibilityChanged(){return N(this,void 0,void 0,function*(){this.isInBackground=document.visibilityState===`hidden`,!this.isInBackground&&this.kind===e.Kind.Video&&setTimeout(()=>this.attachedElements.forEach(e=>e.play().catch(()=>{})),0)})}addAppVisibilityListener(){hu()?(this.isInBackground=document.visibilityState===`hidden`,document.addEventListener(`visibilitychange`,this.appVisibilityChangedListener)):this.isInBackground=!1}removeAppVisibilityListener(){hu()&&document.removeEventListener(`visibilitychange`,this.appVisibilityChangedListener)}};function Jl(e,t){let n;n=t.srcObject instanceof MediaStream?t.srcObject:new MediaStream;let r;r=e.kind===`audio`?n.getAudioTracks():n.getVideoTracks(),r.includes(e)||(r.forEach(e=>{n.removeTrack(e)}),n.addTrack(e)),(!lu()||!(t instanceof HTMLVideoElement))&&(t.autoplay=!0),t.muted=n.getAudioTracks().length===0,t instanceof HTMLVideoElement&&(t.playsInline=!0),t.srcObject!==n&&(t.srcObject=n,(lu()||su())&&t instanceof HTMLVideoElement&&setTimeout(()=>{t.srcObject=n,t.play().catch(()=>{})},0))}function Yl(e,t){if(t.srcObject instanceof MediaStream){let n=t.srcObject;n.removeTrack(e),n.getTracks().length>0?t.srcObject=n:t.srcObject=null}}(function(e){let t;(function(e){e.Audio=`audio`,e.Video=`video`,e.Unknown=`unknown`})(t=e.Kind||={});let n;(function(e){e.Camera=`camera`,e.Microphone=`microphone`,e.ScreenShare=`screen_share`,e.ScreenShareAudio=`screen_share_audio`,e.Unknown=`unknown`})(n=e.Source||={});let r;(function(e){e.Active=`active`,e.Paused=`paused`,e.Unknown=`unknown`})(r=e.StreamState||={});function i(e){switch(e){case t.Audio:return la.AUDIO;case t.Video:return la.VIDEO;default:return la.DATA}}e.kindToProto=i;function a(e){switch(e){case la.AUDIO:return t.Audio;case la.VIDEO:return t.Video;default:return t.Unknown}}e.kindFromProto=a;function o(e){switch(e){case n.Camera:return ua.CAMERA;case n.Microphone:return ua.MICROPHONE;case n.ScreenShare:return ua.SCREEN_SHARE;case n.ScreenShareAudio:return ua.SCREEN_SHARE_AUDIO;default:return ua.UNKNOWN}}e.sourceToProto=o;function s(e){switch(e){case ua.CAMERA:return n.Camera;case ua.MICROPHONE:return n.Microphone;case ua.SCREEN_SHARE:return n.ScreenShare;case ua.SCREEN_SHARE_AUDIO:return n.ScreenShareAudio;default:return n.Unknown}}e.sourceFromProto=s;function c(e){switch(e){case lo.ACTIVE:return r.Active;case lo.PAUSED:return r.Paused;default:return r.Unknown}}e.streamStateFromProto=c})(U||={});var Xl=`|`,Zl=`https://aomediacodec.github.io/av1-rtp-spec/#dependency-descriptor-rtp-header-extension`;function Ql(e){let t=e.split(Xl);return t.length>1?[t[0],e.substr(t[0].length+1)]:[e,``]}function $l(e){return new Qc(t=>vl.setTimeout(t,e))}function eu(){return`addTransceiver`in RTCPeerConnection.prototype}function tu(){return`addTrack`in RTCPeerConnection.prototype}function nu(){if(!(`getCapabilities`in RTCRtpSender)||lu()||su())return!1;let e=RTCRtpSender.getCapabilities(`video`),t=!1;if(e){for(let n of e.codecs)if(n.mimeType.toLowerCase()===`video/av1`){t=!0;break}}return t}function ru(){if(!(`getCapabilities`in RTCRtpSender)||su())return!1;if(lu()){let e=tl();if(e?.version&&Su(e.version,`16`)<0||e?.os===`iOS`&&e?.osVersion&&Su(e.osVersion,`16`)<0)return!1}let e=RTCRtpSender.getCapabilities(`video`),t=!1;if(e){for(let n of e.codecs)if(n.mimeType.toLowerCase()===`video/vp9`){t=!0;break}}return t}function iu(e){return e===`av1`||e===`vp9`}function au(e){return!document||uu()?!1:(e||=document.createElement(`audio`),`setSinkId`in e)}function ou(){return typeof RTCPeerConnection>`u`?!1:eu()||tu()}function su(){return tl()?.name===`Firefox`}function cu(){let e=tl();return!!e&&e.name===`Chrome`&&e.os!==`iOS`}function lu(){return tl()?.name===`Safari`}function uu(){let e=tl();return e?.name===`Safari`||e?.os===`iOS`}function du(){let e=tl();return e?.name===`Safari`&&e.version.startsWith(`17.`)||e?.os===`iOS`&&!!e?.osVersion&&Su(e.osVersion,`17`)>=0}function fu(e){return e||=tl(),e?.name===`Safari`&&Su(e.version,`18.3`)>0||e?.os===`iOS`&&!!e?.osVersion&&Su(e.osVersion,`18.3`)>0}function pu(){return hu()?navigator.userAgentData?.mobile??/Tablet|iPad|Mobile|Android|BlackBerry/.test(navigator.userAgent):!1}function mu(){let e=tl(),t=`17.2`;if(e)return e.name!==`Safari`&&e.os!==`iOS`||e.os===`iOS`&&e.osVersion&&Su(e.osVersion,t)>=0?!0:e.name===`Safari`&&Su(e.version,t)>=0}function hu(){return typeof document<`u`}function gu(){return navigator.product==`ReactNative`}function _u(e){return e.hostname.endsWith(`.livekit.cloud`)||e.hostname.endsWith(`.livekit.run`)}function vu(e){return _u(e)?e.hostname.split(`.`)[0]:null}function yu(){if(global&&global.LiveKitReactNativeGlobal)return global.LiveKitReactNativeGlobal}function bu(){if(!gu())return;let e=yu();if(e)return e.platform}function xu(){if(hu())return window.devicePixelRatio;if(gu()){let e=yu();if(e)return e.devicePixelRatio}return 1}function Su(e,t){let n=e.split(`.`),r=t.split(`.`),i=Math.min(n.length,r.length);for(let e=0;e<i;++e){let t=parseInt(n[e],10),a=parseInt(r[e],10);if(t>a)return 1;if(t<a)return-1;if(e===i-1&&t===a)return 0}return e===``&&t!==``?-1:t===``?1:n.length==r.length?0:n.length<r.length?-1:1}function Cu(e){for(let t of e)t.target.handleResize(t)}function wu(e){for(let t of e)t.target.handleVisibilityChanged(t)}var Tu=null,Eu=()=>(Tu||=new ResizeObserver(Cu),Tu),Du=null,Ou=()=>(Du||=new IntersectionObserver(wu,{root:null,rootMargin:`0px`}),Du);function ku(){let e=new Ya({sdk:Xa.JS,protocol:16,version:al});return gu()&&(e.os=bu()??``),e}function Au(){let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:16,t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:16,n=arguments.length>2&&arguments[2]!==void 0?arguments[2]:!1,r=arguments.length>3&&arguments[3]!==void 0?arguments[3]:!1,i=document.createElement(`canvas`);i.width=e,i.height=t;let a=i.getContext(`2d`);a?.fillRect(0,0,i.width,i.height),r&&a&&(a.beginPath(),a.arc(e/2,t/2,50,0,Math.PI*2,!0),a.closePath(),a.fillStyle=`grey`,a.fill());let[o]=i.captureStream().getTracks();if(!o)throw Error(`Could not get empty media stream video track`);return o.enabled=n,o}var ju;function Mu(){if(!ju){let e=new AudioContext,t=e.createOscillator(),n=e.createGain();n.gain.setValueAtTime(0,0);let r=e.createMediaStreamDestination();if(t.connect(n),n.connect(r),t.start(),[ju]=r.stream.getAudioTracks(),!ju)throw Error(`Could not get empty media stream audio track`);ju.enabled=!1}return ju.clone()}var Nu=class{get isResolved(){return this._isResolved}constructor(e,t){this._isResolved=!1,this.onFinally=t,this.promise=new Promise((t,n)=>N(this,void 0,void 0,function*(){this.resolve=t,this.reject=n,e&&(yield e(t,n))})).finally(()=>{var e;this._isResolved=!0,(e=this.onFinally)==null||e.call(this)})}};function Pu(e){return xl.includes(e)}function Fu(e){if(typeof e==`string`||typeof e==`number`)return e;if(Array.isArray(e))return e[0];if(e.exact!==void 0)return Array.isArray(e.exact)?e.exact[0]:e.exact;if(e.ideal!==void 0)return Array.isArray(e.ideal)?e.ideal[0]:e.ideal;throw Error(`could not unwrap constraint`)}function Iu(e){return e.startsWith(`http`)?e.replace(/^(http)/,`ws`):e}function Lu(e){return e.startsWith(`ws`)?e.replace(/^(ws)/,`http`):e}function Ru(e,t){return e.segments.map(e=>{let{id:n,text:r,language:i,startTime:a,endTime:o,final:s}=e,c=t.get(n)??Date.now(),l=Date.now();return s?t.delete(n):t.set(n,c),{id:n,text:r,startTime:Number.parseInt(a.toString()),endTime:Number.parseInt(o.toString()),final:s,language:i,firstReceivedTime:c,lastReceivedTime:l}})}function zu(e){let{id:t,timestamp:n,message:r,editTimestamp:i}=e;return{id:t,timestamp:Number.parseInt(n.toString()),editTimestamp:i?Number.parseInt(i.toString()):void 0,message:r}}function Bu(e){switch(e.reason){case P.LeaveRequest:return e.context;case P.Cancelled:return ma.CLIENT_INITIATED;case P.NotAllowed:return ma.USER_REJECTED;case P.ServerUnreachable:return ma.JOIN_FAILURE;default:return ma.UNKNOWN_REASON}}function Vu(e){return e===void 0?void 0:Number(e)}function Hu(e){return e===void 0?void 0:BigInt(e)}function Uu(e){return!!e&&!(e instanceof MediaStreamTrack)&&e.isLocal}function Wu(e){return!!e&&e.kind==U.Kind.Audio}function Gu(e){return!!e&&e.kind==U.Kind.Video}function Ku(e){return Uu(e)&&Gu(e)}function qu(e){return Uu(e)&&Wu(e)}function Ju(e){return!!e&&!e.isLocal}function Yu(e){return!!e&&!e.isLocal}function Xu(e){return Ju(e)&&Gu(e)}function Zu(e){return e.isLocal}function Qu(e,t){let n=[],r=new TextEncoder().encode(e);for(;r.length>t;){let e=t;for(;e>0;){let t=r[e];if(t!==void 0&&(t&192)!=128)break;e--}n.push(r.slice(0,e)),r=r.slice(e)}return r.length>0&&n.push(r),n}function $u(e){let t=e.get(`Cache-Control`);if(t){let e=t.match(/(?:^|[,\s])max-age=(\d+)/)?.[1];if(e)return parseInt(e,10)}}function ed(){return typeof CompressionStream<`u`}function td(e,t){let n=arguments.length>2&&arguments[2]!==void 0?arguments[2]:!1,r=nd(e,t);return n?r:ad(r,`v1`)}function nd(e,t){let n=new URL(Iu(e));return t.forEach((e,t)=>{n.searchParams.set(t,e)}),ad(n,`rtc`)}function rd(e){return ad(new URL(Lu(e)),`validate`)}function id(e){return e.endsWith(`/`)?e:`${e}/`}function ad(e,t){return e.pathname=`${id(e.pathname)}${t}`,e}function od(e){if(typeof e==`string`)return po.fromJson(JSON.parse(e),{ignoreUnknownFields:!0});if(e instanceof ArrayBuffer)return po.fromBinary(new Uint8Array(e));throw Error(`could not decode websocket message: ${typeof e}`)}function sd(e){let t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:`Unknown reason`;if(!(e instanceof AbortSignal))return t;let n=e.reason;switch(typeof n){case`string`:return n;case`object`:return n instanceof Error?n.message:t;default:return`toString`in n?n.toString():t}}var cd=`lk_e2ee`,ld;(function(e){e.SetKey=`setKey`,e.RatchetRequest=`ratchetRequest`,e.KeyRatcheted=`keyRatcheted`})(ld||={});var ud;(function(e){e.KeyRatcheted=`keyRatcheted`})(ud||={});var dd;(function(e){e.ParticipantEncryptionStatusChanged=`participantEncryptionStatusChanged`,e.EncryptionError=`encryptionError`})(dd||={});var fd;(function(e){e.Error=`cryptorError`})(fd||={});function pd(){return hd()||md()}function md(){return window.RTCRtpScriptTransform!==void 0}function hd(){return window.RTCRtpSender!==void 0&&window.RTCRtpSender.prototype.createEncodedStreams!==void 0}function gd(e){if(e.value?.case!==`sipDtmf`&&e.value?.case!==`metrics`&&e.value?.case!==`speaker`&&e.value?.case!==`transcription`&&e.value?.case!==`encryptedPacket`)return new Pa({value:e.value})}Bs.EventEmitter;var _d;(function(e){e[e.InvalidKey=0]=`InvalidKey`,e[e.MissingKey=1]=`MissingKey`,e[e.InternalError=2]=`InternalError`})(_d||={});var vd=class extends Bs.EventEmitter{constructor(e,t){super(),this.decryptDataRequests=new Map,this.encryptDataRequests=new Map,this.onWorkerMessage=e=>{let{kind:t,data:n}=e.data;switch(t){case`error`:if(M.error(n.error.message),n.uuid){let e=this.decryptDataRequests.get(n.uuid);if(e?.reject){e.reject(n.error);break}let t=this.encryptDataRequests.get(n.uuid);if(t?.reject){t.reject(n.error);break}}this.emit(dd.EncryptionError,n.error,n.participantIdentity);break;case`initAck`:n.enabled&&this.keyProvider.getKeys().forEach(e=>{this.postKey(e,!1)});break;case`enable`:if(n.enabled&&this.keyProvider.getKeys().forEach(e=>{this.postKey(e,!1)}),this.encryptionEnabled!==n.enabled&&n.participantIdentity===this.room?.localParticipant.identity)this.emit(dd.ParticipantEncryptionStatusChanged,n.enabled,this.room.localParticipant),this.encryptionEnabled=n.enabled;else if(n.participantIdentity){let e=this.room?.getParticipantByIdentity(n.participantIdentity);if(!e)throw TypeError(`couldn't set encryption status, participant not found${n.participantIdentity}`);this.emit(dd.ParticipantEncryptionStatusChanged,n.enabled,e)}break;case`ratchetKey`:this.keyProvider.emit(ld.KeyRatcheted,n.ratchetResult,n.participantIdentity,n.keyIndex);break;case`decryptDataResponse`:let e=this.decryptDataRequests.get(n.uuid);e?.resolve&&e.resolve(n);break;case`encryptDataResponse`:let t=this.encryptDataRequests.get(n.uuid);t?.resolve&&t.resolve(n);break}},this.onWorkerError=e=>{M.error(`e2ee worker encountered an error:`,{error:e.error}),this.emit(dd.EncryptionError,e.error,void 0)},this.keyProvider=e.keyProvider,this.worker=e.worker,this.encryptionEnabled=!1,this.dataChannelEncryptionEnabled=t}get isEnabled(){return this.encryptionEnabled}get isDataChannelEncryptionEnabled(){return this.isEnabled&&this.dataChannelEncryptionEnabled}setup(e){if(!pd())throw new cl(`tried to setup end-to-end encryption on an unsupported browser`);if(M.info(`setting up e2ee`),e!==this.room){this.room=e,this.setupEventListeners(e,this.keyProvider);let t={kind:`init`,data:{keyProviderOptions:this.keyProvider.getOptions(),loglevel:Ds.getLevel()}};this.worker&&(M.info(`initializing worker`,{worker:this.worker}),this.worker.onmessage=this.onWorkerMessage,this.worker.onerror=this.onWorkerError,this.worker.postMessage(t))}}setParticipantCryptorEnabled(e,t){M.debug(`set e2ee to ${e} for participant ${t}`),this.postEnable(e,t)}setSifTrailer(e){!e||e.length===0?M.warn(`ignoring server sent trailer as it's empty`):this.postSifTrailer(e)}setupEngine(e){e.on(z.RTPVideoMapUpdate,e=>{this.postRTPMap(e)})}setupEventListeners(e,t){e.on(L.TrackPublished,(e,t)=>this.setParticipantCryptorEnabled(e.trackInfo.encryption!==j.NONE,t.identity)),e.on(L.ConnectionStateChanged,t=>{t===Y.Connected&&e.remoteParticipants.forEach(e=>{e.trackPublications.forEach(t=>{this.setParticipantCryptorEnabled(t.trackInfo.encryption!==j.NONE,e.identity)})})}).on(L.TrackUnsubscribed,(e,t,n)=>{var r;let i={kind:`removeTransform`,data:{participantIdentity:n.identity,trackId:e.mediaStreamID}};(r=this.worker)==null||r.postMessage(i)}).on(L.TrackSubscribed,(e,t,n)=>{this.setupE2EEReceiver(e,n.identity,t.trackInfo)}).on(L.SignalConnected,()=>{if(!this.room)throw TypeError(`expected room to be present on signal connect`);let e=t.getLatestManuallySetKeyIndex();t.getKeys().forEach(t=>{this.postKey(t,e===(t.keyIndex??0))}),this.setParticipantCryptorEnabled(this.room.localParticipant.isE2EEEnabled,this.room.localParticipant.identity)}),e.localParticipant.on(R.LocalSenderCreated,(e,t)=>N(this,void 0,void 0,function*(){this.setupE2EESender(t,e)})),e.localParticipant.on(R.LocalTrackPublished,e=>{if(!Gu(e.track)||!uu())return;let t={kind:`updateCodec`,data:{trackId:e.track.mediaStreamID,codec:Ll(e.trackInfo.codecs[0].mimeType),participantIdentity:this.room.localParticipant.identity}};this.worker.postMessage(t)}),t.on(ld.SetKey,(e,t)=>this.postKey(e,t??!0)).on(ld.RatchetRequest,(e,t)=>this.postRatchetRequest(e,t))}encryptData(e){return N(this,void 0,void 0,function*(){if(!this.worker)throw Error(`could not encrypt data, worker is missing`);let t=crypto.randomUUID(),n={kind:`encryptDataRequest`,data:{uuid:t,payload:e,participantIdentity:this.room.localParticipant.identity}},r=new Nu;return r.onFinally=()=>{this.encryptDataRequests.delete(t)},this.encryptDataRequests.set(t,r),this.worker.postMessage(n),r.promise})}handleEncryptedData(e,t,n,r){if(!this.worker)throw Error(`could not handle encrypted data, worker is missing`);let i=crypto.randomUUID(),a={kind:`decryptDataRequest`,data:{uuid:i,payload:e,iv:t,participantIdentity:n,keyIndex:r}},o=new Nu;return o.onFinally=()=>{this.decryptDataRequests.delete(i)},this.decryptDataRequests.set(i,o),this.worker.postMessage(a),o.promise}postRatchetRequest(e,t){if(!this.worker)throw Error(`could not ratchet key, worker is missing`);let n={kind:`ratchetRequest`,data:{participantIdentity:e,keyIndex:t}};this.worker.postMessage(n)}postKey(e,t){let{key:n,participantIdentity:r,keyIndex:i}=e;if(!this.worker)throw Error(`could not set key, worker is missing`);let a={kind:`setKey`,data:{participantIdentity:r,isPublisher:r===this.room?.localParticipant.identity,key:n,keyIndex:i,updateCurrentKeyIndex:t}};this.worker.postMessage(a)}postEnable(e,t){if(this.worker){let n={kind:`enable`,data:{enabled:e,participantIdentity:t}};this.worker.postMessage(n)}else throw ReferenceError(`failed to enable e2ee, worker is not ready`)}postRTPMap(e){if(!this.worker)throw TypeError(`could not post rtp map, worker is missing`);if(!this.room?.localParticipant.identity)throw TypeError(`could not post rtp map, local participant identity is missing`);let t={kind:`setRTPMap`,data:{map:e,participantIdentity:this.room.localParticipant.identity}};this.worker.postMessage(t)}postSifTrailer(e){if(!this.worker)throw Error(`could not post SIF trailer, worker is missing`);let t={kind:`setSifTrailer`,data:{trailer:e}};this.worker.postMessage(t)}setupE2EEReceiver(e,t,n){if(e.receiver){if(!n?.mimeType||n.mimeType===``)throw TypeError(`MimeType missing from trackInfo, cannot set up E2EE cryptor`);this.handleReceiver(e.receiver,e.mediaStreamID,t,e.kind===`video`?Ll(n.mimeType):void 0)}}setupE2EESender(e,t){if(!Uu(e)||!t){t||M.warn(`early return because sender is not ready`);return}this.handleSender(t,e.mediaStreamID,void 0)}handleReceiver(e,t,n,r){return N(this,void 0,void 0,function*(){if(this.worker){if(md()&&!cu()){let i={kind:`decode`,participantIdentity:n,trackId:t,codec:r};e.transform=new RTCRtpScriptTransform(this.worker,i)}else{if(cd in e&&r){let e={kind:`updateCodec`,data:{trackId:t,codec:r,participantIdentity:n}};this.worker.postMessage(e);return}let i=e.writableStream,a=e.readableStream;if(!i||!a){let t=e.createEncodedStreams();e.writableStream=t.writable,i=t.writable,e.readableStream=t.readable,a=t.readable}let o={kind:`decode`,data:{readableStream:a,writableStream:i,trackId:t,codec:r,participantIdentity:n,isReuse:cd in e}};this.worker.postMessage(o,[a,i])}e[cd]=!0}})}handleSender(e,t,n){if(!(cd in e||!this.worker)){if(!this.room?.localParticipant.identity||this.room.localParticipant.identity===``)throw TypeError(`local identity needs to be known in order to set up encrypted sender`);if(md()&&!cu()){M.info(`initialize script transform`);let r={kind:`encode`,participantIdentity:this.room.localParticipant.identity,trackId:t,codec:n};e.transform=new RTCRtpScriptTransform(this.worker,r)}else{M.info(`initialize encoded streams`);let r=e.createEncodedStreams(),i={kind:`encode`,data:{readableStream:r.readable,writableStream:r.writable,codec:n,trackId:t,participantIdentity:this.room.localParticipant.identity,isReuse:!1}};this.worker.postMessage(i,[r.readable,r.writable])}e[cd]=!0}}},yd=500,bd=15e3,xd=class e{constructor(){this.failedConnectionAttempts=new Map,this.backOffPromises=new Map}static getInstance(){return this._instance||=new e,this._instance}addFailedConnectionAttempt(e){let t=vu(new URL(e));if(!t)return;let n=this.failedConnectionAttempts.get(t)??0;this.failedConnectionAttempts.set(t,n+1),this.backOffPromises.set(t,$l(Math.min(yd*2**n,bd)))}getBackOffPromise(e){let t=new URL(e),n=t&&vu(t);return n&&this.backOffPromises.get(n)||Promise.resolve()}resetFailedConnectionAttempts(e){let t=new URL(e),n=t&&vu(t);n&&(this.failedConnectionAttempts.set(n,0),this.backOffPromises.set(n,Promise.resolve()))}resetAll(){this.backOffPromises.clear(),this.failedConnectionAttempts.clear()}};xd._instance=null;var Sd=`default`,Cd=class e{constructor(){this._previousDevices=[]}static getInstance(){return this.instance===void 0&&(this.instance=new e),this.instance}get previousDevices(){return this._previousDevices}getDevices(t){return N(this,arguments,void 0,function(t){var n=this;let r=arguments.length>1&&arguments[1]!==void 0?arguments[1]:!0;return function*(){if(e.userMediaPromiseMap?.size>0){M.debug(`awaiting getUserMedia promise`);try{t?yield e.userMediaPromiseMap.get(t):yield Promise.all(e.userMediaPromiseMap.values())}catch{M.warn(`error waiting for media permissons`)}}let i=yield navigator.mediaDevices.enumerateDevices();if(r&&!(lu()&&n.hasDeviceInUse(t))&&(i.filter(e=>e.kind===t).length===0||i.some(e=>{let n=e.label===``,r=t?e.kind===t:!0;return n&&r}))){let e={video:t!==`audioinput`&&t!==`audiooutput`,audio:t!==`videoinput`&&{deviceId:{ideal:`default`}}},n=yield navigator.mediaDevices.getUserMedia(e);i=yield navigator.mediaDevices.enumerateDevices(),n.getTracks().forEach(e=>{e.stop()})}return n._previousDevices=i,t&&(i=i.filter(e=>e.kind===t)),i}()})}normalizeDeviceId(e,t,n){return N(this,void 0,void 0,function*(){if(t!==Sd)return t;let r=yield this.getDevices(e),i=r.find(e=>e.deviceId===Sd);if(!i){M.warn(`could not reliably determine default device`);return}let a=r.find(e=>e.deviceId!==Sd&&e.groupId===(n??i.groupId));if(!a){M.warn(`could not reliably determine default device`);return}return a?.deviceId})}hasDeviceInUse(t){return t?e.userMediaPromiseMap.has(t):e.userMediaPromiseMap.size>0}};Cd.mediaDeviceKinds=[`audioinput`,`audiooutput`,`videoinput`],Cd.userMediaPromiseMap=new Map;var wd=65535,Td=4294967295,Ed=class e{static u16(t){return new e(t,wd)}static u32(t){return new e(t,Td)}constructor(e,t){if(this.value=e,e<0)throw Error(`WrapAroundUnsignedInt: cannot faithfully represent an integer smaller than 0`);if(t>2**53-1)throw Error(`WrapAroundUnsignedInt: cannot faithfully represent an integer bigger than MAX_SAFE_INTEGER.`);this.maxSize=t,this.clamp()}clamp(){for(;this.value>this.maxSize;)this.value-=this.maxSize+1;for(;this.value<0;)this.value+=this.maxSize+1}clone(){return new e(this.value,this.maxSize)}update(e){this.value=e(this.value),this.clamp()}increment(){let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:1;this.update(t=>t+e)}decrement(){let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:1;this.update(t=>t-e)}getThenIncrement(){let t=this.value;return this.increment(),new e(t,this.maxSize)}isBefore(e){let t=this.value>>>0,n=(e.value>>>0)-t>>>0;return n!==0&&n<this.maxSize+1}},Dd=class e{static fromRtpTicks(t){return new e(t,9e4)}static rtpRandom(){let t=Math.round(Math.random()*Td);return e.fromRtpTicks(t)}constructor(e,t){this.timestamp=Ed.u32(e),this.rateInHz=t}asTicks(){return this.timestamp.value}clone(){return new e(this.timestamp.value,this.rateInHz)}wrappingAdd(e){this.timestamp.increment(e)}isBefore(e){return this.timestamp.isBefore(e.timestamp)}},Od=class e{constructor(e,t,n){this.epoch=t,this.base=n,this.previous=n.clone(),this.rateInHz=e}static startingNow(t,n){return new e(n,new Date,t)}static startingAtTime(t,n,r){return new e(r,t,n)}static rtpStartingNow(t){return e.startingNow(t,9e4)}static rtpStartingAtTime(t,n){return e.startingAtTime(t,n,9e4)}now(){return this.at(new Date)}at(t){let n=t.getTime()-this.epoch.getTime(),r=e.durationInMsToTicks(n,this.rateInHz),i=this.base.clone();return i.wrappingAdd(r),i.isBefore(this.previous)&&(i=this.previous),this.previous=i.clone(),i.clone()}static durationInMsToTicks(e,t){let n=(e*1e6*t+5e8)/1e9;return Math.round(n)}};function kd(e){if(e instanceof DataView)return e;if(e instanceof ArrayBuffer)return new DataView(e);if(e instanceof Uint8Array)return new DataView(e.buffer,e.byteOffset,e.byteLength);throw Error(`Error coercing ${e} to DataView - input was not DataView, ArrayBuffer, or Uint8Array.`)}var Ad;(function(e){e[e.Reserved=0]=`Reserved`,e[e.TooLarge=1]=`TooLarge`})(Ad||={});var jd=class e extends sl{constructor(e,t){super(19,e),this.name=`DataTrackHandleError`,this.reason=t,this.reasonName=Ad[t]}isReason(e){return this.reason===e}static tooLarge(){return new e(`Value too large to be a valid track handle`,Ad.TooLarge)}static reserved(t){return new e(`0x${t.toString(16)} is a reserved value.`,Ad.Reserved)}},Md={fromNumber(e){if(e===0)throw jd.reserved(e);if(e>wd)throw jd.tooLarge();return e}},Nd=class{constructor(){this.value=0}get(){return this.value+=1,this.value>wd?null:this.value}},Pd={from(e){return{sid:e.sid,pubHandle:e.pubHandle,name:e.name,usesE2ee:e.encryption!==j.NONE}},toProtobuf(e){return new Da({sid:e.sid,pubHandle:e.pubHandle,name:e.name,encryption:e.usesE2ee?j.GCM:j.NONE})}},Fd;(function(e){e[e.WAITING=0]=`WAITING`,e[e.RUNNING=1]=`RUNNING`,e[e.COMPLETED=2]=`COMPLETED`})(Fd||={});var Id=class{constructor(){this.pendingTasks=new Map,this.taskMutex=new ur,this.nextTaskIndex=0}run(e){return N(this,void 0,void 0,function*(){let t={id:this.nextTaskIndex++,enqueuedAt:Date.now(),status:Fd.WAITING};this.pendingTasks.set(t.id,t);let n=yield this.taskMutex.lock();try{return t.executedAt=Date.now(),t.status=Fd.RUNNING,yield e()}finally{t.status=Fd.COMPLETED,this.pendingTasks.delete(t.id),n()}})}flush(){return N(this,void 0,void 0,function*(){return this.run(()=>N(this,void 0,void 0,function*(){}))})}snapshot(){return Array.from(this.pendingTasks.values())}},Ld=class{get readyState(){return this.ws.readyState}constructor(e){let t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{};if(t.signal?.aborted)throw new DOMException(`This operation was aborted`,`AbortError`);this.url=e;let n=new WebSocket(e,t.protocols??[]);n.binaryType=`arraybuffer`,this.ws=n;let r=function(){let{closeCode:e,reason:t}=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};return n.close(e,t)};this.opened=new Qc((e,t)=>{let i=()=>{t(F.websocket(`Encountered websocket error during connection establishment`))};n.onopen=()=>{e({readable:new ReadableStream({start(e){n.onmessage=t=>{let{data:n}=t;return e.enqueue(n)},n.onerror=t=>e.error(t)},cancel:r}),writable:new WritableStream({write(e){n.send(e)},abort(){n.close()},close:r}),protocol:n.protocol,extensions:n.extensions}),n.removeEventListener(`error`,i)},n.addEventListener(`error`,i)}),this.closed=new Qc((e,t)=>{let r=()=>N(this,void 0,void 0,function*(){let r=new Qc(e=>{n.readyState!==WebSocket.CLOSED&&n.addEventListener(`close`,t=>{e(t)},{once:!0})}),i=yield Qc.race([$l(250),r]);i?e(i):t(F.websocket(`Encountered unspecified websocket error without a timely close event`))});n.onclose=t=>{let{code:i,reason:a}=t;e({closeCode:i,reason:a}),n.removeEventListener(`error`,r)},n.addEventListener(`error`,r)}),t.signal&&(t.signal.onabort=()=>n.close()),this.close=r}},Rd=[`syncState`,`trickle`,`offer`,`answer`,`simulate`,`leave`];function zd(e){let t=Rd.indexOf(e.case)>=0;return M.trace(`request allowed to bypass queue:`,{canPass:t,req:e}),t}var W;(function(e){e[e.CONNECTING=0]=`CONNECTING`,e[e.CONNECTED=1]=`CONNECTED`,e[e.RECONNECTING=2]=`RECONNECTING`,e[e.DISCONNECTING=3]=`DISCONNECTING`,e[e.DISCONNECTED=4]=`DISCONNECTED`})(W||={});var Bd=250,Vd=class{get currentState(){return this.state}get isDisconnected(){return this.state===W.DISCONNECTING||this.state===W.DISCONNECTED}get isEstablishingConnection(){return this.state===W.CONNECTING||this.state===W.RECONNECTING}getNextRequestId(){return this._requestId+=1,this._requestId}constructor(){let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:!1,t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{};this.rtt=0,this.state=W.DISCONNECTED,this.log=M,this._requestId=0,this.useV0SignalPath=!1,this.resetCallbacks=()=>{this.onAnswer=void 0,this.onLeave=void 0,this.onLocalTrackPublished=void 0,this.onLocalTrackUnpublished=void 0,this.onNegotiateRequested=void 0,this.onOffer=void 0,this.onRemoteMuteChanged=void 0,this.onSubscribedQualityUpdate=void 0,this.onTokenRefresh=void 0,this.onTrickle=void 0,this.onClose=void 0,this.onMediaSectionsRequirement=void 0},this.log=Es(t.loggerName??Ts.Signal),this.loggerContextCb=t.loggerContextCb,this.useJSON=e,this.requestQueue=new Id,this.queuedRequests=[],this.closingLock=new ur,this.connectionLock=new ur,this.state=W.DISCONNECTED}get logContext(){return this.loggerContextCb?.call(this)??{}}join(e,t,n,r){return N(this,arguments,void 0,function(e,t,n,r){var i=this;let a=arguments.length>4&&arguments[4]!==void 0?arguments[4]:!1,o=arguments.length>5?arguments[5]:void 0;return function*(){return i.state=W.CONNECTING,i.options=n,yield i.connect(e,t,n,r,a,o)}()})}reconnect(e,t,n,r){return N(this,void 0,void 0,function*(){if(!this.options){this.log.warn(`attempted to reconnect without signal options being set, ignoring`,this.logContext);return}return this.state=W.RECONNECTING,this.clearPingInterval(),yield this.connect(e,t,Object.assign(Object.assign({},this.options),{reconnect:!0,sid:n,reconnectReason:r}),void 0,this.useV0SignalPath)})}connect(e,t,n,r){return N(this,arguments,void 0,function(e,t,n,r){var i=this;let a=arguments.length>4&&arguments[4]!==void 0?arguments[4]:!1,o=arguments.length>5?arguments[5]:void 0;return function*(){let s=yield i.connectionLock.lock();i.connectOptions=n,i.useV0SignalPath=a;let c=ku(),l=td(e,a?Wd(t,c,n):yield Gd(t,c,n,o),a).toString(),u=rd(l).toString();return new Promise((e,t)=>N(i,void 0,void 0,function*(){try{let i=!1,a=e=>N(this,void 0,void 0,function*(){if(i)return;i=!0;let n=sd(e instanceof Event?e.currentTarget:e,`Abort handler called`);this.streamWriter&&!this.isDisconnected?this.sendLeave().then(()=>this.close(n)).catch(e=>{this.log.error(e),this.close()}):this.close(),o(),t(F.cancelled(n))});r?.addEventListener(`abort`,a);let o=()=>{clearTimeout(s),r?.removeEventListener(`abort`,a)},s=setTimeout(()=>{a(F.timeout(`room connection has timed out (signal)`))},n.websocketTimeout),c=(e,t)=>{this.handleSignalConnected(e,s,t)},d=new URL(l);d.searchParams.has(`access_token`)&&d.searchParams.set(`access_token`,`<redacted>`),this.log.debug(`connecting to ${d}`,Object.assign({reconnect:n.reconnect,reconnectReason:n.reconnectReason},this.logContext)),this.ws&&(yield this.close(!1)),this.ws=new Ld(l);try{this.ws.closed.then(e=>{this.isEstablishingConnection&&t(F.internal(`Websocket got closed during a (re)connection attempt: ${e.reason}`)),e.closeCode!==1e3&&(this.log.warn(`websocket closed`,Object.assign(Object.assign({},this.logContext),{reason:e.reason,code:e.closeCode,wasClean:e.closeCode===1e3,state:this.state})),this.state===W.CONNECTED&&this.handleOnClose(e.reason??`Unexpected WS error`))}).catch(e=>{this.isEstablishingConnection&&t(F.internal(`Websocket error during a (re)connection attempt: ${e}`))});let r=yield this.ws.opened.catch(e=>N(this,void 0,void 0,function*(){if(this.state!==W.CONNECTED){this.state=W.DISCONNECTED,clearTimeout(s),t(yield this.handleConnectionError(e,u));return}this.handleWSError(e),t(e)}));if(clearTimeout(s),!r)return;let i=r.readable.getReader();this.streamWriter=r.writable.getWriter();let a=yield i.read();if(i.releaseLock(),!a.value)throw F.internal(`no message received as first message`);let o=od(a.value),l=this.validateFirstMessage(o,n.reconnect??!1);if(!l.isValid){t(l.error);return}o.message?.case===`join`&&(this.pingTimeoutDuration=o.message.value.pingTimeout,this.pingIntervalDuration=o.message.value.pingInterval,this.pingTimeoutDuration&&this.pingTimeoutDuration>0&&this.log.debug(`ping config`,Object.assign(Object.assign({},this.logContext),{timeout:this.pingTimeoutDuration,interval:this.pingIntervalDuration})),this.onJoined&&this.onJoined(o.message.value)),c(r,l.shouldProcessFirstMessage?o:void 0),e(l.response)}catch(e){t(e)}finally{o()}}finally{s()}}))}()})}startReadingLoop(e,t){return N(this,void 0,void 0,function*(){for(t&&this.handleSignalResponse(t);;){this.signalLatency&&(yield $l(this.signalLatency));let{done:t,value:n}=yield e.read();if(t)break;let r=od(n);this.handleSignalResponse(r)}})}close(){return N(this,arguments,void 0,function(){var e=this;let t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:!0,n=arguments.length>1&&arguments[1]!==void 0?arguments[1]:`Close method called on signal client`;return function*(){if([W.DISCONNECTING||W.DISCONNECTED].includes(e.state)){e.log.debug(`ignoring signal close as it's already in disconnecting state`);return}let r=yield e.closingLock.lock();try{if(e.clearPingInterval(),t&&(e.state=W.DISCONNECTING),e.ws){e.ws.close({closeCode:1e3,reason:n});let t=e.ws.closed;e.ws=void 0,e.streamWriter=void 0,yield Promise.race([t,$l(Bd)])}}catch(t){e.log.debug(`websocket error while closing`,Object.assign(Object.assign({},e.logContext),{error:t}))}finally{t&&(e.state=W.DISCONNECTED),r()}}()})}sendOffer(e,t){this.log.debug(`sending offer`,Object.assign(Object.assign({},this.logContext),{offerSdp:e.sdp})),this.sendRequest({case:`offer`,value:Ud(e,t)})}sendAnswer(e,t){return this.log.debug(`sending answer`,Object.assign(Object.assign({},this.logContext),{answerSdp:e.sdp})),this.sendRequest({case:`answer`,value:Ud(e,t)})}sendIceCandidate(e,t){return this.log.debug(`sending ice candidate`,Object.assign(Object.assign({},this.logContext),{candidate:e})),this.sendRequest({case:`trickle`,value:new So({candidateInit:JSON.stringify(e),target:t})})}sendMuteTrack(e,t){return this.sendRequest({case:`mute`,value:new Co({sid:e,muted:t})})}sendAddTrack(e){return this.sendRequest({case:`addTrack`,value:e})}sendUpdateLocalMetadata(e,t){return N(this,arguments,void 0,function(e,t){var n=this;let r=arguments.length>2&&arguments[2]!==void 0?arguments[2]:{};return function*(){let i=n.getNextRequestId();return yield n.sendRequest({case:`updateMetadata`,value:new zo({requestId:i,metadata:e,name:t,attributes:r})}),i}()})}sendUpdateTrackSettings(e){this.sendRequest({case:`trackSetting`,value:e})}sendUpdateSubscription(e){return this.sendRequest({case:`subscription`,value:e})}sendSyncState(e){return this.sendRequest({case:`syncState`,value:e})}sendUpdateVideoLayers(e,t){return this.sendRequest({case:`updateLayers`,value:new Ro({trackSid:e,layers:t})})}sendUpdateSubscriptionPermissions(e,t){return this.sendRequest({case:`subscriptionPermission`,value:new Qo({allParticipants:e,trackPermissions:t})})}sendSimulateScenario(e){return this.sendRequest({case:`simulate`,value:e})}sendPing(){return Promise.all([this.sendRequest({case:`ping`,value:O.parse(Date.now())}),this.sendRequest({case:`pingReq`,value:new as({timestamp:O.parse(Date.now()),rtt:O.parse(this.rtt)})})])}sendUpdateLocalAudioTrack(e,t){return this.sendRequest({case:`updateAudioTrack`,value:new Po({trackSid:e,features:t})})}sendLeave(){return this.sendRequest({case:`leave`,value:new Io({reason:ma.CLIENT_INITIATED,action:Lo.DISCONNECT})})}sendPublishDataTrackRequest(e,t,n){return this.sendRequest({case:`publishDataTrackRequest`,value:new go({pubHandle:e,name:t,encryption:n?j.GCM:j.NONE})})}sendUnPublishDataTrackRequest(e){return this.sendRequest({case:`unpublishDataTrackRequest`,value:new vo({pubHandle:e})})}sendUpdateDataSubscription(e,t){return this.sendRequest({case:`updateDataSubscription`,value:new jo({updates:[new Mo({trackSid:e,subscribe:t})]})})}sendRequest(e){return N(this,arguments,void 0,function(e){var t=this;let n=arguments.length>1&&arguments[1]!==void 0?arguments[1]:!1;return function*(){if(!n&&!zd(e)&&t.state===W.RECONNECTING){t.queuedRequests.push(()=>N(t,void 0,void 0,function*(){yield this.sendRequest(e,!0)}));return}if(n||(yield t.requestQueue.flush()),t.signalLatency&&(yield $l(t.signalLatency)),t.isDisconnected){t.log.debug(`skipping signal request (type: ${e.case}) - SignalClient disconnected`);return}if(!t.streamWriter){t.log.error(`cannot send signal request before connected, type: ${e?.case}`,t.logContext);return}let r=new fo({message:e});try{t.useJSON?yield t.streamWriter.write(r.toJsonString()):yield t.streamWriter.write(r.toBinary())}catch(e){t.log.error(`error sending signal message`,Object.assign(Object.assign({},t.logContext),{error:e}))}}()})}handleSignalResponse(e){let t=e.message;if(t==null){this.log.debug(`received unsupported message`,this.logContext);return}let n=!1;if(t.case===`answer`){let e=Hd(t.value);this.onAnswer&&this.onAnswer(e,t.value.id,t.value.midToTrackId)}else if(t.case===`offer`){let e=Hd(t.value);this.onOffer&&this.onOffer(e,t.value.id,t.value.midToTrackId)}else if(t.case===`trickle`){let e=JSON.parse(t.value.candidateInit);this.onTrickle&&this.onTrickle(e,t.value.target)}else t.case===`update`?this.onParticipantUpdate&&this.onParticipantUpdate(t.value.participants??[]):t.case===`trackPublished`?this.onLocalTrackPublished&&this.onLocalTrackPublished(t.value):t.case===`speakersChanged`?this.onSpeakersChanged&&this.onSpeakersChanged(t.value.speakers??[]):t.case===`leave`?this.onLeave&&this.onLeave(t.value):t.case===`mute`?this.onRemoteMuteChanged&&this.onRemoteMuteChanged(t.value.sid,t.value.muted):t.case===`roomUpdate`?this.onRoomUpdate&&t.value.room&&this.onRoomUpdate(t.value.room):t.case===`connectionQuality`?this.onConnectionQuality&&this.onConnectionQuality(t.value):t.case===`streamStateUpdate`?this.onStreamStateUpdate&&this.onStreamStateUpdate(t.value):t.case===`subscribedQualityUpdate`?this.onSubscribedQualityUpdate&&this.onSubscribedQualityUpdate(t.value):t.case===`subscriptionPermissionUpdate`?this.onSubscriptionPermissionUpdate&&this.onSubscriptionPermissionUpdate(t.value):t.case===`refreshToken`?this.onTokenRefresh&&this.onTokenRefresh(t.value):t.case===`trackUnpublished`?this.onLocalTrackUnpublished&&this.onLocalTrackUnpublished(t.value):t.case===`subscriptionResponse`?this.onSubscriptionError&&this.onSubscriptionError(t.value):t.case===`pong`||(t.case===`pongResp`?(this.rtt=Date.now()-Number.parseInt(t.value.lastPingTimestamp.toString()),this.resetPingTimeout(),n=!0):t.case===`requestResponse`?this.onRequestResponse&&this.onRequestResponse(t.value):t.case===`trackSubscribed`?this.onLocalTrackSubscribed&&this.onLocalTrackSubscribed(t.value.trackSid):t.case===`roomMoved`?(this.onTokenRefresh&&this.onTokenRefresh(t.value.token),this.onRoomMoved&&this.onRoomMoved(t.value)):t.case===`mediaSectionsRequirement`?this.onMediaSectionsRequirement&&this.onMediaSectionsRequirement(t.value):t.case===`publishDataTrackResponse`?this.onPublishDataTrackResponse&&this.onPublishDataTrackResponse(t.value):t.case===`unpublishDataTrackResponse`?this.onUnPublishDataTrackResponse&&this.onUnPublishDataTrackResponse(t.value):t.case===`dataTrackSubscriberHandles`?this.onDataTrackSubscriberHandles&&this.onDataTrackSubscriberHandles(t.value):this.log.debug(`unsupported message`,Object.assign(Object.assign({},this.logContext),{msgCase:t.case})));n||this.resetPingTimeout()}setReconnected(){for(;this.queuedRequests.length>0;){let e=this.queuedRequests.shift();e&&this.requestQueue.run(e)}}handleOnClose(e){return N(this,void 0,void 0,function*(){if(this.state===W.DISCONNECTED)return;let t=this.onClose;yield this.close(void 0,e),this.log.debug(`websocket connection closed: ${e}`,Object.assign(Object.assign({},this.logContext),{reason:e})),t&&t(e)})}handleWSError(e){this.log.error(`websocket error`,Object.assign(Object.assign({},this.logContext),{error:e}))}resetPingTimeout(){if(this.clearPingTimeout(),!this.pingTimeoutDuration){this.log.warn(`ping timeout duration not set`,this.logContext);return}this.pingTimeout=vl.setTimeout(()=>{this.log.warn(`ping timeout triggered. last pong received at: ${new Date(Date.now()-this.pingTimeoutDuration*1e3).toUTCString()}`,this.logContext),this.handleOnClose(`ping timeout`)},this.pingTimeoutDuration*1e3)}clearPingTimeout(){this.pingTimeout&&vl.clearTimeout(this.pingTimeout)}startPingInterval(){if(this.clearPingInterval(),this.resetPingTimeout(),!this.pingIntervalDuration){this.log.warn(`ping interval duration not set`,this.logContext);return}this.log.debug(`start ping interval`,this.logContext),this.pingInterval=vl.setInterval(()=>{this.sendPing()},this.pingIntervalDuration*1e3)}clearPingInterval(){this.log.debug(`clearing ping interval`,this.logContext),this.clearPingTimeout(),this.pingInterval&&vl.clearInterval(this.pingInterval)}handleSignalConnected(e,t,n){this.state=W.CONNECTED,clearTimeout(t),this.startPingInterval(),this.startReadingLoop(e.readable.getReader(),n)}validateFirstMessage(e,t){return e.message?.case===`join`?{isValid:!0,response:e.message.value}:this.state===W.RECONNECTING&&e.message?.case!==`leave`?e.message?.case===`reconnect`?{isValid:!0,response:e.message.value}:(this.log.debug(`declaring signal reconnected without reconnect response received`,this.logContext),{isValid:!0,response:void 0,shouldProcessFirstMessage:!0}):this.isEstablishingConnection&&e.message?.case===`leave`?{isValid:!1,error:F.leaveRequest(`Received leave request while trying to (re)connect`,e.message.value.reason)}:t?{isValid:!1,error:F.internal(`Unexpected first message`)}:{isValid:!1,error:F.internal(`did not receive join response, got ${e.message?.case} instead`)}}handleConnectionError(e,t){return N(this,void 0,void 0,function*(){try{let n=yield fetch(t);switch(n.status){case 404:return F.serviceNotFound(`v1 RTC path not found. Consider upgrading your LiveKit server version`,`v0-rtc`);case 401:case 403:let e=yield n.text();return F.notAllowed(e,n.status);default:break}return e instanceof F?e:F.internal(`Encountered unknown websocket error during connection: ${e}`,{status:n.status,statusText:n.statusText})}catch(e){return e instanceof F?e:F.serverUnreachable(e instanceof Error?e.message:`server was not reachable`)}})}};function Hd(e){let t={type:`offer`,sdp:e.sdp};switch(e.type){case`answer`:case`offer`:case`pranswer`:case`rollback`:t.type=e.type;break}return t}function Ud(e,t){return new Oo({sdp:e.sdp,type:e.type,id:t})}function Wd(e,t,n){let r=new URLSearchParams;return r.set(`access_token`,e),n.reconnect&&(r.set(`reconnect`,`1`),n.sid&&r.set(`sid`,n.sid)),r.set(`auto_subscribe`,n.autoSubscribe?`1`:`0`),r.set(`sdk`,gu()?`reactnative`:`js`),r.set(`version`,t.version),r.set(`protocol`,t.protocol.toString()),t.deviceModel&&r.set(`device_model`,t.deviceModel),t.os&&r.set(`os`,t.os),t.osVersion&&r.set(`os_version`,t.osVersion),t.browser&&r.set(`browser`,t.browser),t.browserVersion&&r.set(`browser_version`,t.browserVersion),n.adaptiveStream&&r.set(`adaptive_stream`,`1`),n.reconnectReason&&r.set(`reconnect_reason`,n.reconnectReason.toString()),navigator.connection?.type&&r.set(`network`,navigator.connection.type),r}function Gd(e,t,n,r){return N(this,void 0,void 0,function*(){let i=new URLSearchParams;i.set(`access_token`,e);let a=new ms({clientInfo:t,connectionSettings:new ps({autoSubscribe:!!n.autoSubscribe,adaptiveStream:!!n.adaptiveStream}),reconnect:!!n.reconnect,participantSid:n.sid?n.sid:void 0,publisherOffer:r});n.reconnectReason&&(a.reconnectReason=n.reconnectReason);let o=a.toBinary(),s,c;if(ed()){let e=new CompressionStream(`gzip`),t=e.writable.getWriter();t.write(new Uint8Array(o)),t.close();let n=[],r=e.readable.getReader();for(;;){let{done:e,value:t}=yield r.read();if(e)break;n.push(t)}let i=n.reduce((e,t)=>e+t.length,0),a=new Uint8Array(i),l=0;for(let e of n)a.set(e,l),l+=e.length;s=a,c=gs.GZIP}else s=o,c=gs.NONE;let l=new hs({joinRequest:s,compression:c}).toBinary();return i.set(`join_request`,(e=>{let t=Array.from(e,e=>String.fromCodePoint(e)).join(``);return btoa(t)})(l).replace(/\+/g,`-`).replace(/\//g,`_`)),i})}var Kd=class{constructor(){this.buffer=[],this._totalSize=0}push(e){this.buffer.push(e),this._totalSize+=e.data.byteLength}pop(){let e=this.buffer.shift();return e&&(this._totalSize-=e.data.byteLength),e}getAll(){return this.buffer.slice()}popToSequence(e){for(;this.buffer.length>0&&this.buffer[0].sequence<=e;)this.pop()}alignBufferedAmount(e){for(;this.buffer.length>0;){let t=this.buffer[0];if(this._totalSize-t.data.byteLength<=e)break;this.pop()}}get length(){return this.buffer.length}},qd=class{constructor(e){this._map=new Map,this._lastCleanup=0,this.ttl=e}set(e,t){let n=Date.now();n-this._lastCleanup>this.ttl/2&&this.cleanup();let r=n+this.ttl;return this._map.set(e,{value:t,expiresAt:r}),this}get(e){let t=this._map.get(e);if(t){if(t.expiresAt<Date.now()){this._map.delete(e);return}return t.value}}has(e){let t=this._map.get(e);return t?t.expiresAt<Date.now()?(this._map.delete(e),!1):!0:!1}delete(e){return this._map.delete(e)}clear(){this._map.clear()}cleanup(){let e=Date.now();for(let[t,n]of this._map.entries())n.expiresAt<e&&this._map.delete(t);this._lastCleanup=e}get size(){return this.cleanup(),this._map.size}forEach(e){this.cleanup();for(let[t,n]of this._map.entries())n.expiresAt>=Date.now()&&e(n.value,t,this.asValueMap())}map(e){this.cleanup();let t=[],n=this.asValueMap();for(let[r,i]of n.entries())t.push(e(i,r,n));return t}asValueMap(){let e=new Map;for(let[t,n]of this._map.entries())n.expiresAt>=Date.now()&&e.set(t,n.value);return e}},Jd={},Yd={},Xd={exports:{}},Zd;function Qd(){if(Zd)return Xd.exports;Zd=1;var e=Xd.exports={v:[{name:`version`,reg:/^(\d*)$/}],o:[{name:`origin`,reg:/^(\S*) (\d*) (\d*) (\S*) IP(\d) (\S*)/,names:[`username`,`sessionId`,`sessionVersion`,`netType`,`ipVer`,`address`],format:`%s %s %d %s IP%d %s`}],s:[{name:`name`}],i:[{name:`description`}],u:[{name:`uri`}],e:[{name:`email`}],p:[{name:`phone`}],z:[{name:`timezones`}],r:[{name:`repeats`}],t:[{name:`timing`,reg:/^(\d*) (\d*)/,names:[`start`,`stop`],format:`%d %d`}],c:[{name:`connection`,reg:/^IN IP(\d) (\S*)/,names:[`version`,`ip`],format:`IN IP%d %s`}],b:[{push:`bandwidth`,reg:/^(TIAS|AS|CT|RR|RS):(\d*)/,names:[`type`,`limit`],format:`%s:%s`}],m:[{reg:/^(\w*) (\d*) ([\w/]*)(?: (.*))?/,names:[`type`,`port`,`protocol`,`payloads`],format:`%s %d %s %s`}],a:[{push:`rtp`,reg:/^rtpmap:(\d*) ([\w\-.]*)(?:\s*\/(\d*)(?:\s*\/(\S*))?)?/,names:[`payload`,`codec`,`rate`,`encoding`],format:function(e){return e.encoding?`rtpmap:%d %s/%s/%s`:e.rate?`rtpmap:%d %s/%s`:`rtpmap:%d %s`}},{push:`fmtp`,reg:/^fmtp:(\d*) ([\S| ]*)/,names:[`payload`,`config`],format:`fmtp:%d %s`},{name:`control`,reg:/^control:(.*)/,format:`control:%s`},{name:`rtcp`,reg:/^rtcp:(\d*)(?: (\S*) IP(\d) (\S*))?/,names:[`port`,`netType`,`ipVer`,`address`],format:function(e){return e.address==null?`rtcp:%d`:`rtcp:%d %s IP%d %s`}},{push:`rtcpFbTrrInt`,reg:/^rtcp-fb:(\*|\d*) trr-int (\d*)/,names:[`payload`,`value`],format:`rtcp-fb:%s trr-int %d`},{push:`rtcpFb`,reg:/^rtcp-fb:(\*|\d*) ([\w-_]*)(?: ([\w-_]*))?/,names:[`payload`,`type`,`subtype`],format:function(e){return e.subtype==null?`rtcp-fb:%s %s`:`rtcp-fb:%s %s %s`}},{push:`ext`,reg:/^extmap:(\d+)(?:\/(\w+))?(?: (urn:ietf:params:rtp-hdrext:encrypt))? (\S*)(?: (\S*))?/,names:[`value`,`direction`,`encrypt-uri`,`uri`,`config`],format:function(e){return`extmap:%d`+(e.direction?`/%s`:`%v`)+(e[`encrypt-uri`]?` %s`:`%v`)+` %s`+(e.config?` %s`:``)}},{name:`extmapAllowMixed`,reg:/^(extmap-allow-mixed)/},{push:`crypto`,reg:/^crypto:(\d*) ([\w_]*) (\S*)(?: (\S*))?/,names:[`id`,`suite`,`config`,`sessionConfig`],format:function(e){return e.sessionConfig==null?`crypto:%d %s %s`:`crypto:%d %s %s %s`}},{name:`setup`,reg:/^setup:(\w*)/,format:`setup:%s`},{name:`connectionType`,reg:/^connection:(new|existing)/,format:`connection:%s`},{name:`mid`,reg:/^mid:([^\s]*)/,format:`mid:%s`},{name:`msid`,reg:/^msid:(.*)/,format:`msid:%s`},{name:`ptime`,reg:/^ptime:(\d*(?:\.\d*)*)/,format:`ptime:%d`},{name:`maxptime`,reg:/^maxptime:(\d*(?:\.\d*)*)/,format:`maxptime:%d`},{name:`direction`,reg:/^(sendrecv|recvonly|sendonly|inactive)/},{name:`icelite`,reg:/^(ice-lite)/},{name:`iceUfrag`,reg:/^ice-ufrag:(\S*)/,format:`ice-ufrag:%s`},{name:`icePwd`,reg:/^ice-pwd:(\S*)/,format:`ice-pwd:%s`},{name:`fingerprint`,reg:/^fingerprint:(\S*) (\S*)/,names:[`type`,`hash`],format:`fingerprint:%s %s`},{push:`candidates`,reg:/^candidate:(\S*) (\d*) (\S*) (\d*) (\S*) (\d*) typ (\S*)(?: raddr (\S*) rport (\d*))?(?: tcptype (\S*))?(?: generation (\d*))?(?: network-id (\d*))?(?: network-cost (\d*))?/,names:[`foundation`,`component`,`transport`,`priority`,`ip`,`port`,`type`,`raddr`,`rport`,`tcptype`,`generation`,`network-id`,`network-cost`],format:function(e){var t=`candidate:%s %d %s %d %s %d typ %s`;return t+=e.raddr==null?`%v%v`:` raddr %s rport %d`,t+=e.tcptype==null?`%v`:` tcptype %s`,e.generation!=null&&(t+=` generation %d`),t+=e[`network-id`]==null?`%v`:` network-id %d`,t+=e[`network-cost`]==null?`%v`:` network-cost %d`,t}},{name:`endOfCandidates`,reg:/^(end-of-candidates)/},{name:`remoteCandidates`,reg:/^remote-candidates:(.*)/,format:`remote-candidates:%s`},{name:`iceOptions`,reg:/^ice-options:(\S*)/,format:`ice-options:%s`},{push:`ssrcs`,reg:/^ssrc:(\d*) ([\w_-]*)(?::(.*))?/,names:[`id`,`attribute`,`value`],format:function(e){var t=`ssrc:%d`;return e.attribute!=null&&(t+=` %s`,e.value!=null&&(t+=`:%s`)),t}},{push:`ssrcGroups`,reg:/^ssrc-group:([\x21\x23\x24\x25\x26\x27\x2A\x2B\x2D\x2E\w]*) (.*)/,names:[`semantics`,`ssrcs`],format:`ssrc-group:%s %s`},{name:`msidSemantic`,reg:/^msid-semantic:\s?(\w*) (\S*)/,names:[`semantic`,`token`],format:`msid-semantic: %s %s`},{push:`groups`,reg:/^group:(\w*) (.*)/,names:[`type`,`mids`],format:`group:%s %s`},{name:`rtcpMux`,reg:/^(rtcp-mux)/},{name:`rtcpRsize`,reg:/^(rtcp-rsize)/},{name:`sctpmap`,reg:/^sctpmap:([\w_/]*) (\S*)(?: (\S*))?/,names:[`sctpmapNumber`,`app`,`maxMessageSize`],format:function(e){return e.maxMessageSize==null?`sctpmap:%s %s`:`sctpmap:%s %s %s`}},{name:`xGoogleFlag`,reg:/^x-google-flag:([^\s]*)/,format:`x-google-flag:%s`},{push:`rids`,reg:/^rid:([\d\w]+) (\w+)(?: ([\S| ]*))?/,names:[`id`,`direction`,`params`],format:function(e){return e.params?`rid:%s %s %s`:`rid:%s %s`}},{push:`imageattrs`,reg:RegExp(`^imageattr:(\\d+|\\*)[\\s\\t]+(send|recv)[\\s\\t]+(\\*|\\[\\S+\\](?:[\\s\\t]+\\[\\S+\\])*)(?:[\\s\\t]+(recv|send)[\\s\\t]+(\\*|\\[\\S+\\](?:[\\s\\t]+\\[\\S+\\])*))?`),names:[`pt`,`dir1`,`attrs1`,`dir2`,`attrs2`],format:function(e){return`imageattr:%s %s %s`+(e.dir2?` %s %s`:``)}},{name:`simulcast`,reg:RegExp(`^simulcast:(send|recv) ([a-zA-Z0-9\\-_~;,]+)(?:\\s?(send|recv) ([a-zA-Z0-9\\-_~;,]+))?$`),names:[`dir1`,`list1`,`dir2`,`list2`],format:function(e){return`simulcast:%s %s`+(e.dir2?` %s %s`:``)}},{name:`simulcast_03`,reg:/^simulcast:[\s\t]+([\S+\s\t]+)$/,names:[`value`],format:`simulcast: %s`},{name:`framerate`,reg:/^framerate:(\d+(?:$|\.\d+))/,format:`framerate:%s`},{name:`sourceFilter`,reg:/^source-filter: *(excl|incl) (\S*) (IP4|IP6|\*) (\S*) (.*)/,names:[`filterMode`,`netType`,`addressTypes`,`destAddress`,`srcList`],format:`source-filter: %s %s %s %s %s`},{name:`bundleOnly`,reg:/^(bundle-only)/},{name:`label`,reg:/^label:(.+)/,format:`label:%s`},{name:`sctpPort`,reg:/^sctp-port:(\d+)$/,format:`sctp-port:%s`},{name:`maxMessageSize`,reg:/^max-message-size:(\d+)$/,format:`max-message-size:%s`},{push:`tsRefClocks`,reg:/^ts-refclk:([^\s=]*)(?:=(\S*))?/,names:[`clksrc`,`clksrcExt`],format:function(e){return`ts-refclk:%s`+(e.clksrcExt==null?``:`=%s`)}},{name:`mediaClk`,reg:/^mediaclk:(?:id=(\S*))? *([^\s=]*)(?:=(\S*))?(?: *rate=(\d+)\/(\d+))?/,names:[`id`,`mediaClockName`,`mediaClockValue`,`rateNumerator`,`rateDenominator`],format:function(e){var t=`mediaclk:`;return t+=e.id==null?`%v%s`:`id=%s %s`,t+=e.mediaClockValue==null?``:`=%s`,t+=e.rateNumerator==null?``:` rate=%s`,t+=e.rateDenominator==null?``:`/%s`,t}},{name:`keywords`,reg:/^keywds:(.+)$/,format:`keywds:%s`},{name:`content`,reg:/^content:(.+)/,format:`content:%s`},{name:`bfcpFloorCtrl`,reg:/^floorctrl:(c-only|s-only|c-s)/,format:`floorctrl:%s`},{name:`bfcpConfId`,reg:/^confid:(\d+)/,format:`confid:%s`},{name:`bfcpUserId`,reg:/^userid:(\d+)/,format:`userid:%s`},{name:`bfcpFloorId`,reg:/^floorid:(.+) (?:m-stream|mstrm):(.+)/,names:[`id`,`mStream`],format:`floorid:%s mstrm:%s`},{push:`invalid`,names:[`value`]}]};return Object.keys(e).forEach(function(t){e[t].forEach(function(e){e.reg||=/(.*)/,e.format||=`%s`})}),Xd.exports}var $d;function ef(){return $d?Yd:($d=1,(function(e){var t=function(e){return String(Number(e))===e?Number(e):e},n=function(e,n,r,i){if(i&&!r)n[i]=t(e[1]);else for(var a=0;a<r.length;a+=1)e[a+1]!=null&&(n[r[a]]=t(e[a+1]))},r=function(e,t,r){var i=e.name&&e.names;e.push&&!t[e.push]?t[e.push]=[]:i&&!t[e.name]&&(t[e.name]={});var a=e.push?{}:i?t[e.name]:t;n(r.match(e.reg),a,e.names,e.name),e.push&&t[e.push].push(a)},i=Qd(),a=RegExp.prototype.test.bind(/^([a-z])=(.*)/);e.parse=function(e){var t={},n=[],o=t;return e.split(/(\r\n|\r|\n)/).filter(a).forEach(function(e){var t=e[0],a=e.slice(2);t===`m`&&(n.push({rtp:[],fmtp:[]}),o=n[n.length-1]);for(var s=0;s<(i[t]||[]).length;s+=1){var c=i[t][s];if(c.reg.test(a))return r(c,o,a)}}),t.media=n,t};var o=function(e,n){var r=n.split(/=(.+)/,2);return r.length===2?e[r[0]]=t(r[1]):r.length===1&&n.length>1&&(e[r[0]]=void 0),e};e.parseParams=function(e){return e.split(/;\s?/).reduce(o,{})},e.parseFmtpConfig=e.parseParams,e.parsePayloads=function(e){return e.toString().split(` `).map(Number)},e.parseRemoteCandidates=function(e){for(var n=[],r=e.split(` `).map(t),i=0;i<r.length;i+=3)n.push({component:r[i],ip:r[i+1],port:r[i+2]});return n},e.parseImageAttributes=function(e){return e.split(` `).map(function(e){return e.substring(1,e.length-1).split(`,`).reduce(o,{})})},e.parseSimulcastStreamList=function(e){return e.split(`;`).map(function(e){return e.split(`,`).map(function(e){var n,r=!1;return e[0]===`~`?(n=t(e.substring(1,e.length)),r=!0):n=t(e),{scid:n,paused:r}})})}})(Yd),Yd)}var tf,nf;function rf(){if(nf)return tf;nf=1;var e=Qd(),t=/%[sdv%]/g,n=function(e){var n=1,r=arguments,i=r.length;return e.replace(t,function(e){if(n>=i)return e;var t=r[n];switch(n+=1,e){case`%%`:return`%`;case`%s`:return String(t);case`%d`:return Number(t);case`%v`:return``}})},r=function(e,t,r){var i=t.format instanceof Function?t.format(t.push?r:r[t.name]):t.format,a=[e+`=`+i];if(t.names)for(var o=0;o<t.names.length;o+=1){var s=t.names[o];t.name?a.push(r[t.name][s]):a.push(r[t.names[o]])}else a.push(r[t.name]);return n.apply(null,a)},i=[`v`,`o`,`s`,`i`,`u`,`e`,`p`,`c`,`b`,`t`,`r`,`z`,`a`],a=[`i`,`c`,`b`,`a`];return tf=function(t,n){n||={},t.version??=0,t.name??=` `,t.media.forEach(function(e){e.payloads??=``});var o=n.outerOrder||i,s=n.innerOrder||a,c=[];return o.forEach(function(n){e[n].forEach(function(e){e.name in t&&t[e.name]!=null?c.push(r(n,e,t)):e.push in t&&t[e.push]!=null&&t[e.push].forEach(function(t){c.push(r(n,e,t))})})}),t.media.forEach(function(t){c.push(r(`m`,e.m[0],t)),s.forEach(function(n){e[n].forEach(function(e){e.name in t&&t[e.name]!=null?c.push(r(n,e,t)):e.push in t&&t[e.push]!=null&&t[e.push].forEach(function(t){c.push(r(n,e,t))})})})}),c.join(`\r
|
|
66
66
|
`)+`\r
|
|
67
|
-
`},ef}var rf;function af(){if(rf)return qd;rf=1;var e=$d(),t=nf();return qd.grammar=Zd(),qd.write=t,qd.parse=e.parse,qd.parseParams=e.parseParams,qd.parseFmtpConfig=e.parseFmtpConfig,qd.parsePayloads=e.parsePayloads,qd.parseRemoteCandidates=e.parseRemoteCandidates,qd.parseImageAttributes=e.parseImageAttributes,qd.parseSimulcastStreamList=e.parseSimulcastStreamList,qd}var of=af();function sf(e){let t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:50,n=arguments.length>2&&arguments[2]!==void 0?arguments[2]:{},r,i=n.isImmediate??!1,a=n.callback??!1,o=n.maxWait,s=Date.now(),c=[];function l(){if(o!==void 0){let e=Date.now()-s;if(e+t>=o)return o-e}return t}let u=function(){for(var t=arguments.length,n=Array(t),o=0;o<t;o++)n[o]=arguments[o];let u=this;return new Promise((t,o)=>{let d=function(){if(r=void 0,s=Date.now(),!i){let t=e.apply(u,n);a&&a(t),c.forEach(e=>{let{resolve:n}=e;return n(t)}),c=[]}},f=i&&r===void 0;if(r!==void 0&&_l.clearTimeout(r),r=_l.setTimeout(d,l()),f){let r=e.apply(u,n);return a&&a(r),t(r)}c.push({resolve:t,reject:o})})};return u.cancel=function(e){r!==void 0&&_l.clearTimeout(r),c.forEach(t=>{let{reject:n}=t;return n(e)}),c=[]},u}var cf=.7,lf=20,uf={NegotiationStarted:`negotiationStarted`,NegotiationComplete:`negotiationComplete`,RTPVideoPayloadTypes:`rtpVideoPayloadTypes`},df=class extends zs.EventEmitter{get pc(){return this._pc||=this.createPC(),this._pc}constructor(e){let t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{};super(),this.log=M,this.ddExtID=0,this.latestOfferId=0,this.pendingCandidates=[],this.restartingIce=!1,this.renegotiate=!1,this.trackBitrates=[],this.remoteStereoMids=[],this.remoteNackMids=[],this.negotiate=sf(e=>N(this,void 0,void 0,function*(){this.emit(uf.NegotiationStarted);try{yield this.createAndSendOffer()}catch(t){if(e)e(t);else throw t}}),lf),this.close=()=>{this._pc&&=(this._pc.close(),this._pc.onconnectionstatechange=null,this._pc.oniceconnectionstatechange=null,this._pc.onicegatheringstatechange=null,this._pc.ondatachannel=null,this._pc.onnegotiationneeded=null,this._pc.onsignalingstatechange=null,this._pc.onicecandidate=null,this._pc.ondatachannel=null,this._pc.ontrack=null,this._pc.onconnectionstatechange=null,this._pc.oniceconnectionstatechange=null,null)},this.log=Ts(t.loggerName??ws.PCTransport),this.loggerOptions=t,this.config=e,this._pc=this.createPC(),this.offerLock=new ur}createPC(){let e=new RTCPeerConnection(this.config);return e.onicecandidate=e=>{var t;e.candidate&&((t=this.onIceCandidate)==null||t.call(this,e.candidate))},e.onicecandidateerror=e=>{var t;(t=this.onIceCandidateError)==null||t.call(this,e)},e.oniceconnectionstatechange=()=>{var t;(t=this.onIceConnectionStateChange)==null||t.call(this,e.iceConnectionState)},e.onsignalingstatechange=()=>{var t;(t=this.onSignalingStatechange)==null||t.call(this,e.signalingState)},e.onconnectionstatechange=()=>{var t;(t=this.onConnectionStateChange)==null||t.call(this,e.connectionState)},e.ondatachannel=e=>{var t;(t=this.onDataChannel)==null||t.call(this,e)},e.ontrack=e=>{var t;(t=this.onTrack)==null||t.call(this,e)},e}get logContext(){var e;return Object.assign({},(e=this.loggerOptions).loggerContextCb?.call(e))}get isICEConnected(){return this._pc!==null&&(this.pc.iceConnectionState===`connected`||this.pc.iceConnectionState===`completed`)}addIceCandidate(e){return N(this,void 0,void 0,function*(){if(this.pc.remoteDescription&&!this.restartingIce)return this.pc.addIceCandidate(e);this.pendingCandidates.push(e)})}setRemoteDescription(e,t){return N(this,void 0,void 0,function*(){if(e.type===`answer`&&this.latestOfferId>0&&t>0&&t!==this.latestOfferId)return this.log.warn(`ignoring answer for old offer`,Object.assign(Object.assign({},this.logContext),{offerId:t,latestOfferId:this.latestOfferId})),!1;let n;if(e.type===`offer`){let{stereoMids:t,nackMids:n}=pf(e);this.remoteStereoMids=t,this.remoteNackMids=n}else if(e.type===`answer`){if(this.pendingInitialOffer){let e=this.pendingInitialOffer;this.pendingInitialOffer=void 0;let t=of.parse(e.sdp??``);t.media.forEach(e=>{mf(e)}),this.log.debug(`setting pending initial offer before processing answer`,this.logContext),yield this.setMungedSDP(e,of.write(t))}let t=of.parse(e.sdp??``);t.media.forEach(e=>{let t=hf(e.mid);e.type===`audio`&&this.trackBitrates.some(n=>{if(!n.transceiver||t!=n.transceiver.mid)return!1;let r=0;if(e.rtp.some(e=>e.codec.toUpperCase()===n.codec.toUpperCase()?(r=e.payload,!0):!1),r===0)return!0;let i=!1;for(let t of e.fmtp)if(t.payload===r){t.config=t.config.split(`;`).filter(e=>!e.includes(`maxaveragebitrate`)).join(`;`),n.maxbr>0&&(t.config+=`;maxaveragebitrate=${n.maxbr*1e3}`),i=!0;break}return i||n.maxbr>0&&e.fmtp.push({payload:r,config:`maxaveragebitrate=${n.maxbr*1e3}`}),!0})}),n=of.write(t)}return yield this.setMungedSDP(e,n,!0),this.pendingCandidates.forEach(e=>{this.pc.addIceCandidate(e)}),this.pendingCandidates=[],this.restartingIce=!1,this.renegotiate?(this.renegotiate=!1,yield this.createAndSendOffer()):e.type===`answer`&&(this.emit(uf.NegotiationComplete),e.sdp&&of.parse(e.sdp).media.forEach(e=>{e.type===`video`&&this.emit(uf.RTPVideoPayloadTypes,e.rtp)})),!0})}createInitialOffer(){return N(this,void 0,void 0,function*(){let e=yield this.offerLock.lock();try{if(this.pc.signalingState!==`stable`){this.log.warn(`signaling state is not stable, cannot create initial offer`,this.logContext);return}let e=this.latestOfferId+1;this.latestOfferId=e;let t=yield this.pc.createOffer();this.pendingInitialOffer={sdp:t.sdp,type:t.type};let n=of.parse(t.sdp??``);return n.media.forEach(e=>{mf(e)}),t.sdp=of.write(n),{offer:t,offerId:e}}finally{e()}})}createAndSendOffer(e){return N(this,void 0,void 0,function*(){let t=yield this.offerLock.lock();try{if(this.onOffer===void 0)return;if(e?.iceRestart&&(this.log.debug(`restarting ICE`,this.logContext),this.restartingIce=!0),this._pc&&(this._pc.signalingState===`have-local-offer`||this.pendingInitialOffer)){let t=this._pc.remoteDescription;if(e?.iceRestart&&t)yield this._pc.setRemoteDescription(t);else{this.renegotiate=!0,this.log.debug(`requesting renegotiation`,Object.assign({},this.logContext));return}}else if(!this._pc||this._pc.signalingState===`closed`){this.log.warn(`could not createOffer with closed peer connection`,this.logContext);return}this.log.debug(`starting to negotiate`,this.logContext);let t=this.latestOfferId+1;this.latestOfferId=t;let n=yield this.pc.createOffer(e);this.log.debug(`original offer`,Object.assign({sdp:n.sdp},this.logContext));let r=of.parse(n.sdp??``);if(r.media.forEach(e=>{mf(e),e.type===`audio`?ff(e,[`all`],[]):e.type===`video`&&this.trackBitrates.some(t=>{if(!e.msid||!t.cid||!e.msid.includes(t.cid))return!1;let n=0;if(e.rtp.some(e=>e.codec.toUpperCase()===t.codec.toUpperCase()?(n=e.payload,!0):!1),n===0||(ru(t.codec)&&!cu()&&this.ensureVideoDDExtensionForSVC(e,r),!ru(t.codec)))return!0;let i=Math.round(t.maxbr*cf);for(let t of e.fmtp)if(t.payload===n){t.config.includes(`x-google-start-bitrate`)||(t.config+=`;x-google-start-bitrate=${i}`);break}return!0})}),this.latestOfferId>t){this.log.warn(`latestOfferId mismatch`,Object.assign(Object.assign({},this.logContext),{latestOfferId:this.latestOfferId,offerId:t}));return}yield this.setMungedSDP(n,of.write(r)),this.onOffer(n,this.latestOfferId)}finally{t()}})}createAndSetAnswer(){return N(this,void 0,void 0,function*(){let e=yield this.pc.createAnswer(),t=of.parse(e.sdp??``);return t.media.forEach(e=>{mf(e),e.type===`audio`&&ff(e,this.remoteStereoMids,this.remoteNackMids)}),yield this.setMungedSDP(e,of.write(t)),e})}createDataChannel(e,t){return this.pc.createDataChannel(e,t)}addTransceiver(e,t){return this.pc.addTransceiver(e,t)}addTransceiverOfKind(e,t){return this.pc.addTransceiver(e,t)}addTrack(e){if(!this._pc)throw new I(`PC closed, cannot add track`);return this._pc.addTrack(e)}setTrackCodecBitrate(e){this.trackBitrates.push(e)}setConfiguration(e){if(!this._pc)throw new I(`PC closed, cannot configure`);return this._pc?.setConfiguration(e)}canRemoveTrack(){return!!this._pc?.removeTrack}removeTrack(e){return this._pc?.removeTrack(e)}getConnectionState(){return this._pc?.connectionState??`closed`}getICEConnectionState(){return this._pc?.iceConnectionState??`closed`}getSignallingState(){return this._pc?.signalingState??`closed`}getTransceivers(){return this._pc?.getTransceivers()??[]}getSenders(){return this._pc?.getSenders()??[]}getLocalDescription(){return this._pc?.localDescription}getRemoteDescription(){return this.pc?.remoteDescription}getStats(){return this.pc.getStats()}getConnectedAddress(){return N(this,void 0,void 0,function*(){if(!this._pc)return;let e=``,t=new Map,n=new Map;if((yield this._pc.getStats()).forEach(r=>{switch(r.type){case`transport`:e=r.selectedCandidatePairId;break;case`candidate-pair`:e===``&&r.selected&&(e=r.id),t.set(r.id,r);break;case`remote-candidate`:n.set(r.id,`${r.address}:${r.port}`);break}}),e===``)return;let r=t.get(e)?.remoteCandidateId;if(r!==void 0)return n.get(r)})}setMungedSDP(e,t,n){return N(this,void 0,void 0,function*(){if(t){let r=e.sdp;e.sdp=t;try{this.log.debug(`setting munged ${n?`remote`:`local`} description`,this.logContext),n?yield this.pc.setRemoteDescription(e):yield this.pc.setLocalDescription(e);return}catch(n){this.log.warn(`not able to set ${e.type}, falling back to unmodified sdp`,Object.assign(Object.assign({},this.logContext),{error:n,sdp:t})),e.sdp=r}}try{n?yield this.pc.setRemoteDescription(e):yield this.pc.setLocalDescription(e)}catch(t){let r=`unknown error`;t instanceof Error?r=t.message:typeof t==`string`&&(r=t);let i={error:r,sdp:e.sdp};throw!n&&this.pc.remoteDescription&&(i.remoteSdp=this.pc.remoteDescription),this.log.error(`unable to set ${e.type}`,Object.assign(Object.assign({},this.logContext),{fields:i})),new ul(r)}})}ensureVideoDDExtensionForSVC(e,t){var n;if(!e.ext?.some(e=>e.uri===Xl)){if(this.ddExtID===0){let e=0;t.media.forEach(t=>{var n;t.type===`video`&&((n=t.ext)==null||n.forEach(t=>{t.value>e&&(e=t.value)}))}),this.ddExtID=e+1}(n=e.ext)==null||n.push({value:this.ddExtID,uri:Xl})}}};function ff(e,t,n){let r=hf(e.mid),i=0;e.rtp.some(e=>e.codec===`opus`?(i=e.payload,!0):!1),i>0&&(e.rtcpFb||=[],n.includes(r)&&!e.rtcpFb.some(e=>e.payload===i&&e.type===`nack`)&&e.rtcpFb.push({payload:i,type:`nack`}),(t.includes(r)||t.length===1&&t[0]===`all`)&&e.fmtp.some(e=>e.payload===i?(e.config.includes(`stereo=1`)||(e.config+=`;stereo=1`),!0):!1))}function pf(e){let t=[],n=[],r=of.parse(e.sdp??``),i=0;return r.media.forEach(e=>{let r=hf(e.mid);e.type===`audio`&&(e.rtp.some(e=>e.codec===`opus`?(i=e.payload,!0):!1),e.rtcpFb?.some(e=>e.payload===i&&e.type===`nack`)&&n.push(r),e.fmtp.some(e=>e.payload===i?(e.config.includes(`sprop-stereo=1`)&&t.push(r),!0):!1))}),{stereoMids:t,nackMids:n}}function mf(e){if(e.connection){let t=e.connection.ip.indexOf(`:`)>=0;(e.connection.version===4&&t||e.connection.version===6&&!t)&&(e.connection.ip=`0.0.0.0`,e.connection.version=4)}}function hf(e){return typeof e==`number`?e.toFixed(0):e}var gf=`vp8`,_f={audioPreset:wl.music,dtx:!0,red:!0,forceStereo:!1,simulcast:!0,screenShareEncoding:Dl.h1080fps15.encoding,stopMicTrackOnMute:!1,videoCodec:gf,backupCodec:!0,preConnectBuffer:!1},vf={deviceId:{ideal:`default`},autoGainControl:!0,echoCancellation:!0,noiseSuppression:!0,voiceIsolation:!0},yf={deviceId:{ideal:`default`},resolution:Tl.h720.resolution},bf={adaptiveStream:!1,dynacast:!1,stopLocalTrackOnUnpublish:!0,reconnectPolicy:new ks,disconnectOnPageLeave:!0,webAudioMix:!1,singlePeerConnection:!0},xf={autoSubscribe:!0,maxRetries:1,peerConnectionTimeout:15e3,websocketTimeout:15e3},G;(function(e){e[e.NEW=0]=`NEW`,e[e.CONNECTING=1]=`CONNECTING`,e[e.CONNECTED=2]=`CONNECTED`,e[e.FAILED=3]=`FAILED`,e[e.CLOSING=4]=`CLOSING`,e[e.CLOSED=5]=`CLOSED`})(G||={});var Sf=class{get needsPublisher(){return this.isPublisherConnectionRequired}get needsSubscriber(){return this.isSubscriberConnectionRequired}get currentState(){return this.state}get mode(){return this._mode}constructor(e,t,n){this.peerConnectionTimeout=xf.peerConnectionTimeout,this.log=M,this.updateState=()=>{var e;let t=this.state,n=this.requiredTransports.map(e=>e.getConnectionState());n.every(e=>e===`connected`)?this.state=G.CONNECTED:n.some(e=>e===`failed`)?this.state=G.FAILED:n.some(e=>e===`connecting`)?this.state=G.CONNECTING:n.every(e=>e===`closed`)?this.state=G.CLOSED:n.some(e=>e===`closed`)?this.state=G.CLOSING:n.every(e=>e===`new`)&&(this.state=G.NEW),t!==this.state&&(this.log.debug(`pc state change: from ${G[t]} to ${G[this.state]}`,this.logContext),(e=this.onStateChange)==null||e.call(this,this.state,this.publisher.getConnectionState(),this.subscriber?.getConnectionState()))},this.log=Ts(t.loggerName??ws.PCManager),this.loggerOptions=t,this.isPublisherConnectionRequired=e!==`subscriber-primary`,this.isSubscriberConnectionRequired=e===`subscriber-primary`,this.publisher=new df(n,t),this._mode=e,e!==`publisher-only`&&(this.subscriber=new df(n,t),this.subscriber.onConnectionStateChange=this.updateState,this.subscriber.onIceConnectionStateChange=this.updateState,this.subscriber.onSignalingStatechange=this.updateState,this.subscriber.onIceCandidate=e=>{var t;(t=this.onIceCandidate)==null||t.call(this,e,so.SUBSCRIBER)},this.subscriber.onDataChannel=e=>{var t;(t=this.onDataChannel)==null||t.call(this,e)},this.subscriber.onTrack=e=>{var t;(t=this.onTrack)==null||t.call(this,e)}),this.publisher.onConnectionStateChange=this.updateState,this.publisher.onIceConnectionStateChange=this.updateState,this.publisher.onSignalingStatechange=this.updateState,this.publisher.onIceCandidate=e=>{var t;(t=this.onIceCandidate)==null||t.call(this,e,so.PUBLISHER)},this.publisher.onTrack=e=>{var t;(t=this.onTrack)==null||t.call(this,e)},this.publisher.onOffer=(e,t)=>{var n;(n=this.onPublisherOffer)==null||n.call(this,e,t)},this.state=G.NEW,this.connectionLock=new ur,this.remoteOfferLock=new ur}get logContext(){var e;return Object.assign({},(e=this.loggerOptions).loggerContextCb?.call(e))}requirePublisher(){this.isPublisherConnectionRequired=arguments.length>0&&arguments[0]!==void 0?arguments[0]:!0,this.updateState()}createAndSendPublisherOffer(e){return this.publisher.createAndSendOffer(e)}setPublisherAnswer(e,t){return this.publisher.setRemoteDescription(e,t)}removeTrack(e){return this.publisher.removeTrack(e)}close(){return N(this,void 0,void 0,function*(){if(this.publisher&&this.publisher.getSignallingState()!==`closed`){let e=this.publisher;for(let t of e.getSenders())try{e.canRemoveTrack()&&e.removeTrack(t)}catch(e){this.log.warn(`could not removeTrack`,Object.assign(Object.assign({},this.logContext),{error:e}))}}yield Promise.all([this.publisher.close(),this.subscriber?.close()]),this.updateState()})}triggerIceRestart(){return N(this,void 0,void 0,function*(){this.subscriber&&(this.subscriber.restartingIce=!0),this.needsPublisher&&(yield this.createAndSendPublisherOffer({iceRestart:!0}))})}addIceCandidate(e,t){return N(this,void 0,void 0,function*(){t===so.PUBLISHER?yield this.publisher.addIceCandidate(e):yield this.subscriber?.addIceCandidate(e)})}createSubscriberAnswerFromOffer(e,t){return N(this,void 0,void 0,function*(){this.log.debug(`received server offer`,Object.assign(Object.assign({},this.logContext),{RTCSdpType:e.type,sdp:e.sdp,signalingState:this.subscriber?.getSignallingState().toString()}));let n=yield this.remoteOfferLock.lock();try{return(yield this.subscriber?.setRemoteDescription(e,t))?yield this.subscriber?.createAndSetAnswer():void 0}finally{n()}})}updateConfiguration(e,t){var n;this.publisher.setConfiguration(e),(n=this.subscriber)==null||n.setConfiguration(e),t&&this.triggerIceRestart()}ensurePCTransportConnection(e,t){return N(this,void 0,void 0,function*(){let n=yield this.connectionLock.lock();try{this.isPublisherConnectionRequired&&this.publisher.getConnectionState()!==`connected`&&this.publisher.getConnectionState()!==`connecting`&&(this.log.debug(`negotiation required, start negotiating`,this.logContext),this.publisher.negotiate()),yield Promise.all(this.requiredTransports?.map(n=>this.ensureTransportConnected(n,e,t)))}finally{n()}})}negotiate(e){return N(this,void 0,void 0,function*(){return new Zc((t,n)=>N(this,void 0,void 0,function*(){let r=setTimeout(()=>{n(new ul(`negotiation timed out`))},this.peerConnectionTimeout),i=()=>{clearTimeout(r),this.publisher.off(uf.NegotiationStarted,o),e.signal.removeEventListener(`abort`,a)},a=()=>{i(),n(new ul(`negotiation aborted`))},o=()=>{e.signal.aborted||(clearTimeout(r),r=setTimeout(()=>{i(),n(new ul(`negotiation timed out`))},this.peerConnectionTimeout))};e.signal.addEventListener(`abort`,a),this.publisher.on(uf.NegotiationStarted,o),this.publisher.once(uf.NegotiationComplete,()=>{i(),t()}),yield this.publisher.negotiate(e=>{i(),e instanceof Error?n(e):n(Error(String(e)))})}))})}addPublisherTransceiver(e,t){return this.publisher.addTransceiver(e,t)}addPublisherTransceiverOfKind(e,t){return this.publisher.addTransceiverOfKind(e,t)}getMidForReceiver(e){return(this.subscriber?this.subscriber.getTransceivers():this.publisher.getTransceivers()).find(t=>t.receiver===e)?.mid}addPublisherTrack(e){return this.publisher.addTrack(e)}createPublisherDataChannel(e,t){return this.publisher.createDataChannel(e,t)}getConnectedAddress(e){return e===so.PUBLISHER||e===so.SUBSCRIBER?this.publisher.getConnectedAddress():this.requiredTransports[0].getConnectedAddress()}get requiredTransports(){let e=[];return this.isPublisherConnectionRequired&&e.push(this.publisher),this.isSubscriberConnectionRequired&&this.subscriber&&e.push(this.subscriber),e}ensureTransportConnected(e,t){return N(this,arguments,void 0,function(e,t){var n=this;let r=arguments.length>2&&arguments[2]!==void 0?arguments[2]:this.peerConnectionTimeout;return function*(){if(e.getConnectionState()!==`connected`)return new Promise((e,i)=>N(n,void 0,void 0,function*(){let n=()=>{this.log.warn(`abort transport connection`,this.logContext),_l.clearTimeout(a),i(F.cancelled(`room connection has been cancelled`))};t?.signal.aborted&&n(),t?.signal.addEventListener(`abort`,n);let a=_l.setTimeout(()=>{t?.signal.removeEventListener(`abort`,n),i(F.internal(`could not establish pc connection`))},r);for(;this.state!==G.CONNECTED;)if(yield Ql(50),t?.signal.aborted){i(F.cancelled(`room connection has been cancelled`));return}_l.clearTimeout(a),t?.signal.removeEventListener(`abort`,n),e()}))}()})}},Cf=5e3,wf=3e4,Tf=class e{static fetchRegionSettings(t,n,r){return N(this,void 0,void 0,function*(){let i=yield e.fetchLock.lock();try{let e=yield fetch(`${Ef(t)}/regions`,{headers:{authorization:`Bearer ${n}`},signal:r});if(e.ok){let t=Qu(e.headers),n=t?t*1e3:Cf;return{regionSettings:yield e.json(),updatedAtInMs:Date.now(),maxAgeInMs:n}}else if(e.status===401)throw F.notAllowed(`Could not fetch region settings: ${e.statusText}`,e.status);else throw F.internal(`Could not fetch region settings: ${e.statusText}`)}catch(e){throw e instanceof F?e:r?.aborted?F.cancelled(`Region fetching was aborted`):F.serverUnreachable(`Could not fetch region settings, ${e instanceof Error?`${e.name}: ${e.message}`:e}`)}finally{i()}})}static scheduleRefetch(t,n,r){return N(this,void 0,void 0,function*(){let i=e.settingsTimeouts.get(t.hostname);clearTimeout(i),e.settingsTimeouts.set(t.hostname,setTimeout(()=>N(this,void 0,void 0,function*(){try{let r=yield e.fetchRegionSettings(t,n);e.updateCachedRegionSettings(t,n,r)}catch(i){if(i instanceof F&&i.reason===P.NotAllowed){M.debug(`token is not valid, cancelling auto region refresh`);return}M.debug(`auto refetching of region settings failed`,{error:i}),e.scheduleRefetch(t,n,r)}}),r))})}static updateCachedRegionSettings(t,n,r){e.cache.set(t.hostname,r),e.scheduleRefetch(t,n,r.maxAgeInMs)}static stopRefetch(t){let n=e.settingsTimeouts.get(t);n&&(clearTimeout(n),e.settingsTimeouts.delete(t))}static scheduleCleanup(t){let n=e.connectionTrackers.get(t);n&&(n.cleanupTimeout&&clearTimeout(n.cleanupTimeout),n.cleanupTimeout=setTimeout(()=>{let n=e.connectionTrackers.get(t);n&&n.connectionCount===0&&(M.debug(`stopping region refetch after disconnect delay`,{hostname:t}),e.stopRefetch(t)),n&&(n.cleanupTimeout=void 0)},wf))}static cancelCleanup(t){let n=e.connectionTrackers.get(t);n?.cleanupTimeout&&(clearTimeout(n.cleanupTimeout),n.cleanupTimeout=void 0)}notifyConnected(){let t=this.serverUrl.hostname,n=e.connectionTrackers.get(t);n||(n={connectionCount:0},e.connectionTrackers.set(t,n)),n.connectionCount++,e.cancelCleanup(t)}notifyDisconnected(){let t=this.serverUrl.hostname,n=e.connectionTrackers.get(t);n&&(n.connectionCount=Math.max(0,n.connectionCount-1),n.connectionCount===0&&e.scheduleCleanup(t))}constructor(e,t){this.attemptedRegions=[],this.serverUrl=new URL(e),this.token=t}updateToken(e){this.token=e}isCloud(){return gu(this.serverUrl)}getServerUrl(){return this.serverUrl}fetchRegionSettings(t){return N(this,void 0,void 0,function*(){return e.fetchRegionSettings(this.serverUrl,this.token,t)})}getNextBestRegionUrl(t){return N(this,void 0,void 0,function*(){if(!this.isCloud())throw Error(`region availability is only supported for LiveKit Cloud domains`);let n=e.cache.get(this.serverUrl.hostname);(!n||Date.now()-n.updatedAtInMs>n.maxAgeInMs)&&(n=yield this.fetchRegionSettings(t),e.updateCachedRegionSettings(this.serverUrl,this.token,n));let r=n.regionSettings.regions.filter(e=>!this.attemptedRegions.find(t=>t.url===e.url));if(r.length>0){let e=r[0];return this.attemptedRegions.push(e),M.debug(`next region: ${e.region}`),e.url}else return null})}resetAttempts(){this.attemptedRegions=[]}setServerReportedRegions(t){e.updateCachedRegionSettings(this.serverUrl,this.token,t)}};Tf.cache=new Map,Tf.settingsTimeouts=new Map,Tf.connectionTrackers=new Map,Tf.fetchLock=new ur;function Ef(e){return`${e.protocol.replace(`ws`,`http`)}//${e.host}/settings`}var Df=class e extends Error{constructor(t,n,r){super(n),this.code=t,this.message=Af(n,e.MAX_MESSAGE_BYTES),this.data=r?Af(r,e.MAX_DATA_BYTES):void 0}static fromProto(t){return new e(t.code,t.message,t.data)}toProto(){return new Wa({code:this.code,message:this.message,data:this.data})}static builtIn(t,n){return new e(e.ErrorCode[t],e.ErrorMessage[t],n)}};Df.MAX_MESSAGE_BYTES=256,Df.MAX_DATA_BYTES=15360,Df.ErrorCode={APPLICATION_ERROR:1500,CONNECTION_TIMEOUT:1501,RESPONSE_TIMEOUT:1502,RECIPIENT_DISCONNECTED:1503,RESPONSE_PAYLOAD_TOO_LARGE:1504,SEND_FAILED:1505,UNSUPPORTED_METHOD:1400,RECIPIENT_NOT_FOUND:1401,REQUEST_PAYLOAD_TOO_LARGE:1402,UNSUPPORTED_SERVER:1403,UNSUPPORTED_VERSION:1404},Df.ErrorMessage={APPLICATION_ERROR:`Application error in method handler`,CONNECTION_TIMEOUT:`Connection timeout`,RESPONSE_TIMEOUT:`Response timeout`,RECIPIENT_DISCONNECTED:`Recipient disconnected`,RESPONSE_PAYLOAD_TOO_LARGE:`Response payload too large`,SEND_FAILED:`Failed to send`,UNSUPPORTED_METHOD:`Method not supported at destination`,RECIPIENT_NOT_FOUND:`Recipient not found`,REQUEST_PAYLOAD_TOO_LARGE:`Request payload too large`,UNSUPPORTED_SERVER:`RPC not supported by server`,UNSUPPORTED_VERSION:`Unsupported RPC version`};var Of=15360;function kf(e){return new TextEncoder().encode(e).length}function Af(e,t){if(kf(e)<=t)return e;let n=0,r=e.length,i=new TextEncoder;for(;n<r;){let a=Math.floor((n+r+1)/2);i.encode(e.slice(0,a)).length<=t?n=a:r=a-1}return e.slice(0,n)}var jf=2e3;function Mf(e,t){if(!t)return 0;let n,r;return`bytesReceived`in e?(n=e.bytesReceived,r=t.bytesReceived):`bytesSent`in e&&(n=e.bytesSent,r=t.bytesSent),n===void 0||r===void 0||e.timestamp===void 0||t.timestamp===void 0?0:(n-r)*8*1e3/(e.timestamp-t.timestamp)}var Nf=typeof MediaRecorder<`u`,Pf=Nf?MediaRecorder:class{constructor(){throw Error(`MediaRecorder is not available in this environment`)}},Ff=class extends Pf{constructor(e,t){if(!Nf)throw Error(`MediaRecorder is not available in this environment`);super(new MediaStream([e.mediaStreamTrack]),t);let n,r,i=()=>r===void 0,a=()=>{this.removeEventListener(`dataavailable`,n),this.removeEventListener(`stop`,a),this.removeEventListener(`error`,o),r?.close(),r=void 0},o=e=>{r?.error(e),this.removeEventListener(`dataavailable`,n),this.removeEventListener(`stop`,a),this.removeEventListener(`error`,o),r=void 0};this.byteStream=new ReadableStream({start:e=>{r=e,n=t=>N(this,void 0,void 0,function*(){let n;if(t.data.arrayBuffer){let e=yield t.data.arrayBuffer();n=new Uint8Array(e)}else if(t.data.byteArray)n=t.data.byteArray;else throw Error(`no data available!`);i()||e.enqueue(n)}),this.addEventListener(`dataavailable`,n)},cancel:()=>{a()}}),this.addEventListener(`stop`,a),this.addEventListener(`error`,o)}};function If(){return Nf}var Lf=1e3,Rf=1e4,zf=class extends U{get sender(){return this._sender}set sender(e){this._sender=e}get constraints(){return this._constraints}get hasPreConnectBuffer(){return!!this.localTrackRecorder}constructor(e,t,n){let r=arguments.length>3&&arguments[3]!==void 0?arguments[3]:!1,i=arguments.length>4?arguments[4]:void 0;super(e,t,i),this.manuallyStopped=!1,this.pendingDeviceChange=!1,this._isUpstreamPaused=!1,this.handleTrackMuteEvent=()=>this.debouncedTrackMuteHandler().catch(()=>this.log.debug(`track mute bounce got cancelled by an unmute event`,this.logContext)),this.debouncedTrackMuteHandler=sf(()=>N(this,void 0,void 0,function*(){yield this.pauseUpstream()}),5e3),this.handleTrackUnmuteEvent=()=>N(this,void 0,void 0,function*(){this.debouncedTrackMuteHandler.cancel(`unmute`),yield this.resumeUpstream()}),this.handleEnded=()=>{this.isInBackground&&(this.reacquireTrack=!0),this._mediaStreamTrack.removeEventListener(`mute`,this.handleTrackMuteEvent),this._mediaStreamTrack.removeEventListener(`unmute`,this.handleTrackUnmuteEvent),this.emit(B.Ended,this)},this.reacquireTrack=!1,this.providedByUser=r,this.muteLock=new ur,this.pauseUpstreamLock=new ur,this.trackChangeLock=new ur,this.trackChangeLock.lock().then(t=>N(this,void 0,void 0,function*(){try{yield this.setMediaStreamTrack(e,!0)}finally{t()}})),this._constraints=e.getConstraints(),n&&(this._constraints=n)}get id(){return this._mediaStreamTrack.id}get dimensions(){if(this.kind!==U.Kind.Video)return;let{width:e,height:t}=this._mediaStreamTrack.getSettings();if(e&&t)return{width:e,height:t}}get isUpstreamPaused(){return this._isUpstreamPaused}get isUserProvided(){return this.providedByUser}get mediaStreamTrack(){return this.processor?.processedTrack??this._mediaStreamTrack}get isLocal(){return!0}getSourceTrackSettings(){return this._mediaStreamTrack.getSettings()}setMediaStreamTrack(e,t,n){return N(this,void 0,void 0,function*(){if(e===this._mediaStreamTrack&&!t)return;this._mediaStreamTrack&&(this.attachedElements.forEach(e=>{Jl(this._mediaStreamTrack,e)}),this.debouncedTrackMuteHandler.cancel(`new-track`),this._mediaStreamTrack.removeEventListener(`ended`,this.handleEnded),this._mediaStreamTrack.removeEventListener(`mute`,this.handleTrackMuteEvent),this._mediaStreamTrack.removeEventListener(`unmute`,this.handleTrackUnmuteEvent)),this.mediaStream=new MediaStream([e]),e&&(e.addEventListener(`ended`,this.handleEnded),e.addEventListener(`mute`,this.handleTrackMuteEvent),e.addEventListener(`unmute`,this.handleTrackUnmuteEvent),this._constraints=e.getConstraints());let r;if(this.processor&&e){if(this.log.debug(`restarting processor`,this.logContext),this.kind===`unknown`)throw TypeError(`cannot set processor on track of unknown kind`);this.processorElement&&(ql(e,this.processorElement),this.processorElement.muted=!0),yield this.processor.restart({track:e,kind:this.kind,element:this.processorElement}),r=this.processor.processedTrack}this.sender&&this.sender.transport?.state!==`closed`&&(yield this.sender.replaceTrack(r??e)),!this.providedByUser&&this._mediaStreamTrack!==e&&this._mediaStreamTrack.stop(),this._mediaStreamTrack=e,e&&(this._mediaStreamTrack.enabled=n?!0:!this.isMuted,yield this.resumeUpstream(),this.attachedElements.forEach(t=>{ql(r??e,t)}))})}waitForDimensions(){return N(this,arguments,void 0,function(){var e=this;let t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:Lf;return function*(){if(e.kind===U.Kind.Audio)throw Error(`cannot get dimensions for audio tracks`);el()?.os===`iOS`&&(yield Ql(10));let n=Date.now();for(;Date.now()-n<t;){let t=e.dimensions;if(t)return t;yield Ql(50)}throw new cl(`unable to get track dimensions after timeout`)}()})}setDeviceId(e){return N(this,void 0,void 0,function*(){return this._constraints.deviceId===e&&this._mediaStreamTrack.getSettings().deviceId===Pu(e)?!0:(this._constraints.deviceId=e,this.isMuted?(this.pendingDeviceChange=!0,!0):(yield this.restartTrack(),Pu(e)===this._mediaStreamTrack.getSettings().deviceId))})}getDeviceId(){return N(this,arguments,void 0,function(){var e=this;let t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:!0;return function*(){if(e.source===U.Source.ScreenShare)return;let{deviceId:n,groupId:r}=e._mediaStreamTrack.getSettings(),i=e.kind===U.Kind.Audio?`audioinput`:`videoinput`;return t?Sd.getInstance().normalizeDeviceId(i,n,r):n}()})}mute(){return N(this,void 0,void 0,function*(){return this.setTrackMuted(!0),this})}unmute(){return N(this,void 0,void 0,function*(){return this.setTrackMuted(!1),this})}replaceTrack(e,t){return N(this,void 0,void 0,function*(){let n=yield this.trackChangeLock.lock();try{if(!this.sender)throw new cl(`unable to replace an unpublished track`);let n,r;return typeof t==`boolean`?n=t:t!==void 0&&(n=t.userProvidedTrack,r=t.stopProcessor),this.providedByUser=n??!0,this.log.debug(`replace MediaStreamTrack`,this.logContext),yield this.setMediaStreamTrack(e),r&&this.processor&&(yield this.internalStopProcessor()),this}finally{n()}})}restart(e,t){return N(this,void 0,void 0,function*(){this.manuallyStopped=!1;let n=yield this.trackChangeLock.lock();try{e||=this._constraints;let{deviceId:n,facingMode:r}=e,i=As(e,[`deviceId`,`facingMode`]);this.log.debug(`restarting track with constraints`,Object.assign(Object.assign({},this.logContext),{constraints:e}));let a={audio:!1,video:!1};this.kind===U.Kind.Video?a.video=n||r?{deviceId:n,facingMode:r}:!0:a.audio=n?Object.assign({deviceId:n},i):!0,this.attachedElements.forEach(e=>{Jl(this.mediaStreamTrack,e)}),this._mediaStreamTrack.removeEventListener(`ended`,this.handleEnded),this._mediaStreamTrack.stop();let o=(yield navigator.mediaDevices.getUserMedia(a)).getTracks()[0];return this.kind===U.Kind.Video&&(yield o.applyConstraints(i)),o.addEventListener(`ended`,this.handleEnded),this.log.debug(`re-acquired MediaStreamTrack`,this.logContext),yield this.setMediaStreamTrack(o,!1,t),this._constraints=e,this.pendingDeviceChange=!1,this.emit(B.Restarted,this),this.manuallyStopped&&(this.log.warn(`track was stopped during a restart, stopping restarted track`,this.logContext),this.stop()),this}finally{n()}})}setTrackMuted(e){this.log.debug(`setting ${this.kind} track ${e?`muted`:`unmuted`}`,this.logContext),!(this.isMuted===e&&this._mediaStreamTrack.enabled!==e)&&(this.isMuted=e,this._mediaStreamTrack.enabled=!e,this.emit(e?B.Muted:B.Unmuted,this))}get needsReAcquisition(){return this._mediaStreamTrack.readyState!==`live`||this._mediaStreamTrack.muted||!this._mediaStreamTrack.enabled||this.reacquireTrack}handleAppVisibilityChanged(){let e=Object.create(null,{handleAppVisibilityChanged:{get:()=>super.handleAppVisibilityChanged}});return N(this,void 0,void 0,function*(){yield e.handleAppVisibilityChanged.call(this),fu()&&(this.log.debug(`visibility changed, is in Background: ${this.isInBackground}`,this.logContext),!this.isInBackground&&this.needsReAcquisition&&!this.isUserProvided&&!this.isMuted&&(this.log.debug(`track needs to be reacquired, restarting ${this.source}`,this.logContext),yield this.restart(),this.reacquireTrack=!1))})}stop(){var e;this.manuallyStopped=!0,super.stop(),this._mediaStreamTrack.removeEventListener(`ended`,this.handleEnded),this._mediaStreamTrack.removeEventListener(`mute`,this.handleTrackMuteEvent),this._mediaStreamTrack.removeEventListener(`unmute`,this.handleTrackUnmuteEvent),(e=this.processor)==null||e.destroy(),this.processor=void 0}pauseUpstream(){return N(this,void 0,void 0,function*(){let e=yield this.pauseUpstreamLock.lock();try{if(this._isUpstreamPaused===!0)return;if(!this.sender){this.log.warn(`unable to pause upstream for an unpublished track`,this.logContext);return}this._isUpstreamPaused=!0,this.emit(B.UpstreamPaused,this);let e=el();if(e?.name===`Safari`&&xu(e.version,`12.0`)<0)throw new sl(`pauseUpstream is not supported on Safari < 12.`);this.sender.transport?.state!==`closed`&&(yield this.sender.replaceTrack(null))}finally{e()}})}resumeUpstream(){return N(this,void 0,void 0,function*(){let e=yield this.pauseUpstreamLock.lock();try{if(this._isUpstreamPaused===!1)return;if(!this.sender){this.log.warn(`unable to resume upstream for an unpublished track`,this.logContext);return}this._isUpstreamPaused=!1,this.emit(B.UpstreamResumed,this),this.sender.transport?.state!==`closed`&&(yield this.sender.replaceTrack(this.mediaStreamTrack))}finally{e()}})}getRTCStatsReport(){return N(this,void 0,void 0,function*(){if(this.sender?.getStats)return yield this.sender.getStats()})}setProcessor(e){return N(this,arguments,void 0,function(e){var t=this;let n=arguments.length>1&&arguments[1]!==void 0?arguments[1]:!0;return function*(){let r=yield t.trackChangeLock.lock();try{t.log.debug(`setting up processor`,t.logContext);let r=document.createElement(t.kind),i={kind:t.kind,track:t._mediaStreamTrack,element:r,audioContext:t.audioContext};if(yield e.init(i),t.log.debug(`processor initialized`,t.logContext),t.processor&&(yield t.internalStopProcessor()),t.kind===`unknown`)throw TypeError(`cannot set processor on track of unknown kind`);if(ql(t._mediaStreamTrack,r),r.muted=!0,r.play().catch(e=>{e instanceof DOMException&&e.name===`AbortError`?(t.log.warn(`failed to play processor element, retrying`,Object.assign(Object.assign({},t.logContext),{error:e})),setTimeout(()=>{r.play().catch(e=>{t.log.error(`failed to play processor element`,Object.assign(Object.assign({},t.logContext),{err:e}))})},100)):t.log.error(`failed to play processor element`,Object.assign(Object.assign({},t.logContext),{error:e}))}),t.processor=e,t.processorElement=r,t.processor.processedTrack){for(let e of t.attachedElements)e!==t.processorElement&&n&&(Jl(t._mediaStreamTrack,e),ql(t.processor.processedTrack,e));yield t.sender?.replaceTrack(t.processor.processedTrack)}t.emit(B.TrackProcessorUpdate,t.processor)}finally{r()}}()})}getProcessor(){return this.processor}stopProcessor(){return N(this,arguments,void 0,function(){var e=this;let t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:!0;return function*(){let n=yield e.trackChangeLock.lock();try{yield e.internalStopProcessor(t)}finally{n()}}()})}internalStopProcessor(){return N(this,arguments,void 0,function(){var e=this;let t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:!0;return function*(){var n,r;e.processor&&(e.log.debug(`stopping processor`,e.logContext),(n=e.processor.processedTrack)==null||n.stop(),yield e.processor.destroy(),e.processor=void 0,t||((r=e.processorElement)==null||r.remove(),e.processorElement=void 0),yield e._mediaStreamTrack.applyConstraints(e._constraints),yield e.setMediaStreamTrack(e._mediaStreamTrack,!0),e.emit(B.TrackProcessorUpdate))}()})}startPreConnectBuffer(){let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:100;if(!If()){this.log.warn(`MediaRecorder is not available, cannot start preconnect buffer`,this.logContext);return}if(this.localTrackRecorder){this.log.warn(`preconnect buffer already started`);return}else{let e=`audio/webm;codecs=opus`;MediaRecorder.isTypeSupported(e)||(e=`video/mp4`),this.localTrackRecorder=new Ff(this,{mimeType:e})}this.localTrackRecorder.start(e),this.autoStopPreConnectBuffer=setTimeout(()=>{this.log.warn(`preconnect buffer timed out, stopping recording automatically`,this.logContext),this.stopPreConnectBuffer()},Rf)}stopPreConnectBuffer(){clearTimeout(this.autoStopPreConnectBuffer),this.localTrackRecorder&&=(this.localTrackRecorder.stop(),void 0)}getPreConnectBuffer(){return this.localTrackRecorder?.byteStream}getPreConnectBufferMimeType(){return this.localTrackRecorder?.mimeType}},Bf=class extends zf{get enhancedNoiseCancellation(){return this.isKrispNoiseFilterEnabled}constructor(e,t){let n=arguments.length>2&&arguments[2]!==void 0?arguments[2]:!0,r=arguments.length>3?arguments[3]:void 0,i=arguments.length>4?arguments[4]:void 0;super(e,U.Kind.Audio,t,n,i),this.stopOnMute=!1,this.isKrispNoiseFilterEnabled=!1,this.monitorSender=()=>N(this,void 0,void 0,function*(){if(!this.sender){this._currentBitrate=0;return}let e;try{e=yield this.getSenderStats()}catch(e){this.log.error(`could not get audio sender stats`,Object.assign(Object.assign({},this.logContext),{error:e}));return}e&&this.prevStats&&(this._currentBitrate=Mf(e,this.prevStats)),this.prevStats=e}),this.handleKrispNoiseFilterEnable=()=>{this.isKrispNoiseFilterEnabled=!0,this.log.debug(`Krisp noise filter enabled`,this.logContext),this.emit(B.AudioTrackFeatureUpdate,this,ga.TF_ENHANCED_NOISE_CANCELLATION,!0)},this.handleKrispNoiseFilterDisable=()=>{this.isKrispNoiseFilterEnabled=!1,this.log.debug(`Krisp noise filter disabled`,this.logContext),this.emit(B.AudioTrackFeatureUpdate,this,ga.TF_ENHANCED_NOISE_CANCELLATION,!1)},this.audioContext=r,this.checkForSilence()}mute(){let e=Object.create(null,{mute:{get:()=>super.mute}});return N(this,void 0,void 0,function*(){let t=yield this.muteLock.lock();try{return this.isMuted?(this.log.debug(`Track already muted`,this.logContext),this):(this.source===U.Source.Microphone&&this.stopOnMute&&!this.isUserProvided&&(this.log.debug(`stopping mic track`,this.logContext),this._mediaStreamTrack.stop()),yield e.mute.call(this),this)}finally{t()}})}unmute(){let e=Object.create(null,{unmute:{get:()=>super.unmute}});return N(this,void 0,void 0,function*(){let t=yield this.muteLock.lock();try{return this.isMuted?(this.source===U.Source.Microphone&&(this.stopOnMute||this._mediaStreamTrack.readyState===`ended`||this.pendingDeviceChange)&&!this.isUserProvided&&(this.log.debug(`reacquiring mic track`,this.logContext),yield this.restart(void 0,!0)),yield e.unmute.call(this),this):(this.log.debug(`Track already unmuted`,this.logContext),this)}finally{t()}})}restartTrack(e){return N(this,void 0,void 0,function*(){let t;if(e){let n=Al({audio:e});typeof n.audio!=`boolean`&&(t=n.audio)}yield this.restart(t)})}restart(e,t){let n=Object.create(null,{restart:{get:()=>super.restart}});return N(this,void 0,void 0,function*(){let r=yield n.restart.call(this,e,t);return this.checkForSilence(),r})}startMonitor(){mu()&&(this.monitorInterval||=setInterval(()=>{this.monitorSender()},jf))}setProcessor(e){return N(this,void 0,void 0,function*(){let t=yield this.trackChangeLock.lock();try{if(!hu()&&!this.audioContext)throw Error(`Audio context needs to be set on LocalAudioTrack in order to enable processors`);this.processor&&(yield this.internalStopProcessor());let t={kind:this.kind,track:this._mediaStreamTrack,audioContext:this.audioContext};this.log.debug(`setting up audio processor ${e.name}`,this.logContext),yield e.init(t),this.processor=e,this.processor.processedTrack&&(yield this.sender?.replaceTrack(this.processor.processedTrack),this.processor.processedTrack.addEventListener(`enable-lk-krisp-noise-filter`,this.handleKrispNoiseFilterEnable),this.processor.processedTrack.addEventListener(`disable-lk-krisp-noise-filter`,this.handleKrispNoiseFilterDisable)),this.emit(B.TrackProcessorUpdate,this.processor)}finally{t()}})}setAudioContext(e){this.audioContext=e}getSenderStats(){return N(this,void 0,void 0,function*(){if(!this.sender?.getStats)return;let e=yield this.sender.getStats(),t;return e.forEach(e=>{e.type===`outbound-rtp`&&(t={type:`audio`,streamId:e.id,packetsSent:e.packetsSent,packetsLost:e.packetsLost,bytesSent:e.bytesSent,timestamp:e.timestamp,roundTripTime:e.roundTripTime,jitter:e.jitter})}),t})}checkForSilence(){return N(this,void 0,void 0,function*(){let e=yield jl(this);return e&&(this.isMuted||this.log.debug(`silence detected on local audio track`,this.logContext),this.emit(B.AudioSilenceDetected)),e})}};function Vf(e,t,n){switch(e.kind){case`audio`:return new Bf(e,t,!1,void 0,n);case`video`:return new ap(e,t,!1,n);default:throw new cl(`unsupported track type: ${e.kind}`)}}var Hf=Object.values(Tl),Uf=Object.values(El),Wf=Object.values(Dl),Gf=[Tl.h180,Tl.h360],Kf=[El.h180,El.h360],qf=e=>[{scaleResolutionDownBy:2,fps:e.encoding.maxFramerate}].map(t=>new V(Math.floor(e.width/t.scaleResolutionDownBy),Math.floor(e.height/t.scaleResolutionDownBy),Math.max(15e4,Math.floor(e.encoding.maxBitrate/(t.scaleResolutionDownBy**2*((e.encoding.maxFramerate??30)/(t.fps??30))))),t.fps,e.encoding.priority)),Jf=[`q`,`h`,`f`];function Yf(e,t,n,r){let i=r?.videoEncoding;e&&(i=r?.screenShareEncoding);let a=r?.simulcast,o=r?.scalabilityMode,s=r?.videoCodec;if(!i&&!a&&!o||!t||!n)return[{}];i||(i=Zf(e,t,n,s),M.debug(`using video encoding`,i));let c=i.maxFramerate,l=new V(t,n,i.maxBitrate,i.maxFramerate,i.priority);if(o&&ru(s)){let e=new np(o),t=[];if(e.spatial>3)throw Error(`unsupported scalabilityMode: ${o}`);let n=el();if(lu()||hu()||n?.name===`Chrome`&&xu(n?.version,`113`)<0){let r=e.suffix==`h`?2:3,a=du(n);for(let n=0;n<e.spatial;n+=1)t.push({rid:Jf[2-n],maxBitrate:i.maxBitrate/r**+n,maxFramerate:l.encoding.maxFramerate,scaleResolutionDownBy:a?2**n:void 0});t[0].scalabilityMode=o}else t.push({maxBitrate:i.maxBitrate,maxFramerate:l.encoding.maxFramerate,scalabilityMode:o});return l.encoding.priority&&(t[0].priority=l.encoding.priority,t[0].networkPriority=l.encoding.priority),M.debug(`using svc encoding`,{encodings:t}),t}if(!a)return[i];let u=[];u=e?tp(r?.screenShareSimulcastLayers)??$f(e,l):tp(r?.videoSimulcastLayers)??$f(e,l);let d;if(u.length>0){let e=u[0];u.length>1&&([,d]=u);let r=Math.max(t,n);if(r>=960&&d)return ep(t,n,[e,d,l],c);if(r>=480)return ep(t,n,[e,l],c)}return ep(t,n,[l])}function Xf(e,t,n){if(!n.backupCodec||n.backupCodec===!0||n.backupCodec.codec===n.videoCodec)return;t!==n.backupCodec.codec&&M.warn(`requested a different codec than specified as backup`,{serverRequested:t,backup:n.backupCodec.codec}),n.videoCodec=t,n.videoEncoding=n.backupCodec.encoding;let r=e.mediaStreamTrack.getSettings(),i=r.width??e.dimensions?.width,a=r.height??e.dimensions?.height;return e.source===U.Source.ScreenShare&&n.simulcast&&(n.simulcast=!1),Yf(e.source===U.Source.ScreenShare,i,a,n)}function Zf(e,t,n,r){let i=Qf(e,t,n),{encoding:a}=i[0],o=Math.max(t,n);for(let e=0;e<i.length;e+=1){let t=i[e];if(a=t.encoding,t.width>=o)break}if(r)switch(r){case`av1`:case`h265`:a=Object.assign({},a),a.maxBitrate*=.7;break;case`vp9`:a=Object.assign({},a),a.maxBitrate*=.85;break}return a}function Qf(e,t,n){if(e)return Wf;let r=t>n?t/n:n/t;return Math.abs(r-16/9)<Math.abs(r-4/3)?Hf:Uf}function $f(e,t){if(e)return qf(t);let{width:n,height:r}=t,i=n>r?n/r:r/n;return Math.abs(i-16/9)<Math.abs(i-4/3)?Gf:Kf}function ep(e,t,n,r){let i=[];if(n.forEach((n,a)=>{if(a>=Jf.length)return;let o=Math.min(e,t),s={rid:Jf[a],scaleResolutionDownBy:Math.max(1,o/Math.min(n.width,n.height)),maxBitrate:n.encoding.maxBitrate},c=r&&n.encoding.maxFramerate?Math.min(r,n.encoding.maxFramerate):n.encoding.maxFramerate;c&&(s.maxFramerate=c);let l=ou()||a===0;n.encoding.priority&&l&&(s.priority=n.encoding.priority,s.networkPriority=n.encoding.priority),i.push(s)}),hu()&&yu()===`ios`){let e;i.forEach(t=>{e?t.maxFramerate&&t.maxFramerate>e&&(e=t.maxFramerate):e=t.maxFramerate});let t=!0;i.forEach(n=>{n.maxFramerate!=e&&(t&&(t=!1,M.info(`Simulcast on iOS React-Native requires all encodings to share the same framerate.`)),M.info(`Setting framerate of encoding "${n.rid??``}" to ${e}`),n.maxFramerate=e)})}return i}function tp(e){if(e)return e.sort((e,t)=>{let{encoding:n}=e,{encoding:r}=t;return n.maxBitrate>r.maxBitrate?1:n.maxBitrate<r.maxBitrate?-1:n.maxBitrate===r.maxBitrate&&n.maxFramerate&&r.maxFramerate?n.maxFramerate>r.maxFramerate?1:-1:0})}var np=class{constructor(e){let t=e.match(/^L(\d)T(\d)(h|_KEY|_KEY_SHIFT){0,1}$/);if(!t)throw Error(`invalid scalability mode`);if(this.spatial=parseInt(t[1]),this.temporal=parseInt(t[2]),t.length>3)switch(t[3]){case`h`:case`_KEY`:case`_KEY_SHIFT`:this.suffix=t[3]}}toString(){return`L${this.spatial}T${this.temporal}${this.suffix??``}`}};function rp(e){return e.source===U.Source.ScreenShare||e.constraints.height&&Pu(e.constraints.height)>=1080?`maintain-resolution`:`balanced`}var ip=5e3,ap=class extends zf{get sender(){return this._sender}set sender(e){this._sender=e,this.degradationPreference&&this.setDegradationPreference(this.degradationPreference)}constructor(e,t){let n=arguments.length>2&&arguments[2]!==void 0?arguments[2]:!0,r=arguments.length>3?arguments[3]:void 0;super(e,U.Kind.Video,t,n,r),this.simulcastCodecs=new Map,this.degradationPreference=`balanced`,this.isCpuConstrained=!1,this.optimizeForPerformance=!1,this.monitorSender=()=>N(this,void 0,void 0,function*(){if(!this.sender){this._currentBitrate=0;return}let e;try{e=yield this.getSenderStats()}catch(e){this.log.error(`could not get video sender stats`,Object.assign(Object.assign({},this.logContext),{error:e}));return}let t=new Map(e.map(e=>[e.rid,e])),n=e.some(e=>e.qualityLimitationReason===`cpu`);if(n!==this.isCpuConstrained&&(this.isCpuConstrained=n,this.isCpuConstrained&&this.emit(B.CpuConstrained)),this.prevStats){let e=0;t.forEach((t,n)=>{let r=this.prevStats?.get(n);e+=Mf(t,r)}),this._currentBitrate=e}this.prevStats=t}),this.senderLock=new ur}get isSimulcast(){return!!(this.sender&&this.sender.getParameters().encodings.length>1)}startMonitor(e){if(this.signalClient=e,!mu())return;let t=this.sender?.getParameters();t&&(this.encodings=t.encodings),!this.monitorInterval&&(this.monitorInterval=setInterval(()=>{this.monitorSender()},jf))}stop(){this._mediaStreamTrack.getConstraints(),this.simulcastCodecs.forEach(e=>{e.mediaStreamTrack.stop()}),super.stop()}pauseUpstream(){let e=Object.create(null,{pauseUpstream:{get:()=>super.pauseUpstream}});return N(this,void 0,void 0,function*(){var t,n,r,i;yield e.pauseUpstream.call(this);try{for(var a=!0,o=Fs(this.simulcastCodecs.values()),s;s=yield o.next(),t=s.done,!t;a=!0)i=s.value,a=!1,yield i.sender?.replaceTrack(null)}catch(e){n={error:e}}finally{try{!a&&!t&&(r=o.return)&&(yield r.call(o))}finally{if(n)throw n.error}}})}resumeUpstream(){let e=Object.create(null,{resumeUpstream:{get:()=>super.resumeUpstream}});return N(this,void 0,void 0,function*(){var t,n,r,i;yield e.resumeUpstream.call(this);try{for(var a=!0,o=Fs(this.simulcastCodecs.values()),s;s=yield o.next(),t=s.done,!t;a=!0){i=s.value,a=!1;let e=i;yield e.sender?.replaceTrack(e.mediaStreamTrack)}}catch(e){n={error:e}}finally{try{!a&&!t&&(r=o.return)&&(yield r.call(o))}finally{if(n)throw n.error}}})}mute(){let e=Object.create(null,{mute:{get:()=>super.mute}});return N(this,void 0,void 0,function*(){let t=yield this.muteLock.lock();try{return this.isMuted?(this.log.debug(`Track already muted`,this.logContext),this):(this.source===U.Source.Camera&&!this.isUserProvided&&(this.log.debug(`stopping camera track`,this.logContext),this._mediaStreamTrack.stop()),yield e.mute.call(this),this)}finally{t()}})}unmute(){let e=Object.create(null,{unmute:{get:()=>super.unmute}});return N(this,void 0,void 0,function*(){let t=yield this.muteLock.lock();try{return this.isMuted?(this.source===U.Source.Camera&&!this.isUserProvided&&(this.log.debug(`reacquiring camera track`,this.logContext),yield this.restart(void 0,!0)),yield e.unmute.call(this),this):(this.log.debug(`Track already unmuted`,this.logContext),this)}finally{t()}})}setTrackMuted(e){super.setTrackMuted(e);for(let t of this.simulcastCodecs.values())t.mediaStreamTrack.enabled=!e}getSenderStats(){return N(this,void 0,void 0,function*(){if(!this.sender?.getStats)return[];let e=[],t=yield this.sender.getStats();return t.forEach(n=>{if(n.type===`outbound-rtp`){let r={type:`video`,streamId:n.id,frameHeight:n.frameHeight,frameWidth:n.frameWidth,framesPerSecond:n.framesPerSecond,framesSent:n.framesSent,firCount:n.firCount,pliCount:n.pliCount,nackCount:n.nackCount,packetsSent:n.packetsSent,bytesSent:n.bytesSent,qualityLimitationReason:n.qualityLimitationReason,qualityLimitationDurations:n.qualityLimitationDurations,qualityLimitationResolutionChanges:n.qualityLimitationResolutionChanges,rid:n.rid??n.id,retransmittedPacketsSent:n.retransmittedPacketsSent,targetBitrate:n.targetBitrate,timestamp:n.timestamp},i=t.get(n.remoteId);i&&(r.jitter=i.jitter,r.packetsLost=i.packetsLost,r.roundTripTime=i.roundTripTime),e.push(r)}}),e.sort((e,t)=>(t.frameWidth??0)-(e.frameWidth??0)),e})}setPublishingQuality(e){let t=[];for(let n=Kl.LOW;n<=Kl.HIGH;n+=1)t.push(new Ko({quality:n,enabled:n<=e}));this.log.debug(`setting publishing quality. max quality ${e}`,this.logContext),this.setPublishingLayers(ru(this.codec),t)}restartTrack(e){return N(this,void 0,void 0,function*(){var t,n,r,i;let a;if(e){let t=Al({video:e});typeof t.video!=`boolean`&&(a=t.video)}yield this.restart(a),this.isCpuConstrained=!1;try{for(var o=!0,s=Fs(this.simulcastCodecs.values()),c;c=yield s.next(),t=c.done,!t;o=!0){i=c.value,o=!1;let e=i;e.sender&&e.sender.transport?.state!==`closed`&&(e.mediaStreamTrack=this.mediaStreamTrack.clone(),yield e.sender.replaceTrack(e.mediaStreamTrack))}}catch(e){n={error:e}}finally{try{!o&&!t&&(r=s.return)&&(yield r.call(s))}finally{if(n)throw n.error}}})}setProcessor(e){let t=Object.create(null,{setProcessor:{get:()=>super.setProcessor}});return N(this,arguments,void 0,function(e){var n=this;let r=arguments.length>1&&arguments[1]!==void 0?arguments[1]:!0;return function*(){var i,a,o,s;if(yield t.setProcessor.call(n,e,r),n.processor?.processedTrack)try{for(var c=!0,l=Fs(n.simulcastCodecs.values()),u;u=yield l.next(),i=u.done,!i;c=!0)s=u.value,c=!1,yield s.sender?.replaceTrack(n.processor.processedTrack)}catch(e){a={error:e}}finally{try{!c&&!i&&(o=l.return)&&(yield o.call(l))}finally{if(a)throw a.error}}}()})}setDegradationPreference(e){return N(this,void 0,void 0,function*(){if(this.degradationPreference=e,this.sender)try{this.log.debug(`setting degradationPreference to ${e}`,this.logContext);let t=this.sender.getParameters();t.degradationPreference=e,this.sender.setParameters(t)}catch(e){this.log.warn(`failed to set degradationPreference`,Object.assign({error:e},this.logContext))}})}addSimulcastTrack(e,t){if(this.simulcastCodecs.has(e)){this.log.error(`${e} already added, skipping adding simulcast codec`,this.logContext);return}let n={codec:e,mediaStreamTrack:this.mediaStreamTrack.clone(),sender:void 0,encodings:t};return this.simulcastCodecs.set(e,n),n}setSimulcastTrackSender(e,t){let n=this.simulcastCodecs.get(e);n&&(n.sender=t,setTimeout(()=>{this.subscribedCodecs&&this.setPublishingCodecs(this.subscribedCodecs)},ip))}setPublishingCodecs(e){return N(this,void 0,void 0,function*(){var t,n,r,i,a,o,s;if(this.log.debug(`setting publishing codecs`,Object.assign(Object.assign({},this.logContext),{codecs:e,currentCodec:this.codec})),!this.codec&&e.length>0)return yield this.setPublishingLayers(ru(e[0].codec),e[0].qualities),[];this.subscribedCodecs=e;let c=[];try{for(t=!0,n=Fs(e);r=yield n.next(),i=r.done,!i;t=!0){s=r.value,t=!1;let e=s;if(!this.codec||this.codec===e.codec)yield this.setPublishingLayers(ru(e.codec),e.qualities);else{let t=this.simulcastCodecs.get(e.codec);if(this.log.debug(`try setPublishingCodec for ${e.codec}`,Object.assign(Object.assign({},this.logContext),{simulcastCodecInfo:t})),!t||!t.sender){for(let t of e.qualities)if(t.enabled){c.push(e.codec);break}}else t.encodings&&(this.log.debug(`try setPublishingLayersForSender ${e.codec}`,this.logContext),yield op(t.sender,t.encodings,e.qualities,this.senderLock,ru(e.codec),this.log,this.logContext))}}}catch(e){a={error:e}}finally{try{!t&&!i&&(o=n.return)&&(yield o.call(n))}finally{if(a)throw a.error}}return c})}setPublishingLayers(e,t){return N(this,void 0,void 0,function*(){if(this.optimizeForPerformance){this.log.info(`skipping setPublishingLayers due to optimized publishing performance`,Object.assign(Object.assign({},this.logContext),{qualities:t}));return}this.log.debug(`setting publishing layers`,Object.assign(Object.assign({},this.logContext),{qualities:t})),!(!this.sender||!this.encodings)&&(yield op(this.sender,this.encodings,t,this.senderLock,e,this.log,this.logContext))})}prioritizePerformance(){return N(this,void 0,void 0,function*(){if(!this.sender)throw Error(`sender not found`);let e=yield this.senderLock.lock();try{this.optimizeForPerformance=!0;let e=this.sender.getParameters();e.encodings=e.encodings.map((e,t)=>Object.assign(Object.assign({},e),{active:t===0,scaleResolutionDownBy:Math.max(1,Math.ceil((this.mediaStreamTrack.getSettings().height??360)/360)),scalabilityMode:t===0&&ru(this.codec)?`L1T3`:void 0,maxFramerate:t===0?15:0,maxBitrate:t===0?e.maxBitrate:0})),this.log.debug(`setting performance optimised encodings`,Object.assign(Object.assign({},this.logContext),{encodings:e.encodings})),this.encodings=e.encodings,yield this.sender.setParameters(e)}catch(e){this.log.error(`failed to set performance optimised encodings`,Object.assign(Object.assign({},this.logContext),{error:e})),this.optimizeForPerformance=!1}finally{e()}})}handleAppVisibilityChanged(){let e=Object.create(null,{handleAppVisibilityChanged:{get:()=>super.handleAppVisibilityChanged}});return N(this,void 0,void 0,function*(){yield e.handleAppVisibilityChanged.call(this),fu()&&this.isInBackground&&this.source===U.Source.Camera&&(this._mediaStreamTrack.enabled=!1)})}};function op(e,t,n,r,i,a,o){return N(this,void 0,void 0,function*(){let s=yield r.lock();a.debug(`setPublishingLayersForSender`,Object.assign(Object.assign({},o),{sender:e,qualities:n,senderEncodings:t}));try{let r=e.getParameters(),{encodings:s}=r;if(!s)return;if(s.length!==t.length){a.warn(`cannot set publishing layers, encodings mismatch`,Object.assign(Object.assign({},o),{encodings:s,senderEncodings:t}));return}let c=!1;i&&n.some(e=>e.enabled)&&n.forEach(e=>e.enabled=!0),s.forEach((e,r)=>{let i=e.rid??``;i===``&&(i=`q`);let s=sp(i),l=n.find(e=>e.quality===s);l&&e.active!==l.enabled&&(c=!0,e.active=l.enabled,a.debug(`setting layer ${l.quality} to ${e.active?`enabled`:`disabled`}`,o),ou()&&(l.enabled?(e.scaleResolutionDownBy=t[r].scaleResolutionDownBy,e.maxBitrate=t[r].maxBitrate,e.maxFrameRate=t[r].maxFrameRate):(e.scaleResolutionDownBy=4,e.maxBitrate=10,e.maxFrameRate=2)))}),c&&(r.encodings=s,a.debug(`setting encodings`,Object.assign(Object.assign({},o),{encodings:r.encodings})),yield e.setParameters(r))}finally{s()}})}function sp(e){switch(e){case`f`:return Kl.HIGH;case`h`:return Kl.MEDIUM;case`q`:return Kl.LOW;default:return Kl.HIGH}}function cp(e,t,n,r){if(!n)return[new Oa({quality:Kl.HIGH,width:e,height:t,bitrate:0,ssrc:0})];if(r){let r=n[0].scalabilityMode,i=new np(r),a=[],o=i.suffix==`h`?1.5:2,s=i.suffix==`h`?2:3;for(let r=0;r<i.spatial;r+=1)a.push(new Oa({quality:Math.min(Kl.HIGH,i.spatial-1)-r,width:Math.ceil(e/o**+r),height:Math.ceil(t/o**+r),bitrate:n[0].maxBitrate?Math.ceil(n[0].maxBitrate/s**+r):0,ssrc:0}));return a}return n.map(n=>{let r=n.scaleResolutionDownBy??1;return new Oa({quality:sp(n.rid??``),width:Math.ceil(e/r),height:Math.ceil(t/r),bitrate:n.maxBitrate??0,ssrc:0})})}var lp=`_lossy`,up=`_reliable`,dp=`_data_track`,fp=2*1e3,pp=`leave-reconnect`,mp=3e4,hp=8*1024,gp=256*1024,_p=3,vp=3,yp;(function(e){e[e.New=0]=`New`,e[e.Connected=1]=`Connected`,e[e.Disconnected=2]=`Disconnected`,e[e.Reconnecting=3]=`Reconnecting`,e[e.Closed=4]=`Closed`})(yp||={});var K;(function(e){e[e.RELIABLE=0]=`RELIABLE`,e[e.LOSSY=1]=`LOSSY`,e[e.DATA_TRACK_LOSSY=2]=`DATA_TRACK_LOSSY`})(K||={});var bp=class extends zs.EventEmitter{get isClosed(){return this._isClosed}get isNewlyCreated(){return this._isNewlyCreated}get pendingReconnect(){return!!this.reconnectTimeout}constructor(e){super(),this.options=e,this.rtcConfig={},this.peerConnectionTimeout=xf.peerConnectionTimeout,this.fullReconnectOnNext=!1,this.latestRemoteOfferId=0,this.subscriberPrimary=!1,this.pcState=yp.New,this._isClosed=!0,this._isNewlyCreated=!0,this.pendingTrackResolvers={},this.reconnectAttempts=0,this.reconnectStart=0,this.attemptingReconnect=!1,this.joinAttempts=0,this.maxJoinAttempts=1,this.shouldFailNext=!1,this.log=M,this.reliableDataSequence=1,this.reliableMessageBuffer=new Gd,this.reliableReceivedState=new Kd(mp),this.lossyDataStatCurrentBytes=0,this.lossyDataStatByterate=0,this.lossyDataDropCount=0,this.midToTrackId={},this.isWaitingForNetworkReconnect=!1,this.handleDataChannel=e=>N(this,[e],void 0,function(e){var t=this;let{channel:n}=e;return function*(){if(!n)return;let e;if(n.label===up)t.reliableDCSub=n,e=t.handleDataMessage;else if(n.label===lp)t.lossyDCSub=n,e=t.handleDataMessage;else if(n.label===dp)t.dataTrackDCSub=n,e=t.handleDataTrackMessage;else return;t.log.debug(`on data channel ${n.id}, ${n.label}`,t.logContext),n.onmessage=e}()}),this.handleDataMessage=e=>N(this,void 0,void 0,function*(){let t=yield this.dataProcessLock.lock();try{let t;if(e.data instanceof ArrayBuffer)t=e.data;else if(e.data instanceof Blob)t=yield e.data.arrayBuffer();else{this.log.error(`unsupported data type`,Object.assign(Object.assign({},this.logContext),{data:e.data}));return}let n=Aa.fromBinary(new Uint8Array(t));if(n.sequence>0&&n.participantSid!==``){let e=this.reliableReceivedState.get(n.participantSid);if(e&&n.sequence<=e)return;this.reliableReceivedState.set(n.participantSid,n.sequence)}if(n.value?.case===`speaker`)this.emit(z.ActiveSpeakersUpdate,n.value.value.speakers);else if(n.value?.case===`encryptedPacket`){if(!this.e2eeManager){this.log.error(`Received encrypted packet but E2EE not set up`,this.logContext);return}let e=yield this.e2eeManager?.handleEncryptedData(n.value.value.encryptedValue,n.value.value.iv,n.participantIdentity,n.value.value.keyIndex),t=new Aa({value:Na.fromBinary(e.payload).value,participantIdentity:n.participantIdentity,participantSid:n.participantSid});t.value?.case===`user`&&xp(t,t.value.value),this.emit(z.DataPacketReceived,t,n.value.value.encryptionType)}else n.value?.case===`user`&&xp(n,n.value.value),this.emit(z.DataPacketReceived,n,j.NONE)}finally{t()}}),this.handleDataTrackMessage=e=>N(this,void 0,void 0,function*(){let t;if(e.data instanceof ArrayBuffer)t=e.data;else if(e.data instanceof Blob)t=yield e.data.arrayBuffer();else{this.log.error(`unsupported data type`,Object.assign(Object.assign({},this.logContext),{data:e.data}));return}this.emit(`dataTrackPacketReceived`,new Uint8Array(t))}),this.handleDataError=e=>{let t=e.currentTarget.maxRetransmits===0?`lossy`:`reliable`;if(e instanceof ErrorEvent&&e.error){let{error:n}=e.error;this.log.error(`DataChannel error on ${t}: ${e.message}`,Object.assign(Object.assign({},this.logContext),{error:n}))}else this.log.error(`Unknown DataChannel error on ${t}`,Object.assign(Object.assign({},this.logContext),{event:e}))},this.handleBufferedAmountLow=e=>{this.updateAndEmitDCBufferStatus(e)},this.handleDisconnect=(e,t)=>{if(this._isClosed)return;this.log.warn(`${e} disconnected`,this.logContext),this.reconnectAttempts===0&&(this.reconnectStart=Date.now());let n=e=>{this.log.warn(`could not recover connection after ${this.reconnectAttempts} attempts, ${e}ms. giving up`,this.logContext),this.emit(z.Disconnected),this.close()},r=Date.now()-this.reconnectStart,i=this.getNextRetryDelay({elapsedMs:r,retryCount:this.reconnectAttempts});if(i===null){n(r);return}e===pp&&(i=0),this.log.debug(`reconnecting in ${i}ms`,this.logContext),this.clearReconnectTimeout(),this.token&&this.regionUrlProvider&&this.regionUrlProvider.updateToken(this.token),this.reconnectTimeout=_l.setTimeout(()=>this.attemptReconnect(t).finally(()=>this.reconnectTimeout=void 0),i)},this.waitForRestarted=()=>new Promise((e,t)=>{this.pcState===yp.Connected&&e();let n=()=>{this.off(z.Disconnected,r),e()},r=()=>{this.off(z.Restarted,n),t()};this.once(z.Restarted,n),this.once(z.Disconnected,r)}),this.updateAndEmitDCBufferStatus=e=>{if(e===K.RELIABLE){let t=this.dataChannelForKind(e);t&&this.reliableMessageBuffer.alignBufferedAmount(t.bufferedAmount)}let t=this.isBufferStatusLow(e);t!==void 0&&t!==this.dcBufferStatus.get(e)&&(this.dcBufferStatus.set(e,t),this.emit(z.DCBufferStatusChanged,t,e))},this.isBufferStatusLow=e=>{let t=this.dataChannelForKind(e);if(t)return t.bufferedAmount<=t.bufferedAmountLowThreshold},this.handleBrowserOnLine=()=>N(this,void 0,void 0,function*(){this.url&&(yield fetch(Iu(this.url),{method:`HEAD`}).then(e=>e.ok).catch(()=>!1))&&(this.log.info(`detected network reconnected`),(this.client.currentState===W.RECONNECTING||this.isWaitingForNetworkReconnect&&this.client.currentState===W.CONNECTED)&&(this.clearReconnectTimeout(),this.attemptReconnect(ma.RR_SIGNAL_DISCONNECTED),this.isWaitingForNetworkReconnect=!1))}),this.handleBrowserOffline=()=>N(this,void 0,void 0,function*(){if(this.url)try{yield Promise.race([fetch(Iu(this.url),{method:`HEAD`}),Ql(4e3).then(()=>Promise.reject())])}catch{window.navigator.onLine===!1&&(this.log.info(`detected network interruption`),this.isWaitingForNetworkReconnect=!0)}}),this.log=Ts(e.loggerName??ws.Engine),this.loggerOptions={loggerName:e.loggerName,loggerContextCb:()=>this.logContext},this.client=new Bd(void 0,this.loggerOptions),this.client.signalLatency=this.options.expSignalLatency,this.reconnectPolicy=this.options.reconnectPolicy,this.closingLock=new ur,this.dataProcessLock=new ur,this.dcBufferStatus=new Map([[K.RELIABLE,!0],[K.LOSSY,!0],[K.DATA_TRACK_LOSSY,!0]]),this.client.onParticipantUpdate=e=>this.emit(z.ParticipantUpdate,e),this.client.onConnectionQuality=e=>this.emit(z.ConnectionQualityUpdate,e),this.client.onRoomUpdate=e=>this.emit(z.RoomUpdate,e),this.client.onSubscriptionError=e=>this.emit(z.SubscriptionError,e),this.client.onSubscriptionPermissionUpdate=e=>this.emit(z.SubscriptionPermissionUpdate,e),this.client.onSpeakersChanged=e=>this.emit(z.SpeakersChanged,e),this.client.onStreamStateUpdate=e=>this.emit(z.StreamStateChanged,e),this.client.onRequestResponse=e=>this.emit(z.SignalRequestResponse,e),this.client.onParticipantUpdate=e=>this.emit(z.ParticipantUpdate,e),this.client.onJoined=e=>this.emit(z.Joined,e)}get logContext(){return{room:this.latestJoinResponse?.room?.name,roomID:this.latestJoinResponse?.room?.sid,participant:this.latestJoinResponse?.participant?.identity,participantID:this.participantSid}}join(e,t,n,r){return N(this,arguments,void 0,function(e,t,n,r){var i=this;let a=arguments.length>4&&arguments[4]!==void 0?arguments[4]:!1;return function*(){var o;i._isNewlyCreated=!1,i.url=e,i.token=t,i.signalOpts=n,i.maxJoinAttempts=n.maxRetries;try{i.joinAttempts+=1,i.setupSignalClientCallbacks();let s;if(!a&&$u()){i.pcManager||(yield i.configure(),i.createDataChannels(),i.addMediaSections(_p,vp));let e=yield i.pcManager?.publisher.createInitialOffer();e&&(s=Hd(e.offer,e.offerId))}if(r?.aborted)throw F.cancelled(`Connection aborted`);let c=yield i.client.join(e,t,n,r,a,s);return i._isClosed=!1,i.latestJoinResponse=c,i.participantSid=c.participant?.sid,i.subscriberPrimary=c.subscriberPrimary,!a&&$u()?(o=i.pcManager)==null||o.updateConfiguration(i.makeRTCConfiguration(c)):(i.pcManager||(yield i.configure(c,!a)),(!i.subscriberPrimary||c.fastPublish)&&i.negotiate().catch(e=>{M.error(e,i.logContext)})),i.registerOnLineListener(),i.clientConfiguration=c.clientConfiguration,i.emit(z.SignalConnected,c),c}catch(o){if(o instanceof F){if(o.reason===P.ServerUnreachable){if(i.log.warn(`Couldn't connect to server, attempt ${i.joinAttempts} of ${i.maxJoinAttempts}`,i.logContext),i.joinAttempts<i.maxJoinAttempts)return i.join(e,t,n,r,a)}else if(o.reason===P.ServiceNotFound)return i.log.warn(`Initial connection failed: ${o.message} – Retrying`),i.join(e,t,n,r,!0)}throw o}}()})}close(){return N(this,void 0,void 0,function*(){let e=yield this.closingLock.lock();if(this.isClosed){e();return}try{this._isClosed=!0,this.joinAttempts=0,this.emit(z.Closing),this.removeAllListeners(),this.deregisterOnLineListener(),this.clearPendingReconnect(),this.cleanupLossyDataStats(),yield this.cleanupPeerConnections(),yield this.cleanupClient()}finally{e()}})}cleanupPeerConnections(){return N(this,void 0,void 0,function*(){yield this.pcManager?.close(),this.pcManager=void 0;let e=e=>{e&&(e.close(),e.onbufferedamountlow=null,e.onclose=null,e.onclosing=null,e.onerror=null,e.onmessage=null,e.onopen=null)};e(this.lossyDC),e(this.lossyDCSub),e(this.reliableDC),e(this.reliableDCSub),e(this.dataTrackDC),e(this.dataTrackDCSub),this.lossyDC=void 0,this.lossyDCSub=void 0,this.reliableDC=void 0,this.reliableDCSub=void 0,this.dataTrackDC=void 0,this.dataTrackDCSub=void 0,this.reliableMessageBuffer=new Gd,this.reliableDataSequence=1,this.reliableReceivedState.clear()})}cleanupLossyDataStats(){this.lossyDataStatByterate=0,this.lossyDataStatCurrentBytes=0,this.lossyDataStatInterval&&=(clearInterval(this.lossyDataStatInterval),void 0),this.lossyDataDropCount=0}cleanupClient(){return N(this,void 0,void 0,function*(){yield this.client.close(),this.client.resetCallbacks()})}addTrack(e){if(this.pendingTrackResolvers[e.cid])throw new cl(`a track with the same ID has already been published`);return new Promise((t,n)=>{let r=setTimeout(()=>{delete this.pendingTrackResolvers[e.cid],n(F.timeout(`publication of local track timed out, no response from server`))},1e4);this.pendingTrackResolvers[e.cid]={resolve:e=>{clearTimeout(r),t(e)},reject:()=>{clearTimeout(r),n(Error(`Cancelled publication by calling unpublish`))}},this.client.sendAddTrack(e)})}removeTrack(e){if(e.track&&this.pendingTrackResolvers[e.track.id]){let{reject:t}=this.pendingTrackResolvers[e.track.id];t&&t(),delete this.pendingTrackResolvers[e.track.id]}try{return this.pcManager.removeTrack(e),!0}catch(e){this.log.warn(`failed to remove track`,Object.assign(Object.assign({},this.logContext),{error:e}))}return!1}updateMuteStatus(e,t){this.client.sendMuteTrack(e,t)}get dataSubscriberReadyState(){return this.reliableDCSub?.readyState}getConnectedServerAddress(){return N(this,void 0,void 0,function*(){return this.pcManager?.getConnectedAddress()})}setRegionUrlProvider(e){this.regionUrlProvider=e}configure(e,t){return N(this,void 0,void 0,function*(){if(!(this.pcManager&&this.pcManager.currentState!==G.NEW)){if(e){this.participantSid=e.participant?.sid;let n=this.makeRTCConfiguration(e);this.pcManager=new Sf(t?`publisher-only`:e.subscriberPrimary?`subscriber-primary`:`publisher-primary`,this.loggerOptions,n)}else{let e=this.makeRTCConfiguration();this.pcManager=new Sf(`publisher-only`,this.loggerOptions,e)}this.emit(z.TransportsCreated,this.pcManager.publisher,this.pcManager.subscriber),this.pcManager.onIceCandidate=(e,t)=>{this.client.sendIceCandidate(e,t)},this.pcManager.onPublisherOffer=(e,t)=>{this.client.sendOffer(e,t)},this.pcManager.onDataChannel=this.handleDataChannel,this.pcManager.onStateChange=(e,t,n)=>N(this,void 0,void 0,function*(){if(this.log.debug(`primary PC state changed ${e}`,this.logContext),[`closed`,`disconnected`,`failed`].includes(t)&&(this.publisherConnectionPromise=void 0),e===G.CONNECTED){let e=this.pcState===yp.New;this.pcState=yp.Connected,e&&this.emit(z.Connected,this.latestJoinResponse)}else e===G.FAILED&&(this.pcState===yp.Connected||this.pcState===yp.Reconnecting)&&(this.pcState=yp.Disconnected,this.handleDisconnect(`peerconnection failed`,n===`failed`?ma.RR_SUBSCRIBER_FAILED:ma.RR_PUBLISHER_FAILED));let r=this.client.isDisconnected||this.client.currentState===W.RECONNECTING,i=[G.FAILED,G.CLOSING,G.CLOSED].includes(e);r&&i&&!this._isClosed&&this.emit(z.Offline)}),this.pcManager.onTrack=e=>{e.streams.length!==0&&this.emit(z.MediaTrackAdded,e.track,e.streams[0],e.receiver)}}})}setupSignalClientCallbacks(){this.client.onAnswer=(e,t,n)=>N(this,void 0,void 0,function*(){this.pcManager&&(this.log.debug(`received server answer`,Object.assign(Object.assign({},this.logContext),{RTCSdpType:e.type,sdp:e.sdp,midToTrackId:n})),this.midToTrackId=n,yield this.pcManager.setPublisherAnswer(e,t))}),this.client.onTrickle=(e,t)=>{this.pcManager&&(this.log.debug(`got ICE candidate from peer`,Object.assign(Object.assign({},this.logContext),{candidate:e,target:t})),this.pcManager.addIceCandidate(e,t))},this.client.onOffer=(e,t,n)=>N(this,void 0,void 0,function*(){if(this.latestRemoteOfferId=t,!this.pcManager)return;this.midToTrackId=n;let r=yield this.pcManager.createSubscriberAnswerFromOffer(e,t);r&&this.client.sendAnswer(r,t)}),this.client.onLocalTrackPublished=e=>{if(this.log.debug(`received trackPublishedResponse`,Object.assign(Object.assign({},this.logContext),{cid:e.cid,track:e.track?.sid})),!this.pendingTrackResolvers[e.cid]){this.log.error(`missing track resolver for ${e.cid}`,Object.assign(Object.assign({},this.logContext),{cid:e.cid}));return}let{resolve:t}=this.pendingTrackResolvers[e.cid];delete this.pendingTrackResolvers[e.cid],t(e.track)},this.client.onLocalTrackUnpublished=e=>{this.emit(z.LocalTrackUnpublished,e)},this.client.onLocalTrackSubscribed=e=>{this.emit(z.LocalTrackSubscribed,e)},this.client.onTokenRefresh=e=>{var t;this.token=e,(t=this.regionUrlProvider)==null||t.updateToken(e)},this.client.onRemoteMuteChanged=(e,t)=>{this.emit(z.RemoteMute,e,t)},this.client.onSubscribedQualityUpdate=e=>{this.emit(z.SubscribedQualityUpdate,e)},this.client.onRoomMoved=e=>{this.participantSid=e.participant?.sid,this.latestJoinResponse&&(this.latestJoinResponse.room=e.room),this.emit(z.RoomMoved,e)},this.client.onMediaSectionsRequirement=e=>{this.addMediaSections(e.numAudios,e.numVideos),this.negotiate()},this.client.onPublishDataTrackResponse=e=>{this.emit(z.PublishDataTrackResponse,e)},this.client.onUnPublishDataTrackResponse=e=>{this.emit(z.UnPublishDataTrackResponse,e)},this.client.onDataTrackSubscriberHandles=e=>{this.emit(z.DataTrackSubscriberHandles,e)},this.client.onClose=()=>{this.handleDisconnect(`signal`,ma.RR_SIGNAL_DISCONNECTED)},this.client.onLeave=e=>{switch(this.log.debug(`client leave request`,Object.assign(Object.assign({},this.logContext),{reason:e?.reason})),e.regions&&this.regionUrlProvider&&(this.log.debug(`updating regions`,this.logContext),this.regionUrlProvider.setServerReportedRegions({updatedAtInMs:Date.now(),maxAgeInMs:Cf,regionSettings:e.regions})),e.action){case Io.DISCONNECT:this.emit(z.Disconnected,e?.reason),this.close();break;case Io.RECONNECT:this.fullReconnectOnNext=!0,this.handleDisconnect(pp);break;case Io.RESUME:this.handleDisconnect(pp)}}}makeRTCConfiguration(e){let t=Object.assign({},this.rtcConfig);if(this.signalOpts?.e2eeEnabled&&(this.log.debug(`E2EE - setting up transports with insertable streams`,this.logContext),t.encodedInsertableStreams=!0),t.sdpSemantics=`unified-plan`,t.continualGatheringPolicy=`gather_continually`,!e)return t;if(e.iceServers&&!t.iceServers){let n=[];e.iceServers.forEach(e=>{let t={urls:e.urls};e.username&&(t.username=e.username),e.credential&&(t.credential=e.credential),n.push(t)}),t.iceServers=n}return e.clientConfiguration&&e.clientConfiguration.forceRelay===fa.ENABLED&&(t.iceTransportPolicy=`relay`),t}addMediaSections(e,t){var n,r;let i={direction:`recvonly`};for(let t=0;t<e;t++)(n=this.pcManager)==null||n.addPublisherTransceiverOfKind(`audio`,i);for(let e=0;e<t;e++)(r=this.pcManager)==null||r.addPublisherTransceiverOfKind(`video`,i)}createDataChannels(){this.pcManager&&(this.lossyDC&&(this.lossyDC.onmessage=null,this.lossyDC.onerror=null),this.reliableDC&&(this.reliableDC.onmessage=null,this.reliableDC.onerror=null),this.dataTrackDC&&(this.dataTrackDC.onmessage=null,this.dataTrackDC.onerror=null),this.lossyDC=this.pcManager.createPublisherDataChannel(lp,{ordered:!1,maxRetransmits:0}),this.reliableDC=this.pcManager.createPublisherDataChannel(up,{ordered:!0}),this.dataTrackDC=this.pcManager.createPublisherDataChannel(dp,{ordered:!1,maxRetransmits:0}),this.lossyDC.onmessage=this.handleDataMessage,this.reliableDC.onmessage=this.handleDataMessage,this.dataTrackDC.onmessage=this.handleDataTrackMessage,this.lossyDC.onerror=this.handleDataError,this.reliableDC.onerror=this.handleDataError,this.dataTrackDC.onerror=this.handleDataError,this.lossyDC.bufferedAmountLowThreshold=65535,this.reliableDC.bufferedAmountLowThreshold=65535,this.dataTrackDC.bufferedAmountLowThreshold=65535,this.lossyDC.onbufferedamountlow=()=>this.handleBufferedAmountLow(K.LOSSY),this.reliableDC.onbufferedamountlow=()=>this.handleBufferedAmountLow(K.RELIABLE),this.dataTrackDC.onbufferedamountlow=()=>this.handleBufferedAmountLow(K.DATA_TRACK_LOSSY),this.cleanupLossyDataStats(),this.lossyDataStatInterval=setInterval(()=>{this.lossyDataStatByterate=this.lossyDataStatCurrentBytes,this.lossyDataStatCurrentBytes=0;let e=this.dataChannelForKind(K.LOSSY);if(e){let t=this.lossyDataStatByterate/10;e.bufferedAmountLowThreshold=Math.min(Math.max(t,hp),gp)}},1e3))}createSender(e,t,n){return N(this,void 0,void 0,function*(){if($l())return yield this.createTransceiverRTCRtpSender(e,t,n);if(eu())return this.log.warn(`using add-track fallback`,this.logContext),yield this.createRTCRtpSender(e.mediaStreamTrack);throw new I(`Required webRTC APIs not supported on this device`)})}createSimulcastSender(e,t,n,r){return N(this,void 0,void 0,function*(){if($l())return this.createSimulcastTransceiverSender(e,t,n,r);if(eu())return this.log.debug(`using add-track fallback`,this.logContext),this.createRTCRtpSender(e.mediaStreamTrack);throw new I(`Cannot stream on this device`)})}createTransceiverRTCRtpSender(e,t,n){return N(this,void 0,void 0,function*(){if(!this.pcManager)throw new I(`publisher is closed`);let r=[];e.mediaStream&&r.push(e.mediaStream),Wu(e)&&(e.codec=t.videoCodec);let i={direction:`sendonly`,streams:r};return n&&(i.sendEncodings=n),(yield this.pcManager.addPublisherTransceiver(e.mediaStreamTrack,i)).sender})}createSimulcastTransceiverSender(e,t,n,r){return N(this,void 0,void 0,function*(){if(!this.pcManager)throw new I(`publisher is closed`);let i={direction:`sendonly`};r&&(i.sendEncodings=r);let a=yield this.pcManager.addPublisherTransceiver(t.mediaStreamTrack,i);if(n.videoCodec)return e.setSimulcastTrackSender(n.videoCodec,a.sender),a.sender})}createRTCRtpSender(e){return N(this,void 0,void 0,function*(){if(!this.pcManager)throw new I(`publisher is closed`);return this.pcManager.addPublisherTrack(e)})}attemptReconnect(e){return N(this,void 0,void 0,function*(){if(!this._isClosed){if(this.attemptingReconnect){M.warn(`already attempting reconnect, returning early`,this.logContext);return}(this.clientConfiguration?.resumeConnection===fa.DISABLED||(this.pcManager?.currentState??G.NEW)===G.NEW)&&(this.fullReconnectOnNext=!0);try{this.attemptingReconnect=!0,this.fullReconnectOnNext?yield this.restartConnection():yield this.resumeConnection(e),this.clearPendingReconnect(),this.fullReconnectOnNext=!1}catch(e){this.reconnectAttempts+=1;let t=!0;e instanceof I?(this.log.debug(`received unrecoverable error`,Object.assign(Object.assign({},this.logContext),{error:e})),t=!1):e instanceof hl||(this.fullReconnectOnNext=!0),t?this.handleDisconnect(`reconnect`,ma.RR_UNKNOWN):(this.log.info(`could not recover connection after ${this.reconnectAttempts} attempts, ${Date.now()-this.reconnectStart}ms. giving up`,this.logContext),this.emit(z.Disconnected),yield this.close())}finally{this.attemptingReconnect=!1}}})}getNextRetryDelay(e){try{return this.reconnectPolicy.nextRetryDelayInMs(e)}catch(e){this.log.warn(`encountered error in reconnect policy`,Object.assign(Object.assign({},this.logContext),{error:e}))}return null}restartConnection(e){return N(this,void 0,void 0,function*(){var t,n;try{if(!this.url||!this.token)throw new I(`could not reconnect, url or token not saved`);this.log.info(`reconnecting, attempt: ${this.reconnectAttempts}`,this.logContext),this.emit(z.Restarting),this.client.isDisconnected||(yield this.client.sendLeave()),yield this.cleanupPeerConnections(),yield this.cleanupClient();let n;try{if(!this.signalOpts)throw this.log.warn(`attempted connection restart, without signal options present`,this.logContext),new hl;n=yield this.join(e??this.url,this.token,this.signalOpts,void 0,!this.options.singlePeerConnection)}catch(e){throw e instanceof F&&e.reason===P.NotAllowed?new I(`could not reconnect, token might be expired`):new hl}if(this.shouldFailNext)throw this.shouldFailNext=!1,Error(`simulated failure`);if(this.client.setReconnected(),this.emit(z.SignalRestarted,n),yield this.waitForPCReconnected(),this.client.currentState!==W.CONNECTED)throw new hl(`Signal connection got severed during reconnect`);(t=this.regionUrlProvider)==null||t.resetAttempts(),this.emit(z.Restarted)}catch(e){let t=yield this.regionUrlProvider?.getNextBestRegionUrl();if(t){yield this.restartConnection(t);return}else throw(n=this.regionUrlProvider)==null||n.resetAttempts(),e}})}resumeConnection(e){return N(this,void 0,void 0,function*(){if(!this.url||!this.token)throw new I(`could not reconnect, url or token not saved`);if(!this.pcManager)throw new I(`publisher and subscriber connections unset`);this.log.info(`resuming signal connection, attempt ${this.reconnectAttempts}`,this.logContext),this.emit(z.Resuming);let t;try{this.setupSignalClientCallbacks(),t=yield this.client.reconnect(this.url,this.token,this.participantSid,e)}catch(e){let t=``;throw e instanceof Error&&(t=e.message,this.log.error(e.message,Object.assign(Object.assign({},this.logContext),{error:e}))),e instanceof F&&e.reason===P.NotAllowed?new I(`could not reconnect, token might be expired`):e instanceof F&&e.reason===P.LeaveRequest?e:new hl(t)}if(this.emit(z.SignalResumed),t){let e=this.makeRTCConfiguration(t);this.pcManager.updateConfiguration(e),this.latestJoinResponse&&(this.latestJoinResponse.serverInfo=t.serverInfo)}else this.log.warn(`Did not receive reconnect response`,this.logContext);if(this.shouldFailNext)throw this.shouldFailNext=!1,Error(`simulated failure`);if(yield this.pcManager.triggerIceRestart(),yield this.waitForPCReconnected(),this.client.currentState!==W.CONNECTED)throw new hl(`Signal connection got severed during reconnect`);this.client.setReconnected(),this.reliableDC?.readyState===`open`&&this.reliableDC.id===null&&this.createDataChannels(),t?.lastMessageSeq&&this.resendReliableMessagesForResume(t.lastMessageSeq),this.emit(z.Resumed)})}waitForPCInitialConnection(e,t){return N(this,void 0,void 0,function*(){if(!this.pcManager)throw new I(`PC manager is closed`);yield this.pcManager.ensurePCTransportConnection(t,e)})}waitForPCReconnected(){return N(this,void 0,void 0,function*(){this.pcState=yp.Reconnecting,this.log.debug(`waiting for peer connection to reconnect`,this.logContext);try{if(yield Ql(fp),!this.pcManager)throw new I(`PC manager is closed`);yield this.pcManager.ensurePCTransportConnection(void 0,this.peerConnectionTimeout),this.pcState=yp.Connected}catch(e){throw this.pcState=yp.Disconnected,F.internal(`could not establish PC connection, ${e.message}`)}})}publishRpcResponse(e,t,n,r){return N(this,void 0,void 0,function*(){let i=new Aa({destinationIdentities:[e],kind:ja.RELIABLE,value:{case:`rpcResponse`,value:new Ua({requestId:t,value:r?{case:`error`,value:r.toProto()}:{case:`payload`,value:n??``}})}});yield this.sendDataPacket(i,K.RELIABLE)})}publishRpcAck(e,t){return N(this,void 0,void 0,function*(){let n=new Aa({destinationIdentities:[e],kind:ja.RELIABLE,value:{case:`rpcAck`,value:new Ha({requestId:t})}});yield this.sendDataPacket(n,K.RELIABLE)})}sendDataPacket(e,t){return N(this,void 0,void 0,function*(){if(yield this.ensurePublisherConnected(t),this.e2eeManager&&this.e2eeManager.isDataChannelEncryptionEnabled){let t=hd(e);if(t){let n=yield this.e2eeManager.encryptData(t.toBinary());e.value={case:`encryptedPacket`,value:new Ma({encryptedValue:n.payload,iv:n.iv,keyIndex:n.keyIndex})}}}t===K.RELIABLE&&(e.sequence=this.reliableDataSequence,this.reliableDataSequence+=1);let n=e.toBinary();switch(t){case K.LOSSY:case K.DATA_TRACK_LOSSY:return this.sendLossyBytes(n,t);case K.RELIABLE:let r=this.dataChannelForKind(t);if(r){if(yield this.waitForBufferStatusLow(t),this.reliableMessageBuffer.push({data:n,sequence:e.sequence}),this.attemptingReconnect)return;r.send(n)}this.updateAndEmitDCBufferStatus(t);break}})}sendLossyBytes(e,t){return N(this,arguments,void 0,function(e,t){var n=this;let r=arguments.length>2&&arguments[2]!==void 0?arguments[2]:`drop`;return function*(){yield n.ensurePublisherConnected(t);let i=n.dataChannelForKind(t);if(i){if(!n.isBufferStatusLow(t))switch(r){case`wait`:yield n.waitForBufferStatusLow(t);break;case`drop`:n.lossyDataDropCount+=1,n.lossyDataDropCount%100==0&&n.log.warn(`dropping lossy data channel messages, total dropped: ${n.lossyDataDropCount}`,n.logContext);return}if(n.lossyDataStatCurrentBytes+=e.byteLength,n.attemptingReconnect)return;i.send(e)}n.updateAndEmitDCBufferStatus(t)}()})}resendReliableMessagesForResume(e){return N(this,void 0,void 0,function*(){yield this.ensurePublisherConnected(K.RELIABLE);let t=this.dataChannelForKind(K.RELIABLE);t&&(this.reliableMessageBuffer.popToSequence(e),this.reliableMessageBuffer.getAll().forEach(e=>{t.send(e.data)})),this.updateAndEmitDCBufferStatus(K.RELIABLE)})}waitForBufferStatusLow(e){return new Zc((t,n)=>N(this,void 0,void 0,function*(){if(this.isBufferStatusLow(e))t();else{let r=()=>n(new I(`engine closed`));for(this.once(z.Closing,r);!this.dcBufferStatus.get(e);)yield Ql(10);this.off(z.Closing,r),t()}}))}ensureDataTransportConnected(e){return N(this,arguments,void 0,function(e){var t=this;let n=arguments.length>1&&arguments[1]!==void 0?arguments[1]:this.subscriberPrimary;return function*(){if(!t.pcManager)throw new I(`PC manager is closed`);let r=n?t.pcManager.subscriber:t.pcManager.publisher,i=n?`Subscriber`:`Publisher`;if(!r)throw F.internal(`${i} connection not set`);let a=!1;if(!n&&!t.dataChannelForKind(e,n)&&(t.createDataChannels(),a=!0),!a&&!n&&!t.pcManager.publisher.isICEConnected&&t.pcManager.publisher.getICEConnectionState()!==`checking`&&(a=!0),a&&t.negotiate().catch(e=>{M.error(e,t.logContext)}),t.dataChannelForKind(e,n)?.readyState===`open`)return;let o=new Date().getTime()+t.peerConnectionTimeout;for(;new Date().getTime()<o;){if(r.isICEConnected&&t.dataChannelForKind(e,n)?.readyState===`open`)return;yield Ql(50)}throw F.internal(`could not establish ${i} connection, state: ${r.getICEConnectionState()}`)}()})}ensurePublisherConnected(e){return N(this,void 0,void 0,function*(){this.publisherConnectionPromise||=this.ensureDataTransportConnected(e,!1),yield this.publisherConnectionPromise})}verifyTransport(){return!(!this.pcManager||![G.CONNECTING,G.CONNECTED].includes(this.pcManager.currentState)||!this.client.ws||this.client.ws.readyState===WebSocket.CLOSED)}negotiate(){return N(this,void 0,void 0,function*(){return new Zc((e,t)=>N(this,void 0,void 0,function*(){if(!this.pcManager){t(new ul(`PC manager is closed`));return}this.pcManager.requirePublisher(),this.pcManager.publisher.getTransceivers().length==0&&!this.lossyDC&&!this.reliableDC&&!this.dataTrackDC&&this.createDataChannels();let n=new AbortController,r=()=>{n.abort(),this.log.debug(`engine disconnected while negotiation was ongoing`,this.logContext),e()};this.isClosed&&t(new ul(`cannot negotiate on closed engine`)),this.on(z.Closing,r),this.on(z.Restarting,r),this.pcManager.publisher.once(uf.RTPVideoPayloadTypes,e=>{let t=new Map;e.forEach(e=>{let n=e.codec.toLowerCase();Nu(n)&&t.set(e.payload,n)}),this.emit(z.RTPVideoMapUpdate,t)});try{yield this.pcManager.negotiate(n),e()}catch(r){if(n.signal.aborted){e();return}r instanceof ul&&(this.fullReconnectOnNext=!0),this.handleDisconnect(`negotiation`,ma.RR_UNKNOWN),r instanceof Error?t(r):t(Error(String(r)))}finally{this.off(z.Closing,r),this.off(z.Restarting,r)}}))})}dataChannelForKind(e,t){switch(e){case K.RELIABLE:return t?this.reliableDCSub:this.reliableDC;case K.LOSSY:return t?this.lossyDCSub:this.lossyDC;case K.DATA_TRACK_LOSSY:return t?this.dataTrackDCSub:this.dataTrackDC}}sendSyncState(e,t,n){if(!this.pcManager){this.log.warn(`sync state cannot be sent without peer connection setup`,this.logContext);return}let r=this.pcManager.publisher.getLocalDescription(),i=this.pcManager.publisher.getRemoteDescription(),a=this.pcManager.subscriber?.getRemoteDescription(),o=this.pcManager.subscriber?.getLocalDescription(),s=this.signalOpts?.autoSubscribe??!0,c=[],l=[];e.forEach(e=>{e.isDesired!==s&&c.push(e.trackSid),e.isEnabled||l.push(e.trackSid)}),this.client.sendSyncState(new es({answer:this.pcManager.mode===`publisher-only`?i?Hd({sdp:i.sdp,type:i.type}):void 0:o?Hd({sdp:o.sdp,type:o.type}):void 0,offer:this.pcManager.mode===`publisher-only`?r?Hd({sdp:r.sdp,type:r.type}):void 0:a?Hd({sdp:a.sdp,type:a.type}):void 0,subscription:new ko({trackSids:c,subscribe:!s,participantTracks:[]}),publishTracks:Ll(t),dataChannels:this.dataChannelsInfo(),trackSidsDisabled:l,datachannelReceiveStates:this.reliableReceivedState.map((e,t)=>new ts({publisherSid:t,lastSeq:e})),publishDataTracks:n.map(e=>new go({info:Nd.toProtobuf(e)}))}))}failNext(){this.shouldFailNext=!0}dataChannelsInfo(){let e=[],t=(t,n)=>{t?.id!==void 0&&t.id!==null&&e.push(new ns({label:t.label,id:t.id,target:n}))};return t(this.dataChannelForKind(K.LOSSY),so.PUBLISHER),t(this.dataChannelForKind(K.RELIABLE),so.PUBLISHER),t(this.dataChannelForKind(K.LOSSY,!0),so.SUBSCRIBER),t(this.dataChannelForKind(K.RELIABLE,!0),so.SUBSCRIBER),e}clearReconnectTimeout(){this.reconnectTimeout&&_l.clearTimeout(this.reconnectTimeout)}clearPendingReconnect(){this.clearReconnectTimeout(),this.reconnectAttempts=0}registerOnLineListener(){mu()&&(window.addEventListener(`online`,this.handleBrowserOnLine),window.addEventListener(`offline`,this.handleBrowserOffline))}deregisterOnLineListener(){mu()&&(window.removeEventListener(`online`,this.handleBrowserOnLine),window.removeEventListener(`offline`,this.handleBrowserOffline))}getTrackIdForReceiver(e){let t=this.pcManager?.getMidForReceiver(e);if(t){let e=Object.entries(this.midToTrackId).find(e=>{let[n]=e;return n===t});if(e)return e[1]}}};function xp(e,t){let n=e.participantIdentity?e.participantIdentity:t.participantIdentity;e.participantIdentity=n,t.participantIdentity=n;let r=e.destinationIdentities.length===0?t.destinationIdentities:e.destinationIdentities;e.destinationIdentities=r,t.destinationIdentities=r}var Sp=class{get info(){return this._info}validateBytesReceived(){let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:!1;if(!(typeof this.totalByteSize!=`number`||this.totalByteSize===0)){if(e&&this.bytesReceived<this.totalByteSize)throw new ml(`Not enough chunk(s) received - expected ${this.totalByteSize} bytes of data total, only received ${this.bytesReceived} bytes`,pl.Incomplete);if(this.bytesReceived>this.totalByteSize)throw new ml(`Extra chunk(s) received - expected ${this.totalByteSize} bytes of data total, received ${this.bytesReceived} bytes`,pl.LengthExceeded)}}constructor(e,t,n){this.reader=t,this.totalByteSize=n,this._info=e,this.bytesReceived=0}},Cp=class extends Sp{handleChunkReceived(e){var t;this.bytesReceived+=e.content.byteLength,this.validateBytesReceived();let n=this.totalByteSize?this.bytesReceived/this.totalByteSize:void 0;(t=this.onProgress)==null||t.call(this,n)}[Symbol.asyncIterator](){let e=this.reader.getReader();e.closed.catch(()=>{});let t=()=>{e.releaseLock(),this.signal=void 0};return{next:()=>N(this,void 0,void 0,function*(){try{let t=this.signal;if(t?.aborted)throw t.reason;let n=yield new Promise((n,r)=>{if(t){let i=()=>r(t.reason);t.addEventListener(`abort`,i,{once:!0}),e.read().then(n,r).finally(()=>{t.removeEventListener(`abort`,i)})}else e.read().then(n,r)});return n.done?(this.validateBytesReceived(!0),{done:!0,value:void 0}):(this.handleChunkReceived(n.value),{done:!1,value:n.value.content})}catch(e){throw t(),e}}),return(){return N(this,void 0,void 0,function*(){return t(),{done:!0,value:void 0}})}}}withAbortSignal(e){return this.signal=e,this}readAll(){return N(this,arguments,void 0,function(){var e=this;let t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};return function*(){var n,r,i,a;let o=new Set,s=t.signal?e.withAbortSignal(t.signal):e;try{for(var c=!0,l=Fs(s),u;u=yield l.next(),n=u.done,!n;c=!0){a=u.value,c=!1;let e=a;o.add(e)}}catch(e){r={error:e}}finally{try{!c&&!n&&(i=l.return)&&(yield i.call(l))}finally{if(r)throw r.error}}return Array.from(o)}()})}},wp=class extends Sp{constructor(e,t,n){super(e,t,n),this.receivedChunks=new Map}handleChunkReceived(e){var t;let n=Bu(e.chunkIndex),r=this.receivedChunks.get(n);if(r&&r.version>e.version)return;this.receivedChunks.set(n,e),this.bytesReceived+=e.content.byteLength,this.validateBytesReceived();let i=this.totalByteSize?this.bytesReceived/this.totalByteSize:void 0;(t=this.onProgress)==null||t.call(this,i)}[Symbol.asyncIterator](){let e=this.reader.getReader();e.closed.catch(()=>{});let t=new TextDecoder(`utf-8`,{fatal:!0}),n=this.signal,r=()=>{e.releaseLock(),this.signal=void 0};return{next:()=>N(this,void 0,void 0,function*(){try{if(n?.aborted)throw n.reason;let r=yield new Promise((t,r)=>{if(n){let i=()=>r(n.reason);n.addEventListener(`abort`,i,{once:!0}),e.read().then(t,r).finally(()=>{n.removeEventListener(`abort`,i)})}else e.read().then(t,r)});if(r.done)return this.validateBytesReceived(!0),{done:!0,value:void 0};{this.handleChunkReceived(r.value);let e;try{e=t.decode(r.value.content)}catch(e){throw new ml(`Cannot decode datastream chunk ${r.value.chunkIndex} as text: ${e}`,pl.DecodeFailed)}return{done:!1,value:e}}}catch(e){throw r(),e}}),return(){return N(this,void 0,void 0,function*(){return r(),{done:!0,value:void 0}})}}}withAbortSignal(e){return this.signal=e,this}readAll(){return N(this,arguments,void 0,function(){var e=this;let t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};return function*(){var n,r,i,a;let o=``,s=t.signal?e.withAbortSignal(t.signal):e;try{for(var c=!0,l=Fs(s),u;u=yield l.next(),n=u.done,!n;c=!0)a=u.value,c=!1,o+=a}catch(e){r={error:e}}finally{try{!c&&!n&&(i=l.return)&&(yield i.call(l))}finally{if(r)throw r.error}}return o}()})}},Tp=class{constructor(){this.log=M,this.byteStreamControllers=new Map,this.textStreamControllers=new Map,this.byteStreamHandlers=new Map,this.textStreamHandlers=new Map}registerTextStreamHandler(e,t){if(this.textStreamHandlers.has(e))throw new ml(`A text stream handler for topic "${e}" has already been set.`,pl.HandlerAlreadyRegistered);this.textStreamHandlers.set(e,t)}unregisterTextStreamHandler(e){this.textStreamHandlers.delete(e)}registerByteStreamHandler(e,t){if(this.byteStreamHandlers.has(e))throw new ml(`A byte stream handler for topic "${e}" has already been set.`,pl.HandlerAlreadyRegistered);this.byteStreamHandlers.set(e,t)}unregisterByteStreamHandler(e){this.byteStreamHandlers.delete(e)}clearControllers(){this.byteStreamControllers.clear(),this.textStreamControllers.clear()}validateParticipantHasNoActiveDataStreams(e){let t=Array.from(this.textStreamControllers.entries()).filter(t=>t[1].sendingParticipantIdentity===e),n=Array.from(this.byteStreamControllers.entries()).filter(t=>t[1].sendingParticipantIdentity===e);if(t.length>0||n.length>0){let r=new ml(`Participant ${e} unexpectedly disconnected in the middle of sending data`,pl.AbnormalEnd);for(let[e,t]of n)t.controller.error(r),this.byteStreamControllers.delete(e);for(let[e,n]of t)n.controller.error(r),this.textStreamControllers.delete(e)}}handleDataStreamPacket(e,t){return N(this,void 0,void 0,function*(){switch(e.value.case){case`streamHeader`:return this.handleStreamHeader(e.value.value,e.participantIdentity,t);case`streamChunk`:return this.handleStreamChunk(e.value.value,t);case`streamTrailer`:return this.handleStreamTrailer(e.value.value,t);default:throw Error(`DataPacket of value "${e.value.case}" is not data stream related!`)}})}handleStreamHeader(e,t,n){return N(this,void 0,void 0,function*(){if(e.contentHeader.case===`byteHeader`){let r=this.byteStreamHandlers.get(e.topic);if(!r){this.log.debug(`ignoring incoming byte stream due to no handler for topic`,e.topic);return}let i,a={id:e.streamId,name:e.contentHeader.value.name??`unknown`,mimeType:e.mimeType,size:e.totalLength?Number(e.totalLength):void 0,topic:e.topic,timestamp:Bu(e.timestamp),attributes:e.attributes,encryptionType:n};r(new Cp(a,new ReadableStream({start:n=>{if(i=n,this.textStreamControllers.has(e.streamId))throw new ml(`A data stream read is already in progress for a stream with id ${e.streamId}.`,pl.AlreadyOpened);this.byteStreamControllers.set(e.streamId,{info:a,controller:i,startTime:Date.now(),sendingParticipantIdentity:t})}}),Bu(e.totalLength)),{identity:t})}else if(e.contentHeader.case===`textHeader`){let r=this.textStreamHandlers.get(e.topic);if(!r){this.log.debug(`ignoring incoming text stream due to no handler for topic`,e.topic);return}let i,a={id:e.streamId,mimeType:e.mimeType,size:e.totalLength?Number(e.totalLength):void 0,topic:e.topic,timestamp:Number(e.timestamp),attributes:e.attributes,encryptionType:n,attachedStreamIds:e.contentHeader.value.attachedStreamIds};r(new wp(a,new ReadableStream({start:n=>{if(i=n,this.textStreamControllers.has(e.streamId))throw new ml(`A data stream read is already in progress for a stream with id ${e.streamId}.`,pl.AlreadyOpened);this.textStreamControllers.set(e.streamId,{info:a,controller:i,startTime:Date.now(),sendingParticipantIdentity:t})}}),Bu(e.totalLength)),{identity:t})}})}handleStreamChunk(e,t){let n=this.byteStreamControllers.get(e.streamId);n&&(n.info.encryptionType===t?e.content.length>0&&n.controller.enqueue(e):(n.controller.error(new ml(`Encryption type mismatch for stream ${e.streamId}. Expected ${t}, got ${n.info.encryptionType}`,pl.EncryptionTypeMismatch)),this.byteStreamControllers.delete(e.streamId)));let r=this.textStreamControllers.get(e.streamId);r&&(r.info.encryptionType===t?e.content.length>0&&r.controller.enqueue(e):(r.controller.error(new ml(`Encryption type mismatch for stream ${e.streamId}. Expected ${t}, got ${r.info.encryptionType}`,pl.EncryptionTypeMismatch)),this.textStreamControllers.delete(e.streamId)))}handleStreamTrailer(e,t){let n=this.textStreamControllers.get(e.streamId);n&&(n.info.encryptionType===t?(n.info.attributes=Object.assign(Object.assign({},n.info.attributes),e.attributes),n.controller.close(),this.textStreamControllers.delete(e.streamId)):n.controller.error(new ml(`Encryption type mismatch for stream ${e.streamId}. Expected ${t}, got ${n.info.encryptionType}`,pl.EncryptionTypeMismatch)));let r=this.byteStreamControllers.get(e.streamId);r&&(r.info.encryptionType===t?(r.info.attributes=Object.assign(Object.assign({},r.info.attributes),e.attributes),r.controller.close()):r.controller.error(new ml(`Encryption type mismatch for stream ${e.streamId}. Expected ${t}, got ${r.info.encryptionType}`,pl.EncryptionTypeMismatch)),this.byteStreamControllers.delete(e.streamId))}},Ep=class{constructor(e,t,n){this.writableStream=e,this.defaultWriter=e.getWriter(),this.onClose=n,this.info=t}write(e){return this.defaultWriter.write(e)}close(){return N(this,void 0,void 0,function*(){var e;yield this.defaultWriter.close(),this.defaultWriter.releaseLock(),(e=this.onClose)==null||e.call(this)})}},Dp=class extends Ep{},Op=class extends Ep{},kp=15e3,Ap=class{constructor(e,t){this.engine=e,this.log=t}setupEngine(e){this.engine=e}sendText(e,t){return N(this,void 0,void 0,function*(){let n=crypto.randomUUID(),r=new TextEncoder().encode(e).byteLength,i=(t?.attachments)?.map(()=>crypto.randomUUID()),a=Array(i?i.length+1:1).fill(0),o=(e,n)=>{var r;a[n]=e;let i=a.reduce((e,t)=>e+t,0);(r=t?.onProgress)==null||r.call(t,i)},s=yield this.streamText({streamId:n,totalSize:r,destinationIdentities:t?.destinationIdentities,topic:t?.topic,attachedStreamIds:i,attributes:t?.attributes});return yield s.write(e),o(1,0),yield s.close(),t?.attachments&&i&&(yield Promise.all(t.attachments.map((e,n)=>N(this,void 0,void 0,function*(){return this._sendFile(i[n],e,{topic:t.topic,mimeType:e.type,onProgress:e=>{o(e,n+1)}})})))),s.info})}streamText(e){return N(this,void 0,void 0,function*(){let t=e?.streamId??crypto.randomUUID(),n={id:t,mimeType:`text/plain`,timestamp:Date.now(),topic:e?.topic??``,size:e?.totalSize,attributes:e?.attributes,encryptionType:this.engine.e2eeManager?.isDataChannelEncryptionEnabled?j.GCM:j.NONE,attachedStreamIds:e?.attachedStreamIds},r=new ro({streamId:t,mimeType:n.mimeType,topic:n.topic,timestamp:Vu(n.timestamp),totalLength:Vu(n.size),attributes:n.attributes,contentHeader:{case:`textHeader`,value:new to({version:e?.version,attachedStreamIds:n.attachedStreamIds,replyToStreamId:e?.replyToStreamId,operationType:e?.type===`update`?eo.UPDATE:eo.CREATE})}}),i=e?.destinationIdentities,a=new Aa({destinationIdentities:i,value:{case:`streamHeader`,value:r}});yield this.engine.sendDataPacket(a,K.RELIABLE);let o=0,s=this.engine,c=new WritableStream({write(e){return N(this,void 0,void 0,function*(){for(let n of Zu(e,kp)){let e=new Aa({destinationIdentities:i,value:{case:`streamChunk`,value:new io({content:n,streamId:t,chunkIndex:Vu(o)})}});yield s.sendDataPacket(e,K.RELIABLE),o+=1}})},close(){return N(this,void 0,void 0,function*(){let e=new Aa({destinationIdentities:i,value:{case:`streamTrailer`,value:new ao({streamId:t})}});yield s.sendDataPacket(e,K.RELIABLE)})},abort(e){console.log(`Sink error:`,e)}}),l=()=>N(this,void 0,void 0,function*(){yield u.close()});s.once(z.Closing,l);let u=new Dp(c,n,()=>this.engine.off(z.Closing,l));return u})}sendFile(e,t){return N(this,void 0,void 0,function*(){let n=crypto.randomUUID();return yield this._sendFile(n,e,t),{id:n}})}_sendFile(e,t,n){return N(this,void 0,void 0,function*(){let r=yield this.streamBytes({streamId:e,totalSize:t.size,name:t.name,mimeType:n?.mimeType??t.type,topic:n?.topic,destinationIdentities:n?.destinationIdentities}),i=t.stream().getReader();for(;;){let{done:e,value:t}=yield i.read();if(e)break;yield r.write(t)}return yield r.close(),r.info})}streamBytes(e){return N(this,void 0,void 0,function*(){let t=e?.streamId??crypto.randomUUID(),n=e?.destinationIdentities,r={id:t,mimeType:e?.mimeType??`application/octet-stream`,topic:e?.topic??``,timestamp:Date.now(),attributes:e?.attributes,size:e?.totalSize,name:e?.name??`unknown`,encryptionType:this.engine.e2eeManager?.isDataChannelEncryptionEnabled?j.GCM:j.NONE},i=new Aa({destinationIdentities:n,value:{case:`streamHeader`,value:new ro({totalLength:Vu(r.size),mimeType:r.mimeType,streamId:t,topic:r.topic,timestamp:Vu(Date.now()),attributes:r.attributes,contentHeader:{case:`byteHeader`,value:new no({name:r.name})}})}});yield this.engine.sendDataPacket(i,K.RELIABLE);let a=0,o=new ur,s=this.engine,c=this.log;return new Op(new WritableStream({write(e){return N(this,void 0,void 0,function*(){let r=yield o.lock(),i=0;try{for(;i<e.byteLength;){let r=e.slice(i,i+kp),o=new Aa({destinationIdentities:n,value:{case:`streamChunk`,value:new io({content:r,streamId:t,chunkIndex:Vu(a)})}});yield s.sendDataPacket(o,K.RELIABLE),a+=1,i+=r.byteLength}}finally{r()}})},close(){return N(this,void 0,void 0,function*(){let e=new Aa({destinationIdentities:n,value:{case:`streamTrailer`,value:new ao({streamId:t})}});yield s.sendDataPacket(e,K.RELIABLE)})},abort(e){c.error(`Sink error:`,e)}}),r)})}};function jp(e){if(e.length===0)return new AbortController().signal;if(e.length===1)return e[0];for(let t of e)if(t.aborted)return t;let t=new AbortController,n=Array(e.length),r=()=>{for(let e of n)e()};return e.forEach((e,i)=>{let a=()=>{t.abort(e.reason),r()};e.addEventListener(`abort`,a),n[i]=()=>e.removeEventListener(`abort`,a)}),t.signal}function Mp(e){let t=new AbortController;return setTimeout(()=>{t.abort(new DOMException(`signal timed out after ${e} ms`,`TimeoutError`))},e),t.signal}var q=1,Np=2,Pp=4,Fp=8,Ip=0,Lp=12,Rp=5,zp=7,Bp=3,Vp=3,Hp=2,Up=1,Wp=0,Gp=3,Kp=2,qp=2,Jp=1,Yp=0,Xp;(function(e){e[e.TooShort=0]=`TooShort`,e[e.HeaderOverrun=1]=`HeaderOverrun`,e[e.MissingExtWords=2]=`MissingExtWords`,e[e.UnsupportedVersion=3]=`UnsupportedVersion`,e[e.InvalidHandle=4]=`InvalidHandle`,e[e.MalformedExt=5]=`MalformedExt`})(Xp||={});var Zp=class e extends ol{constructor(e,t,n){super(19,e,n),this.name=`DataTrackDeserializeError`,this.reason=t,this.reasonName=Xp[t]}static tooShort(){return new e(`Too short to contain a valid header`,Xp.TooShort)}static headerOverrun(){return new e(`Header exceeds total packet length`,Xp.HeaderOverrun)}static missingExtWords(){return new e(`Extension word indicator is missing`,Xp.MissingExtWords)}static unsupportedVersion(t){return new e(`Unsupported version ${t}`,Xp.UnsupportedVersion)}static invalidHandle(t){return new e(`invalid track handle: ${t.message}`,Xp.InvalidHandle,{cause:t})}static malformedExt(t){return new e(`Extension with tag ${t} is malformed`,Xp.MalformedExt)}},Qp;(function(e){e[e.TooSmallForHeader=0]=`TooSmallForHeader`,e[e.TooSmallForPayload=1]=`TooSmallForPayload`})(Qp||={});var $p=class e extends ol{constructor(e,t,n){super(19,e,n),this.name=`DataTrackSerializeError`,this.reason=t,this.reasonName=Qp[t]}static tooSmallForHeader(){return new e(`Buffer cannot fit header`,Qp.TooSmallForHeader)}static tooSmallForPayload(){return new e(`Buffer cannot fit payload`,Qp.TooSmallForPayload)}},em=class{toBinary(){let e=this.toBinaryLengthBytes(),t=new ArrayBuffer(e),n=new DataView(t),r=this.toBinaryInto(n);if(e!==r)throw Error(`${this.constructor.name}.toBinary: written bytes (${r} bytes) not equal to allocated array buffer length (${e} bytes).`);return new Uint8Array(t)}},tm;(function(e){e[e.UserTimestamp=2]=`UserTimestamp`,e[e.E2ee=1]=`E2ee`})(tm||={});var nm=class extends em{},rm=class e extends nm{constructor(e){super(),this.timestamp=e}toBinaryLengthBytes(){return q+q+e.lengthBytes}toBinaryInto(t){let n=0;t.setUint8(n,e.tag),n+=q,t.setUint8(n,e.lengthBytes),n+=q,t.setBigUint64(n,this.timestamp),n+=Fp;let r=this.toBinaryLengthBytes();if(n!==r)throw Error(`DataTrackUserTimestampExtension.toBinaryInto: Wrote ${n} bytes but expected length was ${r} bytes`);return n}toJSON(){return{tag:e.tag,lengthBytes:e.lengthBytes,timestamp:this.timestamp}}};rm.tag=tm.UserTimestamp,rm.lengthBytes=8;var im=class e extends nm{constructor(e,t){super(),this.keyIndex=e,this.iv=t}toBinaryLengthBytes(){return q+q+e.lengthBytes}toBinaryInto(t){let n=0;t.setUint8(n,e.tag),n+=q,t.setUint8(n,e.lengthBytes),n+=q,t.setUint8(n,this.keyIndex),n+=q;for(let e=0;e<this.iv.length;e+=1)t.setUint8(n,this.iv[e]),n+=q;let r=this.toBinaryLengthBytes();if(n!==r)throw Error(`DataTrackE2eeExtension.toBinaryInto: Wrote ${n} bytes but expected length was ${r} bytes`);return n}toJSON(){return{tag:e.tag,lengthBytes:e.lengthBytes,keyIndex:this.keyIndex,iv:this.iv}}};im.tag=tm.E2ee,im.lengthBytes=13;var am=class e extends em{constructor(){let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};super(),this.userTimestamp=e.userTimestamp,this.e2ee=e.e2ee}toBinaryLengthBytes(){let e=0;return this.userTimestamp&&(e+=this.userTimestamp.toBinaryLengthBytes()),this.e2ee&&(e+=this.e2ee.toBinaryLengthBytes()),e}toBinaryInto(e){let t=0;if(this.e2ee){let n=this.e2ee.toBinaryInto(e);t+=n}if(this.userTimestamp){let n=this.userTimestamp.toBinaryInto(new DataView(e.buffer,e.byteOffset+t));t+=n}let n=this.toBinaryLengthBytes();if(t!==n)throw Error(`DataTrackExtensions.toBinaryInto: Wrote ${t} bytes but expected length was ${n} bytes`);return t}static fromBinary(t){let n=Od(t),r,i,a=0;for(;n.byteLength-a>=q+q;){let e=n.getUint8(a);a+=q;let t=n.getUint8(a);if(a+=q,e!==Yp)switch(e){case tm.UserTimestamp:if(n.byteLength-a<rm.lengthBytes)throw Zp.malformedExt(e);r=new rm(n.getBigUint64(a)),a+=t;break;case tm.E2ee:if(n.byteLength-a<im.lengthBytes)throw Zp.malformedExt(e);let o=n.getUint8(a),s=new Uint8Array(12);for(let e=0;e<s.length;e+=1){let t=a;t+=q,t+=e*q,s[e]=n.getUint8(t)}i=new im(o,s),a+=t;break;default:if(n.byteLength-a<t)throw Zp.malformedExt(e);a+=t;break}}return[new e({userTimestamp:r,e2ee:i}),n.byteLength]}toJSON(){return{userTimestamp:this.userTimestamp?.toJSON()??null,e2ee:this.e2ee?.toJSON()??null}}},om={from(e){return{payload:e.payload,extensions:new am({userTimestamp:e.userTimestamp?new rm(e.userTimestamp):void 0})}},lossyIntoFrame(e){return{payload:e.payload,userTimestamp:e.extensions.userTimestamp?.timestamp}}},sm=Symbol.for(`lk.track`),cm=Symbol.for(`lk.data-track`),lm=class{constructor(e,t,n){this.trackSymbol=sm,this.isLocal=!1,this.typeSymbol=cm,this.info=e,this.manager=t,this.publisherIdentity=n.publisherIdentity}subscribe(e){try{let[t]=this.manager.openSubscriptionStream(this.info.sid,e?.signal,e?.bufferSize);return t}catch(e){throw e}}},um=class e extends em{constructor(e){super(),this.marker=e.marker,this.trackHandle=e.trackHandle,this.sequence=e.sequence,this.frameNumber=e.frameNumber,this.timestamp=e.timestamp,this.extensions=e.extensions??new am}extensionsMetrics(){let e=this.extensions.toBinaryLengthBytes(),t=Math.ceil(e/4);return{lengthBytes:e,lengthWords:t,paddingLengthBytes:t*4-e}}toBinaryLengthBytes(){let{lengthBytes:e,paddingLengthBytes:t}=this.extensionsMetrics(),n=Lp;return e>0&&(n+=Kp+e+t),n}toBinaryInto(e){if(e.byteLength<this.toBinaryLengthBytes())throw $p.tooSmallForHeader();let t=Ip<<Rp,n;switch(this.marker){case J.Inter:n=Wp;break;case J.Final:n=Up;break;case J.Start:n=Hp;break;case J.Single:n=Gp;break}t|=n<<Bp;let{lengthBytes:r,lengthWords:i,paddingLengthBytes:a}=this.extensionsMetrics();r>0&&(t|=1<<qp);let o=0;if(e.setUint8(o,t),o+=q,e.setUint8(o,0),o+=q,e.setUint16(o,this.trackHandle),o+=Np,e.setUint16(o,this.sequence.value),o+=Np,e.setUint16(o,this.frameNumber.value),o+=Np,e.setUint32(o,this.timestamp.asTicks()),o+=Pp,r>0){let t=i-1;e.setUint16(o,t),o+=Np;let n=this.extensions.toBinaryInto(new DataView(e.buffer,e.byteOffset+o));o+=n;for(let t=0;t<a;t+=1)e.setUint8(o,0),o+=q}let s=this.toBinaryLengthBytes();if(o!==s)throw Error(`DataTrackPacketHeader.toBinaryInto: Wrote ${o} bytes but expected length was ${s} bytes`);return s}static fromBinary(t){let n=Od(t);if(n.byteLength<Lp)throw Zp.tooShort();let r=0,i=n.getUint8(r);r+=q;let a=i>>Rp&zp;if(a>Ip)throw Zp.unsupportedVersion(a);let o;switch(i>>Bp&Vp){case Hp:o=J.Start;break;case Up:o=J.Final;break;case Gp:o=J.Single;break;case Wp:default:o=J.Inter;break}let s=(i>>qp&Jp)>0;r+=q;let c;try{c=jd.fromNumber(n.getUint16(r))}catch(e){throw e instanceof Ad&&(e.isReason(kd.Reserved)||e.isReason(kd.TooLarge))?Zp.invalidHandle(e):e}r+=Np;let l=Td.u16(n.getUint16(r));r+=Np;let u=Td.u16(n.getUint16(r));r+=Np;let d=Ed.fromRtpTicks(n.getUint32(r));r+=Pp;let f=new am;if(s){if(n.byteLength-r<Np)throw Zp.missingExtWords();let e=n.getUint16(r);r+=Np;let t=4*(e+1);if(r+t>n.byteLength)throw Zp.headerOverrun();let i=new DataView(n.buffer,n.byteOffset+r,t),[a,o]=am.fromBinary(i);f=a,r+=o}return[new e({marker:o,trackHandle:c,sequence:l,frameNumber:u,timestamp:d,extensions:f}),r]}toJSON(){return{marker:this.marker,trackHandle:this.trackHandle,sequence:this.sequence.value,frameNumber:this.frameNumber.value,timestamp:this.timestamp.asTicks(),extensions:this.extensions.toJSON()}}},J;(function(e){e[e.Start=0]=`Start`,e[e.Inter=1]=`Inter`,e[e.Final=2]=`Final`,e[e.Single=3]=`Single`})(J||={});var dm=class e extends em{constructor(e,t){super(),this.header=e,this.payload=t}toBinaryLengthBytes(){return this.header.toBinaryLengthBytes()+this.payload.byteLength}toBinaryInto(e){let t=0,n=this.header.toBinaryInto(e);if(t+=n,e.byteLength-t<this.payload.byteLength)throw $p.tooSmallForPayload();for(let n=0;n<this.payload.length;n+=1)e.setUint8(t,this.payload[n]),t+=q;let r=this.toBinaryLengthBytes();if(t!==r)throw Error(`DataTrackPacket.toBinaryInto: Wrote ${t} bytes but expected length was ${r} bytes`);return r}static fromBinary(t){let n=Od(t),[r,i]=um.fromBinary(n),a=n.buffer.slice(n.byteOffset+i,n.byteOffset+n.byteLength);return[new e(r,new Uint8Array(a)),n.byteLength]}toJSON(){return{header:this.header.toJSON(),payload:this.payload}}},fm=Ts(ws.DataTracks),pm=class e extends ol{constructor(e,t,n,r){super(19,`Frame ${n} dropped: ${e}`,r),this.name=`DataTrackDepacketizerDropError`,this.reason=t,this.reasonName=mm[t],this.frameNumber=n}static interrupted(t,n){return new e(`Interrupted by the start of a new frame ${n}`,mm.Interrupted,t)}static unknownFrame(t){return new e(`Initial packet was never received.`,mm.UnknownFrame,t)}static bufferFull(t){return new e(`Reorder buffer is full.`,mm.BufferFull,t)}static incomplete(t,n,r){return new e(`Not all packets received before final packet. Received ${n} packets, expected ${r} packets.`,mm.Incomplete,t)}},mm;(function(e){e[e.Interrupted=0]=`Interrupted`,e[e.UnknownFrame=1]=`UnknownFrame`,e[e.BufferFull=2]=`BufferFull`,e[e.Incomplete=3]=`Incomplete`})(mm||={});var hm=class e{constructor(){this.partial=null}push(e,t){switch(e.header.marker){case J.Single:return this.frameFromSingle(e,t);case J.Start:return this.beginPartial(e,t);case J.Inter:case J.Final:return this.pushToPartial(e)}}reset(){this.partial=null}frameFromSingle(e,t){if(e.header.marker!==J.Single)throw Error(`Depacketizer.frameFromSingle: packet.header.marker was not FrameMarker.Single, found ${e.header.marker}.`);if(this.partial)if(t?.errorOnPartialFrames){let t=this.partial.frameNumber;throw this.reset(),pm.interrupted(t,e.header.frameNumber.value)}else fm.warn(`Data track frame ${this.partial.frameNumber} was interrupted by the start of a new frame, dropping.`);return this.reset(),{payload:e.payload,extensions:e.header.extensions}}beginPartial(e,t){if(e.header.marker!==J.Start)throw Error(`Depacketizer.beginPartial: packet.header.marker was not FrameMarker.Start, found ${e.header.marker}.`);if(this.partial)if(t?.errorOnPartialFrames){let t=this.partial.frameNumber;throw this.reset(),pm.interrupted(t,e.header.frameNumber.value)}else fm.warn(`Data track frame ${this.partial.frameNumber} was interrupted by the start of a new frame ${e.header.frameNumber.value}, dropping.`);this.reset();let n=e.header.sequence;return this.partial={frameNumber:e.header.frameNumber.value,startSequence:n,extensions:e.header.extensions,payloads:new Map([[n.value,e.payload]])},null}pushToPartial(t){if(t.header.marker!==J.Inter&&t.header.marker!==J.Final)throw Error(`Depacketizer.pushToPartial: packet.header.marker was not FrameMarker.Inter or FrameMarker.Final, found ${t.header.marker}.`);if(!this.partial)throw this.reset(),pm.unknownFrame(t.header.frameNumber.value);if(t.header.frameNumber.value!==this.partial.frameNumber){let e=this.partial.frameNumber;throw this.reset(),pm.interrupted(e,t.header.frameNumber.value)}if(this.partial.payloads.size>=e.MAX_BUFFER_PACKETS){let e=this.partial.frameNumber;throw this.reset(),pm.bufferFull(e)}return this.partial.payloads.has(t.header.sequence.value)&&fm.warn(`Data track frame ${this.partial.frameNumber} received duplicate packet for sequence ${t.header.sequence.value}, so replacing with newly received packet.`),this.partial.payloads.set(t.header.sequence.value,t.payload),t.header.marker===J.Final?this.finalize(this.partial,t.header.sequence.value):null}finalize(e,t){let n=e.payloads.size,r=0;for(let t of e.payloads.values())r+=t.length;let i=new Uint8Array(r),a=e.startSequence.clone(),o=0;for(;;){let n=e.payloads.get(a.value);if(!n)break;e.payloads.delete(a.value);let r=i.length-o;if(n.length>r)throw Error(`Depacketizer.finalize: Expected at least ${n.length} more bytes left in the payload buffer, only got ${r} bytes.`);if(i.set(n,o),o+=n.length,a.value!=t){a.increment();continue}return this.reset(),{payload:i,extensions:e.extensions}}throw this.reset(),pm.incomplete(e.frameNumber,n,t-e.startSequence.value+1)}};hm.MAX_BUFFER_PACKETS=128;var gm;(function(e){e[e.Unpublished=0]=`Unpublished`,e[e.Timeout=1]=`Timeout`,e[e.Disconnected=2]=`Disconnected`,e[e.Cancelled=4]=`Cancelled`})(gm||={});var _m=class e extends ol{constructor(e,t,n){super(22,e,n),this.name=`DataTrackSubscribeError`,this.reason=t,this.reasonName=gm[t]}static unpublished(){return new e(`The track has been unpublished and is no longer available`,gm.Unpublished)}static timeout(){return new e(`Request to subscribe to data track timed-out`,gm.Timeout)}static disconnected(){return new e(`Cannot subscribe to data track when disconnected`,gm.Disconnected)}static cancelled(){return new e(`Subscription to data track cancelled by caller`,gm.Cancelled)}},vm=Ts(ws.DataTracks),ym=class{constructor(e){let t=e.e2eeManager!==null;if(e.info.usesE2ee!==t)throw Error(`IncomingDataTrackPipeline: DataTrackInfo.usesE2ee must match presence of decryptionProvider`);let n=new hm;this.publisherIdentity=e.publisherIdentity,this.e2eeManager=e.e2eeManager??null,this.depacketizer=n}updateE2eeManager(e){this.e2eeManager=e}processPacket(e){return N(this,void 0,void 0,function*(){let t=this.depacketize(e);return t&&(yield this.decryptIfNeeded(t))||null})}depacketize(e){let t;try{t=this.depacketizer.push(e)}catch(e){return vm.warn(`Data frame depacketize error: ${e}`),null}return t}decryptIfNeeded(e){return N(this,void 0,void 0,function*(){let t=this.e2eeManager;if(!t)return e;let n=e.extensions?.e2ee??null;if(!n)return vm.error(`Missing E2EE meta`),null;let r;try{r=yield t.handleEncryptedData(e.payload,n.iv,this.publisherIdentity,n.keyIndex)}catch(e){return vm.error(`Error decrypting packet: ${e}`),null}return e.payload=r.payload,e})}},bm=Ts(ws.DataTracks),xm=1e4,Sm=16,Cm=class extends zs.EventEmitter{constructor(e){super(),this.descriptors=new Map,this.subscriptionHandles=new Map,this.e2eeManager=e?.e2eeManager??null}updateE2eeManager(e){this.e2eeManager=e;for(let t of this.descriptors.values())t.subscription.type===`active`&&t.subscription.pipeline.updateE2eeManager(e)}openSubscriptionStream(e,t){let n=arguments.length>2&&arguments[2]!==void 0?arguments[2]:Sm,r=null,i=new Mu;return[new ReadableStream({start:n=>{r=n;let a=()=>{var e;n.error(_m.cancelled()),(e=i.reject)==null||e.call(i,_m.cancelled())};this.subscribeRequest(e,t).then(()=>N(this,void 0,void 0,function*(){var r;t?.addEventListener(`abort`,a);let o=this.descriptors.get(e);if(!o){bm.error(`Unknown track ${e}`);return}if(o.subscription.type!==`active`){bm.error(`Subscription for track ${e} is not active`);return}o.subscription.streamControllers.add(n),(r=i.resolve)==null||r.call(i)})).catch(e=>{var t;n.error(e),(t=i.reject)==null||t.call(i,e)}).finally(()=>{t?.removeEventListener(`abort`,a)})},cancel:()=>{if(!r){bm.warn(`ReadableStream subscribed to ${e} was not started.`);return}let t=this.descriptors.get(e);if(!t){bm.warn(`Unknown track ${e}, skipping cancel...`);return}if(t.subscription.type!==`active`){bm.warn(`Subscription for track ${e} is not active, skipping cancel...`);return}t.subscription.streamControllers.delete(r),t.subscription.streamControllers.size===0&&this.unSubscribeRequest(t.info.sid)}},new CountQueuingStrategy({highWaterMark:n})),i.promise]}subscribeRequest(e,t){return N(this,void 0,void 0,function*(){let n=this.descriptors.get(e);if(!n)throw Error(`Cannot subscribe to unknown track`);let r=(t,n,r)=>N(this,void 0,void 0,function*(){if(t.subscription.type===`active`)return;if(t.subscription.type!==`pending`)throw Error(`Descriptor for track ${e} is not pending, found ${t.subscription.type}`);let i=jp([n,r].filter(e=>e!==void 0)),a=new Mu;t.subscription.completionFuture.promise.then(()=>a.resolve?.call(a)).catch(e=>a.reject?.call(a,e));let o=()=>{var e;if(t.subscription.type===`pending`){if(--t.subscription.pendingRequestCount,r?.aborted){t.subscription.cancel();return}if(t.subscription.pendingRequestCount<=0){t.subscription.cancel();return}(e=a.reject)==null||e.call(a,_m.cancelled())}};i.aborted&&o(),i.addEventListener(`abort`,o),yield a.promise,i.removeEventListener(`abort`,o)});switch(n.subscription.type){case`none`:{n.subscription={type:`pending`,completionFuture:new Mu,pendingRequestCount:1,cancel:()=>{var t,r;let a=n.subscription;n.subscription={type:`none`},this.emit(`sfuUpdateSubscription`,{sid:e,subscribe:!1}),a.type===`pending`&&((r=(t=a.completionFuture).reject)==null||r.call(t,i.aborted?_m.timeout():_m.cancelled()))}},this.emit(`sfuUpdateSubscription`,{sid:e,subscribe:!0});let i=Mp(xm);yield r(n,t,i);return}case`pending`:n.subscription.pendingRequestCount+=1,yield r(n,t);return;case`active`:return}})}querySubscribed(){return N(this,void 0,void 0,function*(){return Array.from(this.descriptors.values()).filter(e=>e.subscription.type===`active`).map(e=>[e.info,e.publisherIdentity])})}unSubscribeRequest(e){let t=this.descriptors.get(e);if(!t)throw Error(`Cannot subscribe to unknown track`);if(t.subscription.type!==`active`){bm.warn(`Unexpected descriptor state in unSubscribeRequest, expected active, found ${t.subscription?.type}`);return}for(let e of t.subscription.streamControllers)e.close();let n=t.subscription;t.subscription={type:`none`},this.subscriptionHandles.delete(n.subcriptionHandle),this.emit(`sfuUpdateSubscription`,{sid:e,subscribe:!1})}receiveSfuPublicationUpdates(e){return N(this,void 0,void 0,function*(){if(e.size===0)return;let t=new Map;for(let[n,r]of e.entries()){let e=new Set;for(let t of r)e.add(t.sid),!this.descriptors.has(t.sid)&&(yield this.handleTrackPublished(n,t));t.set(n,e)}for(let[e,n]of t.entries()){let t=Array.from(this.descriptors.entries()).filter(t=>{let[n,r]=t;return r.publisherIdentity===e}).map(e=>{let[t]=e;return t}).filter(e=>!n.has(e));for(let e of t)this.handleTrackUnpublished(e)}})}queryPublications(){return N(this,void 0,void 0,function*(){return Array.from(this.descriptors.values()).map(e=>e.info)})}handleTrackPublished(e,t){return N(this,void 0,void 0,function*(){if(this.descriptors.has(t.sid)){bm.error(`Existing descriptor for track ${t.sid}`);return}let n={info:t,publisherIdentity:e,subscription:{type:`none`}};this.descriptors.set(n.info.sid,n);let r=new lm(n.info,this,{publisherIdentity:e});this.emit(`trackPublished`,{track:r})})}handleTrackUnpublished(e){let t=this.descriptors.get(e);if(!t){bm.error(`Unknown track ${e}`);return}this.descriptors.delete(e),t.subscription.type===`active`&&this.subscriptionHandles.delete(t.subscription.subcriptionHandle),this.emit(`trackUnpublished`,{sid:e,publisherIdentity:t.publisherIdentity})}receivedSfuSubscriberHandles(e){for(let[t,n]of e.entries())this.registerSubscriberHandle(t,n)}registerSubscriberHandle(e,t){var n,r;let i=this.descriptors.get(t);if(!i){bm.error(`Unknown track ${t}`);return}switch(i.subscription.type){case`none`:bm.warn(`No subscription for ${t}`);return;case`active`:i.subscription.subcriptionHandle=e,this.subscriptionHandles.set(e,t);return;case`pending`:{let a=new ym({info:i.info,publisherIdentity:i.publisherIdentity,e2eeManager:this.e2eeManager}),o=i.subscription;i.subscription={type:`active`,subcriptionHandle:e,pipeline:a,streamControllers:new Set},this.subscriptionHandles.set(e,t),(r=(n=o.completionFuture).resolve)==null||r.call(n)}}}packetReceived(e){return N(this,void 0,void 0,function*(){let t;try{[t]=dm.fromBinary(e)}catch(e){bm.error(`Failed to deserialize packet: ${e}`);return}let n=this.subscriptionHandles.get(t.header.trackHandle);if(!n){bm.warn(`Unknown subscriber handle ${t.header.trackHandle}`);return}let r=this.descriptors.get(n);if(!r){bm.error(`Missing descriptor for track ${n}`);return}if(r.subscription.type!==`active`){bm.warn(`Received packet for track ${n} without active subscription`);return}let i=yield r.subscription.pipeline.processPacket(t);if(i)for(let e of r.subscription.streamControllers){if(e.desiredSize!==null&&e.desiredSize<=0){bm.warn(`Cannot send frame to subscribers: readable stream is full (desiredSize is ${e.desiredSize}). To increase this threshold, set a higher 'options.highWaterMark' when calling .subscribe().`);continue}let t=om.lossyIntoFrame(i);e.enqueue(t)}})}resendSubscriptionUpdates(){for(let[e,t]of this.descriptors)t.subscription.type!==`none`&&this.emit(`sfuUpdateSubscription`,{sid:e,subscribe:!0})}handleRemoteParticipantDisconnected(e){var t,n;for(let r of this.descriptors.values())if(r.publisherIdentity===e)switch(r.subscription.type){case`none`:break;case`pending`:(n=(t=r.subscription.completionFuture).reject)==null||n.call(t,_m.disconnected());break;case`active`:this.unSubscribeRequest(r.info.sid);break}}shutdown(){var e,t;for(let n of this.descriptors.values())this.emit(`trackUnpublished`,{sid:n.info.sid,publisherIdentity:n.publisherIdentity}),n.subscription.type===`pending`&&((t=(e=n.subscription.completionFuture).reject)==null||t.call(e,_m.disconnected()));this.descriptors.clear()}},wm=class e extends ol{constructor(e,t,n){super(19,e,n),this.name=`DataTrackPacketizerError`,this.reason=t,this.reasonName=Tm[t]}static mtuTooShort(){return new e(`MTU is too short to send frame`,Tm.MtuTooShort)}},Tm;(function(e){e[e.MtuTooShort=0]=`MtuTooShort`})(Tm||={});var Em=class e{constructor(e,t){this.sequence=Td.u16(0),this.frameNumber=Td.u16(0),this.clock=Dd.rtpStartingNow(Ed.rtpRandom()),this.handle=e,this.mtuSizeBytes=t}static computeFrameMarker(e,t){return t<=1?J.Single:e===0?J.Start:e===t-1?J.Final:J.Inter}*packetize(t,n){let r=this.frameNumber.getThenIncrement(),i={marker:J.Inter,trackHandle:this.handle,sequence:Td.u16(0),frameNumber:r,timestamp:n?.now??this.clock.now(),extensions:t.extensions},a=new um(i).toBinaryLengthBytes();if(a>=this.mtuSizeBytes)throw wm.mtuTooShort();let o=this.mtuSizeBytes-a,s=Math.ceil(t.payload.byteLength/o);for(let n=0,r=0;r<t.payload.byteLength;[n,r]=[n+1,r+o]){let a=this.sequence.getThenIncrement(),c=new um(Object.assign(Object.assign({},i),{marker:e.computeFrameMarker(n,s),sequence:a})),l=Math.min(o,t.payload.byteLength-r);yield new dm(c,new Uint8Array(t.payload.buffer,t.payload.byteOffset+r,l))}}},Dm;(function(e){e[e.NotAllowed=0]=`NotAllowed`,e[e.DuplicateName=1]=`DuplicateName`,e[e.Timeout=2]=`Timeout`,e[e.LimitReached=3]=`LimitReached`,e[e.Disconnected=4]=`Disconnected`,e[e.Cancelled=5]=`Cancelled`,e[e.InvalidName=6]=`InvalidName`,e[e.Unknown=7]=`Unknown`})(Dm||={});var Om=class e extends ol{constructor(e,t,n){super(21,e,n),this.name=`DataTrackPublishError`,this.reason=t,this.reasonName=Dm[t],this.rawMessage=n?.rawMessage}static notAllowed(t){return new e(`Data track publishing unauthorized`,Dm.NotAllowed,{rawMessage:t})}static duplicateName(t){return new e(`Track name already taken`,Dm.DuplicateName,{rawMessage:t})}static invalidName(t){return new e(`Track name is invalid`,Dm.InvalidName,{rawMessage:t})}static timeout(){return new e(`Publish data track timed-out. Does the LiveKit server support data tracks?`,Dm.Timeout)}static limitReached(t){return new e(`Data track publication limit reached`,Dm.LimitReached,{rawMessage:t})}static unknown(t,n){return new e(`Received RequestResponse for publishDataTrack, but reason was unrecognised (${t}, ${n})`,Dm.Unknown)}static disconnected(){return new e(`Room disconnected`,Dm.Disconnected)}static cancelled(){return new e(`Publish data track cancelled by caller`,Dm.Cancelled)}},km;(function(e){e[e.TrackUnpublished=0]=`TrackUnpublished`,e[e.Dropped=1]=`Dropped`})(km||={});var Am=class e extends ol{constructor(e,t,n){super(22,e,n),this.name=`DataTrackPushFrameError`,this.reason=t,this.reasonName=km[t]}static trackUnpublished(){return new e(`Track is no longer published`,km.TrackUnpublished)}static dropped(t){return new e(`Frame was dropped`,km.Dropped,{cause:t})}},jm;(function(e){e[e.Packetizer=0]=`Packetizer`,e[e.Encryption=1]=`Encryption`})(jm||={});var Mm=class e extends ol{constructor(e,t,n){super(21,e,n),this.name=`DataTrackOutgoingPipelineError`,this.reason=t,this.reasonName=jm[t]}static packetizer(t){return new e(`Error packetizing frame`,jm.Packetizer,{cause:t})}static encryption(t){return new e(`Error encrypting frame`,jm.Encryption,{cause:t})}},Nm=class e{constructor(e,t){this.trackSymbol=sm,this.isLocal=!0,this.typeSymbol=cm,this.handle=null,this.log=M,this.options=e,this.manager=t,this.log=Ts(ws.DataTracks)}static withExplicitHandle(t,n,r){let i=new e(t,n);return i.handle=r,i}get info(){let e=this.descriptor;if(e?.type===`active`)return e.info}get descriptor(){return this.handle?this.manager.getDescriptor(this.handle):null}publish(e){return N(this,void 0,void 0,function*(){try{this.handle=yield this.manager.publishRequest(this.options,e)}catch(e){throw e}})}isPublished(){return this.descriptor?.type===`active`&&this.descriptor.publishState!==`unpublished`}tryPush(e){if(!this.handle)throw Am.trackUnpublished();let t=om.from(e);try{return this.manager.tryProcessAndSend(this.handle,t)}catch(e){throw e}}unpublish(){return N(this,void 0,void 0,function*(){if(!this.handle){M.warn(`Data track "${this.options.name}" is not published, so unpublishing has no effect.`);return}try{yield this.manager.unpublishRequest(this.handle)}catch(e){throw e}})}},Pm=class e{constructor(t){this.e2eeManager=t.e2eeManager,this.packetizer=new Em(t.info.pubHandle,e.TRANSPORT_MTU_BYTES)}updateE2eeManager(e){this.e2eeManager=e}processFrame(e){return Ns(this,arguments,function*(){let t=yield Ms(this.encryptIfNeeded(e));try{yield Ms(yield*Ps(Fs(this.packetizer.packetize(t))))}catch(e){throw e instanceof wm?Mm.packetizer(e):e}})}encryptIfNeeded(e){return N(this,void 0,void 0,function*(){if(!this.e2eeManager)return e;let t;try{t=yield this.e2eeManager.encryptData(e.payload)}catch(e){throw Mm.encryption(e)}return e.payload=t.payload,e.extensions.e2ee=new im(t.keyIndex,t.iv),e})}};Pm.TRANSPORT_MTU_BYTES=16e3;var Fm=Ts(ws.DataTracks),Im={pending(){return{type:`pending`,completionFuture:new Mu}},active(e,t){return{type:`active`,info:e,publishState:`published`,pipeline:new Pm({info:e,e2eeManager:t}),unpublishingFuture:new Mu}}},Lm=1e4,Rm=class e extends zs.EventEmitter{constructor(e){super(),this.handleAllocator=new Md,this.descriptors=new Map,this.e2eeManager=e?.e2eeManager??null}static withDescriptors(t){let n=new e;return n.descriptors=t,n}updateE2eeManager(e){this.e2eeManager=e;for(let t of this.descriptors.values())t.type===`active`&&t.pipeline.updateE2eeManager(e)}getDescriptor(e){return this.descriptors.get(e)??null}tryProcessAndSend(e,t){return N(this,void 0,void 0,function*(){var n,r,i,a;let o=this.getDescriptor(e);if(o?.type!==`active`||o.publishState===`unpublished`)throw Am.trackUnpublished();if(o.publishState===`republishing`)throw Am.dropped(`Data track republishing`);try{try{for(var s=!0,c=Fs(o.pipeline.processFrame(t)),l;l=yield c.next(),n=l.done,!n;s=!0){a=l.value,s=!1;let e=a;this.emit(`packetAvailable`,{bytes:e.toBinary()})}}catch(e){r={error:e}}finally{try{!s&&!n&&(i=c.return)&&(yield i.call(c))}finally{if(r)throw r.error}}}catch(e){throw Am.dropped(e)}})}publishRequest(e,t){return N(this,void 0,void 0,function*(){let n=this.handleAllocator.get();if(!n)throw Om.limitReached();let r=Mp(Lm),i=t?jp([t,r]):r;if(this.descriptors.has(n))throw Error(`Descriptor for handle already exists`);let a=Im.pending();this.descriptors.set(n,a);let o=()=>{var e,t;let i=this.descriptors.get(n);if(!i){Fm.warn(`No descriptor for ${n}`);return}this.descriptors.delete(n),this.emit(`sfuUnpublishRequest`,{handle:n}),i.type===`pending`&&((t=(e=i.completionFuture).reject)==null||t.call(e,r.aborted?Om.timeout():Om.cancelled()))};return i.aborted?(o(),a.completionFuture.promise.then(()=>n)):(i.addEventListener(`abort`,o),this.emit(`sfuPublishRequest`,{handle:n,name:e.name,usesE2ee:this.e2eeManager!==null}),yield a.completionFuture.promise,i.removeEventListener(`abort`,o),this.emit(`trackPublished`,{track:Nm.withExplicitHandle(e,this,n)}),n)})}queryPublished(){return Array.from(this.descriptors.values()).filter(e=>e.type===`active`).map(e=>e.info)}unpublishRequest(e){return N(this,void 0,void 0,function*(){let t=this.descriptors.get(e);if(!t){Fm.warn(`No descriptor for ${e}`);return}if(t.type!==`active`){Fm.warn(`Track ${e} not active`);return}this.emit(`sfuUnpublishRequest`,{handle:e}),yield t.unpublishingFuture.promise,this.emit(`trackUnpublished`,{sid:t.info.sid})})}receivedSfuPublishResponse(e,t){var n,r,i,a;let o=this.descriptors.get(e);if(!o){Fm.warn(`No descriptor for ${e}`);return}switch(this.descriptors.delete(e),o.type){case`pending`:if(t.type===`ok`){let e=t.data,i=e.usesE2ee?this.e2eeManager:null;this.descriptors.set(e.pubHandle,Im.active(e,i)),(r=(n=o.completionFuture).resolve)==null||r.call(n)}else (a=(i=o.completionFuture).reject)==null||a.call(i,t.error);return;case`active`:if(o.publishState!==`republishing`){Fm.warn(`Track ${e} already active`);return}if(t.type===`error`){Fm.warn(`Republish failed for track ${e}`);return}Fm.debug(`Track ${e} republished`),o.info.sid=t.data.sid,o.publishState=`published`,this.descriptors.set(o.info.pubHandle,o)}}receivedSfuUnpublishResponse(e){var t,n;let r=this.descriptors.get(e);if(!r){Fm.warn(`No descriptor for ${e}`);return}if(this.descriptors.delete(e),r.type!==`active`){Fm.warn(`Track ${e} not active`);return}r.publishState=`unpublished`,(n=(t=r.unpublishingFuture).resolve)==null||n.call(t)}sfuWillRepublishTracks(){var e,t;for(let[n,r]of this.descriptors.entries())switch(r.type){case`pending`:this.descriptors.delete(n),(t=(e=r.completionFuture).reject)==null||t.call(e,Om.disconnected());break;case`active`:r.publishState=`republishing`,this.emit(`sfuPublishRequest`,{handle:r.info.pubHandle,name:r.info.name,usesE2ee:r.info.usesE2ee})}}shutdown(){return N(this,void 0,void 0,function*(){var e,t,n,r;for(let i of this.descriptors.values())switch(i.type){case`pending`:(t=(e=i.completionFuture).reject)==null||t.call(e,Om.disconnected());break;case`active`:(r=(n=i.unpublishingFuture).resolve)==null||r.call(n),yield this.unpublishRequest(i.info.pubHandle);break}this.descriptors.clear()})}},zm=class extends U{constructor(e,t,n,r,i){super(e,n,i),this.sid=t,this.receiver=r}get isLocal(){return!1}setMuted(e){this.isMuted!==e&&(this.isMuted=e,this._mediaStreamTrack.enabled=!e,this.emit(e?B.Muted:B.Unmuted,this))}setMediaStream(e){this.mediaStream=e;let t=n=>{n.track===this._mediaStreamTrack&&(e.removeEventListener(`removetrack`,t),this.receiver&&`playoutDelayHint`in this.receiver&&(this.receiver.playoutDelayHint=void 0),this.receiver=void 0,this._currentBitrate=0,this.emit(B.Ended,this))};e.addEventListener(`removetrack`,t)}start(){this.startMonitor(),super.enable()}stop(){this.stopMonitor(),super.disable()}getRTCStatsReport(){return N(this,void 0,void 0,function*(){if(this.receiver?.getStats)return yield this.receiver.getStats()})}setPlayoutDelay(e){this.receiver?`playoutDelayHint`in this.receiver?this.receiver.playoutDelayHint=e:this.log.warn(`Playout delay not supported in this browser`):this.log.warn(`Cannot set playout delay, track already ended`)}getPlayoutDelay(){if(this.receiver){if(`playoutDelayHint`in this.receiver)return this.receiver.playoutDelayHint;this.log.warn(`Playout delay not supported in this browser`)}else this.log.warn(`Cannot get playout delay, track already ended`);return 0}startMonitor(){this.monitorInterval||=setInterval(()=>this.monitorReceiver(),jf),Rl()&&this.registerTimeSyncUpdate()}registerTimeSyncUpdate(){let e=()=>{this.timeSyncHandle=requestAnimationFrame(()=>e());let t=this.receiver?.getSynchronizationSources()[0];if(t){let{timestamp:e,rtpTimestamp:n}=t;n&&this.rtpTimestamp!==n&&(this.emit(B.TimeSyncUpdate,{timestamp:e,rtpTimestamp:n}),this.rtpTimestamp=n)}};e()}},Bm=class extends zm{constructor(e,t,n,r,i,a){super(e,t,U.Kind.Audio,n,a),this.monitorReceiver=()=>N(this,void 0,void 0,function*(){if(!this.receiver){this._currentBitrate=0;return}let e=yield this.getReceiverStats();e&&this.prevStats&&this.receiver&&(this._currentBitrate=Mf(e,this.prevStats)),this.prevStats=e}),this.audioContext=r,this.webAudioPluginNodes=[],i&&(this.sinkId=i.deviceId)}setVolume(e){var t;for(let n of this.attachedElements)this.audioContext?(t=this.gainNode)==null||t.gain.setTargetAtTime(e,0,.1):n.volume=e;hu()&&this._mediaStreamTrack._setVolume(e),this.elementVolume=e}getVolume(){if(this.elementVolume)return this.elementVolume;if(hu())return 1;let e=0;return this.attachedElements.forEach(t=>{t.volume>e&&(e=t.volume)}),e}setSinkId(e){return N(this,void 0,void 0,function*(){this.sinkId=e,yield Promise.all(this.attachedElements.map(t=>{if(iu(t))return t.setSinkId(e)}))})}attach(e){let t=this.attachedElements.length===0;return e?super.attach(e):e=super.attach(),this.sinkId&&iu(e)&&e.setSinkId(this.sinkId).catch(e=>{this.log.error(`Failed to set sink id on remote audio track`,e,this.logContext)}),this.audioContext&&t&&(this.log.debug(`using audio context mapping`,this.logContext),this.connectWebAudio(this.audioContext,e),e.volume=0,e.muted=!0),this.elementVolume&&this.setVolume(this.elementVolume),e}detach(e){let t;return e?(t=super.detach(e),this.audioContext&&(this.attachedElements.length>0?this.connectWebAudio(this.audioContext,this.attachedElements[0]):this.disconnectWebAudio())):(t=super.detach(),this.disconnectWebAudio()),t}setAudioContext(e){this.audioContext=e,e&&this.attachedElements.length>0?this.connectWebAudio(e,this.attachedElements[0]):e||this.disconnectWebAudio()}setWebAudioPlugins(e){this.webAudioPluginNodes=e,this.attachedElements.length>0&&this.audioContext&&this.connectWebAudio(this.audioContext,this.attachedElements[0])}connectWebAudio(e,t){this.disconnectWebAudio(),this.sourceNode=e.createMediaStreamSource(t.srcObject);let n=this.sourceNode;this.webAudioPluginNodes.forEach(e=>{n.connect(e),n=e}),this.gainNode=e.createGain(),n.connect(this.gainNode),this.gainNode.connect(e.destination),this.elementVolume&&this.gainNode.gain.setTargetAtTime(this.elementVolume,0,.1),e.state!==`running`&&e.resume().then(()=>{e.state!==`running`&&this.emit(B.AudioPlaybackFailed,Error(`Audio Context couldn't be started automatically`))}).catch(e=>{this.emit(B.AudioPlaybackFailed,e)})}disconnectWebAudio(){var e,t;(e=this.gainNode)==null||e.disconnect(),(t=this.sourceNode)==null||t.disconnect(),this.gainNode=void 0,this.sourceNode=void 0}getReceiverStats(){return N(this,void 0,void 0,function*(){if(!this.receiver||!this.receiver.getStats)return;let e=yield this.receiver.getStats(),t;return e.forEach(e=>{e.type===`inbound-rtp`&&(t={type:`audio`,streamId:e.id,timestamp:e.timestamp,jitter:e.jitter,bytesReceived:e.bytesReceived,concealedSamples:e.concealedSamples,concealmentEvents:e.concealmentEvents,silentConcealedSamples:e.silentConcealedSamples,silentConcealmentEvents:e.silentConcealmentEvents,totalAudioEnergy:e.totalAudioEnergy,totalSamplesDuration:e.totalSamplesDuration})}),t})}},Vm=100,Hm=class extends zm{constructor(e,t,n,r,i){super(e,t,U.Kind.Video,n,i),this.elementInfos=[],this.monitorReceiver=()=>N(this,void 0,void 0,function*(){if(!this.receiver){this._currentBitrate=0;return}let e=yield this.getReceiverStats();e&&this.prevStats&&this.receiver&&(this._currentBitrate=Mf(e,this.prevStats)),this.prevStats=e}),this.debouncedHandleResize=sf(()=>{this.updateDimensions()},Vm),this.adaptiveStreamSettings=r}get isAdaptiveStream(){return this.adaptiveStreamSettings!==void 0}setStreamState(e){super.setStreamState(e),this.log.debug(`setStreamState`,e),this.isAdaptiveStream&&e===U.StreamState.Active&&this.updateVisibility()}get mediaStreamTrack(){return this._mediaStreamTrack}setMuted(e){super.setMuted(e),this.attachedElements.forEach(t=>{e?Jl(this._mediaStreamTrack,t):ql(this._mediaStreamTrack,t)})}attach(e){if(e?super.attach(e):e=super.attach(),this.adaptiveStreamSettings&&this.elementInfos.find(t=>t.element===e)===void 0){let t=new Um(e);this.observeElementInfo(t)}return e}observeElementInfo(e){this.adaptiveStreamSettings&&this.elementInfos.find(t=>t===e)===void 0?(e.handleResize=()=>{this.debouncedHandleResize()},e.handleVisibilityChanged=()=>{this.updateVisibility()},this.elementInfos.push(e),e.observe(),this.debouncedHandleResize(),this.updateVisibility()):this.log.warn(`visibility resize observer not triggered`,this.logContext)}stopObservingElementInfo(e){if(!this.isAdaptiveStream){this.log.warn(`stopObservingElementInfo ignored`,this.logContext);return}let t=this.elementInfos.filter(t=>t===e);for(let e of t)e.stopObserving();this.elementInfos=this.elementInfos.filter(t=>t!==e),this.updateVisibility(),this.debouncedHandleResize()}detach(e){let t=[];if(e)return this.stopObservingElement(e),super.detach(e);t=super.detach();for(let e of t)this.stopObservingElement(e);return t}getDecoderImplementation(){return this.prevStats?.decoderImplementation}getReceiverStats(){return N(this,void 0,void 0,function*(){if(!this.receiver||!this.receiver.getStats)return;let e=yield this.receiver.getStats(),t,n=``,r=new Map;return e.forEach(e=>{e.type===`inbound-rtp`?(n=e.codecId,t={type:`video`,streamId:e.id,framesDecoded:e.framesDecoded,framesDropped:e.framesDropped,framesReceived:e.framesReceived,packetsReceived:e.packetsReceived,packetsLost:e.packetsLost,frameWidth:e.frameWidth,frameHeight:e.frameHeight,pliCount:e.pliCount,firCount:e.firCount,nackCount:e.nackCount,jitter:e.jitter,timestamp:e.timestamp,bytesReceived:e.bytesReceived,decoderImplementation:e.decoderImplementation}):e.type===`codec`&&r.set(e.id,e)}),t&&n!==``&&r.get(n)&&(t.mimeType=r.get(n).mimeType),t})}stopObservingElement(e){let t=this.elementInfos.filter(t=>t.element===e);for(let e of t)this.stopObservingElementInfo(e)}handleAppVisibilityChanged(){let e=Object.create(null,{handleAppVisibilityChanged:{get:()=>super.handleAppVisibilityChanged}});return N(this,void 0,void 0,function*(){yield e.handleAppVisibilityChanged.call(this),this.isAdaptiveStream&&this.updateVisibility()})}updateVisibility(e){let t=this.elementInfos.reduce((e,t)=>Math.max(e,t.visibilityChangedAt||0),0),n=this.adaptiveStreamSettings?.pauseVideoInBackground??!0?this.isInBackground:!1,r=this.elementInfos.some(e=>e.pictureInPicture),i=this.elementInfos.some(e=>e.visible)&&!n||r;if(!(this.lastVisible===i&&!e)){if(!i&&Date.now()-t<Vm){_l.setTimeout(()=>{this.updateVisibility()},Vm);return}this.lastVisible=i,this.emit(B.VisibilityChanged,i,this)}}updateDimensions(){let e=0,t=0,n=this.getPixelDensity();for(let r of this.elementInfos){let i=r.width()*n,a=r.height()*n;i+a>e+t&&(e=i,t=a)}this.lastDimensions?.width===e&&this.lastDimensions?.height===t||(this.lastDimensions={width:e,height:t},this.emit(B.VideoDimensionsChanged,this.lastDimensions,this))}getPixelDensity(){let e=this.adaptiveStreamSettings?.pixelDensity;return e===`screen`?bu():e||(bu()>2?2:1)}},Um=class{get visible(){return this.isPiP||this.isIntersecting}get pictureInPicture(){return this.isPiP}constructor(e,t){this.onVisibilityChanged=e=>{var t;let{target:n,isIntersecting:r}=e;n===this.element&&(this.isIntersecting=r,this.isPiP=Wm(this.element),this.visibilityChangedAt=Date.now(),(t=this.handleVisibilityChanged)==null||t.call(this))},this.onEnterPiP=()=>{var e,t;(e=window.documentPictureInPicture?.window)==null||e.addEventListener(`pagehide`,this.onLeavePiP),this.isPiP=Wm(this.element),(t=this.handleVisibilityChanged)==null||t.call(this)},this.onLeavePiP=()=>{var e;this.isPiP=Wm(this.element),(e=this.handleVisibilityChanged)==null||e.call(this)},this.element=e,this.isIntersecting=t??Gm(e),this.isPiP=mu()&&Wm(e),this.visibilityChangedAt=0}width(){return this.element.clientWidth}height(){return this.element.clientHeight}observe(){var e,t;this.isIntersecting=Gm(this.element),this.isPiP=Wm(this.element),this.element.handleResize=()=>{var e;(e=this.handleResize)==null||e.call(this)},this.element.handleVisibilityChanged=this.onVisibilityChanged,Du().observe(this.element),Tu().observe(this.element),this.element.addEventListener(`enterpictureinpicture`,this.onEnterPiP),this.element.addEventListener(`leavepictureinpicture`,this.onLeavePiP),(e=window.documentPictureInPicture)==null||e.addEventListener(`enter`,this.onEnterPiP),(t=window.documentPictureInPicture?.window)==null||t.addEventListener(`pagehide`,this.onLeavePiP)}stopObserving(){var e,t,n,r;(e=Du())==null||e.unobserve(this.element),(t=Tu())==null||t.unobserve(this.element),this.element.removeEventListener(`enterpictureinpicture`,this.onEnterPiP),this.element.removeEventListener(`leavepictureinpicture`,this.onLeavePiP),(n=window.documentPictureInPicture)==null||n.removeEventListener(`enter`,this.onEnterPiP),(r=window.documentPictureInPicture?.window)==null||r.removeEventListener(`pagehide`,this.onLeavePiP)}};function Wm(e){return document.pictureInPictureElement===e?!0:window.documentPictureInPicture?.window?Gm(e,window.documentPictureInPicture?.window):!1}function Gm(e,t){let n=t||window,r=e.offsetTop,i=e.offsetLeft,a=e.offsetWidth,o=e.offsetHeight,{hidden:s}=e,{display:c}=getComputedStyle(e);for(;e.offsetParent;)e=e.offsetParent,r+=e.offsetTop,i+=e.offsetLeft;return r<n.pageYOffset+n.innerHeight&&i<n.pageXOffset+n.innerWidth&&r+o>n.pageYOffset&&i+a>n.pageXOffset&&!s&&c!==`none`}var Km=class extends zs.EventEmitter{constructor(e,t,n,r){super(),this.metadataMuted=!1,this.encryption=j.NONE,this.log=M,this.handleMuted=()=>{this.emit(B.Muted)},this.handleUnmuted=()=>{this.emit(B.Unmuted)},this.log=Ts(r?.loggerName??ws.Publication),this.loggerContextCb=this.loggerContextCb,this.setMaxListeners(100),this.kind=e,this.trackSid=t,this.trackName=n,this.source=U.Source.Unknown}setTrack(e){this.track&&(this.track.off(B.Muted,this.handleMuted),this.track.off(B.Unmuted,this.handleUnmuted)),this.track=e,e&&(e.on(B.Muted,this.handleMuted),e.on(B.Unmuted,this.handleUnmuted))}get logContext(){return Object.assign(Object.assign({},this.loggerContextCb?.call(this)),H(this))}get isMuted(){return this.metadataMuted}get isEnabled(){return!0}get isSubscribed(){return this.track!==void 0}get isEncrypted(){return this.encryption!==j.NONE}get audioTrack(){if(Uu(this.track))return this.track}get videoTrack(){if(Wu(this.track))return this.track}updateInfo(e){this.trackSid=e.sid,this.trackName=e.name,this.source=U.sourceFromProto(e.source),this.mimeType=e.mimeType,this.kind===U.Kind.Video&&e.width>0&&(this.dimensions={width:e.width,height:e.height},this.simulcasted=e.simulcast),this.encryption=e.encryption,this.trackInfo=e,this.log.debug(`update publication info`,Object.assign(Object.assign({},this.logContext),{info:e}))}};(function(e){(function(e){e.Desired=`desired`,e.Subscribed=`subscribed`,e.Unsubscribed=`unsubscribed`})(e.SubscriptionStatus||={}),(function(e){e.Allowed=`allowed`,e.NotAllowed=`not_allowed`})(e.PermissionStatus||={})})(Km||={});var qm=class extends Km{get isUpstreamPaused(){return this.track?.isUpstreamPaused}constructor(e,t,n,r){super(e,t.sid,t.name,r),this.track=void 0,this.handleTrackEnded=()=>{this.emit(B.Ended)},this.handleCpuConstrained=()=>{this.track&&Wu(this.track)&&this.emit(B.CpuConstrained,this.track)},this.updateInfo(t),this.setTrack(n)}setTrack(e){this.track&&(this.track.off(B.Ended,this.handleTrackEnded),this.track.off(B.CpuConstrained,this.handleCpuConstrained)),super.setTrack(e),e&&(e.on(B.Ended,this.handleTrackEnded),e.on(B.CpuConstrained,this.handleCpuConstrained))}get isMuted(){return this.track?this.track.isMuted:super.isMuted}get audioTrack(){return super.audioTrack}get videoTrack(){return super.videoTrack}get isLocal(){return!0}mute(){return N(this,void 0,void 0,function*(){return this.track?.mute()})}unmute(){return N(this,void 0,void 0,function*(){return this.track?.unmute()})}pauseUpstream(){return N(this,void 0,void 0,function*(){yield this.track?.pauseUpstream()})}resumeUpstream(){return N(this,void 0,void 0,function*(){yield this.track?.resumeUpstream()})}getTrackFeatures(){if(Uu(this.track)){let e=this.track.getSourceTrackSettings(),t=new Set;return e.autoGainControl&&t.add(ga.TF_AUTO_GAIN_CONTROL),e.echoCancellation&&t.add(ga.TF_ECHO_CANCELLATION),e.noiseSuppression&&t.add(ga.TF_NOISE_SUPPRESSION),e.channelCount&&e.channelCount>1&&t.add(ga.TF_STEREO),this.options?.dtx||t.add(ga.TF_NO_DTX),this.track.enhancedNoiseCancellation&&t.add(ga.TF_ENHANCED_NOISE_CANCELLATION),Array.from(t.values())}else return[]}};function Jm(e,t){return N(this,void 0,void 0,function*(){e??={};let n=!1,{audioProcessor:r,videoProcessor:i,optionsWithoutProcessor:a}=Bl(e),o=a.audio,s=a.video;if(r&&typeof a.audio==`object`&&(a.audio.processor=r),i&&typeof a.video==`object`&&(a.video.processor=i),e.audio&&typeof a.audio==`object`&&typeof a.audio.deviceId==`string`){let e=a.audio.deviceId;a.audio.deviceId={exact:e},n=!0,o=Object.assign(Object.assign({},a.audio),{deviceId:{ideal:e}})}if(a.video&&typeof a.video==`object`&&typeof a.video.deviceId==`string`){let e=a.video.deviceId;a.video.deviceId={exact:e},n=!0,s=Object.assign(Object.assign({},a.video),{deviceId:{ideal:e}})}a.audio===!0?a.audio={deviceId:`default`}:typeof a.audio==`object`&&a.audio!==null&&(a.audio=Object.assign(Object.assign({},a.audio),{deviceId:a.audio.deviceId||`default`})),a.video===!0?a.video={deviceId:`default`}:typeof a.video==`object`&&!a.video.deviceId&&(a.video.deviceId=`default`);let c=Ol(a,vf,yf),l=Al(c),u=navigator.mediaDevices.getUserMedia(l);a.audio&&(Sd.userMediaPromiseMap.set(`audioinput`,u),u.catch(()=>Sd.userMediaPromiseMap.delete(`audioinput`))),a.video&&(Sd.userMediaPromiseMap.set(`videoinput`,u),u.catch(()=>Sd.userMediaPromiseMap.delete(`videoinput`)));try{let e=yield u;return yield Promise.all(e.getTracks().map(n=>N(this,void 0,void 0,function*(){let a=n.kind===`audio`,o=a?c.audio:c.video;(typeof o==`boolean`||!o)&&(o={});let s,u=a?l.audio:l.video;typeof u!=`boolean`&&(s=u);let d=n.getSettings().deviceId;s?.deviceId&&Pu(s.deviceId)!==d?s.deviceId=d:s||={deviceId:d};let f=Vf(n,s,t);return f.kind===U.Kind.Video?f.source=U.Source.Camera:f.kind===U.Kind.Audio&&(f.source=U.Source.Microphone),f.mediaStream=e,Uu(f)&&r?yield f.setProcessor(r):Wu(f)&&i&&(yield f.setProcessor(i)),f})))}catch(r){if(!n)throw r;return Jm(Object.assign(Object.assign({},e),{audio:o,video:s}),t)}})}function Ym(e){return N(this,void 0,void 0,function*(){return(yield Jm({audio:e??!0,video:!1}))[0]})}var Xm;(function(e){e.Excellent=`excellent`,e.Good=`good`,e.Poor=`poor`,e.Lost=`lost`,e.Unknown=`unknown`})(Xm||={});function Zm(e){switch(e){case da.EXCELLENT:return Xm.Excellent;case da.GOOD:return Xm.Good;case da.POOR:return Xm.Poor;case da.LOST:return Xm.Lost;default:return Xm.Unknown}}var Qm=class extends zs.EventEmitter{get logContext(){var e;return Object.assign({},((e=this.loggerOptions)?.loggerContextCb)?.call(e))}get isEncrypted(){return this.trackPublications.size>0&&Array.from(this.trackPublications.values()).every(e=>e.isEncrypted)}get isAgent(){return this.permissions?.agent||this.kind===Sa.AGENT}get isActive(){return this.participantInfo?.state===xa.ACTIVE}get kind(){return this._kind}get attributes(){return Object.freeze(Object.assign({},this._attributes))}constructor(e,t,n,r,i,a){let o=arguments.length>6&&arguments[6]!==void 0?arguments[6]:Sa.STANDARD;super(),this.audioLevel=0,this.isSpeaking=!1,this._connectionQuality=Xm.Unknown,this.log=M,this.log=Ts(a?.loggerName??ws.Participant),this.loggerOptions=a,this.setMaxListeners(100),this.sid=e,this.identity=t,this.name=n,this.metadata=r,this.audioTrackPublications=new Map,this.videoTrackPublications=new Map,this.trackPublications=new Map,this._kind=o,this._attributes=i??{}}getTrackPublications(){return Array.from(this.trackPublications.values())}getTrackPublication(e){for(let[,t]of this.trackPublications)if(t.source===e)return t}getTrackPublicationByName(e){for(let[,t]of this.trackPublications)if(t.trackName===e)return t}waitUntilActive(){return this.isActive?Promise.resolve():this.activeFuture?this.activeFuture.promise:(this.activeFuture=new Mu,this.once(R.Active,()=>{var e,t;(t=(e=this.activeFuture)?.resolve)==null||t.call(e),this.activeFuture=void 0}),this.activeFuture.promise)}get connectionQuality(){return this._connectionQuality}get isCameraEnabled(){return!(this.getTrackPublication(U.Source.Camera)?.isMuted??!0)}get isMicrophoneEnabled(){return!(this.getTrackPublication(U.Source.Microphone)?.isMuted??!0)}get isScreenShareEnabled(){return!!this.getTrackPublication(U.Source.ScreenShare)}get isLocal(){return!1}get joinedAt(){return this.participantInfo?new Date(Number.parseInt(this.participantInfo.joinedAt.toString())*1e3):new Date}updateInfo(e){return this.participantInfo&&this.participantInfo.sid===e.sid&&this.participantInfo.version>e.version?!1:(this.identity=e.identity,this.sid=e.sid,this._setName(e.name),this._setMetadata(e.metadata),this._setAttributes(e.attributes),e.state===xa.ACTIVE&&this.participantInfo?.state!==xa.ACTIVE&&this.emit(R.Active),e.permission&&this.setPermissions(e.permission),this.participantInfo=e,!0)}_setMetadata(e){let t=this.metadata!==e,n=this.metadata;this.metadata=e,t&&this.emit(R.ParticipantMetadataChanged,n)}_setName(e){let t=this.name!==e;this.name=e,t&&this.emit(R.ParticipantNameChanged,e)}_setAttributes(e){let t=zl(this.attributes,e);this._attributes=e,Object.keys(t).length>0&&this.emit(R.AttributesChanged,t)}setPermissions(e){let t=this.permissions,n=e.canPublish!==this.permissions?.canPublish||e.canSubscribe!==this.permissions?.canSubscribe||e.canPublishData!==this.permissions?.canPublishData||e.hidden!==this.permissions?.hidden||e.recorder!==this.permissions?.recorder||e.canPublishSources.length!==this.permissions.canPublishSources.length||e.canPublishSources.some((e,t)=>e!==this.permissions?.canPublishSources[t])||e.canSubscribeMetrics!==this.permissions?.canSubscribeMetrics;return this.permissions=e,n&&this.emit(R.ParticipantPermissionsChanged,t),n}setIsSpeaking(e){e!==this.isSpeaking&&(this.isSpeaking=e,e&&(this.lastSpokeAt=new Date),this.emit(R.IsSpeakingChanged,e))}setConnectionQuality(e){let t=this._connectionQuality;this._connectionQuality=Zm(e),t!==this._connectionQuality&&this.emit(R.ConnectionQualityChanged,this._connectionQuality)}setDisconnected(){var e,t;this.activeFuture&&=((t=(e=this.activeFuture).reject)==null||t.call(e,Error(`Participant disconnected`)),void 0)}setAudioContext(e){this.audioContext=e,this.audioTrackPublications.forEach(t=>Uu(t.track)&&t.track.setAudioContext(e))}addTrackPublication(e){e.on(B.Muted,()=>{this.emit(R.TrackMuted,e)}),e.on(B.Unmuted,()=>{this.emit(R.TrackUnmuted,e)});let t=e;switch(t.track&&(t.track.sid=e.trackSid),this.trackPublications.set(e.trackSid,e),e.kind){case U.Kind.Audio:this.audioTrackPublications.set(e.trackSid,e);break;case U.Kind.Video:this.videoTrackPublications.set(e.trackSid,e);break}}};function $m(e){if(!e.participantSid&&!e.participantIdentity)throw Error(`Invalid track permission, must provide at least one of participantIdentity and participantSid`);return new Xo({participantIdentity:e.participantIdentity??``,participantSid:e.participantSid??``,allTracks:e.allowAll??!1,trackSids:e.allowedTrackSids||[]})}var eh=class extends Qm{constructor(e,t,n,r,i,a,o){super(e,t,void 0,void 0,void 0,{loggerName:r.loggerName,loggerContextCb:()=>this.engine.logContext}),this.pendingPublishing=new Set,this.pendingPublishPromises=new Map,this.participantTrackPermissions=[],this.allParticipantsAllowedToSubscribe=!0,this.encryptionType=j.NONE,this.enabledPublishVideoCodecs=[],this.pendingAcks=new Map,this.pendingResponses=new Map,this.handleReconnecting=()=>{this.reconnectFuture||=new Mu},this.handleReconnected=()=>{var e,t;(t=(e=this.reconnectFuture)?.resolve)==null||t.call(e),this.reconnectFuture=void 0,this.updateTrackSubscriptionPermissions()},this.handleClosing=()=>{var e,t,n,r,i,a;this.reconnectFuture&&=(this.reconnectFuture.promise.catch(e=>this.log.warn(e.message,this.logContext)),(t=(e=this.reconnectFuture)?.reject)==null||t.call(e,Error(`Got disconnected during reconnection attempt`)),void 0),this.signalConnectedFuture&&=((r=(n=this.signalConnectedFuture).reject)==null||r.call(n,Error(`Got disconnected without signal connected`)),void 0),(a=(i=this.activeAgentFuture)?.reject)==null||a.call(i,Error(`Got disconnected without active agent present`)),this.activeAgentFuture=void 0,this.firstActiveAgent=void 0},this.handleSignalConnected=e=>{var t,n;e.participant&&this.updateInfo(e.participant),this.signalConnectedFuture||=new Mu,(n=(t=this.signalConnectedFuture).resolve)==null||n.call(t)},this.handleSignalRequestResponse=e=>{let{requestId:t,reason:n,message:r}=e,i=this.pendingSignalRequests.get(t);switch(i&&(n!==us.OK&&i.reject(new fl(r,n)),this.pendingSignalRequests.delete(t)),e.request.case){case`publishDataTrack`:{let t;switch(e.reason){case us.NOT_ALLOWED:t=Om.notAllowed(e.message);break;case us.DUPLICATE_NAME:t=Om.duplicateName(e.message);break;case us.INVALID_NAME:t=Om.invalidName(e.message);break;case us.LIMIT_EXCEEDED:t=Om.limitReached(e.message);break;default:t=Om.unknown(e.reason,e.message);return}this.roomOutgoingDataTrackManager.receivedSfuPublishResponse(e.request.value.pubHandle,{type:`error`,error:t});break}}},this.handleDataPacket=e=>{switch(e.value.case){case`rpcResponse`:let t=e.value.value,n=null,r=null;t.value.case===`payload`?n=t.value.value:t.value.case===`error`&&(r=Df.fromProto(t.value.value)),this.handleIncomingRpcResponse(t.requestId,n,r);break;case`rpcAck`:let i=e.value.value;this.handleIncomingRpcAck(i.requestId);break}},this.updateTrackSubscriptionPermissions=()=>{this.log.debug(`updating track subscription permissions`,Object.assign(Object.assign({},this.logContext),{allParticipantsAllowed:this.allParticipantsAllowedToSubscribe,participantTrackPermissions:this.participantTrackPermissions})),this.engine.client.sendUpdateSubscriptionPermissions(this.allParticipantsAllowedToSubscribe,this.participantTrackPermissions.map(e=>$m(e)))},this.onTrackUnmuted=e=>{this.onTrackMuted(e,e.isUpstreamPaused)},this.onTrackMuted=(e,t)=>{if(t===void 0&&(t=!0),!e.sid){this.log.error(`could not update mute status for unpublished track`,Object.assign(Object.assign({},this.logContext),H(e)));return}this.engine.updateMuteStatus(e.sid,t)},this.onTrackUpstreamPaused=e=>{this.log.debug(`upstream paused`,Object.assign(Object.assign({},this.logContext),H(e))),this.onTrackMuted(e,!0)},this.onTrackUpstreamResumed=e=>{this.log.debug(`upstream resumed`,Object.assign(Object.assign({},this.logContext),H(e))),this.onTrackMuted(e,e.isMuted)},this.onTrackFeatureUpdate=e=>{let t=this.audioTrackPublications.get(e.sid);if(!t){this.log.warn(`Could not update local audio track settings, missing publication for track ${e.sid}`,this.logContext);return}this.engine.client.sendUpdateLocalAudioTrack(t.trackSid,t.getTrackFeatures())},this.onTrackCpuConstrained=(e,t)=>{this.log.debug(`track cpu constrained`,Object.assign(Object.assign({},this.logContext),H(t))),this.emit(R.LocalTrackCpuConstrained,e,t)},this.handleSubscribedQualityUpdate=e=>N(this,void 0,void 0,function*(){var t,n,r,i;if(!this.roomOptions?.dynacast)return;let a=this.videoTrackPublications.get(e.trackSid);if(!a){this.log.warn(`received subscribed quality update for unknown track`,Object.assign(Object.assign({},this.logContext),{trackSid:e.trackSid}));return}if(!a.videoTrack)return;let o=yield a.videoTrack.setPublishingCodecs(e.subscribedCodecs);try{for(var s=!0,c=Fs(o),l;l=yield c.next(),t=l.done,!t;s=!0){i=l.value,s=!1;let e=i;Sl(e)&&(this.log.debug(`publish ${e} for ${a.videoTrack.sid}`,Object.assign(Object.assign({},this.logContext),H(a))),yield this.publishAdditionalCodecForTrack(a.videoTrack,e,a.options))}}catch(e){n={error:e}}finally{try{!s&&!t&&(r=c.return)&&(yield r.call(c))}finally{if(n)throw n.error}}}),this.handleLocalTrackUnpublished=e=>{let t=this.trackPublications.get(e.trackSid);if(!t){this.log.warn(`received unpublished event for unknown track`,Object.assign(Object.assign({},this.logContext),{trackSid:e.trackSid}));return}this.unpublishTrack(t.track)},this.handleTrackEnded=e=>N(this,void 0,void 0,function*(){if(e.source===U.Source.ScreenShare||e.source===U.Source.ScreenShareAudio)this.log.debug(`unpublishing local track due to TrackEnded`,Object.assign(Object.assign({},this.logContext),H(e))),this.unpublishTrack(e);else if(e.isUserProvided)yield e.mute();else if(Ku(e)||Gu(e))try{if(mu())try{let t=yield navigator==null?void 0:navigator.permissions.query({name:e.source===U.Source.Camera?`camera`:`microphone`});if(t&&t.state===`denied`)throw this.log.warn(`user has revoked access to ${e.source}`,Object.assign(Object.assign({},this.logContext),H(e))),t.onchange=()=>{t.state!==`denied`&&(e.isMuted||e.restartTrack(),t.onchange=null)},Error(`GetUserMedia Permission denied`)}catch{}e.isMuted||(this.log.debug(`track ended, attempting to use a different device`,Object.assign(Object.assign({},this.logContext),H(e))),Ku(e)?yield e.restartTrack({deviceId:`default`}):yield e.restartTrack())}catch{this.log.warn(`could not restart track, muting instead`,Object.assign(Object.assign({},this.logContext),H(e))),yield e.mute()}}),this.audioTrackPublications=new Map,this.videoTrackPublications=new Map,this.trackPublications=new Map,this.engine=n,this.roomOptions=r,this.setupEngine(n),this.activeDeviceMap=new Map([[`audioinput`,`default`],[`videoinput`,`default`],[`audiooutput`,`default`]]),this.pendingSignalRequests=new Map,this.rpcHandlers=i,this.roomOutgoingDataStreamManager=a,this.roomOutgoingDataTrackManager=o}get lastCameraError(){return this.cameraError}get lastMicrophoneError(){return this.microphoneError}get isE2EEEnabled(){return this.encryptionType!==j.NONE}getTrackPublication(e){let t=super.getTrackPublication(e);if(t)return t}getTrackPublicationByName(e){let t=super.getTrackPublicationByName(e);if(t)return t}setupEngine(e){this.engine=e,this.engine.on(z.RemoteMute,(e,t)=>{let n=this.trackPublications.get(e);!n||!n.track||(t?n.mute():n.unmute())}),this.signalConnectedFuture?.isResolved&&(this.signalConnectedFuture=void 0),this.engine.on(z.Connected,this.handleReconnected).on(z.SignalConnected,this.handleSignalConnected).on(z.SignalRestarted,this.handleReconnected).on(z.SignalResumed,this.handleReconnected).on(z.Restarting,this.handleReconnecting).on(z.Resuming,this.handleReconnecting).on(z.LocalTrackUnpublished,this.handleLocalTrackUnpublished).on(z.SubscribedQualityUpdate,this.handleSubscribedQualityUpdate).on(z.Closing,this.handleClosing).on(z.SignalRequestResponse,this.handleSignalRequestResponse).on(z.DataPacketReceived,this.handleDataPacket)}setMetadata(e){return N(this,void 0,void 0,function*(){yield this.requestMetadataUpdate({metadata:e})})}setName(e){return N(this,void 0,void 0,function*(){yield this.requestMetadataUpdate({name:e})})}setAttributes(e){return N(this,void 0,void 0,function*(){yield this.requestMetadataUpdate({attributes:e})})}requestMetadataUpdate(e){return N(this,arguments,void 0,function(e){var t=this;let{metadata:n,name:r,attributes:i}=e;return function*(){return new Zc((e,a)=>N(t,void 0,void 0,function*(){try{let t=!1,o=yield this.engine.client.sendUpdateLocalMetadata(n??this.metadata??``,r??this.name??``,i),s=performance.now();for(this.pendingSignalRequests.set(o,{resolve:e,reject:e=>{a(e),t=!0},values:{name:r,metadata:n,attributes:i}});performance.now()-s<5e3&&!t;){if((!r||this.name===r)&&(!n||this.metadata===n)&&(!i||Object.entries(i).every(e=>{let[t,n]=e;return this.attributes[t]===n||n===``&&!this.attributes[t]}))){this.pendingSignalRequests.delete(o),e();return}yield Ql(50)}a(new fl(`Request to update local metadata timed out`,`TimeoutError`))}catch(e){e instanceof Error?a(e):a(Error(String(e)))}}))}()})}setCameraEnabled(e,t,n){return this.setTrackEnabled(U.Source.Camera,e,t,n)}setMicrophoneEnabled(e,t,n){return this.setTrackEnabled(U.Source.Microphone,e,t,n)}setScreenShareEnabled(e,t,n){return this.setTrackEnabled(U.Source.ScreenShare,e,t,n)}setE2EEEnabled(e){return N(this,void 0,void 0,function*(){this.encryptionType=e?j.GCM:j.NONE,yield this.republishAllTracks(void 0,!1)})}setTrackEnabled(e,t,n,r){return N(this,void 0,void 0,function*(){this.log.debug(`setTrackEnabled`,Object.assign(Object.assign({},this.logContext),{source:e,enabled:t})),this.republishPromise&&(yield this.republishPromise);let i=this.getTrackPublication(e);if(t)if(i)yield i.unmute();else{let t;if(this.pendingPublishing.has(e)){let t=yield this.waitForPendingPublicationOfSource(e);return t||this.log.info(`waiting for pending publication promise timed out`,Object.assign(Object.assign({},this.logContext),{source:e})),yield t?.unmute(),t}this.pendingPublishing.add(e);try{switch(e){case U.Source.Camera:t=yield this.createTracks({video:n??!0});break;case U.Source.Microphone:t=yield this.createTracks({audio:n??!0});break;case U.Source.ScreenShare:t=yield this.createScreenTracks(Object.assign({},n));break;default:throw new cl(e)}}catch(n){throw t?.forEach(e=>{e.stop()}),n instanceof Error&&this.emit(R.MediaDevicesError,n,Pl(e)),this.pendingPublishing.delete(e),n}for(let r of t){let t=Object.assign(Object.assign({},this.roomOptions.publishDefaults),n);e===U.Source.Microphone&&Uu(r)&&t.preConnectBuffer&&(this.log.info(`starting preconnect buffer for microphone`,Object.assign({},this.logContext)),r.startPreConnectBuffer())}try{let e=[];for(let n of t)this.log.info(`publishing track`,Object.assign(Object.assign({},this.logContext),H(n))),e.push(this.publishTrack(n,r));let n=yield Promise.all(e);[i]=n}catch(e){throw t?.forEach(e=>{e.stop()}),e}finally{this.pendingPublishing.delete(e)}}else if(!i?.track&&this.pendingPublishing.has(e)&&(i=yield this.waitForPendingPublicationOfSource(e),i||this.log.info(`waiting for pending publication promise timed out`,Object.assign(Object.assign({},this.logContext),{source:e}))),i&&i.track)if(e===U.Source.ScreenShare){i=yield this.unpublishTrack(i.track);let e=this.getTrackPublication(U.Source.ScreenShareAudio);e&&e.track&&this.unpublishTrack(e.track)}else yield i.mute();return i})}enableCameraAndMicrophone(){return N(this,void 0,void 0,function*(){if(!(this.pendingPublishing.has(U.Source.Camera)||this.pendingPublishing.has(U.Source.Microphone))){this.pendingPublishing.add(U.Source.Camera),this.pendingPublishing.add(U.Source.Microphone);try{let e=yield this.createTracks({audio:!0,video:!0});yield Promise.all(e.map(e=>this.publishTrack(e)))}finally{this.pendingPublishing.delete(U.Source.Camera),this.pendingPublishing.delete(U.Source.Microphone)}}})}createTracks(e){return N(this,void 0,void 0,function*(){e??={};let t=Ol(e,this.roomOptions?.audioCaptureDefaults,this.roomOptions?.videoCaptureDefaults);try{return(yield Jm(t,{loggerName:this.roomOptions.loggerName,loggerContextCb:()=>this.logContext})).map(e=>(Uu(e)&&(this.microphoneError=void 0,e.setAudioContext(this.audioContext),e.source=U.Source.Microphone,this.emit(R.AudioStreamAcquired)),Wu(e)&&(this.cameraError=void 0,e.source=U.Source.Camera),e))}catch(t){throw t instanceof Error&&(e.audio&&(this.microphoneError=t),e.video&&(this.cameraError=t)),t}})}createScreenTracks(e){return N(this,void 0,void 0,function*(){if(e===void 0&&(e={}),navigator.mediaDevices.getDisplayMedia===void 0)throw new sl(`getDisplayMedia not supported`);e.resolution===void 0&&!uu()&&(e.resolution=Dl.h1080fps30.resolution);let t=Fl(e),n=yield navigator.mediaDevices.getDisplayMedia(t),r=n.getVideoTracks();if(r.length===0)throw new cl(`no video track found`);let i=new ap(r[0],void 0,!1,{loggerName:this.roomOptions.loggerName,loggerContextCb:()=>this.logContext});i.source=U.Source.ScreenShare,e.contentHint&&(i.mediaStreamTrack.contentHint=e.contentHint);let a=[i];if(n.getAudioTracks().length>0){this.emit(R.AudioStreamAcquired);let e=new Bf(n.getAudioTracks()[0],void 0,!1,this.audioContext,{loggerName:this.roomOptions.loggerName,loggerContextCb:()=>this.logContext});e.source=U.Source.ScreenShareAudio,a.push(e)}return a})}publishTrack(e,t){return N(this,void 0,void 0,function*(){return this.publishOrRepublishTrack(e,t)})}publishOrRepublishTrack(e,t){return N(this,arguments,void 0,function(e,t){var n=this;let r=arguments.length>2&&arguments[2]!==void 0?arguments[2]:!1;return function*(){Ku(e)&&e.setAudioContext(n.audioContext),yield n.reconnectFuture?.promise,n.republishPromise&&!r&&(yield n.republishPromise),Hu(e)&&n.pendingPublishPromises.has(e)&&(yield n.pendingPublishPromises.get(e));let i;if(e instanceof MediaStreamTrack)i=e.getConstraints();else{i=e.constraints;let t;switch(e.source){case U.Source.Microphone:t=`audioinput`;break;case U.Source.Camera:t=`videoinput`}t&&n.activeDeviceMap.has(t)&&(i=Object.assign(Object.assign({},i),{deviceId:n.activeDeviceMap.get(t)}))}if(e instanceof MediaStreamTrack)switch(e.kind){case`audio`:e=new Bf(e,i,!0,n.audioContext,{loggerName:n.roomOptions.loggerName,loggerContextCb:()=>n.logContext});break;case`video`:e=new ap(e,i,!0,{loggerName:n.roomOptions.loggerName,loggerContextCb:()=>n.logContext});break;default:throw new cl(`unsupported MediaStreamTrack kind ${e.kind}`)}else e.updateLoggerOptions({loggerName:n.roomOptions.loggerName,loggerContextCb:()=>n.logContext});let a;if(n.trackPublications.forEach(t=>{t.track&&t.track===e&&(a=t)}),a)return n.log.warn(`track has already been published, skipping`,Object.assign(Object.assign({},n.logContext),H(a))),a;let o=Object.assign(Object.assign({},n.roomOptions.publishDefaults),t),s=`channelCount`in e.mediaStreamTrack.getSettings()&&e.mediaStreamTrack.getSettings().channelCount===2||e.mediaStreamTrack.getConstraints().channelCount===2,c=o.forceStereo??s;c&&(o.dtx===void 0&&n.log.info(`Opus DTX will be disabled for stereo tracks by default. Enable them explicitly to make it work.`,Object.assign(Object.assign({},n.logContext),H(e))),o.red===void 0&&n.log.info(`Opus RED will be disabled for stereo tracks by default. Enable them explicitly to make it work.`),o.dtx??=!1,o.red??=!1),!pu()&&n.roomOptions.e2ee&&(n.log.info(`End-to-end encryption is set up, simulcast publishing will be disabled on Safari versions and iOS browsers running iOS < v17.2`,Object.assign({},n.logContext)),o.simulcast=!1),o.source&&(e.source=o.source);let l=new Promise((t,r)=>N(n,void 0,void 0,function*(){try{if(this.engine.client.currentState!==W.CONNECTED){this.log.debug(`deferring track publication until signal is connected`,Object.assign(Object.assign({},this.logContext),{track:H(e)}));let n=!1,i=setTimeout(()=>{n=!0,e.stop(),r(new dl(`publishing rejected as engine not connected within timeout`,408))},15e3);if(yield this.waitUntilEngineConnected(),clearTimeout(i),n)return;t(yield this.publish(e,o,c))}else try{t(yield this.publish(e,o,c))}catch(e){r(e)}}catch(e){r(e)}}));n.pendingPublishPromises.set(e,l);try{return yield l}catch(e){throw e}finally{n.pendingPublishPromises.delete(e)}}()})}waitUntilEngineConnected(){return this.signalConnectedFuture||=new Mu,this.signalConnectedFuture.promise}hasPermissionsToPublish(e){if(!this.permissions)return this.log.warn(`no permissions present for publishing track`,Object.assign(Object.assign({},this.logContext),H(e))),!1;let{canPublish:t,canPublishSources:n}=this.permissions;return t&&(n.length===0||n.map(e=>Vl(e)).includes(e.source))?!0:(this.log.warn(`insufficient permissions to publish`,Object.assign(Object.assign({},this.logContext),H(e))),!1)}publish(e,t,n){return N(this,void 0,void 0,function*(){if(!this.hasPermissionsToPublish(e))throw new dl(`failed to publish track, insufficient permissions`,403);Array.from(this.trackPublications.values()).find(t=>Hu(e)&&t.source===e.source)&&e.source!==U.Source.Unknown&&this.log.info(`publishing a second track with the same source: ${e.source}`,Object.assign(Object.assign({},this.logContext),H(e))),t.stopMicTrackOnMute&&Uu(e)&&(e.stopOnMute=!0),e.source===U.Source.ScreenShare&&ou()&&(t.simulcast=!1),t.videoCodec===`av1`&&!tu()&&(t.videoCodec=void 0),t.videoCodec===`vp9`&&!nu()&&(t.videoCodec=void 0),t.videoCodec===void 0&&(t.videoCodec=gf),this.enabledPublishVideoCodecs.length>0&&(this.enabledPublishVideoCodecs.some(e=>t.videoCodec===Il(e.mime))||(t.videoCodec=Il(this.enabledPublishVideoCodecs[0].mime)));let r=t.videoCodec;e.on(B.Muted,this.onTrackMuted),e.on(B.Unmuted,this.onTrackUnmuted),e.on(B.Ended,this.handleTrackEnded),e.on(B.UpstreamPaused,this.onTrackUpstreamPaused),e.on(B.UpstreamResumed,this.onTrackUpstreamResumed),e.on(B.AudioTrackFeatureUpdate,this.onTrackFeatureUpdate);let i=[],a=!(t.dtx??!0),o=e.getSourceTrackSettings();o.autoGainControl&&i.push(ga.TF_AUTO_GAIN_CONTROL),o.echoCancellation&&i.push(ga.TF_ECHO_CANCELLATION),o.noiseSuppression&&i.push(ga.TF_NOISE_SUPPRESSION),o.channelCount&&o.channelCount>1&&i.push(ga.TF_STEREO),a&&i.push(ga.TF_NO_DTX),Ku(e)&&e.hasPreConnectBuffer&&i.push(ga.TF_PRECONNECT_BUFFER);let s=new mo({cid:e.mediaStreamTrack.id,name:t.name,type:U.kindToProto(e.kind),muted:e.isMuted,source:U.sourceToProto(e.source),disableDtx:a,encryption:this.encryptionType,stereo:n,disableRed:this.isE2EEEnabled||!(t.red??!0),stream:t?.stream,backupCodecPolicy:t?.backupCodecPolicy,audioFeatures:i}),c;if(e.kind===U.Kind.Video){let n={width:0,height:0};try{n=yield e.waitForDimensions()}catch{let t=this.roomOptions.videoCaptureDefaults?.resolution??Tl.h720.resolution;n={width:t.width,height:t.height},this.log.error(`could not determine track dimensions, using defaults`,Object.assign(Object.assign(Object.assign({},this.logContext),H(e)),{dims:n}))}s.width=n.width,s.height=n.height,Gu(e)&&(ru(r)&&(e.source===U.Source.ScreenShare&&(t.scalabilityMode=`L1T3`,`contentHint`in e.mediaStreamTrack&&(e.mediaStreamTrack.contentHint=`motion`,this.log.info(`forcing contentHint to motion for screenshare with SVC codecs`,Object.assign(Object.assign({},this.logContext),H(e))))),t.scalabilityMode=t.scalabilityMode??`L3T3_KEY`),s.simulcastCodecs=[new po({codec:r,cid:e.mediaStreamTrack.id})],t.backupCodec===!0&&(t.backupCodec={codec:gf}),t.backupCodec&&r!==t.backupCodec.codec&&s.encryption===j.NONE&&(this.roomOptions.dynacast||(this.roomOptions.dynacast=!0),s.simulcastCodecs.push(new po({codec:t.backupCodec.codec,cid:``})))),c=Yf(e.source===U.Source.ScreenShare,s.width,s.height,t),s.layers=cp(s.width,s.height,c,ru(t.videoCodec))}else e.kind===U.Kind.Audio&&(c=[{maxBitrate:t.audioPreset?.maxBitrate,priority:t.audioPreset?.priority??`high`,networkPriority:t.audioPreset?.priority??`high`}]);if(!this.engine||this.engine.isClosed)throw new I(`cannot publish track when not connected`);let l=()=>N(this,void 0,void 0,function*(){if(!this.engine.pcManager)throw new I(`pcManager is not ready`);if(e.sender=yield this.engine.createSender(e,t,c),this.emit(R.LocalSenderCreated,e.sender,e),Gu(e)&&(t.degradationPreference??=rp(e),e.setDegradationPreference(t.degradationPreference)),c)if(ou()&&e.kind===U.Kind.Audio){let t;for(let n of this.engine.pcManager.publisher.getTransceivers())if(n.sender===e.sender){t=n;break}t&&this.engine.pcManager.publisher.setTrackCodecBitrate({transceiver:t,codec:`opus`,maxbr:c[0]?.maxBitrate?c[0].maxBitrate/1e3:0})}else e.codec&&ru(e.codec)&&c[0]?.maxBitrate&&this.engine.pcManager.publisher.setTrackCodecBitrate({cid:s.cid,codec:e.codec,maxbr:c[0].maxBitrate/1e3});yield this.engine.negotiate()}),u,d=new Promise((t,n)=>N(this,void 0,void 0,function*(){try{u=yield this.engine.addTrack(s),t(u)}catch(t){e.sender&&this.engine.pcManager?.publisher&&(this.engine.pcManager.publisher.removeTrack(e.sender),yield this.engine.negotiate().catch(t=>{this.log.error(`failed to negotiate after removing track due to failed add track request`,Object.assign(Object.assign(Object.assign({},this.logContext),H(e)),{error:t}))})),n(t)}}));if(this.enabledPublishVideoCodecs.length>0)u=(yield Promise.all([d,l()]))[0];else{u=yield d;let n;if(u.codecs.forEach(e=>{n===void 0&&(n=e.mimeType)}),n&&e.kind===U.Kind.Video){let i=Il(n);i!==r&&(this.log.debug(`falling back to server selected codec`,Object.assign(Object.assign(Object.assign({},this.logContext),H(e)),{codec:i})),t.videoCodec=i,c=Yf(e.source===U.Source.ScreenShare,s.width,s.height,t))}yield l()}let f=new qm(e.kind,u,e,{loggerName:this.roomOptions.loggerName,loggerContextCb:()=>this.logContext});if(f.on(B.CpuConstrained,e=>this.onTrackCpuConstrained(e,f)),f.options=t,e.sid=u.sid,this.log.debug(`publishing ${e.kind} with encodings`,Object.assign(Object.assign({},this.logContext),{encodings:c,trackInfo:u})),Gu(e)?e.startMonitor(this.engine.client):Ku(e)&&e.startMonitor(),this.addTrackPublication(f),this.emit(R.LocalTrackPublished,f),Ku(e)&&u.audioFeatures.includes(ga.TF_PRECONNECT_BUFFER)){let t=e.getPreConnectBuffer(),n=e.getPreConnectBufferMimeType();this.on(R.LocalTrackSubscribed,t=>{if(t.trackSid===u.sid){if(!e.hasPreConnectBuffer){this.log.warn(`subscribe event came to late, buffer already closed`,this.logContext);return}this.log.debug(`finished recording preconnect buffer`,Object.assign(Object.assign({},this.logContext),H(e))),e.stopPreConnectBuffer()}}),t&&new Promise((r,i)=>N(this,void 0,void 0,function*(){var a,s,c,l;try{this.log.debug(`waiting for agent`,Object.assign(Object.assign({},this.logContext),H(e)));let m=setTimeout(()=>{i(Error(`agent not active within 10 seconds`))},1e4),ee=yield this.waitUntilActiveAgentPresent();clearTimeout(m),this.log.debug(`sending preconnect buffer`,Object.assign(Object.assign({},this.logContext),H(e)));let h=yield this.streamBytes({name:`preconnect-buffer`,mimeType:n,topic:`lk.agent.pre-connect-audio-buffer`,destinationIdentities:[ee.identity],attributes:{trackId:f.trackSid,sampleRate:String(o.sampleRate??`48000`),channels:String(o.channelCount??`1`)}});try{for(var u=!0,d=Fs(t),p;p=yield d.next(),a=p.done,!a;u=!0){l=p.value,u=!1;let e=l;yield h.write(e)}}catch(e){s={error:e}}finally{try{!u&&!a&&(c=d.return)&&(yield c.call(d))}finally{if(s)throw s.error}}yield h.close(),r()}catch(e){i(e)}})).then(()=>{this.log.debug(`preconnect buffer sent successfully`,Object.assign(Object.assign({},this.logContext),H(e)))}).catch(t=>{this.log.error(`error sending preconnect buffer`,Object.assign(Object.assign(Object.assign({},this.logContext),H(e)),{error:t}))})}return f})}get isLocal(){return!0}publishAdditionalCodecForTrack(e,t,n){return N(this,void 0,void 0,function*(){if(this.encryptionType!==j.NONE)return;let r;if(this.trackPublications.forEach(t=>{t.track&&t.track===e&&(r=t)}),!r)throw new cl(`track is not published`);if(!Gu(e))throw new cl(`track is not a video track`);let i=Object.assign(Object.assign({},this.roomOptions?.publishDefaults),n),a=Xf(e,t,i);if(!a){this.log.info(`backup codec has been disabled, ignoring request to add additional codec for track`,Object.assign(Object.assign({},this.logContext),H(e)));return}let o=e.addSimulcastTrack(t,a);if(!o)return;let s=new mo({cid:o.mediaStreamTrack.id,type:U.kindToProto(e.kind),muted:e.isMuted,source:U.sourceToProto(e.source),sid:e.sid,simulcastCodecs:[{codec:i.videoCodec,cid:o.mediaStreamTrack.id}]});if(s.layers=cp(s.width,s.height,a),!this.engine||this.engine.isClosed)throw new I(`cannot publish track when not connected`);let c=(yield Promise.all([this.engine.addTrack(s),N(this,void 0,void 0,function*(){yield this.engine.createSimulcastSender(e,o,i,a),yield this.engine.negotiate()})]))[0];this.log.debug(`published ${t} for track ${e.sid}`,Object.assign(Object.assign({},this.logContext),{encodings:a,trackInfo:c}))})}unpublishTrack(e,t){return N(this,void 0,void 0,function*(){if(Hu(e)){let t=this.pendingPublishPromises.get(e);t&&(this.log.info(`awaiting publish promise before attempting to unpublish`,Object.assign(Object.assign({},this.logContext),H(e))),yield t)}let n=this.getPublicationForTrack(e),r=n?H(n):void 0;if(this.log.debug(`unpublishing track`,Object.assign(Object.assign({},this.logContext),r)),!n||!n.track){this.log.warn(`track was not unpublished because no publication was found`,Object.assign(Object.assign({},this.logContext),r));return}e=n.track,e.off(B.Muted,this.onTrackMuted),e.off(B.Unmuted,this.onTrackUnmuted),e.off(B.Ended,this.handleTrackEnded),e.off(B.UpstreamPaused,this.onTrackUpstreamPaused),e.off(B.UpstreamResumed,this.onTrackUpstreamResumed),e.off(B.AudioTrackFeatureUpdate,this.onTrackFeatureUpdate),t===void 0&&(t=this.roomOptions?.stopLocalTrackOnUnpublish??!0),t?e.stop():e.stopMonitor();let i=!1,a=e.sender;if(e.sender=void 0,this.engine.pcManager&&this.engine.pcManager.currentState<G.FAILED&&a)try{for(let e of this.engine.pcManager.publisher.getTransceivers())e.sender===a&&(e.direction=`inactive`,i=!0);if(this.engine.removeTrack(a)&&(i=!0),Gu(e)){for(let[,t]of e.simulcastCodecs)t.sender&&=(this.engine.removeTrack(t.sender)&&(i=!0),void 0);e.simulcastCodecs.clear()}}catch(e){this.log.warn(`failed to unpublish track`,Object.assign(Object.assign(Object.assign({},this.logContext),r),{error:e}))}switch(this.trackPublications.delete(n.trackSid),n.kind){case U.Kind.Audio:this.audioTrackPublications.delete(n.trackSid);break;case U.Kind.Video:this.videoTrackPublications.delete(n.trackSid);break}return this.emit(R.LocalTrackUnpublished,n),n.setTrack(void 0),i&&(yield this.engine.negotiate()),n})}unpublishTracks(e){return N(this,void 0,void 0,function*(){return(yield Promise.all(e.map(e=>this.unpublishTrack(e)))).filter(e=>!!e)})}republishAllTracks(e){return N(this,arguments,void 0,function(e){var t=this;let n=arguments.length>1&&arguments[1]!==void 0?arguments[1]:!0;return function*(){t.republishPromise&&(yield t.republishPromise),t.republishPromise=new Zc((r,i)=>N(t,void 0,void 0,function*(){try{let t=[];this.trackPublications.forEach(n=>{n.track&&(e&&(n.options=Object.assign(Object.assign({},n.options),e)),t.push(n))}),yield Promise.all(t.map(e=>N(this,void 0,void 0,function*(){let t=e.track;yield this.unpublishTrack(t,!1),n&&!t.isMuted&&t.source!==U.Source.ScreenShare&&t.source!==U.Source.ScreenShareAudio&&(Ku(t)||Gu(t))&&!t.isUserProvided&&(this.log.debug(`restarting existing track`,Object.assign(Object.assign({},this.logContext),{track:e.trackSid})),yield t.restartTrack()),yield this.publishOrRepublishTrack(t,e.options,!0)}))),r()}catch(e){e instanceof Error?i(e):i(Error(String(e)))}finally{this.republishPromise=void 0}})),yield t.republishPromise}()})}publishData(e){return N(this,arguments,void 0,function(e){var t=this;let n=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{};return function*(){let r=n.reliable?K.RELIABLE:K.LOSSY,i=n.reliable?ja.RELIABLE:ja.LOSSY,a=n.destinationIdentities,o=n.topic,s=new Aa({kind:i,value:{case:`user`,value:new Ia({participantIdentity:t.identity,payload:e,destinationIdentities:a,topic:o})}});yield t.engine.sendDataPacket(s,r)}()})}publishDtmf(e,t){return N(this,void 0,void 0,function*(){let n=new Aa({kind:ja.RELIABLE,value:{case:`sipDtmf`,value:new La({code:e,digit:t})}});yield this.engine.sendDataPacket(n,K.RELIABLE)})}sendChatMessage(e,t){return N(this,void 0,void 0,function*(){let n={id:crypto.randomUUID(),message:e,timestamp:Date.now(),attachedFiles:t?.attachments},r=new Aa({value:{case:`chatMessage`,value:new Ba(Object.assign(Object.assign({},n),{timestamp:D.parse(n.timestamp)}))}});return yield this.engine.sendDataPacket(r,K.RELIABLE),this.emit(R.ChatMessage,n),n})}editChatMessage(e,t){return N(this,void 0,void 0,function*(){let n=Object.assign(Object.assign({},t),{message:e,editTimestamp:Date.now()}),r=new Aa({value:{case:`chatMessage`,value:new Ba(Object.assign(Object.assign({},n),{timestamp:D.parse(n.timestamp),editTimestamp:D.parse(n.editTimestamp)}))}});return yield this.engine.sendDataPacket(r,K.RELIABLE),this.emit(R.ChatMessage,n),n})}sendText(e,t){return N(this,void 0,void 0,function*(){return this.roomOutgoingDataStreamManager.sendText(e,t)})}streamText(e){return N(this,void 0,void 0,function*(){return this.roomOutgoingDataStreamManager.streamText(e)})}sendFile(e,t){return N(this,void 0,void 0,function*(){return this.roomOutgoingDataStreamManager.sendFile(e,t)})}streamBytes(e){return N(this,void 0,void 0,function*(){return this.roomOutgoingDataStreamManager.streamBytes(e)})}performRpc(e){let{destinationIdentity:t,method:n,payload:r,responseTimeout:i=15e3}=e,a=7e3;return a+1e3,new Zc((e,o)=>N(this,void 0,void 0,function*(){if(kf(r)>Of){o(Df.builtIn(`REQUEST_PAYLOAD_TOO_LARGE`));return}if(this.engine.latestJoinResponse?.serverInfo?.version&&xu(this.engine.latestJoinResponse?.serverInfo?.version,`1.8.0`)<0){o(Df.builtIn(`UNSUPPORTED_SERVER`));return}let s=Math.max(i,8e3),c=crypto.randomUUID();yield this.publishRpcRequest(t,c,n,r,s);let l=setTimeout(()=>{this.pendingAcks.delete(c),o(Df.builtIn(`CONNECTION_TIMEOUT`)),this.pendingResponses.delete(c),clearTimeout(u)},a);this.pendingAcks.set(c,{resolve:()=>{clearTimeout(l)},participantIdentity:t});let u=setTimeout(()=>{this.pendingResponses.delete(c),o(Df.builtIn(`RESPONSE_TIMEOUT`))},i);this.pendingResponses.set(c,{resolve:(t,n)=>{clearTimeout(u),this.pendingAcks.has(c)&&(this.log.warn(`RPC response received before ack`,c),this.pendingAcks.delete(c),clearTimeout(l)),n?o(n):e(t??``)},participantIdentity:t})}))}registerRpcMethod(e,t){this.rpcHandlers.has(e)&&this.log.warn(`you're overriding the RPC handler for method ${e}, in the future this will throw an error`),this.rpcHandlers.set(e,t)}unregisterRpcMethod(e){this.rpcHandlers.delete(e)}setTrackSubscriptionPermissions(e){this.participantTrackPermissions=arguments.length>1&&arguments[1]!==void 0?arguments[1]:[],this.allParticipantsAllowedToSubscribe=e,this.engine.client.isDisconnected||this.updateTrackSubscriptionPermissions()}handleIncomingRpcAck(e){let t=this.pendingAcks.get(e);t?(t.resolve(),this.pendingAcks.delete(e)):console.error(`Ack received for unexpected RPC request`,e)}handleIncomingRpcResponse(e,t,n){let r=this.pendingResponses.get(e);r?(r.resolve(t,n),this.pendingResponses.delete(e)):console.error(`Response received for unexpected RPC request`,e)}publishRpcRequest(e,t,n,r,i){return N(this,void 0,void 0,function*(){let a=new Aa({destinationIdentities:[e],kind:ja.RELIABLE,value:{case:`rpcRequest`,value:new Va({id:t,method:n,payload:r,responseTimeoutMs:i,version:1})}});yield this.engine.sendDataPacket(a,K.RELIABLE)})}handleParticipantDisconnected(e){for(let[t,{participantIdentity:n}]of this.pendingAcks)n===e&&this.pendingAcks.delete(t);for(let[t,{participantIdentity:n,resolve:r}]of this.pendingResponses)n===e&&(r(null,Df.builtIn(`RECIPIENT_DISCONNECTED`)),this.pendingResponses.delete(t))}setEnabledPublishCodecs(e){this.enabledPublishVideoCodecs=e.filter(e=>e.mime.split(`/`)[0].toLowerCase()===`video`)}updateInfo(e){return super.updateInfo(e)?(e.tracks.forEach(e=>{let t=this.trackPublications.get(e.sid);if(t){let n=t.isMuted||(t.track?.isUpstreamPaused??!1);n!==e.muted&&(this.log.debug(`updating server mute state after reconcile`,Object.assign(Object.assign(Object.assign({},this.logContext),H(t)),{mutedOnServer:n})),this.engine.client.sendMuteTrack(e.sid,n))}}),!0):!1}setActiveAgent(e){var t,n,r,i;this.firstActiveAgent=e,e&&!this.firstActiveAgent&&(this.firstActiveAgent=e),e?(n=(t=this.activeAgentFuture)?.resolve)==null||n.call(t,e):(i=(r=this.activeAgentFuture)?.reject)==null||i.call(r,Error(`Agent disconnected`)),this.activeAgentFuture=void 0}waitUntilActiveAgentPresent(){return this.firstActiveAgent?Promise.resolve(this.firstActiveAgent):(this.activeAgentFuture||=new Mu,this.activeAgentFuture.promise)}getPublicationForTrack(e){let t;return this.trackPublications.forEach(n=>{let r=n.track;r&&(e instanceof MediaStreamTrack?(Ku(r)||Gu(r))&&r.mediaStreamTrack===e&&(t=n):e===r&&(t=n))}),t}waitForPendingPublicationOfSource(e){return N(this,void 0,void 0,function*(){let t=Date.now();for(;Date.now()<t+1e4;){let t=Array.from(this.pendingPublishPromises.entries()).find(t=>{let[n]=t;return n.source===e});if(t)return t[1];yield Ql(20)}})}publishDataTrack(e){return N(this,void 0,void 0,function*(){let t=new Nm(e,this.roomOutgoingDataTrackManager);return yield t.publish(),t})}},th=class extends DOMException{constructor(e,t){super(e,`AbortError`),this.reason=t}},nh=class extends Map{constructor(){super(...arguments),this.pending=new Map}set(e,t){var n;super.set(e,t);let r=this.pending.get(e);if(r){for(let e of r)e.isResolved||(n=e.resolve)==null||n.call(e,t);this.pending.delete(e)}return this}get[Symbol.toStringTag](){return`WaitableMap`}getDeferred(e,t){return N(this,void 0,void 0,function*(){let n=this.get(e);if(n!==void 0)return n;if(t?.aborted)throw new th(`The operation was aborted.`,t.reason);let r=new Mu(void 0,()=>{let t=this.pending.get(e);if(!t)return;let n=t.indexOf(r);n!==-1&&t.splice(n,1),t.length===0&&this.pending.delete(e)}),i=this.pending.get(e);if(i?i.push(r):this.pending.set(e,[r]),t){let e=()=>{var e;r.isResolved||(e=r.reject)==null||e.call(r,new th(`The operation was aborted.`,t.reason))};t.addEventListener(`abort`,e,{once:!0}),r.promise.finally(()=>{t.removeEventListener(`abort`,e)})}return r.promise})}},rh=class extends Km{constructor(e,t,n,r){super(e,t.sid,t.name,r),this.track=void 0,this.allowed=!0,this.requestedDisabled=void 0,this.visible=!0,this.handleEnded=e=>{this.setTrack(void 0),this.emit(B.Ended,e)},this.handleVisibilityChange=e=>{this.log.debug(`adaptivestream video visibility ${this.trackSid}, visible=${e}`,this.logContext),this.visible=e,this.emitTrackUpdate()},this.handleVideoDimensionsChange=e=>{this.log.debug(`adaptivestream video dimensions ${e.width}x${e.height}`,this.logContext),this.videoDimensionsAdaptiveStream=e,this.emitTrackUpdate()},this.subscribed=n,this.updateInfo(t)}setSubscribed(e){let t=this.subscriptionStatus,n=this.permissionStatus;this.subscribed=e,e&&(this.allowed=!0);let r=new ko({trackSids:[this.trackSid],subscribe:this.subscribed,participantTracks:[new Ga({participantSid:``,trackSids:[this.trackSid]})]});this.emit(B.UpdateSubscription,r),this.emitSubscriptionUpdateIfChanged(t),this.emitPermissionUpdateIfChanged(n)}get subscriptionStatus(){return this.subscribed===!1?Km.SubscriptionStatus.Unsubscribed:super.isSubscribed?Km.SubscriptionStatus.Subscribed:Km.SubscriptionStatus.Desired}get permissionStatus(){return this.allowed?Km.PermissionStatus.Allowed:Km.PermissionStatus.NotAllowed}get isSubscribed(){return this.subscribed===!1?!1:super.isSubscribed}get isDesired(){return this.subscribed!==!1}get isEnabled(){return this.requestedDisabled===void 0?this.isAdaptiveStream?this.visible:!0:!this.requestedDisabled}get isLocal(){return!1}setEnabled(e){!this.isManualOperationAllowed()||this.requestedDisabled===!e||(this.requestedDisabled=!e,this.emitTrackUpdate())}setVideoQuality(e){!this.isManualOperationAllowed()||this.requestedMaxQuality===e||(this.requestedMaxQuality=e,this.requestedVideoDimensions=void 0,this.emitTrackUpdate())}setVideoDimensions(e){this.isManualOperationAllowed()&&(this.requestedVideoDimensions?.width===e.width&&this.requestedVideoDimensions?.height===e.height||(Yu(this.track)&&(this.requestedVideoDimensions=e),this.requestedMaxQuality=void 0,this.emitTrackUpdate()))}setVideoFPS(e){this.isManualOperationAllowed()&&Yu(this.track)&&this.fps!==e&&(this.fps=e,this.emitTrackUpdate())}get videoQuality(){return this.requestedMaxQuality??Kl.HIGH}setTrack(e){let t=this.subscriptionStatus,n=this.permissionStatus,r=this.track;r!==e&&(r&&(r.off(B.VideoDimensionsChanged,this.handleVideoDimensionsChange),r.off(B.VisibilityChanged,this.handleVisibilityChange),r.off(B.Ended,this.handleEnded),r.detach(),r.stopMonitor(),this.emit(B.Unsubscribed,r)),super.setTrack(e),e&&(e.sid=this.trackSid,e.on(B.VideoDimensionsChanged,this.handleVideoDimensionsChange),e.on(B.VisibilityChanged,this.handleVisibilityChange),e.on(B.Ended,this.handleEnded),this.emit(B.Subscribed,e)),this.emitPermissionUpdateIfChanged(n),this.emitSubscriptionUpdateIfChanged(t))}setAllowed(e){let t=this.subscriptionStatus,n=this.permissionStatus;this.allowed=e,this.emitPermissionUpdateIfChanged(n),this.emitSubscriptionUpdateIfChanged(t)}setSubscriptionError(e){this.emit(B.SubscriptionFailed,e)}updateInfo(e){super.updateInfo(e);let t=this.metadataMuted;this.metadataMuted=e.muted,this.track?this.track.setMuted(e.muted):t!==e.muted&&this.emit(e.muted?B.Muted:B.Unmuted)}emitSubscriptionUpdateIfChanged(e){let t=this.subscriptionStatus;e!==t&&this.emit(B.SubscriptionStatusChanged,t,e)}emitPermissionUpdateIfChanged(e){this.permissionStatus!==e&&this.emit(B.SubscriptionPermissionChanged,this.permissionStatus,e)}isManualOperationAllowed(){return this.isDesired?!0:(this.log.warn(`cannot update track settings when not subscribed`,this.logContext),!1)}get isAdaptiveStream(){return Yu(this.track)&&this.track.isAdaptiveStream}emitTrackUpdate(){let e=new Mo({trackSids:[this.trackSid],disabled:!this.isEnabled,fps:this.fps});if(this.kind===U.Kind.Video){let t=this.requestedVideoDimensions;if(this.videoDimensionsAdaptiveStream!==void 0)if(t)Hl(this.videoDimensionsAdaptiveStream,t)&&(this.log.debug(`using adaptive stream dimensions instead of requested`,Object.assign(Object.assign({},this.logContext),this.videoDimensionsAdaptiveStream)),t=this.videoDimensionsAdaptiveStream);else if(this.requestedMaxQuality!==void 0&&this.trackInfo){let e=Ul(this.trackInfo,this.requestedMaxQuality);e&&Hl(this.videoDimensionsAdaptiveStream,e)&&(this.log.debug(`using adaptive stream dimensions instead of max quality layer`,Object.assign(Object.assign({},this.logContext),this.videoDimensionsAdaptiveStream)),t=this.videoDimensionsAdaptiveStream)}else this.log.debug(`using adaptive stream dimensions`,Object.assign(Object.assign({},this.logContext),this.videoDimensionsAdaptiveStream)),t=this.videoDimensionsAdaptiveStream;t?(e.width=Math.ceil(t.width),e.height=Math.ceil(t.height)):this.requestedMaxQuality===void 0?(this.log.debug(`using default quality`,Object.assign(Object.assign({},this.logContext),{quality:Kl.HIGH})),e.quality=Kl.HIGH):(this.log.debug(`using requested max quality`,Object.assign(Object.assign({},this.logContext),{quality:this.requestedMaxQuality})),e.quality=this.requestedMaxQuality)}this.emit(B.UpdateSettings,e)}},ih=class e extends Qm{static fromParticipantInfo(t,n,r){return new e(t,n.sid,n.identity,n.name,n.metadata,n.attributes,r,n.kind)}get logContext(){return Object.assign(Object.assign({},super.logContext),{remoteParticipantID:this.sid,remoteParticipant:this.identity})}constructor(e,t,n,r,i,a,o){let s=arguments.length>7&&arguments[7]!==void 0?arguments[7]:Sa.STANDARD;super(t,n||``,r,i,a,o,s),this.signalClient=e,this.trackPublications=new Map,this.audioTrackPublications=new Map,this.videoTrackPublications=new Map,this.dataTracks=new nh,this.volumeMap=new Map}addTrackPublication(e){super.addTrackPublication(e),e.on(B.UpdateSettings,t=>{this.log.debug(`send update settings`,Object.assign(Object.assign(Object.assign({},this.logContext),H(e)),{settings:t})),this.signalClient.sendUpdateTrackSettings(t)}),e.on(B.UpdateSubscription,e=>{e.participantTracks.forEach(e=>{e.participantSid=this.sid}),this.signalClient.sendUpdateSubscription(e)}),e.on(B.SubscriptionPermissionChanged,t=>{this.emit(R.TrackSubscriptionPermissionChanged,e,t)}),e.on(B.SubscriptionStatusChanged,t=>{this.emit(R.TrackSubscriptionStatusChanged,e,t)}),e.on(B.Subscribed,t=>{this.emit(R.TrackSubscribed,t,e)}),e.on(B.Unsubscribed,t=>{this.emit(R.TrackUnsubscribed,t,e)}),e.on(B.SubscriptionFailed,t=>{this.emit(R.TrackSubscriptionFailed,e.trackSid,t)})}getTrackPublication(e){let t=super.getTrackPublication(e);if(t)return t}getTrackPublicationByName(e){let t=super.getTrackPublicationByName(e);if(t)return t}setVolume(e){let t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:U.Source.Microphone;this.volumeMap.set(t,e);let n=this.getTrackPublication(t);n&&n.track&&n.track.setVolume(e)}getVolume(){let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:U.Source.Microphone,t=this.getTrackPublication(e);return t&&t.track?t.track.getVolume():this.volumeMap.get(e)}addSubscribedMediaTrack(e,t,n,r,i,a){let o=this.getTrackPublicationBySid(t);if(o||t.startsWith(`TR`)||this.trackPublications.forEach(t=>{!o&&e.kind===t.kind.toString()&&(o=t)}),!o){if(a===0){this.log.error(`could not find published track`,Object.assign(Object.assign({},this.logContext),{trackSid:t})),this.emit(R.TrackSubscriptionFailed,t);return}a===void 0&&(a=20),setTimeout(()=>{this.addSubscribedMediaTrack(e,t,n,r,i,a-1)},150);return}if(e.readyState===`ended`){this.log.error(`unable to subscribe because MediaStreamTrack is ended. Do not call MediaStreamTrack.stop()`,Object.assign(Object.assign({},this.logContext),H(o))),this.emit(R.TrackSubscriptionFailed,t);return}let s=e.kind===`video`,c;return c=s?new Hm(e,t,r,i):new Bm(e,t,r,this.audioContext,this.audioOutput),c.source=o.source,c.isMuted=o.isMuted,c.setMediaStream(n),c.start(),o.setTrack(c),this.volumeMap.has(o.source)&&qu(c)&&Uu(c)&&c.setVolume(this.volumeMap.get(o.source)),o}get hasMetadata(){return!!this.participantInfo}getTrackPublicationBySid(e){return this.trackPublications.get(e)}updateInfo(e){if(!super.updateInfo(e))return!1;let t=new Map,n=new Map;return e.tracks.forEach(e=>{let r=this.getTrackPublicationBySid(e.sid);if(r)r.updateInfo(e);else{let t=U.kindFromProto(e.type);if(!t)return;r=new rh(t,e,this.signalClient.connectOptions?.autoSubscribe,{loggerContextCb:()=>this.logContext,loggerName:this.loggerOptions?.loggerName}),r.updateInfo(e),n.set(e.sid,r);let i=Array.from(this.trackPublications.values()).find(e=>e.source===r?.source);i&&r.source!==U.Source.Unknown&&this.log.debug(`received a second track publication for ${this.identity} with the same source: ${r.source}`,Object.assign(Object.assign({},this.logContext),{oldTrack:H(i),newTrack:H(r)})),this.addTrackPublication(r)}t.set(e.sid,r)}),this.trackPublications.forEach(e=>{t.has(e.trackSid)||(this.log.trace(`detected removed track on remote participant, unpublishing`,Object.assign(Object.assign({},this.logContext),H(e))),this.unpublishTrack(e.trackSid,!0))}),n.forEach(e=>{this.emit(R.TrackPublished,e)}),!0}unpublishTrack(e,t){let n=this.trackPublications.get(e);if(!n)return;let{track:r}=n;switch(r&&(r.stop(),n.setTrack(void 0)),this.trackPublications.delete(e),n.kind){case U.Kind.Audio:this.audioTrackPublications.delete(e);break;case U.Kind.Video:this.videoTrackPublications.delete(e);break}t&&this.emit(R.TrackUnpublished,n)}setAudioOutput(e){return N(this,void 0,void 0,function*(){this.audioOutput=e;let t=[];this.audioTrackPublications.forEach(n=>{Uu(n.track)&&qu(n.track)&&t.push(n.track.setSinkId(e.deviceId??`default`))}),yield Promise.all(t)})}addRemoteDataTrack(e){this.dataTracks.set(e.info.name,e)}removeRemoteDataTrack(e){for(let[t,n]of this.dataTracks.entries())e===n.info.sid&&this.dataTracks.delete(t)}emit(e){var t=[...arguments].slice(1);return this.log.trace(`participant event`,Object.assign(Object.assign({},this.logContext),{event:e,args:t})),super.emit(e,...t)}},Y;(function(e){e.Disconnected=`disconnected`,e.Connecting=`connecting`,e.Connected=`connected`,e.Reconnecting=`reconnecting`,e.SignalReconnecting=`signalReconnecting`})(Y||={});var ah=4*1e3,oh=class e extends zs.EventEmitter{get hasE2EESetup(){return this.e2eeManager!==void 0}constructor(t){var n,r,i;if(super(),n=this,this.state=Y.Disconnected,this.activeSpeakers=[],this.isE2EEEnabled=!1,this.audioEnabled=!0,this.isVideoPlaybackBlocked=!1,this.log=M,this.bufferedEvents=[],this.isResuming=!1,this.rpcHandlers=new Map,this.connect=(e,t,n)=>N(this,void 0,void 0,function*(){if(!au())throw hu()?Error(`WebRTC isn't detected, have you called registerGlobals?`):Error(`LiveKit doesn't seem to be supported on this browser. Try to update your browser and make sure no browser extensions are disabling webRTC.`);let r=yield this.disconnectLock.lock();if(this.state===Y.Connected)return this.log.info(`already connected to room ${this.name}`,this.logContext),r(),Promise.resolve();if(this.connectFuture)return r(),this.connectFuture.promise;this.setAndEmitConnectionState(Y.Connecting),this.regionUrlProvider?.getServerUrl().toString()!==rd(e)&&(this.regionUrl=void 0,this.regionUrlProvider=void 0),gu(new URL(e))&&(this.regionUrlProvider===void 0?this.regionUrlProvider=new Tf(e,t):this.regionUrlProvider.updateToken(t),this.regionUrlProvider.fetchRegionSettings().then(e=>{var t;(t=this.regionUrlProvider)==null||t.setServerReportedRegions(e)}).catch(e=>{this.log.warn(`could not fetch region settings`,Object.assign(Object.assign({},this.logContext),{error:e}))}));let i=(a,o,s)=>N(this,void 0,void 0,function*(){this.abortController&&this.abortController.abort();let c=new AbortController;this.abortController=c,r?.();try{if(yield bd.getInstance().getBackOffPromise(e),c.signal.aborted)throw F.cancelled(`Connection attempt aborted`);yield this.attemptConnection(s??e,t,n,c),this.abortController=void 0,a()}catch(t){if(this.regionUrlProvider&&t instanceof F&&t.reason!==P.Cancelled&&t.reason!==P.NotAllowed){let n=null;try{this.log.debug(`Fetching next region`),n=yield this.regionUrlProvider.getNextBestRegionUrl(this.abortController?.signal)}catch(e){if(e instanceof F&&(e.status===401||e.reason===P.Cancelled)){this.handleDisconnect(this.options.stopLocalTrackOnUnpublish),o(e);return}}[P.InternalError,P.ServerUnreachable,P.Timeout].includes(t.reason)&&(this.log.debug(`Adding failed connection attempt to back off`),bd.getInstance().addFailedConnectionAttempt(e)),n&&!this.abortController?.signal.aborted?(this.log.info(`Initial connection failed with ConnectionError: ${t.message}. Retrying with another region: ${n}`,this.logContext),this.recreateEngine(!0),yield i(a,o,n)):(this.handleDisconnect(this.options.stopLocalTrackOnUnpublish,zu(t)),o(t))}else{let e=pa.UNKNOWN_REASON;t instanceof F&&(e=zu(t)),this.handleDisconnect(this.options.stopLocalTrackOnUnpublish,e),o(t)}}}),a=this.regionUrl;return this.regionUrl=void 0,this.connectFuture=new Mu((e,t)=>{i(e,t,a)},()=>{this.clearConnectionFutures()}),this.connectFuture.promise}),this.connectSignal=(e,t,n,r,i,a)=>N(this,void 0,void 0,function*(){let o=yield n.join(e,t,{autoSubscribe:r.autoSubscribe,adaptiveStream:typeof i.adaptiveStream==`object`?!0:i.adaptiveStream,maxRetries:r.maxRetries,e2eeEnabled:!!this.e2eeManager,websocketTimeout:r.websocketTimeout},a.signal,!i.singlePeerConnection),s=o.serverInfo;if(s||={version:o.serverVersion,region:o.serverRegion},this.serverInfo=s,this.log.debug(`connected to Livekit Server ${Object.entries(s).map(e=>{let[t,n]=e;return`${t}: ${n}`}).join(`, `)}`,{room:o.room?.name,roomSid:o.room?.sid,identity:o.participant?.identity}),!s.version)throw new ll(`unknown server version`);return s.version===`0.15.1`&&this.options.dynacast&&(this.log.debug(`disabling dynacast due to server version`,this.logContext),i.dynacast=!1),o}),this.applyJoinResponse=e=>{let t=e.participant;if(this.localParticipant.sid=t.sid,this.localParticipant.identity=t.identity,this.localParticipant.setEnabledPublishCodecs(e.enabledPublishCodecs),this.e2eeManager)try{this.e2eeManager.setSifTrailer(e.sifTrailer)}catch(e){this.log.error(e instanceof Error?e.message:`Could not set SifTrailer`,Object.assign(Object.assign({},this.logContext),{error:e}))}this.handleParticipantUpdates([t,...e.otherParticipants]),e.room&&this.handleRoomUpdate(e.room)},this.attemptConnection=(e,t,n,r)=>N(this,void 0,void 0,function*(){this.state===Y.Reconnecting||this.isResuming||this.engine?.pendingReconnect?(this.log.info(`Reconnection attempt replaced by new connection attempt`,this.logContext),this.recreateEngine(!0)):this.maybeCreateEngine(),this.regionUrlProvider?.isCloud()&&this.engine.setRegionUrlProvider(this.regionUrlProvider),this.acquireAudioContext(),this.connOptions=Object.assign(Object.assign({},xf),n),this.connOptions.rtcConfig&&(this.engine.rtcConfig=this.connOptions.rtcConfig),this.connOptions.peerConnectionTimeout&&(this.engine.peerConnectionTimeout=this.connOptions.peerConnectionTimeout);try{let n=yield this.connectSignal(e,t,this.engine,this.connOptions,this.options,r);this.applyJoinResponse(n),this.setupLocalParticipantEvents(),this.emit(L.SignalConnected)}catch(e){yield this.engine.close(),this.recreateEngine();let t=r.signal.aborted?F.cancelled(`Signal connection aborted`):F.serverUnreachable(`could not establish signal connection`);throw e instanceof Error&&(t.message=`${t.message}: ${e.message}`),e instanceof F&&(t.reason=e.reason,t.status=e.status),this.log.debug(`error trying to establish signal connection`,Object.assign(Object.assign({},this.logContext),{error:e})),t}if(r.signal.aborted)throw yield this.engine.close(),this.recreateEngine(),F.cancelled(`Connection attempt aborted`);try{yield this.engine.waitForPCInitialConnection(this.connOptions.peerConnectionTimeout,r)}catch(e){throw yield this.engine.close(),this.recreateEngine(),e}mu()&&this.options.disconnectOnPageLeave&&(window.addEventListener(`pagehide`,this.onPageLeave),window.addEventListener(`beforeunload`,this.onPageLeave)),mu()&&window.addEventListener(`freeze`,this.onPageLeave),this.setAndEmitConnectionState(Y.Connected),this.emit(L.Connected),bd.getInstance().resetFailedConnectionAttempts(e),this.registerConnectionReconcile(),this.regionUrlProvider&&this.regionUrlProvider.notifyConnected()}),this.disconnect=function(){return N(n,[...[...arguments]],void 0,function(){var e=this;let t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:!0;return function*(){var n,r,i;let a=yield e.disconnectLock.lock();try{if(e.state===Y.Disconnected){e.log.debug(`already disconnected`,e.logContext);return}if(e.log.info(`disconnect from room`,Object.assign({},e.logContext)),e.state===Y.Connecting||e.state===Y.Reconnecting||e.isResuming){let t=`Abort connection attempt due to user initiated disconnect`;e.log.warn(t,e.logContext),(n=e.abortController)==null||n.abort(t),(i=(r=e.connectFuture)?.reject)==null||i.call(r,F.cancelled(`Client initiated disconnect`)),e.connectFuture=void 0}e.engine&&(e.engine.client.isDisconnected||(yield e.engine.client.sendLeave()),yield e.engine.close()),e.handleDisconnect(t,pa.CLIENT_INITIATED),e.engine=void 0}finally{a()}}()})},this.onPageLeave=()=>N(this,void 0,void 0,function*(){this.log.info(`Page leave detected, disconnecting`,this.logContext),yield this.disconnect()}),this.startAudio=()=>N(this,void 0,void 0,function*(){let e=[],t=el();if(t&&t.os===`iOS`){let t=`livekit-dummy-audio-el`,n=document.getElementById(t);if(!n){n=document.createElement(`audio`),n.id=t,n.autoplay=!0,n.hidden=!0;let e=ju();e.enabled=!0;let r=new MediaStream([e]);n.srcObject=r,document.addEventListener(`visibilitychange`,()=>{n&&(n.srcObject=document.hidden?null:r,document.hidden||(this.log.debug(`page visible again, triggering startAudio to resume playback and update playback status`,this.logContext),this.startAudio()))}),document.body.append(n),this.once(L.Disconnected,()=>{n?.remove(),n=null})}e.push(n)}this.remoteParticipants.forEach(t=>{t.audioTrackPublications.forEach(t=>{t.track&&t.track.attachedElements.forEach(t=>{e.push(t)})})});try{yield Promise.all([this.acquireAudioContext(),...e.map(e=>(e.muted=!1,e.play()))]),this.handleAudioPlaybackStarted()}catch(e){throw this.handleAudioPlaybackFailed(e),e}}),this.startVideo=()=>N(this,void 0,void 0,function*(){let e=[];for(let t of this.remoteParticipants.values())t.videoTrackPublications.forEach(t=>{var n;(n=t.track)==null||n.attachedElements.forEach(t=>{e.includes(t)||e.push(t)})});yield Promise.all(e.map(e=>e.play())).then(()=>{this.handleVideoPlaybackStarted()}).catch(e=>{e.name===`NotAllowedError`?this.handleVideoPlaybackFailed():this.log.warn("Resuming video playback failed, make sure you call `startVideo` directly in a user gesture handler",this.logContext)})}),this.handleRestarting=()=>{this.clearConnectionReconcile(),this.isResuming=!1;for(let e of this.remoteParticipants.values())this.handleParticipantDisconnected(e.identity,e);this.setAndEmitConnectionState(Y.Reconnecting)&&this.emit(L.Reconnecting)},this.handleRestarted=()=>{this.outgoingDataTrackManager.sfuWillRepublishTracks(),this.incomingDataTrackManager.resendSubscriptionUpdates()},this.handleSignalRestarted=e=>N(this,void 0,void 0,function*(){this.log.debug(`signal reconnected to server, region ${e.serverRegion}`,Object.assign(Object.assign({},this.logContext),{region:e.serverRegion})),this.bufferedEvents=[],this.applyJoinResponse(e);try{yield this.localParticipant.republishAllTracks(void 0,!0)}catch(e){this.log.error(`error trying to re-publish tracks after reconnection`,Object.assign(Object.assign({},this.logContext),{error:e}))}try{yield this.engine.waitForRestarted(),this.log.debug(`fully reconnected to server`,Object.assign(Object.assign({},this.logContext),{region:e.serverRegion}))}catch{return}this.setAndEmitConnectionState(Y.Connected),this.emit(L.Reconnected),this.registerConnectionReconcile(),this.emitBufferedEvents()}),this.handleParticipantUpdates=e=>{for(let t of e){if(t.identity===this.localParticipant.identity){this.localParticipant.updateInfo(t);continue}t.identity===``&&(t.identity=this.sidToIdentity.get(t.sid)??``);let e=this.remoteParticipants.get(t.identity);t.state===xa.DISCONNECTED?this.handleParticipantDisconnected(t.identity,e):e=this.getOrCreateParticipant(t.identity,t)}let t=new Map(e.filter(e=>e.identity!==this.localParticipant.identity).map(e=>[e.identity,e.dataTracks.map(e=>Nd.from(e))]));this.incomingDataTrackManager.receiveSfuPublicationUpdates(t)},this.handleActiveSpeakersUpdate=e=>{let t=[],n={};e.forEach(e=>{if(n[e.sid]=!0,e.sid===this.localParticipant.sid)this.localParticipant.audioLevel=e.level,this.localParticipant.setIsSpeaking(!0),t.push(this.localParticipant);else{let n=this.getRemoteParticipantBySid(e.sid);n&&(n.audioLevel=e.level,n.setIsSpeaking(!0),t.push(n))}}),n[this.localParticipant.sid]||(this.localParticipant.audioLevel=0,this.localParticipant.setIsSpeaking(!1)),this.remoteParticipants.forEach(e=>{n[e.sid]||(e.audioLevel=0,e.setIsSpeaking(!1))}),this.activeSpeakers=t,this.emitWhenConnected(L.ActiveSpeakersChanged,t)},this.handleSpeakersChanged=e=>{let t=new Map;this.activeSpeakers.forEach(e=>{let n=this.remoteParticipants.get(e.identity);n&&n.sid!==e.sid||t.set(e.sid,e)}),e.forEach(e=>{let n=this.getRemoteParticipantBySid(e.sid);e.sid===this.localParticipant.sid&&(n=this.localParticipant),n&&(n.audioLevel=e.level,n.setIsSpeaking(e.active),e.active?t.set(e.sid,n):t.delete(e.sid))});let n=Array.from(t.values());n.sort((e,t)=>t.audioLevel-e.audioLevel),this.activeSpeakers=n,this.emitWhenConnected(L.ActiveSpeakersChanged,n)},this.handleStreamStateUpdate=e=>{e.streamStates.forEach(e=>{let t=this.getRemoteParticipantBySid(e.participantSid);if(!t)return;let n=t.getTrackPublicationBySid(e.trackSid);if(!n||!n.track)return;let r=U.streamStateFromProto(e.state);n.track.setStreamState(r),r!==n.track.streamState&&(t.emit(R.TrackStreamStateChanged,n,n.track.streamState),this.emitWhenConnected(L.TrackStreamStateChanged,n,n.track.streamState,t))})},this.handleSubscriptionPermissionUpdate=e=>{let t=this.getRemoteParticipantBySid(e.participantSid);if(!t)return;let n=t.getTrackPublicationBySid(e.trackSid);n&&n.setAllowed(e.allowed)},this.handleSubscriptionError=e=>{let t=Array.from(this.remoteParticipants.values()).find(t=>t.trackPublications.has(e.trackSid));if(!t)return;let n=t.getTrackPublicationBySid(e.trackSid);n&&n.setSubscriptionError(e.err)},this.handleDataPacket=(e,t)=>{let n=this.remoteParticipants.get(e.participantIdentity);if(e.value.case===`user`)this.handleUserPacket(n,e.value.value,e.kind,t);else if(e.value.case===`transcription`)this.handleTranscription(n,e.value.value);else if(e.value.case===`sipDtmf`)this.handleSipDtmf(n,e.value.value);else if(e.value.case===`chatMessage`)this.handleChatMessage(n,e.value.value);else if(e.value.case===`metrics`)this.handleMetrics(e.value.value,n);else if(e.value.case===`streamHeader`||e.value.case===`streamChunk`||e.value.case===`streamTrailer`)this.handleDataStream(e,t);else if(e.value.case===`rpcRequest`){let t=e.value.value;this.handleIncomingRpcRequest(e.participantIdentity,t.id,t.method,t.payload,t.responseTimeoutMs,t.version)}},this.handleUserPacket=(e,t,n,r)=>{this.emit(L.DataReceived,t.payload,e,n,t.topic,r),e?.emit(R.DataReceived,t.payload,n,r)},this.handleSipDtmf=(e,t)=>{this.emit(L.SipDTMFReceived,t,e),e?.emit(R.SipDTMFReceived,t)},this.handleTranscription=(e,t)=>{let n=t.transcribedParticipantIdentity===this.localParticipant.identity?this.localParticipant:this.getParticipantByIdentity(t.transcribedParticipantIdentity),r=n?.trackPublications.get(t.trackId),i=Lu(t,this.transcriptionReceivedTimes);r?.emit(B.TranscriptionReceived,i),n?.emit(R.TranscriptionReceived,i,r),this.emit(L.TranscriptionReceived,i,n,r)},this.handleChatMessage=(e,t)=>{let n=Ru(t);this.emit(L.ChatMessage,n,e)},this.handleMetrics=(e,t)=>{this.emit(L.MetricsReceived,e,t)},this.handleDataStream=(e,t)=>{this.incomingDataStreamManager.handleDataStreamPacket(e,t)},this.bufferedSegments=new Map,this.handleAudioPlaybackStarted=()=>{this.canPlaybackAudio||(this.audioEnabled=!0,this.emit(L.AudioPlaybackStatusChanged,!0))},this.handleAudioPlaybackFailed=e=>{this.log.warn(`could not playback audio`,Object.assign(Object.assign({},this.logContext),{error:e})),this.canPlaybackAudio&&(this.audioEnabled=!1,this.emit(L.AudioPlaybackStatusChanged,!1))},this.handleVideoPlaybackStarted=()=>{this.isVideoPlaybackBlocked&&(this.isVideoPlaybackBlocked=!1,this.emit(L.VideoPlaybackStatusChanged,!0))},this.handleVideoPlaybackFailed=()=>{this.isVideoPlaybackBlocked||(this.isVideoPlaybackBlocked=!0,this.emit(L.VideoPlaybackStatusChanged,!1))},this.handleDeviceChange=()=>N(this,void 0,void 0,function*(){el()?.os!==`iOS`&&(yield this.selectDefaultDevices()),this.emit(L.MediaDevicesChanged)}),this.handleRoomUpdate=e=>{let t=this.roomInfo;this.roomInfo=e,t&&t.metadata!==e.metadata&&this.emitWhenConnected(L.RoomMetadataChanged,e.metadata),t?.activeRecording!==e.activeRecording&&this.emitWhenConnected(L.RecordingStatusChanged,e.activeRecording)},this.handleConnectionQualityUpdate=e=>{e.updates.forEach(e=>{if(e.participantSid===this.localParticipant.sid){this.localParticipant.setConnectionQuality(e.quality);return}let t=this.getRemoteParticipantBySid(e.participantSid);t&&t.setConnectionQuality(e.quality)})},this.onLocalParticipantMetadataChanged=e=>{this.emit(L.ParticipantMetadataChanged,e,this.localParticipant)},this.onLocalParticipantNameChanged=e=>{this.emit(L.ParticipantNameChanged,e,this.localParticipant)},this.onLocalAttributesChanged=e=>{this.emit(L.ParticipantAttributesChanged,e,this.localParticipant)},this.onLocalTrackMuted=e=>{this.emit(L.TrackMuted,e,this.localParticipant)},this.onLocalTrackUnmuted=e=>{this.emit(L.TrackUnmuted,e,this.localParticipant)},this.onTrackProcessorUpdate=e=>{var t;(t=e?.onPublish)==null||t.call(e,this)},this.onLocalTrackPublished=e=>N(this,void 0,void 0,function*(){var t,n,r,i;(t=e.track)==null||t.on(B.TrackProcessorUpdate,this.onTrackProcessorUpdate),(n=e.track)==null||n.on(B.Restarted,this.onLocalTrackRestarted),(i=(r=e.track?.getProcessor())?.onPublish)==null||i.call(r,this),this.emit(L.LocalTrackPublished,e,this.localParticipant),Ku(e.track)&&(yield e.track.checkForSilence())&&this.emit(L.LocalAudioSilenceDetected,e);let a=yield e.track?.getDeviceId(!1),o=Pl(e.source);o&&a&&a!==this.localParticipant.activeDeviceMap.get(o)&&(this.localParticipant.activeDeviceMap.set(o,a),this.emit(L.ActiveDeviceChanged,o,a))}),this.onLocalTrackUnpublished=e=>{var t,n;(t=e.track)==null||t.off(B.TrackProcessorUpdate,this.onTrackProcessorUpdate),(n=e.track)==null||n.off(B.Restarted,this.onLocalTrackRestarted),this.emit(L.LocalTrackUnpublished,e,this.localParticipant)},this.onLocalTrackRestarted=e=>N(this,void 0,void 0,function*(){let t=yield e.getDeviceId(!1),n=Pl(e.source);n&&t&&t!==this.localParticipant.activeDeviceMap.get(n)&&(this.log.debug(`local track restarted, setting ${n} ${t} active`,this.logContext),this.localParticipant.activeDeviceMap.set(n,t),this.emit(L.ActiveDeviceChanged,n,t))}),this.onLocalConnectionQualityChanged=e=>{this.emit(L.ConnectionQualityChanged,e,this.localParticipant)},this.onMediaDevicesError=(e,t)=>{this.emit(L.MediaDevicesError,e,t)},this.onLocalParticipantPermissionsChanged=e=>{this.emit(L.ParticipantPermissionsChanged,e,this.localParticipant)},this.onLocalChatMessageSent=e=>{this.emit(L.ChatMessage,e,this.localParticipant)},this.setMaxListeners(100),this.remoteParticipants=new Map,this.sidToIdentity=new Map,this.options=Object.assign(Object.assign({},bf),t),this.log=Ts(this.options.loggerName??ws.Room),this.transcriptionReceivedTimes=new Map,this.options.audioCaptureDefaults=Object.assign(Object.assign({},vf),t?.audioCaptureDefaults),this.options.videoCaptureDefaults=Object.assign(Object.assign({},yf),t?.videoCaptureDefaults),this.options.publishDefaults=Object.assign(Object.assign({},_f),t?.publishDefaults),this.maybeCreateEngine(),this.incomingDataStreamManager=new Tp,this.outgoingDataStreamManager=new Ap(this.engine,this.log),this.incomingDataTrackManager=new Cm({e2eeManager:this.e2eeManager}),this.incomingDataTrackManager.on(`sfuUpdateSubscription`,e=>{this.engine.client.sendUpdateDataSubscription(e.sid,e.subscribe)}).on(`trackPublished`,e=>{var t;e.track.publisherIdentity!==this.localParticipant.identity&&(this.emit(L.DataTrackPublished,e.track),(t=this.remoteParticipants.get(e.track.publisherIdentity))==null||t.addRemoteDataTrack(e.track))}).on(`trackUnpublished`,e=>{var t;e.publisherIdentity!==this.localParticipant.identity&&(this.emit(L.DataTrackUnpublished,e.sid),(t=this.remoteParticipants.get(e.publisherIdentity))==null||t.removeRemoteDataTrack(e.sid))}),this.outgoingDataTrackManager=new Rm({e2eeManager:this.e2eeManager}),this.outgoingDataTrackManager.on(`sfuPublishRequest`,e=>{this.engine.client.sendPublishDataTrackRequest(e.handle,e.name,e.usesE2ee)}).on(`sfuUnpublishRequest`,e=>{this.engine.client.sendUnPublishDataTrackRequest(e.handle)}).on(`trackPublished`,e=>{this.emit(L.LocalDataTrackPublished,e.track)}).on(`trackUnpublished`,e=>{this.emit(L.LocalDataTrackUnpublished,e.sid)}).on(`packetAvailable`,e=>{let{bytes:t}=e;this.engine.sendLossyBytes(t,K.DATA_TRACK_LOSSY,`wait`)}),this.disconnectLock=new ur,this.localParticipant=new eh(``,``,this.engine,this.options,this.rpcHandlers,this.outgoingDataStreamManager,this.outgoingDataTrackManager),(this.options.e2ee||this.options.encryption)&&this.setupE2EE(),this.engine.e2eeManager=this.e2eeManager,this.incomingDataTrackManager.updateE2eeManager(this.e2eeManager??null),this.outgoingDataTrackManager.updateE2eeManager(this.e2eeManager??null),this.options.videoCaptureDefaults.deviceId&&this.localParticipant.activeDeviceMap.set(`videoinput`,Pu(this.options.videoCaptureDefaults.deviceId)),this.options.audioCaptureDefaults.deviceId&&this.localParticipant.activeDeviceMap.set(`audioinput`,Pu(this.options.audioCaptureDefaults.deviceId)),this.options.audioOutput?.deviceId&&this.switchActiveDevice(`audiooutput`,Pu(this.options.audioOutput.deviceId)).catch(e=>this.log.warn(`Could not set audio output: ${e.message}`,this.logContext)),mu()){let t=new AbortController;(i=(r=navigator.mediaDevices)?.addEventListener)==null||i.call(r,`devicechange`,this.handleDeviceChange,{signal:t.signal}),e.cleanupRegistry&&e.cleanupRegistry.register(this,()=>{t.abort()})}}registerTextStreamHandler(e,t){return this.incomingDataStreamManager.registerTextStreamHandler(e,t)}unregisterTextStreamHandler(e){return this.incomingDataStreamManager.unregisterTextStreamHandler(e)}registerByteStreamHandler(e,t){return this.incomingDataStreamManager.registerByteStreamHandler(e,t)}unregisterByteStreamHandler(e){return this.incomingDataStreamManager.unregisterByteStreamHandler(e)}registerRpcMethod(e,t){if(this.rpcHandlers.has(e))throw Error(`RPC handler already registered for method ${e}, unregisterRpcMethod before trying to register again`);this.rpcHandlers.set(e,t)}unregisterRpcMethod(e){this.rpcHandlers.delete(e)}setE2EEEnabled(e){return N(this,void 0,void 0,function*(){if(this.e2eeManager)yield Promise.all([this.localParticipant.setE2EEEnabled(e)]),this.localParticipant.identity!==``&&this.e2eeManager.setParticipantCryptorEnabled(e,this.localParticipant.identity);else throw Error(`e2ee not configured, please set e2ee settings within the room options`)})}setupE2EE(){var e;let t=!!this.options.encryption,n=this.options.encryption||this.options.e2ee;n&&(`e2eeManager`in n?(this.e2eeManager=n.e2eeManager,this.e2eeManager.isDataChannelEncryptionEnabled=t):this.e2eeManager=new _d(n,t),this.e2eeManager.on(ud.ParticipantEncryptionStatusChanged,(e,t)=>{Xu(t)&&(this.isE2EEEnabled=e),this.emit(L.ParticipantEncryptionStatusChanged,e,t)}),this.e2eeManager.on(ud.EncryptionError,(e,t)=>{let n=t?this.getParticipantByIdentity(t):void 0;this.emit(L.EncryptionError,e,n)}),(e=this.e2eeManager)==null||e.setup(this))}get logContext(){return{room:this.name,roomID:this.roomInfo?.sid,participant:this.localParticipant.identity,participantID:this.localParticipant.sid}}get isRecording(){return this.roomInfo?.activeRecording??!1}getSid(){return this.state===Y.Disconnected?Zc.resolve(``):this.roomInfo&&this.roomInfo.sid!==``?Zc.resolve(this.roomInfo.sid):new Zc((e,t)=>{let n=t=>{t.sid!==``&&(this.engine.off(z.RoomUpdate,n),e(t.sid))};this.engine.on(z.RoomUpdate,n),this.once(L.Disconnected,()=>{this.engine.off(z.RoomUpdate,n),t(new I(`Room disconnected before room server id was available`))})})}get name(){return this.roomInfo?.name??``}get metadata(){return this.roomInfo?.metadata}get numParticipants(){return this.roomInfo?.numParticipants??0}get numPublishers(){return this.roomInfo?.numPublishers??0}maybeCreateEngine(){this.engine&&(this.engine.isNewlyCreated||!this.engine.isClosed)||(this.engine=new bp(this.options),this.engine.e2eeManager=this.e2eeManager,this.engine.on(z.ParticipantUpdate,this.handleParticipantUpdates).on(z.RoomUpdate,this.handleRoomUpdate).on(z.SpeakersChanged,this.handleSpeakersChanged).on(z.StreamStateChanged,this.handleStreamStateUpdate).on(z.ConnectionQualityUpdate,this.handleConnectionQualityUpdate).on(z.SubscriptionError,this.handleSubscriptionError).on(z.SubscriptionPermissionUpdate,this.handleSubscriptionPermissionUpdate).on(z.MediaTrackAdded,(e,t,n)=>{this.onTrackAdded(e,t,n)}).on(z.Disconnected,e=>{this.handleDisconnect(this.options.stopLocalTrackOnUnpublish,e)}).on(z.ActiveSpeakersUpdate,this.handleActiveSpeakersUpdate).on(z.DataPacketReceived,this.handleDataPacket).on(z.Resuming,()=>{this.clearConnectionReconcile(),this.isResuming=!0,this.log.info(`Resuming signal connection`,this.logContext),this.setAndEmitConnectionState(Y.SignalReconnecting)&&this.emit(L.SignalReconnecting)}).on(z.Resumed,()=>{this.registerConnectionReconcile(),this.isResuming=!1,this.log.info(`Resumed signal connection`,this.logContext),this.updateSubscriptions(),this.emitBufferedEvents(),this.setAndEmitConnectionState(Y.Connected)&&this.emit(L.Reconnected)}).on(z.SignalResumed,()=>{this.bufferedEvents=[],(this.state===Y.Reconnecting||this.isResuming)&&this.sendSyncState()}).on(z.Restarting,this.handleRestarting).on(z.Restarted,this.handleRestarted).on(z.SignalRestarted,this.handleSignalRestarted).on(z.Offline,()=>{this.setAndEmitConnectionState(Y.Reconnecting)&&this.emit(L.Reconnecting)}).on(z.DCBufferStatusChanged,(e,t)=>{this.emit(L.DCBufferStatusChanged,e,t)}).on(z.LocalTrackSubscribed,e=>{let t=this.localParticipant.getTrackPublications().find(t=>{let{trackSid:n}=t;return n===e});if(!t){this.log.warn(`could not find local track subscription for subscribed event`,this.logContext);return}this.localParticipant.emit(R.LocalTrackSubscribed,t),this.emitWhenConnected(L.LocalTrackSubscribed,t,this.localParticipant)}).on(z.RoomMoved,e=>{this.log.debug(`room moved`,e),e.room&&this.handleRoomUpdate(e.room),this.remoteParticipants.forEach((e,t)=>{this.handleParticipantDisconnected(t,e)}),this.emit(L.Moved,e.room.name),e.participant?this.handleParticipantUpdates([e.participant,...e.otherParticipants]):this.handleParticipantUpdates(e.otherParticipants)}).on(z.PublishDataTrackResponse,e=>{if(!e.info){this.log.warn(`received PublishDataTrackResponse, but event.info was ${e.info}, so skipping.`,this.logContext);return}this.outgoingDataTrackManager.receivedSfuPublishResponse(e.info.pubHandle,{type:`ok`,data:{sid:e.info.sid,pubHandle:e.info.pubHandle,name:e.info.name,usesE2ee:e.info.encryption!==j.NONE}})}).on(z.UnPublishDataTrackResponse,e=>{if(!e.info){this.log.warn(`received UnPublishDataTrackResponse, but event.info was ${e.info}, so skipping.`,this.logContext);return}this.outgoingDataTrackManager.receivedSfuUnpublishResponse(e.info.pubHandle)}).on(z.DataTrackSubscriberHandles,e=>{let t=new Map(Object.entries(e.subHandles).map(e=>{let[t,n]=e;return[parseInt(t,10),n.trackSid]}));this.incomingDataTrackManager.receivedSfuSubscriberHandles(t)}).on(z.DataTrackPacketReceived,e=>{try{this.incomingDataTrackManager.packetReceived(e)}catch(e){throw e}}).on(z.Joined,e=>{let t=new Map(e.otherParticipants.map(e=>[e.identity,e.dataTracks.map(e=>Nd.from(e))]));this.incomingDataTrackManager.receiveSfuPublicationUpdates(t)}),this.localParticipant&&this.localParticipant.setupEngine(this.engine),this.e2eeManager&&this.e2eeManager.setupEngine(this.engine),this.outgoingDataStreamManager&&this.outgoingDataStreamManager.setupEngine(this.engine))}static getLocalDevices(e){let t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:!0;return Sd.getInstance().getDevices(e,t)}prepareConnection(e,t){return N(this,void 0,void 0,function*(){if(this.state===Y.Disconnected){this.log.debug(`prepareConnection to ${e}`,this.logContext);try{if(gu(new URL(e))&&t){this.regionUrlProvider=new Tf(e,t);let n=yield this.regionUrlProvider.getNextBestRegionUrl();n&&this.state===Y.Disconnected&&(this.regionUrl=n,yield fetch(Iu(n),{method:`HEAD`}),this.log.debug(`prepared connection to ${n}`,this.logContext))}else yield fetch(Iu(e),{method:`HEAD`})}catch(e){this.log.warn(`could not prepare connection`,Object.assign(Object.assign({},this.logContext),{error:e}))}}})}getParticipantByIdentity(e){return this.localParticipant.identity===e?this.localParticipant:this.remoteParticipants.get(e)}clearConnectionFutures(){this.connectFuture=void 0}simulateScenario(e,t){return N(this,void 0,void 0,function*(){let n=()=>N(this,void 0,void 0,function*(){}),r;switch(e){case`signal-reconnect`:yield this.engine.client.handleOnClose(`simulate disconnect`);break;case`speaker`:r=new rs({scenario:{case:`speakerUpdate`,value:3}});break;case`node-failure`:r=new rs({scenario:{case:`nodeFailure`,value:!0}});break;case`server-leave`:r=new rs({scenario:{case:`serverLeave`,value:!0}});break;case`migration`:r=new rs({scenario:{case:`migration`,value:!0}});break;case`resume-reconnect`:this.engine.failNext(),yield this.engine.client.handleOnClose(`simulate resume-disconnect`);break;case`disconnect-signal-on-resume`:n=()=>N(this,void 0,void 0,function*(){yield this.engine.client.handleOnClose(`simulate resume-disconnect`)}),r=new rs({scenario:{case:`disconnectSignalOnResume`,value:!0}});break;case`disconnect-signal-on-resume-no-messages`:n=()=>N(this,void 0,void 0,function*(){yield this.engine.client.handleOnClose(`simulate resume-disconnect`)}),r=new rs({scenario:{case:`disconnectSignalOnResumeNoMessages`,value:!0}});break;case`full-reconnect`:this.engine.fullReconnectOnNext=!0,yield this.engine.client.handleOnClose(`simulate full-reconnect`);break;case`force-tcp`:case`force-tls`:r=new rs({scenario:{case:`switchCandidateProtocol`,value:e===`force-tls`?2:1}}),n=()=>N(this,void 0,void 0,function*(){let e=this.engine.client.onLeave;e&&e(new Fo({reason:pa.CLIENT_INITIATED,action:Io.RECONNECT}))});break;case`subscriber-bandwidth`:if(t===void 0||typeof t!=`number`)throw Error(`subscriber-bandwidth requires a number as argument`);r=new rs({scenario:{case:`subscriberBandwidth`,value:Vu(t)}});break;case`leave-full-reconnect`:r=new rs({scenario:{case:`leaveRequestFullReconnect`,value:!0}})}r&&(yield this.engine.client.sendSimulateScenario(r),yield n())})}get canPlaybackAudio(){return this.audioEnabled}get canPlaybackVideo(){return!this.isVideoPlaybackBlocked}getActiveDevice(e){return this.localParticipant.activeDeviceMap.get(e)}switchActiveDevice(e,t){return N(this,arguments,void 0,function(e,t){var n=this;let r=arguments.length>2&&arguments[2]!==void 0?arguments[2]:!0;return function*(){var i,a;let o=!0,s=!1,c=r?{exact:t}:t;if(e===`audioinput`){s=n.localParticipant.audioTrackPublications.size===0;let t=n.getActiveDevice(e)??n.options.audioCaptureDefaults.deviceId;n.options.audioCaptureDefaults.deviceId=c;let r=Array.from(n.localParticipant.audioTrackPublications.values()).filter(e=>e.source===U.Source.Microphone);try{o=(yield Promise.all(r.map(e=>e.audioTrack?.setDeviceId(c)))).every(e=>e===!0)}catch(e){throw n.options.audioCaptureDefaults.deviceId=t,e}let i=r.some(e=>e.track?.isMuted??!1);o&&i&&(s=!0)}else if(e===`videoinput`){s=n.localParticipant.videoTrackPublications.size===0;let t=n.getActiveDevice(e)??n.options.videoCaptureDefaults.deviceId;n.options.videoCaptureDefaults.deviceId=c;let r=Array.from(n.localParticipant.videoTrackPublications.values()).filter(e=>e.source===U.Source.Camera);try{o=(yield Promise.all(r.map(e=>e.videoTrack?.setDeviceId(c)))).every(e=>e===!0)}catch(e){throw n.options.videoCaptureDefaults.deviceId=t,e}let i=r.some(e=>e.track?.isMuted??!1);o&&i&&(s=!0)}else if(e===`audiooutput`){if(s=!0,!iu()&&!n.options.webAudioMix||n.options.webAudioMix&&n.audioContext&&!(`setSinkId`in n.audioContext))throw Error(`cannot switch audio output, the current browser does not support it`);n.options.webAudioMix&&(t=(yield Sd.getInstance().normalizeDeviceId(`audiooutput`,t))??``),(a=n.options).audioOutput??(a.audioOutput={});let r=n.getActiveDevice(e)??n.options.audioOutput.deviceId;n.options.audioOutput.deviceId=t;try{n.options.webAudioMix&&((i=n.audioContext)==null||i.setSinkId(t)),yield Promise.all(Array.from(n.remoteParticipants.values()).map(e=>e.setAudioOutput({deviceId:t})))}catch(e){throw n.options.audioOutput.deviceId=r,e}}return s&&(n.localParticipant.activeDeviceMap.set(e,t),n.emit(L.ActiveDeviceChanged,e,t)),o}()})}setupLocalParticipantEvents(){this.localParticipant.on(R.ParticipantMetadataChanged,this.onLocalParticipantMetadataChanged).on(R.ParticipantNameChanged,this.onLocalParticipantNameChanged).on(R.AttributesChanged,this.onLocalAttributesChanged).on(R.TrackMuted,this.onLocalTrackMuted).on(R.TrackUnmuted,this.onLocalTrackUnmuted).on(R.LocalTrackPublished,this.onLocalTrackPublished).on(R.LocalTrackUnpublished,this.onLocalTrackUnpublished).on(R.ConnectionQualityChanged,this.onLocalConnectionQualityChanged).on(R.MediaDevicesError,this.onMediaDevicesError).on(R.AudioStreamAcquired,this.startAudio).on(R.ChatMessage,this.onLocalChatMessageSent).on(R.ParticipantPermissionsChanged,this.onLocalParticipantPermissionsChanged)}recreateEngine(e){let t=this.engine;e&&t&&!t.client.isDisconnected?t.client.sendLeave().finally(()=>t.close()):t?.close(),this.engine=void 0,this.isResuming=!1,this.remoteParticipants.clear(),this.sidToIdentity.clear(),this.bufferedEvents=[],this.maybeCreateEngine()}onTrackAdded(e,t,n){if(this.state===Y.Connecting||this.state===Y.Reconnecting){let r=()=>{this.log.debug(`deferring on track for later`,{mediaTrackId:e.id,mediaStreamId:t.id,tracksInStream:t.getTracks().map(e=>e.id)}),this.onTrackAdded(e,t,n),i()},i=()=>{this.off(L.Reconnected,r),this.off(L.Connected,r),this.off(L.Disconnected,i)};this.once(L.Reconnected,r),this.once(L.Connected,r),this.once(L.Disconnected,i);return}if(this.state===Y.Disconnected){this.log.warn(`skipping incoming track after Room disconnected`,this.logContext);return}if(e.readyState===`ended`){this.log.info(`skipping incoming track as it already ended`,this.logContext);return}let r=Zl(t.id),i=r[0],a=r[1],o=e.id;if(a&&a.startsWith(`TR`)&&(o=a),i===this.localParticipant.sid){this.log.warn(`tried to create RemoteParticipant for local participant`,this.logContext);return}let s=Array.from(this.remoteParticipants.values()).find(e=>e.sid===i);if(!s){i.startsWith(`PA`)&&this.log.error(`Tried to add a track for a participant, that's not present. Sid: ${i}`,this.logContext);return}if(!o.startsWith(`TR`)){let e=this.engine.getTrackIdForReceiver(n);if(!e){this.log.error(`Tried to add a track whose 'sid' could not be found for a participant, that's not present. Sid: ${i}`,this.logContext);return}o=e}o.startsWith(`TR`)||this.log.warn(`Tried to add a track whose 'sid' could not be determined for a participant, that's not present. Sid: ${i}, streamId: ${a}, trackId: ${o}`,Object.assign(Object.assign({},this.logContext),{remoteParticipantID:i,streamId:a,trackId:o}));let c;this.options.adaptiveStream&&(c=typeof this.options.adaptiveStream==`object`?this.options.adaptiveStream:{});let l=s.addSubscribedMediaTrack(e,o,t,n,c);l?.isEncrypted&&!this.e2eeManager&&this.emit(L.EncryptionError,Error(`Encrypted ${l.source} track received from participant ${s.sid}, but room does not have encryption enabled!`))}handleDisconnect(){let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:!0,t=arguments.length>1?arguments[1]:void 0;var n,r;if(this.clearConnectionReconcile(),this.isResuming=!1,this.bufferedEvents=[],this.transcriptionReceivedTimes.clear(),this.incomingDataStreamManager.clearControllers(),this.state!==Y.Disconnected){this.regionUrl=void 0,this.regionUrlProvider&&this.regionUrlProvider.notifyDisconnected();try{this.remoteParticipants.forEach(e=>{e.trackPublications.forEach(t=>{e.unpublishTrack(t.trackSid)})}),this.localParticipant.trackPublications.forEach(t=>{var n,r,i;t.track&&this.localParticipant.unpublishTrack(t.track,e),e?((n=t.track)==null||n.detach(),(r=t.track)==null||r.stop()):(i=t.track)==null||i.stopMonitor()}),this.localParticipant.off(R.ParticipantMetadataChanged,this.onLocalParticipantMetadataChanged).off(R.ParticipantNameChanged,this.onLocalParticipantNameChanged).off(R.AttributesChanged,this.onLocalAttributesChanged).off(R.TrackMuted,this.onLocalTrackMuted).off(R.TrackUnmuted,this.onLocalTrackUnmuted).off(R.LocalTrackPublished,this.onLocalTrackPublished).off(R.LocalTrackUnpublished,this.onLocalTrackUnpublished).off(R.ConnectionQualityChanged,this.onLocalConnectionQualityChanged).off(R.MediaDevicesError,this.onMediaDevicesError).off(R.AudioStreamAcquired,this.startAudio).off(R.ChatMessage,this.onLocalChatMessageSent).off(R.ParticipantPermissionsChanged,this.onLocalParticipantPermissionsChanged),this.localParticipant.trackPublications.clear(),this.localParticipant.videoTrackPublications.clear(),this.localParticipant.audioTrackPublications.clear(),this.remoteParticipants.clear(),this.sidToIdentity.clear(),this.activeSpeakers=[],this.audioContext&&typeof this.options.webAudioMix==`boolean`&&(this.audioContext.close(),this.audioContext=void 0),mu()&&(window.removeEventListener(`beforeunload`,this.onPageLeave),window.removeEventListener(`pagehide`,this.onPageLeave),window.removeEventListener(`freeze`,this.onPageLeave),(r=(n=navigator.mediaDevices)?.removeEventListener)==null||r.call(n,`devicechange`,this.handleDeviceChange))}finally{this.setAndEmitConnectionState(Y.Disconnected),this.emit(L.Disconnected,t)}}}handleParticipantDisconnected(e,t){var n;this.remoteParticipants.delete(e),t&&(this.incomingDataStreamManager.validateParticipantHasNoActiveDataStreams(e),this.incomingDataTrackManager.handleRemoteParticipantDisconnected(e),t.trackPublications.forEach(e=>{t.unpublishTrack(e.trackSid,!0)}),this.emit(L.ParticipantDisconnected,t),t.setDisconnected(),(n=this.localParticipant)==null||n.handleParticipantDisconnected(t.identity))}handleIncomingRpcRequest(e,t,n,r,i,a){return N(this,void 0,void 0,function*(){if(yield this.engine.publishRpcAck(e,t),a!==1){yield this.engine.publishRpcResponse(e,t,null,Df.builtIn(`UNSUPPORTED_VERSION`));return}let o=this.rpcHandlers.get(n);if(!o){yield this.engine.publishRpcResponse(e,t,null,Df.builtIn(`UNSUPPORTED_METHOD`));return}let s=null,c=null;try{let a=yield o({requestId:t,callerIdentity:e,payload:r,responseTimeout:i});kf(a)>Of?(s=Df.builtIn(`RESPONSE_PAYLOAD_TOO_LARGE`),this.log.warn(`RPC Response payload too large for ${n}`)):c=a}catch(e){e instanceof Df?s=e:(this.log.warn(`Uncaught error returned by RPC handler for ${n}. Returning APPLICATION_ERROR instead.`,e),s=Df.builtIn(`APPLICATION_ERROR`))}yield this.engine.publishRpcResponse(e,t,c,s)})}selectDefaultDevices(){return N(this,void 0,void 0,function*(){let e=Sd.getInstance().previousDevices,t=yield Sd.getInstance().getDevices(void 0,!1),n=el();if(n?.name===`Chrome`&&n.os!==`iOS`)for(let n of t){let t=e.find(e=>e.deviceId===n.deviceId);t&&t.label!==``&&t.kind===n.kind&&t.label!==n.label&&this.getActiveDevice(n.kind)===`default`&&this.emit(L.ActiveDeviceChanged,n.kind,n.deviceId)}for(let n of[`audiooutput`,`audioinput`,`videoinput`]){let r=Nl(n),i=this.localParticipant.getTrackPublication(r);if(i&&i.track?.isUserProvided)continue;let a=t.filter(e=>e.kind===n),o=this.getActiveDevice(n);if(o===e.filter(e=>e.kind===n)[0]?.deviceId&&a.length>0&&a[0]?.deviceId!==o){yield this.switchActiveDevice(n,a[0].deviceId);continue}n===`audioinput`&&!lu()||n===`videoinput`||a.length>0&&!a.find(e=>e.deviceId===this.getActiveDevice(n))&&(n!==`audiooutput`||!lu())&&(yield this.switchActiveDevice(n,a[0].deviceId))}})}acquireAudioContext(){return N(this,void 0,void 0,function*(){if(typeof this.options.webAudioMix!=`boolean`&&this.options.webAudioMix.audioContext?this.audioContext=this.options.webAudioMix.audioContext:(!this.audioContext||this.audioContext.state===`closed`)&&(this.audioContext=Ml()??void 0),this.options.webAudioMix&&this.remoteParticipants.forEach(e=>e.setAudioContext(this.audioContext)),this.localParticipant.setAudioContext(this.audioContext),this.audioContext&&this.audioContext.state===`suspended`)try{yield Promise.race([this.audioContext.resume(),Ql(200)])}catch(e){this.log.warn(`Could not resume audio context`,Object.assign(Object.assign({},this.logContext),{error:e}))}let e=this.audioContext?.state===`running`;e!==this.canPlaybackAudio&&(this.audioEnabled=e,this.emit(L.AudioPlaybackStatusChanged,e))})}createParticipant(e,t){let n;return n=t?ih.fromParticipantInfo(this.engine.client,t,{loggerContextCb:()=>this.logContext,loggerName:this.options.loggerName}):new ih(this.engine.client,``,e,void 0,void 0,void 0,{loggerContextCb:()=>this.logContext,loggerName:this.options.loggerName}),this.options.webAudioMix&&n.setAudioContext(this.audioContext),this.options.audioOutput?.deviceId&&n.setAudioOutput(this.options.audioOutput).catch(e=>this.log.warn(`Could not set audio output: ${e.message}`,this.logContext)),n}getOrCreateParticipant(e,t){if(this.remoteParticipants.has(e)){let n=this.remoteParticipants.get(e);return t&&n.updateInfo(t)&&this.sidToIdentity.set(t.sid,t.identity),n}let n=this.createParticipant(e,t);return this.remoteParticipants.set(e,n),this.sidToIdentity.set(t.sid,t.identity),this.emitWhenConnected(L.ParticipantConnected,n),n.on(R.TrackPublished,e=>{this.emitWhenConnected(L.TrackPublished,e,n)}).on(R.TrackSubscribed,(e,t)=>{e.kind===U.Kind.Audio?(e.on(B.AudioPlaybackStarted,this.handleAudioPlaybackStarted),e.on(B.AudioPlaybackFailed,this.handleAudioPlaybackFailed)):e.kind===U.Kind.Video&&(e.on(B.VideoPlaybackFailed,this.handleVideoPlaybackFailed),e.on(B.VideoPlaybackStarted,this.handleVideoPlaybackStarted)),this.emitWhenConnected(L.TrackSubscribed,e,t,n)}).on(R.TrackUnpublished,e=>{this.emit(L.TrackUnpublished,e,n)}).on(R.TrackUnsubscribed,(e,t)=>{this.emit(L.TrackUnsubscribed,e,t,n)}).on(R.TrackMuted,e=>{this.emitWhenConnected(L.TrackMuted,e,n)}).on(R.TrackUnmuted,e=>{this.emitWhenConnected(L.TrackUnmuted,e,n)}).on(R.ParticipantMetadataChanged,e=>{this.emitWhenConnected(L.ParticipantMetadataChanged,e,n)}).on(R.ParticipantNameChanged,e=>{this.emitWhenConnected(L.ParticipantNameChanged,e,n)}).on(R.AttributesChanged,e=>{this.emitWhenConnected(L.ParticipantAttributesChanged,e,n)}).on(R.ConnectionQualityChanged,e=>{this.emitWhenConnected(L.ConnectionQualityChanged,e,n)}).on(R.ParticipantPermissionsChanged,e=>{this.emitWhenConnected(L.ParticipantPermissionsChanged,e,n)}).on(R.TrackSubscriptionStatusChanged,(e,t)=>{this.emitWhenConnected(L.TrackSubscriptionStatusChanged,e,t,n)}).on(R.TrackSubscriptionFailed,(e,t)=>{this.emit(L.TrackSubscriptionFailed,e,n,t)}).on(R.TrackSubscriptionPermissionChanged,(e,t)=>{this.emitWhenConnected(L.TrackSubscriptionPermissionChanged,e,t,n)}).on(R.Active,()=>{this.emitWhenConnected(L.ParticipantActive,n),n.kind===Sa.AGENT&&this.localParticipant.setActiveAgent(n)}),t&&n.updateInfo(t),n}sendSyncState(){let e=Array.from(this.remoteParticipants.values()).reduce((e,t)=>(e.push(...t.getTrackPublications()),e),[]),t=this.localParticipant.getTrackPublications(),n=this.outgoingDataTrackManager.queryPublished();this.engine.sendSyncState(e,t,n)}updateSubscriptions(){for(let e of this.remoteParticipants.values())for(let t of e.videoTrackPublications.values())t.isSubscribed&&Ju(t)&&t.emitTrackUpdate()}getRemoteParticipantBySid(e){let t=this.sidToIdentity.get(e);if(t)return this.remoteParticipants.get(t)}registerConnectionReconcile(){this.clearConnectionReconcile();let e=0;this.connectionReconcileInterval=_l.setInterval(()=>{!this.engine||this.engine.isClosed||!this.engine.verifyTransport()?(e++,this.log.warn(`detected connection state mismatch`,Object.assign(Object.assign({},this.logContext),{numFailures:e,engine:this.engine?{closed:this.engine.isClosed,transportsConnectedOrConnecting:this.engine.verifyTransport()}:void 0})),e>=3&&(this.recreateEngine(),this.handleDisconnect(this.options.stopLocalTrackOnUnpublish,pa.STATE_MISMATCH))):e=0},ah)}clearConnectionReconcile(){this.connectionReconcileInterval&&_l.clearInterval(this.connectionReconcileInterval)}setAndEmitConnectionState(e){return e===this.state?!1:(this.state=e,this.emit(L.ConnectionStateChanged,this.state),!0)}emitBufferedEvents(){this.bufferedEvents.forEach(e=>{let[t,n]=e;this.emit(t,...n)}),this.bufferedEvents=[]}emitWhenConnected(e){var t=[...arguments].slice(1);if(this.state===Y.Reconnecting||this.isResuming||!this.engine||this.engine.pendingReconnect)this.bufferedEvents.push([e,t]);else if(this.state===Y.Connected)return this.emit(e,...t);return!1}simulateParticipants(e){return N(this,void 0,void 0,function*(){let t=Object.assign({audio:!0,video:!0,useRealTracks:!1},e.publish),n=Object.assign({count:9,audio:!1,video:!0,aspectRatios:[1.66,1.7,1.3]},e.participants);if(this.handleDisconnect(),this.roomInfo=new _a({sid:`RM_SIMULATED`,name:`simulated-room`,emptyTimeout:0,maxParticipants:0,creationTime:D.parse(new Date().getTime()),metadata:``,numParticipants:1,numPublishers:1,turnPassword:``,enabledCodecs:[],activeRecording:!1}),this.localParticipant.updateInfo(new ba({identity:`simulated-local`,name:`local-name`})),this.setupLocalParticipantEvents(),this.emit(L.SignalConnected),this.emit(L.Connected),this.setAndEmitConnectionState(Y.Connected),t.video){let e=new qm(U.Kind.Video,new Ta({source:A.CAMERA,sid:Math.floor(Math.random()*1e4).toString(),type:la.AUDIO,name:`video-dummy`}),new ap(t.useRealTracks&&window.navigator.mediaDevices?.getUserMedia?(yield window.navigator.mediaDevices.getUserMedia({video:!0})).getVideoTracks()[0]:ku(160*(n.aspectRatios[0]??1),160,!0,!0),void 0,!1,{loggerName:this.options.loggerName,loggerContextCb:()=>this.logContext}),{loggerName:this.options.loggerName,loggerContextCb:()=>this.logContext});this.localParticipant.addTrackPublication(e),this.localParticipant.emit(R.LocalTrackPublished,e)}if(t.audio){let e=new qm(U.Kind.Audio,new Ta({source:A.MICROPHONE,sid:Math.floor(Math.random()*1e4).toString(),type:la.AUDIO}),new Bf(t.useRealTracks&&navigator.mediaDevices?.getUserMedia?(yield navigator.mediaDevices.getUserMedia({audio:!0})).getAudioTracks()[0]:ju(),void 0,!1,this.audioContext,{loggerName:this.options.loggerName,loggerContextCb:()=>this.logContext}),{loggerName:this.options.loggerName,loggerContextCb:()=>this.logContext});this.localParticipant.addTrackPublication(e),this.localParticipant.emit(R.LocalTrackPublished,e)}for(let e=0;e<n.count-1;e+=1){let t=new ba({sid:Math.floor(Math.random()*1e4).toString(),identity:`simulated-${e}`,state:xa.ACTIVE,tracks:[],joinedAt:D.parse(Date.now())}),r=this.getOrCreateParticipant(t.identity,t);if(n.video){let i=ku(160*(n.aspectRatios[e%n.aspectRatios.length]??1),160,!1,!0),a=new Ta({source:A.CAMERA,sid:Math.floor(Math.random()*1e4).toString(),type:la.AUDIO});r.addSubscribedMediaTrack(i,a.sid,new MediaStream([i]),new RTCRtpReceiver),t.tracks=[...t.tracks,a]}if(n.audio){let e=ju(),n=new Ta({source:A.MICROPHONE,sid:Math.floor(Math.random()*1e4).toString(),type:la.AUDIO});r.addSubscribedMediaTrack(e,n.sid,new MediaStream([e]),new RTCRtpReceiver),t.tracks=[...t.tracks,n]}r.updateInfo(t)}})}emit(e){var t=[...arguments].slice(1);if(e!==L.ActiveSpeakersChanged&&e!==L.TranscriptionReceived){let n=sh(t).filter(e=>e!==void 0);(e===L.TrackSubscribed||e===L.TrackUnsubscribed)&&this.log.trace(`subscribe trace: ${e}`,Object.assign(Object.assign({},this.logContext),{event:e,args:n})),this.log.debug(`room event ${e}`,Object.assign(Object.assign({},this.logContext),{event:e,args:n}))}return super.emit(e,...t)}};oh.cleanupRegistry=typeof FinalizationRegistry<`u`&&new FinalizationRegistry(e=>{e()});function sh(e){return e.map(e=>{if(e)return Array.isArray(e)?sh(e):typeof e==`object`?`logContext`in e?e.logContext:void 0:e})}var ch;(function(e){e[e.IDLE=0]=`IDLE`,e[e.RUNNING=1]=`RUNNING`,e[e.SKIPPED=2]=`SKIPPED`,e[e.SUCCESS=3]=`SUCCESS`,e[e.FAILED=4]=`FAILED`})(ch||={}),zs.EventEmitter,zs.EventEmitter;function X(e,t,n){return(t=uh(t))in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function lh(e,t){if(typeof e!=`object`||!e)return e;var n=e[Symbol.toPrimitive];if(n!==void 0){var r=n.call(e,t);if(typeof r!=`object`)return r;throw TypeError(`@@toPrimitive must return a primitive value.`)}return(t===`string`?String:Number)(e)}function uh(e){var t=lh(e,`string`);return typeof t==`symbol`?t:t+``}new TextEncoder,new TextDecoder;var dh=class extends Error{constructor(e,t){var n;super(e,t),X(this,`code`,`ERR_JOSE_GENERIC`),this.name=this.constructor.name,(n=Error.captureStackTrace)==null||n.call(Error,this,this.constructor)}};X(dh,`code`,`ERR_JOSE_GENERIC`),X(class extends dh{constructor(e,t){let n=arguments.length>2&&arguments[2]!==void 0?arguments[2]:`unspecified`,r=arguments.length>3&&arguments[3]!==void 0?arguments[3]:`unspecified`;super(e,{cause:{claim:n,reason:r,payload:t}}),X(this,`code`,`ERR_JWT_CLAIM_VALIDATION_FAILED`),X(this,`claim`,void 0),X(this,`reason`,void 0),X(this,`payload`,void 0),this.claim=n,this.reason=r,this.payload=t}},`code`,`ERR_JWT_CLAIM_VALIDATION_FAILED`),X(class extends dh{constructor(e,t){let n=arguments.length>2&&arguments[2]!==void 0?arguments[2]:`unspecified`,r=arguments.length>3&&arguments[3]!==void 0?arguments[3]:`unspecified`;super(e,{cause:{claim:n,reason:r,payload:t}}),X(this,`code`,`ERR_JWT_EXPIRED`),X(this,`claim`,void 0),X(this,`reason`,void 0),X(this,`payload`,void 0),this.claim=n,this.reason=r,this.payload=t}},`code`,`ERR_JWT_EXPIRED`),X(class extends dh{constructor(){super(...arguments),X(this,`code`,`ERR_JOSE_ALG_NOT_ALLOWED`)}},`code`,`ERR_JOSE_ALG_NOT_ALLOWED`),X(class extends dh{constructor(){super(...arguments),X(this,`code`,`ERR_JOSE_NOT_SUPPORTED`)}},`code`,`ERR_JOSE_NOT_SUPPORTED`),X(class extends dh{constructor(){let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:`decryption operation failed`,t=arguments.length>1?arguments[1]:void 0;super(e,t),X(this,`code`,`ERR_JWE_DECRYPTION_FAILED`)}},`code`,`ERR_JWE_DECRYPTION_FAILED`),X(class extends dh{constructor(){super(...arguments),X(this,`code`,`ERR_JWE_INVALID`)}},`code`,`ERR_JWE_INVALID`),X(class extends dh{constructor(){super(...arguments),X(this,`code`,`ERR_JWS_INVALID`)}},`code`,`ERR_JWS_INVALID`),X(class extends dh{constructor(){super(...arguments),X(this,`code`,`ERR_JWT_INVALID`)}},`code`,`ERR_JWT_INVALID`),X(class extends dh{constructor(){super(...arguments),X(this,`code`,`ERR_JWK_INVALID`)}},`code`,`ERR_JWK_INVALID`),X(class extends dh{constructor(){super(...arguments),X(this,`code`,`ERR_JWKS_INVALID`)}},`code`,`ERR_JWKS_INVALID`),X(class extends dh{constructor(){let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:`no applicable key found in the JSON Web Key Set`,t=arguments.length>1?arguments[1]:void 0;super(e,t),X(this,`code`,`ERR_JWKS_NO_MATCHING_KEY`)}},`code`,`ERR_JWKS_NO_MATCHING_KEY`),X(class extends dh{constructor(){let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:`multiple matching keys found in the JSON Web Key Set`,t=arguments.length>1?arguments[1]:void 0;super(e,t),X(this,Symbol.asyncIterator,void 0),X(this,`code`,`ERR_JWKS_MULTIPLE_MATCHING_KEYS`)}},`code`,`ERR_JWKS_MULTIPLE_MATCHING_KEYS`),X(class extends dh{constructor(){let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:`request timed out`,t=arguments.length>1?arguments[1]:void 0;super(e,t),X(this,`code`,`ERR_JWKS_TIMEOUT`)}},`code`,`ERR_JWKS_TIMEOUT`),X(class extends dh{constructor(){let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:`signature verification failed`,t=arguments.length>1?arguments[1]:void 0;super(e,t),X(this,`code`,`ERR_JWS_SIGNATURE_VERIFICATION_FAILED`)}},`code`,`ERR_JWS_SIGNATURE_VERIFICATION_FAILED`);function fh(){return fh=Object.assign?Object.assign.bind():function(e){for(var t=1;t<arguments.length;t++){var n=arguments[t];for(var r in n)({}).hasOwnProperty.call(n,r)&&(e[r]=n[r])}return e},fh.apply(null,arguments)}var ph=new Uint8Array,mh=class{static getFullOptions(e){return fh({clientTools:{},onConnect:()=>{},onDebug:()=>{},onDisconnect:()=>{},onError:()=>{},onMessage:()=>{},onAudio:()=>{},onModeChange:()=>{},onStatusChange:()=>{},onCanSendFeedbackChange:()=>{},onInterruption:()=>{}},e)}constructor(e,t){var n=this;this.options=void 0,this.connection=void 0,this.lastInterruptTimestamp=0,this.mode=`listening`,this.status=`connecting`,this.volume=1,this.currentEventId=1,this.lastFeedbackEventId=0,this.canSendFeedback=!1,this.endSessionWithDetails=async function(e){n.status!==`connected`&&n.status!==`connecting`||(n.updateStatus(`disconnecting`),await n.handleEndSession(),n.updateStatus(`disconnected`),n.options.onDisconnect&&n.options.onDisconnect(e))},this.onMessage=async function(e){switch(e.type){case`interruption`:n.handleInterruption(e);return;case`agent_response`:n.handleAgentResponse(e);return;case`user_transcript`:n.handleUserTranscript(e);return;case`internal_tentative_agent_response`:n.handleTentativeAgentResponse(e);return;case`client_tool_call`:try{await n.handleClientToolCall(e)}catch(t){n.onError(`Unexpected error in client tool call handling: ${t instanceof Error?t.message:String(t)}`,{clientToolName:e.client_tool_call.tool_name,toolCallId:e.client_tool_call.tool_call_id})}return;case`audio`:n.handleAudio(e);return;case`vad_score`:n.handleVadScore(e);return;case`ping`:n.connection.sendMessage({type:`pong`,event_id:e.ping_event.event_id});return;case`mcp_tool_call`:n.handleMCPToolCall(e);return;case`mcp_connection_status`:n.handleMCPConnectionStatus(e);return;case`agent_tool_request`:n.handleAgentToolRequest(e);return;case`agent_tool_response`:n.handleAgentToolResponse(e);return;case`conversation_initiation_metadata`:n.handleConversationMetadata(e);return;case`asr_initiation_metadata`:n.handleAsrInitiationMetadata(e);return;case`agent_chat_response_part`:n.handleAgentChatResponsePart(e);return;case`error`:n.handleErrorEvent(e);return;default:n.options.onDebug&&n.options.onDebug(e);return}},this.setVolume=({volume:e})=>{this.volume=e},this.options=e,this.connection=t,this.options.onConnect&&this.options.onConnect({conversationId:t.conversationId}),this.connection.onMessage(this.onMessage),this.connection.onDisconnect(this.endSessionWithDetails),this.connection.onModeChange(e=>this.updateMode(e)),this.updateStatus(`connected`)}endSession(){return this.endSessionWithDetails({reason:`user`})}async handleEndSession(){this.connection.close()}updateMode(e){e!==this.mode&&(this.mode=e,this.options.onModeChange&&this.options.onModeChange({mode:e}))}updateStatus(e){e!==this.status&&(this.status=e,this.options.onStatusChange&&this.options.onStatusChange({status:e}))}updateCanSendFeedback(){let e=this.currentEventId!==this.lastFeedbackEventId;this.canSendFeedback!==e&&(this.canSendFeedback=e,this.options.onCanSendFeedbackChange&&this.options.onCanSendFeedbackChange({canSendFeedback:e}))}handleInterruption(e){e.interruption_event&&(this.lastInterruptTimestamp=e.interruption_event.event_id,this.options.onInterruption&&this.options.onInterruption({event_id:e.interruption_event.event_id}))}handleAgentResponse(e){this.options.onMessage&&this.options.onMessage({source:`ai`,role:`agent`,message:e.agent_response_event.agent_response})}handleUserTranscript(e){this.options.onMessage&&this.options.onMessage({source:`user`,role:`user`,message:e.user_transcription_event.user_transcript})}handleTentativeAgentResponse(e){this.options.onDebug&&this.options.onDebug({type:`tentative_agent_response`,response:e.tentative_agent_response_internal_event.tentative_agent_response})}handleVadScore(e){this.options.onVadScore&&this.options.onVadScore({vadScore:e.vad_score_event.vad_score})}async handleClientToolCall(e){if(Object.prototype.hasOwnProperty.call(this.options.clientTools,e.client_tool_call.tool_name))try{let t=await this.options.clientTools[e.client_tool_call.tool_name](e.client_tool_call.parameters)??`Client tool execution successful.`,n=typeof t==`object`?JSON.stringify(t):String(t);this.connection.sendMessage({type:`client_tool_result`,tool_call_id:e.client_tool_call.tool_call_id,result:n,is_error:!1})}catch(t){this.onError(`Client tool execution failed with following error: ${t?.message}`,{clientToolName:e.client_tool_call.tool_name}),this.connection.sendMessage({type:`client_tool_result`,tool_call_id:e.client_tool_call.tool_call_id,result:`Client tool execution failed: ${t?.message}`,is_error:!0})}else{if(this.options.onUnhandledClientToolCall)return void this.options.onUnhandledClientToolCall(e.client_tool_call);this.onError(`Client tool with name ${e.client_tool_call.tool_name} is not defined on client`,{clientToolName:e.client_tool_call.tool_name}),this.connection.sendMessage({type:`client_tool_result`,tool_call_id:e.client_tool_call.tool_call_id,result:`Client tool with name ${e.client_tool_call.tool_name} is not defined on client`,is_error:!0})}}handleAudio(e){}handleMCPToolCall(e){this.options.onMCPToolCall&&this.options.onMCPToolCall(e.mcp_tool_call)}handleMCPConnectionStatus(e){this.options.onMCPConnectionStatus&&this.options.onMCPConnectionStatus(e.mcp_connection_status)}handleAgentToolRequest(e){this.options.onAgentToolRequest&&this.options.onAgentToolRequest(e.agent_tool_request)}handleAgentToolResponse(e){e.agent_tool_response.tool_name===`end_call`&&this.endSessionWithDetails({reason:`agent`,context:new CloseEvent(`end_call`,{reason:`Agent ended the call`})}),this.options.onAgentToolResponse&&this.options.onAgentToolResponse(e.agent_tool_response)}handleConversationMetadata(e){this.options.onConversationMetadata&&this.options.onConversationMetadata(e.conversation_initiation_metadata_event)}handleAsrInitiationMetadata(e){this.options.onAsrInitiationMetadata&&this.options.onAsrInitiationMetadata(e.asr_initiation_metadata_event)}handleAgentChatResponsePart(e){this.options.onAgentChatResponsePart&&this.options.onAgentChatResponsePart(e.text_response_part)}handleErrorEvent(e){let t=e.error_event.error_type,n=e.error_event.message||e.error_event.reason||`Unknown error`;t===`max_duration_exceeded`?this.endSessionWithDetails({reason:`error`,message:n,context:new Event(`max_duration_exceeded`)}):this.onError(`Server error: ${n}`,{errorType:t,code:e.error_event.code,debugMessage:e.error_event.debug_message,details:e.error_event.details})}onError(e,t){console.error(e,t),this.options.onError&&this.options.onError(e,t)}getId(){return this.connection.conversationId}isOpen(){return this.status===`connected`}setMicMuted(e){this.connection.setMicMuted(e)}getInputByteFrequencyData(){return ph}getOutputByteFrequencyData(){return ph}getInputVolume(){return 0}getOutputVolume(){return 0}sendFeedback(e){this.canSendFeedback?(this.connection.sendMessage({type:`feedback`,score:e?`like`:`dislike`,event_id:this.currentEventId}),this.lastFeedbackEventId=this.currentEventId,this.updateCanSendFeedback()):console.warn(this.lastFeedbackEventId===0?`Cannot send feedback: the conversation has not started yet.`:`Cannot send feedback: feedback has already been sent for the current response.`)}sendContextualUpdate(e){this.connection.sendMessage({type:`contextual_update`,text:e})}sendUserMessage(e){this.connection.sendMessage({type:`user_message`,text:e})}sendUserActivity(){this.connection.sendMessage({type:`user_activity`})}sendMCPToolApprovalResult(e,t){this.connection.sendMessage({type:`mcp_tool_approval_result`,tool_call_id:e,is_approved:t})}},hh=class{constructor(e={}){this.queue=[],this.disconnectionDetails=null,this.onDisconnectCallback=null,this.onMessageCallback=null,this.onModeChangeCallback=null,this.onDebug=void 0,this.onDebug=e.onDebug}debug(e){this.onDebug&&this.onDebug(e)}onMessage(e){this.onMessageCallback=e;let t=this.queue;this.queue=[],t.length>0&&queueMicrotask(()=>{t.forEach(e)})}onDisconnect(e){this.onDisconnectCallback=e;let t=this.disconnectionDetails;t&&queueMicrotask(()=>{e(t)})}onModeChange(e){this.onModeChangeCallback=e}updateMode(e){var t;(t=this.onModeChangeCallback)==null||t.call(this,e)}disconnect(e){var t;this.disconnectionDetails||(this.disconnectionDetails=e,(t=this.onDisconnectCallback)==null||t.call(this,e))}handleMessage(e){this.onMessageCallback?this.onMessageCallback(e):this.queue.push(e)}};function gh(e){let[t,n]=e.split(`_`);if(![`pcm`,`ulaw`].includes(t))throw Error(`Invalid format: ${e}`);let r=Number.parseInt(n);if(Number.isNaN(r))throw Error(`Invalid sample rate: ${n}`);return{format:t,sampleRate:r}}var _h=`0.12.2`;function vh(e){return!!e.type}var yh=`conversation_initiation_client_data`;function bh(e){var t;let n={type:yh};return e.overrides&&(n.conversation_config_override={agent:{prompt:e.overrides.agent?.prompt,first_message:e.overrides.agent?.firstMessage,language:e.overrides.agent?.language},tts:{voice_id:e.overrides.tts?.voiceId,speed:e.overrides.tts?.speed},conversation:{text_only:e.overrides.conversation?.textOnly}}),e.customLlmExtraBody&&(n.custom_llm_extra_body=e.customLlmExtraBody),e.dynamicVariables&&(n.dynamic_variables=e.dynamicVariables),e.userId&&(n.user_id=e.userId),(t=e.overrides)!=null&&t.client&&(n.source_info={source:e.overrides.client.source,version:e.overrides.client.version}),n}var xh=class e extends hh{constructor(e,t,n,r){super(),this.socket=void 0,this.conversationId=void 0,this.inputFormat=void 0,this.outputFormat=void 0,this.socket=e,this.conversationId=t,this.inputFormat=n,this.outputFormat=r,this.socket.addEventListener(`error`,e=>{setTimeout(()=>this.disconnect({reason:`error`,message:`The connection was closed due to a socket error.`,context:e}),0)}),this.socket.addEventListener(`close`,e=>{this.disconnect(e.code===1e3?{reason:`agent`,context:e}:{reason:`error`,message:e.reason||`The connection was closed by the server.`,context:e})}),this.socket.addEventListener(`message`,e=>{try{let t=JSON.parse(e.data);if(!vh(t))return void this.debug({type:`invalid_event`,message:`Received invalid socket event`,data:e.data});this.handleMessage(t)}catch(t){this.debug({type:`parsing_error`,message:`Failed to parse socket message`,error:t instanceof Error?t.message:String(t),data:e.data})}})}static async create(t){let n=null;try{var r,i;let a=t.origin??`wss://api.elevenlabs.io`,o,s=((r=t.overrides)==null||(r=r.client)==null?void 0:r.version)||_h,c=((i=t.overrides)==null||(i=i.client)==null?void 0:i.source)||`js_sdk`;if(t.signedUrl){let e=t.signedUrl.includes(`?`)?`&`:`?`;o=`${t.signedUrl}${e}source=${c}&version=${s}`}else o=`${a}/v1/convai/conversation?agent_id=${t.agentId}&source=${c}&version=${s}`;let l=[`convai`];t.authorization&&l.push(`bearer.${t.authorization}`),n=new WebSocket(o,l);let{conversation_id:u,agent_output_audio_format:d,user_input_audio_format:f}=await new Promise((e,r)=>{n.addEventListener(`open`,()=>{var e;let r=bh(t);(e=n)==null||e.send(JSON.stringify(r))},{once:!0}),n.addEventListener(`error`,e=>{setTimeout(()=>r(e),0)}),n.addEventListener(`close`,r),n.addEventListener(`message`,t=>{let n=JSON.parse(t.data);vh(n)&&(n.type===`conversation_initiation_metadata`?e(n.conversation_initiation_metadata_event):console.warn(`First received message is not conversation metadata.`))},{once:!0})}),p=gh(f??`pcm_16000`),m=gh(d);return new e(n,u,p,m)}catch(e){var a;throw(a=n)==null||a.close(),e}}close(){this.socket.close(1e3,`User ended conversation`)}sendMessage(e){this.socket.send(JSON.stringify(e))}async setMicMuted(e){console.warn(`WebSocket connection setMicMuted called with ${e}, but this is handled by VoiceConversation`)}};function Sh(e){let t=new Uint8Array(e);return window.btoa(String.fromCharCode(...t))}function Ch(e){let t=window.atob(e),n=t.length,r=new Uint8Array(n);for(let e=0;e<n;e++)r[e]=t.charCodeAt(e);return r.buffer}var wh=new Map;function Th(e,t){return async(n,r)=>{let i=wh.get(e);if(i)return n.addModule(i);if(r)try{await n.addModule(r),wh.set(e,r);return}catch(t){throw Error(`Failed to load the ${e} worklet module from path: ${r}. Error: ${t}`)}let a=new Blob([t],{type:`application/javascript`}),o=URL.createObjectURL(a);try{await n.addModule(o),wh.set(e,o);return}catch{URL.revokeObjectURL(o)}try{let r=`data:application/javascript;base64,${btoa(t)}`;await n.addModule(r),wh.set(e,r)}catch{throw Error(`Failed to load the ${e} worklet module. Make sure the browser supports AudioWorklets. If you are using a strict CSP, you may need to self-host the worklet files.`)}}}var Eh=Th(`rawAudioProcessor`,`/*
|
|
67
|
+
`},tf}var af;function of(){if(af)return Jd;af=1;var e=ef(),t=rf();return Jd.grammar=Qd(),Jd.write=t,Jd.parse=e.parse,Jd.parseParams=e.parseParams,Jd.parseFmtpConfig=e.parseFmtpConfig,Jd.parsePayloads=e.parsePayloads,Jd.parseRemoteCandidates=e.parseRemoteCandidates,Jd.parseImageAttributes=e.parseImageAttributes,Jd.parseSimulcastStreamList=e.parseSimulcastStreamList,Jd}var sf=of();function cf(e){let t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:50,n=arguments.length>2&&arguments[2]!==void 0?arguments[2]:{},r,i=n.isImmediate??!1,a=n.callback??!1,o=n.maxWait,s=Date.now(),c=[];function l(){if(o!==void 0){let e=Date.now()-s;if(e+t>=o)return o-e}return t}let u=function(){for(var t=arguments.length,n=Array(t),o=0;o<t;o++)n[o]=arguments[o];let u=this;return new Promise((t,o)=>{let d=function(){if(r=void 0,s=Date.now(),!i){let t=e.apply(u,n);a&&a(t),c.forEach(e=>{let{resolve:n}=e;return n(t)}),c=[]}},f=i&&r===void 0;if(r!==void 0&&vl.clearTimeout(r),r=vl.setTimeout(d,l()),f){let r=e.apply(u,n);return a&&a(r),t(r)}c.push({resolve:t,reject:o})})};return u.cancel=function(e){r!==void 0&&vl.clearTimeout(r),c.forEach(t=>{let{reject:n}=t;return n(e)}),c=[]},u}var lf=.7,uf=20,df={NegotiationStarted:`negotiationStarted`,NegotiationComplete:`negotiationComplete`,RTPVideoPayloadTypes:`rtpVideoPayloadTypes`},ff=class extends Bs.EventEmitter{get pc(){return this._pc||=this.createPC(),this._pc}constructor(e){let t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{};super(),this.log=M,this.ddExtID=0,this.latestOfferId=0,this.pendingCandidates=[],this.restartingIce=!1,this.renegotiate=!1,this.trackBitrates=[],this.remoteStereoMids=[],this.remoteNackMids=[],this.negotiate=cf(e=>N(this,void 0,void 0,function*(){this.emit(df.NegotiationStarted);try{yield this.createAndSendOffer()}catch(t){if(e)e(t);else throw t}}),uf),this.close=()=>{this._pc&&=(this._pc.close(),this._pc.onconnectionstatechange=null,this._pc.oniceconnectionstatechange=null,this._pc.onicegatheringstatechange=null,this._pc.ondatachannel=null,this._pc.onnegotiationneeded=null,this._pc.onsignalingstatechange=null,this._pc.onicecandidate=null,this._pc.ondatachannel=null,this._pc.ontrack=null,this._pc.onconnectionstatechange=null,this._pc.oniceconnectionstatechange=null,null)},this.log=Es(t.loggerName??Ts.PCTransport),this.loggerOptions=t,this.config=e,this._pc=this.createPC(),this.offerLock=new ur}createPC(){let e=new RTCPeerConnection(this.config);return e.onicecandidate=e=>{var t;e.candidate&&((t=this.onIceCandidate)==null||t.call(this,e.candidate))},e.onicecandidateerror=e=>{var t;(t=this.onIceCandidateError)==null||t.call(this,e)},e.oniceconnectionstatechange=()=>{var t;(t=this.onIceConnectionStateChange)==null||t.call(this,e.iceConnectionState)},e.onsignalingstatechange=()=>{var t;(t=this.onSignalingStatechange)==null||t.call(this,e.signalingState)},e.onconnectionstatechange=()=>{var t;(t=this.onConnectionStateChange)==null||t.call(this,e.connectionState)},e.ondatachannel=e=>{var t;(t=this.onDataChannel)==null||t.call(this,e)},e.ontrack=e=>{var t;(t=this.onTrack)==null||t.call(this,e)},e}get logContext(){var e;return Object.assign({},(e=this.loggerOptions).loggerContextCb?.call(e))}get isICEConnected(){return this._pc!==null&&(this.pc.iceConnectionState===`connected`||this.pc.iceConnectionState===`completed`)}addIceCandidate(e){return N(this,void 0,void 0,function*(){if(this.pc.remoteDescription&&!this.restartingIce)return this.pc.addIceCandidate(e);this.pendingCandidates.push(e)})}setRemoteDescription(e,t){return N(this,void 0,void 0,function*(){if(e.type===`answer`&&this.latestOfferId>0&&t>0&&t!==this.latestOfferId)return this.log.warn(`ignoring answer for old offer`,Object.assign(Object.assign({},this.logContext),{offerId:t,latestOfferId:this.latestOfferId})),!1;let n;if(e.type===`offer`){let{stereoMids:t,nackMids:n}=mf(e);this.remoteStereoMids=t,this.remoteNackMids=n}else if(e.type===`answer`){if(this.pendingInitialOffer){let e=this.pendingInitialOffer;this.pendingInitialOffer=void 0;let t=sf.parse(e.sdp??``);t.media.forEach(e=>{hf(e)}),this.log.debug(`setting pending initial offer before processing answer`,this.logContext),yield this.setMungedSDP(e,sf.write(t))}let t=sf.parse(e.sdp??``);t.media.forEach(e=>{let t=gf(e.mid);e.type===`audio`&&this.trackBitrates.some(n=>{if(!n.transceiver||t!=n.transceiver.mid)return!1;let r=0;if(e.rtp.some(e=>e.codec.toUpperCase()===n.codec.toUpperCase()?(r=e.payload,!0):!1),r===0)return!0;let i=!1;for(let t of e.fmtp)if(t.payload===r){t.config=t.config.split(`;`).filter(e=>!e.includes(`maxaveragebitrate`)).join(`;`),n.maxbr>0&&(t.config+=`;maxaveragebitrate=${n.maxbr*1e3}`),i=!0;break}return i||n.maxbr>0&&e.fmtp.push({payload:r,config:`maxaveragebitrate=${n.maxbr*1e3}`}),!0})}),n=sf.write(t)}return yield this.setMungedSDP(e,n,!0),this.pendingCandidates.forEach(e=>{this.pc.addIceCandidate(e)}),this.pendingCandidates=[],this.restartingIce=!1,this.renegotiate?(this.renegotiate=!1,yield this.createAndSendOffer()):e.type===`answer`&&(this.emit(df.NegotiationComplete),e.sdp&&sf.parse(e.sdp).media.forEach(e=>{e.type===`video`&&this.emit(df.RTPVideoPayloadTypes,e.rtp)})),!0})}createInitialOffer(){return N(this,void 0,void 0,function*(){let e=yield this.offerLock.lock();try{if(this.pc.signalingState!==`stable`){this.log.warn(`signaling state is not stable, cannot create initial offer`,this.logContext);return}let e=this.latestOfferId+1;this.latestOfferId=e;let t=yield this.pc.createOffer();this.pendingInitialOffer={sdp:t.sdp,type:t.type};let n=sf.parse(t.sdp??``);return n.media.forEach(e=>{hf(e)}),t.sdp=sf.write(n),{offer:t,offerId:e}}finally{e()}})}createAndSendOffer(e){return N(this,void 0,void 0,function*(){let t=yield this.offerLock.lock();try{if(this.onOffer===void 0)return;if(e?.iceRestart&&(this.log.debug(`restarting ICE`,this.logContext),this.restartingIce=!0),this._pc&&(this._pc.signalingState===`have-local-offer`||this.pendingInitialOffer)){let t=this._pc.remoteDescription;if(e?.iceRestart&&t)yield this._pc.setRemoteDescription(t);else{this.renegotiate=!0,this.log.debug(`requesting renegotiation`,Object.assign({},this.logContext));return}}else if(!this._pc||this._pc.signalingState===`closed`){this.log.warn(`could not createOffer with closed peer connection`,this.logContext);return}this.log.debug(`starting to negotiate`,this.logContext);let t=this.latestOfferId+1;this.latestOfferId=t;let n=yield this.pc.createOffer(e);this.log.debug(`original offer`,Object.assign({sdp:n.sdp},this.logContext));let r=sf.parse(n.sdp??``);if(r.media.forEach(e=>{hf(e),e.type===`audio`?pf(e,[`all`],[]):e.type===`video`&&this.trackBitrates.some(t=>{if(!e.msid||!t.cid||!e.msid.includes(t.cid))return!1;let n=0;if(e.rtp.some(e=>e.codec.toUpperCase()===t.codec.toUpperCase()?(n=e.payload,!0):!1),n===0||(iu(t.codec)&&!lu()&&this.ensureVideoDDExtensionForSVC(e,r),!iu(t.codec)))return!0;let i=Math.round(t.maxbr*lf);for(let t of e.fmtp)if(t.payload===n){t.config.includes(`x-google-start-bitrate`)||(t.config+=`;x-google-start-bitrate=${i}`);break}return!0})}),this.latestOfferId>t){this.log.warn(`latestOfferId mismatch`,Object.assign(Object.assign({},this.logContext),{latestOfferId:this.latestOfferId,offerId:t}));return}yield this.setMungedSDP(n,sf.write(r)),this.onOffer(n,this.latestOfferId)}finally{t()}})}createAndSetAnswer(){return N(this,void 0,void 0,function*(){let e=yield this.pc.createAnswer(),t=sf.parse(e.sdp??``);return t.media.forEach(e=>{hf(e),e.type===`audio`&&pf(e,this.remoteStereoMids,this.remoteNackMids)}),yield this.setMungedSDP(e,sf.write(t)),e})}createDataChannel(e,t){return this.pc.createDataChannel(e,t)}addTransceiver(e,t){return this.pc.addTransceiver(e,t)}addTransceiverOfKind(e,t){return this.pc.addTransceiver(e,t)}addTrack(e){if(!this._pc)throw new I(`PC closed, cannot add track`);return this._pc.addTrack(e)}setTrackCodecBitrate(e){this.trackBitrates.push(e)}setConfiguration(e){if(!this._pc)throw new I(`PC closed, cannot configure`);return this._pc?.setConfiguration(e)}canRemoveTrack(){return!!this._pc?.removeTrack}removeTrack(e){return this._pc?.removeTrack(e)}getConnectionState(){return this._pc?.connectionState??`closed`}getICEConnectionState(){return this._pc?.iceConnectionState??`closed`}getSignallingState(){return this._pc?.signalingState??`closed`}getTransceivers(){return this._pc?.getTransceivers()??[]}getSenders(){return this._pc?.getSenders()??[]}getLocalDescription(){return this._pc?.localDescription}getRemoteDescription(){return this.pc?.remoteDescription}getStats(){return this.pc.getStats()}getConnectedAddress(){return N(this,void 0,void 0,function*(){if(!this._pc)return;let e=``,t=new Map,n=new Map;if((yield this._pc.getStats()).forEach(r=>{switch(r.type){case`transport`:e=r.selectedCandidatePairId;break;case`candidate-pair`:e===``&&r.selected&&(e=r.id),t.set(r.id,r);break;case`remote-candidate`:n.set(r.id,`${r.address}:${r.port}`);break}}),e===``)return;let r=t.get(e)?.remoteCandidateId;if(r!==void 0)return n.get(r)})}setMungedSDP(e,t,n){return N(this,void 0,void 0,function*(){if(t){let r=e.sdp;e.sdp=t;try{this.log.debug(`setting munged ${n?`remote`:`local`} description`,this.logContext),n?yield this.pc.setRemoteDescription(e):yield this.pc.setLocalDescription(e);return}catch(n){this.log.warn(`not able to set ${e.type}, falling back to unmodified sdp`,Object.assign(Object.assign({},this.logContext),{error:n,sdp:t})),e.sdp=r}}try{n?yield this.pc.setRemoteDescription(e):yield this.pc.setLocalDescription(e)}catch(t){let r=`unknown error`;t instanceof Error?r=t.message:typeof t==`string`&&(r=t);let i={error:r,sdp:e.sdp};throw!n&&this.pc.remoteDescription&&(i.remoteSdp=this.pc.remoteDescription),this.log.error(`unable to set ${e.type}`,Object.assign(Object.assign({},this.logContext),{fields:i})),new dl(r)}})}ensureVideoDDExtensionForSVC(e,t){var n;if(!e.ext?.some(e=>e.uri===Zl)){if(this.ddExtID===0){let e=0;t.media.forEach(t=>{var n;t.type===`video`&&((n=t.ext)==null||n.forEach(t=>{t.value>e&&(e=t.value)}))}),this.ddExtID=e+1}(n=e.ext)==null||n.push({value:this.ddExtID,uri:Zl})}}};function pf(e,t,n){let r=gf(e.mid),i=0;e.rtp.some(e=>e.codec===`opus`?(i=e.payload,!0):!1),i>0&&(e.rtcpFb||=[],n.includes(r)&&!e.rtcpFb.some(e=>e.payload===i&&e.type===`nack`)&&e.rtcpFb.push({payload:i,type:`nack`}),(t.includes(r)||t.length===1&&t[0]===`all`)&&e.fmtp.some(e=>e.payload===i?(e.config.includes(`stereo=1`)||(e.config+=`;stereo=1`),!0):!1))}function mf(e){let t=[],n=[],r=sf.parse(e.sdp??``),i=0;return r.media.forEach(e=>{let r=gf(e.mid);e.type===`audio`&&(e.rtp.some(e=>e.codec===`opus`?(i=e.payload,!0):!1),e.rtcpFb?.some(e=>e.payload===i&&e.type===`nack`)&&n.push(r),e.fmtp.some(e=>e.payload===i?(e.config.includes(`sprop-stereo=1`)&&t.push(r),!0):!1))}),{stereoMids:t,nackMids:n}}function hf(e){if(e.connection){let t=e.connection.ip.indexOf(`:`)>=0;(e.connection.version===4&&t||e.connection.version===6&&!t)&&(e.connection.ip=`0.0.0.0`,e.connection.version=4)}}function gf(e){return typeof e==`number`?e.toFixed(0):e}var _f=`vp8`,vf={audioPreset:Tl.music,dtx:!0,red:!0,forceStereo:!1,simulcast:!0,screenShareEncoding:Ol.h1080fps15.encoding,stopMicTrackOnMute:!1,videoCodec:_f,backupCodec:!0,preConnectBuffer:!1},yf={deviceId:{ideal:`default`},autoGainControl:!0,echoCancellation:!0,noiseSuppression:!0,voiceIsolation:!0},bf={deviceId:{ideal:`default`},resolution:El.h720.resolution},xf={adaptiveStream:!1,dynacast:!1,stopLocalTrackOnUnpublish:!0,reconnectPolicy:new As,disconnectOnPageLeave:!0,webAudioMix:!1,singlePeerConnection:!0},Sf={autoSubscribe:!0,maxRetries:1,peerConnectionTimeout:15e3,websocketTimeout:15e3},G;(function(e){e[e.NEW=0]=`NEW`,e[e.CONNECTING=1]=`CONNECTING`,e[e.CONNECTED=2]=`CONNECTED`,e[e.FAILED=3]=`FAILED`,e[e.CLOSING=4]=`CLOSING`,e[e.CLOSED=5]=`CLOSED`})(G||={});var Cf=class{get needsPublisher(){return this.isPublisherConnectionRequired}get needsSubscriber(){return this.isSubscriberConnectionRequired}get currentState(){return this.state}get mode(){return this._mode}constructor(e,t,n){this.peerConnectionTimeout=Sf.peerConnectionTimeout,this.log=M,this.updateState=()=>{var e;let t=this.state,n=this.requiredTransports.map(e=>e.getConnectionState());n.every(e=>e===`connected`)?this.state=G.CONNECTED:n.some(e=>e===`failed`)?this.state=G.FAILED:n.some(e=>e===`connecting`)?this.state=G.CONNECTING:n.every(e=>e===`closed`)?this.state=G.CLOSED:n.some(e=>e===`closed`)?this.state=G.CLOSING:n.every(e=>e===`new`)&&(this.state=G.NEW),t!==this.state&&(this.log.debug(`pc state change: from ${G[t]} to ${G[this.state]}`,this.logContext),(e=this.onStateChange)==null||e.call(this,this.state,this.publisher.getConnectionState(),this.subscriber?.getConnectionState()))},this.log=Es(t.loggerName??Ts.PCManager),this.loggerOptions=t,this.isPublisherConnectionRequired=e!==`subscriber-primary`,this.isSubscriberConnectionRequired=e===`subscriber-primary`,this.publisher=new ff(n,t),this._mode=e,e!==`publisher-only`&&(this.subscriber=new ff(n,t),this.subscriber.onConnectionStateChange=this.updateState,this.subscriber.onIceConnectionStateChange=this.updateState,this.subscriber.onSignalingStatechange=this.updateState,this.subscriber.onIceCandidate=e=>{var t;(t=this.onIceCandidate)==null||t.call(this,e,co.SUBSCRIBER)},this.subscriber.onDataChannel=e=>{var t;(t=this.onDataChannel)==null||t.call(this,e)},this.subscriber.onTrack=e=>{var t;(t=this.onTrack)==null||t.call(this,e)}),this.publisher.onConnectionStateChange=this.updateState,this.publisher.onIceConnectionStateChange=this.updateState,this.publisher.onSignalingStatechange=this.updateState,this.publisher.onIceCandidate=e=>{var t;(t=this.onIceCandidate)==null||t.call(this,e,co.PUBLISHER)},this.publisher.onTrack=e=>{var t;(t=this.onTrack)==null||t.call(this,e)},this.publisher.onOffer=(e,t)=>{var n;(n=this.onPublisherOffer)==null||n.call(this,e,t)},this.state=G.NEW,this.connectionLock=new ur,this.remoteOfferLock=new ur}get logContext(){var e;return Object.assign({},(e=this.loggerOptions).loggerContextCb?.call(e))}requirePublisher(){this.isPublisherConnectionRequired=arguments.length>0&&arguments[0]!==void 0?arguments[0]:!0,this.updateState()}createAndSendPublisherOffer(e){return this.publisher.createAndSendOffer(e)}setPublisherAnswer(e,t){return this.publisher.setRemoteDescription(e,t)}removeTrack(e){return this.publisher.removeTrack(e)}close(){return N(this,void 0,void 0,function*(){if(this.publisher&&this.publisher.getSignallingState()!==`closed`){let e=this.publisher;for(let t of e.getSenders())try{e.canRemoveTrack()&&e.removeTrack(t)}catch(e){this.log.warn(`could not removeTrack`,Object.assign(Object.assign({},this.logContext),{error:e}))}}yield Promise.all([this.publisher.close(),this.subscriber?.close()]),this.updateState()})}triggerIceRestart(){return N(this,void 0,void 0,function*(){this.subscriber&&(this.subscriber.restartingIce=!0),this.needsPublisher&&(yield this.createAndSendPublisherOffer({iceRestart:!0}))})}addIceCandidate(e,t){return N(this,void 0,void 0,function*(){t===co.PUBLISHER?yield this.publisher.addIceCandidate(e):yield this.subscriber?.addIceCandidate(e)})}createSubscriberAnswerFromOffer(e,t){return N(this,void 0,void 0,function*(){this.log.debug(`received server offer`,Object.assign(Object.assign({},this.logContext),{RTCSdpType:e.type,sdp:e.sdp,signalingState:this.subscriber?.getSignallingState().toString()}));let n=yield this.remoteOfferLock.lock();try{return(yield this.subscriber?.setRemoteDescription(e,t))?yield this.subscriber?.createAndSetAnswer():void 0}finally{n()}})}updateConfiguration(e,t){var n;this.publisher.setConfiguration(e),(n=this.subscriber)==null||n.setConfiguration(e),t&&this.triggerIceRestart()}ensurePCTransportConnection(e,t){return N(this,void 0,void 0,function*(){let n=yield this.connectionLock.lock();try{this.isPublisherConnectionRequired&&this.publisher.getConnectionState()!==`connected`&&this.publisher.getConnectionState()!==`connecting`&&(this.log.debug(`negotiation required, start negotiating`,this.logContext),this.publisher.negotiate()),yield Promise.all(this.requiredTransports?.map(n=>this.ensureTransportConnected(n,e,t)))}finally{n()}})}negotiate(e){return N(this,void 0,void 0,function*(){return new Qc((t,n)=>N(this,void 0,void 0,function*(){let r=setTimeout(()=>{n(new dl(`negotiation timed out`))},this.peerConnectionTimeout),i=()=>{clearTimeout(r),this.publisher.off(df.NegotiationStarted,o),e.signal.removeEventListener(`abort`,a)},a=()=>{i(),n(new dl(`negotiation aborted`))},o=()=>{e.signal.aborted||(clearTimeout(r),r=setTimeout(()=>{i(),n(new dl(`negotiation timed out`))},this.peerConnectionTimeout))};e.signal.addEventListener(`abort`,a),this.publisher.on(df.NegotiationStarted,o),this.publisher.once(df.NegotiationComplete,()=>{i(),t()}),yield this.publisher.negotiate(e=>{i(),e instanceof Error?n(e):n(Error(String(e)))})}))})}addPublisherTransceiver(e,t){return this.publisher.addTransceiver(e,t)}addPublisherTransceiverOfKind(e,t){return this.publisher.addTransceiverOfKind(e,t)}getMidForReceiver(e){return(this.subscriber?this.subscriber.getTransceivers():this.publisher.getTransceivers()).find(t=>t.receiver===e)?.mid}addPublisherTrack(e){return this.publisher.addTrack(e)}createPublisherDataChannel(e,t){return this.publisher.createDataChannel(e,t)}getConnectedAddress(e){return e===co.PUBLISHER||e===co.SUBSCRIBER?this.publisher.getConnectedAddress():this.requiredTransports[0].getConnectedAddress()}get requiredTransports(){let e=[];return this.isPublisherConnectionRequired&&e.push(this.publisher),this.isSubscriberConnectionRequired&&this.subscriber&&e.push(this.subscriber),e}ensureTransportConnected(e,t){return N(this,arguments,void 0,function(e,t){var n=this;let r=arguments.length>2&&arguments[2]!==void 0?arguments[2]:this.peerConnectionTimeout;return function*(){if(e.getConnectionState()!==`connected`)return new Promise((e,i)=>N(n,void 0,void 0,function*(){let n=()=>{this.log.warn(`abort transport connection`,this.logContext),vl.clearTimeout(a),i(F.cancelled(`room connection has been cancelled`))};t?.signal.aborted&&n(),t?.signal.addEventListener(`abort`,n);let a=vl.setTimeout(()=>{t?.signal.removeEventListener(`abort`,n),i(F.internal(`could not establish pc connection`))},r);for(;this.state!==G.CONNECTED;)if(yield $l(50),t?.signal.aborted){i(F.cancelled(`room connection has been cancelled`));return}vl.clearTimeout(a),t?.signal.removeEventListener(`abort`,n),e()}))}()})}},wf=5e3,Tf=3e4,Ef=class e{static fetchRegionSettings(t,n,r){return N(this,void 0,void 0,function*(){let i=yield e.fetchLock.lock();try{let e=yield fetch(`${Df(t)}/regions`,{headers:{authorization:`Bearer ${n}`},signal:r});if(e.ok){let t=$u(e.headers),n=t?t*1e3:wf;return{regionSettings:yield e.json(),updatedAtInMs:Date.now(),maxAgeInMs:n}}else if(e.status===401)throw F.notAllowed(`Could not fetch region settings: ${e.statusText}`,e.status);else throw F.internal(`Could not fetch region settings: ${e.statusText}`)}catch(e){throw e instanceof F?e:r?.aborted?F.cancelled(`Region fetching was aborted`):F.serverUnreachable(`Could not fetch region settings, ${e instanceof Error?`${e.name}: ${e.message}`:e}`)}finally{i()}})}static scheduleRefetch(t,n,r){return N(this,void 0,void 0,function*(){let i=e.settingsTimeouts.get(t.hostname);clearTimeout(i),e.settingsTimeouts.set(t.hostname,setTimeout(()=>N(this,void 0,void 0,function*(){try{let r=yield e.fetchRegionSettings(t,n);e.updateCachedRegionSettings(t,n,r)}catch(i){if(i instanceof F&&i.reason===P.NotAllowed){M.debug(`token is not valid, cancelling auto region refresh`);return}M.debug(`auto refetching of region settings failed`,{error:i}),e.scheduleRefetch(t,n,r)}}),r))})}static updateCachedRegionSettings(t,n,r){e.cache.set(t.hostname,r),e.scheduleRefetch(t,n,r.maxAgeInMs)}static stopRefetch(t){let n=e.settingsTimeouts.get(t);n&&(clearTimeout(n),e.settingsTimeouts.delete(t))}static scheduleCleanup(t){let n=e.connectionTrackers.get(t);n&&(n.cleanupTimeout&&clearTimeout(n.cleanupTimeout),n.cleanupTimeout=setTimeout(()=>{let n=e.connectionTrackers.get(t);n&&n.connectionCount===0&&(M.debug(`stopping region refetch after disconnect delay`,{hostname:t}),e.stopRefetch(t)),n&&(n.cleanupTimeout=void 0)},Tf))}static cancelCleanup(t){let n=e.connectionTrackers.get(t);n?.cleanupTimeout&&(clearTimeout(n.cleanupTimeout),n.cleanupTimeout=void 0)}notifyConnected(){let t=this.serverUrl.hostname,n=e.connectionTrackers.get(t);n||(n={connectionCount:0},e.connectionTrackers.set(t,n)),n.connectionCount++,e.cancelCleanup(t)}notifyDisconnected(){let t=this.serverUrl.hostname,n=e.connectionTrackers.get(t);n&&(n.connectionCount=Math.max(0,n.connectionCount-1),n.connectionCount===0&&e.scheduleCleanup(t))}constructor(e,t){this.attemptedRegions=[],this.serverUrl=new URL(e),this.token=t}updateToken(e){this.token=e}isCloud(){return _u(this.serverUrl)}getServerUrl(){return this.serverUrl}fetchRegionSettings(t){return N(this,void 0,void 0,function*(){return e.fetchRegionSettings(this.serverUrl,this.token,t)})}getNextBestRegionUrl(t){return N(this,void 0,void 0,function*(){if(!this.isCloud())throw Error(`region availability is only supported for LiveKit Cloud domains`);let n=e.cache.get(this.serverUrl.hostname);(!n||Date.now()-n.updatedAtInMs>n.maxAgeInMs)&&(n=yield this.fetchRegionSettings(t),e.updateCachedRegionSettings(this.serverUrl,this.token,n));let r=n.regionSettings.regions.filter(e=>!this.attemptedRegions.find(t=>t.url===e.url));if(r.length>0){let e=r[0];return this.attemptedRegions.push(e),M.debug(`next region: ${e.region}`),e.url}else return null})}resetAttempts(){this.attemptedRegions=[]}setServerReportedRegions(t){e.updateCachedRegionSettings(this.serverUrl,this.token,t)}};Ef.cache=new Map,Ef.settingsTimeouts=new Map,Ef.connectionTrackers=new Map,Ef.fetchLock=new ur;function Df(e){return`${e.protocol.replace(`ws`,`http`)}//${e.host}/settings`}var Of=class e extends Error{constructor(t,n,r){super(n),this.code=t,this.message=jf(n,e.MAX_MESSAGE_BYTES),this.data=r?jf(r,e.MAX_DATA_BYTES):void 0}static fromProto(t){return new e(t.code,t.message,t.data)}toProto(){return new Ga({code:this.code,message:this.message,data:this.data})}static builtIn(t,n){return new e(e.ErrorCode[t],e.ErrorMessage[t],n)}};Of.MAX_MESSAGE_BYTES=256,Of.MAX_DATA_BYTES=15360,Of.ErrorCode={APPLICATION_ERROR:1500,CONNECTION_TIMEOUT:1501,RESPONSE_TIMEOUT:1502,RECIPIENT_DISCONNECTED:1503,RESPONSE_PAYLOAD_TOO_LARGE:1504,SEND_FAILED:1505,UNSUPPORTED_METHOD:1400,RECIPIENT_NOT_FOUND:1401,REQUEST_PAYLOAD_TOO_LARGE:1402,UNSUPPORTED_SERVER:1403,UNSUPPORTED_VERSION:1404},Of.ErrorMessage={APPLICATION_ERROR:`Application error in method handler`,CONNECTION_TIMEOUT:`Connection timeout`,RESPONSE_TIMEOUT:`Response timeout`,RECIPIENT_DISCONNECTED:`Recipient disconnected`,RESPONSE_PAYLOAD_TOO_LARGE:`Response payload too large`,SEND_FAILED:`Failed to send`,UNSUPPORTED_METHOD:`Method not supported at destination`,RECIPIENT_NOT_FOUND:`Recipient not found`,REQUEST_PAYLOAD_TOO_LARGE:`Request payload too large`,UNSUPPORTED_SERVER:`RPC not supported by server`,UNSUPPORTED_VERSION:`Unsupported RPC version`};var kf=15360;function Af(e){return new TextEncoder().encode(e).length}function jf(e,t){if(Af(e)<=t)return e;let n=0,r=e.length,i=new TextEncoder;for(;n<r;){let a=Math.floor((n+r+1)/2);i.encode(e.slice(0,a)).length<=t?n=a:r=a-1}return e.slice(0,n)}var Mf=2e3;function Nf(e,t){if(!t)return 0;let n,r;return`bytesReceived`in e?(n=e.bytesReceived,r=t.bytesReceived):`bytesSent`in e&&(n=e.bytesSent,r=t.bytesSent),n===void 0||r===void 0||e.timestamp===void 0||t.timestamp===void 0?0:(n-r)*8*1e3/(e.timestamp-t.timestamp)}var Pf=typeof MediaRecorder<`u`,Ff=Pf?MediaRecorder:class{constructor(){throw Error(`MediaRecorder is not available in this environment`)}},If=class extends Ff{constructor(e,t){if(!Pf)throw Error(`MediaRecorder is not available in this environment`);super(new MediaStream([e.mediaStreamTrack]),t);let n,r,i=()=>r===void 0,a=()=>{this.removeEventListener(`dataavailable`,n),this.removeEventListener(`stop`,a),this.removeEventListener(`error`,o),r?.close(),r=void 0},o=e=>{r?.error(e),this.removeEventListener(`dataavailable`,n),this.removeEventListener(`stop`,a),this.removeEventListener(`error`,o),r=void 0};this.byteStream=new ReadableStream({start:e=>{r=e,n=t=>N(this,void 0,void 0,function*(){let n;if(t.data.arrayBuffer){let e=yield t.data.arrayBuffer();n=new Uint8Array(e)}else if(t.data.byteArray)n=t.data.byteArray;else throw Error(`no data available!`);i()||e.enqueue(n)}),this.addEventListener(`dataavailable`,n)},cancel:()=>{a()}}),this.addEventListener(`stop`,a),this.addEventListener(`error`,o)}};function Lf(){return Pf}var Rf=1e3,zf=1e4,Bf=class extends U{get sender(){return this._sender}set sender(e){this._sender=e}get constraints(){return this._constraints}get hasPreConnectBuffer(){return!!this.localTrackRecorder}constructor(e,t,n){let r=arguments.length>3&&arguments[3]!==void 0?arguments[3]:!1,i=arguments.length>4?arguments[4]:void 0;super(e,t,i),this.manuallyStopped=!1,this.pendingDeviceChange=!1,this._isUpstreamPaused=!1,this.handleTrackMuteEvent=()=>this.debouncedTrackMuteHandler().catch(()=>this.log.debug(`track mute bounce got cancelled by an unmute event`,this.logContext)),this.debouncedTrackMuteHandler=cf(()=>N(this,void 0,void 0,function*(){yield this.pauseUpstream()}),5e3),this.handleTrackUnmuteEvent=()=>N(this,void 0,void 0,function*(){this.debouncedTrackMuteHandler.cancel(`unmute`),yield this.resumeUpstream()}),this.handleEnded=()=>{this.isInBackground&&(this.reacquireTrack=!0),this._mediaStreamTrack.removeEventListener(`mute`,this.handleTrackMuteEvent),this._mediaStreamTrack.removeEventListener(`unmute`,this.handleTrackUnmuteEvent),this.emit(B.Ended,this)},this.reacquireTrack=!1,this.providedByUser=r,this.muteLock=new ur,this.pauseUpstreamLock=new ur,this.trackChangeLock=new ur,this.trackChangeLock.lock().then(t=>N(this,void 0,void 0,function*(){try{yield this.setMediaStreamTrack(e,!0)}finally{t()}})),this._constraints=e.getConstraints(),n&&(this._constraints=n)}get id(){return this._mediaStreamTrack.id}get dimensions(){if(this.kind!==U.Kind.Video)return;let{width:e,height:t}=this._mediaStreamTrack.getSettings();if(e&&t)return{width:e,height:t}}get isUpstreamPaused(){return this._isUpstreamPaused}get isUserProvided(){return this.providedByUser}get mediaStreamTrack(){return this.processor?.processedTrack??this._mediaStreamTrack}get isLocal(){return!0}getSourceTrackSettings(){return this._mediaStreamTrack.getSettings()}setMediaStreamTrack(e,t,n){return N(this,void 0,void 0,function*(){if(e===this._mediaStreamTrack&&!t)return;this._mediaStreamTrack&&(this.attachedElements.forEach(e=>{Yl(this._mediaStreamTrack,e)}),this.debouncedTrackMuteHandler.cancel(`new-track`),this._mediaStreamTrack.removeEventListener(`ended`,this.handleEnded),this._mediaStreamTrack.removeEventListener(`mute`,this.handleTrackMuteEvent),this._mediaStreamTrack.removeEventListener(`unmute`,this.handleTrackUnmuteEvent)),this.mediaStream=new MediaStream([e]),e&&(e.addEventListener(`ended`,this.handleEnded),e.addEventListener(`mute`,this.handleTrackMuteEvent),e.addEventListener(`unmute`,this.handleTrackUnmuteEvent),this._constraints=e.getConstraints());let r;if(this.processor&&e){if(this.log.debug(`restarting processor`,this.logContext),this.kind===`unknown`)throw TypeError(`cannot set processor on track of unknown kind`);this.processorElement&&(Jl(e,this.processorElement),this.processorElement.muted=!0),yield this.processor.restart({track:e,kind:this.kind,element:this.processorElement}),r=this.processor.processedTrack}this.sender&&this.sender.transport?.state!==`closed`&&(yield this.sender.replaceTrack(r??e)),!this.providedByUser&&this._mediaStreamTrack!==e&&this._mediaStreamTrack.stop(),this._mediaStreamTrack=e,e&&(this._mediaStreamTrack.enabled=n?!0:!this.isMuted,yield this.resumeUpstream(),this.attachedElements.forEach(t=>{Jl(r??e,t)}))})}waitForDimensions(){return N(this,arguments,void 0,function(){var e=this;let t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:Rf;return function*(){if(e.kind===U.Kind.Audio)throw Error(`cannot get dimensions for audio tracks`);tl()?.os===`iOS`&&(yield $l(10));let n=Date.now();for(;Date.now()-n<t;){let t=e.dimensions;if(t)return t;yield $l(50)}throw new ll(`unable to get track dimensions after timeout`)}()})}setDeviceId(e){return N(this,void 0,void 0,function*(){return this._constraints.deviceId===e&&this._mediaStreamTrack.getSettings().deviceId===Fu(e)?!0:(this._constraints.deviceId=e,this.isMuted?(this.pendingDeviceChange=!0,!0):(yield this.restartTrack(),Fu(e)===this._mediaStreamTrack.getSettings().deviceId))})}getDeviceId(){return N(this,arguments,void 0,function(){var e=this;let t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:!0;return function*(){if(e.source===U.Source.ScreenShare)return;let{deviceId:n,groupId:r}=e._mediaStreamTrack.getSettings(),i=e.kind===U.Kind.Audio?`audioinput`:`videoinput`;return t?Cd.getInstance().normalizeDeviceId(i,n,r):n}()})}mute(){return N(this,void 0,void 0,function*(){return this.setTrackMuted(!0),this})}unmute(){return N(this,void 0,void 0,function*(){return this.setTrackMuted(!1),this})}replaceTrack(e,t){return N(this,void 0,void 0,function*(){let n=yield this.trackChangeLock.lock();try{if(!this.sender)throw new ll(`unable to replace an unpublished track`);let n,r;return typeof t==`boolean`?n=t:t!==void 0&&(n=t.userProvidedTrack,r=t.stopProcessor),this.providedByUser=n??!0,this.log.debug(`replace MediaStreamTrack`,this.logContext),yield this.setMediaStreamTrack(e),r&&this.processor&&(yield this.internalStopProcessor()),this}finally{n()}})}restart(e,t){return N(this,void 0,void 0,function*(){this.manuallyStopped=!1;let n=yield this.trackChangeLock.lock();try{e||=this._constraints;let{deviceId:n,facingMode:r}=e,i=js(e,[`deviceId`,`facingMode`]);this.log.debug(`restarting track with constraints`,Object.assign(Object.assign({},this.logContext),{constraints:e}));let a={audio:!1,video:!1};this.kind===U.Kind.Video?a.video=n||r?{deviceId:n,facingMode:r}:!0:a.audio=n?Object.assign({deviceId:n},i):!0,this.attachedElements.forEach(e=>{Yl(this.mediaStreamTrack,e)}),this._mediaStreamTrack.removeEventListener(`ended`,this.handleEnded),this._mediaStreamTrack.stop();let o=(yield navigator.mediaDevices.getUserMedia(a)).getTracks()[0];return this.kind===U.Kind.Video&&(yield o.applyConstraints(i)),o.addEventListener(`ended`,this.handleEnded),this.log.debug(`re-acquired MediaStreamTrack`,this.logContext),yield this.setMediaStreamTrack(o,!1,t),this._constraints=e,this.pendingDeviceChange=!1,this.emit(B.Restarted,this),this.manuallyStopped&&(this.log.warn(`track was stopped during a restart, stopping restarted track`,this.logContext),this.stop()),this}finally{n()}})}setTrackMuted(e){this.log.debug(`setting ${this.kind} track ${e?`muted`:`unmuted`}`,this.logContext),!(this.isMuted===e&&this._mediaStreamTrack.enabled!==e)&&(this.isMuted=e,this._mediaStreamTrack.enabled=!e,this.emit(e?B.Muted:B.Unmuted,this))}get needsReAcquisition(){return this._mediaStreamTrack.readyState!==`live`||this._mediaStreamTrack.muted||!this._mediaStreamTrack.enabled||this.reacquireTrack}handleAppVisibilityChanged(){let e=Object.create(null,{handleAppVisibilityChanged:{get:()=>super.handleAppVisibilityChanged}});return N(this,void 0,void 0,function*(){yield e.handleAppVisibilityChanged.call(this),pu()&&(this.log.debug(`visibility changed, is in Background: ${this.isInBackground}`,this.logContext),!this.isInBackground&&this.needsReAcquisition&&!this.isUserProvided&&!this.isMuted&&(this.log.debug(`track needs to be reacquired, restarting ${this.source}`,this.logContext),yield this.restart(),this.reacquireTrack=!1))})}stop(){var e;this.manuallyStopped=!0,super.stop(),this._mediaStreamTrack.removeEventListener(`ended`,this.handleEnded),this._mediaStreamTrack.removeEventListener(`mute`,this.handleTrackMuteEvent),this._mediaStreamTrack.removeEventListener(`unmute`,this.handleTrackUnmuteEvent),(e=this.processor)==null||e.destroy(),this.processor=void 0}pauseUpstream(){return N(this,void 0,void 0,function*(){let e=yield this.pauseUpstreamLock.lock();try{if(this._isUpstreamPaused===!0)return;if(!this.sender){this.log.warn(`unable to pause upstream for an unpublished track`,this.logContext);return}this._isUpstreamPaused=!0,this.emit(B.UpstreamPaused,this);let e=tl();if(e?.name===`Safari`&&Su(e.version,`12.0`)<0)throw new cl(`pauseUpstream is not supported on Safari < 12.`);this.sender.transport?.state!==`closed`&&(yield this.sender.replaceTrack(null))}finally{e()}})}resumeUpstream(){return N(this,void 0,void 0,function*(){let e=yield this.pauseUpstreamLock.lock();try{if(this._isUpstreamPaused===!1)return;if(!this.sender){this.log.warn(`unable to resume upstream for an unpublished track`,this.logContext);return}this._isUpstreamPaused=!1,this.emit(B.UpstreamResumed,this),this.sender.transport?.state!==`closed`&&(yield this.sender.replaceTrack(this.mediaStreamTrack))}finally{e()}})}getRTCStatsReport(){return N(this,void 0,void 0,function*(){if(this.sender?.getStats)return yield this.sender.getStats()})}setProcessor(e){return N(this,arguments,void 0,function(e){var t=this;let n=arguments.length>1&&arguments[1]!==void 0?arguments[1]:!0;return function*(){let r=yield t.trackChangeLock.lock();try{t.log.debug(`setting up processor`,t.logContext);let r=document.createElement(t.kind),i={kind:t.kind,track:t._mediaStreamTrack,element:r,audioContext:t.audioContext};if(yield e.init(i),t.log.debug(`processor initialized`,t.logContext),t.processor&&(yield t.internalStopProcessor()),t.kind===`unknown`)throw TypeError(`cannot set processor on track of unknown kind`);if(Jl(t._mediaStreamTrack,r),r.muted=!0,r.play().catch(e=>{e instanceof DOMException&&e.name===`AbortError`?(t.log.warn(`failed to play processor element, retrying`,Object.assign(Object.assign({},t.logContext),{error:e})),setTimeout(()=>{r.play().catch(e=>{t.log.error(`failed to play processor element`,Object.assign(Object.assign({},t.logContext),{err:e}))})},100)):t.log.error(`failed to play processor element`,Object.assign(Object.assign({},t.logContext),{error:e}))}),t.processor=e,t.processorElement=r,t.processor.processedTrack){for(let e of t.attachedElements)e!==t.processorElement&&n&&(Yl(t._mediaStreamTrack,e),Jl(t.processor.processedTrack,e));yield t.sender?.replaceTrack(t.processor.processedTrack)}t.emit(B.TrackProcessorUpdate,t.processor)}finally{r()}}()})}getProcessor(){return this.processor}stopProcessor(){return N(this,arguments,void 0,function(){var e=this;let t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:!0;return function*(){let n=yield e.trackChangeLock.lock();try{yield e.internalStopProcessor(t)}finally{n()}}()})}internalStopProcessor(){return N(this,arguments,void 0,function(){var e=this;let t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:!0;return function*(){var n,r;e.processor&&(e.log.debug(`stopping processor`,e.logContext),(n=e.processor.processedTrack)==null||n.stop(),yield e.processor.destroy(),e.processor=void 0,t||((r=e.processorElement)==null||r.remove(),e.processorElement=void 0),yield e._mediaStreamTrack.applyConstraints(e._constraints),yield e.setMediaStreamTrack(e._mediaStreamTrack,!0),e.emit(B.TrackProcessorUpdate))}()})}startPreConnectBuffer(){let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:100;if(!Lf()){this.log.warn(`MediaRecorder is not available, cannot start preconnect buffer`,this.logContext);return}if(this.localTrackRecorder){this.log.warn(`preconnect buffer already started`);return}else{let e=`audio/webm;codecs=opus`;MediaRecorder.isTypeSupported(e)||(e=`video/mp4`),this.localTrackRecorder=new If(this,{mimeType:e})}this.localTrackRecorder.start(e),this.autoStopPreConnectBuffer=setTimeout(()=>{this.log.warn(`preconnect buffer timed out, stopping recording automatically`,this.logContext),this.stopPreConnectBuffer()},zf)}stopPreConnectBuffer(){clearTimeout(this.autoStopPreConnectBuffer),this.localTrackRecorder&&=(this.localTrackRecorder.stop(),void 0)}getPreConnectBuffer(){return this.localTrackRecorder?.byteStream}getPreConnectBufferMimeType(){return this.localTrackRecorder?.mimeType}},Vf=class extends Bf{get enhancedNoiseCancellation(){return this.isKrispNoiseFilterEnabled}constructor(e,t){let n=arguments.length>2&&arguments[2]!==void 0?arguments[2]:!0,r=arguments.length>3?arguments[3]:void 0,i=arguments.length>4?arguments[4]:void 0;super(e,U.Kind.Audio,t,n,i),this.stopOnMute=!1,this.isKrispNoiseFilterEnabled=!1,this.monitorSender=()=>N(this,void 0,void 0,function*(){if(!this.sender){this._currentBitrate=0;return}let e;try{e=yield this.getSenderStats()}catch(e){this.log.error(`could not get audio sender stats`,Object.assign(Object.assign({},this.logContext),{error:e}));return}e&&this.prevStats&&(this._currentBitrate=Nf(e,this.prevStats)),this.prevStats=e}),this.handleKrispNoiseFilterEnable=()=>{this.isKrispNoiseFilterEnabled=!0,this.log.debug(`Krisp noise filter enabled`,this.logContext),this.emit(B.AudioTrackFeatureUpdate,this,_a.TF_ENHANCED_NOISE_CANCELLATION,!0)},this.handleKrispNoiseFilterDisable=()=>{this.isKrispNoiseFilterEnabled=!1,this.log.debug(`Krisp noise filter disabled`,this.logContext),this.emit(B.AudioTrackFeatureUpdate,this,_a.TF_ENHANCED_NOISE_CANCELLATION,!1)},this.audioContext=r,this.checkForSilence()}mute(){let e=Object.create(null,{mute:{get:()=>super.mute}});return N(this,void 0,void 0,function*(){let t=yield this.muteLock.lock();try{return this.isMuted?(this.log.debug(`Track already muted`,this.logContext),this):(this.source===U.Source.Microphone&&this.stopOnMute&&!this.isUserProvided&&(this.log.debug(`stopping mic track`,this.logContext),this._mediaStreamTrack.stop()),yield e.mute.call(this),this)}finally{t()}})}unmute(){let e=Object.create(null,{unmute:{get:()=>super.unmute}});return N(this,void 0,void 0,function*(){let t=yield this.muteLock.lock();try{return this.isMuted?(this.source===U.Source.Microphone&&(this.stopOnMute||this._mediaStreamTrack.readyState===`ended`||this.pendingDeviceChange)&&!this.isUserProvided&&(this.log.debug(`reacquiring mic track`,this.logContext),yield this.restart(void 0,!0)),yield e.unmute.call(this),this):(this.log.debug(`Track already unmuted`,this.logContext),this)}finally{t()}})}restartTrack(e){return N(this,void 0,void 0,function*(){let t;if(e){let n=jl({audio:e});typeof n.audio!=`boolean`&&(t=n.audio)}yield this.restart(t)})}restart(e,t){let n=Object.create(null,{restart:{get:()=>super.restart}});return N(this,void 0,void 0,function*(){let r=yield n.restart.call(this,e,t);return this.checkForSilence(),r})}startMonitor(){hu()&&(this.monitorInterval||=setInterval(()=>{this.monitorSender()},Mf))}setProcessor(e){return N(this,void 0,void 0,function*(){let t=yield this.trackChangeLock.lock();try{if(!gu()&&!this.audioContext)throw Error(`Audio context needs to be set on LocalAudioTrack in order to enable processors`);this.processor&&(yield this.internalStopProcessor());let t={kind:this.kind,track:this._mediaStreamTrack,audioContext:this.audioContext};this.log.debug(`setting up audio processor ${e.name}`,this.logContext),yield e.init(t),this.processor=e,this.processor.processedTrack&&(yield this.sender?.replaceTrack(this.processor.processedTrack),this.processor.processedTrack.addEventListener(`enable-lk-krisp-noise-filter`,this.handleKrispNoiseFilterEnable),this.processor.processedTrack.addEventListener(`disable-lk-krisp-noise-filter`,this.handleKrispNoiseFilterDisable)),this.emit(B.TrackProcessorUpdate,this.processor)}finally{t()}})}setAudioContext(e){this.audioContext=e}getSenderStats(){return N(this,void 0,void 0,function*(){if(!this.sender?.getStats)return;let e=yield this.sender.getStats(),t;return e.forEach(e=>{e.type===`outbound-rtp`&&(t={type:`audio`,streamId:e.id,packetsSent:e.packetsSent,packetsLost:e.packetsLost,bytesSent:e.bytesSent,timestamp:e.timestamp,roundTripTime:e.roundTripTime,jitter:e.jitter})}),t})}checkForSilence(){return N(this,void 0,void 0,function*(){let e=yield Ml(this);return e&&(this.isMuted||this.log.debug(`silence detected on local audio track`,this.logContext),this.emit(B.AudioSilenceDetected)),e})}};function Hf(e,t,n){switch(e.kind){case`audio`:return new Vf(e,t,!1,void 0,n);case`video`:return new op(e,t,!1,n);default:throw new ll(`unsupported track type: ${e.kind}`)}}var Uf=Object.values(El),Wf=Object.values(Dl),Gf=Object.values(Ol),Kf=[El.h180,El.h360],qf=[Dl.h180,Dl.h360],Jf=e=>[{scaleResolutionDownBy:2,fps:e.encoding.maxFramerate}].map(t=>new V(Math.floor(e.width/t.scaleResolutionDownBy),Math.floor(e.height/t.scaleResolutionDownBy),Math.max(15e4,Math.floor(e.encoding.maxBitrate/(t.scaleResolutionDownBy**2*((e.encoding.maxFramerate??30)/(t.fps??30))))),t.fps,e.encoding.priority)),Yf=[`q`,`h`,`f`];function Xf(e,t,n,r){let i=r?.videoEncoding;e&&(i=r?.screenShareEncoding);let a=r?.simulcast,o=r?.scalabilityMode,s=r?.videoCodec;if(!i&&!a&&!o||!t||!n)return[{}];i||(i=Qf(e,t,n,s),M.debug(`using video encoding`,i));let c=i.maxFramerate,l=new V(t,n,i.maxBitrate,i.maxFramerate,i.priority);if(o&&iu(s)){let e=new rp(o),t=[];if(e.spatial>3)throw Error(`unsupported scalabilityMode: ${o}`);let n=tl();if(uu()||gu()||n?.name===`Chrome`&&Su(n?.version,`113`)<0){let r=e.suffix==`h`?2:3,a=fu(n);for(let n=0;n<e.spatial;n+=1)t.push({rid:Yf[2-n],maxBitrate:i.maxBitrate/r**+n,maxFramerate:l.encoding.maxFramerate,scaleResolutionDownBy:a?2**n:void 0});t[0].scalabilityMode=o}else t.push({maxBitrate:i.maxBitrate,maxFramerate:l.encoding.maxFramerate,scalabilityMode:o});return l.encoding.priority&&(t[0].priority=l.encoding.priority,t[0].networkPriority=l.encoding.priority),M.debug(`using svc encoding`,{encodings:t}),t}if(!a)return[i];let u=[];u=e?np(r?.screenShareSimulcastLayers)??ep(e,l):np(r?.videoSimulcastLayers)??ep(e,l);let d;if(u.length>0){let e=u[0];u.length>1&&([,d]=u);let r=Math.max(t,n);if(r>=960&&d)return tp(t,n,[e,d,l],c);if(r>=480)return tp(t,n,[e,l],c)}return tp(t,n,[l])}function Zf(e,t,n){if(!n.backupCodec||n.backupCodec===!0||n.backupCodec.codec===n.videoCodec)return;t!==n.backupCodec.codec&&M.warn(`requested a different codec than specified as backup`,{serverRequested:t,backup:n.backupCodec.codec}),n.videoCodec=t,n.videoEncoding=n.backupCodec.encoding;let r=e.mediaStreamTrack.getSettings(),i=r.width??e.dimensions?.width,a=r.height??e.dimensions?.height;return e.source===U.Source.ScreenShare&&n.simulcast&&(n.simulcast=!1),Xf(e.source===U.Source.ScreenShare,i,a,n)}function Qf(e,t,n,r){let i=$f(e,t,n),{encoding:a}=i[0],o=Math.max(t,n);for(let e=0;e<i.length;e+=1){let t=i[e];if(a=t.encoding,t.width>=o)break}if(r)switch(r){case`av1`:case`h265`:a=Object.assign({},a),a.maxBitrate*=.7;break;case`vp9`:a=Object.assign({},a),a.maxBitrate*=.85;break}return a}function $f(e,t,n){if(e)return Gf;let r=t>n?t/n:n/t;return Math.abs(r-16/9)<Math.abs(r-4/3)?Uf:Wf}function ep(e,t){if(e)return Jf(t);let{width:n,height:r}=t,i=n>r?n/r:r/n;return Math.abs(i-16/9)<Math.abs(i-4/3)?Kf:qf}function tp(e,t,n,r){let i=[];if(n.forEach((n,a)=>{if(a>=Yf.length)return;let o=Math.min(e,t),s={rid:Yf[a],scaleResolutionDownBy:Math.max(1,o/Math.min(n.width,n.height)),maxBitrate:n.encoding.maxBitrate},c=r&&n.encoding.maxFramerate?Math.min(r,n.encoding.maxFramerate):n.encoding.maxFramerate;c&&(s.maxFramerate=c);let l=su()||a===0;n.encoding.priority&&l&&(s.priority=n.encoding.priority,s.networkPriority=n.encoding.priority),i.push(s)}),gu()&&bu()===`ios`){let e;i.forEach(t=>{e?t.maxFramerate&&t.maxFramerate>e&&(e=t.maxFramerate):e=t.maxFramerate});let t=!0;i.forEach(n=>{n.maxFramerate!=e&&(t&&(t=!1,M.info(`Simulcast on iOS React-Native requires all encodings to share the same framerate.`)),M.info(`Setting framerate of encoding "${n.rid??``}" to ${e}`),n.maxFramerate=e)})}return i}function np(e){if(e)return e.sort((e,t)=>{let{encoding:n}=e,{encoding:r}=t;return n.maxBitrate>r.maxBitrate?1:n.maxBitrate<r.maxBitrate?-1:n.maxBitrate===r.maxBitrate&&n.maxFramerate&&r.maxFramerate?n.maxFramerate>r.maxFramerate?1:-1:0})}var rp=class{constructor(e){let t=e.match(/^L(\d)T(\d)(h|_KEY|_KEY_SHIFT){0,1}$/);if(!t)throw Error(`invalid scalability mode`);if(this.spatial=parseInt(t[1]),this.temporal=parseInt(t[2]),t.length>3)switch(t[3]){case`h`:case`_KEY`:case`_KEY_SHIFT`:this.suffix=t[3]}}toString(){return`L${this.spatial}T${this.temporal}${this.suffix??``}`}};function ip(e){return e.source===U.Source.ScreenShare||e.constraints.height&&Fu(e.constraints.height)>=1080?`maintain-resolution`:`balanced`}var ap=5e3,op=class extends Bf{get sender(){return this._sender}set sender(e){this._sender=e,this.degradationPreference&&this.setDegradationPreference(this.degradationPreference)}constructor(e,t){let n=arguments.length>2&&arguments[2]!==void 0?arguments[2]:!0,r=arguments.length>3?arguments[3]:void 0;super(e,U.Kind.Video,t,n,r),this.simulcastCodecs=new Map,this.degradationPreference=`balanced`,this.isCpuConstrained=!1,this.optimizeForPerformance=!1,this.monitorSender=()=>N(this,void 0,void 0,function*(){if(!this.sender){this._currentBitrate=0;return}let e;try{e=yield this.getSenderStats()}catch(e){this.log.error(`could not get video sender stats`,Object.assign(Object.assign({},this.logContext),{error:e}));return}let t=new Map(e.map(e=>[e.rid,e])),n=e.some(e=>e.qualityLimitationReason===`cpu`);if(n!==this.isCpuConstrained&&(this.isCpuConstrained=n,this.isCpuConstrained&&this.emit(B.CpuConstrained)),this.prevStats){let e=0;t.forEach((t,n)=>{let r=this.prevStats?.get(n);e+=Nf(t,r)}),this._currentBitrate=e}this.prevStats=t}),this.senderLock=new ur}get isSimulcast(){return!!(this.sender&&this.sender.getParameters().encodings.length>1)}startMonitor(e){if(this.signalClient=e,!hu())return;let t=this.sender?.getParameters();t&&(this.encodings=t.encodings),!this.monitorInterval&&(this.monitorInterval=setInterval(()=>{this.monitorSender()},Mf))}stop(){this._mediaStreamTrack.getConstraints(),this.simulcastCodecs.forEach(e=>{e.mediaStreamTrack.stop()}),super.stop()}pauseUpstream(){let e=Object.create(null,{pauseUpstream:{get:()=>super.pauseUpstream}});return N(this,void 0,void 0,function*(){var t,n,r,i;yield e.pauseUpstream.call(this);try{for(var a=!0,o=Is(this.simulcastCodecs.values()),s;s=yield o.next(),t=s.done,!t;a=!0)i=s.value,a=!1,yield i.sender?.replaceTrack(null)}catch(e){n={error:e}}finally{try{!a&&!t&&(r=o.return)&&(yield r.call(o))}finally{if(n)throw n.error}}})}resumeUpstream(){let e=Object.create(null,{resumeUpstream:{get:()=>super.resumeUpstream}});return N(this,void 0,void 0,function*(){var t,n,r,i;yield e.resumeUpstream.call(this);try{for(var a=!0,o=Is(this.simulcastCodecs.values()),s;s=yield o.next(),t=s.done,!t;a=!0){i=s.value,a=!1;let e=i;yield e.sender?.replaceTrack(e.mediaStreamTrack)}}catch(e){n={error:e}}finally{try{!a&&!t&&(r=o.return)&&(yield r.call(o))}finally{if(n)throw n.error}}})}mute(){let e=Object.create(null,{mute:{get:()=>super.mute}});return N(this,void 0,void 0,function*(){let t=yield this.muteLock.lock();try{return this.isMuted?(this.log.debug(`Track already muted`,this.logContext),this):(this.source===U.Source.Camera&&!this.isUserProvided&&(this.log.debug(`stopping camera track`,this.logContext),this._mediaStreamTrack.stop()),yield e.mute.call(this),this)}finally{t()}})}unmute(){let e=Object.create(null,{unmute:{get:()=>super.unmute}});return N(this,void 0,void 0,function*(){let t=yield this.muteLock.lock();try{return this.isMuted?(this.source===U.Source.Camera&&!this.isUserProvided&&(this.log.debug(`reacquiring camera track`,this.logContext),yield this.restart(void 0,!0)),yield e.unmute.call(this),this):(this.log.debug(`Track already unmuted`,this.logContext),this)}finally{t()}})}setTrackMuted(e){super.setTrackMuted(e);for(let t of this.simulcastCodecs.values())t.mediaStreamTrack.enabled=!e}getSenderStats(){return N(this,void 0,void 0,function*(){if(!this.sender?.getStats)return[];let e=[],t=yield this.sender.getStats();return t.forEach(n=>{if(n.type===`outbound-rtp`){let r={type:`video`,streamId:n.id,frameHeight:n.frameHeight,frameWidth:n.frameWidth,framesPerSecond:n.framesPerSecond,framesSent:n.framesSent,firCount:n.firCount,pliCount:n.pliCount,nackCount:n.nackCount,packetsSent:n.packetsSent,bytesSent:n.bytesSent,qualityLimitationReason:n.qualityLimitationReason,qualityLimitationDurations:n.qualityLimitationDurations,qualityLimitationResolutionChanges:n.qualityLimitationResolutionChanges,rid:n.rid??n.id,retransmittedPacketsSent:n.retransmittedPacketsSent,targetBitrate:n.targetBitrate,timestamp:n.timestamp},i=t.get(n.remoteId);i&&(r.jitter=i.jitter,r.packetsLost=i.packetsLost,r.roundTripTime=i.roundTripTime),e.push(r)}}),e.sort((e,t)=>(t.frameWidth??0)-(e.frameWidth??0)),e})}setPublishingQuality(e){let t=[];for(let n=ql.LOW;n<=ql.HIGH;n+=1)t.push(new qo({quality:n,enabled:n<=e}));this.log.debug(`setting publishing quality. max quality ${e}`,this.logContext),this.setPublishingLayers(iu(this.codec),t)}restartTrack(e){return N(this,void 0,void 0,function*(){var t,n,r,i;let a;if(e){let t=jl({video:e});typeof t.video!=`boolean`&&(a=t.video)}yield this.restart(a),this.isCpuConstrained=!1;try{for(var o=!0,s=Is(this.simulcastCodecs.values()),c;c=yield s.next(),t=c.done,!t;o=!0){i=c.value,o=!1;let e=i;e.sender&&e.sender.transport?.state!==`closed`&&(e.mediaStreamTrack=this.mediaStreamTrack.clone(),yield e.sender.replaceTrack(e.mediaStreamTrack))}}catch(e){n={error:e}}finally{try{!o&&!t&&(r=s.return)&&(yield r.call(s))}finally{if(n)throw n.error}}})}setProcessor(e){let t=Object.create(null,{setProcessor:{get:()=>super.setProcessor}});return N(this,arguments,void 0,function(e){var n=this;let r=arguments.length>1&&arguments[1]!==void 0?arguments[1]:!0;return function*(){var i,a,o,s;if(yield t.setProcessor.call(n,e,r),n.processor?.processedTrack)try{for(var c=!0,l=Is(n.simulcastCodecs.values()),u;u=yield l.next(),i=u.done,!i;c=!0)s=u.value,c=!1,yield s.sender?.replaceTrack(n.processor.processedTrack)}catch(e){a={error:e}}finally{try{!c&&!i&&(o=l.return)&&(yield o.call(l))}finally{if(a)throw a.error}}}()})}setDegradationPreference(e){return N(this,void 0,void 0,function*(){if(this.degradationPreference=e,this.sender)try{this.log.debug(`setting degradationPreference to ${e}`,this.logContext);let t=this.sender.getParameters();t.degradationPreference=e,this.sender.setParameters(t)}catch(e){this.log.warn(`failed to set degradationPreference`,Object.assign({error:e},this.logContext))}})}addSimulcastTrack(e,t){if(this.simulcastCodecs.has(e)){this.log.error(`${e} already added, skipping adding simulcast codec`,this.logContext);return}let n={codec:e,mediaStreamTrack:this.mediaStreamTrack.clone(),sender:void 0,encodings:t};return this.simulcastCodecs.set(e,n),n}setSimulcastTrackSender(e,t){let n=this.simulcastCodecs.get(e);n&&(n.sender=t,setTimeout(()=>{this.subscribedCodecs&&this.setPublishingCodecs(this.subscribedCodecs)},ap))}setPublishingCodecs(e){return N(this,void 0,void 0,function*(){var t,n,r,i,a,o,s;if(this.log.debug(`setting publishing codecs`,Object.assign(Object.assign({},this.logContext),{codecs:e,currentCodec:this.codec})),!this.codec&&e.length>0)return yield this.setPublishingLayers(iu(e[0].codec),e[0].qualities),[];this.subscribedCodecs=e;let c=[];try{for(t=!0,n=Is(e);r=yield n.next(),i=r.done,!i;t=!0){s=r.value,t=!1;let e=s;if(!this.codec||this.codec===e.codec)yield this.setPublishingLayers(iu(e.codec),e.qualities);else{let t=this.simulcastCodecs.get(e.codec);if(this.log.debug(`try setPublishingCodec for ${e.codec}`,Object.assign(Object.assign({},this.logContext),{simulcastCodecInfo:t})),!t||!t.sender){for(let t of e.qualities)if(t.enabled){c.push(e.codec);break}}else t.encodings&&(this.log.debug(`try setPublishingLayersForSender ${e.codec}`,this.logContext),yield sp(t.sender,t.encodings,e.qualities,this.senderLock,iu(e.codec),this.log,this.logContext))}}}catch(e){a={error:e}}finally{try{!t&&!i&&(o=n.return)&&(yield o.call(n))}finally{if(a)throw a.error}}return c})}setPublishingLayers(e,t){return N(this,void 0,void 0,function*(){if(this.optimizeForPerformance){this.log.info(`skipping setPublishingLayers due to optimized publishing performance`,Object.assign(Object.assign({},this.logContext),{qualities:t}));return}this.log.debug(`setting publishing layers`,Object.assign(Object.assign({},this.logContext),{qualities:t})),!(!this.sender||!this.encodings)&&(yield sp(this.sender,this.encodings,t,this.senderLock,e,this.log,this.logContext))})}prioritizePerformance(){return N(this,void 0,void 0,function*(){if(!this.sender)throw Error(`sender not found`);let e=yield this.senderLock.lock();try{this.optimizeForPerformance=!0;let e=this.sender.getParameters();e.encodings=e.encodings.map((e,t)=>Object.assign(Object.assign({},e),{active:t===0,scaleResolutionDownBy:Math.max(1,Math.ceil((this.mediaStreamTrack.getSettings().height??360)/360)),scalabilityMode:t===0&&iu(this.codec)?`L1T3`:void 0,maxFramerate:t===0?15:0,maxBitrate:t===0?e.maxBitrate:0})),this.log.debug(`setting performance optimised encodings`,Object.assign(Object.assign({},this.logContext),{encodings:e.encodings})),this.encodings=e.encodings,yield this.sender.setParameters(e)}catch(e){this.log.error(`failed to set performance optimised encodings`,Object.assign(Object.assign({},this.logContext),{error:e})),this.optimizeForPerformance=!1}finally{e()}})}handleAppVisibilityChanged(){let e=Object.create(null,{handleAppVisibilityChanged:{get:()=>super.handleAppVisibilityChanged}});return N(this,void 0,void 0,function*(){yield e.handleAppVisibilityChanged.call(this),pu()&&this.isInBackground&&this.source===U.Source.Camera&&(this._mediaStreamTrack.enabled=!1)})}};function sp(e,t,n,r,i,a,o){return N(this,void 0,void 0,function*(){let s=yield r.lock();a.debug(`setPublishingLayersForSender`,Object.assign(Object.assign({},o),{sender:e,qualities:n,senderEncodings:t}));try{let r=e.getParameters(),{encodings:s}=r;if(!s)return;if(s.length!==t.length){a.warn(`cannot set publishing layers, encodings mismatch`,Object.assign(Object.assign({},o),{encodings:s,senderEncodings:t}));return}let c=!1;i&&n.some(e=>e.enabled)&&n.forEach(e=>e.enabled=!0),s.forEach((e,r)=>{let i=e.rid??``;i===``&&(i=`q`);let s=cp(i),l=n.find(e=>e.quality===s);l&&e.active!==l.enabled&&(c=!0,e.active=l.enabled,a.debug(`setting layer ${l.quality} to ${e.active?`enabled`:`disabled`}`,o),su()&&(l.enabled?(e.scaleResolutionDownBy=t[r].scaleResolutionDownBy,e.maxBitrate=t[r].maxBitrate,e.maxFrameRate=t[r].maxFrameRate):(e.scaleResolutionDownBy=4,e.maxBitrate=10,e.maxFrameRate=2)))}),c&&(r.encodings=s,a.debug(`setting encodings`,Object.assign(Object.assign({},o),{encodings:r.encodings})),yield e.setParameters(r))}finally{s()}})}function cp(e){switch(e){case`f`:return ql.HIGH;case`h`:return ql.MEDIUM;case`q`:return ql.LOW;default:return ql.HIGH}}function lp(e,t,n,r){if(!n)return[new ka({quality:ql.HIGH,width:e,height:t,bitrate:0,ssrc:0})];if(r){let r=n[0].scalabilityMode,i=new rp(r),a=[],o=i.suffix==`h`?1.5:2,s=i.suffix==`h`?2:3;for(let r=0;r<i.spatial;r+=1)a.push(new ka({quality:Math.min(ql.HIGH,i.spatial-1)-r,width:Math.ceil(e/o**+r),height:Math.ceil(t/o**+r),bitrate:n[0].maxBitrate?Math.ceil(n[0].maxBitrate/s**+r):0,ssrc:0}));return a}return n.map(n=>{let r=n.scaleResolutionDownBy??1;return new ka({quality:cp(n.rid??``),width:Math.ceil(e/r),height:Math.ceil(t/r),bitrate:n.maxBitrate??0,ssrc:0})})}var up=`_lossy`,dp=`_reliable`,fp=`_data_track`,pp=2*1e3,mp=`leave-reconnect`,hp=3e4,gp=8*1024,_p=256*1024,vp=3,yp=3,bp;(function(e){e[e.New=0]=`New`,e[e.Connected=1]=`Connected`,e[e.Disconnected=2]=`Disconnected`,e[e.Reconnecting=3]=`Reconnecting`,e[e.Closed=4]=`Closed`})(bp||={});var K;(function(e){e[e.RELIABLE=0]=`RELIABLE`,e[e.LOSSY=1]=`LOSSY`,e[e.DATA_TRACK_LOSSY=2]=`DATA_TRACK_LOSSY`})(K||={});var xp=class extends Bs.EventEmitter{get isClosed(){return this._isClosed}get isNewlyCreated(){return this._isNewlyCreated}get pendingReconnect(){return!!this.reconnectTimeout}constructor(e){super(),this.options=e,this.rtcConfig={},this.peerConnectionTimeout=Sf.peerConnectionTimeout,this.fullReconnectOnNext=!1,this.latestRemoteOfferId=0,this.subscriberPrimary=!1,this.pcState=bp.New,this._isClosed=!0,this._isNewlyCreated=!0,this.pendingTrackResolvers={},this.reconnectAttempts=0,this.reconnectStart=0,this.attemptingReconnect=!1,this.joinAttempts=0,this.maxJoinAttempts=1,this.shouldFailNext=!1,this.log=M,this.reliableDataSequence=1,this.reliableMessageBuffer=new Kd,this.reliableReceivedState=new qd(hp),this.lossyDataStatCurrentBytes=0,this.lossyDataStatByterate=0,this.lossyDataDropCount=0,this.midToTrackId={},this.isWaitingForNetworkReconnect=!1,this.handleDataChannel=e=>N(this,[e],void 0,function(e){var t=this;let{channel:n}=e;return function*(){if(!n)return;let e;if(n.label===dp)t.reliableDCSub=n,e=t.handleDataMessage;else if(n.label===up)t.lossyDCSub=n,e=t.handleDataMessage;else if(n.label===fp)t.dataTrackDCSub=n,e=t.handleDataTrackMessage;else return;t.log.debug(`on data channel ${n.id}, ${n.label}`,t.logContext),n.onmessage=e}()}),this.handleDataMessage=e=>N(this,void 0,void 0,function*(){let t=yield this.dataProcessLock.lock();try{let t;if(e.data instanceof ArrayBuffer)t=e.data;else if(e.data instanceof Blob)t=yield e.data.arrayBuffer();else{this.log.error(`unsupported data type`,Object.assign(Object.assign({},this.logContext),{data:e.data}));return}let n=ja.fromBinary(new Uint8Array(t));if(n.sequence>0&&n.participantSid!==``){let e=this.reliableReceivedState.get(n.participantSid);if(e&&n.sequence<=e)return;this.reliableReceivedState.set(n.participantSid,n.sequence)}if(n.value?.case===`speaker`)this.emit(z.ActiveSpeakersUpdate,n.value.value.speakers);else if(n.value?.case===`encryptedPacket`){if(!this.e2eeManager){this.log.error(`Received encrypted packet but E2EE not set up`,this.logContext);return}let e=yield this.e2eeManager?.handleEncryptedData(n.value.value.encryptedValue,n.value.value.iv,n.participantIdentity,n.value.value.keyIndex),t=new ja({value:Pa.fromBinary(e.payload).value,participantIdentity:n.participantIdentity,participantSid:n.participantSid});t.value?.case===`user`&&Sp(t,t.value.value),this.emit(z.DataPacketReceived,t,n.value.value.encryptionType)}else n.value?.case===`user`&&Sp(n,n.value.value),this.emit(z.DataPacketReceived,n,j.NONE)}finally{t()}}),this.handleDataTrackMessage=e=>N(this,void 0,void 0,function*(){let t;if(e.data instanceof ArrayBuffer)t=e.data;else if(e.data instanceof Blob)t=yield e.data.arrayBuffer();else{this.log.error(`unsupported data type`,Object.assign(Object.assign({},this.logContext),{data:e.data}));return}this.emit(`dataTrackPacketReceived`,new Uint8Array(t))}),this.handleDataError=e=>{let t=e.currentTarget.maxRetransmits===0?`lossy`:`reliable`;if(e instanceof ErrorEvent&&e.error){let{error:n}=e.error;this.log.error(`DataChannel error on ${t}: ${e.message}`,Object.assign(Object.assign({},this.logContext),{error:n}))}else this.log.error(`Unknown DataChannel error on ${t}`,Object.assign(Object.assign({},this.logContext),{event:e}))},this.handleBufferedAmountLow=e=>{this.updateAndEmitDCBufferStatus(e)},this.handleDisconnect=(e,t)=>{if(this._isClosed)return;this.log.warn(`${e} disconnected`,this.logContext),this.reconnectAttempts===0&&(this.reconnectStart=Date.now());let n=e=>{this.log.warn(`could not recover connection after ${this.reconnectAttempts} attempts, ${e}ms. giving up`,this.logContext),this.emit(z.Disconnected),this.close()},r=Date.now()-this.reconnectStart,i=this.getNextRetryDelay({elapsedMs:r,retryCount:this.reconnectAttempts});if(i===null){n(r);return}e===mp&&(i=0),this.log.debug(`reconnecting in ${i}ms`,this.logContext),this.clearReconnectTimeout(),this.token&&this.regionUrlProvider&&this.regionUrlProvider.updateToken(this.token),this.reconnectTimeout=vl.setTimeout(()=>this.attemptReconnect(t).finally(()=>this.reconnectTimeout=void 0),i)},this.waitForRestarted=()=>new Promise((e,t)=>{this.pcState===bp.Connected&&e();let n=()=>{this.off(z.Disconnected,r),e()},r=()=>{this.off(z.Restarted,n),t()};this.once(z.Restarted,n),this.once(z.Disconnected,r)}),this.updateAndEmitDCBufferStatus=e=>{if(e===K.RELIABLE){let t=this.dataChannelForKind(e);t&&this.reliableMessageBuffer.alignBufferedAmount(t.bufferedAmount)}let t=this.isBufferStatusLow(e);t!==void 0&&t!==this.dcBufferStatus.get(e)&&(this.dcBufferStatus.set(e,t),this.emit(z.DCBufferStatusChanged,t,e))},this.isBufferStatusLow=e=>{let t=this.dataChannelForKind(e);if(t)return t.bufferedAmount<=t.bufferedAmountLowThreshold},this.handleBrowserOnLine=()=>N(this,void 0,void 0,function*(){this.url&&(yield fetch(Lu(this.url),{method:`HEAD`}).then(e=>e.ok).catch(()=>!1))&&(this.log.info(`detected network reconnected`),(this.client.currentState===W.RECONNECTING||this.isWaitingForNetworkReconnect&&this.client.currentState===W.CONNECTED)&&(this.clearReconnectTimeout(),this.attemptReconnect(ha.RR_SIGNAL_DISCONNECTED),this.isWaitingForNetworkReconnect=!1))}),this.handleBrowserOffline=()=>N(this,void 0,void 0,function*(){if(this.url)try{yield Promise.race([fetch(Lu(this.url),{method:`HEAD`}),$l(4e3).then(()=>Promise.reject())])}catch{window.navigator.onLine===!1&&(this.log.info(`detected network interruption`),this.isWaitingForNetworkReconnect=!0)}}),this.log=Es(e.loggerName??Ts.Engine),this.loggerOptions={loggerName:e.loggerName,loggerContextCb:()=>this.logContext},this.client=new Vd(void 0,this.loggerOptions),this.client.signalLatency=this.options.expSignalLatency,this.reconnectPolicy=this.options.reconnectPolicy,this.closingLock=new ur,this.dataProcessLock=new ur,this.dcBufferStatus=new Map([[K.RELIABLE,!0],[K.LOSSY,!0],[K.DATA_TRACK_LOSSY,!0]]),this.client.onParticipantUpdate=e=>this.emit(z.ParticipantUpdate,e),this.client.onConnectionQuality=e=>this.emit(z.ConnectionQualityUpdate,e),this.client.onRoomUpdate=e=>this.emit(z.RoomUpdate,e),this.client.onSubscriptionError=e=>this.emit(z.SubscriptionError,e),this.client.onSubscriptionPermissionUpdate=e=>this.emit(z.SubscriptionPermissionUpdate,e),this.client.onSpeakersChanged=e=>this.emit(z.SpeakersChanged,e),this.client.onStreamStateUpdate=e=>this.emit(z.StreamStateChanged,e),this.client.onRequestResponse=e=>this.emit(z.SignalRequestResponse,e),this.client.onParticipantUpdate=e=>this.emit(z.ParticipantUpdate,e),this.client.onJoined=e=>this.emit(z.Joined,e)}get logContext(){return{room:this.latestJoinResponse?.room?.name,roomID:this.latestJoinResponse?.room?.sid,participant:this.latestJoinResponse?.participant?.identity,participantID:this.participantSid}}join(e,t,n,r){return N(this,arguments,void 0,function(e,t,n,r){var i=this;let a=arguments.length>4&&arguments[4]!==void 0?arguments[4]:!1;return function*(){var o;i._isNewlyCreated=!1,i.url=e,i.token=t,i.signalOpts=n,i.maxJoinAttempts=n.maxRetries;try{i.joinAttempts+=1,i.setupSignalClientCallbacks();let s;if(!a&&ed()){i.pcManager||(yield i.configure(),i.createDataChannels(),i.addMediaSections(vp,yp));let e=yield i.pcManager?.publisher.createInitialOffer();e&&(s=Ud(e.offer,e.offerId))}if(r?.aborted)throw F.cancelled(`Connection aborted`);let c=yield i.client.join(e,t,n,r,a,s);return i._isClosed=!1,i.latestJoinResponse=c,i.participantSid=c.participant?.sid,i.subscriberPrimary=c.subscriberPrimary,!a&&ed()?(o=i.pcManager)==null||o.updateConfiguration(i.makeRTCConfiguration(c)):(i.pcManager||(yield i.configure(c,!a)),(!i.subscriberPrimary||c.fastPublish)&&i.negotiate().catch(e=>{M.error(e,i.logContext)})),i.registerOnLineListener(),i.clientConfiguration=c.clientConfiguration,i.emit(z.SignalConnected,c),c}catch(o){if(o instanceof F){if(o.reason===P.ServerUnreachable){if(i.log.warn(`Couldn't connect to server, attempt ${i.joinAttempts} of ${i.maxJoinAttempts}`,i.logContext),i.joinAttempts<i.maxJoinAttempts)return i.join(e,t,n,r,a)}else if(o.reason===P.ServiceNotFound)return i.log.warn(`Initial connection failed: ${o.message} – Retrying`),i.join(e,t,n,r,!0)}throw o}}()})}close(){return N(this,void 0,void 0,function*(){let e=yield this.closingLock.lock();if(this.isClosed){e();return}try{this._isClosed=!0,this.joinAttempts=0,this.emit(z.Closing),this.removeAllListeners(),this.deregisterOnLineListener(),this.clearPendingReconnect(),this.cleanupLossyDataStats(),yield this.cleanupPeerConnections(),yield this.cleanupClient()}finally{e()}})}cleanupPeerConnections(){return N(this,void 0,void 0,function*(){yield this.pcManager?.close(),this.pcManager=void 0;let e=e=>{e&&(e.close(),e.onbufferedamountlow=null,e.onclose=null,e.onclosing=null,e.onerror=null,e.onmessage=null,e.onopen=null)};e(this.lossyDC),e(this.lossyDCSub),e(this.reliableDC),e(this.reliableDCSub),e(this.dataTrackDC),e(this.dataTrackDCSub),this.lossyDC=void 0,this.lossyDCSub=void 0,this.reliableDC=void 0,this.reliableDCSub=void 0,this.dataTrackDC=void 0,this.dataTrackDCSub=void 0,this.reliableMessageBuffer=new Kd,this.reliableDataSequence=1,this.reliableReceivedState.clear()})}cleanupLossyDataStats(){this.lossyDataStatByterate=0,this.lossyDataStatCurrentBytes=0,this.lossyDataStatInterval&&=(clearInterval(this.lossyDataStatInterval),void 0),this.lossyDataDropCount=0}cleanupClient(){return N(this,void 0,void 0,function*(){yield this.client.close(),this.client.resetCallbacks()})}addTrack(e){if(this.pendingTrackResolvers[e.cid])throw new ll(`a track with the same ID has already been published`);return new Promise((t,n)=>{let r=setTimeout(()=>{delete this.pendingTrackResolvers[e.cid],n(F.timeout(`publication of local track timed out, no response from server`))},1e4);this.pendingTrackResolvers[e.cid]={resolve:e=>{clearTimeout(r),t(e)},reject:()=>{clearTimeout(r),n(Error(`Cancelled publication by calling unpublish`))}},this.client.sendAddTrack(e)})}removeTrack(e){if(e.track&&this.pendingTrackResolvers[e.track.id]){let{reject:t}=this.pendingTrackResolvers[e.track.id];t&&t(),delete this.pendingTrackResolvers[e.track.id]}try{return this.pcManager.removeTrack(e),!0}catch(e){this.log.warn(`failed to remove track`,Object.assign(Object.assign({},this.logContext),{error:e}))}return!1}updateMuteStatus(e,t){this.client.sendMuteTrack(e,t)}get dataSubscriberReadyState(){return this.reliableDCSub?.readyState}getConnectedServerAddress(){return N(this,void 0,void 0,function*(){return this.pcManager?.getConnectedAddress()})}setRegionUrlProvider(e){this.regionUrlProvider=e}configure(e,t){return N(this,void 0,void 0,function*(){if(!(this.pcManager&&this.pcManager.currentState!==G.NEW)){if(e){this.participantSid=e.participant?.sid;let n=this.makeRTCConfiguration(e);this.pcManager=new Cf(t?`publisher-only`:e.subscriberPrimary?`subscriber-primary`:`publisher-primary`,this.loggerOptions,n)}else{let e=this.makeRTCConfiguration();this.pcManager=new Cf(`publisher-only`,this.loggerOptions,e)}this.emit(z.TransportsCreated,this.pcManager.publisher,this.pcManager.subscriber),this.pcManager.onIceCandidate=(e,t)=>{this.client.sendIceCandidate(e,t)},this.pcManager.onPublisherOffer=(e,t)=>{this.client.sendOffer(e,t)},this.pcManager.onDataChannel=this.handleDataChannel,this.pcManager.onStateChange=(e,t,n)=>N(this,void 0,void 0,function*(){if(this.log.debug(`primary PC state changed ${e}`,this.logContext),[`closed`,`disconnected`,`failed`].includes(t)&&(this.publisherConnectionPromise=void 0),e===G.CONNECTED){let e=this.pcState===bp.New;this.pcState=bp.Connected,e&&this.emit(z.Connected,this.latestJoinResponse)}else e===G.FAILED&&(this.pcState===bp.Connected||this.pcState===bp.Reconnecting)&&(this.pcState=bp.Disconnected,this.handleDisconnect(`peerconnection failed`,n===`failed`?ha.RR_SUBSCRIBER_FAILED:ha.RR_PUBLISHER_FAILED));let r=this.client.isDisconnected||this.client.currentState===W.RECONNECTING,i=[G.FAILED,G.CLOSING,G.CLOSED].includes(e);r&&i&&!this._isClosed&&this.emit(z.Offline)}),this.pcManager.onTrack=e=>{e.streams.length!==0&&this.emit(z.MediaTrackAdded,e.track,e.streams[0],e.receiver)}}})}setupSignalClientCallbacks(){this.client.onAnswer=(e,t,n)=>N(this,void 0,void 0,function*(){this.pcManager&&(this.log.debug(`received server answer`,Object.assign(Object.assign({},this.logContext),{RTCSdpType:e.type,sdp:e.sdp,midToTrackId:n})),this.midToTrackId=n,yield this.pcManager.setPublisherAnswer(e,t))}),this.client.onTrickle=(e,t)=>{this.pcManager&&(this.log.debug(`got ICE candidate from peer`,Object.assign(Object.assign({},this.logContext),{candidate:e,target:t})),this.pcManager.addIceCandidate(e,t))},this.client.onOffer=(e,t,n)=>N(this,void 0,void 0,function*(){if(this.latestRemoteOfferId=t,!this.pcManager)return;this.midToTrackId=n;let r=yield this.pcManager.createSubscriberAnswerFromOffer(e,t);r&&this.client.sendAnswer(r,t)}),this.client.onLocalTrackPublished=e=>{if(this.log.debug(`received trackPublishedResponse`,Object.assign(Object.assign({},this.logContext),{cid:e.cid,track:e.track?.sid})),!this.pendingTrackResolvers[e.cid]){this.log.error(`missing track resolver for ${e.cid}`,Object.assign(Object.assign({},this.logContext),{cid:e.cid}));return}let{resolve:t}=this.pendingTrackResolvers[e.cid];delete this.pendingTrackResolvers[e.cid],t(e.track)},this.client.onLocalTrackUnpublished=e=>{this.emit(z.LocalTrackUnpublished,e)},this.client.onLocalTrackSubscribed=e=>{this.emit(z.LocalTrackSubscribed,e)},this.client.onTokenRefresh=e=>{var t;this.token=e,(t=this.regionUrlProvider)==null||t.updateToken(e)},this.client.onRemoteMuteChanged=(e,t)=>{this.emit(z.RemoteMute,e,t)},this.client.onSubscribedQualityUpdate=e=>{this.emit(z.SubscribedQualityUpdate,e)},this.client.onRoomMoved=e=>{this.participantSid=e.participant?.sid,this.latestJoinResponse&&(this.latestJoinResponse.room=e.room),this.emit(z.RoomMoved,e)},this.client.onMediaSectionsRequirement=e=>{this.addMediaSections(e.numAudios,e.numVideos),this.negotiate()},this.client.onPublishDataTrackResponse=e=>{this.emit(z.PublishDataTrackResponse,e)},this.client.onUnPublishDataTrackResponse=e=>{this.emit(z.UnPublishDataTrackResponse,e)},this.client.onDataTrackSubscriberHandles=e=>{this.emit(z.DataTrackSubscriberHandles,e)},this.client.onClose=()=>{this.handleDisconnect(`signal`,ha.RR_SIGNAL_DISCONNECTED)},this.client.onLeave=e=>{switch(this.log.debug(`client leave request`,Object.assign(Object.assign({},this.logContext),{reason:e?.reason})),e.regions&&this.regionUrlProvider&&(this.log.debug(`updating regions`,this.logContext),this.regionUrlProvider.setServerReportedRegions({updatedAtInMs:Date.now(),maxAgeInMs:wf,regionSettings:e.regions})),e.action){case Lo.DISCONNECT:this.emit(z.Disconnected,e?.reason),this.close();break;case Lo.RECONNECT:this.fullReconnectOnNext=!0,this.handleDisconnect(mp);break;case Lo.RESUME:this.handleDisconnect(mp)}}}makeRTCConfiguration(e){let t=Object.assign({},this.rtcConfig);if(this.signalOpts?.e2eeEnabled&&(this.log.debug(`E2EE - setting up transports with insertable streams`,this.logContext),t.encodedInsertableStreams=!0),t.sdpSemantics=`unified-plan`,t.continualGatheringPolicy=`gather_continually`,!e)return t;if(e.iceServers&&!t.iceServers){let n=[];e.iceServers.forEach(e=>{let t={urls:e.urls};e.username&&(t.username=e.username),e.credential&&(t.credential=e.credential),n.push(t)}),t.iceServers=n}return e.clientConfiguration&&e.clientConfiguration.forceRelay===pa.ENABLED&&(t.iceTransportPolicy=`relay`),t}addMediaSections(e,t){var n,r;let i={direction:`recvonly`};for(let t=0;t<e;t++)(n=this.pcManager)==null||n.addPublisherTransceiverOfKind(`audio`,i);for(let e=0;e<t;e++)(r=this.pcManager)==null||r.addPublisherTransceiverOfKind(`video`,i)}createDataChannels(){this.pcManager&&(this.lossyDC&&(this.lossyDC.onmessage=null,this.lossyDC.onerror=null),this.reliableDC&&(this.reliableDC.onmessage=null,this.reliableDC.onerror=null),this.dataTrackDC&&(this.dataTrackDC.onmessage=null,this.dataTrackDC.onerror=null),this.lossyDC=this.pcManager.createPublisherDataChannel(up,{ordered:!1,maxRetransmits:0}),this.reliableDC=this.pcManager.createPublisherDataChannel(dp,{ordered:!0}),this.dataTrackDC=this.pcManager.createPublisherDataChannel(fp,{ordered:!1,maxRetransmits:0}),this.lossyDC.onmessage=this.handleDataMessage,this.reliableDC.onmessage=this.handleDataMessage,this.dataTrackDC.onmessage=this.handleDataTrackMessage,this.lossyDC.onerror=this.handleDataError,this.reliableDC.onerror=this.handleDataError,this.dataTrackDC.onerror=this.handleDataError,this.lossyDC.bufferedAmountLowThreshold=65535,this.reliableDC.bufferedAmountLowThreshold=65535,this.dataTrackDC.bufferedAmountLowThreshold=65535,this.lossyDC.onbufferedamountlow=()=>this.handleBufferedAmountLow(K.LOSSY),this.reliableDC.onbufferedamountlow=()=>this.handleBufferedAmountLow(K.RELIABLE),this.dataTrackDC.onbufferedamountlow=()=>this.handleBufferedAmountLow(K.DATA_TRACK_LOSSY),this.cleanupLossyDataStats(),this.lossyDataStatInterval=setInterval(()=>{this.lossyDataStatByterate=this.lossyDataStatCurrentBytes,this.lossyDataStatCurrentBytes=0;let e=this.dataChannelForKind(K.LOSSY);if(e){let t=this.lossyDataStatByterate/10;e.bufferedAmountLowThreshold=Math.min(Math.max(t,gp),_p)}},1e3))}createSender(e,t,n){return N(this,void 0,void 0,function*(){if(eu())return yield this.createTransceiverRTCRtpSender(e,t,n);if(tu())return this.log.warn(`using add-track fallback`,this.logContext),yield this.createRTCRtpSender(e.mediaStreamTrack);throw new I(`Required webRTC APIs not supported on this device`)})}createSimulcastSender(e,t,n,r){return N(this,void 0,void 0,function*(){if(eu())return this.createSimulcastTransceiverSender(e,t,n,r);if(tu())return this.log.debug(`using add-track fallback`,this.logContext),this.createRTCRtpSender(e.mediaStreamTrack);throw new I(`Cannot stream on this device`)})}createTransceiverRTCRtpSender(e,t,n){return N(this,void 0,void 0,function*(){if(!this.pcManager)throw new I(`publisher is closed`);let r=[];e.mediaStream&&r.push(e.mediaStream),Gu(e)&&(e.codec=t.videoCodec);let i={direction:`sendonly`,streams:r};return n&&(i.sendEncodings=n),(yield this.pcManager.addPublisherTransceiver(e.mediaStreamTrack,i)).sender})}createSimulcastTransceiverSender(e,t,n,r){return N(this,void 0,void 0,function*(){if(!this.pcManager)throw new I(`publisher is closed`);let i={direction:`sendonly`};r&&(i.sendEncodings=r);let a=yield this.pcManager.addPublisherTransceiver(t.mediaStreamTrack,i);if(n.videoCodec)return e.setSimulcastTrackSender(n.videoCodec,a.sender),a.sender})}createRTCRtpSender(e){return N(this,void 0,void 0,function*(){if(!this.pcManager)throw new I(`publisher is closed`);return this.pcManager.addPublisherTrack(e)})}attemptReconnect(e){return N(this,void 0,void 0,function*(){if(!this._isClosed){if(this.attemptingReconnect){M.warn(`already attempting reconnect, returning early`,this.logContext);return}(this.clientConfiguration?.resumeConnection===pa.DISABLED||(this.pcManager?.currentState??G.NEW)===G.NEW)&&(this.fullReconnectOnNext=!0);try{this.attemptingReconnect=!0,this.fullReconnectOnNext?yield this.restartConnection():yield this.resumeConnection(e),this.clearPendingReconnect(),this.fullReconnectOnNext=!1}catch(e){this.reconnectAttempts+=1;let t=!0;e instanceof I?(this.log.debug(`received unrecoverable error`,Object.assign(Object.assign({},this.logContext),{error:e})),t=!1):e instanceof gl||(this.fullReconnectOnNext=!0),t?this.handleDisconnect(`reconnect`,ha.RR_UNKNOWN):(this.log.info(`could not recover connection after ${this.reconnectAttempts} attempts, ${Date.now()-this.reconnectStart}ms. giving up`,this.logContext),this.emit(z.Disconnected),yield this.close())}finally{this.attemptingReconnect=!1}}})}getNextRetryDelay(e){try{return this.reconnectPolicy.nextRetryDelayInMs(e)}catch(e){this.log.warn(`encountered error in reconnect policy`,Object.assign(Object.assign({},this.logContext),{error:e}))}return null}restartConnection(e){return N(this,void 0,void 0,function*(){var t,n;try{if(!this.url||!this.token)throw new I(`could not reconnect, url or token not saved`);this.log.info(`reconnecting, attempt: ${this.reconnectAttempts}`,this.logContext),this.emit(z.Restarting),this.client.isDisconnected||(yield this.client.sendLeave()),yield this.cleanupPeerConnections(),yield this.cleanupClient();let n;try{if(!this.signalOpts)throw this.log.warn(`attempted connection restart, without signal options present`,this.logContext),new gl;n=yield this.join(e??this.url,this.token,this.signalOpts,void 0,!this.options.singlePeerConnection)}catch(e){throw e instanceof F&&e.reason===P.NotAllowed?new I(`could not reconnect, token might be expired`):new gl}if(this.shouldFailNext)throw this.shouldFailNext=!1,Error(`simulated failure`);if(this.client.setReconnected(),this.emit(z.SignalRestarted,n),yield this.waitForPCReconnected(),this.client.currentState!==W.CONNECTED)throw new gl(`Signal connection got severed during reconnect`);(t=this.regionUrlProvider)==null||t.resetAttempts(),this.emit(z.Restarted)}catch(e){let t=yield this.regionUrlProvider?.getNextBestRegionUrl();if(t){yield this.restartConnection(t);return}else throw(n=this.regionUrlProvider)==null||n.resetAttempts(),e}})}resumeConnection(e){return N(this,void 0,void 0,function*(){if(!this.url||!this.token)throw new I(`could not reconnect, url or token not saved`);if(!this.pcManager)throw new I(`publisher and subscriber connections unset`);this.log.info(`resuming signal connection, attempt ${this.reconnectAttempts}`,this.logContext),this.emit(z.Resuming);let t;try{this.setupSignalClientCallbacks(),t=yield this.client.reconnect(this.url,this.token,this.participantSid,e)}catch(e){let t=``;throw e instanceof Error&&(t=e.message,this.log.error(e.message,Object.assign(Object.assign({},this.logContext),{error:e}))),e instanceof F&&e.reason===P.NotAllowed?new I(`could not reconnect, token might be expired`):e instanceof F&&e.reason===P.LeaveRequest?e:new gl(t)}if(this.emit(z.SignalResumed),t){let e=this.makeRTCConfiguration(t);this.pcManager.updateConfiguration(e),this.latestJoinResponse&&(this.latestJoinResponse.serverInfo=t.serverInfo)}else this.log.warn(`Did not receive reconnect response`,this.logContext);if(this.shouldFailNext)throw this.shouldFailNext=!1,Error(`simulated failure`);if(yield this.pcManager.triggerIceRestart(),yield this.waitForPCReconnected(),this.client.currentState!==W.CONNECTED)throw new gl(`Signal connection got severed during reconnect`);this.client.setReconnected(),this.reliableDC?.readyState===`open`&&this.reliableDC.id===null&&this.createDataChannels(),t?.lastMessageSeq&&this.resendReliableMessagesForResume(t.lastMessageSeq),this.emit(z.Resumed)})}waitForPCInitialConnection(e,t){return N(this,void 0,void 0,function*(){if(!this.pcManager)throw new I(`PC manager is closed`);yield this.pcManager.ensurePCTransportConnection(t,e)})}waitForPCReconnected(){return N(this,void 0,void 0,function*(){this.pcState=bp.Reconnecting,this.log.debug(`waiting for peer connection to reconnect`,this.logContext);try{if(yield $l(pp),!this.pcManager)throw new I(`PC manager is closed`);yield this.pcManager.ensurePCTransportConnection(void 0,this.peerConnectionTimeout),this.pcState=bp.Connected}catch(e){throw this.pcState=bp.Disconnected,F.internal(`could not establish PC connection, ${e.message}`)}})}publishRpcResponse(e,t,n,r){return N(this,void 0,void 0,function*(){let i=new ja({destinationIdentities:[e],kind:Ma.RELIABLE,value:{case:`rpcResponse`,value:new Wa({requestId:t,value:r?{case:`error`,value:r.toProto()}:{case:`payload`,value:n??``}})}});yield this.sendDataPacket(i,K.RELIABLE)})}publishRpcAck(e,t){return N(this,void 0,void 0,function*(){let n=new ja({destinationIdentities:[e],kind:Ma.RELIABLE,value:{case:`rpcAck`,value:new Ua({requestId:t})}});yield this.sendDataPacket(n,K.RELIABLE)})}sendDataPacket(e,t){return N(this,void 0,void 0,function*(){if(yield this.ensurePublisherConnected(t),this.e2eeManager&&this.e2eeManager.isDataChannelEncryptionEnabled){let t=gd(e);if(t){let n=yield this.e2eeManager.encryptData(t.toBinary());e.value={case:`encryptedPacket`,value:new Na({encryptedValue:n.payload,iv:n.iv,keyIndex:n.keyIndex})}}}t===K.RELIABLE&&(e.sequence=this.reliableDataSequence,this.reliableDataSequence+=1);let n=e.toBinary();switch(t){case K.LOSSY:case K.DATA_TRACK_LOSSY:return this.sendLossyBytes(n,t);case K.RELIABLE:let r=this.dataChannelForKind(t);if(r){if(yield this.waitForBufferStatusLow(t),this.reliableMessageBuffer.push({data:n,sequence:e.sequence}),this.attemptingReconnect)return;r.send(n)}this.updateAndEmitDCBufferStatus(t);break}})}sendLossyBytes(e,t){return N(this,arguments,void 0,function(e,t){var n=this;let r=arguments.length>2&&arguments[2]!==void 0?arguments[2]:`drop`;return function*(){yield n.ensurePublisherConnected(t);let i=n.dataChannelForKind(t);if(i){if(!n.isBufferStatusLow(t))switch(r){case`wait`:yield n.waitForBufferStatusLow(t);break;case`drop`:n.lossyDataDropCount+=1,n.lossyDataDropCount%100==0&&n.log.warn(`dropping lossy data channel messages, total dropped: ${n.lossyDataDropCount}`,n.logContext);return}if(n.lossyDataStatCurrentBytes+=e.byteLength,n.attemptingReconnect)return;i.send(e)}n.updateAndEmitDCBufferStatus(t)}()})}resendReliableMessagesForResume(e){return N(this,void 0,void 0,function*(){yield this.ensurePublisherConnected(K.RELIABLE);let t=this.dataChannelForKind(K.RELIABLE);t&&(this.reliableMessageBuffer.popToSequence(e),this.reliableMessageBuffer.getAll().forEach(e=>{t.send(e.data)})),this.updateAndEmitDCBufferStatus(K.RELIABLE)})}waitForBufferStatusLow(e){return new Qc((t,n)=>N(this,void 0,void 0,function*(){if(this.isBufferStatusLow(e))t();else{let r=()=>n(new I(`engine closed`));for(this.once(z.Closing,r);!this.dcBufferStatus.get(e);)yield $l(10);this.off(z.Closing,r),t()}}))}ensureDataTransportConnected(e){return N(this,arguments,void 0,function(e){var t=this;let n=arguments.length>1&&arguments[1]!==void 0?arguments[1]:this.subscriberPrimary;return function*(){if(!t.pcManager)throw new I(`PC manager is closed`);let r=n?t.pcManager.subscriber:t.pcManager.publisher,i=n?`Subscriber`:`Publisher`;if(!r)throw F.internal(`${i} connection not set`);let a=!1;if(!n&&!t.dataChannelForKind(e,n)&&(t.createDataChannels(),a=!0),!a&&!n&&!t.pcManager.publisher.isICEConnected&&t.pcManager.publisher.getICEConnectionState()!==`checking`&&(a=!0),a&&t.negotiate().catch(e=>{M.error(e,t.logContext)}),t.dataChannelForKind(e,n)?.readyState===`open`)return;let o=new Date().getTime()+t.peerConnectionTimeout;for(;new Date().getTime()<o;){if(r.isICEConnected&&t.dataChannelForKind(e,n)?.readyState===`open`)return;yield $l(50)}throw F.internal(`could not establish ${i} connection, state: ${r.getICEConnectionState()}`)}()})}ensurePublisherConnected(e){return N(this,void 0,void 0,function*(){this.publisherConnectionPromise||=this.ensureDataTransportConnected(e,!1),yield this.publisherConnectionPromise})}verifyTransport(){return!(!this.pcManager||![G.CONNECTING,G.CONNECTED].includes(this.pcManager.currentState)||!this.client.ws||this.client.ws.readyState===WebSocket.CLOSED)}negotiate(){return N(this,void 0,void 0,function*(){return new Qc((e,t)=>N(this,void 0,void 0,function*(){if(!this.pcManager){t(new dl(`PC manager is closed`));return}this.pcManager.requirePublisher(),this.pcManager.publisher.getTransceivers().length==0&&!this.lossyDC&&!this.reliableDC&&!this.dataTrackDC&&this.createDataChannels();let n=new AbortController,r=()=>{n.abort(),this.log.debug(`engine disconnected while negotiation was ongoing`,this.logContext),e()};this.isClosed&&t(new dl(`cannot negotiate on closed engine`)),this.on(z.Closing,r),this.on(z.Restarting,r),this.pcManager.publisher.once(df.RTPVideoPayloadTypes,e=>{let t=new Map;e.forEach(e=>{let n=e.codec.toLowerCase();Pu(n)&&t.set(e.payload,n)}),this.emit(z.RTPVideoMapUpdate,t)});try{yield this.pcManager.negotiate(n),e()}catch(r){if(n.signal.aborted){e();return}r instanceof dl&&(this.fullReconnectOnNext=!0),this.handleDisconnect(`negotiation`,ha.RR_UNKNOWN),r instanceof Error?t(r):t(Error(String(r)))}finally{this.off(z.Closing,r),this.off(z.Restarting,r)}}))})}dataChannelForKind(e,t){switch(e){case K.RELIABLE:return t?this.reliableDCSub:this.reliableDC;case K.LOSSY:return t?this.lossyDCSub:this.lossyDC;case K.DATA_TRACK_LOSSY:return t?this.dataTrackDCSub:this.dataTrackDC}}sendSyncState(e,t,n){if(!this.pcManager){this.log.warn(`sync state cannot be sent without peer connection setup`,this.logContext);return}let r=this.pcManager.publisher.getLocalDescription(),i=this.pcManager.publisher.getRemoteDescription(),a=this.pcManager.subscriber?.getRemoteDescription(),o=this.pcManager.subscriber?.getLocalDescription(),s=this.signalOpts?.autoSubscribe??!0,c=[],l=[];e.forEach(e=>{e.isDesired!==s&&c.push(e.trackSid),e.isEnabled||l.push(e.trackSid)}),this.client.sendSyncState(new ts({answer:this.pcManager.mode===`publisher-only`?i?Ud({sdp:i.sdp,type:i.type}):void 0:o?Ud({sdp:o.sdp,type:o.type}):void 0,offer:this.pcManager.mode===`publisher-only`?r?Ud({sdp:r.sdp,type:r.type}):void 0:a?Ud({sdp:a.sdp,type:a.type}):void 0,subscription:new Ao({trackSids:c,subscribe:!s,participantTracks:[]}),publishTracks:Rl(t),dataChannels:this.dataChannelsInfo(),trackSidsDisabled:l,datachannelReceiveStates:this.reliableReceivedState.map((e,t)=>new ns({publisherSid:t,lastSeq:e})),publishDataTracks:n.map(e=>new _o({info:Pd.toProtobuf(e)}))}))}failNext(){this.shouldFailNext=!0}dataChannelsInfo(){let e=[],t=(t,n)=>{t?.id!==void 0&&t.id!==null&&e.push(new rs({label:t.label,id:t.id,target:n}))};return t(this.dataChannelForKind(K.LOSSY),co.PUBLISHER),t(this.dataChannelForKind(K.RELIABLE),co.PUBLISHER),t(this.dataChannelForKind(K.LOSSY,!0),co.SUBSCRIBER),t(this.dataChannelForKind(K.RELIABLE,!0),co.SUBSCRIBER),e}clearReconnectTimeout(){this.reconnectTimeout&&vl.clearTimeout(this.reconnectTimeout)}clearPendingReconnect(){this.clearReconnectTimeout(),this.reconnectAttempts=0}registerOnLineListener(){hu()&&(window.addEventListener(`online`,this.handleBrowserOnLine),window.addEventListener(`offline`,this.handleBrowserOffline))}deregisterOnLineListener(){hu()&&(window.removeEventListener(`online`,this.handleBrowserOnLine),window.removeEventListener(`offline`,this.handleBrowserOffline))}getTrackIdForReceiver(e){let t=this.pcManager?.getMidForReceiver(e);if(t){let e=Object.entries(this.midToTrackId).find(e=>{let[n]=e;return n===t});if(e)return e[1]}}};function Sp(e,t){let n=e.participantIdentity?e.participantIdentity:t.participantIdentity;e.participantIdentity=n,t.participantIdentity=n;let r=e.destinationIdentities.length===0?t.destinationIdentities:e.destinationIdentities;e.destinationIdentities=r,t.destinationIdentities=r}var Cp=class{get info(){return this._info}validateBytesReceived(){let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:!1;if(!(typeof this.totalByteSize!=`number`||this.totalByteSize===0)){if(e&&this.bytesReceived<this.totalByteSize)throw new hl(`Not enough chunk(s) received - expected ${this.totalByteSize} bytes of data total, only received ${this.bytesReceived} bytes`,ml.Incomplete);if(this.bytesReceived>this.totalByteSize)throw new hl(`Extra chunk(s) received - expected ${this.totalByteSize} bytes of data total, received ${this.bytesReceived} bytes`,ml.LengthExceeded)}}constructor(e,t,n){this.reader=t,this.totalByteSize=n,this._info=e,this.bytesReceived=0}},wp=class extends Cp{handleChunkReceived(e){var t;this.bytesReceived+=e.content.byteLength,this.validateBytesReceived();let n=this.totalByteSize?this.bytesReceived/this.totalByteSize:void 0;(t=this.onProgress)==null||t.call(this,n)}[Symbol.asyncIterator](){let e=this.reader.getReader();e.closed.catch(()=>{});let t=()=>{e.releaseLock(),this.signal=void 0};return{next:()=>N(this,void 0,void 0,function*(){try{let t=this.signal;if(t?.aborted)throw t.reason;let n=yield new Promise((n,r)=>{if(t){let i=()=>r(t.reason);t.addEventListener(`abort`,i,{once:!0}),e.read().then(n,r).finally(()=>{t.removeEventListener(`abort`,i)})}else e.read().then(n,r)});return n.done?(this.validateBytesReceived(!0),{done:!0,value:void 0}):(this.handleChunkReceived(n.value),{done:!1,value:n.value.content})}catch(e){throw t(),e}}),return(){return N(this,void 0,void 0,function*(){return t(),{done:!0,value:void 0}})}}}withAbortSignal(e){return this.signal=e,this}readAll(){return N(this,arguments,void 0,function(){var e=this;let t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};return function*(){var n,r,i,a;let o=new Set,s=t.signal?e.withAbortSignal(t.signal):e;try{for(var c=!0,l=Is(s),u;u=yield l.next(),n=u.done,!n;c=!0){a=u.value,c=!1;let e=a;o.add(e)}}catch(e){r={error:e}}finally{try{!c&&!n&&(i=l.return)&&(yield i.call(l))}finally{if(r)throw r.error}}return Array.from(o)}()})}},Tp=class extends Cp{constructor(e,t,n){super(e,t,n),this.receivedChunks=new Map}handleChunkReceived(e){var t;let n=Vu(e.chunkIndex),r=this.receivedChunks.get(n);if(r&&r.version>e.version)return;this.receivedChunks.set(n,e),this.bytesReceived+=e.content.byteLength,this.validateBytesReceived();let i=this.totalByteSize?this.bytesReceived/this.totalByteSize:void 0;(t=this.onProgress)==null||t.call(this,i)}[Symbol.asyncIterator](){let e=this.reader.getReader();e.closed.catch(()=>{});let t=new TextDecoder(`utf-8`,{fatal:!0}),n=this.signal,r=()=>{e.releaseLock(),this.signal=void 0};return{next:()=>N(this,void 0,void 0,function*(){try{if(n?.aborted)throw n.reason;let r=yield new Promise((t,r)=>{if(n){let i=()=>r(n.reason);n.addEventListener(`abort`,i,{once:!0}),e.read().then(t,r).finally(()=>{n.removeEventListener(`abort`,i)})}else e.read().then(t,r)});if(r.done)return this.validateBytesReceived(!0),{done:!0,value:void 0};{this.handleChunkReceived(r.value);let e;try{e=t.decode(r.value.content)}catch(e){throw new hl(`Cannot decode datastream chunk ${r.value.chunkIndex} as text: ${e}`,ml.DecodeFailed)}return{done:!1,value:e}}}catch(e){throw r(),e}}),return(){return N(this,void 0,void 0,function*(){return r(),{done:!0,value:void 0}})}}}withAbortSignal(e){return this.signal=e,this}readAll(){return N(this,arguments,void 0,function(){var e=this;let t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};return function*(){var n,r,i,a;let o=``,s=t.signal?e.withAbortSignal(t.signal):e;try{for(var c=!0,l=Is(s),u;u=yield l.next(),n=u.done,!n;c=!0)a=u.value,c=!1,o+=a}catch(e){r={error:e}}finally{try{!c&&!n&&(i=l.return)&&(yield i.call(l))}finally{if(r)throw r.error}}return o}()})}},Ep=class{constructor(){this.log=M,this.byteStreamControllers=new Map,this.textStreamControllers=new Map,this.byteStreamHandlers=new Map,this.textStreamHandlers=new Map}registerTextStreamHandler(e,t){if(this.textStreamHandlers.has(e))throw new hl(`A text stream handler for topic "${e}" has already been set.`,ml.HandlerAlreadyRegistered);this.textStreamHandlers.set(e,t)}unregisterTextStreamHandler(e){this.textStreamHandlers.delete(e)}registerByteStreamHandler(e,t){if(this.byteStreamHandlers.has(e))throw new hl(`A byte stream handler for topic "${e}" has already been set.`,ml.HandlerAlreadyRegistered);this.byteStreamHandlers.set(e,t)}unregisterByteStreamHandler(e){this.byteStreamHandlers.delete(e)}clearControllers(){this.byteStreamControllers.clear(),this.textStreamControllers.clear()}validateParticipantHasNoActiveDataStreams(e){let t=Array.from(this.textStreamControllers.entries()).filter(t=>t[1].sendingParticipantIdentity===e),n=Array.from(this.byteStreamControllers.entries()).filter(t=>t[1].sendingParticipantIdentity===e);if(t.length>0||n.length>0){let r=new hl(`Participant ${e} unexpectedly disconnected in the middle of sending data`,ml.AbnormalEnd);for(let[e,t]of n)t.controller.error(r),this.byteStreamControllers.delete(e);for(let[e,n]of t)n.controller.error(r),this.textStreamControllers.delete(e)}}handleDataStreamPacket(e,t){return N(this,void 0,void 0,function*(){switch(e.value.case){case`streamHeader`:return this.handleStreamHeader(e.value.value,e.participantIdentity,t);case`streamChunk`:return this.handleStreamChunk(e.value.value,t);case`streamTrailer`:return this.handleStreamTrailer(e.value.value,t);default:throw Error(`DataPacket of value "${e.value.case}" is not data stream related!`)}})}handleStreamHeader(e,t,n){return N(this,void 0,void 0,function*(){if(e.contentHeader.case===`byteHeader`){let r=this.byteStreamHandlers.get(e.topic);if(!r){this.log.debug(`ignoring incoming byte stream due to no handler for topic`,e.topic);return}let i,a={id:e.streamId,name:e.contentHeader.value.name??`unknown`,mimeType:e.mimeType,size:e.totalLength?Number(e.totalLength):void 0,topic:e.topic,timestamp:Vu(e.timestamp),attributes:e.attributes,encryptionType:n};r(new wp(a,new ReadableStream({start:n=>{if(i=n,this.textStreamControllers.has(e.streamId))throw new hl(`A data stream read is already in progress for a stream with id ${e.streamId}.`,ml.AlreadyOpened);this.byteStreamControllers.set(e.streamId,{info:a,controller:i,startTime:Date.now(),sendingParticipantIdentity:t})}}),Vu(e.totalLength)),{identity:t})}else if(e.contentHeader.case===`textHeader`){let r=this.textStreamHandlers.get(e.topic);if(!r){this.log.debug(`ignoring incoming text stream due to no handler for topic`,e.topic);return}let i,a={id:e.streamId,mimeType:e.mimeType,size:e.totalLength?Number(e.totalLength):void 0,topic:e.topic,timestamp:Number(e.timestamp),attributes:e.attributes,encryptionType:n,attachedStreamIds:e.contentHeader.value.attachedStreamIds};r(new Tp(a,new ReadableStream({start:n=>{if(i=n,this.textStreamControllers.has(e.streamId))throw new hl(`A data stream read is already in progress for a stream with id ${e.streamId}.`,ml.AlreadyOpened);this.textStreamControllers.set(e.streamId,{info:a,controller:i,startTime:Date.now(),sendingParticipantIdentity:t})}}),Vu(e.totalLength)),{identity:t})}})}handleStreamChunk(e,t){let n=this.byteStreamControllers.get(e.streamId);n&&(n.info.encryptionType===t?e.content.length>0&&n.controller.enqueue(e):(n.controller.error(new hl(`Encryption type mismatch for stream ${e.streamId}. Expected ${t}, got ${n.info.encryptionType}`,ml.EncryptionTypeMismatch)),this.byteStreamControllers.delete(e.streamId)));let r=this.textStreamControllers.get(e.streamId);r&&(r.info.encryptionType===t?e.content.length>0&&r.controller.enqueue(e):(r.controller.error(new hl(`Encryption type mismatch for stream ${e.streamId}. Expected ${t}, got ${r.info.encryptionType}`,ml.EncryptionTypeMismatch)),this.textStreamControllers.delete(e.streamId)))}handleStreamTrailer(e,t){let n=this.textStreamControllers.get(e.streamId);n&&(n.info.encryptionType===t?(n.info.attributes=Object.assign(Object.assign({},n.info.attributes),e.attributes),n.controller.close(),this.textStreamControllers.delete(e.streamId)):n.controller.error(new hl(`Encryption type mismatch for stream ${e.streamId}. Expected ${t}, got ${n.info.encryptionType}`,ml.EncryptionTypeMismatch)));let r=this.byteStreamControllers.get(e.streamId);r&&(r.info.encryptionType===t?(r.info.attributes=Object.assign(Object.assign({},r.info.attributes),e.attributes),r.controller.close()):r.controller.error(new hl(`Encryption type mismatch for stream ${e.streamId}. Expected ${t}, got ${r.info.encryptionType}`,ml.EncryptionTypeMismatch)),this.byteStreamControllers.delete(e.streamId))}},Dp=class{constructor(e,t,n){this.writableStream=e,this.defaultWriter=e.getWriter(),this.onClose=n,this.info=t}write(e){return this.defaultWriter.write(e)}close(){return N(this,void 0,void 0,function*(){var e;yield this.defaultWriter.close(),this.defaultWriter.releaseLock(),(e=this.onClose)==null||e.call(this)})}},Op=class extends Dp{},kp=class extends Dp{},Ap=15e3,jp=class{constructor(e,t){this.engine=e,this.log=t}setupEngine(e){this.engine=e}sendText(e,t){return N(this,void 0,void 0,function*(){let n=crypto.randomUUID(),r=new TextEncoder().encode(e).byteLength,i=(t?.attachments)?.map(()=>crypto.randomUUID()),a=Array(i?i.length+1:1).fill(0),o=(e,n)=>{var r;a[n]=e;let i=a.reduce((e,t)=>e+t,0);(r=t?.onProgress)==null||r.call(t,i)},s=yield this.streamText({streamId:n,totalSize:r,destinationIdentities:t?.destinationIdentities,topic:t?.topic,attachedStreamIds:i,attributes:t?.attributes});return yield s.write(e),o(1,0),yield s.close(),t?.attachments&&i&&(yield Promise.all(t.attachments.map((e,n)=>N(this,void 0,void 0,function*(){return this._sendFile(i[n],e,{topic:t.topic,mimeType:e.type,onProgress:e=>{o(e,n+1)}})})))),s.info})}streamText(e){return N(this,void 0,void 0,function*(){let t=e?.streamId??crypto.randomUUID(),n={id:t,mimeType:`text/plain`,timestamp:Date.now(),topic:e?.topic??``,size:e?.totalSize,attributes:e?.attributes,encryptionType:this.engine.e2eeManager?.isDataChannelEncryptionEnabled?j.GCM:j.NONE,attachedStreamIds:e?.attachedStreamIds},r=new io({streamId:t,mimeType:n.mimeType,topic:n.topic,timestamp:Hu(n.timestamp),totalLength:Hu(n.size),attributes:n.attributes,contentHeader:{case:`textHeader`,value:new no({version:e?.version,attachedStreamIds:n.attachedStreamIds,replyToStreamId:e?.replyToStreamId,operationType:e?.type===`update`?to.UPDATE:to.CREATE})}}),i=e?.destinationIdentities,a=new ja({destinationIdentities:i,value:{case:`streamHeader`,value:r}});yield this.engine.sendDataPacket(a,K.RELIABLE);let o=0,s=this.engine,c=new WritableStream({write(e){return N(this,void 0,void 0,function*(){for(let n of Qu(e,Ap)){let e=new ja({destinationIdentities:i,value:{case:`streamChunk`,value:new ao({content:n,streamId:t,chunkIndex:Hu(o)})}});yield s.sendDataPacket(e,K.RELIABLE),o+=1}})},close(){return N(this,void 0,void 0,function*(){let e=new ja({destinationIdentities:i,value:{case:`streamTrailer`,value:new oo({streamId:t})}});yield s.sendDataPacket(e,K.RELIABLE)})},abort(e){console.log(`Sink error:`,e)}}),l=()=>N(this,void 0,void 0,function*(){yield u.close()});s.once(z.Closing,l);let u=new Op(c,n,()=>this.engine.off(z.Closing,l));return u})}sendFile(e,t){return N(this,void 0,void 0,function*(){let n=crypto.randomUUID();return yield this._sendFile(n,e,t),{id:n}})}_sendFile(e,t,n){return N(this,void 0,void 0,function*(){let r=yield this.streamBytes({streamId:e,totalSize:t.size,name:t.name,mimeType:n?.mimeType??t.type,topic:n?.topic,destinationIdentities:n?.destinationIdentities}),i=t.stream().getReader();for(;;){let{done:e,value:t}=yield i.read();if(e)break;yield r.write(t)}return yield r.close(),r.info})}streamBytes(e){return N(this,void 0,void 0,function*(){let t=e?.streamId??crypto.randomUUID(),n=e?.destinationIdentities,r={id:t,mimeType:e?.mimeType??`application/octet-stream`,topic:e?.topic??``,timestamp:Date.now(),attributes:e?.attributes,size:e?.totalSize,name:e?.name??`unknown`,encryptionType:this.engine.e2eeManager?.isDataChannelEncryptionEnabled?j.GCM:j.NONE},i=new ja({destinationIdentities:n,value:{case:`streamHeader`,value:new io({totalLength:Hu(r.size),mimeType:r.mimeType,streamId:t,topic:r.topic,timestamp:Hu(Date.now()),attributes:r.attributes,contentHeader:{case:`byteHeader`,value:new ro({name:r.name})}})}});yield this.engine.sendDataPacket(i,K.RELIABLE);let a=0,o=new ur,s=this.engine,c=this.log;return new kp(new WritableStream({write(e){return N(this,void 0,void 0,function*(){let r=yield o.lock(),i=0;try{for(;i<e.byteLength;){let r=e.slice(i,i+Ap),o=new ja({destinationIdentities:n,value:{case:`streamChunk`,value:new ao({content:r,streamId:t,chunkIndex:Hu(a)})}});yield s.sendDataPacket(o,K.RELIABLE),a+=1,i+=r.byteLength}}finally{r()}})},close(){return N(this,void 0,void 0,function*(){let e=new ja({destinationIdentities:n,value:{case:`streamTrailer`,value:new oo({streamId:t})}});yield s.sendDataPacket(e,K.RELIABLE)})},abort(e){c.error(`Sink error:`,e)}}),r)})}};function Mp(e){if(e.length===0)return new AbortController().signal;if(e.length===1)return e[0];for(let t of e)if(t.aborted)return t;let t=new AbortController,n=Array(e.length),r=()=>{for(let e of n)e()};return e.forEach((e,i)=>{let a=()=>{t.abort(e.reason),r()};e.addEventListener(`abort`,a),n[i]=()=>e.removeEventListener(`abort`,a)}),t.signal}function Np(e){let t=new AbortController;return setTimeout(()=>{t.abort(new DOMException(`signal timed out after ${e} ms`,`TimeoutError`))},e),t.signal}var q=1,Pp=2,Fp=4,Ip=8,Lp=0,Rp=12,zp=5,Bp=7,Vp=3,Hp=3,Up=2,Wp=1,Gp=0,Kp=3,qp=2,Jp=2,Yp=1,Xp=0,Zp;(function(e){e[e.TooShort=0]=`TooShort`,e[e.HeaderOverrun=1]=`HeaderOverrun`,e[e.MissingExtWords=2]=`MissingExtWords`,e[e.UnsupportedVersion=3]=`UnsupportedVersion`,e[e.InvalidHandle=4]=`InvalidHandle`,e[e.MalformedExt=5]=`MalformedExt`})(Zp||={});var Qp=class e extends sl{constructor(e,t,n){super(19,e,n),this.name=`DataTrackDeserializeError`,this.reason=t,this.reasonName=Zp[t]}static tooShort(){return new e(`Too short to contain a valid header`,Zp.TooShort)}static headerOverrun(){return new e(`Header exceeds total packet length`,Zp.HeaderOverrun)}static missingExtWords(){return new e(`Extension word indicator is missing`,Zp.MissingExtWords)}static unsupportedVersion(t){return new e(`Unsupported version ${t}`,Zp.UnsupportedVersion)}static invalidHandle(t){return new e(`invalid track handle: ${t.message}`,Zp.InvalidHandle,{cause:t})}static malformedExt(t){return new e(`Extension with tag ${t} is malformed`,Zp.MalformedExt)}},$p;(function(e){e[e.TooSmallForHeader=0]=`TooSmallForHeader`,e[e.TooSmallForPayload=1]=`TooSmallForPayload`})($p||={});var em=class e extends sl{constructor(e,t,n){super(19,e,n),this.name=`DataTrackSerializeError`,this.reason=t,this.reasonName=$p[t]}static tooSmallForHeader(){return new e(`Buffer cannot fit header`,$p.TooSmallForHeader)}static tooSmallForPayload(){return new e(`Buffer cannot fit payload`,$p.TooSmallForPayload)}},tm=class{toBinary(){let e=this.toBinaryLengthBytes(),t=new ArrayBuffer(e),n=new DataView(t),r=this.toBinaryInto(n);if(e!==r)throw Error(`${this.constructor.name}.toBinary: written bytes (${r} bytes) not equal to allocated array buffer length (${e} bytes).`);return new Uint8Array(t)}},nm;(function(e){e[e.UserTimestamp=2]=`UserTimestamp`,e[e.E2ee=1]=`E2ee`})(nm||={});var rm=class extends tm{},im=class e extends rm{constructor(e){super(),this.timestamp=e}toBinaryLengthBytes(){return q+q+e.lengthBytes}toBinaryInto(t){let n=0;t.setUint8(n,e.tag),n+=q,t.setUint8(n,e.lengthBytes),n+=q,t.setBigUint64(n,this.timestamp),n+=Ip;let r=this.toBinaryLengthBytes();if(n!==r)throw Error(`DataTrackUserTimestampExtension.toBinaryInto: Wrote ${n} bytes but expected length was ${r} bytes`);return n}toJSON(){return{tag:e.tag,lengthBytes:e.lengthBytes,timestamp:this.timestamp}}};im.tag=nm.UserTimestamp,im.lengthBytes=8;var am=class e extends rm{constructor(e,t){super(),this.keyIndex=e,this.iv=t}toBinaryLengthBytes(){return q+q+e.lengthBytes}toBinaryInto(t){let n=0;t.setUint8(n,e.tag),n+=q,t.setUint8(n,e.lengthBytes),n+=q,t.setUint8(n,this.keyIndex),n+=q;for(let e=0;e<this.iv.length;e+=1)t.setUint8(n,this.iv[e]),n+=q;let r=this.toBinaryLengthBytes();if(n!==r)throw Error(`DataTrackE2eeExtension.toBinaryInto: Wrote ${n} bytes but expected length was ${r} bytes`);return n}toJSON(){return{tag:e.tag,lengthBytes:e.lengthBytes,keyIndex:this.keyIndex,iv:this.iv}}};am.tag=nm.E2ee,am.lengthBytes=13;var om=class e extends tm{constructor(){let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};super(),this.userTimestamp=e.userTimestamp,this.e2ee=e.e2ee}toBinaryLengthBytes(){let e=0;return this.userTimestamp&&(e+=this.userTimestamp.toBinaryLengthBytes()),this.e2ee&&(e+=this.e2ee.toBinaryLengthBytes()),e}toBinaryInto(e){let t=0;if(this.e2ee){let n=this.e2ee.toBinaryInto(e);t+=n}if(this.userTimestamp){let n=this.userTimestamp.toBinaryInto(new DataView(e.buffer,e.byteOffset+t));t+=n}let n=this.toBinaryLengthBytes();if(t!==n)throw Error(`DataTrackExtensions.toBinaryInto: Wrote ${t} bytes but expected length was ${n} bytes`);return t}static fromBinary(t){let n=kd(t),r,i,a=0;for(;n.byteLength-a>=q+q;){let e=n.getUint8(a);a+=q;let t=n.getUint8(a);if(a+=q,e!==Xp)switch(e){case nm.UserTimestamp:if(n.byteLength-a<im.lengthBytes)throw Qp.malformedExt(e);r=new im(n.getBigUint64(a)),a+=t;break;case nm.E2ee:if(n.byteLength-a<am.lengthBytes)throw Qp.malformedExt(e);let o=n.getUint8(a),s=new Uint8Array(12);for(let e=0;e<s.length;e+=1){let t=a;t+=q,t+=e*q,s[e]=n.getUint8(t)}i=new am(o,s),a+=t;break;default:if(n.byteLength-a<t)throw Qp.malformedExt(e);a+=t;break}}return[new e({userTimestamp:r,e2ee:i}),n.byteLength]}toJSON(){return{userTimestamp:this.userTimestamp?.toJSON()??null,e2ee:this.e2ee?.toJSON()??null}}},sm={from(e){return{payload:e.payload,extensions:new om({userTimestamp:e.userTimestamp?new im(e.userTimestamp):void 0})}},lossyIntoFrame(e){return{payload:e.payload,userTimestamp:e.extensions.userTimestamp?.timestamp}}},cm=Symbol.for(`lk.track`),lm=Symbol.for(`lk.data-track`),um=class{constructor(e,t,n){this.trackSymbol=cm,this.isLocal=!1,this.typeSymbol=lm,this.info=e,this.manager=t,this.publisherIdentity=n.publisherIdentity}subscribe(e){try{let[t]=this.manager.openSubscriptionStream(this.info.sid,e?.signal,e?.bufferSize);return t}catch(e){throw e}}},dm=class e extends tm{constructor(e){super(),this.marker=e.marker,this.trackHandle=e.trackHandle,this.sequence=e.sequence,this.frameNumber=e.frameNumber,this.timestamp=e.timestamp,this.extensions=e.extensions??new om}extensionsMetrics(){let e=this.extensions.toBinaryLengthBytes(),t=Math.ceil(e/4);return{lengthBytes:e,lengthWords:t,paddingLengthBytes:t*4-e}}toBinaryLengthBytes(){let{lengthBytes:e,paddingLengthBytes:t}=this.extensionsMetrics(),n=Rp;return e>0&&(n+=qp+e+t),n}toBinaryInto(e){if(e.byteLength<this.toBinaryLengthBytes())throw em.tooSmallForHeader();let t=Lp<<zp,n;switch(this.marker){case J.Inter:n=Gp;break;case J.Final:n=Wp;break;case J.Start:n=Up;break;case J.Single:n=Kp;break}t|=n<<Vp;let{lengthBytes:r,lengthWords:i,paddingLengthBytes:a}=this.extensionsMetrics();r>0&&(t|=1<<Jp);let o=0;if(e.setUint8(o,t),o+=q,e.setUint8(o,0),o+=q,e.setUint16(o,this.trackHandle),o+=Pp,e.setUint16(o,this.sequence.value),o+=Pp,e.setUint16(o,this.frameNumber.value),o+=Pp,e.setUint32(o,this.timestamp.asTicks()),o+=Fp,r>0){let t=i-1;e.setUint16(o,t),o+=Pp;let n=this.extensions.toBinaryInto(new DataView(e.buffer,e.byteOffset+o));o+=n;for(let t=0;t<a;t+=1)e.setUint8(o,0),o+=q}let s=this.toBinaryLengthBytes();if(o!==s)throw Error(`DataTrackPacketHeader.toBinaryInto: Wrote ${o} bytes but expected length was ${s} bytes`);return s}static fromBinary(t){let n=kd(t);if(n.byteLength<Rp)throw Qp.tooShort();let r=0,i=n.getUint8(r);r+=q;let a=i>>zp&Bp;if(a>Lp)throw Qp.unsupportedVersion(a);let o;switch(i>>Vp&Hp){case Up:o=J.Start;break;case Wp:o=J.Final;break;case Kp:o=J.Single;break;case Gp:default:o=J.Inter;break}let s=(i>>Jp&Yp)>0;r+=q;let c;try{c=Md.fromNumber(n.getUint16(r))}catch(e){throw e instanceof jd&&(e.isReason(Ad.Reserved)||e.isReason(Ad.TooLarge))?Qp.invalidHandle(e):e}r+=Pp;let l=Ed.u16(n.getUint16(r));r+=Pp;let u=Ed.u16(n.getUint16(r));r+=Pp;let d=Dd.fromRtpTicks(n.getUint32(r));r+=Fp;let f=new om;if(s){if(n.byteLength-r<Pp)throw Qp.missingExtWords();let e=n.getUint16(r);r+=Pp;let t=4*(e+1);if(r+t>n.byteLength)throw Qp.headerOverrun();let i=new DataView(n.buffer,n.byteOffset+r,t),[a,o]=om.fromBinary(i);f=a,r+=o}return[new e({marker:o,trackHandle:c,sequence:l,frameNumber:u,timestamp:d,extensions:f}),r]}toJSON(){return{marker:this.marker,trackHandle:this.trackHandle,sequence:this.sequence.value,frameNumber:this.frameNumber.value,timestamp:this.timestamp.asTicks(),extensions:this.extensions.toJSON()}}},J;(function(e){e[e.Start=0]=`Start`,e[e.Inter=1]=`Inter`,e[e.Final=2]=`Final`,e[e.Single=3]=`Single`})(J||={});var fm=class e extends tm{constructor(e,t){super(),this.header=e,this.payload=t}toBinaryLengthBytes(){return this.header.toBinaryLengthBytes()+this.payload.byteLength}toBinaryInto(e){let t=0,n=this.header.toBinaryInto(e);if(t+=n,e.byteLength-t<this.payload.byteLength)throw em.tooSmallForPayload();for(let n=0;n<this.payload.length;n+=1)e.setUint8(t,this.payload[n]),t+=q;let r=this.toBinaryLengthBytes();if(t!==r)throw Error(`DataTrackPacket.toBinaryInto: Wrote ${t} bytes but expected length was ${r} bytes`);return r}static fromBinary(t){let n=kd(t),[r,i]=dm.fromBinary(n),a=n.buffer.slice(n.byteOffset+i,n.byteOffset+n.byteLength);return[new e(r,new Uint8Array(a)),n.byteLength]}toJSON(){return{header:this.header.toJSON(),payload:this.payload}}},pm=Es(Ts.DataTracks),mm=class e extends sl{constructor(e,t,n,r){super(19,`Frame ${n} dropped: ${e}`,r),this.name=`DataTrackDepacketizerDropError`,this.reason=t,this.reasonName=hm[t],this.frameNumber=n}static interrupted(t,n){return new e(`Interrupted by the start of a new frame ${n}`,hm.Interrupted,t)}static unknownFrame(t){return new e(`Initial packet was never received.`,hm.UnknownFrame,t)}static bufferFull(t){return new e(`Reorder buffer is full.`,hm.BufferFull,t)}static incomplete(t,n,r){return new e(`Not all packets received before final packet. Received ${n} packets, expected ${r} packets.`,hm.Incomplete,t)}},hm;(function(e){e[e.Interrupted=0]=`Interrupted`,e[e.UnknownFrame=1]=`UnknownFrame`,e[e.BufferFull=2]=`BufferFull`,e[e.Incomplete=3]=`Incomplete`})(hm||={});var gm=class e{constructor(){this.partial=null}push(e,t){switch(e.header.marker){case J.Single:return this.frameFromSingle(e,t);case J.Start:return this.beginPartial(e,t);case J.Inter:case J.Final:return this.pushToPartial(e)}}reset(){this.partial=null}frameFromSingle(e,t){if(e.header.marker!==J.Single)throw Error(`Depacketizer.frameFromSingle: packet.header.marker was not FrameMarker.Single, found ${e.header.marker}.`);if(this.partial)if(t?.errorOnPartialFrames){let t=this.partial.frameNumber;throw this.reset(),mm.interrupted(t,e.header.frameNumber.value)}else pm.warn(`Data track frame ${this.partial.frameNumber} was interrupted by the start of a new frame, dropping.`);return this.reset(),{payload:e.payload,extensions:e.header.extensions}}beginPartial(e,t){if(e.header.marker!==J.Start)throw Error(`Depacketizer.beginPartial: packet.header.marker was not FrameMarker.Start, found ${e.header.marker}.`);if(this.partial)if(t?.errorOnPartialFrames){let t=this.partial.frameNumber;throw this.reset(),mm.interrupted(t,e.header.frameNumber.value)}else pm.warn(`Data track frame ${this.partial.frameNumber} was interrupted by the start of a new frame ${e.header.frameNumber.value}, dropping.`);this.reset();let n=e.header.sequence;return this.partial={frameNumber:e.header.frameNumber.value,startSequence:n,extensions:e.header.extensions,payloads:new Map([[n.value,e.payload]])},null}pushToPartial(t){if(t.header.marker!==J.Inter&&t.header.marker!==J.Final)throw Error(`Depacketizer.pushToPartial: packet.header.marker was not FrameMarker.Inter or FrameMarker.Final, found ${t.header.marker}.`);if(!this.partial)throw this.reset(),mm.unknownFrame(t.header.frameNumber.value);if(t.header.frameNumber.value!==this.partial.frameNumber){let e=this.partial.frameNumber;throw this.reset(),mm.interrupted(e,t.header.frameNumber.value)}if(this.partial.payloads.size>=e.MAX_BUFFER_PACKETS){let e=this.partial.frameNumber;throw this.reset(),mm.bufferFull(e)}return this.partial.payloads.has(t.header.sequence.value)&&pm.warn(`Data track frame ${this.partial.frameNumber} received duplicate packet for sequence ${t.header.sequence.value}, so replacing with newly received packet.`),this.partial.payloads.set(t.header.sequence.value,t.payload),t.header.marker===J.Final?this.finalize(this.partial,t.header.sequence.value):null}finalize(e,t){let n=e.payloads.size,r=0;for(let t of e.payloads.values())r+=t.length;let i=new Uint8Array(r),a=e.startSequence.clone(),o=0;for(;;){let n=e.payloads.get(a.value);if(!n)break;e.payloads.delete(a.value);let r=i.length-o;if(n.length>r)throw Error(`Depacketizer.finalize: Expected at least ${n.length} more bytes left in the payload buffer, only got ${r} bytes.`);if(i.set(n,o),o+=n.length,a.value!=t){a.increment();continue}return this.reset(),{payload:i,extensions:e.extensions}}throw this.reset(),mm.incomplete(e.frameNumber,n,t-e.startSequence.value+1)}};gm.MAX_BUFFER_PACKETS=128;var _m;(function(e){e[e.Unpublished=0]=`Unpublished`,e[e.Timeout=1]=`Timeout`,e[e.Disconnected=2]=`Disconnected`,e[e.Cancelled=4]=`Cancelled`})(_m||={});var vm=class e extends sl{constructor(e,t,n){super(22,e,n),this.name=`DataTrackSubscribeError`,this.reason=t,this.reasonName=_m[t]}static unpublished(){return new e(`The track has been unpublished and is no longer available`,_m.Unpublished)}static timeout(){return new e(`Request to subscribe to data track timed-out`,_m.Timeout)}static disconnected(){return new e(`Cannot subscribe to data track when disconnected`,_m.Disconnected)}static cancelled(){return new e(`Subscription to data track cancelled by caller`,_m.Cancelled)}},ym=Es(Ts.DataTracks),bm=class{constructor(e){let t=e.e2eeManager!==null;if(e.info.usesE2ee!==t)throw Error(`IncomingDataTrackPipeline: DataTrackInfo.usesE2ee must match presence of decryptionProvider`);let n=new gm;this.publisherIdentity=e.publisherIdentity,this.e2eeManager=e.e2eeManager??null,this.depacketizer=n}updateE2eeManager(e){this.e2eeManager=e}processPacket(e){return N(this,void 0,void 0,function*(){let t=this.depacketize(e);return t&&(yield this.decryptIfNeeded(t))||null})}depacketize(e){let t;try{t=this.depacketizer.push(e)}catch(e){return ym.warn(`Data frame depacketize error: ${e}`),null}return t}decryptIfNeeded(e){return N(this,void 0,void 0,function*(){let t=this.e2eeManager;if(!t)return e;let n=e.extensions?.e2ee??null;if(!n)return ym.error(`Missing E2EE meta`),null;let r;try{r=yield t.handleEncryptedData(e.payload,n.iv,this.publisherIdentity,n.keyIndex)}catch(e){return ym.error(`Error decrypting packet: ${e}`),null}return e.payload=r.payload,e})}},xm=Es(Ts.DataTracks),Sm=1e4,Cm=16,wm=class extends Bs.EventEmitter{constructor(e){super(),this.descriptors=new Map,this.subscriptionHandles=new Map,this.e2eeManager=e?.e2eeManager??null}updateE2eeManager(e){this.e2eeManager=e;for(let t of this.descriptors.values())t.subscription.type===`active`&&t.subscription.pipeline.updateE2eeManager(e)}openSubscriptionStream(e,t){let n=arguments.length>2&&arguments[2]!==void 0?arguments[2]:Cm,r=null,i=new Nu;return[new ReadableStream({start:n=>{r=n;let a=()=>{var e;n.error(vm.cancelled()),(e=i.reject)==null||e.call(i,vm.cancelled())};this.subscribeRequest(e,t).then(()=>N(this,void 0,void 0,function*(){var r;t?.addEventListener(`abort`,a);let o=this.descriptors.get(e);if(!o){xm.error(`Unknown track ${e}`);return}if(o.subscription.type!==`active`){xm.error(`Subscription for track ${e} is not active`);return}o.subscription.streamControllers.add(n),(r=i.resolve)==null||r.call(i)})).catch(e=>{var t;n.error(e),(t=i.reject)==null||t.call(i,e)}).finally(()=>{t?.removeEventListener(`abort`,a)})},cancel:()=>{if(!r){xm.warn(`ReadableStream subscribed to ${e} was not started.`);return}let t=this.descriptors.get(e);if(!t){xm.warn(`Unknown track ${e}, skipping cancel...`);return}if(t.subscription.type!==`active`){xm.warn(`Subscription for track ${e} is not active, skipping cancel...`);return}t.subscription.streamControllers.delete(r),t.subscription.streamControllers.size===0&&this.unSubscribeRequest(t.info.sid)}},new CountQueuingStrategy({highWaterMark:n})),i.promise]}subscribeRequest(e,t){return N(this,void 0,void 0,function*(){let n=this.descriptors.get(e);if(!n)throw Error(`Cannot subscribe to unknown track`);let r=(t,n,r)=>N(this,void 0,void 0,function*(){if(t.subscription.type===`active`)return;if(t.subscription.type!==`pending`)throw Error(`Descriptor for track ${e} is not pending, found ${t.subscription.type}`);let i=Mp([n,r].filter(e=>e!==void 0)),a=new Nu;t.subscription.completionFuture.promise.then(()=>a.resolve?.call(a)).catch(e=>a.reject?.call(a,e));let o=()=>{var e;if(t.subscription.type===`pending`){if(--t.subscription.pendingRequestCount,r?.aborted){t.subscription.cancel();return}if(t.subscription.pendingRequestCount<=0){t.subscription.cancel();return}(e=a.reject)==null||e.call(a,vm.cancelled())}};i.aborted&&o(),i.addEventListener(`abort`,o),yield a.promise,i.removeEventListener(`abort`,o)});switch(n.subscription.type){case`none`:{n.subscription={type:`pending`,completionFuture:new Nu,pendingRequestCount:1,cancel:()=>{var t,r;let a=n.subscription;n.subscription={type:`none`},this.emit(`sfuUpdateSubscription`,{sid:e,subscribe:!1}),a.type===`pending`&&((r=(t=a.completionFuture).reject)==null||r.call(t,i.aborted?vm.timeout():vm.cancelled()))}},this.emit(`sfuUpdateSubscription`,{sid:e,subscribe:!0});let i=Np(Sm);yield r(n,t,i);return}case`pending`:n.subscription.pendingRequestCount+=1,yield r(n,t);return;case`active`:return}})}querySubscribed(){return N(this,void 0,void 0,function*(){return Array.from(this.descriptors.values()).filter(e=>e.subscription.type===`active`).map(e=>[e.info,e.publisherIdentity])})}unSubscribeRequest(e){let t=this.descriptors.get(e);if(!t)throw Error(`Cannot subscribe to unknown track`);if(t.subscription.type!==`active`){xm.warn(`Unexpected descriptor state in unSubscribeRequest, expected active, found ${t.subscription?.type}`);return}for(let e of t.subscription.streamControllers)e.close();let n=t.subscription;t.subscription={type:`none`},this.subscriptionHandles.delete(n.subcriptionHandle),this.emit(`sfuUpdateSubscription`,{sid:e,subscribe:!1})}receiveSfuPublicationUpdates(e){return N(this,void 0,void 0,function*(){if(e.size===0)return;let t=new Map;for(let[n,r]of e.entries()){let e=new Set;for(let t of r)e.add(t.sid),!this.descriptors.has(t.sid)&&(yield this.handleTrackPublished(n,t));t.set(n,e)}for(let[e,n]of t.entries()){let t=Array.from(this.descriptors.entries()).filter(t=>{let[n,r]=t;return r.publisherIdentity===e}).map(e=>{let[t]=e;return t}).filter(e=>!n.has(e));for(let e of t)this.handleTrackUnpublished(e)}})}queryPublications(){return N(this,void 0,void 0,function*(){return Array.from(this.descriptors.values()).map(e=>e.info)})}handleTrackPublished(e,t){return N(this,void 0,void 0,function*(){if(this.descriptors.has(t.sid)){xm.error(`Existing descriptor for track ${t.sid}`);return}let n={info:t,publisherIdentity:e,subscription:{type:`none`}};this.descriptors.set(n.info.sid,n);let r=new um(n.info,this,{publisherIdentity:e});this.emit(`trackPublished`,{track:r})})}handleTrackUnpublished(e){let t=this.descriptors.get(e);if(!t){xm.error(`Unknown track ${e}`);return}this.descriptors.delete(e),t.subscription.type===`active`&&this.subscriptionHandles.delete(t.subscription.subcriptionHandle),this.emit(`trackUnpublished`,{sid:e,publisherIdentity:t.publisherIdentity})}receivedSfuSubscriberHandles(e){for(let[t,n]of e.entries())this.registerSubscriberHandle(t,n)}registerSubscriberHandle(e,t){var n,r;let i=this.descriptors.get(t);if(!i){xm.error(`Unknown track ${t}`);return}switch(i.subscription.type){case`none`:xm.warn(`No subscription for ${t}`);return;case`active`:i.subscription.subcriptionHandle=e,this.subscriptionHandles.set(e,t);return;case`pending`:{let a=new bm({info:i.info,publisherIdentity:i.publisherIdentity,e2eeManager:this.e2eeManager}),o=i.subscription;i.subscription={type:`active`,subcriptionHandle:e,pipeline:a,streamControllers:new Set},this.subscriptionHandles.set(e,t),(r=(n=o.completionFuture).resolve)==null||r.call(n)}}}packetReceived(e){return N(this,void 0,void 0,function*(){let t;try{[t]=fm.fromBinary(e)}catch(e){xm.error(`Failed to deserialize packet: ${e}`);return}let n=this.subscriptionHandles.get(t.header.trackHandle);if(!n){xm.warn(`Unknown subscriber handle ${t.header.trackHandle}`);return}let r=this.descriptors.get(n);if(!r){xm.error(`Missing descriptor for track ${n}`);return}if(r.subscription.type!==`active`){xm.warn(`Received packet for track ${n} without active subscription`);return}let i=yield r.subscription.pipeline.processPacket(t);if(i)for(let e of r.subscription.streamControllers){if(e.desiredSize!==null&&e.desiredSize<=0){xm.warn(`Cannot send frame to subscribers: readable stream is full (desiredSize is ${e.desiredSize}). To increase this threshold, set a higher 'options.highWaterMark' when calling .subscribe().`);continue}let t=sm.lossyIntoFrame(i);e.enqueue(t)}})}resendSubscriptionUpdates(){for(let[e,t]of this.descriptors)t.subscription.type!==`none`&&this.emit(`sfuUpdateSubscription`,{sid:e,subscribe:!0})}handleRemoteParticipantDisconnected(e){var t,n;for(let r of this.descriptors.values())if(r.publisherIdentity===e)switch(r.subscription.type){case`none`:break;case`pending`:(n=(t=r.subscription.completionFuture).reject)==null||n.call(t,vm.disconnected());break;case`active`:this.unSubscribeRequest(r.info.sid);break}}shutdown(){var e,t;for(let n of this.descriptors.values())this.emit(`trackUnpublished`,{sid:n.info.sid,publisherIdentity:n.publisherIdentity}),n.subscription.type===`pending`&&((t=(e=n.subscription.completionFuture).reject)==null||t.call(e,vm.disconnected()));this.descriptors.clear()}},Tm=class e extends sl{constructor(e,t,n){super(19,e,n),this.name=`DataTrackPacketizerError`,this.reason=t,this.reasonName=Em[t]}static mtuTooShort(){return new e(`MTU is too short to send frame`,Em.MtuTooShort)}},Em;(function(e){e[e.MtuTooShort=0]=`MtuTooShort`})(Em||={});var Dm=class e{constructor(e,t){this.sequence=Ed.u16(0),this.frameNumber=Ed.u16(0),this.clock=Od.rtpStartingNow(Dd.rtpRandom()),this.handle=e,this.mtuSizeBytes=t}static computeFrameMarker(e,t){return t<=1?J.Single:e===0?J.Start:e===t-1?J.Final:J.Inter}*packetize(t,n){let r=this.frameNumber.getThenIncrement(),i={marker:J.Inter,trackHandle:this.handle,sequence:Ed.u16(0),frameNumber:r,timestamp:n?.now??this.clock.now(),extensions:t.extensions},a=new dm(i).toBinaryLengthBytes();if(a>=this.mtuSizeBytes)throw Tm.mtuTooShort();let o=this.mtuSizeBytes-a,s=Math.ceil(t.payload.byteLength/o);for(let n=0,r=0;r<t.payload.byteLength;[n,r]=[n+1,r+o]){let a=this.sequence.getThenIncrement(),c=new dm(Object.assign(Object.assign({},i),{marker:e.computeFrameMarker(n,s),sequence:a})),l=Math.min(o,t.payload.byteLength-r);yield new fm(c,new Uint8Array(t.payload.buffer,t.payload.byteOffset+r,l))}}},Om;(function(e){e[e.NotAllowed=0]=`NotAllowed`,e[e.DuplicateName=1]=`DuplicateName`,e[e.Timeout=2]=`Timeout`,e[e.LimitReached=3]=`LimitReached`,e[e.Disconnected=4]=`Disconnected`,e[e.Cancelled=5]=`Cancelled`,e[e.InvalidName=6]=`InvalidName`,e[e.Unknown=7]=`Unknown`})(Om||={});var km=class e extends sl{constructor(e,t,n){super(21,e,n),this.name=`DataTrackPublishError`,this.reason=t,this.reasonName=Om[t],this.rawMessage=n?.rawMessage}static notAllowed(t){return new e(`Data track publishing unauthorized`,Om.NotAllowed,{rawMessage:t})}static duplicateName(t){return new e(`Track name already taken`,Om.DuplicateName,{rawMessage:t})}static invalidName(t){return new e(`Track name is invalid`,Om.InvalidName,{rawMessage:t})}static timeout(){return new e(`Publish data track timed-out. Does the LiveKit server support data tracks?`,Om.Timeout)}static limitReached(t){return new e(`Data track publication limit reached`,Om.LimitReached,{rawMessage:t})}static unknown(t,n){return new e(`Received RequestResponse for publishDataTrack, but reason was unrecognised (${t}, ${n})`,Om.Unknown)}static disconnected(){return new e(`Room disconnected`,Om.Disconnected)}static cancelled(){return new e(`Publish data track cancelled by caller`,Om.Cancelled)}},Am;(function(e){e[e.TrackUnpublished=0]=`TrackUnpublished`,e[e.Dropped=1]=`Dropped`})(Am||={});var jm=class e extends sl{constructor(e,t,n){super(22,e,n),this.name=`DataTrackPushFrameError`,this.reason=t,this.reasonName=Am[t]}static trackUnpublished(){return new e(`Track is no longer published`,Am.TrackUnpublished)}static dropped(t){return new e(`Frame was dropped`,Am.Dropped,{cause:t})}},Mm;(function(e){e[e.Packetizer=0]=`Packetizer`,e[e.Encryption=1]=`Encryption`})(Mm||={});var Nm=class e extends sl{constructor(e,t,n){super(21,e,n),this.name=`DataTrackOutgoingPipelineError`,this.reason=t,this.reasonName=Mm[t]}static packetizer(t){return new e(`Error packetizing frame`,Mm.Packetizer,{cause:t})}static encryption(t){return new e(`Error encrypting frame`,Mm.Encryption,{cause:t})}},Pm=class e{constructor(e,t){this.trackSymbol=cm,this.isLocal=!0,this.typeSymbol=lm,this.handle=null,this.log=M,this.options=e,this.manager=t,this.log=Es(Ts.DataTracks)}static withExplicitHandle(t,n,r){let i=new e(t,n);return i.handle=r,i}get info(){let e=this.descriptor;if(e?.type===`active`)return e.info}get descriptor(){return this.handle?this.manager.getDescriptor(this.handle):null}publish(e){return N(this,void 0,void 0,function*(){try{this.handle=yield this.manager.publishRequest(this.options,e)}catch(e){throw e}})}isPublished(){return this.descriptor?.type===`active`&&this.descriptor.publishState!==`unpublished`}tryPush(e){if(!this.handle)throw jm.trackUnpublished();let t=sm.from(e);try{return this.manager.tryProcessAndSend(this.handle,t)}catch(e){throw e}}unpublish(){return N(this,void 0,void 0,function*(){if(!this.handle){M.warn(`Data track "${this.options.name}" is not published, so unpublishing has no effect.`);return}try{yield this.manager.unpublishRequest(this.handle)}catch(e){throw e}})}},Fm=class e{constructor(t){this.e2eeManager=t.e2eeManager,this.packetizer=new Dm(t.info.pubHandle,e.TRANSPORT_MTU_BYTES)}updateE2eeManager(e){this.e2eeManager=e}processFrame(e){return Ps(this,arguments,function*(){let t=yield Ns(this.encryptIfNeeded(e));try{yield Ns(yield*Fs(Is(this.packetizer.packetize(t))))}catch(e){throw e instanceof Tm?Nm.packetizer(e):e}})}encryptIfNeeded(e){return N(this,void 0,void 0,function*(){if(!this.e2eeManager)return e;let t;try{t=yield this.e2eeManager.encryptData(e.payload)}catch(e){throw Nm.encryption(e)}return e.payload=t.payload,e.extensions.e2ee=new am(t.keyIndex,t.iv),e})}};Fm.TRANSPORT_MTU_BYTES=16e3;var Im=Es(Ts.DataTracks),Lm={pending(){return{type:`pending`,completionFuture:new Nu}},active(e,t){return{type:`active`,info:e,publishState:`published`,pipeline:new Fm({info:e,e2eeManager:t}),unpublishingFuture:new Nu}}},Rm=1e4,zm=class e extends Bs.EventEmitter{constructor(e){super(),this.handleAllocator=new Nd,this.descriptors=new Map,this.e2eeManager=e?.e2eeManager??null}static withDescriptors(t){let n=new e;return n.descriptors=t,n}updateE2eeManager(e){this.e2eeManager=e;for(let t of this.descriptors.values())t.type===`active`&&t.pipeline.updateE2eeManager(e)}getDescriptor(e){return this.descriptors.get(e)??null}tryProcessAndSend(e,t){return N(this,void 0,void 0,function*(){var n,r,i,a;let o=this.getDescriptor(e);if(o?.type!==`active`||o.publishState===`unpublished`)throw jm.trackUnpublished();if(o.publishState===`republishing`)throw jm.dropped(`Data track republishing`);try{try{for(var s=!0,c=Is(o.pipeline.processFrame(t)),l;l=yield c.next(),n=l.done,!n;s=!0){a=l.value,s=!1;let e=a;this.emit(`packetAvailable`,{bytes:e.toBinary()})}}catch(e){r={error:e}}finally{try{!s&&!n&&(i=c.return)&&(yield i.call(c))}finally{if(r)throw r.error}}}catch(e){throw jm.dropped(e)}})}publishRequest(e,t){return N(this,void 0,void 0,function*(){let n=this.handleAllocator.get();if(!n)throw km.limitReached();let r=Np(Rm),i=t?Mp([t,r]):r;if(this.descriptors.has(n))throw Error(`Descriptor for handle already exists`);let a=Lm.pending();this.descriptors.set(n,a);let o=()=>{var e,t;let i=this.descriptors.get(n);if(!i){Im.warn(`No descriptor for ${n}`);return}this.descriptors.delete(n),this.emit(`sfuUnpublishRequest`,{handle:n}),i.type===`pending`&&((t=(e=i.completionFuture).reject)==null||t.call(e,r.aborted?km.timeout():km.cancelled()))};return i.aborted?(o(),a.completionFuture.promise.then(()=>n)):(i.addEventListener(`abort`,o),this.emit(`sfuPublishRequest`,{handle:n,name:e.name,usesE2ee:this.e2eeManager!==null}),yield a.completionFuture.promise,i.removeEventListener(`abort`,o),this.emit(`trackPublished`,{track:Pm.withExplicitHandle(e,this,n)}),n)})}queryPublished(){return Array.from(this.descriptors.values()).filter(e=>e.type===`active`).map(e=>e.info)}unpublishRequest(e){return N(this,void 0,void 0,function*(){let t=this.descriptors.get(e);if(!t){Im.warn(`No descriptor for ${e}`);return}if(t.type!==`active`){Im.warn(`Track ${e} not active`);return}this.emit(`sfuUnpublishRequest`,{handle:e}),yield t.unpublishingFuture.promise,this.emit(`trackUnpublished`,{sid:t.info.sid})})}receivedSfuPublishResponse(e,t){var n,r,i,a;let o=this.descriptors.get(e);if(!o){Im.warn(`No descriptor for ${e}`);return}switch(this.descriptors.delete(e),o.type){case`pending`:if(t.type===`ok`){let e=t.data,i=e.usesE2ee?this.e2eeManager:null;this.descriptors.set(e.pubHandle,Lm.active(e,i)),(r=(n=o.completionFuture).resolve)==null||r.call(n)}else (a=(i=o.completionFuture).reject)==null||a.call(i,t.error);return;case`active`:if(o.publishState!==`republishing`){Im.warn(`Track ${e} already active`);return}if(t.type===`error`){Im.warn(`Republish failed for track ${e}`);return}Im.debug(`Track ${e} republished`),o.info.sid=t.data.sid,o.publishState=`published`,this.descriptors.set(o.info.pubHandle,o)}}receivedSfuUnpublishResponse(e){var t,n;let r=this.descriptors.get(e);if(!r){Im.warn(`No descriptor for ${e}`);return}if(this.descriptors.delete(e),r.type!==`active`){Im.warn(`Track ${e} not active`);return}r.publishState=`unpublished`,(n=(t=r.unpublishingFuture).resolve)==null||n.call(t)}sfuWillRepublishTracks(){var e,t;for(let[n,r]of this.descriptors.entries())switch(r.type){case`pending`:this.descriptors.delete(n),(t=(e=r.completionFuture).reject)==null||t.call(e,km.disconnected());break;case`active`:r.publishState=`republishing`,this.emit(`sfuPublishRequest`,{handle:r.info.pubHandle,name:r.info.name,usesE2ee:r.info.usesE2ee})}}shutdown(){return N(this,void 0,void 0,function*(){var e,t,n,r;for(let i of this.descriptors.values())switch(i.type){case`pending`:(t=(e=i.completionFuture).reject)==null||t.call(e,km.disconnected());break;case`active`:(r=(n=i.unpublishingFuture).resolve)==null||r.call(n),yield this.unpublishRequest(i.info.pubHandle);break}this.descriptors.clear()})}},Bm=class extends U{constructor(e,t,n,r,i){super(e,n,i),this.sid=t,this.receiver=r}get isLocal(){return!1}setMuted(e){this.isMuted!==e&&(this.isMuted=e,this._mediaStreamTrack.enabled=!e,this.emit(e?B.Muted:B.Unmuted,this))}setMediaStream(e){this.mediaStream=e;let t=n=>{n.track===this._mediaStreamTrack&&(e.removeEventListener(`removetrack`,t),this.receiver&&`playoutDelayHint`in this.receiver&&(this.receiver.playoutDelayHint=void 0),this.receiver=void 0,this._currentBitrate=0,this.emit(B.Ended,this))};e.addEventListener(`removetrack`,t)}start(){this.startMonitor(),super.enable()}stop(){this.stopMonitor(),super.disable()}getRTCStatsReport(){return N(this,void 0,void 0,function*(){if(this.receiver?.getStats)return yield this.receiver.getStats()})}setPlayoutDelay(e){this.receiver?`playoutDelayHint`in this.receiver?this.receiver.playoutDelayHint=e:this.log.warn(`Playout delay not supported in this browser`):this.log.warn(`Cannot set playout delay, track already ended`)}getPlayoutDelay(){if(this.receiver){if(`playoutDelayHint`in this.receiver)return this.receiver.playoutDelayHint;this.log.warn(`Playout delay not supported in this browser`)}else this.log.warn(`Cannot get playout delay, track already ended`);return 0}startMonitor(){this.monitorInterval||=setInterval(()=>this.monitorReceiver(),Mf),zl()&&this.registerTimeSyncUpdate()}registerTimeSyncUpdate(){let e=()=>{this.timeSyncHandle=requestAnimationFrame(()=>e());let t=this.receiver?.getSynchronizationSources()[0];if(t){let{timestamp:e,rtpTimestamp:n}=t;n&&this.rtpTimestamp!==n&&(this.emit(B.TimeSyncUpdate,{timestamp:e,rtpTimestamp:n}),this.rtpTimestamp=n)}};e()}},Vm=class extends Bm{constructor(e,t,n,r,i,a){super(e,t,U.Kind.Audio,n,a),this.monitorReceiver=()=>N(this,void 0,void 0,function*(){if(!this.receiver){this._currentBitrate=0;return}let e=yield this.getReceiverStats();e&&this.prevStats&&this.receiver&&(this._currentBitrate=Nf(e,this.prevStats)),this.prevStats=e}),this.audioContext=r,this.webAudioPluginNodes=[],i&&(this.sinkId=i.deviceId)}setVolume(e){var t;for(let n of this.attachedElements)this.audioContext?(t=this.gainNode)==null||t.gain.setTargetAtTime(e,0,.1):n.volume=e;gu()&&this._mediaStreamTrack._setVolume(e),this.elementVolume=e}getVolume(){if(this.elementVolume)return this.elementVolume;if(gu())return 1;let e=0;return this.attachedElements.forEach(t=>{t.volume>e&&(e=t.volume)}),e}setSinkId(e){return N(this,void 0,void 0,function*(){this.sinkId=e,yield Promise.all(this.attachedElements.map(t=>{if(au(t))return t.setSinkId(e)}))})}attach(e){let t=this.attachedElements.length===0;return e?super.attach(e):e=super.attach(),this.sinkId&&au(e)&&e.setSinkId(this.sinkId).catch(e=>{this.log.error(`Failed to set sink id on remote audio track`,e,this.logContext)}),this.audioContext&&t&&(this.log.debug(`using audio context mapping`,this.logContext),this.connectWebAudio(this.audioContext,e),e.volume=0,e.muted=!0),this.elementVolume&&this.setVolume(this.elementVolume),e}detach(e){let t;return e?(t=super.detach(e),this.audioContext&&(this.attachedElements.length>0?this.connectWebAudio(this.audioContext,this.attachedElements[0]):this.disconnectWebAudio())):(t=super.detach(),this.disconnectWebAudio()),t}setAudioContext(e){this.audioContext=e,e&&this.attachedElements.length>0?this.connectWebAudio(e,this.attachedElements[0]):e||this.disconnectWebAudio()}setWebAudioPlugins(e){this.webAudioPluginNodes=e,this.attachedElements.length>0&&this.audioContext&&this.connectWebAudio(this.audioContext,this.attachedElements[0])}connectWebAudio(e,t){this.disconnectWebAudio(),this.sourceNode=e.createMediaStreamSource(t.srcObject);let n=this.sourceNode;this.webAudioPluginNodes.forEach(e=>{n.connect(e),n=e}),this.gainNode=e.createGain(),n.connect(this.gainNode),this.gainNode.connect(e.destination),this.elementVolume&&this.gainNode.gain.setTargetAtTime(this.elementVolume,0,.1),e.state!==`running`&&e.resume().then(()=>{e.state!==`running`&&this.emit(B.AudioPlaybackFailed,Error(`Audio Context couldn't be started automatically`))}).catch(e=>{this.emit(B.AudioPlaybackFailed,e)})}disconnectWebAudio(){var e,t;(e=this.gainNode)==null||e.disconnect(),(t=this.sourceNode)==null||t.disconnect(),this.gainNode=void 0,this.sourceNode=void 0}getReceiverStats(){return N(this,void 0,void 0,function*(){if(!this.receiver||!this.receiver.getStats)return;let e=yield this.receiver.getStats(),t;return e.forEach(e=>{e.type===`inbound-rtp`&&(t={type:`audio`,streamId:e.id,timestamp:e.timestamp,jitter:e.jitter,bytesReceived:e.bytesReceived,concealedSamples:e.concealedSamples,concealmentEvents:e.concealmentEvents,silentConcealedSamples:e.silentConcealedSamples,silentConcealmentEvents:e.silentConcealmentEvents,totalAudioEnergy:e.totalAudioEnergy,totalSamplesDuration:e.totalSamplesDuration})}),t})}},Hm=100,Um=class extends Bm{constructor(e,t,n,r,i){super(e,t,U.Kind.Video,n,i),this.elementInfos=[],this.monitorReceiver=()=>N(this,void 0,void 0,function*(){if(!this.receiver){this._currentBitrate=0;return}let e=yield this.getReceiverStats();e&&this.prevStats&&this.receiver&&(this._currentBitrate=Nf(e,this.prevStats)),this.prevStats=e}),this.debouncedHandleResize=cf(()=>{this.updateDimensions()},Hm),this.adaptiveStreamSettings=r}get isAdaptiveStream(){return this.adaptiveStreamSettings!==void 0}setStreamState(e){super.setStreamState(e),this.log.debug(`setStreamState`,e),this.isAdaptiveStream&&e===U.StreamState.Active&&this.updateVisibility()}get mediaStreamTrack(){return this._mediaStreamTrack}setMuted(e){super.setMuted(e),this.attachedElements.forEach(t=>{e?Yl(this._mediaStreamTrack,t):Jl(this._mediaStreamTrack,t)})}attach(e){if(e?super.attach(e):e=super.attach(),this.adaptiveStreamSettings&&this.elementInfos.find(t=>t.element===e)===void 0){let t=new Wm(e);this.observeElementInfo(t)}return e}observeElementInfo(e){this.adaptiveStreamSettings&&this.elementInfos.find(t=>t===e)===void 0?(e.handleResize=()=>{this.debouncedHandleResize()},e.handleVisibilityChanged=()=>{this.updateVisibility()},this.elementInfos.push(e),e.observe(),this.debouncedHandleResize(),this.updateVisibility()):this.log.warn(`visibility resize observer not triggered`,this.logContext)}stopObservingElementInfo(e){if(!this.isAdaptiveStream){this.log.warn(`stopObservingElementInfo ignored`,this.logContext);return}let t=this.elementInfos.filter(t=>t===e);for(let e of t)e.stopObserving();this.elementInfos=this.elementInfos.filter(t=>t!==e),this.updateVisibility(),this.debouncedHandleResize()}detach(e){let t=[];if(e)return this.stopObservingElement(e),super.detach(e);t=super.detach();for(let e of t)this.stopObservingElement(e);return t}getDecoderImplementation(){return this.prevStats?.decoderImplementation}getReceiverStats(){return N(this,void 0,void 0,function*(){if(!this.receiver||!this.receiver.getStats)return;let e=yield this.receiver.getStats(),t,n=``,r=new Map;return e.forEach(e=>{e.type===`inbound-rtp`?(n=e.codecId,t={type:`video`,streamId:e.id,framesDecoded:e.framesDecoded,framesDropped:e.framesDropped,framesReceived:e.framesReceived,packetsReceived:e.packetsReceived,packetsLost:e.packetsLost,frameWidth:e.frameWidth,frameHeight:e.frameHeight,pliCount:e.pliCount,firCount:e.firCount,nackCount:e.nackCount,jitter:e.jitter,timestamp:e.timestamp,bytesReceived:e.bytesReceived,decoderImplementation:e.decoderImplementation}):e.type===`codec`&&r.set(e.id,e)}),t&&n!==``&&r.get(n)&&(t.mimeType=r.get(n).mimeType),t})}stopObservingElement(e){let t=this.elementInfos.filter(t=>t.element===e);for(let e of t)this.stopObservingElementInfo(e)}handleAppVisibilityChanged(){let e=Object.create(null,{handleAppVisibilityChanged:{get:()=>super.handleAppVisibilityChanged}});return N(this,void 0,void 0,function*(){yield e.handleAppVisibilityChanged.call(this),this.isAdaptiveStream&&this.updateVisibility()})}updateVisibility(e){let t=this.elementInfos.reduce((e,t)=>Math.max(e,t.visibilityChangedAt||0),0),n=this.adaptiveStreamSettings?.pauseVideoInBackground??!0?this.isInBackground:!1,r=this.elementInfos.some(e=>e.pictureInPicture),i=this.elementInfos.some(e=>e.visible)&&!n||r;if(!(this.lastVisible===i&&!e)){if(!i&&Date.now()-t<Hm){vl.setTimeout(()=>{this.updateVisibility()},Hm);return}this.lastVisible=i,this.emit(B.VisibilityChanged,i,this)}}updateDimensions(){let e=0,t=0,n=this.getPixelDensity();for(let r of this.elementInfos){let i=r.width()*n,a=r.height()*n;i+a>e+t&&(e=i,t=a)}this.lastDimensions?.width===e&&this.lastDimensions?.height===t||(this.lastDimensions={width:e,height:t},this.emit(B.VideoDimensionsChanged,this.lastDimensions,this))}getPixelDensity(){let e=this.adaptiveStreamSettings?.pixelDensity;return e===`screen`?xu():e||(xu()>2?2:1)}},Wm=class{get visible(){return this.isPiP||this.isIntersecting}get pictureInPicture(){return this.isPiP}constructor(e,t){this.onVisibilityChanged=e=>{var t;let{target:n,isIntersecting:r}=e;n===this.element&&(this.isIntersecting=r,this.isPiP=Gm(this.element),this.visibilityChangedAt=Date.now(),(t=this.handleVisibilityChanged)==null||t.call(this))},this.onEnterPiP=()=>{var e,t;(e=window.documentPictureInPicture?.window)==null||e.addEventListener(`pagehide`,this.onLeavePiP),this.isPiP=Gm(this.element),(t=this.handleVisibilityChanged)==null||t.call(this)},this.onLeavePiP=()=>{var e;this.isPiP=Gm(this.element),(e=this.handleVisibilityChanged)==null||e.call(this)},this.element=e,this.isIntersecting=t??Km(e),this.isPiP=hu()&&Gm(e),this.visibilityChangedAt=0}width(){return this.element.clientWidth}height(){return this.element.clientHeight}observe(){var e,t;this.isIntersecting=Km(this.element),this.isPiP=Gm(this.element),this.element.handleResize=()=>{var e;(e=this.handleResize)==null||e.call(this)},this.element.handleVisibilityChanged=this.onVisibilityChanged,Ou().observe(this.element),Eu().observe(this.element),this.element.addEventListener(`enterpictureinpicture`,this.onEnterPiP),this.element.addEventListener(`leavepictureinpicture`,this.onLeavePiP),(e=window.documentPictureInPicture)==null||e.addEventListener(`enter`,this.onEnterPiP),(t=window.documentPictureInPicture?.window)==null||t.addEventListener(`pagehide`,this.onLeavePiP)}stopObserving(){var e,t,n,r;(e=Ou())==null||e.unobserve(this.element),(t=Eu())==null||t.unobserve(this.element),this.element.removeEventListener(`enterpictureinpicture`,this.onEnterPiP),this.element.removeEventListener(`leavepictureinpicture`,this.onLeavePiP),(n=window.documentPictureInPicture)==null||n.removeEventListener(`enter`,this.onEnterPiP),(r=window.documentPictureInPicture?.window)==null||r.removeEventListener(`pagehide`,this.onLeavePiP)}};function Gm(e){return document.pictureInPictureElement===e?!0:window.documentPictureInPicture?.window?Km(e,window.documentPictureInPicture?.window):!1}function Km(e,t){let n=t||window,r=e.offsetTop,i=e.offsetLeft,a=e.offsetWidth,o=e.offsetHeight,{hidden:s}=e,{display:c}=getComputedStyle(e);for(;e.offsetParent;)e=e.offsetParent,r+=e.offsetTop,i+=e.offsetLeft;return r<n.pageYOffset+n.innerHeight&&i<n.pageXOffset+n.innerWidth&&r+o>n.pageYOffset&&i+a>n.pageXOffset&&!s&&c!==`none`}var qm=class extends Bs.EventEmitter{constructor(e,t,n,r){super(),this.metadataMuted=!1,this.encryption=j.NONE,this.log=M,this.handleMuted=()=>{this.emit(B.Muted)},this.handleUnmuted=()=>{this.emit(B.Unmuted)},this.log=Es(r?.loggerName??Ts.Publication),this.loggerContextCb=this.loggerContextCb,this.setMaxListeners(100),this.kind=e,this.trackSid=t,this.trackName=n,this.source=U.Source.Unknown}setTrack(e){this.track&&(this.track.off(B.Muted,this.handleMuted),this.track.off(B.Unmuted,this.handleUnmuted)),this.track=e,e&&(e.on(B.Muted,this.handleMuted),e.on(B.Unmuted,this.handleUnmuted))}get logContext(){return Object.assign(Object.assign({},this.loggerContextCb?.call(this)),H(this))}get isMuted(){return this.metadataMuted}get isEnabled(){return!0}get isSubscribed(){return this.track!==void 0}get isEncrypted(){return this.encryption!==j.NONE}get audioTrack(){if(Wu(this.track))return this.track}get videoTrack(){if(Gu(this.track))return this.track}updateInfo(e){this.trackSid=e.sid,this.trackName=e.name,this.source=U.sourceFromProto(e.source),this.mimeType=e.mimeType,this.kind===U.Kind.Video&&e.width>0&&(this.dimensions={width:e.width,height:e.height},this.simulcasted=e.simulcast),this.encryption=e.encryption,this.trackInfo=e,this.log.debug(`update publication info`,Object.assign(Object.assign({},this.logContext),{info:e}))}};(function(e){(function(e){e.Desired=`desired`,e.Subscribed=`subscribed`,e.Unsubscribed=`unsubscribed`})(e.SubscriptionStatus||={}),(function(e){e.Allowed=`allowed`,e.NotAllowed=`not_allowed`})(e.PermissionStatus||={})})(qm||={});var Jm=class extends qm{get isUpstreamPaused(){return this.track?.isUpstreamPaused}constructor(e,t,n,r){super(e,t.sid,t.name,r),this.track=void 0,this.handleTrackEnded=()=>{this.emit(B.Ended)},this.handleCpuConstrained=()=>{this.track&&Gu(this.track)&&this.emit(B.CpuConstrained,this.track)},this.updateInfo(t),this.setTrack(n)}setTrack(e){this.track&&(this.track.off(B.Ended,this.handleTrackEnded),this.track.off(B.CpuConstrained,this.handleCpuConstrained)),super.setTrack(e),e&&(e.on(B.Ended,this.handleTrackEnded),e.on(B.CpuConstrained,this.handleCpuConstrained))}get isMuted(){return this.track?this.track.isMuted:super.isMuted}get audioTrack(){return super.audioTrack}get videoTrack(){return super.videoTrack}get isLocal(){return!0}mute(){return N(this,void 0,void 0,function*(){return this.track?.mute()})}unmute(){return N(this,void 0,void 0,function*(){return this.track?.unmute()})}pauseUpstream(){return N(this,void 0,void 0,function*(){yield this.track?.pauseUpstream()})}resumeUpstream(){return N(this,void 0,void 0,function*(){yield this.track?.resumeUpstream()})}getTrackFeatures(){if(Wu(this.track)){let e=this.track.getSourceTrackSettings(),t=new Set;return e.autoGainControl&&t.add(_a.TF_AUTO_GAIN_CONTROL),e.echoCancellation&&t.add(_a.TF_ECHO_CANCELLATION),e.noiseSuppression&&t.add(_a.TF_NOISE_SUPPRESSION),e.channelCount&&e.channelCount>1&&t.add(_a.TF_STEREO),this.options?.dtx||t.add(_a.TF_NO_DTX),this.track.enhancedNoiseCancellation&&t.add(_a.TF_ENHANCED_NOISE_CANCELLATION),Array.from(t.values())}else return[]}};function Ym(e,t){return N(this,void 0,void 0,function*(){e??={};let n=!1,{audioProcessor:r,videoProcessor:i,optionsWithoutProcessor:a}=Vl(e),o=a.audio,s=a.video;if(r&&typeof a.audio==`object`&&(a.audio.processor=r),i&&typeof a.video==`object`&&(a.video.processor=i),e.audio&&typeof a.audio==`object`&&typeof a.audio.deviceId==`string`){let e=a.audio.deviceId;a.audio.deviceId={exact:e},n=!0,o=Object.assign(Object.assign({},a.audio),{deviceId:{ideal:e}})}if(a.video&&typeof a.video==`object`&&typeof a.video.deviceId==`string`){let e=a.video.deviceId;a.video.deviceId={exact:e},n=!0,s=Object.assign(Object.assign({},a.video),{deviceId:{ideal:e}})}a.audio===!0?a.audio={deviceId:`default`}:typeof a.audio==`object`&&a.audio!==null&&(a.audio=Object.assign(Object.assign({},a.audio),{deviceId:a.audio.deviceId||`default`})),a.video===!0?a.video={deviceId:`default`}:typeof a.video==`object`&&!a.video.deviceId&&(a.video.deviceId=`default`);let c=kl(a,yf,bf),l=jl(c),u=navigator.mediaDevices.getUserMedia(l);a.audio&&(Cd.userMediaPromiseMap.set(`audioinput`,u),u.catch(()=>Cd.userMediaPromiseMap.delete(`audioinput`))),a.video&&(Cd.userMediaPromiseMap.set(`videoinput`,u),u.catch(()=>Cd.userMediaPromiseMap.delete(`videoinput`)));try{let e=yield u;return yield Promise.all(e.getTracks().map(n=>N(this,void 0,void 0,function*(){let a=n.kind===`audio`,o=a?c.audio:c.video;(typeof o==`boolean`||!o)&&(o={});let s,u=a?l.audio:l.video;typeof u!=`boolean`&&(s=u);let d=n.getSettings().deviceId;s?.deviceId&&Fu(s.deviceId)!==d?s.deviceId=d:s||={deviceId:d};let f=Hf(n,s,t);return f.kind===U.Kind.Video?f.source=U.Source.Camera:f.kind===U.Kind.Audio&&(f.source=U.Source.Microphone),f.mediaStream=e,Wu(f)&&r?yield f.setProcessor(r):Gu(f)&&i&&(yield f.setProcessor(i)),f})))}catch(r){if(!n)throw r;return Ym(Object.assign(Object.assign({},e),{audio:o,video:s}),t)}})}function Xm(e){return N(this,void 0,void 0,function*(){return(yield Ym({audio:e??!0,video:!1}))[0]})}var Zm;(function(e){e.Excellent=`excellent`,e.Good=`good`,e.Poor=`poor`,e.Lost=`lost`,e.Unknown=`unknown`})(Zm||={});function Qm(e){switch(e){case fa.EXCELLENT:return Zm.Excellent;case fa.GOOD:return Zm.Good;case fa.POOR:return Zm.Poor;case fa.LOST:return Zm.Lost;default:return Zm.Unknown}}var $m=class extends Bs.EventEmitter{get logContext(){var e;return Object.assign({},((e=this.loggerOptions)?.loggerContextCb)?.call(e))}get isEncrypted(){return this.trackPublications.size>0&&Array.from(this.trackPublications.values()).every(e=>e.isEncrypted)}get isAgent(){return this.permissions?.agent||this.kind===Ca.AGENT}get isActive(){return this.participantInfo?.state===Sa.ACTIVE}get kind(){return this._kind}get attributes(){return Object.freeze(Object.assign({},this._attributes))}constructor(e,t,n,r,i,a){let o=arguments.length>6&&arguments[6]!==void 0?arguments[6]:Ca.STANDARD;super(),this.audioLevel=0,this.isSpeaking=!1,this._connectionQuality=Zm.Unknown,this.log=M,this.log=Es(a?.loggerName??Ts.Participant),this.loggerOptions=a,this.setMaxListeners(100),this.sid=e,this.identity=t,this.name=n,this.metadata=r,this.audioTrackPublications=new Map,this.videoTrackPublications=new Map,this.trackPublications=new Map,this._kind=o,this._attributes=i??{}}getTrackPublications(){return Array.from(this.trackPublications.values())}getTrackPublication(e){for(let[,t]of this.trackPublications)if(t.source===e)return t}getTrackPublicationByName(e){for(let[,t]of this.trackPublications)if(t.trackName===e)return t}waitUntilActive(){return this.isActive?Promise.resolve():this.activeFuture?this.activeFuture.promise:(this.activeFuture=new Nu,this.once(R.Active,()=>{var e,t;(t=(e=this.activeFuture)?.resolve)==null||t.call(e),this.activeFuture=void 0}),this.activeFuture.promise)}get connectionQuality(){return this._connectionQuality}get isCameraEnabled(){return!(this.getTrackPublication(U.Source.Camera)?.isMuted??!0)}get isMicrophoneEnabled(){return!(this.getTrackPublication(U.Source.Microphone)?.isMuted??!0)}get isScreenShareEnabled(){return!!this.getTrackPublication(U.Source.ScreenShare)}get isLocal(){return!1}get joinedAt(){return this.participantInfo?new Date(Number.parseInt(this.participantInfo.joinedAt.toString())*1e3):new Date}updateInfo(e){return this.participantInfo&&this.participantInfo.sid===e.sid&&this.participantInfo.version>e.version?!1:(this.identity=e.identity,this.sid=e.sid,this._setName(e.name),this._setMetadata(e.metadata),this._setAttributes(e.attributes),e.state===Sa.ACTIVE&&this.participantInfo?.state!==Sa.ACTIVE&&this.emit(R.Active),e.permission&&this.setPermissions(e.permission),this.participantInfo=e,!0)}_setMetadata(e){let t=this.metadata!==e,n=this.metadata;this.metadata=e,t&&this.emit(R.ParticipantMetadataChanged,n)}_setName(e){let t=this.name!==e;this.name=e,t&&this.emit(R.ParticipantNameChanged,e)}_setAttributes(e){let t=Bl(this.attributes,e);this._attributes=e,Object.keys(t).length>0&&this.emit(R.AttributesChanged,t)}setPermissions(e){let t=this.permissions,n=e.canPublish!==this.permissions?.canPublish||e.canSubscribe!==this.permissions?.canSubscribe||e.canPublishData!==this.permissions?.canPublishData||e.hidden!==this.permissions?.hidden||e.recorder!==this.permissions?.recorder||e.canPublishSources.length!==this.permissions.canPublishSources.length||e.canPublishSources.some((e,t)=>e!==this.permissions?.canPublishSources[t])||e.canSubscribeMetrics!==this.permissions?.canSubscribeMetrics;return this.permissions=e,n&&this.emit(R.ParticipantPermissionsChanged,t),n}setIsSpeaking(e){e!==this.isSpeaking&&(this.isSpeaking=e,e&&(this.lastSpokeAt=new Date),this.emit(R.IsSpeakingChanged,e))}setConnectionQuality(e){let t=this._connectionQuality;this._connectionQuality=Qm(e),t!==this._connectionQuality&&this.emit(R.ConnectionQualityChanged,this._connectionQuality)}setDisconnected(){var e,t;this.activeFuture&&=((t=(e=this.activeFuture).reject)==null||t.call(e,Error(`Participant disconnected`)),void 0)}setAudioContext(e){this.audioContext=e,this.audioTrackPublications.forEach(t=>Wu(t.track)&&t.track.setAudioContext(e))}addTrackPublication(e){e.on(B.Muted,()=>{this.emit(R.TrackMuted,e)}),e.on(B.Unmuted,()=>{this.emit(R.TrackUnmuted,e)});let t=e;switch(t.track&&(t.track.sid=e.trackSid),this.trackPublications.set(e.trackSid,e),e.kind){case U.Kind.Audio:this.audioTrackPublications.set(e.trackSid,e);break;case U.Kind.Video:this.videoTrackPublications.set(e.trackSid,e);break}}};function eh(e){if(!e.participantSid&&!e.participantIdentity)throw Error(`Invalid track permission, must provide at least one of participantIdentity and participantSid`);return new Zo({participantIdentity:e.participantIdentity??``,participantSid:e.participantSid??``,allTracks:e.allowAll??!1,trackSids:e.allowedTrackSids||[]})}var th=class extends $m{constructor(e,t,n,r,i,a,o){super(e,t,void 0,void 0,void 0,{loggerName:r.loggerName,loggerContextCb:()=>this.engine.logContext}),this.pendingPublishing=new Set,this.pendingPublishPromises=new Map,this.participantTrackPermissions=[],this.allParticipantsAllowedToSubscribe=!0,this.encryptionType=j.NONE,this.enabledPublishVideoCodecs=[],this.pendingAcks=new Map,this.pendingResponses=new Map,this.handleReconnecting=()=>{this.reconnectFuture||=new Nu},this.handleReconnected=()=>{var e,t;(t=(e=this.reconnectFuture)?.resolve)==null||t.call(e),this.reconnectFuture=void 0,this.updateTrackSubscriptionPermissions()},this.handleClosing=()=>{var e,t,n,r,i,a;this.reconnectFuture&&=(this.reconnectFuture.promise.catch(e=>this.log.warn(e.message,this.logContext)),(t=(e=this.reconnectFuture)?.reject)==null||t.call(e,Error(`Got disconnected during reconnection attempt`)),void 0),this.signalConnectedFuture&&=((r=(n=this.signalConnectedFuture).reject)==null||r.call(n,Error(`Got disconnected without signal connected`)),void 0),(a=(i=this.activeAgentFuture)?.reject)==null||a.call(i,Error(`Got disconnected without active agent present`)),this.activeAgentFuture=void 0,this.firstActiveAgent=void 0},this.handleSignalConnected=e=>{var t,n;e.participant&&this.updateInfo(e.participant),this.signalConnectedFuture||=new Nu,(n=(t=this.signalConnectedFuture).resolve)==null||n.call(t)},this.handleSignalRequestResponse=e=>{let{requestId:t,reason:n,message:r}=e,i=this.pendingSignalRequests.get(t);switch(i&&(n!==ds.OK&&i.reject(new pl(r,n)),this.pendingSignalRequests.delete(t)),e.request.case){case`publishDataTrack`:{let t;switch(e.reason){case ds.NOT_ALLOWED:t=km.notAllowed(e.message);break;case ds.DUPLICATE_NAME:t=km.duplicateName(e.message);break;case ds.INVALID_NAME:t=km.invalidName(e.message);break;case ds.LIMIT_EXCEEDED:t=km.limitReached(e.message);break;default:t=km.unknown(e.reason,e.message);return}this.roomOutgoingDataTrackManager.receivedSfuPublishResponse(e.request.value.pubHandle,{type:`error`,error:t});break}}},this.handleDataPacket=e=>{switch(e.value.case){case`rpcResponse`:let t=e.value.value,n=null,r=null;t.value.case===`payload`?n=t.value.value:t.value.case===`error`&&(r=Of.fromProto(t.value.value)),this.handleIncomingRpcResponse(t.requestId,n,r);break;case`rpcAck`:let i=e.value.value;this.handleIncomingRpcAck(i.requestId);break}},this.updateTrackSubscriptionPermissions=()=>{this.log.debug(`updating track subscription permissions`,Object.assign(Object.assign({},this.logContext),{allParticipantsAllowed:this.allParticipantsAllowedToSubscribe,participantTrackPermissions:this.participantTrackPermissions})),this.engine.client.sendUpdateSubscriptionPermissions(this.allParticipantsAllowedToSubscribe,this.participantTrackPermissions.map(e=>eh(e)))},this.onTrackUnmuted=e=>{this.onTrackMuted(e,e.isUpstreamPaused)},this.onTrackMuted=(e,t)=>{if(t===void 0&&(t=!0),!e.sid){this.log.error(`could not update mute status for unpublished track`,Object.assign(Object.assign({},this.logContext),H(e)));return}this.engine.updateMuteStatus(e.sid,t)},this.onTrackUpstreamPaused=e=>{this.log.debug(`upstream paused`,Object.assign(Object.assign({},this.logContext),H(e))),this.onTrackMuted(e,!0)},this.onTrackUpstreamResumed=e=>{this.log.debug(`upstream resumed`,Object.assign(Object.assign({},this.logContext),H(e))),this.onTrackMuted(e,e.isMuted)},this.onTrackFeatureUpdate=e=>{let t=this.audioTrackPublications.get(e.sid);if(!t){this.log.warn(`Could not update local audio track settings, missing publication for track ${e.sid}`,this.logContext);return}this.engine.client.sendUpdateLocalAudioTrack(t.trackSid,t.getTrackFeatures())},this.onTrackCpuConstrained=(e,t)=>{this.log.debug(`track cpu constrained`,Object.assign(Object.assign({},this.logContext),H(t))),this.emit(R.LocalTrackCpuConstrained,e,t)},this.handleSubscribedQualityUpdate=e=>N(this,void 0,void 0,function*(){var t,n,r,i;if(!this.roomOptions?.dynacast)return;let a=this.videoTrackPublications.get(e.trackSid);if(!a){this.log.warn(`received subscribed quality update for unknown track`,Object.assign(Object.assign({},this.logContext),{trackSid:e.trackSid}));return}if(!a.videoTrack)return;let o=yield a.videoTrack.setPublishingCodecs(e.subscribedCodecs);try{for(var s=!0,c=Is(o),l;l=yield c.next(),t=l.done,!t;s=!0){i=l.value,s=!1;let e=i;Cl(e)&&(this.log.debug(`publish ${e} for ${a.videoTrack.sid}`,Object.assign(Object.assign({},this.logContext),H(a))),yield this.publishAdditionalCodecForTrack(a.videoTrack,e,a.options))}}catch(e){n={error:e}}finally{try{!s&&!t&&(r=c.return)&&(yield r.call(c))}finally{if(n)throw n.error}}}),this.handleLocalTrackUnpublished=e=>{let t=this.trackPublications.get(e.trackSid);if(!t){this.log.warn(`received unpublished event for unknown track`,Object.assign(Object.assign({},this.logContext),{trackSid:e.trackSid}));return}this.unpublishTrack(t.track)},this.handleTrackEnded=e=>N(this,void 0,void 0,function*(){if(e.source===U.Source.ScreenShare||e.source===U.Source.ScreenShareAudio)this.log.debug(`unpublishing local track due to TrackEnded`,Object.assign(Object.assign({},this.logContext),H(e))),this.unpublishTrack(e);else if(e.isUserProvided)yield e.mute();else if(qu(e)||Ku(e))try{if(hu())try{let t=yield navigator==null?void 0:navigator.permissions.query({name:e.source===U.Source.Camera?`camera`:`microphone`});if(t&&t.state===`denied`)throw this.log.warn(`user has revoked access to ${e.source}`,Object.assign(Object.assign({},this.logContext),H(e))),t.onchange=()=>{t.state!==`denied`&&(e.isMuted||e.restartTrack(),t.onchange=null)},Error(`GetUserMedia Permission denied`)}catch{}e.isMuted||(this.log.debug(`track ended, attempting to use a different device`,Object.assign(Object.assign({},this.logContext),H(e))),qu(e)?yield e.restartTrack({deviceId:`default`}):yield e.restartTrack())}catch{this.log.warn(`could not restart track, muting instead`,Object.assign(Object.assign({},this.logContext),H(e))),yield e.mute()}}),this.audioTrackPublications=new Map,this.videoTrackPublications=new Map,this.trackPublications=new Map,this.engine=n,this.roomOptions=r,this.setupEngine(n),this.activeDeviceMap=new Map([[`audioinput`,`default`],[`videoinput`,`default`],[`audiooutput`,`default`]]),this.pendingSignalRequests=new Map,this.rpcHandlers=i,this.roomOutgoingDataStreamManager=a,this.roomOutgoingDataTrackManager=o}get lastCameraError(){return this.cameraError}get lastMicrophoneError(){return this.microphoneError}get isE2EEEnabled(){return this.encryptionType!==j.NONE}getTrackPublication(e){let t=super.getTrackPublication(e);if(t)return t}getTrackPublicationByName(e){let t=super.getTrackPublicationByName(e);if(t)return t}setupEngine(e){this.engine=e,this.engine.on(z.RemoteMute,(e,t)=>{let n=this.trackPublications.get(e);!n||!n.track||(t?n.mute():n.unmute())}),this.signalConnectedFuture?.isResolved&&(this.signalConnectedFuture=void 0),this.engine.on(z.Connected,this.handleReconnected).on(z.SignalConnected,this.handleSignalConnected).on(z.SignalRestarted,this.handleReconnected).on(z.SignalResumed,this.handleReconnected).on(z.Restarting,this.handleReconnecting).on(z.Resuming,this.handleReconnecting).on(z.LocalTrackUnpublished,this.handleLocalTrackUnpublished).on(z.SubscribedQualityUpdate,this.handleSubscribedQualityUpdate).on(z.Closing,this.handleClosing).on(z.SignalRequestResponse,this.handleSignalRequestResponse).on(z.DataPacketReceived,this.handleDataPacket)}setMetadata(e){return N(this,void 0,void 0,function*(){yield this.requestMetadataUpdate({metadata:e})})}setName(e){return N(this,void 0,void 0,function*(){yield this.requestMetadataUpdate({name:e})})}setAttributes(e){return N(this,void 0,void 0,function*(){yield this.requestMetadataUpdate({attributes:e})})}requestMetadataUpdate(e){return N(this,arguments,void 0,function(e){var t=this;let{metadata:n,name:r,attributes:i}=e;return function*(){return new Qc((e,a)=>N(t,void 0,void 0,function*(){try{let t=!1,o=yield this.engine.client.sendUpdateLocalMetadata(n??this.metadata??``,r??this.name??``,i),s=performance.now();for(this.pendingSignalRequests.set(o,{resolve:e,reject:e=>{a(e),t=!0},values:{name:r,metadata:n,attributes:i}});performance.now()-s<5e3&&!t;){if((!r||this.name===r)&&(!n||this.metadata===n)&&(!i||Object.entries(i).every(e=>{let[t,n]=e;return this.attributes[t]===n||n===``&&!this.attributes[t]}))){this.pendingSignalRequests.delete(o),e();return}yield $l(50)}a(new pl(`Request to update local metadata timed out`,`TimeoutError`))}catch(e){e instanceof Error?a(e):a(Error(String(e)))}}))}()})}setCameraEnabled(e,t,n){return this.setTrackEnabled(U.Source.Camera,e,t,n)}setMicrophoneEnabled(e,t,n){return this.setTrackEnabled(U.Source.Microphone,e,t,n)}setScreenShareEnabled(e,t,n){return this.setTrackEnabled(U.Source.ScreenShare,e,t,n)}setE2EEEnabled(e){return N(this,void 0,void 0,function*(){this.encryptionType=e?j.GCM:j.NONE,yield this.republishAllTracks(void 0,!1)})}setTrackEnabled(e,t,n,r){return N(this,void 0,void 0,function*(){this.log.debug(`setTrackEnabled`,Object.assign(Object.assign({},this.logContext),{source:e,enabled:t})),this.republishPromise&&(yield this.republishPromise);let i=this.getTrackPublication(e);if(t)if(i)yield i.unmute();else{let t;if(this.pendingPublishing.has(e)){let t=yield this.waitForPendingPublicationOfSource(e);return t||this.log.info(`waiting for pending publication promise timed out`,Object.assign(Object.assign({},this.logContext),{source:e})),yield t?.unmute(),t}this.pendingPublishing.add(e);try{switch(e){case U.Source.Camera:t=yield this.createTracks({video:n??!0});break;case U.Source.Microphone:t=yield this.createTracks({audio:n??!0});break;case U.Source.ScreenShare:t=yield this.createScreenTracks(Object.assign({},n));break;default:throw new ll(e)}}catch(n){throw t?.forEach(e=>{e.stop()}),n instanceof Error&&this.emit(R.MediaDevicesError,n,Fl(e)),this.pendingPublishing.delete(e),n}for(let r of t){let t=Object.assign(Object.assign({},this.roomOptions.publishDefaults),n);e===U.Source.Microphone&&Wu(r)&&t.preConnectBuffer&&(this.log.info(`starting preconnect buffer for microphone`,Object.assign({},this.logContext)),r.startPreConnectBuffer())}try{let e=[];for(let n of t)this.log.info(`publishing track`,Object.assign(Object.assign({},this.logContext),H(n))),e.push(this.publishTrack(n,r));let n=yield Promise.all(e);[i]=n}catch(e){throw t?.forEach(e=>{e.stop()}),e}finally{this.pendingPublishing.delete(e)}}else if(!i?.track&&this.pendingPublishing.has(e)&&(i=yield this.waitForPendingPublicationOfSource(e),i||this.log.info(`waiting for pending publication promise timed out`,Object.assign(Object.assign({},this.logContext),{source:e}))),i&&i.track)if(e===U.Source.ScreenShare){i=yield this.unpublishTrack(i.track);let e=this.getTrackPublication(U.Source.ScreenShareAudio);e&&e.track&&this.unpublishTrack(e.track)}else yield i.mute();return i})}enableCameraAndMicrophone(){return N(this,void 0,void 0,function*(){if(!(this.pendingPublishing.has(U.Source.Camera)||this.pendingPublishing.has(U.Source.Microphone))){this.pendingPublishing.add(U.Source.Camera),this.pendingPublishing.add(U.Source.Microphone);try{let e=yield this.createTracks({audio:!0,video:!0});yield Promise.all(e.map(e=>this.publishTrack(e)))}finally{this.pendingPublishing.delete(U.Source.Camera),this.pendingPublishing.delete(U.Source.Microphone)}}})}createTracks(e){return N(this,void 0,void 0,function*(){e??={};let t=kl(e,this.roomOptions?.audioCaptureDefaults,this.roomOptions?.videoCaptureDefaults);try{return(yield Ym(t,{loggerName:this.roomOptions.loggerName,loggerContextCb:()=>this.logContext})).map(e=>(Wu(e)&&(this.microphoneError=void 0,e.setAudioContext(this.audioContext),e.source=U.Source.Microphone,this.emit(R.AudioStreamAcquired)),Gu(e)&&(this.cameraError=void 0,e.source=U.Source.Camera),e))}catch(t){throw t instanceof Error&&(e.audio&&(this.microphoneError=t),e.video&&(this.cameraError=t)),t}})}createScreenTracks(e){return N(this,void 0,void 0,function*(){if(e===void 0&&(e={}),navigator.mediaDevices.getDisplayMedia===void 0)throw new cl(`getDisplayMedia not supported`);e.resolution===void 0&&!du()&&(e.resolution=Ol.h1080fps30.resolution);let t=Il(e),n=yield navigator.mediaDevices.getDisplayMedia(t),r=n.getVideoTracks();if(r.length===0)throw new ll(`no video track found`);let i=new op(r[0],void 0,!1,{loggerName:this.roomOptions.loggerName,loggerContextCb:()=>this.logContext});i.source=U.Source.ScreenShare,e.contentHint&&(i.mediaStreamTrack.contentHint=e.contentHint);let a=[i];if(n.getAudioTracks().length>0){this.emit(R.AudioStreamAcquired);let e=new Vf(n.getAudioTracks()[0],void 0,!1,this.audioContext,{loggerName:this.roomOptions.loggerName,loggerContextCb:()=>this.logContext});e.source=U.Source.ScreenShareAudio,a.push(e)}return a})}publishTrack(e,t){return N(this,void 0,void 0,function*(){return this.publishOrRepublishTrack(e,t)})}publishOrRepublishTrack(e,t){return N(this,arguments,void 0,function(e,t){var n=this;let r=arguments.length>2&&arguments[2]!==void 0?arguments[2]:!1;return function*(){qu(e)&&e.setAudioContext(n.audioContext),yield n.reconnectFuture?.promise,n.republishPromise&&!r&&(yield n.republishPromise),Uu(e)&&n.pendingPublishPromises.has(e)&&(yield n.pendingPublishPromises.get(e));let i;if(e instanceof MediaStreamTrack)i=e.getConstraints();else{i=e.constraints;let t;switch(e.source){case U.Source.Microphone:t=`audioinput`;break;case U.Source.Camera:t=`videoinput`}t&&n.activeDeviceMap.has(t)&&(i=Object.assign(Object.assign({},i),{deviceId:n.activeDeviceMap.get(t)}))}if(e instanceof MediaStreamTrack)switch(e.kind){case`audio`:e=new Vf(e,i,!0,n.audioContext,{loggerName:n.roomOptions.loggerName,loggerContextCb:()=>n.logContext});break;case`video`:e=new op(e,i,!0,{loggerName:n.roomOptions.loggerName,loggerContextCb:()=>n.logContext});break;default:throw new ll(`unsupported MediaStreamTrack kind ${e.kind}`)}else e.updateLoggerOptions({loggerName:n.roomOptions.loggerName,loggerContextCb:()=>n.logContext});let a;if(n.trackPublications.forEach(t=>{t.track&&t.track===e&&(a=t)}),a)return n.log.warn(`track has already been published, skipping`,Object.assign(Object.assign({},n.logContext),H(a))),a;let o=Object.assign(Object.assign({},n.roomOptions.publishDefaults),t),s=`channelCount`in e.mediaStreamTrack.getSettings()&&e.mediaStreamTrack.getSettings().channelCount===2||e.mediaStreamTrack.getConstraints().channelCount===2,c=o.forceStereo??s;c&&(o.dtx===void 0&&n.log.info(`Opus DTX will be disabled for stereo tracks by default. Enable them explicitly to make it work.`,Object.assign(Object.assign({},n.logContext),H(e))),o.red===void 0&&n.log.info(`Opus RED will be disabled for stereo tracks by default. Enable them explicitly to make it work.`),o.dtx??=!1,o.red??=!1),!mu()&&n.roomOptions.e2ee&&(n.log.info(`End-to-end encryption is set up, simulcast publishing will be disabled on Safari versions and iOS browsers running iOS < v17.2`,Object.assign({},n.logContext)),o.simulcast=!1),o.source&&(e.source=o.source);let l=new Promise((t,r)=>N(n,void 0,void 0,function*(){try{if(this.engine.client.currentState!==W.CONNECTED){this.log.debug(`deferring track publication until signal is connected`,Object.assign(Object.assign({},this.logContext),{track:H(e)}));let n=!1,i=setTimeout(()=>{n=!0,e.stop(),r(new fl(`publishing rejected as engine not connected within timeout`,408))},15e3);if(yield this.waitUntilEngineConnected(),clearTimeout(i),n)return;t(yield this.publish(e,o,c))}else try{t(yield this.publish(e,o,c))}catch(e){r(e)}}catch(e){r(e)}}));n.pendingPublishPromises.set(e,l);try{return yield l}catch(e){throw e}finally{n.pendingPublishPromises.delete(e)}}()})}waitUntilEngineConnected(){return this.signalConnectedFuture||=new Nu,this.signalConnectedFuture.promise}hasPermissionsToPublish(e){if(!this.permissions)return this.log.warn(`no permissions present for publishing track`,Object.assign(Object.assign({},this.logContext),H(e))),!1;let{canPublish:t,canPublishSources:n}=this.permissions;return t&&(n.length===0||n.map(e=>Hl(e)).includes(e.source))?!0:(this.log.warn(`insufficient permissions to publish`,Object.assign(Object.assign({},this.logContext),H(e))),!1)}publish(e,t,n){return N(this,void 0,void 0,function*(){if(!this.hasPermissionsToPublish(e))throw new fl(`failed to publish track, insufficient permissions`,403);Array.from(this.trackPublications.values()).find(t=>Uu(e)&&t.source===e.source)&&e.source!==U.Source.Unknown&&this.log.info(`publishing a second track with the same source: ${e.source}`,Object.assign(Object.assign({},this.logContext),H(e))),t.stopMicTrackOnMute&&Wu(e)&&(e.stopOnMute=!0),e.source===U.Source.ScreenShare&&su()&&(t.simulcast=!1),t.videoCodec===`av1`&&!nu()&&(t.videoCodec=void 0),t.videoCodec===`vp9`&&!ru()&&(t.videoCodec=void 0),t.videoCodec===void 0&&(t.videoCodec=_f),this.enabledPublishVideoCodecs.length>0&&(this.enabledPublishVideoCodecs.some(e=>t.videoCodec===Ll(e.mime))||(t.videoCodec=Ll(this.enabledPublishVideoCodecs[0].mime)));let r=t.videoCodec;e.on(B.Muted,this.onTrackMuted),e.on(B.Unmuted,this.onTrackUnmuted),e.on(B.Ended,this.handleTrackEnded),e.on(B.UpstreamPaused,this.onTrackUpstreamPaused),e.on(B.UpstreamResumed,this.onTrackUpstreamResumed),e.on(B.AudioTrackFeatureUpdate,this.onTrackFeatureUpdate);let i=[],a=!(t.dtx??!0),o=e.getSourceTrackSettings();o.autoGainControl&&i.push(_a.TF_AUTO_GAIN_CONTROL),o.echoCancellation&&i.push(_a.TF_ECHO_CANCELLATION),o.noiseSuppression&&i.push(_a.TF_NOISE_SUPPRESSION),o.channelCount&&o.channelCount>1&&i.push(_a.TF_STEREO),a&&i.push(_a.TF_NO_DTX),qu(e)&&e.hasPreConnectBuffer&&i.push(_a.TF_PRECONNECT_BUFFER);let s=new ho({cid:e.mediaStreamTrack.id,name:t.name,type:U.kindToProto(e.kind),muted:e.isMuted,source:U.sourceToProto(e.source),disableDtx:a,encryption:this.encryptionType,stereo:n,disableRed:this.isE2EEEnabled||!(t.red??!0),stream:t?.stream,backupCodecPolicy:t?.backupCodecPolicy,audioFeatures:i}),c;if(e.kind===U.Kind.Video){let n={width:0,height:0};try{n=yield e.waitForDimensions()}catch{let t=this.roomOptions.videoCaptureDefaults?.resolution??El.h720.resolution;n={width:t.width,height:t.height},this.log.error(`could not determine track dimensions, using defaults`,Object.assign(Object.assign(Object.assign({},this.logContext),H(e)),{dims:n}))}s.width=n.width,s.height=n.height,Ku(e)&&(iu(r)&&(e.source===U.Source.ScreenShare&&(t.scalabilityMode=`L1T3`,`contentHint`in e.mediaStreamTrack&&(e.mediaStreamTrack.contentHint=`motion`,this.log.info(`forcing contentHint to motion for screenshare with SVC codecs`,Object.assign(Object.assign({},this.logContext),H(e))))),t.scalabilityMode=t.scalabilityMode??`L3T3_KEY`),s.simulcastCodecs=[new mo({codec:r,cid:e.mediaStreamTrack.id})],t.backupCodec===!0&&(t.backupCodec={codec:_f}),t.backupCodec&&r!==t.backupCodec.codec&&s.encryption===j.NONE&&(this.roomOptions.dynacast||(this.roomOptions.dynacast=!0),s.simulcastCodecs.push(new mo({codec:t.backupCodec.codec,cid:``})))),c=Xf(e.source===U.Source.ScreenShare,s.width,s.height,t),s.layers=lp(s.width,s.height,c,iu(t.videoCodec))}else e.kind===U.Kind.Audio&&(c=[{maxBitrate:t.audioPreset?.maxBitrate,priority:t.audioPreset?.priority??`high`,networkPriority:t.audioPreset?.priority??`high`}]);if(!this.engine||this.engine.isClosed)throw new I(`cannot publish track when not connected`);let l=()=>N(this,void 0,void 0,function*(){if(!this.engine.pcManager)throw new I(`pcManager is not ready`);if(e.sender=yield this.engine.createSender(e,t,c),this.emit(R.LocalSenderCreated,e.sender,e),Ku(e)&&(t.degradationPreference??=ip(e),e.setDegradationPreference(t.degradationPreference)),c)if(su()&&e.kind===U.Kind.Audio){let t;for(let n of this.engine.pcManager.publisher.getTransceivers())if(n.sender===e.sender){t=n;break}t&&this.engine.pcManager.publisher.setTrackCodecBitrate({transceiver:t,codec:`opus`,maxbr:c[0]?.maxBitrate?c[0].maxBitrate/1e3:0})}else e.codec&&iu(e.codec)&&c[0]?.maxBitrate&&this.engine.pcManager.publisher.setTrackCodecBitrate({cid:s.cid,codec:e.codec,maxbr:c[0].maxBitrate/1e3});yield this.engine.negotiate()}),u,d=new Promise((t,n)=>N(this,void 0,void 0,function*(){try{u=yield this.engine.addTrack(s),t(u)}catch(t){e.sender&&this.engine.pcManager?.publisher&&(this.engine.pcManager.publisher.removeTrack(e.sender),yield this.engine.negotiate().catch(t=>{this.log.error(`failed to negotiate after removing track due to failed add track request`,Object.assign(Object.assign(Object.assign({},this.logContext),H(e)),{error:t}))})),n(t)}}));if(this.enabledPublishVideoCodecs.length>0)u=(yield Promise.all([d,l()]))[0];else{u=yield d;let n;if(u.codecs.forEach(e=>{n===void 0&&(n=e.mimeType)}),n&&e.kind===U.Kind.Video){let i=Ll(n);i!==r&&(this.log.debug(`falling back to server selected codec`,Object.assign(Object.assign(Object.assign({},this.logContext),H(e)),{codec:i})),t.videoCodec=i,c=Xf(e.source===U.Source.ScreenShare,s.width,s.height,t))}yield l()}let f=new Jm(e.kind,u,e,{loggerName:this.roomOptions.loggerName,loggerContextCb:()=>this.logContext});if(f.on(B.CpuConstrained,e=>this.onTrackCpuConstrained(e,f)),f.options=t,e.sid=u.sid,this.log.debug(`publishing ${e.kind} with encodings`,Object.assign(Object.assign({},this.logContext),{encodings:c,trackInfo:u})),Ku(e)?e.startMonitor(this.engine.client):qu(e)&&e.startMonitor(),this.addTrackPublication(f),this.emit(R.LocalTrackPublished,f),qu(e)&&u.audioFeatures.includes(_a.TF_PRECONNECT_BUFFER)){let t=e.getPreConnectBuffer(),n=e.getPreConnectBufferMimeType();this.on(R.LocalTrackSubscribed,t=>{if(t.trackSid===u.sid){if(!e.hasPreConnectBuffer){this.log.warn(`subscribe event came to late, buffer already closed`,this.logContext);return}this.log.debug(`finished recording preconnect buffer`,Object.assign(Object.assign({},this.logContext),H(e))),e.stopPreConnectBuffer()}}),t&&new Promise((r,i)=>N(this,void 0,void 0,function*(){var a,s,c,l;try{this.log.debug(`waiting for agent`,Object.assign(Object.assign({},this.logContext),H(e)));let m=setTimeout(()=>{i(Error(`agent not active within 10 seconds`))},1e4),ee=yield this.waitUntilActiveAgentPresent();clearTimeout(m),this.log.debug(`sending preconnect buffer`,Object.assign(Object.assign({},this.logContext),H(e)));let h=yield this.streamBytes({name:`preconnect-buffer`,mimeType:n,topic:`lk.agent.pre-connect-audio-buffer`,destinationIdentities:[ee.identity],attributes:{trackId:f.trackSid,sampleRate:String(o.sampleRate??`48000`),channels:String(o.channelCount??`1`)}});try{for(var u=!0,d=Is(t),p;p=yield d.next(),a=p.done,!a;u=!0){l=p.value,u=!1;let e=l;yield h.write(e)}}catch(e){s={error:e}}finally{try{!u&&!a&&(c=d.return)&&(yield c.call(d))}finally{if(s)throw s.error}}yield h.close(),r()}catch(e){i(e)}})).then(()=>{this.log.debug(`preconnect buffer sent successfully`,Object.assign(Object.assign({},this.logContext),H(e)))}).catch(t=>{this.log.error(`error sending preconnect buffer`,Object.assign(Object.assign(Object.assign({},this.logContext),H(e)),{error:t}))})}return f})}get isLocal(){return!0}publishAdditionalCodecForTrack(e,t,n){return N(this,void 0,void 0,function*(){if(this.encryptionType!==j.NONE)return;let r;if(this.trackPublications.forEach(t=>{t.track&&t.track===e&&(r=t)}),!r)throw new ll(`track is not published`);if(!Ku(e))throw new ll(`track is not a video track`);let i=Object.assign(Object.assign({},this.roomOptions?.publishDefaults),n),a=Zf(e,t,i);if(!a){this.log.info(`backup codec has been disabled, ignoring request to add additional codec for track`,Object.assign(Object.assign({},this.logContext),H(e)));return}let o=e.addSimulcastTrack(t,a);if(!o)return;let s=new ho({cid:o.mediaStreamTrack.id,type:U.kindToProto(e.kind),muted:e.isMuted,source:U.sourceToProto(e.source),sid:e.sid,simulcastCodecs:[{codec:i.videoCodec,cid:o.mediaStreamTrack.id}]});if(s.layers=lp(s.width,s.height,a),!this.engine||this.engine.isClosed)throw new I(`cannot publish track when not connected`);let c=(yield Promise.all([this.engine.addTrack(s),N(this,void 0,void 0,function*(){yield this.engine.createSimulcastSender(e,o,i,a),yield this.engine.negotiate()})]))[0];this.log.debug(`published ${t} for track ${e.sid}`,Object.assign(Object.assign({},this.logContext),{encodings:a,trackInfo:c}))})}unpublishTrack(e,t){return N(this,void 0,void 0,function*(){if(Uu(e)){let t=this.pendingPublishPromises.get(e);t&&(this.log.info(`awaiting publish promise before attempting to unpublish`,Object.assign(Object.assign({},this.logContext),H(e))),yield t)}let n=this.getPublicationForTrack(e),r=n?H(n):void 0;if(this.log.debug(`unpublishing track`,Object.assign(Object.assign({},this.logContext),r)),!n||!n.track){this.log.warn(`track was not unpublished because no publication was found`,Object.assign(Object.assign({},this.logContext),r));return}e=n.track,e.off(B.Muted,this.onTrackMuted),e.off(B.Unmuted,this.onTrackUnmuted),e.off(B.Ended,this.handleTrackEnded),e.off(B.UpstreamPaused,this.onTrackUpstreamPaused),e.off(B.UpstreamResumed,this.onTrackUpstreamResumed),e.off(B.AudioTrackFeatureUpdate,this.onTrackFeatureUpdate),t===void 0&&(t=this.roomOptions?.stopLocalTrackOnUnpublish??!0),t?e.stop():e.stopMonitor();let i=!1,a=e.sender;if(e.sender=void 0,this.engine.pcManager&&this.engine.pcManager.currentState<G.FAILED&&a)try{for(let e of this.engine.pcManager.publisher.getTransceivers())e.sender===a&&(e.direction=`inactive`,i=!0);if(this.engine.removeTrack(a)&&(i=!0),Ku(e)){for(let[,t]of e.simulcastCodecs)t.sender&&=(this.engine.removeTrack(t.sender)&&(i=!0),void 0);e.simulcastCodecs.clear()}}catch(e){this.log.warn(`failed to unpublish track`,Object.assign(Object.assign(Object.assign({},this.logContext),r),{error:e}))}switch(this.trackPublications.delete(n.trackSid),n.kind){case U.Kind.Audio:this.audioTrackPublications.delete(n.trackSid);break;case U.Kind.Video:this.videoTrackPublications.delete(n.trackSid);break}return this.emit(R.LocalTrackUnpublished,n),n.setTrack(void 0),i&&(yield this.engine.negotiate()),n})}unpublishTracks(e){return N(this,void 0,void 0,function*(){return(yield Promise.all(e.map(e=>this.unpublishTrack(e)))).filter(e=>!!e)})}republishAllTracks(e){return N(this,arguments,void 0,function(e){var t=this;let n=arguments.length>1&&arguments[1]!==void 0?arguments[1]:!0;return function*(){t.republishPromise&&(yield t.republishPromise),t.republishPromise=new Qc((r,i)=>N(t,void 0,void 0,function*(){try{let t=[];this.trackPublications.forEach(n=>{n.track&&(e&&(n.options=Object.assign(Object.assign({},n.options),e)),t.push(n))}),yield Promise.all(t.map(e=>N(this,void 0,void 0,function*(){let t=e.track;yield this.unpublishTrack(t,!1),n&&!t.isMuted&&t.source!==U.Source.ScreenShare&&t.source!==U.Source.ScreenShareAudio&&(qu(t)||Ku(t))&&!t.isUserProvided&&(this.log.debug(`restarting existing track`,Object.assign(Object.assign({},this.logContext),{track:e.trackSid})),yield t.restartTrack()),yield this.publishOrRepublishTrack(t,e.options,!0)}))),r()}catch(e){e instanceof Error?i(e):i(Error(String(e)))}finally{this.republishPromise=void 0}})),yield t.republishPromise}()})}publishData(e){return N(this,arguments,void 0,function(e){var t=this;let n=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{};return function*(){let r=n.reliable?K.RELIABLE:K.LOSSY,i=n.reliable?Ma.RELIABLE:Ma.LOSSY,a=n.destinationIdentities,o=n.topic,s=new ja({kind:i,value:{case:`user`,value:new La({participantIdentity:t.identity,payload:e,destinationIdentities:a,topic:o})}});yield t.engine.sendDataPacket(s,r)}()})}publishDtmf(e,t){return N(this,void 0,void 0,function*(){let n=new ja({kind:Ma.RELIABLE,value:{case:`sipDtmf`,value:new Ra({code:e,digit:t})}});yield this.engine.sendDataPacket(n,K.RELIABLE)})}sendChatMessage(e,t){return N(this,void 0,void 0,function*(){let n={id:crypto.randomUUID(),message:e,timestamp:Date.now(),attachedFiles:t?.attachments},r=new ja({value:{case:`chatMessage`,value:new Va(Object.assign(Object.assign({},n),{timestamp:O.parse(n.timestamp)}))}});return yield this.engine.sendDataPacket(r,K.RELIABLE),this.emit(R.ChatMessage,n),n})}editChatMessage(e,t){return N(this,void 0,void 0,function*(){let n=Object.assign(Object.assign({},t),{message:e,editTimestamp:Date.now()}),r=new ja({value:{case:`chatMessage`,value:new Va(Object.assign(Object.assign({},n),{timestamp:O.parse(n.timestamp),editTimestamp:O.parse(n.editTimestamp)}))}});return yield this.engine.sendDataPacket(r,K.RELIABLE),this.emit(R.ChatMessage,n),n})}sendText(e,t){return N(this,void 0,void 0,function*(){return this.roomOutgoingDataStreamManager.sendText(e,t)})}streamText(e){return N(this,void 0,void 0,function*(){return this.roomOutgoingDataStreamManager.streamText(e)})}sendFile(e,t){return N(this,void 0,void 0,function*(){return this.roomOutgoingDataStreamManager.sendFile(e,t)})}streamBytes(e){return N(this,void 0,void 0,function*(){return this.roomOutgoingDataStreamManager.streamBytes(e)})}performRpc(e){let{destinationIdentity:t,method:n,payload:r,responseTimeout:i=15e3}=e,a=7e3;return a+1e3,new Qc((e,o)=>N(this,void 0,void 0,function*(){if(Af(r)>kf){o(Of.builtIn(`REQUEST_PAYLOAD_TOO_LARGE`));return}if(this.engine.latestJoinResponse?.serverInfo?.version&&Su(this.engine.latestJoinResponse?.serverInfo?.version,`1.8.0`)<0){o(Of.builtIn(`UNSUPPORTED_SERVER`));return}let s=Math.max(i,8e3),c=crypto.randomUUID();yield this.publishRpcRequest(t,c,n,r,s);let l=setTimeout(()=>{this.pendingAcks.delete(c),o(Of.builtIn(`CONNECTION_TIMEOUT`)),this.pendingResponses.delete(c),clearTimeout(u)},a);this.pendingAcks.set(c,{resolve:()=>{clearTimeout(l)},participantIdentity:t});let u=setTimeout(()=>{this.pendingResponses.delete(c),o(Of.builtIn(`RESPONSE_TIMEOUT`))},i);this.pendingResponses.set(c,{resolve:(t,n)=>{clearTimeout(u),this.pendingAcks.has(c)&&(this.log.warn(`RPC response received before ack`,c),this.pendingAcks.delete(c),clearTimeout(l)),n?o(n):e(t??``)},participantIdentity:t})}))}registerRpcMethod(e,t){this.rpcHandlers.has(e)&&this.log.warn(`you're overriding the RPC handler for method ${e}, in the future this will throw an error`),this.rpcHandlers.set(e,t)}unregisterRpcMethod(e){this.rpcHandlers.delete(e)}setTrackSubscriptionPermissions(e){this.participantTrackPermissions=arguments.length>1&&arguments[1]!==void 0?arguments[1]:[],this.allParticipantsAllowedToSubscribe=e,this.engine.client.isDisconnected||this.updateTrackSubscriptionPermissions()}handleIncomingRpcAck(e){let t=this.pendingAcks.get(e);t?(t.resolve(),this.pendingAcks.delete(e)):console.error(`Ack received for unexpected RPC request`,e)}handleIncomingRpcResponse(e,t,n){let r=this.pendingResponses.get(e);r?(r.resolve(t,n),this.pendingResponses.delete(e)):console.error(`Response received for unexpected RPC request`,e)}publishRpcRequest(e,t,n,r,i){return N(this,void 0,void 0,function*(){let a=new ja({destinationIdentities:[e],kind:Ma.RELIABLE,value:{case:`rpcRequest`,value:new Ha({id:t,method:n,payload:r,responseTimeoutMs:i,version:1})}});yield this.engine.sendDataPacket(a,K.RELIABLE)})}handleParticipantDisconnected(e){for(let[t,{participantIdentity:n}]of this.pendingAcks)n===e&&this.pendingAcks.delete(t);for(let[t,{participantIdentity:n,resolve:r}]of this.pendingResponses)n===e&&(r(null,Of.builtIn(`RECIPIENT_DISCONNECTED`)),this.pendingResponses.delete(t))}setEnabledPublishCodecs(e){this.enabledPublishVideoCodecs=e.filter(e=>e.mime.split(`/`)[0].toLowerCase()===`video`)}updateInfo(e){return super.updateInfo(e)?(e.tracks.forEach(e=>{let t=this.trackPublications.get(e.sid);if(t){let n=t.isMuted||(t.track?.isUpstreamPaused??!1);n!==e.muted&&(this.log.debug(`updating server mute state after reconcile`,Object.assign(Object.assign(Object.assign({},this.logContext),H(t)),{mutedOnServer:n})),this.engine.client.sendMuteTrack(e.sid,n))}}),!0):!1}setActiveAgent(e){var t,n,r,i;this.firstActiveAgent=e,e&&!this.firstActiveAgent&&(this.firstActiveAgent=e),e?(n=(t=this.activeAgentFuture)?.resolve)==null||n.call(t,e):(i=(r=this.activeAgentFuture)?.reject)==null||i.call(r,Error(`Agent disconnected`)),this.activeAgentFuture=void 0}waitUntilActiveAgentPresent(){return this.firstActiveAgent?Promise.resolve(this.firstActiveAgent):(this.activeAgentFuture||=new Nu,this.activeAgentFuture.promise)}getPublicationForTrack(e){let t;return this.trackPublications.forEach(n=>{let r=n.track;r&&(e instanceof MediaStreamTrack?(qu(r)||Ku(r))&&r.mediaStreamTrack===e&&(t=n):e===r&&(t=n))}),t}waitForPendingPublicationOfSource(e){return N(this,void 0,void 0,function*(){let t=Date.now();for(;Date.now()<t+1e4;){let t=Array.from(this.pendingPublishPromises.entries()).find(t=>{let[n]=t;return n.source===e});if(t)return t[1];yield $l(20)}})}publishDataTrack(e){return N(this,void 0,void 0,function*(){let t=new Pm(e,this.roomOutgoingDataTrackManager);return yield t.publish(),t})}},nh=class extends DOMException{constructor(e,t){super(e,`AbortError`),this.reason=t}},rh=class extends Map{constructor(){super(...arguments),this.pending=new Map}set(e,t){var n;super.set(e,t);let r=this.pending.get(e);if(r){for(let e of r)e.isResolved||(n=e.resolve)==null||n.call(e,t);this.pending.delete(e)}return this}get[Symbol.toStringTag](){return`WaitableMap`}getDeferred(e,t){return N(this,void 0,void 0,function*(){let n=this.get(e);if(n!==void 0)return n;if(t?.aborted)throw new nh(`The operation was aborted.`,t.reason);let r=new Nu(void 0,()=>{let t=this.pending.get(e);if(!t)return;let n=t.indexOf(r);n!==-1&&t.splice(n,1),t.length===0&&this.pending.delete(e)}),i=this.pending.get(e);if(i?i.push(r):this.pending.set(e,[r]),t){let e=()=>{var e;r.isResolved||(e=r.reject)==null||e.call(r,new nh(`The operation was aborted.`,t.reason))};t.addEventListener(`abort`,e,{once:!0}),r.promise.finally(()=>{t.removeEventListener(`abort`,e)})}return r.promise})}},ih=class extends qm{constructor(e,t,n,r){super(e,t.sid,t.name,r),this.track=void 0,this.allowed=!0,this.requestedDisabled=void 0,this.visible=!0,this.handleEnded=e=>{this.setTrack(void 0),this.emit(B.Ended,e)},this.handleVisibilityChange=e=>{this.log.debug(`adaptivestream video visibility ${this.trackSid}, visible=${e}`,this.logContext),this.visible=e,this.emitTrackUpdate()},this.handleVideoDimensionsChange=e=>{this.log.debug(`adaptivestream video dimensions ${e.width}x${e.height}`,this.logContext),this.videoDimensionsAdaptiveStream=e,this.emitTrackUpdate()},this.subscribed=n,this.updateInfo(t)}setSubscribed(e){let t=this.subscriptionStatus,n=this.permissionStatus;this.subscribed=e,e&&(this.allowed=!0);let r=new Ao({trackSids:[this.trackSid],subscribe:this.subscribed,participantTracks:[new Ka({participantSid:``,trackSids:[this.trackSid]})]});this.emit(B.UpdateSubscription,r),this.emitSubscriptionUpdateIfChanged(t),this.emitPermissionUpdateIfChanged(n)}get subscriptionStatus(){return this.subscribed===!1?qm.SubscriptionStatus.Unsubscribed:super.isSubscribed?qm.SubscriptionStatus.Subscribed:qm.SubscriptionStatus.Desired}get permissionStatus(){return this.allowed?qm.PermissionStatus.Allowed:qm.PermissionStatus.NotAllowed}get isSubscribed(){return this.subscribed===!1?!1:super.isSubscribed}get isDesired(){return this.subscribed!==!1}get isEnabled(){return this.requestedDisabled===void 0?this.isAdaptiveStream?this.visible:!0:!this.requestedDisabled}get isLocal(){return!1}setEnabled(e){!this.isManualOperationAllowed()||this.requestedDisabled===!e||(this.requestedDisabled=!e,this.emitTrackUpdate())}setVideoQuality(e){!this.isManualOperationAllowed()||this.requestedMaxQuality===e||(this.requestedMaxQuality=e,this.requestedVideoDimensions=void 0,this.emitTrackUpdate())}setVideoDimensions(e){this.isManualOperationAllowed()&&(this.requestedVideoDimensions?.width===e.width&&this.requestedVideoDimensions?.height===e.height||(Xu(this.track)&&(this.requestedVideoDimensions=e),this.requestedMaxQuality=void 0,this.emitTrackUpdate()))}setVideoFPS(e){this.isManualOperationAllowed()&&Xu(this.track)&&this.fps!==e&&(this.fps=e,this.emitTrackUpdate())}get videoQuality(){return this.requestedMaxQuality??ql.HIGH}setTrack(e){let t=this.subscriptionStatus,n=this.permissionStatus,r=this.track;r!==e&&(r&&(r.off(B.VideoDimensionsChanged,this.handleVideoDimensionsChange),r.off(B.VisibilityChanged,this.handleVisibilityChange),r.off(B.Ended,this.handleEnded),r.detach(),r.stopMonitor(),this.emit(B.Unsubscribed,r)),super.setTrack(e),e&&(e.sid=this.trackSid,e.on(B.VideoDimensionsChanged,this.handleVideoDimensionsChange),e.on(B.VisibilityChanged,this.handleVisibilityChange),e.on(B.Ended,this.handleEnded),this.emit(B.Subscribed,e)),this.emitPermissionUpdateIfChanged(n),this.emitSubscriptionUpdateIfChanged(t))}setAllowed(e){let t=this.subscriptionStatus,n=this.permissionStatus;this.allowed=e,this.emitPermissionUpdateIfChanged(n),this.emitSubscriptionUpdateIfChanged(t)}setSubscriptionError(e){this.emit(B.SubscriptionFailed,e)}updateInfo(e){super.updateInfo(e);let t=this.metadataMuted;this.metadataMuted=e.muted,this.track?this.track.setMuted(e.muted):t!==e.muted&&this.emit(e.muted?B.Muted:B.Unmuted)}emitSubscriptionUpdateIfChanged(e){let t=this.subscriptionStatus;e!==t&&this.emit(B.SubscriptionStatusChanged,t,e)}emitPermissionUpdateIfChanged(e){this.permissionStatus!==e&&this.emit(B.SubscriptionPermissionChanged,this.permissionStatus,e)}isManualOperationAllowed(){return this.isDesired?!0:(this.log.warn(`cannot update track settings when not subscribed`,this.logContext),!1)}get isAdaptiveStream(){return Xu(this.track)&&this.track.isAdaptiveStream}emitTrackUpdate(){let e=new No({trackSids:[this.trackSid],disabled:!this.isEnabled,fps:this.fps});if(this.kind===U.Kind.Video){let t=this.requestedVideoDimensions;if(this.videoDimensionsAdaptiveStream!==void 0)if(t)Ul(this.videoDimensionsAdaptiveStream,t)&&(this.log.debug(`using adaptive stream dimensions instead of requested`,Object.assign(Object.assign({},this.logContext),this.videoDimensionsAdaptiveStream)),t=this.videoDimensionsAdaptiveStream);else if(this.requestedMaxQuality!==void 0&&this.trackInfo){let e=Wl(this.trackInfo,this.requestedMaxQuality);e&&Ul(this.videoDimensionsAdaptiveStream,e)&&(this.log.debug(`using adaptive stream dimensions instead of max quality layer`,Object.assign(Object.assign({},this.logContext),this.videoDimensionsAdaptiveStream)),t=this.videoDimensionsAdaptiveStream)}else this.log.debug(`using adaptive stream dimensions`,Object.assign(Object.assign({},this.logContext),this.videoDimensionsAdaptiveStream)),t=this.videoDimensionsAdaptiveStream;t?(e.width=Math.ceil(t.width),e.height=Math.ceil(t.height)):this.requestedMaxQuality===void 0?(this.log.debug(`using default quality`,Object.assign(Object.assign({},this.logContext),{quality:ql.HIGH})),e.quality=ql.HIGH):(this.log.debug(`using requested max quality`,Object.assign(Object.assign({},this.logContext),{quality:this.requestedMaxQuality})),e.quality=this.requestedMaxQuality)}this.emit(B.UpdateSettings,e)}},ah=class e extends $m{static fromParticipantInfo(t,n,r){return new e(t,n.sid,n.identity,n.name,n.metadata,n.attributes,r,n.kind)}get logContext(){return Object.assign(Object.assign({},super.logContext),{remoteParticipantID:this.sid,remoteParticipant:this.identity})}constructor(e,t,n,r,i,a,o){let s=arguments.length>7&&arguments[7]!==void 0?arguments[7]:Ca.STANDARD;super(t,n||``,r,i,a,o,s),this.signalClient=e,this.trackPublications=new Map,this.audioTrackPublications=new Map,this.videoTrackPublications=new Map,this.dataTracks=new rh,this.volumeMap=new Map}addTrackPublication(e){super.addTrackPublication(e),e.on(B.UpdateSettings,t=>{this.log.debug(`send update settings`,Object.assign(Object.assign(Object.assign({},this.logContext),H(e)),{settings:t})),this.signalClient.sendUpdateTrackSettings(t)}),e.on(B.UpdateSubscription,e=>{e.participantTracks.forEach(e=>{e.participantSid=this.sid}),this.signalClient.sendUpdateSubscription(e)}),e.on(B.SubscriptionPermissionChanged,t=>{this.emit(R.TrackSubscriptionPermissionChanged,e,t)}),e.on(B.SubscriptionStatusChanged,t=>{this.emit(R.TrackSubscriptionStatusChanged,e,t)}),e.on(B.Subscribed,t=>{this.emit(R.TrackSubscribed,t,e)}),e.on(B.Unsubscribed,t=>{this.emit(R.TrackUnsubscribed,t,e)}),e.on(B.SubscriptionFailed,t=>{this.emit(R.TrackSubscriptionFailed,e.trackSid,t)})}getTrackPublication(e){let t=super.getTrackPublication(e);if(t)return t}getTrackPublicationByName(e){let t=super.getTrackPublicationByName(e);if(t)return t}setVolume(e){let t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:U.Source.Microphone;this.volumeMap.set(t,e);let n=this.getTrackPublication(t);n&&n.track&&n.track.setVolume(e)}getVolume(){let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:U.Source.Microphone,t=this.getTrackPublication(e);return t&&t.track?t.track.getVolume():this.volumeMap.get(e)}addSubscribedMediaTrack(e,t,n,r,i,a){let o=this.getTrackPublicationBySid(t);if(o||t.startsWith(`TR`)||this.trackPublications.forEach(t=>{!o&&e.kind===t.kind.toString()&&(o=t)}),!o){if(a===0){this.log.error(`could not find published track`,Object.assign(Object.assign({},this.logContext),{trackSid:t})),this.emit(R.TrackSubscriptionFailed,t);return}a===void 0&&(a=20),setTimeout(()=>{this.addSubscribedMediaTrack(e,t,n,r,i,a-1)},150);return}if(e.readyState===`ended`){this.log.error(`unable to subscribe because MediaStreamTrack is ended. Do not call MediaStreamTrack.stop()`,Object.assign(Object.assign({},this.logContext),H(o))),this.emit(R.TrackSubscriptionFailed,t);return}let s=e.kind===`video`,c;return c=s?new Um(e,t,r,i):new Vm(e,t,r,this.audioContext,this.audioOutput),c.source=o.source,c.isMuted=o.isMuted,c.setMediaStream(n),c.start(),o.setTrack(c),this.volumeMap.has(o.source)&&Ju(c)&&Wu(c)&&c.setVolume(this.volumeMap.get(o.source)),o}get hasMetadata(){return!!this.participantInfo}getTrackPublicationBySid(e){return this.trackPublications.get(e)}updateInfo(e){if(!super.updateInfo(e))return!1;let t=new Map,n=new Map;return e.tracks.forEach(e=>{let r=this.getTrackPublicationBySid(e.sid);if(r)r.updateInfo(e);else{let t=U.kindFromProto(e.type);if(!t)return;r=new ih(t,e,this.signalClient.connectOptions?.autoSubscribe,{loggerContextCb:()=>this.logContext,loggerName:this.loggerOptions?.loggerName}),r.updateInfo(e),n.set(e.sid,r);let i=Array.from(this.trackPublications.values()).find(e=>e.source===r?.source);i&&r.source!==U.Source.Unknown&&this.log.debug(`received a second track publication for ${this.identity} with the same source: ${r.source}`,Object.assign(Object.assign({},this.logContext),{oldTrack:H(i),newTrack:H(r)})),this.addTrackPublication(r)}t.set(e.sid,r)}),this.trackPublications.forEach(e=>{t.has(e.trackSid)||(this.log.trace(`detected removed track on remote participant, unpublishing`,Object.assign(Object.assign({},this.logContext),H(e))),this.unpublishTrack(e.trackSid,!0))}),n.forEach(e=>{this.emit(R.TrackPublished,e)}),!0}unpublishTrack(e,t){let n=this.trackPublications.get(e);if(!n)return;let{track:r}=n;switch(r&&(r.stop(),n.setTrack(void 0)),this.trackPublications.delete(e),n.kind){case U.Kind.Audio:this.audioTrackPublications.delete(e);break;case U.Kind.Video:this.videoTrackPublications.delete(e);break}t&&this.emit(R.TrackUnpublished,n)}setAudioOutput(e){return N(this,void 0,void 0,function*(){this.audioOutput=e;let t=[];this.audioTrackPublications.forEach(n=>{Wu(n.track)&&Ju(n.track)&&t.push(n.track.setSinkId(e.deviceId??`default`))}),yield Promise.all(t)})}addRemoteDataTrack(e){this.dataTracks.set(e.info.name,e)}removeRemoteDataTrack(e){for(let[t,n]of this.dataTracks.entries())e===n.info.sid&&this.dataTracks.delete(t)}emit(e){var t=[...arguments].slice(1);return this.log.trace(`participant event`,Object.assign(Object.assign({},this.logContext),{event:e,args:t})),super.emit(e,...t)}},Y;(function(e){e.Disconnected=`disconnected`,e.Connecting=`connecting`,e.Connected=`connected`,e.Reconnecting=`reconnecting`,e.SignalReconnecting=`signalReconnecting`})(Y||={});var oh=4*1e3,sh=class e extends Bs.EventEmitter{get hasE2EESetup(){return this.e2eeManager!==void 0}constructor(t){var n,r,i;if(super(),n=this,this.state=Y.Disconnected,this.activeSpeakers=[],this.isE2EEEnabled=!1,this.audioEnabled=!0,this.isVideoPlaybackBlocked=!1,this.log=M,this.bufferedEvents=[],this.isResuming=!1,this.rpcHandlers=new Map,this.connect=(e,t,n)=>N(this,void 0,void 0,function*(){if(!ou())throw gu()?Error(`WebRTC isn't detected, have you called registerGlobals?`):Error(`LiveKit doesn't seem to be supported on this browser. Try to update your browser and make sure no browser extensions are disabling webRTC.`);let r=yield this.disconnectLock.lock();if(this.state===Y.Connected)return this.log.info(`already connected to room ${this.name}`,this.logContext),r(),Promise.resolve();if(this.connectFuture)return r(),this.connectFuture.promise;this.setAndEmitConnectionState(Y.Connecting),this.regionUrlProvider?.getServerUrl().toString()!==id(e)&&(this.regionUrl=void 0,this.regionUrlProvider=void 0),_u(new URL(e))&&(this.regionUrlProvider===void 0?this.regionUrlProvider=new Ef(e,t):this.regionUrlProvider.updateToken(t),this.regionUrlProvider.fetchRegionSettings().then(e=>{var t;(t=this.regionUrlProvider)==null||t.setServerReportedRegions(e)}).catch(e=>{this.log.warn(`could not fetch region settings`,Object.assign(Object.assign({},this.logContext),{error:e}))}));let i=(a,o,s)=>N(this,void 0,void 0,function*(){this.abortController&&this.abortController.abort();let c=new AbortController;this.abortController=c,r?.();try{if(yield xd.getInstance().getBackOffPromise(e),c.signal.aborted)throw F.cancelled(`Connection attempt aborted`);yield this.attemptConnection(s??e,t,n,c),this.abortController=void 0,a()}catch(t){if(this.regionUrlProvider&&t instanceof F&&t.reason!==P.Cancelled&&t.reason!==P.NotAllowed){let n=null;try{this.log.debug(`Fetching next region`),n=yield this.regionUrlProvider.getNextBestRegionUrl(this.abortController?.signal)}catch(e){if(e instanceof F&&(e.status===401||e.reason===P.Cancelled)){this.handleDisconnect(this.options.stopLocalTrackOnUnpublish),o(e);return}}[P.InternalError,P.ServerUnreachable,P.Timeout].includes(t.reason)&&(this.log.debug(`Adding failed connection attempt to back off`),xd.getInstance().addFailedConnectionAttempt(e)),n&&!this.abortController?.signal.aborted?(this.log.info(`Initial connection failed with ConnectionError: ${t.message}. Retrying with another region: ${n}`,this.logContext),this.recreateEngine(!0),yield i(a,o,n)):(this.handleDisconnect(this.options.stopLocalTrackOnUnpublish,Bu(t)),o(t))}else{let e=ma.UNKNOWN_REASON;t instanceof F&&(e=Bu(t)),this.handleDisconnect(this.options.stopLocalTrackOnUnpublish,e),o(t)}}}),a=this.regionUrl;return this.regionUrl=void 0,this.connectFuture=new Nu((e,t)=>{i(e,t,a)},()=>{this.clearConnectionFutures()}),this.connectFuture.promise}),this.connectSignal=(e,t,n,r,i,a)=>N(this,void 0,void 0,function*(){let o=yield n.join(e,t,{autoSubscribe:r.autoSubscribe,adaptiveStream:typeof i.adaptiveStream==`object`?!0:i.adaptiveStream,maxRetries:r.maxRetries,e2eeEnabled:!!this.e2eeManager,websocketTimeout:r.websocketTimeout},a.signal,!i.singlePeerConnection),s=o.serverInfo;if(s||={version:o.serverVersion,region:o.serverRegion},this.serverInfo=s,this.log.debug(`connected to Livekit Server ${Object.entries(s).map(e=>{let[t,n]=e;return`${t}: ${n}`}).join(`, `)}`,{room:o.room?.name,roomSid:o.room?.sid,identity:o.participant?.identity}),!s.version)throw new ul(`unknown server version`);return s.version===`0.15.1`&&this.options.dynacast&&(this.log.debug(`disabling dynacast due to server version`,this.logContext),i.dynacast=!1),o}),this.applyJoinResponse=e=>{let t=e.participant;if(this.localParticipant.sid=t.sid,this.localParticipant.identity=t.identity,this.localParticipant.setEnabledPublishCodecs(e.enabledPublishCodecs),this.e2eeManager)try{this.e2eeManager.setSifTrailer(e.sifTrailer)}catch(e){this.log.error(e instanceof Error?e.message:`Could not set SifTrailer`,Object.assign(Object.assign({},this.logContext),{error:e}))}this.handleParticipantUpdates([t,...e.otherParticipants]),e.room&&this.handleRoomUpdate(e.room)},this.attemptConnection=(e,t,n,r)=>N(this,void 0,void 0,function*(){this.state===Y.Reconnecting||this.isResuming||this.engine?.pendingReconnect?(this.log.info(`Reconnection attempt replaced by new connection attempt`,this.logContext),this.recreateEngine(!0)):this.maybeCreateEngine(),this.regionUrlProvider?.isCloud()&&this.engine.setRegionUrlProvider(this.regionUrlProvider),this.acquireAudioContext(),this.connOptions=Object.assign(Object.assign({},Sf),n),this.connOptions.rtcConfig&&(this.engine.rtcConfig=this.connOptions.rtcConfig),this.connOptions.peerConnectionTimeout&&(this.engine.peerConnectionTimeout=this.connOptions.peerConnectionTimeout);try{let n=yield this.connectSignal(e,t,this.engine,this.connOptions,this.options,r);this.applyJoinResponse(n),this.setupLocalParticipantEvents(),this.emit(L.SignalConnected)}catch(e){yield this.engine.close(),this.recreateEngine();let t=r.signal.aborted?F.cancelled(`Signal connection aborted`):F.serverUnreachable(`could not establish signal connection`);throw e instanceof Error&&(t.message=`${t.message}: ${e.message}`),e instanceof F&&(t.reason=e.reason,t.status=e.status),this.log.debug(`error trying to establish signal connection`,Object.assign(Object.assign({},this.logContext),{error:e})),t}if(r.signal.aborted)throw yield this.engine.close(),this.recreateEngine(),F.cancelled(`Connection attempt aborted`);try{yield this.engine.waitForPCInitialConnection(this.connOptions.peerConnectionTimeout,r)}catch(e){throw yield this.engine.close(),this.recreateEngine(),e}hu()&&this.options.disconnectOnPageLeave&&(window.addEventListener(`pagehide`,this.onPageLeave),window.addEventListener(`beforeunload`,this.onPageLeave)),hu()&&window.addEventListener(`freeze`,this.onPageLeave),this.setAndEmitConnectionState(Y.Connected),this.emit(L.Connected),xd.getInstance().resetFailedConnectionAttempts(e),this.registerConnectionReconcile(),this.regionUrlProvider&&this.regionUrlProvider.notifyConnected()}),this.disconnect=function(){return N(n,[...[...arguments]],void 0,function(){var e=this;let t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:!0;return function*(){var n,r,i;let a=yield e.disconnectLock.lock();try{if(e.state===Y.Disconnected){e.log.debug(`already disconnected`,e.logContext);return}if(e.log.info(`disconnect from room`,Object.assign({},e.logContext)),e.state===Y.Connecting||e.state===Y.Reconnecting||e.isResuming){let t=`Abort connection attempt due to user initiated disconnect`;e.log.warn(t,e.logContext),(n=e.abortController)==null||n.abort(t),(i=(r=e.connectFuture)?.reject)==null||i.call(r,F.cancelled(`Client initiated disconnect`)),e.connectFuture=void 0}e.engine&&(e.engine.client.isDisconnected||(yield e.engine.client.sendLeave()),yield e.engine.close()),e.handleDisconnect(t,ma.CLIENT_INITIATED),e.engine=void 0}finally{a()}}()})},this.onPageLeave=()=>N(this,void 0,void 0,function*(){this.log.info(`Page leave detected, disconnecting`,this.logContext),yield this.disconnect()}),this.startAudio=()=>N(this,void 0,void 0,function*(){let e=[],t=tl();if(t&&t.os===`iOS`){let t=`livekit-dummy-audio-el`,n=document.getElementById(t);if(!n){n=document.createElement(`audio`),n.id=t,n.autoplay=!0,n.hidden=!0;let e=Mu();e.enabled=!0;let r=new MediaStream([e]);n.srcObject=r,document.addEventListener(`visibilitychange`,()=>{n&&(n.srcObject=document.hidden?null:r,document.hidden||(this.log.debug(`page visible again, triggering startAudio to resume playback and update playback status`,this.logContext),this.startAudio()))}),document.body.append(n),this.once(L.Disconnected,()=>{n?.remove(),n=null})}e.push(n)}this.remoteParticipants.forEach(t=>{t.audioTrackPublications.forEach(t=>{t.track&&t.track.attachedElements.forEach(t=>{e.push(t)})})});try{yield Promise.all([this.acquireAudioContext(),...e.map(e=>(e.muted=!1,e.play()))]),this.handleAudioPlaybackStarted()}catch(e){throw this.handleAudioPlaybackFailed(e),e}}),this.startVideo=()=>N(this,void 0,void 0,function*(){let e=[];for(let t of this.remoteParticipants.values())t.videoTrackPublications.forEach(t=>{var n;(n=t.track)==null||n.attachedElements.forEach(t=>{e.includes(t)||e.push(t)})});yield Promise.all(e.map(e=>e.play())).then(()=>{this.handleVideoPlaybackStarted()}).catch(e=>{e.name===`NotAllowedError`?this.handleVideoPlaybackFailed():this.log.warn("Resuming video playback failed, make sure you call `startVideo` directly in a user gesture handler",this.logContext)})}),this.handleRestarting=()=>{this.clearConnectionReconcile(),this.isResuming=!1;for(let e of this.remoteParticipants.values())this.handleParticipantDisconnected(e.identity,e);this.setAndEmitConnectionState(Y.Reconnecting)&&this.emit(L.Reconnecting)},this.handleRestarted=()=>{this.outgoingDataTrackManager.sfuWillRepublishTracks(),this.incomingDataTrackManager.resendSubscriptionUpdates()},this.handleSignalRestarted=e=>N(this,void 0,void 0,function*(){this.log.debug(`signal reconnected to server, region ${e.serverRegion}`,Object.assign(Object.assign({},this.logContext),{region:e.serverRegion})),this.bufferedEvents=[],this.applyJoinResponse(e);try{yield this.localParticipant.republishAllTracks(void 0,!0)}catch(e){this.log.error(`error trying to re-publish tracks after reconnection`,Object.assign(Object.assign({},this.logContext),{error:e}))}try{yield this.engine.waitForRestarted(),this.log.debug(`fully reconnected to server`,Object.assign(Object.assign({},this.logContext),{region:e.serverRegion}))}catch{return}this.setAndEmitConnectionState(Y.Connected),this.emit(L.Reconnected),this.registerConnectionReconcile(),this.emitBufferedEvents()}),this.handleParticipantUpdates=e=>{for(let t of e){if(t.identity===this.localParticipant.identity){this.localParticipant.updateInfo(t);continue}t.identity===``&&(t.identity=this.sidToIdentity.get(t.sid)??``);let e=this.remoteParticipants.get(t.identity);t.state===Sa.DISCONNECTED?this.handleParticipantDisconnected(t.identity,e):e=this.getOrCreateParticipant(t.identity,t)}let t=new Map(e.filter(e=>e.identity!==this.localParticipant.identity).map(e=>[e.identity,e.dataTracks.map(e=>Pd.from(e))]));this.incomingDataTrackManager.receiveSfuPublicationUpdates(t)},this.handleActiveSpeakersUpdate=e=>{let t=[],n={};e.forEach(e=>{if(n[e.sid]=!0,e.sid===this.localParticipant.sid)this.localParticipant.audioLevel=e.level,this.localParticipant.setIsSpeaking(!0),t.push(this.localParticipant);else{let n=this.getRemoteParticipantBySid(e.sid);n&&(n.audioLevel=e.level,n.setIsSpeaking(!0),t.push(n))}}),n[this.localParticipant.sid]||(this.localParticipant.audioLevel=0,this.localParticipant.setIsSpeaking(!1)),this.remoteParticipants.forEach(e=>{n[e.sid]||(e.audioLevel=0,e.setIsSpeaking(!1))}),this.activeSpeakers=t,this.emitWhenConnected(L.ActiveSpeakersChanged,t)},this.handleSpeakersChanged=e=>{let t=new Map;this.activeSpeakers.forEach(e=>{let n=this.remoteParticipants.get(e.identity);n&&n.sid!==e.sid||t.set(e.sid,e)}),e.forEach(e=>{let n=this.getRemoteParticipantBySid(e.sid);e.sid===this.localParticipant.sid&&(n=this.localParticipant),n&&(n.audioLevel=e.level,n.setIsSpeaking(e.active),e.active?t.set(e.sid,n):t.delete(e.sid))});let n=Array.from(t.values());n.sort((e,t)=>t.audioLevel-e.audioLevel),this.activeSpeakers=n,this.emitWhenConnected(L.ActiveSpeakersChanged,n)},this.handleStreamStateUpdate=e=>{e.streamStates.forEach(e=>{let t=this.getRemoteParticipantBySid(e.participantSid);if(!t)return;let n=t.getTrackPublicationBySid(e.trackSid);if(!n||!n.track)return;let r=U.streamStateFromProto(e.state);n.track.setStreamState(r),r!==n.track.streamState&&(t.emit(R.TrackStreamStateChanged,n,n.track.streamState),this.emitWhenConnected(L.TrackStreamStateChanged,n,n.track.streamState,t))})},this.handleSubscriptionPermissionUpdate=e=>{let t=this.getRemoteParticipantBySid(e.participantSid);if(!t)return;let n=t.getTrackPublicationBySid(e.trackSid);n&&n.setAllowed(e.allowed)},this.handleSubscriptionError=e=>{let t=Array.from(this.remoteParticipants.values()).find(t=>t.trackPublications.has(e.trackSid));if(!t)return;let n=t.getTrackPublicationBySid(e.trackSid);n&&n.setSubscriptionError(e.err)},this.handleDataPacket=(e,t)=>{let n=this.remoteParticipants.get(e.participantIdentity);if(e.value.case===`user`)this.handleUserPacket(n,e.value.value,e.kind,t);else if(e.value.case===`transcription`)this.handleTranscription(n,e.value.value);else if(e.value.case===`sipDtmf`)this.handleSipDtmf(n,e.value.value);else if(e.value.case===`chatMessage`)this.handleChatMessage(n,e.value.value);else if(e.value.case===`metrics`)this.handleMetrics(e.value.value,n);else if(e.value.case===`streamHeader`||e.value.case===`streamChunk`||e.value.case===`streamTrailer`)this.handleDataStream(e,t);else if(e.value.case===`rpcRequest`){let t=e.value.value;this.handleIncomingRpcRequest(e.participantIdentity,t.id,t.method,t.payload,t.responseTimeoutMs,t.version)}},this.handleUserPacket=(e,t,n,r)=>{this.emit(L.DataReceived,t.payload,e,n,t.topic,r),e?.emit(R.DataReceived,t.payload,n,r)},this.handleSipDtmf=(e,t)=>{this.emit(L.SipDTMFReceived,t,e),e?.emit(R.SipDTMFReceived,t)},this.handleTranscription=(e,t)=>{let n=t.transcribedParticipantIdentity===this.localParticipant.identity?this.localParticipant:this.getParticipantByIdentity(t.transcribedParticipantIdentity),r=n?.trackPublications.get(t.trackId),i=Ru(t,this.transcriptionReceivedTimes);r?.emit(B.TranscriptionReceived,i),n?.emit(R.TranscriptionReceived,i,r),this.emit(L.TranscriptionReceived,i,n,r)},this.handleChatMessage=(e,t)=>{let n=zu(t);this.emit(L.ChatMessage,n,e)},this.handleMetrics=(e,t)=>{this.emit(L.MetricsReceived,e,t)},this.handleDataStream=(e,t)=>{this.incomingDataStreamManager.handleDataStreamPacket(e,t)},this.bufferedSegments=new Map,this.handleAudioPlaybackStarted=()=>{this.canPlaybackAudio||(this.audioEnabled=!0,this.emit(L.AudioPlaybackStatusChanged,!0))},this.handleAudioPlaybackFailed=e=>{this.log.warn(`could not playback audio`,Object.assign(Object.assign({},this.logContext),{error:e})),this.canPlaybackAudio&&(this.audioEnabled=!1,this.emit(L.AudioPlaybackStatusChanged,!1))},this.handleVideoPlaybackStarted=()=>{this.isVideoPlaybackBlocked&&(this.isVideoPlaybackBlocked=!1,this.emit(L.VideoPlaybackStatusChanged,!0))},this.handleVideoPlaybackFailed=()=>{this.isVideoPlaybackBlocked||(this.isVideoPlaybackBlocked=!0,this.emit(L.VideoPlaybackStatusChanged,!1))},this.handleDeviceChange=()=>N(this,void 0,void 0,function*(){tl()?.os!==`iOS`&&(yield this.selectDefaultDevices()),this.emit(L.MediaDevicesChanged)}),this.handleRoomUpdate=e=>{let t=this.roomInfo;this.roomInfo=e,t&&t.metadata!==e.metadata&&this.emitWhenConnected(L.RoomMetadataChanged,e.metadata),t?.activeRecording!==e.activeRecording&&this.emitWhenConnected(L.RecordingStatusChanged,e.activeRecording)},this.handleConnectionQualityUpdate=e=>{e.updates.forEach(e=>{if(e.participantSid===this.localParticipant.sid){this.localParticipant.setConnectionQuality(e.quality);return}let t=this.getRemoteParticipantBySid(e.participantSid);t&&t.setConnectionQuality(e.quality)})},this.onLocalParticipantMetadataChanged=e=>{this.emit(L.ParticipantMetadataChanged,e,this.localParticipant)},this.onLocalParticipantNameChanged=e=>{this.emit(L.ParticipantNameChanged,e,this.localParticipant)},this.onLocalAttributesChanged=e=>{this.emit(L.ParticipantAttributesChanged,e,this.localParticipant)},this.onLocalTrackMuted=e=>{this.emit(L.TrackMuted,e,this.localParticipant)},this.onLocalTrackUnmuted=e=>{this.emit(L.TrackUnmuted,e,this.localParticipant)},this.onTrackProcessorUpdate=e=>{var t;(t=e?.onPublish)==null||t.call(e,this)},this.onLocalTrackPublished=e=>N(this,void 0,void 0,function*(){var t,n,r,i;(t=e.track)==null||t.on(B.TrackProcessorUpdate,this.onTrackProcessorUpdate),(n=e.track)==null||n.on(B.Restarted,this.onLocalTrackRestarted),(i=(r=e.track?.getProcessor())?.onPublish)==null||i.call(r,this),this.emit(L.LocalTrackPublished,e,this.localParticipant),qu(e.track)&&(yield e.track.checkForSilence())&&this.emit(L.LocalAudioSilenceDetected,e);let a=yield e.track?.getDeviceId(!1),o=Fl(e.source);o&&a&&a!==this.localParticipant.activeDeviceMap.get(o)&&(this.localParticipant.activeDeviceMap.set(o,a),this.emit(L.ActiveDeviceChanged,o,a))}),this.onLocalTrackUnpublished=e=>{var t,n;(t=e.track)==null||t.off(B.TrackProcessorUpdate,this.onTrackProcessorUpdate),(n=e.track)==null||n.off(B.Restarted,this.onLocalTrackRestarted),this.emit(L.LocalTrackUnpublished,e,this.localParticipant)},this.onLocalTrackRestarted=e=>N(this,void 0,void 0,function*(){let t=yield e.getDeviceId(!1),n=Fl(e.source);n&&t&&t!==this.localParticipant.activeDeviceMap.get(n)&&(this.log.debug(`local track restarted, setting ${n} ${t} active`,this.logContext),this.localParticipant.activeDeviceMap.set(n,t),this.emit(L.ActiveDeviceChanged,n,t))}),this.onLocalConnectionQualityChanged=e=>{this.emit(L.ConnectionQualityChanged,e,this.localParticipant)},this.onMediaDevicesError=(e,t)=>{this.emit(L.MediaDevicesError,e,t)},this.onLocalParticipantPermissionsChanged=e=>{this.emit(L.ParticipantPermissionsChanged,e,this.localParticipant)},this.onLocalChatMessageSent=e=>{this.emit(L.ChatMessage,e,this.localParticipant)},this.setMaxListeners(100),this.remoteParticipants=new Map,this.sidToIdentity=new Map,this.options=Object.assign(Object.assign({},xf),t),this.log=Es(this.options.loggerName??Ts.Room),this.transcriptionReceivedTimes=new Map,this.options.audioCaptureDefaults=Object.assign(Object.assign({},yf),t?.audioCaptureDefaults),this.options.videoCaptureDefaults=Object.assign(Object.assign({},bf),t?.videoCaptureDefaults),this.options.publishDefaults=Object.assign(Object.assign({},vf),t?.publishDefaults),this.maybeCreateEngine(),this.incomingDataStreamManager=new Ep,this.outgoingDataStreamManager=new jp(this.engine,this.log),this.incomingDataTrackManager=new wm({e2eeManager:this.e2eeManager}),this.incomingDataTrackManager.on(`sfuUpdateSubscription`,e=>{this.engine.client.sendUpdateDataSubscription(e.sid,e.subscribe)}).on(`trackPublished`,e=>{var t;e.track.publisherIdentity!==this.localParticipant.identity&&(this.emit(L.DataTrackPublished,e.track),(t=this.remoteParticipants.get(e.track.publisherIdentity))==null||t.addRemoteDataTrack(e.track))}).on(`trackUnpublished`,e=>{var t;e.publisherIdentity!==this.localParticipant.identity&&(this.emit(L.DataTrackUnpublished,e.sid),(t=this.remoteParticipants.get(e.publisherIdentity))==null||t.removeRemoteDataTrack(e.sid))}),this.outgoingDataTrackManager=new zm({e2eeManager:this.e2eeManager}),this.outgoingDataTrackManager.on(`sfuPublishRequest`,e=>{this.engine.client.sendPublishDataTrackRequest(e.handle,e.name,e.usesE2ee)}).on(`sfuUnpublishRequest`,e=>{this.engine.client.sendUnPublishDataTrackRequest(e.handle)}).on(`trackPublished`,e=>{this.emit(L.LocalDataTrackPublished,e.track)}).on(`trackUnpublished`,e=>{this.emit(L.LocalDataTrackUnpublished,e.sid)}).on(`packetAvailable`,e=>{let{bytes:t}=e;this.engine.sendLossyBytes(t,K.DATA_TRACK_LOSSY,`wait`)}),this.disconnectLock=new ur,this.localParticipant=new th(``,``,this.engine,this.options,this.rpcHandlers,this.outgoingDataStreamManager,this.outgoingDataTrackManager),(this.options.e2ee||this.options.encryption)&&this.setupE2EE(),this.engine.e2eeManager=this.e2eeManager,this.incomingDataTrackManager.updateE2eeManager(this.e2eeManager??null),this.outgoingDataTrackManager.updateE2eeManager(this.e2eeManager??null),this.options.videoCaptureDefaults.deviceId&&this.localParticipant.activeDeviceMap.set(`videoinput`,Fu(this.options.videoCaptureDefaults.deviceId)),this.options.audioCaptureDefaults.deviceId&&this.localParticipant.activeDeviceMap.set(`audioinput`,Fu(this.options.audioCaptureDefaults.deviceId)),this.options.audioOutput?.deviceId&&this.switchActiveDevice(`audiooutput`,Fu(this.options.audioOutput.deviceId)).catch(e=>this.log.warn(`Could not set audio output: ${e.message}`,this.logContext)),hu()){let t=new AbortController;(i=(r=navigator.mediaDevices)?.addEventListener)==null||i.call(r,`devicechange`,this.handleDeviceChange,{signal:t.signal}),e.cleanupRegistry&&e.cleanupRegistry.register(this,()=>{t.abort()})}}registerTextStreamHandler(e,t){return this.incomingDataStreamManager.registerTextStreamHandler(e,t)}unregisterTextStreamHandler(e){return this.incomingDataStreamManager.unregisterTextStreamHandler(e)}registerByteStreamHandler(e,t){return this.incomingDataStreamManager.registerByteStreamHandler(e,t)}unregisterByteStreamHandler(e){return this.incomingDataStreamManager.unregisterByteStreamHandler(e)}registerRpcMethod(e,t){if(this.rpcHandlers.has(e))throw Error(`RPC handler already registered for method ${e}, unregisterRpcMethod before trying to register again`);this.rpcHandlers.set(e,t)}unregisterRpcMethod(e){this.rpcHandlers.delete(e)}setE2EEEnabled(e){return N(this,void 0,void 0,function*(){if(this.e2eeManager)yield Promise.all([this.localParticipant.setE2EEEnabled(e)]),this.localParticipant.identity!==``&&this.e2eeManager.setParticipantCryptorEnabled(e,this.localParticipant.identity);else throw Error(`e2ee not configured, please set e2ee settings within the room options`)})}setupE2EE(){var e;let t=!!this.options.encryption,n=this.options.encryption||this.options.e2ee;n&&(`e2eeManager`in n?(this.e2eeManager=n.e2eeManager,this.e2eeManager.isDataChannelEncryptionEnabled=t):this.e2eeManager=new vd(n,t),this.e2eeManager.on(dd.ParticipantEncryptionStatusChanged,(e,t)=>{Zu(t)&&(this.isE2EEEnabled=e),this.emit(L.ParticipantEncryptionStatusChanged,e,t)}),this.e2eeManager.on(dd.EncryptionError,(e,t)=>{let n=t?this.getParticipantByIdentity(t):void 0;this.emit(L.EncryptionError,e,n)}),(e=this.e2eeManager)==null||e.setup(this))}get logContext(){return{room:this.name,roomID:this.roomInfo?.sid,participant:this.localParticipant.identity,participantID:this.localParticipant.sid}}get isRecording(){return this.roomInfo?.activeRecording??!1}getSid(){return this.state===Y.Disconnected?Qc.resolve(``):this.roomInfo&&this.roomInfo.sid!==``?Qc.resolve(this.roomInfo.sid):new Qc((e,t)=>{let n=t=>{t.sid!==``&&(this.engine.off(z.RoomUpdate,n),e(t.sid))};this.engine.on(z.RoomUpdate,n),this.once(L.Disconnected,()=>{this.engine.off(z.RoomUpdate,n),t(new I(`Room disconnected before room server id was available`))})})}get name(){return this.roomInfo?.name??``}get metadata(){return this.roomInfo?.metadata}get numParticipants(){return this.roomInfo?.numParticipants??0}get numPublishers(){return this.roomInfo?.numPublishers??0}maybeCreateEngine(){this.engine&&(this.engine.isNewlyCreated||!this.engine.isClosed)||(this.engine=new xp(this.options),this.engine.e2eeManager=this.e2eeManager,this.engine.on(z.ParticipantUpdate,this.handleParticipantUpdates).on(z.RoomUpdate,this.handleRoomUpdate).on(z.SpeakersChanged,this.handleSpeakersChanged).on(z.StreamStateChanged,this.handleStreamStateUpdate).on(z.ConnectionQualityUpdate,this.handleConnectionQualityUpdate).on(z.SubscriptionError,this.handleSubscriptionError).on(z.SubscriptionPermissionUpdate,this.handleSubscriptionPermissionUpdate).on(z.MediaTrackAdded,(e,t,n)=>{this.onTrackAdded(e,t,n)}).on(z.Disconnected,e=>{this.handleDisconnect(this.options.stopLocalTrackOnUnpublish,e)}).on(z.ActiveSpeakersUpdate,this.handleActiveSpeakersUpdate).on(z.DataPacketReceived,this.handleDataPacket).on(z.Resuming,()=>{this.clearConnectionReconcile(),this.isResuming=!0,this.log.info(`Resuming signal connection`,this.logContext),this.setAndEmitConnectionState(Y.SignalReconnecting)&&this.emit(L.SignalReconnecting)}).on(z.Resumed,()=>{this.registerConnectionReconcile(),this.isResuming=!1,this.log.info(`Resumed signal connection`,this.logContext),this.updateSubscriptions(),this.emitBufferedEvents(),this.setAndEmitConnectionState(Y.Connected)&&this.emit(L.Reconnected)}).on(z.SignalResumed,()=>{this.bufferedEvents=[],(this.state===Y.Reconnecting||this.isResuming)&&this.sendSyncState()}).on(z.Restarting,this.handleRestarting).on(z.Restarted,this.handleRestarted).on(z.SignalRestarted,this.handleSignalRestarted).on(z.Offline,()=>{this.setAndEmitConnectionState(Y.Reconnecting)&&this.emit(L.Reconnecting)}).on(z.DCBufferStatusChanged,(e,t)=>{this.emit(L.DCBufferStatusChanged,e,t)}).on(z.LocalTrackSubscribed,e=>{let t=this.localParticipant.getTrackPublications().find(t=>{let{trackSid:n}=t;return n===e});if(!t){this.log.warn(`could not find local track subscription for subscribed event`,this.logContext);return}this.localParticipant.emit(R.LocalTrackSubscribed,t),this.emitWhenConnected(L.LocalTrackSubscribed,t,this.localParticipant)}).on(z.RoomMoved,e=>{this.log.debug(`room moved`,e),e.room&&this.handleRoomUpdate(e.room),this.remoteParticipants.forEach((e,t)=>{this.handleParticipantDisconnected(t,e)}),this.emit(L.Moved,e.room.name),e.participant?this.handleParticipantUpdates([e.participant,...e.otherParticipants]):this.handleParticipantUpdates(e.otherParticipants)}).on(z.PublishDataTrackResponse,e=>{if(!e.info){this.log.warn(`received PublishDataTrackResponse, but event.info was ${e.info}, so skipping.`,this.logContext);return}this.outgoingDataTrackManager.receivedSfuPublishResponse(e.info.pubHandle,{type:`ok`,data:{sid:e.info.sid,pubHandle:e.info.pubHandle,name:e.info.name,usesE2ee:e.info.encryption!==j.NONE}})}).on(z.UnPublishDataTrackResponse,e=>{if(!e.info){this.log.warn(`received UnPublishDataTrackResponse, but event.info was ${e.info}, so skipping.`,this.logContext);return}this.outgoingDataTrackManager.receivedSfuUnpublishResponse(e.info.pubHandle)}).on(z.DataTrackSubscriberHandles,e=>{let t=new Map(Object.entries(e.subHandles).map(e=>{let[t,n]=e;return[parseInt(t,10),n.trackSid]}));this.incomingDataTrackManager.receivedSfuSubscriberHandles(t)}).on(z.DataTrackPacketReceived,e=>{try{this.incomingDataTrackManager.packetReceived(e)}catch(e){throw e}}).on(z.Joined,e=>{let t=new Map(e.otherParticipants.map(e=>[e.identity,e.dataTracks.map(e=>Pd.from(e))]));this.incomingDataTrackManager.receiveSfuPublicationUpdates(t)}),this.localParticipant&&this.localParticipant.setupEngine(this.engine),this.e2eeManager&&this.e2eeManager.setupEngine(this.engine),this.outgoingDataStreamManager&&this.outgoingDataStreamManager.setupEngine(this.engine))}static getLocalDevices(e){let t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:!0;return Cd.getInstance().getDevices(e,t)}prepareConnection(e,t){return N(this,void 0,void 0,function*(){if(this.state===Y.Disconnected){this.log.debug(`prepareConnection to ${e}`,this.logContext);try{if(_u(new URL(e))&&t){this.regionUrlProvider=new Ef(e,t);let n=yield this.regionUrlProvider.getNextBestRegionUrl();n&&this.state===Y.Disconnected&&(this.regionUrl=n,yield fetch(Lu(n),{method:`HEAD`}),this.log.debug(`prepared connection to ${n}`,this.logContext))}else yield fetch(Lu(e),{method:`HEAD`})}catch(e){this.log.warn(`could not prepare connection`,Object.assign(Object.assign({},this.logContext),{error:e}))}}})}getParticipantByIdentity(e){return this.localParticipant.identity===e?this.localParticipant:this.remoteParticipants.get(e)}clearConnectionFutures(){this.connectFuture=void 0}simulateScenario(e,t){return N(this,void 0,void 0,function*(){let n=()=>N(this,void 0,void 0,function*(){}),r;switch(e){case`signal-reconnect`:yield this.engine.client.handleOnClose(`simulate disconnect`);break;case`speaker`:r=new is({scenario:{case:`speakerUpdate`,value:3}});break;case`node-failure`:r=new is({scenario:{case:`nodeFailure`,value:!0}});break;case`server-leave`:r=new is({scenario:{case:`serverLeave`,value:!0}});break;case`migration`:r=new is({scenario:{case:`migration`,value:!0}});break;case`resume-reconnect`:this.engine.failNext(),yield this.engine.client.handleOnClose(`simulate resume-disconnect`);break;case`disconnect-signal-on-resume`:n=()=>N(this,void 0,void 0,function*(){yield this.engine.client.handleOnClose(`simulate resume-disconnect`)}),r=new is({scenario:{case:`disconnectSignalOnResume`,value:!0}});break;case`disconnect-signal-on-resume-no-messages`:n=()=>N(this,void 0,void 0,function*(){yield this.engine.client.handleOnClose(`simulate resume-disconnect`)}),r=new is({scenario:{case:`disconnectSignalOnResumeNoMessages`,value:!0}});break;case`full-reconnect`:this.engine.fullReconnectOnNext=!0,yield this.engine.client.handleOnClose(`simulate full-reconnect`);break;case`force-tcp`:case`force-tls`:r=new is({scenario:{case:`switchCandidateProtocol`,value:e===`force-tls`?2:1}}),n=()=>N(this,void 0,void 0,function*(){let e=this.engine.client.onLeave;e&&e(new Io({reason:ma.CLIENT_INITIATED,action:Lo.RECONNECT}))});break;case`subscriber-bandwidth`:if(t===void 0||typeof t!=`number`)throw Error(`subscriber-bandwidth requires a number as argument`);r=new is({scenario:{case:`subscriberBandwidth`,value:Hu(t)}});break;case`leave-full-reconnect`:r=new is({scenario:{case:`leaveRequestFullReconnect`,value:!0}})}r&&(yield this.engine.client.sendSimulateScenario(r),yield n())})}get canPlaybackAudio(){return this.audioEnabled}get canPlaybackVideo(){return!this.isVideoPlaybackBlocked}getActiveDevice(e){return this.localParticipant.activeDeviceMap.get(e)}switchActiveDevice(e,t){return N(this,arguments,void 0,function(e,t){var n=this;let r=arguments.length>2&&arguments[2]!==void 0?arguments[2]:!0;return function*(){var i,a;let o=!0,s=!1,c=r?{exact:t}:t;if(e===`audioinput`){s=n.localParticipant.audioTrackPublications.size===0;let t=n.getActiveDevice(e)??n.options.audioCaptureDefaults.deviceId;n.options.audioCaptureDefaults.deviceId=c;let r=Array.from(n.localParticipant.audioTrackPublications.values()).filter(e=>e.source===U.Source.Microphone);try{o=(yield Promise.all(r.map(e=>e.audioTrack?.setDeviceId(c)))).every(e=>e===!0)}catch(e){throw n.options.audioCaptureDefaults.deviceId=t,e}let i=r.some(e=>e.track?.isMuted??!1);o&&i&&(s=!0)}else if(e===`videoinput`){s=n.localParticipant.videoTrackPublications.size===0;let t=n.getActiveDevice(e)??n.options.videoCaptureDefaults.deviceId;n.options.videoCaptureDefaults.deviceId=c;let r=Array.from(n.localParticipant.videoTrackPublications.values()).filter(e=>e.source===U.Source.Camera);try{o=(yield Promise.all(r.map(e=>e.videoTrack?.setDeviceId(c)))).every(e=>e===!0)}catch(e){throw n.options.videoCaptureDefaults.deviceId=t,e}let i=r.some(e=>e.track?.isMuted??!1);o&&i&&(s=!0)}else if(e===`audiooutput`){if(s=!0,!au()&&!n.options.webAudioMix||n.options.webAudioMix&&n.audioContext&&!(`setSinkId`in n.audioContext))throw Error(`cannot switch audio output, the current browser does not support it`);n.options.webAudioMix&&(t=(yield Cd.getInstance().normalizeDeviceId(`audiooutput`,t))??``),(a=n.options).audioOutput??(a.audioOutput={});let r=n.getActiveDevice(e)??n.options.audioOutput.deviceId;n.options.audioOutput.deviceId=t;try{n.options.webAudioMix&&((i=n.audioContext)==null||i.setSinkId(t)),yield Promise.all(Array.from(n.remoteParticipants.values()).map(e=>e.setAudioOutput({deviceId:t})))}catch(e){throw n.options.audioOutput.deviceId=r,e}}return s&&(n.localParticipant.activeDeviceMap.set(e,t),n.emit(L.ActiveDeviceChanged,e,t)),o}()})}setupLocalParticipantEvents(){this.localParticipant.on(R.ParticipantMetadataChanged,this.onLocalParticipantMetadataChanged).on(R.ParticipantNameChanged,this.onLocalParticipantNameChanged).on(R.AttributesChanged,this.onLocalAttributesChanged).on(R.TrackMuted,this.onLocalTrackMuted).on(R.TrackUnmuted,this.onLocalTrackUnmuted).on(R.LocalTrackPublished,this.onLocalTrackPublished).on(R.LocalTrackUnpublished,this.onLocalTrackUnpublished).on(R.ConnectionQualityChanged,this.onLocalConnectionQualityChanged).on(R.MediaDevicesError,this.onMediaDevicesError).on(R.AudioStreamAcquired,this.startAudio).on(R.ChatMessage,this.onLocalChatMessageSent).on(R.ParticipantPermissionsChanged,this.onLocalParticipantPermissionsChanged)}recreateEngine(e){let t=this.engine;e&&t&&!t.client.isDisconnected?t.client.sendLeave().finally(()=>t.close()):t?.close(),this.engine=void 0,this.isResuming=!1,this.remoteParticipants.clear(),this.sidToIdentity.clear(),this.bufferedEvents=[],this.maybeCreateEngine()}onTrackAdded(e,t,n){if(this.state===Y.Connecting||this.state===Y.Reconnecting){let r=()=>{this.log.debug(`deferring on track for later`,{mediaTrackId:e.id,mediaStreamId:t.id,tracksInStream:t.getTracks().map(e=>e.id)}),this.onTrackAdded(e,t,n),i()},i=()=>{this.off(L.Reconnected,r),this.off(L.Connected,r),this.off(L.Disconnected,i)};this.once(L.Reconnected,r),this.once(L.Connected,r),this.once(L.Disconnected,i);return}if(this.state===Y.Disconnected){this.log.warn(`skipping incoming track after Room disconnected`,this.logContext);return}if(e.readyState===`ended`){this.log.info(`skipping incoming track as it already ended`,this.logContext);return}let r=Ql(t.id),i=r[0],a=r[1],o=e.id;if(a&&a.startsWith(`TR`)&&(o=a),i===this.localParticipant.sid){this.log.warn(`tried to create RemoteParticipant for local participant`,this.logContext);return}let s=Array.from(this.remoteParticipants.values()).find(e=>e.sid===i);if(!s){i.startsWith(`PA`)&&this.log.error(`Tried to add a track for a participant, that's not present. Sid: ${i}`,this.logContext);return}if(!o.startsWith(`TR`)){let e=this.engine.getTrackIdForReceiver(n);if(!e){this.log.error(`Tried to add a track whose 'sid' could not be found for a participant, that's not present. Sid: ${i}`,this.logContext);return}o=e}o.startsWith(`TR`)||this.log.warn(`Tried to add a track whose 'sid' could not be determined for a participant, that's not present. Sid: ${i}, streamId: ${a}, trackId: ${o}`,Object.assign(Object.assign({},this.logContext),{remoteParticipantID:i,streamId:a,trackId:o}));let c;this.options.adaptiveStream&&(c=typeof this.options.adaptiveStream==`object`?this.options.adaptiveStream:{});let l=s.addSubscribedMediaTrack(e,o,t,n,c);l?.isEncrypted&&!this.e2eeManager&&this.emit(L.EncryptionError,Error(`Encrypted ${l.source} track received from participant ${s.sid}, but room does not have encryption enabled!`))}handleDisconnect(){let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:!0,t=arguments.length>1?arguments[1]:void 0;var n,r;if(this.clearConnectionReconcile(),this.isResuming=!1,this.bufferedEvents=[],this.transcriptionReceivedTimes.clear(),this.incomingDataStreamManager.clearControllers(),this.state!==Y.Disconnected){this.regionUrl=void 0,this.regionUrlProvider&&this.regionUrlProvider.notifyDisconnected();try{this.remoteParticipants.forEach(e=>{e.trackPublications.forEach(t=>{e.unpublishTrack(t.trackSid)})}),this.localParticipant.trackPublications.forEach(t=>{var n,r,i;t.track&&this.localParticipant.unpublishTrack(t.track,e),e?((n=t.track)==null||n.detach(),(r=t.track)==null||r.stop()):(i=t.track)==null||i.stopMonitor()}),this.localParticipant.off(R.ParticipantMetadataChanged,this.onLocalParticipantMetadataChanged).off(R.ParticipantNameChanged,this.onLocalParticipantNameChanged).off(R.AttributesChanged,this.onLocalAttributesChanged).off(R.TrackMuted,this.onLocalTrackMuted).off(R.TrackUnmuted,this.onLocalTrackUnmuted).off(R.LocalTrackPublished,this.onLocalTrackPublished).off(R.LocalTrackUnpublished,this.onLocalTrackUnpublished).off(R.ConnectionQualityChanged,this.onLocalConnectionQualityChanged).off(R.MediaDevicesError,this.onMediaDevicesError).off(R.AudioStreamAcquired,this.startAudio).off(R.ChatMessage,this.onLocalChatMessageSent).off(R.ParticipantPermissionsChanged,this.onLocalParticipantPermissionsChanged),this.localParticipant.trackPublications.clear(),this.localParticipant.videoTrackPublications.clear(),this.localParticipant.audioTrackPublications.clear(),this.remoteParticipants.clear(),this.sidToIdentity.clear(),this.activeSpeakers=[],this.audioContext&&typeof this.options.webAudioMix==`boolean`&&(this.audioContext.close(),this.audioContext=void 0),hu()&&(window.removeEventListener(`beforeunload`,this.onPageLeave),window.removeEventListener(`pagehide`,this.onPageLeave),window.removeEventListener(`freeze`,this.onPageLeave),(r=(n=navigator.mediaDevices)?.removeEventListener)==null||r.call(n,`devicechange`,this.handleDeviceChange))}finally{this.setAndEmitConnectionState(Y.Disconnected),this.emit(L.Disconnected,t)}}}handleParticipantDisconnected(e,t){var n;this.remoteParticipants.delete(e),t&&(this.incomingDataStreamManager.validateParticipantHasNoActiveDataStreams(e),this.incomingDataTrackManager.handleRemoteParticipantDisconnected(e),t.trackPublications.forEach(e=>{t.unpublishTrack(e.trackSid,!0)}),this.emit(L.ParticipantDisconnected,t),t.setDisconnected(),(n=this.localParticipant)==null||n.handleParticipantDisconnected(t.identity))}handleIncomingRpcRequest(e,t,n,r,i,a){return N(this,void 0,void 0,function*(){if(yield this.engine.publishRpcAck(e,t),a!==1){yield this.engine.publishRpcResponse(e,t,null,Of.builtIn(`UNSUPPORTED_VERSION`));return}let o=this.rpcHandlers.get(n);if(!o){yield this.engine.publishRpcResponse(e,t,null,Of.builtIn(`UNSUPPORTED_METHOD`));return}let s=null,c=null;try{let a=yield o({requestId:t,callerIdentity:e,payload:r,responseTimeout:i});Af(a)>kf?(s=Of.builtIn(`RESPONSE_PAYLOAD_TOO_LARGE`),this.log.warn(`RPC Response payload too large for ${n}`)):c=a}catch(e){e instanceof Of?s=e:(this.log.warn(`Uncaught error returned by RPC handler for ${n}. Returning APPLICATION_ERROR instead.`,e),s=Of.builtIn(`APPLICATION_ERROR`))}yield this.engine.publishRpcResponse(e,t,c,s)})}selectDefaultDevices(){return N(this,void 0,void 0,function*(){let e=Cd.getInstance().previousDevices,t=yield Cd.getInstance().getDevices(void 0,!1),n=tl();if(n?.name===`Chrome`&&n.os!==`iOS`)for(let n of t){let t=e.find(e=>e.deviceId===n.deviceId);t&&t.label!==``&&t.kind===n.kind&&t.label!==n.label&&this.getActiveDevice(n.kind)===`default`&&this.emit(L.ActiveDeviceChanged,n.kind,n.deviceId)}for(let n of[`audiooutput`,`audioinput`,`videoinput`]){let r=Pl(n),i=this.localParticipant.getTrackPublication(r);if(i&&i.track?.isUserProvided)continue;let a=t.filter(e=>e.kind===n),o=this.getActiveDevice(n);if(o===e.filter(e=>e.kind===n)[0]?.deviceId&&a.length>0&&a[0]?.deviceId!==o){yield this.switchActiveDevice(n,a[0].deviceId);continue}n===`audioinput`&&!uu()||n===`videoinput`||a.length>0&&!a.find(e=>e.deviceId===this.getActiveDevice(n))&&(n!==`audiooutput`||!uu())&&(yield this.switchActiveDevice(n,a[0].deviceId))}})}acquireAudioContext(){return N(this,void 0,void 0,function*(){if(typeof this.options.webAudioMix!=`boolean`&&this.options.webAudioMix.audioContext?this.audioContext=this.options.webAudioMix.audioContext:(!this.audioContext||this.audioContext.state===`closed`)&&(this.audioContext=Nl()??void 0),this.options.webAudioMix&&this.remoteParticipants.forEach(e=>e.setAudioContext(this.audioContext)),this.localParticipant.setAudioContext(this.audioContext),this.audioContext&&this.audioContext.state===`suspended`)try{yield Promise.race([this.audioContext.resume(),$l(200)])}catch(e){this.log.warn(`Could not resume audio context`,Object.assign(Object.assign({},this.logContext),{error:e}))}let e=this.audioContext?.state===`running`;e!==this.canPlaybackAudio&&(this.audioEnabled=e,this.emit(L.AudioPlaybackStatusChanged,e))})}createParticipant(e,t){let n;return n=t?ah.fromParticipantInfo(this.engine.client,t,{loggerContextCb:()=>this.logContext,loggerName:this.options.loggerName}):new ah(this.engine.client,``,e,void 0,void 0,void 0,{loggerContextCb:()=>this.logContext,loggerName:this.options.loggerName}),this.options.webAudioMix&&n.setAudioContext(this.audioContext),this.options.audioOutput?.deviceId&&n.setAudioOutput(this.options.audioOutput).catch(e=>this.log.warn(`Could not set audio output: ${e.message}`,this.logContext)),n}getOrCreateParticipant(e,t){if(this.remoteParticipants.has(e)){let n=this.remoteParticipants.get(e);return t&&n.updateInfo(t)&&this.sidToIdentity.set(t.sid,t.identity),n}let n=this.createParticipant(e,t);return this.remoteParticipants.set(e,n),this.sidToIdentity.set(t.sid,t.identity),this.emitWhenConnected(L.ParticipantConnected,n),n.on(R.TrackPublished,e=>{this.emitWhenConnected(L.TrackPublished,e,n)}).on(R.TrackSubscribed,(e,t)=>{e.kind===U.Kind.Audio?(e.on(B.AudioPlaybackStarted,this.handleAudioPlaybackStarted),e.on(B.AudioPlaybackFailed,this.handleAudioPlaybackFailed)):e.kind===U.Kind.Video&&(e.on(B.VideoPlaybackFailed,this.handleVideoPlaybackFailed),e.on(B.VideoPlaybackStarted,this.handleVideoPlaybackStarted)),this.emitWhenConnected(L.TrackSubscribed,e,t,n)}).on(R.TrackUnpublished,e=>{this.emit(L.TrackUnpublished,e,n)}).on(R.TrackUnsubscribed,(e,t)=>{this.emit(L.TrackUnsubscribed,e,t,n)}).on(R.TrackMuted,e=>{this.emitWhenConnected(L.TrackMuted,e,n)}).on(R.TrackUnmuted,e=>{this.emitWhenConnected(L.TrackUnmuted,e,n)}).on(R.ParticipantMetadataChanged,e=>{this.emitWhenConnected(L.ParticipantMetadataChanged,e,n)}).on(R.ParticipantNameChanged,e=>{this.emitWhenConnected(L.ParticipantNameChanged,e,n)}).on(R.AttributesChanged,e=>{this.emitWhenConnected(L.ParticipantAttributesChanged,e,n)}).on(R.ConnectionQualityChanged,e=>{this.emitWhenConnected(L.ConnectionQualityChanged,e,n)}).on(R.ParticipantPermissionsChanged,e=>{this.emitWhenConnected(L.ParticipantPermissionsChanged,e,n)}).on(R.TrackSubscriptionStatusChanged,(e,t)=>{this.emitWhenConnected(L.TrackSubscriptionStatusChanged,e,t,n)}).on(R.TrackSubscriptionFailed,(e,t)=>{this.emit(L.TrackSubscriptionFailed,e,n,t)}).on(R.TrackSubscriptionPermissionChanged,(e,t)=>{this.emitWhenConnected(L.TrackSubscriptionPermissionChanged,e,t,n)}).on(R.Active,()=>{this.emitWhenConnected(L.ParticipantActive,n),n.kind===Ca.AGENT&&this.localParticipant.setActiveAgent(n)}),t&&n.updateInfo(t),n}sendSyncState(){let e=Array.from(this.remoteParticipants.values()).reduce((e,t)=>(e.push(...t.getTrackPublications()),e),[]),t=this.localParticipant.getTrackPublications(),n=this.outgoingDataTrackManager.queryPublished();this.engine.sendSyncState(e,t,n)}updateSubscriptions(){for(let e of this.remoteParticipants.values())for(let t of e.videoTrackPublications.values())t.isSubscribed&&Yu(t)&&t.emitTrackUpdate()}getRemoteParticipantBySid(e){let t=this.sidToIdentity.get(e);if(t)return this.remoteParticipants.get(t)}registerConnectionReconcile(){this.clearConnectionReconcile();let e=0;this.connectionReconcileInterval=vl.setInterval(()=>{!this.engine||this.engine.isClosed||!this.engine.verifyTransport()?(e++,this.log.warn(`detected connection state mismatch`,Object.assign(Object.assign({},this.logContext),{numFailures:e,engine:this.engine?{closed:this.engine.isClosed,transportsConnectedOrConnecting:this.engine.verifyTransport()}:void 0})),e>=3&&(this.recreateEngine(),this.handleDisconnect(this.options.stopLocalTrackOnUnpublish,ma.STATE_MISMATCH))):e=0},oh)}clearConnectionReconcile(){this.connectionReconcileInterval&&vl.clearInterval(this.connectionReconcileInterval)}setAndEmitConnectionState(e){return e===this.state?!1:(this.state=e,this.emit(L.ConnectionStateChanged,this.state),!0)}emitBufferedEvents(){this.bufferedEvents.forEach(e=>{let[t,n]=e;this.emit(t,...n)}),this.bufferedEvents=[]}emitWhenConnected(e){var t=[...arguments].slice(1);if(this.state===Y.Reconnecting||this.isResuming||!this.engine||this.engine.pendingReconnect)this.bufferedEvents.push([e,t]);else if(this.state===Y.Connected)return this.emit(e,...t);return!1}simulateParticipants(e){return N(this,void 0,void 0,function*(){let t=Object.assign({audio:!0,video:!0,useRealTracks:!1},e.publish),n=Object.assign({count:9,audio:!1,video:!0,aspectRatios:[1.66,1.7,1.3]},e.participants);if(this.handleDisconnect(),this.roomInfo=new va({sid:`RM_SIMULATED`,name:`simulated-room`,emptyTimeout:0,maxParticipants:0,creationTime:O.parse(new Date().getTime()),metadata:``,numParticipants:1,numPublishers:1,turnPassword:``,enabledCodecs:[],activeRecording:!1}),this.localParticipant.updateInfo(new xa({identity:`simulated-local`,name:`local-name`})),this.setupLocalParticipantEvents(),this.emit(L.SignalConnected),this.emit(L.Connected),this.setAndEmitConnectionState(Y.Connected),t.video){let e=new Jm(U.Kind.Video,new Ea({source:ua.CAMERA,sid:Math.floor(Math.random()*1e4).toString(),type:la.AUDIO,name:`video-dummy`}),new op(t.useRealTracks&&window.navigator.mediaDevices?.getUserMedia?(yield window.navigator.mediaDevices.getUserMedia({video:!0})).getVideoTracks()[0]:Au(160*(n.aspectRatios[0]??1),160,!0,!0),void 0,!1,{loggerName:this.options.loggerName,loggerContextCb:()=>this.logContext}),{loggerName:this.options.loggerName,loggerContextCb:()=>this.logContext});this.localParticipant.addTrackPublication(e),this.localParticipant.emit(R.LocalTrackPublished,e)}if(t.audio){let e=new Jm(U.Kind.Audio,new Ea({source:ua.MICROPHONE,sid:Math.floor(Math.random()*1e4).toString(),type:la.AUDIO}),new Vf(t.useRealTracks&&navigator.mediaDevices?.getUserMedia?(yield navigator.mediaDevices.getUserMedia({audio:!0})).getAudioTracks()[0]:Mu(),void 0,!1,this.audioContext,{loggerName:this.options.loggerName,loggerContextCb:()=>this.logContext}),{loggerName:this.options.loggerName,loggerContextCb:()=>this.logContext});this.localParticipant.addTrackPublication(e),this.localParticipant.emit(R.LocalTrackPublished,e)}for(let e=0;e<n.count-1;e+=1){let t=new xa({sid:Math.floor(Math.random()*1e4).toString(),identity:`simulated-${e}`,state:Sa.ACTIVE,tracks:[],joinedAt:O.parse(Date.now())}),r=this.getOrCreateParticipant(t.identity,t);if(n.video){let i=Au(160*(n.aspectRatios[e%n.aspectRatios.length]??1),160,!1,!0),a=new Ea({source:ua.CAMERA,sid:Math.floor(Math.random()*1e4).toString(),type:la.AUDIO});r.addSubscribedMediaTrack(i,a.sid,new MediaStream([i]),new RTCRtpReceiver),t.tracks=[...t.tracks,a]}if(n.audio){let e=Mu(),n=new Ea({source:ua.MICROPHONE,sid:Math.floor(Math.random()*1e4).toString(),type:la.AUDIO});r.addSubscribedMediaTrack(e,n.sid,new MediaStream([e]),new RTCRtpReceiver),t.tracks=[...t.tracks,n]}r.updateInfo(t)}})}emit(e){var t=[...arguments].slice(1);if(e!==L.ActiveSpeakersChanged&&e!==L.TranscriptionReceived){let n=ch(t).filter(e=>e!==void 0);(e===L.TrackSubscribed||e===L.TrackUnsubscribed)&&this.log.trace(`subscribe trace: ${e}`,Object.assign(Object.assign({},this.logContext),{event:e,args:n})),this.log.debug(`room event ${e}`,Object.assign(Object.assign({},this.logContext),{event:e,args:n}))}return super.emit(e,...t)}};sh.cleanupRegistry=typeof FinalizationRegistry<`u`&&new FinalizationRegistry(e=>{e()});function ch(e){return e.map(e=>{if(e)return Array.isArray(e)?ch(e):typeof e==`object`?`logContext`in e?e.logContext:void 0:e})}var lh;(function(e){e[e.IDLE=0]=`IDLE`,e[e.RUNNING=1]=`RUNNING`,e[e.SKIPPED=2]=`SKIPPED`,e[e.SUCCESS=3]=`SUCCESS`,e[e.FAILED=4]=`FAILED`})(lh||={}),Bs.EventEmitter,Bs.EventEmitter;function X(e,t,n){return(t=dh(t))in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function uh(e,t){if(typeof e!=`object`||!e)return e;var n=e[Symbol.toPrimitive];if(n!==void 0){var r=n.call(e,t);if(typeof r!=`object`)return r;throw TypeError(`@@toPrimitive must return a primitive value.`)}return(t===`string`?String:Number)(e)}function dh(e){var t=uh(e,`string`);return typeof t==`symbol`?t:t+``}new TextEncoder,new TextDecoder;var fh=class extends Error{constructor(e,t){var n;super(e,t),X(this,`code`,`ERR_JOSE_GENERIC`),this.name=this.constructor.name,(n=Error.captureStackTrace)==null||n.call(Error,this,this.constructor)}};X(fh,`code`,`ERR_JOSE_GENERIC`),X(class extends fh{constructor(e,t){let n=arguments.length>2&&arguments[2]!==void 0?arguments[2]:`unspecified`,r=arguments.length>3&&arguments[3]!==void 0?arguments[3]:`unspecified`;super(e,{cause:{claim:n,reason:r,payload:t}}),X(this,`code`,`ERR_JWT_CLAIM_VALIDATION_FAILED`),X(this,`claim`,void 0),X(this,`reason`,void 0),X(this,`payload`,void 0),this.claim=n,this.reason=r,this.payload=t}},`code`,`ERR_JWT_CLAIM_VALIDATION_FAILED`),X(class extends fh{constructor(e,t){let n=arguments.length>2&&arguments[2]!==void 0?arguments[2]:`unspecified`,r=arguments.length>3&&arguments[3]!==void 0?arguments[3]:`unspecified`;super(e,{cause:{claim:n,reason:r,payload:t}}),X(this,`code`,`ERR_JWT_EXPIRED`),X(this,`claim`,void 0),X(this,`reason`,void 0),X(this,`payload`,void 0),this.claim=n,this.reason=r,this.payload=t}},`code`,`ERR_JWT_EXPIRED`),X(class extends fh{constructor(){super(...arguments),X(this,`code`,`ERR_JOSE_ALG_NOT_ALLOWED`)}},`code`,`ERR_JOSE_ALG_NOT_ALLOWED`),X(class extends fh{constructor(){super(...arguments),X(this,`code`,`ERR_JOSE_NOT_SUPPORTED`)}},`code`,`ERR_JOSE_NOT_SUPPORTED`),X(class extends fh{constructor(){let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:`decryption operation failed`,t=arguments.length>1?arguments[1]:void 0;super(e,t),X(this,`code`,`ERR_JWE_DECRYPTION_FAILED`)}},`code`,`ERR_JWE_DECRYPTION_FAILED`),X(class extends fh{constructor(){super(...arguments),X(this,`code`,`ERR_JWE_INVALID`)}},`code`,`ERR_JWE_INVALID`),X(class extends fh{constructor(){super(...arguments),X(this,`code`,`ERR_JWS_INVALID`)}},`code`,`ERR_JWS_INVALID`),X(class extends fh{constructor(){super(...arguments),X(this,`code`,`ERR_JWT_INVALID`)}},`code`,`ERR_JWT_INVALID`),X(class extends fh{constructor(){super(...arguments),X(this,`code`,`ERR_JWK_INVALID`)}},`code`,`ERR_JWK_INVALID`),X(class extends fh{constructor(){super(...arguments),X(this,`code`,`ERR_JWKS_INVALID`)}},`code`,`ERR_JWKS_INVALID`),X(class extends fh{constructor(){let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:`no applicable key found in the JSON Web Key Set`,t=arguments.length>1?arguments[1]:void 0;super(e,t),X(this,`code`,`ERR_JWKS_NO_MATCHING_KEY`)}},`code`,`ERR_JWKS_NO_MATCHING_KEY`),X(class extends fh{constructor(){let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:`multiple matching keys found in the JSON Web Key Set`,t=arguments.length>1?arguments[1]:void 0;super(e,t),X(this,Symbol.asyncIterator,void 0),X(this,`code`,`ERR_JWKS_MULTIPLE_MATCHING_KEYS`)}},`code`,`ERR_JWKS_MULTIPLE_MATCHING_KEYS`),X(class extends fh{constructor(){let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:`request timed out`,t=arguments.length>1?arguments[1]:void 0;super(e,t),X(this,`code`,`ERR_JWKS_TIMEOUT`)}},`code`,`ERR_JWKS_TIMEOUT`),X(class extends fh{constructor(){let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:`signature verification failed`,t=arguments.length>1?arguments[1]:void 0;super(e,t),X(this,`code`,`ERR_JWS_SIGNATURE_VERIFICATION_FAILED`)}},`code`,`ERR_JWS_SIGNATURE_VERIFICATION_FAILED`);function ph(){return ph=Object.assign?Object.assign.bind():function(e){for(var t=1;t<arguments.length;t++){var n=arguments[t];for(var r in n)({}).hasOwnProperty.call(n,r)&&(e[r]=n[r])}return e},ph.apply(null,arguments)}var mh=new Uint8Array,hh=class{static getFullOptions(e){return ph({clientTools:{},onConnect:()=>{},onDebug:()=>{},onDisconnect:()=>{},onError:()=>{},onMessage:()=>{},onAudio:()=>{},onModeChange:()=>{},onStatusChange:()=>{},onCanSendFeedbackChange:()=>{},onInterruption:()=>{}},e)}constructor(e,t){var n=this;this.options=void 0,this.connection=void 0,this.lastInterruptTimestamp=0,this.mode=`listening`,this.status=`connecting`,this.volume=1,this.currentEventId=1,this.lastFeedbackEventId=0,this.canSendFeedback=!1,this.endSessionWithDetails=async function(e){n.status!==`connected`&&n.status!==`connecting`||(n.updateStatus(`disconnecting`),await n.handleEndSession(),n.updateStatus(`disconnected`),n.options.onDisconnect&&n.options.onDisconnect(e))},this.onMessage=async function(e){switch(e.type){case`interruption`:n.handleInterruption(e);return;case`agent_response`:n.handleAgentResponse(e);return;case`user_transcript`:n.handleUserTranscript(e);return;case`internal_tentative_agent_response`:n.handleTentativeAgentResponse(e);return;case`client_tool_call`:try{await n.handleClientToolCall(e)}catch(t){n.onError(`Unexpected error in client tool call handling: ${t instanceof Error?t.message:String(t)}`,{clientToolName:e.client_tool_call.tool_name,toolCallId:e.client_tool_call.tool_call_id})}return;case`audio`:n.handleAudio(e);return;case`vad_score`:n.handleVadScore(e);return;case`ping`:n.connection.sendMessage({type:`pong`,event_id:e.ping_event.event_id});return;case`mcp_tool_call`:n.handleMCPToolCall(e);return;case`mcp_connection_status`:n.handleMCPConnectionStatus(e);return;case`agent_tool_request`:n.handleAgentToolRequest(e);return;case`agent_tool_response`:n.handleAgentToolResponse(e);return;case`conversation_initiation_metadata`:n.handleConversationMetadata(e);return;case`asr_initiation_metadata`:n.handleAsrInitiationMetadata(e);return;case`agent_chat_response_part`:n.handleAgentChatResponsePart(e);return;case`error`:n.handleErrorEvent(e);return;default:n.options.onDebug&&n.options.onDebug(e);return}},this.setVolume=({volume:e})=>{this.volume=e},this.options=e,this.connection=t,this.options.onConnect&&this.options.onConnect({conversationId:t.conversationId}),this.connection.onMessage(this.onMessage),this.connection.onDisconnect(this.endSessionWithDetails),this.connection.onModeChange(e=>this.updateMode(e)),this.updateStatus(`connected`)}endSession(){return this.endSessionWithDetails({reason:`user`})}async handleEndSession(){this.connection.close()}updateMode(e){e!==this.mode&&(this.mode=e,this.options.onModeChange&&this.options.onModeChange({mode:e}))}updateStatus(e){e!==this.status&&(this.status=e,this.options.onStatusChange&&this.options.onStatusChange({status:e}))}updateCanSendFeedback(){let e=this.currentEventId!==this.lastFeedbackEventId;this.canSendFeedback!==e&&(this.canSendFeedback=e,this.options.onCanSendFeedbackChange&&this.options.onCanSendFeedbackChange({canSendFeedback:e}))}handleInterruption(e){e.interruption_event&&(this.lastInterruptTimestamp=e.interruption_event.event_id,this.options.onInterruption&&this.options.onInterruption({event_id:e.interruption_event.event_id}))}handleAgentResponse(e){this.options.onMessage&&this.options.onMessage({source:`ai`,role:`agent`,message:e.agent_response_event.agent_response})}handleUserTranscript(e){this.options.onMessage&&this.options.onMessage({source:`user`,role:`user`,message:e.user_transcription_event.user_transcript})}handleTentativeAgentResponse(e){this.options.onDebug&&this.options.onDebug({type:`tentative_agent_response`,response:e.tentative_agent_response_internal_event.tentative_agent_response})}handleVadScore(e){this.options.onVadScore&&this.options.onVadScore({vadScore:e.vad_score_event.vad_score})}async handleClientToolCall(e){if(Object.prototype.hasOwnProperty.call(this.options.clientTools,e.client_tool_call.tool_name))try{let t=await this.options.clientTools[e.client_tool_call.tool_name](e.client_tool_call.parameters)??`Client tool execution successful.`,n=typeof t==`object`?JSON.stringify(t):String(t);this.connection.sendMessage({type:`client_tool_result`,tool_call_id:e.client_tool_call.tool_call_id,result:n,is_error:!1})}catch(t){this.onError(`Client tool execution failed with following error: ${t?.message}`,{clientToolName:e.client_tool_call.tool_name}),this.connection.sendMessage({type:`client_tool_result`,tool_call_id:e.client_tool_call.tool_call_id,result:`Client tool execution failed: ${t?.message}`,is_error:!0})}else{if(this.options.onUnhandledClientToolCall)return void this.options.onUnhandledClientToolCall(e.client_tool_call);this.onError(`Client tool with name ${e.client_tool_call.tool_name} is not defined on client`,{clientToolName:e.client_tool_call.tool_name}),this.connection.sendMessage({type:`client_tool_result`,tool_call_id:e.client_tool_call.tool_call_id,result:`Client tool with name ${e.client_tool_call.tool_name} is not defined on client`,is_error:!0})}}handleAudio(e){}handleMCPToolCall(e){this.options.onMCPToolCall&&this.options.onMCPToolCall(e.mcp_tool_call)}handleMCPConnectionStatus(e){this.options.onMCPConnectionStatus&&this.options.onMCPConnectionStatus(e.mcp_connection_status)}handleAgentToolRequest(e){this.options.onAgentToolRequest&&this.options.onAgentToolRequest(e.agent_tool_request)}handleAgentToolResponse(e){e.agent_tool_response.tool_name===`end_call`&&this.endSessionWithDetails({reason:`agent`,context:new CloseEvent(`end_call`,{reason:`Agent ended the call`})}),this.options.onAgentToolResponse&&this.options.onAgentToolResponse(e.agent_tool_response)}handleConversationMetadata(e){this.options.onConversationMetadata&&this.options.onConversationMetadata(e.conversation_initiation_metadata_event)}handleAsrInitiationMetadata(e){this.options.onAsrInitiationMetadata&&this.options.onAsrInitiationMetadata(e.asr_initiation_metadata_event)}handleAgentChatResponsePart(e){this.options.onAgentChatResponsePart&&this.options.onAgentChatResponsePart(e.text_response_part)}handleErrorEvent(e){let t=e.error_event.error_type,n=e.error_event.message||e.error_event.reason||`Unknown error`;t===`max_duration_exceeded`?this.endSessionWithDetails({reason:`error`,message:n,context:new Event(`max_duration_exceeded`)}):this.onError(`Server error: ${n}`,{errorType:t,code:e.error_event.code,debugMessage:e.error_event.debug_message,details:e.error_event.details})}onError(e,t){console.error(e,t),this.options.onError&&this.options.onError(e,t)}getId(){return this.connection.conversationId}isOpen(){return this.status===`connected`}setMicMuted(e){this.connection.setMicMuted(e)}getInputByteFrequencyData(){return mh}getOutputByteFrequencyData(){return mh}getInputVolume(){return 0}getOutputVolume(){return 0}sendFeedback(e){this.canSendFeedback?(this.connection.sendMessage({type:`feedback`,score:e?`like`:`dislike`,event_id:this.currentEventId}),this.lastFeedbackEventId=this.currentEventId,this.updateCanSendFeedback()):console.warn(this.lastFeedbackEventId===0?`Cannot send feedback: the conversation has not started yet.`:`Cannot send feedback: feedback has already been sent for the current response.`)}sendContextualUpdate(e){this.connection.sendMessage({type:`contextual_update`,text:e})}sendUserMessage(e){this.connection.sendMessage({type:`user_message`,text:e})}sendUserActivity(){this.connection.sendMessage({type:`user_activity`})}sendMCPToolApprovalResult(e,t){this.connection.sendMessage({type:`mcp_tool_approval_result`,tool_call_id:e,is_approved:t})}},gh=class{constructor(e={}){this.queue=[],this.disconnectionDetails=null,this.onDisconnectCallback=null,this.onMessageCallback=null,this.onModeChangeCallback=null,this.onDebug=void 0,this.onDebug=e.onDebug}debug(e){this.onDebug&&this.onDebug(e)}onMessage(e){this.onMessageCallback=e;let t=this.queue;this.queue=[],t.length>0&&queueMicrotask(()=>{t.forEach(e)})}onDisconnect(e){this.onDisconnectCallback=e;let t=this.disconnectionDetails;t&&queueMicrotask(()=>{e(t)})}onModeChange(e){this.onModeChangeCallback=e}updateMode(e){var t;(t=this.onModeChangeCallback)==null||t.call(this,e)}disconnect(e){var t;this.disconnectionDetails||(this.disconnectionDetails=e,(t=this.onDisconnectCallback)==null||t.call(this,e))}handleMessage(e){this.onMessageCallback?this.onMessageCallback(e):this.queue.push(e)}};function _h(e){let[t,n]=e.split(`_`);if(![`pcm`,`ulaw`].includes(t))throw Error(`Invalid format: ${e}`);let r=Number.parseInt(n);if(Number.isNaN(r))throw Error(`Invalid sample rate: ${n}`);return{format:t,sampleRate:r}}var vh=`0.12.2`;function yh(e){return!!e.type}var bh=`conversation_initiation_client_data`;function xh(e){var t;let n={type:bh};return e.overrides&&(n.conversation_config_override={agent:{prompt:e.overrides.agent?.prompt,first_message:e.overrides.agent?.firstMessage,language:e.overrides.agent?.language},tts:{voice_id:e.overrides.tts?.voiceId,speed:e.overrides.tts?.speed},conversation:{text_only:e.overrides.conversation?.textOnly}}),e.customLlmExtraBody&&(n.custom_llm_extra_body=e.customLlmExtraBody),e.dynamicVariables&&(n.dynamic_variables=e.dynamicVariables),e.userId&&(n.user_id=e.userId),(t=e.overrides)!=null&&t.client&&(n.source_info={source:e.overrides.client.source,version:e.overrides.client.version}),n}var Sh=class e extends gh{constructor(e,t,n,r){super(),this.socket=void 0,this.conversationId=void 0,this.inputFormat=void 0,this.outputFormat=void 0,this.socket=e,this.conversationId=t,this.inputFormat=n,this.outputFormat=r,this.socket.addEventListener(`error`,e=>{setTimeout(()=>this.disconnect({reason:`error`,message:`The connection was closed due to a socket error.`,context:e}),0)}),this.socket.addEventListener(`close`,e=>{this.disconnect(e.code===1e3?{reason:`agent`,context:e}:{reason:`error`,message:e.reason||`The connection was closed by the server.`,context:e})}),this.socket.addEventListener(`message`,e=>{try{let t=JSON.parse(e.data);if(!yh(t))return void this.debug({type:`invalid_event`,message:`Received invalid socket event`,data:e.data});this.handleMessage(t)}catch(t){this.debug({type:`parsing_error`,message:`Failed to parse socket message`,error:t instanceof Error?t.message:String(t),data:e.data})}})}static async create(t){let n=null;try{var r,i;let a=t.origin??`wss://api.elevenlabs.io`,o,s=((r=t.overrides)==null||(r=r.client)==null?void 0:r.version)||vh,c=((i=t.overrides)==null||(i=i.client)==null?void 0:i.source)||`js_sdk`;if(t.signedUrl){let e=t.signedUrl.includes(`?`)?`&`:`?`;o=`${t.signedUrl}${e}source=${c}&version=${s}`}else o=`${a}/v1/convai/conversation?agent_id=${t.agentId}&source=${c}&version=${s}`;let l=[`convai`];t.authorization&&l.push(`bearer.${t.authorization}`),n=new WebSocket(o,l);let{conversation_id:u,agent_output_audio_format:d,user_input_audio_format:f}=await new Promise((e,r)=>{n.addEventListener(`open`,()=>{var e;let r=xh(t);(e=n)==null||e.send(JSON.stringify(r))},{once:!0}),n.addEventListener(`error`,e=>{setTimeout(()=>r(e),0)}),n.addEventListener(`close`,r),n.addEventListener(`message`,t=>{let n=JSON.parse(t.data);yh(n)&&(n.type===`conversation_initiation_metadata`?e(n.conversation_initiation_metadata_event):console.warn(`First received message is not conversation metadata.`))},{once:!0})}),p=_h(f??`pcm_16000`),m=_h(d);return new e(n,u,p,m)}catch(e){var a;throw(a=n)==null||a.close(),e}}close(){this.socket.close(1e3,`User ended conversation`)}sendMessage(e){this.socket.send(JSON.stringify(e))}async setMicMuted(e){console.warn(`WebSocket connection setMicMuted called with ${e}, but this is handled by VoiceConversation`)}};function Ch(e){let t=new Uint8Array(e);return window.btoa(String.fromCharCode(...t))}function wh(e){let t=window.atob(e),n=t.length,r=new Uint8Array(n);for(let e=0;e<n;e++)r[e]=t.charCodeAt(e);return r.buffer}var Th=new Map;function Eh(e,t){return async(n,r)=>{let i=Th.get(e);if(i)return n.addModule(i);if(r)try{await n.addModule(r),Th.set(e,r);return}catch(t){throw Error(`Failed to load the ${e} worklet module from path: ${r}. Error: ${t}`)}let a=new Blob([t],{type:`application/javascript`}),o=URL.createObjectURL(a);try{await n.addModule(o),Th.set(e,o);return}catch{URL.revokeObjectURL(o)}try{let r=`data:application/javascript;base64,${btoa(t)}`;await n.addModule(r),Th.set(e,r)}catch{throw Error(`Failed to load the ${e} worklet module. Make sure the browser supports AudioWorklets. If you are using a strict CSP, you may need to self-host the worklet files.`)}}}var Dh=Eh(`rawAudioProcessor`,`/*
|
|
68
68
|
* ulaw encoding logic taken from the wavefile library
|
|
69
69
|
* https://github.com/rochars/wavefile/blob/master/lib/codecs/mulaw.js
|
|
70
70
|
* USED BY @elevenlabs/client
|
|
@@ -188,7 +188,7 @@ class RawAudioProcessor extends AudioWorkletProcessor {
|
|
|
188
188
|
}
|
|
189
189
|
}
|
|
190
190
|
registerProcessor("rawAudioProcessor", RawAudioProcessor);
|
|
191
|
-
`),Dh=class e extends hh{constructor(e,t,n,r,i={}){super(i),this.conversationId=void 0,this.inputFormat=void 0,this.outputFormat=void 0,this.room=void 0,this.isConnected=!1,this.audioEventId=1,this.audioCaptureContext=null,this.audioElements=[],this.outputDeviceId=null,this.outputAnalyser=null,this.outputFrequencyData=null,this.room=e,this.conversationId=t,this.inputFormat=n,this.outputFormat=r,this.setupRoomEventListeners()}static async create(t){let n;if(`conversationToken`in t&&t.conversationToken)n=t.conversationToken;else{if(!(`agentId`in t)||!t.agentId)throw Error(`Either conversationToken or agentId is required for WebRTC connection`);try{var r,i;let e=((r=t.overrides)==null||(r=r.client)==null?void 0:r.version)||_h,o=((i=t.overrides)==null||(i=i.client)==null?void 0:i.source)||`js_sdk`,s=`${a=t.origin??`https://api.elevenlabs.io`,a.replace(/^wss:\/\//,`https://`)}/v1/convai/conversation/token?agent_id=${t.agentId}&source=${o}&version=${e}`,c=await fetch(s);if(!c.ok)throw Error(`ElevenLabs API returned ${c.status} ${c.statusText}`);if(n=(await c.json()).token,!n)throw Error(`No conversation token received from API`)}catch(e){let n=e instanceof Error?e.message:String(e);throw e instanceof Error&&e.message.includes(`401`)&&(n=`Your agent has authentication enabled, but no signed URL or conversation token was provided.`),Error(`Failed to fetch conversation token for agent ${t.agentId}: ${n}`)}}var a;let o=new oh;try{let r=new e(o,`room_${Date.now()}`,gh(`pcm_48000`),gh(`pcm_48000`),t),i=t.livekitUrl||`wss://livekit.rtc.elevenlabs.io`;await o.connect(i,n),await new Promise(e=>{if(r.isConnected)e();else{let t=()=>{o.off(L.Connected,t),e()};o.on(L.Connected,t)}}),o.name&&(r.conversationId=o.name.match(/(conv_[a-zA-Z0-9]+)/)?.[0]||o.name),await o.localParticipant.setMicrophoneEnabled(!0);let a=bh(t);return r.debug({type:yh,message:a}),await r.sendMessage(a),r}catch(e){throw await o.disconnect(),e}}setupRoomEventListeners(){var e=this;this.room.on(L.Connected,async function(){e.isConnected=!0,console.info(`WebRTC room connected`)}),this.room.on(L.Disconnected,e=>{this.isConnected=!1,this.disconnect({reason:`agent`,context:new CloseEvent(`close`,{reason:e?.toString()})})}),this.room.on(L.ConnectionStateChanged,e=>{e===Y.Disconnected&&(this.isConnected=!1,this.disconnect({reason:`error`,message:`LiveKit connection state changed to ${e}`,context:new Event(`connection_state_changed`)}))}),this.room.on(L.DataReceived,(e,t)=>{try{let t=JSON.parse(new TextDecoder().decode(e));if(t.type===`audio`)return;vh(t)?this.handleMessage(t):console.warn(`Invalid socket event received:`,t)}catch(t){console.warn(`Failed to parse incoming data message:`,t),console.warn(`Raw payload:`,new TextDecoder().decode(e))}}),this.room.on(L.TrackSubscribed,async function(t,n,r){if(t.kind===U.Kind.Audio&&r.identity.includes(`agent`)){let n=t,r=n.attach();if(r.autoplay=!0,r.controls=!1,e.outputDeviceId&&r.setSinkId)try{await r.setSinkId(e.outputDeviceId)}catch(e){console.warn(`Failed to set output device for new audio element:`,e)}r.style.display=`none`,document.body.appendChild(r),e.audioElements.push(r),e.audioElements.length===1&&(e.onDebug==null||e.onDebug({type:`audio_element_ready`})),await e.setupAudioCapture(n)}}),this.room.on(L.ActiveSpeakersChanged,async function(t){e.updateMode(t.length>0&&t[0].identity.startsWith(`agent`)?`speaking`:`listening`)}),this.room.on(L.ParticipantDisconnected,e=>{var t;(t=e.identity)!=null&&t.startsWith(`agent`)&&this.disconnect({reason:`agent`,context:new CloseEvent(`close`,{reason:`agent disconnected`})})})}close(){if(this.isConnected){try{this.room.localParticipant.audioTrackPublications.forEach(e=>{e.track&&e.track.stop()})}catch(e){console.warn(`Error stopping local tracks:`,e)}this.audioCaptureContext&&=(this.audioCaptureContext.close().catch(e=>{console.warn(`Error closing audio capture context:`,e)}),null),this.audioElements.forEach(e=>{e.parentNode&&e.parentNode.removeChild(e)}),this.audioElements=[],this.room.disconnect()}}async sendMessage(e){if(this.isConnected&&this.room.localParticipant){if(!(`user_audio_chunk`in e))try{let t=new TextEncoder().encode(JSON.stringify(e));await this.room.localParticipant.publishData(t,{reliable:!0})}catch(t){this.debug({type:`send_message_error`,message:{message:e,error:t}}),console.error(`Failed to send message via WebRTC:`,t)}}else console.warn(`Cannot send message: room not connected or no local participant`)}getRoom(){return this.room}async setMicMuted(e){if(!this.isConnected||!this.room.localParticipant)return void console.warn(`Cannot set microphone muted: room not connected or no local participant`);let t=this.room.localParticipant.getTrackPublication(U.Source.Microphone);if(t!=null&&t.track)try{e?await t.track.mute():await t.track.unmute()}catch{await this.room.localParticipant.setMicrophoneEnabled(!e)}else await this.room.localParticipant.setMicrophoneEnabled(!e)}async setupAudioCapture(e){try{let t=new AudioContext;this.audioCaptureContext=t,this.outputAnalyser=t.createAnalyser(),this.outputAnalyser.fftSize=2048,this.outputAnalyser.smoothingTimeConstant=.8;let n=new MediaStream([e.mediaStreamTrack]),r=t.createMediaStreamSource(n);r.connect(this.outputAnalyser),await Eh(t.audioWorklet);let i=new AudioWorkletNode(t,`rawAudioProcessor`);this.outputAnalyser.connect(i),i.port.postMessage({type:`setFormat`,format:this.outputFormat.format,sampleRate:this.outputFormat.sampleRate}),i.port.onmessage=e=>{let[t,n]=e.data;if(n>.01){let e=Sh(t.buffer),n=this.audioEventId++;this.handleMessage({type:`audio`,audio_event:{audio_base_64:e,event_id:n}})}},r.connect(i)}catch(e){console.warn(`Failed to set up audio capture:`,e)}}setAudioVolume(e){this.audioElements.forEach(t=>{t.volume=e})}async setAudioOutputDevice(e){if(!(`setSinkId`in HTMLAudioElement.prototype))throw Error(`setSinkId is not supported in this browser`);let t=this.audioElements.map(async function(t){try{await t.setSinkId(e)}catch(e){throw console.error(`Failed to set sink ID for audio element:`,e),e}});await Promise.all(t),this.outputDeviceId=e}async setAudioInputDevice(e){if(!this.isConnected||!this.room.localParticipant)throw Error(`Cannot change input device: room not connected or no local participant`);try{let t=this.room.localParticipant.getTrackPublication(U.Source.Microphone);t!=null&&t.track&&(await t.track.stop(),await this.room.localParticipant.unpublishTrack(t.track));let n=await Ym({deviceId:{exact:e},echoCancellation:!0,noiseSuppression:!0,autoGainControl:!0,channelCount:{ideal:1}});await this.room.localParticipant.publishTrack(n,{name:`microphone`,source:U.Source.Microphone})}catch(e){console.error(`Failed to change input device:`,e);try{await this.room.localParticipant.setMicrophoneEnabled(!0)}catch(e){console.error(`Failed to recover microphone after device switch error:`,e)}throw e}}getOutputByteFrequencyData(){return this.outputAnalyser?(this.outputFrequencyData??=new Uint8Array(this.outputAnalyser.frequencyBinCount),this.outputAnalyser.getByteFrequencyData(this.outputFrequencyData),this.outputFrequencyData):null}};async function Oh(e){let t=function(e){return e.connectionType?e.connectionType:`conversationToken`in e&&e.conversationToken?`webrtc`:`websocket`}(e);switch(t){case`websocket`:return xh.create(e);case`webrtc`:return Dh.create(e);default:throw Error(`Unknown connection type: ${t}`)}}function kh(){return[`iPad Simulator`,`iPhone Simulator`,`iPod Simulator`,`iPad`,`iPhone`,`iPod`].includes(navigator.platform)||navigator.userAgent.includes(`Mac`)&&`ontouchend`in document}async function Ah(e={default:0,android:3e3}){let t=e.default;/android/i.test(navigator.userAgent)?t=e.android??t:kh()&&(t=e.ios??t),t>0&&await new Promise(e=>setTimeout(e,t))}var jh=class e extends mh{static async startSession(t){let n=mh.getFullOptions(t);n.onStatusChange&&n.onStatusChange({status:`connecting`}),n.onCanSendFeedbackChange&&n.onCanSendFeedbackChange({canSendFeedback:!1}),n.onModeChange&&n.onModeChange({mode:`listening`}),n.onCanSendFeedbackChange&&n.onCanSendFeedbackChange({canSendFeedback:!1});let r=null;try{return await Ah(n.connectionDelay),r=await Oh(t),new e(n,r)}catch(e){var i;throw n.onStatusChange&&n.onStatusChange({status:`disconnected`}),(i=r)==null||i.close(),e}}},Mh={echoCancellation:!0,noiseSuppression:!0,autoGainControl:!0,channelCount:{ideal:1}},Nh=class e{static async create({sampleRate:t,format:n,preferHeadphonesForIosDevices:r,inputDeviceId:i,workletPaths:a,libsampleratePath:o}){let s=null,c=null;try{let l=fh({sampleRate:{ideal:t}},Mh);if(kh()&&r){let e=(await window.navigator.mediaDevices.enumerateDevices()).find(e=>e.kind===`audioinput`&&[`airpod`,`headphone`,`earphone`].find(t=>e.label.toLowerCase().includes(t)));e&&(l.deviceId={ideal:e.deviceId})}i&&(l.deviceId=e.getDeviceIdConstraint(i));let u=navigator.mediaDevices.getSupportedConstraints().sampleRate;s=new window.AudioContext(u?{sampleRate:t}:{});let d=s.createAnalyser();if(!u){let e=o||`https://cdn.jsdelivr.net/npm/@alexanderolsen/libsamplerate-js@2.1.2/dist/libsamplerate.worklet.js`;await s.audioWorklet.addModule(e)}await Eh(s.audioWorklet,a?.rawAudioProcessor);let f=fh({voiceIsolation:!0},l);c=await navigator.mediaDevices.getUserMedia({audio:f});let p=s.createMediaStreamSource(c),m=new AudioWorkletNode(s,`rawAudioProcessor`);return m.port.postMessage({type:`setFormat`,format:n,sampleRate:t}),p.connect(d),d.connect(m),await s.resume(),new e(s,d,m,c,p)}catch(e){var l,u;throw(l=c)==null||l.getTracks().forEach(e=>{e.stop()}),(u=s)==null||u.close(),e}}static getDeviceIdConstraint(e){if(e)return kh()?{ideal:e}:{exact:e}}constructor(e,t,n,r,i){this.context=void 0,this.analyser=void 0,this.worklet=void 0,this.inputStream=void 0,this.mediaStreamSource=void 0,this.context=e,this.analyser=t,this.worklet=n,this.inputStream=r,this.mediaStreamSource=i}async close(){this.inputStream.getTracks().forEach(e=>{e.stop()}),this.mediaStreamSource.disconnect(),await this.context.close()}setMuted(e){this.worklet.port.postMessage({type:`setMuted`,isMuted:e})}async setInputDevice(t){try{let n=fh({},Mh);t&&(n.deviceId=e.getDeviceIdConstraint(t));let r=fh({voiceIsolation:!0},n),i=await navigator.mediaDevices.getUserMedia({audio:r});this.inputStream.getTracks().forEach(e=>{e.stop()}),this.mediaStreamSource.disconnect(),this.inputStream=i,this.mediaStreamSource=this.context.createMediaStreamSource(i),this.mediaStreamSource.connect(this.analyser)}catch(e){throw console.error(`Failed to switch input device:`,e),e}}},Ph=Th(`audioConcatProcessor`,`/*
|
|
191
|
+
`),Oh=class e extends gh{constructor(e,t,n,r,i={}){super(i),this.conversationId=void 0,this.inputFormat=void 0,this.outputFormat=void 0,this.room=void 0,this.isConnected=!1,this.audioEventId=1,this.audioCaptureContext=null,this.audioElements=[],this.outputDeviceId=null,this.outputAnalyser=null,this.outputFrequencyData=null,this.room=e,this.conversationId=t,this.inputFormat=n,this.outputFormat=r,this.setupRoomEventListeners()}static async create(t){let n;if(`conversationToken`in t&&t.conversationToken)n=t.conversationToken;else{if(!(`agentId`in t)||!t.agentId)throw Error(`Either conversationToken or agentId is required for WebRTC connection`);try{var r,i;let e=((r=t.overrides)==null||(r=r.client)==null?void 0:r.version)||vh,o=((i=t.overrides)==null||(i=i.client)==null?void 0:i.source)||`js_sdk`,s=`${a=t.origin??`https://api.elevenlabs.io`,a.replace(/^wss:\/\//,`https://`)}/v1/convai/conversation/token?agent_id=${t.agentId}&source=${o}&version=${e}`,c=await fetch(s);if(!c.ok)throw Error(`ElevenLabs API returned ${c.status} ${c.statusText}`);if(n=(await c.json()).token,!n)throw Error(`No conversation token received from API`)}catch(e){let n=e instanceof Error?e.message:String(e);throw e instanceof Error&&e.message.includes(`401`)&&(n=`Your agent has authentication enabled, but no signed URL or conversation token was provided.`),Error(`Failed to fetch conversation token for agent ${t.agentId}: ${n}`)}}var a;let o=new sh;try{let r=new e(o,`room_${Date.now()}`,_h(`pcm_48000`),_h(`pcm_48000`),t),i=t.livekitUrl||`wss://livekit.rtc.elevenlabs.io`;await o.connect(i,n),await new Promise(e=>{if(r.isConnected)e();else{let t=()=>{o.off(L.Connected,t),e()};o.on(L.Connected,t)}}),o.name&&(r.conversationId=o.name.match(/(conv_[a-zA-Z0-9]+)/)?.[0]||o.name),await o.localParticipant.setMicrophoneEnabled(!0);let a=xh(t);return r.debug({type:bh,message:a}),await r.sendMessage(a),r}catch(e){throw await o.disconnect(),e}}setupRoomEventListeners(){var e=this;this.room.on(L.Connected,async function(){e.isConnected=!0,console.info(`WebRTC room connected`)}),this.room.on(L.Disconnected,e=>{this.isConnected=!1,this.disconnect({reason:`agent`,context:new CloseEvent(`close`,{reason:e?.toString()})})}),this.room.on(L.ConnectionStateChanged,e=>{e===Y.Disconnected&&(this.isConnected=!1,this.disconnect({reason:`error`,message:`LiveKit connection state changed to ${e}`,context:new Event(`connection_state_changed`)}))}),this.room.on(L.DataReceived,(e,t)=>{try{let t=JSON.parse(new TextDecoder().decode(e));if(t.type===`audio`)return;yh(t)?this.handleMessage(t):console.warn(`Invalid socket event received:`,t)}catch(t){console.warn(`Failed to parse incoming data message:`,t),console.warn(`Raw payload:`,new TextDecoder().decode(e))}}),this.room.on(L.TrackSubscribed,async function(t,n,r){if(t.kind===U.Kind.Audio&&r.identity.includes(`agent`)){let n=t,r=n.attach();if(r.autoplay=!0,r.controls=!1,e.outputDeviceId&&r.setSinkId)try{await r.setSinkId(e.outputDeviceId)}catch(e){console.warn(`Failed to set output device for new audio element:`,e)}r.style.display=`none`,document.body.appendChild(r),e.audioElements.push(r),e.audioElements.length===1&&(e.onDebug==null||e.onDebug({type:`audio_element_ready`})),await e.setupAudioCapture(n)}}),this.room.on(L.ActiveSpeakersChanged,async function(t){e.updateMode(t.length>0&&t[0].identity.startsWith(`agent`)?`speaking`:`listening`)}),this.room.on(L.ParticipantDisconnected,e=>{var t;(t=e.identity)!=null&&t.startsWith(`agent`)&&this.disconnect({reason:`agent`,context:new CloseEvent(`close`,{reason:`agent disconnected`})})})}close(){if(this.isConnected){try{this.room.localParticipant.audioTrackPublications.forEach(e=>{e.track&&e.track.stop()})}catch(e){console.warn(`Error stopping local tracks:`,e)}this.audioCaptureContext&&=(this.audioCaptureContext.close().catch(e=>{console.warn(`Error closing audio capture context:`,e)}),null),this.audioElements.forEach(e=>{e.parentNode&&e.parentNode.removeChild(e)}),this.audioElements=[],this.room.disconnect()}}async sendMessage(e){if(this.isConnected&&this.room.localParticipant){if(!(`user_audio_chunk`in e))try{let t=new TextEncoder().encode(JSON.stringify(e));await this.room.localParticipant.publishData(t,{reliable:!0})}catch(t){this.debug({type:`send_message_error`,message:{message:e,error:t}}),console.error(`Failed to send message via WebRTC:`,t)}}else console.warn(`Cannot send message: room not connected or no local participant`)}getRoom(){return this.room}async setMicMuted(e){if(!this.isConnected||!this.room.localParticipant)return void console.warn(`Cannot set microphone muted: room not connected or no local participant`);let t=this.room.localParticipant.getTrackPublication(U.Source.Microphone);if(t!=null&&t.track)try{e?await t.track.mute():await t.track.unmute()}catch{await this.room.localParticipant.setMicrophoneEnabled(!e)}else await this.room.localParticipant.setMicrophoneEnabled(!e)}async setupAudioCapture(e){try{let t=new AudioContext;this.audioCaptureContext=t,this.outputAnalyser=t.createAnalyser(),this.outputAnalyser.fftSize=2048,this.outputAnalyser.smoothingTimeConstant=.8;let n=new MediaStream([e.mediaStreamTrack]),r=t.createMediaStreamSource(n);r.connect(this.outputAnalyser),await Dh(t.audioWorklet);let i=new AudioWorkletNode(t,`rawAudioProcessor`);this.outputAnalyser.connect(i),i.port.postMessage({type:`setFormat`,format:this.outputFormat.format,sampleRate:this.outputFormat.sampleRate}),i.port.onmessage=e=>{let[t,n]=e.data;if(n>.01){let e=Ch(t.buffer),n=this.audioEventId++;this.handleMessage({type:`audio`,audio_event:{audio_base_64:e,event_id:n}})}},r.connect(i)}catch(e){console.warn(`Failed to set up audio capture:`,e)}}setAudioVolume(e){this.audioElements.forEach(t=>{t.volume=e})}async setAudioOutputDevice(e){if(!(`setSinkId`in HTMLAudioElement.prototype))throw Error(`setSinkId is not supported in this browser`);let t=this.audioElements.map(async function(t){try{await t.setSinkId(e)}catch(e){throw console.error(`Failed to set sink ID for audio element:`,e),e}});await Promise.all(t),this.outputDeviceId=e}async setAudioInputDevice(e){if(!this.isConnected||!this.room.localParticipant)throw Error(`Cannot change input device: room not connected or no local participant`);try{let t=this.room.localParticipant.getTrackPublication(U.Source.Microphone);t!=null&&t.track&&(await t.track.stop(),await this.room.localParticipant.unpublishTrack(t.track));let n=await Xm({deviceId:{exact:e},echoCancellation:!0,noiseSuppression:!0,autoGainControl:!0,channelCount:{ideal:1}});await this.room.localParticipant.publishTrack(n,{name:`microphone`,source:U.Source.Microphone})}catch(e){console.error(`Failed to change input device:`,e);try{await this.room.localParticipant.setMicrophoneEnabled(!0)}catch(e){console.error(`Failed to recover microphone after device switch error:`,e)}throw e}}getOutputByteFrequencyData(){return this.outputAnalyser?(this.outputFrequencyData??=new Uint8Array(this.outputAnalyser.frequencyBinCount),this.outputAnalyser.getByteFrequencyData(this.outputFrequencyData),this.outputFrequencyData):null}};async function kh(e){let t=function(e){return e.connectionType?e.connectionType:`conversationToken`in e&&e.conversationToken?`webrtc`:`websocket`}(e);switch(t){case`websocket`:return Sh.create(e);case`webrtc`:return Oh.create(e);default:throw Error(`Unknown connection type: ${t}`)}}function Ah(){return[`iPad Simulator`,`iPhone Simulator`,`iPod Simulator`,`iPad`,`iPhone`,`iPod`].includes(navigator.platform)||navigator.userAgent.includes(`Mac`)&&`ontouchend`in document}async function jh(e={default:0,android:3e3}){let t=e.default;/android/i.test(navigator.userAgent)?t=e.android??t:Ah()&&(t=e.ios??t),t>0&&await new Promise(e=>setTimeout(e,t))}var Mh=class e extends hh{static async startSession(t){let n=hh.getFullOptions(t);n.onStatusChange&&n.onStatusChange({status:`connecting`}),n.onCanSendFeedbackChange&&n.onCanSendFeedbackChange({canSendFeedback:!1}),n.onModeChange&&n.onModeChange({mode:`listening`}),n.onCanSendFeedbackChange&&n.onCanSendFeedbackChange({canSendFeedback:!1});let r=null;try{return await jh(n.connectionDelay),r=await kh(t),new e(n,r)}catch(e){var i;throw n.onStatusChange&&n.onStatusChange({status:`disconnected`}),(i=r)==null||i.close(),e}}},Nh={echoCancellation:!0,noiseSuppression:!0,autoGainControl:!0,channelCount:{ideal:1}},Ph=class e{static async create({sampleRate:t,format:n,preferHeadphonesForIosDevices:r,inputDeviceId:i,workletPaths:a,libsampleratePath:o}){let s=null,c=null;try{let l=ph({sampleRate:{ideal:t}},Nh);if(Ah()&&r){let e=(await window.navigator.mediaDevices.enumerateDevices()).find(e=>e.kind===`audioinput`&&[`airpod`,`headphone`,`earphone`].find(t=>e.label.toLowerCase().includes(t)));e&&(l.deviceId={ideal:e.deviceId})}i&&(l.deviceId=e.getDeviceIdConstraint(i));let u=navigator.mediaDevices.getSupportedConstraints().sampleRate;s=new window.AudioContext(u?{sampleRate:t}:{});let d=s.createAnalyser();if(!u){let e=o||`https://cdn.jsdelivr.net/npm/@alexanderolsen/libsamplerate-js@2.1.2/dist/libsamplerate.worklet.js`;await s.audioWorklet.addModule(e)}await Dh(s.audioWorklet,a?.rawAudioProcessor);let f=ph({voiceIsolation:!0},l);c=await navigator.mediaDevices.getUserMedia({audio:f});let p=s.createMediaStreamSource(c),m=new AudioWorkletNode(s,`rawAudioProcessor`);return m.port.postMessage({type:`setFormat`,format:n,sampleRate:t}),p.connect(d),d.connect(m),await s.resume(),new e(s,d,m,c,p)}catch(e){var l,u;throw(l=c)==null||l.getTracks().forEach(e=>{e.stop()}),(u=s)==null||u.close(),e}}static getDeviceIdConstraint(e){if(e)return Ah()?{ideal:e}:{exact:e}}constructor(e,t,n,r,i){this.context=void 0,this.analyser=void 0,this.worklet=void 0,this.inputStream=void 0,this.mediaStreamSource=void 0,this.context=e,this.analyser=t,this.worklet=n,this.inputStream=r,this.mediaStreamSource=i}async close(){this.inputStream.getTracks().forEach(e=>{e.stop()}),this.mediaStreamSource.disconnect(),await this.context.close()}setMuted(e){this.worklet.port.postMessage({type:`setMuted`,isMuted:e})}async setInputDevice(t){try{let n=ph({},Nh);t&&(n.deviceId=e.getDeviceIdConstraint(t));let r=ph({voiceIsolation:!0},n),i=await navigator.mediaDevices.getUserMedia({audio:r});this.inputStream.getTracks().forEach(e=>{e.stop()}),this.mediaStreamSource.disconnect(),this.inputStream=i,this.mediaStreamSource=this.context.createMediaStreamSource(i),this.mediaStreamSource.connect(this.analyser)}catch(e){throw console.error(`Failed to switch input device:`,e),e}}},Fh=Eh(`audioConcatProcessor`,`/*
|
|
192
192
|
* ulaw decoding logic taken from the wavefile library
|
|
193
193
|
* https://github.com/rochars/wavefile/blob/master/lib/codecs/mulaw.js
|
|
194
194
|
* USED BY @elevenlabs/client
|
|
@@ -280,7 +280,7 @@ class AudioConcatProcessor extends AudioWorkletProcessor {
|
|
|
280
280
|
}
|
|
281
281
|
|
|
282
282
|
registerProcessor("audioConcatProcessor", AudioConcatProcessor);
|
|
283
|
-
`),Fh=class e{static async create({sampleRate:t,format:n,outputDeviceId:r,workletPaths:i}){let a=null,o=null;try{a=new AudioContext({sampleRate:t});let s=a.createAnalyser(),c=a.createGain();o=new Audio,o.src=``,o.load(),o.autoplay=!0,o.style.display=`none`,document.body.appendChild(o);let l=a.createMediaStreamDestination();o.srcObject=l.stream,c.connect(s),s.connect(l),await Ph(a.audioWorklet,i?.audioConcatProcessor);let u=new AudioWorkletNode(a,`audioConcatProcessor`);return u.port.postMessage({type:`setFormat`,format:n}),u.connect(c),await a.resume(),r&&o.setSinkId&&await o.setSinkId(r),new e(a,s,c,u,o)}catch(e){var s,c;throw(s=o)!=null&&s.parentNode&&o.parentNode.removeChild(o),(c=o)==null||c.pause(),a&&a.state!==`closed`&&await a.close(),e}}constructor(e,t,n,r,i){this.context=void 0,this.analyser=void 0,this.gain=void 0,this.worklet=void 0,this.audioElement=void 0,this.context=e,this.analyser=t,this.gain=n,this.worklet=r,this.audioElement=i}async setOutputDevice(e){if(!(`setSinkId`in HTMLAudioElement.prototype))throw Error(`setSinkId is not supported in this browser`);await this.audioElement.setSinkId(e||``)}async close(){this.audioElement.parentNode&&this.audioElement.parentNode.removeChild(this.audioElement),this.audioElement.pause(),await this.context.close()}},Ih=class e extends mh{static async startSession(t){var n;let r=mh.getFullOptions(t);r.onStatusChange&&r.onStatusChange({status:`connecting`}),r.onCanSendFeedbackChange&&r.onCanSendFeedbackChange({canSendFeedback:!1});let i=null,a=null,o=null,s=null,c=null;if((n=t.useWakeLock)==null||n)try{c=await navigator.wakeLock.request(`screen`)}catch{}try{var l;return s=await navigator.mediaDevices.getUserMedia({audio:!0}),await Ah(r.connectionDelay),a=await Oh(t),[i,o]=await Promise.all([Nh.create(fh({},a.inputFormat,{preferHeadphonesForIosDevices:t.preferHeadphonesForIosDevices,inputDeviceId:t.inputDeviceId,workletPaths:t.workletPaths,libsampleratePath:t.libsampleratePath})),Fh.create(fh({},a.outputFormat,{outputDeviceId:t.outputDeviceId,workletPaths:t.workletPaths}))]),(l=s)==null||l.getTracks().forEach(e=>{e.stop()}),s=null,new e(r,a,i,o,c)}catch(e){var u,d;r.onStatusChange&&r.onStatusChange({status:`disconnected`}),(u=s)==null||u.getTracks().forEach(e=>{e.stop()}),(d=a)==null||d.close(),await i?.close(),await o?.close();try{await c?.release(),c=null}catch{}throw e}}constructor(e,t,n,r,i){super(e,t),this.input=void 0,this.output=void 0,this.wakeLock=void 0,this.inputFrequencyData=void 0,this.outputFrequencyData=void 0,this.onInputWorkletMessage=e=>{this.status===`connected`&&this.connection.sendMessage({user_audio_chunk:Sh(e.data[0].buffer)})},this.onOutputWorkletMessage=({data:e})=>{e.type===`process`&&this.updateMode(e.finished?`listening`:`speaking`)},this.addAudioBase64Chunk=e=>{this.output.gain.gain.cancelScheduledValues(this.output.context.currentTime),this.output.gain.gain.value=this.volume,this.output.worklet.port.postMessage({type:`clearInterrupted`}),this.output.worklet.port.postMessage({type:`buffer`,buffer:Ch(e)})},this.fadeOutAudio=()=>{this.updateMode(`listening`),this.output.worklet.port.postMessage({type:`interrupt`}),this.output.gain.gain.exponentialRampToValueAtTime(1e-4,this.output.context.currentTime+2),setTimeout(()=>{this.output.gain.gain.value=this.volume,this.output.worklet.port.postMessage({type:`clearInterrupted`})},2e3)},this.calculateVolume=e=>{if(e.length===0)return 0;let t=0;for(let n=0;n<e.length;n++)t+=e[n]/255;return t/=e.length,t<0?0:t>1?1:t},this.setVolume=({volume:e})=>{let t=Number.isFinite(e)?Math.min(1,Math.max(0,e)):1;this.volume=t,this.connection instanceof Dh?this.connection.setAudioVolume(t):this.output.gain.gain.value=t},this.input=n,this.output=r,this.wakeLock=i,this.input.worklet.port.onmessage=this.onInputWorkletMessage,this.output.worklet.port.onmessage=this.onOutputWorkletMessage}async handleEndSession(){await super.handleEndSession();try{await this.wakeLock?.release(),this.wakeLock=null}catch{}await this.input.close(),await this.output.close()}handleInterruption(e){super.handleInterruption(e),this.fadeOutAudio()}handleAudio(e){var t,n;this.lastInterruptTimestamp<=e.audio_event.event_id&&((t=(n=this.options).onAudio)==null||t.call(n,e.audio_event.audio_base_64),this.connection instanceof Dh||this.addAudioBase64Chunk(e.audio_event.audio_base_64),this.currentEventId=e.audio_event.event_id,this.updateCanSendFeedback(),this.updateMode(`speaking`))}setMicMuted(e){this.connection instanceof Dh?this.connection.setMicMuted(e):this.input.setMuted(e)}getInputByteFrequencyData(){return this.inputFrequencyData??=new Uint8Array(this.input.analyser.frequencyBinCount),this.input.analyser.getByteFrequencyData(this.inputFrequencyData),this.inputFrequencyData}getOutputByteFrequencyData(){return this.connection instanceof Dh?this.connection.getOutputByteFrequencyData()||new Uint8Array(1024):(this.outputFrequencyData??=new Uint8Array(this.output.analyser.frequencyBinCount),this.output.analyser.getByteFrequencyData(this.outputFrequencyData),this.outputFrequencyData)}getInputVolume(){return this.calculateVolume(this.getInputByteFrequencyData())}getOutputVolume(){return this.calculateVolume(this.getOutputByteFrequencyData())}async changeInputDevice({sampleRate:e,format:t,preferHeadphonesForIosDevices:n,inputDeviceId:r}){try{if(this.connection instanceof xh)try{return await this.input.setInputDevice(r),this.input}catch(e){console.warn(`Failed to change device on existing input, recreating:`,e)}return this.connection instanceof Dh&&await this.connection.setAudioInputDevice(r||``),await this.input.close(),this.input=await Nh.create({sampleRate:e??this.connection.inputFormat.sampleRate,format:t??this.connection.inputFormat.format,preferHeadphonesForIosDevices:n,inputDeviceId:r,workletPaths:this.options.workletPaths,libsampleratePath:this.options.libsampleratePath}),this.input.worklet.port.onmessage=this.onInputWorkletMessage,this.input}catch(e){throw console.error(`Error changing input device`,e),e}}async changeOutputDevice({sampleRate:e,format:t,outputDeviceId:n}){try{if(this.connection instanceof xh)try{return await this.output.setOutputDevice(n),this.output}catch(e){console.warn(`Failed to change device on existing output, recreating:`,e)}return this.connection instanceof Dh&&await this.connection.setAudioOutputDevice(n||``),await this.output.close(),this.output=await Fh.create({sampleRate:e??this.connection.outputFormat.sampleRate,format:t??this.connection.outputFormat.format,outputDeviceId:n,workletPaths:this.options.workletPaths}),this.output}catch(e){throw console.error(`Error changing output device`,e),e}}},Lh=class{constructor(){this.listeners=new Map}on(e,t){this.listeners.has(e)||this.listeners.set(e,new Set);let n=this.listeners.get(e);n&&n.add(t)}off(e,t){let n=this.listeners.get(e);n&&n.delete(t)}emit(e,...t){let n=this.listeners.get(e);n&&n.forEach(e=>{e(...t)})}},Z;(function(e){e.SESSION_STARTED=`session_started`,e.PARTIAL_TRANSCRIPT=`partial_transcript`,e.COMMITTED_TRANSCRIPT=`committed_transcript`,e.COMMITTED_TRANSCRIPT_WITH_TIMESTAMPS=`committed_transcript_with_timestamps`,e.AUTH_ERROR=`auth_error`,e.ERROR=`error`,e.OPEN=`open`,e.CLOSE=`close`,e.QUOTA_EXCEEDED=`quota_exceeded`,e.COMMIT_THROTTLED=`commit_throttled`,e.TRANSCRIBER_ERROR=`transcriber_error`,e.UNACCEPTED_TERMS=`unaccepted_terms`,e.RATE_LIMITED=`rate_limited`,e.INPUT_ERROR=`input_error`,e.QUEUE_OVERFLOW=`queue_overflow`,e.RESOURCE_EXHAUSTED=`resource_exhausted`,e.SESSION_TIME_LIMIT_EXCEEDED=`session_time_limit_exceeded`,e.CHUNK_SIZE_EXCEEDED=`chunk_size_exceeded`,e.INSUFFICIENT_AUDIO_ACTIVITY=`insufficient_audio_activity`})(Z||={});var Rh=class{constructor(e){this.websocket=null,this.eventEmitter=new Lh,this.currentSampleRate=16e3,this._audioCleanup=void 0,this.currentSampleRate=e}setWebSocket(e){this.websocket=e,this.websocket.readyState===WebSocket.OPEN?this.eventEmitter.emit(Z.OPEN):this.websocket.addEventListener(`open`,()=>{this.eventEmitter.emit(Z.OPEN)}),this.websocket.addEventListener(`message`,e=>{try{let t=JSON.parse(e.data);switch(t.message_type){case`session_started`:this.eventEmitter.emit(Z.SESSION_STARTED,t);break;case`partial_transcript`:this.eventEmitter.emit(Z.PARTIAL_TRANSCRIPT,t);break;case`committed_transcript`:this.eventEmitter.emit(Z.COMMITTED_TRANSCRIPT,t);break;case`committed_transcript_with_timestamps`:this.eventEmitter.emit(Z.COMMITTED_TRANSCRIPT_WITH_TIMESTAMPS,t);break;case`auth_error`:this.eventEmitter.emit(Z.AUTH_ERROR,t),this.eventEmitter.emit(Z.ERROR,t);break;case`quota_exceeded`:this.eventEmitter.emit(Z.QUOTA_EXCEEDED,t),this.eventEmitter.emit(Z.ERROR,t);break;case`commit_throttled`:this.eventEmitter.emit(Z.COMMIT_THROTTLED,t),this.eventEmitter.emit(Z.ERROR,t);break;case`transcriber_error`:this.eventEmitter.emit(Z.TRANSCRIBER_ERROR,t),this.eventEmitter.emit(Z.ERROR,t);break;case`unaccepted_terms`:this.eventEmitter.emit(Z.UNACCEPTED_TERMS,t),this.eventEmitter.emit(Z.ERROR,t);break;case`rate_limited`:this.eventEmitter.emit(Z.RATE_LIMITED,t),this.eventEmitter.emit(Z.ERROR,t);break;case`input_error`:this.eventEmitter.emit(Z.INPUT_ERROR,t),this.eventEmitter.emit(Z.ERROR,t);break;case`queue_overflow`:this.eventEmitter.emit(Z.QUEUE_OVERFLOW,t),this.eventEmitter.emit(Z.ERROR,t);break;case`resource_exhausted`:this.eventEmitter.emit(Z.RESOURCE_EXHAUSTED,t),this.eventEmitter.emit(Z.ERROR,t);break;case`session_time_limit_exceeded`:this.eventEmitter.emit(Z.SESSION_TIME_LIMIT_EXCEEDED,t),this.eventEmitter.emit(Z.ERROR,t);break;case`chunk_size_exceeded`:this.eventEmitter.emit(Z.CHUNK_SIZE_EXCEEDED,t),this.eventEmitter.emit(Z.ERROR,t);break;case`insufficient_audio_activity`:this.eventEmitter.emit(Z.INSUFFICIENT_AUDIO_ACTIVITY,t),this.eventEmitter.emit(Z.ERROR,t);break;case`error`:this.eventEmitter.emit(Z.ERROR,t);break;default:console.warn(`Unknown message type:`,t)}}catch(t){console.error(`Failed to parse WebSocket message:`,t,e.data),this.eventEmitter.emit(Z.ERROR,Error(`Failed to parse message: ${t}`))}}),this.websocket.addEventListener(`error`,e=>{console.error(`WebSocket error:`,e),this.eventEmitter.emit(Z.ERROR,e)}),this.websocket.addEventListener(`close`,e=>{if(console.log(`WebSocket closed: code=${e.code}, reason="${e.reason}", wasClean=${e.wasClean}`),!e.wasClean||e.code!==1e3&&e.code!==1005){let t=`WebSocket closed unexpectedly: ${e.code} - ${e.reason||`No reason provided`}`;console.error(t),this.eventEmitter.emit(Z.ERROR,Error(t))}this.eventEmitter.emit(Z.CLOSE,e)})}on(e,t){this.eventEmitter.on(e,t)}off(e,t){this.eventEmitter.off(e,t)}send(e){var t;if(!this.websocket||this.websocket.readyState!==WebSocket.OPEN)throw Error(`WebSocket is not connected`);let n={message_type:`input_audio_chunk`,audio_base_64:e.audioBase64,commit:(t=e.commit)!=null&&t,sample_rate:e.sampleRate??this.currentSampleRate,previous_text:e.previousText};this.websocket.send(JSON.stringify(n))}commit(){if(!this.websocket||this.websocket.readyState!==WebSocket.OPEN)throw Error(`WebSocket is not connected`);this.websocket.send(JSON.stringify({message_type:`input_audio_chunk`,audio_base_64:``,commit:!0,sample_rate:this.currentSampleRate}))}close(){this._audioCleanup&&this._audioCleanup(),this.websocket&&this.websocket.close(1e3,`User ended session`)}},zh=Th(`scribeAudioProcessor`,`/*
|
|
283
|
+
`),Ih=class e{static async create({sampleRate:t,format:n,outputDeviceId:r,workletPaths:i}){let a=null,o=null;try{a=new AudioContext({sampleRate:t});let s=a.createAnalyser(),c=a.createGain();o=new Audio,o.src=``,o.load(),o.autoplay=!0,o.style.display=`none`,document.body.appendChild(o);let l=a.createMediaStreamDestination();o.srcObject=l.stream,c.connect(s),s.connect(l),await Fh(a.audioWorklet,i?.audioConcatProcessor);let u=new AudioWorkletNode(a,`audioConcatProcessor`);return u.port.postMessage({type:`setFormat`,format:n}),u.connect(c),await a.resume(),r&&o.setSinkId&&await o.setSinkId(r),new e(a,s,c,u,o)}catch(e){var s,c;throw(s=o)!=null&&s.parentNode&&o.parentNode.removeChild(o),(c=o)==null||c.pause(),a&&a.state!==`closed`&&await a.close(),e}}constructor(e,t,n,r,i){this.context=void 0,this.analyser=void 0,this.gain=void 0,this.worklet=void 0,this.audioElement=void 0,this.context=e,this.analyser=t,this.gain=n,this.worklet=r,this.audioElement=i}async setOutputDevice(e){if(!(`setSinkId`in HTMLAudioElement.prototype))throw Error(`setSinkId is not supported in this browser`);await this.audioElement.setSinkId(e||``)}async close(){this.audioElement.parentNode&&this.audioElement.parentNode.removeChild(this.audioElement),this.audioElement.pause(),await this.context.close()}},Lh=class e extends hh{static async startSession(t){var n;let r=hh.getFullOptions(t);r.onStatusChange&&r.onStatusChange({status:`connecting`}),r.onCanSendFeedbackChange&&r.onCanSendFeedbackChange({canSendFeedback:!1});let i=null,a=null,o=null,s=null,c=null;if((n=t.useWakeLock)==null||n)try{c=await navigator.wakeLock.request(`screen`)}catch{}try{var l;return s=await navigator.mediaDevices.getUserMedia({audio:!0}),await jh(r.connectionDelay),a=await kh(t),[i,o]=await Promise.all([Ph.create(ph({},a.inputFormat,{preferHeadphonesForIosDevices:t.preferHeadphonesForIosDevices,inputDeviceId:t.inputDeviceId,workletPaths:t.workletPaths,libsampleratePath:t.libsampleratePath})),Ih.create(ph({},a.outputFormat,{outputDeviceId:t.outputDeviceId,workletPaths:t.workletPaths}))]),(l=s)==null||l.getTracks().forEach(e=>{e.stop()}),s=null,new e(r,a,i,o,c)}catch(e){var u,d;r.onStatusChange&&r.onStatusChange({status:`disconnected`}),(u=s)==null||u.getTracks().forEach(e=>{e.stop()}),(d=a)==null||d.close(),await i?.close(),await o?.close();try{await c?.release(),c=null}catch{}throw e}}constructor(e,t,n,r,i){super(e,t),this.input=void 0,this.output=void 0,this.wakeLock=void 0,this.inputFrequencyData=void 0,this.outputFrequencyData=void 0,this.onInputWorkletMessage=e=>{this.status===`connected`&&this.connection.sendMessage({user_audio_chunk:Ch(e.data[0].buffer)})},this.onOutputWorkletMessage=({data:e})=>{e.type===`process`&&this.updateMode(e.finished?`listening`:`speaking`)},this.addAudioBase64Chunk=e=>{this.output.gain.gain.cancelScheduledValues(this.output.context.currentTime),this.output.gain.gain.value=this.volume,this.output.worklet.port.postMessage({type:`clearInterrupted`}),this.output.worklet.port.postMessage({type:`buffer`,buffer:wh(e)})},this.fadeOutAudio=()=>{this.updateMode(`listening`),this.output.worklet.port.postMessage({type:`interrupt`}),this.output.gain.gain.exponentialRampToValueAtTime(1e-4,this.output.context.currentTime+2),setTimeout(()=>{this.output.gain.gain.value=this.volume,this.output.worklet.port.postMessage({type:`clearInterrupted`})},2e3)},this.calculateVolume=e=>{if(e.length===0)return 0;let t=0;for(let n=0;n<e.length;n++)t+=e[n]/255;return t/=e.length,t<0?0:t>1?1:t},this.setVolume=({volume:e})=>{let t=Number.isFinite(e)?Math.min(1,Math.max(0,e)):1;this.volume=t,this.connection instanceof Oh?this.connection.setAudioVolume(t):this.output.gain.gain.value=t},this.input=n,this.output=r,this.wakeLock=i,this.input.worklet.port.onmessage=this.onInputWorkletMessage,this.output.worklet.port.onmessage=this.onOutputWorkletMessage}async handleEndSession(){await super.handleEndSession();try{await this.wakeLock?.release(),this.wakeLock=null}catch{}await this.input.close(),await this.output.close()}handleInterruption(e){super.handleInterruption(e),this.fadeOutAudio()}handleAudio(e){var t,n;this.lastInterruptTimestamp<=e.audio_event.event_id&&((t=(n=this.options).onAudio)==null||t.call(n,e.audio_event.audio_base_64),this.connection instanceof Oh||this.addAudioBase64Chunk(e.audio_event.audio_base_64),this.currentEventId=e.audio_event.event_id,this.updateCanSendFeedback(),this.updateMode(`speaking`))}setMicMuted(e){this.connection instanceof Oh?this.connection.setMicMuted(e):this.input.setMuted(e)}getInputByteFrequencyData(){return this.inputFrequencyData??=new Uint8Array(this.input.analyser.frequencyBinCount),this.input.analyser.getByteFrequencyData(this.inputFrequencyData),this.inputFrequencyData}getOutputByteFrequencyData(){return this.connection instanceof Oh?this.connection.getOutputByteFrequencyData()||new Uint8Array(1024):(this.outputFrequencyData??=new Uint8Array(this.output.analyser.frequencyBinCount),this.output.analyser.getByteFrequencyData(this.outputFrequencyData),this.outputFrequencyData)}getInputVolume(){return this.calculateVolume(this.getInputByteFrequencyData())}getOutputVolume(){return this.calculateVolume(this.getOutputByteFrequencyData())}async changeInputDevice({sampleRate:e,format:t,preferHeadphonesForIosDevices:n,inputDeviceId:r}){try{if(this.connection instanceof Sh)try{return await this.input.setInputDevice(r),this.input}catch(e){console.warn(`Failed to change device on existing input, recreating:`,e)}return this.connection instanceof Oh&&await this.connection.setAudioInputDevice(r||``),await this.input.close(),this.input=await Ph.create({sampleRate:e??this.connection.inputFormat.sampleRate,format:t??this.connection.inputFormat.format,preferHeadphonesForIosDevices:n,inputDeviceId:r,workletPaths:this.options.workletPaths,libsampleratePath:this.options.libsampleratePath}),this.input.worklet.port.onmessage=this.onInputWorkletMessage,this.input}catch(e){throw console.error(`Error changing input device`,e),e}}async changeOutputDevice({sampleRate:e,format:t,outputDeviceId:n}){try{if(this.connection instanceof Sh)try{return await this.output.setOutputDevice(n),this.output}catch(e){console.warn(`Failed to change device on existing output, recreating:`,e)}return this.connection instanceof Oh&&await this.connection.setAudioOutputDevice(n||``),await this.output.close(),this.output=await Ih.create({sampleRate:e??this.connection.outputFormat.sampleRate,format:t??this.connection.outputFormat.format,outputDeviceId:n,workletPaths:this.options.workletPaths}),this.output}catch(e){throw console.error(`Error changing output device`,e),e}}},Rh=class{constructor(){this.listeners=new Map}on(e,t){this.listeners.has(e)||this.listeners.set(e,new Set);let n=this.listeners.get(e);n&&n.add(t)}off(e,t){let n=this.listeners.get(e);n&&n.delete(t)}emit(e,...t){let n=this.listeners.get(e);n&&n.forEach(e=>{e(...t)})}},Z;(function(e){e.SESSION_STARTED=`session_started`,e.PARTIAL_TRANSCRIPT=`partial_transcript`,e.COMMITTED_TRANSCRIPT=`committed_transcript`,e.COMMITTED_TRANSCRIPT_WITH_TIMESTAMPS=`committed_transcript_with_timestamps`,e.AUTH_ERROR=`auth_error`,e.ERROR=`error`,e.OPEN=`open`,e.CLOSE=`close`,e.QUOTA_EXCEEDED=`quota_exceeded`,e.COMMIT_THROTTLED=`commit_throttled`,e.TRANSCRIBER_ERROR=`transcriber_error`,e.UNACCEPTED_TERMS=`unaccepted_terms`,e.RATE_LIMITED=`rate_limited`,e.INPUT_ERROR=`input_error`,e.QUEUE_OVERFLOW=`queue_overflow`,e.RESOURCE_EXHAUSTED=`resource_exhausted`,e.SESSION_TIME_LIMIT_EXCEEDED=`session_time_limit_exceeded`,e.CHUNK_SIZE_EXCEEDED=`chunk_size_exceeded`,e.INSUFFICIENT_AUDIO_ACTIVITY=`insufficient_audio_activity`})(Z||={});var zh=class{constructor(e){this.websocket=null,this.eventEmitter=new Rh,this.currentSampleRate=16e3,this._audioCleanup=void 0,this.currentSampleRate=e}setWebSocket(e){this.websocket=e,this.websocket.readyState===WebSocket.OPEN?this.eventEmitter.emit(Z.OPEN):this.websocket.addEventListener(`open`,()=>{this.eventEmitter.emit(Z.OPEN)}),this.websocket.addEventListener(`message`,e=>{try{let t=JSON.parse(e.data);switch(t.message_type){case`session_started`:this.eventEmitter.emit(Z.SESSION_STARTED,t);break;case`partial_transcript`:this.eventEmitter.emit(Z.PARTIAL_TRANSCRIPT,t);break;case`committed_transcript`:this.eventEmitter.emit(Z.COMMITTED_TRANSCRIPT,t);break;case`committed_transcript_with_timestamps`:this.eventEmitter.emit(Z.COMMITTED_TRANSCRIPT_WITH_TIMESTAMPS,t);break;case`auth_error`:this.eventEmitter.emit(Z.AUTH_ERROR,t),this.eventEmitter.emit(Z.ERROR,t);break;case`quota_exceeded`:this.eventEmitter.emit(Z.QUOTA_EXCEEDED,t),this.eventEmitter.emit(Z.ERROR,t);break;case`commit_throttled`:this.eventEmitter.emit(Z.COMMIT_THROTTLED,t),this.eventEmitter.emit(Z.ERROR,t);break;case`transcriber_error`:this.eventEmitter.emit(Z.TRANSCRIBER_ERROR,t),this.eventEmitter.emit(Z.ERROR,t);break;case`unaccepted_terms`:this.eventEmitter.emit(Z.UNACCEPTED_TERMS,t),this.eventEmitter.emit(Z.ERROR,t);break;case`rate_limited`:this.eventEmitter.emit(Z.RATE_LIMITED,t),this.eventEmitter.emit(Z.ERROR,t);break;case`input_error`:this.eventEmitter.emit(Z.INPUT_ERROR,t),this.eventEmitter.emit(Z.ERROR,t);break;case`queue_overflow`:this.eventEmitter.emit(Z.QUEUE_OVERFLOW,t),this.eventEmitter.emit(Z.ERROR,t);break;case`resource_exhausted`:this.eventEmitter.emit(Z.RESOURCE_EXHAUSTED,t),this.eventEmitter.emit(Z.ERROR,t);break;case`session_time_limit_exceeded`:this.eventEmitter.emit(Z.SESSION_TIME_LIMIT_EXCEEDED,t),this.eventEmitter.emit(Z.ERROR,t);break;case`chunk_size_exceeded`:this.eventEmitter.emit(Z.CHUNK_SIZE_EXCEEDED,t),this.eventEmitter.emit(Z.ERROR,t);break;case`insufficient_audio_activity`:this.eventEmitter.emit(Z.INSUFFICIENT_AUDIO_ACTIVITY,t),this.eventEmitter.emit(Z.ERROR,t);break;case`error`:this.eventEmitter.emit(Z.ERROR,t);break;default:console.warn(`Unknown message type:`,t)}}catch(t){console.error(`Failed to parse WebSocket message:`,t,e.data),this.eventEmitter.emit(Z.ERROR,Error(`Failed to parse message: ${t}`))}}),this.websocket.addEventListener(`error`,e=>{console.error(`WebSocket error:`,e),this.eventEmitter.emit(Z.ERROR,e)}),this.websocket.addEventListener(`close`,e=>{if(console.log(`WebSocket closed: code=${e.code}, reason="${e.reason}", wasClean=${e.wasClean}`),!e.wasClean||e.code!==1e3&&e.code!==1005){let t=`WebSocket closed unexpectedly: ${e.code} - ${e.reason||`No reason provided`}`;console.error(t),this.eventEmitter.emit(Z.ERROR,Error(t))}this.eventEmitter.emit(Z.CLOSE,e)})}on(e,t){this.eventEmitter.on(e,t)}off(e,t){this.eventEmitter.off(e,t)}send(e){var t;if(!this.websocket||this.websocket.readyState!==WebSocket.OPEN)throw Error(`WebSocket is not connected`);let n={message_type:`input_audio_chunk`,audio_base_64:e.audioBase64,commit:(t=e.commit)!=null&&t,sample_rate:e.sampleRate??this.currentSampleRate,previous_text:e.previousText};this.websocket.send(JSON.stringify(n))}commit(){if(!this.websocket||this.websocket.readyState!==WebSocket.OPEN)throw Error(`WebSocket is not connected`);this.websocket.send(JSON.stringify({message_type:`input_audio_chunk`,audio_base_64:``,commit:!0,sample_rate:this.currentSampleRate}))}close(){this._audioCleanup&&this._audioCleanup(),this.websocket&&this.websocket.close(1e3,`User ended session`)}},Bh=Eh(`scribeAudioProcessor`,`/*
|
|
284
284
|
* Scribe Audio Processor for converting microphone audio to PCM16 format
|
|
285
285
|
* USED BY @elevenlabs/client
|
|
286
286
|
*/
|
|
@@ -332,7 +332,7 @@ class ScribeAudioProcessor extends AudioWorkletProcessor {
|
|
|
332
332
|
|
|
333
333
|
registerProcessor("scribeAudioProcessor", ScribeAudioProcessor);
|
|
334
334
|
|
|
335
|
-
`),
|
|
335
|
+
`),Vh,Hh;(function(e){e.PCM_8000=`pcm_8000`,e.PCM_16000=`pcm_16000`,e.PCM_22050=`pcm_22050`,e.PCM_24000=`pcm_24000`,e.PCM_44100=`pcm_44100`,e.PCM_48000=`pcm_48000`,e.ULAW_8000=`ulaw_8000`})(Vh||={}),function(e){e.MANUAL=`manual`,e.VAD=`vad`}(Hh||={});var Uh=class e{static getWebSocketUri(t=e.DEFAULT_BASE_URI){return`${t}/v1/speech-to-text/realtime`}static buildWebSocketUri(t){let n=e.getWebSocketUri(t.baseUri),r=new URLSearchParams;if(r.append(`model_id`,t.modelId),r.append(`token`,t.token),t.commitStrategy!==void 0&&r.append(`commit_strategy`,t.commitStrategy),t.audioFormat!==void 0&&r.append(`audio_format`,t.audioFormat),t.vadSilenceThresholdSecs!==void 0){if(t.vadSilenceThresholdSecs<=.3||t.vadSilenceThresholdSecs>3)throw Error(`vadSilenceThresholdSecs must be between 0.3 and 3.0`);r.append(`vad_silence_threshold_secs`,t.vadSilenceThresholdSecs.toString())}if(t.vadThreshold!==void 0){if(t.vadThreshold<.1||t.vadThreshold>.9)throw Error(`vadThreshold must be between 0.1 and 0.9`);r.append(`vad_threshold`,t.vadThreshold.toString())}if(t.minSpeechDurationMs!==void 0){if(t.minSpeechDurationMs<=50||t.minSpeechDurationMs>2e3)throw Error(`minSpeechDurationMs must be between 50 and 2000`);r.append(`min_speech_duration_ms`,t.minSpeechDurationMs.toString())}if(t.minSilenceDurationMs!==void 0){if(t.minSilenceDurationMs<=50||t.minSilenceDurationMs>2e3)throw Error(`minSilenceDurationMs must be between 50 and 2000`);r.append(`min_silence_duration_ms`,t.minSilenceDurationMs.toString())}t.languageCode!==void 0&&r.append(`language_code`,t.languageCode),t.includeTimestamps!==void 0&&r.append(`include_timestamps`,t.includeTimestamps?`true`:`false`);let i=r.toString();return i?`${n}?${i}`:n}static connect(t){if(!t.modelId)throw Error(`modelId is required`);let n=new zh(`microphone`in t&&t.microphone?16e3:t.sampleRate),r=e.buildWebSocketUri(t),i=new WebSocket(r);return`microphone`in t&&t.microphone&&i.addEventListener(`open`,()=>{e.streamFromMicrophone(t,n)}),n.setWebSocket(i),n}static async streamFromMicrophone(e,t){try{var n,r,i;let a=await navigator.mediaDevices.getUserMedia({audio:{deviceId:e.microphone?.deviceId,echoCancellation:(n=e.microphone?.echoCancellation)==null||n,noiseSuppression:(r=e.microphone?.noiseSuppression)==null||r,autoGainControl:(i=e.microphone?.autoGainControl)==null||i,channelCount:e.microphone?.channelCount??1,sampleRate:{ideal:16e3}}}),o=new AudioContext({sampleRate:16e3});await Bh(o.audioWorklet);let s=o.createMediaStreamSource(a),c=new AudioWorkletNode(o,`scribeAudioProcessor`);c.port.onmessage=e=>{let{audioData:n}=e.data,r=new Uint8Array(n),i=``;for(let e=0;e<r.length;e++)i+=String.fromCharCode(r[e]);let a=btoa(i);t.send({audioBase64:a})},s.connect(c),o.state===`suspended`&&await o.resume(),t._audioCleanup=()=>{a.getTracks().forEach(e=>{e.stop()}),s.disconnect(),c.disconnect(),o.close()}}catch(e){throw console.error(`Failed to start microphone streaming:`,e),e}}};Uh.DEFAULT_BASE_URI=`wss://api.elevenlabs.io`;var Wh=class extends hh{static startSession(e){return e.textOnly?Mh.startSession(e):Lh.startSession(e)}},Q=`fe-vv`;function Gh(){if(typeof document>`u`||document.getElementById(`${Q}-styles`))return;let e=`
|
|
336
336
|
/* ── Action toast ───────────────────────────────────────────────────────────── */
|
|
337
337
|
#${Q}-toast {
|
|
338
338
|
position: fixed;
|
|
@@ -472,29 +472,29 @@ registerProcessor("scribeAudioProcessor", ScribeAudioProcessor);
|
|
|
472
472
|
50% { transform: translate(-4px,-4px) scale(0.82); }
|
|
473
473
|
100% { transform: translate(-4px,-4px) scale(1); }
|
|
474
474
|
}
|
|
475
|
-
`,t=document.createElement(`style`);t.id=`${Q}-styles`,t.textContent=e,(document.head||document.documentElement).appendChild(t)}var
|
|
475
|
+
`,t=document.createElement(`style`);t.id=`${Q}-styles`,t.textContent=e,(document.head||document.documentElement).appendChild(t)}var Kh=null,qh=null;function Jh(){return(!Kh||!Kh.isConnected)&&(Kh=document.createElement(`div`),Kh.id=`${Q}-toast`,document.body.appendChild(Kh)),Kh}function Yh(e,{spinner:t=!0,icon:n=null,duration:r=0}={}){if(typeof document>`u`)return;Gh(),qh&&=(clearTimeout(qh),null);let i=Jh();if(i.innerHTML=``,n){let e=document.createElement(`span`);e.className=`${Q}-icon`,e.textContent=n,i.appendChild(e)}else if(t){let e=document.createElement(`span`);e.className=`${Q}-spin`,i.appendChild(e)}let a=document.createElement(`span`);a.textContent=e,i.appendChild(a),i.classList.remove(`${Q}-show`),i.offsetHeight,i.classList.add(`${Q}-show`),r>0&&(qh=setTimeout(()=>Xh(),r))}function Xh(e=0){Kh&&(e>0?qh=setTimeout(()=>{Kh&&Kh.classList.remove(`${Q}-show`)},e):Kh&&Kh.classList.remove(`${Q}-show`))}var Zh=null,Qh=[];function $h(){return(!Zh||!Zh.isConnected)&&(Zh=document.createElement(`div`),Zh.id=`${Q}-bar`,document.body.appendChild(Zh)),Zh}function eg(){if(typeof document>`u`)return;Gh(),Qh.forEach(clearTimeout),Qh=[];let e=$h();e.style.transition=`none`,e.style.width=`0%`,e.classList.add(`${Q}-bar-active`),e.offsetHeight,e.style.transition=`width 0.35s ease, opacity 0.25s ease`;let t=[[80,`width 0.6s ease`],[92,`width 1.2s ease`]],n=50;for(let[e,r]of t){let t=n,i=e,a=r;Qh.push(setTimeout(()=>{Zh&&(Zh.style.transition=a,Zh.style.width=`${i}%`)},t)),n+=800}}function tg(){Zh&&(Qh.forEach(clearTimeout),Qh=[],Zh.style.transition=`width 0.2s ease`,Zh.style.width=`100%`,Qh.push(setTimeout(()=>{Zh&&(Zh.style.transition=`opacity 0.35s ease`,Zh.style.opacity=`0`,Qh.push(setTimeout(()=>{Zh&&(Zh.style.width=`0%`,Zh.classList.remove(`${Q}-bar-active`))},380)))},220)))}function ng(){typeof document>`u`||document.querySelectorAll(`.${Q}-field-active, .${Q}-field-filled`).forEach(e=>e.classList.remove(`${Q}-field-active`,`${Q}-field-filled`))}function rg(e){!e||typeof document>`u`||(Gh(),ng(),e.classList.add(`${Q}-field-active`))}function ig(e){e&&(e.classList.remove(`${Q}-field-active`),e.classList.add(`${Q}-field-filled`),setTimeout(()=>{e.isConnected&&e.classList.remove(`${Q}-field-filled`)},1400))}var ag=`<svg xmlns="http://www.w3.org/2000/svg" width="22" height="22" viewBox="0 0 22 22" fill="none">
|
|
476
476
|
<filter id="${Q}-csh">
|
|
477
477
|
<feDropShadow dx="1" dy="2" stdDeviation="1.5" flood-color="#00000060"/>
|
|
478
478
|
</filter>
|
|
479
479
|
<path d="M4 2L19 10.5L11 12.8L8 20L4 2Z"
|
|
480
480
|
fill="white" stroke="#1e1b4b" stroke-width="1.6" stroke-linejoin="round"
|
|
481
481
|
filter="url(#${Q}-csh)"/>
|
|
482
|
-
</svg>`,
|
|
482
|
+
</svg>`,og=null,sg=!1;function cg(){return(!og||!og.isConnected)&&(og=document.createElement(`div`),og.id=`${Q}-cursor`,og.innerHTML=ag,document.body.appendChild(og),sg=!1),og}async function lg(e){if(typeof document>`u`||!e)return;Gh();let t;try{t=e.getBoundingClientRect()}catch{return}let n=t.left+Math.min(16,t.width*.2),r=t.top+Math.min(12,t.height*.25),i=cg();sg||=(i.style.transition=`none`,i.style.left=`${window.innerWidth/2}px`,i.style.top=`${window.innerHeight*.4}px`,i.classList.add(`${Q}-cursor-visible`),i.offsetHeight,i.style.transition=`left 0.32s cubic-bezier(0.25,0.46,0.45,0.94), top 0.32s cubic-bezier(0.25,0.46,0.45,0.94), opacity 0.2s ease`,!0),i.style.left=`${n}px`,i.style.top=`${r}px`,await mg(360)}function ug(e=!1){og&&(e?(og.classList.remove(`${Q}-cursor-visible`),sg=!1):(og.classList.remove(`${Q}-cursor-visible`),setTimeout(()=>{sg=!1},250)))}async function dg(e){og&&(og.classList.add(`${Q}-cursor-click`),await mg(280),og.classList.remove(`${Q}-cursor-click`))}function fg(e){if(!e||typeof document>`u`)return;Gh();let t;try{t=e.getBoundingClientRect()}catch{return}let n=e.style.position,r=e.style.overflow,i=window.getComputedStyle(e).position;[`relative`,`absolute`,`fixed`,`sticky`].includes(i)||(e.style.position=`relative`),e.style.overflow=`hidden`;let a=document.createElement(`span`);a.className=`${Q}-ripple`;let o=Math.max(t.width,t.height)*1.2;Object.assign(a.style,{width:`${o}px`,height:`${o}px`,left:`${t.width/2-o/2}px`,top:`${t.height/2-o/2}px`}),e.appendChild(a),setTimeout(()=>{a.remove(),e.style.position=n,e.style.overflow=r},650)}async function pg(e,t,n){if(!e||!t)return;if(!(t.length<=72&&!/^https?:\/\//i.test(t)&&!/^\d+$/.test(t))){n(e,t);return}let r={bubbles:!0,cancelable:!0,composed:!0};n(e,``),e.dispatchEvent(new Event(`input`,r));for(let i=1;i<=t.length;i++){n(e,t.slice(0,i));try{e.dispatchEvent(new InputEvent(`input`,{...r,inputType:`insertText`,data:t[i-1]}))}catch{e.dispatchEvent(new Event(`input`,r))}await mg(28+Math.random()*27)}e.dispatchEvent(new Event(`change`,r))}function mg(e){return new Promise(t=>setTimeout(t,e))}function hg(e){return(...t)=>{try{let n=e(...t);return n instanceof Promise?n.catch(()=>{}):n}catch{return}}}var gg=hg(Yh),_g=hg(Xh),vg=hg(eg),yg=hg(tg),bg=hg(rg),xg=hg(ig),Sg=hg(ng),Cg=hg(lg),wg=hg(ug),Tg=hg(dg),Eg=hg(fg);function $(...e){Yt()&&console.log(`[FlowEngage:voice-tools]`,...e)}var Dg=`#flowengage-root, .flowengage-shell`;function Og(e){if(!e||typeof e.closest!=`function`)return!1;try{return!!e.closest(Dg)}catch{return!1}}var kg=new Set([`SCRIPT`,`STYLE`,`NOSCRIPT`,`SVG`,`CANVAS`,`VIDEO`,`AUDIO`,`IFRAME`,`OBJECT`,`EMBED`,`NAV`,`FOOTER`]);function Ag(e,t=3e3){if(!e)return``;let n=[],r=0;function i(e){if(r>=t)return;if(e.nodeType===Node.TEXT_NODE){let t=e.textContent.replace(/\s+/g,` `).trim();t&&(n.push(t),r+=t.length);return}if(e.nodeType!==Node.ELEMENT_NODE||kg.has(e.tagName)||Og(e))return;try{let t=Fg(e);if(t.display===`none`||t.visibility===`hidden`)return}catch{}let a=/^(P|H[1-6]|DIV|SECTION|ARTICLE|LI|TR|BLOCKQUOTE|PRE|HEADER|DT|DD|FIGCAPTION)$/.test(e.tagName);a&&n.length>0&&n.push(`
|
|
483
483
|
`);for(let n of e.childNodes)if(i(n),r>=t)break;a&&n.push(`
|
|
484
484
|
`)}i(e);let a=n.join(` `).replace(/[ \t]+/g,` `).replace(/\n /g,`
|
|
485
485
|
`).replace(/\n{3,}/g,`
|
|
486
486
|
|
|
487
|
-
`).trim();return a.length>t&&(a=a.slice(0,t).replace(/\s\S*$/,``)+`…`),a}function Ag(){if(typeof document>`u`)return null;for(let e of[`main`,`article`,`[role="main"]`,`#content`,`#main-content`,`#main`,`.main-content`,`.content`,`.post-content`,`.article-content`,`.entry-content`]){let t=document.querySelector(e);if(t&&!Dg(t))return t}return document.body}function jg(e){if(!e||typeof e.querySelector!=`function`)return e;let t=e.querySelector([`.post-content`,`.entry-content`,`.article-body`,`[itemprop='articleBody']`,`.article__body`,`.field-item`,`.field--name-body`,`.field--body`,`.node__content`].join(`, `));return t&&!Dg(t)?t:e}function Mg(e){if(!e)return null;try{return e.closest(`form`)}catch{let t=e.parentElement;for(;t;){if(t.tagName===`FORM`)return t;t=t.parentElement}return null}}function Ng(e){if(!e)return null;let t=e.querySelector(`h1, h2, h3, h4, h5, legend`);if(t)return t.textContent.replace(/\s+/g,` `).trim().slice(0,60);let n=e.getAttribute(`aria-label`);if(n)return n.trim().slice(0,60);let r=e.getAttribute(`title`);if(r)return r.trim().slice(0,60);let i=e.previousElementSibling;for(let e=0;e<3&&i;e++){if(/^H[1-5]$/.test(i.tagName))return i.textContent.replace(/\s+/g,` `).trim().slice(0,60);i=i.previousElementSibling}return null}function Pg(e){try{let t=e.ownerDocument?.defaultView;if(t)return t.getComputedStyle(e)}catch{}return window.getComputedStyle(e)}function Fg(e){let t=new Set;function n(r){if(!r||t.has(r))return;t.add(r),e(r);let i=r.querySelectorAll(`iframe`);for(let e of i)if(!Dg(e))try{let t=e.contentDocument;t&&n(t)}catch{}}typeof document<`u`&&n(document)}function Ig(e){return e==null?null:String(e).replace(/\u00a0/g,` `).replace(/\s*\*+\s*$/u,``).replace(/\s+/g,` `).trim()}function Lg(e){let t=e.ownerDocument||document,n=e.getAttribute(`aria-labelledby`);if(n){let e=n.trim().split(/\s+/).filter(Boolean),r=[];for(let n of e)try{let e=t.getElementById(n);e?.textContent&&r.push(e.textContent.trim())}catch{}if(r.length)return Ig(r.join(` `))}if(e.labels&&e.labels.length)return Ig(e.labels[0].textContent);let r=e.id;if(r)try{let e=t.querySelector(`label[for="${CSS.escape(r)}"]`);if(e)return Ig(e.textContent)}catch{let e=t.querySelector(`label[for="${r.replace(/"/g,`\\"`)}"]`);if(e)return Ig(e.textContent)}let i=e.previousElementSibling;for(let e=0;e<6&&i;e+=1){if(i.tagName===`LABEL`)return Ig(i.textContent);let e=(i.className||``).toString().toLowerCase();if(/chakra-form__label|formlabel|field-label|form-label|mui-form-label/.test(e)){let e=Ig(i.textContent);if(e)return e}i=i.previousElementSibling}let a=e.parentElement;for(let e=0;e<5&&a;e+=1){if(a.tagName===`LABEL`)return Ig(a.textContent);let e=a.querySelector?.(`:scope > label, :scope > [class*='FormLabel'], :scope > [class*='form__label']`);if(e?.textContent)return Ig(e.textContent);a=a.parentElement}let o=e.getAttribute(`aria-label`);return o?Ig(o):null}function Rg(){let e=[];return Fg(t=>{e.push(...Array.from(t.querySelectorAll(`input, select, textarea`)).filter(e=>{if(Dg(e))return!1;let t=(e.type||``).toLowerCase();if([`hidden`,`submit`,`button`,`image`].includes(t)||e.disabled||e.readOnly)return!1;try{let t=Pg(e);if(t.display===`none`||t.visibility===`hidden`||parseFloat(t.opacity)===0)return!1}catch{}try{if(e.offsetWidth===0&&e.offsetHeight===0)return!1}catch{}return!0}))}),e}function zg(e){if(!e||typeof e.closest!=`function`)return!1;try{return!!e.closest(`footer, [role="contentinfo"], #footer, .site-footer, [class*="footer"], [id*="footer"]`)}catch{return!1}}function Bg(){let e=Rg();for(let t of e){if((t.type||``).toLowerCase()!==`email`||zg(t))continue;let e=Mg(t);if(e)return e}return null}function Vg(){let e=Rg(),t=new Map,n=0;return e.map((e,r)=>{let i=Mg(e),a=i||`__orphan__`;t.has(a)||t.set(a,n++);let o=t.get(a);return{formIndex:o,formName:(i?Ng(i):null)||`Form ${o}`,fieldIndex:r,tag:e.tagName,type:e.type||`text`,name:e.name||null,id:e.id||null,label:Lg(e),placeholder:e.placeholder||null}})}function Hg(e){if(Dg(e)||e.disabled)return!1;try{let t=Pg(e);if(t.display===`none`||t.visibility===`hidden`||parseFloat(t.opacity)===0)return!1}catch{}return!0}function Ug(){let e=[];return Fg(t=>{e.push(...Array.from(t.querySelectorAll(`button, [role="button"], input[type="submit"], input[type="button"]`)).filter(Hg)),e.push(...Array.from(t.querySelectorAll(`a[href]`)).filter(e=>{if(!Hg(e))return!1;let t=(e.textContent||``).replace(/\s+/g,` `).trim();return!(!t||t.length<2||t.length>150)}))}),e.slice(0,60).map((e,t)=>({index:t,text:(e.textContent||e.value||``).replace(/\s+/g,` `).trim().slice(0,120)||null,ariaLabel:e.getAttribute(`aria-label`),type:e.type||e.tagName}))}function Wg(e){return String(e||``).toLowerCase().replace(/\u00a0/g,` `).replace(/\*/g,``).replace(/\s+/g,` `).trim()}function Gg(e){let t=Wg(e);return t=t.replace(/\s+field\s*$/i,``).trim(),t}function Kg(e,t){let n=Gg(t);if(!n)return 0;let r=(e.name||``).toLowerCase(),i=(e.id||``).toLowerCase();if(r===`url`&&/url|website|domain|audit|conduct|site(\s|$)|page(\s|$)/.test(n)&&!/email|e-mail|mail|name|message|phone/.test(n)||(i===`url-input`||i.endsWith(`-url-input`))&&/url|website|domain|audit|conduct/.test(n)&&!/email|e-mail|mail|name|message|phone/.test(n))return 100;let a=(e.type||``).toLowerCase();if(a===`email`&&/email|e-mail|mail/.test(n))return 100;if(a===`tel`&&/phone|mobile|tel|cell/.test(n))return 95;if(a===`url`&&/url|website|domain|link/.test(n))return 100;let o=[e.name,e.id,e.placeholder,Lg(e),e.getAttribute(`aria-label`),e.getAttribute(`title`),e.getAttribute(`data-testid`),e.getAttribute(`autocomplete`)].filter(Boolean).map(e=>Wg(e)),s=0;for(let e of o){if(!e)continue;if(e===n){s=100;break}if(e.includes(n)||n.includes(e)){s=Math.max(s,96);continue}let t=n.split(/\s+/).filter(e=>e.length>1);if(!t.length)continue;let r=0;for(let n of t)e.includes(n)&&(r+=1);let i=r/t.length;i>0&&(s=Math.max(s,i*88))}return s}var qg=22;function Jg(e,t){let n=null,r=0;for(let i of e){let e=Kg(i,t);e>r&&(r=e,n=i)}return!n||r<qg?null:n}function Yg(e,t,n){let r=String(t||``).toLowerCase().trim(),i=String(n||``).trim();if(/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(i)||!(/^https?:\/\//i.test(i)||/\.\w{2,}(\/|\s|$)/.test(i)||r.includes(`url`)||r.includes(`website`)||r.includes(`domain`)||r.includes(`site`)))return null;let a=null,o=0;for(let t of e){if(t.tagName!==`INPUT`&&t.tagName!==`TEXTAREA`)continue;let e=(t.type||``).toLowerCase();if([`hidden`,`submit`,`button`,`checkbox`,`radio`].includes(e))continue;let n=0;(e===`url`||e===`text`||e===`search`)&&(n+=45);let r=[t.name,t.id,t.placeholder,Lg(t),t.getAttribute(`aria-label`),t.getAttribute(`autocomplete`)].filter(Boolean).join(` `).toLowerCase();/(website|url|domain|site\s*url)/.test(r)&&(n+=55),n>o&&(o=n,a=t)}return!a||o<42?null:a}function Xg(e){let t=String(e??``).trim();return!t||/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(t)?!1:/^https?:\/\//i.test(t)?!0:/\.\w{2,}(\/|\s|$)/.test(t)}function Zg(e){let t=String(e??``).toLowerCase().trim();return t?!!(t===`url`||t===`website`||t===`website url`||t===`website_url`||t===`enter website url`||t.includes(`website`)||t.includes(`domain`)||/(enter\s+website|site\s*url|page\s*url)/.test(t)):!1}function Qg(e){if(!e||e.tagName!==`INPUT`&&e.tagName!==`TEXTAREA`)return!1;let t=(e.type||``).toLowerCase();return![`hidden`,`submit`,`button`,`checkbox`,`radio`,`file`].includes(t)}function $g(e){if(!Qg(e))return!1;let t=(e.name||``).toLowerCase(),n=(e.id||``).toLowerCase(),r=[e.name,e.id,e.placeholder,Lg(e),e.getAttribute(`aria-label`)].filter(Boolean).join(` `).toLowerCase();return t===`url`||n===`url-input`||n.endsWith(`-url-input`)||/(website\s*url|enter\s+website|site\s*url)/.test(r)||/(website|domain)/.test(r)&&/(url|site)/.test(r)}function e_(e,t,n){let r=String(t??``),i=String(n??``),a=r_(e,r)||Jg(e,r)||Yg(e,r,i);if(!a)return[];let o=new Set([a]);if(Xg(i)&&Zg(r))for(let t of e)t!==a&&$g(t)&&o.add(t);let s=Array.from(o);return s.sort((e,t)=>{if(e===t)return 0;let n=e.compareDocumentPosition(t);return n&Node.DOCUMENT_POSITION_FOLLOWING?-1:n&Node.DOCUMENT_POSITION_PRECEDING?1:0}),s}function t_(e,t){try{if(!e?.getBoundingClientRect||!t?.getBoundingClientRect)return 1/0;let n=e.getBoundingClientRect(),r=t.getBoundingClientRect(),i={x:n.left+n.width/2,y:n.top+n.height/2},a={x:r.left+r.width/2,y:r.top+r.height/2};return Math.hypot(i.x-a.x,i.y-a.y)}catch{return 1/0}}function n_(e){if(!e||typeof e!=`string`)return null;let t=null;return Fg(n=>{try{let r=n.getElementById(e);r&&!Dg(r)&&r.matches?.(`input, select, textarea`)&&(t=r)}catch{}}),t}function r_(e,t){let n=String(t??``).trim();if(!n)return null;let r=n.match(/^name:\s*([\w.-]+)$/i);if(r){let t=r[1];for(let n of e)if(n.name===t)return n}let i=n.match(/^id:\s*([\w.-]+)$/i);if(i){let e=n_(i[1]);if(e)return e}let a=n.startsWith(`#`)?n.slice(1):n;if(/^[\w-]+$/.test(a)){let e=n_(a);if(e)return e}let o=n.toLowerCase().replace(/\s+/g,` `);if(o===`url`||o===`website`||o===`website url`||o===`website_url`||o===`enter website url`)for(let t of e){let e=(t.name||``).toLowerCase(),n=(t.id||``).toLowerCase();if(e===`url`||n===`url-input`||n.endsWith(`-url-input`))return t}return null}function i_(e,t){let n=String(t||``).toLowerCase().trim();if(!n)return 0;let r=[e.textContent,e.value,e.getAttribute(`aria-label`),e.getAttribute(`title`)].filter(Boolean).join(` `).toLowerCase().replace(/\s+/g,` `);if(r===n)return 100;if(r.includes(n))return 98;let i=n.split(/\s+/).filter(e=>e.length>1);if(!i.length)return 0;let a=0;for(let e of i)r.includes(e)&&(a+=1);return a/i.length*92}function a_(e,t){let n=[];Fg(e=>{n.push(...Array.from(e.querySelectorAll(`button, [role="button"], input[type="submit"], input[type="button"]`)).filter(Hg)),n.push(...Array.from(e.querySelectorAll(`a[href]`)).filter(e=>{if(!Hg(e))return!1;let t=(e.textContent||``).replace(/\s+/g,` `).trim();return!(!t||t.length<2||t.length>150)}))});let r=0,i=n.map(t=>({el:t,s:i_(t,e)}));for(let{s:e}of i)e>r&&(r=e);let a=e.split(/\s+/).filter(e=>e.length>1).length>=3?28:36;if(r<a)return null;let o=i.filter(({s:e})=>e===r).map(({el:e})=>e);if(o.length===1)return o[0];let s=Array.isArray(t)?t.filter(e=>e&&e.isConnected):[];if(s.length){let e=o[0],t=1/0;for(let n of o)for(let r of s){let i=t_(n,r);i<t&&(t=i,e=n)}return e}return o[0]}function o_(e){if(e==null)return{};if(typeof e==`string`){let t=e.trim();if(!t)return{};try{return JSON.parse(t)}catch{return{url:t}}}return e}function s_(e){let t=o_(e);if(Array.isArray(t)&&t.length>0){let e=t[0];if(e?.field_key!=null||e?.fieldKey!=null)return t.map(e=>({field_key:e.field_key??e.fieldKey,value:e.value}))}if(!t||typeof t!=`object`)return[];let n=t.fields??t.Fields??t.field_list??t.fieldList??t.data?.fields;if(typeof n==`string`)try{n=JSON.parse(n)}catch{n=null}n&&!Array.isArray(n)&&typeof n==`object`&&(n=Object.values(n)),(!n||n.length===0)&&(t.field_key!=null||t.fieldKey!=null)&&t.value!=null&&(n=[{field_key:t.field_key??t.fieldKey,value:t.value}]);let r=t.website_url??t.websiteUrl??t.url??t.website??t.domain??t.site_url??t.siteUrl;return(!n||n.length===0)&&r!=null&&String(r).trim()&&(n=[{field_key:t.field_key??t.fieldKey??`url`,value:String(r).trim()}]),Array.isArray(n)?n.map(e=>({field_key:e?.field_key??e?.fieldKey,value:e?.value??e?.Value})):[]}function c_(e){if(!e||typeof e!=`string`)return e;let t=e.trim();return/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(t)?t:(t=t.replace(/\s+at\s+the\s+rate\s*(of)?\s+/gi,`@`),t=t.replace(/\s+at\s+/gi,`@`),t=t.replace(/\s+dot\s+/gi,`.`),t=t.replace(/\s+/g,``),t=t.replace(/\.{2,}/g,`.`).replace(/\.$/,``),t)}function l_(e){if(!e||typeof e!=`string`)return e;let t={zero:`0`,one:`1`,two:`2`,three:`3`,four:`4`,five:`5`,six:`6`,seven:`7`,eight:`8`,nine:`9`,oh:`0`,o:`0`},n=e.toLowerCase().trim();for(let[e,r]of Object.entries(t))n=n.replace(RegExp(`\\b${e}\\b`,`g`),r);return n=n.replace(/[^\d+]/g,``),n}function u_(e){if(!e||typeof e!=`string`)return[];let t=e.trim();if(!t||/\b[a-z0-9._%+-]+@[a-z0-9.-]+\.[a-z]{2,}\b/i.test(t))return[];let n=t.match(/https?:\/\/[^\s<>"']+/i);if(n)return[{field_key:`url`,value:n[0].replace(/[.,;:)]+$/,``)}];let r=t.match(/\b(?:[\w-]+\.)+[a-z]{2,}\b/i);if(r){let e=r[0].replace(/[.,;:)]+$/,``);return/^https?:/i.test(e)||(e=`https://${e}`),[{field_key:`url`,value:e}]}return[]}function d_(e){if(!e||typeof e!=`string`)return[];let t=e.trim();if(!t)return[];let n=[],r=new Set,i=/\b([a-z0-9._%+-]+@[a-z0-9.-]+\.[a-z]{2,})\b/i,a=(e,t)=>{let i=String(t??``).trim().replace(/^["']|["']$/g,``);if(!i||i.length>800)return;let a=`${e}\0${i}`;r.has(a)||(r.add(a),n.push({field_key:e,value:i}))},o=c_(t),s=i.test(o),c=o.match(/^\s*([a-z0-9._%+-]+@[a-z0-9.-]+\.[a-z]{2,})\s*$/i);if(c)return a(`Email Address`,c[1]),n;if(!i.test(t)&&s){let e=o.match(i);if(e)return a(`Email Address`,e[1]),n}let l=t.match(/\b(?:please\s+)?(?:enter|type|put)\s+(.+?)\s+in(?:to)?\s+(?:the\s+)?(?:full\s*name|full\s*name\s*field|name\s*field)\b/i);if(l&&a(`Full Name`,l[1]),l=t.match(/\bfull\s*name,?\s*(?:please\s+)?(?:enter|type|put)\s+(.+?)(?:\.|$|!|\?)/i),l&&a(`Full Name`,l[1]),l=t.match(/\bfull\s*name\s*(?:is|:|please\s+enter|-)\s*(.+?)(?:\.|$|(?=\s+(?:and|my\s+email|email|message))\b)/i),l&&a(`Full Name`,l[1]),l=t.match(/\b(.+?)\s+for\s+(?:the\s+)?full\s*name\b/i),l){let e=l[1].trim();e.length>1&&e.length<120&&!/@/.test(e)&&a(`Full Name`,e)}if(l=t.match(/\b(?:email|e-mail)(?:\s*address)?\s*(?:is|:|please\s+use|enter|-)\s*([^\s@]+@[^\s@]+\.[^\s,]+)/i),l&&a(`Email Address`,l[1]),l=t.match(/\b(?:enter|type|put)\s+([^\s@]+@[^\s@]+\.[^\s,]+)\s+in(?:to)?\s+(?:the\s+)?(?:email|e-mail)/i),l&&a(`Email Address`,l[1]),l=t.match(/\b(?:message|comment)\s*(?:is|:|please\s+enter|-)\s*(.+)$/is),l){let e=l[1].trim();e.length>0&&a(`Message`,e)}if(!n.some(e=>/email/i.test(String(e.field_key)))){let e=t.match(i);if(e){let r=t.replace(e[0],``).trim().replace(/^(please|it's|it is|use|is|my email is|e-?mail is)\s*/i,``).replace(/[.,;:!?]+$/,``).trim();if(t.length<=96&&r.length<=36)return a(`Email Address`,e[1]),n}}if(n.length===0){let e=t.split(/\s+/).filter(Boolean).length,n=/[.!?]/.test(t)||e>=6||t.length>=24&&e>=5||t.length>=42,r=/^[A-Z][a-z]+\s+[A-Z][a-z]+$/.test(t.trim());n&&t.length>=16&&!i.test(t)&&!r&&a(`Message`,t)}return n}function f_(e){if(!e||typeof e!=`object`)return null;let t=e.url??e.target_url??e.page_url??e.pageUrl??e.link??e.href??e.path;return t==null?null:String(t).trim()||null}function p_(e){if(!e||typeof e!=`object`)return null;let t=e.query??e.q??e.search??e.text??e.keywords??e.search_query??e.searchQuery??e.question??e.prompt??e.topic??e.intent;return t==null?null:String(t).trim()||null}function m_(e){let t=e.ownerDocument?.defaultView||window,n=e.tagName===`TEXTAREA`?t.HTMLTextAreaElement.prototype:t.HTMLInputElement.prototype,r=Object.getOwnPropertyDescriptor(n,`value`);return(e,t)=>{try{e._valueTracker&&e._valueTracker.setValue(``)}catch{}r?.set?r.set.call(e,t):e.value=t}}async function h_(e,t,n){if(!n?.skipScroll)try{e.scrollIntoView({behavior:`smooth`,block:`center`,inline:`nearest`})}catch{try{e.scrollIntoView(!0)}catch{}}try{await Sg(e)}catch{}try{yg(e)}catch{}await new Promise(e=>setTimeout(e,180));try{e.focus({preventScroll:!0})}catch{try{e.focus()}catch{}}let r=e.tagName,i=(e.type||``).toLowerCase(),a={bubbles:!0,cancelable:!0,composed:!0};if(r===`SELECT`)return e.value=String(t),e.dispatchEvent(new Event(`input`,a)),e.dispatchEvent(new Event(`change`,a)),e.dispatchEvent(new Event(`blur`,a)),bg(e),!0;if(i===`checkbox`||i===`radio`)return e.checked=[`1`,`true`,`yes`,`on`].includes(String(t).toLowerCase().trim()),e.dispatchEvent(new Event(`input`,a)),e.dispatchEvent(new Event(`change`,a)),bg(e),!0;let o=String(t);if(r===`INPUT`||r===`TEXTAREA`){let t=m_(e);try{await fg(e,o,t)}catch{t(e,o)}e.value!==o&&t(e,o)}else e.value=o;try{e.dispatchEvent(new InputEvent(`input`,{...a,inputType:`insertText`,data:o}))}catch{e.dispatchEvent(new Event(`input`,a))}e.dispatchEvent(new Event(`change`,a)),e.dispatchEvent(new Event(`blur`,a));try{e.focus({preventScroll:!0})}catch{}try{queueMicrotask(()=>{try{e.dispatchEvent(new Event(`input`,a)),e.dispatchEvent(new Event(`change`,a))}catch{}})}catch{}return bg(e),!0}function g_(e){let t=e.siteId||null,n=(e.apiBaseUrl||``).replace(/\/$/,``),r=e.voicePageHighlightMode||`speech`,i=typeof e.getLastUserVoiceText==`function`?e.getLastUserVoiceText:null,a=[],o=null,s={navigate_to_page:async n=>{$(`navigate_to_page ▶ raw parameters:`,n);let i=o_(n),a=f_(i),o=i.section_text??i.sectionText??i.section;if($(`navigate_to_page · coerced:`,{url:a,sectionText:o}),!a){let e=`Missing url: pass a string url, path like /pricing, or JSON with a url field.`;return $(`navigate_to_page ✖`,e),e}let s=typeof window<`u`?vn(a):a;if(hg(`Navigating to ${String(s).replace(/^https?:\/\/[^/]+/,``)||`/`}…`),_g(),!await bn(s,{siteId:t,apiBaseUrl:e.apiBaseUrl})){vg(),gg(200);let e=`That page is not available in the site index; answer without navigating.`;return $(`navigate_to_page ✖ blocked`,e),e}try{if($(`navigate_to_page → shadowNavigate`,s),await Sn(s,{sectionText:o||void 0}),await new Promise(e=>setTimeout(e,600)),vg(),gg(300),o&&typeof o==`string`&&r!==`off`){let e=rn(null,o);e&&gn(e,{speaking:!0,scroll:!0}),$(`navigate_to_page · highlight`,{sectionText:o,found:!!e})}let e=``;try{let t=Vg(),n=Ug();if(t.length>0){let r=t.map(e=>e.label||e.placeholder||e.name||e.id).filter(Boolean).join(`, `),i=n.map(e=>e.text).filter(Boolean).join(`, `);e=` This page has a form with fields: [${r}]`+(i?` and buttons: [${i}].`:`.`)+` Call list_page_forms then start filling.`}}catch{}let t=`OK_NAVIGATION ${s}${e}`;return $(`navigate_to_page ✓`,t),t}catch(e){vg(),gg(200);let t=`Navigation error: ${e?.message||String(e)}`;return $(`navigate_to_page ✖`,t),t}},highlight_on_page:async t=>{if($(`highlight_on_page ▶`,t),r===`off`)return $(`highlight_on_page · skipped (voicePageHighlightMode=off)`),`OK_HIGHLIGHT page highlighting is disabled.`;let n=o_(t),i=n?.section_id||n?.sectionId,a=n?.section_text||n?.sectionText,o=rn(i||null,a||null);if(!o)return $(`highlight_on_page ✖ no element`),`Could not find that section on the page.`;gn(o,{speaking:!0,scroll:!0});try{e.markExplicitToolHighlight?.()}catch{}return $(`highlight_on_page ✓ (speaking)`),`OK_HIGHLIGHT section is now highlighted and scrolled into view.`},search_site_content:async e=>{$(`search_site_content ▶`,e);let r=p_(o_(e));if($(`search_site_content · query:`,r,`siteId:`,t,`apiBase:`,n||`(empty)`),hg(`Searching site content…`,{spinner:!0}),!r)return gg(),$(`search_site_content ✖ missing query`),`Missing query parameter.`;if(!t)return gg(),$(`search_site_content ✖ no siteId`),`Site is not configured for search.`;if(!n)return gg(),$(`search_site_content ✖ no api base`),`API base URL is missing; cannot search.`;try{let e=`${n}/api/site-tools/search`;$(`search_site_content → POST`,e);let i=await fetch(e,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({siteId:t,query:r,currentUrl:typeof window<`u`?window.location.href:``})}),a=await i.json();if($(`search_site_content · HTTP`,i.status,`success:`,a.success),gg(200),!a.success){let e=a.error||`Search failed.`;return $(`search_site_content ✖`,e),e}let o=a.results||[];return $(`search_site_content ✓`,`${o.length} result(s)`,o.slice(0,3).map(e=>e?.url||e)),JSON.stringify(o)}catch(e){gg();let t=`Search error: ${e.message||`network`}`;return $(`search_site_content ✖`,t),t}},read_page_content:async t=>{$(`read_page_content ▶`,t);let n=o_(t),i=n?.section_text||n?.sectionText,a=3e3;try{if(i){let t=rn(null,i);if(!t){let e=String(i).trim().split(/\s+/).filter(e=>e.length>2);for(let n=Math.min(e.length,5);n>=2&&!t;n--)t=rn(null,e.slice(0,n).join(` `))}if(!t)return`Could not find a section matching "${i}" on this page. Try navigate_to_page or click_page_button with the article title, then read_page_content again.`;if(r!==`off`){gn(t,{speaking:!0,scroll:!0});try{e.markExplicitToolHighlight?.()}catch{}}let n=kg(t,a);if(!n)return`Found the section but it appears to be empty.`;$(`read_page_content ✓ section:`,n.length,`chars`);try{e.markHostPageReading?.()}catch{}return`OK_READ: ${n}`}let t=jg(Ag());if(!t)return`Could not determine the main content area of this page.`;let n=kg(t,a);if(!n)return`The page appears to have no readable text content.`;$(`read_page_content ✓ page:`,n.length,`chars`);try{e.markHostPageReading?.()}catch{}return`OK_READ: ${n}`}catch(e){return $(`read_page_content ✖`,e?.message),`Error reading page content: ${e?.message||`unknown error`}`}},end_voice_session:async()=>($(`end_voice_session ▶`),hg(`Ending voice session…`,{icon:`👋`,spinner:!1,duration:2e3}),Cg(!0),xg(),typeof e.requestEndSession==`function`&&e.requestEndSession(),`Voice session is ending.`),list_page_forms:async()=>{let e=Vg(),t=Ug();return $(`list_page_forms ✓`,`${e.length} field(s)`,`${t.length} button(s)`),o=Bg(),$(`list_page_forms · activeFormAncestor`,o?`contact-preferring`:`none`),JSON.stringify({fields:e,buttons:t,hint:`Fields are grouped by formIndex/formName. Work with ONE form at a time — only fill fields from the same formIndex. Do not jump to fields in a different form. On pages with a contact form AND a footer or secondary website-URL field: only use the contact form unless the visitor explicitly asks to use the URL or promo flow. Contact forms: fill in order Full Name → Email Address → Message. Message must be a short note the visitor wants to send (one or two sentences), never a recap of the whole chat or assistant replies. field_key: use placeholder, label, name, or id from this list. click_page_button picks the button nearest the filled fields (e.g. Send Message on the same form).`})},fill_form_fields:async e=>{try{$(`fill_form_fields ▶ raw:`,e);let t=s_(e);if(!t.length&&i){let e=i(),n=u_(e);n.length?$(`fill_form_fields · inferred URL from last user utterance (model omitted usable fields):`,n):(n=d_(e),n.length&&$(`fill_form_fields · inferred contact fields from last user utterance (empty tool params):`,n)),n.length&&(t=n)}if($(`fill_form_fields · normalized fields:`,t),!t.length)return`No fields provided. Call list_page_forms for field_key strings, then fill_form_fields with { "fields": [ { "field_key": "<label or placeholder from list>", "value": "<user value>" } ] }. Never use empty {}. Pass the value the user just said (email, message, name, URL) in fields.`;t.length>1&&hg(`Filling ${t.length} fields…`);let n=[];for(let e of t){let t=e?.field_key??e?.fieldKey,r=e?.value;if(t==null||r==null)continue;let i=String(t).toLowerCase();if(/email|e-mail|mail/.test(i))r=c_(r);else if(/phone|mobile|tel|cell/.test(i))r=l_(r);else if(Zg(t)||i===`url`){let e=String(r??``).trim();if(/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(e)||/\bat\b/i.test(e)&&/\bdot\b/i.test(e)){let n=c_(e);/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(n.trim())&&($(`fill_form_fields · remapping url/website intent to Email Address (value is an email)`),t=`Email Address`,i=`email address`,r=n.trim())}}hg(`Filling ${t}…`),$(`fill_form_fields · processing field:`,t,`=`,r);let s=Rg(),c=s;if(o){let e=s.filter(e=>Mg(e)===o);e.length>0&&(c=e,$(`fill_form_fields · scoped to active form, inputs:`,e.length))}$(`fill_form_fields · visible inputs count:`,s.length,`scoped:`,c.length);let l=!1;for(let e of[c,...c===s?[]:[s]]){let i=e_(e,String(t),r);if(i.length){for(let e=0;e<i.length;e++)await h_(i[e],r,{skipScroll:e>0}),await new Promise(e=>setTimeout(e,80));a=i,o=Mg(i[0])||o,n.push(String(t)),l=!0;break}let s=r_(e,String(t));if(s||=Jg(e,String(t)),s||=Yg(e,String(t),r),s){await h_(s,r),a=[s],o=Mg(s)||o,n.push(String(t)),l=!0;break}}l||$(`fill_form_fields · no match for field:`,t)}gg(400);try{Cg()}catch{}if(!n.length)return $(`fill_form_fields ✖ no matches`),`Could not match any fields. Call list_page_forms and use field_key values that match placeholder, label, name, or id (e.g. Enter Website URL). Ensure the form is on the page, not the chat panel.`;let r=`OK_FILLED: ${n.join(`, `)}`;return $(`fill_form_fields ✓`,r),r}catch(e){gg(),xg(),Cg(!0);let t=`fill_form_fields error: ${e?.message||String(e)}`;return $(`fill_form_fields ✖`,t),t}},click_page_button:async e=>{let t=o_(e),n=(t.button_text??t.buttonText??t.text??``).trim();if($(`click_page_button ▶`,n),!n)return`Missing button_text: pass the visible label, e.g. Submit or Read more.`;hg(`Clicking "${n}"…`);let r=a_(n,a);if(!r)return gg(200),$(`click_page_button ✖ no match`),`Could not find a button matching "${n}". Call list_page_forms to see button texts.`;try{try{r.scrollIntoView({behavior:`smooth`,block:`center`,inline:`nearest`})}catch{r.scrollIntoView(!0)}try{await Sg(r)}catch{}try{Tg(r)}catch{}try{await wg(r)}catch{}let e=Mg(r)||o,t=[];if(e){let n=Array.from(e.querySelectorAll(`input[required], textarea[required], select[required]`)).filter(e=>!Dg(e));for(let e of n)if(!(e.value||``).trim()){let n=Lg(e)||e.placeholder||e.name||e.type;t.push(n)}}if(t.length>0){gg(200);try{Cg()}catch{}let e=`Cannot submit — these required fields are still empty: ${t.join(`, `)}. Fill them first with fill_form_fields, then click again.`;return $(`click_page_button ✖ empty required fields:`,t),e}r.focus?.(),r.click();let n=(r.textContent||r.value||r.getAttribute(`aria-label`)||``).trim().slice(0,80)||`button`;gg(600);try{Cg()}catch{}xg(),o=null,a=[];let i=`OK_CLICK ${n}`;return $(`click_page_button ✓`,i),i}catch(e){gg(200),Cg(!0);let t=`Click failed: ${e?.message||String(e)}`;return $(`click_page_button ✖`,t),t}}};return{...s,navigateToPage:s.navigate_to_page,highlightOnPage:s.highlight_on_page,searchSiteContent:s.search_site_content,endVoiceSession:s.end_voice_session,listPageForms:s.list_page_forms,fillFormFields:s.fill_form_fields,clickPageButton:s.click_page_button}}function __(e){return!e||typeof e!=`object`?e:Object.fromEntries(Object.entries(e).map(([e,t])=>[e,async n=>{let r=Xt();r?console.log(`[FlowEngage:voice-tool] ▶`,e,n):console.info(`[FlowEngage] voice tool » ${e}`);let i;try{i=await t(n)}catch(t){let n=`Tool error: ${t?.message||String(t)}`;return console.error(`[FlowEngage] voice tool ${e} threw:`,t),n}let a=typeof i==`string`?i.length>220?`${i.slice(0,220)}…`:i:String(i);return r?console.log(`[FlowEngage:voice-tool] ◀`,e,a):console.info(`[FlowEngage] voice tool « ${e}:`,a),i}]))}var v_={idle:`rgba(99,102,241,0.18)`,listening:`rgba(16,185,129,0.25)`,speaking:`rgba(245,158,11,0.25)`,error:`rgba(239,68,68,0.2)`},y_={idle:`#6366f1`,listening:`#10b981`,speaking:`#f59e0b`,error:`#ef4444`},b_=720,x_=280;function S_(e,t){let n=(t||``).trim();return n?!!(/\b(let'?s|let us)\s+(end|stop|finish|wrap up|close)\s+(the\s+)?(voice\s+)?(session|call|chat)\b/i.test(n)||/\bend\s+(this\s+)?(the\s+)?(voice\s+)?(session|call|chat)\b/i.test(n)||/\b(hang\s+up|disconnect)\b/i.test(n)||/\b(that'?s all|we'?re done)\b/i.test(n)||e===`bot`&&(/\b(I'?ll|I will|Let me|I can|I'?m going to)\s+(end|close)\s+(the\s+)?(voice\s+)?(session|call)\b/i.test(n)||/\b(ending|closing)\s+(the\s+)?(voice\s+)?session\b|\bvoice\s+session\s+(is\s+)?(now\s+)?(ended|over|closing)\b/i.test(n)||/\b(session|call)\s+(is\s+)?(now\s+)?(ended|over)\b/i.test(n)||/\bwe\s+can\s+end\s+(the\s+)?(session|call)?\s*(here|now)\b/i.test(n)||/\b(wrapping\s+up|signing\s+off)\b/i.test(n))||/^(goodbye|bye|that'?s all|we'?re done|hang up|disconnect)\b/i.test(n)):!1}function C_({agentId:e,chatId:t,siteId:n,apiBaseUrl:r,onEnd:i,historyRef:a,hasSyncedRef:o,onMessageSync:s,onStartSync:c,voicePageHighlightMode:d=`speech`,priorChatContext:f=``}){let[p,m]=(0,l.useState)(`idle`),[ee,h]=(0,l.useState)(null),[g,_]=(0,l.useState)(!1),te=(0,l.useRef)(null),ne=(0,l.useRef)(null),re=(0,l.useRef)(``),ie=(0,l.useRef)(async()=>{}),ae=(0,l.useRef)(!1),oe=(0,l.useRef)(``),v=(0,l.useRef)(null),se=(0,l.useRef)(null),ce=(0,l.useRef)(null),y=(0,l.useRef)(!1),le=(0,l.useRef)(!1),ue=(0,l.useRef)(0),de=(0,l.useRef)(null),fe=(0,l.useCallback)(()=>{se.current&&=(clearTimeout(se.current),null),oe.current=``,v.current=null,y.current=!1,le.current=!1,ue.current=0,de.current=null,ce.current!=null&&(cancelAnimationFrame(ce.current),ce.current=null);try{_n()}catch{}},[]),pe=(0,l.useCallback)(async()=>{fe();try{await te.current?.endSession?.()}catch{}te.current=null,_(!1),m(`idle`),ae.current=!1,typeof s==`function`&&await s(a.current),typeof i==`function`&&i()},[fe,a,s,i]);ie.current=pe,(0,l.useEffect)(()=>{let t=!1,i=null;return(async()=>{let o=typeof f==`string`?f.trim():``;try{if(await navigator.mediaDevices.getUserMedia({audio:!0}),t)return;a.current=[],re.current=``,ae.current=!1,y.current=!1,le.current=!1;let s=d===`transcript`||d===`speech`,l=__(g_({siteId:n||null,apiBaseUrl:r||null,getLastUserVoiceText:()=>re.current,voicePageHighlightMode:d,markHostPageReading:()=>{le.current=!0},markExplicitToolHighlight:()=>{ue.current=Date.now()+4500},requestEndSession:()=>{queueMicrotask(()=>{ae.current||(ae.current=!0,ie.current?.())})}})),u=()=>{try{if(!s)return;let e=oe.current;if(!e?.trim()||v.current==null||e.trim().length<12||!(y.current||le.current||e.trim().length>=40)||Date.now()<ue.current)return;nn();let t=pn(e,{strict:!1}),n=t?mn(t):null;if(n){let e=!1;de.current!==n&&(e=hn(n),de.current=n),gn(n,{speaking:!0,scroll:e})}}catch(e){console.warn(`[VoiceInterface] block highlight failed`,e?.message)}},f=(e=!1)=>{if(!s)return;se.current&&clearTimeout(se.current);let t=(oe.current||``).trim();if(t.length<10)return;let n=/[.!?]["']?\s*$/.test(t),r=e?0:n&&t.length>=24?x_:b_;se.current=setTimeout(()=>{se.current=null,ce.current!=null&&cancelAnimationFrame(ce.current),ce.current=requestAnimationFrame(()=>{ce.current=null,u()})},r)},p=await Uh.startSession({agentId:e,clientTools:l,onUnhandledClientToolCall:e=>{console.error(`[VoiceInterface] ElevenLabs requested a client tool that is not registered in the widget:`,e?.tool_name,e?.parameters,`Add a matching handler in voiceClientTools (snake_case and camelCase are both supported).`)},onModeChange:({mode:e})=>{t||m(e===`speaking`?`speaking`:`listening`)},onAgentChatResponsePart:e=>{if(t)return;let n=e?.text_response_part??e,r=n?.type,i=n?.text??``;r===`start`?(se.current&&=(clearTimeout(se.current),null),ce.current!=null&&(cancelAnimationFrame(ce.current),ce.current=null),de.current=null,oe.current=i,v.current=Date.now()):r===`delta`?(oe.current+=i,v.current??=Date.now()):r===`stop`?oe.current+=i:(oe.current+=i,v.current==null&&i&&(v.current=Date.now())),s&&oe.current.trim().length>=10&&f(r===`stop`)},onInterruption:()=>{fe()},onMessage:e=>{if(t)return;let n=e.role===`user`?`user`:`bot`,r=e.message||e.text||e.content||``;if(!r)return;let i={sender:n,message:r,timestamp:new Date().toISOString()};if(n===`user`)re.current=r,r.trim().length>=1&&(y.current=!0);else if(n===`bot`&&r.trim()&&s&&(y.current||le.current)){let e=r.trim();e.length>(oe.current?.length||0)&&(oe.current=e,v.current??=Date.now(),e.length>=10&&f(!1))}a.current=[...a.current,i],S_(n,r)&&queueMicrotask(()=>{ae.current||(ae.current=!0,ie.current?.())})},onError:e=>{t||(console.error(`[VoiceInterface] ElevenLabs error`,e),fe(),m(`error`),h(`Voice session encountered an error.`))},onDisconnect:()=>{t||(console.log(`[VoiceInterface] session disconnected`),fe(),_(!1),m(`idle`))}});if(t){p.endSession().catch(()=>{});return}i=p,te.current=p,_(!0),m(`listening`);try{let e=typeof window<`u`?window.location.href:``,t=``;try{t=await l.list_page_forms()}catch{t=`[]`}p.sendContextualUpdate(`Current page URL: ${e}. Site ID: ${n||`unknown`}. Page fields/buttons JSON: ${t}. Navigation: when the user wants to go to any page (contact, pricing, about, services, etc.), call search_site_content then navigate_to_page immediately — never ask permission. After navigating to a page with a form, call list_page_forms and proactively start helping the user fill it. Contact / lead forms: use only the main contact form (Full Name, Email, Message). Ignore footer or secondary marketing URL fields unless the user explicitly asks to use them. Fill in order: name → email → message. Message must be a short visitor note (what they want from the team), not a transcript of the conversation. Forms: use fill_form_fields then click_page_button (e.g. Send Message) when appropriate. Fill each field right after the user gives that value — do not click submit until required fields are filled. `+(s?`On-page reading: the widget highlights host regions from your speech (debounced). For a precise block, call highlight_on_page({ section_text: "..." }) using visible headings or labels on the page, or read_page_content({ section_text: "..." }). `:`On-page reading: highlight the correct section by calling highlight_on_page({ section_text: "..." }) with visible heading/plan text, or read_page_content({ section_text: "..." }) when reading a specific section — the UI follows tool targets, not loose speech. `)+`Voice: if the user wants to end the voice session, call end_voice_session or confirm and end.`),o&&p.sendContextualUpdate(`Prior messages in this chat (same conversation thread). Continue naturally; do not repeat verbatim unless the user asks.\n${o}`)}catch{}typeof c==`function`&&c()}catch(e){t||(console.error(`[VoiceInterface] startSession failed`,e),m(`error`),h(`Could not start voice session. Please try again.`))}})(),()=>{t=!0,fe(),i?i.endSession().catch(()=>{}):te.current&&te.current.endSession().catch(()=>{})}},[e,n,r,a,c,fe,d]);let me=p===`listening`||p===`speaking`,he=y_[p]||y_.idle,ge=v_[p]||v_.idle;return(0,u.jsxs)(`div`,{ref:ne,style:{display:`flex`,flexDirection:`column`,alignItems:`center`,justifyContent:`center`,flex:1,gap:`24px`,padding:`24px 20px`,background:`transparent`},children:[(0,u.jsxs)(`div`,{style:{position:`relative`,width:`140px`,height:`140px`,display:`flex`,alignItems:`center`,justifyContent:`center`},children:[me&&(0,u.jsx)(`div`,{style:{position:`absolute`,inset:`-16px`,borderRadius:`50%`,border:`2px solid ${he}`,animation:`fe-orb-pulse 1.4s ease-in-out infinite`,opacity:.6}}),me&&(0,u.jsx)(`div`,{style:{position:`absolute`,inset:`-8px`,borderRadius:`50%`,border:`2px solid ${he}`,animation:`fe-orb-pulse 1.4s ease-in-out 0.35s infinite`,opacity:.4}}),(0,u.jsx)(`div`,{style:{width:`140px`,height:`140px`,borderRadius:`50%`,background:ge,border:`3px solid ${he}`,display:`flex`,alignItems:`center`,justifyContent:`center`,transition:`all 0.35s ease`,transform:p===`speaking`?`scale(1.08)`:`scale(1)`,boxShadow:`0 0 40px ${ge}, 0 8px 32px rgba(0,0,0,0.08)`},children:(0,u.jsx)(Nn,{size:44,color:he})})]}),(0,u.jsxs)(`div`,{style:{fontSize:`15px`,fontWeight:600,color:p===`error`?`#ef4444`:`#374151`,letterSpacing:`0.01em`,textAlign:`center`},children:[p===`idle`&&`Starting voice session…`,p===`listening`&&`Listening…`,p===`speaking`&&`AI is speaking…`,p===`error`&&(ee||`Error`)]}),(0,u.jsxs)(`button`,{onClick:pe,style:{display:`flex`,alignItems:`center`,gap:`8px`,padding:`12px 24px`,borderRadius:`999px`,background:`#fee2e2`,color:`#dc2626`,border:`1px solid #fca5a5`,fontWeight:600,fontSize:`14px`,cursor:`pointer`,transition:`all 0.2s ease`},onMouseEnter:e=>{e.currentTarget.style.background=`#fecaca`},onMouseLeave:e=>{e.currentTarget.style.background=`#fee2e2`},children:[(0,u.jsx)(Pn,{size:18}),`End Voice Session`]}),(0,u.jsx)(`style`,{children:`
|
|
487
|
+
`).trim();return a.length>t&&(a=a.slice(0,t).replace(/\s\S*$/,``)+`…`),a}function jg(){if(typeof document>`u`)return null;for(let e of[`main`,`article`,`[role="main"]`,`#content`,`#main-content`,`#main`,`.main-content`,`.content`,`.post-content`,`.article-content`,`.entry-content`]){let t=document.querySelector(e);if(t&&!Og(t))return t}return document.body}function Mg(e){if(!e||typeof e.querySelector!=`function`)return e;let t=e.querySelector([`.post-content`,`.entry-content`,`.article-body`,`[itemprop='articleBody']`,`.article__body`,`.field-item`,`.field--name-body`,`.field--body`,`.node__content`].join(`, `));return t&&!Og(t)?t:e}function Ng(e){if(!e)return null;try{return e.closest(`form`)}catch{let t=e.parentElement;for(;t;){if(t.tagName===`FORM`)return t;t=t.parentElement}return null}}function Pg(e){if(!e)return null;let t=e.querySelector(`h1, h2, h3, h4, h5, legend`);if(t)return t.textContent.replace(/\s+/g,` `).trim().slice(0,60);let n=e.getAttribute(`aria-label`);if(n)return n.trim().slice(0,60);let r=e.getAttribute(`title`);if(r)return r.trim().slice(0,60);let i=e.previousElementSibling;for(let e=0;e<3&&i;e++){if(/^H[1-5]$/.test(i.tagName))return i.textContent.replace(/\s+/g,` `).trim().slice(0,60);i=i.previousElementSibling}return null}function Fg(e){try{let t=e.ownerDocument?.defaultView;if(t)return t.getComputedStyle(e)}catch{}return window.getComputedStyle(e)}function Ig(e){let t=new Set;function n(r){if(!r||t.has(r))return;t.add(r),e(r);let i=r.querySelectorAll(`iframe`);for(let e of i)if(!Og(e))try{let t=e.contentDocument;t&&n(t)}catch{}}typeof document<`u`&&n(document)}function Lg(e){return e==null?null:String(e).replace(/\u00a0/g,` `).replace(/\s*\*+\s*$/u,``).replace(/\s+/g,` `).trim()}function Rg(e){let t=e.ownerDocument||document,n=e.getAttribute(`aria-labelledby`);if(n){let e=n.trim().split(/\s+/).filter(Boolean),r=[];for(let n of e)try{let e=t.getElementById(n);e?.textContent&&r.push(e.textContent.trim())}catch{}if(r.length)return Lg(r.join(` `))}if(e.labels&&e.labels.length)return Lg(e.labels[0].textContent);let r=e.id;if(r)try{let e=t.querySelector(`label[for="${CSS.escape(r)}"]`);if(e)return Lg(e.textContent)}catch{let e=t.querySelector(`label[for="${r.replace(/"/g,`\\"`)}"]`);if(e)return Lg(e.textContent)}let i=e.previousElementSibling;for(let e=0;e<6&&i;e+=1){if(i.tagName===`LABEL`)return Lg(i.textContent);let e=(i.className||``).toString().toLowerCase();if(/chakra-form__label|formlabel|field-label|form-label|mui-form-label/.test(e)){let e=Lg(i.textContent);if(e)return e}i=i.previousElementSibling}let a=e.parentElement;for(let e=0;e<5&&a;e+=1){if(a.tagName===`LABEL`)return Lg(a.textContent);let e=a.querySelector?.(`:scope > label, :scope > [class*='FormLabel'], :scope > [class*='form__label']`);if(e?.textContent)return Lg(e.textContent);a=a.parentElement}let o=e.getAttribute(`aria-label`);return o?Lg(o):null}function zg(){let e=[];return Ig(t=>{e.push(...Array.from(t.querySelectorAll(`input, select, textarea`)).filter(e=>{if(Og(e))return!1;let t=(e.type||``).toLowerCase();if([`hidden`,`submit`,`button`,`image`].includes(t)||e.disabled||e.readOnly)return!1;try{let t=Fg(e);if(t.display===`none`||t.visibility===`hidden`||parseFloat(t.opacity)===0)return!1}catch{}try{if(e.offsetWidth===0&&e.offsetHeight===0)return!1}catch{}return!0}))}),e}function Bg(e){if(!e||typeof e.closest!=`function`)return!1;try{return!!e.closest(`footer, [role="contentinfo"], #footer, .site-footer, [class*="footer"], [id*="footer"]`)}catch{return!1}}function Vg(){let e=zg();for(let t of e){if((t.type||``).toLowerCase()!==`email`||Bg(t))continue;let e=Ng(t);if(e)return e}return null}function Hg(){let e=zg(),t=new Map,n=0;return e.map((e,r)=>{let i=Ng(e),a=i||`__orphan__`;t.has(a)||t.set(a,n++);let o=t.get(a);return{formIndex:o,formName:(i?Pg(i):null)||`Form ${o}`,fieldIndex:r,tag:e.tagName,type:e.type||`text`,name:e.name||null,id:e.id||null,label:Rg(e),placeholder:e.placeholder||null}})}function Ug(e){if(Og(e)||e.disabled)return!1;try{let t=Fg(e);if(t.display===`none`||t.visibility===`hidden`||parseFloat(t.opacity)===0)return!1}catch{}return!0}function Wg(){let e=[];return Ig(t=>{e.push(...Array.from(t.querySelectorAll(`button, [role="button"], input[type="submit"], input[type="button"]`)).filter(Ug)),e.push(...Array.from(t.querySelectorAll(`a[href]`)).filter(e=>{if(!Ug(e))return!1;let t=(e.textContent||``).replace(/\s+/g,` `).trim();return!(!t||t.length<2||t.length>150)}))}),e.slice(0,60).map((e,t)=>({index:t,text:(e.textContent||e.value||``).replace(/\s+/g,` `).trim().slice(0,120)||null,ariaLabel:e.getAttribute(`aria-label`),type:e.type||e.tagName}))}function Gg(e){return String(e||``).toLowerCase().replace(/\u00a0/g,` `).replace(/\*/g,``).replace(/\s+/g,` `).trim()}function Kg(e){let t=Gg(e);return t=t.replace(/\s+field\s*$/i,``).trim(),t}function qg(e,t){let n=Kg(t);if(!n)return 0;let r=(e.name||``).toLowerCase(),i=(e.id||``).toLowerCase();if(r===`url`&&/url|website|domain|audit|conduct|site(\s|$)|page(\s|$)/.test(n)&&!/email|e-mail|mail|name|message|phone/.test(n)||(i===`url-input`||i.endsWith(`-url-input`))&&/url|website|domain|audit|conduct/.test(n)&&!/email|e-mail|mail|name|message|phone/.test(n))return 100;let a=(e.type||``).toLowerCase();if(a===`email`&&/email|e-mail|mail/.test(n))return 100;if(a===`tel`&&/phone|mobile|tel|cell/.test(n))return 95;if(a===`url`&&/url|website|domain|link/.test(n))return 100;let o=[e.name,e.id,e.placeholder,Rg(e),e.getAttribute(`aria-label`),e.getAttribute(`title`),e.getAttribute(`data-testid`),e.getAttribute(`autocomplete`)].filter(Boolean).map(e=>Gg(e)),s=0;for(let e of o){if(!e)continue;if(e===n){s=100;break}if(e.includes(n)||n.includes(e)){s=Math.max(s,96);continue}let t=n.split(/\s+/).filter(e=>e.length>1);if(!t.length)continue;let r=0;for(let n of t)e.includes(n)&&(r+=1);let i=r/t.length;i>0&&(s=Math.max(s,i*88))}return s}var Jg=22;function Yg(e,t){let n=null,r=0;for(let i of e){let e=qg(i,t);e>r&&(r=e,n=i)}return!n||r<Jg?null:n}function Xg(e,t,n){let r=String(t||``).toLowerCase().trim(),i=String(n||``).trim();if(/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(i)||!(/^https?:\/\//i.test(i)||/\.\w{2,}(\/|\s|$)/.test(i)||r.includes(`url`)||r.includes(`website`)||r.includes(`domain`)||r.includes(`site`)))return null;let a=null,o=0;for(let t of e){if(t.tagName!==`INPUT`&&t.tagName!==`TEXTAREA`)continue;let e=(t.type||``).toLowerCase();if([`hidden`,`submit`,`button`,`checkbox`,`radio`].includes(e))continue;let n=0;(e===`url`||e===`text`||e===`search`)&&(n+=45);let r=[t.name,t.id,t.placeholder,Rg(t),t.getAttribute(`aria-label`),t.getAttribute(`autocomplete`)].filter(Boolean).join(` `).toLowerCase();/(website|url|domain|site\s*url)/.test(r)&&(n+=55),n>o&&(o=n,a=t)}return!a||o<42?null:a}function Zg(e){let t=String(e??``).trim();return!t||/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(t)?!1:/^https?:\/\//i.test(t)?!0:/\.\w{2,}(\/|\s|$)/.test(t)}function Qg(e){let t=String(e??``).toLowerCase().trim();return t?!!(t===`url`||t===`website`||t===`website url`||t===`website_url`||t===`enter website url`||t.includes(`website`)||t.includes(`domain`)||/(enter\s+website|site\s*url|page\s*url)/.test(t)):!1}function $g(e){if(!e||e.tagName!==`INPUT`&&e.tagName!==`TEXTAREA`)return!1;let t=(e.type||``).toLowerCase();return![`hidden`,`submit`,`button`,`checkbox`,`radio`,`file`].includes(t)}function e_(e){if(!$g(e))return!1;let t=(e.name||``).toLowerCase(),n=(e.id||``).toLowerCase(),r=[e.name,e.id,e.placeholder,Rg(e),e.getAttribute(`aria-label`)].filter(Boolean).join(` `).toLowerCase();return t===`url`||n===`url-input`||n.endsWith(`-url-input`)||/(website\s*url|enter\s+website|site\s*url)/.test(r)||/(website|domain)/.test(r)&&/(url|site)/.test(r)}function t_(e,t,n){let r=String(t??``),i=String(n??``),a=i_(e,r)||Yg(e,r)||Xg(e,r,i);if(!a)return[];let o=new Set([a]);if(Zg(i)&&Qg(r))for(let t of e)t!==a&&e_(t)&&o.add(t);let s=Array.from(o);return s.sort((e,t)=>{if(e===t)return 0;let n=e.compareDocumentPosition(t);return n&Node.DOCUMENT_POSITION_FOLLOWING?-1:n&Node.DOCUMENT_POSITION_PRECEDING?1:0}),s}function n_(e,t){try{if(!e?.getBoundingClientRect||!t?.getBoundingClientRect)return 1/0;let n=e.getBoundingClientRect(),r=t.getBoundingClientRect(),i={x:n.left+n.width/2,y:n.top+n.height/2},a={x:r.left+r.width/2,y:r.top+r.height/2};return Math.hypot(i.x-a.x,i.y-a.y)}catch{return 1/0}}function r_(e){if(!e||typeof e!=`string`)return null;let t=null;return Ig(n=>{try{let r=n.getElementById(e);r&&!Og(r)&&r.matches?.(`input, select, textarea`)&&(t=r)}catch{}}),t}function i_(e,t){let n=String(t??``).trim();if(!n)return null;let r=n.match(/^name:\s*([\w.-]+)$/i);if(r){let t=r[1];for(let n of e)if(n.name===t)return n}let i=n.match(/^id:\s*([\w.-]+)$/i);if(i){let e=r_(i[1]);if(e)return e}let a=n.startsWith(`#`)?n.slice(1):n;if(/^[\w-]+$/.test(a)){let e=r_(a);if(e)return e}let o=n.toLowerCase().replace(/\s+/g,` `);if(o===`url`||o===`website`||o===`website url`||o===`website_url`||o===`enter website url`)for(let t of e){let e=(t.name||``).toLowerCase(),n=(t.id||``).toLowerCase();if(e===`url`||n===`url-input`||n.endsWith(`-url-input`))return t}return null}function a_(e,t){let n=String(t||``).toLowerCase().trim();if(!n)return 0;let r=[e.textContent,e.value,e.getAttribute(`aria-label`),e.getAttribute(`title`)].filter(Boolean).join(` `).toLowerCase().replace(/\s+/g,` `);if(r===n)return 100;if(r.includes(n))return 98;let i=n.split(/\s+/).filter(e=>e.length>1);if(!i.length)return 0;let a=0;for(let e of i)r.includes(e)&&(a+=1);return a/i.length*92}function o_(e,t){let n=[];Ig(e=>{n.push(...Array.from(e.querySelectorAll(`button, [role="button"], input[type="submit"], input[type="button"]`)).filter(Ug)),n.push(...Array.from(e.querySelectorAll(`a[href]`)).filter(e=>{if(!Ug(e))return!1;let t=(e.textContent||``).replace(/\s+/g,` `).trim();return!(!t||t.length<2||t.length>150)}))});let r=0,i=n.map(t=>({el:t,s:a_(t,e)}));for(let{s:e}of i)e>r&&(r=e);let a=e.split(/\s+/).filter(e=>e.length>1).length>=3?28:36;if(r<a)return null;let o=i.filter(({s:e})=>e===r).map(({el:e})=>e);if(o.length===1)return o[0];let s=Array.isArray(t)?t.filter(e=>e&&e.isConnected):[];if(s.length){let e=o[0],t=1/0;for(let n of o)for(let r of s){let i=n_(n,r);i<t&&(t=i,e=n)}return e}return o[0]}function s_(e){if(e==null)return{};if(typeof e==`string`){let t=e.trim();if(!t)return{};try{return JSON.parse(t)}catch{return{url:t}}}return e}function c_(e){let t=s_(e);if(Array.isArray(t)&&t.length>0){let e=t[0];if(e?.field_key!=null||e?.fieldKey!=null)return t.map(e=>({field_key:e.field_key??e.fieldKey,value:e.value}))}if(!t||typeof t!=`object`)return[];let n=t.fields??t.Fields??t.field_list??t.fieldList??t.data?.fields;if(typeof n==`string`)try{n=JSON.parse(n)}catch{n=null}n&&!Array.isArray(n)&&typeof n==`object`&&(n=Object.values(n)),(!n||n.length===0)&&(t.field_key!=null||t.fieldKey!=null)&&t.value!=null&&(n=[{field_key:t.field_key??t.fieldKey,value:t.value}]);let r=t.website_url??t.websiteUrl??t.url??t.website??t.domain??t.site_url??t.siteUrl;return(!n||n.length===0)&&r!=null&&String(r).trim()&&(n=[{field_key:t.field_key??t.fieldKey??`url`,value:String(r).trim()}]),Array.isArray(n)?n.map(e=>({field_key:e?.field_key??e?.fieldKey,value:e?.value??e?.Value})):[]}function l_(e){if(!e||typeof e!=`string`)return e;let t=e.trim();return/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(t)?t:(t=t.replace(/\s+at\s+the\s+rate\s*(of)?\s+/gi,`@`),t=t.replace(/\s+at\s+/gi,`@`),t=t.replace(/\s+dot\s+/gi,`.`),t=t.replace(/\s+/g,``),t=t.replace(/\.{2,}/g,`.`).replace(/\.$/,``),t)}function u_(e){if(!e||typeof e!=`string`)return e;let t={zero:`0`,one:`1`,two:`2`,three:`3`,four:`4`,five:`5`,six:`6`,seven:`7`,eight:`8`,nine:`9`,oh:`0`,o:`0`},n=e.toLowerCase().trim();for(let[e,r]of Object.entries(t))n=n.replace(RegExp(`\\b${e}\\b`,`g`),r);return n=n.replace(/[^\d+]/g,``),n}function d_(e){if(!e||typeof e!=`string`)return[];let t=e.trim();if(!t||/\b[a-z0-9._%+-]+@[a-z0-9.-]+\.[a-z]{2,}\b/i.test(t))return[];let n=t.match(/https?:\/\/[^\s<>"']+/i);if(n)return[{field_key:`url`,value:n[0].replace(/[.,;:)]+$/,``)}];let r=t.match(/\b(?:[\w-]+\.)+[a-z]{2,}\b/i);if(r){let e=r[0].replace(/[.,;:)]+$/,``);return/^https?:/i.test(e)||(e=`https://${e}`),[{field_key:`url`,value:e}]}return[]}function f_(e){if(!e||typeof e!=`string`)return[];let t=e.trim();if(!t)return[];let n=[],r=new Set,i=/\b([a-z0-9._%+-]+@[a-z0-9.-]+\.[a-z]{2,})\b/i,a=(e,t)=>{let i=String(t??``).trim().replace(/^["']|["']$/g,``);if(!i||i.length>800)return;let a=`${e}\0${i}`;r.has(a)||(r.add(a),n.push({field_key:e,value:i}))},o=l_(t),s=i.test(o),c=o.match(/^\s*([a-z0-9._%+-]+@[a-z0-9.-]+\.[a-z]{2,})\s*$/i);if(c)return a(`Email Address`,c[1]),n;if(!i.test(t)&&s){let e=o.match(i);if(e)return a(`Email Address`,e[1]),n}let l=t.match(/\b(?:please\s+)?(?:enter|type|put)\s+(.+?)\s+in(?:to)?\s+(?:the\s+)?(?:full\s*name|full\s*name\s*field|name\s*field)\b/i);if(l&&a(`Full Name`,l[1]),l=t.match(/\bfull\s*name,?\s*(?:please\s+)?(?:enter|type|put)\s+(.+?)(?:\.|$|!|\?)/i),l&&a(`Full Name`,l[1]),l=t.match(/\bfull\s*name\s*(?:is|:|please\s+enter|-)\s*(.+?)(?:\.|$|(?=\s+(?:and|my\s+email|email|message))\b)/i),l&&a(`Full Name`,l[1]),l=t.match(/\b(.+?)\s+for\s+(?:the\s+)?full\s*name\b/i),l){let e=l[1].trim();e.length>1&&e.length<120&&!/@/.test(e)&&a(`Full Name`,e)}if(l=t.match(/\b(?:email|e-mail)(?:\s*address)?\s*(?:is|:|please\s+use|enter|-)\s*([^\s@]+@[^\s@]+\.[^\s,]+)/i),l&&a(`Email Address`,l[1]),l=t.match(/\b(?:enter|type|put)\s+([^\s@]+@[^\s@]+\.[^\s,]+)\s+in(?:to)?\s+(?:the\s+)?(?:email|e-mail)/i),l&&a(`Email Address`,l[1]),l=t.match(/\b(?:message|comment)\s*(?:is|:|please\s+enter|-)\s*(.+)$/is),l){let e=l[1].trim();e.length>0&&a(`Message`,e)}if(!n.some(e=>/email/i.test(String(e.field_key)))){let e=t.match(i);if(e){let r=t.replace(e[0],``).trim().replace(/^(please|it's|it is|use|is|my email is|e-?mail is)\s*/i,``).replace(/[.,;:!?]+$/,``).trim();if(t.length<=96&&r.length<=36)return a(`Email Address`,e[1]),n}}if(n.length===0){let e=t.split(/\s+/).filter(Boolean).length,n=/[.!?]/.test(t)||e>=6||t.length>=24&&e>=5||t.length>=42,r=/^[A-Z][a-z]+\s+[A-Z][a-z]+$/.test(t.trim());n&&t.length>=16&&!i.test(t)&&!r&&a(`Message`,t)}return n}function p_(e){if(!e||typeof e!=`object`)return null;let t=e.url??e.target_url??e.page_url??e.pageUrl??e.link??e.href??e.path;return t==null?null:String(t).trim()||null}function m_(e){if(!e||typeof e!=`object`)return null;let t=e.query??e.q??e.search??e.text??e.keywords??e.search_query??e.searchQuery??e.question??e.prompt??e.topic??e.intent;return t==null?null:String(t).trim()||null}function h_(e){let t=e.ownerDocument?.defaultView||window,n=e.tagName===`TEXTAREA`?t.HTMLTextAreaElement.prototype:t.HTMLInputElement.prototype,r=Object.getOwnPropertyDescriptor(n,`value`);return(e,t)=>{try{e._valueTracker&&e._valueTracker.setValue(``)}catch{}r?.set?r.set.call(e,t):e.value=t}}async function g_(e,t,n){if(!n?.skipScroll)try{e.scrollIntoView({behavior:`smooth`,block:`center`,inline:`nearest`})}catch{try{e.scrollIntoView(!0)}catch{}}try{await Cg(e)}catch{}try{bg(e)}catch{}await new Promise(e=>setTimeout(e,180));try{e.focus({preventScroll:!0})}catch{try{e.focus()}catch{}}let r=e.tagName,i=(e.type||``).toLowerCase(),a={bubbles:!0,cancelable:!0,composed:!0};if(r===`SELECT`)return e.value=String(t),e.dispatchEvent(new Event(`input`,a)),e.dispatchEvent(new Event(`change`,a)),e.dispatchEvent(new Event(`blur`,a)),xg(e),!0;if(i===`checkbox`||i===`radio`)return e.checked=[`1`,`true`,`yes`,`on`].includes(String(t).toLowerCase().trim()),e.dispatchEvent(new Event(`input`,a)),e.dispatchEvent(new Event(`change`,a)),xg(e),!0;let o=String(t);if(r===`INPUT`||r===`TEXTAREA`){let t=h_(e);try{await pg(e,o,t)}catch{t(e,o)}e.value!==o&&t(e,o)}else e.value=o;try{e.dispatchEvent(new InputEvent(`input`,{...a,inputType:`insertText`,data:o}))}catch{e.dispatchEvent(new Event(`input`,a))}e.dispatchEvent(new Event(`change`,a)),e.dispatchEvent(new Event(`blur`,a));try{e.focus({preventScroll:!0})}catch{}try{queueMicrotask(()=>{try{e.dispatchEvent(new Event(`input`,a)),e.dispatchEvent(new Event(`change`,a))}catch{}})}catch{}return xg(e),!0}function __(e){let t=e.siteId||null,n=(e.apiBaseUrl||``).replace(/\/$/,``),r=e.voicePageHighlightMode||`speech`,i=typeof e.getLastUserVoiceText==`function`?e.getLastUserVoiceText:null,a=[],o=null,s={navigate_to_page:async n=>{$(`navigate_to_page ▶ raw parameters:`,n);let i=s_(n),a=p_(i),o=i.section_text??i.sectionText??i.section;if($(`navigate_to_page · coerced:`,{url:a,sectionText:o}),!a){let e=`Missing url: pass a string url, path like /pricing, or JSON with a url field.`;return $(`navigate_to_page ✖`,e),e}let s=typeof window<`u`?_n(a):a;if(gg(`Navigating to ${String(s).replace(/^https?:\/\/[^/]+/,``)||`/`}…`),vg(),!await yn(s,{siteId:t,apiBaseUrl:e.apiBaseUrl})){yg(),_g(200);let e=`That page is not available in the site index; answer without navigating.`;return $(`navigate_to_page ✖ blocked`,e),e}try{if($(`navigate_to_page → shadowNavigate`,s),await xn(s,{sectionText:o||void 0}),await new Promise(e=>setTimeout(e,600)),yg(),_g(300),o&&typeof o==`string`&&r!==`off`){let e=nn(null,o);e&&hn(e,{speaking:!0,scroll:!0}),$(`navigate_to_page · highlight`,{sectionText:o,found:!!e})}let e=``;try{let t=Hg(),n=Wg();if(t.length>0){let r=t.map(e=>e.label||e.placeholder||e.name||e.id).filter(Boolean).join(`, `),i=n.map(e=>e.text).filter(Boolean).join(`, `);e=` This page has a form with fields: [${r}]`+(i?` and buttons: [${i}].`:`.`)+` Call list_page_forms then start filling.`}}catch{}let t=`OK_NAVIGATION ${s}${e}`;return $(`navigate_to_page ✓`,t),t}catch(e){yg(),_g(200);let t=`Navigation error: ${e?.message||String(e)}`;return $(`navigate_to_page ✖`,t),t}},highlight_on_page:async t=>{if($(`highlight_on_page ▶`,t),r===`off`)return $(`highlight_on_page · skipped (voicePageHighlightMode=off)`),`OK_HIGHLIGHT page highlighting is disabled.`;let n=s_(t),i=n?.section_id||n?.sectionId,a=n?.section_text||n?.sectionText,o=nn(i||null,a||null);if(!o)return $(`highlight_on_page ✖ no element`),`Could not find that section on the page.`;hn(o,{speaking:!0,scroll:!0});try{e.markExplicitToolHighlight?.()}catch{}return $(`highlight_on_page ✓ (speaking)`),`OK_HIGHLIGHT section is now highlighted and scrolled into view.`},search_site_content:async e=>{$(`search_site_content ▶`,e);let r=m_(s_(e));if($(`search_site_content · query:`,r,`siteId:`,t,`apiBase:`,n||`(empty)`),gg(`Searching site content…`,{spinner:!0}),!r)return _g(),$(`search_site_content ✖ missing query`),`Missing query parameter.`;if(!t)return _g(),$(`search_site_content ✖ no siteId`),`Site is not configured for search.`;if(!n)return _g(),$(`search_site_content ✖ no api base`),`API base URL is missing; cannot search.`;try{let e=`${n}/api/site-tools/search`;$(`search_site_content → POST`,e);let i=await fetch(e,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({siteId:t,query:r,currentUrl:typeof window<`u`?window.location.href:``})}),a=await i.json();if($(`search_site_content · HTTP`,i.status,`success:`,a.success),_g(200),!a.success){let e=a.error||`Search failed.`;return $(`search_site_content ✖`,e),e}let o=a.results||[];return $(`search_site_content ✓`,`${o.length} result(s)`,o.slice(0,3).map(e=>e?.url||e)),JSON.stringify(o)}catch(e){_g();let t=`Search error: ${e.message||`network`}`;return $(`search_site_content ✖`,t),t}},read_page_content:async t=>{$(`read_page_content ▶`,t);let n=s_(t),i=n?.section_text||n?.sectionText,a=3e3;try{if(i){let t=nn(null,i);if(!t){let e=String(i).trim().split(/\s+/).filter(e=>e.length>2);for(let n=Math.min(e.length,5);n>=2&&!t;n--)t=nn(null,e.slice(0,n).join(` `))}if(!t)return`Could not find a section matching "${i}" on this page. Try navigate_to_page or click_page_button with the article title, then read_page_content again.`;if(r!==`off`){hn(t,{speaking:!0,scroll:!0});try{e.markExplicitToolHighlight?.()}catch{}}let n=Ag(t,a);if(!n)return`Found the section but it appears to be empty.`;$(`read_page_content ✓ section:`,n.length,`chars`);try{e.markHostPageReading?.()}catch{}return`OK_READ: ${n}`}let t=Mg(jg());if(!t)return`Could not determine the main content area of this page.`;let n=Ag(t,a);if(!n)return`The page appears to have no readable text content.`;$(`read_page_content ✓ page:`,n.length,`chars`);try{e.markHostPageReading?.()}catch{}return`OK_READ: ${n}`}catch(e){return $(`read_page_content ✖`,e?.message),`Error reading page content: ${e?.message||`unknown error`}`}},end_voice_session:async()=>($(`end_voice_session ▶`),gg(`Ending voice session…`,{icon:`👋`,spinner:!1,duration:2e3}),wg(!0),Sg(),typeof e.requestEndSession==`function`&&e.requestEndSession(),`Voice session is ending.`),list_page_forms:async()=>{let e=Hg(),t=Wg();return $(`list_page_forms ✓`,`${e.length} field(s)`,`${t.length} button(s)`),o=Vg(),$(`list_page_forms · activeFormAncestor`,o?`contact-preferring`:`none`),JSON.stringify({fields:e,buttons:t,hint:`Fields are grouped by formIndex/formName. Work with ONE form at a time — only fill fields from the same formIndex. Do not jump to fields in a different form. On pages with a contact form AND a footer or secondary website-URL field: only use the contact form unless the visitor explicitly asks to use the URL or promo flow. Contact forms: fill in order Full Name → Email Address → Message. Message must be a short note the visitor wants to send (one or two sentences), never a recap of the whole chat or assistant replies. field_key: use placeholder, label, name, or id from this list. click_page_button picks the button nearest the filled fields (e.g. Send Message on the same form).`})},fill_form_fields:async e=>{try{$(`fill_form_fields ▶ raw:`,e);let t=c_(e);if(!t.length&&i){let e=i(),n=d_(e);n.length?$(`fill_form_fields · inferred URL from last user utterance (model omitted usable fields):`,n):(n=f_(e),n.length&&$(`fill_form_fields · inferred contact fields from last user utterance (empty tool params):`,n)),n.length&&(t=n)}if($(`fill_form_fields · normalized fields:`,t),!t.length)return`No fields provided. Call list_page_forms for field_key strings, then fill_form_fields with { "fields": [ { "field_key": "<label or placeholder from list>", "value": "<user value>" } ] }. Never use empty {}. Pass the value the user just said (email, message, name, URL) in fields.`;t.length>1&&gg(`Filling ${t.length} fields…`);let n=[];for(let e of t){let t=e?.field_key??e?.fieldKey,r=e?.value;if(t==null||r==null)continue;let i=String(t).toLowerCase();if(/email|e-mail|mail/.test(i))r=l_(r);else if(/phone|mobile|tel|cell/.test(i))r=u_(r);else if(Qg(t)||i===`url`){let e=String(r??``).trim();if(/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(e)||/\bat\b/i.test(e)&&/\bdot\b/i.test(e)){let n=l_(e);/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(n.trim())&&($(`fill_form_fields · remapping url/website intent to Email Address (value is an email)`),t=`Email Address`,i=`email address`,r=n.trim())}}gg(`Filling ${t}…`),$(`fill_form_fields · processing field:`,t,`=`,r);let s=zg(),c=s;if(o){let e=s.filter(e=>Ng(e)===o);e.length>0&&(c=e,$(`fill_form_fields · scoped to active form, inputs:`,e.length))}$(`fill_form_fields · visible inputs count:`,s.length,`scoped:`,c.length);let l=!1;for(let e of[c,...c===s?[]:[s]]){let i=t_(e,String(t),r);if(i.length){for(let e=0;e<i.length;e++)await g_(i[e],r,{skipScroll:e>0}),await new Promise(e=>setTimeout(e,80));a=i,o=Ng(i[0])||o,n.push(String(t)),l=!0;break}let s=i_(e,String(t));if(s||=Yg(e,String(t)),s||=Xg(e,String(t),r),s){await g_(s,r),a=[s],o=Ng(s)||o,n.push(String(t)),l=!0;break}}l||$(`fill_form_fields · no match for field:`,t)}_g(400);try{wg()}catch{}if(!n.length)return $(`fill_form_fields ✖ no matches`),`Could not match any fields. Call list_page_forms and use field_key values that match placeholder, label, name, or id (e.g. Enter Website URL). Ensure the form is on the page, not the chat panel.`;let r=`OK_FILLED: ${n.join(`, `)}`;return $(`fill_form_fields ✓`,r),r}catch(e){_g(),Sg(),wg(!0);let t=`fill_form_fields error: ${e?.message||String(e)}`;return $(`fill_form_fields ✖`,t),t}},click_page_button:async e=>{let t=s_(e),n=(t.button_text??t.buttonText??t.text??``).trim();if($(`click_page_button ▶`,n),!n)return`Missing button_text: pass the visible label, e.g. Submit or Read more.`;gg(`Clicking "${n}"…`);let r=o_(n,a);if(!r)return _g(200),$(`click_page_button ✖ no match`),`Could not find a button matching "${n}". Call list_page_forms to see button texts.`;try{try{r.scrollIntoView({behavior:`smooth`,block:`center`,inline:`nearest`})}catch{r.scrollIntoView(!0)}try{await Cg(r)}catch{}try{Eg(r)}catch{}try{await Tg(r)}catch{}let e=Ng(r)||o,t=[];if(e){let n=Array.from(e.querySelectorAll(`input[required], textarea[required], select[required]`)).filter(e=>!Og(e));for(let e of n)if(!(e.value||``).trim()){let n=Rg(e)||e.placeholder||e.name||e.type;t.push(n)}}if(t.length>0){_g(200);try{wg()}catch{}let e=`Cannot submit — these required fields are still empty: ${t.join(`, `)}. Fill them first with fill_form_fields, then click again.`;return $(`click_page_button ✖ empty required fields:`,t),e}r.focus?.(),r.click();let n=(r.textContent||r.value||r.getAttribute(`aria-label`)||``).trim().slice(0,80)||`button`;_g(600);try{wg()}catch{}Sg(),o=null,a=[];let i=`OK_CLICK ${n}`;return $(`click_page_button ✓`,i),i}catch(e){_g(200),wg(!0);let t=`Click failed: ${e?.message||String(e)}`;return $(`click_page_button ✖`,t),t}}};return{...s,navigateToPage:s.navigate_to_page,highlightOnPage:s.highlight_on_page,searchSiteContent:s.search_site_content,endVoiceSession:s.end_voice_session,listPageForms:s.list_page_forms,fillFormFields:s.fill_form_fields,clickPageButton:s.click_page_button}}function v_(e){return!e||typeof e!=`object`?e:Object.fromEntries(Object.entries(e).map(([e,t])=>[e,async n=>{let r=Yt();r?console.log(`[FlowEngage:voice-tool] ▶`,e,n):console.info(`[FlowEngage] voice tool » ${e}`);let i;try{i=await t(n)}catch(t){let n=`Tool error: ${t?.message||String(t)}`;return console.error(`[FlowEngage] voice tool ${e} threw:`,t),n}let a=typeof i==`string`?i.length>220?`${i.slice(0,220)}…`:i:String(i);return r?console.log(`[FlowEngage:voice-tool] ◀`,e,a):console.info(`[FlowEngage] voice tool « ${e}:`,a),i}]))}var y_={idle:`rgba(99,102,241,0.18)`,listening:`rgba(16,185,129,0.25)`,speaking:`rgba(245,158,11,0.25)`,error:`rgba(239,68,68,0.2)`},b_={idle:`#6366f1`,listening:`#10b981`,speaking:`#f59e0b`,error:`#ef4444`},x_=720,S_=280;function C_(e,t){let n=(t||``).trim();return n?!!(/\b(let'?s|let us)\s+(end|stop|finish|wrap up|close)\s+(the\s+)?(voice\s+)?(session|call|chat)\b/i.test(n)||/\bend\s+(this\s+)?(the\s+)?(voice\s+)?(session|call|chat)\b/i.test(n)||/\b(hang\s+up|disconnect)\b/i.test(n)||/\b(that'?s all|we'?re done)\b/i.test(n)||e===`bot`&&(/\b(I'?ll|I will|Let me|I can|I'?m going to)\s+(end|close)\s+(the\s+)?(voice\s+)?(session|call)\b/i.test(n)||/\b(ending|closing)\s+(the\s+)?(voice\s+)?session\b|\bvoice\s+session\s+(is\s+)?(now\s+)?(ended|over|closing)\b/i.test(n)||/\b(session|call)\s+(is\s+)?(now\s+)?(ended|over)\b/i.test(n)||/\bwe\s+can\s+end\s+(the\s+)?(session|call)?\s*(here|now)\b/i.test(n)||/\b(wrapping\s+up|signing\s+off)\b/i.test(n))||/^(goodbye|bye|that'?s all|we'?re done|hang up|disconnect)\b/i.test(n)):!1}function w_({agentId:e,chatId:t,siteId:n,apiBaseUrl:r,onEnd:i,historyRef:a,hasSyncedRef:o,onMessageSync:s,onStartSync:c,voicePageHighlightMode:d=`speech`,priorChatContext:f=``}){let[p,m]=(0,l.useState)(`idle`),[ee,h]=(0,l.useState)(null),[g,te]=(0,l.useState)(!1),ne=(0,l.useRef)(null),re=(0,l.useRef)(null),ie=(0,l.useRef)(``),ae=(0,l.useRef)(async()=>{}),oe=(0,l.useRef)(!1),_=(0,l.useRef)(``),v=(0,l.useRef)(null),se=(0,l.useRef)(null),ce=(0,l.useRef)(null),le=(0,l.useRef)(!1),y=(0,l.useRef)(!1),ue=(0,l.useRef)(0),de=(0,l.useRef)(null),fe=(0,l.useCallback)(()=>{se.current&&=(clearTimeout(se.current),null),_.current=``,v.current=null,le.current=!1,y.current=!1,ue.current=0,de.current=null,ce.current!=null&&(cancelAnimationFrame(ce.current),ce.current=null);try{gn()}catch{}},[]),pe=(0,l.useCallback)(async()=>{fe();try{await ne.current?.endSession?.()}catch{}ne.current=null,te(!1),m(`idle`),oe.current=!1,typeof s==`function`&&await s(a.current),typeof i==`function`&&i()},[fe,a,s,i]);ae.current=pe,(0,l.useEffect)(()=>{let t=!1,i=null;return(async()=>{let o=typeof f==`string`?f.trim():``;try{if(await navigator.mediaDevices.getUserMedia({audio:!0}),t)return;a.current=[],ie.current=``,oe.current=!1,le.current=!1,y.current=!1;let s=d===`transcript`||d===`speech`,l=v_(__({siteId:n||null,apiBaseUrl:r||null,getLastUserVoiceText:()=>ie.current,voicePageHighlightMode:d,markHostPageReading:()=>{y.current=!0},markExplicitToolHighlight:()=>{ue.current=Date.now()+4500},requestEndSession:()=>{queueMicrotask(()=>{oe.current||(oe.current=!0,ae.current?.())})}})),u=()=>{try{if(!s)return;let e=_.current;if(!e?.trim()||v.current==null||e.trim().length<12||!(le.current||y.current||e.trim().length>=40)||Date.now()<ue.current)return;tn();let t=fn(e,{strict:!1}),n=t?pn(t):null;if(n){let e=!1;de.current!==n&&(e=mn(n),de.current=n),hn(n,{speaking:!0,scroll:e})}}catch(e){console.warn(`[VoiceInterface] block highlight failed`,e?.message)}},f=(e=!1)=>{if(!s)return;se.current&&clearTimeout(se.current);let t=(_.current||``).trim();if(t.length<10)return;let n=/[.!?]["']?\s*$/.test(t),r=e?0:n&&t.length>=24?S_:x_;se.current=setTimeout(()=>{se.current=null,ce.current!=null&&cancelAnimationFrame(ce.current),ce.current=requestAnimationFrame(()=>{ce.current=null,u()})},r)},p=await Wh.startSession({agentId:e,clientTools:l,onUnhandledClientToolCall:e=>{console.error(`[VoiceInterface] ElevenLabs requested a client tool that is not registered in the widget:`,e?.tool_name,e?.parameters,`Add a matching handler in voiceClientTools (snake_case and camelCase are both supported).`)},onModeChange:({mode:e})=>{t||m(e===`speaking`?`speaking`:`listening`)},onAgentChatResponsePart:e=>{if(t)return;let n=e?.text_response_part??e,r=n?.type,i=n?.text??``;r===`start`?(se.current&&=(clearTimeout(se.current),null),ce.current!=null&&(cancelAnimationFrame(ce.current),ce.current=null),de.current=null,_.current=i,v.current=Date.now()):r===`delta`?(_.current+=i,v.current??=Date.now()):r===`stop`?_.current+=i:(_.current+=i,v.current==null&&i&&(v.current=Date.now())),s&&_.current.trim().length>=10&&f(r===`stop`)},onInterruption:()=>{fe()},onMessage:e=>{if(t)return;let n=e.role===`user`?`user`:`bot`,r=e.message||e.text||e.content||``;if(!r)return;let i={sender:n,message:r,timestamp:new Date().toISOString()};if(n===`user`)ie.current=r,r.trim().length>=1&&(le.current=!0);else if(n===`bot`&&r.trim()&&s&&(le.current||y.current)){let e=r.trim();e.length>(_.current?.length||0)&&(_.current=e,v.current??=Date.now(),e.length>=10&&f(!1))}a.current=[...a.current,i],C_(n,r)&&queueMicrotask(()=>{oe.current||(oe.current=!0,ae.current?.())})},onError:e=>{t||(console.error(`[VoiceInterface] ElevenLabs error`,e),fe(),m(`error`),h(`Voice session encountered an error.`))},onDisconnect:()=>{t||(console.log(`[VoiceInterface] session disconnected`),fe(),te(!1),m(`idle`))}});if(t){p.endSession().catch(()=>{});return}i=p,ne.current=p,te(!0),m(`listening`);try{let e=typeof window<`u`?window.location.href:``,t=``;try{t=await l.list_page_forms()}catch{t=`[]`}p.sendContextualUpdate(`Current page URL: ${e}. Site ID: ${n||`unknown`}. Page fields/buttons JSON: ${t}. Navigation: when the user wants to go to any page (contact, pricing, about, services, etc.), call search_site_content then navigate_to_page immediately — never ask permission. After navigating to a page with a form, call list_page_forms and proactively start helping the user fill it. Contact / lead forms: use only the main contact form (Full Name, Email, Message). Ignore footer or secondary marketing URL fields unless the user explicitly asks to use them. Fill in order: name → email → message. Message must be a short visitor note (what they want from the team), not a transcript of the conversation. Forms: use fill_form_fields then click_page_button (e.g. Send Message) when appropriate. Fill each field right after the user gives that value — do not click submit until required fields are filled. `+(s?`On-page reading: the widget highlights host regions from your speech (debounced). For a precise block, call highlight_on_page({ section_text: "..." }) using visible headings or labels on the page, or read_page_content({ section_text: "..." }). `:`On-page reading: highlight the correct section by calling highlight_on_page({ section_text: "..." }) with visible heading/plan text, or read_page_content({ section_text: "..." }) when reading a specific section — the UI follows tool targets, not loose speech. `)+`Voice: if the user wants to end the voice session, call end_voice_session or confirm and end.`),o&&p.sendContextualUpdate(`Prior messages in this chat (same conversation thread). Continue naturally; do not repeat verbatim unless the user asks.\n${o}`)}catch{}typeof c==`function`&&c()}catch(e){t||(console.error(`[VoiceInterface] startSession failed`,e),m(`error`),h(`Could not start voice session. Please try again.`))}})(),()=>{t=!0,fe(),i?i.endSession().catch(()=>{}):ne.current&&ne.current.endSession().catch(()=>{})}},[e,n,r,a,c,fe,d]);let me=p===`listening`||p===`speaking`,he=b_[p]||b_.idle,ge=y_[p]||y_.idle;return(0,u.jsxs)(`div`,{ref:re,style:{display:`flex`,flexDirection:`column`,alignItems:`center`,justifyContent:`center`,flex:1,gap:`24px`,padding:`24px 20px`,background:`transparent`},children:[(0,u.jsxs)(`div`,{style:{position:`relative`,width:`140px`,height:`140px`,display:`flex`,alignItems:`center`,justifyContent:`center`},children:[me&&(0,u.jsx)(`div`,{style:{position:`absolute`,inset:`-16px`,borderRadius:`50%`,border:`2px solid ${he}`,animation:`fe-orb-pulse 1.4s ease-in-out infinite`,opacity:.6}}),me&&(0,u.jsx)(`div`,{style:{position:`absolute`,inset:`-8px`,borderRadius:`50%`,border:`2px solid ${he}`,animation:`fe-orb-pulse 1.4s ease-in-out 0.35s infinite`,opacity:.4}}),(0,u.jsx)(`div`,{style:{width:`140px`,height:`140px`,borderRadius:`50%`,background:ge,border:`3px solid ${he}`,display:`flex`,alignItems:`center`,justifyContent:`center`,transition:`all 0.35s ease`,transform:p===`speaking`?`scale(1.08)`:`scale(1)`,boxShadow:`0 0 40px ${ge}, 0 8px 32px rgba(0,0,0,0.08)`},children:(0,u.jsx)(Nn,{size:44,color:he})})]}),(0,u.jsxs)(`div`,{style:{fontSize:`15px`,fontWeight:600,color:p===`error`?`#ef4444`:`#374151`,letterSpacing:`0.01em`,textAlign:`center`},children:[p===`idle`&&`Starting voice session…`,p===`listening`&&`Listening…`,p===`speaking`&&`AI is speaking…`,p===`error`&&(ee||`Error`)]}),(0,u.jsxs)(`button`,{onClick:pe,style:{display:`flex`,alignItems:`center`,gap:`8px`,padding:`12px 24px`,borderRadius:`999px`,background:`#fee2e2`,color:`#dc2626`,border:`1px solid #fca5a5`,fontWeight:600,fontSize:`14px`,cursor:`pointer`,transition:`all 0.2s ease`},onMouseEnter:e=>{e.currentTarget.style.background=`#fecaca`},onMouseLeave:e=>{e.currentTarget.style.background=`#fee2e2`},children:[(0,u.jsx)(Pn,{size:18}),`End Voice Session`]}),(0,u.jsx)(`style`,{children:`
|
|
488
488
|
@keyframes fe-orb-pulse {
|
|
489
489
|
0% { transform: scale(1); opacity: 0.6; }
|
|
490
490
|
50% { transform: scale(1.18); opacity: 0.15; }
|
|
491
491
|
100% { transform: scale(1); opacity: 0.6; }
|
|
492
492
|
}
|
|
493
|
-
`})]})}function
|
|
493
|
+
`})]})}function T_(e,t={}){let n=t.maxChars??4500;if(!Array.isArray(e)||e.length===0)return``;let r=[];for(let t of e){if(!t||t.isPending)continue;let e=String(t.sender||``).toLowerCase(),n=null;if(e===`user`?n=`Visitor`:(e===`bot`||e===`ai`||e===`agent`)&&(n=`Assistant`),!n)continue;let i=String(t.message||``).replace(/<[^>]+>/g,` `).replace(/\s+/g,` `).trim().slice(0,1200);i&&r.push(`${n}: ${i}`)}if(r.length===0)return``;let i=r.join(`
|
|
494
494
|
`);return i.length>n&&(i=`…(earlier messages omitted)
|
|
495
|
-
`+i.slice(-n)),i}var
|
|
495
|
+
`+i.slice(-n)),i}var E_=[{key:`become_client`,label:`Become a Client`},{key:`sales_enquiry`,label:`Sales Enquiry`},{key:`learn_services`,label:`Learn about our Services`},{key:`get_support`,label:`Get Support`},{key:`looking_for_job`,label:`Looking for a Job`}],D_=()=>(0,u.jsx)(`div`,{style:{display:`flex`,marginBottom:`12px`,justifyContent:`flex-start`},children:(0,u.jsxs)(`div`,{style:{display:`flex`,alignItems:`center`,gap:`5px`,padding:`12px 16px`,borderRadius:`18px`,background:`#fff`,color:`#111827`,boxShadow:`0 2px 6px rgba(0,0,0,0.04)`},children:[[0,1,2].map(e=>(0,u.jsx)(`span`,{style:{width:`7px`,height:`7px`,borderRadius:`50%`,background:`#9ca3af`,animation:`fe-dot-bounce 1.2s ease-in-out ${e*.2}s infinite`,display:`inline-block`}},e)),(0,u.jsx)(`style`,{children:`
|
|
496
496
|
@keyframes fe-dot-bounce {
|
|
497
497
|
0%, 80%, 100% { transform: translateY(0); opacity: 0.5; }
|
|
498
498
|
40% { transform: translateY(-5px); opacity: 1; }
|
|
499
499
|
}
|
|
500
|
-
`})]})});function
|
|
500
|
+
`})]})});function O_(){let{status:e,runtimeConfig:t,resolvedConfig:n,chatId:r,chatHistory:i,isOpen:a,activeScreen:o,isHumanHandled:s,agentName:c,agentHeadshot:d,visitorEmail:f,isAgentTyping:p,isAiTyping:m,isLoading:ee,isVoiceMode:h,isRateLimited:g,rateLimitMessage:te,isConversationEnded:ne,incomingCall:re,activeCallId:ie,callConnectionState:ae,callConnectedAt:oe,isCallMuted:_,webRTCError:v,language:se,historyRef:ce,onMessageSync:le,endConversation:y,acceptCall:ue,rejectCall:de,endWebRTCCall:fe,toggleCallMute:pe,dismissCallError:me,captureVisitorEmail:he,openWidget:ge,closeWidget:_e,sendMessage:ve,setVoiceMode:ye,startTyping:be,stopTyping:xe,updateTypingDraft:Se}=Jt(),[Ce,we]=(0,l.useState)(``),[Te,Ee]=(0,l.useState)(null),[De,Oe]=(0,l.useState)(null),[ke,Ae]=(0,l.useState)(null),[je,Me]=(0,l.useState)(0),[Ne,b]=(0,l.useState)(f||``),[Pe,Fe]=(0,l.useState)(``);(0,l.useEffect)(()=>{try{en()}catch{}},[]);let Ie=t?.widgetSettings||{},x=n?.widgetSettings||{},S={...x.branding||{},...Ie.branding||{}},Le={...x.theme||{},...Ie.theme||{}},Re=Le.primaryColor||`#3B82F6`,ze=Le.accentColor||`#1D4ED8`,Be=(Le.position||`bottom-right`)===`bottom-left`?{left:`1.5rem`,bottom:`1.5rem`}:{right:`1.5rem`,bottom:`1.5rem`},Ve={"--flowengage-primary":Re,"--flowengage-accent":ze,position:`fixed`,zIndex:999999,border:`none`,outline:`none`,fontFamily:`ui-sans-serif, system-ui, sans-serif`,...a?{}:Be},He=(Ie.recommendations?.[se]||x.recommendations?.[se]||E_||[]).filter(e=>String(e?.label??``).trim().length>0),Ue=Ie.greetings?.[se]||x.greetings?.[se],We=S.chatButtonText||`Chat with us`,Ge=S.headerName||t?.websiteName||`OpenSense Labs`,Ke=S.logoUrl||null,C=S.hideWatermark||!1,w=x.elevenLabsAgentId||t?.elevenLabsAgentId||null,T=t?.siteId||n?.siteId||null,qe=t?.apiBaseUrl||``,Je=S.fallbackAgentName||`Agent`,Ye=S.botLabel||`AI`,Xe=(0,l.useMemo)(()=>S.fallbackAgentName&&String(S.fallbackAgentName).trim()||c||`Agent`,[S.fallbackAgentName,c]),Ze=S.fallbackAgentName&&String(S.fallbackAgentName).trim()||``,Qe=d&&String(d).trim()||t?.ownerProfileImageUrl&&String(t.ownerProfileImageUrl).trim()||null,$e=o===`agent`&&Ze?null:Qe,et=re?.agentName||Xe,tt=i.some(e=>e.sender===`user`),nt=(0,l.useMemo)(()=>{let e=i.findIndex(e=>e.sender===`user`);return e===-1?!1:i.slice(e+1).some(e=>e.sender===`bot`||e.sender===`ai`||e.sender===`agent`)},[i]),rt=(0,l.useMemo)(()=>T_(i),[i]),it=!f&&tt&&nt;(0,l.useEffect)(()=>{b(f||``),f&&Fe(``)},[f]),(0,l.useEffect)(()=>{if(!oe||ae!==`connected`){Me(0);return}let e=()=>{let e=new Date(oe).getTime();isNaN(e)||Me(Math.max(0,Math.floor((Date.now()-e)/1e3)))};e();let t=window.setInterval(e,1e3);return()=>window.clearInterval(t)},[oe,ae]),(0,l.useEffect)(()=>{if(!s||h||ne){Se(``),xe();return}if(!Ce.trim()){Se(``),xe();return}be();let e=window.setTimeout(()=>{Se(Ce)},120),t=window.setTimeout(()=>{xe()},1200);return()=>{window.clearTimeout(e),window.clearTimeout(t)}},[Ce,s,h,ne,be,xe,Se]);let at=e=>e?{replyTo:e.messageId||e.id||null,replyToContent:(e.replyToContent||e.message||``).replace(/<[^>]+>/g,``).trim().slice(0,200),replyToSender:e.sender||null}:null,ot=async e=>{if(e.preventDefault(),ne)return;if(it){let e=Ne.trim().toLowerCase();if(!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(e)){Fe(`Please enter a valid email so we can continue helping you.`);return}await he(e),Fe(``);return}if(!Ce.trim())return;let t=Ce.trim(),n=at(ke);we(``),Ae(null),await ve(t,``,n)},st=async()=>{if(it){Fe(`Please share your email before starting a call.`);return}if(h){ye(!1);return}Oe(null);try{Ee(await navigator.mediaDevices.getUserMedia({audio:!0})),ye(!0)}catch(e){Oe(e.message||`Could not access microphone.`)}},ct=()=>{Te&&(Te.getTracks().forEach(e=>e.stop()),Ee(null)),ye(!1)},lt=e=>{let t=Math.floor(e/60),n=e%60;return`${t.toString().padStart(2,`0`)}:${n.toString().padStart(2,`0`)}`};return e===`ready`?(0,u.jsxs)(`div`,{className:`flowengage-shell`,"data-open":a?`true`:`false`,style:Ve,children:[(0,u.jsx)(Vn,{isOpen:a,openWidget:ge,launcherText:We,primaryColor:Re,posInline:Be}),a&&(0,u.jsxs)(`div`,{className:`flowengage-chat-panel`,style:{background:i.length===0&&!h?`linear-gradient(to bottom, ${Re} 0%, ${ze} 52%, #ffffff 88%)`:`white`},children:[(0,u.jsx)(Kn,{logoUrl:Ke,brandName:Ge,agentName:c,fallbackAgentName:Je,activeScreen:o,branding:S,isConversationEnded:ne,endConversation:y,closeWidget:_e,isInitial:i.length===0&&!h,botLabel:Ye,agentAvatarUrl:o===`agent`?$e:null,primaryColor:Re}),(0,u.jsx)(`div`,{style:{flex:1,overflowY:`auto`,display:`flex`,flexDirection:`column`},className:`flowengage-content-wrapper`,children:h?(0,u.jsx)(`div`,{style:{flex:1,display:`flex`,flexDirection:`column`},className:`fe-screen-fade-in`,children:(0,u.jsx)(w_,{agentId:w,chatId:r,siteId:T,apiBaseUrl:qe,historyRef:ce,onMessageSync:le,onEnd:ct,priorChatContext:rt})},`voice`):i.length===0?(0,u.jsx)(`div`,{style:{flex:1,display:`flex`,flexDirection:`column`},className:`fe-screen-fade-in`,children:(0,u.jsx)(tr,{greetings:Ue,recommendations:He,onSendMessage:ve})},`welcome`):(0,u.jsx)(`div`,{style:{flex:1,display:`flex`,flexDirection:`column`},className:`fe-screen-fade-in`,children:(0,u.jsx)(Zn,{chatHistory:i,isAiTyping:m,isAgentTyping:p,setReplyContext:Ae,TypingDots:D_,primaryColor:Re,agentHeadshot:Qe,agentDisplayName:Xe})},`history`)}),(0,u.jsx)(ar,{webRTCError:v,micError:De,setMicError:Oe,dismissCallError:me,incomingCall:re,rejectCall:de,acceptCall:ue,activeCallId:ie,callConnectionState:ae,formatCallDuration:lt,callDurationSeconds:je,endWebRTCCall:fe,isCallMuted:_,toggleCallMute:pe,isAIVoiceActive:h,currentCallAgentName:et,isRateLimited:g,rateLimitMessage:te}),!h&&(0,u.jsx)(`div`,{style:{position:`relative`,zIndex:1},children:(0,u.jsx)(nr,{input:Ce,setInput:we,onSubmit:ot,isConversationEnded:ne,callUiActive:!!(re||ie),handleToggleVoice:st,activeScreen:o,inputDisabled:ee||g||ne,replyContext:ke,clearReplyContext:()=>Ae(null),requiresEmail:it,emailInput:Ne,setEmailInput:b,emailError:Pe})}),!C&&(0,u.jsx)(`div`,{style:{position:`relative`,zIndex:1,display:`flex`,alignItems:`center`,justifyContent:`center`,gap:`12px`,paddingTop:`12px`,paddingBottom:`16px`,fontSize:`12px`,color:`#9ca3af`},children:(0,u.jsxs)(`div`,{children:[`Powered by `,(0,u.jsx)(`span`,{style:{color:`#3b82f6`},children:`Flow`}),(0,u.jsx)(`span`,{style:{color:`#ef4444`},children:`Engage`})]})})]})]}):null}exports.FlowEngageProvider=An,exports.FlowEngageWidget=O_,exports.useFlowEngage=Jt;
|