@formant/data-sdk 0.0.53 → 0.0.57
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/data-sdk.es.js
CHANGED
|
@@ -18228,6 +18228,14 @@ let FORMANT_API_URL = "https://api.formant.io";
|
|
|
18228
18228
|
if (typeof window !== "undefined") {
|
|
18229
18229
|
FORMANT_API_URL = window.FORMANT_API_URL || FORMANT_API_URL;
|
|
18230
18230
|
}
|
|
18231
|
+
let urlParams$1 = new URLSearchParams("");
|
|
18232
|
+
if (typeof window !== "undefined") {
|
|
18233
|
+
urlParams$1 = new URLSearchParams(window.location.search);
|
|
18234
|
+
}
|
|
18235
|
+
const moduleName$1 = urlParams$1.get("formant_dev");
|
|
18236
|
+
if (moduleName$1) {
|
|
18237
|
+
FORMANT_API_URL = "https://api-dev.formant.io";
|
|
18238
|
+
}
|
|
18231
18239
|
function delay(ms) {
|
|
18232
18240
|
return new Promise((resolve) => setTimeout(resolve, ms));
|
|
18233
18241
|
}
|
|
@@ -18548,15 +18556,26 @@ class CaptureStream {
|
|
|
18548
18556
|
}
|
|
18549
18557
|
class Manipulator {
|
|
18550
18558
|
constructor(device, config) {
|
|
18559
|
+
__publicField(this, "currentListeners", []);
|
|
18560
|
+
__publicField(this, "onRealtimeMessage", (_peerId, message) => {
|
|
18561
|
+
if (message.payload.jointState) {
|
|
18562
|
+
this.currentListeners.forEach((listener) => listener(message.payload.jointState));
|
|
18563
|
+
}
|
|
18564
|
+
});
|
|
18551
18565
|
this.device = device;
|
|
18552
18566
|
this.config = config;
|
|
18553
18567
|
}
|
|
18554
18568
|
async synchronize() {
|
|
18555
|
-
this.device.addRealtimeListener(
|
|
18556
|
-
console.log(message);
|
|
18557
|
-
});
|
|
18569
|
+
this.device.addRealtimeListener(this.onRealtimeMessage);
|
|
18558
18570
|
this.device.startListeningToRealtimeDataStream(this.config.currentJointStateStream);
|
|
18559
18571
|
}
|
|
18572
|
+
async desynchronize() {
|
|
18573
|
+
this.device.removeRealtimeListener(this.onRealtimeMessage);
|
|
18574
|
+
this.device.stopListeningToRealtimeDataStream(this.config.currentJointStateStream);
|
|
18575
|
+
}
|
|
18576
|
+
async addCurrentJointStateListener(listener) {
|
|
18577
|
+
this.currentListeners.push(listener);
|
|
18578
|
+
}
|
|
18560
18579
|
}
|
|
18561
18580
|
class RequestDataChannel {
|
|
18562
18581
|
constructor(device, channel_name, timeout) {
|
|
@@ -18828,10 +18847,10 @@ class Device {
|
|
|
18828
18847
|
async getRealtimeManipulators() {
|
|
18829
18848
|
var _a;
|
|
18830
18849
|
const document2 = await this.getConfiguration();
|
|
18831
|
-
const
|
|
18850
|
+
const manipulators = [];
|
|
18832
18851
|
for (const _ of (_a = document2.teleop.rosStreams) != null ? _a : []) {
|
|
18833
18852
|
if (_.topicType == "sensor_msgs/JointState") {
|
|
18834
|
-
|
|
18853
|
+
manipulators.push(new Manipulator(this, {
|
|
18835
18854
|
currentJointStateStream: { name: _.topicName },
|
|
18836
18855
|
plannedJointStateStream: _.plannedTopic ? { name: _.plannedTopic } : void 0,
|
|
18837
18856
|
planValidStream: _.planValidTopic ? { name: _.planValidTopic } : void 0,
|
|
@@ -18842,7 +18861,7 @@ class Device {
|
|
|
18842
18861
|
}));
|
|
18843
18862
|
}
|
|
18844
18863
|
}
|
|
18845
|
-
return
|
|
18864
|
+
return manipulators;
|
|
18846
18865
|
}
|
|
18847
18866
|
async startListeningToRealtimeVideo(stream) {
|
|
18848
18867
|
const client = defined(this.rtcClient, "Realtime connection has not been started");
|
|
@@ -19169,10 +19188,72 @@ const _Fleet = class {
|
|
|
19169
19188
|
const telemetry = await data.json();
|
|
19170
19189
|
return telemetry.items;
|
|
19171
19190
|
}
|
|
19191
|
+
static async getFileUrl(uuid) {
|
|
19192
|
+
const data = await fetch(`${FORMANT_API_URL}/v1/admin/files/query`, {
|
|
19193
|
+
method: "POST",
|
|
19194
|
+
body: JSON.stringify({
|
|
19195
|
+
fileIds: [uuid]
|
|
19196
|
+
}),
|
|
19197
|
+
headers: {
|
|
19198
|
+
"Content-Type": "application/json",
|
|
19199
|
+
Authorization: "Bearer " + Authentication.token
|
|
19200
|
+
}
|
|
19201
|
+
});
|
|
19202
|
+
const result = await data.json();
|
|
19203
|
+
if (result.fileUrls.length === 0) {
|
|
19204
|
+
throw new Error("File not found");
|
|
19205
|
+
}
|
|
19206
|
+
return result.fileUrls[0];
|
|
19207
|
+
}
|
|
19172
19208
|
};
|
|
19173
19209
|
let Fleet = _Fleet;
|
|
19174
19210
|
__publicField(Fleet, "defaultDeviceId");
|
|
19175
19211
|
__publicField(Fleet, "knownContext", []);
|
|
19212
|
+
class KeyValue {
|
|
19213
|
+
static async set(key, value) {
|
|
19214
|
+
try {
|
|
19215
|
+
const result = await fetch(FORMANT_API_URL + "/v1/admin/key-value", {
|
|
19216
|
+
method: "POST",
|
|
19217
|
+
body: JSON.stringify({
|
|
19218
|
+
organizationId: defined(Authentication.currentUser).organizationId,
|
|
19219
|
+
key,
|
|
19220
|
+
value
|
|
19221
|
+
}),
|
|
19222
|
+
headers: {
|
|
19223
|
+
"Content-Type": "application/json",
|
|
19224
|
+
Authorization: "Bearer " + Authentication.token
|
|
19225
|
+
}
|
|
19226
|
+
});
|
|
19227
|
+
const keyValue = await result.json();
|
|
19228
|
+
if (result.status !== 200) {
|
|
19229
|
+
throw new Error(keyValue.message);
|
|
19230
|
+
}
|
|
19231
|
+
} catch (e) {
|
|
19232
|
+
throw e;
|
|
19233
|
+
}
|
|
19234
|
+
}
|
|
19235
|
+
static async get(key) {
|
|
19236
|
+
try {
|
|
19237
|
+
const result = await fetch(FORMANT_API_URL + `/v1/admin/key-value/${key}`, {
|
|
19238
|
+
method: "GET",
|
|
19239
|
+
body: JSON.stringify({
|
|
19240
|
+
organizationId: defined(Authentication.currentUser).organizationId
|
|
19241
|
+
}),
|
|
19242
|
+
headers: {
|
|
19243
|
+
"Content-Type": "application/json",
|
|
19244
|
+
Authorization: "Bearer " + Authentication.token
|
|
19245
|
+
}
|
|
19246
|
+
});
|
|
19247
|
+
const keyValue = await result.json();
|
|
19248
|
+
if (result.status !== 200) {
|
|
19249
|
+
throw new Error(keyValue.message);
|
|
19250
|
+
}
|
|
19251
|
+
return keyValue.value;
|
|
19252
|
+
} catch (e) {
|
|
19253
|
+
throw e;
|
|
19254
|
+
}
|
|
19255
|
+
}
|
|
19256
|
+
}
|
|
19176
19257
|
let urlParams = new URLSearchParams("");
|
|
19177
19258
|
if (typeof window !== "undefined") {
|
|
19178
19259
|
urlParams = new URLSearchParams(window.location.search);
|
|
@@ -19189,4 +19270,4 @@ const moduleName = urlParams.get("module");
|
|
|
19189
19270
|
if (moduleName) {
|
|
19190
19271
|
Authentication.listenForRefresh();
|
|
19191
19272
|
}
|
|
19192
|
-
export { App, Authentication, BinaryRequestDataChannel, CaptureStream, DataChannel, Device, Fleet, Manipulator, TextRequestDataChannel };
|
|
19273
|
+
export { App, Authentication, BinaryRequestDataChannel, CaptureStream, DataChannel, Device, Fleet, KeyValue, Manipulator, TextRequestDataChannel };
|
package/dist/data-sdk.umd.js
CHANGED
|
@@ -41,4 +41,4 @@ In order to be iterable, non-array objects must have a [Symbol.iterator]() metho
|
|
|
41
41
|
`))},s.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,r){function n(g){return(n=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(s){return typeof s}:function(s){return s&&typeof Symbol=="function"&&s.constructor===Symbol&&s!==Symbol.prototype?"symbol":typeof s})(g)}function i(g,s){for(var o=0;o<s.length;o++){var l=s[o];l.enumerable=l.enumerable||!1,l.configurable=!0,"value"in l&&(l.writable=!0),Object.defineProperty(g,l.key,l)}}e.exports=function(){function g(l){if(function(u,m){if(!(u instanceof m))throw new TypeError("Cannot call a class as a function")}(this,g),!l)throw new Error("Logger is required for profiling.");this.logger=l,this.start=Date.now()}var s,o;return s=g,(o=[{key:"done",value:function(){for(var l=arguments.length,u=new Array(l),m=0;m<l;m++)u[m]=arguments[m];typeof u[u.length-1]=="function"&&(console.warn("Callback function no longer supported as of winston@3.0.0"),u.pop());var R=n(u[u.length-1])==="object"?u.pop():{};return R.level=R.level||"info",R.durationMs=Date.now()-this.start,this.logger.write(R)}}])&&i(s.prototype,o),g}()},function(e,t,r){(function(n){const i=r(208),{MESSAGE:g}=r(3),s=r(31);function o(l,u){return u instanceof n?u.toString("base64"):typeof u=="bigint"?u.toString():u}e.exports=i((l,u={})=>(l[g]=(u.stable?s.stableStringify:s)(l,u.replacer||o,u.space),l))}).call(this,r(4).Buffer)},function(e,t,r){class n extends Error{constructor(g){super(`Format functions must be synchronous taking a two arguments: (info, opts)
|
|
42
42
|
Found: ${g.toString().split(`
|
|
43
43
|
`)[0]}
|
|
44
|
-
`),Error.captureStackTrace(this,n)}}e.exports=i=>{if(i.length>2)throw new n(i);function g(o={}){this.options=o}function s(o){return new g(o)}return g.prototype.transform=i,s.Format=g,s}},function(e,t,r){function n(s,o){if(!(s instanceof o))throw new TypeError("Cannot call a class as a function")}function i(s,o){for(var l=0;l<o.length;l++){var u=o[l];u.enumerable=u.enumerable||!1,u.configurable=!0,"value"in u&&(u.writable=!0),Object.defineProperty(s,u.key,u)}}var g=r(85);e.exports=function(){function s(){var u=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};n(this,s),this.loggers=new Map,this.options=u}var o,l;return o=s,(l=[{key:"add",value:function(u,m){var R=this;if(!this.loggers.has(u)){var y=(m=Object.assign({},m||this.options)).transports||this.options.transports;m.transports=y?y.slice():[];var S=g(m);S.on("close",function(){return R._delete(u)}),this.loggers.set(u,S)}return this.loggers.get(u)}},{key:"get",value:function(u,m){return this.add(u,m)}},{key:"has",value:function(u){return!!this.loggers.has(u)}},{key:"close",value:function(u){var m=this;if(u)return this._removeLogger(u);this.loggers.forEach(function(R,y){return m._removeLogger(y)})}},{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,l),s}()},function(e,t,r){(function(n){const i=r(49),g=/^([A-Za-z0-9+/]{4})*([A-Za-z0-9+/]{4}|[A-Za-z0-9+/]{3}=|[A-Za-z0-9+/]{2}==)$/;e.exports=function(s,o,l){let u,m,R=!1,y=!1;function S(E,P){let F=`"${o}" ${P}`;throw E&&(F=`${F}, but is set to "${E}"`),m&&(F=`${F}. An example of a valid value would be: ${m}`),new i(F)}function c(E){return function(){let P=s[o];if(P===void 0)if(u===void 0&&y)S(void 0,"is a required variable, but it was not set");else{if(u===void 0)return;P=u}y&&P.trim().length===0&&S(void 0,"is a required variable, but its value was empty"),R&&(P.match(g)||S(P,"should be a valid base64 string if using convertFromBase64"),P=n.from(P,"base64").toString());const F=[P].concat(Array.prototype.slice.call(arguments));try{return E.apply(E,F)}catch(M){S(P,M.message)}}}const w={asArray:c(r(211)),asBoolStrict:c(r(212)),asBool:c(r(213)),asPortNumber:c(r(214)),asEnum:c(r(215)),asFloatNegative:c(r(216)),asFloatPositive:c(r(217)),asFloat:c(r(51)),asIntNegative:c(r(218)),asIntPositive:c(r(91)),asInt:c(r(50)),asJsonArray:c(r(219)),asJsonObject:c(r(220)),asJson:c(r(52)),asString:c(r(35)),asUrlObject:c(r(92)),asUrlString:c(r(221)),convertFromBase64:function(){return R=!0,w},default:function(E){if(typeof E=="number")u=E.toString();else if(Array.isArray(E)||typeof E=="object"&&E!==null)u=JSON.stringify(E);else{if(typeof E!="string")throw new i("values passed to default() must be of Number, String, Array, or Object type");u=E}return w},required:function(E){return y=E===void 0||E,w},example:function(E){return m=E,w}};return Object.entries(l).forEach(([E,P])=>{w[E]=c(P)}),w}}).call(this,r(4).Buffer)},function(e,t,r){const n=r(35);e.exports=function(i,g){return g=g||",",i.length?n(i).split(g).filter(Boolean):[]}},function(e,t,r){e.exports=function(n){const i=n.toLowerCase();if(i!=="false"&&i!=="true")throw new Error('should be either "true", "false", "TRUE", or "FALSE"');return i!=="false"}},function(e,t,r){e.exports=function(n){const i=n.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,r){const n=r(91);e.exports=function(i){var g=n(i);if(g>65535)throw new Error("cannot assign a port number greater than 65535");return g}},function(e,t,r){const n=r(35);e.exports=function(i,g){const s=n(i);if(g.indexOf(s)<0)throw new Error(`should be one of [${g.join(", ")}]`);return s}},function(e,t,r){const n=r(51);e.exports=function(i){const g=n(i);if(g>0)throw new Error("should be a negative float");return g}},function(e,t,r){const n=r(51);e.exports=function(i){const g=n(i);if(g<0)throw new Error("should be a positive float");return g}},function(e,t,r){const n=r(50);e.exports=function(i){const g=n(i);if(g>0)throw new Error("should be a negative integer");return g}},function(e,t,r){const n=r(52);e.exports=function(i){var g=n(i);if(!Array.isArray(g))throw new Error("should be a parseable JSON Array");return g}},function(e,t,r){const n=r(52);e.exports=function(i){var g=n(i);if(Array.isArray(g))throw new Error("should be a parseable JSON Object");return g}},function(e,t,r){const n=r(92);e.exports=function(i){return n(i).toString()}},function(e,t,r){function n(o){var l=this;if(l instanceof n||(l=new n),l.tail=null,l.head=null,l.length=0,o&&typeof o.forEach=="function")o.forEach(function(R){l.push(R)});else if(arguments.length>0)for(var u=0,m=arguments.length;u<m;u++)l.push(arguments[u]);return l}function i(o,l){o.tail=new s(l,o.tail,null,o),o.head||(o.head=o.tail),o.length++}function g(o,l){o.head=new s(l,null,o.head,o),o.tail||(o.tail=o.head),o.length++}function s(o,l,u,m){if(!(this instanceof s))return new s(o,l,u,m);this.list=m,this.value=o,l?(l.next=this,this.prev=l):this.prev=null,u?(u.prev=this,this.next=u):this.next=null}e.exports=n,n.Node=s,n.create=n,n.prototype.removeNode=function(o){if(o.list!==this)throw new Error("removing node which does not belong to this list");var l=o.next,u=o.prev;l&&(l.prev=u),u&&(u.next=l),o===this.head&&(this.head=l),o===this.tail&&(this.tail=u),o.list.length--,o.next=null,o.prev=null,o.list=null},n.prototype.unshiftNode=function(o){if(o!==this.head){o.list&&o.list.removeNode(o);var l=this.head;o.list=this,o.next=l,l&&(l.prev=o),this.head=o,this.tail||(this.tail=o),this.length++}},n.prototype.pushNode=function(o){if(o!==this.tail){o.list&&o.list.removeNode(o);var l=this.tail;o.list=this,o.prev=l,l&&(l.next=o),this.tail=o,this.head||(this.head=o),this.length++}},n.prototype.push=function(){for(var o=0,l=arguments.length;o<l;o++)i(this,arguments[o]);return this.length},n.prototype.unshift=function(){for(var o=0,l=arguments.length;o<l;o++)g(this,arguments[o]);return this.length},n.prototype.pop=function(){if(this.tail){var o=this.tail.value;return this.tail=this.tail.prev,this.tail?this.tail.next=null:this.head=null,this.length--,o}},n.prototype.shift=function(){if(this.head){var o=this.head.value;return this.head=this.head.next,this.head?this.head.prev=null:this.tail=null,this.length--,o}},n.prototype.forEach=function(o,l){l=l||this;for(var u=this.head,m=0;u!==null;m++)o.call(l,u.value,m,this),u=u.next},n.prototype.forEachReverse=function(o,l){l=l||this;for(var u=this.tail,m=this.length-1;u!==null;m--)o.call(l,u.value,m,this),u=u.prev},n.prototype.get=function(o){for(var l=0,u=this.head;u!==null&&l<o;l++)u=u.next;if(l===o&&u!==null)return u.value},n.prototype.getReverse=function(o){for(var l=0,u=this.tail;u!==null&&l<o;l++)u=u.prev;if(l===o&&u!==null)return u.value},n.prototype.map=function(o,l){l=l||this;for(var u=new n,m=this.head;m!==null;)u.push(o.call(l,m.value,this)),m=m.next;return u},n.prototype.mapReverse=function(o,l){l=l||this;for(var u=new n,m=this.tail;m!==null;)u.push(o.call(l,m.value,this)),m=m.prev;return u},n.prototype.reduce=function(o,l){var u,m=this.head;if(arguments.length>1)u=l;else{if(!this.head)throw new TypeError("Reduce of empty list with no initial value");m=this.head.next,u=this.head.value}for(var R=0;m!==null;R++)u=o(u,m.value,R),m=m.next;return u},n.prototype.reduceReverse=function(o,l){var u,m=this.tail;if(arguments.length>1)u=l;else{if(!this.tail)throw new TypeError("Reduce of empty list with no initial value");m=this.tail.prev,u=this.tail.value}for(var R=this.length-1;m!==null;R--)u=o(u,m.value,R),m=m.prev;return u},n.prototype.toArray=function(){for(var o=new Array(this.length),l=0,u=this.head;u!==null;l++)o[l]=u.value,u=u.next;return o},n.prototype.toArrayReverse=function(){for(var o=new Array(this.length),l=0,u=this.tail;u!==null;l++)o[l]=u.value,u=u.prev;return o},n.prototype.slice=function(o,l){(l=l||this.length)<0&&(l+=this.length),(o=o||0)<0&&(o+=this.length);var u=new n;if(l<o||l<0)return u;o<0&&(o=0),l>this.length&&(l=this.length);for(var m=0,R=this.head;R!==null&&m<o;m++)R=R.next;for(;R!==null&&m<l;m++,R=R.next)u.push(R.value);return u},n.prototype.sliceReverse=function(o,l){(l=l||this.length)<0&&(l+=this.length),(o=o||0)<0&&(o+=this.length);var u=new n;if(l<o||l<0)return u;o<0&&(o=0),l>this.length&&(l=this.length);for(var m=this.length,R=this.tail;R!==null&&m>l;m--)R=R.prev;for(;R!==null&&m>o;m--,R=R.prev)u.push(R.value);return u},n.prototype.reverse=function(){for(var o=this.head,l=this.tail,u=o;u!==null;u=u.prev){var m=u.prev;u.prev=u.next,u.next=m}return this.head=l,this.tail=o,this};try{r(223)(n)}catch{}},function(e,t,r){e.exports=function(n){n.prototype[Symbol.iterator]=function*(){for(let i=this.head;i;i=i.next)yield i.value}}},function(e,t,r){(function(n){(function(){var i,g,s,o,l,u;typeof performance!="undefined"&&performance!==null&&performance.now?e.exports=function(){return performance.now()}:n!=null&&n.hrtime?(e.exports=function(){return(i()-l)/1e6},g=n.hrtime,o=(i=function(){var m;return 1e9*(m=g())[0]+m[1]})(),u=1e9*n.uptime(),l=o-u):Date.now?(e.exports=function(){return Date.now()-s},s=Date.now()):(e.exports=function(){return new Date().getTime()-s},s=new Date().getTime())}).call(this)}).call(this,r(2))},function(e,t,r){var n,i,g=r(96),s=r(97),o=0,l=0;e.exports=function(u,m,R){var y=m&&R||0,S=m||[],c=(u=u||{}).node||n,w=u.clockseq!==void 0?u.clockseq:i;if(c==null||w==null){var E=g();c==null&&(c=n=[1|E[0],E[1],E[2],E[3],E[4],E[5]]),w==null&&(w=i=16383&(E[6]<<8|E[7]))}var P=u.msecs!==void 0?u.msecs:new Date().getTime(),F=u.nsecs!==void 0?u.nsecs:l+1,M=P-o+(F-l)/1e4;if(M<0&&u.clockseq===void 0&&(w=w+1&16383),(M<0||P>o)&&u.nsecs===void 0&&(F=0),F>=1e4)throw new Error("uuid.v1(): Can't create more than 10M uuids/sec");o=P,l=F,i=w;var A=(1e4*(268435455&(P+=122192928e5))+F)%4294967296;S[y++]=A>>>24&255,S[y++]=A>>>16&255,S[y++]=A>>>8&255,S[y++]=255&A;var p=P/4294967296*1e4&268435455;S[y++]=p>>>8&255,S[y++]=255&p,S[y++]=p>>>24&15|16,S[y++]=p>>>16&255,S[y++]=w>>>8|128,S[y++]=255&w;for(var N=0;N<6;++N)S[y+N]=c[N];return m||s(S)}},function(e,t,r){var n=r(96),i=r(97);e.exports=function(g,s,o){var l=s&&o||0;typeof g=="string"&&(s=g==="binary"?new Array(16):null,g=null);var u=(g=g||{}).random||(g.rng||n)();if(u[6]=15&u[6]|64,u[8]=63&u[8]|128,s)for(var m=0;m<16;++m)s[l+m]=u[m];return s||i(u)}},function(e,t,r){(function(n){(function(i){function g(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 s(o,l){if(l=l===void 0?{fatal:!1}:l,(o=o===void 0?"utf-8":o)!=="utf-8")throw new RangeError("Failed to construct 'TextDecoder': The encoding label provided ('"+o+"') is invalid.");if(l.fatal)throw Error("Failed to construct 'TextDecoder': the 'fatal' option is unsupported.")}if(i.TextEncoder&&i.TextDecoder)return!1;Object.defineProperty(g.prototype,"encoding",{value:"utf-8"}),g.prototype.encode=function(o,l){if((l=l===void 0?{stream:!1}:l).stream)throw Error("Failed to encode: the 'stream' option is unsupported.");l=0;for(var u=o.length,m=0,R=Math.max(32,u+(u>>1)+7),y=new Uint8Array(R>>3<<3);l<u;){var S=o.charCodeAt(l++);if(55296<=S&&56319>=S){if(l<u){var c=o.charCodeAt(l);(64512&c)==56320&&(++l,S=((1023&S)<<10)+(1023&c)+65536)}if(55296<=S&&56319>=S)continue}if(m+4>y.length&&(R+=8,R=(R*=1+l/o.length*2)>>3<<3,(c=new Uint8Array(R)).set(y),y=c),(4294967168&S)==0)y[m++]=S;else{if((4294965248&S)==0)y[m++]=S>>6&31|192;else if((4294901760&S)==0)y[m++]=S>>12&15|224,y[m++]=S>>6&63|128;else{if((4292870144&S)!=0)continue;y[m++]=S>>18&7|240,y[m++]=S>>12&63|128,y[m++]=S>>6&63|128}y[m++]=63&S|128}}return y.slice(0,m)},Object.defineProperty(s.prototype,"encoding",{value:"utf-8"}),Object.defineProperty(s.prototype,"fatal",{value:!1}),Object.defineProperty(s.prototype,"ignoreBOM",{value:!1}),s.prototype.decode=function(o,l){if((l=l===void 0?{stream:!1}:l).stream)throw Error("Failed to decode: the 'stream' option is unsupported.");l=0;for(var u=(o=new Uint8Array(o)).length,m=[];l<u;){var R=o[l++];if(R===0)break;if((128&R)==0)m.push(R);else if((224&R)==192){var y=63&o[l++];m.push((31&R)<<6|y)}else if((240&R)==224){y=63&o[l++];var S=63&o[l++];m.push((31&R)<<12|y<<6|S)}else(248&R)==240&&(65535<(R=(7&R)<<18|(y=63&o[l++])<<12|(S=63&o[l++])<<6|63&o[l++])&&(R-=65536,m.push(R>>>10&1023|55296),R=56320|1023&R),m.push(R))}return String.fromCharCode.apply(null,m)},i.TextEncoder=g,i.TextDecoder=s})(typeof window!="undefined"?window:n!==void 0?n:this)}).call(this,r(5))},function(e,t,r){r.r(t),r.d(t,"AuthClient",function(){return g}),r.d(t,"RtcSignalingClient",function(){return o}),r.d(t,"Credentials",function(){return w}),r.d(t,"SignalingPromiseClient",function(){return E.SignalingPromiseClient}),r.d(t,"IRtcClientConfiguration",function(){}),r.d(t,"IRtcConnectConfiguration",function(){}),r.d(t,"IRtcConnectionStatsInfo",function(){}),r.d(t,"IRtcSendConfiguration",function(){}),r.d(t,"IRtcSessionMetricsMessageCounts",function(){}),r.d(t,"IRtcStreamMessage",function(){}),r.d(t,"IStreamControl",function(){}),r.d(t,"RtcClient",function(){return se});var n=r(26),i=function(oe,z,Z,te){return new(Z||(Z=Promise))(function(ce,ae){function he(fe){try{me(te.next(fe))}catch(ge){ae(ge)}}function de(fe){try{me(te.throw(fe))}catch(ge){ae(ge)}}function me(fe){var ge;fe.done?ce(fe.value):(ge=fe.value,ge instanceof Z?ge:new Z(function(_e){_e(ge)})).then(he,de)}me((te=te.apply(oe,z||[])).next())})};class g extends n.a{adminSignup(z,Z){return i(this,void 0,void 0,function*(){return yield this.fetch("auth/admin-signup",{token:Z,method:"POST",body:JSON.stringify(z)})})}login(z){return i(this,void 0,void 0,function*(){return yield this.fetch("auth/login",{method:"POST",body:JSON.stringify(z),allowUnsafeRetries:!0})})}loginWithGoogleToken(z){return i(this,void 0,void 0,function*(){return yield this.fetch("auth/login-google",{method:"POST",body:JSON.stringify(z),allowUnsafeRetries:!0})})}refresh(z,Z){return i(this,void 0,void 0,function*(){return yield this.fetch("auth/refresh",{method:"POST",body:JSON.stringify({refreshToken:z,tokenExpirationSeconds:Z}),allowUnsafeRetries:!0})})}respondToNewPasswordRequiredChallenge(z){return i(this,void 0,void 0,function*(){return yield this.fetch("auth/respond-to-new-password-required-challenge",{method:"POST",body:JSON.stringify(z)})})}forgotPassword(z){return i(this,void 0,void 0,function*(){return yield this.fetch("auth/forgot-password",{method:"POST",body:JSON.stringify({email:z})})})}confirmForgotPassword(z){return i(this,void 0,void 0,function*(){return yield this.fetch("auth/confirm-forgot-password",{method:"POST",body:JSON.stringify(z)})})}resendInvitation(z){return i(this,void 0,void 0,function*(){return yield this.fetch("auth/resend-invitation",{method:"POST",body:JSON.stringify({email:z})})})}changePassword({token:z,refreshToken:Z,currentPassword:te,newPassword:ce}){return i(this,void 0,void 0,function*(){return yield this.fetch("auth/change-password",{token:z,method:"POST",body:JSON.stringify({refreshToken:Z,currentPassword:te,newPassword:ce})})})}getDeviceCredentials(z){return i(this,void 0,void 0,function*(){return yield this.fetch("auth/device-credentials",{token:z,method:"POST",allowUnsafeRetries:!0})})}impersonate(z,Z){return i(this,void 0,void 0,function*(){return yield this.fetch("auth/impersonate",{token:z,method:"POST",allowUnsafeRetries:!0,body:JSON.stringify({userId:Z})})})}createServiceAccount(z,Z,te){return i(this,void 0,void 0,function*(){return yield this.fetch("auth/service-account",{token:z,method:"POST",allowUnsafeRetries:!0,body:JSON.stringify({name:Z,role:te})})})}sendPlanUpgradeRequest(z){return i(this,void 0,void 0,function*(){return yield this.fetch("auth/upgrade-plan",{token:z,method:"POST",allowUnsafeRetries:!0})})}}var s=function(oe,z,Z,te){return new(Z||(Z=Promise))(function(ce,ae){function he(fe){try{me(te.next(fe))}catch(ge){ae(ge)}}function de(fe){try{me(te.throw(fe))}catch(ge){ae(ge)}}function me(fe){var ge;fe.done?ce(fe.value):(ge=fe.value,ge instanceof Z?ge:new Z(function(_e){_e(ge)})).then(he,de)}me((te=te.apply(oe,z||[])).next())})};class o extends n.a{createPeer(z,Z){return s(this,void 0,void 0,function*(){return yield this.fetch("peers",{token:z,method:"POST",body:JSON.stringify(Z)})})}getPeers(z){return s(this,void 0,void 0,function*(){return(yield this.fetch("peers",{token:z})).items})}refreshPeer(z,Z){return s(this,void 0,void 0,function*(){yield this.fetch(`peers/${Z}/refresh`,{token:z,method:"POST",allowUnsafeRetries:!0})})}createSession(z,Z){return s(this,void 0,void 0,function*(){return yield this.fetch("sessions",{token:z,method:"POST",body:JSON.stringify(Z)})})}refreshSession(z,Z){return s(this,void 0,void 0,function*(){yield this.fetch(`sessions/${Z}/refresh`,{token:z,method:"POST",allowUnsafeRetries:!0})})}deleteSession(z,Z){return s(this,void 0,void 0,function*(){yield this.fetch(`sessions/${Z}`,{token:z,method:"DELETE",allowUnsafeRetries:!0})})}getSessions(z){return s(this,void 0,void 0,function*(){return(yield this.fetch("sessions",{token:z})).items})}getIceServers(z){return s(this,void 0,void 0,function*(){return(yield this.fetch("ice-servers",{token:z})).items})}addSignals(z,Z,te){return s(this,void 0,void 0,function*(){yield this.fetch(`sessions/${Z}/add-signals`,{token:z,method:"POST",body:JSON.stringify(te)})})}takeSignals(z,Z){return s(this,void 0,void 0,function*(){return(yield this.fetch(`sessions/${Z}/take-signals`,{token:z,method:"POST"})).items})}}var l=r(1),u=r(10),m=r(21),R=r(102),y=function(oe,z,Z,te){return new(Z||(Z=Promise))(function(ce,ae){function he(fe){try{me(te.next(fe))}catch(ge){ae(ge)}}function de(fe){try{me(te.throw(fe))}catch(ge){ae(ge)}}function me(fe){var ge;fe.done?ce(fe.value):(ge=fe.value,ge instanceof Z?ge:new Z(function(_e){_e(ge)})).then(he,de)}me((te=te.apply(oe,z||[])).next())})};class S extends class{constructor(z={}){this.cache=new R(z),this.stringify=z.fastStringify?JSON.stringify:m}set(z,Z,te){if(!this.cache.set(this.stringify(z),Z,te))throw Error(`Value too large (${this.cache.lengthCalculator(Z)} > ${this.cache.max})`)}get(z){return this.cache.get(this.stringify(z))}del(z){this.cache.del(this.stringify(z))}length(){return this.cache.length}reset(){this.cache.reset()}prune(){return this.cache.prune()}forEach(z){return this.cache.forEach(z)}}{constructor(z={}){if(super(z),this.expireRejectedPromiseValues=z.expireRejectedPromiseValues===void 0||z.expireRejectedPromiseValues,this.rejectedPromiseValueTtl=z.rejectedPromiseValueTtl!==void 0?z.rejectedPromiseValueTtl:l.a.second,this.rejectedPromiseValueTtl<0)throw new Error("rejectedPromiseValueTtl must not be negative")}set(z,Z,te){const ce=this.stringify(z);this.cache.set(ce,Z,te),this.expireRejectedPromiseValues&&Promise.resolve(Z).catch(()=>y(this,void 0,void 0,function*(){yield Object(u.a)(this.rejectedPromiseValueTtl),this.cache.peek(ce)===Z&&this.cache.del(ce)}))}}var c=function(oe,z,Z,te){return new(Z||(Z=Promise))(function(ce,ae){function he(fe){try{me(te.next(fe))}catch(ge){ae(ge)}}function de(fe){try{me(te.throw(fe))}catch(ge){ae(ge)}}function me(fe){var ge;fe.done?ce(fe.value):(ge=fe.value,ge instanceof Z?ge:new Z(function(_e){_e(ge)})).then(he,de)}me((te=te.apply(oe,z||[])).next())})};class w{constructor(z,Z,te){this.authClient=z,this.email=Z,this.password=te,this.tokenTtlMs=1*l.a.hour,this.tokenCache=new S({max:100,maxAge:this.tokenTtlMs-5*l.a.minute,fastStringify:!0})}getToken(){return c(this,void 0,void 0,function*(){let z=this.tokenCache.get(this.email);return z||(z=(()=>c(this,void 0,void 0,function*(){const{authentication:Z}=yield this.authClient.login({email:this.email,password:this.password,tokenExpirationSeconds:this.tokenTtlMs/l.a.second});if(!Z)throw new Error("User account not verified.");return Z.accessToken}))(),this.tokenCache.set(this.email,z)),z})}}var E=r(93),P=function(oe,z,Z,te){return new(Z||(Z=Promise))(function(ce,ae){function he(fe){try{me(te.next(fe))}catch(ge){ae(ge)}}function de(fe){try{me(te.throw(fe))}catch(ge){ae(ge)}}function me(fe){var ge;fe.done?ce(fe.value):(ge=fe.value,ge instanceof Z?ge:new Z(function(_e){_e(ge)})).then(he,de)}me((te=te.apply(oe,z||[])).next())})};function F(oe){return P(this,void 0,void 0,function*(){return(yield Promise.all(oe.map(z=>z.catch(Z=>Z)))).filter(z=>z instanceof Error)})}function M(oe){if(oe!==void 0)return oe;throw new Error("Value is undefined")}var A=r(0),p=function(oe,z,Z,te){return new(Z||(Z=Promise))(function(ce,ae){function he(fe){try{me(te.next(fe))}catch(ge){ae(ge)}}function de(fe){try{me(te.throw(fe))}catch(ge){ae(ge)}}function me(fe){var ge;fe.done?ce(fe.value):(ge=fe.value,ge instanceof Z?ge:new Z(function(_e){_e(ge)})).then(he,de)}me((te=te.apply(oe,z||[])).next())})};function N({func:oe,delay:z,immediate:Z}){let te=!1,ce=setTimeout(function he(){return p(this,void 0,void 0,function*(){if(te)return;const de=new Date().getTime();try{ae=oe(),yield ae}finally{if(!te){const me=new Date().getTime();ce=setTimeout(he,Math.max(z-(me-de),0))}}})},Z?0:z),ae=Promise.resolve();return{stop(){return p(this,void 0,void 0,function*(){te=!0,clearTimeout(ce),yield ae})}}}function $(oe,z){return Object.keys(oe).reduce((Z,te)=>Object.assign(Object.assign({},Z),{[te]:z(oe[te])}),{})}var q=function(oe,z,Z,te){return new(Z||(Z=Promise))(function(ce,ae){function he(fe){try{me(te.next(fe))}catch(ge){ae(ge)}}function de(fe){try{me(te.throw(fe))}catch(ge){ae(ge)}}function me(fe){var ge;fe.done?ce(fe.value):(ge=fe.value,ge instanceof Z?ge:new Z(function(_e){_e(ge)})).then(he,de)}me((te=te.apply(oe,z||[])).next())})};class h{constructor(z){this.message=z}send(z){return q(this,void 0,void 0,function*(){A.a.info(this.message,$(z,Z=>{const{sum:te,count:ce}=Z,ae=te/ce;return Object.assign(Object.assign({},Z),{average:ae})}))})}}var d=function(oe,z,Z,te){return new(Z||(Z=Promise))(function(ce,ae){function he(fe){try{me(te.next(fe))}catch(ge){ae(ge)}}function de(fe){try{me(te.throw(fe))}catch(ge){ae(ge)}}function me(fe){var ge;fe.done?ce(fe.value):(ge=fe.value,ge instanceof Z?ge:new Z(function(_e){_e(ge)})).then(he,de)}me((te=te.apply(oe,z||[])).next())})};const O=r(224),_=!!r(7).c,x=new class{constructor(oe=60){this.buffer={},this.metrics={},this.reporters=[],this.flushInterval=N({func:()=>this.flushStats(),delay:oe*l.a.second})}shutdown(){return d(this,void 0,void 0,function*(){yield this.flushInterval.stop(),yield this.flushStats(),yield Object(u.a)(2*l.a.second)})}aggregate(oe,z){if(this.buffer[oe]){const{min:Z,max:te,sum:ce,count:ae}=this.buffer[oe];this.buffer[oe]={min:Math.min(Z,z),max:Math.max(te,z),sum:ce+z,count:ae+1}}else this.buffer[oe]={min:z,max:z,sum:z,count:1}}increment(oe){this.aggregate(oe,1)}timer(oe,z){return d(this,void 0,void 0,function*(){const Z=O(),te=yield z(),ce=O();return this.aggregate(oe,ce-Z),te})}metric(oe,z){this.metrics[oe]=z}registerStatsReporter(oe){this.reporters.push(oe)}write(oe){return d(this,void 0,void 0,function*(){if(Object.values(oe).length===0)return;const z=yield F(this.reporters.map(Z=>Z.send(oe)));for(const Z of z)A.a.warn("Failed to write stats",{error:Z})})}flushStats(){return d(this,void 0,void 0,function*(){const oe=Object.assign(Object.assign({},this.buffer),$(this.metrics,z=>{const Z=z();return{min:Z,max:Z,sum:Z,count:1}}));Object.keys(oe).length>0&&(yield this.write(oe),this.buffer={})})}};_||x.registerStatsReporter(new h("stats"));var D=r(11),L=r(22),T=r(103),C=r(36),U=function(oe,z,Z,te){return new(Z||(Z=Promise))(function(ce,ae){function he(fe){try{me(te.next(fe))}catch(ge){ae(ge)}}function de(fe){try{me(te.throw(fe))}catch(ge){ae(ge)}}function me(fe){var ge;fe.done?ce(fe.value):(ge=fe.value,ge instanceof Z?ge:new Z(function(_e){_e(ge)})).then(he,de)}me((te=te.apply(oe,z||[])).next())})};class b extends C.a{constructor(z){super(z)}postLanRtcOffer(z){return U(this,void 0,void 0,function*(){return yield this.fetch("v1/lan-rtc-offer",{method:"POST",body:JSON.stringify(z)})})}}var f=r(55);const B={ordered:!1,maxPacketLifeTime:300*l.a.millisecond},k={ordered:!0},Y={ordered:!0},K={ordered:!1,maxRetransmits:0},Q={ordered:!1,maxRetransmits:0};function G({entityId:oe,streamName:z,streamType:Z}){return`${oe}.${z}.${Z}`}var V=function(oe,z,Z,te){return new(Z||(Z=Promise))(function(ce,ae){function he(fe){try{me(te.next(fe))}catch(ge){ae(ge)}}function de(fe){try{me(te.throw(fe))}catch(ge){ae(ge)}}function me(fe){var ge;fe.done?ce(fe.value):(ge=fe.value,ge instanceof Z?ge:new Z(function(_e){_e(ge)})).then(he,de)}me((te=te.apply(oe,z||[])).next())})};class v{constructor(z,Z){this.sessionId=z,this.connection=Z,this.counts={localSent:new Map,localReceived:new Map,remoteSent:new Map,remoteReceived:new Map},this.sessionId=z,this.connection=Z}updateRemoteMessagesCounts(z){if(z.payload.streamsInfo){this.counts.remoteSent=new Map,this.counts.remoteReceived=new Map;for(const Z of z.payload.streamsInfo.items)this.counts.remoteSent.set(Z.streamId,Z.sentCount),this.counts.remoteReceived.set(Z.streamId,Z.receivedCount)}}getLocalStreamsInfo(z){const{localSent:Z,localReceived:te}=this.counts;return{items:[...new Set([...Z.keys(),...te.keys()])].map(ce=>{var ae,he;return{streamId:ce,sentCount:(ae=Z.get(ce))!==null&&ae!==void 0?ae:0,receivedCount:(he=te.get(ce))!==null&&he!==void 0?he:0}}),timestamp:z}}incrementLocalSent(z){const{localSent:Z}=this.counts,te=G(z.header.stream);Z.set(te,(Z.get(te)||0)+1)}incrementLocalReceived(z){const{localReceived:Z}=this.counts,te=G(z.header.stream),ce=Z.get(te)||0;if(ce===0){const{streamName:ae,streamType:he}=z.header.stream;A.a.debug("RTC client received first message for stream",{streamName:ae,streamType:he})}Z.set(te,ce+1)}uploadMetrics(){return V(this,void 0,void 0,function*(){const{sessionId:z}=this,Z=yield this.connection.peerConnection.getStats(),te={};Z.forEach(fe=>te[fe.id]=fe),A.a.debug("rtc-stats",Object.assign(Object.assign({},te),{sessionId:z}));const{localSent:ce,localReceived:ae,remoteSent:he,remoteReceived:de}=this.counts,me=[...new Set([...ce.keys(),...ae.keys()])].reduce((fe,ge)=>{const _e=ce.get(ge),Se=ae.get(ge),Oe=he.get(ge),Pe=de.get(ge);return Object.assign(Object.assign({},fe),{[`local-${ge}-sent`]:_e,[`local-${ge}-received`]:Se,[`remote-${ge}-sent`]:Oe,[`remote-${ge}-received`]:Pe})},{sessionId:z});A.a.debug("rtc-message-report",Object.assign({deviceId:this.connection.getRemoteDeviceId()},me))})}}function j(oe){return new Set(["disconnected","failed","closed"]).has(oe.iceConnectionState)}var W=function(oe,z,Z,te){return new(Z||(Z=Promise))(function(ce,ae){function he(fe){try{me(te.next(fe))}catch(ge){ae(ge)}}function de(fe){try{me(te.throw(fe))}catch(ge){ae(ge)}}function me(fe){var ge;fe.done?ce(fe.value):(ge=fe.value,ge instanceof Z?ge:new Z(function(_e){_e(ge)})).then(he,de)}me((te=te.apply(oe,z||[])).next())})};class ee{constructor(z,Z,te){this.peerConnection=z,this.config=Z,this.dataChannelNotifier=te,this.connectTimeoutMs=20*l.a.second,this.iceGatheringTimeoutMs=15*l.a.second,this.pingUpdateTimeoutMs=1*l.a.second,this.streamsInfoUpdateTimeoutMs=2*l.a.second,this.reassemblyTimeoutMs=500*l.a.millisecond,this.reassemblyTableCleanupMs=1*l.a.second,this.heartbeatTimeoutMs=20*l.a.millisecond,this.streamLatestTimestamp=new Map,this.reassemblyTable=new Map,this.reassemblyTableLastTimestamp=new Map,this.closeCalled=!1,this.gotOffer=!1,this.hasIceCandidate=!1;const{isOffer:ce}=Z.baseConfig;ce?this.initializeChannels(z):z.ondatachannel=ae=>{switch(ae.channel.label){case"stream.latest-ttl":this.latestTtlStreamChannel=ae.channel;break;case"stream.reliable":this.reliableStreamChannel=ae.channel;break;case"stream.latest-reliable":this.latestReliableStreamChannel=ae.channel;break;case"stream.latest-try-once":this.latestTryOnceStreamChannel=ae.channel;break;case"heartbeat":return void(this.heartbeatChannel=ae.channel);default:return void this.dataChannelNotifier(ae.channel)}this.setupChannel(ae.channel)},this.pingUpdateTimeout=setInterval(()=>{const{reliableStreamChannel:ae}=this;ae&&this.sendSystemMessage(ae,{type:"ping"})},this.pingUpdateTimeoutMs),this.streamsInfoUpdateTimeout=setInterval(()=>{const{latestTtlStreamChannel:ae}=this;ae&&this.sendSystemMessage(ae,{type:"streams-info"})},this.streamsInfoUpdateTimeoutMs),this.reassemblyTableCleanupTimeout=setInterval(()=>{const ae=new Date().getTime();this.reassemblyTableLastTimestamp.forEach((he,de,me)=>{ae>de+this.reassemblyTimeoutMs&&this.reassemblyTable.delete(he)})},this.reassemblyTableCleanupMs),this.heartbeatTimeout=setInterval(()=>{const{heartbeatChannel:ae}=this;ae&&ae.readyState==="open"&&ae.send(new Uint8Array([1]))},this.heartbeatTimeoutMs)}handleSignal(z){return W(this,void 0,void 0,function*(){const{peerConnection:Z}=this,{track:te}=this.config.baseConfig,ce=(()=>{try{return JSON.parse(z.getPayload())}catch{return}})();if(!ce)return void A.a.error("Received unparseable signal.");A.a.debug("Handling signal",{description:ce});const{sdp:ae,type:he}=ce;if(!ae||!he)return void A.a.warn("Received non-SDP signal");const{signalingState:de,connectionState:me}=Z;if(de!=="stable"||me!=="connected")if(Z.remoteDescription)A.a.warn(`Received SDP after remote description was set: ${ae}`);else{if(he==="offer"){if(de!=="stable")return void A.a.warn("Received offer SDP when signaling is ongoing.");yield Z.setRemoteDescription(ce);const fe=yield Z.createAnswer();yield Z.setLocalDescription(fe);const ge=z.clone();return te==null||te("Answer Received",ge),ge.setPayload(JSON.stringify(fe)),ge.setReceiverId(z.getSenderId()),ge.setSenderId(z.getReceiverId()),ge}if(he==="answer"){if(de==="stable")return void A.a.warn("Received answer SDP when signaling hasn't started.");yield Z.setRemoteDescription(ce)}}else A.a.warn(`Received SDP when already connected: ${ae}`)})}send(z,Z){const te=this.getChannelFromLabel(Z.channelLabel);te?this.sendOnChannel(te,z):A.a.warn("Send called with unexpected channel label",{channelLabel:Z.channelLabel})}controlRemoteStream(z){this.sendSystemMessage(M(this.reliableStreamChannel),{type:"stream-control",streamControl:z})}isActive(){return new Set(["new","checking","connected","completed"]).has(this.peerConnection.iceConnectionState)||this.isReady()}isReady(){const{reliableStreamChannel:z,latestTtlStreamChannel:Z,latestTryOnceStreamChannel:te,latestReliableStreamChannel:ce}=this;return(z==null?void 0:z.readyState)==="open"&&(Z==null?void 0:Z.readyState)==="open"&&(te==null?void 0:te.readyState)==="open"&&(ce==null?void 0:ce.readyState)==="open"}close(){return W(this,void 0,void 0,function*(){if(this.closeCalled)return;this.closeCalled=!0,this.sessionMetrics&&(yield this.sessionMetrics.uploadMetrics()),this.pingUpdateTimeout&&clearInterval(this.pingUpdateTimeout),this.reassemblyTableCleanupTimeout&&clearInterval(this.reassemblyTableCleanupTimeout),this.streamsInfoUpdateTimeout&&clearInterval(this.streamsInfoUpdateTimeout),this.heartbeatTimeout&&clearInterval(this.heartbeatTimeout);const{peerConnection:z,reliableStreamChannel:Z,latestTtlStreamChannel:te,latestTryOnceStreamChannel:ce,latestReliableStreamChannel:ae}=this;z.close(),Z==null||Z.close(),te==null||te.close(),ce==null||ce.close(),ae==null||ae.close()})}getPing(){return this.pingTimeMs}getLastMessageTimestamp(){return this.lastMessageTimestamp}getSessionCreatedTimestamp(){var z;return(z=this.config.remoteConfig)===null||z===void 0?void 0:z.sessionCreatedTimestamp}setSessionCreatedTimestamp(z){this.config.remoteConfig&&(this.config.remoteConfig.sessionCreatedTimestamp=z)}getSessionId(){var z;return(z=this.config.remoteConfig)===null||z===void 0?void 0:z.sessionId}setSessionId(z){this.config.remoteConfig&&(this.config.remoteConfig.sessionId=z,this.sessionMetrics=new v(z,this))}getRemotePeerId(){return this.config.baseConfig.remotePeerId}getRemoteDeviceId(){var z;return(z=this.config.baseConfig)===null||z===void 0?void 0:z.remoteDeviceId}setRemoteDeviceId(z){this.config.baseConfig.remoteDeviceId=z}getSessionMetricsMessageCounts(){var z;return(z=this.sessionMetrics)===null||z===void 0?void 0:z.counts}getConnectionStatsInfo(){return W(this,void 0,void 0,function*(){const{peerConnection:z}=this;if(!z)return;const Z=yield z.getStats(null),te=[];Z.forEach(me=>{te.push(me)});const ce=te.find(me=>me.type==="transport");if(!ce)return;const ae=te.find(me=>(me.type==="candidate-pair"||me.type==="candidatepair")&&me.id===ce.selectedCandidatePairId);if(!ae)return;const he=te.find(me=>me.id===ae.localCandidateId),de=te.find(me=>me.id===ae.remoteCandidateId);return he&&de&&(he.address=he.address||he.ip,de.address=de.address||de.ip,he.address!==void 0&&de.address!==void 0)?{transport:ce,localCandidate:he,remoteCandidate:de}:void 0})}initializeChannels(z){this.heartbeatChannel=z.createDataChannel("heartbeat",Q),this.heartbeatChannel.binaryType="arraybuffer",this.latestTtlStreamChannel=z.createDataChannel("stream.latest-ttl",B),this.latestTtlStreamChannel.binaryType="arraybuffer",this.reliableStreamChannel=z.createDataChannel("stream.reliable",k),this.reliableStreamChannel.binaryType="arraybuffer",this.latestReliableStreamChannel=z.createDataChannel("stream.latest-reliable",Y),this.latestReliableStreamChannel.binaryType="arraybuffer",this.latestTryOnceStreamChannel=z.createDataChannel("stream.latest-try-once",K),this.latestTryOnceStreamChannel.binaryType="arraybuffer",this.setupChannel(this.latestTtlStreamChannel),this.setupChannel(this.reliableStreamChannel),this.setupChannel(this.latestReliableStreamChannel),this.setupChannel(this.latestTryOnceStreamChannel)}getOffer(){var z,Z,te;return W(this,void 0,void 0,function*(){const{gotOffer:ce}=this,{peerConnection:ae,config:he}=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 de=(z=this.config.remoteConfig)===null||z===void 0?void 0:z.sessionId;if(ce)return void A.a.debug("Failed to generate offer because gotOffer was already called.");if(this.gotOffer=!0,j(this.peerConnection))return void A.a.debug("Failed to generate offer because the peer connection was inactive.");const me=he.baseConfig.track;ae.onicecandidate=()=>{this.hasIceCandidate=!0},ae.oniceconnectionstatechange=()=>W(this,void 0,void 0,function*(){const Oe=ae.iceConnectionState;if(Oe==="connected"||Oe==="completed"){const Pe=yield this.getConnectionStatsInfo(),Fe=Pe?function(De){const Le=De.localCandidate.candidateType,xe=De.remoteCandidate.candidateType;return Le==="host"&&xe==="host"?"local":Le==="relay"||xe==="relay"?"TURN":"STUN"}(Pe):void 0;A.a.info(`ICE connection state changed to ${Oe}`,{sessionId:de,connectionStatsInfo:Pe,iceMode:Fe}),me==null||me("ICE connection state change",{iceConnectionState:Oe,sessionId:de,connectionStatsInfo:Pe,iceMode:Fe})}}),yield ae.setLocalDescription(yield ae.createOffer());const fe=new Date().getTime();for(;;){const Oe=new Date().getTime()-fe;if(Oe>this.connectTimeoutMs)return void A.a.debug("Failed to generate offer because ICE gathering timed out.");if(Oe>this.iceGatheringTimeoutMs&&this.hasIceCandidate){A.a.debug("ICE gathering partially completed; proceeding",{iceTransportPolicy:ae.getConfiguration().iceTransportPolicy,waitTime:Oe}),me==null||me("ICE gathering partially completed",{sessionId:de,iceTransportPolicy:ae.getConfiguration().iceTransportPolicy,waitTime:Oe});break}if(ae.iceGatheringState==="complete"){A.a.debug("ICE gathering complete",{iceTransportPolicy:ae.getConfiguration().iceTransportPolicy,waitTime:Oe}),me==null||me("ICE gathering completed",{sessionId:de,iceTransportPolicy:ae.getConfiguration().iceTransportPolicy,waitTime:Oe});break}yield Object(u.a)(.1*l.a.second)}const ge=(Z=this.peerConnection.getConfiguration().iceServers)!==null&&Z!==void 0?Z:[];for(const Oe of ge)Oe.credentialType=void 0;const _e=JSON.stringify(ge),Se=new D.Signal;return Se.setPayload(JSON.stringify(ae.localDescription)),Se.setSenderId(this.config.baseConfig.localPeerId),Se.setReceiverId(this.config.baseConfig.remotePeerId),Se.setIceServers(_e),Se.setIceTransportPolicy((te=this.peerConnection.getConfiguration().iceTransportPolicy)!==null&&te!==void 0?te:"all"),A.a.debug("Sending offer signal with description",{description:Se.getPayload()}),Se})}getLanOffer(){return W(this,void 0,void 0,function*(){const{peerConnection:z,gotOffer:Z}=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(Z)return void A.a.debug("Failed to generate offer because gotOffer was already called.");if(this.gotOffer=!0,j(this.peerConnection))return void A.a.debug("Failed to generate offer because the peer connection was inactive.");yield z.setLocalDescription(yield z.createOffer());const te=new Date().getTime();for(;;){if(new Date().getTime()-te>this.iceGatheringTimeoutMs)return void A.a.debug("Failed to generate offer because ICE gathering timed out.");if(z.iceGatheringState==="complete")break;yield Object(u.a)(.1*l.a.second)}const ce=z.localDescription;if(ce)return A.a.debug("Sending LAN offer signal with description",{description:ce}),ce;A.a.error("Failed to generate LAN offer description")})}handleLanAnswer(z){return W(this,void 0,void 0,function*(){const{peerConnection:Z}=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 Z.setRemoteDescription(z)})}getChannelFromLabel(z){switch(z){case"stream.latest-ttl":return this.latestTtlStreamChannel;case"stream.reliable":return this.reliableStreamChannel;case"stream.latest-reliable":return this.latestReliableStreamChannel;case"stream.latest-try-once":return this.latestTryOnceStreamChannel}}sendOnChannel(z,Z){let te;try{te=Object(f.encode)(JSON.stringify(Z))}catch(ce){return void A.a.warn("Failed to encode RTC message",{error:ce})}try{z.send(te),this.sessionMetrics&&this.sessionMetrics.incrementLocalSent(Z)}catch(ce){A.a.warn("Failed to send message to channel",{error:ce,channel:z.label})}}channelNotRecognized(z){return z!==this.latestTtlStreamChannel&&z!==this.latestReliableStreamChannel&&z!==this.latestTryOnceStreamChannel&&z!==this.reliableStreamChannel}setupChannel(z){z.onmessage=Z=>{if(this.channelNotRecognized(z))return void A.a.warn("Received message on unrecognized data channel.");let te;try{te=JSON.parse(Object(f.decode)(Z.data))}catch(ce){return void A.a.warn("Received unparseable message on RTC stream data channel",{error:ce,channel:z.label})}te.communicationType==="message-chunk"?this.receiveChannelMessageChunk(z,te):this.receiveChannelMessage(z,te)},z.onerror=Z=>{A.a.warn(`Channel error: ${Z.error}`,{error:Z.error,sessionId:this.getSessionId(),channelLabel:z.label})},z.onopen=()=>{A.a.debug("Channel opened",{sessionId:this.getSessionId(),channelLabel:z.label})},z.onclose=()=>{const Z={bufferedAmount:z.bufferedAmount,sessionId:this.getSessionId(),channelLabel:z.label};this.closeCalled===!1?A.a.debug("Unexpected channel closed",Z):A.a.debug("Channel closed",Z)}}receiveChannelMessage(z,Z){const{config:te}=this,{remotePeerId:ce}=this.config.baseConfig;this.lastMessageTimestamp=new Date().getTime(),Z=function(ae){switch(ae.header.stream.streamType){case"twist":const{twist:he}=ae.payload;if(!he)throw Error("twist not in payload of RTC message with type twist");return{header:ae.header,payload:{twist:{linear:Object.assign({x:0,y:0,z:0},he.linear),angular:Object.assign({x:0,y:0,z:0},he.angular)}}};case"pose":const{pose:de}=ae.payload;if(!de)throw Error("pose not in payload of RTC message with type pose");return{header:ae.header,payload:{pose:{translation:Object.assign({x:0,y:0,z:0},de.translation),rotation:Object.assign({x:0,y:0,z:0,w:0},de.rotation)}}};case"pose-with-covariance":const{poseWithCovariance:me}=ae.payload;if(!me)throw Error("poseWithCovariance not in payload of RTC message with type pose-with-covariance");const fe=new Array(36).fill(0);return me.covariance.forEach((_e,Se)=>{if(Se>=36)throw Error("covariance contains more than 36 elements");fe[Se]=_e}),{header:ae.header,payload:{poseWithCovariance:{pose:{translation:Object.assign({x:0,y:0,z:0},me.pose.translation),rotation:Object.assign({x:0,y:0,z:0,w:0},me.pose.rotation)},covariance:fe}}};case"point":const{point:ge}=ae.payload;if(!ge)throw Error("point not in payload of RTC message with type point");return{header:ae.header,payload:{point:Object.assign({x:0,y:0,z:0},ge)}};default:return ae}}(Z),this.sessionMetrics&&this.sessionMetrics.incrementLocalReceived(Z),this.handleSystemMessage(z,Z)||(z===this.latestTryOnceStreamChannel||z===this.latestTtlStreamChannel||z===this.latestReliableStreamChannel)&&!this.isLatestMessage(Z)||te.baseConfig.receive(ce,Z)}receiveChannelMessageChunk(z,Z){const te=this.reassemblyTable.get(Z.id)||[];if(te.push(Z),te.length===Z.total){const ce=function(ae){const he=ae.sort((de,me)=>de.seq<me.seq?-1:1).map(de=>de.part).reduce((de,me)=>de+me);try{return JSON.parse(he)}catch{return void A.a.warn("Could not reassemble RTC message chunks")}}(te);return ce&&this.receiveChannelMessage(z,ce),void this.reassemblyTable.delete(Z.id)}this.reassemblyTable.set(Z.id,te),this.reassemblyTableLastTimestamp.set(Z.id,new Date().getTime())}handleSystemMessage(z,Z){var te,ce;const{config:ae}=this,{baseConfig:he}=ae,{remotePeerId:de}=he;switch(Z.header.stream.streamType){case"ping":return this.sendSystemMessage(z,{type:"pong",timestamp:M(Z.payload.ping)}),!0;case"pong":const me=new Date().getTime()-M(Z.payload.pong);return this.pingTimeMs=me,x.aggregate("rtc-ping-time",me),!0;case"streams-info":const{sessionMetrics:fe}=this,ge=(te=Z.payload.streamsInfo)===null||te===void 0?void 0:te.timestamp;return!!ge&&(fe==null||fe.updateRemoteMessagesCounts(Z),(ce=he.onStreamsInfoUpdate)===null||ce===void 0||ce.call(he,de,ge),!0);case"stream-control":return!0;default:return!1}}sendSystemMessage(z,Z){var te;const{localUserId:ce,localPeerId:ae}=this.config.baseConfig;if(z.readyState!=="open")return;const he={entityId:ce!=null?ce:ae,streamName:`$.${Z.type}`,streamType:Z.type};let de;switch(Z.type){case"ping":de={ping:new Date().getTime()};break;case"pong":de={pong:Z.timestamp};break;case"stream-control":de={streamControl:Z.streamControl};break;case"streams-info":de={streamsInfo:(te=this.sessionMetrics)===null||te===void 0?void 0:te.getLocalStreamsInfo(new Date().getTime())}}this.sendOnChannel(z,function(me,fe){return{header:{stream:me,created:Date.now(),frameId:""},payload:fe}}(he,de))}isLatestMessage(z){const Z=G(z.header.stream),te=(this.streamLatestTimestamp.get(Z)||0)<=z.header.created;return te&&this.streamLatestTimestamp.set(Z,z.header.created),te}}function J(oe){var z,Z;return{userId:(z=oe.getUserId())===null||z===void 0?void 0:z.getValue(),deviceId:(Z=oe.getDeviceId())===null||Z===void 0?void 0:Z.getValue(),organizationId:oe.getOrganizationId(),id:oe.getPeerId(),capabilities:[],capabilitySet:{}}}var re=function(oe,z,Z,te){return new(Z||(Z=Promise))(function(ce,ae){function he(fe){try{me(te.next(fe))}catch(ge){ae(ge)}}function de(fe){try{me(te.throw(fe))}catch(ge){ae(ge)}}function me(fe){var ge;fe.done?ce(fe.value):(ge=fe.value,ge instanceof Z?ge:new Z(function(_e){_e(ge)})).then(he,de)}me((te=te.apply(oe,z||[])).next())})};class se{constructor(z){this.config=z,this.grpcCallDeadline=5*l.a.second,this.refreshIntervalDelayMs=2*l.a.second,this.iceServersTtl=30*l.a.minute,this.connections=[],this.localConnections=[],this.isConnectionInitiator=new Map,this.isOutgoingConnection=new Map,this.peerDataChannelListeners=[];const{refreshIntervalDelayMs:Z}=this;this.refreshInterval=N({func:()=>re(this,void 0,void 0,function*(){try{yield this.update()}catch(te){A.a.warn("RTC refresh failed",{error:te})}}),delay:Z,immediate:!0})}send(z,Z,te){const ce=this.getActiveConnection(z);ce?ce.isReady()?ce.send(Z,te):A.a.warn("Send called with unready connection."):A.a.warn("Send called with no connection.")}controlRemoteStream(z,Z){const te=this.getActiveConnection(z);te?te.isReady()?te.controlRemoteStream(Z):A.a.warn("controlRemoteStream called with unready connection."):A.a.warn("controlRemoteStream called with no connection.")}getLocalPeer(){return re(this,void 0,void 0,function*(){for(;!this.localPeer;)yield Object(u.a)(.1*l.a.second);return J(this.localPeer)})}connect(z,Z){var te,ce,ae;return re(this,void 0,void 0,function*(){if(this.config.lanOnlyMode===!0)throw new Error("connect method called in local only mode.");const{track:he,signalingClient:de}=this.config,{localPeer:me,receiveSignalStream:fe,iceServers:ge}=this;if(!me||!fe||!ge)return void A.a.warn("Connect called prior to local peer, receiveSignalStream, and ICE servers ready");if(this.getActiveConnection(z))return void A.a.warn("Connect called for peer with existing connection.");if(this.isOutgoingConnection.get(z))return void A.a.warn("Connect called for peer with an existing outgoing connection offer.");this.isOutgoingConnection.set(z,!0);const _e=new ee(yield this.createRTCPeerConnection(ge,Z),{baseConfig:{isOffer:!0,isLan:!1,receive:(Le,xe)=>this.config.receive(Le,xe),onStreamsInfoUpdate:this.config.onStreamsInfoUpdate?(Le,xe)=>{var Ne,Ue;return(Ue=(Ne=this.config).onStreamsInfoUpdate)===null||Ue===void 0?void 0:Ue.call(Ne,Le,xe)}:void 0,track:this.config.lanOnlyMode?void 0:this.config.track,localUserId:(te=me.getUserId())===null||te===void 0?void 0:te.getValue(),localPeerId:me.getPeerId(),remotePeerId:z},remoteConfig:{}},Le=>this.onCustomDataChannel(z,Le)),Se=yield _e.getOffer();if(!Se)return A.a.error("Failed to generate offer."),void this.isOutgoingConnection.delete(z);A.a.debug("Sending offer."),he==null||he("Sending offer",Se);const Oe=new D.SendSignalRequest;Oe.setSignal(Se);const Pe=yield(()=>re(this,void 0,void 0,function*(){try{return yield de.sendSignal(Oe,yield this.getMetadata({}))}catch(Le){A.a.warn("Error when sending signal",{error:Le})}}))();if(!this.isOutgoingConnection.get(z))return void A.a.debug("No offer set after receiving offer signal response.");A.a.debug("Offer sent.");const Fe=(ce=Pe==null?void 0:Pe.getSessionId())===null||ce===void 0?void 0:ce.getValue(),De=(ae=Pe==null?void 0:Pe.getSessionCreatedTimestamp())===null||ae===void 0?void 0:ae.getValue();return Fe&&De?(_e.setSessionId(Fe),_e.setSessionCreatedTimestamp(De),this.isOutgoingConnection.delete(z),this.connections.push(_e),this.isConnectionInitiator.set(_e,!0),this.setupHandlers(_e),Fe):(A.a.warn("No session ID or no session created timestamp on send signal response."),void this.isOutgoingConnection.delete(z))})}connectLan(z){var Z,te;return re(this,void 0,void 0,function*(){const ce=new b(z),ae=new ee(yield this.createRTCPeerConnection([]),{baseConfig:{isOffer:!0,isLan:!0,receive:(fe,ge)=>this.config.receive(fe,ge),onStreamsInfoUpdate:this.config.onStreamsInfoUpdate?(fe,ge)=>{var _e,Se;return(Se=(_e=this.config).onStreamsInfoUpdate)===null||Se===void 0?void 0:Se.call(_e,fe,ge)}:void 0,track:this.config.lanOnlyMode?void 0:this.config.track,localUserId:(te=(Z=this.localPeer)===null||Z===void 0?void 0:Z.getUserId())===null||te===void 0?void 0:te.getValue(),localPeerId:"lan_client",remotePeerId:z}},fe=>this.onCustomDataChannel(z,fe)),he=yield ae.getLanOffer();if(!he)return A.a.warn("Could not generate LAN offer"),!1;const de=yield ce.postLanRtcOffer({offer:JSON.stringify(he)}),me=new RTCSessionDescription(JSON.parse(de.answer));return yield ae.handleLanAnswer(me),this.localConnections.push(ae),Object(T.v4)()})}getConnections(){return[...this.connections,...this.localConnections]}createCustomDataChannel(z,Z,te,ce,ae){const he=this.getActiveConnection(z);if(he&&this.isConnectionInitiator.has(he)){const me=he.peerConnection.createDataChannel("custom."+Z,te);return ce&&(me.binaryType="arraybuffer"),ae(z,me),()=>{}}const de=(me,fe)=>{z===me&&fe.label==="custom."+Z&&ae(z,fe)};return this.peerDataChannelListeners.push(de),()=>{this.peerDataChannelListeners=this.peerDataChannelListeners.filter(me=>me!==de)}}onCustomDataChannel(z,Z){this.peerDataChannelListeners.forEach(te=>te(z,Z))}getConnectionStatus(z){if(this.isOutgoingConnection.get(z))return"connecting";const Z=this.getActiveConnection(z);return Z?Z.isReady()?"connected":"connecting":"disconnected"}getConnectionStatsInfo(z){return re(this,void 0,void 0,function*(){const Z=this.getActiveConnection(z);if(Z)return yield Z.getConnectionStatsInfo()})}disconnect(z){return re(this,void 0,void 0,function*(){const Z=this.getActiveConnection(z);Z&&(yield Z.close())})}getPeers(){return re(this,void 0,void 0,function*(){if(this.config.lanOnlyMode)throw new Error("getPeers method cannot be used in local-only mode.");const{signalingClient:z}=this.config,Z=yield(()=>re(this,void 0,void 0,function*(){try{return yield z.getPeers(new D.GetPeersRequest,yield this.getMetadata({}))}catch(ae){A.a.warn("Error when getting peers",{error:ae})}}))();if(!Z)return[];const te=Z.getPeersList();if(!te)return[];const ce=ae=>{var he,de;return(de=(he=ae.getPeerCreatedTimestamp())===null||he===void 0?void 0:he.getValue())!==null&&de!==void 0?de:0};return te.sort((ae,he)=>ce(he)-ce(ae)).map(ae=>J(ae))})}getPing(z){const Z=this.getActiveConnection(z);if(Z)return Z.getPing();A.a.warn("Attempted to get ping time from inactive peer.")}getLastMessageTimestamp(z){const Z=this.getActiveConnection(z);if(Z)return Z.getLastMessageTimestamp();A.a.warn("Attempted to get last message time from inactive peer.")}getSessionMetricsMessageCounts(z){const Z=this.getActiveConnection(z);if(Z)return Z.getSessionMetricsMessageCounts();A.a.warn("Attempted to get session metrics counts from inactive peer.")}isReady(){if(this.config.lanOnlyMode)return!0;const{localPeer:z,receiveSignalStream:Z,iceServers:te}=this;return!!(z&&Z&&te)}shutdown(){return re(this,void 0,void 0,function*(){A.a.info("Shutdown called on RTC client"),yield this.refreshInterval.stop(),this.receiveSignalStream&&this.receiveSignalStream.cancel();const z=this.connections;this.connections=[],yield this.closeConnections(z);const{localPeer:Z}=this;if(!Z||this.config.lanOnlyMode)return;const{signalingClient:te}=this.config;yield(()=>re(this,void 0,void 0,function*(){try{const ce=new D.DeletePeerRequest;ce.setPeerId(Z.getPeerId()),yield te.deletePeer(ce,yield this.getMetadata({}))}catch(ce){return void A.a.warn("Error deleting local peer",{error:ce})}}))()})}createPeer(){return re(this,void 0,void 0,function*(){if(this.config.lanOnlyMode)throw new Error("createPeer method cannot be used in local-only mode.");const{signalingClient:z}=this.config,Z=yield(()=>re(this,void 0,void 0,function*(){try{return yield z.createPeer(new D.CreatePeerRequest,yield this.getMetadata({}))}catch(ce){throw new Error(`Was not able to create peer: ${ce}`)}}))(),te=Z==null?void 0:Z.getPeer();if(!te)throw new Error("Response did not provide peer.");return this.localPeer=te})}createReceiveSignalStream(){return re(this,void 0,void 0,function*(){if(this.config.lanOnlyMode)throw new Error("createReceiveSignalStream method cannot be used in local-only mode.");const{signalingClient:z}=this.config,{localPeer:Z,iceServers:te}=this;if(!Z||!te)return;const{receiveSignalStream:ce}=this;ce&&ce.cancel();const ae=new D.ReceiveSignalStreamRequest;ae.setPeerId(Z.getPeerId());const he=yield(()=>re(this,void 0,void 0,function*(){try{return z.receiveSignalStream(ae,yield this.getMetadata({hasDeadline:!1}))}catch(de){throw new Error(`Unable to create receive signal stream: ${de}`)}}))();if(!he)throw new Error("Response did not provide stream.");return he.on("data",de=>re(this,void 0,void 0,function*(){var me,fe,ge,_e;const Se=de.getSignal(),Oe=(me=Se==null?void 0:Se.getSessionId())===null||me===void 0?void 0:me.getValue(),Pe=Se==null?void 0:Se.getSenderId(),Fe=Se==null?void 0:Se.getReceiverId(),De=(fe=Se==null?void 0:Se.getSessionCreatedTimestamp())===null||fe===void 0?void 0:fe.getValue();if(!(Se&&Oe&&Pe&&Fe&&De))return void A.a.warn("Received signal with missing information.");const Le=this.getActiveConnection(Pe);if(Le)if(Le.getSessionId()!==Oe){if(A.a.debug("Received signal: different session for a peer we're already connected to."),(Le.getSessionCreatedTimestamp()||0)>De)return;const xe=new ee(yield this.createRTCPeerConnection(te),{baseConfig:{isOffer:!1,isLan:!1,receive:(Ne,Ue)=>this.config.receive(Ne,Ue),onStreamsInfoUpdate:this.config.onStreamsInfoUpdate?(Ne,Ue)=>{var We,ze;return(ze=(We=this.config).onStreamsInfoUpdate)===null||ze===void 0?void 0:ze.call(We,Ne,Ue)}:void 0,track:this.config.lanOnlyMode?void 0:this.config.track,localPeerId:Z.getPeerId(),localUserId:(_e=Z.getUserId())===null||_e===void 0?void 0:_e.getValue(),remotePeerId:Pe},remoteConfig:{sessionId:Oe,sessionCreatedTimestamp:De}},Ne=>this.onCustomDataChannel(Pe,Ne));yield xe.handleSignal(Se),this.connections.push(xe)}else A.a.debug("Received signal: for an existing connection."),yield Le.handleSignal(Se);else{A.a.debug("Received signal: new connection.");const xe=new ee(yield this.createRTCPeerConnection(te),{baseConfig:{isOffer:!1,isLan:!1,receive:(Ne,Ue)=>this.config.receive(Ne,Ue),onStreamsInfoUpdate:this.config.onStreamsInfoUpdate?(Ne,Ue)=>{var We,ze;return(ze=(We=this.config).onStreamsInfoUpdate)===null||ze===void 0?void 0:ze.call(We,Ne,Ue)}:void 0,track:this.config.lanOnlyMode?void 0:this.config.track,localPeerId:Z.getPeerId(),localUserId:(ge=Z.getUserId())===null||ge===void 0?void 0:ge.getValue(),remotePeerId:Pe},remoteConfig:{sessionId:Oe,sessionCreatedTimestamp:De}},Ne=>this.onCustomDataChannel(Pe,Ne));yield xe.handleSignal(Se),this.connections.push(xe)}})),he.on("end",()=>{he.cancel(),this.receiveSignalStream=void 0}),he.on("error",de=>{switch(de.code){case L.StatusCode.CANCELLED:case L.StatusCode.UNAVAILABLE:case L.StatusCode.UNKNOWN:A.a.debug("Receive signal stream error",{error:de});break;case L.StatusCode.UNAUTHENTICATED:A.a.warn("Receive signal stream error",{error:de});break;default:A.a.error("Receive signal stream error",{error:de})}he.cancel(),this.receiveSignalStream=void 0}),this.receiveSignalStream=he})}createRTCPeerConnection(z,Z){var te;return re(this,void 0,void 0,function*(){const ce=Z==null?void 0:Z.rtcIceTransportPolicy,ae=(te=this.config.alternateRTCPeerConnection)!==null&&te!==void 0?te:window.RTCPeerConnection;if(!ae)throw new Error("RTCPeerConnection class not found. WebRTC must be enabled.");return new ae(Object.assign({iceServers:z,iceTransportPolicy:ce},Z))})}closeConnections(z){return re(this,void 0,void 0,function*(){const Z=yield F(z.map(te=>re(this,void 0,void 0,function*(){yield te.close()})));for(const te of Z)A.a.warn("Request to close session failed",{error:te})})}getActiveConnection(z){return this.getConnections().find(Z=>Z.getRemotePeerId()===z&&Z.isActive())}update(){var z;return re(this,void 0,void 0,function*(){if(this.localConnections=this.localConnections.filter(de=>de.isActive()),this.config.lanOnlyMode)return;const{signalingClient:Z}=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(de=>!de.isActive())),this.connections=this.connections.filter(de=>de.isActive());const{localPeer:te}=this,ce=this.connections.filter(de=>de.getSessionId).map(de=>M(de.getSessionId()));te.setSessionIdsList(ce);const ae=new D.RefreshPeerRequest;ae.setPeer(te);try{yield Z.refreshPeer(ae,yield this.getMetadata({}))}catch(de){de.code===L.StatusCode.NOT_FOUND?(A.a.warn("Peer expired, creating new peer",{peerId:te.getPeerId()}),yield this.reset()):A.a.warn("Error calling RefreshPeer",{error:de})}const he=yield this.getPeers();for(const de of this.connections)de.setRemoteDeviceId((z=he.find(me=>me.id===de.getRemotePeerId()))===null||z===void 0?void 0:z.deviceId)})}reset(){return re(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 re(this,void 0,void 0,function*(){if(this.config.lanOnlyMode)return;const{iceServersLastUpdate:z,iceServersTtl:Z}=this,te=new Date().getTime();if(!z||te-z>Z)try{const ce=(yield this.config.signalingClient.getIceServers(new D.GetIceServersRequest,yield this.getMetadata({}))).getIceServers();this.iceServers=JSON.parse(ce),this.iceServersLastUpdate=te}catch(ce){A.a.warn("Error in updateIceServers",{error:ce})}})}setupHandlers(z){const{peerConnection:Z}=z,te=z.getSessionCreatedTimestamp();Z.onconnectionstatechange=()=>re(this,void 0,void 0,function*(){const ce=Z.connectionState;if(te)switch(ce){case"connected":x.aggregate("rtc-connect-time",new Date().getTime()-te);break;case"failed":x.increment("rtc-connect-failed")}})}getMetadata(z){return re(this,void 0,void 0,function*(){if(this.config.lanOnlyMode)throw new Error("getMetadata method cannot be called in local-only mode");const{getToken:Z}=this.config,{grpcCallDeadline:te}=this,{hasDeadline:ce}=z,ae=ce===!1?void 0:new Date().getTime()+te;return{authorization:yield Z(),deadline:ae}})}}},,function(e,t,r){r.r(t),r.d(t,"LogClient",function(){return g});var n=r(26),i=function(s,o,l,u){return new(l||(l=Promise))(function(m,R){function y(w){try{c(u.next(w))}catch(E){R(E)}}function S(w){try{c(u.throw(w))}catch(E){R(E)}}function c(w){var E;w.done?m(w.value):(E=w.value,E instanceof l?E:new l(function(P){P(E)})).then(y,S)}c((u=u.apply(s,o||[])).next())})};class g extends n.a{log(o){return i(this,void 0,void 0,function*(){yield this.fetch("logs",{method:"POST",body:JSON.stringify({logs:o}),allowUnsafeRetries:!0})})}}}])})})(dist);let FORMANT_API_URL="https://api.formant.io";typeof window!="undefined"&&(FORMANT_API_URL=window.FORMANT_API_URL||FORMANT_API_URL);function delay(e){return new Promise(t=>setTimeout(t,e))}function defined(e,t){if(e!==void 0)return e;throw new Error(t||"Value is undefined")}class App{static sendAppMessage(t){window.parent.postMessage(t,"*")}static getCurrentModuleContext(){let t=new URLSearchParams("");return typeof window!="undefined"&&(t=new URLSearchParams(window.location.search)),t.get("module")}static isModule(){return this.getCurrentModuleContext()!==null}static goToTime(t){this.sendAppMessage({type:"go_to_time",time:t.getTime()})}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,r){const n=this.getCurrentModuleContext();if(!n)throw new Error("No module context");this.sendAppMessage({type:"set_module_data_time_range",module:n,before:t,after:r||0})}static refreshAuthToken(){const t=this.getCurrentModuleContext();if(!t)throw new Error("No module context");this.sendAppMessage({type:"refresh_auth_token",module:t})}static setupModuleMenus(t){const r=this.getCurrentModuleContext();if(!r)throw new Error("No module context");this.sendAppMessage({type:"setup_module_menus",module:r,menus:t})}static addMenuListener(t){window.addEventListener("message",r=>{const n=r.data;n.type==="module_menu_item_clicked"&&t(n.menu)})}static addAccessTokenRefreshListener(t){window.addEventListener("message",r=>{const n=r.data;n.type==="auth_token"&&t(n.token)})}static addModuleDataListener(t){window.addEventListener("message",r=>{const n=r.data;n.type==="module_data"&&t({streams:n.streams,time:n.time,queryRange:n.queryRange})})}}const Te=class{static async login(t,r){try{const n=await fetch(`${FORMANT_API_URL}/v1/admin/auth/login`,{method:"POST",body:JSON.stringify({email:t,password:r}),headers:{"Content-Type":"application/json"}}),i=await n.json();if(n.status!==200)throw new Error(i.message);return await Te.loginWithToken(i.authentication.accessToken,i.authentication.refreshToken),i.authentication}catch(n){return Te.waitingForAuth.forEach(i=>i(!1)),Te.waitingForAuth=[],Promise.reject(n)}}static async loginWithToken(t,r){const n=JSON.parse(atob(t.split(".")[1]));try{let i=n.sub;n["formant:claims"]&&n["formant:claims"].userId&&(i=n["formant:claims"].userId);const g=await fetch(`${FORMANT_API_URL}/v1/admin/users/${i}`,{method:"GET",headers:{"Content-Type":"application/json",Authorization:"Bearer "+t}}),s=await g.json();if(g.status!==200)throw new Error(s.message);Te.currentUser=s,Te.token=t,Te.waitingForAuth.forEach(o=>o(!0))}catch(i){console.error(i),Te.waitingForAuth.forEach(g=>g(!1))}Te.waitingForAuth=[],r&&(Te.refreshToken=r,setInterval(async()=>{if(Te.refreshToken){const g=await(await fetch(`${FORMANT_API_URL}/v1/admin/auth/refresh`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({refreshToken:Te.refreshToken})})).json();Te.token=g.authentication.accessToken}},1e3*60*60))}static isAuthenticated(){return Te.token!==void 0}static getCurrentUser(){return Te.currentUser}static async waitTilAuthenticated(){return Te.token!==void 0?!0:new Promise(t=>{Te.waitingForAuth.push(function(r){t(r)})})}static async listenForRefresh(){App.addAccessTokenRefreshListener(t=>{this.loginWithToken(t)}),setInterval(async()=>{App.refreshAuthToken()},1e3*60*60)}};let Authentication=Te;Me(Authentication,"token"),Me(Authentication,"refreshToken"),Me(Authentication,"currentUser"),Me(Authentication,"defaultDeviceId"),Me(Authentication,"waitingForAuth",[]);class DataChannel{constructor(t){Me(this,"ready",!1);Me(this,"listeners",[]);Me(this,"binaryListeners",[]);Me(this,"error");Me(this,"decoder",new TextDecoder);this.dataChannel=t,this.dataChannel.binaryType="arraybuffer",this.dataChannel.onopen=()=>{this.ready=!0},this.dataChannel.onclose=()=>{this.ready=!1},this.dataChannel.onerror=r=>{console.error(r),this.error="An error occurred in DataChannel"},this.dataChannel.onmessage=r=>{this.listeners.forEach(n=>{const i=new Uint8Array(r.data),g=this.decoder.decode(i);n(g)}),this.binaryListeners.forEach(n=>{n(new Uint8Array(r.data))})}}async waitTilReady(){return this.ready?!0:new Promise((r,n)=>{let i=window.setInterval(()=>{this.ready&&(window.clearInterval(i),r(!0)),this.error&&n(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 r=this.listeners.indexOf(t);if(r===-1)throw new Error("Could not find data channel listener to remove");if(this.error)throw new Error(this.error);this.listeners.splice(r,1)}addBinaryListener(t){this.binaryListeners.push(t)}removeBinaryListener(t){const r=this.binaryListeners.indexOf(t);if(r===-1)throw new Error("Could not find data channel listener to remove");if(this.error)throw new Error(this.error);this.binaryListeners.splice(r,1)}}class CaptureStream{constructor(t){Me(this,"token");this.captureSession=t}async ingestJSON(t){if(!this.token){const n=await(await fetch(`${FORMANT_API_URL}/v1/admin/capture-sessions/${this.captureSession.code}/authenticate`,{method:"POST"})).json();this.token=n.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,r){this.device=t,this.config=r}async synchronize(){this.device.addRealtimeListener((t,r)=>{console.log(r)}),this.device.startListeningToRealtimeDataStream(this.config.currentJointStateStream)}}class RequestDataChannel{constructor(t,r,n){Me(this,"channel");Me(this,"requestIdToResponseMap",new Map);this.device=t,this.channel_name=r,this.timeout=n}}class BinaryRequestDataChannel extends RequestDataChannel{constructor(){super(...arguments);Me(this,"RESPONSE_SUCCESS_BYTE",0);Me(this,"decoder",new TextDecoder)}generateBinaryId(){const t=new Uint8Array(16);for(let r=0;r<t.length;r++)t[r]=Math.floor(Math.random()*256);return t}async initialize(){this.channel=await this.device.createCustomDataChannel(this.channel_name),this.channel.addBinaryListener(t=>{const n=t.slice(0,16).toString();if(n.length===0)throw new Error("Invalid response");const i=t.slice(16);if(i.length===0)throw new Error("Invalid response");this.requestIdToResponseMap.has(n)&&this.requestIdToResponseMap.set(n,i)})}async request(t){if(this.channel||await this.initialize(),!this.channel)throw new Error("Failed to create channel");const{channel:r,requestIdToResponseMap:n,timeout:i}=this;await r.waitTilReady();const g=this.generateBinaryId(),s=g.toString();n.set(s,!0),r.sendBinary(new Uint8Array([...g,...t]));const o=new Date().getTime();for(;new Date().getTime()<o+i;)if(await delay(50),n.has(s)){const l=n.get(s);if(l!==!0){n.delete(s);const u=l[0]===this.RESPONSE_SUCCESS_BYTE,m=l.slice(1);if(u)return m;throw{name:"AdapterError",message:this.decoder.decode(m)}}}throw n.delete(s),{name:"TimeoutError",message:`Request timed out after ${i/1e3} seconds`}}}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 r=JSON.parse(t),{id:n,data:i,error:g}=r;if(!n)throw new Error("Invalid response");if(!i&&!g)throw new Error("Invalid response");this.requestIdToResponseMap.has(n)&&this.requestIdToResponseMap.set(n,r)})}async request(t){if(this.channel||await this.initialize(),!this.channel)throw new Error("Failed to create channel");const{channel:r,requestIdToResponseMap:n,timeout:i}=this;await r.waitTilReady();const g=this.generateTextId();n.set(g,!0),r.send(JSON.stringify({id:g,data:t}));const s=new Date().getTime();for(;new Date().getTime()<s+i;)if(await delay(50),n.has(g)){const o=n.get(g);if(o!==!0){n.delete(g);const{data:l,error:u}=o;if(l)return l;if(u)throw{name:"AdapterError",message:u}}}throw n.delete(g),{name:"TimeoutError",message:`Request timed out after ${i/1e3} seconds`}}}class Device{constructor(t,r,n){Me(this,"rtcClient");Me(this,"realtimeListeners",[]);Me(this,"handleMessage",(t,r)=>{this.realtimeListeners.forEach(n=>n(t,r))});this.id=t,this.name=r,this.organizationId=n}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 r=await t.json();if(!r.state.reportedConfiguration)throw new Error("Device has no configuration, has it ever been turned on?");const n=r.state.reportedConfiguration.version;return t=await fetch(`${FORMANT_API_URL}/v1/admin/devices/${this.id}/configurations/${n}`,{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({fileId:[t]}),headers:{"Content-Type":"application/json",Authorization:"Bearer "+Authentication.token}})).json()).fileUrls}async startRealtimeConnection(){if(this.rtcClient)throw new Error(`Already created realtime connection to device ${this.id}`);{const t=new dist.exports.RtcClient({signalingClient:new dist.exports.SignalingPromiseClient(FORMANT_API_URL,null,null),getToken:async()=>defined(Authentication.token,"Realtime when user isn't authorized"),receive:this.handleMessage});for(;!t.isReady();)await delay(100);const n=(await t.getPeers()).find(g=>g.deviceId===this.id);if(!n)throw new Error("Cannot find peer, is the robot offline?");const i=n.id;for(await t.connect(i);t.getConnectionStatus(i)!=="connected";)await delay(100);this.rtcClient=t}}addRealtimeListener(t){this.realtimeListeners.push(t)}removeRealtimeListener(t){const r=this.realtimeListeners.indexOf(t);if(r===-1)throw new Error("Could not find realtime listener to remove");this.realtimeListeners.splice(r,1)}async getRealtimeVideoStreams(){var n,i,g;const t=await this.getConfiguration(),r=[];for(const s of(n=t.teleop.hardwareStreams)!=null?n:[])s.rtcStreamType==="h264-video-frame"&&r.push({name:s.name});for(const s of(i=t.teleop.rosStreams)!=null?i:[])s.topicType=="formant/H264VideoFrame"&&r.push({name:s.topicName});for(const s of(g=t.teleop.customStreams)!=null?g:[])s.rtcStreamType==="h264-video-frame"&&r.push({name:s.name});return r}async getRealtimeManipulators(){var n;const t=await this.getConfiguration(),r=[];for(const i of(n=t.teleop.rosStreams)!=null?n:[])i.topicType=="sensor_msgs/JointState"&&r.push(new Manipulator(this,{currentJointStateStream:{name:i.topicName},plannedJointStateStream:i.plannedTopic?{name:i.plannedTopic}:void 0,planValidStream:i.planValidTopic?{name:i.planValidTopic}:void 0,endEffectorStream:i.endEffectorTopic?{name:i.endEffectorTopic}:void 0,endEffectorLinkName:i.endEffectorLinkName,baseReferenceFrame:i.baseReferenceFrame,localFrame:i.localFrame}));return r}async startListeningToRealtimeVideo(t){const r=defined(this.rtcClient,"Realtime connection has not been started"),n=await this.getRemotePeer();r.controlRemoteStream(defined(n).id,{streamName:t.name,enable:!0,pipeline:"rtc"})}async stopListeningToRealtimeVideo(t){const r=defined(this.rtcClient,"Realtime connection has not been started"),n=await this.getRemotePeer();r.controlRemoteStream(defined(n).id,{streamName:t.name,enable:!1,pipeline:"rtc"})}async startListeningToRealtimeDataStream(t){const r=defined(this.rtcClient,"Realtime connection has not been started"),n=await this.getRemotePeer();r.controlRemoteStream(defined(n).id,{streamName:t.name,enable:!0,pipeline:"rtc"})}async stopListeningToRealtimeDataStream(t){const r=defined(this.rtcClient,"Realtime connection has not been started"),n=await this.getRemotePeer();r.controlRemoteStream(defined(n).id,{streamName:t.name,enable:!1,pipeline:"rtc"})}async enableRealtimeTelemetryPriorityIngestion(t){const r=defined(this.rtcClient,"Realtime connection has not been started"),n=await this.getRemotePeer();r.controlRemoteStream(defined(n).id,{streamName:t,enablePriorityUpload:!0,pipeline:"telemetry"})}async disableRealtimeTelemetryPriorityIngestion(t){const r=defined(this.rtcClient,"Realtime connection has not been started"),n=await this.getRemotePeer();r.controlRemoteStream(defined(n).id,{streamName:t,enablePriorityUpload:!1,pipeline:"telemetry"})}async getRemotePeer(){const r=(await defined(this.rtcClient,"Realtime connection has not been started").getPeers()).find(n=>n.deviceId===this.id);return defined(r,"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 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(n=>({name:n.name,id:n.id,command:n.command,description:n.description,parameterEnabled:n.parameterEnabled,parameterValue:n.parameterValue,parameterMeta:n.parameterMeta}))}async sendCommand(t,r,n,i){var R;const s=(await this.getAvailableCommands()).find(y=>y.name===t);if(!s)throw new Error(`Could not find command with name "${t}"`);let o;if(r===void 0)if(s.parameterEnabled&&s.parameterValue)o=s.parameterValue;else throw new Error("Command has no default parameter value, you must provide one");else o=r;let l={value:o,scrubberTime:(n||new Date).toISOString(),meta:st(st({},s.parameterMeta),i)};return(await(await fetch(`${FORMANT_API_URL}/v1/admin/commands`,{method:"POST",body:JSON.stringify({commandTemplateId:s.id,organizationId:this.organizationId,deviceId:this.id,command:s.command,parameter:l,userId:(R=Authentication.currentUser)==null?void 0:R.id}),headers:{"Content-Type":"application/json",Authorization:"Bearer "+Authentication.token}})).json()).fileUrls}async createCustomDataChannel(t,r){const n=defined(this.rtcClient,"Realtime connection has not been started"),i=await this.getRemotePeer();return new Promise(s=>{n.createCustomDataChannel(defined(i).id,t,st({ordered:!0},r),!1,(o,l)=>{const u=new DataChannel(l);s(u)})})}createCustomRequestDataChannel(t,r=3e3){return new TextRequestDataChannel(this,t,r)}createCustomBinaryRequestDataChannel(t,r=3e3){return new BinaryRequestDataChannel(this,t,r)}async createCaptureStream(t){const n=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(n)}async getTelemetry(t,r,n,i){return await Fleet.getTelemetry(this.id,t,r,n,i)}async getTelemetryStreams(){var o,l;const t=await this.getConfiguration(),r=await fetch(`${FORMANT_API_URL}/v1/queries/metadata/stream-names`,{method:"POST",body:JSON.stringify({deviceIds:[this.id]}),headers:{"Content-Type":"application/json",Authorization:"Bearer "+Authentication.token}}),n=[],i=[];return(l=(o=t.telemetry)==null?void 0:o.streams)==null||l.forEach(u=>{u.disabled!==!0&&n.push(u.name),u.onDemand===!0&&i.push(u.name)}),console.log(i),(await r.json()).items.filter(u=>!n.includes(u)).map(u=>({name:u,onDemand:i.includes(u)}))}}const Ae=class{static async setDefaultDevice(t){Ae.defaultDeviceId=t}static async getCurrentDevice(){if(!Authentication.token)throw new Error("Not authenticated");if(!Ae.defaultDeviceId)throw new Error("No known default device");const r=await(await fetch(`${FORMANT_API_URL}/v1/admin/devices/${Ae.defaultDeviceId}`,{method:"GET",headers:{"Content-Type":"application/json",Authorization:"Bearer "+Authentication.token}})).json(),n=r.name,i=new Device(Ae.defaultDeviceId,n,r.organizationId);return Ae.knownContext.push(new WeakRef(i)),i}static async getDevice(t){if(!Authentication.token)throw new Error("Not authenticated");const n=await(await fetch(`${FORMANT_API_URL}/v1/admin/devices/${t}`,{method:"GET",headers:{"Content-Type":"application/json",Authorization:"Bearer "+Authentication.token}})).json(),i=n.name,g=new Device(t,i,n.organizationId);return Ae.knownContext.push(new WeakRef(g)),g}static async getDevices(){if(!Authentication.token)throw new Error("Not authenticated");const r=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 r.items,r.items.map(n=>new Device(n.id,n.name,n.organizationId))}static async getOnlineDevices(){if(!Authentication.token)throw new Error("Not authenticated");const n=(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 Ae.getDevices()).filter(g=>n.includes(g.id))}static async getRealtimeDevices(){if(!Authentication.token)throw new Error("Not authenticated");const n=(await(await fetch(`${FORMANT_API_URL}/v1/signaling/peers`,{method:"GET",headers:{"Content-Type":"application/json",Authorization:"Bearer "+Authentication.token}})).json()).items.map(g=>g.deviceId);return(await Ae.getDevices()).filter(g=>n.includes(g.id))}static async getLatestTelemetry(t){let r=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:r}),headers:{"Content-Type":"application/json",Authorization:"Bearer "+Authentication.token}})).json()).items}static async getTelemetry(t,r,n,i,g){let s=t;Array.isArray(t)||(s=[t]);let o=r;return Array.isArray(r)||(o=[r]),(await(await fetch(`${FORMANT_API_URL}/v1/queries/queries`,{method:"POST",body:JSON.stringify({deviceIds:s,end:i.toISOString(),names:o,start:n.toISOString(),tags:g}),headers:{"Content-Type":"application/json",Authorization:"Bearer "+Authentication.token}})).json()).items}};let Fleet=Ae;Me(Fleet,"defaultDeviceId"),Me(Fleet,"knownContext",[]);let urlParams=new URLSearchParams("");typeof window!="undefined"&&(urlParams=new URLSearchParams(window.location.search));const urlDevice=urlParams.get("device");urlDevice&&Fleet.setDefaultDevice(urlDevice);const urlAuth=urlParams.get("auth");urlAuth&&Authentication.loginWithToken(urlAuth);const moduleName=urlParams.get("module");moduleName&&Authentication.listenForRefresh(),exports.App=App,exports.Authentication=Authentication,exports.BinaryRequestDataChannel=BinaryRequestDataChannel,exports.CaptureStream=CaptureStream,exports.DataChannel=DataChannel,exports.Device=Device,exports.Fleet=Fleet,exports.Manipulator=Manipulator,exports.TextRequestDataChannel=TextRequestDataChannel,Object.defineProperty(exports,"__esModule",{value:!0}),exports[Symbol.toStringTag]="Module"});
|
|
44
|
+
`),Error.captureStackTrace(this,n)}}e.exports=i=>{if(i.length>2)throw new n(i);function g(o={}){this.options=o}function s(o){return new g(o)}return g.prototype.transform=i,s.Format=g,s}},function(e,t,r){function n(s,o){if(!(s instanceof o))throw new TypeError("Cannot call a class as a function")}function i(s,o){for(var l=0;l<o.length;l++){var u=o[l];u.enumerable=u.enumerable||!1,u.configurable=!0,"value"in u&&(u.writable=!0),Object.defineProperty(s,u.key,u)}}var g=r(85);e.exports=function(){function s(){var u=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};n(this,s),this.loggers=new Map,this.options=u}var o,l;return o=s,(l=[{key:"add",value:function(u,m){var R=this;if(!this.loggers.has(u)){var y=(m=Object.assign({},m||this.options)).transports||this.options.transports;m.transports=y?y.slice():[];var S=g(m);S.on("close",function(){return R._delete(u)}),this.loggers.set(u,S)}return this.loggers.get(u)}},{key:"get",value:function(u,m){return this.add(u,m)}},{key:"has",value:function(u){return!!this.loggers.has(u)}},{key:"close",value:function(u){var m=this;if(u)return this._removeLogger(u);this.loggers.forEach(function(R,y){return m._removeLogger(y)})}},{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,l),s}()},function(e,t,r){(function(n){const i=r(49),g=/^([A-Za-z0-9+/]{4})*([A-Za-z0-9+/]{4}|[A-Za-z0-9+/]{3}=|[A-Za-z0-9+/]{2}==)$/;e.exports=function(s,o,l){let u,m,R=!1,y=!1;function S(E,P){let F=`"${o}" ${P}`;throw E&&(F=`${F}, but is set to "${E}"`),m&&(F=`${F}. An example of a valid value would be: ${m}`),new i(F)}function c(E){return function(){let P=s[o];if(P===void 0)if(u===void 0&&y)S(void 0,"is a required variable, but it was not set");else{if(u===void 0)return;P=u}y&&P.trim().length===0&&S(void 0,"is a required variable, but its value was empty"),R&&(P.match(g)||S(P,"should be a valid base64 string if using convertFromBase64"),P=n.from(P,"base64").toString());const F=[P].concat(Array.prototype.slice.call(arguments));try{return E.apply(E,F)}catch(M){S(P,M.message)}}}const w={asArray:c(r(211)),asBoolStrict:c(r(212)),asBool:c(r(213)),asPortNumber:c(r(214)),asEnum:c(r(215)),asFloatNegative:c(r(216)),asFloatPositive:c(r(217)),asFloat:c(r(51)),asIntNegative:c(r(218)),asIntPositive:c(r(91)),asInt:c(r(50)),asJsonArray:c(r(219)),asJsonObject:c(r(220)),asJson:c(r(52)),asString:c(r(35)),asUrlObject:c(r(92)),asUrlString:c(r(221)),convertFromBase64:function(){return R=!0,w},default:function(E){if(typeof E=="number")u=E.toString();else if(Array.isArray(E)||typeof E=="object"&&E!==null)u=JSON.stringify(E);else{if(typeof E!="string")throw new i("values passed to default() must be of Number, String, Array, or Object type");u=E}return w},required:function(E){return y=E===void 0||E,w},example:function(E){return m=E,w}};return Object.entries(l).forEach(([E,P])=>{w[E]=c(P)}),w}}).call(this,r(4).Buffer)},function(e,t,r){const n=r(35);e.exports=function(i,g){return g=g||",",i.length?n(i).split(g).filter(Boolean):[]}},function(e,t,r){e.exports=function(n){const i=n.toLowerCase();if(i!=="false"&&i!=="true")throw new Error('should be either "true", "false", "TRUE", or "FALSE"');return i!=="false"}},function(e,t,r){e.exports=function(n){const i=n.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,r){const n=r(91);e.exports=function(i){var g=n(i);if(g>65535)throw new Error("cannot assign a port number greater than 65535");return g}},function(e,t,r){const n=r(35);e.exports=function(i,g){const s=n(i);if(g.indexOf(s)<0)throw new Error(`should be one of [${g.join(", ")}]`);return s}},function(e,t,r){const n=r(51);e.exports=function(i){const g=n(i);if(g>0)throw new Error("should be a negative float");return g}},function(e,t,r){const n=r(51);e.exports=function(i){const g=n(i);if(g<0)throw new Error("should be a positive float");return g}},function(e,t,r){const n=r(50);e.exports=function(i){const g=n(i);if(g>0)throw new Error("should be a negative integer");return g}},function(e,t,r){const n=r(52);e.exports=function(i){var g=n(i);if(!Array.isArray(g))throw new Error("should be a parseable JSON Array");return g}},function(e,t,r){const n=r(52);e.exports=function(i){var g=n(i);if(Array.isArray(g))throw new Error("should be a parseable JSON Object");return g}},function(e,t,r){const n=r(92);e.exports=function(i){return n(i).toString()}},function(e,t,r){function n(o){var l=this;if(l instanceof n||(l=new n),l.tail=null,l.head=null,l.length=0,o&&typeof o.forEach=="function")o.forEach(function(R){l.push(R)});else if(arguments.length>0)for(var u=0,m=arguments.length;u<m;u++)l.push(arguments[u]);return l}function i(o,l){o.tail=new s(l,o.tail,null,o),o.head||(o.head=o.tail),o.length++}function g(o,l){o.head=new s(l,null,o.head,o),o.tail||(o.tail=o.head),o.length++}function s(o,l,u,m){if(!(this instanceof s))return new s(o,l,u,m);this.list=m,this.value=o,l?(l.next=this,this.prev=l):this.prev=null,u?(u.prev=this,this.next=u):this.next=null}e.exports=n,n.Node=s,n.create=n,n.prototype.removeNode=function(o){if(o.list!==this)throw new Error("removing node which does not belong to this list");var l=o.next,u=o.prev;l&&(l.prev=u),u&&(u.next=l),o===this.head&&(this.head=l),o===this.tail&&(this.tail=u),o.list.length--,o.next=null,o.prev=null,o.list=null},n.prototype.unshiftNode=function(o){if(o!==this.head){o.list&&o.list.removeNode(o);var l=this.head;o.list=this,o.next=l,l&&(l.prev=o),this.head=o,this.tail||(this.tail=o),this.length++}},n.prototype.pushNode=function(o){if(o!==this.tail){o.list&&o.list.removeNode(o);var l=this.tail;o.list=this,o.prev=l,l&&(l.next=o),this.tail=o,this.head||(this.head=o),this.length++}},n.prototype.push=function(){for(var o=0,l=arguments.length;o<l;o++)i(this,arguments[o]);return this.length},n.prototype.unshift=function(){for(var o=0,l=arguments.length;o<l;o++)g(this,arguments[o]);return this.length},n.prototype.pop=function(){if(this.tail){var o=this.tail.value;return this.tail=this.tail.prev,this.tail?this.tail.next=null:this.head=null,this.length--,o}},n.prototype.shift=function(){if(this.head){var o=this.head.value;return this.head=this.head.next,this.head?this.head.prev=null:this.tail=null,this.length--,o}},n.prototype.forEach=function(o,l){l=l||this;for(var u=this.head,m=0;u!==null;m++)o.call(l,u.value,m,this),u=u.next},n.prototype.forEachReverse=function(o,l){l=l||this;for(var u=this.tail,m=this.length-1;u!==null;m--)o.call(l,u.value,m,this),u=u.prev},n.prototype.get=function(o){for(var l=0,u=this.head;u!==null&&l<o;l++)u=u.next;if(l===o&&u!==null)return u.value},n.prototype.getReverse=function(o){for(var l=0,u=this.tail;u!==null&&l<o;l++)u=u.prev;if(l===o&&u!==null)return u.value},n.prototype.map=function(o,l){l=l||this;for(var u=new n,m=this.head;m!==null;)u.push(o.call(l,m.value,this)),m=m.next;return u},n.prototype.mapReverse=function(o,l){l=l||this;for(var u=new n,m=this.tail;m!==null;)u.push(o.call(l,m.value,this)),m=m.prev;return u},n.prototype.reduce=function(o,l){var u,m=this.head;if(arguments.length>1)u=l;else{if(!this.head)throw new TypeError("Reduce of empty list with no initial value");m=this.head.next,u=this.head.value}for(var R=0;m!==null;R++)u=o(u,m.value,R),m=m.next;return u},n.prototype.reduceReverse=function(o,l){var u,m=this.tail;if(arguments.length>1)u=l;else{if(!this.tail)throw new TypeError("Reduce of empty list with no initial value");m=this.tail.prev,u=this.tail.value}for(var R=this.length-1;m!==null;R--)u=o(u,m.value,R),m=m.prev;return u},n.prototype.toArray=function(){for(var o=new Array(this.length),l=0,u=this.head;u!==null;l++)o[l]=u.value,u=u.next;return o},n.prototype.toArrayReverse=function(){for(var o=new Array(this.length),l=0,u=this.tail;u!==null;l++)o[l]=u.value,u=u.prev;return o},n.prototype.slice=function(o,l){(l=l||this.length)<0&&(l+=this.length),(o=o||0)<0&&(o+=this.length);var u=new n;if(l<o||l<0)return u;o<0&&(o=0),l>this.length&&(l=this.length);for(var m=0,R=this.head;R!==null&&m<o;m++)R=R.next;for(;R!==null&&m<l;m++,R=R.next)u.push(R.value);return u},n.prototype.sliceReverse=function(o,l){(l=l||this.length)<0&&(l+=this.length),(o=o||0)<0&&(o+=this.length);var u=new n;if(l<o||l<0)return u;o<0&&(o=0),l>this.length&&(l=this.length);for(var m=this.length,R=this.tail;R!==null&&m>l;m--)R=R.prev;for(;R!==null&&m>o;m--,R=R.prev)u.push(R.value);return u},n.prototype.reverse=function(){for(var o=this.head,l=this.tail,u=o;u!==null;u=u.prev){var m=u.prev;u.prev=u.next,u.next=m}return this.head=l,this.tail=o,this};try{r(223)(n)}catch{}},function(e,t,r){e.exports=function(n){n.prototype[Symbol.iterator]=function*(){for(let i=this.head;i;i=i.next)yield i.value}}},function(e,t,r){(function(n){(function(){var i,g,s,o,l,u;typeof performance!="undefined"&&performance!==null&&performance.now?e.exports=function(){return performance.now()}:n!=null&&n.hrtime?(e.exports=function(){return(i()-l)/1e6},g=n.hrtime,o=(i=function(){var m;return 1e9*(m=g())[0]+m[1]})(),u=1e9*n.uptime(),l=o-u):Date.now?(e.exports=function(){return Date.now()-s},s=Date.now()):(e.exports=function(){return new Date().getTime()-s},s=new Date().getTime())}).call(this)}).call(this,r(2))},function(e,t,r){var n,i,g=r(96),s=r(97),o=0,l=0;e.exports=function(u,m,R){var y=m&&R||0,S=m||[],c=(u=u||{}).node||n,w=u.clockseq!==void 0?u.clockseq:i;if(c==null||w==null){var E=g();c==null&&(c=n=[1|E[0],E[1],E[2],E[3],E[4],E[5]]),w==null&&(w=i=16383&(E[6]<<8|E[7]))}var P=u.msecs!==void 0?u.msecs:new Date().getTime(),F=u.nsecs!==void 0?u.nsecs:l+1,M=P-o+(F-l)/1e4;if(M<0&&u.clockseq===void 0&&(w=w+1&16383),(M<0||P>o)&&u.nsecs===void 0&&(F=0),F>=1e4)throw new Error("uuid.v1(): Can't create more than 10M uuids/sec");o=P,l=F,i=w;var A=(1e4*(268435455&(P+=122192928e5))+F)%4294967296;S[y++]=A>>>24&255,S[y++]=A>>>16&255,S[y++]=A>>>8&255,S[y++]=255&A;var p=P/4294967296*1e4&268435455;S[y++]=p>>>8&255,S[y++]=255&p,S[y++]=p>>>24&15|16,S[y++]=p>>>16&255,S[y++]=w>>>8|128,S[y++]=255&w;for(var N=0;N<6;++N)S[y+N]=c[N];return m||s(S)}},function(e,t,r){var n=r(96),i=r(97);e.exports=function(g,s,o){var l=s&&o||0;typeof g=="string"&&(s=g==="binary"?new Array(16):null,g=null);var u=(g=g||{}).random||(g.rng||n)();if(u[6]=15&u[6]|64,u[8]=63&u[8]|128,s)for(var m=0;m<16;++m)s[l+m]=u[m];return s||i(u)}},function(e,t,r){(function(n){(function(i){function g(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 s(o,l){if(l=l===void 0?{fatal:!1}:l,(o=o===void 0?"utf-8":o)!=="utf-8")throw new RangeError("Failed to construct 'TextDecoder': The encoding label provided ('"+o+"') is invalid.");if(l.fatal)throw Error("Failed to construct 'TextDecoder': the 'fatal' option is unsupported.")}if(i.TextEncoder&&i.TextDecoder)return!1;Object.defineProperty(g.prototype,"encoding",{value:"utf-8"}),g.prototype.encode=function(o,l){if((l=l===void 0?{stream:!1}:l).stream)throw Error("Failed to encode: the 'stream' option is unsupported.");l=0;for(var u=o.length,m=0,R=Math.max(32,u+(u>>1)+7),y=new Uint8Array(R>>3<<3);l<u;){var S=o.charCodeAt(l++);if(55296<=S&&56319>=S){if(l<u){var c=o.charCodeAt(l);(64512&c)==56320&&(++l,S=((1023&S)<<10)+(1023&c)+65536)}if(55296<=S&&56319>=S)continue}if(m+4>y.length&&(R+=8,R=(R*=1+l/o.length*2)>>3<<3,(c=new Uint8Array(R)).set(y),y=c),(4294967168&S)==0)y[m++]=S;else{if((4294965248&S)==0)y[m++]=S>>6&31|192;else if((4294901760&S)==0)y[m++]=S>>12&15|224,y[m++]=S>>6&63|128;else{if((4292870144&S)!=0)continue;y[m++]=S>>18&7|240,y[m++]=S>>12&63|128,y[m++]=S>>6&63|128}y[m++]=63&S|128}}return y.slice(0,m)},Object.defineProperty(s.prototype,"encoding",{value:"utf-8"}),Object.defineProperty(s.prototype,"fatal",{value:!1}),Object.defineProperty(s.prototype,"ignoreBOM",{value:!1}),s.prototype.decode=function(o,l){if((l=l===void 0?{stream:!1}:l).stream)throw Error("Failed to decode: the 'stream' option is unsupported.");l=0;for(var u=(o=new Uint8Array(o)).length,m=[];l<u;){var R=o[l++];if(R===0)break;if((128&R)==0)m.push(R);else if((224&R)==192){var y=63&o[l++];m.push((31&R)<<6|y)}else if((240&R)==224){y=63&o[l++];var S=63&o[l++];m.push((31&R)<<12|y<<6|S)}else(248&R)==240&&(65535<(R=(7&R)<<18|(y=63&o[l++])<<12|(S=63&o[l++])<<6|63&o[l++])&&(R-=65536,m.push(R>>>10&1023|55296),R=56320|1023&R),m.push(R))}return String.fromCharCode.apply(null,m)},i.TextEncoder=g,i.TextDecoder=s})(typeof window!="undefined"?window:n!==void 0?n:this)}).call(this,r(5))},function(e,t,r){r.r(t),r.d(t,"AuthClient",function(){return g}),r.d(t,"RtcSignalingClient",function(){return o}),r.d(t,"Credentials",function(){return w}),r.d(t,"SignalingPromiseClient",function(){return E.SignalingPromiseClient}),r.d(t,"IRtcClientConfiguration",function(){}),r.d(t,"IRtcConnectConfiguration",function(){}),r.d(t,"IRtcConnectionStatsInfo",function(){}),r.d(t,"IRtcSendConfiguration",function(){}),r.d(t,"IRtcSessionMetricsMessageCounts",function(){}),r.d(t,"IRtcStreamMessage",function(){}),r.d(t,"IStreamControl",function(){}),r.d(t,"RtcClient",function(){return se});var n=r(26),i=function(oe,z,Z,te){return new(Z||(Z=Promise))(function(ce,ae){function he(fe){try{me(te.next(fe))}catch(ge){ae(ge)}}function de(fe){try{me(te.throw(fe))}catch(ge){ae(ge)}}function me(fe){var ge;fe.done?ce(fe.value):(ge=fe.value,ge instanceof Z?ge:new Z(function(_e){_e(ge)})).then(he,de)}me((te=te.apply(oe,z||[])).next())})};class g extends n.a{adminSignup(z,Z){return i(this,void 0,void 0,function*(){return yield this.fetch("auth/admin-signup",{token:Z,method:"POST",body:JSON.stringify(z)})})}login(z){return i(this,void 0,void 0,function*(){return yield this.fetch("auth/login",{method:"POST",body:JSON.stringify(z),allowUnsafeRetries:!0})})}loginWithGoogleToken(z){return i(this,void 0,void 0,function*(){return yield this.fetch("auth/login-google",{method:"POST",body:JSON.stringify(z),allowUnsafeRetries:!0})})}refresh(z,Z){return i(this,void 0,void 0,function*(){return yield this.fetch("auth/refresh",{method:"POST",body:JSON.stringify({refreshToken:z,tokenExpirationSeconds:Z}),allowUnsafeRetries:!0})})}respondToNewPasswordRequiredChallenge(z){return i(this,void 0,void 0,function*(){return yield this.fetch("auth/respond-to-new-password-required-challenge",{method:"POST",body:JSON.stringify(z)})})}forgotPassword(z){return i(this,void 0,void 0,function*(){return yield this.fetch("auth/forgot-password",{method:"POST",body:JSON.stringify({email:z})})})}confirmForgotPassword(z){return i(this,void 0,void 0,function*(){return yield this.fetch("auth/confirm-forgot-password",{method:"POST",body:JSON.stringify(z)})})}resendInvitation(z){return i(this,void 0,void 0,function*(){return yield this.fetch("auth/resend-invitation",{method:"POST",body:JSON.stringify({email:z})})})}changePassword({token:z,refreshToken:Z,currentPassword:te,newPassword:ce}){return i(this,void 0,void 0,function*(){return yield this.fetch("auth/change-password",{token:z,method:"POST",body:JSON.stringify({refreshToken:Z,currentPassword:te,newPassword:ce})})})}getDeviceCredentials(z){return i(this,void 0,void 0,function*(){return yield this.fetch("auth/device-credentials",{token:z,method:"POST",allowUnsafeRetries:!0})})}impersonate(z,Z){return i(this,void 0,void 0,function*(){return yield this.fetch("auth/impersonate",{token:z,method:"POST",allowUnsafeRetries:!0,body:JSON.stringify({userId:Z})})})}createServiceAccount(z,Z,te){return i(this,void 0,void 0,function*(){return yield this.fetch("auth/service-account",{token:z,method:"POST",allowUnsafeRetries:!0,body:JSON.stringify({name:Z,role:te})})})}sendPlanUpgradeRequest(z){return i(this,void 0,void 0,function*(){return yield this.fetch("auth/upgrade-plan",{token:z,method:"POST",allowUnsafeRetries:!0})})}}var s=function(oe,z,Z,te){return new(Z||(Z=Promise))(function(ce,ae){function he(fe){try{me(te.next(fe))}catch(ge){ae(ge)}}function de(fe){try{me(te.throw(fe))}catch(ge){ae(ge)}}function me(fe){var ge;fe.done?ce(fe.value):(ge=fe.value,ge instanceof Z?ge:new Z(function(_e){_e(ge)})).then(he,de)}me((te=te.apply(oe,z||[])).next())})};class o extends n.a{createPeer(z,Z){return s(this,void 0,void 0,function*(){return yield this.fetch("peers",{token:z,method:"POST",body:JSON.stringify(Z)})})}getPeers(z){return s(this,void 0,void 0,function*(){return(yield this.fetch("peers",{token:z})).items})}refreshPeer(z,Z){return s(this,void 0,void 0,function*(){yield this.fetch(`peers/${Z}/refresh`,{token:z,method:"POST",allowUnsafeRetries:!0})})}createSession(z,Z){return s(this,void 0,void 0,function*(){return yield this.fetch("sessions",{token:z,method:"POST",body:JSON.stringify(Z)})})}refreshSession(z,Z){return s(this,void 0,void 0,function*(){yield this.fetch(`sessions/${Z}/refresh`,{token:z,method:"POST",allowUnsafeRetries:!0})})}deleteSession(z,Z){return s(this,void 0,void 0,function*(){yield this.fetch(`sessions/${Z}`,{token:z,method:"DELETE",allowUnsafeRetries:!0})})}getSessions(z){return s(this,void 0,void 0,function*(){return(yield this.fetch("sessions",{token:z})).items})}getIceServers(z){return s(this,void 0,void 0,function*(){return(yield this.fetch("ice-servers",{token:z})).items})}addSignals(z,Z,te){return s(this,void 0,void 0,function*(){yield this.fetch(`sessions/${Z}/add-signals`,{token:z,method:"POST",body:JSON.stringify(te)})})}takeSignals(z,Z){return s(this,void 0,void 0,function*(){return(yield this.fetch(`sessions/${Z}/take-signals`,{token:z,method:"POST"})).items})}}var l=r(1),u=r(10),m=r(21),R=r(102),y=function(oe,z,Z,te){return new(Z||(Z=Promise))(function(ce,ae){function he(fe){try{me(te.next(fe))}catch(ge){ae(ge)}}function de(fe){try{me(te.throw(fe))}catch(ge){ae(ge)}}function me(fe){var ge;fe.done?ce(fe.value):(ge=fe.value,ge instanceof Z?ge:new Z(function(_e){_e(ge)})).then(he,de)}me((te=te.apply(oe,z||[])).next())})};class S extends class{constructor(z={}){this.cache=new R(z),this.stringify=z.fastStringify?JSON.stringify:m}set(z,Z,te){if(!this.cache.set(this.stringify(z),Z,te))throw Error(`Value too large (${this.cache.lengthCalculator(Z)} > ${this.cache.max})`)}get(z){return this.cache.get(this.stringify(z))}del(z){this.cache.del(this.stringify(z))}length(){return this.cache.length}reset(){this.cache.reset()}prune(){return this.cache.prune()}forEach(z){return this.cache.forEach(z)}}{constructor(z={}){if(super(z),this.expireRejectedPromiseValues=z.expireRejectedPromiseValues===void 0||z.expireRejectedPromiseValues,this.rejectedPromiseValueTtl=z.rejectedPromiseValueTtl!==void 0?z.rejectedPromiseValueTtl:l.a.second,this.rejectedPromiseValueTtl<0)throw new Error("rejectedPromiseValueTtl must not be negative")}set(z,Z,te){const ce=this.stringify(z);this.cache.set(ce,Z,te),this.expireRejectedPromiseValues&&Promise.resolve(Z).catch(()=>y(this,void 0,void 0,function*(){yield Object(u.a)(this.rejectedPromiseValueTtl),this.cache.peek(ce)===Z&&this.cache.del(ce)}))}}var c=function(oe,z,Z,te){return new(Z||(Z=Promise))(function(ce,ae){function he(fe){try{me(te.next(fe))}catch(ge){ae(ge)}}function de(fe){try{me(te.throw(fe))}catch(ge){ae(ge)}}function me(fe){var ge;fe.done?ce(fe.value):(ge=fe.value,ge instanceof Z?ge:new Z(function(_e){_e(ge)})).then(he,de)}me((te=te.apply(oe,z||[])).next())})};class w{constructor(z,Z,te){this.authClient=z,this.email=Z,this.password=te,this.tokenTtlMs=1*l.a.hour,this.tokenCache=new S({max:100,maxAge:this.tokenTtlMs-5*l.a.minute,fastStringify:!0})}getToken(){return c(this,void 0,void 0,function*(){let z=this.tokenCache.get(this.email);return z||(z=(()=>c(this,void 0,void 0,function*(){const{authentication:Z}=yield this.authClient.login({email:this.email,password:this.password,tokenExpirationSeconds:this.tokenTtlMs/l.a.second});if(!Z)throw new Error("User account not verified.");return Z.accessToken}))(),this.tokenCache.set(this.email,z)),z})}}var E=r(93),P=function(oe,z,Z,te){return new(Z||(Z=Promise))(function(ce,ae){function he(fe){try{me(te.next(fe))}catch(ge){ae(ge)}}function de(fe){try{me(te.throw(fe))}catch(ge){ae(ge)}}function me(fe){var ge;fe.done?ce(fe.value):(ge=fe.value,ge instanceof Z?ge:new Z(function(_e){_e(ge)})).then(he,de)}me((te=te.apply(oe,z||[])).next())})};function F(oe){return P(this,void 0,void 0,function*(){return(yield Promise.all(oe.map(z=>z.catch(Z=>Z)))).filter(z=>z instanceof Error)})}function M(oe){if(oe!==void 0)return oe;throw new Error("Value is undefined")}var A=r(0),p=function(oe,z,Z,te){return new(Z||(Z=Promise))(function(ce,ae){function he(fe){try{me(te.next(fe))}catch(ge){ae(ge)}}function de(fe){try{me(te.throw(fe))}catch(ge){ae(ge)}}function me(fe){var ge;fe.done?ce(fe.value):(ge=fe.value,ge instanceof Z?ge:new Z(function(_e){_e(ge)})).then(he,de)}me((te=te.apply(oe,z||[])).next())})};function N({func:oe,delay:z,immediate:Z}){let te=!1,ce=setTimeout(function he(){return p(this,void 0,void 0,function*(){if(te)return;const de=new Date().getTime();try{ae=oe(),yield ae}finally{if(!te){const me=new Date().getTime();ce=setTimeout(he,Math.max(z-(me-de),0))}}})},Z?0:z),ae=Promise.resolve();return{stop(){return p(this,void 0,void 0,function*(){te=!0,clearTimeout(ce),yield ae})}}}function $(oe,z){return Object.keys(oe).reduce((Z,te)=>Object.assign(Object.assign({},Z),{[te]:z(oe[te])}),{})}var q=function(oe,z,Z,te){return new(Z||(Z=Promise))(function(ce,ae){function he(fe){try{me(te.next(fe))}catch(ge){ae(ge)}}function de(fe){try{me(te.throw(fe))}catch(ge){ae(ge)}}function me(fe){var ge;fe.done?ce(fe.value):(ge=fe.value,ge instanceof Z?ge:new Z(function(_e){_e(ge)})).then(he,de)}me((te=te.apply(oe,z||[])).next())})};class h{constructor(z){this.message=z}send(z){return q(this,void 0,void 0,function*(){A.a.info(this.message,$(z,Z=>{const{sum:te,count:ce}=Z,ae=te/ce;return Object.assign(Object.assign({},Z),{average:ae})}))})}}var d=function(oe,z,Z,te){return new(Z||(Z=Promise))(function(ce,ae){function he(fe){try{me(te.next(fe))}catch(ge){ae(ge)}}function de(fe){try{me(te.throw(fe))}catch(ge){ae(ge)}}function me(fe){var ge;fe.done?ce(fe.value):(ge=fe.value,ge instanceof Z?ge:new Z(function(_e){_e(ge)})).then(he,de)}me((te=te.apply(oe,z||[])).next())})};const O=r(224),_=!!r(7).c,x=new class{constructor(oe=60){this.buffer={},this.metrics={},this.reporters=[],this.flushInterval=N({func:()=>this.flushStats(),delay:oe*l.a.second})}shutdown(){return d(this,void 0,void 0,function*(){yield this.flushInterval.stop(),yield this.flushStats(),yield Object(u.a)(2*l.a.second)})}aggregate(oe,z){if(this.buffer[oe]){const{min:Z,max:te,sum:ce,count:ae}=this.buffer[oe];this.buffer[oe]={min:Math.min(Z,z),max:Math.max(te,z),sum:ce+z,count:ae+1}}else this.buffer[oe]={min:z,max:z,sum:z,count:1}}increment(oe){this.aggregate(oe,1)}timer(oe,z){return d(this,void 0,void 0,function*(){const Z=O(),te=yield z(),ce=O();return this.aggregate(oe,ce-Z),te})}metric(oe,z){this.metrics[oe]=z}registerStatsReporter(oe){this.reporters.push(oe)}write(oe){return d(this,void 0,void 0,function*(){if(Object.values(oe).length===0)return;const z=yield F(this.reporters.map(Z=>Z.send(oe)));for(const Z of z)A.a.warn("Failed to write stats",{error:Z})})}flushStats(){return d(this,void 0,void 0,function*(){const oe=Object.assign(Object.assign({},this.buffer),$(this.metrics,z=>{const Z=z();return{min:Z,max:Z,sum:Z,count:1}}));Object.keys(oe).length>0&&(yield this.write(oe),this.buffer={})})}};_||x.registerStatsReporter(new h("stats"));var D=r(11),L=r(22),T=r(103),C=r(36),U=function(oe,z,Z,te){return new(Z||(Z=Promise))(function(ce,ae){function he(fe){try{me(te.next(fe))}catch(ge){ae(ge)}}function de(fe){try{me(te.throw(fe))}catch(ge){ae(ge)}}function me(fe){var ge;fe.done?ce(fe.value):(ge=fe.value,ge instanceof Z?ge:new Z(function(_e){_e(ge)})).then(he,de)}me((te=te.apply(oe,z||[])).next())})};class b extends C.a{constructor(z){super(z)}postLanRtcOffer(z){return U(this,void 0,void 0,function*(){return yield this.fetch("v1/lan-rtc-offer",{method:"POST",body:JSON.stringify(z)})})}}var f=r(55);const B={ordered:!1,maxPacketLifeTime:300*l.a.millisecond},k={ordered:!0},Y={ordered:!0},K={ordered:!1,maxRetransmits:0},Q={ordered:!1,maxRetransmits:0};function G({entityId:oe,streamName:z,streamType:Z}){return`${oe}.${z}.${Z}`}var V=function(oe,z,Z,te){return new(Z||(Z=Promise))(function(ce,ae){function he(fe){try{me(te.next(fe))}catch(ge){ae(ge)}}function de(fe){try{me(te.throw(fe))}catch(ge){ae(ge)}}function me(fe){var ge;fe.done?ce(fe.value):(ge=fe.value,ge instanceof Z?ge:new Z(function(_e){_e(ge)})).then(he,de)}me((te=te.apply(oe,z||[])).next())})};class v{constructor(z,Z){this.sessionId=z,this.connection=Z,this.counts={localSent:new Map,localReceived:new Map,remoteSent:new Map,remoteReceived:new Map},this.sessionId=z,this.connection=Z}updateRemoteMessagesCounts(z){if(z.payload.streamsInfo){this.counts.remoteSent=new Map,this.counts.remoteReceived=new Map;for(const Z of z.payload.streamsInfo.items)this.counts.remoteSent.set(Z.streamId,Z.sentCount),this.counts.remoteReceived.set(Z.streamId,Z.receivedCount)}}getLocalStreamsInfo(z){const{localSent:Z,localReceived:te}=this.counts;return{items:[...new Set([...Z.keys(),...te.keys()])].map(ce=>{var ae,he;return{streamId:ce,sentCount:(ae=Z.get(ce))!==null&&ae!==void 0?ae:0,receivedCount:(he=te.get(ce))!==null&&he!==void 0?he:0}}),timestamp:z}}incrementLocalSent(z){const{localSent:Z}=this.counts,te=G(z.header.stream);Z.set(te,(Z.get(te)||0)+1)}incrementLocalReceived(z){const{localReceived:Z}=this.counts,te=G(z.header.stream),ce=Z.get(te)||0;if(ce===0){const{streamName:ae,streamType:he}=z.header.stream;A.a.debug("RTC client received first message for stream",{streamName:ae,streamType:he})}Z.set(te,ce+1)}uploadMetrics(){return V(this,void 0,void 0,function*(){const{sessionId:z}=this,Z=yield this.connection.peerConnection.getStats(),te={};Z.forEach(fe=>te[fe.id]=fe),A.a.debug("rtc-stats",Object.assign(Object.assign({},te),{sessionId:z}));const{localSent:ce,localReceived:ae,remoteSent:he,remoteReceived:de}=this.counts,me=[...new Set([...ce.keys(),...ae.keys()])].reduce((fe,ge)=>{const _e=ce.get(ge),Se=ae.get(ge),Oe=he.get(ge),Pe=de.get(ge);return Object.assign(Object.assign({},fe),{[`local-${ge}-sent`]:_e,[`local-${ge}-received`]:Se,[`remote-${ge}-sent`]:Oe,[`remote-${ge}-received`]:Pe})},{sessionId:z});A.a.debug("rtc-message-report",Object.assign({deviceId:this.connection.getRemoteDeviceId()},me))})}}function j(oe){return new Set(["disconnected","failed","closed"]).has(oe.iceConnectionState)}var W=function(oe,z,Z,te){return new(Z||(Z=Promise))(function(ce,ae){function he(fe){try{me(te.next(fe))}catch(ge){ae(ge)}}function de(fe){try{me(te.throw(fe))}catch(ge){ae(ge)}}function me(fe){var ge;fe.done?ce(fe.value):(ge=fe.value,ge instanceof Z?ge:new Z(function(_e){_e(ge)})).then(he,de)}me((te=te.apply(oe,z||[])).next())})};class ee{constructor(z,Z,te){this.peerConnection=z,this.config=Z,this.dataChannelNotifier=te,this.connectTimeoutMs=20*l.a.second,this.iceGatheringTimeoutMs=15*l.a.second,this.pingUpdateTimeoutMs=1*l.a.second,this.streamsInfoUpdateTimeoutMs=2*l.a.second,this.reassemblyTimeoutMs=500*l.a.millisecond,this.reassemblyTableCleanupMs=1*l.a.second,this.heartbeatTimeoutMs=20*l.a.millisecond,this.streamLatestTimestamp=new Map,this.reassemblyTable=new Map,this.reassemblyTableLastTimestamp=new Map,this.closeCalled=!1,this.gotOffer=!1,this.hasIceCandidate=!1;const{isOffer:ce}=Z.baseConfig;ce?this.initializeChannels(z):z.ondatachannel=ae=>{switch(ae.channel.label){case"stream.latest-ttl":this.latestTtlStreamChannel=ae.channel;break;case"stream.reliable":this.reliableStreamChannel=ae.channel;break;case"stream.latest-reliable":this.latestReliableStreamChannel=ae.channel;break;case"stream.latest-try-once":this.latestTryOnceStreamChannel=ae.channel;break;case"heartbeat":return void(this.heartbeatChannel=ae.channel);default:return void this.dataChannelNotifier(ae.channel)}this.setupChannel(ae.channel)},this.pingUpdateTimeout=setInterval(()=>{const{reliableStreamChannel:ae}=this;ae&&this.sendSystemMessage(ae,{type:"ping"})},this.pingUpdateTimeoutMs),this.streamsInfoUpdateTimeout=setInterval(()=>{const{latestTtlStreamChannel:ae}=this;ae&&this.sendSystemMessage(ae,{type:"streams-info"})},this.streamsInfoUpdateTimeoutMs),this.reassemblyTableCleanupTimeout=setInterval(()=>{const ae=new Date().getTime();this.reassemblyTableLastTimestamp.forEach((he,de,me)=>{ae>de+this.reassemblyTimeoutMs&&this.reassemblyTable.delete(he)})},this.reassemblyTableCleanupMs),this.heartbeatTimeout=setInterval(()=>{const{heartbeatChannel:ae}=this;ae&&ae.readyState==="open"&&ae.send(new Uint8Array([1]))},this.heartbeatTimeoutMs)}handleSignal(z){return W(this,void 0,void 0,function*(){const{peerConnection:Z}=this,{track:te}=this.config.baseConfig,ce=(()=>{try{return JSON.parse(z.getPayload())}catch{return}})();if(!ce)return void A.a.error("Received unparseable signal.");A.a.debug("Handling signal",{description:ce});const{sdp:ae,type:he}=ce;if(!ae||!he)return void A.a.warn("Received non-SDP signal");const{signalingState:de,connectionState:me}=Z;if(de!=="stable"||me!=="connected")if(Z.remoteDescription)A.a.warn(`Received SDP after remote description was set: ${ae}`);else{if(he==="offer"){if(de!=="stable")return void A.a.warn("Received offer SDP when signaling is ongoing.");yield Z.setRemoteDescription(ce);const fe=yield Z.createAnswer();yield Z.setLocalDescription(fe);const ge=z.clone();return te==null||te("Answer Received",ge),ge.setPayload(JSON.stringify(fe)),ge.setReceiverId(z.getSenderId()),ge.setSenderId(z.getReceiverId()),ge}if(he==="answer"){if(de==="stable")return void A.a.warn("Received answer SDP when signaling hasn't started.");yield Z.setRemoteDescription(ce)}}else A.a.warn(`Received SDP when already connected: ${ae}`)})}send(z,Z){const te=this.getChannelFromLabel(Z.channelLabel);te?this.sendOnChannel(te,z):A.a.warn("Send called with unexpected channel label",{channelLabel:Z.channelLabel})}controlRemoteStream(z){this.sendSystemMessage(M(this.reliableStreamChannel),{type:"stream-control",streamControl:z})}isActive(){return new Set(["new","checking","connected","completed"]).has(this.peerConnection.iceConnectionState)||this.isReady()}isReady(){const{reliableStreamChannel:z,latestTtlStreamChannel:Z,latestTryOnceStreamChannel:te,latestReliableStreamChannel:ce}=this;return(z==null?void 0:z.readyState)==="open"&&(Z==null?void 0:Z.readyState)==="open"&&(te==null?void 0:te.readyState)==="open"&&(ce==null?void 0:ce.readyState)==="open"}close(){return W(this,void 0,void 0,function*(){if(this.closeCalled)return;this.closeCalled=!0,this.sessionMetrics&&(yield this.sessionMetrics.uploadMetrics()),this.pingUpdateTimeout&&clearInterval(this.pingUpdateTimeout),this.reassemblyTableCleanupTimeout&&clearInterval(this.reassemblyTableCleanupTimeout),this.streamsInfoUpdateTimeout&&clearInterval(this.streamsInfoUpdateTimeout),this.heartbeatTimeout&&clearInterval(this.heartbeatTimeout);const{peerConnection:z,reliableStreamChannel:Z,latestTtlStreamChannel:te,latestTryOnceStreamChannel:ce,latestReliableStreamChannel:ae}=this;z.close(),Z==null||Z.close(),te==null||te.close(),ce==null||ce.close(),ae==null||ae.close()})}getPing(){return this.pingTimeMs}getLastMessageTimestamp(){return this.lastMessageTimestamp}getSessionCreatedTimestamp(){var z;return(z=this.config.remoteConfig)===null||z===void 0?void 0:z.sessionCreatedTimestamp}setSessionCreatedTimestamp(z){this.config.remoteConfig&&(this.config.remoteConfig.sessionCreatedTimestamp=z)}getSessionId(){var z;return(z=this.config.remoteConfig)===null||z===void 0?void 0:z.sessionId}setSessionId(z){this.config.remoteConfig&&(this.config.remoteConfig.sessionId=z,this.sessionMetrics=new v(z,this))}getRemotePeerId(){return this.config.baseConfig.remotePeerId}getRemoteDeviceId(){var z;return(z=this.config.baseConfig)===null||z===void 0?void 0:z.remoteDeviceId}setRemoteDeviceId(z){this.config.baseConfig.remoteDeviceId=z}getSessionMetricsMessageCounts(){var z;return(z=this.sessionMetrics)===null||z===void 0?void 0:z.counts}getConnectionStatsInfo(){return W(this,void 0,void 0,function*(){const{peerConnection:z}=this;if(!z)return;const Z=yield z.getStats(null),te=[];Z.forEach(me=>{te.push(me)});const ce=te.find(me=>me.type==="transport");if(!ce)return;const ae=te.find(me=>(me.type==="candidate-pair"||me.type==="candidatepair")&&me.id===ce.selectedCandidatePairId);if(!ae)return;const he=te.find(me=>me.id===ae.localCandidateId),de=te.find(me=>me.id===ae.remoteCandidateId);return he&&de&&(he.address=he.address||he.ip,de.address=de.address||de.ip,he.address!==void 0&&de.address!==void 0)?{transport:ce,localCandidate:he,remoteCandidate:de}:void 0})}initializeChannels(z){this.heartbeatChannel=z.createDataChannel("heartbeat",Q),this.heartbeatChannel.binaryType="arraybuffer",this.latestTtlStreamChannel=z.createDataChannel("stream.latest-ttl",B),this.latestTtlStreamChannel.binaryType="arraybuffer",this.reliableStreamChannel=z.createDataChannel("stream.reliable",k),this.reliableStreamChannel.binaryType="arraybuffer",this.latestReliableStreamChannel=z.createDataChannel("stream.latest-reliable",Y),this.latestReliableStreamChannel.binaryType="arraybuffer",this.latestTryOnceStreamChannel=z.createDataChannel("stream.latest-try-once",K),this.latestTryOnceStreamChannel.binaryType="arraybuffer",this.setupChannel(this.latestTtlStreamChannel),this.setupChannel(this.reliableStreamChannel),this.setupChannel(this.latestReliableStreamChannel),this.setupChannel(this.latestTryOnceStreamChannel)}getOffer(){var z,Z,te;return W(this,void 0,void 0,function*(){const{gotOffer:ce}=this,{peerConnection:ae,config:he}=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 de=(z=this.config.remoteConfig)===null||z===void 0?void 0:z.sessionId;if(ce)return void A.a.debug("Failed to generate offer because gotOffer was already called.");if(this.gotOffer=!0,j(this.peerConnection))return void A.a.debug("Failed to generate offer because the peer connection was inactive.");const me=he.baseConfig.track;ae.onicecandidate=()=>{this.hasIceCandidate=!0},ae.oniceconnectionstatechange=()=>W(this,void 0,void 0,function*(){const Oe=ae.iceConnectionState;if(Oe==="connected"||Oe==="completed"){const Pe=yield this.getConnectionStatsInfo(),Fe=Pe?function(De){const Le=De.localCandidate.candidateType,xe=De.remoteCandidate.candidateType;return Le==="host"&&xe==="host"?"local":Le==="relay"||xe==="relay"?"TURN":"STUN"}(Pe):void 0;A.a.info(`ICE connection state changed to ${Oe}`,{sessionId:de,connectionStatsInfo:Pe,iceMode:Fe}),me==null||me("ICE connection state change",{iceConnectionState:Oe,sessionId:de,connectionStatsInfo:Pe,iceMode:Fe})}}),yield ae.setLocalDescription(yield ae.createOffer());const fe=new Date().getTime();for(;;){const Oe=new Date().getTime()-fe;if(Oe>this.connectTimeoutMs)return void A.a.debug("Failed to generate offer because ICE gathering timed out.");if(Oe>this.iceGatheringTimeoutMs&&this.hasIceCandidate){A.a.debug("ICE gathering partially completed; proceeding",{iceTransportPolicy:ae.getConfiguration().iceTransportPolicy,waitTime:Oe}),me==null||me("ICE gathering partially completed",{sessionId:de,iceTransportPolicy:ae.getConfiguration().iceTransportPolicy,waitTime:Oe});break}if(ae.iceGatheringState==="complete"){A.a.debug("ICE gathering complete",{iceTransportPolicy:ae.getConfiguration().iceTransportPolicy,waitTime:Oe}),me==null||me("ICE gathering completed",{sessionId:de,iceTransportPolicy:ae.getConfiguration().iceTransportPolicy,waitTime:Oe});break}yield Object(u.a)(.1*l.a.second)}const ge=(Z=this.peerConnection.getConfiguration().iceServers)!==null&&Z!==void 0?Z:[];for(const Oe of ge)Oe.credentialType=void 0;const _e=JSON.stringify(ge),Se=new D.Signal;return Se.setPayload(JSON.stringify(ae.localDescription)),Se.setSenderId(this.config.baseConfig.localPeerId),Se.setReceiverId(this.config.baseConfig.remotePeerId),Se.setIceServers(_e),Se.setIceTransportPolicy((te=this.peerConnection.getConfiguration().iceTransportPolicy)!==null&&te!==void 0?te:"all"),A.a.debug("Sending offer signal with description",{description:Se.getPayload()}),Se})}getLanOffer(){return W(this,void 0,void 0,function*(){const{peerConnection:z,gotOffer:Z}=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(Z)return void A.a.debug("Failed to generate offer because gotOffer was already called.");if(this.gotOffer=!0,j(this.peerConnection))return void A.a.debug("Failed to generate offer because the peer connection was inactive.");yield z.setLocalDescription(yield z.createOffer());const te=new Date().getTime();for(;;){if(new Date().getTime()-te>this.iceGatheringTimeoutMs)return void A.a.debug("Failed to generate offer because ICE gathering timed out.");if(z.iceGatheringState==="complete")break;yield Object(u.a)(.1*l.a.second)}const ce=z.localDescription;if(ce)return A.a.debug("Sending LAN offer signal with description",{description:ce}),ce;A.a.error("Failed to generate LAN offer description")})}handleLanAnswer(z){return W(this,void 0,void 0,function*(){const{peerConnection:Z}=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 Z.setRemoteDescription(z)})}getChannelFromLabel(z){switch(z){case"stream.latest-ttl":return this.latestTtlStreamChannel;case"stream.reliable":return this.reliableStreamChannel;case"stream.latest-reliable":return this.latestReliableStreamChannel;case"stream.latest-try-once":return this.latestTryOnceStreamChannel}}sendOnChannel(z,Z){let te;try{te=Object(f.encode)(JSON.stringify(Z))}catch(ce){return void A.a.warn("Failed to encode RTC message",{error:ce})}try{z.send(te),this.sessionMetrics&&this.sessionMetrics.incrementLocalSent(Z)}catch(ce){A.a.warn("Failed to send message to channel",{error:ce,channel:z.label})}}channelNotRecognized(z){return z!==this.latestTtlStreamChannel&&z!==this.latestReliableStreamChannel&&z!==this.latestTryOnceStreamChannel&&z!==this.reliableStreamChannel}setupChannel(z){z.onmessage=Z=>{if(this.channelNotRecognized(z))return void A.a.warn("Received message on unrecognized data channel.");let te;try{te=JSON.parse(Object(f.decode)(Z.data))}catch(ce){return void A.a.warn("Received unparseable message on RTC stream data channel",{error:ce,channel:z.label})}te.communicationType==="message-chunk"?this.receiveChannelMessageChunk(z,te):this.receiveChannelMessage(z,te)},z.onerror=Z=>{A.a.warn(`Channel error: ${Z.error}`,{error:Z.error,sessionId:this.getSessionId(),channelLabel:z.label})},z.onopen=()=>{A.a.debug("Channel opened",{sessionId:this.getSessionId(),channelLabel:z.label})},z.onclose=()=>{const Z={bufferedAmount:z.bufferedAmount,sessionId:this.getSessionId(),channelLabel:z.label};this.closeCalled===!1?A.a.debug("Unexpected channel closed",Z):A.a.debug("Channel closed",Z)}}receiveChannelMessage(z,Z){const{config:te}=this,{remotePeerId:ce}=this.config.baseConfig;this.lastMessageTimestamp=new Date().getTime(),Z=function(ae){switch(ae.header.stream.streamType){case"twist":const{twist:he}=ae.payload;if(!he)throw Error("twist not in payload of RTC message with type twist");return{header:ae.header,payload:{twist:{linear:Object.assign({x:0,y:0,z:0},he.linear),angular:Object.assign({x:0,y:0,z:0},he.angular)}}};case"pose":const{pose:de}=ae.payload;if(!de)throw Error("pose not in payload of RTC message with type pose");return{header:ae.header,payload:{pose:{translation:Object.assign({x:0,y:0,z:0},de.translation),rotation:Object.assign({x:0,y:0,z:0,w:0},de.rotation)}}};case"pose-with-covariance":const{poseWithCovariance:me}=ae.payload;if(!me)throw Error("poseWithCovariance not in payload of RTC message with type pose-with-covariance");const fe=new Array(36).fill(0);return me.covariance.forEach((_e,Se)=>{if(Se>=36)throw Error("covariance contains more than 36 elements");fe[Se]=_e}),{header:ae.header,payload:{poseWithCovariance:{pose:{translation:Object.assign({x:0,y:0,z:0},me.pose.translation),rotation:Object.assign({x:0,y:0,z:0,w:0},me.pose.rotation)},covariance:fe}}};case"point":const{point:ge}=ae.payload;if(!ge)throw Error("point not in payload of RTC message with type point");return{header:ae.header,payload:{point:Object.assign({x:0,y:0,z:0},ge)}};default:return ae}}(Z),this.sessionMetrics&&this.sessionMetrics.incrementLocalReceived(Z),this.handleSystemMessage(z,Z)||(z===this.latestTryOnceStreamChannel||z===this.latestTtlStreamChannel||z===this.latestReliableStreamChannel)&&!this.isLatestMessage(Z)||te.baseConfig.receive(ce,Z)}receiveChannelMessageChunk(z,Z){const te=this.reassemblyTable.get(Z.id)||[];if(te.push(Z),te.length===Z.total){const ce=function(ae){const he=ae.sort((de,me)=>de.seq<me.seq?-1:1).map(de=>de.part).reduce((de,me)=>de+me);try{return JSON.parse(he)}catch{return void A.a.warn("Could not reassemble RTC message chunks")}}(te);return ce&&this.receiveChannelMessage(z,ce),void this.reassemblyTable.delete(Z.id)}this.reassemblyTable.set(Z.id,te),this.reassemblyTableLastTimestamp.set(Z.id,new Date().getTime())}handleSystemMessage(z,Z){var te,ce;const{config:ae}=this,{baseConfig:he}=ae,{remotePeerId:de}=he;switch(Z.header.stream.streamType){case"ping":return this.sendSystemMessage(z,{type:"pong",timestamp:M(Z.payload.ping)}),!0;case"pong":const me=new Date().getTime()-M(Z.payload.pong);return this.pingTimeMs=me,x.aggregate("rtc-ping-time",me),!0;case"streams-info":const{sessionMetrics:fe}=this,ge=(te=Z.payload.streamsInfo)===null||te===void 0?void 0:te.timestamp;return!!ge&&(fe==null||fe.updateRemoteMessagesCounts(Z),(ce=he.onStreamsInfoUpdate)===null||ce===void 0||ce.call(he,de,ge),!0);case"stream-control":return!0;default:return!1}}sendSystemMessage(z,Z){var te;const{localUserId:ce,localPeerId:ae}=this.config.baseConfig;if(z.readyState!=="open")return;const he={entityId:ce!=null?ce:ae,streamName:`$.${Z.type}`,streamType:Z.type};let de;switch(Z.type){case"ping":de={ping:new Date().getTime()};break;case"pong":de={pong:Z.timestamp};break;case"stream-control":de={streamControl:Z.streamControl};break;case"streams-info":de={streamsInfo:(te=this.sessionMetrics)===null||te===void 0?void 0:te.getLocalStreamsInfo(new Date().getTime())}}this.sendOnChannel(z,function(me,fe){return{header:{stream:me,created:Date.now(),frameId:""},payload:fe}}(he,de))}isLatestMessage(z){const Z=G(z.header.stream),te=(this.streamLatestTimestamp.get(Z)||0)<=z.header.created;return te&&this.streamLatestTimestamp.set(Z,z.header.created),te}}function J(oe){var z,Z;return{userId:(z=oe.getUserId())===null||z===void 0?void 0:z.getValue(),deviceId:(Z=oe.getDeviceId())===null||Z===void 0?void 0:Z.getValue(),organizationId:oe.getOrganizationId(),id:oe.getPeerId(),capabilities:[],capabilitySet:{}}}var re=function(oe,z,Z,te){return new(Z||(Z=Promise))(function(ce,ae){function he(fe){try{me(te.next(fe))}catch(ge){ae(ge)}}function de(fe){try{me(te.throw(fe))}catch(ge){ae(ge)}}function me(fe){var ge;fe.done?ce(fe.value):(ge=fe.value,ge instanceof Z?ge:new Z(function(_e){_e(ge)})).then(he,de)}me((te=te.apply(oe,z||[])).next())})};class se{constructor(z){this.config=z,this.grpcCallDeadline=5*l.a.second,this.refreshIntervalDelayMs=2*l.a.second,this.iceServersTtl=30*l.a.minute,this.connections=[],this.localConnections=[],this.isConnectionInitiator=new Map,this.isOutgoingConnection=new Map,this.peerDataChannelListeners=[];const{refreshIntervalDelayMs:Z}=this;this.refreshInterval=N({func:()=>re(this,void 0,void 0,function*(){try{yield this.update()}catch(te){A.a.warn("RTC refresh failed",{error:te})}}),delay:Z,immediate:!0})}send(z,Z,te){const ce=this.getActiveConnection(z);ce?ce.isReady()?ce.send(Z,te):A.a.warn("Send called with unready connection."):A.a.warn("Send called with no connection.")}controlRemoteStream(z,Z){const te=this.getActiveConnection(z);te?te.isReady()?te.controlRemoteStream(Z):A.a.warn("controlRemoteStream called with unready connection."):A.a.warn("controlRemoteStream called with no connection.")}getLocalPeer(){return re(this,void 0,void 0,function*(){for(;!this.localPeer;)yield Object(u.a)(.1*l.a.second);return J(this.localPeer)})}connect(z,Z){var te,ce,ae;return re(this,void 0,void 0,function*(){if(this.config.lanOnlyMode===!0)throw new Error("connect method called in local only mode.");const{track:he,signalingClient:de}=this.config,{localPeer:me,receiveSignalStream:fe,iceServers:ge}=this;if(!me||!fe||!ge)return void A.a.warn("Connect called prior to local peer, receiveSignalStream, and ICE servers ready");if(this.getActiveConnection(z))return void A.a.warn("Connect called for peer with existing connection.");if(this.isOutgoingConnection.get(z))return void A.a.warn("Connect called for peer with an existing outgoing connection offer.");this.isOutgoingConnection.set(z,!0);const _e=new ee(yield this.createRTCPeerConnection(ge,Z),{baseConfig:{isOffer:!0,isLan:!1,receive:(Le,xe)=>this.config.receive(Le,xe),onStreamsInfoUpdate:this.config.onStreamsInfoUpdate?(Le,xe)=>{var Ne,Ue;return(Ue=(Ne=this.config).onStreamsInfoUpdate)===null||Ue===void 0?void 0:Ue.call(Ne,Le,xe)}:void 0,track:this.config.lanOnlyMode?void 0:this.config.track,localUserId:(te=me.getUserId())===null||te===void 0?void 0:te.getValue(),localPeerId:me.getPeerId(),remotePeerId:z},remoteConfig:{}},Le=>this.onCustomDataChannel(z,Le)),Se=yield _e.getOffer();if(!Se)return A.a.error("Failed to generate offer."),void this.isOutgoingConnection.delete(z);A.a.debug("Sending offer."),he==null||he("Sending offer",Se);const Oe=new D.SendSignalRequest;Oe.setSignal(Se);const Pe=yield(()=>re(this,void 0,void 0,function*(){try{return yield de.sendSignal(Oe,yield this.getMetadata({}))}catch(Le){A.a.warn("Error when sending signal",{error:Le})}}))();if(!this.isOutgoingConnection.get(z))return void A.a.debug("No offer set after receiving offer signal response.");A.a.debug("Offer sent.");const Fe=(ce=Pe==null?void 0:Pe.getSessionId())===null||ce===void 0?void 0:ce.getValue(),De=(ae=Pe==null?void 0:Pe.getSessionCreatedTimestamp())===null||ae===void 0?void 0:ae.getValue();return Fe&&De?(_e.setSessionId(Fe),_e.setSessionCreatedTimestamp(De),this.isOutgoingConnection.delete(z),this.connections.push(_e),this.isConnectionInitiator.set(_e,!0),this.setupHandlers(_e),Fe):(A.a.warn("No session ID or no session created timestamp on send signal response."),void this.isOutgoingConnection.delete(z))})}connectLan(z){var Z,te;return re(this,void 0,void 0,function*(){const ce=new b(z),ae=new ee(yield this.createRTCPeerConnection([]),{baseConfig:{isOffer:!0,isLan:!0,receive:(fe,ge)=>this.config.receive(fe,ge),onStreamsInfoUpdate:this.config.onStreamsInfoUpdate?(fe,ge)=>{var _e,Se;return(Se=(_e=this.config).onStreamsInfoUpdate)===null||Se===void 0?void 0:Se.call(_e,fe,ge)}:void 0,track:this.config.lanOnlyMode?void 0:this.config.track,localUserId:(te=(Z=this.localPeer)===null||Z===void 0?void 0:Z.getUserId())===null||te===void 0?void 0:te.getValue(),localPeerId:"lan_client",remotePeerId:z}},fe=>this.onCustomDataChannel(z,fe)),he=yield ae.getLanOffer();if(!he)return A.a.warn("Could not generate LAN offer"),!1;const de=yield ce.postLanRtcOffer({offer:JSON.stringify(he)}),me=new RTCSessionDescription(JSON.parse(de.answer));return yield ae.handleLanAnswer(me),this.localConnections.push(ae),Object(T.v4)()})}getConnections(){return[...this.connections,...this.localConnections]}createCustomDataChannel(z,Z,te,ce,ae){const he=this.getActiveConnection(z);if(he&&this.isConnectionInitiator.has(he)){const me=he.peerConnection.createDataChannel("custom."+Z,te);return ce&&(me.binaryType="arraybuffer"),ae(z,me),()=>{}}const de=(me,fe)=>{z===me&&fe.label==="custom."+Z&&ae(z,fe)};return this.peerDataChannelListeners.push(de),()=>{this.peerDataChannelListeners=this.peerDataChannelListeners.filter(me=>me!==de)}}onCustomDataChannel(z,Z){this.peerDataChannelListeners.forEach(te=>te(z,Z))}getConnectionStatus(z){if(this.isOutgoingConnection.get(z))return"connecting";const Z=this.getActiveConnection(z);return Z?Z.isReady()?"connected":"connecting":"disconnected"}getConnectionStatsInfo(z){return re(this,void 0,void 0,function*(){const Z=this.getActiveConnection(z);if(Z)return yield Z.getConnectionStatsInfo()})}disconnect(z){return re(this,void 0,void 0,function*(){const Z=this.getActiveConnection(z);Z&&(yield Z.close())})}getPeers(){return re(this,void 0,void 0,function*(){if(this.config.lanOnlyMode)throw new Error("getPeers method cannot be used in local-only mode.");const{signalingClient:z}=this.config,Z=yield(()=>re(this,void 0,void 0,function*(){try{return yield z.getPeers(new D.GetPeersRequest,yield this.getMetadata({}))}catch(ae){A.a.warn("Error when getting peers",{error:ae})}}))();if(!Z)return[];const te=Z.getPeersList();if(!te)return[];const ce=ae=>{var he,de;return(de=(he=ae.getPeerCreatedTimestamp())===null||he===void 0?void 0:he.getValue())!==null&&de!==void 0?de:0};return te.sort((ae,he)=>ce(he)-ce(ae)).map(ae=>J(ae))})}getPing(z){const Z=this.getActiveConnection(z);if(Z)return Z.getPing();A.a.warn("Attempted to get ping time from inactive peer.")}getLastMessageTimestamp(z){const Z=this.getActiveConnection(z);if(Z)return Z.getLastMessageTimestamp();A.a.warn("Attempted to get last message time from inactive peer.")}getSessionMetricsMessageCounts(z){const Z=this.getActiveConnection(z);if(Z)return Z.getSessionMetricsMessageCounts();A.a.warn("Attempted to get session metrics counts from inactive peer.")}isReady(){if(this.config.lanOnlyMode)return!0;const{localPeer:z,receiveSignalStream:Z,iceServers:te}=this;return!!(z&&Z&&te)}shutdown(){return re(this,void 0,void 0,function*(){A.a.info("Shutdown called on RTC client"),yield this.refreshInterval.stop(),this.receiveSignalStream&&this.receiveSignalStream.cancel();const z=this.connections;this.connections=[],yield this.closeConnections(z);const{localPeer:Z}=this;if(!Z||this.config.lanOnlyMode)return;const{signalingClient:te}=this.config;yield(()=>re(this,void 0,void 0,function*(){try{const ce=new D.DeletePeerRequest;ce.setPeerId(Z.getPeerId()),yield te.deletePeer(ce,yield this.getMetadata({}))}catch(ce){return void A.a.warn("Error deleting local peer",{error:ce})}}))()})}createPeer(){return re(this,void 0,void 0,function*(){if(this.config.lanOnlyMode)throw new Error("createPeer method cannot be used in local-only mode.");const{signalingClient:z}=this.config,Z=yield(()=>re(this,void 0,void 0,function*(){try{return yield z.createPeer(new D.CreatePeerRequest,yield this.getMetadata({}))}catch(ce){throw new Error(`Was not able to create peer: ${ce}`)}}))(),te=Z==null?void 0:Z.getPeer();if(!te)throw new Error("Response did not provide peer.");return this.localPeer=te})}createReceiveSignalStream(){return re(this,void 0,void 0,function*(){if(this.config.lanOnlyMode)throw new Error("createReceiveSignalStream method cannot be used in local-only mode.");const{signalingClient:z}=this.config,{localPeer:Z,iceServers:te}=this;if(!Z||!te)return;const{receiveSignalStream:ce}=this;ce&&ce.cancel();const ae=new D.ReceiveSignalStreamRequest;ae.setPeerId(Z.getPeerId());const he=yield(()=>re(this,void 0,void 0,function*(){try{return z.receiveSignalStream(ae,yield this.getMetadata({hasDeadline:!1}))}catch(de){throw new Error(`Unable to create receive signal stream: ${de}`)}}))();if(!he)throw new Error("Response did not provide stream.");return he.on("data",de=>re(this,void 0,void 0,function*(){var me,fe,ge,_e;const Se=de.getSignal(),Oe=(me=Se==null?void 0:Se.getSessionId())===null||me===void 0?void 0:me.getValue(),Pe=Se==null?void 0:Se.getSenderId(),Fe=Se==null?void 0:Se.getReceiverId(),De=(fe=Se==null?void 0:Se.getSessionCreatedTimestamp())===null||fe===void 0?void 0:fe.getValue();if(!(Se&&Oe&&Pe&&Fe&&De))return void A.a.warn("Received signal with missing information.");const Le=this.getActiveConnection(Pe);if(Le)if(Le.getSessionId()!==Oe){if(A.a.debug("Received signal: different session for a peer we're already connected to."),(Le.getSessionCreatedTimestamp()||0)>De)return;const xe=new ee(yield this.createRTCPeerConnection(te),{baseConfig:{isOffer:!1,isLan:!1,receive:(Ne,Ue)=>this.config.receive(Ne,Ue),onStreamsInfoUpdate:this.config.onStreamsInfoUpdate?(Ne,Ue)=>{var We,ze;return(ze=(We=this.config).onStreamsInfoUpdate)===null||ze===void 0?void 0:ze.call(We,Ne,Ue)}:void 0,track:this.config.lanOnlyMode?void 0:this.config.track,localPeerId:Z.getPeerId(),localUserId:(_e=Z.getUserId())===null||_e===void 0?void 0:_e.getValue(),remotePeerId:Pe},remoteConfig:{sessionId:Oe,sessionCreatedTimestamp:De}},Ne=>this.onCustomDataChannel(Pe,Ne));yield xe.handleSignal(Se),this.connections.push(xe)}else A.a.debug("Received signal: for an existing connection."),yield Le.handleSignal(Se);else{A.a.debug("Received signal: new connection.");const xe=new ee(yield this.createRTCPeerConnection(te),{baseConfig:{isOffer:!1,isLan:!1,receive:(Ne,Ue)=>this.config.receive(Ne,Ue),onStreamsInfoUpdate:this.config.onStreamsInfoUpdate?(Ne,Ue)=>{var We,ze;return(ze=(We=this.config).onStreamsInfoUpdate)===null||ze===void 0?void 0:ze.call(We,Ne,Ue)}:void 0,track:this.config.lanOnlyMode?void 0:this.config.track,localPeerId:Z.getPeerId(),localUserId:(ge=Z.getUserId())===null||ge===void 0?void 0:ge.getValue(),remotePeerId:Pe},remoteConfig:{sessionId:Oe,sessionCreatedTimestamp:De}},Ne=>this.onCustomDataChannel(Pe,Ne));yield xe.handleSignal(Se),this.connections.push(xe)}})),he.on("end",()=>{he.cancel(),this.receiveSignalStream=void 0}),he.on("error",de=>{switch(de.code){case L.StatusCode.CANCELLED:case L.StatusCode.UNAVAILABLE:case L.StatusCode.UNKNOWN:A.a.debug("Receive signal stream error",{error:de});break;case L.StatusCode.UNAUTHENTICATED:A.a.warn("Receive signal stream error",{error:de});break;default:A.a.error("Receive signal stream error",{error:de})}he.cancel(),this.receiveSignalStream=void 0}),this.receiveSignalStream=he})}createRTCPeerConnection(z,Z){var te;return re(this,void 0,void 0,function*(){const ce=Z==null?void 0:Z.rtcIceTransportPolicy,ae=(te=this.config.alternateRTCPeerConnection)!==null&&te!==void 0?te:window.RTCPeerConnection;if(!ae)throw new Error("RTCPeerConnection class not found. WebRTC must be enabled.");return new ae(Object.assign({iceServers:z,iceTransportPolicy:ce},Z))})}closeConnections(z){return re(this,void 0,void 0,function*(){const Z=yield F(z.map(te=>re(this,void 0,void 0,function*(){yield te.close()})));for(const te of Z)A.a.warn("Request to close session failed",{error:te})})}getActiveConnection(z){return this.getConnections().find(Z=>Z.getRemotePeerId()===z&&Z.isActive())}update(){var z;return re(this,void 0,void 0,function*(){if(this.localConnections=this.localConnections.filter(de=>de.isActive()),this.config.lanOnlyMode)return;const{signalingClient:Z}=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(de=>!de.isActive())),this.connections=this.connections.filter(de=>de.isActive());const{localPeer:te}=this,ce=this.connections.filter(de=>de.getSessionId).map(de=>M(de.getSessionId()));te.setSessionIdsList(ce);const ae=new D.RefreshPeerRequest;ae.setPeer(te);try{yield Z.refreshPeer(ae,yield this.getMetadata({}))}catch(de){de.code===L.StatusCode.NOT_FOUND?(A.a.warn("Peer expired, creating new peer",{peerId:te.getPeerId()}),yield this.reset()):A.a.warn("Error calling RefreshPeer",{error:de})}const he=yield this.getPeers();for(const de of this.connections)de.setRemoteDeviceId((z=he.find(me=>me.id===de.getRemotePeerId()))===null||z===void 0?void 0:z.deviceId)})}reset(){return re(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 re(this,void 0,void 0,function*(){if(this.config.lanOnlyMode)return;const{iceServersLastUpdate:z,iceServersTtl:Z}=this,te=new Date().getTime();if(!z||te-z>Z)try{const ce=(yield this.config.signalingClient.getIceServers(new D.GetIceServersRequest,yield this.getMetadata({}))).getIceServers();this.iceServers=JSON.parse(ce),this.iceServersLastUpdate=te}catch(ce){A.a.warn("Error in updateIceServers",{error:ce})}})}setupHandlers(z){const{peerConnection:Z}=z,te=z.getSessionCreatedTimestamp();Z.onconnectionstatechange=()=>re(this,void 0,void 0,function*(){const ce=Z.connectionState;if(te)switch(ce){case"connected":x.aggregate("rtc-connect-time",new Date().getTime()-te);break;case"failed":x.increment("rtc-connect-failed")}})}getMetadata(z){return re(this,void 0,void 0,function*(){if(this.config.lanOnlyMode)throw new Error("getMetadata method cannot be called in local-only mode");const{getToken:Z}=this.config,{grpcCallDeadline:te}=this,{hasDeadline:ce}=z,ae=ce===!1?void 0:new Date().getTime()+te;return{authorization:yield Z(),deadline:ae}})}}},,function(e,t,r){r.r(t),r.d(t,"LogClient",function(){return g});var n=r(26),i=function(s,o,l,u){return new(l||(l=Promise))(function(m,R){function y(w){try{c(u.next(w))}catch(E){R(E)}}function S(w){try{c(u.throw(w))}catch(E){R(E)}}function c(w){var E;w.done?m(w.value):(E=w.value,E instanceof l?E:new l(function(P){P(E)})).then(y,S)}c((u=u.apply(s,o||[])).next())})};class g extends n.a{log(o){return i(this,void 0,void 0,function*(){yield this.fetch("logs",{method:"POST",body:JSON.stringify({logs:o}),allowUnsafeRetries:!0})})}}}])})})(dist);let FORMANT_API_URL="https://api.formant.io";typeof window!="undefined"&&(FORMANT_API_URL=window.FORMANT_API_URL||FORMANT_API_URL);let urlParams$1=new URLSearchParams("");typeof window!="undefined"&&(urlParams$1=new URLSearchParams(window.location.search));const moduleName$1=urlParams$1.get("formant_dev");moduleName$1&&(FORMANT_API_URL="https://api-dev.formant.io");function delay(e){return new Promise(t=>setTimeout(t,e))}function defined(e,t){if(e!==void 0)return e;throw new Error(t||"Value is undefined")}class App{static sendAppMessage(t){window.parent.postMessage(t,"*")}static getCurrentModuleContext(){let t=new URLSearchParams("");return typeof window!="undefined"&&(t=new URLSearchParams(window.location.search)),t.get("module")}static isModule(){return this.getCurrentModuleContext()!==null}static goToTime(t){this.sendAppMessage({type:"go_to_time",time:t.getTime()})}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,r){const n=this.getCurrentModuleContext();if(!n)throw new Error("No module context");this.sendAppMessage({type:"set_module_data_time_range",module:n,before:t,after:r||0})}static refreshAuthToken(){const t=this.getCurrentModuleContext();if(!t)throw new Error("No module context");this.sendAppMessage({type:"refresh_auth_token",module:t})}static setupModuleMenus(t){const r=this.getCurrentModuleContext();if(!r)throw new Error("No module context");this.sendAppMessage({type:"setup_module_menus",module:r,menus:t})}static addMenuListener(t){window.addEventListener("message",r=>{const n=r.data;n.type==="module_menu_item_clicked"&&t(n.menu)})}static addAccessTokenRefreshListener(t){window.addEventListener("message",r=>{const n=r.data;n.type==="auth_token"&&t(n.token)})}static addModuleDataListener(t){window.addEventListener("message",r=>{const n=r.data;n.type==="module_data"&&t({streams:n.streams,time:n.time,queryRange:n.queryRange})})}}const Te=class{static async login(t,r){try{const n=await fetch(`${FORMANT_API_URL}/v1/admin/auth/login`,{method:"POST",body:JSON.stringify({email:t,password:r}),headers:{"Content-Type":"application/json"}}),i=await n.json();if(n.status!==200)throw new Error(i.message);return await Te.loginWithToken(i.authentication.accessToken,i.authentication.refreshToken),i.authentication}catch(n){return Te.waitingForAuth.forEach(i=>i(!1)),Te.waitingForAuth=[],Promise.reject(n)}}static async loginWithToken(t,r){const n=JSON.parse(atob(t.split(".")[1]));try{let i=n.sub;n["formant:claims"]&&n["formant:claims"].userId&&(i=n["formant:claims"].userId);const g=await fetch(`${FORMANT_API_URL}/v1/admin/users/${i}`,{method:"GET",headers:{"Content-Type":"application/json",Authorization:"Bearer "+t}}),s=await g.json();if(g.status!==200)throw new Error(s.message);Te.currentUser=s,Te.token=t,Te.waitingForAuth.forEach(o=>o(!0))}catch(i){console.error(i),Te.waitingForAuth.forEach(g=>g(!1))}Te.waitingForAuth=[],r&&(Te.refreshToken=r,setInterval(async()=>{if(Te.refreshToken){const g=await(await fetch(`${FORMANT_API_URL}/v1/admin/auth/refresh`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({refreshToken:Te.refreshToken})})).json();Te.token=g.authentication.accessToken}},1e3*60*60))}static isAuthenticated(){return Te.token!==void 0}static getCurrentUser(){return Te.currentUser}static async waitTilAuthenticated(){return Te.token!==void 0?!0:new Promise(t=>{Te.waitingForAuth.push(function(r){t(r)})})}static async listenForRefresh(){App.addAccessTokenRefreshListener(t=>{this.loginWithToken(t)}),setInterval(async()=>{App.refreshAuthToken()},1e3*60*60)}};let Authentication=Te;Me(Authentication,"token"),Me(Authentication,"refreshToken"),Me(Authentication,"currentUser"),Me(Authentication,"defaultDeviceId"),Me(Authentication,"waitingForAuth",[]);class DataChannel{constructor(t){Me(this,"ready",!1);Me(this,"listeners",[]);Me(this,"binaryListeners",[]);Me(this,"error");Me(this,"decoder",new TextDecoder);this.dataChannel=t,this.dataChannel.binaryType="arraybuffer",this.dataChannel.onopen=()=>{this.ready=!0},this.dataChannel.onclose=()=>{this.ready=!1},this.dataChannel.onerror=r=>{console.error(r),this.error="An error occurred in DataChannel"},this.dataChannel.onmessage=r=>{this.listeners.forEach(n=>{const i=new Uint8Array(r.data),g=this.decoder.decode(i);n(g)}),this.binaryListeners.forEach(n=>{n(new Uint8Array(r.data))})}}async waitTilReady(){return this.ready?!0:new Promise((r,n)=>{let i=window.setInterval(()=>{this.ready&&(window.clearInterval(i),r(!0)),this.error&&n(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 r=this.listeners.indexOf(t);if(r===-1)throw new Error("Could not find data channel listener to remove");if(this.error)throw new Error(this.error);this.listeners.splice(r,1)}addBinaryListener(t){this.binaryListeners.push(t)}removeBinaryListener(t){const r=this.binaryListeners.indexOf(t);if(r===-1)throw new Error("Could not find data channel listener to remove");if(this.error)throw new Error(this.error);this.binaryListeners.splice(r,1)}}class CaptureStream{constructor(t){Me(this,"token");this.captureSession=t}async ingestJSON(t){if(!this.token){const n=await(await fetch(`${FORMANT_API_URL}/v1/admin/capture-sessions/${this.captureSession.code}/authenticate`,{method:"POST"})).json();this.token=n.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,r){Me(this,"currentListeners",[]);Me(this,"onRealtimeMessage",(t,r)=>{r.payload.jointState&&this.currentListeners.forEach(n=>n(r.payload.jointState))});this.device=t,this.config=r}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,r,n){Me(this,"channel");Me(this,"requestIdToResponseMap",new Map);this.device=t,this.channel_name=r,this.timeout=n}}class BinaryRequestDataChannel extends RequestDataChannel{constructor(){super(...arguments);Me(this,"RESPONSE_SUCCESS_BYTE",0);Me(this,"decoder",new TextDecoder)}generateBinaryId(){const t=new Uint8Array(16);for(let r=0;r<t.length;r++)t[r]=Math.floor(Math.random()*256);return t}async initialize(){this.channel=await this.device.createCustomDataChannel(this.channel_name),this.channel.addBinaryListener(t=>{const n=t.slice(0,16).toString();if(n.length===0)throw new Error("Invalid response");const i=t.slice(16);if(i.length===0)throw new Error("Invalid response");this.requestIdToResponseMap.has(n)&&this.requestIdToResponseMap.set(n,i)})}async request(t){if(this.channel||await this.initialize(),!this.channel)throw new Error("Failed to create channel");const{channel:r,requestIdToResponseMap:n,timeout:i}=this;await r.waitTilReady();const g=this.generateBinaryId(),s=g.toString();n.set(s,!0),r.sendBinary(new Uint8Array([...g,...t]));const o=new Date().getTime();for(;new Date().getTime()<o+i;)if(await delay(50),n.has(s)){const l=n.get(s);if(l!==!0){n.delete(s);const u=l[0]===this.RESPONSE_SUCCESS_BYTE,m=l.slice(1);if(u)return m;throw{name:"AdapterError",message:this.decoder.decode(m)}}}throw n.delete(s),{name:"TimeoutError",message:`Request timed out after ${i/1e3} seconds`}}}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 r=JSON.parse(t),{id:n,data:i,error:g}=r;if(!n)throw new Error("Invalid response");if(!i&&!g)throw new Error("Invalid response");this.requestIdToResponseMap.has(n)&&this.requestIdToResponseMap.set(n,r)})}async request(t){if(this.channel||await this.initialize(),!this.channel)throw new Error("Failed to create channel");const{channel:r,requestIdToResponseMap:n,timeout:i}=this;await r.waitTilReady();const g=this.generateTextId();n.set(g,!0),r.send(JSON.stringify({id:g,data:t}));const s=new Date().getTime();for(;new Date().getTime()<s+i;)if(await delay(50),n.has(g)){const o=n.get(g);if(o!==!0){n.delete(g);const{data:l,error:u}=o;if(l)return l;if(u)throw{name:"AdapterError",message:u}}}throw n.delete(g),{name:"TimeoutError",message:`Request timed out after ${i/1e3} seconds`}}}class Device{constructor(t,r,n){Me(this,"rtcClient");Me(this,"realtimeListeners",[]);Me(this,"handleMessage",(t,r)=>{this.realtimeListeners.forEach(n=>n(t,r))});this.id=t,this.name=r,this.organizationId=n}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 r=await t.json();if(!r.state.reportedConfiguration)throw new Error("Device has no configuration, has it ever been turned on?");const n=r.state.reportedConfiguration.version;return t=await fetch(`${FORMANT_API_URL}/v1/admin/devices/${this.id}/configurations/${n}`,{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({fileId:[t]}),headers:{"Content-Type":"application/json",Authorization:"Bearer "+Authentication.token}})).json()).fileUrls}async startRealtimeConnection(){if(this.rtcClient)throw new Error(`Already created realtime connection to device ${this.id}`);{const t=new dist.exports.RtcClient({signalingClient:new dist.exports.SignalingPromiseClient(FORMANT_API_URL,null,null),getToken:async()=>defined(Authentication.token,"Realtime when user isn't authorized"),receive:this.handleMessage});for(;!t.isReady();)await delay(100);const n=(await t.getPeers()).find(g=>g.deviceId===this.id);if(!n)throw new Error("Cannot find peer, is the robot offline?");const i=n.id;for(await t.connect(i);t.getConnectionStatus(i)!=="connected";)await delay(100);this.rtcClient=t}}addRealtimeListener(t){this.realtimeListeners.push(t)}removeRealtimeListener(t){const r=this.realtimeListeners.indexOf(t);if(r===-1)throw new Error("Could not find realtime listener to remove");this.realtimeListeners.splice(r,1)}async getRealtimeVideoStreams(){var n,i,g;const t=await this.getConfiguration(),r=[];for(const s of(n=t.teleop.hardwareStreams)!=null?n:[])s.rtcStreamType==="h264-video-frame"&&r.push({name:s.name});for(const s of(i=t.teleop.rosStreams)!=null?i:[])s.topicType=="formant/H264VideoFrame"&&r.push({name:s.topicName});for(const s of(g=t.teleop.customStreams)!=null?g:[])s.rtcStreamType==="h264-video-frame"&&r.push({name:s.name});return r}async getRealtimeManipulators(){var n;const t=await this.getConfiguration(),r=[];for(const i of(n=t.teleop.rosStreams)!=null?n:[])i.topicType=="sensor_msgs/JointState"&&r.push(new Manipulator(this,{currentJointStateStream:{name:i.topicName},plannedJointStateStream:i.plannedTopic?{name:i.plannedTopic}:void 0,planValidStream:i.planValidTopic?{name:i.planValidTopic}:void 0,endEffectorStream:i.endEffectorTopic?{name:i.endEffectorTopic}:void 0,endEffectorLinkName:i.endEffectorLinkName,baseReferenceFrame:i.baseReferenceFrame,localFrame:i.localFrame}));return r}async startListeningToRealtimeVideo(t){const r=defined(this.rtcClient,"Realtime connection has not been started"),n=await this.getRemotePeer();r.controlRemoteStream(defined(n).id,{streamName:t.name,enable:!0,pipeline:"rtc"})}async stopListeningToRealtimeVideo(t){const r=defined(this.rtcClient,"Realtime connection has not been started"),n=await this.getRemotePeer();r.controlRemoteStream(defined(n).id,{streamName:t.name,enable:!1,pipeline:"rtc"})}async startListeningToRealtimeDataStream(t){const r=defined(this.rtcClient,"Realtime connection has not been started"),n=await this.getRemotePeer();r.controlRemoteStream(defined(n).id,{streamName:t.name,enable:!0,pipeline:"rtc"})}async stopListeningToRealtimeDataStream(t){const r=defined(this.rtcClient,"Realtime connection has not been started"),n=await this.getRemotePeer();r.controlRemoteStream(defined(n).id,{streamName:t.name,enable:!1,pipeline:"rtc"})}async enableRealtimeTelemetryPriorityIngestion(t){const r=defined(this.rtcClient,"Realtime connection has not been started"),n=await this.getRemotePeer();r.controlRemoteStream(defined(n).id,{streamName:t,enablePriorityUpload:!0,pipeline:"telemetry"})}async disableRealtimeTelemetryPriorityIngestion(t){const r=defined(this.rtcClient,"Realtime connection has not been started"),n=await this.getRemotePeer();r.controlRemoteStream(defined(n).id,{streamName:t,enablePriorityUpload:!1,pipeline:"telemetry"})}async getRemotePeer(){const r=(await defined(this.rtcClient,"Realtime connection has not been started").getPeers()).find(n=>n.deviceId===this.id);return defined(r,"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 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(n=>({name:n.name,id:n.id,command:n.command,description:n.description,parameterEnabled:n.parameterEnabled,parameterValue:n.parameterValue,parameterMeta:n.parameterMeta}))}async sendCommand(t,r,n,i){var R;const s=(await this.getAvailableCommands()).find(y=>y.name===t);if(!s)throw new Error(`Could not find command with name "${t}"`);let o;if(r===void 0)if(s.parameterEnabled&&s.parameterValue)o=s.parameterValue;else throw new Error("Command has no default parameter value, you must provide one");else o=r;let l={value:o,scrubberTime:(n||new Date).toISOString(),meta:st(st({},s.parameterMeta),i)};return(await(await fetch(`${FORMANT_API_URL}/v1/admin/commands`,{method:"POST",body:JSON.stringify({commandTemplateId:s.id,organizationId:this.organizationId,deviceId:this.id,command:s.command,parameter:l,userId:(R=Authentication.currentUser)==null?void 0:R.id}),headers:{"Content-Type":"application/json",Authorization:"Bearer "+Authentication.token}})).json()).fileUrls}async createCustomDataChannel(t,r){const n=defined(this.rtcClient,"Realtime connection has not been started"),i=await this.getRemotePeer();return new Promise(s=>{n.createCustomDataChannel(defined(i).id,t,st({ordered:!0},r),!1,(o,l)=>{const u=new DataChannel(l);s(u)})})}createCustomRequestDataChannel(t,r=3e3){return new TextRequestDataChannel(this,t,r)}createCustomBinaryRequestDataChannel(t,r=3e3){return new BinaryRequestDataChannel(this,t,r)}async createCaptureStream(t){const n=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(n)}async getTelemetry(t,r,n,i){return await Fleet.getTelemetry(this.id,t,r,n,i)}async getTelemetryStreams(){var o,l;const t=await this.getConfiguration(),r=await fetch(`${FORMANT_API_URL}/v1/queries/metadata/stream-names`,{method:"POST",body:JSON.stringify({deviceIds:[this.id]}),headers:{"Content-Type":"application/json",Authorization:"Bearer "+Authentication.token}}),n=[],i=[];return(l=(o=t.telemetry)==null?void 0:o.streams)==null||l.forEach(u=>{u.disabled!==!0&&n.push(u.name),u.onDemand===!0&&i.push(u.name)}),console.log(i),(await r.json()).items.filter(u=>!n.includes(u)).map(u=>({name:u,onDemand:i.includes(u)}))}}const Ae=class{static async setDefaultDevice(t){Ae.defaultDeviceId=t}static async getCurrentDevice(){if(!Authentication.token)throw new Error("Not authenticated");if(!Ae.defaultDeviceId)throw new Error("No known default device");const r=await(await fetch(`${FORMANT_API_URL}/v1/admin/devices/${Ae.defaultDeviceId}`,{method:"GET",headers:{"Content-Type":"application/json",Authorization:"Bearer "+Authentication.token}})).json(),n=r.name,i=new Device(Ae.defaultDeviceId,n,r.organizationId);return Ae.knownContext.push(new WeakRef(i)),i}static async getDevice(t){if(!Authentication.token)throw new Error("Not authenticated");const n=await(await fetch(`${FORMANT_API_URL}/v1/admin/devices/${t}`,{method:"GET",headers:{"Content-Type":"application/json",Authorization:"Bearer "+Authentication.token}})).json(),i=n.name,g=new Device(t,i,n.organizationId);return Ae.knownContext.push(new WeakRef(g)),g}static async getDevices(){if(!Authentication.token)throw new Error("Not authenticated");const r=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 r.items,r.items.map(n=>new Device(n.id,n.name,n.organizationId))}static async getOnlineDevices(){if(!Authentication.token)throw new Error("Not authenticated");const n=(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 Ae.getDevices()).filter(g=>n.includes(g.id))}static async getRealtimeDevices(){if(!Authentication.token)throw new Error("Not authenticated");const n=(await(await fetch(`${FORMANT_API_URL}/v1/signaling/peers`,{method:"GET",headers:{"Content-Type":"application/json",Authorization:"Bearer "+Authentication.token}})).json()).items.map(g=>g.deviceId);return(await Ae.getDevices()).filter(g=>n.includes(g.id))}static async getLatestTelemetry(t){let r=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:r}),headers:{"Content-Type":"application/json",Authorization:"Bearer "+Authentication.token}})).json()).items}static async getTelemetry(t,r,n,i,g){let s=t;Array.isArray(t)||(s=[t]);let o=r;return Array.isArray(r)||(o=[r]),(await(await fetch(`${FORMANT_API_URL}/v1/queries/queries`,{method:"POST",body:JSON.stringify({deviceIds:s,end:i.toISOString(),names:o,start:n.toISOString(),tags:g}),headers:{"Content-Type":"application/json",Authorization:"Bearer "+Authentication.token}})).json()).items}static async getFileUrl(t){const n=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(n.fileUrls.length===0)throw new Error("File not found");return n.fileUrls[0]}};let Fleet=Ae;Me(Fleet,"defaultDeviceId"),Me(Fleet,"knownContext",[]);class KeyValue{static async set(t,r){try{const n=await fetch(FORMANT_API_URL+"/v1/admin/key-value",{method:"POST",body:JSON.stringify({organizationId:defined(Authentication.currentUser).organizationId,key:t,value:r}),headers:{"Content-Type":"application/json",Authorization:"Bearer "+Authentication.token}}),i=await n.json();if(n.status!==200)throw new Error(i.message)}catch(n){throw n}}static async get(t){try{const r=await fetch(FORMANT_API_URL+`/v1/admin/key-value/${t}`,{method:"GET",body:JSON.stringify({organizationId:defined(Authentication.currentUser).organizationId}),headers:{"Content-Type":"application/json",Authorization:"Bearer "+Authentication.token}}),n=await r.json();if(r.status!==200)throw new Error(n.message);return n.value}catch(r){throw r}}}let urlParams=new URLSearchParams("");typeof window!="undefined"&&(urlParams=new URLSearchParams(window.location.search));const urlDevice=urlParams.get("device");urlDevice&&Fleet.setDefaultDevice(urlDevice);const urlAuth=urlParams.get("auth");urlAuth&&Authentication.loginWithToken(urlAuth);const moduleName=urlParams.get("module");moduleName&&Authentication.listenForRefresh(),exports.App=App,exports.Authentication=Authentication,exports.BinaryRequestDataChannel=BinaryRequestDataChannel,exports.CaptureStream=CaptureStream,exports.DataChannel=DataChannel,exports.Device=Device,exports.Fleet=Fleet,exports.KeyValue=KeyValue,exports.Manipulator=Manipulator,exports.TextRequestDataChannel=TextRequestDataChannel,Object.defineProperty(exports,"__esModule",{value:!0}),exports[Symbol.toStringTag]="Module"});
|
|
@@ -24,11 +24,17 @@ export interface Command {
|
|
|
24
24
|
topic?: string;
|
|
25
25
|
};
|
|
26
26
|
}
|
|
27
|
+
export interface IJointState {
|
|
28
|
+
name: string[];
|
|
29
|
+
position: number[];
|
|
30
|
+
velocity?: number[];
|
|
31
|
+
effort?: number[];
|
|
32
|
+
}
|
|
27
33
|
export interface TelemetryStream {
|
|
28
34
|
name: string;
|
|
29
35
|
onDemand: boolean;
|
|
30
36
|
}
|
|
31
|
-
export declare type
|
|
37
|
+
export declare type RealtimeMessage = {
|
|
32
38
|
header: {
|
|
33
39
|
created: number;
|
|
34
40
|
stream: {
|
|
@@ -38,7 +44,8 @@ export declare type RealtimeListener = (peerId: string, message: {
|
|
|
38
44
|
};
|
|
39
45
|
};
|
|
40
46
|
payload: any;
|
|
41
|
-
}
|
|
47
|
+
};
|
|
48
|
+
export declare type RealtimeListener = (peerId: string, message: RealtimeMessage) => void;
|
|
42
49
|
export declare type RealtimeVideoStream = {
|
|
43
50
|
name: string;
|
|
44
51
|
};
|
|
@@ -28,4 +28,5 @@ export declare class Fleet {
|
|
|
28
28
|
static getTelemetry(deviceIdOrDeviceIds: string | string[], streamNameOrStreamNames: string | string[], start: Date, end: Date, tags?: {
|
|
29
29
|
[key in string]: string[];
|
|
30
30
|
}): Promise<TelemetryResult[]>;
|
|
31
|
+
static getFileUrl(uuid: string): Promise<string>;
|
|
31
32
|
}
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { Device, RealtimeDataStream } from "./Device";
|
|
1
|
+
import { Device, RealtimeDataStream, IJointState, RealtimeMessage } from "./Device";
|
|
2
2
|
export declare type RealtimeManipulatorConfig = {
|
|
3
3
|
currentJointStateStream: RealtimeDataStream;
|
|
4
4
|
plannedJointStateStream?: RealtimeDataStream;
|
|
@@ -11,6 +11,10 @@ export declare type RealtimeManipulatorConfig = {
|
|
|
11
11
|
export declare class Manipulator {
|
|
12
12
|
private device;
|
|
13
13
|
private config;
|
|
14
|
+
currentListeners: ((js: IJointState) => void)[];
|
|
14
15
|
constructor(device: Device, config: RealtimeManipulatorConfig);
|
|
15
16
|
synchronize(): Promise<void>;
|
|
17
|
+
desynchronize(): Promise<void>;
|
|
18
|
+
onRealtimeMessage: (_peerId: string, message: RealtimeMessage) => void;
|
|
19
|
+
addCurrentJointStateListener(listener: (js: IJointState) => void): Promise<void>;
|
|
16
20
|
}
|