@formant/data-sdk 1.80.1 → 1.80.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/data-sdk.cjs.js +1 -1
- package/dist/data-sdk.cjs.js.map +1 -1
- package/dist/data-sdk.es.js +5 -0
- package/dist/data-sdk.es.js.map +1 -1
- package/dist/data-sdk.es6.js +5 -0
- package/dist/data-sdk.umd.js +1 -1
- package/dist/types/data-sdk/src/devices/BaseDevice.d.ts +2 -0
- package/package.json +1 -1
package/dist/data-sdk.umd.js
CHANGED
|
@@ -59,7 +59,7 @@ In order to be iterable, non-array objects must have a [Symbol.iterator]() metho
|
|
|
59
59
|
`))},g.prototype.close=function(){this.transport.close&&this.transport.close(),this.transport.__winstonError&&(this.transport.removeListener("error",this.transport.__winstonError),this.transport.__winstonError=null)}},function(e,t,n){function r(s){return(r=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(g){return typeof g}:function(g){return g&&typeof Symbol=="function"&&g.constructor===Symbol&&g!==Symbol.prototype?"symbol":typeof g})(s)}function o(s,g){for(var l=0;l<g.length;l++){var u=g[l];u.enumerable=u.enumerable||!1,u.configurable=!0,"value"in u&&(u.writable=!0),Object.defineProperty(s,u.key,u)}}e.exports=function(){function s(u){if(function(c,d){if(!(c instanceof d))throw new TypeError("Cannot call a class as a function")}(this,s),!u)throw new Error("Logger is required for profiling.");this.logger=u,this.start=Date.now()}var g,l;return g=s,(l=[{key:"done",value:function(){for(var u=arguments.length,c=new Array(u),d=0;d<u;d++)c[d]=arguments[d];typeof c[c.length-1]=="function"&&(console.warn("Callback function no longer supported as of winston@3.0.0"),c.pop());var B=r(c[c.length-1])==="object"?c.pop():{};return B.level=B.level||"info",B.durationMs=Date.now()-this.start,this.logger.write(B)}}])&&o(g.prototype,l),Object.defineProperty(g,"prototype",{writable:!1}),s}()},function(e,t,n){const r=n(214),{MESSAGE:o}=n(4),s=n(29);function g(l,u){return typeof u=="bigint"?u.toString():u}e.exports=r((l,u)=>{const c=s.configure(u);return l[o]=c(l,u.replacer||g,u.space),l})},function(e,t,n){class r extends Error{constructor(s){super(`Format functions must be synchronous taking a two arguments: (info, opts)
|
|
60
60
|
Found: ${s.toString().split(`
|
|
61
61
|
`)[0]}
|
|
62
|
-
`),Error.captureStackTrace(this,r)}}e.exports=o=>{if(o.length>2)throw new r(o);function s(l={}){this.options=l}function g(l){return new s(l)}return s.prototype.transform=o,g.Format=s,g}},function(e,t,n){function r(g,l){if(!(g instanceof l))throw new TypeError("Cannot call a class as a function")}function o(g,l){for(var u=0;u<l.length;u++){var c=l[u];c.enumerable=c.enumerable||!1,c.configurable=!0,"value"in c&&(c.writable=!0),Object.defineProperty(g,c.key,c)}}var s=n(87);e.exports=function(){function g(){var c=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};r(this,g),this.loggers=new Map,this.options=c}var l,u;return l=g,(u=[{key:"add",value:function(c,d){var B=this;if(!this.loggers.has(c)){var Q=(d=Object.assign({},d||this.options)).transports||this.options.transports;d.transports=Q?Q.slice():[];var U=s(d);U.on("close",function(){return B._delete(c)}),this.loggers.set(c,U)}return this.loggers.get(c)}},{key:"get",value:function(c,d){return this.add(c,d)}},{key:"has",value:function(c){return!!this.loggers.has(c)}},{key:"close",value:function(c){var d=this;if(c)return this._removeLogger(c);this.loggers.forEach(function(B,Q){return d._removeLogger(Q)})}},{key:"_removeLogger",value:function(c){this.loggers.has(c)&&(this.loggers.get(c).close(),this._delete(c))}},{key:"_delete",value:function(c){this.loggers.delete(c)}}])&&o(l.prototype,u),Object.defineProperty(l,"prototype",{writable:!1}),g}()},function(e,t,n){(function(r){const o=n(51),s=/^([A-Za-z0-9+/]{4})*([A-Za-z0-9+/]{4}|[A-Za-z0-9+/]{3}=|[A-Za-z0-9+/]{2}==)$/;e.exports=function(g,l,u,c){let d,B,Q=!1,U=!1;const p=n(93);function f(J){c(l,J)}function b(J,m){let y=`"${l}" ${m}`;throw J&&(y=""+y),B&&(y=`${y}. An example of a valid value would be: ${B}`),new o(y)}const M={convertFromBase64:function(){return f("marking for base64 conversion"),Q=!0,M},default:function(J){if(typeof J=="number")d=J.toString();else if(Array.isArray(J)||typeof J=="object"&&J!==null)d=JSON.stringify(J);else{if(typeof J!="string")throw new o("values passed to default() must be of Number, String, Array, or Object type");d=J}return f(`setting default value to "${d}"`),M},required:function(J){return J===void 0?(f("marked as required"),U=!0):(f("setting required flag to "+J),U=J),M},example:function(J){return B=J,M}};return Object.entries({...p,...u}).forEach(([J,m])=>{M[J]=function(y){return function(){let h=g[l];if(f(`will be read from the environment using "${y.name}" accessor`),h===void 0)if(d===void 0&&U)f("was not found in the environment, but is required to be set"),b(void 0,"is a required variable, but it was not set");else{if(d===void 0)return void f("was not found in the environment, but is not required. returning undefined");f(`was not found in the environment, parsing default value "${d}" instead`),h=d}U&&(f("verifying variable value is not an empty string"),h.trim().length===0&&b(void 0,"is a required variable, but its value was empty")),Q&&(f("verifying variable is a valid base64 string"),h.match(s)||b(h,"should be a valid base64 string if using convertFromBase64"),f("converting from base64 to utf8 string"),h=r.from(h,"base64").toString());const T=[h].concat(Array.prototype.slice.call(arguments));try{f(`passing value "${h}" to "${y.name}" accessor`);const I=y.apply(y,T);return f("parsed successfully, returning "+I),I}catch(I){b(h,I.message)}}}(m)}),M}}).call(this,n(5).Buffer)},function(e,t,n){const r=n(34);e.exports=function(o,s){return s=s||",",o.length?r(o).split(s).filter(Boolean):[]}},function(e,t,n){e.exports=function(r){const o=r.toLowerCase();if(o!=="false"&&o!=="true")throw new Error('should be either "true", "false", "TRUE", or "FALSE"');return o!=="false"}},function(e,t,n){e.exports=function(r){const o=r.toLowerCase();if(["false","0","true","1"].indexOf(o)===-1)throw new Error('should be either "true", "false", "TRUE", "FALSE", 1, or 0');return!(o==="0"||o==="false")}},function(e,t,n){const r=n(94);e.exports=function(o){var s=r(o);if(s>65535)throw new Error("cannot assign a port number greater than 65535");return s}},function(e,t,n){const r=n(34);e.exports=function(o,s){const g=r(o);if(s.indexOf(g)<0)throw new Error(`should be one of [${s.join(", ")}]`);return g}},function(e,t,n){const r=n(53);e.exports=function(o){const s=r(o);if(s>0)throw new Error("should be a negative float");return s}},function(e,t,n){const r=n(53);e.exports=function(o){const s=r(o);if(s<0)throw new Error("should be a positive float");return s}},function(e,t,n){const r=n(52);e.exports=function(o){const s=r(o);if(s>0)throw new Error("should be a negative integer");return s}},function(e,t,n){const r=n(54);e.exports=function(o){var s=r(o);if(!Array.isArray(s))throw new Error("should be a parseable JSON Array");return s}},function(e,t,n){const r=n(54);e.exports=function(o){var s=r(o);if(Array.isArray(s))throw new Error("should be a parseable JSON Object");return s}},function(e,t,n){e.exports=function(r,o){try{RegExp(void 0,o)}catch{throw new Error("invalid regexp flags")}try{return new RegExp(r,o)}catch{throw new Error("should be a valid regexp")}}},function(e,t,n){const r=n(95);e.exports=function(o){return r(o).toString()}},function(e,t,n){const r=n(34),o=/^(?:[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*|"(?:[\u0001-\u0008\u000b\u000c\u000e-\u001f\u0021\u0023-\u005b\u005d-\u007f]|\\[\u0001-\u0009\u000b\u000c\u000e-\u007f])*")@(?:(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?|\[(?:(?:(2(5[0-5]|[0-4][0-9])|1[0-9][0-9]|[1-9]?[0-9]))\.){3}(?:(2(5[0-5]|[0-4][0-9])|1[0-9][0-9]|[1-9]?[0-9])|[a-z0-9-]*[a-z0-9]:(?:[\u0001-\u0008\u000b\u000c\u000e-\u001f\u0021-\u005a\u0053-\u007f]|\\[\u0001-\u0009\u000b\u000c\u000e-\u007f])+)\])$/;e.exports=function(s){const g=r(s);if(!o.test(g))throw new Error("should be a valid email address");return g}},function(e,t,n){e.exports=function(r,o){return function(s,g){o&&o.match(/prod|production/)||r(`env-var (${s}): ${g}`)}}},function(e,t,n){(function(r){(function(){var o,s,g,l,u,c;typeof performance!="undefined"&&performance!==null&&performance.now?e.exports=function(){return performance.now()}:r!=null&&r.hrtime?(e.exports=function(){return(o()-u)/1e6},s=r.hrtime,l=(o=function(){var d;return 1e9*(d=s())[0]+d[1]})(),c=1e9*r.uptime(),u=l-c):Date.now?(e.exports=function(){return Date.now()-g},g=Date.now()):(e.exports=function(){return new Date().getTime()-g},g=new Date().getTime())}).call(this)}).call(this,n(2))},function(e,t,n){(function(r){(function(o){function s(l){if((l=l===void 0?"utf-8":l)!=="utf-8")throw new RangeError("Failed to construct 'TextEncoder': The encoding label provided ('"+l+"') is invalid.")}function g(l,u){if(u=u===void 0?{fatal:!1}:u,(l=l===void 0?"utf-8":l)!=="utf-8")throw new RangeError("Failed to construct 'TextDecoder': The encoding label provided ('"+l+"') is invalid.");if(u.fatal)throw Error("Failed to construct 'TextDecoder': the 'fatal' option is unsupported.")}if(o.TextEncoder&&o.TextDecoder)return!1;Object.defineProperty(s.prototype,"encoding",{value:"utf-8"}),s.prototype.encode=function(l,u){if((u=u===void 0?{stream:!1}:u).stream)throw Error("Failed to encode: the 'stream' option is unsupported.");u=0;for(var c=l.length,d=0,B=Math.max(32,c+(c>>1)+7),Q=new Uint8Array(B>>3<<3);u<c;){var U=l.charCodeAt(u++);if(55296<=U&&56319>=U){if(u<c){var p=l.charCodeAt(u);(64512&p)==56320&&(++u,U=((1023&U)<<10)+(1023&p)+65536)}if(55296<=U&&56319>=U)continue}if(d+4>Q.length&&(B+=8,B=(B*=1+u/l.length*2)>>3<<3,(p=new Uint8Array(B)).set(Q),Q=p),(4294967168&U)==0)Q[d++]=U;else{if(!(4294965248&U))Q[d++]=U>>6&31|192;else if(!(4294901760&U))Q[d++]=U>>12&15|224,Q[d++]=U>>6&63|128;else{if(4292870144&U)continue;Q[d++]=U>>18&7|240,Q[d++]=U>>12&63|128,Q[d++]=U>>6&63|128}Q[d++]=63&U|128}}return Q.slice(0,d)},Object.defineProperty(g.prototype,"encoding",{value:"utf-8"}),Object.defineProperty(g.prototype,"fatal",{value:!1}),Object.defineProperty(g.prototype,"ignoreBOM",{value:!1}),g.prototype.decode=function(l,u){if((u=u===void 0?{stream:!1}:u).stream)throw Error("Failed to decode: the 'stream' option is unsupported.");u=0;for(var c=(l=new Uint8Array(l)).length,d=[];u<c;){var B=l[u++];if(B===0)break;if(!(128&B))d.push(B);else if((224&B)==192){var Q=63&l[u++];d.push((31&B)<<6|Q)}else if((240&B)==224){Q=63&l[u++];var U=63&l[u++];d.push((31&B)<<12|Q<<6|U)}else(248&B)==240&&(65535<(B=(7&B)<<18|(Q=63&l[u++])<<12|(U=63&l[u++])<<6|63&l[u++])&&(B-=65536,d.push(B>>>10&1023|55296),B=56320|1023&B),d.push(B))}return String.fromCharCode.apply(null,d)},o.TextEncoder=s,o.TextDecoder=g})(typeof window!="undefined"?window:r!==void 0?r:this)}).call(this,n(6))},function(e,t,n){n.r(t),n.d(t,"AuthClient",function(){return s}),n.d(t,"RtcSignalingClient",function(){return l}),n.d(t,"Credentials",function(){return C}),n.d(t,"SignalingPromiseClient",function(){return W.SignalingPromiseClient}),n.d(t,"RtcClient",function(){return Pt}),n.d(t,"RtcClientV1",function(){return Dt}),n.d(t,"createRtcStreamMessage",function(){return Ct});var r=n(26),o=function(Re,Z,L,q){return new(L||(L=Promise))(function(ie,ae){function ue(ce){try{fe(q.next(ce))}catch(le){ae(le)}}function Ue(ce){try{fe(q.throw(ce))}catch(le){ae(le)}}function fe(ce){var le;ce.done?ie(ce.value):(le=ce.value,le instanceof L?le:new L(function(me){me(le)})).then(ue,Ue)}fe((q=q.apply(Re,Z||[])).next())})};class s extends r.a{adminSignup(Z,L){return o(this,void 0,void 0,function*(){return yield this.fetch("auth/admin-signup",{token:L,method:"POST",body:Z})})}login(Z){return o(this,void 0,void 0,function*(){return yield this.fetch("auth/login",{method:"POST",body:Z,allowUnsafeRetries:!0})})}loginWithGoogleToken(Z){return o(this,void 0,void 0,function*(){return yield this.fetch("auth/login-google",{method:"POST",body:Z,allowUnsafeRetries:!0})})}refresh(Z,L){return o(this,void 0,void 0,function*(){return yield this.fetch("auth/refresh",{method:"POST",body:{refreshToken:Z,tokenExpirationSeconds:L},allowUnsafeRetries:!0})})}respondToNewPasswordRequiredChallenge(Z){return o(this,void 0,void 0,function*(){return yield this.fetch("auth/respond-to-new-password-required-challenge",{method:"POST",body:Z})})}forgotPassword(Z){return o(this,void 0,void 0,function*(){return yield this.fetch("auth/forgot-password",{method:"POST",body:{email:Z}})})}confirmForgotPassword(Z){return o(this,void 0,void 0,function*(){return yield this.fetch("auth/confirm-forgot-password",{method:"POST",body:Z})})}resendInvitation(Z){return o(this,void 0,void 0,function*(){return yield this.fetch("auth/resend-invitation",{method:"POST",body:{email:Z}})})}changePassword({token:Z,refreshToken:L,currentPassword:q,newPassword:ie}){return o(this,void 0,void 0,function*(){return yield this.fetch("auth/change-password",{token:Z,method:"POST",body:{refreshToken:L,currentPassword:q,newPassword:ie}})})}getDeviceCredentials(Z){return o(this,void 0,void 0,function*(){return yield this.fetch("auth/device-credentials",{token:Z,method:"POST",allowUnsafeRetries:!0})})}impersonate(Z,L){return o(this,void 0,void 0,function*(){return yield this.fetch("auth/impersonate",{token:Z,method:"POST",allowUnsafeRetries:!0,body:{userId:L}})})}createServiceAccount(Z,L,q,ie){return o(this,void 0,void 0,function*(){return yield this.fetch("auth/service-account",{token:Z,method:"POST",allowUnsafeRetries:!0,body:{name:L,roleId:q,tags:ie}})})}getFeatures(Z){return o(this,void 0,void 0,function*(){return(yield this.fetch("auth/features",{token:Z})).features})}checkSso(Z,L){return o(this,void 0,void 0,function*(){return yield this.fetch("auth/check-sso",{method:"POST",body:{email:Z,allowUserAutoCreation:L}})})}loginWithSso(Z,L){return o(this,void 0,void 0,function*(){return yield this.fetch("auth/login-sso",{method:"POST",body:{token:Z,refreshToken:L}})})}}var g=function(Re,Z,L,q){return new(L||(L=Promise))(function(ie,ae){function ue(ce){try{fe(q.next(ce))}catch(le){ae(le)}}function Ue(ce){try{fe(q.throw(ce))}catch(le){ae(le)}}function fe(ce){var le;ce.done?ie(ce.value):(le=ce.value,le instanceof L?le:new L(function(me){me(le)})).then(ue,Ue)}fe((q=q.apply(Re,Z||[])).next())})};class l extends r.a{createPeer(Z,L){return g(this,void 0,void 0,function*(){return yield this.fetch("peers",{token:Z,method:"POST",body:L})})}getPeers(Z){return g(this,void 0,void 0,function*(){return(yield this.fetch("peers",{token:Z})).items})}refreshPeer(Z,L){return g(this,void 0,void 0,function*(){yield this.fetch(`peers/${L}/refresh`,{token:Z,method:"POST",allowUnsafeRetries:!0})})}createSession(Z,L){return g(this,void 0,void 0,function*(){return yield this.fetch("sessions",{token:Z,method:"POST",body:L})})}refreshSession(Z,L){return g(this,void 0,void 0,function*(){yield this.fetch(`sessions/${L}/refresh`,{token:Z,method:"POST",allowUnsafeRetries:!0})})}deleteSession(Z,L){return g(this,void 0,void 0,function*(){yield this.fetch("sessions/"+L,{token:Z,method:"DELETE",allowUnsafeRetries:!0})})}getSessions(Z){return g(this,void 0,void 0,function*(){return(yield this.fetch("sessions",{token:Z})).items})}getIceServers(Z){return g(this,void 0,void 0,function*(){return(yield this.fetch("ice-servers",{token:Z})).items})}addSignals(Z,L,q){return g(this,void 0,void 0,function*(){yield this.fetch(`sessions/${L}/add-signals`,{token:Z,method:"POST",body:q})})}takeSignals(Z,L){return g(this,void 0,void 0,function*(){return(yield this.fetch(`sessions/${L}/take-signals`,{token:Z,method:"POST"})).items})}}var u=n(1),c=n(9),d=n(15),B=n.n(d),Q=n(101),U=n.n(Q),p=n(3),f=n(0),b=function(Re,Z,L,q){return new(L||(L=Promise))(function(ie,ae){function ue(ce){try{fe(q.next(ce))}catch(le){ae(le)}}function Ue(ce){try{fe(q.throw(ce))}catch(le){ae(le)}}function fe(ce){var le;ce.done?ie(ce.value):(le=ce.value,le instanceof L?le:new L(function(me){me(le)})).then(ue,Ue)}fe((q=q.apply(Re,Z||[])).next())})};class M extends class{constructor(Z,L){this.type=Z,this.name=L}}{constructor(Z){super("simple","LogReporter"),this.message=Z}send(Z){return b(this,void 0,void 0,function*(){var L,q;f.a.debug(this.message,(L=Z.reduce((ie,ae)=>Object.assign(Object.assign({},ie),{[ae.name]:ae.stat}),{}),q=ie=>{const{sum:ae,count:ue}=ie,Ue=ae/ue;return Object.assign(Object.assign({},ie),{average:Ue})},Object.keys(L).reduce((ie,ae)=>Object.assign(Object.assign({},ie),{[ae]:q(L[ae])}),{})))})}}const J=/^[a-zA-Z0-9-_.,:?'"()@\/\\#$+ ]{1,255}$/,m=/^[*a-zA-Z0-9-_.,:?'"()@\/\\#$+ ]{1,255}$/;function y(Re,Z=!1){return!!(Re!=null&&Re.match(Z?m:J))}var h=function(Re,Z,L,q){return new(L||(L=Promise))(function(ie,ae){function ue(ce){try{fe(q.next(ce))}catch(le){ae(le)}}function Ue(ce){try{fe(q.throw(ce))}catch(le){ae(le)}}function fe(ce){var le;ce.done?ie(ce.value):(le=ce.value,le instanceof L?le:new L(function(me){me(le)})).then(ue,Ue)}fe((q=q.apply(Re,Z||[])).next())})};function T({func:Re,delay:Z,immediate:L=!1}){let q=!1,ie=setTimeout(function ue(){return h(this,void 0,void 0,function*(){if(q)return;const Ue=new Date().getTime();try{ae=Re(),yield ae}finally{if(!q){const fe=new Date().getTime();ie=setTimeout(ue,Math.max(Z-(fe-Ue),0))}}})},L?0:Z),ae=Promise.resolve();return{stop(){return h(this,void 0,void 0,function*(){q=!0,clearTimeout(ie),yield ae})}}}var I=function(Re,Z,L,q){return new(L||(L=Promise))(function(ie,ae){function ue(ce){try{fe(q.next(ce))}catch(le){ae(le)}}function Ue(ce){try{fe(q.throw(ce))}catch(le){ae(le)}}function fe(ce){var le;ce.done?ie(ce.value):(le=ce.value,le instanceof L?le:new L(function(me){me(le)})).then(ue,Ue)}fe((q=q.apply(Re,Z||[])).next())})};const X=n(231);class F{constructor(Z){this.buffer={},this.reporters=[],this.flushInterval=T({func:()=>this.flushStats(),delay:F.samplePeriodMs}),this.tags=this.filterTags((Z==null?void 0:Z.tags)||{app:p.a,version:p.k,namespace:p.j})}shutdown(){return I(this,void 0,void 0,function*(){yield this.flushInterval.stop(),yield this.flushStats(),yield Object(c.a)(2*u.a.second)})}aggregate(Z,L,q){this.addToBuffer(this.buffer,this.encodeKey({metric:Z,tags:this.filterTags(q||{})}),typeof L=="number"?{min:L,max:L,sum:L,count:1}:L)}increment(Z,L){this.aggregate(Z,1,L)}timer(Z,L,q){return I(this,void 0,void 0,function*(){const ie=X(),ae=yield L(),ue=X();return this.aggregate(Z,ue-ie,q),ae})}registerStatsReporter(Z){this.reporters.push(Z)}setTag(Z,L){const q=this.filterTags({[Z]:L});this.tags=Object.assign(Object.assign({},this.tags),q)}addToBuffer(Z,L,q){if(Z[L]){const{min:ie,max:ae,sum:ue,count:Ue}=Z[L];Z[L]={min:Math.min(ie,q.min),max:Math.max(ae,q.max),sum:ue+q.sum,count:Ue+q.count}}else Z[L]=q}write(Z){return I(this,void 0,void 0,function*(){yield Promise.all(this.reporters.map(L=>I(this,void 0,void 0,function*(){let q;const ie={};switch(L.type){case"simple":for(const[ue,Ue]of Object.entries(Z)){const{metric:fe}=this.decodeKey(ue);this.addToBuffer(ie,this.encodeKey({metric:fe}),Ue)}q=ie;break;case"tagged":q=Z;break;default:(function(ue){throw new Error(`Unreachable type encountered (${ue})`)})(L.type)}const ae=Object.entries(q);if(ae.length>0)return L.send(ae.map(([ue,Ue])=>{const{metric:fe,tags:ce}=this.decodeKey(ue);return{name:fe,tags:Object.assign(Object.assign({},ce),this.tags),stat:Ue}}),F.samplePeriodMs).catch(ue=>{f.a.debug("Failed to write stats to "+L.name,{error:ue})})})))})}flushStats(){return I(this,void 0,void 0,function*(){yield this.write(this.buffer),this.buffer={}})}encodeKey(Z){return B()(Object.assign(Object.assign({},Z),Object.keys(Z.tags||{}).length>0?{tags:Z.tags}:{}))}decodeKey(Z){return JSON.parse(Z)}filterTags(Z){return Object.entries(Z||{}).reduce((L,[q,ie])=>(y(q)&&y(ie)&&(L[q]=ie),L),{})}}F.samplePeriodMs=5*u.a.minute;const R=!!p.d,x=new F;R||["local","on-prem"].includes(p.j)||x.registerStatsReporter(new M("stats"));var w=function(Re,Z,L,q){return new(L||(L=Promise))(function(ie,ae){function ue(ce){try{fe(q.next(ce))}catch(le){ae(le)}}function Ue(ce){try{fe(q.throw(ce))}catch(le){ae(le)}}function fe(ce){var le;ce.done?ie(ce.value):(le=ce.value,le instanceof L?le:new L(function(me){me(le)})).then(ue,Ue)}fe((q=q.apply(Re,Z||[])).next())})};class _ extends class{constructor(Z){this.options=Z,this.cache=new U.a(Object.assign(Object.assign(Object.assign({},Z.dispose||Z.disposeAfter?{ttlAutopurge:!0}:{}),Z),{dispose:(...L)=>{var q;L[2]==="evict"&&x.increment("lru-eviction",{name:Z.name}),(q=Z.dispose)===null||q===void 0||q.call(Z,...L)},disposeAfter:(...L)=>{var q;this.updateStats(),(q=Z.disposeAfter)===null||q===void 0||q.call(Z,...L)}})),this.stringify=Z.fastStringify?JSON.stringify:B.a}set(Z,L,q){const ie=this.stringify(Z);if(!this.cache.set(ie,L,{ttl:q})){const ae=this.cache.sizeCalculation?this.cache.sizeCalculation(L,ie):"unknown";throw Error(`Value too large (${ae} > ${this.cache.max})`)}this.updateStats()}get(Z){const{name:L}=this.options,q=this.stringify(Z),ie=this.cache.getRemainingTTL(q);return ie<=0?x.increment("cache-miss",{name:L}):ie!==1/0&&x.aggregate("cache-item-ttl",ie,{name:L}),this.cache.get(q)}delete(Z){this.cache.delete(this.stringify(Z))}peek(Z){return this.cache.peek(this.stringify(Z))}size(){return this.cache.size}clear(){this.cache.clear()}forEach(Z){this.cache.forEach(Z)}purgeStale(){return this.cache.purgeStale()}updateStats(){const{name:Z}=this.options;x.aggregate("cache-item-count",this.cache.size,{name:Z}),this.cache.calculatedSize!==void 0&&x.aggregate("cache-length",this.cache.calculatedSize,{name:Z})}}{constructor(Z){if(super(Z),this.expireRejectedPromiseValues=Z.expireRejectedPromiseValues===void 0||Z.expireRejectedPromiseValues,this.rejectedPromiseValueTtl=Z.rejectedPromiseValueTtl!==void 0?Z.rejectedPromiseValueTtl:u.a.second,this.rejectedPromiseValueTtl<0)throw new Error("rejectedPromiseValueTtl must not be negative")}set(Z,L,q){super.set(Z,L,q),this.expireRejectedPromiseValues&&L.catch(()=>w(this,void 0,void 0,function*(){yield Object(c.a)(this.rejectedPromiseValueTtl),this.peek(Z)===L&&this.delete(Z)}))}}var j=function(Re,Z,L,q){return new(L||(L=Promise))(function(ie,ae){function ue(ce){try{fe(q.next(ce))}catch(le){ae(le)}}function Ue(ce){try{fe(q.throw(ce))}catch(le){ae(le)}}function fe(ce){var le;ce.done?ie(ce.value):(le=ce.value,le instanceof L?le:new L(function(me){me(le)})).then(ue,Ue)}fe((q=q.apply(Re,Z||[])).next())})};class C{constructor(Z,L,q){this.authClient=Z,this.email=L,this.password=q,this.tokenTtlMs=1*u.a.hour,this.tokenCache=new _({name:"Credentials-tokenCache",max:100,ttl:this.tokenTtlMs-5*u.a.minute,fastStringify:!0})}getToken(){return j(this,void 0,void 0,function*(){let Z=this.tokenCache.get(this.email);return Z||(Z=(()=>j(this,void 0,void 0,function*(){const{authentication:L}=yield this.authClient.login({email:this.email,password:this.password,tokenExpirationSeconds:this.tokenTtlMs/u.a.second});if(!L)throw new Error("User account not verified.");return L.accessToken}))(),this.tokenCache.set(this.email,Z)),Z})}}var W=n(96),v=n(17),D=n(236),A=n(41),E=function(Re,Z,L,q){return new(L||(L=Promise))(function(ie,ae){function ue(ce){try{fe(q.next(ce))}catch(le){ae(le)}}function Ue(ce){try{fe(q.throw(ce))}catch(le){ae(le)}}function fe(ce){var le;ce.done?ie(ce.value):(le=ce.value,le instanceof L?le:new L(function(me){me(le)})).then(ue,Ue)}fe((q=q.apply(Re,Z||[])).next())})};class P extends A.a{constructor(Z){super(Z)}postLanRtcOffer(Z){return E(this,void 0,void 0,function*(){return yield this.fetch("v1/lan-rtc-offer",{method:"POST",body:Z})})}}var G=function(Re,Z,L,q){return new(L||(L=Promise))(function(ie,ae){function ue(ce){try{fe(q.next(ce))}catch(le){ae(le)}}function Ue(ce){try{fe(q.throw(ce))}catch(le){ae(le)}}function fe(ce){var le;ce.done?ie(ce.value):(le=ce.value,le instanceof L?le:new L(function(me){me(le)})).then(ue,Ue)}fe((q=q.apply(Re,Z||[])).next())})};function $(Re){return G(this,void 0,void 0,function*(){return(yield Promise.all(Re.map(Z=>Z.catch(L=>L)))).filter(Z=>Z instanceof Error)})}function ee(Re,Z){if(Re===void 0)throw new Error("Value is undefined"+(Z?": "+Z:""))}function re(Re,Z){if(Re===null)throw new Error("Value is null"+(Z?": "+Z:""))}function O(Re){return ee(Re),Re}function k(Re,Z){const L=Re.reduce((q,ie)=>[...q,...ie.urls],[]).filter(q=>S(q,Z)).sort(q=>V(q,"udp")?-1:0).shift();if(L)return Object.assign(Object.assign({},O(Re.find(q=>q.urls.includes(L)))),{urls:[L]})}function S(Re,Z){switch(Z){case"stun":return/^stuns?:/.test(Re);case"turn":return/^turns?:/.test(Re)}}function V(Re,Z){return Re.endsWith("transport="+Z)}var z=n(10);class K extends Error{constructor(Z,L){super(`Deadline expired after ${Z}ms + ${L}ms`)}}class Y{static withDeadline(Z,L){const q=new Promise((ie,ae)=>{setTimeout(()=>{ae(new K(L,this.grpcCallDeadlineSlopMs))},L+this.grpcCallDeadlineSlopMs)});return Promise.race([Z,q])}}Y.grpcCallDeadlineSlopMs=500*u.a.millisecond;var te=n(27);const oe={ordered:!1,maxPacketLifeTime:300*u.a.millisecond},ge={ordered:!0},Se={ordered:!0},ve={ordered:!1,maxRetransmits:0},ye={ordered:!1,maxRetransmits:0},Je=Re=>"received"in Re&&Re.received!==void 0,Ee=Re=>!("received"in Re)||Re.received===void 0,be=2*u.a.second,we=10*u.a.second;function Ze(Re,Z={}){const L=Array.from(Re.values()),q=L.filter(Je),ie=q.length>0,ae=Math.max(...L.map(le=>le.sent)),ue=Math.max(...q.map(le=>le.received));let Ue;if(ie){const le=Date.now()-ae<=u.a.millisecond?L.length-1:L.length,me=q.length>le?le:q.length,Ve=q.map(Me=>Me.received-Me.sent),{standardDeviation:Ce,mean:xe,jitter:He}=function(Me){const Le=Me.length;if(Le===0)return{mean:NaN,standardDeviation:-1,jitter:NaN};const ze=Me.reduce((Xe,tt)=>Xe+tt,0)/Le,qe=Math.sqrt(Me.map(Xe=>Math.pow(Xe-ze,2)).reduce((Xe,tt)=>Xe+tt)/Le);if(Le===1)return{mean:ze,standardDeviation:qe,jitter:NaN};let yt=0;for(let Xe=1;Xe<Le;Xe++)yt+=Math.abs(Me[Xe]-Me[Xe-1]);return{mean:ze,standardDeviation:qe,jitter:yt/(Le-1)}}(Ve),Ye=L.filter(Me=>Me.sent<ue-be),$e=Ye.filter(Ee),Pe=$e.length===0?0:$e.length/Ye.length;Ue={pingsSent:le,pongsReceived:me,average:xe,standardDeviation:Ce,jitter:He,max:Math.max(...Ve),min:Math.min(...Ve),loss:Pe}}else Ue=null;const{temporalNow:fe=Date.now()}=Z,ce=(ie?ue:fe)-we;return Array.from(Re.entries()).forEach(le=>{const[me,Ve]=le;Ve.sent<ce&&Re.delete(me)}),Ue}function Oe({entityId:Re,streamName:Z,streamType:L}){return`${Re}.${Z}.${L}`}var gt=function(Re,Z,L,q){return new(L||(L=Promise))(function(ie,ae){function ue(ce){try{fe(q.next(ce))}catch(le){ae(le)}}function Ue(ce){try{fe(q.throw(ce))}catch(le){ae(le)}}function fe(ce){var le;ce.done?ie(ce.value):(le=ce.value,le instanceof L?le:new L(function(me){me(le)})).then(ue,Ue)}fe((q=q.apply(Re,Z||[])).next())})};class Tt{constructor(Z,L){this.counts={localSent:new Map,localReceived:new Map,remoteSent:new Map,remoteReceived:new Map},this.sessionId=Z,this.connection=L}updateRemoteMessagesCounts(Z){if(Z.payload.streamsInfo){this.counts.remoteSent=new Map,this.counts.remoteReceived=new Map;for(const L of Z.payload.streamsInfo.items)this.counts.remoteSent.set(L.streamId,L.sentCount),this.counts.remoteReceived.set(L.streamId,L.receivedCount)}}getLocalStreamsInfo(Z){const{localSent:L,localReceived:q}=this.counts;return{items:[...new Set([...L.keys(),...q.keys()])].map(ie=>{var ae,ue;return{streamId:ie,sentCount:(ae=L.get(ie))!==null&&ae!==void 0?ae:0,receivedCount:(ue=q.get(ie))!==null&&ue!==void 0?ue:0}}),timestamp:Z}}incrementLocalSent(Z){const{localSent:L}=this.counts,q=Oe(Z.header.stream);L.set(q,(L.get(q)||0)+1)}incrementLocalReceived(Z){const{localReceived:L}=this.counts,q=Oe(Z.header.stream),ie=L.get(q)||0;if(ie===0){const{streamName:ae,streamType:ue}=Z.header.stream;f.a.debug("RTC client received first message for stream",{streamName:ae,streamType:ue})}L.set(q,ie+1)}uploadMetrics(){return gt(this,void 0,void 0,function*(){const{sessionId:Z}=this,L=yield this.connection.peerConnection.getStats(),q={};L.forEach(ce=>q[ce.id]=ce),f.a.debug("rtc-stats",Object.assign(Object.assign({},q),{sessionId:Z}));const{localSent:ie,localReceived:ae,remoteSent:ue,remoteReceived:Ue}=this.counts,fe=[...new Set([...ie.keys(),...ae.keys()])].reduce((ce,le)=>{const me=ie.get(le),Ve=ae.get(le),Ce=ue.get(le),xe=Ue.get(le);return Object.assign(Object.assign({},ce),{[`local-${le}-sent`]:me,[`local-${le}-received`]:Ve,[`remote-${le}-sent`]:Ce,[`remote-${le}-received`]:xe})},{sessionId:Z});f.a.debug("rtc-message-report",Object.assign({deviceId:this.connection.getRemoteDeviceId()},fe))})}}function Ct(Re,Z,L){return{header:{stream:Re,created:Date.now(),frameId:L||""},payload:Z}}function vt(Re){const Z=Re.localCandidate.candidateType,L=Re.remoteCandidate.candidateType;return Z==="host"&&L==="host"?"local":Z==="relay"||L==="relay"?"TURN":"STUN"}function pt(Re){return new Set(["disconnected","failed","closed"]).has(Re.iceConnectionState)}function _t(Re){switch(Re.header.stream.streamType){case"twist":{const{twist:Z}=Re.payload;if(!Z)throw Error("twist not in payload of RTC message with type twist");return{header:Re.header,payload:{twist:{linear:Object.assign({x:0,y:0,z:0},Z.linear),angular:Object.assign({x:0,y:0,z:0},Z.angular)}}}}case"pose":{const{pose:Z}=Re.payload;if(!Z)throw Error("pose not in payload of RTC message with type pose");return{header:Re.header,payload:{pose:{translation:Object.assign({x:0,y:0,z:0},Z.translation),rotation:Object.assign({x:0,y:0,z:0,w:0},Z.rotation)}}}}case"pose-with-covariance":{const{poseWithCovariance:Z}=Re.payload;if(!Z)throw Error("poseWithCovariance not in payload of RTC message with type pose-with-covariance");const L=new Array(36).fill(0);return Z.covariance.forEach((q,ie)=>{if(ie>=36)throw Error("covariance contains more than 36 elements");L[ie]=q}),{header:Re.header,payload:{poseWithCovariance:{pose:{translation:Object.assign({x:0,y:0,z:0},Z.pose.translation),rotation:Object.assign({x:0,y:0,z:0,w:0},Z.pose.rotation)},covariance:L}}}}case"point":{const{point:Z}=Re.payload;if(!Z)throw Error("point not in payload of RTC message with type point");return{header:Re.header,payload:{point:Object.assign({x:0,y:0,z:0},Z)}}}default:return Re}}var ut=function(Re,Z,L,q){return new(L||(L=Promise))(function(ie,ae){function ue(ce){try{fe(q.next(ce))}catch(le){ae(le)}}function Ue(ce){try{fe(q.throw(ce))}catch(le){ae(le)}}function fe(ce){var le;ce.done?ie(ce.value):(le=ce.value,le instanceof L?le:new L(function(me){me(le)})).then(ue,Ue)}fe((q=q.apply(Re,Z||[])).next())})};class Vt{get peerConnection(){return re(this._peerConnection,"RTCPeerConnection is closed!"),this._peerConnection}constructor(Z,L,q,ie){this.iceServers=L,this.config=q,this.dataChannelNotifier=ie,this.connectTimeoutMs=20*u.a.second,this.iceGatheringTimeoutMs=3*u.a.second,this.pingUpdateTimeoutMs=1*u.a.second,this.pingV2UpdateTimeoutMs=250*u.a.millisecond,this.pingV2MetricsGatherTimeoutMs=1*u.a.second,this.streamsInfoUpdateTimeoutMs=2*u.a.second,this.reassemblyTimeoutMs=500*u.a.millisecond,this.reassemblyTableCleanupMs=1*u.a.second,this.heartbeatTimeoutMs=20*u.a.millisecond,this._peerConnection=null,this.heartbeatChannel=null,this.latestTtlStreamChannel=null,this.reliableStreamChannel=null,this.latestReliableStreamChannel=null,this.latestTryOnceStreamChannel=null,this.streamLatestTimestamp=new Map,this.reassemblyTable=new Map,this.reassemblyTableLastTimestamp=new Map,this.closeCalled=!1,this.gotOffer=!1,this.hasIceCandidate=!1,this.pingV2Map=new Map,this.sendPingV2=()=>{const{latestTryOnceStreamChannel:ue}=this;if(!ue)return;const Ue=new Date().getTime(),fe=Object(D.a)();this.sendSystemMessage(ue,{type:"ping-v2",payload:{timestamp:Ue,id:fe}}),this.pingV2Map.set(fe,{sent:Ue})},this.gatherPingV2Metrics=()=>{const ue=Ze(this.pingV2Map);if(ue){const Ue=this.getRemoteDeviceId();this.pingInfo=ue,x.aggregate("rtc-ping-average",ue.average,Object.assign({},Ue?{deviceId:Ue}:{})),x.aggregate("rtc-ping-loss",ue.loss,Object.assign({},Ue?{deviceId:Ue}:{})),x.aggregate("rtc-jitter",ue.jitter,Object.assign({},Ue?{deviceId:Ue}:{}))}},this._peerConnection=Z;const{isOffer:ae}=q.baseConfig;ae?this.initializeChannels(Z):Z.ondatachannel=ue=>{switch(ue.channel.label){case"stream.latest-ttl":this.latestTtlStreamChannel=ue.channel;break;case"stream.reliable":this.reliableStreamChannel=ue.channel;break;case"stream.latest-reliable":this.latestReliableStreamChannel=ue.channel;break;case"stream.latest-try-once":this.latestTryOnceStreamChannel=ue.channel;break;case"heartbeat":return void(this.heartbeatChannel=ue.channel);default:return void this.dataChannelNotifier(ue.channel)}this.setupChannel(ue.channel)},this.pingUpdateTimeout=setInterval(()=>{const{reliableStreamChannel:ue}=this;ue&&this.sendSystemMessage(ue,{type:"ping"})},this.pingUpdateTimeoutMs),this.pingV2UpdateTimeout=setInterval(this.sendPingV2,this.pingV2UpdateTimeoutMs),this.pingV2MetricsGatherTimeout=setInterval(this.gatherPingV2Metrics,this.pingV2MetricsGatherTimeoutMs),this.streamsInfoUpdateTimeout=setInterval(()=>{const{latestTtlStreamChannel:ue}=this;ue&&this.sendSystemMessage(ue,{type:"streams-info"})},this.streamsInfoUpdateTimeoutMs),this.reassemblyTableCleanupTimeout=setInterval(()=>{const ue=new Date().getTime();this.reassemblyTableLastTimestamp.forEach((Ue,fe,ce)=>{ue>fe+this.reassemblyTimeoutMs&&this.reassemblyTable.delete(Ue)})},this.reassemblyTableCleanupMs),this.heartbeatTimeout=setInterval(()=>{const{heartbeatChannel:ue}=this;ue&&ue.readyState==="open"&&ue.send(new Uint8Array([1]))},this.heartbeatTimeoutMs)}handleSignal(Z){return ut(this,void 0,void 0,function*(){const{peerConnection:L}=this,{track:q}=this.config.baseConfig,ie=(()=>{try{return JSON.parse(Z.getPayload())}catch{return}})();if(!ie)return void f.a.error("Received unparseable signal.");f.a.debug("Handling signal",{description:ie});const{sdp:ae,type:ue}=ie;if(!ae||!ue)return void f.a.warn("Received non-SDP signal");const{signalingState:Ue,connectionState:fe}=L;if(Ue!=="stable"||fe!=="connected")if(L.remoteDescription)f.a.warn("Received SDP after remote description was set: "+ae);else{if(ue==="offer"){if(Ue!=="stable")return void f.a.warn("Received offer SDP when signaling is ongoing.");yield L.setRemoteDescription(ie);const ce=yield L.createAnswer();yield L.setLocalDescription(ce);const le=Z.clone();return q==null||q("Answer Received",le),le.setPayload(JSON.stringify(ce)),le.setReceiverId(Z.getSenderId()),le.setSenderId(Z.getReceiverId()),le}if(ue==="answer"){if(Ue==="stable")return void f.a.warn("Received answer SDP when signaling hasn't started.");yield L.setRemoteDescription(ie)}}else f.a.warn("Received SDP when already connected: "+ae)})}send(Z,L){const q=this.getChannelFromLabel(L.channelLabel);q?this.sendOnChannel(q,Z):f.a.warn("Send called with unexpected channel label",{channelLabel:L.channelLabel})}controlRemoteStream(Z){var L;this.sendSystemMessage((re(L=this.reliableStreamChannel),L),{type:"stream-control",streamControl:Z})}isActive(){return new Set(["new","checking","connected","completed"]).has(this.peerConnection.iceConnectionState)||this.isReady()}isReady(){const{reliableStreamChannel:Z,latestTtlStreamChannel:L,latestTryOnceStreamChannel:q,latestReliableStreamChannel:ie}=this;return(Z==null?void 0:Z.readyState)==="open"&&(L==null?void 0:L.readyState)==="open"&&(q==null?void 0:q.readyState)==="open"&&(ie==null?void 0:ie.readyState)==="open"}close(){var Z,L,q,ie,ae,ue,Ue;return ut(this,void 0,void 0,function*(){this.closeCalled||(this.closeCalled=!0,yield(Z=this.sessionMetrics)===null||Z===void 0?void 0:Z.uploadMetrics(),Ft(this.pingUpdateTimeout),Ft(this.pingV2UpdateTimeout),Ft(this.pingV2MetricsGatherTimeout),Ft(this.reassemblyTableCleanupTimeout),Ft(this.streamsInfoUpdateTimeout),Ft(this.heartbeatTimeout),(L=this._peerConnection)===null||L===void 0||L.close(),(q=this.heartbeatChannel)===null||q===void 0||q.close(),(ie=this.latestReliableStreamChannel)===null||ie===void 0||ie.close(),(ae=this.latestTryOnceStreamChannel)===null||ae===void 0||ae.close(),(ue=this.latestTtlStreamChannel)===null||ue===void 0||ue.close(),(Ue=this.reliableStreamChannel)===null||Ue===void 0||Ue.close(),this._peerConnection=null,this.heartbeatChannel=null,this.latestReliableStreamChannel=null,this.latestTryOnceStreamChannel=null,this.latestTtlStreamChannel=null,this.reliableStreamChannel=null)})}getPing(){return this.pingTimeMs}getPingInfo(){return this.pingInfo}getLastMessageTimestamp(){return this.lastMessageTimestamp}getSessionCreatedTimestamp(){var Z;return(Z=this.config.remoteConfig)===null||Z===void 0?void 0:Z.sessionCreatedTimestamp}setSessionCreatedTimestamp(Z){this.config.remoteConfig&&(this.config.remoteConfig.sessionCreatedTimestamp=Z)}getSessionId(){var Z;return(Z=this.config.remoteConfig)===null||Z===void 0?void 0:Z.sessionId}setSessionId(Z){this.config.remoteConfig&&(this.config.remoteConfig.sessionId=Z,this.sessionMetrics=new Tt(Z,this))}getRemotePeerId(){return this.config.baseConfig.remotePeerId}getRemoteDeviceId(){var Z;return(Z=this.config.baseConfig)===null||Z===void 0?void 0:Z.remoteDeviceId}setRemoteDeviceId(Z){this.config.baseConfig.remoteDeviceId=Z}getSessionMetricsMessageCounts(){var Z;return(Z=this.sessionMetrics)===null||Z===void 0?void 0:Z.counts}getConnectionStatsInfo(){return ut(this,void 0,void 0,function*(){const{peerConnection:Z}=this;if(!Z)return;const L=yield Z.getStats(null),q=[];L.forEach(fe=>{q.push(fe)});const ie=q.find(fe=>fe.type==="transport");if(!ie)return;const ae=q.find(fe=>(fe.type==="candidate-pair"||fe.type==="candidatepair")&&fe.id===ie.selectedCandidatePairId);if(!ae)return;const ue=q.find(fe=>fe.id===ae.localCandidateId),Ue=q.find(fe=>fe.id===ae.remoteCandidateId);return ue&&Ue&&(ue.address=ue.address||ue.ip,Ue.address=Ue.address||Ue.ip,ue.address!==void 0&&Ue.address!==void 0)?{transport:ie,localCandidate:ue,remoteCandidate:Ue,candidatePair:ae}:void 0})}initializeChannels(Z){this.heartbeatChannel=Z.createDataChannel("heartbeat",ye),this.heartbeatChannel.binaryType="arraybuffer",this.latestTtlStreamChannel=Z.createDataChannel("stream.latest-ttl",oe),this.latestTtlStreamChannel.binaryType="arraybuffer",this.reliableStreamChannel=Z.createDataChannel("stream.reliable",ge),this.reliableStreamChannel.binaryType="arraybuffer",this.latestReliableStreamChannel=Z.createDataChannel("stream.latest-reliable",Se),this.latestReliableStreamChannel.binaryType="arraybuffer",this.latestTryOnceStreamChannel=Z.createDataChannel("stream.latest-try-once",ve),this.latestTryOnceStreamChannel.binaryType="arraybuffer",this.setupChannel(this.latestTtlStreamChannel),this.setupChannel(this.reliableStreamChannel),this.setupChannel(this.latestReliableStreamChannel),this.setupChannel(this.latestTryOnceStreamChannel)}getOffer(){var Z,L;return ut(this,void 0,void 0,function*(){const{gotOffer:q}=this,{peerConnection:ie,config:ae}=this;if(this.config.baseConfig.isLan)throw new Error('"getOffer" method can only be called with internet connections. LAN connections should call the "getLanOffer" method.');const ue=(Z=this.config.remoteConfig)===null||Z===void 0?void 0:Z.sessionId;if(q)return void f.a.debug("Failed to generate offer because gotOffer was already called.");if(this.gotOffer=!0,pt(this.peerConnection))return void f.a.debug("Failed to generate offer because the peer connection was inactive.");const Ue=ae.baseConfig.track;ie.onicecandidate=()=>{this.hasIceCandidate=!0},ie.oniceconnectionstatechange=()=>ut(this,void 0,void 0,function*(){const Ce=ie.iceConnectionState;if(Ce==="connected"||Ce==="completed"){const xe=yield this.getConnectionStatsInfo(),He=xe?vt(xe):void 0;f.a.info("ICE connection state changed to "+Ce,{sessionId:ue,connectionStatsInfo:xe,iceMode:He}),Ue==null||Ue("ICE connection state change",{iceConnectionState:Ce,sessionId:ue,connectionStatsInfo:xe,iceMode:He})}}),yield ie.setLocalDescription(yield ie.createOffer());const fe=ie.getConfiguration?ie.getConfiguration().iceTransportPolicy:"all",ce=new Date().getTime();for(;;){const Ce=new Date().getTime()-ce;if(Ce>this.connectTimeoutMs)return void f.a.debug("Failed to generate offer because ICE gathering timed out.");if(Ce>this.iceGatheringTimeoutMs&&this.hasIceCandidate){f.a.debug("ICE gathering partially completed; proceeding",{iceTransportPolicy:fe,waitTime:Ce}),Ue==null||Ue("ICE gathering partially completed",{sessionId:ue,iceTransportPolicy:fe,waitTime:Ce});break}if(ie.iceGatheringState==="complete"){f.a.debug("ICE gathering complete",{iceTransportPolicy:fe,waitTime:Ce}),Ue==null||Ue("ICE gathering completed",{sessionId:ue,iceTransportPolicy:fe,waitTime:Ce});break}yield Object(c.a)(.1*u.a.second)}const le=(L=this.iceServers)!==null&&L!==void 0?L:[];for(const Ce of le)"credentialType"in Ce&&(Ce.credentialType=void 0);const me=JSON.stringify(le),Ve=new z.Signal;return Ve.setPayload(JSON.stringify(ie.localDescription)),Ve.setSenderId(this.config.baseConfig.localPeerId),Ve.setReceiverId(this.config.baseConfig.remotePeerId),Ve.setIceServers(me),Ve.setIceTransportPolicy(fe!=null?fe:"all"),this.config.baseConfig.sessionType!==void 0?Ve.setSessionType(this.config.baseConfig.sessionType):Ve.setSessionType(z.SessionType.TELEOP),f.a.debug("Sending offer signal with description",{description:Ve.getPayload()}),Ve})}getLanOffer(){return ut(this,void 0,void 0,function*(){const{peerConnection:Z,gotOffer:L}=this;if(!this.config.baseConfig.isLan)throw new Error('"getLanOffer" method can only be used with LAN connections. Internet connections should call the "getOffer" method.');if(L)return void f.a.debug("Failed to generate offer because gotOffer was already called.");if(this.gotOffer=!0,pt(this.peerConnection))return void f.a.debug("Failed to generate offer because the peer connection was inactive.");yield Z.setLocalDescription(yield Z.createOffer());const q=new Date().getTime();for(;;){if(new Date().getTime()-q>this.iceGatheringTimeoutMs)return void f.a.debug("Failed to generate offer because ICE gathering timed out.");if(Z.iceGatheringState==="complete")break;yield Object(c.a)(.1*u.a.second)}const ie=Z.localDescription;if(ie)return f.a.debug("Sending LAN offer signal with description",{description:ie}),ie;f.a.error("Failed to generate LAN offer description")})}handleLanAnswer(Z){return ut(this,void 0,void 0,function*(){const{peerConnection:L}=this;if(!this.config.baseConfig.isLan)throw new Error('"handleLanAnswer" method can only be used with LAN connections. Internet connections should call the "handleSignal" method.');yield L.setRemoteDescription(Z)})}getChannelFromLabel(Z){switch(Z){case"stream.latest-ttl":return this.latestTtlStreamChannel;case"stream.reliable":return this.reliableStreamChannel;case"stream.latest-reliable":return this.latestReliableStreamChannel;case"stream.latest-try-once":return this.latestTryOnceStreamChannel}}sendOnChannel(Z,L){var q;let ie;try{ie=Object(te.encode)(JSON.stringify(L))}catch(ae){return void f.a.warn("Failed to encode RTC message",{error:ae})}try{Z.send(ie),(q=this.sessionMetrics)===null||q===void 0||q.incrementLocalSent(L)}catch(ae){f.a.warn("Failed to send message to channel",{error:ae,channel:Z.label})}}channelNotRecognized(Z){return Z!==this.latestTtlStreamChannel&&Z!==this.latestReliableStreamChannel&&Z!==this.latestTryOnceStreamChannel&&Z!==this.reliableStreamChannel}setupChannel(Z){Z.onmessage=L=>{if(this.channelNotRecognized(Z))return void f.a.warn("Received message on unrecognized data channel.");let q;try{q=JSON.parse(Object(te.decode)(L.data))}catch(ie){return void f.a.warn("Received unparseable message on RTC stream data channel",{error:ie,channel:Z.label})}q.communicationType==="message-chunk"?this.receiveChannelMessageChunk(Z,q):this.receiveChannelMessage(Z,q)},Z.onerror=L=>{f.a.warn("Channel error: "+L.error,{error:L.error,sessionId:this.getSessionId(),channelLabel:Z.label})},Z.onopen=()=>{f.a.debug("Channel opened",{sessionId:this.getSessionId(),channelLabel:Z.label})},Z.onclose=()=>{const L={bufferedAmount:Z.bufferedAmount,sessionId:this.getSessionId(),channelLabel:Z.label};this.closeCalled===!1?f.a.debug("Unexpected channel closed",L):f.a.debug("Channel closed",L)}}receiveChannelMessage(Z,L){var q;const{config:ie}=this,{remotePeerId:ae}=this.config.baseConfig;this.lastMessageTimestamp=new Date().getTime(),L=_t(L),(q=this.sessionMetrics)===null||q===void 0||q.incrementLocalReceived(L),!this.handleSystemMessage(Z,L)&&((Z===this.latestTryOnceStreamChannel||Z===this.latestTtlStreamChannel||Z===this.latestReliableStreamChannel)&&!this.isLatestMessage(L)||ie.baseConfig.receive(ae,L))}receiveChannelMessageChunk(Z,L){const q=this.reassemblyTable.get(L.id)||[];if(q.push(L),q.length===L.total){const ie=function(ae){const ue=ae.sort((Ue,fe)=>Ue.seq<fe.seq?-1:1).map(Ue=>Ue.part).reduce((Ue,fe)=>Ue+fe);try{return JSON.parse(ue)}catch{return void f.a.warn("Could not reassemble RTC message chunks")}}(q);return ie&&this.receiveChannelMessage(Z,ie),void this.reassemblyTable.delete(L.id)}this.reassemblyTable.set(L.id,q),this.reassemblyTableLastTimestamp.set(L.id,new Date().getTime())}handleSystemMessage(Z,L){var q,ie;const{config:ae}=this,{baseConfig:ue}=ae,{remotePeerId:Ue,remoteDeviceId:fe}=ue;switch(L.header.stream.streamType){case"ping":return this.sendSystemMessage(Z,{type:"pong",timestamp:O(L.payload.ping)}),!0;case"pong":{const ce=new Date().getTime()-O(L.payload.pong);return this.pingTimeMs=ce,x.aggregate("rtc-ping-time",ce,Object.assign({},fe?{deviceId:fe}:{})),!0}case"ping-v2":return this.sendPingV2(),!0;case"pong-v2":{const ce=O(L.payload.pongV2),le=this.pingV2Map.get(ce.id);return(le==null?void 0:le.sent)!==ce.timestamp&&f.a.warn("Pong timestamp doesn't match stored value",{currentEntry:le,pong:ce}),this.pingV2Map.set(ce.id,{sent:ce.timestamp,received:new Date().getTime()}),!0}case"streams-info":{const{sessionMetrics:ce}=this,le=(q=L.payload.streamsInfo)===null||q===void 0?void 0:q.timestamp;return!!le&&(ce==null||ce.updateRemoteMessagesCounts(L),(ie=ue.onStreamsInfoUpdate)===null||ie===void 0||ie.call(ue,Ue,le),!0)}case"stream-control":return!0;default:return!1}}sendSystemMessage(Z,L){var q;const{localUserId:ie,localPeerId:ae}=this.config.baseConfig;if(Z.readyState!=="open")return;const ue={entityId:ie!=null?ie:ae,streamName:"$."+L.type,streamType:L.type};let Ue;switch(L.type){case"ping":Ue={ping:new Date().getTime()};break;case"pong":Ue={pong:L.timestamp};break;case"ping-v2":Ue={pingV2:L.payload};break;case"pong-v2":Ue={pongV2:L.payload};break;case"stream-control":Ue={streamControl:L.streamControl};break;case"streams-info":Ue={streamsInfo:(q=this.sessionMetrics)===null||q===void 0?void 0:q.getLocalStreamsInfo(new Date().getTime())}}this.sendOnChannel(Z,Ct(ue,Ue))}isLatestMessage(Z){const L=Oe(Z.header.stream),q=(this.streamLatestTimestamp.get(L)||0)<=Z.header.created;return q&&this.streamLatestTimestamp.set(L,Z.header.created),q}}function Ft(Re){Re&&clearInterval(Re)}function Nt(){f.a.debug("forceGarbageCollection() triggered"),queueMicrotask(()=>{let Re=document.createElement("img");Re.src=window.URL.createObjectURL(new Blob([new ArrayBuffer(5e7)])),Re.onerror=function(){window.URL.revokeObjectURL(this.src),Re=null}})}function jt(Re){try{return Re instanceof Error?`${Re.name}: ${Re.message}`:typeof Re=="object"?JSON.stringify(Re):String(Re)}catch{return"Unknown error"}}function ht(Re){var Z,L;return{userId:(Z=Re.getUserId())===null||Z===void 0?void 0:Z.getValue(),deviceId:(L=Re.getDeviceId())===null||L===void 0?void 0:L.getValue(),organizationId:Re.getOrganizationId(),id:Re.getPeerId(),capabilities:[],capabilitySet:{}}}var De=function(Re,Z,L,q){return new(L||(L=Promise))(function(ie,ae){function ue(ce){try{fe(q.next(ce))}catch(le){ae(le)}}function Ue(ce){try{fe(q.throw(ce))}catch(le){ae(le)}}function fe(ce){var le;ce.done?ie(ce.value):(le=ce.value,le instanceof L?le:new L(function(me){me(le)})).then(ue,Ue)}fe((q=q.apply(Re,Z||[])).next())})};const Qt=Re=>Re.map(Z=>Object.assign(Object.assign(Object.assign({},Z),Z.username?{username:"<REDACTED>"}:null),Z.credential?{credential:"<REDACTED>"}:null));class Pt{constructor(Z){this.config=Z,this.grpcCallDeadline=5*u.a.second,this.refreshIntervalDelayMs=2*u.a.second,this.iceServersTtl=30*u.a.minute,this.connections=[],this.localConnections=[],this.isConnectionInitiator=new WeakSet,this.isOutgoingConnection=new Set,this.peerDataChannelListeners=[],this.rtcInstancesConstructed=0,this.statsLoopsExecuted=0;const{refreshIntervalDelayMs:L}=this;this.refreshInterval=T({func:()=>De(this,void 0,void 0,function*(){try{yield this.update()}catch(q){f.a.warn("RTC refresh failed",{error:q})}}),delay:L,immediate:!0})}send(Z,L,q){const ie=this.getActiveConnection(Z);ie?ie.isReady()?ie.send(L,q):f.a.warn("Send called with unready connection."):f.a.warn("Send called with no connection.")}controlRemoteStream(Z,L){const q=this.getActiveConnection(Z);q?q.isReady()?q.controlRemoteStream(L):f.a.warn("controlRemoteStream called with unready connection."):f.a.warn("controlRemoteStream called with no connection.")}getLocalPeer(){return De(this,void 0,void 0,function*(){for(;!this.localPeer;)yield Object(c.a)(.1*u.a.second);return ht(this.localPeer)})}connect(Z,L){var q,ie,ae;return De(this,void 0,void 0,function*(){if(this.config.lanOnlyMode===!0)throw new Error("connect method called in local only mode.");const{track:ue,signalingClient:Ue}=this.config,{localPeer:fe,receiveSignalStream:ce,iceServers:le}=this;if(!fe||!ce||!le)return void f.a.warn("Connect called prior to local peer, receiveSignalStream, and ICE servers ready");if(this.getActiveConnection(Z))return void f.a.warn("Connect called for peer with existing connection.");if(this.isOutgoingConnection.has(Z))return void f.a.warn("Connect called for peer with an existing outgoing connection offer.");this.isOutgoingConnection.add(Z);const me=function(Pe,Me,Le){const{rtcIceTransportPolicies:ze,rtcIceServerProtocol:qe,useAllServers:yt}=Me||{},Xe=Pe.map(tt=>Object.assign(Object.assign({},tt),{urls:tt.urls.filter(ct=>{const wt=(ze===void 0||ze.some(Ot=>S(ct,Ot)))&&(qe===void 0||V(ct,qe));return wt||f.a.debug("Ignoring ICE server: "+ct,{organizationId:Le}),wt})})).filter(({urls:tt})=>tt.filter(ct=>ct).length>0);return yt?Xe:[k(Xe,"stun"),k(Xe,"turn")].filter(tt=>tt!==void 0).map(tt=>O(tt))}(le,L);f.a.debug("Received ICE servers:",Qt(le)),f.a.debug("Using ICE servers:",Qt(me));const Ve=new Vt(yield this.createRTCPeerConnection(me),me,{baseConfig:{isOffer:!0,isLan:!1,receive:(Pe,Me)=>this.config.receive(Pe,Me),onStreamsInfoUpdate:this.config.onStreamsInfoUpdate?(Pe,Me)=>{var Le,ze;return(ze=(Le=this.config).onStreamsInfoUpdate)===null||ze===void 0?void 0:ze.call(Le,Pe,Me)}:void 0,track:this.config.lanOnlyMode?void 0:this.config.track,localUserId:(q=fe.getUserId())===null||q===void 0?void 0:q.getValue(),localPeerId:fe.getPeerId(),remotePeerId:Z,sessionType:this.config.sessionType},remoteConfig:{}},Pe=>this.onCustomDataChannel(Z,Pe)),Ce=yield Ve.getOffer();if(!Ce)return f.a.error("Failed to generate offer."),void this.isOutgoingConnection.delete(Z);f.a.debug("Sending offer."),ue==null||ue("Sending offer",Ce);const xe=new z.SendSignalRequest;xe.setSignal(Ce);const He=yield(()=>De(this,void 0,void 0,function*(){try{return yield Y.withDeadline(Ue.sendSignal(xe,yield this.getMetadata()),this.grpcCallDeadline)}catch(Pe){f.a.warn("Error when sending signal",{error:Pe})}}))();if(!this.isOutgoingConnection.has(Z))return void f.a.debug("No offer set after receiving offer signal response.");f.a.debug("Offer sent.");const Ye=(ie=He==null?void 0:He.getSessionId())===null||ie===void 0?void 0:ie.getValue(),$e=(ae=He==null?void 0:He.getSessionCreatedTimestamp())===null||ae===void 0?void 0:ae.getValue();return Ye&&$e?(Ve.setSessionId(Ye),Ve.setSessionCreatedTimestamp($e),this.isOutgoingConnection.delete(Z),this.connections.push(Ve),this.isConnectionInitiator.add(Ve),this.setupHandlers(Ve),Ye):(f.a.warn("No session ID or no session created timestamp on send signal response."),void this.isOutgoingConnection.delete(Z))})}connectLan(Z){var L,q;return De(this,void 0,void 0,function*(){const ie=new P(Z),ae=new Vt(yield this.createRTCPeerConnection([]),[],{baseConfig:{isOffer:!0,isLan:!0,receive:(ce,le)=>this.config.receive(ce,le),onStreamsInfoUpdate:this.config.onStreamsInfoUpdate?(ce,le)=>{var me,Ve;return(Ve=(me=this.config).onStreamsInfoUpdate)===null||Ve===void 0?void 0:Ve.call(me,ce,le)}:void 0,track:this.config.lanOnlyMode?void 0:this.config.track,localUserId:(q=(L=this.localPeer)===null||L===void 0?void 0:L.getUserId())===null||q===void 0?void 0:q.getValue(),localPeerId:"lan_client",remotePeerId:Z}},ce=>this.onCustomDataChannel(Z,ce)),ue=yield ae.getLanOffer();if(!ue)return f.a.warn("Could not generate LAN offer"),!1;const Ue=yield ie.postLanRtcOffer({offer:JSON.stringify(ue)}),fe=new RTCSessionDescription(JSON.parse(Ue.answer));return yield ae.handleLanAnswer(fe),this.localConnections.push(ae),this.isConnectionInitiator.add(ae),Object(D.a)()})}getConnections(){return[...this.connections,...this.localConnections]}createCustomDataChannel(Z,L,q,ie,ae){const ue=this.getActiveConnection(Z);if(ue&&this.isConnectionInitiator.has(ue)){const fe=ue.peerConnection.createDataChannel("custom."+L,q);return ie&&(fe.binaryType="arraybuffer"),ae(Z,fe),()=>{}}const Ue=(fe,ce)=>{Z===fe&&ce.label==="custom."+L&&ae(Z,ce)};return this.peerDataChannelListeners.push(Ue),()=>{this.peerDataChannelListeners=this.peerDataChannelListeners.filter(fe=>fe!==Ue)}}onCustomDataChannel(Z,L){this.peerDataChannelListeners.forEach(q=>q(Z,L))}getConnectionStatus(Z){if(this.isOutgoingConnection.has(Z))return"connecting";const L=this.getActiveConnection(Z);return L?L.isReady()?"connected":"connecting":"disconnected"}getConnectionStatsInfo(Z){return De(this,void 0,void 0,function*(){const L=this.getActiveConnection(Z);if(L)return yield L.getConnectionStatsInfo()})}disconnect(Z){return De(this,void 0,void 0,function*(){const L=this.getActiveConnection(Z);L&&(yield L.close(),this.connections=this.connections.filter(q=>q!==L),this.localConnections=this.localConnections.filter(q=>q!==L))})}getPeers(){return De(this,void 0,void 0,function*(){if(this.config.lanOnlyMode)throw new Error("getPeers method cannot be used in local-only mode.");const{signalingClient:Z}=this.config,L=yield(()=>De(this,void 0,void 0,function*(){try{return yield Y.withDeadline(Z.getPeers(new z.GetPeersRequest,yield this.getMetadata()),this.grpcCallDeadline)}catch(ae){f.a.warn("Error when getting peers",{error:ae})}}))();if(!L)return[];const q=L.getPeersList();if(!q)return[];const ie=ae=>{var ue,Ue;return(Ue=(ue=ae.getPeerCreatedTimestamp())===null||ue===void 0?void 0:ue.getValue())!==null&&Ue!==void 0?Ue:0};return q.sort((ae,ue)=>ie(ue)-ie(ae)).map(ae=>ht(ae))})}getSessions(){return De(this,void 0,void 0,function*(){if(this.config.lanOnlyMode)throw new Error("getPeers method cannot be used in local-only mode.");const{signalingClient:Z}=this.config,L=yield(()=>De(this,void 0,void 0,function*(){try{return yield Y.withDeadline(Z.getPeers(new z.GetPeersRequest,yield this.getMetadata()),this.grpcCallDeadline)}catch(ae){f.a.warn("Error when getting peers",{error:ae})}}))();if(!L)return{};const q=L.getPeersList(),ie={};for(const ae of q)ie[ae.getPeerId()]=ae.getSessionIdsList();return ie})}getPing(Z){const L=this.getActiveConnection(Z);if(L)return L.getPing();f.a.warn("Attempted to get ping time from inactive peer.")}getPingInfo(Z){const L=this.getActiveConnection(Z);if(L)return L.getPingInfo();f.a.warn("Attempted to get ping time from inactive peer.")}getLastMessageTimestamp(Z){const L=this.getActiveConnection(Z);if(L)return L.getLastMessageTimestamp();f.a.warn("Attempted to get last message time from inactive peer.")}getSessionMetricsMessageCounts(Z){const L=this.getActiveConnection(Z);if(L)return L.getSessionMetricsMessageCounts();f.a.warn("Attempted to get session metrics counts from inactive peer.")}isReady(){if(this.config.lanOnlyMode)return!0;const{localPeer:Z,receiveSignalStream:L,iceServers:q}=this;return!!(Z&&L&&q)}shutdown(){return De(this,void 0,void 0,function*(){yield this.refreshInterval.stop(),this.receiveSignalStream&&this.receiveSignalStream.cancel();const Z=this.connections;this.connections=[],yield this.closeConnections(Z);const L=this.localConnections;this.localConnections=[],yield this.closeConnections(L),this.isOutgoingConnection.clear(),this.peerDataChannelListeners=[];const{localPeer:q}=this;if(!q||this.config.lanOnlyMode)return;const{signalingClient:ie}=this.config;yield(()=>De(this,void 0,void 0,function*(){try{const ae=new z.DeletePeerRequest;ae.setPeerId(q.getPeerId()),yield Y.withDeadline(ie.deletePeer(ae,yield this.getMetadata()),this.grpcCallDeadline)}catch(ae){return void f.a.warn("Error deleting local peer",{error:ae})}}))()})}createPeer(){return De(this,void 0,void 0,function*(){if(this.config.lanOnlyMode)throw new Error("createPeer method cannot be used in local-only mode.");const{signalingClient:Z}=this.config,L=yield(()=>De(this,void 0,void 0,function*(){try{return yield Y.withDeadline(Z.createPeer(new z.CreatePeerRequest,yield this.getMetadata()),this.grpcCallDeadline)}catch(ie){const ae=ie;f.a.debug("createPeer failed",{error:ae});const ue=jt(ae);throw new Error("Was not able to create peer: "+ue)}}))(),q=L==null?void 0:L.getPeer();if(!q)throw new Error("Response did not provide peer.");return this.localPeer=q})}createReceiveSignalStream(){return De(this,void 0,void 0,function*(){if(this.config.lanOnlyMode)throw new Error("createReceiveSignalStream method cannot be used in local-only mode.");const{signalingClient:Z}=this.config,{localPeer:L,iceServers:q}=this;if(!L||!q)return;const{receiveSignalStream:ie}=this;ie&&ie.cancel();const ae=new z.ReceiveSignalStreamRequest;ae.setPeerId(L.getPeerId());const ue=yield(()=>De(this,void 0,void 0,function*(){try{return Z.receiveSignalStream(ae,yield this.getMetadata({hasDeadline:!1}))}catch(Ue){f.a.debug("createReceiveSignalStream failed",{error:Ue});const fe=jt(Ue);throw new Error("Unable to create receive signal stream: "+fe)}}))();if(!ue)throw new Error("Response did not provide stream.");return ue.on("data",Ue=>De(this,void 0,void 0,function*(){var fe,ce,le,me;const Ve=Ue.getSignal(),Ce=(fe=Ve==null?void 0:Ve.getSessionId())===null||fe===void 0?void 0:fe.getValue(),xe=Ve==null?void 0:Ve.getSenderId(),He=Ve==null?void 0:Ve.getReceiverId(),Ye=(ce=Ve==null?void 0:Ve.getSessionCreatedTimestamp())===null||ce===void 0?void 0:ce.getValue();if(!(Ve&&Ce&&xe&&He&&Ye))return void f.a.warn("Received signal with missing information.");const $e=this.getActiveConnection(xe);if($e)if($e.getSessionId()!==Ce){if(f.a.debug("Received signal: different session for a peer we're already connected to."),($e.getSessionCreatedTimestamp()||0)>Ye)return;const Pe=new Vt(yield this.createRTCPeerConnection(q),q,{baseConfig:{isOffer:!1,isLan:!1,receive:(Me,Le)=>this.config.receive(Me,Le),onStreamsInfoUpdate:this.config.onStreamsInfoUpdate?(Me,Le)=>{var ze,qe;return(qe=(ze=this.config).onStreamsInfoUpdate)===null||qe===void 0?void 0:qe.call(ze,Me,Le)}:void 0,track:this.config.lanOnlyMode?void 0:this.config.track,localPeerId:L.getPeerId(),localUserId:(me=L.getUserId())===null||me===void 0?void 0:me.getValue(),remotePeerId:xe},remoteConfig:{sessionId:Ce,sessionCreatedTimestamp:Ye}},Me=>this.onCustomDataChannel(xe,Me));yield Pe.handleSignal(Ve),this.connections.push(Pe)}else f.a.debug("Received signal: for an existing connection."),yield $e.handleSignal(Ve);else{f.a.debug("Received signal: new connection.");const Pe=new Vt(yield this.createRTCPeerConnection(q),q,{baseConfig:{isOffer:!1,isLan:!1,receive:(Me,Le)=>this.config.receive(Me,Le),onStreamsInfoUpdate:this.config.onStreamsInfoUpdate?(Me,Le)=>{var ze,qe;return(qe=(ze=this.config).onStreamsInfoUpdate)===null||qe===void 0?void 0:qe.call(ze,Me,Le)}:void 0,track:this.config.lanOnlyMode?void 0:this.config.track,localPeerId:L.getPeerId(),localUserId:(le=L.getUserId())===null||le===void 0?void 0:le.getValue(),remotePeerId:xe},remoteConfig:{sessionId:Ce,sessionCreatedTimestamp:Ye}},Me=>this.onCustomDataChannel(xe,Me));yield Pe.handleSignal(Ve),this.connections.push(Pe)}})),ue.on("end",()=>{ue.cancel(),this.receiveSignalStream=void 0}),ue.on("error",Ue=>{switch(Ue.code){case v.StatusCode.CANCELLED:case v.StatusCode.UNAVAILABLE:case v.StatusCode.UNKNOWN:f.a.debug("Receive signal stream error",{error:Ue});break;case v.StatusCode.UNAUTHENTICATED:f.a.warn("Receive signal stream error",{error:Ue});break;default:f.a.error("Receive signal stream error",{error:Ue})}ue.cancel(),this.receiveSignalStream=void 0}),this.receiveSignalStream=ue})}createRTCPeerConnection(Z){var L;return De(this,void 0,void 0,function*(){const q=(L=this.config.alternateRTCPeerConnection)!==null&&L!==void 0?L:window.RTCPeerConnection;if(!q)throw function(){if(typeof navigator=="undefined")throw new Error("not a browser");const{userAgent:ie}=navigator;return ie.includes("Firefox/")?"Firefox":ie.includes("Edg/")?"Edge":ie.includes("Chrome/")?"Chrome":ie.includes("Safari/")?"Safari":ie.includes("MSIE/")||ie.includes("Trident/")?"IE":"Other"}()!=="Chrome"?new Error("WebRTC is not enabled. Please try again with the latest version of Google Chrome."):new Error("WebRTC is not enabled. Please ensure WebRTC is not disabled by ad blocking software.");this.rtcInstancesConstructed++,this.rtcInstancesConstructed%20||Nt();try{return new q({iceServers:Z})}catch(ie){throw f.a.debug(`Failed to create RTCPeerConnection: ${this.rtcInstancesConstructed} total allocated`),ie}})}closeConnections(Z){return De(this,void 0,void 0,function*(){const L=yield $(Z.map(q=>De(this,void 0,void 0,function*(){yield q.close()})));for(const q of L)f.a.warn("Request to close session failed",{error:q})})}getActiveConnection(Z){return this.getConnections().find(L=>L.getRemotePeerId()===Z&&L.isActive())}update(){var Z;return De(this,void 0,void 0,function*(){if(this.localConnections=this.localConnections.filter(me=>me.isActive()),this.config.lanOnlyMode)return;const{signalingClient:L}=this.config;if(!this.localPeer||!this.receiveSignalStream||!this.iceServers){const me=[];return this.localPeer||me.push(this.createPeer()),this.iceServers||me.push(this.updateIceServers()),yield Promise.all(me),void(this.receiveSignalStream||(yield this.createReceiveSignalStream()))}const[q,ie]=(ae=this.connections,ue=me=>me.isActive(),ae.reduce((me,Ve,Ce,xe)=>{const[He,Ye]=me;return(ue(Ve,Ce,xe)?He:Ye).push(Ve),me},[[],[]]));var ae,ue;yield this.closeConnections(ie),this.connections=q,this.gatherConnectionStats().catch(me=>{f.a.warn("Error calling gatherConnectionStats",{error:me})}),this.statsLoopsExecuted++;const{localPeer:Ue}=this,fe=this.connections.filter(me=>me.getSessionId).map(me=>O(me.getSessionId()));Ue.setSessionIdsList(fe);const ce=new z.RefreshPeerRequest;ce.setPeer(Ue);try{yield Y.withDeadline(L.refreshPeer(ce,yield this.getMetadata()),this.grpcCallDeadline)}catch(me){me instanceof v.RpcError&&me.code===v.StatusCode.NOT_FOUND?(f.a.warn("Peer expired, creating new peer",{peerId:Ue.getPeerId()}),yield this.reset()):f.a.warn("Error calling RefreshPeer",{error:me})}const le=yield this.getPeers();for(const me of this.connections)me.setRemoteDeviceId((Z=le.find(Ve=>Ve.id===me.getRemotePeerId()))===null||Z===void 0?void 0:Z.deviceId)})}gatherConnectionStats(){return De(this,void 0,void 0,function*(){if(this.statsLoopsExecuted%10!=0||this.connections.length!==1)return;const Z=yield this.connections[0].getConnectionStatsInfo(),L=Z?vt(Z):void 0;L?x.setTag("rtc-connection-type",L):x.setTag("rtc-connection-type","unknown")})}reset(){return De(this,void 0,void 0,function*(){yield this.closeConnections(this.connections),this.connections=[],this.isOutgoingConnection.clear(),yield this.createPeer(),yield this.createReceiveSignalStream()})}updateIceServers(){return De(this,void 0,void 0,function*(){if(this.config.lanOnlyMode)return;const{iceServersLastUpdate:Z,iceServersTtl:L}=this,q=new Date().getTime();if(!Z||q-Z>L)try{const ie=(yield Y.withDeadline(this.config.signalingClient.getIceServers(new z.GetIceServersRequest,yield this.getMetadata()),this.grpcCallDeadline)).getIceServers();this.iceServers=JSON.parse(ie),this.iceServersLastUpdate=q}catch(ie){f.a.warn("Error in updateIceServers",{error:ie})}})}setupHandlers(Z){const{peerConnection:L}=Z,q=Z.getSessionCreatedTimestamp();L.onconnectionstatechange=()=>De(this,void 0,void 0,function*(){const ie=L.connectionState;if(!q)return;const ae=Z.getRemoteDeviceId();switch(ie){case"connected":x.aggregate("rtc-connect-time",new Date().getTime()-q,Object.assign({},ae?{deviceId:ae}:{}));break;case"failed":x.increment("rtc-connect-failed",Object.assign({},ae?{deviceId:ae}:{}))}})}getMetadata(Z={}){return De(this,void 0,void 0,function*(){if(this.config.lanOnlyMode)throw new Error("getMetadata method cannot be called in local-only mode");const{getToken:L}=this.config,{grpcCallDeadline:q}=this,{hasDeadline:ie=!0}=Z,ae=ie?{deadline:(Date.now()+q).toString(10)}:null;try{const ue=yield L();return Object.assign({authorization:ue},ae)}catch(ue){throw f.a.error("getToken() failed",{error:ue}),new Error("Cannot get authorization token")}})}}var it=n(12),Rt=n(11),zt=function(Re,Z,L,q){return new(L||(L=Promise))(function(ie,ae){function ue(ce){try{fe(q.next(ce))}catch(le){ae(le)}}function Ue(ce){try{fe(q.throw(ce))}catch(le){ae(le)}}function fe(ce){var le;ce.done?ie(ce.value):(le=ce.value,le instanceof L?le:new L(function(me){me(le)})).then(ue,Ue)}fe((q=q.apply(Re,Z||[])).next())})};class kt{constructor(Z,L){this.sentMessagesCounts=new Map,this.receivedMessagesCounts=new Map,this.sessionId=Z,this.connection=L}incrementMessageSent(Z){const L=Oe(Z.header.stream);this.sentMessagesCounts.set(L,(this.sentMessagesCounts.get(L)||0)+1)}incrementMessageReceived(Z){const L=Oe(Z.header.stream);this.receivedMessagesCounts.set(L,(this.receivedMessagesCounts.get(L)||0)+1)}uploadMetrics(){return zt(this,void 0,void 0,function*(){const{sessionId:Z}=this,L=yield this.connection.peerConnection.getStats(),q={};L.forEach(ae=>q[ae.id]=ae),f.a.debug("rtc-stats",Object.assign(Object.assign({},q),{sessionId:Z}));const ie=[...new Set(Array.from(this.sentMessagesCounts.keys()).concat(Array.from(this.receivedMessagesCounts.keys())))].reduce((ae,ue)=>{const Ue=this.sentMessagesCounts.get(ue),fe=this.receivedMessagesCounts.get(ue);return Object.assign(Object.assign({},ae),{[ue+"-sent"]:Ue,[ue+"-received"]:fe})},{sessionId:Z});f.a.debug("rtc-message-report",ie)})}}function Bt(Re,Z){return Oe(Re)===Oe(Z)}var st=function(Re,Z,L,q){return new(L||(L=Promise))(function(ie,ae){function ue(ce){try{fe(q.next(ce))}catch(le){ae(le)}}function Ue(ce){try{fe(q.throw(ce))}catch(le){ae(le)}}function fe(ce){var le;ce.done?ie(ce.value):(le=ce.value,le instanceof L?le:new L(function(me){me(le)})).then(ue,Ue)}fe((q=q.apply(Re,Z||[])).next())})};class Mt{constructor(Z,L){this.peerConnection=Z,this.config=L,this.connectTimeoutMs=10*u.a.second,this.gatherIceTimeoutMs=5*u.a.second,this.pingUpdateTimeoutMs=2*u.a.second,this.streamLatestTimestamp=new Map,this.closeCalled=!1,this.connectCalled=!1,this.sentOffer=!1,this.receivedIceCandidate=!1;const{isOffer:q}=L;q?this.initializeChannels(Z):Z.ondatachannel=ie=>{switch(ie.channel.label){case"stream.latest-ttl":this.latestTtlStreamChannel=ie.channel;break;case"stream.reliable":this.reliableStreamChannel=ie.channel;break;case"stream.latest-reliable":this.latestReliableStreamChannel=ie.channel;break;case"stream.latest-try-once":this.latestTryOnceStreamChannel=ie.channel}this.setupChannel(ie.channel)},this.sessionMetrics=new kt(this.getSessionId(),this)}connect(){return st(this,void 0,void 0,function*(){if(this.connectCalled)return;this.connectCalled=!0,this.pingUpdateTimeout=setInterval(()=>{const{reliableStreamChannel:ie}=this;ie&&this.sendSystemMessage(ie,{type:"ping"})},this.pingUpdateTimeoutMs),this.connectTimeout=setTimeout(()=>st(this,void 0,void 0,function*(){this.isReady()||(f.a.warn("RTC connect timed out, closing connection"),yield this.close())}),this.connectTimeoutMs);const{peerConnection:Z,config:{isOffer:L,sessionId:q}}=this;if(L){const ie=yield Z.createOffer();yield Z.setLocalDescription(ie)}L&&(this.gatherIceTimeout=setTimeout(()=>st(this,void 0,void 0,function*(){this.sentOffer||(f.a.warn("ICE gathering timed out"),this.receivedIceCandidate?(f.a.warn("Attempting to connect with partial ICE candidate pool"),yield this.sendOffer()):yield this.close())}),this.gatherIceTimeoutMs),Z.onicecandidate=ie=>st(this,void 0,void 0,function*(){ie.candidate?this.receivedIceCandidate=!0:yield this.sendOffer()}),Z.onicegatheringstatechange=()=>st(this,void 0,void 0,function*(){Z.iceGatheringState==="complete"&&(yield this.sendOffer())}),Z.onnegotiationneeded=()=>{f.a.debug("Negotiation needed",{sessionId:q})})})}handleSignal(Z){return st(this,void 0,void 0,function*(){const{peerConnection:L,config:{sessionId:q,sendSignal:ie}}=this,{description:ae}=JSON.parse(Z.payload);if(f.a.debug("Handling signal",{sessionId:q,description:JSON.stringify(ae)}),ae)if(L.signalingState!=="stable"||L.connectionState!=="connected")if(L.remoteDescription)f.a.warn("Received SDP signal during negotiation when remote description is already set: "+JSON.stringify(Z));else if(ae.type==="offer"){yield L.setRemoteDescription(ae);const ue=yield L.createAnswer();yield L.setLocalDescription(ue),yield ie({payload:JSON.stringify({description:ue})})}else ae.type==="answer"&&(yield L.setRemoteDescription(ae));else f.a.warn("Received SDP signal when signaling is stable and connected: "+JSON.stringify(Z));else f.a.warn("Received non-SDP signal: "+JSON.stringify(Z))})}send(Z,L){const q=this.getChannelFromLabel(L.channelLabel);q?this.sendOnChannel(q,Z):f.a.warn("Send called with unexpected channel label",{channelLabel:L.channelLabel})}controlRemoteStream(Z){this.sendSystemMessage(O(this.reliableStreamChannel),{type:"stream-control",streamControl:Z})}isActive(){return new Set(["new","connecting","connected"]).has(this.peerConnection.connectionState)}isReady(){const{peerConnection:Z,latestTtlStreamChannel:L,reliableStreamChannel:q,latestTryOnceStreamChannel:ie}=this;return!!(q&&L&&ie)&&Z.connectionState==="connected"&&q.readyState==="open"&&L.readyState==="open"&&ie.readyState==="open"}isClosed(){const{peerConnection:Z,reliableStreamChannel:L,latestTryOnceStreamChannel:q,latestTtlStreamChannel:ie}=this;return!(Z.connectionState!=="closed"||L!==void 0&&L.readyState!=="closed"||q!==void 0&&q.readyState!=="closed"||ie!==void 0&&ie.readyState!=="closed")}needsClosing(){const{peerConnection:Z,latestTtlStreamChannel:L,reliableStreamChannel:q,latestTryOnceStreamChannel:ie}=this;if(this.isClosed())return!1;const ae=new Set(["closing","closed"]),ue=Ue=>Ue&&ae.has(Ue.readyState);return pt(Z)||ue(L)||ue(q)||ue(ie)}close(){return st(this,void 0,void 0,function*(){this.closeCalled||(this.closeCalled=!0,yield this.sessionMetrics.uploadMetrics(),this.pingUpdateTimeout&&clearInterval(this.pingUpdateTimeout),this.connectTimeout&&clearTimeout(this.connectTimeout),this.gatherIceTimeout&&clearTimeout(this.gatherIceTimeout),this.peerConnection.close())})}getPing(){return this.pingTimeMs}getLastMessageTimestamp(){return this.lastMessageTimestamp}getSessionId(){return this.config.sessionId}getRemotePeer(){return this.config.remotePeer}initializeChannels(Z){this.latestTtlStreamChannel=Z.createDataChannel("stream.latest-ttl",oe),this.reliableStreamChannel=Z.createDataChannel("stream.reliable",ge),this.latestReliableStreamChannel=Z.createDataChannel("stream.latest-reliable",Se),this.latestTryOnceStreamChannel=Z.createDataChannel("stream.latest-try-once",ve),this.setupChannel(this.latestTtlStreamChannel),this.setupChannel(this.reliableStreamChannel),this.setupChannel(this.latestReliableStreamChannel),this.setupChannel(this.latestTryOnceStreamChannel)}sendOffer(){return st(this,void 0,void 0,function*(){if(this.sentOffer||(this.sentOffer=!0,pt(this.peerConnection)))return;const{peerConnection:Z,config:{sendSignal:L}}=this,q=yield Z.createOffer();yield Z.setLocalDescription(q);const ie={payload:JSON.stringify({description:q})};yield L(ie)})}getChannelFromLabel(Z){switch(Z){case"stream.latest-ttl":return this.latestTtlStreamChannel;case"stream.reliable":return this.reliableStreamChannel;case"stream.latest-reliable":return this.latestReliableStreamChannel;case"stream.latest-try-once":return this.latestTryOnceStreamChannel}}sendOnChannel(Z,L){let q;try{q=Object(te.encode)(JSON.stringify(L))}catch(ie){return void f.a.warn("Failed to encode RTC message",{error:ie})}try{Z.send(q),this.sessionMetrics.incrementMessageSent(L)}catch(ie){f.a.warn("Failed to send message to channel",{error:ie,channel:Z.label})}}channelNotRecognized(Z){return Z!==this.latestTtlStreamChannel&&Z!==this.latestReliableStreamChannel&&Z!==this.latestTryOnceStreamChannel&&Z!==this.reliableStreamChannel}setupChannel(Z){Z.onmessage=L=>{if(this.channelNotRecognized(Z))return void f.a.warn("Received message on unrecognized data channel.");let q;try{q=JSON.parse(Object(te.decode)(L.data))}catch(ie){return void f.a.warn("Received unparseable RTC message",{error:ie,channel:Z.label})}if(this.lastMessageTimestamp=new Date().getTime(),q=_t(q),this.sessionMetrics.incrementMessageReceived(q),!this.handleSystemMessage(Z,q)){if(!this.hasCapabilities(q))return void f.a.warn("Received RTC message that was not within the capability scope of the connection.");(Z===this.latestTryOnceStreamChannel||Z===this.latestTtlStreamChannel||Z===this.latestReliableStreamChannel)&&!this.isLatestMessage(q)||this.config.receive(this.config.remotePeer.id,q)}},Z.onerror=L=>{f.a.warn("Channel error: "+L.error,{error:L.error,sessionId:this.getSessionId(),channelLabel:Z.label})},Z.onopen=()=>{f.a.debug("Channel opened",{sessionId:this.getSessionId(),channelLabel:Z.label})},Z.onclose=()=>{const L={bufferedAmount:Z.bufferedAmount,sessionId:this.getSessionId(),channelLabel:Z.label};this.closeCalled===!1?f.a.debug("Unexpected channel closed",L):f.a.debug("Channel closed",L)}}handleSystemMessage(Z,L){switch(L.header.stream.streamType){case"ping":return this.sendSystemMessage(Z,{type:"pong",timestamp:O(L.payload.ping)}),!0;case"pong":{const q=new Date().getTime()-O(L.payload.pong);return this.pingTimeMs=q,x.aggregate("rtc-ping-time",q),!0}case"stream-control":return!0;default:return!1}}sendSystemMessage(Z,L){if(Z.readyState!=="open")return;const q={entityId:O(this.config.localPeer.deviceId||this.config.localPeer.userId),streamName:"$."+L.type,streamType:L.type};let ie;switch(L.type){case"ping":ie={ping:new Date().getTime()};break;case"pong":ie={pong:L.timestamp};break;case"stream-control":ie={streamControl:L.streamControl}}this.sendOnChannel(Z,Ct(q,ie))}hasCapabilities(Z){var L,q;const{localPeer:ie,remotePeer:ae}=this.config,ue=(L=ie.capabilitySet.streaming)===null||L===void 0?void 0:L.streams,Ue=ue&&ue.some(le=>le.receive&&Bt(le.stream,Z.header.stream)),fe=(q=ae.capabilitySet.streaming)===null||q===void 0?void 0:q.streams,ce=fe&&fe.some(le=>le.send&&Bt(le.stream,Z.header.stream));return Ue||ce}isLatestMessage(Z){const L=Oe(Z.header.stream),q=(this.streamLatestTimestamp.get(L)||0)<=Z.header.created;return q&&this.streamLatestTimestamp.set(L,Z.header.created),q}}var Ae=function(Re,Z,L,q){return new(L||(L=Promise))(function(ie,ae){function ue(ce){try{fe(q.next(ce))}catch(le){ae(le)}}function Ue(ce){try{fe(q.throw(ce))}catch(le){ae(le)}}function fe(ce){var le;ce.done?ie(ce.value):(le=ce.value,le instanceof L?le:new L(function(me){me(le)})).then(ue,Ue)}fe((q=q.apply(Re,Z||[])).next())})};class Dt{constructor(Z){this.config=Z,this.connections=[],this.connectingSessions=new Map,this.rtcInstancesConstructed=0,this.updateInterval=T({func:()=>Ae(this,void 0,void 0,function*(){try{yield this.update()}catch(L){f.a.warn("RTC update failed",{error:L})}}),delay:250*u.a.millisecond,immediate:!0}),this.localPeer=this.createPeer()}send(Z,L,q){const ie=this.getActiveConnection(Z);ie?ie.isReady()?ie.send(L,q):f.a.warn("Attempted to send with an active connection to that peer which was not yet ready."):f.a.warn("Attempted to send with no active connection to that peer.")}controlRemoteStream(Z,L){const q=this.getActiveConnection(Z);q?q.isReady()?q.controlRemoteStream(L):f.a.warn("Attempted to control remote stream with an active connection to that peer which was not yet ready."):f.a.warn("Attempted to control remote stream with no active connection to that peer.")}connect(Z){return Ae(this,void 0,void 0,function*(){const L=yield this.getLocalPeer();if(this.getActiveConnection(Z))return void f.a.warn("Attempted to connect to peer with an already active connection.");let q;try{q=yield this.config.signalingClient.createSession(yield this.config.getToken(),{offerPeerId:L.id,answerPeerId:Z})}catch(ie){Object(it.a)(ie,Rt.a,ae=>ae.statusCode===404),f.a.warn("Attempted to connect to peer that does not exist.")}if(q)for(this.connectingSessions.set(q.id,new Date().getTime()),yield this.connectToSession(q);;)switch(yield Object(c.a)(.1),this.getConnectionStatus(Z)){case"connecting":continue;case"connected":return q.id;case"disconnected":return}})}getConnectionStatus(Z){const L=this.getActiveConnection(Z);return L?L.isReady()?"connected":"connecting":"disconnected"}getIceMode(Z){const L=this.getActiveConnection(Z);if(L)return L.iceMode}disconnect(Z){return Ae(this,void 0,void 0,function*(){const L=this.getActiveConnection(Z);L&&(yield this.closeConnection(L))})}getLocalPeer(){return Ae(this,void 0,void 0,function*(){return yield this.localPeer})}getPeers(){return Ae(this,void 0,void 0,function*(){return yield this.config.signalingClient.getPeers(yield this.config.getToken())})}getPing(Z){const L=this.getActiveConnection(Z);if(L)return L.getPing();f.a.warn("Attempted to get ping time from inactive peer.")}getLastMessageTimestamp(Z){const L=this.getActiveConnection(Z);if(L)return L.getLastMessageTimestamp();f.a.warn("Attempted to get ping time from inactive peer.")}shutdown(){return Ae(this,void 0,void 0,function*(){yield this.updateInterval.stop();const Z=this.connections;this.connections=[],yield this.closeConnections(Z)})}closeConnection(Z){return Ae(this,void 0,void 0,function*(){this.connectingSessions.delete(Z.getSessionId()),yield Z.close();try{yield this.config.signalingClient.deleteSession(yield this.config.getToken(),Z.getSessionId())}catch(L){Object(it.a)(L,Rt.a,q=>q.statusCode===404)}})}getSessions(){return Ae(this,void 0,void 0,function*(){const Z=yield this.getLocalPeer();return(yield this.config.signalingClient.getSessions(yield this.config.getToken())).filter(L=>L.offer.peer.id===Z.id||L.answer.peer.id===Z.id)})}createPeer(){return Ae(this,void 0,void 0,function*(){return yield this.config.signalingClient.createPeer(yield this.config.getToken(),{capabilitySet:this.config.capabilitySet||{}})})}createRTCPeerConnection(Z={}){return Ae(this,void 0,void 0,function*(){const L=this.config.alternateRTCPeerConnection||RTCPeerConnection;this.rtcInstancesConstructed++,this.rtcInstancesConstructed%20||Nt();try{return new L(Object.assign({iceServers:yield this.config.signalingClient.getIceServers(yield this.config.getToken())},Z))}catch(q){throw f.a.debug(`Failed to create RTCPeerConnection: ${this.rtcInstancesConstructed} total allocated`),q}})}closeConnections(Z){return Ae(this,void 0,void 0,function*(){const L=yield $(Z.map(q=>Ae(this,void 0,void 0,function*(){yield this.closeConnection(q)})));for(const q of L)f.a.warn("Request to close session failed",{error:q})})}reset(){return Ae(this,void 0,void 0,function*(){yield this.closeConnections(this.connections),this.connections=[],this.connectingSessions=new Map,this.localPeer=this.createPeer(),yield this.localPeer})}getActiveConnection(Z){return this.connections.find(L=>L.getRemotePeer().id===Z&&L.isActive())}update(){return Ae(this,void 0,void 0,function*(){const Z=yield this.getLocalPeer();try{yield this.config.signalingClient.refreshPeer(yield this.config.getToken(),Z.id)}catch(L){Object(it.a)(L,Rt.a,q=>q.statusCode===404),f.a.warn("Peer expired, creating new peer",{peerId:Z.id}),yield this.reset()}yield this.handleSessions(yield this.getSessions())})}handleSessions(Z){return Ae(this,void 0,void 0,function*(){yield this.syncConnectionsAndSessions(Z);const L=Z.map(q=>({session:q,connection:this.connections.find(ie=>ie.getSessionId()===q.id)}));yield Promise.all(L.map(({session:q,connection:ie})=>Ae(this,void 0,void 0,function*(){return yield this.maintainConnection(q,ie)})))})}syncConnectionsAndSessions(Z){return Ae(this,void 0,void 0,function*(){const L=new Set(Z.map(ae=>ae.id)),q=ae=>L.has(ae.getSessionId())||this.connectingSessions.has(ae.getSessionId());this.connections=this.connections.filter(ae=>q(ae));const ie=this.connections.filter(ae=>!q(ae)||ae.needsClosing());yield Promise.all(ie.map(ae=>Ae(this,void 0,void 0,function*(){yield this.closeConnection(ae)})))})}maintainConnection(Z,L){return Ae(this,void 0,void 0,function*(){const q=yield this.getLocalPeer(),ie=Z.offer.peer.id===q.id;if(L){if(L.isReady())try{yield this.config.signalingClient.refreshSession(yield this.config.getToken(),Z.id)}catch(ae){Object(it.a)(ae,Rt.a,ue=>ue.statusCode===404),f.a.debug("Refresh session not found",{sessionId:Z.id})}else if(L.isActive())try{yield this.consumeSignals(L)}catch(ae){f.a.warn("Failed to ingest signals, closing connection",{error:ae}),yield this.closeConnection(L)}}else{if(ie)return;yield this.connectToSession(Z)}})}connectToSession(Z){return Ae(this,void 0,void 0,function*(){const L=yield this.getLocalPeer(),q=Z.offer.peer.id===L.id,ie=yield this.createRTCPeerConnection(),ae=new Mt(ie,{localPeer:q?Z.offer.peer:Z.answer.peer,remotePeer:q?Z.answer.peer:Z.offer.peer,sessionId:Z.id,isOffer:q,sendSignal:ue=>this.sendSignal(Z.id,ue),receive:(ue,Ue)=>this.config.receive(ue,Ue)});if(this.connections.find(ue=>ue.getSessionId()===Z.id))return f.a.warn("connectToSession called on a session that already has a connection.",{sessionId:Z.id}),void(yield ae.close());this.setupHandlers(ae),this.connections.push(ae);try{yield ae.connect()}catch(ue){f.a.warn("Failed to handle negotiation, closing connection",{error:ue}),yield this.closeConnection(ae)}})}setupHandlers(Z){const{peerConnection:L}=Z,q=Z.getSessionId();L.onconnectionstatechange=()=>Ae(this,void 0,void 0,function*(){const ie=this.connectingSessions.get(q);if(ie===void 0)return;const ae=L.connectionState;switch(pt(L)&&this.connectingSessions.delete(q),ae){case"connected":{this.connectingSessions.delete(q);const ue=new Date().getTime()-ie;x.aggregate("rtc-connect-time",ue);break}case"failed":x.increment("rtc-connect-failed"),yield this.closeConnection(Z)}})}consumeSignals(Z){return Ae(this,void 0,void 0,function*(){let L=[];try{L=yield this.config.signalingClient.takeSignals(yield this.config.getToken(),Z.getSessionId())}catch(q){Object(it.a)(q,Rt.a,ie=>ie.statusCode===404)}for(const q of L)yield Z.handleSignal(q)})}sendSignal(Z,L){return Ae(this,void 0,void 0,function*(){try{yield this.config.signalingClient.addSignals(yield this.config.getToken(),Z,{signals:[L]})}catch(q){Object(it.a)(q,Rt.a,ie=>ie.statusCode===404)}})}}},,function(e,t,n){n.r(t),n.d(t,"LogClient",function(){return l});var r=n(26),o=n(12),s=n(11),g=function(u,c,d,B){return new(d||(d=Promise))(function(Q,U){function p(M){try{b(B.next(M))}catch(J){U(J)}}function f(M){try{b(B.throw(M))}catch(J){U(J)}}function b(M){var J;M.done?Q(M.value):(J=M.value,J instanceof d?J:new d(function(m){m(J)})).then(p,f)}b((B=B.apply(u,c||[])).next())})};class l extends r.a{log(c){return g(this,void 0,void 0,function*(){const d=l.token;try{yield this.fetch("logs",{token:d,method:"POST",body:{logs:c},allowUnsafeRetries:!0})}catch(B){Object(o.a)(B,s.a,Q=>Q.statusCode===401&&d!==void 0),l.token===d&&delete l.token,yield this.log(c)}})}}},function(e,t,n){var r={randomUUID:typeof crypto!="undefined"&&crypto.randomUUID&&crypto.randomUUID.bind(crypto)};let o;const s=new Uint8Array(16);function g(){if(!o&&(o=typeof crypto!="undefined"&&crypto.getRandomValues&&crypto.getRandomValues.bind(crypto),!o))throw new Error("crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported");return o(s)}const l=[];for(let c=0;c<256;++c)l.push((c+256).toString(16).slice(1));function u(c,d=0){return(l[c[d+0]]+l[c[d+1]]+l[c[d+2]]+l[c[d+3]]+"-"+l[c[d+4]]+l[c[d+5]]+"-"+l[c[d+6]]+l[c[d+7]]+"-"+l[c[d+8]]+l[c[d+9]]+"-"+l[c[d+10]]+l[c[d+11]]+l[c[d+12]]+l[c[d+13]]+l[c[d+14]]+l[c[d+15]]).toLowerCase()}t.a=function(c,d,B){if(r.randomUUID&&!d&&!c)return r.randomUUID();const Q=(c=c||{}).random||(c.rng||g)();if(Q[6]=15&Q[6]|64,Q[8]=63&Q[8]|128,d){B=B||0;for(let U=0;U<16;++U)d[B+U]=Q[U];return d}return u(Q)}}])})})(dist);var distExports=dist.exports;const SessionTypes={UNKNOWN:0,TELEOP:1,PORT_FORWARD:2,OBSERVE:3,HEADLESS:4},SessionTypeConstants={...SessionTypes,Unknown:SessionTypes.UNKNOWN,Teleop:SessionTypes.TELEOP,PortForward:SessionTypes.PORT_FORWARD,Observe:SessionTypes.OBSERVE,Headless:SessionTypes.HEADLESS,unknown:SessionTypes.UNKNOWN,teleop:SessionTypes.TELEOP,portForward:SessionTypes.PORT_FORWARD,observe:SessionTypes.OBSERVE,headless:SessionTypes.HEADLESS},singleton=Symbol("RtcClientPool.instance");class RtcClientPool{constructor(t){he(this,rt,null);he(this,"createClient");he(this,"ttlMs");he(this,"proxyHandler");he(this,"proxyReceivers",new Map);he(this,"teardownTimeout",null);he(this,"dispatch",(t,n)=>{this.proxyReceivers.forEach(r=>r==null?void 0:r(t,n))});const{createClient:n,ttlMs:r=0}=t;this.createClient=n,this.ttlMs=Math.max(r,0),this.proxyHandler={get:(o,s,g)=>{switch(s){case"shutdown":return()=>this.releaseInstance(g);default:return Reflect.get(o,s,g)}}}}get isActive(){return this[singleton]!==null}get size(){return this.proxyReceivers.size}get(t){const n=new Proxy(this.allocate(),this.proxyHandler);return this.proxyReceivers.set(n,t!=null?t:null),n}allocate(){if(this[singleton])return this.teardownTimeout&&(clearTimeout(this.teardownTimeout),this.teardownTimeout=null),this[singleton];const t=this.createClient(this.dispatch);return this[singleton]=t,t}async teardown(){const t=this[singleton];if(!t){console.warn("singleton has already been shutdown!");return}try{await t.shutdown()}finally{this[singleton]=null}}async releaseInstance(t){return this.proxyReceivers.delete(t)?this.proxyReceivers.size!==0?!1:(!this.teardownTimeout&&Number.isFinite(this.ttlMs)&&(this.ttlMs===0?await this.teardown():this.teardownTimeout=setTimeout(()=>{this.teardown().catch(n=>console.error("teardown failed",{err:n})).finally(()=>this.teardownTimeout=null)},this.ttlMs)),!0):(console.warn("this instance has already been released!"),!1)}}rt=singleton;const getToken=async()=>defined$1(Authentication.token,"Realtime when user isn't authorized"),EnumRtcClientPools={[SessionTypes.UNKNOWN]:new RtcClientPool({ttlMs:2500,createClient:e=>new distExports.RtcClient({signalingClient:new distExports.SignalingPromiseClient(exports.FORMANT_API_URL),getToken,sessionType:SessionTypes.UNKNOWN,receive:e})}),[SessionTypes.TELEOP]:new RtcClientPool({ttlMs:2500,createClient:e=>new distExports.RtcClient({signalingClient:new distExports.SignalingPromiseClient(exports.FORMANT_API_URL),getToken,sessionType:SessionTypes.TELEOP,receive:e})}),[SessionTypes.PORT_FORWARD]:new RtcClientPool({ttlMs:2500,createClient:e=>new distExports.RtcClient({signalingClient:new distExports.SignalingPromiseClient(exports.FORMANT_API_URL),getToken,sessionType:SessionTypes.PORT_FORWARD,receive:e})}),[SessionTypes.OBSERVE]:new RtcClientPool({ttlMs:2500,createClient:e=>new distExports.RtcClient({signalingClient:new distExports.SignalingPromiseClient(exports.FORMANT_API_URL),getToken,sessionType:SessionTypes.OBSERVE,receive:e})}),[SessionTypes.HEADLESS]:new RtcClientPool({ttlMs:2500,createClient:e=>new distExports.RtcClient({signalingClient:new distExports.SignalingPromiseClient(exports.FORMANT_API_URL),getToken,sessionType:SessionTypes.HEADLESS,receive:e})})},AppRtcClientPools={...EnumRtcClientPools,unknown:EnumRtcClientPools[SessionTypes.UNKNOWN],teleop:EnumRtcClientPools[SessionTypes.TELEOP],portForward:EnumRtcClientPools[SessionTypes.PORT_FORWARD],observe:EnumRtcClientPools[SessionTypes.OBSERVE],headless:EnumRtcClientPools[SessionTypes.HEADLESS]},defaultRtcClientPool=EnumRtcClientPools[SessionTypes.TELEOP],getRtcClientPool=e=>{const{sessionType:t}=e;return t?AppRtcClientPools[t]:defaultRtcClientPool};async function getPeers(){if(!Authentication.token)throw new Error("Not authenticated");const e=defaultRtcClientPool.get();try{return await e.getPeers()}finally{await e.shutdown()}}async function getRealtimeSessions(){if(!Authentication.token)throw new Error("Not authenticated");const e=defaultRtcClientPool.get();try{return await e.getSessions()}finally{await e.shutdown()}}async function getTelemetry(e,t,n,r,o,s){let g=e;Array.isArray(e)||(g=[e]);let l=t;return Array.isArray(t)||(l=[t]),(await(await fetch(`${exports.FORMANT_API_URL}/v1/queries/queries`,{method:"POST",body:JSON.stringify({deviceIds:g,end:r.toISOString(),names:l,start:n.toISOString(),tags:o,latestOnly:s}),headers:{"Content-Type":"application/json",Authorization:"Bearer "+Authentication.token}})).json()).items}async function patchDevice(e,t){if(!Authentication.token)throw new Error("Not authenticated");return await(await fetch(`${exports.FORMANT_API_URL}/v1/admin/devices/${e}`,{method:"PATCH",body:JSON.stringify(t),headers:{"Content-Type":"application/json",Authorization:"Bearer "+Authentication.token}})).json()}async function queryDevicesData(e){if(!Authentication.token)throw new Error("Not authenticated");return(await(await fetch(`${exports.FORMANT_API_URL}/v1/admin/devices/query`,{method:"POST",body:JSON.stringify(e),headers:{"Content-Type":"application/json",Authorization:"Bearer "+Authentication.token}})).json()).items}const isRtcPeer=e=>e!==void 0&&e.capabilities!==void 0&&e.capabilitySet!==void 0;var eventemitter3={exports:{}};(function(e){var t=Object.prototype.hasOwnProperty,n="~";function r(){}Object.create&&(r.prototype=Object.create(null),new r().__proto__||(n=!1));function o(u,c,d){this.fn=u,this.context=c,this.once=d||!1}function s(u,c,d,B,Q){if(typeof d!="function")throw new TypeError("The listener must be a function");var U=new o(d,B||u,Q),p=n?n+c:c;return u._events[p]?u._events[p].fn?u._events[p]=[u._events[p],U]:u._events[p].push(U):(u._events[p]=U,u._eventsCount++),u}function g(u,c){--u._eventsCount===0?u._events=new r:delete u._events[c]}function l(){this._events=new r,this._eventsCount=0}l.prototype.eventNames=function(){var c=[],d,B;if(this._eventsCount===0)return c;for(B in d=this._events)t.call(d,B)&&c.push(n?B.slice(1):B);return Object.getOwnPropertySymbols?c.concat(Object.getOwnPropertySymbols(d)):c},l.prototype.listeners=function(c){var d=n?n+c:c,B=this._events[d];if(!B)return[];if(B.fn)return[B.fn];for(var Q=0,U=B.length,p=new Array(U);Q<U;Q++)p[Q]=B[Q].fn;return p},l.prototype.listenerCount=function(c){var d=n?n+c:c,B=this._events[d];return B?B.fn?1:B.length:0},l.prototype.emit=function(c,d,B,Q,U,p){var f=n?n+c:c;if(!this._events[f])return!1;var b=this._events[f],M=arguments.length,J,m;if(b.fn){switch(b.once&&this.removeListener(c,b.fn,void 0,!0),M){case 1:return b.fn.call(b.context),!0;case 2:return b.fn.call(b.context,d),!0;case 3:return b.fn.call(b.context,d,B),!0;case 4:return b.fn.call(b.context,d,B,Q),!0;case 5:return b.fn.call(b.context,d,B,Q,U),!0;case 6:return b.fn.call(b.context,d,B,Q,U,p),!0}for(m=1,J=new Array(M-1);m<M;m++)J[m-1]=arguments[m];b.fn.apply(b.context,J)}else{var y=b.length,h;for(m=0;m<y;m++)switch(b[m].once&&this.removeListener(c,b[m].fn,void 0,!0),M){case 1:b[m].fn.call(b[m].context);break;case 2:b[m].fn.call(b[m].context,d);break;case 3:b[m].fn.call(b[m].context,d,B);break;case 4:b[m].fn.call(b[m].context,d,B,Q);break;default:if(!J)for(h=1,J=new Array(M-1);h<M;h++)J[h-1]=arguments[h];b[m].fn.apply(b[m].context,J)}}return!0},l.prototype.on=function(c,d,B){return s(this,c,d,B,!1)},l.prototype.once=function(c,d,B){return s(this,c,d,B,!0)},l.prototype.removeListener=function(c,d,B,Q){var U=n?n+c:c;if(!this._events[U])return this;if(!d)return g(this,U),this;var p=this._events[U];if(p.fn)p.fn===d&&(!Q||p.once)&&(!B||p.context===B)&&g(this,U);else{for(var f=0,b=[],M=p.length;f<M;f++)(p[f].fn!==d||Q&&!p[f].once||B&&p[f].context!==B)&&b.push(p[f]);b.length?this._events[U]=b.length===1?b[0]:b:g(this,U)}return this},l.prototype.removeAllListeners=function(c){var d;return c?(d=n?n+c:c,this._events[d]&&g(this,d)):(this._events=new r,this._eventsCount=0),this},l.prototype.off=l.prototype.removeListener,l.prototype.addListener=l.prototype.on,l.prefixed=n,l.EventEmitter=l,e.exports=l})(eventemitter3);var eventemitter3Exports=eventemitter3.exports;const EventEmitter=getDefaultExportFromCjs(eventemitter3Exports);class Manipulator{constructor(t,n){he(this,"currentListeners",[]);he(this,"onRealtimeMessage",(t,n)=>{n.payload.jointState&&this.currentListeners.forEach(r=>{n.payload.jointState&&r(n.payload.jointState)})});this.device=t,this.config=n}async synchronize(){this.device.addRealtimeListener(this.onRealtimeMessage),this.device.startListeningToRealtimeDataStream(this.config.currentJointStateStream)}async desynchronize(){this.device.removeRealtimeListener(this.onRealtimeMessage),this.device.stopListeningToRealtimeDataStream(this.config.currentJointStateStream)}async addCurrentJointStateListener(t){this.currentListeners.push(t)}}class RequestDataChannel{constructor(t,n,r){he(this,"channel");he(this,"requestIdToResponseMap",new Map);this.device=t,this.channel_name=n,this.timeout=r}addOpenListener(t){defined$1(this.channel,"channel not initalized").addOpenListener(t)}removeOpenListener(t){defined$1(this.channel,"channel not initalized").removeOpenListener(t)}addCloseListener(t){defined$1(this.channel,"channel not initalized").addCloseListener(t)}removeCloseListener(t){defined$1(this.channel,"channel not initalized").removeCloseListener(t)}addErrorListener(t){defined$1(this.channel,"channel not initalized").addErrorListener(t)}removeErrorListener(t){defined$1(this.channel,"channel not initalized").removeErrorListener(t)}}class BinaryRequestDataChannel extends RequestDataChannel{constructor(){super(...arguments);he(this,"RESPONSE_SUCCESS_BYTE",0);he(this,"decoder",new TextDecoder)}generateBinaryId(){const n=new Uint8Array(16);for(let r=0;r<n.length;r++)n[r]=Math.floor(Math.random()*256);return n}async initialize(){this.channel=await this.device.createCustomDataChannel(this.channel_name),this.channel.addBinaryListener(n=>{const o=n.slice(0,16).toString();if(o.length===0)throw new Error("Invalid response");const s=n.slice(16);if(s.length===0)throw new Error("Invalid response");this.requestIdToResponseMap.has(o)&&this.requestIdToResponseMap.set(o,s)})}async request(n){if(this.channel||await this.initialize(),!this.channel)throw new Error("Failed to create channel");const{channel:r,requestIdToResponseMap:o,timeout:s}=this;await r.waitTilReady();const g=this.generateBinaryId(),l=g.toString();o.set(l,!0),r.sendBinary(new Uint8Array([...g,...n]));const u=new Date().getTime();for(;new Date().getTime()<u+s;)if(await delay$1(50),o.has(l)){const c=o.get(l);if(c!==!0){o.delete(l);const d=c[0]===this.RESPONSE_SUCCESS_BYTE,B=c.slice(1);if(d)return B;throw console.error({name:"AdapterError",message:this.decoder.decode(B)}),new Error("Binary request datachannel adapter error")}}throw o.delete(l),console.error({name:"TimeoutError",message:`Request timed out after ${s/1e3} seconds`}),new Error("Binary request data channel request timed out")}}class TextRequestDataChannel extends RequestDataChannel{generateTextId(){return Math.random().toString(36).substring(2)+"-"+Math.random().toString(36).substring(2)}async initialize(){this.channel=await this.device.createCustomDataChannel(this.channel_name),this.channel.addListener(t=>{const n=JSON.parse(t),{id:r,data:o,error:s}=n;if(!r)throw new Error("Invalid response");if(!o&&!s)throw new Error("Invalid response");this.requestIdToResponseMap.has(r)&&this.requestIdToResponseMap.set(r,n)})}async request(t){if(this.channel||await this.initialize(),!this.channel)throw new Error("Failed to create channel");const{channel:n,requestIdToResponseMap:r,timeout:o}=this;await n.waitTilReady();const s=this.generateTextId();r.set(s,!0),n.send(JSON.stringify({id:s,data:t}));const g=new Date().getTime();for(;new Date().getTime()<g+o;)if(await delay$1(50),r.has(s)){const l=r.get(s);if(l!==!0){r.delete(s);const{data:u,error:c}=l;if(u)return u;if(c)throw console.error({name:"AdapterError",message:c}),new Error("Text request datachannel adapter error")}}throw r.delete(s),console.error({name:"TimeoutError",message:`Request timed out after ${o/1e3} seconds`}),new Error("Text request datachannel request timed out")}}class BaseDevice extends EventEmitter{constructor(){super(...arguments);he(this,"rtcClient");he(this,"remoteDevicePeerId",null);he(this,"realtimeListeners",[]);he(this,"connectionMonitorInterval");he(this,"handleMessage",(n,r)=>{this.realtimeListeners.forEach(o=>o(n,r))})}stopConnectionMonitoring(){clearInterval(this.connectionMonitorInterval),this.connectionMonitorInterval=void 0}assertNotCancelled(n){if(n)throw new Error("Cancelled by deadline")}getRealtimeStatus(){if(this.rtcClient&&this.remoteDevicePeerId)return this.rtcClient.getConnectionStatus(this.remoteDevicePeerId);throw new Error("Realtime connection hasn't been started")}getRealtimePing(){if(this.rtcClient&&this.remoteDevicePeerId)return this.rtcClient.getPing(this.remoteDevicePeerId);throw new Error("Realtime connection hasn't been started")}addRealtimeListener(n){this.realtimeListeners.push(n)}removeRealtimeListener(n){const r=this.realtimeListeners.indexOf(n);if(r===-1)throw new Error("Could not find realtime listener to remove");this.realtimeListeners.splice(r,1)}async getRealtimeManipulators(){var o;const n=await this.getConfiguration(),r=[];for(const s of(o=n.teleop.rosStreams)!=null?o:[])s.topicType=="sensor_msgs/JointState"&&r.push(new Manipulator(this,{currentJointStateStream:{name:s.topicName},plannedJointStateStream:s.plannedTopic?{name:s.plannedTopic}:void 0,planValidStream:s.planValidTopic?{name:s.planValidTopic}:void 0,endEffectorStream:s.endEffectorTopic?{name:s.endEffectorTopic}:void 0,endEffectorLinkName:s.endEffectorLinkName,baseReferenceFrame:s.baseReferenceFrame,localFrame:s.localFrame}));return r}async getRealtimeVideoStreams(){var o,s,g,l,u,c;const n=await this.getConfiguration(),r=[];for(const d of(s=(o=n.teleop)==null?void 0:o.hardwareStreams)!=null?s:[])d.rtcStreamType==="h264-video-frame"&&r.push({name:d.name});for(const d of(l=(g=n.teleop)==null?void 0:g.rosStreams)!=null?l:[])d.topicType=="formant/H264VideoFrame"&&r.push({name:d.topicName}),(d.topicType==="sensor_msgs/Image"||d.topicType==="sensor_msgs/CompressedImage")&&d.encodeVideo&&r.push({name:d.topicName});for(const d of(c=(u=n.teleop)==null?void 0:u.customStreams)!=null?c:[])d.rtcStreamType==="h264-video-frame"&&r.push({name:d.name});return r}createCustomRequestDataChannel(n,r=3e3){return new TextRequestDataChannel(this,n,r)}createCustomBinaryRequestDataChannel(n,r=3e3){return new BinaryRequestDataChannel(this,n,r)}async startListeningToRealtimeVideo(n){const r=defined$1(this.rtcClient,"Realtime connection has not been started"),o=await this.getRemotePeer();r.controlRemoteStream(defined$1(o).id,{streamName:n.name,enable:!0,pipeline:"rtc"})}async stopListeningToRealtimeVideo(n){const r=defined$1(this.rtcClient,"Realtime connection has not been started"),o=await this.getRemotePeer();r.controlRemoteStream(defined$1(o).id,{streamName:n.name,enable:!1,pipeline:"rtc"})}async startListeningToRealtimeDataStream(n){const r=defined$1(this.rtcClient,"Realtime connection has not been started"),o=await this.getRemotePeer();r.controlRemoteStream(defined$1(o).id,{streamName:n.name,enable:!0,pipeline:"rtc"})}async stopListeningToRealtimeDataStream(n){const r=defined$1(this.rtcClient,"Realtime connection has not been started"),o=await this.getRemotePeer();r.controlRemoteStream(defined$1(o).id,{streamName:n.name,enable:!1,pipeline:"rtc"})}async enableRealtimeTelemetryPriorityIngestion(n){const r=defined$1(this.rtcClient,"Realtime connection has not been started"),o=await this.getRemotePeer();r.controlRemoteStream(defined$1(o).id,{streamName:n,enablePriorityUpload:!0,pipeline:"telemetry"})}async disableRealtimeTelemetryPriorityIngestion(n){const r=defined$1(this.rtcClient,"Realtime connection has not been started"),o=await this.getRemotePeer();r.controlRemoteStream(defined$1(o).id,{streamName:n,enablePriorityUpload:!1,pipeline:"telemetry"})}async changeStreamAudioType(n,r){const o=defined$1(this.rtcClient,"Realtime connection has not been started"),s=await this.getRemotePeer();o.controlRemoteStream(defined$1(s).id,{streamName:n,setAudioFormat:r})}async createCustomDataChannel(n,r){const o=defined$1(this.rtcClient,"Realtime connection has not been started"),s=await this.getRemotePeer(),g=await new Promise(l=>{o.createCustomDataChannel(defined$1(s).id,n,{ordered:!0,...r},!1,(u,c)=>{const d=new DataChannel(c);l(d)})});return await g.waitTilReady(),g}async sendRealtimeMessage(n,r={channelLabel:"stream.reliable"}){const o=defined$1(this.rtcClient,"Realtime connection has not been started"),s=await this.getRemotePeer();o.send(defined$1(s).id,n,r)}async getRealtimeAudioStreams(){var o,s,g,l,u,c;const n=await this.getConfiguration(),r=[];for(const d of(s=(o=n.teleop)==null?void 0:o.hardwareStreams)!=null?s:[])d.rtcStreamType==="audio-chunk"&&r.push({name:d.name});for(const d of(l=(g=n.teleop)==null?void 0:g.rosStreams)!=null?l:[])d.topicType=="audio_common_msgs/AudioData"&&r.push({name:d.topicName});for(const d of(c=(u=n.teleop)==null?void 0:u.customStreams)!=null?c:[])d.rtcStreamType==="audio-chunk"&&r.push({name:d.name});return r}}class Device extends BaseDevice{constructor(t,n,r,o){super(),this.id=t,this.name=n,this.organizationId=r,this.tags=o}async getLatestTelemetry(){return(await(await fetch(`${exports.FORMANT_API_URL}/v1/queries/stream-current-value`,{method:"POST",body:JSON.stringify({deviceIds:[this.id]}),headers:{"Content-Type":"application/json",Authorization:"Bearer "+Authentication.token}})).json()).items}async getConfiguration(t=!1){let n=await fetch(`${exports.FORMANT_API_URL}/v1/admin/devices/${this.id}`,{method:"GET",headers:{"Content-Type":"application/json",Authorization:"Bearer "+Authentication.token}});const r=await n.json();if(!r.state.reportedConfiguration)throw new Error("Device has no configuration, has it ever been turned on?");const o=t?r.desiredConfigurationVersion:r.state.reportedConfiguration.version;return n=await fetch(`${exports.FORMANT_API_URL}/v1/admin/devices/${this.id}/configurations/${o}`,{method:"GET",headers:{"Content-Type":"application/json",Authorization:"Bearer "+Authentication.token}}),(await n.json()).document}async getAgentVersion(){var r;const n=await(await fetch(`${exports.FORMANT_API_URL}/v1/admin/devices/${this.id}`,{method:"GET",headers:{"Content-Type":"application/json",Authorization:"Bearer "+Authentication.token}})).json();return(r=n==null?void 0:n.state)==null?void 0:r.agentVersion}async getFileUrl(t){return(await(await fetch(`${exports.FORMANT_API_URL}/v1/admin/files/query`,{method:"POST",body:JSON.stringify({fileIds:[t]}),headers:{"Content-Type":"application/json",Authorization:"Bearer "+Authentication.token}})).json()).fileUrls}async startRealtimeConnection(t={}){if(console.debug(`${new Date().toISOString()} :: Connection start requested`),this.rtcClient&&this.connectionMonitorInterval!==void 0)throw new Error(`Already created realtime connection to device ${this.id}`);this.rtcClient&&console.warn("overwriting existing rtcClient due to missing connectionMonitorInterval");const{sessionType:n,deadlineMs:r=1e4,maxConnectRetries:o=3}=typeof t=="number"?{sessionType:t}:t,g=getRtcClientPool({sessionType:n}).get(this.handleMessage);let l=!1;const u=new Promise((d,B)=>setTimeout(()=>{l=!0,B(new Error("Connection timed out: the connection could not be finalized in time, possibly due to network issues or misconfigured settings."))},r)),c=async()=>{if("isReady"in g)for(;!g.isReady();)this.assertNotCancelled(l),await delay$1(100);const d=await this.getRemoteDevicePeerId(g);this.assertNotCancelled(l);let B;for(let U=0;U<o&&(B=await g.connect(d),!B);U++)delay$1(100),this.assertNotCancelled(l);if(!B)throw new Error(`Session could not be created: exhausted ${o} retries`);let Q=0;for(;!l&&g.getConnectionStatus(d)!=="connected";)await delay$1(100),Q+=1;return this.assertNotCancelled(l),console.debug(`${new Date().toISOString()} :: Connection completed after ${Q} retries`),d};return Promise.race([c(),u]).then(d=>{this.remoteDevicePeerId=d,this.initConnectionMonitoring(),this.rtcClient=g,this.emit("connect")}).catch(d=>{throw console.debug(`${new Date().toISOString()} :: Connection failed: %o`,d),this.remoteDevicePeerId=null,g.shutdown().catch(B=>{console.error("rtcClient cannot shutdown: %o",B)}),this.emit("connection_failed",d),d})}async getRemoteDevicePeerId(t){const r=(await t.getPeers()).find(o=>o.deviceId===this.id);if(!isRtcPeer(r))throw new Error("Cannot find peer, is the robot offline?");return r.id}initConnectionMonitoring(){this.connectionMonitorInterval=setInterval(async()=>{let t=!1;if(this.rtcClient){const r=this.rtcClient.getConnections().find(o=>o.getRemotePeerId()===this.remoteDevicePeerId&&o.isActive());(r===void 0||!r.isReady())&&(console.debug(`${new Date().toISOString()} :: data channel closed`),t=!0)}(!this.rtcClient||!this.remoteDevicePeerId||await this.rtcClient.getConnectionStatsInfo(this.remoteDevicePeerId)===void 0||t)&&(this.emit("disconnect"),this.stopRealtimeConnection().catch(n=>{console.error(n)}))},1e3)}async getRemotePeer(){const n=(await defined$1(this.rtcClient,"Realtime connection has not been started").getPeers()).find(r=>r.deviceId===this.id);return defined$1(n,"Could not find remote peer for device "+this.id)}async stopRealtimeConnection(){let t=!1;if(this.rtcClient){this.stopConnectionMonitoring(),this.remoteDevicePeerId?(await this.rtcClient.disconnect(this.remoteDevicePeerId),this.remoteDevicePeerId=null):t=!0;try{await this.rtcClient.shutdown()}finally{this.rtcClient=void 0}}if(t)throw new Error(`Realtime connection hasn't been started for ${this.id}`)}async isInRealtimeSession(){const t=await getPeers(),n=await getRealtimeSessions(),r=t.find(o=>o.deviceId===this.id);return r?n[r.id].length>0:!1}async getAvailableCommands(t=!0){return(await(await fetch(`${exports.FORMANT_API_URL}/v1/admin/command-templates/`,{method:"GET",headers:{"Content-Type":"application/json",Authorization:"Bearer "+Authentication.token}})).json()).items.map(o=>({name:o.name,id:o.id,command:o.command,description:o.description,parameterEnabled:o.parameterEnabled,parameterValue:o.parameterValue,parameterMeta:o.parameterMeta,enabled:o.enabled,tags:o.tags})).filter(o=>t?!0:o.enabled)}async sendCommand(t,n,r,o,s){var B;const l=(await this.getAvailableCommands(!1)).find(Q=>s?Q.id===s:Q.name===t);if(!l)throw new Error(`Could not find command with name "${t}"`);let u="";n===void 0?l.parameterEnabled&&l.parameterValue&&(u=l.parameterValue):u=n;let c={value:u,scrubberTime:(r||new Date).toISOString(),meta:{...l.parameterMeta,...o}};return await fetch(`${exports.FORMANT_API_URL}/v1/admin/commands`,{method:"POST",body:JSON.stringify({commandTemplateId:l.id,organizationId:this.organizationId,deviceId:this.id,command:l.command,parameter:c,userId:(B=Authentication.currentUser)==null?void 0:B.id}),headers:{"Content-Type":"application/json",Authorization:"Bearer "+Authentication.token}})}async getCommand(t){return await fetch(`${exports.FORMANT_API_URL}/v1/admin/commands/${t}`,{method:"GET",headers:{"Content-Type":"application/json",Authorization:"Bearer "+Authentication.token}})}async createCaptureStream(t){const r=await(await fetch(`${exports.FORMANT_API_URL}/v1/admin/capture-sessions`,{method:"POST",body:JSON.stringify({deviceId:this.id,streamName:t,tags:{}}),headers:{"Content-Type":"application/json",Authorization:"Bearer "+Authentication.token}})).json();return new CaptureStream(r)}async getTelemetry(t,n,r,o,s,g,l){if(s!==void 0||g!==void 0)throw new Error("Limit and offset are not supported in this method");return await getTelemetry(this.id,t,n,r,o,l)}async queryEvents(t){if(t.deviceIds)throw new Error("Cannot filter multiple devices via Device class");return t.deviceIds=[this.id],queryEvents(t)}async getTelemetryStreams(){var l,u;const t=await this.getConfiguration(),n=await fetch(`${exports.FORMANT_API_URL}/v1/queries/metadata/stream-names`,{method:"POST",body:JSON.stringify({deviceIds:[this.id]}),headers:{"Content-Type":"application/json",Authorization:"Bearer "+Authentication.token}}),r=[],o=[];return(u=(l=t.telemetry)==null?void 0:l.streams)==null||u.forEach(c=>{c.disabled!==!0&&r.push(c.name),c.onDemand===!0&&o.push(c.name)}),console.log(o),(await n.json()).items.filter(c=>!r.includes(c)).map(c=>({name:c,onDemand:o.includes(c)}))}async createInterventionRequest(t,n,r,o){return await(await fetch(`${exports.FORMANT_API_URL}/v1/admin/intervention-requests`,{method:"POST",body:JSON.stringify({message:t,interventionType:n,time:new Date().toISOString(),deviceId:this.id,tags:o,data:r}),headers:{"Content-Type":"application/json",Authorization:"Bearer "+Authentication.token}})).json()}async addInterventionResponse(t,n,r){return await(await fetch(`${exports.FORMANT_API_URL}/v1/admin/intervention-responses`,{method:"POST",body:JSON.stringify({interventionId:t,interventionType:n,data:r}),headers:{"Content-Type":"application/json",Authorization:"Bearer "+Authentication.token}})).json()}async getAnnotationCount(t,n){return await getAnnotationCount({...t,deviceIds:[this.id]},n)}async getAnnotationCountByIntervals(t,n,r){return await getAnnotationCountByIntervals({...t,deviceIds:[this.id]},n,r)}async eventsCounter(t,n,r,o,s){return await eventsCounter(t,n,r,o,{...s,deviceIds:[this.id]})}async createShareLink(t,n){return t.scope.deviceIds=[this.id],await createShareLink(t,n)}}he(Device,"createDevice",createDevice),he(Device,"patchDevice",patchDevice),he(Device,"getDevicesData",getDevicesData),he(Device,"queryDevicesData",queryDevicesData),he(Device,"disableDevice",disableDevice);class PeerDevice extends BaseDevice{constructor(n){super();he(this,"id");he(this,"telemetryStreamActive",!1);he(this,"streamTelemetry",{});this.peerUrl=n}async getLatestTelemetry(){this.telemetryStreamActive||this.subscribeToTelemetry();const n=this.streamTelemetry;return Object.entries(n).map(([o,s])=>({deviceId:this.id,streamName:o,streamType:"json",currentValue:s,currentValueTime:s.timestamp,tags:{}}))}async getTelemetry(n,r,o,s,g,l,u){if(Array.isArray(n))throw new Error("Multiple stream names not supported");if(s)throw new Error("Tags not supported");if(u&&g===void 0)g=1;else if(u&&g!==void 0)throw new Error("latestOnly and limit cannot be used together");let c=`${this.peerUrl}/v1/querydatapoints?stream_name=${n}&start=${r.toISOString()}&end=${o.toISOString()}`;g!=null&&g>0&&(c+=`&limit=${g}`),l!=null&&l>=0&&(c+=`&offset=${l}`);const B=await(await fetch(c)).json(),Q=[];for(const U of B.results){const p=parseInt(U.timestamp),f=U.tags.data_type;delete U.tags.data_type,Q.push({deviceId:this.id,name:U.stream,points:[[p,this.getPointPayload(f,U)]],tags:U.tags,type:f})}return Q.reverse()}async queryEvents(n){const r=["id","viewed","keyword","message","sort","eventTypes","notificationEnabled","userIds","annotationTemplateIds","disableNullMatches","severities","deviceIds","names","types","tags","notNames"];this.checkKeysAndThrow(n,r);let o=`${this.peerUrl}/v1/queryevents?start=${n.start}&end=${n.end}`;n.count!=null&&n.count>0&&(o+=`&limit=${n.count}`),n.offset!=null&&n.offset>=0&&(o+=`&offset=${n.offset}`);const g=await(await fetch(o)).json(),l=[];for(const u of g.results){const c=parseInt(u.timestamp),d={deviceId:this.id,time:new Date(c).toISOString(),message:u.message,notificationEnabled:u.notificationEnabled,type:u.type,tags:u.tags};u.id!==""&&(d.id=u.id),u.type!==""&&(d.type=u.type),u.streamName!==""&&(d.streamName=u.streamName),u.streamType!==""&&(d.streamType=u.streamType),u.severity!==""&&(d.severity=u.severity.toLowerCase()),u.tags&&(d.tags=u.tags),u.endTimestamp!=="0"&&(d.endTime=new Date(parseInt(u.endTimestamp)).toISOString()),l.push(d)}return l.reverse()}checkKeysAndThrow(n,r){const o=r.filter(s=>s in n);if(o.length>0)throw new Error(`Filters not currently supported: ${o.join(", ")}.`)}getPointPayload(n,r){switch(n){case"numeric":return r.numeric.value;case"numeric set":return r.numericSet.numerics;case"text":return r.text.value;case"json":return r.json.value;case"bitset":const o=[],s=[];for(const g of r.bitset.bits)o.push(g.key),s.push(g.value);return{keys:o,values:s};case"location":return r.location;case"health":return r.health;case"battery":return r.battery;default:return{}}}subscribeToTelemetry(){this.telemetryStreamActive=!0;let n=0;const r=new XMLHttpRequest;r.responseType="text",r.addEventListener("error",o=>{this.handleXHRError("error")}),r.addEventListener("abort",o=>{this.handleXHRError("abort")}),r.addEventListener("timeout",o=>{this.handleXHRError("timeout")}),r.addEventListener("readystatechange",o=>{r.readyState===XMLHttpRequest.DONE&&this.handleXHRError("closed")}),r.addEventListener("progress",o=>{const s=o.loaded,g=s-n;n=s,r.responseText.substr(-g).split(`
|
|
62
|
+
`),Error.captureStackTrace(this,r)}}e.exports=o=>{if(o.length>2)throw new r(o);function s(l={}){this.options=l}function g(l){return new s(l)}return s.prototype.transform=o,g.Format=s,g}},function(e,t,n){function r(g,l){if(!(g instanceof l))throw new TypeError("Cannot call a class as a function")}function o(g,l){for(var u=0;u<l.length;u++){var c=l[u];c.enumerable=c.enumerable||!1,c.configurable=!0,"value"in c&&(c.writable=!0),Object.defineProperty(g,c.key,c)}}var s=n(87);e.exports=function(){function g(){var c=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};r(this,g),this.loggers=new Map,this.options=c}var l,u;return l=g,(u=[{key:"add",value:function(c,d){var B=this;if(!this.loggers.has(c)){var Q=(d=Object.assign({},d||this.options)).transports||this.options.transports;d.transports=Q?Q.slice():[];var U=s(d);U.on("close",function(){return B._delete(c)}),this.loggers.set(c,U)}return this.loggers.get(c)}},{key:"get",value:function(c,d){return this.add(c,d)}},{key:"has",value:function(c){return!!this.loggers.has(c)}},{key:"close",value:function(c){var d=this;if(c)return this._removeLogger(c);this.loggers.forEach(function(B,Q){return d._removeLogger(Q)})}},{key:"_removeLogger",value:function(c){this.loggers.has(c)&&(this.loggers.get(c).close(),this._delete(c))}},{key:"_delete",value:function(c){this.loggers.delete(c)}}])&&o(l.prototype,u),Object.defineProperty(l,"prototype",{writable:!1}),g}()},function(e,t,n){(function(r){const o=n(51),s=/^([A-Za-z0-9+/]{4})*([A-Za-z0-9+/]{4}|[A-Za-z0-9+/]{3}=|[A-Za-z0-9+/]{2}==)$/;e.exports=function(g,l,u,c){let d,B,Q=!1,U=!1;const p=n(93);function f(J){c(l,J)}function b(J,m){let y=`"${l}" ${m}`;throw J&&(y=""+y),B&&(y=`${y}. An example of a valid value would be: ${B}`),new o(y)}const M={convertFromBase64:function(){return f("marking for base64 conversion"),Q=!0,M},default:function(J){if(typeof J=="number")d=J.toString();else if(Array.isArray(J)||typeof J=="object"&&J!==null)d=JSON.stringify(J);else{if(typeof J!="string")throw new o("values passed to default() must be of Number, String, Array, or Object type");d=J}return f(`setting default value to "${d}"`),M},required:function(J){return J===void 0?(f("marked as required"),U=!0):(f("setting required flag to "+J),U=J),M},example:function(J){return B=J,M}};return Object.entries({...p,...u}).forEach(([J,m])=>{M[J]=function(y){return function(){let h=g[l];if(f(`will be read from the environment using "${y.name}" accessor`),h===void 0)if(d===void 0&&U)f("was not found in the environment, but is required to be set"),b(void 0,"is a required variable, but it was not set");else{if(d===void 0)return void f("was not found in the environment, but is not required. returning undefined");f(`was not found in the environment, parsing default value "${d}" instead`),h=d}U&&(f("verifying variable value is not an empty string"),h.trim().length===0&&b(void 0,"is a required variable, but its value was empty")),Q&&(f("verifying variable is a valid base64 string"),h.match(s)||b(h,"should be a valid base64 string if using convertFromBase64"),f("converting from base64 to utf8 string"),h=r.from(h,"base64").toString());const T=[h].concat(Array.prototype.slice.call(arguments));try{f(`passing value "${h}" to "${y.name}" accessor`);const I=y.apply(y,T);return f("parsed successfully, returning "+I),I}catch(I){b(h,I.message)}}}(m)}),M}}).call(this,n(5).Buffer)},function(e,t,n){const r=n(34);e.exports=function(o,s){return s=s||",",o.length?r(o).split(s).filter(Boolean):[]}},function(e,t,n){e.exports=function(r){const o=r.toLowerCase();if(o!=="false"&&o!=="true")throw new Error('should be either "true", "false", "TRUE", or "FALSE"');return o!=="false"}},function(e,t,n){e.exports=function(r){const o=r.toLowerCase();if(["false","0","true","1"].indexOf(o)===-1)throw new Error('should be either "true", "false", "TRUE", "FALSE", 1, or 0');return!(o==="0"||o==="false")}},function(e,t,n){const r=n(94);e.exports=function(o){var s=r(o);if(s>65535)throw new Error("cannot assign a port number greater than 65535");return s}},function(e,t,n){const r=n(34);e.exports=function(o,s){const g=r(o);if(s.indexOf(g)<0)throw new Error(`should be one of [${s.join(", ")}]`);return g}},function(e,t,n){const r=n(53);e.exports=function(o){const s=r(o);if(s>0)throw new Error("should be a negative float");return s}},function(e,t,n){const r=n(53);e.exports=function(o){const s=r(o);if(s<0)throw new Error("should be a positive float");return s}},function(e,t,n){const r=n(52);e.exports=function(o){const s=r(o);if(s>0)throw new Error("should be a negative integer");return s}},function(e,t,n){const r=n(54);e.exports=function(o){var s=r(o);if(!Array.isArray(s))throw new Error("should be a parseable JSON Array");return s}},function(e,t,n){const r=n(54);e.exports=function(o){var s=r(o);if(Array.isArray(s))throw new Error("should be a parseable JSON Object");return s}},function(e,t,n){e.exports=function(r,o){try{RegExp(void 0,o)}catch{throw new Error("invalid regexp flags")}try{return new RegExp(r,o)}catch{throw new Error("should be a valid regexp")}}},function(e,t,n){const r=n(95);e.exports=function(o){return r(o).toString()}},function(e,t,n){const r=n(34),o=/^(?:[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*|"(?:[\u0001-\u0008\u000b\u000c\u000e-\u001f\u0021\u0023-\u005b\u005d-\u007f]|\\[\u0001-\u0009\u000b\u000c\u000e-\u007f])*")@(?:(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?|\[(?:(?:(2(5[0-5]|[0-4][0-9])|1[0-9][0-9]|[1-9]?[0-9]))\.){3}(?:(2(5[0-5]|[0-4][0-9])|1[0-9][0-9]|[1-9]?[0-9])|[a-z0-9-]*[a-z0-9]:(?:[\u0001-\u0008\u000b\u000c\u000e-\u001f\u0021-\u005a\u0053-\u007f]|\\[\u0001-\u0009\u000b\u000c\u000e-\u007f])+)\])$/;e.exports=function(s){const g=r(s);if(!o.test(g))throw new Error("should be a valid email address");return g}},function(e,t,n){e.exports=function(r,o){return function(s,g){o&&o.match(/prod|production/)||r(`env-var (${s}): ${g}`)}}},function(e,t,n){(function(r){(function(){var o,s,g,l,u,c;typeof performance!="undefined"&&performance!==null&&performance.now?e.exports=function(){return performance.now()}:r!=null&&r.hrtime?(e.exports=function(){return(o()-u)/1e6},s=r.hrtime,l=(o=function(){var d;return 1e9*(d=s())[0]+d[1]})(),c=1e9*r.uptime(),u=l-c):Date.now?(e.exports=function(){return Date.now()-g},g=Date.now()):(e.exports=function(){return new Date().getTime()-g},g=new Date().getTime())}).call(this)}).call(this,n(2))},function(e,t,n){(function(r){(function(o){function s(l){if((l=l===void 0?"utf-8":l)!=="utf-8")throw new RangeError("Failed to construct 'TextEncoder': The encoding label provided ('"+l+"') is invalid.")}function g(l,u){if(u=u===void 0?{fatal:!1}:u,(l=l===void 0?"utf-8":l)!=="utf-8")throw new RangeError("Failed to construct 'TextDecoder': The encoding label provided ('"+l+"') is invalid.");if(u.fatal)throw Error("Failed to construct 'TextDecoder': the 'fatal' option is unsupported.")}if(o.TextEncoder&&o.TextDecoder)return!1;Object.defineProperty(s.prototype,"encoding",{value:"utf-8"}),s.prototype.encode=function(l,u){if((u=u===void 0?{stream:!1}:u).stream)throw Error("Failed to encode: the 'stream' option is unsupported.");u=0;for(var c=l.length,d=0,B=Math.max(32,c+(c>>1)+7),Q=new Uint8Array(B>>3<<3);u<c;){var U=l.charCodeAt(u++);if(55296<=U&&56319>=U){if(u<c){var p=l.charCodeAt(u);(64512&p)==56320&&(++u,U=((1023&U)<<10)+(1023&p)+65536)}if(55296<=U&&56319>=U)continue}if(d+4>Q.length&&(B+=8,B=(B*=1+u/l.length*2)>>3<<3,(p=new Uint8Array(B)).set(Q),Q=p),(4294967168&U)==0)Q[d++]=U;else{if(!(4294965248&U))Q[d++]=U>>6&31|192;else if(!(4294901760&U))Q[d++]=U>>12&15|224,Q[d++]=U>>6&63|128;else{if(4292870144&U)continue;Q[d++]=U>>18&7|240,Q[d++]=U>>12&63|128,Q[d++]=U>>6&63|128}Q[d++]=63&U|128}}return Q.slice(0,d)},Object.defineProperty(g.prototype,"encoding",{value:"utf-8"}),Object.defineProperty(g.prototype,"fatal",{value:!1}),Object.defineProperty(g.prototype,"ignoreBOM",{value:!1}),g.prototype.decode=function(l,u){if((u=u===void 0?{stream:!1}:u).stream)throw Error("Failed to decode: the 'stream' option is unsupported.");u=0;for(var c=(l=new Uint8Array(l)).length,d=[];u<c;){var B=l[u++];if(B===0)break;if(!(128&B))d.push(B);else if((224&B)==192){var Q=63&l[u++];d.push((31&B)<<6|Q)}else if((240&B)==224){Q=63&l[u++];var U=63&l[u++];d.push((31&B)<<12|Q<<6|U)}else(248&B)==240&&(65535<(B=(7&B)<<18|(Q=63&l[u++])<<12|(U=63&l[u++])<<6|63&l[u++])&&(B-=65536,d.push(B>>>10&1023|55296),B=56320|1023&B),d.push(B))}return String.fromCharCode.apply(null,d)},o.TextEncoder=s,o.TextDecoder=g})(typeof window!="undefined"?window:r!==void 0?r:this)}).call(this,n(6))},function(e,t,n){n.r(t),n.d(t,"AuthClient",function(){return s}),n.d(t,"RtcSignalingClient",function(){return l}),n.d(t,"Credentials",function(){return C}),n.d(t,"SignalingPromiseClient",function(){return W.SignalingPromiseClient}),n.d(t,"RtcClient",function(){return Pt}),n.d(t,"RtcClientV1",function(){return Dt}),n.d(t,"createRtcStreamMessage",function(){return Ct});var r=n(26),o=function(Re,Z,L,q){return new(L||(L=Promise))(function(ie,ae){function ue(ce){try{fe(q.next(ce))}catch(le){ae(le)}}function Ue(ce){try{fe(q.throw(ce))}catch(le){ae(le)}}function fe(ce){var le;ce.done?ie(ce.value):(le=ce.value,le instanceof L?le:new L(function(me){me(le)})).then(ue,Ue)}fe((q=q.apply(Re,Z||[])).next())})};class s extends r.a{adminSignup(Z,L){return o(this,void 0,void 0,function*(){return yield this.fetch("auth/admin-signup",{token:L,method:"POST",body:Z})})}login(Z){return o(this,void 0,void 0,function*(){return yield this.fetch("auth/login",{method:"POST",body:Z,allowUnsafeRetries:!0})})}loginWithGoogleToken(Z){return o(this,void 0,void 0,function*(){return yield this.fetch("auth/login-google",{method:"POST",body:Z,allowUnsafeRetries:!0})})}refresh(Z,L){return o(this,void 0,void 0,function*(){return yield this.fetch("auth/refresh",{method:"POST",body:{refreshToken:Z,tokenExpirationSeconds:L},allowUnsafeRetries:!0})})}respondToNewPasswordRequiredChallenge(Z){return o(this,void 0,void 0,function*(){return yield this.fetch("auth/respond-to-new-password-required-challenge",{method:"POST",body:Z})})}forgotPassword(Z){return o(this,void 0,void 0,function*(){return yield this.fetch("auth/forgot-password",{method:"POST",body:{email:Z}})})}confirmForgotPassword(Z){return o(this,void 0,void 0,function*(){return yield this.fetch("auth/confirm-forgot-password",{method:"POST",body:Z})})}resendInvitation(Z){return o(this,void 0,void 0,function*(){return yield this.fetch("auth/resend-invitation",{method:"POST",body:{email:Z}})})}changePassword({token:Z,refreshToken:L,currentPassword:q,newPassword:ie}){return o(this,void 0,void 0,function*(){return yield this.fetch("auth/change-password",{token:Z,method:"POST",body:{refreshToken:L,currentPassword:q,newPassword:ie}})})}getDeviceCredentials(Z){return o(this,void 0,void 0,function*(){return yield this.fetch("auth/device-credentials",{token:Z,method:"POST",allowUnsafeRetries:!0})})}impersonate(Z,L){return o(this,void 0,void 0,function*(){return yield this.fetch("auth/impersonate",{token:Z,method:"POST",allowUnsafeRetries:!0,body:{userId:L}})})}createServiceAccount(Z,L,q,ie){return o(this,void 0,void 0,function*(){return yield this.fetch("auth/service-account",{token:Z,method:"POST",allowUnsafeRetries:!0,body:{name:L,roleId:q,tags:ie}})})}getFeatures(Z){return o(this,void 0,void 0,function*(){return(yield this.fetch("auth/features",{token:Z})).features})}checkSso(Z,L){return o(this,void 0,void 0,function*(){return yield this.fetch("auth/check-sso",{method:"POST",body:{email:Z,allowUserAutoCreation:L}})})}loginWithSso(Z,L){return o(this,void 0,void 0,function*(){return yield this.fetch("auth/login-sso",{method:"POST",body:{token:Z,refreshToken:L}})})}}var g=function(Re,Z,L,q){return new(L||(L=Promise))(function(ie,ae){function ue(ce){try{fe(q.next(ce))}catch(le){ae(le)}}function Ue(ce){try{fe(q.throw(ce))}catch(le){ae(le)}}function fe(ce){var le;ce.done?ie(ce.value):(le=ce.value,le instanceof L?le:new L(function(me){me(le)})).then(ue,Ue)}fe((q=q.apply(Re,Z||[])).next())})};class l extends r.a{createPeer(Z,L){return g(this,void 0,void 0,function*(){return yield this.fetch("peers",{token:Z,method:"POST",body:L})})}getPeers(Z){return g(this,void 0,void 0,function*(){return(yield this.fetch("peers",{token:Z})).items})}refreshPeer(Z,L){return g(this,void 0,void 0,function*(){yield this.fetch(`peers/${L}/refresh`,{token:Z,method:"POST",allowUnsafeRetries:!0})})}createSession(Z,L){return g(this,void 0,void 0,function*(){return yield this.fetch("sessions",{token:Z,method:"POST",body:L})})}refreshSession(Z,L){return g(this,void 0,void 0,function*(){yield this.fetch(`sessions/${L}/refresh`,{token:Z,method:"POST",allowUnsafeRetries:!0})})}deleteSession(Z,L){return g(this,void 0,void 0,function*(){yield this.fetch("sessions/"+L,{token:Z,method:"DELETE",allowUnsafeRetries:!0})})}getSessions(Z){return g(this,void 0,void 0,function*(){return(yield this.fetch("sessions",{token:Z})).items})}getIceServers(Z){return g(this,void 0,void 0,function*(){return(yield this.fetch("ice-servers",{token:Z})).items})}addSignals(Z,L,q){return g(this,void 0,void 0,function*(){yield this.fetch(`sessions/${L}/add-signals`,{token:Z,method:"POST",body:q})})}takeSignals(Z,L){return g(this,void 0,void 0,function*(){return(yield this.fetch(`sessions/${L}/take-signals`,{token:Z,method:"POST"})).items})}}var u=n(1),c=n(9),d=n(15),B=n.n(d),Q=n(101),U=n.n(Q),p=n(3),f=n(0),b=function(Re,Z,L,q){return new(L||(L=Promise))(function(ie,ae){function ue(ce){try{fe(q.next(ce))}catch(le){ae(le)}}function Ue(ce){try{fe(q.throw(ce))}catch(le){ae(le)}}function fe(ce){var le;ce.done?ie(ce.value):(le=ce.value,le instanceof L?le:new L(function(me){me(le)})).then(ue,Ue)}fe((q=q.apply(Re,Z||[])).next())})};class M extends class{constructor(Z,L){this.type=Z,this.name=L}}{constructor(Z){super("simple","LogReporter"),this.message=Z}send(Z){return b(this,void 0,void 0,function*(){var L,q;f.a.debug(this.message,(L=Z.reduce((ie,ae)=>Object.assign(Object.assign({},ie),{[ae.name]:ae.stat}),{}),q=ie=>{const{sum:ae,count:ue}=ie,Ue=ae/ue;return Object.assign(Object.assign({},ie),{average:Ue})},Object.keys(L).reduce((ie,ae)=>Object.assign(Object.assign({},ie),{[ae]:q(L[ae])}),{})))})}}const J=/^[a-zA-Z0-9-_.,:?'"()@\/\\#$+ ]{1,255}$/,m=/^[*a-zA-Z0-9-_.,:?'"()@\/\\#$+ ]{1,255}$/;function y(Re,Z=!1){return!!(Re!=null&&Re.match(Z?m:J))}var h=function(Re,Z,L,q){return new(L||(L=Promise))(function(ie,ae){function ue(ce){try{fe(q.next(ce))}catch(le){ae(le)}}function Ue(ce){try{fe(q.throw(ce))}catch(le){ae(le)}}function fe(ce){var le;ce.done?ie(ce.value):(le=ce.value,le instanceof L?le:new L(function(me){me(le)})).then(ue,Ue)}fe((q=q.apply(Re,Z||[])).next())})};function T({func:Re,delay:Z,immediate:L=!1}){let q=!1,ie=setTimeout(function ue(){return h(this,void 0,void 0,function*(){if(q)return;const Ue=new Date().getTime();try{ae=Re(),yield ae}finally{if(!q){const fe=new Date().getTime();ie=setTimeout(ue,Math.max(Z-(fe-Ue),0))}}})},L?0:Z),ae=Promise.resolve();return{stop(){return h(this,void 0,void 0,function*(){q=!0,clearTimeout(ie),yield ae})}}}var I=function(Re,Z,L,q){return new(L||(L=Promise))(function(ie,ae){function ue(ce){try{fe(q.next(ce))}catch(le){ae(le)}}function Ue(ce){try{fe(q.throw(ce))}catch(le){ae(le)}}function fe(ce){var le;ce.done?ie(ce.value):(le=ce.value,le instanceof L?le:new L(function(me){me(le)})).then(ue,Ue)}fe((q=q.apply(Re,Z||[])).next())})};const X=n(231);class F{constructor(Z){this.buffer={},this.reporters=[],this.flushInterval=T({func:()=>this.flushStats(),delay:F.samplePeriodMs}),this.tags=this.filterTags((Z==null?void 0:Z.tags)||{app:p.a,version:p.k,namespace:p.j})}shutdown(){return I(this,void 0,void 0,function*(){yield this.flushInterval.stop(),yield this.flushStats(),yield Object(c.a)(2*u.a.second)})}aggregate(Z,L,q){this.addToBuffer(this.buffer,this.encodeKey({metric:Z,tags:this.filterTags(q||{})}),typeof L=="number"?{min:L,max:L,sum:L,count:1}:L)}increment(Z,L){this.aggregate(Z,1,L)}timer(Z,L,q){return I(this,void 0,void 0,function*(){const ie=X(),ae=yield L(),ue=X();return this.aggregate(Z,ue-ie,q),ae})}registerStatsReporter(Z){this.reporters.push(Z)}setTag(Z,L){const q=this.filterTags({[Z]:L});this.tags=Object.assign(Object.assign({},this.tags),q)}addToBuffer(Z,L,q){if(Z[L]){const{min:ie,max:ae,sum:ue,count:Ue}=Z[L];Z[L]={min:Math.min(ie,q.min),max:Math.max(ae,q.max),sum:ue+q.sum,count:Ue+q.count}}else Z[L]=q}write(Z){return I(this,void 0,void 0,function*(){yield Promise.all(this.reporters.map(L=>I(this,void 0,void 0,function*(){let q;const ie={};switch(L.type){case"simple":for(const[ue,Ue]of Object.entries(Z)){const{metric:fe}=this.decodeKey(ue);this.addToBuffer(ie,this.encodeKey({metric:fe}),Ue)}q=ie;break;case"tagged":q=Z;break;default:(function(ue){throw new Error(`Unreachable type encountered (${ue})`)})(L.type)}const ae=Object.entries(q);if(ae.length>0)return L.send(ae.map(([ue,Ue])=>{const{metric:fe,tags:ce}=this.decodeKey(ue);return{name:fe,tags:Object.assign(Object.assign({},ce),this.tags),stat:Ue}}),F.samplePeriodMs).catch(ue=>{f.a.debug("Failed to write stats to "+L.name,{error:ue})})})))})}flushStats(){return I(this,void 0,void 0,function*(){yield this.write(this.buffer),this.buffer={}})}encodeKey(Z){return B()(Object.assign(Object.assign({},Z),Object.keys(Z.tags||{}).length>0?{tags:Z.tags}:{}))}decodeKey(Z){return JSON.parse(Z)}filterTags(Z){return Object.entries(Z||{}).reduce((L,[q,ie])=>(y(q)&&y(ie)&&(L[q]=ie),L),{})}}F.samplePeriodMs=5*u.a.minute;const R=!!p.d,x=new F;R||["local","on-prem"].includes(p.j)||x.registerStatsReporter(new M("stats"));var w=function(Re,Z,L,q){return new(L||(L=Promise))(function(ie,ae){function ue(ce){try{fe(q.next(ce))}catch(le){ae(le)}}function Ue(ce){try{fe(q.throw(ce))}catch(le){ae(le)}}function fe(ce){var le;ce.done?ie(ce.value):(le=ce.value,le instanceof L?le:new L(function(me){me(le)})).then(ue,Ue)}fe((q=q.apply(Re,Z||[])).next())})};class _ extends class{constructor(Z){this.options=Z,this.cache=new U.a(Object.assign(Object.assign(Object.assign({},Z.dispose||Z.disposeAfter?{ttlAutopurge:!0}:{}),Z),{dispose:(...L)=>{var q;L[2]==="evict"&&x.increment("lru-eviction",{name:Z.name}),(q=Z.dispose)===null||q===void 0||q.call(Z,...L)},disposeAfter:(...L)=>{var q;this.updateStats(),(q=Z.disposeAfter)===null||q===void 0||q.call(Z,...L)}})),this.stringify=Z.fastStringify?JSON.stringify:B.a}set(Z,L,q){const ie=this.stringify(Z);if(!this.cache.set(ie,L,{ttl:q})){const ae=this.cache.sizeCalculation?this.cache.sizeCalculation(L,ie):"unknown";throw Error(`Value too large (${ae} > ${this.cache.max})`)}this.updateStats()}get(Z){const{name:L}=this.options,q=this.stringify(Z),ie=this.cache.getRemainingTTL(q);return ie<=0?x.increment("cache-miss",{name:L}):ie!==1/0&&x.aggregate("cache-item-ttl",ie,{name:L}),this.cache.get(q)}delete(Z){this.cache.delete(this.stringify(Z))}peek(Z){return this.cache.peek(this.stringify(Z))}size(){return this.cache.size}clear(){this.cache.clear()}forEach(Z){this.cache.forEach(Z)}purgeStale(){return this.cache.purgeStale()}updateStats(){const{name:Z}=this.options;x.aggregate("cache-item-count",this.cache.size,{name:Z}),this.cache.calculatedSize!==void 0&&x.aggregate("cache-length",this.cache.calculatedSize,{name:Z})}}{constructor(Z){if(super(Z),this.expireRejectedPromiseValues=Z.expireRejectedPromiseValues===void 0||Z.expireRejectedPromiseValues,this.rejectedPromiseValueTtl=Z.rejectedPromiseValueTtl!==void 0?Z.rejectedPromiseValueTtl:u.a.second,this.rejectedPromiseValueTtl<0)throw new Error("rejectedPromiseValueTtl must not be negative")}set(Z,L,q){super.set(Z,L,q),this.expireRejectedPromiseValues&&L.catch(()=>w(this,void 0,void 0,function*(){yield Object(c.a)(this.rejectedPromiseValueTtl),this.peek(Z)===L&&this.delete(Z)}))}}var j=function(Re,Z,L,q){return new(L||(L=Promise))(function(ie,ae){function ue(ce){try{fe(q.next(ce))}catch(le){ae(le)}}function Ue(ce){try{fe(q.throw(ce))}catch(le){ae(le)}}function fe(ce){var le;ce.done?ie(ce.value):(le=ce.value,le instanceof L?le:new L(function(me){me(le)})).then(ue,Ue)}fe((q=q.apply(Re,Z||[])).next())})};class C{constructor(Z,L,q){this.authClient=Z,this.email=L,this.password=q,this.tokenTtlMs=1*u.a.hour,this.tokenCache=new _({name:"Credentials-tokenCache",max:100,ttl:this.tokenTtlMs-5*u.a.minute,fastStringify:!0})}getToken(){return j(this,void 0,void 0,function*(){let Z=this.tokenCache.get(this.email);return Z||(Z=(()=>j(this,void 0,void 0,function*(){const{authentication:L}=yield this.authClient.login({email:this.email,password:this.password,tokenExpirationSeconds:this.tokenTtlMs/u.a.second});if(!L)throw new Error("User account not verified.");return L.accessToken}))(),this.tokenCache.set(this.email,Z)),Z})}}var W=n(96),v=n(17),D=n(236),A=n(41),E=function(Re,Z,L,q){return new(L||(L=Promise))(function(ie,ae){function ue(ce){try{fe(q.next(ce))}catch(le){ae(le)}}function Ue(ce){try{fe(q.throw(ce))}catch(le){ae(le)}}function fe(ce){var le;ce.done?ie(ce.value):(le=ce.value,le instanceof L?le:new L(function(me){me(le)})).then(ue,Ue)}fe((q=q.apply(Re,Z||[])).next())})};class P extends A.a{constructor(Z){super(Z)}postLanRtcOffer(Z){return E(this,void 0,void 0,function*(){return yield this.fetch("v1/lan-rtc-offer",{method:"POST",body:Z})})}}var G=function(Re,Z,L,q){return new(L||(L=Promise))(function(ie,ae){function ue(ce){try{fe(q.next(ce))}catch(le){ae(le)}}function Ue(ce){try{fe(q.throw(ce))}catch(le){ae(le)}}function fe(ce){var le;ce.done?ie(ce.value):(le=ce.value,le instanceof L?le:new L(function(me){me(le)})).then(ue,Ue)}fe((q=q.apply(Re,Z||[])).next())})};function $(Re){return G(this,void 0,void 0,function*(){return(yield Promise.all(Re.map(Z=>Z.catch(L=>L)))).filter(Z=>Z instanceof Error)})}function ee(Re,Z){if(Re===void 0)throw new Error("Value is undefined"+(Z?": "+Z:""))}function re(Re,Z){if(Re===null)throw new Error("Value is null"+(Z?": "+Z:""))}function O(Re){return ee(Re),Re}function k(Re,Z){const L=Re.reduce((q,ie)=>[...q,...ie.urls],[]).filter(q=>S(q,Z)).sort(q=>V(q,"udp")?-1:0).shift();if(L)return Object.assign(Object.assign({},O(Re.find(q=>q.urls.includes(L)))),{urls:[L]})}function S(Re,Z){switch(Z){case"stun":return/^stuns?:/.test(Re);case"turn":return/^turns?:/.test(Re)}}function V(Re,Z){return Re.endsWith("transport="+Z)}var z=n(10);class K extends Error{constructor(Z,L){super(`Deadline expired after ${Z}ms + ${L}ms`)}}class Y{static withDeadline(Z,L){const q=new Promise((ie,ae)=>{setTimeout(()=>{ae(new K(L,this.grpcCallDeadlineSlopMs))},L+this.grpcCallDeadlineSlopMs)});return Promise.race([Z,q])}}Y.grpcCallDeadlineSlopMs=500*u.a.millisecond;var te=n(27);const oe={ordered:!1,maxPacketLifeTime:300*u.a.millisecond},ge={ordered:!0},Se={ordered:!0},ve={ordered:!1,maxRetransmits:0},ye={ordered:!1,maxRetransmits:0},Je=Re=>"received"in Re&&Re.received!==void 0,Ee=Re=>!("received"in Re)||Re.received===void 0,be=2*u.a.second,we=10*u.a.second;function Ze(Re,Z={}){const L=Array.from(Re.values()),q=L.filter(Je),ie=q.length>0,ae=Math.max(...L.map(le=>le.sent)),ue=Math.max(...q.map(le=>le.received));let Ue;if(ie){const le=Date.now()-ae<=u.a.millisecond?L.length-1:L.length,me=q.length>le?le:q.length,Ve=q.map(Me=>Me.received-Me.sent),{standardDeviation:Ce,mean:xe,jitter:He}=function(Me){const Le=Me.length;if(Le===0)return{mean:NaN,standardDeviation:-1,jitter:NaN};const ze=Me.reduce((Xe,tt)=>Xe+tt,0)/Le,qe=Math.sqrt(Me.map(Xe=>Math.pow(Xe-ze,2)).reduce((Xe,tt)=>Xe+tt)/Le);if(Le===1)return{mean:ze,standardDeviation:qe,jitter:NaN};let yt=0;for(let Xe=1;Xe<Le;Xe++)yt+=Math.abs(Me[Xe]-Me[Xe-1]);return{mean:ze,standardDeviation:qe,jitter:yt/(Le-1)}}(Ve),Ye=L.filter(Me=>Me.sent<ue-be),$e=Ye.filter(Ee),Pe=$e.length===0?0:$e.length/Ye.length;Ue={pingsSent:le,pongsReceived:me,average:xe,standardDeviation:Ce,jitter:He,max:Math.max(...Ve),min:Math.min(...Ve),loss:Pe}}else Ue=null;const{temporalNow:fe=Date.now()}=Z,ce=(ie?ue:fe)-we;return Array.from(Re.entries()).forEach(le=>{const[me,Ve]=le;Ve.sent<ce&&Re.delete(me)}),Ue}function Oe({entityId:Re,streamName:Z,streamType:L}){return`${Re}.${Z}.${L}`}var gt=function(Re,Z,L,q){return new(L||(L=Promise))(function(ie,ae){function ue(ce){try{fe(q.next(ce))}catch(le){ae(le)}}function Ue(ce){try{fe(q.throw(ce))}catch(le){ae(le)}}function fe(ce){var le;ce.done?ie(ce.value):(le=ce.value,le instanceof L?le:new L(function(me){me(le)})).then(ue,Ue)}fe((q=q.apply(Re,Z||[])).next())})};class Tt{constructor(Z,L){this.counts={localSent:new Map,localReceived:new Map,remoteSent:new Map,remoteReceived:new Map},this.sessionId=Z,this.connection=L}updateRemoteMessagesCounts(Z){if(Z.payload.streamsInfo){this.counts.remoteSent=new Map,this.counts.remoteReceived=new Map;for(const L of Z.payload.streamsInfo.items)this.counts.remoteSent.set(L.streamId,L.sentCount),this.counts.remoteReceived.set(L.streamId,L.receivedCount)}}getLocalStreamsInfo(Z){const{localSent:L,localReceived:q}=this.counts;return{items:[...new Set([...L.keys(),...q.keys()])].map(ie=>{var ae,ue;return{streamId:ie,sentCount:(ae=L.get(ie))!==null&&ae!==void 0?ae:0,receivedCount:(ue=q.get(ie))!==null&&ue!==void 0?ue:0}}),timestamp:Z}}incrementLocalSent(Z){const{localSent:L}=this.counts,q=Oe(Z.header.stream);L.set(q,(L.get(q)||0)+1)}incrementLocalReceived(Z){const{localReceived:L}=this.counts,q=Oe(Z.header.stream),ie=L.get(q)||0;if(ie===0){const{streamName:ae,streamType:ue}=Z.header.stream;f.a.debug("RTC client received first message for stream",{streamName:ae,streamType:ue})}L.set(q,ie+1)}uploadMetrics(){return gt(this,void 0,void 0,function*(){const{sessionId:Z}=this,L=yield this.connection.peerConnection.getStats(),q={};L.forEach(ce=>q[ce.id]=ce),f.a.debug("rtc-stats",Object.assign(Object.assign({},q),{sessionId:Z}));const{localSent:ie,localReceived:ae,remoteSent:ue,remoteReceived:Ue}=this.counts,fe=[...new Set([...ie.keys(),...ae.keys()])].reduce((ce,le)=>{const me=ie.get(le),Ve=ae.get(le),Ce=ue.get(le),xe=Ue.get(le);return Object.assign(Object.assign({},ce),{[`local-${le}-sent`]:me,[`local-${le}-received`]:Ve,[`remote-${le}-sent`]:Ce,[`remote-${le}-received`]:xe})},{sessionId:Z});f.a.debug("rtc-message-report",Object.assign({deviceId:this.connection.getRemoteDeviceId()},fe))})}}function Ct(Re,Z,L){return{header:{stream:Re,created:Date.now(),frameId:L||""},payload:Z}}function vt(Re){const Z=Re.localCandidate.candidateType,L=Re.remoteCandidate.candidateType;return Z==="host"&&L==="host"?"local":Z==="relay"||L==="relay"?"TURN":"STUN"}function pt(Re){return new Set(["disconnected","failed","closed"]).has(Re.iceConnectionState)}function _t(Re){switch(Re.header.stream.streamType){case"twist":{const{twist:Z}=Re.payload;if(!Z)throw Error("twist not in payload of RTC message with type twist");return{header:Re.header,payload:{twist:{linear:Object.assign({x:0,y:0,z:0},Z.linear),angular:Object.assign({x:0,y:0,z:0},Z.angular)}}}}case"pose":{const{pose:Z}=Re.payload;if(!Z)throw Error("pose not in payload of RTC message with type pose");return{header:Re.header,payload:{pose:{translation:Object.assign({x:0,y:0,z:0},Z.translation),rotation:Object.assign({x:0,y:0,z:0,w:0},Z.rotation)}}}}case"pose-with-covariance":{const{poseWithCovariance:Z}=Re.payload;if(!Z)throw Error("poseWithCovariance not in payload of RTC message with type pose-with-covariance");const L=new Array(36).fill(0);return Z.covariance.forEach((q,ie)=>{if(ie>=36)throw Error("covariance contains more than 36 elements");L[ie]=q}),{header:Re.header,payload:{poseWithCovariance:{pose:{translation:Object.assign({x:0,y:0,z:0},Z.pose.translation),rotation:Object.assign({x:0,y:0,z:0,w:0},Z.pose.rotation)},covariance:L}}}}case"point":{const{point:Z}=Re.payload;if(!Z)throw Error("point not in payload of RTC message with type point");return{header:Re.header,payload:{point:Object.assign({x:0,y:0,z:0},Z)}}}default:return Re}}var ut=function(Re,Z,L,q){return new(L||(L=Promise))(function(ie,ae){function ue(ce){try{fe(q.next(ce))}catch(le){ae(le)}}function Ue(ce){try{fe(q.throw(ce))}catch(le){ae(le)}}function fe(ce){var le;ce.done?ie(ce.value):(le=ce.value,le instanceof L?le:new L(function(me){me(le)})).then(ue,Ue)}fe((q=q.apply(Re,Z||[])).next())})};class Vt{get peerConnection(){return re(this._peerConnection,"RTCPeerConnection is closed!"),this._peerConnection}constructor(Z,L,q,ie){this.iceServers=L,this.config=q,this.dataChannelNotifier=ie,this.connectTimeoutMs=20*u.a.second,this.iceGatheringTimeoutMs=3*u.a.second,this.pingUpdateTimeoutMs=1*u.a.second,this.pingV2UpdateTimeoutMs=250*u.a.millisecond,this.pingV2MetricsGatherTimeoutMs=1*u.a.second,this.streamsInfoUpdateTimeoutMs=2*u.a.second,this.reassemblyTimeoutMs=500*u.a.millisecond,this.reassemblyTableCleanupMs=1*u.a.second,this.heartbeatTimeoutMs=20*u.a.millisecond,this._peerConnection=null,this.heartbeatChannel=null,this.latestTtlStreamChannel=null,this.reliableStreamChannel=null,this.latestReliableStreamChannel=null,this.latestTryOnceStreamChannel=null,this.streamLatestTimestamp=new Map,this.reassemblyTable=new Map,this.reassemblyTableLastTimestamp=new Map,this.closeCalled=!1,this.gotOffer=!1,this.hasIceCandidate=!1,this.pingV2Map=new Map,this.sendPingV2=()=>{const{latestTryOnceStreamChannel:ue}=this;if(!ue)return;const Ue=new Date().getTime(),fe=Object(D.a)();this.sendSystemMessage(ue,{type:"ping-v2",payload:{timestamp:Ue,id:fe}}),this.pingV2Map.set(fe,{sent:Ue})},this.gatherPingV2Metrics=()=>{const ue=Ze(this.pingV2Map);if(ue){const Ue=this.getRemoteDeviceId();this.pingInfo=ue,x.aggregate("rtc-ping-average",ue.average,Object.assign({},Ue?{deviceId:Ue}:{})),x.aggregate("rtc-ping-loss",ue.loss,Object.assign({},Ue?{deviceId:Ue}:{})),x.aggregate("rtc-jitter",ue.jitter,Object.assign({},Ue?{deviceId:Ue}:{}))}},this._peerConnection=Z;const{isOffer:ae}=q.baseConfig;ae?this.initializeChannels(Z):Z.ondatachannel=ue=>{switch(ue.channel.label){case"stream.latest-ttl":this.latestTtlStreamChannel=ue.channel;break;case"stream.reliable":this.reliableStreamChannel=ue.channel;break;case"stream.latest-reliable":this.latestReliableStreamChannel=ue.channel;break;case"stream.latest-try-once":this.latestTryOnceStreamChannel=ue.channel;break;case"heartbeat":return void(this.heartbeatChannel=ue.channel);default:return void this.dataChannelNotifier(ue.channel)}this.setupChannel(ue.channel)},this.pingUpdateTimeout=setInterval(()=>{const{reliableStreamChannel:ue}=this;ue&&this.sendSystemMessage(ue,{type:"ping"})},this.pingUpdateTimeoutMs),this.pingV2UpdateTimeout=setInterval(this.sendPingV2,this.pingV2UpdateTimeoutMs),this.pingV2MetricsGatherTimeout=setInterval(this.gatherPingV2Metrics,this.pingV2MetricsGatherTimeoutMs),this.streamsInfoUpdateTimeout=setInterval(()=>{const{latestTtlStreamChannel:ue}=this;ue&&this.sendSystemMessage(ue,{type:"streams-info"})},this.streamsInfoUpdateTimeoutMs),this.reassemblyTableCleanupTimeout=setInterval(()=>{const ue=new Date().getTime();this.reassemblyTableLastTimestamp.forEach((Ue,fe,ce)=>{ue>fe+this.reassemblyTimeoutMs&&this.reassemblyTable.delete(Ue)})},this.reassemblyTableCleanupMs),this.heartbeatTimeout=setInterval(()=>{const{heartbeatChannel:ue}=this;ue&&ue.readyState==="open"&&ue.send(new Uint8Array([1]))},this.heartbeatTimeoutMs)}handleSignal(Z){return ut(this,void 0,void 0,function*(){const{peerConnection:L}=this,{track:q}=this.config.baseConfig,ie=(()=>{try{return JSON.parse(Z.getPayload())}catch{return}})();if(!ie)return void f.a.error("Received unparseable signal.");f.a.debug("Handling signal",{description:ie});const{sdp:ae,type:ue}=ie;if(!ae||!ue)return void f.a.warn("Received non-SDP signal");const{signalingState:Ue,connectionState:fe}=L;if(Ue!=="stable"||fe!=="connected")if(L.remoteDescription)f.a.warn("Received SDP after remote description was set: "+ae);else{if(ue==="offer"){if(Ue!=="stable")return void f.a.warn("Received offer SDP when signaling is ongoing.");yield L.setRemoteDescription(ie);const ce=yield L.createAnswer();yield L.setLocalDescription(ce);const le=Z.clone();return q==null||q("Answer Received",le),le.setPayload(JSON.stringify(ce)),le.setReceiverId(Z.getSenderId()),le.setSenderId(Z.getReceiverId()),le}if(ue==="answer"){if(Ue==="stable")return void f.a.warn("Received answer SDP when signaling hasn't started.");yield L.setRemoteDescription(ie)}}else f.a.warn("Received SDP when already connected: "+ae)})}send(Z,L){const q=this.getChannelFromLabel(L.channelLabel);q?this.sendOnChannel(q,Z):f.a.warn("Send called with unexpected channel label",{channelLabel:L.channelLabel})}controlRemoteStream(Z){var L;this.sendSystemMessage((re(L=this.reliableStreamChannel),L),{type:"stream-control",streamControl:Z})}isActive(){return new Set(["new","checking","connected","completed"]).has(this.peerConnection.iceConnectionState)||this.isReady()}isReady(){const{reliableStreamChannel:Z,latestTtlStreamChannel:L,latestTryOnceStreamChannel:q,latestReliableStreamChannel:ie}=this;return(Z==null?void 0:Z.readyState)==="open"&&(L==null?void 0:L.readyState)==="open"&&(q==null?void 0:q.readyState)==="open"&&(ie==null?void 0:ie.readyState)==="open"}close(){var Z,L,q,ie,ae,ue,Ue;return ut(this,void 0,void 0,function*(){this.closeCalled||(this.closeCalled=!0,yield(Z=this.sessionMetrics)===null||Z===void 0?void 0:Z.uploadMetrics(),Ft(this.pingUpdateTimeout),Ft(this.pingV2UpdateTimeout),Ft(this.pingV2MetricsGatherTimeout),Ft(this.reassemblyTableCleanupTimeout),Ft(this.streamsInfoUpdateTimeout),Ft(this.heartbeatTimeout),(L=this._peerConnection)===null||L===void 0||L.close(),(q=this.heartbeatChannel)===null||q===void 0||q.close(),(ie=this.latestReliableStreamChannel)===null||ie===void 0||ie.close(),(ae=this.latestTryOnceStreamChannel)===null||ae===void 0||ae.close(),(ue=this.latestTtlStreamChannel)===null||ue===void 0||ue.close(),(Ue=this.reliableStreamChannel)===null||Ue===void 0||Ue.close(),this._peerConnection=null,this.heartbeatChannel=null,this.latestReliableStreamChannel=null,this.latestTryOnceStreamChannel=null,this.latestTtlStreamChannel=null,this.reliableStreamChannel=null)})}getPing(){return this.pingTimeMs}getPingInfo(){return this.pingInfo}getLastMessageTimestamp(){return this.lastMessageTimestamp}getSessionCreatedTimestamp(){var Z;return(Z=this.config.remoteConfig)===null||Z===void 0?void 0:Z.sessionCreatedTimestamp}setSessionCreatedTimestamp(Z){this.config.remoteConfig&&(this.config.remoteConfig.sessionCreatedTimestamp=Z)}getSessionId(){var Z;return(Z=this.config.remoteConfig)===null||Z===void 0?void 0:Z.sessionId}setSessionId(Z){this.config.remoteConfig&&(this.config.remoteConfig.sessionId=Z,this.sessionMetrics=new Tt(Z,this))}getRemotePeerId(){return this.config.baseConfig.remotePeerId}getRemoteDeviceId(){var Z;return(Z=this.config.baseConfig)===null||Z===void 0?void 0:Z.remoteDeviceId}setRemoteDeviceId(Z){this.config.baseConfig.remoteDeviceId=Z}getSessionMetricsMessageCounts(){var Z;return(Z=this.sessionMetrics)===null||Z===void 0?void 0:Z.counts}getConnectionStatsInfo(){return ut(this,void 0,void 0,function*(){const{peerConnection:Z}=this;if(!Z)return;const L=yield Z.getStats(null),q=[];L.forEach(fe=>{q.push(fe)});const ie=q.find(fe=>fe.type==="transport");if(!ie)return;const ae=q.find(fe=>(fe.type==="candidate-pair"||fe.type==="candidatepair")&&fe.id===ie.selectedCandidatePairId);if(!ae)return;const ue=q.find(fe=>fe.id===ae.localCandidateId),Ue=q.find(fe=>fe.id===ae.remoteCandidateId);return ue&&Ue&&(ue.address=ue.address||ue.ip,Ue.address=Ue.address||Ue.ip,ue.address!==void 0&&Ue.address!==void 0)?{transport:ie,localCandidate:ue,remoteCandidate:Ue,candidatePair:ae}:void 0})}initializeChannels(Z){this.heartbeatChannel=Z.createDataChannel("heartbeat",ye),this.heartbeatChannel.binaryType="arraybuffer",this.latestTtlStreamChannel=Z.createDataChannel("stream.latest-ttl",oe),this.latestTtlStreamChannel.binaryType="arraybuffer",this.reliableStreamChannel=Z.createDataChannel("stream.reliable",ge),this.reliableStreamChannel.binaryType="arraybuffer",this.latestReliableStreamChannel=Z.createDataChannel("stream.latest-reliable",Se),this.latestReliableStreamChannel.binaryType="arraybuffer",this.latestTryOnceStreamChannel=Z.createDataChannel("stream.latest-try-once",ve),this.latestTryOnceStreamChannel.binaryType="arraybuffer",this.setupChannel(this.latestTtlStreamChannel),this.setupChannel(this.reliableStreamChannel),this.setupChannel(this.latestReliableStreamChannel),this.setupChannel(this.latestTryOnceStreamChannel)}getOffer(){var Z,L;return ut(this,void 0,void 0,function*(){const{gotOffer:q}=this,{peerConnection:ie,config:ae}=this;if(this.config.baseConfig.isLan)throw new Error('"getOffer" method can only be called with internet connections. LAN connections should call the "getLanOffer" method.');const ue=(Z=this.config.remoteConfig)===null||Z===void 0?void 0:Z.sessionId;if(q)return void f.a.debug("Failed to generate offer because gotOffer was already called.");if(this.gotOffer=!0,pt(this.peerConnection))return void f.a.debug("Failed to generate offer because the peer connection was inactive.");const Ue=ae.baseConfig.track;ie.onicecandidate=()=>{this.hasIceCandidate=!0},ie.oniceconnectionstatechange=()=>ut(this,void 0,void 0,function*(){const Ce=ie.iceConnectionState;if(Ce==="connected"||Ce==="completed"){const xe=yield this.getConnectionStatsInfo(),He=xe?vt(xe):void 0;f.a.info("ICE connection state changed to "+Ce,{sessionId:ue,connectionStatsInfo:xe,iceMode:He}),Ue==null||Ue("ICE connection state change",{iceConnectionState:Ce,sessionId:ue,connectionStatsInfo:xe,iceMode:He})}}),yield ie.setLocalDescription(yield ie.createOffer());const fe=ie.getConfiguration?ie.getConfiguration().iceTransportPolicy:"all",ce=new Date().getTime();for(;;){const Ce=new Date().getTime()-ce;if(Ce>this.connectTimeoutMs)return void f.a.debug("Failed to generate offer because ICE gathering timed out.");if(Ce>this.iceGatheringTimeoutMs&&this.hasIceCandidate){f.a.debug("ICE gathering partially completed; proceeding",{iceTransportPolicy:fe,waitTime:Ce}),Ue==null||Ue("ICE gathering partially completed",{sessionId:ue,iceTransportPolicy:fe,waitTime:Ce});break}if(ie.iceGatheringState==="complete"){f.a.debug("ICE gathering complete",{iceTransportPolicy:fe,waitTime:Ce}),Ue==null||Ue("ICE gathering completed",{sessionId:ue,iceTransportPolicy:fe,waitTime:Ce});break}yield Object(c.a)(.1*u.a.second)}const le=(L=this.iceServers)!==null&&L!==void 0?L:[];for(const Ce of le)"credentialType"in Ce&&(Ce.credentialType=void 0);const me=JSON.stringify(le),Ve=new z.Signal;return Ve.setPayload(JSON.stringify(ie.localDescription)),Ve.setSenderId(this.config.baseConfig.localPeerId),Ve.setReceiverId(this.config.baseConfig.remotePeerId),Ve.setIceServers(me),Ve.setIceTransportPolicy(fe!=null?fe:"all"),this.config.baseConfig.sessionType!==void 0?Ve.setSessionType(this.config.baseConfig.sessionType):Ve.setSessionType(z.SessionType.TELEOP),f.a.debug("Sending offer signal with description",{description:Ve.getPayload()}),Ve})}getLanOffer(){return ut(this,void 0,void 0,function*(){const{peerConnection:Z,gotOffer:L}=this;if(!this.config.baseConfig.isLan)throw new Error('"getLanOffer" method can only be used with LAN connections. Internet connections should call the "getOffer" method.');if(L)return void f.a.debug("Failed to generate offer because gotOffer was already called.");if(this.gotOffer=!0,pt(this.peerConnection))return void f.a.debug("Failed to generate offer because the peer connection was inactive.");yield Z.setLocalDescription(yield Z.createOffer());const q=new Date().getTime();for(;;){if(new Date().getTime()-q>this.iceGatheringTimeoutMs)return void f.a.debug("Failed to generate offer because ICE gathering timed out.");if(Z.iceGatheringState==="complete")break;yield Object(c.a)(.1*u.a.second)}const ie=Z.localDescription;if(ie)return f.a.debug("Sending LAN offer signal with description",{description:ie}),ie;f.a.error("Failed to generate LAN offer description")})}handleLanAnswer(Z){return ut(this,void 0,void 0,function*(){const{peerConnection:L}=this;if(!this.config.baseConfig.isLan)throw new Error('"handleLanAnswer" method can only be used with LAN connections. Internet connections should call the "handleSignal" method.');yield L.setRemoteDescription(Z)})}getChannelFromLabel(Z){switch(Z){case"stream.latest-ttl":return this.latestTtlStreamChannel;case"stream.reliable":return this.reliableStreamChannel;case"stream.latest-reliable":return this.latestReliableStreamChannel;case"stream.latest-try-once":return this.latestTryOnceStreamChannel}}sendOnChannel(Z,L){var q;let ie;try{ie=Object(te.encode)(JSON.stringify(L))}catch(ae){return void f.a.warn("Failed to encode RTC message",{error:ae})}try{Z.send(ie),(q=this.sessionMetrics)===null||q===void 0||q.incrementLocalSent(L)}catch(ae){f.a.warn("Failed to send message to channel",{error:ae,channel:Z.label})}}channelNotRecognized(Z){return Z!==this.latestTtlStreamChannel&&Z!==this.latestReliableStreamChannel&&Z!==this.latestTryOnceStreamChannel&&Z!==this.reliableStreamChannel}setupChannel(Z){Z.onmessage=L=>{if(this.channelNotRecognized(Z))return void f.a.warn("Received message on unrecognized data channel.");let q;try{q=JSON.parse(Object(te.decode)(L.data))}catch(ie){return void f.a.warn("Received unparseable message on RTC stream data channel",{error:ie,channel:Z.label})}q.communicationType==="message-chunk"?this.receiveChannelMessageChunk(Z,q):this.receiveChannelMessage(Z,q)},Z.onerror=L=>{f.a.warn("Channel error: "+L.error,{error:L.error,sessionId:this.getSessionId(),channelLabel:Z.label})},Z.onopen=()=>{f.a.debug("Channel opened",{sessionId:this.getSessionId(),channelLabel:Z.label})},Z.onclose=()=>{const L={bufferedAmount:Z.bufferedAmount,sessionId:this.getSessionId(),channelLabel:Z.label};this.closeCalled===!1?f.a.debug("Unexpected channel closed",L):f.a.debug("Channel closed",L)}}receiveChannelMessage(Z,L){var q;const{config:ie}=this,{remotePeerId:ae}=this.config.baseConfig;this.lastMessageTimestamp=new Date().getTime(),L=_t(L),(q=this.sessionMetrics)===null||q===void 0||q.incrementLocalReceived(L),!this.handleSystemMessage(Z,L)&&((Z===this.latestTryOnceStreamChannel||Z===this.latestTtlStreamChannel||Z===this.latestReliableStreamChannel)&&!this.isLatestMessage(L)||ie.baseConfig.receive(ae,L))}receiveChannelMessageChunk(Z,L){const q=this.reassemblyTable.get(L.id)||[];if(q.push(L),q.length===L.total){const ie=function(ae){const ue=ae.sort((Ue,fe)=>Ue.seq<fe.seq?-1:1).map(Ue=>Ue.part).reduce((Ue,fe)=>Ue+fe);try{return JSON.parse(ue)}catch{return void f.a.warn("Could not reassemble RTC message chunks")}}(q);return ie&&this.receiveChannelMessage(Z,ie),void this.reassemblyTable.delete(L.id)}this.reassemblyTable.set(L.id,q),this.reassemblyTableLastTimestamp.set(L.id,new Date().getTime())}handleSystemMessage(Z,L){var q,ie;const{config:ae}=this,{baseConfig:ue}=ae,{remotePeerId:Ue,remoteDeviceId:fe}=ue;switch(L.header.stream.streamType){case"ping":return this.sendSystemMessage(Z,{type:"pong",timestamp:O(L.payload.ping)}),!0;case"pong":{const ce=new Date().getTime()-O(L.payload.pong);return this.pingTimeMs=ce,x.aggregate("rtc-ping-time",ce,Object.assign({},fe?{deviceId:fe}:{})),!0}case"ping-v2":return this.sendPingV2(),!0;case"pong-v2":{const ce=O(L.payload.pongV2),le=this.pingV2Map.get(ce.id);return(le==null?void 0:le.sent)!==ce.timestamp&&f.a.warn("Pong timestamp doesn't match stored value",{currentEntry:le,pong:ce}),this.pingV2Map.set(ce.id,{sent:ce.timestamp,received:new Date().getTime()}),!0}case"streams-info":{const{sessionMetrics:ce}=this,le=(q=L.payload.streamsInfo)===null||q===void 0?void 0:q.timestamp;return!!le&&(ce==null||ce.updateRemoteMessagesCounts(L),(ie=ue.onStreamsInfoUpdate)===null||ie===void 0||ie.call(ue,Ue,le),!0)}case"stream-control":return!0;default:return!1}}sendSystemMessage(Z,L){var q;const{localUserId:ie,localPeerId:ae}=this.config.baseConfig;if(Z.readyState!=="open")return;const ue={entityId:ie!=null?ie:ae,streamName:"$."+L.type,streamType:L.type};let Ue;switch(L.type){case"ping":Ue={ping:new Date().getTime()};break;case"pong":Ue={pong:L.timestamp};break;case"ping-v2":Ue={pingV2:L.payload};break;case"pong-v2":Ue={pongV2:L.payload};break;case"stream-control":Ue={streamControl:L.streamControl};break;case"streams-info":Ue={streamsInfo:(q=this.sessionMetrics)===null||q===void 0?void 0:q.getLocalStreamsInfo(new Date().getTime())}}this.sendOnChannel(Z,Ct(ue,Ue))}isLatestMessage(Z){const L=Oe(Z.header.stream),q=(this.streamLatestTimestamp.get(L)||0)<=Z.header.created;return q&&this.streamLatestTimestamp.set(L,Z.header.created),q}}function Ft(Re){Re&&clearInterval(Re)}function Nt(){f.a.debug("forceGarbageCollection() triggered"),queueMicrotask(()=>{let Re=document.createElement("img");Re.src=window.URL.createObjectURL(new Blob([new ArrayBuffer(5e7)])),Re.onerror=function(){window.URL.revokeObjectURL(this.src),Re=null}})}function jt(Re){try{return Re instanceof Error?`${Re.name}: ${Re.message}`:typeof Re=="object"?JSON.stringify(Re):String(Re)}catch{return"Unknown error"}}function ht(Re){var Z,L;return{userId:(Z=Re.getUserId())===null||Z===void 0?void 0:Z.getValue(),deviceId:(L=Re.getDeviceId())===null||L===void 0?void 0:L.getValue(),organizationId:Re.getOrganizationId(),id:Re.getPeerId(),capabilities:[],capabilitySet:{}}}var De=function(Re,Z,L,q){return new(L||(L=Promise))(function(ie,ae){function ue(ce){try{fe(q.next(ce))}catch(le){ae(le)}}function Ue(ce){try{fe(q.throw(ce))}catch(le){ae(le)}}function fe(ce){var le;ce.done?ie(ce.value):(le=ce.value,le instanceof L?le:new L(function(me){me(le)})).then(ue,Ue)}fe((q=q.apply(Re,Z||[])).next())})};const Qt=Re=>Re.map(Z=>Object.assign(Object.assign(Object.assign({},Z),Z.username?{username:"<REDACTED>"}:null),Z.credential?{credential:"<REDACTED>"}:null));class Pt{constructor(Z){this.config=Z,this.grpcCallDeadline=5*u.a.second,this.refreshIntervalDelayMs=2*u.a.second,this.iceServersTtl=30*u.a.minute,this.connections=[],this.localConnections=[],this.isConnectionInitiator=new WeakSet,this.isOutgoingConnection=new Set,this.peerDataChannelListeners=[],this.rtcInstancesConstructed=0,this.statsLoopsExecuted=0;const{refreshIntervalDelayMs:L}=this;this.refreshInterval=T({func:()=>De(this,void 0,void 0,function*(){try{yield this.update()}catch(q){f.a.warn("RTC refresh failed",{error:q})}}),delay:L,immediate:!0})}send(Z,L,q){const ie=this.getActiveConnection(Z);ie?ie.isReady()?ie.send(L,q):f.a.warn("Send called with unready connection."):f.a.warn("Send called with no connection.")}controlRemoteStream(Z,L){const q=this.getActiveConnection(Z);q?q.isReady()?q.controlRemoteStream(L):f.a.warn("controlRemoteStream called with unready connection."):f.a.warn("controlRemoteStream called with no connection.")}getLocalPeer(){return De(this,void 0,void 0,function*(){for(;!this.localPeer;)yield Object(c.a)(.1*u.a.second);return ht(this.localPeer)})}connect(Z,L){var q,ie,ae;return De(this,void 0,void 0,function*(){if(this.config.lanOnlyMode===!0)throw new Error("connect method called in local only mode.");const{track:ue,signalingClient:Ue}=this.config,{localPeer:fe,receiveSignalStream:ce,iceServers:le}=this;if(!fe||!ce||!le)return void f.a.warn("Connect called prior to local peer, receiveSignalStream, and ICE servers ready");if(this.getActiveConnection(Z))return void f.a.warn("Connect called for peer with existing connection.");if(this.isOutgoingConnection.has(Z))return void f.a.warn("Connect called for peer with an existing outgoing connection offer.");this.isOutgoingConnection.add(Z);const me=function(Pe,Me,Le){const{rtcIceTransportPolicies:ze,rtcIceServerProtocol:qe,useAllServers:yt}=Me||{},Xe=Pe.map(tt=>Object.assign(Object.assign({},tt),{urls:tt.urls.filter(ct=>{const wt=(ze===void 0||ze.some(Ot=>S(ct,Ot)))&&(qe===void 0||V(ct,qe));return wt||f.a.debug("Ignoring ICE server: "+ct,{organizationId:Le}),wt})})).filter(({urls:tt})=>tt.filter(ct=>ct).length>0);return yt?Xe:[k(Xe,"stun"),k(Xe,"turn")].filter(tt=>tt!==void 0).map(tt=>O(tt))}(le,L);f.a.debug("Received ICE servers:",Qt(le)),f.a.debug("Using ICE servers:",Qt(me));const Ve=new Vt(yield this.createRTCPeerConnection(me),me,{baseConfig:{isOffer:!0,isLan:!1,receive:(Pe,Me)=>this.config.receive(Pe,Me),onStreamsInfoUpdate:this.config.onStreamsInfoUpdate?(Pe,Me)=>{var Le,ze;return(ze=(Le=this.config).onStreamsInfoUpdate)===null||ze===void 0?void 0:ze.call(Le,Pe,Me)}:void 0,track:this.config.lanOnlyMode?void 0:this.config.track,localUserId:(q=fe.getUserId())===null||q===void 0?void 0:q.getValue(),localPeerId:fe.getPeerId(),remotePeerId:Z,sessionType:this.config.sessionType},remoteConfig:{}},Pe=>this.onCustomDataChannel(Z,Pe)),Ce=yield Ve.getOffer();if(!Ce)return f.a.error("Failed to generate offer."),void this.isOutgoingConnection.delete(Z);f.a.debug("Sending offer."),ue==null||ue("Sending offer",Ce);const xe=new z.SendSignalRequest;xe.setSignal(Ce);const He=yield(()=>De(this,void 0,void 0,function*(){try{return yield Y.withDeadline(Ue.sendSignal(xe,yield this.getMetadata()),this.grpcCallDeadline)}catch(Pe){f.a.warn("Error when sending signal",{error:Pe})}}))();if(!this.isOutgoingConnection.has(Z))return void f.a.debug("No offer set after receiving offer signal response.");f.a.debug("Offer sent.");const Ye=(ie=He==null?void 0:He.getSessionId())===null||ie===void 0?void 0:ie.getValue(),$e=(ae=He==null?void 0:He.getSessionCreatedTimestamp())===null||ae===void 0?void 0:ae.getValue();return Ye&&$e?(Ve.setSessionId(Ye),Ve.setSessionCreatedTimestamp($e),this.isOutgoingConnection.delete(Z),this.connections.push(Ve),this.isConnectionInitiator.add(Ve),this.setupHandlers(Ve),Ye):(f.a.warn("No session ID or no session created timestamp on send signal response."),void this.isOutgoingConnection.delete(Z))})}connectLan(Z){var L,q;return De(this,void 0,void 0,function*(){const ie=new P(Z),ae=new Vt(yield this.createRTCPeerConnection([]),[],{baseConfig:{isOffer:!0,isLan:!0,receive:(ce,le)=>this.config.receive(ce,le),onStreamsInfoUpdate:this.config.onStreamsInfoUpdate?(ce,le)=>{var me,Ve;return(Ve=(me=this.config).onStreamsInfoUpdate)===null||Ve===void 0?void 0:Ve.call(me,ce,le)}:void 0,track:this.config.lanOnlyMode?void 0:this.config.track,localUserId:(q=(L=this.localPeer)===null||L===void 0?void 0:L.getUserId())===null||q===void 0?void 0:q.getValue(),localPeerId:"lan_client",remotePeerId:Z}},ce=>this.onCustomDataChannel(Z,ce)),ue=yield ae.getLanOffer();if(!ue)return f.a.warn("Could not generate LAN offer"),!1;const Ue=yield ie.postLanRtcOffer({offer:JSON.stringify(ue)}),fe=new RTCSessionDescription(JSON.parse(Ue.answer));return yield ae.handleLanAnswer(fe),this.localConnections.push(ae),this.isConnectionInitiator.add(ae),Object(D.a)()})}getConnections(){return[...this.connections,...this.localConnections]}createCustomDataChannel(Z,L,q,ie,ae){const ue=this.getActiveConnection(Z);if(ue&&this.isConnectionInitiator.has(ue)){const fe=ue.peerConnection.createDataChannel("custom."+L,q);return ie&&(fe.binaryType="arraybuffer"),ae(Z,fe),()=>{}}const Ue=(fe,ce)=>{Z===fe&&ce.label==="custom."+L&&ae(Z,ce)};return this.peerDataChannelListeners.push(Ue),()=>{this.peerDataChannelListeners=this.peerDataChannelListeners.filter(fe=>fe!==Ue)}}onCustomDataChannel(Z,L){this.peerDataChannelListeners.forEach(q=>q(Z,L))}getConnectionStatus(Z){if(this.isOutgoingConnection.has(Z))return"connecting";const L=this.getActiveConnection(Z);return L?L.isReady()?"connected":"connecting":"disconnected"}getConnectionStatsInfo(Z){return De(this,void 0,void 0,function*(){const L=this.getActiveConnection(Z);if(L)return yield L.getConnectionStatsInfo()})}disconnect(Z){return De(this,void 0,void 0,function*(){const L=this.getActiveConnection(Z);L&&(yield L.close(),this.connections=this.connections.filter(q=>q!==L),this.localConnections=this.localConnections.filter(q=>q!==L))})}getPeers(){return De(this,void 0,void 0,function*(){if(this.config.lanOnlyMode)throw new Error("getPeers method cannot be used in local-only mode.");const{signalingClient:Z}=this.config,L=yield(()=>De(this,void 0,void 0,function*(){try{return yield Y.withDeadline(Z.getPeers(new z.GetPeersRequest,yield this.getMetadata()),this.grpcCallDeadline)}catch(ae){f.a.warn("Error when getting peers",{error:ae})}}))();if(!L)return[];const q=L.getPeersList();if(!q)return[];const ie=ae=>{var ue,Ue;return(Ue=(ue=ae.getPeerCreatedTimestamp())===null||ue===void 0?void 0:ue.getValue())!==null&&Ue!==void 0?Ue:0};return q.sort((ae,ue)=>ie(ue)-ie(ae)).map(ae=>ht(ae))})}getSessions(){return De(this,void 0,void 0,function*(){if(this.config.lanOnlyMode)throw new Error("getPeers method cannot be used in local-only mode.");const{signalingClient:Z}=this.config,L=yield(()=>De(this,void 0,void 0,function*(){try{return yield Y.withDeadline(Z.getPeers(new z.GetPeersRequest,yield this.getMetadata()),this.grpcCallDeadline)}catch(ae){f.a.warn("Error when getting peers",{error:ae})}}))();if(!L)return{};const q=L.getPeersList(),ie={};for(const ae of q)ie[ae.getPeerId()]=ae.getSessionIdsList();return ie})}getPing(Z){const L=this.getActiveConnection(Z);if(L)return L.getPing();f.a.warn("Attempted to get ping time from inactive peer.")}getPingInfo(Z){const L=this.getActiveConnection(Z);if(L)return L.getPingInfo();f.a.warn("Attempted to get ping time from inactive peer.")}getLastMessageTimestamp(Z){const L=this.getActiveConnection(Z);if(L)return L.getLastMessageTimestamp();f.a.warn("Attempted to get last message time from inactive peer.")}getSessionMetricsMessageCounts(Z){const L=this.getActiveConnection(Z);if(L)return L.getSessionMetricsMessageCounts();f.a.warn("Attempted to get session metrics counts from inactive peer.")}isReady(){if(this.config.lanOnlyMode)return!0;const{localPeer:Z,receiveSignalStream:L,iceServers:q}=this;return!!(Z&&L&&q)}shutdown(){return De(this,void 0,void 0,function*(){yield this.refreshInterval.stop(),this.receiveSignalStream&&this.receiveSignalStream.cancel();const Z=this.connections;this.connections=[],yield this.closeConnections(Z);const L=this.localConnections;this.localConnections=[],yield this.closeConnections(L),this.isOutgoingConnection.clear(),this.peerDataChannelListeners=[];const{localPeer:q}=this;if(!q||this.config.lanOnlyMode)return;const{signalingClient:ie}=this.config;yield(()=>De(this,void 0,void 0,function*(){try{const ae=new z.DeletePeerRequest;ae.setPeerId(q.getPeerId()),yield Y.withDeadline(ie.deletePeer(ae,yield this.getMetadata()),this.grpcCallDeadline)}catch(ae){return void f.a.warn("Error deleting local peer",{error:ae})}}))()})}createPeer(){return De(this,void 0,void 0,function*(){if(this.config.lanOnlyMode)throw new Error("createPeer method cannot be used in local-only mode.");const{signalingClient:Z}=this.config,L=yield(()=>De(this,void 0,void 0,function*(){try{return yield Y.withDeadline(Z.createPeer(new z.CreatePeerRequest,yield this.getMetadata()),this.grpcCallDeadline)}catch(ie){const ae=ie;f.a.debug("createPeer failed",{error:ae});const ue=jt(ae);throw new Error("Was not able to create peer: "+ue)}}))(),q=L==null?void 0:L.getPeer();if(!q)throw new Error("Response did not provide peer.");return this.localPeer=q})}createReceiveSignalStream(){return De(this,void 0,void 0,function*(){if(this.config.lanOnlyMode)throw new Error("createReceiveSignalStream method cannot be used in local-only mode.");const{signalingClient:Z}=this.config,{localPeer:L,iceServers:q}=this;if(!L||!q)return;const{receiveSignalStream:ie}=this;ie&&ie.cancel();const ae=new z.ReceiveSignalStreamRequest;ae.setPeerId(L.getPeerId());const ue=yield(()=>De(this,void 0,void 0,function*(){try{return Z.receiveSignalStream(ae,yield this.getMetadata({hasDeadline:!1}))}catch(Ue){f.a.debug("createReceiveSignalStream failed",{error:Ue});const fe=jt(Ue);throw new Error("Unable to create receive signal stream: "+fe)}}))();if(!ue)throw new Error("Response did not provide stream.");return ue.on("data",Ue=>De(this,void 0,void 0,function*(){var fe,ce,le,me;const Ve=Ue.getSignal(),Ce=(fe=Ve==null?void 0:Ve.getSessionId())===null||fe===void 0?void 0:fe.getValue(),xe=Ve==null?void 0:Ve.getSenderId(),He=Ve==null?void 0:Ve.getReceiverId(),Ye=(ce=Ve==null?void 0:Ve.getSessionCreatedTimestamp())===null||ce===void 0?void 0:ce.getValue();if(!(Ve&&Ce&&xe&&He&&Ye))return void f.a.warn("Received signal with missing information.");const $e=this.getActiveConnection(xe);if($e)if($e.getSessionId()!==Ce){if(f.a.debug("Received signal: different session for a peer we're already connected to."),($e.getSessionCreatedTimestamp()||0)>Ye)return;const Pe=new Vt(yield this.createRTCPeerConnection(q),q,{baseConfig:{isOffer:!1,isLan:!1,receive:(Me,Le)=>this.config.receive(Me,Le),onStreamsInfoUpdate:this.config.onStreamsInfoUpdate?(Me,Le)=>{var ze,qe;return(qe=(ze=this.config).onStreamsInfoUpdate)===null||qe===void 0?void 0:qe.call(ze,Me,Le)}:void 0,track:this.config.lanOnlyMode?void 0:this.config.track,localPeerId:L.getPeerId(),localUserId:(me=L.getUserId())===null||me===void 0?void 0:me.getValue(),remotePeerId:xe},remoteConfig:{sessionId:Ce,sessionCreatedTimestamp:Ye}},Me=>this.onCustomDataChannel(xe,Me));yield Pe.handleSignal(Ve),this.connections.push(Pe)}else f.a.debug("Received signal: for an existing connection."),yield $e.handleSignal(Ve);else{f.a.debug("Received signal: new connection.");const Pe=new Vt(yield this.createRTCPeerConnection(q),q,{baseConfig:{isOffer:!1,isLan:!1,receive:(Me,Le)=>this.config.receive(Me,Le),onStreamsInfoUpdate:this.config.onStreamsInfoUpdate?(Me,Le)=>{var ze,qe;return(qe=(ze=this.config).onStreamsInfoUpdate)===null||qe===void 0?void 0:qe.call(ze,Me,Le)}:void 0,track:this.config.lanOnlyMode?void 0:this.config.track,localPeerId:L.getPeerId(),localUserId:(le=L.getUserId())===null||le===void 0?void 0:le.getValue(),remotePeerId:xe},remoteConfig:{sessionId:Ce,sessionCreatedTimestamp:Ye}},Me=>this.onCustomDataChannel(xe,Me));yield Pe.handleSignal(Ve),this.connections.push(Pe)}})),ue.on("end",()=>{ue.cancel(),this.receiveSignalStream=void 0}),ue.on("error",Ue=>{switch(Ue.code){case v.StatusCode.CANCELLED:case v.StatusCode.UNAVAILABLE:case v.StatusCode.UNKNOWN:f.a.debug("Receive signal stream error",{error:Ue});break;case v.StatusCode.UNAUTHENTICATED:f.a.warn("Receive signal stream error",{error:Ue});break;default:f.a.error("Receive signal stream error",{error:Ue})}ue.cancel(),this.receiveSignalStream=void 0}),this.receiveSignalStream=ue})}createRTCPeerConnection(Z){var L;return De(this,void 0,void 0,function*(){const q=(L=this.config.alternateRTCPeerConnection)!==null&&L!==void 0?L:window.RTCPeerConnection;if(!q)throw function(){if(typeof navigator=="undefined")throw new Error("not a browser");const{userAgent:ie}=navigator;return ie.includes("Firefox/")?"Firefox":ie.includes("Edg/")?"Edge":ie.includes("Chrome/")?"Chrome":ie.includes("Safari/")?"Safari":ie.includes("MSIE/")||ie.includes("Trident/")?"IE":"Other"}()!=="Chrome"?new Error("WebRTC is not enabled. Please try again with the latest version of Google Chrome."):new Error("WebRTC is not enabled. Please ensure WebRTC is not disabled by ad blocking software.");this.rtcInstancesConstructed++,this.rtcInstancesConstructed%20||Nt();try{return new q({iceServers:Z})}catch(ie){throw f.a.debug(`Failed to create RTCPeerConnection: ${this.rtcInstancesConstructed} total allocated`),ie}})}closeConnections(Z){return De(this,void 0,void 0,function*(){const L=yield $(Z.map(q=>De(this,void 0,void 0,function*(){yield q.close()})));for(const q of L)f.a.warn("Request to close session failed",{error:q})})}getActiveConnection(Z){return this.getConnections().find(L=>L.getRemotePeerId()===Z&&L.isActive())}update(){var Z;return De(this,void 0,void 0,function*(){if(this.localConnections=this.localConnections.filter(me=>me.isActive()),this.config.lanOnlyMode)return;const{signalingClient:L}=this.config;if(!this.localPeer||!this.receiveSignalStream||!this.iceServers){const me=[];return this.localPeer||me.push(this.createPeer()),this.iceServers||me.push(this.updateIceServers()),yield Promise.all(me),void(this.receiveSignalStream||(yield this.createReceiveSignalStream()))}const[q,ie]=(ae=this.connections,ue=me=>me.isActive(),ae.reduce((me,Ve,Ce,xe)=>{const[He,Ye]=me;return(ue(Ve,Ce,xe)?He:Ye).push(Ve),me},[[],[]]));var ae,ue;yield this.closeConnections(ie),this.connections=q,this.gatherConnectionStats().catch(me=>{f.a.warn("Error calling gatherConnectionStats",{error:me})}),this.statsLoopsExecuted++;const{localPeer:Ue}=this,fe=this.connections.filter(me=>me.getSessionId).map(me=>O(me.getSessionId()));Ue.setSessionIdsList(fe);const ce=new z.RefreshPeerRequest;ce.setPeer(Ue);try{yield Y.withDeadline(L.refreshPeer(ce,yield this.getMetadata()),this.grpcCallDeadline)}catch(me){me instanceof v.RpcError&&me.code===v.StatusCode.NOT_FOUND?(f.a.warn("Peer expired, creating new peer",{peerId:Ue.getPeerId()}),yield this.reset()):f.a.warn("Error calling RefreshPeer",{error:me})}const le=yield this.getPeers();for(const me of this.connections)me.setRemoteDeviceId((Z=le.find(Ve=>Ve.id===me.getRemotePeerId()))===null||Z===void 0?void 0:Z.deviceId)})}gatherConnectionStats(){return De(this,void 0,void 0,function*(){if(this.statsLoopsExecuted%10!=0||this.connections.length!==1)return;const Z=yield this.connections[0].getConnectionStatsInfo(),L=Z?vt(Z):void 0;L?x.setTag("rtc-connection-type",L):x.setTag("rtc-connection-type","unknown")})}reset(){return De(this,void 0,void 0,function*(){yield this.closeConnections(this.connections),this.connections=[],this.isOutgoingConnection.clear(),yield this.createPeer(),yield this.createReceiveSignalStream()})}updateIceServers(){return De(this,void 0,void 0,function*(){if(this.config.lanOnlyMode)return;const{iceServersLastUpdate:Z,iceServersTtl:L}=this,q=new Date().getTime();if(!Z||q-Z>L)try{const ie=(yield Y.withDeadline(this.config.signalingClient.getIceServers(new z.GetIceServersRequest,yield this.getMetadata()),this.grpcCallDeadline)).getIceServers();this.iceServers=JSON.parse(ie),this.iceServersLastUpdate=q}catch(ie){f.a.warn("Error in updateIceServers",{error:ie})}})}setupHandlers(Z){const{peerConnection:L}=Z,q=Z.getSessionCreatedTimestamp();L.onconnectionstatechange=()=>De(this,void 0,void 0,function*(){const ie=L.connectionState;if(!q)return;const ae=Z.getRemoteDeviceId();switch(ie){case"connected":x.aggregate("rtc-connect-time",new Date().getTime()-q,Object.assign({},ae?{deviceId:ae}:{}));break;case"failed":x.increment("rtc-connect-failed",Object.assign({},ae?{deviceId:ae}:{}))}})}getMetadata(Z={}){return De(this,void 0,void 0,function*(){if(this.config.lanOnlyMode)throw new Error("getMetadata method cannot be called in local-only mode");const{getToken:L}=this.config,{grpcCallDeadline:q}=this,{hasDeadline:ie=!0}=Z,ae=ie?{deadline:(Date.now()+q).toString(10)}:null;try{const ue=yield L();return Object.assign({authorization:ue},ae)}catch(ue){throw f.a.error("getToken() failed",{error:ue}),new Error("Cannot get authorization token")}})}}var it=n(12),Rt=n(11),zt=function(Re,Z,L,q){return new(L||(L=Promise))(function(ie,ae){function ue(ce){try{fe(q.next(ce))}catch(le){ae(le)}}function Ue(ce){try{fe(q.throw(ce))}catch(le){ae(le)}}function fe(ce){var le;ce.done?ie(ce.value):(le=ce.value,le instanceof L?le:new L(function(me){me(le)})).then(ue,Ue)}fe((q=q.apply(Re,Z||[])).next())})};class kt{constructor(Z,L){this.sentMessagesCounts=new Map,this.receivedMessagesCounts=new Map,this.sessionId=Z,this.connection=L}incrementMessageSent(Z){const L=Oe(Z.header.stream);this.sentMessagesCounts.set(L,(this.sentMessagesCounts.get(L)||0)+1)}incrementMessageReceived(Z){const L=Oe(Z.header.stream);this.receivedMessagesCounts.set(L,(this.receivedMessagesCounts.get(L)||0)+1)}uploadMetrics(){return zt(this,void 0,void 0,function*(){const{sessionId:Z}=this,L=yield this.connection.peerConnection.getStats(),q={};L.forEach(ae=>q[ae.id]=ae),f.a.debug("rtc-stats",Object.assign(Object.assign({},q),{sessionId:Z}));const ie=[...new Set(Array.from(this.sentMessagesCounts.keys()).concat(Array.from(this.receivedMessagesCounts.keys())))].reduce((ae,ue)=>{const Ue=this.sentMessagesCounts.get(ue),fe=this.receivedMessagesCounts.get(ue);return Object.assign(Object.assign({},ae),{[ue+"-sent"]:Ue,[ue+"-received"]:fe})},{sessionId:Z});f.a.debug("rtc-message-report",ie)})}}function Bt(Re,Z){return Oe(Re)===Oe(Z)}var st=function(Re,Z,L,q){return new(L||(L=Promise))(function(ie,ae){function ue(ce){try{fe(q.next(ce))}catch(le){ae(le)}}function Ue(ce){try{fe(q.throw(ce))}catch(le){ae(le)}}function fe(ce){var le;ce.done?ie(ce.value):(le=ce.value,le instanceof L?le:new L(function(me){me(le)})).then(ue,Ue)}fe((q=q.apply(Re,Z||[])).next())})};class Mt{constructor(Z,L){this.peerConnection=Z,this.config=L,this.connectTimeoutMs=10*u.a.second,this.gatherIceTimeoutMs=5*u.a.second,this.pingUpdateTimeoutMs=2*u.a.second,this.streamLatestTimestamp=new Map,this.closeCalled=!1,this.connectCalled=!1,this.sentOffer=!1,this.receivedIceCandidate=!1;const{isOffer:q}=L;q?this.initializeChannels(Z):Z.ondatachannel=ie=>{switch(ie.channel.label){case"stream.latest-ttl":this.latestTtlStreamChannel=ie.channel;break;case"stream.reliable":this.reliableStreamChannel=ie.channel;break;case"stream.latest-reliable":this.latestReliableStreamChannel=ie.channel;break;case"stream.latest-try-once":this.latestTryOnceStreamChannel=ie.channel}this.setupChannel(ie.channel)},this.sessionMetrics=new kt(this.getSessionId(),this)}connect(){return st(this,void 0,void 0,function*(){if(this.connectCalled)return;this.connectCalled=!0,this.pingUpdateTimeout=setInterval(()=>{const{reliableStreamChannel:ie}=this;ie&&this.sendSystemMessage(ie,{type:"ping"})},this.pingUpdateTimeoutMs),this.connectTimeout=setTimeout(()=>st(this,void 0,void 0,function*(){this.isReady()||(f.a.warn("RTC connect timed out, closing connection"),yield this.close())}),this.connectTimeoutMs);const{peerConnection:Z,config:{isOffer:L,sessionId:q}}=this;if(L){const ie=yield Z.createOffer();yield Z.setLocalDescription(ie)}L&&(this.gatherIceTimeout=setTimeout(()=>st(this,void 0,void 0,function*(){this.sentOffer||(f.a.warn("ICE gathering timed out"),this.receivedIceCandidate?(f.a.warn("Attempting to connect with partial ICE candidate pool"),yield this.sendOffer()):yield this.close())}),this.gatherIceTimeoutMs),Z.onicecandidate=ie=>st(this,void 0,void 0,function*(){ie.candidate?this.receivedIceCandidate=!0:yield this.sendOffer()}),Z.onicegatheringstatechange=()=>st(this,void 0,void 0,function*(){Z.iceGatheringState==="complete"&&(yield this.sendOffer())}),Z.onnegotiationneeded=()=>{f.a.debug("Negotiation needed",{sessionId:q})})})}handleSignal(Z){return st(this,void 0,void 0,function*(){const{peerConnection:L,config:{sessionId:q,sendSignal:ie}}=this,{description:ae}=JSON.parse(Z.payload);if(f.a.debug("Handling signal",{sessionId:q,description:JSON.stringify(ae)}),ae)if(L.signalingState!=="stable"||L.connectionState!=="connected")if(L.remoteDescription)f.a.warn("Received SDP signal during negotiation when remote description is already set: "+JSON.stringify(Z));else if(ae.type==="offer"){yield L.setRemoteDescription(ae);const ue=yield L.createAnswer();yield L.setLocalDescription(ue),yield ie({payload:JSON.stringify({description:ue})})}else ae.type==="answer"&&(yield L.setRemoteDescription(ae));else f.a.warn("Received SDP signal when signaling is stable and connected: "+JSON.stringify(Z));else f.a.warn("Received non-SDP signal: "+JSON.stringify(Z))})}send(Z,L){const q=this.getChannelFromLabel(L.channelLabel);q?this.sendOnChannel(q,Z):f.a.warn("Send called with unexpected channel label",{channelLabel:L.channelLabel})}controlRemoteStream(Z){this.sendSystemMessage(O(this.reliableStreamChannel),{type:"stream-control",streamControl:Z})}isActive(){return new Set(["new","connecting","connected"]).has(this.peerConnection.connectionState)}isReady(){const{peerConnection:Z,latestTtlStreamChannel:L,reliableStreamChannel:q,latestTryOnceStreamChannel:ie}=this;return!!(q&&L&&ie)&&Z.connectionState==="connected"&&q.readyState==="open"&&L.readyState==="open"&&ie.readyState==="open"}isClosed(){const{peerConnection:Z,reliableStreamChannel:L,latestTryOnceStreamChannel:q,latestTtlStreamChannel:ie}=this;return!(Z.connectionState!=="closed"||L!==void 0&&L.readyState!=="closed"||q!==void 0&&q.readyState!=="closed"||ie!==void 0&&ie.readyState!=="closed")}needsClosing(){const{peerConnection:Z,latestTtlStreamChannel:L,reliableStreamChannel:q,latestTryOnceStreamChannel:ie}=this;if(this.isClosed())return!1;const ae=new Set(["closing","closed"]),ue=Ue=>Ue&&ae.has(Ue.readyState);return pt(Z)||ue(L)||ue(q)||ue(ie)}close(){return st(this,void 0,void 0,function*(){this.closeCalled||(this.closeCalled=!0,yield this.sessionMetrics.uploadMetrics(),this.pingUpdateTimeout&&clearInterval(this.pingUpdateTimeout),this.connectTimeout&&clearTimeout(this.connectTimeout),this.gatherIceTimeout&&clearTimeout(this.gatherIceTimeout),this.peerConnection.close())})}getPing(){return this.pingTimeMs}getLastMessageTimestamp(){return this.lastMessageTimestamp}getSessionId(){return this.config.sessionId}getRemotePeer(){return this.config.remotePeer}initializeChannels(Z){this.latestTtlStreamChannel=Z.createDataChannel("stream.latest-ttl",oe),this.reliableStreamChannel=Z.createDataChannel("stream.reliable",ge),this.latestReliableStreamChannel=Z.createDataChannel("stream.latest-reliable",Se),this.latestTryOnceStreamChannel=Z.createDataChannel("stream.latest-try-once",ve),this.setupChannel(this.latestTtlStreamChannel),this.setupChannel(this.reliableStreamChannel),this.setupChannel(this.latestReliableStreamChannel),this.setupChannel(this.latestTryOnceStreamChannel)}sendOffer(){return st(this,void 0,void 0,function*(){if(this.sentOffer||(this.sentOffer=!0,pt(this.peerConnection)))return;const{peerConnection:Z,config:{sendSignal:L}}=this,q=yield Z.createOffer();yield Z.setLocalDescription(q);const ie={payload:JSON.stringify({description:q})};yield L(ie)})}getChannelFromLabel(Z){switch(Z){case"stream.latest-ttl":return this.latestTtlStreamChannel;case"stream.reliable":return this.reliableStreamChannel;case"stream.latest-reliable":return this.latestReliableStreamChannel;case"stream.latest-try-once":return this.latestTryOnceStreamChannel}}sendOnChannel(Z,L){let q;try{q=Object(te.encode)(JSON.stringify(L))}catch(ie){return void f.a.warn("Failed to encode RTC message",{error:ie})}try{Z.send(q),this.sessionMetrics.incrementMessageSent(L)}catch(ie){f.a.warn("Failed to send message to channel",{error:ie,channel:Z.label})}}channelNotRecognized(Z){return Z!==this.latestTtlStreamChannel&&Z!==this.latestReliableStreamChannel&&Z!==this.latestTryOnceStreamChannel&&Z!==this.reliableStreamChannel}setupChannel(Z){Z.onmessage=L=>{if(this.channelNotRecognized(Z))return void f.a.warn("Received message on unrecognized data channel.");let q;try{q=JSON.parse(Object(te.decode)(L.data))}catch(ie){return void f.a.warn("Received unparseable RTC message",{error:ie,channel:Z.label})}if(this.lastMessageTimestamp=new Date().getTime(),q=_t(q),this.sessionMetrics.incrementMessageReceived(q),!this.handleSystemMessage(Z,q)){if(!this.hasCapabilities(q))return void f.a.warn("Received RTC message that was not within the capability scope of the connection.");(Z===this.latestTryOnceStreamChannel||Z===this.latestTtlStreamChannel||Z===this.latestReliableStreamChannel)&&!this.isLatestMessage(q)||this.config.receive(this.config.remotePeer.id,q)}},Z.onerror=L=>{f.a.warn("Channel error: "+L.error,{error:L.error,sessionId:this.getSessionId(),channelLabel:Z.label})},Z.onopen=()=>{f.a.debug("Channel opened",{sessionId:this.getSessionId(),channelLabel:Z.label})},Z.onclose=()=>{const L={bufferedAmount:Z.bufferedAmount,sessionId:this.getSessionId(),channelLabel:Z.label};this.closeCalled===!1?f.a.debug("Unexpected channel closed",L):f.a.debug("Channel closed",L)}}handleSystemMessage(Z,L){switch(L.header.stream.streamType){case"ping":return this.sendSystemMessage(Z,{type:"pong",timestamp:O(L.payload.ping)}),!0;case"pong":{const q=new Date().getTime()-O(L.payload.pong);return this.pingTimeMs=q,x.aggregate("rtc-ping-time",q),!0}case"stream-control":return!0;default:return!1}}sendSystemMessage(Z,L){if(Z.readyState!=="open")return;const q={entityId:O(this.config.localPeer.deviceId||this.config.localPeer.userId),streamName:"$."+L.type,streamType:L.type};let ie;switch(L.type){case"ping":ie={ping:new Date().getTime()};break;case"pong":ie={pong:L.timestamp};break;case"stream-control":ie={streamControl:L.streamControl}}this.sendOnChannel(Z,Ct(q,ie))}hasCapabilities(Z){var L,q;const{localPeer:ie,remotePeer:ae}=this.config,ue=(L=ie.capabilitySet.streaming)===null||L===void 0?void 0:L.streams,Ue=ue&&ue.some(le=>le.receive&&Bt(le.stream,Z.header.stream)),fe=(q=ae.capabilitySet.streaming)===null||q===void 0?void 0:q.streams,ce=fe&&fe.some(le=>le.send&&Bt(le.stream,Z.header.stream));return Ue||ce}isLatestMessage(Z){const L=Oe(Z.header.stream),q=(this.streamLatestTimestamp.get(L)||0)<=Z.header.created;return q&&this.streamLatestTimestamp.set(L,Z.header.created),q}}var Ae=function(Re,Z,L,q){return new(L||(L=Promise))(function(ie,ae){function ue(ce){try{fe(q.next(ce))}catch(le){ae(le)}}function Ue(ce){try{fe(q.throw(ce))}catch(le){ae(le)}}function fe(ce){var le;ce.done?ie(ce.value):(le=ce.value,le instanceof L?le:new L(function(me){me(le)})).then(ue,Ue)}fe((q=q.apply(Re,Z||[])).next())})};class Dt{constructor(Z){this.config=Z,this.connections=[],this.connectingSessions=new Map,this.rtcInstancesConstructed=0,this.updateInterval=T({func:()=>Ae(this,void 0,void 0,function*(){try{yield this.update()}catch(L){f.a.warn("RTC update failed",{error:L})}}),delay:250*u.a.millisecond,immediate:!0}),this.localPeer=this.createPeer()}send(Z,L,q){const ie=this.getActiveConnection(Z);ie?ie.isReady()?ie.send(L,q):f.a.warn("Attempted to send with an active connection to that peer which was not yet ready."):f.a.warn("Attempted to send with no active connection to that peer.")}controlRemoteStream(Z,L){const q=this.getActiveConnection(Z);q?q.isReady()?q.controlRemoteStream(L):f.a.warn("Attempted to control remote stream with an active connection to that peer which was not yet ready."):f.a.warn("Attempted to control remote stream with no active connection to that peer.")}connect(Z){return Ae(this,void 0,void 0,function*(){const L=yield this.getLocalPeer();if(this.getActiveConnection(Z))return void f.a.warn("Attempted to connect to peer with an already active connection.");let q;try{q=yield this.config.signalingClient.createSession(yield this.config.getToken(),{offerPeerId:L.id,answerPeerId:Z})}catch(ie){Object(it.a)(ie,Rt.a,ae=>ae.statusCode===404),f.a.warn("Attempted to connect to peer that does not exist.")}if(q)for(this.connectingSessions.set(q.id,new Date().getTime()),yield this.connectToSession(q);;)switch(yield Object(c.a)(.1),this.getConnectionStatus(Z)){case"connecting":continue;case"connected":return q.id;case"disconnected":return}})}getConnectionStatus(Z){const L=this.getActiveConnection(Z);return L?L.isReady()?"connected":"connecting":"disconnected"}getIceMode(Z){const L=this.getActiveConnection(Z);if(L)return L.iceMode}disconnect(Z){return Ae(this,void 0,void 0,function*(){const L=this.getActiveConnection(Z);L&&(yield this.closeConnection(L))})}getLocalPeer(){return Ae(this,void 0,void 0,function*(){return yield this.localPeer})}getPeers(){return Ae(this,void 0,void 0,function*(){return yield this.config.signalingClient.getPeers(yield this.config.getToken())})}getPing(Z){const L=this.getActiveConnection(Z);if(L)return L.getPing();f.a.warn("Attempted to get ping time from inactive peer.")}getLastMessageTimestamp(Z){const L=this.getActiveConnection(Z);if(L)return L.getLastMessageTimestamp();f.a.warn("Attempted to get ping time from inactive peer.")}shutdown(){return Ae(this,void 0,void 0,function*(){yield this.updateInterval.stop();const Z=this.connections;this.connections=[],yield this.closeConnections(Z)})}closeConnection(Z){return Ae(this,void 0,void 0,function*(){this.connectingSessions.delete(Z.getSessionId()),yield Z.close();try{yield this.config.signalingClient.deleteSession(yield this.config.getToken(),Z.getSessionId())}catch(L){Object(it.a)(L,Rt.a,q=>q.statusCode===404)}})}getSessions(){return Ae(this,void 0,void 0,function*(){const Z=yield this.getLocalPeer();return(yield this.config.signalingClient.getSessions(yield this.config.getToken())).filter(L=>L.offer.peer.id===Z.id||L.answer.peer.id===Z.id)})}createPeer(){return Ae(this,void 0,void 0,function*(){return yield this.config.signalingClient.createPeer(yield this.config.getToken(),{capabilitySet:this.config.capabilitySet||{}})})}createRTCPeerConnection(Z={}){return Ae(this,void 0,void 0,function*(){const L=this.config.alternateRTCPeerConnection||RTCPeerConnection;this.rtcInstancesConstructed++,this.rtcInstancesConstructed%20||Nt();try{return new L(Object.assign({iceServers:yield this.config.signalingClient.getIceServers(yield this.config.getToken())},Z))}catch(q){throw f.a.debug(`Failed to create RTCPeerConnection: ${this.rtcInstancesConstructed} total allocated`),q}})}closeConnections(Z){return Ae(this,void 0,void 0,function*(){const L=yield $(Z.map(q=>Ae(this,void 0,void 0,function*(){yield this.closeConnection(q)})));for(const q of L)f.a.warn("Request to close session failed",{error:q})})}reset(){return Ae(this,void 0,void 0,function*(){yield this.closeConnections(this.connections),this.connections=[],this.connectingSessions=new Map,this.localPeer=this.createPeer(),yield this.localPeer})}getActiveConnection(Z){return this.connections.find(L=>L.getRemotePeer().id===Z&&L.isActive())}update(){return Ae(this,void 0,void 0,function*(){const Z=yield this.getLocalPeer();try{yield this.config.signalingClient.refreshPeer(yield this.config.getToken(),Z.id)}catch(L){Object(it.a)(L,Rt.a,q=>q.statusCode===404),f.a.warn("Peer expired, creating new peer",{peerId:Z.id}),yield this.reset()}yield this.handleSessions(yield this.getSessions())})}handleSessions(Z){return Ae(this,void 0,void 0,function*(){yield this.syncConnectionsAndSessions(Z);const L=Z.map(q=>({session:q,connection:this.connections.find(ie=>ie.getSessionId()===q.id)}));yield Promise.all(L.map(({session:q,connection:ie})=>Ae(this,void 0,void 0,function*(){return yield this.maintainConnection(q,ie)})))})}syncConnectionsAndSessions(Z){return Ae(this,void 0,void 0,function*(){const L=new Set(Z.map(ae=>ae.id)),q=ae=>L.has(ae.getSessionId())||this.connectingSessions.has(ae.getSessionId());this.connections=this.connections.filter(ae=>q(ae));const ie=this.connections.filter(ae=>!q(ae)||ae.needsClosing());yield Promise.all(ie.map(ae=>Ae(this,void 0,void 0,function*(){yield this.closeConnection(ae)})))})}maintainConnection(Z,L){return Ae(this,void 0,void 0,function*(){const q=yield this.getLocalPeer(),ie=Z.offer.peer.id===q.id;if(L){if(L.isReady())try{yield this.config.signalingClient.refreshSession(yield this.config.getToken(),Z.id)}catch(ae){Object(it.a)(ae,Rt.a,ue=>ue.statusCode===404),f.a.debug("Refresh session not found",{sessionId:Z.id})}else if(L.isActive())try{yield this.consumeSignals(L)}catch(ae){f.a.warn("Failed to ingest signals, closing connection",{error:ae}),yield this.closeConnection(L)}}else{if(ie)return;yield this.connectToSession(Z)}})}connectToSession(Z){return Ae(this,void 0,void 0,function*(){const L=yield this.getLocalPeer(),q=Z.offer.peer.id===L.id,ie=yield this.createRTCPeerConnection(),ae=new Mt(ie,{localPeer:q?Z.offer.peer:Z.answer.peer,remotePeer:q?Z.answer.peer:Z.offer.peer,sessionId:Z.id,isOffer:q,sendSignal:ue=>this.sendSignal(Z.id,ue),receive:(ue,Ue)=>this.config.receive(ue,Ue)});if(this.connections.find(ue=>ue.getSessionId()===Z.id))return f.a.warn("connectToSession called on a session that already has a connection.",{sessionId:Z.id}),void(yield ae.close());this.setupHandlers(ae),this.connections.push(ae);try{yield ae.connect()}catch(ue){f.a.warn("Failed to handle negotiation, closing connection",{error:ue}),yield this.closeConnection(ae)}})}setupHandlers(Z){const{peerConnection:L}=Z,q=Z.getSessionId();L.onconnectionstatechange=()=>Ae(this,void 0,void 0,function*(){const ie=this.connectingSessions.get(q);if(ie===void 0)return;const ae=L.connectionState;switch(pt(L)&&this.connectingSessions.delete(q),ae){case"connected":{this.connectingSessions.delete(q);const ue=new Date().getTime()-ie;x.aggregate("rtc-connect-time",ue);break}case"failed":x.increment("rtc-connect-failed"),yield this.closeConnection(Z)}})}consumeSignals(Z){return Ae(this,void 0,void 0,function*(){let L=[];try{L=yield this.config.signalingClient.takeSignals(yield this.config.getToken(),Z.getSessionId())}catch(q){Object(it.a)(q,Rt.a,ie=>ie.statusCode===404)}for(const q of L)yield Z.handleSignal(q)})}sendSignal(Z,L){return Ae(this,void 0,void 0,function*(){try{yield this.config.signalingClient.addSignals(yield this.config.getToken(),Z,{signals:[L]})}catch(q){Object(it.a)(q,Rt.a,ie=>ie.statusCode===404)}})}}},,function(e,t,n){n.r(t),n.d(t,"LogClient",function(){return l});var r=n(26),o=n(12),s=n(11),g=function(u,c,d,B){return new(d||(d=Promise))(function(Q,U){function p(M){try{b(B.next(M))}catch(J){U(J)}}function f(M){try{b(B.throw(M))}catch(J){U(J)}}function b(M){var J;M.done?Q(M.value):(J=M.value,J instanceof d?J:new d(function(m){m(J)})).then(p,f)}b((B=B.apply(u,c||[])).next())})};class l extends r.a{log(c){return g(this,void 0,void 0,function*(){const d=l.token;try{yield this.fetch("logs",{token:d,method:"POST",body:{logs:c},allowUnsafeRetries:!0})}catch(B){Object(o.a)(B,s.a,Q=>Q.statusCode===401&&d!==void 0),l.token===d&&delete l.token,yield this.log(c)}})}}},function(e,t,n){var r={randomUUID:typeof crypto!="undefined"&&crypto.randomUUID&&crypto.randomUUID.bind(crypto)};let o;const s=new Uint8Array(16);function g(){if(!o&&(o=typeof crypto!="undefined"&&crypto.getRandomValues&&crypto.getRandomValues.bind(crypto),!o))throw new Error("crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported");return o(s)}const l=[];for(let c=0;c<256;++c)l.push((c+256).toString(16).slice(1));function u(c,d=0){return(l[c[d+0]]+l[c[d+1]]+l[c[d+2]]+l[c[d+3]]+"-"+l[c[d+4]]+l[c[d+5]]+"-"+l[c[d+6]]+l[c[d+7]]+"-"+l[c[d+8]]+l[c[d+9]]+"-"+l[c[d+10]]+l[c[d+11]]+l[c[d+12]]+l[c[d+13]]+l[c[d+14]]+l[c[d+15]]).toLowerCase()}t.a=function(c,d,B){if(r.randomUUID&&!d&&!c)return r.randomUUID();const Q=(c=c||{}).random||(c.rng||g)();if(Q[6]=15&Q[6]|64,Q[8]=63&Q[8]|128,d){B=B||0;for(let U=0;U<16;++U)d[B+U]=Q[U];return d}return u(Q)}}])})})(dist);var distExports=dist.exports;const SessionTypes={UNKNOWN:0,TELEOP:1,PORT_FORWARD:2,OBSERVE:3,HEADLESS:4},SessionTypeConstants={...SessionTypes,Unknown:SessionTypes.UNKNOWN,Teleop:SessionTypes.TELEOP,PortForward:SessionTypes.PORT_FORWARD,Observe:SessionTypes.OBSERVE,Headless:SessionTypes.HEADLESS,unknown:SessionTypes.UNKNOWN,teleop:SessionTypes.TELEOP,portForward:SessionTypes.PORT_FORWARD,observe:SessionTypes.OBSERVE,headless:SessionTypes.HEADLESS},singleton=Symbol("RtcClientPool.instance");class RtcClientPool{constructor(t){he(this,rt,null);he(this,"createClient");he(this,"ttlMs");he(this,"proxyHandler");he(this,"proxyReceivers",new Map);he(this,"teardownTimeout",null);he(this,"dispatch",(t,n)=>{this.proxyReceivers.forEach(r=>r==null?void 0:r(t,n))});const{createClient:n,ttlMs:r=0}=t;this.createClient=n,this.ttlMs=Math.max(r,0),this.proxyHandler={get:(o,s,g)=>{switch(s){case"shutdown":return()=>this.releaseInstance(g);default:return Reflect.get(o,s,g)}}}}get isActive(){return this[singleton]!==null}get size(){return this.proxyReceivers.size}get(t){const n=new Proxy(this.allocate(),this.proxyHandler);return this.proxyReceivers.set(n,t!=null?t:null),n}allocate(){if(this[singleton])return this.teardownTimeout&&(clearTimeout(this.teardownTimeout),this.teardownTimeout=null),this[singleton];const t=this.createClient(this.dispatch);return this[singleton]=t,t}async teardown(){const t=this[singleton];if(!t){console.warn("singleton has already been shutdown!");return}try{await t.shutdown()}finally{this[singleton]=null}}async releaseInstance(t){return this.proxyReceivers.delete(t)?this.proxyReceivers.size!==0?!1:(!this.teardownTimeout&&Number.isFinite(this.ttlMs)&&(this.ttlMs===0?await this.teardown():this.teardownTimeout=setTimeout(()=>{this.teardown().catch(n=>console.error("teardown failed",{err:n})).finally(()=>this.teardownTimeout=null)},this.ttlMs)),!0):(console.warn("this instance has already been released!"),!1)}}rt=singleton;const getToken=async()=>defined$1(Authentication.token,"Realtime when user isn't authorized"),EnumRtcClientPools={[SessionTypes.UNKNOWN]:new RtcClientPool({ttlMs:2500,createClient:e=>new distExports.RtcClient({signalingClient:new distExports.SignalingPromiseClient(exports.FORMANT_API_URL),getToken,sessionType:SessionTypes.UNKNOWN,receive:e})}),[SessionTypes.TELEOP]:new RtcClientPool({ttlMs:2500,createClient:e=>new distExports.RtcClient({signalingClient:new distExports.SignalingPromiseClient(exports.FORMANT_API_URL),getToken,sessionType:SessionTypes.TELEOP,receive:e})}),[SessionTypes.PORT_FORWARD]:new RtcClientPool({ttlMs:2500,createClient:e=>new distExports.RtcClient({signalingClient:new distExports.SignalingPromiseClient(exports.FORMANT_API_URL),getToken,sessionType:SessionTypes.PORT_FORWARD,receive:e})}),[SessionTypes.OBSERVE]:new RtcClientPool({ttlMs:2500,createClient:e=>new distExports.RtcClient({signalingClient:new distExports.SignalingPromiseClient(exports.FORMANT_API_URL),getToken,sessionType:SessionTypes.OBSERVE,receive:e})}),[SessionTypes.HEADLESS]:new RtcClientPool({ttlMs:2500,createClient:e=>new distExports.RtcClient({signalingClient:new distExports.SignalingPromiseClient(exports.FORMANT_API_URL),getToken,sessionType:SessionTypes.HEADLESS,receive:e})})},AppRtcClientPools={...EnumRtcClientPools,unknown:EnumRtcClientPools[SessionTypes.UNKNOWN],teleop:EnumRtcClientPools[SessionTypes.TELEOP],portForward:EnumRtcClientPools[SessionTypes.PORT_FORWARD],observe:EnumRtcClientPools[SessionTypes.OBSERVE],headless:EnumRtcClientPools[SessionTypes.HEADLESS]},defaultRtcClientPool=EnumRtcClientPools[SessionTypes.TELEOP],getRtcClientPool=e=>{const{sessionType:t}=e;return t?AppRtcClientPools[t]:defaultRtcClientPool};async function getPeers(){if(!Authentication.token)throw new Error("Not authenticated");const e=defaultRtcClientPool.get();try{return await e.getPeers()}finally{await e.shutdown()}}async function getRealtimeSessions(){if(!Authentication.token)throw new Error("Not authenticated");const e=defaultRtcClientPool.get();try{return await e.getSessions()}finally{await e.shutdown()}}async function getTelemetry(e,t,n,r,o,s){let g=e;Array.isArray(e)||(g=[e]);let l=t;return Array.isArray(t)||(l=[t]),(await(await fetch(`${exports.FORMANT_API_URL}/v1/queries/queries`,{method:"POST",body:JSON.stringify({deviceIds:g,end:r.toISOString(),names:l,start:n.toISOString(),tags:o,latestOnly:s}),headers:{"Content-Type":"application/json",Authorization:"Bearer "+Authentication.token}})).json()).items}async function patchDevice(e,t){if(!Authentication.token)throw new Error("Not authenticated");return await(await fetch(`${exports.FORMANT_API_URL}/v1/admin/devices/${e}`,{method:"PATCH",body:JSON.stringify(t),headers:{"Content-Type":"application/json",Authorization:"Bearer "+Authentication.token}})).json()}async function queryDevicesData(e){if(!Authentication.token)throw new Error("Not authenticated");return(await(await fetch(`${exports.FORMANT_API_URL}/v1/admin/devices/query`,{method:"POST",body:JSON.stringify(e),headers:{"Content-Type":"application/json",Authorization:"Bearer "+Authentication.token}})).json()).items}const isRtcPeer=e=>e!==void 0&&e.capabilities!==void 0&&e.capabilitySet!==void 0;var eventemitter3={exports:{}};(function(e){var t=Object.prototype.hasOwnProperty,n="~";function r(){}Object.create&&(r.prototype=Object.create(null),new r().__proto__||(n=!1));function o(u,c,d){this.fn=u,this.context=c,this.once=d||!1}function s(u,c,d,B,Q){if(typeof d!="function")throw new TypeError("The listener must be a function");var U=new o(d,B||u,Q),p=n?n+c:c;return u._events[p]?u._events[p].fn?u._events[p]=[u._events[p],U]:u._events[p].push(U):(u._events[p]=U,u._eventsCount++),u}function g(u,c){--u._eventsCount===0?u._events=new r:delete u._events[c]}function l(){this._events=new r,this._eventsCount=0}l.prototype.eventNames=function(){var c=[],d,B;if(this._eventsCount===0)return c;for(B in d=this._events)t.call(d,B)&&c.push(n?B.slice(1):B);return Object.getOwnPropertySymbols?c.concat(Object.getOwnPropertySymbols(d)):c},l.prototype.listeners=function(c){var d=n?n+c:c,B=this._events[d];if(!B)return[];if(B.fn)return[B.fn];for(var Q=0,U=B.length,p=new Array(U);Q<U;Q++)p[Q]=B[Q].fn;return p},l.prototype.listenerCount=function(c){var d=n?n+c:c,B=this._events[d];return B?B.fn?1:B.length:0},l.prototype.emit=function(c,d,B,Q,U,p){var f=n?n+c:c;if(!this._events[f])return!1;var b=this._events[f],M=arguments.length,J,m;if(b.fn){switch(b.once&&this.removeListener(c,b.fn,void 0,!0),M){case 1:return b.fn.call(b.context),!0;case 2:return b.fn.call(b.context,d),!0;case 3:return b.fn.call(b.context,d,B),!0;case 4:return b.fn.call(b.context,d,B,Q),!0;case 5:return b.fn.call(b.context,d,B,Q,U),!0;case 6:return b.fn.call(b.context,d,B,Q,U,p),!0}for(m=1,J=new Array(M-1);m<M;m++)J[m-1]=arguments[m];b.fn.apply(b.context,J)}else{var y=b.length,h;for(m=0;m<y;m++)switch(b[m].once&&this.removeListener(c,b[m].fn,void 0,!0),M){case 1:b[m].fn.call(b[m].context);break;case 2:b[m].fn.call(b[m].context,d);break;case 3:b[m].fn.call(b[m].context,d,B);break;case 4:b[m].fn.call(b[m].context,d,B,Q);break;default:if(!J)for(h=1,J=new Array(M-1);h<M;h++)J[h-1]=arguments[h];b[m].fn.apply(b[m].context,J)}}return!0},l.prototype.on=function(c,d,B){return s(this,c,d,B,!1)},l.prototype.once=function(c,d,B){return s(this,c,d,B,!0)},l.prototype.removeListener=function(c,d,B,Q){var U=n?n+c:c;if(!this._events[U])return this;if(!d)return g(this,U),this;var p=this._events[U];if(p.fn)p.fn===d&&(!Q||p.once)&&(!B||p.context===B)&&g(this,U);else{for(var f=0,b=[],M=p.length;f<M;f++)(p[f].fn!==d||Q&&!p[f].once||B&&p[f].context!==B)&&b.push(p[f]);b.length?this._events[U]=b.length===1?b[0]:b:g(this,U)}return this},l.prototype.removeAllListeners=function(c){var d;return c?(d=n?n+c:c,this._events[d]&&g(this,d)):(this._events=new r,this._eventsCount=0),this},l.prototype.off=l.prototype.removeListener,l.prototype.addListener=l.prototype.on,l.prefixed=n,l.EventEmitter=l,e.exports=l})(eventemitter3);var eventemitter3Exports=eventemitter3.exports;const EventEmitter=getDefaultExportFromCjs(eventemitter3Exports);class Manipulator{constructor(t,n){he(this,"currentListeners",[]);he(this,"onRealtimeMessage",(t,n)=>{n.payload.jointState&&this.currentListeners.forEach(r=>{n.payload.jointState&&r(n.payload.jointState)})});this.device=t,this.config=n}async synchronize(){this.device.addRealtimeListener(this.onRealtimeMessage),this.device.startListeningToRealtimeDataStream(this.config.currentJointStateStream)}async desynchronize(){this.device.removeRealtimeListener(this.onRealtimeMessage),this.device.stopListeningToRealtimeDataStream(this.config.currentJointStateStream)}async addCurrentJointStateListener(t){this.currentListeners.push(t)}}class RequestDataChannel{constructor(t,n,r){he(this,"channel");he(this,"requestIdToResponseMap",new Map);this.device=t,this.channel_name=n,this.timeout=r}addOpenListener(t){defined$1(this.channel,"channel not initalized").addOpenListener(t)}removeOpenListener(t){defined$1(this.channel,"channel not initalized").removeOpenListener(t)}addCloseListener(t){defined$1(this.channel,"channel not initalized").addCloseListener(t)}removeCloseListener(t){defined$1(this.channel,"channel not initalized").removeCloseListener(t)}addErrorListener(t){defined$1(this.channel,"channel not initalized").addErrorListener(t)}removeErrorListener(t){defined$1(this.channel,"channel not initalized").removeErrorListener(t)}}class BinaryRequestDataChannel extends RequestDataChannel{constructor(){super(...arguments);he(this,"RESPONSE_SUCCESS_BYTE",0);he(this,"decoder",new TextDecoder)}generateBinaryId(){const n=new Uint8Array(16);for(let r=0;r<n.length;r++)n[r]=Math.floor(Math.random()*256);return n}async initialize(){this.channel=await this.device.createCustomDataChannel(this.channel_name),this.channel.addBinaryListener(n=>{const o=n.slice(0,16).toString();if(o.length===0)throw new Error("Invalid response");const s=n.slice(16);if(s.length===0)throw new Error("Invalid response");this.requestIdToResponseMap.has(o)&&this.requestIdToResponseMap.set(o,s)})}async request(n){if(this.channel||await this.initialize(),!this.channel)throw new Error("Failed to create channel");const{channel:r,requestIdToResponseMap:o,timeout:s}=this;await r.waitTilReady();const g=this.generateBinaryId(),l=g.toString();o.set(l,!0),r.sendBinary(new Uint8Array([...g,...n]));const u=new Date().getTime();for(;new Date().getTime()<u+s;)if(await delay$1(50),o.has(l)){const c=o.get(l);if(c!==!0){o.delete(l);const d=c[0]===this.RESPONSE_SUCCESS_BYTE,B=c.slice(1);if(d)return B;throw console.error({name:"AdapterError",message:this.decoder.decode(B)}),new Error("Binary request datachannel adapter error")}}throw o.delete(l),console.error({name:"TimeoutError",message:`Request timed out after ${s/1e3} seconds`}),new Error("Binary request data channel request timed out")}}class TextRequestDataChannel extends RequestDataChannel{generateTextId(){return Math.random().toString(36).substring(2)+"-"+Math.random().toString(36).substring(2)}async initialize(){this.channel=await this.device.createCustomDataChannel(this.channel_name),this.channel.addListener(t=>{const n=JSON.parse(t),{id:r,data:o,error:s}=n;if(!r)throw new Error("Invalid response");if(!o&&!s)throw new Error("Invalid response");this.requestIdToResponseMap.has(r)&&this.requestIdToResponseMap.set(r,n)})}async request(t){if(this.channel||await this.initialize(),!this.channel)throw new Error("Failed to create channel");const{channel:n,requestIdToResponseMap:r,timeout:o}=this;await n.waitTilReady();const s=this.generateTextId();r.set(s,!0),n.send(JSON.stringify({id:s,data:t}));const g=new Date().getTime();for(;new Date().getTime()<g+o;)if(await delay$1(50),r.has(s)){const l=r.get(s);if(l!==!0){r.delete(s);const{data:u,error:c}=l;if(u)return u;if(c)throw console.error({name:"AdapterError",message:c}),new Error("Text request datachannel adapter error")}}throw r.delete(s),console.error({name:"TimeoutError",message:`Request timed out after ${o/1e3} seconds`}),new Error("Text request datachannel request timed out")}}class BaseDevice extends EventEmitter{constructor(){super(...arguments);he(this,"rtcClient");he(this,"remoteDevicePeerId",null);he(this,"realtimeListeners",[]);he(this,"connectionMonitorInterval");he(this,"handleMessage",(n,r)=>{this.realtimeListeners.forEach(o=>o(n,r))})}stopConnectionMonitoring(){clearInterval(this.connectionMonitorInterval),this.connectionMonitorInterval=void 0}assertNotCancelled(n){if(n)throw new Error("Cancelled by deadline")}getRealtimeStatus(){if(this.rtcClient&&this.remoteDevicePeerId)return this.rtcClient.getConnectionStatus(this.remoteDevicePeerId);throw new Error("Realtime connection hasn't been started")}getRealtimePingInfo(){if(this.rtcClient&&this.remoteDevicePeerId)return this.rtcClient.getPingInfo(this.remoteDevicePeerId);throw new Error("Realtime connection hasn't been started")}getRealtimePing(){if(this.rtcClient&&this.remoteDevicePeerId)return this.rtcClient.getPing(this.remoteDevicePeerId);throw new Error("Realtime connection hasn't been started")}addRealtimeListener(n){this.realtimeListeners.push(n)}removeRealtimeListener(n){const r=this.realtimeListeners.indexOf(n);if(r===-1)throw new Error("Could not find realtime listener to remove");this.realtimeListeners.splice(r,1)}async getRealtimeManipulators(){var o;const n=await this.getConfiguration(),r=[];for(const s of(o=n.teleop.rosStreams)!=null?o:[])s.topicType=="sensor_msgs/JointState"&&r.push(new Manipulator(this,{currentJointStateStream:{name:s.topicName},plannedJointStateStream:s.plannedTopic?{name:s.plannedTopic}:void 0,planValidStream:s.planValidTopic?{name:s.planValidTopic}:void 0,endEffectorStream:s.endEffectorTopic?{name:s.endEffectorTopic}:void 0,endEffectorLinkName:s.endEffectorLinkName,baseReferenceFrame:s.baseReferenceFrame,localFrame:s.localFrame}));return r}async getRealtimeVideoStreams(){var o,s,g,l,u,c;const n=await this.getConfiguration(),r=[];for(const d of(s=(o=n.teleop)==null?void 0:o.hardwareStreams)!=null?s:[])d.rtcStreamType==="h264-video-frame"&&r.push({name:d.name});for(const d of(l=(g=n.teleop)==null?void 0:g.rosStreams)!=null?l:[])d.topicType=="formant/H264VideoFrame"&&r.push({name:d.topicName}),(d.topicType==="sensor_msgs/Image"||d.topicType==="sensor_msgs/CompressedImage")&&d.encodeVideo&&r.push({name:d.topicName});for(const d of(c=(u=n.teleop)==null?void 0:u.customStreams)!=null?c:[])d.rtcStreamType==="h264-video-frame"&&r.push({name:d.name});return r}createCustomRequestDataChannel(n,r=3e3){return new TextRequestDataChannel(this,n,r)}createCustomBinaryRequestDataChannel(n,r=3e3){return new BinaryRequestDataChannel(this,n,r)}async startListeningToRealtimeVideo(n){const r=defined$1(this.rtcClient,"Realtime connection has not been started"),o=await this.getRemotePeer();r.controlRemoteStream(defined$1(o).id,{streamName:n.name,enable:!0,pipeline:"rtc"})}async stopListeningToRealtimeVideo(n){const r=defined$1(this.rtcClient,"Realtime connection has not been started"),o=await this.getRemotePeer();r.controlRemoteStream(defined$1(o).id,{streamName:n.name,enable:!1,pipeline:"rtc"})}async startListeningToRealtimeDataStream(n){const r=defined$1(this.rtcClient,"Realtime connection has not been started"),o=await this.getRemotePeer();r.controlRemoteStream(defined$1(o).id,{streamName:n.name,enable:!0,pipeline:"rtc"})}async stopListeningToRealtimeDataStream(n){const r=defined$1(this.rtcClient,"Realtime connection has not been started"),o=await this.getRemotePeer();r.controlRemoteStream(defined$1(o).id,{streamName:n.name,enable:!1,pipeline:"rtc"})}async enableRealtimeTelemetryPriorityIngestion(n){const r=defined$1(this.rtcClient,"Realtime connection has not been started"),o=await this.getRemotePeer();r.controlRemoteStream(defined$1(o).id,{streamName:n,enablePriorityUpload:!0,pipeline:"telemetry"})}async disableRealtimeTelemetryPriorityIngestion(n){const r=defined$1(this.rtcClient,"Realtime connection has not been started"),o=await this.getRemotePeer();r.controlRemoteStream(defined$1(o).id,{streamName:n,enablePriorityUpload:!1,pipeline:"telemetry"})}async changeStreamAudioType(n,r){const o=defined$1(this.rtcClient,"Realtime connection has not been started"),s=await this.getRemotePeer();o.controlRemoteStream(defined$1(s).id,{streamName:n,setAudioFormat:r})}async createCustomDataChannel(n,r){const o=defined$1(this.rtcClient,"Realtime connection has not been started"),s=await this.getRemotePeer(),g=await new Promise(l=>{o.createCustomDataChannel(defined$1(s).id,n,{ordered:!0,...r},!1,(u,c)=>{const d=new DataChannel(c);l(d)})});return await g.waitTilReady(),g}async sendRealtimeMessage(n,r={channelLabel:"stream.reliable"}){const o=defined$1(this.rtcClient,"Realtime connection has not been started"),s=await this.getRemotePeer();o.send(defined$1(s).id,n,r)}async getRealtimeAudioStreams(){var o,s,g,l,u,c;const n=await this.getConfiguration(),r=[];for(const d of(s=(o=n.teleop)==null?void 0:o.hardwareStreams)!=null?s:[])d.rtcStreamType==="audio-chunk"&&r.push({name:d.name});for(const d of(l=(g=n.teleop)==null?void 0:g.rosStreams)!=null?l:[])d.topicType=="audio_common_msgs/AudioData"&&r.push({name:d.topicName});for(const d of(c=(u=n.teleop)==null?void 0:u.customStreams)!=null?c:[])d.rtcStreamType==="audio-chunk"&&r.push({name:d.name});return r}}class Device extends BaseDevice{constructor(t,n,r,o){super(),this.id=t,this.name=n,this.organizationId=r,this.tags=o}async getLatestTelemetry(){return(await(await fetch(`${exports.FORMANT_API_URL}/v1/queries/stream-current-value`,{method:"POST",body:JSON.stringify({deviceIds:[this.id]}),headers:{"Content-Type":"application/json",Authorization:"Bearer "+Authentication.token}})).json()).items}async getConfiguration(t=!1){let n=await fetch(`${exports.FORMANT_API_URL}/v1/admin/devices/${this.id}`,{method:"GET",headers:{"Content-Type":"application/json",Authorization:"Bearer "+Authentication.token}});const r=await n.json();if(!r.state.reportedConfiguration)throw new Error("Device has no configuration, has it ever been turned on?");const o=t?r.desiredConfigurationVersion:r.state.reportedConfiguration.version;return n=await fetch(`${exports.FORMANT_API_URL}/v1/admin/devices/${this.id}/configurations/${o}`,{method:"GET",headers:{"Content-Type":"application/json",Authorization:"Bearer "+Authentication.token}}),(await n.json()).document}async getAgentVersion(){var r;const n=await(await fetch(`${exports.FORMANT_API_URL}/v1/admin/devices/${this.id}`,{method:"GET",headers:{"Content-Type":"application/json",Authorization:"Bearer "+Authentication.token}})).json();return(r=n==null?void 0:n.state)==null?void 0:r.agentVersion}async getFileUrl(t){return(await(await fetch(`${exports.FORMANT_API_URL}/v1/admin/files/query`,{method:"POST",body:JSON.stringify({fileIds:[t]}),headers:{"Content-Type":"application/json",Authorization:"Bearer "+Authentication.token}})).json()).fileUrls}async startRealtimeConnection(t={}){if(console.debug(`${new Date().toISOString()} :: Connection start requested`),this.rtcClient&&this.connectionMonitorInterval!==void 0)throw new Error(`Already created realtime connection to device ${this.id}`);this.rtcClient&&console.warn("overwriting existing rtcClient due to missing connectionMonitorInterval");const{sessionType:n,deadlineMs:r=1e4,maxConnectRetries:o=3}=typeof t=="number"?{sessionType:t}:t,g=getRtcClientPool({sessionType:n}).get(this.handleMessage);let l=!1;const u=new Promise((d,B)=>setTimeout(()=>{l=!0,B(new Error("Connection timed out: the connection could not be finalized in time, possibly due to network issues or misconfigured settings."))},r)),c=async()=>{if("isReady"in g)for(;!g.isReady();)this.assertNotCancelled(l),await delay$1(100);const d=await this.getRemoteDevicePeerId(g);this.assertNotCancelled(l);let B;for(let U=0;U<o&&(B=await g.connect(d),!B);U++)delay$1(100),this.assertNotCancelled(l);if(!B)throw new Error(`Session could not be created: exhausted ${o} retries`);let Q=0;for(;!l&&g.getConnectionStatus(d)!=="connected";)await delay$1(100),Q+=1;return this.assertNotCancelled(l),console.debug(`${new Date().toISOString()} :: Connection completed after ${Q} retries`),d};return Promise.race([c(),u]).then(d=>{this.remoteDevicePeerId=d,this.initConnectionMonitoring(),this.rtcClient=g,this.emit("connect")}).catch(d=>{throw console.debug(`${new Date().toISOString()} :: Connection failed: %o`,d),this.remoteDevicePeerId=null,g.shutdown().catch(B=>{console.error("rtcClient cannot shutdown: %o",B)}),this.emit("connection_failed",d),d})}async getRemoteDevicePeerId(t){const r=(await t.getPeers()).find(o=>o.deviceId===this.id);if(!isRtcPeer(r))throw new Error("Cannot find peer, is the robot offline?");return r.id}initConnectionMonitoring(){this.connectionMonitorInterval=setInterval(async()=>{let t=!1;if(this.rtcClient){const r=this.rtcClient.getConnections().find(o=>o.getRemotePeerId()===this.remoteDevicePeerId&&o.isActive());(r===void 0||!r.isReady())&&(console.debug(`${new Date().toISOString()} :: data channel closed`),t=!0)}(!this.rtcClient||!this.remoteDevicePeerId||await this.rtcClient.getConnectionStatsInfo(this.remoteDevicePeerId)===void 0||t)&&(this.emit("disconnect"),this.stopRealtimeConnection().catch(n=>{console.error(n)}))},1e3)}async getRemotePeer(){const n=(await defined$1(this.rtcClient,"Realtime connection has not been started").getPeers()).find(r=>r.deviceId===this.id);return defined$1(n,"Could not find remote peer for device "+this.id)}async stopRealtimeConnection(){let t=!1;if(this.rtcClient){this.stopConnectionMonitoring(),this.remoteDevicePeerId?(await this.rtcClient.disconnect(this.remoteDevicePeerId),this.remoteDevicePeerId=null):t=!0;try{await this.rtcClient.shutdown()}finally{this.rtcClient=void 0}}if(t)throw new Error(`Realtime connection hasn't been started for ${this.id}`)}async isInRealtimeSession(){const t=await getPeers(),n=await getRealtimeSessions(),r=t.find(o=>o.deviceId===this.id);return r?n[r.id].length>0:!1}async getAvailableCommands(t=!0){return(await(await fetch(`${exports.FORMANT_API_URL}/v1/admin/command-templates/`,{method:"GET",headers:{"Content-Type":"application/json",Authorization:"Bearer "+Authentication.token}})).json()).items.map(o=>({name:o.name,id:o.id,command:o.command,description:o.description,parameterEnabled:o.parameterEnabled,parameterValue:o.parameterValue,parameterMeta:o.parameterMeta,enabled:o.enabled,tags:o.tags})).filter(o=>t?!0:o.enabled)}async sendCommand(t,n,r,o,s){var B;const l=(await this.getAvailableCommands(!1)).find(Q=>s?Q.id===s:Q.name===t);if(!l)throw new Error(`Could not find command with name "${t}"`);let u="";n===void 0?l.parameterEnabled&&l.parameterValue&&(u=l.parameterValue):u=n;let c={value:u,scrubberTime:(r||new Date).toISOString(),meta:{...l.parameterMeta,...o}};return await fetch(`${exports.FORMANT_API_URL}/v1/admin/commands`,{method:"POST",body:JSON.stringify({commandTemplateId:l.id,organizationId:this.organizationId,deviceId:this.id,command:l.command,parameter:c,userId:(B=Authentication.currentUser)==null?void 0:B.id}),headers:{"Content-Type":"application/json",Authorization:"Bearer "+Authentication.token}})}async getCommand(t){return await fetch(`${exports.FORMANT_API_URL}/v1/admin/commands/${t}`,{method:"GET",headers:{"Content-Type":"application/json",Authorization:"Bearer "+Authentication.token}})}async createCaptureStream(t){const r=await(await fetch(`${exports.FORMANT_API_URL}/v1/admin/capture-sessions`,{method:"POST",body:JSON.stringify({deviceId:this.id,streamName:t,tags:{}}),headers:{"Content-Type":"application/json",Authorization:"Bearer "+Authentication.token}})).json();return new CaptureStream(r)}async getTelemetry(t,n,r,o,s,g,l){if(s!==void 0||g!==void 0)throw new Error("Limit and offset are not supported in this method");return await getTelemetry(this.id,t,n,r,o,l)}async queryEvents(t){if(t.deviceIds)throw new Error("Cannot filter multiple devices via Device class");return t.deviceIds=[this.id],queryEvents(t)}async getTelemetryStreams(){var l,u;const t=await this.getConfiguration(),n=await fetch(`${exports.FORMANT_API_URL}/v1/queries/metadata/stream-names`,{method:"POST",body:JSON.stringify({deviceIds:[this.id]}),headers:{"Content-Type":"application/json",Authorization:"Bearer "+Authentication.token}}),r=[],o=[];return(u=(l=t.telemetry)==null?void 0:l.streams)==null||u.forEach(c=>{c.disabled!==!0&&r.push(c.name),c.onDemand===!0&&o.push(c.name)}),console.log(o),(await n.json()).items.filter(c=>!r.includes(c)).map(c=>({name:c,onDemand:o.includes(c)}))}async createInterventionRequest(t,n,r,o){return await(await fetch(`${exports.FORMANT_API_URL}/v1/admin/intervention-requests`,{method:"POST",body:JSON.stringify({message:t,interventionType:n,time:new Date().toISOString(),deviceId:this.id,tags:o,data:r}),headers:{"Content-Type":"application/json",Authorization:"Bearer "+Authentication.token}})).json()}async addInterventionResponse(t,n,r){return await(await fetch(`${exports.FORMANT_API_URL}/v1/admin/intervention-responses`,{method:"POST",body:JSON.stringify({interventionId:t,interventionType:n,data:r}),headers:{"Content-Type":"application/json",Authorization:"Bearer "+Authentication.token}})).json()}async getAnnotationCount(t,n){return await getAnnotationCount({...t,deviceIds:[this.id]},n)}async getAnnotationCountByIntervals(t,n,r){return await getAnnotationCountByIntervals({...t,deviceIds:[this.id]},n,r)}async eventsCounter(t,n,r,o,s){return await eventsCounter(t,n,r,o,{...s,deviceIds:[this.id]})}async createShareLink(t,n){return t.scope.deviceIds=[this.id],await createShareLink(t,n)}}he(Device,"createDevice",createDevice),he(Device,"patchDevice",patchDevice),he(Device,"getDevicesData",getDevicesData),he(Device,"queryDevicesData",queryDevicesData),he(Device,"disableDevice",disableDevice);class PeerDevice extends BaseDevice{constructor(n){super();he(this,"id");he(this,"telemetryStreamActive",!1);he(this,"streamTelemetry",{});this.peerUrl=n}async getLatestTelemetry(){this.telemetryStreamActive||this.subscribeToTelemetry();const n=this.streamTelemetry;return Object.entries(n).map(([o,s])=>({deviceId:this.id,streamName:o,streamType:"json",currentValue:s,currentValueTime:s.timestamp,tags:{}}))}async getTelemetry(n,r,o,s,g,l,u){if(Array.isArray(n))throw new Error("Multiple stream names not supported");if(s)throw new Error("Tags not supported");if(u&&g===void 0)g=1;else if(u&&g!==void 0)throw new Error("latestOnly and limit cannot be used together");let c=`${this.peerUrl}/v1/querydatapoints?stream_name=${n}&start=${r.toISOString()}&end=${o.toISOString()}`;g!=null&&g>0&&(c+=`&limit=${g}`),l!=null&&l>=0&&(c+=`&offset=${l}`);const B=await(await fetch(c)).json(),Q=[];for(const U of B.results){const p=parseInt(U.timestamp),f=U.tags.data_type;delete U.tags.data_type,Q.push({deviceId:this.id,name:U.stream,points:[[p,this.getPointPayload(f,U)]],tags:U.tags,type:f})}return Q.reverse()}async queryEvents(n){const r=["id","viewed","keyword","message","sort","eventTypes","notificationEnabled","userIds","annotationTemplateIds","disableNullMatches","severities","deviceIds","names","types","tags","notNames"];this.checkKeysAndThrow(n,r);let o=`${this.peerUrl}/v1/queryevents?start=${n.start}&end=${n.end}`;n.count!=null&&n.count>0&&(o+=`&limit=${n.count}`),n.offset!=null&&n.offset>=0&&(o+=`&offset=${n.offset}`);const g=await(await fetch(o)).json(),l=[];for(const u of g.results){const c=parseInt(u.timestamp),d={deviceId:this.id,time:new Date(c).toISOString(),message:u.message,notificationEnabled:u.notificationEnabled,type:u.type,tags:u.tags};u.id!==""&&(d.id=u.id),u.type!==""&&(d.type=u.type),u.streamName!==""&&(d.streamName=u.streamName),u.streamType!==""&&(d.streamType=u.streamType),u.severity!==""&&(d.severity=u.severity.toLowerCase()),u.tags&&(d.tags=u.tags),u.endTimestamp!=="0"&&(d.endTime=new Date(parseInt(u.endTimestamp)).toISOString()),l.push(d)}return l.reverse()}checkKeysAndThrow(n,r){const o=r.filter(s=>s in n);if(o.length>0)throw new Error(`Filters not currently supported: ${o.join(", ")}.`)}getPointPayload(n,r){switch(n){case"numeric":return r.numeric.value;case"numeric set":return r.numericSet.numerics;case"text":return r.text.value;case"json":return r.json.value;case"bitset":const o=[],s=[];for(const g of r.bitset.bits)o.push(g.key),s.push(g.value);return{keys:o,values:s};case"location":return r.location;case"health":return r.health;case"battery":return r.battery;default:return{}}}subscribeToTelemetry(){this.telemetryStreamActive=!0;let n=0;const r=new XMLHttpRequest;r.responseType="text",r.addEventListener("error",o=>{this.handleXHRError("error")}),r.addEventListener("abort",o=>{this.handleXHRError("abort")}),r.addEventListener("timeout",o=>{this.handleXHRError("timeout")}),r.addEventListener("readystatechange",o=>{r.readyState===XMLHttpRequest.DONE&&this.handleXHRError("closed")}),r.addEventListener("progress",o=>{const s=o.loaded,g=s-n;n=s,r.responseText.substr(-g).split(`
|
|
63
63
|
`).forEach(c=>{var d;if(c.length>0){const B=JSON.parse(c);if((d=B.result)!=null&&d.datapoint){const Q=B.result.datapoint,U=Q.stream;delete Q.stream,this.streamTelemetry[U]=Q}}})}),r.open("POST",`${this.peerUrl}/v1/telemetry`),r.send()}handleXHRError(n){console.warn(`Telemetry stream ended: ${n}`),this.telemetryStreamActive=!1}async getDeviceId(){return(await(await fetch(`${this.peerUrl}/v1/config`)).json()).configuration.id}async getConfiguration(){return(await(await fetch(`${this.peerUrl}/v1/config`)).json()).configuration.document}async getViews(){return(await(await fetch(`${this.peerUrl}/v1/views`)).json()).views}async startRealtimeConnection(n){if(console.debug(`${new Date().toISOString()} :: Connection start requested`),this.rtcClient&&this.connectionMonitorInterval!==void 0)throw new Error(`Already created realtime connection to device ${this.id}`);this.rtcClient&&console.warn("overwriting existing rtcClient due to missing connectionMonitorInterval");const r=new distExports.RtcClient({lanOnlyMode:!0,receive:this.handleMessage,sessionType:n});for(await r.connectLan(this.peerUrl);r.getConnectionStatus(this.peerUrl)!=="connected";)await delay$1(100);this.rtcClient=r,this.initConnectionMonitoring()}initConnectionMonitoring(){this.connectionMonitorInterval=setInterval(async()=>{let n=!1;this.rtcClient&&this.rtcClient.getConnectionStatus(this.peerUrl)!=="connected"&&(console.debug(`${new Date().toISOString()} :: data channel closed`),n=!0),(!this.rtcClient||n)&&(this.emit("disconnect"),this.stopRealtimeConnection().catch(r=>{console.error(r)}))},1e3)}async getRemotePeer(){return{id:this.peerUrl,organizationId:"",deviceId:this.id,capabilities:[],capabilitySet:{}}}async stopRealtimeConnection(){let n=!1;if(this.rtcClient){this.stopConnectionMonitoring(),this.id?(await this.rtcClient.disconnect(this.id),this.remoteDevicePeerId=null):n=!0;try{await this.rtcClient.shutdown()}finally{this.rtcClient=void 0}}if(n)throw new Error(`Realtime connection hasn't been started for ${this.id}`)}async getCommandMetadata(){return(await fetch(`${this.peerUrl}/v1/commands`)).json()}async sendCommand(n,r,o,s){const g={value:r,scrubberTime:(o||new Date).toISOString(),meta:s};return await fetch(`${this.peerUrl}/v1/enqueue-command`,{method:"POST",body:JSON.stringify({command:n,parameter:g}),headers:{"Content-Type":"application/json"}})}}async function addDeviceToFleet(e,t){if(!Authentication.token)throw new Error("Not authenticated");return await(await fetch(`${exports.FORMANT_API_URL}/v1/admin/devices/${e}`,{method:"PATCH",body:JSON.stringify({fleetId:t}),headers:{"Content-Type":"application/json",Authorization:"Bearer "+Authentication.token}})).json()}async function aggregateTelemetry(e){if(!Authentication.token)throw new Error("Not authenticated");return(await(await fetch(`${exports.FORMANT_API_URL}/v1/queries/queries`,{method:"POST",body:JSON.stringify(e),headers:{"Content-Type":"application/json",Authorization:"Bearer "+Authentication.token}})).json()).aggregates}async function deleteFleet(e){if(!Authentication.token)throw new Error("Not authenticated");await fetch(`${exports.FORMANT_API_URL}/v1/admin/fleets/${e}`,{method:"DELETE",headers:{"Content-Type":"application/json",Authorization:"Bearer "+Authentication.token}})}async function getAnalyticStreams(){if(!Authentication.token)throw new Error("Not authenticated");return(await(await fetch(`${exports.FORMANT_API_URL}/v1/queries/analytics/streams`,{method:"GET",headers:{"Content-Type":"application/json",Authorization:"Bearer "+Authentication.token}})).json()).items}async function getAnalyticsModules(){if(!Authentication.token)throw new Error("Not authenticated");return(await(await fetch(`${exports.FORMANT_API_URL}/v1/admin/analytics-modules`,{method:"GET",headers:{"Content-Type":"application/json",Authorization:"Bearer "+Authentication.token}})).json()).items}async function getAnalyticsRows(e){if(!Authentication.token)throw new Error("Not authenticated");return await(await fetch(`${exports.FORMANT_API_URL}/v1/queries/analytics/rows`,{method:"POST",body:JSON.stringify(e),headers:{"Content-Type":"application/json",Authorization:"Bearer "+Authentication.token}})).json()}async function queryDevices(e){if(!Authentication.token)throw new Error("Not authenticated");return(await(await fetch(`${exports.FORMANT_API_URL}/v1/admin/devices/query`,{method:"POST",body:JSON.stringify(e),headers:{"Content-Type":"application/json",Authorization:"Bearer "+Authentication.token}})).json()).items.map(r=>new Device(r.id,r.name,r.organizationId,r.tags))}async function getCurrentGroup(){if(!Authentication.token)throw new Error("Not authenticated");let e=new URLSearchParams("");typeof window!="undefined"&&window.location&&(e=new URLSearchParams(window.location.search));const t=e.get("group");if(t===null||t.trim()==="")return;const n=await fetch(`${exports.FORMANT_API_URL}/v1/admin/groups/`+t,{headers:{"Content-Type":"application/json",Authorization:"Bearer "+Authentication.token}}),{tagKey:r,tagValue:o}=await n.json();return await queryDevices({tags:{[r]:[o]},enabled:!0,type:"default"})}async function getDevice(e){if(!Authentication.token)throw new Error("Not authenticated");const n=await(await fetch(`${exports.FORMANT_API_URL}/v1/admin/devices/${e}`,{method:"GET",headers:{"Content-Type":"application/json",Authorization:"Bearer "+Authentication.token}})).json(),r=n.name;return new Device(e,r,n.organizationId,n.tags)}async function getDevices(){if(!Authentication.token)throw new Error("Not authenticated");const t=await(await fetch(`${exports.FORMANT_API_URL}/v1/admin/device-details/query`,{method:"POST",body:JSON.stringify({enabled:!0,type:"default"}),headers:{"Content-Type":"application/json",Authorization:"Bearer "+Authentication.token}})).json();return t.items,t.items.map(n=>new Device(n.id,n.name,defined$1(Authentication.currentOrganization),n.tags))}async function getEvent(e){if(!Authentication.token)throw new Error("Not authenticated");return(await(await fetch(`${exports.FORMANT_API_URL}/v1/admin/events/query/id=${e}`,{method:"GET",headers:{"Content-Type":"application/json",Authorization:"Bearer "+Authentication.token}})).json()).items}async function getFileUrl(e){const n=await(await fetch(`${exports.FORMANT_API_URL}/v1/admin/files/query`,{method:"POST",body:JSON.stringify({fileIds:[e]}),headers:{"Content-Type":"application/json",Authorization:"Bearer "+Authentication.token}})).json();if(n.fileUrls.length===0)throw new Error("File not found");return n.fileUrls[0]}async function getFleet(e){if(!Authentication.token)throw new Error("Not authenticated");return await(await fetch(`${exports.FORMANT_API_URL}/v1/admin/fleets/${e}`,{method:"GET",headers:{"Content-Type":"application/json",Authorization:"Bearer "+Authentication.token}})).json()}async function getFleetDevices(e){if(!Authentication.token)throw new Error("Not authenticated");return(await(await fetch(`${exports.FORMANT_API_URL}/v1/admin/fleets/${e}/devices`,{method:"GET",headers:{"Content-Type":"application/json",Authorization:"Bearer "+Authentication.token}})).json()).items}async function getInterventions(){if(!Authentication.token)throw new Error("Not authenticated");return(await(await fetch(`${exports.FORMANT_API_URL}/v1/admin/intervention-requests`,{method:"GET",headers:{"Content-Type":"application/json",Authorization:"Bearer "+Authentication.token}})).json()).items}async function getLatestTelemetry(...e){const t=e.flat().filter(o=>!!o);return t.length===0?[]:(await(await fetch(`${exports.FORMANT_API_URL}/v1/queries/stream-current-value`,{method:"POST",body:JSON.stringify({deviceIds:t}),headers:{"Content-Type":"application/json",Authorization:"Bearer "+Authentication.token}})).json()).items}async function getOnlineDevices(){if(!Authentication.token)throw new Error("Not authenticated");const n=(await(await fetch(`${exports.FORMANT_API_URL}/v1/queries/online-devices`,{method:"GET",headers:{"Content-Type":"application/json",Authorization:"Bearer "+Authentication.token}})).json()).items;return(await getDevices()).filter(o=>n.includes(o.id))}async function getRealtimeDevices(){if(!Authentication.token)throw new Error("Not authenticated");const n=(await(await fetch(`${exports.FORMANT_API_URL}/v1/signaling/peers`,{method:"GET",headers:{"Content-Type":"application/json",Authorization:"Bearer "+Authentication.token}})).json()).items.map(o=>o.deviceId);return(await getDevices()).filter(o=>n.includes(o.id))}async function getStreams(){if(!Authentication.token)throw new Error("Not authenticated");return(await(await fetch(`${exports.FORMANT_API_URL}/v1/admin/streams`,{method:"GET",headers:{"Content-Type":"application/json",Authorization:"Bearer "+Authentication.token}})).json()).items.filter(n=>n.enabled)}async function getTaskReportRows(e){if(!Authentication.token)throw new Error("Not authenticated");return await(await fetch(`${exports.FORMANT_API_URL}/v1/queries/analytics/task-report-rows`,{method:"POST",body:JSON.stringify(e),headers:{"Content-Type":"application/json",Authorization:"Bearer "+Authentication.token}})).json()}async function getTaskReportTables(){if(!Authentication.token)throw new Error("Not authenticated");return(await(await fetch(`${exports.FORMANT_API_URL}/v1/queries/analytics/task-reports`,{method:"GET",headers:{"Content-Type":"application/json",Authorization:"Bearer "+Authentication.token}})).json()).items}async function listFleets(){if(!Authentication.token)throw new Error("Not authenticated");return(await(await fetch(`${exports.FORMANT_API_URL}/v1/admin/fleets`,{method:"GET",headers:{"Content-Type":"application/json",Authorization:"Bearer "+Authentication.token}})).json()).items}async function patchFleet(e,t){if(!Authentication.token)throw new Error("Not authenticated");return await(await fetch(`${exports.FORMANT_API_URL}/v1/admin/fleets/${e}`,{method:"PATCH",body:JSON.stringify(t),headers:{"Content-Type":"application/json",Authorization:"Bearer "+Authentication.token}})).json()}async function patchStream(e){if(!Authentication.token)throw new Error("Not authenticated");return await(await fetch(`${exports.FORMANT_API_URL}/v1/admin/streams/${e.id}`,{method:"PATCH",body:JSON.stringify(e),headers:{"Content-Type":"application/json",Authorization:"Bearer "+Authentication.token}})).json()}async function patchView(e){if(!Authentication.token)throw new Error("Not authenticated");return await(await fetch(`${exports.FORMANT_API_URL}/v1/admin/views/${e.id}`,{method:"PATCH",body:JSON.stringify(e),headers:{"Content-Type":"application/json",Authorization:"Bearer "+Authentication.token}})).json()}async function queryAnalytics(e){if(!Authentication.token)throw new Error("Not authenticated");return await(await fetch(`${exports.FORMANT_API_URL}/v1/queries/analytics`,{method:"POST",body:JSON.stringify(e),headers:{"Content-Type":"application/json",Authorization:"Bearer "+Authentication.token}})).json()}async function createFleet(e){if(!Authentication.token)throw new Error("Not authenticated");return await(await fetch(`${exports.FORMANT_API_URL}/v1/admin/fleets`,{method:"POST",body:JSON.stringify(e),headers:{"Content-Type":"application/json",Authorization:"Bearer "+Authentication.token}})).json()}async function getAllEventTriggerGroup(){if(!Authentication.token)throw new Error("Not authenticated");return(await(await fetch(`${exports.FORMANT_API_URL}/v1/admin/event-trigger-groups`,{method:"GET",headers:{"Content-Type":"application/json",Authorization:"Bearer "+Authentication.token}})).json()).items}async function getEventTriggerGroup(e){if(!Authentication.token)throw new Error("Not authenticated");return await(await fetch(`${exports.FORMANT_API_URL}/v1/admin/event-trigger-groups/${e}`,{method:"GET",headers:{"Content-Type":"application/json",Authorization:"Bearer "+Authentication.token}})).json()}async function patchEventTriggerGroup(e,t){if(!Authentication.token)throw new Error("Not authenticated");return await(await fetch(`${exports.FORMANT_API_URL}/v1/admin/event-trigger-groups/${e}`,{method:"PATCH",body:JSON.stringify(t),headers:{"Content-Type":"application/json",Authorization:"Bearer "+Authentication.token}})).json()}const et=class{static async setDefaultDevice(t){et.defaultDeviceId=t}static async getCurrentDevice(){if(!Authentication.token)throw new Error("Not authenticated");if(!et.defaultDeviceId)throw new Error("No known default device");const r=(await(await fetch(`${exports.FORMANT_API_URL}/v1/admin/device-details/query`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:"Bearer "+Authentication.token}})).json()).items.find(g=>g.id===et.defaultDeviceId),o=r.name,s=new Device(et.defaultDeviceId,o,defined$1(Authentication.currentOrganization),r.tags);return et.knownContext.push(new WeakRef(s)),s}static async getPeerDevice(t){const n=new PeerDevice(t);return n.id=await n.getDeviceId(),n}static async getDevice(t){const n=await getDevice(t);return et.knownContext.push(new WeakRef(n)),n}};let Fleet=et;he(Fleet,"defaultDeviceId"),he(Fleet,"knownContext",[]),he(Fleet,"createFleet",createFleet),he(Fleet,"listFleets",listFleets),he(Fleet,"getFleet",getFleet),he(Fleet,"patchFleet",patchFleet),he(Fleet,"deleteFleet",deleteFleet),he(Fleet,"addDeviceToFleet",addDeviceToFleet),he(Fleet,"getFleetDevices",getFleetDevices),he(Fleet,"aggregateTelemetry",aggregateTelemetry),he(Fleet,"createShareLink",createShareLink),he(Fleet,"eventsCounter",eventsCounter),he(Fleet,"getAnalyticStreams",getAnalyticStreams),he(Fleet,"getAnalyticsModules",getAnalyticsModules),he(Fleet,"getAnalyticsRows",getAnalyticsRows),he(Fleet,"getAnnotationCount",getAnnotationCount),he(Fleet,"getAnnotationCountByIntervals",getAnnotationCountByIntervals),he(Fleet,"getCurrentGroup",getCurrentGroup),he(Fleet,"getDevices",getDevices),he(Fleet,"getEvent",getEvent),he(Fleet,"getFileUrl",getFileUrl),he(Fleet,"getInterventions",getInterventions),he(Fleet,"getLatestTelemetry",getLatestTelemetry),he(Fleet,"getOnlineDevices",getOnlineDevices),he(Fleet,"getPeers",getPeers),he(Fleet,"getRealtimeDevices",getRealtimeDevices),he(Fleet,"getRealtimeSessions",getRealtimeSessions),he(Fleet,"getStreams",getStreams),he(Fleet,"getTaskReportRows",getTaskReportRows),he(Fleet,"getTaskReportTables",getTaskReportTables),he(Fleet,"getTelemetry",getTelemetry),he(Fleet,"getViews",getViews),he(Fleet,"patchStream",patchStream),he(Fleet,"patchView",patchView),he(Fleet,"queryAnalytics",queryAnalytics),he(Fleet,"queryDevices",queryDevices),he(Fleet,"queryEvents",queryEvents),he(Fleet,"queryTelemetry",queryTelemetry),he(Fleet,"getAllEventTriggerGroup",getAllEventTriggerGroup),he(Fleet,"getEventTriggerGroup",getEventTriggerGroup),he(Fleet,"patchEventTriggergroup",patchEventTriggerGroup);class KeyValue{static async set(t,n,r){try{const o=await fetch(exports.FORMANT_API_URL+"/v1/admin/key-value",{method:"POST",body:JSON.stringify({organizationId:defined$1(Authentication.currentUser).organizationId,key:t,value:n,tags:r}),headers:{"Content-Type":"application/json",Authorization:"Bearer "+Authentication.token}}),s=await o.json();if(o.status!==200)throw new Error(s.message)}catch(o){throw o}}static async get(t){try{const n=await fetch(exports.FORMANT_API_URL+`/v1/admin/key-value/${t}`,{method:"GET",headers:{"Content-Type":"application/json",Authorization:"Bearer "+Authentication.token}}),r=await n.json();if(n.status!==200)throw new Error(r.message);return r.value}catch(n){throw n}}static async list(){try{const t=await fetch(exports.FORMANT_API_URL+"/v1/admin/key-value",{method:"GET",headers:{"Content-Type":"application/json",Authorization:"Bearer "+Authentication.token}}),n=await t.json();if(t.status!==200)throw new Error(n.message);return n.items}catch(t){throw t}}static async delete(t){try{if(!(await fetch(exports.FORMANT_API_URL+`/v1/admin/key-value/${t}`,{method:"DELETE",headers:{"Content-Type":"application/json",Authorization:"Bearer "+Authentication.token}})).ok)throw new Error("Unable to handle request");return}catch(n){throw n}}static async query(t){try{const n=await fetch(exports.FORMANT_API_URL+"/v1/admin/key-value/query",{method:"POST",body:JSON.stringify({keys:t}),headers:{"Content-Type":"application/json",Authorization:"Bearer "+Authentication.token}});if(!n.ok)throw new Error("Unable to handle request");return(await n.json()).items}catch(n){throw n}}}class Role{static async listRoles(){if(!Authentication.token)throw new Error("Not authenticated");return(await(await fetch(`${exports.FORMANT_API_URL}/v1/admin/roles`,{method:"GET",headers:{"Content-Type":"application/json",Authorization:"Bearer "+Authentication.token}})).json()).items}static async createRole(t){if(!Authentication.token)throw new Error("Not authenticated");return await(await fetch(`${exports.FORMANT_API_URL}/v1/admin/roles`,{method:"POST",body:JSON.stringify(t),headers:{"Content-Type":"application/json",Authorization:"Bearer "+Authentication.token}})).json()}static async getRole(t){if(!Authentication.token)throw new Error("Not authenticated");return await(await fetch(`${exports.FORMANT_API_URL}/v1/admin/roles/${t}`,{method:"GET",headers:{"Content-Type":"application/json",Authorization:"Bearer "+Authentication.token}})).json()}static async patchRole(t,n){if(!Authentication.token)throw new Error("Not authenticated");return await(await fetch(`${exports.FORMANT_API_URL}/v1/admin/roles/${t}`,{method:"PATCH",body:JSON.stringify(n),headers:{"Content-Type":"application/json",Authorization:"Bearer "+Authentication.token}})).json()}static async deleteRole(t){if(!Authentication.token)throw new Error("Not authenticated");await fetch(`${exports.FORMANT_API_URL}/v1/admin/roles/${t}`,{method:"DELETE",headers:{"Content-Type":"application/json",Authorization:"Bearer "+Authentication.token}})}}class User{static async listUsers(){if(!Authentication.token)throw new Error("Not authenticated");return(await(await fetch(`${exports.FORMANT_API_URL}/v1/admin/users`,{method:"GET",headers:{"Content-Type":"application/json",Authorization:"Bearer "+Authentication.token}})).json()).items}static async createUser(t){if(!Authentication.token)throw new Error("Not authenticated");return await(await fetch(`${exports.FORMANT_API_URL}/v1/admin/users`,{method:"POST",body:JSON.stringify(t),headers:{"Content-Type":"application/json",Authorization:"Bearer "+Authentication.token}})).json()}static async getUser(t){if(!Authentication.token)throw new Error("Not authenticated");return await(await fetch(`${exports.FORMANT_API_URL}/v1/admin/users/${t}`,{method:"GET",headers:{"Content-Type":"application/json",Authorization:"Bearer "+Authentication.token}})).json()}static async patchUser(t,n){if(!Authentication.token)throw new Error("Not authenticated");return await(await fetch(`${exports.FORMANT_API_URL}/v1/admin/users/${t}`,{method:"PATCH",body:JSON.stringify(n),headers:{"Content-Type":"application/json",Authorization:"Bearer "+Authentication.token}})).json()}static async deleteUser(t){if(!Authentication.token)throw new Error("Not authenticated");await fetch(`${exports.FORMANT_API_URL}/v1/admin/users/${t}`,{method:"PATCH",body:JSON.stringify({enabled:!1,roleId:null,teamId:null}),headers:{"Content-Type":"application/json",Authorization:"Bearer "+Authentication.token}})}}async function request(e,t){if(!Authentication.token)throw new Error("Not authenticated");const n=await fetch(`${exports.FORMANT_API_URL}/v1${e}`,{...t,headers:{"Content-Type":"application/json",Authorization:`Bearer ${Authentication.token}`,...t==null?void 0:t.headers}});if(!n.ok)throw new Error(`Error: ${n.statusText}`);return n.status===204||n.headers.get("content-length")==="0"?null:await n.json()}async function fetchTeleopViews(){return(await request("/admin/teleop-views")).items}async function getTeleopView(e){return await request(`/admin/teleop-views/${e}`)}async function createTeleopView(e){return await request("/admin/teleop-views",{method:"POST",body:JSON.stringify(e)})}async function updateTeleopView(e,t){return await request(`/admin/teleop-views/${e}`,{method:"PATCH",body:JSON.stringify(t)})}async function deleteTeleopView(e){await request(`/admin/teleop-views/${e}`,{method:"DELETE"})}class Views{constructor(){}}he(Views,"createTeleopView",createTeleopView),he(Views,"updateTeleopView",updateTeleopView),he(Views,"deleteTeleopView",deleteTeleopView),he(Views,"getTeleopView",getTeleopView),he(Views,"fetchTeleopViews",fetchTeleopViews);const viewer="viewer",operator="operator",administrator="administrator",accessLevels=["viewer","operator","administrator"],aggregateLevels=["year","month","week","day","hour","minute"],annotationTypes=["tag","sheet","user"],eventTypes=["triggered-event","datapoint-event","device-online","device-offline","intervention-request","teleop-session-record","port-forwarding-session-record","command-request","command-response","command-delivery","intervention-response","custom","comment","system","annotation","task-summary","stateful"],healthStatuses=["unknown","operational","offline","error"],interventionTypes=["selection","labeling","teleop"],severities=["info","warning","error","critical"],videoMimeTypes=["video/mp4"],timeout=e=>new Promise(t=>setTimeout(t,e*1e3));try{const e=typeof window!="undefined"&&window.location?new URLSearchParams(window.location.search):new URLSearchParams(""),t=e.get("device");t&&Fleet.setDefaultDevice(t);const n=e.get("auth");n&&Authentication.loginWithToken(n),e.get("module")&&Authentication.listenForRefresh(),typeof window!="undefined"&&App.listenForConnectionEvents()}catch(e){}var __defProp=Object.defineProperty,__defProps=Object.defineProperties,__getOwnPropDescs=Object.getOwnPropertyDescriptors,__getOwnPropSymbols=Object.getOwnPropertySymbols,__hasOwnProp=Object.prototype.hasOwnProperty,__propIsEnum=Object.prototype.propertyIsEnumerable,__defNormalProp=(e,t,n)=>t in e?__defProp(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n,__spreadValues=(e,t)=>{for(var n in t||(t={}))__hasOwnProp.call(t,n)&&__defNormalProp(e,n,t[n]);if(__getOwnPropSymbols)for(var n of __getOwnPropSymbols(t))__propIsEnum.call(t,n)&&__defNormalProp(e,n,t[n]);return e},__spreadProps=(e,t)=>__defProps(e,__getOwnPropDescs(t)),__publicField=(e,t,n)=>(__defNormalProp(e,typeof t!="symbol"?t+"":t,n),n);const millisecond$1=1,second$1=1e3,minute$1=60*second$1,hour$1=60*minute$1,day$1=24*hour$1,week$1=7*day$1,month$1=30*day$1,year$1=365*day$1,duration$1={millisecond:millisecond$1,second:second$1,minute:minute$1,hour:hour$1,day:day$1,week:week$1,month:month$1,year:year$1};class H264Decoder{constructor(t,n,r){__publicField(this,"worker"),__publicField(this,"onReceive"),__publicField(this,"onError"),__publicField(this,"onReceiveMessage",s=>{const{data:g}=s;if(g.error){const l=new Error(`${g.error}`);l.cause=g.error,console.warn("H264 worker failure",{error:l}),this.onError(g.index);return}this.onReceive(g)});var o;this.worker=t,(o=this.worker)==null||o.addEventListener("message",this.onReceiveMessage),this.onReceive=n,this.onError=r}post(t,n,r,o){var s;(s=this.worker)==null||s.postMessage({timestamp:t,encodedFrame:n,flags:r,index:o})}release(){var t,n;(t=this.worker)==null||t.removeEventListener("message",this.onReceiveMessage),(n=this.worker)==null||n.terminate(),this.worker=void 0}}class YUVCanvas{constructor(t){__publicField(this,"gl"),__publicField(this,"program"),__publicField(this,"texturePosBuffer"),__publicField(this,"textureRef"),__publicField(this,"height",0),__publicField(this,"width",0),this.gl=t,this.program=this.initProgram();const{texturePosBuffer:n}=this.initBuffers();this.texturePosBuffer=n;const{textureRef:r}=this.initTextures();this.textureRef=r}draw(t){const{gl:n,height:r,width:o,texturePosBuffer:s,textureRef:g}=this;n.viewport(0,0,o,r);const l=new Float32Array([1,0,0,0,1,1,0,1]);return n.bindBuffer(n.ARRAY_BUFFER,s),n.bufferData(n.ARRAY_BUFFER,l,n.DYNAMIC_DRAW),n.activeTexture(n.TEXTURE0),n.bindTexture(n.TEXTURE_2D,g),n.texImage2D(n.TEXTURE_2D,0,n.LUMINANCE,o,r+r/2,0,n.LUMINANCE,n.UNSIGNED_BYTE,t),n.drawArrays(n.TRIANGLE_STRIP,0,4),n.getError()}initProgram(){const{gl:t}=this,n=`
|
|
64
64
|
attribute vec4 vertexPos;
|
|
65
65
|
attribute vec4 texturePos;
|