@formant/data-sdk 0.0.142 → 0.0.144

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.
@@ -20272,6 +20272,14 @@ class App {
20272
20272
  });
20273
20273
  });
20274
20274
  }
20275
+ static addOverviewDeviceListener(t) {
20276
+ this.sendAppMessage({ type: "request_devices" });
20277
+ const n = (r) => {
20278
+ const i = r.data;
20279
+ i.type === "overview_devices" && t(i.data);
20280
+ };
20281
+ return window.addEventListener("message", n), () => window.removeEventListener("message", n);
20282
+ }
20275
20283
  static addStreamListener(t, n, r) {
20276
20284
  const i = (s) => {
20277
20285
  const l = s.data;
@@ -20306,12 +20314,6 @@ class App {
20306
20314
  });
20307
20315
  });
20308
20316
  }
20309
- static requestOverviewDevices(t) {
20310
- this.sendAppMessage({ type: "request_devices" }), window.addEventListener("message", (n) => {
20311
- const r = n.data;
20312
- t(r);
20313
- });
20314
- }
20315
20317
  static async prompt(t, n) {
20316
20318
  return new Promise((r) => {
20317
20319
  const i = Math.random().toString();
@@ -21110,12 +21112,15 @@ class Device extends EventEmitter {
21110
21112
  }
21111
21113
  }
21112
21114
  initConnectionMonitoring() {
21113
- this.connectionMonitorInterval = setInterval(() => {
21114
- (!this.rtcClient || !this.remoteDevicePeerId || this.rtcClient.getConnectionStatus(this.remoteDevicePeerId) !== "connected") && (this.emit("disconnect"), this.stopRealtimeConnection().catch((n) => {
21115
+ this.connectionMonitorInterval = setInterval(async () => {
21116
+ this.isV2Signaling(this.rtcClient) && (!this.rtcClient || !this.remoteDevicePeerId || await this.rtcClient.getConnectionStatsInfo(this.remoteDevicePeerId) === void 0) && (this.emit("disconnect"), this.stopRealtimeConnection().catch((n) => {
21115
21117
  console.error(n);
21116
21118
  }));
21117
21119
  }, 1e3);
21118
21120
  }
21121
+ isV2Signaling(n) {
21122
+ return n.getConnectionStatsInfo !== void 0;
21123
+ }
21119
21124
  stopConnectionMonitoring() {
21120
21125
  clearInterval(this.connectionMonitorInterval), this.connectionMonitorInterval = void 0;
21121
21126
  }
@@ -21307,8 +21312,8 @@ class Device extends EventEmitter {
21307
21312
  }));
21308
21313
  }
21309
21314
  async sendCommand(n, r, i, s) {
21310
- var f;
21311
- const o = (await this.getAvailableCommands()).find((E) => E.name === n);
21315
+ var E;
21316
+ const o = (await this.getAvailableCommands()).find((w) => w.name === n);
21312
21317
  if (!o)
21313
21318
  throw new Error(`Could not find command with name "${n}"`);
21314
21319
  let c = "";
@@ -21321,7 +21326,7 @@ class Device extends EventEmitter {
21321
21326
  ...s
21322
21327
  }
21323
21328
  };
21324
- await fetch(`${FORMANT_API_URL}/v1/admin/commands`, {
21329
+ return await fetch(`${FORMANT_API_URL}/v1/admin/commands`, {
21325
21330
  method: "POST",
21326
21331
  body: JSON.stringify({
21327
21332
  commandTemplateId: o.id,
@@ -21329,7 +21334,7 @@ class Device extends EventEmitter {
21329
21334
  deviceId: this.id,
21330
21335
  command: o.command,
21331
21336
  parameter: u,
21332
- userId: (f = Authentication.currentUser) == null ? void 0 : f.id
21337
+ userId: (E = Authentication.currentUser) == null ? void 0 : E.id
21333
21338
  }),
21334
21339
  headers: {
21335
21340
  "Content-Type": "application/json",
@@ -21337,6 +21342,18 @@ class Device extends EventEmitter {
21337
21342
  }
21338
21343
  });
21339
21344
  }
21345
+ async getCommand(n) {
21346
+ return await fetch(
21347
+ `${FORMANT_API_URL}/v1/admin/commands/${n}`,
21348
+ {
21349
+ method: "GET",
21350
+ headers: {
21351
+ "Content-Type": "application/json",
21352
+ Authorization: "Bearer " + Authentication.token
21353
+ }
21354
+ }
21355
+ );
21356
+ }
21340
21357
  async createCustomDataChannel(n, r) {
21341
21358
  if (rtcClientVersion === "1")
21342
21359
  throw new Error(
@@ -46,7 +46,7 @@ In order to be iterable, non-array objects must have a [Symbol.iterator]() metho
46
46
  `))},l.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(l){return typeof l}:function(l){return l&&typeof Symbol=="function"&&l.constructor===Symbol&&l!==Symbol.prototype?"symbol":typeof l})(s)}function i(s,l){for(var o=0;o<l.length;o++){var c=l[o];c.enumerable=c.enumerable||!1,c.configurable=!0,"value"in c&&(c.writable=!0),Object.defineProperty(s,c.key,c)}}e.exports=function(){function s(c){if(function(u,f){if(!(u instanceof f))throw new TypeError("Cannot call a class as a function")}(this,s),!c)throw new Error("Logger is required for profiling.");this.logger=c,this.start=Date.now()}var l,o;return l=s,(o=[{key:"done",value:function(){for(var c=arguments.length,u=new Array(c),f=0;f<c;f++)u[f]=arguments[f];typeof u[u.length-1]=="function"&&(console.warn("Callback function no longer supported as of winston@3.0.0"),u.pop());var E=r(u[u.length-1])==="object"?u.pop():{};return E.level=E.level||"info",E.durationMs=Date.now()-this.start,this.logger.write(E)}}])&&i(l.prototype,o),s}()},function(e,t,n){(function(r){const i=n(209),{MESSAGE:s}=n(3),l=n(35);function o(c,u){return u instanceof r?u.toString("base64"):typeof u=="bigint"?u.toString():u}e.exports=i((c,u={})=>(c[s]=(u.stable?l.stableStringify:l)(c,u.replacer||o,u.space),c))}).call(this,n(5).Buffer)},function(e,t,n){class r extends Error{constructor(s){super(`Format functions must be synchronous taking a two arguments: (info, opts)
47
47
  Found: ${s.toString().split(`
48
48
  `)[0]}
49
- `),Error.captureStackTrace(this,r)}}e.exports=i=>{if(i.length>2)throw new r(i);function s(o={}){this.options=o}function l(o){return new s(o)}return s.prototype.transform=i,l.Format=s,l}},function(e,t,n){function r(l,o){if(!(l instanceof o))throw new TypeError("Cannot call a class as a function")}function i(l,o){for(var c=0;c<o.length;c++){var u=o[c];u.enumerable=u.enumerable||!1,u.configurable=!0,"value"in u&&(u.writable=!0),Object.defineProperty(l,u.key,u)}}var s=n(88);e.exports=function(){function l(){var u=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};r(this,l),this.loggers=new Map,this.options=u}var o,c;return o=l,(c=[{key:"add",value:function(u,f){var E=this;if(!this.loggers.has(u)){var w=(f=Object.assign({},f||this.options)).transports||this.options.transports;f.transports=w?w.slice():[];var h=s(f);h.on("close",function(){return E._delete(u)}),this.loggers.set(u,h)}return this.loggers.get(u)}},{key:"get",value:function(u,f){return this.add(u,f)}},{key:"has",value:function(u){return!!this.loggers.has(u)}},{key:"close",value:function(u){var f=this;if(u)return this._removeLogger(u);this.loggers.forEach(function(E,w){return f._removeLogger(w)})}},{key:"_removeLogger",value:function(u){this.loggers.has(u)&&(this.loggers.get(u).close(),this._delete(u))}},{key:"_delete",value:function(u){this.loggers.delete(u)}}])&&i(o.prototype,c),l}()},function(e,t,n){(function(r){const i=n(52),s=/^([A-Za-z0-9+/]{4})*([A-Za-z0-9+/]{4}|[A-Za-z0-9+/]{3}=|[A-Za-z0-9+/]{2}==)$/;e.exports=function(l,o,c,u){let f,E,w=!1,h=!1;const g=n(94);function b(F){u(o,F)}function R(F,M){let A=`"${o}" ${M}`;throw F&&(A=`${A}`),E&&(A=`${A}. An example of a valid value would be: ${E}`),new i(A)}const j={convertFromBase64:function(){return b("marking for base64 conversion"),w=!0,j},default:function(F){if(typeof F=="number")f=F.toString();else if(Array.isArray(F)||typeof F=="object"&&F!==null)f=JSON.stringify(F);else{if(typeof F!="string")throw new i("values passed to default() must be of Number, String, Array, or Object type");f=F}return b(`setting default value to "${f}"`),j},required:function(F){return F===void 0?(b("marked as required"),h=!0):(b(`setting required flag to ${F}`),h=F),j},example:function(F){return E=F,j}};return Object.entries({...g,...c}).forEach(([F,M])=>{j[F]=function(A){return function(){let d=l[o];if(b(`will be read from the environment using "${A.name}" accessor`),d===void 0)if(f===void 0&&h)b("was not found in the environment, but is required to be set"),R(void 0,"is a required variable, but it was not set");else{if(f===void 0)return void b("was not found in the environment, but is not required. returning undefined");b(`was not found in the environment, parsing default value "${f}" instead`),d=f}h&&(b("verifying variable value is not an empty string"),d.trim().length===0&&R(void 0,"is a required variable, but its value was empty")),w&&(b("verifying variable is a valid base64 string"),d.match(s)||R(d,"should be a valid base64 string if using convertFromBase64"),b("converting from base64 to utf8 string"),d=r.from(d,"base64").toString());const C=[d].concat(Array.prototype.slice.call(arguments));try{b(`passing value "${d}" to "${A.name}" accessor`);const $=A.apply(A,C);return b(`parsed successfully, returning ${$}`),$}catch($){R(d,$.message)}}}(M)}),j}}).call(this,n(5).Buffer)},function(e,t,n){const r=n(33);e.exports=function(i,s){return s=s||",",i.length?r(i).split(s).filter(Boolean):[]}},function(e,t,n){e.exports=function(r){const i=r.toLowerCase();if(i!=="false"&&i!=="true")throw new Error('should be either "true", "false", "TRUE", or "FALSE"');return i!=="false"}},function(e,t,n){e.exports=function(r){const i=r.toLowerCase();if(["false","0","true","1"].indexOf(i)===-1)throw new Error('should be either "true", "false", "TRUE", "FALSE", 1, or 0');return!(i==="0"||i==="false")}},function(e,t,n){const r=n(95);e.exports=function(i){var s=r(i);if(s>65535)throw new Error("cannot assign a port number greater than 65535");return s}},function(e,t,n){const r=n(33);e.exports=function(i,s){const l=r(i);if(s.indexOf(l)<0)throw new Error(`should be one of [${s.join(", ")}]`);return l}},function(e,t,n){const r=n(54);e.exports=function(i){const s=r(i);if(s>0)throw new Error("should be a negative float");return s}},function(e,t,n){const r=n(54);e.exports=function(i){const s=r(i);if(s<0)throw new Error("should be a positive float");return s}},function(e,t,n){const r=n(53);e.exports=function(i){const s=r(i);if(s>0)throw new Error("should be a negative integer");return s}},function(e,t,n){const r=n(55);e.exports=function(i){var s=r(i);if(!Array.isArray(s))throw new Error("should be a parseable JSON Array");return s}},function(e,t,n){const r=n(55);e.exports=function(i){var s=r(i);if(Array.isArray(s))throw new Error("should be a parseable JSON Object");return s}},function(e,t,n){e.exports=function(r,i){try{RegExp(void 0,i)}catch{throw new Error("invalid regexp flags")}try{return new RegExp(r,i)}catch{throw new Error("should be a valid regexp")}}},function(e,t,n){const r=n(96);e.exports=function(i){return r(i).toString()}},function(e,t,n){const r=n(33),i=/^(?:[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 l=r(s);if(!i.test(l))throw new Error("should be a valid email address");return l}},function(e,t,n){e.exports=function(r,i){return function(s,l){i&&i.match(/prod|production/)||r(`env-var (${s}): ${l}`)}}},function(e,t,n){(function(r){(function(){var i,s,l,o,c,u;typeof performance<"u"&&performance!==null&&performance.now?e.exports=function(){return performance.now()}:r!=null&&r.hrtime?(e.exports=function(){return(i()-c)/1e6},s=r.hrtime,o=(i=function(){var f;return 1e9*(f=s())[0]+f[1]})(),u=1e9*r.uptime(),c=o-u):Date.now?(e.exports=function(){return Date.now()-l},l=Date.now()):(e.exports=function(){return new Date().getTime()-l},l=new Date().getTime())}).call(this)}).call(this,n(2))},function(e,t,n){(function(r){(function(i){function s(o){if((o=o===void 0?"utf-8":o)!=="utf-8")throw new RangeError("Failed to construct 'TextEncoder': The encoding label provided ('"+o+"') is invalid.")}function l(o,c){if(c=c===void 0?{fatal:!1}:c,(o=o===void 0?"utf-8":o)!=="utf-8")throw new RangeError("Failed to construct 'TextDecoder': The encoding label provided ('"+o+"') is invalid.");if(c.fatal)throw Error("Failed to construct 'TextDecoder': the 'fatal' option is unsupported.")}if(i.TextEncoder&&i.TextDecoder)return!1;Object.defineProperty(s.prototype,"encoding",{value:"utf-8"}),s.prototype.encode=function(o,c){if((c=c===void 0?{stream:!1}:c).stream)throw Error("Failed to encode: the 'stream' option is unsupported.");c=0;for(var u=o.length,f=0,E=Math.max(32,u+(u>>1)+7),w=new Uint8Array(E>>3<<3);c<u;){var h=o.charCodeAt(c++);if(55296<=h&&56319>=h){if(c<u){var g=o.charCodeAt(c);(64512&g)==56320&&(++c,h=((1023&h)<<10)+(1023&g)+65536)}if(55296<=h&&56319>=h)continue}if(f+4>w.length&&(E+=8,E=(E*=1+c/o.length*2)>>3<<3,(g=new Uint8Array(E)).set(w),w=g),(4294967168&h)==0)w[f++]=h;else{if(!(4294965248&h))w[f++]=h>>6&31|192;else if(!(4294901760&h))w[f++]=h>>12&15|224,w[f++]=h>>6&63|128;else{if(4292870144&h)continue;w[f++]=h>>18&7|240,w[f++]=h>>12&63|128,w[f++]=h>>6&63|128}w[f++]=63&h|128}}return w.slice(0,f)},Object.defineProperty(l.prototype,"encoding",{value:"utf-8"}),Object.defineProperty(l.prototype,"fatal",{value:!1}),Object.defineProperty(l.prototype,"ignoreBOM",{value:!1}),l.prototype.decode=function(o,c){if((c=c===void 0?{stream:!1}:c).stream)throw Error("Failed to decode: the 'stream' option is unsupported.");c=0;for(var u=(o=new Uint8Array(o)).length,f=[];c<u;){var E=o[c++];if(E===0)break;if(!(128&E))f.push(E);else if((224&E)==192){var w=63&o[c++];f.push((31&E)<<6|w)}else if((240&E)==224){w=63&o[c++];var h=63&o[c++];f.push((31&E)<<12|w<<6|h)}else(248&E)==240&&(65535<(E=(7&E)<<18|(w=63&o[c++])<<12|(h=63&o[c++])<<6|63&o[c++])&&(E-=65536,f.push(E>>>10&1023|55296),E=56320|1023&E),f.push(E))}return String.fromCharCode.apply(null,f)},i.TextEncoder=s,i.TextDecoder=l})(typeof window<"u"?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 o}),n.d(t,"Credentials",function(){return L}),n.d(t,"IRtcStream",function(){}),n.d(t,"SignalingPromiseClient",function(){return W.SignalingPromiseClient}),n.d(t,"IRtcClientConfigurationV1",function(){}),n.d(t,"IRtcClientConfiguration",function(){}),n.d(t,"IRtcConnectionStatsInfo",function(){}),n.d(t,"IRtcSendConfiguration",function(){}),n.d(t,"IRtcSessionMetricsMessageCounts",function(){}),n.d(t,"IRtcStreamMessage",function(){}),n.d(t,"IRtcStreamPayload",function(){}),n.d(t,"IStreamControl",function(){}),n.d(t,"RtcClient",function(){return Nt}),n.d(t,"RtcClientV1",function(){return Rt}),n.d(t,"createRtcStreamMessage",function(){return De});var r=n(28),i=function(pe,D,H,X){return new(H||(H=Promise))(function(ie,oe){function de(ce){try{be(X.next(ce))}catch(le){oe(le)}}function ye(ce){try{be(X.throw(ce))}catch(le){oe(le)}}function be(ce){var le;ce.done?ie(ce.value):(le=ce.value,le instanceof H?le:new H(function(Re){Re(le)})).then(de,ye)}be((X=X.apply(pe,D||[])).next())})};class s extends r.a{adminSignup(D,H){return i(this,void 0,void 0,function*(){return yield this.fetch("auth/admin-signup",{token:H,method:"POST",body:JSON.stringify(D)})})}login(D){return i(this,void 0,void 0,function*(){return yield this.fetch("auth/login",{method:"POST",body:JSON.stringify(D),allowUnsafeRetries:!0})})}loginWithGoogleToken(D){return i(this,void 0,void 0,function*(){return yield this.fetch("auth/login-google",{method:"POST",body:JSON.stringify(D),allowUnsafeRetries:!0})})}refresh(D,H){return i(this,void 0,void 0,function*(){return yield this.fetch("auth/refresh",{method:"POST",body:JSON.stringify({refreshToken:D,tokenExpirationSeconds:H}),allowUnsafeRetries:!0})})}respondToNewPasswordRequiredChallenge(D){return i(this,void 0,void 0,function*(){return yield this.fetch("auth/respond-to-new-password-required-challenge",{method:"POST",body:JSON.stringify(D)})})}forgotPassword(D){return i(this,void 0,void 0,function*(){return yield this.fetch("auth/forgot-password",{method:"POST",body:JSON.stringify({email:D})})})}confirmForgotPassword(D){return i(this,void 0,void 0,function*(){return yield this.fetch("auth/confirm-forgot-password",{method:"POST",body:JSON.stringify(D)})})}resendInvitation(D){return i(this,void 0,void 0,function*(){return yield this.fetch("auth/resend-invitation",{method:"POST",body:JSON.stringify({email:D})})})}changePassword({token:D,refreshToken:H,currentPassword:X,newPassword:ie}){return i(this,void 0,void 0,function*(){return yield this.fetch("auth/change-password",{token:D,method:"POST",body:JSON.stringify({refreshToken:H,currentPassword:X,newPassword:ie})})})}getDeviceCredentials(D){return i(this,void 0,void 0,function*(){return yield this.fetch("auth/device-credentials",{token:D,method:"POST",allowUnsafeRetries:!0})})}impersonate(D,H){return i(this,void 0,void 0,function*(){return yield this.fetch("auth/impersonate",{token:D,method:"POST",allowUnsafeRetries:!0,body:JSON.stringify({userId:H})})})}createServiceAccount(D,H,X,ie){return i(this,void 0,void 0,function*(){return yield this.fetch("auth/service-account",{token:D,method:"POST",allowUnsafeRetries:!0,body:JSON.stringify({name:H,roleId:X,tags:ie})})})}getFeatures(D){return i(this,void 0,void 0,function*(){return(yield this.fetch("auth/features",{token:D})).features})}}var l=function(pe,D,H,X){return new(H||(H=Promise))(function(ie,oe){function de(ce){try{be(X.next(ce))}catch(le){oe(le)}}function ye(ce){try{be(X.throw(ce))}catch(le){oe(le)}}function be(ce){var le;ce.done?ie(ce.value):(le=ce.value,le instanceof H?le:new H(function(Re){Re(le)})).then(de,ye)}be((X=X.apply(pe,D||[])).next())})};class o extends r.a{createPeer(D,H){return l(this,void 0,void 0,function*(){return yield this.fetch("peers",{token:D,method:"POST",body:JSON.stringify(H)})})}getPeers(D){return l(this,void 0,void 0,function*(){return(yield this.fetch("peers",{token:D})).items})}refreshPeer(D,H){return l(this,void 0,void 0,function*(){yield this.fetch(`peers/${H}/refresh`,{token:D,method:"POST",allowUnsafeRetries:!0})})}createSession(D,H){return l(this,void 0,void 0,function*(){return yield this.fetch("sessions",{token:D,method:"POST",body:JSON.stringify(H)})})}refreshSession(D,H){return l(this,void 0,void 0,function*(){yield this.fetch(`sessions/${H}/refresh`,{token:D,method:"POST",allowUnsafeRetries:!0})})}deleteSession(D,H){return l(this,void 0,void 0,function*(){yield this.fetch(`sessions/${H}`,{token:D,method:"DELETE",allowUnsafeRetries:!0})})}getSessions(D){return l(this,void 0,void 0,function*(){return(yield this.fetch("sessions",{token:D})).items})}getIceServers(D){return l(this,void 0,void 0,function*(){return(yield this.fetch("ice-servers",{token:D})).items})}addSignals(D,H,X){return l(this,void 0,void 0,function*(){yield this.fetch(`sessions/${H}/add-signals`,{token:D,method:"POST",body:JSON.stringify(X)})})}takeSignals(D,H){return l(this,void 0,void 0,function*(){return(yield this.fetch(`sessions/${H}/take-signals`,{token:D,method:"POST"})).items})}}var c=n(1),u=n(8),f=n(14),E=n.n(f),w=n(104),h=n.n(w),g=n(0),b=function(pe,D,H,X){return new(H||(H=Promise))(function(ie,oe){function de(ce){try{be(X.next(ce))}catch(le){oe(le)}}function ye(ce){try{be(X.throw(ce))}catch(le){oe(le)}}function be(ce){var le;ce.done?ie(ce.value):(le=ce.value,le instanceof H?le:new H(function(Re){Re(le)})).then(de,ye)}be((X=X.apply(pe,D||[])).next())})};class R{constructor(D){this.name="LogReporter",this.type="simple",this.message=D}send(D){return b(this,void 0,void 0,function*(){var H,X;g.a.info(this.message,(H=D.reduce((ie,oe)=>Object.assign(Object.assign({},ie),{[oe.name]:oe.stat}),{}),X=ie=>{const{sum:oe,count:de}=ie,ye=oe/de;return Object.assign(Object.assign({},ie),{average:ye})},Object.keys(H).reduce((ie,oe)=>Object.assign(Object.assign({},ie),{[oe]:X(H[oe])}),{})))})}}var j=n(4),F=n(39);function M(pe){return!!pe.match(/^[a-zA-Z0-9-_.,:?'"()@\/\\#$+ ]{1,255}$/)}var A=function(pe,D,H,X){return new(H||(H=Promise))(function(ie,oe){function de(ce){try{be(X.next(ce))}catch(le){oe(le)}}function ye(ce){try{be(X.throw(ce))}catch(le){oe(le)}}function be(ce){var le;ce.done?ie(ce.value):(le=ce.value,le instanceof H?le:new H(function(Re){Re(le)})).then(de,ye)}be((X=X.apply(pe,D||[])).next())})};function d({func:pe,delay:D,immediate:H=!1}){let X=!1,ie=setTimeout(function de(){return A(this,void 0,void 0,function*(){if(X)return;const ye=new Date().getTime();try{oe=pe(),yield oe}finally{if(!X){const be=new Date().getTime();ie=setTimeout(de,Math.max(D-(be-ye),0))}}})},H?0:D),oe=Promise.resolve();return{stop(){return A(this,void 0,void 0,function*(){X=!0,clearTimeout(ie),yield oe})}}}var C=function(pe,D,H,X){return new(H||(H=Promise))(function(ie,oe){function de(ce){try{be(X.next(ce))}catch(le){oe(le)}}function ye(ce){try{be(X.throw(ce))}catch(le){oe(le)}}function be(ce){var le;ce.done?ie(ce.value):(le=ce.value,le instanceof H?le:new H(function(Re){Re(le)})).then(de,ye)}be((X=X.apply(pe,D||[])).next())})};const $=n(226),q=!!j.c,y=new class{constructor(pe){this.samplePeriodSeconds=60,this.buffer={},this.reporters=[],this.flushInterval=d({func:()=>this.flushStats(),delay:this.samplePeriodSeconds*c.a.second}),this.tags=this.filterTags((pe==null?void 0:pe.tags)||{app:j.a,version:j.j,namespace:j.i,instanceId:F.a})}shutdown(){return C(this,void 0,void 0,function*(){yield this.flushInterval.stop(),yield this.flushStats(),yield Object(u.a)(2*c.a.second)})}aggregate(pe,D,H){this.addToBuffer(this.buffer,this.encodeKey({metric:pe,tags:this.filterTags(H||{})}),typeof D=="number"?{min:D,max:D,sum:D,count:1}:D)}increment(pe,D){this.aggregate(pe,1,D)}timer(pe,D,H){return C(this,void 0,void 0,function*(){const X=$(),ie=yield D(),oe=$();return this.aggregate(pe,oe-X,H),ie})}registerStatsReporter(pe){this.reporters.push(pe)}setTag(pe,D){const H=this.filterTags({[pe]:D});this.tags=Object.assign(Object.assign({},this.tags),H)}addToBuffer(pe,D,H){if(pe[D]){const{min:X,max:ie,sum:oe,count:de}=pe[D];pe[D]={min:Math.min(X,H.min),max:Math.max(ie,H.max),sum:oe+H.sum,count:de+H.count}}else pe[D]=H}write(pe){return C(this,void 0,void 0,function*(){yield Promise.all(this.reporters.map(D=>C(this,void 0,void 0,function*(){let H;const X={};switch(D.type){case"simple":for(const[oe,de]of Object.entries(pe)){const{metric:ye}=this.decodeKey(oe);this.addToBuffer(X,this.encodeKey({metric:ye}),de)}H=X;break;case"tagged":H=pe;break;default:(function(oe){throw new Error(`Unreachable type encountered (${oe})`)})(D.type)}const ie=Object.entries(H);if(ie.length>0)return D.send(ie.map(([oe,de])=>{const{metric:ye,tags:be}=this.decodeKey(oe);return{name:ye,tags:Object.assign(Object.assign({},be),this.tags),stat:de}}),this.samplePeriodSeconds).catch(oe=>{g.a.debug(`Failed to write stats to ${D.name}`,{error:oe})})})))})}flushStats(){return C(this,void 0,void 0,function*(){yield this.write(this.buffer),this.buffer={}})}encodeKey(pe){return E()(Object.assign(Object.assign({},pe),Object.keys(pe.tags||{}).length>0?{tags:pe.tags}:{}))}decodeKey(pe){return JSON.parse(pe)}filterTags(pe){return Object.entries(pe||{}).reduce((D,[H,X])=>(M(H)&&M(X)&&(D[H]=X),D),{})}};q||["local","on-prem"].includes(j.i)||y.registerStatsReporter(new R("stats"));var m=function(pe,D,H,X){return new(H||(H=Promise))(function(ie,oe){function de(ce){try{be(X.next(ce))}catch(le){oe(le)}}function ye(ce){try{be(X.throw(ce))}catch(le){oe(le)}}function be(ce){var le;ce.done?ie(ce.value):(le=ce.value,le instanceof H?le:new H(function(Re){Re(le)})).then(de,ye)}be((X=X.apply(pe,D||[])).next())})};class I extends class{constructor(D){this.options=D,this.cache=new h.a(Object.assign(Object.assign(Object.assign({},D.dispose||D.disposeAfter?{ttlAutopurge:!0}:{}),D),{dispose:(...H)=>{var X;H[2]==="evict"&&y.increment("lru-eviction",{name:D.name}),(X=D.dispose)===null||X===void 0||X.call(D,...H)},disposeAfter:(...H)=>{var X;this.updateStats(),(X=D.disposeAfter)===null||X===void 0||X.call(D,...H)}})),this.stringify=D.fastStringify?JSON.stringify:E.a}set(D,H,X){const ie=this.stringify(D);if(!this.cache.set(ie,H,{ttl:X})){const oe=this.cache.sizeCalculation?this.cache.sizeCalculation(H,ie):"unknown";throw Error(`Value too large (${oe} > ${this.cache.max})`)}this.updateStats()}get(D){const{name:H}=this.options,X=this.stringify(D),ie=this.cache.getRemainingTTL(X);return ie<=0?y.increment("cache-miss",{name:H}):ie!==1/0&&y.aggregate("cache-item-ttl",ie,{name:H}),this.cache.get(X)}delete(D){this.cache.delete(this.stringify(D))}peek(D){return this.cache.peek(this.stringify(D))}size(){return this.cache.size}clear(){this.cache.clear()}forEach(D){this.cache.forEach(D)}purgeStale(){return this.cache.purgeStale()}updateStats(){const{name:D}=this.options;y.aggregate("cache-item-count",this.cache.size,{name:D}),this.cache.calculatedSize!==void 0&&y.aggregate("cache-length",this.cache.calculatedSize,{name:D})}}{constructor(D){if(super(D),this.expireRejectedPromiseValues=D.expireRejectedPromiseValues===void 0||D.expireRejectedPromiseValues,this.rejectedPromiseValueTtl=D.rejectedPromiseValueTtl!==void 0?D.rejectedPromiseValueTtl:c.a.second,this.rejectedPromiseValueTtl<0)throw new Error("rejectedPromiseValueTtl must not be negative")}set(D,H,X){super.set(D,H,X),this.expireRejectedPromiseValues&&H.catch(()=>m(this,void 0,void 0,function*(){yield Object(u.a)(this.rejectedPromiseValueTtl),this.peek(D)===H&&this.delete(D)}))}}var _=function(pe,D,H,X){return new(H||(H=Promise))(function(ie,oe){function de(ce){try{be(X.next(ce))}catch(le){oe(le)}}function ye(ce){try{be(X.throw(ce))}catch(le){oe(le)}}function be(ce){var le;ce.done?ie(ce.value):(le=ce.value,le instanceof H?le:new H(function(Re){Re(le)})).then(de,ye)}be((X=X.apply(pe,D||[])).next())})};class L{constructor(D,H,X){this.authClient=D,this.email=H,this.password=X,this.tokenTtlMs=1*c.a.hour,this.tokenCache=new I({name:"Credentials-tokenCache",max:100,ttl:this.tokenTtlMs-5*c.a.minute,fastStringify:!0})}getToken(){return _(this,void 0,void 0,function*(){let D=this.tokenCache.get(this.email);return D||(D=(()=>_(this,void 0,void 0,function*(){const{authentication:H}=yield this.authClient.login({email:this.email,password:this.password,tokenExpirationSeconds:this.tokenTtlMs/c.a.second});if(!H)throw new Error("User account not verified.");return H.accessToken}))(),this.tokenCache.set(this.email,D)),D})}}var W=n(97),B=n(40),N=function(pe,D,H,X){return new(H||(H=Promise))(function(ie,oe){function de(ce){try{be(X.next(ce))}catch(le){oe(le)}}function ye(ce){try{be(X.throw(ce))}catch(le){oe(le)}}function be(ce){var le;ce.done?ie(ce.value):(le=ce.value,le instanceof H?le:new H(function(Re){Re(le)})).then(de,ye)}be((X=X.apply(pe,D||[])).next())})};class P extends B.a{constructor(D){super(D)}postLanRtcOffer(D){return N(this,void 0,void 0,function*(){return yield this.fetch("v1/lan-rtc-offer",{method:"POST",body:JSON.stringify(D)})})}}var z=function(pe,D,H,X){return new(H||(H=Promise))(function(ie,oe){function de(ce){try{be(X.next(ce))}catch(le){oe(le)}}function ye(ce){try{be(X.throw(ce))}catch(le){oe(le)}}function be(ce){var le;ce.done?ie(ce.value):(le=ce.value,le instanceof H?le:new H(function(Re){Re(le)})).then(de,ye)}be((X=X.apply(pe,D||[])).next())})};function O(pe){return z(this,void 0,void 0,function*(){return(yield Promise.all(pe.map(D=>D.catch(H=>H)))).filter(D=>D instanceof Error)})}function p(pe){if(pe!==void 0)return pe;throw new Error("Value is undefined")}function U(pe,D){const H=pe.reduce((X,ie)=>[...X,...ie.urls],[]).filter(X=>V(X,D)).sort(X=>Q(X,"udp")?-1:0).shift();if(H)return Object.assign(Object.assign({},p(pe.find(X=>X.urls.includes(H)))),{urls:[H]})}function V(pe,D){switch(D){case"stun":return/^stuns?:/.test(pe);case"turn":return/^turns?:/.test(pe)}}function Q(pe,D){return pe.endsWith(`transport=${D}`)}var ee=n(9),ne=n(24),Y=n(229);class G extends Error{constructor(D,H){super(`Deadline expired after ${D}ms + ${H}ms`)}}class S{static withDeadline(D,H){const X=new Promise((ie,oe)=>{setTimeout(()=>{oe(new G(H,this.grpcCallDeadlineSlopMs))},H+this.grpcCallDeadlineSlopMs)});return Promise.race([D,X])}}S.grpcCallDeadlineSlopMs=500*c.a.millisecond;var T=n(29);const k={ordered:!1,maxPacketLifeTime:300*c.a.millisecond},J={ordered:!0},K={ordered:!0},re={ordered:!1,maxRetransmits:0},se={ordered:!1,maxRetransmits:0},fe=pe=>"received"in pe&&pe.received!==void 0,ve=pe=>!("received"in pe)||pe.received===void 0,Ce=2*c.a.second;function Se(pe,D={}){const H=Array.from(pe.values()),X=H.filter(fe),ie=X.length>0,oe=Math.max(...X.map(ce=>ce.received));let de;if(ie){const ce=H.length,le=X.length,Re=X.map(Le=>Le.received-Le.sent),{standardDeviation:Me,mean:xe,jitter:ze}=function(Le){const ke=Le.length;if(ke===0)return{mean:NaN,standardDeviation:-1,jitter:NaN};const $e=Le.reduce((Qe,st)=>Qe+st,0)/ke,qe=Math.sqrt(Le.map(Qe=>Math.pow(Qe-$e,2)).reduce((Qe,st)=>Qe+st)/ke);if(ke===1)return{mean:$e,standardDeviation:qe,jitter:NaN};let Je=0;for(let Qe=1;Qe<ke;Qe++)Je+=Math.abs(Le[Qe]-Le[Qe-1]);return{mean:$e,standardDeviation:qe,jitter:Je/(ke-1)}}(Re),Xe=H.filter(Le=>Le.sent<oe-Ce),Ze=Xe.filter(ve),Ke=Ze.length===0?0:Ze.length/Xe.length;de={pingsSent:ce,pongsReceived:le,average:xe,standardDeviation:Me,jitter:ze,max:Math.max(...Re),min:Math.min(...Re),loss:Ke}}else de=null;const{temporalNow:ye=Date.now()}=D,be=(ie?oe:ye)-4*Ce;return Array.from(pe.entries()).forEach(ce=>{const[le,Re]=ce;Re.sent<be&&pe.delete(le)}),de}function Ie({entityId:pe,streamName:D,streamType:H}){return`${pe}.${D}.${H}`}var Te=function(pe,D,H,X){return new(H||(H=Promise))(function(ie,oe){function de(ce){try{be(X.next(ce))}catch(le){oe(le)}}function ye(ce){try{be(X.throw(ce))}catch(le){oe(le)}}function be(ce){var le;ce.done?ie(ce.value):(le=ce.value,le instanceof H?le:new H(function(Re){Re(le)})).then(de,ye)}be((X=X.apply(pe,D||[])).next())})};class Oe{constructor(D,H){this.sessionId=D,this.connection=H,this.counts={localSent:new Map,localReceived:new Map,remoteSent:new Map,remoteReceived:new Map},this.sessionId=D,this.connection=H}updateRemoteMessagesCounts(D){if(D.payload.streamsInfo){this.counts.remoteSent=new Map,this.counts.remoteReceived=new Map;for(const H of D.payload.streamsInfo.items)this.counts.remoteSent.set(H.streamId,H.sentCount),this.counts.remoteReceived.set(H.streamId,H.receivedCount)}}getLocalStreamsInfo(D){const{localSent:H,localReceived:X}=this.counts;return{items:[...new Set([...H.keys(),...X.keys()])].map(ie=>{var oe,de;return{streamId:ie,sentCount:(oe=H.get(ie))!==null&&oe!==void 0?oe:0,receivedCount:(de=X.get(ie))!==null&&de!==void 0?de:0}}),timestamp:D}}incrementLocalSent(D){const{localSent:H}=this.counts,X=Ie(D.header.stream);H.set(X,(H.get(X)||0)+1)}incrementLocalReceived(D){const{localReceived:H}=this.counts,X=Ie(D.header.stream),ie=H.get(X)||0;if(ie===0){const{streamName:oe,streamType:de}=D.header.stream;g.a.debug("RTC client received first message for stream",{streamName:oe,streamType:de})}H.set(X,ie+1)}uploadMetrics(){return Te(this,void 0,void 0,function*(){const{sessionId:D}=this,H=yield this.connection.peerConnection.getStats(),X={};H.forEach(ce=>X[ce.id]=ce),g.a.debug("rtc-stats",Object.assign(Object.assign({},X),{sessionId:D}));const{localSent:ie,localReceived:oe,remoteSent:de,remoteReceived:ye}=this.counts,be=[...new Set([...ie.keys(),...oe.keys()])].reduce((ce,le)=>{const Re=ie.get(le),Me=oe.get(le),xe=de.get(le),ze=ye.get(le);return Object.assign(Object.assign({},ce),{[`local-${le}-sent`]:Re,[`local-${le}-received`]:Me,[`remote-${le}-sent`]:xe,[`remote-${le}-received`]:ze})},{sessionId:D});g.a.debug("rtc-message-report",Object.assign({deviceId:this.connection.getRemoteDeviceId()},be))})}}function De(pe,D,H){return{header:{stream:pe,created:Date.now(),frameId:H||""},payload:D}}function Ye(pe){return new Set(["disconnected","failed","closed"]).has(pe.iceConnectionState)}function nt(pe){switch(pe.header.stream.streamType){case"twist":{const{twist:D}=pe.payload;if(!D)throw Error("twist not in payload of RTC message with type twist");return{header:pe.header,payload:{twist:{linear:Object.assign({x:0,y:0,z:0},D.linear),angular:Object.assign({x:0,y:0,z:0},D.angular)}}}}case"pose":{const{pose:D}=pe.payload;if(!D)throw Error("pose not in payload of RTC message with type pose");return{header:pe.header,payload:{pose:{translation:Object.assign({x:0,y:0,z:0},D.translation),rotation:Object.assign({x:0,y:0,z:0,w:0},D.rotation)}}}}case"pose-with-covariance":{const{poseWithCovariance:D}=pe.payload;if(!D)throw Error("poseWithCovariance not in payload of RTC message with type pose-with-covariance");const H=new Array(36).fill(0);return D.covariance.forEach((X,ie)=>{if(ie>=36)throw Error("covariance contains more than 36 elements");H[ie]=X}),{header:pe.header,payload:{poseWithCovariance:{pose:{translation:Object.assign({x:0,y:0,z:0},D.pose.translation),rotation:Object.assign({x:0,y:0,z:0,w:0},D.pose.rotation)},covariance:H}}}}case"point":{const{point:D}=pe.payload;if(!D)throw Error("point not in payload of RTC message with type point");return{header:pe.header,payload:{point:Object.assign({x:0,y:0,z:0},D)}}}default:return pe}}var tt=function(pe,D,H,X){return new(H||(H=Promise))(function(ie,oe){function de(ce){try{be(X.next(ce))}catch(le){oe(le)}}function ye(ce){try{be(X.throw(ce))}catch(le){oe(le)}}function be(ce){var le;ce.done?ie(ce.value):(le=ce.value,le instanceof H?le:new H(function(Re){Re(le)})).then(de,ye)}be((X=X.apply(pe,D||[])).next())})};class bt{constructor(D,H,X){this.peerConnection=D,this.config=H,this.dataChannelNotifier=X,this.connectTimeoutMs=20*c.a.second,this.iceGatheringTimeoutMs=15*c.a.second,this.pingUpdateTimeoutMs=1*c.a.second,this.pingV2UpdateTimeoutMs=250*c.a.millisecond,this.pingV2MetricsGatherTimeoutMs=1*c.a.second,this.streamsInfoUpdateTimeoutMs=2*c.a.second,this.reassemblyTimeoutMs=500*c.a.millisecond,this.reassemblyTableCleanupMs=1*c.a.second,this.heartbeatTimeoutMs=20*c.a.millisecond,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:oe}=this;if(!oe)return;const de=new Date().getTime(),ye=Object(Y.a)();this.sendSystemMessage(oe,{type:"ping-v2",payload:{timestamp:de,id:ye}}),this.pingV2Map.set(ye,{sent:de})},this.gatherPingV2Metrics=()=>{const oe=Se(this.pingV2Map);if(oe){const de=this.getRemoteDeviceId();this.pingInfo=oe,y.aggregate("rtc-ping-average",oe.average,Object.assign({},de?{deviceId:de}:{})),y.aggregate("rtc-ping-loss",oe.loss,Object.assign({},de?{deviceId:de}:{})),y.aggregate("rtc-jitter",oe.jitter,Object.assign({},de?{deviceId:de}:{}))}};const{isOffer:ie}=H.baseConfig;ie?this.initializeChannels(D):D.ondatachannel=oe=>{switch(oe.channel.label){case"stream.latest-ttl":this.latestTtlStreamChannel=oe.channel;break;case"stream.reliable":this.reliableStreamChannel=oe.channel;break;case"stream.latest-reliable":this.latestReliableStreamChannel=oe.channel;break;case"stream.latest-try-once":this.latestTryOnceStreamChannel=oe.channel;break;case"heartbeat":return void(this.heartbeatChannel=oe.channel);default:return void this.dataChannelNotifier(oe.channel)}this.setupChannel(oe.channel)},this.pingUpdateTimeout=setInterval(()=>{const{reliableStreamChannel:oe}=this;oe&&this.sendSystemMessage(oe,{type:"ping"})},this.pingUpdateTimeoutMs),this.pingV2UpdateTimeout=setInterval(this.sendPingV2,this.pingV2UpdateTimeoutMs),this.pingV2MetricsGatherTimeout=setInterval(this.gatherPingV2Metrics,this.pingV2MetricsGatherTimeoutMs),this.streamsInfoUpdateTimeout=setInterval(()=>{const{latestTtlStreamChannel:oe}=this;oe&&this.sendSystemMessage(oe,{type:"streams-info"})},this.streamsInfoUpdateTimeoutMs),this.reassemblyTableCleanupTimeout=setInterval(()=>{const oe=new Date().getTime();this.reassemblyTableLastTimestamp.forEach((de,ye,be)=>{oe>ye+this.reassemblyTimeoutMs&&this.reassemblyTable.delete(de)})},this.reassemblyTableCleanupMs),this.heartbeatTimeout=setInterval(()=>{const{heartbeatChannel:oe}=this;oe&&oe.readyState==="open"&&oe.send(new Uint8Array([1]))},this.heartbeatTimeoutMs)}handleSignal(D){return tt(this,void 0,void 0,function*(){const{peerConnection:H}=this,{track:X}=this.config.baseConfig,ie=(()=>{try{return JSON.parse(D.getPayload())}catch{return}})();if(!ie)return void g.a.error("Received unparseable signal.");g.a.debug("Handling signal",{description:ie});const{sdp:oe,type:de}=ie;if(!oe||!de)return void g.a.warn("Received non-SDP signal");const{signalingState:ye,connectionState:be}=H;if(ye!=="stable"||be!=="connected")if(H.remoteDescription)g.a.warn(`Received SDP after remote description was set: ${oe}`);else{if(de==="offer"){if(ye!=="stable")return void g.a.warn("Received offer SDP when signaling is ongoing.");yield H.setRemoteDescription(ie);const ce=yield H.createAnswer();yield H.setLocalDescription(ce);const le=D.clone();return X==null||X("Answer Received",le),le.setPayload(JSON.stringify(ce)),le.setReceiverId(D.getSenderId()),le.setSenderId(D.getReceiverId()),le}if(de==="answer"){if(ye==="stable")return void g.a.warn("Received answer SDP when signaling hasn't started.");yield H.setRemoteDescription(ie)}}else g.a.warn(`Received SDP when already connected: ${oe}`)})}send(D,H){const X=this.getChannelFromLabel(H.channelLabel);X?this.sendOnChannel(X,D):g.a.warn("Send called with unexpected channel label",{channelLabel:H.channelLabel})}controlRemoteStream(D){this.sendSystemMessage(p(this.reliableStreamChannel),{type:"stream-control",streamControl:D})}isActive(){return new Set(["new","checking","connected","completed"]).has(this.peerConnection.iceConnectionState)||this.isReady()}isReady(){const{reliableStreamChannel:D,latestTtlStreamChannel:H,latestTryOnceStreamChannel:X,latestReliableStreamChannel:ie}=this;return(D==null?void 0:D.readyState)==="open"&&(H==null?void 0:H.readyState)==="open"&&(X==null?void 0:X.readyState)==="open"&&(ie==null?void 0:ie.readyState)==="open"}close(){return tt(this,void 0,void 0,function*(){if(this.closeCalled)return;this.closeCalled=!0,this.sessionMetrics&&(yield this.sessionMetrics.uploadMetrics()),lt(this.pingUpdateTimeout),lt(this.pingV2UpdateTimeout),lt(this.pingV2MetricsGatherTimeout),lt(this.reassemblyTableCleanupTimeout),lt(this.streamsInfoUpdateTimeout),lt(this.heartbeatTimeout);const{peerConnection:D,reliableStreamChannel:H,latestTtlStreamChannel:X,latestTryOnceStreamChannel:ie,latestReliableStreamChannel:oe}=this;D.close(),H==null||H.close(),X==null||X.close(),ie==null||ie.close(),oe==null||oe.close()})}getPing(){return this.pingTimeMs}getPingInfo(){return this.pingInfo}getLastMessageTimestamp(){return this.lastMessageTimestamp}getSessionCreatedTimestamp(){var D;return(D=this.config.remoteConfig)===null||D===void 0?void 0:D.sessionCreatedTimestamp}setSessionCreatedTimestamp(D){this.config.remoteConfig&&(this.config.remoteConfig.sessionCreatedTimestamp=D)}getSessionId(){var D;return(D=this.config.remoteConfig)===null||D===void 0?void 0:D.sessionId}setSessionId(D){this.config.remoteConfig&&(this.config.remoteConfig.sessionId=D,this.sessionMetrics=new Oe(D,this))}getRemotePeerId(){return this.config.baseConfig.remotePeerId}getRemoteDeviceId(){var D;return(D=this.config.baseConfig)===null||D===void 0?void 0:D.remoteDeviceId}setRemoteDeviceId(D){this.config.baseConfig.remoteDeviceId=D}getSessionMetricsMessageCounts(){var D;return(D=this.sessionMetrics)===null||D===void 0?void 0:D.counts}getConnectionStatsInfo(){return tt(this,void 0,void 0,function*(){const{peerConnection:D}=this;if(!D)return;const H=yield D.getStats(null),X=[];H.forEach(be=>{X.push(be)});const ie=X.find(be=>be.type==="transport");if(!ie)return;const oe=X.find(be=>(be.type==="candidate-pair"||be.type==="candidatepair")&&be.id===ie.selectedCandidatePairId);if(!oe)return;const de=X.find(be=>be.id===oe.localCandidateId),ye=X.find(be=>be.id===oe.remoteCandidateId);return de&&ye&&(de.address=de.address||de.ip,ye.address=ye.address||ye.ip,de.address!==void 0&&ye.address!==void 0)?{transport:ie,localCandidate:de,remoteCandidate:ye}:void 0})}initializeChannels(D){this.heartbeatChannel=D.createDataChannel("heartbeat",se),this.heartbeatChannel.binaryType="arraybuffer",this.latestTtlStreamChannel=D.createDataChannel("stream.latest-ttl",k),this.latestTtlStreamChannel.binaryType="arraybuffer",this.reliableStreamChannel=D.createDataChannel("stream.reliable",J),this.reliableStreamChannel.binaryType="arraybuffer",this.latestReliableStreamChannel=D.createDataChannel("stream.latest-reliable",K),this.latestReliableStreamChannel.binaryType="arraybuffer",this.latestTryOnceStreamChannel=D.createDataChannel("stream.latest-try-once",re),this.latestTryOnceStreamChannel.binaryType="arraybuffer",this.setupChannel(this.latestTtlStreamChannel),this.setupChannel(this.reliableStreamChannel),this.setupChannel(this.latestReliableStreamChannel),this.setupChannel(this.latestTryOnceStreamChannel)}getOffer(){var D,H,X;return tt(this,void 0,void 0,function*(){const{gotOffer:ie}=this,{peerConnection:oe,config:de}=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 ye=(D=this.config.remoteConfig)===null||D===void 0?void 0:D.sessionId;if(ie)return void g.a.debug("Failed to generate offer because gotOffer was already called.");if(this.gotOffer=!0,Ye(this.peerConnection))return void g.a.debug("Failed to generate offer because the peer connection was inactive.");const be=de.baseConfig.track;oe.onicecandidate=()=>{this.hasIceCandidate=!0},oe.oniceconnectionstatechange=()=>tt(this,void 0,void 0,function*(){const xe=oe.iceConnectionState;if(xe==="connected"||xe==="completed"){const ze=yield this.getConnectionStatsInfo(),Xe=ze?function(Ze){const Ke=Ze.localCandidate.candidateType,Le=Ze.remoteCandidate.candidateType;return Ke==="host"&&Le==="host"?"local":Ke==="relay"||Le==="relay"?"TURN":"STUN"}(ze):void 0;g.a.info(`ICE connection state changed to ${xe}`,{sessionId:ye,connectionStatsInfo:ze,iceMode:Xe}),be==null||be("ICE connection state change",{iceConnectionState:xe,sessionId:ye,connectionStatsInfo:ze,iceMode:Xe})}}),yield oe.setLocalDescription(yield oe.createOffer());const ce=new Date().getTime();for(;;){const xe=new Date().getTime()-ce;if(xe>this.connectTimeoutMs)return void g.a.debug("Failed to generate offer because ICE gathering timed out.");if(xe>this.iceGatheringTimeoutMs&&this.hasIceCandidate){g.a.debug("ICE gathering partially completed; proceeding",{iceTransportPolicy:oe.getConfiguration().iceTransportPolicy,waitTime:xe}),be==null||be("ICE gathering partially completed",{sessionId:ye,iceTransportPolicy:oe.getConfiguration().iceTransportPolicy,waitTime:xe});break}if(oe.iceGatheringState==="complete"){g.a.debug("ICE gathering complete",{iceTransportPolicy:oe.getConfiguration().iceTransportPolicy,waitTime:xe}),be==null||be("ICE gathering completed",{sessionId:ye,iceTransportPolicy:oe.getConfiguration().iceTransportPolicy,waitTime:xe});break}yield Object(u.a)(.1*c.a.second)}const le=(H=this.peerConnection.getConfiguration().iceServers)!==null&&H!==void 0?H:[];for(const xe of le)"credentialType"in xe&&(xe.credentialType=void 0);const Re=JSON.stringify(le),Me=new ee.Signal;return Me.setPayload(JSON.stringify(oe.localDescription)),Me.setSenderId(this.config.baseConfig.localPeerId),Me.setReceiverId(this.config.baseConfig.remotePeerId),Me.setIceServers(Re),Me.setIceTransportPolicy((X=this.peerConnection.getConfiguration().iceTransportPolicy)!==null&&X!==void 0?X:"all"),this.config.baseConfig.sessionType!==void 0?Me.setSessionType(this.config.baseConfig.sessionType):Me.setSessionType(ee.SessionType.TELEOP),g.a.debug("Sending offer signal with description",{description:Me.getPayload()}),Me})}getLanOffer(){return tt(this,void 0,void 0,function*(){const{peerConnection:D,gotOffer:H}=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(H)return void g.a.debug("Failed to generate offer because gotOffer was already called.");if(this.gotOffer=!0,Ye(this.peerConnection))return void g.a.debug("Failed to generate offer because the peer connection was inactive.");yield D.setLocalDescription(yield D.createOffer());const X=new Date().getTime();for(;;){if(new Date().getTime()-X>this.iceGatheringTimeoutMs)return void g.a.debug("Failed to generate offer because ICE gathering timed out.");if(D.iceGatheringState==="complete")break;yield Object(u.a)(.1*c.a.second)}const ie=D.localDescription;if(ie)return g.a.debug("Sending LAN offer signal with description",{description:ie}),ie;g.a.error("Failed to generate LAN offer description")})}handleLanAnswer(D){return tt(this,void 0,void 0,function*(){const{peerConnection:H}=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 H.setRemoteDescription(D)})}getChannelFromLabel(D){switch(D){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(D,H){let X;try{X=Object(T.encode)(JSON.stringify(H))}catch(ie){return void g.a.warn("Failed to encode RTC message",{error:ie})}try{D.send(X),this.sessionMetrics&&this.sessionMetrics.incrementLocalSent(H)}catch(ie){g.a.warn("Failed to send message to channel",{error:ie,channel:D.label})}}channelNotRecognized(D){return D!==this.latestTtlStreamChannel&&D!==this.latestReliableStreamChannel&&D!==this.latestTryOnceStreamChannel&&D!==this.reliableStreamChannel}setupChannel(D){D.onmessage=H=>{if(this.channelNotRecognized(D))return void g.a.warn("Received message on unrecognized data channel.");let X;try{X=JSON.parse(Object(T.decode)(H.data))}catch(ie){return void g.a.warn("Received unparseable message on RTC stream data channel",{error:ie,channel:D.label})}X.communicationType==="message-chunk"?this.receiveChannelMessageChunk(D,X):this.receiveChannelMessage(D,X)},D.onerror=H=>{g.a.warn(`Channel error: ${H.error}`,{error:H.error,sessionId:this.getSessionId(),channelLabel:D.label})},D.onopen=()=>{g.a.debug("Channel opened",{sessionId:this.getSessionId(),channelLabel:D.label})},D.onclose=()=>{const H={bufferedAmount:D.bufferedAmount,sessionId:this.getSessionId(),channelLabel:D.label};this.closeCalled===!1?g.a.debug("Unexpected channel closed",H):g.a.debug("Channel closed",H)}}receiveChannelMessage(D,H){const{config:X}=this,{remotePeerId:ie}=this.config.baseConfig;this.lastMessageTimestamp=new Date().getTime(),H=nt(H),this.sessionMetrics&&this.sessionMetrics.incrementLocalReceived(H),this.handleSystemMessage(D,H)||(D===this.latestTryOnceStreamChannel||D===this.latestTtlStreamChannel||D===this.latestReliableStreamChannel)&&!this.isLatestMessage(H)||X.baseConfig.receive(ie,H)}receiveChannelMessageChunk(D,H){const X=this.reassemblyTable.get(H.id)||[];if(X.push(H),X.length===H.total){const ie=function(oe){const de=oe.sort((ye,be)=>ye.seq<be.seq?-1:1).map(ye=>ye.part).reduce((ye,be)=>ye+be);try{return JSON.parse(de)}catch{return void g.a.warn("Could not reassemble RTC message chunks")}}(X);return ie&&this.receiveChannelMessage(D,ie),void this.reassemblyTable.delete(H.id)}this.reassemblyTable.set(H.id,X),this.reassemblyTableLastTimestamp.set(H.id,new Date().getTime())}handleSystemMessage(D,H){var X,ie;const{config:oe}=this,{baseConfig:de}=oe,{remotePeerId:ye,remoteDeviceId:be}=de;switch(H.header.stream.streamType){case"ping":return this.sendSystemMessage(D,{type:"pong",timestamp:p(H.payload.ping)}),!0;case"pong":{const ce=new Date().getTime()-p(H.payload.pong);return this.pingTimeMs=ce,y.aggregate("rtc-ping-time",ce,Object.assign({},be?{deviceId:be}:{})),!0}case"ping-v2":return this.sendPingV2(),!0;case"pong-v2":{const ce=p(H.payload.pongV2),le=this.pingV2Map.get(ce.id);return(le==null?void 0:le.sent)!==ce.timestamp&&g.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=(X=H.payload.streamsInfo)===null||X===void 0?void 0:X.timestamp;return!!le&&(ce==null||ce.updateRemoteMessagesCounts(H),(ie=de.onStreamsInfoUpdate)===null||ie===void 0||ie.call(de,ye,le),!0)}case"stream-control":return!0;default:return!1}}sendSystemMessage(D,H){var X;const{localUserId:ie,localPeerId:oe}=this.config.baseConfig;if(D.readyState!=="open")return;const de={entityId:ie??oe,streamName:`$.${H.type}`,streamType:H.type};let ye;switch(H.type){case"ping":ye={ping:new Date().getTime()};break;case"pong":ye={pong:H.timestamp};break;case"ping-v2":ye={pingV2:H.payload};break;case"pong-v2":ye={pongV2:H.payload};break;case"stream-control":ye={streamControl:H.streamControl};break;case"streams-info":ye={streamsInfo:(X=this.sessionMetrics)===null||X===void 0?void 0:X.getLocalStreamsInfo(new Date().getTime())}}this.sendOnChannel(D,De(de,ye))}isLatestMessage(D){const H=Ie(D.header.stream),X=(this.streamLatestTimestamp.get(H)||0)<=D.header.created;return X&&this.streamLatestTimestamp.set(H,D.header.created),X}}function lt(pe){pe&&clearInterval(pe)}function _t(){g.a.debug("forceGarbageCollection() triggered"),queueMicrotask(()=>{let pe=document.createElement("img");pe.src=window.URL.createObjectURL(new Blob([new ArrayBuffer(5e7)])),pe.onerror=function(){window.URL.revokeObjectURL(this.src),pe=null}})}function It(pe){try{return pe instanceof Error?`${pe.name}: ${pe.message}`:typeof pe=="object"?JSON.stringify(pe):String(pe)}catch{return"Unknown error"}}function Et(pe){var D,H;return{userId:(D=pe.getUserId())===null||D===void 0?void 0:D.getValue(),deviceId:(H=pe.getDeviceId())===null||H===void 0?void 0:H.getValue(),organizationId:pe.getOrganizationId(),id:pe.getPeerId(),capabilities:[],capabilitySet:{}}}var Ue=function(pe,D,H,X){return new(H||(H=Promise))(function(ie,oe){function de(ce){try{be(X.next(ce))}catch(le){oe(le)}}function ye(ce){try{be(X.throw(ce))}catch(le){oe(le)}}function be(ce){var le;ce.done?ie(ce.value):(le=ce.value,le instanceof H?le:new H(function(Re){Re(le)})).then(de,ye)}be((X=X.apply(pe,D||[])).next())})};class Nt{constructor(D){this.config=D,this.grpcCallDeadline=5*c.a.second,this.refreshIntervalDelayMs=2*c.a.second,this.iceServersTtl=30*c.a.minute,this.connections=[],this.localConnections=[],this.isConnectionInitiator=new Map,this.isOutgoingConnection=new Map,this.peerDataChannelListeners=[],this.rtcInstancesConstructed=0;const{refreshIntervalDelayMs:H}=this;this.refreshInterval=d({func:()=>Ue(this,void 0,void 0,function*(){try{yield this.update()}catch(X){g.a.warn("RTC refresh failed",{error:X})}}),delay:H,immediate:!0})}send(D,H,X){const ie=this.getActiveConnection(D);ie?ie.isReady()?ie.send(H,X):g.a.warn("Send called with unready connection."):g.a.warn("Send called with no connection.")}controlRemoteStream(D,H){const X=this.getActiveConnection(D);X?X.isReady()?X.controlRemoteStream(H):g.a.warn("controlRemoteStream called with unready connection."):g.a.warn("controlRemoteStream called with no connection.")}getLocalPeer(){return Ue(this,void 0,void 0,function*(){for(;!this.localPeer;)yield Object(u.a)(.1*c.a.second);return Et(this.localPeer)})}connect(D,H){var X,ie,oe;return Ue(this,void 0,void 0,function*(){if(this.config.lanOnlyMode===!0)throw new Error("connect method called in local only mode.");const{track:de,signalingClient:ye}=this.config,{localPeer:be,receiveSignalStream:ce,iceServers:le}=this;if(!be||!ce||!le)return void g.a.warn("Connect called prior to local peer, receiveSignalStream, and ICE servers ready");if(this.getActiveConnection(D))return void g.a.warn("Connect called for peer with existing connection.");if(this.isOutgoingConnection.get(D))return void g.a.warn("Connect called for peer with an existing outgoing connection offer.");this.isOutgoingConnection.set(D,!0);const Re=function(Le,ke,$e){const{rtcIceTransportPolicies:qe,rtcIceServerProtocol:Je,useAllServers:Qe}=ke||{},st=Le.map(at=>Object.assign(Object.assign({},at),{urls:at.urls.filter(ct=>{const et=(qe===void 0||qe.some(Mt=>V(ct,Mt)))&&(Je===void 0||Q(ct,Je));return et||g.a.debug(`Ignoring ICE server: ${ct}`,{organizationId:$e}),et})})).filter(({urls:at})=>at.filter(ct=>ct).length>0);return Qe?st:[U(st,"stun"),U(st,"turn")].filter(at=>at!==void 0).map(at=>p(at))}(le,H);g.a.debug("Received ICE servers:",le),g.a.debug("Using ICE servers:",Re);const Me=new bt(yield this.createRTCPeerConnection(Re),{baseConfig:{isOffer:!0,isLan:!1,receive:(Le,ke)=>this.config.receive(Le,ke),onStreamsInfoUpdate:this.config.onStreamsInfoUpdate?(Le,ke)=>{var $e,qe;return(qe=($e=this.config).onStreamsInfoUpdate)===null||qe===void 0?void 0:qe.call($e,Le,ke)}:void 0,track:this.config.lanOnlyMode?void 0:this.config.track,localUserId:(X=be.getUserId())===null||X===void 0?void 0:X.getValue(),localPeerId:be.getPeerId(),remotePeerId:D,sessionType:this.config.sessionType},remoteConfig:{}},Le=>this.onCustomDataChannel(D,Le)),xe=yield Me.getOffer();if(!xe)return g.a.error("Failed to generate offer."),void this.isOutgoingConnection.delete(D);g.a.debug("Sending offer."),de==null||de("Sending offer",xe);const ze=new ee.SendSignalRequest;ze.setSignal(xe);const Xe=yield(()=>Ue(this,void 0,void 0,function*(){try{return yield S.withDeadline(ye.sendSignal(ze,yield this.getMetadata({})),this.grpcCallDeadline)}catch(Le){g.a.warn("Error when sending signal",{error:Le})}}))();if(!this.isOutgoingConnection.get(D))return void g.a.debug("No offer set after receiving offer signal response.");g.a.debug("Offer sent.");const Ze=(ie=Xe==null?void 0:Xe.getSessionId())===null||ie===void 0?void 0:ie.getValue(),Ke=(oe=Xe==null?void 0:Xe.getSessionCreatedTimestamp())===null||oe===void 0?void 0:oe.getValue();return Ze&&Ke?(Me.setSessionId(Ze),Me.setSessionCreatedTimestamp(Ke),this.isOutgoingConnection.delete(D),this.connections.push(Me),this.isConnectionInitiator.set(Me,!0),this.setupHandlers(Me),Ze):(g.a.warn("No session ID or no session created timestamp on send signal response."),void this.isOutgoingConnection.delete(D))})}connectLan(D){var H,X;return Ue(this,void 0,void 0,function*(){const ie=new P(D),oe=new bt(yield this.createRTCPeerConnection([]),{baseConfig:{isOffer:!0,isLan:!0,receive:(ce,le)=>this.config.receive(ce,le),onStreamsInfoUpdate:this.config.onStreamsInfoUpdate?(ce,le)=>{var Re,Me;return(Me=(Re=this.config).onStreamsInfoUpdate)===null||Me===void 0?void 0:Me.call(Re,ce,le)}:void 0,track:this.config.lanOnlyMode?void 0:this.config.track,localUserId:(X=(H=this.localPeer)===null||H===void 0?void 0:H.getUserId())===null||X===void 0?void 0:X.getValue(),localPeerId:"lan_client",remotePeerId:D}},ce=>this.onCustomDataChannel(D,ce)),de=yield oe.getLanOffer();if(!de)return g.a.warn("Could not generate LAN offer"),!1;const ye=yield ie.postLanRtcOffer({offer:JSON.stringify(de)}),be=new RTCSessionDescription(JSON.parse(ye.answer));return yield oe.handleLanAnswer(be),this.localConnections.push(oe),this.isConnectionInitiator.set(oe,!0),Object(Y.a)()})}getConnections(){return[...this.connections,...this.localConnections]}createCustomDataChannel(D,H,X,ie,oe){const de=this.getActiveConnection(D);if(de&&this.isConnectionInitiator.has(de)){const be=de.peerConnection.createDataChannel("custom."+H,X);return ie&&(be.binaryType="arraybuffer"),oe(D,be),()=>{}}const ye=(be,ce)=>{D===be&&ce.label==="custom."+H&&oe(D,ce)};return this.peerDataChannelListeners.push(ye),()=>{this.peerDataChannelListeners=this.peerDataChannelListeners.filter(be=>be!==ye)}}onCustomDataChannel(D,H){this.peerDataChannelListeners.forEach(X=>X(D,H))}getConnectionStatus(D){if(this.isOutgoingConnection.get(D))return"connecting";const H=this.getActiveConnection(D);return H?H.isReady()?"connected":"connecting":"disconnected"}getConnectionStatsInfo(D){return Ue(this,void 0,void 0,function*(){const H=this.getActiveConnection(D);if(H)return yield H.getConnectionStatsInfo()})}disconnect(D){return Ue(this,void 0,void 0,function*(){const H=this.getActiveConnection(D);H&&(yield H.close())})}getPeers(){return Ue(this,void 0,void 0,function*(){if(this.config.lanOnlyMode)throw new Error("getPeers method cannot be used in local-only mode.");const{signalingClient:D}=this.config,H=yield(()=>Ue(this,void 0,void 0,function*(){try{return yield S.withDeadline(D.getPeers(new ee.GetPeersRequest,yield this.getMetadata({})),this.grpcCallDeadline)}catch(oe){g.a.warn("Error when getting peers",{error:oe})}}))();if(!H)return[];const X=H.getPeersList();if(!X)return[];const ie=oe=>{var de,ye;return(ye=(de=oe.getPeerCreatedTimestamp())===null||de===void 0?void 0:de.getValue())!==null&&ye!==void 0?ye:0};return X.sort((oe,de)=>ie(de)-ie(oe)).map(oe=>Et(oe))})}getSessions(){return Ue(this,void 0,void 0,function*(){if(this.config.lanOnlyMode)throw new Error("getPeers method cannot be used in local-only mode.");const{signalingClient:D}=this.config,H=yield(()=>Ue(this,void 0,void 0,function*(){try{return yield S.withDeadline(D.getPeers(new ee.GetPeersRequest,yield this.getMetadata({})),this.grpcCallDeadline)}catch(oe){g.a.warn("Error when getting peers",{error:oe})}}))();if(!H)return{};const X=H.getPeersList(),ie={};for(const oe of X)ie[oe.getPeerId()]=oe.getSessionIdsList();return ie})}getPing(D){const H=this.getActiveConnection(D);if(H)return H.getPing();g.a.warn("Attempted to get ping time from inactive peer.")}getPingInfo(D){const H=this.getActiveConnection(D);if(H)return H.getPingInfo();g.a.warn("Attempted to get ping time from inactive peer.")}getLastMessageTimestamp(D){const H=this.getActiveConnection(D);if(H)return H.getLastMessageTimestamp();g.a.warn("Attempted to get last message time from inactive peer.")}getSessionMetricsMessageCounts(D){const H=this.getActiveConnection(D);if(H)return H.getSessionMetricsMessageCounts();g.a.warn("Attempted to get session metrics counts from inactive peer.")}isReady(){if(this.config.lanOnlyMode)return!0;const{localPeer:D,receiveSignalStream:H,iceServers:X}=this;return!!(D&&H&&X)}shutdown(){return Ue(this,void 0,void 0,function*(){g.a.info("Shutdown called on RTC client"),yield this.refreshInterval.stop(),this.receiveSignalStream&&this.receiveSignalStream.cancel();const D=this.connections;this.connections=[],yield this.closeConnections(D);const{localPeer:H}=this;if(!H||this.config.lanOnlyMode)return;const{signalingClient:X}=this.config;yield(()=>Ue(this,void 0,void 0,function*(){try{const ie=new ee.DeletePeerRequest;ie.setPeerId(H.getPeerId()),yield S.withDeadline(X.deletePeer(ie,yield this.getMetadata({})),this.grpcCallDeadline)}catch(ie){return void g.a.warn("Error deleting local peer",{error:ie})}}))()})}createPeer(){return Ue(this,void 0,void 0,function*(){if(this.config.lanOnlyMode)throw new Error("createPeer method cannot be used in local-only mode.");const{signalingClient:D}=this.config,H=yield(()=>Ue(this,void 0,void 0,function*(){try{return yield S.withDeadline(D.createPeer(new ee.CreatePeerRequest,yield this.getMetadata({})),this.grpcCallDeadline)}catch(ie){const oe=ie;g.a.debug("createPeer failed",{error:oe});const de=It(oe);throw new Error(`Was not able to create peer: ${de}`)}}))(),X=H==null?void 0:H.getPeer();if(!X)throw new Error("Response did not provide peer.");return this.localPeer=X})}createReceiveSignalStream(){return Ue(this,void 0,void 0,function*(){if(this.config.lanOnlyMode)throw new Error("createReceiveSignalStream method cannot be used in local-only mode.");const{signalingClient:D}=this.config,{localPeer:H,iceServers:X}=this;if(!H||!X)return;const{receiveSignalStream:ie}=this;ie&&ie.cancel();const oe=new ee.ReceiveSignalStreamRequest;oe.setPeerId(H.getPeerId());const de=yield(()=>Ue(this,void 0,void 0,function*(){try{return D.receiveSignalStream(oe,yield this.getMetadata({hasDeadline:!1}))}catch(ye){g.a.debug("createReceiveSignalStream failed",{error:ye});const be=It(ye);throw new Error(`Unable to create receive signal stream: ${be}`)}}))();if(!de)throw new Error("Response did not provide stream.");return de.on("data",ye=>Ue(this,void 0,void 0,function*(){var be,ce,le,Re;const Me=ye.getSignal(),xe=(be=Me==null?void 0:Me.getSessionId())===null||be===void 0?void 0:be.getValue(),ze=Me==null?void 0:Me.getSenderId(),Xe=Me==null?void 0:Me.getReceiverId(),Ze=(ce=Me==null?void 0:Me.getSessionCreatedTimestamp())===null||ce===void 0?void 0:ce.getValue();if(!(Me&&xe&&ze&&Xe&&Ze))return void g.a.warn("Received signal with missing information.");const Ke=this.getActiveConnection(ze);if(Ke)if(Ke.getSessionId()!==xe){if(g.a.debug("Received signal: different session for a peer we're already connected to."),(Ke.getSessionCreatedTimestamp()||0)>Ze)return;const Le=new bt(yield this.createRTCPeerConnection(X),{baseConfig:{isOffer:!1,isLan:!1,receive:(ke,$e)=>this.config.receive(ke,$e),onStreamsInfoUpdate:this.config.onStreamsInfoUpdate?(ke,$e)=>{var qe,Je;return(Je=(qe=this.config).onStreamsInfoUpdate)===null||Je===void 0?void 0:Je.call(qe,ke,$e)}:void 0,track:this.config.lanOnlyMode?void 0:this.config.track,localPeerId:H.getPeerId(),localUserId:(Re=H.getUserId())===null||Re===void 0?void 0:Re.getValue(),remotePeerId:ze},remoteConfig:{sessionId:xe,sessionCreatedTimestamp:Ze}},ke=>this.onCustomDataChannel(ze,ke));yield Le.handleSignal(Me),this.connections.push(Le)}else g.a.debug("Received signal: for an existing connection."),yield Ke.handleSignal(Me);else{g.a.debug("Received signal: new connection.");const Le=new bt(yield this.createRTCPeerConnection(X),{baseConfig:{isOffer:!1,isLan:!1,receive:(ke,$e)=>this.config.receive(ke,$e),onStreamsInfoUpdate:this.config.onStreamsInfoUpdate?(ke,$e)=>{var qe,Je;return(Je=(qe=this.config).onStreamsInfoUpdate)===null||Je===void 0?void 0:Je.call(qe,ke,$e)}:void 0,track:this.config.lanOnlyMode?void 0:this.config.track,localPeerId:H.getPeerId(),localUserId:(le=H.getUserId())===null||le===void 0?void 0:le.getValue(),remotePeerId:ze},remoteConfig:{sessionId:xe,sessionCreatedTimestamp:Ze}},ke=>this.onCustomDataChannel(ze,ke));yield Le.handleSignal(Me),this.connections.push(Le)}})),de.on("end",()=>{de.cancel(),this.receiveSignalStream=void 0}),de.on("error",ye=>{switch(ye.code){case ne.StatusCode.CANCELLED:case ne.StatusCode.UNAVAILABLE:case ne.StatusCode.UNKNOWN:g.a.debug("Receive signal stream error",{error:ye});break;case ne.StatusCode.UNAUTHENTICATED:g.a.warn("Receive signal stream error",{error:ye});break;default:g.a.error("Receive signal stream error",{error:ye})}de.cancel(),this.receiveSignalStream=void 0}),this.receiveSignalStream=de})}createRTCPeerConnection(D){var H;return Ue(this,void 0,void 0,function*(){const X=(H=this.config.alternateRTCPeerConnection)!==null&&H!==void 0?H:window.RTCPeerConnection;if(!X)throw function(){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||_t();try{return new X({iceServers:D})}catch(ie){throw g.a.debug(`Failed to create RTCPeerConnection: ${this.rtcInstancesConstructed} total allocated`),ie}})}closeConnections(D){return Ue(this,void 0,void 0,function*(){const H=yield O(D.map(X=>Ue(this,void 0,void 0,function*(){yield X.close()})));for(const X of H)g.a.warn("Request to close session failed",{error:X})})}getActiveConnection(D){return this.getConnections().find(H=>H.getRemotePeerId()===D&&H.isActive())}update(){var D;return Ue(this,void 0,void 0,function*(){if(this.localConnections=this.localConnections.filter(ye=>ye.isActive()),this.config.lanOnlyMode)return;const{signalingClient:H}=this.config;if(!this.localPeer||!this.receiveSignalStream||!this.iceServers){const ye=[];return this.localPeer||ye.push(this.createPeer()),this.iceServers||ye.push(this.updateIceServers()),yield Promise.all(ye),void(this.receiveSignalStream||(yield this.createReceiveSignalStream()))}yield this.closeConnections(this.connections.filter(ye=>!ye.isActive())),this.connections=this.connections.filter(ye=>ye.isActive());const{localPeer:X}=this,ie=this.connections.filter(ye=>ye.getSessionId).map(ye=>p(ye.getSessionId()));X.setSessionIdsList(ie);const oe=new ee.RefreshPeerRequest;oe.setPeer(X);try{yield S.withDeadline(H.refreshPeer(oe,yield this.getMetadata({})),this.grpcCallDeadline)}catch(ye){ye.code===ne.StatusCode.NOT_FOUND?(g.a.warn("Peer expired, creating new peer",{peerId:X.getPeerId()}),yield this.reset()):g.a.warn("Error calling RefreshPeer",{error:ye})}const de=yield this.getPeers();for(const ye of this.connections)ye.setRemoteDeviceId((D=de.find(be=>be.id===ye.getRemotePeerId()))===null||D===void 0?void 0:D.deviceId)})}reset(){return Ue(this,void 0,void 0,function*(){yield this.closeConnections(this.connections),this.connections=[],this.isOutgoingConnection=new Map,yield this.createPeer(),yield this.createReceiveSignalStream()})}updateIceServers(){return Ue(this,void 0,void 0,function*(){if(this.config.lanOnlyMode)return;const{iceServersLastUpdate:D,iceServersTtl:H}=this,X=new Date().getTime();if(!D||X-D>H)try{const ie=(yield S.withDeadline(this.config.signalingClient.getIceServers(new ee.GetIceServersRequest,yield this.getMetadata({})),this.grpcCallDeadline)).getIceServers();this.iceServers=JSON.parse(ie),this.iceServersLastUpdate=X}catch(ie){g.a.warn("Error in updateIceServers",{error:ie})}})}setupHandlers(D){const{peerConnection:H}=D,X=D.getSessionCreatedTimestamp();H.onconnectionstatechange=()=>Ue(this,void 0,void 0,function*(){const ie=H.connectionState;if(!X)return;const oe=D.getRemoteDeviceId();switch(ie){case"connected":y.aggregate("rtc-connect-time",new Date().getTime()-X,Object.assign({},oe?{deviceId:oe}:{}));break;case"failed":y.increment("rtc-connect-failed",Object.assign({},oe?{deviceId:oe}:{}))}})}getMetadata(D){return Ue(this,void 0,void 0,function*(){if(this.config.lanOnlyMode)throw new Error("getMetadata method cannot be called in local-only mode");const{getToken:H}=this.config,{grpcCallDeadline:X}=this,{hasDeadline:ie}=D,oe=ie===!1?void 0:new Date().getTime()+X;try{return{authorization:yield H(),deadline:oe}}catch(de){throw g.a.error("getToken() failed",{error:de}),new Error("Cannot get authorization token")}})}}var rt=n(10),ot=n(11),jt=function(pe,D,H,X){return new(H||(H=Promise))(function(ie,oe){function de(ce){try{be(X.next(ce))}catch(le){oe(le)}}function ye(ce){try{be(X.throw(ce))}catch(le){oe(le)}}function be(ce){var le;ce.done?ie(ce.value):(le=ce.value,le instanceof H?le:new H(function(Re){Re(le)})).then(de,ye)}be((X=X.apply(pe,D||[])).next())})};class pt{constructor(D,H){this.sessionId=D,this.connection=H,this.sentMessagesCounts=new Map,this.receivedMessagesCounts=new Map,this.sessionId=D,this.connection=H}incrementMessageSent(D){const H=Ie(D.header.stream);this.sentMessagesCounts.set(H,(this.sentMessagesCounts.get(H)||0)+1)}incrementMessageReceived(D){const H=Ie(D.header.stream);this.receivedMessagesCounts.set(H,(this.receivedMessagesCounts.get(H)||0)+1)}uploadMetrics(){return jt(this,void 0,void 0,function*(){const{sessionId:D}=this,H=yield this.connection.peerConnection.getStats(),X={};H.forEach(oe=>X[oe.id]=oe),g.a.debug("rtc-stats",Object.assign(Object.assign({},X),{sessionId:D}));const ie=[...new Set(Array.from(this.sentMessagesCounts.keys()).concat(Array.from(this.receivedMessagesCounts.keys())))].reduce((oe,de)=>{const ye=this.sentMessagesCounts.get(de),be=this.receivedMessagesCounts.get(de);return Object.assign(Object.assign({},oe),{[`${de}-sent`]:ye,[`${de}-received`]:be})},{sessionId:D});g.a.debug("rtc-message-report",ie)})}}function Ct(pe,D){return Ie(pe)===Ie(D)}var ut=function(pe,D,H,X){return new(H||(H=Promise))(function(ie,oe){function de(ce){try{be(X.next(ce))}catch(le){oe(le)}}function ye(ce){try{be(X.throw(ce))}catch(le){oe(le)}}function be(ce){var le;ce.done?ie(ce.value):(le=ce.value,le instanceof H?le:new H(function(Re){Re(le)})).then(de,ye)}be((X=X.apply(pe,D||[])).next())})};class Tt{constructor(D,H){this.peerConnection=D,this.config=H,this.connectTimeoutMs=10*c.a.second,this.gatherIceTimeoutMs=5*c.a.second,this.pingUpdateTimeoutMs=2*c.a.second,this.streamLatestTimestamp=new Map,this.closeCalled=!1,this.connectCalled=!1,this.sentOffer=!1,this.receivedIceCandidate=!1;const{isOffer:X}=H;X?this.initializeChannels(D):D.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 pt(this.getSessionId(),this)}connect(){return ut(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(()=>ut(this,void 0,void 0,function*(){this.isReady()||(g.a.warn("RTC connect timed out, closing connection"),yield this.close())}),this.connectTimeoutMs);const{peerConnection:D,config:{isOffer:H,sessionId:X}}=this;if(H){const ie=yield D.createOffer();yield D.setLocalDescription(ie)}H&&(this.gatherIceTimeout=setTimeout(()=>ut(this,void 0,void 0,function*(){this.sentOffer||(g.a.warn("ICE gathering timed out"),this.receivedIceCandidate?(g.a.warn("Attempting to connect with partial ICE candidate pool"),yield this.sendOffer()):yield this.close())}),this.gatherIceTimeoutMs),D.onicecandidate=ie=>ut(this,void 0,void 0,function*(){ie.candidate?this.receivedIceCandidate=!0:yield this.sendOffer()}),D.onicegatheringstatechange=()=>ut(this,void 0,void 0,function*(){D.iceGatheringState==="complete"&&(yield this.sendOffer())}),D.onnegotiationneeded=()=>{g.a.debug("Negotiation needed",{sessionId:X})})})}handleSignal(D){return ut(this,void 0,void 0,function*(){const{peerConnection:H,config:{sessionId:X,sendSignal:ie}}=this,{description:oe}=JSON.parse(D.payload);if(g.a.debug("Handling signal",{sessionId:X,description:JSON.stringify(oe)}),oe)if(H.signalingState!=="stable"||H.connectionState!=="connected")if(H.remoteDescription)g.a.warn(`Received SDP signal during negotiation when remote description is already set: ${JSON.stringify(D)}`);else if(oe.type==="offer"){yield H.setRemoteDescription(oe);const de=yield H.createAnswer();yield H.setLocalDescription(de),yield ie({payload:JSON.stringify({description:de})})}else oe.type==="answer"&&(yield H.setRemoteDescription(oe));else g.a.warn(`Received SDP signal when signaling is stable and connected: ${JSON.stringify(D)}`);else g.a.warn(`Received non-SDP signal: ${JSON.stringify(D)}`)})}send(D,H){const X=this.getChannelFromLabel(H.channelLabel);X?this.sendOnChannel(X,D):g.a.warn("Send called with unexpected channel label",{channelLabel:H.channelLabel})}controlRemoteStream(D){this.sendSystemMessage(p(this.reliableStreamChannel),{type:"stream-control",streamControl:D})}isActive(){return new Set(["new","connecting","connected"]).has(this.peerConnection.connectionState)}isReady(){const{peerConnection:D,latestTtlStreamChannel:H,reliableStreamChannel:X,latestTryOnceStreamChannel:ie}=this;return!!(X&&H&&ie)&&D.connectionState==="connected"&&X.readyState==="open"&&H.readyState==="open"&&ie.readyState==="open"}isClosed(){const{peerConnection:D,reliableStreamChannel:H,latestTryOnceStreamChannel:X,latestTtlStreamChannel:ie}=this;return!(D.connectionState!=="closed"||H!==void 0&&H.readyState!=="closed"||X!==void 0&&X.readyState!=="closed"||ie!==void 0&&ie.readyState!=="closed")}needsClosing(){const{peerConnection:D,latestTtlStreamChannel:H,reliableStreamChannel:X,latestTryOnceStreamChannel:ie}=this;if(this.isClosed())return!1;const oe=new Set(["closing","closed"]),de=ye=>ye&&oe.has(ye.readyState);return Ye(D)||de(H)||de(X)||de(ie)}close(){return ut(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(D){this.latestTtlStreamChannel=D.createDataChannel("stream.latest-ttl",k),this.reliableStreamChannel=D.createDataChannel("stream.reliable",J),this.latestReliableStreamChannel=D.createDataChannel("stream.latest-reliable",K),this.latestTryOnceStreamChannel=D.createDataChannel("stream.latest-try-once",re),this.setupChannel(this.latestTtlStreamChannel),this.setupChannel(this.reliableStreamChannel),this.setupChannel(this.latestReliableStreamChannel),this.setupChannel(this.latestTryOnceStreamChannel)}sendOffer(){return ut(this,void 0,void 0,function*(){if(this.sentOffer||(this.sentOffer=!0,Ye(this.peerConnection)))return;const{peerConnection:D,config:{sendSignal:H}}=this,X=yield D.createOffer();yield D.setLocalDescription(X);const ie={payload:JSON.stringify({description:X})};yield H(ie)})}getChannelFromLabel(D){switch(D){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(D,H){let X;try{X=Object(T.encode)(JSON.stringify(H))}catch(ie){return void g.a.warn("Failed to encode RTC message",{error:ie})}try{D.send(X),this.sessionMetrics.incrementMessageSent(H)}catch(ie){g.a.warn("Failed to send message to channel",{error:ie,channel:D.label})}}channelNotRecognized(D){return D!==this.latestTtlStreamChannel&&D!==this.latestReliableStreamChannel&&D!==this.latestTryOnceStreamChannel&&D!==this.reliableStreamChannel}setupChannel(D){D.onmessage=H=>{if(this.channelNotRecognized(D))return void g.a.warn("Received message on unrecognized data channel.");let X;try{X=JSON.parse(Object(T.decode)(H.data))}catch(ie){return void g.a.warn("Received unparseable RTC message",{error:ie,channel:D.label})}if(this.lastMessageTimestamp=new Date().getTime(),X=nt(X),this.sessionMetrics.incrementMessageReceived(X),!this.handleSystemMessage(D,X)){if(!this.hasCapabilities(X))return void g.a.warn("Received RTC message that was not within the capability scope of the connection.");(D===this.latestTryOnceStreamChannel||D===this.latestTtlStreamChannel||D===this.latestReliableStreamChannel)&&!this.isLatestMessage(X)||this.config.receive(this.config.remotePeer.id,X)}},D.onerror=H=>{g.a.warn(`Channel error: ${H.error}`,{error:H.error,sessionId:this.getSessionId(),channelLabel:D.label})},D.onopen=()=>{g.a.debug("Channel opened",{sessionId:this.getSessionId(),channelLabel:D.label})},D.onclose=()=>{const H={bufferedAmount:D.bufferedAmount,sessionId:this.getSessionId(),channelLabel:D.label};this.closeCalled===!1?g.a.debug("Unexpected channel closed",H):g.a.debug("Channel closed",H)}}handleSystemMessage(D,H){switch(H.header.stream.streamType){case"ping":return this.sendSystemMessage(D,{type:"pong",timestamp:p(H.payload.ping)}),!0;case"pong":{const X=new Date().getTime()-p(H.payload.pong);return this.pingTimeMs=X,y.aggregate("rtc-ping-time",X),!0}case"stream-control":return!0;default:return!1}}sendSystemMessage(D,H){if(D.readyState!=="open")return;const X={entityId:p(this.config.localPeer.deviceId||this.config.localPeer.userId),streamName:`$.${H.type}`,streamType:H.type};let ie;switch(H.type){case"ping":ie={ping:new Date().getTime()};break;case"pong":ie={pong:H.timestamp};break;case"stream-control":ie={streamControl:H.streamControl}}this.sendOnChannel(D,De(X,ie))}hasCapabilities(D){var H,X;const{localPeer:ie,remotePeer:oe}=this.config,de=(H=ie.capabilitySet.streaming)===null||H===void 0?void 0:H.streams,ye=de&&de.some(le=>le.receive&&Ct(le.stream,D.header.stream)),be=(X=oe.capabilitySet.streaming)===null||X===void 0?void 0:X.streams,ce=be&&be.some(le=>le.send&&Ct(le.stream,D.header.stream));return ye||ce}isLatestMessage(D){const H=Ie(D.header.stream),X=(this.streamLatestTimestamp.get(H)||0)<=D.header.created;return X&&this.streamLatestTimestamp.set(H,D.header.created),X}}var Fe=function(pe,D,H,X){return new(H||(H=Promise))(function(ie,oe){function de(ce){try{be(X.next(ce))}catch(le){oe(le)}}function ye(ce){try{be(X.throw(ce))}catch(le){oe(le)}}function be(ce){var le;ce.done?ie(ce.value):(le=ce.value,le instanceof H?le:new H(function(Re){Re(le)})).then(de,ye)}be((X=X.apply(pe,D||[])).next())})};class Rt{constructor(D){this.config=D,this.connections=[],this.connectingSessions=new Map,this.rtcInstancesConstructed=0,this.updateInterval=d({func:()=>Fe(this,void 0,void 0,function*(){try{yield this.update()}catch(H){g.a.warn("RTC update failed",{error:H})}}),delay:250*c.a.millisecond,immediate:!0}),this.localPeer=this.createPeer()}send(D,H,X){const ie=this.getActiveConnection(D);ie?ie.isReady()?ie.send(H,X):g.a.warn("Attempted to send with an active connection to that peer which was not yet ready."):g.a.warn("Attempted to send with no active connection to that peer.")}controlRemoteStream(D,H){const X=this.getActiveConnection(D);X?X.isReady()?X.controlRemoteStream(H):g.a.warn("Attempted to control remote stream with an active connection to that peer which was not yet ready."):g.a.warn("Attempted to control remote stream with no active connection to that peer.")}connect(D){return Fe(this,void 0,void 0,function*(){const H=yield this.getLocalPeer();if(this.getActiveConnection(D))return void g.a.warn("Attempted to connect to peer with an already active connection.");let X;try{X=yield this.config.signalingClient.createSession(yield this.config.getToken(),{offerPeerId:H.id,answerPeerId:D})}catch(ie){Object(ot.a)(ie,rt.a,oe=>oe.statusCode===404),g.a.warn("Attempted to connect to peer that does not exist.")}if(X)for(this.connectingSessions.set(X.id,new Date().getTime()),yield this.connectToSession(X);;)switch(yield Object(u.a)(.1),this.getConnectionStatus(D)){case"connecting":continue;case"connected":return X.id;case"disconnected":return}})}getConnectionStatus(D){const H=this.getActiveConnection(D);return H?H.isReady()?"connected":"connecting":"disconnected"}getIceMode(D){const H=this.getActiveConnection(D);if(H)return H.iceMode}disconnect(D){return Fe(this,void 0,void 0,function*(){const H=this.getActiveConnection(D);H&&(yield this.closeConnection(H))})}getLocalPeer(){return Fe(this,void 0,void 0,function*(){return yield this.localPeer})}getPeers(){return Fe(this,void 0,void 0,function*(){return yield this.config.signalingClient.getPeers(yield this.config.getToken())})}getPing(D){const H=this.getActiveConnection(D);if(H)return H.getPing();g.a.warn("Attempted to get ping time from inactive peer.")}getLastMessageTimestamp(D){const H=this.getActiveConnection(D);if(H)return H.getLastMessageTimestamp();g.a.warn("Attempted to get ping time from inactive peer.")}shutdown(){return Fe(this,void 0,void 0,function*(){yield this.updateInterval.stop();const D=this.connections;this.connections=[],yield this.closeConnections(D)})}closeConnection(D){return Fe(this,void 0,void 0,function*(){this.connectingSessions.delete(D.getSessionId()),yield D.close();try{yield this.config.signalingClient.deleteSession(yield this.config.getToken(),D.getSessionId())}catch(H){Object(ot.a)(H,rt.a,X=>X.statusCode===404)}})}getSessions(){return Fe(this,void 0,void 0,function*(){const D=yield this.getLocalPeer();return(yield this.config.signalingClient.getSessions(yield this.config.getToken())).filter(H=>H.offer.peer.id===D.id||H.answer.peer.id===D.id)})}createPeer(){return Fe(this,void 0,void 0,function*(){return yield this.config.signalingClient.createPeer(yield this.config.getToken(),{capabilitySet:this.config.capabilitySet||{}})})}createRTCPeerConnection(D={}){return Fe(this,void 0,void 0,function*(){const H=this.config.alternateRTCPeerConnection||RTCPeerConnection;this.rtcInstancesConstructed++,this.rtcInstancesConstructed%20||_t();try{return new H(Object.assign({iceServers:yield this.config.signalingClient.getIceServers(yield this.config.getToken())},D))}catch(X){throw g.a.debug(`Failed to create RTCPeerConnection: ${this.rtcInstancesConstructed} total allocated`),X}})}closeConnections(D){return Fe(this,void 0,void 0,function*(){const H=yield O(D.map(X=>Fe(this,void 0,void 0,function*(){yield this.closeConnection(X)})));for(const X of H)g.a.warn("Request to close session failed",{error:X})})}reset(){return Fe(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(D){return this.connections.find(H=>H.getRemotePeer().id===D&&H.isActive())}update(){return Fe(this,void 0,void 0,function*(){const D=yield this.getLocalPeer();try{yield this.config.signalingClient.refreshPeer(yield this.config.getToken(),D.id)}catch(H){Object(ot.a)(H,rt.a,X=>X.statusCode===404),g.a.warn("Peer expired, creating new peer",{peerId:D.id}),yield this.reset()}yield this.handleSessions(yield this.getSessions())})}handleSessions(D){return Fe(this,void 0,void 0,function*(){yield this.syncConnectionsAndSessions(D);const H=D.map(X=>({session:X,connection:this.connections.find(ie=>ie.getSessionId()===X.id)}));yield Promise.all(H.map(({session:X,connection:ie})=>Fe(this,void 0,void 0,function*(){return yield this.maintainConnection(X,ie)})))})}syncConnectionsAndSessions(D){return Fe(this,void 0,void 0,function*(){const H=new Set(D.map(oe=>oe.id)),X=oe=>H.has(oe.getSessionId())||this.connectingSessions.has(oe.getSessionId());this.connections=this.connections.filter(oe=>X(oe));const ie=this.connections.filter(oe=>!X(oe)||oe.needsClosing());yield Promise.all(ie.map(oe=>Fe(this,void 0,void 0,function*(){yield this.closeConnection(oe)})))})}maintainConnection(D,H){return Fe(this,void 0,void 0,function*(){const X=yield this.getLocalPeer(),ie=D.offer.peer.id===X.id;if(H){if(H.isReady())try{yield this.config.signalingClient.refreshSession(yield this.config.getToken(),D.id)}catch(oe){Object(ot.a)(oe,rt.a,de=>de.statusCode===404),g.a.debug("Refresh session not found",{sessionId:D.id})}else if(H.isActive())try{yield this.consumeSignals(H)}catch(oe){g.a.warn("Failed to ingest signals, closing connection",{error:oe}),yield this.closeConnection(H)}}else{if(ie)return;yield this.connectToSession(D)}})}connectToSession(D){return Fe(this,void 0,void 0,function*(){const H=yield this.getLocalPeer(),X=D.offer.peer.id===H.id,ie=yield this.createRTCPeerConnection(),oe=new Tt(ie,{localPeer:X?D.offer.peer:D.answer.peer,remotePeer:X?D.answer.peer:D.offer.peer,sessionId:D.id,isOffer:X,sendSignal:de=>this.sendSignal(D.id,de),receive:(de,ye)=>this.config.receive(de,ye)});if(this.connections.find(de=>de.getSessionId()===D.id))return g.a.warn("connectToSession called on a session that already has a connection.",{sessionId:D.id}),void(yield oe.close());this.setupHandlers(oe),this.connections.push(oe);try{yield oe.connect()}catch(de){g.a.warn("Failed to handle negotiation, closing connection",{error:de}),yield this.closeConnection(oe)}})}setupHandlers(D){const{peerConnection:H}=D,X=D.getSessionId();H.onconnectionstatechange=()=>Fe(this,void 0,void 0,function*(){const ie=this.connectingSessions.get(X);if(ie===void 0)return;const oe=H.connectionState;switch(Ye(H)&&this.connectingSessions.delete(X),oe){case"connected":{this.connectingSessions.delete(X);const de=new Date().getTime()-ie;y.aggregate("rtc-connect-time",de);break}case"failed":y.increment("rtc-connect-failed"),yield this.closeConnection(D)}})}consumeSignals(D){return Fe(this,void 0,void 0,function*(){let H=[];try{H=yield this.config.signalingClient.takeSignals(yield this.config.getToken(),D.getSessionId())}catch(X){Object(ot.a)(X,rt.a,ie=>ie.statusCode===404)}for(const X of H)yield D.handleSignal(X)})}sendSignal(D,H){return Fe(this,void 0,void 0,function*(){try{yield this.config.signalingClient.addSignals(yield this.config.getToken(),D,{signals:[H]})}catch(X){Object(ot.a)(X,rt.a,ie=>ie.statusCode===404)}})}}},function(e,t,n){var r={randomUUID:typeof crypto<"u"&&crypto.randomUUID&&crypto.randomUUID.bind(crypto)};let i;const s=new Uint8Array(16);function l(){if(!i&&(i=typeof crypto<"u"&&crypto.getRandomValues&&crypto.getRandomValues.bind(crypto),!i))throw new Error("crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported");return i(s)}const o=[];for(let u=0;u<256;++u)o.push((u+256).toString(16).slice(1));function c(u,f=0){return(o[u[f+0]]+o[u[f+1]]+o[u[f+2]]+o[u[f+3]]+"-"+o[u[f+4]]+o[u[f+5]]+"-"+o[u[f+6]]+o[u[f+7]]+"-"+o[u[f+8]]+o[u[f+9]]+"-"+o[u[f+10]]+o[u[f+11]]+o[u[f+12]]+o[u[f+13]]+o[u[f+14]]+o[u[f+15]]).toLowerCase()}t.a=function(u,f,E){if(r.randomUUID&&!f&&!u)return r.randomUUID();const w=(u=u||{}).random||(u.rng||l)();if(w[6]=15&w[6]|64,w[8]=63&w[8]|128,f){E=E||0;for(let h=0;h<16;++h)f[E+h]=w[h];return f}return c(w)}},,function(e,t,n){n.r(t),n.d(t,"LogClient",function(){return o});var r=n(28),i=n(11),s=n(10),l=function(c,u,f,E){return new(f||(f=Promise))(function(w,h){function g(j){try{R(E.next(j))}catch(F){h(F)}}function b(j){try{R(E.throw(j))}catch(F){h(F)}}function R(j){var F;j.done?w(j.value):(F=j.value,F instanceof f?F:new f(function(M){M(F)})).then(g,b)}R((E=E.apply(c,u||[])).next())})};class o extends r.a{log(u){return l(this,void 0,void 0,function*(){const f=o.token;try{yield this.fetch("logs",{token:f,method:"POST",body:JSON.stringify({logs:u}),allowUnsafeRetries:!0})}catch(E){Object(i.a)(E,s.a,w=>w.statusCode===401&&f!==void 0),o.token===f&&delete o.token,yield this.log(u)}})}}}])})})(dist);function defined(e,t){if(e!==void 0)return e;throw new Error(t||"Value is undefined")}let FORMANT_API_URL="https://api.formant.io";typeof window<"u"&&(FORMANT_API_URL=window.FORMANT_API_URL||FORMANT_API_URL);let urlParams$2=new URLSearchParams("");typeof window<"u"&&(urlParams$2=new URLSearchParams(window.location.search));const envDev=urlParams$2.get("formant_dev");envDev&&(FORMANT_API_URL="https://api-dev.formant.io");const envStage=urlParams$2.get("formant_stage");envStage&&(FORMANT_API_URL="https://api-stage.formant.io");const envLocal=urlParams$2.get("formant_local");envLocal&&(FORMANT_API_URL="https://api.formant.local");const millisecond=1,second=1e3,minute=60*second,hour=60*minute,day=24*hour,week=7*day,month=30*day,year=365*day,duration={millisecond,second,minute,hour,day,week,month,year};function filterDataByType(e,t){return e.filter(n=>t.includes(n.type))}function filterDataByTime(e,t,n){const r=t.getTime(),i=n.getTime();return e.map(s=>({...s,points:s.points.filter(([l])=>l>=r&&l<i)})).filter(({points:s})=>s.length>0)}function fork(e){}class StoreCache{constructor({capacity:t,timeout:n}={}){Ae(this,"entries",new Map);Ae(this,"metadata",new Map);Ae(this,"capacity");Ae(this,"timeout");this.capacity=t||1e4,this.timeout=n||duration.minute}get(t,n){const r=this.keyToCacheKey(t),i=this.entries.get(r),s=this.metadata.get(r);return(i===void 0||s&&(s==null?void 0:s.expiration.getTime())<Date.now())&&!(s!=null&&s.generating)&&n&&this.generate(t,n()),i===void 0&&s&&s.lastValue!==void 0?s.lastValue:i}set(t,n){const r=this.keyToCacheKey(t);this.metadata.set(r,{generating:!1,expiration:new Date(Date.now()+this.timeout),lastValue:n}),this.entries.set(r,n),this.metadata.size>this.capacity&&this.deleteOldestEntry()}clear(){this.entries.clear(),[...this.metadata.values()].forEach(t=>t.generating=!1)}clearKey(t){this.metadata.delete(t),this.entries.delete(t)}keyToCacheKey(t){return JSON.stringify(t)}deleteOldestEntry(){if(this.metadata.size<1)return;const[t]=[...this.metadata.entries()].reduce(([n,r],[i,s])=>s.expiration.getTime()<r.expiration.getTime()?[i,s]:[n,r]);this.clearKey(t)}generate(t,n){const r=this.keyToCacheKey(t),i=this.metadata.get(r)||{};this.metadata.set(r,{...i,generating:!0,expiration:new Date(Date.now()+this.timeout)}),setTimeout(()=>{n.then(s=>{const l=this.metadata.get(r);!(l!=null&&l.generating)||this.set(t,s)})},0)}}class QueryStore{constructor(){Ae(this,"queryStoreCache",new StoreCache({capacity:1e4,timeout:20*duration.second}));Ae(this,"liveQueryStoreCache",new StoreCache({capacity:1e4,timeout:200*duration.millisecond}))}moduleQuery(t,n,r,i,s,l=!1){const o={...t,names:[...n],types:[...r]},c=this.query(o,i,s,l);return c===void 0||c==="too much data"?c:filterDataByType(c,r)}query(t,n,r,i=!1){const s={...t,start:dateFns.startOfMinute(n).toISOString(),end:i?r.toISOString():dateFns.addMinutes(dateFns.roundToNearestMinutes(r),1).toISOString(),latestOnly:i},l=r>dateFns.addSeconds(new Date,-20);let o;return l?o=this.liveQueryCache(s):o=this.queryCache(s),!o||o==="too much data"||i?o:filterDataByTime(o,n,r)}queryCache(t){return this.queryStoreCache.get(t,async()=>{try{return await Fleet.queryTelemetry(t)}catch(n){throw n}})}liveQueryCache(t){return this.liveQueryStoreCache.get(t,async()=>{try{return await Fleet.queryTelemetry(t)}catch(n){throw n}})}}const queryStore=new QueryStore;class App{static sendAppMessage(t){window.parent.postMessage(t,"*")}static getCurrentModuleContext(){let t=new URLSearchParams("");return typeof window<"u"&&(t=new URLSearchParams(window.location.search)),t.get("module")}static async getCurrentModuleConfiguration(){let t=new URLSearchParams("");typeof window<"u"&&(t=new URLSearchParams(window.location.search));const n=t.get("configuration");return n===null||n.trim()===""?void 0:(await(await fetch(`${FORMANT_API_URL}/v1/admin/module-configurations/`+n,{headers:{"Content-Type":"application/json",Authorization:"Bearer "+Authentication.token}})).json()).configuration}static isModule(){return this.getCurrentModuleContext()!==null}static goToTime(t){this.sendAppMessage({type:"go_to_time",time:t.getTime()})}static goToDevice(t){this.sendAppMessage({type:"go_to_device",deviceId:t})}static showMessage(t){this.sendAppMessage({type:"show_message",message:t})}static requestModuleData(){const t=this.getCurrentModuleContext();if(!t)throw new Error("No module context");this.sendAppMessage({type:"request_module_data",module:t})}static setModuleDateTimeRange(t,n){const r=this.getCurrentModuleContext();if(!r)throw new Error("No module context");this.sendAppMessage({type:"set_module_data_time_range",module:r,before:t,after:n||0})}static refreshAuthToken(){const t=this.getCurrentModuleContext();if(!t)throw new Error("No module context");this.sendAppMessage({type:"refresh_auth_token",module:t})}static sendChannelData(t,n){const r=this.getCurrentModuleContext();if(!r)throw new Error("No module context");this.sendAppMessage({type:"send_channel_data",source:r,channel:t,data:n})}static setupModuleMenus(t){const n=this.getCurrentModuleContext();if(!n)throw new Error("No module context");this.sendAppMessage({type:"setup_module_menus",module:n,menus:t})}static addMenuListener(t){window.addEventListener("message",n=>{const r=n.data;r.type==="module_menu_item_clicked"&&t(r.menu)})}static addAccessTokenRefreshListener(t){window.addEventListener("message",n=>{const r=n.data;r.type==="auth_token"&&t(r.token)})}static addModuleDataListener(t){const n=this.getCurrentModuleContext();n&&this.sendAppMessage({type:"request_module_data",module:n}),window.addEventListener("message",r=>{const i=r.data;i.type==="module_data"&&t({streams:i.streams,time:i.time,queryRange:i.queryRange})})}static addStreamListener(t,n,r){const i=s=>{const l=s.data;if(l.type==="module_data"){const{start:o,end:c}=l.queryRange;r(queryStore.moduleQuery({},t,n,new Date(o),new Date(c),!1))}};return window.addEventListener("message",i),()=>window.removeEventListener("message",i)}static addModuleConfigurationListener(t){window.addEventListener("message",n=>{const r=n.data;r.type==="module_configuration"&&t(r)})}static addChannelDataListener(t,n){window.addEventListener("message",r=>{const i=r.data;i.type==="channel_data"&&i.channel===t&&n({source:i.source,data:i.data})})}static requestOverviewDevices(t){this.sendAppMessage({type:"request_devices"}),window.addEventListener("message",n=>{const r=n.data;t(r)})}static async prompt(t,n){return new Promise(r=>{const i=Math.random().toString();this.sendAppMessage({type:"prompt",promptId:i,schema:t,okText:n==null?void 0:n.okText,cancelText:n==null?void 0:n.cancelText});const s=l=>{const o=l.data;o.type==="prompt_response"&&o.promptId===i&&r(o.data),window.removeEventListener("message",s)};window.addEventListener("message",s)})}}const je=class{static async login(t,n){try{const r=await fetch(`${FORMANT_API_URL}/v1/admin/auth/login`,{method:"POST",body:JSON.stringify({email:t,password:n}),headers:{"Content-Type":"application/json"}}),i=await r.json();if(r.status!==200)throw new Error(i.message);return await je.loginWithToken(i.authentication.accessToken,i.authentication.refreshToken),i.authentication}catch(r){return je.waitingForAuth.forEach(i=>i(!1)),je.waitingForAuth=[],Promise.reject(r)}}static async loginWithToken(t,n){const r=JSON.parse(atob(t.split(".")[1]));try{let i;if(je.isShareToken=r["formant:claims"]&&r["formant:claims"].type=="share",r["formant:claims"]&&(je.currentOrganization=r["formant:claims"].organizationId),r["custom:organization_id"]&&(je.currentOrganization=r["custom:organization_id"]),je.isShareToken||(i=r.sub),r["formant:claims"]&&r["formant:claims"].userId&&(i=r["formant:claims"].userId),i){const s=await fetch(`${FORMANT_API_URL}/v1/admin/users/${i}`,{method:"GET",headers:{"Content-Type":"application/json",Authorization:"Bearer "+t}}),l=await s.json();if(s.status!==200)throw new Error(l.message);je.currentUser=l}je.token=t,je.waitingForAuth.forEach(s=>s(!0))}catch(i){console.error(i),je.waitingForAuth.forEach(s=>s(!1))}je.waitingForAuth=[],n&&(je.refreshToken=n,setInterval(async()=>{if(je.refreshToken){const s=await(await fetch(`${FORMANT_API_URL}/v1/admin/auth/refresh`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({refreshToken:je.refreshToken})})).json();je.token=s.authentication.accessToken}},1e3*60*60))}static isAuthenticated(){return je.token!==void 0}static getCurrentUser(){return je.currentUser}static async waitTilAuthenticated(){return je.token!==void 0?!0:new Promise(t=>{je.waitingForAuth.push(function(n){t(n)})})}static async listenForRefresh(){App.addAccessTokenRefreshListener(t=>{this.loginWithToken(t)}),setInterval(async()=>{App.refreshAuthToken()},1e3*60*60)}static async forgotPassword(t){await fetch(`${FORMANT_API_URL}/v1/admin/auth/forgot-password`,{method:"POST",body:JSON.stringify({email:t}),headers:{"Content-Type":"application/json"}})}static async confirmForgotPassword(t){return(await fetch(`${FORMANT_API_URL}/v1/admin/auth/confirm-forgot-password`,{method:"POST",body:JSON.stringify(t),headers:{"Content-Type":"application/json"}})).ok}static async respondToNewPasswordRequiredChallenge(t){return await(await fetch(`${FORMANT_API_URL}/v1/admin/auth/respond-to-new-password-required-challenge`,{method:"POST",body:JSON.stringify(t),headers:{"Content-Type":"application/json"}})).json()}static async loginWithGoogle(t){return await(await fetch(`${FORMANT_API_URL}/v1/admin/auth/login-google`,{method:"POST",body:JSON.stringify(t),headers:{"Content-Type":"application/json"}})).json()}static async refresh(t){const r=await(await fetch(`${FORMANT_API_URL}/v1/admin/auth/refresh`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({refreshToken:t})})).json();await je.loginWithToken(r.authentication.accessToken,t)}};let Authentication=je;Ae(Authentication,"token"),Ae(Authentication,"refreshToken"),Ae(Authentication,"currentUser"),Ae(Authentication,"currentOrganization"),Ae(Authentication,"isShareToken",!1),Ae(Authentication,"defaultDeviceId"),Ae(Authentication,"waitingForAuth",[]);function delay(e){return new Promise(t=>setTimeout(t,e))}class DataChannel{constructor(t){Ae(this,"ready",!1);Ae(this,"listeners",[]);Ae(this,"openListeners",[]);Ae(this,"closeListeners",[]);Ae(this,"errorListeners",[]);Ae(this,"binaryListeners",[]);Ae(this,"error");Ae(this,"decoder",new TextDecoder);this.dataChannel=t,this.dataChannel.binaryType="arraybuffer",this.dataChannel.onopen=()=>{this.ready=!0,this.openListeners.forEach(n=>n())},this.dataChannel.onclose=()=>{this.ready=!1,this.closeListeners.forEach(n=>n())},this.dataChannel.onerror=n=>{console.error(n),this.error="An error occurred in DataChannel",this.errorListeners.forEach(r=>r(n))},this.dataChannel.onmessage=n=>{this.listeners.forEach(r=>{const i=new Uint8Array(n.data),s=this.decoder.decode(i);r(s)}),this.binaryListeners.forEach(r=>{r(new Uint8Array(n.data))})}}addOpenListener(t){this.openListeners.push(t)}removeOpenListener(t){this.openListeners=this.openListeners.filter(n=>n!==t)}addCloseListener(t){this.closeListeners.push(t)}removeCloseListener(t){this.closeListeners=this.closeListeners.filter(n=>n!==t)}addErrorListener(t){this.errorListeners.push(t)}removeErrorListener(t){this.errorListeners=this.errorListeners.filter(n=>n!==t)}async waitTilReady(){return this.ready?!0:new Promise((n,r)=>{let i=window.setInterval(()=>{this.ready&&(window.clearInterval(i),n(!0)),this.error&&r(this.error)},10)})}send(t){if(!this.ready)throw new Error("Connection has been closed");this.dataChannel.send(t)}sendBinary(t){if(!this.ready)throw new Error("Connection has been closed");this.dataChannel.send(t)}addListener(t){this.listeners.push(t)}removeListener(t){const n=this.listeners.indexOf(t);if(n===-1)throw new Error("Could not find data channel listener to remove");if(this.error)throw new Error(this.error);this.listeners.splice(n,1)}addBinaryListener(t){this.binaryListeners.push(t)}removeBinaryListener(t){const n=this.binaryListeners.indexOf(t);if(n===-1)throw new Error("Could not find data channel listener to remove");if(this.error)throw new Error(this.error);this.binaryListeners.splice(n,1)}}class CaptureStream{constructor(t){Ae(this,"token");this.captureSession=t}async ingestJSON(t){if(!this.token){const r=await(await fetch(`${FORMANT_API_URL}/v1/admin/capture-sessions/${this.captureSession.code}/authenticate`,{method:"POST"})).json();this.token=r.token}await fetch(`${FORMANT_API_URL}/v1/ingest`,{method:"POST",body:JSON.stringify({deviceId:this.captureSession.deviceId,name:this.captureSession.streamName,type:"json",points:[[Date.now(),JSON.stringify(t)]]}),headers:{"Content-Type":"application/json",Authorization:"Bearer "+this.token}})}}class Manipulator{constructor(t,n){Ae(this,"currentListeners",[]);Ae(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){Ae(this,"channel");Ae(this,"requestIdToResponseMap",new Map);this.device=t,this.channel_name=n,this.timeout=r}addOpenListener(t){defined(this.channel,"channel not initalized").addOpenListener(t)}removeOpenListener(t){defined(this.channel,"channel not initalized").removeOpenListener(t)}addCloseListener(t){defined(this.channel,"channel not initalized").addCloseListener(t)}removeCloseListener(t){defined(this.channel,"channel not initalized").removeCloseListener(t)}addErrorListener(t){defined(this.channel,"channel not initalized").addErrorListener(t)}removeErrorListener(t){defined(this.channel,"channel not initalized").removeErrorListener(t)}}class BinaryRequestDataChannel extends RequestDataChannel{constructor(){super(...arguments);Ae(this,"RESPONSE_SUCCESS_BYTE",0);Ae(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 i=n.slice(0,16).toString();if(i.length===0)throw new Error("Invalid response");const s=n.slice(16);if(s.length===0)throw new Error("Invalid response");this.requestIdToResponseMap.has(i)&&this.requestIdToResponseMap.set(i,s)})}async request(n){if(this.channel||await this.initialize(),!this.channel)throw new Error("Failed to create channel");const{channel:r,requestIdToResponseMap:i,timeout:s}=this;await r.waitTilReady();const l=this.generateBinaryId(),o=l.toString();i.set(o,!0),r.sendBinary(new Uint8Array([...l,...n]));const c=new Date().getTime();for(;new Date().getTime()<c+s;)if(await delay(50),i.has(o)){const u=i.get(o);if(u!==!0){i.delete(o);const f=u[0]===this.RESPONSE_SUCCESS_BYTE,E=u.slice(1);if(f)return E;throw console.error({name:"AdapterError",message:this.decoder.decode(E)}),new Error("Binary request datachannel adapter error")}}throw i.delete(o),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:i,error:s}=n;if(!r)throw new Error("Invalid response");if(!i&&!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:i}=this;await n.waitTilReady();const s=this.generateTextId();r.set(s,!0),n.send(JSON.stringify({id:s,data:t}));const l=new Date().getTime();for(;new Date().getTime()<l+i;)if(await delay(50),r.has(s)){const o=r.get(s);if(o!==!0){r.delete(s);const{data:c,error:u}=o;if(c)return c;if(u)throw console.error({name:"AdapterError",message:u}),new Error("Text request datachannel adapter error")}}throw r.delete(s),console.error({name:"TimeoutError",message:`Request timed out after ${i/1e3} seconds`}),new Error("Text request datachannel request timed out")}}var domain;function EventHandlers(){}EventHandlers.prototype=Object.create(null);function EventEmitter(){EventEmitter.init.call(this)}EventEmitter.EventEmitter=EventEmitter,EventEmitter.usingDomains=!1,EventEmitter.prototype.domain=void 0,EventEmitter.prototype._events=void 0,EventEmitter.prototype._maxListeners=void 0,EventEmitter.defaultMaxListeners=10,EventEmitter.init=function(){this.domain=null,EventEmitter.usingDomains&&domain.active,(!this._events||this._events===Object.getPrototypeOf(this)._events)&&(this._events=new EventHandlers,this._eventsCount=0),this._maxListeners=this._maxListeners||void 0},EventEmitter.prototype.setMaxListeners=function e(t){if(typeof t!="number"||t<0||isNaN(t))throw new TypeError('"n" argument must be a positive number');return this._maxListeners=t,this};function $getMaxListeners(e){return e._maxListeners===void 0?EventEmitter.defaultMaxListeners:e._maxListeners}EventEmitter.prototype.getMaxListeners=function e(){return $getMaxListeners(this)};function emitNone(e,t,n){if(t)e.call(n);else for(var r=e.length,i=arrayClone(e,r),s=0;s<r;++s)i[s].call(n)}function emitOne(e,t,n,r){if(t)e.call(n,r);else for(var i=e.length,s=arrayClone(e,i),l=0;l<i;++l)s[l].call(n,r)}function emitTwo(e,t,n,r,i){if(t)e.call(n,r,i);else for(var s=e.length,l=arrayClone(e,s),o=0;o<s;++o)l[o].call(n,r,i)}function emitThree(e,t,n,r,i,s){if(t)e.call(n,r,i,s);else for(var l=e.length,o=arrayClone(e,l),c=0;c<l;++c)o[c].call(n,r,i,s)}function emitMany(e,t,n,r){if(t)e.apply(n,r);else for(var i=e.length,s=arrayClone(e,i),l=0;l<i;++l)s[l].apply(n,r)}EventEmitter.prototype.emit=function e(t){var n,r,i,s,l,o,c,u=t==="error";if(o=this._events,o)u=u&&o.error==null;else if(!u)return!1;if(c=this.domain,u){if(n=arguments[1],c)n||(n=new Error('Uncaught, unspecified "error" event')),n.domainEmitter=this,n.domain=c,n.domainThrown=!1,c.emit("error",n);else{if(n instanceof Error)throw n;var f=new Error('Uncaught, unspecified "error" event. ('+n+")");throw f.context=n,f}return!1}if(r=o[t],!r)return!1;var E=typeof r=="function";switch(i=arguments.length,i){case 1:emitNone(r,E,this);break;case 2:emitOne(r,E,this,arguments[1]);break;case 3:emitTwo(r,E,this,arguments[1],arguments[2]);break;case 4:emitThree(r,E,this,arguments[1],arguments[2],arguments[3]);break;default:for(s=new Array(i-1),l=1;l<i;l++)s[l-1]=arguments[l];emitMany(r,E,this,s)}return!0};function _addListener(e,t,n,r){var i,s,l;if(typeof n!="function")throw new TypeError('"listener" argument must be a function');if(s=e._events,s?(s.newListener&&(e.emit("newListener",t,n.listener?n.listener:n),s=e._events),l=s[t]):(s=e._events=new EventHandlers,e._eventsCount=0),!l)l=s[t]=n,++e._eventsCount;else if(typeof l=="function"?l=s[t]=r?[n,l]:[l,n]:r?l.unshift(n):l.push(n),!l.warned&&(i=$getMaxListeners(e),i&&i>0&&l.length>i)){l.warned=!0;var o=new Error("Possible EventEmitter memory leak detected. "+l.length+" "+t+" listeners added. Use emitter.setMaxListeners() to increase limit");o.name="MaxListenersExceededWarning",o.emitter=e,o.type=t,o.count=l.length,emitWarning(o)}return e}function emitWarning(e){typeof console.warn=="function"?console.warn(e):console.log(e)}EventEmitter.prototype.addListener=function e(t,n){return _addListener(this,t,n,!1)},EventEmitter.prototype.on=EventEmitter.prototype.addListener,EventEmitter.prototype.prependListener=function e(t,n){return _addListener(this,t,n,!0)};function _onceWrap(e,t,n){var r=!1;function i(){e.removeListener(t,i),r||(r=!0,n.apply(e,arguments))}return i.listener=n,i}EventEmitter.prototype.once=function e(t,n){if(typeof n!="function")throw new TypeError('"listener" argument must be a function');return this.on(t,_onceWrap(this,t,n)),this},EventEmitter.prototype.prependOnceListener=function e(t,n){if(typeof n!="function")throw new TypeError('"listener" argument must be a function');return this.prependListener(t,_onceWrap(this,t,n)),this},EventEmitter.prototype.removeListener=function e(t,n){var r,i,s,l,o;if(typeof n!="function")throw new TypeError('"listener" argument must be a function');if(i=this._events,!i)return this;if(r=i[t],!r)return this;if(r===n||r.listener&&r.listener===n)--this._eventsCount===0?this._events=new EventHandlers:(delete i[t],i.removeListener&&this.emit("removeListener",t,r.listener||n));else if(typeof r!="function"){for(s=-1,l=r.length;l-- >0;)if(r[l]===n||r[l].listener&&r[l].listener===n){o=r[l].listener,s=l;break}if(s<0)return this;if(r.length===1){if(r[0]=void 0,--this._eventsCount===0)return this._events=new EventHandlers,this;delete i[t]}else spliceOne(r,s);i.removeListener&&this.emit("removeListener",t,o||n)}return this},EventEmitter.prototype.removeAllListeners=function e(t){var n,r;if(r=this._events,!r)return this;if(!r.removeListener)return arguments.length===0?(this._events=new EventHandlers,this._eventsCount=0):r[t]&&(--this._eventsCount===0?this._events=new EventHandlers:delete r[t]),this;if(arguments.length===0){for(var i=Object.keys(r),s=0,l;s<i.length;++s)l=i[s],l!=="removeListener"&&this.removeAllListeners(l);return this.removeAllListeners("removeListener"),this._events=new EventHandlers,this._eventsCount=0,this}if(n=r[t],typeof n=="function")this.removeListener(t,n);else if(n)do this.removeListener(t,n[n.length-1]);while(n[0]);return this},EventEmitter.prototype.listeners=function e(t){var n,r,i=this._events;return i?(n=i[t],n?typeof n=="function"?r=[n.listener||n]:r=unwrapListeners(n):r=[]):r=[],r},EventEmitter.listenerCount=function(e,t){return typeof e.listenerCount=="function"?e.listenerCount(t):listenerCount$1.call(e,t)},EventEmitter.prototype.listenerCount=listenerCount$1;function listenerCount$1(e){var t=this._events;if(t){var n=t[e];if(typeof n=="function")return 1;if(n)return n.length}return 0}EventEmitter.prototype.eventNames=function e(){return this._eventsCount>0?Reflect.ownKeys(this._events):[]};function spliceOne(e,t){for(var n=t,r=n+1,i=e.length;r<i;n+=1,r+=1)e[n]=e[r];e.pop()}function arrayClone(e,t){for(var n=new Array(t);t--;)n[t]=e[t];return n}function unwrapListeners(e){for(var t=new Array(e.length),n=0;n<t.length;++n)t[n]=e[n].listener||e[n];return t}const urlParams$1=new URLSearchParams(window.location.search),rtcClientVersion=urlParams$1.get("rtc_client"),SessionType={Teleop:1,Observe:3};class Device extends EventEmitter{constructor(n,r,i){super();Ae(this,"rtcClient");Ae(this,"remoteDevicePeerId");Ae(this,"realtimeListeners",[]);Ae(this,"connectionMonitorInterval");Ae(this,"handleMessage",(n,r)=>{this.realtimeListeners.forEach(i=>i(n,r))});this.id=n,this.name=r,this.organizationId=i}async getLatestTelemetry(){return(await(await fetch(`${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(){let n=await fetch(`${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 i=r.state.reportedConfiguration.version;return n=await fetch(`${FORMANT_API_URL}/v1/admin/devices/${this.id}/configurations/${i}`,{method:"GET",headers:{"Content-Type":"application/json",Authorization:"Bearer "+Authentication.token}}),(await n.json()).document}async getFileUrl(n){return(await(await fetch(`${FORMANT_API_URL}/v1/admin/files/query`,{method:"POST",body:JSON.stringify({fileIds:[n]}),headers:{"Content-Type":"application/json",Authorization:"Bearer "+Authentication.token}})).json()).fileUrls}getRealtimeStatus(){if(this.rtcClient&&this.remoteDevicePeerId)return this.rtcClient.getConnectionStatus(this.remoteDevicePeerId);throw new Error(`Realtime connection hasn't been started for ${this.id}`)}getRealtimePing(){if(this.rtcClient&&this.remoteDevicePeerId)return this.rtcClient.getPing(this.remoteDevicePeerId);throw new Error(`Realtime connection hasn't been started for ${this.id}`)}async startRealtimeConnection(n){if(this.rtcClient)throw new Error(`Already created realtime connection to device ${this.id}`);{let r;if(rtcClientVersion==="1"?r=new distExports.RtcClientV1({signalingClient:new distExports.RtcSignalingClient(FORMANT_API_URL+"/v1/signaling"),getToken:async()=>defined(Authentication.token,"Realtime when user isn't authorized"),receive:this.handleMessage}):r=new distExports.RtcClient({signalingClient:new distExports.SignalingPromiseClient(FORMANT_API_URL,null,null),getToken:async()=>defined(Authentication.token,"Realtime when user isn't authorized"),receive:this.handleMessage,sessionType:n}),r.isReady)for(;!r.isReady();)await delay(100);const s=(await r.getPeers()).find(l=>l.deviceId===this.id);if(!s)throw new Error("Cannot find peer, is the robot offline?");for(this.remoteDevicePeerId=s.id,await r.connect(this.remoteDevicePeerId);r.getConnectionStatus(this.remoteDevicePeerId)!=="connected";)await delay(100);this.rtcClient=r,this.emit("connect"),this.initConnectionMonitoring()}}initConnectionMonitoring(){this.connectionMonitorInterval=setInterval(()=>{(!this.rtcClient||!this.remoteDevicePeerId||this.rtcClient.getConnectionStatus(this.remoteDevicePeerId)!=="connected")&&(this.emit("disconnect"),this.stopRealtimeConnection().catch(n=>{console.error(n)}))},1e3)}stopConnectionMonitoring(){clearInterval(this.connectionMonitorInterval),this.connectionMonitorInterval=void 0}async sendRealtimeMessage(n,r={channelLabel:"stream.reliable"}){const i=defined(this.rtcClient,"Realtime connection has not been started"),s=await this.getRemotePeer();i.send(defined(s).id,n,r)}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 getRealtimeAudioStreams(){var i,s,l;const n=await this.getConfiguration(),r=[];for(const o of((i=n.teleop)==null?void 0:i.hardwareStreams)??[])o.rtcStreamType==="audio-chunk"&&r.push({name:o.name});for(const o of((s=n.teleop)==null?void 0:s.rosStreams)??[])o.topicType=="audio_common_msgs/AudioData"&&r.push({name:o.topicName});for(const o of((l=n.teleop)==null?void 0:l.customStreams)??[])o.rtcStreamType==="audio-chunk"&&r.push({name:o.name});return r}async getRealtimeVideoStreams(){var i,s,l;const n=await this.getConfiguration(),r=[];for(const o of((i=n.teleop)==null?void 0:i.hardwareStreams)??[])o.rtcStreamType==="h264-video-frame"&&r.push({name:o.name});for(const o of((s=n.teleop)==null?void 0:s.rosStreams)??[])o.topicType=="formant/H264VideoFrame"&&r.push({name:o.topicName}),(o.topicType==="sensor_msgs/Image"||o.topicType==="sensor_msgs/CompressedImage")&&o.encodeVideo&&r.push({name:o.topicName});for(const o of((l=n.teleop)==null?void 0:l.customStreams)??[])o.rtcStreamType==="h264-video-frame"&&r.push({name:o.name});return r}async getRealtimeManipulators(){const n=await this.getConfiguration(),r=[];for(const i of n.teleop.rosStreams??[])i.topicType=="sensor_msgs/JointState"&&r.push(new Manipulator(this,{currentJointStateStream:{name:i.topicName},plannedJointStateStream:i.plannedTopic?{name:i.plannedTopic}:void 0,planValidStream:i.planValidTopic?{name:i.planValidTopic}:void 0,endEffectorStream:i.endEffectorTopic?{name:i.endEffectorTopic}:void 0,endEffectorLinkName:i.endEffectorLinkName,baseReferenceFrame:i.baseReferenceFrame,localFrame:i.localFrame}));return r}async startListeningToRealtimeVideo(n){const r=defined(this.rtcClient,"Realtime connection has not been started"),i=await this.getRemotePeer();r.controlRemoteStream(defined(i).id,{streamName:n.name,enable:!0,pipeline:"rtc"})}async stopListeningToRealtimeVideo(n){const r=defined(this.rtcClient,"Realtime connection has not been started"),i=await this.getRemotePeer();r.controlRemoteStream(defined(i).id,{streamName:n.name,enable:!1,pipeline:"rtc"})}async startListeningToRealtimeDataStream(n){const r=defined(this.rtcClient,"Realtime connection has not been started"),i=await this.getRemotePeer();r.controlRemoteStream(defined(i).id,{streamName:n.name,enable:!0,pipeline:"rtc"})}async stopListeningToRealtimeDataStream(n){const r=defined(this.rtcClient,"Realtime connection has not been started"),i=await this.getRemotePeer();r.controlRemoteStream(defined(i).id,{streamName:n.name,enable:!1,pipeline:"rtc"})}async enableRealtimeTelemetryPriorityIngestion(n){const r=defined(this.rtcClient,"Realtime connection has not been started"),i=await this.getRemotePeer();r.controlRemoteStream(defined(i).id,{streamName:n,enablePriorityUpload:!0,pipeline:"telemetry"})}async changeStreamAudioType(n,r){const i=defined(this.rtcClient,"Realtime connection has not been started"),s=await this.getRemotePeer();i.controlRemoteStream(defined(s).id,{streamName:n,setAudioFormat:r})}async disableRealtimeTelemetryPriorityIngestion(n){const r=defined(this.rtcClient,"Realtime connection has not been started"),i=await this.getRemotePeer();r.controlRemoteStream(defined(i).id,{streamName:n,enablePriorityUpload:!1,pipeline:"telemetry"})}async getRemotePeer(){const r=(await defined(this.rtcClient,"Realtime connection has not been started").getPeers()).find(i=>i.deviceId===this.id);return defined(r,"Could not find remote peer for device "+this.id)}async stopRealtimeConnection(){if(this.rtcClient)this.stopConnectionMonitoring(),await this.rtcClient.disconnect(this.id),this.rtcClient=void 0;else throw new Error(`Realtime connection hasn't been started for ${this.id}`)}async isInRealtimeSession(){let n=await Fleet.getPeers(),r=await Fleet.getRealtimeSessions(),i=n.find(s=>s.deviceId===this.id);return i?r[i.id].length>0:!1}async getAvailableCommands(){return(await(await fetch(`${FORMANT_API_URL}/v1/admin/command-templates/`,{method:"GET",headers:{"Content-Type":"application/json",Authorization:"Bearer "+Authentication.token}})).json()).items.map(i=>({name:i.name,id:i.id,command:i.command,description:i.description,parameterEnabled:i.parameterEnabled,parameterValue:i.parameterValue,parameterMeta:i.parameterMeta,enabled:i.enabled}))}async sendCommand(n,r,i,s){var f;const o=(await this.getAvailableCommands()).find(E=>E.name===n);if(!o)throw new Error(`Could not find command with name "${n}"`);let c="";r===void 0?o.parameterEnabled&&o.parameterValue&&(c=o.parameterValue):c=r;let u={value:c,scrubberTime:(i||new Date).toISOString(),meta:{...o.parameterMeta,...s}};await fetch(`${FORMANT_API_URL}/v1/admin/commands`,{method:"POST",body:JSON.stringify({commandTemplateId:o.id,organizationId:this.organizationId,deviceId:this.id,command:o.command,parameter:u,userId:(f=Authentication.currentUser)==null?void 0:f.id}),headers:{"Content-Type":"application/json",Authorization:"Bearer "+Authentication.token}})}async createCustomDataChannel(n,r){if(rtcClientVersion==="1")throw new Error("createCustomDataChannel is not supported in rtcClientVersion 1");const i=defined(this.rtcClient,"Realtime connection has not been started"),s=await this.getRemotePeer(),l=await new Promise(o=>{i.createCustomDataChannel(defined(s).id,n,{ordered:!0,...r},!1,(c,u)=>{const f=new DataChannel(u);o(f)})});return await l.waitTilReady(),l}createCustomRequestDataChannel(n,r=3e3){return new TextRequestDataChannel(this,n,r)}createCustomBinaryRequestDataChannel(n,r=3e3){return new BinaryRequestDataChannel(this,n,r)}async createCaptureStream(n){const i=await(await fetch(`${FORMANT_API_URL}/v1/admin/capture-sessions`,{method:"POST",body:JSON.stringify({deviceId:this.id,streamName:n,tags:{}}),headers:{"Content-Type":"application/json",Authorization:"Bearer "+Authentication.token}})).json();return new CaptureStream(i)}async getTelemetry(n,r,i,s){return await Fleet.getTelemetry(this.id,n,r,i,s)}async getTelemetryStreams(){var c,u;const n=await this.getConfiguration(),r=await fetch(`${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}}),i=[],s=[];return(u=(c=n.telemetry)==null?void 0:c.streams)==null||u.forEach(f=>{f.disabled!==!0&&i.push(f.name),f.onDemand===!0&&s.push(f.name)}),console.log(s),(await r.json()).items.filter(f=>!i.includes(f)).map(f=>({name:f,onDemand:s.includes(f)}))}async createInterventionRequest(n,r,i,s){return await(await fetch(`${FORMANT_API_URL}/v1/admin/intervention-requests`,{method:"POST",body:JSON.stringify({message:n,interventionType:r,time:new Date().toISOString(),deviceId:this.id,tags:s,data:i}),headers:{"Content-Type":"application/json",Authorization:"Bearer "+Authentication.token}})).json()}async addInterventionResponse(n,r,i){return await(await fetch(`${FORMANT_API_URL}/v1/admin/intervention-responses`,{method:"POST",body:JSON.stringify({interventionId:n,interventionType:r,data:i}),headers:{"Content-Type":"application/json",Authorization:"Bearer "+Authentication.token}})).json()}async getAnnotationCount(n,r){return await Fleet.getAnnotationCount({...n,deviceIds:[this.id]},r)}async getAnnotationCountByIntervals(n,r,i){return await Fleet.getAnnotationCountByIntervals({...n,deviceIds:[this.id]},r,i)}async eventsCounter(n,r,i,s,l){return await Fleet.eventsCounter(n,r,i,s,{...l,deviceIds:[this.id]})}async createShareLink(n,r){return n.scope.deviceIds=[this.id],await Fleet.createShareLink(n,r)}}class PeerDevice{constructor(t){Ae(this,"rtcClient");Ae(this,"remoteDevicePeerId");Ae(this,"realtimeListeners",[]);Ae(this,"id");Ae(this,"handleMessage",(t,n)=>{this.realtimeListeners.forEach(r=>r(t,n))});this.peerUrl=t}async getLatestTelemetry(){const n=await(await fetch(`${this.peerUrl}/telemetry`)).json();return Object.entries(n).map(([i,s])=>({deviceId:this.id,streamName:i,streamType:"json",currentValue:s,currentValueTime:s.timestamp,tags:{}}))}async getDeviceId(){return(await(await fetch(`${this.peerUrl}/configuration`)).json()).agent_config.id}async getConfiguration(){return(await(await fetch(`${this.peerUrl}/configuration`)).json()).agent_config.document}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")}async startRealtimeConnection(t){if(this.rtcClient)throw new Error(`Already created realtime connection to device ${this.id}`);{const n=new distExports.RtcClient({lanOnlyMode:!0,receive:this.handleMessage,sessionType:t});for(await n.connectLan(this.peerUrl);n.getConnectionStatus(this.peerUrl)!=="connected";)await delay(100);this.rtcClient=n}}addRealtimeListener(t){this.realtimeListeners.push(t)}removeRealtimeListener(t){const n=this.realtimeListeners.indexOf(t);if(n===-1)throw new Error("Could not find realtime listener to remove");this.realtimeListeners.splice(n,1)}async getRealtimeVideoStreams(){const t=await this.getConfiguration(),n=[];for(const r of t.teleop.hardwareStreams??[])r.rtcStreamType==="h264-video-frame"&&n.push({name:r.name});for(const r of t.teleop.rosStreams??[])r.topicType=="formant/H264VideoFrame"&&n.push({name:r.topicName}),(r.topicType==="sensor_msgs/Image"||r.topicType==="sensor_msgs/CompressedImage")&&r.encodeVideo&&n.push({name:r.topicName});for(const r of t.teleop.customStreams??[])r.rtcStreamType==="h264-video-frame"&&n.push({name:r.name});return n}async getRealtimeManipulators(){const t=await this.getConfiguration(),n=[];for(const r of t.teleop.rosStreams??[])r.topicType=="sensor_msgs/JointState"&&n.push(new Manipulator(this,{currentJointStateStream:{name:r.topicName},plannedJointStateStream:r.plannedTopic?{name:r.plannedTopic}:void 0,planValidStream:r.planValidTopic?{name:r.planValidTopic}:void 0,endEffectorStream:r.endEffectorTopic?{name:r.endEffectorTopic}:void 0,endEffectorLinkName:r.endEffectorLinkName,baseReferenceFrame:r.baseReferenceFrame,localFrame:r.localFrame}));return n}async startListeningToRealtimeVideo(t){const n=defined(this.rtcClient,"Realtime connection has not been started"),r=await this.getRemotePeer();n.controlRemoteStream(defined(r).id,{streamName:t.name,enable:!0,pipeline:"rtc"})}async stopListeningToRealtimeVideo(t){const n=defined(this.rtcClient,"Realtime connection has not been started"),r=await this.getRemotePeer();n.controlRemoteStream(defined(r).id,{streamName:t.name,enable:!1,pipeline:"rtc"})}async startListeningToRealtimeDataStream(t){const n=defined(this.rtcClient,"Realtime connection has not been started"),r=await this.getRemotePeer();n.controlRemoteStream(defined(r).id,{streamName:t.name,enable:!0,pipeline:"rtc"})}async stopListeningToRealtimeDataStream(t){const n=defined(this.rtcClient,"Realtime connection has not been started"),r=await this.getRemotePeer();n.controlRemoteStream(defined(r).id,{streamName:t.name,enable:!1,pipeline:"rtc"})}async enableRealtimeTelemetryPriorityIngestion(t){const n=defined(this.rtcClient,"Realtime connection has not been started"),r=await this.getRemotePeer();n.controlRemoteStream(defined(r).id,{streamName:t,enablePriorityUpload:!0,pipeline:"telemetry"})}async disableRealtimeTelemetryPriorityIngestion(t){const n=defined(this.rtcClient,"Realtime connection has not been started"),r=await this.getRemotePeer();n.controlRemoteStream(defined(r).id,{streamName:t,enablePriorityUpload:!1,pipeline:"telemetry"})}async getRemotePeer(){return{id:this.peerUrl,organizationId:"",deviceId:this.id,capabilities:[],capabilitySet:{}}}async stopRealtimeConnection(){if(this.rtcClient)await this.rtcClient.disconnect(this.id);else throw new Error(`Realtime connection hasn't been started for ${this.id}`)}async createCustomDataChannel(t,n){const r=defined(this.rtcClient,"Realtime connection has not been started"),i=await this.getRemotePeer(),s=await new Promise(l=>{r.createCustomDataChannel(defined(i).id,t,{ordered:!0,...n},!1,(o,c)=>{const u=new DataChannel(c);l(u)})});return await s.waitTilReady(),s}createCustomRequestDataChannel(t,n=3e3){return new TextRequestDataChannel(this,t,n)}createCustomBinaryRequestDataChannel(t,n=3e3){return new BinaryRequestDataChannel(this,t,n)}}const Ge=class{static async setDefaultDevice(t){Ge.defaultDeviceId=t}static async getCurrentDevice(){if(!Authentication.token)throw new Error("Not authenticated");if(!Ge.defaultDeviceId)throw new Error("No known default device");const i=(await(await fetch(`${FORMANT_API_URL}/v1/admin/device-details/query`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:"Bearer "+Authentication.token}})).json()).items.find(l=>l.id===Ge.defaultDeviceId).name,s=new Device(Ge.defaultDeviceId,i,defined(Authentication.currentOrganization));return Ge.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){if(!Authentication.token)throw new Error("Not authenticated");const r=await(await fetch(`${FORMANT_API_URL}/v1/admin/devices/${t}`,{method:"GET",headers:{"Content-Type":"application/json",Authorization:"Bearer "+Authentication.token}})).json(),i=r.name,s=new Device(t,i,r.organizationId);return Ge.knownContext.push(new WeakRef(s)),s}static async getDevices(){if(!Authentication.token)throw new Error("Not authenticated");const n=await(await fetch(`${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 n.items,n.items.map(r=>new Device(r.id,r.name,r.organizationId))}static async queryDevices(t){if(!Authentication.token)throw new Error("Not authenticated");return(await(await fetch(`${FORMANT_API_URL}/v1/admin/devices/query`,{method:"POST",body:JSON.stringify(t),headers:{"Content-Type":"application/json",Authorization:"Bearer "+Authentication.token}})).json()).items.map(i=>new Device(i.id,i.name,i.organizationId))}static async getOnlineDevices(){if(!Authentication.token)throw new Error("Not authenticated");const r=(await(await fetch(`${FORMANT_API_URL}/v1/queries/online-devices`,{method:"GET",headers:{"Content-Type":"application/json",Authorization:"Bearer "+Authentication.token}})).json()).items;return(await Ge.getDevices()).filter(s=>r.includes(s.id))}static async getPeers(){if(!Authentication.token)throw new Error("Not authenticated");return await new distExports.RtcClient({signalingClient:new distExports.SignalingPromiseClient(FORMANT_API_URL,null,null),getToken:async()=>defined(Authentication.token,"Realtime when user isn't authorized"),receive:()=>{}}).getPeers()}static async getRealtimeSessions(){if(!Authentication.token)throw new Error("Not authenticated");return await new distExports.RtcClient({signalingClient:new distExports.SignalingPromiseClient(FORMANT_API_URL,null,null),getToken:async()=>defined(Authentication.token,"Realtime when user isn't authorized"),receive:()=>{}}).getSessions()}static async getRealtimeDevices(){if(!Authentication.token)throw new Error("Not authenticated");const r=(await(await fetch(`${FORMANT_API_URL}/v1/signaling/peers`,{method:"GET",headers:{"Content-Type":"application/json",Authorization:"Bearer "+Authentication.token}})).json()).items.map(s=>s.deviceId);return(await Ge.getDevices()).filter(s=>r.includes(s.id))}static async getLatestTelemetry(t){let n=t;return t&&!Array.isArray(t)&&(t=[t]),(await(await fetch(`${FORMANT_API_URL}/v1/queries/stream-current-value`,{method:"POST",body:JSON.stringify({deviceIds:n}),headers:{"Content-Type":"application/json",Authorization:"Bearer "+Authentication.token}})).json()).items}static async getTelemetry(t,n,r,i,s){let l=t;Array.isArray(t)||(l=[t]);let o=n;return Array.isArray(n)||(o=[n]),(await(await fetch(`${FORMANT_API_URL}/v1/queries/queries`,{method:"POST",body:JSON.stringify({deviceIds:l,end:i.toISOString(),names:o,start:r.toISOString(),tags:s}),headers:{"Content-Type":"application/json",Authorization:"Bearer "+Authentication.token}})).json()).items}static async getFileUrl(t){const r=await(await fetch(`${FORMANT_API_URL}/v1/admin/files/query`,{method:"POST",body:JSON.stringify({fileIds:[t]}),headers:{"Content-Type":"application/json",Authorization:"Bearer "+Authentication.token}})).json();if(r.fileUrls.length===0)throw new Error("File not found");return r.fileUrls[0]}static async queryTelemetry(t){if(!Authentication.token)throw new Error("Not authenticated");return(await(await fetch(`${FORMANT_API_URL}/v1/queries/queries`,{method:"POST",body:JSON.stringify(t),headers:{"Content-Type":"application/json",Authorization:"Bearer "+Authentication.token}})).json()).items}static async aggregateTelemetry(t){if(!Authentication.token)throw new Error("Not authenticated");return(await(await fetch(`${FORMANT_API_URL}/v1/queries/queries`,{method:"POST",body:JSON.stringify(t),headers:{"Content-Type":"application/json",Authorization:"Bearer "+Authentication.token}})).json()).aggregates}static async queryEvents(t){if(!Authentication.token)throw new Error("Not authenticated");return(await(await fetch(`${FORMANT_API_URL}/v1/admin/events/query`,{method:"POST",body:JSON.stringify(t),headers:{"Content-Type":"application/json",Authorization:"Bearer "+Authentication.token}})).json()).items}static async getEvent(t){if(!Authentication.token)throw new Error("Not authenticated");return(await(await fetch(`${FORMANT_API_URL}/v1/admin/events/query/id=${t}`,{method:"GET",headers:{"Content-Type":"application/json",Authorization:"Bearer "+Authentication.token}})).json()).items}static async getInterventions(){if(!Authentication.token)throw new Error("Not authenticated");return(await(await fetch(`${FORMANT_API_URL}/v1/admin/intervention-requests`,{method:"GET",headers:{"Content-Type":"application/json",Authorization:"Bearer "+Authentication.token}})).json()).items}static async getCurrentGroup(){if(!Authentication.token)throw new Error("Not authenticated");let t=new URLSearchParams("");typeof window<"u"&&(t=new URLSearchParams(window.location.search));const n=t.get("group");if(n===null||n.trim()==="")return;const r=await fetch(`${FORMANT_API_URL}/v1/admin/groups/`+n,{headers:{"Content-Type":"application/json",Authorization:"Bearer "+Authentication.token}}),{tagKey:i,tagValue:s}=await r.json();return await this.queryDevices({tags:{[i]:[s]},enabled:!0,type:"default"})}static async getAnnotationCount(t,n){return(await this.queryEvents({...t,eventTypes:["annotation"]})).filter(l=>!!l.tags&&Object.keys(l.tags).includes(n)).reduce((l,o)=>{const c=o.tags[n];return c in l?(l[c]+=1,l):(l[c]=1,l)},{})}static async getAnnotationCountByIntervals(t,n,r){const{end:i,start:s}=t,o=aggregateByDateFunctions[r].interval({start:new Date(s),end:new Date(i)}),c=o.map((f,E)=>{const w=new Date(f).toISOString(),h=E===o.length-1?new Date(Date.now()).toISOString():new Date(o[E+1]);return this.getAnnotationCount({...t,start:w,end:h},n)}),u=await Promise.all(c);return o.map((f,E)=>({date:new Date(f).toISOString(),annotations:u[E]}))}static async getStreams(){if(!Authentication.token)throw new Error("Not authenticated");return(await(await fetch(`${FORMANT_API_URL}/v1/admin/streams`,{method:"GET",headers:{"Content-Type":"application/json",Authorization:"Bearer "+Authentication.token}})).json()).items.filter(r=>r.enabled)}static async patchStream(t){if(!Authentication.token)throw new Error("Not authenticated");return await(await fetch(`${FORMANT_API_URL}/v1/admin/streams/${t.id}`,{method:"PATCH",body:JSON.stringify(t),headers:{"Content-Type":"application/json",Authorization:"Bearer "+Authentication.token}})).json()}static async getViews(){if(!Authentication.token)throw new Error("Not authenticated");return(await(await fetch(`${FORMANT_API_URL}/v1/admin/views`,{method:"GET",headers:{"Content-Type":"application/json",Authorization:"Bearer "+Authentication.token}})).json()).items}static async patchView(t){if(!Authentication.token)throw new Error("Not authenticated");return await(await fetch(`${FORMANT_API_URL}/v1/admin/views/${t.id}`,{method:"PATCH",body:JSON.stringify(t),headers:{"Content-Type":"application/json",Authorization:"Bearer "+Authentication.token}})).json()}static async eventsCounter(t,n,r,i,s){const l=aggregateByDateFunctions[n];return await Promise.all(Array(r).fill(0).map(async(o,c)=>{const u=new Date(i),f=l.sub(l.start(u),r-c-1),E=l.sub(l.end(u),r-c-1),w=formatTimeFrameText(f.toLocaleDateString(),E.toLocaleDateString()),h=await Ge.queryEvents({...s,eventTypes:t,start:new Date(f).toISOString(),end:new Date(E).toISOString()});return{date:w,events:h}}))}static async getAnalyticsModules(){if(!Authentication.token)throw new Error("Not authenticated");return(await(await fetch(`${FORMANT_API_URL}/v1/admin/analytics-modules`,{method:"GET",headers:{"Content-Type":"application/json",Authorization:"Bearer "+Authentication.token}})).json()).items}static async getAnalyticStreams(){if(!Authentication.token)throw new Error("Not authenticated");return(await(await fetch(`${FORMANT_API_URL}/v1/queries/analytics/streams`,{method:"GET",headers:{"Content-Type":"application/json",Authorization:"Bearer "+Authentication.token}})).json()).items}static async getTaskReportTables(){if(!Authentication.token)throw new Error("Not authenticated");return(await(await fetch(`${FORMANT_API_URL}/v1/queries/analytics/task-reports`,{method:"GET",headers:{"Content-Type":"application/json",Authorization:"Bearer "+Authentication.token}})).json()).items}static async queryAnalytics(t){if(!Authentication.token)throw new Error("Not authenticated");return await(await fetch(`${FORMANT_API_URL}/v1/queries/analytics`,{method:"POST",body:JSON.stringify(t),headers:{"Content-Type":"application/json",Authorization:"Bearer "+Authentication.token}})).json()}static async getAnalyticsRows(t){if(!Authentication.token)throw new Error("Not authenticated");return await(await fetch(`${FORMANT_API_URL}/v1/queries/analytics/rows`,{method:"POST",body:JSON.stringify(t),headers:{"Content-Type":"application/json",Authorization:"Bearer "+Authentication.token}})).json()}static async getTaskReportRows(t){if(!Authentication.token)throw new Error("Not authenticated");return await(await fetch(`${FORMANT_API_URL}/v1/queries/analytics/task-report-rows`,{method:"POST",body:JSON.stringify(t),headers:{"Content-Type":"application/json",Authorization:"Bearer "+Authentication.token}})).json()}static async createShareLink(t,n){if(!Authentication.token)throw new Error("Not authenticated");const i=(await this.getViews()).filter(c=>c.name===n);if(i.length===0)return console.warn("View does not exist or it is misspell"),null;const s=await fetch(`${FORMANT_API_URL}/v1/admin/shares`,{method:"POST",body:JSON.stringify(t),headers:{"Content-Type":"application/json",Authorization:"Bearer "+Authentication.token}}),l=FORMANT_API_URL.replace("api","app"),{code:o}=await s.json();return`${l}/shares/${o}#${serializeHash({viewId:i[0].id})}`}};let Fleet=Ge;Ae(Fleet,"defaultDeviceId"),Ae(Fleet,"knownContext",[]);class KeyValue{static async set(t,n){try{const r=await fetch(FORMANT_API_URL+"/v1/admin/key-value",{method:"POST",body:JSON.stringify({organizationId:defined(Authentication.currentUser).organizationId,key:t,value:n}),headers:{"Content-Type":"application/json",Authorization:"Bearer "+Authentication.token}}),i=await r.json();if(r.status!==200)throw new Error(i.message)}catch(r){throw r}}static async get(t){try{const n=await fetch(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(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(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}}}const vailableAggregationIntervals=["day","week","month","year","hour","minute","quarter"],aggregateFunctions=["interval","start","end","sub","get"];function getVariance(e){return e.count<2?0:e.sumOfSquares/(e.count-1)}function getStandardDeviation(e){return Math.sqrt(getVariance(e))}function getMax(e){return e.max}function getMin(e){return e.min}function getAverage(e){return e.count===0?-1:e.sum/e.count}function getSum(e){return e.sum}function getCount(e){return e.count}const aggregateFunctionMap={min:getMin,max:getMax,"standard deviation":getStandardDeviation,average:getAverage,sum:getSum,count:getCount},aggregateByDateFunctions={day:{interval:dateFns__namespace.eachDayOfInterval,start:dateFns__namespace.startOfDay,end:dateFns__namespace.endOfDay,sub:dateFns__namespace.subDays,get:dateFns__namespace.getDay},week:{interval:dateFns__namespace.eachWeekOfInterval,start:dateFns__namespace.startOfWeek,end:dateFns__namespace.endOfWeek,sub:dateFns__namespace.subWeeks,get:dateFns__namespace.getWeek},month:{interval:dateFns__namespace.eachMonthOfInterval,start:dateFns__namespace.startOfMonth,end:dateFns__namespace.endOfMonth,sub:dateFns__namespace.subMonths,get:dateFns__namespace.getMonth},year:{interval:dateFns__namespace.eachYearOfInterval,start:dateFns__namespace.startOfYear,end:dateFns__namespace.endOfYear,sub:dateFns__namespace.subYears,get:dateFns__namespace.getYear},hour:{interval:dateFns__namespace.eachHourOfInterval,start:dateFns__namespace.startOfHour,end:dateFns__namespace.endOfHour,sub:dateFns__namespace.subHours,get:dateFns__namespace.getHours},minute:{interval:dateFns__namespace.eachMinuteOfInterval,start:dateFns__namespace.startOfMinute,end:dateFns__namespace.endOfMinute,sub:dateFns__namespace.subMinutes,get:dateFns__namespace.getMinutes},quarter:{interval:dateFns__namespace.eachQuarterOfInterval,start:dateFns__namespace.startOfQuarter,end:dateFns__namespace.endOfQuarter,sub:dateFns__namespace.subQuarters,get:dateFns__namespace.getQuarter}},formatTimeFrameText=(e,t)=>e.split("/")[0]+"/"+e.split("/")[1]+"–"+t.split("/")[0]+"/"+t.split("/")[1];function getZeroINumericSet(){return{min:Number.MAX_SAFE_INTEGER,max:0,sum:0,count:0,sumOfSquares:0}}function reduceNumericStreamAggregates(e){return e.aggregates.reduce((t,n)=>{const r=n[1];return combineNumericAggregates(r,t)},getZeroINumericSet())}function reduceNumericSetStreamAggregates(e,t){var n;return(n=e.aggregates.reduce((r,i)=>{const s=i[1];return combineNumericSetAggregates(s,r)},{})[t])==null?void 0:n.value}function combineNumericAggregates(e,t){return{min:Math.min(e.min,t.min),max:Math.max(e.max,t.max),sum:e.sum+t.sum,count:e.count+t.count,sumOfSquares:e.sumOfSquares+t.sumOfSquares}}function combineNumericSetAggregates(e,t){return Object.keys(e).reduce((n,r)=>{var i;return{...n,[r]:{value:combineNumericAggregates(e[r].value,((i=t[r])==null?void 0:i.value)??getZeroINumericSet()),unit:e[r].unit}}},{})}const timeout=e=>new Promise(t=>setTimeout(t,e*1e3));function defaultSetTimout(){throw new Error("setTimeout has not been defined")}function defaultClearTimeout(){throw new Error("clearTimeout has not been defined")}var cachedSetTimeout=defaultSetTimout,cachedClearTimeout=defaultClearTimeout;typeof global$1.setTimeout=="function"&&(cachedSetTimeout=setTimeout),typeof global$1.clearTimeout=="function"&&(cachedClearTimeout=clearTimeout);function runTimeout(e){if(cachedSetTimeout===setTimeout)return setTimeout(e,0);if((cachedSetTimeout===defaultSetTimout||!cachedSetTimeout)&&setTimeout)return cachedSetTimeout=setTimeout,setTimeout(e,0);try{return cachedSetTimeout(e,0)}catch{try{return cachedSetTimeout.call(null,e,0)}catch{return cachedSetTimeout.call(this,e,0)}}}function runClearTimeout(e){if(cachedClearTimeout===clearTimeout)return clearTimeout(e);if((cachedClearTimeout===defaultClearTimeout||!cachedClearTimeout)&&clearTimeout)return cachedClearTimeout=clearTimeout,clearTimeout(e);try{return cachedClearTimeout(e)}catch{try{return cachedClearTimeout.call(null,e)}catch{return cachedClearTimeout.call(this,e)}}}var queue=[],draining=!1,currentQueue,queueIndex=-1;function cleanUpNextTick(){!draining||!currentQueue||(draining=!1,currentQueue.length?queue=currentQueue.concat(queue):queueIndex=-1,queue.length&&drainQueue())}function drainQueue(){if(!draining){var e=runTimeout(cleanUpNextTick);draining=!0;for(var t=queue.length;t;){for(currentQueue=queue,queue=[];++queueIndex<t;)currentQueue&&currentQueue[queueIndex].run();queueIndex=-1,t=queue.length}currentQueue=null,draining=!1,runClearTimeout(e)}}function nextTick(e){var t=new Array(arguments.length-1);if(arguments.length>1)for(var n=1;n<arguments.length;n++)t[n-1]=arguments[n];queue.push(new Item(e,t)),queue.length===1&&!draining&&runTimeout(drainQueue)}function Item(e,t){this.fun=e,this.array=t}Item.prototype.run=function(){this.fun.apply(null,this.array)};var title="browser",platform="browser",browser$1=!0,env={},argv=[],version="",versions={},release={},config={};function noop(){}var on=noop,addListener=noop,once=noop,off=noop,removeListener=noop,removeAllListeners=noop,emit=noop;function binding$1(e){throw new Error("process.binding is not supported")}function cwd(){return"/"}function chdir(e){throw new Error("process.chdir is not supported")}function umask(){return 0}var performance$1=global$1.performance||{},performanceNow=performance$1.now||performance$1.mozNow||performance$1.msNow||performance$1.oNow||performance$1.webkitNow||function(){return new Date().getTime()};function hrtime(e){var t=performanceNow.call(performance$1)*.001,n=Math.floor(t),r=Math.floor(t%1*1e9);return e&&(n=n-e[0],r=r-e[1],r<0&&(n--,r+=1e9)),[n,r]}var startTime=new Date;function uptime(){var e=new Date,t=e-startTime;return t/1e3}var browser$1$1={nextTick,title,browser:browser$1,env,argv,version,versions,on,addListener,once,off,removeListener,removeAllListeners,emit,binding:binding$1,cwd,chdir,umask,hrtime,platform,release,config,uptime},inherits;typeof Object.create=="function"?inherits=function(t,n){t.super_=n,t.prototype=Object.create(n.prototype,{constructor:{value:t,enumerable:!1,writable:!0,configurable:!0}})}:inherits=function(t,n){t.super_=n;var r=function(){};r.prototype=n.prototype,t.prototype=new r,t.prototype.constructor=t};const inherits$1=inherits;var formatRegExp=/%[sdj%]/g;function format(e){if(!isString(e)){for(var t=[],n=0;n<arguments.length;n++)t.push(inspect(arguments[n]));return t.join(" ")}for(var n=1,r=arguments,i=r.length,s=String(e).replace(formatRegExp,function(o){if(o==="%%")return"%";if(n>=i)return o;switch(o){case"%s":return String(r[n++]);case"%d":return Number(r[n++]);case"%j":try{return JSON.stringify(r[n++])}catch{return"[Circular]"}default:return o}}),l=r[n];n<i;l=r[++n])isNull(l)||!isObject(l)?s+=" "+l:s+=" "+inspect(l);return s}function deprecate(e,t){if(isUndefined(global$1.process))return function(){return deprecate(e,t).apply(this,arguments)};if(browser$1$1.noDeprecation===!0)return e;var n=!1;function r(){if(!n){if(browser$1$1.throwDeprecation)throw new Error(t);browser$1$1.traceDeprecation?console.trace(t):console.error(t),n=!0}return e.apply(this,arguments)}return r}var debugs={},debugEnviron;function debuglog(e){if(isUndefined(debugEnviron)&&(debugEnviron=browser$1$1.env.NODE_DEBUG||""),e=e.toUpperCase(),!debugs[e])if(new RegExp("\\b"+e+"\\b","i").test(debugEnviron)){var t=0;debugs[e]=function(){var n=format.apply(null,arguments);console.error("%s %d: %s",e,t,n)}}else debugs[e]=function(){};return debugs[e]}function inspect(e,t){var n={seen:[],stylize:stylizeNoColor};return arguments.length>=3&&(n.depth=arguments[2]),arguments.length>=4&&(n.colors=arguments[3]),isBoolean(t)?n.showHidden=t:t&&_extend(n,t),isUndefined(n.showHidden)&&(n.showHidden=!1),isUndefined(n.depth)&&(n.depth=2),isUndefined(n.colors)&&(n.colors=!1),isUndefined(n.customInspect)&&(n.customInspect=!0),n.colors&&(n.stylize=stylizeWithColor),formatValue(n,e,n.depth)}inspect.colors={bold:[1,22],italic:[3,23],underline:[4,24],inverse:[7,27],white:[37,39],grey:[90,39],black:[30,39],blue:[34,39],cyan:[36,39],green:[32,39],magenta:[35,39],red:[31,39],yellow:[33,39]},inspect.styles={special:"cyan",number:"yellow",boolean:"yellow",undefined:"grey",null:"bold",string:"green",date:"magenta",regexp:"red"};function stylizeWithColor(e,t){var n=inspect.styles[t];return n?"\x1B["+inspect.colors[n][0]+"m"+e+"\x1B["+inspect.colors[n][1]+"m":e}function stylizeNoColor(e,t){return e}function arrayToHash(e){var t={};return e.forEach(function(n,r){t[n]=!0}),t}function formatValue(e,t,n){if(e.customInspect&&t&&isFunction(t.inspect)&&t.inspect!==inspect&&!(t.constructor&&t.constructor.prototype===t)){var r=t.inspect(n,e);return isString(r)||(r=formatValue(e,r,n)),r}var i=formatPrimitive(e,t);if(i)return i;var s=Object.keys(t),l=arrayToHash(s);if(e.showHidden&&(s=Object.getOwnPropertyNames(t)),isError(t)&&(s.indexOf("message")>=0||s.indexOf("description")>=0))return formatError(t);if(s.length===0){if(isFunction(t)){var o=t.name?": "+t.name:"";return e.stylize("[Function"+o+"]","special")}if(isRegExp(t))return e.stylize(RegExp.prototype.toString.call(t),"regexp");if(isDate(t))return e.stylize(Date.prototype.toString.call(t),"date");if(isError(t))return formatError(t)}var c="",u=!1,f=["{","}"];if(isArray(t)&&(u=!0,f=["[","]"]),isFunction(t)){var E=t.name?": "+t.name:"";c=" [Function"+E+"]"}if(isRegExp(t)&&(c=" "+RegExp.prototype.toString.call(t)),isDate(t)&&(c=" "+Date.prototype.toUTCString.call(t)),isError(t)&&(c=" "+formatError(t)),s.length===0&&(!u||t.length==0))return f[0]+c+f[1];if(n<0)return isRegExp(t)?e.stylize(RegExp.prototype.toString.call(t),"regexp"):e.stylize("[Object]","special");e.seen.push(t);var w;return u?w=formatArray(e,t,n,l,s):w=s.map(function(h){return formatProperty(e,t,n,l,h,u)}),e.seen.pop(),reduceToSingleString(w,c,f)}function formatPrimitive(e,t){if(isUndefined(t))return e.stylize("undefined","undefined");if(isString(t)){var n="'"+JSON.stringify(t).replace(/^"|"$/g,"").replace(/'/g,"\\'").replace(/\\"/g,'"')+"'";return e.stylize(n,"string")}if(isNumber(t))return e.stylize(""+t,"number");if(isBoolean(t))return e.stylize(""+t,"boolean");if(isNull(t))return e.stylize("null","null")}function formatError(e){return"["+Error.prototype.toString.call(e)+"]"}function formatArray(e,t,n,r,i){for(var s=[],l=0,o=t.length;l<o;++l)hasOwnProperty(t,String(l))?s.push(formatProperty(e,t,n,r,String(l),!0)):s.push("");return i.forEach(function(c){c.match(/^\d+$/)||s.push(formatProperty(e,t,n,r,c,!0))}),s}function formatProperty(e,t,n,r,i,s){var l,o,c;if(c=Object.getOwnPropertyDescriptor(t,i)||{value:t[i]},c.get?c.set?o=e.stylize("[Getter/Setter]","special"):o=e.stylize("[Getter]","special"):c.set&&(o=e.stylize("[Setter]","special")),hasOwnProperty(r,i)||(l="["+i+"]"),o||(e.seen.indexOf(c.value)<0?(isNull(n)?o=formatValue(e,c.value,null):o=formatValue(e,c.value,n-1),o.indexOf(`
49
+ `),Error.captureStackTrace(this,r)}}e.exports=i=>{if(i.length>2)throw new r(i);function s(o={}){this.options=o}function l(o){return new s(o)}return s.prototype.transform=i,l.Format=s,l}},function(e,t,n){function r(l,o){if(!(l instanceof o))throw new TypeError("Cannot call a class as a function")}function i(l,o){for(var c=0;c<o.length;c++){var u=o[c];u.enumerable=u.enumerable||!1,u.configurable=!0,"value"in u&&(u.writable=!0),Object.defineProperty(l,u.key,u)}}var s=n(88);e.exports=function(){function l(){var u=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};r(this,l),this.loggers=new Map,this.options=u}var o,c;return o=l,(c=[{key:"add",value:function(u,f){var E=this;if(!this.loggers.has(u)){var w=(f=Object.assign({},f||this.options)).transports||this.options.transports;f.transports=w?w.slice():[];var h=s(f);h.on("close",function(){return E._delete(u)}),this.loggers.set(u,h)}return this.loggers.get(u)}},{key:"get",value:function(u,f){return this.add(u,f)}},{key:"has",value:function(u){return!!this.loggers.has(u)}},{key:"close",value:function(u){var f=this;if(u)return this._removeLogger(u);this.loggers.forEach(function(E,w){return f._removeLogger(w)})}},{key:"_removeLogger",value:function(u){this.loggers.has(u)&&(this.loggers.get(u).close(),this._delete(u))}},{key:"_delete",value:function(u){this.loggers.delete(u)}}])&&i(o.prototype,c),l}()},function(e,t,n){(function(r){const i=n(52),s=/^([A-Za-z0-9+/]{4})*([A-Za-z0-9+/]{4}|[A-Za-z0-9+/]{3}=|[A-Za-z0-9+/]{2}==)$/;e.exports=function(l,o,c,u){let f,E,w=!1,h=!1;const g=n(94);function b(F){u(o,F)}function R(F,M){let A=`"${o}" ${M}`;throw F&&(A=`${A}`),E&&(A=`${A}. An example of a valid value would be: ${E}`),new i(A)}const j={convertFromBase64:function(){return b("marking for base64 conversion"),w=!0,j},default:function(F){if(typeof F=="number")f=F.toString();else if(Array.isArray(F)||typeof F=="object"&&F!==null)f=JSON.stringify(F);else{if(typeof F!="string")throw new i("values passed to default() must be of Number, String, Array, or Object type");f=F}return b(`setting default value to "${f}"`),j},required:function(F){return F===void 0?(b("marked as required"),h=!0):(b(`setting required flag to ${F}`),h=F),j},example:function(F){return E=F,j}};return Object.entries({...g,...c}).forEach(([F,M])=>{j[F]=function(A){return function(){let d=l[o];if(b(`will be read from the environment using "${A.name}" accessor`),d===void 0)if(f===void 0&&h)b("was not found in the environment, but is required to be set"),R(void 0,"is a required variable, but it was not set");else{if(f===void 0)return void b("was not found in the environment, but is not required. returning undefined");b(`was not found in the environment, parsing default value "${f}" instead`),d=f}h&&(b("verifying variable value is not an empty string"),d.trim().length===0&&R(void 0,"is a required variable, but its value was empty")),w&&(b("verifying variable is a valid base64 string"),d.match(s)||R(d,"should be a valid base64 string if using convertFromBase64"),b("converting from base64 to utf8 string"),d=r.from(d,"base64").toString());const C=[d].concat(Array.prototype.slice.call(arguments));try{b(`passing value "${d}" to "${A.name}" accessor`);const $=A.apply(A,C);return b(`parsed successfully, returning ${$}`),$}catch($){R(d,$.message)}}}(M)}),j}}).call(this,n(5).Buffer)},function(e,t,n){const r=n(33);e.exports=function(i,s){return s=s||",",i.length?r(i).split(s).filter(Boolean):[]}},function(e,t,n){e.exports=function(r){const i=r.toLowerCase();if(i!=="false"&&i!=="true")throw new Error('should be either "true", "false", "TRUE", or "FALSE"');return i!=="false"}},function(e,t,n){e.exports=function(r){const i=r.toLowerCase();if(["false","0","true","1"].indexOf(i)===-1)throw new Error('should be either "true", "false", "TRUE", "FALSE", 1, or 0');return!(i==="0"||i==="false")}},function(e,t,n){const r=n(95);e.exports=function(i){var s=r(i);if(s>65535)throw new Error("cannot assign a port number greater than 65535");return s}},function(e,t,n){const r=n(33);e.exports=function(i,s){const l=r(i);if(s.indexOf(l)<0)throw new Error(`should be one of [${s.join(", ")}]`);return l}},function(e,t,n){const r=n(54);e.exports=function(i){const s=r(i);if(s>0)throw new Error("should be a negative float");return s}},function(e,t,n){const r=n(54);e.exports=function(i){const s=r(i);if(s<0)throw new Error("should be a positive float");return s}},function(e,t,n){const r=n(53);e.exports=function(i){const s=r(i);if(s>0)throw new Error("should be a negative integer");return s}},function(e,t,n){const r=n(55);e.exports=function(i){var s=r(i);if(!Array.isArray(s))throw new Error("should be a parseable JSON Array");return s}},function(e,t,n){const r=n(55);e.exports=function(i){var s=r(i);if(Array.isArray(s))throw new Error("should be a parseable JSON Object");return s}},function(e,t,n){e.exports=function(r,i){try{RegExp(void 0,i)}catch{throw new Error("invalid regexp flags")}try{return new RegExp(r,i)}catch{throw new Error("should be a valid regexp")}}},function(e,t,n){const r=n(96);e.exports=function(i){return r(i).toString()}},function(e,t,n){const r=n(33),i=/^(?:[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 l=r(s);if(!i.test(l))throw new Error("should be a valid email address");return l}},function(e,t,n){e.exports=function(r,i){return function(s,l){i&&i.match(/prod|production/)||r(`env-var (${s}): ${l}`)}}},function(e,t,n){(function(r){(function(){var i,s,l,o,c,u;typeof performance<"u"&&performance!==null&&performance.now?e.exports=function(){return performance.now()}:r!=null&&r.hrtime?(e.exports=function(){return(i()-c)/1e6},s=r.hrtime,o=(i=function(){var f;return 1e9*(f=s())[0]+f[1]})(),u=1e9*r.uptime(),c=o-u):Date.now?(e.exports=function(){return Date.now()-l},l=Date.now()):(e.exports=function(){return new Date().getTime()-l},l=new Date().getTime())}).call(this)}).call(this,n(2))},function(e,t,n){(function(r){(function(i){function s(o){if((o=o===void 0?"utf-8":o)!=="utf-8")throw new RangeError("Failed to construct 'TextEncoder': The encoding label provided ('"+o+"') is invalid.")}function l(o,c){if(c=c===void 0?{fatal:!1}:c,(o=o===void 0?"utf-8":o)!=="utf-8")throw new RangeError("Failed to construct 'TextDecoder': The encoding label provided ('"+o+"') is invalid.");if(c.fatal)throw Error("Failed to construct 'TextDecoder': the 'fatal' option is unsupported.")}if(i.TextEncoder&&i.TextDecoder)return!1;Object.defineProperty(s.prototype,"encoding",{value:"utf-8"}),s.prototype.encode=function(o,c){if((c=c===void 0?{stream:!1}:c).stream)throw Error("Failed to encode: the 'stream' option is unsupported.");c=0;for(var u=o.length,f=0,E=Math.max(32,u+(u>>1)+7),w=new Uint8Array(E>>3<<3);c<u;){var h=o.charCodeAt(c++);if(55296<=h&&56319>=h){if(c<u){var g=o.charCodeAt(c);(64512&g)==56320&&(++c,h=((1023&h)<<10)+(1023&g)+65536)}if(55296<=h&&56319>=h)continue}if(f+4>w.length&&(E+=8,E=(E*=1+c/o.length*2)>>3<<3,(g=new Uint8Array(E)).set(w),w=g),(4294967168&h)==0)w[f++]=h;else{if(!(4294965248&h))w[f++]=h>>6&31|192;else if(!(4294901760&h))w[f++]=h>>12&15|224,w[f++]=h>>6&63|128;else{if(4292870144&h)continue;w[f++]=h>>18&7|240,w[f++]=h>>12&63|128,w[f++]=h>>6&63|128}w[f++]=63&h|128}}return w.slice(0,f)},Object.defineProperty(l.prototype,"encoding",{value:"utf-8"}),Object.defineProperty(l.prototype,"fatal",{value:!1}),Object.defineProperty(l.prototype,"ignoreBOM",{value:!1}),l.prototype.decode=function(o,c){if((c=c===void 0?{stream:!1}:c).stream)throw Error("Failed to decode: the 'stream' option is unsupported.");c=0;for(var u=(o=new Uint8Array(o)).length,f=[];c<u;){var E=o[c++];if(E===0)break;if(!(128&E))f.push(E);else if((224&E)==192){var w=63&o[c++];f.push((31&E)<<6|w)}else if((240&E)==224){w=63&o[c++];var h=63&o[c++];f.push((31&E)<<12|w<<6|h)}else(248&E)==240&&(65535<(E=(7&E)<<18|(w=63&o[c++])<<12|(h=63&o[c++])<<6|63&o[c++])&&(E-=65536,f.push(E>>>10&1023|55296),E=56320|1023&E),f.push(E))}return String.fromCharCode.apply(null,f)},i.TextEncoder=s,i.TextDecoder=l})(typeof window<"u"?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 o}),n.d(t,"Credentials",function(){return L}),n.d(t,"IRtcStream",function(){}),n.d(t,"SignalingPromiseClient",function(){return W.SignalingPromiseClient}),n.d(t,"IRtcClientConfigurationV1",function(){}),n.d(t,"IRtcClientConfiguration",function(){}),n.d(t,"IRtcConnectionStatsInfo",function(){}),n.d(t,"IRtcSendConfiguration",function(){}),n.d(t,"IRtcSessionMetricsMessageCounts",function(){}),n.d(t,"IRtcStreamMessage",function(){}),n.d(t,"IRtcStreamPayload",function(){}),n.d(t,"IStreamControl",function(){}),n.d(t,"RtcClient",function(){return Nt}),n.d(t,"RtcClientV1",function(){return Rt}),n.d(t,"createRtcStreamMessage",function(){return De});var r=n(28),i=function(pe,D,H,X){return new(H||(H=Promise))(function(ie,oe){function de(ce){try{be(X.next(ce))}catch(le){oe(le)}}function ye(ce){try{be(X.throw(ce))}catch(le){oe(le)}}function be(ce){var le;ce.done?ie(ce.value):(le=ce.value,le instanceof H?le:new H(function(Re){Re(le)})).then(de,ye)}be((X=X.apply(pe,D||[])).next())})};class s extends r.a{adminSignup(D,H){return i(this,void 0,void 0,function*(){return yield this.fetch("auth/admin-signup",{token:H,method:"POST",body:JSON.stringify(D)})})}login(D){return i(this,void 0,void 0,function*(){return yield this.fetch("auth/login",{method:"POST",body:JSON.stringify(D),allowUnsafeRetries:!0})})}loginWithGoogleToken(D){return i(this,void 0,void 0,function*(){return yield this.fetch("auth/login-google",{method:"POST",body:JSON.stringify(D),allowUnsafeRetries:!0})})}refresh(D,H){return i(this,void 0,void 0,function*(){return yield this.fetch("auth/refresh",{method:"POST",body:JSON.stringify({refreshToken:D,tokenExpirationSeconds:H}),allowUnsafeRetries:!0})})}respondToNewPasswordRequiredChallenge(D){return i(this,void 0,void 0,function*(){return yield this.fetch("auth/respond-to-new-password-required-challenge",{method:"POST",body:JSON.stringify(D)})})}forgotPassword(D){return i(this,void 0,void 0,function*(){return yield this.fetch("auth/forgot-password",{method:"POST",body:JSON.stringify({email:D})})})}confirmForgotPassword(D){return i(this,void 0,void 0,function*(){return yield this.fetch("auth/confirm-forgot-password",{method:"POST",body:JSON.stringify(D)})})}resendInvitation(D){return i(this,void 0,void 0,function*(){return yield this.fetch("auth/resend-invitation",{method:"POST",body:JSON.stringify({email:D})})})}changePassword({token:D,refreshToken:H,currentPassword:X,newPassword:ie}){return i(this,void 0,void 0,function*(){return yield this.fetch("auth/change-password",{token:D,method:"POST",body:JSON.stringify({refreshToken:H,currentPassword:X,newPassword:ie})})})}getDeviceCredentials(D){return i(this,void 0,void 0,function*(){return yield this.fetch("auth/device-credentials",{token:D,method:"POST",allowUnsafeRetries:!0})})}impersonate(D,H){return i(this,void 0,void 0,function*(){return yield this.fetch("auth/impersonate",{token:D,method:"POST",allowUnsafeRetries:!0,body:JSON.stringify({userId:H})})})}createServiceAccount(D,H,X,ie){return i(this,void 0,void 0,function*(){return yield this.fetch("auth/service-account",{token:D,method:"POST",allowUnsafeRetries:!0,body:JSON.stringify({name:H,roleId:X,tags:ie})})})}getFeatures(D){return i(this,void 0,void 0,function*(){return(yield this.fetch("auth/features",{token:D})).features})}}var l=function(pe,D,H,X){return new(H||(H=Promise))(function(ie,oe){function de(ce){try{be(X.next(ce))}catch(le){oe(le)}}function ye(ce){try{be(X.throw(ce))}catch(le){oe(le)}}function be(ce){var le;ce.done?ie(ce.value):(le=ce.value,le instanceof H?le:new H(function(Re){Re(le)})).then(de,ye)}be((X=X.apply(pe,D||[])).next())})};class o extends r.a{createPeer(D,H){return l(this,void 0,void 0,function*(){return yield this.fetch("peers",{token:D,method:"POST",body:JSON.stringify(H)})})}getPeers(D){return l(this,void 0,void 0,function*(){return(yield this.fetch("peers",{token:D})).items})}refreshPeer(D,H){return l(this,void 0,void 0,function*(){yield this.fetch(`peers/${H}/refresh`,{token:D,method:"POST",allowUnsafeRetries:!0})})}createSession(D,H){return l(this,void 0,void 0,function*(){return yield this.fetch("sessions",{token:D,method:"POST",body:JSON.stringify(H)})})}refreshSession(D,H){return l(this,void 0,void 0,function*(){yield this.fetch(`sessions/${H}/refresh`,{token:D,method:"POST",allowUnsafeRetries:!0})})}deleteSession(D,H){return l(this,void 0,void 0,function*(){yield this.fetch(`sessions/${H}`,{token:D,method:"DELETE",allowUnsafeRetries:!0})})}getSessions(D){return l(this,void 0,void 0,function*(){return(yield this.fetch("sessions",{token:D})).items})}getIceServers(D){return l(this,void 0,void 0,function*(){return(yield this.fetch("ice-servers",{token:D})).items})}addSignals(D,H,X){return l(this,void 0,void 0,function*(){yield this.fetch(`sessions/${H}/add-signals`,{token:D,method:"POST",body:JSON.stringify(X)})})}takeSignals(D,H){return l(this,void 0,void 0,function*(){return(yield this.fetch(`sessions/${H}/take-signals`,{token:D,method:"POST"})).items})}}var c=n(1),u=n(8),f=n(14),E=n.n(f),w=n(104),h=n.n(w),g=n(0),b=function(pe,D,H,X){return new(H||(H=Promise))(function(ie,oe){function de(ce){try{be(X.next(ce))}catch(le){oe(le)}}function ye(ce){try{be(X.throw(ce))}catch(le){oe(le)}}function be(ce){var le;ce.done?ie(ce.value):(le=ce.value,le instanceof H?le:new H(function(Re){Re(le)})).then(de,ye)}be((X=X.apply(pe,D||[])).next())})};class R{constructor(D){this.name="LogReporter",this.type="simple",this.message=D}send(D){return b(this,void 0,void 0,function*(){var H,X;g.a.info(this.message,(H=D.reduce((ie,oe)=>Object.assign(Object.assign({},ie),{[oe.name]:oe.stat}),{}),X=ie=>{const{sum:oe,count:de}=ie,ye=oe/de;return Object.assign(Object.assign({},ie),{average:ye})},Object.keys(H).reduce((ie,oe)=>Object.assign(Object.assign({},ie),{[oe]:X(H[oe])}),{})))})}}var j=n(4),F=n(39);function M(pe){return!!pe.match(/^[a-zA-Z0-9-_.,:?'"()@\/\\#$+ ]{1,255}$/)}var A=function(pe,D,H,X){return new(H||(H=Promise))(function(ie,oe){function de(ce){try{be(X.next(ce))}catch(le){oe(le)}}function ye(ce){try{be(X.throw(ce))}catch(le){oe(le)}}function be(ce){var le;ce.done?ie(ce.value):(le=ce.value,le instanceof H?le:new H(function(Re){Re(le)})).then(de,ye)}be((X=X.apply(pe,D||[])).next())})};function d({func:pe,delay:D,immediate:H=!1}){let X=!1,ie=setTimeout(function de(){return A(this,void 0,void 0,function*(){if(X)return;const ye=new Date().getTime();try{oe=pe(),yield oe}finally{if(!X){const be=new Date().getTime();ie=setTimeout(de,Math.max(D-(be-ye),0))}}})},H?0:D),oe=Promise.resolve();return{stop(){return A(this,void 0,void 0,function*(){X=!0,clearTimeout(ie),yield oe})}}}var C=function(pe,D,H,X){return new(H||(H=Promise))(function(ie,oe){function de(ce){try{be(X.next(ce))}catch(le){oe(le)}}function ye(ce){try{be(X.throw(ce))}catch(le){oe(le)}}function be(ce){var le;ce.done?ie(ce.value):(le=ce.value,le instanceof H?le:new H(function(Re){Re(le)})).then(de,ye)}be((X=X.apply(pe,D||[])).next())})};const $=n(226),q=!!j.c,y=new class{constructor(pe){this.samplePeriodSeconds=60,this.buffer={},this.reporters=[],this.flushInterval=d({func:()=>this.flushStats(),delay:this.samplePeriodSeconds*c.a.second}),this.tags=this.filterTags((pe==null?void 0:pe.tags)||{app:j.a,version:j.j,namespace:j.i,instanceId:F.a})}shutdown(){return C(this,void 0,void 0,function*(){yield this.flushInterval.stop(),yield this.flushStats(),yield Object(u.a)(2*c.a.second)})}aggregate(pe,D,H){this.addToBuffer(this.buffer,this.encodeKey({metric:pe,tags:this.filterTags(H||{})}),typeof D=="number"?{min:D,max:D,sum:D,count:1}:D)}increment(pe,D){this.aggregate(pe,1,D)}timer(pe,D,H){return C(this,void 0,void 0,function*(){const X=$(),ie=yield D(),oe=$();return this.aggregate(pe,oe-X,H),ie})}registerStatsReporter(pe){this.reporters.push(pe)}setTag(pe,D){const H=this.filterTags({[pe]:D});this.tags=Object.assign(Object.assign({},this.tags),H)}addToBuffer(pe,D,H){if(pe[D]){const{min:X,max:ie,sum:oe,count:de}=pe[D];pe[D]={min:Math.min(X,H.min),max:Math.max(ie,H.max),sum:oe+H.sum,count:de+H.count}}else pe[D]=H}write(pe){return C(this,void 0,void 0,function*(){yield Promise.all(this.reporters.map(D=>C(this,void 0,void 0,function*(){let H;const X={};switch(D.type){case"simple":for(const[oe,de]of Object.entries(pe)){const{metric:ye}=this.decodeKey(oe);this.addToBuffer(X,this.encodeKey({metric:ye}),de)}H=X;break;case"tagged":H=pe;break;default:(function(oe){throw new Error(`Unreachable type encountered (${oe})`)})(D.type)}const ie=Object.entries(H);if(ie.length>0)return D.send(ie.map(([oe,de])=>{const{metric:ye,tags:be}=this.decodeKey(oe);return{name:ye,tags:Object.assign(Object.assign({},be),this.tags),stat:de}}),this.samplePeriodSeconds).catch(oe=>{g.a.debug(`Failed to write stats to ${D.name}`,{error:oe})})})))})}flushStats(){return C(this,void 0,void 0,function*(){yield this.write(this.buffer),this.buffer={}})}encodeKey(pe){return E()(Object.assign(Object.assign({},pe),Object.keys(pe.tags||{}).length>0?{tags:pe.tags}:{}))}decodeKey(pe){return JSON.parse(pe)}filterTags(pe){return Object.entries(pe||{}).reduce((D,[H,X])=>(M(H)&&M(X)&&(D[H]=X),D),{})}};q||["local","on-prem"].includes(j.i)||y.registerStatsReporter(new R("stats"));var m=function(pe,D,H,X){return new(H||(H=Promise))(function(ie,oe){function de(ce){try{be(X.next(ce))}catch(le){oe(le)}}function ye(ce){try{be(X.throw(ce))}catch(le){oe(le)}}function be(ce){var le;ce.done?ie(ce.value):(le=ce.value,le instanceof H?le:new H(function(Re){Re(le)})).then(de,ye)}be((X=X.apply(pe,D||[])).next())})};class I extends class{constructor(D){this.options=D,this.cache=new h.a(Object.assign(Object.assign(Object.assign({},D.dispose||D.disposeAfter?{ttlAutopurge:!0}:{}),D),{dispose:(...H)=>{var X;H[2]==="evict"&&y.increment("lru-eviction",{name:D.name}),(X=D.dispose)===null||X===void 0||X.call(D,...H)},disposeAfter:(...H)=>{var X;this.updateStats(),(X=D.disposeAfter)===null||X===void 0||X.call(D,...H)}})),this.stringify=D.fastStringify?JSON.stringify:E.a}set(D,H,X){const ie=this.stringify(D);if(!this.cache.set(ie,H,{ttl:X})){const oe=this.cache.sizeCalculation?this.cache.sizeCalculation(H,ie):"unknown";throw Error(`Value too large (${oe} > ${this.cache.max})`)}this.updateStats()}get(D){const{name:H}=this.options,X=this.stringify(D),ie=this.cache.getRemainingTTL(X);return ie<=0?y.increment("cache-miss",{name:H}):ie!==1/0&&y.aggregate("cache-item-ttl",ie,{name:H}),this.cache.get(X)}delete(D){this.cache.delete(this.stringify(D))}peek(D){return this.cache.peek(this.stringify(D))}size(){return this.cache.size}clear(){this.cache.clear()}forEach(D){this.cache.forEach(D)}purgeStale(){return this.cache.purgeStale()}updateStats(){const{name:D}=this.options;y.aggregate("cache-item-count",this.cache.size,{name:D}),this.cache.calculatedSize!==void 0&&y.aggregate("cache-length",this.cache.calculatedSize,{name:D})}}{constructor(D){if(super(D),this.expireRejectedPromiseValues=D.expireRejectedPromiseValues===void 0||D.expireRejectedPromiseValues,this.rejectedPromiseValueTtl=D.rejectedPromiseValueTtl!==void 0?D.rejectedPromiseValueTtl:c.a.second,this.rejectedPromiseValueTtl<0)throw new Error("rejectedPromiseValueTtl must not be negative")}set(D,H,X){super.set(D,H,X),this.expireRejectedPromiseValues&&H.catch(()=>m(this,void 0,void 0,function*(){yield Object(u.a)(this.rejectedPromiseValueTtl),this.peek(D)===H&&this.delete(D)}))}}var _=function(pe,D,H,X){return new(H||(H=Promise))(function(ie,oe){function de(ce){try{be(X.next(ce))}catch(le){oe(le)}}function ye(ce){try{be(X.throw(ce))}catch(le){oe(le)}}function be(ce){var le;ce.done?ie(ce.value):(le=ce.value,le instanceof H?le:new H(function(Re){Re(le)})).then(de,ye)}be((X=X.apply(pe,D||[])).next())})};class L{constructor(D,H,X){this.authClient=D,this.email=H,this.password=X,this.tokenTtlMs=1*c.a.hour,this.tokenCache=new I({name:"Credentials-tokenCache",max:100,ttl:this.tokenTtlMs-5*c.a.minute,fastStringify:!0})}getToken(){return _(this,void 0,void 0,function*(){let D=this.tokenCache.get(this.email);return D||(D=(()=>_(this,void 0,void 0,function*(){const{authentication:H}=yield this.authClient.login({email:this.email,password:this.password,tokenExpirationSeconds:this.tokenTtlMs/c.a.second});if(!H)throw new Error("User account not verified.");return H.accessToken}))(),this.tokenCache.set(this.email,D)),D})}}var W=n(97),B=n(40),N=function(pe,D,H,X){return new(H||(H=Promise))(function(ie,oe){function de(ce){try{be(X.next(ce))}catch(le){oe(le)}}function ye(ce){try{be(X.throw(ce))}catch(le){oe(le)}}function be(ce){var le;ce.done?ie(ce.value):(le=ce.value,le instanceof H?le:new H(function(Re){Re(le)})).then(de,ye)}be((X=X.apply(pe,D||[])).next())})};class P extends B.a{constructor(D){super(D)}postLanRtcOffer(D){return N(this,void 0,void 0,function*(){return yield this.fetch("v1/lan-rtc-offer",{method:"POST",body:JSON.stringify(D)})})}}var z=function(pe,D,H,X){return new(H||(H=Promise))(function(ie,oe){function de(ce){try{be(X.next(ce))}catch(le){oe(le)}}function ye(ce){try{be(X.throw(ce))}catch(le){oe(le)}}function be(ce){var le;ce.done?ie(ce.value):(le=ce.value,le instanceof H?le:new H(function(Re){Re(le)})).then(de,ye)}be((X=X.apply(pe,D||[])).next())})};function O(pe){return z(this,void 0,void 0,function*(){return(yield Promise.all(pe.map(D=>D.catch(H=>H)))).filter(D=>D instanceof Error)})}function p(pe){if(pe!==void 0)return pe;throw new Error("Value is undefined")}function U(pe,D){const H=pe.reduce((X,ie)=>[...X,...ie.urls],[]).filter(X=>V(X,D)).sort(X=>Q(X,"udp")?-1:0).shift();if(H)return Object.assign(Object.assign({},p(pe.find(X=>X.urls.includes(H)))),{urls:[H]})}function V(pe,D){switch(D){case"stun":return/^stuns?:/.test(pe);case"turn":return/^turns?:/.test(pe)}}function Q(pe,D){return pe.endsWith(`transport=${D}`)}var ee=n(9),ne=n(24),Y=n(229);class G extends Error{constructor(D,H){super(`Deadline expired after ${D}ms + ${H}ms`)}}class S{static withDeadline(D,H){const X=new Promise((ie,oe)=>{setTimeout(()=>{oe(new G(H,this.grpcCallDeadlineSlopMs))},H+this.grpcCallDeadlineSlopMs)});return Promise.race([D,X])}}S.grpcCallDeadlineSlopMs=500*c.a.millisecond;var T=n(29);const k={ordered:!1,maxPacketLifeTime:300*c.a.millisecond},J={ordered:!0},K={ordered:!0},re={ordered:!1,maxRetransmits:0},se={ordered:!1,maxRetransmits:0},fe=pe=>"received"in pe&&pe.received!==void 0,ve=pe=>!("received"in pe)||pe.received===void 0,Ce=2*c.a.second;function Se(pe,D={}){const H=Array.from(pe.values()),X=H.filter(fe),ie=X.length>0,oe=Math.max(...X.map(ce=>ce.received));let de;if(ie){const ce=H.length,le=X.length,Re=X.map(Le=>Le.received-Le.sent),{standardDeviation:Me,mean:xe,jitter:ze}=function(Le){const ke=Le.length;if(ke===0)return{mean:NaN,standardDeviation:-1,jitter:NaN};const $e=Le.reduce((Qe,st)=>Qe+st,0)/ke,qe=Math.sqrt(Le.map(Qe=>Math.pow(Qe-$e,2)).reduce((Qe,st)=>Qe+st)/ke);if(ke===1)return{mean:$e,standardDeviation:qe,jitter:NaN};let Je=0;for(let Qe=1;Qe<ke;Qe++)Je+=Math.abs(Le[Qe]-Le[Qe-1]);return{mean:$e,standardDeviation:qe,jitter:Je/(ke-1)}}(Re),Xe=H.filter(Le=>Le.sent<oe-Ce),Ze=Xe.filter(ve),Ke=Ze.length===0?0:Ze.length/Xe.length;de={pingsSent:ce,pongsReceived:le,average:xe,standardDeviation:Me,jitter:ze,max:Math.max(...Re),min:Math.min(...Re),loss:Ke}}else de=null;const{temporalNow:ye=Date.now()}=D,be=(ie?oe:ye)-4*Ce;return Array.from(pe.entries()).forEach(ce=>{const[le,Re]=ce;Re.sent<be&&pe.delete(le)}),de}function Ie({entityId:pe,streamName:D,streamType:H}){return`${pe}.${D}.${H}`}var Te=function(pe,D,H,X){return new(H||(H=Promise))(function(ie,oe){function de(ce){try{be(X.next(ce))}catch(le){oe(le)}}function ye(ce){try{be(X.throw(ce))}catch(le){oe(le)}}function be(ce){var le;ce.done?ie(ce.value):(le=ce.value,le instanceof H?le:new H(function(Re){Re(le)})).then(de,ye)}be((X=X.apply(pe,D||[])).next())})};class Oe{constructor(D,H){this.sessionId=D,this.connection=H,this.counts={localSent:new Map,localReceived:new Map,remoteSent:new Map,remoteReceived:new Map},this.sessionId=D,this.connection=H}updateRemoteMessagesCounts(D){if(D.payload.streamsInfo){this.counts.remoteSent=new Map,this.counts.remoteReceived=new Map;for(const H of D.payload.streamsInfo.items)this.counts.remoteSent.set(H.streamId,H.sentCount),this.counts.remoteReceived.set(H.streamId,H.receivedCount)}}getLocalStreamsInfo(D){const{localSent:H,localReceived:X}=this.counts;return{items:[...new Set([...H.keys(),...X.keys()])].map(ie=>{var oe,de;return{streamId:ie,sentCount:(oe=H.get(ie))!==null&&oe!==void 0?oe:0,receivedCount:(de=X.get(ie))!==null&&de!==void 0?de:0}}),timestamp:D}}incrementLocalSent(D){const{localSent:H}=this.counts,X=Ie(D.header.stream);H.set(X,(H.get(X)||0)+1)}incrementLocalReceived(D){const{localReceived:H}=this.counts,X=Ie(D.header.stream),ie=H.get(X)||0;if(ie===0){const{streamName:oe,streamType:de}=D.header.stream;g.a.debug("RTC client received first message for stream",{streamName:oe,streamType:de})}H.set(X,ie+1)}uploadMetrics(){return Te(this,void 0,void 0,function*(){const{sessionId:D}=this,H=yield this.connection.peerConnection.getStats(),X={};H.forEach(ce=>X[ce.id]=ce),g.a.debug("rtc-stats",Object.assign(Object.assign({},X),{sessionId:D}));const{localSent:ie,localReceived:oe,remoteSent:de,remoteReceived:ye}=this.counts,be=[...new Set([...ie.keys(),...oe.keys()])].reduce((ce,le)=>{const Re=ie.get(le),Me=oe.get(le),xe=de.get(le),ze=ye.get(le);return Object.assign(Object.assign({},ce),{[`local-${le}-sent`]:Re,[`local-${le}-received`]:Me,[`remote-${le}-sent`]:xe,[`remote-${le}-received`]:ze})},{sessionId:D});g.a.debug("rtc-message-report",Object.assign({deviceId:this.connection.getRemoteDeviceId()},be))})}}function De(pe,D,H){return{header:{stream:pe,created:Date.now(),frameId:H||""},payload:D}}function Ye(pe){return new Set(["disconnected","failed","closed"]).has(pe.iceConnectionState)}function nt(pe){switch(pe.header.stream.streamType){case"twist":{const{twist:D}=pe.payload;if(!D)throw Error("twist not in payload of RTC message with type twist");return{header:pe.header,payload:{twist:{linear:Object.assign({x:0,y:0,z:0},D.linear),angular:Object.assign({x:0,y:0,z:0},D.angular)}}}}case"pose":{const{pose:D}=pe.payload;if(!D)throw Error("pose not in payload of RTC message with type pose");return{header:pe.header,payload:{pose:{translation:Object.assign({x:0,y:0,z:0},D.translation),rotation:Object.assign({x:0,y:0,z:0,w:0},D.rotation)}}}}case"pose-with-covariance":{const{poseWithCovariance:D}=pe.payload;if(!D)throw Error("poseWithCovariance not in payload of RTC message with type pose-with-covariance");const H=new Array(36).fill(0);return D.covariance.forEach((X,ie)=>{if(ie>=36)throw Error("covariance contains more than 36 elements");H[ie]=X}),{header:pe.header,payload:{poseWithCovariance:{pose:{translation:Object.assign({x:0,y:0,z:0},D.pose.translation),rotation:Object.assign({x:0,y:0,z:0,w:0},D.pose.rotation)},covariance:H}}}}case"point":{const{point:D}=pe.payload;if(!D)throw Error("point not in payload of RTC message with type point");return{header:pe.header,payload:{point:Object.assign({x:0,y:0,z:0},D)}}}default:return pe}}var tt=function(pe,D,H,X){return new(H||(H=Promise))(function(ie,oe){function de(ce){try{be(X.next(ce))}catch(le){oe(le)}}function ye(ce){try{be(X.throw(ce))}catch(le){oe(le)}}function be(ce){var le;ce.done?ie(ce.value):(le=ce.value,le instanceof H?le:new H(function(Re){Re(le)})).then(de,ye)}be((X=X.apply(pe,D||[])).next())})};class bt{constructor(D,H,X){this.peerConnection=D,this.config=H,this.dataChannelNotifier=X,this.connectTimeoutMs=20*c.a.second,this.iceGatheringTimeoutMs=15*c.a.second,this.pingUpdateTimeoutMs=1*c.a.second,this.pingV2UpdateTimeoutMs=250*c.a.millisecond,this.pingV2MetricsGatherTimeoutMs=1*c.a.second,this.streamsInfoUpdateTimeoutMs=2*c.a.second,this.reassemblyTimeoutMs=500*c.a.millisecond,this.reassemblyTableCleanupMs=1*c.a.second,this.heartbeatTimeoutMs=20*c.a.millisecond,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:oe}=this;if(!oe)return;const de=new Date().getTime(),ye=Object(Y.a)();this.sendSystemMessage(oe,{type:"ping-v2",payload:{timestamp:de,id:ye}}),this.pingV2Map.set(ye,{sent:de})},this.gatherPingV2Metrics=()=>{const oe=Se(this.pingV2Map);if(oe){const de=this.getRemoteDeviceId();this.pingInfo=oe,y.aggregate("rtc-ping-average",oe.average,Object.assign({},de?{deviceId:de}:{})),y.aggregate("rtc-ping-loss",oe.loss,Object.assign({},de?{deviceId:de}:{})),y.aggregate("rtc-jitter",oe.jitter,Object.assign({},de?{deviceId:de}:{}))}};const{isOffer:ie}=H.baseConfig;ie?this.initializeChannels(D):D.ondatachannel=oe=>{switch(oe.channel.label){case"stream.latest-ttl":this.latestTtlStreamChannel=oe.channel;break;case"stream.reliable":this.reliableStreamChannel=oe.channel;break;case"stream.latest-reliable":this.latestReliableStreamChannel=oe.channel;break;case"stream.latest-try-once":this.latestTryOnceStreamChannel=oe.channel;break;case"heartbeat":return void(this.heartbeatChannel=oe.channel);default:return void this.dataChannelNotifier(oe.channel)}this.setupChannel(oe.channel)},this.pingUpdateTimeout=setInterval(()=>{const{reliableStreamChannel:oe}=this;oe&&this.sendSystemMessage(oe,{type:"ping"})},this.pingUpdateTimeoutMs),this.pingV2UpdateTimeout=setInterval(this.sendPingV2,this.pingV2UpdateTimeoutMs),this.pingV2MetricsGatherTimeout=setInterval(this.gatherPingV2Metrics,this.pingV2MetricsGatherTimeoutMs),this.streamsInfoUpdateTimeout=setInterval(()=>{const{latestTtlStreamChannel:oe}=this;oe&&this.sendSystemMessage(oe,{type:"streams-info"})},this.streamsInfoUpdateTimeoutMs),this.reassemblyTableCleanupTimeout=setInterval(()=>{const oe=new Date().getTime();this.reassemblyTableLastTimestamp.forEach((de,ye,be)=>{oe>ye+this.reassemblyTimeoutMs&&this.reassemblyTable.delete(de)})},this.reassemblyTableCleanupMs),this.heartbeatTimeout=setInterval(()=>{const{heartbeatChannel:oe}=this;oe&&oe.readyState==="open"&&oe.send(new Uint8Array([1]))},this.heartbeatTimeoutMs)}handleSignal(D){return tt(this,void 0,void 0,function*(){const{peerConnection:H}=this,{track:X}=this.config.baseConfig,ie=(()=>{try{return JSON.parse(D.getPayload())}catch{return}})();if(!ie)return void g.a.error("Received unparseable signal.");g.a.debug("Handling signal",{description:ie});const{sdp:oe,type:de}=ie;if(!oe||!de)return void g.a.warn("Received non-SDP signal");const{signalingState:ye,connectionState:be}=H;if(ye!=="stable"||be!=="connected")if(H.remoteDescription)g.a.warn(`Received SDP after remote description was set: ${oe}`);else{if(de==="offer"){if(ye!=="stable")return void g.a.warn("Received offer SDP when signaling is ongoing.");yield H.setRemoteDescription(ie);const ce=yield H.createAnswer();yield H.setLocalDescription(ce);const le=D.clone();return X==null||X("Answer Received",le),le.setPayload(JSON.stringify(ce)),le.setReceiverId(D.getSenderId()),le.setSenderId(D.getReceiverId()),le}if(de==="answer"){if(ye==="stable")return void g.a.warn("Received answer SDP when signaling hasn't started.");yield H.setRemoteDescription(ie)}}else g.a.warn(`Received SDP when already connected: ${oe}`)})}send(D,H){const X=this.getChannelFromLabel(H.channelLabel);X?this.sendOnChannel(X,D):g.a.warn("Send called with unexpected channel label",{channelLabel:H.channelLabel})}controlRemoteStream(D){this.sendSystemMessage(p(this.reliableStreamChannel),{type:"stream-control",streamControl:D})}isActive(){return new Set(["new","checking","connected","completed"]).has(this.peerConnection.iceConnectionState)||this.isReady()}isReady(){const{reliableStreamChannel:D,latestTtlStreamChannel:H,latestTryOnceStreamChannel:X,latestReliableStreamChannel:ie}=this;return(D==null?void 0:D.readyState)==="open"&&(H==null?void 0:H.readyState)==="open"&&(X==null?void 0:X.readyState)==="open"&&(ie==null?void 0:ie.readyState)==="open"}close(){return tt(this,void 0,void 0,function*(){if(this.closeCalled)return;this.closeCalled=!0,this.sessionMetrics&&(yield this.sessionMetrics.uploadMetrics()),lt(this.pingUpdateTimeout),lt(this.pingV2UpdateTimeout),lt(this.pingV2MetricsGatherTimeout),lt(this.reassemblyTableCleanupTimeout),lt(this.streamsInfoUpdateTimeout),lt(this.heartbeatTimeout);const{peerConnection:D,reliableStreamChannel:H,latestTtlStreamChannel:X,latestTryOnceStreamChannel:ie,latestReliableStreamChannel:oe}=this;D.close(),H==null||H.close(),X==null||X.close(),ie==null||ie.close(),oe==null||oe.close()})}getPing(){return this.pingTimeMs}getPingInfo(){return this.pingInfo}getLastMessageTimestamp(){return this.lastMessageTimestamp}getSessionCreatedTimestamp(){var D;return(D=this.config.remoteConfig)===null||D===void 0?void 0:D.sessionCreatedTimestamp}setSessionCreatedTimestamp(D){this.config.remoteConfig&&(this.config.remoteConfig.sessionCreatedTimestamp=D)}getSessionId(){var D;return(D=this.config.remoteConfig)===null||D===void 0?void 0:D.sessionId}setSessionId(D){this.config.remoteConfig&&(this.config.remoteConfig.sessionId=D,this.sessionMetrics=new Oe(D,this))}getRemotePeerId(){return this.config.baseConfig.remotePeerId}getRemoteDeviceId(){var D;return(D=this.config.baseConfig)===null||D===void 0?void 0:D.remoteDeviceId}setRemoteDeviceId(D){this.config.baseConfig.remoteDeviceId=D}getSessionMetricsMessageCounts(){var D;return(D=this.sessionMetrics)===null||D===void 0?void 0:D.counts}getConnectionStatsInfo(){return tt(this,void 0,void 0,function*(){const{peerConnection:D}=this;if(!D)return;const H=yield D.getStats(null),X=[];H.forEach(be=>{X.push(be)});const ie=X.find(be=>be.type==="transport");if(!ie)return;const oe=X.find(be=>(be.type==="candidate-pair"||be.type==="candidatepair")&&be.id===ie.selectedCandidatePairId);if(!oe)return;const de=X.find(be=>be.id===oe.localCandidateId),ye=X.find(be=>be.id===oe.remoteCandidateId);return de&&ye&&(de.address=de.address||de.ip,ye.address=ye.address||ye.ip,de.address!==void 0&&ye.address!==void 0)?{transport:ie,localCandidate:de,remoteCandidate:ye}:void 0})}initializeChannels(D){this.heartbeatChannel=D.createDataChannel("heartbeat",se),this.heartbeatChannel.binaryType="arraybuffer",this.latestTtlStreamChannel=D.createDataChannel("stream.latest-ttl",k),this.latestTtlStreamChannel.binaryType="arraybuffer",this.reliableStreamChannel=D.createDataChannel("stream.reliable",J),this.reliableStreamChannel.binaryType="arraybuffer",this.latestReliableStreamChannel=D.createDataChannel("stream.latest-reliable",K),this.latestReliableStreamChannel.binaryType="arraybuffer",this.latestTryOnceStreamChannel=D.createDataChannel("stream.latest-try-once",re),this.latestTryOnceStreamChannel.binaryType="arraybuffer",this.setupChannel(this.latestTtlStreamChannel),this.setupChannel(this.reliableStreamChannel),this.setupChannel(this.latestReliableStreamChannel),this.setupChannel(this.latestTryOnceStreamChannel)}getOffer(){var D,H,X;return tt(this,void 0,void 0,function*(){const{gotOffer:ie}=this,{peerConnection:oe,config:de}=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 ye=(D=this.config.remoteConfig)===null||D===void 0?void 0:D.sessionId;if(ie)return void g.a.debug("Failed to generate offer because gotOffer was already called.");if(this.gotOffer=!0,Ye(this.peerConnection))return void g.a.debug("Failed to generate offer because the peer connection was inactive.");const be=de.baseConfig.track;oe.onicecandidate=()=>{this.hasIceCandidate=!0},oe.oniceconnectionstatechange=()=>tt(this,void 0,void 0,function*(){const xe=oe.iceConnectionState;if(xe==="connected"||xe==="completed"){const ze=yield this.getConnectionStatsInfo(),Xe=ze?function(Ze){const Ke=Ze.localCandidate.candidateType,Le=Ze.remoteCandidate.candidateType;return Ke==="host"&&Le==="host"?"local":Ke==="relay"||Le==="relay"?"TURN":"STUN"}(ze):void 0;g.a.info(`ICE connection state changed to ${xe}`,{sessionId:ye,connectionStatsInfo:ze,iceMode:Xe}),be==null||be("ICE connection state change",{iceConnectionState:xe,sessionId:ye,connectionStatsInfo:ze,iceMode:Xe})}}),yield oe.setLocalDescription(yield oe.createOffer());const ce=new Date().getTime();for(;;){const xe=new Date().getTime()-ce;if(xe>this.connectTimeoutMs)return void g.a.debug("Failed to generate offer because ICE gathering timed out.");if(xe>this.iceGatheringTimeoutMs&&this.hasIceCandidate){g.a.debug("ICE gathering partially completed; proceeding",{iceTransportPolicy:oe.getConfiguration().iceTransportPolicy,waitTime:xe}),be==null||be("ICE gathering partially completed",{sessionId:ye,iceTransportPolicy:oe.getConfiguration().iceTransportPolicy,waitTime:xe});break}if(oe.iceGatheringState==="complete"){g.a.debug("ICE gathering complete",{iceTransportPolicy:oe.getConfiguration().iceTransportPolicy,waitTime:xe}),be==null||be("ICE gathering completed",{sessionId:ye,iceTransportPolicy:oe.getConfiguration().iceTransportPolicy,waitTime:xe});break}yield Object(u.a)(.1*c.a.second)}const le=(H=this.peerConnection.getConfiguration().iceServers)!==null&&H!==void 0?H:[];for(const xe of le)"credentialType"in xe&&(xe.credentialType=void 0);const Re=JSON.stringify(le),Me=new ee.Signal;return Me.setPayload(JSON.stringify(oe.localDescription)),Me.setSenderId(this.config.baseConfig.localPeerId),Me.setReceiverId(this.config.baseConfig.remotePeerId),Me.setIceServers(Re),Me.setIceTransportPolicy((X=this.peerConnection.getConfiguration().iceTransportPolicy)!==null&&X!==void 0?X:"all"),this.config.baseConfig.sessionType!==void 0?Me.setSessionType(this.config.baseConfig.sessionType):Me.setSessionType(ee.SessionType.TELEOP),g.a.debug("Sending offer signal with description",{description:Me.getPayload()}),Me})}getLanOffer(){return tt(this,void 0,void 0,function*(){const{peerConnection:D,gotOffer:H}=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(H)return void g.a.debug("Failed to generate offer because gotOffer was already called.");if(this.gotOffer=!0,Ye(this.peerConnection))return void g.a.debug("Failed to generate offer because the peer connection was inactive.");yield D.setLocalDescription(yield D.createOffer());const X=new Date().getTime();for(;;){if(new Date().getTime()-X>this.iceGatheringTimeoutMs)return void g.a.debug("Failed to generate offer because ICE gathering timed out.");if(D.iceGatheringState==="complete")break;yield Object(u.a)(.1*c.a.second)}const ie=D.localDescription;if(ie)return g.a.debug("Sending LAN offer signal with description",{description:ie}),ie;g.a.error("Failed to generate LAN offer description")})}handleLanAnswer(D){return tt(this,void 0,void 0,function*(){const{peerConnection:H}=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 H.setRemoteDescription(D)})}getChannelFromLabel(D){switch(D){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(D,H){let X;try{X=Object(T.encode)(JSON.stringify(H))}catch(ie){return void g.a.warn("Failed to encode RTC message",{error:ie})}try{D.send(X),this.sessionMetrics&&this.sessionMetrics.incrementLocalSent(H)}catch(ie){g.a.warn("Failed to send message to channel",{error:ie,channel:D.label})}}channelNotRecognized(D){return D!==this.latestTtlStreamChannel&&D!==this.latestReliableStreamChannel&&D!==this.latestTryOnceStreamChannel&&D!==this.reliableStreamChannel}setupChannel(D){D.onmessage=H=>{if(this.channelNotRecognized(D))return void g.a.warn("Received message on unrecognized data channel.");let X;try{X=JSON.parse(Object(T.decode)(H.data))}catch(ie){return void g.a.warn("Received unparseable message on RTC stream data channel",{error:ie,channel:D.label})}X.communicationType==="message-chunk"?this.receiveChannelMessageChunk(D,X):this.receiveChannelMessage(D,X)},D.onerror=H=>{g.a.warn(`Channel error: ${H.error}`,{error:H.error,sessionId:this.getSessionId(),channelLabel:D.label})},D.onopen=()=>{g.a.debug("Channel opened",{sessionId:this.getSessionId(),channelLabel:D.label})},D.onclose=()=>{const H={bufferedAmount:D.bufferedAmount,sessionId:this.getSessionId(),channelLabel:D.label};this.closeCalled===!1?g.a.debug("Unexpected channel closed",H):g.a.debug("Channel closed",H)}}receiveChannelMessage(D,H){const{config:X}=this,{remotePeerId:ie}=this.config.baseConfig;this.lastMessageTimestamp=new Date().getTime(),H=nt(H),this.sessionMetrics&&this.sessionMetrics.incrementLocalReceived(H),this.handleSystemMessage(D,H)||(D===this.latestTryOnceStreamChannel||D===this.latestTtlStreamChannel||D===this.latestReliableStreamChannel)&&!this.isLatestMessage(H)||X.baseConfig.receive(ie,H)}receiveChannelMessageChunk(D,H){const X=this.reassemblyTable.get(H.id)||[];if(X.push(H),X.length===H.total){const ie=function(oe){const de=oe.sort((ye,be)=>ye.seq<be.seq?-1:1).map(ye=>ye.part).reduce((ye,be)=>ye+be);try{return JSON.parse(de)}catch{return void g.a.warn("Could not reassemble RTC message chunks")}}(X);return ie&&this.receiveChannelMessage(D,ie),void this.reassemblyTable.delete(H.id)}this.reassemblyTable.set(H.id,X),this.reassemblyTableLastTimestamp.set(H.id,new Date().getTime())}handleSystemMessage(D,H){var X,ie;const{config:oe}=this,{baseConfig:de}=oe,{remotePeerId:ye,remoteDeviceId:be}=de;switch(H.header.stream.streamType){case"ping":return this.sendSystemMessage(D,{type:"pong",timestamp:p(H.payload.ping)}),!0;case"pong":{const ce=new Date().getTime()-p(H.payload.pong);return this.pingTimeMs=ce,y.aggregate("rtc-ping-time",ce,Object.assign({},be?{deviceId:be}:{})),!0}case"ping-v2":return this.sendPingV2(),!0;case"pong-v2":{const ce=p(H.payload.pongV2),le=this.pingV2Map.get(ce.id);return(le==null?void 0:le.sent)!==ce.timestamp&&g.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=(X=H.payload.streamsInfo)===null||X===void 0?void 0:X.timestamp;return!!le&&(ce==null||ce.updateRemoteMessagesCounts(H),(ie=de.onStreamsInfoUpdate)===null||ie===void 0||ie.call(de,ye,le),!0)}case"stream-control":return!0;default:return!1}}sendSystemMessage(D,H){var X;const{localUserId:ie,localPeerId:oe}=this.config.baseConfig;if(D.readyState!=="open")return;const de={entityId:ie??oe,streamName:`$.${H.type}`,streamType:H.type};let ye;switch(H.type){case"ping":ye={ping:new Date().getTime()};break;case"pong":ye={pong:H.timestamp};break;case"ping-v2":ye={pingV2:H.payload};break;case"pong-v2":ye={pongV2:H.payload};break;case"stream-control":ye={streamControl:H.streamControl};break;case"streams-info":ye={streamsInfo:(X=this.sessionMetrics)===null||X===void 0?void 0:X.getLocalStreamsInfo(new Date().getTime())}}this.sendOnChannel(D,De(de,ye))}isLatestMessage(D){const H=Ie(D.header.stream),X=(this.streamLatestTimestamp.get(H)||0)<=D.header.created;return X&&this.streamLatestTimestamp.set(H,D.header.created),X}}function lt(pe){pe&&clearInterval(pe)}function _t(){g.a.debug("forceGarbageCollection() triggered"),queueMicrotask(()=>{let pe=document.createElement("img");pe.src=window.URL.createObjectURL(new Blob([new ArrayBuffer(5e7)])),pe.onerror=function(){window.URL.revokeObjectURL(this.src),pe=null}})}function It(pe){try{return pe instanceof Error?`${pe.name}: ${pe.message}`:typeof pe=="object"?JSON.stringify(pe):String(pe)}catch{return"Unknown error"}}function Et(pe){var D,H;return{userId:(D=pe.getUserId())===null||D===void 0?void 0:D.getValue(),deviceId:(H=pe.getDeviceId())===null||H===void 0?void 0:H.getValue(),organizationId:pe.getOrganizationId(),id:pe.getPeerId(),capabilities:[],capabilitySet:{}}}var Ue=function(pe,D,H,X){return new(H||(H=Promise))(function(ie,oe){function de(ce){try{be(X.next(ce))}catch(le){oe(le)}}function ye(ce){try{be(X.throw(ce))}catch(le){oe(le)}}function be(ce){var le;ce.done?ie(ce.value):(le=ce.value,le instanceof H?le:new H(function(Re){Re(le)})).then(de,ye)}be((X=X.apply(pe,D||[])).next())})};class Nt{constructor(D){this.config=D,this.grpcCallDeadline=5*c.a.second,this.refreshIntervalDelayMs=2*c.a.second,this.iceServersTtl=30*c.a.minute,this.connections=[],this.localConnections=[],this.isConnectionInitiator=new Map,this.isOutgoingConnection=new Map,this.peerDataChannelListeners=[],this.rtcInstancesConstructed=0;const{refreshIntervalDelayMs:H}=this;this.refreshInterval=d({func:()=>Ue(this,void 0,void 0,function*(){try{yield this.update()}catch(X){g.a.warn("RTC refresh failed",{error:X})}}),delay:H,immediate:!0})}send(D,H,X){const ie=this.getActiveConnection(D);ie?ie.isReady()?ie.send(H,X):g.a.warn("Send called with unready connection."):g.a.warn("Send called with no connection.")}controlRemoteStream(D,H){const X=this.getActiveConnection(D);X?X.isReady()?X.controlRemoteStream(H):g.a.warn("controlRemoteStream called with unready connection."):g.a.warn("controlRemoteStream called with no connection.")}getLocalPeer(){return Ue(this,void 0,void 0,function*(){for(;!this.localPeer;)yield Object(u.a)(.1*c.a.second);return Et(this.localPeer)})}connect(D,H){var X,ie,oe;return Ue(this,void 0,void 0,function*(){if(this.config.lanOnlyMode===!0)throw new Error("connect method called in local only mode.");const{track:de,signalingClient:ye}=this.config,{localPeer:be,receiveSignalStream:ce,iceServers:le}=this;if(!be||!ce||!le)return void g.a.warn("Connect called prior to local peer, receiveSignalStream, and ICE servers ready");if(this.getActiveConnection(D))return void g.a.warn("Connect called for peer with existing connection.");if(this.isOutgoingConnection.get(D))return void g.a.warn("Connect called for peer with an existing outgoing connection offer.");this.isOutgoingConnection.set(D,!0);const Re=function(Le,ke,$e){const{rtcIceTransportPolicies:qe,rtcIceServerProtocol:Je,useAllServers:Qe}=ke||{},st=Le.map(at=>Object.assign(Object.assign({},at),{urls:at.urls.filter(ct=>{const et=(qe===void 0||qe.some(Mt=>V(ct,Mt)))&&(Je===void 0||Q(ct,Je));return et||g.a.debug(`Ignoring ICE server: ${ct}`,{organizationId:$e}),et})})).filter(({urls:at})=>at.filter(ct=>ct).length>0);return Qe?st:[U(st,"stun"),U(st,"turn")].filter(at=>at!==void 0).map(at=>p(at))}(le,H);g.a.debug("Received ICE servers:",le),g.a.debug("Using ICE servers:",Re);const Me=new bt(yield this.createRTCPeerConnection(Re),{baseConfig:{isOffer:!0,isLan:!1,receive:(Le,ke)=>this.config.receive(Le,ke),onStreamsInfoUpdate:this.config.onStreamsInfoUpdate?(Le,ke)=>{var $e,qe;return(qe=($e=this.config).onStreamsInfoUpdate)===null||qe===void 0?void 0:qe.call($e,Le,ke)}:void 0,track:this.config.lanOnlyMode?void 0:this.config.track,localUserId:(X=be.getUserId())===null||X===void 0?void 0:X.getValue(),localPeerId:be.getPeerId(),remotePeerId:D,sessionType:this.config.sessionType},remoteConfig:{}},Le=>this.onCustomDataChannel(D,Le)),xe=yield Me.getOffer();if(!xe)return g.a.error("Failed to generate offer."),void this.isOutgoingConnection.delete(D);g.a.debug("Sending offer."),de==null||de("Sending offer",xe);const ze=new ee.SendSignalRequest;ze.setSignal(xe);const Xe=yield(()=>Ue(this,void 0,void 0,function*(){try{return yield S.withDeadline(ye.sendSignal(ze,yield this.getMetadata({})),this.grpcCallDeadline)}catch(Le){g.a.warn("Error when sending signal",{error:Le})}}))();if(!this.isOutgoingConnection.get(D))return void g.a.debug("No offer set after receiving offer signal response.");g.a.debug("Offer sent.");const Ze=(ie=Xe==null?void 0:Xe.getSessionId())===null||ie===void 0?void 0:ie.getValue(),Ke=(oe=Xe==null?void 0:Xe.getSessionCreatedTimestamp())===null||oe===void 0?void 0:oe.getValue();return Ze&&Ke?(Me.setSessionId(Ze),Me.setSessionCreatedTimestamp(Ke),this.isOutgoingConnection.delete(D),this.connections.push(Me),this.isConnectionInitiator.set(Me,!0),this.setupHandlers(Me),Ze):(g.a.warn("No session ID or no session created timestamp on send signal response."),void this.isOutgoingConnection.delete(D))})}connectLan(D){var H,X;return Ue(this,void 0,void 0,function*(){const ie=new P(D),oe=new bt(yield this.createRTCPeerConnection([]),{baseConfig:{isOffer:!0,isLan:!0,receive:(ce,le)=>this.config.receive(ce,le),onStreamsInfoUpdate:this.config.onStreamsInfoUpdate?(ce,le)=>{var Re,Me;return(Me=(Re=this.config).onStreamsInfoUpdate)===null||Me===void 0?void 0:Me.call(Re,ce,le)}:void 0,track:this.config.lanOnlyMode?void 0:this.config.track,localUserId:(X=(H=this.localPeer)===null||H===void 0?void 0:H.getUserId())===null||X===void 0?void 0:X.getValue(),localPeerId:"lan_client",remotePeerId:D}},ce=>this.onCustomDataChannel(D,ce)),de=yield oe.getLanOffer();if(!de)return g.a.warn("Could not generate LAN offer"),!1;const ye=yield ie.postLanRtcOffer({offer:JSON.stringify(de)}),be=new RTCSessionDescription(JSON.parse(ye.answer));return yield oe.handleLanAnswer(be),this.localConnections.push(oe),this.isConnectionInitiator.set(oe,!0),Object(Y.a)()})}getConnections(){return[...this.connections,...this.localConnections]}createCustomDataChannel(D,H,X,ie,oe){const de=this.getActiveConnection(D);if(de&&this.isConnectionInitiator.has(de)){const be=de.peerConnection.createDataChannel("custom."+H,X);return ie&&(be.binaryType="arraybuffer"),oe(D,be),()=>{}}const ye=(be,ce)=>{D===be&&ce.label==="custom."+H&&oe(D,ce)};return this.peerDataChannelListeners.push(ye),()=>{this.peerDataChannelListeners=this.peerDataChannelListeners.filter(be=>be!==ye)}}onCustomDataChannel(D,H){this.peerDataChannelListeners.forEach(X=>X(D,H))}getConnectionStatus(D){if(this.isOutgoingConnection.get(D))return"connecting";const H=this.getActiveConnection(D);return H?H.isReady()?"connected":"connecting":"disconnected"}getConnectionStatsInfo(D){return Ue(this,void 0,void 0,function*(){const H=this.getActiveConnection(D);if(H)return yield H.getConnectionStatsInfo()})}disconnect(D){return Ue(this,void 0,void 0,function*(){const H=this.getActiveConnection(D);H&&(yield H.close())})}getPeers(){return Ue(this,void 0,void 0,function*(){if(this.config.lanOnlyMode)throw new Error("getPeers method cannot be used in local-only mode.");const{signalingClient:D}=this.config,H=yield(()=>Ue(this,void 0,void 0,function*(){try{return yield S.withDeadline(D.getPeers(new ee.GetPeersRequest,yield this.getMetadata({})),this.grpcCallDeadline)}catch(oe){g.a.warn("Error when getting peers",{error:oe})}}))();if(!H)return[];const X=H.getPeersList();if(!X)return[];const ie=oe=>{var de,ye;return(ye=(de=oe.getPeerCreatedTimestamp())===null||de===void 0?void 0:de.getValue())!==null&&ye!==void 0?ye:0};return X.sort((oe,de)=>ie(de)-ie(oe)).map(oe=>Et(oe))})}getSessions(){return Ue(this,void 0,void 0,function*(){if(this.config.lanOnlyMode)throw new Error("getPeers method cannot be used in local-only mode.");const{signalingClient:D}=this.config,H=yield(()=>Ue(this,void 0,void 0,function*(){try{return yield S.withDeadline(D.getPeers(new ee.GetPeersRequest,yield this.getMetadata({})),this.grpcCallDeadline)}catch(oe){g.a.warn("Error when getting peers",{error:oe})}}))();if(!H)return{};const X=H.getPeersList(),ie={};for(const oe of X)ie[oe.getPeerId()]=oe.getSessionIdsList();return ie})}getPing(D){const H=this.getActiveConnection(D);if(H)return H.getPing();g.a.warn("Attempted to get ping time from inactive peer.")}getPingInfo(D){const H=this.getActiveConnection(D);if(H)return H.getPingInfo();g.a.warn("Attempted to get ping time from inactive peer.")}getLastMessageTimestamp(D){const H=this.getActiveConnection(D);if(H)return H.getLastMessageTimestamp();g.a.warn("Attempted to get last message time from inactive peer.")}getSessionMetricsMessageCounts(D){const H=this.getActiveConnection(D);if(H)return H.getSessionMetricsMessageCounts();g.a.warn("Attempted to get session metrics counts from inactive peer.")}isReady(){if(this.config.lanOnlyMode)return!0;const{localPeer:D,receiveSignalStream:H,iceServers:X}=this;return!!(D&&H&&X)}shutdown(){return Ue(this,void 0,void 0,function*(){g.a.info("Shutdown called on RTC client"),yield this.refreshInterval.stop(),this.receiveSignalStream&&this.receiveSignalStream.cancel();const D=this.connections;this.connections=[],yield this.closeConnections(D);const{localPeer:H}=this;if(!H||this.config.lanOnlyMode)return;const{signalingClient:X}=this.config;yield(()=>Ue(this,void 0,void 0,function*(){try{const ie=new ee.DeletePeerRequest;ie.setPeerId(H.getPeerId()),yield S.withDeadline(X.deletePeer(ie,yield this.getMetadata({})),this.grpcCallDeadline)}catch(ie){return void g.a.warn("Error deleting local peer",{error:ie})}}))()})}createPeer(){return Ue(this,void 0,void 0,function*(){if(this.config.lanOnlyMode)throw new Error("createPeer method cannot be used in local-only mode.");const{signalingClient:D}=this.config,H=yield(()=>Ue(this,void 0,void 0,function*(){try{return yield S.withDeadline(D.createPeer(new ee.CreatePeerRequest,yield this.getMetadata({})),this.grpcCallDeadline)}catch(ie){const oe=ie;g.a.debug("createPeer failed",{error:oe});const de=It(oe);throw new Error(`Was not able to create peer: ${de}`)}}))(),X=H==null?void 0:H.getPeer();if(!X)throw new Error("Response did not provide peer.");return this.localPeer=X})}createReceiveSignalStream(){return Ue(this,void 0,void 0,function*(){if(this.config.lanOnlyMode)throw new Error("createReceiveSignalStream method cannot be used in local-only mode.");const{signalingClient:D}=this.config,{localPeer:H,iceServers:X}=this;if(!H||!X)return;const{receiveSignalStream:ie}=this;ie&&ie.cancel();const oe=new ee.ReceiveSignalStreamRequest;oe.setPeerId(H.getPeerId());const de=yield(()=>Ue(this,void 0,void 0,function*(){try{return D.receiveSignalStream(oe,yield this.getMetadata({hasDeadline:!1}))}catch(ye){g.a.debug("createReceiveSignalStream failed",{error:ye});const be=It(ye);throw new Error(`Unable to create receive signal stream: ${be}`)}}))();if(!de)throw new Error("Response did not provide stream.");return de.on("data",ye=>Ue(this,void 0,void 0,function*(){var be,ce,le,Re;const Me=ye.getSignal(),xe=(be=Me==null?void 0:Me.getSessionId())===null||be===void 0?void 0:be.getValue(),ze=Me==null?void 0:Me.getSenderId(),Xe=Me==null?void 0:Me.getReceiverId(),Ze=(ce=Me==null?void 0:Me.getSessionCreatedTimestamp())===null||ce===void 0?void 0:ce.getValue();if(!(Me&&xe&&ze&&Xe&&Ze))return void g.a.warn("Received signal with missing information.");const Ke=this.getActiveConnection(ze);if(Ke)if(Ke.getSessionId()!==xe){if(g.a.debug("Received signal: different session for a peer we're already connected to."),(Ke.getSessionCreatedTimestamp()||0)>Ze)return;const Le=new bt(yield this.createRTCPeerConnection(X),{baseConfig:{isOffer:!1,isLan:!1,receive:(ke,$e)=>this.config.receive(ke,$e),onStreamsInfoUpdate:this.config.onStreamsInfoUpdate?(ke,$e)=>{var qe,Je;return(Je=(qe=this.config).onStreamsInfoUpdate)===null||Je===void 0?void 0:Je.call(qe,ke,$e)}:void 0,track:this.config.lanOnlyMode?void 0:this.config.track,localPeerId:H.getPeerId(),localUserId:(Re=H.getUserId())===null||Re===void 0?void 0:Re.getValue(),remotePeerId:ze},remoteConfig:{sessionId:xe,sessionCreatedTimestamp:Ze}},ke=>this.onCustomDataChannel(ze,ke));yield Le.handleSignal(Me),this.connections.push(Le)}else g.a.debug("Received signal: for an existing connection."),yield Ke.handleSignal(Me);else{g.a.debug("Received signal: new connection.");const Le=new bt(yield this.createRTCPeerConnection(X),{baseConfig:{isOffer:!1,isLan:!1,receive:(ke,$e)=>this.config.receive(ke,$e),onStreamsInfoUpdate:this.config.onStreamsInfoUpdate?(ke,$e)=>{var qe,Je;return(Je=(qe=this.config).onStreamsInfoUpdate)===null||Je===void 0?void 0:Je.call(qe,ke,$e)}:void 0,track:this.config.lanOnlyMode?void 0:this.config.track,localPeerId:H.getPeerId(),localUserId:(le=H.getUserId())===null||le===void 0?void 0:le.getValue(),remotePeerId:ze},remoteConfig:{sessionId:xe,sessionCreatedTimestamp:Ze}},ke=>this.onCustomDataChannel(ze,ke));yield Le.handleSignal(Me),this.connections.push(Le)}})),de.on("end",()=>{de.cancel(),this.receiveSignalStream=void 0}),de.on("error",ye=>{switch(ye.code){case ne.StatusCode.CANCELLED:case ne.StatusCode.UNAVAILABLE:case ne.StatusCode.UNKNOWN:g.a.debug("Receive signal stream error",{error:ye});break;case ne.StatusCode.UNAUTHENTICATED:g.a.warn("Receive signal stream error",{error:ye});break;default:g.a.error("Receive signal stream error",{error:ye})}de.cancel(),this.receiveSignalStream=void 0}),this.receiveSignalStream=de})}createRTCPeerConnection(D){var H;return Ue(this,void 0,void 0,function*(){const X=(H=this.config.alternateRTCPeerConnection)!==null&&H!==void 0?H:window.RTCPeerConnection;if(!X)throw function(){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||_t();try{return new X({iceServers:D})}catch(ie){throw g.a.debug(`Failed to create RTCPeerConnection: ${this.rtcInstancesConstructed} total allocated`),ie}})}closeConnections(D){return Ue(this,void 0,void 0,function*(){const H=yield O(D.map(X=>Ue(this,void 0,void 0,function*(){yield X.close()})));for(const X of H)g.a.warn("Request to close session failed",{error:X})})}getActiveConnection(D){return this.getConnections().find(H=>H.getRemotePeerId()===D&&H.isActive())}update(){var D;return Ue(this,void 0,void 0,function*(){if(this.localConnections=this.localConnections.filter(ye=>ye.isActive()),this.config.lanOnlyMode)return;const{signalingClient:H}=this.config;if(!this.localPeer||!this.receiveSignalStream||!this.iceServers){const ye=[];return this.localPeer||ye.push(this.createPeer()),this.iceServers||ye.push(this.updateIceServers()),yield Promise.all(ye),void(this.receiveSignalStream||(yield this.createReceiveSignalStream()))}yield this.closeConnections(this.connections.filter(ye=>!ye.isActive())),this.connections=this.connections.filter(ye=>ye.isActive());const{localPeer:X}=this,ie=this.connections.filter(ye=>ye.getSessionId).map(ye=>p(ye.getSessionId()));X.setSessionIdsList(ie);const oe=new ee.RefreshPeerRequest;oe.setPeer(X);try{yield S.withDeadline(H.refreshPeer(oe,yield this.getMetadata({})),this.grpcCallDeadline)}catch(ye){ye.code===ne.StatusCode.NOT_FOUND?(g.a.warn("Peer expired, creating new peer",{peerId:X.getPeerId()}),yield this.reset()):g.a.warn("Error calling RefreshPeer",{error:ye})}const de=yield this.getPeers();for(const ye of this.connections)ye.setRemoteDeviceId((D=de.find(be=>be.id===ye.getRemotePeerId()))===null||D===void 0?void 0:D.deviceId)})}reset(){return Ue(this,void 0,void 0,function*(){yield this.closeConnections(this.connections),this.connections=[],this.isOutgoingConnection=new Map,yield this.createPeer(),yield this.createReceiveSignalStream()})}updateIceServers(){return Ue(this,void 0,void 0,function*(){if(this.config.lanOnlyMode)return;const{iceServersLastUpdate:D,iceServersTtl:H}=this,X=new Date().getTime();if(!D||X-D>H)try{const ie=(yield S.withDeadline(this.config.signalingClient.getIceServers(new ee.GetIceServersRequest,yield this.getMetadata({})),this.grpcCallDeadline)).getIceServers();this.iceServers=JSON.parse(ie),this.iceServersLastUpdate=X}catch(ie){g.a.warn("Error in updateIceServers",{error:ie})}})}setupHandlers(D){const{peerConnection:H}=D,X=D.getSessionCreatedTimestamp();H.onconnectionstatechange=()=>Ue(this,void 0,void 0,function*(){const ie=H.connectionState;if(!X)return;const oe=D.getRemoteDeviceId();switch(ie){case"connected":y.aggregate("rtc-connect-time",new Date().getTime()-X,Object.assign({},oe?{deviceId:oe}:{}));break;case"failed":y.increment("rtc-connect-failed",Object.assign({},oe?{deviceId:oe}:{}))}})}getMetadata(D){return Ue(this,void 0,void 0,function*(){if(this.config.lanOnlyMode)throw new Error("getMetadata method cannot be called in local-only mode");const{getToken:H}=this.config,{grpcCallDeadline:X}=this,{hasDeadline:ie}=D,oe=ie===!1?void 0:new Date().getTime()+X;try{return{authorization:yield H(),deadline:oe}}catch(de){throw g.a.error("getToken() failed",{error:de}),new Error("Cannot get authorization token")}})}}var rt=n(10),ot=n(11),jt=function(pe,D,H,X){return new(H||(H=Promise))(function(ie,oe){function de(ce){try{be(X.next(ce))}catch(le){oe(le)}}function ye(ce){try{be(X.throw(ce))}catch(le){oe(le)}}function be(ce){var le;ce.done?ie(ce.value):(le=ce.value,le instanceof H?le:new H(function(Re){Re(le)})).then(de,ye)}be((X=X.apply(pe,D||[])).next())})};class pt{constructor(D,H){this.sessionId=D,this.connection=H,this.sentMessagesCounts=new Map,this.receivedMessagesCounts=new Map,this.sessionId=D,this.connection=H}incrementMessageSent(D){const H=Ie(D.header.stream);this.sentMessagesCounts.set(H,(this.sentMessagesCounts.get(H)||0)+1)}incrementMessageReceived(D){const H=Ie(D.header.stream);this.receivedMessagesCounts.set(H,(this.receivedMessagesCounts.get(H)||0)+1)}uploadMetrics(){return jt(this,void 0,void 0,function*(){const{sessionId:D}=this,H=yield this.connection.peerConnection.getStats(),X={};H.forEach(oe=>X[oe.id]=oe),g.a.debug("rtc-stats",Object.assign(Object.assign({},X),{sessionId:D}));const ie=[...new Set(Array.from(this.sentMessagesCounts.keys()).concat(Array.from(this.receivedMessagesCounts.keys())))].reduce((oe,de)=>{const ye=this.sentMessagesCounts.get(de),be=this.receivedMessagesCounts.get(de);return Object.assign(Object.assign({},oe),{[`${de}-sent`]:ye,[`${de}-received`]:be})},{sessionId:D});g.a.debug("rtc-message-report",ie)})}}function Ct(pe,D){return Ie(pe)===Ie(D)}var ut=function(pe,D,H,X){return new(H||(H=Promise))(function(ie,oe){function de(ce){try{be(X.next(ce))}catch(le){oe(le)}}function ye(ce){try{be(X.throw(ce))}catch(le){oe(le)}}function be(ce){var le;ce.done?ie(ce.value):(le=ce.value,le instanceof H?le:new H(function(Re){Re(le)})).then(de,ye)}be((X=X.apply(pe,D||[])).next())})};class Tt{constructor(D,H){this.peerConnection=D,this.config=H,this.connectTimeoutMs=10*c.a.second,this.gatherIceTimeoutMs=5*c.a.second,this.pingUpdateTimeoutMs=2*c.a.second,this.streamLatestTimestamp=new Map,this.closeCalled=!1,this.connectCalled=!1,this.sentOffer=!1,this.receivedIceCandidate=!1;const{isOffer:X}=H;X?this.initializeChannels(D):D.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 pt(this.getSessionId(),this)}connect(){return ut(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(()=>ut(this,void 0,void 0,function*(){this.isReady()||(g.a.warn("RTC connect timed out, closing connection"),yield this.close())}),this.connectTimeoutMs);const{peerConnection:D,config:{isOffer:H,sessionId:X}}=this;if(H){const ie=yield D.createOffer();yield D.setLocalDescription(ie)}H&&(this.gatherIceTimeout=setTimeout(()=>ut(this,void 0,void 0,function*(){this.sentOffer||(g.a.warn("ICE gathering timed out"),this.receivedIceCandidate?(g.a.warn("Attempting to connect with partial ICE candidate pool"),yield this.sendOffer()):yield this.close())}),this.gatherIceTimeoutMs),D.onicecandidate=ie=>ut(this,void 0,void 0,function*(){ie.candidate?this.receivedIceCandidate=!0:yield this.sendOffer()}),D.onicegatheringstatechange=()=>ut(this,void 0,void 0,function*(){D.iceGatheringState==="complete"&&(yield this.sendOffer())}),D.onnegotiationneeded=()=>{g.a.debug("Negotiation needed",{sessionId:X})})})}handleSignal(D){return ut(this,void 0,void 0,function*(){const{peerConnection:H,config:{sessionId:X,sendSignal:ie}}=this,{description:oe}=JSON.parse(D.payload);if(g.a.debug("Handling signal",{sessionId:X,description:JSON.stringify(oe)}),oe)if(H.signalingState!=="stable"||H.connectionState!=="connected")if(H.remoteDescription)g.a.warn(`Received SDP signal during negotiation when remote description is already set: ${JSON.stringify(D)}`);else if(oe.type==="offer"){yield H.setRemoteDescription(oe);const de=yield H.createAnswer();yield H.setLocalDescription(de),yield ie({payload:JSON.stringify({description:de})})}else oe.type==="answer"&&(yield H.setRemoteDescription(oe));else g.a.warn(`Received SDP signal when signaling is stable and connected: ${JSON.stringify(D)}`);else g.a.warn(`Received non-SDP signal: ${JSON.stringify(D)}`)})}send(D,H){const X=this.getChannelFromLabel(H.channelLabel);X?this.sendOnChannel(X,D):g.a.warn("Send called with unexpected channel label",{channelLabel:H.channelLabel})}controlRemoteStream(D){this.sendSystemMessage(p(this.reliableStreamChannel),{type:"stream-control",streamControl:D})}isActive(){return new Set(["new","connecting","connected"]).has(this.peerConnection.connectionState)}isReady(){const{peerConnection:D,latestTtlStreamChannel:H,reliableStreamChannel:X,latestTryOnceStreamChannel:ie}=this;return!!(X&&H&&ie)&&D.connectionState==="connected"&&X.readyState==="open"&&H.readyState==="open"&&ie.readyState==="open"}isClosed(){const{peerConnection:D,reliableStreamChannel:H,latestTryOnceStreamChannel:X,latestTtlStreamChannel:ie}=this;return!(D.connectionState!=="closed"||H!==void 0&&H.readyState!=="closed"||X!==void 0&&X.readyState!=="closed"||ie!==void 0&&ie.readyState!=="closed")}needsClosing(){const{peerConnection:D,latestTtlStreamChannel:H,reliableStreamChannel:X,latestTryOnceStreamChannel:ie}=this;if(this.isClosed())return!1;const oe=new Set(["closing","closed"]),de=ye=>ye&&oe.has(ye.readyState);return Ye(D)||de(H)||de(X)||de(ie)}close(){return ut(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(D){this.latestTtlStreamChannel=D.createDataChannel("stream.latest-ttl",k),this.reliableStreamChannel=D.createDataChannel("stream.reliable",J),this.latestReliableStreamChannel=D.createDataChannel("stream.latest-reliable",K),this.latestTryOnceStreamChannel=D.createDataChannel("stream.latest-try-once",re),this.setupChannel(this.latestTtlStreamChannel),this.setupChannel(this.reliableStreamChannel),this.setupChannel(this.latestReliableStreamChannel),this.setupChannel(this.latestTryOnceStreamChannel)}sendOffer(){return ut(this,void 0,void 0,function*(){if(this.sentOffer||(this.sentOffer=!0,Ye(this.peerConnection)))return;const{peerConnection:D,config:{sendSignal:H}}=this,X=yield D.createOffer();yield D.setLocalDescription(X);const ie={payload:JSON.stringify({description:X})};yield H(ie)})}getChannelFromLabel(D){switch(D){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(D,H){let X;try{X=Object(T.encode)(JSON.stringify(H))}catch(ie){return void g.a.warn("Failed to encode RTC message",{error:ie})}try{D.send(X),this.sessionMetrics.incrementMessageSent(H)}catch(ie){g.a.warn("Failed to send message to channel",{error:ie,channel:D.label})}}channelNotRecognized(D){return D!==this.latestTtlStreamChannel&&D!==this.latestReliableStreamChannel&&D!==this.latestTryOnceStreamChannel&&D!==this.reliableStreamChannel}setupChannel(D){D.onmessage=H=>{if(this.channelNotRecognized(D))return void g.a.warn("Received message on unrecognized data channel.");let X;try{X=JSON.parse(Object(T.decode)(H.data))}catch(ie){return void g.a.warn("Received unparseable RTC message",{error:ie,channel:D.label})}if(this.lastMessageTimestamp=new Date().getTime(),X=nt(X),this.sessionMetrics.incrementMessageReceived(X),!this.handleSystemMessage(D,X)){if(!this.hasCapabilities(X))return void g.a.warn("Received RTC message that was not within the capability scope of the connection.");(D===this.latestTryOnceStreamChannel||D===this.latestTtlStreamChannel||D===this.latestReliableStreamChannel)&&!this.isLatestMessage(X)||this.config.receive(this.config.remotePeer.id,X)}},D.onerror=H=>{g.a.warn(`Channel error: ${H.error}`,{error:H.error,sessionId:this.getSessionId(),channelLabel:D.label})},D.onopen=()=>{g.a.debug("Channel opened",{sessionId:this.getSessionId(),channelLabel:D.label})},D.onclose=()=>{const H={bufferedAmount:D.bufferedAmount,sessionId:this.getSessionId(),channelLabel:D.label};this.closeCalled===!1?g.a.debug("Unexpected channel closed",H):g.a.debug("Channel closed",H)}}handleSystemMessage(D,H){switch(H.header.stream.streamType){case"ping":return this.sendSystemMessage(D,{type:"pong",timestamp:p(H.payload.ping)}),!0;case"pong":{const X=new Date().getTime()-p(H.payload.pong);return this.pingTimeMs=X,y.aggregate("rtc-ping-time",X),!0}case"stream-control":return!0;default:return!1}}sendSystemMessage(D,H){if(D.readyState!=="open")return;const X={entityId:p(this.config.localPeer.deviceId||this.config.localPeer.userId),streamName:`$.${H.type}`,streamType:H.type};let ie;switch(H.type){case"ping":ie={ping:new Date().getTime()};break;case"pong":ie={pong:H.timestamp};break;case"stream-control":ie={streamControl:H.streamControl}}this.sendOnChannel(D,De(X,ie))}hasCapabilities(D){var H,X;const{localPeer:ie,remotePeer:oe}=this.config,de=(H=ie.capabilitySet.streaming)===null||H===void 0?void 0:H.streams,ye=de&&de.some(le=>le.receive&&Ct(le.stream,D.header.stream)),be=(X=oe.capabilitySet.streaming)===null||X===void 0?void 0:X.streams,ce=be&&be.some(le=>le.send&&Ct(le.stream,D.header.stream));return ye||ce}isLatestMessage(D){const H=Ie(D.header.stream),X=(this.streamLatestTimestamp.get(H)||0)<=D.header.created;return X&&this.streamLatestTimestamp.set(H,D.header.created),X}}var Fe=function(pe,D,H,X){return new(H||(H=Promise))(function(ie,oe){function de(ce){try{be(X.next(ce))}catch(le){oe(le)}}function ye(ce){try{be(X.throw(ce))}catch(le){oe(le)}}function be(ce){var le;ce.done?ie(ce.value):(le=ce.value,le instanceof H?le:new H(function(Re){Re(le)})).then(de,ye)}be((X=X.apply(pe,D||[])).next())})};class Rt{constructor(D){this.config=D,this.connections=[],this.connectingSessions=new Map,this.rtcInstancesConstructed=0,this.updateInterval=d({func:()=>Fe(this,void 0,void 0,function*(){try{yield this.update()}catch(H){g.a.warn("RTC update failed",{error:H})}}),delay:250*c.a.millisecond,immediate:!0}),this.localPeer=this.createPeer()}send(D,H,X){const ie=this.getActiveConnection(D);ie?ie.isReady()?ie.send(H,X):g.a.warn("Attempted to send with an active connection to that peer which was not yet ready."):g.a.warn("Attempted to send with no active connection to that peer.")}controlRemoteStream(D,H){const X=this.getActiveConnection(D);X?X.isReady()?X.controlRemoteStream(H):g.a.warn("Attempted to control remote stream with an active connection to that peer which was not yet ready."):g.a.warn("Attempted to control remote stream with no active connection to that peer.")}connect(D){return Fe(this,void 0,void 0,function*(){const H=yield this.getLocalPeer();if(this.getActiveConnection(D))return void g.a.warn("Attempted to connect to peer with an already active connection.");let X;try{X=yield this.config.signalingClient.createSession(yield this.config.getToken(),{offerPeerId:H.id,answerPeerId:D})}catch(ie){Object(ot.a)(ie,rt.a,oe=>oe.statusCode===404),g.a.warn("Attempted to connect to peer that does not exist.")}if(X)for(this.connectingSessions.set(X.id,new Date().getTime()),yield this.connectToSession(X);;)switch(yield Object(u.a)(.1),this.getConnectionStatus(D)){case"connecting":continue;case"connected":return X.id;case"disconnected":return}})}getConnectionStatus(D){const H=this.getActiveConnection(D);return H?H.isReady()?"connected":"connecting":"disconnected"}getIceMode(D){const H=this.getActiveConnection(D);if(H)return H.iceMode}disconnect(D){return Fe(this,void 0,void 0,function*(){const H=this.getActiveConnection(D);H&&(yield this.closeConnection(H))})}getLocalPeer(){return Fe(this,void 0,void 0,function*(){return yield this.localPeer})}getPeers(){return Fe(this,void 0,void 0,function*(){return yield this.config.signalingClient.getPeers(yield this.config.getToken())})}getPing(D){const H=this.getActiveConnection(D);if(H)return H.getPing();g.a.warn("Attempted to get ping time from inactive peer.")}getLastMessageTimestamp(D){const H=this.getActiveConnection(D);if(H)return H.getLastMessageTimestamp();g.a.warn("Attempted to get ping time from inactive peer.")}shutdown(){return Fe(this,void 0,void 0,function*(){yield this.updateInterval.stop();const D=this.connections;this.connections=[],yield this.closeConnections(D)})}closeConnection(D){return Fe(this,void 0,void 0,function*(){this.connectingSessions.delete(D.getSessionId()),yield D.close();try{yield this.config.signalingClient.deleteSession(yield this.config.getToken(),D.getSessionId())}catch(H){Object(ot.a)(H,rt.a,X=>X.statusCode===404)}})}getSessions(){return Fe(this,void 0,void 0,function*(){const D=yield this.getLocalPeer();return(yield this.config.signalingClient.getSessions(yield this.config.getToken())).filter(H=>H.offer.peer.id===D.id||H.answer.peer.id===D.id)})}createPeer(){return Fe(this,void 0,void 0,function*(){return yield this.config.signalingClient.createPeer(yield this.config.getToken(),{capabilitySet:this.config.capabilitySet||{}})})}createRTCPeerConnection(D={}){return Fe(this,void 0,void 0,function*(){const H=this.config.alternateRTCPeerConnection||RTCPeerConnection;this.rtcInstancesConstructed++,this.rtcInstancesConstructed%20||_t();try{return new H(Object.assign({iceServers:yield this.config.signalingClient.getIceServers(yield this.config.getToken())},D))}catch(X){throw g.a.debug(`Failed to create RTCPeerConnection: ${this.rtcInstancesConstructed} total allocated`),X}})}closeConnections(D){return Fe(this,void 0,void 0,function*(){const H=yield O(D.map(X=>Fe(this,void 0,void 0,function*(){yield this.closeConnection(X)})));for(const X of H)g.a.warn("Request to close session failed",{error:X})})}reset(){return Fe(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(D){return this.connections.find(H=>H.getRemotePeer().id===D&&H.isActive())}update(){return Fe(this,void 0,void 0,function*(){const D=yield this.getLocalPeer();try{yield this.config.signalingClient.refreshPeer(yield this.config.getToken(),D.id)}catch(H){Object(ot.a)(H,rt.a,X=>X.statusCode===404),g.a.warn("Peer expired, creating new peer",{peerId:D.id}),yield this.reset()}yield this.handleSessions(yield this.getSessions())})}handleSessions(D){return Fe(this,void 0,void 0,function*(){yield this.syncConnectionsAndSessions(D);const H=D.map(X=>({session:X,connection:this.connections.find(ie=>ie.getSessionId()===X.id)}));yield Promise.all(H.map(({session:X,connection:ie})=>Fe(this,void 0,void 0,function*(){return yield this.maintainConnection(X,ie)})))})}syncConnectionsAndSessions(D){return Fe(this,void 0,void 0,function*(){const H=new Set(D.map(oe=>oe.id)),X=oe=>H.has(oe.getSessionId())||this.connectingSessions.has(oe.getSessionId());this.connections=this.connections.filter(oe=>X(oe));const ie=this.connections.filter(oe=>!X(oe)||oe.needsClosing());yield Promise.all(ie.map(oe=>Fe(this,void 0,void 0,function*(){yield this.closeConnection(oe)})))})}maintainConnection(D,H){return Fe(this,void 0,void 0,function*(){const X=yield this.getLocalPeer(),ie=D.offer.peer.id===X.id;if(H){if(H.isReady())try{yield this.config.signalingClient.refreshSession(yield this.config.getToken(),D.id)}catch(oe){Object(ot.a)(oe,rt.a,de=>de.statusCode===404),g.a.debug("Refresh session not found",{sessionId:D.id})}else if(H.isActive())try{yield this.consumeSignals(H)}catch(oe){g.a.warn("Failed to ingest signals, closing connection",{error:oe}),yield this.closeConnection(H)}}else{if(ie)return;yield this.connectToSession(D)}})}connectToSession(D){return Fe(this,void 0,void 0,function*(){const H=yield this.getLocalPeer(),X=D.offer.peer.id===H.id,ie=yield this.createRTCPeerConnection(),oe=new Tt(ie,{localPeer:X?D.offer.peer:D.answer.peer,remotePeer:X?D.answer.peer:D.offer.peer,sessionId:D.id,isOffer:X,sendSignal:de=>this.sendSignal(D.id,de),receive:(de,ye)=>this.config.receive(de,ye)});if(this.connections.find(de=>de.getSessionId()===D.id))return g.a.warn("connectToSession called on a session that already has a connection.",{sessionId:D.id}),void(yield oe.close());this.setupHandlers(oe),this.connections.push(oe);try{yield oe.connect()}catch(de){g.a.warn("Failed to handle negotiation, closing connection",{error:de}),yield this.closeConnection(oe)}})}setupHandlers(D){const{peerConnection:H}=D,X=D.getSessionId();H.onconnectionstatechange=()=>Fe(this,void 0,void 0,function*(){const ie=this.connectingSessions.get(X);if(ie===void 0)return;const oe=H.connectionState;switch(Ye(H)&&this.connectingSessions.delete(X),oe){case"connected":{this.connectingSessions.delete(X);const de=new Date().getTime()-ie;y.aggregate("rtc-connect-time",de);break}case"failed":y.increment("rtc-connect-failed"),yield this.closeConnection(D)}})}consumeSignals(D){return Fe(this,void 0,void 0,function*(){let H=[];try{H=yield this.config.signalingClient.takeSignals(yield this.config.getToken(),D.getSessionId())}catch(X){Object(ot.a)(X,rt.a,ie=>ie.statusCode===404)}for(const X of H)yield D.handleSignal(X)})}sendSignal(D,H){return Fe(this,void 0,void 0,function*(){try{yield this.config.signalingClient.addSignals(yield this.config.getToken(),D,{signals:[H]})}catch(X){Object(ot.a)(X,rt.a,ie=>ie.statusCode===404)}})}}},function(e,t,n){var r={randomUUID:typeof crypto<"u"&&crypto.randomUUID&&crypto.randomUUID.bind(crypto)};let i;const s=new Uint8Array(16);function l(){if(!i&&(i=typeof crypto<"u"&&crypto.getRandomValues&&crypto.getRandomValues.bind(crypto),!i))throw new Error("crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported");return i(s)}const o=[];for(let u=0;u<256;++u)o.push((u+256).toString(16).slice(1));function c(u,f=0){return(o[u[f+0]]+o[u[f+1]]+o[u[f+2]]+o[u[f+3]]+"-"+o[u[f+4]]+o[u[f+5]]+"-"+o[u[f+6]]+o[u[f+7]]+"-"+o[u[f+8]]+o[u[f+9]]+"-"+o[u[f+10]]+o[u[f+11]]+o[u[f+12]]+o[u[f+13]]+o[u[f+14]]+o[u[f+15]]).toLowerCase()}t.a=function(u,f,E){if(r.randomUUID&&!f&&!u)return r.randomUUID();const w=(u=u||{}).random||(u.rng||l)();if(w[6]=15&w[6]|64,w[8]=63&w[8]|128,f){E=E||0;for(let h=0;h<16;++h)f[E+h]=w[h];return f}return c(w)}},,function(e,t,n){n.r(t),n.d(t,"LogClient",function(){return o});var r=n(28),i=n(11),s=n(10),l=function(c,u,f,E){return new(f||(f=Promise))(function(w,h){function g(j){try{R(E.next(j))}catch(F){h(F)}}function b(j){try{R(E.throw(j))}catch(F){h(F)}}function R(j){var F;j.done?w(j.value):(F=j.value,F instanceof f?F:new f(function(M){M(F)})).then(g,b)}R((E=E.apply(c,u||[])).next())})};class o extends r.a{log(u){return l(this,void 0,void 0,function*(){const f=o.token;try{yield this.fetch("logs",{token:f,method:"POST",body:JSON.stringify({logs:u}),allowUnsafeRetries:!0})}catch(E){Object(i.a)(E,s.a,w=>w.statusCode===401&&f!==void 0),o.token===f&&delete o.token,yield this.log(u)}})}}}])})})(dist);function defined(e,t){if(e!==void 0)return e;throw new Error(t||"Value is undefined")}let FORMANT_API_URL="https://api.formant.io";typeof window<"u"&&(FORMANT_API_URL=window.FORMANT_API_URL||FORMANT_API_URL);let urlParams$2=new URLSearchParams("");typeof window<"u"&&(urlParams$2=new URLSearchParams(window.location.search));const envDev=urlParams$2.get("formant_dev");envDev&&(FORMANT_API_URL="https://api-dev.formant.io");const envStage=urlParams$2.get("formant_stage");envStage&&(FORMANT_API_URL="https://api-stage.formant.io");const envLocal=urlParams$2.get("formant_local");envLocal&&(FORMANT_API_URL="https://api.formant.local");const millisecond=1,second=1e3,minute=60*second,hour=60*minute,day=24*hour,week=7*day,month=30*day,year=365*day,duration={millisecond,second,minute,hour,day,week,month,year};function filterDataByType(e,t){return e.filter(n=>t.includes(n.type))}function filterDataByTime(e,t,n){const r=t.getTime(),i=n.getTime();return e.map(s=>({...s,points:s.points.filter(([l])=>l>=r&&l<i)})).filter(({points:s})=>s.length>0)}function fork(e){}class StoreCache{constructor({capacity:t,timeout:n}={}){Ae(this,"entries",new Map);Ae(this,"metadata",new Map);Ae(this,"capacity");Ae(this,"timeout");this.capacity=t||1e4,this.timeout=n||duration.minute}get(t,n){const r=this.keyToCacheKey(t),i=this.entries.get(r),s=this.metadata.get(r);return(i===void 0||s&&(s==null?void 0:s.expiration.getTime())<Date.now())&&!(s!=null&&s.generating)&&n&&this.generate(t,n()),i===void 0&&s&&s.lastValue!==void 0?s.lastValue:i}set(t,n){const r=this.keyToCacheKey(t);this.metadata.set(r,{generating:!1,expiration:new Date(Date.now()+this.timeout),lastValue:n}),this.entries.set(r,n),this.metadata.size>this.capacity&&this.deleteOldestEntry()}clear(){this.entries.clear(),[...this.metadata.values()].forEach(t=>t.generating=!1)}clearKey(t){this.metadata.delete(t),this.entries.delete(t)}keyToCacheKey(t){return JSON.stringify(t)}deleteOldestEntry(){if(this.metadata.size<1)return;const[t]=[...this.metadata.entries()].reduce(([n,r],[i,s])=>s.expiration.getTime()<r.expiration.getTime()?[i,s]:[n,r]);this.clearKey(t)}generate(t,n){const r=this.keyToCacheKey(t),i=this.metadata.get(r)||{};this.metadata.set(r,{...i,generating:!0,expiration:new Date(Date.now()+this.timeout)}),setTimeout(()=>{n.then(s=>{const l=this.metadata.get(r);!(l!=null&&l.generating)||this.set(t,s)})},0)}}class QueryStore{constructor(){Ae(this,"queryStoreCache",new StoreCache({capacity:1e4,timeout:20*duration.second}));Ae(this,"liveQueryStoreCache",new StoreCache({capacity:1e4,timeout:200*duration.millisecond}))}moduleQuery(t,n,r,i,s,l=!1){const o={...t,names:[...n],types:[...r]},c=this.query(o,i,s,l);return c===void 0||c==="too much data"?c:filterDataByType(c,r)}query(t,n,r,i=!1){const s={...t,start:dateFns.startOfMinute(n).toISOString(),end:i?r.toISOString():dateFns.addMinutes(dateFns.roundToNearestMinutes(r),1).toISOString(),latestOnly:i},l=r>dateFns.addSeconds(new Date,-20);let o;return l?o=this.liveQueryCache(s):o=this.queryCache(s),!o||o==="too much data"||i?o:filterDataByTime(o,n,r)}queryCache(t){return this.queryStoreCache.get(t,async()=>{try{return await Fleet.queryTelemetry(t)}catch(n){throw n}})}liveQueryCache(t){return this.liveQueryStoreCache.get(t,async()=>{try{return await Fleet.queryTelemetry(t)}catch(n){throw n}})}}const queryStore=new QueryStore;class App{static sendAppMessage(t){window.parent.postMessage(t,"*")}static getCurrentModuleContext(){let t=new URLSearchParams("");return typeof window<"u"&&(t=new URLSearchParams(window.location.search)),t.get("module")}static async getCurrentModuleConfiguration(){let t=new URLSearchParams("");typeof window<"u"&&(t=new URLSearchParams(window.location.search));const n=t.get("configuration");return n===null||n.trim()===""?void 0:(await(await fetch(`${FORMANT_API_URL}/v1/admin/module-configurations/`+n,{headers:{"Content-Type":"application/json",Authorization:"Bearer "+Authentication.token}})).json()).configuration}static isModule(){return this.getCurrentModuleContext()!==null}static goToTime(t){this.sendAppMessage({type:"go_to_time",time:t.getTime()})}static goToDevice(t){this.sendAppMessage({type:"go_to_device",deviceId:t})}static showMessage(t){this.sendAppMessage({type:"show_message",message:t})}static requestModuleData(){const t=this.getCurrentModuleContext();if(!t)throw new Error("No module context");this.sendAppMessage({type:"request_module_data",module:t})}static setModuleDateTimeRange(t,n){const r=this.getCurrentModuleContext();if(!r)throw new Error("No module context");this.sendAppMessage({type:"set_module_data_time_range",module:r,before:t,after:n||0})}static refreshAuthToken(){const t=this.getCurrentModuleContext();if(!t)throw new Error("No module context");this.sendAppMessage({type:"refresh_auth_token",module:t})}static sendChannelData(t,n){const r=this.getCurrentModuleContext();if(!r)throw new Error("No module context");this.sendAppMessage({type:"send_channel_data",source:r,channel:t,data:n})}static setupModuleMenus(t){const n=this.getCurrentModuleContext();if(!n)throw new Error("No module context");this.sendAppMessage({type:"setup_module_menus",module:n,menus:t})}static addMenuListener(t){window.addEventListener("message",n=>{const r=n.data;r.type==="module_menu_item_clicked"&&t(r.menu)})}static addAccessTokenRefreshListener(t){window.addEventListener("message",n=>{const r=n.data;r.type==="auth_token"&&t(r.token)})}static addModuleDataListener(t){const n=this.getCurrentModuleContext();n&&this.sendAppMessage({type:"request_module_data",module:n}),window.addEventListener("message",r=>{const i=r.data;i.type==="module_data"&&t({streams:i.streams,time:i.time,queryRange:i.queryRange})})}static addOverviewDeviceListener(t){this.sendAppMessage({type:"request_devices"});const n=r=>{const i=r.data;i.type==="overview_devices"&&t(i.data)};return window.addEventListener("message",n),()=>window.removeEventListener("message",n)}static addStreamListener(t,n,r){const i=s=>{const l=s.data;if(l.type==="module_data"){const{start:o,end:c}=l.queryRange;r(queryStore.moduleQuery({},t,n,new Date(o),new Date(c),!1))}};return window.addEventListener("message",i),()=>window.removeEventListener("message",i)}static addModuleConfigurationListener(t){window.addEventListener("message",n=>{const r=n.data;r.type==="module_configuration"&&t(r)})}static addChannelDataListener(t,n){window.addEventListener("message",r=>{const i=r.data;i.type==="channel_data"&&i.channel===t&&n({source:i.source,data:i.data})})}static async prompt(t,n){return new Promise(r=>{const i=Math.random().toString();this.sendAppMessage({type:"prompt",promptId:i,schema:t,okText:n==null?void 0:n.okText,cancelText:n==null?void 0:n.cancelText});const s=l=>{const o=l.data;o.type==="prompt_response"&&o.promptId===i&&r(o.data),window.removeEventListener("message",s)};window.addEventListener("message",s)})}}const je=class{static async login(t,n){try{const r=await fetch(`${FORMANT_API_URL}/v1/admin/auth/login`,{method:"POST",body:JSON.stringify({email:t,password:n}),headers:{"Content-Type":"application/json"}}),i=await r.json();if(r.status!==200)throw new Error(i.message);return await je.loginWithToken(i.authentication.accessToken,i.authentication.refreshToken),i.authentication}catch(r){return je.waitingForAuth.forEach(i=>i(!1)),je.waitingForAuth=[],Promise.reject(r)}}static async loginWithToken(t,n){const r=JSON.parse(atob(t.split(".")[1]));try{let i;if(je.isShareToken=r["formant:claims"]&&r["formant:claims"].type=="share",r["formant:claims"]&&(je.currentOrganization=r["formant:claims"].organizationId),r["custom:organization_id"]&&(je.currentOrganization=r["custom:organization_id"]),je.isShareToken||(i=r.sub),r["formant:claims"]&&r["formant:claims"].userId&&(i=r["formant:claims"].userId),i){const s=await fetch(`${FORMANT_API_URL}/v1/admin/users/${i}`,{method:"GET",headers:{"Content-Type":"application/json",Authorization:"Bearer "+t}}),l=await s.json();if(s.status!==200)throw new Error(l.message);je.currentUser=l}je.token=t,je.waitingForAuth.forEach(s=>s(!0))}catch(i){console.error(i),je.waitingForAuth.forEach(s=>s(!1))}je.waitingForAuth=[],n&&(je.refreshToken=n,setInterval(async()=>{if(je.refreshToken){const s=await(await fetch(`${FORMANT_API_URL}/v1/admin/auth/refresh`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({refreshToken:je.refreshToken})})).json();je.token=s.authentication.accessToken}},1e3*60*60))}static isAuthenticated(){return je.token!==void 0}static getCurrentUser(){return je.currentUser}static async waitTilAuthenticated(){return je.token!==void 0?!0:new Promise(t=>{je.waitingForAuth.push(function(n){t(n)})})}static async listenForRefresh(){App.addAccessTokenRefreshListener(t=>{this.loginWithToken(t)}),setInterval(async()=>{App.refreshAuthToken()},1e3*60*60)}static async forgotPassword(t){await fetch(`${FORMANT_API_URL}/v1/admin/auth/forgot-password`,{method:"POST",body:JSON.stringify({email:t}),headers:{"Content-Type":"application/json"}})}static async confirmForgotPassword(t){return(await fetch(`${FORMANT_API_URL}/v1/admin/auth/confirm-forgot-password`,{method:"POST",body:JSON.stringify(t),headers:{"Content-Type":"application/json"}})).ok}static async respondToNewPasswordRequiredChallenge(t){return await(await fetch(`${FORMANT_API_URL}/v1/admin/auth/respond-to-new-password-required-challenge`,{method:"POST",body:JSON.stringify(t),headers:{"Content-Type":"application/json"}})).json()}static async loginWithGoogle(t){return await(await fetch(`${FORMANT_API_URL}/v1/admin/auth/login-google`,{method:"POST",body:JSON.stringify(t),headers:{"Content-Type":"application/json"}})).json()}static async refresh(t){const r=await(await fetch(`${FORMANT_API_URL}/v1/admin/auth/refresh`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({refreshToken:t})})).json();await je.loginWithToken(r.authentication.accessToken,t)}};let Authentication=je;Ae(Authentication,"token"),Ae(Authentication,"refreshToken"),Ae(Authentication,"currentUser"),Ae(Authentication,"currentOrganization"),Ae(Authentication,"isShareToken",!1),Ae(Authentication,"defaultDeviceId"),Ae(Authentication,"waitingForAuth",[]);function delay(e){return new Promise(t=>setTimeout(t,e))}class DataChannel{constructor(t){Ae(this,"ready",!1);Ae(this,"listeners",[]);Ae(this,"openListeners",[]);Ae(this,"closeListeners",[]);Ae(this,"errorListeners",[]);Ae(this,"binaryListeners",[]);Ae(this,"error");Ae(this,"decoder",new TextDecoder);this.dataChannel=t,this.dataChannel.binaryType="arraybuffer",this.dataChannel.onopen=()=>{this.ready=!0,this.openListeners.forEach(n=>n())},this.dataChannel.onclose=()=>{this.ready=!1,this.closeListeners.forEach(n=>n())},this.dataChannel.onerror=n=>{console.error(n),this.error="An error occurred in DataChannel",this.errorListeners.forEach(r=>r(n))},this.dataChannel.onmessage=n=>{this.listeners.forEach(r=>{const i=new Uint8Array(n.data),s=this.decoder.decode(i);r(s)}),this.binaryListeners.forEach(r=>{r(new Uint8Array(n.data))})}}addOpenListener(t){this.openListeners.push(t)}removeOpenListener(t){this.openListeners=this.openListeners.filter(n=>n!==t)}addCloseListener(t){this.closeListeners.push(t)}removeCloseListener(t){this.closeListeners=this.closeListeners.filter(n=>n!==t)}addErrorListener(t){this.errorListeners.push(t)}removeErrorListener(t){this.errorListeners=this.errorListeners.filter(n=>n!==t)}async waitTilReady(){return this.ready?!0:new Promise((n,r)=>{let i=window.setInterval(()=>{this.ready&&(window.clearInterval(i),n(!0)),this.error&&r(this.error)},10)})}send(t){if(!this.ready)throw new Error("Connection has been closed");this.dataChannel.send(t)}sendBinary(t){if(!this.ready)throw new Error("Connection has been closed");this.dataChannel.send(t)}addListener(t){this.listeners.push(t)}removeListener(t){const n=this.listeners.indexOf(t);if(n===-1)throw new Error("Could not find data channel listener to remove");if(this.error)throw new Error(this.error);this.listeners.splice(n,1)}addBinaryListener(t){this.binaryListeners.push(t)}removeBinaryListener(t){const n=this.binaryListeners.indexOf(t);if(n===-1)throw new Error("Could not find data channel listener to remove");if(this.error)throw new Error(this.error);this.binaryListeners.splice(n,1)}}class CaptureStream{constructor(t){Ae(this,"token");this.captureSession=t}async ingestJSON(t){if(!this.token){const r=await(await fetch(`${FORMANT_API_URL}/v1/admin/capture-sessions/${this.captureSession.code}/authenticate`,{method:"POST"})).json();this.token=r.token}await fetch(`${FORMANT_API_URL}/v1/ingest`,{method:"POST",body:JSON.stringify({deviceId:this.captureSession.deviceId,name:this.captureSession.streamName,type:"json",points:[[Date.now(),JSON.stringify(t)]]}),headers:{"Content-Type":"application/json",Authorization:"Bearer "+this.token}})}}class Manipulator{constructor(t,n){Ae(this,"currentListeners",[]);Ae(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){Ae(this,"channel");Ae(this,"requestIdToResponseMap",new Map);this.device=t,this.channel_name=n,this.timeout=r}addOpenListener(t){defined(this.channel,"channel not initalized").addOpenListener(t)}removeOpenListener(t){defined(this.channel,"channel not initalized").removeOpenListener(t)}addCloseListener(t){defined(this.channel,"channel not initalized").addCloseListener(t)}removeCloseListener(t){defined(this.channel,"channel not initalized").removeCloseListener(t)}addErrorListener(t){defined(this.channel,"channel not initalized").addErrorListener(t)}removeErrorListener(t){defined(this.channel,"channel not initalized").removeErrorListener(t)}}class BinaryRequestDataChannel extends RequestDataChannel{constructor(){super(...arguments);Ae(this,"RESPONSE_SUCCESS_BYTE",0);Ae(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 i=n.slice(0,16).toString();if(i.length===0)throw new Error("Invalid response");const s=n.slice(16);if(s.length===0)throw new Error("Invalid response");this.requestIdToResponseMap.has(i)&&this.requestIdToResponseMap.set(i,s)})}async request(n){if(this.channel||await this.initialize(),!this.channel)throw new Error("Failed to create channel");const{channel:r,requestIdToResponseMap:i,timeout:s}=this;await r.waitTilReady();const l=this.generateBinaryId(),o=l.toString();i.set(o,!0),r.sendBinary(new Uint8Array([...l,...n]));const c=new Date().getTime();for(;new Date().getTime()<c+s;)if(await delay(50),i.has(o)){const u=i.get(o);if(u!==!0){i.delete(o);const f=u[0]===this.RESPONSE_SUCCESS_BYTE,E=u.slice(1);if(f)return E;throw console.error({name:"AdapterError",message:this.decoder.decode(E)}),new Error("Binary request datachannel adapter error")}}throw i.delete(o),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:i,error:s}=n;if(!r)throw new Error("Invalid response");if(!i&&!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:i}=this;await n.waitTilReady();const s=this.generateTextId();r.set(s,!0),n.send(JSON.stringify({id:s,data:t}));const l=new Date().getTime();for(;new Date().getTime()<l+i;)if(await delay(50),r.has(s)){const o=r.get(s);if(o!==!0){r.delete(s);const{data:c,error:u}=o;if(c)return c;if(u)throw console.error({name:"AdapterError",message:u}),new Error("Text request datachannel adapter error")}}throw r.delete(s),console.error({name:"TimeoutError",message:`Request timed out after ${i/1e3} seconds`}),new Error("Text request datachannel request timed out")}}var domain;function EventHandlers(){}EventHandlers.prototype=Object.create(null);function EventEmitter(){EventEmitter.init.call(this)}EventEmitter.EventEmitter=EventEmitter,EventEmitter.usingDomains=!1,EventEmitter.prototype.domain=void 0,EventEmitter.prototype._events=void 0,EventEmitter.prototype._maxListeners=void 0,EventEmitter.defaultMaxListeners=10,EventEmitter.init=function(){this.domain=null,EventEmitter.usingDomains&&domain.active,(!this._events||this._events===Object.getPrototypeOf(this)._events)&&(this._events=new EventHandlers,this._eventsCount=0),this._maxListeners=this._maxListeners||void 0},EventEmitter.prototype.setMaxListeners=function e(t){if(typeof t!="number"||t<0||isNaN(t))throw new TypeError('"n" argument must be a positive number');return this._maxListeners=t,this};function $getMaxListeners(e){return e._maxListeners===void 0?EventEmitter.defaultMaxListeners:e._maxListeners}EventEmitter.prototype.getMaxListeners=function e(){return $getMaxListeners(this)};function emitNone(e,t,n){if(t)e.call(n);else for(var r=e.length,i=arrayClone(e,r),s=0;s<r;++s)i[s].call(n)}function emitOne(e,t,n,r){if(t)e.call(n,r);else for(var i=e.length,s=arrayClone(e,i),l=0;l<i;++l)s[l].call(n,r)}function emitTwo(e,t,n,r,i){if(t)e.call(n,r,i);else for(var s=e.length,l=arrayClone(e,s),o=0;o<s;++o)l[o].call(n,r,i)}function emitThree(e,t,n,r,i,s){if(t)e.call(n,r,i,s);else for(var l=e.length,o=arrayClone(e,l),c=0;c<l;++c)o[c].call(n,r,i,s)}function emitMany(e,t,n,r){if(t)e.apply(n,r);else for(var i=e.length,s=arrayClone(e,i),l=0;l<i;++l)s[l].apply(n,r)}EventEmitter.prototype.emit=function e(t){var n,r,i,s,l,o,c,u=t==="error";if(o=this._events,o)u=u&&o.error==null;else if(!u)return!1;if(c=this.domain,u){if(n=arguments[1],c)n||(n=new Error('Uncaught, unspecified "error" event')),n.domainEmitter=this,n.domain=c,n.domainThrown=!1,c.emit("error",n);else{if(n instanceof Error)throw n;var f=new Error('Uncaught, unspecified "error" event. ('+n+")");throw f.context=n,f}return!1}if(r=o[t],!r)return!1;var E=typeof r=="function";switch(i=arguments.length,i){case 1:emitNone(r,E,this);break;case 2:emitOne(r,E,this,arguments[1]);break;case 3:emitTwo(r,E,this,arguments[1],arguments[2]);break;case 4:emitThree(r,E,this,arguments[1],arguments[2],arguments[3]);break;default:for(s=new Array(i-1),l=1;l<i;l++)s[l-1]=arguments[l];emitMany(r,E,this,s)}return!0};function _addListener(e,t,n,r){var i,s,l;if(typeof n!="function")throw new TypeError('"listener" argument must be a function');if(s=e._events,s?(s.newListener&&(e.emit("newListener",t,n.listener?n.listener:n),s=e._events),l=s[t]):(s=e._events=new EventHandlers,e._eventsCount=0),!l)l=s[t]=n,++e._eventsCount;else if(typeof l=="function"?l=s[t]=r?[n,l]:[l,n]:r?l.unshift(n):l.push(n),!l.warned&&(i=$getMaxListeners(e),i&&i>0&&l.length>i)){l.warned=!0;var o=new Error("Possible EventEmitter memory leak detected. "+l.length+" "+t+" listeners added. Use emitter.setMaxListeners() to increase limit");o.name="MaxListenersExceededWarning",o.emitter=e,o.type=t,o.count=l.length,emitWarning(o)}return e}function emitWarning(e){typeof console.warn=="function"?console.warn(e):console.log(e)}EventEmitter.prototype.addListener=function e(t,n){return _addListener(this,t,n,!1)},EventEmitter.prototype.on=EventEmitter.prototype.addListener,EventEmitter.prototype.prependListener=function e(t,n){return _addListener(this,t,n,!0)};function _onceWrap(e,t,n){var r=!1;function i(){e.removeListener(t,i),r||(r=!0,n.apply(e,arguments))}return i.listener=n,i}EventEmitter.prototype.once=function e(t,n){if(typeof n!="function")throw new TypeError('"listener" argument must be a function');return this.on(t,_onceWrap(this,t,n)),this},EventEmitter.prototype.prependOnceListener=function e(t,n){if(typeof n!="function")throw new TypeError('"listener" argument must be a function');return this.prependListener(t,_onceWrap(this,t,n)),this},EventEmitter.prototype.removeListener=function e(t,n){var r,i,s,l,o;if(typeof n!="function")throw new TypeError('"listener" argument must be a function');if(i=this._events,!i)return this;if(r=i[t],!r)return this;if(r===n||r.listener&&r.listener===n)--this._eventsCount===0?this._events=new EventHandlers:(delete i[t],i.removeListener&&this.emit("removeListener",t,r.listener||n));else if(typeof r!="function"){for(s=-1,l=r.length;l-- >0;)if(r[l]===n||r[l].listener&&r[l].listener===n){o=r[l].listener,s=l;break}if(s<0)return this;if(r.length===1){if(r[0]=void 0,--this._eventsCount===0)return this._events=new EventHandlers,this;delete i[t]}else spliceOne(r,s);i.removeListener&&this.emit("removeListener",t,o||n)}return this},EventEmitter.prototype.removeAllListeners=function e(t){var n,r;if(r=this._events,!r)return this;if(!r.removeListener)return arguments.length===0?(this._events=new EventHandlers,this._eventsCount=0):r[t]&&(--this._eventsCount===0?this._events=new EventHandlers:delete r[t]),this;if(arguments.length===0){for(var i=Object.keys(r),s=0,l;s<i.length;++s)l=i[s],l!=="removeListener"&&this.removeAllListeners(l);return this.removeAllListeners("removeListener"),this._events=new EventHandlers,this._eventsCount=0,this}if(n=r[t],typeof n=="function")this.removeListener(t,n);else if(n)do this.removeListener(t,n[n.length-1]);while(n[0]);return this},EventEmitter.prototype.listeners=function e(t){var n,r,i=this._events;return i?(n=i[t],n?typeof n=="function"?r=[n.listener||n]:r=unwrapListeners(n):r=[]):r=[],r},EventEmitter.listenerCount=function(e,t){return typeof e.listenerCount=="function"?e.listenerCount(t):listenerCount$1.call(e,t)},EventEmitter.prototype.listenerCount=listenerCount$1;function listenerCount$1(e){var t=this._events;if(t){var n=t[e];if(typeof n=="function")return 1;if(n)return n.length}return 0}EventEmitter.prototype.eventNames=function e(){return this._eventsCount>0?Reflect.ownKeys(this._events):[]};function spliceOne(e,t){for(var n=t,r=n+1,i=e.length;r<i;n+=1,r+=1)e[n]=e[r];e.pop()}function arrayClone(e,t){for(var n=new Array(t);t--;)n[t]=e[t];return n}function unwrapListeners(e){for(var t=new Array(e.length),n=0;n<t.length;++n)t[n]=e[n].listener||e[n];return t}const urlParams$1=new URLSearchParams(window.location.search),rtcClientVersion=urlParams$1.get("rtc_client"),SessionType={Teleop:1,Observe:3};class Device extends EventEmitter{constructor(n,r,i){super();Ae(this,"rtcClient");Ae(this,"remoteDevicePeerId");Ae(this,"realtimeListeners",[]);Ae(this,"connectionMonitorInterval");Ae(this,"handleMessage",(n,r)=>{this.realtimeListeners.forEach(i=>i(n,r))});this.id=n,this.name=r,this.organizationId=i}async getLatestTelemetry(){return(await(await fetch(`${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(){let n=await fetch(`${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 i=r.state.reportedConfiguration.version;return n=await fetch(`${FORMANT_API_URL}/v1/admin/devices/${this.id}/configurations/${i}`,{method:"GET",headers:{"Content-Type":"application/json",Authorization:"Bearer "+Authentication.token}}),(await n.json()).document}async getFileUrl(n){return(await(await fetch(`${FORMANT_API_URL}/v1/admin/files/query`,{method:"POST",body:JSON.stringify({fileIds:[n]}),headers:{"Content-Type":"application/json",Authorization:"Bearer "+Authentication.token}})).json()).fileUrls}getRealtimeStatus(){if(this.rtcClient&&this.remoteDevicePeerId)return this.rtcClient.getConnectionStatus(this.remoteDevicePeerId);throw new Error(`Realtime connection hasn't been started for ${this.id}`)}getRealtimePing(){if(this.rtcClient&&this.remoteDevicePeerId)return this.rtcClient.getPing(this.remoteDevicePeerId);throw new Error(`Realtime connection hasn't been started for ${this.id}`)}async startRealtimeConnection(n){if(this.rtcClient)throw new Error(`Already created realtime connection to device ${this.id}`);{let r;if(rtcClientVersion==="1"?r=new distExports.RtcClientV1({signalingClient:new distExports.RtcSignalingClient(FORMANT_API_URL+"/v1/signaling"),getToken:async()=>defined(Authentication.token,"Realtime when user isn't authorized"),receive:this.handleMessage}):r=new distExports.RtcClient({signalingClient:new distExports.SignalingPromiseClient(FORMANT_API_URL,null,null),getToken:async()=>defined(Authentication.token,"Realtime when user isn't authorized"),receive:this.handleMessage,sessionType:n}),r.isReady)for(;!r.isReady();)await delay(100);const s=(await r.getPeers()).find(l=>l.deviceId===this.id);if(!s)throw new Error("Cannot find peer, is the robot offline?");for(this.remoteDevicePeerId=s.id,await r.connect(this.remoteDevicePeerId);r.getConnectionStatus(this.remoteDevicePeerId)!=="connected";)await delay(100);this.rtcClient=r,this.emit("connect"),this.initConnectionMonitoring()}}initConnectionMonitoring(){this.connectionMonitorInterval=setInterval(async()=>{this.isV2Signaling(this.rtcClient)&&(!this.rtcClient||!this.remoteDevicePeerId||await this.rtcClient.getConnectionStatsInfo(this.remoteDevicePeerId)===void 0)&&(this.emit("disconnect"),this.stopRealtimeConnection().catch(n=>{console.error(n)}))},1e3)}isV2Signaling(n){return n.getConnectionStatsInfo!==void 0}stopConnectionMonitoring(){clearInterval(this.connectionMonitorInterval),this.connectionMonitorInterval=void 0}async sendRealtimeMessage(n,r={channelLabel:"stream.reliable"}){const i=defined(this.rtcClient,"Realtime connection has not been started"),s=await this.getRemotePeer();i.send(defined(s).id,n,r)}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 getRealtimeAudioStreams(){var i,s,l;const n=await this.getConfiguration(),r=[];for(const o of((i=n.teleop)==null?void 0:i.hardwareStreams)??[])o.rtcStreamType==="audio-chunk"&&r.push({name:o.name});for(const o of((s=n.teleop)==null?void 0:s.rosStreams)??[])o.topicType=="audio_common_msgs/AudioData"&&r.push({name:o.topicName});for(const o of((l=n.teleop)==null?void 0:l.customStreams)??[])o.rtcStreamType==="audio-chunk"&&r.push({name:o.name});return r}async getRealtimeVideoStreams(){var i,s,l;const n=await this.getConfiguration(),r=[];for(const o of((i=n.teleop)==null?void 0:i.hardwareStreams)??[])o.rtcStreamType==="h264-video-frame"&&r.push({name:o.name});for(const o of((s=n.teleop)==null?void 0:s.rosStreams)??[])o.topicType=="formant/H264VideoFrame"&&r.push({name:o.topicName}),(o.topicType==="sensor_msgs/Image"||o.topicType==="sensor_msgs/CompressedImage")&&o.encodeVideo&&r.push({name:o.topicName});for(const o of((l=n.teleop)==null?void 0:l.customStreams)??[])o.rtcStreamType==="h264-video-frame"&&r.push({name:o.name});return r}async getRealtimeManipulators(){const n=await this.getConfiguration(),r=[];for(const i of n.teleop.rosStreams??[])i.topicType=="sensor_msgs/JointState"&&r.push(new Manipulator(this,{currentJointStateStream:{name:i.topicName},plannedJointStateStream:i.plannedTopic?{name:i.plannedTopic}:void 0,planValidStream:i.planValidTopic?{name:i.planValidTopic}:void 0,endEffectorStream:i.endEffectorTopic?{name:i.endEffectorTopic}:void 0,endEffectorLinkName:i.endEffectorLinkName,baseReferenceFrame:i.baseReferenceFrame,localFrame:i.localFrame}));return r}async startListeningToRealtimeVideo(n){const r=defined(this.rtcClient,"Realtime connection has not been started"),i=await this.getRemotePeer();r.controlRemoteStream(defined(i).id,{streamName:n.name,enable:!0,pipeline:"rtc"})}async stopListeningToRealtimeVideo(n){const r=defined(this.rtcClient,"Realtime connection has not been started"),i=await this.getRemotePeer();r.controlRemoteStream(defined(i).id,{streamName:n.name,enable:!1,pipeline:"rtc"})}async startListeningToRealtimeDataStream(n){const r=defined(this.rtcClient,"Realtime connection has not been started"),i=await this.getRemotePeer();r.controlRemoteStream(defined(i).id,{streamName:n.name,enable:!0,pipeline:"rtc"})}async stopListeningToRealtimeDataStream(n){const r=defined(this.rtcClient,"Realtime connection has not been started"),i=await this.getRemotePeer();r.controlRemoteStream(defined(i).id,{streamName:n.name,enable:!1,pipeline:"rtc"})}async enableRealtimeTelemetryPriorityIngestion(n){const r=defined(this.rtcClient,"Realtime connection has not been started"),i=await this.getRemotePeer();r.controlRemoteStream(defined(i).id,{streamName:n,enablePriorityUpload:!0,pipeline:"telemetry"})}async changeStreamAudioType(n,r){const i=defined(this.rtcClient,"Realtime connection has not been started"),s=await this.getRemotePeer();i.controlRemoteStream(defined(s).id,{streamName:n,setAudioFormat:r})}async disableRealtimeTelemetryPriorityIngestion(n){const r=defined(this.rtcClient,"Realtime connection has not been started"),i=await this.getRemotePeer();r.controlRemoteStream(defined(i).id,{streamName:n,enablePriorityUpload:!1,pipeline:"telemetry"})}async getRemotePeer(){const r=(await defined(this.rtcClient,"Realtime connection has not been started").getPeers()).find(i=>i.deviceId===this.id);return defined(r,"Could not find remote peer for device "+this.id)}async stopRealtimeConnection(){if(this.rtcClient)this.stopConnectionMonitoring(),await this.rtcClient.disconnect(this.id),this.rtcClient=void 0;else throw new Error(`Realtime connection hasn't been started for ${this.id}`)}async isInRealtimeSession(){let n=await Fleet.getPeers(),r=await Fleet.getRealtimeSessions(),i=n.find(s=>s.deviceId===this.id);return i?r[i.id].length>0:!1}async getAvailableCommands(){return(await(await fetch(`${FORMANT_API_URL}/v1/admin/command-templates/`,{method:"GET",headers:{"Content-Type":"application/json",Authorization:"Bearer "+Authentication.token}})).json()).items.map(i=>({name:i.name,id:i.id,command:i.command,description:i.description,parameterEnabled:i.parameterEnabled,parameterValue:i.parameterValue,parameterMeta:i.parameterMeta,enabled:i.enabled}))}async sendCommand(n,r,i,s){var E;const o=(await this.getAvailableCommands()).find(w=>w.name===n);if(!o)throw new Error(`Could not find command with name "${n}"`);let c="";r===void 0?o.parameterEnabled&&o.parameterValue&&(c=o.parameterValue):c=r;let u={value:c,scrubberTime:(i||new Date).toISOString(),meta:{...o.parameterMeta,...s}};return await fetch(`${FORMANT_API_URL}/v1/admin/commands`,{method:"POST",body:JSON.stringify({commandTemplateId:o.id,organizationId:this.organizationId,deviceId:this.id,command:o.command,parameter:u,userId:(E=Authentication.currentUser)==null?void 0:E.id}),headers:{"Content-Type":"application/json",Authorization:"Bearer "+Authentication.token}})}async getCommand(n){return await fetch(`${FORMANT_API_URL}/v1/admin/commands/${n}`,{method:"GET",headers:{"Content-Type":"application/json",Authorization:"Bearer "+Authentication.token}})}async createCustomDataChannel(n,r){if(rtcClientVersion==="1")throw new Error("createCustomDataChannel is not supported in rtcClientVersion 1");const i=defined(this.rtcClient,"Realtime connection has not been started"),s=await this.getRemotePeer(),l=await new Promise(o=>{i.createCustomDataChannel(defined(s).id,n,{ordered:!0,...r},!1,(c,u)=>{const f=new DataChannel(u);o(f)})});return await l.waitTilReady(),l}createCustomRequestDataChannel(n,r=3e3){return new TextRequestDataChannel(this,n,r)}createCustomBinaryRequestDataChannel(n,r=3e3){return new BinaryRequestDataChannel(this,n,r)}async createCaptureStream(n){const i=await(await fetch(`${FORMANT_API_URL}/v1/admin/capture-sessions`,{method:"POST",body:JSON.stringify({deviceId:this.id,streamName:n,tags:{}}),headers:{"Content-Type":"application/json",Authorization:"Bearer "+Authentication.token}})).json();return new CaptureStream(i)}async getTelemetry(n,r,i,s){return await Fleet.getTelemetry(this.id,n,r,i,s)}async getTelemetryStreams(){var c,u;const n=await this.getConfiguration(),r=await fetch(`${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}}),i=[],s=[];return(u=(c=n.telemetry)==null?void 0:c.streams)==null||u.forEach(f=>{f.disabled!==!0&&i.push(f.name),f.onDemand===!0&&s.push(f.name)}),console.log(s),(await r.json()).items.filter(f=>!i.includes(f)).map(f=>({name:f,onDemand:s.includes(f)}))}async createInterventionRequest(n,r,i,s){return await(await fetch(`${FORMANT_API_URL}/v1/admin/intervention-requests`,{method:"POST",body:JSON.stringify({message:n,interventionType:r,time:new Date().toISOString(),deviceId:this.id,tags:s,data:i}),headers:{"Content-Type":"application/json",Authorization:"Bearer "+Authentication.token}})).json()}async addInterventionResponse(n,r,i){return await(await fetch(`${FORMANT_API_URL}/v1/admin/intervention-responses`,{method:"POST",body:JSON.stringify({interventionId:n,interventionType:r,data:i}),headers:{"Content-Type":"application/json",Authorization:"Bearer "+Authentication.token}})).json()}async getAnnotationCount(n,r){return await Fleet.getAnnotationCount({...n,deviceIds:[this.id]},r)}async getAnnotationCountByIntervals(n,r,i){return await Fleet.getAnnotationCountByIntervals({...n,deviceIds:[this.id]},r,i)}async eventsCounter(n,r,i,s,l){return await Fleet.eventsCounter(n,r,i,s,{...l,deviceIds:[this.id]})}async createShareLink(n,r){return n.scope.deviceIds=[this.id],await Fleet.createShareLink(n,r)}}class PeerDevice{constructor(t){Ae(this,"rtcClient");Ae(this,"remoteDevicePeerId");Ae(this,"realtimeListeners",[]);Ae(this,"id");Ae(this,"handleMessage",(t,n)=>{this.realtimeListeners.forEach(r=>r(t,n))});this.peerUrl=t}async getLatestTelemetry(){const n=await(await fetch(`${this.peerUrl}/telemetry`)).json();return Object.entries(n).map(([i,s])=>({deviceId:this.id,streamName:i,streamType:"json",currentValue:s,currentValueTime:s.timestamp,tags:{}}))}async getDeviceId(){return(await(await fetch(`${this.peerUrl}/configuration`)).json()).agent_config.id}async getConfiguration(){return(await(await fetch(`${this.peerUrl}/configuration`)).json()).agent_config.document}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")}async startRealtimeConnection(t){if(this.rtcClient)throw new Error(`Already created realtime connection to device ${this.id}`);{const n=new distExports.RtcClient({lanOnlyMode:!0,receive:this.handleMessage,sessionType:t});for(await n.connectLan(this.peerUrl);n.getConnectionStatus(this.peerUrl)!=="connected";)await delay(100);this.rtcClient=n}}addRealtimeListener(t){this.realtimeListeners.push(t)}removeRealtimeListener(t){const n=this.realtimeListeners.indexOf(t);if(n===-1)throw new Error("Could not find realtime listener to remove");this.realtimeListeners.splice(n,1)}async getRealtimeVideoStreams(){const t=await this.getConfiguration(),n=[];for(const r of t.teleop.hardwareStreams??[])r.rtcStreamType==="h264-video-frame"&&n.push({name:r.name});for(const r of t.teleop.rosStreams??[])r.topicType=="formant/H264VideoFrame"&&n.push({name:r.topicName}),(r.topicType==="sensor_msgs/Image"||r.topicType==="sensor_msgs/CompressedImage")&&r.encodeVideo&&n.push({name:r.topicName});for(const r of t.teleop.customStreams??[])r.rtcStreamType==="h264-video-frame"&&n.push({name:r.name});return n}async getRealtimeManipulators(){const t=await this.getConfiguration(),n=[];for(const r of t.teleop.rosStreams??[])r.topicType=="sensor_msgs/JointState"&&n.push(new Manipulator(this,{currentJointStateStream:{name:r.topicName},plannedJointStateStream:r.plannedTopic?{name:r.plannedTopic}:void 0,planValidStream:r.planValidTopic?{name:r.planValidTopic}:void 0,endEffectorStream:r.endEffectorTopic?{name:r.endEffectorTopic}:void 0,endEffectorLinkName:r.endEffectorLinkName,baseReferenceFrame:r.baseReferenceFrame,localFrame:r.localFrame}));return n}async startListeningToRealtimeVideo(t){const n=defined(this.rtcClient,"Realtime connection has not been started"),r=await this.getRemotePeer();n.controlRemoteStream(defined(r).id,{streamName:t.name,enable:!0,pipeline:"rtc"})}async stopListeningToRealtimeVideo(t){const n=defined(this.rtcClient,"Realtime connection has not been started"),r=await this.getRemotePeer();n.controlRemoteStream(defined(r).id,{streamName:t.name,enable:!1,pipeline:"rtc"})}async startListeningToRealtimeDataStream(t){const n=defined(this.rtcClient,"Realtime connection has not been started"),r=await this.getRemotePeer();n.controlRemoteStream(defined(r).id,{streamName:t.name,enable:!0,pipeline:"rtc"})}async stopListeningToRealtimeDataStream(t){const n=defined(this.rtcClient,"Realtime connection has not been started"),r=await this.getRemotePeer();n.controlRemoteStream(defined(r).id,{streamName:t.name,enable:!1,pipeline:"rtc"})}async enableRealtimeTelemetryPriorityIngestion(t){const n=defined(this.rtcClient,"Realtime connection has not been started"),r=await this.getRemotePeer();n.controlRemoteStream(defined(r).id,{streamName:t,enablePriorityUpload:!0,pipeline:"telemetry"})}async disableRealtimeTelemetryPriorityIngestion(t){const n=defined(this.rtcClient,"Realtime connection has not been started"),r=await this.getRemotePeer();n.controlRemoteStream(defined(r).id,{streamName:t,enablePriorityUpload:!1,pipeline:"telemetry"})}async getRemotePeer(){return{id:this.peerUrl,organizationId:"",deviceId:this.id,capabilities:[],capabilitySet:{}}}async stopRealtimeConnection(){if(this.rtcClient)await this.rtcClient.disconnect(this.id);else throw new Error(`Realtime connection hasn't been started for ${this.id}`)}async createCustomDataChannel(t,n){const r=defined(this.rtcClient,"Realtime connection has not been started"),i=await this.getRemotePeer(),s=await new Promise(l=>{r.createCustomDataChannel(defined(i).id,t,{ordered:!0,...n},!1,(o,c)=>{const u=new DataChannel(c);l(u)})});return await s.waitTilReady(),s}createCustomRequestDataChannel(t,n=3e3){return new TextRequestDataChannel(this,t,n)}createCustomBinaryRequestDataChannel(t,n=3e3){return new BinaryRequestDataChannel(this,t,n)}}const Ge=class{static async setDefaultDevice(t){Ge.defaultDeviceId=t}static async getCurrentDevice(){if(!Authentication.token)throw new Error("Not authenticated");if(!Ge.defaultDeviceId)throw new Error("No known default device");const i=(await(await fetch(`${FORMANT_API_URL}/v1/admin/device-details/query`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:"Bearer "+Authentication.token}})).json()).items.find(l=>l.id===Ge.defaultDeviceId).name,s=new Device(Ge.defaultDeviceId,i,defined(Authentication.currentOrganization));return Ge.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){if(!Authentication.token)throw new Error("Not authenticated");const r=await(await fetch(`${FORMANT_API_URL}/v1/admin/devices/${t}`,{method:"GET",headers:{"Content-Type":"application/json",Authorization:"Bearer "+Authentication.token}})).json(),i=r.name,s=new Device(t,i,r.organizationId);return Ge.knownContext.push(new WeakRef(s)),s}static async getDevices(){if(!Authentication.token)throw new Error("Not authenticated");const n=await(await fetch(`${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 n.items,n.items.map(r=>new Device(r.id,r.name,r.organizationId))}static async queryDevices(t){if(!Authentication.token)throw new Error("Not authenticated");return(await(await fetch(`${FORMANT_API_URL}/v1/admin/devices/query`,{method:"POST",body:JSON.stringify(t),headers:{"Content-Type":"application/json",Authorization:"Bearer "+Authentication.token}})).json()).items.map(i=>new Device(i.id,i.name,i.organizationId))}static async getOnlineDevices(){if(!Authentication.token)throw new Error("Not authenticated");const r=(await(await fetch(`${FORMANT_API_URL}/v1/queries/online-devices`,{method:"GET",headers:{"Content-Type":"application/json",Authorization:"Bearer "+Authentication.token}})).json()).items;return(await Ge.getDevices()).filter(s=>r.includes(s.id))}static async getPeers(){if(!Authentication.token)throw new Error("Not authenticated");return await new distExports.RtcClient({signalingClient:new distExports.SignalingPromiseClient(FORMANT_API_URL,null,null),getToken:async()=>defined(Authentication.token,"Realtime when user isn't authorized"),receive:()=>{}}).getPeers()}static async getRealtimeSessions(){if(!Authentication.token)throw new Error("Not authenticated");return await new distExports.RtcClient({signalingClient:new distExports.SignalingPromiseClient(FORMANT_API_URL,null,null),getToken:async()=>defined(Authentication.token,"Realtime when user isn't authorized"),receive:()=>{}}).getSessions()}static async getRealtimeDevices(){if(!Authentication.token)throw new Error("Not authenticated");const r=(await(await fetch(`${FORMANT_API_URL}/v1/signaling/peers`,{method:"GET",headers:{"Content-Type":"application/json",Authorization:"Bearer "+Authentication.token}})).json()).items.map(s=>s.deviceId);return(await Ge.getDevices()).filter(s=>r.includes(s.id))}static async getLatestTelemetry(t){let n=t;return t&&!Array.isArray(t)&&(t=[t]),(await(await fetch(`${FORMANT_API_URL}/v1/queries/stream-current-value`,{method:"POST",body:JSON.stringify({deviceIds:n}),headers:{"Content-Type":"application/json",Authorization:"Bearer "+Authentication.token}})).json()).items}static async getTelemetry(t,n,r,i,s){let l=t;Array.isArray(t)||(l=[t]);let o=n;return Array.isArray(n)||(o=[n]),(await(await fetch(`${FORMANT_API_URL}/v1/queries/queries`,{method:"POST",body:JSON.stringify({deviceIds:l,end:i.toISOString(),names:o,start:r.toISOString(),tags:s}),headers:{"Content-Type":"application/json",Authorization:"Bearer "+Authentication.token}})).json()).items}static async getFileUrl(t){const r=await(await fetch(`${FORMANT_API_URL}/v1/admin/files/query`,{method:"POST",body:JSON.stringify({fileIds:[t]}),headers:{"Content-Type":"application/json",Authorization:"Bearer "+Authentication.token}})).json();if(r.fileUrls.length===0)throw new Error("File not found");return r.fileUrls[0]}static async queryTelemetry(t){if(!Authentication.token)throw new Error("Not authenticated");return(await(await fetch(`${FORMANT_API_URL}/v1/queries/queries`,{method:"POST",body:JSON.stringify(t),headers:{"Content-Type":"application/json",Authorization:"Bearer "+Authentication.token}})).json()).items}static async aggregateTelemetry(t){if(!Authentication.token)throw new Error("Not authenticated");return(await(await fetch(`${FORMANT_API_URL}/v1/queries/queries`,{method:"POST",body:JSON.stringify(t),headers:{"Content-Type":"application/json",Authorization:"Bearer "+Authentication.token}})).json()).aggregates}static async queryEvents(t){if(!Authentication.token)throw new Error("Not authenticated");return(await(await fetch(`${FORMANT_API_URL}/v1/admin/events/query`,{method:"POST",body:JSON.stringify(t),headers:{"Content-Type":"application/json",Authorization:"Bearer "+Authentication.token}})).json()).items}static async getEvent(t){if(!Authentication.token)throw new Error("Not authenticated");return(await(await fetch(`${FORMANT_API_URL}/v1/admin/events/query/id=${t}`,{method:"GET",headers:{"Content-Type":"application/json",Authorization:"Bearer "+Authentication.token}})).json()).items}static async getInterventions(){if(!Authentication.token)throw new Error("Not authenticated");return(await(await fetch(`${FORMANT_API_URL}/v1/admin/intervention-requests`,{method:"GET",headers:{"Content-Type":"application/json",Authorization:"Bearer "+Authentication.token}})).json()).items}static async getCurrentGroup(){if(!Authentication.token)throw new Error("Not authenticated");let t=new URLSearchParams("");typeof window<"u"&&(t=new URLSearchParams(window.location.search));const n=t.get("group");if(n===null||n.trim()==="")return;const r=await fetch(`${FORMANT_API_URL}/v1/admin/groups/`+n,{headers:{"Content-Type":"application/json",Authorization:"Bearer "+Authentication.token}}),{tagKey:i,tagValue:s}=await r.json();return await this.queryDevices({tags:{[i]:[s]},enabled:!0,type:"default"})}static async getAnnotationCount(t,n){return(await this.queryEvents({...t,eventTypes:["annotation"]})).filter(l=>!!l.tags&&Object.keys(l.tags).includes(n)).reduce((l,o)=>{const c=o.tags[n];return c in l?(l[c]+=1,l):(l[c]=1,l)},{})}static async getAnnotationCountByIntervals(t,n,r){const{end:i,start:s}=t,o=aggregateByDateFunctions[r].interval({start:new Date(s),end:new Date(i)}),c=o.map((f,E)=>{const w=new Date(f).toISOString(),h=E===o.length-1?new Date(Date.now()).toISOString():new Date(o[E+1]);return this.getAnnotationCount({...t,start:w,end:h},n)}),u=await Promise.all(c);return o.map((f,E)=>({date:new Date(f).toISOString(),annotations:u[E]}))}static async getStreams(){if(!Authentication.token)throw new Error("Not authenticated");return(await(await fetch(`${FORMANT_API_URL}/v1/admin/streams`,{method:"GET",headers:{"Content-Type":"application/json",Authorization:"Bearer "+Authentication.token}})).json()).items.filter(r=>r.enabled)}static async patchStream(t){if(!Authentication.token)throw new Error("Not authenticated");return await(await fetch(`${FORMANT_API_URL}/v1/admin/streams/${t.id}`,{method:"PATCH",body:JSON.stringify(t),headers:{"Content-Type":"application/json",Authorization:"Bearer "+Authentication.token}})).json()}static async getViews(){if(!Authentication.token)throw new Error("Not authenticated");return(await(await fetch(`${FORMANT_API_URL}/v1/admin/views`,{method:"GET",headers:{"Content-Type":"application/json",Authorization:"Bearer "+Authentication.token}})).json()).items}static async patchView(t){if(!Authentication.token)throw new Error("Not authenticated");return await(await fetch(`${FORMANT_API_URL}/v1/admin/views/${t.id}`,{method:"PATCH",body:JSON.stringify(t),headers:{"Content-Type":"application/json",Authorization:"Bearer "+Authentication.token}})).json()}static async eventsCounter(t,n,r,i,s){const l=aggregateByDateFunctions[n];return await Promise.all(Array(r).fill(0).map(async(o,c)=>{const u=new Date(i),f=l.sub(l.start(u),r-c-1),E=l.sub(l.end(u),r-c-1),w=formatTimeFrameText(f.toLocaleDateString(),E.toLocaleDateString()),h=await Ge.queryEvents({...s,eventTypes:t,start:new Date(f).toISOString(),end:new Date(E).toISOString()});return{date:w,events:h}}))}static async getAnalyticsModules(){if(!Authentication.token)throw new Error("Not authenticated");return(await(await fetch(`${FORMANT_API_URL}/v1/admin/analytics-modules`,{method:"GET",headers:{"Content-Type":"application/json",Authorization:"Bearer "+Authentication.token}})).json()).items}static async getAnalyticStreams(){if(!Authentication.token)throw new Error("Not authenticated");return(await(await fetch(`${FORMANT_API_URL}/v1/queries/analytics/streams`,{method:"GET",headers:{"Content-Type":"application/json",Authorization:"Bearer "+Authentication.token}})).json()).items}static async getTaskReportTables(){if(!Authentication.token)throw new Error("Not authenticated");return(await(await fetch(`${FORMANT_API_URL}/v1/queries/analytics/task-reports`,{method:"GET",headers:{"Content-Type":"application/json",Authorization:"Bearer "+Authentication.token}})).json()).items}static async queryAnalytics(t){if(!Authentication.token)throw new Error("Not authenticated");return await(await fetch(`${FORMANT_API_URL}/v1/queries/analytics`,{method:"POST",body:JSON.stringify(t),headers:{"Content-Type":"application/json",Authorization:"Bearer "+Authentication.token}})).json()}static async getAnalyticsRows(t){if(!Authentication.token)throw new Error("Not authenticated");return await(await fetch(`${FORMANT_API_URL}/v1/queries/analytics/rows`,{method:"POST",body:JSON.stringify(t),headers:{"Content-Type":"application/json",Authorization:"Bearer "+Authentication.token}})).json()}static async getTaskReportRows(t){if(!Authentication.token)throw new Error("Not authenticated");return await(await fetch(`${FORMANT_API_URL}/v1/queries/analytics/task-report-rows`,{method:"POST",body:JSON.stringify(t),headers:{"Content-Type":"application/json",Authorization:"Bearer "+Authentication.token}})).json()}static async createShareLink(t,n){if(!Authentication.token)throw new Error("Not authenticated");const i=(await this.getViews()).filter(c=>c.name===n);if(i.length===0)return console.warn("View does not exist or it is misspell"),null;const s=await fetch(`${FORMANT_API_URL}/v1/admin/shares`,{method:"POST",body:JSON.stringify(t),headers:{"Content-Type":"application/json",Authorization:"Bearer "+Authentication.token}}),l=FORMANT_API_URL.replace("api","app"),{code:o}=await s.json();return`${l}/shares/${o}#${serializeHash({viewId:i[0].id})}`}};let Fleet=Ge;Ae(Fleet,"defaultDeviceId"),Ae(Fleet,"knownContext",[]);class KeyValue{static async set(t,n){try{const r=await fetch(FORMANT_API_URL+"/v1/admin/key-value",{method:"POST",body:JSON.stringify({organizationId:defined(Authentication.currentUser).organizationId,key:t,value:n}),headers:{"Content-Type":"application/json",Authorization:"Bearer "+Authentication.token}}),i=await r.json();if(r.status!==200)throw new Error(i.message)}catch(r){throw r}}static async get(t){try{const n=await fetch(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(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(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}}}const vailableAggregationIntervals=["day","week","month","year","hour","minute","quarter"],aggregateFunctions=["interval","start","end","sub","get"];function getVariance(e){return e.count<2?0:e.sumOfSquares/(e.count-1)}function getStandardDeviation(e){return Math.sqrt(getVariance(e))}function getMax(e){return e.max}function getMin(e){return e.min}function getAverage(e){return e.count===0?-1:e.sum/e.count}function getSum(e){return e.sum}function getCount(e){return e.count}const aggregateFunctionMap={min:getMin,max:getMax,"standard deviation":getStandardDeviation,average:getAverage,sum:getSum,count:getCount},aggregateByDateFunctions={day:{interval:dateFns__namespace.eachDayOfInterval,start:dateFns__namespace.startOfDay,end:dateFns__namespace.endOfDay,sub:dateFns__namespace.subDays,get:dateFns__namespace.getDay},week:{interval:dateFns__namespace.eachWeekOfInterval,start:dateFns__namespace.startOfWeek,end:dateFns__namespace.endOfWeek,sub:dateFns__namespace.subWeeks,get:dateFns__namespace.getWeek},month:{interval:dateFns__namespace.eachMonthOfInterval,start:dateFns__namespace.startOfMonth,end:dateFns__namespace.endOfMonth,sub:dateFns__namespace.subMonths,get:dateFns__namespace.getMonth},year:{interval:dateFns__namespace.eachYearOfInterval,start:dateFns__namespace.startOfYear,end:dateFns__namespace.endOfYear,sub:dateFns__namespace.subYears,get:dateFns__namespace.getYear},hour:{interval:dateFns__namespace.eachHourOfInterval,start:dateFns__namespace.startOfHour,end:dateFns__namespace.endOfHour,sub:dateFns__namespace.subHours,get:dateFns__namespace.getHours},minute:{interval:dateFns__namespace.eachMinuteOfInterval,start:dateFns__namespace.startOfMinute,end:dateFns__namespace.endOfMinute,sub:dateFns__namespace.subMinutes,get:dateFns__namespace.getMinutes},quarter:{interval:dateFns__namespace.eachQuarterOfInterval,start:dateFns__namespace.startOfQuarter,end:dateFns__namespace.endOfQuarter,sub:dateFns__namespace.subQuarters,get:dateFns__namespace.getQuarter}},formatTimeFrameText=(e,t)=>e.split("/")[0]+"/"+e.split("/")[1]+"–"+t.split("/")[0]+"/"+t.split("/")[1];function getZeroINumericSet(){return{min:Number.MAX_SAFE_INTEGER,max:0,sum:0,count:0,sumOfSquares:0}}function reduceNumericStreamAggregates(e){return e.aggregates.reduce((t,n)=>{const r=n[1];return combineNumericAggregates(r,t)},getZeroINumericSet())}function reduceNumericSetStreamAggregates(e,t){var n;return(n=e.aggregates.reduce((r,i)=>{const s=i[1];return combineNumericSetAggregates(s,r)},{})[t])==null?void 0:n.value}function combineNumericAggregates(e,t){return{min:Math.min(e.min,t.min),max:Math.max(e.max,t.max),sum:e.sum+t.sum,count:e.count+t.count,sumOfSquares:e.sumOfSquares+t.sumOfSquares}}function combineNumericSetAggregates(e,t){return Object.keys(e).reduce((n,r)=>{var i;return{...n,[r]:{value:combineNumericAggregates(e[r].value,((i=t[r])==null?void 0:i.value)??getZeroINumericSet()),unit:e[r].unit}}},{})}const timeout=e=>new Promise(t=>setTimeout(t,e*1e3));function defaultSetTimout(){throw new Error("setTimeout has not been defined")}function defaultClearTimeout(){throw new Error("clearTimeout has not been defined")}var cachedSetTimeout=defaultSetTimout,cachedClearTimeout=defaultClearTimeout;typeof global$1.setTimeout=="function"&&(cachedSetTimeout=setTimeout),typeof global$1.clearTimeout=="function"&&(cachedClearTimeout=clearTimeout);function runTimeout(e){if(cachedSetTimeout===setTimeout)return setTimeout(e,0);if((cachedSetTimeout===defaultSetTimout||!cachedSetTimeout)&&setTimeout)return cachedSetTimeout=setTimeout,setTimeout(e,0);try{return cachedSetTimeout(e,0)}catch{try{return cachedSetTimeout.call(null,e,0)}catch{return cachedSetTimeout.call(this,e,0)}}}function runClearTimeout(e){if(cachedClearTimeout===clearTimeout)return clearTimeout(e);if((cachedClearTimeout===defaultClearTimeout||!cachedClearTimeout)&&clearTimeout)return cachedClearTimeout=clearTimeout,clearTimeout(e);try{return cachedClearTimeout(e)}catch{try{return cachedClearTimeout.call(null,e)}catch{return cachedClearTimeout.call(this,e)}}}var queue=[],draining=!1,currentQueue,queueIndex=-1;function cleanUpNextTick(){!draining||!currentQueue||(draining=!1,currentQueue.length?queue=currentQueue.concat(queue):queueIndex=-1,queue.length&&drainQueue())}function drainQueue(){if(!draining){var e=runTimeout(cleanUpNextTick);draining=!0;for(var t=queue.length;t;){for(currentQueue=queue,queue=[];++queueIndex<t;)currentQueue&&currentQueue[queueIndex].run();queueIndex=-1,t=queue.length}currentQueue=null,draining=!1,runClearTimeout(e)}}function nextTick(e){var t=new Array(arguments.length-1);if(arguments.length>1)for(var n=1;n<arguments.length;n++)t[n-1]=arguments[n];queue.push(new Item(e,t)),queue.length===1&&!draining&&runTimeout(drainQueue)}function Item(e,t){this.fun=e,this.array=t}Item.prototype.run=function(){this.fun.apply(null,this.array)};var title="browser",platform="browser",browser$1=!0,env={},argv=[],version="",versions={},release={},config={};function noop(){}var on=noop,addListener=noop,once=noop,off=noop,removeListener=noop,removeAllListeners=noop,emit=noop;function binding$1(e){throw new Error("process.binding is not supported")}function cwd(){return"/"}function chdir(e){throw new Error("process.chdir is not supported")}function umask(){return 0}var performance$1=global$1.performance||{},performanceNow=performance$1.now||performance$1.mozNow||performance$1.msNow||performance$1.oNow||performance$1.webkitNow||function(){return new Date().getTime()};function hrtime(e){var t=performanceNow.call(performance$1)*.001,n=Math.floor(t),r=Math.floor(t%1*1e9);return e&&(n=n-e[0],r=r-e[1],r<0&&(n--,r+=1e9)),[n,r]}var startTime=new Date;function uptime(){var e=new Date,t=e-startTime;return t/1e3}var browser$1$1={nextTick,title,browser:browser$1,env,argv,version,versions,on,addListener,once,off,removeListener,removeAllListeners,emit,binding:binding$1,cwd,chdir,umask,hrtime,platform,release,config,uptime},inherits;typeof Object.create=="function"?inherits=function(t,n){t.super_=n,t.prototype=Object.create(n.prototype,{constructor:{value:t,enumerable:!1,writable:!0,configurable:!0}})}:inherits=function(t,n){t.super_=n;var r=function(){};r.prototype=n.prototype,t.prototype=new r,t.prototype.constructor=t};const inherits$1=inherits;var formatRegExp=/%[sdj%]/g;function format(e){if(!isString(e)){for(var t=[],n=0;n<arguments.length;n++)t.push(inspect(arguments[n]));return t.join(" ")}for(var n=1,r=arguments,i=r.length,s=String(e).replace(formatRegExp,function(o){if(o==="%%")return"%";if(n>=i)return o;switch(o){case"%s":return String(r[n++]);case"%d":return Number(r[n++]);case"%j":try{return JSON.stringify(r[n++])}catch{return"[Circular]"}default:return o}}),l=r[n];n<i;l=r[++n])isNull(l)||!isObject(l)?s+=" "+l:s+=" "+inspect(l);return s}function deprecate(e,t){if(isUndefined(global$1.process))return function(){return deprecate(e,t).apply(this,arguments)};if(browser$1$1.noDeprecation===!0)return e;var n=!1;function r(){if(!n){if(browser$1$1.throwDeprecation)throw new Error(t);browser$1$1.traceDeprecation?console.trace(t):console.error(t),n=!0}return e.apply(this,arguments)}return r}var debugs={},debugEnviron;function debuglog(e){if(isUndefined(debugEnviron)&&(debugEnviron=browser$1$1.env.NODE_DEBUG||""),e=e.toUpperCase(),!debugs[e])if(new RegExp("\\b"+e+"\\b","i").test(debugEnviron)){var t=0;debugs[e]=function(){var n=format.apply(null,arguments);console.error("%s %d: %s",e,t,n)}}else debugs[e]=function(){};return debugs[e]}function inspect(e,t){var n={seen:[],stylize:stylizeNoColor};return arguments.length>=3&&(n.depth=arguments[2]),arguments.length>=4&&(n.colors=arguments[3]),isBoolean(t)?n.showHidden=t:t&&_extend(n,t),isUndefined(n.showHidden)&&(n.showHidden=!1),isUndefined(n.depth)&&(n.depth=2),isUndefined(n.colors)&&(n.colors=!1),isUndefined(n.customInspect)&&(n.customInspect=!0),n.colors&&(n.stylize=stylizeWithColor),formatValue(n,e,n.depth)}inspect.colors={bold:[1,22],italic:[3,23],underline:[4,24],inverse:[7,27],white:[37,39],grey:[90,39],black:[30,39],blue:[34,39],cyan:[36,39],green:[32,39],magenta:[35,39],red:[31,39],yellow:[33,39]},inspect.styles={special:"cyan",number:"yellow",boolean:"yellow",undefined:"grey",null:"bold",string:"green",date:"magenta",regexp:"red"};function stylizeWithColor(e,t){var n=inspect.styles[t];return n?"\x1B["+inspect.colors[n][0]+"m"+e+"\x1B["+inspect.colors[n][1]+"m":e}function stylizeNoColor(e,t){return e}function arrayToHash(e){var t={};return e.forEach(function(n,r){t[n]=!0}),t}function formatValue(e,t,n){if(e.customInspect&&t&&isFunction(t.inspect)&&t.inspect!==inspect&&!(t.constructor&&t.constructor.prototype===t)){var r=t.inspect(n,e);return isString(r)||(r=formatValue(e,r,n)),r}var i=formatPrimitive(e,t);if(i)return i;var s=Object.keys(t),l=arrayToHash(s);if(e.showHidden&&(s=Object.getOwnPropertyNames(t)),isError(t)&&(s.indexOf("message")>=0||s.indexOf("description")>=0))return formatError(t);if(s.length===0){if(isFunction(t)){var o=t.name?": "+t.name:"";return e.stylize("[Function"+o+"]","special")}if(isRegExp(t))return e.stylize(RegExp.prototype.toString.call(t),"regexp");if(isDate(t))return e.stylize(Date.prototype.toString.call(t),"date");if(isError(t))return formatError(t)}var c="",u=!1,f=["{","}"];if(isArray(t)&&(u=!0,f=["[","]"]),isFunction(t)){var E=t.name?": "+t.name:"";c=" [Function"+E+"]"}if(isRegExp(t)&&(c=" "+RegExp.prototype.toString.call(t)),isDate(t)&&(c=" "+Date.prototype.toUTCString.call(t)),isError(t)&&(c=" "+formatError(t)),s.length===0&&(!u||t.length==0))return f[0]+c+f[1];if(n<0)return isRegExp(t)?e.stylize(RegExp.prototype.toString.call(t),"regexp"):e.stylize("[Object]","special");e.seen.push(t);var w;return u?w=formatArray(e,t,n,l,s):w=s.map(function(h){return formatProperty(e,t,n,l,h,u)}),e.seen.pop(),reduceToSingleString(w,c,f)}function formatPrimitive(e,t){if(isUndefined(t))return e.stylize("undefined","undefined");if(isString(t)){var n="'"+JSON.stringify(t).replace(/^"|"$/g,"").replace(/'/g,"\\'").replace(/\\"/g,'"')+"'";return e.stylize(n,"string")}if(isNumber(t))return e.stylize(""+t,"number");if(isBoolean(t))return e.stylize(""+t,"boolean");if(isNull(t))return e.stylize("null","null")}function formatError(e){return"["+Error.prototype.toString.call(e)+"]"}function formatArray(e,t,n,r,i){for(var s=[],l=0,o=t.length;l<o;++l)hasOwnProperty(t,String(l))?s.push(formatProperty(e,t,n,r,String(l),!0)):s.push("");return i.forEach(function(c){c.match(/^\d+$/)||s.push(formatProperty(e,t,n,r,c,!0))}),s}function formatProperty(e,t,n,r,i,s){var l,o,c;if(c=Object.getOwnPropertyDescriptor(t,i)||{value:t[i]},c.get?c.set?o=e.stylize("[Getter/Setter]","special"):o=e.stylize("[Getter]","special"):c.set&&(o=e.stylize("[Setter]","special")),hasOwnProperty(r,i)||(l="["+i+"]"),o||(e.seen.indexOf(c.value)<0?(isNull(n)?o=formatValue(e,c.value,null):o=formatValue(e,c.value,n-1),o.indexOf(`
50
50
  `)>-1&&(s?o=o.split(`
51
51
  `).map(function(u){return" "+u}).join(`
52
52
  `).substr(2):o=`
@@ -1,5 +1,10 @@
1
- import { IStreamData, StreamType } from "./main";
1
+ import { IStreamData, ITags, StreamType } from "./main";
2
2
  import { JsonSchema } from "./model/JsonSchema";
3
+ export interface IDevice {
4
+ name: string;
5
+ id: string;
6
+ tags: ITags;
7
+ }
3
8
  export type AppMessage = {
4
9
  type: "go_to_time";
5
10
  time: number;
@@ -46,6 +51,9 @@ export type ModuleConfigurationMessage = {
46
51
  configuration: string;
47
52
  };
48
53
  export type EmbeddedAppMessage = {
54
+ type: "overview_devices";
55
+ data: IDevice[];
56
+ } | {
49
57
  type: "module_menu_item_clicked";
50
58
  menu: string;
51
59
  } | {
@@ -117,13 +125,13 @@ export declare class App {
117
125
  static addMenuListener(handler: (label: string) => void): void;
118
126
  static addAccessTokenRefreshListener(handler: (token: string) => void): void;
119
127
  static addModuleDataListener(handler: (data: ModuleData) => void): void;
128
+ static addOverviewDeviceListener(handler: (devices: IDevice[]) => void): () => void;
120
129
  static addStreamListener(streamNames: string[], streamTypes: StreamType[], handler: (response: IStreamData[] | "too much data" | undefined) => void): () => void;
121
130
  static addModuleConfigurationListener(handler: (event: ModuleConfigurationMessage) => void): void;
122
131
  static addChannelDataListener(channel: string, handler: (e: {
123
132
  source: string;
124
133
  data: any;
125
134
  }) => void): void;
126
- static requestOverviewDevices(handler: (data: any) => void): void;
127
135
  static prompt(schema: JsonSchema, options?: {
128
136
  okText?: string;
129
137
  cancelText?: string;
@@ -109,6 +109,7 @@ export declare class Device extends EventEmitter implements IRealtimeDevice {
109
109
  getRealtimePing(): number | undefined;
110
110
  startRealtimeConnection(sessionType?: number): Promise<void>;
111
111
  private initConnectionMonitoring;
112
+ private isV2Signaling;
112
113
  private stopConnectionMonitoring;
113
114
  sendRealtimeMessage(message: IRtcStreamMessage, config?: IRtcSendConfiguration): Promise<void>;
114
115
  addRealtimeListener(listener: RealtimeListener): void;
@@ -127,7 +128,8 @@ export declare class Device extends EventEmitter implements IRealtimeDevice {
127
128
  stopRealtimeConnection(): Promise<void>;
128
129
  isInRealtimeSession(): Promise<boolean>;
129
130
  getAvailableCommands(): Promise<Command[]>;
130
- sendCommand(name: string, data?: string, time?: Date, metadata?: {}): Promise<void>;
131
+ sendCommand(name: string, data?: string, time?: Date, metadata?: {}): Promise<Response>;
132
+ getCommand(id: string): Promise<Response>;
131
133
  createCustomDataChannel(channelName: string, rtcConfig?: RTCDataChannelInit): Promise<DataChannel>;
132
134
  createCustomRequestDataChannel(channelName: string, timeout?: number): TextRequestDataChannel;
133
135
  createCustomBinaryRequestDataChannel(channelName: string, timeout?: number): BinaryRequestDataChannel;
package/package.json CHANGED
@@ -18,7 +18,7 @@
18
18
  "require": "./dist/data-sdk.umd.js"
19
19
  }
20
20
  },
21
- "version": "0.0.142",
21
+ "version": "0.0.144",
22
22
  "scripts": {
23
23
  "dev": "vite --port 9146",
24
24
  "build": "tsc && vite build",