@formant/data-sdk 0.0.138 → 0.0.139

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.
@@ -21159,17 +21159,8 @@ class Device {
21159
21159
  deviceIds: [this.id]
21160
21160
  });
21161
21161
  }
21162
- async createShareLink(t) {
21163
- if (!Authentication.token)
21164
- throw new Error("Not authenticated");
21165
- return await (await fetch(`${FORMANT_API_URL}/v1/admin/shares`, {
21166
- method: "POST",
21167
- body: JSON.stringify({ ...t, deviceIds: [this.id] }),
21168
- headers: {
21169
- "Content-Type": "application/json",
21170
- Authorization: "Bearer " + Authentication.token
21171
- }
21172
- })).json();
21162
+ async createShareLink(t, n) {
21163
+ return t.scope.deviceIds = [this.id], await Fleet.createShareLink(t, n);
21173
21164
  }
21174
21165
  }
21175
21166
  class PeerDevice {
@@ -21945,6 +21936,7 @@ const it = class {
21945
21936
  /**
21946
21937
  * @param scope is required
21947
21938
  * @param time is required
21939
+ * @param view View name
21948
21940
  * @returns
21949
21941
  * Share link
21950
21942
  * @example
@@ -21961,21 +21953,22 @@ const it = class {
21961
21953
  * userName: "User",
21962
21954
  * });
21963
21955
  */
21964
- static async createShareLink(t) {
21956
+ static async createShareLink(t, n) {
21965
21957
  if (!Authentication.token)
21966
21958
  throw new Error("Not authenticated");
21967
- const n = await fetch(`${FORMANT_API_URL}/v1/admin/shares`, {
21959
+ const i = (await this.getViews()).filter((c) => c.name === n);
21960
+ if (i.length === 0)
21961
+ return console.warn("View does not exist or it is misspell"), null;
21962
+ const s = await fetch(`${FORMANT_API_URL}/v1/admin/shares`, {
21968
21963
  method: "POST",
21969
21964
  body: JSON.stringify(t),
21970
21965
  headers: {
21971
21966
  "Content-Type": "application/json",
21972
21967
  Authorization: "Bearer " + Authentication.token
21973
21968
  }
21974
- }), r = FORMANT_API_URL.replace("api", "app"), { code: i } = await n.json();
21975
- return `${r}/shares/${i}/${serializeHash({
21976
- module: "pause",
21977
- speed: 1,
21978
- time: t.time
21969
+ }), l = FORMANT_API_URL.replace("api", "app"), { code: o } = await s.json();
21970
+ return `${l}/shares/${o}#${serializeHash({
21971
+ viewId: i[0].id
21979
21972
  })}`;
21980
21973
  }
21981
21974
  };
@@ -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 x={convertFromBase64:function(){return b("marking for base64 conversion"),w=!0,x},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}"`),x},required:function(F){return F===void 0?(b("marked as required"),h=!0):(b(`setting required flag to ${F}`),h=F),x},example:function(F){return E=F,x}};return Object.entries({...g,...c}).forEach(([F,M])=>{x[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 I=[d].concat(Array.prototype.slice.call(arguments));try{b(`passing value "${d}" to "${A.name}" accessor`);const $=A.apply(A,I);return b(`parsed successfully, returning ${$}`),$}catch($){R(d,$.message)}}}(M)}),x}}).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 z.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 vt}),n.d(t,"RtcClientV1",function(){return Mt}),n.d(t,"createRtcStreamMessage",function(){return Te});var r=n(28),i=function(be,D,H,X){return new(H||(H=Promise))(function(ie,oe){function de(ce){try{me(X.next(ce))}catch(ue){oe(ue)}}function ye(ce){try{me(X.throw(ce))}catch(ue){oe(ue)}}function me(ce){var ue;ce.done?ie(ce.value):(ue=ce.value,ue instanceof H?ue:new H(function(Ae){Ae(ue)})).then(de,ye)}me((X=X.apply(be,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(be,D,H,X){return new(H||(H=Promise))(function(ie,oe){function de(ce){try{me(X.next(ce))}catch(ue){oe(ue)}}function ye(ce){try{me(X.throw(ce))}catch(ue){oe(ue)}}function me(ce){var ue;ce.done?ie(ce.value):(ue=ce.value,ue instanceof H?ue:new H(function(Ae){Ae(ue)})).then(de,ye)}me((X=X.apply(be,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(be,D,H,X){return new(H||(H=Promise))(function(ie,oe){function de(ce){try{me(X.next(ce))}catch(ue){oe(ue)}}function ye(ce){try{me(X.throw(ce))}catch(ue){oe(ue)}}function me(ce){var ue;ce.done?ie(ce.value):(ue=ce.value,ue instanceof H?ue:new H(function(Ae){Ae(ue)})).then(de,ye)}me((X=X.apply(be,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 x=n(4),F=n(39);function M(be){return!!be.match(/^[a-zA-Z0-9-_.,:?'"()@\/\\#$+ ]{1,255}$/)}var A=function(be,D,H,X){return new(H||(H=Promise))(function(ie,oe){function de(ce){try{me(X.next(ce))}catch(ue){oe(ue)}}function ye(ce){try{me(X.throw(ce))}catch(ue){oe(ue)}}function me(ce){var ue;ce.done?ie(ce.value):(ue=ce.value,ue instanceof H?ue:new H(function(Ae){Ae(ue)})).then(de,ye)}me((X=X.apply(be,D||[])).next())})};function d({func:be,delay:D,immediate:H}){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=be(),yield oe}finally{if(!X){const me=new Date().getTime();ie=setTimeout(de,Math.max(D-(me-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 I=function(be,D,H,X){return new(H||(H=Promise))(function(ie,oe){function de(ce){try{me(X.next(ce))}catch(ue){oe(ue)}}function ye(ce){try{me(X.throw(ce))}catch(ue){oe(ue)}}function me(ce){var ue;ce.done?ie(ce.value):(ue=ce.value,ue instanceof H?ue:new H(function(Ae){Ae(ue)})).then(de,ye)}me((X=X.apply(be,D||[])).next())})};const $=n(226),q=!!x.c,m=new class{constructor(be){this.samplePeriodSeconds=60,this.buffer={},this.reporters=[],this.flushInterval=d({func:()=>this.flushStats(),delay:this.samplePeriodSeconds*c.a.second}),this.tags=this.filterTags((be==null?void 0:be.tags)||{app:x.a,version:x.j,namespace:x.i,instanceId:F.a})}shutdown(){return I(this,void 0,void 0,function*(){yield this.flushInterval.stop(),yield this.flushStats(),yield Object(u.a)(2*c.a.second)})}aggregate(be,D,H){this.addToBuffer(this.buffer,this.encodeKey({metric:be,tags:this.filterTags(H||{})}),typeof D=="number"?{min:D,max:D,sum:D,count:1}:D)}increment(be,D){this.aggregate(be,1,D)}timer(be,D,H){return I(this,void 0,void 0,function*(){const X=$(),ie=yield D(),oe=$();return this.aggregate(be,oe-X,H),ie})}registerStatsReporter(be){this.reporters.push(be)}setTag(be,D){const H=this.filterTags({[be]:D});this.tags=Object.assign(Object.assign({},this.tags),H)}addToBuffer(be,D,H){if(be[D]){const{min:X,max:ie,sum:oe,count:de}=be[D];be[D]={min:Math.min(X,H.min),max:Math.max(ie,H.max),sum:oe+H.sum,count:de+H.count}}else be[D]=H}write(be){return I(this,void 0,void 0,function*(){yield Promise.all(this.reporters.map(D=>I(this,void 0,void 0,function*(){let H;const X={};switch(D.type){case"simple":for(const[oe,de]of Object.entries(be)){const{metric:ye}=this.decodeKey(oe);this.addToBuffer(X,this.encodeKey({metric:ye}),de)}H=X;break;case"tagged":H=be;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:me}=this.decodeKey(oe);return{name:ye,tags:Object.assign(Object.assign({},me),this.tags),stat:de}}),this.samplePeriodSeconds).catch(oe=>{g.a.debug(`Failed to write stats to ${D.name}`,{error:oe})})})))})}flushStats(){return I(this,void 0,void 0,function*(){yield this.write(this.buffer),this.buffer={}})}encodeKey(be){return E()(Object.assign(Object.assign({},be),Object.keys(be.tags||{}).length>0?{tags:be.tags}:{}))}decodeKey(be){return JSON.parse(be)}filterTags(be){return Object.entries(be||{}).reduce((D,[H,X])=>(M(H)&&M(X)&&(D[H]=X),D),{})}};q||["local","on-prem"].includes(x.i)||m.registerStatsReporter(new R("stats"));var y=function(be,D,H,X){return new(H||(H=Promise))(function(ie,oe){function de(ce){try{me(X.next(ce))}catch(ue){oe(ue)}}function ye(ce){try{me(X.throw(ce))}catch(ue){oe(ue)}}function me(ce){var ue;ce.done?ie(ce.value):(ue=ce.value,ue instanceof H?ue:new H(function(Ae){Ae(ue)})).then(de,ye)}me((X=X.apply(be,D||[])).next())})};class C 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"&&m.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?m.increment("cache-miss",{name:H}):ie!==1/0&&m.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;m.aggregate("cache-item-count",this.cache.size,{name:D}),this.cache.calculatedSize!==void 0&&m.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(()=>y(this,void 0,void 0,function*(){yield Object(u.a)(this.rejectedPromiseValueTtl),this.peek(D)===H&&this.delete(D)}))}}var _=function(be,D,H,X){return new(H||(H=Promise))(function(ie,oe){function de(ce){try{me(X.next(ce))}catch(ue){oe(ue)}}function ye(ce){try{me(X.throw(ce))}catch(ue){oe(ue)}}function me(ce){var ue;ce.done?ie(ce.value):(ue=ce.value,ue instanceof H?ue:new H(function(Ae){Ae(ue)})).then(de,ye)}me((X=X.apply(be,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 C({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 z=n(97),B=n(40),N=function(be,D,H,X){return new(H||(H=Promise))(function(ie,oe){function de(ce){try{me(X.next(ce))}catch(ue){oe(ue)}}function ye(ce){try{me(X.throw(ce))}catch(ue){oe(ue)}}function me(ce){var ue;ce.done?ie(ce.value):(ue=ce.value,ue instanceof H?ue:new H(function(Ae){Ae(ue)})).then(de,ye)}me((X=X.apply(be,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 W=function(be,D,H,X){return new(H||(H=Promise))(function(ie,oe){function de(ce){try{me(X.next(ce))}catch(ue){oe(ue)}}function ye(ce){try{me(X.throw(ce))}catch(ue){oe(ue)}}function me(ce){var ue;ce.done?ie(ce.value):(ue=ce.value,ue instanceof H?ue:new H(function(Ae){Ae(ue)})).then(de,ye)}me((X=X.apply(be,D||[])).next())})};function O(be){return W(this,void 0,void 0,function*(){return(yield Promise.all(be.map(D=>D.catch(H=>H)))).filter(D=>D instanceof Error)})}function p(be){if(be!==void 0)return be;throw new Error("Value is undefined")}function U(be,D){const H=be.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(be.find(X=>X.urls.includes(H)))),{urls:[H]})}function V(be,D){switch(D){case"stun":return/^stuns?:/.test(be);case"turn":return/^turns?:/.test(be)}}function Q(be,D){return be.endsWith(`transport=${D}`)}var ee=n(9),ne=n(24),Y=n(229),G=n(29);const S={ordered:!1,maxPacketLifeTime:300*c.a.millisecond},T={ordered:!0},k={ordered:!0},J={ordered:!1,maxRetransmits:0},K={ordered:!1,maxRetransmits:0},re=be=>"received"in be&&be.received!==void 0,se=be=>!("received"in be)||be.received===void 0,fe=2*c.a.second;function ve(be,D={}){const H=Array.from(be.values()),X=H.filter(re),ie=X.length>0,oe=Math.max(...X.map(ce=>ce.received));let de;if(ie){const ce=H.length,ue=X.length,Ae=X.map(Ne=>Ne.received-Ne.sent),{standardDeviation:Me,mean:Ue,jitter:Ge}=function(Ne){const Fe=Ne.length;if(Fe===0)return{mean:NaN,standardDeviation:-1,jitter:NaN};const Ye=Ne.reduce((Je,ot)=>Je+ot,0)/Fe,Ke=Math.sqrt(Ne.map(Je=>Math.pow(Je-Ye,2)).reduce((Je,ot)=>Je+ot)/Fe);let Xe=0;for(let Je=1;Je<Fe;++Je)Xe+=Math.abs(Ne[Je]-Ne[Je-1]);return{mean:Ye,standardDeviation:Ke,jitter:Xe/(Fe-1)}}(Ae),Qe=H.filter(Ne=>Ne.sent<oe-fe),qe=Qe.filter(se),$e=qe.length===0?0:qe.length/Qe.length;de={pingsSent:ce,pongsReceived:ue,average:Ue,standardDeviation:Me,jitter:Ge,max:Math.max(...Ae),min:Math.min(...Ae),loss:$e}}else de=null;const{temporalNow:ye=Date.now()}=D,me=(ie?oe:ye)-4*fe;return Array.from(be.entries()).forEach(ce=>{const[ue,Ae]=ce;Ae.sent<me&&be.delete(ue)}),de}function Ie({entityId:be,streamName:D,streamType:H}){return`${be}.${D}.${H}`}var Se=function(be,D,H,X){return new(H||(H=Promise))(function(ie,oe){function de(ce){try{me(X.next(ce))}catch(ue){oe(ue)}}function ye(ce){try{me(X.throw(ce))}catch(ue){oe(ue)}}function me(ce){var ue;ce.done?ie(ce.value):(ue=ce.value,ue instanceof H?ue:new H(function(Ae){Ae(ue)})).then(de,ye)}me((X=X.apply(be,D||[])).next())})};class Ce{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 Se(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,me=[...new Set([...ie.keys(),...oe.keys()])].reduce((ce,ue)=>{const Ae=ie.get(ue),Me=oe.get(ue),Ue=de.get(ue),Ge=ye.get(ue);return Object.assign(Object.assign({},ce),{[`local-${ue}-sent`]:Ae,[`local-${ue}-received`]:Me,[`remote-${ue}-sent`]:Ue,[`remote-${ue}-received`]:Ge})},{sessionId:D});g.a.debug("rtc-message-report",Object.assign({deviceId:this.connection.getRemoteDeviceId()},me))})}}function Te(be,D,H){return{header:{stream:be,created:Date.now(),frameId:H||""},payload:D}}function Re(be){return new Set(["disconnected","failed","closed"]).has(be.iceConnectionState)}function Be(be){switch(be.header.stream.streamType){case"twist":{const{twist:D}=be.payload;if(!D)throw Error("twist not in payload of RTC message with type twist");return{header:be.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}=be.payload;if(!D)throw Error("pose not in payload of RTC message with type pose");return{header:be.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}=be.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:be.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}=be.payload;if(!D)throw Error("point not in payload of RTC message with type point");return{header:be.header,payload:{point:Object.assign({x:0,y:0,z:0},D)}}}default:return be}}var Ze=function(be,D,H,X){return new(H||(H=Promise))(function(ie,oe){function de(ce){try{me(X.next(ce))}catch(ue){oe(ue)}}function ye(ce){try{me(X.throw(ce))}catch(ue){oe(ue)}}function me(ce){var ue;ce.done?ie(ce.value):(ue=ce.value,ue instanceof H?ue:new H(function(Ae){Ae(ue)})).then(de,ye)}me((X=X.apply(be,D||[])).next())})};class et{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=ve(this.pingV2Map);oe&&(this.pingInfo=oe,m.aggregate("rtc-ping-average",oe.average),m.aggregate("rtc-ping-loss",oe.loss),m.aggregate("rtc-jitter",oe.jitter))};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,me)=>{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 Ze(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:me}=H;if(ye!=="stable"||me!=="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 ue=D.clone();return X==null||X("Answer Received",ue),ue.setPayload(JSON.stringify(ce)),ue.setReceiverId(D.getSenderId()),ue.setSenderId(D.getReceiverId()),ue}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 Ze(this,void 0,void 0,function*(){if(this.closeCalled)return;this.closeCalled=!0,this.sessionMetrics&&(yield this.sessionMetrics.uploadMetrics()),nt(this.pingUpdateTimeout),nt(this.pingV2UpdateTimeout),nt(this.pingV2MetricsGatherTimeout),nt(this.reassemblyTableCleanupTimeout),nt(this.streamsInfoUpdateTimeout),nt(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 Ce(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 Ze(this,void 0,void 0,function*(){const{peerConnection:D}=this;if(!D)return;const H=yield D.getStats(null),X=[];H.forEach(me=>{X.push(me)});const ie=X.find(me=>me.type==="transport");if(!ie)return;const oe=X.find(me=>(me.type==="candidate-pair"||me.type==="candidatepair")&&me.id===ie.selectedCandidatePairId);if(!oe)return;const de=X.find(me=>me.id===oe.localCandidateId),ye=X.find(me=>me.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",K),this.heartbeatChannel.binaryType="arraybuffer",this.latestTtlStreamChannel=D.createDataChannel("stream.latest-ttl",S),this.latestTtlStreamChannel.binaryType="arraybuffer",this.reliableStreamChannel=D.createDataChannel("stream.reliable",T),this.reliableStreamChannel.binaryType="arraybuffer",this.latestReliableStreamChannel=D.createDataChannel("stream.latest-reliable",k),this.latestReliableStreamChannel.binaryType="arraybuffer",this.latestTryOnceStreamChannel=D.createDataChannel("stream.latest-try-once",J),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 Ze(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,Re(this.peerConnection))return void g.a.debug("Failed to generate offer because the peer connection was inactive.");const me=de.baseConfig.track;oe.onicecandidate=()=>{this.hasIceCandidate=!0},oe.oniceconnectionstatechange=()=>Ze(this,void 0,void 0,function*(){const Ue=oe.iceConnectionState;if(Ue==="connected"||Ue==="completed"){const Ge=yield this.getConnectionStatsInfo(),Qe=Ge?function(qe){const $e=qe.localCandidate.candidateType,Ne=qe.remoteCandidate.candidateType;return $e==="host"&&Ne==="host"?"local":$e==="relay"||Ne==="relay"?"TURN":"STUN"}(Ge):void 0;g.a.info(`ICE connection state changed to ${Ue}`,{sessionId:ye,connectionStatsInfo:Ge,iceMode:Qe}),me==null||me("ICE connection state change",{iceConnectionState:Ue,sessionId:ye,connectionStatsInfo:Ge,iceMode:Qe})}}),yield oe.setLocalDescription(yield oe.createOffer());const ce=new Date().getTime();for(;;){const Ue=new Date().getTime()-ce;if(Ue>this.connectTimeoutMs)return void g.a.debug("Failed to generate offer because ICE gathering timed out.");if(Ue>this.iceGatheringTimeoutMs&&this.hasIceCandidate){g.a.debug("ICE gathering partially completed; proceeding",{iceTransportPolicy:oe.getConfiguration().iceTransportPolicy,waitTime:Ue}),me==null||me("ICE gathering partially completed",{sessionId:ye,iceTransportPolicy:oe.getConfiguration().iceTransportPolicy,waitTime:Ue});break}if(oe.iceGatheringState==="complete"){g.a.debug("ICE gathering complete",{iceTransportPolicy:oe.getConfiguration().iceTransportPolicy,waitTime:Ue}),me==null||me("ICE gathering completed",{sessionId:ye,iceTransportPolicy:oe.getConfiguration().iceTransportPolicy,waitTime:Ue});break}yield Object(u.a)(.1*c.a.second)}const ue=(H=this.peerConnection.getConfiguration().iceServers)!==null&&H!==void 0?H:[];for(const Ue of ue)Ue.credentialType=void 0;const Ae=JSON.stringify(ue),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(Ae),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 Ze(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,Re(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 Ze(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(G.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(G.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=Be(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,me)=>ye.seq<me.seq?-1:1).map(ye=>ye.part).reduce((ye,me)=>ye+me);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}=de;switch(H.header.stream.streamType){case"ping":return this.sendSystemMessage(D,{type:"pong",timestamp:p(H.payload.ping)}),!0;case"pong":{const me=new Date().getTime()-p(H.payload.pong);return this.pingTimeMs=me,m.aggregate("rtc-ping-time",me),!0}case"ping-v2":return this.sendPingV2(),!0;case"pong-v2":{const me=p(H.payload.pongV2),ce=this.pingV2Map.get(me.id);return(ce==null?void 0:ce.sent)!==me.timestamp?(g.a.warn("Pong timestamp doesn't match stored value",{currentEntry:ce,pong:me}),!0):(this.pingV2Map.set(me.id,{sent:me.timestamp,received:new Date().getTime()}),!0)}case"streams-info":{const{sessionMetrics:me}=this,ce=(X=H.payload.streamsInfo)===null||X===void 0?void 0:X.timestamp;return!!ce&&(me==null||me.updateRemoteMessagesCounts(H),(ie=de.onStreamsInfoUpdate)===null||ie===void 0||ie.call(de,ye,ce),!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,Te(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 nt(be){be&&clearInterval(be)}function Rt(be){var D,H;return{userId:(D=be.getUserId())===null||D===void 0?void 0:D.getValue(),deviceId:(H=be.getDeviceId())===null||H===void 0?void 0:H.getValue(),organizationId:be.getOrganizationId(),id:be.getPeerId(),capabilities:[],capabilitySet:{}}}var Pe=function(be,D,H,X){return new(H||(H=Promise))(function(ie,oe){function de(ce){try{me(X.next(ce))}catch(ue){oe(ue)}}function ye(ce){try{me(X.throw(ce))}catch(ue){oe(ue)}}function me(ce){var ue;ce.done?ie(ce.value):(ue=ce.value,ue instanceof H?ue:new H(function(Ae){Ae(ue)})).then(de,ye)}me((X=X.apply(be,D||[])).next())})};class vt{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=[];const{refreshIntervalDelayMs:H}=this;this.refreshInterval=d({func:()=>Pe(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 Pe(this,void 0,void 0,function*(){for(;!this.localPeer;)yield Object(u.a)(.1*c.a.second);return Rt(this.localPeer)})}connect(D,H){var X,ie,oe;return Pe(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:me,receiveSignalStream:ce,iceServers:ue}=this;if(!me||!ce||!ue)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 Ae=function(Ne,Fe,Ye){const{rtcIceTransportPolicies:Ke,rtcIceServerProtocol:Xe,useAllServers:Je}=Fe||{},ot=Ne.map(at=>Object.assign(Object.assign({},at),{urls:at.urls.filter(dt=>{const wt=(Ke===void 0||Ke.some(St=>V(dt,St)))&&(Xe===void 0||Q(dt,Xe));return wt||g.a.debug(`Ignoring ICE server: ${dt}`,{organizationId:Ye}),wt})})).filter(({urls:at})=>at.filter(dt=>dt).length>0);return Je?ot:[U(ot,"stun"),U(ot,"turn")].filter(at=>at!==void 0).map(at=>p(at))}(ue,H);g.a.debug("Received ICE servers:",ue),g.a.debug("Using ICE servers:",Ae);const Me=new et(yield this.createRTCPeerConnection(Ae),{baseConfig:{isOffer:!0,isLan:!1,receive:(Ne,Fe)=>this.config.receive(Ne,Fe),onStreamsInfoUpdate:this.config.onStreamsInfoUpdate?(Ne,Fe)=>{var Ye,Ke;return(Ke=(Ye=this.config).onStreamsInfoUpdate)===null||Ke===void 0?void 0:Ke.call(Ye,Ne,Fe)}:void 0,track:this.config.lanOnlyMode?void 0:this.config.track,localUserId:(X=me.getUserId())===null||X===void 0?void 0:X.getValue(),localPeerId:me.getPeerId(),remotePeerId:D,sessionType:this.config.sessionType},remoteConfig:{}},Ne=>this.onCustomDataChannel(D,Ne)),Ue=yield Me.getOffer();if(!Ue)return g.a.error("Failed to generate offer."),void this.isOutgoingConnection.delete(D);g.a.debug("Sending offer."),de==null||de("Sending offer",Ue);const Ge=new ee.SendSignalRequest;Ge.setSignal(Ue);const Qe=yield(()=>Pe(this,void 0,void 0,function*(){try{return yield ye.sendSignal(Ge,yield this.getMetadata({}))}catch(Ne){g.a.warn("Error when sending signal",{error:Ne})}}))();if(!this.isOutgoingConnection.get(D))return void g.a.debug("No offer set after receiving offer signal response.");g.a.debug("Offer sent.");const qe=(ie=Qe==null?void 0:Qe.getSessionId())===null||ie===void 0?void 0:ie.getValue(),$e=(oe=Qe==null?void 0:Qe.getSessionCreatedTimestamp())===null||oe===void 0?void 0:oe.getValue();return qe&&$e?(Me.setSessionId(qe),Me.setSessionCreatedTimestamp($e),this.isOutgoingConnection.delete(D),this.connections.push(Me),this.isConnectionInitiator.set(Me,!0),this.setupHandlers(Me),qe):(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 Pe(this,void 0,void 0,function*(){const ie=new P(D),oe=new et(yield this.createRTCPeerConnection([]),{baseConfig:{isOffer:!0,isLan:!0,receive:(ce,ue)=>this.config.receive(ce,ue),onStreamsInfoUpdate:this.config.onStreamsInfoUpdate?(ce,ue)=>{var Ae,Me;return(Me=(Ae=this.config).onStreamsInfoUpdate)===null||Me===void 0?void 0:Me.call(Ae,ce,ue)}: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)}),me=new RTCSessionDescription(JSON.parse(ye.answer));return yield oe.handleLanAnswer(me),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 me=de.peerConnection.createDataChannel("custom."+H,X);return ie&&(me.binaryType="arraybuffer"),oe(D,me),()=>{}}const ye=(me,ce)=>{D===me&&ce.label==="custom."+H&&oe(D,ce)};return this.peerDataChannelListeners.push(ye),()=>{this.peerDataChannelListeners=this.peerDataChannelListeners.filter(me=>me!==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 Pe(this,void 0,void 0,function*(){const H=this.getActiveConnection(D);if(H)return yield H.getConnectionStatsInfo()})}disconnect(D){return Pe(this,void 0,void 0,function*(){const H=this.getActiveConnection(D);H&&(yield H.close())})}getPeers(){return Pe(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(()=>Pe(this,void 0,void 0,function*(){try{return yield D.getPeers(new ee.GetPeersRequest,yield this.getMetadata({}))}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=>Rt(oe))})}getSessions(){return Pe(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(()=>Pe(this,void 0,void 0,function*(){try{return yield D.getPeers(new ee.GetPeersRequest,yield this.getMetadata({}))}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 Pe(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(()=>Pe(this,void 0,void 0,function*(){try{const ie=new ee.DeletePeerRequest;ie.setPeerId(H.getPeerId()),yield X.deletePeer(ie,yield this.getMetadata({}))}catch(ie){return void g.a.warn("Error deleting local peer",{error:ie})}}))()})}createPeer(){return Pe(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(()=>Pe(this,void 0,void 0,function*(){try{return yield D.createPeer(new ee.CreatePeerRequest,yield this.getMetadata({}))}catch(ie){throw new Error(`Was not able to create peer: ${JSON.stringify(ie)}`)}}))(),X=H==null?void 0:H.getPeer();if(!X)throw new Error("Response did not provide peer.");return this.localPeer=X})}createReceiveSignalStream(){return Pe(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(()=>Pe(this,void 0,void 0,function*(){try{return D.receiveSignalStream(oe,yield this.getMetadata({hasDeadline:!1}))}catch(ye){throw new Error(`Unable to create receive signal stream: ${JSON.stringify(ye)}`)}}))();if(!de)throw new Error("Response did not provide stream.");return de.on("data",ye=>Pe(this,void 0,void 0,function*(){var me,ce,ue,Ae;const Me=ye.getSignal(),Ue=(me=Me==null?void 0:Me.getSessionId())===null||me===void 0?void 0:me.getValue(),Ge=Me==null?void 0:Me.getSenderId(),Qe=Me==null?void 0:Me.getReceiverId(),qe=(ce=Me==null?void 0:Me.getSessionCreatedTimestamp())===null||ce===void 0?void 0:ce.getValue();if(!(Me&&Ue&&Ge&&Qe&&qe))return void g.a.warn("Received signal with missing information.");const $e=this.getActiveConnection(Ge);if($e)if($e.getSessionId()!==Ue){if(g.a.debug("Received signal: different session for a peer we're already connected to."),($e.getSessionCreatedTimestamp()||0)>qe)return;const Ne=new et(yield this.createRTCPeerConnection(X),{baseConfig:{isOffer:!1,isLan:!1,receive:(Fe,Ye)=>this.config.receive(Fe,Ye),onStreamsInfoUpdate:this.config.onStreamsInfoUpdate?(Fe,Ye)=>{var Ke,Xe;return(Xe=(Ke=this.config).onStreamsInfoUpdate)===null||Xe===void 0?void 0:Xe.call(Ke,Fe,Ye)}:void 0,track:this.config.lanOnlyMode?void 0:this.config.track,localPeerId:H.getPeerId(),localUserId:(Ae=H.getUserId())===null||Ae===void 0?void 0:Ae.getValue(),remotePeerId:Ge},remoteConfig:{sessionId:Ue,sessionCreatedTimestamp:qe}},Fe=>this.onCustomDataChannel(Ge,Fe));yield Ne.handleSignal(Me),this.connections.push(Ne)}else g.a.debug("Received signal: for an existing connection."),yield $e.handleSignal(Me);else{g.a.debug("Received signal: new connection.");const Ne=new et(yield this.createRTCPeerConnection(X),{baseConfig:{isOffer:!1,isLan:!1,receive:(Fe,Ye)=>this.config.receive(Fe,Ye),onStreamsInfoUpdate:this.config.onStreamsInfoUpdate?(Fe,Ye)=>{var Ke,Xe;return(Xe=(Ke=this.config).onStreamsInfoUpdate)===null||Xe===void 0?void 0:Xe.call(Ke,Fe,Ye)}:void 0,track:this.config.lanOnlyMode?void 0:this.config.track,localPeerId:H.getPeerId(),localUserId:(ue=H.getUserId())===null||ue===void 0?void 0:ue.getValue(),remotePeerId:Ge},remoteConfig:{sessionId:Ue,sessionCreatedTimestamp:qe}},Fe=>this.onCustomDataChannel(Ge,Fe));yield Ne.handleSignal(Me),this.connections.push(Ne)}})),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 Pe(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.");return new X({iceServers:D})})}closeConnections(D){return Pe(this,void 0,void 0,function*(){const H=yield O(D.map(X=>Pe(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 Pe(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)return this.localPeer||(yield this.createPeer()),this.iceServers||(yield this.updateIceServers()),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 H.refreshPeer(oe,yield this.getMetadata({}))}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(me=>me.id===ye.getRemotePeerId()))===null||D===void 0?void 0:D.deviceId)})}reset(){return Pe(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 Pe(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 this.config.signalingClient.getIceServers(new ee.GetIceServersRequest,yield this.getMetadata({}))).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=()=>Pe(this,void 0,void 0,function*(){const ie=H.connectionState;if(X)switch(ie){case"connected":m.aggregate("rtc-connect-time",new Date().getTime()-X);break;case"failed":m.increment("rtc-connect-failed")}})}getMetadata(D){return Pe(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;return{authorization:yield H(),deadline:oe}})}}var ft=n(10),ut=n(11),Ot=function(be,D,H,X){return new(H||(H=Promise))(function(ie,oe){function de(ce){try{me(X.next(ce))}catch(ue){oe(ue)}}function ye(ce){try{me(X.throw(ce))}catch(ue){oe(ue)}}function me(ce){var ue;ce.done?ie(ce.value):(ue=ce.value,ue instanceof H?ue:new H(function(Ae){Ae(ue)})).then(de,ye)}me((X=X.apply(be,D||[])).next())})};class It{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 Ot(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),me=this.receivedMessagesCounts.get(de);return Object.assign(Object.assign({},oe),{[`${de}-sent`]:ye,[`${de}-received`]:me})},{sessionId:D});g.a.debug("rtc-message-report",ie)})}}function ct(be,D){return Ie(be)===Ie(D)}var tt=function(be,D,H,X){return new(H||(H=Promise))(function(ie,oe){function de(ce){try{me(X.next(ce))}catch(ue){oe(ue)}}function ye(ce){try{me(X.throw(ce))}catch(ue){oe(ue)}}function me(ce){var ue;ce.done?ie(ce.value):(ue=ce.value,ue instanceof H?ue:new H(function(Ae){Ae(ue)})).then(de,ye)}me((X=X.apply(be,D||[])).next())})};class Ct{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 It(this.getSessionId(),this)}connect(){return tt(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(()=>tt(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(()=>tt(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=>tt(this,void 0,void 0,function*(){ie.candidate?this.receivedIceCandidate=!0:yield this.sendOffer()}),D.onicegatheringstatechange=()=>tt(this,void 0,void 0,function*(){D.iceGatheringState==="complete"&&(yield this.sendOffer())}),D.onnegotiationneeded=()=>{g.a.debug("Negotiation needed",{sessionId:X})})})}handleSignal(D){return tt(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 Re(D)||de(H)||de(X)||de(ie)}close(){return tt(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",S),this.reliableStreamChannel=D.createDataChannel("stream.reliable",T),this.latestReliableStreamChannel=D.createDataChannel("stream.latest-reliable",k),this.latestTryOnceStreamChannel=D.createDataChannel("stream.latest-try-once",J),this.setupChannel(this.latestTtlStreamChannel),this.setupChannel(this.reliableStreamChannel),this.setupChannel(this.latestReliableStreamChannel),this.setupChannel(this.latestTryOnceStreamChannel)}sendOffer(){return tt(this,void 0,void 0,function*(){if(this.sentOffer||(this.sentOffer=!0,Re(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(G.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(G.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=Be(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,m.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,Te(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(ue=>ue.receive&&ct(ue.stream,D.header.stream)),me=(X=oe.capabilitySet.streaming)===null||X===void 0?void 0:X.streams,ce=me&&me.some(ue=>ue.send&&ct(ue.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 ke=function(be,D,H,X){return new(H||(H=Promise))(function(ie,oe){function de(ce){try{me(X.next(ce))}catch(ue){oe(ue)}}function ye(ce){try{me(X.throw(ce))}catch(ue){oe(ue)}}function me(ce){var ue;ce.done?ie(ce.value):(ue=ce.value,ue instanceof H?ue:new H(function(Ae){Ae(ue)})).then(de,ye)}me((X=X.apply(be,D||[])).next())})};class Mt{constructor(D){this.config=D,this.connections=[],this.connectingSessions=new Map,this.updateInterval=d({func:()=>ke(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 ke(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(ft.a)(ie,ut.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 ke(this,void 0,void 0,function*(){const H=this.getActiveConnection(D);H&&(yield this.closeConnection(H))})}getLocalPeer(){return ke(this,void 0,void 0,function*(){return yield this.localPeer})}getPeers(){return ke(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 ke(this,void 0,void 0,function*(){yield this.updateInterval.stop();const D=this.connections;this.connections=[],yield this.closeConnections(D)})}closeConnection(D){return ke(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(ft.a)(H,ut.a,X=>X.statusCode===404)}})}getSessions(){return ke(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 ke(this,void 0,void 0,function*(){return yield this.config.signalingClient.createPeer(yield this.config.getToken(),{capabilitySet:this.config.capabilitySet||{}})})}createRTCPeerConnection(D={}){return ke(this,void 0,void 0,function*(){return new(this.config.alternateRTCPeerConnection||RTCPeerConnection)(Object.assign({iceServers:yield this.config.signalingClient.getIceServers(yield this.config.getToken())},D))})}closeConnections(D){return ke(this,void 0,void 0,function*(){const H=yield O(D.map(X=>ke(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 ke(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 ke(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(ft.a)(H,ut.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 ke(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})=>ke(this,void 0,void 0,function*(){return yield this.maintainConnection(X,ie)})))})}syncConnectionsAndSessions(D){return ke(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=>ke(this,void 0,void 0,function*(){yield this.closeConnection(oe)})))})}maintainConnection(D,H){return ke(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(ft.a)(oe,ut.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 ke(this,void 0,void 0,function*(){const H=yield this.getLocalPeer(),X=D.offer.peer.id===H.id,ie=yield this.createRTCPeerConnection(),oe=new Ct(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=()=>ke(this,void 0,void 0,function*(){const ie=this.connectingSessions.get(X);if(ie===void 0)return;const oe=H.connectionState;switch(Re(H)&&this.connectingSessions.delete(X),oe){case"connected":{this.connectingSessions.delete(X);const de=new Date().getTime()-ie;m.aggregate("rtc-connect-time",de);break}case"failed":m.increment("rtc-connect-failed"),yield this.closeConnection(D)}})}consumeSignals(D){return ke(this,void 0,void 0,function*(){let H=[];try{H=yield this.config.signalingClient.takeSignals(yield this.config.getToken(),D.getSessionId())}catch(X){Object(ft.a)(X,ut.a,ie=>ie.statusCode===404)}for(const X of H)yield D.handleSignal(X)})}sendSignal(D,H){return ke(this,void 0,void 0,function*(){try{yield this.config.signalingClient.addSignals(yield this.config.getToken(),D,{signals:[H]})}catch(X){Object(ft.a)(X,ut.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(10),s=n(11),l=function(c,u,f,E){return new(f||(f=Promise))(function(w,h){function g(x){try{R(E.next(x))}catch(F){h(F)}}function b(x){try{R(E.throw(x))}catch(F){h(F)}}function R(x){var F;x.done?w(x.value):(F=x.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}={}){Oe(this,"entries",new Map);Oe(this,"metadata",new Map);Oe(this,"capacity");Oe(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(){Oe(this,"queryStoreCache",new StoreCache({capacity:1e4,timeout:20*duration.second}));Oe(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;Oe(Authentication,"token"),Oe(Authentication,"refreshToken"),Oe(Authentication,"currentUser"),Oe(Authentication,"currentOrganization"),Oe(Authentication,"isShareToken",!1),Oe(Authentication,"defaultDeviceId"),Oe(Authentication,"waitingForAuth",[]);function delay(e){return new Promise(t=>setTimeout(t,e))}class DataChannel{constructor(t){Oe(this,"ready",!1);Oe(this,"listeners",[]);Oe(this,"openListeners",[]);Oe(this,"closeListeners",[]);Oe(this,"errorListeners",[]);Oe(this,"binaryListeners",[]);Oe(this,"error");Oe(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){Oe(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){Oe(this,"currentListeners",[]);Oe(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){Oe(this,"channel");Oe(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);Oe(this,"RESPONSE_SUCCESS_BYTE",0);Oe(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")}}const urlParams$1=new URLSearchParams(window.location.search),rtcClientVersion=urlParams$1.get("rtc_client"),SessionType={Teleop:1,Observe:3};class Device{constructor(t,n,r){Oe(this,"rtcClient");Oe(this,"remoteDevicePeerId");Oe(this,"realtimeListeners",[]);Oe(this,"handleMessage",(t,n)=>{this.realtimeListeners.forEach(r=>r(t,n))});this.id=t,this.name=n,this.organizationId=r}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 t=await fetch(`${FORMANT_API_URL}/v1/admin/devices/${this.id}`,{method:"GET",headers:{"Content-Type":"application/json",Authorization:"Bearer "+Authentication.token}});const n=await t.json();if(!n.state.reportedConfiguration)throw new Error("Device has no configuration, has it ever been turned on?");const r=n.state.reportedConfiguration.version;return t=await fetch(`${FORMANT_API_URL}/v1/admin/devices/${this.id}/configurations/${r}`,{method:"GET",headers:{"Content-Type":"application/json",Authorization:"Bearer "+Authentication.token}}),(await t.json()).document}async getFileUrl(t){return(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()).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(t){if(this.rtcClient)throw new Error(`Already created realtime connection to device ${this.id}`);{let n;if(rtcClientVersion==="1"?n=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}):n=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:t}),n.isReady)for(;!n.isReady();)await delay(100);const i=(await n.getPeers()).find(s=>s.deviceId===this.id);if(!i)throw new Error("Cannot find peer, is the robot offline?");for(this.remoteDevicePeerId=i.id,await n.connect(this.remoteDevicePeerId);n.getConnectionStatus(this.remoteDevicePeerId)!=="connected";)await delay(100);this.rtcClient=n}}async sendRealtimeMessage(t,n={channelLabel:"stream.reliable"}){const r=defined(this.rtcClient,"Realtime connection has not been started"),i=await this.getRemotePeer();r.send(defined(i).id,t,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 getRealtimeAudioStreams(){var r,i,s;const t=await this.getConfiguration(),n=[];for(const l of((r=t.teleop)==null?void 0:r.hardwareStreams)??[])l.rtcStreamType==="audio-chunk"&&n.push({name:l.name});for(const l of((i=t.teleop)==null?void 0:i.rosStreams)??[])l.topicType=="audio_common_msgs/AudioData"&&n.push({name:l.topicName});for(const l of((s=t.teleop)==null?void 0:s.customStreams)??[])l.rtcStreamType==="audio-chunk"&&n.push({name:l.name});return n}async getRealtimeVideoStreams(){var r,i,s;const t=await this.getConfiguration(),n=[];for(const l of((r=t.teleop)==null?void 0:r.hardwareStreams)??[])l.rtcStreamType==="h264-video-frame"&&n.push({name:l.name});for(const l of((i=t.teleop)==null?void 0:i.rosStreams)??[])l.topicType=="formant/H264VideoFrame"&&n.push({name:l.topicName});for(const l of((s=t.teleop)==null?void 0:s.customStreams)??[])l.rtcStreamType==="h264-video-frame"&&n.push({name:l.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 changeStreamAudioType(t,n){const r=defined(this.rtcClient,"Realtime connection has not been started"),i=await this.getRemotePeer();r.controlRemoteStream(defined(i).id,{streamName:t,setAudioFormat:n})}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(){const n=(await defined(this.rtcClient,"Realtime connection has not been started").getPeers()).find(r=>r.deviceId===this.id);return defined(n,"Could not find remote peer for device "+this.id)}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 isInRealtimeSession(){let t=await Fleet.getPeers(),n=await Fleet.getRealtimeSessions(),r=t.find(i=>i.deviceId===this.id);return r?n[r.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(r=>({name:r.name,id:r.id,command:r.command,description:r.description,parameterEnabled:r.parameterEnabled,parameterValue:r.parameterValue,parameterMeta:r.parameterMeta,enabled:r.enabled}))}async sendCommand(t,n,r,i){var u;const l=(await this.getAvailableCommands()).find(f=>f.name===t);if(!l)throw new Error(`Could not find command with name "${t}"`);let o="";n===void 0?l.parameterEnabled&&l.parameterValue&&(o=l.parameterValue):o=n;let c={value:o,scrubberTime:(r||new Date).toISOString(),meta:{...l.parameterMeta,...i}};await fetch(`${FORMANT_API_URL}/v1/admin/commands`,{method:"POST",body:JSON.stringify({commandTemplateId:l.id,organizationId:this.organizationId,deviceId:this.id,command:l.command,parameter:c,userId:(u=Authentication.currentUser)==null?void 0:u.id}),headers:{"Content-Type":"application/json",Authorization:"Bearer "+Authentication.token}})}async createCustomDataChannel(t,n){if(rtcClientVersion==="1")throw new Error("createCustomDataChannel is not supported in rtcClientVersion 1");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)}async createCaptureStream(t){const r=await(await fetch(`${FORMANT_API_URL}/v1/admin/capture-sessions`,{method:"POST",body:JSON.stringify({deviceId:this.id,streamName:t,tags:{}}),headers:{"Content-Type":"application/json",Authorization:"Bearer "+Authentication.token}})).json();return new CaptureStream(r)}async getTelemetry(t,n,r,i){return await Fleet.getTelemetry(this.id,t,n,r,i)}async getTelemetryStreams(){var o,c;const t=await this.getConfiguration(),n=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}}),r=[],i=[];return(c=(o=t.telemetry)==null?void 0:o.streams)==null||c.forEach(u=>{u.disabled!==!0&&r.push(u.name),u.onDemand===!0&&i.push(u.name)}),console.log(i),(await n.json()).items.filter(u=>!r.includes(u)).map(u=>({name:u,onDemand:i.includes(u)}))}async createInterventionRequest(t,n,r,i){return await(await fetch(`${FORMANT_API_URL}/v1/admin/intervention-requests`,{method:"POST",body:JSON.stringify({message:t,interventionType:n,time:new Date().toISOString(),deviceId:this.id,tags:i,data:r}),headers:{"Content-Type":"application/json",Authorization:"Bearer "+Authentication.token}})).json()}async addInterventionResponse(t,n,r){return await(await fetch(`${FORMANT_API_URL}/v1/admin/intervention-responses`,{method:"POST",body:JSON.stringify({interventionId:t,interventionType:n,data:r}),headers:{"Content-Type":"application/json",Authorization:"Bearer "+Authentication.token}})).json()}async getAnnotationCount(t,n){return await Fleet.getAnnotationCount({...t,deviceIds:[this.id]},n)}async getAnnotationCountByIntervals(t,n,r){return await Fleet.getAnnotationCountByIntervals({...t,deviceIds:[this.id]},n,r)}async eventsCounter(t,n,r,i,s){return await Fleet.eventsCounter(t,n,r,i,{...s,deviceIds:[this.id]})}async createShareLink(t){if(!Authentication.token)throw new Error("Not authenticated");return await(await fetch(`${FORMANT_API_URL}/v1/admin/shares`,{method:"POST",body:JSON.stringify({...t,deviceIds:[this.id]}),headers:{"Content-Type":"application/json",Authorization:"Bearer "+Authentication.token}})).json()}}class PeerDevice{constructor(t){Oe(this,"rtcClient");Oe(this,"remoteDevicePeerId");Oe(this,"realtimeListeners",[]);Oe(this,"id");Oe(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});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 Ve=class{static async setDefaultDevice(t){Ve.defaultDeviceId=t}static async getCurrentDevice(){if(!Authentication.token)throw new Error("Not authenticated");if(!Ve.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===Ve.defaultDeviceId).name,s=new Device(Ve.defaultDeviceId,i,defined(Authentication.currentOrganization));return Ve.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 Ve.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 Ve.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 Ve.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 Ve.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){if(!Authentication.token)throw new Error("Not authenticated");const n=await fetch(`${FORMANT_API_URL}/v1/admin/shares`,{method:"POST",body:JSON.stringify(t),headers:{"Content-Type":"application/json",Authorization:"Bearer "+Authentication.token}}),r=FORMANT_API_URL.replace("api","app"),{code:i}=await n.json();return`${r}/shares/${i}/${serializeHash({module:"pause",speed:1,time:t.time})}`}};let Fleet=Ve;Oe(Fleet,"defaultDeviceId"),Oe(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},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}var 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 x={convertFromBase64:function(){return b("marking for base64 conversion"),w=!0,x},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}"`),x},required:function(F){return F===void 0?(b("marked as required"),h=!0):(b(`setting required flag to ${F}`),h=F),x},example:function(F){return E=F,x}};return Object.entries({...g,...c}).forEach(([F,M])=>{x[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 I=[d].concat(Array.prototype.slice.call(arguments));try{b(`passing value "${d}" to "${A.name}" accessor`);const $=A.apply(A,I);return b(`parsed successfully, returning ${$}`),$}catch($){R(d,$.message)}}}(M)}),x}}).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 z.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 vt}),n.d(t,"RtcClientV1",function(){return Mt}),n.d(t,"createRtcStreamMessage",function(){return Te});var r=n(28),i=function(be,D,H,X){return new(H||(H=Promise))(function(ie,oe){function de(ce){try{me(X.next(ce))}catch(ue){oe(ue)}}function ye(ce){try{me(X.throw(ce))}catch(ue){oe(ue)}}function me(ce){var ue;ce.done?ie(ce.value):(ue=ce.value,ue instanceof H?ue:new H(function(Ae){Ae(ue)})).then(de,ye)}me((X=X.apply(be,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(be,D,H,X){return new(H||(H=Promise))(function(ie,oe){function de(ce){try{me(X.next(ce))}catch(ue){oe(ue)}}function ye(ce){try{me(X.throw(ce))}catch(ue){oe(ue)}}function me(ce){var ue;ce.done?ie(ce.value):(ue=ce.value,ue instanceof H?ue:new H(function(Ae){Ae(ue)})).then(de,ye)}me((X=X.apply(be,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(be,D,H,X){return new(H||(H=Promise))(function(ie,oe){function de(ce){try{me(X.next(ce))}catch(ue){oe(ue)}}function ye(ce){try{me(X.throw(ce))}catch(ue){oe(ue)}}function me(ce){var ue;ce.done?ie(ce.value):(ue=ce.value,ue instanceof H?ue:new H(function(Ae){Ae(ue)})).then(de,ye)}me((X=X.apply(be,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 x=n(4),F=n(39);function M(be){return!!be.match(/^[a-zA-Z0-9-_.,:?'"()@\/\\#$+ ]{1,255}$/)}var A=function(be,D,H,X){return new(H||(H=Promise))(function(ie,oe){function de(ce){try{me(X.next(ce))}catch(ue){oe(ue)}}function ye(ce){try{me(X.throw(ce))}catch(ue){oe(ue)}}function me(ce){var ue;ce.done?ie(ce.value):(ue=ce.value,ue instanceof H?ue:new H(function(Ae){Ae(ue)})).then(de,ye)}me((X=X.apply(be,D||[])).next())})};function d({func:be,delay:D,immediate:H}){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=be(),yield oe}finally{if(!X){const me=new Date().getTime();ie=setTimeout(de,Math.max(D-(me-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 I=function(be,D,H,X){return new(H||(H=Promise))(function(ie,oe){function de(ce){try{me(X.next(ce))}catch(ue){oe(ue)}}function ye(ce){try{me(X.throw(ce))}catch(ue){oe(ue)}}function me(ce){var ue;ce.done?ie(ce.value):(ue=ce.value,ue instanceof H?ue:new H(function(Ae){Ae(ue)})).then(de,ye)}me((X=X.apply(be,D||[])).next())})};const $=n(226),q=!!x.c,m=new class{constructor(be){this.samplePeriodSeconds=60,this.buffer={},this.reporters=[],this.flushInterval=d({func:()=>this.flushStats(),delay:this.samplePeriodSeconds*c.a.second}),this.tags=this.filterTags((be==null?void 0:be.tags)||{app:x.a,version:x.j,namespace:x.i,instanceId:F.a})}shutdown(){return I(this,void 0,void 0,function*(){yield this.flushInterval.stop(),yield this.flushStats(),yield Object(u.a)(2*c.a.second)})}aggregate(be,D,H){this.addToBuffer(this.buffer,this.encodeKey({metric:be,tags:this.filterTags(H||{})}),typeof D=="number"?{min:D,max:D,sum:D,count:1}:D)}increment(be,D){this.aggregate(be,1,D)}timer(be,D,H){return I(this,void 0,void 0,function*(){const X=$(),ie=yield D(),oe=$();return this.aggregate(be,oe-X,H),ie})}registerStatsReporter(be){this.reporters.push(be)}setTag(be,D){const H=this.filterTags({[be]:D});this.tags=Object.assign(Object.assign({},this.tags),H)}addToBuffer(be,D,H){if(be[D]){const{min:X,max:ie,sum:oe,count:de}=be[D];be[D]={min:Math.min(X,H.min),max:Math.max(ie,H.max),sum:oe+H.sum,count:de+H.count}}else be[D]=H}write(be){return I(this,void 0,void 0,function*(){yield Promise.all(this.reporters.map(D=>I(this,void 0,void 0,function*(){let H;const X={};switch(D.type){case"simple":for(const[oe,de]of Object.entries(be)){const{metric:ye}=this.decodeKey(oe);this.addToBuffer(X,this.encodeKey({metric:ye}),de)}H=X;break;case"tagged":H=be;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:me}=this.decodeKey(oe);return{name:ye,tags:Object.assign(Object.assign({},me),this.tags),stat:de}}),this.samplePeriodSeconds).catch(oe=>{g.a.debug(`Failed to write stats to ${D.name}`,{error:oe})})})))})}flushStats(){return I(this,void 0,void 0,function*(){yield this.write(this.buffer),this.buffer={}})}encodeKey(be){return E()(Object.assign(Object.assign({},be),Object.keys(be.tags||{}).length>0?{tags:be.tags}:{}))}decodeKey(be){return JSON.parse(be)}filterTags(be){return Object.entries(be||{}).reduce((D,[H,X])=>(M(H)&&M(X)&&(D[H]=X),D),{})}};q||["local","on-prem"].includes(x.i)||m.registerStatsReporter(new R("stats"));var y=function(be,D,H,X){return new(H||(H=Promise))(function(ie,oe){function de(ce){try{me(X.next(ce))}catch(ue){oe(ue)}}function ye(ce){try{me(X.throw(ce))}catch(ue){oe(ue)}}function me(ce){var ue;ce.done?ie(ce.value):(ue=ce.value,ue instanceof H?ue:new H(function(Ae){Ae(ue)})).then(de,ye)}me((X=X.apply(be,D||[])).next())})};class C 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"&&m.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?m.increment("cache-miss",{name:H}):ie!==1/0&&m.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;m.aggregate("cache-item-count",this.cache.size,{name:D}),this.cache.calculatedSize!==void 0&&m.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(()=>y(this,void 0,void 0,function*(){yield Object(u.a)(this.rejectedPromiseValueTtl),this.peek(D)===H&&this.delete(D)}))}}var _=function(be,D,H,X){return new(H||(H=Promise))(function(ie,oe){function de(ce){try{me(X.next(ce))}catch(ue){oe(ue)}}function ye(ce){try{me(X.throw(ce))}catch(ue){oe(ue)}}function me(ce){var ue;ce.done?ie(ce.value):(ue=ce.value,ue instanceof H?ue:new H(function(Ae){Ae(ue)})).then(de,ye)}me((X=X.apply(be,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 C({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 z=n(97),B=n(40),N=function(be,D,H,X){return new(H||(H=Promise))(function(ie,oe){function de(ce){try{me(X.next(ce))}catch(ue){oe(ue)}}function ye(ce){try{me(X.throw(ce))}catch(ue){oe(ue)}}function me(ce){var ue;ce.done?ie(ce.value):(ue=ce.value,ue instanceof H?ue:new H(function(Ae){Ae(ue)})).then(de,ye)}me((X=X.apply(be,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 W=function(be,D,H,X){return new(H||(H=Promise))(function(ie,oe){function de(ce){try{me(X.next(ce))}catch(ue){oe(ue)}}function ye(ce){try{me(X.throw(ce))}catch(ue){oe(ue)}}function me(ce){var ue;ce.done?ie(ce.value):(ue=ce.value,ue instanceof H?ue:new H(function(Ae){Ae(ue)})).then(de,ye)}me((X=X.apply(be,D||[])).next())})};function O(be){return W(this,void 0,void 0,function*(){return(yield Promise.all(be.map(D=>D.catch(H=>H)))).filter(D=>D instanceof Error)})}function p(be){if(be!==void 0)return be;throw new Error("Value is undefined")}function U(be,D){const H=be.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(be.find(X=>X.urls.includes(H)))),{urls:[H]})}function V(be,D){switch(D){case"stun":return/^stuns?:/.test(be);case"turn":return/^turns?:/.test(be)}}function Q(be,D){return be.endsWith(`transport=${D}`)}var ee=n(9),ne=n(24),Y=n(229),G=n(29);const S={ordered:!1,maxPacketLifeTime:300*c.a.millisecond},T={ordered:!0},k={ordered:!0},J={ordered:!1,maxRetransmits:0},K={ordered:!1,maxRetransmits:0},re=be=>"received"in be&&be.received!==void 0,se=be=>!("received"in be)||be.received===void 0,fe=2*c.a.second;function ve(be,D={}){const H=Array.from(be.values()),X=H.filter(re),ie=X.length>0,oe=Math.max(...X.map(ce=>ce.received));let de;if(ie){const ce=H.length,ue=X.length,Ae=X.map(Ne=>Ne.received-Ne.sent),{standardDeviation:Me,mean:Ue,jitter:Ge}=function(Ne){const Fe=Ne.length;if(Fe===0)return{mean:NaN,standardDeviation:-1,jitter:NaN};const Ye=Ne.reduce((Je,ot)=>Je+ot,0)/Fe,Ke=Math.sqrt(Ne.map(Je=>Math.pow(Je-Ye,2)).reduce((Je,ot)=>Je+ot)/Fe);let Xe=0;for(let Je=1;Je<Fe;++Je)Xe+=Math.abs(Ne[Je]-Ne[Je-1]);return{mean:Ye,standardDeviation:Ke,jitter:Xe/(Fe-1)}}(Ae),Qe=H.filter(Ne=>Ne.sent<oe-fe),qe=Qe.filter(se),$e=qe.length===0?0:qe.length/Qe.length;de={pingsSent:ce,pongsReceived:ue,average:Ue,standardDeviation:Me,jitter:Ge,max:Math.max(...Ae),min:Math.min(...Ae),loss:$e}}else de=null;const{temporalNow:ye=Date.now()}=D,me=(ie?oe:ye)-4*fe;return Array.from(be.entries()).forEach(ce=>{const[ue,Ae]=ce;Ae.sent<me&&be.delete(ue)}),de}function Ie({entityId:be,streamName:D,streamType:H}){return`${be}.${D}.${H}`}var Se=function(be,D,H,X){return new(H||(H=Promise))(function(ie,oe){function de(ce){try{me(X.next(ce))}catch(ue){oe(ue)}}function ye(ce){try{me(X.throw(ce))}catch(ue){oe(ue)}}function me(ce){var ue;ce.done?ie(ce.value):(ue=ce.value,ue instanceof H?ue:new H(function(Ae){Ae(ue)})).then(de,ye)}me((X=X.apply(be,D||[])).next())})};class Ce{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 Se(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,me=[...new Set([...ie.keys(),...oe.keys()])].reduce((ce,ue)=>{const Ae=ie.get(ue),Me=oe.get(ue),Ue=de.get(ue),Ge=ye.get(ue);return Object.assign(Object.assign({},ce),{[`local-${ue}-sent`]:Ae,[`local-${ue}-received`]:Me,[`remote-${ue}-sent`]:Ue,[`remote-${ue}-received`]:Ge})},{sessionId:D});g.a.debug("rtc-message-report",Object.assign({deviceId:this.connection.getRemoteDeviceId()},me))})}}function Te(be,D,H){return{header:{stream:be,created:Date.now(),frameId:H||""},payload:D}}function Re(be){return new Set(["disconnected","failed","closed"]).has(be.iceConnectionState)}function Be(be){switch(be.header.stream.streamType){case"twist":{const{twist:D}=be.payload;if(!D)throw Error("twist not in payload of RTC message with type twist");return{header:be.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}=be.payload;if(!D)throw Error("pose not in payload of RTC message with type pose");return{header:be.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}=be.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:be.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}=be.payload;if(!D)throw Error("point not in payload of RTC message with type point");return{header:be.header,payload:{point:Object.assign({x:0,y:0,z:0},D)}}}default:return be}}var Ze=function(be,D,H,X){return new(H||(H=Promise))(function(ie,oe){function de(ce){try{me(X.next(ce))}catch(ue){oe(ue)}}function ye(ce){try{me(X.throw(ce))}catch(ue){oe(ue)}}function me(ce){var ue;ce.done?ie(ce.value):(ue=ce.value,ue instanceof H?ue:new H(function(Ae){Ae(ue)})).then(de,ye)}me((X=X.apply(be,D||[])).next())})};class et{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=ve(this.pingV2Map);oe&&(this.pingInfo=oe,m.aggregate("rtc-ping-average",oe.average),m.aggregate("rtc-ping-loss",oe.loss),m.aggregate("rtc-jitter",oe.jitter))};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,me)=>{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 Ze(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:me}=H;if(ye!=="stable"||me!=="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 ue=D.clone();return X==null||X("Answer Received",ue),ue.setPayload(JSON.stringify(ce)),ue.setReceiverId(D.getSenderId()),ue.setSenderId(D.getReceiverId()),ue}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 Ze(this,void 0,void 0,function*(){if(this.closeCalled)return;this.closeCalled=!0,this.sessionMetrics&&(yield this.sessionMetrics.uploadMetrics()),nt(this.pingUpdateTimeout),nt(this.pingV2UpdateTimeout),nt(this.pingV2MetricsGatherTimeout),nt(this.reassemblyTableCleanupTimeout),nt(this.streamsInfoUpdateTimeout),nt(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 Ce(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 Ze(this,void 0,void 0,function*(){const{peerConnection:D}=this;if(!D)return;const H=yield D.getStats(null),X=[];H.forEach(me=>{X.push(me)});const ie=X.find(me=>me.type==="transport");if(!ie)return;const oe=X.find(me=>(me.type==="candidate-pair"||me.type==="candidatepair")&&me.id===ie.selectedCandidatePairId);if(!oe)return;const de=X.find(me=>me.id===oe.localCandidateId),ye=X.find(me=>me.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",K),this.heartbeatChannel.binaryType="arraybuffer",this.latestTtlStreamChannel=D.createDataChannel("stream.latest-ttl",S),this.latestTtlStreamChannel.binaryType="arraybuffer",this.reliableStreamChannel=D.createDataChannel("stream.reliable",T),this.reliableStreamChannel.binaryType="arraybuffer",this.latestReliableStreamChannel=D.createDataChannel("stream.latest-reliable",k),this.latestReliableStreamChannel.binaryType="arraybuffer",this.latestTryOnceStreamChannel=D.createDataChannel("stream.latest-try-once",J),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 Ze(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,Re(this.peerConnection))return void g.a.debug("Failed to generate offer because the peer connection was inactive.");const me=de.baseConfig.track;oe.onicecandidate=()=>{this.hasIceCandidate=!0},oe.oniceconnectionstatechange=()=>Ze(this,void 0,void 0,function*(){const Ue=oe.iceConnectionState;if(Ue==="connected"||Ue==="completed"){const Ge=yield this.getConnectionStatsInfo(),Qe=Ge?function(qe){const $e=qe.localCandidate.candidateType,Ne=qe.remoteCandidate.candidateType;return $e==="host"&&Ne==="host"?"local":$e==="relay"||Ne==="relay"?"TURN":"STUN"}(Ge):void 0;g.a.info(`ICE connection state changed to ${Ue}`,{sessionId:ye,connectionStatsInfo:Ge,iceMode:Qe}),me==null||me("ICE connection state change",{iceConnectionState:Ue,sessionId:ye,connectionStatsInfo:Ge,iceMode:Qe})}}),yield oe.setLocalDescription(yield oe.createOffer());const ce=new Date().getTime();for(;;){const Ue=new Date().getTime()-ce;if(Ue>this.connectTimeoutMs)return void g.a.debug("Failed to generate offer because ICE gathering timed out.");if(Ue>this.iceGatheringTimeoutMs&&this.hasIceCandidate){g.a.debug("ICE gathering partially completed; proceeding",{iceTransportPolicy:oe.getConfiguration().iceTransportPolicy,waitTime:Ue}),me==null||me("ICE gathering partially completed",{sessionId:ye,iceTransportPolicy:oe.getConfiguration().iceTransportPolicy,waitTime:Ue});break}if(oe.iceGatheringState==="complete"){g.a.debug("ICE gathering complete",{iceTransportPolicy:oe.getConfiguration().iceTransportPolicy,waitTime:Ue}),me==null||me("ICE gathering completed",{sessionId:ye,iceTransportPolicy:oe.getConfiguration().iceTransportPolicy,waitTime:Ue});break}yield Object(u.a)(.1*c.a.second)}const ue=(H=this.peerConnection.getConfiguration().iceServers)!==null&&H!==void 0?H:[];for(const Ue of ue)Ue.credentialType=void 0;const Ae=JSON.stringify(ue),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(Ae),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 Ze(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,Re(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 Ze(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(G.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(G.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=Be(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,me)=>ye.seq<me.seq?-1:1).map(ye=>ye.part).reduce((ye,me)=>ye+me);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}=de;switch(H.header.stream.streamType){case"ping":return this.sendSystemMessage(D,{type:"pong",timestamp:p(H.payload.ping)}),!0;case"pong":{const me=new Date().getTime()-p(H.payload.pong);return this.pingTimeMs=me,m.aggregate("rtc-ping-time",me),!0}case"ping-v2":return this.sendPingV2(),!0;case"pong-v2":{const me=p(H.payload.pongV2),ce=this.pingV2Map.get(me.id);return(ce==null?void 0:ce.sent)!==me.timestamp?(g.a.warn("Pong timestamp doesn't match stored value",{currentEntry:ce,pong:me}),!0):(this.pingV2Map.set(me.id,{sent:me.timestamp,received:new Date().getTime()}),!0)}case"streams-info":{const{sessionMetrics:me}=this,ce=(X=H.payload.streamsInfo)===null||X===void 0?void 0:X.timestamp;return!!ce&&(me==null||me.updateRemoteMessagesCounts(H),(ie=de.onStreamsInfoUpdate)===null||ie===void 0||ie.call(de,ye,ce),!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,Te(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 nt(be){be&&clearInterval(be)}function Rt(be){var D,H;return{userId:(D=be.getUserId())===null||D===void 0?void 0:D.getValue(),deviceId:(H=be.getDeviceId())===null||H===void 0?void 0:H.getValue(),organizationId:be.getOrganizationId(),id:be.getPeerId(),capabilities:[],capabilitySet:{}}}var Pe=function(be,D,H,X){return new(H||(H=Promise))(function(ie,oe){function de(ce){try{me(X.next(ce))}catch(ue){oe(ue)}}function ye(ce){try{me(X.throw(ce))}catch(ue){oe(ue)}}function me(ce){var ue;ce.done?ie(ce.value):(ue=ce.value,ue instanceof H?ue:new H(function(Ae){Ae(ue)})).then(de,ye)}me((X=X.apply(be,D||[])).next())})};class vt{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=[];const{refreshIntervalDelayMs:H}=this;this.refreshInterval=d({func:()=>Pe(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 Pe(this,void 0,void 0,function*(){for(;!this.localPeer;)yield Object(u.a)(.1*c.a.second);return Rt(this.localPeer)})}connect(D,H){var X,ie,oe;return Pe(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:me,receiveSignalStream:ce,iceServers:ue}=this;if(!me||!ce||!ue)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 Ae=function(Ne,Fe,Ye){const{rtcIceTransportPolicies:Ke,rtcIceServerProtocol:Xe,useAllServers:Je}=Fe||{},ot=Ne.map(at=>Object.assign(Object.assign({},at),{urls:at.urls.filter(dt=>{const wt=(Ke===void 0||Ke.some(St=>V(dt,St)))&&(Xe===void 0||Q(dt,Xe));return wt||g.a.debug(`Ignoring ICE server: ${dt}`,{organizationId:Ye}),wt})})).filter(({urls:at})=>at.filter(dt=>dt).length>0);return Je?ot:[U(ot,"stun"),U(ot,"turn")].filter(at=>at!==void 0).map(at=>p(at))}(ue,H);g.a.debug("Received ICE servers:",ue),g.a.debug("Using ICE servers:",Ae);const Me=new et(yield this.createRTCPeerConnection(Ae),{baseConfig:{isOffer:!0,isLan:!1,receive:(Ne,Fe)=>this.config.receive(Ne,Fe),onStreamsInfoUpdate:this.config.onStreamsInfoUpdate?(Ne,Fe)=>{var Ye,Ke;return(Ke=(Ye=this.config).onStreamsInfoUpdate)===null||Ke===void 0?void 0:Ke.call(Ye,Ne,Fe)}:void 0,track:this.config.lanOnlyMode?void 0:this.config.track,localUserId:(X=me.getUserId())===null||X===void 0?void 0:X.getValue(),localPeerId:me.getPeerId(),remotePeerId:D,sessionType:this.config.sessionType},remoteConfig:{}},Ne=>this.onCustomDataChannel(D,Ne)),Ue=yield Me.getOffer();if(!Ue)return g.a.error("Failed to generate offer."),void this.isOutgoingConnection.delete(D);g.a.debug("Sending offer."),de==null||de("Sending offer",Ue);const Ge=new ee.SendSignalRequest;Ge.setSignal(Ue);const Qe=yield(()=>Pe(this,void 0,void 0,function*(){try{return yield ye.sendSignal(Ge,yield this.getMetadata({}))}catch(Ne){g.a.warn("Error when sending signal",{error:Ne})}}))();if(!this.isOutgoingConnection.get(D))return void g.a.debug("No offer set after receiving offer signal response.");g.a.debug("Offer sent.");const qe=(ie=Qe==null?void 0:Qe.getSessionId())===null||ie===void 0?void 0:ie.getValue(),$e=(oe=Qe==null?void 0:Qe.getSessionCreatedTimestamp())===null||oe===void 0?void 0:oe.getValue();return qe&&$e?(Me.setSessionId(qe),Me.setSessionCreatedTimestamp($e),this.isOutgoingConnection.delete(D),this.connections.push(Me),this.isConnectionInitiator.set(Me,!0),this.setupHandlers(Me),qe):(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 Pe(this,void 0,void 0,function*(){const ie=new P(D),oe=new et(yield this.createRTCPeerConnection([]),{baseConfig:{isOffer:!0,isLan:!0,receive:(ce,ue)=>this.config.receive(ce,ue),onStreamsInfoUpdate:this.config.onStreamsInfoUpdate?(ce,ue)=>{var Ae,Me;return(Me=(Ae=this.config).onStreamsInfoUpdate)===null||Me===void 0?void 0:Me.call(Ae,ce,ue)}: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)}),me=new RTCSessionDescription(JSON.parse(ye.answer));return yield oe.handleLanAnswer(me),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 me=de.peerConnection.createDataChannel("custom."+H,X);return ie&&(me.binaryType="arraybuffer"),oe(D,me),()=>{}}const ye=(me,ce)=>{D===me&&ce.label==="custom."+H&&oe(D,ce)};return this.peerDataChannelListeners.push(ye),()=>{this.peerDataChannelListeners=this.peerDataChannelListeners.filter(me=>me!==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 Pe(this,void 0,void 0,function*(){const H=this.getActiveConnection(D);if(H)return yield H.getConnectionStatsInfo()})}disconnect(D){return Pe(this,void 0,void 0,function*(){const H=this.getActiveConnection(D);H&&(yield H.close())})}getPeers(){return Pe(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(()=>Pe(this,void 0,void 0,function*(){try{return yield D.getPeers(new ee.GetPeersRequest,yield this.getMetadata({}))}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=>Rt(oe))})}getSessions(){return Pe(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(()=>Pe(this,void 0,void 0,function*(){try{return yield D.getPeers(new ee.GetPeersRequest,yield this.getMetadata({}))}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 Pe(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(()=>Pe(this,void 0,void 0,function*(){try{const ie=new ee.DeletePeerRequest;ie.setPeerId(H.getPeerId()),yield X.deletePeer(ie,yield this.getMetadata({}))}catch(ie){return void g.a.warn("Error deleting local peer",{error:ie})}}))()})}createPeer(){return Pe(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(()=>Pe(this,void 0,void 0,function*(){try{return yield D.createPeer(new ee.CreatePeerRequest,yield this.getMetadata({}))}catch(ie){throw new Error(`Was not able to create peer: ${JSON.stringify(ie)}`)}}))(),X=H==null?void 0:H.getPeer();if(!X)throw new Error("Response did not provide peer.");return this.localPeer=X})}createReceiveSignalStream(){return Pe(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(()=>Pe(this,void 0,void 0,function*(){try{return D.receiveSignalStream(oe,yield this.getMetadata({hasDeadline:!1}))}catch(ye){throw new Error(`Unable to create receive signal stream: ${JSON.stringify(ye)}`)}}))();if(!de)throw new Error("Response did not provide stream.");return de.on("data",ye=>Pe(this,void 0,void 0,function*(){var me,ce,ue,Ae;const Me=ye.getSignal(),Ue=(me=Me==null?void 0:Me.getSessionId())===null||me===void 0?void 0:me.getValue(),Ge=Me==null?void 0:Me.getSenderId(),Qe=Me==null?void 0:Me.getReceiverId(),qe=(ce=Me==null?void 0:Me.getSessionCreatedTimestamp())===null||ce===void 0?void 0:ce.getValue();if(!(Me&&Ue&&Ge&&Qe&&qe))return void g.a.warn("Received signal with missing information.");const $e=this.getActiveConnection(Ge);if($e)if($e.getSessionId()!==Ue){if(g.a.debug("Received signal: different session for a peer we're already connected to."),($e.getSessionCreatedTimestamp()||0)>qe)return;const Ne=new et(yield this.createRTCPeerConnection(X),{baseConfig:{isOffer:!1,isLan:!1,receive:(Fe,Ye)=>this.config.receive(Fe,Ye),onStreamsInfoUpdate:this.config.onStreamsInfoUpdate?(Fe,Ye)=>{var Ke,Xe;return(Xe=(Ke=this.config).onStreamsInfoUpdate)===null||Xe===void 0?void 0:Xe.call(Ke,Fe,Ye)}:void 0,track:this.config.lanOnlyMode?void 0:this.config.track,localPeerId:H.getPeerId(),localUserId:(Ae=H.getUserId())===null||Ae===void 0?void 0:Ae.getValue(),remotePeerId:Ge},remoteConfig:{sessionId:Ue,sessionCreatedTimestamp:qe}},Fe=>this.onCustomDataChannel(Ge,Fe));yield Ne.handleSignal(Me),this.connections.push(Ne)}else g.a.debug("Received signal: for an existing connection."),yield $e.handleSignal(Me);else{g.a.debug("Received signal: new connection.");const Ne=new et(yield this.createRTCPeerConnection(X),{baseConfig:{isOffer:!1,isLan:!1,receive:(Fe,Ye)=>this.config.receive(Fe,Ye),onStreamsInfoUpdate:this.config.onStreamsInfoUpdate?(Fe,Ye)=>{var Ke,Xe;return(Xe=(Ke=this.config).onStreamsInfoUpdate)===null||Xe===void 0?void 0:Xe.call(Ke,Fe,Ye)}:void 0,track:this.config.lanOnlyMode?void 0:this.config.track,localPeerId:H.getPeerId(),localUserId:(ue=H.getUserId())===null||ue===void 0?void 0:ue.getValue(),remotePeerId:Ge},remoteConfig:{sessionId:Ue,sessionCreatedTimestamp:qe}},Fe=>this.onCustomDataChannel(Ge,Fe));yield Ne.handleSignal(Me),this.connections.push(Ne)}})),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 Pe(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.");return new X({iceServers:D})})}closeConnections(D){return Pe(this,void 0,void 0,function*(){const H=yield O(D.map(X=>Pe(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 Pe(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)return this.localPeer||(yield this.createPeer()),this.iceServers||(yield this.updateIceServers()),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 H.refreshPeer(oe,yield this.getMetadata({}))}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(me=>me.id===ye.getRemotePeerId()))===null||D===void 0?void 0:D.deviceId)})}reset(){return Pe(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 Pe(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 this.config.signalingClient.getIceServers(new ee.GetIceServersRequest,yield this.getMetadata({}))).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=()=>Pe(this,void 0,void 0,function*(){const ie=H.connectionState;if(X)switch(ie){case"connected":m.aggregate("rtc-connect-time",new Date().getTime()-X);break;case"failed":m.increment("rtc-connect-failed")}})}getMetadata(D){return Pe(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;return{authorization:yield H(),deadline:oe}})}}var ft=n(10),ut=n(11),Ot=function(be,D,H,X){return new(H||(H=Promise))(function(ie,oe){function de(ce){try{me(X.next(ce))}catch(ue){oe(ue)}}function ye(ce){try{me(X.throw(ce))}catch(ue){oe(ue)}}function me(ce){var ue;ce.done?ie(ce.value):(ue=ce.value,ue instanceof H?ue:new H(function(Ae){Ae(ue)})).then(de,ye)}me((X=X.apply(be,D||[])).next())})};class It{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 Ot(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),me=this.receivedMessagesCounts.get(de);return Object.assign(Object.assign({},oe),{[`${de}-sent`]:ye,[`${de}-received`]:me})},{sessionId:D});g.a.debug("rtc-message-report",ie)})}}function ct(be,D){return Ie(be)===Ie(D)}var tt=function(be,D,H,X){return new(H||(H=Promise))(function(ie,oe){function de(ce){try{me(X.next(ce))}catch(ue){oe(ue)}}function ye(ce){try{me(X.throw(ce))}catch(ue){oe(ue)}}function me(ce){var ue;ce.done?ie(ce.value):(ue=ce.value,ue instanceof H?ue:new H(function(Ae){Ae(ue)})).then(de,ye)}me((X=X.apply(be,D||[])).next())})};class Ct{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 It(this.getSessionId(),this)}connect(){return tt(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(()=>tt(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(()=>tt(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=>tt(this,void 0,void 0,function*(){ie.candidate?this.receivedIceCandidate=!0:yield this.sendOffer()}),D.onicegatheringstatechange=()=>tt(this,void 0,void 0,function*(){D.iceGatheringState==="complete"&&(yield this.sendOffer())}),D.onnegotiationneeded=()=>{g.a.debug("Negotiation needed",{sessionId:X})})})}handleSignal(D){return tt(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 Re(D)||de(H)||de(X)||de(ie)}close(){return tt(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",S),this.reliableStreamChannel=D.createDataChannel("stream.reliable",T),this.latestReliableStreamChannel=D.createDataChannel("stream.latest-reliable",k),this.latestTryOnceStreamChannel=D.createDataChannel("stream.latest-try-once",J),this.setupChannel(this.latestTtlStreamChannel),this.setupChannel(this.reliableStreamChannel),this.setupChannel(this.latestReliableStreamChannel),this.setupChannel(this.latestTryOnceStreamChannel)}sendOffer(){return tt(this,void 0,void 0,function*(){if(this.sentOffer||(this.sentOffer=!0,Re(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(G.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(G.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=Be(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,m.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,Te(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(ue=>ue.receive&&ct(ue.stream,D.header.stream)),me=(X=oe.capabilitySet.streaming)===null||X===void 0?void 0:X.streams,ce=me&&me.some(ue=>ue.send&&ct(ue.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 ke=function(be,D,H,X){return new(H||(H=Promise))(function(ie,oe){function de(ce){try{me(X.next(ce))}catch(ue){oe(ue)}}function ye(ce){try{me(X.throw(ce))}catch(ue){oe(ue)}}function me(ce){var ue;ce.done?ie(ce.value):(ue=ce.value,ue instanceof H?ue:new H(function(Ae){Ae(ue)})).then(de,ye)}me((X=X.apply(be,D||[])).next())})};class Mt{constructor(D){this.config=D,this.connections=[],this.connectingSessions=new Map,this.updateInterval=d({func:()=>ke(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 ke(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(ft.a)(ie,ut.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 ke(this,void 0,void 0,function*(){const H=this.getActiveConnection(D);H&&(yield this.closeConnection(H))})}getLocalPeer(){return ke(this,void 0,void 0,function*(){return yield this.localPeer})}getPeers(){return ke(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 ke(this,void 0,void 0,function*(){yield this.updateInterval.stop();const D=this.connections;this.connections=[],yield this.closeConnections(D)})}closeConnection(D){return ke(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(ft.a)(H,ut.a,X=>X.statusCode===404)}})}getSessions(){return ke(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 ke(this,void 0,void 0,function*(){return yield this.config.signalingClient.createPeer(yield this.config.getToken(),{capabilitySet:this.config.capabilitySet||{}})})}createRTCPeerConnection(D={}){return ke(this,void 0,void 0,function*(){return new(this.config.alternateRTCPeerConnection||RTCPeerConnection)(Object.assign({iceServers:yield this.config.signalingClient.getIceServers(yield this.config.getToken())},D))})}closeConnections(D){return ke(this,void 0,void 0,function*(){const H=yield O(D.map(X=>ke(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 ke(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 ke(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(ft.a)(H,ut.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 ke(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})=>ke(this,void 0,void 0,function*(){return yield this.maintainConnection(X,ie)})))})}syncConnectionsAndSessions(D){return ke(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=>ke(this,void 0,void 0,function*(){yield this.closeConnection(oe)})))})}maintainConnection(D,H){return ke(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(ft.a)(oe,ut.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 ke(this,void 0,void 0,function*(){const H=yield this.getLocalPeer(),X=D.offer.peer.id===H.id,ie=yield this.createRTCPeerConnection(),oe=new Ct(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=()=>ke(this,void 0,void 0,function*(){const ie=this.connectingSessions.get(X);if(ie===void 0)return;const oe=H.connectionState;switch(Re(H)&&this.connectingSessions.delete(X),oe){case"connected":{this.connectingSessions.delete(X);const de=new Date().getTime()-ie;m.aggregate("rtc-connect-time",de);break}case"failed":m.increment("rtc-connect-failed"),yield this.closeConnection(D)}})}consumeSignals(D){return ke(this,void 0,void 0,function*(){let H=[];try{H=yield this.config.signalingClient.takeSignals(yield this.config.getToken(),D.getSessionId())}catch(X){Object(ft.a)(X,ut.a,ie=>ie.statusCode===404)}for(const X of H)yield D.handleSignal(X)})}sendSignal(D,H){return ke(this,void 0,void 0,function*(){try{yield this.config.signalingClient.addSignals(yield this.config.getToken(),D,{signals:[H]})}catch(X){Object(ft.a)(X,ut.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(10),s=n(11),l=function(c,u,f,E){return new(f||(f=Promise))(function(w,h){function g(x){try{R(E.next(x))}catch(F){h(F)}}function b(x){try{R(E.throw(x))}catch(F){h(F)}}function R(x){var F;x.done?w(x.value):(F=x.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}={}){Oe(this,"entries",new Map);Oe(this,"metadata",new Map);Oe(this,"capacity");Oe(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(){Oe(this,"queryStoreCache",new StoreCache({capacity:1e4,timeout:20*duration.second}));Oe(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;Oe(Authentication,"token"),Oe(Authentication,"refreshToken"),Oe(Authentication,"currentUser"),Oe(Authentication,"currentOrganization"),Oe(Authentication,"isShareToken",!1),Oe(Authentication,"defaultDeviceId"),Oe(Authentication,"waitingForAuth",[]);function delay(e){return new Promise(t=>setTimeout(t,e))}class DataChannel{constructor(t){Oe(this,"ready",!1);Oe(this,"listeners",[]);Oe(this,"openListeners",[]);Oe(this,"closeListeners",[]);Oe(this,"errorListeners",[]);Oe(this,"binaryListeners",[]);Oe(this,"error");Oe(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){Oe(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){Oe(this,"currentListeners",[]);Oe(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){Oe(this,"channel");Oe(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);Oe(this,"RESPONSE_SUCCESS_BYTE",0);Oe(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")}}const urlParams$1=new URLSearchParams(window.location.search),rtcClientVersion=urlParams$1.get("rtc_client"),SessionType={Teleop:1,Observe:3};class Device{constructor(t,n,r){Oe(this,"rtcClient");Oe(this,"remoteDevicePeerId");Oe(this,"realtimeListeners",[]);Oe(this,"handleMessage",(t,n)=>{this.realtimeListeners.forEach(r=>r(t,n))});this.id=t,this.name=n,this.organizationId=r}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 t=await fetch(`${FORMANT_API_URL}/v1/admin/devices/${this.id}`,{method:"GET",headers:{"Content-Type":"application/json",Authorization:"Bearer "+Authentication.token}});const n=await t.json();if(!n.state.reportedConfiguration)throw new Error("Device has no configuration, has it ever been turned on?");const r=n.state.reportedConfiguration.version;return t=await fetch(`${FORMANT_API_URL}/v1/admin/devices/${this.id}/configurations/${r}`,{method:"GET",headers:{"Content-Type":"application/json",Authorization:"Bearer "+Authentication.token}}),(await t.json()).document}async getFileUrl(t){return(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()).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(t){if(this.rtcClient)throw new Error(`Already created realtime connection to device ${this.id}`);{let n;if(rtcClientVersion==="1"?n=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}):n=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:t}),n.isReady)for(;!n.isReady();)await delay(100);const i=(await n.getPeers()).find(s=>s.deviceId===this.id);if(!i)throw new Error("Cannot find peer, is the robot offline?");for(this.remoteDevicePeerId=i.id,await n.connect(this.remoteDevicePeerId);n.getConnectionStatus(this.remoteDevicePeerId)!=="connected";)await delay(100);this.rtcClient=n}}async sendRealtimeMessage(t,n={channelLabel:"stream.reliable"}){const r=defined(this.rtcClient,"Realtime connection has not been started"),i=await this.getRemotePeer();r.send(defined(i).id,t,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 getRealtimeAudioStreams(){var r,i,s;const t=await this.getConfiguration(),n=[];for(const l of((r=t.teleop)==null?void 0:r.hardwareStreams)??[])l.rtcStreamType==="audio-chunk"&&n.push({name:l.name});for(const l of((i=t.teleop)==null?void 0:i.rosStreams)??[])l.topicType=="audio_common_msgs/AudioData"&&n.push({name:l.topicName});for(const l of((s=t.teleop)==null?void 0:s.customStreams)??[])l.rtcStreamType==="audio-chunk"&&n.push({name:l.name});return n}async getRealtimeVideoStreams(){var r,i,s;const t=await this.getConfiguration(),n=[];for(const l of((r=t.teleop)==null?void 0:r.hardwareStreams)??[])l.rtcStreamType==="h264-video-frame"&&n.push({name:l.name});for(const l of((i=t.teleop)==null?void 0:i.rosStreams)??[])l.topicType=="formant/H264VideoFrame"&&n.push({name:l.topicName});for(const l of((s=t.teleop)==null?void 0:s.customStreams)??[])l.rtcStreamType==="h264-video-frame"&&n.push({name:l.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 changeStreamAudioType(t,n){const r=defined(this.rtcClient,"Realtime connection has not been started"),i=await this.getRemotePeer();r.controlRemoteStream(defined(i).id,{streamName:t,setAudioFormat:n})}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(){const n=(await defined(this.rtcClient,"Realtime connection has not been started").getPeers()).find(r=>r.deviceId===this.id);return defined(n,"Could not find remote peer for device "+this.id)}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 isInRealtimeSession(){let t=await Fleet.getPeers(),n=await Fleet.getRealtimeSessions(),r=t.find(i=>i.deviceId===this.id);return r?n[r.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(r=>({name:r.name,id:r.id,command:r.command,description:r.description,parameterEnabled:r.parameterEnabled,parameterValue:r.parameterValue,parameterMeta:r.parameterMeta,enabled:r.enabled}))}async sendCommand(t,n,r,i){var u;const l=(await this.getAvailableCommands()).find(f=>f.name===t);if(!l)throw new Error(`Could not find command with name "${t}"`);let o="";n===void 0?l.parameterEnabled&&l.parameterValue&&(o=l.parameterValue):o=n;let c={value:o,scrubberTime:(r||new Date).toISOString(),meta:{...l.parameterMeta,...i}};await fetch(`${FORMANT_API_URL}/v1/admin/commands`,{method:"POST",body:JSON.stringify({commandTemplateId:l.id,organizationId:this.organizationId,deviceId:this.id,command:l.command,parameter:c,userId:(u=Authentication.currentUser)==null?void 0:u.id}),headers:{"Content-Type":"application/json",Authorization:"Bearer "+Authentication.token}})}async createCustomDataChannel(t,n){if(rtcClientVersion==="1")throw new Error("createCustomDataChannel is not supported in rtcClientVersion 1");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)}async createCaptureStream(t){const r=await(await fetch(`${FORMANT_API_URL}/v1/admin/capture-sessions`,{method:"POST",body:JSON.stringify({deviceId:this.id,streamName:t,tags:{}}),headers:{"Content-Type":"application/json",Authorization:"Bearer "+Authentication.token}})).json();return new CaptureStream(r)}async getTelemetry(t,n,r,i){return await Fleet.getTelemetry(this.id,t,n,r,i)}async getTelemetryStreams(){var o,c;const t=await this.getConfiguration(),n=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}}),r=[],i=[];return(c=(o=t.telemetry)==null?void 0:o.streams)==null||c.forEach(u=>{u.disabled!==!0&&r.push(u.name),u.onDemand===!0&&i.push(u.name)}),console.log(i),(await n.json()).items.filter(u=>!r.includes(u)).map(u=>({name:u,onDemand:i.includes(u)}))}async createInterventionRequest(t,n,r,i){return await(await fetch(`${FORMANT_API_URL}/v1/admin/intervention-requests`,{method:"POST",body:JSON.stringify({message:t,interventionType:n,time:new Date().toISOString(),deviceId:this.id,tags:i,data:r}),headers:{"Content-Type":"application/json",Authorization:"Bearer "+Authentication.token}})).json()}async addInterventionResponse(t,n,r){return await(await fetch(`${FORMANT_API_URL}/v1/admin/intervention-responses`,{method:"POST",body:JSON.stringify({interventionId:t,interventionType:n,data:r}),headers:{"Content-Type":"application/json",Authorization:"Bearer "+Authentication.token}})).json()}async getAnnotationCount(t,n){return await Fleet.getAnnotationCount({...t,deviceIds:[this.id]},n)}async getAnnotationCountByIntervals(t,n,r){return await Fleet.getAnnotationCountByIntervals({...t,deviceIds:[this.id]},n,r)}async eventsCounter(t,n,r,i,s){return await Fleet.eventsCounter(t,n,r,i,{...s,deviceIds:[this.id]})}async createShareLink(t,n){return t.scope.deviceIds=[this.id],await Fleet.createShareLink(t,n)}}class PeerDevice{constructor(t){Oe(this,"rtcClient");Oe(this,"remoteDevicePeerId");Oe(this,"realtimeListeners",[]);Oe(this,"id");Oe(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});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 Ve=class{static async setDefaultDevice(t){Ve.defaultDeviceId=t}static async getCurrentDevice(){if(!Authentication.token)throw new Error("Not authenticated");if(!Ve.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===Ve.defaultDeviceId).name,s=new Device(Ve.defaultDeviceId,i,defined(Authentication.currentOrganization));return Ve.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 Ve.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 Ve.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 Ve.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 Ve.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=Ve;Oe(Fleet,"defaultDeviceId"),Oe(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},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}var 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=`
@@ -148,5 +148,5 @@ export declare class Device implements IRealtimeDevice {
148
148
  date: string;
149
149
  events: import("./main").IEvent[];
150
150
  }[]>;
151
- createShareLink(params: IShare): Promise<any>;
151
+ createShareLink(share: IShare, view: string): Promise<string>;
152
152
  }
@@ -183,6 +183,7 @@ export declare class Fleet {
183
183
  /**
184
184
  * @param scope is required
185
185
  * @param time is required
186
+ * @param view View name
186
187
  * @returns
187
188
  * Share link
188
189
  * @example
@@ -199,5 +200,5 @@ export declare class Fleet {
199
200
  * userName: "User",
200
201
  * });
201
202
  */
202
- static createShareLink(share: IShare): Promise<string>;
203
+ static createShareLink(share: IShare, view: string): Promise<string>;
203
204
  }
package/package.json CHANGED
@@ -18,7 +18,7 @@
18
18
  "require": "./dist/data-sdk.umd.js"
19
19
  }
20
20
  },
21
- "version": "0.0.138",
21
+ "version": "0.0.139",
22
22
  "scripts": {
23
23
  "dev": "vite --port 9146",
24
24
  "build": "tsc && vite build",