1(()=>{var xT=Object.create;var Um=Object.defineProperty;var NT=Object.getOwnPropertyDescriptor;var FT=Object.getOwnPropertyNames;var UT=Object.getPrototypeOf,jT=Object.prototype.hasOwnProperty;var or=(i,e)=>()=>{try{return e||i((e={exports:{}}).exports,e),e.exports}catch(t){throw e=0,t}};var BT=(i,e,t,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let r of FT(e))!jT.call(i,r)&&r!==t&&Um(i,r,{get:()=>e[r],enumerable:!(n=NT(e,r))||n.enumerable});return i};var qT=(i,e,t)=>(t=i!=null?xT(UT(i)):{},BT(e||!i||!i.__esModule?Um(t,"default",{value:i,enumerable:!0}):t,i));var Tk=or((Bs,rh)=>{(function(i,e){typeof Bs=="object"&&typeof rh=="object"?rh.exports=e():typeof define=="function"&&define.amd?define([],e):typeof Bs=="object"?Bs.Daily=e():i.Daily=e()})(Bs,(function(){return(function(){var i={7:function(n){"use strict";var r,s=typeof Reflect=="object"?Reflect:null,o=s&&typeof s.apply=="function"?s.apply:function(j,M,P){return Function.prototype.apply.call(j,M,P)};r=s&&typeof s.ownKeys=="function"?s.ownKeys:Object.getOwnPropertySymbols?function(j){return Object.getOwnPropertyNames(j).concat(Object.getOwnPropertySymbols(j))}:function(j){return Object.getOwnPropertyNames(j)};var a=Number.isNaN||function(j){return j!=j};function d(){d.init.call(this)}n.exports=d,n.exports.once=function(j,M){return new Promise((function(P,B){function q(ie){j.removeListener(M,K),B(ie)}function K(){typeof j.removeListener=="function"&&j.removeListener("error",q),P([].slice.call(arguments))}L(j,M,K,{once:!0}),M!=="error"&&(function(ie,te){typeof ie.on=="function"&&L(ie,"error",te,{once:!0})})(j,q)}))},d.EventEmitter=d,d.prototype._events=void 0,d.prototype._eventsCount=0,d.prototype._maxListeners=void 0;var l=10;function f(j){if(typeof j!="function")throw new TypeError('The "listener" argument must be of type Function. Received type '+typeof j)}function p(j){return j._maxListeners===void 0?d.defaultMaxListeners:j._maxListeners}function g(j,M,P,B){var q,K,ie,te;if(f(P),(K=j._events)===void 0?(K=j._events=Object.create(null),j._eventsCount=0):(K.newListener!==void 0&&(j.emit("newListener",M,P.listener?P.listener:P),K=j._events),ie=K[M]),ie===void 0)ie=K[M]=P,++j._eventsCount;else if(typeof ie=="function"?ie=K[M]=B?[P,ie]:[ie,P]:B?ie.unshift(P):ie.push(P),(q=p(j))>0&&ie.length>q&&!ie.warned){ie.warned=!0;var ae=new Error("Possible EventEmitter memory leak detected. "+ie.length+" "+String(M)+" listeners added. Use emitter.setMaxListeners() to increase limit");ae.name="MaxListenersExceededWarning",ae.emitter=j,ae.type=M,ae.count=ie.length,te=ae,console&&console.warn&&console.warn(te)}return j}function b(){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 R(j,M,P){var B={fired:!1,wrapFn:void 0,target:j,type:M,listener:P},q=b.bind(B);return q.listener=P,B.wrapFn=q,q}function w(j,M,P){var B=j._events;if(B===void 0)return[];var q=B[M];return q===void 0?[]:typeof q=="function"?P?[q.listener||q]:[q]:P?(function(K){for(var ie=new Array(K.length),te=0;te<ie.length;++te)ie[te]=K[te].listener||K[te];return ie})(q):N(q,q.length)}function I(j){var M=this._events;if(M!==void 0){var P=M[j];if(typeof P=="function")return 1;if(P!==void 0)return P.length}return 0}function N(j,M){for(var P=new Array(M),B=0;B<M;++B)P[B]=j[B];return P}function L(j,M,P,B){if(typeof j.on=="function")B.once?j.once(M,P):j.on(M,P);else{if(typeof j.addEventListener!="function")throw new TypeError('The "emitter" argument must be of type EventEmitter. Received type '+typeof j);j.addEventListener(M,(function q(K){B.once&&j.removeEventListener(M,q),P(K)}))}}Object.defineProperty(d,"defaultMaxListeners",{enumerable:!0,get:function(){return l},set:function(j){if(typeof j!="number"||j<0||a(j))throw new RangeError('The value of "defaultMaxListeners" is out of range. It must be a non-negative number. Received '+j+".");l=j}}),d.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},d.prototype.setMaxListeners=function(j){if(typeof j!="number"||j<0||a(j))throw new RangeError('The value of "n" is out of range. It must be a non-negative number. Received '+j+".");return this._maxListeners=j,this},d.prototype.getMaxListeners=function(){return p(this)},d.prototype.emit=function(j){for(var M=[],P=1;P<arguments.length;P++)M.push(arguments[P]);var B=j==="error",q=this._events;if(q!==void 0)B=B&&q.error===void 0;else if(!B)return!1;if(B){var K;if(M.length>0&&(K=M[0]),K instanceof Error)throw K;var ie=new Error("Unhandled error."+(K?" ("+K.message+")":""));throw ie.context=K,ie}var te=q[j];if(te===void 0)return!1;if(typeof te=="function")o(te,this,M);else{var ae=te.length,ge=N(te,ae);for(P=0;P<ae;++P)o(ge[P],this,M)}return!0},d.prototype.addListener=function(j,M){return g(this,j,M,!1)},d.prototype.on=d.prototype.addListener,d.prototype.prependListener=function(j,M){return g(this,j,M,!0)}
1,d.prototype.once=function(j,M){return f(M),this.on(j,R(this,j,M)),this},d.prototype.prependOnceListener=function(j,M){return f(M),this.prependListener(j,R(this,j,M)),this},d.prototype.removeListener=function(j,M){var P,B,q,K,ie;if(f(M),(B=this._events)===void 0)return this;if((P=B[j])===void 0)return this;if(P===M||P.listener===M)--this._eventsCount==0?this._events=Object.create(null):(delete B[j],B.removeListener&&this.emit("removeListener",j,P.listener||M));else if(typeof P!="function"){for(q=-1,K=P.length-1;K>=0;K--)if(P[K]===M||P[K].listener===M){ie=P[K].listener,q=K;break}if(q<0)return this;q===0?P.shift():(function(te,ae){for(;ae+1<te.length;ae++)te[ae]=te[ae+1];te.pop()})(P,q),P.length===1&&(B[j]=P[0]),B.removeListener!==void 0&&this.emit("removeListener",j,ie||M)}return this},d.prototype.off=d.prototype.removeListener,d.prototype.removeAllListeners=function(j){var M,P,B;if((P=this._events)===void 0)return this;if(P.removeListener===void 0)return arguments.length===0?(this._events=Object.create(null),this._eventsCount=0):P[j]!==void 0&&(--this._eventsCount==0?this._events=Object.create(null):delete P[j]),this;if(arguments.length===0){var q,K=Object.keys(P);for(B=0;B<K.length;++B)(q=K[B])!=="removeListener"&&this.removeAllListeners(q);return this.removeAllListeners("removeListener"),this._events=Object.create(null),this._eventsCount=0,this}if(typeof(M=P[j])=="function")this.removeListener(j,M);else if(M!==void 0)for(B=M.length-1;B>=0;B--)this.removeListener(j,M[B]);return this},d.prototype.listeners=function(j){return w(this,j,!0)},d.prototype.rawListeners=function(j){return w(this,j,!1)},d.listenerCount=function(j,M){return typeof j.listenerCount=="function"?j.listenerCount(M):I.call(j,M)},d.prototype.listenerCount=I,d.prototype.eventNames=function(){return this._eventsCount>0?r(this._events):[]}},781:function(n,r,s){var o=s(948);n.exports=o.default},880:function(n){n.exports=(function(r){var s={};function o(a){if(s[a])return s[a].exports;var d=s[a]={i:a,l:!1,exports:{}};return r[a].call(d.exports,d,d.exports,o),d.l=!0,d.exports}return o.m=r,o.c=s,o.d=function(a,d,l){o.o(a,d)||Object.defineProperty(a,d,{enumerable:!0,get:l})},o.r=function(a){typeof Symbol<"u"&&Symbol.toStringTag&&Object.defineProperty(a,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(a,"__esModule",{value:!0})},o.t=function(a,d){if(1&d&&(a=o(a)),8&d||4&d&&typeof a=="object"&&a&&a.__esModule)return a;var l=Object.create(null);if(o.r(l),Object.defineProperty(l,"default",{enumerable:!0,value:a}),2&d&&typeof a!="string")for(var f in a)o.d(l,f,function(p){return a[p]}.bind(null,f));return l},o.n=function(a){var d=a&&a.__esModule?function(){return a.default}:function(){return a};return o.d(d,"a",d),d},o.o=function(a,d){return Object.prototype.hasOwnProperty.call(a,d)},o.p="",o(o.s=90)})({17:function(r,s,o){"use strict";s.__esModule=!0,s.default=void 0;var a=o(18),d=(function(){function l(){}return l.getFirstMatch=function(f,p){var g=p.match(f);return g&&g.length>0&&g[1]||""},l.getSecondMatch=function(f,p){var g=p.match(f);return g&&g.length>1&&g[2]||""},l.matchAndReturnConst=function(f,p,g){if(f.test(p))return g},l.getWindowsVersionName=function(f){switch(f){case"NT":return"NT";case"XP":case"NT 5.1":return"XP";case"NT 5.0":return"2000";case"NT 5.2":return"2003";case"NT 6.0":return"Vista";case"NT 6.1":return"7";case"NT 6.2":return"8";case"NT 6.3":return"8.1";case"NT 10.0":return"10";default:return}},l.getMacOSVersionName=function(f){var p=f.split(".").splice(0,2).map((function(g){return parseInt(g,10)||0}));if(p.push(0),p[0]===10)switch(p[1]){case 5:return"Leopard";case 6:return"Snow Leopard";case 7:return"Lion";case 8:return"Mountain Lion";case 9:return"Mavericks";case 10:return"Yosemite";case 11:return"El Capitan";case 12:return"Sierra";case 13:return"High Sierra";case 14:return"Mojave";case 15:return"Catalina";default:return}},l.getAndroidVersionName=function(f){var p=f.split(".").splice(0,2).map((function(g){return parseInt(g,10)||0}));if(p.push(0),!(p[0]===1&&p[1]<5))return p[0]===1&&p[1]<6?"Cupcake":p[0]===1&&p[1]>=6?"Donut":p[0]===2&&p[1]<2?"Eclair":p[0]===2&&p[1]===2?"Froyo":p[0]===2&&p[1]>2?"Gingerbread":p[0]===3?"Honeycomb":p[0]===4&&p[1]<1?"Ice Cream Sandwich":p[0]===4&&p[1]<4?"Jelly Bean":p[0]===4&&p[1]>=4?"KitKat":p[0]===5?"Lollipop":p[0]===6?"Marshmallow":p[0]===7?"Nougat":p[0]===8?"Oreo":p[0]===9?"Pie":void 0},l.getVersionPrecision=function(f){return f.split(".").length},l.compareVersions=function(f,p,g){g===void 0&&(g=!1);var b=l.getVersionPrecision(f),R=l.getVersionPrecision(p),w=Math.max(b,R),I=0,N=l.map([f,p],(function(L){var j=w-l.getVersionPrecision(L),M=L+new Array(j+1).join(".0");return l.map(M.split("."),(function(P){return new Array(20-P.length).join("0")+P})).reverse()}));for(g&&(I=w-Math.min(b,R)),w-=1;w>=I;){if(N[0][w]>N[1][w])return 1;if(N[0][w]===N[1][w]){if(w===I)return 0;w-=1}else if(N[0][w]<N[1][w])return-1}},l.map=function(f,p){var g,b=[];if(Array.prototype.map)return Array.prototype.map.call(f,p);for(g=0;g<f.length;g+=1)b.push(p(f[g]));return b},l.find=function(f,p){var g,b;if(Array.prototype.find)return Array.prototype.find.call(f,p);for(g=0,b=f.length;g<b;g+=1){var R=f[g];if(p(R,g))return R}},l.assign=function(f){for(var p,g,b=f,R=arguments.length,w=new Array(R>1?R-1:0),I=1;I<R;I++)w[I-1]=arguments[I];if(Object.assign)return Object.assign.apply(Object,[f].concat(w));var N=function(){var L=w[p];
1typeof L=="object"&&L!==null&&Object.keys(L).forEach((function(j){b[j]=L[j]}))};for(p=0,g=w.length;p<g;p+=1)N();return f},l.getBrowserAlias=function(f){return a.BROWSER_ALIASES_MAP[f]},l.getBrowserTypeByAlias=function(f){return a.BROWSER_MAP[f]||""},l})();s.default=d,r.exports=s.default},18:function(r,s,o){"use strict";s.__esModule=!0,s.ENGINE_MAP=s.OS_MAP=s.PLATFORMS_MAP=s.BROWSER_MAP=s.BROWSER_ALIASES_MAP=void 0,s.BROWSER_ALIASES_MAP={"Amazon Silk":"amazon_silk","Android Browser":"android",Bada:"bada",BlackBerry:"blackberry",Chrome:"chrome",Chromium:"chromium",Electron:"electron",Epiphany:"epiphany",Firefox:"firefox",Focus:"focus",Generic:"generic","Google Search":"google_search",Googlebot:"googlebot","Internet Explorer":"ie","K-Meleon":"k_meleon",Maxthon:"maxthon","Microsoft Edge":"edge","MZ Browser":"mz","NAVER Whale Browser":"naver",Opera:"opera","Opera Coast":"opera_coast",PhantomJS:"phantomjs",Puffin:"puffin",QupZilla:"qupzilla",QQ:"qq",QQLite:"qqlite",Safari:"safari",Sailfish:"sailfish","Samsung Internet for Android":"samsung_internet",SeaMonkey:"seamonkey",Sleipnir:"sleipnir",Swing:"swing",Tizen:"tizen","UC Browser":"uc",Vivaldi:"vivaldi","WebOS Browser":"webos",WeChat:"wechat","Yandex Browser":"yandex",Roku:"roku"},s.BROWSER_MAP={amazon_silk:"Amazon Silk",android:"Android Browser",bada:"Bada",blackberry:"BlackBerry",chrome:"Chrome",chromium:"Chromium",electron:"Electron",epiphany:"Epiphany",firefox:"Firefox",focus:"Focus",generic:"Generic",googlebot:"Googlebot",google_search:"Google Search",ie:"Internet Explorer",k_meleon:"K-Meleon",maxthon:"Maxthon",edge:"Microsoft Edge",mz:"MZ Browser",naver:"NAVER Whale Browser",opera:"Opera",opera_coast:"Opera Coast",phantomjs:"PhantomJS",puffin:"Puffin",qupzilla:"QupZilla",qq:"QQ Browser",qqlite:"QQ Browser Lite",safari:"Safari",sailfish:"Sailfish",samsung_internet:"Samsung Internet for Android",seamonkey:"SeaMonkey",sleipnir:"Sleipnir",swing:"Swing",tizen:"Tizen",uc:"UC Browser",vivaldi:"Vivaldi",webos:"WebOS Browser",wechat:"WeChat",yandex:"Yandex Browser"},s.PLATFORMS_MAP={tablet:"tablet",mobile:"mobile",desktop:"desktop",tv:"tv"},s.OS_MAP={WindowsPhone:"Windows Phone",Windows:"Windows",MacOS:"macOS",iOS:"iOS",Android:"Android",WebOS:"WebOS",BlackBerry:"BlackBerry",Bada:"Bada",Tizen:"Tizen",Linux:"Linux",ChromeOS:"Chrome OS",PlayStation4:"PlayStation 4",Roku:"Roku"},s.ENGINE_MAP={EdgeHTML:"EdgeHTML",Blink:"Blink",Trident:"Trident",Presto:"Presto",Gecko:"Gecko",WebKit:"WebKit"}},90:function(r,s,o){"use strict";s.__esModule=!0,s.default=void 0;var a,d=(a=o(91))&&a.__esModule?a:{default:a},l=o(18);function f(g,b){for(var R=0;R<b.length;R++){var w=b[R];w.enumerable=w.enumerable||!1,w.configurable=!0,"value"in w&&(w.writable=!0),Object.defineProperty(g,w.key,w)}}var p=(function(){function g(){}var b,R;return g.getParser=function(w,I){if(I===void 0&&(I=!1),typeof w!="string")throw new Error("UserAgent should be a string");return new d.default(w,I)},g.parse=function(w){return new d.default(w).getResult()},b=g,R=[{key:"BROWSER_MAP",get:function(){return l.BROWSER_MAP}},{key:"ENGINE_MAP",get:function(){return l.ENGINE_MAP}},{key:"OS_MAP",get:function(){return l.OS_MAP}},{key:"PLATFORMS_MAP",get:function(){return l.PLATFORMS_MAP}}],R&&f(b,R),g})();s.default=p,r.exports=s.default},91:function(r,s,o){"use strict";s.__esModule=!0,s.default=void 0;var a=g(o(92)),d=g(o(93)),l=g(o(94)),f=g(o(95)),p=g(o(17));function g(R){return R&&R.__esModule?R:{default:R}}var b=(function(){function R(I,N){if(N===void 0&&(N=!1),I==null||I==="")throw new Error("UserAgent parameter can't be empty");this._ua=I,this.parsedResult={},N!==!0&&this.parse()}var w=R.prototype;return w.getUA=function(){return this._ua},w.test=function(I){return I.test(this._ua)},w.parseBrowser=function(){var I=this;this.parsedResult.browser={};var N=p.default.find(a.default,(function(L){if(typeof L.test=="function")return L.test(I);if(L.test instanceof Array)return L.test.some((function(j){return I.test(j)}));throw new Error("Browser's test function is not valid")}));return N&&(this.parsedResult.browser=N.describe(this.getUA())),this.parsedResult.browser},w.getBrowser=function(){return this.parsedResult.browser?this.parsedResult.browser:this.parseBrowser()},w.getBrowserName=function(I){return I?String(this.getBrowser().name).toLowerCase()||"":this.getBrowser().name||""},w.getBrowserVersion=function(){return this.getBrowser().version},w.getOS=function(){return this.parsedResult.os?this.parsedResult.os:this.parseOS()},w.parseOS=function(){var I=this;this.parsedResult.os={};var N=p.default.find(d.default,(function(L){if(typeof L.test=="function")return L.test(I
1);if(L.test instanceof Array)return L.test.some((function(j){return I.test(j)}));throw new Error("Browser's test function is not valid")}));return N&&(this.parsedResult.os=N.describe(this.getUA())),this.parsedResult.os},w.getOSName=function(I){var N=this.getOS().name;return I?String(N).toLowerCase()||"":N||""},w.getOSVersion=function(){return this.getOS().version},w.getPlatform=function(){return this.parsedResult.platform?this.parsedResult.platform:this.parsePlatform()},w.getPlatformType=function(I){I===void 0&&(I=!1);var N=this.getPlatform().type;return I?String(N).toLowerCase()||"":N||""},w.parsePlatform=function(){var I=this;this.parsedResult.platform={};var N=p.default.find(l.default,(function(L){if(typeof L.test=="function")return L.test(I);if(L.test instanceof Array)return L.test.some((function(j){return I.test(j)}));throw new Error("Browser's test function is not valid")}));return N&&(this.parsedResult.platform=N.describe(this.getUA())),this.parsedResult.platform},w.getEngine=function(){return this.parsedResult.engine?this.parsedResult.engine:this.parseEngine()},w.getEngineName=function(I){return I?String(this.getEngine().name).toLowerCase()||"":this.getEngine().name||""},w.parseEngine=function(){var I=this;this.parsedResult.engine={};var N=p.default.find(f.default,(function(L){if(typeof L.test=="function")return L.test(I);if(L.test instanceof Array)return L.test.some((function(j){return I.test(j)}));throw new Error("Browser's test function is not valid")}));return N&&(this.parsedResult.engine=N.describe(this.getUA())),this.parsedResult.engine},w.parse=function(){return this.parseBrowser(),this.parseOS(),this.parsePlatform(),this.parseEngine(),this},w.getResult=function(){return p.default.assign({},this.parsedResult)},w.satisfies=function(I){var N=this,L={},j=0,M={},P=0;if(Object.keys(I).forEach((function(ke){var Oe=I[ke];typeof Oe=="string"?(M[ke]=Oe,P+=1):typeof Oe=="object"&&(L[ke]=Oe,j+=1)})),j>0){var B=Object.keys(L),q=p.default.find(B,(function(ke){return N.isOS(ke)}));if(q){var K=this.satisfies(L[q]);if(K!==void 0)return K}var ie=p.default.find(B,(function(ke){return N.isPlatform(ke)}));if(ie){var te=this.satisfies(L[ie]);if(te!==void 0)return te}}if(P>0){var ae=Object.keys(M),ge=p.default.find(ae,(function(ke){return N.isBrowser(ke,!0)}));if(ge!==void 0)return this.compareVersion(M[ge])}},w.isBrowser=function(I,N){N===void 0&&(N=!1);var L=this.getBrowserName().toLowerCase(),j=I.toLowerCase(),M=p.default.getBrowserTypeByAlias(j);return N&&M&&(j=M.toLowerCase()),j===L},w.compareVersion=function(I){var N=[0],L=I,j=!1,M=this.getBrowserVersion();if(typeof M=="string")return I[0]===">"||I[0]==="<"?(L=I.substr(1),I[1]==="="?(j=!0,L=I.substr(2)):N=[],I[0]===">"?N.push(1):N.push(-1)):I[0]==="="?L=I.substr(1):I[0]==="~"&&(j=!0,L=I.substr(1)),N.indexOf(p.default.compareVersions(M,L,j))>-1},w.isOS=function(I){return this.getOSName(!0)===String(I).toLowerCase()},w.isPlatform=function(I){return this.getPlatformType(!0)===String(I).toLowerCase()},w.isEngine=function(I){return this.getEngineName(!0)===String(I).toLowerCase()},w.is=function(I,N){return N===void 0&&(N=!1),this.isBrowser(I,N)||this.isOS(I)||this.isPlatform(I)},w.some=function(I){var N=this;return I===void 0&&(I=[]),I.some((function(L){return N.is(L)}))},R})();s.default=b,r.exports=s.default},92:function(r,s,o){"use strict";s.__esModule=!0,s.default=void 0;var a,d=(a=o(17))&&a.__esModule?a:{default:a},l=/version\/(\d+(\.?_?\d+)+)/i,f=[{test:[/googlebot/i],describe:function(p){var g={name:"Googlebot"},b=d.default.getFirstMatch(/googlebot\/(\d+(\.\d+))/i,p)||d.default.getFirstMatch(l,p);return b&&(g.version=b),g}},{test:[/opera/i],describe:function(p){var g={name:"Opera"},b=d.default.getFirstMatch(l,p)||d.default.getFirstMatch(/(?:opera)[\s/](\d+(\.?_?\d+)+)/i,p);return b&&(g.version=b),g}},{test:[/opr\/|opios/i],describe:function(p){var g={name:"Opera"},b=d.default.getFirstMatch(/(?:opr|opios)[\s/](\S+)/i,p)||d.default.getFirstMatch(l,p);return b&&(g.version=b),g}},{test:[/SamsungBrowser/i],describe:function(p){var g={name:"Samsung Internet for Android"},b=d.default.getFirstMatch(l,p)||d.default.getFirstMatch(/(?:SamsungBrowser)[\s/](\d+(\.?_?\d+)+)/i,p);return b&&(g.version=b),g}},{test:[/Whale/i],describe:function(p){var g={name:"NAVER Whale Browser"},b=d.default.getFirstMatch(l,p)||d.default.getFirstMatch(/(?:whale)[\s/](\d+(?:\.\d+)+)/i,p);return b&&(g.version=b),g}},{test:[/MZBrowser/i],describe:function(p){var g={name:"MZ Browser"},b=d.default.getFirstMatch(/(?:MZBrowser)[\s/](\d+(?:\.\d+)+)/i,p)||d.default.getFirstMatch(l,p);return b&&(g.version=b),g}},{test:[/focus/i],describe:function(p){var g={name:"Focus"},b=d.default.getFirstMatch(/(?:focus)[\s/](\d+(?:\.\d+)+)/i,p)||d.default.getFirstMatch(l,p);return b&&(g.version=b),g}},{test:[/swing/i],describe:function(p){var g={name:"Swing"},b=d.default.getFirstMatch(/(?:swing)[\s/](\d+(?:\.\d+)+)/i,p)||d.default.getFirstMatch(l,p);return b&&(g.version=b),g}},{test:[/coast/i],describe:function(p){var g={name:"Opera Coast"},b=d.default.getFirstMatch(l,p)||d.default.getFirstMatch(/(?:coast)[\s/](\d+(\.?_?\d+)+)/i,p);return b&&(g.version=b),g}},{test:[/opt\/\d+(?:.?_?\d+)+/i],describe:function(p){var g={name:"Opera Touch"},b=d.default.getFirstMatch(/(?:opt)[\s/](\d+(\.?_?\d+)+)/i,p)||d.default.getFirstMatch(l,p);return b&&(g.version=b),g}},{test:[/yabrowser/i],describe:function(p){var g={name:"Yandex Browser"},b=d.default.getFirstMatch(/(?:yabrowser)[\s/](\d+(\.?_?\d+)+)/i,p)||d.default.getFirstMatch(l,p);return b&&(g.version=b),g}},{test:[/ucbrowser/i],describe:function(p){var g={name:"UC Browser"},b=d.default.getFirstMatch(l,p)||d.default.getFirstMatch(/(?:ucbrowser)[\s/](\d+(\.?_?\d+)+)/i,p);return b&&(g.version=b),g}},{test:[/Maxthon|mxios/i],describe:function(p){var g={name:"Maxthon"}
vendor: 7,818 bytes, line 1
1,b=d.default.getFirstMatch(l,p)||d.default.getFirstMatch(/(?:Maxthon|mxios)[\s/](\d+(\.?_?\d+)+)/i,p);return b&&(g.version=b),g}},{test:[/epiphany/i],describe:function(p){var g={name:"Epiphany"},b=d.default.getFirstMatch(l,p)||d.default.getFirstMatch(/(?:epiphany)[\s/](\d+(\.?_?\d+)+)/i,p);return b&&(g.version=b),g}},{test:[/puffin/i],describe:function(p){var g={name:"Puffin"},b=d.default.getFirstMatch(l,p)||d.default.getFirstMatch(/(?:puffin)[\s/](\d+(\.?_?\d+)+)/i,p);return b&&(g.version=b),g}},{test:[/sleipnir/i],describe:function(p){var g={name:"Sleipnir"},b=d.default.getFirstMatch(l,p)||d.default.getFirstMatch(/(?:sleipnir)[\s/](\d+(\.?_?\d+)+)/i,p);return b&&(g.version=b),g}},{test:[/k-meleon/i],describe:function(p){var g={name:"K-Meleon"},b=d.default.getFirstMatch(l,p)||d.default.getFirstMatch(/(?:k-meleon)[\s/](\d+(\.?_?\d+)+)/i,p);return b&&(g.version=b),g}},{test:[/micromessenger/i],describe:function(p){var g={name:"WeChat"},b=d.default.getFirstMatch(/(?:micromessenger)[\s/](\d+(\.?_?\d+)+)/i,p)||d.default.getFirstMatch(l,p);return b&&(g.version=b),g}},{test:[/qqbrowser/i],describe:function(p){var g={name:/qqbrowserlite/i.test(p)?"QQ Browser Lite":"QQ Browser"},b=d.default.getFirstMatch(/(?:qqbrowserlite|qqbrowser)[/](\d+(\.?_?\d+)+)/i,p)||d.default.getFirstMatch(l,p);return b&&(g.version=b),g}},{test:[/msie|trident/i],describe:function(p){var g={name:"Internet Explorer"},b=d.default.getFirstMatch(/(?:msie |rv:)(\d+(\.?_?\d+)+)/i,p);return b&&(g.version=b),g}},{test:[/\sedg\//i],describe:function(p){var g={name:"Microsoft Edge"},b=d.default.getFirstMatch(/\sedg\/(\d+(\.?_?\d+)+)/i,p);return b&&(g.version=b),g}},{test:[/edg([ea]|ios)/i],describe:function(p){var g={name:"Microsoft Edge"},b=d.default.getSecondMatch(/edg([ea]|ios)\/(\d+(\.?_?\d+)+)/i,p);return b&&(g.version=b),g}},{test:[/vivaldi/i],describe:function(p){var g={name:"Vivaldi"},b=d.default.getFirstMatch(/vivaldi\/(\d+(\.?_?\d+)+)/i,p);return b&&(g.version=b),g}},{test:[/seamonkey/i],describe:function(p){var g={name:"SeaMonkey"},b=d.default.getFirstMatch(/seamonkey\/(\d+(\.?_?\d+)+)/i,p);return b&&(g.version=b),g}},{test:[/sailfish/i],describe:function(p){var g={name:"Sailfish"},b=d.default.getFirstMatch(/sailfish\s?browser\/(\d+(\.\d+)?)/i,p);return b&&(g.version=b),g}},{test:[/silk/i],describe:function(p){var g={name:"Amazon Silk"},b=d.default.getFirstMatch(/silk\/(\d+(\.?_?\d+)+)/i,p);return b&&(g.version=b),g}},{test:[/phantom/i],describe:function(p){var g={name:"PhantomJS"},b=d.default.getFirstMatch(/phantomjs\/(\d+(\.?_?\d+)+)/i,p);return b&&(g.version=b),g}},{test:[/slimerjs/i],describe:function(p){var g={name:"SlimerJS"},b=d.default.getFirstMatch(/slimerjs\/(\d+(\.?_?\d+)+)/i,p);return b&&(g.version=b),g}},{test:[/blackberry|\bbb\d+/i,/rim\stablet/i],describe:function(p){var g={name:"BlackBerry"},b=d.default.getFirstMatch(l,p)||d.default.getFirstMatch(/blackberry[\d]+\/(\d+(\.?_?\d+)+)/i,p);return b&&(g.version=b),g}},{test:[/(web|hpw)[o0]s/i],describe:function(p){var g={name:"WebOS Browser"},b=d.default.getFirstMatch(l,p)||d.default.getFirstMatch(/w(?:eb)?[o0]sbrowser\/(\d+(\.?_?\d+)+)/i,p);return b&&(g.version=b),g}},{test:[/bada/i],describe:function(p){var g={name:"Bada"},b=d.default.getFirstMatch(/dolfin\/(\d+(\.?_?\d+)+)/i,p);return b&&(g.version=b),g}},{test:[/tizen/i],describe:function(p){var g={name:"Tizen"},b=d.default.getFirstMatch(/(?:tizen\s?)?browser\/(\d+(\.?_?\d+)+)/i,p)||d.default.getFirstMatch(l,p);return b&&(g.version=b),g}},{test:[/qupzilla/i],describe:function(p){var g={name:"QupZilla"},b=d.default.getFirstMatch(/(?:qupzilla)[\s/](\d+(\.?_?\d+)+)/i,p)||d.default.getFirstMatch(l,p);return b&&(g.version=b),g}},{test:[/firefox|iceweasel|fxios/i],describe:function(p){var g={name:"Firefox"},b=d.default.getFirstMatch(/(?:firefox|iceweasel|fxios)[\s/](\d+(\.?_?\d+)+)/i,p);return b&&(g.version=b),g}},{test:[/electron/i],describe:function(p){var g={name:"Electron"},b=d.default.getFirstMatch(/(?:electron)\/(\d+(\.?_?\d+)+)/i,p);return b&&(g.version=b),g}},{test:[/MiuiBrowser/i],describe:function(p){var g={name:"Miui"},b=d.default.getFirstMatch(/(?:MiuiBrowser)[\s/](\d+(\.?_?\d+)+)/i,p);return b&&(g.version=b),g}},{test:[/chromium/i],describe:function(p){var g={name:"Chromium"},b=d.default.getFirstMatch(/(?:chromium)[\s/](\d+(\.?_?\d+)+)/i,p)||d.default.getFirstMatch(l,p);return b&&(g.version=b),g}},{test:[/chrome|crios|crmo/i],describe:function(p){var g={name:"Chrome"},b=d.default.getFirstMatch(/(?:chrome|crios|crmo)\/(\d+(\.?_?\d+)+)/i,p);return b&&(g.version=b),g}},{test:[/GSA/i],describe:function(p){var g={name:"Google Search"},b=d.default.getFirstMatch(/(?:GSA)\/(\d+(\.?_?\d+)+)/i,p);return b&&(g.version=b),g}},{test:function(p){var g=!p.test(/like android/i),b=p.test(/android/i);return g&&b},describe:function(p){var g={name:"Android Browser"},b=d.default.getFirstMatch(l,p);return b&&(g.version=b),g}},{test:[/playstation 4/i],describe:function(p){var g={name:"PlayStation 4"},b=d.default.getFirstMatch(l,p);return b&&(g.version=b),g}},{test:[/safari|applewebkit/i],describe:function(p){var g={name:"Safari"},b=d.default.getFirstMatch(l,p);return b&&(g.version=b),g}},{test:[/.*/i],describe:function(p){var g=p.search("\\(")!==-1?/^(.*)\/(.*)[ \t]\((.*)/:/^(.*)\/(.*) /;return{name:d.default.getFirstMatch(g,p),version:d.default.getSecondMatch(g,p)}}}];s.default=f,r.exports=s.default},93:function(r,s,o){"use strict";s.__esModule=!0,s.default=void 0;var a,d=(a=o(17))&&a.__esModule?a:{default:a},l=o(18),f=[{test:[/Roku\/DVP/],describe:function(p){var g=d.default.getFirstMatch(/Roku\/DVP-(\d+\.\d+)/i,p);return{name:l.OS_MAP.Roku,version:g}}},{test:[/windows phone/i],describe:function(p){var g=d.default.getFirstMatch(/windows phone (?:os)?\s?(\d+(\.\d+)*)/i,p);return{name:l.OS_MAP.WindowsPhone,version:g}}},{test:[/windows /i],describe:function(p){var g=d.default.getFirstMatch(/Windows ((NT|XP)( \d\d?.\d)?)/i,p),b=d.default.getWindowsVersionName(g);return{name:l.OS_MAP.Windows,version:g,versionName:b}}},{test:[/Macintosh(.*?) FxiOS(.*?)\//],describe:function(p){var g={name:l.OS_MAP.iOS},b=d.default.getSecondMatch(/(Version\/)(\d[\d.]+)/,p);return b&&(g.version=b),g}},{test:[/macintosh/i],describe:function(p){var g=d.default.getFirstMatch(/mac os x (\d+(\.?_?\d+)+)/i,p).replace(/[_\s]/g,"."),b=d.default.getMacOSVersionName(g),R={name:l.OS_MAP.MacOS,version:g};return b&&(R.versionName=b),R}},{test:[/(ipod|iphone|ipad)/i],describe:function(p){var g=d.default.getFirstMatch(/os (\d+([_\s]\d+)*) like mac os x/i,p).replace(/[_\s]/g,".");return{name:l.OS_MAP.iOS,version:g}}},{test:function(p){var g=!p.test(/like android/i),b=p.test(/android/i);return g&&b},describe:function(p){var g=d.default.getFirstMatch(/android[\s/-](\d+(\.\d+)*)/i,p),b=d.default.getAndroidVersionName(g),R={name:l.OS_MAP.Android,version:g};return b&&(R.versionName=b),R}},{test:[/(web|hpw)[o0]s/i],describe:function(p){var g=d.default.getFirstMatch(/(?:web|hpw)[o0]s\/(\d+(\.\d+)*)/i,p),b={name:l.OS_MAP.WebOS};return g&&g.length&&(b.version=g),b}},{test:[/blackberry|\bbb\d+/i,/rim\stablet/i],describe:function(p){var g=d.default.getFirstMatch(/rim\stablet\sos\s(\d+(\.\d+)*)/i,p)||d.default.getFirstMatch(/blackberry\d+\/(\d+([_\s]\d+)*)/i,p)||d.default.getFirstMatch(/\bbb(\d+)/i,p);return{name:l.OS_MAP.BlackBerry,version:g}}},{test:[/bada/i],describe:function(p){var g=d.default.getFirstMatch(/bada\/(\d+(\.\d+)*)/i,p);return{name:l.OS_MAP.Bada,version:g}}},{test:[/tizen/i],describe:function(p){var g=d.default.getFirstMatch(/tizen[/\s](\d+(\.\d+)*)/i,p);return{name:l.OS_MAP.Tizen,version:g}}},{test:[/linux/i],describe:function(){return{name:l.OS_MAP.Linux}}},{test:[/CrOS/],describe:function(){return{name:l.OS_MAP.ChromeOS}}},{test:[/PlayStation 4/],describe:function(p){var g=d.default.getFirstMatch(/PlayStation 4[/\s](\d+(\.\d+)*)/i,p);
1return{name:l.OS_MAP.PlayStation4,version:g}}}];s.default=f,r.exports=s.default},94:function(r,s,o){"use strict";s.__esModule=!0,s.default=void 0;var a,d=(a=o(17))&&a.__esModule?a:{default:a},l=o(18),f=[{test:[/googlebot/i],describe:function(){return{type:"bot",vendor:"Google"}}},{test:[/huawei/i],describe:function(p){var g=d.default.getFirstMatch(/(can-l01)/i,p)&&"Nova",b={type:l.PLATFORMS_MAP.mobile,vendor:"Huawei"};return g&&(b.model=g),b}},{test:[/nexus\s*(?:7|8|9|10).*/i],describe:function(){return{type:l.PLATFORMS_MAP.tablet,vendor:"Nexus"}}},{test:[/ipad/i],describe:function(){return{type:l.PLATFORMS_MAP.tablet,vendor:"Apple",model:"iPad"}}},{test:[/Macintosh(.*?) FxiOS(.*?)\//],describe:function(){return{type:l.PLATFORMS_MAP.tablet,vendor:"Apple",model:"iPad"}}},{test:[/kftt build/i],describe:function(){return{type:l.PLATFORMS_MAP.tablet,vendor:"Amazon",model:"Kindle Fire HD 7"}}},{test:[/silk/i],describe:function(){return{type:l.PLATFORMS_MAP.tablet,vendor:"Amazon"}}},{test:[/tablet(?! pc)/i],describe:function(){return{type:l.PLATFORMS_MAP.tablet}}},{test:function(p){var g=p.test(/ipod|iphone/i),b=p.test(/like (ipod|iphone)/i);return g&&!b},describe:function(p){var g=d.default.getFirstMatch(/(ipod|iphone)/i,p);return{type:l.PLATFORMS_MAP.mobile,vendor:"Apple",model:g}}},{test:[/nexus\s*[0-6].*/i,/galaxy nexus/i],describe:function(){return{type:l.PLATFORMS_MAP.mobile,vendor:"Nexus"}}},{test:[/[^-]mobi/i],describe:function(){return{type:l.PLATFORMS_MAP.mobile}}},{test:function(p){return p.getBrowserName(!0)==="blackberry"},describe:function(){return{type:l.PLATFORMS_MAP.mobile,vendor:"BlackBerry"}}},{test:function(p){return p.getBrowserName(!0)==="bada"},describe:function(){return{type:l.PLATFORMS_MAP.mobile}}},{test:function(p){return p.getBrowserName()==="windows phone"},describe:function(){return{type:l.PLATFORMS_MAP.mobile,vendor:"Microsoft"}}},{test:function(p){var g=Number(String(p.getOSVersion()).split(".")[0]);return p.getOSName(!0)==="android"&&g>=3},describe:function(){return{type:l.PLATFORMS_MAP.tablet}}},{test:function(p){return p.getOSName(!0)==="android"},describe:function(){return{type:l.PLATFORMS_MAP.mobile}}},{test:function(p){return p.getOSName(!0)==="macos"},describe:function(){return{type:l.PLATFORMS_MAP.desktop,vendor:"Apple"}}},{test:function(p){return p.getOSName(!0)==="windows"},describe:function(){return{type:l.PLATFORMS_MAP.desktop}}},{test:function(p){return p.getOSName(!0)==="linux"},describe:function(){return{type:l.PLATFORMS_MAP.desktop}}},{test:function(p){return p.getOSName(!0)==="playstation 4"},describe:function(){return{type:l.PLATFORMS_MAP.tv}}},{test:function(p){return p.getOSName(!0)==="roku"},describe:function(){return{type:l.PLATFORMS_MAP.tv}}}];s.default=f,r.exports=s.default},95:function(r,s,o){"use strict";s.__esModule=!0,s.default=void 0;var a,d=(a=o(17))&&a.__esModule?a:{default:a},l=o(18),f=[{test:function(p){return p.getBrowserName(!0)==="microsoft edge"},describe:function(p){if(/\sedg\//i.test(p))return{name:l.ENGINE_MAP.Blink};var g=d.default.getFirstMatch(/edge\/(\d+(\.?_?\d+)+)/i,p);return{name:l.ENGINE_MAP.EdgeHTML,version:g}}},{test:[/trident/i],describe:function(p){var g={name:l.ENGINE_MAP.Trident},b=d.default.getFirstMatch(/trident\/(\d+(\.?_?\d+)+)/i,p);return b&&(g.version=b),g}},{test:function(p){return p.test(/presto/i)},describe:function(p){var g={name:l.ENGINE_MAP.Presto},b=d.default.getFirstMatch(/presto\/(\d+(\.?_?\d+)+)/i,p);return b&&(g.version=b),g}},{test:function(p){var g=p.test(/gecko/i),b=p.test(/like gecko/i);return g&&!b},describe:function(p){var g={name:l.ENGINE_MAP.Gecko},b=d.default.getFirstMatch(/gecko\/(\d+(\.?_?\d+)+)/i,p);return b&&(g.version=b),g}},{test:[/(apple)?webkit\/537\.36/i],describe:function(){return{name:l.ENGINE_MAP.Blink}}},{test:[/(apple)?webkit/i],describe:function(p){var g={name:l.ENGINE_MAP.WebKit},b=d.default.getFirstMatch(/webkit\/(\d+(\.?_?\d+)+)/i,p);return b&&(g.version=b),g}}];s.default=f,r.exports=s.default}})},948:function(n,r,s){"use strict";function o(u,c){if(u==null)return{};var h,m,y=(function(S,C){if(S==null)return{};var E={};for(var O in S)if({}.hasOwnProperty.call(S,O)){if(C.indexOf(O)!==-1)continue;E[O]=S[O]}return E})(u,c);if(Object.getOwnPropertySymbols){var k=Object.getOwnPropertySymbols(u);for(m=0;m<k.length;m++)h=k[m],c.indexOf(h)===-1&&{}.propertyIsEnumerable.call(u,h)&&(y[h]=u[h])}return y}
1function a(u,c){if(!(u instanceof c))throw new TypeError("Cannot call a class as a function")}function d(u){return d=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(c){return typeof c}:function(c){return c&&typeof Symbol=="function"&&c.constructor===Symbol&&c!==Symbol.prototype?"symbol":typeof c},d(u)}function l(u){var c=(function(h){if(d(h)!="object"||!h)return h;var m=h[Symbol.toPrimitive];if(m!==void 0){var y=m.call(h,"string");if(d(y)!="object")return y;throw new TypeError("@@toPrimitive must return a primitive value.")}return String(h)})(u);return d(c)=="symbol"?c:c+""}function f(u,c){for(var h=0;h<c.length;h++){var m=c[h];m.enumerable=m.enumerable||!1,m.configurable=!0,"value"in m&&(m.writable=!0),Object.defineProperty(u,l(m.key),m)}}function p(u,c,h){return c&&f(u.prototype,c),h&&f(u,h),Object.defineProperty(u,"prototype",{writable:!1}),u}function g(u,c){if(c&&(d(c)=="object"||typeof c=="function"))return c;if(c!==void 0)throw new TypeError("Derived constructors may only return object or undefined");return(function(h){if(h===void 0)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return h})(u)}function b(u){return b=Object.setPrototypeOf?Object.getPrototypeOf.bind():function(c){return c.__proto__||Object.getPrototypeOf(c)},b(u)}function R(u,c){return R=Object.setPrototypeOf?Object.setPrototypeOf.bind():function(h,m){return h.__proto__=m,h},R(u,c)}function w(u,c){if(typeof c!="function"&&c!==null)throw new TypeError("Super expression must either be null or a function");u.prototype=Object.create(c&&c.prototype,{constructor:{value:u,writable:!0,configurable:!0}}),Object.defineProperty(u,"prototype",{writable:!1}),c&&R(u,c)}function I(u,c,h){return(c=l(c))in u?Object.defineProperty(u,c,{value:h,enumerable:!0,configurable:!0,writable:!0}):u[c]=h,u}function N(u,c,h,m,y,k,S){try{var C=u[k](S),E=C.value}catch(O){return void h(O)}C.done?c(E):Promise.resolve(E).then(m,y)}function L(u){return function(){var c=this,h=arguments;return new Promise((function(m,y){var k=u.apply(c,h);function S(E){N(k,m,y,S,C,"next",E)}function C(E){N(k,m,y,S,C,"throw",E)}S(void 0)}))}}function j(u,c){(c==null||c>u.length)&&(c=u.length);for(var h=0,m=Array(c);h<c;h++)m[h]=u[h];return m}function M(u,c){return(function(h){if(Array.isArray(h))return h})(u)||(function(h,m){var y=h==null?null:typeof Symbol<"u"&&h[Symbol.iterator]||h["@@iterator"];if(y!=null){var k,S,C,E,O=[],F=!0,V=!1;try{if(C=(y=y.call(h)).next,m===0){if(Object(y)!==y)return;F=!1}else for(;!(F=(k=C.call(y)).done)&&(O.push(k.value),O.length!==m);F=!0);}catch(G){V=!0,S=G}finally{try{if(!F&&y.return!=null&&(E=y.return(),Object(E)!==E))return}finally{if(V)throw S}}return O}})(u,c)||(function(h,m){if(h){if(typeof h=="string")return j(h,m);var y={}.toString.call(h).slice(8,-1);return y==="Object"&&h.constructor&&(y=h.constructor.name),y==="Map"||y==="Set"?Array.from(h):y==="Arguments"||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(y)?j(h,m):void 0}})(u,c)||(function(){throw new TypeError(`Invalid attempt to destructure non-iterable instance. 2In order to be iterable, non-array objects must have a [Symbol.iterator]() method.`)})()}s.r(r),s.d(r,{DAILY_ACCESS_LEVEL_FULL:function(){return _p},DAILY_ACCESS_LEVEL_LOBBY:function(){return JS},DAILY_ACCESS_LEVEL_NONE:function(){return HS},DAILY_ACCESS_UNKNOWN:function(){return oo},DAILY_CAMERA_ERROR_CAM_AND_MIC_IN_USE:function(){return iT},DAILY_CAMERA_ERROR_CAM_IN_USE:function(){return tT},DAILY_CAMERA_ERROR_CONSTRAINTS:function(){return aT},DAILY_CAMERA_ERROR_MIC_IN_USE:function(){return nT},DAILY_CAMERA_ERROR_NOT_FOUND:function(){return oT},DAILY_CAMERA_ERROR_PERMISSIONS:function(){return rT},DAILY_CAMERA_ERROR_UNDEF_MEDIADEVICES:function(){return sT},DAILY_CAMERA_ERROR_UNKNOWN:function(){return cT},DAILY_EVENT_ACCESS_STATE_UPDATED:function(){return Vp},DAILY_EVENT_ACTIVE_SPEAKER_CHANGE:function(){return hf},DAILY_EVENT_ACTIVE_SPEAKER_MODE_CHANGE:function(){return pf},DAILY_EVENT_APP_MSG:function(){return rf},DAILY_EVENT_CAMERA_ERROR:function(){return Lp},DAILY_EVENT_CPU_LOAD_CHANGE:function(){return gf},DAILY_EVENT_ERROR:function(){return Wc},DAILY_EVENT_EXIT_FULLSCREEN:function(){return Jr},DAILY_EVENT_FACE_COUNTS_UPDATED:function(){return vf},DAILY_EVENT_FULLSCREEN:function(){return Gr},DAILY_EVENT_IFRAME_LAUNCH_CONFIG:function(){return Mp},DAILY_EVENT_IFRAME_READY_FOR_LAUNCH_CONFIG:function(){return Ap},DAILY_EVENT_INPUT_SETTINGS_UPDATED:function(){return Vc},DAILY_EVENT_JOINED_MEETING:function(){return Np},DAILY_EVENT_JOINING_MEETING:function(){return xp},DAILY_EVENT_LANG_UPDATED:function(){return Tf},DAILY_EVENT_LEFT_MEETING:function(){return Fp},DAILY_EVENT_LIVE_STREAMING_ERROR:function(){return Sf},DAILY_EVENT_LIVE_STREAMING_STARTED:function(){return yf},DAILY_EVENT_LIVE_STREAMING_STOPPED:function(){return kf},DAILY_EVENT_LIVE_STREAMING_UPDATED:function(){return bf},DAILY_EVENT_LOADED:function(){return jc},DAILY_EVENT_LOADING:function(){return Ip},DAILY_EVENT_LOAD_ATTEMPT_FAILED:function(){return Op},DAILY_EVENT_LOCAL_SCREEN_SHARE_CANCELED:function(){return df},DAILY_EVENT_LOCAL_SCREEN_SHARE_STARTED:function(){return lf},DAILY_EVENT_LOCAL_SCREEN_SHARE_STOPPED:function(){return uf},DAILY_EVENT_MEETING_SESSION_DATA_ERROR:function(){return lT},DAILY_EVENT_MEETING_SESSION_STATE_UPDATED:function(){return Wp},DAILY_EVENT_MEETING_SESSION_SUMMARY_UPDATED:function(){return $p},DAILY_EVENT_NETWORK_CONNECTION:function(){return mf},DAILY_EVENT_NETWORK_QUALITY_CHANGE:function(){return ff},DAILY_EVENT_NONFATAL_ERROR:function(){return $c},DAILY_EVENT_PARTICIPANT_COUNTS_UPDATED:function(){return qp},DAILY_EVENT_PARTICIPANT_JOINED:function(){return Up},DAILY_EVENT_PARTICIPANT_LEFT:function(){return Bp},DAILY_EVENT_PARTICIPANT_UPDATED:function(){return jp},DAILY_EVENT_RECEIVE_SETTINGS_UPDATED:function(){return _f},DAILY_EVENT_RECORDING_DATA:function(){return nf},DAILY_EVENT_RECORDING_ERROR:function(){return ef},DAILY_EVENT_RECORDING_STARTED:function(){return Bc},DAILY_EVENT_RECORDING_STATS:function(){return Zp},DAILY_EVENT_RECORDING_STOPPED:function(){return qc},DAILY_EVENT_RECORDING_UPLOAD_COMPLETED:function(){return tf},DAILY_EVENT_REMOTE_MEDIA_PLAYER_STARTED:function(){return of},DAILY_EVENT_REMOTE_MEDIA_PLAYER_STOPPED:function(){return cf},DAILY_EVENT_REMOTE_MEDIA_PLAYER_UPDATED:function(){return af},DAILY_EVENT_STARTED_CAMERA:function(){return Dp},DAILY_EVENT_THEME_UPDATED:function(){return Rp},DAILY_EVENT_TRACK_STARTED:function(){return Kp},DAILY_EVENT_TRACK_STOPPED:function(){return zp},DAILY_EVENT_TRANSCRIPTION_ERROR:function(){return Xp},DAILY_EVENT_TRANSCRIPTION_MSG:function(){return sf},DAILY_EVENT_TRANSCRIPTION_STARTED:function(){return Yp},DAILY_EVENT_TRANSCRIPTION_STOPPED:function(){return Qp},DAILY_EVENT_WAITING_PARTICIPANT_ADDED:function(){return Gp},DAILY_EVENT_WAITING_PARTICIPANT_REMOVED:function(){return Hp},DAILY_EVENT_WAITING_PARTICIPANT_UPDATED:function(){return Jp},DAILY_FATAL_ERROR_CONNECTION:function(){return Pp},DAILY_FATAL_ERROR_EJECTED:function(){return KS},DAILY_FATAL_ERROR_EOL:function(){return Ep},DAILY_FATAL_ERROR_EXP_ROOM:function(){return QS},DAILY_FATAL_ERROR_EXP_TOKEN:function(){return XS},DAILY_FATAL_ERROR_MEETING_FULL:function(){return ZS},DAILY_FATAL_ERROR_NBF_ROOM:function(){return zS},DAILY_FATAL_ERROR_NBF_TOKEN:function(){return YS},DAILY_FATAL_ERROR_NOT_ALLOWED:function(){return eT},DAILY_FATAL_ERROR_NO_ROOM:function(){return Uc},DAILY_RECEIVE_SETTINGS_ALL_PARTICIPANTS_KEY:function(){return wp},DAILY_RECEIVE_SETTINGS_BASE_KEY:function(){return Cp},DAILY_STATE_ERROR:function(){return Cn},DAILY_STATE_JOINED:function(){return Vn},DAILY_STATE_JOINING:function(){return so},DAILY_STATE_LEFT:function(){return _n},DAILY_STATE_NEW:function(){return Fc},DAILY_TRACK_STATE_BLOCKED:function(){return qS},DAILY_TRACK_STATE_INTERRUPTED:function(){return GS},DAILY_TRACK_STATE_LOADING:function(){return WS},DAILY_TRACK_STATE_OFF:function(){return VS},DAILY_TRACK_STATE_PLAYABLE:function(){return Tp},DAILY_TRACK_STATE_SENDABLE:function(){return $S},default:function(){return RT}});var P=s(7),B=s.n(P),q=Object.prototype.hasOwnProperty;function K(u,c,h){for(h of u.keys())if(ie(h,c))return h}function ie(u,c){var h,m,y;if(u===c)return!0;
2if(u&&c&&(h=u.constructor)===c.constructor){if(h===Date)return u.getTime()===c.getTime();if(h===RegExp)return u.toString()===c.toString();if(h===Array){if((m=u.length)===c.length)for(;m--&&ie(u[m],c[m]););return m===-1}if(h===Set){if(u.size!==c.size)return!1;for(m of u)if((y=m)&&typeof y=="object"&&!(y=K(c,y))||!c.has(y))return!1;return!0}if(h===Map){if(u.size!==c.size)return!1;for(m of u)if((y=m[0])&&typeof y=="object"&&!(y=K(c,y))||!ie(m[1],c.get(y)))return!1;return!0}if(h===ArrayBuffer)u=new Uint8Array(u),c=new Uint8Array(c);else if(h===DataView){if((m=u.byteLength)===c.byteLength)for(;m--&&u.getInt8(m)===c.getInt8(m););return m===-1}if(ArrayBuffer.isView(u)){if((m=u.byteLength)===c.byteLength)for(;m--&&u[m]===c[m];);return m===-1}if(!h||typeof u=="object"){for(h in m=0,u)if(q.call(u,h)&&++m&&!q.call(c,h)||!(h in c)||!ie(u[h],c[h]))return!1;return Object.keys(c).length===m}}return u!=u&&c!=c}var te=s(880),ae=s.n(te);function ge(){return Date.now()+Math.random().toString()}function ke(){throw new Error("Method must be implemented in subclass")}function Oe(u,c){return c!=null&&c.proxyUrl?c.proxyUrl+(c.proxyUrl.slice(-1)==="/"?"":"/")+u.substring(8):u}function Je(u){return u!=null&&u.callObjectBundleUrlOverride?u.callObjectBundleUrlOverride:Oe("https://c.daily.co/call-machine/versioned/".concat("0.87.0","/static/call-machine-object-bundle.js"),u)}function mt(u){try{new URL(u)}catch{return!1}return!0}let Ee=typeof __SENTRY_DEBUG__>"u"||__SENTRY_DEBUG__,je=typeof __SENTRY_DEBUG__>"u"||__SENTRY_DEBUG__,gt="8.55.0",Pe=globalThis;function Un(u,c,h){let m=h||Pe,y=m.__SENTRY__=m.__SENTRY__||{},k=y[gt]=y[gt]||{};return k[u]||(k[u]=c())}let oi=["debug","info","warn","error","log","assert","trace"],jn={};function vn(u){if(!("console"in Pe))return u();let c=Pe.console,h={},m=Object.keys(jn);m.forEach((y=>{let k=jn[y];h[y]=c[y],c[y]=k}));try{return u()}finally{m.forEach((y=>{c[y]=h[y]}))}}let be=Un("logger",(function(){let u=!1,c={enable:()=>{u=!0},disable:()=>{u=!1},isEnabled:()=>u};return je?oi.forEach((h=>{c[h]=(...m)=>{u&&vn((()=>{Pe.console[h](`Sentry Logger [${h}]:`,...m)}))}})):oi.forEach((h=>{c[h]=()=>{}})),c})),Br=[];function Gi(u,c){for(let h of c)h&&h.afterAllSetup&&h.afterAllSetup(u)}function dh(u,c,h){if(h[c.name])Ee&&be.log(`Integration skipped because it was already installed: ${c.name}`);else{if(h[c.name]=c,Br.indexOf(c.name)===-1&&typeof c.setupOnce=="function"&&(c.setupOnce(),Br.push(c.name)),c.setup&&typeof c.setup=="function"&&c.setup(u),typeof c.preprocessEvent=="function"){let m=c.preprocessEvent.bind(c);u.on("preprocessEvent",((y,k)=>m(y,k,u)))}if(typeof c.processEvent=="function"){let m=c.processEvent.bind(c),y=Object.assign(((k,S)=>m(k,S,u)),{id:c.name});u.addEventProcessor(y)}Ee&&be.log(`Integration installed: ${c.name}`)}}let hh=Object.prototype.toString;function ic(u){switch(hh.call(u)){case"[object Error]":case"[object Exception]":case"[object DOMException]":case"[object WebAssembly.Exception]":return!0;default:return ai(u,Error)}}function Ji(u,c){return hh.call(u)===`[object ${c}]`}function ph(u){return Ji(u,"ErrorEvent")}function fh(u){return Ji(u,"DOMError")}function yn(u){return Ji(u,"String")}function rc(u){return typeof u=="object"&&u!==null&&"__sentry_template_string__"in u&&"__sentry_template_values__"in u}function sc(u){return u===null||rc(u)||typeof u!="object"&&typeof u!="function"}function Hi(u){return Ji(u,"Object")}function Vs(u){return typeof Event<"u"&&ai(u,Event)}function $s(u){return!!(u&&u.then&&typeof u.then=="function")}function ai(u,c){try{return u instanceof c}catch{return!1}}function mh(u){return!(typeof u!="object"||u===null||!u.__isVue&&!u._isVue)}let oc=Pe;function gh(u,c={}){if(!u)return"<unknown>";try{let h=u,m=5,y=[],k=0,S=0,C=" > ",E=C.length,O,F=Array.isArray(c)?c:c.keyAttrs,V=!Array.isArray(c)&&c.maxStringLength||80;for(;h&&k++<m&&(O=qk(h,F),!(O==="html"||k>1&&S+y.length*E+O.length>=V));)y.push(O),S+=O.length,h=h.parentNode;return y.reverse().join(C)}catch{return"<unknown>"}}function qk(u,c){let h=u,m=[];if(!h||!h.tagName)return"";if(oc.HTMLElement&&h instanceof HTMLElement&&h.dataset){if(h.dataset.sentryComponent)return h.dataset.sentryComponent;if(h.dataset.sentryElement)return h.dataset.sentryElement}m.push(h.tagName.toLowerCase());let y=c&&c.length?c.filter((S=>h.getAttribute(S))).map((S=>[S,h.getAttribute(S)])):null;if(y&&y.length)y.forEach((S=>{m.push(`[${S[0]}="${S[1]}"]`)}));else{h.id&&m.push(`#${h.id}`);let S=h.className;if(S&&yn(S)){let C=S.split(/\s+/);for(let E of C)m.push(`.${E}`)}}let k=["aria-label","type","name","title","alt"];for(let S of k){let C=h.getAttribute(S);C&&m.push(`[${S}="${C}"]`)}return m.join("")}function Ki(u,c=0){return typeof u!="string"||c===0||u.length<=c?u:`${u.slice(0,c)}...`}
2function vh(u,c){if(!Array.isArray(u))return"";let h=[];for(let m=0;m<u.length;m++){let y=u[m];try{mh(y)?h.push("[VueViewModel]"):h.push(String(y))}catch{h.push("[value cannot be serialized]")}}return h.join(c)}function Ws(u,c=[],h=!1){return c.some((m=>(function(y,k,S=!1){return!!yn(y)&&(Ji(k,"RegExp")?k.test(y):!!yn(k)&&(S?y===k:y.includes(k)))})(u,m,h)))}function Ct(u,c,h){if(!(c in u))return;let m=u[c],y=h(m);typeof y=="function"&&yh(y,m);try{u[c]=y}catch{je&&be.log(`Failed to replace method "${c}" in object`,u)}}function ci(u,c,h){try{Object.defineProperty(u,c,{value:h,writable:!0,configurable:!0})}catch{je&&be.log(`Failed to add non-enumerable property "${c}" to object`,u)}}function yh(u,c){try{let h=c.prototype||{};u.prototype=c.prototype=h,ci(u,"__sentry_original__",c)}catch{}}function ac(u){return u.__sentry_original__}function bh(u){if(ic(u))return{message:u.message,name:u.name,stack:u.stack,...Sh(u)};if(Vs(u)){let c={type:u.type,target:kh(u.target),currentTarget:kh(u.currentTarget),...Sh(u)};return typeof CustomEvent<"u"&&ai(u,CustomEvent)&&(c.detail=u.detail),c}return u}function kh(u){try{return typeof Element<"u"&&ai(u,Element)?gh(u):Object.prototype.toString.call(u)}catch{return"<unknown>"}}function Sh(u){if(typeof u=="object"&&u!==null){let c={};for(let h in u)Object.prototype.hasOwnProperty.call(u,h)&&(c[h]=u[h]);return c}return{}}function Rt(u){return cc(u,new Map)}function cc(u,c){if((function(h){if(!Hi(h))return!1;try{let m=Object.getPrototypeOf(h).constructor.name;return!m||m==="Object"}catch{return!0}})(u)){let h=c.get(u);if(h!==void 0)return h;let m={};c.set(u,m);for(let y of Object.getOwnPropertyNames(u))u[y]!==void 0&&(m[y]=cc(u[y],c));return m}if(Array.isArray(u)){let h=c.get(u);if(h!==void 0)return h;let m=[];return c.set(u,m),u.forEach((y=>{m.push(cc(y,c))})),m}return u}function It(){let u=Pe,c=u.crypto||u.msCrypto,h=()=>16*Math.random();try{if(c&&c.randomUUID)return c.randomUUID().replace(/-/g,"");c&&c.getRandomValues&&(h=()=>{let m=new Uint8Array(1);return c.getRandomValues(m),m[0]})}catch{}return("10000000100040008000"+1e11).replace(/[018]/g,(m=>(m^(15&h())>>m/4).toString(16)))}function Th(u){return u.exception&&u.exception.values?u.exception.values[0]:void 0}function Bn(u){let{message:c,event_id:h}=u;if(c)return c;let m=Th(u);return m?m.type&&m.value?`${m.type}: ${m.value}`:m.type||m.value||h||"<unknown>":h||"<unknown>"}function lc(u,c,h){let m=u.exception=u.exception||{},y=m.values=m.values||[],k=y[0]=y[0]||{};k.value||(k.value=c||""),k.type||(k.type=h||"Error")}function zi(u,c){let h=Th(u);if(!h)return;let m=h.mechanism;if(h.mechanism={type:"generic",handled:!0,...m,...c},c&&"data"in c){let y={...m&&m.data,...c.data};h.mechanism.data=y}}function _h(u){if((function(c){try{return c.__sentry_captured__}catch{}})(u))return!0;try{ci(u,"__sentry_captured__",!0)}catch{}return!1}let Vk=[/^Script error\.?$/,/^Javascript error: Script error\.? on line 0$/,/^ResizeObserver loop completed with undelivered notifications.$/,/^Cannot redefine property: googletag$/,"undefined is not an object (evaluating 'a.L')",`can't redefine non-configurable property "solana"`,"vv().getRestrictions is not a function. (In 'vv().getRestrictions(1,a)', 'vv().getRestrictions' is undefined)","Can't find variable: _AutofillCallbackHandler",/^Non-Error promise rejection captured with value: Object Not Found Matching Id:\d+, MethodName:simulateEvent, ParamCount:\d+$/],$k=(u={})=>({name:"InboundFilters",processEvent(c,h,m){let y=m.getOptions(),k=(function(S={},C={}){return{allowUrls:[...S.allowUrls||[],...C.allowUrls||[]],denyUrls:[...S.denyUrls||[],...C.denyUrls||[]],ignoreErrors:[...S.ignoreErrors||[],...C.ignoreErrors||[],...S.disableErrorDefaults?[]:Vk],ignoreTransactions:[...S.ignoreTransactions||[],...C.ignoreTransactions||[]],ignoreInternal:S.ignoreInternal===void 0||S.ignoreInternal}})(u,y);return(function(S,C){return C.ignoreInternal&&(function(E){try{return E.exception.values[0].type==="SentryError"}catch{}return!1})(S)?(Ee&&be.warn(`Event dropped due to being internal Sentry Error. 3Event: ${Bn(S)}`),!0):(function(E,O){return!(E.type||!O||!O.length)&&(function(F){let V=[],G;F.message&&V.push(F.message);try{G=F.exception.values[F.exception.values.length-1]}catch{}return G&&G.value&&(V.push(G.value),G.type&&V.push(`${G.type}: ${G.value}`)),V})(E).some((F=>Ws(F,O)))})(S,C.ignoreErrors)?(Ee&&be.warn(`Event dropped due to being matched by \`ignoreErrors\` option. 4Event: ${Bn(S)}`),!0):(function(E){return!E.type&&!(!E.exception||!E.exception.values||E.exception.values.length===0)&&!E.message&&!E.exception.values.some((O=>O.stacktrace||O.type&&O.type!=="Error"||O.value))})(S)?(Ee&&be.warn(`Event dropped due to not having an error message, error type or stacktrace. 5Event: ${Bn(S)}`),!0):(function(E,O){if(E.type!=="transaction"||!O||!O.length)return!1;let F=E.transaction;return!!F&&Ws(F,O)})(S,C.ignoreTransactions)?(Ee&&be.warn(`Event dropped due to being matched by \`ignoreTransactions\` option. 6Event: ${Bn(S)}`),!0):(function(E,O){if(!O||!O.length)return!1;let F=Gs(E);return!!F&&Ws(F,O)})(S,C.denyUrls)?(Ee&&be.warn(`Event dropped due to being matched by \`denyUrls\` option. 7Event: ${Bn(S)}. 8Url: ${Gs(S)}`),!0):!(function(E,O){if(!O||!O.length)return!0;let F=Gs(E);return!F||Ws(F,O)})(S,C.allowUrls)&&(Ee&&be.warn(`Event dropped due to not being matched by \`allowUrls\` option. 9Event: ${Bn(S)}. 10Url: ${Gs(S)}`),!0)})(c,k)?null:c}});function Gs(u){try{let c;try{c=u.exception.values[0].stacktrace.frames}catch{}return c?(function(h=[]){for(let m=h.length-1;m>=0;m--){let y=h[m];if(y&&y.filename!=="<anonymous>"&&y.filename!=="[native code]")return y.filename||null}return null})(c):null}catch{return Ee&&be.error(`Cannot extract url for event ${Bn(u)}`),null}}function Js(){return uc(Pe),Pe}function uc(u){let c=u.__SENTRY__=u.__SENTRY__||{};return c.version=c.version||gt,c[gt]=c[gt]||{}}function qr(){return Date.now()/1e3}let bn=(function(){let{performance:u}=Pe;if(!u||!u.now)return qr;let c=Date.now()-u.now(),h=u.timeOrigin==null?c:u.timeOrigin;return()=>(h+u.now())/1e3})(),Hs;function Yi(u,c={}){if(c.user&&(!u.ipAddress&&c.user.ip_address&&(u.ipAddress=c.user.ip_address),u.did||c.did||(u.did=c.user.id||c.user.email||c.user.username)),u.timestamp=c.timestamp||bn(),c.abnormal_mechanism&&(u.abnormal_mechanism=c.abnormal_mechanism),c.ignoreDuration&&(u.ignoreDuration=c.ignoreDuration),c.sid&&(u.sid=c.sid.length===32?c.sid:It()),c.init!==void 0&&(u.init=c.init),!u.did&&c.did&&(u.did=`${c.did}`),typeof c.started=="number"&&(u.started=c.started),u.ignoreDuration)u.duration=void 0;else if(typeof c.duration=="number")u.duration=c.duration;else{let h=u.timestamp-u.started;u.duration=h>=0?h:0}c.release&&(u.release=c.release),c.environment&&(u.environment=c.environment),!u.ipAddress&&c.ipAddress&&(u.ipAddress=c.ipAddress),!u.userAgent&&c.userAgent&&(u.userAgent=c.userAgent),t
10ypeof c.errors=="number"&&(u.errors=c.errors),c.status&&(u.status=c.status)}function Ch(){return It()}function dc(){return It().substring(16)}function Ks(u,c,h=2){if(!c||typeof c!="object"||h<=0)return c;if(u&&c&&Object.keys(c).length===0)return u;let m={...u};for(let y in c)Object.prototype.hasOwnProperty.call(c,y)&&(m[y]=Ks(m[y],c[y],h-1));return m}(()=>{let{performance:u}=Pe;if(!u||!u.now)return void(Hs="none");let c=36e5,h=u.now(),m=Date.now(),y=u.timeOrigin?Math.abs(u.timeOrigin+h-m):c,k=y<c,S=u.timing&&u.timing.navigationStart,C=typeof S=="number"?Math.abs(S+h-m):c;k||C<c?y<=C?(Hs="timeOrigin",u.timeOrigin):Hs="navigationStart":Hs="dateNow"})();let hc="_sentrySpan";function wh(u,c){c?ci(u,hc,c):delete u[hc]}function Eh(u){return u[hc]}class pc{constructor(){this._notifyingListeners=!1,this._scopeListeners=[],this._eventProcessors=[],this._breadcrumbs=[],this._attachments=[],this._user={},this._tags={},this._extra={},this._contexts={},this._sdkProcessingMetadata={},this._propagationContext={traceId:Ch(),spanId:dc()}}clone(){let c=new pc;return c._breadcrumbs=[...this._breadcrumbs],c._tags={...this._tags},c._extra={...this._extra},c._contexts={...this._contexts},this._contexts.flags&&(c._contexts.flags={values:[...this._contexts.flags.values]}),c._user=this._user,c._level=this._level,c._session=this._session,c._transactionName=this._transactionName,c._fingerprint=this._fingerprint,c._eventProcessors=[...this._eventProcessors],c._requestSession=this._requestSession,c._attachments=[...this._attachments],c._sdkProcessingMetadata={...this._sdkProcessingMetadata},c._propagationContext={...this._propagationContext},c._client=this._client,c._lastEventId=this._lastEventId,wh(c,Eh(this)),c}setClient(c){this._client=c}setLastEventId(c){this._lastEventId=c}getClient(){return this._client}lastEventId(){return this._lastEventId}addScopeListener(c){this._scopeListeners.push(c)}addEventProcessor(c){return this._eventProcessors.push(c),this}setUser(c){return this._user=c||{email:void 0,id:void 0,ip_address:void 0,username:void 0},this._session&&Yi(this._session,{user:c}),this._notifyScopeListeners(),this}getUser(){return this._user}getRequestSession(){return this._requestSession}setRequestSession(c){return this._requestSession=c,this}setTags(c){return this._tags={...this._tags,...c},this._notifyScopeListeners(),this}setTag(c,h){return this._tags={...this._tags,[c]:h},this._notifyScopeListeners(),this}setExtras(c){return this._extra={...this._extra,...c},this._notifyScopeListeners(),this}setExtra(c,h){return this._extra={...this._extra,[c]:h},this._notifyScopeListeners(),this}setFingerprint(c){return this._fingerprint=c,this._notifyScopeListeners(),this}setLevel(c){return this._level=c,this._notifyScopeListeners(),this}setTransactionName(c){return this._transactionName=c,this._notifyScopeListeners(),this}setContext(c,h){return h===null?delete this._contexts[c]:this._contexts[c]=h,this._notifyScopeListeners(),this}setSession(c){return c?this._session=c:delete this._session,this._notifyScopeListeners(),this}getSession(){return this._session}update(c){if(!c)return this;let h=typeof c=="function"?c(this):c,[m,y]=h instanceof kn?[h.getScopeData(),h.getRequestSession()]:Hi(h)?[c,c.requestSession]:[],{tags:k,extra:S,user:C,contexts:E,level:O,fingerprint:F=[],propagationContext:V}=m||{};return this._tags={...this._tags,...k},this._extra={...this._extra,...S},this._contexts={...this._contexts,...E},C&&Object.keys(C).length&&(this._user=C),O&&(this._level=O),F.length&&(this._fingerprint=F),V&&(this._propagationContext=V),y&&(this._requestSession=y),this}clear(){return this._breadcrumbs=[],this._tags={},this._extra={},this._user={},this._contexts={},this._level=void 0,this._transactionName=void 0,this._fingerprint=void 0,this._requestSession=void 0,this._session=void 0,wh(this,void 0),this._attachments=[],this.setPropagationContext({traceId:Ch()}),this._notifyScopeListeners(),this}addBreadcrumb(c,h){let m=typeof h=="number"?h:100;if(m<=0)return this;let y={timestamp:qr(),...c};return this._breadcrumbs.push(y),this._breadcrumbs.length>m&&(this._breadcrumbs=this._breadcrumbs.slice(-m),this._client&&this._client.re
10cordDroppedEvent("buffer_overflow","log_item")),this._notifyScopeListeners(),this}getLastBreadcrumb(){return this._breadcrumbs[this._breadcrumbs.length-1]}clearBreadcrumbs(){return this._breadcrumbs=[],this._notifyScopeListeners(),this}addAttachment(c){return this._attachments.push(c),this}clearAttachments(){return this._attachments=[],this}getScopeData(){return{breadcrumbs:this._breadcrumbs,attachments:this._attachments,contexts:this._contexts,tags:this._tags,extra:this._extra,user:this._user,level:this._level,fingerprint:this._fingerprint||[],eventProcessors:this._eventProcessors,propagationContext:this._propagationContext,sdkProcessingMetadata:this._sdkProcessingMetadata,transactionName:this._transactionName,span:Eh(this)}}setSDKProcessingMetadata(c){return this._sdkProcessingMetadata=Ks(this._sdkProcessingMetadata,c,2),this}setPropagationContext(c){return this._propagationContext={spanId:dc(),...c},this}getPropagationContext(){return this._propagationContext}captureException(c,h){let m=h&&h.event_id?h.event_id:It();if(!this._client)return be.warn("No client configured on scope - will not capture exception!"),m;let y=new Error("Sentry syntheticException");return this._client.captureException(c,{originalException:c,syntheticException:y,...h,event_id:m},this),m}captureMessage(c,h,m){let y=m&&m.event_id?m.event_id:It();if(!this._client)return be.warn("No client configured on scope - will not capture message!"),y;let k=new Error(c);return this._client.captureMessage(c,h,{originalException:c,syntheticException:k,...m,event_id:y},this),y}captureEvent(c,h){let m=h&&h.event_id?h.event_id:It();return this._client?(this._client.captureEvent(c,{...h,event_id:m},this),m):(be.warn("No client configured on scope - will not capture event!"),m)}_notifyScopeListeners(){this._notifyingListeners||(this._notifyingListeners=!0,this._scopeListeners.forEach((c=>{c(this)})),this._notifyingListeners=!1)}}let kn=pc;class Wk{constructor(c,h){let m,y;m=c||new kn,y=h||new kn,this._stack=[{scope:m}],this._isolationScope=y}withScope(c){let h=this._pushScope(),m;try{m=c(h)}catch(y){throw this._popScope(),y}return $s(m)?m.then((y=>(this._popScope(),y)),(y=>{throw this._popScope(),y})):(this._popScope(),m)}getClient(){return this.getStackTop().client}getScope(){return this.getStackTop().scope}getIsolationScope(){return this._isolationScope}getStackTop(){return this._stack[this._stack.length-1]}_pushScope(){let c=this.getScope().clone();return this._stack.push({client:this.getClient(),scope:c}),c}_popScope(){return!(this._stack.length<=1||!this._stack.pop())}}function Qi(){let u=uc(Js());return u.stack=u.stack||new Wk(Un("defaultCurrentScope",(()=>new kn)),Un("defaultIsolationScope",(()=>new kn)))}function Gk(u){return Qi().withScope(u)}function Jk(u,c){let h=Qi();return h.withScope((()=>(h.getStackTop().scope=u,c(u))))}function Ph(u){return Qi().withScope((()=>u(Qi().getIsolationScope())))}function fc(u){let c=uc(u);return c.acs?c.acs:{withIsolationScope:Ph,withScope:Gk,withSetScope:Jk,withSetIsolationScope:(h,m)=>Ph(m),getCurrentScope:()=>Qi().getScope(),getIsolationScope:()=>Qi().getIsolationScope()}}function li(){return fc(Js()).getCurrentScope()}function Vr(){return fc(Js()).getIsolationScope()}function ht(){return li().getClient()}function Hk(u){let c=u.getPropagationContext(),{traceId:h,spanId:m,parentSpanId:y}=c;return Rt({trace_id:h,span_id:m,parent_span_id:y})}let Ah,Mh=new WeakMap,Kk=()=>({name:"FunctionToString",setupOnce(){Ah=Function.prototype.toString;try{Function.prototype.toString=function(...u){let c=ac(this),h=Mh.has(ht())&&c!==void 0?c:this;return Ah.apply(h,u)}}catch{}},setup(u){Mh.set(u,!0)}}),ui="?",Rh=/\(error: (.*)\)/,Ih=/captureMessage|captureException/;function zs(u){return u[u.length-1]||{}}let Oh="<anonymous>";function qn(u){try{return u&&typeof u=="function"&&u.name||Oh}catch{return Oh}}function Dh(u){let c=u.exception;if(c){let h=[];try{return c.values.forEach((m=>{m.stacktrace.frames&&h.push(...m.stacktrace.frames)})),h}catch{return}}}let zk=()=>{let u;return{name:"Dedupe",processEvent(c){if(c.type)return c;try{if((function(h,m){return!!m&&(!!(function(y,k){let S=y.message,C=k.message;return!(!S&&!C)&&!(S&&!C||!S&&C)&&S===C&&!!xh(y,k)&&!!Lh(y,k)})(h,m)||!!(function(y,k){let S=Nh(k),C=Nh(y);return!(!S||!C)&&S.type===C.type&&S.value===C.value&&!!xh(y,k)&&!!Lh(y,k)})(h,m))})(c,u))return Ee&&be.warn("Event dropped due to being a duplicate of previously captured event."),null}catch{}return u=c}}};function Lh(u,c){let h=Dh(u),m=Dh(c);if(!h&&!m)return!0;
10if(h&&!m||!h&&m||m.length!==h.length)return!1;for(let y=0;y<m.length;y++){let k=m[y],S=h[y];if(k.filename!==S.filename||k.lineno!==S.lineno||k.colno!==S.colno||k.function!==S.function)return!1}return!0}function xh(u,c){let h=u.fingerprint,m=c.fingerprint;if(!h&&!m)return!0;if(h&&!m||!h&&m)return!1;try{return h.join("")===m.join("")}catch{return!1}}function Nh(u){return u.exception&&u.exception.values&&u.exception.values[0]}let Ys={},Fh={};function di(u,c){Ys[u]=Ys[u]||[],Ys[u].push(c)}function hi(u,c){if(!Fh[u]){Fh[u]=!0;try{c()}catch(h){je&&be.error(`Error while instrumenting ${u}`,h)}}}function jt(u,c){let h=u&&Ys[u];if(h)for(let m of h)try{m(c)}catch(y){je&&be.error(`Error while triggering instrumentation handler. 11Type: ${u} 12Name: ${qn(m)} 13Error:`,y)}}let vt=Pe,Uh,mc,gc;function Yk(){if(!vt.document)return;let u=jt.bind(null,"dom"),c=jh(u,!0);vt.document.addEventListener("click",c,!1),vt.document.addEventListener("keypress",c,!1),["EventTarget","Node"].forEach((h=>{let m=vt[h],y=m&&m.prototype;y&&y.hasOwnProperty&&y.hasOwnProperty("addEventListener")&&(Ct(y,"addEventListener",(function(k){return function(S,C,E){if(S==="click"||S=="keypress")try{let O=this.__sentry_instrumentation_handlers__=this.__sentry_instrumentation_handlers__||{},F=O[S]=O[S]||{refCount:0};if(!F.handler){let V=jh(u);F.handler=V,k.call(this,S,V,E)}F.refCount++}catch{}return k.call(this,S,C,E)}})),Ct(y,"removeEventListener",(function(k){return function(S,C,E){if(S==="click"||S=="keypress")try{let O=this.__sentry_instrumentation_handlers__||{},F=O[S];F&&(F.refCount--,F.refCount<=0&&(k.call(this,S,F.handler,E),F.handler=void 0,delete O[S]),Object.keys(O).length===0&&delete this.__sentry_instrumentation_handlers__)}catch{}return k.call(this,S,C,E)}})))}))}function jh(u,c=!1){return h=>{if(!h||h._sentryCaptured)return;let m=(function(k){try{return k.target}catch{return null}})(h);if((function(k,S){return k==="keypress"&&(!S||!S.tagName||S.tagName!=="INPUT"&&S.tagName!=="TEXTAREA"&&!S.isContentEditable)})(h.type,m))return;ci(h,"_sentryCaptured",!0),m&&!m._sentryId&&ci(m,"_sentryId",It());let y=h.type==="keypress"?"input":h.type;(function(k){if(k.type!==mc)return!1;try{if(!k.target||k.target._sentryId!==gc)return!1}catch{}return!0})(h)||(u({event:h,name:y,global:c}),mc=h.type,gc=m?m._sentryId:void 0),clearTimeout(Uh),Uh=vt.setTimeout((()=>{gc=void 0,mc=void 0}),1e3)}}let $r="__sentry_xhr_v3__";function Qk(){if(!vt.XMLHttpRequest)return;let u=XMLHttpRequest.prototype;u.open=new Proxy(u.open,{apply(c,h,m){let y=new Error,k=1e3*bn(),S=yn(m[0])?m[0].toUpperCase():void 0,C=(function(O){if(yn(O))return O;try{return O.toString()}catch{}})(m[1]);if(!S||!C)return c.apply(h,m);h[$r]={method:S,url:C,request_headers:{}},S==="POST"&&C.match(/sentry_key/)&&(h.__sentry_own_request__=!0);let E=()=>{let O=h[$r];if(O&&h.readyState===4){try{O.status_code=h.status}catch{}jt("xhr",{endTimestamp:1e3*bn(),startTimestamp:k,xhr:h,virtualError:y})}};return"onreadystatechange"in h&&typeof h.onreadystatechange=="function"?h.onreadystatechange=new Proxy(h.onreadystatechange,{apply(O,F,V){return E(),O.apply(F,V)}}):h.addEventListener("readystatechange",E),h.setRequestHeader=new Proxy(h.setRequestHeader,{apply(O,F,V){let[G,Q]=V,W=F[$r];
13return W&&yn(G)&&yn(Q)&&(W.request_headers[G.toLowerCase()]=Q),O.apply(F,V)}}),c.apply(h,m)}}),u.send=new Proxy(u.send,{apply(c,h,m){let y=h[$r];return y&&(m[0]!==void 0&&(y.body=m[0]),jt("xhr",{startTimestamp:1e3*bn(),xhr:h})),c.apply(h,m)}})}let Qs=Pe,Xs;function Bh(u){let c="history";di(c,u),hi(c,Xk)}function Xk(){if(!(function(){let h=Qs.chrome,m=h&&h.app&&h.app.runtime,y="history"in Qs&&!!Qs.history.pushState&&!!Qs.history.replaceState;return!m&&y})())return;let u=vt.onpopstate;function c(h){return function(...m){let y=m.length>2?m[2]:void 0;if(y){let k=Xs,S=String(y);Xs=S,jt("history",{from:k,to:S})}return h.apply(this,m)}}vt.onpopstate=function(...h){let m=vt.location.href,y=Xs;if(Xs=m,jt("history",{from:y,to:m}),u)try{return u.apply(this,h)}catch{}},Ct(vt.history,"pushState",c),Ct(vt.history,"replaceState",c)}function Zk(){"console"in Pe&&oi.forEach((function(u){u in Pe.console&&Ct(Pe.console,u,(function(c){return jn[u]=c,function(...h){jt("console",{args:h,level:u});let m=jn[u];m&&m.apply(Pe.console,h)}}))}))}let vc=Pe;function yc(u){return u&&/^function\s+\w+\(\)\s+\{\s+\[native code\]\s+\}$/.test(u.toString())}function eS(u,c=!1){c&&!(function(){if(typeof EdgeRuntime=="string")return!0;if(!(function(){if(!("fetch"in vc))return!1;try{return new Headers,new Request("http://www.example.com"),new Response,!0}catch{return!1}})())return!1;if(yc(vc.fetch))return!0;let h=!1,m=vc.document;if(m&&typeof m.createElement=="function")try{let y=m.createElement("iframe");y.hidden=!0,m.head.appendChild(y),y.contentWindow&&y.contentWindow.fetch&&(h=yc(y.contentWindow.fetch)),m.head.removeChild(y)}catch(y){je&&be.warn("Could not create sandbox iframe for pure fetch check, bailing to window.fetch: ",y)}return h})()||Ct(Pe,"fetch",(function(h){return function(...m){let y=new Error,{method:k,url:S}=(function(E){if(E.length===0)return{method:"GET",url:""};if(E.length===2){let[F,V]=E;return{url:qh(F),method:bc(V,"method")?String(V.method).toUpperCase():"GET"}}let O=E[0];return{url:qh(O),method:bc(O,"method")?String(O.method).toUpperCase():"GET"}})(m),C={args:m,fetchData:{method:k,url:S},startTimestamp:1e3*bn(),virtualError:y};return u||jt("fetch",{...C}),h.apply(Pe,m).then((async E=>(u?u(E):jt("fetch",{...C,endTimestamp:1e3*bn(),response:E}),E)),(E=>{throw jt("fetch",{...C,endTimestamp:1e3*bn(),error:E}),ic(E)&&E.stack===void 0&&(E.stack=y.stack,ci(E,"framesToPop",1)),E}))}}))}function bc(u,c){return!!u&&typeof u=="object"&&!!u[c]}function qh(u){return typeof u=="string"?u:u?bc(u,"url")?u.url:u.toString?u.toString():"":""}let tS=100;function pi(u,c){let h=ht(),m=Vr();if(!h)return;let{beforeBreadcrumb:y=null,maxBreadcrumbs:k=tS}=h.getOptions();if(k<=0)return;let S={timestamp:qr(),...u},C=y?vn((()=>y(S,c))):S;C!==null&&(h.emit&&h.emit("beforeAddBreadcrumb",C,c),m.addBreadcrumb(C,k))}function Vh(u){return u===void 0?void 0:u>=400&&u<500?"warning":u>=500?"error":void 0}function kc(u){if(!u)return{};let c=u.match(/^(([^:/?#]+):)?(\/\/([^/?#]*))?([^?#]*)(\?([^#]*))?(#(.*))?$/);if(!c)return{};let h=c[6]||"",m=c[8]||"";return{host:c[4],path:c[5],protocol:c[2],search:h,hash:m,relative:c[5]+h+m}}let Zs=typeof __SENTRY_DEBUG__>"u"||__SENTRY_DEBUG__,Sc="production";var Sn;function fi(u){return new Ot((c=>{c(u)}))}function eo(u){return new Ot(((c,h)=>{h(u)}))}(function(u){u[u.PENDING=0]="PENDING",u[u.RESOLVED=1]="RESOLVED",u[u.REJECTED=2]="REJECTED"})(Sn||(Sn={}));class Ot{constructor(c){Ot.prototype.__init.call(this),Ot.prototype.__init2.call(this),Ot.prototype.__init3.call(this),Ot.prototype.__init4.call(this),this._state=Sn.PENDING,this._handlers=[];try{c(this._resolve,this._reject)}catch(h){this._reject(h)}}then(c,h){return new Ot(((m,y)=>{this._handlers.push([!1,k=>{if(c)try{m(c(k))}catch(S){y(S)}else m(k)},k=>{if(h)try{m(h(k))}catch(S){y(S)}else y(k)}]),this._executeHandlers()}))}catch(c){return this.then((h=>h),c)}finally(c){return new Ot(((h,m)=>{let y,k;return this.then((S=>{k=!1,y=S,c&&c()}),(S=>{k=!0,y=S,c&&c()})).then((()=>{k?m(y):h(y)}))}))}__init(){this._resolve=c=>{this._setResult(Sn.RESOLVED,c)}}__init2(){this._reject=c=>{this._setResult(Sn.REJECTED,c)}}__init3(){this._setResult=(c,h)=>{this._state===Sn.PENDING&&($s(h)?h.then(this._resolve,this._reject):(this._state=c,this._value=h,this._executeHandlers()))}}__init4(){this._executeHandlers=()=>
13{if(this._state===Sn.PENDING)return;let c=this._handlers.slice();this._handlers=[],c.forEach((h=>{h[0]||(this._state===Sn.RESOLVED&&h[1](this._value),this._state===Sn.REJECTED&&h[2](this._value),h[0]=!0)}))}}}function Tc(u,c,h,m=0){return new Ot(((y,k)=>{let S=u[m];if(c===null||typeof S!="function")y(c);else{let C=S({...c},h);Ee&&S.id&&C===null&&be.log(`Event processor "${S.id}" dropped event`),$s(C)?C.then((E=>Tc(u,E,h,m+1).then(y))).then(null,k):Tc(u,C,h,m+1).then(y).then(null,k)}}))}let to,$h,_c;function Tn(u,c=100,h=1/0){try{return Cc("",u,c,h)}catch(m){return{ERROR:`**non-serializable** (${m})`}}}function Wh(u,c=3,h=102400){let m=Tn(u,c);return y=m,(function(k){return~-encodeURI(k).split(/%..|./).length})(JSON.stringify(y))>h?Wh(u,c-1,h):m;var y}function Cc(u,c,h=1/0,m=1/0,y=(function(){let k=typeof WeakSet=="function",S=k?new WeakSet:[];return[function(C){if(k)return!!S.has(C)||(S.add(C),!1);for(let E=0;E<S.length;E++)if(S[E]===C)return!0;return S.push(C),!1},function(C){if(k)S.delete(C);else for(let E=0;E<S.length;E++)if(S[E]===C){S.splice(E,1);break}}]})()){let[k,S]=y;if(c==null||["boolean","string"].includes(typeof c)||typeof c=="number"&&Number.isFinite(c))return c;let C=(function(Q,W){try{if(Q==="domain"&&W&&typeof W=="object"&&W._events)return"[Domain]";if(Q==="domainEmitter")return"[DomainEmitter]";if(typeof window<"u"&&W===window)return"[Global]";if(typeof window<"u"&&W===window)return"[Window]";if(typeof document<"u"&&W===document)return"[Document]";if(mh(W))return"[VueViewModel]";if(Hi(z=W)&&"nativeEvent"in z&&"preventDefault"in z&&"stopPropagation"in z)return"[SyntheticEvent]";if(typeof W=="number"&&!Number.isFinite(W))return`[${W}]`;if(typeof W=="function")return`[Function: ${qn(W)}]`;if(typeof W=="symbol")return`[${String(W)}]`;if(typeof W=="bigint")return`[BigInt: ${String(W)}]`;let ne=(function(oe){let ue=Object.getPrototypeOf(oe);return ue?ue.constructor.name:"null prototype"})(W);return/^HTML(\w*)Element$/.test(ne)?`[HTMLElement: ${ne}]`:`[object ${ne}]`}catch(ne){return`**non-serializable** (${ne})`}var z})(u,c);if(!C.startsWith("[object "))return C;if(c.__sentry_skip_normalization__)return c;let E=typeof c.__sentry_override_normalization_depth__=="number"?c.__sentry_override_normalization_depth__:h;if(E===0)return C.replace("object ","");if(k(c))return"[Circular ~]";let O=c;if(O&&typeof O.toJSON=="function")try{return Cc("",O.toJSON(),E-1,m,y)}catch{}let F=Array.isArray(c)?[]:{},V=0,G=bh(c);for(let Q in G){if(!Object.prototype.hasOwnProperty.call(G,Q))continue;if(V>=m){F[Q]="[MaxProperties ~]";break}let W=G[Q];F[Q]=Cc(Q,W,E-1,m,y),V++}return S(c),F}let nS=/^sentry-/;function Gh(u){return u.split(",").map((c=>c.split("=").map((h=>decodeURIComponent(h.trim()))))).reduce(((c,[h,m])=>(h&&m&&(c[h]=m),c)),{})}function iS(u){let c=u._sentryMetrics;if(!c)return;let h={};for(let[,[m,y]]of c)(h[m]||(h[m]=[])).push(Rt(y));return h}let Jh=!1;function rS(u){let{spanId:c,traceId:h,isRemote:m}=u.spanContext();return Rt({parent_span_id:m?c:wc(u).parent_span_id,span_id:m?dc():c,trace_id:h})}function Hh(u){return typeof u=="number"?Kh(u):Array.isArray(u)?u[0]+u[1]/1e9:u instanceof Date?Kh(u.getTime()):bn()}function Kh(u){return u>9999999999?u/1e3:u}function wc(u){if((function(c){return typeof c.getSpanJSON=="function"})(u))return u.getSpanJSON();try{let{spanId:c,traceId:h}=u.spanContext();if((function(m){let y=m;return!!(y.attributes&&y.startTime&&y.name&&y.endTime&&y.status)})(u)){let{attributes:m,startTime:y,name:k,endTime:S,parentSpanId:C,status:E}=u;return Rt({span_id:c,trace_id:h,data:m,description:k,parent_span_id:C,start_timestamp:Hh(y),timestamp:Hh(S)||void 0,status:sS(E),op:m["sentry.op"],origin:m["sentry.origin"],_metrics_summary:iS(u)})}return{span_id:c,trace_id:h}}catch{return{}}}function sS(u){if(u&&u.code!==0)return u.code===1?"ok":u.message||"unknown_error"}function zh(u){return u._sentryRootSpan||u}function Yh(u,c){let h=c.getOptions(),{publicKey:m}=c.getDsn()||{},y=Rt({environment:h.environment||Sc,release:h.release,public_key:m,trace_id:u});return c.emit("createDsc",y),y}function oS(u){let c=ht();if(!c)return{};let h=zh(u),m=h._frozenDsc;if(m)return m;let y=h.spanContext().traceState,k=y&&y.get("sentry.dsc"),S=k&&(function(Q){let W=(function(ne){if(ne&&(yn(ne)||Array.isArray(ne)))return Array.isArray(ne)?ne.reduce(((oe,ue)=>{let me=Gh(ue);return Object.entries(me).forEach((([he,we])=>{oe[he]=we})),oe}),{}):Gh(ne)})(Q);if(!W)return;let z=Object.entries(W).reduce(((ne,[oe,ue])=>(oe.match(nS)&&(ne[oe.slice(7)]=ue),ne)),{});return Object.keys(z).length>0?z:void 0})(k);if(S)return S;let C=Yh(u.spanContext().traceId,c),E=wc(h),O=E.data||{},F=O["sentry.sample_rate"];F!=null&&(C.sample_rate=`${F}`);let V=O["sentry.source"],G=E.description;return V!=="url"&&G&&(C.transaction=G),(function(){if(typeof __SENTRY_TRACING__=="boolean"&&!__SENTRY_TRACING__)return!1;
13let Q=ht(),W=Q&&Q.getOptions();return!!W&&(W.enableTracing||"tracesSampleRate"in W||"tracesSampler"in W)})()&&(C.sampled=String((function(Q){let{traceFlags:W}=Q.spanContext();return W===1})(h))),c.emit("createDsc",C,h),C}function Qh(u,c){let{extra:h,tags:m,user:y,contexts:k,level:S,sdkProcessingMetadata:C,breadcrumbs:E,fingerprint:O,eventProcessors:F,attachments:V,propagationContext:G,transactionName:Q,span:W}=c;no(u,"extra",h),no(u,"tags",m),no(u,"user",y),no(u,"contexts",k),u.sdkProcessingMetadata=Ks(u.sdkProcessingMetadata,C,2),S&&(u.level=S),Q&&(u.transactionName=Q),W&&(u.span=W),E.length&&(u.breadcrumbs=[...u.breadcrumbs,...E]),O.length&&(u.fingerprint=[...u.fingerprint,...O]),F.length&&(u.eventProcessors=[...u.eventProcessors,...F]),V.length&&(u.attachments=[...u.attachments,...V]),u.propagationContext={...u.propagationContext,...G}}function no(u,c,h){u[c]=Ks(u[c],h,1)}function aS(u,c,h,m,y,k){let{normalizeDepth:S=3,normalizeMaxBreadth:C=1e3}=u,E={...c,event_id:c.event_id||h.event_id||It(),timestamp:c.timestamp||qr()},O=h.integrations||u.integrations.map((W=>W.name));(function(W,z){let{environment:ne,release:oe,dist:ue,maxValueLength:me=250}=z;W.environment=W.environment||ne||Sc,!W.release&&oe&&(W.release=oe),!W.dist&&ue&&(W.dist=ue),W.message&&(W.message=Ki(W.message,me));let he=W.exception&&W.exception.values&&W.exception.values[0];he&&he.value&&(he.value=Ki(he.value,me));let we=W.request;we&&we.url&&(we.url=Ki(we.url,me))})(E,u),(function(W,z){z.length>0&&(W.sdk=W.sdk||{},W.sdk.integrations=[...W.sdk.integrations||[],...z])})(E,O),y&&y.emit("applyFrameMetadata",c),c.type===void 0&&(function(W,z){let ne=(function(oe){let ue=Pe._sentryDebugIds;if(!ue)return{};let me=Object.keys(ue);return _c&&me.length===$h||($h=me.length,_c=me.reduce(((he,we)=>{to||(to={});let qe=to[we];if(qe)he[qe[0]]=qe[1];else{let Vt=oe(we);for(let Et=Vt.length-1;Et>=0;Et--){let En=Vt[Et],sn=En&&En.filename,Pn=ue[we];if(sn&&Pn){he[sn]=Pn,to[we]=[sn,Pn];break}}}return he}),{})),_c})(z);try{W.exception.values.forEach((oe=>{oe.stacktrace.frames.forEach((ue=>{ne&&ue.filename&&(ue.debug_id=ne[ue.filename])}))}))}catch{}})(E,u.stackParser);let F=(function(W,z){if(!z)return W;let ne=W?W.clone():new kn;return ne.update(z),ne})(m,h.captureContext);h.mechanism&&zi(E,h.mechanism);let V=y?y.getEventProcessors():[],G=Un("globalScope",(()=>new kn)).getScopeData();k&&Qh(G,k.getScopeData()),F&&Qh(G,F.getScopeData());let Q=[...h.attachments||[],...G.attachments];return Q.length&&(h.attachments=Q),(function(W,z){let{fingerprint:ne,span:oe,breadcrumbs:ue,sdkProcessingMetadata:me}=z;(function(he,we){let{extra:qe,tags:Vt,user:Et,contexts:En,level:sn,transactionName:Pn}=we,nr=Rt(qe);nr&&Object.keys(nr).length&&(he.extra={...nr,...he.extra});let ir=Rt(Vt);ir&&Object.keys(ir).length&&(he.tags={...ir,...he.tags});let rr=Rt(Et);rr&&Object.keys(rr).length&&(he.user={...rr,...he.user});let sr=Rt(En);sr&&Object.keys(sr).length&&(he.contexts={...sr,...he.contexts}),sn&&(he.level=sn),Pn&&he.type!=="transaction"&&(he.transaction=Pn)})(W,z),oe&&(function(he,we){he.contexts={trace:rS(we),...he.contexts},he.sdkProcessingMetadata={dynamicSamplingContext:oS(we),...he.sdkProcessingMetadata};let qe=wc(zh(we)).description;qe&&!he.transaction&&he.type==="transaction"&&(he.transaction=qe)})(W,oe),(function(he,we){he.fingerprint=he.fingerprint?Array.isArray(he.fingerprint)?he.fingerprint:[he.fingerprint]:[],we&&(he.fingerprint=he.fingerprint.concat(we)),he.fingerprint&&!he.fingerprint.length&&delete he.fingerprint})(W,ne),(function(he,we){let qe=[...he.breadcrumbs||[],...we];he.breadcrumbs=qe.length?qe:void 0})(W,ue),(function(he,we){he.sdkProcessingMetadata={...he.sdkProcessingMetadata,...we}})(W,me)})(E,G),Tc([...V,...G.eventProcessors],E,h).then((W=>(W&&(function(z){let ne={};try{z.exception.values.forEach((ue=>{ue.stacktrace.frames.forEach((me=>{me.debug_id&&(me.abs_path?ne[me.abs_path]=me.debug_id:me.filename&&(ne[me.filename]=me.debug_id),delete me.debug_id)}))}))}catch{}if(Object.keys(ne).length===0)return;z.debug_meta=z.debug_meta||{},z.debug_meta.images=z.debug_meta.images||[];let oe=z.debug_meta.images;Object.entries(ne).forEach((([ue,me])=>{oe.push({type:"sourcemap",code_file:ue,debug_id:me})}))})(W),typeof S=="number"&&S>0?(function(z,ne,oe){if(!z)return null;let ue={...z,...z.breadcrumbs&&{breadcrumbs:z.breadcrumbs.map((me=>({...me,...me.data&&{data:Tn(me.data,ne,oe)}})))},...z.user&&{user:Tn(z.user,ne,oe)},...z.contexts&&{contexts:Tn(z.contexts,ne,oe)},...z.extra&&{extra:Tn(z.extra,ne,oe)}};return z.contexts&&z.contexts.trace&&ue.contexts&&(ue.contexts.trace=z.contexts.trace,z.contexts.trace.data&&(ue.contexts.trace.data=Tn(z.contexts.trace.data,ne,oe))),z.spans&&(ue.spans=z.spans.map((me=>({...me,...me.data&&{data:Tn(me.data,ne,oe)}})))),z.contexts&&z.contexts.flags&&ue.contexts&&(ue.contexts.flags=Tn(z.contexts.flags,3,oe)),ue})(W,S,C):W)))}let cS=["user","level","extra","contexts","tags","fingerprint","requestSession","propagationContext"];function Xh(u,c){return li().captureEvent(u,c)}function Zh(u){let c=ht(),h=Vr(),m=li(),{release:y,environment:k=Sc}=c&&c.getOptions()||{},{userAgent:S}=Pe.navigator||{},C=(function(O){let F=bn(),V={sid:It(),init:!0,timestamp:F,started:F,duration:0,status:"ok",errors:0,ignoreDuration:!1,toJSON:()=>(function(G){return Rt({sid:`${G.sid}`,init:G.init,started:new Date(1e3*G.started).toISOString(),timestamp:new Date(1e3*G.timestamp).toISOString(),status:G.status,errors:G.errors,did:typeof G.did=="number"||typeof G.did=="string"?`${G.did}`:void 0,duration:G.duration,abnormal_mechanism:G.abnormal_mechanism,attrs:{release:G.release,environment:G.environment,ip_address:G.ipAddress,user_agent:G.userAgent}})})(V)};return O&&Yi(V,O),V})({release:y,environment:k,user:m.getUser()||h.getUser(),...S&&{userAgent:S},...u}),E=h.getSession();return E&&E.status==="ok"&&Yi(E,{status:"exited"}),ep(),h.setSession(C),m.setSession(C),C}function ep(){let u=Vr(),c=li(),h=c.getSession()||u.getSession();h&&(function(m){let y={};m.status==="ok"&&(y={status:"exited"}),Yi(m,y)})(h),tp(),u.setSession(),c.setSession()}function tp(){let u=Vr(),c=li(),h=ht(),m=c.getSession()||u.getSession();m&&h&&h.captureSession(m)}function np(u=!1){u?ep():tp()}let rt=Pe,Ec=0;function ip(){return Ec>0}function Xi(u,c={}){if(!(function(m){return typeof m=="function"})(u))return u;try{let m=u.__sentry_wrapped__;if(m)return typeof m=="function"?m:u;if(ac(u))return u}catch{return u}let h=function(...m){try{let y=m.map((k=>Xi(k,c)));return u.apply(this,y)}catch(y){throw Ec++,setTimeout((()=>{Ec--})),(function(...k){let S=fc(Js());if(k.length===2){let[C,E]=k;return C?S.withSetScope(C,E):S.withScope(E)}S.withScope(k[0])})((k=>{var S;k.addEventProcessor((C=>(c.mechanism&&(lc(C,void 0,void 0),zi(C,c.mechanism)),C.extra={...C.extra,arguments:m},C))),S=y,li().captureException(S,(function(C){if(C)return(function(E){return E instanceof kn||typeof E=="function"})(C)||(function(E){return Object.keys(E).some((O=>cS.includes(O)))})(C)?{captureContext:C}:C})(void 0))})),y}};try{for(let m in u)Object.prototype.hasOwnProperty.call(u,m)&&(h[m]=u[m])}catch{}yh(h,u),ci(u,"__sentry_wrapped__",h);try{Object.getOwnPropertyDescriptor(h,"name").configurable&&Object.defineProperty(h,"name",{get(){return u.name}})}catch{}return h}let lS=(u={})=>{let c={console:!0,dom:!0,fetch:!0,history:!0,sentry:!0,xhr:!0,...u};return{name:"Breadcrumbs",setup(h){var m;c.console&&(function(y){let k="console";di(k,y),hi(k,Zk)})((function(y){return function(k){if(ht()!==y)return;let S={category:"console",data:{arguments:k.args,logger:"console"},level:(C=k.level,C==="warn"?"warning":["fatal","error","warning","log","info","debug"].includes(C)?C:"log"),message:vh(k.args," ")};var C;if(k.level==="assert"){if(k.args[0]!==!1)return;S.message=`Assertion failed: ${vh(k.args.slice(1)," ")||"console.assert"}`,S.data.arguments=k.args.slice(1)}pi(S,{input:k.args,level:k.level})}})(h)),c.dom&&(m=(function(y,k){return function(S){if(ht()!==y)return;let C,E,O=typeof k=="object"?k.serializeAttribute:void 0,F=typeof k=="object"&&typeof k.maxStringLength=="number"?k.maxStringLength:void 0;F&&F>1024&&(Zs&&be.warn(`\`dom.maxStringLength\` cannot exceed 1024, but a value of ${F} was configured. Sentry will use 1024 instead.`),F=1024),typeof O=="string"&&(O=[O]);try{let G=S.event,Q=(function(W){return!!W&&!!W.target})(G)?G.target:G;C=gh(Q,{keyAttrs:O,maxStringLength:F}),E=(function(W){if(!oc.HTMLElement)return null;let z=W;for(let ne=0;ne<5;ne++){if(!z)return null;if(z instanceof HTMLElement){if(z.dataset.sentryComponent)return z.dataset.sentryComponent;if(z.dataset.sentryElement)return z.dataset.sentryElement}z=z.parentNode}return null})(Q)}catch{C="<unknown>"}if(C.length===0)return;let V={category:`ui.${S.name}`,message:C};E&&(V.data={"ui.component_name":E}),pi(V,{event:S.event,name:S.name,global:S.global})}})(h,c.dom),di("dom",m),hi("dom",Yk)),c.xhr&&(function(y){di("xhr",y),hi("xhr",Qk)})((function(y){return function(k){if(ht()!==y)return;let{startTimestamp:S,endTimestamp:C}=k,E=k.xhr[$r];if(!S||!C||!E)return;let{method:O,url:F,status_code:V,body:G}=E,Q={method:O,url:F,status_code:V},W={xhr:k.xhr,input:G,startTimestamp:S,endTimestamp:C};pi({category:"xhr",data:Q,type:"http",level:Vh(V)},W)}})(h)),c.fetch&&(function(y){let k="fetch";di(k,y),hi(k,(()=>eS(void 0,void 0)))})((function(y){return function(k){if(ht()!==y)return;let{startTimestamp:S,endTimestamp:C}=k;
13if(C&&(!k.fetchData.url.match(/sentry_key/)||k.fetchData.method!=="POST"))if(k.error)pi({category:"fetch",data:k.fetchData,level:"error",type:"http"},{data:k.error,input:k.args,startTimestamp:S,endTimestamp:C});else{let E=k.response,O={...k.fetchData,status_code:E&&E.status},F={input:k.args,response:E,startTimestamp:S,endTimestamp:C};pi({category:"fetch",data:O,type:"http",level:Vh(O.status_code)},F)}}})(h)),c.history&&Bh((function(y){return function(k){if(ht()!==y)return;let S=k.from,C=k.to,E=kc(rt.location.href),O=S?kc(S):void 0,F=kc(C);O&&O.path||(O=E),E.protocol===F.protocol&&E.host===F.host&&(C=F.relative),E.protocol===O.protocol&&E.host===O.host&&(S=O.relative),pi({category:"navigation",data:{from:S,to:C}})}})(h)),c.sentry&&h.on("beforeSendEvent",(function(y){return function(k){ht()===y&&pi({category:"sentry."+(k.type==="transaction"?"transaction":"event"),event_id:k.event_id,level:k.level,message:Bn(k)},{event:k})}})(h))}}},uS=["EventTarget","Window","Node","ApplicationCache","AudioTrackList","BroadcastChannel","ChannelMergerNode","CryptoOperation","EventSource","FileReader","HTMLUnknownElement","IDBDatabase","IDBRequest","IDBTransaction","KeyOperation","MediaController","MessagePort","ModalWindow","Notification","SVGElementInstance","Screen","SharedWorker","TextTrack","TextTrackCue","TextTrackList","WebSocket","WebSocketWorker","Worker","XMLHttpRequest","XMLHttpRequestEventTarget","XMLHttpRequestUpload"],dS=(u={})=>{let c={XMLHttpRequest:!0,eventTarget:!0,requestAnimationFrame:!0,setInterval:!0,setTimeout:!0,...u};return{name:"BrowserApiErrors",setupOnce(){c.setTimeout&&Ct(rt,"setTimeout",rp),c.setInterval&&Ct(rt,"setInterval",rp),c.requestAnimationFrame&&Ct(rt,"requestAnimationFrame",hS),c.XMLHttpRequest&&"XMLHttpRequest"in rt&&Ct(XMLHttpRequest.prototype,"send",pS);let h=c.eventTarget;h&&(Array.isArray(h)?h:uS).forEach(fS)}}};function rp(u){return function(...c){let h=c[0];return c[0]=Xi(h,{mechanism:{data:{function:qn(u)},handled:!1,type:"instrument"}}),u.apply(this,c)}}function hS(u){return function(c){return u.apply(this,[Xi(c,{mechanism:{data:{function:"requestAnimationFrame",handler:qn(u)},handled:!1,type:"instrument"}})])}}function pS(u){return function(...c){let h=this;return["onload","onerror","onprogress","onreadystatechange"].forEach((m=>{m in h&&typeof h[m]=="function"&&Ct(h,m,(function(y){let k={mechanism:{data:{function:m,handler:qn(y)},handled:!1,type:"instrument"}},S=ac(y);return S&&(k.mechanism.data.handler=qn(S)),Xi(y,k)}))})),u.apply(this,c)}}function fS(u){let c=rt[u],h=c&&c.prototype;h&&h.hasOwnProperty&&h.hasOwnProperty("addEventListener")&&(Ct(h,"addEventListener",(function(m){return function(y,k,S){try{typeof k.handleEvent=="function"&&(k.handleEvent=Xi(k.handleEvent,{mechanism:{data:{function:"handleEvent",handler:qn(k),target:u},handled:!1,type:"instrument"}}))}catch{}return m.apply(this,[y,Xi(k,{mechanism:{data:{function:"addEventListener",handler:qn(k),target:u},handled:!1,type:"instrument"}}),S])}})),Ct(h,"removeEventListener",(function(m){return function(y,k,S){try{let C=k.__sentry_wrapped__;C&&m.call(this,y,C,S)}catch{}return m.call(this,y,k,S)}})))}let Pc=null;function mS(){Pc=Pe.onerror,Pe.onerror=function(u,c,h,m,y){return jt("error",{column:m,error:y,line:h,msg:u,url:c}),!!Pc&&Pc.apply(this,arguments)},Pe.onerror.__SENTRY_INSTRUMENTED__=!0}let Ac=null;function gS(){Ac=Pe.onunhandledrejection,Pe.onunhandledrejection=function(u){return jt("unhandledrejection",u),!Ac||Ac.apply(this,arguments)},Pe.onunhandledrejection.__SENTRY_INSTRUMENTED__=!0}function Mc(u,c){let h=Ic(u,c),m={type:yS(c),value:bS(c)};return h.length&&(m.stacktrace={frames:h}),m.type===void 0&&m.value===""&&(m.value="Unrecoverable error caught"),m}function Rc(u,c){return{exception:{values:[Mc(u,c)]}}}function Ic(u,c){let h=c.stacktrace||c.stack||"",m=(function(k){return k&&vS.test(k.message)?1:0})(c),y=(function(k){return typeof k.framesToPop=="number"?k.framesToPop:0})(c);try{return u(h,m,y)}catch{}return[]}let vS=/Minified React error #\d+;/i;function sp(u){return typeof WebAssembly<"u"&&WebAssembly.Exception!==void 0&&u instanceof WebAssembly.Exception}function yS(u){let c=u&&u.name;return!c&&sp(u)?u.message&&Array.isArray(u.message)&&u.message.length==2?u.message[0]:"WebAssembly.Exception":c}function bS(u){let c=u&&u.message;return c?c.error&&typeof c.error.message=="string"?c.error.message:sp(u)&&Array.isArray(u.message)&&u.message.length==2?u.message[1]:c:"No error message"}function Oc(u,c,h,m,y){let k;if(ph(c)&&c.error)return Rc(u,c.error);if(fh(c)||Ji(c,"DOMException")){let S=c;if("stack"in c)k=Rc(u,c);else{let C=S.name||(fh(S)?"DOMError":"DOMException"),E=S.message?`${C}: ${S.message}`:C;k=Dc(u,E,h,m),lc(k,E)}return"code"in S&&(k.tags={...k.tags,"DOMException.code":`${S.code}`}),k}return ic(c)?Rc(u,c):Hi(c)||Vs(c)?(k=(function(S,C,E,O){let F=ht(),V=F&&F.getOptions().normalizeDepth,G=(function(z){for(let ne in z)if(Object.prototype.hasOwnProperty.call(z,ne)){let oe=z[ne];if(oe instanceof Error)return oe}})(C),Q={__serialized__:Wh(C,V)};if(G)return{exception:{values:[Mc(S,G)]},extra:Q};let W={exception:{values:[{type:Vs(C)?C.constructor.name:O?"UnhandledRejection":"Error",value:kS(C,{isUnhandledRejection:O})}]},extra:Q};if(E){let z=Ic(S,E);z.length&&(W.exception.values[0].stacktrace={frames:z})}return W})(u,c,h,y),zi(k,{synthetic:!0}),k):(k=Dc(u,c,h,m),lc(k,`${c}`,void 0),zi(k,{synthetic:!0}),k)}function Dc(u,c,h,m){let y={};if(m&&h){let k=Ic(u,h);k.length&&(y.exception={values:[{value:c,stacktrace:{frames:k}}]}),zi(y,{synthetic:!0})}
13if(rc(c)){let{__sentry_template_string__:k,__sentry_template_values__:S}=c;return y.logentry={message:k,params:S},y}return y.message=c,y}function kS(u,{isUnhandledRejection:c}){let h=(function(y,k=40){let S=Object.keys(bh(y));S.sort();let C=S[0];if(!C)return"[object has no keys]";if(C.length>=k)return Ki(C,k);for(let E=S.length;E>0;E--){let O=S.slice(0,E).join(", ");if(!(O.length>k))return E===S.length?O:Ki(O,k)}return""})(u),m=c?"promise rejection":"exception";return ph(u)?`Event \`ErrorEvent\` captured as ${m} with message \`${u.message}\``:Vs(u)?`Event \`${(function(y){try{let k=Object.getPrototypeOf(y);return k?k.constructor.name:void 0}catch{}})(u)}\` (type=${u.type}) captured as ${m}`:`Object captured as ${m} with keys: ${h}`}let SS=(u={})=>{let c={onerror:!0,onunhandledrejection:!0,...u};return{name:"GlobalHandlers",setupOnce(){Error.stackTraceLimit=50},setup(h){c.onerror&&((function(m){(function(){let y="error";di(y,(k=>{let{stackParser:S,attachStacktrace:C}=ap();if(ht()!==m||ip())return;let{msg:E,url:O,line:F,column:V,error:G}=k,Q=(function(W,z,ne,oe){let ue=W.exception=W.exception||{},me=ue.values=ue.values||[],he=me[0]=me[0]||{},we=he.stacktrace=he.stacktrace||{},qe=we.frames=we.frames||[],Vt=oe,Et=ne,En=yn(z)&&z.length>0?z:(function(){try{return oc.document.location.href}catch{return""}})();return qe.length===0&&qe.push({colno:Vt,filename:En,function:ui,in_app:!0,lineno:Et}),W})(Oc(S,G||E,void 0,C,!1),O,F,V);Q.level="error",Xh(Q,{originalException:G,mechanism:{handled:!1,type:"onerror"}})})),hi(y,mS)})()})(h),op("onerror")),c.onunhandledrejection&&((function(m){(function(){let y="unhandledrejection";di(y,(k=>{let{stackParser:S,attachStacktrace:C}=ap();if(ht()!==m||ip())return;let E=(function(F){if(sc(F))return F;try{if("reason"in F)return F.reason;if("detail"in F&&"reason"in F.detail)return F.detail.reason}catch{}return F})(k),O=sc(E)?{exception:{values:[{type:"UnhandledRejection",value:`Non-Error promise rejection captured with value: ${String(E)}`}]}}:Oc(S,E,void 0,C,!0);O.level="error",Xh(O,{originalException:E,mechanism:{handled:!1,type:"onunhandledrejection"}})})),hi(y,gS)})()})(h),op("onunhandledrejection"))}}};function op(u){Zs&&be.log(`Global Handler attached: ${u}`)}function ap(){let u=ht();return u&&u.getOptions()||{stackParser:()=>[],attachStacktrace:!1}}
13function TS(u,c,h=250,m,y,k,S){if(!(k.exception&&k.exception.values&&S&&ai(S.originalException,Error)))return;let C=k.exception.values.length>0?k.exception.values[k.exception.values.length-1]:void 0;var E,O;C&&(k.exception.values=(E=Lc(u,c,y,S.originalException,m,k.exception.values,C,0),O=h,E.map((F=>(F.value&&(F.value=Ki(F.value,O)),F)))))}function Lc(u,c,h,m,y,k,S,C){if(k.length>=h+1)return k;let E=[...k];if(ai(m[y],Error)){cp(S,C);let O=u(c,m[y]),F=E.length;lp(O,y,F,C),E=Lc(u,c,h,m[y],y,[O,...E],O,F)}return Array.isArray(m.errors)&&m.errors.forEach(((O,F)=>{if(ai(O,Error)){cp(S,C);let V=u(c,O),G=E.length;lp(V,`errors[${F}]`,G,C),E=Lc(u,c,h,O,y,[V,...E],V,G)}})),E}function cp(u,c){u.mechanism=u.mechanism||{type:"generic",handled:!0},u.mechanism={...u.mechanism,...u.type==="AggregateError"&&{is_exception_group:!0},exception_id:c}}function lp(u,c,h,m){u.mechanism=u.mechanism||{type:"generic",handled:!0},u.mechanism={...u.mechanism,type:"chained",source:c,exception_id:h,parent_id:m}}let _S=(u={})=>{let c=u.limit||5,h=u.key||"cause";return{name:"LinkedErrors",preprocessEvent(m,y,k){let S=k.getOptions();TS(Mc,S.stackParser,S.maxValueLength,h,c,m,y)}}};function CS(u){let c=[$k(),Kk(),dS(),lS(),SS(),_S(),zk(),{name:"HttpContext",preprocessEvent(h){if(!rt.navigator&&!rt.location&&!rt.document)return;let m=h.request&&h.request.url||rt.location&&rt.location.href,{referrer:y}=rt.document||{},{userAgent:k}=rt.navigator||{},S={...h.request&&h.request.headers,...y&&{Referer:y},...k&&{"User-Agent":k}},C={...h.request,...m&&{url:m},headers:S};h.request=C}}];return u.autoSessionTracking!==!1&&c.push({name:"BrowserSession",setupOnce(){rt.document!==void 0?(Zh({ignoreDuration:!0}),np(),Bh((({from:h,to:m})=>{h!==void 0&&h!==m&&(Zh({ignoreDuration:!0}),np())}))):Zs&&be.warn("Using the `browserSessionIntegration` in non-browser environments is not supported.")}}),c}let wS=/^(?:(\w+):)\/\/(?:(\w+)(?::(\w+)?)?@)([\w.-]+)(?::(\d+))?\/(.+)/;function io(u,c=!1){let{host:h,path:m,pass:y,port:k,projectId:S,protocol:C,publicKey:E}=u;return`${C}://${E}${c&&y?`:${y}`:""}@${h}${k?`:${k}`:""}/${m&&`${m}/`}${S}`}function up(u){return{protocol:u.protocol,publicKey:u.publicKey||"",pass:u.pass||"",host:u.host,port:u.port||"",path:u.path||"",projectId:u.projectId}}function Wr(u,c=[]){return[u,c]}function ES(u,c){let[h,m]=u;return[h,[...m,c]]}function dp(u,c){let h=u[1];for(let m of h)if(c(m,m[0].type))return!0;return!1}function xc(u){return Pe.__SENTRY__&&Pe.__SENTRY__.encodePolyfill?Pe.__SENTRY__.encodePolyfill(u):new TextEncoder().encode(u)}function PS(u){let[c,h]=u,m=JSON.stringify(c);function y(k){typeof m=="string"?m=typeof k=="string"?m+k:[xc(m),k]:m.push(typeof k=="string"?xc(k):k)}for(let k of h){let[S,C]=k;if(y(` 14${JSON.stringify(S)} 15`),typeof C=="string"||C instanceof Uint8Array)y(C);else{let E;try{E=JSON.stringify(C)}catch{E=JSON.stringify(Tn(C))}y(E)}}return typeof m=="string"?m:(function(k){let S=k.reduce(((O,F)=>O+F.length),0),C=new Uint8Array(S),E=0;for(let O of k)C.set(O,E),E+=O.length;return C})(m)}function AS(u){let c=typeof u.data=="string"?xc(u.data):u.data;return[Rt({type:"attachment",length:c.length,filename:u.filename,content_type:u.contentType,attachment_type:u.attachmentType}),c]}let MS={session:"session",sessions:"session",attachment:"attachment",transaction:"transaction",event:"error",client_report:"internal",user_report:"default",profile:"profile",profile_chunk:"profile",replay_event:"replay",replay_recording:"replay",check_in:"monitor",feedback:"feedback",span:"span",statsd:"metric_bucket",raw_security:"security"};function hp(u){return MS[u]}function pp(u){if(!u||!u.sdk)return;let{name:c,version:h}=u.sdk;return{name:c,version:h}}class Bt extends Error{constructor(c,h="warn"){super(c),this.message=c,this.logLevel=h}}let fp="Not capturing exception because it's already been captured.";class RS{constructor(c){if(this._options=c,this._integrations={},this._numProcessing=0,this._outcomes={},this._hooks={},this._eventProcessors=[],c.dsn?this._dsn=(function(S){let C=typeof S=="string"?(function(E){let O=wS.exec(E);if(!O)return void vn((()=>{console.error(`Invalid Sentry Dsn: ${E}`)}));let[F,V,G="",Q="",W="",z=""]=O.slice(1),ne="",oe=z,ue=oe.split("/");if(ue.length>1&&(ne=ue.slice(0,-1).join("/"),oe=ue.pop()),oe){let me=oe.match(/^\d+/);me&&(oe=me[0])}return up({host:Q,pass:G,path:ne,projectId:oe,port:W,protocol:F,publicKey:V})})(S):up(S);if(C&&(function(E){if(!je)return!0;let{port:O,projectId:F,protocol:V}=E;return!(["protocol","publicKey","host","projectId"].find((G=>!E[G]&&(be.error(`Invalid Sentry Dsn: ${G} missing`),!0)))||(F.match(/^\d+$/)?(function(G){return G==="http"||G==="https"})(V)?O&&isNaN(parseInt(O,10))&&(be.error(`Invalid Sentry Dsn: Invalid port ${O}`),1):(be.error(`Invalid Sentry Dsn: Invalid protocol ${V}`),1):(be.error(`Invalid Sentry Dsn: Invalid projectId ${F}`),1)))})(C))return C})(c.dsn):Ee&&be.warn("No DSN provided, client will not send events."),this._dsn){let S=(h=this._dsn,m=c.tunnel,y=c._metadata?c._metadata.sdk:void 0,m||`${(function(C){return`${(function(E){let O=E.protocol?`${E.protocol}:`:"",F=E.port?`:${E.port}`:"";return`${O}//${E.host}${F}${E.path?`/${E.path}`:""}/api/`})(C)}${C.projectId}/envelope/`})(h)}?${(function(C,E){let O={sentry_version:"7"};return C.publicKey&&(O.sentry_key=C.publicKey),E&&(O.sentry_client=`${E.name}/${E.version}`),new URLSearchParams(O).toString()})(h,y)}`);this._transport=c.transport({tunnel:this._options.tunnel,recordDroppedEvent:this.recordDroppedEvent.bind(this),...c.transportOptions,url:S})}var h,m,y;let k=["enableTracing","tracesSampleRate","tracesSampler"].find((S=>S in c&&c[S]==null));k&&vn((()=>{console.warn(`[Sentry] Deprecation warning: \`${k}\` is set to undefined, which leads to tracing being enabled. In v9, a value of \`undefined\` will result in tracing being disabled.`)}))}
15captureException(c,h,m){let y=It();if(_h(c))return Ee&&be.log(fp),y;let k={event_id:y,...h};return this._process(this.eventFromException(c,k).then((S=>this._captureEvent(S,k,m)))),k.event_id}captureMessage(c,h,m,y){let k={event_id:It(),...m},S=rc(c)?c:String(c),C=sc(c)?this.eventFromMessage(S,h,k):this.eventFromException(c,k);return this._process(C.then((E=>this._captureEvent(E,k,y)))),k.event_id}captureEvent(c,h,m){let y=It();if(h&&h.originalException&&_h(h.originalException))return Ee&&be.log(fp),y;let k={event_id:y,...h},S=(c.sdkProcessingMetadata||{}).capturedSpanScope;return this._process(this._captureEvent(c,k,S||m)),k.event_id}captureSession(c){typeof c.release!="string"?Ee&&be.warn("Discarded session because of missing or non-string release"):(this.sendSession(c),Yi(c,{init:!1}))}getDsn(){return this._dsn}getOptions(){return this._options}getSdkMetadata(){return this._options._metadata}getTransport(){return this._transport}flush(c){let h=this._transport;return h?(this.emit("flush"),this._isClientDoneProcessing(c).then((m=>h.flush(c).then((y=>m&&y))))):fi(!0)}close(c){return this.flush(c).then((h=>(this.getOptions().enabled=!1,this.emit("close"),h)))}getEventProcessors(){return this._eventProcessors}addEventProcessor(c){this._eventProcessors.push(c)}init(){(this._isEnabled()||this._options.integrations.some((({name:c})=>c.startsWith("Spotlight"))))&&this._setupIntegrations()}getIntegrationByName(c){return this._integrations[c]}addIntegration(c){let h=this._integrations[c.name];dh(this,c,this._integrations),h||Gi(this,[c])}sendEvent(c,h={}){this.emit("beforeSendEvent",c,h);let m=(function(k,S,C,E){let O=pp(C),F=k.type&&k.type!=="replay_event"?k.type:"event";(function(G,Q){Q&&(G.sdk=G.sdk||{},G.sdk.name=G.sdk.name||Q.name,G.sdk.version=G.sdk.version||Q.version,G.sdk.integrations=[...G.sdk.integrations||[],...Q.integrations||[]],G.sdk.packages=[...G.sdk.packages||[],...Q.packages||[]])})(k,C&&C.sdk);let V=(function(G,Q,W,z){let ne=G.sdkProcessingMetadata&&G.sdkProcessingMetadata.dynamicSamplingContext;return{event_id:G.event_id,sent_at:new Date().toISOString(),...Q&&{sdk:Q},...!!W&&z&&{dsn:io(z)},...ne&&{trace:Rt({...ne})}}})(k,O,E,S);return delete k.sdkProcessingMetadata,Wr(V,[[{type:F},k]])})(c,this._dsn,this._options._metadata,this._options.tunnel);for(let k of h.attachments||[])m=ES(m,AS(k));let y=this.sendEnvelope(m);y&&y.then((k=>this.emit("afterSendEvent",c,k)),null)}sendSession(c){let h=(function(m,y,k,S){let C=pp(k);return Wr({sent_at:new Date().toISOString(),...C&&{sdk:C},...!!S&&y&&{dsn:io(y)}},["aggregates"in m?[{type:"sessions"},m]:[{type:"session"},m.toJSON()]])})(c,this._dsn,this._options._metadata,this._options.tunnel);this.sendEnvelope(h)}recordDroppedEvent(c,h,m){if(this._options.sendClientReports){let y=typeof m=="number"?m:1,k=`${c}:${h}`;
15Ee&&be.log(`Recording outcome: "${k}"${y>1?` (${y} times)`:""}`),this._outcomes[k]=(this._outcomes[k]||0)+y}}on(c,h){let m=this._hooks[c]=this._hooks[c]||[];return m.push(h),()=>{let y=m.indexOf(h);y>-1&&m.splice(y,1)}}emit(c,...h){let m=this._hooks[c];m&&m.forEach((y=>y(...h)))}sendEnvelope(c){return this.emit("beforeEnvelope",c),this._isEnabled()&&this._transport?this._transport.send(c).then(null,(h=>(Ee&&be.error("Error while sending envelope:",h),h))):(Ee&&be.error("Transport disabled"),fi({}))}_setupIntegrations(){let{integrations:c}=this._options;this._integrations=(function(h,m){let y={};return m.forEach((k=>{k&&dh(h,k,y)})),y})(this,c),Gi(this,c)}_updateSessionFromEvent(c,h){let m=h.level==="fatal",y=!1,k=h.exception&&h.exception.values;if(k){y=!0;for(let C of k){let E=C.mechanism;if(E&&E.handled===!1){m=!0;break}}}let S=c.status==="ok";(S&&c.errors===0||S&&m)&&(Yi(c,{...m&&{status:"crashed"},errors:c.errors||Number(y||m)}),this.captureSession(c))}_isClientDoneProcessing(c){return new Ot((h=>{let m=0,y=setInterval((()=>{this._numProcessing==0?(clearInterval(y),h(!0)):(m+=1,c&&m>=c&&(clearInterval(y),h(!1)))}),1)}))}_isEnabled(){return this.getOptions().enabled!==!1&&this._transport!==void 0}_prepareEvent(c,h,m=li(),y=Vr()){let k=this.getOptions(),S=Object.keys(this._integrations);return!h.integrations&&S.length>0&&(h.integrations=S),this.emit("preprocessEvent",c,h),c.type||y.setLastEventId(c.event_id||h.event_id),aS(k,c,h,m,this,y).then((C=>{if(C===null)return C;C.contexts={trace:Hk(m),...C.contexts};let E=(function(O,F){let V=F.getPropagationContext();return V.dsc||Yh(V.traceId,O)})(this,m);return C.sdkProcessingMetadata={dynamicSamplingContext:E,...C.sdkProcessingMetadata},C}))}_captureEvent(c,h={},m){return this._processEvent(c,h,m).then((y=>y.event_id),(y=>{Ee&&(y instanceof Bt&&y.logLevel==="log"?be.log(y.message):be.warn(y))}))}_processEvent(c,h,m){let y=this.getOptions(),{sampleRate:k}=y,S=gp(c),C=mp(c),E=c.type||"error",O=`before send for type \`${E}\``,F=k===void 0?void 0:(function(Q){if(typeof Q=="boolean")return Number(Q);let W=typeof Q=="string"?parseFloat(Q):Q;if(!(typeof W!="number"||isNaN(W)||W<0||W>1))return W;Ee&&be.warn(`[Tracing] Given sample rate is invalid. Sample rate must be a boolean or a number between 0 and 1. Got ${JSON.stringify(Q)} of type ${JSON.stringify(typeof Q)}.`)})(k);if(C&&typeof F=="number"&&Math.random()>F)return this.recordDroppedEvent("sample_rate","error",c),eo(new Bt(`Discarding event because it's not included in the random sample (sampling rate = ${k})`,"log"));let V=E==="replay_event"?"replay":E,G=(c.sdkProcessingMetadata||{}).capturedSpanIsolationScope;return this._prepareEvent(c,h,m,G).then((Q=>{if(Q===null)throw this.recordDroppedEvent("event_processor",V,c),new Bt("An event processor returned `null`, will not send event.","log");if(h.data&&h.data.__sentry__===!0)return Q;let W=(function(z,ne,oe,ue){let{beforeSend:me,beforeSendTransaction:he,beforeSendSpan:we}=ne;if(mp(oe)&&me)return me(oe,ue);if(gp(oe)){if(oe.spans&&we){let qe=[];for(let Vt of oe.spans){let Et=we(Vt);Et?qe.push(Et):(Jh||(vn((()=>{console.warn("[Sentry] Deprecation warning: Returning null from `beforeSendSpan` will be disallowed from SDK version 9.0.0 onwards. The callback will only support mutating spans. To drop certain spans, configure the respective integrations directly.")})),Jh=!0),z.recordDroppedEvent("before_send","span"))}oe.spans=qe}if(he){if(oe.spans){let qe=oe.spans.length;oe.sdkProcessingMetadata={...oe.sdkProcessingMetadata,spanCountBeforeProcessing:qe}}return he(oe,ue)}}return oe})(this,y,Q,h);return(function(z,ne){let oe=`${ne} must return \`null\` or a valid event.`;if($s(z))return z.then((ue=>{if(!Hi(ue)&&ue!==null)throw new Bt(oe);return ue}),(ue=>{throw new Bt(`${ne} rejected with ${ue}`)}));if(!Hi(z)&&z!==null)throw new Bt(oe);return z})(W,O)})).then((Q=>{if(Q===null){if(this.recordDroppedEvent("before_send",V,c),S){let ne=1+(c.spans||[]).length;this.recordDroppedEvent("before_send","span",ne)}throw new Bt(`${O} returned \`null\`, will not send event.`,"log")}let W=m&&m.getSession();if(!S&&W&&this._updateSessionFromEvent(W,Q),S){let ne=(Q.sdkProcessingMetadata&&Q.sdkProcessingMetadata.spanCountBeforeProcessing||0)-(Q.spans?Q.spans.length:0);ne>0&&this.recordDroppedEvent("before_send","span",ne)}let z=Q.transaction_info;if(S&&z&&Q.transaction!==c.transaction){let ne="custom";Q.transaction_info={...z,source:ne}}return this.sendEvent(Q,h),Q})).then(null,(Q=>{throw Q instanceof Bt?Q:(this.captureException(Q,{data:{__sentry__:!0},originalException:Q}),new Bt(`Event processing pipeline threw an error, original event will not be sent. Details have been sent as a new event. 16Reason: ${Q}`))}))}_process(c){this._numProcessing++,c.then((h=>(this._numProcessing--,h)),(h=>(this._numProcessing--,h)))}_clearOutcomes(){let c=this._outcomes;return this._outcomes={},Object.entries(c).map((([h,m])=>{let[y,k]=h.split(":");return{reason:y,category:k,quantity:m}}))}_flushOutcomes(){Ee&&be.log("Flushing outcomes...");let c=this._clearOutcomes();if(c.length===0)return void(Ee&&be.log("No outcomes to send"));if(!this._dsn)return void(Ee&&be.log("No dsn provided, will not send outcomes"));Ee&&be.log("Sending outcomes:",c);let h=(m=c,Wr((y=this._options.tunnel&&io(this._dsn))?{dsn:y}:{},[[{type:"client_report"},{timestamp:qr(),discarded_events:m}]]));var m,y;this.sendEnvelope(h)}}function mp(u){return u.type===void 0}function gp(u){return u.type==="transaction"}class IS extends RS{constructor(c){let h={parentSpanIsAlwaysRootSpan:!0,...c};(function(m,y,k=[y],S="npm"){let C=m._metadata||{};C.sdk||(C.sdk={name:`sentry.javascript.${y}`,packages:k.map((E=>({name:`${S}:@sentry/${E}`,version:gt}))),version:gt}),m._metadata=C}
16)(h,"browser",["browser"],rt.SENTRY_SDK_SOURCE||"npm"),super(h),h.sendClientReports&&rt.document&&rt.document.addEventListener("visibilitychange",(()=>{rt.document.visibilityState==="hidden"&&this._flushOutcomes()}))}eventFromException(c,h){return(function(m,y,k,S){let C=Oc(m,y,k&&k.syntheticException||void 0,S);return zi(C),C.level="error",k&&k.event_id&&(C.event_id=k.event_id),fi(C)})(this._options.stackParser,c,h,this._options.attachStacktrace)}eventFromMessage(c,h="info",m){return(function(y,k,S="info",C,E){let O=Dc(y,k,C&&C.syntheticException||void 0,E);return O.level=S,C&&C.event_id&&(O.event_id=C.event_id),fi(O)})(this._options.stackParser,c,h,m,this._options.attachStacktrace)}captureUserFeedback(c){if(!this._isEnabled())return void(Zs&&be.warn("SDK not enabled, will not capture user feedback."));let h=(function(m,{metadata:y,tunnel:k,dsn:S}){let C={event_id:m.event_id,sent_at:new Date().toISOString(),...y&&y.sdk&&{sdk:{name:y.sdk.name,version:y.sdk.version}},...!!k&&!!S&&{dsn:io(S)}};return Wr(C,[(function(O){return[{type:"user_report"},O]})(m)])})(c,{metadata:this.getSdkMetadata(),dsn:this.getDsn(),tunnel:this.getOptions().tunnel});this.sendEnvelope(h)}_prepareEvent(c,h,m){return c.platform=c.platform||"javascript",super._prepareEvent(c,h,m)}}let OS=typeof __SENTRY_DEBUG__>"u"||__SENTRY_DEBUG__,ro={};function vp(u){ro[u]=void 0}function DS(u,c,h=(function(m){let y=[];function k(S){return y.splice(y.indexOf(S),1)[0]||Promise.resolve(void 0)}return{$:y,add:function(S){if(!(m===void 0||y.length<m))return eo(new Bt("Not adding Promise because buffer limit was reached."));let C=S();return y.indexOf(C)===-1&&y.push(C),C.then((()=>k(C))).then(null,(()=>k(C).then(null,(()=>{})))),C},drain:function(S){return new Ot(((C,E)=>{let O=y.length;if(!O)return C(!0);let F=setTimeout((()=>{S&&S>0&&C(!1)}),S);y.forEach((V=>{fi(V).then((()=>{--O||(clearTimeout(F),C(!0))}),E)}))}))}}})(u.bufferSize||64)){let m={};return{send:function(y){let k=[];if(dp(y,((E,O)=>{let F=hp(O);if((function(V,G,Q=Date.now()){return(function(W,z){return W[z]||W.all||0})(V,G)>Q})(m,F)){let V=yp(E,O);u.recordDroppedEvent("ratelimit_backoff",F,V)}else k.push(E)})),k.length===0)return fi({});let S=Wr(y[0],k),C=E=>{dp(S,((O,F)=>{let V=yp(O,F);u.recordDroppedEvent(E,hp(F),V)}))};return h.add((()=>c({body:PS(S)}).then((E=>(E.statusCode!==void 0&&(E.statusCode<200||E.statusCode>=300)&&Ee&&be.warn(`Sentry responded with status code ${E.statusCode} to sent event.`),m=(function(O,{statusCode:F,headers:V},G=Date.now()){let Q={...O},W=V&&V["x-sentry-rate-limits"],z=V&&V["retry-after"];if(W)for(let ne of W.trim().split(",")){let[oe,ue,,,me]=ne.split(":",5),he=parseInt(oe,10),we=1e3*(isNaN(he)?60:he);if(ue)for(let qe of ue.split(";"))qe==="metric_bucket"&&me&&!me.split(";").includes("custom")||(Q[qe]=G+we);else Q.all=G+we}else z?Q.all=G+(function(ne,oe=Date.now()){let ue=parseInt(`${ne}`,10);if(!isNaN(ue))return 1e3*ue;let me=Date.parse(`${ne}`);return isNaN(me)?6e4:me-oe})(z,G):F===429&&(Q.all=G+6e4);return Q})(m,E),E)),(E=>{throw C("network_error"),E})))).then((E=>E),(E=>{if(E instanceof Bt)return Ee&&be.error("Skipped sending event because buffer is full."),C("queue_overflow"),fi({});throw E}))},flush:y=>h.drain(y)}}function yp(u,c){if(c==="event"||c==="transaction")return Array.isArray(u)?u[1]:void 0}function LS(u,c=(function(h){let m=ro[h];if(m)return m;let y=vt[h];if(yc(y))return ro[h]=y.bind(vt);let k=vt.document;if(k&&typeof k.createElement=="function")try{let S=k.createElement("iframe");S.hidden=!0,k.head.appendChild(S);let C=S.contentWindow;C&&C[h]&&(y=C[h]),k.head.removeChild(S)}catch(S){OS&&be.warn(`Could not create sandbox iframe for ${h} check, bailing to window.${h}: `,S)}return y&&(ro[h]=y.bind(vt))})("fetch")){let h=0,m=0;return DS(u,(function(y){let k=y.body.length;h+=k,m++;let S={body:y.body,method:"POST",referrerPolicy:"origin",headers:u.headers,keepalive:h<=6e4&&m<15,...u.fetchOptions};if(!c)return vp("fetch"),eo("No fetch implementation available");try{return c(u.url,S).then((C=>(h-=k,m--,{statusCode:C.status,headers:{"x-sentry-rate-limits":C.headers.get("X-Sentry-Rate-Limits"),"retry-after":C.headers.get("Retry-After")}})))}catch(C){return vp("fetch"),h-=k,m--,eo(C)}}))}function Nc(u,c,h,m){let y={filename:u,function:c==="<anonymous>"?ui:c,in_app:!0};return h!==void 0&&(y.lineno=h),m!==void 0&&(y.colno=m),y}let xS=/^\s*at (\S+?)(?::(\d+))(?::(\d+))\s*$/i,NS=/^\s*at (?:(.+?\)(?: \[.+\])?|.*?) ?\((?:address at )?)?(?:async )?((?:<anonymous>|[-a-z]+:|.*bundle|\/)?.*?)(?::(\d+))?(?::(\d+))?\)?\s*$/i,FS=/\((\S*)(?::(\d+))(?::(\d+))\)/,US=/^\s*(.*?)(?:\((.*?)\))?(?:^|@)?((?:[-a-z]+)?:\/.*?|\[native code\]|[^@]*(?:bundle|\d+\.js)|\/[\w\-. /=]+)(?::(\d+))?(?::(\d+))?\s*$/i,jS=/(\S+) line (\d+)(?: > eval line \d+)* > eval/i,BS=(function(...u){let c=u.sort(((h,m)=>h[0]-m[0])).map((h=>h[1]));
16return(h,m=0,y=0)=>{let k=[],S=h.split(` 17`);for(let C=m;C<S.length;C++){let E=S[C];if(E.length>1024)continue;let O=Rh.test(E)?E.replace(Rh,"$1"):E;if(!O.match(/\S*Error: /)){for(let F of c){let V=F(O);if(V){k.push(V);break}}if(k.length>=50+y)break}}return(function(C){if(!C.length)return[];let E=Array.from(C);return/sentryWrapped/.test(zs(E).function||"")&&E.pop(),E.reverse(),Ih.test(zs(E).function||"")&&(E.pop(),Ih.test(zs(E).function||"")&&E.pop()),E.slice(0,50).map((O=>({...O,filename:O.filename||zs(E).filename,function:O.function||ui})))})(k.slice(y))}})([30,u=>{let c=xS.exec(u);if(c){let[,m,y,k]=c;return Nc(m,ui,+y,+k)}let h=NS.exec(u);if(h){if(h[2]&&h[2].indexOf("eval")===0){let k=FS.exec(h[2]);k&&(h[2]=k[1],h[3]=k[2],h[4]=k[3])}let[m,y]=bp(h[1]||ui,h[2]);return Nc(y,m,h[3]?+h[3]:void 0,h[4]?+h[4]:void 0)}}],[50,u=>{let c=US.exec(u);if(c){if(c[3]&&c[3].indexOf(" > eval")>-1){let y=jS.exec(c[3]);y&&(c[1]=c[1]||"eval",c[3]=y[1],c[4]=y[2],c[5]="")}let h=c[3],m=c[1]||ui;return[m,h]=bp(m,h),Nc(h,m,c[4]?+c[4]:void 0,c[5]?+c[5]:void 0)}}]),bp=(u,c)=>{let h=u.indexOf("safari-extension")!==-1,m=u.indexOf("safari-web-extension")!==-1;return h||m?[u.indexOf("@")!==-1?u.split("@")[0]:ui,h?`safari-extension:${c}`:`safari-web-extension:${c}`]:[u,c]};var Fc="new",kp="loading",Sp="loaded",so="joining-meeting",Vn="joined-meeting",_n="left-meeting",Cn="error",qS="blocked",VS="off",$S="sendable",WS="loading",GS="interrupted",Tp="playable",oo="unknown",_p="full",JS="lobby",HS="none",Cp="base",wp="*",KS="ejected",zS="nbf-room",YS="nbf-token",QS="exp-room",XS="exp-token",Uc="no-room",ZS="meeting-full",Ep="end-of-life",eT="not-allowed",Pp="connection-error",tT="cam-in-use",nT="mic-in-use",iT="cam-mic-in-use",rT="permissions",sT="undefined-mediadevices",oT="not-found",aT="constraints",cT="unknown",Ap="iframe-ready-for-launch-config",Mp="iframe-launch-config",Rp="theme-updated",Ip="loading",Op="load-attempt-failed",jc="loaded",Dp="started-camera",Lp="camera-error",xp="joining-meeting",Np="joined-meeting",Fp="left-meeting",Up="participant-joined",jp="participant-updated",Bp="participant-left",qp="participant-counts-updated",Vp="access-state-updated",$p="meeting-session-summary-updated",Wp="meeting-session-state-updated",lT="meeting-session-data-error",Gp="waiting-participant-added",Jp="waiting-participant-updated",Hp="waiting-participant-removed",Kp="track-started",zp="track-stopped",Yp="transcription-started",Qp="transcription-stopped",Xp="transcription-error",Bc="recording-started",qc="recording-stopped",Zp="recording-stats",ef="recording-error",tf="recording-upload-completed",nf="recording-data",rf="app-message",sf="transcription-message",of="remote-media-player-started",af="remote-media-player-updated",cf="remote-media-player-stopped",lf="local-screen-share-started",uf="local-screen-share-stopped",df="local-screen-share-canceled",hf="active-speaker-change",pf="active-speaker-mode-change",ff="network-quality-change",mf="network-connection",gf="cpu-load-change",vf="face-counts-updated",Gr="fullscreen",Jr="exited-fullscreen",yf="live-streaming-started",bf="live-streaming-updated",kf="live-streaming-stopped",Sf="live-streaming-error",Tf="lang-updated",_f="receive-settings-updated",Vc="input-settings-updated",$c="nonfatal-error",Wc="error",Gc=4096,Cf=102400,Jc="iframe-call-message",wf="local-screen-start",Ef="daily-method-update-live-streaming-endpoints",ao="transmit-log",wn="daily-custom-track",co={NONE:"none",BGBLUR:"background-blur",BGIMAGE:"background-image",FACE_DETECTION:"face-detection"},Pf={NONE:"none",NOISE_CANCELLATION:"noise-cancellation"},Hc={PLAY:"play",PAUSE:"pause"},Kc=["jpg","png","jpeg"],Af="sip-call-transfer";function Dt(){return!Ae()&&typeof window<"u"&&window.navigator&&window.navigator.userAgent?window.navigator.userAgent:""}function Ae(){return typeof navigator<"u"&&navigator.product&&navigator.product==="ReactNative"}function Mf(){return navigator&&navigator.mediaDevices&&navigator.mediaDevices.getUserMedia}function Rf(){if(Ae()||!document)return!1;var u=document.createElement("iframe");return!!u.requestFullscreen||!!u.webkitRequestFullscreen}var zc="none",uT=(function(){try{var u,c=document.createElement("canvas"),h=!1;(u=c.getContext("webgl2",{failIfMajorPerformanceCaveat:!0}))||(h=!0,u=c.getContext("webgl2"));var m=u!=null;
17return c.remove(),m?h?"software":"hardware":zc}catch{return zc}})();function If(){var u=arguments.length>0&&arguments[0]!==void 0&&arguments[0];return!Ae()&&uT!==zc&&(u?!Lf()&&["Chrome","Firefox"].includes($n()):(function(){if(Lf())return!1;var c=$n();if(c==="Safari"){var h=Xc();if(h.major<15||h.major===15&&h.minor<4)return!1}return c==="Chrome"?Qc().major>=77:c==="Firefox"?Zc().major>=97:["Chrome","Firefox","Safari"].includes(c)})())}function Of(){if(Ae()||Df()||typeof AudioWorkletNode>"u")return!1;switch($n()){case"Chrome":case"Firefox":return!0;case"Safari":var u=lo();return u.major>17||u.major===17&&u.minor>=4}return!1}function Yc(){return Mf()&&typeof MediaStreamTrack<"u"&&!(function(){var u,c=$n();if(!Dt())return!0;switch(c){case"Chrome":return(u=Qc()).major&&u.major>0&&u.major<75;case"Firefox":return(u=Zc()).major<91;case"Safari":return(u=Xc()).major<13||u.major===13&&u.minor<1;default:return!0}})()}function Df(){return Dt().match(/Linux; Android/)}function Lf(){var u,c=Dt(),h=c.match(/Mac/)&&(!Ae()&&typeof window<"u"&&(u=window)!==null&&u!==void 0&&(u=u.navigator)!==null&&u!==void 0&&u.maxTouchPoints?window.navigator.maxTouchPoints:0)>=5;return!!(c.match(/Mobi/)||c.match(/Android/)||h)||!!Dt().match(/DailyAnd\//)||void 0}function $n(){if(typeof window<"u"){var u=Dt();return xf()?"Safari":u.indexOf("Edge")>-1?"Edge":u.match(/Chrome\//)?"Chrome":u.indexOf("Safari")>-1||Nf()?"Safari":u.indexOf("Firefox")>-1?"Firefox":u.indexOf("MSIE")>-1||u.indexOf(".NET")>-1?"IE":"Unknown Browser"}}function lo(){switch($n()){case"Chrome":return Qc();case"Safari":return Xc();case"Firefox":return Zc();case"Edge":return(function(){var u=0,c=0;if(typeof window<"u"){var h=Dt().match(/Edge\/(\d+).(\d+)/);if(h)try{u=parseInt(h[1]),c=parseInt(h[2])}catch{}}return{major:u,minor:c}})()}}function Qc(){var u=0,c=0,h=0,m=0,y=!1;if(typeof window<"u"){var k=Dt(),S=k.match(/Chrome\/(\d+).(\d+).(\d+).(\d+)/);if(S)try{u=parseInt(S[1]),c=parseInt(S[2]),h=parseInt(S[3]),m=parseInt(S[4]),y=k.indexOf("OPR/")>-1}catch{}}return{major:u,minor:c,build:h,patch:m,opera:y}}function xf(){return!!Dt().match(/iPad|iPhone|iPod/i)&&Mf()}function Nf(){return Dt().indexOf("AppleWebKit/605.1.15")>-1}function Xc(){var u=0,c=0,h=0;if(typeof window<"u"){var m=Dt().match(/Version\/(\d+).(\d+)(.(\d+))?/);if(m)try{u=parseInt(m[1]),c=parseInt(m[2]),h=parseInt(m[4])}catch{}else(xf()||Nf())&&(u=14,c=0,h=3)}return{major:u,minor:c,point:h}}function Zc(){var u=0,c=0;if(typeof window<"u"){var h=Dt().match(/Firefox\/(\d+).(\d+)/);if(h)try{u=parseInt(h[1]),c=parseInt(h[2])}catch{}}return{major:u,minor:c}}var Ff=(function(){return p((function u(){a(this,u)}),[{key:"addListenerForMessagesFromCallMachine",value:function(u,c,h){ke()}},{key:"addListenerForMessagesFromDailyJs",value:function(u,c,h){ke()}},{key:"sendMessageToCallMachine",value:function(u,c,h,m){ke()}},{key:"sendMessageToDailyJs",value:function(u,c){ke()}},{key:"removeListener",value:function(u){ke()}}])})();function Uf(u,c){var h=Object.keys(u);if(Object.getOwnPropertySymbols){var m=Object.getOwnPropertySymbols(u);c&&(m=m.filter((function(y){return Object.getOwnPropertyDescriptor(u,y).enumerable}))),h.push.apply(h,m)}return h}function el(u){for(var c=1;c<arguments.length;c++){var h=arguments[c]!=null?arguments[c]:{};c%2?Uf(Object(h),!0).forEach((function(m){I(u,m,h[m])})):Object.getOwnPropertyDescriptors?Object.defineProperties(u,Object.getOwnPropertyDescriptors(h)):Uf(Object(h)).forEach((function(m){Object.defineProperty(u,m,Object.getOwnPropertyDescriptor(h,m))}))}return u}function jf(){try{var u=!Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],(function(){})))}catch{}return(jf=function(){return!!u})()}var dT=(function(u){function c(){var h,m,y,k;return a(this,c),m=this,y=b(y=c),(h=g(m,jf()?Reflect.construct(y,[],b(m).constructor):y.apply(m,k)))._wrappedListeners={},h._messageCallbacks={},h}return w(c,u),p(c,[{key:"addListenerForMessagesFromCallMachine",value:function(h,m,y){var k=this,S=function(C){if(C.data&&C.data.what==="iframe-call-message"&&(!C.data.callClientId||C.data.callClientId===m)&&(!C.data.from||C.data.from!=="module")){var E=el({},C.data);if(delete E.from,E.callbackStamp&&k._messageCallbacks[E.callbackStamp]){var O=E.callbackStamp;k._messageCallbacks[O].call(y,E),delete k._messageCallbacks[O]}delete E.what,delete E.callbackStamp,h.call(y,E)}};this._wrappedListeners[h]=S,window.addEventListener("message",S)}},{key:"addListenerForMessagesFromDailyJs",value:function(h,m,y){var k=function(S){var C;if(!(!S.data||S.data.what!==Jc||!S.data.action||S.data.from&&S.data.from!=="module"||S.data.callClientId&&m&&S.data.callClientId!==m||S!=null&&(C=S.data)!==null&&C!==void 0&&C.callFrameId)){var E=S.data;h.call(y,E)}};this._wrappedListeners[h]=k,window.addEventListener("message",k)}},{key:"sendMessageToCallMachine",value:function(h,m,y,k){if(!y)throw new Error("undefined callClientId. Are you trying to use a DailyCall instance previously destroyed?");var S=el({},h);if(S.what=Jc,S.from="module",S.callClientId=y,m){var C=ge();this._messageCallbacks[C]=m,S.callbackStamp=C}
17var E=k?k.contentWindow:window,O=this._callMachineTargetOrigin(k);O&&E.postMessage(S,O)}},{key:"sendMessageToDailyJs",value:function(h,m){h.what=Jc,h.callClientId=m,h.from="embedded",window.postMessage(h,this._targetOriginFromWindowLocation())}},{key:"removeListener",value:function(h){var m=this._wrappedListeners[h];m&&(window.removeEventListener("message",m),delete this._wrappedListeners[h])}},{key:"forwardPackagedMessageToCallMachine",value:function(h,m,y){var k=el({},h);k.callClientId=y;var S=m?m.contentWindow:window,C=this._callMachineTargetOrigin(m);C&&S.postMessage(k,C)}},{key:"addListenerForPackagedMessagesFromCallMachine",value:function(h,m){var y=function(k){if(k.data&&k.data.what==="iframe-call-message"&&(!k.data.callClientId||k.data.callClientId===m)&&(!k.data.from||k.data.from!=="module")){var S=k.data;h(S)}};return this._wrappedListeners[h]=y,window.addEventListener("message",y),h}},{key:"removeListenerForPackagedMessagesFromCallMachine",value:function(h){var m=this._wrappedListeners[h];m&&(window.removeEventListener("message",m),delete this._wrappedListeners[h])}},{key:"_callMachineTargetOrigin",value:function(h){return h?h.src?new URL(h.src).origin:void 0:this._targetOriginFromWindowLocation()}},{key:"_targetOriginFromWindowLocation",value:function(){return window.location.protocol==="file:"?"*":window.location.origin}}])})(Ff);function Bf(u,c){var h=Object.keys(u);if(Object.getOwnPropertySymbols){var m=Object.getOwnPropertySymbols(u);c&&(m=m.filter((function(y){return Object.getOwnPropertyDescriptor(u,y).enumerable}))),h.push.apply(h,m)}return h}function qf(){try{var u=!Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],(function(){})))}catch{}return(qf=function(){return!!u})()}var hT=(function(u){function c(){var h,m,y,k;return a(this,c),m=this,y=b(y=c),h=g(m,qf()?Reflect.construct(y,[],b(m).constructor):y.apply(m,k)),window.callMachineToDailyJsEmitter=window.callMachineToDailyJsEmitter||new P.EventEmitter,window.dailyJsToCallMachineEmitter=window.dailyJsToCallMachineEmitter||new P.EventEmitter,h._wrappedListeners={},h._messageCallbacks={},h}return w(c,u),p(c,[{key:"addListenerForMessagesFromCallMachine",value:function(h,m,y){this._addListener(h,window.callMachineToDailyJsEmitter,m,y,"received call machine message")}},{key:"addListenerForMessagesFromDailyJs",value:function(h,m,y){this._addListener(h,window.dailyJsToCallMachineEmitter,m,y,"received daily-js message")}},{key:"sendMessageToCallMachine",value:function(h,m,y){this._sendMessage(h,window.dailyJsToCallMachineEmitter,y,m,"sending message to call machine")}},{key:"sendMessageToDailyJs",value:function(h,m){this._sendMessage(h,window.callMachineToDailyJsEmitter,m,null,"sending message to daily-js")}},{key:"removeListener",value:function(h){var m=this._wrappedListeners[h];m&&(window.callMachineToDailyJsEmitter.removeListener("message",m),window.dailyJsToCallMachineEmitter.removeListener("message",m),delete this._wrappedListeners[h])}},{key:"_addListener",value:function(h,m,y,k,S){var C=this,E=function(O){if(O.callClientId===y){if(O.callbackStamp&&C._messageCallbacks[O.callbackStamp]){var F=O.callbackStamp;C._messageCallbacks[F].call(k,O),delete C._messageCallbacks[F]}h.call(k,O)}};this._wrappedListeners[h]=E,m.addListener("message",E)}},{key:"_sendMessage",value:function(h,m,y,k,S){var C=(function(O){for(var F=1;F<arguments.length;F++){var V=arguments[F]!=null?arguments[F]:{};F%2?Bf(Object(V),!0).forEach((function(G){I(O,G,V[G])})):Object.getOwnPropertyDescriptors?Object.defineProperties(O,Object.getOwnPropertyDescriptors(V)):Bf(Object(V)).forEach((function(G){Object.defineProperty(O,G,Object.getOwnPropertyDescriptor(V,G))}))}return O})({},h);if(C.callClientId=y,k){var E=ge();this._messageCallbacks[E]=k,C.callbackStamp=E}m.emit("message",C)}}])})(Ff),tl="replace",nl="shallow-merge",Vf=[tl,nl],pT=(function(){function u(){var c=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{},h=c.data,m=c.mergeStrategy,y=m===void 0?tl:m;a(this,u),u._validateMergeStrategy(y),u._validateData(h,y),this.mergeStrategy=y,this.data=h}return p(u,[{key:"isNoOp",value:function(){return u.isNoOpUpdate(this.data,this.mergeStrategy)}}],[{key:"isNoOpUpdate",value:function(c,h){return Object.keys(c).length===0&&h===nl}},{key:"_validateMergeStrategy",value:function(c){if(!Vf.includes(c))throw Error("Unrecognized mergeStrategy provided. Options are: [".concat(Vf,"]"))}},{key:"_validateData",value:function(c,h){if(!(function(C){if(C==null||d(C)!=="object")return!1;var E=Object.getPrototypeOf(C);return E==null||E===Object.prototype})(c))throw Error("Meeting session data must be a plain (map-like) object");var m;try{if(m=JSON.stringify(c),h===tl){var y=JSON.parse(m);ie(y,c)||console.warn("The meeting session data provided will be modified when serialized.",
17y,c)}else if(h===nl){for(var k in c)if(Object.hasOwnProperty.call(c,k)&&c[k]!==void 0){var S=JSON.parse(JSON.stringify(c[k]));ie(c[k],S)||console.warn("At least one key in the meeting session data provided will be modified when serialized.",S,c[k])}}}catch(C){throw Error("Meeting session data must be serializable to JSON: ".concat(C))}if(m.length>Cf)throw Error("Meeting session data is too large (".concat(m.length," characters). Maximum size suppported is ").concat(Cf,"."))}}])})();function $f(){try{var u=!Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],(function(){})))}catch{}return($f=function(){return!!u})()}function il(u){var c=typeof Map=="function"?new Map:void 0;return il=function(h){if(h===null||!(function(y){try{return Function.toString.call(y).indexOf("[native code]")!==-1}catch{return typeof y=="function"}})(h))return h;if(typeof h!="function")throw new TypeError("Super expression must either be null or a function");if(c!==void 0){if(c.has(h))return c.get(h);c.set(h,m)}function m(){return(function(y,k,S){if($f())return Reflect.construct.apply(null,arguments);var C=[null];C.push.apply(C,k);var E=new(y.bind.apply(y,C));return S&&R(E,S.prototype),E})(h,arguments,b(this).constructor)}return m.prototype=Object.create(h.prototype,{constructor:{value:m,enumerable:!1,writable:!0,configurable:!0}}),R(m,h)},il(u)}function Wf(){try{var u=!Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],(function(){})))}catch{}return(Wf=function(){return!!u})()}function Gf(u){var c,h=(c=window._daily)===null||c===void 0?void 0:c.pendings;if(h){var m=h.indexOf(u);m!==-1&&h.splice(m,1)}}var fT=(function(){return p((function u(c){a(this,u),this._currentLoad=null,this._callClientId=c}),[{key:"load",value:function(){var u,c=this,h=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{},m=arguments.length>1?arguments[1]:void 0,y=arguments.length>2?arguments[2]:void 0;if(this.loaded)return window._daily.instances[this._callClientId].callMachine.reset(),void m(!0);u=this._callClientId,window._daily.pendings.push(u),this._currentLoad&&this._currentLoad.cancel(),this._currentLoad=new mT(h,(function(){m(!1)}),(function(k,S){S||Gf(c._callClientId),y(k,S)})),this._currentLoad.start()}},{key:"cancel",value:function(){this._currentLoad&&this._currentLoad.cancel(),Gf(this._callClientId)}},{key:"loaded",get:function(){return this._currentLoad&&this._currentLoad.succeeded}}])})(),mT=(function(){return p((function u(){var c=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{},h=arguments.length>1?arguments[1]:void 0,m=arguments.length>2?arguments[2]:void 0;a(this,u),this._attemptsRemaining=3,this._currentAttempt=null,this._dailyConfig=c,this._successCallback=h,this._failureCallback=m}),[{key:"start",value:function(){var u=this;if(!this._currentAttempt){var c=function(h){u._currentAttempt.cancelled||(u._attemptsRemaining--,u._failureCallback(h,u._attemptsRemaining>0),u._attemptsRemaining<=0||setTimeout((function(){u._currentAttempt.cancelled||(u._currentAttempt=new Jf(u._dailyConfig,u._successCallback,c),u._currentAttempt.start())}),3e3))};this._currentAttempt=new Jf(this._dailyConfig,this._successCallback,c),this._currentAttempt.start()}}},{key:"cancel",value:function(){this._currentAttempt&&this._currentAttempt.cancel()}},{key:"cancelled",get:function(){return this._currentAttempt&&this._currentAttempt.cancelled}},{key:"succeeded",get:function(){return this._currentAttempt&&this._currentAttempt.succeeded}}])})(),rl=(function(u){function c(){return a(this,c),h=this,y=arguments,m=b(m=c),g(h,Wf()?Reflect.construct(m,y||[],b(h).constructor):m.apply(h,y));var h,m,y}return w(c,u),p(c)})(il(Error)),uo=2e4,Jf=(function(){return p((function c(h,m,y){a(this,c),this._loadAttemptImpl=Ae()||!h.avoidEval?new gT(h,m,y):new vT(h,m,y)}),[{key:"start",value:(u=L((function*(){return this._loadAttemptImpl.start()})),function(){return u.apply(this,arguments)})},{key:"cancel",value:function(){this._loadAttemptImpl.cancel()}},{key:"cancelled",get:function(){return this._loadAttemptImpl.cancelled}},{key:"succeeded",get:function(){return this._loadAttemptImpl.succeeded}}]);var u})(),gT=(function(){return p((function y(k,S,C){a(this,y),this.cancelled=!1,this.succeeded=!1,this._networkTimedOut=!1,this._networkTimeout=null,this._iosCache=typeof iOSCallObjectBundleCache<"u"&&iOSCallObjectBundleCache,this._refetchHeaders=null,this._dailyConfig=k,this._successCallback=S,this._failureCallback=C}),[{key:"start",value:(m=L((function*(){var y=Je(this._dailyConfig);!(yield this._tryLoadFromIOSCache(y))&&this._loadFromNetwork(y)})),function(){return m.apply(this,arguments)})},{key:"cancel",value:function(){clearTimeout(this._networkTimeout),this.cancelled=!0}},{key:"_tryLoadFromIOSCache",value:(h=L((function*(y){if(!this._iosCache)return!1;try{var k=yield this._iosCache.get(y);return!!this.cancelled||!!k&&(k.code?(Function('"use strict";'+k.code)(),this.succeeded=!0,this._successCallback(),!0):(this._refetchHeaders=k.refetchHeaders,!1))}catch{return!1}}
17)),function(y){return h.apply(this,arguments)})},{key:"_loadFromNetwork",value:(c=L((function*(y){var k=this;this._networkTimeout=setTimeout((function(){k._networkTimedOut=!0,k._failureCallback({msg:"Timed out (>".concat(uo," ms) when loading call object bundle ").concat(y),type:"timeout"})}),uo);try{var S=this._refetchHeaders?{headers:this._refetchHeaders}:{},C=yield fetch(y,S);if(clearTimeout(this._networkTimeout),this.cancelled||this._networkTimedOut)throw new rl;var E=yield this._getBundleCodeFromResponse(y,C);if(this.cancelled)throw new rl;Function('"use strict";'+E)(),this._iosCache&&this._iosCache.set(y,E,C.headers),this.succeeded=!0,this._successCallback()}catch(O){if(clearTimeout(this._networkTimeout),O instanceof rl||this.cancelled||this._networkTimedOut)return;this._failureCallback({msg:"Failed to load call object bundle ".concat(y,": ").concat(O),type:O.message})}})),function(y){return c.apply(this,arguments)})},{key:"_getBundleCodeFromResponse",value:(u=L((function*(y,k){if(k.ok)return yield k.text();if(this._iosCache&&k.status===304)return(yield this._iosCache.renew(y,k.headers)).code;throw new Error("Received ".concat(k.status," response"))})),function(y,k){return u.apply(this,arguments)})}]);var u,c,h,m})(),vT=(function(){return p((function u(c,h,m){a(this,u),this.cancelled=!1,this.succeeded=!1,this._dailyConfig=c,this._successCallback=h,this._failureCallback=m,this._attemptId=ge(),this._networkTimeout=null,this._scriptElement=null}),[{key:"start",value:function(){window._dailyCallMachineLoadWaitlist||(window._dailyCallMachineLoadWaitlist=new Set);var u=Je(this._dailyConfig);(typeof document>"u"?"undefined":d(document))==="object"?this._startLoading(u):this._failureCallback({msg:"Call object bundle must be loaded in a DOM/web context",type:"missing context"})}},{key:"cancel",value:function(){this._stopLoading(),this.cancelled=!0}},{key:"_startLoading",value:function(u){var c=this;this._signUpForCallMachineLoadWaitlist(),this._networkTimeout=setTimeout((function(){c._stopLoading(),c._failureCallback({msg:"Timed out (>".concat(uo," ms) when loading call object bundle ").concat(u),type:"timeout"})}),uo);var h=document.getElementsByTagName("head")[0],m=document.createElement("script");this._scriptElement=m,m.onload=function(){c._stopLoading(),c.succeeded=!0,c._successCallback()},m.onerror=function(y){c._stopLoading(),c._failureCallback({msg:"Failed to load call object bundle ".concat(y.target.src),type:y.message})},m.src=u,h.appendChild(m)}},{key:"_stopLoading",value:function(){this._withdrawFromCallMachineLoadWaitlist(),clearTimeout(this._networkTimeout),this._scriptElement&&(this._scriptElement.onload=null,this._scriptElement.onerror=null)}},{key:"_signUpForCallMachineLoadWaitlist",value:function(){window._dailyCallMachineLoadWaitlist.add(this._attemptId)}},{key:"_withdrawFromCallMachineLoadWaitlist",value:function(){window._dailyCallMachineLoadWaitlist.delete(this._attemptId)}}])})(),ho=function(u,c,h){return bT(u.local,c,h)===!0},yT=function(u,c,h){return u.local.streams&&u.local.streams[c]&&u.local.streams[c].stream&&u.local.streams[c].stream["get".concat(h==="video"?"Video":"Audio","Tracks")]()[0]},Zi=function(u,c,h,m){var y=kT(u,c,h,m);return y&&y.pendingTrack},bT=function(u,c,h){if(!u)return!1;var m=function(k){switch(k){case"avatar":return!0;case"staged":return k;default:return!!k}},y=u.public.subscribedTracks;return y&&y[c]?["cam-audio","cam-video","screen-video","screen-audio","rmpAudio","rmpVideo"].indexOf(h)===-1&&y[c].custom?[!0,"staged"].includes(y[c].custom)?m(y[c].custom):m(y[c].custom[h]):m(y[c][h]):!y||m(y.ALL)},kT=function(u,c,h,m){var y=Object.values(u.streams||{}).filter((function(k){return k.participantId===c&&k.type===h&&k.pendingTrack&&k.pendingTrack.kind===m})).sort((function(k,S){return new Date(S.starttime)-new Date(k.starttime)}));return y&&y[0]},ST=function(u,c){var h=u.local.public.customTracks;if(h&&h[c])return h[c].track};function Hf(u,c){for(var h=c.getState(),m=0,y=["cam","screen"];m<y.length;m++)for(var k=y[m],S=0,C=["video","audio"];S<C.length;S++){var E=C[S],O=k==="cam"?E:"screen".concat(E.charAt(0).toUpperCase()+E.slice(1)),F=u.tracks[O];if(F){var V=u.local?yT(h,k,E):Zi(h,u.session_id,k,E);F.state==="playable"&&(F.track=V),F.persistentTrack=V}}}function Kf(u,c){try{var h=c.getState();for(var m in u.tracks)if(!TT(m)){var y=u.tracks[m].kind;if(y){var k=u.tracks[m];if(k){var S=u.local?ST(h,m):Zi(h,u.session_id,m,y);k.state==="playable"&&(u.tracks[m].track=S),k.persistentTrack=S}}else console.error("unknown type for custom track")}}catch(C){console.error(C)}}function TT(u){return["video","audio","screenVideo","screenAudio"].includes(u)}function zf(u,c,h){var m=h.getState();if(u.local){if(u.audio)try{u.audioTrack=m.local.streams.cam.stream.getAudioTracks()[0],u.audioTrack||(u.audio=!1)}catch{}if(u.video)try{u.videoTrack=m.local.streams.cam.stream.getVideoTracks()[0],u.videoTrack||(u.video=!1)}catch{}if(u.screen)try{u.screenVideoTrack=m.local.streams.screen.stream.getVideoTracks()[0],u.screenAudioTrack=m.local.streams.screen.stream.getAudioTracks()[0],u.screenVideoTrack||u.screenAudioTrack||(u.screen=!1)}catch{}}else{var y=!0;try{var k=m.participants[u.session_id];k&&k.public&&k.public.rtcType&&k.public.rtcType.impl==="peer-to-peer"&&k.private&&!["connected","completed"].includes(k.private.peeringState)&&(y=!1)}catch(F){console.error(F)}if(!y)return u.audio=!1,u.audioTrack=!1,u.video=!1,u.videoTrack=!1,u.screen=!1,void(u.screenTrack=!1);try{if(m.streams,u.audio&&ho(m,u.session_id,"cam-audio")){var S=Zi(m,u.session_id,"cam","audio");S&&(c&&c.audioTrack&&c.audioTrack.id===S.id?u.audioTrack=S:S.muted||(u.audioTrack=S)),u.audioTrack||(u.audio=!1)}if(u.video&&ho(m,u.session_id,"cam-video")){var C=Zi(m,u.session_id,"cam","video");C&&(c&&c.videoTrack&&c.videoTrack.id===C.id?u.videoTrack=C:C.muted||(u.videoTrack=C)),u.videoTrack||(u.video=!1)}if(u.screen&&ho(m,u.session_id,"screen-audio")){var E=Zi(m,u.session_id,"screen","audio");E&&(c&&c.screenAudioTrack&&c.screenAudioTrack.id===E.id?u.screenAudioTrack=E:E.muted||(u.screenAudioTrack=E))}if(u.screen&&ho(m,u.session_id,"screen-video")){var O=Zi(m,u.session_id,"screen","video");
17O&&(c&&c.screenVideoTrack&&c.screenVideoTrack.id===O.id?u.screenVideoTrack=O:O.muted||(u.screenVideoTrack=O))}u.screenVideoTrack||u.screenAudioTrack||(u.screen=!1)}catch(F){console.error("unexpected error matching up tracks",F)}}}function Yf(u,c){(c==null||c>u.length)&&(c=u.length);for(var h=0,m=Array(c);h<c;h++)m[h]=u[h];return m}var nn=new Map,er=null;function Qf(u,c){(c==null||c>u.length)&&(c=u.length);for(var h=0,m=Array(c);h<c;h++)m[h]=u[h];return m}var rn=new Map,Hr=null;function _T(u){Xf()?(function(c){nn.has(c)||(nn.set(c,{}),navigator.mediaDevices.enumerateDevices().then((function(h){nn.has(c)&&(nn.get(c).lastDevicesString=JSON.stringify(h),er||(er=(function(){var m=L((function*(){var y,k=yield navigator.mediaDevices.enumerateDevices(),S=(function(O,F){var V=typeof Symbol<"u"&&O[Symbol.iterator]||O["@@iterator"];if(!V){if(Array.isArray(O)||(V=(function(oe,ue){if(oe){if(typeof oe=="string")return Yf(oe,ue);var me={}.toString.call(oe).slice(8,-1);return me==="Object"&&oe.constructor&&(me=oe.constructor.name),me==="Map"||me==="Set"?Array.from(oe):me==="Arguments"||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(me)?Yf(oe,ue):void 0}})(O))||F&&O&&typeof O.length=="number"){V&&(O=V);var G=0,Q=function(){};return{s:Q,n:function(){return G>=O.length?{done:!0}:{done:!1,value:O[G++]}},e:function(oe){throw oe},f:Q}}throw new TypeError(`Invalid attempt to iterate non-iterable instance. 18In order to be iterable, non-array objects must have a [Symbol.iterator]() method.`)}var W,z=!0,ne=!1;return{s:function(){V=V.call(O)},n:function(){var oe=V.next();return z=oe.done,oe},e:function(oe){ne=!0,W=oe},f:function(){try{z||V.return==null||V.return()}finally{if(ne)throw W}}}})(nn.keys());try{for(S.s();!(y=S.n()).done;){var C=y.value,E=JSON.stringify(k);E!==nn.get(C).lastDevicesString&&(nn.get(C).lastDevicesString=E,C(k))}}catch(O){S.e(O)}finally{S.f()}}));return function(){return m.apply(this,arguments)}})(),navigator.mediaDevices.addEventListener("devicechange",er)))})).catch((function(){})))})(u):(function(c){rn.has(c)||(rn.set(c,{}),navigator.mediaDevices.enumerateDevices().then((function(h){rn.has(c)&&(rn.get(c).lastDevicesString=JSON.stringify(h),Hr||(Hr=setInterval(L((function*(){var m,y=yield navigator.mediaDevices.enumerateDevices(),k=(function(E,O){var F=typeof Symbol<"u"&&E[Symbol.iterator]||E["@@iterator"];if(!F){if(Array.isArray(E)||(F=(function(ne,oe){if(ne){if(typeof ne=="string")return Qf(ne,oe);var ue={}.toString.call(ne).slice(8,-1);return ue==="Object"&&ne.constructor&&(ue=ne.constructor.name),ue==="Map"||ue==="Set"?Array.from(ne):ue==="Arguments"||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(ue)?Qf(ne,oe):void 0}})(E))||O&&E&&typeof E.length=="number"){F&&(E=F);var V=0,G=function(){};return{s:G,n:function(){return V>=E.length?{done:!0}:{done:!1,value:E[V++]}},e:function(ne){throw ne},f:G}}throw new TypeError(`Invalid attempt to iterate non-iterable instance. 19In order to be iterable, non-array objects must have a [Symbol.iterator]() method.`)}var Q,W=!0,z=!1;return{s:function(){F=F.call(E)},n:function(){var ne=F.next();return W=ne.done,ne},e:function(ne){z=!0,Q=ne},f:function(){try{W||F.return==null||F.return()}finally{if(z)throw Q}}}})(rn.keys());try{for(k.s();!(m=k.n()).done;){var S=m.value,C=JSON.stringify(y);C!==rn.get(S).lastDevicesString&&(rn.get(S).lastDevicesString=C,S(y))}}catch(E){k.e(E)}finally{k.f()}})),3e3)))})))})(u)}function Xf(){var u;return Ae()||((u=navigator.mediaDevices)===null||u===void 0?void 0:u.ondevicechange)!==void 0}var CT=new Set;function Zf(u,c){var h=Object.keys(u);if(Object.getOwnPropertySymbols){var m=Object.getOwnPropertySymbols(u);c&&(m=m.filter((function(y){return Object.getOwnPropertyDescriptor(u,y).enumerable}))),h.push.apply(h,m)}return h}function Wn(u){for(var c=1;c<arguments.length;c++){var h=arguments[c]!=null?arguments[c]:{};c%2?Zf(Object(h),!0).forEach((function(m){I(u,m,h[m])})):Object.getOwnPropertyDescriptors?Object.defineProperties(u,Object.getOwnPropertyDescriptors(h)):Zf(Object(h)).forEach((function(m){Object.defineProperty(u,m,Object.getOwnPropertyDescriptor(h,m))}))}return u}var Kr=Object.freeze({VIDEO:"video",AUDIO:"audio",SCREEN_VIDEO:"screenVideo",SCREEN_AUDIO:"screenAudio",CUSTOM_VIDEO:"customVideo",CUSTOM_AUDIO:"customAudio"}),wT=Object.freeze({PARTICIPANTS:"participants",STREAMING:"streaming",TRANSCRIPTION:"transcription"}),zr=Object.values(Kr),em=["v","a","sv","sa","cv","ca"],ET=(Object.freeze(zr.reduce((function(u,c,h){return u[c]=em[h],u}),{})),Object.freeze(em.reduce((function(u,c,h){return u[c]=zr[h],u}),{})),[Kr.VIDEO,Kr.AUDIO,Kr.SCREEN_VIDEO,Kr.SCREEN_AUDIO]),tm=Object.values(wT),nm=["p","s","t"],im=(Object.freeze(tm.reduce((function(u,c,h){return u[c]=nm[h],u}),{})),Object.freeze(nm.reduce((function(u,c,h){return u[c]=tm[h],u}),{})),(function(){function u(){var c=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{},h=c.base,m=c.byUserId,y=c.byParticipantId;a(this,u),this.base=h,this.byUserId=m,this.byParticipantId=y}return p(u,[{key:"clone",value:function(){var c=new u;if(this.base instanceof at?c.base=this.base.clone():c.base=this.base,this.byUserId!==void 0)for(var h in c.byUserId={},this.byUserId){var m=this.byUserId[h];c.byUserId[h]=m instanceof at?m.clone():m}if(this.byParticipantId!==void 0)for(var y in c.byParticipantId={},this.byParticipantId){var k=this.byParticipantId[y];c.byParticipantId[y]=k instanceof at?k.clone():k}return c}},{key:"toJSONObject",value:function(){var c={};if(typeof this.base=="boolean"?c.base=this.base:this.base instanceof at&&(c.base=this.base.toJSONObject()),this.byUserId!==void 0)for(var h in c.byUserId={},this.byUserId){var m=this.byUserId[h];c.byUserId[h]=m instanceof at?m.toJSONObject():m}if(this.byParticipantId!==void 0)for(var y in c.byParticipantId={},this.byParticipantId){var k=this.byParticipantId[y];c.byParticipantId[y]=k instanceof at?k.toJSONObject():k}return c}},{key:"toMinifiedJSONObject",value:function(){var c={};if(this.base!==void 0&&(typeof this.base=="boolean"?c.b=this.base:c.b=this.base.toMinifiedJSONObject()),this.byUserId!==void 0)for(var h in c.u={},this.byUserId){var m=this.byUserId[h];c.u[h]=typeof m=="boolean"?m:m.toMinifiedJSONObject()}if(this.byParticipantId!==void 0)for(var y in c.p={},this.byParticipantId){var k=this.byParticipantId[y];c.p[y]=typeof k=="boolean"?k:k.toMinifiedJSONObject()}return c}},{key:"normalize",value:function(){return this.base instanceof at&&(this.base=this.base.normalize()),this.byUserId&&(this.byUserId=Object.fromEntries(Object.entries(this.byUserId).map((function(c){var h=M(c,2),m=h[0],y=h[1];return[m,y instanceof at?y.normalize():y]})))),this.byParticipantId&&(this.byParticipantId=Object.fromEntries(Object.entries(this.byParticipantId).map((function(c){var h=M(c,2),m=h[0],y=h[1];return[m,y instanceof at?y.normalize():y]})))),this}}],[{key:"fromJSONObject",value:function(c){var h,m,y;if(c.base!==void 0&&(h=typeof c.base=="boolean"?c.base:at.fromJSONObject(c.base)),c.byUserId!==void 0)for(var k in m={},c.byUserId){var S=c.byUserId[k];m[k]=typeof S=="boolean"?S:at.fromJSONObject(S)}if(c.byParticipantId!==void 0)for(var C in y={},c.byParticipantId){var E=c.byParticipantId[C];y[C]=typeof E=="boolean"?E:at.fromJSONObject(E)}return new u({base:h,byUserId:m,byParticipantId:y})}},{key:"fromMinifiedJSONObject",value:function(c){var h,m,y;if(c.b!==void 0&&(h=typeof c.b=="boolean"?c.b:at.fromMinifiedJSONObject(c.b)),c.u!==void 0)for(var k in m={},c.u){var S=c.u[k];m[k]=typeof S=="boolean"?S:at.fromMinifiedJSONObject(S)}if(c.p!==void 0)for(var C in y={},c.p){var E=c.p[C];y[C]=typeof E=="boolean"?E:at.fromMinifiedJSONObject(E)}return new u({base:h,byUserId:m,byParticipantId:y})}},{key:"validateJSONObject",value:function(c){if(d(c)!=="object")return[!1,"canReceive must be an object"];for(var h=["base","byUserId","byParticipantId"],m=0,y=Object.keys(c);m<y.length;m++){var k=y[m];if(!h.includes(k))return[!1,"canReceive can only contain keys (".concat(h.join(", "),")")];if(k==="base"){var S=M(at.validateJSONObject(c.base,!0),2),C=S[0],E=S[1];if(!C)return[!1,E]}else{if(d(c[k])!=="object")return[!1,"invalid (non-object) value for field '".concat(k,"' in canReceive")];for(var O=0,F=Object.values(c[k]);O<F.length;O++){var V=F[O],G=M(at.validateJSONObject(V),2),Q=G[0],W=G[1];if(!Q)return[!1,W]}}}return[!0]}}])})()),at=(function(){function u(){var c=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{},h=c.video,m=c.audio,y=c.screenVideo,k=c.screenAudio,S=c.customVideo,C=c.customAudio;a(this,u),this.video=h,this.audio=m,this.screenVideo=y,this.screenAudio=k,this.customVideo=S,this.customAudio=C}return p(u,[{key:"clone",value:function(){var c=new u;return this.video!==void 0&&(c.video=this.video),this.audio!==void 0&&(c.audio=this.audio),this.screenVideo!==void 0&&(c.screenVideo=this.screenVideo),this.screenAudio!==void 0&&(c.screenAudio=this.screenAudio),this.customVideo!==void 0&&(c.customVideo=Wn({},this.customVideo)),this.customAudio!==void 0&&(c.customAudio=Wn({},this.customAudio)),c}},{key:"toJSONObject",value:function(){var c={};return this.video!==void 0&&(c.video=this.video),this.audio!==void 0&&(c.audio=this.audio),this.screenVideo!==void 0&&(c.screenVideo=this.screenVideo),this.screenAudio!==void 0&&(c.screenAudio=this.screenAudio),this.customVideo!==void 0&&(c.customVideo=Wn({},this.customVideo)),this.customAudio!==void 0&&(c.customAudio=Wn({},this.customAudio)),c}},{key:"toMinifiedJSONObject",value:function(){var c={};return this.video!==void 0&&(c.v=this.video),this.audio!==void 0&&(c.a=this.audio),this.screenVideo!==void 0&&(c.sv=this.screenVideo),this.screenAudio!==void 0&&(c.sa=this.screenAudio),this.customVideo!==void 0&&(c.cv=Wn({},this.customVideo)),this.customAudio!==void 0&&(c.ca=Wn({},this.customAudio)),c}},{key:"normalize",value:function(){function c(h,m){return h&&Object.keys(h).length===1&&h["*"]===m}return!(this.video!==!0||this.audio!==!0||this.screenVideo!==!0||this.screenAudio!==!0||!c(this.customVideo,!0)||!c(this.customAudio,!0))||(this.video!==!1||this.audio!==!1||this.screenVideo!==!1||this.screenAudio!==!1||!c(this.customVideo,!1)||!c(this.customAudio,!1))&&this}}],[{key:"fromBoolean",value:function(c){return new u({video:c,audio:c,screenVideo:c,screenAudio:c,customVideo:{"*":c},customAudio:{"*":c}})}},{key:"fromJSONObject",value:function(c){return new u({video:c.video,audio:c.audio,screenVideo:c.screenVideo,screenAudio:c.screenAudio,customVideo:c.customVideo!==void 0?Wn({},c.customVideo):void 0,customAudio:c.customAudio!==void 0?Wn({},c.customAudio):void 0})}},{key:"fromMinifiedJSONObject",value:function(c){return new u({video:c.v,audio:c.a,screenVideo:c.sv,screenAudio:c.sa,customVideo:c.cv,customAudio:c.ca})}},{key:"validateJSONObject",value:function(c,h){if(typeof c=="boolean")return[!0];if(d(c)!=="object")return[!1,"invalid (non-object, non-boolean) value in canReceive"];for(var m=Object.keys(c),y=0,k=m;y<k.length;y++){var S=k[y];if(!zr.includes(S))return[!1,"invalid media type '".concat(S,"' in canReceive")];if(ET.includes(S)){if(typeof c[S]!="boolean")return[!1,"invalid (non-boolean) value for media type '".concat(S,"' in canReceive")]}else{if(d(c[S])!=="object")return[!1,"invalid (non-object) value for media type '".concat(S,"' in canReceive")];for(var C=0,E=Object.values(c[S]);C<E.length;C++)if(typeof E[C]!="boolean")return[!1,"invalid (non-boolean) value for entry within '".concat(S,"' in canReceive")];if(h&&c[S]["*"]===void 0)return[!1,`canReceive "base" permission must specify "*" as an entry within '`.concat(S,"'")]}}return h&&m.length!==zr.length?[!1,'canReceive "base" permission must specify all media types: '.concat(zr.join(", ")," (or be set to a boolean shorthand)")]:[!0]}}])})(),PT=["result"],AT=["preserveIframe"];function rm(u,c){var h=Object.keys(u);if(Object.getOwnPropertySymbols){var m=Object.getOwnPropertySymbols(u);c&&(m=m.filter((function(y){return Object.getOwnPropertyDescriptor(u,y).enumerable}))),h.push.apply(h,m)}return h}function fe(u){for(var c=1;c<arguments.length;c++){var h=arguments[c]!=null?arguments[c]:{};
19c%2?rm(Object(h),!0).forEach((function(m){I(u,m,h[m])})):Object.getOwnPropertyDescriptors?Object.defineProperties(u,Object.getOwnPropertyDescriptors(h)):rm(Object(h)).forEach((function(m){Object.defineProperty(u,m,Object.getOwnPropertyDescriptor(h,m))}))}return u}function sm(){try{var u=!Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],(function(){})))}catch{}return(sm=function(){return!!u})()}function om(u,c){var h=typeof Symbol<"u"&&u[Symbol.iterator]||u["@@iterator"];if(!h){if(Array.isArray(u)||(h=(function(E,O){if(E){if(typeof E=="string")return am(E,O);var F={}.toString.call(E).slice(8,-1);return F==="Object"&&E.constructor&&(F=E.constructor.name),F==="Map"||F==="Set"?Array.from(E):F==="Arguments"||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(F)?am(E,O):void 0}})(u))||c&&u&&typeof u.length=="number"){h&&(u=h);var m=0,y=function(){};return{s:y,n:function(){return m>=u.length?{done:!0}:{done:!1,value:u[m++]}},e:function(E){throw E},f:y}}throw new TypeError(`Invalid attempt to iterate non-iterable instance. 20In order to be iterable, non-array objects must have a [Symbol.iterator]() method.`)}var k,S=!0,C=!1;return{s:function(){h=h.call(u)},n:function(){var E=h.next();return S=E.done,E},e:function(E){C=!0,k=E},f:function(){try{S||h.return==null||h.return()}finally{if(C)throw k}}}}function am(u,c){(c==null||c>u.length)&&(c=u.length);for(var h=0,m=Array(c);h<c;h++)m[h]=u[h];return m}var mi={},cm="video",MT="voice",lm=Ae()?{data:{}}:{data:{},topology:"none"},um={present:0,hidden:0},dm={maxBitrate:{min:1e5,max:25e5},maxFramerate:{min:1,max:30},scaleResolutionDownBy:{min:1,max:8}},sl=Object.keys(dm),hm=["state","volume","simulcastEncodings"],pm={androidInCallNotification:{title:"string",subtitle:"string",iconName:"string",disableForCustomOverride:"boolean"},disableAutoDeviceManagement:{audio:"boolean",video:"boolean"}},po={id:{iconPath:"string",iconPathDarkMode:"string",label:"string",tooltip:"string",visualState:"'default' | 'sidebar-open' | 'active'"}},ol={id:{allow:"string",controlledBy:"'*' | 'owners' | string[]",csp:"string",iconURL:"string",label:"string",loading:"'eager' | 'lazy'",location:"'main' | 'sidebar'",name:"string",referrerPolicy:"string",sandbox:"string",src:"string",srcdoc:"string",shared:"string[] | 'owners' | boolean"}},gi={customIntegrations:{validate:_m,help:Sm()},customTrayButtons:{validate:Tm,help:"customTrayButtons should be a dictionary of the type ".concat(JSON.stringify(po))},url:{validate:function(u){return typeof u=="string"},help:"url should be a string"},baseUrl:{validate:function(u){return typeof u=="string"},help:"baseUrl should be a string"},token:{validate:function(u){return typeof u=="string"},help:"token should be a string",queryString:"t"},dailyConfig:{validate:function(u,c){try{return c.validateDailyConfig(u),!0}catch(h){console.error("Failed to validate dailyConfig",h)}return!1},help:"Unsupported dailyConfig. Check error logs for detailed info."},reactNativeConfig:{validate:function(u){return Cm(u,pm)},help:"reactNativeConfig should look like ".concat(JSON.stringify(pm),", all fields optional")},lang:{validate:function(u){return["da","de","en-us","en","es","fi","fr","it","jp","ka","nl","no","pl","pt","pt-BR","ru","sv","tr","user"].includes(u)},help:"language not supported. Options are: da, de, en-us, en, es, fi, fr, it, jp, ka, nl, no, pl, pt, pt-BR, ru, sv, tr, user"},userName:!0,userData:{validate:function(u){try{return mm(u),!0}catch(c){return console.error(c),!1}},help:"invalid userData type provided"},startVideoOff:!0,startAudioOff:!0,allowLocalVideo:!0,allowLocalAudio:!0,activeSpeakerMode:!0,showLeaveButton:!0,showLocalVideo:!0,showParticipantsBar:!0,showFullscreenButton:!0,showUserNameChangeUI:!0,iframeStyle:!0,customLayout:!0,cssFile:!0,cssText:!0,bodyClass:!0,videoSource:{validate:function(u,c){if(typeof u=="boolean")return c._preloadCache.allowLocalVideo=u,!0;var h;if(u instanceof MediaStreamTrack)c._sharedTracks.videoTrack=u,h={customTrack:wn};else{if(delete c._sharedTracks.videoTrack,typeof u!="string")return console.error("videoSource must be a MediaStreamTrack, boolean, or a string"),!1;h={deviceId:u}}return c._updatePreloadCacheInputSettings({video:{settings:h}},!1),!0}}
20,audioSource:{validate:function(u,c){if(typeof u=="boolean")return c._preloadCache.allowLocalAudio=u,!0;var h;if(u instanceof MediaStreamTrack)c._sharedTracks.audioTrack=u,h={customTrack:wn};else{if(delete c._sharedTracks.audioTrack,typeof u!="string")return console.error("audioSource must be a MediaStreamTrack, boolean, or a string"),!1;h={deviceId:u}}return c._updatePreloadCacheInputSettings({audio:{settings:h}},!1),!0}},subscribeToTracksAutomatically:{validate:function(u,c){return c._preloadCache.subscribeToTracksAutomatically=u,!0}},theme:{validate:function(u){var c=["accent","accentText","background","backgroundAccent","baseText","border","mainAreaBg","mainAreaBgAccent","mainAreaText","supportiveText"],h=function(m){for(var y=0,k=Object.keys(m);y<k.length;y++){var S=k[y];if(!c.includes(S))return console.error('unsupported color "'.concat(S,'". Valid colors: ').concat(c.join(", "))),!1;if(!m[S].match(/^#[0-9a-f]{6}|#[0-9a-f]{3}$/i))return console.error("".concat(S,' theme color should be provided in valid hex color format. Received: "').concat(m[S],'"')),!1}return!0};return d(u)==="object"&&("light"in u&&"dark"in u||"colors"in u)?"light"in u&&"dark"in u?"colors"in u.light?"colors"in u.dark?h(u.light.colors)&&h(u.dark.colors):(console.error('Dark theme is missing "colors" property.',u),!1):(console.error('Light theme is missing "colors" property.',u),!1):h(u.colors):(console.error('Theme must contain either both "light" and "dark" properties, or "colors".',u),!1)},help:"unsupported theme configuration. Check error logs for detailed info."},layoutConfig:{validate:function(u){if("grid"in u){var c=u.grid;if("maxTilesPerPage"in c){if(!Number.isInteger(c.maxTilesPerPage))return console.error("grid.maxTilesPerPage should be an integer. You passed ".concat(c.maxTilesPerPage,".")),!1;if(c.maxTilesPerPage>49)return console.error("grid.maxTilesPerPage can't be larger than 49 without sacrificing browser performance. Please contact us at https://www.daily.co/contact to talk about your use case."),!1}if("minTilesPerPage"in c){if(!Number.isInteger(c.minTilesPerPage))return console.error("grid.minTilesPerPage should be an integer. You passed ".concat(c.minTilesPerPage,".")),!1;if(c.minTilesPerPage<1)return console.error("grid.minTilesPerPage can't be lower than 1."),!1;if("maxTilesPerPage"in c&&c.minTilesPerPage>c.maxTilesPerPage)return console.error("grid.minTilesPerPage can't be higher than grid.maxTilesPerPage."),!1}}return!0},help:"unsupported layoutConfig. Check error logs for detailed info."},receiveSettings:{validate:function(u){return gm(u,{allowAllParticipantsKey:!1})},help:km({allowAllParticipantsKey:!1})},sendSettings:{validate:function(u,c){return!!(function(h,m){try{return m.validateUpdateSendSettings(h),!0}catch(y){return console.error("Failed to validate send settings",y),!1}})(u,c)&&(c._preloadCache.sendSettings=u,!0)},help:"Invalid sendSettings provided. Check error logs for detailed info."},inputSettings:{validate:function(u,c){var h;return!!vm(u)&&(c._inputSettings||(c._inputSettings={}),ym(u,(h=c.properties)===null||h===void 0?void 0:h.dailyConfig,c._sharedTracks),c._updatePreloadCacheInputSettings(u,!0),!0)},help:ll()},layout:{validate:function(u){return u==="custom-v1"||u==="browser"||u==="none"},help:'layout may only be set to "custom-v1"',queryString:"layout"},emb:{queryString:"emb"},embHref:{queryString:"embHref"},dailyJsVersion:{queryString:"dailyJsVersion"},proxy:{queryString:"proxy"},strictMode:!0,allowMultipleCallInstances:!0},fo={styles:{validate:function(u){for(var c in u)if(c!=="cam"&&c!=="screen")return!1;if(u.cam){for(var h in u.cam)if(h!=="div"&&h!=="video")return!1}if(u.screen){for(var m in u.screen)if(m!=="div"&&m!=="video")return!1}return!0},help:"styles format should be a subset of: { cam: {div: {}, video: {}}, screen: {div: {}, video: {}} }"},setSubscribedTracks:{validate:function(u,c){if(c._preloadCache.subscribeToTracksAutomatically)return!1;var h=[!0,!1,"staged"];if(h.includes(u)||!Ae()&&u==="avatar")return!0;var m=["audio","video","screenAudio","screenVideo","rmpAudio","rmpVideo"],y=function(k){var S=arguments.length>1&&arguments[1]!==void 0&&arguments[1];for(var C in k)if(C==="custom"){if(!h.includes(k[C])&&!y(k[C],!0))return!1}else{var E=!S&&!m.includes(C),O=!h.includes(k[C]);if(E||O)return!1}return!0};return y(u)},help:"setSubscribedTracks cannot be used when setSubscribeToTracksAutomatically is enabled, and should be of the form: "+"true".concat(Ae()?"":" | 'avatar'"," | false | 'staged' | { [audio: true|false|'staged'], [video: true|false|'staged'], [screenAudio: true|false|'staged'], [screenVideo: true|false|'staged'] }")},setAudio:!0,setVideo:!0,setScreenShare:{validate:function(u){return u===!1},help:"setScreenShare must be false, as it's only meant for stopping remote participants' screen shares"},eject:!0,updatePermissions:{validate:function(u){for(var c=0,h=Object.entries(u);c<h.length;c++){var m=M(h[c],2),y=m[0],k=m[1];switch(y){case"hasPresence":if(typeof k!="boolean")return!1;break;case"canSend":if(k instanceof Set||k instanceof Array||Array.isArray(k)){var S,C=["video","audio","screenVideo","screenAudio","customVideo","customAudio"],E=om(k);try{for(E.s();!(S=E.n()).done;){var O=S.value;if(!C.includes(O))return!1}}catch(oe){E.e(oe)}finally{E.f()}}else if(typeof k!="boolean")return!1;(k instanceof Array||Array.isArray(k))&&(u.canSend=new Set(k));break;
20case"canReceive":var F=M(im.validateJSONObject(k),2),V=F[0],G=F[1];if(!V)return console.error(G),!1;break;case"canAdmin":if(k instanceof Set||k instanceof Array||Array.isArray(k)){var Q,W=["participants","streaming","transcription"],z=om(k);try{for(z.s();!(Q=z.n()).done;){var ne=Q.value;if(!W.includes(ne))return!1}}catch(oe){z.e(oe)}finally{z.f()}}else if(typeof k!="boolean")return!1;(k instanceof Array||Array.isArray(k))&&(u.canAdmin=new Set(k));break;default:return!1}}return!0},help:"updatePermissions can take hasPresence, canSend, canReceive, and canAdmin permissions. hasPresence must be a boolean. canSend can be a boolean or an Array or Set of media types (video, audio, screenVideo, screenAudio, customVideo, customAudio). canReceive must be an object specifying base, byUserId, and/or byParticipantId fields (see documentation for more details). canAdmin can be a boolean or an Array or Set of admin types (participants, streaming, transcription)."}};Promise.any||(Promise.any=(function(){var u=L((function*(c){return new Promise((function(h,m){var y=[];c.forEach((function(k){return Promise.resolve(k).then((function(S){h(S)})).catch((function(S){y.push(S),y.length===c.length&&m(y)}))}))}))}));return function(c){return u.apply(this,arguments)}})());var RT=(function(u){function c(v){var _,T,x,D,$,Z,se=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{};if(a(this,c),x=this,D=b(D=c),I(T=g(x,sm()?Reflect.construct(D,[],b(x).constructor):D.apply(x,$)),"startListeningForDeviceChanges",(function(){_T(T.handleDeviceChange)})),I(T,"stopListeningForDeviceChanges",(function(){var de;de=T.handleDeviceChange,Xf()?(function(Se){nn.has(Se)&&(nn.delete(Se),nn.size===0&&er&&(navigator.mediaDevices.removeEventListener("devicechange",er),er=null))})(de):(function(Se){rn.has(Se)&&(rn.delete(Se),rn.size===0&&Hr&&(clearInterval(Hr),Hr=null))})(de)})),I(T,"handleDeviceChange",(function(de){de=de.map((function(Se){return JSON.parse(JSON.stringify(Se))})),T.emitDailyJSEvent({action:"available-devices-updated",availableDevices:de})})),I(T,"handleNativeAppStateChange",(function(){var de=L((function*(Se){if(Se==="destroyed")return console.warn("App has been destroyed before leaving the meeting. Cleaning up all the resources!"),void(yield T.destroy());var on=Se==="active";T.disableReactNativeAutoDeviceManagement("video")||(on?T.camUnmutedBeforeLosingNativeActiveState&&T.setLocalVideo(!0):(T.camUnmutedBeforeLosingNativeActiveState=T.localVideo(),T.camUnmutedBeforeLosingNativeActiveState&&T.setLocalVideo(!1)))}));return function(Se){return de.apply(this,arguments)}})()),I(T,"handleNativeAudioFocusChange",(function(de){T.disableReactNativeAutoDeviceManagement("audio")||(T._hasNativeAudioFocus=de,T.toggleParticipantAudioBasedOnNativeAudioFocus(),T._hasNativeAudioFocus?T.micUnmutedBeforeLosingNativeAudioFocus&&T.setLocalAudio(!0):(T.micUnmutedBeforeLosingNativeAudioFocus=T.localAudio(),T.setLocalAudio(!1)))})),I(T,"handleNativeSystemScreenCaptureStop",(function(){T.stopScreenShare()})),!Yc()&&!Ae())throw new Error("WebRTC not supported or suppressed");if(T.strictMode=se.strictMode===void 0||se.strictMode,T.allowMultipleCallInstances=(_=se.allowMultipleCallInstances)!==null&&_!==void 0&&_,Object.keys(mi).length&&(T._logDuplicateInstanceAttempt(),!T.allowMultipleCallInstances)){if(T.strictMode)throw new Error("Duplicate DailyIframe instances are not allowed");console.warn("Using strictMode: false to allow multiple call instances is now deprecated. Set `allowMultipleCallInstances: true`")}if(window._daily||(window._daily={pendings:[],instances:{}}),T.callClientId=ge(),mi[(Z=T).callClientId]=Z,window._daily.instances[T.callClientId]={},T._sharedTracks={},window._daily.instances[T.callClientId].tracks=T._sharedTracks,se.dailyJsVersion=c.version(),T._iframe=v,T._callObjectMode=se.layout==="none"&&!T._iframe,T._preloadCache={subscribeToTracksAutomatically:!0,outputDeviceId:null,inputSettings:null,sendSettings:null,videoTrackForNetworkConnectivityTest:null,videoTrackForConnectionQualityTest:null},se.showLocalVideo!==void 0?T._callObjectMode?console.error("showLocalVideo is not available in call object mode"):T._showLocalVideo=!!se.showLocalVideo:T._showLocalVideo=!0,se.showParticipantsBar!==void 0?T._callObjectMode?console.error("showParticipantsBar is not available in call object mode"):T._showParticipantsBar=!!se.showParticipantsBar:T._showParticipantsBar=!0,se.customIntegrations!==void 0?T._callObjectMode?console.error("customIntegrations is not available in call object mode"):T._customIntegrations=se.customIntegrations:T._customIntegrations={},se.customTrayButtons!==void 0?T._callObjectMode?console.error("customTrayButtons is not available in call object mode"):T._customTrayButtons=se.customTrayButtons:T._customTrayButtons={},se.activeSpeakerMode!==void 0?T._callObjectMode?console.error("activeSpeakerMode is not available in call object mode"):T._activeSpeakerMode=!!se.activeSpeakerMode:T._activeSpeakerMode=!1,se.receiveSettings?T._callObjectMode?T._receiveSettings=se.receiveSettings:console.error("receiveSettings is only available in call object mode"):T._receiveSettings={},T.validateProperties(se),T.properties=fe({},se),T._inputSettings||(T._inputSettings={}),T._callObjectLoader=T._callObjectMode?new fT(T.callClientId):null,T._callState=Fc,T._isPreparingToJoin=!1,T._accessState={access:oo},T._meetingSessionSummary={},T._finalSummaryOfPrevSession={},T._meetingSessionState=ul(lm,T._callObjectMode),T._nativeInCallAudioMode=cm,T._participants={},T._isScreenSharing=!1,T._participantCounts=um,T._rmpPlayerState={},T._waitingParticipants={},T._network={threshold:"good",quality:100,networkState:"unknown",stats:{}},T._activeSpeaker={},T._localAudioLevel=0,T._isLocalAudioLevelObserverRunning=!1,T._remoteParticipantsAudioLevel={},T._isRemoteParticipantsAudioLevelObserverRunning=!1,T._maxAppMessageSize=Gc,T._messageChannel=Ae()?new hT:new dT,T._iframe&&(T._iframe.requestFullscreen?T._iframe.addEventListener("fullscreenchange",(function(){document.fullscreenElement===T._iframe?(T.emitDailyJSEvent({action:Gr}),T.sendMessageToCallMachine({action:Gr})):(T.emitDailyJSEvent({action:Jr}),T.sendMessageToCallMachine({action:Jr}))})):T._iframe.webkitRequestFullscreen&&T._iframe.addEventListener("webkitfullscreenchange",(function(){document.webkitFullscreenElement===T._iframe?(T.emitDailyJSEvent({action:Gr}),T.sendMessageToCallMachine({action:Gr})):(T.emitDailyJSEvent({action:Jr}),T.sendMessageToCallMachine({action:Jr}))}))),Ae()){var le=T.nativeUtils();le.addAudioFocusChangeListener&&le.removeAudioFocusChangeListener&&le.addAppStateChangeListener&&le.removeAppStateChangeListener&&le.addSystemScreenCaptureStopListener&&le.removeSystemScreenCaptureStopListener||console.warn("expected (add|remove)(AudioFocusChange|AppActiveStateChange|SystemScreenCaptureStop)Listener to be available in React Native"),T._hasNativeAudioFocus=!0,le.addAudioFocusChangeListener(T.handleNativeAudioFocusChange),le.addAppStateChangeListener(T.handleNativeAppStateChange),le.addSystemScreenCaptureStopListener(T.handleNativeSystemScreenCaptureStop)}return T._callObjectMode&&T.startListeningForDeviceChanges(),T._messageChannel.addListenerForMessagesFromCallMachine(T.handleMessageFromCallMachine,T.callClientId,T),T}return w(c,u),p(c,[{key:"destroy",value:(xm=L((function*(){var v;try{yield this.leave()}catch{}var _=this._iframe;if(_){var T=_.parentElement;T&&T.removeChild(_)}if(this._messageChannel.removeListener(this.handleMessageFromCallMachine),Ae()){var x=this.nativeUtils();x.removeAudioFocusChangeListener(this.handleNativeAudioFocusChange),x.removeAppStateChangeListener(this.handleNativeAppStateChange),x.removeSystemScreenCaptureStopListener(this.handleNativeSystemScreenCaptureStop)}this._callObjectMode&&this.stopListeningForDeviceChanges(),this.resetMeetingDependentVars(),this._destroyed=!0,this.emitDailyJSEvent({action:"call-instance-destroyed"}),delete mi[this.callClientId],!((v=window)===null||v===void 0||(v=v._daily)===null||v===void 0)&&v.instances&&delete window._daily.instances[this.callClientId],this.strictMode&&(this.callClientId=void 0)})),function(){return xm.apply(this,arguments)})},{key:"isDestroyed",value:function(){return!!this._destroyed}},{key:"loadCss",value:function(v){var _=v.bodyClass,T=v.cssFile,x=v.cssText;return Me(),this.sendMessageToCallMachine({action:"load-css",cssFile:this.absoluteUrl(T),bodyClass:_,cssText:x}),this}},{key:"iframe",value:function(){return Me(),this._iframe}},{key:"meetingState",value:function(){return this._callState}},{key:"accessState",value:function(){return qt(this._callObjectMode,"accessState()"),this._accessState}},{key:"participants",value:function(){return this._participants}},{key:"participantCounts",value:function(){return this._participantCounts}},{key:"waitingParticipants",value:function(){return qt(this._callObjectMode,"waitingParticipants()"),this._waitingParticipants}},{key:"validateParticipantProperties",value:function(v,_){for(var T in _){if(!fo[T])throw new Error("unrecognized updateParticipant property ".concat(T));if(fo[T].validate&&!fo[T].validate(_[T],this,this._participants[v]))throw new Error(fo[T].help)}}},{key:"updateParticipant",value:function(v,_){return this._participants.local&&this._participants.local.session_id===v&&(v="local"),v&&_&&(this.validateParticipantProperties(v,_),this.sendMessageToCallMachine({action:"update-participant",id:v,properties:_})),this}},{key:"updateParticipants",value:function(v){var _=this._participants.local&&this._participants.local.session_id;for(var T in v)T===_&&(T="local"),T&&v[T]&&this.validateParticipantProperties(T,v[T]);return this.sendMessageToCallMachine({action:"update-participants",participants:v}),this}},{key:"updateWaitingParticipant",value:(Lm=L((function*(){var v=this,_=arguments.length>0&&arguments[0]!==void 0?arguments[0]:"",T=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{};if(qt(this._callObjectMode,"updateWaitingParticipant()"),Ne(this._callState,"updateWaitingParticipant()"),typeof _!="string"||d(T)!=="object")throw new Error("updateWaitingParticipant() must take an id string and a updates object");
20return new Promise((function(x,D){v.sendMessageToCallMachine({action:"daily-method-update-waiting-participant",id:_,updates:T},(function($){$.error&&D($.error),$.id||D(new Error("unknown error in updateWaitingParticipant()")),x({id:$.id})}))}))})),function(){return Lm.apply(this,arguments)})},{key:"updateWaitingParticipants",value:(Dm=L((function*(){var v=this,_=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};if(qt(this._callObjectMode,"updateWaitingParticipants()"),Ne(this._callState,"updateWaitingParticipants()"),d(_)!=="object")throw new Error("updateWaitingParticipants() must take a mapping between ids and update objects");return new Promise((function(T,x){v.sendMessageToCallMachine({action:"daily-method-update-waiting-participants",updatesById:_},(function(D){D.error&&x(D.error),D.ids||x(new Error("unknown error in updateWaitingParticipants()")),T({ids:D.ids})}))}))})),function(){return Dm.apply(this,arguments)})},{key:"requestAccess",value:(Om=L((function*(){var v=this,_=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{},T=_.access,x=T===void 0?{level:_p}:T,D=_.name,$=D===void 0?"":D;return qt(this._callObjectMode,"requestAccess()"),Ne(this._callState,"requestAccess()"),new Promise((function(Z,se){v.sendMessageToCallMachine({action:"daily-method-request-access",access:x,name:$},(function(le){le.error&&se(le.error),le.access||se(new Error("unknown error in requestAccess()")),Z({access:le.access,granted:le.granted})}))}))})),function(){return Om.apply(this,arguments)})},{key:"localAudio",value:function(){return this._participants.local?!["blocked","off"].includes(this._participants.local.tracks.audio.state):null}},{key:"localVideo",value:function(){return this._participants.local?!["blocked","off"].includes(this._participants.local.tracks.video.state):null}},{key:"setLocalAudio",value:function(v){var _=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{};return"forceDiscardTrack"in _&&(Ae()?(console.warn("forceDiscardTrack option not supported in React Native; ignoring"),_={}):v&&(console.warn("forceDiscardTrack option only supported when calling setLocalAudio(false); ignoring"),_={})),this.sendMessageToCallMachine({action:"local-audio",state:v,options:_}),this}},{key:"localScreenAudio",value:function(){return this._participants.local?!["blocked","off"].includes(this._participants.local.tracks.screenAudio.state):null}},{key:"localScreenVideo",value:function(){return this._participants.local?!["blocked","off"].includes(this._participants.local.tracks.screenVideo.state):null}},{key:"updateScreenShare",value:function(v){if(this._isScreenSharing)return this.sendMessageToCallMachine({action:"local-screen-update",options:v}),this;console.warn("There is no screen share in progress. Try calling startScreenShare first.")}},{key:"setLocalVideo",value:function(v){return this.sendMessageToCallMachine({action:"local-video",state:v}),this}},{key:"_setAllowLocalAudio",value:function(v){if(this._preloadCache.allowLocalAudio=v,this._callMachineInitialized)return this.sendMessageToCallMachine({action:"set-allow-local-audio",state:v}),this}},{key:"_setAllowLocalVideo",value:function(v){if(this._preloadCache.allowLocalVideo=v,this._callMachineInitialized)return this.sendMessageToCallMachine({action:"set-allow-local-video",state:v}),this}},{key:"getReceiveSettings",value:(Im=L((function*(v){var _=this,T=(arguments.length>1&&arguments[1]!==void 0?arguments[1]:{}).showInheritedValues,x=T!==void 0&&T;if(qt(this._callObjectMode,"getReceiveSettings()"),!this._callMachineInitialized)return this._receiveSettings;switch(d(v)){case"string":return new Promise((function(D){_.sendMessageToCallMachine({action:"get-single-participant-receive-settings",id:v,showInheritedValues:x},(function($){D($.receiveSettings)}))}));case"undefined":return this._receiveSettings;default:throw new Error('first argument to getReceiveSettings() must be a participant id (or "base"), or there should be no arguments')}})),function(v){return Im.apply(this,arguments)})},{key:"updateReceiveSettings",value:(Rm=L((function*(v){var _=this;if(qt(this._callObjectMode,"updateReceiveSettings()"),!gm(v,{allowAllParticipantsKey:!0}))throw new Error(km({allowAllParticipantsKey:!0}));return Ne(this._callState,"updateReceiveSettings()","To specify receive settings earlier, use the receiveSettings config property."),new Promise((function(T){_.sendMessageToCallMachine({action:"update-receive-settings",receiveSettings:v},(function(x){T({receiveSettings:x.receiveSettings})}))}))})),function(v){return Rm.apply(this,arguments)})},{key:"_prepInputSettingsForSharing",value:function(v,_){if(v){var T={};if(v.audio){var x,D,$;v.audio.settings&&(!Object.keys(v.audio.settings).length&&_||(T.audio={settings:fe({},v.audio.settings)})),_&&(x=T.audio)!==null&&x!==void 0&&(x=x.settings)!==null&&x!==void 0&&x.customTrack&&(T.audio.settings={customTrack:this._sharedTracks.audioTrack});var Z=((D=v.audio.processor)===null||D===void 0?void 0:D.type)==="none"&&(($=v.audio.processor)===null||$===void 0?void 0:$._isDefaultWhenNone);if(v.audio.processor&&!Z){var se=fe({},v.audio.processor);delete se._isDefaultWhenNone,T.audio=fe(fe({},T.audio),{},{processor:se})}}if(v.video){var le,de,Se;v.video.settings&&(!Object.keys(v.video.settings).length&&_||(T.video={settings:fe({},v.video.settings)})),_&&(le=T.video)!==null&&le!==void 0&&(le=le.settings)!==null&&le!==void 0&&le.customTrack&&(T.video.settings={customTrack:this._sharedTracks.videoTrack});var on=((de=v.video.processor)===null||de===void 0?void 0:de.type)==="none"&&((Se=v.video.processor)===null||Se===void 0?void 0:Se._isDefaultWhenNone);if(v.video.processor&&!on){var vi=fe({},v.video.processor);delete vi._isDefaultWhenNone,T.video=fe(fe({},T.video),{},{processor:vi})}}return T}}},{key:"getInputSettings",value:function(){var v=this;return Me(),new Promise((function(_){_(v._getInputSettings())}))}},{key:"_getInputSettings",value:function(){var v,_,T,x,D,$,Z={processor:{type:"none",_isDefaultWhenNone:!0}};this._inputSettings?(v=((T=this._inputSettings)===null||T===void 0?void 0:T.video)||Z,_=((x=this._inputSettings)===null||x===void 0?void 0:x.audio)||Z):(v=((D=this._preloadCache)===null||D===void 0||(D=D.inputSettings)===null||D===void 0?void 0:D.video)||Z,_=(($=this._preloadCache)===null||$===void 0||($=$.inputSettings)===null||$===void 0?void 0:$.audio)||Z);var se={audio:_,video:v};return this._prepInputSettingsForSharing(se,!0)}},{key:"_updatePreloadCacheInputSettings",value:function(v,_){var T,x,D,$,Z,se,le=this._inputSettings||{},de={};v.video?(de.video={},v.video.settings?(de.video.settings={},_||v.video.settings.customTrack||(D=le.video)===null||D===void 0||!D.settings?de.video.settings=v.video.settings:de.video.settings=fe(fe({},le.video.settings),v.video.settings),Object.keys(de.video.settings).length||delete de.video.settings):(T=le.video)!==null&&T!==void 0&&T.settings&&(de.video.settings=le.video.settings),v.video.processor?de.video.processor=v.video.processor:(x=le.video)!==null&&x!==void 0&&x.processor&&(de.video.processor=le.video.processor)):le.video&&(de.video=le.video),v.audio?(de.audio={},v.audio.settings?(de.audio.settings={},_||v.audio.settings.customTrack||(se=le.audio)===null||se===void 0||!se.settings?de.audio.settings=v.audio.settings:de.audio.settings=fe(fe({},le.audio.settings),v.audio.settings),Object.keys(de.audio.settings).length||delete de.audio.settings):($=le.audio)!==null&&$!==void 0&&$.settings&&(de.audio.settings=le.audio.settings),v.audio.processor?de.audio.processor=v.audio.processor:(Z=le.audio)!==null&&Z!==void 0&&Z.processor&&(de.audio.processor=le.audio.processor)):le.audio&&(de.audio=le.audio),this._maybeUpdateInputSettings(de)}},{key:"_devicesFromInputSettings",value:function(v){var _,T,x=(v==null||(_=v.video)===null||_===void 0||(_=_.settings)===null||_===void 0?void 0:_.deviceId)||null,D=(v==null||(T=v.audio)===null||T===void 0||(T=T.settings)===null||T===void 0?void 0:T.deviceId)||null,$=this._preloadCache.outputDeviceId||null;return{camera:x?{deviceId:x}:{},mic:D?{deviceId:D}:{},speaker:$?{deviceId:$}:{}}}},{key:"updateInputSettings",value:(Mm=L((function*(v){var _=this;return Me(),vm(v)?v.video||v.audio?(ym(v,this.properties.dailyConfig,this._sharedTracks),this._callObjectMode&&!this._callMachineInitialized?(this._updatePreloadCacheInputSettings(v,!0),this._getInputSettings()):new Promise((function(T,x){_.
20sendMessageToCallMachine({action:"update-input-settings",inputSettings:v},(function(D){if(D.error)x(D.error);else{if(D.returnPreloadCache)return _._updatePreloadCacheInputSettings(v,!0),void T(_._getInputSettings());_._maybeUpdateInputSettings(D.inputSettings),T(_._prepInputSettingsForSharing(D.inputSettings,!0))}}))}))):this._getInputSettings():(console.error(ll()),Promise.reject(ll()))})),function(v){return Mm.apply(this,arguments)})},{key:"setBandwidth",value:function(v){var _=v.kbs,T=v.trackConstraints;if(Me(),this._callMachineInitialized)return this.sendMessageToCallMachine({action:"set-bandwidth",kbs:_,trackConstraints:T}),this}},{key:"getDailyLang",value:function(){var v=this;if(Me(),this._callMachineInitialized)return new Promise((function(_){v.sendMessageToCallMachine({action:"get-daily-lang"},(function(T){delete T.action,delete T.callbackStamp,_(T)}))}))}},{key:"setDailyLang",value:function(v){return Me(),this.sendMessageToCallMachine({action:"set-daily-lang",lang:v}),this}},{key:"setProxyUrl",value:function(v){return this.sendMessageToCallMachine({action:"set-proxy-url",proxyUrl:v}),this}},{key:"setIceConfig",value:function(v){return this.sendMessageToCallMachine({action:"set-ice-config",iceConfig:v}),this}},{key:"meetingSessionSummary",value:function(){return[_n,Cn].includes(this._callState)?this._finalSummaryOfPrevSession:this._meetingSessionSummary}},{key:"getMeetingSession",value:(Am=L((function*(){var v=this;return console.warn("getMeetingSession() is deprecated: use meetingSessionSummary(), which will return immediately"),Ne(this._callState,"getMeetingSession()"),new Promise((function(_){v.sendMessageToCallMachine({action:"get-meeting-session"},(function(T){delete T.action,delete T.callbackStamp,_(T)}))}))})),function(){return Am.apply(this,arguments)})},{key:"meetingSessionState",value:function(){return Ne(this._callState,"meetingSessionState"),this._meetingSessionState}},{key:"setMeetingSessionData",value:function(v){var _=arguments.length>1&&arguments[1]!==void 0?arguments[1]:"replace";qt(this._callObjectMode,"setMeetingSessionData()"),Ne(this._callState,"setMeetingSessionData");try{(function(T,x){new pT({data:T,mergeStrategy:x})})(v,_)}catch(T){throw console.error(T),T}try{this.sendMessageToCallMachine({action:"set-session-data",data:v,mergeStrategy:_})}catch(T){throw new Error("Error setting meeting session data: ".concat(T))}}},{key:"setUserName",value:function(v,_){var T=this;return this.properties.userName=v,new Promise((function(x){T.sendMessageToCallMachine({action:"set-user-name",name:v??"",thisMeetingOnly:Ae()||!!_&&!!_.thisMeetingOnly},(function(D){delete D.action,delete D.callbackStamp,x(D)}))}))}},{key:"setUserData",value:(sr=L((function*(v){var _=this;try{mm(v)}catch(T){throw console.error(T),T}if(this.properties.userData=v,this._callMachineInitialized)return new Promise((function(T){try{_.sendMessageToCallMachine({action:"set-user-data",userData:v},(function(x){delete x.action,delete x.callbackStamp,T(x)}))}catch(x){throw new Error("Error setting user data: ".concat(x))}}))})),function(v){return sr.apply(this,arguments)})},{key:"validateAudioLevelInterval",value:function(v){if(v&&(v<100||typeof v!="number"))throw new Error("The interval must be a number greater than or equal to 100 milliseconds.")}},{key:"startLocalAudioLevelObserver",value:function(v){var _=this;if(typeof AudioWorkletNode>"u"&&!Ae())throw new Error("startLocalAudioLevelObserver() is not supported on this browser");if(this.validateAudioLevelInterval(v),this._callMachineInitialized)return this._isLocalAudioLevelObserverRunning=!0,new Promise((function(T,x){_.sendMessageToCallMachine({action:"start-local-audio-level-observer",interval:v},(function(D){_._isLocalAudioLevelObserverRunning=!D.error,D.error?x({error:D.error}):T()}))}));this._preloadCache.localAudioLevelObserver={enabled:!0,interval:v}}},{key:"isLocalAudioLevelObserverRunning",value:function(){return this._isLocalAudioLevelObserverRunning}},{key:"stopLocalAudioLevelObserver",value:function(){this._preloadCache.localAudioLevelObserver=null,this._localAudioLevel=0,this._isLocalAudioLevelObserverRunning=!1,this.sendMessageToCallMachine({action:"stop-local-audio-level-observer"})}},{key:"startRemoteParticipantsAudioLevelObserver",value:function(v){var _=this;if(this.validateAudioLevelInterval(v),this._callMachineInitialized)return this._isRemoteParticipantsAudioLevelObserverRunning=!0,new Promise((function(T,x){_.
20sendMessageToCallMachine({action:"start-remote-participants-audio-level-observer",interval:v},(function(D){_._isRemoteParticipantsAudioLevelObserverRunning=!D.error,D.error?x({error:D.error}):T()}))}));this._preloadCache.remoteParticipantsAudioLevelObserver={enabled:!0,interval:v}}},{key:"isRemoteParticipantsAudioLevelObserverRunning",value:function(){return this._isRemoteParticipantsAudioLevelObserverRunning}},{key:"stopRemoteParticipantsAudioLevelObserver",value:function(){this._preloadCache.remoteParticipantsAudioLevelObserver=null,this._remoteParticipantsAudioLevel={},this._isRemoteParticipantsAudioLevelObserverRunning=!1,this.sendMessageToCallMachine({action:"stop-remote-participants-audio-level-observer"})}},{key:"startCamera",value:(rr=L((function*(){var v=this,_=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};if(qt(this._callObjectMode,"startCamera()"),al(this._callState,this._isPreparingToJoin,"startCamera()","Did you mean to use setLocalAudio() and/or setLocalVideo() instead?"),this.needsLoad())try{yield this.load(_)}catch(T){return Promise.reject(T)}else{if(this._didPreAuth){if(_.url&&_.url!==this.properties.url)return console.error("url in startCamera() is different than the one used in preAuth()"),Promise.reject();if(_.token&&_.token!==this.properties.token)return console.error("token in startCamera() is different than the one used in preAuth()"),Promise.reject()}this.validateProperties(_),this.properties=fe(fe({},this.properties),_)}return new Promise((function(T,x){v._preloadCache.inputSettings=v._prepInputSettingsForSharing(v._inputSettings,!1),v.sendMessageToCallMachine({action:"start-camera",properties:tr(v.properties,v.callClientId),preloadCache:tr(v._preloadCache,v.callClientId)},(function(D){D.error?x(D.error):T({camera:D.camera,mic:D.mic,speaker:D.speaker})}))}))})),function(){return rr.apply(this,arguments)})},{key:"validateCustomTrack",value:function(v,_,T){if(T&&T.length>50)throw new Error("Custom track `trackName` must not be more than 50 characters");if(_&&_!=="music"&&_!=="speech"&&!(_ instanceof Object))throw new Error("Custom track `mode` must be either `music` | `speech` | `DailyMicAudioModeSettings` or `undefined`");if(T&&["cam-audio","cam-video","screen-video","screen-audio","rmpAudio","rmpVideo","customVideoDefaults"].includes(T))throw new Error("Custom track `trackName` must not match a track name already used by daily: cam-audio, cam-video, customVideoDefaults, screen-video, screen-audio, rmpAudio, rmpVideo");if(!(v instanceof MediaStreamTrack))throw new Error("Custom tracks provided must be instances of MediaStreamTrack")}},{key:"startCustomTrack",value:function(){var v=this,_=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{track,mode,trackName,ignoreAudioLevel};return Me(),Ne(this._callState,"startCustomTrack()"),this.validateCustomTrack(_.track,_.mode,_.trackName),new Promise((function(T,x){v._sharedTracks.customTrack=_.track,_.track=wn,v.sendMessageToCallMachine({action:"start-custom-track",properties:_},(function(D){D.error?x({error:D.error}):T(D.mediaTag)}))}))}},{key:"stopCustomTrack",value:function(v){var _=this;return Me(),Ne(this._callState,"stopCustomTrack()"),new Promise((function(T){_.sendMessageToCallMachine({action:"stop-custom-track",mediaTag:v},(function(x){T(x.mediaTag)}))}))}},{key:"setCamera",value:function(v){var _=this;return Yr(),go(this._callMachineInitialized,"setCamera()"),new Promise((function(T){_.sendMessageToCallMachine({action:"set-camera",cameraDeviceId:v},(function(x){T({device:x.device})}))}))}},{key:"setAudioDevice",value:(ir=L((function*(v){return Yr(),this.nativeUtils().setAudioDevice(v),{deviceId:yield this.nativeUtils().getAudioDevice()}})),function(v){return ir.apply(this,arguments)})},{key:"cycleCamera",value:function(){var v=this,_=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};return new Promise((function(T){v.sendMessageToCallMachine({action:"cycle-camera",properties:_},(function(x){T({device:x.device})}))}))}},{key:"cycleMic",value:function(){var v=this;return Me(),new Promise((function(_){v.sendMessageToCallMachine({action:"cycle-mic"},(function(T){_({device:T.device})}))}))}},{key:"getCameraFacingMode",value:function(){var v=this;return Yr(),new Promise((function(_){v.sendMessageToCallMachine({action:"get-camera-facing-mode"},(function(T){_(T.facingMode)}))}))}},{key:"setInputDevicesAsync",value:(nr=L((function*(v){var _=this,T=v.audioDeviceId,x=v.videoDeviceId,D=v.audioSource,$=v.videoSource;if(Me(),D!==void 0&&(T=D),$!==void 0&&(x=$),typeof T=="boolean"&&(this._setAllowLocalAudio(T),T=void 0),typeof x=="boolean"&&(this._setAllowLocalVideo(x),x=void 0),!T&&!x)return yield this.getInputDevices();var Z={};return T&&(T instanceof MediaStreamTrack?(this._sharedTracks.audioTrack=T,T=wn,Z.audio={settings:{customTrack:T}}):(delete this._sharedTracks.audioTrack,Z.audio={settings:{deviceId:T}})),x&&(x instanceof MediaStreamTrack?(this._sharedTracks.videoTrack=x,x=wn,Z.video={settings:{customTrack:x}}):(delete this._sharedTracks.videoTrack,Z.video={settings:{deviceId:x}})),this._callObjectMode&&this.needsLoad()?(this._updatePreloadCacheInputSettings(Z,!1),this._devicesFromInputSettings(this._inputSettings)):new Promise((function(se){_.sendMessageToCallMachine({action:"set-input-devices",audioDeviceId:T,videoDeviceId:x},(function(le){if(delete le.action,delete le.callbackStamp,le.returnPreloadCache)return _._updatePreloadCacheInputSettings(Z,!1),void se(_._devicesFromInputSettings(_._inputSettings));se(le)}))}
20))})),function(v){return nr.apply(this,arguments)})},{key:"setOutputDeviceAsync",value:(Pn=L((function*(v){var _=this,T=v.outputDeviceId;if(Me(),!T||typeof T!="string")throw new Error("outputDeviceId must be provided and must be a valid device id");return this._preloadCache.outputDeviceId=T,this._callObjectMode&&this.needsLoad()?this._devicesFromInputSettings(this._inputSettings):new Promise((function(x,D){_.sendMessageToCallMachine({action:"set-output-device",outputDeviceId:T},(function($){if(delete $.action,delete $.callbackStamp,$.error){var Z=new Error($.error.message);return Z.type=$.error.type,void D(Z)}$.returnPreloadCache?x(_._devicesFromInputSettings(_._inputSettings)):x($)}))}))})),function(v){return Pn.apply(this,arguments)})},{key:"getInputDevices",value:(sn=L((function*(){var v=this;return this._callObjectMode&&this.needsLoad()?this._devicesFromInputSettings(this._inputSettings):new Promise((function(_){v.sendMessageToCallMachine({action:"get-input-devices"},(function(T){T.returnPreloadCache?_(v._devicesFromInputSettings(v._inputSettings)):_({camera:T.camera,mic:T.mic,speaker:T.speaker})}))}))})),function(){return sn.apply(this,arguments)})},{key:"nativeInCallAudioMode",value:function(){return Yr(),this._nativeInCallAudioMode}},{key:"setNativeInCallAudioMode",value:function(v){if(Yr(),[cm,MT].includes(v)){if(v!==this._nativeInCallAudioMode)return this._nativeInCallAudioMode=v,!this.disableReactNativeAutoDeviceManagement("audio")&&mo(this._callState,this._isPreparingToJoin)&&this.nativeUtils().setAudioMode(this._nativeInCallAudioMode),this}else console.error("invalid in-call audio mode specified: ",v)}},{key:"preAuth",value:(En=L((function*(){var v=this,_=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};if(qt(this._callObjectMode,"preAuth()"),al(this._callState,this._isPreparingToJoin,"preAuth()"),this.needsLoad()&&(yield this.load(_)),!_.url)throw new Error("preAuth() requires at least a url to be provided");return this.validateProperties(_),this.properties=fe(fe({},this.properties),_),new Promise((function(T,x){v._preloadCache.inputSettings=v._prepInputSettingsForSharing(v._inputSettings,!1),v.sendMessageToCallMachine({action:"daily-method-preauth",properties:tr(v.properties,v.callClientId),preloadCache:tr(v._preloadCache,v.callClientId)},(function(D){return D.error?x(D.error):D.access?(v._didPreAuth=!0,void T({access:D.access})):x(new Error("unknown error in preAuth()"))}))}))})),function(){return En.apply(this,arguments)})},{key:"load",value:(Et=L((function*(v){var _=this;if(this.needsLoad()){if(this._destroyed&&(this._logUseAfterDestroy(),this.strictMode))throw new Error("Use after destroy");if(v&&(this.validateProperties(v),this.properties=fe(fe({},this.properties),v)),!this._callObjectMode&&!this.properties.url)throw new Error("can't load iframe meeting because url property isn't set");return this._updateCallState(kp),this.emitDailyJSEvent({action:Ip}),this._callObjectMode?new Promise((function(T,x){_._callObjectLoader.cancel();var D=Date.now();_._callObjectLoader.load(_.properties.dailyConfig,(function($){_._bundleLoadTime=$?"no-op":Date.now()-D,_._updateCallState(Sp),$&&_.emitDailyJSEvent({action:jc}),T()}),(function($,Z){if(_.emitDailyJSEvent({action:Op}),!Z){_._updateCallState(Cn),_.resetMeetingDependentVars();var se={action:Wc,errorMsg:$.msg,error:{type:"connection-error",msg:"Failed to load call object bundle.",details:{on:"load",sourceError:$,bundleUrl:Je(_.properties.dailyConfig)}}};_._maybeSendToSentry(se),_.emitDailyJSEvent(se),x($.msg)}}))})):(this._iframe.src=Oe(this.assembleMeetingUrl(),this.properties.dailyConfig),new Promise((function(T,x){_._loadedCallback=function(D){_._callState!==Cn?(_._updateCallState(Sp),(_.properties.cssFile||_.properties.cssText)&&_.loadCss(_.properties),T()):x(D)}})))}})),function(v){return Et.apply(this,arguments)})},{key:"join",value:(Vt=L((function*(){var v=this,_=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};if(this._testCallInProgress&&this.stopTestCallQuality(),!_.url&&!this.properties.url){var T="No room URL has been provided";return console.error(T),Promise.reject(new Error(T))}var x=!1;if(this.needsLoad()){this.updateIsPreparingToJoin(!0);try{yield this.load(_)}catch(D){return this.updateIsPreparingToJoin(!1),Promise.reject(D)}}else{if(x=!(!this.properties.cssFile&&!this.properties.cssText),this._didPreAuth){if(_.url&&_.url!==this.properties.url)return console.error("url in join() is different than the one used in preAuth()"),this.updateIsPreparingToJoin(!1),Promise.reject();if(_.token&&_.token!==this.properties.token)return console.error("token in join() is different than the one used in preAuth()"),this.updateIsPreparingToJoin(!1),Promise.reject()}if(_.url&&!this._callObjectMode&&_.url&&_.url!==this.properties.url)return console.error("url in join() is different than the one used in load() (".concat(this.properties.url," -> ").concat(_.url,")")),this.updateIsPreparingToJoin(!1),Promise.reject();this.validateProperties(_),this.properties=fe(fe({},this.properties),_)}return _.showLocalVideo!==void 0&&(this._callObjectMode?console.error("showLocalVideo is not available in callObject mode"):this._showLocalVideo=!!_.showLocalVideo),_.showParticipantsBar!==void 0&&(this._callObjectMode?console.error("showParticipantsBar is not available in callObject mode"):this._showParticipantsBar=!!_.showParticipantsBar),this._callState===Vn||this._callState===so?(console.warn("already joined meeting, call leave() before joining again"),void this.updateIsPreparingToJoin(!1)):(this._updateCallState(so,!1),this.emitDailyJSEvent({action:xp}),this._preloadCache.inputSettings=this._prepInputSettingsForSharing(this._inputSettings||{},!1),this.sendMessageToCallMachine({action:"join-meeting",properties:tr(this.properties,this.callClientId),preloadCache:tr(this._preloadCache,this.callClientId)},(function(D){D.error&&v._joinedCallback&&(v._joinedCallback(null,D.error),v._joinedCallback=null)})),new Promise((function(D,$){v._joinedCallback=function(Z,se){if(v._callState!==Cn){if(se)return v._updateCallState(_n),void $(se);if(v._updateCallState(Vn),Z)for(var le in Z){if(v._callObjectMode){var de=v._callMachine().store;Hf(Z[le],de),Kf(Z[le],de),zf(Z[le],v._participants[le],de)}v._participants[le]=fe({},Z[le]),v.toggleParticipantAudioBasedOnNativeAudioFocus()}x&&v.loadCss(v.properties),D(Z)}else $(se)}})))})),function(){return Vt.apply(this,arguments)})},{key:"leave",value:(qe=L((function*(){var v=this;return this._testCallInProgress&&this.stopTestCallQuality(),new Promise((function(_){v._callState===_n||v._callState===Cn?_():v._callObjectLoader&&!v._callObjectLoader.loaded?(v._callObjectLoader.cancel(),v._updateCallState(_n),v.resetMeetingDependentVars(),v.emitDailyJSEvent({action:_n}),_()):(v._resolveLeave=_,v.sendMessageToCallMachine({action:"leave-meeting"}))}))})),function(){return qe.apply(this,arguments)})}
20,{key:"startScreenShare",value:(we=L((function*(){var v=this,_=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};if(go(this._callMachineInitialized,"startScreenShare()"),_.screenVideoSendSettings&&this._validateVideoSendSettings("screenVideo",_.screenVideoSendSettings),_.mediaStream&&(this._sharedTracks.screenMediaStream=_.mediaStream,_.mediaStream=wn),typeof DailyNativeUtils<"u"&&DailyNativeUtils.isIOS!==void 0&&DailyNativeUtils.isIOS){var T=this.nativeUtils();if(yield T.isScreenBeingCaptured())return void this.emitDailyJSEvent({action:$c,type:"screen-share-error",errorMsg:"Could not start the screen sharing. The screen is already been captured!"});T.setSystemScreenCaptureStartCallback((function(){T.setSystemScreenCaptureStartCallback(null),v.sendMessageToCallMachine({action:wf,captureOptions:_})})),T.presentSystemScreenCapturePrompt()}else this.sendMessageToCallMachine({action:wf,captureOptions:_})})),function(){return we.apply(this,arguments)})},{key:"stopScreenShare",value:function(){go(this._callMachineInitialized,"stopScreenShare()"),this.sendMessageToCallMachine({action:"local-screen-stop"})}},{key:"startRecording",value:function(){var v=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{},_=v.type;if(_&&_!=="cloud"&&_!=="cloud-audio-only"&&_!=="raw-tracks"&&_!=="local")throw new Error("invalid type: ".concat(_,", allowed values 'cloud', 'cloud-audio-only', 'raw-tracks', or 'local'"));this.sendMessageToCallMachine(fe({action:"local-recording-start"},v))}},{key:"updateRecording",value:function(v){var _=v.layout,T=_===void 0?{preset:"default"}:_,x=v.instanceId;this.sendMessageToCallMachine({action:"daily-method-update-recording",layout:T,instanceId:x})}},{key:"stopRecording",value:function(){var v=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};this.sendMessageToCallMachine(fe({action:"local-recording-stop"},v))}},{key:"startLiveStreaming",value:function(){var v=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};this.sendMessageToCallMachine(fe({action:"daily-method-start-live-streaming"},v))}},{key:"updateLiveStreaming",value:function(v){var _=v.layout,T=_===void 0?{preset:"default"}:_,x=v.instanceId;this.sendMessageToCallMachine({action:"daily-method-update-live-streaming",layout:T,instanceId:x})}},{key:"addLiveStreamingEndpoints",value:function(v){var _=v.endpoints,T=v.instanceId;this.sendMessageToCallMachine({action:Ef,endpointsOp:"add-endpoints",endpoints:_,instanceId:T})}},{key:"removeLiveStreamingEndpoints",value:function(v){var _=v.endpoints,T=v.instanceId;this.sendMessageToCallMachine({action:Ef,endpointsOp:"remove-endpoints",endpoints:_,instanceId:T})}},{key:"stopLiveStreaming",value:function(){var v=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};
20this.sendMessageToCallMachine(fe({action:"daily-method-stop-live-streaming"},v))}},{key:"validateDailyConfig",value:function(v){v.camSimulcastEncodings&&(console.warn("camSimulcastEncodings is deprecated. Use sendSettings, found in DailyCallOptions, to provide camera simulcast settings."),this.validateSimulcastEncodings(v.camSimulcastEncodings)),v.screenSimulcastEncodings&&console.warn("screenSimulcastEncodings is deprecated. Use sendSettings, found in DailyCallOptions, to provide screen simulcast settings."),Df()&&v.noAutoDefaultDeviceChange&&console.warn("noAutoDefaultDeviceChange is not supported on Android, and will be ignored.")}},{key:"validateSimulcastEncodings",value:function(v){var _=arguments.length>1&&arguments[1]!==void 0?arguments[1]:null,T=arguments.length>2&&arguments[2]!==void 0&&arguments[2];if(v){if(!(v instanceof Array||Array.isArray(v)))throw new Error("encodings must be an Array");if(!Pm(v.length,1,3))throw new Error("encodings must be an Array with between 1 to ".concat(3," layers"));for(var x=0;x<v.length;x++){var D=v[x];for(var $ in this._validateEncodingLayerHasValidProperties(D),D)if(sl.includes($)){if(typeof D[$]!="number")throw new Error("".concat($," must be a number"));if(_){var Z=_[$],se=Z.min,le=Z.max;if(!Pm(D[$],se,le))throw new Error("".concat($," value not in range. valid range: ").concat(se," to ").concat(le))}}else if(!["active","scalabilityMode"].includes($))throw new Error("Invalid key ".concat($,", valid keys are:")+Object.values(sl));if(T&&!D.hasOwnProperty("maxBitrate"))throw new Error("maxBitrate is not specified")}}}},{key:"startRemoteMediaPlayer",value:(he=L((function*(v){var _=this,T=v.url,x=v.settings,D=x===void 0?{state:Hc.PLAY}:x;try{(function($){if(typeof $!="string")throw new Error('url parameter must be "string" type')})(T),Em(D),(function($){for(var Z in $)if(!hm.includes(Z))throw new Error("Invalid key ".concat(Z,", valid keys are: ").concat(hm));$.simulcastEncodings&&this.validateSimulcastEncodings($.simulcastEncodings,dm,!0)})(D)}catch($){throw console.error("invalid argument Error: ".concat($)),console.error(`startRemoteMediaPlayer arguments must be of the form: 21 { url: "playback url", 22 settings?: 23 {state: "play"|"pause", simulcastEncodings?: [{}] } }`),$}return new Promise((function($,Z){_.sendMessageToCallMachine({action:"daily-method-start-remote-media-player",url:T,settings:D},(function(se){se.error?Z({error:se.error,errorMsg:se.errorMsg}):$({session_id:se.session_id,remoteMediaPlayerState:{state:se.state,settings:se.settings}})}))}))})),function(v){return he.apply(this,arguments)})},{key:"stopRemoteMediaPlayer",value:(me=L((function*(v){var _=this;if(typeof v!="string")throw new Error(" remotePlayerID must be of type string");return new Promise((function(T,x){_.sendMessageToCallMachine({action:"daily-method-stop-remote-media-player",session_id:v},(function(D){D.error?x({error:D.error,errorMsg:D.errorMsg}):T()}))}))})),function(v){return me.apply(this,arguments)})},{key:"updateRemoteMediaPlayer",value:(ue=L((function*(v){var _=this,T=v.session_id,x=v.settings;try{Em(x)}catch(D){throw console.error("invalid argument Error: ".concat(D)),console.error(`updateRemoteMediaPlayer arguments must be of the form: 24 session_id: "participant session", 25 { settings?: {state: "play"|"pause"} }`),D}return new Promise((function(D,$){_.sendMessageToCallMachine({action:"daily-method-update-remote-media-player",session_id:T,settings:x},(function(Z){Z.error?$({error:Z.error,errorMsg:Z.errorMsg}):D({session_id:Z.session_id,remoteMediaPlayerState:{state:Z.state,settings:Z.settings}})}))}))})),function(v){return ue.apply(this,arguments)})},{key:"startTranscription",value:function(v){Ne(this._callState,"startTranscription()"),this.sendMessageToCallMachine(fe({action:"daily-method-start-transcription"},v))}},{key:"updateTranscription",value:function(v){if(Ne(this._callState,"updateTranscription()"),!v)throw new Error("updateTranscription Error: options is mandatory");if(d(v)!=="object")throw new Error("updateTranscription Error: options must be object type");if(v.participants&&!Array.isArray(v.participants))throw new Error("updateTranscription
25Error: participants must be an array");this.sendMessageToCallMachine(fe({action:"daily-method-update-transcription"},v))}},{key:"stopTranscription",value:function(v){if(Ne(this._callState,"stopTranscription()"),v&&d(v)!=="object")throw new Error("stopTranscription Error: options must be object type");if(v&&!v.instanceId)throw new Error('"instanceId" not provided');this.sendMessageToCallMachine(fe({action:"daily-method-stop-transcription"},v))}},{key:"startDialOut",value:(oe=L((function*(v){var _=this;Ne(this._callState,"startDialOut()");var T=function(Z){if(Z){if(!Array.isArray(Z))throw new Error("Error starting dial out: audio codec must be an array");if(Z.length<=0)throw new Error("Error starting dial out: audio codec array specified but empty");Z.forEach((function(se){if(typeof se!="string")throw new Error("Error starting dial out: audio codec must be a string");if(se!=="OPUS"&&se!=="PCMU"&&se!=="PCMA"&&se!=="G722")throw new Error("Error starting dial out: audio codec must be one of OPUS, PCMU, PCMA, G722")}))}};if(!v.sipUri&&!v.phoneNumber)throw new Error("Error starting dial out: either a sip uri or phone number must be provided");if(v.sipUri&&v.phoneNumber)throw new Error("Error starting dial out: only one of sip uri or phone number must be provided");
25if(v.sipUri){if(typeof v.sipUri!="string")throw new Error("Error starting dial out: sipUri must be a string");if(!v.sipUri.startsWith("sip:"))throw new Error("Error starting dial out: Invalid SIP URI, must start with 'sip:'");if(v.video&&typeof v.video!="boolean")throw new Error("Error starting dial out: video must be a boolean value");(function(Z){if(Z&&(T(Z.audio),Z.video)){if(!Array.isArray(Z.video))throw new Error("Error starting dial out: video codec must be an array");if(Z.video.length<=0)throw new Error("Error starting dial out: video codec array specified but empty");Z.video.forEach((function(se){if(typeof se!="string")throw new Error("Error starting dial out: video codec must be a string");if(se!=="H264"&&se!=="VP8")throw new Error("Error starting dial out: video codec must be H264 or VP8")}))}})(v.codecs)}if(v.phoneNumber){if(typeof v.phoneNumber!="string")throw new Error("Error starting dial out: phoneNumber must be a string");if(!/^\+\d{1,}$/.test(v.phoneNumber))throw new Error("Error starting dial out: Invalid phone number, must be valid phone number as per E.164");v.codecs&&T(v.codecs.audio)}if(v.callerId){if(typeof v.callerId!="string")throw new Error("Error starting dial out: callerId must be a string");if(v.sipUri)throw new Error("Error starting dial out: callerId not allowed with sipUri")}
25if(v.displayName){if(typeof v.displayName!="string")throw new Error("Error starting dial out: displayName must be a string");if(v.displayName.length>=200)throw new Error("Error starting dial out: displayName length must be less than 200")}if(v.userId){if(typeof v.userId!="string")throw new Error("Error starting dial out: userId must be a string");if(v.userId.length>36)throw new Error("Error starting dial out: userId length must be less than or equal to 36")}if(fm(v),v.permissions&&v.permissions.canReceive){var x=M(im.validateJSONObject(v.permissions.canReceive),2),D=x[0],$=x[1];if(!D)throw new Error($)}if(v.provider){if(v.provider!=="daily")throw new Error("Error: provider can be set only to 'daily', got: ".concat(v.provider));if(v.phoneNumber)throw new Error("Error starting dial out: provider valid only for sipUri, not phoneNumber");console.warn("(pre-beta) provider=daily is currently in pre-beta, things might break!")}return new Promise((function(Z,se){_.sendMessageToCallMachine(fe({action:"dialout-start"},v),(function(le){le.error?se(le.error):Z(le)}))}))})),function(v){return oe.apply(this,arguments)})},{key:"stopDialOut",value:function(v){var _=this;return Ne(this._callState,"stopDialOut()"),new Promise((function(T,x){_.sendMessageToCallMachine(fe({action:"dialout-stop"},v),(function(D){D.error?x(D.error):T(D)}))}))}},{key:"sipCallTransfer",value:(ne=L((function*(v){var _=this;if(Ne(this._callState,"sipCallTransfer()"),!v)throw new Error("sipCallTransfer() requires a sessionId and toEndPoint");return v.useSipRefer=!1,wm(v,"sipCallTransfer"),fm(v),new Promise((function(T,x){_.sendMessageToCallMachine(fe({action:Af},v),(function(D){D.error?x(D.error):T(D)}))}))})),function(v){return ne.apply(this,arguments)})},{key:"sipRefer",value:(z=L((function*(v){var _=this;if(Ne(this._callState,"sipRefer()"),!v)throw new Error("sessionId and toEndPoint are mandatory parameter");return v.useSipRefer=!0,wm(v,"sipRefer"),new Promise((function(T,x){_.sendMessageToCallMachine(fe({action:Af},v),(function(D){D.error?x(D.error):T(D)}))}))})),function(v){return z.apply(this,arguments)})},{key:"sendDTMF",value:(W=L((function*(v){var _=this;return Ne(this._callState,"sendDTMF()"),(function(T){var x=T.sessionId,D=T.tones;if(!x||!D)throw new Error("sessionId and tones are mandatory parameter");if(typeof x!="string"||typeof D!="string")throw new Error("sessionId and tones should be of string type");if(D.length>20)throw new Error("tones string must be upto 20 characters");var $=D.match(/[^0-9A-D*#]/g);if($&&$[0])throw new Error("".concat($[0]," is not valid DTMF tone"))})(v),new Promise((function(T,x){_.sendMessageToCallMachine(fe({action:"send-dtmf"},v),(function(D){D.error?x(D.error):T(D)}))}))})),function(v){return W.apply(this,arguments)})},{key:"getNetworkStats",value:function(){var v=this;return this._callState!==Vn?Promise.resolve(fe({stats:{latest:{}}},this._network)):new Promise((function(_){v.sendMessageToCallMachine({action:"get-calc-stats"},(function(T){_(fe(fe({},v._network),{},{stats:T.stats}))}))}))}},{key:"testWebsocketConnectivity",value:(Q=L((function*(){var v=this;if(cl(this._testCallInProgress,"testWebsocketConnectivity()"),this.needsLoad())try{yield this.load()}catch(_){return Promise.reject(_)}return new Promise((function(_,T){v.sendMessageToCallMachine({action:"test-websocket-connectivity"},(function(x){x.error?T(x.error):_(x.results)}))}))})),function(){return Q.apply(this,arguments)})},{key:"abortTestWebsocketConnectivity",value:function(){this.sendMessageToCallMachine({action:"abort-test-websocket-connectivity"})}},{key:"_validateVideoTrackForNetworkTests",value:function(v){return v?v instanceof MediaStreamTrack?!!(function(_,T){var x=T.isLocalScreenVideo;return _&&_.readyState==="live"&&!(function(D,$){return(!$.isLocalScreenVideo||$n()!=="Chrome")&&D.muted&&!CT.has(D.id)})(_,{isLocalScreenVideo:x})})(v,{isLocalScreenVideo:!1})||(console.error("Video track is not playable. This test needs a live video track."),!1):(console.error("Video track needs to be of type `MediaStreamTrack`."),!1):(console.error("Missing video track. You must provide a video track in order to run this test."),!1)}},{key:"testCallQuality",value:(G=L((function*(){var v=this;Me(),qt(this._callObjectMode,"testCallQuality()"),go(this._callMachineInitialized,"testCallQuality()",null,!0),al(this._callState,this._isPreparingToJoin,"testCallQuality()");var _=this._testCallAlreadyInProgress,T=function(D){_||(v._testCallInProgress=D)};if(T(!0),this.needsLoad())try{var x=this._callState;yield this.load(),this._callState=x}catch(D){return T(!1),Promise.reject(D)}return new Promise((function(D){v.sendMessageToCallMachine({action:"test-call-quality",dailyJsVersion:v.properties.dailyJsVersion},(function($){var Z=$.results,se=Z.result,le=o(Z,PT);if(se==="failed"){var de,Se=fe({},le);(de=le.error)!==null&&de!==void 0&&de.details?(le.error.details=JSON.parse(le.error.details),Se.error=fe(fe({},Se.error),{},{details:fe({},Se.error.details)}),Se.error.details.duringTest="testCallQuality"):(Se.error=Se.error?fe({},Se.error):{},Se.error.details={duringTest:"testCallQuality"}),v._maybeSendToSentry(Se)}T(!1),D(fe({result:se},le))}))}))})),function(){return G.apply(this,arguments)})},{key:"stopTestCallQuality",value:function(){this.sendMessageToCallMachine({action:"stop-test-call-quality"})}},{key:"testConnectionQuality",value:(V=L((function*(v){var _;
25Ae()?(console.warn("testConnectionQuality() is deprecated: use testPeerToPeerCallQuality() instead"),_=yield this.testPeerToPeerCallQuality(v)):(console.warn("testConnectionQuality() is deprecated: use testCallQuality() instead"),_=yield this.testCallQuality());var T={result:_.result,secondsElapsed:_.secondsElapsed};return _.data&&(T.data={maxRTT:_.data.maxRoundTripTime,packetLoss:_.data.avgRecvPacketLoss}),T})),function(v){return V.apply(this,arguments)})},{key:"testPeerToPeerCallQuality",value:(F=L((function*(v){var _=this;if(cl(this._testCallInProgress,"testPeerToPeerCallQuality()"),this.needsLoad())try{yield this.load()}catch(D){return Promise.reject(D)}var T=v.videoTrack,x=v.duration;if(!this._validateVideoTrackForNetworkTests(T))throw new Error("Video track error");return this._sharedTracks.videoTrackForConnectionQualityTest=T,new Promise((function(D,$){_.sendMessageToCallMachine({action:"test-p2p-call-quality",duration:x},(function(Z){Z.error?$(Z.error):D(Z.results)}))}))})),function(v){return F.apply(this,arguments)})},{key:"stopTestConnectionQuality",value:function(){Ae()?(console.warn("stopTestConnectionQuality() is deprecated: use testPeerToPeerCallQuality() and stopTestPeerToPeerCallQuality() instead"),this.stopTestPeerToPeerCallQuality()):(console.warn("stopTestConnectionQuality() is deprecated: use testCallQuality() and stopTestCallQuality() instead"),this.stopTestCallQuality())}},{key:"stopTestPeerToPeerCallQuality",value:function(){this.sendMessageToCallMachine({action:"stop-test-p2p-call-quality"})}},{key:"testNetworkConnectivity",value:(O=L((function*(v){var _=this;if(cl(this._testCallInProgress,"testNetworkConnectivity()"),this.needsLoad())try{yield this.load()}catch(T){return Promise.reject(T)}if(!this._validateVideoTrackForNetworkTests(v))throw new Error("Video track error");return this._sharedTracks.videoTrackForNetworkConnectivityTest=v,new Promise((function(T,x){_.sendMessageToCallMachine({action:"test-network-connectivity"},(function(D){D.error?x(D.error):T(D.results)}))}))})),function(v){return O.apply(this,arguments)})},{key:"abortTestNetworkConnectivity",value:function(){this.sendMessageToCallMachine({action:"abort-test-network-connectivity"})}},{key:"getCpuLoadStats",value:function(){var v=this;return new Promise((function(_){v._callState===Vn?v.sendMessageToCallMachine({action:"get-cpu-load-stats"},(function(T){_(T.cpuStats)})):_({cpuLoadState:void 0,cpuLoadStateReason:void 0,stats:{}})}))}},{key:"_validateEncodingLayerHasValidProperties",value:function(v){var _;if(!(((_=Object.keys(v))===null||_===void 0?void 0:_.length)>0))throw new Error("Empty encoding is not allowed. At least one of these valid keys should be specified:"+Object.values(sl))}},{key:"_validateVideoSendSettings",value:function(v,_){var T=v==="screenVideo"?["default-screen-video","detail-optimized","motion-optimized","motion-and-detail-balanced"]:["default-video","bandwidth-optimized","bandwidth-and-quality-balanced","quality-optimized","adaptive-2-layers","adaptive-3-layers"],x="Video send settings should be either an object or one of the supported presets: ".concat(T.join());if(typeof _=="string"){if(!T.includes(_))throw new Error(x)}else{if(d(_)!=="object")throw new Error(x);if(!_.maxQuality&&!_.encodings&&_.allowAdaptiveLayers===void 0)throw new Error("Video send settings must contain at least maxQuality, allowAdaptiveLayers or encodings attribute");if(_.maxQuality&&["low","medium","high"].indexOf(_.maxQuality)===-1)throw new Error("maxQuality must be either low, medium or high");if(_.encodings){var D=!1;switch(Object.keys(_.encodings).length){case 1:D=!_.encodings.low;break;case 2:D=!_.encodings.low||!_.encodings.medium;break;case 3:D=!_.encodings.low||!_.encodings.medium||!_.encodings.high;break;default:D=!0}if(D)throw new Error("Encodings must be defined as: low, low and medium, or low, medium and high.");_.encodings.low&&this._validateEncodingLayerHasValidProperties(_.encodings.low),_.encodings.medium&&this._validateEncodingLayerHasValidProperties(_.encodings.medium),_.encodings.high&&this._validateEncodingLayerHasValidProperties(_.encodings.high)}}}},{key:"validateUpdateSendSettings",value:function(v){var _=this;if(!v||Object.keys(v).length===0)throw new Error("Send settings must contain at least information for one track!");Object.entries(v).forEach((function(T){var x=M(T,2),D=x[0],$=x[1];_._validateVideoSendSettings(D,$)}))}},{key:"updateSendSettings",value:function(v){var _=this;return this.validateUpdateSendSettings(v),this.needsLoad()?(this._preloadCache.sendSettings=v,{sendSettings:this._preloadCache.sendSettings}
25):new Promise((function(T,x){_.sendMessageToCallMachine({action:"update-send-settings",sendSettings:v},(function(D){D.error?x(D.error):T(D.sendSettings)}))}))}},{key:"getSendSettings",value:function(){return this._sendSettings||this._preloadCache.sendSettings}},{key:"getLocalAudioLevel",value:function(){return this._localAudioLevel}},{key:"getRemoteParticipantsAudioLevel",value:function(){return this._remoteParticipantsAudioLevel}},{key:"getActiveSpeaker",value:function(){return Me(),this._activeSpeaker}},{key:"setActiveSpeakerMode",value:function(v){return Me(),this.sendMessageToCallMachine({action:"set-active-speaker-mode",enabled:v}),this}},{key:"activeSpeakerMode",value:function(){return Me(),this._activeSpeakerMode}},{key:"subscribeToTracksAutomatically",value:function(){return this._preloadCache.subscribeToTracksAutomatically}},{key:"setSubscribeToTracksAutomatically",value:function(v){return Ne(this._callState,"setSubscribeToTracksAutomatically()","Use the subscribeToTracksAutomatically configuration property."),this._preloadCache.subscribeToTracksAutomatically=v,this.sendMessageToCallMachine({action:"daily-method-subscribe-to-tracks-automatically",enabled:v}),this}},{key:"enumerateDevices",value:(E=L((function*(){var v=this;if(this._callObjectMode){var _=yield navigator.mediaDevices.enumerateDevices();return $n()==="Firefox"&&lo().major>115&&lo().major<123&&(_=_.filter((function(T){return T.kind!=="audiooutput"}))),{devices:_.map((function(T){var x=JSON.parse(JSON.stringify(T));if(!Ae()&&T.kind==="videoinput"&&T.getCapabilities){var D,$=T.getCapabilities();x.facing=($==null||(D=$.facingMode)===null||D===void 0?void 0:D.length)>=1?$.facingMode[0]:void 0}return x}))}}return new Promise((function(T){v.sendMessageToCallMachine({action:"enumerate-devices"},(function(x){T({devices:x.devices})}))}))})),function(){return E.apply(this,arguments)})},{key:"sendAppMessage",value:function(v){var _=arguments.length>1&&arguments[1]!==void 0?arguments[1]:"*";if(Ne(this._callState,"sendAppMessage()"),JSON.stringify(v).length>this._maxAppMessageSize)throw new Error("Message data too large. Max size is "+this._maxAppMessageSize);return this.sendMessageToCallMachine({action:"app-msg",data:v,to:_}),this}},{key:"addFakeParticipant",value:function(v){return Me(),Ne(this._callState,"addFakeParticipant()"),this.sendMessageToCallMachine(fe({action:"add-fake-participant"},v)),this}},{key:"setShowNamesMode",value:function(v){return wt(this._callObjectMode,"setShowNamesMode()"),Me(),v&&v!=="always"&&v!=="never"?(console.error('setShowNamesMode argument should be "always", "never", or false'),this):(this.sendMessageToCallMachine({action:"set-show-names",mode:v}),this)}},{key:"setShowLocalVideo",value:function(){var v=!(arguments.length>0&&arguments[0]!==void 0)||arguments[0];return wt(this._callObjectMode,"setShowLocalVideo()"),Me(),Ne(this._callState,"setShowLocalVideo()"),typeof v!="boolean"?(console.error("setShowLocalVideo only accepts a boolean value"),this):(this.sendMessageToCallMachine({action:"set-show-local-video",show:v}),this._showLocalVideo=v,this)}},{key:"showLocalVideo",value:function(){return wt(this._callObjectMode,"showLocalVideo()"),Me(),this._showLocalVideo}},{key:"setShowParticipantsBar",value:function(){var v=!(arguments.length>0&&arguments[0]!==void 0)||arguments[0];return wt(this._callObjectMode,"setShowParticipantsBar()"),Me(),Ne(this._callState,"setShowParticipantsBar()"),typeof v!="boolean"?(console.error("setShowParticipantsBar only accepts a boolean value"),this):(this.sendMessageToCallMachine({action:"set-show-participants-bar",show:v}),this._showParticipantsBar=v,this)}},{key:"showParticipantsBar",value:function(){return wt(this._callObjectMode,"showParticipantsBar()"),Me(),this._showParticipantsBar}},{key:"customIntegrations",value:function(){return Me(),wt(this._callObjectMode,"customIntegrations()"),this._customIntegrations}},{key:"setCustomIntegrations",value:function(v){return Me(),wt(this._callObjectMode,"setCustomIntegrations()"),Ne(this._callState,"setCustomIntegrations()"),_m(v)?(this.sendMessageToCallMachine({action:"set-custom-integrations",integrations:v}),this._customIntegrations=v,this):this}},{key:"startCustomIntegrations",value:function(v){var _=this;
25if(Me(),wt(this._callObjectMode,"startCustomIntegrations()"),Ne(this._callState,"startCustomIntegrations()"),Array.isArray(v)&&v.some((function(D){return typeof D!="string"}))||!Array.isArray(v)&&typeof v!="string")return console.error("startCustomIntegrations() only accepts string | string[]"),this;var T=typeof v=="string"?[v]:v,x=T.filter((function(D){return!(D in _._customIntegrations)}));return x.length?(console.error(`Can't find custom integration(s): "`.concat(x.join(", "),'"')),this):(this.sendMessageToCallMachine({action:"start-custom-integrations",ids:T}),this)}},{key:"stopCustomIntegrations",value:function(v){var _=this;if(Me(),wt(this._callObjectMode,"stopCustomIntegrations()"),Ne(this._callState,"stopCustomIntegrations()"),Array.isArray(v)&&v.some((function(D){return typeof D!="string"}))||!Array.isArray(v)&&typeof v!="string")return console.error("stopCustomIntegrations() only accepts string | string[]"),this;var T=typeof v=="string"?[v]:v,x=T.filter((function(D){return!(D in _._customIntegrations)}));return x.length?(console.error(`Can't find custom integration(s): "`.concat(x.join(", "),'"')),this):(this.sendMessageToCallMachine({action:"stop-custom-integrations",ids:T}),this)}},{key:"customTrayButtons",value:function(){return wt(this._callObjectMode,"customTrayButtons()"),Me(),this._customTrayButtons}},{key:"updateCustomTrayButtons",value:function(v){return wt(this._callObjectMode,"updateCustomTrayButtons()"),Me(),Ne(this._callState,"updateCustomTrayButtons()"),Tm(v)?(this.sendMessageToCallMachine({action:"update-custom-tray-buttons",btns:v}),this._customTrayButtons=v,this):(console.error("updateCustomTrayButtons only accepts a dictionary of the type ".concat(JSON.stringify(po))),this)}},{key:"theme",value:function(){return wt(this._callObjectMode,"theme()"),this.properties.theme}},{key:"setTheme",value:function(v){var _=this;return wt(this._callObjectMode,"setTheme()"),new Promise((function(T,x){try{_.validateProperties({theme:v}),_.properties.theme=fe({},v),_.sendMessageToCallMachine({action:"set-theme",theme:_.properties.theme});try{_.emitDailyJSEvent({action:Rp,theme:_.properties.theme})}catch(D){console.log("could not emit 'theme-updated'",D)}T(_.properties.theme)}catch(D){x(D)}}))}},{key:"requestFullscreen",value:(C=L((function*(){if(Me(),this._iframe&&!document.fullscreenElement&&Rf())try{(yield this._iframe.requestFullscreen)?this._iframe.requestFullscreen():this._iframe.webkitRequestFullscreen()}catch(v){console.log("could not make video call fullscreen",v)}})),function(){return C.apply(this,arguments)})},{key:"exitFullscreen",value:function(){Me(),document.fullscreenElement?document.exitFullscreen():document.webkitFullscreenElement&&document.webkitExitFullscreen()}},{key:"getSidebarView",value:(S=L((function*(){var v=this;return this._callObjectMode?(console.error("getSidebarView is not available in callObject mode"),Promise.resolve(null)):new Promise((function(_){v.sendMessageToCallMachine({action:"get-sidebar-view"},(function(T){_(T.view)}))}))})),function(){return S.apply(this,arguments)})},{key:"setSidebarView",value:function(v){return this._callObjectMode?(console.error("setSidebarView is not available in callObject mode"),this):(this.sendMessageToCallMachine({action:"set-sidebar-view",view:v}),this)}},{key:"room",value:(k=L((function*(){var v=this,_=(arguments.length>0&&arguments[0]!==void 0?arguments[0]:{}).includeRoomConfigDefaults,T=_===void 0||_;return this._accessState.access===oo||this.needsLoad()?this.properties.url?{roomUrlPendingJoin:this.properties.url}:null:new Promise((function(x){v.sendMessageToCallMachine({action:"lib-room-info",includeRoomConfigDefaults:T},(function(D){delete D.action,delete D.callbackStamp,x(D)}))}))})),function(){return k.apply(this,arguments)})},{key:"geo",value:(y=L((function*(){try{var v=yield fetch("https://gs.daily.co/_ks_/x-swsl/:");return{current:(yield v.json()).geo}}catch(_){return console.error("geo lookup failed",_),{current:""}}})),function(){return y.apply(this,arguments)})},{key:"setNetworkTopology",value:(m=L((function*(v){var _=this;return Me(),Ne(this._callState,"setNetworkTopology()"),new Promise((function(T,x){_.
25sendMessageToCallMachine({action:"set-network-topology",opts:v},(function(D){D.error?x({error:D.error}):T({workerId:D.workerId})}))}))})),function(v){return m.apply(this,arguments)})},{key:"getNetworkTopology",value:(h=L((function*(){var v=this;return new Promise((function(_,T){v.needsLoad()&&_({topology:"none"}),v.sendMessageToCallMachine({action:"get-network-topology"},(function(x){x.error?T({error:x.error}):_({topology:x.topology})}))}))})),function(){return h.apply(this,arguments)})},{key:"setPlayNewParticipantSound",value:function(v){if(Me(),typeof v!="number"&&v!==!0&&v!==!1)throw new Error("argument to setShouldPlayNewParticipantSound should be true, false, or a number, but is ".concat(v));this.sendMessageToCallMachine({action:"daily-method-set-play-ding",arg:v})}},{key:"on",value:function(v,_){return B().prototype.on.call(this,v,_)}},{key:"once",value:function(v,_){return B().prototype.once.call(this,v,_)}},{key:"off",value:function(v,_){return B().prototype.off.call(this,v,_)}},{key:"validateProperties",value:function(v){var _,T;if(v!=null&&(_=v.dailyConfig)!==null&&_!==void 0&&_.userMediaAudioConstraints){var x,D;Ae()||console.warn("userMediaAudioConstraints is deprecated. You can override constraints with inputSettings.audio.settings, found in DailyCallOptions.");var $=v.inputSettings||{};$.audio=((x=v.inputSettings)===null||x===void 0?void 0:x.audio)||{},$.audio.settings=((D=v.inputSettings)===null||D===void 0||(D=D.audio)===null||D===void 0?void 0:D.settings)||{},$.audio.settings=fe(fe({},$.audio.settings),v.dailyConfig.userMediaAudioConstraints),v.inputSettings=$,delete v.dailyConfig.userMediaAudioConstraints}if(v!=null&&(T=v.dailyConfig)!==null&&T!==void 0&&T.userMediaVideoConstraints){var Z,se;Ae()||console.warn("userMediaVideoConstraints is deprecated. You can override constraints with inputSettings.video.settings, found in DailyCallOptions.");var le=v.inputSettings||{};le.video=((Z=v.inputSettings)===null||Z===void 0?void 0:Z.video)||{},le.video.settings=((se=v.inputSettings)===null||se===void 0||(se=se.video)===null||se===void 0?void 0:se.settings)||{},le.video.settings=fe(fe({},le.video.settings),v.dailyConfig.userMediaVideoConstraints),v.inputSettings=le,delete v.dailyConfig.userMediaVideoConstraints}for(var de in v)if(gi[de]){if(gi[de].validate&&!gi[de].validate(v[de],this))throw new Error("property '".concat(de,"': ").concat(gi[de].help))}else console.warn("Ignoring unrecognized property '".concat(de,"'")),delete v[de]}},{key:"assembleMeetingUrl",value:function(){var v,_,T=fe(fe({},this.properties),{},{emb:this.callClientId,embHref:encodeURIComponent(window.location.href),proxy:(v=this.properties.dailyConfig)!==null&&v!==void 0&&v.proxyUrl?encodeURIComponent((_=this.properties.dailyConfig)===null||_===void 0?void 0:_.proxyUrl):void 0}),x=T.url.match(/\?/)?"&":"?";return T.url+x+Object.keys(gi).filter((function(D){return gi[D].queryString&&T[D]!==void 0})).map((function(D){return"".concat(gi[D].queryString,"=").concat(T[D])})).join("&")}},{key:"needsLoad",value:function(){return[Fc,kp,_n,Cn].includes(this._callState)}},{key:"sendMessageToCallMachine",value:function(v,_){if(this._destroyed&&(this._logUseAfterDestroy(),this.strictMode))throw new Error("Use after destroy");this._messageChannel.sendMessageToCallMachine(v,_,this.callClientId,this._iframe)}},{key:"forwardPackagedMessageToCallMachine",value:function(v){this._messageChannel.forwardPackagedMessageToCallMachine(v,this._iframe,this.callClientId)}},{key:"addListenerForPackagedMessagesFromCallMachine",value:function(v){return this._messageChannel.addListenerForPackagedMessagesFromCallMachine(v,this.callClientId)}},{key:"removeListenerForPackagedMessagesFromCallMachine",value:function(v){this._messageChannel.removeListenerForPackagedMessagesFromCallMachine(v)}},{key:"handleMessageFromCallMachine",value:function(v){switch(v.action){case Ap:this.sendMessageToCallMachine(fe({action:Mp},this.properties));break;case"call-machine-initialized":this._callMachineInitialized=!0;var _={action:ao,level:"log",code:1011,stats:{event:"bundle load",time:this._bundleLoadTime==="no-op"?0:this._bundleLoadTime,preLoaded:this._bundleLoadTime==="no-op",url:Je(this.properties.dailyConfig)}
vendor: 6,477 bytes, line 25
25};this.sendMessageToCallMachine(_),this._delayDuplicateInstanceLog&&this._logDuplicateInstanceAttempt();break;case jc:this._loadedCallback&&(this._loadedCallback(),this._loadedCallback=null),this.emitDailyJSEvent(v);break;case Np:var T,x=fe({},v);delete x.internal,this._maxAppMessageSize=((T=v.internal)===null||T===void 0?void 0:T._maxAppMessageSize)||Gc,this._joinedCallback&&(this._joinedCallback(v.participants),this._joinedCallback=null),this.emitDailyJSEvent(x);break;case Up:case jp:if(this._callState===_n)return;if(v.participant&&v.participant.session_id){var D=v.participant.local?"local":v.participant.session_id;if(this._callObjectMode){var $=this._callMachine().store;Hf(v.participant,$),Kf(v.participant,$),zf(v.participant,this._participants[D],$)}try{this.maybeParticipantTracksStopped(this._participants[D],v.participant),this.maybeParticipantTracksStarted(this._participants[D],v.participant),this.maybeEventRecordingStopped(this._participants[D],v.participant),this.maybeEventRecordingStarted(this._participants[D],v.participant)}catch(LT){console.error("track events error",LT)}this.compareEqualForParticipantUpdateEvent(v.participant,this._participants[D])||(this._participants[D]=fe({},v.participant),this.toggleParticipantAudioBasedOnNativeAudioFocus(),this.emitDailyJSEvent(v))}break;case Bp:if(v.participant&&v.participant.session_id){var Z=this._participants[v.participant.session_id];Z&&this.maybeParticipantTracksStopped(Z,null),delete this._participants[v.participant.session_id],this.emitDailyJSEvent(v)}break;case qp:ie(this._participantCounts,v.participantCounts)||(this._participantCounts=v.participantCounts,this.emitDailyJSEvent(v));break;case Vp:var se={access:v.access};v.awaitingAccess&&(se.awaitingAccess=v.awaitingAccess),ie(this._accessState,se)||(this._accessState=se,this.emitDailyJSEvent(v));break;case $p:if(v.meetingSession){this._meetingSessionSummary=v.meetingSession,this.emitDailyJSEvent(v);var le=fe(fe({},v),{},{action:"meeting-session-updated"});this.emitDailyJSEvent(le)}break;case Wc:var de;this._iframe&&!v.preserveIframe&&(this._iframe.src=""),this._updateCallState(Cn),this.resetMeetingDependentVars(),this._loadedCallback&&(this._loadedCallback(v.errorMsg),this._loadedCallback=null),v.preserveIframe;var Se=o(v,AT);Se!=null&&(de=Se.error)!==null&&de!==void 0&&de.details&&(Se.error.details=JSON.parse(Se.error.details)),this._maybeSendToSentry(v),this._joinedCallback&&(this._joinedCallback(null,Se),this._joinedCallback=null),this.emitDailyJSEvent(Se);break;case Fp:this._callState!==Cn&&this._updateCallState(_n),this.resetMeetingDependentVars(),this._resolveLeave&&(this._resolveLeave(),this._resolveLeave=null),this.emitDailyJSEvent(v);break;case"selected-devices-updated":v.devices&&this.emitDailyJSEvent(v);break;case ff:var on=v.state,vi=v.threshold,Qr=v.quality,st=on.state,Lt=on.reasons;st===this._network.networkState&&ie(Lt,this._network.networkStateReasons)&&vi===this._network.threshold&&Qr===this._network.quality||(this._network.networkState=st,this._network.networkStateReasons=Lt,this._network.quality=Qr,this._network.threshold=vi,v.networkState=st,Lt.length&&(v.networkStateReasons=Lt),delete v.state,this.emitDailyJSEvent(v));break;case gf:v&&v.cpuLoadState&&this.emitDailyJSEvent(v);break;case vf:v&&v.faceCounts!==void 0&&this.emitDailyJSEvent(v);break;case hf:var yi=v.activeSpeaker;this._activeSpeaker.peerId!==yi.peerId&&(this._activeSpeaker.peerId=yi.peerId,this.emitDailyJSEvent({action:v.action,activeSpeaker:this._activeSpeaker}));break;case"show-local-video-changed":if(this._callObjectMode)return;var Xr=v.show;this._showLocalVideo=Xr,this.emitDailyJSEvent({action:v.action,show:Xr});break;case pf:var vo=v.enabled;this._activeSpeakerMode!==vo&&(this._activeSpeakerMode=vo,this.emitDailyJSEvent({action:v.action,enabled:this._activeSpeakerMode}));break;case Gp:case Jp:case Hp:this._waitingParticipants=v.allWaitingParticipants,this.emitDailyJSEvent({action:v.action,participant:v.participant});break;case _f:ie(this._receiveSettings,v.receiveSettings)||(this._receiveSettings=v.receiveSettings,this.emitDailyJSEvent({action:v.action,receiveSettings:v.receiveSettings}));break;case Vc:this._maybeUpdateInputSettings(v.inputSettings);break;case"send-settings-updated":ie(this._sendSettings,v.sendSettings)||(this._sendSettings=v.sendSettings,this._preloadCache.sendSettings=null,this.emitDailyJSEvent({action:v.action,sendSettings:v.sendSettings}));break;case"local-audio-level":this._localAudioLevel=v.audioLevel,this._preloadCache.localAudioLevelObserver=null,this.emitDailyJSEvent(v);break;case"remote-participants-audio-level":this._remoteParticipantsAudioLevel=v.participantsAudioLevel,this._preloadCache.remoteParticipantsAudioLevelObserver=null,this.emitDailyJSEvent(v);break;case of:var dl=v.session_id;this._rmpPlayerState[dl]=v.playerState,this.emitDailyJSEvent(v);break;case cf:delete this._rmpPlayerState[v.session_id],this.emitDailyJSEvent(v);break;case af:var Nm=v.session_id,Fm=this._rmpPlayerState[Nm];Fm&&this.compareEqualForRMPUpdateEvent(Fm,v.remoteMediaPlayerState)||(this._rmpPlayerState[Nm]=v.remoteMediaPlayerState,this.emitDailyJSEvent(v));break;case"custom-button-click":case"sidebar-view-changed":case"pip-started":case"pip-stopped":this.emitDailyJSEvent(v);break;case Wp:var DT=this._meetingSessionState.topology!==(v.meetingSessionState&&v.meetingSessionState.topology);this._meetingSessionState=ul(v.meetingSessionState,this._callObjectMode),(this._callObjectMode||DT)&&this.emitDailyJSEvent(v);break;case lf:this._isScreenSharing=!0,this.emitDailyJSEvent(v);break;case uf:case df:this._isScreenSharing=!1,this.emitDailyJSEvent(v);break;case Bc:case qc:case Zp:case ef:case tf:case Yp:case Qp:case Xp:case Dp:case Lp:case rf:case sf:case"test-completed":case mf:case nf:case yf:case bf:case kf:case Sf:case $c:case Tf:case"dialin-ready":case"dialin-connected":case"dialin-error":case"dialin-stopped":case"dialin-warning":case"dialout-connected":case"dialout-answered":case"dialout-error":case"dialout-stopped":case"dialout-warning":this.emitDailyJSEvent(v);break;case"request-fullscreen":this.requestFullscreen();break;case"request-exit-fullscreen":this.exitFullscreen()}}},{key:"maybeEventRecordingStopped",value:function(v,_){var T="record";v&&(_.local||_[T]!==!1||v[T]===_[T]||this.emitDailyJSEvent({action:qc}))}},{key:"maybeEventRecordingStarted",value:function(v,_){var T="record";v&&(_.local||_[T]!==!0||v[T]===_[T]||this.emitDailyJSEvent({action:Bc}
25))}},{key:"_trackStatePlayable",value:function(v){return!(!v||v.state!==Tp)}},{key:"_trackChanged",value:function(v,_){return v?.id!==_?.id}},{key:"maybeEventTrackStopped",value:function(v,_,T){var x,D,$=(x=_?.tracks[v])!==null&&x!==void 0?x:null,Z=(D=T?.tracks[v])!==null&&D!==void 0?D:null,se=$?.track;if(se){var le=this._trackStatePlayable($),de=this._trackStatePlayable(Z),Se=this._trackChanged(se,Z?.track);le&&(de&&!Se||this.emitDailyJSEvent({action:zp,track:se,participant:T??_,type:v}))}}},{key:"maybeEventTrackStarted",value:function(v,_,T){var x,D,$=(x=_?.tracks[v])!==null&&x!==void 0?x:null,Z=(D=T?.tracks[v])!==null&&D!==void 0?D:null,se=Z?.track;if(se){var le=this._trackStatePlayable($),de=this._trackStatePlayable(Z),Se=this._trackChanged($?.track,se);de&&(le&&!Se||this.emitDailyJSEvent({action:Kp,track:se,participant:T,type:v}))}}},{key:"maybeParticipantTracksStopped",value:function(v,_){if(v)for(var T in v.tracks)this.maybeEventTrackStopped(T,v,_)}},{key:"maybeParticipantTracksStarted",value:function(v,_){if(_)for(var T in _.tracks)this.maybeEventTrackStarted(T,v,_)}},{key:"compareEqualForRMPUpdateEvent",value:function(v,_){var T,x;return v.state===_.state&&((T=v.settings)===null||T===void 0?void 0:T.volume)===((x=_.settings)===null||x===void 0?void 0:x.volume)}},{key:"emitDailyJSEvent",value:function(v){try{v.callClientId=this.callClientId,this.emit(v.action,v)}catch(_){console.log("could not emit",v,_)}}},{key:"compareEqualForParticipantUpdateEvent",value:function(v,_){return!(!ie(v,_)||v.videoTrack&&_.videoTrack&&(v.videoTrack.id!==_.videoTrack.id||v.videoTrack.muted!==_.videoTrack.muted||v.videoTrack.enabled!==_.videoTrack.enabled)||v.audioTrack&&_.audioTrack&&(v.audioTrack.id!==_.audioTrack.id||v.audioTrack.muted!==_.audioTrack.muted||v.audioTrack.enabled!==_.audioTrack.enabled))}},{key:"nativeUtils",value:function(){return Ae()?typeof DailyNativeUtils>"u"?(console.warn("in React Native, DailyNativeUtils is expected to be available"),null):DailyNativeUtils:null}},{key:"updateIsPreparingToJoin",value:function(v){this._updateCallState(this._callState,v)}},{key:"_updateCallState",value:function(v){var _=arguments.length>1&&arguments[1]!==void 0?arguments[1]:this._isPreparingToJoin;if(v!==this._callState||_!==this._isPreparingToJoin){var T=this._callState,x=this._isPreparingToJoin;this._callState=v,this._isPreparingToJoin=_;var D=this._callState===Vn;this.updateShowAndroidOngoingMeetingNotification(D);var $=mo(T,x),Z=mo(this._callState,this._isPreparingToJoin);$!==Z&&(this.updateKeepDeviceAwake(Z),this.updateDeviceAudioMode(Z),this.updateNoOpRecordingEnsuringBackgroun
vendor: 1,530 bytes, line 25
25dContinuity(Z))}}},{key:"resetMeetingDependentVars",value:function(){this._participants={},this._participantCounts=um,this._waitingParticipants={},this._activeSpeaker={},this._activeSpeakerMode=!1,this._didPreAuth=!1,this._accessState={access:oo},this._finalSummaryOfPrevSession=this._meetingSessionSummary,this._meetingSessionSummary={},this._meetingSessionState=ul(lm,this._callObjectMode),this._isScreenSharing=!1,this._receiveSettings={},this._inputSettings=void 0,this._sendSettings={},this._localAudioLevel=0,this._isLocalAudioLevelObserverRunning=!1,this._remoteParticipantsAudioLevel={},this._isRemoteParticipantsAudioLevelObserverRunning=!1,this._maxAppMessageSize=Gc,this._callMachineInitialized=!1,this._bundleLoadTime=void 0,this._preloadCache}},{key:"updateKeepDeviceAwake",value:function(v){Ae()&&this.nativeUtils().setKeepDeviceAwake(v,this.callClientId)}},{key:"updateDeviceAudioMode",value:function(v){if(Ae()&&!this.disableReactNativeAutoDeviceManagement("audio")){var _=v?this._nativeInCallAudioMode:"idle";this.nativeUtils().setAudioMode(_)}}},{key:"updateShowAndroidOngoingMeetingNotification",value:function(v){if(Ae()&&this.nativeUtils().setShowOngoingMeetingNotification){var _,T,x,D;if(this.properties.reactNativeConfig&&this.properties.reactNativeConfig.androidInCallNotification){var $=this.properties.reactNativeConfig.androidInCallNotification;_=$.title,T=$.subtitle,x=$.iconName,D=$.disableForCustomOverride}D&&(v=!1),this.nativeUtils().setShowOngoingMeetingNotification(v,_,T,x,this.callClientId)}}}
25,{key:"updateNoOpRecordingEnsuringBackgroundContinuity",value:function(v){Ae()&&this.nativeUtils().enableNoOpRecordingEnsuringBackgroundContinuity&&this.nativeUtils().enableNoOpRecordingEnsuringBackgroundContinuity(v)}},{key:"toggleParticipantAudioBasedOnNativeAudioFocus",value:function(){var v;if(Ae()){var _=(v=this._callMachine())===null||v===void 0||(v=v.store)===null||v===void 0?void 0:v.getState();for(var T in _?.streams){var x=_.streams[T];x&&x.pendingTrack&&x.pendingTrack.kind==="audio"&&(x.pendingTrack.enabled=this._hasNativeAudioFocus)}}}},{key:"disableReactNativeAutoDeviceManagement",value:function(v){return this.properties.reactNativeConfig&&this.properties.reactNativeConfig.disableAutoDeviceManagement&&this.properties.reactNativeConfig.disableAutoDeviceManagement[v]}},{key:"absoluteUrl",value:function(v){if(v!==void 0){var _=document.createElement("a");return _.href=v,_.href}}},{key:"sayHello",value:function(){var v="hello, world.";return console.log(v),v}},{key:"_logUseAfterDestroy",value:function(){var v=Object.values(mi)[0];if(this.needsLoad())if(v&&!v.needsLoad()){var _={action:ao,level:"error",code:this.strictMode?9995:9997};v.sendMessageToCallMachine(_)}else this.strictMode||console.error("You are are attempting to use a call instance that was previously destroyed, which is unsupported. Please remove `strictMode: false` from your constructor properties to enable strict mode to track down and fix this unsupported usage.");else{var T={action:ao,level:"error",code:this.strictMode?9995:9997};this._messageChannel.sendMessageToCallMachine(T,null,this.callClientId,this._iframe)}}},{key:"_logDuplicateInstanceAttempt",value:function(){for(var v=0,_=Object.values(mi);v<_.length;v++){var T=_[v];T._callMachineInitialized?(T.sendMessageToCallMachine({action:ao,level:"warn",code:this.allowMultipleCallInstances?9993:9992}),T._delayDuplicateInstanceLog=!1):T._delayDuplicateInstanceLog=!0}}},{key:"_maybeSendToSentry",value:function(v){var _,T,x,D;if(!((_=v.error)!==null&&_!==void 0&&_.type&&(![Pp,Ep,Uc].includes(v.error.type)||v.error.type===Uc&&v.error.msg.includes("deleted")))){var $=(T=this.properties)!==null&&T!==void 0&&T.url?new URL(this.properties.url):void 0,Z="production";$&&$.host.includes(".staging.daily")&&(Z="staging");var se,le,de,Se,on,vi=CS({}).filter((function(dl){return!["BrowserApiErrors","Breadcrumbs","GlobalHandlers"].includes(dl.name)})),Qr=new IS({dsn:"https://[email protected]/168844",transport:LS,stackParser:BS,integrations:vi,environment:Z}),st=new kn;if(st.setClient(Qr),Qr.init(),this.session_id&&st.setExtra("sessionId",this.session_id),this.properties){var Lt=fe({},this.properties);Lt.userName=Lt.userName?"[Filtered]":void 0,Lt.userData=Lt.userData?"[Filtered]":void 0,Lt.token=Lt.token?"[Filtered]":void 0,st.setExtra("properties",Lt)}if($){var yi=$.searchParams.get("domain");if(!yi){var Xr=$.host.match(/(.*?)\./);yi=Xr&&Xr[1]||""}yi&&st.setTag("domain",yi)}v.error&&(st.setTag("fatalErrorType",v.error.type),st.setExtra("errorDetails",v.error.details),!((se=v.error.details)===null||se===void 0)&&se.uri&&st.setTag("serverAddress",v.error.details.uri),!((le=v.error.details)===null||le===void 0)&&le.workerGroup&&st.setTag("workerGroup",v.error.details.workerGroup),!((de=v.error.details)===null||de===void 0)&&de.geoGroup&&st.setTag("geoGroup",v.error.details.geoGroup),!((Se=v.error.details)===null||Se===void 0)&&Se.on&&st.setTag("connectionAttempt",v.error.details.on),(on=v.error.details)!==null&&on!==void 0&&on.bundleUrl&&(st.setTag("bundleUrl",v.error.details.bundleUrl),st.setTag("bundleError",v.error.details.sourceError.type))),st.setTags({callMode:this._callObjectMode?Ae()?"reactNative":(x=this.properties)!==null&&x!==void 0&&(x=x.dailyConfig)!==null&&x!==void 0&&(x=x.callMode)!==null&&x!==void 0&&x.includes("prebuilt")?this.properties.dailyConfig.callMode:"custom":"prebuilt-frame",version:c.version()});var vo=((D=v.error)===null||D===void 0?void 0:D.msg)||v.errorMsg;st.captureException(new Error(vo))}}},{key:"_callMachine",value:function(){var v;return(v=window._daily)===null||v===void 0||(v=v.instances)===null||v===void 0||(v=v[this.callClientId])===null||v===void 0?void 0:v.callMachine}},{key:"_maybeUpdateInputSettings",value:function(v){if(!ie(this._inputSettings,v)){var _=this._getInputSettings();this._inputSettings=v;var T=this._getInputSettings();ie(_,T)||this.emitDailyJSEvent({action:Vc,inputSettings:T})}}}],[{key:"supportedBrowser",value:function(){if(Ae())return{supported:!0,mobile:!0,name:"React Native",version:null,supportsScreenShare:!0,supportsSfu:!0,supportsVideoProcessing:!1,supportsAudioProcessing:!1};var v=ae().getParser(Dt());return{supported:!!Yc(),mobile:v.getPlatformType()==="mobile",name:v.getBrowserName(),version:v.getBrowserVersion(),supportsFullscreen:!!Rf(),supportsScreenShare:!!(navigator&&navigator.mediaDevices&&navigator.mediaDevices.getDisplayMedia&&((function(_,T){if(!_||!T)return!0;switch(_){case"Chrome":return T.major>=75;case"Safari":return RTCRtpTransceiver.prototype.hasOwnProperty("currentDirection")&&!(T.major===13&&T.minor===0&&T.point===0);case"Firefox":return T.major>=67}return!0})($n(),lo())||Ae())),supportsSfu:!!Yc(),supportsVideoProcessing:If(),supportsAudioProcessing:Of()}}},{key:"version",value:function(){return"0.87.0"}},{key:"createCallObject",value:function(){var v=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};return v.layout="none",new c(null,v)}},{key:"wrap",value:function(v){var _=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{};if(Me(),!v||!v.contentWindow||typeof v.src!="string")throw new Error("DailyIframe::Wrap needs an iframe-like first argument");return _.layout||(_.customLayout?_.layout="custom-v1":_.layout="browser"),new c(v,_)}},{key:"createFrame",value:function(v,_){var T,x;Me(),v&&_?(T=v,x=_):v&&v.append?(T=v,x={}):(T=document.body,x=v||{});var D=x.iframeStyle;D||(D=T===document.body?{position:"fixed",border:"1px solid black",backgroundColor:"white",width:"375px",height:"450px",right:"1em",bottom:"1em"}:{border:0,width:"100%",height:"100%"});var $=document.createElement("iframe");window.navigator&&window.navigator.userAgent.match(/Chrome\/61\./)?$.allow="microphone, camera":$.allow="microphone; camera; autoplay; display-capture; screen-wake-lock; compute-pressure;",$.style.visibility="hidden",T.appendChild($),$.style.visibility=null,Object.keys(D).forEac
25h((function(Z){return $.style[Z]=D[Z]})),x.layout||(x.customLayout?x.layout="custom-v1":x.layout="browser");try{return new c($,x)}catch(Z){throw T.removeChild($),Z}}},{key:"createTransparentFrame",value:function(){var v=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};Me();var _=document.createElement("iframe");return _.allow="microphone; camera; autoplay",_.style.cssText=` 26 position: fixed; 27 top: 0; 28 left: 0; 29 width: 100%; 30 height: 100%; 31 border: 0; 32 pointer-events: none; 33 `,document.body.appendChild(_),v.layout||(v.layout="custom-v1"),c.wrap(_,v)}},{key:"getCallInstance",value:function(){var v=arguments.length>0&&arguments[0]!==void 0?arguments[0]:void 0;return v?mi[v]:Object.values(mi)[0]}}]);var h,m,y,k,S,C,E,O,F,V,G,Q,W,z,ne,oe,ue,me,he,we,qe,Vt,Et,En,sn,Pn,nr,ir,rr,sr,Am,Mm,Rm,Im,Om,Dm,Lm,xm})(B());function fm(u){if(u.extension){if(typeof u.extension!="string")throw new Error("Error starting dial out: extension must be a string");if(u.extension.length>20)throw new Error("Error starting dial out: extension length must be less than or equal to 20")}if(u.waitBeforeExtensionDialSec){if(typeof u.waitBeforeExtensionDialSec!="number")throw new Error("Error starting dial out: waitBeforeExtensionDialSec must be a number");if(u.waitBeforeExtensionDialSec>60)throw new Error("Error starting dial out: waitBeforeExtensionDialSec must be less than or equal to 60");if(!u.extension)throw new Error("Error starting dial out: waitBeforeExtensionDialSec requires a phoneNumber and extension")}}function tr(u,c){var h={};for(var m in u)if(u[m]instanceof MediaStreamTrack)console.warn("MediaStreamTrack found in props or cache.",m),h[m]=wn;else if(m==="dailyConfig"){if(u[m].modifyLocalSdpHook){var y=window._daily.instances[c].customCallbacks||{};y.modifyLocalSdpHook=u[m].modifyLocalSdpHook,window._daily.instances[c].customCallbacks=y,delete u[m].modifyLocalSdpHook}if(u[m].modifyRemoteSdpHook){var k=window._daily.instances[c].customCallbacks||{};k.modifyRemoteSdpHook=u[m].modifyRemoteSdpHook,window._daily.instances[c].customCallbacks=k,delete u[m].modifyRemoteSdpHook}h[m]=u[m]}else h[m]=u[m];return h}function Ne(u){var c=arguments.length>2?arguments[2]:void 0;if(u!==Vn){var h="".concat(arguments.length>1&&arguments[1]!==void 0?arguments[1]:"This daily-js method"," only supported after join.");throw c&&(h+=" ".concat(c)),console.error(h),new Error(h)}}function mo(u,c){return[so,Vn].includes(u)||c}function al(u,c){var h=arguments.length>2&&arguments[2]!==void 0?arguments[2]:"This daily-js method",m=arguments.length>3?arguments[3]:void 0;if(mo(u,c)){var y="".concat(h," not supported after joining a meeting.");throw m&&(y+=" ".concat(m)),console.error(y),new Error(y)}}function go(u){var c=arguments.length>2?arguments[2]:void 0;if(!u){var h="".concat(arguments.length>1&&arguments[1]!==void 0?arguments[1]:"This daily-js method",arguments.length>3&&arguments[3]!==void 0&&arguments[3]?" requires preAuth() or startCamera() to initialize call state.":" requires preAuth(), startCamera(), or join() to initialize call state.");throw c&&(h+=" ".concat(c)),console.error(h),new Error(h)}}function cl(u){if(u){var c="A pre-call quality test is in progress. Please try ".concat(arguments.length>1&&arguments[1]!==void 0?arguments[1]:"This daily-js method"," again once testing has completed. Use stopTestCallQuality() to end it early.");throw console.error(c),new Error(c)}}function qt(u){if(!u){var c="".concat(arguments.length>1&&arguments[1]!==void 0?arguments[1]:"This daily-js method"," is only supported on custom callObject instances");throw console.error(c),new Error(c)}}function wt(u){if(u){var c="".concat(arguments.length>1&&arguments[1]!==void 0?arguments[1]:"This daily-js method"," is only supported as part of Daily's Prebuilt");throw console.error(c),new Error(c)}}function Me(){if(Ae())throw new Error("This daily-js method is not currently supported in React Native")}function Yr(){if(!Ae())throw new Error("This daily-js method is only supported in React Native")}function mm(u){if(u===void 0)return!0;var c;if(typeof u=="string")c=u;else try{c=JSON.stringify(u),ie(JSON.parse(c),u)||console.warn("The userData provided will be modified when serialized.")}catch(h){throw Error("userData must be serializable to JSON: ".concat(h))}if(c.length>4096)throw Error("userData is too large (".concat(c.length," characters). Maximum size suppported is ").concat(4096,"."));return!0}function gm(u,c){for(var h=c.allowAllParticipantsKey,m=function(V){var G=["local"];return h||G.push("*"),V&&!G.includes(V)},y=function(V){return!!(V.layer===void 0||Number.isInteger(V.layer)&&V.layer>=0||V.layer==="inherit")},k=function(V){return!(!V||V.video&&!y(V.video)||V.screenVideo&&!y(V.screenVideo))},S=0,C=Object.entries(u);S<C.length;S++){var E=M(C[S],2),O=E[0],F=E[1];if(!m(O)||!k(F))return!1}return!0}function vm(u){if(d(u)!=="object")return!1;for(var c=0,h=Object.entries(u);c<h.length;c++){var m=M(h[c],2),y=m[0],k=m[1];switch(y){case"video":if(d(k)!=="object")return!1;for(var S=0,C=Object.entries(k);S<C.length;S++){var E=M(C[S],2),O=E[0],F=E[1];switch(O){case"processor":if(!OT(F))return!1;break;case"settings":if(!bm(F))return!1;break;default:return!1}}break;case"audio":if(d(k)!=="object")return!1;for(var V=0,G=Object.entries(k);V<G.length;V++){var Q=M(G[V],2),W=Q[0],z=Q[1];switch(W){case"processor":if(!IT(z))return!1;break;case"settings":if(!bm(z))return!1;break;default:return!1}}break;default:return!1}}return!0}function ym(u,c,h){var m,y=[];u.video&&u.video.processor&&(If((m=c?.useLegacyVideoProcessor)!==null&&m!==void 0&&m)||(u.video.settings?delete u.video.processor:delete u.video,y.push("video"))),u.audio&&u.audio.processor&&(Of()||(u.audio.settings?delete u.audio.processor:delete u.audio,y.push("audio"))),y.length>0&&console.error("Ignoring settings for browser- or platform-unsupported input processor(s): ".concat(y.join(", "))),u.audio&&u.audio.settings&&(u.audio.settings.customTrack?(h.audioTrack=u.audio.settings.customTrack,u.audio.settings={customTrack:wn}):delete h.audioTrack),u.video&&u.video.settings&&(u.video.settings.customTrack?(h.videoTrack=u.video.settings.customTrack,u.video.settings={customTrack:wn}):delete h.videoTrack)}function IT(u){if(Ae())return console.warn("Video processing is not yet supported in React Native"),!1;var c,h=["type"];return!(!u||d(u)!=="object"||(Object.keys(u).filter((function(m){return!h.includes(m)}
33)).forEach((function(m){console.warn("invalid key inputSettings -> audio -> processor : ".concat(m)),delete u[m]})),c=u.type,typeof c!="string"||!Object.values(Pf).includes(c)&&(console.error("inputSettings audio processor type invalid"),1)))}function OT(u){if(Ae())return console.warn("Video processing is not yet supported in React Native"),!1;var c,h=["type","config"];return!u||d(u)!=="object"||typeof(c=u.type)!="string"||!Object.values(co).includes(c)&&(console.error("inputSettings video processor type invalid"),1)||u.config&&(d(u.config)!=="object"||!(function(m,y){var k=Object.keys(y);if(k.length===0)return!0;var S="invalid object in inputSettings -> video -> processor -> config";switch(m){case co.BGBLUR:return k.length>1||k[0]!=="strength"?(console.error(S),!1):!(typeof y.strength!="number"||y.strength<=0||y.strength>1||isNaN(y.strength))||(console.error("".concat(S,"; expected: {0 < strength <= 1}, got: ").concat(y.strength)),!1);case co.BGIMAGE:return!(y.source!==void 0&&!(function(C){return C.source==="default"?(C.type="default",!0):C.source instanceof ArrayBuffer||(mt(C.source)?(C.type="url",!!(function(F){var V=new URL(F),G=V.pathname;if(V.protocol==="data:")try{var Q=G.substring(G.indexOf(":")+1,G.indexOf(";")).split("/")[1];return Kc.includes(Q)}catch(z){return console.error("failed to deduce blob content type",z),!1}var W=G.split(".").at(-1).toLowerCase().trim();return Kc.includes(W)})(C.source)||(console.error("invalid image type; supported types: [".concat(Kc.join(", "),"]")),!1)):(E=C.source,O=Number(E),isNaN(O)||!Number.isInteger(O)||O<=0||O>10?(console.error("invalid image selection; must be an int, > 0, <= ".concat(10)),!1):(C.type="daily-preselect",!0)));var E,O})(y));default:return!0}})(u.type,u.config))?!1:(Object.keys(u).filter((function(m){return!h.includes(m)})).forEach((function(m){console.warn("invalid key inputSettings -> video -> processor : ".concat(m)),delete u[m]})),!0)}function bm(u){return d(u)==="object"&&(!u.customTrack||u.customTrack instanceof MediaStreamTrack)}function ll(){var u=Object.values(co).join(" | "),c=Object.values(Pf).join(" | ");return"inputSettings must be of the form: { video?: { processor?: { type: [ ".concat(u," ], config?: {} } }, audio?: { processor: {type: [ ").concat(c," ] } } }")}function km(u){var c=u.allowAllParticipantsKey;return"receiveSettings must be of the form { [<remote participant id> | ".concat(Cp).concat(c?' | "'.concat(wp,'"'):"","]: ")+'{ [video: [{ layer: [<non-negative integer> | "inherit"] } | "inherit"]], [screenVideo: [{ layer: [<non-negative integer> | "inherit"] } | "inherit"]] }}}'}function Sm(){return"customIntegrations should be an object of type ".concat(JSON.stringify(ol),".")}function Tm(u){if(u&&d(u)!=="object"||Array.isArray(u))return console.error("customTrayButtons should be an Object of the type ".concat(JSON.stringify(po),".")),!1;if(u)for(var c=0,h=Object.entries(u);c<h.length;c++)for(var m=M(h[c],1)[0],y=0,k=Object.entries(u[m]);y<k.length;y++){var S=M(k[y],2),C=S[0],E=S[1],O=po.id[C];if(!O)return console.error("customTrayButton does not support key ".concat(C)),!1;switch(C){case"iconPath":case"iconPathDarkMode":if(!mt(E))return console.error("customTrayButton ".concat(C," should be a url.")),!1;break;case"visualState":if(!["default","sidebar-open","active"].includes(E))return console.error("customTrayButton ".concat(C," should be ").concat(O,". Got: ").concat(E)),!1;break;default:if(d(E)!==O)return console.error("customTrayButton ".concat(C," should be a ").concat(O,".")),!1}}return!0}function _m(u){if(!u||u&&d(u)!=="object"||Array.isArray(u))return console.error(Sm()),!1;for(var c=function(V){return"".concat(V," should be ").concat(ol.id[V])},h=function(V,G){return console.error("customIntegration ".concat(V,": ").concat(G))},m=0,y=Object.entries(u);m<y.length;m++){var k=M(y[m],1)[0];if(!("label"in u[k]))return h(k,"label is required"),!1;if(!("location"in u[k]))return h(k,"location is required"),!1;if(!("src"in u[k])&&!("srcdoc"in u[k]))return h(k,"src or srcdoc is required"),!1;for(var S=0,C=Object.entries(u[k]);S<C.length;S++){var E=M(C[S],2),O=E[0],F=E[1];switch(O){case"allow":case"csp":case"name":case"referrerPolicy":case"sandbox":if(typeof F!="string")return h(k,c(O)),!1;break;case"iconURL":if(!mt(F))return h(k,"".concat(O," should be a url")),!1;break;case"src":if("srcdoc"in u[k])return h(k,"cannot have both src and srcdoc"),!1;if(!mt(F))return h(k,'src "'.concat(F,'" is not a valid URL')),!1;break;case"srcdoc":if("src"in u[k])return h(k,"cannot have both src and srcdoc"),!1;if(typeof F!="string")return h(k,c(O)),!1;break;case"location":if(!["main","sidebar"].includes(F))return h(k,c(O)),!1;break;case"controlledBy":if(F!=="*"&&F!=="owners"&&(!Array.isArray(F)||F.some((function(V){return typeof V!="string"}))))return h(k,c(O)),!1;break;case"shared":if((!Array.isArray(F)||F.some((function(V){return typeof V!="string"})))&&F!=="owners"&&typeof F!="boolean")return h(k,c(O)),!1;break;default:if(!ol.id[O])return console.error("customIntegration does not support key ".concat(O)),!1}}}return!0}function Cm(u,c){if(c===void 0)return!1;switch(d(c)){case"string":return d(u)===c;case"object":if(d(u)!=="object")return!1;for(var h in u)if(!Cm(u[h],c[h]))return!1;return!0;default:return!1}}function wm(u,c){var h=u.sessionId,m=u.toEndPoint,y=u.callerId,k=u.useSipRefer;if(!h||!m)throw new Error("".concat(c,"() requires a sessionId and toEndPoint"));if(typeof h!="string"||typeof m!="string")throw new Error("Invalid paramater: sessionId and toEndPoint must be of type string");if(k&&!m.startsWith("sip:"))throw new Error('"toEndPoint" must be a "sip" address');
33if(!m.startsWith("sip:")&&!m.startsWith("+"))throw new Error("toEndPoint: ".concat(m,' must starts with either "sip:" or "+"'));if(y&&typeof y!="string")throw new Error("callerId must be of type string");if(y&&!m.startsWith("+"))throw new Error("callerId is only valid when transferring to a PSTN number")}function Em(u){if(d(u)!=="object")throw new Error('RemoteMediaPlayerSettings: must be "object" type');if(u.state&&!Object.values(Hc).includes(u.state))throw new Error("Invalid value for RemoteMediaPlayerSettings.state, valid values are: "+JSON.stringify(Hc));if(u.volume){if(typeof u.volume!="number")throw new Error('RemoteMediaPlayerSettings.volume: must be "number" type');if(u.volume<0||u.volume>2)throw new Error("RemoteMediaPlayerSettings.volume: must be between 0.0 - 2.0")}}function Pm(u,c,h){return!(typeof u!="number"||u<c||u>h)}function ul(u,c){return u&&!c&&delete u.data,u}}},e={};function t(n){var r=e[n];if(r!==void 0)return r.exports;var s=e[n]={exports:{}};return i[n].call(s.exports,s,s.exports,t),s.exports}return t.n=function(n){var r=n&&n.__esModule?function(){return n.default}:function(){return n};return t.d(r,{a:r}),r},t.d=function(n,r){for(var s in r)t.o(r,s)&&!t.o(n,s)&&Object.defineProperty(n,s,{enumerable:!0,get:r[s]})},t.o=function(n,r){return Object.prototype.hasOwnProperty.call(n,r)},t.r=function(n){typeof Symbol<"u"&&Symbol.toStringTag&&Object.defineProperty(n,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(n,"__esModule",{value:!0})},t(781)})()})),globalThis&&globalThis.Daily&&(globalThis.DailyIframe=globalThis.Daily)});var Dk=or((nI,sh)=>{"use strict";var Fr=typeof Reflect=="object"?Reflect:null,_k=Fr&&typeof Fr.apply=="function"?Fr.apply:function(e,t,n){return Function.prototype.apply.call(e,t,n)},Xa;Fr&&typeof Fr.ownKeys=="function"?Xa=Fr.ownKeys:Object.getOwnPropertySymbols?Xa=function(e){return Object.getOwnPropertyNames(e).concat(Object.getOwnPropertySymbols(e))}:Xa=function(e){return Object.getOwnPropertyNames(e)};function uP(i){console&&console.warn&&console.warn(i)}var wk=Number.isNaN||function(e){return e!==e};function xe(){xe.init.call(this)}sh.exports=xe;sh.exports.once=fP;xe.EventEmitter=xe;xe.prototype._events=void 0;xe.prototype._eventsCount=0;xe.prototype._maxListeners=void 0;var Ck=10;function Za(i){if(typeof i!="function")throw new TypeError('The "listener" argument must be of type Function. Received type '+typeof i)}Object.defineProperty(xe,"defaultMaxListeners",{enumerable:!0,get:function(){return Ck},set:function(i){if(typeof i!="number"||i<0||wk(i))throw new RangeError('The value of "defaultMaxListeners" is out of range. It must be a non-negative number. Received '+i+".");Ck=i}});xe.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};xe.prototype.setMaxListeners=function(e){if(typeof e!="number"||e<0||wk(e))throw new RangeError('The value of "n" is out of range. It must be a non-negative number. Received '+e+".");return this._maxListeners=e,this};function Ek(i){return i._maxListeners===void 0?xe.defaultMaxListeners:i._maxListeners}xe.prototype.getMaxListeners=function(){return Ek(this)};xe.prototype.emit=function(e){for(var t=[],n=1;n<arguments.length;n++)t.push(arguments[n]);var r=e==="error",s=this._events;if(s!==void 0)r=r&&s.error===void 0;else if(!r)return!1;if(r){var o;if(t.length>0&&(o=t[0]),o instanceof Error)throw o;var a=new Error("Unhandled error."+(o?" ("+o.message+")":""));throw a.context=o,a}var d=s[e];if(d===void 0)return!1;if(typeof d=="function")_k(d,this,t);else for(var l=d.length,f=Ik(d,l),n=0;n<l;++n)_k(f[n],this,t);return!0};function Pk(i,e,t,n){var r,s,o;if(Za(t),s=i._events,s===void 0?(s=i._events=Object.create(null),i._eventsCount=0):(s.newListener!==void 0&&(i.emit("newListener",e,t.listener?t.listener:t),s=i._events),o=s[e]),o===void 0)o=s[e]=t,++i._eventsCount;else if(typeof o=="function"?o=s[e]=n?[t,o]:[o,t]:n?o.unshift(t):o.push(t),r=Ek(i),r>0&&o.length>r&&!o.warned){o.warned=!0;var a=new Error("Possible EventEmitter memory leak detected. "+o.length+" "+String(e)+" listeners added. Use emitter.setMaxListeners() to increase limit");a.name="MaxListenersExceededWarning",a.emitter=i,a.type=e,a.count=o.length,uP(a)}return i}xe.prototype.addListener=function(e,t){return Pk(this,e,t,!1)};xe.prototype.on=xe.prototype.addListener;xe.prototype.prependListener=function(e,t){return Pk(this,e,t,!0)};function dP(){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 Ak(i,e,t){var n={fired:!1,wrapFn:void 0,target:i,type:e,listener:t},r=dP.bind(n);return r.listener=t,n.wrapFn=r,r}xe.prototype.once=function(e,t){return Za(t),this.on(e,Ak(this,e,t)),this};xe.prototype.prependOnceListener=function(e,t){return Za(t),this.prependListener(e,Ak(this,e,t)),this};xe.prototype.removeListener=function(e,t){var n,r,s,o,a;if(Za(t),r=this._events,r===void 0)return this;if(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
33("removeListener",e,n.listener||t));else if(typeof n!="function"){for(s=-1,o=n.length-1;o>=0;o--)if(n[o]===t||n[o].listener===t){a=n[o].listener,s=o;break}if(s<0)return this;s===0?n.shift():hP(n,s),n.length===1&&(r[e]=n[0]),r.removeListener!==void 0&&this.emit("removeListener",e,a||t)}return this};xe.prototype.off=xe.prototype.removeListener;xe.prototype.removeAllListeners=function(e){var t,n,r;if(n=this._events,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 s=Object.keys(n),o;for(r=0;r<s.length;++r)o=s[r],o!=="removeListener"&&this.removeAllListeners(o);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 Mk(i,e,t){var n=i._events;if(n===void 0)return[];var r=n[e];return r===void 0?[]:typeof r=="function"?t?[r.listener||r]:[r]:t?pP(r):Ik(r,r.length)}xe.prototype.listeners=function(e){return Mk(this,e,!0)};xe.prototype.rawListeners=function(e){return Mk(this,e,!1)};xe.listenerCount=function(i,e){return typeof i.listenerCount=="function"?i.listenerCount(e):Rk.call(i,e)};xe.prototype.listenerCount=Rk;function Rk(i){var e=this._events;if(e!==void 0){var t=e[i];if(typeof t=="function")return 1;if(t!==void 0)return t.length}return 0}xe.prototype.eventNames=function(){return this._eventsCount>0?Xa(this._events):[]};function Ik(i,e){for(var t=new Array(e),n=0;n<e;++n)t[n]=i[n];return t}function hP(i,e){for(;e+1<i.length;e++)i[e]=i[e+1];i.pop()}function pP(i){for(var e=new Array(i.length),t=0;t<e.length;++t)e[t]=i[t].listener||i[t];return e}function fP(i,e){return new Promise(function(t,n){function r(o){i.removeListener(e,s),n(o)}function s(){typeof i.removeListener=="function"&&i.removeListener("error",r),t([].slice.call(arguments))}Ok(i,e,s,{once:!0}),e!=="error"&&mP(i,r,{once:!0})})}function mP(i,e,t){typeof i.on=="function"&&Ok(i,"error",e,t)}function Ok(i,e,t,n){if(typeof i.on=="function")n.once?i.once(e,t):i.on(e,t);else if(typeof i.addEventListener=="function")i.addEventListener(e,function r(s){n.once&&i.removeEventListener(e,r),t(s)});else throw new TypeError('The "emitter" argument must be of type EventEmitter. Received type '+typeof i)}});var Lk=or(si=>{"use strict";Object.defineProperty(si,"__esModule",{value:!0});si.Api=si.HttpClient=si.ContentType=void 0;var ee;(function(i){i.Json="application/json",i.JsonApi="application/vnd.api+json",i.FormData="multipart/form-data",i.UrlEncoded="application/x-www-form-urlencoded",i.Text="text/plain"})(ee||(si.ContentType=ee={}));var ec=class{baseUrl="https://api.vapi.ai";securityData=null;securityWorker;abortControllers=new Map;customFetch=(...e)=>fetch(...e);baseApiParams={credentials:"same-origin",headers:{},redirect:"follow",referrerPolicy:"no-referrer"};constructor(e={}){Object.assign(this,e)}setSecurityData=e=>{this.securityData=e};encodeQueryParam(e,t){return`${encodeURIComponent(e)}=${encodeURIComponent(typeof t=="number"?t:`${t}`)}`}addQueryParam(e,t){return this.encodeQueryParam(t,e[t])}addArrayQueryParam(e,t){return e[t].map(r=>this.encodeQueryParam(t,r)).join("&")}toQueryString(e){let t=e||{};return Object.keys(t).filter(r=>typeof t[r]<"u").map(r=>Array.isArray(t[r])?this.addArrayQueryParam(t,r):this.addQueryParam(t,r)).join("&")}addQueryParams(e){let t=this.toQueryString(e);return t?`?${t}`:""}contentFormatters={[ee.Json]:e=>e!==null&&(typeof e=="object"||typeof e=="string")?JSON.stringify(e):e,[ee.JsonApi]:e=>e!==null&&(typeof e=="object"||typeof e=="string")?JSON.stringify(e):e,[ee.Text]:e=>e!==null&&typeof e!="string"?JSON.stringify(e):e,[ee.FormData]:e=>e instanceof FormData?e:Object.keys(e||{}).reduce((t,n)=>{let r=e[n];return t.append(n,r instanceof Blob?r:typeof r=="object"&&r!==null?JSON.stringify(r):`${r}`),t},new FormData),[ee.UrlEncoded]:e=>this.toQueryString(e)};
33mergeRequestParams(e,t){return{...this.baseApiParams,...e,...t||{},headers:{...this.baseApiParams.headers||{},...e.headers||{},...t&&t.headers||{}}}}createAbortSignal=e=>{if(this.abortControllers.has(e)){let n=this.abortControllers.get(e);return n?n.signal:void 0}let t=new AbortController;return this.abortControllers.set(e,t),t.signal};abortRequest=e=>{let t=this.abortControllers.get(e);t&&(t.abort(),this.abortControllers.delete(e))};request=async({body:e,secure:t,path:n,type:r,query:s,format:o,baseUrl:a,cancelToken:d,...l})=>{let f=(typeof t=="boolean"?t:this.baseApiParams.secure)&&this.securityWorker&&await this.securityWorker(this.securityData)||{},p=this.mergeRequestParams(l,f),g=s&&this.toQueryString(s),b=this.contentFormatters[r||ee.Json],R=o||p.format;return this.customFetch(`${a||this.baseUrl||""}${n}${g?`?${g}`:""}`,{...p,headers:{...p.headers||{},...r&&r!==ee.FormData?{"Content-Type":r}:{}},signal:(d?this.createAbortSignal(d):p.signal)||null,body:typeof e>"u"||e===null?null:b(e)}).then(async w=>{let I=w;I.data=null,I.error=null;let N=R?w.clone():w,L=R?await N[R]().then(j=>(I.ok?I.data=j:I.error=j,I)).catch(j=>(I.error=j,I)):I;if(d&&this.abortControllers.delete(d),!w.ok)throw L;return L})}};si.HttpClient=ec;var oh=class extends ec{assistant={assistantControllerCreate:(e,t={})=>this.request({path:"/assistant",method:"POST",body:e,secure:!0,type:ee.Json,format:"json",...t}),assistantControllerFindAll:(e,t={})=>this.request({path:"/assistant",method:"GET",query:e,secure:!0,format:"json",...t}),assistantControllerFindAllOrgDrafts:(e,t={})=>this.request({path:"/assistant/draft",method:"GET",query:e,secure:!0,format:"json",...t}),assistantControllerFindOne:(e,t={})=>this.request({path:`/assistant/${e}`,method:"GET",secure:!0,format:"json",...t}),assistantControllerUpdate:(e,t,n={})=>this.request({path:`/assistant/${e}`,method:"PATCH",body:t,secure:!0,type:ee.Json,format:"json",...n}),assistantControllerReplace:(e,t,n={})=>this.request({path:`/assistant/${e}`,method:"PUT",body:t,secure:!0,type:ee.Json,format:"json",...n}),assistantControllerRemove:(e,t={})=>this.request({path:`/assistant/${e}`,method:"DELETE",secure:!0,format:"json",...t}),assistantControllerFindVersions:(e,t,n={})=>this.request({path:`/assistant/${e}/version`,method:"GET",query:t,secure:!0,format:"json",...n}),assistantControllerFindAllVersions:(e,t,n={})=>this.request({path:`/assistant/${e}/versions`,method:"GET",query:t,secure:!0,format:"json",...n}),assistantControllerFindOneVersion:(e,t,n,r={})=>this.request({path:`/assistant/${e}/versions/${t}`,method:"GET",query:n,secure:!0,format:"json",...r}),assistantControllerAssistantVersionMetadataUpdate:(e,t,n,r={})=>this.request({path:`/assistant/${e}/versions/${t}`,method:"PATCH",body:n,secure:!0,type:ee.Json,format:"json",...r}),assistantControllerSoftDeleteVersion:(e,t,n,r={})=>this.request({path:`/assistant/${e}/versions/${t}`,method:"DELETE",query:n,secure:!0,format:"json",...r}),assistantControllerRestoreVersion:(e,t,n={})=>this.request({path:`/assistant/${e}/restore/${t}`,method:"POST",secure:!0,format:"json",...n}),assistantControllerFindAllDrafts:(e,t,n={})=>this.request({path:`/assistant/${e}/draft`,method:"GET",query:t,secure:!0,format:"json",...n}),assistantControllerCreateDraft:(e,t,n={})=>this.request({path:`/assistant/${e}/draft`,method:"POST",body:t,secure:!0,type:ee.Json,format:"json",...n}),assistantControllerFindOneDraft:(e,t,n={})=>this.request({path:`/assistant/${e}/draft/${t}`,method:"GET",secure:!0,format:"json",...n}),assistantControllerUpdateDraft:(e,t,n,r={})=>this.request({path:`/assistant/${e}/draft/${t}`,method:"PATCH",body:n,secure:!0,type:ee.Json,format:"json",...r}),assistantControllerDeleteDraft:(e,t,n={})=>this.request({path:`/assistant/${e}/draft/${t}`,method:"DELETE",secure:!0,format:"json",...n})};v2={assistantControllerFindAllPaginated:(e,t={})=>this.request({path:"/v2/assistant",method:"GET",query:e,secure:!0,format:"json",...t}),callControllerCallsExport:(e,t={})=>this.request({path:"/v2/call/export",method:"GET",query:e,secure:!0,...t}),callControllerFindAllPaginated:(e,t={})=>this.request({path:"/v2/call",method:"GET",query:e,secure:!0,format:"json",...t}),callControllerFindAllMetadataPaginated:(e,t={})=>this.request({path:"/v2/call/metadata",method:"GET",query:e,secure:!0,format:"json",...t}),campaignControllerCreateV2:(e,t={})=>this.request({path:"/v2/campaign",method:"POST",body:e,secure:!0,type:ee.Json,format:"json",...t}),campaignControllerFindAllV2:(e,t={})=>this.request({path:"/v2/campaign",method:"GET",query:e,secure:!0,format:"json",...t}),campaignControllerFindOneV2:(e,t,n={})=>this.request({path:`/v2/campaign/${e}`,method:"GET",query:t,secure:!0,format:"json",...n}),campaignControllerUpdateV2:(e,t,n={})=>this.request({path:`/v2/campaign/${e}`,method:"PATCH",body:t,secure:!0,type:ee.Json,format:"json",...n}),campaignControllerRemoveV2:(e,t={})=>this.request({path:`/v2/campaign/${e}`,method:"DELETE",secure:!0,format:"json",...t}),campaignControllerGetCampaignV2Contacts:(e,t,n={})=>this.request({path:`/v2/campaign/${e}/contacts`,method:"GET",query:t,secure:!0,format:"json",...n}),phoneNumberControllerFindAllPaginated:(e,t={})=>this.request({path:"/v2/phone-number",method:"GET",query:e,secure:!0,format:"json",...t}),knowledgeBaseV2ControllerCreate:(e,t={})=>this.request({path:"/v2/knowledge-base",method:"POST",body:e,secure:!0,type:ee.Json,format:"json",...t}),knowledgeBaseV2ControllerFindAll:(e,t={})=>this.request({path:"/v2/knowledge-base",method:"GET",query:e,secure:!0,format:"json",...t}),knowledgeBaseV2ControllerFilesGet:(e,t={})=>this.request({path:`/v2/knowledge-base/${e}/file`,method:"GET",secure:!0,format:"json",...t}),knowledgeBaseV2ControllerFileAttach:(e,t,n={})=>this.request({path:`/v2/knowledge-base/${e}/file`,method:"POST",body:t,secure:!0,type:ee.Json,format:"json",...n}),knowledgeBaseV2ControllerFileDetach:(e,t,n={})=>this.request({path:`/v2/knowledge-base/${e}/file/${t}`,method:"DELETE",secure:!0,format:"json",...n}),knowledgeBaseV2ControllerFileRetry:(e,t,n={})=>this.request({path:`/v2/knowledge-base/${e}/file/${t}/retry`,method:"POST",secure:!0,format:"json",...n}),knowledgeBaseV2ControllerUpdate:(e,t,n={})=>this.request({path:`/v2/knowledge-base/${e}`,method:"PATCH",body:t,secure:!0,type:ee.Json,format:"json",...n}),knowledgeBaseV2ControllerFindOne:(e,t={})=>this.request({path:`/v2/knowledge-base/${e}`,method:"GET",secure:!0,format:"json",...t}),knowledgeBaseV2ControllerRemove:(e,t={})=>this.request({path:`/v2/knowledge-base/${e}`,method:"DELETE",secure:!0,format:"json",...t})};squad={squadControllerCreate:(e,t={})=>this.request({path:"/squad",method:"POST",body:e,secure:!0,type:ee.Json,format:"json",...t}),squadControllerFindAll:(e,t={})=>this.request({path:"/squad",method:"GET",query:e,secure:!0,format:"json",...t}),squadControllerFindOne:(e,t={})=>this.request({path:`/squad/${e}`,method:"GET",secure:!0,format:"json",...t}),squadControllerUpdate:(e,t,n={})=>this.request({path:`/squad/${e}`,method:"PATCH",body:t,secure:!0,type:ee.Json,format:"json",...n}),squadControllerRemove:(e,t={})=>this.request({path:`/squad/${e}`,method:"DELETE",secure:!0,format:"json",...t})};workflow={workflowControllerFindAll:(e={})=>this.request({path:"/workflow",method:"GET",secure:!0,format:"json",...e}),workflowControllerCreate:(e,t={})=>this.request({path:"/workflow",method:"POST",body:e,secure:!0,type:ee.Json,format:"json",...t}),workflowControllerFindOne:(e,t={})=>this.request({path:`/workflow/${e}`,method:"GET",secure:!0,format:"json",...t}),workflowControllerDelete:(e,t={})=>this.request({path:`/workflow/${e}`,method:"DELETE",secure:!0,format:"json",...t}),workflowControllerUpdate:(e,t,n={})=>this.request({path:`/workflow/${e}`,method:"PATCH",body:t,secure:!0,type:ee.Json,format:"json",...n})};call={callControllerCreate:(e,t={})=>this.request({path:"/call",method:"POST",body:e,secure:!0,type:ee.Json,format:"json",...t}),callControllerFindAll:(e,t={})=>this.request({path:"/call",method:"GET",query:e,secure:!0,format:"json",...t}),callControllerFindOne:(e,t={})=>this.request({path:`/call/${e}`,method:"GET",secure:!0,format:"json",...t}),callControllerUpdate:(e,t,n={})=>this.request({path:`/call/${e}`,method:"PATCH",body:t,secure:!0,type:ee.Json,format:"json",...n}),callControllerDeleteCallData:(e,t,n={})=>this.request({path:`/call/${e}`,method:"DELETE",body:t,secure:!0,type:ee.Json,format:"json",...n}),callControllerCreatePhoneCall:(e,t={})=>this.request({path:"/call/phone",method:"POST",body:e,secure:!0,type:ee.Json,format:"json",...t}),callControllerCreateWebCall:(e,t={})=>this.request({path:"/call/web",method:"POST",body:e,secure:!0,type:ee.Json,format:"json",...t}),callArtifactControllerMonoRecordingDownload:(e,t={})=>this.request({path:`/call/${e}/mono-recording`,method:"GET",secure:!0,...t}),callArtifactControllerStereoRecordingDownload:(e,t={})=>this.request({path:`/call/${e}/stereo-recording`,method:"GET",secure:!0,...t}),callArtifactControllerVideoRecordingDownload:(e,t={})=>this.request({path:`/call/${e}/video-recording`,method:"GET",secure:!0,...t}),callArtifactControllerCustomerRecordingDownload:(e,t={})=>this.request({path:`/call/${e}/customer-recording`,method:"GET",secure:!0,...t}),callArtifactControllerAssistantRecordingDownload:(e,t={})=>this.request({path:`/call/${e}/assistant-recording`,method:"GET",secure:!0,...t}),callArtifactControllerPcapDownload:(e,t={})=>this.request({path:`/call/${e}/pcap`,method:"GET",secure:!0,...t}),callArtifactControllerCallLogsDownload:(e,t={})=>this.request({path:`/call/${e}/call-logs`,method:"GET",secure:!0,...t})};chat={chatControllerListChats:(e,t={})=>this.request({path:"/chat",method:"GET",query:e,secure:!0,format:"json",...t}),chatControllerCreateChat:(e,t={})=>this.request({path:"/chat",method:"POST",body:e,secure:!0,type:ee.Json,format:"json",...t}),chatControllerChatsExport:(e,t={})=>this.request({path:"/chat/export",method:"GET",query:e,secure:!0,...t}),chatControllerGetChat:(e,t={})=>this.request({path:`/chat/${e}`,method:"GET",secure:!0,format:"json",...t}),chatControllerDeleteChat:(e,t={})=>this.request({path:`/chat/${e}`,method:"DELETE",secure:!0,format:"json",...t}),chatControllerCreateOpenAiChat:(e,t={})=>this.request({path:"/chat/responses",method:"POST",body:e,secure:!0,type:ee.Json,format:"json",...t}),chatControllerCreateWebChat:(e,t={})=>this.request({path:"/chat/web",method:"POST",body:e,secure:!0,type:ee.Json,format:"json",...t}),chatControllerCreateOpenAiWebChat:(e,t={})=>this.request({path:"/chat/web/responses",method:"POST",body:e,secure:!0,type:ee.Json,format:"json",...t})};campaign={campaignControllerCreate:(e,t={})=>this.request({path:"/campaign",method:"POST",body:e,secure:!0,type:ee.Json,format:"json",...t}),campaignControllerFindAll:(e,t={})=>this.request({path:"/campaign",method:"GET",query:e,secure:!0,format:"json",...t}),campaignControllerFindOne:(e,t={})=>this.request({path:`/campaign/${e}`,method:"GET",secure:!0,format:"json",...t}),campaignControllerUpdate:(e,t,n={})=>this.request({path:`/campaign/${e}`,method:"PATCH",body:t,secure:!0,type:ee.Json,format:"json",...n}),campaignControllerRemove:(e,t={})=>this.request({path:`/campaign/${e}`,method:"DELETE",secure:!0,format:"json",...t})};session={sessionControllerCreate:(e,t={})=>this.request({path:"/session",method:"POST",body:e,secure:!0,type:ee.Json,format:"json",...t}),sessionControllerFindAllPaginated:(e,t={})=>this.request({path:"/session",method:"GET",query:e,secure:!0,format:"json",...t}),sessionControllerSessionsExport:(e,t={})=>this.request({path:"/session/export",method:"GET",query:e,secure:!0,...t}),sessionControllerFindOne:(e,t={})=>this.request({path:`/session/${e}`,method:"GET",secure:!0,format:"json",...t}),sessionControllerUpdate:(e,t,n={})=>this.request({path:`/session/${e}`,method:"PATCH",body:t,secure:!0,type:ee.Json,format:"json",...n}),sessionControllerRemove:(e,t={})=>this.request({path:`/session/${e}`,method:"DELETE",secure:!0,format:"json",...t})};phoneNumber={phoneNumberControllerImportTwilio:(e,t={})=>this.request({path:"/phone-number/import/twilio",method:"POST",body:e,secure:!0,type:ee.Json,format:"json",...t}),phoneNumberControllerImportVonage:(e,t={})=>this.request({path:"/phone-number/import/vonage",method:"POST",body:e,secure:!0,type:ee.Json,format:"json",...t}),phoneNumberControllerCreate:(e,t={})=>this.request({path:"/phone-number",method:"POST",body:e,secure:!0,type:ee.Json,format:"json",...t}),phoneNumberControllerFindAll:(e,t={})=>this.request({path:"/phone-number",method:"GET",query:e,secure:!0,format:"json",...t}),phoneNumberControllerFindOne:(e,t={})=>this.request({path:`/phone-number/${e}`,method:"GET",secure:!0,format:"json",...t}),phoneNumberControllerUpdate:(e,t,n={})=>this.request({path:`/phone-number/${e}`,method:"PATCH",body:t,secure:!0,type:ee.Json,format:"json",...n}),phoneNumberControllerRemove:(e,t={})=>this.request({path:`/phone-number/${e}`,method:"DELETE",secure:!0,format:"json",...t})};tool={toolControllerCreate:(e,t={})=>this.request({path:"/tool",method:"POST",body:e,secure:!0,type:ee.Json,format:"json",...t}),toolControllerFindAll:(e,t={})=>this.request({path:"/tool",method:"GET",query:e,secure:!0,format:"json",...t}),toolControllerFindAllOrgDrafts:(e,t={})=>this.request({path:"/tool/draft",method:"GET",query:e,secure:!0,format:"json",...t}),toolControllerFindOne:(e,t={})=>this.request({path:`/tool/${e}`,method:"GET",secure:!0,format:"json",...t}),toolControllerUpdate:(e,t,n={})=>this.request({path:`/tool/${e}`,method:"PATCH",body:t,secure:!0,type:ee.Json,format:"json",...n}),toolControllerRemove:(e,t={})=>this.request({path:`/tool/${e}`,method:"DELETE",secure:!0,format:"json",...t}),toolControllerFindAllVersions:(e,t,n={})=>this.request({path:`/tool/${e}/versions`,method:"GET",query:t,secure:!0,format:"json",...n}),toolControllerFindOneVersion:(e,t,n,r={})=>this.request({path:`/tool/${e}/versions/${t}`,method:"GET",query:n,secure:!0,format:"json",...r}),toolControllerToolVersionMetadataUpdate:(e,t,n,r={})=>this.request({path:`/tool/${e}/versions/${t}`,method:"PATCH",body:n,secure:!0,type:ee.Json,format:"json",...r}),toolControllerSoftDeleteVersion:(e,t,n,r={})=>this.request({path:`/tool/${e}/versions/${t}`,method:"DELETE",query:n,secure:!0,format:"json",...r}),toolControllerFindAllDrafts:(e,t,n={})=>this.request({path:`/tool/${e}/draft`,method:"GET",query:t,secure:!0,format:"json",...n}),toolControllerCreateDraft:(e,t,n={})=>this.request({path:`/tool/${e}/draft`,method:"POST",body:t,secure:!0,type:ee.Json,format:"json",...n}),toolControllerFindOneDraft:(e,t,n={})=>this.request({path:`/tool/${e}/draft/${t}`,method:"GET",secure:!0,format:"json",...n}),toolControllerUpdateDraft:(e,t,n,r={})=>this.request({path:`/tool/${e}/draft/${t}`,method:"PATCH",body:n,secure:!0,type:ee.Json,format:"json",...r}),toolControllerDeleteDraft:(e,t,n={})=>this.request({path:`/tool/${e}/draft/${t}`,method:"DELETE",secure:!0,format:"json",...n})};file={fileControllerCreateDeprecated:(e,t={})=>this.request({path:"/file/upload",method:"POST",body:e,secure:!0,type:ee.FormData,format:"json",...t}),fileControllerCreate:(e,t={})=>this.request({path:"/file",method:"POST",body:e,secure:!0,type:ee.FormData,format:"json",...t}),fileControllerFindAll:(e,t={})=>this.request({path:"/file",method:"GET",query:e,secure:!0,format:"json",...t}),fileControllerFindOne:(e,t={})=>this.request({path:`/file/${e}`,method:"GET",secure:!0,format:"json",...t}),fileControllerUpdate:(e,t,n={})=>this.request({path:`/file/${e}`,method:"PATCH",body:t,secure:!0,type:ee.Json,format:"json",...n}),fileControllerRemove:(e,t={})=>this.request({path:`/file/${e}`,method:"DELETE",secure:!0,format:"json",...t})};knowledgeBase={knowledgeBaseControllerCreate:(e,t={})=>this.request({path:"/knowledge-base",method:"POST",body:e,secure:!0,type:ee.Json,format:"json",...t}),knowledgeBaseControllerFindAll:(e,t={})=>this.request({path:"/knowledge-base",method:"GET",query:e,secure:!0,format:"json",...t}),knowledgeBaseControllerFindOne:(e,t={})=>this.request({path:`/knowledge-base/${e}`,method:"GET",secure:!0,format:"json",...t}),knowledgeBaseControllerUpdate:(e,t,n={})=>this.request({path:`/knowledge-base/${e}`,method:"PATCH",body:t,secure:!0,type:ee.Json,format:"json",...n}),knowledgeBaseControllerRemove:(e,t={})=>this.request({path:`/knowledge-base/${e}`,method:"DELETE",secure:!0,for
33mat:"json",...t})};structuredOutput={structuredOutputControllerFindAll:(e,t={})=>this.request({path:"/structured-output",method:"GET",query:e,secure:!0,format:"json",...t}),structuredOutputControllerCreate:(e,t={})=>this.request({path:"/structured-output",method:"POST",body:e,secure:!0,type:ee.Json,format:"json",...t}),structuredOutputControllerFindOne:(e,t={})=>this.request({path:`/structured-output/${e}`,method:"GET",secure:!0,format:"json",...t}),structuredOutputControllerUpdate:(e,t,n,r={})=>this.request({path:`/structured-output/${e}`,method:"PATCH",query:t,body:n,secure:!0,type:ee.Json,format:"json",...r}),structuredOutputControllerRemove:(e,t={})=>this.request({path:`/structured-output/${e}`,method:"DELETE",secure:!0,format:"json",...t}),structuredOutputControllerRun:(e,t={})=>this.request({path:"/structured-output/run",method:"POST",body:e,secure:!0,type:ee.Json,format:"json",...t})};testSuite={testSuiteControllerFindAllPaginated:(e,t={})=>this.request({path:"/test-suite",method:"GET",query:e,secure:!0,format:"json",...t}),testSuiteControllerCreate:(e,t={})=>this.request({path:"/test-suite",method:"POST",body:e,secure:!0,type:ee.Json,format:"json",...t}),testSuiteControllerFindOne:(e,t={})=>this.request({path:`/test-suite/${e}`,method:"GET",secure:!0,format:"json",...t}),testSuiteControllerUpdate:(e,t,n={})=>this.request({path:`/test-suite/${e}`,method:"PATCH",body:t,secure:!0,type:ee.Json,format:"json",...n}),testSuiteControllerRemove:(e,t={})=>this.request({path:`/test-suite/${e}`,method:"DELETE",secure:!0,format:"json",...t}),testSuiteTestControllerFindAllPaginated:(e,t,n={})=>this.request({path:`/test-suite/${e}/test`,method:"GET",query:t,secure:!0,format:"json",...n}),testSuiteTestControllerCreate:(e,t,n={})=>this.request({path:`/test-suite/${e}/test`,method:"POST",body:t,secure:!0,type:ee.Json,format:"json",...n}),testSuiteTestControllerFindOne:(e,t,n={})=>this.request({path:`/test-suite/${e}/test/${t}`,method:"GET",secure:!0,format:"json",...n}),testSuiteTestControllerUpdate:(e,t,n,r={})=>this.request({path:`/test-suite/${e}/test/${t}`,method:"PATCH",body:n,secure:!0,type:ee.Json,format:"json",...r}),testSuiteTestControllerRemove:(e,t,n={})=>this.request({path:`/test-suite/${e}/test/${t}`,method:"DELETE",secure:!0,format:"json",...n}),testSuiteRunControllerFindAllPaginated:(e,t,n={})=>this.request({path:`/test-suite/${e}/run`,method:"GET",query:t,secure:!0,format:"json",...n}),testSuiteRunControllerCreate:(e,t,n={})=>this.request({path:`/test-suite/${e}/run`,method:"POST",body:t,secure:!0,type:ee.Json,format:"json",...n}),testSuiteRunControllerFindOne:(e,t,n={})=>this.request({path:`/test-suite/${e}/run/${t}`,method:"GET",secure:!0,format:"json",...n}),testSuiteRunControllerUpdate:(e,t,n,r={})=>this.request({path:`/test-suite/${e}/run/${t}`,method:"PATCH",body:n,secure:!0,type:ee.Json,format:"json",...r}),testSuiteRunControllerRemove:(e,t,n={})=>this.request({path:`/test-suite/${e}/run/${t}`,method:"DELETE",secure:!0,format:"json",...n})};eval={personalityControllerCreate:(e,t={})=>this.request({path:"/eval/simulation/personality",method:"POST",body:e,secure:!0,type:ee.Json,format:"json",...t}),personalityControllerFindAll:(e,t={})=>this.request({path:"/eval/simulation/personality",method:"GET",query:e,secure:!0,format:"json",...t}),personalityControllerFindOne:(e,t={})=>this.request({path:`/eval/simulation/personality/${e}`,method:"GET",secure:!0,format:"json",...t}),personalityControllerUpdate:(e,t,n={})=>this.request({path:`/eval/simulation/personality/${e}`,method:"PATCH",body:t,secure:!0,type:ee.Json,format:"json",...n}),personalityControllerRemove:(e,t={})=>this.request({path:`/eval/simulation/personality/${e}`,method:"DELETE",secure:!0,format:"json",...t}),scenarioControllerCreate:(e,t={})=>this.request({path:"/eval/simulation/scenario",method:"POST",body:e,secure:!0,type:ee.Json,format:"json",...t}),scenarioControllerFindAll:(e,t={})=>this.request({path:"/eval/simulation/scenario",method:"GET",query:e,secure:!0,format:"json",...t}),scenarioControllerFindOne:(e,t={})=>this.request({path:`/eval/simulation/scenario/${e}`,method:"GET",secure:!0,format:"json",...t}),scenarioControllerUpdate:(e,t,n={})=>this.request({path:`/eval/simulation/scenario/${e}`,method:"PATCH",body:t,secure:!0,type:ee.Json,format:"json",...n}),scenarioControllerRemove:(e,t={})=>this.request({path:`/eval/simulation/scenario/${e}`,method:"DELETE",secure:!0,format:"json",...t}),simulationRunControllerCreate:(e,t={})=>this.request({path:"/eval/simulation/run",method:"POST",body:e,secure:!0,type:ee.Json,format:"json",...t}),simulationRunControllerFindAll:(e,t={})=>this.request({path:"/eval/simulation/run",method:"GET",query:e,secure:!0,format:"json",...t}),simulationRunControllerFindOne:(e,t={})=>this.request({path:`/eval/simulation/run/${e}`,method:"GET",secure:!0,format:"json",...t}),simulationRunControllerCancelGroup:(e,t={})=>this.request({path:`/eval/simulation/run/${e}`,method:"PATCH",secure:!0,format:"json",...t}),simulationRunControllerFindItems:(e,t,n={})=>this.request({path:`/eval/simulation/run/${e}/item`,method:"GET",query:t,secure:!0,format:"json",...n}),simulationRunControllerFindItem:(e,t,n={})=>this.request({path:`/eval/simulation/run/${e}/item/${t}`,method:"GET",secure:!0,format:"json",...n}),simulationRunControllerCancelItem:(e,t,n={})=>this.request({path:`/eval/simulation/run/${e}/item/${t}`,method:"PATCH",secure:!0,format:"json",...n}),simulationRunControllerGenerateSuggestions:(e,t,n,r={})=>this.request({path:`/eval/simulation/run/${e}/item/${t}/generate`,method:"POST",query:n,secure:!0,...r}),simulationSuiteControllerCreate:(e,t={})=>this.request({path:"/eval/simulation/suite",method:"POST",body:e,secure:!0,type:ee.Json,format:"json",...t}),simulationSuiteControllerFindAll:(e,t={})=>this.request({path:"/eval/simulation/suite",method:"GET",query:e,secure:!0,format:"json",...t}),simulationSuiteControllerFindOne:(e,t={})=>this.request({path:`/eval/simulation/suite/${e}`,method:"GET",secure:!0,format:"json",...t}),simulationSuiteControllerUpdate:(e,t,n={})=>this.request({path:`/eval/simulation/suite/${e}`,method:"PATCH",body:t,secure:!0,type:ee.Json,format:"json",...n}),simulationSuiteControllerRemove:(e,t={})=>this.request({path:`/eval/simulation/suite/${e}`,method:"DELETE",secure:!0,format:"json",...t}),simulationGenerateControllerGenerate:(e,t={})=>this.request({path:"/eval/simulation/scenario/generate",method:"POST",body:e,secure:!0,type:ee.Json,format:"json",...t}),simulationControllerCreate:(e,t={})=>this.request({path:"/eval/simulation",method:"POST",body:e,secure:!0,type:ee.Json,format:"json",...t}),simulationControllerFindAll:(e,t={})=>this.request({path:"/eval/simulation",method:"GET",query:e,secure:!0,format:"json",...t}),simulationControllerFindOne:(e,t={})=>this.request({path:`/eval/simulation/${e}`,method:"GET",secure:!0,format:"json",...t}),simulationControllerUpdate:(e,t,n={})=>this.request({path:`/eval/simulation/${e}`,method:"PATCH",body:t,secure:!0,type:ee.Json,format:"json",...n}),simulationControllerRemove:(e,t={})=>this.request({path:`/eval/simulation/${e}`,method:"DELETE",secure:!0,format:"json",...t}),simulationControllerGetConcurrency:(e={})=>this.request({path:"/eval/simulation/concurrency",method:"GET",secure:!0,format:"json",...e}),evalControllerCreate:(e,t={})=>this.request({path:"/eval",method:"POST",body:e,secure:!0,type:ee.Json,format:"json",...t}),evalControllerGetPaginated:(e,t={})=>this.request({path:"/eval",method:"GET",query:e,secure:!0,format:"json",...t}),evalControllerUpdate:(e,t,n={})=>this.request({path:`/eval/${e}`,method:"PATCH",body:t,secure:!0,type:ee.Json,format:"json",...n}),evalControllerRemove:(e,t={})=>this.request({path:`/eval/${e}`,method:"DELETE",secure:!0,format:"json",...t}),evalControllerGet:(e,t={})=>this.request({path:`/eval/${e}`,method:"GET",secure:!0,format:"json",...t}),evalControllerRemoveRun:(e,t={})=>this.request({path:`/eval/run/${e}`,method:"DELETE",secure:!0,format:"json",...t}),evalControllerGetRun:(e,t={})=>this.request({path:`/eval/run/${e}`,method:"GET",secure:!0,format:"json",...t}),evalControllerRun:(e,t={})=>this.request({path:"/eval/run",method:"POST",body:e,secure:!0,type:ee.Json,...t}),evalControllerGetRunsPaginated:(e,t={})=>this.request({path:"/eval/run",method:"GET",query:e,secure:!0,format:"json",...t})};reporting={insightControllerCreate:(e,t={})=>this.request({path:"/reporting/insight",method:"POST",body:e,secure:!0,type:ee.Json,format:"json",...t}),insightControllerFindAll:(e,t={})=>this.request({path:"/reporting/insight",method:"GET",query:e,secure:!0,format:"json",...t}),insightControllerUpdate:(e,t,n={})=>this.request({path:`/reporting/insight/${e}`,method:"PATCH",body:t,secure:!0,type:ee.Json,format:"json",...n}),insightControllerFindOne:(e,t={})=>this.request({path:`/reporting/insight/${e}`,method:"GET",secure:!0,format:"json",...t}),insightControllerRemove:(e,t={})=>this.request({path:`/reporting/insight/${e}`,method:"DELETE",secure:!0,format:"json",...t}),insightControllerRun:(e,t,n={})=>this.request({path:`/reporting/insight/${e}/run`,method:"POST",body:t,secure:!0,type:ee.Json,format:"json",...n}),insightControllerPreview:(e,t={})=>this.request({path:"/reporting/insight/preview",method:"POST",body:e,secure:!0,type:ee.Json,format:"json",...t}),boardControllerCreate:(e,t={})=>this.request({path:"/reporting/board",method:"POST",body:e,secure:!0,type:ee.Json,format:"json",...t}),boardControllerFindAll:(e,t={})=>this.request({path:"/reporting/board",method:"GET",query:e,secure:!0,format:"json",...t}),boardControllerMetricsOverviewEnsure:(e={})=>this.request({path:"/reporting/board/default/metrics-overview",method:"GET",secure:!0,format:"json",...e}),boardControllerUpdate:(e,t,n={})=>this.request({path:`/reporting/board/${e}`,method:"PATCH",body:t,secure:!0,type:ee.Json,format:"json",...n}),boardControllerFindOne:(e,t={})=>this.request({path:`/reporting/board/${e}`,method:"GET",secure:!0,format:"json",...t}),boardControllerRemove:(e,t={})=>this.request({path:`/reporting/board/${e}`,method:"DELETE",secure:!0,format:"json",...t})};observability={scorecardControllerGet:(e,t={})=>this.request({path:`/observability/scorecard/${e}`,method:"GET",secure:!0,format:"json",...t}),scorecardControllerUpdate:(e,t,n={})=>this.request({path:`/observability/scorecard/${e}`,method:"PATCH",body:t,secure:!0,type:ee.Json,format:"json",...n}),scorecardControllerRemove:(e,t={})=>this.request({path:`/observability/scorecard/${e}`,method:"DELETE",secure:!0,format:"json",...t}),scorecardControllerGetPaginated:(e,t={})=>this.request({path:"/observability/scorecard",method:"GET",query:e,secure:!0,format:"json",...t}),scorecardControllerCreate:(e,t={})=>this.request({path:"/observability/scorecard",method:"POST",body:e,secure:!0,type:ee.Json,format:"json",...t})};org={orgControllerCreate:(e,t={})=>this.request({path:"/org",method:"POST",body:e,secure:!0,type:ee.Json,format:"json",...t}),orgControllerFindAll:(e={})=>this.request({path:"/org",method:"GET",secure:!0,format:"json",...e}),orgControllerFeatureFlagEnabled:(e,t={})=>this.request({path:"/org/feature-flag",method:"GET",query:e,secure:!0,format:"json",...t}),orgControllerFindOne:(e,t={})=>this.request({path:`/org/${e}`,method:"GET",secure:!0,format:"json",...t}),orgControllerUpdate:(e,t,n={})=>this.request({path:`/org/${e}`,method:"PATCH",body:t,secure:!0,type:ee.Json,format:"json",...n}),orgControllerDeleteOrg:(e,t={})=>this.request({path:`/org/${e}`,method:"DELETE",secure:!0,...t}),orgControllerFindAllUsers:(e,t={})=>this.request({path:`/org/${e}/user`,method:"GET",secure:!0,format:"json",...t}),orgControllerOrgLeave:(e,t={})=>this.request({path:`/org/${e}/leave`,method:"DELETE",secure:!0,...t}),orgControllerOrgRemoveUser:(e,t,n={})=>this.request({path:`/org/${e}/member/${t}/leave`,method:"DELETE",secure:!0,...n}),orgControllerUsersInvite:(e,t,n={})=>this.request({path:`/org/${e}/invite`,method:"POST",body:t,secure:!0,type:ee.Json,...n}),orgControllerPendingInvitationsList:(e,t={})=>this.request({path:`/org/${e}/invitations/pending`,method:"GET",secure:!0,format:"json",...t}),orgControllerPendingInvitationRevoke:(e,t,n={})=>this.request({path:`/org/${e}/invitations/${t}`,method:"DELETE",secure:!0,format:"json",...n}),orgControllerUserUpdate:(e,t,n={})=>this.request({path:`/org/${e}/role`,method:"PATCH",body:t,secure:!0,type:ee.Json,...n}),orgControllerOrgToken:(e,t={})=>this.request({path:`/org/${e}/auth`,method:"GET",secure:!0,format:"json",...t}),orgControllerZdrBuy:(e,t={})=>this.request({path:`/org/${e}/zdr`,method:"POST",secure:!0,format:"json",...t}),orgControllerZdrRemove:(e,t={})=>this.request({path:`/org/${e}/zdr`,method:"DELETE",secure:!0,format:"json",...t})};token={tokenControllerCreate:(e,t={})=>this.request({path:"/token",method:"POST",body:e,secure:!0,type:ee.Json,format:"json",...t}),tokenControllerFindAll:(e,t={})=>this.request({path:"/token",method:"GET",query:e,secure:!0,format:"json",...t}),tokenControllerFindOne:(e,t={})=>this.request({path:`/token/${e}`,method:"GET",secure:!0,format:"json",...t}),tokenControllerUpdate:(e,t,n={})=>this.request({path:`/token/${e}`,method:"PATCH",body:t,secure:!0,type:ee.Json,format:"json",...n}),tokenControllerRemove:(e,t={})=>this.request({path:`/token/${e}`,method:"DELETE",secure:!0,format:"json",...t})};credential={credentialControllerCreate:(e,t={})=>this.request({path:"/credential",method:"POST",body:e,secure:!0,type:ee.Json,format:"json",...t}),credentialControllerFindAll:(e,t={})=>this.request({path:"/credential",method:"GET",query:e,secure:!0,format:"json",...t}),credentialControllerFindOne:(e,t={})=>this.request({path:`/credential/${e}`,method:"GET",secure:!0,format:"json",...t}),credentialControllerUpdate:(e,t,n={})=>this.request({path:`/credential/${e}`,method:"PATCH",body:t,secure:!0,type:ee.Json,format:"json",...n}),credentialControllerRemove:(e,t={})=>this.request({path:`/credential/${e}`,method:"DELETE",secure:!0,format:"json",...t})};template={templateControllerCreate:(e,t={})=>this.request({path:"/template",method:"POST",body:e,secure:!0,type:ee.Json,format:"json",...t}),templateControllerFindAll:(e,t={})=>this.request({path:"/template",method:"GET",query:e,secure:!0,format:"json",...t}),templateControllerFindAllPinned:(e={})=>this.request({path:"/template/pinned",method:"GET",secure:!0,format:"json",...e}),templateControllerFindOne:(e,t={})=>this.request({path:`/template/${e}`,method:"GET",secure:!0,format:"json",...t}),templateControllerUpdate:(e,t,n={})=>this.request({path:`/template/${e}`,method:"PATCH",body:t,secure:!0,type:ee.Json,format:"json",...n}),templateControllerRemove:(e,t={})=>this.request({path:`/template/${e}`,method:"DELETE",secure:!0,format:"json",...t})};voiceLibrary={voiceLibraryControllerVoiceGetByProvider:(e,t,n={})=>this.request({path:`/voice-library/${e}`,method:"GET",query:t,secure:!0,format:"json",...n}),voiceLibraryControllerVoiceGetAccentsByProvider:(e,t={})=>this.request({path:`/voice-library/${e}/accents`,method:"GET",secure:!0,format:"json",...t}),voiceLibraryControllerVoiceLibrarySyncByProvider:(e,t={})=>this.request({path:`/voice-library/sync/${e}`,method:"POST",secure:!0,format:"json",...t}),voiceLibraryControllerVoiceLibrarySyncDefaultVoices:(e,t={})=>this.request({path:"/voice-library/sync",method:"POST",body:e,secure:!0,type:ee.Json,format:"json",...t}),voiceLibraryControllerVoiceLibraryCreateSesameVoice:(e,t={})=>this.request({path:"/voice-library/create-sesame-voice",method:"POST",body:e,secure:!0,type:ee.FormData,...t}),voiceLibraryControllerVoiceLibraryVoiceUpdate:(e,t,n={})=>this.request({path:`/voice-library/${e}`,method:"PATCH",body:t,secure:!0,type:ee.Json,format:"json",...n}),voiceLibraryControllerVoiceLibraryVoiceDelete:(e,t={})=>this.request({path:`/voice-library/${e}`,method:"DELETE",secure:!0,...t})};provider={providerResourceControllerCreateProviderResource:(e,t,n={})=>this.request({path:`/provider/${e}/${t}`,method:"POST",secure:!0,format:"json",...n}),providerResourceControllerGetProviderResourcesPaginated:(e,t,n,r={})=>this.request({path:`/provider/${e}/${t}`,method:"GET",query:n,secure:!0,format:"json",...r}),providerResourceControllerGetProviderResource:(e,t,n,r={})=>this.request({path:`/provider/${e}/${t}/${n}`,method:"GET",secure:!0,format:"json",...r}),providerResourceControllerDeleteProviderResource:(e,t,n,r={})=>thi
33s.request({path:`/provider/${e}/${t}/${n}`,method:"DELETE",secure:!0,format:"json",...r}),providerResourceControllerUpdateProviderResource:(e,t,n,r={})=>this.request({path:`/provider/${e}/${t}/${n}`,method:"PATCH",secure:!0,format:"json",...r}),providerControllerGetWorkflows:(e,t,n={})=>this.request({path:`/${e}/workflows`,method:"GET",query:t,secure:!0,format:"json",...n}),providerControllerGetWorkflowTriggerHook:(e,t,n={})=>this.request({path:`/${e}/workflows/${t}/hooks`,method:"GET",secure:!0,format:"json",...n}),providerControllerGetLocations:(e,t={})=>this.request({path:`/${e}/locations`,method:"GET",secure:!0,format:"json",...t}),voiceProviderControllerSearchVoices:(e,t,n={})=>this.request({path:`/${e}/voices/search`,method:"GET",query:t,secure:!0,format:"json",...n}),voiceProviderControllerSearchVoice:(e,t,n={})=>this.request({path:`/${e}/voice/search`,method:"GET",query:t,secure:!0,format:"json",...n}),voiceProviderControllerAddVoices:(e,t,n={})=>this.request({path:`/${e}/voices/add`,method:"POST",body:t,secure:!0,type:ee.Json,format:"json",...n}),voiceProviderControllerAddVoice:(e,t,n={})=>this.request({path:`/${e}/voice/add`,method:"POST",body:t,secure:!0,type:ee.Json,format:"json",...n})};v11Labs={voiceProviderControllerCloneVoices:(e,t={})=>this.request({path:"/11labs/voice/clone",method:"POST",body:e,secure:!0,type:ee.FormData,...t})};vapi={voiceProviderControllerCloneVapiVoice:(e,t={})=>this.request({path:"/vapi/voice/clone",method:"POST",body:e,secure:!0,type:ee.FormData,...t})};analytics={analyticsControllerQuery:(e,t={})=>this.request({path:"/analytics",method:"POST",body:e,secure:!0,type:ee.Json,format:"json",...t})}};si.Api=oh});var xk=or(tc=>{"use strict";Object.defineProperty(tc,"__esModule",{value:!0});tc.client=void 0;var gP=Lk(),vP=new gP.Api({baseUrl:"https://api.vapi.ai",baseApiParams:{secure:!0},securityWorker:async i=>{if(i)return{headers:{Authorization:`Bearer ${i}`}}}});tc.client=vP});var Nk=or(Ur=>{"use strict";
33Object.defineProperty(Ur,"__esModule",{value:!0});Ur.createSafeDailyConfig=yP;Ur.safeSetLocalAudio=bP;Ur.safeSetInputDevicesAsync=kP;Ur.createSafeDailyFactoryOptions=SP;function yP(i){if(!i)return{};let{alwaysIncludeMicInPermissionPrompt:e,...t}=i;return e===!1?(console.warn("[Vapi] alwaysIncludeMicInPermissionPrompt:false detected. This can cause Chrome 140+ issues. Removing the property."),t):i}function bP(i,e){if(!i)throw new Error("Call object is not available.");i.setLocalAudio(e)}async function kP(i,e){if(!i)throw new Error("Call object is not available.");if("audioSource"in e&&e.audioSource===!1){console.warn("[Vapi] setInputDevicesAsync with audioSource:false detected. This can cause Chrome 140+ issues. Using default device instead.");let{audioSource:t,...n}=e;await i.setInputDevicesAsync(n);return}await i.setInputDevicesAsync(e)}function SP(i){return i?i.audioSource===!1?(console.warn("[Vapi] audioSource:false detected in factory options. This can cause Chrome 140+ issues. Defaulting to true."),{...i,audioSource:!0}):i:{}}});var jk=or(qs=>{"use strict";var Uk=qs&&qs.__importDefault||function(i){return i&&i.__esModule?i:{default:i}};Object.defineProperty(qs,"__esModule",{value:!0});var ah=Uk(Tk()),TP=Uk(Dk()),ch=xk(),Wi=Nk();function it(i){if(i==null)return{message:"Unknown error (null or undefined)"};if(i instanceof Error){let e={message:i.message,name:i.name,stack:i.stack},t=i;return t.code!==void 0&&(e.code=t.code),t.cause!==void 0&&(e.cause=String(t.cause)),t.reason!==void 0&&(e.reason=t.reason),t.details!==void 0&&(e.details=t.details),t.errorMsg!==void 0&&(e.errorMsg=t.errorMsg),t.error!==void 0&&typeof t.error=="string"&&(e.errorDetail=t.error),e}if(typeof i=="string")return{message:i};if(typeof i=="object"){let e=i;return{message:e.message||e.error||JSON.stringify(i),...e}}return{message:String(i)}}async function _P(i,e){i.muted=!1,i.autoplay=!0,e!=null&&(i.srcObject=new MediaStream([e]),await i.play())}async function CP(i,e,t){let n=document.createElement("audio");n.dataset.participantId=e,typeof t=="number"&&(n.volume=t),document.body.appendChild(n);try{await _P(n,i)}catch(r){throw n.remove(),r}return n}function wP(i){document.querySelector(`audio[data-participant-id="${i}"]`)?.remove()}function Fk(i,e,t,n){i.participant.local||e.updateParticipant(i.participant.session_id,{setSubscribedTracks:{audio:!0,video:t||n}})}var lh=class extends TP.default{on(e,t){return super.on(e,t),this}once(e,t){return super.once(e,t),this}emit(e,...t){return super.emit(e,...t)}removeListener(e,t){return super.removeListener(e,t),this}removeAllListeners(e){return super.removeAllListeners(e),this}},uh=class extends lh{started=!1;call=null;audioPlayer=null;desiredVolume=null;audioBuildSequence=0;pendingAudioBuilds=new Map;attachedAudioBuild=0;speakingTimeout=null;dailyCallConfig={};dailyCallObject={};hasEmittedCallEndedStatus=!1;constructor(e,t,n,r){super(),ch.client.baseUrl=t??"https://api.vapi.ai",ch.client.setSecurityData(e),this.dailyCallConfig=(0,Wi.createSafeDailyConfig)(n),this.dailyCallObject=(0,Wi.createSafeDailyFactoryOptions)(r)}async cleanup(){this.started=!1,this.hasEmittedCallEndedStatus=!1,this.call&&(await this.call.destroy(),this.call=null),this.audioPlayer=null,this.pendingAudioBuilds.clear(),this.speakingTimeout=null}isMobileDevice(){if(typeof navigator>"u")return!1;let e=navigator.userAgent;return/android|iphone|ipad|ipod|iemobile|blackberry|bada/i.test(e.toLowerCase())}async sleep(e){return new Promise(t=>setTimeout(t,e))}emitAudioProcessingError(e,t){this.emit("error",{type:`${e}-error`,stage:e,error:it(t),timestamp:new Date().toISOString()})}async start(e,t,n,r,s,o){let a=Date.now();if(!e&&!n&&!r){let d=new Error("Assistant or Squad or Workflow must be provided.");throw this.emit("error",{type:"validation-error",stage:"input-validation",error:it(d),timestamp:new Date().toISOString()}),d}if(this.started)return this.emit("call-start-progress",{stage:"validation",status:"failed",timestamp:new Date().toISOString(),metadata:{reason:"already-started"}}),null;this.emit("call-start-progress",{stage:"initialization",status:"started",timestamp:new Date().toISOString(),metadata:{hasAssistant:!!e,hasSquad:!!n,hasWorkflow:!!r}}),this.started=!0;
33try{this.emit("call-start-progress",{stage:"web-call-creation",status:"started",timestamp:new Date().toISOString()});let d=Date.now(),l=(await ch.client.call.callControllerCreateWebCall({assistant:typeof e=="string"?void 0:e,assistantId:typeof e=="string"?e:void 0,assistantOverrides:t,squad:typeof n=="string"?void 0:n,squadId:typeof n=="string"?n:void 0,workflow:typeof r=="string"?void 0:r,workflowId:typeof r=="string"?r:void 0,workflowOverrides:s,roomDeleteOnUserLeaveEnabled:o?.roomDeleteOnUserLeaveEnabled})).data,f=Date.now()-d;this.emit("call-start-progress",{stage:"web-call-creation",status:"completed",duration:f,timestamp:new Date().toISOString(),metadata:{callId:l?.id||"unknown",videoRecordingEnabled:l?.artifactPlan?.videoRecordingEnabled??!1,voiceProvider:l?.assistant?.voice?.provider||"unknown"}}),this.call&&(this.emit("call-start-progress",{stage:"daily-call-object-creation",status:"started",timestamp:new Date().toISOString(),metadata:{action:"cleanup-existing"}}),await this.cleanup());let p=l?.artifactPlan?.videoRecordingEnabled??!1,g=l?.assistant?.voice?.provider==="tavus",b=l?.transport?.callToken;this.emit("call-start-progress",{stage:"daily-call-object-creation",status:"started",timestamp:new Date().toISOString(),metadata:{audioSource:this.dailyCallObject.audioSource??!0,videoSource:this.dailyCallObject.videoSource??p,isVideoRecordingEnabled:p,isVideoEnabled:g}});let R=Date.now();try{this.call=ah.default.createCallObject({audioSource:this.dailyCallObject.audioSource??!0,videoSource:this.dailyCallObject.videoSource??p,dailyConfig:this.dailyCallConfig});let P=Date.now()-R;this.emit("call-start-progress",{stage:"daily-call-object-creation",status:"completed",duration:P,timestamp:new Date().toISOString()})}catch(P){let B=Date.now()-R,q=it(P);throw this.emit("call-start-progress",{stage:"daily-call-object-creation",status:"failed",duration:B,timestamp:new Date().toISOString(),metadata:{error:q.message}}),this.emit("error",{type:"daily-call-object-creation-error",stage:"daily-call-object-creation",error:q,timestamp:new Date().toISOString()}),P}this.call.iframe()?.style.setProperty("display","none"),this.call.on("left-meeting",()=>{this.emit("call-end"),this.hasEmittedCallEndedStatus||(this.emit("message",{type:"status-update",status:"ended",endedReason:"customer-ended-call"}),this.hasEmittedCallEndedStatus=!0),p&&this.call?.stopRecording(),this.cleanup().catch(console.error)}),this.call.on("error",P=>{this.emit("error",{type:"daily-error",error:it(P),timestamp:new Date().toISOString()}),p&&this.call?.stopRecording()}),this.call.on("camera-error",P=>{this.emit("camera-error",{type:"camera-error",error:it(P),timestamp:new Date().toISOString()})}),this.call.on("network-quality-change",P=>{this.emit("network-quality-change",P)}),this.call.on("network-connection",P=>{this.emit("network-connection",P)}),this.call.on("recording-started",P=>{P&&this.emit("recording-started",P)}),this.call.on("recording-stopped",P=>{P&&this.emit("recording-stopped",P)}),this.call.on("recording-stats",P=>{P&&this.emit("recording-stats",P)}),this.call.on("recording-error",P=>{P&&this.emit("recording-error",P)}),this.call.on("recording-upload-completed",P=>{P&&this.emit("recording-upload-completed",P)}),this.call.on("track-started",P=>this.handleTrackStarted(P)),this.call.on("participant-joined",P=>{!P||!this.call||Fk(P,this.call,p,g)}),this.call.on("participant-updated",P=>{P&&this.emit("daily-participant-updated",P.participant)}),this.call.on("participant-left",P=>{P&&this.detachAudioPlayer(P.participant.session_id)});let w=0;p&&this.call.once("recording-started",()=>{let P=(new Date().getTime()-w)/1e3;this.emit("call-start-progress",{stage:"video-recording-started",status:"completed",timestamp:new Date().toISOString(),metadata:{delaySeconds:P}}),this.send({type:"control",control:"say-first-message",videoRecordingStartDelaySeconds:P})});let I=this.isMobileDevice();if(this.emit("call-start-progress",{stage:"mobile-permissions",status:"started",timestamp:new Date().toISOString(),metadata:{isMobile:I}}),I){let P=Date.now();await this.sleep(1e3);let B=Date.now()-P;
33this.emit("call-start-progress",{stage:"mobile-permissions",status:"completed",duration:B,timestamp:new Date().toISOString(),metadata:{action:"permissions-wait"}})}else this.emit("call-start-progress",{stage:"mobile-permissions",status:"completed",timestamp:new Date().toISOString(),metadata:{action:"skipped-not-mobile"}});this.emit("call-start-progress",{stage:"daily-call-join",status:"started",timestamp:new Date().toISOString()});let N=Date.now();w=N;try{await this.call.join({url:l.webCallUrl,...b?{token:b}:{},subscribeToTracksAutomatically:!1});let P=Date.now()-N;this.emit("call-start-progress",{stage:"daily-call-join",status:"completed",duration:P,timestamp:new Date().toISOString()})}catch(P){let B=Date.now()-N,q=it(P);throw this.emit("call-start-progress",{stage:"daily-call-join",status:"failed",duration:B,timestamp:new Date().toISOString(),metadata:{error:q.message}}),this.emit("error",{type:"daily-call-join-error",stage:"daily-call-join",error:q,duration:B,timestamp:new Date().toISOString()}),P}if(p&&b)this.emit("call-start-progress",{stage:"video-recording-setup",status:"completed",timestamp:new Date().toISOString(),metadata:{action:"auto-started-via-meeting-token"}});else if(p){this.emit("call-start-progress",{stage:"video-recording-setup",status:"started",timestamp:new Date().toISOString()});let P=Date.now();try{w=new Date().getTime(),this.startRecording();let B=Date.now()-P;this.emit("call-start-progress",{stage:"video-recording-setup",status:"completed",duration:B,timestamp:new Date().toISOString()})}catch(B){let q=Date.now()-P,K=it(B);this.emit("call-start-progress",{stage:"video-recording-setup",status:"failed",duration:q,timestamp:new Date().toISOString(),metadata:{error:K.message}}),this.emit("error",{type:"video-recording-setup-error",stage:"video-recording-setup",error:K,timestamp:new Date().toISOString()})}}else this.emit("call-start-progress",{stage:"video-recording-setup",status:"completed",timestamp:new Date().toISOString(),metadata:{action:"skipped-not-enabled"}});this.emit("call-start-progress",{stage:"audio-observer-setup",status:"started",timestamp:new Date().toISOString()});let L=Date.now();try{this.call.startRemoteParticipantsAudioLevelObserver(100),this.call.startLocalAudioLevelObserver(100);let P=Date.now()-L;this.emit("call-start-progress",{stage:"audio-observer-setup",status:"completed",duration:P,timestamp:new Date().toISOString()})}catch(P){let B=Date.now()-L,q=it(P);this.emit("call-start-progress",{stage:"audio-observer-setup",status:"failed",duration:B,timestamp:new Date().toISOString(),metadata:{error:q.message}}),this.emit("error",{type:"audio-observer-setup-error",stage:"audio-observer-setup",error:q,timestamp:new Date().toISOString()})}this.call.on("remote-participants-audio-level",P=>{P&&this.handleRemoteParticipantsAudioLevel(P)}),this.call.on("local-audio-level",P=>{P&&this.handleLocalAudioLevel(P)}),this.call.on("app-message",P=>this.onAppMessage(P)),this.call.on("nonfatal-error",P=>{P?.type==="local-audio-level-observer-error"&&this.emit("local-audio-level-observer-error",it(P)),P?.type==="audio-processor-error"&&this.call?.updateInputSettings({audio:{processor:{type:"none"}}}).then(()=>{(0,Wi.safeSetLocalAudio)(this.call,!0)}).catch(B=>{this.emitAudioProcessingError("audio-processor-recovery",B)})}),this.emit("call-start-progress",{stage:"audio-processing-setup",status:"started",timestamp:new Date().toISOString()});let j=Date.now();try{this.call.updateInputSettings({audio:{processor:{type:"noise-cancellation"}}}).catch(B=>{this.emitAudioProcessingError("audio-processing-setup",B)});let P=Date.now()-j;this.emit("call-start-progress",{stage:"audio-processing-setup",status:"completed",duration:P,timestamp:new Date().toISOString()})}catch(P){let B=Date.now()-j,q=it(P);this.emit("call-start-progress",{stage:"audio-processing-setup",status:"failed",duration:B,timestamp:new Date().toISOString(),metadata:{error:q.message}}),this.emit("error",{type:"audio-processing-setup-error",stage:"audio-processing-setup",error:q,timestamp:new Date().toISOString()})}let M=Date.now()-a;
33return this.emit("call-start-success",{totalDuration:M,callId:l?.id||"unknown",timestamp:new Date().toISOString()}),l}catch(d){let l=Date.now()-a,f=it(d);return this.emit("call-start-failed",{stage:"unknown",totalDuration:l,error:f.message,errorStack:f.stack||"No stack trace available",timestamp:new Date().toISOString(),context:{hasAssistant:!!e,hasSquad:!!n,hasWorkflow:!!r,isMobile:this.isMobileDevice()}}),this.emit("error",{type:"start-method-error",stage:"unknown",error:f,totalDuration:l,timestamp:new Date().toISOString(),context:{hasAssistant:!!e,hasSquad:!!n,hasWorkflow:!!r,isMobile:this.isMobileDevice()}}),await this.cleanup(),null}}onAppMessage(e){if(e)try{if(e.data==="listening")return this.emit("call-start");try{let t=JSON.parse(e.data);this.emit("message",t),t&&"type"in t&&"status"in t&&t.type==="status-update"&&t.status==="ended"&&(this.hasEmittedCallEndedStatus=!0)}catch(t){console.log("Error parsing message data: ",t)}}catch(t){console.error(t)}}handleRemoteParticipantsAudioLevel(e){let t=Object.values(e.participantsAudioLevel).reduce((r,s)=>r+s,0);this.emit("volume-level",Math.min(1,t/.15)),t>.01&&(this.speakingTimeout?(clearTimeout(this.speakingTimeout),this.speakingTimeout=null):this.emit("speech-start"),this.speakingTimeout=setTimeout(()=>{this.emit("speech-end"),this.speakingTimeout=null},1e3))}handleLocalAudioLevel(e){this.emit("local-volume-level",e.audioLevel)}async stop(){this.started=!1,this.call&&(await this.call.destroy(),this.call=null),this.audioPlayer=null,this.pendingAudioBuilds.clear(),this.speakingTimeout=null}send(e){this.call?.sendAppMessage(JSON.stringify(e))}audioPlayerBuild(e,t,n){return CP(e,t,n)}audioPlayerDestroy(e){wP(e)}desiredVolumeResolve(){return this.desiredVolume===null||!Number.isFinite(this.desiredVolume)?null:Math.min(1,Math.max(0,this.desiredVolume))}async handleTrackStarted(e){if(!(!e||!e.participant)&&!e.participant?.local&&e.participant?.user_name==="Vapi Speaker"){if(e.track.kind==="video"&&this.emitToConsumer("video",e.track),e.track.kind==="audio"){let t=this.call,n=++this.audioBuildSequence;this.pendingAudioBuilds.set(n,e.participant.session_id);let r;try{r=await this.audioPlayerBuild(e.track,e.participant.session_id,this.desiredVolumeResolve())}catch(o){this.pendingAudioBuilds.delete(n),console.error("[vapi] could not start assistant audio",o),this.emitToConsumer("error",{type:"audio-start-failed",error:it(o)});return}let s=this.pendingAudioBuilds.delete(n);if(!t||this.call!==t||!s||n<this.attachedAudioBuild){r.remove();return}this.attachedAudioBuild=n,this.attachAudioPlayer(r)}this.call?.sendAppMessage("playable")}}attachAudioPlayer(e){this.audioPlayer&&this.audioPlayer!==e&&this.audioPlayer.remove();let t=this.desiredVolumeResolve();t!==null&&(e.volume=t),this.audioPlayer=e,this.emitToConsumer("audio",e)}emitToConsumer(e,...t){try{this.emit(e,...t)}catch(n){console.error(`[vapi] ${e} event listener threw`,n)}}detachAudioPlayer(e){this.audioPlayer?.dataset.participantId===e&&(this.audioPlayer=null);for(let[t,n]of this.pendingAudioBuilds)n===e&&this.pendingAudioBuilds.delete(t);this.audioPlayerDestroy(e)}getAudioPlayer(){return this.audioPlayer}setVolume(e){Number.isFinite(e)&&(this.desiredVolume=Math.min(1,Math.max(0,e)),this.audioPlayer&&(this.audioPlayer.volume=this.desiredVolume))}setMuted(e){(0,Wi.safeSetLocalAudio)(this.call,!e)}isMuted(){return this.call?this.call.localAudio()===!1:!1}say(e,t,n,r){this.send({type:"say",message:e,endCallAfterSpoken:t,interruptionsEnabled:n??!1,interruptAssistantEnabled:r??!1})}end(){this.send({type:"end-call"}),this.stop()}setInputDevicesAsync(e){return(0,Wi.safeSetInputDevicesAsync)(this.call,e)}async increaseMicLevel(e){if(!this.call)throw new Error("Call object is not available.");try{let t=await navigator.mediaDevices.getUserMedia({audio:!0}),n=new AudioContext,r=n.createMediaStreamSource(t),s=n.createGain();s.gain.value=e,r.connect(s);let o=n.createMediaStreamDestination();s.connect(o);let[a]=o.stream.getAudioTracks();await(0,Wi.safeSetInputDevicesAsync)(this.call,{audioSource:a})}catch(t){console.error("Error adjusting microphone level:",t)}}setOutputDeviceAsync(e){this.call?.setOutputDeviceAsync(e)}getDailyCallObject(){return this.call}getLocalAudioLevel(){return this.call?this.call.getLocalAudioLevel():0}async startLocalAudioLevelObserver(e){if(!this.call)throw new Error("Call object is not available.");await this.call.startLocalAudioLevelObserver(e)}stopLocalAudioLevelObserver(){this.call?.stopLocalAudioLevelObserver()}isLocalAudioLevelObserverRunning(){return this.call?this.call.isLocalAudioLevelObserverRunning():!1}startScreenSharing(e,t){this.call?.startScreenShare({displayMediaOptions:e,screenVideoSendSettings:t})}
33stopScreenSharing(){this.call?.stopScreenShare()}startRecording(){if(!this.call)throw new Error("Call object is not available.");this.call.startRecording({width:1280,height:720,backgroundColor:"#FF1F2D3D",layout:{preset:"default"}})}stopRecording(){this.call?.stopRecording()}async reconnect(e){let t=Date.now();if(this.started)throw new Error("Cannot reconnect while a call is already in progress. Call stop() first.");if(!e.webCallUrl)throw new Error("webCallUrl is required for reconnection.");this.emit("call-start-progress",{stage:"reconnect-initialization",status:"started",timestamp:new Date().toISOString(),metadata:{callId:e.id||"unknown",hasVideoRecording:!!e?.artifactPlan?.videoRecordingEnabled,voiceProvider:e?.assistant?.voice?.provider||"unknown"}}),this.started=!0;try{this.call&&(this.emit("call-start-progress",{stage:"cleanup-existing-call",status:"started",timestamp:new Date().toISOString()}),await this.cleanup(),this.emit("call-start-progress",{stage:"cleanup-existing-call",status:"completed",timestamp:new Date().toISOString()}));let n=e?.artifactPlan?.videoRecordingEnabled??!1,r=e?.assistant?.voice?.provider==="tavus",s=e?.transport?.callToken;this.emit("call-start-progress",{stage:"daily-call-object-creation",status:"started",timestamp:new Date().toISOString(),metadata:{audioSource:this.dailyCallObject.audioSource??!0,videoSource:this.dailyCallObject.videoSource??n,isVideoRecordingEnabled:n,isVideoEnabled:r}});let o=Date.now();this.call=ah.default.createCallObject({audioSource:this.dailyCallObject.audioSource??!0,videoSource:this.dailyCallObject.videoSource??n,dailyConfig:this.dailyCallConfig});let a=Date.now()-o;this.emit("call-start-progress",{stage:"daily-call-object-creation",status:"completed",duration:a,timestamp:new Date().toISOString()}),this.call.iframe()?.style.setProperty("display","none"),this.call.on("left-meeting",()=>{this.emit("call-end"),this.hasEmittedCallEndedStatus||(this.emit("message",{type:"status-update",status:"ended",endedReason:"customer-ended-call"}),this.hasEmittedCallEndedStatus=!0),n&&this.call?.stopRecording(),this.cleanup().catch(console.error)}),this.call.on("error",w=>{this.emit("error",{type:"daily-error",error:it(w),timestamp:new Date().toISOString()}),n&&this.call?.stopRecording()}),this.call.on("camera-error",w=>{this.emit("camera-error",{type:"camera-error",error:it(w),timestamp:new Date().toISOString()})}),this.call.on("network-quality-change",w=>{this.emit("network-quality-change",w)}),this.call.on("network-connection",w=>{this.emit("network-connection",w)}),this.call.on("recording-started",w=>{w&&this.emit("recording-started",w)}),this.call.on("recording-stopped",w=>{w&&this.emit("recording-stopped",w)}),this.call.on("recording-stats",w=>{w&&this.emit("recording-stats",w)}),this.call.on("recording-error",w=>{w&&this.emit("recording-error",w)}),this.call.on("recording-upload-completed",w=>{w&&this.emit("recording-upload-completed",w)}),this.call.on("track-started",w=>this.handleTrackStarted(w)),this.call.on("participant-joined",w=>{!w||!this.call||Fk(w,this.call,n,r)}),this.call.on("participant-updated",w=>{w&&this.emit("daily-participant-updated",w.participant)}),this.call.on("participant-left",w=>{w&&this.detachAudioPlayer(w.participant.session_id)}),this.call.on("remote-participants-audio-level",w=>{w&&this.handleRemoteParticipantsAudioLevel(w)}),this.call.on("local-audio-level",w=>{w&&this.handleLocalAudioLevel(w)}),this.call.on("app-message",w=>this.onAppMessage(w)),this.call.on("nonfatal-error",w=>{w?.type==="local-audio-level-observer-error"&&this.emit("local-audio-level-observer-error",it(w)),w?.type==="audio-processor-error"&&this.call?.updateInputSettings({audio:{processor:{type:"none"}}}).then(()=>{(0,Wi.safeSetLocalAudio)(this.call,!0)}).catch(I=>{this.emitAudioProcessingError("audio-processor-recovery",I)})});let d=0;n&&this.call.once("recording-started",()=>{let w=(new Date().getTime()-d)/1e3;this.emit("call-start-progress",{stage:"video-recording-started",status:"completed",timestamp:new Date().toISOString(),metadata:{delaySeconds:w}}),this.send({type:"control",control:"say-first-message",videoRecordingStartDelaySeconds:w})});let l=this.isMobileDevice();
33if(this.emit("call-start-progress",{stage:"mobile-permissions",status:"started",timestamp:new Date().toISOString(),metadata:{isMobile:l}}),l){let w=Date.now();await this.sleep(1e3);let I=Date.now()-w;this.emit("call-start-progress",{stage:"mobile-permissions",status:"completed",duration:I,timestamp:new Date().toISOString(),metadata:{action:"permissions-wait"}})}else this.emit("call-start-progress",{stage:"mobile-permissions",status:"completed",timestamp:new Date().toISOString(),metadata:{action:"skipped-not-mobile"}});this.emit("call-start-progress",{stage:"daily-call-join",status:"started",timestamp:new Date().toISOString()});let f=Date.now();d=f,await this.call.join({url:e.webCallUrl,...s?{token:s}:{},subscribeToTracksAutomatically:!1});let p=Date.now()-f;if(this.emit("call-start-progress",{stage:"daily-call-join",status:"completed",duration:p,timestamp:new Date().toISOString()}),n&&s)this.emit("call-start-progress",{stage:"video-recording-setup",status:"completed",timestamp:new Date().toISOString(),metadata:{action:"auto-started-via-meeting-token"}});else if(n){this.emit("call-start-progress",{stage:"video-recording-setup",status:"started",timestamp:new Date().toISOString()});let w=Date.now();try{d=new Date().getTime(),this.startRecording();let I=Date.now()-w;this.emit("call-start-progress",{stage:"video-recording-setup",status:"completed",duration:I,timestamp:new Date().toISOString()})}catch(I){let N=Date.now()-w,L=it(I);this.emit("call-start-progress",{stage:"video-recording-setup",status:"failed",duration:N,timestamp:new Date().toISOString(),metadata:{error:L.message}})}}else this.emit("call-start-progress",{stage:"video-recording-setup",status:"completed",timestamp:new Date().toISOString(),metadata:{action:"skipped-not-enabled"}});this.emit("call-start-progress",{stage:"audio-observer-setup",status:"started",timestamp:new Date().toISOString()});let g=Date.now();try{this.call.startRemoteParticipantsAudioLevelObserver(100),this.call.startLocalAudioLevelObserver(100);let w=Date.now()-g;this.emit("call-start-progress",{stage:"audio-observer-setup",status:"completed",duration:w,timestamp:new Date().toISOString()})}catch(w){let I=Date.now()-g,N=it(w);this.emit("call-start-progress",{stage:"audio-observer-setup",status:"failed",duration:I,timestamp:new Date().toISOString(),metadata:{error:N.message}})}this.emit("call-start-progress",{stage:"audio-processing-setup",status:"started",timestamp:new Date().toISOString()});let b=Date.now();try{this.call.updateInputSettings({audio:{processor:{type:"noise-cancellation"}}}).catch(I=>{this.emitAudioProcessingError("audio-processing-setup",I)});let w=Date.now()-b;this.emit("call-start-progress",{stage:"audio-processing-setup",status:"completed",duration:w,timestamp:new Date().toISOString()})}catch(w){let I=Date.now()-b,N=it(w);this.emit("call-start-progress",{stage:"audio-processing-setup",status:"failed",duration:I,timestamp:new Date().toISOString(),metadata:{error:N.message}})}let R=Date.now()-t;this.emit("call-start-success",{totalDuration:R,callId:e?.id||"unknown",timestamp:new Date().toISOString()}),this.emit("call-start")}catch(n){let r=Date.now()-t,s=it(n);throw this.emit("call-start-failed",{stage:"reconnect",totalDuration:r,error:s.message,errorStack:s.stack||"No stack trace available",timestamp:new Date().toISOString(),context:{isReconnect:!0,callId:e?.id||"unknown",hasVideoRecording:!!e?.artifactPlan?.videoRecordingEnabled,voiceProvider:e?.assistant?.voice?.provider||"unknown",isMobile:this.isMobileDevice()}}),this.emit("error",{type:"reconnect-error",error:s,totalDuration:r,timestamp:new Date().toISOString(),context:{isReconnect:!0,callId:e?.id||"unknown",hasVideoRecording:!!e?.artifactPlan?.videoRecordingEnabled,voiceProvider:e?.assistant?.voice?.provider||"unknown",isMobile:this.isMobileDevice()}}),await this.cleanup(),n}}static async runNetworkTestsStandalone(){console.log("Starting standalone network connectivity tests...");let e={},t=null;try{console.log("Creating temporary call object for testing..."),t=ah.default.createCallObject({audioSource:!0,videoSource:!0}),console.log(` 341. Testing network connectivity (TURN server)...`);let n=null;try{n=(await navigator.mediaDevices.getUserMedia({video:!0})).getVideoTracks()[0];let s=await t.testNetworkConnectivity(n);e.networkConnectivity=s,console.log("Network connectivity test result:",s)}catch(r){e.networkConnectivity={result:"error",error:r?.toString()},console.error("Network connectivity test error:",r)}finally{n&&n.stop()}console.log(` 352. Testing websocket connectivity...`);try{let r=await t.testWebsocketConnectivity();e.websocketConnectivity=r,console.log("Websocket connectivity test result:",r)}catch(r){e.websocketConnectivity={result:"error",error:r?.toString()},console.error("Websocket connectivity test error:",r)}console.log(` 363. Testing call quality...`);try{if(typeof t.testCallQuality=="function")try{console.log("Initializing call state with startCamera..."),await t.startCamera();let r=await t.testCallQuality();e.callQuality=r,console.log("Call quality test result:",r)}catch(r){console.error("Failed to start camera for call quality test:",r),e.callQuality={result:"error",error:r?.toString(),message:"Failed to initialize camera for call quality test. Check camera permissions."}}else e.callQuality={result:"not-available",message:"testCallQuality method not available"},console.log("Call quality test not available in current Daily.co version")}catch(r){e.callQuality={result:"error",error:r?.toString()},console.error("Call quality test error:",r)}}catch(n){console.error("Failed to create temporary call object:",n),e.error=n?.toString()}finally{if(t)try{console.log("Cleaning up temporary call object..."),await t.destroy()}catch(n){console.error("Error destroying temporary call object:",n)}}return console.log(` 37=== Network Test Summary ===`),console.log("Results:",JSON.stringify(e,null,2)),e}};qs.default=uh});function Hm(i){return i.replace(/(?:[_-])([a-z0-9])/g,(e,t)=>t.toUpperCase())}function VT(i){return Hm(i.replace(/--/g,"-").replace(/__/g,"_"))}function bo(i){return i.charAt(0).toUpperCase()+i.slice(1)}function $T(i){return i.replace(/([A-Z])/g,(e,t)=>`-${t.toLowerCase()}`)}function jm(i){return i!=null}function Bm(i,e){return Object.prototype.hasOwnProperty.call(i,e)}function hl(i,e){let t=Km(i);return Array.from(t.reduce((n,r)=>(GT(r,e).forEach(s=>n.add(s)),n),new Set))}function WT(i,e){return Km(i).reduce((n,r)=>(n.push(...JT(r,e)),n),[])}function Km(i){let e=[];for(;i;)e.push(i),i=Object.getPrototypeOf(i);return e.reverse()}function GT(i,e){let t=i[e];return Array.isArray(t)?t:[]}function JT(i,e){let t=i[e];return t?Object.keys(t).map(n=>[n,t[n]]):[]}var PP=(()=>{function i(t){function n(){return Reflect.construct(t,arguments,new.target)}return n.prototype=Object.create(t.prototype,{constructor:{value:n}}),Reflect.setPrototypeOf(n,t),n}function e(){let n=i(function(){this.a.call(this)});return n.prototype.a=function(){},new n}try{return e(),i}catch{return n=>class extends n{}}})();var MP={controllerAttribute:"data-controller",actionAttribute:"data-action",targetAttribute:"data-target",targetAttributeForScope:i=>`data-${i}-target`,outletAttributeForScope:(i,e)=>`data-${i}-${e}
37-outlet`,keyMappings:Object.assign(Object.assign({enter:"Enter",tab:"Tab",esc:"Escape",space:" ",up:"ArrowUp",down:"ArrowDown",left:"ArrowLeft",right:"ArrowRight",home:"Home",end:"End",page_up:"PageUp",page_down:"PageDown"},qm("abcdefghijklmnopqrstuvwxyz".split("").map(i=>[i,i]))),qm("0123456789".split("").map(i=>[i,i])))};function qm(i){return i.reduce((e,[t,n])=>Object.assign(Object.assign({},e),{[t]:n}),{})}function HT(i){return hl(i,"classes").reduce((t,n)=>Object.assign(t,KT(n)),{})}function KT(i){return{[`${i}Class`]:{get(){let{classes:e}=this;if(e.has(i))return e.get(i);{let t=e.getAttributeName(i);throw new Error(`Missing attribute "${t}"`)}}},[`${i}Classes`]:{get(){return this.classes.getAll(i)}},[`has${bo(i)}Class`]:{get(){return this.classes.has(i)}}}}function zT(i){return hl(i,"outlets").reduce((t,n)=>Object.assign(t,YT(n)),{})}function Vm(i,e,t){return i.application.getControllerForElementAndIdentifier(e,t)}function $m(i,e,t){let n=Vm(i,e,t);if(n||(i.application.router.proposeToConnectScopeForElementAndIdentifier(e,t),n=Vm(i,e,t),n))return n}function YT(i){let e=VT(i);return{[`${e}Outlet`]:{get(){let t=this.outlets.find(i),n=this.outlets.getSelectorForOutletName(i);if(t){let r=$m(this,t,i);if(r)return r;throw new Error(`The provided outlet element is missing an outlet controller "${i}" instance for host controller "${this.identifier}"`)}throw new Error(`Missing outlet element "${i}" for host controller "${this.identifier}". Stimulus couldn't find a matching outlet element using selector "${n}".`)}},[`${e}Outlets`]:{get(){let t=this.outlets.findAll(i);return t.length>0?t.map(n=>{let r=$m(this,n,i);if(r)return r;console.warn(`The provided outlet element is missing an outlet controller "${i}" instance for host controller "${this.identifier}"`,n)}).filter(n=>n):[]}},[`${e}OutletElement`]:{get(){let t=this.outlets.find(i),n=this.outlets.getSelectorForOutletName(i);if(t)return t;throw new Error(`Missing outlet element "${i}" for host controller "${this.identifier}". Stimulus couldn't find a matching outlet element using selector "${n}".`)}},[`${e}OutletElements`]:{get(){return this.outlets.findAll(i)}},[`has${bo(e)}Outlet`]:{get(){return this.outlets.has(i)}}}}function QT(i){return hl(i,"targets").reduce((t,n)=>Object.assign(t,XT(n)),{})}function XT(i){return{[`${i}Target`]:{get(){let e=this.targets.find(i);if(e)return e;throw new Error(`Missing target element "${i}" for "${this.identifier}" controller`)}},[`${i}Targets`]:{get(){return this.targets.findAll(i)}},[`has${bo(i)}Target`]:{get(){return this.targets.has(i)}}}}function ZT(i){let e=WT(i,"values"),t={valueDescriptorMap:{get(){return e.reduce((n,r)=>{let s=zm(r,this.identifier),o=this.data.getAttributeNameForKey(s.key);return Object.assign(n,{[o]:s})},{})}}};return e.reduce((n,r)=>Object.assign(n,e0(r)),t)}function e0(i,e){let t=zm(i,e),{key:n,name:r,reader:s,writer:o}=t;return{[r]:{get(){let a=this.data.get(n);return a!==null?s(a):t.defaultValue},set(a){a===void 0?this.data.delete(n):this.data.set(n,o(a))}},[`has${bo(r)}`]:{get(){return this.data.has(n)||t.hasCustomDefaultValue}}}}function zm([i,e],t){return r0({controller:t,token:i,typeDefinition:e})}function yo(i){switch(i){case Array:return"array";case Boolean:return"boolean";case Number:return"number";case Object:return"object";case String:return"string"}}function Zr(i){switch(typeof i){case"boolean":return"boolean";case"number":return"number";case"string":return"string"}if(Array.isArray(i))return"array";if(Object.prototype.toString.call(i)==="[object Object]")return"object"}function t0(i){let{controller:e,token:t,typeObject:n}=i,r=jm(n.type),s=jm(n.default),o=r&&s,a=r&&!s,d=!r&&s,l=yo(n.type),f=Zr(i.typeObject.default);if(a)return l;if(d)return f;if(l!==f){let p=e?`${e}.${t}`:t;throw new Error(`The specified default value for the Stimulus Value "${p}" must match the defined type "${l}". The provided default value of "${n.default}" is of type "${f}".`)}if(o)return l}function n0(i){let{controller:e,token:t,typeDefinition:n}=i,s=t0({controller:e,token:t,typeObject:n}),o=Zr(n),a=yo(n),d=s||o||a;if(d)return d;let l=e?`${e}.${n}`:t;throw new Error(`Unknown value type "${l}" for "${t}" value`)}function i0(i){let e=yo(i);if(e)return Wm[e];let t=Bm(i,"default"),n=Bm(i,"type"),r=i;if(t)return r.default;if(n){let{type:s}=r,o=yo(s);if(o)return Wm[o]}return i}function r0(i){let{token:e,typeDefinition:t}=i,n=`${$T(e)}-value`,r=n0(i);return{type:r,key:n,name:Hm(n),get defaultValue(){return i0(t)},get hasCustomDefaultValue(){return Zr(t)!==void 0},reader:s0[r],writer:Gm[r]||Gm.default}}var Wm={get array(){return[]},boolean:!1,number:0,get object(){return{}},string:""},s0={array(i){let e=JSON.parse(i);if(!Array.isArray(e))throw new TypeError(`expected value of type "array" but instead got value "${i}" of type "${Zr(e)}"`);return e},boolean(i){return!(i=="0"||String(i).toLowerCase()=="false")},number(i){return Number(i.replace(/_/g,""))},object(i){let e=JSON.parse(i);if(e===null||typeof e!="object"||Array.isArray(e))throw new TypeError(`expected value of type "object" but instead got value "${i}" of type "${Zr(e)}"`);return e},string(i){return i}},Gm={default:o0,array:Jm,object:Jm};function Jm(i){return JSON.stringify(i)}function o0(i){return`${i}`}var Gn=class{constructor(e){this.context=e}static get shouldLoad(){return!0}static afterLoad(e,t){}get application(){return this.context.application}get scope(){return this.context.scope}
37get element(){return this.scope.element}get identifier(){return this.scope.identifier}get targets(){return this.scope.targets}get outlets(){return this.scope.outlets}get classes(){return this.scope.classes}get data(){return this.scope.data}initialize(){}connect(){}disconnect(){}dispatch(e,{target:t=this.element,detail:n={},prefix:r=this.identifier,bubbles:s=!0,cancelable:o=!0}={}){let a=r?`${r}:${e}`:e,d=new CustomEvent(a,{detail:n,bubbles:s,cancelable:o});return t.dispatchEvent(d),d}};Gn.blessings=[HT,QT,ZT,zT];Gn.targets=[];Gn.outlets=[];Gn.values={};function Ym(i,e={}){window.Sentry&&window.Sentry.captureException(i,{extra:e})}var bi=class extends Gn{captureError(e,t={}){let n={controller:this.identifier,element:this.element?.outerHTML?.substring(0,200),...t};Ym(e,n)}};var ar=class{queue=[];outgoingQueue=[];disconnectionDetails=null;onDisconnectCallback=null;onMessageCallback=null;onModeChangeCallback=null;onDebug;onOutgoingMessageCallback=null;constructor(e={}){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}onOutgoingMessage(e){this.onOutgoingMessageCallback=e;let t=this.outgoingQueue;this.outgoingQueue=[],t.length>0&&queueMicrotask(()=>{t.forEach(e)})}updateMode(e){this.onModeChangeCallback?.(e)}disconnect(e){this.disconnectionDetails||(this.disconnectionDetails=e,this.onDisconnectCallback?.(e))}handleMessage(e){this.onMessageCallback?this.onMessageCallback(e):this.queue.push(e)}handleOutgoingMessage(e){this.onOutgoingMessageCallback?this.onOutgoingMessageCallback(e):this.outgoingQueue.push(e)}};function cr(i){let[e,t]=i.split("_");if(!["pcm","ulaw"].includes(e))throw new Error(`Invalid format: ${i}`);let n=Number.parseInt(t);if(Number.isNaN(n))throw new Error(`Invalid sample rate: ${t}`);return{format:e,sampleRate:n}}function lr(i){return i!=null&&typeof i=="object"&&!Array.isArray(i)}function Qm(i,e="Expected a JSON object"){if(!lr(i))throw new Error(e)}async function ko(i){try{let e=await i.json();if(!lr(e))return i.statusText||"Unknown error";let t=e.detail,n=lr(t)?t.message:t;if(typeof n=="string")return n}catch(e){console.warn("Failed to parse API error response as JSON:",e)}return i.statusText||"Unknown error"}var ur=class extends Error{closeCode;closeReason;constructor(e,t){super(e),this.name="SessionConnectionError",this.closeCode=t?.closeCode,this.closeReason=t?.closeReason}};var Xm="1.25.0";var ki=Object.freeze({name:"js_sdk",version:Xm});function dr(i){return!!i.type}function a0(i,e){return e.forEach(function(t){t&&typeof t!="string"&&!Array.isArray(t)&&Object.keys(t).forEach(function(n){if(n!=="default"&&!(n in i)){var r=Object.getOwnPropertyDescriptor(t,n);Object.defineProperty(i,n,r.get?r:{enumerable:!0,get:function(){return t[n]}})}})}),Object.freeze(i)}var c0=Object.defineProperty,l0=(i,e,t)=>e in i?c0(i,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):i[e]=t,Zm=(i,e,t)=>l0(i,typeof e!="symbol"?e+"":e,t),tt=class{constructor(){Zm(this,"_locking"),Zm(this,"_locks"),this._locking=Promise.resolve(),this._locks=0}isLocked(){return this._locks>0}lock(){this._locks+=1;let e,t=new Promise(r=>e=()=>{this._locks-=1,r()}),n=this._locking.then(()=>e);return this._locking=this._locking.then(()=>t),n}};function Ke(i,e){if(!i)throw new Error(e)}var u0=34028234663852886e22,d0=-34028234663852886e22,h0=4294967295,p0=2147483647,f0=-2147483648;function Po(i){if(typeof i!="number")throw new Error("invalid int 32: "+typeof i);if(!Number.isInteger(i)||i>p0||i<f0)throw new Error("invalid int 32: "+i)}function jl(i){if(typeof i!="number")throw new Error("invalid uint 32: "+typeof i);if(!Number.isInteger(i)||i>h0||i<0)throw new Error("invalid uint 32: "+i)}function vv(i){if(typeof i!="number")throw new Error("invalid float 32: "+typeof i);if(Number.isFinite(i)&&(i>u0||i<d0))throw new Error("invalid float 32: "+i)}var yv=Symbol("@bufbuild/protobuf/enum-type");function m0(i){let e=i[yv];return Ke(e,"missing enum type on enum object"),e}function bv(i,e,t,n){i[yv]=kv(e,t.map(r=>({no:r.no,name:r.name,localName:i[r.no]})))}function kv(i,e,t){let n=Object.create(null),r=Object.create(null),s=[];for(let o of e){let a=Sv(o);s.push(a),n[o.name]=a,r[o.no]=a}return{typeName:i,values:s,findName(o){return n[o]},findNumber(o){return r[o]}}}function g0(i,e,t){let n={};for(let r of e){let s=Sv(r);n[s.localName]=s.no,n[s.no]=s.localName}return bv(n,i,e),n}function Sv(i){return"localName"in i?i:Object.assign(Object.assign({},i),{localName:i.name})}var ms=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(),r=n.runtime.bin,s=r.makeReadOptions(t);return r.readMessage(this,s.readerFactory(e),e.byteLength,s),this}fromJson(e,t){let n=this.getType(),r=n.runtime.json,s=r.makeReadOptions(t);return r.readMessage(n,e,s,this),this}fromJsonString(e,t){let n;try{n=JSON.parse(e)}catch(r){throw new Error("cannot decode ".concat(this.getType().typeName," from JSON: ").concat(r instanceof Error?r.message:String(r)))}return this.fromJson(n,t)}toBinary(e){let t=this.getType(),n=t.runtime.bin,r=n.makeWriteOptions(e),s=r.writerFactory();return n.writeMessage(this,s,r),s.finish()}
37toJson(e){let t=this.getType(),n=t.runtime.json,r=n.makeWriteOptions(e);return n.writeMessage(this,r)}toJsonString(e){var t;let n=this.toJson(e);return JSON.stringify(n,null,(t=e?.prettySpaces)!==null&&t!==void 0?t:0)}toJSON(){return this.toJson({emitDefaultValues:!0})}getType(){return Object.getPrototypeOf(this).constructor}};function v0(i,e,t,n){var r;let s=(r=n?.localName)!==null&&r!==void 0?r:e.substring(e.lastIndexOf(".")+1),o={[s]:function(a){i.util.initFields(this),i.util.initPartial(a,this)}}[s];return Object.setPrototypeOf(o.prototype,new ms),Object.assign(o,{runtime:i,typeName:e,fields:i.util.newFieldList(t),fromBinary(a,d){return new o().fromBinary(a,d)},fromJson(a,d){return new o().fromJson(a,d)},fromJsonString(a,d){return new o().fromJsonString(a,d)},equals(a,d){return i.util.equals(o,a,d)}}),o}function y0(){let i=0,e=0;for(let n=0;n<28;n+=7){let r=this.buf[this.pos++];if(i|=(r&127)<<n,(r&128)==0)return this.assertBounds(),[i,e]}let t=this.buf[this.pos++];if(i|=(t&15)<<28,e=(t&112)>>4,(t&128)==0)return this.assertBounds(),[i,e];for(let n=3;n<=31;n+=7){let r=this.buf[this.pos++];if(e|=(r&127)<<n,(r&128)==0)return this.assertBounds(),[i,e]}throw new Error("invalid varint")}function pl(i,e,t){for(let s=0;s<28;s=s+7){let o=i>>>s,a=!(!(o>>>7)&&e==0),d=(a?o|128:o)&255;if(t.push(d),!a)return}let n=i>>>28&15|(e&7)<<4,r=e>>3!=0;if(t.push((r?n|128:n)&255),!!r){for(let s=3;s<31;s=s+7){let o=e>>>s,a=!!(o>>>7),d=(a?o|128:o)&255;if(t.push(d),!a)return}t.push(e>>>31&1)}}var Ao=4294967296;function eg(i){let e=i[0]==="-";e&&(i=i.slice(1));let t=1e6,n=0,r=0;function s(o,a){let d=Number(i.slice(o,a));r*=t,n=n*t+d,n>=Ao&&(r=r+(n/Ao|0),n=n%Ao)}return s(-24,-18),s(-18,-12),s(-12,-6),s(-6),e?_v(n,r):md(n,r)}function b0(i,e){let t=md(i,e),n=t.hi&2147483648;n&&(t=_v(t.lo,t.hi));let r=Tv(t.lo,t.hi);return n?"-"+r:r}function Tv(i,e){var t=k0(i,e);if(i=t.lo,e=t.hi,e<=2097151)return String(Ao*e+i);let n=i&16777215,r=(i>>>24|e<<8)&16777215,s=e>>16&65535,o=n+r*6777216+s*6710656,a=r+s*8147497,d=s*2,l=1e7;return o>=l&&(a+=Math.floor(o/l),o%=l),a>=l&&(d+=Math.floor(a/l),a%=l),d.toString()+tg(a)+tg(o)}function k0(i,e){return{lo:i>>>0,hi:e>>>0}}function md(i,e){return{lo:i|0,hi:e|0}}function _v(i,e){return e=~e,i?i=~i+1:e+=1,md(i,e)}var tg=i=>{let e=String(i);return"0000000".slice(e.length)+e};function ng(i,e){if(i>=0){for(;i>127;)e.push(i&127|128),i=i>>>7;e.push(i)}else{for(let t=0;t<9;t++)e.push(i&127|128),i=i>>7;e.push(1)}}function S0(){let i=this.buf[this.pos++],e=i&127;if((i&128)==0)return this.assertBounds(),e;if(i=this.buf[this.pos++],e|=(i&127)<<7,(i&128)==0)return this.assertBounds(),e;if(i=this.buf[this.pos++],e|=(i&127)<<14,(i&128)==0)return this.assertBounds(),e;if(i=this.buf[this.pos++],e|=(i&127)<<21,(i&128)==0)return this.assertBounds(),e;i=this.buf[this.pos++],e|=(i&15)<<28;for(let t=5;(i&128)!==0&&t<10;t++)i=this.buf[this.pos++];if((i&128)!=0)throw new Error("invalid varint");return this.assertBounds(),e>>>0}function T0(){let i=new DataView(new ArrayBuffer(8));if(typeof BigInt=="function"&&typeof i.getBigInt64=="function"&&typeof i.getBigUint64=="function"&&typeof i.setBigInt64=="function"&&typeof i.setBigUint64=="function"&&(typeof process!="object"||typeof process.env!="object"||process.env.BUF_BIGINT_DISABLE!=="1")){let r=BigInt("-9223372036854775808"),s=BigInt("9223372036854775807"),o=BigInt("0"),a=BigInt("18446744073709551615");return{zero:BigInt(0),supported:!0,parse(d){let l=typeof d=="bigint"?d:BigInt(d);if(l>s||l<r)throw new Error("int64 invalid: ".concat(d));return l},uParse(d){let l=typeof d=="bigint"?d:BigInt(d);if(l>a||l<o)throw new Error("uint64 invalid: ".concat(d));return l},enc(d){return i.setBigInt64(0,this.parse(d),!0),{lo:i.getInt32(0,!0),hi:i.getInt32(4,!0)}},uEnc(d){return i.setBigInt64(0,this.uParse(d),!0),{lo:i.getInt32(0,!0),hi:i.getInt32(4,!0)}},dec(d,l){return i.setInt32(0,d,!0),i.setInt32(4,l,!0),i.getBigInt64(0,!0)},uDec(d,l){return i.setInt32(0,d,!0),i.setInt32(4,l,!0),i.getBigUint64(0,!0)}}}let t=r=>Ke(/^-?[0-9]+$/.test(r),"int64 invalid: ".concat(r)),n=r=>Ke(/^[0-9]+$/.test(r),"uint64 invalid: ".concat(r));return{zero:"0",supported:!1,parse(r){return typeof r!="string"&&(r=r.toString()),t(r),r},uParse(r){return typeof r!="string"&&(r=r.toString()),n(r),r},enc(r){return typeof r!="string"&&(r=r.toString()),t(r),eg(r)},uEnc(r){return typeof r!="string"&&(r=r.toString()),n(r),eg(r)},dec(r,s){return b0(r,s)},uDec(r,s){return Tv(r,s)}}}var Ge=T0(),Y;(function(i){i[i.DOUBLE=1]="DOUBLE",i[i.FLOAT=2]="FLOAT",i[i.INT64=3]="INT64",i[i.UINT64=4]="UINT64",i[i.INT32=5]="INT32",i[i.FIXED64=6]="FIXED64",i[i.FIXED32=7]="FIXED32",i[i.BOOL=8]="BOOL",i[i.STRING=9]="STRING",i[i.BYTES=12]="BYTES",i[i.UINT32=13]="UINT32",i[i.SFIXED32=15]="SFIXED32",i[i.SFIXED64=16]="SFIXED64",i[i.SINT32=17]="SINT32",i[i.SINT64=18]="SINT64"})(Y||(Y={}));var ni;(function(i){i[i.BIGINT=0]="BIGINT",i[i.STRING=1]="STRING"})(ni||(ni={}));function Jn(i,e,t){if(e===t)return!0;
37if(i==Y.BYTES){if(!(e instanceof Uint8Array)||!(t instanceof Uint8Array)||e.length!==t.length)return!1;for(let n=0;n<e.length;n++)if(e[n]!==t[n])return!1;return!0}switch(i){case Y.UINT64:case Y.FIXED64:case Y.INT64:case Y.SFIXED64:case Y.SINT64:return e==t}return!1}function wr(i,e){switch(i){case Y.BOOL:return!1;case Y.UINT64:case Y.FIXED64:case Y.INT64:case Y.SFIXED64:case Y.SINT64:return e==0?Ge.zero:"0";case Y.DOUBLE:case Y.FLOAT:return 0;case Y.BYTES:return new Uint8Array(0);case Y.STRING:return"";default:return 0}}function Cv(i,e){switch(i){case Y.BOOL:return e===!1;case Y.STRING:return e==="";case Y.BYTES:return e instanceof Uint8Array&&!e.byteLength;default:return e==0}}function ig(i,e){(e==null||e>i.length)&&(e=i.length);for(var t=0,n=Array(e);t<e;t++)n[t]=i[t];return n}function _0(i){if(Array.isArray(i))return i}function Ce(i,e,t){return(e=P0(e))in i?Object.defineProperty(i,e,{value:t,enumerable:!0,configurable:!0,writable:!0}):i[e]=t,i}function C0(i,e){var t=i==null?null:typeof Symbol<"u"&&i[Symbol.iterator]||i["@@iterator"];if(t!=null){var n,r,s,o,a=[],d=!0,l=!1;try{if(s=(t=t.call(i)).next,e===0){if(Object(t)!==t)return;d=!1}else for(;!(d=(n=s.call(t)).done)&&(a.push(n.value),a.length!==e);d=!0);}catch(f){l=!0,r=f}finally{try{if(!d&&t.return!=null&&(o=t.return(),Object(o)!==o))return}finally{if(l)throw r}}return a}}function w0(){throw new TypeError(`Invalid attempt to destructure non-iterable instance. 38In order to be iterable, non-array objects must have a [Symbol.iterator]() method.`)}function pe(i,e){return _0(i)||C0(i,e)||A0(i,e)||w0()}function E0(i,e){if(typeof i!="object"||!i)return i;var t=i[Symbol.toPrimitive];if(t!==void 0){var n=t.call(i,e);if(typeof n!="object")return n;throw new TypeError("@@toPrimitive must return a primitive value.")}return(e==="string"?String:Number)(i)}function P0(i){var e=E0(i,"string");return typeof e=="symbol"?e:e+""}function A0(i,e){if(i){if(typeof i=="string")return ig(i,e);var t={}.toString.call(i).slice(8,-1);return t==="Object"&&i.constructor&&(t=i.constructor.name),t==="Map"||t==="Set"?Array.from(i):t==="Arguments"||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(t)?ig(i,e):void 0}}var Qe;(function(i){i[i.Varint=0]="Varint",i[i.Bit64=1]="Bit64",i[i.LengthDelimited=2]="LengthDelimited",i[i.StartGroup=3]="StartGroup",i[i.EndGroup=4]="EndGroup",i[i.Bit32=5]="Bit32"})(Qe||(Qe={}));var Bl=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 r=0;r<this.chunks.length;r++)e+=this.chunks[r].length;let t=new Uint8Array(e),n=0;for(let r=0;r<this.chunks.length;r++)t.set(this.chunks[r],n),n+=this.chunks[r].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 new 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(jl(e);e>127;)this.buf.push(e&127|128),e=e>>>7;return this.buf.push(e),this}int32(e){return Po(e),ng(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){vv(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){jl(e);let t=new Uint8Array(4);return new DataView(t.buffer).setUint32(0,e,!0),this.raw(t)}sfixed32(e){Po(e);let t=new Uint8Array(4);return new DataView(t.buffer).setInt32(0,e,!0),this.raw(t)}sint32(e){return Po(e),e=(e<<1^e>>31)>>>0,ng(e,this.buf),this}sfixed64(e){let t=new Uint8Array(8),n=new DataView(t.buffer),r=Ge.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=Ge.uEnc(e);return n.setInt32(0,r.lo,!0),n.setInt32(4,r.hi,!0),this.raw(t)}int64(e){let t=Ge.enc(e);return pl(t.lo,t.hi,this.buf),this}sint64(e){let t=Ge.enc(e),n=t.hi>>31,r=t.lo<<1^n,s=(t.hi<<1|t.lo>>>31)^n;return pl(r,s,this.buf),this}uint64(e){let t=Ge.uEnc(e);return pl(t.lo,t.hi,this.buf),this}},ql=class{constructor(e,t){this.varint64=y0,this.uint32=S0,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;
vendor: 7,599 bytes, lines 38-39
38if(t<=0||n<0||n>5)throw new Error("illegal tag: field no "+t+" wire type "+n);return[t,n]}skip(e,t){let n=this.pos;switch(e){case Qe.Varint:for(;this.buf[this.pos++]&128;);break;case Qe.Bit64:this.pos+=4;case Qe.Bit32:this.pos+=4;break;case Qe.LengthDelimited:let r=this.uint32();this.pos+=r;break;case Qe.StartGroup:for(;;){let s=this.tag(),o=pe(s,2),a=o[0],d=o[1];if(d===Qe.EndGroup){if(t!==void 0&&a!==t)throw new Error("invalid end group tag");break}this.skip(d,a)}break;default:throw new Error("cant skip wire type "+e)}return this.assertBounds(),this.buf.subarray(n,this.pos)}assertBounds(){if(this.pos>this.len)throw new RangeError("premature EOF")}int32(){return this.uint32()|0}sint32(){let e=this.uint32();return e>>>1^-(e&1)}int64(){return Ge.dec(...this.varint64())}uint64(){return Ge.uDec(...this.varint64())}sint64(){let e=this.varint64(),t=pe(e,2),n=t[0],r=t[1],s=-(n&1);return n=(n>>>1|(r&1)<<31)^s,r=r>>>1^s,Ge.dec(n,r)}bool(){let e=this.varint64(),t=pe(e,2),n=t[0],r=t[1];return n!==0||r!==0}fixed32(){return this.view.getUint32((this.pos+=4)-4,!0)}sfixed32(){return this.view.getInt32((this.pos+=4)-4,!0)}fixed64(){return Ge.uDec(this.sfixed32(),this.sfixed32())}sfixed64(){return Ge.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 M0(i,e,t,n){let r;return{typeName:e,extendee:t,get field(){if(!r){let s=typeof n=="function"?n():n;s.name=e.split(".").pop(),s.jsonName="[".concat(e,"]"),r=i.util.newFieldList([s]).list()[0]}return r},runtime:i}}function wv(i){let e=i.field.localName,t=Object.create(null);return t[e]=R0(i),[t,()=>t[e]]}function R0(i){let e=i.field;if(e.repeated)return[];if(e.default!==void 0)return e.default;switch(e.kind){case"enum":return e.T.values[0].no;case"scalar":return wr(e.T,e.L);case"message":let t=e.T,n=new t;return t.fieldWrapper?t.fieldWrapper.unwrapField(n):n;case"map":throw"map fields are not allowed to be extensions"}}function I0(i,e){if(!e.repeated&&(e.kind=="enum"||e.kind=="scalar")){for(let t=i.length-1;t>=0;--t)if(i[t].no==e.no)return[i[t]];return[]}return i.filter(t=>t.no===e.no)}var On="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/".split(""),_a=[];for(let i=0;i<On.length;i++)_a[On[i].charCodeAt(0)]=i;_a[45]=On.indexOf("+");_a[95]=On.indexOf("/");var Ev={dec(i){let e=i.length*3/4;i[i.length-2]=="="?e-=2:i[i.length-1]=="="&&(e-=1);let t=new Uint8Array(e),n=0,r=0,s,o=0;for(let a=0;a<i.length;a++){if(s=_a[i.charCodeAt(a)],s===void 0)switch(i[a]){case"=":r=0;case` 39`:case"\r":case" ":case" ":continue;default:throw Error("invalid base64 string.")}switch(r){case 0:o=s,r=1;break;case 1:t[n++]=o<<2|(s&48)>>4,o=s,r=2;break;case 2:t[n++]=(o&15)<<4|(s&60)>>2,o=s,r=3;break;case 3:t[n++]=(o&3)<<6|s,r=0;break}}if(r==1)throw Error("invalid base64 string.");return t.subarray(0,n)},enc(i){let e="",t=0,n,r=0;for(let s=0;s<i.length;s++)switch(n=i[s],t){case 0:e+=On[n>>2],r=(n&3)<<4,t=1;break;case 1:e+=On[r|n>>4],r=(n&15)<<2,t=2;break;case 2:e+=On[r|n>>6],e+=On[n&63],t=0;break}return t&&(e+=On[r],e+="=",t==1&&(e+="=")),e}};function O0(i,e,t){Av(e,i);let n=e.runtime.bin.makeReadOptions(t),r=I0(i.getType().runtime.bin.listUnknownFields(i),e.field),s=wv(e),o=pe(s,2),a=o[0],d=o[1];for(let l of r)e.runtime.bin.readField(a,n.readerFactory(l.data),e.field,l.wireType,n);return d()}function D0(i,e,t,n){Av(e,i);let r=e.runtime.bin.makeReadOptions(n),s=e.runtime.bin.makeWriteOptions(n);if(Pv(i,e)){let l=i.getType().runtime.bin.listUnknownFields(i).filter(f=>f.no!=e.field.no);i.getType().runtime.bin.discardUnknownFields(i);for(let f of l)i.getType().runtime.bin.onUnknownField(i,f.no,f.wireType,f.data)}let o=s.writerFactory(),a=e.field;!a.opt&&!a.repeated&&(a.kind=="enum"||a.kind=="scalar")&&(a=Object.assign(Object.assign({},e.field),{opt:!0})),e.runtime.bin.writeField(a,t,o,s);let d=r.readerFactory(o.finish());for(;d.pos<d.len;){let l=d.tag(),f=pe(l,2),p=f[0],g=f[1],b=d.skip(g,p);i.getType().runtime.bin.onUnknownField(i,p,g,b)}}function Pv(i,e){let t=i.getType();return e.extendee.typeName===t.typeName&&!!t.runtime.bin.listUnknownFields(i).find(n=>n.no==e.field.no)}function Av(i,e){Ke(i.extendee.typeName==e.getType().typeName,"extension ".concat(i.typeName," can only be applied to message ").concat(i.extendee.typeName))}function Mv(i,e){let t=i.localName;if(i.repeated)return e[t].length>0;if(i.oneof)return e[i.oneof.localName].case===t;switch(i.kind){case"enum":case"scalar":return i.opt||i.req?e[t]!==void 0:i.kind=="enum"?e[t]!==i.T.values[0].no:!Cv(i.T,e[t]);case"message":return e[t]!==void 0;case"map":return Object.keys(e[t]).length>0}}function rg(i,e){let t=i.localName,n=!i.opt&&!i.req;if(i.repeated)e[t]=[];else if(i.oneof)e[i.oneof.localName]={case:void 0};else switch(i.kind){case"map":e[t]={};break;case"enum":e[t]=n?i.T.values[0].no:void 0;break;case"scalar":e[t]=n?wr(i.T,i.L):void 0;break;case"message":e[t]=void 0;break}}function Dn(i,e){if(i===null||typeof i!="object"||!Object.getOwnPropertyNames(ms.prototype).every(n=>n in i&&typeof i[n]=="function"))return!1;let t=i.getType();return t===null||typeof t!="function"||!("typeName"in t)||typeof t.typeName!="string"?!1:e===void 0?!0:t.typeName==e.typeName}function Rv(i,e){return Dn(e)||!i.fieldWrapper?e:i.fieldWrapper.wrapField(e)}Y.DOUBLE,Y.FLOAT,Y.INT64,Y.UINT64,Y.INT32,Y.UINT32,Y.BOOL,Y.STRING,Y.BYTES;var sg={ignoreUnknownFields:!1},og={emitDefaultValues:!1,enumAsInteger:!1,useProtoFieldName:!1,prettySpaces:0};function L0(i){return i?Object.assign(Object.assign({},sg),i):sg}function x0(i){return i?Object.assign(Object.assign({},og),i):og}var Bo=Symbol(),Mo=Symbol();function N0(){return{makeReadOptions:L0,makeWriteOptions:x0,readMessage(i,e,t,n){if(e==null||Array.isArray(e)||typeof e!="object")throw new Error("cannot decode message ".concat(i.typeName," from JSON: ").concat(ln(e)));n=n??new i;let r=new Map,s=t.typeRegistry;for(let a of Object.entries(e)){var o=pe(a,2);let d=o[0],l=o[1],f=i.fields.findJsonName(d);if(f){if(f.oneof){if(l===null&&f.kind=="scalar")continue;let p=r.get(f.oneof);if(p!==void 0)throw new Error("cannot decode message ".concat(i.typeName,' from JSON: multiple keys for oneof "').concat(f.oneof.name,'" present: "').concat(p,'", "').concat(d,'"'));r.set(f.oneof,d)}ag(n,l,f,t,i)}else{let p=!1;if(s?.findExtension&&d.startsWith("[")&&d.endsWith("]")){let g=s.findExtension(d.substring(1,d.length-1));if(g&&g.extendee.typeName==i.typeName){p=!0;let b=wv(g),R=pe(b,2),w=R[0],I=R[1];ag(w,l,g.field,t,g),D0(n,g,I(),t)}}if(!p&&!t.ignoreUnknownFields)throw new Error("cannot decode message ".concat(i.typeName,' from JSON: key "').concat(d,'" is unknown'))}}return n},writeMessage(i,e){let t=i.getType(),n={},r;try{for(r of t.fields.byNumber()){if(!Mv(r,i)){if(r.req)throw"required field not set";if(!e.emitDefaultValues||!U0(r))continue}let o=r.oneof?i[r.oneof.localName].value:i[r.localName],a=cg(r,o,e);a!==void 0&&(n[e.useProtoFieldName?r.name:r.jsonName]=a)}let s=e.typeRegistry;if(s?.findExtensionFor)for(let o of t.runtime.bin.listUnknownFields(i)){let a=s.findExtensionFor(t.typeName,o.no);if(a&&Pv(i,a)){let d=O0(i,a,e),l=cg(a.field,d,e);l!==void 0&&(n[a.field.jsonName]=l)}}}catch(s){let o=r?"cannot encode field ".concat(t.typeName,".").concat(r.name," to JSON"):"cannot encode message ".concat(t.typeName," to JSON"),a=s instanceof Error?s.message:String(s);throw new Error(o+(a.length>0?": ".concat(a):""))}return n}
39,readScalar(i,e,t){return as(i,e,t??ni.BIGINT,!0)},writeScalar(i,e,t){if(e!==void 0&&(t||Cv(i,e)))return Ro(i,e)},debug:ln}}function ln(i){if(i===null)return"null";switch(typeof i){case"object":return Array.isArray(i)?"array":"object";case"string":return i.length>100?"string":'"'.concat(i.split('"').join('\\"'),'"');default:return String(i)}}function ag(i,e,t,n,r){let s=t.localName;if(t.repeated){if(Ke(t.kind!="map"),e===null)return;if(!Array.isArray(e))throw new Error("cannot decode field ".concat(r.typeName,".").concat(t.name," from JSON: ").concat(ln(e)));let a=i[s];for(let d of e){if(d===null)throw new Error("cannot decode field ".concat(r.typeName,".").concat(t.name," from JSON: ").concat(ln(d)));switch(t.kind){case"message":a.push(t.T.fromJson(d,n));break;case"enum":let l=fl(t.T,d,n.ignoreUnknownFields,!0);l!==Mo&&a.push(l);break;case"scalar":try{a.push(as(t.T,d,t.L,!0))}catch(f){let p="cannot decode field ".concat(r.typeName,".").concat(t.name," from JSON: ").concat(ln(d));throw f instanceof Error&&f.message.length>0&&(p+=": ".concat(f.message)),new Error(p)}break}}}else if(t.kind=="map"){if(e===null)return;if(typeof e!="object"||Array.isArray(e))throw new Error("cannot decode field ".concat(r.typeName,".").concat(t.name," from JSON: ").concat(ln(e)));let a=i[s];for(let d of Object.entries(e)){var o=pe(d,2);let l=o[0],f=o[1];if(f===null)throw new Error("cannot decode field ".concat(r.typeName,".").concat(t.name," from JSON: map value null"));let p;try{p=F0(t.K,l)}catch(g){let b="cannot decode map key for field ".concat(r.typeName,".").concat(t.name," from JSON: ").concat(ln(e));throw g instanceof Error&&g.message.length>0&&(b+=": ".concat(g.message)),new Error(b)}switch(t.V.kind){case"message":a[p]=t.V.T.fromJson(f,n);break;case"enum":let g=fl(t.V.T,f,n.ignoreUnknownFields,!0);g!==Mo&&(a[p]=g);break;case"scalar":try{a[p]=as(t.V.T,f,ni.BIGINT,!0)}catch(b){let R="cannot decode map value for field ".concat(r.typeName,".").concat(t.name," from JSON: ").concat(ln(e));throw b instanceof Error&&b.message.length>0&&(R+=": ".concat(b.message)),new Error(R)}break}}}else switch(t.oneof&&(i=i[t.oneof.localName]={case:s},s="value"),t.kind){case"message":let a=t.T;if(e===null&&a.typeName!="google.protobuf.Value")return;let d=i[s];Dn(d)?d.fromJson(e,n):(i[s]=d=a.fromJson(e,n),a.fieldWrapper&&!t.oneof&&(i[s]=a.fieldWrapper.unwrapField(d)));break;case"enum":let l=fl(t.T,e,n.ignoreUnknownFields,!1);switch(l){case Bo:rg(t,i);break;case Mo:break;default:i[s]=l;break}break;case"scalar":try{let f=as(t.T,e,t.L,!1);f===Bo?rg(t,i):i[s]=f}catch(f){let p="cannot decode field ".concat(r.typeName,".").concat(t.name," from JSON: ").concat(ln(e));throw f instanceof Error&&f.message.length>0&&(p+=": ".concat(f.message)),new Error(p)}break}}function F0(i,e){if(i===Y.BOOL)switch(e){case"true":e=!0;break;case"false":e=!1;break}return as(i,e,ni.BIGINT,!0).toString()}function as(i,e,t,n){if(e===null)return n?wr(i,t):Bo;switch(i){case Y.DOUBLE:case Y.FLOAT:if(e==="NaN")return Number.NaN;if(e==="Infinity")return Number.POSITIVE_INFINITY;if(e==="-Infinity")return Number.NEGATIVE_INFINITY;if(e===""||typeof e=="string"&&e.trim().length!==e.length||typeof e!="string"&&typeof e!="number")break;let r=Number(e);if(Number.isNaN(r)||!Number.isFinite(r))break;return i==Y.FLOAT&&vv(r),r;case Y.INT32:case Y.FIXED32:case Y.SFIXED32:case Y.SINT32:case Y.UINT32:let s;if(typeof e=="number"?s=e:typeof e=="string"&&e.length>0&&e.trim().length===e.length&&(s=Number(e)),s===void 0)break;return i==Y.UINT32||i==Y.FIXED32?jl(s):Po(s),s;case Y.INT64:case Y.SFIXED64:case Y.SINT64:if(typeof e!="number"&&typeof e!="string")break;let o=Ge.parse(e);return t?o.toString():o;case Y.FIXED64:case Y.UINT64:if(typeof e!="number"&&typeof e!="string")break;let a=Ge.uParse(e);return t?a.toString():a;case Y.BOOL:if(typeof e!="boolean")break;return e;case Y.STRING:if(typeof e!="string")break;try{encodeURIComponent(e)}catch{throw new Error("invalid UTF8")}return e;case Y.BYTES:if(e==="")return new Uint8Array(0);if(typeof e!="string")break;return Ev.dec(e)}throw new Error}function fl(i,e,t,n){if(e===null)return i.typeName=="google.protobuf.NullValue"?0:n?i.values[0].no:Bo;switch(typeof e){case"number":if(Number.isInteger(e))return e;break;case"string":let r=i.findName(e);
39if(r!==void 0)return r.no;if(t)return Mo;break}throw new Error("cannot decode enum ".concat(i.typeName," from JSON: ").concat(ln(e)))}function U0(i){return i.repeated||i.kind=="map"?!0:!(i.oneof||i.kind=="message"||i.opt||i.req)}function cg(i,e,t){if(i.kind=="map"){Ke(typeof e=="object"&&e!=null);let o={},a=Object.entries(e);switch(i.V.kind){case"scalar":for(let l of a){var n=pe(l,2);let f=n[0],p=n[1];o[f.toString()]=Ro(i.V.T,p)}break;case"message":for(let l of a){var r=pe(l,2);let f=r[0],p=r[1];o[f.toString()]=p.toJson(t)}break;case"enum":let d=i.V.T;for(let l of a){var s=pe(l,2);let f=s[0],p=s[1];o[f.toString()]=ml(d,p,t.enumAsInteger)}break}return t.emitDefaultValues||a.length>0?o:void 0}if(i.repeated){Ke(Array.isArray(e));let o=[];switch(i.kind){case"scalar":for(let a=0;a<e.length;a++)o.push(Ro(i.T,e[a]));break;case"enum":for(let a=0;a<e.length;a++)o.push(ml(i.T,e[a],t.enumAsInteger));break;case"message":for(let a=0;a<e.length;a++)o.push(e[a].toJson(t));break}return t.emitDefaultValues||o.length>0?o:void 0}switch(i.kind){case"scalar":return Ro(i.T,e);case"enum":return ml(i.T,e,t.enumAsInteger);case"message":return Rv(i.T,e).toJson(t)}}function ml(i,e,t){var n;if(Ke(typeof e=="number"),i.typeName=="google.protobuf.NullValue")return null;if(t)return e;let r=i.findNumber(e);return(n=r?.name)!==null&&n!==void 0?n:e}function Ro(i,e){switch(i){case Y.INT32:case Y.SFIXED32:case Y.SINT32:case Y.FIXED32:case Y.UINT32:return Ke(typeof e=="number"),e;case Y.FLOAT:case Y.DOUBLE:return Ke(typeof e=="number"),Number.isNaN(e)?"NaN":e===Number.POSITIVE_INFINITY?"Infinity":e===Number.NEGATIVE_INFINITY?"-Infinity":e;case Y.STRING:return Ke(typeof e=="string"),e;case Y.BOOL:return Ke(typeof e=="boolean"),e;case Y.UINT64:case Y.FIXED64:case Y.INT64:case Y.SFIXED64:case Y.SINT64:return Ke(typeof e=="bigint"||typeof e=="string"||typeof e=="number"),e.toString();case Y.BYTES:return Ke(e instanceof Uint8Array),Ev.enc(e)}}var hr=Symbol("@bufbuild/protobuf/unknown-fields"),lg={readUnknownFields:!0,readerFactory:i=>new ql(i)},ug={writeUnknownFields:!0,writerFactory:()=>new Bl};function j0(i){return i?Object.assign(Object.assign({},lg),i):lg}function B0(i){return i?Object.assign(Object.assign({},ug),i):ug}function q0(){return{makeReadOptions:j0,makeWriteOptions:B0,listUnknownFields(i){var e;return(e=i[hr])!==null&&e!==void 0?e:[]},discardUnknownFields(i){delete i[hr]},writeUnknownFields(i,e){let n=i[hr];if(n)for(let r of n)e.tag(r.no,r.wireType).raw(r.data)},onUnknownField(i,e,t,n){let r=i;Array.isArray(r[hr])||(r[hr]=[]),r[hr].push({no:e,wireType:t,data:n})},readMessage(i,e,t,n,r){let s=i.getType(),o=r?e.len:e.pos+t,a,d;for(;e.pos<o;){var l=e.tag(),f=pe(l,2);if(a=f[0],d=f[1],r===!0&&d==Qe.EndGroup)break;let p=s.fields.find(a);if(!p){let g=e.skip(d,a);n.readUnknownFields&&this.onUnknownField(i,a,d,g);continue}dg(i,e,p,d,n)}if(r&&(d!=Qe.EndGroup||a!==t))throw new Error("invalid end group tag")},readField:dg,writeMessage(i,e,t){let n=i.getType();for(let r of n.fields.byNumber()){if(!Mv(r,i)){if(r.req)throw new Error("cannot encode field ".concat(n.typeName,".").concat(r.name," to binary: required field not set"));continue}let s=r.oneof?i[r.oneof.localName].value:i[r.localName];hg(r,s,e,t)}return t.writeUnknownFields&&this.writeUnknownFields(i,e),e},writeField(i,e,t,n){e!==void 0&&hg(i,e,t,n)}}}function dg(i,e,t,n,r){let s=t.repeated,o=t.localName;switch(t.oneof&&(i=i[t.oneof.localName],i.case!=o&&delete i.value,i.case=o,o="value"),t.kind){case"scalar":case"enum":let a=t.kind=="enum"?Y.INT32:t.T,d=qo;if(t.kind=="scalar"&&t.L>0&&(d=$0),s){let R=i[o];if(n==Qe.LengthDelimited&&a!=Y.STRING&&a!=Y.BYTES){let I=e.uint32()+e.pos;for(;e.pos<I;)R.push(d(e,a))}else R.push(d(e,a))}else i[o]=d(e,a);break;case"message":let l=t.T;s?i[o].push(Io(e,new l,r,t)):Dn(i[o])?Io(e,i[o],r,t):(i[o]=Io(e,new l,r,t),l.fieldWrapper&&!t.oneof&&!t.repeated&&(i[o]=l.fieldWrapper.unwrapField(i[o])));break;case"map":let f=V0(t,e,r),p=pe(f,2),g=p[0],b=p[1];i[o][g]=b;break}}function Io(i,e,t,n){let r=e.getType().runtime.bin,s=n?.delimited;return r.readMessage(e,i,s?n.no:i.uint32(),t,s),e}function V0(i,e,t){let n=e.uint32(),r=e.pos+n,s,o;for(;e.pos<r;){let a=e.tag();switch(pe(a,1)[0]){case 1:s=qo(e,i.K);break;case 2:switch(i.V.kind){case"scalar":o=qo(e,i.V.T);break;case"enum":o=e.int32();break;case"message":o=Io(e,new i.V.T,t,void 0);break}break}}
vendor: 4,611 bytes, line 39
39if(s===void 0&&(s=wr(i.K,ni.BIGINT)),typeof s!="string"&&typeof s!="number"&&(s=s.toString()),o===void 0)switch(i.V.kind){case"scalar":o=wr(i.V.T,ni.BIGINT);break;case"enum":o=i.V.T.values[0].no;break;case"message":o=new i.V.T;break}return[s,o]}function $0(i,e){let t=qo(i,e);return typeof t=="bigint"?t.toString():t}function qo(i,e){switch(e){case Y.STRING:return i.string();case Y.BOOL:return i.bool();case Y.DOUBLE:return i.double();case Y.FLOAT:return i.float();case Y.INT32:return i.int32();case Y.INT64:return i.int64();case Y.UINT64:return i.uint64();case Y.FIXED64:return i.fixed64();case Y.BYTES:return i.bytes();case Y.FIXED32:return i.fixed32();case Y.SFIXED32:return i.sfixed32();case Y.SFIXED64:return i.sfixed64();case Y.SINT64:return i.sint64();case Y.UINT32:return i.uint32();case Y.SINT32:return i.sint32()}}function hg(i,e,t,n){Ke(e!==void 0);let r=i.repeated;switch(i.kind){case"scalar":case"enum":let o=i.kind=="enum"?Y.INT32:i.T;if(r)if(Ke(Array.isArray(e)),i.packed)G0(t,o,i.no,e);else for(let a of e)cs(t,o,i.no,a);else cs(t,o,i.no,e);break;case"message":if(r){Ke(Array.isArray(e));for(let a of e)pg(t,n,i,a)}else pg(t,n,i,e);break;case"map":Ke(typeof e=="object"&&e!=null);for(let a of Object.entries(e)){var s=pe(a,2);let d=s[0],l=s[1];W0(t,n,i,d,l)}break}}function W0(i,e,t,n,r){i.tag(t.no,Qe.LengthDelimited),i.fork();let s=n;switch(t.K){case Y.INT32:case Y.FIXED32:case Y.UINT32:case Y.SFIXED32:case Y.SINT32:s=Number.parseInt(n);break;case Y.BOOL:Ke(n=="true"||n=="false"),s=n=="true";break}switch(cs(i,t.K,1,s),t.V.kind){case"scalar":cs(i,t.V.T,2,r);break;case"enum":cs(i,Y.INT32,2,r);break;case"message":Ke(r!==void 0),i.tag(2,Qe.LengthDelimited).bytes(r.toBinary(e));break}i.join()}function pg(i,e,t,n){let r=Rv(t.T,n);t.delimited?i.tag(t.no,Qe.StartGroup).raw(r.toBinary(e)).tag(t.no,Qe.EndGroup):i.tag(t.no,Qe.LengthDelimited).bytes(r.toBinary(e))}function cs(i,e,t,n){Ke(n!==void 0);let r=Iv(e),s=pe(r,2),o=s[0],a=s[1];i.tag(t,o)[a](n)}function G0(i,e,t,n){if(!n.length)return;i.tag(t,Qe.LengthDelimited).fork();let r=Iv(e),s=pe(r,2),o=s[1];for(let a=0;a<n.length;a++)i[o](n[a]);i.join()}function Iv(i){let e=Qe.Varint;switch(i){case Y.BYTES:case Y.STRING:e=Qe.LengthDelimited;break;case Y.DOUBLE:case Y.FIXED64:case Y.SFIXED64:e=Qe.Bit64;break;case Y.FIXED32:case Y.SFIXED32:case Y.FLOAT:e=Qe.Bit32;break}let t=Y[i].toLowerCase();return[e,t]}function J0(){return{setEnumType:bv,initPartial(i,e){if(i===void 0)return;let t=e.getType();for(let r of t.fields.byMember()){let s=r.localName,o=e,a=i;if(a[s]!=null)switch(r.kind){case"oneof":let d=a[s].case;if(d===void 0)continue;let l=r.findField(d),f=a[s].value;l&&l.kind=="message"&&!Dn(f,l.T)?f=new l.T(f):l&&l.kind==="scalar"&&l.T===Y.BYTES&&(f=es(f)),o[s]={case:d,value:f};break;case"scalar":case"enum":let p=a[s];r.T===Y.BYTES&&(p=r.repeated?p.map(es):es(p)),o[s]=p;break;case"map":switch(r.V.kind){case"scalar":case"enum":if(r.V.T===Y.BYTES)for(let R of Object.entries(a[s])){var n=pe(R,2);let w=n[0],I=n[1];o[s][w]=es(I)}else Object.assign(o[s],a[s]);break;case"message":let b=r.V.T;for(let R of Object.keys(a[s])){let w=a[s][R];b.fieldWrapper||(w=new b(w)),o[s][R]=w}break}break;case"message":let g=r.T;if(r.repeated)o[s]=a[s].map(b=>Dn(b,g)?b:new g(b));else{let b=a[s];g.fieldWrapper?g.typeName==="google.protobuf.BytesValue"?o[s]=es(b):o[s]=b:o[s]=Dn(b,g)?b:new g(b)}break}}},equals(i,e,t){return e===t?!0:!e||!t?!1:i.fields.byMember().every(n=>{let r=e[n.localName],s=t[n.localName];if(n.repeated){if(r.length!==s.length)return!1;switch(n.kind){case"message":return r.every((o,a)=>n.T.equals(o,s[a]));case"scalar":return r.every((o,a)=>Jn(n.T,o,s[a]));case"enum":return r.every((o,a)=>Jn(Y.INT32,o,s[a]))}throw new Error("repeated cannot contain ".concat(n.kind))}switch(n.kind){case"message":let o=r,a=s;return n.T.fieldWrapper&&(o!==void 0&&!Dn(o)&&(o=n.T.fieldWrapper.wrapField(o)),a!==void 0&&!Dn(a)&&(a=n.T.fieldWrapper.wrapField(a))),n.T.equals(o,a);case"enum":return Jn(Y.INT32,r,s);case"scalar":return Jn(n.T,r,s);case"oneof":if(r.case!==s.case)return!1;let d=n.findField(r.case);if(d===void 0)return!0;switch(d.kind){case"message":return d.T.equals(r.value,s.value);case"enum":return Jn(Y.INT32,r.value,s.value);case"scalar":return Jn(d.T,r.value,s.value)}throw new Error("oneof cannot contain ".concat(d.kind));case"map":let l=Object.keys(r).concat(Object.keys(s));switch(n.V.kind){case"message":let f=n.V.T;return l.every(g=>f.equals(r[g],s[g]));case"enum":return l.every(g=>Jn(Y.INT32,r[g],s[g]));case"scalar":let p=n.V.T;return l.every(g=>Jn(p,r[g],s[g]))}break}})},clone(i){let e=i.getType(),t=new e,n=t;
39for(let s of e.fields.byMember()){let o=i[s.localName],a;if(s.repeated)a=o.map(So);else if(s.kind=="map"){a=n[s.localName];for(let d of Object.entries(o)){var r=pe(d,2);let l=r[0],f=r[1];a[l]=So(f)}}else s.kind=="oneof"?a=s.findField(o.case)?{case:o.case,value:So(o.value)}:{case:void 0}:a=So(o);n[s.localName]=a}for(let s of e.runtime.bin.listUnknownFields(i))e.runtime.bin.onUnknownField(n,s.no,s.wireType,s.data);return t}}}function So(i){if(i===void 0)return i;if(Dn(i))return i.clone();if(i instanceof Uint8Array){let e=new Uint8Array(i.byteLength);return e.set(i),e}return i}function es(i){return i instanceof Uint8Array?i:new Uint8Array(i)}function H0(i,e,t){return{syntax:i,json:N0(),bin:q0(),util:Object.assign(Object.assign({},J0()),{newFieldList:e,initFields:t}),makeMessageType(n,r,s){return v0(this,n,r,s)},makeEnum:g0,makeEnumType:kv,getEnumType:m0,makeExtension(n,r,s){return M0(this,n,r,s)}}}var Vl=class{constructor(e,t){this._fields=e,this._normalizer=t}findJsonName(e){if(!this.jsonNames){let t={};for(let n of this.list())t[n.jsonName]=t[n.name]=n;this.jsonNames=t}return this.jsonNames[e]}find(e){if(!this.numbers){let t={};for(let n of this.list())t[n.no]=n;this.numbers=t}return this.numbers[e]}list(){return this.all||(this.all=this._normalizer(this._fields)),this.all}byNumber(){return this.numbersAsc||(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 Ov(i,e){let t=Dv(i);return e?t:Z0(X0(t))}function K0(i){return Ov(i,!1)}var z0=Dv;function Dv(i){let e=!1,t=[];for(let n=0;n<i.length;n++){let r=i.charAt(n);switch(r){case"_":e=!0;break;case"0":case"1":case"2":case"3":case"4":case"5":case"6":case"7":case"8":case"9":t.push(r),e=!1;break;default:e&&(e=!1,r=r.toUpperCase()),t.push(r);break}}return t.join("")}var Y0=new Set(["constructor","toString","toJSON","valueOf"]),Q0=new Set(["getType","clone","equals","fromBinary","fromJson","fromJsonString","toBinary","toJson","toJsonString","toObject"]),Lv=i=>"".concat(i,"$"),X0=i=>Q0.has(i)?Lv(i):i,Z0=i=>Y0.has(i)?Lv(i):i,$l=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=K0(e)}addField(e){Ke(e.oneof===this,"field ".concat(e.name," not one of ").concat(this.name)),this.fields.push(e)}findField(e){if(!this._lookup){this._lookup=Object.create(null);for(let t=0;t<this.fields.length;t++)this._lookup[this.fields[t].localName]=this.fields[t]}return this._lookup[e]}};function e_(i,e){var t,n,r,s,o,a;let d=[],l;for(let f of typeof i=="function"?i():i){let p=f;if(p.localName=Ov(f.name,f.oneof!==void 0),p.jsonName=(t=f.jsonName)!==null&&t!==void 0?t:z0(f.name),p.repeated=(n=f.repeated)!==null&&n!==void 0?n:!1,f.kind=="scalar"&&(p.L=(r=f.L)!==null&&r!==void 0?r:ni.BIGINT),p.delimited=(s=f.delimited)!==null&&s!==void 0?s:!1,p.req=(o=f.req)!==null&&o!==void 0?o:!1,p.opt=(a=f.opt)!==null&&a!==void 0?a:!1,f.packed===void 0&&(p.packed=f.kind=="enum"||f.kind=="scalar"&&f.T!=Y.BYTES&&f.T!=Y.STRING),f.oneof!==void 0){let g=typeof f.oneof=="string"?f.oneof:f.oneof.name;(!l||l.name!=g)&&(l=new $l(g)),p.oneof=l,l.addField(p)}d.push(p)}return d}var U=H0("proto3",i=>new Vl(i,e=>e_(e)),i=>{for(let e of i.getType().fields.byMember()){if(e.opt)continue;let t=e.localName,n=i;if(e.repeated){n[t]=[];continue}switch(e.kind){case"oneof":n[t]={case:void 0};break;case"enum":n[t]=0;break;case"map":n[t]={};break;case"scalar":n[t]=wr(e.T,e.L);break}}}),Nn=class i extends ms{constructor(e){super(),this.seconds=Ge.zero,this.nanos=0,U.util.initPartial(e,this)}fromJson(e,t){if(typeof e!="string")throw new Error("cannot decode google.protobuf.Timestamp from JSON: ".concat(U.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 new 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 new Error("cannot decode google.protobuf.Timestamp from JSON: invali
39d RFC 3339 string");if(r<Date.parse("0001-01-01T00:00:00Z")||r>Date.parse("9999-12-31T23:59:59Z"))throw new 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=Ge.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 new 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 new Error("cannot encode google.protobuf.Timestamp to JSON: nanos must not be negative");let n="Z";if(this.nanos>0){let r=(this.nanos+1e9).toString().substring(1);r.substring(3)==="000000"?n="."+r.substring(0,3)+"Z":r.substring(6)==="000"?n="."+r.substring(0,6)+"Z":n="."+r+"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 i.fromDate(new Date)}static fromDate(e){let t=e.getTime();return new i({seconds:Ge.parse(Math.floor(t/1e3)),nanos:t%1e3*1e6})}static fromBinary(e,t){return new i().fromBinary(e,t)}static fromJson(e,t){return new i().fromJson(e,t)}static fromJsonString(e,t){return new i().fromJsonString(e,t)}static equals(e,t){return U.util.equals(i,e,t)}};Nn.runtime=U;Nn.typeName="google.protobuf.Timestamp";Nn.fields=U.util.newFieldList(()=>[{no:1,name:"seconds",kind:"scalar",T:3},{no:2,name:"nanos",kind:"scalar",T:5}]);var t_=U.makeMessageType("livekit.MetricsBatch",()=>[{no:1,name:"timestamp_ms",kind:"scalar",T:3},{no:2,name:"normalized_timestamp",kind:"message",T:Nn},{no:3,name:"str_data",kind:"scalar",T:9,repeated:!0},{no:4,name:"time_series",kind:"message",T:n_,repeated:!0},{no:5,name:"events",kind:"message",T:r_,repeated:!0}]),n_=U.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:i_,repeated:!0},{no:5,name:"rid",kind:"scalar",T:13}]),i_=U.makeMessageType("livekit.MetricSample",()=>[{no:1,name:"timestamp_ms",kind:"scalar",T:3},{no:2,name:"normalized_timestamp",kind:"message",T:Nn},{no:3,name:"value",kind:"scalar",T:2}]),r_=U.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:Nn},{no:7,name:"normalized_end_timestamp",kind:"message",T:Nn,opt:!0},{no:8,name:"metadata",kind:"scalar",T:9},{no:9,name:"rid",kind:"scalar",T:13}]);var xv=U.makeEnum("livekit.BackupCodecPolicy",[{no:0,name:"PREFER_REGRESSION"},{no:1,name:"SIMULCAST"},{no:2,name:"REGRESSION"}]),Kt=U.makeEnum("livekit.TrackType",[{no:0,name:"AUDIO"},{no:1,name:"VIDEO"},{no:2,name:"DATA"}]),et=U.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"}]),gd=U.makeEnum("livekit.VideoQuality",[{no:0,name:"LOW"},{no:1,name:"MEDIUM"},{no:2,name:"HIGH"},{no:3,name:"OFF"}]),pr=U.makeEnum("livekit.ConnectionQuality",[{no:0,name:"POOR"},{no:1,name:"GOOD"},{no:2,name:"EXCELLENT"},{no:3,name:"LOST"}]),gs=U.makeEnum("livekit.ClientConfigSetting",[{no:0,name:"UNSET"},{no:1,name:"DISABLED"},{no:2,name:"ENABLED"}]),Qt=U.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"},{no:16,name:"AGENT_ERROR"}]),Mn=U.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"}]),s_=U.makeEnum("livekit.SubscriptionError",[{no:0,name:"SE_UNKNOWN"},{no:1,name:"SE_CODEC_UNSUPPORTED"},{no:2,name:"SE_TRACK_NOTFOUND"}]),ot=U.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"}]),Er=U.makeEnum("livekit.PacketTrailerFeature",[{no:0,name:"PTF_USER_TIMESTAMP"},{no:1,name:"PTF_FRAME_ID"},{no:2,name:"PTF_USER_DATA"}]),Ca=U.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:Vo,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:Yv}]),Vo=U.makeMessageType("livekit.Codec",()=>[{no:1,name:"mime",kind:"scalar",T:9},{no:2,name:"fmtp_line",kind:"scalar",T:9}]),o_=U.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:U.getEnumType(et),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},{no:13,name:"can_manage_agent_session",kind:"scalar",T:8}]),Ii=U.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:U.getEnumType(gr)},{no:4,name:"tracks",kind:"message",T:fr,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:o_},{no:12,name:"region",kind:"scalar",T:9},{no:13,name:"is_publisher",kind:"scalar",T:8},{no:14,name:"kind",kind:"enum",T:U.getEnumType(vs)},{no:15,name:"attributes",kind:"map",K:9,V:{kind:"scalar",T:9}},{no:16,name:"disconnect_reason",kind:"enum",T:U.getEnumType(Qt)},{no:18,name:"kind_details",kind:"enum",T:U.getEnumType(a_),repeated:!0},{no:19,name:"data_tracks",kind:"message",T:wa,repeated:!0},{no:20,name:"client_protocol",kind:"scalar",T:5},{no:21,name:"capabilities",kind:"enum",T:U.getEnumType(ys),repeated:!0}]),gr=U.makeEnum("livekit.ParticipantInfo.State",[{no:0,name:"JOINING"},{no:1,name:"JOINED"},{no:2,name:"ACTIVE"},{no:3,name:"DISCONNECTED"}]),vs=U.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"}]),a_=U.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"},{no:5,name:"SIMULATION"}]),Ie=U.makeEnum("livekit.Encryption.Type",[{no:0,name:"NONE"},{no:1,name:"GCM"},{no:2,name:"CUSTOM"}]),c_=U.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:Qn,repeated:!0},{no:5,name:"video_layer_mode",kind:"enum",T:U.getEnumType(Uv)},{no:6,name:"sdp_cid",kind:"scalar",T:9}]),fr=U.makeMessageType("livekit.TrackInfo",()=>[{no:1,name:"sid",kind:"scalar",T:9},{no:2,name:"type",kind:"enum",T:U.getEnumType(Kt)},{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:U.getEnumType(et)},{no:10,name:"layers",kind:"message",T:Qn,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:c_,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:U.getEnumType(Ie)},{no:17,name:"stream",kind:"scalar",T:9},{no:18,name:"version",kind:"message",T:Yv},{no:19,name:"audio_features",kind:"enum",T:U.getEnumType(ot),repeated:!0},{no:20,name:"backup_codec_policy",kind:"enum",T:U.getEnumType(xv)},{no:21,name:"packet_trailer_features",kind:"enum",T:U.getEnumType(Er),repeated:!0}]),wa=U.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:U.getEnumType(Ie)},{no:5,name:"frame_encoding",kind:"message",T:Nv,opt:!0},{no:6,name:"schema",kind:"message",T:vd,opt:!0}]),Nv=U.makeMessageType("livekit.DataTrackFrameEncoding",()=>[{no:1,name:"well_known",kind:"enum",T:U.getEnumType(l_),oneof:"value"},{no:2,name:"custom",kind:"scalar",T:9,oneof:"value"}]),l_=U.makeEnum("livekit.DataTrackFrameEncoding.WellKnownFrameEncoding",[{no:0,name:"WELL_KNOWN_FRAME_ENCODING_UNSPECIFIED",localName:"UNSPECIFIED"},{no:1,name:"WELL_KNOWN_FRAME_ENCODING_ROS1",localName:"ROS1"},{no:2,name:"WELL_KNOWN_FRAME_ENCODING_CDR",localName:"CDR"},{no:3,name:"WELL_KNOWN_FRAME_ENCODING_PROTOBUF",localName:"PROTOBUF"},{no:4,name:"WELL_KNOWN_FRAME_ENCODING_FLATBUFFER",localName:"FLATBUFFER"},{no:5,name:"WELL_KNOWN_FRAME_ENCODING_CBOR",localName:"CBOR"},{no:6,name:"WELL_KNOWN_FRAME_ENCODING_MSGPACK",localName:"MSGPACK"},{no:7,name:"WELL_KNOWN_FRAME_ENCODING_JSON",localName:"JSON"}]),u_=U.makeMessageType("livekit.DataTrackSchemaEncoding",()=>[{no:1,name:"well_known",kind:"enum",T:U.getEnumType(d_),oneof:"value"},{no:2,name:"custom",kind:"scalar",T:9,oneof:"value"}]),d_=U.makeEnum("livekit.DataTrackSchemaEncoding.WellKnownSchemaEncoding",[{no:0,name:"WELL_KNOWN_SCHEMA_ENCODING_UNSPECIFIED",localName:"UNSPECIFIED"},{no:1,name:"WELL_KNOWN_SCHEMA_ENCODING_PROTOBUF",localName:"PROTOBUF"},{no:2,name:"WELL_KNOWN_SCHEMA_ENCODING_FLATBUFFER",localName:"FLATBUFFER"},{no:3,name:"WELL_KNOWN_SCHEMA_ENCODING_ROS1_MSG",localName:"ROS1_MSG"},{no:4,name:"WELL_KNOWN_SCHEMA_ENCODING_ROS2_MSG",localName:"ROS2_MSG"},{no:5,name:"WELL_KNOWN_SCHEMA_ENCODING_ROS2_IDL",localName:"ROS2_IDL"},{no:6,name:"WELL_KNOWN_SCHEMA_ENCODING_OMG_IDL",localName:"OMG_IDL"},{no:7,name:"WELL_KNOWN_SCHEMA_ENCODING_JSON_SCHEMA",localName:"JSON_SCHEMA"}]),vd=U.makeMessageType("livekit.DataTrackSchemaId",()=>[{no:1,name:"name",kind:"scalar",T:9},{no:2,name:"encoding",kind:"message",T:u_}]),h_=U.makeMessageType("livekit.DataTrackSubscriptionOptions",()=>[{no:1,name:"target_fps",kind:"scalar",T:13,opt:!0}]),yd=U.makeMessageType("livekit.DataBlobKey",()=>[{no:1,name:"generic",kind:"scalar",T:9,oneof:"key"},{no:2,name:"schema_id",kind:"message",T:vd,oneof:"key"}]),Fv=U.makeMessageType("livekit.DataBlob",()=>[{no:1,name:"key",kind:"message",T:yd},{no:2,name:"contents",kind:"scalar",T:12}]),Qn=U.makeMessageType("livekit.VideoLayer",()=>[{no:1,name:"quality",kind:"enum",T:U.getEnumType(gd)},{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}]),Uv=U.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"}]),yt=U.makeMessageType("livekit.DataPacket",()=>[{no:1,name:"kind",kind:"enum",T:U.getEnumType(Xn)},{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:bd,oneof:"value"},{no:3,name:"speaker",kind:"message",T:p_,oneof:"value"},{no:6,name:"sip_dtmf",kind:"message",T:Vv,oneof:"value"},{no:7,name:"transcription",kind:"message",T:f_,oneof:"value"},{no:8,name:"metrics",kind:"message",T:t_,oneof:"value"},{no:9,name:"chat_message",kind:"message",T:$o,oneof:"value"},{no:10,name:"rpc_request",kind:"message",T:kd,oneof:"value"},{no:11,name:"rpc_ack",kind:"message",T:Ea,oneof:"value"},{no:12,name:"rpc_response",kind:"message",T:Sd,oneof:"value"},{no:13,name:"stream_header",kind:"message",T:Pa,oneof:"value"},{no:14,name:"stream_chunk",kind:"message",T:Ln,oneof:"value"},{no:15,name:"stream_trailer",kind:"message",T:Td,oneof:"value"},{no:18,name:"encrypted_packet",kind:"message",T:jv,oneof:"value"},{no:16,name:"sequence",kind:"scalar",T:13},{no:17,name:"participant_sid",kind:"scalar",T:9}]),Xn=U.makeEnum("livekit.DataPacket.Kind",[{no:0,name:"RELIABLE"},{no:1,name:"LOSSY"}]),jv=U.makeMessageType("livekit.EncryptedPacket",()=>[{no:1,name:"encryption_type",kind:"enum",T:U.getEnumType(Ie)},{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}]),Bv=U.makeMessageType("livekit.EncryptedPacketPayload",()=>[{no:1,name:"user",kind:"message",T:bd,oneof:"value"},{no:3,name:"chat_message",kind:"message",T:$o,oneof:"value"},{no:4,name:"rpc_request",kind:"message",T:kd,oneof:"value"},{no:5,name:"rpc_ack",kind:"message",T:Ea,oneof:"value"},{no:6,name:"rpc_response",kind:"message",T:Sd,oneof:"value"},{no:7,name:"stream_header",kind:"message",T:Pa,oneof:"value"},{no:8,name:"stream_chunk",kind:"message",T:Ln,oneof:"value"},{no:9,name:"stream_trailer",kind:"message",T:Td,oneof:"value"}]),p_=U.makeMessageType("livekit.ActiveSpeakerUpdate",()=>[{no:1,name:"speakers",kind:"message",T:qv,repeated:!0}]),qv=U.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}]),bd=U.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}]),Vv=U.makeMessageType("livekit.SipDTMF",()=>[{no:3,name:"code",kind:"scalar",T:13},{no:4,name:"digit",kind:"scalar",T:9}]),f_=U.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:m_,repeated:!0}]),m_=U.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}]),$o=U.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}
vendor: 16,384 bytes, line 39
39]),kd=U.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},{no:6,name:"compressed_payload",kind:"scalar",T:12}]),Ea=U.makeMessageType("livekit.RpcAck",()=>[{no:1,name:"request_id",kind:"scalar",T:9}]),Sd=U.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:$v,oneof:"value"},{no:4,name:"compressed_payload",kind:"scalar",T:12,oneof:"value"}]),$v=U.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}]),Wv=U.makeMessageType("livekit.ParticipantTracks",()=>[{no:1,name:"participant_sid",kind:"scalar",T:9},{no:2,name:"track_sids",kind:"scalar",T:9,repeated:!0}]),Gv=U.makeMessageType("livekit.ServerInfo",()=>[{no:1,name:"edition",kind:"enum",T:U.getEnumType(Jv)},{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}]),Jv=U.makeEnum("livekit.ServerInfo.Edition",[{no:0,name:"Standard"},{no:1,name:"Cloud"}]),Hv=U.makeMessageType("livekit.ClientInfo",()=>[{no:1,name:"sdk",kind:"enum",T:U.getEnumType(Kv)},{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},{no:12,name:"client_protocol",kind:"scalar",T:5},{no:13,name:"capabilities",kind:"enum",T:U.getEnumType(ys),repeated:!0}]),Kv=U.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"}]),ys=U.makeEnum("livekit.ClientInfo.Capability",[{no:0,name:"CAP_UNUSED"},{no:1,name:"CAP_PACKET_TRAILER"},{no:2,name:"CAP_COMPRESSION_DEFLATE_RAW"}]),zv=U.makeMessageType("livekit.ClientConfiguration",()=>[{no:1,name:"video",kind:"message",T:fg},{no:2,name:"screen",kind:"message",T:fg},{no:3,name:"resume_connection",kind:"enum",T:U.getEnumType(gs)},{no:4,name:"disabled_codecs",kind:"message",T:g_},{no:5,name:"force_relay",kind:"enum",T:U.getEnumType(gs)}]),fg=U.makeMessageType("livekit.VideoConfiguration",()=>[{no:1,name:"hardware_encoder",kind:"enum",T:U.getEnumType(gs)}]),g_=U.makeMessageType("livekit.DisabledCodecs",()=>[{no:1,name:"codecs",kind:"message",T:Vo,repeated:!0},{no:2,name:"publish",kind:"message",T:Vo,repeated:!0}]),Yv=U.makeMessageType("livekit.TimedVersion",()=>[{no:1,name:"unix_micro",kind:"scalar",T:3},{no:2,name:"ticks",kind:"scalar",T:5}]),Wl=U.makeEnum("livekit.DataStream.OperationType",[{no:0,name:"CREATE"},{no:1,name:"UPDATE"},{no:2,name:"DELETE"},{no:3,name:"REACTION"}]),pt=U.makeEnum("livekit.DataStream.CompressionType",[{no:0,name:"NONE"},{no:1,name:"DEFLATE_RAW"}]),Qv=U.makeMessageType("livekit.DataStream.TextHeader",()=>[{no:1,name:"operation_type",kind:"enum",T:U.getEnumType(Wl)},{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"}),Xv=U.makeMessageType("livekit.DataStream.ByteHeader",()=>[{no:1,name:"name",kind:"scalar",T:9}],{localName:"DataStream_ByteHeader"}),Pa=U.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:U.getEnumType(Ie)},{no:8,name:"attributes",kind:"map",K:9,V:{kind:"scalar",T:9}},{no:9,name:"text_header",kind:"message",T:Qv,oneof:"content_header"},{no:10,name:"byte_header",kind:"message",T:Xv,oneof:"content_header"},{no:11,name:"inline_content",kind:"scalar",T:12,opt:!0},{no:12,name:"compression",kind:"enum",T:U.getEnumType(pt)}],{localName:"DataStream_Header"}),Ln=U.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"}),Td=U.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"});var v_=U.makeMessageType("livekit.SubscribedAudioCodec",()=>[{no:1,name:"codec",kind:"scalar",T:9},{no:2,name:"enabled",kind:"scalar",T:8}]);var zt=U.makeEnum("livekit.SignalTarget",[{no:0,name:"PUBLISHER"},{no:1,name:"SUBSCRIBER"}]),Gl=U.makeEnum("livekit.StreamState",[{no:0,name:"ACTIVE"},{no:1,name:"PAUSED"}]),y_=U.makeEnum("livekit.CandidateProtocol",[{no:0,name:"UDP"},{no:1,name:"TCP"},{no:2,name:"TLS"}]),b_=U.makeMessageType("livekit.SignalRequest",()=>[{no:1,name:"offer",kind:"message",T:ii,oneof:"message"},{no:2,name:"answer",kind:"message",T:ii,oneof:"message"},{no:3,name:"trickle",kind:"message",T:Aa,oneof:"message"},{no:4,name:"add_track",kind:"message",T:bs,oneof:"message"},{no:5,name:"mute",kind:"message",T:Ma,oneof:"message"},{no:6,name:"subscription",kind:"message",T:Ra,oneof:"message"},{no:7,name:"track_setting",kind:"message",T:ty,oneof:"message"},{no:8,name:"leave",kind:"message",T:Ia,oneof:"message"},{no:10,name:"update_layers",kind:"message",T:iy,oneof:"message"},{no:11,name:"subscription_permission",kind:"message",T:oy,oneof:"message"},{no:12,name:"sync_state",kind:"message",T:Rd,oneof:"message"},{no:13,name:"simulate",kind:"message",T:cn,oneof:"message"},{no:14,name:"ping",kind:"scalar",T:3,oneof:"message"},{no:15,name:"update_metadata",kind:"message",T:Ad,oneof:"message"},{no:16,name:"ping_req",kind:"message",T:ly,oneof:"message"},{no:17,name:"update_audio_track",kind:"message",T:Pd,oneof:"message"},{no:18,name:"update_video_track",kind:"message",T:ny,oneof:"message"},{no:19,name:"publish_data_track_request",kind:"message",T:_d,oneof:"message"},{no:20,name:"unpublish_data_track_request",kind:"message",T:wd,oneof:"message"},{no:21,name:"update_data_subscription",kind:"message",T:Zv,oneof:"message"},{no:22,name:"store_data_blob_request",kind:"message",T:P_,oneof:"message"},{no:23,name:"get_data_blob_request",kind:"message",T:M_,oneof:"message"}]),mg=U.makeMessageType("livekit.SignalResponse",()=>[{no:1,name:"join",kind:"message",T:__,oneof:"message"},{no:2,name:"answer",kind:"message",T:ii,oneof:"message"},{no:3,name:"offer",kind:"message",T:ii,oneof:"message"},{no:4,name:"trickle",kind:"message",T:Aa,oneof:"message"},{no:5,name:"update",kind:"message",T:E_,oneof:"message"},{no:6,name:"track_published",kind:"message",T:Ed,oneof:"message"},{no:8,name:"leave",kind:"message",T:Ia,oneof:"message"},{no:9,name:"mute",kind:"message",T:Ma,oneof:"message"},{no:10,name:"speakers_changed",kind:"message",T:I_,oneof:"message"},{no:11,name:"room_update",kind:"message",T:O_,oneof:"message"},{no:12,name:"connection_quality",kind:"message",T:L_,oneof:"message"},{no:13,name:"stream_state_update",kind:"message",T:N_,oneof:"message"},{no:14,name:"subscribed_quality_update",kind:"message",T:U_,oneof:"message"},{no:15,name:"subscription_permission_update",kind:"message",T:B_,oneof:"message"},{no:16,name:"refresh_token",kind:"scalar",T:9,oneof:"message"},{no:17,name:"track_unpublished",kind:"message",T:w_,oneof:"message"},{no:18,name:"pong",kind:"scalar",T:3,oneof:"message"},{no:19,name:"reconnect",kind:"message",T:C_,oneof:"message"},{no:20,name:"pong_resp",kind:"message",T:V_,oneof:"message"},{no:21,name:"subscription_response",kind:"message",T:G_,oneof:"message"},{no:22,name:"request_response",kind:"message",T:J_,oneof:"message"},{no:23,name:"track_subscribed",kind:"message",T:H_,oneof:"message"},{no:24,name:"room_moved",kind:"message",T:q_,oneof:"message"},{no:25,name:"media_sections_requirement",kind:"message",T:Y_,oneof:"message"},{no:26,name:"subscribed_audio_codec_update",kind:"message",T:j_,oneof:"message"},{no:27,name:"publish_data_track_response",kind:"message",T:Cd,oneof:"message"},{no:28,name:"unpublish_data_track_response",kind:"message",T:k_,oneof:"message"},{no:29,name:"data_track_subscriber_handles",kind:"message",T:S_,oneof:"message"},{no:30,name:"store_data_blob_response",kind:"message",T:A_,oneof:"message"},{no:31,name:"get_data_blob_response",kind:"message",T:R_,oneof:"message"}]),Jl=U.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:Qn,repeated:!0},{no:5,name:"video_layer_mode",kind:"enum",T:U.getEnumType(Uv)}]),bs=U.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:U.getEnumType(Kt)},{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:U.getEnumType(et)},{no:9,name:"layers",kind:"message",T:Qn,repeated:!0},{no:10,name:"simulcast_codecs",kind:"message",T:Jl,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:U.getEnumType(Ie)},{no:15,name:"stream",kind:"scalar",T:9},{no:16,name:"backup_codec_policy",kind:"enum",T:U.getEnumType(xv)},{no:17,name:"audio_features",kind:"enum",T:U.getEnumType(ot),repeated:!0},{no:18,name:"packet_trailer_features",kind:"enum",T:U.getEnumType(Er),repeated:!0}]),_d=U.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:U.getEnumType(Ie)},{no:4,name:"frame_encoding",kind:"message",T:Nv,opt:!0},{no:5,name:"schema",kind:"message",T:vd,opt:!0}]),Cd=U.makeMessageType("livekit.PublishDataTrackResponse",()=>[{no:1,name:"info",kind:"message",T:wa}]),wd=U.makeMessageType("livekit.UnpublishDataTrackRequest",()=>[{no:1,name:"pub_handle",kind:"scalar",T:13}]),k_=U.makeMessageType("livekit.UnpublishDataTrackResponse",()=>[{no:1,name:"info",kind:"message",T:wa}]),S_=U.makeMessageType("livekit.DataTrackSubscriberHandles",()=>[{no:1,name:"sub_handles",kind:"map",K:13,V:{kind:"message",T:T_}}]),T_=U.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"}),Aa=U.makeMessageType("livekit.TrickleRequest",()=>[{no:1,name:"candidateInit",kind:"scalar",T:9},{no:2,name:"target",kind:"enum",T:U.getEnumType(zt)},{no:3,name:"final",kind:"scalar",T:8}]),Ma=U.makeMessageType("livekit.MuteTrackRequest",()=>[{no:1,name:"sid",kind:"scalar",T:9},{no:2,name:"muted",kind:"scalar",T:8}]),__=U.makeMessageType("livekit.JoinResponse",()=>[{no:1,name:"room",kind:"message",T:Ca},{no:2,name:"participant",kind:"message",T:Ii},{no:3,name:"other_participants",kind:"message",T:Ii,repeated:!0},{no:4,name:"server_version",kind:"scalar",T:9},{no:5,name:"ice_servers",kind:"message",T:ry,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:zv},{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:Gv},{no:13,name:"sif_trailer",kind:"scalar",T:12},{no:14,name:"enabled_publish_codecs",kind:"message",T:Vo,repeated:!0},{no:15,name:"fast_publish",kind:"scalar",T:8}]),C_=U.makeMessageType("livekit.ReconnectResponse",()=>[{no:1,name:"ice_servers",kind:"message",T:ry,repeated:!0},{no:2,name:"client_configuration",kind:"message",T:zv},{no:3,name:"server_info",kind:"message",T:Gv},{no:4,name:"last_message_seq",kind:"scalar",T:13}]),Ed=U.makeMessageType("livekit.TrackPublishedResponse",()=>[{no:1,name:"cid",kind:"scalar",T:9},{no:2,name:"track",kind:"message",T:fr}]),w_=U.makeMessageType("livekit.TrackUnpublishedResponse",()=>[{no:1,name:"track_sid",kind:"scalar",T:9}]),ii=U.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}}]),E_=U.makeMessageType("livekit.ParticipantUpdate",()=>[{no:1,name:"participants",kind:"message",T:Ii,repeated:!0}]),Ra=U.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:Wv,repeated:!0}]),Zv=U.makeMessageType("livekit.UpdateDataSubscription",()=>[{no:1,name:"updates",kind:"message",T:ey,repeated:!0}]),ey=U.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:h_}],{localName:"UpdateDataSubscription_Update"}),P_=U.makeMessageType("livekit.StoreDataBlobRequest",()=>[{no:1,name:"request_id",kind:"scalar",T:13},{no:2,name:"blob",kind:"message",T:Fv}]),A_=U.makeMessageType("livekit.StoreDataBlobResponse",()=>[{no:1,name:"request_id",kind:"scalar",T:13},{no:2,name:"key",kind:"message",T:yd}]),M_=U.makeMessageType("livekit.GetDataBlobRequest",()=>[{no:1,name:"request_id",kind:"scalar",T:13},{no:2,name:"participant_identity",kind:"scalar",T:9},{no:3,name:"key",kind:"message",T:yd}]),R_=U.makeMessageType("livekit.GetDataBlobResponse",()=>[{no:1,name:"request_id",kind:"scalar",T:13},{no:2,name:"blob",kind:"message",T:Fv}]),ty=U.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:U.getEnumType(gd)},{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}]),Pd=U.makeMessageType("livekit.UpdateLocalAudioTrack",()=>[{no:1,name:"track_sid",kind:"scalar",T:9},{no:2,name:"features",kind:"enum",T:U.getEnumType(ot),repeated:!0}]),ny=U.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}]),Ia=U.makeMessageType("livekit.LeaveRequest",()=>[{no:1,name:"can_reconnect",kind:"scalar",T:8},{no:2,name:"reason",kind:"enum",T:U.getEnumType(Qt)},{no:3,name:"action",kind:"enum",T:U.getEnumType(vr)},{no:4,name:"regions",kind:"message",T:$_}]),vr=U.makeEnum("livekit.LeaveRequest.Action",[{no:0,name:"DISCONNECT"},{no:1,name:"RESUME"},{no:2,name:"RECONNECT"}]),iy=U.makeMessageType("livekit.UpdateVideoLayers",()=>[{no:1,name:"track_sid",kind:"scalar",T:9},{no:2,name:"layers",kind:"message",T:Qn,repeated:!0}]),Ad=U.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}]),ry=U.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}]),I_=U.makeMessageType("livekit.SpeakersChanged",()=>[{no:1,name:"speakers",kind:"message",T:qv,repeated:!0}]),O_=U.makeMessag
vendor: 5,463 bytes, line 39
39eType("livekit.RoomUpdate",()=>[{no:1,name:"room",kind:"message",T:Ca}]),D_=U.makeMessageType("livekit.ConnectionQualityInfo",()=>[{no:1,name:"participant_sid",kind:"scalar",T:9},{no:2,name:"quality",kind:"enum",T:U.getEnumType(pr)},{no:3,name:"score",kind:"scalar",T:2}]),L_=U.makeMessageType("livekit.ConnectionQualityUpdate",()=>[{no:1,name:"updates",kind:"message",T:D_,repeated:!0}]),x_=U.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:U.getEnumType(Gl)}]),N_=U.makeMessageType("livekit.StreamStateUpdate",()=>[{no:1,name:"stream_states",kind:"message",T:x_,repeated:!0}]),Md=U.makeMessageType("livekit.SubscribedQuality",()=>[{no:1,name:"quality",kind:"enum",T:U.getEnumType(gd)},{no:2,name:"enabled",kind:"scalar",T:8}]),F_=U.makeMessageType("livekit.SubscribedCodec",()=>[{no:1,name:"codec",kind:"scalar",T:9},{no:2,name:"qualities",kind:"message",T:Md,repeated:!0}]),U_=U.makeMessageType("livekit.SubscribedQualityUpdate",()=>[{no:1,name:"track_sid",kind:"scalar",T:9},{no:2,name:"subscribed_qualities",kind:"message",T:Md,repeated:!0},{no:3,name:"subscribed_codecs",kind:"message",T:F_,repeated:!0}]),j_=U.makeMessageType("livekit.SubscribedAudioCodecUpdate",()=>[{no:1,name:"track_sid",kind:"scalar",T:9},{no:2,name:"subscribed_audio_codecs",kind:"message",T:v_,repeated:!0}]),sy=U.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}]),oy=U.makeMessageType("livekit.SubscriptionPermission",()=>[{no:1,name:"all_participants",kind:"scalar",T:8},{no:2,name:"track_permissions",kind:"message",T:sy,repeated:!0}]),B_=U.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}]),q_=U.makeMessageType("livekit.RoomMovedResponse",()=>[{no:1,name:"room",kind:"message",T:Ca},{no:2,name:"token",kind:"scalar",T:9},{no:3,name:"participant",kind:"message",T:Ii},{no:4,name:"other_participants",kind:"message",T:Ii,repeated:!0}]),Rd=U.makeMessageType("livekit.SyncState",()=>[{no:1,name:"answer",kind:"message",T:ii},{no:2,name:"subscription",kind:"message",T:Ra},{no:3,name:"publish_tracks",kind:"message",T:Ed,repeated:!0},{no:4,name:"data_channels",kind:"message",T:cy,repeated:!0},{no:5,name:"offer",kind:"message",T:ii},{no:6,name:"track_sids_disabled",kind:"scalar",T:9,repeated:!0},{no:7,name:"datachannel_receive_states",kind:"message",T:ay,repeated:!0},{no:8,name:"publish_data_tracks",kind:"message",T:Cd,repeated:!0}]),ay=U.makeMessageType("livekit.DataChannelReceiveState",()=>[{no:1,name:"publisher_sid",kind:"scalar",T:9},{no:2,name:"last_seq",kind:"scalar",T:13}]),cy=U.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:U.getEnumType(zt)}]),cn=U.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:U.getEnumType(y_),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"}]),ly=U.makeMessageType("livekit.Ping",()=>[{no:1,name:"timestamp",kind:"scalar",T:3},{no:2,name:"rtt",kind:"scalar",T:3}]),V_=U.makeMessageType("livekit.Pong",()=>[{no:1,name:"last_ping_timestamp",kind:"scalar",T:3},{no:2,name:"timestamp",kind:"scalar",T:3}]),$_=U.makeMessageType("livekit.RegionSettings",()=>[{no:1,name:"regions",kind:"message",T:W_,repeated:!0}]),W_=U.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}]),G_=U.makeMessageType("livekit.SubscriptionResponse",()=>[{no:1,name:"track_sid",kind:"scalar",T:9},{no:2,name:"err",kind:"enum",T:U.getEnumType(s_)}]),J_=U.makeMessageType("livekit.RequestResponse",()=>[{no:1,name:"request_id",kind:"scalar",T:13},{no:2,name:"reason",kind:"enum",T:U.getEnumType(Ti)},{no:3,name:"message",kind:"scalar",T:9},{no:4,name:"trickle",kind:"message",T:Aa,oneof:"request"},{no:5,name:"add_track",kind:"message",T:bs,oneof:"request"},{no:6,name:"mute",kind:"message",T:Ma,oneof:"request"},{no:7,name:"update_metadata",kind:"message",T:Ad,oneof:"request"},{no:8,name:"update_audio_track",kind:"message",T:Pd,oneof:"request"},{no:9,name:"update_video_track",kind:"message",T:ny,oneof:"request"},{no:10,name:"publish_data_track",kind:"message",T:_d,oneof:"request"},{no:11,name:"unpublish_data_track",kind:"message",T:wd,oneof:"request"}]),Ti=U.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"}
vendor: 5,932 bytes, line 39
39,{no:8,name:"INVALID_NAME"},{no:9,name:"DUPLICATE_HANDLE"},{no:10,name:"DUPLICATE_NAME"},{no:11,name:"INVALID_REQUEST"}]),H_=U.makeMessageType("livekit.TrackSubscribed",()=>[{no:1,name:"track_sid",kind:"scalar",T:9}]),uy=U.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}]),K_=U.makeMessageType("livekit.JoinRequest",()=>[{no:1,name:"client_info",kind:"message",T:Hv},{no:2,name:"connection_settings",kind:"message",T:uy},{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:bs,repeated:!0},{no:6,name:"publisher_offer",kind:"message",T:ii},{no:7,name:"reconnect",kind:"scalar",T:8},{no:8,name:"reconnect_reason",kind:"enum",T:U.getEnumType(Mn)},{no:9,name:"participant_sid",kind:"scalar",T:9},{no:10,name:"sync_state",kind:"message",T:Rd}]),z_=U.makeMessageType("livekit.WrappedJoinRequest",()=>[{no:1,name:"compression",kind:"enum",T:U.getEnumType(Hl)},{no:2,name:"join_request",kind:"scalar",T:12}]),Hl=U.makeEnum("livekit.WrappedJoinRequest.Compression",[{no:0,name:"NONE"},{no:1,name:"GZIP"}]),Y_=U.makeMessageType("livekit.MediaSectionsRequirement",()=>[{no:1,name:"num_audios",kind:"scalar",T:13},{no:2,name:"num_videos",kind:"scalar",T:13}]);function Q_(i){return i&&i.__esModule&&Object.prototype.hasOwnProperty.call(i,"default")?i.default:i}var Oo={exports:{}},X_=Oo.exports,gg;function Z_(){return gg||(gg=1,(function(i){(function(e,t){i.exports?i.exports=t():e.log=t()})(X_,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"],s={},o=null;function a(w,I){var N=w[I];if(typeof N.bind=="function")return N.bind(w);try{return Function.prototype.bind.call(N,w)}catch{return function(){return Function.prototype.apply.apply(N,[w,arguments])}}}function d(){console.log&&(console.log.apply?console.log.apply(console,arguments):Function.prototype.apply.apply(console.log,[console,arguments])),console.trace&&console.trace()}function l(w){return w==="debug"&&(w="log"),typeof console===t?!1:w==="trace"&&n?d:console[w]!==void 0?a(console,w):console.log!==void 0?a(console,"log"):e}function f(){for(var w=this.getLevel(),I=0;I<r.length;I++){var N=r[I];this[N]=I<w?e:this.methodFactory(N,w,this.name)}if(this.log=this.debug,typeof console===t&&w<this.levels.SILENT)return"No console available for logging"}function p(w){return function(){typeof console!==t&&(f.call(this),this[w].apply(this,arguments))}}function g(w,I,N){return l(w)||p.apply(this,arguments)}function b(w,I){var N=this,L,j,M,P="loglevel";typeof w=="string"?P+=":"+w:typeof w=="symbol"&&(P=void 0);function B(ae){var ge=(r[ae]||"silent").toUpperCase();if(!(typeof window===t||!P)){try{window.localStorage[P]=ge;return}catch{}try{window.document.cookie=encodeURIComponent(P)+"="+ge+";"}catch{}}}function q(){var ae;if(!(typeof window===t||!P)){try{ae=window.localStorage[P]}catch{}if(typeof ae===t)try{var ge=window.document.cookie,ke=encodeURIComponent(P),Oe=ge.indexOf(ke+"=");Oe!==-1&&(ae=/^([^;]+)/.exec(ge.slice(Oe+ke.length+1))[1])}catch{}return N.levels[ae]===void 0&&(ae=void 0),ae}}function K(){if(!(typeof window===t||!P)){try{window.localStorage.removeItem(P)}catch{}try{window.document.cookie=encodeURIComponent(P)+"=; expires=Thu, 01 Jan 1970 00:00:00 UTC"}catch{}}}function ie(ae){var ge=ae;if(typeof ge=="string"&&N.levels[ge.toUpperCase()]!==void 0&&(ge=N.levels[ge.toUpperCase()]),typeof ge=="number"&&ge>=0&&ge<=N.levels.SILENT)return ge;throw new TypeError("log.setLevel() called with invalid level: "+ae)}N.name=w,N.levels={TRACE:0,DEBUG:1,INFO:2,WARN:3,ERROR:4,SILENT:5},N.methodFactory=I||g,N.getLevel=function(){return M??j??L},N.setLevel=function(ae,ge){return M=ie(ae),ge!==!1&&B(M),f.call(N)},N.setDefaultLevel=function(ae){j=ie(ae),q()||N.setLevel(ae,!1)},N.resetLevel=function(){M=null,K(),f.call(N)},N.enableAll=function(ae){N.setLevel(N.levels.TRACE,ae)},N.disableAll=function(ae){N.setLevel(N.levels.SILENT,ae)},N.rebuild=function(){if(o!==N&&(L=ie(o.getLevel())),f.call(N),o===N)for(var ae in s)s[ae].rebuild()},L=ie(o?o.getLevel():"WARN");var te=q();te!=null&&(M=ie(te)),f.call(N)}o=new b,o.getLogger=function(I){if(typeof I!="symbol"&&typeof I!="string"||I==="")throw new TypeError("You must supply a name when creating a logger.");var N=s[I];return N||(N=s[I]=new b(I,o.methodFactory)),N};var R=typeof window!==t?window.log:void 0;return o.noConflict=function(){return typeof window!==t&&window.log===o&&(window.log=R),o},o.getLoggers=function(){return s},o.default=o,o})})(Oo)),Oo.exports}var Oa=Z_(),Kl;(function(i){i[i.trace=0]="trace",i[i.debug=1]="debug",i[i.info=2]="info",i[i.warn=3]="warn",i[i.error=4]="error",i[i.silent=5]="silent"})(Kl||(Kl={}));var Xe;(function(i){i.Default="livekit",i.Room="livekit-room",i.TokenSource="livekit-token-source",i.Participant="livekit-participant",i.Track="livekit-track",i.Publication="livekit-track-publication",i.Engine="livekit-engine",i.Signal="livekit-signal",i.PCManager="livekit-pc-manager",i.PCTransport="livekit-pc-transport",i.E2EE="lk-e2ee",i.DataTracks="livekit-data-tracks",i.Region="livekit-region",i.ICE="livekit-ice"})(Xe||(Xe={}));var ye=Oa.getLogger(Xe.Default),$P=Object.values(Xe).map(i=>Oa.getLogger(i));ye.setDefaultLevel(Kl.info);function ut(i,e){let t=Oa.getLogger(i);return t.setDefaultLevel(ye.getLevel()),e?eC(t,e):t}function eC(i,e){let t=r=>(s,o)=>{let a=e(),d=a||o?Object.assign(Object.assign({},a),o):void 0;i[r](s,d)},n=Object.create(i);return n.trace=t("trace"),n.debug=t("debug"),n.info=t("info"),n.warn=t("warn"),n.error=t("error"),n}
vendor: 9,812 bytes, line 39
39var tC=Oa.getLogger(Xe.E2EE),ts=7e3,nC=[0,300,4*300,9*300,16*300,ts,ts,ts,ts,ts],zl=class{constructor(e){this._retryDelays=e!==void 0?[...e]:nC}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 iC(i,e){var t={};for(var n in i)Object.prototype.hasOwnProperty.call(i,n)&&e.indexOf(n)<0&&(t[n]=i[n]);if(i!=null&&typeof Object.getOwnPropertySymbols=="function")for(var r=0,n=Object.getOwnPropertySymbols(i);r<n.length;r++)e.indexOf(n[r])<0&&Object.prototype.propertyIsEnumerable.call(i,n[r])&&(t[n[r]]=i[n[r]]);return t}function A(i,e,t,n){function r(s){return s instanceof t?s:new t(function(o){o(s)})}return new(t||(t=Promise))(function(s,o){function a(f){try{l(n.next(f))}catch(p){o(p)}}function d(f){try{l(n.throw(f))}catch(p){o(p)}}function l(f){f.done?s(f.value):r(f.value).then(a,d)}l((n=n.apply(i,e||[])).next())})}function vg(i){var e=typeof Symbol=="function"&&Symbol.iterator,t=e&&i[e],n=0;if(t)return t.call(i);if(i&&typeof i.length=="number")return{next:function(){return i&&n>=i.length&&(i=void 0),{value:i&&i[n++],done:!i}}};throw new TypeError(e?"Object is not iterable.":"Symbol.iterator is not defined.")}function xn(i){return this instanceof xn?(this.v=i,this):new xn(i)}function dy(i,e,t){if(!Symbol.asyncIterator)throw new TypeError("Symbol.asyncIterator is not defined.");var n=t.apply(i,e||[]),r,s=[];return r=Object.create((typeof AsyncIterator=="function"?AsyncIterator:Object).prototype),a("next"),a("throw"),a("return",o),r[Symbol.asyncIterator]=function(){return this},r;function o(b){return function(R){return Promise.resolve(R).then(b,p)}}function a(b,R){n[b]&&(r[b]=function(w){return new Promise(function(I,N){s.push([b,w,I,N])>1||d(b,w)})},R&&(r[b]=R(r[b])))}function d(b,R){try{l(n[b](R))}catch(w){g(s[0][3],w)}}function l(b){b.value instanceof xn?Promise.resolve(b.value.v).then(f,p):g(s[0][2],b)}function f(b){d("next",b)}function p(b){d("throw",b)}function g(b,R){b(R),s.shift(),s.length&&d(s[0][0],s[0][1])}}function rC(i){var e,t;return e={},n("next"),n("throw",function(r){throw r}),n("return"),e[Symbol.iterator]=function(){return this},e;function n(r,s){e[r]=i[r]?function(o){return(t=!t)?{value:xn(i[r](o)),done:!1}:s?s(o):o}:s}}function Ft(i){if(!Symbol.asyncIterator)throw new TypeError("Symbol.asyncIterator is not defined.");var e=i[Symbol.asyncIterator],t;return e?e.call(i):(i=typeof vg=="function"?vg(i):i[Symbol.iterator](),t={},n("next"),n("throw"),n("return"),t[Symbol.asyncIterator]=function(){return this},t);function n(s){t[s]=i[s]&&function(o){return new Promise(function(a,d){o=i[s](o),r(a,d,o.done,o.value)})}}function r(s,o,a,d){Promise.resolve(d).then(function(l){s({value:l,done:a})},o)}}var To={exports:{}},yg;function sC(){if(yg)return To.exports;yg=1;var i=typeof Reflect=="object"?Reflect:null,e=i&&typeof i.apply=="function"?i.apply:function(P,B,q){return Function.prototype.apply.call(P,B,q)},t;i&&typeof i.ownKeys=="function"?t=i.ownKeys:Object.getOwnPropertySymbols?t=function(P){return Object.getOwnPropertyNames(P).concat(Object.getOwnPropertySymbols(P))}:t=function(P){return Object.getOwnPropertyNames(P)};function n(M){console&&console.warn&&console.warn(M)}var r=Number.isNaN||function(P){return P!==P};function s(){s.init.call(this)}To.exports=s,To.exports.once=N,s.EventEmitter=s,s.prototype._events=void 0,s.prototype._eventsCount=0,s.prototype._maxListeners=void 0;var o=10;function a(M){if(typeof M!="function")throw new TypeError('The "listener" argument must be of type Function. Received type '+typeof M)}Object.defineProperty(s,"defaultMaxListeners",{enumerable:!0,get:function(){return o},set:function(M){if(typeof M!="number"||M<0||r(M))throw new RangeError('The value of "defaultMaxListeners" is out of range. It must be a non-negative number. Received '+M+".");o=M}}),s.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},s.prototype.setMaxListeners=function(P){if(typeof P!="number"||P<0||r(P))throw new RangeError('The value of "n" is out of range. It must be a non-negative number. Received '+P+".");return this._maxListeners=P,this};function d(M){return M._maxListeners===void 0?s.defaultMaxListeners:M._maxListeners}s.prototype.getMaxListeners=function(){return d(this)},s.prototype.emit=function(P){for(var B=[],q=1;q<arguments.length;q++)B.push(arguments[q]);var K=P==="error",ie=this._events;if(ie!==void 0)K=K&&ie.error===void 0;else if(!K)return!1;if(K){var te;if(B.length>0&&(te=B[0]),te instanceof Error)throw te;var ae=new Error("Unhandled error."+(te?" ("+te.message+")":""));throw ae.context=te,ae}var ge=ie[P];if(ge===void 0)return!1;if(typeof ge=="function")e(ge,this,B);else for(var ke=ge.length,Oe=R(ge,ke),q=0;q<ke;++q)e(Oe[q],this,B);return!0};function l(M,P,B,q){var K,ie,te;if(a(B),ie=M._events,ie===void 0?(ie=M._events=Object.create(null),M._eventsCount=0):(ie.newListener!==void 0&&(M.emit("newListener",P,B.listener?B.listener:B),ie=M._events),te=ie[P]),te===void 0)te=ie[P]=B,++M._eventsCount;else if(typeof te=="function"?te=ie[P]=q?[B,te]:[te,B]:q?te.unshift(B):te.push(B),K=d(M),K>0&&te.length>K&&!te.warned){te.warned=!0;var ae=new Error("Possible EventEmitter memory leak detected. "+te.length+" "+String(P)+" listeners added. Use emitter.setMaxListeners() to increase limit");ae.name="MaxListenersExceededWarning",ae.emitter=M,ae.type=P,ae.count=te.length,n(ae)}return M}s.prototype.addListener=function(P,B){return l(this,P,B,!1)},s.prototype.on=s.prototype.addListener,s.prototype.prependListener=function(P,B){return l(this,P,B,!0)};function f(){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 p(M,P,B){var q={fired:!1,wrapFn:void 0,target:M,type:P,listener:B},K=f.bind(q);return K.listener=B,q.wrapFn=K,K}s.prototype.once=function(P,B){return a(B),this.on(P,p(this,P,B)),this},s.prototype.prependOnceListener=function(P,B){return a(B),this.prependListener(P,p(this,P,B)),this},s.prototype.removeListener=function(P,B){var q,K,ie,te,ae;if(a(B),K=this._events,K===void 0)return this;if(q=K[P],q===void 0)return this;if(q===B||q.listener===B)--this._eventsCount===0?this._events=Object.create(null):(delete K[P],K.removeListener&&this.emit("removeListener",P,q.listener||B));else if(typeof q!="function"){for(ie=-1,te=q.length-1;te>=0;te--)if(q[te]===B||q[te].listener===B){ae=q[te].listener,ie=te;break}if(ie<0)return this;ie===0?q.shift():w(q,ie),q.length===1&&(K[P]=q[0]),K.removeListener!==void 0&&this.emit("removeListener",P,ae||B)}return this},s.prototype.off=s.prototype.removeListener,s.prototype.removeAllListeners=function(P){var B,q,K;if(q=this._events,q===void 0)return this;if(q.removeListener===void 0)return arguments.length===0?(this._events=Object.create(null),this._eventsCount=0):q[P]!==void 0&&(--this._eventsCount===0?this._events=Object.create(null):delete q[P]),this;if(arguments.length===0){var ie=Object.keys(q),te;for(K=0;K<ie.length;++K)te=ie[K],te!=="removeListener"&&this.removeAllListeners(te);return this.removeAllListeners("removeListener"),this._events=Object.create(null),this._eventsCount=0,this}if(B=q[P],typeof B=="function")this.removeListener(P,B);else if(B!==void 0)for(K=B.length-1;K>=0;K--)this.removeListener(P,B[K]);return this};function g(M,P,B){var q=M._events;if(q===void 0)return[];var K=q[P];return K===void 0?[]:typeof K=="function"?B?[K.listener||K]:[K]:B?I(K):R(K,K.length)}s.prototype.listeners=function(P){return g(this,P,!0)},s.prototype.rawListeners=function(P){return g(this,P,!1)},s.listenerCount=function(M,P){return typeof M.listenerCount=="function"?M.listenerCount(P):b.call(M,P)},s.prototype.listenerCount=b;function b(M){var P=this._events;if(P!==void 0){var B=P[M];if(typeof B=="function")return 1;if(B!==void 0)return B.length}return 0}s.prototype.eventNames=function(){return this._eventsCount>0?t(this._events):[]};function R(M,P){for(var B=new Array(P),q=0;q<P;++q)B[q]=M[q];return B}function w(M,P){for(;P+1<M.length;P++)M[P]=M[P+1];M.pop()}function I(M){for(var P=new Array(M.length),B=0;B<P.length;++B)P[B]=M[B].listener||M[B];return P}function N(M,P){return new Promise(function(B,q){function K(te){M.removeListener(P,ie),q(te)}function ie(){typeof M.removeListener=="function"&&M.removeListener("error",K),B([].slice.call(arguments))}j(M,P,ie,{once:!0}),P!=="error"&&L(M,K,{once:!0})})}function L(M,P,B){typeof M.on=="function"&&j(M,"error",P,B)}function j(M,P,B,q){if(typeof M.on=="function")q.once?M.once(P,B):M.on(P,B);else if(typeof M.addEventListener=="function")M.addEventListener(P,function K(ie){q.once&&M.removeEventListener(P,K),B(ie)});else throw new TypeError('The "emitter" argument must be of type EventEmitter. Received type '+typeof M)}return To.exports}var _t=sC(),hy=!0,py=!0;function os(i,e,t){let n=i.match(e);return n&&n.length>=t&&parseFloat(n[t],10)}function Ni(i,e,t){if(!i.RTCPeerConnection)return;if(!Object.getOwnPropertyDescriptor(EventTarget.prototype,"addEventListener").writable){Id("Unable to polyfill events");return}let r=i.RTCPeerConnection.prototype,s=r.addEventListener;r.addEventListener=function(a,d){if(a!==e)return s.apply(this,arguments);let l=f=>{let p=t(f);p&&(d.handleEvent?d.handleEvent(p):d(p))};return this._eventMap=this._eventMap||{},this._eventMap[e]||(this._eventMap[e]=new Map),this._eventMap[e].set(d,l),s.apply(this,[a,l])};let o=r.removeEventListener;r.removeEventListener=function(a,d){if(a!==e||!this._eventMap||!this._eventMap[e])return o.apply(this,arguments);if(!this._eventMap[e].has(d))return o.apply(this,arguments);let l=this._eventMap[e].get(d);
vendor: 13,980 bytes, line 39
39return this._eventMap[e].delete(d),this._eventMap[e].size===0&&delete this._eventMap[e],Object.keys(this._eventMap).length===0&&delete this._eventMap,o.apply(this,[a,l])},Object.defineProperty(r,"on"+e,{get(){return this["_on"+e]},set(a){this["_on"+e]&&(this.removeEventListener(e,this["_on"+e]),delete this["_on"+e]),a&&this.addEventListener(e,this["_on"+e]=a)},enumerable:!0,configurable:!0})}function oC(i){return typeof i!="boolean"?new Error("Argument type: "+typeof i+". Please use a boolean."):(hy=i,i?"adapter.js logging disabled":"adapter.js logging enabled")}function aC(i){return typeof i!="boolean"?new Error("Argument type: "+typeof i+". Please use a boolean."):(py=!i,"adapter.js deprecation warnings "+(i?"disabled":"enabled"))}function Id(){if(typeof window=="object"){if(hy)return;typeof console<"u"&&typeof console.log=="function"&&console.log.apply(console,arguments)}}function Od(i,e){py&&console.warn(i+" is deprecated, please use "+e+" instead.")}function cC(i){let e={browser:null,version:null};if(typeof i>"u"||!i.navigator||!i.navigator.userAgent)return e.browser="Not a browser.",e;let t=i.navigator;if(t.userAgentData&&t.userAgentData.brands){let n=t.userAgentData.brands.find(r=>r.brand==="Chromium");if(n){let r=parseInt(n.version,10);if(r>=90)return{browser:"chrome",version:r}}}if(t.mozGetUserMedia)e.browser="firefox",e.version=parseInt(os(t.userAgent,/Firefox\/(\d+)\./,1));else if(t.webkitGetUserMedia||i.isSecureContext===!1&&i.webkitRTCPeerConnection)e.browser="chrome",e.version=parseInt(os(t.userAgent,/Chrom(e|ium)\/(\d+)\./,2))||null;else if(i.RTCPeerConnection&&t.userAgent.match(/AppleWebKit\/(\d+)\./))e.browser="safari",e.version=parseInt(os(t.userAgent,/AppleWebKit\/(\d+)\./,1)),e.supportsUnifiedPlan=i.RTCRtpTransceiver&&"currentDirection"in i.RTCRtpTransceiver.prototype,e._safariVersion=os(t.userAgent,/Version\/(\d+(\.?\d+))/,1);else return e.browser="Not a supported browser.",e;return e}function bg(i){return Object.prototype.toString.call(i)==="[object Object]"}function fy(i){return bg(i)?Object.keys(i).reduce(function(e,t){let n=bg(i[t]),r=n?fy(i[t]):i[t],s=n&&!Object.keys(r).length;return r===void 0||s?e:Object.assign(e,{[t]:r})},{}):i}function Yl(i,e,t){!e||t.has(e.id)||(t.set(e.id,e),Object.keys(e).forEach(n=>{n.endsWith("Id")?Yl(i,i.get(e[n]),t):n.endsWith("Ids")&&e[n].forEach(r=>{Yl(i,i.get(r),t)})}))}function kg(i,e,t){let n=t?"outbound-rtp":"inbound-rtp",r=new Map;if(e===null)return r;let s=[];return i.forEach(o=>{o.type==="track"&&o.trackIdentifier===e.id&&s.push(o)}),s.forEach(o=>{i.forEach(a=>{a.type===n&&a.trackId===o.id&&Yl(i,a,r)})}),r}var Sg=Id;function my(i,e){if(e.version>=64)return;let t=i&&i.navigator;if(!t.mediaDevices)return;let n=function(a){if(typeof a!="object"||a.mandatory||a.optional)return a;let d={};return Object.keys(a).forEach(l=>{if(l==="require"||l==="advanced"||l==="mediaSource")return;let f=typeof a[l]=="object"?a[l]:{ideal:a[l]};f.exact!==void 0&&typeof f.exact=="number"&&(f.min=f.max=f.exact);let p=function(g,b){return g?g+b.charAt(0).toUpperCase()+b.slice(1):b==="deviceId"?"sourceId":b};if(f.ideal!==void 0){d.optional=d.optional||[];let g={};typeof f.ideal=="number"?(g[p("min",l)]=f.ideal,d.optional.push(g),g={},g[p("max",l)]=f.ideal,d.optional.push(g)):(g[p("",l)]=f.ideal,d.optional.push(g))}f.exact!==void 0&&typeof f.exact!="number"?(d.mandatory=d.mandatory||{},d.mandatory[p("",l)]=f.exact):["min","max"].forEach(g=>{f[g]!==void 0&&(d.mandatory=d.mandatory||{},d.mandatory[p(g,l)]=f[g])})}),a.advanced&&(d.optional=(d.optional||[]).concat(a.advanced)),d},r=function(a,d){if(e.version>=61)return d(a);if(a=JSON.parse(JSON.stringify(a)),a&&typeof a.audio=="object"){let l=function(f,p,g){p in f&&!(g in f)&&(f[g]=f[p],delete f[p])};a=JSON.parse(JSON.stringify(a)),l(a.audio,"autoGainControl","googAutoGainControl"),l(a.audio,"noiseSuppression","googNoiseSuppression"),a.audio=n(a.audio)}if(a&&typeof a.video=="object"){let l=a.video.facingMode;l=l&&(typeof l=="object"?l:{ideal:l});let f=e.version<66;if(l&&(l.exact==="user"||l.exact==="environment"||l.ideal==="user"||l.ideal==="environment")&&!(t.mediaDevices.getSupportedConstraints&&t.mediaDevices.getSupportedConstraints().facingMode&&!f)){delete a.video.facingMode;let p;if(l.exact==="environment"||l.ideal==="environment"?p=["back","rear"]:(l.exact==="user"||l.ideal==="user")&&(p=["front"]),p)return t.mediaDevices.enumerateDevices().then(g=>{g=g.filter(R=>R.kind==="videoinput");let b=g.find(R=>p.some(w=>R.label.toLowerCase().includes(w)));return!b&&g.length&&p.includes("back")&&(b=g[g.length-1]),b&&(a.video.deviceId=l.exact?{exact:b.deviceId}:{ideal:b.deviceId}),a.video=n(a.video),Sg("chrome: "+JSON.stringify(a)),d(a)})}a.video=n(a.video)}return Sg("chrome: "+JSON.stringify(a)),d(a)},s=function(a){return e.version>=64?a:{name:{PermissionDeniedError:"NotAllowedError",PermissionDismissedError:"NotAllowedError",InvalidStateError:"NotAllowedError",DevicesNotFoundError:"NotFoundError",ConstraintNotSatisfiedError:"OverconstrainedError",TrackStartError:"NotReadableError",MediaDeviceFailedDueToShutdown:"NotAllowedError",MediaDeviceKillSwitchOn:"NotAllowedError",TabCaptureError:"AbortError",ScreenCaptureError:"AbortError",DeviceCaptureError:"AbortError"}[a.name]||a.name,message:a.message,constraint:a.constraint||a.constraintName,toString(){return this.name+(this.message&&": ")+this.message}}},o=function(a,d,l){r(a,f=>{t.webkitGetUserMedia(f,d,p=>{l&&l(s(p))})})};if(t.getUserMedia=o.bind(t),t.mediaDevices.getUserMedia){let a=t.mediaDevices.getUserMedia.bind(t.mediaDevices);t.mediaDevices.getUserMedia=function(d){return r(d,l=>a(l).then(f=>{if(l.audio&&!f.getAudioTracks().length||l.video&&!f.getVideoTracks().length)throw f.getTracks().forEach(p=>{p.stop()}),new DOMException("","NotFoundError");return f},f=>Promise.reject(s(f))))}}}function gy(i){i.MediaStream=i.MediaStream||i.webkitMediaStream}function vy(i,e){if(!(e.version>102))if(typeof i=="object"&&i.RTCPeerConnection&&!("ontrack"in i.RTCPeerConnection.prototype)){Object.defineProperty(i.RTCPeerConnection.prototype,"ontrack",{get(){return this._ontrack},set(n){this._ontrack&&this.removeEventListener("track",this._ontrack),this.addEventListener("track",this._ontrack=n)},enumerable:!0,configurable:!0});let t=i.RTCPeerConnection.prototype.setRemoteDescription;i.RTCPeerConnection.prototype.setRemoteDescription=function(){return this._ontrackpoly||(this._ontrackpoly=r=>{r.stream.addEventListener("addtrack",s=>{let o;i.RTCPeerConnection.prototype.getReceivers?o=this.getReceivers().find(d=>d.track&&d.track.id===s.track.id):o={track:s.track};let a=new Event("track");a.track=s.track,a.receiver=o,a.transceiver={receiver:o},a.streams=[r.stream],this.dispatchEvent(a)}),r.stream.getTracks().forEach(s=>{let o;i.RTCPeerConnection.prototype.getReceivers?o=this.getReceivers().find(d=>d.track&&d.track.id===s.id):o={track:s};let a=new Event("track");a.track=s,a.receiver=o,a.transceiver={receiver:o},a.streams=[r.stream],this.dispatchEvent(a)})},this.addEventListener("addstream",this._ontrackpoly)),t.apply(this,arguments)}}else Ni(i,"track",t=>(t.transceiver||Object.defineProperty(t,"transceiver",{value:{receiver:t.receiver}}),t))}function yy(i){if(typeof i=="object"&&i.RTCPeerConnection&&!("getSenders"in i.RTCPeerConnection.prototype)&&"createDTMFSender"in i.RTCPeerConnection.prototype){let e=function(r,s){return{track:s,get dtmf(){return this._dtmf===void 0&&(s.kind==="audio"?this._dtmf=r.createDTMFSender(s):this._dtmf=null),this._dtmf},_pc:r}};if(!i.RTCPeerConnection.prototype.getSenders){i.RTCPeerConnection.prototype.getSenders=function(){return this._senders=this._senders||[],this._senders.slice()};let r=i.RTCPeerConnection.prototype.addTrack;i.RTCPeerConnection.prototype.addTrack=function(a,d){let l=r.apply(this,arguments);return l||(l=e(this,a),this._senders.push(l)),l};let s=i.RTCPeerConnection.prototype.removeTrack;i.RTCPeerConnection.prototype.removeTrack=function(a){s.apply(this,arguments);let d=this._senders.indexOf(a);d!==-1&&this._senders.splice(d,1)}}let t=i.RTCPeerConnection.prototype.addStream;i.RTCPeerConnection.prototype.addStream=function(s){this._senders=this._senders||[],t.apply(this,[s]),s.getTracks().forEach(o=>{this._senders.push(e(this,o))})};let n=i.RTCPeerConnection.prototype.removeStream;i.RTCPeerConnection.prototype.removeStream=function(s){this._senders=this._senders||[],n.apply(this,[s]),s.getTracks().forEach(o=>{let a=this._senders.find(d=>d.track===o);a&&this._senders.splice(this._senders.indexOf(a),1)})}}else if(typeof i=="object"&&i.RTCPeerConnection&&"getSenders"in i.RTCPeerConnection.prototype&&"createDTMFSender"in i.RTCPeerConnection.prototype&&i.RTCRtpSender&&!("dtmf"in i.RTCRtpSender.prototype)){let e=i.RTCPeerConnection.prototype.getSenders;i.RTCPeerConnection.prototype.getSenders=function(){let n=e.apply(this,[]);return n.forEach(r=>r._pc=this),n},Object.defineProperty(i.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 by(i,e){if(e.version>=67||!(typeof i=="object"&&i.RTCPeerConnection&&i.RTCRtpSender&&i.RTCRtpReceiver))return;if(!("getStats"in i.RTCRtpSender.prototype)){let n=i.RTCPeerConnection.prototype.getSenders;n&&(i.RTCPeerConnection.prototype.getSenders=function(){let o=n.apply(this,[]);return o.forEach(a=>a._pc=this),o});let r=i.RTCPeerConnection.prototype.addTrack;r&&(i.RTCPeerConnection.prototype.addTrack=function(){let o=r.apply(this,arguments);return o._pc=this,o}),i.RTCRtpSender.prototype.getStats=function(){let o=this;return this._pc.getStats().then(a=>kg(a,o.track,!0))}}if(!("getStats"in i.RTCRtpReceiver.prototype)){let n=i.RTCPeerConnection.prototype.getReceivers;n&&(i.RTCPeerConnection.prototype.getReceivers=function(){let s=n.apply(this,[]);return s.forEach(o=>o._pc=this),s}),Ni(i,"track",r=>(r.receiver._pc=r.srcElement,r)),i.RTCRtpReceiver.prototype.getStats=function(){let s=this;return this._pc.getStats().then(o=>kg(o,s.track,!1))}}if(!("getStats"in i.RTCRtpSender.prototype&&"getStats"in i.RTCRtpReceiver.prototype))return;let t=i.RTCPeerConnection.prototype.getStats;i.RTCPeerConnection.prototype.getStats=function(){if(arguments.length>0&&arguments[0]instanceof i.MediaStreamTrack){let r=arguments[0],s,o,a;return this.getSenders().forEach(d=>{d.track===r&&(s?a=!0:s=d)}),this.getReceivers().forEach(d=>(d.track===r&&(o?a=!0:o=d),d.track===r)),a||s&&o?Promise.reject(new DOMException("There are more than one sender or receiver for the track.","InvalidAccessError")):s?s.getStats():o?o.getStats():Promise.reject(new DOMException("There is no sender or receiver for the track.","InvalidAccessError"))}return t.apply(this,arguments)}}function ky(i){i.RTCPeerConnection.prototype.getLocalStreams=function(){return this._shimmedLocalStreams=this._shimmedLocalStreams||{},Object.keys(this._shimmedLocalStreams).map(o=>this._shimmedLocalStreams[o][0])};let e=i.RTCPeerConnection.prototype.addTrack;i.RTCPeerConnection.prototype.addTrack=function(o,a){if(!a)return e.apply(this,arguments);this._shimmedLocalStreams=this._shimmedLocalStreams||{};let d=e.apply(this,arguments);return this._shimmedLocalStreams[a.id]?this._shimmedLocalStreams[a.id].indexOf(d)===-1&&this._shimmedLocalStreams[a.id].push(d):this._shimmedLocalStreams[a.id]=[a,d],d};let t=i.RTCPeerConnection.prototype.addStream;i.RTCPeerConnection.prototype.addStream=function(o){this._shimmedLocalStreams=this._shimmedLocalStreams||{},o.getTracks().forEach(l=>{if(this.getSenders().find(p=>p.track===l))throw new DOMException("Track already exists.","InvalidAccessError")});let a=this.getSenders();t.apply(this,arguments);let d=this.getSenders().filter(l=>a.indexOf(l)===-1);this._shimmedLocalStreams[o.id]=[o].concat(d)};let n=i.RTCPeerConnection.prototype.removeStream;i.RTCPeerConnection.prototype.removeStream=function(o){return this._shimmedLocalStreams=this._shimmedLocalStreams||{},delete this._shimmedLocalStreams[o.id],n.apply(this,arguments)};let r=i.RTCPeerConnection.prototype.removeTrack;i.RTCPeerConnection.prototype.removeTrack=function(o){return this._shimmedLocalStreams=this._shimmedLocalStreams||{},o&&Object.keys(this._shimmedLocalStreams).forEach(a=>{let d=this._shimmedLocalStreams[a].indexOf(o);d!==-1&&this._shimmedLocalStreams[a].splice(d,1),this._shimmedLocalStreams[a].length===1&&delete this._shimmedLocalStreams[a]}),r.apply(this,arguments)}}function Sy(i,e){if(!i.RTCPeerConnection)return;if(i.RTCPeerConnection.prototype.addTrack&&e.version>=65)return ky(i);let t=i.RTCPeerConnection.prototype.getLocalStreams;i.RTCPeerConnection.prototype.getLocalStreams=function(){let f=t.apply(this);return this._reverseStreams=this._reverseStreams||{},f.map(p=>this._reverseStreams[p.id])};let n=i.RTCPeerConnection.prototype.addStream;i.RTCPeerConnection.prototype.addStream=function(f){if(this._streams=this._streams||{},this._reverseStreams=this._reverseStreams||{},f.getTracks().forEach(p=>{if(this.getSenders().find(b=>b.track===p))throw new DOMException("Track already exists.","InvalidAccessError")}),!this._reverseStreams[f.id]){let p=new i.MediaStream(f.getTracks());this._streams[f.id]=p,this._reverseStreams[p.id]=f,f=p}n.apply(this,[f])};let r=i.RTCPeerConnection.prototype.removeStream;i.RTCPeerConnection.prototype.removeStream=function(f){this._streams=this._streams||{},this._reverseStreams=this._reverseStreams||{},r.apply(this,[this._streams[f.id]||f]),delete this._reverseStreams[this._streams[f.id]?this._streams[f.id].id:f.id],delete this._streams[f.id]},i.RTCPeerConnection.prototype.addTrack=function(f,p){if(this.signalingState==="closed")throw new DOMException("The RTCPeerConnection's signalingState is 'closed'.","InvalidStateError");let g=[].slice.call(arguments,1);if(g.length!==1||!g[0].getTracks().find(w=>w===f))throw new DOMException("The adapter.js addTrack polyfill only supports a single stream which is associated with the specified track.","NotSupportedError");
vendor: 10,292 bytes, line 39
39if(this.getSenders().find(w=>w.track===f))throw new DOMException("Track already exists.","InvalidAccessError");this._streams=this._streams||{},this._reverseStreams=this._reverseStreams||{};let R=this._streams[p.id];if(R)R.addTrack(f),Promise.resolve().then(()=>{this.dispatchEvent(new Event("negotiationneeded"))});else{let w=new i.MediaStream([f]);this._streams[p.id]=w,this._reverseStreams[w.id]=p,this.addStream(w)}return this.getSenders().find(w=>w.track===f)};function s(l,f){let p=f.sdp;return Object.keys(l._reverseStreams||[]).forEach(g=>{let b=l._reverseStreams[g],R=l._streams[b.id];p=p.replace(new RegExp(R.id,"g"),b.id)}),new RTCSessionDescription({type:f.type,sdp:p})}function o(l,f){let p=f.sdp;return Object.keys(l._reverseStreams||[]).forEach(g=>{let b=l._reverseStreams[g],R=l._streams[b.id];p=p.replace(new RegExp(b.id,"g"),R.id)}),new RTCSessionDescription({type:f.type,sdp:p})}["createOffer","createAnswer"].forEach(function(l){let f=i.RTCPeerConnection.prototype[l],p={[l](){let g=arguments;return arguments.length&&typeof arguments[0]=="function"?f.apply(this,[R=>{let w=s(this,R);g[0].apply(null,[w])},R=>{g[1]&&g[1].apply(null,R)},arguments[2]]):f.apply(this,arguments).then(R=>s(this,R))}};i.RTCPeerConnection.prototype[l]=p[l]});let a=i.RTCPeerConnection.prototype.setLocalDescription;i.RTCPeerConnection.prototype.setLocalDescription=function(){return!arguments.length||!arguments[0].type?a.apply(this,arguments):(arguments[0]=o(this,arguments[0]),a.apply(this,arguments))};let d=Object.getOwnPropertyDescriptor(i.RTCPeerConnection.prototype,"localDescription");Object.defineProperty(i.RTCPeerConnection.prototype,"localDescription",{get(){let l=d.get.apply(this);return l.type===""?l:s(this,l)}}),i.RTCPeerConnection.prototype.removeTrack=function(f){if(this.signalingState==="closed")throw new DOMException("The RTCPeerConnection's signalingState is 'closed'.","InvalidStateError");if(!f._pc)throw new DOMException("Argument 1 of RTCPeerConnection.removeTrack does not implement interface RTCRtpSender.","TypeError");if(!(f._pc===this))throw new DOMException("Sender was not created by this connection.","InvalidAccessError");this._streams=this._streams||{};let g;Object.keys(this._streams).forEach(b=>{this._streams[b].getTracks().find(w=>f.track===w)&&(g=this._streams[b])}),g&&(g.getTracks().length===1?this.removeStream(this._reverseStreams[g.id]):g.removeTrack(f.track),this.dispatchEvent(new Event("negotiationneeded")))}}function Ql(i,e){!i.RTCPeerConnection&&i.webkitRTCPeerConnection&&(i.RTCPeerConnection=i.webkitRTCPeerConnection),i.RTCPeerConnection&&e.version<53&&["setLocalDescription","setRemoteDescription","addIceCandidate"].forEach(function(t){let n=i.RTCPeerConnection.prototype[t],r={[t](){return arguments[0]=new(t==="addIceCandidate"?i.RTCIceCandidate:i.RTCSessionDescription)(arguments[0]),n.apply(this,arguments)}};i.RTCPeerConnection.prototype[t]=r[t]})}function Ty(i,e){e.version>102||Ni(i,"negotiationneeded",t=>{let n=t.target;if(!((e.version<72||n.getConfiguration&&n.getConfiguration().sdpSemantics==="plan-b")&&n.signalingState!=="stable"))return t})}var Tg=Object.freeze({__proto__:null,fixNegotiationNeeded:Ty,shimAddTrackRemoveTrack:Sy,shimAddTrackRemoveTrackWithNative:ky,shimGetSendersWithDtmf:yy,shimGetUserMedia:my,shimMediaStream:gy,shimOnTrack:vy,shimPeerConnection:Ql,shimSenderReceiverGetStats:by});function _y(i,e){let t=i&&i.navigator;if(!t.mediaDevices)return;let n=i&&i.MediaStreamTrack;if(t.getUserMedia=function(r,s,o){Od("navigator.getUserMedia","navigator.mediaDevices.getUserMedia"),t.mediaDevices.getUserMedia(r).then(s,o)},!(e.version>55&&"autoGainControl"in t.mediaDevices.getSupportedConstraints())){let r=function(o,a,d){a in o&&!(d in o)&&(o[d]=o[a],delete o[a])},s=t.mediaDevices.getUserMedia.bind(t.mediaDevices);if(t.mediaDevices.getUserMedia=function(o){return typeof o=="object"&&typeof o.audio=="object"&&(o=JSON.parse(JSON.stringify(o)),r(o.audio,"autoGainControl","mozAutoGainControl"),r(o.audio,"noiseSuppression","mozNoiseSuppression")),s(o)},n&&n.prototype.getSettings){let o=n.prototype.getSettings;n.prototype.getSettings=function(){let a=o.apply(this,arguments);return r(a,"mozAutoGainControl","autoGainControl"),r(a,"mozNoiseSuppression","noiseSuppression"),a}}if(n&&n.prototype.applyConstraints){let o=n.prototype.applyConstraints;n.prototype.applyConstraints=function(a){return this.kind==="audio"&&typeof a=="object"&&(a=JSON.parse(JSON.stringify(a)),r(a,"autoGainControl","mozAutoGainControl"),r(a,"noiseSuppression","mozNoiseSuppression")),o.apply(this,[a])}}}}function lC(i,e){i.navigator.mediaDevices&&(i.navigator.mediaDevices&&"getDisplayMedia"in i.navigator.mediaDevices||(i.navigator.mediaDevices.getDisplayMedia=function(n){if(!(n&&n.video)){let r=new DOMException("getDisplayMedia without video constraints is undefined");return r.name="NotFoundError",r.code=8,Promise.reject(r)}return n.video===!0?n.video={mediaSource:e}:n.video.mediaSource=e,i.navigator.mediaDevices.getUserMedia(n)}))}function Cy(i){typeof i=="object"&&i.RTCTrackEvent&&"receiver"in i.RTCTrackEvent.prototype&&!("transceiver"in i.RTCTrackEvent.prototype)&&Object.defineProperty(i.RTCTrackEvent.prototype,"transceiver",{get(){return{receiver:this.receiver}}})}function Xl(i,e){typeof i!="object"||!(i.RTCPeerConnection||i.mozRTCPeerConnection)||(!i.RTCPeerConnection&&i.mozRTCPeerConnection&&(i.RTCPeerConnection=i.mozRTCPeerConnection),e.version<53&&["setLocalDescription","setRemoteDescription","addIceCandidate"].forEach(function(t){let n=i.RTCPeerConnection.prototype[t],r={[t](){return arguments[0]=new(t==="addIceCandidate"?i.RTCIceCandidate:i.RTCSessionDescription)(arguments[0]),n.apply(this,arguments)}};i.RTCPeerConnection.prototype[t]=r[t]}))}function wy(i,e){if(typeof i!="object"||!(i.RTCPeerConnection||i.mozRTCPeerConnection)||e.version>=151)return;let t={inboundrtp:"inbound-rtp",outboundrtp:"outbound-rtp",candidatepair:"candidate-pair",localcandidate:"local-candidate",remotecandidate:"remote-candidate"},n=i.RTCPeerConnection.prototype.getStats;i.RTCPeerConnection.prototype.getStats=function(){let s=Array.prototype.slice.call(arguments),o=s[0],a=s[1],d=s[2];return this.signalingState==="closed"?Promise.resolve(new Map):n.apply(this,[o||null]).then(l=>{if(e.version<53&&!a)try{l.forEach(f=>{f.type=t[f.type]||f.type})}catch(f){if(f.name!=="TypeError")throw f;l.forEach((p,g)=>{l.set(g,Object.assign({},p,{type:t[p.type]||p.type}))})}return l}).then(a,d)}}function Ey(i){if(!(typeof i=="object"&&i.RTCPeerConnection&&i.RTCRtpSender)||i.RTCRtpSender&&"getStats"in i.RTCRtpSender.prototype)return;let e=i.RTCPeerConnection.prototype.getSenders;e&&(i.RTCPeerConnection.prototype.getSenders=function(){let r=e.apply(this,[]);return r.forEach(s=>s._pc=this),r});let t=i.RTCPeerConnection.prototype.addTrack;t&&(i.RTCPeerConnection.prototype.addTrack=function(){let r=t.apply(this,arguments);return r._pc=this,r}),i.RTCRtpSender.prototype.getStats=function(){return this.track?this._pc.getStats(this.track):Promise.resolve(new Map)}}function Py(i){if(!(typeof i=="object"&&i.RTCPeerConnection&&i.RTCRtpSender)||i.RTCRtpSender&&"getStats"in i.RTCRtpReceiver.prototype)return;let e=i.RTCPeerConnection.prototype.getReceivers;e&&(i.RTCPeerConnection.prototype.getReceivers=function(){let n=e.apply(this,[]);return n.forEach(r=>r._pc=this),n}),Ni(i,"track",t=>(t.receiver._pc=t.srcElement,t)),i.RTCRtpReceiver.prototype.getStats=function(){return this._pc.getStats(this.track)}}function Ay(i){!i.RTCPeerConnection||"removeStream"in i.RTCPeerConnection.prototype||(i.RTCPeerConnection.prototype.removeStream=function(t){Od("removeStream","removeTrack"),this.getSenders().forEach(n=>{n.track&&t.getTracks().includes(n.track)&&this.removeTrack(n)})})}function My(i){i.DataChannel&&!i.RTCDataChannel&&(i.RTCDataChannel=i.DataChannel)}function Ry(i,e){if(!(typeof i=="object"&&i.RTCPeerConnection)||e.version>=110)return;let t=i.RTCPeerConnection.prototype.addTransceiver;t&&(i.RTCPeerConnection.prototype.addTransceiver=function(){this.setParametersPromises=[];let r=arguments[1]&&arguments[1].sendEncodings;r===void 0&&(r=[]),r=[...r];let s=r.length>0;s&&r.forEach(a=>{if("rid"in a&&!/^[a-z0-9]{0,16}$/i.test(a.rid))throw new TypeError("Invalid RID value provided.");if("scaleResolutionDownBy"in a&&!(parseFloat(a.scaleResolutionDownBy)>=1))throw new RangeError("scale_resolution_down_by must be >= 1.0");if("maxFramerate"in a&&!(parseFloat(a.maxFramerate)>=0))throw new RangeError("max_framerate must be >= 0.0")});let o=t.apply(this,arguments);if(s){let a=o.sender,d=a.getParameters();(!("encodings"in d)||d.encodings.length===1&&Object.keys(d.encodings[0]).length===0)&&(d.encodings=r,a.sendEncodings=r,this.setParametersPromises.push(a.setParameters(d).then(()=>{delete a.sendEncodings}).catch(()=>{delete a.sendEncodings})))}return o})}function Iy(i,e){if(!(typeof i=="object"&&i.RTCRtpSender)||e.version>=110)return;let t=i.RTCRtpSender.prototype.getParameters;t&&(i.RTCRtpSender.prototype.getParameters=function(){let r=t.apply(this,arguments);return"encodings"in r||(r.encodings=[].concat(this.sendEncodings||[{}])),r})}function Oy(i,e){if(!(typeof i=="object"&&i.RTCPeerConnection)||e.version>=110)return;let t=i.RTCPeerConnection.prototype.createOffer;i.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 Dy(i,e){if(!(typeof i=="object"&&i.RTCPeerConnection)||e.version>=110)return;let t=i.RTCPeerConnection.prototype.createAnswer;i.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 _g=Object.freeze({__proto__:null,shimAddTransceiver:Ry,shimCreateAnswer:Dy,shimCreateOffer:Oy,shimGetDisplayMedia:lC,shimGetParameters:Iy,shimGetStats:wy,shimGetUserMedia:_y,shimOnTrack:Cy,shimPeerConnection:Xl,shimRTCDataChannel:My,shimReceiverGetStats:Py,shimRemoveStream:Ay,shimSenderGetStats:Ey});function Ly(i){if(!(typeof i!="object"||!i.RTCPeerConnection)){if
vendor: 6,149 bytes, lines 39-41
39("getLocalStreams"in i.RTCPeerConnection.prototype||(i.RTCPeerConnection.prototype.getLocalStreams=function(){return this._localStreams||(this._localStreams=[]),this._localStreams}),!("addStream"in i.RTCPeerConnection.prototype)){let e=i.RTCPeerConnection.prototype.addTrack;i.RTCPeerConnection.prototype.addStream=function(n){this._localStreams||(this._localStreams=[]),this._localStreams.includes(n)||this._localStreams.push(n),n.getAudioTracks().forEach(r=>e.call(this,r,n)),n.getVideoTracks().forEach(r=>e.call(this,r,n))},i.RTCPeerConnection.prototype.addTrack=function(n){for(var r=arguments.length,s=new Array(r>1?r-1:0),o=1;o<r;o++)s[o-1]=arguments[o];return s&&s.forEach(a=>{this._localStreams?this._localStreams.includes(a)||this._localStreams.push(a):this._localStreams=[a]}),e.apply(this,arguments)}}"removeStream"in i.RTCPeerConnection.prototype||(i.RTCPeerConnection.prototype.removeStream=function(t){this._localStreams||(this._localStreams=[]);let n=this._localStreams.indexOf(t);if(n===-1)return;this._localStreams.splice(n,1);let r=t.getTracks();this.getSenders().forEach(s=>{r.includes(s.track)&&this.removeTrack(s)})})}}function xy(i){if(!(typeof i!="object"||!i.RTCPeerConnection)&&("getRemoteStreams"in i.RTCPeerConnection.prototype||(i.RTCPeerConnection.prototype.getRemoteStreams=function(){return this._remoteStreams?this._remoteStreams:[]}),!("onaddstream"in i.RTCPeerConnection.prototype))){Object.defineProperty(i.RTCPeerConnection.prototype,"onaddstream",{get(){return this._onaddstream},set(t){this._onaddstream&&(this.removeEventListener("addstream",this._onaddstream),this.removeEventListener("track",this._onaddstreampoly)),this.addEventListener("addstream",this._onaddstream=t),this.addEventListener("track",this._onaddstreampoly=n=>{n.streams.forEach(r=>{if(this._remoteStreams||(this._remoteStreams=[]),this._remoteStreams.includes(r))return;this._remoteStreams.push(r);let s=new Event("addstream");s.stream=r,this.dispatchEvent(s)})})}});let e=i.RTCPeerConnection.prototype.setRemoteDescription;i.RTCPeerConnection.prototype.setRemoteDescription=function(){let n=this;return this._onaddstreampoly||this.addEventListener("track",this._onaddstreampoly=function(r){r.streams.forEach(s=>{if(n._remoteStreams||(n._remoteStreams=[]),n._remoteStreams.indexOf(s)>=0)return;n._remoteStreams.push(s);let o=new Event("addstream");o.stream=s,n.dispatchEvent(o)})}),e.apply(n,arguments)}}}function Ny(i){if(typeof i!="object"||!i.RTCPeerConnection)return;let e=i.RTCPeerConnection.prototype,t=e.createOffer,n=e.createAnswer,r=e.setLocalDescription,s=e.setRemoteDescription,o=e.addIceCandidate;e.createOffer=function(l,f){let p=arguments.length>=2?arguments[2]:arguments[0],g=t.apply(this,[p]);return f?(g.then(l,f),Promise.resolve()):g},e.createAnswer=function(l,f){let p=arguments.length>=2?arguments[2]:arguments[0],g=n.apply(this,[p]);return f?(g.then(l,f),Promise.resolve()):g};let a=function(d,l,f){let p=r.apply(this,[d]);return f?(p.then(l,f),Promise.resolve()):p};e.setLocalDescription=a,a=function(d,l,f){let p=s.apply(this,[d]);return f?(p.then(l,f),Promise.resolve()):p},e.setRemoteDescription=a,a=function(d,l,f){let p=o.apply(this,[d]);return f?(p.then(l,f),Promise.resolve()):p},e.addIceCandidate=a}function Fy(i){let e=i&&i.navigator;if(e.mediaDevices&&e.mediaDevices.getUserMedia){let t=e.mediaDevices,n=t.getUserMedia.bind(t);e.mediaDevices.getUserMedia=r=>n(Uy(r))}!e.getUserMedia&&e.mediaDevices&&e.mediaDevices.getUserMedia&&(e.getUserMedia=function(n,r,s){e.mediaDevices.getUserMedia(n).then(r,s)}.bind(e))}function Uy(i){return i&&i.video!==void 0?Object.assign({},i,{video:fy(i.video)}):i}function jy(i){if(!i.RTCPeerConnection)return;let e=i.RTCPeerConnection;i.RTCPeerConnection=function(n,r){if(n&&n.iceServers){let s=[];for(let o=0;o<n.iceServers.length;o++){let a=n.iceServers[o];a.urls===void 0&&a.url?(Od("RTCIceServer.url","RTCIceServer.urls"),a=JSON.parse(JSON.stringify(a)),a.urls=a.url,delete a.url,s.push(a)):s.push(n.iceServers[o])}n.iceServers=s}return new e(n,r)},i.RTCPeerConnection.prototype=e.prototype,"generateCertificate"in e&&Object.defineProperty(i.RTCPeerConnection,"generateCertificate",{get(){return e.generateCertificate}})}function By(i){typeof i=="object"&&i.RTCTrackEvent&&"receiver"in i.RTCTrackEvent.prototype&&!("transceiver"in i.RTCTrackEvent.prototype)&&Object.defineProperty(i.RTCTrackEvent.prototype,"transceiver",{get(){return{receiver:this.receiver}}})}function qy(i){let e=i.RTCPeerConnection.prototype.createOffer;i.RTCPeerConnection.prototype.createOffer=function(n){if(n){typeof n.offerToReceiveAudio<"u"&&(n.offerToReceiveAudio=!!n.offerToReceiveAudio);let r=this.getTransceivers().find(o=>o.receiver.track.kind==="audio");n.offerToReceiveAudio===!1&&r?r.direction==="sendrecv"?r.setDirection?r.setDirection("sendonly"):r.direction="sendonly":r.direction==="recvonly"&&(r.setDirection?r.setDirection("inactive"):r.direction="inactive"):n.offerToReceiveAudio===!0&&!r&&this.addTransceiver("audio",{direction:"recvonly"}),typeof n.offerToReceiveVideo<"u"&&(n.offerToReceiveVideo=!!n.offerToReceiveVideo);let s=this.getTransceivers().find(o=>o.receiver.track.kind==="video");n.offerToReceiveVideo===!1&&s?s.direction==="sendrecv"?s.setDirection?s.setDirection("sendonly"):s.direction="sendonly":s.direction==="recvonly"&&(s.setDirection?s.setDirection("inactive"):s.direction="inactive"):n.offerToReceiveVideo===!0&&!s&&this.addTransceiver("video",{direction:"recvonly"})}return e.apply(this,arguments)}}function Vy(i){typeof i!="object"||i.AudioContext||(i.AudioContext=i.webkitAudioContext)}var Cg=Object.freeze({__proto__:null,shimAudioContext:Vy,shimCallbacksAPI:Ny,shimConstraints:Uy,shimCreateOfferLegacy:qy,shimGetUserMedia:Fy,shimLocalStreamsAPI:Ly,shimRTCIceServerUrls:jy,shimRemoteStreamsAPI:xy,shimTrackEventTransceiver:By}),gl={exports:{}},wg;function uC(){return wg||(wg=1,(function(i){let e={};e.generateIdentifier=function(){return Math.random().toString(36).substring(2,12)},e.localCName=e.generateIdentifier(),e.splitLines=function(t){return t.trim().split(` 40`).map(n=>n.trim())},e.splitSections=function(t){return t.split(` 41m=`).map((r,s)=>(s>
vendor: 6,819 bytes, lines 41-56
410?"m="+r:r).trim()+`\r 42`)},e.getDescription=function(t){let n=e.splitSections(t);return n&&n[0]},e.getMediaSections=function(t){let n=e.splitSections(t);return n.shift(),n},e.matchPrefix=function(t,n){return e.splitLines(t).filter(r=>r.indexOf(n)===0)},e.parseCandidate=function(t){let n;t.indexOf("a=candidate:")===0?n=t.substring(12).split(" "):n=t.substring(10).split(" ");let r={foundation:n[0],component:{1:"rtp",2:"rtcp"}[n[1]]||n[1],protocol:n[2].toLowerCase(),priority:parseInt(n[3],10),ip:n[4],address:n[4],port:parseInt(n[5],10),type:n[7]};for(let s=8;s<n.length;s+=2)switch(n[s]){case"raddr":r.relatedAddress=n[s+1];break;case"rport":r.relatedPort=parseInt(n[s+1],10);break;case"tcptype":r.tcpType=n[s+1];break;case"ufrag":r.ufrag=n[s+1],r.usernameFragment=n[s+1];break;default:r[n[s]]===void 0&&(r[n[s]]=n[s+1]);break}return r},e.writeCandidate=function(t){let n=[];n.push(t.foundation);let r=t.component;r==="rtp"?n.push(1):r==="rtcp"?n.push(2):n.push(r),n.push(t.protocol.toUpperCase()),n.push(t.priority),n.push(t.address||t.ip),n.push(t.port);let s=t.type;return n.push("typ"),n.push(s),s!=="host"&&t.relatedAddress&&t.relatedPort!==void 0&&(n.push("raddr"),n.push(t.relatedAddress),n.push("rport"),n.push(t.relatedPort)),t.tcpType&&t.protocol.toLowerCase()==="tcp"&&(n.push("tcptype"),n.push(t.tcpType)),(t.usernameFragment||t.ufrag)&&(n.push("ufrag"),n.push(t.usernameFragment||t.ufrag)),"candidate:"+n.join(" ")},e.parseIceOptions=function(t){return t.substring(14).split(" ")},e.parseRtpMap=function(t){let n=t.substring(9).split(" "),r={payloadType:parseInt(n.shift(),10)};return n=n[0].split("/"),r.name=n[0],r.clockRate=parseInt(n[1],10),r.channels=n.length===3?parseInt(n[2],10):1,r.numChannels=r.channels,r},e.writeRtpMap=function(t){let n=t.payloadType;t.preferredPayloadType!==void 0&&(n=t.preferredPayloadType);let r=t.channels||t.numChannels||1;return"a=rtpmap:"+n+" "+t.name+"/"+t.clockRate+(r!==1?"/"+r:"")+`\r 43`},e.parseExtmap=function(t){let n=t.substring(9).split(" ");return{id:parseInt(n[0],10),direction:n[0].indexOf("/")>0?n[0].split("/")[1]:"sendrecv",uri:n[1],attributes:n.slice(2).join(" ")}},e.writeExtmap=function(t){return"a=extmap:"+(t.id||t.preferredId)+(t.direction&&t.direction!=="sendrecv"?"/"+t.direction:"")+" "+t.uri+(t.attributes?" "+t.attributes:"")+`\r 44`},e.parseFmtp=function(t){let n={},r,s=t.substring(t.indexOf(" ")+1).split(";");for(let o=0;o<s.length;o++)r=s[o].trim().split("="),n[r[0].trim()]=r[1];return n},e.writeFmtp=function(t){let n="",r=t.payloadType;if(t.preferredPayloadType!==void 0&&(r=t.preferredPayloadType),t.parameters&&Object.keys(t.parameters).length){let s=[];Object.keys(t.parameters).forEach(o=>{t.parameters[o]!==void 0?s.push(o+"="+t.parameters[o]):s.push(o)}),n+="a=fmtp:"+r+" "+s.join(";")+`\r 45`}return n},e.parseRtcpFb=function(t){let n=t.substring(t.indexOf(" ")+1).split(" ");return{type:n.shift(),parameter:n.join(" ")}},e.writeRtcpFb=function(t){let n="",r=t.payloadType;return t.preferredPayloadType!==void 0&&(r=t.preferredPayloadType),t.rtcpFeedback&&t.rtcpFeedback.length&&t.rtcpFeedback.forEach(s=>{n+="a=rtcp-fb:"+r+" "+s.type+(s.parameter&&s.parameter.length?" "+s.parameter:"")+`\r 46`}),n},e.parseSsrcMedia=function(t){let n=t.indexOf(" "),r={ssrc:parseInt(t.substring(7,n),10)},s=t.indexOf(":",n);return s>-1?(r.attribute=t.substring(n+1,s),r.value=t.substring(s+1)):r.attribute=t.substring(n+1),r},e.parseSsrcGroup=function(t){let n=t.substring(13).split(" ");return{semantics:n.shift(),ssrcs:n.map(r=>parseInt(r,10))}},e.getMid=function(t){let n=e.matchPrefix(t,"a=mid:")[0];if(n)return n.substring(6)},e.parseFingerprint=function(t){let n=t.substring(14).split(" ");return{algorithm:n[0].toLowerCase(),value:n[1].toUpperCase()}},e.getDtlsParameters=function(t,n){return{role:"auto",fingerprints:e.matchPrefix(t+n,"a=fingerprint:").map(e.parseFingerprint)}},e.writeDtlsParameters=function(t,n){let r="a=setup:"+n+`\r 47`;return t.fingerprints.forEach(s=>{r+="a=fingerprint:"+s.algorithm+" "+s.value+`\r 48`}),r},e.parseCryptoLine=function(t){let n=t.substring(9).split(" ");return{tag:parseInt(n[0],10),cryptoSuite:n[1],keyParams:n[2],sessionParams:n.slice(3)}},e.writeCryptoLine=function(t){return"a=crypto:"+t.tag+" "+t.cryptoSuite+" "+(typeof t.keyParams=="object"?e.writeCryptoKeyParams(t.keyParams):t.keyParams)+(t.sessionParams?" "+t.sessionParams.join(" "):"")+`\r 49`},e.parseCryptoKeyParams=function(t){if(t.indexOf("inline:")!==0)return null;let n=t.substring(7).split("|");return{keyMethod:"inline",keySalt:n[0],lifeTime:n[1],mkiValue:n[2]?n[2].split(":")[0]:void 0,mkiLength:n[2]?n[2].split(":")[1]:void 0}},e.writeCryptoKeyParams=function(t){return t.keyMethod+":"+t.keySalt+(t.lifeTime?"|"+t.lifeTime:"")+(t.mkiValue&&t.mkiLength?"|"+t.mkiValue+":"+t.mkiLength:"")},e.getCryptoParameters=function(t,n){return e.matchPrefix(t+n,"a=crypto:").map(e.parseCryptoLine)},e.getIceParameters=function(t,n){let r=e.matchPrefix(t+n,"a=ice-ufrag:")[0],s=e.matchPrefix(t+n,"a=ice-pwd:")[0];return r&&s?{usernameFragment:r.substring(12),password:s.substring(10)}:null},e.writeIceParameters=function(t){let n="a=ice-ufrag:"+t.usernameFragment+`\r 50a=ice-pwd:`+t.password+`\r 51`;return t.iceLite&&(n+=`a=ice-lite\r 52`),n},e.parseRtpParameters=function(t){let n={codecs:[],headerExtensions:[],fecMechanisms:[],rtcp:[]},s=e.splitLines(t)[0].split(" ");n.profile=s[2];for(let a=3;a<s.length;a++){let d=s[a],l=e.matchPrefix(t,"a=rtpmap:"+d+" ")[0];if(l){let f=e.parseRtpMap(l),p=e.matchPrefix(t,"a=fmtp:"+d+" ");switch(f.parameters=p.length?e.parseFmtp(p[0]):{},f.rtcpFeedback=e.matchPrefix(t,"a=rtcp-fb:"+d+" ").map(e.parseRtcpFb),n.codecs.push(f),f.name.toUpperCase()){case"RED":case"ULPFEC":n.fecMechanisms.push(f.name.toUpperCase());break}}}e.matchPrefix(t,"a=extmap:").forEach(a=>{n.headerExtensions.push(e.parseExtmap(a))});let o=e.matchPrefix(t,"a=rtcp-fb:* ").map(e.parseRtcpFb);return n.codecs.forEach(a=>{o.forEach(d=>{a.rtcpFeedback.find(f=>f.type===d.type&&f.parameter===d.parameter)||a.rtcpFeedback.push(d)})}),n},e.writeRtpDescription=function(t,n){let r="";r+="m="+t+" ",r+=n.codecs.length>0?"9":"0",r+=" "+(n.profile||"UDP/TLS/RTP/SAVPF")+" ",r+=n.codecs.map(o=>o.preferredPayloadType!==void 0?o.preferredPayloadType:o.payloadType).join(" ")+`\r 53`,r+=`c=IN IP4 0.0.0.0\r 54`,r+=`a=rtcp:9 IN IP4 0.0.0.0\r 55`,n.codecs.forEach(o=>{r+=e.writeRtpMap(o),r+=e.writeFmtp(o),r+=e.writeRtcpFb(o)});let s=0;return n.codecs.forEach(o=>{o.maxptime>s&&(s=o.maxptime)}),s>0&&(r+="a=maxptime:"+s+`\r 56`),n.headerExtensions&&n.headerExtensions.forEach(o=>{r+=e.writeExtmap(o)}),r},e.parseRtpEncodingParameters=function(t){let n=[],r=e.parseRtpParameters(t),s=r.fecMechanisms.indexOf("RED")!==-1,o=r.fecMechanisms.indexOf("ULPFEC")!==-1,a=e.matchPrefix(t,"a=ssrc:").map(g=>e.parseSsrcMedia(g)).filter(g=>g.attribute==="cname"),d=a.length>
560&&a[0].ssrc,l,f=e.matchPrefix(t,"a=ssrc-group:FID").map(g=>g.substring(17).split(" ").map(R=>parseInt(R,10)));f.length>0&&f[0].length>1&&f[0][0]===d&&(l=f[0][1]),r.codecs.forEach(g=>{if(g.name.toUpperCase()==="RTX"&&g.parameters.apt){let b={ssrc:d,codecPayloadType:parseInt(g.parameters.apt,10)};d&&l&&(b.rtx={ssrc:l}),n.push(b),s&&(b=JSON.parse(JSON.stringify(b)),b.fec={ssrc:d,mechanism:o?"red+ulpfec":"red"},n.push(b))}}),n.length===0&&d&&n.push({ssrc:d});let p=e.matchPrefix(t,"b=");return p.length&&(p[0].indexOf("b=TIAS:")===0?p=parseInt(p[0].substring(7),10):p[0].indexOf("b=AS:")===0?p=parseInt(p[0].substring(5),10)*1e3*.95-2e3*8:p=void 0,n.forEach(g=>{g.maxBitrate=p})),n},e.parseRtcpParameters=function(t){let n={},r=e.matchPrefix(t,"a=ssrc:").map(a=>e.parseSsrcMedia(a)).filter(a=>a.attribute==="cname")[0];r&&(n.cname=r.value,n.ssrc=r.ssrc);let s=e.matchPrefix(t,"a=rtcp-rsize");n.reducedSize=s.length>0,n.compound=s.length===0;let o=e.matchPrefix(t,"a=rtcp-mux");return n.mux=o.length>0,n},e.writeRtcpParameters=function(t){let n="";return t.reducedSize&&(n+=`a=rtcp-rsize\r 57`),t.mux&&(n+=`a=rtcp-mux\r 58`),t.ssrc!==void 0&&t.cname&&(n+="a=ssrc:"+t.ssrc+" cname:"+t.cname+`\r 59`),n},e.parseMsid=function(t){let n,r=e.matchPrefix(t,"a=msid:");if(r.length===1)return n=r[0].substring(7).split(" "),{stream:n[0],track:n[1]};let s=e.matchPrefix(t,"a=ssrc:").map(o=>e.parseSsrcMedia(o)).filter(o=>o.attribute==="msid");if(s.length>0)return n=s[0].value.split(" "),{stream:n[0],track:n[1]}},e.parseSctpDescription=function(t){let n=e.parseMLine(t),r=e.matchPrefix(t,"a=max-message-size:"),s;r.length>0&&(s=parseInt(r[0].substring(19),10)),isNaN(s)&&(s=65536);let o=e.matchPrefix(t,"a=sctp-port:");if(o.length>0)return{port:parseInt(o[0].substring(12),10),protocol:n.fmt,maxMessageSize:s};let a=e.matchPrefix(t,"a=sctpmap:");if(a.length>0){let d=a[0].substring(10).split(" ");return{port:parseInt(d[0],10),protocol:d[1],maxMessageSize:s}}},e.writeSctpDescription=function(t,n){let r=[];return t.protocol!=="DTLS/SCTP"?r=["m="+t.kind+" 9 "+t.protocol+" "+n.protocol+`\r 60`,`c=IN IP4 0.0.0.0\r 61`,"a=sctp-port:"+n.port+`\r 62`]:r=["m="+t.kind+" 9 "+t.protocol+" "+n.port+`\r 63`,`c=IN IP4 0.0.0.0\r 64`,"a=sctpmap:"+n.port+" "+n.protocol+` 65535\r 65`],n.maxMessageSize!==void 0&&r.push("a=max-message-size:"+n.maxMessageSize+`\r 66`),r.join("")},e.generateSessionId=function(){return Math.random().toString().substr(2,22)},e.writeSessionBoilerplate=function(t,n,r){let s,o=n!==void 0?n:2;return t?s=t:s=e.generateSessionId(),`v=0\r 67o=`+(r||"thisisadapterortc")+" "+s+" "+o+` IN IP4 127.0.0.1\r 68s=-\r 69t=0 0\r 70`},e.getDirection=function(t,n){let r=e.splitLines(t);for(let s=0;s<r.length;s++)switch(r[s]){case"a=sendrecv":case"a=sendonly":case"a=recvonly":case"a=inactive":return r[s].substring(2)}return n?e.getDirection(n):"sendrecv"},e.getKind=function(t){return e.splitLines(t)[0].split(" ")[0].substring(2)},e.isRejected=function(t){return t.split(" ",2)[1]==="0"},e.parseMLine=function(t){let r=e.splitLines(t)[0].substring(2).split(" ");return{kind:r[0],port:parseInt(r[1],10),protocol:r[2],fmt:r.slice(3).join(" ")}},e.parseOLine=function(t){let r=e.matchPrefix(t,"o=")[0].substring(2).split(" ");return{username:r[0],sessionId:r[1],sessionVersion:parseInt(r[2],10),netType:r[3],addressType:r[4],address:r[5]}},e.isValidSDP=function(t){if(typeof t!="string"||t.length===0)return!1;let n=e.splitLines(t);for(let r=0;r<n.length;r++)if(n[r].length<2||n[r].charAt(1)!=="=")return!1;return!0},i.exports=e})(gl)),gl.exports}var $y=uC(),yr=Q_($y),dC=a0({__proto__:null,default:yr},[$y]);function Do(i){if(!i.RTCIceCandidate||i.RTCIceCandidate&&"foundation"in i.RTCIceCandidate.prototype)return;let e=i.RTCIceCandidate;i.RTCIceCandidate=function(n){if(typeof n=="object"&&n.candidate&&n.candidate.indexOf("a=")===0&&(n=JSON.parse(JSON.stringify(n)),n.candidate=n.candidate.substring(2)),n.candidate&&n.candidate.length){let r=new e(n),s=yr.parseCandidate(n.candidate);for(let o in s)o in r||Object.defineProperty(r,o,{value:s[o]});return r.toJSON=function(){return{candidate:r.candidate,sdpMid:r.sdpMid,sdpMLineIndex:r.
vendor: 4,459 bytes, lines 70-73
70sdpMLineIndex,usernameFragment:r.usernameFragment}},r}return new e(n)},i.RTCIceCandidate.prototype=e.prototype,Ni(i,"icecandidate",t=>(t.candidate&&Object.defineProperty(t,"candidate",{value:new i.RTCIceCandidate(t.candidate),writable:"false"}),t))}function Zl(i){!i.RTCIceCandidate||i.RTCIceCandidate&&"relayProtocol"in i.RTCIceCandidate.prototype||Ni(i,"icecandidate",e=>{if(e.candidate){let t=yr.parseCandidate(e.candidate.candidate);t.type==="relay"&&(e.candidate.relayProtocol={0:"tls",1:"tcp",2:"udp"}[t.priority>>24])}return e})}function Lo(i,e){if(!i.RTCPeerConnection||e.browser==="chrome"&&e.version>102||e.browser==="firefox"&&e.version>=113)return;"sctp"in i.RTCPeerConnection.prototype||Object.defineProperty(i.RTCPeerConnection.prototype,"sctp",{get(){return typeof this._sctp>"u"?null:this._sctp}});let t=function(a){if(!a||!a.sdp)return!1;let d=yr.splitSections(a.sdp);return d.shift(),d.some(l=>{let f=yr.parseMLine(l);return f&&f.kind==="application"&&f.protocol.indexOf("SCTP")!==-1})},n=function(a){let d=a.sdp.match(/mozilla...THIS_IS_SDPARTA-(\d+)/);if(d===null||d.length<2)return-1;let l=parseInt(d[1],10);return l!==l?-1:l},r=function(a){let d=65536;return e.browser==="firefox"&&(e.version<57?a===-1?d=16384:d=2147483637:e.version<60?d=e.version===57?65535:65536:d=2147483637),d},s=function(a,d){let l=65536;e.browser==="firefox"&&e.version===57&&(l=65535);let f=yr.matchPrefix(a.sdp,"a=max-message-size:");return f.length>0?l=parseInt(f[0].substring(19),10):e.browser==="firefox"&&d!==-1&&(l=2147483637),l},o=i.RTCPeerConnection.prototype.setRemoteDescription;i.RTCPeerConnection.prototype.setRemoteDescription=function(){if(this._sctp=null,e.browser==="chrome"&&e.version>=76&&this.getConfiguration().sdpSemantics==="plan-b"&&Object.defineProperty(this,"sctp",{get(){return typeof this._sctp>"u"?null:this._sctp},enumerable:!0,configurable:!0}),t(arguments[0])){let d=n(arguments[0]),l=r(d),f=s(arguments[0],d),p;l===0&&f===0?p=Number.POSITIVE_INFINITY:l===0||f===0?p=Math.max(l,f):p=Math.min(l,f);let g={};Object.defineProperty(g,"maxMessageSize",{get(){return p}}),this._sctp=g}return o.apply(this,arguments)}}function xo(i,e){if(!(i.RTCPeerConnection&&"createDataChannel"in i.RTCPeerConnection.prototype)||e.browser==="chrome"&&e.version>=149||e.browser==="firefox"&&e.version>60)return;function t(r,s){let o=r.send;r.send=function(){let d=arguments[0],l=d.length||d.size||d.byteLength;if(r.readyState==="open"&&s.sctp&&l>s.sctp.maxMessageSize)throw new TypeError("Message too large (can send a maximum of "+s.sctp.maxMessageSize+" bytes)");return o.apply(r,arguments)}}let n=i.RTCPeerConnection.prototype.createDataChannel;i.RTCPeerConnection.prototype.createDataChannel=function(){let s=n.apply(this,arguments);return t(s,this),s},Ni(i,"datachannel",r=>(t(r.channel,r.target),r))}function eu(i){if(!i.RTCPeerConnection||"connectionState"in i.RTCPeerConnection.prototype)return;let e=i.RTCPeerConnection.prototype;Object.defineProperty(e,"connectionState",{get(){return{completed:"connected",checking:"connecting"}[this.iceConnectionState]||this.iceConnectionState},enumerable:!0,configurable:!0}),Object.defineProperty(e,"onconnectionstatechange",{get(){return this._onconnectionstatechange||null},set(t){this._onconnectionstatechange&&(this.removeEventListener("connectionstatechange",this._onconnectionstatechange),delete this._onconnectionstatechange),t&&this.addEventListener("connectionstatechange",this._onconnectionstatechange=t)},enumerable:!0,configurable:!0}),["setLocalDescription","setRemoteDescription"].forEach(t=>{let n=e[t];e[t]=function(){return this._connectionstatechangepoly||(this._connectionstatechangepoly=r=>{let s=r.target;if(s._lastConnectionState!==s.connectionState){s._lastConnectionState=s.connectionState;let o=new Event("connectionstatechange",r);s.dispatchEvent(o)}return r},this.addEventListener("iceconnectionstatechange",this._connectionstatechangepoly)),n.apply(this,arguments)}})}function tu(i,e){if(!i.RTCPeerConnection||e.browser==="chrome"&&e.version>=71||e.browser==="safari"&&e._safariVersion>=13.1)return;let t=i.RTCPeerConnection.prototype.setRemoteDescription;i.RTCPeerConnection.prototype.setRemoteDescription=function(r){if(r&&r.sdp&&r.sdp.indexOf(` 71a=extmap-allow-mixed`)!==-1){let s=r.sdp.split(` 72`).filter(o=>o.trim()!=="a=extmap-allow-mixed").join(` 73`);i.RTCSessionDescription&&r instanceof i.RTCSessionDescription?arguments[0]=new i.RTCSessionDescription({type:r.type,sdp:s}
73):r.sdp=s}return t.apply(this,arguments)}}function No(i,e){if(!(i.RTCPeerConnection&&i.RTCPeerConnection.prototype))return;let t=i.RTCPeerConnection.prototype.addIceCandidate;!t||t.length===0||(i.RTCPeerConnection.prototype.addIceCandidate=function(){return arguments[0]?(e.browser==="chrome"&&e.version<78||e.browser==="firefox"&&e.version<68||e.browser==="safari")&&arguments[0]&&arguments[0].candidate===""?Promise.resolve():t.apply(this,arguments):(arguments[1]&&arguments[1].apply(null),Promise.resolve())})}function Fo(i,e){if(!(i.RTCPeerConnection&&i.RTCPeerConnection.prototype))return;let t=i.RTCPeerConnection.prototype.setLocalDescription;!t||t.length===0||(i.RTCPeerConnection.prototype.setLocalDescription=function(){let r=arguments[0]||{};if(typeof r!="object"||r.type&&r.sdp)return t.apply(this,arguments);if(r={type:r.type,sdp:r.sdp},!r.type)switch(this.signalingState){case"stable":case"have-local-offer":case"have-remote-pranswer":r.type="offer";break;default:r.type="answer";break}return r.sdp||r.type!=="offer"&&r.type!=="answer"?t.apply(this,[r]):(r.type==="offer"?this.createOffer:this.createAnswer).apply(this).then(o=>t.apply(this,[o]))})}var hC=Object.freeze({__proto__:null,removeExtmapAllowMixed:tu,shimAddIceCandidateNullOrEmpty:No,shimConnectionState:eu,shimMaxMessageSize:Lo,shimParameterlessSetLocalDescription:Fo,shimRTCIceCandidate:Do,shimRTCIceCandidateRelayProtocol:Zl,shimSendThrowTypeError:xo});function pC(){let i=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{},e=i.window,t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{shimChrome:!0,shimFirefox:!0,shimSafari:!0},n=Id,r=cC(e),s={browserDetails:r,commonShim:hC,extractVersion:os,disableLog:oC,disableWarnings:aC,sdp:dC};switch(r.browser){case"chrome":if(!Tg||!Ql||!t.shimChrome)return n("Chrome shim is not included in this adapter release."),s;if(r.version===null)return n("Chrome shim can not determine version, not shimming."),s;n("adapter.js shimming chrome."),s.browserShim=Tg,No(e,r),Fo(e),my(e,r),gy(e),Ql(e,r),vy(e,r),Sy(e,r),yy(e),by(e,r),Ty(e,r),Do(e),Zl(e),eu(e),Lo(e,r),xo(e,r),tu(e,r);break;case"firefox":if(!_g||!Xl||!t.shimFirefox)return n("Firefox shim is not included in this adapter release."),s;n("adapter.js shimming firefox."),s.browserShim=_g,No(e,r),Fo(e),_y(e,r),Xl(e,r),wy(e,r),Cy(e),Ay(e),Ey(e),Py(e),My(e),Ry(e,r),Iy(e,r),Oy(e,r),Dy(e,r),Do(e),eu(e),Lo(e,r),xo(e,r);break;case"safari":if(!Cg||!t.shimSafari)return n("Safari shim is not included in this adapter release."),s;n("adapter.js shimming safari."),s.browserShim=Cg,No(e,r),Fo(e),jy(e),qy(e),Ny(e),Ly(e),xy(e),By(e),Fy(e),Vy(e),Do(e),Zl(e),Lo(e,r),xo(e,r),tu(e,r);break;default:n("Unsupported browser!");break}return s}pC({window:typeof window>"u"?void 0:window});var nu,Wy,lt=class extends(Wy=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)}};nu=lt;lt.resolve=i=>Reflect.get(Wy,"resolve",nu).call(nu,i);var fC=/version\/(\d+(\.?_?\d+)+)/i,vl;function bt(i){let e=arguments.length>1&&arguments[1]!==void 0?arguments[1]:!0;if(typeof i>"u"&&typeof navigator>"u")return;let t=(i??navigator.userAgent).toLowerCase();if(vl===void 0||e){let n=mC.find(r=>r.test.test(t));vl=n?.describe(t)}return vl}var mC=[{test:/firefox|iceweasel|fxios/i,describe(i){return{name:"Firefox",version:Uo(/(?:firefox|iceweasel|fxios)[\s/](\d+(\.?_?\d+)+)/i,i),os:i.toLowerCase().includes("fxios")?"iOS":void 0,osVersion:yl(i)}}},{test:/chrom|crios|crmo/i,describe(i){return{name:"Chrome",version:Uo(/(?:chrome|chromium|crios|crmo)\/(\d+(\.?_?\d+)+)/i,i),os:i.toLowerCase().includes("crios")?"iOS":void 0,osVersion:yl(i)}}},{test:/safari|applewebkit/i,describe(i){return{name:"Safari",version:Uo(fC,i),os:i.includes("mobile/")?"iOS":"macOS",osVersion:yl(i)}}}];function Uo(i,e){let t=arguments.length>2&&arguments[2]!==void 0?arguments[2]:1,n=e.match(i);return n&&n.length>=t&&n[t]||""}function yl(i){return i.includes("mac os")?Uo(/\(.+?(\d+_\d+(:?_\d+)?)/,i,1).replace(/_/g,"."):void 0}var gC="2.22.0",vC=gC,yC=17,Gy=0,iu=1,Jy=2,bC=Jy,Zt=class extends
73Error{constructor(e,t,n){super(t||"an error has occurred"),this.name="LiveKitError",this.code=e,typeof n?.cause<"u"&&(this.cause=n?.cause)}},Tt=class extends Zt{};var Ue;(function(i){i[i.NotAllowed=0]="NotAllowed",i[i.ServerUnreachable=1]="ServerUnreachable",i[i.InternalError=2]="InternalError",i[i.Cancelled=3]="Cancelled",i[i.LeaveRequest=4]="LeaveRequest",i[i.Timeout=5]="Timeout",i[i.WebSocket=6]="WebSocket",i[i.ServiceNotFound=7]="ServiceNotFound"})(Ue||(Ue={}));var ve=class i extends Tt{constructor(e,t,n,r){super(1,e),this.name="ConnectionError",this.status=n,this.reason=t,this.context=r,this.reasonName=Ue[t]}static notAllowed(e,t,n){return new i(e,Ue.NotAllowed,t,n)}static timeout(e){return new i(e,Ue.Timeout)}static leaveRequest(e,t){return new i(e,Ue.LeaveRequest,void 0,t)}static internal(e,t){return new i(e,Ue.InternalError,void 0,t)}static cancelled(e){return new i(e,Ue.Cancelled)}static serverUnreachable(e,t){return new i(e,Ue.ServerUnreachable,t)}static websocket(e,t,n){return new i(e,Ue.WebSocket,t,n)}static serviceNotFound(e,t){return new i(e,Ue.ServiceNotFound,void 0,t)}},ks=class extends Zt{constructor(e){super(21,e??"device is unsupported"),this.name="DeviceUnsupportedError"}},Yt=class extends Zt{constructor(e){super(20,e??"track is invalid"),this.name="TrackInvalidError"}},ru=class extends Zt{constructor(e){super(10,e||"unsupported server"),this.name="UnsupportedServer"}},Be=class extends Zt{constructor(e){super(12,e||"unexpected connection state"),this.name="UnexpectedConnectionState"}},hn=class extends Zt{constructor(e){super(13,e||"unable to negotiate"),this.name="NegotiationError"}},su=class extends Zt{constructor(e){super(14,e||"unable to publish data"),this.name="PublishDataError"}},Wo=class extends Zt{constructor(e,t){super(15,e),this.name="PublishTrackError",this.status=t}},Go=class extends Tt{constructor(e,t){super(15,e),this.name="SignalRequestError",this.reason=t,this.reasonName=typeof t=="string"?t:Ti[t]}},He;(function(i){i[i.AlreadyOpened=0]="AlreadyOpened",i[i.AbnormalEnd=1]="AbnormalEnd",i[i.DecodeFailed=2]="DecodeFailed",i[i.LengthExceeded=3]="LengthExceeded",i[i.Incomplete=4]="Incomplete",i[i.HandlerAlreadyRegistered=7]="HandlerAlreadyRegistered",i[i.EncryptionTypeMismatch=8]="EncryptionTypeMismatch",i[i.HeaderTooLarge=9]="HeaderTooLarge",i[i.PayloadTooLarge=10]="PayloadTooLarge"})(He||(He={}));var Ye=class extends Tt{constructor(e,t){super(16,e),this.name="DataStreamError",this.reason=t,this.reasonName=He[t]}},Hn=class extends Zt{constructor(e){super(18,e),this.name="SignalReconnectError"}},Jo;(function(i){i.PermissionDenied="PermissionDenied",i.NotFound="NotFound",i.DeviceInUse="DeviceInUse",i.Other="Other"})(Jo||(Jo={}));(function(i){function e(t){if(t&&"name"in t)return t.name==="NotFoundError"||t.name==="DevicesNotFoundError"?i.NotFound:t.name==="NotAllowedError"||t.name==="PermissionDeniedError"?i.PermissionDenied:t.name==="NotReadableError"||t.name==="TrackStartError"?i.DeviceInUse:i.Other}i.getFailure=e})(Jo||(Jo={}));var Le=class{};Le.setTimeout=function(){return setTimeout(...arguments)};Le.setInterval=function(){return setInterval(...arguments)};Le.clearTimeout=function(){return clearTimeout(...arguments)};Le.clearInterval=function(){return clearInterval(...arguments)};var H;(function(i){i.Connected="connected",i.Reconnecting="reconnecting",i.SignalReconnecting="signalReconnecting",i.Reconnected="reconnected",i.Disconnected="disconnected",i.ConnectionStateChanged="connectionStateChanged",i.Moved="moved",i.MediaDevicesChanged="mediaDevicesChanged",i.ParticipantConnected="participantConnected",i.ParticipantDisconnected="participantDisconnected",i.TrackPublished="trackPublished",i.TrackSubscribed="trackSubscribed",i.TrackSubscriptionFailed="trackSubscriptionFailed",i.TrackUnpublished="trackUnpublished",i.TrackUnsubscribed="trackUnsubscribed",i.TrackMuted="trackMuted",i.TrackUnmuted="trackUnmuted",i.LocalTrackPublished="localTrackPublished",i.LocalTrackUnpublished="localTrackUnpublished",i.LocalAudioSilenceDetected="localAudioSilenceDetected",i.ActiveSpeakersChanged="activeSpeakersChanged",i.ParticipantMetadataChanged="participantMetadataChanged",i.ParticipantNameChanged="participantNameChanged",i.ParticipantAttributesChanged="participantAttributesChanged",i.ParticipantActive="participantActive",i.RoomMetadataChanged="roomMetadataChanged",i.DataReceived="dataReceived",i.SipDTMFReceived="sipDTMFReceived",i.TranscriptionReceived="transcriptionReceived",i.ConnectionQualityChanged="connectionQualityChanged",i.TrackStreamStateChanged="trackStreamStateChanged",i.TrackSubscriptionPermissionChanged="trackSubscriptionPermissionChanged",i.TrackSubscriptionStatusChanged="trackSubscriptionStatusChanged",i.AudioPlaybackStatusChanged="audioPlaybackChanged",i.VideoPlaybackStatusChanged="videoPlaybackChanged",i.MediaDevicesError="mediaDevicesError",i.ParticipantPermissionsChanged="participantPermissionsChanged",i.SignalConnected="signalConnected",i.RecordingStatusChanged="recordingStatusChanged",i.ParticipantEncryptionStatusChanged="participantEncryptionStatusChanged",i.EncryptionError="encryptionError",i.DCBufferStatusChanged="dcBufferStatusChanged",i.ActiveDeviceChanged="activeDeviceChanged",i.ChatMessage="chatMessage",i.LocalTrackSubscribed="localTrackSubscribed",i.MetricsReceived="metricsReceived",i.DataTrackPublished="dataTrackPublished",i.DataTrackUnpublished="dataTrackUnpublished",i.LocalDataTrackPublished="localDataTrackPublished",i.LocalDataTrackUnpublished="localDataTrackUnpublished"})(H||(H={}));var ce;(function(i){i.TrackPublished="trackPublished",i.TrackSubscribed="trackSubscribed",i.TrackSubscriptionFailed="trackSubscriptionFailed",i.TrackUnpublished="trackUnpublished",i.TrackUnsubscribed="trackUnsubscribed",i.TrackMuted="trackMuted",i.TrackUnmuted="trackUnmuted",i.LocalTrackPublished="localTrackPublished",i.LocalTrackUnpublished="localTrackUnpublished",i.LocalTrackCpuConstrained="localTrackCpuConstrained",i.LocalSenderCreated="localSenderCreated",i.ParticipantMetadataChanged="participantMetadataChanged",i.ParticipantNameChanged="participantNameChanged",i.DataReceived="dataReceived",i.SipDTMFReceived="sipDTMFReceived",i.TranscriptionReceived="transcriptionReceived",i.IsSpeakingChanged="isSpeakingChanged",i.ConnectionQualityChanged="connectionQualityChanged",i.TrackStreamStateChanged="trackStreamStateChanged",i.TrackSubscriptionPermissionChanged="trackSubscriptionPermissionChanged",i.TrackSubscriptionStatusChanged="trackSubscriptionStatusChanged",i.TrackCpuConstrained="trackCpuConstrained",i.MediaDevicesError="mediaDevicesError",i.AudioStreamAcquired="audioStreamAcquired",i.ParticipantPermissionsChanged="participantPermissionsChanged",i.PCTrackAdded="pcTrackAdded",i.AttributesChanged="attributesChanged",i.LocalTrackSubscribed="localTrackSubscribed",i.ChatMessage="chatMessage",i.Active="active"})(ce||(ce={}));var X;(function(i){i.TransportsCreated="transportsCreated",i.Connected="connected",i.Disconnected="disconnected",i.Resuming="resuming",i.Resumed="resumed",i.Restarting="restarting",i.Restarted="restarted",i.SignalResumed="signalResumed",i.SignalRestarted="signalRestarted",i.Closing="closing",i.MediaTrackAdded="mediaTrackAdded",i.ActiveSpeakersUpdate="activeSpeakersUpdate",i.DataPacketReceived="dataPacketReceived",i.RTPVideoMapUpdate="rtpVideoMapUpdate",i.DCBufferStatusChanged="dcBufferStatusChanged",i.ParticipantUpdate="participantUpdate",i.RoomUpdate="roomUpdate",i.SpeakersChanged="speakersChanged",i.StreamStateChanged="streamStateChanged",i.ConnectionQualityUpdate="connectionQualityUpdate",i.SubscriptionError="subscriptionError",i.SubscriptionPermissionUpdate="subscriptionPermissionUpdate",i.RemoteMute="remoteMute",i.SubscribedQualityUpdate="subscribedQualityUpdate",i.LocalTrackUnpublished="localTrackUnpublished",i.LocalTrackSubscribed="localTrackSubscribed",i.Offline="offline",i.SignalRequestResponse="signalRequestResponse",i.SignalConnected="signalConnected",i.RoomMoved="roomMoved",i.PublishDataTrackResponse="publishDataTrackResponse",i.UnPublishDataTrackResponse="unPublishDataTrackResponse",i.DataTrackSubscriberHandles="dataTrackSubscriberHandles",i.DataTrackPacketReceived="dataTrackPacketReceived",i.Joined="joined",i.TokenRefreshed="tokenRefreshed",i.ServerRegionsReported="serverRegionsReported"})(X||(X={}));var re;(function(i){i.Message="message",i.Muted="muted",i.Unmuted="unmuted",i.Restarted="restarted",i.Ended="ended",i.Subscribed="subscribed",i.Unsubscribed="unsubscribed",i.CpuConstrained="cpuConstrained",i.UpdateSettings="updateSettings",i.UpdateSubscription="updateSubscription",i.AudioPlaybackStarted="audioPlaybackStarted",i.AudioPlaybackFailed="audioPlaybackFailed",i.AudioSilenceDetected="audioSilenceDetected",i.VisibilityChanged="visibilityChanged",i.VideoDimensionsChanged="videoDimensionsChanged",i.VideoPlaybackStarted="videoPlaybackStarted",i.VideoPlaybackFailed="videoPlaybackFailed",i.ElementAttached="elementAttached",i.ElementDetached="elementDetached",i.UpstreamPaused="upstreamPaused",i.UpstreamResumed="upstreamResumed",i.SubscriptionPermissionChanged="subscriptionPermissionChanged",i.SubscriptionStatusChanged="subscriptionStatusChanged",i.SubscriptionFailed="subscriptionFailed",i.TrackProcessorUpdate="trackProcessorUpdate",i.AudioTrackFeatureUpdate="audioTrackFeatureUpdate",i.TranscriptionReceived="transcriptionReceived",i.TimeSyncUpdate="timeSyncUpdate",i.PreConnectBufferFlushed="preConnectBufferFlushed"})(re||(re={}));function kC(i){return typeof i>"u"?i:typeof structuredClone=="function"?typeof i=="object"&&i!==null?structuredClone(Object.assign({},i)):structuredClone(i):JSON.parse(JSON.stringify(i))}
73var De=class{constructor(e,t,n,r,s){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:s};else throw new 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}}};var SC=["vp8","h264"],TC=["vp8","h264","vp9","av1","h265"];function Hy(i){return!!SC.find(e=>e===i)}var _C=Hy,Eg;(function(i){i[i.PREFER_REGRESSION=0]="PREFER_REGRESSION",i[i.SIMULCAST=1]="SIMULCAST",i[i.REGRESSION=2]="REGRESSION"})(Eg||(Eg={}));var ou;(function(i){i.telephone={maxBitrate:12e3},i.speech={maxBitrate:24e3},i.music={maxBitrate:48e3},i.musicStereo={maxBitrate:64e3},i.musicHighQuality={maxBitrate:96e3},i.musicHighQualityStereo={maxBitrate:128e3}})(ou||(ou={}));var Ss={h90:new De(160,90,9e4,20),h180:new De(320,180,16e4,20),h216:new De(384,216,18e4,20),h360:new De(640,360,45e4,20),h540:new De(960,540,8e5,25),h720:new De(1280,720,17e5,30),h1080:new De(1920,1080,3e6,30),h1440:new De(2560,1440,5e6,30),h2160:new De(3840,2160,8e6,30)},au={h120:new De(160,120,7e4,20),h180:new De(240,180,125e3,20),h240:new De(320,240,14e4,20),h360:new De(480,360,33e4,20),h480:new De(640,480,5e5,20),h540:new De(720,540,6e5,25),h720:new De(960,720,13e5,30),h1080:new De(1440,1080,23e5,30),h1440:new De(1920,1440,38e5,30)},Dd={h360fps3:new De(640,360,2e5,3,"medium"),h360fps15:new De(640,360,4e5,15,"medium"),h720fps5:new De(1280,720,8e5,5,"medium"),h720fps15:new De(1280,720,15e5,15,"medium"),h720fps30:new De(1280,720,2e6,30,"medium"),h1080fps15:new De(1920,1080,25e5,15,"medium"),h1080fps30:new De(1920,1080,5e6,30,"medium"),original:new De(0,0,7e6,30,"medium")};function Ky(i,e,t){var n,r,s,o;let a=Qy(i??{}),d=a.optionsWithoutProcessor,l=a.audioProcessor,f=a.videoProcessor,p=e?.processor,g=t?.processor,b=d??{};return b.audio===!0&&(b.audio={}),b.video===!0&&(b.video={}),b.audio&&(cu(b.audio,e),(n=(s=b.audio).deviceId)!==null&&n!==void 0||(s.deviceId={ideal:"default"}),(l||p)&&(b.audio.processor=l??p)),b.video&&(cu(b.video,t),(r=(o=b.video).deviceId)!==null&&r!==void 0||(o.deviceId={ideal:"default"}),(f||g)&&(b.video.processor=f??g)),b}function cu(i,e){return Object.keys(e).forEach(t=>{i[t]===void 0&&(i[t]=e[t])}),i}function Ld(i){var e,t,n,r;let s={};if(i.video)if(typeof i.video=="object"){let o={},a=o,d=i.video;Object.keys(d).forEach(l=>{l==="resolution"?cu(a,d.resolution):a[l]=d[l]}),s.video=o,(e=(n=s.video).deviceId)!==null&&e!==void 0||(n.deviceId={ideal:"default"})}else s.video=i.video?{deviceId:{ideal:"default"}}:!1;else s.video=!1;return i.audio?typeof i.audio=="object"?(s.audio=i.audio,(t=(r=s.audio).deviceId)!==null&&t!==void 0||(r.deviceId={ideal:"default"})):s.audio={deviceId:{ideal:"default"}}:s.audio=!1,s}function zy(i){return A(this,arguments,void 0,function(e){let t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:200;return(function*(){let n=Yy();if(n){let r=n.createAnalyser();r.fftSize=2048;let s=r.frequencyBinCount,o=new Uint8Array(s);n.createMediaStreamSource(new MediaStream([e.mediaStreamTrack])).connect(r),yield ft(t),r.getByteTimeDomainData(o);let d=o.some(l=>l!==128&&l!==0);return n.close(),!d}return!1})()})}function Yy(){var i;let e=typeof window<"u"&&(window.AudioContext||window.webkitAudioContext);if(e){let t=new e({latencyHint:"interactive"});if(t.state==="suspended"&&typeof window<"u"&&(!((i=window.document)===null||i===void 0)&&i.body)){let n=()=>A(this,void 0,void 0,function*(){var r;try{t.state==="suspended"&&(yield t.resume())}catch(s){console.warn("Error trying to auto-resume audio context",s)}finally{(r=window.document.body)===null||r===void 0||r.removeEventListener("click",n)}});t.addEventListener("statechange",()=>{var r;t.state==="closed"&&((r=window.document.body)===null||r===void 0||r.removeEventListener("click",n))}),window.document.body.addEventListener("click",n)}return t}}function CC(i){return i==="audioinput"?J.Source.Microphone:i==="videoinput"?J.Source.Camera:J.Source.Unknown}
73function lu(i){return i===J.Source.Microphone?"audioinput":i===J.Source.Camera?"videoinput":void 0}function wC(i){var e,t;let n=(e=i.video)!==null&&e!==void 0?e:!0;return i.resolution&&i.resolution.width>0&&i.resolution.height>0&&(n=typeof n=="boolean"?{}:n,Di()?n=Object.assign(Object.assign({},n),{width:{max:i.resolution.width},height:{max:i.resolution.height},frameRate:i.resolution.frameRate}):n=Object.assign(Object.assign({},n),{width:{ideal:i.resolution.width},height:{ideal:i.resolution.height},frameRate:i.resolution.frameRate})),{audio:(t=i.audio)!==null&&t!==void 0?t:!1,video:n,controller:i.controller,selfBrowserSurface:i.selfBrowserSurface,surfaceSwitching:i.surfaceSwitching,systemAudio:i.systemAudio,preferCurrentTab:i.preferCurrentTab}}function ls(i){return i.split("/")[1].toLowerCase()}function EC(i){let e=[];return i.forEach(t=>{t.track!==void 0&&e.push(new Ed({cid:t.track.mediaStreamID,track:t.trackInfo}))}),e}function _e(i){return"mediaStreamTrack"in i?{trackID:i.sid,source:i.source,muted:i.isMuted,enabled:i.mediaStreamTrack.enabled,kind:i.kind,streamID:i.mediaStreamID,streamTrackID:i.mediaStreamTrack.id}:{trackID:i.trackSid,enabled:i.isEnabled,muted:i.isMuted,trackInfo:Object.assign({mimeType:i.mimeType,name:i.trackName,encrypted:i.isEncrypted,kind:i.kind,source:i.source},i.track?_e(i.track):{})}}function PC(){return typeof RTCRtpReceiver<"u"&&typeof RTCRtpReceiver.prototype.getSynchronizationSources=="function"}function AC(i,e){var t;i===void 0&&(i={}),e===void 0&&(e={});let n=[...Object.keys(e),...Object.keys(i)],r={};for(let s of n)i[s]!==e[s]&&(r[s]=(t=e[s])!==null&&t!==void 0?t:"");return r}function Qy(i){let e=Object.assign({},i),t,n;return typeof e.audio=="object"&&e.audio.processor&&(t=e.audio.processor,e.audio=Object.assign(Object.assign({},e.audio),{processor:void 0})),typeof e.video=="object"&&e.video.processor&&(n=e.video.processor,e.video=Object.assign(Object.assign({},e.video),{processor:void 0})),{audioProcessor:t,videoProcessor:n,optionsWithoutProcessor:kC(e)}}function MC(i){switch(i){case et.CAMERA:return J.Source.Camera;case et.MICROPHONE:return J.Source.Microphone;case et.SCREEN_SHARE:return J.Source.ScreenShare;case et.SCREEN_SHARE_AUDIO:return J.Source.ScreenShareAudio;default:return J.Source.Unknown}}function Pg(i,e){return i.width*i.height<e.width*e.height}function RC(i,e){var t;return(t=i.layers)===null||t===void 0?void 0:t.find(n=>n.quality===e)}var IC=5e3,ns=[],At;(function(i){i[i.LOW=0]="LOW",i[i.MEDIUM=1]="MEDIUM",i[i.HIGH=2]="HIGH"})(At||(At={}));var J=class i extends _t.EventEmitter{get streamState(){return this._streamState}setStreamState(e){this._streamState!==e&&this.log.debug("stream state changed: ".concat(this._streamState," -> ").concat(e)),this._streamState=e}constructor(e,t){let n=arguments.length>2&&arguments[2]!==void 0?arguments[2]:{};var r;super(),this.attachedElements=[],this.isMuted=!1,this._streamState=i.StreamState.Active,this.isInBackground=!1,this._currentBitrate=0,this.log=ye,this.appVisibilityChangedListener=()=>{this.backgroundTimeout&&clearTimeout(this.backgroundTimeout),document.visibilityState==="hidden"?this.backgroundTimeout=setTimeout(()=>this.handleAppVisibilityChanged(),IC):this.handleAppVisibilityChanged()},this.loggerContextCb=n.loggerContextCb,this.log=ut((r=n.loggerName)!==null&&r!==void 0?r:Xe.Track,()=>this.logContext),this.setMaxListeners(100),this.kind=t,this._mediaStreamTrack=e,this._mediaStreamID=e.id,this.source=i.Source.Unknown}get logContext(){var e;return Object.assign(Object.assign({},(e=this.loggerContextCb)===null||e===void 0?void 0:e.call(this)),_e(this))}get currentBitrate(){return this._currentBitrate}get mediaStreamTrack(){return this._mediaStreamTrack}get mediaStreamID(){return this._mediaStreamID}attach(e){let t="audio";this.kind===i.Kind.Video&&(t="video"),this.attachedElements.length===0&&this.kind===i.Kind.Video&&this.addAppVisibilityListener(),e||(t==="audio"&&(ns.forEach(s=>{s.parentElement===null&&!e&&(e=s)}),e&&ns.splice(ns.indexOf(e),1)),e||(e=document.createElement(t))),this.attachedElements.includes(e)||this.attachedElements.push(e),mr(this.mediaStreamTrack,e);let n=e.srcObject.getTracks(),r=n.some(s=>s.kind==="audio");return e.play().then(()=>
73{this.emit(r?re.AudioPlaybackStarted:re.VideoPlaybackStarted)}).catch(s=>{s.name==="NotAllowedError"?this.emit(r?re.AudioPlaybackFailed:re.VideoPlaybackFailed,s):s.name==="AbortError"?this.log.debug("".concat(r?"audio":"video"," playback aborted, likely due to new play request")):this.log.warn("could not playback ".concat(r?"audio":"video"),{error:s}),r&&e&&n.some(o=>o.kind==="video")&&s.name==="NotAllowedError"&&(e.muted=!0,e.play().catch(()=>{}))}),this.emit(re.ElementAttached,e),e}detach(e){try{if(e){br(this.mediaStreamTrack,e);let n=this.attachedElements.indexOf(e);return n>=0&&(this.attachedElements.splice(n,1),this.recycleElement(e),this.emit(re.ElementDetached,e)),e}let t=[];return this.attachedElements.forEach(n=>{br(this.mediaStreamTrack,n),t.push(n),this.recycleElement(n),this.emit(re.ElementDetached,n)}),this.attachedElements=[],t}finally{this.attachedElements.length===0&&this.removeAppVisibilityListener()}}stop(){this.log.debug("stopping track"),this.stopMonitor(),this._mediaStreamTrack.stop()}enable(){this._mediaStreamTrack.enabled=!0}disable(){this._mediaStreamTrack.enabled=!1}stopMonitor(){this.monitorInterval&&clearInterval(this.monitorInterval),this.timeSyncHandle!==void 0&&(cancelAnimationFrame(this.timeSyncHandle),this.timeSyncHandle=void 0)}updateLoggerOptions(e){e.loggerContextCb&&(this.loggerContextCb=e.loggerContextCb),e.loggerName&&(this.log=ut(e.loggerName,()=>this.logContext))}recycleElement(e){if(e instanceof HTMLAudioElement){let t=!0;e.pause(),ns.forEach(n=>{n.parentElement||(t=!1)}),t&&ns.push(e)}}handleAppVisibilityChanged(){return A(this,void 0,void 0,function*(){this.isInBackground=document.visibilityState==="hidden",!this.isInBackground&&this.kind===i.Kind.Video&&setTimeout(()=>this.attachedElements.forEach(e=>e.play().catch(()=>{})),0)})}addAppVisibilityListener(){St()?(this.isInBackground=document.visibilityState==="hidden",document.addEventListener("visibilitychange",this.appVisibilityChangedListener)):this.isInBackground=!1}removeAppVisibilityListener(){St()&&document.removeEventListener("visibilitychange",this.appVisibilityChangedListener)}};function mr(i,e){let t;e.srcObject instanceof MediaStream?t=e.srcObject:t=new MediaStream;let n;i.kind==="audio"?n=t.getAudioTracks():n=t.getVideoTracks(),n.includes(i)||(n.forEach(r=>{t.removeTrack(r)}),t.addTrack(i)),(!Di()||!(e instanceof HTMLVideoElement))&&(e.autoplay=!0),e.muted=t.getAudioTracks().length===0,e instanceof HTMLVideoElement&&(e.playsInline=!0),e.srcObject!==t&&(e.srcObject=t,(Di()||Oi())&&e instanceof HTMLVideoElement&&setTimeout(()=>{e.srcObject=t,e.play().catch(()=>{})},0))}function br(i,e){if(e.srcObject instanceof MediaStream){let t=e.srcObject;t.removeTrack(i),t.getTracks().length>0?e.srcObject=t:e.srcObject=null}}(function(i){let e;(function(l){l.Audio="audio",l.Video="video",l.Unknown="unknown"})(e=i.Kind||(i.Kind={}));let t;(function(l){l.Camera="camera",l.Microphone="microphone",l.ScreenShare="screen_share",l.ScreenShareAudio="screen_share_audio",l.Unknown="unknown"})(t=i.Source||(i.Source={}));let n;(function(l){l.Active="active",l.Paused="paused",l.Unknown="unknown"})(n=i.StreamState||(i.StreamState={}));function r(l){switch(l){case e.Audio:return Kt.AUDIO;case e.Video:return Kt.VIDEO;default:return Kt.DATA}}i.kindToProto=r;function s(l){switch(l){case Kt.AUDIO:return e.Audio;case Kt.VIDEO:return e.Video;default:return e.Unknown}}i.kindFromProto=s;function o(l){switch(l){case t.Camera:return et.CAMERA;case t.Microphone:return et.MICROPHONE;case t.ScreenShare:return et.SCREEN_SHARE;case t.ScreenShareAudio:return et.SCREEN_SHARE_AUDIO;default:return et.UNKNOWN}}i.sourceToProto=o;function a(l){switch(l){case et.CAMERA:return t.Camera;case et.MICROPHONE:return t.Microphone;case et.SCREEN_SHARE:return t.ScreenShare;case et.SCREEN_SHARE_AUDIO:return t.ScreenShareAudio;default:return t.Unknown}}i.sourceFromProto=a;function d(l){switch(l){case Gl.ACTIVE:return n.Active;case Gl.PAUSED:return n.Paused;default:return n.Unknown}}i.streamStateFromProto=d})(J||(J={}));var OC="|",kr="https://aomediacodec.github.io/av1-rtp-spec/#dependency-descriptor-rtp-header-extension";function Xy(i){let e=i.split(OC);return e.length>1?[e[0],i.substr(e[0].length+1)]:[i,""]}function ft(i){return new lt(e=>
73Le.setTimeout(e,i))}function uu(){return"addTransceiver"in RTCPeerConnection.prototype}function du(){return"addTrack"in RTCPeerConnection.prototype}function DC(){if(!("getCapabilities"in RTCRtpSender)||Di()||Oi())return!1;let i=RTCRtpSender.getCapabilities("video"),e=!1;if(i){for(let t of i.codecs)if(t.mimeType.toLowerCase()==="video/av1"){e=!0;break}}return e}function LC(){if(!("getCapabilities"in RTCRtpSender)||Oi())return!1;if(Di()){let t=bt();if(t?.version&&fn(t.version,"16")<0||t?.os==="iOS"&&t?.osVersion&&fn(t.osVersion,"16")<0)return!1}let i=RTCRtpSender.getCapabilities("video"),e=!1;if(i){for(let t of i.codecs)if(t.mimeType.toLowerCase()==="video/vp9"){e=!0;break}}return e}function un(i){return i==="av1"||i==="vp9"}function xC(i){var e;let t=(e=i.getHeaderExtensionsToNegotiate)===null||e===void 0?void 0:e.call(i);if(!t||!i.setHeaderExtensionsToNegotiate)return!1;let n=t.find(r=>r.uri===kr);if(!n)return!1;if(n.direction!=="stopped")return!0;n.direction="sendrecv";try{return i.setHeaderExtensionsToNegotiate(t),!0}catch{return!1}}function hu(i){return!document||Ts()?!1:(i||(i=document.createElement("audio")),"setSinkId"in i)}function NC(){return typeof RTCPeerConnection>"u"?!1:uu()||du()}function Oi(){var i;return((i=bt())===null||i===void 0?void 0:i.name)==="Firefox"}function FC(){let i=bt();return!!i&&i.name==="Chrome"&&i.os!=="iOS"}function pu(){return typeof window<"u"&&typeof window.RTCRtpScriptTransform<"u"&&!FC()}function Di(){var i;return((i=bt())===null||i===void 0?void 0:i.name)==="Safari"}function Ts(){let i=bt();return i?.name==="Safari"||i?.os==="iOS"}function UC(){let i=bt();return i?.name==="Safari"&&i.version.startsWith("17.")||i?.os==="iOS"&&!!i?.osVersion&&fn(i.osVersion,"17")>=0}function jC(i){return i||(i=bt()),i?.name==="Safari"&&fn(i.version,"18.3")>0||i?.os==="iOS"&&!!i?.osVersion&&fn(i.osVersion,"18.3")>0}function Zy(){var i,e;return St()?(e=(i=navigator.userAgentData)===null||i===void 0?void 0:i.mobile)!==null&&e!==void 0?e:/Tablet|iPad|Mobile|Android|BlackBerry/.test(navigator.userAgent):!1}function BC(){let i=bt(),e="17.2";if(i)return i.name!=="Safari"&&i.os!=="iOS"||i.os==="iOS"&&i.osVersion&&fn(i.osVersion,e)>=0?!0:i.name==="Safari"&&fn(i.version,e)>=0}function St(){return typeof document<"u"}function en(){return navigator.product=="ReactNative"}function Pr(i){return i.hostname.endsWith(".livekit.cloud")||i.hostname.endsWith(".livekit.run")}function bl(i){return Pr(i)?i.hostname.split(".")[0]:null}function eb(){if(global&&global.LiveKitReactNativeGlobal)return global.LiveKitReactNativeGlobal}function tb(){if(!en())return;let i=eb();if(i)return i.platform}function Ag(){if(St())return window.devicePixelRatio;if(en()){let i=eb();if(i)return i.devicePixelRatio}return 1}function fn(i,e){let t=i.split("."),n=e.split("."),r=Math.min(t.length,n.length);for(let s=0;s<r;++s){let o=parseInt(t[s],10),a=parseInt(n[s],10);if(o>a)return 1;if(o<a)return-1;if(s===r-1&&o===a)return 0}return i===""&&e!==""?-1:e===""?1:t.length==n.length?0:t.length<n.length?-1:1}function qC(i){for(let e of i)e.target.handleResize(e)}function VC(i){for(let e of i)e.target.handleVisibilityChanged(e)}var kl=null,Mg=()=>(kl||(kl=new ResizeObserver(qC)),kl),Sl=null,Rg=()=>(Sl||(Sl=new IntersectionObserver(VC,{root:null,rootMargin:"0px"})),Sl);function $C(i){var e;let t=new Hv({capabilities:i,sdk:Kv.JS,protocol:yC,clientProtocol:bC,version:vC});return en()&&(t.os=(e=tb())!==null&&e!==void 0?e:""),t}function Ig(){let i=arguments.length>0&&arguments[0]!==void 0?arguments[0]:16,e=arguments.length>1&&arguments[1]!==void 0?arguments[1]:16,t=arguments.length>2&&arguments[2]!==void 0?arguments[2]:!1,n=arguments.length>3&&arguments[3]!==void 0?arguments[3]:!1,r=document.createElement("canvas");r.width=i,r.height=e;let s=r.getContext("2d");s?.fillRect(0,0,r.width,r.height),n&&s&&(s.beginPath(),s.arc(i/2,e/2,50,0,Math.PI*2,!0),s.closePath(),s.fillStyle="grey",s.fill());let a=r.captureStream().getTracks(),d=pe(a,1),l=d[0];if(!l)throw Error("Could not get empty media stream video track");return l.enabled=t,l}var is;function Tl(){if(!is){let t=new AudioContext,n=t.createOscillator(),r=t.createGain();r.gain.setValueAtTime(0,0);let s=t.createMediaStreamDestination();n.connect(r),r.connect(s),n.start();var i=s.stream.getAudioTracks(),e=pe(i,1);if(is=e[0],!is)throw Error("Could not get empty media stream audio track");is.enabled=!1}return is.clone()}var nt=class{get isResolved(){return this._isResolved}constructor(e,t){this._isResolved=!1,this.onFinally=t,this.promise=new Promise((n,r)=>A(this,void 0,void 0,function*(){this.resolve=n,this.reject=r,e&&(yield e(n,r))})).finally(()=>{var n;this._isResolved=!0,(n=this.onFinally)===null||n===void 0||n.call(this)})}};function nb(i){return TC.includes(i)}function Sr(i){if(typeof i=="string"||typeof i=="number")return i;if(Array.isArray(i))return i[0];if(i.exact!==void 0)return Array.isArray(i.exact)?i.exact[0]:i.exact;if(i.ideal!==void 0)return Array.isArray(i.ideal)?i.ideal[0]:i.ideal;throw Error("could not unwrap constraint")}function WC(i){return i.startsWith("http")?i.replace(/^(http)/,"ws"):i}function _s(i){return i.startsWith("ws")?i.replace(/^(ws)/,"http"):i}function GC(i,e){return i.segments.map(t=>{let n=t.id,r=t.text,s=t.language,o=t.startTime,a=t.endTime,d=t.final;var l;let f=(l=e.get(n))!==null&&l!==void 0?l:Date.now(),p=Date.now();return d?e.delete(n):e.set(n,f),{id:n,text:r,startTime:Number.parseInt(o.toString()),endTime:Number.parseInt(a.toString()),final:d,language:s,firstReceivedTime:f,lastReceivedTime:p}})}function JC(i){let e=i.id,t=i.timestamp,n=i.message,r=i.editTimestamp;return{id:e,timestamp:Number.parseInt(t.toString()),editTimestamp:r?Number.parseInt(r.toString()):void 0,message:n}}function Og(i){switch(i.reason){case Ue.LeaveRequest:return i.context;case Ue.Cancelled:return Qt.CLIENT_INITIATED;case Ue.NotAllowed:return Qt.USER_REJECTED;case Ue.ServerUnreachable:return Qt.JOIN_FAILURE;default:return Qt.UNKNOWN_REASON}}function _i(i){return i!==void 0?Number(i):void 0}function Xt(i){return i!==void 0?BigInt(i):void 0}function Tr(i){return!!i&&!(i instanceof MediaStreamTrack)&&i.isLocal}function pn(i){return!!i&&i.kind==J.Kind.Audio}function Fn(i){return!!i&&i.kind==J.Kind.Video}function an(i){return Tr(i)&&Fn(i)}function Rn(i){return Tr(i)&&pn(i)}function fu(i){return!!i&&!i.isLocal}function HC(i){return!!i&&!i.isLocal}function _l(i){return fu(i)&&Fn(i)}function KC(i){return i.isLocal}function zC(i,e){let t=[],n=new TextEncoder().encode(i);for(;n.length>e;){let r=e;for(;r>0;){let s=n[r];if(s!==void 0&&(s&192)!==128)break;r--}t.push(n.slice(0,r)),n=n.slice(r)}return n.length>0&&t.push(n),t}function jo(i){return new ReadableStream({start(e){e.enqueue(i),e.close()}})}function YC(i,e){return dy(this,arguments,function*(){let n=i.getReader(),r
73=new Uint8Array(0);try{for(;;){let s=yield xn(n.read()),o=s.done,a=s.value;if(o)break;if(a.byteLength===0)continue;let d=new Uint8Array(r.byteLength+a.byteLength);for(d.set(r),d.set(a,r.byteLength),r=d;r.byteLength>=e;)yield yield xn(r.slice(0,e)),r=r.slice(e)}r.byteLength>0&&(yield yield xn(r))}finally{n.releaseLock()}})}function QC(i){var e;let t=i.get("Cache-Control");if(t){let n=(e=t.match(/(?:^|[,\s])max-age=(\d+)/))===null||e===void 0?void 0:e[1];if(n)return parseInt(n,10)}}function Zn(){return typeof CompressionStream<"u"}function XC(){return Zn()&&!Oi()}function Dg(i,e){let t=Xy(e.id),n=pe(t,2),r=n[1];if(r?.startsWith("TR"))return r;if(i.id.startsWith("TR"))return i.id}function ZC(i,e){let t=arguments.length>2&&arguments[2]!==void 0?arguments[2]:!1,n=ew(i,e);return t?n:xd(n,"v1")}function ew(i,e){let t=new URL(WC(i));return e.forEach((n,r)=>{t.searchParams.set(r,n)}),xd(t,"rtc")}function tw(i){let e=new URL(_s(i));return xd(e,"validate")}function ib(i){return i.endsWith("/")?i:"".concat(i,"/")}function xd(i,e){return i.pathname="".concat(ib(i.pathname)).concat(e),i}function Lg(i){if(typeof i=="string")return mg.fromJson(JSON.parse(i),{ignoreUnknownFields:!0});if(i instanceof ArrayBuffer)return mg.fromBinary(new Uint8Array(i));throw new Error("could not decode websocket message: ".concat(typeof i))}function nw(i){let e=arguments.length>1&&arguments[1]!==void 0?arguments[1]:"Unknown reason";if(!(i instanceof AbortSignal))return e;let t=i.reason;switch(typeof t){case"string":return t;case"object":return t instanceof Error?t.message:e;default:return"toString"in t?t.toString():e}}var iw=10,rs="lk_e2ee",rw="LKFrameEncryptionKey",sw={sharedKey:!1,ratchetSalt:rw,ratchetWindowSize:8,failureTolerance:iw,keyringSize:16,keySize:128},ei;(function(i){i.SetKey="setKey",i.RatchetRequest="ratchetRequest",i.KeyRatcheted="keyRatcheted"})(ei||(ei={}));var xg;(function(i){i.KeyRatcheted="keyRatcheted"})(xg||(xg={}));var zn;(function(i){i.ParticipantEncryptionStatusChanged="participantEncryptionStatusChanged",i.EncryptionError="encryptionError"})(zn||(zn={}));var Ng;(function(i){i.Error="cryptorError"})(Ng||(Ng={}));function ow(){return Nd()||aw()}function aw(){return typeof window<"u"&&typeof window.RTCRtpScriptTransform<"u"}function Nd(){return typeof window<"u"&&typeof window.RTCRtpSender<"u"&&typeof window.RTCRtpSender.prototype.createEncodedStreams<"u"}function cw(i){var e,t,n,r,s;if(((e=i.value)===null||e===void 0?void 0:e.case)!=="sipDtmf"&&((t=i.value)===null||t===void 0?void 0:t.case)!=="metrics"&&((n=i.value)===null||n===void 0?void 0:n.case)!=="speaker"&&((r=i.value)===null||r===void 0?void 0:r.case)!=="transcription"&&((s=i.value)===null||s===void 0?void 0:s.case)!=="encryptedPacket")return new Bv({value:i.value})}var Fg=class extends _t.EventEmitter{constructor(){let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};super(),this.latestManuallySetKeyIndex=0,this.onKeyRatcheted=(t,n,r)=>{ye.debug("key ratcheted event received",{ratchetResult:t,participantId:n,keyIndex:r})},this.keyInfoMap=new Map,this.options=Object.assign(Object.assign({},sw),e),this.on(ei.KeyRatcheted,this.onKeyRatcheted)}onSetEncryptionKey(e,t,n){let r={key:e,participantIdentity:t,keyIndex:n};if(!this.options.sharedKey&&!t)throw new Error("participant identity needs to be passed for encryption key if sharedKey option is false");this.keyInfoMap.set("".concat(t??"shared","-").concat(n??0),r),n!==void 0&&(this.latestManuallySetKeyIndex=n),this.emit(ei.SetKey,r,n!==void 0)}getKeys(){return Array.from(this.keyInfoMap.values())}getLatestManuallySetKeyIndex(){return this.latestManuallySetKeyIndex}getOptions(){return this.options}ratchetKey(e,t){this.emit(ei.RatchetRequest,e,t)}};var Ug;(function(i){i[i.InvalidKey=0]="InvalidKey",i[i.MissingKey=1]="MissingKey",i[i.InternalError=2]="InternalError"})(Ug||(Ug={}));function Cs(){return pu()}function ws(i){return!!i?.worker&&(Nd()||Cs())}function Ho(i){return!!(i?.timestamp||i?.frameId)}function lw(i){let e=[];return i?.timestamp&&e.push(Er.PTF_USER_TIMESTAMP),i?.frameId&&e.push(Er.PTF_FRAME_ID),e}function uw(i){if(!i||i.length===0)return;let e={};return i.includes(Er.PTF_USER_TIMESTAMP)&&(e.timestamp=!0),i.includes(Er.PTF_FRAME_ID)&&(e.frameId=!0),e.timestamp||e.frameId?e:void 0}function Fd(i){let e=arguments.length>1&&arguments[1]!==void 0?arguments[1]:50,t=arguments.length>2&&arguments[2]!==void 0?arguments[2]:{};var n,r;let s,o=(n=t.isImmediate)!==null&&n!==void 0?n:!1,a=(r=t.callback)!==null&&r!==void 0?r:!1,d=t.maxWait,l=Date.now(),f=[];function p(){if(d!==void 0){let b=Date.now()-l;if(b+e>=d)return d-b}return e}let g=function(){for(var b=arguments.length,R=new Array(b),w=0;w<b;w++)R[w]=arguments[w];let I=this;return new Promise((N,L)=>{let j=function(){if(s=void 0,l=Date.now(),!o){let P=i.apply(I,R);a&&a(P),f.forEach(B=>{let q=B.resolve;return q(P)}),f=[]}},M=o&&s===void 0;if(s!==void 0&&Le.clearTimeout(s),s=Le.setTimeout(j,p()),M){let P=i.apply(I,R);return a&&a(P),N(P)}f.push({resolve:N,reject:L})})};return g.cancel=function(b){s!==void 0&&Le.clearTimeout(s),f.forEach(R=>{let w=R.reject;return w(b)}),f=[]},g}var Ud=2e3;function Da(i,e){if(!e)return 0;let t,n;return"bytesReceived"in i?(t=i.bytesReceived,n=e.bytesReceived):"bytesSent"in i&&(t=i.bytesSent,n=e.bytesSent),t===void 0||n===void 0||i.timestamp===void 0||e.timestamp===void 0?0:(t-n)*8*1e3/(i.timestamp-e.timestamp)}
73var Ko=class extends J{constructor(e,t,n,r,s){super(e,n,s),this.timeSyncLoop=()=>{var o;if(this.listenerCount(re.TimeSyncUpdate)===0){this.timeSyncHandle=void 0;return}this.timeSyncHandle=requestAnimationFrame(this.timeSyncLoop);let a=(o=this.receiver)===null||o===void 0?void 0:o.getSynchronizationSources()[0];if(a){let d=a.timestamp,l=a.rtpTimestamp;l&&this.rtpTimestamp!==l&&(this.emit(re.TimeSyncUpdate,{timestamp:d,rtpTimestamp:l}),this.rtpTimestamp=l)}},this.onTimeSyncListenerAdded=o=>{o===re.TimeSyncUpdate&&this.timeSyncHandle===void 0&&(this.timeSyncHandle=requestAnimationFrame(this.timeSyncLoop))},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?re.Muted:re.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(re.Ended,this))};e.addEventListener("removetrack",t)}start(){this.startMonitor(),super.enable()}stop(){this.stopMonitor(),super.disable()}getRTCStatsReport(){return A(this,void 0,void 0,function*(){var e;return!((e=this.receiver)===null||e===void 0)&&e.getStats?yield this.receiver.getStats():void 0})}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||(this.monitorInterval=setInterval(()=>this.monitorReceiver(),Ud)),PC()&&this.registerTimeSyncUpdate()}stopMonitor(){super.stopMonitor(),this.off("newListener",this.onTimeSyncListenerAdded)}registerTimeSyncUpdate(){let e=this;e.off("newListener",this.onTimeSyncListenerAdded),e.on("newListener",this.onTimeSyncListenerAdded),this.timeSyncHandle===void 0&&this.timeSyncLoop()}},Cl=100,Es=class extends Ko{constructor(e,t,n,r,s){super(e,t,J.Kind.Video,n,s),this.elementInfos=[],this.monitorReceiver=()=>A(this,void 0,void 0,function*(){if(!this.receiver){this._currentBitrate=0;return}let o=yield this.getReceiverStats();o&&this.prevStats&&this.receiver&&(this._currentBitrate=Da(o,this.prevStats)),this.prevStats=o}),this.debouncedHandleResize=Fd(()=>{this.updateDimensions()},Cl),this.adaptiveStreamSettings=r}get isAdaptiveStream(){return this.adaptiveStreamSettings!==void 0}lookupFrameMetadata(e){let t=e.rtpTimestamp;var n;return(n=this.frameMetadataExtractor)===null||n===void 0?void 0:n.lookupMetadata(t)}setStreamState(e){super.setStreamState(e),this.log.debug("setStreamState",e),this.isAdaptiveStream&&e===J.StreamState.Active&&this.updateVisibility()}get mediaStreamTrack(){return this._mediaStreamTrack}setMuted(e){super.setMuted(e),this.attachedElements.forEach(t=>{e?br(this._mediaStreamTrack,t):mr(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 mu(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(n=>n===e);for(let n of t)n.stopObserving();this.elementInfos=this.elementInfos.filter(n=>n!==e),this.updateVisibility(),this.debouncedHandleResize()}detach(e){if(e)return this.stopObservingElement(e),super.detach(e);let t=super.detach();for(let n of t)this.stopObservingElement(n);return t}getDecoderImplementation(){var e;return(e=this.prevStats)===null||e===void 0?void 0:e.decoderImplementation}getReceiverStats(){return A(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(s=>{s.type==="inbound-rtp"?(n=s.codecId,t={type:"video",streamId:s.id,framesDecoded:s.framesDecoded,framesDropped:s.framesDropped,framesReceived:s.framesReceived,packetsReceived:s.packetsReceived,packetsLost:s.packetsLost,frameWidth:s.frameWidth,frameHeight:s.frameHeight,pliCount:s.pliCount,firCount:s.firCount,nackCount:s.nackCount,jitter:s.jitter,timestamp:s.timestamp,bytesReceived:s.bytesReceived,decoderImplementation:s.decoderImplementation}):s.type==="codec"&&r.set(s.id,s)}),t&&n!==""&&r.get(n)&&(t.mimeType=r.get(n).mimeType),t})}stopObservingElement(e){let t=this.elementInfos.filter(n=>n.element===e);for(let n of t)this.stopObservingElementInfo(n)}handleAppVisibilityChanged(){let e=Object.create(null,{handleAppVisibilityChanged:{get:()=>super.handleAppVisibilityChanged}});return A(this,void 0,void 0,function*(){yield e.handleAppVisibilityChanged.call(this),this.isAdaptiveStream&&this.updateVisibility()})}updateVisibility(e){var t,n;let r=this.elementInfos.reduce((d,l)=>Math.max(d,l.visibilityChangedAt||0),0),s=!((n=(t=this.adaptiveStreamSettings)===null||t===void 0?void 0:t.pauseVideoInBackgroun
73d)!==null&&n!==void 0)||n?this.isInBackground:!1,o=this.elementInfos.some(d=>d.pictureInPicture),a=this.elementInfos.some(d=>d.visible)&&!s||o;if(!(this.lastVisible===a&&!e)){if(!a&&Date.now()-r<Cl){Le.setTimeout(()=>{this.updateVisibility()},Cl);return}this.lastVisible=a,this.emit(re.VisibilityChanged,a,this)}}updateDimensions(){var e,t;let n=0,r=0,s=this.getPixelDensity();for(let o of this.elementInfos){let a=o.width()*s,d=o.height()*s;a+d>n+r&&(n=a,r=d)}((e=this.lastDimensions)===null||e===void 0?void 0:e.width)===n&&((t=this.lastDimensions)===null||t===void 0?void 0:t.height)===r||(this.lastDimensions={width:n,height:r},this.emit(re.VideoDimensionsChanged,this.lastDimensions,this))}getPixelDensity(){var e;let t=(e=this.adaptiveStreamSettings)===null||e===void 0?void 0:e.pixelDensity;return t==="screen"?Ag():t||(Ag()>2?2:1)}},mu=class{get visible(){return this.isPiP||this.isIntersecting}get pictureInPicture(){return this.isPiP}constructor(e,t){this.onVisibilityChanged=n=>{var r;let s=n.target,o=n.isIntersecting;s===this.element&&(this.isIntersecting=o,this.isPiP=ss(this.element),this.visibilityChangedAt=Date.now(),(r=this.handleVisibilityChanged)===null||r===void 0||r.call(this))},this.onEnterPiP=()=>{var n,r;(r=(n=window.documentPictureInPicture)===null||n===void 0?void 0:n.window)===null||r===void 0||r.addEventListener("pagehide",this.onLeavePiP),queueMicrotask(()=>{requestAnimationFrame(()=>{var s;this.isPiP=ss(this.element),(s=this.handleVisibilityChanged)===null||s===void 0||s.call(this)})})},this.onLeavePiP=()=>{var n;this.isPiP=ss(this.element),(n=this.handleVisibilityChanged)===null||n===void 0||n.call(this)},this.element=e,this.isIntersecting=t??gu(e),this.isPiP=St()&&ss(e),this.visibilityChangedAt=0}width(){return this.element.clientWidth}height(){return this.element.clientHeight}observe(){var e,t,n;this.isIntersecting=gu(this.element),this.isPiP=ss(this.element),this.element.handleResize=()=>{var r;(r=this.handleResize)===null||r===void 0||r.call(this)},this.element.handleVisibilityChanged=this.onVisibilityChanged,Rg().observe(this.element),Mg().observe(this.element),this.element.addEventListener("enterpictureinpicture",this.onEnterPiP),this.element.addEventListener("leavepictureinpicture",this.onLeavePiP),(e=window.documentPictureInPicture)===null||e===void 0||e.addEventListener("enter",this.onEnterPiP),(n=(t=window.documentPictureInPicture)===null||t===void 0?void 0:t.window)===null||n===void 0||n.addEventListener("pagehide",this.onLeavePiP)}stopObserving(){var e,t,n,r,s;(e=Rg())===null||e===void 0||e.unobserve(this.element),(t=Mg())===null||t===void 0||t.unobserve(this.element),this.element.removeEventListener("enterpictureinpicture",this.onEnterPiP),this.element.removeEventListener("leavepictureinpicture",this.onLeavePiP),(n=window.documentPictureInPicture)===null||n===void 0||n.removeEventListener("enter",this.onEnterPiP),(s=(r=window.documentPictureInPicture)===null||r===void 0?void 0:r.window)===null||s===void 0||s.removeEventListener("pagehide",this.onLeavePiP)}};function ss(i){var e,t;return document.pictureInPictureElement===i?!0:!((e=window.documentPictureInPicture)===null||e===void 0)&&e.window?gu(i,(t=window.documentPictureInPicture)===null||t===void 0?void 0:t.window):!1}function gu(i,e){let t=e||window,n=i.offsetTop,r=i.offsetLeft,s=i.offsetWidth,o=i.offsetHeight,a=i,d=a.hidden,l=getComputedStyle(i),f=l.display;for(;i.offsetParent;)i=i.offsetParent,n+=i.offsetTop,r+=i.offsetLeft;return n<t.pageYOffset+t.innerHeight&&r<t.pageXOffset+t.innerWidth&&n+o>t.pageYOffset&&r+s>t.pageXOffset&&!d&&f!=="none"}var vu=class extends _t.EventEmitter{constructor(e,t){super(),this.decryptDataRequests=new Map,this.encryptDataRequests=new Map,this.onWorkerMessage=n=>{var r,s;let o=n.data,a=o.kind,d=o.data;switch(a){case"error":if(ye.error(d.error.message),d.uuid){let p=this.decryptDataRequests.get(d.uuid);if(p?.reject){p.reject(d.error);break}let g=this.encryptDataRequests.get(d.uuid);if(g?.reject){g.reject(d.error);break}}this.emit(zn.EncryptionError,d.error,d.participantIdentity);break;
73case"initAck":d.enabled&&this.keyProvider.getKeys().forEach(p=>{this.postKey(p,!1)});break;case"enable":if(d.enabled&&this.keyProvider.getKeys().forEach(p=>{this.postKey(p,!1)}),this.encryptionEnabled!==d.enabled&&d.participantIdentity===((r=this.room)===null||r===void 0?void 0:r.localParticipant.identity))this.emit(zn.ParticipantEncryptionStatusChanged,d.enabled,this.room.localParticipant),this.encryptionEnabled=d.enabled;else if(d.participantIdentity){let p=(s=this.room)===null||s===void 0?void 0:s.getParticipantByIdentity(d.participantIdentity);if(!p)throw TypeError("couldn't set encryption status, participant not found".concat(d.participantIdentity));this.emit(zn.ParticipantEncryptionStatusChanged,d.enabled,p)}break;case"ratchetKey":this.keyProvider.emit(ei.KeyRatcheted,d.ratchetResult,d.participantIdentity,d.keyIndex);break;case"decryptDataResponse":let l=this.decryptDataRequests.get(d.uuid);l?.resolve&&l.resolve(d);break;case"encryptDataResponse":let f=this.encryptDataRequests.get(d.uuid);f?.resolve&&f.resolve(d);break;case"packetTrailerMetadata":this.handleFrameMetadata(d.trackId,d.rtpTimestamp,d.ssrc,d.metadata);break}},this.onWorkerError=n=>{ye.error("e2ee worker encountered an error:",{error:n.error}),this.emit(zn.EncryptionError,n.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}
vendor: 1,260 bytes, line 73
73setup(e){if(!ow())throw new ks("tried to setup end-to-end encryption on an unsupported browser");if(ye.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:tC.getLevel()}};this.worker&&(ye.info("initializing worker",{worker:this.worker}),this.worker.onmessage=this.onWorkerMessage,this.worker.onerror=this.onWorkerError,this.worker.postMessage(t))}}setParticipantCryptorEnabled(e,t){ye.debug("set e2ee to ".concat(e," for participant ").concat(t)),this.postEnable(e,t)}setSifTrailer(e){!e||e.length===0?ye.warn("ignoring server sent trailer as it's empty"):this.postSifTrailer(e)}handleFrameMetadata(e,t,n,r){if(this.room){for(let s of[this.room.localParticipant,...this.room.remoteParticipants.values()])for(let o of s.trackPublications.values())if(o.track&&o.track.mediaStreamID===e&&o.track instanceof Es&&o.track.frameMetadataExtractor){o.track.frameMetadataExtractor.storeMetadata(t,n,r);return}}}setupEngine(e){e.on(X.RTPVideoMapUpdate,t=>{this.postRTPMap(t)})}setupEventListeners(e,t){e.on(H.TrackPublished,(n,r)=>this.setParticipantCryptorEnabled(n.trackInfo.encryption!==Ie.NONE,r.identity)),e.on(H.ConnectionStateChanged,n=>
73{n===Re.Connected&&e.remoteParticipants.forEach(r=>{r.trackPublications.forEach(s=>{this.setParticipantCryptorEnabled(s.trackInfo.encryption!==Ie.NONE,r.identity)})})}).on(H.TrackUnsubscribed,(n,r,s)=>{var o;let a={kind:"removeTransform",data:{participantIdentity:s.identity,trackId:n.mediaStreamID}};(o=this.worker)===null||o===void 0||o.postMessage(a)}).on(H.TrackSubscribed,(n,r,s)=>{this.setupE2EEReceiver(n,s.identity,r.trackInfo)}).on(H.SignalConnected,()=>{if(!this.room)throw new TypeError("expected room to be present on signal connect");let n=t.getLatestManuallySetKeyIndex();t.getKeys().forEach(r=>{var s;this.postKey(r,n===((s=r.keyIndex)!==null&&s!==void 0?s:0))}),this.setParticipantCryptorEnabled(this.room.localParticipant.isE2EEEnabled,this.room.localParticipant.identity)}),e.localParticipant.on(ce.LocalSenderCreated,(n,r)=>A(this,void 0,void 0,function*(){this.setupE2EESender(r,n)})),e.localParticipant.on(ce.LocalTrackPublished,n=>{if(!Fn(n.track)||!Ts())return;let r={kind:"updateCodec",data:{trackId:n.track.mediaStreamID,codec:ls(n.trackInfo.codecs[0].mimeType),participantIdentity:this.room.localParticipant.identity,hasPacketTrailer:!1}};this.worker.postMessage(r)}),t.on(ei.SetKey,(n,r)=>this.postKey(n,r??!0)).on(ei.RatchetRequest,(n,r)=>this.postRatchetRequest(n,r))}encryptData(e){return A(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 nt;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 s=crypto.randomUUID(),o={kind:"decryptDataRequest",data:{uuid:s,payload:e,iv:t,participantIdentity:n,keyIndex:r}},a=new nt;return a.onFinally=()=>{this.decryptDataRequests.delete(s)},this.decryptDataRequests.set(s,a),this.worker.postMessage(o),a.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 n=e.key,r=e.participantIdentity,s=e.keyIndex;var o;if(!this.worker)throw Error("could not set key, worker is missing");let a={kind:"setKey",data:{participantIdentity:r,isPublisher:r===((o=this.room)===null||o===void 0?void 0:o.localParticipant.identity),key:n,keyIndex:s,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 new ReferenceError("failed to enable e2ee, worker is not ready")}postRTPMap(e){var t;if(!this.worker)throw TypeError("could not post rtp map, worker is missing");if(!(!((t=this.room)===null||t===void 0)&&t.localParticipant.identity))throw TypeError("could not post rtp map, local participant identity is missing");let n={kind:"setRTPMap",data:{map:e,participantIdentity:this.room.localParticipant.identity}};this.worker.postMessage(n)}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)return;if(!n?.mimeType||n.mimeType==="")throw new TypeError("MimeType missing from trackInfo, cannot set up E2EE cryptor");let r=e.kind==="video"&&!!n.packetTrailerFeatures&&n.packetTrailerFeatures.length>0;this.handleReceiver(e.receiver,e.mediaStreamID,t,e.kind==="video"?ls(n.mimeType):void 0,r)}setupE2EESender(e,t){var n,r,s;if(!Tr(e)||!t){t||ye.warn("early return because sender is not ready");return}this.handleSender(t,e.mediaStreamID,void 0,Fn(e)?(r=(n=e.publishOptions)===null||n===void 0?void 0:n.frameMetadata)!==null&&r!==void 0?r:(s=e.publishOptions)===null||s===void 0?void 0:s.packetTrailer:void 0)}handleReceiver(e,t,n,r,s){return A(this,void 0,void 0,function*(){if(this.worker){if(pu()){let o={kind:"decode",participantIdentity:n,trackId:t,codec:r,hasPacketTrailer:s};e.transform=new RTCRtpScriptTransform(this.worker,o)}else{if(rs in e&&r){let l={kind:"updateCodec",data:{trackId:t,codec:r,participantIdentity:n,hasPacketTrailer:s}};this.worker.postMessage(l);return}let o=e.writableStream,a=e.readableStream;if(!o||!a){let l=e.createEncodedStreams();e.writableStream=l.writable,o=l.writable,e.readableStream=l.readable,a=l.readable}let d={kind:"decode",data:{readableStream:a,writableStream:o,trackId:t,codec:r,participantIdentity:n,isReuse:rs in e,hasPacketTrailer:s}};this.worker.postMessage(d,[a,o])}e[rs]=!0}})}handleSender(e,t,n,r){var s;if(!(rs in e||!this.worker)){if(!(!((s=this.room)===null||s===void 0)&&s.localParticipant.identity)||this.room.localParticipant.identity==="")throw TypeError("local identity needs to be known in order to set up encrypted sender");if(pu()){ye.info("initialize script transform");let o={kind:"encode",participantIdentity:this.room.localParticipant.identity,trackId:t,codec:n,hasPacketTrailer:Ho(r),packetTrailer:r};e.transform=new RTCRtpScriptTransform(this.worker,o)}else{ye.info("initialize encoded streams");let o=e.createEncodedStreams(),a={kind:"encode",data:{readableStream:o.readable,writableStream:o.writable,codec:n,trackId:t,participantIdentity:this.room.localParticipant.identity,isReuse:!1,hasPacketTrailer:Ho(r),packetTrailer:r}};
73this.worker.postMessage(a,[o.readable,o.writable])}e[rs]=!0}}},dw=300,yu=class{constructor(){this.metadataMap=new Map,this.activeSsrc=0}storeMetadata(e,t,n){for(this.activeSsrc!==0&&this.activeSsrc!==t&&this.metadataMap.clear(),this.activeSsrc=t;this.metadataMap.size>=dw;){let r=this.metadataMap.keys().next().value;this.metadataMap.delete(r)}this.metadataMap.set(e,n)}lookupMetadata(e){return this.metadataMap.get(e)}dispose(){this.metadataMap.clear(),this.activeSsrc=0}},bu=class{constructor(e){this.extractors=new Map,this.workerPipelines=new Map,this.onWorkerMessage=t=>{let n=t.data;if(n.kind==="metadata"){let r=this.extractors.get(n.data.trackId);r&&r.storeMetadata(n.data.rtpTimestamp,n.data.ssrc,n.data.metadata)}},this.onWorkerError=t=>{ye.error("frame metadata worker encountered an error:",{error:t.error})},this.worker=e?.worker}setup(e){e!==this.room&&(this.room=e,this.worker&&(this.worker.onmessage=this.onWorkerMessage,this.worker.onerror=this.onWorkerError,this.worker.postMessage({kind:"init"})),e.on(H.TrackSubscribed,(t,n,r)=>{t.kind==="video"&&this.setupReceiver(t,n.trackInfo)}).on(H.TrackUnsubscribed,t=>{this.teardownTrack(t)}).on(H.Disconnected,()=>{this.cleanup()}))}setupReceiver(e,t){var n,r,s;let o=e.receiver;if(!o)return;if(!(!!t?.packetTrailerFeatures&&t.packetTrailerFeatures.length>0)){!((n=this.room)===null||n===void 0)&&n.hasE2EESetup||this.setupPassthroughReceiver(o,e.mediaStreamID);return}if(!ws(this.worker?{worker:this.worker}:void 0)&&!(!((r=this.room)===null||r===void 0)&&r.hasE2EESetup)){ye.warn("frame metadata transform not supported; skipping extraction");return}let d=new yu,l=e.mediaStreamID;this.extractors.set(l,d),e.frameMetadataExtractor=d,!(!((s=this.room)===null||s===void 0)&&s.hasE2EESetup)&&this.setupWorkerReceiver(o,l,!0)}setupPassthroughReceiver(e,t){if(Cs()){"transform"in e&&(e.transform=null);return}if(this.worker&&ws({worker:this.worker})&&!this.workerPipelines.has(e)){this.setupWorkerReceiver(e,t,!1);return}this.worker&&this.workerPipelines.has(e)&&this.setupWorkerReceiver(e,t,!1)}setupWorkerReceiver(e,t){let n=arguments.length>2&&arguments[2]!==void 0?arguments[2]:!0,r=this.worker;if(!r)return;if(Cs()){e.transform=new RTCRtpScriptTransform(r,{kind:"decode",trackId:t});return}let s=this.workerPipelines.get(e);if(s){let d={kind:"updateTrackId",data:{oldTrackId:s,newTrackId:t,hasPacketTrailer:n}};r.postMessage(d),this.workerPipelines.set(e,t);return}if(!("createEncodedStreams"in e)){ye.warn("createEncodedStreams not supported");return}let o;try{o=e.createEncodedStreams()}catch(d){ye.warn("failed to create encoded streams",{error:d});return}let a={kind:"decode",data:{readableStream:o.readable,writableStream:o.writable,trackId:t,hasPacketTrailer:n}};r.postMessage(a,[o.readable,o.writable]),this.workerPipelines.set(e,t)}teardownTrack(e){let t=e.mediaStreamID,n=this.extractors.get(t);n&&(n.dispose(),this.extractors.delete(t)),e instanceof Es&&(e.frameMetadataExtractor=void 0)}cleanup(){var e;for(let t of this.extractors.values())t.dispose();this.extractors.clear(),this.workerPipelines.clear(),(e=this.worker)===null||e===void 0||e.terminate()}};var hw=500,pw=15e3,_r=class i{constructor(){this.failedConnectionAttempts=new Map,this.backOffPromises=new Map}static getInstance(){return this._instance||(this._instance=new i),this._instance}addFailedConnectionAttempt(e){var t;let n=new URL(e),r=bl(n);if(!r)return;let s=(t=this.failedConnectionAttempts.get(r))!==null&&t!==void 0?t:0;this.failedConnectionAttempts.set(r,s+1),this.backOffPromises.set(r,ft(Math.min(hw*Math.pow(2,s),pw)))}getBackOffPromise(e){let t=new URL(e),n=t&&bl(t);return n&&this.backOffPromises.get(n)||Promise.resolve()}resetFailedConnectionAttempts(e){let t=new URL(e),n=t&&bl(t);n&&(this.failedConnectionAttempts.set(n,0),this.backOffPromises.set(n,Promise.resolve()))}resetAll(){this.backOffPromises.clear(),this.failedConnectionAttempts.clear()}};_r._instance=null;var wl="default",Mt=class i{constructor(){this._previousDevices=[]}static getInstance(){return this.instance===void 0&&(this.instance=new i),this.instance}get previousDevices(){return this._previousDevices}getDevices(e){return A(this,arguments,void 0,function(t){var n=this;let r=arguments.length>1&&arguments[1]!==void 0?arguments[1]:!0;return(function*(){var s;if(((s=i.userMediaPromiseMap)===null||s===void 0?void 0:s.size)>0){ye.debug("awaiting getUserMedia promise");try{t?yield i.userMediaPromiseMap.get(t):yield Promise.all(i.userMediaPromiseMap.values())}catch{ye.warn("error waiting for media permissons")}}let o=yield navigator.mediaDevices.enumerateDevices();if(r&&!(Di()&&n.hasDeviceInUse(t))&&(o.filter(d=>d.kind===t).length===0||o.some(d=>{let l=d.label==="",f=t?d.kind===t:!0;return l&&f}))){let d={video:t!=="audioinput"&&t!=="audiooutput",audio:t!=="videoinput"&&{deviceId:{ideal:"default"}}},l=yield navigator.mediaDevices.getUserMedia(d);o=yield navigator.mediaDevices.enumerateDevices(),l.getTracks().forEac
vendor: 4,391 bytes, line 73
73h(f=>{f.stop()})}return n._previousDevices=o,t&&(o=o.filter(a=>a.kind===t)),o})()})}normalizeDeviceId(e,t,n){return A(this,void 0,void 0,function*(){if(t!==wl)return t;let r=yield this.getDevices(e),s=r.find(a=>a.deviceId===wl);if(!s){ye.warn("could not reliably determine default device");return}let o=r.find(a=>a.deviceId!==wl&&a.groupId===(n??s.groupId));if(!o){ye.warn("could not reliably determine default device");return}return o?.deviceId})}hasDeviceInUse(e){return e?i.userMediaPromiseMap.has(e):i.userMediaPromiseMap.size>0}};Mt.mediaDeviceKinds=["audioinput","audiooutput","videoinput"];Mt.userMediaPromiseMap=new Map;var jd=65535,rb=4294967295,ti=class i{static u16(e){return new i(e,jd)}static u32(e){return new i(e,rb)}constructor(e,t){if(this.value=e,e<0)throw new Error("WrapAroundUnsignedInt: cannot faithfully represent an integer smaller than 0");if(t>Number.MAX_SAFE_INTEGER)throw new 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 i(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 e=this.value;return this.increment(),new i(e,this.maxSize)}isBefore(e){let t=this.value>>>0,r=(e.value>>>0)-t>>>0;return r!==0&&r<this.maxSize+1}},zo=class i{static fromRtpTicks(e){return new i(e,9e4)}static rtpRandom(){let e=Math.round(Math.random()*rb);return i.fromRtpTicks(e)}constructor(e,t){this.timestamp=ti.u32(e),this.rateInHz=t}asTicks(){return this.timestamp.value}clone(){return new i(this.timestamp.value,this.rateInHz)}wrappingAdd(e){this.timestamp.increment(e)}isBefore(e){return this.timestamp.isBefore(e.timestamp)}},ku=class i{constructor(e,t,n){this.epoch=t,this.base=n,this.previous=n.clone(),this.rateInHz=e}static startingNow(e,t){return new i(t,new Date,e)}static startingAtTime(e,t,n){return new i(n,e,t)}static rtpStartingNow(e){return i.startingNow(e,9e4)}static rtpStartingAtTime(e,t){return i.startingAtTime(e,t,9e4)}now(){return this.at(new Date)}at(e){let t=e.getTime()-this.epoch.getTime(),n=i.durationInMsToTicks(t,this.rateInHz),r=this.base.clone();return r.wrappingAdd(n),r.isBefore(this.previous)&&(r=this.previous),this.previous=r.clone(),r.clone()}static durationInMsToTicks(e,t){let r=(e*1e6*t+5e8)/1e9;return Math.round(r)}};function Bd(i){if(i instanceof DataView)return i;if(i instanceof ArrayBuffer)return new DataView(i);if(i instanceof Uint8Array)return new DataView(i.buffer,i.byteOffset,i.byteLength);throw new Error("Error coercing ".concat(i," to DataView - input was not DataView, ArrayBuffer, or Uint8Array."))}var Ri;(function(i){i[i.Reserved=0]="Reserved",i[i.TooLarge=1]="TooLarge"})(Ri||(Ri={}));var Ps=class i extends Tt{constructor(e,t){super(19,e),this.name="DataTrackHandleError",this.reason=t,this.reasonName=Ri[t]}isReason(e){return this.reason===e}static tooLarge(){return new i("Value too large to be a valid track handle",Ri.TooLarge)}static reserved(e){return new i("0x".concat(e.toString(16)," is a reserved value."),Ri.Reserved)}},fw={fromNumber(i){if(i===0)throw Ps.reserved(i);if(i>jd)throw Ps.tooLarge();return i}},Su=class{constructor(){this.value=0}get(){return this.value+=1,this.value>jd?null:this.value}reset(){this.value=0}},Yo={from(i){return{sid:i.sid,pubHandle:i.pubHandle,name:i.name,usesE2ee:i.encryption!==Ie.NONE}},toProtobuf(i){return new wa({sid:i.sid,pubHandle:i.pubHandle,name:i.name,encryption:i.usesE2ee?Ie.GCM:Ie.NONE})}},us;(function(i){i[i.WAITING=0]="WAITING",i[i.RUNNING=1]="RUNNING",i[i.COMPLETED=2]="COMPLETED"})(us||(us={}));var Tu=class{constructor(){this.pendingTasks=new Map,this.taskMutex=new tt,this.nextTaskIndex=0}run(e){return A(this,void 0,void 0,function*(){let t={id:this.nextTaskIndex++,enqueuedAt:Date.now(),status:us.WAITING};this.pendingTasks.set(t.id,t);let n=yield this.taskMutex.lock();try{return t.executedAt=Date.now(),t.status=us.RUNNING,yield e()}finally{t.status=us.COMPLETED,this.pendingTasks.delete(t.id),n()}})}flush(){return A(this,void 0,void 0,function*(){return this.run(()=>A(this,void 0,void 0,function*(){}))})}
73snapshot(){return Array.from(this.pendingTasks.values())}},_u=class{get readyState(){return this.ws.readyState}constructor(e){let t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{};var n,r;if(!((n=t.signal)===null||n===void 0)&&n.aborted)throw new DOMException("This operation was aborted","AbortError");this.url=e;let s=new WebSocket(e,(r=t.protocols)!==null&&r!==void 0?r:[]);s.binaryType="arraybuffer",this.ws=s;let o=function(){let a=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{},d=a.closeCode,l=a.reason;return s.close(d,l)};this.opened=new lt((a,d)=>{let l=()=>{d(ve.websocket("Encountered websocket error during connection establishment"))};s.onopen=()=>{a({readable:new ReadableStream({start(f){s.onmessage=p=>{let g=p.data;return f.enqueue(g)},s.onerror=p=>f.error(p)},cancel:o}),writable:new WritableStream({write(f){s.send(f)},abort(){s.close()},close:o}),protocol:s.protocol,extensions:s.extensions}),s.removeEventListener("error",l)},s.addEventListener("error",l)}),this.closed=new lt((a,d)=>{let l=()=>A(this,void 0,void 0,function*(){let f=new lt(g=>{s.readyState!==WebSocket.CLOSED&&s.addEventListener("close",b=>{g(b)},{once:!0})}),p=yield lt.race([ft(250),f]);p?a(p):d(ve.websocket("Encountered unspecified websocket error without a timely close event"))});s.onclose=f=>{let p=f.code,g=f.reason;a({closeCode:p,reason:g}),s.removeEventListener("error",l)},s.addEventListener("error",l)}),t.signal&&(t.signal.onabort=()=>s.close()),this.close=o}},mw=["syncState","trickle","offer","answer","simulate","leave"];function gw(i){let e=mw.indexOf(i.case)>=0;return ye.trace("request allowed to bypass queue:",{canPass:e,req:i}),e}var Fe;(function(i){i[i.CONNECTING=0]="CONNECTING",i[i.CONNECTED=1]="CONNECTED",i[i.RECONNECTING=2]="RECONNECTING",i[i.DISCONNECTING=3]="DISCONNECTING",i[i.DISCONNECTED=4]="DISCONNECTED"})(Fe||(Fe={}));var vw=250,yw=5e3,As=class{get currentState(){return this.state}get isDisconnected(){return this.state===Fe.DISCONNECTING||this.state===Fe.DISCONNECTED}get isEstablishingConnection(){return this.state===Fe.CONNECTING||this.state===Fe.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]:{};var n;this.rtt=0,this.state=Fe.DISCONNECTED,this.log=ye,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.loggerContextCb=t.loggerContextCb,this.log=ut((n=t.loggerName)!==null&&n!==void 0?n:Xe.Signal,()=>this.logContext),this.useJSON=e,this.requestQueue=new Tu,this.queuedRequests=[],this.closingLock=new tt,this.connectionLock=new tt,this.state=Fe.DISCONNECTED}get logContext(){var e,t;return(t=(e=this.loggerContextCb)===null||e===void 0?void 0:e.call(this))!==null&&t!==void 0?t:{}}join(e,t,n,r){return A(this,arguments,void 0,function(s,o,a,d){var l=this;let f=arguments.length>4&&arguments[4]!==void 0?arguments[4]:!1,p=arguments.length>5?arguments[5]:void 0;return(function*(){return l.state=Fe.CONNECTING,l.options=a,yield l.connect(s,o,a,d,f,p)})()})}reconnect(e,t,n,r){return A(this,void 0,void 0,function*(){if(!this.options){this.log.warn("attempted to reconnect without signal options being set, ignoring");return}return this.state=Fe.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 A(this,arguments,void 0,function(s,o,a,d){var l=this;let f=arguments.length>4&&arguments[4]!==void 0?arguments[4]:!1,p=arguments.length>5?arguments[5]:void 0;return(function*(){let g=yield l.connectionLock.lock();l.connectOptions=a,l.useV0SignalPath=f;let b=$C(a.clientInfoCapabilities),R=f?bw(o,b,a):yield kw(o,b,a,p),w=ZC(s,R,f).toString(),I=tw(w).toString();return new Promise((N,L)=>A(l,void 0,void 0,function*(){var j,M;try{let P=!1,B=ae=>A(this,void 0,void 0,function*(){if(P)return;P=!0;let ge=ae instanceof Event?ae.currentTarget:ae,ke=nw(ge,"Abort handler called");this.streamWriter&&!this.isDisconnected?this.sendLeave().then(()=>this.close(ke)).catch(Oe=>{this.log.error(Oe),this.close()}):this.close(),q(),L(ve.cancelled(ke))});d?.addEventListener("abort",B);let q=()=>{clearTimeout(K),d?.removeEventListener("abort",B)},K=setTimeout(()=>{B(ve.timeout("room connection has timed out (signal)"))},a.websocketTimeout),ie=(ae,ge)=>{this.handleSignalConnected(ae,K,ge)},te=new URL(w);if(te.searchParams.has("access_token")&&te.searchParams.set("access_token","<redacted>"),this.ws){let ae=performance.now();yield this.close(!1),this.log.debug("closed previous ws connection in ".concat(performance.now()-ae,"ms"))}this.log.info("signal connecting to ".concat(te),{reconnect:a.reconnect,reconnectReason:a.reconnectReason}),this.ws=new _u(w);try{this.ws.closed.then(je=>{this.isEstablishingConnection&&L(ve.internal("Websocket got closed during a (re)connection attempt: ".concat(je.reason))),je.closeCode!==1e3&&(this.log.warn("websocket closed",{reason:je.reason,code:je.closeCode,wasClean:je.closeCode===1e3,state:this.state}),this.state===Fe.CONNECTED&&this.handleOnClose(je.reason||"Unexpected WS error"))}).catch(je=>{this.isEstablishingConnection&&L(ve.internal("Websocket error during a (re)connection attempt: ".concat(je)))});
73let ae=yield this.ws.opened.catch(je=>A(this,void 0,void 0,function*(){if(this.state!==Fe.CONNECTED){this.state=Fe.DISCONNECTED,clearTimeout(K);let gt=yield this.handleConnectionError(je,I);L(gt);return}this.handleWSError(je),L(je)}));if(clearTimeout(K),!ae)return;let ge=ae.readable.getReader();this.streamWriter=ae.writable.getWriter();let ke,Oe;try{ke=yield Promise.race([ge.read(),new Promise((je,gt)=>{Oe=setTimeout(()=>{gt(ve.timeout("signal connection timed out while waiting for the first message"))},yw)})])}catch(je){ge.releaseLock(),L(je),this.close();return}finally{clearTimeout(Oe)}if(ge.releaseLock(),!ke.value)throw ve.internal("no message received as first message");let Je=Lg(ke.value),mt=this.validateFirstMessage(Je,(j=a.reconnect)!==null&&j!==void 0?j:!1);if(!mt.isValid){L(mt.error);return}((M=Je.message)===null||M===void 0?void 0:M.case)==="join"&&(this.pingTimeoutDuration=Je.message.value.pingTimeout,this.pingIntervalDuration=Je.message.value.pingInterval,this.pingTimeoutDuration&&this.pingTimeoutDuration>0&&this.log.debug("ping config",{timeout:this.pingTimeoutDuration,interval:this.pingIntervalDuration}),this.onJoined&&this.onJoined(Je.message.value));let Ee=mt.shouldProcessFirstMessage?Je:void 0;ie(ae,Ee),N(mt.response)}catch(ae){L(ae)}finally{q()}}finally{g()}}))})()})}startReadingLoop(e,t){return A(this,void 0,void 0,function*(){for(t&&this.handleSignalResponse(t);;){this.signalLatency&&(yield ft(this.signalLatency));let n=yield e.read(),r=n.done,s=n.value;if(r)break;let o=Lg(s);this.handleSignalResponse(o)}})}close(){return A(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([Fe.DISCONNECTING||Fe.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=Fe.DISCONNECTING),e.ws){e.ws.close({closeCode:1e3,reason:n});let s=e.ws.closed;e.ws=void 0,e.streamWriter=void 0,yield Promise.race([s,ft(vw)])}}catch(s){e.log.debug("websocket error while closing",{error:s})}finally{t&&(e.state=Fe.DISCONNECTED),r()}})()})}sendOffer(e,t){this.log.debug("sending offer",{offerSdp:e.sdp}),this.sendRequest({case:"offer",value:Ci(e,t)})}sendAnswer(e,t){return this.log.debug("sending answer",{answerSdp:e.sdp}),this.sendRequest({case:"answer",value:Ci(e,t)})}sendIceCandidate(e,t){return this.log.debug("sending ice candidate",{candidate:e}),this.sendRequest({case:"trickle",value:new Aa({candidateInit:JSON.stringify(e),target:t})})}sendMuteTrack(e,t){return this.sendRequest({case:"mute",value:new Ma({sid:e,muted:t})})}sendAddTrack(e){return this.sendRequest({case:"addTrack",value:e})}sendUpdateLocalMetadata(e,t){return A(this,arguments,void 0,function(n,r){var s=this;let o=arguments.length>2&&arguments[2]!==void 0?arguments[2]:{};return(function*(){let a=s.getNextRequestId();return yield s.sendRequest({case:"updateMetadata",value:new Ad({requestId:a,metadata:n,name:r,attributes:o})}),a})()})}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 iy({trackSid:e,layers:t})})}sendUpdateSubscriptionPermissions(e,t){return this.sendRequest({case:"subscriptionPermission",value:new oy({allParticipants:e,trackPermissions:t})})}sendSimulateScenario(e){return this.sendRequest({case:"simulate",value:e})}sendPing(){return Promise.all([this.sendRequest({case:"ping",value:Ge.parse(Date.now())}),this.sendRequest({case:"pingReq",value:new ly({timestamp:Ge.parse(Date.now()),rtt:Ge.parse(this.rtt)})})])}sendUpdateLocalAudioTrack(e,t){return this.sendRequest({case:"updateAudioTrack",value:new Pd({trackSid:e,features:t})})}sendLeave(){return this.sendRequest({case:"leave",value:new Ia({reason:Qt.CLIENT_INITIATED,action:vr.DISCONNECT})})}sendPublishDataTrackRequest(e,t,n){return this.sendRequest({case:"publishDataTrackRequest",value:new _d({pubHandle:e,name:t,encryption:n?Ie.GCM:Ie.NONE})})}sendUnPublishDataTrackRequest(e){return this.sendRequest({case:"unpublishDataTrackRequest",value:new wd({pubHandle:e})})}sendUpdateDataSubscription(e,t){return this.sendRequest({case:"updateDataSubscription",value:new Zv({updates:[new ey({trackSid:e,subscribe:t})]})})}sendRequest(e){return A(this,arguments,void 0,function(t){var n=this;let r=arguments.length>1&&arguments[1]!==void 0?arguments[1]:!1;return(function*(){if(!r&&!gw(t)&&n.state===Fe.RECONNECTING){n.queuedRequests.push(()=>A(n,void 0,void 0,function*(){yield this.sendRequest(t,!0)}));return}if(r||(yield n.requestQueue.flush()),n.signalLatency&&(yield ft(n.signalLatency)),n.isDisconnected){n.log.debug("skipping signal request (type: ".concat(t.case,") - SignalClient disconnected"));return}if(!n.streamWriter){n.log.error("cannot send signal request before connected, type: ".concat(t?.case));return}let o=new b_({message:t});try{n.useJSON?yield n.streamWriter.write(o.toJsonString()):yield n.streamWriter.write(o.toBinary().buffer)}catch(a){n.log.error("error sending signal message",{error:a})}})()})}handleSignalResponse(e){var t,n;let r=e.message;if(r==null){this.log.debug("received unsupported message");return}let s=!1;if(r.case==="answer"){let o=jg(r.value);this.onAnswer&&this.onAnswer(o,r.value.id,r.value.midToTrackId)}else if(r.case==="offer"){let o=jg(r.value);this.onOffer&&this.onOffer(o,r.value.id,r.value.midToTrackId)}else if(r.case==="trickle"){let o=JSON.parse(r.value.candidateInit);this.onTrickle&&this.onTrickle(o,r.value.target)}else r.case==="update"?this.onParticipantUpdate&&this.onParticipantUpdate((t=r.value.participants)!==null&&t!==void 0?t:[]):r.case==="trackPublished"?this.onLocalTrackPublished&&this.onLocalTrackPublished(r.value):r.case==="speakersChanged"?this.onSpeakersChanged&&this.onSpeakersChanged((n=r.value.speakers)!==null&&n!==void 0?n:[]):r.case==="leave"?this.onLeave&&this.onLeave(r.value):r.case==="mute"?this.onRemoteMuteChanged&&this.onRemoteMuteChanged(r.value.sid,r.value.muted):r.case==="roomUpdate"?this.onRoomUpdate&&r.value.room&&this.onRoomUpdate(r.value.room):r.case==="connectionQuality"?this.onConnectionQuality&&this.onConnectionQuality(r.value):r.case==="streamStateUpdate"?this.onStreamStateUpdate&&this.onStreamStateUpdate(r.value):r.case==="subscribedQualityUpdate"?this.onSubscribedQualityUpdate&&this.onSubscribedQualityUpdate(r.value):r.case==="subscriptionPermissionUpdate"?this.onSubscriptionPermissionUpdate&&this.onSubscriptionPermissionUpdate(r.value):r.case==="refreshToken"?this.onTokenRefresh&&this.onTokenRefresh(r.value):r.case==="trackUnpublished"?this.onLocalTrackUnpublished&&this.onLocalTrackUnpublished(r.value):r.case==="subscriptionResponse"?this.onSubscriptionError&&this.onSubscriptionError(r.value):r.case==="pong"||(r.case==="pongResp"?(this.rtt=Date.now()-Number.parseInt(r.value.lastPingTimestamp.toString()),this.resetPingTimeout(),s=!0):r.case==="requestResponse"?this.onRequestResponse&&this.onRequestResponse(r.value):r.case==="trackSubscribed"?this.onLocalTrackSubscribed&&this.onLocalTrackSubscribed(r.value.trackSid):r.case==="roomMoved"?(this.onTokenRefresh&&this.onTokenRefresh(r.value.token),this.onRoomMoved&&this.onRoomMoved(r.value)):r.case==="mediaSectionsRequirement"?this.onMediaSectionsRequirement&&this.onMediaSectionsRequirement
73(r.value):r.case==="publishDataTrackResponse"?this.onPublishDataTrackResponse&&this.onPublishDataTrackResponse(r.value):r.case==="unpublishDataTrackResponse"?this.onUnPublishDataTrackResponse&&this.onUnPublishDataTrackResponse(r.value):r.case==="dataTrackSubscriberHandles"?this.onDataTrackSubscriberHandles&&this.onDataTrackSubscriberHandles(r.value):this.log.debug("unsupported message",{msgCase:r.case}));s||this.resetPingTimeout()}setReconnected(){for(;this.queuedRequests.length>0;){let e=this.queuedRequests.shift();e&&this.requestQueue.run(e)}}handleOnClose(e){return A(this,void 0,void 0,function*(){if(this.state===Fe.DISCONNECTED)return;let t=this.onClose;yield this.close(void 0,e),this.log.info("websocket connection closed: ".concat(e),{reason:e}),t&&t(e)})}handleWSError(e){this.log.error("websocket error",{error:e})}resetPingTimeout(){if(this.clearPingTimeout(),!this.pingTimeoutDuration){this.log.warn("ping timeout duration not set");return}this.pingTimeout=Le.setTimeout(()=>{this.log.warn("ping timeout triggered. last pong received at: ".concat(new Date(Date.now()-this.pingTimeoutDuration*1e3).toUTCString())),this.handleOnClose("ping timeout")},this.pingTimeoutDuration*1e3)}clearPingTimeout(){this.pingTimeout&&Le.clearTimeout(this.pingTimeout)}startPingInterval(){if(this.clearPingInterval(),this.resetPingTimeout(),!this.pingIntervalDuration){this.log.warn("ping interval duration not set");return}this.log.debug("start ping interval"),this.pingInterval=Le.setInterval(()=>{this.sendPing()},this.pingIntervalDuration*1e3)}clearPingInterval(){this.log.debug("clearing ping interval"),this.clearPingTimeout(),this.pingInterval&&Le.clearInterval(this.pingInterval)}handleSignalConnected(e,t,n){this.state=Fe.CONNECTED,this.log.info("signal connected"),clearTimeout(t),this.startPingInterval(),this.startReadingLoop(e.readable.getReader(),n)}validateFirstMessage(e,t){var n,r,s,o,a;return((n=e.message)===null||n===void 0?void 0:n.case)==="join"?{isValid:!0,response:e.message.value}:this.state===Fe.RECONNECTING&&((r=e.message)===null||r===void 0?void 0:r.case)!=="leave"?((s=e.message)===null||s===void 0?void 0:s.case)==="reconnect"?{isValid:!0,response:e.message.value}:(this.log.debug("declaring signal reconnected without reconnect response received"),{isValid:!0,response:void 0,shouldProcessFirstMessage:!0}):this.isEstablishingConnection&&((o=e.message)===null||o===void 0?void 0:o.case)==="leave"?{isValid:!1,error:ve.leaveRequest("Received leave request while trying to (re)connect",e.message.value.reason)}:t?{isValid:!1,error:ve.internal("Unexpected first message")}:{isValid:!1,error:ve.internal("did not receive join response, got ".concat((a=e.message)===null||a===void 0?void 0:a.case," instead"))}}handleConnectionError(e,t){return A(this,void 0,void 0,function*(){try{let n=yield fetch(t);switch(n.status){case 404:let r=yield n.text();return r.includes("requested room does not exist")?ve.notAllowed(r,n.status):ve.serviceNotFound("v1 RTC path not found. Consider upgrading your LiveKit server version","v0-rtc");case 401:case 403:let s=yield n.text();return ve.notAllowed(s,n.status);default:break}return e instanceof ve?e:ve.internal("Encountered unknown websocket error during connection: ".concat(e),{status:n.status,statusText:n.statusText})}catch(n){return n instanceof ve?n:ve.serverUnreachable(n instanceof Error?n.message:"server was not reachable")}})}};function jg(i){let e={type:"offer",sdp:i.sdp};switch(i.type){case"answer":case"offer":case"pranswer":case"rollback":e.type=i.type;break}return e}function Ci(i,e){return new ii({sdp:i.sdp,type:i.type,id:e})}function bw(i,e,t){var n;let r=new URLSearchParams;return r.set("access_token",i),t.reconnect&&(r.set("reconnect","1"),t.sid&&r.set("sid",t.sid)),r.set("auto_subscribe",t.autoSubscribe?"1":"0"),r.set("sdk",en()?"reactnative":"js"),r.set("version",e.version),r.set("protocol",e.protocol.toString()),r.set("client_protocol",e.clientProtocol.toString()),e.deviceModel&&r.set("device_model",e.deviceModel),e.os&&r.set("os",e.os),e.osVersion&&r.set("os_version",e.osVersion),e.browser&&r.set("browser",e.browser),e.browserVersion&&r.set("browser_version",e.browserVersion),t.adaptiveStream&&r.set("adaptive_stream","1"),t.reconnectReason&&r.set("reconnect_reason",t.reconnectReason.toString()),!((n=navigator.connection)===null||n===void 0)&&n.type&&r.set("network",navigator.connection.type),r}function kw(i,e,t,n){return A(this,void 0,void 0,function*(){let r=new URLSearchParams;r.set("access_token",i);let s=new K_({clientInfo:e,connectionSettings:new uy({autoSubscribe:!!t.autoSubscribe,adaptiveStream:!!t.adaptiveStream}),reconnect:!!t.reconnect,participantSid:t.sid?t.sid:void 0,publisherOffer:n});t.reconnectReason&&(s.reconnectReason=t.reconnectReason);let o=s.toBinary(),a,d;if(Zn()){let g=new CompressionStream("gzip"),b=g.writable.getWriter();b.write(new Uint8Array(o)),b.close();let R=[],w=g.readable.getReader();for(;;){let j=yield w.read(),M=j.done,P=j.value;if(M)break;R.push(P)}let I=R.reduce((j,M)=>j+M.length,0),N=new Uint8Array(I),L=0;for(let j of R)N.set(j,L),L+=j.length;a=N,d=Hl.GZIP}else a=o,d=Hl.NONE;let f=new z_({joinRequest:a,compression:d}).toBinary(),p=g=>{let b=Array.from(g,R=>String.fromCodePoint(R)).join("");return btoa(b)};return r.set("join_request",p(f).replace(/\+/g,"-").replace(/\//g,"_")),r})}var Cu=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 n of this._map.entries()){var t=pe(n,2);let r=t[0];t[1].expiresAt<e&&this._map.delete(r)}this._lastCleanup=e}get size(){return this.cleanup(),this._map.size}forEach(e){this.cleanup();for(let n of this._map.entries()){var t=pe(n,2);let r=t[0],s=t[1];s.expiresAt>=Date.now()&&e(s.value,r,this.asValueMap())}}map(e){this.cleanup();let t=[],n=this.asValueMap();for(let s of n.entries()){var r=pe(s,2);let o=r[0],a=r[1];t.push(e(a,o,n))}return t}asValueMap(){let e=new Map;for(let n of this._map.entries()){var t=pe(n,2);let r=t[0],s=t[1];s.expiresAt>=Date.now()&&e.set(r,s.value)}return e}},$t={},El={},Pl={exports:{}},Bg;function qd(){if(Bg)return Pl.exports;Bg=1;var i=Pl
vendor: 6,910 bytes, line 73
73.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 %s IP%d %s":"rtcp:%d"}},{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 %s":"rtcp-fb:%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 %s":"crypto:%d %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?" raddr %s rport %d":"%v%v",t+=e.tcptype!=null?" tcptype %s":"%v",e.generation!=null&&(t+=" generation %d"),t+=e["network-id"]!=null?" network-id %d":"%v",t+=e["network-cost"]!=null?" network-cost %d":"%v",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 %s":"sctpmap:%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:new 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:new 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?"id=%s %s":"%v%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(i).forEach(function(e){var t=i[e];t.forEach(function(n){n.reg||(n.reg=/(.*)/),n.format||(n.format="%s")})}),
vendor: 2,509 bytes, line 73
73Pl.exports}var qg;function Sw(){return qg||(qg=1,(function(i){var e=function(a){return String(Number(a))===a?Number(a):a},t=function(a,d,l,f){if(f&&!l)d[f]=e(a[1]);else for(var p=0;p<l.length;p+=1)a[p+1]!=null&&(d[l[p]]=e(a[p+1]))},n=function(a,d,l){var f=a.name&&a.names;a.push&&!d[a.push]?d[a.push]=[]:f&&!d[a.name]&&(d[a.name]={});var p=a.push?{}:f?d[a.name]:d;t(l.match(a.reg),p,a.names,a.name),a.push&&d[a.push].push(p)},r=qd(),s=RegExp.prototype.test.bind(/^([a-z])=(.*)/);i.parse=function(a){var d={},l=[],f=d;return a.split(/(\r\n|\r|\n)/).filter(s).forEach(function(p){var g=p[0],b=p.slice(2);g==="m"&&(l.push({rtp:[],fmtp:[]}),f=l[l.length-1]);for(var R=0;R<(r[g]||[]).length;R+=1){var w=r[g][R];if(w.reg.test(b))return n(w,f,b)}}),d.media=l,d};var o=function(a,d){var l=d.split(/=(.+)/,2);return l.length===2?a[l[0]]=e(l[1]):l.length===1&&d.length>1&&(a[l[0]]=void 0),a};i.parseParams=function(a){return a.split(/;\s?/).reduce(o,{})},i.parseFmtpConfig=i.parseParams,i.parsePayloads=function(a){return a.toString().split(" ").map(Number)},i.parseRemoteCandidates=function(a){for(var d=[],l=a.split(" ").map(e),f=0;f<l.length;f+=3)d.push({component:l[f],ip:l[f+1],port:l[f+2]});return d},i.parseImageAttributes=function(a){return a.split(" ").map(function(d){return d.substring(1,d.length-1).split(",").reduce(o,{})})},i.parseSimulcastStreamList=function(a){return a.split(";").map(function(d){return d.split(",").map(function(l){var f,p=!1;return l[0]!=="~"?f=e(l):(f=e(l.substring(1,l.length)),p=!0),{scid:f,paused:p}})})}})(El)),El}var Al,Vg;function Tw(){if(Vg)return Al;Vg=1;var i=qd(),e=/%[sdv%]/g,t=function(o){var a=1,d=arguments,l=d.length;return o.replace(e,function(f){if(a>=l)return f;var p=d[a];switch(a+=1,f){case"%%":return"%";case"%s":return String(p);case"%d":return Number(p);case"%v":return""}})},n=function(o,a,d){var l=a.format instanceof Function?a.format(a.push?d:d[a.name]):a.format,f=[o+"="+l];if(a.names)for(var p=0;p<a.names.length;p+=1){var g=a.names[p];a.name?f.push(d[a.name][g]):f.push(d[a.names[p]])}else f.push(d[a.name]);return t.apply(null,f)},r=["v","o","s","i","u","e","p","c","b","t","r","z","a"],s=["i","c","b","a"];return Al=function(o,a){a=a||{},o.version==null&&(o.version=0),o.name==null&&(o.name=" "),o.media.forEach(function(p){p.payloads==null&&(p.payloads="")});var d=a.outerOrder||r,l=a.innerOrder||s,f=[];return d.forEach(function(p){i[p].forEach(function(g){g.name in o&&o[g.name]!=null?f.push(n(p,g,o)):g.push in o&&o[g.push]!=null&&o[g.push].forEac
73h(function(b){f.push(n(p,g,b))})})}),o.media.forEach(function(p){f.push(n("m",i.m[0],p)),l.forEach(function(g){i[g].forEach(function(b){b.name in p&&p[b.name]!=null?f.push(n(g,b,p)):b.push in p&&p[b.push]!=null&&p[b.push].forEach(function(R){f.push(n(g,b,R))})})})}),f.join(`\r 74`)+`\r 75`},Al}var $g;function _w(){if($g)return $t;$g=1;var i=Sw(),e=Tw(),t=qd();return $t.grammar=t,$t.write=e,$t.parse=i.parse,$t.parseParams=i.parseParams,$t.parseFmtpConfig=i.parseFmtpConfig,$t.parsePayloads=i.parsePayloads,$t.parseRemoteCandidates=i.parseRemoteCandidates,$t.parseImageAttributes=i.parseImageAttributes,$t.parseSimulcastStreamList=i.parseSimulcastStreamList,$t}var Nt=_w(),Cw=.9,ww=1e3,Ew=20;function Pw(i,e,t,n){let r=arguments.length>4&&arguments[4]!==void 0?arguments[4]:!1;var s,o,a;if(!(!((s=i.msid)===null||s===void 0)&&s.includes(e)))return;let d=(a=(o=i.rtp.find(g=>g.codec.toUpperCase()===t.toUpperCase()))===null||o===void 0?void 0:o.payload)!==null&&a!==void 0?a:0;if(d===0)return 0;let l=Math.round(n*Cw),f=r?l:Math.min(l,ww),p=i.fmtp.find(g=>g.payload===d);return p?p.config.includes("x-google-start-bitrate")||(p.config+=";x-google-start-bitrate=".concat(f)):i.fmtp.push({payload:d,config:"x-google-start-bitrate=".concat(f)}),d}var Yn={NegotiationStarted:"negotiationStarted",NegotiationComplete:"negotiationComplete",OfferAnswered:"offerAnswered",RTPVideoPayloadTypes:"rtpVideoPayloadTypes"},Qo=class extends _t.EventEmitter{get pc(){return this._pc||(this._pc=this.createPC()),this._pc}constructor(e){let t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{};var n;super(),this.log=ye,this.iceLog=ye,this.ddExtID=0,this.latestOfferId=0,this.latestAcknowledgedOfferId=0,this.pendingCandidates=[],this.restartingIce=!1,this.renegotiate=!1,this.trackBitrates=[],this.remoteStereoMids=[],this.remoteNackMids=[],this.negotiate=Fd(r=>A(this,void 0,void 0,function*(){this.emit(Yn.NegotiationStarted);try{yield this.createAndSendOffer()}catch(s){if(r)r(s);else throw s}}),Ew),this.close=()=>{this._pc&&(this.log.debug("closing peer connection"),this.pendingInitialOffer=void 0,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,this._pc=null)},this.loggerOptions=t,this.log=ut((n=t.loggerName)!==null&&n!==void 0?n:Xe.PCTransport,()=>this.logContext),this.iceLog=ut(Xe.ICE,()=>this.logContext),this.config=e,this._pc=this.createPC(),this.offerLock=new tt}createPC(){let e=new RTCPeerConnection(this.config);return e.onicecandidate=t=>{var n;t.candidate&&(this.iceLog.debug("local ICE candidate gathered",{candidate:t.candidate.candidate}),(n=this.onIceCandidate)===null||n===void 0||n.call(this,t.candidate))},e.onicecandidateerror=t=>{var n;this.iceLog.debug("ICE candidate error",{event:t}),(n=this.onIceCandidateError)===null||n===void 0||n.call(this,t)},e.oniceconnectionstatechange=()=>{var t;this.iceLog.debug("ICE connection state: ".concat(e.iceConnectionState)),(t=this.onIceConnectionStateChange)===null||t===void 0||t.call(this,e.iceConnectionState)},e.onsignalingstatechange=()=>{var t;this.log.debug("signaling state: ".concat(e.signalingState)),(t=this.onSignalingStatechange)===null||t===void 0||t.call(this,e.signalingState)},e.onconnectionstatechange=()=>{var t;this.log.debug("connection state: ".concat(e.connectionState)),(t=this.onConnectionStateChange)===null||t===void 0||t.call(this,e.connectionState)},e.ondatachannel=t=>{var n;this.log.debug("data channel opened by peer",{label:t.channel.label,id:t.channel.id}),(n=this.onDataChannel)===null||n===void 0||n.call(this,t)},e.ontrack=t=>{var n;(n=this.onTrack)===null||n===void 0||n.call(this,t)},e}get logContext(){var e,t;return Object.assign({},(t=(e=this.loggerOptions).loggerContextCb)===null||t===void 0?void 0:t.call(e))}get isICEConnected(){return this._pc!==null&&(this.pc.iceConnectionState==="connected"||this.pc.iceConnectionState==="completed")}addIceCandidate(e){return A(this,void 0,void 0,function*(){if(this.pc.remoteDescription&&!this.restartingIce)return this.pc.addIceCandidate(e);this.iceLog.debug("queuing remote ICE candidate until remote description applied",{pendingCount:this.pendingCandidates.length+1}),this.pendingCandidates.push(e)})}setRemoteDescription(e,t){return A(this,void 0,void 0,function*(){var n,r;if(e.type==="answer"&&this.latestOfferId>0&&t>0&&t!==this.latestOfferId)return this.log.warn("ignoring answer for old offer",{offerId:t,latestOfferId:this.latestOfferId}),!1;let s;if(e.type==="offer"){let o=Dw(e),a=o.stereoMids,d=o.nackMids;this.remoteStereoMids=a,this.remoteNackMids=d}else if(e.type==="answer"){if(this.pendingInitialOffer&&this._pc){let d=this.pendingInitialOffer;this.pendingInitialOffer=void 0;let l=Nt.parse((n=d.sdp)!==null&&n!==void 0?n:"");
75l.media.forEach(f=>{_o(f)}),this.log.debug("setting pending initial offer before processing answer"),yield this.setMungedSDP(d,Nt.write(l))}let o=Nt.parse((r=e.sdp)!==null&&r!==void 0?r:"");o.media.forEach(d=>{let l=ds(d.mid);d.type==="audio"&&this.trackBitrates.some(f=>{if(!f.transceiver||l!=f.transceiver.mid)return!1;let p=0;if(d.rtp.some(b=>b.codec.toUpperCase()===f.codec.toUpperCase()?(p=b.payload,!0):!1),p===0)return!0;let g=!1;for(let b of d.fmtp)if(b.payload===p){b.config=b.config.split(";").filter(R=>!R.includes("maxaveragebitrate")).join(";"),f.maxbr>0&&(b.config+=";maxaveragebitrate=".concat(f.maxbr*1e3)),g=!0;break}return g||f.maxbr>0&&d.fmtp.push({payload:p,config:"maxaveragebitrate=".concat(f.maxbr*1e3)}),!0})});let a=this.getPlaceholderMids();a.size>0&&Jg(o.media,d=>a.has(ds(d.mid))),s=Nt.write(o)}return yield this.setMungedSDP(e,s,!0),this.pendingCandidates.length>0&&this.iceLog.debug("flushing queued ICE candidates",{count:this.pendingCandidates.length}),this.pendingCandidates.forEach(o=>{this.pc.addIceCandidate(o)}),this.pendingCandidates=[],this.restartingIce=!1,e.type==="answer"&&(this.latestAcknowledgedOfferId=t,this.emit(Yn.OfferAnswered,t)),this.renegotiate?(this.renegotiate=!1,yield this.createAndSendOffer()):e.type==="answer"&&(this.emit
75(Yn.NegotiationComplete),e.sdp&&Nt.parse(e.sdp).media.forEach(a=>{a.type==="video"&&this.emit(Yn.RTPVideoPayloadTypes,a.rtp)})),!0})}createInitialOffer(){return A(this,void 0,void 0,function*(){var e;let t=yield this.offerLock.lock();try{if(this.pc.signalingState!=="stable"){this.log.warn("signaling state is not stable, cannot create initial offer");return}let n=this.latestOfferId+1;this.latestOfferId=n;let r=yield this.pc.createOffer();this.pendingInitialOffer={sdp:r.sdp,type:r.type};let s=Nt.parse((e=r.sdp)!==null&&e!==void 0?e:"");return s.media.forEach(o=>{_o(o)}),r.sdp=Nt.write(s),{offer:r,offerId:n}}finally{t()}})}createAndSendOffer(e){return A(this,void 0,void 0,function*(){var t;let n=yield this.offerLock.lock();try{if(this.onOffer===void 0)return;if(e?.iceRestart&&(this.iceLog.debug("restarting ICE"),this.restartingIce=!0),this._pc&&(this._pc.signalingState==="have-local-offer"||this.pendingInitialOffer)){let d=this._pc.remoteDescription;if(e?.iceRestart&&d)yield this._pc.setRemoteDescription(d);else{if(e?.iceRestart)throw new hn("ICE restart requested without a remote description, peer connection must be recreated");this.renegotiate=!0,this.log.debug("requesting renegotiation");return}}else if(!this._pc||this._pc.signalingState==="closed"){this.log.warn("could not createOffer with closed peer connection");return}this.log.debug("starting to negotiate");let r=this.latestOfferId+1;this.latestOfferId=r;let s=yield this.pc.createOffer(e);this.log.debug("original offer",{sdp:s.sdp});let o=Nt.parse((t=s.sdp)!==null&&t!==void 0?t:"");o.media.forEach(d=>{_o(d),d.type==="audio"?Gg(d,["all"],[]):d.type==="video"&&this.trackBitrates.some(l=>{if(!l.cid)return!1;let f=Pw(d,l.cid,l.codec,l.maxbr,l.isScreenShare);return f===void 0?!1:(f>0&&un(l.codec)&&!Di()&&(this.ddExtID=Aw(d,o,this.ddExtID)),!0)})});let a=this.getPlaceholderMids();if(a.size>0&&Jg(o.media,d=>a.has(ds(d.mid))),this.latestOfferId>r){this.log.warn("latestOfferId mismatch",{latestOfferId:this.latestOfferId,offerId:r});return}yield this.setMungedSDP(s,Nt.write(o)),this.onOffer(s,this.latestOfferId)}finally{n()}})}createAndSetAnswer(){return A(this,void 0,void 0,function*(){var e;let t=yield this.pc.createAnswer(),n=Nt.parse((e=t.sdp)!==null&&e!==void 0?e:"");return n.media.forEach(r=>{_o(r),r.type==="audio"&&Gg(r,this.remoteStereoMids,this.remoteNackMids)}),yield this.setMungedSDP(t,Nt.write(n)),t})}getPlaceholderMids(){var e,t;return Ow((t=(e=this._pc)===null||e===void 0?void 0:e.getTransceivers())!==null&&t!==void 0?t:[])}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 Be("PC closed, cannot add track");return this._pc.addTrack(e)}setTrackCodecBitrate(e){this.trackBitrates.push(e)}setConfiguration(e){var t;if(!this._pc)throw new Be("PC closed, cannot configure");return(t=this._pc)===null||t===void 0?void 0:t.setConfiguration(e)}canRemoveTrack(){var e;return!!(!((e=this._pc)===null||e===void 0)&&e.removeTrack)}removeTrack(e){var t;return(t=this._pc)===null||t===void 0?void 0:t.removeTrack(e)}getConnectionState(){var e,t;return(t=(e=this._pc)===null||e===void 0?void 0:e.connectionState)!==null&&t!==void 0?t:"closed"}getICEConnectionState(){var e,t;return(t=(e=this._pc)===null||e===void 0?void 0:e.iceConnectionState)!==null&&t!==void 0?t:"closed"}getSignallingState(){var e,t;return(t=(e=this._pc)===null||e===void 0?void 0:e.signalingState)!==null&&t!==void 0?t:"closed"}getTransceivers(){var e,t;return(t=(e=this._pc)===null||e===void 0?void 0:e.getTransceivers())!==null&&t!==void 0?t:[]}getSenders(){var e,t;return(t=(e=this._pc)===null||e===void 0?void 0:e.getSenders())!==null&&t!==void 0?t:[]}getLocalDescription(){var e;return(e=this._pc)===null||e===void 0?void 0:e.localDescription}getRemoteDescription(){var e;return(e=this.pc)===null||e===void 0?void 0:e.remoteDescription}getStats(){return this.pc.getStats()}getMaxMessageSize(){var e,t;return(t=(e=this._pc)===null||e===void 0?void 0:e.sctp)===null||t===void 0?void 0:t.maxMessageSize}getConnectedAddress(){return A(this,void 0,void 0,function*(){var e;if(!this._pc)return;let t="",n=new Map,r=new Map;
75if((yield this._pc.getStats()).forEach(a=>{switch(a.type){case"transport":t=a.selectedCandidatePairId;break;case"candidate-pair":t===""&&a.selected&&(t=a.id),n.set(a.id,a);break;case"remote-candidate":r.set(a.id,"".concat(a.address,":").concat(a.port));break}}),t==="")return;let o=(e=n.get(t))===null||e===void 0?void 0:e.remoteCandidateId;if(o!==void 0)return r.get(o)})}setMungedSDP(e,t,n){return A(this,void 0,void 0,function*(){var r,s;let o=e.sdp;if(t){e.sdp=t;try{this.log.debug("setting munged ".concat(n?"remote":"local"," description")),n?yield this.pc.setRemoteDescription(e):yield this.pc.setLocalDescription(e);return}catch(a){this.log.warn("not able to set ".concat(e.type,", falling back to unmodified sdp"),{error:a,mungedSdp:t,originalSdp:o}),e.sdp=o}}try{n?yield(r=this._pc)===null||r===void 0?void 0:r.setRemoteDescription(e):yield(s=this._pc)===null||s===void 0?void 0:s.setLocalDescription(e)}catch(a){let d="unknown error";a instanceof Error?d=a.message:typeof a=="string"&&(d=a);let l={error:d,sdp:e.sdp};throw t&&t!==o&&(l.mungedSdp=t),!n&&this.pc.remoteDescription&&(l.remoteSdp=this.pc.remoteDescription),this.log.error("unable to set ".concat(e.type),{fields:l}),new hn(d)}})}};function Aw(i,e,t){var n,r;let s=Mw(e,t);return s===void 0?t:(!((n=i.ext)===null||n===void 0)&&n.some(o=>o.uri===kr)||((r=i.ext)!==null&&r!==void 0||(i.ext=[]),i.ext.push({value:s,uri:kr})),s)}function Mw(i,e){let t=Rw(i,kr);return t!==void 0?Wg(i,t,kr)?void 0:t:e!==0&&!Wg(i,e,kr)?e:Iw(i)}function Rw(i,e){var t;for(let n of i.media){let r=(t=n.ext)===null||t===void 0?void 0:t.find(s=>s.uri===e);if(r)return r.value}}function Wg(i,e,t){return i.media.some(n=>{var r;return(r=n.ext)===null||r===void 0?void 0:r.some(s=>s.value===e&&s.uri!==t)})}function Iw(i){let e=0;return i.media.forEach(t=>{var n;(n=t.ext)===null||n===void 0||n.forEach(r=>{r.value>e&&(e=r.value)})}),e+1===15?16:e+1}function sb(i,e){return i.split(";").some(t=>t.trim()===e)}function Gg(i,e,t){let n=ds(i.mid),r=0;i.rtp.some(s=>s.codec.toLowerCase()==="opus"?(r=s.payload,!0):!1),r>0&&(i.rtcpFb||(i.rtcpFb=[]),t.includes(n)&&!i.rtcpFb.some(s=>s.payload===r&&s.type==="nack")&&i.rtcpFb.push({payload:r,type:"nack"}),(e.includes(n)||e.length===1&&e[0]==="all")&&i.fmtp.some(s=>s.payload===r?(sb(s.config,"stereo=1")||(s.config+=";stereo=1"),!0):!1))}function Ow(i){let e=new Set;for(let t of i)t.mid&&!t.sender.track&&e.add(t.mid);return e}function Jg(i,e){var t,n;let r=new Map,s=new Set;for(let o of i){let a=e(o);for(let d of(t=o.fmtp)!==null&&t!==void 0?t:[])a?r.has(d.payload)||r.set(d.payload,d.config):(r.set(d.payload,d.config),s.add(d.payload))}if(r.size!==0){for(let o of i)if(e(o))for(let a of(n=o.fmtp)!==null&&n!==void 0?n:[]){let d=r.get(a.payload);d!==void 0&&a.config!==d&&(a.config=d)}}}function Dw(i){var e;let t=[],n=[],r=Nt.parse((e=i.sdp)!==null&&e!==void 0?e:""),s=0;return r.media.forEach(o=>{var a;let d=ds(o.mid);o.type==="audio"&&(o.rtp.some(l=>l.codec.toLowerCase()==="opus"?(s=l.payload,!0):!1),!((a=o.rtcpFb)===null||a===void 0)&&a.some(l=>l.payload===s&&l.type==="nack")&&n.push(d),o.fmtp.some(l=>l.payload===s?(sb(l.config,"sprop-stereo=1")&&t.push(d),!0):!1))}),{stereoMids:t,nackMids:n}}function _o(i){if(i.connection){let e=i.connection.ip.indexOf(":")>=0;(i.connection.version===4&&e||i.connection.version===6&&!e)&&(i.connection.ip="0.0.0.0",i.connection.version=4)}}function ds(i){return typeof i=="number"?i.toFixed(0):i}var wu="vp8",Lw={audioPreset:ou.music,dtx:!0,red:!0,forceStereo:!1,simulcast:!0,screenShareEncoding:Dd.h1080fps15.encoding,stopMicTrackOnMute:!1,videoCodec:wu,backupCodec:!0,preConnectBuffer:!1},ob={deviceId:{ideal:"default"},autoGainControl:!0,echoCancellation:!0,noiseSuppression:!0,voiceIsolation:!0},ab={deviceId:{ideal:"default"},resolution:Ss.h720.resolution},xw={adaptiveStream:!1,dynacast:!1,stopLocalTrackOnUnpublish:!0,reconnectPolicy:new zl,disconnectOnPageLeave:!0,webAudioMix:!1,singlePeerConnection:!0},Vd={autoSubscribe:!0,maxRetries:1,peerConnectionTimeout:15e3,websocketTimeout:15e3},Ve;(function(i){i[i.NEW=0]="NEW",i[i.CONNECTING=1]="CONNECTING",i[i.CONNECTED=2]="CONNECTED",i[i.FAILED=3]="FAILED",i[i.CLOSING=4]="CLOSING",i[i.CLOSED=5]="CLOSED"})(Ve||(Ve={}));var Xo=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){var r;this.peerConnectionTimeout=Vd.peerConnectionTimeout,this.log=ye,this.iceLog=ye,this.updateState=()=>{var s,o;let a=this.state,d=this.requiredTransports.map(l=>l.getConnectionState());d.every(l=>l==="connected")?this.state=Ve.CONNECTED:d.some(l=>l==="failed")?this.state=Ve.FAILED:d.some(l=>l==="connecting")?this.state=Ve.CONNECTING:d.every(l=>l==="closed")?this.state=Ve.CLOSED:d.some(l=>l==="closed")?this.state=Ve.CLOSING:d.every(l=>l==="new")&&(this.state=Ve.NEW),a!==this.state&&(this.log.debug("pc state change: from ".concat(Ve[a]," to ").concat(Ve[this.state])),(s=this.onStateChange)===null||s===void 0||s.call(this,this.state,this.publisher.getConnectionState(),(o=this.subscriber)===null||o===void 0?void 0:o.getConnectionState()))},this.loggerOptions=t,this.log=ut((r=t.loggerName)!==null&&r!==void 0?r:Xe.PCManager,()=>this.logContext),this.iceLog=ut(Xe.ICE,()=>this.logContext),this.isPublisherConnectionRequired=e!=="subscriber-primary",this.isSubscriberConnectionRequired=e==="subscriber-primary",this.publisher=new Qo(n,t),this._mode=e,e!=="publisher-only"&&(this.subscriber=new Qo(n,t),this.subscriber.onConnectionStateChange=this.updateState,this.subscriber.onIceConnectionStateChange=this.updateState,this.subscriber.onSignalingStatechange=this.updateState,this.subscriber.onIceCandidate=s=>{var o;(o=this.onIceCandidate)===null||o===void 0||o.call(this,s,zt.SUBSCRIBER)},this.subscriber.onDataChannel=s=>{var o;(o=this.onDataChannel)===null||o===void 0||o.call(this,s)},this.subscriber.onTrack=s=>{var o;(o=this.onTrack)===null||o===void 0||o.call(this,s)}),this.publisher.onConnectionStateChange=this.updateState,this.publisher.onIceConnectionStateChange=this.updateState,this.publisher.onSignalingStatechange=this.updateState,this.publisher.onIceCandidate=s=>{var o;(o=this.onIceCandidate)===null||o===void 0||o.call(this,s,zt.PUBLISHER)},this.publisher.onTrack=s=>{var o;(o=this.onTrack)===null||o===void 0||o.call(this,s)},this.publisher.onOffer=(s,o)=>{var a;(a=this.onPublisherOffer)===null||a===void 0||a.call(this,s,o)},this.state=Ve.NEW,this.connectionLock=new tt,this.remoteOfferLock=new tt}get logContext(){var e,t;return Object.assign({},(t=(e=this.loggerOptions).loggerContextCb)===null||t===void 0?void 0:t.call(e))}requirePublisher(){let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:!0;this.isPublisherConnectionRequired=e,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 A(this,void 0,void 0,function*(){var e;if(this.publisher&&this.publisher.getSignallingState()!=="closed"){let t=this.publisher;for(let n of t.getSenders())try{t.canRemoveTrack()&&t.removeTrack(n)}catch(r){this.log.warn("could not removeTrack",{error:r})}}yield Promise.all([this.publisher.close(),(e=this.subscriber)===null||e===void 0?void 0:e.close()]),this.updateState()})}triggerIceRestart(){return A(this,void 0,void 0,function*(){this.iceLog.warn("triggering ICE restart"),this.subscriber&&(this.subscriber.restartingIce=!0),this.needsPublisher&&(yield this.createAndSendPublisherOffer({iceRestart:!0}))})}addIceCandidate(e,t){return A(this,void 0,void 0,function*(){var n;this.iceLog.debug("adding remote ICE candidate",{target:t,candidate:e}),t===zt.PUBLISHER?yield this.publisher.addIceCandidate(e):yield(n=this.subscriber)===null||n===void 0?void 0:n.addIceCandidate(e)})}createSubscriberAnswerFromOffer(e,t){return A(this,void 0,void 0,function*(){var n,r,s;this.log.debug("received server offer",{RTCSdpType:e.type,sdp:e.sdp,signalingState:(n=this.subscriber)===null||n===void 0?void 0:n.getSignallingState().toString()});let o=yield this.remoteOfferLock.lock();try{return(yield(r=this.subscriber)===null||r===void 0?void 0:r.setRemoteDescription(e,t))?yield(s=this.subscriber)===null||s===void 0?void 0:s.createAndSetAnswer():void 0}finally{o()}})}updateConfiguration(e,t){var n;
vendor: 10,160 bytes, line 75
75this.log.debug("updating rtc configuration",{iceRestart:t}),this.publisher.setConfiguration(e),(n=this.subscriber)===null||n===void 0||n.setConfiguration(e),t&&this.triggerIceRestart()}ensurePCTransportConnection(e,t){return A(this,void 0,void 0,function*(){var n;let r=yield this.connectionLock.lock();try{this.isPublisherConnectionRequired&&this.publisher.getConnectionState()!=="connected"&&this.publisher.getConnectionState()!=="connecting"&&(this.log.debug("negotiation required, start negotiating"),this.publisher.negotiate()),yield Promise.all((n=this.requiredTransports)===null||n===void 0?void 0:n.map(s=>this.ensureTransportConnected(s,e,t)))}finally{r()}})}negotiate(e){return A(this,void 0,void 0,function*(){return new lt((t,n)=>{let r=this.publisher.latestOfferId;if(this.publisher.latestAcknowledgedOfferId>r){this.log.debug("negotiation already handled in more recent acknowledged offer",this.logContext),t();return}let s=!1,o=()=>{s||(s=!0,clearTimeout(l),this.publisher.off(Yn.OfferAnswered,a),e.signal.removeEventListener("abort",d))},a=f=>{f>r&&(o(),t())},d=()=>{o(),n(new hn("negotiation aborted"))},l=setTimeout(()=>{o(),n(new hn("negotiation timed out"))},this.peerConnectionTimeout);e.signal.addEventListener("abort",d),this.publisher.on(Yn.OfferAnswered,a),this.publisher.negotiate(f=>{o(),f instanceof Error?n(f):n(new Error(String(f)))})})})}addPublisherTransceiver(e,t){return this.publisher.addTransceiver(e,t)}addPublisherTransceiverOfKind(e,t){return this.publisher.addTransceiverOfKind(e,t)}getMidForReceiver(e){let n=(this.subscriber?this.subscriber.getTransceivers():this.publisher.getTransceivers()).find(r=>r.receiver===e);return n?.mid}getMaxPublisherMessageSize(){return this.publisher.getMaxMessageSize()}addPublisherTrack(e){return this.publisher.addTrack(e)}createPublisherDataChannel(e,t){return this.publisher.createDataChannel(e,t)}getConnectedAddress(e){return e===zt.PUBLISHER?this.publisher.getConnectedAddress():e===zt.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 A(this,arguments,void 0,function(n,r){var s=this;let o=arguments.length>2&&arguments[2]!==void 0?arguments[2]:this.peerConnectionTimeout;return(function*(){if(n.getConnectionState()!=="connected")return new Promise((d,l)=>A(s,void 0,void 0,function*(){let f=()=>{this.log.warn("abort transport connection"),Le.clearTimeout(p),l(ve.cancelled("room connection has been cancelled"))};r?.signal.aborted&&f(),r?.signal.addEventListener("abort",f);let p=Le.setTimeout(()=>{r?.signal.removeEventListener("abort",f),l(ve.internal("could not establish pc connection"))},o);for(;this.state!==Ve.CONNECTED;)if(yield ft(50),r?.signal.aborted){l(ve.cancelled("room connection has been cancelled"));return}Le.clearTimeout(p),r?.signal.removeEventListener("abort",f),d()}))})()})}},Zo=class{constructor(e){this.bufferStatusLow=!0,this.headroomLock=new tt,this.waiterAbortController=new AbortController,this.kind=e.kind,this.lowWaterMark=e.lowWaterMark,this.highWaterMark=e.highWaterMark,this.isEngineClosed=e.isEngineClosed,this.onBufferStatusChanged=e.onBufferStatusChanged}get channelHandle(){return this.handle}attach(e){this.handle&&this.handle!==e&&this.invalidateWaiters("data channel replaced"),this.handle=e}detach(){let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:"data channel torn down";this.handle&&this.invalidateWaiters(e),this.handle=void 0}getChannel(){return this.handle}isBelowHighWaterMark(e){return e.bufferedAmount<=this.highWaterMark}isBelowLowWaterMark(e){return e.bufferedAmount<=e.bufferedAmountLowThreshold}lockHeadroom(){return this.headroomLock.lock()}waitForHeadroomWithLock(){return A(this,void 0,void 0,function*(){let e=yield this.lockHeadroom();try{yield this.waitForHeadroomWithoutLock()}finally{e()}})}waitForHeadroomWithoutLock(){return A(this,void 0,void 0,function*(){if(this.isEngineClosed())throw new Be("engine closed");let e=this.getChannel();if(!e)throw new Be("DataChannel not found, kind: ".concat(this.kind));if(this.isBelowHighWaterMark(e))return;let t=this.waiterAbortController.signal;yield new lt((n,r)=>{let s=()=>{d(),n()},o=()=>{d(),r(new Be("DataChannel ".concat(this.kind," closed while draining the buffer")))},a=()=>{d(),r(new Be("DataChannel ".concat(this.kind," was replaced or torn down while waiting for headroom")))},d=()=>{e.removeEventListener("bufferedamountlow",s),e.removeEventListener("close",o),t.removeEventListener("abort",a)};if(t.aborted){a();return}e.addEventListener("bufferedamountlow",s),e.addEventListener("close",o),t.addEventListener("abort",a)})})}invalidateWaiters(e){this.waiterAbortController.abort(e),this.waiterAbortController=new AbortController}refreshBufferStatus(){var e;let t=this.getChannel();if(!t)return;let n=this.isBelowLowWaterMark(t);n!==this.bufferStatusLow&&(this.bufferStatusLow=n,(e=this.onBufferStatusChanged)===null||e===void 0||e.call(this,n))}},ea=class extends Zo{constructor(e){super(e),this.statCurrentBytes=0,this.statByterate=0,this.dropCount=0,this.bufferFullBehavior=e.bufferFullBehavior,this.shouldSkipSends=e.shouldSkipSends}send(e){return A(this,void 0,void 0,function*(){let t=this.getChannel();if(t){switch(this.bufferFullBehavior){case"wait":this.isBelowHighWaterMark(t)||(yield this.waitForHeadroomWithLock());break;case"drop":if(!this.isBelowLowWaterMark(t)){this.dropCount+=1,this.dropCount%100===0&&ye.warn("dropping lossy data channel messages, total dropped: ".concat(this.dropCount));return}}if(this.statCurrentBytes+=e.byteLength,!this.shouldSkipSends())try{t.send(e),this.refreshBufferStatus()}catch(n){if(n instanceof TypeError)ye.error(n);else throw n}}})}startThresholdTuning(){this.stopThresholdTuning(),this.statInterval=Le.setInterval(()=>{this.statByterate=this.statCurrentBytes,this.statCurrentBytes=0;let e=this.getChannel();if(e){let t=this.statByterate/10;e.bufferedAmountLowThreshold=Math.min(Math.max(t,this.lowWaterMark),this.highWaterMark)}},1e3)}stopThresholdTuning(){this.statByterate=0,this.statCurrentBytes=0,this.statInterval&&(Le.clearInterval(this.statInterval),this.statInterval=void 0),this.dropCount=0}},ta=class{constructor(){this.buffer=[],this._totalSize=0,this._sentSize=0}push(e){this.buffer.push(e),this._totalSize+=e.data.byteLength,e.sent&&(this._sentSize+=e.data.byteLength)}pop(){let e=this.buffer.shift();return e&&(this._totalSize-=e.data.byteLength,e.sent&&(this._sentSize-=e.data.byteLength)),e}getAll(){return this.buffer.slice()}getUnsent(){return this.buffer.filter(e=>!e.sent)}markSent(e){e.sent||(e.sent=!0,this._sentSize+=e.data.byteLength)}markAllUnsent(){for(let e of this.buffer)e.sent=!1;this._sentSize=0}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(!t.sent||this._sentSize-t.data.byteLength<=e)break;this.pop()}}get length(){return this.buffer.length}},Eu=class extends Zo{constructor(e){super(e),this.messageBuffer=new ta,this.sequence=1,this.isDeferringSends=e.isDeferringSends}nextSequence(){let e=this.sequence;return this.sequence+=1,e}send(e,t){return A(this,void 0,void 0,function*(){if(this.isDeferringSends()){this.messageBuffer.push({data:e,sequence:t,sent:!1});return}let n=this.getChannel();if(n){try{yield this.waitForHeadroomWithLock()}catch(r){if(this.isEngineClosed())throw r;this.messageBuffer.push({data:e,sequence:t,sent:!1});return}if(this.isDeferringSends()){this.messageBuffer.push({data:e,sequence:t,sent:!1});return}this.messageBuffer.push({data:e,sequence:t,sent:!0}),n.send(e),this.refreshBufferStatus()}})}replay(e){return A(this,void 0,void 0,function*(){let t=this.getChannel();if(!t)return;this.messageBuffer.popToSequence(e);let n=yield this.lockHeadroom();try{this.messageBuffer.markAllUnsent();for(let r=this.messageBuffer.getUnsent();r.length>0;r=this.messageBuffer.getUnsent())for(let s of r)yield this.waitForHeadroomWithoutLock(),t.send(s.data),this.messageBuffer.markSent(s)}finally{n()}this.refreshBufferStatus()})}refreshBufferStatus(){let e=this.channelHandle;e&&this.messageBuffer.alignBufferedAmount(e.bufferedAmount),super.refreshBufferStatus()}reset(){this.messageBuffer=new ta,this.sequence=1}},Te;(function(i){i[i.RELIABLE=0]="RELIABLE",i[i.LOSSY=1]="LOSSY",i[i.DATA_TRACK_LOSSY=2]="DATA_TRACK_LOSSY"})(Te||(Te={}));var Nw=64*1024,Fw=1024*1024,Uw=8*1024,jw=256*1024;function Bw(i){return i===Te.RELIABLE?Nw:Uw}function qw(i){return i===Te.RELIABLE?Fw:jw}var Hg="_lossy",Kg="_reliable",zg="_data_track",Pu=class{constructor(e){this.opts=e;let t=n=>({kind:n,lowWaterMark:Bw(n),highWaterMark:qw(n),isEngineClosed:e.isEngineClosed,onBufferStatusChanged:r=>e.onBufferStatusChanged(n,r)});this.reliable=new Eu(Object.assign(Object.assign({},t(Te.RELIABLE)),{isDeferringSends:e.isReconnecting})),this.lossy=new ea(Object.assign(Object.assign({},t(Te.LOSSY)),{bufferFullBehavior:"drop",shouldSkipSends:e.isReconnecting})),this.dataTrack=new ea(Object.assign(Object.assign({},t(Te.DATA_TRACK_LOSSY)),{bufferFullBehavior:"wait",shouldSkipSends:e.isReconnecting}))}channelFor(e){switch(e){case Te.RELIABLE:return this.reliable;case Te.LOSSY:return this.lossy;case Te.DATA_TRACK_LOSSY:return this.dataTrack}}getHandle(e){if(!(arguments.length>1&&arguments[1]!==void 0?arguments[1]:!1))return this.channelFor(e).channelHandle;switch(e){case Te.RELIABLE:return this.reliableSub;case Te.LOSSY:return this.lossySub;case Te.DATA_TRACK_LOSSY:return this.dataTrackSub}}get hasPublisherChannels(){return!!(this.reliable.channelHandle||this.lossy.channelHandle||this.dataTrack.channelHandle)}createPublisherChannels(e){for(let n of[this.lossy,this.reliable,this.dataTrack]){let r=n.channelHandle;r&&(r.onmessage=null,r.onerror=null,r.onclose=null)}let t=(n,r,s)=>{r.onmessage=s,r.onerror=this.opts.onDataError,r.onclose=()=>this.opts.onChannelClose(n.kind),r.bufferedAmountLowThreshold=n.lowWaterMark,r.onbufferedamountlow=()=>n.refreshBufferStatus(),n.attach(r)};
75t(this.lossy,e.createPublisherDataChannel(Hg,{ordered:!1,maxRetransmits:0}),this.opts.onDataMessage),t(this.reliable,e.createPublisherDataChannel(Kg,{ordered:!0}),this.opts.onDataMessage),t(this.dataTrack,e.createPublisherDataChannel(zg,{ordered:!1,maxRetransmits:0}),this.opts.onDataTrackMessage),this.lossy.startThresholdTuning()}adoptSubscriberChannel(e){let t;if(e.label===Kg)this.reliableSub=e,t=this.opts.onDataMessage;else if(e.label===Hg)this.lossySub=e,t=this.opts.onDataMessage;else if(e.label===zg)this.dataTrackSub=e,t=this.opts.onDataTrackMessage;else return!1;return e.onmessage=t,!0}teardown(){let e=t=>{t&&(t.onbufferedamountlow=null,t.onclose=null,t.onclosing=null,t.onerror=null,t.onmessage=null,t.onopen=null,t.close())};for(let t of[this.lossy,this.reliable,this.dataTrack]){let n=t.channelHandle;t.detach("peer connections cleaned up"),e(n)}e(this.lossySub),e(this.reliableSub),e(this.dataTrackSub),this.lossySub=void 0,this.reliableSub=void 0,this.dataTrackSub=void 0,this.reliable.reset()}},$d=typeof MediaRecorder<"u",Au=class{constructor(){throw new Error("MediaRecorder is not available in this environment")}},Vw=$d?MediaRecorder:Au,Mu=class extends Vw{constructor(e,t){if(!$d)throw new Error("MediaRecorder is not available in this environment");super(new MediaStream([e.mediaStreamTrack]),t);let n,r,s=()=>r===void 0,o=()=>{this.removeEventListener("dataavailable",n),this.removeEventListener("stop",o),this.removeEventListener("error",a),r?.close(),r=void 0},a=d=>{r?.error(d),this.removeEventListener("dataavailable",n),this.removeEventListener("stop",o),this.removeEventListener("error",a),r=void 0};this.byteStream=new ReadableStream({start:d=>{r=d,n=l=>A(this,void 0,void 0,function*(){let f;if(l.data.arrayBuffer){let p=yield l.data.arrayBuffer();f=new Uint8Array(p)}else if(l.data.byteArray)f=l.data.byteArray;else throw new Error("no data available!");s()||d.enqueue(f)}),this.addEventListener("dataavailable",n)},cancel:()=>{o()}}),this.addEventListener("stop",o),this.addEventListener("error",a)}};function $w(){return $d}var Ww=1e3,Gw=1e4,na=class extends J{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,s=arguments.length>4?arguments[4]:void 0;super(e,t,s),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=Fd(()=>A(this,void 0,void 0,function*(){yield this.pauseUpstream()}),5e3),this.handleTrackUnmuteEvent=()=>A(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(re.Ended,this)},this.reacquireTrack=!1,this.providedByUser=r,this.muteLock=new tt,this.pauseUpstreamLock=new tt,this.trackChangeLock=new tt,this.trackChangeLock.lock().then(o=>A(this,void 0,void 0,function*(){try{yield this.setMediaStreamTrack(e,!0)}finally{o()}})),this._constraints=e.getConstraints(),n&&(this._constraints=n)}get id(){return this._mediaStreamTrack.id}get dimensions(){if(this.kind!==J.Kind.Video)return;let e=this._mediaStreamTrack.getSettings(),t=e.width,n=e.height;if(t&&n)return{width:t,height:n}}get isUpstreamPaused(){return this._isUpstreamPaused}get isUserProvided(){return this.providedByUser}get mediaStreamTrack(){var e,t;return(t=(e=this.processor)===null||e===void 0?void 0:e.processedTrack)!==null&&t!==void 0?t:this._mediaStreamTrack}get isLocal(){return!0}getSourceTrackSettings(){return this._mediaStreamTrack.getSettings()}setMediaStreamTrack(e,t,n){return A(this,void 0,void 0,function*(){var r;if(e===this._mediaStreamTrack&&!t)return;
75this._mediaStreamTrack&&(this.attachedElements.forEach(o=>{br(this._mediaStreamTrack,o)}),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 s;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&&(mr(e,this.processorElement),this.processorElement.muted=!0),yield this.processor.restart({track:e,kind:this.kind,element:this.processorElement,localTrack:this}),s=this.processor.processedTrack}this.sender&&((r=this.sender.transport)===null||r===void 0?void 0:r.state)!=="closed"&&(yield this.sender.replaceTrack(s??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(o=>{mr(s??e,o)}))})}waitForDimensions(){return A(this,arguments,void 0,function(){var e=this;let t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:Ww;return(function*(){var n;if(e.kind===J.Kind.Audio)throw new Error("cannot get dimensions for audio tracks");((n=bt())===null||n===void 0?void 0:n.os)==="iOS"&&(yield ft(10));let r=Date.now();for(;Date.now()-r<t;){let s=e.dimensions;if(s)return s;yield ft(50)}throw new Yt("unable to get track dimensions after timeout")})()})}setDeviceId(e){return A(this,void 0,void 0,function*(){return this._constraints.deviceId===e&&this._mediaStreamTrack.getSettings().deviceId===Sr(e)?!0:(this._constraints.deviceId=e,this.isMuted?(this.pendingDeviceChange=!0,!0):(yield this.restartTrack(),Sr(e)===this._mediaStreamTrack.getSettings().deviceId))})}getDeviceId(){return A(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===J.Source.ScreenShare)return;let n=e._mediaStreamTrack.getSettings(),r=n.deviceId,s=n.groupId,o=e.kind===J.Kind.Audio?"audioinput":"videoinput";return t?Mt.getInstance().normalizeDeviceId(o,r,s):r})()})}mute(){return A(this,void 0,void 0,function*(){return this.setTrackMuted(!0),this})}unmute(){return A(this,void 0,void 0,function*(){return this.setTrackMuted(!1),this})}replaceTrack(e,t){return A(this,void 0,void 0,function*(){let n=yield this.trackChangeLock.lock();try{if(!this.sender)throw new Yt("unable to replace an unpublished track");let r,s;typeof t=="boolean"?r=t:t!==void 0&&(r=t.userProvidedTrack,s=t.stopProcessor),this.providedByUser=r??!0,this.log.debug("replace MediaStreamTrack",this.logContext),yield this.setMediaStreamTrack(e),s&&this.processor&&(yield this.internalStopProcessor())}finally{n()}return yield this.onSenderTrackSwapped(),this})}onSenderTrackSwapped(){return A(this,void 0,void 0,function*(){})}restart(e,t){return A(this,void 0,void 0,function*(){this.manuallyStopped=!1;let n=yield this.trackChangeLock.lock();try{e||(e=this._constraints);let r=e,s=r.deviceId,o=r.facingMode,a=iC(e,["deviceId","facingMode"]);this.log.debug("restarting track with constraints",Object.assign(Object.assign({},this.logContext),{constraints:e}));let d={audio:!1,video:!1};this.kind===J.Kind.Video?d.video=s||o?{deviceId:s,facingMode:o}:!0:d.audio=s?Object.assign({deviceId:s},a):!0,this.attachedElements.forEach(p=>{br(this.mediaStreamTrack,p)}),this._mediaStreamTrack.removeEventListener("ended",this.handleEnded),this._mediaStreamTrack.stop();let f=(yield navigator.mediaDevices.getUserMedia(d)).getTracks()[0];return this.kind===J.Kind.Video&&(yield f.applyConstraints(a)),f.addEventListener("ended",this.handleEnded),this.log.debug("re-acquired MediaStreamTrack",this.logContext),yield this.setMediaStreamTrack(f,!1,t),this._constraints=e,this.pendingDeviceChange=!1,this.emit
75(re.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 ".concat(this.kind," track ").concat(e?"muted":"unmuted"),this.logContext),!(this.isMuted===e&&this._mediaStreamTrack.enabled!==e)&&(this.isMuted=e,this._mediaStreamTrack.enabled=!e,this.emit(e?re.Muted:re.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 A(this,void 0,void 0,function*(){yield e.handleAppVisibilityChanged.call(this),Zy()&&(this.log.debug("visibility changed, is in Background: ".concat(this.isInBackground),this.logContext),!this.isInBackground&&this.needsReAcquisition&&!this.isUserProvided&&!this.isMuted&&(this.log.debug("track needs to be reacquired, restarting ".concat(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===void 0||e.destroy(),this.processor=void 0}pauseUpstream(){return A(this,void 0,void 0,function*(){var e;let t=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(re.UpstreamPaused,this);let n=bt();if(n?.name==="Safari"&&fn(n.version,"12.0")<0)throw new ks("pauseUpstream is not supported on Safari < 12.");((e=this.sender.transport)===null||e===void 0?void 0:e.state)!=="closed"&&(yield this.sender.replaceTrack(null))}finally{t()}})}resumeUpstream(){return A(this,void 0,void 0,function*(){var e;let t=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(re.UpstreamResumed,this),((e=this.sender.transport)===null||e===void 0?void 0:e.state)!=="closed"&&(yield this.sender.replaceTrack(this.mediaStreamTrack))}finally{t()}})}getRTCStatsReport(){return A(this,void 0,void 0,function*(){var e;return!((e=this.sender)===null||e===void 0)&&e.getStats?yield this.sender.getStats():void 0})}setProcessor(e){return A(this,arguments,void 0,function(t){var n=this;let r=arguments.length>1&&arguments[1]!==void 0?arguments[1]:!0;return(function*(){var s;let o=yield n.trackChangeLock.lock();try{n.log.debug("setting up processor",n.logContext);let a=document.createElement(n.kind),d={kind:n.kind,track:n._mediaStreamTrack,element:a,audioContext:n.audioContext,localTrack:n};if(yield t.init(d),n.log.debug("processor initialized",n.logContext),n.processor&&(yield n.internalStopProcessor()),n.kind==="unknown")throw TypeError("cannot set processor on track of unknown kind");if(mr(n._mediaStreamTrack,a),a.muted=!0,a.play().catch(l=>{l instanceof DOMException&&l.name==="AbortError"?(n.log.warn("failed to play processor element, retrying",Object.assign(Object.assign({},n.logContext),{error:l})),setTimeout(()=>{a.play().catch(f=>{n.log.error("failed to play processor element",Object.assign(Object.assign({},n.logContext),{err:f}))})},100)):n.log.error("failed to play processor element",Object.assign(Object.assign({},n.logContext),{error:l}))}),n.processor=t,n.processorElement=a,n.processor.processedTrack){for(let l of n.attachedElements)l!==n.processorElement&&r&&(br(n._mediaStreamTrack,l),mr(n.processor.processedTrack,l));yield(s=n.sender)===null||s===void 0?void 0:s.replaceTrack(n.processor.processedTrack)}n.emit(re.TrackProcessorUpdate,n.processor)}finally{o()}yield n.onSenderTrackSwapped()})()})}getProcessor(){return this.processor}stopProcessor(){return A(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()}yield e.onSenderTrackSwapped()})()})}internalStopProcessor(){return A(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===void 0||n.stop(),yield e.processor.destroy(),e.processor=void 0,t||((r=e.processorElement)===null||r===void 0||r.remove(),e.processorElement=void 0),yield e._mediaStreamTrack.applyConstraints(e._constraints),yield e.setMediaStreamTrack(e._mediaStreamTrack,!0),e.emit(re.TrackProcessorUpdate))})()})}startPreConnectBuffer(){let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:100;if(!$w()){this.log.warn("MediaRecorder is not available, cannot start prec
75onnect buffer",this.logContext);return}if(this.localTrackRecorder){this.log.warn("preconnect buffer already started");return}else{let t="audio/webm;codecs=opus";MediaRecorder.isTypeSupported(t)||(t="video/mp4"),this.localTrackRecorder=new Mu(this,{mimeType:t})}this.localTrackRecorder.start(e),this.autoStopPreConnectBuffer=setTimeout(()=>{this.log.warn("preconnect buffer timed out, stopping recording automatically",this.logContext),this.stopPreConnectBuffer()},Gw)}stopPreConnectBuffer(){clearTimeout(this.autoStopPreConnectBuffer),this.localTrackRecorder&&(this.localTrackRecorder.stop(),this.localTrackRecorder=void 0)}getPreConnectBuffer(){var e;return(e=this.localTrackRecorder)===null||e===void 0?void 0:e.byteStream}getPreConnectBufferMimeType(){var e;return(e=this.localTrackRecorder)===null||e===void 0?void 0:e.mimeType}},Ar=class extends na{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,s=arguments.length>4?arguments[4]:void 0;super(e,J.Kind.Audio,t,n,s),this.stopOnMute=!1,this.isKrispNoiseFilterEnabled=!1,this.monitorSender=()=>A(this,void 0,void 0,function*(){if(!this.sender){this._currentBitrate=0;return}let o;try{o=yield this.getSenderStats()}catch(a){this.log.error("could not get audio sender stats",Object.assign(Object.assign({},this.logContext),{error:a}));return}o&&this.prevStats&&(this._currentBitrate=Da(o,this.prevStats)),this.prevStats=o}),this.handleKrispNoiseFilterEnable=()=>{this.isKrispNoiseFilterEnabled=!0,this.log.debug("Krisp noise filter enabled",this.logContext),this.emit(re.AudioTrackFeatureUpdate,this,ot.TF_ENHANCED_NOISE_CANCELLATION,!0)},this.handleKrispNoiseFilterDisable=()=>{this.isKrispNoiseFilterEnabled=!1,this.log.debug("Krisp noise filter disabled",this.logContext),this.emit(re.AudioTrackFeatureUpdate,this,ot.TF_ENHANCED_NOISE_CANCELLATION,!1)},this.audioContext=r,this.checkForSilence()}mute(){let e=Object.create(null,{mute:{get:()=>super.mute}});return A(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===J.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 A(this,void 0,void 0,function*(){let t=yield this.muteLock.lock();try{return this.isMuted?(this.source===J.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 A(this,void 0,void 0,function*(){let t;if(e){let n=Ld({audio:e});typeof n.audio!="boolean"&&(t=n.audio)}yield this.restart(t)})}applyConstraints(e){return A(this,void 0,void 0,function*(){let t=yield this.trackChangeLock.lock();try{let n=yield this._mediaStreamTrack.applyConstraints(e);return this._constraints=Object.assign(Object.assign({},this._constraints),e),n}finally{t()}})}restart(e,t){let n=Object.create(null,{restart:{get:()=>super.restart}});return A(this,void 0,void 0,function*(){let r=yield n.restart.call(this,e,t);return this.checkForSilence(),r})}startMonitor(){St()&&(this.monitorInterval||(this.monitorInterval=setInterval(()=>{this.monitorSender()},Ud)))}setProcessor(e){return A(this,void 0,void 0,function*(){var t;let n=yield this.trackChangeLock.lock();try{if(!en()&&!this.audioContext)throw Error("Audio context needs to be set on LocalAudioTrack in order to enable processors");this.processor&&(yield this.internalStopProcessor());let r={kind:this.kind,track:this._mediaStreamTrack,audioContext:this.audioContext,localTrack:this};this.log.debug("setting up audio processor ".concat(e.name),this.logContext),yield e.init(r),this.processor=e,this.processor.processedTrack&&(yield(t=this.sender)===null||t===void 0?void 0:t.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
75(re.TrackProcessorUpdate,this.processor)}finally{n()}})}setAudioContext(e){this.audioContext=e}getSenderStats(){return A(this,void 0,void 0,function*(){var e;if(!(!((e=this.sender)===null||e===void 0)&&e.getStats))return;let t=yield this.sender.getStats(),n;return t.forEach(r=>{r.type==="outbound-rtp"&&(n={type:"audio",streamId:r.id,packetsSent:r.packetsSent,packetsLost:r.packetsLost,bytesSent:r.bytesSent,timestamp:r.timestamp,roundTripTime:r.roundTripTime,jitter:r.jitter})}),n})}checkForSilence(){return A(this,void 0,void 0,function*(){let e=yield zy(this);return e&&(this.isMuted||this.log.debug("silence detected on local audio track",this.logContext),this.emit(re.AudioSilenceDetected)),e})}};function Jw(i,e,t){switch(i.kind){case"audio":return new Ar(i,e,!1,void 0,t);case"video":return new Mr(i,e,!1,t);default:throw new Yt("unsupported track type: ".concat(i.kind))}}var Hw=Object.values(Ss),Kw=Object.values(au),zw=Object.values(Dd),Yw=[Ss.h180,Ss.h360],Qw=[au.h180,au.h360],Xw=i=>[{scaleResolutionDownBy:2,fps:i.encoding.maxFramerate}].map(t=>{var n,r;return new De(Math.floor(i.width/t.scaleResolutionDownBy),Math.floor(i.height/t.scaleResolutionDownBy),Math.max(15e4,Math.floor(i.encoding.maxBitrate/(Math.pow(t.scaleResolutionDownBy,2)*(((n=i.encoding.maxFramerate)!==null&&n!==void 0?n:30)/((r=t.fps)!==null&&r!==void 0?r:30))))),t.fps,i.encoding.priority)}),Ru=["q","h","f"];function ia(i,e,t,n){var r,s;let o=n?.videoEncoding;i&&(o=n?.screenShareEncoding);let a=n?.simulcast,d=n?.scalabilityMode,l=n?.videoCodec;if(!o&&!a&&!d||!e||!t)return[{}];o||(o=Zw(i,e,t,l),ye.debug("using video encoding",o));let f=o.maxFramerate,p=new De(e,t,o.maxBitrate,o.maxFramerate,o.priority);if(d&&un(l)){let I=new ra(d),N=[];if(I.spatial>3)throw new Error("unsupported scalabilityMode: ".concat(d));let L=bt();if(Ts()||en()||L?.name==="Chrome"&&fn(L?.version,"113")<0){let j=I.suffix=="h"?2:3,M=jC(L);for(let P=0;P<I.spatial;P+=1)N.push({rid:Ru[2-P],maxBitrate:o.maxBitrate/Math.pow(j,P),maxFramerate:p.encoding.maxFramerate,scaleResolutionDownBy:M?Math.pow(2,P):void 0});N[0].scalabilityMode=d}else N.push({maxBitrate:o.maxBitrate,maxFramerate:p.encoding.maxFramerate,scalabilityMode:d});return p.encoding.priority&&(N[0].priority=p.encoding.priority,N[0].networkPriority=p.encoding.priority),ye.debug("using svc encoding",{encodings:N}),N}if(!a)return[o];let g;i?g=(r=Qg(n?.screenShareSimulcastLayers))!==null&&r!==void 0?r:Yg(i,p):g=(s=Qg(n?.videoSimulcastLayers))!==null&&s!==void 0?s:Yg(i,p);let b;if(g.length>0){let I=g[0];if(g.length>1){var R=g,w=pe(R,2);b=w[1]}let N=Math.max(e,t);if(N>=960&&b)return Ml(e,t,[I,b,p],f);if(N>=480)return Ml(e,t,[I,p],f)}return Ml(e,t,[p])}function cb(i,e,t){var n,r,s,o;if(!t.backupCodec||t.backupCodec===!0||t.backupCodec.codec===t.videoCodec)return;e!==t.backupCodec.codec&&ye.warn("requested a different codec than specified as backup",{serverRequested:e,backup:t.backupCodec.codec}),t.videoCodec=e,t.videoEncoding=t.backupCodec.encoding;let a=i.mediaStreamTrack.getSettings(),d=(n=a.width)!==null&&n!==void 0?n:(r=i.dimensions)===null||r===void 0?void 0:r.width,l=(s=a.height)!==null&&s!==void 0?s:(o=i.dimensions)===null||o===void 0?void 0:o.height;return i.source===J.Source.ScreenShare&&t.simulcast&&(t.simulcast=!1),ia(i.source===J.Source.ScreenShare,d,l,t)}function Zw(i,e,t,n){let r=eE(i,e,t),s=r[0].encoding,o=Math.max(e,t);for(let a=0;a<r.length;a+=1){let d=r[a];if(s=d.encoding,d.width>=o)break}if(n)switch(n){case"av1":case"h265":s=Object.assign({},s),s.maxBitrate=s.maxBitrate*.7;break;case"vp9":s=Object.assign({},s),s.maxBitrate=s.maxBitrate*.85;break}return s}function eE(i,e,t){if(i)return zw;let n=e>t?e/t:t/e;return Math.abs(n-16/9)<Math.abs(n-4/3)?Hw:Kw}function Yg(i,e){if(i)return Xw(e);let t=e.width,n=e.height,r=t>n?t/n:n/t;return Math.abs(r-16/9)<Math.abs(r-4/3)?Yw:Qw}function Ml(i,e,t,n){let r=[];if(t.forEach((s,o)=>{if(o>=Ru.length)return;let a=Math.min(i,e),l={rid:Ru[o],scaleResolutionDownBy:Math.max(1,a/Math.min(s.width,s.height)),maxBitrate:s.encoding.maxBitrate},f=n&&s.encoding.maxFramerate?Math.min(n,s.encoding.maxFramerate):s.encoding.maxFramerate;f&&(l.maxFramerate=f);
75let p=bt(),g=p?.name==="Firefox"&&p.os!=="iOS"||o===0;s.encoding.priority&&g&&(l.priority=s.encoding.priority,l.networkPriority=s.encoding.priority),r.push(l)}),en()&&tb()==="ios"){let s;r.forEach(a=>{s?a.maxFramerate&&a.maxFramerate>s&&(s=a.maxFramerate):s=a.maxFramerate});let o=!0;r.forEach(a=>{var d;a.maxFramerate!=s&&(o&&(o=!1,ye.info("Simulcast on iOS React-Native requires all encodings to share the same framerate.")),ye.info('Setting framerate of encoding "'.concat((d=a.rid)!==null&&d!==void 0?d:"",'" to ').concat(s)),a.maxFramerate=s)})}return r}function Qg(i){if(i)return i.slice().sort((e,t)=>{let n=e.encoding,r=t.encoding;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 ra=class{constructor(e){let t=e.match(/^L(\d)T(\d)(h|_KEY|_KEY_SHIFT){0,1}$/);if(!t)throw new 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(){var e;return"L".concat(this.spatial,"T").concat(this.temporal).concat((e=this.suffix)!==null&&e!==void 0?e:"")}};function tE(i){switch(i.source){case J.Source.Camera:return"maintain-framerate";case J.Source.ScreenShare:return"maintain-resolution";default:return"balanced"}}var nE=5e3,Mr=class extends na{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,J.Kind.Video,t,n,r),this.simulcastCodecs=new Map,this.degradationPreference="balanced",this.isCpuConstrained=!1,this.optimizeForPerformance=!1,this.monitorSender=()=>A(this,void 0,void 0,function*(){if(!this.sender){this._currentBitrate=0;return}let s;try{s=yield this.getSenderStats()}catch(d){this.log.error("could not get video sender stats",Object.assign(Object.assign({},this.logContext),{error:d}));return}let o=new Map(s.map(d=>[d.rid,d])),a=s.some(d=>d.qualityLimitationReason==="cpu");if(a!==this.isCpuConstrained&&(this.isCpuConstrained=a,this.isCpuConstrained&&this.emit(re.CpuConstrained)),this.prevStats){let d=0;o.forEach((l,f)=>{var p;let g=(p=this.prevStats)===null||p===void 0?void 0:p.get(f);d+=Da(l,g)}),this._currentBitrate=d}this.prevStats=o}),this.senderLock=new tt}get isSimulcast(){return!!(this.sender&&this.sender.getParameters().encodings.length>1)}startMonitor(e){var t;if(this.signalClient=e,!St())return;let n=(t=this.sender)===null||t===void 0?void 0:t.getParameters();n&&(this.encodings=n.encodings),!this.monitorInterval&&(this.monitorInterval=setInterval(()=>{this.monitorSender()},Ud))}stop(){this._mediaStreamTrack.getConstraints(),this.simulcastCodecs.forEach(e=>{e.mediaStreamTrack.stop()}),super.stop()}pauseUpstream(){let e=Object.create(null,{pauseUpstream:{get:()=>super.pauseUpstream}});return A(this,void 0,void 0,function*(){var t,n,r,s,o;yield e.pauseUpstream.call(this);try{for(var a=!0,d=Ft(this.simulcastCodecs.values()),l;l=yield d.next(),t=l.done,!t;a=!0)s=l.value,a=!1,yield(o=s.sender)===null||o===void 0?void 0:o.replaceTrack(null)}catch(f){n={error:f}}finally{try{!a&&!t&&(r=d.return)&&(yield r.call(d))}finally{if(n)throw n.error}}})}resumeUpstream(){let e=Object.create(null,{resumeUpstream:{get:()=>super.resumeUpstream}});return A(this,void 0,void 0,function*(){var t,n,r,s,o;yield e.resumeUpstream.call(this);try{for(var a=!0,d=Ft(this.simulcastCodecs.values()),l;l=yield d.next(),t=l.done,!t;a=!0){s=l.value,a=!1;let f=s;yield(o=f.sender)===null||o===void 0?void 0:o.replaceTrack(f.mediaStreamTrack)}}catch(f){n={error:f}}finally{try{!a&&!t&&(r=d.return)&&(yield r.call(d))}finally{if(n)throw n.error}}})}mute(){let e=Object.create(null,{mute:{get:()=>super.mute}});return A(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===J.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 A(this,void 0,void 0,function*(){let t=yield this.muteLock.lock();try{return this.isMuted?(this.source===J.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 A(this,void 0,void 0,function*(){var e;if(!(!((e=this.sender)===null||e===void 0)&&e.getStats))return[];let t=[],n=yield this.sender.getStats();
75return n.forEach(r=>{var s;if(r.type==="outbound-rtp"){let o={type:"video",streamId:r.id,frameHeight:r.frameHeight,frameWidth:r.frameWidth,framesPerSecond:r.framesPerSecond,framesSent:r.framesSent,firCount:r.firCount,pliCount:r.pliCount,nackCount:r.nackCount,packetsSent:r.packetsSent,bytesSent:r.bytesSent,qualityLimitationReason:r.qualityLimitationReason,qualityLimitationDurations:r.qualityLimitationDurations,qualityLimitationResolutionChanges:r.qualityLimitationResolutionChanges,rid:(s=r.rid)!==null&&s!==void 0?s:r.id,retransmittedPacketsSent:r.retransmittedPacketsSent,targetBitrate:r.targetBitrate,timestamp:r.timestamp},a=n.get(r.remoteId);a&&(o.jitter=a.jitter,o.packetsLost=a.packetsLost,o.roundTripTime=a.roundTripTime),t.push(o)}}),t.sort((r,s)=>{var o,a;return((o=s.frameWidth)!==null&&o!==void 0?o:0)-((a=r.frameWidth)!==null&&a!==void 0?a:0)}),t})}setPublishingQuality(e){let t=[];for(let n=At.LOW;n<=At.HIGH;n+=1)t.push(new Md({quality:n,enabled:n<=e}));this.log.debug("setting publishing quality. max quality ".concat(e),this.logContext),this.setPublishingLayers(un(this.codec),t)}restartTrack(e){return A(this,void 0,void 0,function*(){var t,n,r,s,o;let a;if(e){let p=Ld({video:e});typeof p.video!="boolean"&&(a=p.video)}yield this.restart(a),this.isCpuConstrained=!1;try{for(var d=!0,l=Ft(this.simulcastCodecs.values()),f;f=yield l.next(),t=f.done,!t;d=!0){s=f.value,d=!1;let p=s;p.sender&&((o=p.sender.transport)===null||o===void 0?void 0:o.state)!=="closed"&&(p.mediaStreamTrack=this.mediaStreamTrack.clone(),yield p.sender.replaceTrack(p.mediaStreamTrack))}}catch(p){n={error:p}}finally{try{!d&&!t&&(r=l.return)&&(yield r.call(l))}finally{if(n)throw n.error}}yield this.onSenderTrackSwapped()})}onSenderTrackSwapped(){return A(this,void 0,void 0,function*(){yield this.refreshSen
75derEncodings()})}refreshSenderEncodings(){return A(this,void 0,void 0,function*(){var e;if(!this.sender||!this.publishOptions||this.optimizeForPerformance)return;let t=yield this.senderLock.lock();try{let r;try{r=yield this.waitForDimensions()}catch(a){this.log.warn("could not determine new track dimensions, skipping encoding recompute",Object.assign(Object.assign({},this.logContext),{error:a}));return}if(this.lastEncodedDimensions&&this.lastEncodedDimensions.width===r.width&&this.lastEncodedDimensions.height===r.height)return;let s=this.source===J.Source.ScreenShare,o=ia(s,r.width,r.height,Object.assign({},this.publishOptions));yield this.applyEncodingsToSender(this.sender,o),this.encodings=o,this.lastEncodedDimensions=r;for(let a of this.simulcastCodecs){var n=pe(a,2);let d=n[0],l=n[1];if(!l.sender||((e=l.sender.transport)===null||e===void 0?void 0:e.state)==="closed"||!Hy(d))continue;let f=Object.assign({},this.publishOptions),p=cb(this,d,f);p&&(yield this.applyEncodingsToSender(l.sender,p),l.encodings=p)}}catch(r){this.log.warn("failed to apply recomputed encodings",Object.assign(Object.assign({},this.logContext),{error:r}))}finally{t()}})}applyEncodingsToSender(e,t){return A(this,void 0,void 0,function*(){let n=e.getParameters();!n.encodings||n.encodings.length!==t.length||(n.encodings.forEac
75h((r,s)=>{if(r.active===!1)return;let o=t[s];o.scaleResolutionDownBy!==void 0&&(r.scaleResolutionDownBy=o.scaleResolutionDownBy),o.maxBitrate!==void 0&&(r.maxBitrate=o.maxBitrate),o.maxFramerate!==void 0&&(r.maxFramerate=o.maxFramerate),o.priority!==void 0&&(r.priority=o.priority,r.networkPriority=o.priority)}),this.log.debug("updating sender encodings after track restart",Object.assign(Object.assign({},this.logContext),{encodings:n.encodings})),yield e.setParameters(n))})}setProcessor(e){let t=Object.create(null,{setProcessor:{get:()=>super.setProcessor}});return A(this,arguments,void 0,function(n){var r=this;let s=arguments.length>1&&arguments[1]!==void 0?arguments[1]:!0;return(function*(){var o,a,d,l,f,p;if(yield t.setProcessor.call(r,n,s),!((f=r.processor)===null||f===void 0)&&f.processedTrack)try{for(var g=!0,b=Ft(r.simulcastCodecs.values()),R;R=yield b.next(),o=R.done,!o;g=!0)l=R.value,g=!1,yield(p=l.sender)===null||p===void 0?void 0:p.replaceTrack(r.processor.processedTrack)}catch(w){a={error:w}}finally{try{!g&&!o&&(d=b.return)&&(yield d.call(b))}finally{if(a)throw a.error}}})()})}setDegradationPreference(e){return A(this,void 0,void 0,function*(){this.degradationPreference=e,yield this.applyDegradationPreference(this.sender);for(let t of this.simulcastCodecs.values())yield this.applyDegradationPreference(t.sender)})}applyDegradationPreference(e){return A(this,void 0,void 0,function*(){if(e)try{this.log.debug("setting degradationPreference to ".concat(this.degradationPreference),this.logContext);let t=e.getParameters();t.degradationPreference=this.degradationPreference,yield e.setParameters(t)}catch(t){this.log.warn("failed to set degradationPreference",Object.assign({error:t},this.logContext))}})}addSimulcastTrack(e,t){if(this.simulcastCodecs.has(e)){this.log.error("".concat(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){return A(this,void 0,void 0,function*(){let n=this.simulcastCodecs.get(e);n&&(n.sender=t,yield this.applyDegradationPreference(t),setTimeout(()=>{this.subscribedCodecs&&this.setPublishingCodecs(this.subscribedCodecs)},nE))})}setPublishingCodecs(e){return A(this,void 0,void 0,function*(){var t,n,r,s,o,a,d;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(un(e[0].codec),e[0].qualities),[];this.subscribedCodecs=e;let l=[];try{for(t=!0,n=Ft(e);r=yield n.next(),s=r.done,!s;t=!0){d=r.value,t=!1;let f=d;if(!this.codec||this.codec===f.codec)yield this.setPublishingLayers(un(f.codec),f.qualities);else{let p=this.simulcastCodecs.get(f.codec);if(this.log.debug("try setPublishingCodec for ".concat(f.codec),Object.assign(Object.assign({},this.logContext),{simulcastCodecInfo:p})),!p||!p.sender){for(let g of f.qualities)if(g.enabled){l.push(f.codec);break}}else p.encodings&&(this.log.debug("try setPublishingLayersForSender ".concat(f.codec),this.logContext),yield Xg(p.sender,p.encodings,f.qualities,this.senderLock,un(f.codec),this.log,this.logContext))}}}catch(f){o={error:f}}finally{try{!t&&!s&&(a=n.return)&&(yield a.call(n))}finally{if(o)throw o.error}}return l})}setPublishingLayers(e,t){return A(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 Xg(this.sender,this.encodings,t,this.senderLock,e,this.log,this.logContext))})}prioritizePerformance(){return A(this,void 0,void 0,function*(){if(!this.sender)throw new Error("sender not found");let e=yield this.senderLock.lock();try{this.optimizeForPerformance=!0;let t=this.sender.getParameters();t.encodings=t.encodings.map((n,r)=>{var s;return Object.assign(Object.assign({},n),{active:r===0,scaleResolutionDownBy:Math.max(1,Math.ceil(((s=this.mediaStreamTrack.getSettings().height)!==null&&s!==void 0?s:360)/360)),scalabilityMode:r===0&&un(this.codec)?"L1T3":void 0,maxFramerate:r===0?15:0,maxBitrate:r===0?n.maxBitrate:0})}),this.log.debug("setting performance optimised encodings",Object.assign(Object.assign({},this.logContext),{encodings:t.encodings})),this.encodings=t.encodings,yield this.sender.setParameters(t)}catch(t){this.log.error("failed to set performance optimised encodings",Object.assign(Object.assign({},this.logContext),{error:t})),this.optimizeForPerformance=!1}finally{e()}})}handleAppVisibilityChanged(){let e=Object.create(null,{handleAppVisibilityChanged:{get:()=>super.handleAppVisibilityChanged}});return A(this,void 0,void 0,function*(){yield e.handleAppVisibilityChanged.call(this),Zy()&&this.isInBackgroun
75d&&this.source===J.Source.Camera&&(this._mediaStreamTrack.enabled=!1)})}};function Xg(i,e,t,n,r,s,o){return A(this,void 0,void 0,function*(){let a=yield n.lock();s.debug("setPublishingLayersForSender",Object.assign(Object.assign({},o),{sender:i,qualities:t,senderEncodings:e}));try{let d=i.getParameters(),l=d.encodings;if(!l)return;if(l.length!==e.length){s.warn("cannot set publishing layers, encodings mismatch",Object.assign(Object.assign({},o),{encodings:l,senderEncodings:e}));return}let f=!1;!1&&l[0].scalabilityMode||(r&&t.some(b=>b.enabled)&&t.forEach(b=>b.enabled=!0),l.forEach((g,b)=>{var R;let w=(R=g.rid)!==null&&R!==void 0?R:"";w===""&&(w="q");let I=lb(w),N=t.find(L=>L.quality===I);N&&g.active!==N.enabled&&(f=!0,g.active=N.enabled,s.debug("setting layer ".concat(N.quality," to ").concat(g.active?"enabled":"disabled"),o),Oi()&&(N.enabled?(g.scaleResolutionDownBy=e[b].scaleResolutionDownBy,g.maxBitrate=e[b].maxBitrate,g.maxFrameRate=e[b].maxFrameRate):(g.scaleResolutionDownBy=4,g.maxBitrate=10,g.maxFrameRate=2)))})),f&&(d.encodings=l,s.debug("setting encodings",Object.assign(Object.assign({},o),{encodings:d.encodings})),yield i.setParameters(d))}finally{a()}})}function lb(i){switch(i){case"f":return At.HIGH;case"h":return At.MEDIUM;case"q":return At.LOW;default:return At.HIGH}}function Zg(i,e,t,n){if(!t)return[new Qn({quality:At.HIGH,width:i,height:e,bitrate:0,ssrc:0})];if(n){let r=t[0].scalabilityMode,s=new ra(r),o=[],a=s.suffix=="h"?1.5:2,d=s.suffix=="h"?2:3;for(let l=0;l<s.spatial;l+=1)o.push(new Qn({quality:Math.min(At.HIGH,s.spatial-1)-l,width:Math.ceil(i/Math.pow(a,l)),height:Math.ceil(e/Math.pow(a,l)),bitrate:t[0].maxBitrate?Math.ceil(t[0].maxBitrate/Math.pow(d,l)):0,ssrc:0}));return o}return t.map(r=>{var s,o,a;let d=(s=r.scaleResolutionDownBy)!==null&&s!==void 0?s:1,l=lb((o=r.rid)!==null&&o!==void 0?o:"");return new Qn({quality:l,width:Math.ceil(i/d),height:Math.ceil(e/d),bitrate:(a=r.maxBitrate)!==null&&a!==void 0?a:0,ssrc:0})})}var iE=2*1e3,Rl="leave-reconnect",rE=10*1e3,sE=3e4,oE=3,aE=3,Pt;(function(i){i[i.New=0]="New",i[i.Connected=1]="Connected",i[i.Disconnected=2]="Disconnected",i[i.Reconnecting=3]="Reconnecting",i[i.Closed=4]="Closed"})(Pt||(Pt={}));var ev=64e3,Iu=class extends _t.EventEmitter{get isClosed(){return this._isClosed}get isNewlyCreated(){return this._isNewlyCreated}get pendingReconnect(){return!!this.reconnectTimeout}get reliableChannel(){return this.dataChannels.reliable}get lossyChannel(){return this.dataChannels.lossy}get dataTrackChannel(){return this.dataChannels.dataTrack}constructor(e){var t;super(),this.options=e,this.rtcConfig={},this.peerConnectionTimeout=Vd.peerConnectionTimeout,this.fullReconnectOnNext=!1,this.latestRemoteOfferId=0,this.subscriberPrimary=!1,this.pcState=Pt.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.shouldFailOnV1Path=!1,this.log=ye,this.reliableReceivedState=new Cu(sE),this.midToTrackId={},this.isWaitingForNetworkReconnect=!1,this.handleDataChannel=n=>A(this,[n],void 0,function(r){var s=this;let o=r.channel;return(function*(){o&&s.dataChannels.adoptSubscriberChannel(o)&&s.log.debug("on data channel ".concat(o.id,", ").concat(o.label))})()}),this.handleDataMessage=n=>A(this,void 0,void 0,function*(){var r,s,o,a,d;let l=yield this.dataProcessLock.lock();try{let f=yield this.decodeDataMessage(n);if(!f)return;let p=yt.fromBinary(f);if(p.sequence>0&&p.participantSid!==""){let g=this.reliableReceivedState.get(p.participantSid);if(g&&p.sequence<=g)return;this.reliableReceivedState.set(p.participantSid,p.sequence)}if(((r=p.value)===null||r===void 0?void 0:r.case)==="speaker")this.emit(X.ActiveSpeakersUpdate,p.value.value.speakers);else if(((s=p.value)===null||s===void 0?void 0:s.case)==="encryptedPacket"){if(!this.e2eeManager){this.log.error("Received encrypted packet but E2EE not set up");return}let g=yield(o=this.e2eeManager)===null||o===void 0?void 0:o.handleEncryptedData(p.value.value.encryptedValue,p.value.value.iv,p.participantIdentity,p.value.value.keyIndex),b=Bv.fromBinary(g.payload),R=new yt({value:b.value,participantIdentity:p.participantIdentity,participantSid:p.participantSid});((a=R.value)===null||a===void 0?void 0:a.case)==="user"&&tv(R,R.value.value),this.emit
75(X.DataPacketReceived,R,p.value.value.encryptionType)}else((d=p.value)===null||d===void 0?void 0:d.case)==="user"&&tv(p,p.value.value),this.emit(X.DataPacketReceived,p,Ie.NONE)}finally{l()}}),this.handleDataTrackMessage=n=>A(this,void 0,void 0,function*(){let r=yield this.decodeDataMessage(n);r&&this.emit("dataTrackPacketReceived",r)}),this.handleDataError=n=>{if(this._isClosed)return;let s=n.currentTarget.maxRetransmits===0?"lossy":"reliable";if(typeof RTCErrorEvent<"u"&&n instanceof RTCErrorEvent&&n.error){let o=n.error;this.log.error("DataChannel error on ".concat(s,": ").concat(o.message),{error:o,errorDetail:o.errorDetail,sctpCauseCode:o.sctpCauseCode})}else this.log.error("Unknown DataChannel error on ".concat(s),{event:n})},this.handleDataChannelClose=n=>()=>{var r;!this._isClosed&&((r=this.pcManager)===null||r===void 0?void 0:r.publisher.getConnectionState())==="connected"&&this.log.error("publisher data channel '".concat(Te[n],"' closed unexpectedly"),this.logContext)},this.handleDisconnect=(n,r)=>{if(this._isClosed)return;this.log.warn("".concat(n," disconnected")),this.reconnectAttempts===0&&(this.reconnectStart=Date.now());let s=d=>{this.log.warn("could not recover connection after ".concat(this.reconnectAttempts," attempts, ").concat(d,"ms. giving up")),this.emit(X.Disconnected),this.close()},o=Date.now()-this.reconnectStart,a=this.getNextRetryDelay({elapsedMs:o,retryCount:this.reconnectAttempts});if(a===null){s(o);return}n===Rl&&(a=0),this.log.debug("reconnecting in ".concat(a,"ms")),this.clearReconnectTimeout(),this.token&&this.emit(X.TokenRefreshed,this.token),this.reconnectTimeout=Le.setTimeout(()=>this.attemptReconnect(r).finally(()=>this.reconnectTimeout=void 0),a)},this.waitForRestarted=()=>new Promise((n,r)=>{this.pcState===Pt.Connected&&n();let s=()=>{this.off(X.Disconnected,o),n()},o=()=>{this.off(X.Restarted,s),r()};this.once(X.Restarted,s),this.once(X.Disconnected,o)}),this.onRtpMapAvailable=n=>{let r=new Map;n.forEach(s=>{let o=s.codec.toLowerCase();nb(o)&&r.set(s.payload,o)}),this.emit(X.RTPVideoMapUpdate,r)},this.handleBrowserOnLine=()=>A(this,void 0,void 0,function*(){!this.url||!(yield fetch(_s(this.url),{method:"HEAD"}).then(r=>r.ok).catch(()=>!1))||(this.log.info("detected network reconnected"),(this.client.currentState===Fe.RECONNECTING||this.isWaitingForNetworkReconnect&&this.client.currentState===Fe.CONNECTED)&&(this.clearReconnectTimeout(),this.attemptReconnect(Mn.RR_SIGNAL_DISCONNECTED),this.isWaitingForNetworkReconnect=!1))}),this.handleBrowserOffline=()=>A(this,void 0,void 0,function*(){if(this.url)try{yield Promise.race([fetch(_s(this.url),{method:"HEAD"}),ft(4e3).then(()=>Promise.reject())])}catch{window.navigator.onLine===!1&&(this.log.info("detected network interruption"),this.isWaitingForNetworkReconnect=!0)}}),this.log=ut((t=e.loggerName)!==null&&t!==void 0?t:Xe.Engine,()=>this.logContext),this.loggerOptions={loggerName:e.loggerName,loggerContextCb:()=>this.logContext},this.client=new As(void 0,this.loggerOptions),this.client.signalLatency=this.options.expSignalLatency,this.reconnectPolicy=this.options.reconnectPolicy,this.closingLock=new tt,this.dataProcessLock=new tt,this.dataChannels=new Pu({isEngineClosed:()=>this.isClosed,isReconnecting:()=>this.attemptingReconnect,onDataMessage:n=>this.handleDataMessage(n),onDataTrackMessage:n=>this.handleDataTrackMessage(n),onDataError:n=>this.handleDataError(n),onChannelClose:n=>this.handleDataChannelClose(n)(),onBufferStatusChanged:(n,r)=>this.emit(X.DCBufferStatusChanged,r,n)}),this.client.onParticipantUpdate=n=>this.emit(X.ParticipantUpdate,n),this.client.onConnectionQuality=n=>{this.handleLocalConnectionQuality(n),this.emit(X.ConnectionQualityUpdate,n)},this.client.onRoomUpdate=n=>this.emit(X.RoomUpdate,n),this.client.onSubscriptionError=n=>this.emit(X.SubscriptionError,n),this.client.onSubscriptionPermissionUpdate=n=>this.emit(X.SubscriptionPermissionUpdate,n),this.client.onSpeakersChanged=n=>this.emit(X.SpeakersChanged,n),this.client.onStreamStateUpdate=n=>this.emit(X.StreamStateChanged,n),this.client.onRequestResponse=n=>
75this.emit(X.SignalRequestResponse,n),this.client.onParticipantUpdate=n=>this.emit(X.ParticipantUpdate,n),this.client.onJoined=n=>this.emit(X.Joined,n)}get logContext(){var e,t,n,r,s,o;return{room:(t=(e=this.latestJoinResponse)===null||e===void 0?void 0:e.room)===null||t===void 0?void 0:t.name,roomID:(r=(n=this.latestJoinResponse)===null||n===void 0?void 0:n.room)===null||r===void 0?void 0:r.sid,participant:(o=(s=this.latestJoinResponse)===null||s===void 0?void 0:s.participant)===null||o===void 0?void 0:o.identity,participantID:this.participantSid}}join(e,t,n,r){return A(this,arguments,void 0,function(s,o,a,d){var l=this;let f=arguments.length>4&&arguments[4]!==void 0?arguments[4]:!1;return(function*(){var p,g,b;l._isNewlyCreated=!1,l.url=s,l.token=o,l.signalOpts=a,l.maxJoinAttempts=a.maxRetries;try{l.joinAttempts+=1,l.setupSignalClientCallbacks();let R=!f&&XC(),w;if(R){l.pcManager||(yield l.configure(),l.applyInitialPublisherLayout());let L=yield(p=l.pcManager)===null||p===void 0?void 0:p.publisher.createInitialOffer();L&&(w=Ci(L.offer,L.offerId))}if(d?.aborted)throw ve.cancelled("Connection aborted");if(!f&&l.shouldFailOnV1Path)throw l.shouldFailOnV1Path=!1,ve.serviceNotFound("Simulated v1 path failure","v0-rtc");let I=yield l.client.join(s,o,a,d,f,w);l._isClosed=!1,l.latestJoinResponse=I,l.participantSid=(g=I.participant)===null||g===void 0?void 0:g.sid,l.subscriberPrimary=I.subscriberPrimary,R?(b=l.pcManager)===null||b===void 0||b.updateConfiguration(l.makeRTCConfiguration(I)):(l.pcManager||(yield l.configure(I,!f),f||l.applyInitialPublisherLayout()),(!l.subscriberPrimary||I.fastPublish)&&l.negotiate().catch(L=>{l.log.error(L)})),l.registerOnLineListener(),l.clientConfiguration=I.clientConfiguration,l.emit(X.SignalConnected,I);let N=I.serverInfo;return N||(N={version:I.serverVersion,region:I.serverRegion}),l.log.info("connected to Livekit Server ".concat(Object.entries(N).map(L=>{let j=pe(L,2),M=j[0],P=j[1];return"".concat(M,": ").concat(P)}).join(", "))),{joinResponse:I,serverInfo:N}}catch(R){if(R instanceof ve){if(R.reason===Ue.ServerUnreachable){if(l.log.warn("Couldn't connect to server, attempt ".concat(l.joinAttempts," of ").concat(l.maxJoinAttempts)),l.joinAttempts<l.maxJoinAttempts)return l.join(s,o,a,d,f)}else if(R.reason===Ue.ServiceNotFound)return l.log.warn("Initial connection failed: ".concat(R.message," \u2013 Retrying")),l.pcManager&&(l.pcManager.onStateChange=void 0,yield l.cleanupPeerConnections()),l.join(s,o,a,d,!0)}throw R}})()})}close(){return A(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(X.Closing),this.removeAllListeners(),this.deregisterOnLineListener(),this.clearPendingReconnect(),this.clearLostQualityTimeout(),this.cleanupLossyDataStats(),yield this.cleanupPeerConnections(),yield this.cleanupClient()}finally{e()}})}cleanupPeerConnections(){return A(this,void 0,void 0,function*(){var e;this.dataChannels.teardown(),yield(e=this.pcManager)===null||e===void 0?void 0:e.close(),this.pcManager=void 0,this.transportConnectingSince=void 0,this.reliableReceivedState.clear()})}cleanupLossyDataStats(){this.lossyChannel.stopThresholdTuning()}cleanupClient(){return A(this,void 0,void 0,function*(){yield this.client.close(),this.client.resetCallbacks();for(let e of Object.keys(this.pendingTrackResolvers))this.pendingTrackResolvers[e].reject();this.pendingTrackResolvers={}})}addTrack(e){if(this.pendingTrackResolvers[e.cid])throw new Yt("a track with the same ID has already been published");return new Promise((t,n)=>{let r=Le.setTimeout(()=>{delete this.pendingTrackResolvers[e.cid],n(ve.timeout("publication of local track timed out, no response from server"))},1e4);this.pendingTrackResolvers[e.cid]={resolve:s=>{Le.clearTimeout(r),t(s)},reject:()=>{Le.clearTimeout(r),n(new Error("Cancelled publication by calling unpublish"))}},this.client.sendAddTrack(e)})}removeTrack(e){if(e.track&&this.pendingTrackResolvers[e.track.id]){let t=this.pendingTrackResolvers[e.track.id].reject;t&&t(),delete this.pendingTrackResolvers[e.track.id]}try{return this.pcManager.removeTrack(e),!0}catch(t){this.log.warn("failed to remove track",{error:t})}return!1}updateMuteStatus(e,t){this.client.sendMuteTrack(e,t)}get dataSubscriberReadyState(){var e;return(e=this.dataChannelForKind(Te.RELIABLE,!0))===null||e===void 0?void 0:e.readyState}getConnectedServerAddress(){return A(this,void 0,void 0,function*(){var e;return(e=this.pcManager)===null||e===void 0?void 0:e.getConnectedAddress()})}setRegionStrategy(e){this.regionStrategy=e}configure(e,t){return A(this,void 0,void 0,function*(){var n;if(!(this.pcManager&&this.pcManager.currentState!==Ve.NEW)){if(e){this.participantSid=(n=e.participant)===null||n===void 0?void 0:n.sid;let r=this.makeRTCConfiguration(e);this.pcManager=new Xo(t?"publisher-only":e.subscriberPrimary?"subscriber-primary":"publisher-primary",this.loggerOptions,r)}else{let r=this.makeRTCConfiguration();this.pcManager=new Xo("publisher-only",this.loggerOptions,r)}
75this.emit(X.TransportsCreated,this.pcManager.publisher,this.pcManager.subscriber),this.pcManager.onIceCandidate=(r,s)=>{this.client.sendIceCandidate(r,s)},this.pcManager.onPublisherOffer=(r,s)=>{this.client.sendOffer(r,s)},this.pcManager.onDataChannel=this.handleDataChannel,this.pcManager.onStateChange=(r,s,o)=>A(this,void 0,void 0,function*(){if(this.log.debug("primary PC state changed ".concat(r)),r===Ve.CONNECTING?this.transportConnectingSince=Date.now():this.transportConnectingSince=void 0,["closed","disconnected","failed"].includes(s)&&(this.publisherConnectionPromise=void 0),r===Ve.CONNECTED){let l=this.pcState===Pt.New;this.pcState=Pt.Connected,l&&this.emit(X.Connected,this.latestJoinResponse)}else r===Ve.FAILED&&(this.pcState===Pt.Connected||this.pcState===Pt.Reconnecting)&&(this.pcState=Pt.Disconnected,this.handleDisconnect("peerconnection failed",o==="failed"?Mn.RR_SUBSCRIBER_FAILED:Mn.RR_PUBLISHER_FAILED));let a=this.client.isDisconnected||this.client.currentState===Fe.RECONNECTING,d=[Ve.FAILED,Ve.CLOSING,Ve.CLOSED].includes(r);a&&d&&!this._isClosed&&this.emit(X.Offline)}),this.pcManager.onTrack=r=>{r.streams.length!==0&&this.emit(X.MediaTrackAdded,r.track,r.streams[0],r.receiver)}}})}setupSignalClientCallbacks(){this.client.onAnswer=(e,t,n)=>A(this,void 0,void 0,function*(){this.pcManager&&(this.log.debug("received server answer",{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",{candidate:e,target:t}),this.pcManager.addIceCandidate(e,t))},this.client.onOffer=(e,t,n)=>A(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=>{var t;if(this.log.debug("received trackPublishedResponse",{cid:e.cid,track:(t=e.track)===null||t===void 0?void 0:t.sid}),!this.pendingTrackResolvers[e.cid]){this.log.error("missing track resolver for ".concat(e.cid),{cid:e.cid});return}let n=this.pendingTrackResolvers[e.cid].resolve;delete this.pendingTrackResolvers[e.cid],n(e.track)},this.client.onLocalTrackUnpublished=e=>{this.emit(X.LocalTrackUnpublished,e)},this.client.onLocalTrackSubscribed=e=>{this.emit(X.LocalTrackSubscribed,e)},this.client.onTokenRefresh=e=>{this.token=e,this.emit(X.TokenRefreshed,e)},this.client.onRemoteMuteChanged=(e,t)=>{this.emit(X.RemoteMute,e,t)},this.client.onSubscribedQualityUpdate=e=>{this.emit(X.SubscribedQualityUpdate,e)},this.client.onRoomMoved=e=>{var t;this.participantSid=(t=e.participant)===null||t===void 0?void 0:t.sid,this.latestJoinResponse&&(this.latestJoinResponse.room=e.room),this.emit(X.RoomMoved,e)},this.client.onMediaSectionsRequirement=e=>{this.addMediaSections(e.numAudios,e.numVideos),this.negotiate()},this.client.onPublishDataTrackResponse=e=>{this.emit(X.PublishDataTrackResponse,e)},this.client.onUnPublishDataTrackResponse=e=>{this.emit(X.UnPublishDataTrackResponse,e)},this.client.onDataTrackSubscriberHandles=e=>{this.emit(X.DataTrackSubscriberHandles,e)},this.client.onClose=()=>{this.handleDisconnect("signal",Mn.RR_SIGNAL_DISCONNECTED)},this.client.onLeave=e=>{switch(this.log.info("client leave request received (action=".concat(e?.action,")"),{reason:e?.reason}),e.regions&&(this.log.debug("updating regions"),this.emit(X.ServerRegionsReported,e.regions)),e.action){case vr.DISCONNECT:this.emit(X.Disconnected,e?.reason),this.close();break;case vr.RECONNECT:this.fullReconnectOnNext=!0,this.handleDisconnect(Rl);break;case vr.RESUME:this.handleDisconnect(Rl)}}}makeRTCConfiguration(e){var t;let n=Object.assign({},this.rtcConfig);if((!((t=this.signalOpts)===null||t===void 0)&&t.e2eeEnabled||this.frameMetadataWorker&&!Cs())&&Nd()&&(this.log.debug("E2EE - setting up transports with insertable streams"),n.encodedInsertableStreams=!0),n.sdpSemantics="unified-plan",n.continualGatheringPolicy="gather_continually",!e)return n;if(e.iceServers&&!n.iceServers){let s=[];
75e.iceServers.forEach(o=>{let a={urls:o.urls};o.username&&(a.username=o.username),o.credential&&(a.credential=o.credential),s.push(a)}),n.iceServers=s}return e.clientConfiguration&&e.clientConfiguration.forceRelay===gs.ENABLED&&(n.iceTransportPolicy="relay"),n}applyInitialPublisherLayout(){this.createDataChannels(),en()||this.addMediaSections(oE,aE)}addMediaSections(e,t){var n,r,s;let o={direction:"recvonly"};for(let d=0;d<e;d++)(n=this.pcManager)===null||n===void 0||n.addPublisherTransceiverOfKind("audio",o);let a=((r=this.pcManager)===null||r===void 0?void 0:r.mode)==="publisher-only";for(let d=0;d<t;d++){let l=(s=this.pcManager)===null||s===void 0?void 0:s.addPublisherTransceiverOfKind("video",o);if(a&&l){let f=xC(l);this.log.debug("dependency descriptor negotiated for received video",{negotiated:f})}}}createDataChannels(){this.pcManager&&this.dataChannels.createPublisherChannels(this.pcManager)}decodeDataMessage(e){return A(this,void 0,void 0,function*(){if(e.data instanceof ArrayBuffer)return new Uint8Array(e.data);if(e.data instanceof Blob)return new Uint8Array(yield e.data.arrayBuffer());this.log.error("unsupported data type",{data:e.data})})}createSender(e,t,n){return A(this,void 0,void 0,function*(){let r;if(uu())r=yield this.createTransceiverRTCRtpSender(e,t,n);else if(du())this.log.warn("using add-track fallback"),r=yield this.createRTCRtpSender(e.mediaStreamTrack);else throw new Be("Required webRTC APIs not supported on this device");return this.setupFrameMetadataSender(r,t),r})}createSimulcastSender(e,t,n,r){return A(this,void 0,void 0,function*(){let s;if(uu())s=yield this.createSimulcastTransceiverSender(e,t,n,r);else if(du())this.log.debug("using add-track fallback"),s=yield this.createRTCRtpSender(e.mediaStreamTrack);else throw new Be("Cannot stream on this device");return s&&this.setupFrameMetadataSender(s,n),s})}get frameMetadataWorker(){var e,t;return(t=(e=this.options.frameMetadata)!==null&&e!==void 0?e:this.options.packetTrailer)===null||t===void 0?void 0:t.worker}setupFrameMetadataSender(e){let t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{};var n,r,s;let o=this.frameMetadataWorker;if(!o||!((n=this.signalOpts)===null||n===void 0)&&n.e2eeEnabled)return;let a=(r=t.frameMetadata)!==null&&r!==void 0?r:t.packetTrailer,d=Ho(a);if(Cs()){d&&(e.transform=new RTCRtpScriptTransform(o,{kind:"encode",packetTrailer:a}));return}if(!ws((s=this.options.frameMetadata)!==null&&s!==void 0?s:this.options.packetTrailer)||!("createEncodedStreams"in e)){d&&this.log.warn("frame metadata transform not supported; skipping write",this.logContext);return}let l=e.createEncodedStreams(),f=l.readable,p=l.writable;d?o.postMessage({kind:"encode",data:{readableStream:f,writableStream:p,packetTrailer:a}},[f,p]):f.pipeTo(p)}createTransceiverRTCRtpSender(e,t,n){return A(this,void 0,void 0,function*(){if(!this.pcManager)throw new Be("publisher is closed");let r=[];e.mediaStream&&r.push(e.mediaStream),Fn(e)&&(e.codec=t.videoCodec);let s={direction:"sendonly",streams:r};return n&&(s.sendEncodings=n),(yield this.pcManager.addPublisherTransceiver(e.mediaStreamTrack,s)).sender})}createSimulcastTransceiverSender(e,t,n,r){return A(this,void 0,void 0,function*(){if(!this.pcManager)throw new Be("publisher is closed");let s={direction:"sendonly"};r&&(s.sendEncodings=r);let o=yield this.pcManager.addPublisherTransceiver(t.mediaStreamTrack,s);if(n.videoCodec)return yield e.setSimulcastTrackSender(n.videoCodec,o.sender),o.sender})}createRTCRtpSender(e){return A(this,void 0,void 0,function*(){if(!this.pcManager)throw new Be("publisher is closed");return this.pcManager.addPublisherTrack(e)})}handleLocalConnectionQuality(e){if(!this.participantSid)return;let t=e.updates.find(n=>n.participantSid===this.participantSid);t&&(t.quality===pr.LOST?this.scheduleLostQualityReconnect():this.clearLostQualityTimeout())}scheduleLostQualityReconnect(){this.lostQualityTimeout||(this.lostQualityTimeout=Le.setTimeout(()=>{this.lostQualityTimeout=void 0,!(this._isClosed||this.pcState!==Pt.Connected||this.attemptingReconnect)&&this.hasActivePublisherSenders()&&(this.log.warn("local connection quality lost while publishing, triggering full reconnect",this.logContext),this.fullReconnectOnNext=!0,this.handleDisconnect("connection quality lost",Mn.RR_PUBLISHER_FAILED))},rE))}clearLostQualityTimeout(){this.lostQualityTimeout&&(Le.clearTimeout(this.lostQualityTimeout),this.lostQualityTimeout=void 0)}hasActivePublisherSenders(){var e,t;return(t=(e=this.pcManager)===null||e===void 0?void 0:e.publisher.getSenders().some(n=>!!n.track&&n.track.readyState==="live"))!==null&&t!==void 0?t:!1}reconnect(){let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:Mn.RR_UNKNOWN;this.fullReconnectOnNext=!0,this.handleDisconnect("reconcile",e)}attemptReconnect(e){return A(this,void 0,void 0,function*(){var t,n,r;if(this._isClosed)return;if(this.attemptingReconnect){this.log.warn("already attempting reconnect, returning early");return}this.clearLostQualityTimeout(),(((t=this.clientConfiguration)===null||t===void 0?void 0:t.resumeConnection)===gs.DISABLED||((r=(n=this.pcManager)===null||n===void 0?void 0:n.currentState)!==null&&r!==void 0?r:Ve.NEW)===Ve.NEW)&&(this.fullReconnectOnNext=!0);let s=this.fullReconnectOnNext;this.fullReconnectOnNext=!1;let o=!1;try{this.attemptingReconnect=!0,s?yield this.restartConnection():yield this.resumeConnection(e),this.clearPendingReconnect(),o=!0}catch(a){this.reconnectAttempts+=1;let d=!0;a instanceof Be?(this.log.debug("received unrecoverable error",{error:a}),d=!1):(s||!(a instanceof Hn))&&(this.fullReconnectOnNext=!0),d?this.handleDisconnect("reconnect",Mn.RR_UNKNOWN):(this.log.info("could not recover connection after ".concat(this.reconnectAttempts," attempts, ").concat(Date.now()-this.reconnectStart,"ms. giving up")),this.emit
75(X.Disconnected),yield this.close())}finally{this.attemptingReconnect=!1,o&&this.fullReconnectOnNext&&!this._isClosed&&(this.log.debug("full reconnect requested during in-progress attempt, dispatching"),this.handleDisconnect("reconnect"))}})}getNextRetryDelay(e){try{return this.reconnectPolicy.nextRetryDelayInMs(e)}catch(t){this.log.warn("encountered error in reconnect policy",{error:t})}return null}restartConnection(e){return A(this,void 0,void 0,function*(){var t,n,r;try{if(!this.url||!this.token)throw new Be("could not reconnect, url or token not saved");this.log.info("reconnecting, attempt: ".concat(this.reconnectAttempts)),this.emit(X.Restarting),this.client.isDisconnected||(yield this.client.sendLeave()),yield this.cleanupPeerConnections(),yield this.cleanupClient();let s;try{if(!this.signalOpts)throw this.log.warn("attempted connection restart, without signal options present"),new Hn;s=(yield this.join(e??this.url,this.token,this.signalOpts,void 0,!this.options.singlePeerConnection)).joinResponse}catch(o){throw o instanceof ve&&o.reason===Ue.NotAllowed?new Be("could not reconnect, token might be expired"):new Hn}if(this.shouldFailNext)throw this.shouldFailNext=!1,new Error("simulated failure");if(this.client.setReconnected(),this.emit(X.SignalRestarted,s),yield this.waitForPCReconnected(),this.client.currentState!==Fe.CONNECTED)throw new Hn("Signal connection got severed during reconnect");(t=this.regionStrategy)===null||t===void 0||t.resetAttempts(),this.emit(X.Restarted)}catch(s){let o=yield(n=this.regionStrategy)===null||n===void 0?void 0:n.getNextUrl();if(o){yield this.restartConnection(o);return}else throw(r=this.regionStrategy)===null||r===void 0||r.resetAttempts(),s}})}resumeConnection(e){return A(this,void 0,void 0,function*(){if(!this.url||!this.token)throw new Be("could not reconnect, url or token not saved");if(!this.pcManager)throw new Be("publisher and subscriber connections unset");this.log.info("resuming signal connection, attempt ".concat(this.reconnectAttempts)),this.emit(X.Resuming);let t;try{this.setupSignalClientCallbacks(),t=yield this.client.reconnect(this.url,this.token,this.participantSid,e)}catch(r){let s="";throw r instanceof Error&&(s=r.message,this.log.error(r.message,{error:r})),r instanceof ve&&r.reason===Ue.NotAllowed?new Be("could not reconnect, token might be expired"):r instanceof ve&&r.reason===Ue.LeaveRequest?r:new Hn(s)}
75if(this.emit(X.SignalResumed),t){let r=this.makeRTCConfiguration(t);this.pcManager.updateConfiguration(r),this.latestJoinResponse&&(this.latestJoinResponse.serverInfo=t.serverInfo)}else this.log.warn("Did not receive reconnect response");if(this.shouldFailNext)throw this.shouldFailNext=!1,new Error("simulated failure");if(yield this.pcManager.triggerIceRestart(),yield this.waitForPCReconnected(),this.client.currentState!==Fe.CONNECTED)throw new Hn("Signal connection got severed during reconnect");this.client.setReconnected();let n=this.dataChannelForKind(Te.RELIABLE);n?.readyState==="open"&&n.id===null&&this.createDataChannels(),t?.lastMessageSeq&&this.resendReliableMessagesForResume(t.lastMessageSeq).catch(r=>{this.log.warn("failed to resend reliable messages after resume",Object.assign(Object.assign({},this.logContext),{error:r}))}),this.emit(X.Resumed)})}waitForPCInitialConnection(e,t){return A(this,void 0,void 0,function*(){if(!this.pcManager)throw new Be("PC manager is closed");yield this.pcManager.ensurePCTransportConnection(t,e)})}waitForPCReconnected(){return A(this,void 0,void 0,function*(){this.pcState=Pt.Reconnecting,this.log.debug("waiting for peer connection to reconnect");try{if(yield ft(iE),!this.pcManager)throw new Be("PC manager is closed");yield this.pcManager.ensurePCTransportConnection(void 0,this.peerConnectionTimeout),this.pcState=Pt.Connected}catch(e){throw this.pcState=Pt.Disconnected,ve.internal("could not establish PC connection, ".concat(e.message))}})}publishRpcAck(e,t){return A(this,void 0,void 0,function*(){let n=new yt({destinationIdentities:[e],kind:Xn.RELIABLE,value:{case:"rpcAck",value:new Ea({requestId:t})}});yield this.sendDataPacket(n,Te.RELIABLE)})}sendDataPacket(e,t){return A(this,void 0,void 0,function*(){var n,r;if(yield this.ensurePublisherConnected(t),this.e2eeManager&&this.e2eeManager.isDataChannelEncryptionEnabled){let a=cw(e);if(a){let d=yield this.e2eeManager.encryptData(a.toBinary());e.value={case:"encryptedPacket",value:new jv({encryptedValue:d.payload,iv:d.iv,keyIndex:d.keyIndex})}}}t===Te.RELIABLE&&(e.sequence=this.reliableChannel.nextSequence());let s=e.toBinary(),o=Math.min((r=(n=this.pcManager)===null||n===void 0?void 0:n.getMaxPublisherMessageSize())!==null&&r!==void 0?r:ev,ev);if(typeof o<"u"&&o!==0&&s.byteLength>o)throw new su("cannot publish data packet larger than ".concat(o," bytes (got ").concat(s.byteLength,")"));t===Te.RELIABLE?yield this.reliableChannel.send(s,e.sequence):yield this.lossyChannel.send(s)})}sendDataTrackFrame(e){return A(this,void 0,void 0,function*(){yield this.ensurePublisherConnected(Te.DATA_TRACK_LOSSY),yield this.dataTrackChannel.send(e)})}resendReliableMessagesForResume(e){return A(this,void 0,void 0,function*(){yield this.ensurePublisherConnected(Te.RELIABLE),yield this.reliableChannel.replay(e)})}flowControlFor(e){return this.dataChannels.channelFor(e)}waitForBufferHeadroom(e){return A(this,void 0,void 0,function*(){return this.flowControlFor(e).waitForHeadroomWithLock()})}ensureDataTransportConnected(e){return A(this,arguments,void 0,function(t){var n=this;let r=arguments.length>1&&arguments[1]!==void 0?arguments[1]:this.subscriberPrimary;return(function*(){var s;if(!n.pcManager)throw new Be("PC manager is closed");let o=r?n.pcManager.subscriber:n.pcManager.publisher,a=r?"Subscriber":"Publisher";if(!o)throw ve.internal("".concat(a," connection not set"));let d=!1;!r&&!n.dataChannelForKind(t,r)&&(n.createDataChannels(),d=!0),!d&&!r&&!n.pcManager.publisher.isICEConnected&&n.pcManager.publisher.getICEConnectionState()!=="checking"&&(d=!0),d&&n.negotiate().catch(p=>{n.log.error(p)});let l=n.dataChannelForKind(t,r);if(l?.readyState==="open")return;let f=new Date().getTime()+n.peerConnectionTimeout;for(;new Date().getTime()<f;){if(o.isICEConnected&&((s=n.dataChannelForKind(t,r))===null||s===void 0?void 0:s.readyState)==="open")return;yield ft(50)}throw ve.internal("could not establish ".concat(a," connection, state: ").concat(o.getICEConnectionState()))})()})}ensurePublisherConnected(e){return A(this,void 0,void 0,function*(){this.publisherConnectionPromise||(this.publisherConnectionPromise=this.ensureDataTransportConnected(e,!1)),yield this.publisherConnectionPromise})}verifyTransport(){if(!this.pcManager)return!1;let e=this.pcManager.currentState;return![Ve.CONNECTING,Ve.CONNECTED].includes(e)||!this.client.ws||this.client.ws.readyState===WebSocket.CLOSED?!1:e===Ve.CONNECTING&&this.transportConnectingSince!==void 0&&Date.now()-this.transportConnectingSince>this.peerConnectionTimeout?(this.log.warn("transport stuck in connecting state",this.logContext),!1):!0}negotiate(){return A(this,void 0,void 0,function*(){return new lt((e,t)=>
75A(this,void 0,void 0,function*(){if(!this.pcManager){t(new hn("PC manager is closed"));return}this.pcManager.requirePublisher(),this.pcManager.publisher.getTransceivers().length==0&&!this.dataChannels.hasPublisherChannels&&this.createDataChannels();let n=new AbortController,r=()=>{n.abort(),this.log.debug("engine disconnected while negotiation was ongoing"),e()};this.isClosed&&t(new hn("cannot negotiate on closed engine")),this.on(X.Closing,r),this.on(X.Restarting,r),this.pcManager.publisher.off(Yn.RTPVideoPayloadTypes,this.onRtpMapAvailable),this.pcManager.publisher.once(Yn.RTPVideoPayloadTypes,this.onRtpMapAvailable);try{yield this.pcManager.negotiate(n),e()}catch(s){if(n.signal.aborted){e();return}s instanceof hn&&(this.fullReconnectOnNext=!0),this.handleDisconnect("negotiation",Mn.RR_UNKNOWN),s instanceof Error?t(s):t(new Error(String(s)))}finally{this.off(X.Closing,r),this.off(X.Restarting,r)}}))})}dataChannelForKind(e,t){return this.dataChannels.getHandle(e,t)}sendSyncState(e,t,n){var r,s,o,a;if(!this.pcManager){this.log.warn("sync state cannot be sent without peer connection setup");return}let d=this.pcManager.publisher.getLocalDescription(),l=this.pcManager.publisher.getRemoteDescription(),f=(r=this.pcManager.subscriber)===null||r===void 0?void 0:r.getRemoteDescription(),p=(s=this.pcManager.subscriber)===null||s===void 0?void 0:s.getLocalDescription(),g=(a=(o=this.signalOpts)===null||o===void 0?void 0:o.autoSubscribe)!==null&&a!==void 0?a:!0,b=new Array,R=new Array;e.forEach(w=>{w.isDesired!==g&&b.push(w.trackSid),w.isEnabled||R.push(w.trackSid)}),this.client.sendSyncState(new Rd({answer:this.pcManager.mode==="publisher-only"?l?Ci({sdp:l.sdp,type:l.type}):void 0:p?Ci({sdp:p.sdp,type:p.type}):void 0,offer:this.pcManager.mode==="publisher-only"?d?Ci({sdp:d.sdp,type:d.type}):void 0:f?Ci({sdp:f.sdp,type:f.type}):void 0,subscription:new Ra({trackSids:b,subscribe:!g,participantTracks:[]}),publishTracks:EC(t),dataChannels:this.dataChannelsInfo(),trackSidsDisabled:R,datachannelReceiveStates:this.reliableReceivedState.map((w,I)=>new ay({publisherSid:I,lastSeq:w})),publishDataTracks:n.map(w=>new Cd({info:Yo.toProtobuf(w)}))}))}failNext(){this.shouldFailNext=!0}failNextV1Path(){this.shouldFailOnV1Path=!0}dataChannelsInfo(){let e=[],t=(n,r)=>{n?.id!==void 0&&n.id!==null&&e.push(new cy({label:n.label,id:n.id,target:r}))};return t(this.dataChannelForKind(Te.LOSSY),zt.PUBLISHER),t(this.dataChannelForKind(Te.RELIABLE),zt.PUBLISHER),t(this.dataChannelForKind(Te.LOSSY,!0),zt.SUBSCRIBER),t(this.dataChannelForKind(Te.RELIABLE,!0),zt.SUBSCRIBER),e}clearReconnectTimeout(){this.reconnectTimeout&&Le.clearTimeout(this.reconnectTimeout)}clearPendingReconnect(){this.clearReconnectTimeout(),this.reconnectAttempts=0}registerOnLineListener(){St()&&(window.addEventListener("online",this.handleBrowserOnLine),window.addEventListener("offline",this.handleBrowserOffline))}deregisterOnLineListener(){St()&&(window.removeEventListener("online",this.handleBrowserOnLine),window.removeEventListener("offline",this.handleBrowserOffline))}getTrackIdForReceiver(e){var t;let n=(t=this.pcManager)===null||t===void 0?void 0:t.getMidForReceiver(e);if(n){let r=Object.entries(this.midToTrackId).find(s=>pe(s,1)[0]===n);if(r)return r[1]}}};function tv(i,e){let t=i.participantIdentity?i.participantIdentity:e.participantIdentity;i.participantIdentity=t,e.participantIdentity=t;let n=i.destinationIdentities.length!==0?i.destinationIdentities:e.destinationIdentities;i.destinationIdentities=n,e.destinationIdentities=n}var Co=ut(Xe.Region),Ou=5e3,cE=3e4,tn=class i{static fetchRegionSettings(e,t,n){return A(this,void 0,void 0,function*(){let r=yield i.fetchLock.lock();try{let s=yield fetch("".concat(lE(e),"/regions"),{headers:{authorization:"Bearer ".concat(t)},signal:n});if(s.ok){let o=QC(s.headers),a=o?o*1e3:Ou;return{regionSettings:yield s.json(),updatedAtInMs:Date.now(),maxAgeInMs:a}}else throw s.status===401?ve.notAllowed("Could not fetch region settings: ".concat(s.statusText),s.status):ve.internal("Could not fetch region settings: ".concat(s.statusText))}catch(s){throw s instanceof ve?s:n?.aborted?ve.cancelled("Region fetching was aborted"):ve.serverUnreachable("C
75ould not fetch region settings, ".concat(s instanceof Error?"".concat(s.name,": ").concat(s.message):s))}finally{r()}})}static scheduleRefetch(e,t,n){return A(this,void 0,void 0,function*(){let r=i.settingsTimeouts.get(e.hostname);clearTimeout(r),i.settingsTimeouts.set(e.hostname,setTimeout(()=>A(this,void 0,void 0,function*(){try{let s=yield i.fetchRegionSettings(e,t);i.updateCachedRegionSettings(e,t,s)}catch(s){if(s instanceof ve&&s.reason===Ue.NotAllowed){Co.debug("token is not valid, cancelling auto region refresh");return}Co.debug("auto refetching of region settings failed",{error:s}),i.scheduleRefetch(e,t,n)}}),n))})}static updateCachedRegionSettings(e,t,n){i.cache.set(e.hostname,n),i.scheduleRefetch(e,t,n.maxAgeInMs)}static stopRefetch(e){let t=i.settingsTimeouts.get(e);t&&(clearTimeout(t),i.settingsTimeouts.delete(e))}static scheduleCleanup(e){let t=i.connectionTrackers.get(e);t&&(t.cleanupTimeout&&clearTimeout(t.cleanupTimeout),t.cleanupTimeout=setTimeout(()=>{let n=i.connectionTrackers.get(e);n&&n.connectionCount===0&&(Co.debug("stopping region refetch after disconnect delay",{hostname:e}),i.stopRefetch(e)),n&&(n.cleanupTimeout=void 0)},cE))}static cancelCleanup(e){let t=i.connectionTrackers.get(e);t?.cleanupTimeout&&(clearTimeout(t.cleanupTimeout),t.cleanupTimeout=void 0)}notifyConnected(){let e=this.serverUrl.hostname,t=i.connectionTrackers.get(e);t||(t={connectionCount:0},i.connectionTrackers.set(e,t)),t.connectionCount++,i.cancelCleanup(e)}notifyDisconnected(){let e=this.serverUrl.hostname,t=i.connectionTrackers.get(e);t&&(t.connectionCount=Math.max(0,t.connectionCount-1),t.connectionCount===0&&i.scheduleCleanup(e))}constructor(e,t){this.attemptedRegions=[],this.serverUrl=new URL(e),this.token=t}updateToken(e){var t;this.token=e;let n=this.getServerUrl(),r=i.cache.get(n.hostname);i.scheduleRefetch(this.serverUrl,this.token,(t=r?.maxAgeInMs)!==null&&t!==void 0?t:Ou)}isCloud(){return Pr(this.serverUrl)}getServerUrl(){return this.serverUrl}fetchRegionSettings(e){return A(this,void 0,void 0,function*(){return i.fetchRegionSettings(this.serverUrl,this.token,e)})}getNextBestRegionUrl(e){return A(this,void 0,void 0,function*(){if(!this.isCloud())throw Error("region availability is only supported for LiveKit Cloud domains");let t=i.cache.get(this.serverUrl.hostname);(!t||Date.now()-t.updatedAtInMs>t.maxAgeInMs)&&(t=yield this.fetchRegionSettings(e),i.updateCachedRegionSettings(this.serverUrl,this.token,t));let n=t.regionSettings.regions.filter(r=>!this.attemptedRegions.find(s=>s.url===r.url));if(n.length>0){let r=n[0];return this.attemptedRegions.push(r),Co.info("switching to region: ".concat(r.region),{region:r.region}),r.url}else return null})}resetAttempts(){this.attemptedRegions=[]}setServerReportedRegions(e){i.updateCachedRegionSettings(this.serverUrl,this.token,e)}};tn.cache=new Map;tn.settingsTimeouts=new Map;tn.connectionTrackers=new Map;tn.fetchLock=new tt;function lE(i){return"".concat(i.protocol.replace("ws","http"),"//").concat(i.host,"/settings")}function Il(){return new CompressionStream("deflate-raw")}function ub(){return new DecompressionStream("deflate-raw")}function nv(i,e){return A(this,void 0,void 0,function*(){let t=new DecompressionStream("deflate-raw"),n=t.writable.getWriter();return n.write(i).catch(()=>{}),n.close().catch(()=>{}),db(t.readable,e)})}function db(i,e){return A(this,void 0,void 0,function*(){let t=i.getReader(),n=[],r=0;for(;;){let a=yield t.read(),d=a.done,l=a.value;if(d)break;if(n.push(l),r+=l.byteLength,typeof e=="number"&&r>e)throw yield t.cancel(),new Ye("Decompressed payload exceeds the maximum payload size of ".concat(e," bytes"),He.PayloadTooLarge)}let s=new Uint8Array(r),o=0;for(let a of n)s.set(a,o),o+=a.byteLength;return s})}var wi=15e3,uE=5e9,sa=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 Ye("Not enough chunk(s) received - expected ".concat(this.totalByteSize," bytes of data total, only received ").concat(this.bytesReceived," bytes"),He.Incomplete);if(this.bytesReceived>this.totalByteSize)throw new Ye("Extra chunk(s) received - expected ".concat(this.totalByteSize," bytes of data total, received ").concat(this.bytesReceived," bytes"),He.LengthExceeded)}}constructor(e,t,n){this.reader=t,this.totalByteSize=n,this._info=e,this.bytesReceived=0}},oa=class extends sa{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===void 0||t.call(this,n)}[Symbol.asyncIterator](){let e=this.reader.getReader();e.closed.catch(()=>{});let t=()=>{e.releaseLock(),this.signal=void 0};return{next:()=>A(this,void 0,void 0,function*(){var n;try{let r=this.signal;if(r?.aborted)throw r.reason;let s=yield new Promise((o,a)=>
75{if(r){let d=()=>a(r.reason);r.addEventListener("abort",d,{once:!0}),e.read().then(o,a).finally(()=>{r.removeEventListener("abort",d)})}else e.read().then(o,a)});return s.done?(this.validateBytesReceived(!0),typeof this.totalByteSize=="number"&&((n=this.onProgress)===null||n===void 0||n.call(this,1)),{done:!0,value:void 0}):(this.handleChunkReceived(s.value),{done:!1,value:s.value.content})}catch(r){throw t(),r}}),return(){return A(this,void 0,void 0,function*(){return t(),{done:!0,value:void 0}})}}}withAbortSignal(e){return this.signal=e,this}readAll(){return A(this,arguments,void 0,function(){var e=this;let t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};return(function*(){var n,r,s,o;let a=new Set,d=t.signal?e.withAbortSignal(t.signal):e;try{for(var l=!0,f=Ft(d),p;p=yield f.next(),n=p.done,!n;l=!0){o=p.value,l=!1;let g=o;a.add(g)}}catch(g){r={error:g}}finally{try{!l&&!n&&(s=f.return)&&(yield s.call(f))}finally{if(r)throw r.error}}return Array.from(a)})()})}},aa=class extends sa{constructor(e,t,n){super(e,t,n),this.receivedChunks=new Map}handleChunkReceived(e){var t;let n=_i(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 s=this.totalByteSize?this.bytesReceived/this.totalByteSize:void 0;(t=this.onProgress)===null||t===void 0||t.call(this,s)}[Symbol.asyncIterator](){let e=this.reader.getReader();e.closed.catch(()=>{});let t=new TextDecoder("utf-8"),n=this.signal,r=()=>{e.releaseLock(),this.signal=void 0};return{next:()=>A(this,void 0,void 0,function*(){var s;try{if(n?.aborted)throw n.reason;let o=yield new Promise((a,d)=>{if(n){let l=()=>d(n.reason);n.addEventListener("abort",l,{once:!0}),e.read().then(a,d).finally(()=>{n.removeEventListener("abort",l)})}else e.read().then(a,d)});if(o.done)return this.validateBytesReceived(!0),typeof this.totalByteSize=="number"&&((s=this.onProgress)===null||s===void 0||s.call(this,1)),{done:!0,value:void 0};{this.handleChunkReceived(o.value);let a;try{a=t.decode(o.value.content)}catch(d){throw new Ye("Cannot decode datastream chunk ".concat(o.value.chunkIndex," as text: ").concat(d),He.DecodeFailed)}return{done:!1,value:a}}}catch(o){throw r(),o}}),return(){return A(this,void 0,void 0,function*(){return r(),{done:!0,value:void 0}})}}}withAbortSignal(e){return this.signal=e,this}readAll(){return A(this,arguments,void 0,function(){var e=this;let t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};return(function*(){var n,r,s,o;let a="",d=t.signal?e.withAbortSignal(t.signal):e;try{for(var l=!0,f=Ft(d),p;p=yield f.next(),n=p.done,!n;l=!0)o=p.value,l=!1,a+=o}catch(g){r={error:g}}finally{try{!l&&!n&&(s=f.return)&&(yield s.call(f))}finally{if(r)throw r.error}}return a})()})}},Du=class{constructor(){let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:uE;this.log=ye,this.byteStreamControllers=new Map,this.textStreamControllers=new Map,this.byteStreamHandlers=new Map,this.textStreamHandlers=new Map,this.isConnected=!1,this.bufferedPackets=[],this.maxPayloadByteLength=e}setConnected(e){this.isConnected=e,e&&this.flushBufferedPackets()}flushBufferedPackets(){let e=this.bufferedPackets;this.bufferedPackets=[];for(let t of e){let n=t.packet,r=t.encryptionType;this.handleDataStreamPacket(n,r)}}registerTextStreamHandler(e,t){if(this.textStreamHandlers.has(e))throw new Ye('A text stream handler for topic "'.concat(e,'" has already been set.'),He.HandlerAlreadyRegistered);this.textStreamHandlers.set(e,t)}unregisterTextStreamHandler(e){this.textStreamHandlers.delete(e)}registerByteStreamHandler(e,t){if(this.byteStreamHandlers.has(e))throw new Ye('A byte stream handler for topic "'.concat(e,'" has already been set.'),He.HandlerAlreadyRegistered);this.byteStreamHandlers.set(e,t)}unregisterByteStreamHandler(e){this.byteStreamHandlers.delete(e)}clearControllers(){this.byteStreamControllers.clear(),this.textStreamControllers.clear(),this.bufferedPackets=[]}validateParticipantHasNoActiveDataStreams(e){let t=Array.from(this.textStreamControllers.entries()).filter(o=>o[1].sendingParticipantIdentity===e),n=Array.from(this.byteStreamControllers.entr
75ies()).filter(o=>o[1].sendingParticipantIdentity===e);if(t.length>0||n.length>0){let o=new Ye("Participant ".concat(e," unexpectedly disconnected in the middle of sending data"),He.AbnormalEnd);for(let a of n){var r=pe(a,2);let d=r[0];r[1].controller.error(o),this.byteStreamControllers.delete(d)}for(let a of t){var s=pe(a,2);let d=s[0];s[1].controller.error(o),this.textStreamControllers.delete(d)}}}handleDataStreamPacket(e,t){if(!this.isConnected){this.bufferedPackets.push({packet:e,encryptionType:t});return}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 new Error('DataPacket of value "'.concat(e.value.case,'" is not data stream related!'))}}handleStreamHeader(e,t,n){var r;switch(e.contentHeader.case){case"byteHeader":{let s=this.byteStreamHandlers.get(e.topic);if(!s){this.log.debug("ignoring incoming byte stream due to no handler for topic",e.topic);return}let o,a={id:e.streamId,name:(r=e.contentHeader.value.name)!==null&&r!==void 0?r:"unknown",mimeType:e.mimeType,size:e.totalLength?Number(e.totalLength):void 0,topic:e.topic,timestamp:_i(e.timestamp),attributes:e.attributes,encryptionType:n},d;switch(e.compression){case pt.DEFLATE_RAW:if(!Zn()){ye.warn("Data stream ".concat(e.streamId," received with deflate-raw compression, but this browser does not have support for DecompressionStream. Dropping..."));return}d=!0;break;case pt.NONE:d=!1;break;default:ye.warn("Data stream ".concat(e.streamId," received with unknown compression type ").concat(e.compression,", dropping..."));return}let l=e.inlineContent;if(typeof l<"u"){s(new oa(a,iv(e.streamId,d?nv(l,this.maxPayloadByteLength):l),_i(e.totalLength)),{identity:t});return}let f=new ReadableStream({start:p=>{if(o=p,this.byteStreamControllers.has(e.streamId))throw new Ye("A data stream read is already in progress for a stream with id ".concat(e.streamId,"."),He.AlreadyOpened);this.byteStreamControllers.set(e.streamId,{info:a,controller:o,startTime:Date.now(),sendingParticipantIdentity:t})}});s(new oa(a,d?pE(f,e.streamId,this.maxPayloadByteLength):f,_i(e.totalLength)),{identity:t});return}case"textHeader":{let s=this.textStreamHandlers.get(e.topic);if(!s){this.log.debug("ignoring incoming text stream due to no handler for topic",e.topic);return}let o,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},d;switch(e.compression){case pt.DEFLATE_RAW:if(!Zn()){ye.warn("Data stream ".concat(e.streamId," received with deflate-raw compression, but this browser does not have support for DecompressionStream. Dropping..."));return}d=!0;break;case pt.NONE:d=!1;break;default:ye.warn("Data stream ".concat(e.streamId," received with unknown compression type ").concat(e.compression,", dropping..."));return}let l=e.inlineContent;if(typeof l<"u"){let p=d?nv(l,this.maxPayloadByteLength):l;s(new aa(a,iv(e.streamId,p),_i(e.totalLength)),{identity:t});return}let f=new ReadableStream({start:p=>{if(o=p,this.textStreamControllers.has(e.streamId))throw new Ye("A data stream read is already in progress for a stream with id ".concat(e.streamId,"."),He.AlreadyOpened);this.textStreamControllers.set(e.streamId,{info:a,controller:o,startTime:Date.now(),sendingParticipantIdentity:t})}});s(new aa(a,d?fE(f,e.streamId,this.maxPayloadByteLength):f,_i(e.totalLength)),{identity:t});return}}}handleStreamChunk(e,t){let n=this.byteStreamControllers.get(e.streamId);n&&(n.info.encryptionType!==t?(n.controller.error(new Ye("Encryption type mismatch for stream ".concat(e.streamId,". Expected ").concat(t,", got ").concat(n.info.encryptionType),He.EncryptionTypeMismatch)),this.byteStreamControllers.delete(e.streamId)):e.content.length>0&&n.controller.enqueue(e));let r=this.textStreamControllers.get(e.streamId);r&&(r.info.encryptionType!==t?(r.controller.error(new Ye("Encryption type mismatch for stream ".concat(e.streamId,". Expected ").concat(t,", got ").concat(r.info.encryptionType),He.EncryptionTypeMismatch)),this.textStreamControllers.delete(e.streamId)):e.content.length>0&&r.controller.enqueue(e))}handleStreamTrailer(e,t){let n=this.textStreamControllers.get(e.streamId);n&&(n.info.encryptionType!==t?n.controller.error(new Ye("Encryption type mismatch for stream ".concat(e.streamId,". Expected ").concat(t,", got ").concat(n.info.encryptionType),He.EncryptionTypeMismatch)):(n.info.attributes=Object.assign(Object.assign({},n.info.attributes),e.attributes),e.reason?n.controller.error(new Ye("Data stream ".concat(e.streamId," closed abnormally: ").concat(e.reason),He.AbnormalEnd)):n.controller.close()),this.textStreamControllers.delete(e.streamId));let r=this.byteStreamControllers.get(e.streamId);r&&(r.info.encryptionType!==t?r.controller.error(new Ye("Encryption type mismatch for stream ".concat(e.streamId,". Expected ").concat(t,", got ").concat(r.info.encryptionType),He.EncryptionTypeMismatch)):(r.info.attributes=Object.assign(Object.assign({},r.info.attributes),e.attributes),e.reason?r.controller.error(new Ye("Data stream ".concat(e.streamId," closed abnormally: ").concat(e.reason),He.AbnormalEnd)):r.controller.close()),this.byteStreamControllers.delete(e.streamId))}};function iv(i,e){return new ReadableStream({start:t=>A(this,void 0,void 0,function*(){try{let n=yield e;t.enqueue(new Ln({streamId:i,chunkIndex:BigInt(0),content:n})),t.close()}catch(n){t.error(n)}})})}function hb(i){let e=-1;return new TransformStream({transform:(t,n)=>{let r=_i(t.chunkIndex);if(r<=e){ye.warn("ignoring duplicate chunk ".concat(r," for compressed data stream ").concat(i," (last processed: ").concat(e,")"));return}if(r>e+1)throw new Ye("Missing chunk(s) ".concat(e+1,"..").concat(r-1," for compressed data stream ").concat(i," - cannot continue decompressing"),He.Incomplete);e=r,n.enqueue(t)}})}function pb(){return new TransformStream({transform:(i,e)=>{e.enqueue(i.content)}})}function dE(i){let e=0;return new TransformStream({transform:(t,n)=>{t.byteLength>0&&(n.enqueue(new Ln({streamId:i,chunkIndex:Xt(e),content:t})),e+=1)}})}function hE(i){let e=new TextDecoder("utf-8"),t=new TextEncoder,n=0,r=s=>{try{return s?e.decode(s,{stream:!0}):e.decode()}catch(o){throw new Ye("Cannot decode compressed data stream ".concat(i," as text: ").concat(o),He.DecodeFailed)}};return new TransformStream({transform:(s,o)=>{let a=r(s);a.length>0&&(o.enqueue(new Ln({streamId:i,chunkIndex:Xt(n),content:t.encode(a)})),n+=1)},flush:s=>
75{let o=r();o.length>0&&(s.enqueue(new Ln({streamId:i,chunkIndex:Xt(n),content:t.encode(o)})),n+=1)}})}function pE(i,e,t){return i.pipeThrough(hb(e)).pipeThrough(pb()).pipeThrough(ub()).pipeThrough(fb(e,t)).pipeThrough(dE(e))}function fE(i,e,t){return i.pipeThrough(hb(e)).pipeThrough(pb()).pipeThrough(ub()).pipeThrough(fb(e,t)).pipeThrough(hE(e))}function fb(i,e){let t=0;return new TransformStream({transform:(n,r)=>{if(t+=n.byteLength,t>e)throw new Ye("Data stream ".concat(i," exceeds the maximum payload size of ").concat(e," bytes"),He.PayloadTooLarge);r.enqueue(n)}})}var ca=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 A(this,void 0,void 0,function*(){var e;yield this.defaultWriter.close(),this.defaultWriter.releaseLock(),(e=this.onClose)===null||e===void 0||e.call(this)})}},Lu=class extends ca{},xu=class extends ca{};function Ol(i,e,t){var n;return new Pa({streamId:i.id,mimeType:i.mimeType,topic:i.topic,timestamp:Xt(i.timestamp),totalLength:Xt(i.size),attributes:i.attributes,compression:(n=t?.compression)!==null&&n!==void 0?n:pt.NONE,inlineContent:t?.inlineContent,contentHeader:{case:"textHeader",value:new Qv({version:e?.version,attachedStreamIds:i.attachedStreamIds,replyToStreamId:e?.replyToStreamId,operationType:e?.type==="update"?Wl.UPDATE:Wl.CREATE})}})}function wo(i,e){var t;return new Pa({streamId:i.id,mimeType:i.mimeType,topic:i.topic,timestamp:Xt(i.timestamp),totalLength:Xt(i.size),attributes:i.attributes,compression:(t=e?.compression)!==null&&t!==void 0?t:pt.NONE,inlineContent:e?.inlineContent,contentHeader:{case:"byteHeader",value:new Xv({name:i.name})}})}function Si(i,e){return new yt({destinationIdentities:e,value:{case:"streamHeader",value:i}})}var mE=new TextEncoder,Nu=class{constructor(e,t,n,r,s){this.engine=e,this.log=t,this.getRemoteParticipantClientProtocol=n,this.getRemoteParticipantCapabilities=r,this.getAllRemoteParticipantIdentities=s}setupEngine(e){this.engine=e}sendText(e,t){return A(this,void 0,void 0,function*(){var n,r,s,o,a;let d=crypto.randomUUID(),l=mE.encode(e),f=l.byteLength,p=(n=t?.compress)!==null&&n!==void 0?n:!0,g={id:d,mimeType:"text/plain",timestamp:Date.now(),topic:(r=t?.topic)!==null&&r!==void 0?r:"",size:f,attributes:t?.attributes,encryptionType:!((s=this.engine.e2eeManager)===null||s===void 0)&&s.isDataChannelEncryptionEnabled?Ie.GCM:Ie.NONE},R=p&&Zn()&&this.allRecipientsSupportV2(t?.destinationIdentities)&&this.allRecipientsSupportCompression(t?.destinationIdentities)?la.fromStream(jo(l).pipeThrough(Il())):null;if((!t?.attachments||t.attachments.length===0)&&this.allRecipientsSupportV2(t?.destinationIdentities)){let M=l,P=pt.NONE;if(R){let K=yield R.collect();K.byteLength<l.byteLength&&(M=K,P=pt.DEFLATE_RAW)}let B=Ol(g,void 0,{compression:P,inlineContent:M}),q=Si(B,t?.destinationIdentities);if(q.toBinary().byteLength<=wi)return yield this.engine.sendDataPacket(q,Te.RELIABLE),(o=t?.onProgress)===null||o===void 0||o.call(t,1),g}let I=(a=t?.attachments)===null||a===void 0?void 0:a.map(()=>crypto.randomUUID()),N=I?I.length+1:1,L=new Array(N).fill(0),j=(M,P)=>{var B;L[P]=M,(B=t?.onProgress)===null||B===void 0||B.call(t,L.reduce((q,K)=>q+K,0)/N)};if(R){g.attachedStreamIds=I;let M=Ol(g,void 0,{compression:pt.DEFLATE_RAW}),P=Si(M,t?.destinationIdentities);yield this.sendChunkedByteStream(P,d,t?.destinationIdentities,R.stream().pipeThrough(Dl(l.length,B=>j(B,0)))),l.length===0&&j(1,0)}else{let M=yield this.streamText({streamId:d,totalSize:f,destinationIdentities:t?.destinationIdentities,topic:t?.topic,attachedStreamIds:I,attributes:t?.attributes});yield M.write(e),j(1,0),yield M.close(),g=M.info}return t?.attachments&&I&&(yield Promise.all(t.attachments.map((M,P)=>A(this,void 0,void 0,function*(){return this._sendFile(I[P],M,{topic:t.topic,mimeType:M.type,destinationIdentities:t.destinationIdentities,compress:t.compress,onProgress:B=>{j(B,P+1)}})})))),g})}sendBytes(e,t){return A(this,void 0,void 0,function*(){var n,r,s,o,a,d,l;let f=crypto.randomUUID(),p=t?.destinationIdentities,g=(n=t?.compress)!==null&&n!==void 0?n:!0,b={id:f,name:(r=t?.name)!==null&&r!==void 0?r:"unknown",mimeType:(s=t?.mimeType)!==null&&s!==void 0?s:"application/octet-stream",timestamp:Date.now(),topic:(o=t?.topic)!==null&&o!==void 0?o:"",size:e.byteLength,attributes:t?.attributes,encryptionType:!((a=this.engine.e2eeManager)===null||a===void 0)&&a.isDataChannelEncryptionEnabled?Ie.GCM:Ie.NONE},R=Dl(e.length,t?.onProgress),I=g&&Zn()&&this.allRecipientsSupportV2(p)&&this.allRecipientsSupportCompression(p)?la.fromStream(jo(e).pipeThrough(R).pipeThrough(Il())):null;if(this.allRecipientsSupportV2(p)){let M=e,P=pt.NONE;if(I){let K=yield I.collect();K.byteLength<e.byteLength&&(M=K,P=pt.DEFLATE_RAW)}let B=wo(b,{compression:P,inlineContent:M}),q=Si(B,p);if(q.toBinary().byteLength<=wi)return yield this.engine.sendDataPacket(q,Te.RELIABLE),(d=t?.onProgress)===null||d===void 0||d.call(t,1),b}let N=wo(b,{compression:I?pt.DEFLATE_RAW:pt.NONE}),L=Si(N,p),j=I?I.stream():jo(e).pipeThrough(R);return yield this.sendChunkedByteStream(L,f,p,j),e.length===0&&((l=t?.onProgress)===null||l===void 0||l.call(t,1)),b})}allRecipientsSupportV2(e){return(e&&e.length>0?e:this.getAllRemoteParticipantIdentities()).every(n=>this.getRemoteParticipantClientProtocol(n)>=Jy)}allRecipientsSupportCompression(e){return(e&&e.length>0?e:this.getAllRemoteParticipantIdentities()).every(n=>this.getRemoteParticipantCapabilities(n).includes(ys.CAP_COMPRESSION_DEFLATE_RAW))}sendChunkedByteStream(e,t,n,r){return A(this,void 0,void 0,function*(){var s,o,a,d;let l=this.engine;yield Ll(l,e);let f=0;try{for(var p=!0,g=Ft(YC(r,wi)),b;b=yield g.next(),s=b.done,!s;p=!0){d=b.value,p=!1;let R=d,w=new yt({destinationIdentities:n,value:{case:"streamChunk",value:new Ln({content:R,streamId:t,chunkIndex:Xt(f)})}});yield l.sendDataPacket(w,Te.RELIABLE),f+=1}}catch(R){o={error:R}}finally{try{!p&&!s&&(a=g.return)&&(yield a.call(g))}finally{if(o)throw o.error}}yield xl(t,n,l)})}streamText(e){return A(this,void 0,void 0,function*(){var t,n,r;let s=(t=e?.streamId)!==null&&t!==void 0?t:crypto.randomUUID(),o=e?.destinationIdentities,a={id:s,mimeType:"text/plain",timestamp:Date.now(),topic:(n=e?.topic)!==null&&n!==void 0?n:"",size:e?.totalSize,attributes:e?.attributes,encryptionType:!((r=this.engine.e2eeManager)===null||r===void 0)&&r.isDataChannelEncryptionEnabled?Ie.GCM:Ie.NONE,attachedStreamIds:e?.attachedStreamIds},d=Ol(a,e),l=Si(d,o);yield Ll(this.engine,l);let f=0,p=this.engine,g=new WritableStream({write(w){return A(this,void 0,void 0,function*(){for(let I of zC(w,wi)){let N=new Ln({content:I,streamId:s,chunkIndex:Xt(f)}),L=new yt({destinationIdentities:o,value:{case:"streamChunk",value:N}});yield p.sendDataPacket(L,Te.RELIABLE),f+=1}})},close(){return A(this,void 0,void 0,function*(){yield xl(s,o,p)})},abort(w){console.log("Sink error:",w)}}),b=()=>A(this,void 0,void 0,function*(){yield R.close()});p.once(X.Closing,b);let R=new Lu(g,a,()=>this.engine.off(X.Closing,b));return R})}sendFile(e,t){return A(this,void 0,void 0,function*(){let n=crypto.randomUUID();return yield this._sendFile(n,e,t),{id:n}})}_sendFile(e,t,n){return A(this,void 0,void 0,function*(){var r,s,o,a,d;let l=n?.destinationIdentities,f=((r=n?.compress)!==null&&r!==void 0?r:!0)&&Zn()&&this.allRecipientsSupportV2(l)&&this.allRecipientsSupportCompression(l),p={id:e,name:t.name,mimeType:(s=n?.mimeType)!==null&&s!==void 0?s:t.type,topic:(o=n?.topic)!==null&&o!==void 0?o:"",timestamp:Date.now(),size:t.size,encryptionType:!((a=this.engine.e2eeManager)===null||a===void 0)&&a.isDataChannelEncryptionEnabled?Ie.GCM:Ie.NONE},g=wo(p,{compression:f?pt.DEFLATE_RAW:pt.NONE}),b=Si(g,l),R=t.stream().pipeThrough(Dl(t.size,n?.onProgress)),w=f?R.pipeThrough(Il()):R;
75return yield this.sendChunkedByteStream(b,e,l,w),t.size===0&&((d=n?.onProgress)===null||d===void 0||d.call(n,1)),p})}streamBytes(e){return A(this,void 0,void 0,function*(){var t,n,r,s,o;let a=(t=e?.streamId)!==null&&t!==void 0?t:crypto.randomUUID(),d=e?.destinationIdentities,l={id:a,mimeType:(n=e?.mimeType)!==null&&n!==void 0?n:"application/octet-stream",topic:(r=e?.topic)!==null&&r!==void 0?r:"",timestamp:Date.now(),attributes:e?.attributes,size:e?.totalSize,name:(s=e?.name)!==null&&s!==void 0?s:"unknown",encryptionType:!((o=this.engine.e2eeManager)===null||o===void 0)&&o.isDataChannelEncryptionEnabled?Ie.GCM:Ie.NONE},f=wo(l),p=Si(f,d);yield Ll(this.engine,p);let g=0,b=new tt,R=this.engine,w=this.log,I=new WritableStream({write(L){return A(this,void 0,void 0,function*(){let j=yield b.lock(),M=0;try{for(;M<L.byteLength;){let P=L.slice(M,M+wi),B=new yt({destinationIdentities:d,value:{case:"streamChunk",value:new Ln({content:P,streamId:a,chunkIndex:Xt(g)})}});yield R.sendDataPacket(B,Te.RELIABLE),g+=1,M+=P.byteLength}}finally{j()}})},close(){return A(this,void 0,void 0,function*(){yield xl(a,d,R)})},abort(L){w.error("Sink error:",L)}});return new xu(I,l)})}},la=class i{constructor(e){this.state=e}static fromStream(e){return new i({type:"stream",stream:e})}collect(){return A(this,void 0,void 0,function*(){switch(this.state.type){case"stream":let e=yield db(this.state.stream);return this.state={type:"collected",bytes:e},e;case"collected":return this.state.bytes}})}stream(){switch(this.state.type){case"stream":return this.state.stream;case"collected":return jo(this.state.bytes)}}};function Dl(i,e){let t=0;return new TransformStream({transform(n,r){t+=n.byteLength,e&&typeof i=="number"&&i>0&&e(Math.min(t/i,1)),r.enqueue(n)}})}function Ll(i,e){return A(this,void 0,void 0,function*(){if(e.toBinary().byteLength>wi)throw new Ye("data stream header exceeds the ".concat(wi,"-byte limit; reduce attribute size"),He.HeaderTooLarge);yield i.sendDataPacket(e,Te.RELIABLE)})}function xl(i,e,t){return A(this,void 0,void 0,function*(){let n=new yt({destinationIdentities:e,value:{case:"streamTrailer",value:new Td({streamId:i})}});yield t.sendDataPacket(n,Te.RELIABLE)})}function mb(i){if(i.length===0)return new AbortController().signal;if(i.length===1)return i[0];for(let r of i)if(r.aborted)return r;let e=new AbortController,t=Array(i.length),n=()=>{for(let r of t)r()};return i.forEach((r,s)=>{let o=()=>{e.abort(r.reason),n()};r.addEventListener("abort",o),t[s]=()=>r.removeEventListener("abort",o)}),e.signal}function gb(i){let e=new AbortController;return setTimeout(()=>{e.abort(new DOMException("signal timed out after ".concat(i," ms"),"TimeoutError"))},i),e.signal}var ze=1,An=2,rv=4,gE=8,sv=0,ov=12,av=5,vE=7,cv=3,yE=3,lv=2,uv=1,dv=0,hv=3,Eo=2,pv=2,bE=1,kE=0,In;(function(i){i[i.TooShort=0]="TooShort",i[i.HeaderOverrun=1]="HeaderOverrun",i[i.MissingExtWords=2]="MissingExtWords",i[i.UnsupportedVersion=3]="UnsupportedVersion",i[i.InvalidHandle=4]="InvalidHandle",i[i.MalformedExt=5]="MalformedExt"})(In||(In={}));var dn=class i extends Tt{constructor(e,t,n){super(19,e,n),this.name="DataTrackDeserializeError",this.reason=t,this.reasonName=In[t]}static tooShort(){return new i("Too short to contain a valid header",In.TooShort)}static headerOverrun(){return new i("Header exceeds total packet length",In.HeaderOverrun)}static missingExtWords(){return new i("Extension word indicator is missing",In.MissingExtWords)}static unsupportedVersion(e){return new i("Unsupported version ".concat(e),In.UnsupportedVersion)}static invalidHandle(e){return new i("invalid track handle: ".concat(e.message),In.InvalidHandle,{cause:e})}static malformedExt(e){return new i("Extension with tag ".concat(e," is malformed"),In.MalformedExt)}},hs;(function(i){i[i.TooSmallForHeader=0]="TooSmallForHeader",i[i.TooSmallForPayload=1]="TooSmallForPayload"})(hs||(hs={}));var ua=class i extends Tt{constructor(e,t,n){super(19,e,n),this.name="DataTrackSerializeError",this.reason=t,this.reasonName=hs[t]}static tooSmallForHeader(){return new i("Buffer cannot fit header",hs.TooSmallForHeader)}static tooSmallForPayload(){return new i("Buffer cannot fit payload",hs.TooSmallForPayload)}},Rr=class{toBinary(){let e=this.toBinaryLengthBytes(),t=new ArrayBuffer(e),n=new DataView(t),r=this.toBinaryInto(n);if(e!==r)throw new Error("".concat(this.constructor.name,".toBinary: written bytes (").concat(r," bytes) not equal to allocated array buffer length (").concat(e," bytes)."));return new Uint8Array(t)}},Ir;(function(i){i[i.UserTimestamp=2]="UserTimestamp",i[i.E2ee=1]="E2ee"})(Ir||(Ir={}));var da=class extends Rr{},Li=class i extends da{constructor(e){super(),this.timestamp=e}toBinaryLengthBytes(){return ze+ze+i.lengthBytes}toBinaryInto(e){let t=0;e.setUint8(t,i.tag),t+=ze,e.setUint8(t,i.lengthBytes),t+=ze,e.setBigUint64(t,this.timestamp),t+=gE;let n=this.toBinaryLengthBytes();if(t!==n)throw new Error("DataTrackUserTimestampExtension.toBinaryInto: Wrote ".concat(t," bytes but expected length
75was ").concat(n," bytes"));return t}toJSON(){return{tag:i.tag,lengthBytes:i.lengthBytes,timestamp:this.timestamp}}};Li.tag=Ir.UserTimestamp;Li.lengthBytes=8;var xi=class i extends da{constructor(e,t){super(),this.keyIndex=e,this.iv=t}toBinaryLengthBytes(){return ze+ze+i.lengthBytes}toBinaryInto(e){let t=0;e.setUint8(t,i.tag),t+=ze,e.setUint8(t,i.lengthBytes),t+=ze,e.setUint8(t,this.keyIndex),t+=ze;for(let r=0;r<this.iv.length;r+=1)e.setUint8(t,this.iv[r]),t+=ze;let n=this.toBinaryLengthBytes();if(t!==n)throw new Error("DataTrackE2eeExtension.toBinaryInto: Wrote ".concat(t," bytes but expected length was ").concat(n," bytes"));return t}toJSON(){return{tag:i.tag,lengthBytes:i.lengthBytes,keyIndex:this.keyIndex,iv:this.iv}}};xi.tag=Ir.E2ee;xi.lengthBytes=13;var Cr=class i extends Rr{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 r=this.e2ee.toBinaryInto(e);t+=r}if(this.userTimestamp){let r=this.userTimestamp.toBinaryInto(new DataView(e.buffer,e.byteOffset+t));t+=r}let n=this.toBinaryLengthBytes();if(t!==n)throw new Error("DataTrackExtensions.toBinaryInto: Wrote ".concat(t," bytes but expected length was ").concat(n," bytes"));return t}static fromBinary(e){let t=Bd(e),n,r,s=0;for(;t.byteLength-s>=ze+ze;){let o=t.getUint8(s);s+=ze;let a=t.getUint8(s);if(s+=ze,o!==kE)switch(o){case Ir.UserTimestamp:if(t.byteLength-s<Li.lengthBytes)throw dn.malformedExt(o);n=new Li(t.getBigUint64(s)),s+=a;break;case Ir.E2ee:if(t.byteLength-s<xi.lengthBytes)throw dn.malformedExt(o);let d=t.getUint8(s),l=new Uint8Array(12);for(let f=0;f<l.length;f+=1){let p=s;p+=ze,p+=f*ze,l[f]=t.getUint8(p)}r=new xi(d,l),s+=a;break;default:if(t.byteLength-s<a)throw dn.malformedExt(o);s+=a;break}}return[new i({userTimestamp:n,e2ee:r}),t.byteLength]}toJSON(){var e,t,n,r;return{userTimestamp:(t=(e=this.userTimestamp)===null||e===void 0?void 0:e.toJSON())!==null&&t!==void 0?t:null,e2ee:(r=(n=this.e2ee)===null||n===void 0?void 0:n.toJSON())!==null&&r!==void 0?r:null}}},vb={from(i){return{payload:i.payload,extensions:new Cr({userTimestamp:i.userTimestamp?new Li(i.userTimestamp):void 0})}},lossyIntoFrame(i){var e;return{payload:i.payload,userTimestamp:(e=i.extensions.userTimestamp)===null||e===void 0?void 0:e.timestamp}}},yb=Symbol.for("lk.track"),bb=Symbol.for("lk.data-track"),ha=class{constructor(e,t,n){this.trackSymbol=yb,this.isLocal=!1,this.typeSymbol=bb,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),n=pe(t,2),r=n[0];return n[1].catch(()=>{}),r}catch(t){throw t}}setPipelineOptions(e){this.manager.setPipelineOptions(this.info.sid,e)}},Ms=class i extends Rr{constructor(e){var t;super(),this.marker=e.marker,this.trackHandle=e.trackHandle,this.sequence=e.sequence,this.frameNumber=e.frameNumber,this.timestamp=e.timestamp,this.extensions=(t=e.extensions)!==null&&t!==void 0?t:new Cr}extensionsMetrics(){let e=this.extensions.toBinaryLengthBytes(),t=Math.ceil((Eo+e)/4),n=t*4-Eo-e;return{lengthBytes:e,lengthWords:t,paddingLengthBytes:n}}toBinaryLengthBytes(){let e=this.extensionsMetrics(),t=e.lengthBytes,n=e.paddingLengthBytes,r=ov;return t>0&&(r+=Eo+t+n),r}toBinaryInto(e){if(e.byteLength<this.toBinaryLengthBytes())throw ua.tooSmallForHeader();let t=sv<<av,n;switch(this.marker){case We.Inter:n=dv;break;case We.Final:n=uv;break;case We.Start:n=lv;break;case We.Single:n=hv;break}t|=n<<cv;let r=this.extensionsMetrics(),s=r.lengthBytes,o=r.lengthWords,a=r.paddingLengthBytes;s>0&&(t|=1<<pv);let d=0;if(e.setUint8(d,t),d+=ze,e.setUint8(d,0),d+=ze,e.setUint16(d,this.trackHandle),d+=An,e.setUint16(d,this.sequence.value),d+=An,e.setUint16(d,this.frameNumber.value),d+=An,e.setUint32(d,this.timestamp.asTicks()),d+=rv,s>0){let f=o-1;e.setUint16(d,f),d+=An;let p=this.extensions.toBinaryInto(new DataView(e.buffer,e.byteOffset+d));d+=p;for(let g=0;g<a;g+=1)e.setUint8(d,0),d+=ze}let l=this.toBinaryLengthBytes();if(d!==l)throw new Error("DataTrackPacketHeader.toBinaryInto: Wrote ".concat(d," bytes but expected length
75was ").concat(l," bytes"));return l}static fromBinary(e){let t=Bd(e);if(t.byteLength<ov)throw dn.tooShort();let n=0,r=t.getUint8(n);n+=ze;let s=r>>av&vE;if(s>sv)throw dn.unsupportedVersion(s);let o;switch(r>>cv&yE){case lv:o=We.Start;break;case uv:o=We.Final;break;case hv:o=We.Single;break;case dv:default:o=We.Inter;break}let a=(r>>pv&bE)>0;n+=ze;let d;try{d=fw.fromNumber(t.getUint16(n))}catch(b){throw b instanceof Ps&&(b.isReason(Ri.Reserved)||b.isReason(Ri.TooLarge))?dn.invalidHandle(b):b}n+=An;let l=ti.u16(t.getUint16(n));n+=An;let f=ti.u16(t.getUint16(n));n+=An;let p=zo.fromRtpTicks(t.getUint32(n));n+=rv;let g=new Cr;if(a){if(t.byteLength-n<An)throw dn.missingExtWords();let b=t.getUint16(n);n+=An;let w=4*(b+1)-Eo;if(n+w>t.byteLength)throw dn.headerOverrun();let I=new DataView(t.buffer,t.byteOffset+n,w),N=Cr.fromBinary(I),L=pe(N,2),j=L[0],M=L[1];g=j,n+=M}return[new i({marker:o,trackHandle:d,sequence:l,frameNumber:f,timestamp:p,extensions:g}),n]}toJSON(){return{marker:this.marker,trackHandle:this.trackHandle,sequence:this.sequence.value,frameNumber:this.frameNumber.value,timestamp:this.timestamp.asTicks(),extensions:this.extensions.toJSON()}}},We;(function(i){i[i.Start=0]="Start",i[i.Inter=1]="Inter",i[i.Final=2]="Final",i[i.Single=3]="Single"})(We||(We={}));var pa=class i extends Rr{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 ua.tooSmallForPayload();for(let s=0;s<this.payload.length;s+=1)e.setUint8(t,this.payload[s]),t+=ze;let r=this.toBinaryLengthBytes();if(t!==r)throw new Error("DataTrackPacket.toBinaryInto: Wrote ".concat(t," bytes but expected length was ").concat(r," bytes"));return r}static fromBinary(e){let t=Bd(e),n=Ms.fromBinary(t),r=pe(n,2),s=r[0],o=r[1],a=t.buffer.slice(t.byteOffset+o,t.byteOffset+t.byteLength);return[new i(s,new Uint8Array(a)),t.byteLength]}toJSON(){return{header:this.header.toJSON(),payload:this.payload}}},Nl=ut(Xe.DataTracks),Ei=class i extends Tt{constructor(e,t,n,r){super(19,"Frame ".concat(n," dropped: ").concat(e),r),this.name="DataTrackDepacketizerDropError",this.reason=t,this.reasonName=Pi[t],this.frameNumber=n}static interrupted(e,t){return new i("Interrupted by the start of a new frame ".concat(t),Pi.Interrupted,e)}static unknownFrame(e){return new i("Initial packet was never received.",Pi.UnknownFrame,e)}static bufferFull(e){return new i("Reorder buffer is full.",Pi.BufferFull,e)}static incomplete(e,t,n){return new i("Not all packets received before final packet. Received ".concat(t," packets, expected ").concat(n," packets."),Pi.Incomplete,e)}},Pi;(function(i){i[i.Interrupted=0]="Interrupted",i[i.UnknownFrame=1]="UnknownFrame",i[i.BufferFull=2]="BufferFull",i[i.Incomplete=3]="Incomplete"})(Pi||(Pi={}));var fa=class i{constructor(){this.partials=new Map}push(e,t){switch(e.header.marker){case We.Single:return this.frameFromSingle(e,t);case We.Start:return this.beginPartial(e,t);case We.Inter:case We.Final:return this.pushToPartial(e)}}reset(){this.partials.clear()}peekOldestPartialFrameNumber(){let e=this.partials.keys().next();return e.done?null:e.value}frameFromSingle(e,t){var n;if(e.header.marker!==We.Single)throw new Error("Depacketizer.frameFromSingle: packet.header.marker was not FrameMarker.Single, found ".concat(e.header.marker,"."));let r=(n=t?.maxPartialFrames)!==null&&n!==void 0?n:1;if(this.partials.size>=r){let s=this.peekOldestPartialFrameNumber();if(typeof s!="number")throw new Error("Depacketizer.frameFromSingle: no olde
75st frame number found, but partials.size is ".concat(this.partials.size,"."));if(this.partials.delete(s),t?.throwOnInterruption)throw Ei.interrupted(s,e.header.frameNumber.value);Nl.warn("Data track frame ".concat(s," was interrupted by single-packet frame ").concat(e.header.frameNumber.value,", dropping."))}return{payload:e.payload,extensions:e.header.extensions}}beginPartial(e,t){var n;if(e.header.marker!==We.Start)throw new Error("Depacketizer.beginPartial: packet.header.marker was not FrameMarker.Start, found ".concat(e.header.marker,"."));let r=e.header.sequence,s=e.header.frameNumber.value,o={startSequence:r,extensions:e.header.extensions,payloads:new Map([[r.value,e.payload]])},a=(n=t?.maxPartialFrames)!==null&&n!==void 0?n:1;for(;this.partials.size>=a;){let d=this.peekOldestPartialFrameNumber();if(typeof d!="number")break;if(this.partials.delete(d),t?.throwOnInterruption)throw Ei.interrupted(d,s);Nl.warn("Data track partials full (max ".concat(a,"), evicted oldest frame ").concat(d," to make room for new frame ").concat(s,"."))}return this.partials.set(s,o),null}pushToPartial(e){if(e.header.marker!==We.Inter&&e.header.marker!==We.Final)throw new Error("Depacketizer.pushToPartial: packet.header.marker was not FrameMarker.Inter or FrameMarker.Final, found ".concat(e.header.marker,"."));let t=e.header.frameNumber.value,n=this.partials.get(t);if(!n)throw this.partials.delete(t),Ei.unknownFrame(t);if(n.payloads.size>=i.MAX_BUFFER_PACKETS)throw this.partials.delete(t),Ei.bufferFull(t);return n.payloads.has(e.header.sequence.value)&&Nl.warn("Data track frame ".concat(t," received duplicate packet for sequence ").concat(e.header.sequence.value,", so replacing with newly received packet.")),n.payloads.set(e.header.sequence.value,e.payload),e.header.marker===We.Final?this.finalize(t,n,e.header.sequence.value):null}finalize(e,t,n){let r=t.payloads.size,s=0;for(let l of t.payloads.values())s+=l.length;let o=new Uint8Array(s),a=t.startSequence.clone(),d=0;for(;;){let l=t.payloads.get(a.value);if(!l)break;t.payloads.delete(a.value);let f=o.length-d;if(l.length>f)throw new Error("Depacketizer.finalize: Expected at least ".concat(l.length," more bytes left in the payload buffer, only got ").concat(f," bytes."));if(o.set(l,d),d+=l.length,a.value!=n){a.increment();continue}return this.partials.delete(e),{payload:o,extensions:t.extensions}}throw this.partials.delete(e),Ei.incomplete(e,r,n-t.startSequence.value+1)}};fa.MAX_BUFFER_PACKETS=128;var Ai;(function(i){i[i.Unpublished=0]="Unpublished",i[i.Timeout=1]="Timeout",i[i.Disconnected=2]="Disconnected",i[i.Cancelled=4]="Cancelled"})(Ai||(Ai={}));var Wt=class i extends Tt{constructor(e,t,n){super(22,e,n),this.name="DataTrackSubscribeError",this.reason=t,this.reasonName=Ai[t]}static unpublished(){return new i("The track has been unpublished and is no longer available",Ai.Unpublished)}static timeout(){return new i("Request to subscribe to data track timed-out",Ai.Timeout)}static disconnected(){return new i("Cannot subscribe to data track when disconnected",Ai.Disconnected)}static cancelled(){return new i("Subscription to data track cancelled by caller",Ai.Cancelled)}},Fl=ut(Xe.DataTracks),Fu=class{constructor(e){var t,n;let r=e.e2eeManager!==null;if(e.info.usesE2ee!==r)throw new Error("IncomingDataTrackPipeline: DataTrackInfo.usesE2ee must match presence of decryptionProvider");let s=new fa;this.publisherIdentity=e.publisherIdentity,this.e2eeManager=(t=e.e2eeManager)!==null&&t!==void 0?t:null,this.depacketizer=s,this.options=(n=e.pipelineOptions)!==null&&n!==void 0?n:{}}updateE2eeManager(e){this.e2eeManager=e}setOptions(e){this.options=e}processPacket(e){return A(this,void 0,void 0,function*(){let t=this.depacketize(e);if(!t)return null;let n=yield this.decryptIfNeeded(t);return n||null})}depacketize(e){let t;try{t=this.depacketizer.push(e,{throwOnInterruption:!1,maxPartialFrames:this.options.maxPartialFrames})}catch(n){return Fl.warn("Data frame depacketize error: ".concat(n)),null}return t}decryptIfNeeded(e){return A(this,void 0,void 0,function*(){var t,n;let r=this.e2eeManager;if(!r)return e;let s=(n=(t=e.extensions)===null||t===void 0?void 0:t.e2ee)!==null&&n!==void 0?n:null;if(!s)return Fl.error("Missing E2EE meta"),null;let o;try{o=yield r.handleEncryptedData(e.payload,s.iv,this.publisherIdentity,s.keyIndex)}catch(a){return Fl.error("Error decrypting packet: ".concat(a)),null}return e.payload=o.payload,e})}},Ze=ut(Xe.DataTracks),SE=1e4,TE=16,Uu=class extends _t.EventEmitter{constructor(e){var t;super(),this.descriptors=new Map,this.subscriptionHandles=new Map,this.e2eeManager=(t=e?.e2eeManager)!==null&&t!==void 0?t:null}updateE2eeManager(e){this.e2eeManager=e;for(let t of this.descriptors.values())t.subscription.type==="active"&&t.subscription.pipeline.updateE2eeManager(e)}setPipelineOptions(e,t){let n=this.descriptors.get(e);if(!n){Ze.warn("Unknown track ".concat(e,", cannot set pipeline options."));return}n.pipelineOptions=t,n.subscription.type==="active"&&n.subscription.pipeline.setOptions(t)}openSubscriptionStream(e,t){let n=arguments.length>2&&arguments[2]!==void 0?arguments[2]:TE,r=null,s=new nt,o=this.descriptors.get(e),a=()=>{t?.removeEventListener("abort",l)},d=()=>
75{if(a(),!r){Ze.warn("ReadableStream subscribed to ".concat(e," was not started."));return}if(!o||this.descriptors.get(o.info.sid)!==o){Ze.warn("Unknown track ".concat(e,", skipping cancel..."));return}if(o.subscription.type!=="active"){Ze.warn("Subscription for track ".concat(e," is not active, skipping cancel..."));return}o.subscription.streamControllers.delete(r),o.subscription.streamControllers.size===0&&this.unSubscribeRequest(o.info.sid)},l=()=>{var p;r&&(o?.subscription.type==="active"&&o.subscription.streamControllers.delete(r),r.error(Wt.cancelled()),(p=s.reject)===null||p===void 0||p.call(s,Wt.cancelled()),d())};return[new ReadableStream({start:p=>{r=p,this.subscribeRequest(e,t).then(()=>A(this,void 0,void 0,function*(){var g,b,R;if(!o||this.descriptors.get(o.info.sid)!==o){Ze.error("Unknown track ".concat(e));let w=Wt.disconnected();p.error(w),(g=s.reject)===null||g===void 0||g.call(s,w);return}if(o.subscription.type!=="active"){Ze.error("Subscription for track ".concat(e," is not active"));let w=Wt.disconnected();p.error(w),(b=s.reject)===null||b===void 0||b.call(s,w);return}if(t?.aborted){l();return}t?.addEventListener("abort",l),o.subscription.streamControllers.set(p,a),(R=s.resolve)===null||R===void 0||R.call(s)})).catch(g=>{var b;p.error(g),(b=s.reject)===null||b===void 0||b.call(s,g)})},cancel:()=>{d()}},new CountQueuingStrategy({highWaterMark:n})),s.promise]}subscribeRequest(e,t){return A(this,void 0,void 0,function*(){let n=this.descriptors.get(e);if(!n)throw new Error("Cannot subscribe to unknown track");let r=(s,o,a)=>A(this,void 0,void 0,function*(){if(s.subscription.type==="active")return;if(s.subscription.type!=="pending")throw new Error("Descriptor for track ".concat(e," is not pending, found ").concat(s.subscription.type));let d=mb([o,a].filter(p=>typeof p<"u")),l=new nt;s.subscription.completionFuture.promise.then(()=>{var p;return(p=l.resolve)===null||p===void 0?void 0:p.call(l)}).catch(p=>{var g;return(g=l.reject)===null||g===void 0?void 0:g.call(l,p)});let f=()=>{var p;if(s.subscription.type==="pending"){if(s.subscription.pendingRequestCount-=1,a?.aborted){s.subscription.cancel();return}if(s.subscription.pendingRequestCount<=0){s.subscription.cancel();return}(p=l.reject)===null||p===void 0||p.call(l,Wt.cancelled())}};d.aborted&&f(),d.addEventListener("abort",f),yield l.promise,d.removeEventListener("abort",f)});switch(n.subscription.type){case"none":{n.subscription={type:"pending",completionFuture:new nt,pendingRequestCount:1,cancel:()=>{var o,a;let d=n.subscription;n.subscription={type:"none"},this.emit("sfuUpdateSubscription",{sid:n.info.sid,subscribe:!1}),d.type==="pending"&&((a=(o=d.completionFuture).reject)===null||a===void 0||a.call(o,s.aborted?Wt.timeout():Wt.cancelled()))}},this.emit("sfuUpdateSubscription",{sid:e,subscribe:!0});let s=gb(SE);yield r(n,t,s);return}case"pending":{n.subscription.pendingRequestCount+=1,yield r(n,t);return}case"active":return}})}querySubscribed(){return A(this,void 0,void 0,function*(){return Array.from(this.descriptors.values()).filter(t=>t.subscription.type==="active").map(t=>[t.info,t.publisherIdentity])})}unSubscribeRequest(e){var t;let n=this.descriptors.get(e);if(!n)throw new Error("Cannot subscribe to unknown track");if(n.subscription.type!=="active"){Ze.warn("Unexpected descriptor state in unSubscribeRequest, expected active, found ".concat((t=n.subscription)===null||t===void 0?void 0:t.type));return}this.closeStreamControllers(n.subscription.streamControllers,e);let r=n.subscription;n.subscription={type:"none"},this.subscriptionHandles.delete(r.subcriptionHandle),this.emit("sfuUpdateSubscription",{sid:e,subscribe:!1})}closeStreamControllers(e,t){for(let r of e){var n=pe(r,2);let s=n[0],o=n[1];o();try{s.close()}catch(a){Ze.warn("Failed to close readable stream for track ".concat(t,": ").concat(a))}}}receiveSfuPublicationUpdates(e){return A(this,void 0,void 0,function*(){if(e.size===0)return;let t=new Map;for(let s of e.entries()){var n=pe(s,2);let o=n[0],a=n[1],d=new Set;for(let l of a)d.add(l.sid),!this.descriptors.has(l.sid)&&(this.handleSidReassigned(o,l)||(yield this.handleTrackPublished(o,l)));t.set(o,d)}for(let s of t.entries()){var r=pe(s,2);let o=r[0],a=r[1],l=Array.from(this.descriptors.entries()).filter(f=>{let p=pe(f,2);return p[0],p[1].publisherIdentity===o}).map(f=>pe(f,1)[0]).filter(f=>!a.has(f));for(let f of l)this.handleTrackUnpublished(f)}})}queryPublications(){return A(this,void 0,void 0,function*(){return Array.from(this.descriptors.values()).map(e=>e.info)})}handleTrackPublished(e,t){return A(this,void 0,void 0,function*(){if(this.descriptors.has(t.sid)){Ze.error("Existing descriptor for track ".concat(t.sid));return}let n={info:t,publisherIdentity:e,subscription:{type:"none"},pipelineOptions:{}};this.descriptors.set(n.info.sid,n);let r=new ha(n.info,this,{publisherIdentity:e});
75this.emit("trackPublished",{track:r})})}handleSidReassigned(e,t){let n=Array.from(this.descriptors.entries()).find(p=>{let g=pe(p,2);g[0];let b=g[1];return b.publisherIdentity===e&&b.info.pubHandle===t.pubHandle});if(!n)return!1;let r=pe(n,2),s=r[0],o=r[1],a=o.info,d=a.name,l=a.usesE2ee;if(d!==t.name||l!==t.usesE2ee)return Ze.warn("Info mismatch for ".concat(s,", treating as new publication")),!1;let f=t.sid;if(Ze.debug("SID reassigned: ".concat(s," -> ").concat(f)),!this.descriptors.delete(s))return!1;switch(o.info.sid=f,o.subscription.type){case"none":break;case"pending":case"active":this.emit("sfuUpdateSubscription",{sid:f,subscribe:!0});break}return o.subscription.type==="active"&&this.subscriptionHandles.set(o.subscription.subcriptionHandle,f),this.descriptors.set(f,o),!0}handleTrackUnpublished(e){let t=this.descriptors.get(e);if(!t){Ze.error("Unknown track ".concat(e));return}this.descriptors.delete(e),t.subscription.type==="active"&&(this.closeStreamControllers(t.subscription.streamControllers,e),this.subscriptionHandles.delete(t.subscription.subcriptionHandle)),this.emit("trackUnpublished",{sid:e,publisherIdentity:t.publisherIdentity})}receivedSfuSubscriberHandles(e){for(let n of e.entries()){var t=pe(n,2);let r=t[0],s=t[1];this.registerSubscriberHandle(r,s)}}registerSubscriberHandle(e,t){var n,r;let s=this.descriptors.get(t);if(!s){Ze.error("Unknown track ".concat(t));return}switch(s.subscription.type){case"none":{Ze.warn("No subscription for ".concat(t));return}case"active":{this.subscriptionHandles.delete(s.subscription.subcriptionHandle),s.subscription.subcriptionHandle=e,this.subscriptionHandles.set(e,t);return}case"pending":{Ze.debug("data track subscription activated",{sid:t,handle:e});let o=new Fu({info:s.info,publisherIdentity:s.publisherIdentity,e2eeManager:this.e2eeManager,pipelineOptions:s.pipelineOptions}),a=s.subscription;s.subscription={type:"active",subcriptionHandle:e,pipeline:o,streamControllers:new Map},this.subscriptionHandles.set(e,t),(r=(n=a.completionFuture).resolve)===null||r===void 0||r.call(n)}}}packetReceived(e){return A(this,void 0,void 0,function*(){let t;try{var n=pa.fromBinary(e),r=pe(n,1);t=r[0]}catch(d){Ze.error("Failed to deserialize packet: ".concat(d));return}let s=this.subscriptionHandles.get(t.header.trackHandle);if(!s){Ze.warn("Unknown subscriber handle ".concat(t.header.trackHandle));return}let o=this.descriptors.get(s);if(!o){Ze.error("Missing descriptor for track ".concat(s));return}if(o.subscription.type!=="active"){Ze.warn("Received packet for track ".concat(s," without active subscription"));return}let a=yield o.subscription.pipeline.processPacket(t);if(a)for(let d of o.subscription.streamControllers.keys()){if(d.desiredSize!==null&&d.desiredSize<=0){Ze.warn("Cannot send frame to subscribers: readable stream is full (desiredSize is ".concat(d.desiredSize,"). To increase this threshold, set a higher 'options.highWaterMark' when calling .subscribe()."));continue}let l=vb.lossyIntoFrame(a);d.enqueue(l)}})}resendSubscriptionUpdates(){for(let t of this.descriptors){var e=pe(t,2);let n=e[0];e[1].subscription.type!=="none"&&this.emit("sfuUpdateSubscription",{sid:n,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===void 0||n.call(t,Wt.disconnected());break;case"active":this.unSubscribeRequest(r.info.sid);break}}reset(){var e,t;
75for(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===void 0||t.call(e,Wt.disconnected())),n.subscription.type==="active"&&this.closeStreamControllers(n.subscription.streamControllers,n.info.sid);this.descriptors.clear(),this.subscriptionHandles.clear()}},ma=class i extends Tt{constructor(e,t,n){super(19,e,n),this.name="DataTrackPacketizerError",this.reason=t,this.reasonName=ga[t]}static mtuTooShort(){return new i("MTU is too short to send frame",ga.MtuTooShort)}},ga;(function(i){i[i.MtuTooShort=0]="MtuTooShort"})(ga||(ga={}));var ju=class i{constructor(e,t){this.sequence=ti.u16(0),this.frameNumber=ti.u16(0),this.clock=ku.rtpStartingNow(zo.rtpRandom()),this.handle=e,this.mtuSizeBytes=t}static computeFrameMarker(e,t){return t<=1?We.Single:e===0?We.Start:e===t-1?We.Final:We.Inter}*packetize(e,t){var n;let r=this.frameNumber.getThenIncrement(),s={marker:We.Inter,trackHandle:this.handle,sequence:ti.u16(0),frameNumber:r,timestamp:(n=t?.now)!==null&&n!==void 0?n:this.clock.now(),extensions:e.extensions},o=new Ms(s).toBinaryLengthBytes();if(o>=this.mtuSizeBytes)throw ma.mtuTooShort();let a=this.mtuSizeBytes-o,d=Math.ceil(e.payload.byteLength/a);for(let f=0,p=0;p<e.payload.byteLength;l=[f+1,p+a],f=l[0],p=l[1],l){var l;let g=this.sequence.getThenIncrement(),b=new Ms(Object.assign(Object.assign({},s),{marker:i.computeFrameMarker(f,d),sequence:g})),R=Math.min(a,e.payload.byteLength-p),w=new Uint8Array(e.payload.buffer,e.payload.byteOffset+p,R);yield new pa(b,w)}}},Gt;(function(i){i[i.NotAllowed=0]="NotAllowed",i[i.DuplicateName=1]="DuplicateName",i[i.Timeout=2]="Timeout",i[i.LimitReached=3]="LimitReached",i[i.Disconnected=4]="Disconnected",i[i.Cancelled=5]="Cancelled",i[i.InvalidName=6]="InvalidName",i[i.Unknown=7]="Unknown"})(Gt||(Gt={}));var Ut=class i extends Tt{constructor(e,t,n){super(21,e,n),this.name="DataTrackPublishError",this.reason=t,this.reasonName=Gt[t],this.rawMessage=n?.rawMessage}static notAllowed(e){return new i("Data track publishing unauthorized",Gt.NotAllowed,{rawMessage:e})}static duplicateName(e){return new i("Track name already taken",Gt.DuplicateName,{rawMessage:e})}static invalidName(e){return new i("Track name is invalid",Gt.InvalidName,{rawMessage:e})}static timeout(){return new i("Publish data track timed-out. Does the LiveKit server support data tracks?",Gt.Timeout)}static limitReached(e){return new i("Data track publication limit reached",Gt.LimitReached,{rawMessage:e})}static unknown(e,t){return new i("Received RequestResponse for publishDataTrack, but reason was unrecognised (".concat(e,", ").concat(t,")"),Gt.Unknown)}static disconnected(){return new i("Room disconnected",Gt.Disconnected)}static cancelled(){return new i("Publish data track cancelled by caller",Gt.Cancelled)}},ps;(function(i){i[i.TrackUnpublished=0]="TrackUnpublished",i[i.Dropped=1]="Dropped"})(ps||(ps={}));var Mi=class i extends Tt{constructor(e,t,n){super(22,e,n),this.name="DataTrackPushFrameError",this.reason=t,this.reasonName=ps[t]}static trackUnpublished(){return new i("Track is no longer published",ps.TrackUnpublished)}static dropped(e){return new i("Frame was dropped",ps.Dropped,{cause:e})}},fs;(function(i){i[i.Packetizer=0]="Packetizer",i[i.Encryption=1]="Encryption"})(fs||(fs={}));var va=class i extends Tt{constructor(e,t,n){super(21,e,n),this.name="DataTrackOutgoingPipelineError",this.reason=t,this.reasonName=fs[t]}static packetizer(e){return new i("Error packetizing frame",fs.Packetizer,{cause:e})}static encryption(e){return new i("Error encrypting frame",fs.Encryption,{cause:e})}},ya=class i{constructor(e,t){this.trackSymbol=yb,this.isLocal=!0,this.typeSymbol=bb,this.handle=null,this.log=ye,this.flushedFuture=new nt,this.isFlushed=!0,this.handleManagerReset=()=>{var n,r;(r=(n=this.flushedFuture).resolve)===null||r===void 0||r.call(n),this.manager.off("packetsFlushedChange",this.handleManagerPacketsFlushedChange),this.manager.off("reset",this.handleManagerReset)},this.handleManagerPacketsFlushedChange=n=>{var r,s;this.isFlushed=n.isFlushed,n.isFlushed&&((s=(r=this.flushedFuture).resolve)===null||s===void 0||s.call(r),this.flushedFuture=new nt)},this.options=e,this.manager=t,this.log=ut(Xe.DataTracks),this.manager.on("packetsFlushedChange",this.handleManagerPacketsFlushedChange),this.manager.on("reset",this.handleManagerReset)}static withExplicitHandle(e,t,n){let r=new i(e,t);return r.handle=n,r}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 A(this,void 0,void 0,function*(){try{this.handle=yield this.manager.publishRequest(this.options,e)}catch(t){throw t}})}isPublished(){var e;return((e=this.descriptor)===null||e===void 0?void 0:e.type)==="active"&&this.descriptor.publishState!=="unpublished"}tryPush(e){if(!this.handle)throw Mi.trackUnpublished();let t=vb.from(e);try{return this.manager.tryProcessAndSend(this.handle,t)}catch(n){throw n}}flush(){return A(this,void 0,void 0,function*(){if(!this.isFlushed)return this.flushedFuture.promise})}unpublish(){return A(this,void 0,void 0,function*(){if(!this.handle){ye.warn('Data track "'.concat(this.options.name,'" is not published, so unpublishing has no effect.'));return}try{yield this.manager.unpublishRequest(this.handle)}catch(e){throw e}})}},ba=class i{constructor(e){this.e2eeManager=e.e2eeManager,this.packetizer=new ju(e.info.pubHandle,i.TRANSPORT_MTU_BYTES)}updateE2eeManager(e){this.e2eeManager=e}processFrame(e){return dy(this,arguments,function*(){let n=yield xn(this.encryptIfNeeded(e));try{yield xn(yield*rC(Ft(this.packetizer.packetize(n))))}catch(r){throw r instanceof ma?va.packetizer(r):r}})}encryptIfNeeded(e){return A(this,void 0,void 0,function*(){if(!this.e2eeManager)return e;let t;try{t=yield this.e2eeManager.encryptData(e.payload)}catch(n){throw va.encryption(n)}return e.payload=t.payload,e.extensions.e2ee=new xi(t.keyIndex,t.iv),e})}};ba.TRANSPORT_MTU_BYTES=16e3;var xt=ut(Xe.DataTracks),fv={pending(){return{type:"pending",completionFuture:new nt}},active(i,e){return{type:"active",info:i,publishState:"published",pipeline:new ba({info:i,e2eeManager:e}),unpublishingFuture:new nt}}},_E=1e4,Bu=class i extends _t.EventEmitter{constructor(e){var t;super(),this.handleAllocator=new Su,this.descriptors=new Map,this.inFlightPacketCounter=new Map,this.e2eeManager=(t=e?.e2eeManager)!==null&&t!==void 0?t:null}static withDescriptors(e){let t=new i;return t.descriptors=e,t}updateE2eeManager(e){this.e2eeManager=e;for(let t of this.descriptors.values())t.type==="active"&&t.pipeline.updateE2eeManager(e)}
75getDescriptor(e){var t;return(t=this.descriptors.get(e))!==null&&t!==void 0?t:null}tryProcessAndSend(e,t){return A(this,void 0,void 0,function*(){var n,r,s,o,a;let d=this.getDescriptor(e);if(d?.type!=="active"||d.publishState==="unpublished")throw Mi.trackUnpublished();if(d.publishState==="republishing")throw Mi.dropped("Data track republishing");try{try{for(var l=!0,f=Ft(d.pipeline.processFrame(t)),p;p=yield f.next(),n=p.done,!n;l=!0){o=p.value,l=!1;let g=o,b=(a=this.inFlightPacketCounter.get(e))!==null&&a!==void 0?a:0;this.inFlightPacketCounter.set(e,b+1),b===0&&this.emit("packetsFlushedChange",{handle:e,isFlushed:!1}),this.emit("packetAvailable",{handle:e,bytes:g.toBinary()})}}catch(g){r={error:g}}finally{try{!l&&!n&&(s=f.return)&&(yield s.call(f))}finally{if(r)throw r.error}}}catch(g){throw Mi.dropped(g)}})}handlePacketSendComplete(e){var t;let r=((t=this.inFlightPacketCounter.get(e))!==null&&t!==void 0?t:0)-1;r<0&&(xt.warn("OutgoingDataTrackManager.handlePacketSendComplete: inFlightPacketCounter was decremented below 0 (got ".concat(this.inFlightPacketCounter," - resetting to 0. Were more packets send than were emitted?")),r=0),this.inFlightPacketCounter.set(e,r),r===0&&this.emit("packetsFlushedChange",{handle:e,isFlushed:!0})}publishRequest(e,t){return A(this,void 0,void 0,function*(){let n=this.handleAllocator.get();if(!n)throw Ut.limitReached();let r=gb(_E),s=t?mb([t,r]):r;if(this.descriptors.has(n))throw new Error("Descriptor for handle already exists");let o=fv.pending();this.descriptors.set(n,o);let a=()=>{var d,l;let f=this.descriptors.get(n);if(!f){xt.warn("No descriptor for ".concat(n));return}this.descriptors.delete(n),this.emit("sfuUnpublishRequest",{handle:n}),f.type==="pending"&&((l=(d=f.completionFuture).reject)===null||l===void 0||l.call(d,r.aborted?Ut.timeout():Ut.cancelled()))};return s.aborted?(a(),o.completionFuture.promise.then(()=>n)):(s.addEventListener("abort",a),this.emit("sfuPublishRequest",{handle:n,name:e.name,usesE2ee:this.e2eeManager!==null}),yield o.completionFuture.promise,s.removeEventListener("abort",a),this.emit("trackPublished",{track:ya.withExplicitHandle(e,this,n)}),n)})}queryPublished(){return Array.from(this.descriptors.values()).filter(t=>t.type==="active").map(t=>t.info)}unpublishRequest(e){return A(this,void 0,void 0,function*(){let t=this.descriptors.get(e);if(!t){xt.warn("No descriptor for ".concat(e));return}if(t.type!=="active"){xt.warn("Track ".concat(e," not active"));return}this.emit("sfuUnpublishRequest",{handle:e}),yield t.unpublishingFuture.promise,this.inFlightPacketCounter.delete(e),this.emit("trackUnpublished",{sid:t.info.sid})})}receivedSfuPublishResponse(e,t){var n,r,s,o;let a=this.descriptors.get(e);if(!a){xt.warn("No descriptor for ".concat(e));return}switch(this.descriptors.delete(e),a.type){case"pending":{if(t.type==="ok"){let d=t.data;xt.debug("SFU accepted publish request for handle ".concat(e),{sid:d.sid});let l=d.usesE2ee?this.e2eeManager:null;this.descriptors.set(d.pubHandle,fv.active(d,l)),(r=(n=a.completionFuture).resolve)===null||r===void 0||r.call(n)}else xt.debug("SFU rejected publish request for handle ".concat(e),{error:t.error}),(o=(s=a.completionFuture).reject)===null||o===void 0||o.call(s,t.error);return}case"active":{if(a.publishState!=="republishing"){xt.warn("Track ".concat(e," already active"));return}if(t.type==="error"){xt.warn("Republish failed for track ".concat(e));return}xt.debug("Track ".concat(e," republished")),a.info.sid=t.data.sid,a.publishState="published",this.descriptors.set(a.info.pubHandle,a)}}}receivedSfuUnpublishResponse(e){var t,n;let r=this.descriptors.get(e);if(!r){xt.warn("No descriptor for ".concat(e));return}if(this.descriptors.delete(e),r.type!=="active"){xt.warn("Track ".concat(e," not active"));return}r.publishState="unpublished",(n=(t=r.unpublishingFuture).resolve)===null||n===void 0||n.call(t)}sfuWillRepublishTracks(){var e,t;for(let r of this.descriptors.entries()){var n=pe(r,2);let s=n[0],o=n[1];switch(o.type){case"pending":this.descriptors.delete(s),(t=(e=o.completionFuture).reject)===null||t===void 0||t.call(e,Ut.disconnected());break;
75case"active":o.publishState="republishing",this.emit("sfuPublishRequest",{handle:o.info.pubHandle,name:o.info.name,usesE2ee:o.info.usesE2ee})}}}reset(){return A(this,void 0,void 0,function*(){var e,t,n,r;this.handleAllocator.reset();for(let s of this.descriptors.values())switch(s.type){case"pending":(t=(e=s.completionFuture).reject)===null||t===void 0||t.call(e,Ut.disconnected());break;case"active":(r=(n=s.unpublishingFuture).resolve)===null||r===void 0||r.call(n),yield this.unpublishRequest(s.info.pubHandle);break}this.descriptors.clear(),this.inFlightPacketCounter.clear(),this.emit("reset")})}},$e=class i extends Error{constructor(e,t,n,r){super(t),this.code=e,this.message=mv(t,i.MAX_MESSAGE_BYTES),this.data=n?mv(n,i.MAX_DATA_BYTES):void 0,typeof r?.cause<"u"&&(this.cause=r?.cause)}static fromProto(e){return new i(e.code,e.message,e.data)}toProto(){return new $v({code:this.code,message:this.message,data:this.data})}static builtIn(e,t,n){return new i(i.ErrorCode[e],i.ErrorMessage[e],t,n)}};$e.MAX_MESSAGE_BYTES=256;$e.MAX_DATA_BYTES=15360;$e.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};$e.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 kb=15360,Sb="lk.rpc_request",Tb="lk.rpc_response",ct;(function(i){i.RPC_REQUEST_ID="lk.rpc_request_id",i.RPC_REQUEST_METHOD="lk.rpc_request_method",i.RPC_REQUEST_RESPONSE_TIMEOUT_MS="lk.rpc_request_response_timeout_ms",i.RPC_REQUEST_VERSION="l
75k.rpc_request_version"})(ct||(ct={}));var CE=1,_b=2;function Wd(i){return new TextEncoder().encode(i).length}function mv(i,e){if(Wd(i)<=e)return i;let t=0,n=i.length,r=new TextEncoder;for(;t<n;){let s=Math.floor((t+n+1)/2);r.encode(i.slice(0,s)).length<=e?t=s:n=s-1}return i.slice(0,t)}var qu=class extends _t.EventEmitter{constructor(e,t,n,r){super(),this.pendingAcks=new Map,this.pendingResponses=new Map,this.log=e,this.outgoingDataStreamManager=t,this.getRemoteParticipantClientProtocol=n,this.getServerVersion=r}performRpc(e){return A(this,arguments,void 0,function(t){var n=this;let r=t.destinationIdentity,s=t.method,o=t.payload,a=t.responseTimeout,d=a===void 0?15e3:a;return(function*(){let p=n.getRemoteParticipantClientProtocol(r);if(Wd(o)>kb&&p<iu)throw $e.builtIn("REQUEST_PAYLOAD_TOO_LARGE");let b=n.getServerVersion();if(b&&fn(b,"1.8.0")<0)throw $e.builtIn("UNSUPPORTED_SERVER");let R=Math.max(d,8e3),w=crypto.randomUUID(),I=new nt,N=null,L=setTimeout(()=>{var M;n.pendingAcks.delete(w),(M=I.reject)===null||M===void 0||M.call(I,$e.builtIn("CONNECTION_TIMEOUT")),n.pendingResponses.delete(w),N!==null&&clearTimeout(N)},7e3);n.pendingAcks.set(w,{resolve:()=>{clearTimeout(L)},participantIdentity:r}),n.pendingResponses.set(w,{completionFuture:I,participantIdentity:r}),yield n.publishRpcRequest(r,w,s,o,R,p),N=setTimeout(()=>{var M;n.pendingResponses.delete(w),(M=I.reject)===null||M===void 0||M.call(I,$e.builtIn("RESPONSE_TIMEOUT"))},d);let j=I.promise.finally(()=>{clearTimeout(N),n.pendingAcks.has(w)&&(n.log.warn("RPC response received before ack",w),n.pendingAcks.delete(w),clearTimeout(L))});return[w,j]})()})}publishRpcRequest(e,t,n,r,s,o){return A(this,void 0,void 0,function*(){if(o>=iu){yield this.outgoingDataStreamManager.sendText(r,{topic:Sb,destinationIdentities:[e],attributes:{[ct.RPC_REQUEST_ID]:t,[ct.RPC_REQUEST_METHOD]:n,[ct.RPC_REQUEST_RESPONSE_TIMEOUT_MS]:"".concat(s),[ct.RPC_REQUEST_VERSION]:"".concat(_b)}});return}this.emit("sendDataPacket",{packet:new yt({destinationIdentities:[e],kind:Xn.RELIABLE,value:{case:"rpcRequest",value:new kd({id:t,method:n,payload:r,responseTimeoutMs:s,version:CE})}})})})}handleIncomingDataStream(e,t,n){return A(this,void 0,void 0,function*(){let r=n[ct.RPC_REQUEST_ID];if(!r){this.log.warn("RPC data stream malformed: ".concat(ct.RPC_REQUEST_ID," not set."));return}let s=this.pendingResponses.get(r);if(s&&s.participantIdentity!==t){this.log.warn("RPC response stream for ".concat(r," arrived from unexpected sender ").concat(t,", expected ").concat(s.participantIdentity,". Ignoring."));return}let o;try{o=yield e.readAll()}catch(a){this.log.warn("Error reading RPC response payload: ".concat(a)),this.handleIncomingRpcResponseFailure(r,$e.builtIn("APPLICATION_ERROR","Error reading RPC response payload",{cause:a}));return}this.handleIncomingRpcResponseSuccess(r,o)})}handleIncomingRpcResponseSuccess(e,t){var n,r;let s=this.pendingResponses.get(e);s?((r=(n=s.completionFuture).resolve)===null||r===void 0||r.call(n,t),this.pendingResponses.delete(e)):this.log.error("Response received for unexpected RPC request",e)}handleIncomingRpcResponseFailure(e,t){var n,r;let s=this.pendingResponses.get(e);s?((r=(n=s.completionFuture).reject)===null||r===void 0||r.call(n,t),this.pendingResponses.delete(e)):this.log.error("Response received for unexpected RPC request",e)}handleIncomingRpcAck(e){let t=this.pendingAcks.get(e);t?(t.resolve(),this.pendingAcks.delete(e)):this.log.error("Ack received for unexpected RPC request: ".concat(e))}handleParticipantDisconnected(e){var t;for(let o of this.pendingAcks){var n=pe(o,2);let a=n[0];n[1].participantIdentity===e&&this.pendingAcks.delete(a)}for(let o of this.pendingResponses){var r=pe(o,2);let a=r[0];var s=r[1];let d=s.participantIdentity,l=s.completionFuture;d===e&&((t=l.reject)===null||t===void 0||t.call(l,$e.builtIn("RECIPIENT_DISCONNECTED")),this.pendingResponses.delete(a))}}},Vu=class extends _t.EventEmitter{constructor(e,t,n){super(),this.rpcHandlers=new Map,this.log=e,this.outgoingDataStreamManager=t,this.getRemoteParticipantClientProtocol=n}registerRpcMethod(e,t){if(this.rpcHandlers.has(e))throw Error("RPC handler already registered for method ".concat(e,", unregisterR
75pcMethod before trying to register again"));this.rpcHandlers.set(e,t)}unregisterRpcMethod(e){this.rpcHandlers.delete(e)}handleIncomingRpcRequest(e,t){return A(this,void 0,void 0,function*(){var n;if(this.publishRpcAck(e,t.id),t.version!==1){this.publishRpcResponsePacket(e,t.id,null,$e.builtIn("UNSUPPORTED_VERSION"));return}let r=this.rpcHandlers.get(t.method);if(!r){this.publishRpcResponsePacket(e,t.id,null,$e.builtIn("UNSUPPORTED_METHOD"));return}let s;try{s=yield r({requestId:t.id,callerIdentity:e,payload:t.payload,responseTimeout:t.responseTimeoutMs})}catch(o){let a;o instanceof $e?a=o:(this.log.warn("Uncaught error returned by RPC handler for ".concat(t.method,". Returning APPLICATION_ERROR instead."),o),a=$e.builtIn("APPLICATION_ERROR","Uncaught error: ".concat((n=o?.message)!==null&&n!==void 0?n:o),{cause:o})),this.publishRpcResponsePacket(e,t.id,null,a);return}yield this.publishRpcResponse(e,t.id,s??"")})}handleIncomingDataStream(e,t,n){return A(this,void 0,void 0,function*(){let r=n[ct.RPC_REQUEST_ID],s=n[ct.RPC_REQUEST_METHOD],o=parseInt(n[ct.RPC_REQUEST_RESPONSE_TIMEOUT_MS],10),a=parseInt(n[ct.RPC_REQUEST_VERSION],10);if(!r||!s||Number.isNaN(o)||Number.isNaN(a)){this.log.warn("RPC data stream malformed: ".concat(ct.RPC_REQUEST_ID," / ").concat(ct.RPC_REQUEST_METHOD," / ").concat(ct.RPC_REQUEST_RESPONSE_TIMEOUT_MS," / ").concat(ct.RPC_REQUEST_VERSION," not set.")),this.publishRpcResponsePacket(t,r,null,$e.builtIn("APPLICATION_ERROR","RPC data stream malformed"));return}if(this.publishRpcAck(t,r),a!==_b){this.publishRpcResponsePacket(t,r,null,$e.builtIn("UNSUPPORTED_VERSION"));return}let d;try{d=yield e.readAll()}catch(p){this.log.warn("Error reading RPC request payload: ".concat(p)),this.publishRpcResponsePacket(t,r,null,$e.builtIn("APPLICATION_ERROR","Error reading RPC request payload",{cause:p}));return}let l=this.rpcHandlers.get(s);if(!l){this.publishRpcResponsePacket(t,r,null,$e.builtIn("UNSUPPORTED_METHOD"));return}let f;try{f=yield l({requestId:r,callerIdentity:t,payload:d,responseTimeout:o})}catch(p){let g;p instanceof $e?g=p:(this.log.warn("Uncaught error returned by RPC handler for ".concat(s,". Returning APPLICATION_ERROR instead."),p),g=$e.builtIn("APPLICATION_ERROR")),this.publishRpcResponsePacket(t,r,null,g);return}yield this.publishRpcResponse(t,r,f??"")})}publishRpcAck(e,t){this.emit("sendDataPacket",{packet:new yt({destinationIdentities:[e],kind:Xn.RELIABLE,value:{case:"rpcAck",value:new Ea({requestId:t})}})})}publishRpcResponsePacket(e,t,n,r){this.emit("sendDataPacket",{packet:new yt({destinationIdentities:[e],kind:Xn.RELIABLE,value:{case:"rpcResponse",value:new Sd({requestId:t,value:r?{case:"error",value:r.toProto()}:{case:"payload",value:n??""}})}})})}publishRpcResponse(e,t,n){return A(this,void 0,void 0,function*(){if(this.getRemoteParticipantClientProtocol(e)>=iu){yield this.outgoingDataStreamManager.sendText(n,{topic:Tb,destinationIdentities:[e],attributes:{[ct.RPC_REQUEST_ID]:t}});return}if(Wd(n)>kb){this.log.warn("RPC Response payload too large for request ".concat(t,". To send larger responses, consider updating the sending client.")),this.publishRpcResponsePacket(e,t,null,$e.builtIn("RESPONSE_PAYLOAD_TOO_LARGE"));return}this.publishRpcResponsePacket(e,t,n,null)})}},$u=class extends Ko{constructor(e,t,n,r,s,o){super(e,t,J.Kind.Audio,n,o),this.monitorReceiver=()=>A(this,void 0,void 0,function*(){if(!this.receiver){this._currentBitrate=0;return}let a=yield this.getReceiverStats();a&&this.prevStats&&this.receiver&&(this._currentBitrate=Da(a,this.prevStats)),this.prevStats=a}),this.audioContext=r,this.webAudioPluginNodes=[],s&&(this.sinkId=s.deviceId)}setVolume(e){var t;for(let n of this.attachedElements)this.audioContext?(t=this.gainNode)===null||t===void 0||t.gain.setTargetAtTime(e,0,.1):n.volume=e;en()&&this._mediaStreamTrack._setVolume(e),this.elementVolume=e}getVolume(){if(this.elementVolume)return this.elementVolume;if(en())return 1;let e=0;return this.attachedElements.forEach(t=>{t.volume>e&&(e=t.volume)}),e}setSinkId(e){return A(this,void 0,void 0,function*(){this.sinkId=e,yield Promise.all(this.attachedElements.map(t=>{if(hu(t))return t.setSinkId(e)}))})}attach(e){let t=this.attachedElements.length===0;return e?super.attach(e):e=super.attach(),this.sinkId&&hu(e)&&e.setSinkId(this.sinkId).catch(n=>{this.log.error("Failed to set sink id on remote audio track",n,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;
75this.webAudioPluginNodes.forEach(r=>{n.connect(r),n=r}),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(re.AudioPlaybackFailed,new Error("Audio Context couldn't be started automatically"))}).catch(r=>{this.emit(re.AudioPlaybackFailed,r)})}disconnectWebAudio(){var e,t;(e=this.gainNode)===null||e===void 0||e.disconnect(),(t=this.sourceNode)===null||t===void 0||t.disconnect(),this.gainNode=void 0,this.sourceNode=void 0}getReceiverStats(){return A(this,void 0,void 0,function*(){if(!this.receiver||!this.receiver.getStats)return;let e=yield this.receiver.getStats(),t;return e.forEach(n=>{n.type==="inbound-rtp"&&(t={type:"audio",streamId:n.id,timestamp:n.timestamp,jitter:n.jitter,bytesReceived:n.bytesReceived,concealedSamples:n.concealedSamples,concealmentEvents:n.concealmentEvents,silentConcealedSamples:n.silentConcealedSamples,silentConcealmentEvents:n.silentConcealmentEvents,totalAudioEnergy:n.totalAudioEnergy,totalSamplesDuration:n.totalSamplesDuration})}),t})}},Ht=class extends _t.EventEmitter{constructor(e,t,n,r){var s;super(),this.metadataMuted=!1,this.encryption=Ie.NONE,this.log=ye,this.handleMuted=()=>{this.emit(re.Muted)},this.handleUnmuted=()=>{this.emit(re.Unmuted)},this.log=ut((s=r?.loggerName)!==null&&s!==void 0?s:Xe.Publication),this.loggerContextCb=this.loggerContextCb,this.setMaxListeners(100),this.kind=e,this.trackSid=t,this.trackName=n,this.source=J.Source.Unknown}setTrack(e){this.track&&(this.track.off(re.Muted,this.handleMuted),this.track.off(re.Unmuted,this.handleUnmuted)),this.track=e,e&&(e.on(re.Muted,this.handleMuted),e.on(re.Unmuted,this.handleUnmuted))}get logContext(){var e;return Object.assign(Object.assign({},(e=this.loggerContextCb)===null||e===void 0?void 0:e.call(this)),_e(this))}get isMuted(){return this.metadataMuted}get isEnabled(){return!0}get isSubscribed(){return this.track!==void 0}get isEncrypted(){return this.encryption!==Ie.NONE}get audioTrack(){if(pn(this.track))return this.track}get videoTrack(){if(Fn(this.track))return this.track}updateInfo(e){this.trackSid=e.sid,this.trackName=e.name,this.source=J.sourceFromProto(e.source),this.mimeType=e.mimeType,this.kind===J.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(i){(function(e){e.Desired="desired",e.Subscribed="subscribed",e.Unsubscribed="unsubscribed"})(i.SubscriptionStatus||(i.SubscriptionStatus={})),(function(e){e.Allowed="allowed",e.NotAllowed="not_allowed"})(i.PermissionStatus||(i.PermissionStatus={}))})(Ht||(Ht={}));var Rs=class extends Ht{get isUpstreamPaused(){var e;return(e=this.track)===null||e===void 0?void 0:e.isUpstreamPaused}constructor(e,t,n,r){super(e,t.sid,t.name,r),this.track=void 0,this.handleTrackEnded=()=>{this.emit(re.Ended)},this.handleCpuConstrained=()=>{this.track&&Fn(this.track)&&this.emit(re.CpuConstrained,this.track)},this.updateInfo(t),this.setTrack(n)}setTrack(e){this.track&&(this.track.off(re.Ended,this.handleTrackEnded),this.track.off(re.CpuConstrained,this.handleCpuConstrained)),super.setTrack(e),e&&(e.on(re.Ended,this.handleTrackEnded),e.on(re.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 A(this,void 0,void 0,function*(){var e;return(e=this.track)===null||e===void 0?void 0:e.mute()})}unmute(){return A(this,void 0,void 0,function*(){var e;return(e=this.track)===null||e===void 0?void 0:e.unmute()})}pauseUpstream(){return A(this,void 0,void 0,function*(){var e;yield(e=this.track)===null||e===void 0?void 0:e.pauseUpstream()})}resumeUpstream(){return A(this,void 0,void 0,function*(){var e;yield(e=this.track)===null||e===void 0?void 0:e.resumeUpstream()})}getTrackFeatures(){var e;if(pn(this.track)){let t=this.track.getSourceTrackSettings(),n=new Set;return t.autoGainControl&&n.add(ot.TF_AUTO_GAIN_CONTROL),t.echoCancellation&&n.add(ot.TF_ECHO_CANCELLATION),t.noiseSuppression&&n.add(ot.TF_NOISE_SUPPRESSION),t.channelCount&&t.channelCount>1&&n.add(ot.TF_STEREO),!((e=this.options)===null||e===void 0)&&e.dtx||n.add(ot.TF_NO_DTX),this.track.enhancedNoiseCancellation&&n.add(ot.TF_ENHANCED_NOISE_CANCELLATION),Array.from(n.values())}else return[]}};function La(i,e){return A(this,void 0,void 0,function*(){i??(i={});let t=!1,n=Qy(i),r=n.audioProcessor,s=n.videoProcessor,o=n.optionsWithoutProcessor,a=o.audio,d=o.video;
75if(r&&typeof o.audio=="object"&&(o.audio.processor=r),s&&typeof o.video=="object"&&(o.video.processor=s),i.audio&&typeof o.audio=="object"&&typeof o.audio.deviceId=="string"){let g=o.audio.deviceId;o.audio.deviceId={exact:g},t=!0,a=Object.assign(Object.assign({},o.audio),{deviceId:{ideal:g}})}if(o.video&&typeof o.video=="object"&&typeof o.video.deviceId=="string"){let g=o.video.deviceId;o.video.deviceId={exact:g},t=!0,d=Object.assign(Object.assign({},o.video),{deviceId:{ideal:g}})}o.audio===!0?o.audio={deviceId:"default"}:typeof o.audio=="object"&&o.audio!==null&&(o.audio=Object.assign(Object.assign({},o.audio),{deviceId:o.audio.deviceId||"default"})),o.video===!0?o.video={deviceId:"default"}:typeof o.video=="object"&&!o.video.deviceId&&(o.video.deviceId="default");let l=Ky(o,ob,ab),f=Ld(l),p=navigator.mediaDevices.getUserMedia(f);o.audio&&(Mt.userMediaPromiseMap.set("audioinput",p),p.catch(()=>Mt.userMediaPromiseMap.delete("audioinput"))),o.video&&(Mt.userMediaPromiseMap.set("videoinput",p),p.catch(()=>Mt.userMediaPromiseMap.delete("videoinput")));try{let g=yield p;return yield Promise.all(g.getTracks().map(b=>A(this,void 0,void 0,function*(){let R=b.kind==="audio",w,I=R?f.audio:f.video;typeof I!="boolean"&&(w=I);let N=b.getSettings().deviceId;w?.deviceId&&Sr(w.deviceId)!==N?w.deviceId=N:w||(w={deviceId:N});let L=Jw(b,w,e);return L.kind===J.Kind.Video?L.source=J.Source.Camera:L.kind===J.Kind.Audio&&(L.source=J.Source.Microphone),L.mediaStream=g,pn(L)&&r?yield L.setProcessor(r):Fn(L)&&s&&(yield L.setProcessor(s)),L})))}catch(g){if(!t)throw g;return La(Object.assign(Object.assign({},i),{audio:a,video:d}),e)}})}function wE(i){return A(this,void 0,void 0,function*(){return(yield La({audio:!1,video:i??!0}))[0]})}function Gd(i){return A(this,void 0,void 0,function*(){return(yield La({audio:i??!0,video:!1}
75))[0]})}var Kn;(function(i){i.Excellent="excellent",i.Good="good",i.Poor="poor",i.Lost="lost",i.Unknown="unknown"})(Kn||(Kn={}));function EE(i){switch(i){case pr.EXCELLENT:return Kn.Excellent;case pr.GOOD:return Kn.Good;case pr.POOR:return Kn.Poor;case pr.LOST:return Kn.Lost;default:return Kn.Unknown}}var ka=class extends _t.EventEmitter{get logContext(){var e,t;return Object.assign({},(t=(e=this.loggerOptions)===null||e===void 0?void 0:e.loggerContextCb)===null||t===void 0?void 0:t.call(e))}get isEncrypted(){return this.trackPublications.size>0&&Array.from(this.trackPublications.values()).every(e=>e.isEncrypted)}get isAgent(){var e;return((e=this.permissions)===null||e===void 0?void 0:e.agent)||this.kind===vs.AGENT}get isActive(){var e;return((e=this.participantInfo)===null||e===void 0?void 0:e.state)===gr.ACTIVE}get kind(){return this._kind}get attributes(){return Object.freeze(Object.assign({},this._attributes))}constructor(e,t,n,r,s,o){let a=arguments.length>6&&arguments[6]!==void 0?arguments[6]:vs.STANDARD;var d;super(),this.audioLevel=0,this.isSpeaking=!1,this._connectionQuality=Kn.Unknown,this.log=ye,this.loggerOptions=o,this.log=ut((d=o?.loggerName)!==null&&d!==void 0?d:Xe.Participant,()=>this.logContext),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=a,this._attributes=s??{}}getTrackPublications(){return Array.from(this.trackPublications.values())}getTrackPublication(e){for(let n of this.trackPublications){var t=pe(n,2);let r=t[1];if(r.source===e)return r}}getTrackPublicationByName(e){for(let n of this.trackPublications){var t=pe(n,2);let r=t[1];if(r.trackName===e)return r}}waitUntilActive(){return this.isActive?Promise.resolve():this.activeFuture?this.activeFuture.promise:(this.activeFuture=new nt,this.once(ce.Active,()=>{var e,t;(t=(e=this.activeFuture)===null||e===void 0?void 0:e.resolve)===null||t===void 0||t.call(e),this.activeFuture=void 0}),this.activeFuture.promise)}get connectionQuality(){return this._connectionQuality}get isCameraEnabled(){var e;let t=this.getTrackPublication(J.Source.Camera);return!(!((e=t?.isMuted)!==null&&e!==void 0)||e)}get isMicrophoneEnabled(){var e;let t=this.getTrackPublication(J.Source.Microphone);return!(!((e=t?.isMuted)!==null&&e!==void 0)||e)}get isScreenShareEnabled(){return!!this.getTrackPublication(J.Source.ScreenShare)}get isLocal(){return!1}get joinedAt(){return this.participantInfo?new Date(Number.parseInt(this.participantInfo.joinedAt.toString())*1e3):new Date}updateInfo(e){var t;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===gr.ACTIVE&&((t=this.participantInfo)===null||t===void 0?void 0:t.state)!==gr.ACTIVE&&this.emit(ce.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(ce.ParticipantMetadataChanged,n)}_setName(e){let t=this.name!==e;this.name=e,t&&this.emit(ce.ParticipantNameChanged,e)}_setAttributes(e){let t=AC(this.attributes,e);this._attributes=e,Object.keys(t).length>0&&this.emit(ce.AttributesChanged,t)}setPermissions(e){var t,n,r,s,o,a;let d=this.permissions,l=e.canPublish!==((t=this.permissions)===null||t===void 0?void 0:t.canPublish)||e.canSubscribe!==((n=this.permissions)===null||n===void 0?void 0:n.canSubscribe)||e.canPublishData!==((r=this.permissions)===null||r===void 0?void 0:r.canPublishData)||e.hidden!==((s=this.permissions)===null||s===void 0?void 0:s.hidden)||e.recorder!==((o=this.permissions)===null||o===void 0?void 0:o.recorder)||e.canPublishSources.length!==this.permissions.canPublishSources.length||e.canPublishSources.some((f,p)=>{var g;return f!==((g=this.permissions)===null||g===void 0?void 0:g.canPublishSources[p])})||e.canSubscribeMetrics!==((a=this.permissions)===null||a===void 0?void 0:a.canSubscribeMetrics);
75return this.permissions=e,l&&this.emit(ce.ParticipantPermissionsChanged,d),l}setIsSpeaking(e){e!==this.isSpeaking&&(this.isSpeaking=e,e&&(this.lastSpokeAt=new Date),this.emit(ce.IsSpeakingChanged,e))}setConnectionQuality(e){let t=this._connectionQuality;this._connectionQuality=EE(e),t!==this._connectionQuality&&this.emit(ce.ConnectionQualityChanged,this._connectionQuality)}setDisconnected(){var e,t;this.activeFuture&&((t=(e=this.activeFuture).reject)===null||t===void 0||t.call(e,new Error("Participant disconnected")),this.activeFuture=void 0)}setAudioContext(e){this.audioContext=e,this.audioTrackPublications.forEach(t=>pn(t.track)&&t.track.setAudioContext(e))}addTrackPublication(e){this.log.debug("adding track publication",{trackSid:e.trackSid,source:e.source,kind:e.kind}),e.on(re.Muted,()=>{this.emit(ce.TrackMuted,e)}),e.on(re.Unmuted,()=>{this.emit(ce.TrackUnmuted,e)});let t=e;switch(t.track&&(t.track.sid=e.trackSid),this.trackPublications.set(e.trackSid,e),e.kind){case J.Kind.Audio:this.audioTrackPublications.set(e.trackSid,e);break;case J.Kind.Video:this.videoTrackPublications.set(e.trackSid,e);break}}};function PE(i){var e,t,n;if(!i.participantSid&&!i.participantIdentity)throw new Error("Invalid track permission, must provide at least one of participantIdentity and participantSid");return new sy({participantIdentity:(e=i.participantIdentity)!==null&&e!==void 0?e:"",participantSid:(t=i.participantSid)!==null&&t!==void 0?t:"",allTracks:(n=i.allowAll)!==null&&n!==void 0?n:!1,trackSids:i.allowedTrackSids||[]})}var Wu=class extends ka{constructor(e,t,n,r,s,o,a,d){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=Ie.NONE,this.e2eeStateMutex=new tt,this.enabledPublishVideoCodecs=[],this.handleReconnecting=()=>{this.reconnectFuture||(this.reconnectFuture=new nt)},this.handleReconnected=()=>{var l,f;(f=(l=this.reconnectFuture)===null||l===void 0?void 0:l.resolve)===null||f===void 0||f.call(l),this.reconnectFuture=void 0,this.updateTrackSubscriptionPermissions()},this.handleClosing=()=>{var l,f,p,g,b,R;this.reconnectFuture&&(this.reconnectFuture.promise.catch(w=>this.log.warn(w.message)),(f=(l=this.reconnectFuture)===null||l===void 0?void 0:l.reject)===null||f===void 0||f.call(l,new Error("Got disconnected during reconnection attempt")),this.reconnectFuture=void 0),this.signalConnectedFuture&&((g=(p=this.signalConnectedFuture).reject)===null||g===void 0||g.call(p,new Error("Got disconnected without signal connected")),this.signalConnectedFuture=void 0),(R=(b=this.activeAgentFuture)===null||b===void 0?void 0:b.reject)===null||R===void 0||R.call(b,new Error("Got disconnected without active agent present")),this.activeAgentFuture=void 0,this.firstActiveAgent=void 0},this.handleSignalConnected=l=>{var f,p;l.participant&&this.updateInfo(l.participant),this.signalConnectedFuture||(this.signalConnectedFuture=new nt),(p=(f=this.signalConnectedFuture).resolve)===null||p===void 0||p.call(f)},this.handleSignalRequestResponse=l=>{let f=l.requestId,p=l.reason,g=l.message,b=this.pendingSignalRequests.get(f);switch(b&&(p!==Ti.OK&&b.reject(new Go(g,p)),this.pendingSignalRequests.delete(f)),l.request.case){case"publishDataTrack":{let R;switch(l.reason){case Ti.NOT_ALLOWED:R=Ut.notAllowed(l.message);break;case Ti.DUPLICATE_NAME:R=Ut.duplicateName(l.message);break;case Ti.INVALID_NAME:R=Ut.invalidName(l.message);break;case Ti.LIMIT_EXCEEDED:R=Ut.limitReached(l.message);break;default:R=Ut.unknown(l.reason,l.message);break}this.roomOutgoingDataTrackManager.receivedSfuPublishResponse(l.request.value.pubHandle,{type:"error",error:R});break}}},this.updateTrackSubscriptionPermissions=()=>{this.log.debug("updating track subscription permissions",{allParticipantsAllowed:this.allParticipantsAllowedToSubscribe,participantTrackPermissions:this.participantTrackPermissions}),this.engine.client.sendUpdateSubscriptionPermissions(this.allParticipantsAllowedToSubscribe,this.participantTrackPermissions.map(l=>PE(l)))},this.onTrackUnmuted=l=>{this.onTrackMuted(l,l.isUpstreamPaused)},this.onTrackMuted=(l,f)=>{if(f===void 0&&(f=!0),!l.sid){this.log.error("could not update mute status for unpublished track",_e(l));return}this.engine.updateMuteStatus(l.sid,f)},this.onTrackUpstreamPaused=l=>{this.log.debug("upstream paused",_e(l)),this.onTrackMuted(l,!0)},this.onTrackUpstreamResumed=l=>{this.log.debug("upstream resumed",_e(l)),this.onTrackMuted(l,l.isMuted)},this.onTrackFeatureUpdate=l=>{let f=this.audioTrackPublications.get(l.sid);if(!f){this.log.warn("Could not update local audio track settings, missing publication for track ".concat(l.sid));return}this.engine.client.sendUpdateLocalAudioTrack(f.trackSid,f.getTrackFeatures())},this.onTrackCpuConstrained=(l,f)=>
75{this.log.debug("track cpu constrained",_e(f)),this.emit(ce.LocalTrackCpuConstrained,l,f)},this.handleSubscribedQualityUpdate=l=>A(this,void 0,void 0,function*(){var f,p,g,b,R;if(!(!((R=this.roomOptions)===null||R===void 0)&&R.dynacast))return;let w=this.videoTrackPublications.get(l.trackSid);if(!w){this.log.warn("received subscribed quality update for unknown track",{trackSid:l.trackSid});return}if(!w.videoTrack)return;let I=yield w.videoTrack.setPublishingCodecs(l.subscribedCodecs);try{for(var N=!0,L=Ft(I),j;j=yield L.next(),f=j.done,!f;N=!0){b=j.value,N=!1;let M=b;_C(M)&&(this.log.debug("publish ".concat(M," for ").concat(w.videoTrack.sid),_e(w)),yield this.publishAdditionalCodecForTrack(w.videoTrack,M,w.options))}}catch(M){p={error:M}}finally{try{!N&&!f&&(g=L.return)&&(yield g.call(L))}finally{if(p)throw p.error}}}),this.handleLocalTrackUnpublished=l=>{let f=this.trackPublications.get(l.trackSid);if(!f){this.log.warn("received unpublished event for unknown track",{trackSid:l.trackSid});return}this.unpublishTrack(f.track)},this.handleTrackEnded=l=>A(this,void 0,void 0,function*(){if(l.source===J.Source.ScreenShare||l.source===J.Source.ScreenShareAudio)this.log.debug("unpublishing local track due to TrackEnded",_e(l)),this.unpublishTrack(l);else if(l.isUserProvided)yield l.mute();else if(Rn(l)||an(l))try{if(St())try{let f=yield navigator?.permissions.query({name:l.source===J.Source.Camera?"camera":"microphone"});if(f&&f.state==="denied")throw this.log.warn("user has revoked access to ".concat(l.source),_e(l)),f.onchange=()=>{f.state!=="denied"&&(l.isMuted||l.restartTrack(),f.onchange=null)},new Error("GetUserMedia Permission denied")}catch{}l.isMuted||(this.log.debug("track ended, attempting to use a different device",_e(l)),Rn(l)?yield l.restartTrack({deviceId:"default"}):yield l.restartTrack())}catch{this.log.warn("could not restart track, muting instead",_e(l)),yield l.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.roomOutgoingDataStreamManager=s,this.roomOutgoingDataTrackManager=o,this.rpcClientManager=a,this.rpcServerManager=d}get lastCameraError(){return this.cameraError}get lastMicrophoneError(){return this.microphoneError}get isE2EEEnabled(){return this.encryptionType!==Ie.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){var t;this.engine=e,this.engine.on(X.RemoteMute,(n,r)=>{let s=this.trackPublications.get(n);!s||!s.track||(r?s.mute():s.unmute())}),!((t=this.signalConnectedFuture)===null||t===void 0)&&t.isResolved&&(this.signalConnectedFuture=void 0),this.engine.on(X.Connected,this.handleReconnected).on(X.SignalConnected,this.handleSignalConnected).on(X.SignalRestarted,this.handleReconnected).on(X.SignalResumed,this.handleReconnected).on(X.Restarting,this.handleReconnecting).on(X.Resuming,this.handleReconnecting).on(X.LocalTrackUnpublished,this.handleLocalTrackUnpublished).on(X.SubscribedQualityUpdate,this.handleSubscribedQualityUpdate).on(X.Closing,this.handleClosing).on(X.SignalRequestResponse,this.handleSignalRequestResponse)}setMetadata(e){return A(this,void 0,void 0,function*(){yield this.requestMetadataUpdate({metadata:e})})}setName(e){return A(this,void 0,void 0,function*(){yield this.requestMetadataUpdate({name:e})})}setAttributes(e){return A(this,void 0,void 0,function*(){yield this.requestMetadataUpdate({attributes:e})})}requestMetadataUpdate(e){return A(this,arguments,void 0,function(t){var n=this;let r=t.metadata,s=t.name,o=t.attributes;return(function*(){return new lt((a,d)=>A(n,void 0,void 0,function*(){var l,f;try{let p=!1,g=yield this.engine.client.sendUpdateLocalMetadata((l=r??this.metadata)!==null&&l!==void 0?l:"",(f=s??this.name)!==null&&f!==void 0?f:"",o),b=performance.now();for(this.pendingSignalRequests.set(g,{resolve:a,reject:R=>{d(R),p=!0},values:{name:s,metadata:r,attributes:o}});performance.now()-b<5e3&&!p;){if((!s||this.name===s)&&(!r||this.metadata===r)&&(!o||Object.entries(o).every(R=>{let w=pe(R,2),I=w[0],N=w[1];return this.attributes[I]===N||N===""&&!this.attributes[I]}))){this.pendingSignalRequests.delete(g),a();return}yield ft(50)}d(new Go("Request to update local metadata timed out","TimeoutError"))}catch(p){p instanceof Error?d(p):d(new Error(String(p)))}}))})()})}setCameraEnabled(e,t,n){return this.setTrackEnabled(J.Source.Camera,e,t,n)}setMicrophoneEnabled(e,t,n){return this.setTrackEnabled(J.Source.Microphone,e,t,n)}setScreenShareEnabled(e,t,n){return this.setTrackEnabled(J.Source.ScreenShare,e,t,n)}setE2EEEnabled(e){return A(this,void 0,void 0,function*(){let t=yield this.e2eeStateMutex.lock();try{if(this.encryptionType=e?Ie.GCM:Ie.NONE,yield Promise.all(this.pendingPublishPromises.values()),this.trackPublications.size===0||Array.from(this.trackPublications.values()).every(n=>n.isEncrypted===e))return;yield this.republishAllTracks(void 0,!1)}finally{t()}})}setTrackEnabled(e,t,n,r){return A(this,void 0,void 0,function*(){var s,o;this.log.debug("setTrackEnabled",{source:e,enabled:t}),this.republishPromise&&(yield this.republishPromise);let a=this.getTrackPublication(e);if(t)if(a)yield a.unmute();else{let p;if(this.pendingPublishing.has(e)){let g=yield this.waitForPendingPublicationOfSource(e);return g||this.log.info("waiting for pending publication promise timed out",{source:e}),yield g?.unmute(),g}this.pendingPublishing.add(e);try{switch(e){case J.Source.Camera:p=yield this.createTracks({video:(s=n)!==null&&s!==void 0?s:!0});break;case J.Source.Microphone:p=yield this.createTracks({audio:(o=n)!==null&&o!==void 0?o:!0});break;case J.Source.ScreenShare:p=yield this.createScreenTracks(Object.assign({},n));break;default:throw new Yt(e)}}catch(g){throw p?.forEach(b=>{b.stop()}
75),g instanceof Error&&this.emit(ce.MediaDevicesError,g,lu(e)),this.pendingPublishing.delete(e),g}for(let g of p){let b=Object.assign(Object.assign({},this.roomOptions.publishDefaults),n);e===J.Source.Microphone&&pn(g)&&b.preConnectBuffer&&(this.log.info("starting preconnect buffer for microphone"),g.startPreConnectBuffer())}try{let g=[];for(let R of p)this.log.info("publishing track",_e(R)),g.push(this.publishTrack(R,r));let b=yield Promise.all(g);var d=pe(b,1);a=d[0]}catch(g){throw p?.forEach(b=>{b.stop()}),g}finally{this.pendingPublishing.delete(e)}}else if(!a?.track&&this.pendingPublishing.has(e)&&(a=yield this.waitForPendingPublicationOfSource(e),a||this.log.info("waiting for pending publication promise timed out",{source:e})),a&&a.track)if(e===J.Source.ScreenShare){let p=[this.unpublishTrack(a.track)],g=this.getTrackPublication(J.Source.ScreenShareAudio);g&&g.track&&p.push(this.unpublishTrack(g.track));var l=yield Promise.all(p),f=pe(l,1);a=f[0]}else yield a.mute();return a})}enableCameraAndMicrophone(){return A(this,void 0,void 0,function*(){if(!(this.pendingPublishing.has(J.Source.Camera)||this.pendingPublishing.has(J.Source.Microphone))){this.pendingPublishing.add(J.Source.Camera),this.pendingPublishing.add(J.Source.Microphone);try{let e=yield this.createTracks({audio:!0,video:!0});yield Promise.all(e.map(t=>this.publishTrack(t)))}finally{this.pendingPublishing.delete(J.Source.Camera),this.pendingPublishing.delete(J.Source.Microphone)}}})}createTracks(e){return A(this,void 0,void 0,function*(){var t,n;e??(e={});let r=Ky(e,(t=this.roomOptions)===null||t===void 0?void 0:t.audioCaptureDefaults,(n=this.roomOptions)===null||n===void 0?void 0:n.videoCaptureDefaults);try{return(yield La(r,{loggerName:this.roomOptions.loggerName,loggerContextCb:()=>this.logContext})).map(a=>(pn(a)&&(this.microphoneError=void 0,a.setAudioContext(this.audioContext),a.source=J.Source.Microphone,this.emit(ce.AudioStreamAcquired)),Fn(a)&&(this.cameraError=void 0,a.source=J.Source.Camera),a))}catch(s){throw s instanceof Error&&(e.audio&&(this.microphoneError=s),e.video&&(this.cameraError=s)),s}})}createScreenTracks(e){return A(this,void 0,void 0,function*(){if(e===void 0&&(e={}),navigator.mediaDevices.getDisplayMedia===void 0)throw new ks("getDisplayMedia not supported");e.resolution===void 0&&!UC()&&(e.resolution=Dd.h1080fps30.resolution);let t=wC(e),n=yield navigator.mediaDevices.getDisplayMedia(t),r=n.getVideoTracks();if(r.length===0)throw new Yt("no video track found");let s=new Mr(r[0],void 0,!1,{loggerName:this.roomOptions.loggerName,loggerContextCb:()=>this.logContext});s.source=J.Source.ScreenShare,e.contentHint&&(s.mediaStreamTrack.contentHint=e.contentHint);let o=[s];if(n.getAudioTracks().length>0){this.emit(ce.AudioStreamAcquired);let a=new Ar(n.getAudioTracks()[0],void 0,!1,this.audioContext,{loggerName:this.roomOptions.loggerName,loggerContextCb:()=>this.logContext});a.source=J.Source.ScreenShareAudio,o.push(a)}return o})}publishTrack(e,t){return A(this,void 0,void 0,function*(){return this.publishOrRepublishTrack(e,t)})}waitForNextEngineRestart(){let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:15e3;return new Promise((t,n)=>{let r=()=>{clearTimeout(a),this.engine.off(X.Restarted,s),this.engine.off(X.Closing,o)},s=()=>{r(),t()},o=()=>{r(),n(new Error("engine closed before restart completed"))},a=setTimeout(()=>{r(),n(new Error("timed out waiting for engine restart"))},e);this.engine.once(X.Restarted,s),this.engine.once(X.Closing,o)})}publishOrRepublishTrack(e,t){return A(this,arguments,void 0,function(n,r){var s=this;let o=arguments.length>2&&arguments[2]!==void 0?arguments[2]:!1,a=arguments.length>3&&arguments[3]!==void 0?arguments[3]:!1;return(function*(){var d,l,f,p;Rn(n)&&n.setAudioContext(s.audioContext),yield(d=s.reconnectFuture)===null||d===void 0?void 0:d.promise,s.republishPromise&&!o&&(yield s.republishPromise),Tr(n)&&s.pendingPublishPromises.has(n)&&(yield s.pendingPublishPromises.get(n));let g;if(n instanceof MediaStreamTrack)g=n.getConstraints();else{g=n.constraints;let L;switch(n.source){case J.Source.Microphone:L="audioinput";break;case J.Source.Camera:L="videoinput"}L&&s.activeDeviceMap.has(L)&&(g=Object.assign(Object.assign({},g),{deviceId:s.activeDeviceMap.get(L)}))}if(n instanceof MediaStreamTrack)switch(n.kind){case"audio":n=new Ar(n,g,!0,s.audioContext,{loggerName:s.roomOptions.loggerName,loggerContextCb:()=>s.logContext});break;case"video":n=new Mr(n,g,!0,{loggerName:s.roomOptions.loggerName,loggerContextCb:()=>s.logContext});break;default:throw new Yt("unsupported MediaStreamTrack kind ".concat(n.kind))}else n.updateLoggerOptions({loggerName:s.roomOptions.loggerName,loggerContextCb:()=>s.logContext});let b;if(s.trackPublications.forEach(L=>{L.track&&L.track===n&&(b=L)}),b)return s.log.warn("track has already been published, skipping",_e(b)),b;let R=Object.assign(Object.assign({},s.roomOptions.publishDefaults),r),w="channelCount"in n.mediaStreamTrack.getSettings()&&n.mediaStreamTrack.getSettings().channelCount===2||n.mediaStreamTrack.getConstraints().channelCount===2,I=(l=R.forceStereo)!==null&&l!==void 0?l:w;I&&(R.dtx===void 0&&s.log.debug("Opus DTX will be disabled for stereo tracks by default. Enable them explicitly to make it work.",_e(n)),R.red===void 0&&s.log.debug("Opus RED will be disabled for stereo tracks by default. Enable them explicitly to make it work."),(f=R.dtx)!==null&&f!==void 0||(R.dtx=!1),(p=R.red)!==null&&p!==void 0||(R.red=!1)),!BC()&&s.roomOptions.e2ee&&(s.log.info("End-to-end encryption is set up, simulcast publishing will be disabled on Safari versions and iOS browsers running iOS < v17.2"),R.simulcast=!1),R.source&&(n.source=R.source);let N=new Promise((L,j)=>A(s,void 0,void 0,function*(){try{if(this.engine.client.currentState!==Fe.CONNECTED){this.log.debug("deferring track publication until signal is connected",{track:_e(n)});let M=!1,P=setTimeout(()=>{M=!0,n.stop(),j(new Wo("publishing rejected as engine not connected within timeout",408))},15e3);if(yield this.waitUntilEngineConnected(),clearTimeout(P),M)return;let B=yield this.publish(n,R,I);L(B)}else try{let M=yield this.publish(n,R,I);L(M)}catch(M){j(M)}}catch(M){j(M)}}));s.pendingPublishPromises.set(n,N);try{return yield N}catch(L){if(!a&&L instanceof hn)return s.log.warn("negotiation due to track publish failed, retrying after reconnect",{error:L}
75),s.pendingPublishPromises.delete(n),yield s.waitForNextEngineRestart(),yield s.publishOrRepublishTrack(n,r,o,!0);throw L}finally{s.pendingPublishPromises.delete(n)}})()})}waitUntilEngineConnected(){return this.signalConnectedFuture||(this.signalConnectedFuture=new nt),this.signalConnectedFuture.promise}hasPermissionsToPublish(e){if(!this.permissions)return this.log.warn("no permissions present for publishing track",_e(e)),!1;let t=this.permissions,n=t.canPublish,r=t.canPublishSources;return n&&(r.length===0||r.map(s=>MC(s)).includes(e.source))?!0:(this.log.warn("insufficient permissions to publish",_e(e)),!1)}publish(e,t,n){return A(this,void 0,void 0,function*(){var r,s,o,a,d,l,f,p,g,b;if(!this.hasPermissionsToPublish(e))throw new Wo("failed to publish track, insufficient permissions",403);Array.from(this.trackPublications.values()).find(te=>Tr(e)&&te.source===e.source)&&e.source!==J.Source.Unknown&&this.log.info("publishing a second track with the same source: ".concat(e.source),_e(e)),t.stopMicTrackOnMute&&pn(e)&&(e.stopOnMute=!0),e.source===J.Source.ScreenShare&&Oi()&&(t.simulcast=!1),t.videoCodec==="av1"&&!DC()&&(t.videoCodec=void 0),t.videoCodec==="vp9"&&!LC()&&(t.videoCodec=void 0),t.videoCodec===void 0&&(t.videoCodec=wu),this.enabledPublishVideoCodecs.length>0&&(this.enabledPublishVideoCodecs.some(te=>t.videoCodec===ls(te.mime))||(t.videoCodec=ls(this.enabledPublishVideoCodecs[0].mime)));let w=t.videoCodec;e.on(re.Muted,this.onTrackMuted),e.on(re.Unmuted,this.onTrackUnmuted),e.on(re.Ended,this.handleTrackEnded),e.on(re.UpstreamPaused,this.onTrackUpstreamPaused),e.on(re.UpstreamResumed,this.onTrackUpstreamResumed),e.on(re.AudioTrackFeatureUpdate,this.onTrackFeatureUpdate);let I=[],N=!(!((r=t.dtx)!==null&&r!==void 0)||r),L=e.getSourceTrackSettings();L.autoGainControl&&I.push(ot.TF_AUTO_GAIN_CONTROL),L.echoCancellation&&I.push(ot.TF_ECHO_CANCELLATION),L.noiseSuppression&&I.push(ot.TF_NOISE_SUPPRESSION),L.channelCount&&L.channelCount>1&&I.push(ot.TF_STEREO),N&&I.push(ot.TF_NO_DTX),Rn(e)&&e.hasPreConnectBuffer&&I.push(ot.TF_PRECONNECT_BUFFER);let j=this.normalizeRequestedFrameMetadataOptions(e,t),M=new bs({cid:e.mediaStreamTrack.id,name:t.name,type:J.kindToProto(e.kind),muted:e.isMuted,source:J.sourceToProto(e.source),disableDtx:N,encryption:this.encryptionType,stereo:n,disableRed:this.isE2EEEnabled||!(!((s=t.red)!==null&&s!==void 0)||s),stream:t?.stream,backupCodecPolicy:t?.backupCodecPolicy,audioFeatures:I,packetTrailerFeatures:j}),P;if(e.kind===J.Kind.Video){let te;try{te=yield e.waitForDimensions()}catch{let ge=(a=(o=this.roomOptions.videoCaptureDefaults)===null||o===void 0?void 0:o.resolution)!==null&&a!==void 0?a:Ss.h720.resolution;te={width:ge.width,height:ge.height},this.log.error("could not determine track dimensions, using defaults",Object.assign(Object.assign({},_e(e)),{dims:te}))}M.width=te.width,M.height=te.height,an(e)&&(un(w)&&(e.source===J.Source.ScreenShare&&(t.scalabilityMode="L1T3","contentHint"in e.mediaStreamTrack&&(e.mediaStreamTrack.contentHint="motion",this.log.debug("forcing contentHint to motion for screenshare with SVC codecs",_e(e)))),t.scalabilityMode=(d=t.scalabilityMode)!==null&&d!==void 0?d:"L3T3_KEY"),M.simulcastCodecs=[new Jl({codec:w,cid:e.mediaStreamTrack.id})],t.backupCodec===!0&&(t.backupCodec={codec:wu}),t.backupCodec&&w!==t.backupCodec.codec&&M.encryption===Ie.NONE&&(this.roomOptions.dynacast||(this.roomOptions.dynacast=!0),M.simulcastCodecs.push(new Jl({codec:t.backupCodec.codec,cid:""})))),P=ia(e.source===J.Source.ScreenShare,M.width,M.height,t),M.layers=Zg(M.width,M.height,P,un(t.videoCodec))}else e.kind===J.Kind.Audio&&(P=[{maxBitrate:(l=t.audioPreset)===null||l===void 0?void 0:l.maxBitrate,priority:(p=(f=t.audioPreset)===null||f===void 0?void 0:f.priority)!==null&&p!==void 0?p:"high",networkPriority:(b=(g=t.audioPreset)===null||g===void 0?void 0:g.priority)!==null&&b!==void 0?b:"high"}]);if(!this.engine||this.engine.isClosed)throw new Be("cannot publish track when not connected");let B=()=>A(this,void 0,void 0,function*(){var te,ae,ge,ke;if(!this.engine.pcManager)throw new Be("pcManager is not ready");if(e.sender=yield this.engine.createSender(e,t,P),an(e)&&(e.publishOptions=t),this.emit
75(ce.LocalSenderCreated,e.sender,e),an(e)&&((te=t.degradationPreference)!==null&&te!==void 0||(t.degradationPreference=tE(e)),e.setDegradationPreference(t.degradationPreference)),P){if(Oi()&&e.kind===J.Kind.Audio){let Oe;for(let Je of this.engine.pcManager.publisher.getTransceivers())if(Je.sender===e.sender){Oe=Je;break}Oe&&this.engine.pcManager.publisher.setTrackCodecBitrate({transceiver:Oe,codec:"opus",maxbr:!((ae=P[0])===null||ae===void 0)&&ae.maxBitrate?P[0].maxBitrate/1e3:0})}else if(e.codec&&nb(e.codec)){let Oe=un(e.codec)?(ke=(ge=P[0])===null||ge===void 0?void 0:ge.maxBitrate)!==null&&ke!==void 0?ke:0:P.reduce((Je,mt)=>{var Ee;return Je+((Ee=mt.maxBitrate)!==null&&Ee!==void 0?Ee:0)},0);Oe>0&&this.engine.pcManager.publisher.setTrackCodecBitrate({cid:M.cid,codec:e.codec,maxbr:Oe/1e3,isScreenShare:e.source===J.Source.ScreenShare})}}yield this.engine.negotiate()}),q,K=new Promise((te,ae)=>A(this,void 0,void 0,function*(){var ge;try{q=yield this.engine.addTrack(M),te(q)}catch(ke){if(e.sender&&(!((ge=this.engine.pcManager)===null||ge===void 0)&&ge.publisher)){try{this.engine.pcManager.publisher.removeTrack(e.sender)}catch(Oe){this.log.error(Oe)}yield this.engine.negotiate().catch(Oe=>{this.log.error("failed to negotiate after removing track due to failed add track request",Object.assign(Object.assign({},_e(e)),{error:Oe}))})}ae(ke)}}));if(this.enabledPublishVideoCodecs.length>0&&j.length===0)q=(yield Promise.all([K,B()]))[0];else{q=yield K;let te;if(q.codecs.forEach(ae=>{te===void 0&&(te=ae.mimeType)}),te&&e.kind===J.Kind.Video){let ae=ls(te);ae!==w&&(this.log.debug("falling back to server selected codec",Object.assign(Object.assign({},_e(e)),{codec:ae})),t.videoCodec=ae,P=ia(e.source===J.Source.ScreenShare,M.width,M.height,t))}yield B()}let ie=new Rs(e.kind,q,e,{loggerName:this.roomOptions.loggerName,loggerContextCb:()=>this.logContext});if(ie.on(re.CpuConstrained,te=>this.onTrackCpuConstrained(te,ie)),ie.options=t,e.sid=q.sid,an(e)&&(e.publishOptions=t,M.width&&M.height&&(e.lastEncodedDimensions={width:M.width,height:M.height})),this.log.debug("publishing ".concat(e.kind," with encodings"),{encodings:P,trackInfo:q}),an(e)?e.startMonitor(this.engine.client):Rn(e)&&e.startMonitor(),this.addTrackPublication(ie),this.emit(ce.LocalTrackPublished,ie),Rn(e)&&q.audioFeatures.includes(ot.TF_PRECONNECT_BUFFER)){let te=e.getPreConnectBuffer(),ae=e.getPreConnectBufferMimeType();this.on(ce.LocalTrackSubscribed,ge=>{if(ge.trackSid===q.sid){if(!e.hasPreConnectBuffer){this.log.warn("subscribe event came to late, buffer already closed");return}this.log.debug("finished recording preconnect buffer",_e(e)),e.stopPreConnectBuffer()}}),te&&new Promise((ke,Oe)=>A(this,void 0,void 0,function*(){var Je,mt,Ee,je,gt,Pe;try{this.log.debug("waiting for agent",_e(e));let vn=setTimeout(()=>{Oe(new Error("agent not active within 10 seconds"))},1e4),be=yield this.waitUntilActiveAgentPresent();clearTimeout(vn),this.log.debug("sending preconnect buffer",_e(e));let Br=yield this.streamBytes({name:"preconnect-buffer",mimeType:ae,topic:"lk.agent.pre-connect-audio-buffer",destinationIdentities:[be.identity],attributes:{trackId:ie.trackSid,sampleRate:String((gt=L.sampleRate)!==null&>!==void 0?gt:"48000"),channels:String((Pe=L.channelCount)!==null&&Pe!==void 0?Pe:"1")}});try{for(var Un=!0,oi=Ft(te),jn;jn=yield oi.next(),Je=jn.done,!Je;Un=!0){je=jn.value,Un=!1;let Gi=je;yield Br.write(Gi)}}catch(Gi){mt={error:Gi}}finally{try{!Un&&!Je&&(Ee=oi.return)&&(yield Ee.call(oi))}finally{if(mt)throw mt.error}}yield Br.close(),ke()}catch(vn){Oe(vn)}})).then(()=>{this.log.debug("preconnect buffer sent successfully",_e(e))}).catch(ke=>{this.log.error("error sending preconnect buffer",Object.assign(Object.assign({},_e(e)),{error:ke}))})}return ie})}canPublishFrameMetadata(){var e;return!!(this.roomOptions.e2ee||this.roomOptions.encryption||ws((e=this.roomOptions.frameMetadata)!==null&&e!==void 0?e:this.roomOptions.packetTrailer))}normalizeRequestedFrameMetadataOptions(e,t){var n;let r=(n=t.frameMetadata)!==null&&n!==void 0?n:t.packetTrailer;if(e.kind!==J.Kind.Video||!Ho(r))return t.frameMetadata=void 0,t.packetTrailer=void 0,[];if(!this.canPublishFrameMetadata())return this.log.warn("frame metadata transform not supported; not advertising features",Object.assign(Object.assign({},this.logContext),_e(e))),t.frameMetadata=void 0,t.packetTrailer=void 0,[];let s=lw(r),o=uw(s);return t.frameMetadata=o,t.packetTrailer=o,s}get isLocal(){return!0}publishAdditionalCodecForTrack(e,t,n){return A(this,void 0,void 0,function*(){var r;if(this.encryptionType!==Ie.NONE)return;let s;if(this.trackPublications.forEach(R=>{R.track&&R.track===e&&(s=R)}),!s)throw new Yt("track is not published");if(!an(e))throw new Yt("track is not a video track");let o=Object.assign(Object.assign({},(r=this.roomOptions)===null||r===void 0?void 0:r.publishDefaults),n),a=cb(e,t,o);if(!a){this.log.info("backup codec has been disabled, ignoring request to add additional codec for track",_e(e));return}let d=e.addSimulcastTrack(t,a);if(!d)return;let l=this.normalizeRequestedFrameMetadataOptions(e,o),f=new bs({cid:d.mediaStreamTrack.id,type:J.kindToProto(e.kind),muted:e.isMuted,source:J.sourceToProto(e.source),sid:e.sid,packetTrailerFeatures:l,simulcastCodecs:[{codec:o.videoCodec,cid:d.mediaStreamTrack.id}]});if(f.layers=Zg(f.width,f.height,a),!this.engine||this.engine.isClosed)throw new Be("cannot publish track when not connected");let p=()=>A(this,void 0,void 0,function*(){yield this.engine.createSimulcastSender(e,d,o,a),yield this.engine.negotiate()}),b=(yield Promise.all([this.engine.addTrack(f),p()]))[0];this.log.debug("published ".concat(t," for track ").concat(e.sid),{encodings:a,trackInfo:b})})}unpublishTrack(e,t){return A(this,void 0,void 0,function*(){var n,r;if(Tr(e)){let f=this.pendingPublishPromises.get(e);f&&(this.log.debug("awaiting publish promise before attempting to unpublish",_e(e)),yield f)}let s=this.getPublicationForTrack(e),o=s?_e(s):void 0;if(this.log.info("unpublishing track",o),!s||!s.track){this.log.warn("track was not unpublished because no publication was found",o);return}e=s.track,e.off(re.Muted,this.onTrackMuted),e.off(re.Unmuted,this.onTrackUnmuted),e.off(re.Ended,this.handleTrackEnded),e.off(re.UpstreamPaused,this.onTrackUpstreamPaused),e.off(re.UpstreamResumed,this.onTrackUpstreamResumed),e.off(re.AudioTrackFeatureUpdate,this.onTrackFeatureUpdate),t===void 0&&(t=(r=(n=this.roomOptions)===null||n===void 0?void 0:n.stopLocalTrackOnUnpublish)!==null&&r!==void 0?r:!0),t?e.stop():e.stopMonitor();let a=!1,d=e.sender;if(e.sender=void 0,this.engine.pcManager&&this.engine.pcManager.currentState<Ve.FAILED&&d)try{for(let f of this.engine.pcManager.publisher.getTransceivers())f.sender===d&&(f.direction="inactive",a=!0);try{a=this.engine.removeTrack(d)}catch(f){this.log.warn(f),a=!0}if(an(e)){for(let f of e.simulcastCodecs){var l=pe(f,2);let p=l[1];if(p.sender){try{a=this.engine.removeTrack(p.sender)}catch(g){this.log.warn(g),a=!0}p.sender=void 0}}e.simulcastCodecs.clear()}}catch(f){this.log.warn("failed to unpublish track",Object.assign(Object.assign({},o),{error:f}))}switch(this.trackPublications.delete(s.trackSid),s.kind){case J.Kind.Audio:this.audioTrackPublications.delete(s.trackSid);break;case J.Kind.Video:this.videoTrackPublications.delete(s.trackSid);break}
75return this.emit(ce.LocalTrackUnpublished,s),s.setTrack(void 0),a&&(yield this.engine.negotiate()),s})}unpublishTracks(e){return A(this,void 0,void 0,function*(){return(yield Promise.all(e.map(n=>this.unpublishTrack(n)))).filter(n=>!!n)})}republishAllTracks(e){return A(this,arguments,void 0,function(t){var n=this;let r=arguments.length>1&&arguments[1]!==void 0?arguments[1]:!0;return(function*(){n.republishPromise&&(yield n.republishPromise),n.republishPromise=new lt((s,o)=>A(n,void 0,void 0,function*(){try{let a=[];this.trackPublications.forEach(d=>{d.track&&(t&&(d.options=Object.assign(Object.assign({},d.options),t)),a.push(d))}),yield Promise.all(a.map(d=>A(this,void 0,void 0,function*(){let l=d.track;yield this.unpublishTrack(l,!1),r&&!l.isMuted&&l.source!==J.Source.ScreenShare&&l.source!==J.Source.ScreenShareAudio&&(Rn(l)||an(l))&&!l.isUserProvided&&(this.log.debug("restarting existing track",{track:d.trackSid}),yield l.restartTrack()),yield this.publishOrRepublishTrack(l,d.options,!0)}))),s()}catch(a){a instanceof Error?o(a):o(new Error(String(a)))}finally{this.republishPromise=void 0}})),yield n.republishPromise})()})}publishData(e){return A(this,arguments,void 0,function(t){var n=this;let r=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{};return(function*(){let s=r.reliable?Te.RELIABLE:Te.LOSSY,o=r.reliable?Xn.RELIABLE:Xn.LOSSY,a=r.destinationIdentities,d=r.topic,l=new bd({participantIdentity:n.identity,payload:t,destinationIdentities:a,topic:d}),f=new yt({kind:o,value:{case:"user",value:l}});yield n.engine.sendDataPacket(f,s)})()})}publishDtmf(e,t){return A(this,void 0,void 0,function*(){let n=new yt({kind:Xn.RELIABLE,value:{case:"sipDtmf",value:new Vv({code:e,digit:t})}});yield this.engine.sendDataPacket(n,Te.RELIABLE)})}sendChatMessage(e,t){return A(this,void 0,void 0,function*(){let n={id:crypto.randomUUID(),message:e,timestamp:Date.now(),attachedFiles:t?.attachments},r=new yt({value:{case:"chatMessage",value:new $o(Object.assign(Object.assign({},n),{timestamp:Ge.parse(n.timestamp)}))}});return yield this.engine.sendDataPacket(r,Te.RELIABLE),this.emit(ce.ChatMessage,n),n})}editChatMessage(e,t){return A(this,void 0,void 0,function*(){let n=Object.assign(Object.assign({},t),{message:e,editTimestamp:Date.now()}),r=new yt({value:{case:"chatMessage",value:new $o(Object.assign(Object.assign({},n),{timestamp:Ge.parse(n.timestamp),editTimestamp:Ge.parse(n.editTimestamp)}))}});return yield this.engine.sendDataPacket(r,Te.RELIABLE),this.emit(ce.ChatMessage,n),n})}sendText(e,t){return A(this,void 0,void 0,function*(){return this.roomOutgoingDataStreamManager.sendText(e,t)})}streamText(e){return A(this,void 0,void 0,function*(){return this.roomOutgoingDataStreamManager.streamText(e)})}sendFile(e,t){return A(this,void 0,void 0,function*(){return this.roomOutgoingDataStreamManager.sendFile(e,t)})}sendBytes(e,t){return A(this,void 0,void 0,function*(){return this.roomOutgoingDataStreamManager.sendBytes(e,t)})}streamBytes(e){return A(this,void 0,void 0,function*(){return this.roomOutgoingDataStreamManager.streamBytes(e)})}performRpc(e){return this.rpcClientManager.performRpc(e).then(t=>{let n=pe(t,2);return n[0],n[1]})}
75registerRpcMethod(e,t){this.rpcServerManager.registerRpcMethod(e,t)}unregisterRpcMethod(e){this.rpcServerManager.unregisterRpcMethod(e)}setTrackSubscriptionPermissions(e){let t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:[];this.participantTrackPermissions=t,this.allParticipantsAllowedToSubscribe=e,this.engine.client.isDisconnected||this.updateTrackSubscriptionPermissions()}setEnabledPublishCodecs(e){this.enabledPublishVideoCodecs=e.filter(t=>t.mime.split("/")[0].toLowerCase()==="video")}updateInfo(e){return super.updateInfo(e)?(e.tracks.forEach(t=>{var n,r;let s=this.trackPublications.get(t.sid);if(s){let o=s.isMuted||((r=(n=s.track)===null||n===void 0?void 0:n.isUpstreamPaused)!==null&&r!==void 0?r:!1);o!==t.muted&&(this.log.debug("updating server mute state after reconcile",Object.assign(Object.assign({},_e(s)),{mutedOnServer:o})),this.engine.client.sendMuteTrack(t.sid,o))}}),!0):!1}setActiveAgent(e){var t,n,r,s;this.firstActiveAgent=e,e&&!this.firstActiveAgent&&(this.firstActiveAgent=e),e?(n=(t=this.activeAgentFuture)===null||t===void 0?void 0:t.resolve)===null||n===void 0||n.call(t,e):(s=(r=this.activeAgentFuture)===null||r===void 0?void 0:r.reject)===null||s===void 0||s.call(r,new Error("Agent disconnected")),this.activeAgentFuture=void 0}waitUntilActiveAgentPresent(){return this.firstActiveAgent?Promise.resolve(this.firstActiveAgent):(this.activeAgentFuture||(this.activeAgentFuture=new nt),this.activeAgentFuture.promise)}getPublicationForTrack(e){let t;return this.trackPublications.forEach(n=>{let r=n.track;r&&(e instanceof MediaStreamTrack?(Rn(r)||an(r))&&r.mediaStreamTrack===e&&(t=n):e===r&&(t=n))}),t}waitForPendingPublicationOfSource(e){return A(this,void 0,void 0,function*(){let n=Date.now();for(;Date.now()<n+1e4;){let r=Array.from(this.pendingPublishPromises.entries()).find(s=>pe(s,1)[0].source===e);if(r)return r[1];yield ft(20)}})}publishDataTrack(e){return A(this,void 0,void 0,function*(){let t=new ya(e,this.roomOutgoingDataTrackManager);return yield t.publish(),t})}},Sa=class extends DOMException{constructor(e,t){super(e,"AbortError"),this.reason=t}},Gu=class extends Map{constructor(){super(...arguments),this.pending=new Map}set(e,t){var n,r;super.set(e,t);let s=(n=this.pending)===null||n===void 0?void 0:n.get(e);if(s){for(let o of s)o.isResolved||(r=o.resolve)===null||r===void 0||r.call(o,t);this.pending.delete(e)}return this}get[Symbol.toStringTag](){return"DeferrableMap"}getDeferred(e,t){return A(this,void 0,void 0,function*(){let n=this.get(e);if(typeof n<"u")return n;if(t?.aborted)throw new Sa("The operation was aborted.",t.reason);let r=new nt(void 0,()=>{let o=this.pending.get(e);if(!o)return;let a=o.indexOf(r);a!==-1&&o.splice(a,1),o.length===0&&this.pending.delete(e)}),s=this.pending.get(e);if(s?s.push(r):this.pending.set(e,[r]),t){let o=()=>{var a;r.isResolved||(a=r.reject)===null||a===void 0||a.call(r,new Sa("The operation was aborted.",t.reason))};t.addEventListener("abort",o,{once:!0}),r.promise.finally(()=>{t.removeEventListener("abort",o)})}return r.promise})}},Ju=class extends Ht{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=s=>{this.setTrack(void 0),this.emit(re.Ended,s)},this.handleVisibilityChange=s=>{this.log.debug("adaptivestream video visibility ".concat(this.trackSid,", visible=").concat(s),this.logContext),this.visible=s,this.emitTrackUpdate()},this.handleVideoDimensionsChange=s=>{this.log.debug("adaptivestream video dimensions ".concat(s.width,"x").concat(s.height),this.logContext),this.videoDimensionsAdaptiveStream=s,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 Ra({trackSids:[this.trackSid],subscribe:this.subscribed,participantTracks:[new Wv({participantSid:"",trackSids:[this.trackSid]})]});this.emit(re.UpdateSubscription,r),this.emitSubscriptionUpdateIfChanged(t),this.emitPermissionUpdateIfChanged(n)}get subscriptionStatus(){return this.subscribed===!1?Ht.SubscriptionStatus.Unsubscribed:super.isSubscribed?Ht.SubscriptionStatus.Subscribed:Ht.SubscriptionStatus.Desired}get permissionStatus(){return this.allowed?Ht.PermissionStatus.Allowed:Ht.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.requestedDisabled:this.isAdaptiveStream?this.visible:!0}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){var t,n;this.isManualOperationAllowed()&&(((t=this.requestedVideoDimensions)===null||t===void 0?void 0:t.width)===e.width&&((n=this.requestedVideoDimensions)===null||n===void 0?void 0:n.height)===e.height||(_l(this.track)&&(this.requestedVideoDimensions=e),this.requestedMaxQuality=void 0,this.emitTrackUpdate()))}setVideoFPS(e){this.isManualOperationAllowed()&&_l(this.track)&&this.fps!==e&&(this.fps=e,this.emitTrackUpdate())}get videoQuality(){var e;return(e=this.requestedMaxQuality)!==null&&e!==void 0?e:At.HIGH}setTrack(e){let t=this.subscriptionStatus,n=this.permissionStatus,r=this.track;r!==e&&(r&&(r.off(re.VideoDimensionsChanged,this.handleVideoDimensionsChange),r.off(re.VisibilityChanged,this.handleVisibilityChange),r.off(re.Ended,this.handleEnded),r.detach(),r.stopMonitor(),this.emit
vendor: 4,113 bytes, line 75
75(re.Unsubscribed,r)),super.setTrack(e),e&&(e.sid=this.trackSid,e.on(re.VideoDimensionsChanged,this.handleVideoDimensionsChange),e.on(re.VisibilityChanged,this.handleVisibilityChange),e.on(re.Ended,this.handleEnded),this.emit(re.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(re.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?re.Muted:re.Unmuted)}emitSubscriptionUpdateIfChanged(e){let t=this.subscriptionStatus;e!==t&&this.emit(re.SubscriptionStatusChanged,t,e)}emitPermissionUpdateIfChanged(e){this.permissionStatus!==e&&this.emit(re.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 _l(this.track)&&this.track.isAdaptiveStream}emitTrackUpdate(){let e=new ty({trackSids:[this.trackSid],disabled:!this.isEnabled,fps:this.fps});if(this.kind===J.Kind.Video){let t=this.requestedVideoDimensions;if(this.videoDimensionsAdaptiveStream!==void 0)if(t)Pg(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 n=RC(this.trackInfo,this.requestedMaxQuality);n&&Pg(this.videoDimensionsAdaptiveStream,n)&&(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 requested max quality",Object.assign(Object.assign({},this.logContext),{quality:this.requestedMaxQuality})),e.quality=this.requestedMaxQuality):(this.log.debug("using default quality",Object.assign(Object.assign({},this.logContext),{quality:At.HIGH})),e.quality=At.HIGH)}this.emit(re.UpdateSettings,e)}},Ta=class i extends ka{static fromParticipantInfo(e,t,n,r){return new i(e,t.sid,t.identity,t.name,t.metadata,t.attributes,n,t.kind,t.dataTracks.map(s=>{let o=Yo.from(s);return new ha(o,r,{publisherIdentity:t.identity})}),t.clientProtocol,t.capabilities)}get logContext(){return Object.assign(Object.assign({},super.logContext),{remoteParticipantID:this.sid,remoteParticipant:this.identity})}constructor(e,t,n,r,s,o,a){let d=arguments.length>7&&arguments[7]!==void 0?arguments[7]:vs.STANDARD,l=arguments.length>8&&arguments[8]!==void 0?arguments[8]:[],f=arguments.length>9&&arguments[9]!==void 0?arguments[9]:Gy,p=arguments.length>10&&arguments[10]!==void 0?arguments[10]:[];super(t,n||"",r,s,o,a,d),this.signalClient=e,this.trackPublications=new Map,this.audioTrackPublications=new Map,this.videoTrackPublications=new Map,this.dataTracks=new Gu(l.map(g=>[g.info.name,g])),this.volumeMap=new Map,this.clientProtocol=f,this.capabilities=p}addTrackPublication(e){super.addTrackPublication(e),e.on(re.UpdateSettings,t=>{this.log.debug("send update settings",Object.assign(Object.assign(Object.assign({},this.logContext),_e(e)),{settings:t})),this.signalClient.sendUpdateTrackSettings(t)}),e.on(re.UpdateSubscription,t=>{t.participantTracks.forEach(n=>{n.participantSid=this.sid}),this.signalClient.sendUpdateSubscription(t)}),e.on(re.SubscriptionPermissionChanged,t=>{this.emit(ce.TrackSubscriptionPermissionChanged,e,t)}),e.on(re.SubscriptionStatusChanged,t=>{this.emit(ce.TrackSubscriptionStatusChanged,e,t)}),e.on(re.Subscribed,t=>
75{this.emit(ce.TrackSubscribed,t,e)}),e.on(re.Unsubscribed,t=>{this.emit(ce.TrackUnsubscribed,t,e)}),e.on(re.SubscriptionFailed,t=>{this.emit(ce.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]:J.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]:J.Source.Microphone,t=this.getTrackPublication(e);return t&&t.track?t.track.getVolume():this.volumeMap.get(e)}addSubscribedMediaTrack(e,t,n,r,s,o){let a=this.getTrackPublicationBySid(t);if(a||t.startsWith("TR")||this.trackPublications.forEach(f=>{!a&&e.kind===f.kind.toString()&&(a=f)}),!a){if(o===0){this.log.error("could not find published track",Object.assign(Object.assign({},this.logContext),{trackSid:t})),this.emit(ce.TrackSubscriptionFailed,t);return}o===void 0&&(o=20),setTimeout(()=>{this.addSubscribedMediaTrack(e,t,n,r,s,o-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),_e(a))),this.emit(ce.TrackSubscriptionFailed,t);return}let d=e.kind==="video",l;return d?l=new Es(e,t,r,s):l=new $u(e,t,r,this.audioContext,this.audioOutput),l.source=a.source,l.isMuted=a.isMuted,l.setMediaStream(n),l.start(),a.setTrack(l),this.volumeMap.has(a.source)&&fu(l)&&pn(l)&&l.setVolume(this.volumeMap.get(a.source)),a}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(r=>{var s,o;let a=this.getTrackPublicationBySid(r.sid);if(a)a.updateInfo(r);else{let d=J.kindFromProto(r.type);if(!d)return;a=new Ju(d,r,(s=this.signalClient.connectOptions)===null||s===void 0?void 0:s.autoSubscribe,{loggerContextCb:()=>this.logContext,loggerName:(o=this.loggerOptions)===null||o===void 0?void 0:o.loggerName}),a.updateInfo(r),n.set(r.sid,a);let l=Array.from(this.trackPublications.values()).find(f=>f.source===a?.source);l&&a.source!==J.Source.Unknown&&this.log.debug("received a second track publication for ".concat(this.identity," with the same source: ").concat(a.source),Object.assign(Object.assign({},this.logContext),{oldTrack:_e(l),newTrack:_e(a)})),this.addTrackPublication(a)}t.set(r.sid,a)}),this.trackPublications.forEach(r=>{t.has(r.trackSid)||(this.log.trace("detected removed track on remote participant, unpublishing",Object.assign(Object.assign({},this.logContext),_e(r))),this.unpublishTrack(r.trackSid,!0))}),n.forEach(r=>{this.emit(ce.TrackPublished,r)}),!0}unpublishTrack(e,t){let n=this.trackPublications.get(e);if(!n)return;let r=n.track;switch(r&&(r.stop(),n.setTrack(void 0)),this.trackPublications.delete(e),n.kind){case J.Kind.Audio:this.audioTrackPublications.delete(e);break;case J.Kind.Video:this.videoTrackPublications.delete(e);break}t&&this.emit(ce.TrackUnpublished,n)}setAudioOutput(e){return A(this,void 0,void 0,function*(){this.audioOutput=e;let t=[];this.audioTrackPublications.forEach(n=>{var r;pn(n.track)&&fu(n.track)&&t.push(n.track.setSinkId((r=e.deviceId)!==null&&r!==void 0?r:"default"))}),yield Promise.all(t)})}addRemoteDataTrack(e){this.dataTracks.set(e.info.name,e)}removeRemoteDataTrack(e){for(let n of this.dataTracks.entries()){var t=pe(n,2);let r=t[0],s=t[1];e===s.info.sid&&this.dataTracks.delete(r)}}emit(e){for(var t=arguments.length,n=new Array(t>1?t-1:0),r=1;r<t;r++)n[r-1]=arguments[r];return this.log.trace("participant event",Object.assign(Object.assign({},this.logContext),{event:e,args:n})),super.emit(e,...n)}},Re;(function(i){i.Disconnected="disconnected",i.Connecting="connecting",i.Connected="connected",i.Reconnecting="reconnecting",i.SignalReconnecting="signalReconnecting"})(Re||(Re={}));var AE=4*1e3,Or=class i extends _t.EventEmitter{get hasE2EESetup(){return this.e2eeManager!==void 0}constructor(e){var t,n,r,s,o,a,d;if(super(),t=this,this.state=Re.Disconnected,this.activeSpeakers=[],this.isE2EEEnabled=!1,this.audioEnabled=!0,this.e2eeStateMutex=new tt,this.isVideoPlaybackBlocked=!1,this.log=ye,this.bufferedEvents=[],this.isResuming=!1,this.pendingTrackAddedCallbacks=new Map,this.connect=(l,f,p)=>A(this,void 0,void 0,function*(){var g;if(!NC())throw en()?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 b=yield this.disconnectLock.lock();if(this.state===Re.Connected)return this.log.info("already connected to room ".concat(this.name)),b(),Promise.resolve();if(this.connectFuture)return b(),this.connectFuture.promise;this.setAndEmitConnectionState(Re.Connecting),((g=this.regionUrlProvider)===null||g===void 0?void 0:g.getServerUrl().toString())!==ib(l)&&(this.regionUrl=void 0,this.regionUrlProvider=void 0),Pr(new URL(l))&&(this.regionUrlProvider===void 0?this.regionUrlProvider=new tn(l,f):this.regionUrlProvider.updateToken(f),this.regionUrlProvider.fetchRegionSettings().then(I=>{var N;(N=this.regionUrlProvider)===null||N===void 0||N.setServerReportedRegions(I)}).catch(I=>{this.log.warn("could not fetch region settings",{error:I})}));let R=(I,N,L)=>A(this,void 0,void 0,function*(){var j,M;this.abortController&&this.abortController.abort();let P=new AbortController;this.abortController=P,b?.();try{if(yield _r.getInstance().getBackOffPromise(l),P.signal.aborted)throw ve.cancelled("Connection attempt aborted");yield this.attemptConnection(L??l,f,p,P),this.abortController=void 0,I()}
75catch(B){if(this.regionUrlProvider&&B instanceof ve&&B.reason!==Ue.Cancelled&&B.reason!==Ue.NotAllowed){let q=null;try{this.log.debug("Fetching next region"),q=yield this.regionUrlProvider.getNextBestRegionUrl((j=this.abortController)===null||j===void 0?void 0:j.signal)}catch(K){if(K instanceof ve&&(K.status===401||K.reason===Ue.Cancelled)){this.handleDisconnect(this.options.stopLocalTrackOnUnpublish),N(K);return}}[Ue.InternalError,Ue.ServerUnreachable,Ue.Timeout].includes(B.reason)&&(this.log.debug("Adding failed connection attempt to back off"),_r.getInstance().addFailedConnectionAttempt(l)),q&&!(!((M=this.abortController)===null||M===void 0)&&M.signal.aborted)?(this.log.info("Initial connection failed with ConnectionError: ".concat(B.message,". Retrying with another region: ").concat(q)),this.recreateEngine(!0),yield R(I,N,q)):(this.handleDisconnect(this.options.stopLocalTrackOnUnpublish,Og(B)),N(B))}else{let q=Qt.UNKNOWN_REASON;B instanceof ve&&(q=Og(B)),this.handleDisconnect(this.options.stopLocalTrackOnUnpublish,q),N(B)}}}),w=this.regionUrl;return this.regionUrl=void 0,this.connectFuture=new nt((I,N)=>{R(I,N,w)},()=>{this.clearConnectionFutures()}),this.connectFuture.promise}),this.connectSignal=(l,f,p,g,b,R)=>A(this,void 0,void 0,function*(){let w=yield p.join(l,f,{autoSubscribe:g.autoSubscribe,adaptiveStream:typeof b.adaptiveStream=="object"?!0:b.adaptiveStream,clientInfoCapabilities:this.getClientInfoCapabilities(b),maxRetries:g.maxRetries,e2eeEnabled:!!this.e2eeManager,websocketTimeout:g.websocketTimeout},R.signal,!b.singlePeerConnection),I=w.joinResponse,N=w.serverInfo;if(this.serverInfo=N,!N.version)throw new ru("unknown server version");return N.version==="0.15.1"&&this.options.dynacast&&(this.log.debug("disabling dynacast due to server version"),b.dynacast=!1),I}),this.applyJoinResponse=l=>{let f=l.participant;if(this.localParticipant.sid=f.sid,this.localParticipant.identity=f.identity,this.localParticipant.setEnabledPublishCodecs(l.enabledPublishCodecs),this.e2eeManager)try{this.e2eeManager.setSifTrailer(l.sifTrailer)}catch(p){this.log.error(p instanceof Error?p.message:"Could not set SifTrailer",{error:p})}this.handleParticipantUpdates([f,...l.otherParticipants]),l.room&&this.handleRoomUpdate(l.room)},this.attemptConnection=(l,f,p,g)=>A(this,void 0,void 0,function*(){var b,R;this.state===Re.Reconnecting||this.isResuming||!((b=this.engine)===null||b===void 0)&&b.pendingReconnect?(this.log.info("Reconnection attempt replaced by new connection attempt"),this.recreateEngine(!0)):this.maybeCreateEngine(),!((R=this.regionUrlProvider)===null||R===void 0)&&R.isCloud()&&this.engine.setRegionStrategy(this.createRegionStrategy()),this.acquireAudioContext(),this.connOptions=Object.assign(Object.assign({},Vd),p),this.connOptions.rtcConfig&&(this.engine.rtcConfig=this.connOptions.rtcConfig),this.connOptions.peerConnectionTimeout&&(this.engine.peerConnectionTimeout=this.connOptions.peerConnectionTimeout);try{let w=yield this.connectSignal(l,f,this.engine,this.connOptions,this.options,g);this.applyJoinResponse(w),this.setupLocalParticipantEvents(),this.emit(H.SignalConnected)}catch(w){yield this.engine.close(),this.recreateEngine();let I=g.signal.aborted?ve.cancelled("Signal connection aborted"):ve.serverUnreachable("could not establish signal connection");throw w instanceof Error&&(I.message="".concat(I.message,": ").concat(w.message)),w instanceof ve&&(I.reason=w.reason,I.status=w.status),this.log.debug("error trying to establish signal connection",{error:w}),I}if(g.signal.aborted)throw yield this.engine.close(),this.recreateEngine(),ve.cancelled("Connection attempt aborted");try{yield this.engine.waitForPCInitialConnection(this.connOptions.peerConnectionTimeout,g)}catch(w){throw yield this.engine.close(),this.recreateEngine(),w}St()&&this.options.disconnectOnPageLeave&&(window.addEventListener("pagehide",this.onPageLeave),window.addEventListener("beforeunload",this.onPageLeave)),St()&&window.addEventListener("freeze",this.onPageLeave),this.setAndEmitConnectionState(Re.Connected),this.emit(H.Connected),_r.getInstance().resetFailedConnectionAttempts(l),this.registerConnectionReconcile(),this.regionUrlProvider&&this.regionUrlProvider.notifyConnected()}),this.disconnect=function(){for(var l=arguments.length,f=new Array(l),p=0;p<l;p++)f[p]=arguments[p];return A(t,[...f],void 0,function(){var g=this;let b=arguments.length>0&&arguments[0]!==void 0?arguments[0]:!0;return(function*(){var R,w,I;let N=yield g.disconnectLock.lock();try{if(g.state===Re.Disconnected){g.log.debug("already disconnected");return}if(g.log.info("disconnect from room"),g.state===Re.Connecting||g.state===Re.Reconnecting||g.isResuming){let L="Abort connection attempt due to user initiated disconnect";g.log.warn(L),(R=g.abortController)===null||R===void 0||R.abort(L),(I=(w=g.connectFuture)===null||w===void 0?void 0:w.reject)===null||I===void 0||I.call(w,ve.cancelled("Client initiated disconnect")),g.connectFuture=void 0}g.engine&&(g.engine.client.isDisconnected||(yield g.engine.client.sendLeave()),yield g.engine.close()),g.handleDisconnect(b,Qt.CLIENT_INITIATED),g.engine=void 0}finally{N()}})()})},this.onPageLeave=()=>A(this,void 0,void 0,function*(){this.log.info("Page leave detected, disconnecting"),yield this.disconnect()}),this.startAudio=()=>A(this,void 0,void 0,function*(){let l=[],f=bt();if(f&&f.os==="iOS"){let p="livekit-dummy-audio-el",g=document.getElementById(p);if(!g){g=document.createElement("audio"),g.id=p,g.autoplay=!0,g.hidden=!0;let b=Tl();b.enabled=!0;let R=new MediaStream([b]);g.srcObject=R,document.addEventListener("visibilitychange",()=>
75{g&&(g.srcObject=document.hidden?null:R,document.hidden||(this.log.debug("page visible again, triggering startAudio to resume playback and update playback status"),this.startAudio()))}),document.body.append(g),this.once(H.Disconnected,()=>{g?.remove(),g=null})}l.push(g)}this.remoteParticipants.forEach(p=>{p.audioTrackPublications.forEach(g=>{g.track&&g.track.attachedElements.forEach(b=>{l.push(b)})})});try{yield Promise.all([this.acquireAudioContext(),...l.map(p=>(this.options.webAudioMix||(p.muted=!1),p.play()))]),this.handleAudioPlaybackStarted()}catch(p){throw this.handleAudioPlaybackFailed(p),p}}),this.startVideo=()=>A(this,void 0,void 0,function*(){let l=[];for(let f of this.remoteParticipants.values())f.videoTrackPublications.forEach(p=>{var g;(g=p.track)===null||g===void 0||g.attachedElements.forEach(b=>{l.includes(b)||l.push(b)})});yield Promise.all(l.map(f=>f.play())).then(()=>{this.handleVideoPlaybackStarted()}).catch(f=>{f.name==="NotAllowedError"?this.handleVideoPlaybackFailed():this.log.warn("Resuming video playback failed, make sure you call `startVideo` directly in a user gesture handler")})}),this.handleRestarting=()=>{this.clearConnectionReconcile(),this.isResuming=!1;for(let l of this.remoteParticipants.values())this.handleParticipantDisconnected(l.identity,l);this.setAndEmitConnectionState(Re.Reconnecting)&&this.emit(H.Reconnecting)},this.handleRestarted=()=>{this.outgoingDataTrackManager.sfuWillRepublishTracks(),this.incomingDataTrackManager.resendSubscriptionUpdates()},this.handleSignalRestarted=l=>A(this,void 0,void 0,function*(){this.log.debug("signal reconnected to server, region ".concat(l.serverRegion),{region:l.serverRegion}),this.bufferedEvents=[],this.applyJoinResponse(l);try{yield this.localParticipant.republishAllTracks(void 0,!0)}catch(f){this.log.error("error trying to re-publish tracks after reconnection",{error:f})}try{yield this.engine.waitForRestarted(),this.log.debug("fully reconnected to server",{region:l.serverRegion})}catch{return}this.setAndEmitConnectionState(Re.Connected),this.emit(H.Reconnected),this.registerConnectionReconcile(),this.emitBufferedEvents()}),this.handleParticipantUpdates=l=>{var f;for(let g of l){if(g.identity===this.localParticipant.identity){this.localParticipant.updateInfo(g);continue}g.identity===""&&(g.identity=(f=this.sidToIdentity.get(g.sid))!==null&&f!==void 0?f:"");let b=this.remoteParticipants.get(g.identity);g.state===gr.DISCONNECTED?this.handleParticipantDisconnected(g.identity,b):this.getOrCreateParticipant(g.identity,g)}let p=new Map(l.filter(g=>g.identity!==this.localParticipant.identity).map(g=>[g.identity,g.dataTracks.map(b=>Yo.from(b))]));this.incomingDataTrackManager.receiveSfuPublicationUpdates(p)},this.handleActiveSpeakersUpdate=l=>{let f=[],p={};l.forEach(g=>{if(p[g.sid]=!0,g.sid===this.localParticipant.sid)this.localParticipant.audioLevel=g.level,this.localParticipant.setIsSpeaking(!0),f.push(this.localParticipant);else{let b=this.getRemoteParticipantBySid(g.sid);b&&(b.audioLevel=g.level,b.setIsSpeaking(!0),f.push(b))}}),p[this.localParticipant.sid]||(this.localParticipant.audioLevel=0,this.localParticipant.setIsSpeaking(!1)),this.remoteParticipants.forEac
vendor: 4,129 bytes, line 75
75h(g=>{p[g.sid]||(g.audioLevel=0,g.setIsSpeaking(!1))}),this.activeSpeakers=f,this.emitWhenConnected(H.ActiveSpeakersChanged,f)},this.handleSpeakersChanged=l=>{let f=new Map;this.activeSpeakers.forEach(g=>{let b=this.remoteParticipants.get(g.identity);b&&b.sid!==g.sid||f.set(g.sid,g)}),l.forEach(g=>{let b=this.getRemoteParticipantBySid(g.sid);g.sid===this.localParticipant.sid&&(b=this.localParticipant),b&&(b.audioLevel=g.level,b.setIsSpeaking(g.active),g.active?f.set(g.sid,b):f.delete(g.sid))});let p=Array.from(f.values());p.sort((g,b)=>b.audioLevel-g.audioLevel),this.activeSpeakers=p,this.emitWhenConnected(H.ActiveSpeakersChanged,p)},this.handleStreamStateUpdate=l=>{l.streamStates.forEach(f=>{let p=this.getRemoteParticipantBySid(f.participantSid);if(!p)return;let g=p.getTrackPublicationBySid(f.trackSid);if(!g||!g.track)return;let b=J.streamStateFromProto(f.state),R=g.track.streamState;g.track.setStreamState(b),b!==R&&(p.emit(ce.TrackStreamStateChanged,g,g.track.streamState),this.emitWhenConnected(H.TrackStreamStateChanged,g,g.track.streamState,p))})},this.handleSubscriptionPermissionUpdate=l=>{let f=this.getRemoteParticipantBySid(l.participantSid);if(!f)return;let p=f.getTrackPublicationBySid(l.trackSid);p&&p.setAllowed(l.allowed)},this.handleSubscriptionError=l=>{this.cancelPendingTrackAdded(l.trackSid);let f=Array.from(this.remoteParticipants.values()).find(g=>g.trackPublications.has(l.trackSid));if(!f)return;let p=f.getTrackPublicationBySid(l.trackSid);p&&p.setSubscriptionError(l.err)},this.handleDataPacket=(l,f)=>{let p=this.remoteParticipants.get(l.participantIdentity);if(l.value.case==="user")this.handleUserPacket(p,l.value.value,l.kind,f);else if(l.value.case==="transcription")this.handleTranscription(p,l.value.value);else if(l.value.case==="sipDtmf")this.handleSipDtmf(p,l.value.value);else if(l.value.case==="chatMessage")this.handleChatMessage(p,l.value.value);else if(l.value.case==="metrics")this.handleMetrics(l.value.value,p);else if(l.value.case==="streamHeader"||l.value.case==="streamChunk"||l.value.case==="streamTrailer")this.handleDataStream(l,f);else if(l.value.case==="rpcRequest"){let g=l.value.value;this.rpcServerManager.handleIncomingRpcRequest(l.participantIdentity,g)}else if(l.value.case==="rpcResponse"){let g=l.value.value;switch(g.value.case){case"payload":this.rpcClientManager.handleIncomingRpcResponseSuccess(g.requestId,g.value.value);break;case"error":this.rpcClientManager.handleIncomingRpcResponseFailure(g.requestId,$e.fromProto(g.value.value));break;default:this.log.warn("Unknown rpcResponse.value.case: ".concat(g.value.case),this.logContext);break}}else l.value.case==="rpcAck"&&this.rpcClientManager.handleIncomingRpcAck(l.value.value.requestId)},this.handleUserPacket=(l,f,p,g)=>{this.emit(H.DataReceived,f.payload,l,p,f.topic,g),l?.emit(ce.DataReceived,f.payload,p,g)},this.handleSipDtmf=(l,f)=>{this.emit(H.SipDTMFReceived,f,l),l?.emit(ce.SipDTMFReceived,f)},this.handleTranscription=(l,f)=>{let p=f.transcribedParticipantIdentity===this.localParticipant.identity?this.localParticipant:this.getParticipantByIdentity(f.transcribedParticipantIdentity),g=p?.trackPublications.get(f.trackId),b=GC(f,this.transcriptionReceivedTimes);g?.emit(re.TranscriptionReceived,b),p?.emit(ce.TranscriptionReceived,b,g),this.emit(H.TranscriptionReceived,b,p,g)},this.handleChatMessage=(l,f)=>{let p=JC(f);this.emit(H.ChatMessage,p,l)},this.handleMetrics=(l,f)=>{this.emit(H.MetricsReceived,l,f)},this.handleDataStream=(l,f)=>{this.incomingDataStreamManager.handleDataStreamPacket(l,f)},this.bufferedSegments=new Map,this.handleAudioPlaybackStarted=()=>{this.canPlaybackAudio||(this.audioEnabled=!0,this.emit(H.AudioPlaybackStatusChanged,!0))},this.handleAudioPlaybackFailed=l=>{this.log.warn("could not playback audio",{error:l}),this.canPlaybackAudio&&(this.audioEnabled=!1,this.emit(H.AudioPlaybackStatusChanged,!1))},this.handleVideoPlaybackStarted=()=>{this.isVideoPlaybackBlocked&&(this.isVideoPlaybackBlocked=!1,this.emit(H.VideoPlaybackStatusChanged,!0))},this.handleVideoPlaybackFailed=()=>{this.isVideoPlaybackBlocked||(this.isVideoPlaybackBlocked=!0,this.emit
75(H.VideoPlaybackStatusChanged,!1))},this.handleDeviceChange=()=>A(this,void 0,void 0,function*(){var l;((l=bt())===null||l===void 0?void 0:l.os)!=="iOS"&&(yield this.selectDefaultDevices()),this.emit(H.MediaDevicesChanged)}),this.handleRoomUpdate=l=>{let f=this.roomInfo;this.roomInfo=l,f&&f.metadata!==l.metadata&&this.emitWhenConnected(H.RoomMetadataChanged,l.metadata),f?.activeRecording!==l.activeRecording&&this.emitWhenConnected(H.RecordingStatusChanged,l.activeRecording)},this.handleConnectionQualityUpdate=l=>{l.updates.forEach(f=>{if(f.participantSid===this.localParticipant.sid){this.localParticipant.setConnectionQuality(f.quality);return}let p=this.getRemoteParticipantBySid(f.participantSid);p&&p.setConnectionQuality(f.quality)})},this.getRemoteParticipantClientProtocol=l=>{var f,p;return(p=(f=this.remoteParticipants.get(l))===null||f===void 0?void 0:f.clientProtocol)!==null&&p!==void 0?p:Gy},this.getRemoteParticipantCapabilities=l=>{var f,p;return(p=(f=this.remoteParticipants.get(l))===null||f===void 0?void 0:f.capabilities)!==null&&p!==void 0?p:[]},this.getAllRemoteParticipantIdentities=()=>Array.from(this.remoteParticipants.keys()),this.onLocalParticipantMetadataChanged=l=>{this.emit(H.ParticipantMetadataChanged,l,this.localParticipant)},this.onLocalParticipantNameChanged=l=>{this.emit(H.ParticipantNameChanged,l,this.localParticipant)},this.onLocalAttributesChanged=l=>{this.emit(H.ParticipantAttributesChanged,l,this.localParticipant)},this.onLocalTrackMuted=l=>{this.emit(H.TrackMuted,l,this.localParticipant)},this.onLocalTrackUnmuted=l=>{this.emit(H.TrackUnmuted,l,this.localParticipant)},this.onTrackProcessorUpdate=l=>{var f;(f=l?.onPublish)===null||f===void 0||f.call(l,this)},this.onLocalTrackPublished=l=>A(this,void 0,void 0,function*(){var f,p,g,b,R,w;(f=l.track)===null||f===void 0||f.on(re.TrackProcessorUpdate,this.onTrackProcessorUpdate),(p=l.track)===null||p===void 0||p.on(re.Restarted,this.onLocalTrackRestarted),(R=(b=(g=l.track)===null||g===void 0?void 0:g.getProcessor())===null||b===void 0?void 0:b.onPublish)===null||R===void 0||R.call(b,this),this.emit(H.LocalTrackPublished,l,this.localParticipant),Rn(l.track)&&(yield l.track.checkForSilence())&&this.emit(H.LocalAudioSilenceDetected,l);let I=yield(w=l.track)===null||w===void 0?void 0:w.getDeviceId(!1),N=lu(l.source);N&&I&&I!==this.localParticipant.activeDeviceMap.get(N)&&(this.localParticipant.activeDeviceMap.set(N,I),this.emit(H.ActiveDeviceChanged,N,I))}),this.onLocalTrackUnpublished=l=>{var f,p;(f=l.track)===null||f===void 0||f.off(re.TrackProcessorUpdate,this.onTrackProcessorUpdate),(p=l.track)===null||p===void 0||p.off(re.Restarted,this.onLocalTrackRestarted),this.emit(H.LocalTrackUnpublished,l,this.localParticipant)},this.onLocalTrackRestarted=l=>A(this,void 0,void 0,function*(){let f=yield l.getDeviceId(!1),p=lu(l.source);p&&f&&f!==this.localParticipant.activeDeviceMap.get(p)&&(this.log.debug("local track restarted, setting ".concat(p," ").concat(f," active")),this.localParticipant.activeDeviceMap.set(p,f),this.emit(H.ActiveDeviceChanged,p,f))}),this.onLocalConnectionQualityChanged=l=>{this.emit(H.ConnectionQualityChanged,l,this.localParticipant)},this.onMediaDevicesError=(l,f)=>{this.emit(H.MediaDevicesError,l,f)},this.onLocalParticipantPermissionsChanged=l=>{this.emit(H.ParticipantPermissionsChanged,l,this.localParticipant)},this.onLocalChatMessageSent=l=>{this.emit(H.ChatMessage,l,this.localParticipant)},this.setMaxListeners(100),this.remoteParticipants=new Map,this.sidToIdentity=new Map,this.options=Object.assign(Object.assign({},xw),e),this.log=ut((n=this.options.loggerName)!==null&&n!==void 0?n:Xe.Room,()=>this.logContext),this.transcriptionReceivedTimes=new Map,this.options.audioCaptureDefaults=Object.assign(Object.assign({},ob),e?.audioCaptureDefaults),this.options.videoCaptureDefaults=Object.assign(Object.assign({},ab),e?.videoCaptureDefaults),this.options.publishDefaults=Object.assign(Object.assign({},Lw),e?.publishDefaults),this.maybeCreateEngine(),this.incomingDataStreamManager=new Du,this.outgoingDataStreamManager=new Nu(this.engine,this.log,this.getRemoteParticipantClientProtocol,this.getRemoteParticipantCapabilities,this.getAllRemoteParticipantIdentities),this.incomingDataTrackManager=new
75Uu({e2eeManager:this.e2eeManager}),this.incomingDataTrackManager.on("sfuUpdateSubscription",l=>{this.engine.client.sendUpdateDataSubscription(l.sid,l.subscribe)}).on("trackPublished",l=>{var f;l.track.publisherIdentity!==this.localParticipant.identity&&(this.emit(H.DataTrackPublished,l.track),(f=this.remoteParticipants.get(l.track.publisherIdentity))===null||f===void 0||f.addRemoteDataTrack(l.track))}).on("trackUnpublished",l=>{var f;l.publisherIdentity!==this.localParticipant.identity&&(this.emit(H.DataTrackUnpublished,l.sid),(f=this.remoteParticipants.get(l.publisherIdentity))===null||f===void 0||f.removeRemoteDataTrack(l.sid))}),this.outgoingDataTrackManager=new Bu({e2eeManager:this.e2eeManager}),this.outgoingDataTrackManager.on("sfuPublishRequest",l=>{this.engine.client.sendPublishDataTrackRequest(l.handle,l.name,l.usesE2ee)}).on("sfuUnpublishRequest",l=>{this.engine.client.sendUnPublishDataTrackRequest(l.handle)}).on("trackPublished",l=>{this.emit(H.LocalDataTrackPublished,l.track)}).on("trackUnpublished",l=>{this.emit(H.LocalDataTrackUnpublished,l.sid)}).on("packetAvailable",l=>{let f=l.handle,p=l.bytes;this.engine.sendDataTrackFrame(p).finally(()=>this.outgoingDataTrackManager.handlePacketSendComplete(f))}),this.registerRpcDataStreamHandler(),this.rpcClientManager=new qu(this.log,this.outgoingDataStreamManager,this.getRemoteParticipantClientProtocol,()=>{var l,f;return(f=(l=this.engine.latestJoinResponse)===null||l===void 0?void 0:l.serverInfo)===null||f===void 0?void 0:f.version}),this.rpcClientManager.on("sendDataPacket",l=>{let f=l.packet;var p;(p=this.engine)===null||p===void 0||p.sendDataPacket(f,Te.RELIABLE)}),this.rpcServerManager=new Vu(this.log,this.outgoingDataStreamManager,this.getRemoteParticipantClientProtocol),this.rpcServerManager.on("sendDataPacket",l=>{let f=l.packet;var p;(p=this.engine)===null||p===void 0||p.sendDataPacket(f,Te.RELIABLE)}),this.disconnectLock=new tt,this.localParticipant=new Wu("","",this.engine,this.options,this.outgoingDataStreamManager,this.outgoingDataTrackManager,this.rpcClientManager,this.rpcServerManager),this.setupFrameMetadata(),(this.options.e2ee||this.options.encryption)&&this.setupE2EE(),this.engine.e2eeManager=this.e2eeManager,this.incomingDataTrackManager.updateE2eeManager((r=this.e2eeManager)!==null&&r!==void 0?r:null),this.outgoingDataTrackManager.updateE2eeManager((s=this.e2eeManager)!==null&&s!==void 0?s:null),this.options.videoCaptureDefaults.deviceId&&this.localParticipant.activeDeviceMap.set("videoinput",Sr(this.options.videoCaptureDefaults.deviceId)),this.options.audioCaptureDefaults.deviceId&&this.localParticipant.activeDeviceMap.set("audioinput",Sr(this.options.audioCaptureDefaults.deviceId)),!((o=this.options.audioOutput)===null||o===void 0)&&o.deviceId&&this.switchActiveDevice("audiooutput",Sr(this.options.audioOutput.deviceId)).catch(l=>this.log.warn("Could not set audio output: ".concat(l.message))),St()){let l=new AbortController,f;if(i.cleanupRegistry){let p=new WeakRef(this);f=()=>{let g=p.deref();g&&g.handleDeviceChange()},i.cleanupRegistry.register(this,()=>{l.abort()})}else f=this.handleDeviceChange;(d=(a=navigator.mediaDevices)===null||a===void 0?void 0:a.addEventListener)===null||d===void 0||d.call(a,"devicechange",f,{signal:l.signal})}}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)}
75registerRpcMethod(e,t){this.rpcServerManager.registerRpcMethod(e,t)}unregisterRpcMethod(e){this.rpcServerManager.unregisterRpcMethod(e)}setE2EEEnabled(e){return A(this,void 0,void 0,function*(){let t=yield this.e2eeStateMutex.lock();try{if(this.e2eeManager)this.isE2EEEnabled!==e&&(yield 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")}finally{t()}})}setupE2EE(){var e,t;let n=!!this.options.encryption,r=this.options.encryption||this.options.e2ee;r&&("e2eeManager"in r?(this.e2eeManager=r.e2eeManager,this.e2eeManager.isDataChannelEncryptionEnabled=n):this.e2eeManager=new vu(r,n),this.e2eeManager.on(zn.ParticipantEncryptionStatusChanged,(s,o)=>{KC(o)&&(this.isE2EEEnabled=s),this.emit(H.ParticipantEncryptionStatusChanged,s,o)}),this.e2eeManager.on(zn.EncryptionError,(s,o)=>{let a=o?this.getParticipantByIdentity(o):void 0;this.emit(H.EncryptionError,s,a)}),(e=this.e2eeManager)===null||e===void 0||e.setup(this),(t=this.e2eeManager)===null||t===void 0||t.setupEngine(this.engine))}setupFrameMetadata(){var e;let t=(e=this.options.frameMetadata)!==null&&e!==void 0?e:this.options.packetTrailer;this.frameMetadataManager=new bu(t),this.frameMetadataManager.setup(this)}get logContext(){var e,t,n;return{room:this.name,roomID:(e=this.roomInfo)===null||e===void 0?void 0:e.sid,participant:(t=this.localParticipant)===null||t===void 0?void 0:t.identity,participantID:(n=this.localParticipant)===null||n===void 0?void 0:n.sid}}get isRecording(){var e,t;return(t=(e=this.roomInfo)===null||e===void 0?void 0:e.activeRecording)!==null&&t!==void 0?t:!1}getSid(){return this.state===Re.Disconnected?lt.resolve(""):this.roomInfo&&this.roomInfo.sid!==""?lt.resolve(this.roomInfo.sid):new lt((e,t)=>{let n=r=>{r.sid!==""&&(this.engine.off(X.RoomUpdate,n),e(r.sid))};this.engine.on(X.RoomUpdate,n),this.once(H.Disconnected,()=>{this.engine.off(X.RoomUpdate,n),t(new Be("Room disconnected before room server id was available"))})})}get name(){var e,t;return(t=(e=this.roomInfo)===null||e===void 0?void 0:e.name)!==null&&t!==void 0?t:""}get metadata(){var e;return(e=this.roomInfo)===null||e===void 0?void 0:e.metadata}get numParticipants(){var e,t;return(t=(e=this.roomInfo)===null||e===void 0?void 0:e.numParticipants)!==null&&t!==void 0?t:0}get numPublishers(){var e,t;return(t=(e=this.roomInfo)===null||e===void 0?void 0:e.numPublishers)!==null&&t!==void 0?t:0}maybeCreateEngine(){this.engine&&(this.engine.isNewlyCreated||!this.engine.isClosed)||(this.engine=new Iu(this.options),this.engine.e2eeManager=this.e2eeManager,this.engine.on(X.ParticipantUpdate,this.handleParticipantUpdates).on(X.RoomUpdate,this.handleRoomUpdate).on(X.SpeakersChanged,this.handleSpeakersChanged).on(X.StreamStateChanged,this.handleStreamStateUpdate).on(X.ConnectionQualityUpdate,this.handleConnectionQualityUpdate).on(X.SubscriptionError,this.handleSubscriptionError).on(X.SubscriptionPermissionUpdate,this.handleSubscriptionPermissionUpdate).on(X.MediaTrackAdded,(e,t,n)=>{this.onTrackAdded(e,t,n)}).on(X.Disconnected,e=>{this.handleDisconnect(this.options.stopLocalTrackOnUnpublish,e)}).on(X.ActiveSpeakersUpdate,this.handleActiveSpeakersUpdate).on(X.DataPacketReceived,this.handleDataPacket).on(X.Resuming,()=>{this.clearConnectionReconcile(),this.isResuming=!0,this.log.debug("Resuming signal connection"),this.setAndEmitConnectionState(Re.SignalReconnecting)&&this.emit(H.SignalReconnecting)}).on(X.Resumed,()=>{this.registerConnectionReconcile(),this.isResuming=!1,this.log.debug("Resumed signal connection"),this.updateSubscriptions(),this.setAndEmitConnectionState(Re.Connected)&&this.emit(H.Reconnected),this.emitBufferedEvents()}).on(X.SignalResumed,()=>{(this.state===Re.Reconnecting||this.isResuming)&&this.sendSyncState(),this.emitBufferedEvents()}).on(X.Restarting,this.handleRestarting).on(X.Restarted,this.handleRestarted).on(X.SignalRestarted,this.handleSignalRestarted).on(X.Offline,()=>
75{this.setAndEmitConnectionState(Re.Reconnecting)&&this.emit(H.Reconnecting)}).on(X.DCBufferStatusChanged,(e,t)=>{this.emit(H.DCBufferStatusChanged,e,t)}).on(X.LocalTrackSubscribed,e=>{this.handleLocalTrackSubscribed(e)}).on(X.RoomMoved,e=>{this.log.debug("room moved",e),e.room&&this.handleRoomUpdate(e.room),this.remoteParticipants.forEach((t,n)=>{this.handleParticipantDisconnected(n,t)}),this.emit(H.Moved,e.room.name),e.participant?this.handleParticipantUpdates([e.participant,...e.otherParticipants]):this.handleParticipantUpdates(e.otherParticipants)}).on(X.PublishDataTrackResponse,e=>{if(!e.info){this.log.warn("received PublishDataTrackResponse, but event.info was ".concat(e.info,", so skipping."));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!==Ie.NONE}})}).on(X.UnPublishDataTrackResponse,e=>{if(!e.info){this.log.warn("received UnPublishDataTrackResponse, but event.info was ".concat(e.info,", so skipping."));return}this.outgoingDataTrackManager.receivedSfuUnpublishResponse(e.info.pubHandle)}).on(X.DataTrackSubscriberHandles,e=>{let t=new Map(Object.entries(e.subHandles).map(n=>{let r=pe(n,2),s=r[0],o=r[1];return[parseInt(s,10),o.trackSid]}));this.incomingDataTrackManager.receivedSfuSubscriberHandles(t)}).on(X.DataTrackPacketReceived,e=>{try{this.incomingDataTrackManager.packetReceived(e)}catch(t){throw t}}).on(X.Joined,e=>{let t=new Map(e.otherParticipants.map(n=>[n.identity,n.dataTracks.map(r=>Yo.from(r))]));this.incomingDataTrackManager.receiveSfuPublicationUpdates(t)}).on(X.TokenRefreshed,e=>{var t;(t=this.regionUrlProvider)===null||t===void 0||t.updateToken(e)}).on(X.ServerRegionsReported,e=>{var t;(t=this.regionUrlProvider)===null||t===void 0||t.setServerReportedRegions({regionSettings:e,updatedAtInMs:Date.now(),maxAgeInMs:Ou})}),this.localParticipant&&this.localParticipant.setupEngine(this.engine),this.e2eeManager&&this.e2eeManager.setupEngine(this.engine),this.outgoingDataStreamManager&&this.outgoingDataStreamManager.setupEngine(this.engine))}createRegionStrategy(){return{getNextUrl:e=>A(this,void 0,void 0,function*(){return this.regionUrlProvider?this.regionUrlProvider.getNextBestRegionUrl(e):null}),resetAttempts:()=>{var e;return(e=this.regionUrlProvider)===null||e===void 0?void 0:e.resetAttempts()}}}static getLocalDevices(e){let t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:!0;return Mt.getInstance().getDevices(e,t)}prepareConnection(e,t){return A(this,void 0,void 0,function*(){if(this.state===Re.Disconnected){this.log.debug("prepareConnection to ".concat(e));try{if(Pr(new URL(e))&&t){this.regionUrlProvider=new tn(e,t);let n=yield this.regionUrlProvider.getNextBestRegionUrl();n&&this.state===Re.Disconnected&&(this.regionUrl=n,yield fetch(_s(n),{method:"HEAD"}),this.log.debug("prepared connection to ".concat(n)))}else yield fetch(_s(e),{method:"HEAD"})}catch(n){this.log.warn("could not prepare connection",{error:n})}}})}getParticipantByIdentity(e){return this.localParticipant.identity===e?this.localParticipant:this.remoteParticipants.get(e)}clearConnectionFutures(){this.connectFuture=void 0}simulateScenario(e,t){return A(this,void 0,void 0,function*(){let n=()=>A(this,void 0,void 0,function*(){}),r;switch(e){case"signal-reconnect":yield this.engine.client.handleOnClose("simulate disconnect");break;case"fail-on-v1-path":this.engine.failNextV1Path();break;case"speaker":r=new cn({scenario:{case:"speakerUpdate",value:3}});break;case"node-failure":r=new cn({scenario:{case:"nodeFailure",value:!0}});break;case"server-leave":r=new cn({scenario:{case:"serverLeave",value:!0}});break;case"migration":r=new cn({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=()=>A(this,void 0,void 0,function*(){yield this.engine.client.handleOnClose("simulate resume-disconnect")}),r=new cn({scenario:{case:"disconnectSignalOnResume",value:!0}});break;case"disconnect-signal-on-resume-no-messages":n=()=>A(this,void 0,void 0,function*(){yield this.engine.client.handleOnClose("simulate resume-disconnect")}),r=new cn({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 cn({scenario:{case:"switchCandidateProtocol",value:e==="force-tls"?2:1}}),n=()=>A(this,void 0,void 0,function*(){let s=this.engine.client.onLeave;s&&s(new Ia({reason:Qt.CLIENT_INITIATED,action:vr.RECONNECT}))});break;case"subscriber-bandwidth":if(t===void 0||typeof t!="number")throw new Error("subscriber-bandwidth requires a number as argument");r=new cn({scenario:{case:"subscriberBandwidth",value:Xt(t)}});break;case"leave-full-reconnect":r=new cn({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 A(this,arguments,void 0,function(n,r){var s=this;let o=arguments.length>2&&arguments[2]!==void 0?arguments[2]:!0;return(function*(){var a,d,l,f,p,g,b;let R=!0,w=!1,I=o?{exact:r}:r;if(n==="audioinput"){w=s.localParticipant.audioTrackPublications.size===0;let N=(a=s.getActiveDevice(n))!==null&&a!==void 0?a:s.options.audioCaptureDefaults.deviceId;s.options.audioCaptureDefaults.deviceId=I;let L=Array.from(s.localParticipant.audioTrackPublications.values()).filter(M=>M.source===J.Source.Microphone);try{R=(yield Promise.all(L.map(M=>{var P;return(P=M.audioTrack)===null||P===void 0?void 0:P.setDeviceId(I)}))).every(M=>M===!0)}catch(M){throw s.options.audioCaptureDefaults.deviceId=N,M}let j=L.some(M=>{var P,B;return(B=(P=M.track)===null||P===void 0?void 0:P.isMuted)!==null&&B!==void 0?B:!1});R&&j&&(w=!0)}else if(n==="videoinput"){w=s.localParticipant.videoTrackPublications.size===0;let N=(d=s.getActiveDevice(n))!==null&&d!==void 0?d:s.options.videoCaptureDefaults.deviceId;s.options.videoCaptureDefaults.deviceId=I;let L=Array.from(s.localParticipant.videoTrackPublications.values()).filter(M=>M.source===J.Source.Camera);try{R=(yield Promise.all(L.map(M=>{var P;return(P=M.videoTrack)===null||P===void 0?void 0:P.setDeviceId(I)}))).every(M=>M===!0)}catch(M){throw s.options.videoCaptureDefaults.deviceId=N,M}let j=L.some(M=>{var P,B;return(B=(P=M.track)===null||P===void 0?void 0:P.isMuted)!==null&&B!==void 0?B:!1});R&&j&&(w=!0)}else if(n==="audiooutput"){if(w=!0,!hu()&&!s.options.webAudioMix||s.options.webAudioMix&&s.audioContext&&!("setSinkId"in s.audioContext))throw new Error("cannot switch audio output, the current browser does not support it");s.options.webAudioMix&&(r=(l=yield Mt.getInstance().normalizeDeviceId("audiooutput",r))!==null&&l!==void 0?l:""),(f=(b=s.options).audioOutput)!==null&&f!==void 0||(b.audioOutput={});let N=(p=s.getActiveDevice(n))!==null&&p!==void 0?p:s.options.audioOutput.deviceId;s.options.audioOutput.deviceId=r;try{s.options.webAudioMix&&((g=s.audioContext)===null||g===void 0||g.setSinkId(r)),yield Promise.all(Array.from(s.remoteParticipants.values()).map(L=>L.setAudioOutput({deviceId:r})))}catch(L){throw s.options.audioOutput.deviceId=N,L}}return w&&(s.localParticipant.activeDeviceMap.set(n,r),s.emit(H.ActiveDeviceChanged,n,r)),R})()})}setupLocalParticipantEvents(){this.localParticipant.on(ce.ParticipantMetadataChanged,this.onLocalParticipantMetadataChanged).on(ce.ParticipantNameChanged,this.onLocalParticipantNameChanged).on(ce.AttributesChanged,this.onLocalAttributesChanged).on(ce.TrackMuted,this.onLocalTrackMuted).on(ce.TrackUnmuted,this.onLocalTrackUnmuted).on(ce.LocalTrackPublished,this.onLocalTrackPublished).on(ce.LocalTrackUnpublished,this.onLocalTrackUnpublished).on(ce.ConnectionQualityChanged,this.onLocalConnectionQualityChanged).on(ce.MediaDevicesError,this.onMediaDevicesError).on(ce.AudioStreamAcquired,this.startAudio).on(ce.ChatMessage,this.onLocalChatMessageSent).on(ce.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){var r,s;if([Re.Connecting,Re.Reconnecting].includes(this.state)){let b=Dg(e,t);this.log.debug("deferring on track for later",{mediaTrackId:e.id,mediaStreamId:t.id,tracksInStream:t.getTracks().map(I=>I.id)});let R=()=>{w(),this.onTrackAdded(e,t,n)},w=()=>
75{if(this.off(H.Reconnected,R),this.off(H.Connected,R),this.off(H.Disconnected,w),b){let I=this.pendingTrackAddedCallbacks.get(b);I?.delete(w),I?.size===0&&this.pendingTrackAddedCallbacks.delete(b)}};if(this.once(H.Reconnected,R),this.once(H.Connected,R),this.once(H.Disconnected,w),b){let I=(r=this.pendingTrackAddedCallbacks.get(b))!==null&&r!==void 0?r:new Set;I.add(w),this.pendingTrackAddedCallbacks.set(b,I)}return}if(this.state===Re.Disconnected){this.log.warn("skipping incoming track after Room disconnected");return}if(e.readyState==="ended"){this.log.debug("skipping incoming track as it already ended");return}let o=Xy(t.id),a=o[0],d=o[1],l=(s=Dg(e,t))!==null&&s!==void 0?s:e.id;if(a===this.localParticipant.sid){this.log.warn("tried to create RemoteParticipant for local participant");return}let f=Array.from(this.remoteParticipants.values()).find(b=>b.sid===a);if(!f){a.startsWith("PA")&&this.log.error("Tried to add a track for a participant, that's not present. Sid: ".concat(a));return}if(!l.startsWith("TR")){let b=this.engine.getTrackIdForReceiver(n);if(!b){this.log.error("Tried to add a track whose 'sid' could not be found for a participant, that's not present. Sid: ".concat(a));return}l=b}l.startsWith("TR")||this.log.warn("Tried to add a track whose 'sid' could not be determined for a participant, that's not present. Sid: ".concat(a,", streamId: ").concat(d,", trackId: ").concat(l),{remoteParticipantID:a,streamId:d,trackId:l});let p;this.options.adaptiveStream&&(typeof this.options.adaptiveStream=="object"?p=this.options.adaptiveStream:p={});let g=f.addSubscribedMediaTrack(e,l,t,n,p);g?.isEncrypted&&!this.e2eeManager&&this.emit(H.EncryptionError,new Error("Encrypted ".concat(g.source," track received from participant ").concat(f.sid,", but room does not have encryption enabled!")))}cancelPendingTrackAdded(e){var t;(t=this.pendingTrackAddedCallbacks.get(e))===null||t===void 0||t.forEach(n=>n())}handleLocalTrackSubscribed(e){let t=()=>this.localParticipant.getTrackPublications().find(d=>d.trackSid===e),n=t();if(n){this.emitLocalTrackSubscribed(n);return}this.log.debug("deferring LocalTrackSubscribed, publication not yet available",{subscribedSid:e});let r=1e4,s,o=d=>{d.trackSid===e&&(a(),this.emitLocalTrackSubscribed(d))},a=()=>{clearTimeout(s),this.localParticipant.off(ce.LocalTrackPublished,o),this.off(H.Disconnected,a)};this.localParticipant.on(ce.LocalTrackPublished,o),this.once(H.Disconnected,a),s=setTimeout(()=>{a();let d=t();d?this.emitLocalTrackSubscribed(d):this.log.warn("could not find local track publication for LocalTrackSubscribed event after timeout",{subscribedSid:e})},r)}emitLocalTrackSubscribed(e){this.localParticipant.emit(ce.LocalTrackSubscribed,e),this.emitWhenConnected(H.LocalTrackSubscribed,e,this.localParticipant)}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.incomingDataTrackManager.reset(),this.outgoingDataTrackManager.reset(),this.state!==Re.Disconnected){this.regionUrl=void 0,this.regionUrlProvider&&this.regionUrlProvider.notifyDisconnected();
75try{this.remoteParticipants.forEach(s=>{s.trackPublications.forEach(o=>{s.unpublishTrack(o.trackSid)})}),this.localParticipant.trackPublications.forEach(s=>{var o,a,d;s.track&&this.localParticipant.unpublishTrack(s.track,e),e?((o=s.track)===null||o===void 0||o.detach(),(a=s.track)===null||a===void 0||a.stop()):(d=s.track)===null||d===void 0||d.stopMonitor()}),this.localParticipant.off(ce.ParticipantMetadataChanged,this.onLocalParticipantMetadataChanged).off(ce.ParticipantNameChanged,this.onLocalParticipantNameChanged).off(ce.AttributesChanged,this.onLocalAttributesChanged).off(ce.TrackMuted,this.onLocalTrackMuted).off(ce.TrackUnmuted,this.onLocalTrackUnmuted).off(ce.LocalTrackPublished,this.onLocalTrackPublished).off(ce.LocalTrackUnpublished,this.onLocalTrackUnpublished).off(ce.ConnectionQualityChanged,this.onLocalConnectionQualityChanged).off(ce.MediaDevicesError,this.onMediaDevicesError).off(ce.AudioStreamAcquired,this.startAudio).off(ce.ChatMessage,this.onLocalChatMessageSent).off(ce.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),St()&&(window.removeEventListener("beforeunload",this.onPageLeave),window.removeEventListener("pagehide",this.onPageLeave),window.removeEventListener("freeze",this.onPageLeave),(r=(n=navigator.mediaDevices)===null||n===void 0?void 0:n.removeEventListener)===null||r===void 0||r.call(n,"devicechange",this.handleDeviceChange))}finally{this.setAndEmitConnectionState(Re.Disconnected),this.emit(H.Disconnected,t)}}}handleParticipantDisconnected(e,t){this.remoteParticipants.delete(e),t&&(this.incomingDataStreamManager.validateParticipantHasNoActiveDataStreams(e),this.incomingDataTrackManager.handleRemoteParticipantDisconnected(e),t.trackPublications.forEach(n=>{t.unpublishTrack(n.trackSid,!0)}),this.emit(H.ParticipantDisconnected,t),t.setDisconnected(),this.rpcClientManager.handleParticipantDisconnected(t.identity))}selectDefaultDevices(){return A(this,void 0,void 0,function*(){var e,t,n;let r=Mt.getInstance().previousDevices,s=yield Mt.getInstance().getDevices(void 0,!1),o=bt();if(o?.name==="Chrome"&&o.os!=="iOS")for(let d of s){let l=r.find(f=>f.deviceId===d.deviceId);l&&l.label!==""&&l.kind===d.kind&&l.label!==d.label&&this.getActiveDevice(d.kind)==="default"&&this.emit(H.ActiveDeviceChanged,d.kind,d.deviceId)}let a=["audiooutput","audioinput","videoinput"];for(let d of a){let l=CC(d),f=this.localParticipant.getTrackPublication(l);if(f&&(!((e=f.track)===null||e===void 0)&&e.isUserProvided))continue;let p=s.filter(b=>b.kind===d),g=this.getActiveDevice(d);if(g===((t=r.filter(b=>b.kind===d)[0])===null||t===void 0?void 0:t.deviceId)&&p.length>0&&((n=p[0])===null||n===void 0?void 0:n.deviceId)!==g){yield this.switchActiveDevice(d,p[0].deviceId);continue}d==="audioinput"&&!Ts()||d==="videoinput"||p.length>0&&!p.find(b=>b.deviceId===this.getActiveDevice(d))&&(d!=="audiooutput"||!Ts())&&(yield this.switchActiveDevice(d,p[0].deviceId))}})}acquireAudioContext(){return A(this,void 0,void 0,function*(){var e,t;if(typeof this.options.webAudioMix!="boolean"&&this.options.webAudioMix.audioContext?this.audioContext=this.options.webAudioMix.audioContext:(!this.audioContext||this.audioContext.state==="closed")&&(this.audioContext=(e=Yy())!==null&&e!==void 0?e:void 0),this.options.webAudioMix&&this.remoteParticipants.forEac
75h(r=>r.setAudioContext(this.audioContext)),this.localParticipant.setAudioContext(this.audioContext),this.audioContext&&this.audioContext.state==="suspended")try{yield Promise.race([this.audioContext.resume(),ft(200)])}catch(r){this.log.warn("Could not resume audio context",{error:r})}let n=((t=this.audioContext)===null||t===void 0?void 0:t.state)==="running";n!==this.canPlaybackAudio&&(this.audioEnabled=n,this.emit(H.AudioPlaybackStatusChanged,n))})}createParticipant(e,t){var n;let r;return t?r=Ta.fromParticipantInfo(this.engine.client,t,{loggerContextCb:()=>this.logContext,loggerName:this.options.loggerName},this.incomingDataTrackManager):r=new Ta(this.engine.client,"",e,void 0,void 0,void 0,{loggerContextCb:()=>this.logContext,loggerName:this.options.loggerName}),this.options.webAudioMix&&r.setAudioContext(this.audioContext),!((n=this.options.audioOutput)===null||n===void 0)&&n.deviceId&&r.setAudioOutput(this.options.audioOutput).catch(s=>this.log.warn("Could not set audio output: ".concat(s.message))),r}getOrCreateParticipant(e,t){if(this.remoteParticipants.has(e)){let r=this.remoteParticipants.get(e);return t&&r.updateInfo(t)&&this.sidToIdentity.set(t.sid,t.identity),r}let n=this.createParticipant(e,t);return this.remoteParticipants.set(e,n),this.sidToIdentity.set(t.sid,t.identity),this.emitWhenConnected(H.ParticipantConnected,n),n.on(ce.TrackPublished,r=>{this.emitWhenConnected(H.TrackPublished,r,n)}).on(ce.TrackSubscribed,(r,s)=>{r.kind===J.Kind.Audio?(r.on(re.AudioPlaybackStarted,this.handleAudioPlaybackStarted),r.on(re.AudioPlaybackFailed,this.handleAudioPlaybackFailed)):r.kind===J.Kind.Video&&(r.on(re.VideoPlaybackFailed,this.handleVideoPlaybackFailed),r.on(re.VideoPlaybackStarted,this.handleVideoPlaybackStarted)),this.emitWhenConnected(H.TrackSubscribed,r,s,n)}).on(ce.TrackUnpublished,r=>{this.cancelPendingTrackAdded(r.trackSid),this.emit(H.TrackUnpublished,r,n)}).on(ce.TrackUnsubscribed,(r,s)=>{this.emit(H.TrackUnsubscribed,r,s,n)}).on(ce.TrackMuted,r=>{this.emitWhenConnected(H.TrackMuted,r,n)}).on(ce.TrackUnmuted,r=>{this.emitWhenConnected(H.TrackUnmuted,r,n)}).on(ce.ParticipantMetadataChanged,r=>{this.emitWhenConnected(H.ParticipantMetadataChanged,r,n)}).on(ce.ParticipantNameChanged,r=>{this.emitWhenConnected(H.ParticipantNameChanged,r,n)}).on(ce.AttributesChanged,r=>{this.emitWhenConnected(H.ParticipantAttributesChanged,r,n)}).on(ce.ConnectionQualityChanged,r=>{this.emitWhenConnected(H.ConnectionQualityChanged,r,n)}).on(ce.ParticipantPermissionsChanged,r=>{this.emitWhenConnected(H.ParticipantPermissionsChanged,r,n)}).on(ce.TrackSubscriptionStatusChanged,(r,s)=>{this.emitWhenConnected(H.TrackSubscriptionStatusChanged,r,s,n)}).on(ce.TrackSubscriptionFailed,(r,s)=>{this.emit(H.TrackSubscriptionFailed,r,n,s)}).on(ce.TrackSubscriptionPermissionChanged,(r,s)=>{this.emitWhenConnected(H.TrackSubscriptionPermissionChanged,r,s,n)}).on(ce.Active,()=>{this.emitWhenConnected(H.ParticipantActive,n),n.kind===vs.AGENT&&this.localParticipant.setActiveAgent(n)}),t&&n.updateInfo(t),n}sendSyncState(){let e=Array.from(this.remoteParticipants.values()).reduce((r,s)=>(r.push(...s.getTrackPublications()),r),[]),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&&HC(t)&&t.emitTrackUpdate()}getRemoteParticipantBySid(e){let t=this.sidToIdentity.get(e);if(t)return this.remoteParticipants.get(t)}getClientInfoCapabilities(e){var t;let n=[];return(ws((t=e.frameMetadata)!==null&&t!==void 0?t:e.packetTrailer)||this.e2eeManager)&&n.push(ys.CAP_PACKET_TRAILER),Zn()&&n.push(ys.CAP_COMPRESSION_DEFLATE_RAW),n}registerRpcDataStreamHandler(){this.incomingDataStreamManager.registerTextStreamHandler(Sb,(e,t)=>A(this,[e,t],void 0,function(n,r){var s=this;let o=r.identity;return(function*(){var a;let d=(a=n.info.attributes)!==null&&a!==void 0?a:{};yield s.rpcServerManager.handleIncomingDataStream(n,o,d)})()})),this.incomingDataStreamManager.registerTextStreamHandler(Tb,(e,t)=>A(this,[e,t],void 0,function(n,r){var s=this;
75let o=r.identity;return(function*(){var a;let d=(a=n.info.attributes)!==null&&a!==void 0?a:{};yield s.rpcClientManager.handleIncomingDataStream(n,o,d)})()}))}registerConnectionReconcile(){this.clearConnectionReconcile();let e=0;this.connectionReconcileInterval=Le.setInterval(()=>{!this.engine||this.engine.isClosed||!this.engine.verifyTransport()?(e++,this.log.warn("detected connection state mismatch",{numFailures:e,engine:this.engine?{closed:this.engine.isClosed,transportsConnectedOrConnecting:this.engine.verifyTransport()}:void 0}),e>=3&&(this.clearConnectionReconcile(),this.engine&&!this.engine.isClosed?(this.log.warn("detected connection state mismatch, attempting full reconnect"),this.engine.reconnect()):(this.recreateEngine(),this.handleDisconnect(this.options.stopLocalTrackOnUnpublish,Qt.STATE_MISMATCH)))):e=0},AE)}clearConnectionReconcile(){this.connectionReconcileInterval&&Le.clearInterval(this.connectionReconcileInterval)}setAndEmitConnectionState(e){return e===this.state?!1:(this.log.info("connection state changed: ".concat(this.state," -> ").concat(e)),this.state=e,this.incomingDataStreamManager.setConnected(e===Re.Connected),this.emit(H.ConnectionStateChanged,this.state),!0)}emitBufferedEvents(){this.bufferedEvents.forEach(e=>{let t=pe(e,2),n=t[0],r=t[1];this.emit(n,...r)}),this.bufferedEvents=[]}emitWhenConnected(e){for(var t=arguments.length,n=new Array(t>1?t-1:0),r=1;r<t;r++)n[r-1]=arguments[r];if(this.state===Re.Reconnecting||this.isResuming||!this.engine||this.engine.pendingReconnect)this.bufferedEvents.push([e,n]);else if(this.state===Re.Connected)return this.emit(e,...n);return!1}simulateParticipants(e){return A(this,void 0,void 0,function*(){var t,n,r,s;let o=Object.assign({audio:!0,video:!0,useRealTracks:!1},e.publish),a=Object.assign({count:9,audio:!1,video:!0,aspectRatios:[1.66,1.7,1.3]},e.participants);if(this.handleDisconnect(),this.roomInfo=new Ca({sid:"RM_SIMULATED",name:"simulated-room",emptyTimeout:0,maxParticipants:0,creationTime:Ge.parse(new Date().getTime()),metadata:"",numParticipants:1,numPublishers:1,turnPassword:"",enabledCodecs:[],activeRecording:!1}),this.localParticipant.updateInfo(new Ii({identity:"simulated-local",name:"local-name"})),this.setupLocalParticipantEvents(),this.emit(H.SignalConnected),this.emit(H.Connected),this.setAndEmitConnectionState(Re.Connected),o.video){let d=new Rs(J.Kind.Video,new fr({source:et.CAMERA,sid:Math.floor(Math.random()*1e4).toString(),type:Kt.AUDIO,name:"video-dummy"}),new Mr(o.useRealTracks&&(!((t=window.navigator.mediaDevices)===null||t===void 0)&&t.getUserMedia)?(yield window.navigator.mediaDevices.getUserMedia({video:!0})).getVideoTracks()[0]:Ig(160*((n=a.aspectRatios[0])!==null&&n!==void 0?n:1),160,!0,!0),void 0,!1,{loggerName:this.options.loggerName,loggerContextCb:()=>this.logContext}),{loggerName:this.options.loggerName,loggerContextCb:()=>this.logContext});this.localParticipant.addTrackPublication(d),this.localParticipant.emit(ce.LocalTrackPublished,d)}if(o.audio){let d=new Rs(J.Kind.Audio,new fr({source:et.MICROPHONE,sid:Math.floor(Math.random()*1e4).toString(),type:Kt.AUDIO}),new Ar(o.useRealTracks&&(!((r=navigator.mediaDevices)===null||r===void 0)&&r.getUserMedia)?(yield navigator.mediaDevices.getUserMedia({audio:!0})).getAudioTracks()[0]:Tl(),void 0,!1,this.audioContext,{loggerName:this.options.loggerName,loggerContextCb:()=>this.logContext}),{loggerName:this.options.loggerName,loggerContextCb:()=>this.logContext});this.localParticipant.addTrackPublication(d),this.localParticipant.emit(ce.LocalTrackPublished,d)}for(let d=0;d<a.count-1;d+=1){let l=new Ii({sid:Math.floor(Math.random()*1e4).toString(),identity:"simulated-".concat(d),state:gr.ACTIVE,tracks:[],joinedAt:Ge.parse(Date.now())}),f=this.getOrCreateParticipant(l.identity,l);if(a.video){let p=Ig(160*((s=a.aspectRatios[d%a.aspectRatios.length])!==null&&s!==void 0?s:1),160,!1,!0),g=new fr({source:et.CAMERA,sid:Math.floor(Math.random()*1e4).toString(),type:Kt.AUDIO});f.addSubscribedMediaTrack(p,g.sid,new MediaStream([p]),new RTCRtpReceiver),l.tracks=[...l.tracks,g]}if(a.audio){let p=Tl(),g=new fr({source:et.MICROPHONE,sid:Math.floor(Math.random()*1e4).toString(),type:Kt.AUDIO});f.addSubscribedMediaTrack(p,g.sid,new MediaStream([p]),new RTCRtpReceiver),l.tracks=[...l.tracks,g]}f.updateInfo(l)}})}emit(e){for(var t=arguments.length,n=new Array(t>1?t-1:0),r=1;r<t;r++)n[r-1]=arguments[r];if(e!==H.ActiveSpeakersChanged&&e!==H.TranscriptionReceived){let s=Cb(n).filter(o=>o!==void 0);(e===H.TrackSubscribed||e===H.TrackUnsubscribed)&&this.log.trace("subscribe trace: ".concat(e),{event:e,args:s}),this.log.debug("room event ".concat(e),{event:e,args:s})}return super.emit(e,...n)}};Or.cleanupRegistry=typeof FinalizationRegistry<"u"&&typeof WeakRef<"u"&&new FinalizationRegistry(i=>{i()});function Cb(i){return i.map(e=>{if(e)return Array.isArray(e)?Cb(e):typeof e=="object"?"logContext"in e?e.logContext:void 0:e})}var Jt;(function(i){i[i.IDLE=0]="IDLE",i[i.RUNNING=1]="RUNNING",i[i.SKIPPED=2]="SKIPPED",i[i.SUCCESS=3]="SUCCESS",i[i.FAILED=4]="FAILED"})(Jt||(Jt={}));var mn=class extends _t.EventEmitter{constructor(e,t){let n=arguments.length>2&&arguments[2]!==void 0?arguments[2]:{};super(),this.status=Jt.IDLE,this.logs=[],this.options={},this.url=e,this.token=t,this.name=this.constructor.name,this.room=new Or(n.roomOptions),this.connectOptions=n.connectOptions,this.options=n}run(e){return A(this,void 0,void 0,function*(){if(this.status!==Jt.IDLE)throw Error("check is running already");this.setStatus(Jt.RUNNING);try{yield this.perform()}catch(t){t instanceof Error&&(this.options.errorsAsWarnings?this.appendWarning(t.message):this.appendError(t.message))}return yield this.disconnect(),yield new Promise(t=>setTimeout(t,500)),this.status!==Jt.SKIPPED&&this.setStatus(this.isSuccess()?Jt.SUCCESS:Jt.FAILED),e&&e(),this.getInfo()})}isSuccess(){return!this.logs.some(e=>e.level==="error")}connect(e){return A(this,void 0,void 0,function*(){return this.room.state===Re.Connected?this.room:(e||(e=this.url),yield this.room.connect(e,this.token,this.connectOptions),this.room)}
75)}disconnect(){return A(this,void 0,void 0,function*(){this.room&&this.room.state!==Re.Disconnected&&(yield this.room.disconnect(),yield new Promise(e=>setTimeout(e,500)))})}skip(){this.setStatus(Jt.SKIPPED)}switchProtocol(e){return A(this,void 0,void 0,function*(){let t=!1,n=!1;if(this.room.on(H.Reconnecting,()=>{t=!0}),this.room.once(H.Reconnected,()=>{n=!0}),this.room.simulateScenario("force-".concat(e)),yield new Promise(s=>setTimeout(s,1e3)),!t)return;let r=Date.now()+1e4;for(;Date.now()<r;){if(n)return;yield ft(100)}throw new Error("Could not reconnect using ".concat(e," protocol after 10 seconds"))})}appendMessage(e){this.logs.push({level:"info",message:e}),this.emit("update",this.getInfo())}appendWarning(e){this.logs.push({level:"warning",message:e}),this.emit("update",this.getInfo())}appendError(e){this.logs.push({level:"error",message:e}),this.emit("update",this.getInfo())}setStatus(e){this.status=e,this.emit("update",this.getInfo())}get engine(){var e;return(e=this.room)===null||e===void 0?void 0:e.engine}getInfo(){return{logs:this.logs,name:this.name,status:this.status,description:this.description}}},Hu=class extends mn{get description(){return"Cloud regions"}perform(){return A(this,void 0,void 0,function*(){let e=new tn(this.url,this.token);if(!e.isCloud()){this.skip();return}let t=[],n=new Set;for(let s=0;s<3;s++){let o=yield e.getNextBestRegionUrl();if(!o)break;if(n.has(o))continue;n.add(o);let a=yield this.checkCloudRegion(o);this.appendMessage("".concat(a.region," RTT: ").concat(a.rtt,"ms, duration: ").concat(a.duration,"ms")),t.push(a)}t.sort((s,o)=>(s.duration-o.duration)*.5+(s.rtt-o.rtt)*.5);let r=t[0];this.bestStats=r,this.appendMessage("best Cloud region: ".concat(r.region))})}getInfo(){let e=super.getInfo();return e.data=this.bestStats,e}checkCloudRegion(e){return A(this,void 0,void 0,function*(){var t,n;yield this.connect(e),this.options.protocol==="tcp"&&(yield this.switchProtocol("tcp"));let r=(t=this.room.serverInfo)===null||t===void 0?void 0:t.region;if(!r)throw new Error("Region not found");let s=yield this.room.localParticipant.streamText({topic:"test"}),o=1e3,d=1e6/o,l="A".repeat(o),f=Date.now();for(let R=0;R<d;R++)yield s.write(l);yield s.close();let p=Date.now(),g=yield(n=this.room.engine.pcManager)===null||n===void 0?void 0:n.publisher.getStats(),b={region:r,rtt:1e4,duration:p-f};return g?.forEach(R=>{R.type==="candidate-pair"&&R.nominated&&(b.rtt=R.currentRoundTripTime*1e3)}),yield this.disconnect(),b})}},Ul=1e4,Ku=class extends mn{get description(){return"Connection via UDP vs TCP"}perform(){return A(this,void 0,void 0,function*(){let e=yield this.checkConnectionProtocol("udp"),t=yield this.checkConnectionProtocol("tcp");this.bestStats=e,e.qualityLimitationDurations.bandwidth-t.qualityLimitationDurations.bandwidth>.5||(e.packetsLost-t.packetsLost)/e.packetsSent>.01?(this.appendMessage("best connection quality via tcp"),this.bestStats=t):this.appendMessage("best connection quality via udp");let n=this.bestStats;this.appendMessage("upstream bitrate: ".concat((n.bitrateTotal/n.count/1e3/1e3).toFixed(2)," mbps")),this.appendMessage("RTT: ".concat((n.rttTotal/n.count*1e3).toFixed(2)," ms")),this.appendMessage("jitter: ".concat((n.jitterTotal/n.count*1e3).toFixed(2)," ms")),n.packetsLost>0&&this.appendWarning("packets lost: ".concat((n.packetsLost/n.packetsSent*100).toFixed(2),"%")),n.qualityLimitationDurations.bandwidth>1&&this.appendWarning("bandwidth limited ".concat((n.qualityLimitationDurations.bandwidth/(Ul/1e3)*100).toFixed(2),"%")),n.qualityLimitationDurations.cpu>0&&this.appendWarning("cpu limited ".concat((n.qualityLimitationDurations.cpu/(Ul/1e3)*100).toFixed(2),"%"))})}getInfo(){let e=super.getInfo();return e.data=this.bestStats,e}checkConnectionProtocol(e){return A(this,void 0,void 0,function*(){yield this.connect(),e==="tcp"?yield this.switchProtocol("tcp"):yield this.switchProtocol("udp");let t=document.createElement("canvas");t.width=1280,t.height=720;let n=t.getContext("2d");if(!n)throw new Error("Could not get canvas context");let r=0,s=()=>{r=(r+1)%360,n.fillStyle="hsl(".concat(r,", 100%, 50%)"),n.fillRect(0,0,t.width,t.height),requestAnimationFrame(s)};s();let a=t.captureStream(30).getVideoTracks()[0],l=(yield this.room.localParticipant.publishTrack(a,{simulcast:!1,degradationPreference:"maintain-resolution",videoEncoding:{maxBitrate:2e6}})).track,f={protocol:e,packetsLost:0,packetsSent:0,qualityLimitationDurations:{},rttTotal:0,jitterTotal:0,bitrateTotal:0,count:0},p=setInterval(()=>A(this,void 0,void 0,function*(){let g=yield l.getRTCStatsReport();g?.forEach(b=>{b.type==="outbound-rtp"?(f.packetsSent=b.packetsSent,f.qualityLimitationDurations=b.qualityLimitationDurations,f.bitrateTotal+=b.targetBitrate,f.count++):b.type==="remote-inbound-rtp"&&(f.packetsLost=b.packetsLost,f.rttTotal+=b.roundTripTime,f.jitterTotal+=b.jitter)})}),1e3);return yield new Promise(g=>setTimeout(g,Ul)),clearInterval(p),a.stop(),t.remove(),yield this.disconnect(),f})}},zu=class extends mn{get description(){return"Can publish audio"}perform(){return A(this,void 0,void 0,function*(){var e;let t=yield this.connect(),n=yield Gd();if(yield zy(n,1e3))throw new Error("unable to detect audio from microphone");this.appendMessage("detected audio from microphone"),t.localParticipant.publishTrack(n),yield new Promise(a=>setTimeout(a,3e3));let s=yield(e=n.sender)===null||e===void 0?void 0:e.getStats();if(!s)throw new Error("Could not get RTCStats");let o=0;if(s.forEach(a=>
75{a.type==="outbound-rtp"&&(a.kind==="audio"||!a.kind&&a.mediaType==="audio")&&(o=a.packetsSent)}),o===0)throw new Error("Could not determine packets are sent");this.appendMessage("published ".concat(o," audio packets"))})}},Yu=class extends mn{get description(){return"Can publish video"}perform(){return A(this,void 0,void 0,function*(){var e;let t=yield this.connect(),n=yield wE();yield this.checkForVideo(n.mediaStreamTrack),t.localParticipant.publishTrack(n),yield new Promise(o=>setTimeout(o,5e3));let r=yield(e=n.sender)===null||e===void 0?void 0:e.getStats();if(!r)throw new Error("Could not get RTCStats");let s=0;if(r.forEach(o=>{o.type==="outbound-rtp"&&(o.kind==="video"||!o.kind&&o.mediaType==="video")&&(s+=o.packetsSent)}),s===0)throw new Error("Could not determine packets are sent");this.appendMessage("published ".concat(s," video packets"))})}checkForVideo(e){return A(this,void 0,void 0,function*(){let t=new MediaStream;t.addTrack(e.clone());let n=document.createElement("video");n.srcObject=t,n.muted=!0,n.autoplay=!0,n.playsInline=!0,n.setAttribute("playsinline","true"),document.body.appendChild(n),yield new Promise(r=>{n.onplay=()=>{setTimeout(()=>{var s,o,a,d;let l=document.createElement("canvas"),f=e.getSettings(),p=(o=(s=f.width)!==null&&s!==void 0?s:n.videoWidth)!==null&&o!==void 0?o:1280,g=(d=(a=f.height)!==null&&a!==void 0?a:n.videoHeight)!==null&&d!==void 0?d:720;l.width=p,l.height=g;let b=l.getContext("2d");b.drawImage(n,0,0);let w=b.getImageData(0,0,l.width,l.height).data,I=!0;for(let N=0;N<w.length;N+=4)if(w[N]!==0||w[N+1]!==0||w[N+2]!==0){I=!1;break}I?this.appendError("camera appears to be producing only black frames"):this.appendMessage("received video frames"),r()},1e3)},n.play()}),t.getTracks().forEach(r=>r.stop()),n.remove()})}},Qu=class extends mn{get description(){return"Resuming connection after interruption"}perform(){return A(this,void 0,void 0,function*(){var e;let t=yield this.connect(),n=!1,r=!1,s,o=new Promise(l=>{setTimeout(l,5e3),s=l}),a=()=>{n=!0};t.on(H.SignalReconnecting,a).on(H.Reconnecting,a).on(H.Reconnected,()=>{r=!0,s(!0)}),(e=t.engine.client.ws)===null||e===void 0||e.close();let d=t.engine.client.onClose;if(d&&d(""),yield o,n){if(!r||t.state!==Re.Connected)throw this.appendWarning("reconnection is only possible in Redis-based configurations"),new Error("Not able to reconnect")}else throw new Error("Did not attempt to reconnect")})}},Xu=class extends mn{get description(){return"Can connect via TURN"}perform(){return A(this,void 0,void 0,function*(){var e,t,n;Pr(new URL(this.url))&&(this.appendMessage("Using region specific url"),this.url=(e=yield new tn(this.url,this.token).getNextBestRegionUrl())!==null&&e!==void 0?e:this.url);let r=new As,s=yield r.join(this.url,this.token,{autoSubscribe:!0,maxRetries:0,e2eeEnabled:!1,websocketTimeout:15e3},void 0,!0),o=!1,a=!1,d=!1;for(let l of s.iceServers)for(let f of l.urls)f.startsWith("turn:")?(a=!0,d=!0):f.startsWith("turns:")&&(a=!0,d=!0,o=!0),f.startsWith("stun:")&&(d=!0);d?a&&!o&&this.appendWarning("TURN is configured server side, but TURN/TLS is unavailable."):this.appendWarning("No STUN servers configured on server side."),yield r.close(),!((n=(t=this.connectOptions)===null||t===void 0?void 0:t.rtcConfig)===null||n===void 0)&&n.iceServers||a?yield this.room.connect(this.url,this.token,{rtcConfig:{iceTransportPolicy:"relay"}}):(this.appendWarning("No TURN servers configured."),this.skip(),yield new Promise(l=>setTimeout(l,0)))})}},Zu=class extends mn{get description(){return"Establishing WebRTC connection"}perform(){return A(this,void 0,void 0,function*(){let e=!1,t=!1;this.room.on(H.SignalConnected,()=>{var n;let r=this.room.engine.client.onTrickle;this.room.engine.client.onTrickle=(s,o)=>{if(s.candidate){let a=new RTCIceCandidate(s),d="".concat(a.protocol," ").concat(a.address,":").concat(a.port," ").concat(a.type);a.address&&(ME(a.address)?d+=" (private)":a.protocol==="tcp"&&a.tcpType==="passive"?(e=!0,d+=" (passive)"):a.protocol==="udp"&&(t=!0)),this.appendMessage(d)}r&&r(s,o)},!((n=this.room.engine.pcManager)===null||n===void 0)&&n.subscriber&&(this.room.engine.pcManager.subscriber.onIceCandidateError=s=>{s instanceof RTCPeerConnectionIceErrorEvent&&this.appendWarning("error with ICE candidate: ".concat(s.errorCode," ").concat(s.errorText," ").concat(s.url))})});try{yield this.connect(),ye.info("now the room is connected")}catch(n){throw this.appendWarning("ports need to be open on firewall in order to connect."),n}e||this.appendWarning("Server is not configured for ICE/TCP"),t||this.appendWarning("No public IPv4 UDP candidates were found. Your server is likely not configured correctly")})}};function ME(i){let e=i.split(".");if(e.length===4){if(e[0]==="10")return!0;
75if(e[0]==="192"&&e[1]==="168")return!0;if(e[0]==="172"){let t=parseInt(e[1],10);if(t>=16&&t<=31)return!0}}return!1}var ed=class extends mn{get description(){return"Connecting to signal connection via WebSocket"}perform(){return A(this,void 0,void 0,function*(){var e,t,n;(this.url.startsWith("ws:")||this.url.startsWith("http:"))&&this.appendWarning("Server is insecure, clients may block connections to it");let r=new As,s;try{s=yield r.join(this.url,this.token,{autoSubscribe:!0,maxRetries:0,e2eeEnabled:!1,websocketTimeout:15e3},void 0,!0)}catch(o){if(Pr(new URL(this.url))){this.appendMessage("Initial connection failed with error ".concat(o.message,". Retrying with region fallback"));let d=yield new tn(this.url,this.token).getNextBestRegionUrl();d&&(s=yield r.join(d,this.token,{autoSubscribe:!0,maxRetries:0,e2eeEnabled:!1,websocketTimeout:15e3},void 0,!0),this.appendMessage("Fallback to region worked. To avoid initial connections failing, ensure you're calling room.prepareConnection() ahead of time"))}}s?(this.appendMessage("Connected to server, version ".concat(s.serverVersion,".")),((e=s.serverInfo)===null||e===void 0?void 0:e.edition)===Jv.Cloud&&(!((t=s.serverInfo)===null||t===void 0)&&t.region)&&this.appendMessage("LiveKit Cloud: ".concat((n=s.serverInfo)===null||n===void 0?void 0:n.region))):this.appendError("Websocket connection could not be established"),yield r.close()})}},gv=class extends _t.EventEmitter{constructor(e,t){let n=arguments.length>2&&arguments[2]!==void 0?arguments[2]:{};super(),this.options={},this.checkResults=new Map,this.url=e,this.token=t,this.options=n}getNextCheckId(){let e=this.checkResults.size;return this.checkResults.set(e,{logs:[],status:Jt.IDLE,name:"",description:""}),e}updateCheck(e,t){this.checkResults.set(e,t),this.emit("checkUpdate",e,t)}isSuccess(){return Array.from(this.checkResults.values()).every(e=>e.status!==Jt.FAILED)}getResults(){return Array.from(this.checkResults.values())}createAndRunCheck(e){return A(this,void 0,void 0,function*(){let t=this.getNextCheckId(),n=new e(this.url,this.token,this.options),r=o=>{this.updateCheck(t,o)};n.on("update",r);let s=yield n.run();return n.off("update",r),s})}checkWebsocket(){return A(this,void 0,void 0,function*(){return this.createAndRunCheck(ed)})}checkWebRTC(){return A(this,void 0,void 0,function*(){return this.createAndRunCheck(Zu)})}checkTURN(){return A(this,void 0,void 0,function*(){return this.createAndRunCheck(Xu)})}checkReconnect(){return A(this,void 0,void 0,function*(){return this.createAndRunCheck(Qu)})}checkPublishAudio(){return A(this,void 0,void 0,function*(){return this.createAndRunCheck(zu)})}checkPublishVideo(){return A(this,void 0,void 0,function*(){return this.createAndRunCheck(Yu)})}checkConnectionProtocol(){return A(this,void 0,void 0,function*(){let e=yield this.createAndRunCheck(Ku);if(e.data&&"protocol"in e.data){let t=e.data;this.options.protocol=t.protocol}return e})}checkCloudRegion(){return A(this,void 0,void 0,function*(){return this.createAndRunCheck(Hu)})}};new TextEncoder;var WP=new TextDecoder;var dt=class extends Error{constructor(e,t){var n;super(e,t),Ce(this,"code","ERR_JOSE_GENERIC"),this.name=this.constructor.name,(n=Error.captureStackTrace)===null||n===void 0||n.call(Error,this,this.constructor)}};Ce(dt,"code","ERR_JOSE_GENERIC");var td=class extends dt{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}}),Ce(this,"code","ERR_JWT_CLAIM_VALIDATION_FAILED"),Ce(this,"claim",void 0),Ce(this,"reason",void 0),Ce(this,"payload",void 0),this.claim=n,this.reason=r,this.payload=t}};Ce(td,"code","ERR_JWT_CLAIM_VALIDATION_FAILED");var nd=class extends dt{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}}),Ce(this,"code","ERR_JWT_EXPIRED"),Ce(this,"claim",void 0),Ce(this,"reason",void 0),Ce(this,"payload",void 0),this.claim=n,this.reason=r,this.payload=t}};
75Ce(nd,"code","ERR_JWT_EXPIRED");var id=class extends dt{constructor(){super(...arguments),Ce(this,"code","ERR_JOSE_ALG_NOT_ALLOWED")}};Ce(id,"code","ERR_JOSE_ALG_NOT_ALLOWED");var rd=class extends dt{constructor(){super(...arguments),Ce(this,"code","ERR_JOSE_NOT_SUPPORTED")}};Ce(rd,"code","ERR_JOSE_NOT_SUPPORTED");var sd=class extends dt{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),Ce(this,"code","ERR_JWE_DECRYPTION_FAILED")}};Ce(sd,"code","ERR_JWE_DECRYPTION_FAILED");var od=class extends dt{constructor(){super(...arguments),Ce(this,"code","ERR_JWE_INVALID")}};Ce(od,"code","ERR_JWE_INVALID");var ad=class extends dt{constructor(){super(...arguments),Ce(this,"code","ERR_JWS_INVALID")}};Ce(ad,"code","ERR_JWS_INVALID");var cd=class extends dt{constructor(){super(...arguments),Ce(this,"code","ERR_JWT_INVALID")}};Ce(cd,"code","ERR_JWT_INVALID");var ld=class extends dt{constructor(){super(...arguments),Ce(this,"code","ERR_JWK_INVALID")}};Ce(ld,"code","ERR_JWK_INVALID");var ud=class extends dt{constructor(){super(...arguments),Ce(this,"code","ERR_JWKS_INVALID")}};Ce(ud,"code","ERR_JWKS_INVALID");var dd=class extends dt{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),Ce(this,"code","ERR_JWKS_NO_MATCHING_KEY")}};Ce(dd,"code","ERR_JWKS_NO_MATCHING_KEY");var hd=class extends dt{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),Ce(this,Symbol.asyncIterator,void 0),Ce(this,"code","ERR_JWKS_MULTIPLE_MATCHING_KEYS")}};Ce(hd,"code","ERR_JWKS_MULTIPLE_MATCHING_KEYS");var pd=class extends dt{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),Ce(this,"code","ERR_JWKS_TIMEOUT")}};Ce(pd,"code","ERR_JWKS_TIMEOUT");var fd=class extends dt{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),Ce(this,"code","ERR_JWS_SIGNATURE_VERIFICATION_FAILED")}};Ce(fd,"code","ERR_JWS_SIGNATURE_VERIFICATION_FAILED");var RE=1e3,GP=60*RE;var Jd="conversation_initiation_client_data";function xa(i){let e={type:Jd};return i.overrides&&(e.conversation_config_override={agent:{prompt:i.overrides.agent?.prompt,first_message:i.overrides.agent?.firstMessage,language:i.overrides.agent?.language},tts:{voice_id:i.overrides.tts?.voiceId,speed:i.overrides.tts?.speed,stability:i.overrides.tts?.stability,similarity_boost:i.overrides.tts?.similarityBoost},...i.overrides.asr?.keywords!==void 0?{asr:{keywords:i.overrides.asr.keywords}}:{},conversation:{text_only:i.overrides.conversation?.textOnly}}),i.customLlmExtraBody&&(e.custom_llm_extra_body=i.customLlmExtraBody),i.dynamicVariables&&(e.dynamic_variables=i.dynamicVariables),i.userId&&(e.user_id=i.userId),e.source_info={source:ki.name,version:ki.version},i.toolMockConfig&&(e.tool_mock_config={mocking_strategy:i.toolMockConfig.mockingStrategy,mocked_tool_names:i.toolMockConfig.mockedToolNames,fallback_strategy:i.toolMockConfig.fallbackStrategy}),e}function Dr(i){let e=new Uint8Array(i);return btoa(String.fromCharCode(...e))}function wb(i){let e=atob(i),t=e.length,n=new Uint8Array(t);for(let r=0;r<t;r++)n[r]=e.charCodeAt(r);return n.buffer}var Is={getVolume:()=>0,getByteFrequencyData:()=>{}},IE=100,OE=8e3;function Hd(i,e,t){let n=i.length,r=t/2/n,s=Math.floor(IE/r),o=Math.min(Math.ceil(OE/r),n),a=o-s,d=e.length;for(let l=0;l<d;l++){let f=l/d*a,p=s+Math.floor(f),g=Math.min(p+1,o-1),b=f-Math.floor(f);e[l]=Math.round(i[p]*(1-b)+i[g]*b)}}var Eb;function Pb(i){Eb=i}function Ab(){return Eb?.()??null}var DE="wss://livekit.rtc.elevenlabs.io",LE="https://api.elevenlabs.io",xE=.01;function NE(i){return i.replace(/^wss:\/\//,"https://")}var Fi=class i extends ar{conversationId;inputFormat;outputFormat;room;isConnected=!1;audioEventId=1;outputDeviceId=null;audioAdapter;workletPaths;inputAnalyser=void 0;inputVolumeProvider=Is;outputAnalyser=void 0;outputVolumeProvider=Is;_isMuted=!1;input={close:async()=>
vendor: 5,275 bytes, line 75
75{if(this.isConnected)try{this.room.localParticipant.audioTrackPublications.forEach(e=>{e.track&&e.track.stop()})}catch(e){console.warn("Error stopping local tracks:",e)}},setDevice:async e=>{if(e?.sampleRate!==void 0||e?.format!==void 0||e?.preferHeadphonesForIosDevices!==void 0)throw new Error("WebRTC input device does not support sampleRate, format, or preferHeadphonesForIosDevices options");let t=e?.inputDeviceId;t&&await this.setAudioInputDevice(t)},setMuted:async e=>{if(!this.isConnected||!this.room.localParticipant){console.warn("Cannot set microphone muted: room not connected or no local participant");return}this._isMuted=e;let t=this.room.localParticipant.getTrackPublication(J.Source.Microphone);if(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);if(!e){let n=this.room.localParticipant.getTrackPublication(J.Source.Microphone)?.track;n&&this.setupInputAnalyser(n.mediaStreamTrack)}},isMuted:()=>this._isMuted,getAnalyser:()=>this.inputAnalyser,getVolume:()=>this._isMuted?0:this.inputVolumeProvider.getVolume(),getByteFrequencyData:e=>{if(this._isMuted){e.fill(0);return}this.inputVolumeProvider.getByteFrequencyData(e)}};output={close:async()=>{},setDevice:async e=>{if(e?.sampleRate!==void 0||e?.format!==void 0)throw new Error("WebRTC output device does not support sampleRate or format options");let t=e?.outputDeviceId;t&&await this.setAudioOutputDevice(t)},setVolume:e=>{this.setAudioVolume(e)},interrupt:e=>{},getAnalyser:()=>this.outputAnalyser,getVolume:()=>this.outputVolumeProvider.getVolume(),getByteFrequencyData:e=>{this.outputVolumeProvider.getByteFrequencyData(e)}};constructor(e,t,n,r,s={}){super(s),this.room=e,this.conversationId=t,this.inputFormat=n,this.outputFormat=r,this.audioAdapter=Ab(),this.workletPaths=s.workletPaths,this.setupRoomEventListeners()}static async create(e){let t;if("conversationToken"in e&&e.conversationToken)t=e.conversationToken;else if("agentId"in e&&e.agentId)try{let{name:s,version:o}=ki,a=e.origin??LE,l=`${NE(a)}/v1/convai/conversation/token?agent_id=${e.agentId}&source=${s}&version=${o}`;e.environment&&(l+=`&environment=${encodeURIComponent(e.environment)}`);let f=await fetch(l);if(!f.ok){let g=await ko(f);throw new Error(`ElevenLabs API returned ${f.status} ${g}`)}let p=await f.json();if(!lr(p)||typeof p.token!="string")throw new Error("No conversation token received from API");if(t=p.token,!t)throw new Error("No conversation token received from API")}catch(s){let o=s instanceof Error?s.message:String(s);throw s instanceof Error&&s.message.includes("401")&&(o="Your agent has authentication enabled, but no signed URL or conversation token was provided."),new Error(`Failed to fetch conversation token for agent ${e.agentId}: ${o}`)}else throw new Error("Either conversationToken or agentId is required for WebRTC connection");let n=e.webRtc?.singlePeerConnection,r=new Or(n===void 0?void 0:{singlePeerConnection:n});try{let s=`room_${Date.now()}`,o=cr("pcm_48000"),a=cr("pcm_48000"),d=new i(r,s,o,a,e),l=e.livekitUrl||DE,f=e.textOnly?Promise.resolve():new Promise((R,w)=>{r.once(H.SignalConnected,()=>{d.enableMicrophone(e.inputDeviceId).then(()=>R()).catch(w)})}),p=e.webRtc?.iceTransportPolicy;await r.connect(l,t,{rtcConfig:p?{iceTransportPolicy:p}:void 0}),await new Promise(R=>{if(d.isConnected)R();else{let w=()=>{r.off(H.Connected,w),R()};r.on(H.Connected,w)}}),await f;let g=r.localParticipant.getTrackPublication(J.Source.Microphone)?.track;g&&d.setupInputAnalyser(g.mediaStreamTrack),r.name&&(d.conversationId=r.name.match(/(conv_[a-zA-Z0-9]+)/)?.[0]||r.name);let b=xa(e);return d.debug({type:Jd,message:b}),await d.sendRequiredMessage(b),d}catch(s){throw await r.disconnect(),s}}setupRoomEventListeners(){this.room.on(H.Connected,()=>{this.isConnected=!0}),this.room.on(H.Disconnected,e=>{this.isConnected=!1,this.disconnect({reason:"agent",context:{type:"close",reason:e?.toString()}})}),this.room.on(H.ConnectionStateChanged,e=>{e===Re.Disconnected&&(this.isConnected=!1,this.disconnect({reason:"error",message:`LiveKit connection state changed to ${e}`,context:{type:"connection_state_changed"}}))}),this.room.on(H.DataReceived,(e,t)=>{try{let n=JSON.parse(new TextDecoder().decode(e));if(n.type==="audio"){dr(n)&&this.handleMessage(n);return}dr(n)?this.handleMessage(n):console.warn("Invalid socket event received:",n)}catch(n){console.warn("Failed to parse incoming data message:",n),console.warn("Raw payload:",new TextDecoder().decode(e))}}),this.room.on(H.TrackSubscribed,async(e,t,n)=>{if(e.kind===J.Kind.Audio&&n.identity.includes("agent")){let r=e;this.audioAdapter&&(await this.audioAdapter.attachRemoteTrack(r,this.outputDeviceId),await this.setupAudioCapture(r),this.onDebug?.({type:"audio_element_ready"}))}}),this.room.on(H.ActiveSpeakersChanged,async e=>{e.length>0?this.updateMode(e[0].identity.startsWith("agent")?"speaking":"listening"):this.updateMode("listening")}),this.room.on(H.ParticipantDisconnected,e=>{e.identity?.startsWith("agent")&&this.disconnect({reason:"agent",context:{type:"close",reason:"agent disconnected"}})})}close(){if(this.isConnected){try{this.room.localParticipant.audioTrackPublications.forEach(e
75=>{e.track&&e.track.stop()})}catch(e){console.warn("Error stopping local tracks:",e)}this.audioAdapter?.cleanup(),this.inputAnalyser=void 0,this.outputAnalyser=void 0,this.inputVolumeProvider=Is,this.outputVolumeProvider=Is,this.room.disconnect()}}async sendMessage(e){if(!this.isConnected||!this.room.localParticipant){console.warn("Cannot send message: room not connected or no local participant");return}if(!("user_audio_chunk"in e)){this.handleOutgoingMessage(e);try{await this.publishMessage(e)}catch(t){this.debug({type:"send_message_error",message:{message:e,error:t}}),console.error("Failed to send message via WebRTC:",t)}}}async sendRequiredMessage(e){if(!this.isConnected||!this.room.localParticipant)throw new Error("Cannot send message: room not connected or no local participant");this.handleOutgoingMessage(e),await this.publishMessage(e)}async publishMessage(e){let n=new TextEncoder().encode(JSON.stringify(e));await this.room.localParticipant.publishData(n,{reliable:!0})}getRoom(){return this.room}setupInputAnalyser(e){if(this.audioAdapter)try{let t=this.audioAdapter.setupInputAnalysis(e);this.inputVolumeProvider=t.volumeProvider,this.inputAnalyser=t.analyser}catch(t){console.warn("[ConversationalAI] Failed to set up input volume analyser:",t)}}setInputVolumeProvider(e){this.inputVolumeProvider=e}setOutputVolumeProvider(e){this.outputVolumeProvider=e}async setupAudioCapture(e){if(this.audioAdapter)try{let t=(r,s)=>{if(s>xE){let o=Dr(r),a=this.audioEventId++;this.handleMessage({type:"audio",audio_event:{audio_base_64:o,event_id:a}})}},n=await this.audioAdapter.setupOutputAnalysis(e,this.outputFormat,t,this.workletPaths);this.outputVolumeProvider=n.volumeProvider,this.outputAnalyser=n.analyser}catch(t){console.warn("Failed to set up audio capture:",t)}}setAudioVolume(e){this.audioAdapter?.setVolume(e)}async setAudioOutputDevice(e){if(!this.audioAdapter)throw new Error("Cannot set output device: no audio adapter available on this platform");await this.audioAdapter.setOutputDevice(e),this.outputDeviceId=e}async setAudioInputDevice(e){if(!this.isConnected||!this.room.localParticipant)throw new Error("Cannot change input device: room not connected or no local participant");let t=await this.createMicrophoneTrack(e);try{let n=this.room.localParticipant.getTrackPublication(J.Source.Microphone);n?.track&&await this.room.localParticipant.unpublishTrack(n.track),this._isMuted&&await t.mute(),await this.room.localParticipant.publishTrack(t,{name:"microphone",source:J.Source.Microphone})}catch(n){console.error("Failed to change input device:",n);let r=this.room.localParticipant.getTrackPublication(J.Source.Microphone);if(r?.track!==t&&t.stop(),!r?.track)try{await this.room.localParticipant.setMicrophoneEnabled(!this._isMuted);let s=this.room.localParticipant.getTrackPublication(J.Source.Microphone)?.track;s&&this.setupInputAnalyser(s.mediaStreamTrack)}catch(s){console.error("Failed to recover microphone after device switch error:",s)}throw n}this.setupInputAnalyser(t.mediaStreamTrack)}async enableMicrophone(e){if(!e){await this.room.localParticipant.setMicrophoneEnabled(!0);return}let t=await this.createMicrophoneTrack(e);try{await this.room.localParticipant.publishTrack(t,{name:"microphone",source:J.Source.Microphone})}catch(n){throw t.stop(),n}}createMicrophoneTrack(e){return Gd({deviceId:{exact:e},echoCancellation:!0,noiseSuppression:!0,autoGainControl:!0,channelCount:{ideal:1}})}};var FE='Import the platform-specific entry point (e.g. @elevenlabs/client via the "browser" export).',UE=FE;function Kd(i){return new Error(`No ${i} registered. ${UE}`)}var zd;function Mb(i){zd=i}function Rb(){if(zd)return zd;throw Kd("voice session setup strategy")}function Ib(i){if(!(i instanceof Fi))throw new Error(`setupWebRTCSession requires a WebRTCConnection. Received: ${i?.constructor?.name??typeof i}`);return{connection:i,input:i.input,output:i.output,playbackEventTarget:null,detach:async()=>{}}}var Na=new Map;function jE(i,e){return e?`${i} ${e}`:i}function Lr(i,e){return async(t,n)=>{let r=jE(i,n),s=Na.get(r);if(s)return t.addModule(s);if(n)try{await t.addModule(n),Na.set(r,n);return}catch(d){throw new Error(`Failed to load the ${i} worklet module from path: ${n}. Error: ${d}`)}let o=new Blob([e],{type:"application/javascript"}),a=URL.createObjectURL(o);try{await t.addModule(a),Na.set(r,a);return}catch{URL.revokeObjectURL(a)}try{let l=`data:application/javascript;base64,${btoa(e)}`;await t.addModule(l),Na.set(r,l)}catch{throw new Error(`Failed to load the ${i} worklet module. Make sure the browser supports AudioWorklets. If you are using a strict CSP, you may
75need to self-host the worklet files.`)}}}var Ob=Lr("audioConcatProcessor",`/* 76 * ulaw decoding logic taken from the wavefile library 77 * https://github.com/rochars/wavefile/blob/master/lib/codecs/mulaw.js 78 * USED BY @elevenlabs/client 79 */ 80 81const decodeTable = [0, 132, 396, 924, 1980, 4092, 8316, 16764]; 82 83function decodeSample(muLawSample) { 84 let sign; 85 let exponent; 86 let mantissa; 87 let sample; 88 muLawSample = ~muLawSample; 89 sign = muLawSample & 0x80; 90 exponent = (muLawSample >> 4) & 0x07; 91 mantissa = muLawSample & 0x0f; 92 sample = decodeTable[exponent] + (mantissa << (exponent + 3)); 93 if (sign !== 0) sample = -sample; 94 95 return sample; 96} 97 98class AudioConcatProcessor extends AudioWorkletProcessor { 99 constructor() { 100 super(); 101 this.buffers = []; // Initialize an empty buffer 102 this.cursor = 0; 103 this.currentBuffer = null; 104 this.wasInterrupted = false; 105 this.finished = false; 106 107 this.port.onmessage = ({ data }) => { 108 switch (data.type) { 109 case "setFormat": 110 this.format = data.format; 111 if (globalThis.LibSampleRate && sampleRate !== data.sampleRate) { 112 globalThis.LibSampleRate.create( 113 1, 114 data.sampleRate, 115 sampleRate 116 ).then(resampler => { 117 this.resampler = resampler; 118 }); 119 } 120 break; 121 case "buffer": 122 this.wasInterrupted = false; 123 this.buffers.push( 124 this.format === "ulaw" 125 ? new Uint8Array(data.buffer) 126 : new Int16Array(data.buffer) 127 ); 128 break; 129 case "interrupt": 130 this.wasInterrupted = true; 131 break; 132 case "clearInterrupted": 133 if (this.wasInterrupted) { 134 this.wasInterrupted = false; 135 this.buffers = []; 136 this.currentBuffer = null; 137 } 138 } 139 }; 140 } 141 process(_, outputs) { 142 let finished = false; 143 const output = outputs[0][0]; 144 for (let i = 0; i < output.length; i++) { 145 if (!this.currentBuffer) { 146 if (this.buffers.length === 0) { 147 finished = true; 148 break; 149 } 150 this.currentBuffer = this.buffers.shift(); 151 if (this.resampler) { 152 this.currentBuffer = this.resampler.full(this.currentBuffer); 153 } 154 this.cursor = 0; 155 } 156 157 let value = this.currentBuffer[this.cursor]; 158 if (this.format === "ulaw") { 159 value = decodeSample(value); 160 } 161 output[i] = value / 32768; 162 this.cursor++; 163 164 if (this.cursor >= this.currentBuffer.length) { 165 this.currentBuffer = null; 166 } 167 } 168 169 if (this.finished !== finished) { 170 this.finished = finished; 171 this.port.postMessage({ type: "process", finished }); 172 } 173 174 return true; // Continue processing 175 } 176} 177 178registerProcessor("audioConcatProcessor", AudioConcatProcessor); 179`);var BE="https://cdn.jsdelivr.net/npm/@alexanderolsen/[email protected]/dist/libsamplerate.worklet.js";async function Fa(i,e){let t=e||BE;await i.audioWorklet.addModule(t)}function Db(i){if(i.length===0)return 0;let e=0;for(let t=0;t<i.length;t++)e+=i[t]/255;return e/=i.length,e<0?0:e>1?1:e}function Ui(i,e){let t=i.frequencyBinCount,n,r;return{getVolume(){return n??=new Uint8Array(t),r??=new Uint8Array(t),i.getByteFrequencyData(n),Hd(n,r,e),Db(r)},getByteFrequencyData(s){n??=new Uint8Array(t),i.getByteFrequencyData(n),Hd(n,s,e)}}}function gn(){return["iPad Simulator","iPhone Simulator","iPod Simulator","iPad","iPhone","iPod"].includes(navigator.platform)||navigator.userAgent.includes("Mac")&&"ontouchend"in document}function Lb(){return/android/i.test(navigator.userAgent)}function qE({sampleRate:i,format:e,worklet:t,audioElement:n}){if(!gn())return;let s=Math.floor(i*100/1e3),o=e==="ulaw"?new Uint8Array(s).fill(255):new Int16Array(s);t.port.postMessage({type:"buffer",buffer:o.buffer}),n.play().catch(()=>{})}var Ua=class i{context;analyser;gain;worklet;audioElement;static async create({sampleRate:e,format:t,outputDeviceId:n,workletPaths:r,libsampleratePath:s,audioContext:o}){let a=o??null,d=null;try{let l=navigator.mediaDevices.getSupportedConstraints().sampleRate;a||(a=new AudioContext(l?{sampleRate:e}:{}));let f=a.createAnalyser(),p=a.createGain();d=new Audio,d.src="",d.load(),d.autoplay=!0,d.style.display="none",document.body.appendChild(d);let g=a.createMediaStreamDestination();d.srcObject=g.stream,p.connect(f),f.connect(g),(!l||a.sampleRate!==e)&&(a.sampleRate!==e&&console.warn(`[ConversationalAI] Sample rate ${e} not available, resampling to ${a.sampleRate}`),await Fa(a,s)),await Ob(a.audioWorklet,r?.audioConcatProcessor);let b=new AudioWorkletNode(a,"audioConcatProcessor");return b.port.postMessage({type:"setFormat",format:t,sampleRate:e}),b.connect(p),await a.resume(),qE({sampleRate:e,format:t,worklet:b,audioElement:d}),n&&d.setSinkId&&await d.setSinkId(n),new i(a,f,p,b,d)}catch(l){throw d?.parentNode&&d.parentNode.removeChild(d),d?.pause(),a&&a.state!=="closed"&&await a.close(),l}}volume=1;interrupted=!1;interruptTimeout=null;volumeProvider;
179constructor(e,t,n,r,s){this.context=e,this.analyser=t,this.gain=n,this.worklet=r,this.audioElement=s,this.worklet.port.start(),this.volumeProvider=Ui(t,e.sampleRate)}getAnalyser(){return this.analyser}getVolume(){return this.volumeProvider.getVolume()}getByteFrequencyData(e){this.volumeProvider.getByteFrequencyData(e)}addListener(e){this.worklet.port.addEventListener("message",e)}removeListener(e){this.worklet.port.removeEventListener("message",e)}setVolume(e){this.volume=e,this.gain.gain.value=e}playAudio(e){this.gain.gain.cancelScheduledValues(this.context.currentTime),this.gain.gain.value=this.volume,this.interruptTimeout&&(clearTimeout(this.interruptTimeout),this.interruptTimeout=null),this.worklet.port.postMessage({type:"clearInterrupted"}),this.worklet.port.postMessage({type:"buffer",buffer:e})}interrupt(e=2e3){this.interrupted=!0,this.interruptTimeout&&(clearTimeout(this.interruptTimeout),this.interruptTimeout=null),this.worklet.port.postMessage({type:"interrupt"}),this.gain.gain.exponentialRampToValueAtTime(1e-4,this.context.currentTime+e/1e3),this.interruptTimeout=setTimeout(()=>{this.interrupted=!1,this.gain.gain.value=this.volume,this.worklet.port.postMessage({type:"clearInterrupted"}),this.interruptTimeout=null},e)}async setDevice(e){if(!("setSinkId"in HTMLAudioElement.prototype))throw new Error("setSinkId is not supported in this browser");let t=e?.outputDeviceId;await this.audioElement.setSinkId(t||"")}async close(){this.interruptTimeout&&(clearTimeout(this.interruptTimeout),this.interruptTimeout=null),this.audioElement.parentNode&&this.audioElement.parentNode.removeChild(this.audioElement),this.audioElement.pause(),await this.context.close()}};var ja=Lr("rawAudioProcessor",`/* 180 * ulaw encoding logic taken from the wavefile library 181 * https://github.com/rochars/wavefile/blob/master/lib/codecs/mulaw.js 182 * USED BY @elevenlabs/client 183 */ 184 185const BIAS = 0x84; 186const CLIP = 32635; 187const encodeTable = [ 188 0,0,1,1,2,2,2,2,3,3,3,3,3,3,3,3, 189 4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4, 190 5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5, 191 5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5, 192 6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6, 193 6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6, 194 6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6, 195 6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6, 196 7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7, 197 7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7, 198 7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7, 199 7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7, 200 7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7, 201 7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7, 202 7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7, 203 7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7 204]; 205 206function encodeSample(sample) { 207 let sign; 208 let exponent; 209 let mantissa; 210 let muLawSample; 211 sign = (sample >> 8) & 0x80; 212 if (sign !== 0) sample = -sample; 213 sample = sample + BIAS; 214 if (sample > CLIP) sample = CLIP; 215 exponent = encodeTable[(sample>>7) & 0xFF]; 216 mantissa = (sample >> (exponent+3)) & 0x0F; 217 muLawSample = ~(sign | (exponent << 4) | mantissa); 218 219 return muLawSample; 220} 221 222class RawAudioProcessor extends AudioWorkletProcessor { 223 constructor() { 224 super(); 225 226 this.port.onmessage = ({ data }) => { 227 switch (data.type) { 228 case "setFormat": 229 this.isMuted = false; 230 this.buffer = []; // Initialize an empty buffer 231 const chunkDurationMs = data.chunkDurationMs ?? 25; 232 this.bufferSize = Math.max( 233 1, 234 Math.round((data.sampleRate * chunkDurationMs) / 1000) 235 ); 236 this.format = data.format; 237 238 if (globalThis.LibSampleRate && sampleRate !== data.sampleRate) { 239 globalThis.LibSampleRate.create(1, sampleRate, data.sampleRate).then(resampler => { 240 this.resampler = resampler; 241 }); 242 } 243 break; 244 case "setMuted": 245 this.isMuted = data.isMuted; 246 break; 247 } 248 }; 249 } 250 process(inputs) { 251 if (!this.buffer) { 252 return true; 253 } 254 255 const input = inputs[0]; // Get the first input node 256 if (input.length > 0) { 257 let channelData = input[0]; // Get the first channel's data 258 259 // Resample the audio if necessary 260 if (this.resampler) { 261 channelData = this.resampler.full(channelData); 262 } 263 264 // Add channel data to the buffer 265 this.buffer.push(...channelData); 266 // Get max volume 267 let sum = 0.0; 268 for (let i = 0; i < channelData.length; i++) { 269 sum += channelData[i] * channelData[i]; 270 } 271 const maxVolume = Math.sqrt(sum / channelData.length); 272 // Check if buffer size has reached or exceeded the threshold 273 if (this.buffer.length >= this.bufferSize) { 274 const float32Array = this.isMuted 275 ? new Float32Array(this.buffer.length) 276 : new Float32Array(this.buffer); 277 278 let encodedArray = this.format === "ulaw" 279 ? new Uint8Array(float32Array.length) 280 : new Int16Array(float32Array.length); 281 282 // Iterate through the Float32Array and convert each sample to PCM16 283 for (let i = 0; i < float32Array.length; i++) { 284 // Clamp the value to the range [-1, 1] 285 let sample = Math.max(-1, Math.min(1, float32Array[i])); 286 287 // Scale the sample to the range [-32768, 32767] 288 let value = sample < 0 ? sample * 32768 : sample * 32767; 289 if (this.format === "ulaw") { 290 value = encodeSample(Math.round(value)); 291 } 292 293 encodedArray[i] = value; 294 } 295 296 // Send the buffered data to the main script 297 this.port.postMessage([encodedArray, maxVolume]); 298 299 // Clear the buffer after sending 300 this.buffer = []; 301 } 302 } 303 return true; // Continue processing 304 } 305} 306registerProcessor("rawAudioProcessor", RawAudioProcessor); 307`);var xb={echoCancellation:!0,noiseSuppression:!0,autoGainControl:!0,channelCount:{ideal:1}},Ba=class i{context;analyser;worklet;inputStream;mediaStreamSource;permissions;onError;static async create({sampleRate:e,format:t,preferHeadphonesForIosDevices:n,inputDeviceId:r,workletPaths:s,libsampleratePath:o,onError:a,inputChunkDurationMs:d=25}){let l=null,f=null;try{let p={sampleRate:{ideal:e},...xb};
vendor: 4,428 bytes, line 307
307if(gn()&&n){let j=(await window.navigator.mediaDevices.enumerateDevices()).find(M=>M.kind==="audioinput"&&["airpod","headphone","earphone"].find(P=>M.label.toLowerCase().includes(P)));j&&(p.deviceId={ideal:j.deviceId})}r&&(p.deviceId=i.getDeviceIdConstraint(r));let g=navigator.mediaDevices.getSupportedConstraints().sampleRate;l=new window.AudioContext(g?{sampleRate:e}:{});let b=l.createAnalyser();g||await Fa(l,o),await ja(l.audioWorklet,s?.rawAudioProcessor);let R={voiceIsolation:!0,...p};f=await navigator.mediaDevices.getUserMedia({audio:R});let w=l.createMediaStreamSource(f),I=new AudioWorkletNode(l,"rawAudioProcessor");I.port.postMessage({type:"setFormat",format:t,sampleRate:e,chunkDurationMs:d}),w.connect(b),b.connect(I),await l.resume();let N=await navigator.permissions.query({name:"microphone"});return new i(l,b,I,f,w,N,a)}catch(p){throw f?.getTracks().forEach(g=>{g.stop()}),l?.close(),p}}static getDeviceIdConstraint(e){if(e)return gn()?{ideal:e}:{exact:e}}muted=!1;volumeProvider;constructor(e,t,n,r,s,o,a=console.error){this.context=e,this.analyser=t,this.worklet=n,this.inputStream=r,this.mediaStreamSource=s,this.permissions=o,this.onError=a,this.permissions.addEventListener("change",this.handlePermissionsChange),this.worklet.port.start(),this.volumeProvider=Ui(t,e.sampleRate)}getAnalyser(){return this.analyser}getVolume(){return this.muted?0:this.volumeProvider.getVolume()}getByteFrequencyData(e){if(this.muted){e.fill(0);return}this.volumeProvider.getByteFrequencyData(e)}isMuted(){return this.muted}addListener(e){this.worklet.port.addEventListener("message",e)}removeListener(e){this.worklet.port.removeEventListener("message",e)}forgetInputStreamAndSource(){for(let e of this.inputStream.getTracks())e.stop();this.mediaStreamSource.disconnect()}async close(){this.forgetInputStreamAndSource(),this.permissions.removeEventListener("change",this.handlePermissionsChange),await this.context.close()}async setMuted(e){this.muted=e,this.worklet.port.postMessage({type:"setMuted",isMuted:e})}settingInput=!1;async setDevice(e){try{if(this.settingInput)throw new Error("Input device is already being set");this.settingInput=!0;let t=e?.inputDeviceId,n={...xb};t&&(n.deviceId=i.getDeviceIdConstraint(t));let r={voiceIsolation:!0,...n},s=await navigator.mediaDevices.getUserMedia({audio:r});this.forgetInputStreamAndSource(),this.inputStream=s,this.mediaStreamSource=this.context.createMediaStreamSource(s),this.mediaStreamSource.connect(this.analyser)}catch(t){throw this.onError("Failed to switch input device:",t),t}finally{this.settingInput=!1}}handlePermissionsChange=()=>{if(this.permissions.state==="denied")this.onError("Microphone permission denied");else if(!this.settingInput){let[e]=this.inputStream.getAudioTracks(),{deviceId:t}=e?.getSettings()??{};this.setDevice({inputDeviceId:t}).catch(n=>{this.onError("Failed to reset input device after permission change:",n)})}}};var VE="enclave_setup_config";function Fb(i){return{url:i.url,...i.hmacSecret!==void 0?{hmac_secret:i.hmacSecret}:{}}}function Ub(i){let e={type:VE,agent_config_dict:i.agentConfig??null,override_agent_config_list:i.agentConfigOverrides??null,tools_config_list:i.tools??null,prompt_knowledge_base:i.promptKnowledgeBase??null};return i.bedrockInferenceProfile!==void 0&&(e.bedrock_inference_profile=i.bedrockInferenceProfile),i.postCallTranscriptionWebhook&&(e.post_call_transcription_webhook=Fb(i.postCallTranscriptionWebhook)),i.postCallAudioWebhook&&(e.post_call_audio_webhook=Fb(i.postCallAudioWebhook)),e}var $E="convai",WE="wss://api.elevenlabs.io",GE="/v1/convai/conversation?agent_id=",ji=class i extends ar{socket;conversationId;inputFormat;outputFormat;outputListeners=new Set;pendingAudioEvents=[];constructor(e,t,n,r){super(),this.socket=e,this.conversationId=t,this.inputFormat=n,this.outputFormat=r,this.socket.addEventListener("error",s=>{setTimeout(()=>this.disconnect({reason:"error",message:"The connection was closed due to a socket error.",context:{type:s.type}}),0)}),this.socket.addEventListener("close",s=>{let o=s.code,a=s.reason||void 0,d={type:s.type,code:o,reason:a};this.disconnect(o===1e3?{reason:"agent",context:d,closeCode:o,closeReason:a}:{reason:"error",message:a||"The connection was closed by the server.",context:d,closeCode:o,closeReason:a})}),this.socket.addEventListener("message",s=>{try{let o=JSON.parse(s.data);if(!dr(o)){this.debug({type:"invalid_event",message:"Received invali
307d socket event",data:s.data});return}this.handleMessage(o)}catch(o){this.debug({type:"parsing_error",message:"Failed to parse socket message",error:o instanceof Error?o.message:String(o),data:s.data})}})}static async create(e){let t=null;try{let n,r,{name:s,version:o}=ki;if(e.orchestrator)n=e.orchestrator.url;else{let b=e.origin??WE;if(e.signedUrl){let R=e.signedUrl.includes("?")?"&":"?";n=`${e.signedUrl}${R}source=${s}&version=${o}`}else n=`${b}${GE}${e.agentId}&source=${s}&version=${o}`;e.environment&&(n+=`&environment=${encodeURIComponent(e.environment)}`),r=[$E],e.authorization&&r.push(`bearer.${e.authorization}`)}t=new WebSocket(n,r);let a=await new Promise((b,R)=>{t.addEventListener("open",()=>{e.orchestrator&&t?.send(JSON.stringify(Ub(e.orchestrator)));let w=xa(e);t?.send(JSON.stringify(w))},{once:!0}),t.addEventListener("error",w=>{setTimeout(()=>R(new ur("The connection was closed due to a socket error.")),0)}),t.addEventListener("close",w=>{let I=w.reason||(w.code===1e3?"Connection closed normally before session could be established.":"Connection closed unexpectedly before session could be established.");R(new ur(I,{closeCode:w.code,closeReason:w.reason||void 0}))}),t.addEventListener("message",w=>{let I=JSON.parse(w.data);dr(I)&&(I.type==="conversation_initiation_metadata"?b(I.conversation_initiation_metadata_event):console.warn("First received message is not conversation metadata."))},{once:!0})}),{conversation_id:d,agent_output_audio_format:l,user_input_audio_format:f}=a,p=cr(f??"pcm_16000"),g=cr(l);return new i(t,d,p,g)}catch(n){throw t?.close(),n}}close(){this.pendingAudioEvents=[],this.socket.close(1e3,"User ended conversation")}sendMessage(e){this.handleOutgoingMessage(e),this.socket.send(JSON.stringify(e))}addListener(e){let t=this.outputListeners.size>0;if(this.outputListeners.add(e),t||this.pendingAudioEvents.length===0)return;let n=this.pendingAudioEvents;this.pendingAudioEvents=[];for(let r of n)e(r)}removeListener(e){this.outputListeners.delete(e)}handleMessage(e){if(super.handleMessage(e),e.type==="audio"&&e.audio_event.audio_base_64){let t={audio_base_64:e.audio_event.audio_base_64};if(this.outputListeners.size===0){this.pendingAudioEvents.push(t);return}this.outputListeners.forEach(n=>n(t))}}};function jb(i,e){let t=n=>{let r=n.data[0];e.sendMessage({user_audio_chunk:Dr(r.buffer)})};return i.addListener(t),()=>{i.removeListener(t)}}function Bb(i,e){let t=n=>{e.playAudio(wb(n.audio_base_64))};return i.addListener(t),()=>{i.removeListener(t)}}function JE(i){let e="signedUrl"in i&&i.signedUrl,t="orchestrator"in i&&i.orchestrator;if(e&&i.connectionType==="webrtc")throw new Error("signedUrl only supports websocket connections. Remove connectionType or set it to 'websocket'.");if(t&&i.connectionType==="webrtc")throw new Error("Orchestrator sessions only support websocket connections. Remove connectionType or set it to 'websocket'.");if(t&&(e||"conversationToken"in i&&i.conversationToken||i.authorization))throw new Error("The orchestrator option cannot be combined with signedUrl, conversationToken or authorization.");return i.connectionType?i.connectionType:"conversationToken"in i&&i.conversationToken?"webrtc":e||t||i.textOnly?"websocket":"webrtc"}async function Os(i){let e=JE(i);switch(e){case"websocket":return ji.create(i);case"webrtc":return Fi.create(i);default:throw new Error(`Unknown connection type: ${e}`)}}var HE={default:0,android:3e3};function qa(i,e="default"){let t=i??HE;return e==="android"?t.android??t.default:e==="ios"?t.ios??t.default:t.default}async function Va(i){i>0&&await new Promise(e=>setTimeout(e,i))}var KE=3e4,zE=["touchstart","touchend","click"],qi=null,Bi=null,qb=!1;function YE(i){let e=i.createBuffer(1,1,22050),t=i.createBufferSource();t.buffer=e,t.connect(i.destination),t.start(0),i.resume().catch(()=>{})}function QE(){Bi&&clearTimeout(Bi),Bi=setTimeout(()=>{Bi=null,$a()},KE)}function Vb(){Bi&&(clearTimeout(Bi),Bi=null)}function XE(){if(!gn()||qi)return;let i=new AudioContext;YE(i),qi=i,QE()}function $b(){if(!gn()||qb||typeof document>"u")return;qb=!0;let i=()=>{XE()};
307for(let e of zE)document.addEventListener(e,i,!0)}function Wb(){let i=qi;return qi=null,Vb(),i}function $a(){qi&&(qi.close().catch(()=>{}),qi=null,Vb())}function ZE(){return Lb()?"android":gn()?"ios":"default"}async function Gb(){if("wakeLock"in navigator)try{return await navigator.wakeLock.request("screen")}catch{}return null}async function eP(i,e,t){let[n,r]=await Promise.all([Ba.create({...e.inputFormat,preferHeadphonesForIosDevices:i.preferHeadphonesForIosDevices,inputDeviceId:i.inputDeviceId,inputChunkDurationMs:i.inputChunkDurationMs,workletPaths:i.workletPaths,libsampleratePath:i.libsampleratePath}),Ua.create({...e.outputFormat,outputDeviceId:i.outputDeviceId,workletPaths:i.workletPaths,audioContext:t??void 0})]),s=jb(n,e),o=Bb(e,r);return{input:n,output:r,playbackEventTarget:r,detach:async()=>{s(),o()}}}async function tP(i){let e=i.useWakeLock??!0,t=null,n=null,r=null;try{e&&(t=await Gb()),n=await navigator.mediaDevices.getUserMedia({audio:!0});let s=ZE();await Va(qa(i.connectionDelay,s));let o=await Os(i),a;try{o instanceof ji?(r=Wb(),a={connection:o,...await eP(i,o,r)},r=null):($a(),a=Ib(o))}catch(f){throw await r?.close().catch(()=>{}),r=null,o.close(),f}if(n){for(let f of n.getTracks())f.stop();n=null}let d=null;t&&(d=()=>{document.visibilityState==="visible"&&t?.released&&Gb().then(f=>{t=f})},document.addEventListener("visibilitychange",d));let l=a.detach;return{...a,detach:async()=>{await l(),d&&document.removeEventListener("visibilitychange",d);try{await t?.release(),t=null}catch{}}}}catch(s){if(n)for(let o of n.getTracks())o.stop();try{await t?.release(),t=null}catch{}throw $a(),s}}Mb(tP);var Wa=class{audioElements=[];inputAudioContext=null;audioCaptureContext=null;async attachRemoteTrack(e,t){let n=e.attach();if(n.autoplay=!0,n.controls=!1,t&&n.setSinkId)try{await n.setSinkId(t)}catch(r){console.warn("Failed to set output device for new audio element:",r)}n.style.display="none",document.body.appendChild(n),this.audioElements.push(n)}setupInputAnalysis(e){this.inputAudioContext&&(this.inputAudioContext.close().catch(()=>{}),this.inputAudioContext=null);let t=new AudioContext,n=t.createAnalyser();return t.createMediaStreamSource(new MediaStream([e])).connect(n),this.inputAudioContext=t,{volumeProvider:Ui(n,t.sampleRate),analyser:n}}async setupOutputAnalysis(e,t,n,r){this.audioCaptureContext&&(this.audioCaptureContext.close().catch(()=>{}),this.audioCaptureContext=null);let s=new AudioContext;this.audioCaptureContext=s;let o=s.createAnalyser();o.fftSize=2048,o.smoothingTimeConstant=.8;let a=new MediaStream([e.mediaStreamTrack]),d=s.createMediaStreamSource(a),l=Ui(o,s.sampleRate);await ja(s.audioWorklet,r?.rawAudioProcessor);let f=new AudioWorkletNode(s,"rawAudioProcessor");return f.port.postMessage({type:"setFormat",format:t.format,sampleRate:t.sampleRate}),f.port.onmessage=p=>{let[g,b]=p.data;n(g.buffer,b)},d.connect(o),o.connect(f),{volumeProvider:l,analyser:o}}setVolume(e){for(let t of this.audioElements)t.volume=e}async setOutputDevice(e){if(!("setSinkId"in HTMLAudioElement.prototype))throw new Error("setSinkId is not supported in this browser");await Promise.all(this.audioElements.map(async t=>{try{await t.setSinkId(e)}catch(n){throw console.error("Failed to set sink ID for audio element:",n),n}}))}cleanup(){this.inputAudioContext&&(this.inputAudioContext.close().catch(e=>{console.warn("Error closing input audio context:",e)}),this.inputAudioContext=null),this.audioCaptureContext&&(this.audioCaptureContext.close().catch(e=>{console.warn("Error closing audio capture context:",e)}),this.audioCaptureContext=null);for(let e of this.audioElements)e.remove();this.audioElements=[]}};var nP=null;function Jb(i){nP=i}var Hb=Lr("scribeAudioProcessor",`/* 308 * Scribe Audio Processor for converting microphone audio to PCM16 format 309 * Supports resampling for browsers like Firefox that don't support 310 * AudioContext sample rate constraints. 311 * USED BY @elevenlabs/client 312 */ 313 314class ScribeAudioProcessor extends AudioWorkletProcessor { 315 constructor() { 316 super(); 317 this.buffer = []; 318 this.bufferSize = 4096; // Buffer size for optimal chunk transmission 319 320 // Resampling state 321 this.inputSampleRate = null; 322 this.outputSampleRate = null; 323 this.resampleRatio = 1; 324 this.lastSample = 0; 325 this.resampleAccumulator = 0; 326 327 this.port.onmessage = ({ data }) => { 328 if (data.type === "configure") { 329 this.inputSampleRate = data.inputSampleRate; 330 this.outputSampleRate = data.outputSampleRate; 331 if (this.inputSampleRate && this.outputSampleRate) { 332 this.resampleRatio = this.inputSampleRate / this.outputSampleRate; 333 } 334 } 335 }; 336 } 337 338 // Linear interpolation resampling 339 resample(inputData) { 340 if (this.resampleRatio === 1 || !this.inputSampleRate) { 341 return inputData; 342 } 343 344 const outputSamples = []; 345 346 for (let i = 0; i < inputData.length; i++) { 347 const currentSample = inputData[i]; 348 349 // Generate output samples using linear interpolation 350 while (this.resampleAccumulator < 1) { 351 const interpolated = 352 this.lastSample + 353 (currentSample - this.lastSample) * this.resampleAccumulator; 354 outputSamples.push(interpolated); 355 this.resampleAccumulator += this.resampleRatio; 356 } 357 358 this.resampleAccumulator -= 1; 359 this.lastSample = currentSample; 360 } 361 362 return new Float32Array(outputSamples); 363 } 364 365 process(inputs) { 366 const input = inputs[0]; 367 if (input.length > 0) { 368 let channelData = input[0]; // Get first channel (mono) 369 370 // Resample if needed (for Firefox and other browsers that don't 371 // support AudioContext sample rate constraints) 372 if (this.resampleRatio !== 1) { 373 channelData = this.resample(channelData); 374 } 375 376 // Add incoming audio to buffer 377 for (let i = 0; i < channelData.length; i++) { 378 this.buffer.push(channelData[i]); 379 } 380 381 // When buffer reaches threshold, convert and send 382 if (this.buffer.length >= this.bufferSize) { 383 const float32Array = new Float32Array(this.buffer); 384 const int16Array = new Int16Array(float32Array.length); 385 386 // Convert Float32 [-1, 1] to Int16 [-32768, 32767] 387 for (let i = 0; i < float32Array.length; i++) { 388 // Clamp the value to prevent overflow 389 const sample = Math.max(-1, Math.min(1, float32Array[i])); 390 // Scale to PCM16 range 391 int16Array[i] = sample < 0 ? sample * 32768 : sample * 32767; 392 } 393 394 // Send to main thread as transferable ArrayBuffer 395 this.port.postMessage( 396 { 397 audioData: int16Array.buffer 398 }, 399 [int16Array.buffer] 400 ); 401 402 // Clear buffer 403 this.buffer = []; 404 } 405 } 406 407 return true; // Continue processing 408 } 409} 410 411registerProcessor("scribeAudioProcessor", ScribeAudioProcessor); 412 413`);var Yd=16e3,Kb=async(i,e)=>{let t,n,r,s,o=()=>{for(let a of t?.getTracks()??[])a.stop();r?.disconnect(),s?.disconnect(),n?.close()};try{t=await navigator.mediaDevices.getUserMedia({audio:{deviceId:i.deviceId,echoCancellation:i.echoCancellation??!0,noiseSuppression:i.noiseSuppression??!0,autoGainControl:i.autoGainControl??!0,channelCount:i.channelCount??1,sampleRate:{ideal:Yd}}});let[a]=t.getAudioTracks(),d=a?.getSettings().sampleRate;return n=new AudioContext(d?{sampleRate:d}:{}),await Hb(n.audioWorklet,i.workletPaths?.scribeAudioProcessor),r=n.createMediaStreamSource(t),s=new AudioWorkletNode(n,"scribeAudioProcessor"),n.sampleRate!==Yd&&s.port.postMessage({type:"configure",inputSampleRate:n.sampleRate,outputSampleRate:Yd}),s.port.onmessage=l=>{e(Dr(l.data.audioData))},r.connect(s),n.state==="suspended"&&await n.resume(),{mediaStreamTrack:a,cleanup:o}}catch(a){throw o(),a}};var iP="https://api.elevenlabs.io";async function zb({conversationId:i,origin:e,file:t,filename:n}){let r=(e??iP).replace(/^wss:\/\//,"https://").replace(/^ws:\/\//,"http://"),s=n??("name"in t&&typeof t.name=="string"?t.name:`upload.${(t.type||"image/png").split("/").pop()?.split("+")[0]}`),o=new FormData;
vendor: 6,856 bytes, line 413
413o.append("file",t,s);let a=await fetch(`${r}/v1/convai/conversations/${i}/files`,{method:"POST",body:o});if(!a.ok){let f=await ko(a);throw new Error(`Upload failed: ${a.status} ${f}`)}let d=await a.json();Qm(d,"Upload response is not a JSON object");let{file_id:l}=d;if(typeof l!="string"||!l)throw new Error("Upload response is missing a valid file_id");return{fileId:l}}var Yb={reason:"agent",context:{type:"end_call",reason:"Agent ended the call"}};function Qd(i){let{textOnly:e}=i.overrides?.conversation??{},{textOnly:t}=i;return typeof t=="boolean"?(typeof e=="boolean"&&t!==e&&console.warn(`Conflicting textOnly options provided: ${t} via options.textOnly (will be used) and ${e} via options.overrides.conversation.textOnly (will be ignored)`),t):typeof e=="boolean"?e:void 0}var ri=class{options;connection;lastInterruptTimestamp=0;mode="listening";status="connecting";volume=1;currentEventId=1;canSendFeedback=!1;mcpApprovals=new Map;static getFullOptions(e){let t=Qd(e);return{clientTools:{},onConnect:()=>{},onDebug:()=>{},onDisconnect:()=>{},onError:()=>{},onMessage:()=>{},onAudio:()=>{},onModeChange:()=>{},onStatusChange:()=>{},onCanSendFeedbackChange:()=>{},onInterruption:()=>{},onAgentResponseCorrection:()=>{},onAgentTyping:()=>{},onExternalAgentConnected:()=>{},onExternalAgentDisconnected:()=>{},onPing:()=>{},...e,textOnly:t,overrides:{...e.overrides,conversation:{...e.overrides?.conversation,textOnly:t}}}}constructor(e,t){this.options=e,this.connection=t,this.connection.onMessage(this.onMessage),this.connection.onDisconnect(this.endSessionWithDetails),this.connection.onModeChange(n=>this.updateMode(n)),this.connection.onOutgoingMessage(this.onOutgoingMessage)}markConnected(){this.updateStatus("connected")}endSession(){return this.endSessionWithDetails({reason:"user"})}endSessionWithDetails=async e=>{if(!(this.status!=="connected"&&this.status!=="connecting")){this.updateStatus("disconnecting");for(let t of this.mcpApprovals.keys())this.markMCPApprovalStale(t);try{await this.handleEndSession()}finally{this.updateStatus("disconnected"),this.options.onDisconnect&&this.options.onDisconnect(e)}}};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}),this.updateCanSendFeedback())}updateCanSendFeedback(){let e=this.status==="connected";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.currentEventId=e.agent_response_event.event_id,this.options.onMessage&&this.options.onMessage({source:"ai",role:"agent",message:e.agent_response_event.agent_response,event_id:e.agent_response_event.event_id,attachments:e.agent_response_event.attachments})}handleAgentResponseCorrection(e){this.options.onAgentResponseCorrection&&this.options.onAgentResponseCorrection(e.agent_response_correction_event)}handleUserTranscript(e){this.options.onMessage&&this.options.onMessage({source:"user",role:"user",message:e.user_transcription_event.user_transcript,event_id:e.user_transcription_event.event_id})}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})}handlePing(e){this.options.onPing&&this.options.onPing(e.ping_event)}handleContextUsage(e){this.options.onContextUsage&&this.options.onContextUsage(e.context_usage_event)}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){this.options.onUnhandledClientToolCall(e.client_tool_call);return}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){}async handleMCPToolCall(e){let t=e.mcp_tool_call;if(this.options.onMCPToolCall&&this.options.onMCPToolCall(t),t.state!=="awaiting_approval"){this.markMCPApprovalStale(t.tool_call_id);return}let n=this.options.onMCPToolApprovalRequest;if(!n)return;if(this.status==="disconnecting"||this.status==="disconnected"){this.onError(`Ignored an approval request for MCP tool call ${t.tool_call_id}, which arrived after the session ended`,this.mcpApprovalErrorContext(t));return}if(this.mcpApprovals.has(t.tool_call_id)){this.onError(`Ignored a repeated approval request for MCP tool call ${t.tool_call_id}, which has already been handled`,this.mcpApprovalErrorContext(t));return}let r={state:"pending",controller:new AbortController};this.mcpApprovals.set(t.tool_call_id,r);let s;try{s=await n(t,{signal:r.controller.signal})}catch(o){this.onError(`MCP tool approval handler failed: ${o?.message}`,this.mcpApprovalErrorContext(t)),this.settleMCPApproval(t,!1);return}if(typeof s!="boolean"){this.onError(`MCP tool approval handler must resolve to a boolean, received ${typeof s}`,this.mcpApprovalErrorContext(t)),this.settleMCPApproval(t,!1);return}this.settleMCPApproval(t,s)}settleMCPApproval(e,t){let n=this.mcpApprovals.get(e.tool_call_id);if(!n||n.state!=="pending"){this.onError(`Discarded an approval decision for MCP tool call ${e.tool_call_id}, which is no longer awaiting approval`,this.mcpApprovalErrorContext(e));return}n.state="settled",this.sendMCPToolApprovalResult(e.tool_call_id,t)}markMCPApprovalStale(e){let t=this.mcpApprovals.get(e);!t||t.state!=="pending"||(t.state="stale",t.controller.abort())}mcpApprovalErrorContext(e){return{toolCallId:e.tool_call_id,toolName:e.tool_name,serviceId:e.service_id}}
413handleMCPConnectionStatus(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(Yb).catch(t=>{this.onError("Failed to end session after agent end_call",t)}),this.options.onAgentToolResponse?.(e.agent_tool_response)}handleAgentToolResponseFullPayload(e){e.agent_tool_response_full_payload.tool_name==="end_call"&&this.endSessionWithDetails(Yb).catch(t=>{this.onError("Failed to end session after agent end_call",t)}),this.options.onAgentToolResponse?.(e.agent_tool_response_full_payload)}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)}handleAgentReasoningResponsePart(e){this.options.onAgentReasoningResponsePart&&this.options.onAgentReasoningResponsePart(e.reasoning_response_part)}handleRichContent(e){this.options.onRichContent&&this.options.onRichContent(e.rich_content)}handleGuardrailTriggered(e){this.options.onGuardrailTriggered&&this.options.onGuardrailTriggered()}handleAgentTyping(e){this.options.onAgentTyping&&this.options.onAgentTyping(e.agent_typing_event)}handleExternalAgentConnected(e){this.options.onExternalAgentConnected&&this.options.onExternalAgentConnected()}handleExternalAgentDisconnected(e){this.options.onExternalAgentDisconnected&&this.options.onExternalAgentDisconnected()}handleErrorEvent(e){let t=e.error_event,n=t?.error_type,r=t?.message||t?.reason||"Unknown error";if(n==="max_duration_exceeded"){this.endSessionWithDetails({reason:"error",message:r,context:{type:"max_duration_exceeded"}}).catch(s=>{this.onError("Failed to end session after max_duration_exceeded",s)});return}this.onError(`Server error: ${r}`,{errorType:n,code:t?.code,debugMessage:t?.debug_message,details:t?.details})}onMessage=async e=>{switch(this.options.onIncomingEvent?.(e),e.type){case"interruption":{this.handleInterruption(e);return}case"agent_response":{this.handleAgentResponse(e);return}case"agent_response_correction":{this.handleAgentResponseCorrection(e);return}case"user_transcript":{this.handleUserTranscript(e);return}case"internal_tentative_agent_response":{this.handleTentativeAgentResponse(e);return}case"client_tool_call":{try{await this.handleClientToolCall(e)}catch(t){this.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":{this.handleAudio(e);return}case"vad_score":{this.handleVadScore(e);return}case"ping":{this.connection.sendMessage({type:"pong",event_id:e.ping_event.event_id}),this.handlePing(e);return}case"context_usage":{this.handleContextUsage(e);return}case"mcp_tool_call":{try{await this.handleMCPToolCall(e)}catch(t){this.onError(`Unexpected error in MCP tool call handling: ${t instanceof Error?t.message:String(t)}`,{toolCallId:e.mcp_tool_call.tool_call_id,toolName:e.mcp_tool_call.tool_name})}return}case"mcp_connection_status":{this.handleMCPConnectionStatus(e);return}case"agent_tool_request":{this.handleAgentToolRequest(e);return}case"agent_tool_response":{this.handleAgentToolResponse(e);return}case"agent_tool_response_full_payload":{this.handleAgentToolResponseFullPayload(e);return}case"conversation_initiation_metadata":{this.handleConversationMetadata(e);return}case"asr_initiation_metadata":{this.handleAsrInitiationMetadata(e);return}case"agent_chat_response_part":{this.handleAgentChatResponsePart(e);return}case"agent_reasoning_response_part":{this.handleAgentReasoningResponsePart(e);return}case"rich_content":{this.handleRichContent(e);return}case"guardrail_triggered":{this.handleGuardrailTriggered(e);return}case"error":{this.handleErrorEvent(e);return}case"agent_typing":{this.handleAgentTyping(e);return}
413case"external_agent_connected":{this.handleExternalAgentConnected(e);return}case"external_agent_disconnected":{this.handleExternalAgentDisconnected(e);return}default:{this.options.onDebug&&this.options.onDebug(e);return}}};onError(e,t){console.error(e,t),this.options.onError&&this.options.onError(e,t)}onOutgoingMessage=e=>{this.options.onOutgoingEvent?.(e)};getId(){return this.connection.conversationId}isOpen(){return this.status==="connected"}sendFeedback(e,t){if(!this.canSendFeedback){console.warn("Cannot send feedback: the conversation is not connected.");return}this.connection.sendMessage({type:"feedback",score:e!==null?e?"like":"dislike":null,event_id:t??this.currentEventId})}sendContextualUpdate(e,t){this.connection.sendMessage({type:"contextual_update",text:e,...t?.contextId?{context_id:t.contextId}:{}})}sendUserMessage(e,t){this.connection.sendMessage({type:"user_message",text:e,rich_content_id:t?.richContentId??void 0})}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})}sendMultimodalMessage(e){let n=(e.fileIds?.length?e.fileIds:e.fileId?[e.fileId]:[]).map(r=>({type:"file_input",file_id:r}));this.connection.sendMessage({type:"multimodal_message",text:e.text?{type:"user_message",text:e.text}:void 0,file:n[0],files:n.length?n:void 0})}async uploadFile(e){if(this.options.orchestrator)throw new Error("uploadFile is not supported for self-hosted orchestrator sessions.");return zb({conversationId:this.connection.conversationId,origin:this.options.origin,file:e})}};function Qb(){let i=["fetch","WebSocket","TextEncoder","TextDecoder","URL","btoa","atob"];for(let e of i)if(typeof globalThis[e]>"u")throw new Error(`${e} is not available in this environment.`)}var Xb=new Uint8Array(0),Ds=class i extends ri{type="text";setVolume(){throw new Error("setVolume is not supported in text conversations")}setMicMuted(){throw new Error("setMicMuted is not supported in text conversations")}getInputByteFrequencyData(){return Xb}getOutputByteFrequencyData(){return Xb}getInputVolume(){return 0}getOutputVolume(){return 0}static async startSession(e){let t=ri.getFullOptions(e);t.onStatusChange&&t.onStatusChange({status:"connecting"}),t.onCanSendFeedbackChange&&t.onCanSendFeedbackChange({canSendFeedback:!1}),t.onModeChange&&t.onModeChange({mode:"listening"}),t.onCanSendFeedbackChange&&t.onCanSendFeedbackChange({canSendFeedback:!1});let n=null,r=null;try{return await Va(qa(t.connectionDelay)),n=await Os(t),r=new i(t,n),t.onConversationCreated?.(r),r.markConnected(),t.onConnect?.({conversationId:n.conversationId}),r}catch(s){throw r?await r.endSession().catch(()=>{}):(t.onStatusChange?.({status:"disconnected"}),n?.close()),s}}};var Ls=class i extends ri{input;output;playbackEventTarget;cleanUp;type="voice";static async startSession(e){let t=ri.getFullOptions(e);t.onStatusChange&&t.onStatusChange({status:"connecting"}),t.onCanSendFeedbackChange&&t.onCanSendFeedbackChange({canSendFeedback:!1});let n=null,r=null;try{return r=await Rb()(t),n=new i(t,r.connection,r.input,r.output,r.playbackEventTarget,r.detach),t.onConversationCreated?.(n),n.markConnected(),t.onConnect?.({conversationId:r.connection.conversationId}),n}catch(s){throw n?await n.endSession().catch(()=>{}):(r&&await r.detach().catch(()=>{}),t.onStatusChange?.({status:"disconnected"})),s}}inputFrequencyData;outputFrequencyData;handlePlaybackEvent=e=>{e.data.type==="process"&&this.updateMode(e.data.finished?"listening":"speaking")};constructor(e,t,n,r,s,o){super(e,t),this.input=n,this.output=r,this.playbackEventTarget=s,this.cleanUp=o,s?.addListener(this.handlePlaybackEvent)}async handleEndSession(){this.playbackEventTarget?.removeListener(this.handlePlaybackEvent),this.playbackEventTarget=null,await this.cleanUp(),await super.handleEndSession(),await this.input.close(),await this.output.close()}handleInterruption(e){super.handleInterruption(e),this.updateMode("listening"),this.output.interrupt()}handleAudio(e){super.handleAudio(e),e.audio_event.alignment&&this.options.onAudioAlignment&&this.options.onAudioAlignment(e.audio_event.alignment),this.lastInterruptTimestamp<=e.audio_event.event_id&&(e.audio_event.audio_base_64&&this.options.onAudio?.(e.audio_event.audio_base_64),this.currentEventId=e.audio_event.event_id,this.updateCanSendFeedback(),this.updateMode("speaking"))}static FREQUENCY_BIN_COUNT=1024;setMicMuted(e){this.input.setMuted(e).catch(t=>{this.options.onError?.("Failed to set input muted state",t)})}getInputByteFrequencyData(){return this.inputFrequencyData??=new Uint8Array(i.FREQUENCY_BIN_COUNT),this.input.getByteFrequencyData(this.inputFrequencyData),this.inputFrequencyData}
413getOutputByteFrequencyData(){return this.outputFrequencyData??=new Uint8Array(i.FREQUENCY_BIN_COUNT),this.output.getByteFrequencyData(this.outputFrequencyData),this.outputFrequencyData}getInputVolume(){return this.input.getVolume()}getOutputVolume(){return this.output.getVolume()}async changeInputDevice({sampleRate:e,format:t,preferHeadphonesForIosDevices:n,inputDeviceId:r}){try{await this.input.setDevice({inputDeviceId:r,sampleRate:e,format:t,preferHeadphonesForIosDevices:n})}catch(s){throw console.error("Error changing input device",s),s}}async changeOutputDevice({sampleRate:e,format:t,outputDeviceId:n}){try{await this.output.setDevice({outputDeviceId:n,sampleRate:e,format:t})}catch(r){throw console.error("Error changing output device",r),r}}setVolume=({volume:e})=>{let t=Number.isFinite(e)?Math.min(1,Math.max(0,e)):1;this.volume=t,this.output.setVolume(t)}};var Ga;(function(i){i.SESSION_STARTED="session_started",i.PARTIAL_TRANSCRIPT="partial_transcript",i.FINAL_TRANSCRIPT="final_transcript",i.FINAL_TRANSCRIPT_WITH_TIMESTAMPS="final_transcript_with_timestamps",i.COMMITTED_TRANSCRIPT="committed_transcript",i.COMMITTED_TRANSCRIPT_WITH_TIMESTAMPS="committed_transcript_with_timestamps",i.COMMITTED_TRANSCRIPT_ENTITIES="committed_transcript_entities",i.AUTH_ERROR="auth_error",i.ERROR="error",i.OPEN="open",i.CLOSE="close",i.QUOTA_EXCEEDED="quota_exceeded",i.COMMIT_THROTTLED="commit_throttled",i.TRANSCRIBER_ERROR="transcriber_error",i.UNACCEPTED_TERMS="unaccepted_terms",i.RATE_LIMITED="rate_limited",i.INPUT_ERROR="input_error",i.INVALID_REQUEST="invalid_request",i.QUEUE_OVERFLOW="queue_overflow",i.RESOURCE_EXHAUSTED="resource_exhausted",i.SESSION_TIME_LIMIT_EXCEEDED="session_time_limit_exceeded",i.CHUNK_SIZE_EXCEEDED="chunk_size_exceeded",i.INSUFFICIENT_AUDIO_ACTIVITY="insufficient_audio_activity"})(Ga||(Ga={}));var Ja;(function(i){i.PCM_8000="pcm_8000",i.PCM_16000="pcm_16000",i.PCM_22050="pcm_22050",i.PCM_24000="pcm_24000",i.PCM_44100="pcm_44100",i.PCM_48000="pcm_48000",i.ULAW_8000="ulaw_8000"})(Ja||(Ja={}));var Ha;(function(i){i.MANUAL="manual",i.VAD="vad"})(Ha||(Ha={}));var ek={async startSession(i){return Qb(),Qd(i)?Ds.startSession(i):Ls.startSession(i)}};$b();Pb(()=>new Wa);Jb(Kb);function tk(i){i.getTranslation&&console.warn("useTranslations: getTranslation method already exists on controller"),i.getAllTranslations&&console.warn("useTranslations: getAllTranslations method already exists on controller");let e=new Xd(i.element);i.getTranslation=(t,n={})=>e.t(t,n),i.getAllTranslations=t=>e.getNamespace(t),i.locale=e.locale}var Xd=class{constructor(e){this.element=e||document.body,this.locale=this.findLocale(),this.translations=this.loadTranslations()}t(e,t={}){let n=this.getNestedValue(this.translations,e.split("."));return n==null?(console.warn(`Missing JS translation: ${e} for locale ${this.locale}`),e):t.interpolation&&typeof n=="string"?this.interpolate(n,t.interpolation):n}getNamespace(e){return this.getNestedValue(this.translations,e.split("."))||{}}findLocale(){return this.findTranslationElement()?.dataset?.jsLocale||"en"}loadTranslations(){let e=this.findTranslationElement();if(!e?.dataset?.jsTranslations)return console.warn("No JS translations found in DOM. Make sure to include js_translations helper in your view."),{};try{return JSON.parse(e.dataset.jsTranslations)}catch(t){return console.error("Failed to parse JS translations:",t),{}}}findTranslationElement(){let e=this.element.closest("[data-js-translations]");return e||document.querySelector("[data-js-translations]")}getNestedValue(e,t){return t.reduce((n,r)=>n&&n[r]!==void 0?n[r]:void 0,e)}interpolate(e,t){return Object.keys(t).reduce((n,r)=>{let s=new RegExp(`%{${r}}`,"g");return n.replace(s,t[r])},e)}};var xr={listening:{textColor:"text-[#5E5CFF]",glowColor:"#5E5CFF",ringClasses:"ring-2 ring-[#5E5CFF]",modeIndicatorTarget:"modeIndicatorListening"},speaking:{textColor:"text-green-400",glowColor:"#21F051",ringClasses:"ring-2 ring-green-400",modeIndicatorTarget:"modeIndicatorSpeaking"},connecting:{textColor:"text-gray-400",glowColor:"#656565",ringClasses:"ring-2 ring-[#898989]",modeIndicatorTarget:"modeIndicatorConnecting"},muted:{textColor:"text-gray-400",glowColor:"#656565",ringClasses:"ring-2 ring-[#898989]",modeIndicatorTarget:"modeIndicatorMuted"}},yR=Object.values(xr).map(i=>i.modeIndicatorTarget);var xs=class{constructor(e){this.response=e}get statusCode(){return this.response.status}get redirected(){return this.response.redirected}get ok(){return this.response.ok}get unauthenticated(){return this.statusCode===401}get unprocessableEntity(){return this.statusCode===422}get authenticationURL(){return this.response.headers.get("WWW-Authenticate")}get contentType(){return(this.response.headers.get("Content-Type")||"").replace(/;.*$/,"")}get headers(){return this.response.headers}get html(){return this.contentType.match(/^(application|text)\/(html|xhtml\+xml)$/)?this.text:Promise.reject(new Error(`Expected an HTML response but got "${this.contentType}" instead`))}get json(){return this.contentType.match(/^application\/.*json$/)?this.responseJson||(this.responseJson=this.response.json()):Promise.reject(new Error(`Expected a JSON response but got "${this.contentType}" instead`))}get text(){return this.responseText||(this.responseText=this.response.text())}get isTurboStream(){return this.contentType.match(/^text\/vnd\.turbo-stream\.html/)}get isScript(){return this.contentType.match(/\b(?:java|ecma)script\b/)}async renderTurboStream(){if(this.isTurboStream)window.Turbo?await window.Turbo.renderStreamMessage(
413await this.text):console.warn("You must set `window.Turbo = Turbo` to automatically process Turbo Stream events with request.js");else return Promise.reject(new Error(`Expected a Turbo Stream response but got "${this.contentType}" instead`))}async activeScript(){if(this.isScript){let e=document.createElement("script"),t=document.querySelector("meta[name=csp-nonce]");if(t){let n=t.nonce===""?t.content:t.nonce;n&&e.setAttribute("nonce",n)}e.innerHTML=await this.text,document.body.appendChild(e)}else return Promise.reject(new Error(`Expected a Script response but got "${this.contentType}" instead`))}};var Ns=class{static register(e){this.interceptor=e}static get(){return this.interceptor}static reset(){this.interceptor=void 0}};function nk(i){let e=document.cookie?document.cookie.split("; "):[],t=`${encodeURIComponent(i)}=`,n=e.find(r=>r.startsWith(t));if(n){let r=n.split("=").slice(1).join("=");if(r)return decodeURIComponent(r)}}function ik(i){let e={};for(let t in i){let n=i[t];n!==void 0&&(e[t]=n)}return e}function Zd(i){let e=document.head.querySelector(`meta[name="${i}"]`);return e&&e.content}function rk(i){return[...i].reduce((e,[t,n])=>e.concat(typeof n=="string"?[[t,n]]:[]),[])}function sk(i,e){for(let[t,n]of e)n instanceof window.File||(i.has(t)&&!t.includes("[]")?(i.delete(t),i.set(t,n)):i.append(t,n))}var Vi=class{constructor(e,t,n={}){this.method=e,this.options=n,this.originalUrl=t.toString()}async perform(){try{let r=Ns.get();r&&await r(this)}catch(r){console.error(r)}let e=window.Turbo?window.Turbo.fetch:window.fetch,t=new xs(await e(this.url,this.fetchOptions));return t.unauthenticated&&t.authenticationURL?Promise.reject(window.location.href=t.authenticationURL):(t.isScript&&await t.activeScript(),(t.ok||t.unprocessableEntity)&&t.isTurboStream&&await t.renderTurboStream(),t)}addHeader(e,t){let n=this.additionalHeaders;n[e]=t,this.options.headers=n}sameHostname(){if(!this.originalUrl.startsWith("http:")&&!this.originalUrl.startsWith("https:"))return!0;try{return new URL(this.originalUrl).hostname===window.location.hostname}catch{return!0}}get fetchOptions(){return{method:this.method.toUpperCase(),headers:this.headers,body:this.formattedBody,signal:this.signal,credentials:this.credentials,redirect:this.redirect,keepalive:this.keepalive}}get headers(){let e={"X-Requested-With":"XMLHttpRequest","Content-Type":this.contentType,Accept:this.accept};return this.sameHostname()&&(e["X-CSRF-Token"]=this.csrfToken),ik(Object.assign(e,this.additionalHeaders))}get csrfToken(){return nk(Zd("csrf-param"))||Zd("csrf-token")}get contentType(){return this.options.contentType?this.options.contentType:this.body==null||this.body instanceof window.FormData?void 0:this.body instanceof window.File?this.body.type:"application/json"}get accept(){switch(this.responseKind){case"html":return"text/html, application/xhtml+xml";case"turbo-stream":return"text/vnd.turbo-stream.html, text/html, application/xhtml+xml";case"json":return"application/json, application/vnd.api+json";case"script":return"text/javascript, application/javascript";default:return"*/*"}}get body(){return this.options.body}get query(){let e=(this.originalUrl.split("?")[1]||"").split("#")[0],t=new URLSearchParams(e),n=this.options.query;n instanceof window.FormData?n=rk(n):n instanceof window.URLSearchParams?n=n.entries():n=Object.entries(n||{}),sk(t,n);let r=t.toString();return r.length>0?`?${r}`:""}get url(){return this.originalUrl.split("?")[0].split("#")[0]+this.query}get responseKind(){return this.options.responseKind||"html"}get signal(){return this.options.signal}get redirect(){return this.options.redirect||"follow"}get credentials(){return this.options.credentials||"same-origin"}get keepalive(){return this.options.keepalive||!1}get additionalHeaders(){return this.options.headers||{}}get formattedBody(){let e=Object.prototype.toString.call(this.body)==="[object String]";return this.headers["Content-Type"]==="application/json"&&!e?JSON.stringify(this.body):this.body}};async function Nr(i,e){return new Vi("post",i,e).perform()}async function eh(i,e){return new Vi("patch",i,e).perform()}async function th(i,e){return new Vi("delete",i,e).perform()}var ok=1,ck=1e3,ak=2;async function lk(){try{(await navigator.mediaDevices.getUserMedia({audio:!0}
413)).getTracks().forEach(e=>e.stop())}catch(i){let e=new Error("Microphone permission denied");throw e.cause=i,e}}async function uk(i){let e=await Nr(i.tokenCheckUrlValue,{body:JSON.stringify({conversation_id:i.conversationIdValue}),contentType:"application/json",responseKind:"json"});if(!e.ok){let t=await e.json;throw t?.reason==="premium_required"&&(window.location.href=i.subscriptionsUrlValue),new Error(t?.reason||"check_failed")}}async function dk(i){let e;for(let t=0;t<=ok;t++)try{return await sP(i)}catch(n){if(e=n,t<ok){let r=ck*(t+1);await new Promise(s=>setTimeout(s,r))}}throw e}async function sP(i){let e=await Nr(i.callContextUrlValue,{body:JSON.stringify({conversation_id:i.conversationIdValue}),contentType:"application/json",responseKind:"json"});if(!e.ok)throw new Error(`Failed to get call context: ${e.statusCode}`);return e.json}async function hk(i,e,t){try{let n=await eh(i.conversationUrlValue,{body:JSON.stringify({conversation_id:i.conversationIdValue,call_id:e,eleven_labs_conversation_id:t}),contentType:"application/json",responseKind:"json"});return n.ok||i.captureError(new Error(`Failed to register conversation: ${n.statusCode}`),{context:"register_conversation",callId:e,statusCode:n.statusCode}),n.ok}catch(n){return i.captureError(n,{context:"register_conversation",callId:e}),!1}}async function pk(i,e,t,n){if(!e?.message||!t)return;let r=e.role==="agent"?"assistant":"user",s={conversation_id:i.conversationIdValue,call_id:t,body:e.message,role:r};r==="assistant"&&(s.assistant_token=n);try{let o=await Nr(i.audioMessagesUrlValue,{body:JSON.stringify(s),contentType:"application/json",responseKind:"json"});o.ok||i.captureError(new Error(`Failed to save audio message: ${o.statusCode}`),{context:"save_audio_message",role:r,statusCode:o.statusCode})}catch(o){i.captureError(o,{context:"save_audio_message",role:r})}}async function fk(i,e,t={}){let n;for(let r=0;r<=ak;r++){try{let s=await Nr(i.audioMessagesCompletionUrlValue,{body:JSON.stringify({conversation_id:i.conversationIdValue,call_id:e,...t}),contentType:"application/json",responseKind:"json"});if(s.ok)return;n=new Error(`Completion request failed: ${s.statusCode}`)}catch(s){n=s}if(r<ak){let s=ck*(r+1);await new Promise(o=>setTimeout(o,s))}}i.captureError(n,{context:"mark_call_ended",callId:e})}async function mk(i,e){let t=`${i.agentsUrlValue}/${e}?conversation_id=${i.conversationIdValue}`;try{await th(t)}catch(n){i.captureError(n,{context:"delete_agent",agentId:e})}}function gk(i,e,t={}){if(!e)return;let n={conversation_id:i.conversationIdValue,call_id:e,teardown:"beacon"};for(let[a,d]of Object.entries(t))d!=null&&(n[a]=d);let r=document.querySelector("meta[name='csrf-token']")?.content,s=JSON.stringify(n);if(!r){i.captureError(new Error("Missing CSRF token for end-call beacon"),{context:"send_end_call_beacon",callId:e});try{fetch(i.audioMessagesCompletionUrlValue,{method:"POST",keepalive:!0,headers:{"Content-Type":"application/json"},body:s})}catch{}return}let o=new URLSearchParams({...n,authenticity_token:r});navigator.sendBeacon(i.audioMessagesCompletionUrlValue,o)}var nh=[{freq:783.99,delay:0,duration:.14},{freq:659.25,delay:.13,duration:.14},{freq:523.25,delay:.26,duration:.28}];function vk(){try{let i=new window.AudioContext,e=i.currentTime,t=nh[nh.length-1],n=t.delay+t.duration;for(let r of nh)oP(i,r.freq,e+r.delay,r.duration);setTimeout(()=>i.close(),n*1e3)}catch{}}function oP(i,e,t,n){let r=i.createOscillator(),s=i.createGain();r.type="sine",r.frequency.value=e,s.gain.setValueAtTime(.18,t),s.gain.exponentialRampToValueAtTime(.001,t+n),r.connect(s).connect(i.destination),r.start(t),r.stop(t+n)}var Ka=null,za=null,$i=null;function kk(){Fs();try{$i=new window.AudioContext,za=setTimeout(()=>{$i&&(yk($i),Ka=setInterval(()=>yk($i),3500))},1800)}catch{}}function Fs(){za&&(clearTimeout(za),za=null),Ka&&(clearInterval(Ka),Ka=null),$i&&($i.close().catch(()=>{}),$i=null)}function yk(i){if(i.state==="closed")return;let e=i.currentTime;bk(i,440,e,1),bk(i,480,e,1)}function bk(i,e,t,n){let r=i.createOscillator(),s=i.createGain();r.type="sine",r.frequency.value=e,s.gain.setValueAtTime(.001,t),s.gain.linearRampToValueAtTime(.5,t+.08),s.gain.setValueAtTime(.5,t+n-.08),s.gain.linearRampToValueAtTime(.001,t+n),r.connect(s).connect(i.destination),r.start(t),r.stop(t+n)}function kt(i,e){let t=document.getElementById(i);if(t){let n=`${e}`,r=new CustomEvent(n,{bubbles:!0});t.dispatchEvent(r)}}function Sk(i){let e=i.scrollHeight-i.clientHeight,t=null,n=500,r=o=>o*(2-o),s=o=>{t||(t=o);let a=Math.min(1,(o-t)/n),d=r(a),l=i.scrollTop+(e-i.scrollTop)*d;i.scrollTop=l,a<1&&window.requestAnimationFrame(s)};window.requestAnimationFrame(s)}var aP="premium-plus-character-gate",cP="premium-plus-gate:call";function Ya(){let i=document.getElementById(aP);return i?(i.open||i.showModal(),i.dispatchEvent(new CustomEvent(cP)),!0):!1}var lP=3e4,ih=2e3,Qa=class extends bi{static outlets=["call-bar"];static targets=["serverEndCall","lastMinuteWarning"];static values={conversationId:Number,active:{type:Boolean,default:!1},muted:{type:Boolean,default:!1},callContextUrl:String,tokenCheckUrl:String,subscriptionsUrl:String,agentsUrl:String,conversationUrl:String,audioMessagesUrl:String,audioMessagesCompletionUrl:String,isFreeUser:{type:Boolean,default:!1}};#s=null;#n=null;#k=null;#i=null;#o=0;#u=null;#d=null;#h=!1;#m=null;#p=!1;#c=null;#g=null;#r=null;#l=null;connect(){tk(this)}activeValueChanged(i){document.documentElement.classList.toggle("eleven-labs-call-active",i)}serverEndCallTargetConnected(i){if(!this.activeValue)return;let e=i.dataset.reason,t={insufficient_tokens:"audio_input.out_of_tokens",max_duration_exceeded:"audio_input.call_ended_short",abandoned:"audio_input.call_ended_short",moderation_flagged:"audio_input.call_ended_short"};t[e]&&this.endCall({statusKey:t[e]})}disconnect(){Fs(),document.documentElement.classList.remove("eleven-labs-call-active");let i=this.#n||this.#m;i&&(gk(this,i,{client_end_reason:this.#r??void 0,disconnect_source:this.#c?.reason??void 0}),!this.#h&&(this.#T(),this.#S(),this.#f(),this.#b(),this.activeValue=!1))}async startCall(){if(!this.activeValue&&!Ya()){if(this.isFreeUserValue){kt("premiumSubscriptionModal","show-premium-subscription-modal");return}try{await uk(this)}catch{return}this.activeValue=!0,this.mutedValue=!1,this.#p=!1,this.#c=null,this.#g=null,this.#r=null,this.#e("setMicMuted",!1),this.#e("show"),this.#t(this.getTranslation("audio_input.connecting"),"text-gray-400"),this.#a("connecting"),this.#w(),
413kk();try{if(await lk(),!this.activeValue)return;let i=await dk(this);if(!this.activeValue){await mk(this,i.agent_id);return}this.#n=i.call_id,this.#k=i.assistant_token;let e=await ek.startSession({signedUrl:i.signed_url,connectionType:"websocket",onConnect:()=>{Fs(),this.#f(),this.#b(),this.#r=null,this.#v("listening"),this.#C()},onDisconnect:t=>{this.#c=t,this.endCall()},onMessage:t=>{if(!this.#p&&t?.role==="agent"){this.#p=!0;return}pk(this,t,this.#n,this.#k)},onError:(t,n)=>{this.captureError(new Error(t),{elevenLabsContext:n})},onModeChange:({mode:t})=>{this.#v(t)}});if(!this.activeValue){try{await e.endSession()}catch{}return}this.#s=e,this.mutedValue&&this.#s.setMicMuted(!0),hk(this,this.#n,e.getId()).then(t=>{this.#g=t})}catch(i){if(!this.activeValue)return;this.captureError(i);let e=i.message==="Microphone permission denied"?"audio_input.mic_denied":"audio_input.failed_to_connect";this.#t(this.getTranslation(e),"text-[#EE3127]"),this.#f(),this.#r="setup_failed",this.#l=setTimeout(()=>this.endCall(),ih)}}}async endCall({statusKey:i,clientReason:e}={}){if(!this.activeValue||this.#h)return;this.#h=!0,this.#m=this.#n,this.activeValue=!1,Fs();let t=this.#i!==null;this.#f(),this.#b(),await this.#T();let n=this.#_(e??this.#r);this.#r=null,this.#S(),t&&vk(),i?(this.#t(this.getTranslation(i),"text-[#EE3127]"),this.#a("connecting"),setTimeout(()=>this.#e("hide"),ih)):this.#e("hide"),this.#d=null,this.#E();let r=this.#n;this.#n=null,r&&await fk(this,r,n),this.#h=!1,this.#m=null,this.#p=!1,this.#c=null}#_(i){let e=this.#c;return{client_end_reason:i,disconnect_source:e?.reason,ws_close_code:e?.closeCode,ws_close_reason:e?.closeReason,elapsed_secs:this.#o,registration_ok:this.#g,visibility:document.visibilityState}}toggleMic(){this.activeValue&&(this.mutedValue=!this.mutedValue,this.#s?.setMicMuted(this.mutedValue),this.#e("setMicMuted",this.mutedValue),this.mutedValue?(this.#t(this.getTranslation("audio_input.muted"),xr.muted.textColor),this.#a("muted")):this.#d?this.#v(this.#d):(this.#t(this.getTranslation("audio_input.connecting"),"text-gray-400"),this.#a("connecting")))}#e(i,...e){this.hasCallBarOutlet&&this.callBarOutlet[i](...e)}#a(i){this.#e("setMode",i)}#t(i,e){this.#e("setStatus",i,e)}#v(i){if(this.#d=i,this.mutedValue){this.#t(this.getTranslation("audio_input.muted"),xr.muted.textColor),this.#a("muted");return}let e=xr[i]||xr.listening,t=i==="speaking"?this.getTranslation("audio_input.speaking"):this.getTranslation("audio_input.listening");this.#t(t,e.textColor),this.#a(i)}#C(){this.#i&&clearInterval(this.#i),this.#o=0,this.#y(),this.#e("showTimer"),this.#i=setInterval(()=>{this.#o++,this.#y()},1e3)}#S(){this.#i&&(clearInterval(this.#i),this.#i=null),this.#o=0,this.#y(),this.#e("hideTimer")}#y(){let i=Math.floor(this.#o/60),e=this.#o%60;this.#e("updateTimer",`${i}:${String(e).padStart(2,"0")}`)}#w(){this.#u=setTimeout(()=>{this.captureError(new Error("Connection timeout"),{context:"connection_timeout"}),this.#t(this.getTranslation("audio_input.connection_timed_out"),"text-[#EE3127]"),this.#r="connection_timeout",this.#l=setTimeout(()=>this.endCall(),ih)},lP)}#f(){this.#u&&(clearTimeout(this.#u),this.#u=null)}#b(){this.#l&&(clearTimeout(this.#l),this.#l=null)}async#T(){if(!this.#s)return;let i=this.#s;this.#s=null;try{await i.endSession()}catch(e){this.captureError(e,{context:"end_session"})}}#E(){this.hasLastMinuteWarningTarget&&this.lastMinuteWarningTarget.replaceChildren()}};var Us=class{constructor(){this.userAgent=navigator.userAgent.toLowerCase()}isSafariIOS(){return/iphone|ipad|ipod/.test(this.userAgent)&&/safari/.test(this.userAgent)&&!/crios/.test(this.userAgent)&&!/fxios/.test(this.userAgent)&&!/chrome/.test(this.userAgent)}isIOS(){return/iphone|ipad|ipod/.test(this.userAgent)}isAndroid(){return/android/.test(this.userAgent)}isMobile(){return this.isIOS()||this.isAndroid()}isChrome(){return/chrome/.test(this.userAgent)&&!/edge/.test(this.userAgent)}isSafari(){return/safari/.test(this.userAgent)&&!/chrome/.test(this.userAgent)}isPwa(){return window.matchMedia("(display-mode: standalone)").matches}};var js=class{showPhoneCallConfirmationModal(){kt("phoneCallConfirmationModal","show-phone-call-confirmation-modal")}hidePhoneCallConfirmationModal(){kt("phoneCallConfirmationModal","hide-phone-call-confirmation-modal")}showGuestUserModal(){kt("guestUserModal","show-guest-modal")}hideGuestUserModal(){kt("guestUserModal","hide-guest-modal")}showPremiumSubscriptionModal(){kt("premiumSubscriptionModal","show-premium-subscription-modal")}hidePremiumSubscriptionModal(){kt("premiumSubscriptionModal","hide-premium-subscription-modal")}showPhoneCallModal(){kt("phoneCallModal","show-phone-call-modal")}hidePhoneCallModal(){kt("phoneCallModal","hide-phone-call-modal")}showAllowPermissionModal(){kt("allowPermissionModal","show-allow-permission-modal")}hideAllowPermissionModal(){kt("allowPermissionModal","hide-allow-permission-modal")}showBlockPermissionModal(){kt("blockPermissionModal","show-block-permission-modal")}hideBlockPermissionModal(){kt("blockPermissionModal","hide-block-permission-modal")}};var Bk=qT(jk());var jr=class i{static start(e,t){t.classList.add("hidden"),e.classList.remove("hidden"),e.innerHTML="00:00",this.timer=setInterval(()=>{i.updateTimer(e)},1e3)}static stop(e,t){t.classList.remove("hidden"),e.classList.add("hidden"),this.timer&&(clearInterval(this.timer),this.timer=null)}static updateTimer(e){let t=e.innerHTML,[n,r]=t.split(":").map(Number);r++,r===60&&(n++,r=0),e.innerHTML=i.formatTime(n,r)}static formatTime(e,t){return`${e<10?"0"+e:e}:${t<10?"0"+t:t}`}};var nc=class extends bi{static targets=["callButton","callMeButton","timer","ringingText","ringingSound","transcribedText","listeningText","dontShowAgainCheckboxInput","dontShowAgainCheckboxLabel","blockPermissionSafari","blockPermissionOther"];static values={isFreeUser:Boolean,isGuestUser:Boolean,conversationId:Number,callStarted:Boolean,isSubmitting:{type:Boolean,default:!1},contextMessage:String,maxCallDuration:Number,messageHistory:Array,hasUserCheckedDontShowAgain:Boolean};lastPartialTranscript="";incomingChunkTranscript="";userInCall=!1;connect(){this.listeningTextTarget.classList.add("hidden"),this.isFreeUserValue=this.data.get("isFreeUser"),this.isGuestUserValue=this.data.get("isGuestUser"),this.conversationIdValue=this.data.get("conversationId"),this.moderationMessage=this.data.get("moderationMessage"),this.modals=new js,this.hasUserCheckedDontShowAgainValue=this.getHasUserCheckedDontShowAgainValueFromLocalStorage(),this.device=new
413Us().isMobile()?"mobile":"desktop",this.browser=this.detectBrowser(),this.initTimer(),this.setCorrectBrowserModal()}getHasUserCheckedDontShowAgainValueFromLocalStorage(){return localStorage.getItem("hidePhoneCallConfirmationModal")!==null}persistHidePhoneCallConfirmation(){this.hasUserCheckedDontShowAgainValue&&localStorage.setItem("hidePhoneCallConfirmationModal","true")}closePhoneCallConfirmationModal(){this.toggleSubmitButtonState(!0),this.modals.hidePhoneCallConfirmationModal()}toggleSVG(){let i=this.dontShowAgainCheckboxInputTarget.checked,e=this.dontShowAgainCheckboxLabelTarget;i?(e.classList.remove("hidden"),this.dontShowAgainCheckboxInputTarget.classList.add("hidden!")):(e.classList.add("hidden"),this.dontShowAgainCheckboxInputTarget.classList.remove("hidden!")),this.hasUserCheckedDontShowAgainValue=i}toggleCheckbox(i){i.preventDefault();let e=this.dontShowAgainCheckboxInputTarget;e.checked=!e.checked,this.toggleSVG()}phoneCallConfirmationSubmission(){this.closePhoneCallConfirmationModal(),this.persistHidePhoneCallConfirmation(),this.checkAndListenMicrophonePermission()}initTimer(){this.element.addEventListener("start-timer",()=>{this.transcribedTextTarget.classList.add("hidden")}),this.element.addEventListener("stop-timer",()=>{this.callStartedValue=!1,jr.stop(this.timerTarget,this.ringingTextTarget),this.stopRingingSound()})}showButtonLoader(){this.callMeButtonTarget.classList.add("opacity-50"),this.callMeButtonTarget.classList.add("cursor-not-allowed"),this.callMeButtonTarget.classList.remove("cursor-pointer");let i=document.createElement("div");i.setAttribute("data-correction-stop-scroll","true"),i.classList.add("loading-submit-white"),i.classList.add("ml-3"),this.callMeButtonTarget.appendChild(i)}toggleSubmitButtonState(i){this.isSubmittingValue=!i;let e=i?"remove":"add",t=i?"add":"remove";this.callButtonTargets.forEach(n=>{n.classList[e]("opacity-50"),n.classList[e]("cursor-not-allowed"),n.classList[t]("cursor-pointer")})}closeGuestModal(){this.toggleSubmitButtonState(!0),this.modals.hideGuestUserModal()}closePremiumSubscriptionModal(){this.toggleSubmitButtonState(!0),this.modals.hidePremiumSubscriptionModal()}goToSubscriptionsPage(){this.toggleSubmitButtonState(!0);let i="/subscriptions";window.location.href=i}goToRegisterPage(){this.toggleSubmitButtonState(!0);let i="/users/sign_up";window.location.href=i}goToLoginPage(){this.toggleSubmitButtonState(!0);let i="/users/sign_in";window.location.href=i}async getCallContext(){let i={conversation_id:this.conversationIdValue},e=await fetch("/calls/call_context",{method:"POST",headers:{"Content-Type":"application/json","X-CSRF-Token":document.querySelector('meta[name="csrf-token"]').content},body:JSON.stringify(i)});if(e.ok)return await e.json();{this.endPhoneCall();let t=await e.text();throw new Error(`Error: ${e.status} - ${t}`)}}async saveCall(i){let e={conversation_id:this.conversationIdValue,external_call_id:i},t=await fetch("/calls",{method:"POST",headers:{"Content-Type":"application/json","X-CSRF-Token":document.querySelector('meta[name="csrf-token"]').content},body:JSON.stringify(e)});if(t.ok){let n=await t.json();return this.callId=n.call_id,n}else{this.endPhoneCall();let n=await t.text();throw new Error(`Error: ${t.status} - ${n}`)}}async showFeedbackModal(){let e=await(await fetch(`/calls/${this.callId}/end_call`,{method:"POST",headers:{"Content-Type":"application/json",Accept:"text/vnd.turbo-stream.html","X-CSRF-Token":document.querySelector('meta[name="csrf-token"]').content}})).text();Turbo.renderStreamMessage(e)}async deleteAssistant(i){await fetch(`/calls/vapi_assistant/${i}`,{method:"DELETE",headers:{"X-CSRF-Token":document.querySelector('meta[name="csrf-token"]').content}})}async startPhoneCall(){this.modals.hideAllowPermissionModal(),this.modals.hideBlockPermissionModal(),this.userInCall=!0,this.toggleSubmitButtonState(!1),this.modals.showPhoneCallModal(),this.ringingSoundTarget.play();let i=await this.getCallContext();if(this.vapiAssistantId=i.vapi_assistant_id,!this.userInCall)return this.endPhoneCall();this.vapi&&this.vapi.stop(),this.vapi=new Bk.default(i.vapi_token);let e=await this.vapi.start(i.vapi_assistant_id);this.userInCall||this.vapi.stop(),this.vapi.on("message",t=>{this.onVapiMessage(t)}),this.vapi.on("call-start",()=>{this.onVapiCallStart(e.id)}),this.vapi.on("error",t=>{this.endPhoneCall(),this.captureError(t)})}initiatePhoneCall(i){if(this.isSubmittingValue){i.preventDefault();return}if(!Ya()){if(this.isGuestUserValue)return this.modals.showGuestUserModal();if(this.isFreeUserValue)return this.modals.showPremiumSubscriptionModal();this.hasUserCheckedDontShowAgainValue?this.checkAndListenMicrophonePermission():this.modals.showPhoneCallConfirmationModal()}}endPhoneCall(){this.vapi&&this.vapi.stop(),this.permissionStatus&&(this.permissionStatus.onchange=null),this.userInCall=!1,this.transcribedTextTarget.textContent="",this.modals.hidePhoneCallModal(),this.toggleSubmitButtonState(!0),setTimeout(()=>document.activeElement?.blur(),300),this.vapiAssistantId&&this.deleteAssistant(this.vapiAssistantId),this.callId&&this.show
413FeedbackModal(),this.resetCallState()}resetCallState(){this.callStartedValue=!1,this.callId=null,this.userInCall=!1,this.vapiAssistantId=null}onVapiCallStart(i){this.stopRingingSound(),this.callStartedValue=!0,jr.start(this.timerTarget,this.ringingTextTarget),this.userInCall?this.saveCall(i):this.endPhoneCall()}onVapiMessage(i){i.type==="transcript"&&i.role==="assistant"&&i.transcriptType==="final"&&(i.transcript&&this.moderateMessage(i.transcript.toLowerCase())?this.vapi.say(this.moderationMessage,!1):(this.incomingChunkTranscript+=i.transcript,this.lastPartialTranscript=i.transcript,this.transcribedTextTarget.classList.remove("hidden"),this.showTranscript()))}moderateMessage(i){let e=["\\bnewborns?\\b","\\bkindergartners?\\b","\\bpreschoolers?\\b","\\brugrats?\\b","\\bkids?\\b","\\bchild(s|rens?)?\\b","\\bpa?edoph(il(ia|e(s)?|ic)|os?)\\b","\\bni(g)?gers?\\b","\\bneg(g)?ros?\\b","\\brap(e(d|s)?|ing|ists?)\\b","\\bmolest(ed|ing|ers?|s)?\\b","\\bsuicid(s)?\\b","\\bkill\\s?(my|your|him|our|them)sel(f|ves)\\b","\\babus(e(d|s)?|ing)?\\b","\\bpreteens?\\b","\\bteenagers?\\b","\\btweens?\\b","\\badolescents?\\b","\\bunderage\\b","\\bminors?\\b","\\binfants?\\b","\\btoddlers?\\b","\\b(kindergarten|elementary|grade|middle)\\sschoolers?\\b","\\b([0-9]|1[0-7]|eleven|twelve|thirteen|fo(u)?rteen|fifteen|sixteen|seventeen)(\\s)?(year(s)? old|y(?:\\.|\\s|/)?o)\\b","\\b((first|second|third|fourth|fifth|sixth|seventh|eighth|ninth|tenth|eleventh|twel(f|v)th)|(1[0-8]|[0-9])(st|nd|rd|th)?)((-)?\\s?years?)?\\s(grade(r)?|student)\\b",`\\b(under|almost|below|lower tha(n|t))(\\s)?(1[0-8]|[0-9]|eleven|twelve|thirteen|fo(u)?rteen|fifteen|sixteen|seventeen)\\b(?!\\s?(in(ch(es)?)?|people|percent(s)?|dollar(s)?|mile(s)?|person(s)?|second(s)?|minute(s)?|hour(s)?|day(s)?|month(s)?|cm(s)?|time(s)?|f(ee)?t|"|'))`,`\\b(i(?:'?m|\\s?am)|you(?: are|'re|r)|s?he(?:'s| is)|we(?:'re| are)|they(?:'re| are))\\s(three|four|five|six|seven|eight|nine|ten|eleven|twelve|thirteen|fourteen|fifteen|sixteen|seventeen|3|4|5|6|7|8|9|1[0-7])\\b(?!\\s?(in(ch(es)?)?|people|percent(s)?|dollar(s)?|mile(s)?|person(s)?|second(s)?|minute(s)?|hour(s)?|day(s)?|month(s)?|cm(s)?|time(s)?|f(ee)?t|"|'))`];return new RegExp(e.join("|"),"gi").test(i)}showTranscript(){this.index===void 0&&(this.index=0);let i=()=>{this.index<this.incomingChunkTranscript.length&&(this.transcribedTextTarget.textContent+=this.incomingChunkTranscript[this.index],this.index++,this.index===this.incomingChunkTranscript.length&&(this.transcribedTextTarget.textContent+=" "),Sk(this.transcribedTextTarget),setTimeout(i,50))};i()}checkAndListenMicrophonePermission(){this.browser==="safari"||this.isFirefox()?navigator.mediaDevices.getUserMedia({audio:!0}).then(i=>{this.startPhoneCall()}).catch(i=>{this.showBlockPermissionModal()}):navigator.permissions.query({name:"microphone"}).then(i=>{this.permissionStatus=i,i.onchange=()=>{this.handlePermissionChange(i)},this.handlePermissionChange(i)})}handlePermissionChange(i){i.state==="granted"?this.startPhoneCall():i.state==="prompt"?(this.device==="desktop"&&this.modals.showAllowPermissionModal(),navigator.mediaDevices.getUserMedia({audio:!0})):i.state==="denied"&&this.showBlockPermissionModal()}detectBrowser(){let i=navigator.userAgent;return i.includes("Safari")&&!i.includes("Chrome")?"safari":"other"}isFirefox(){return navigator.userAgent.includes("Firefox")}closeAllowPermissionModal(){this.modals.hideAllowPermissionModal()}closeBlockPermissionModal(){this.modals.hideBlockPermissionModal()}showBlockPermissionModal(){this.device==="desktop"&&(this.modals.hideAllowPermissionModal(),this.modals.showBlockPermissionModal())}setCorrectBrowserModal(){this.browser==="safari"&&(this.blockPermissionOtherTarget.classList.add("hidden"),this.blockPermissionSafariTarget.classList.remove("hidden"))}stopRingingSound(){let i=this.ringingSoundTarget;i.pause(),i.currentTime=0}};window.Stimulus.register("eleven-labs-call",Qa);window.Stimulus.register("phone-call",nc);})();
Line numbers count LF bytes from the start of the resource, as the search results do. Vendor segments are library code the classifier recognised; they are stored but not indexed. Bytes are shown as Latin1 characters, one per byte.