@formant/data-sdk 0.0.63 → 0.0.64
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 +30 -2
- package/dist/data-sdk.umd.js +1 -1
- package/dist/types/data-sdk/src/Fleet.d.ts +6 -0
- package/dist/types/data-sdk/src/model/AggregateLevel.d.ts +1 -0
- package/dist/types/data-sdk/src/model/AnnotationAreaType.d.ts +2 -0
- package/dist/types/data-sdk/src/model/EventSortableColumn.d.ts +1 -0
- package/dist/types/data-sdk/src/model/EventType.d.ts +2 -0
- package/dist/types/data-sdk/src/model/HealthStatus.d.ts +2 -0
- package/dist/types/data-sdk/src/model/HexRgbColor.d.ts +1 -0
- package/dist/types/data-sdk/src/model/IAnnotation.d.ts +13 -0
- package/dist/types/data-sdk/src/model/IAnnotationAreaTypeMap.d.ts +4 -0
- package/dist/types/data-sdk/src/model/IBaseEntity.d.ts +7 -0
- package/dist/types/data-sdk/src/model/IBaseEvent.d.ts +19 -0
- package/dist/types/data-sdk/src/model/IBattery.d.ts +6 -0
- package/dist/types/data-sdk/src/model/IBitset.d.ts +4 -0
- package/dist/types/data-sdk/src/model/IBoundingBox.d.ts +6 -0
- package/dist/types/data-sdk/src/model/ICommandDeliveryEvent.d.ts +3 -0
- package/dist/types/data-sdk/src/model/ICommandEventBase.d.ts +5 -0
- package/dist/types/data-sdk/src/model/ICommandRequestEvent.d.ts +5 -0
- package/dist/types/data-sdk/src/model/ICommandResponseEvent.d.ts +3 -0
- package/dist/types/data-sdk/src/model/IComment.d.ts +7 -0
- package/dist/types/data-sdk/src/model/ICustomEvent.d.ts +5 -0
- package/dist/types/data-sdk/src/model/IDataPoint.d.ts +7 -0
- package/dist/types/data-sdk/src/model/IEvent.d.ts +12 -0
- package/dist/types/data-sdk/src/model/IEventFilter.d.ts +19 -0
- package/dist/types/data-sdk/src/model/IEventQuery.d.ts +7 -0
- package/dist/types/data-sdk/src/model/IEventSort.d.ts +6 -0
- package/dist/types/data-sdk/src/model/IFile.d.ts +6 -0
- package/dist/types/data-sdk/src/model/IFilter.d.ts +10 -0
- package/dist/types/data-sdk/src/model/IGoal.d.ts +5 -0
- package/dist/types/data-sdk/src/model/IHealth.d.ts +4 -0
- package/dist/types/data-sdk/src/model/IImage.d.ts +6 -0
- package/dist/types/data-sdk/src/model/IImageAnnotation.d.ts +9 -0
- package/dist/types/data-sdk/src/model/IInterventionRequest.d.ts +9 -0
- package/dist/types/data-sdk/src/model/IInterventionResponse.d.ts +10 -0
- package/dist/types/data-sdk/src/model/IInterventionTypeMap.d.ts +20 -0
- package/dist/types/data-sdk/src/model/ILabel.d.ts +4 -0
- package/dist/types/data-sdk/src/model/ILabeledPolygon.d.ts +4 -0
- package/dist/types/data-sdk/src/model/ILabelingRequestData.d.ts +8 -0
- package/dist/types/data-sdk/src/model/ILabelingResponseData.d.ts +4 -0
- package/dist/types/data-sdk/src/model/ILocalization.d.ts +12 -0
- package/dist/types/data-sdk/src/model/ILocation.d.ts +6 -0
- package/dist/types/data-sdk/src/model/IMap.d.ts +10 -0
- package/dist/types/data-sdk/src/model/INumericSetEntry.d.ts +5 -0
- package/dist/types/data-sdk/src/model/IOdometry.d.ts +7 -0
- package/dist/types/data-sdk/src/model/IPath.d.ts +5 -0
- package/dist/types/data-sdk/src/model/IPointCloud.d.ts +6 -0
- package/dist/types/data-sdk/src/model/IPortForwardingSessionRecord.d.ts +3 -0
- package/dist/types/data-sdk/src/model/IQuaternion.d.ts +6 -0
- package/dist/types/data-sdk/src/model/IQuery.d.ts +8 -0
- package/dist/types/data-sdk/src/model/IRtcSessionRecord.d.ts +9 -0
- package/dist/types/data-sdk/src/model/ISelectionRequestData.d.ts +6 -0
- package/dist/types/data-sdk/src/model/ISelectionResponseData.d.ts +3 -0
- package/dist/types/data-sdk/src/model/ISpreadsheetIdRange.d.ts +4 -0
- package/dist/types/data-sdk/src/model/IStreamData.d.ts +11 -0
- package/dist/types/data-sdk/src/model/IStreamTypeMap.d.ts +27 -0
- package/dist/types/data-sdk/src/model/ISystemEvent.d.ts +3 -0
- package/dist/types/data-sdk/src/model/ITagSets.d.ts +3 -0
- package/dist/types/data-sdk/src/model/ITaggedUsers.d.ts +4 -0
- package/dist/types/data-sdk/src/model/ITags.d.ts +3 -0
- package/dist/types/data-sdk/src/model/ITeleopRequestData.d.ts +3 -0
- package/dist/types/data-sdk/src/model/ITeleopResponseData.d.ts +4 -0
- package/dist/types/data-sdk/src/model/ITeleopSessionRecord.d.ts +3 -0
- package/dist/types/data-sdk/src/model/ITransform.d.ts +6 -0
- package/dist/types/data-sdk/src/model/ITransformNode.d.ts +7 -0
- package/dist/types/data-sdk/src/model/ITriggeredEvent.d.ts +10 -0
- package/dist/types/data-sdk/src/model/ITwist.d.ts +5 -0
- package/dist/types/data-sdk/src/model/IVector3.d.ts +5 -0
- package/dist/types/data-sdk/src/model/IVideo.d.ts +7 -0
- package/dist/types/data-sdk/src/model/InterventionType.d.ts +2 -0
- package/dist/types/data-sdk/src/model/IsoDate.d.ts +1 -0
- package/dist/types/data-sdk/src/model/Severity.d.ts +2 -0
- package/dist/types/data-sdk/src/model/SortOrder.d.ts +1 -0
- package/dist/types/data-sdk/src/model/StreamType.d.ts +2 -0
- package/dist/types/data-sdk/src/model/Timestamp.d.ts +1 -0
- package/dist/types/data-sdk/src/model/Uuid.d.ts +1 -0
- package/dist/types/data-sdk/src/model/VideoMimeType.d.ts +2 -0
- package/dist/types/data-sdk/src/model/eventTypes.d.ts +1 -0
- package/dist/types/data-sdk/src/model/healthStatuses.d.ts +1 -0
- package/dist/types/data-sdk/src/model/severities.d.ts +1 -0
- package/dist/types/data-sdk/src/model/videoMimeTypes.d.ts +1 -0
- package/package.json +1 -1
package/dist/data-sdk.es.js
CHANGED
|
@@ -18054,7 +18054,7 @@ Found: ${e2.toString().split("\n")[0]}
|
|
|
18054
18054
|
try {
|
|
18055
18055
|
return yield e2.createPeer(new C.CreatePeerRequest(), yield this.getMetadata({}));
|
|
18056
18056
|
} catch (e3) {
|
|
18057
|
-
throw new Error(`Was not able to create peer: ${e3}`);
|
|
18057
|
+
throw new Error(`Was not able to create peer: ${JSON.stringify(e3)}`);
|
|
18058
18058
|
}
|
|
18059
18059
|
}))(), r2 = t2 == null ? void 0 : t2.getPeer();
|
|
18060
18060
|
if (!r2)
|
|
@@ -18077,7 +18077,7 @@ Found: ${e2.toString().split("\n")[0]}
|
|
|
18077
18077
|
try {
|
|
18078
18078
|
return e2.receiveSignalStream(o2, yield this.getMetadata({ hasDeadline: false }));
|
|
18079
18079
|
} catch (e3) {
|
|
18080
|
-
throw new Error(`Unable to create receive signal stream: ${e3}`);
|
|
18080
|
+
throw new Error(`Unable to create receive signal stream: ${JSON.stringify(e3)}`);
|
|
18081
18081
|
}
|
|
18082
18082
|
}))();
|
|
18083
18083
|
if (!i2)
|
|
@@ -19291,6 +19291,34 @@ const _Fleet = class {
|
|
|
19291
19291
|
}
|
|
19292
19292
|
return result.fileUrls[0];
|
|
19293
19293
|
}
|
|
19294
|
+
static async queryTelemetry(query) {
|
|
19295
|
+
if (!Authentication.token) {
|
|
19296
|
+
throw new Error("Not authenticated");
|
|
19297
|
+
}
|
|
19298
|
+
const data = await fetch(`${FORMANT_API_URL}/v1/queries/queries`, {
|
|
19299
|
+
method: "POST",
|
|
19300
|
+
body: JSON.stringify(query),
|
|
19301
|
+
headers: {
|
|
19302
|
+
"Content-Type": "application/json",
|
|
19303
|
+
Authorization: "Bearer " + Authentication.token
|
|
19304
|
+
}
|
|
19305
|
+
});
|
|
19306
|
+
return (await data.json()).items;
|
|
19307
|
+
}
|
|
19308
|
+
static async queryEvents(query) {
|
|
19309
|
+
if (!Authentication.token) {
|
|
19310
|
+
throw new Error("Not authenticated");
|
|
19311
|
+
}
|
|
19312
|
+
const data = await fetch(`${FORMANT_API_URL}/v1/admin/events/query`, {
|
|
19313
|
+
method: "POST",
|
|
19314
|
+
body: JSON.stringify(query),
|
|
19315
|
+
headers: {
|
|
19316
|
+
"Content-Type": "application/json",
|
|
19317
|
+
Authorization: "Bearer " + Authentication.token
|
|
19318
|
+
}
|
|
19319
|
+
});
|
|
19320
|
+
return (await data.json()).items;
|
|
19321
|
+
}
|
|
19294
19322
|
};
|
|
19295
19323
|
let Fleet = _Fleet;
|
|
19296
19324
|
__publicField(Fleet, "defaultDeviceId");
|
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(ge,ie){function he(fe){try{me(te.next(fe))}catch(ue){ie(ue)}}function de(fe){try{me(te.throw(fe))}catch(ue){ie(ue)}}function me(fe){var ue;fe.done?ge(fe.value):(ue=fe.value,ue instanceof Z?ue:new Z(function(_e){_e(ue)})).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:ge}){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:ge})})})}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,roleId:te})})})}getFeatures(z){return i(this,void 0,void 0,function*(){return(yield this.fetch("auth/features",{token:z})).features})}}var s=function(oe,z,Z,te){return new(Z||(Z=Promise))(function(ge,ie){function he(fe){try{me(te.next(fe))}catch(ue){ie(ue)}}function de(fe){try{me(te.throw(fe))}catch(ue){ie(ue)}}function me(fe){var ue;fe.done?ge(fe.value):(ue=fe.value,ue instanceof Z?ue:new Z(function(_e){_e(ue)})).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(11),m=r(21),R=r(102),y=function(oe,z,Z,te){return new(Z||(Z=Promise))(function(ge,ie){function he(fe){try{me(te.next(fe))}catch(ue){ie(ue)}}function de(fe){try{me(te.throw(fe))}catch(ue){ie(ue)}}function me(fe){var ue;fe.done?ge(fe.value):(ue=fe.value,ue instanceof Z?ue:new Z(function(_e){_e(ue)})).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 ge=this.stringify(z);this.cache.set(ge,Z,te),this.expireRejectedPromiseValues&&Promise.resolve(Z).catch(()=>y(this,void 0,void 0,function*(){yield Object(u.a)(this.rejectedPromiseValueTtl),this.cache.peek(ge)===Z&&this.cache.del(ge)}))}}var c=function(oe,z,Z,te){return new(Z||(Z=Promise))(function(ge,ie){function he(fe){try{me(te.next(fe))}catch(ue){ie(ue)}}function de(fe){try{me(te.throw(fe))}catch(ue){ie(ue)}}function me(fe){var ue;fe.done?ge(fe.value):(ue=fe.value,ue instanceof Z?ue:new Z(function(_e){_e(ue)})).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(ge,ie){function he(fe){try{me(te.next(fe))}catch(ue){ie(ue)}}function de(fe){try{me(te.throw(fe))}catch(ue){ie(ue)}}function me(fe){var ue;fe.done?ge(fe.value):(ue=fe.value,ue instanceof Z?ue:new Z(function(_e){_e(ue)})).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(ge,ie){function he(fe){try{me(te.next(fe))}catch(ue){ie(ue)}}function de(fe){try{me(te.throw(fe))}catch(ue){ie(ue)}}function me(fe){var ue;fe.done?ge(fe.value):(ue=fe.value,ue instanceof Z?ue:new Z(function(_e){_e(ue)})).then(he,de)}me((te=te.apply(oe,z||[])).next())})};function N({func:oe,delay:z,immediate:Z}){let te=!1,ge=setTimeout(function he(){return p(this,void 0,void 0,function*(){if(te)return;const de=new Date().getTime();try{ie=oe(),yield ie}finally{if(!te){const me=new Date().getTime();ge=setTimeout(he,Math.max(z-(me-de),0))}}})},Z?0:z),ie=Promise.resolve();return{stop(){return p(this,void 0,void 0,function*(){te=!0,clearTimeout(ge),yield ie})}}}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(ge,ie){function he(fe){try{me(te.next(fe))}catch(ue){ie(ue)}}function de(fe){try{me(te.throw(fe))}catch(ue){ie(ue)}}function me(fe){var ue;fe.done?ge(fe.value):(ue=fe.value,ue instanceof Z?ue:new Z(function(_e){_e(ue)})).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:ge}=Z,ie=te/ge;return Object.assign(Object.assign({},Z),{average:ie})}))})}}var d=function(oe,z,Z,te){return new(Z||(Z=Promise))(function(ge,ie){function he(fe){try{me(te.next(fe))}catch(ue){ie(ue)}}function de(fe){try{me(te.throw(fe))}catch(ue){ie(ue)}}function me(fe){var ue;fe.done?ge(fe.value):(ue=fe.value,ue instanceof Z?ue:new Z(function(_e){_e(ue)})).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:ge,count:ie}=this.buffer[oe];this.buffer[oe]={min:Math.min(Z,z),max:Math.max(te,z),sum:ge+z,count:ie+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(),ge=O();return this.aggregate(oe,ge-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(8),L=r(22),T=r(103),C=r(36),U=function(oe,z,Z,te){return new(Z||(Z=Promise))(function(ge,ie){function he(fe){try{me(te.next(fe))}catch(ue){ie(ue)}}function de(fe){try{me(te.throw(fe))}catch(ue){ie(ue)}}function me(fe){var ue;fe.done?ge(fe.value):(ue=fe.value,ue instanceof Z?ue:new Z(function(_e){_e(ue)})).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(ge,ie){function he(fe){try{me(te.next(fe))}catch(ue){ie(ue)}}function de(fe){try{me(te.throw(fe))}catch(ue){ie(ue)}}function me(fe){var ue;fe.done?ge(fe.value):(ue=fe.value,ue instanceof Z?ue:new Z(function(_e){_e(ue)})).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(ge=>{var ie,he;return{streamId:ge,sentCount:(ie=Z.get(ge))!==null&&ie!==void 0?ie:0,receivedCount:(he=te.get(ge))!==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),ge=Z.get(te)||0;if(ge===0){const{streamName:ie,streamType:he}=z.header.stream;A.a.debug("RTC client received first message for stream",{streamName:ie,streamType:he})}Z.set(te,ge+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:ge,localReceived:ie,remoteSent:he,remoteReceived:de}=this.counts,me=[...new Set([...ge.keys(),...ie.keys()])].reduce((fe,ue)=>{const _e=ge.get(ue),Se=ie.get(ue),Oe=he.get(ue),Pe=de.get(ue);return Object.assign(Object.assign({},fe),{[`local-${ue}-sent`]:_e,[`local-${ue}-received`]:Se,[`remote-${ue}-sent`]:Oe,[`remote-${ue}-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(ge,ie){function he(fe){try{me(te.next(fe))}catch(ue){ie(ue)}}function de(fe){try{me(te.throw(fe))}catch(ue){ie(ue)}}function me(fe){var ue;fe.done?ge(fe.value):(ue=fe.value,ue instanceof Z?ue:new Z(function(_e){_e(ue)})).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:ge}=Z.baseConfig;ge?this.initializeChannels(z):z.ondatachannel=ie=>{switch(ie.channel.label){case"stream.latest-ttl":this.latestTtlStreamChannel=ie.channel;break;case"stream.reliable":this.reliableStreamChannel=ie.channel;break;case"stream.latest-reliable":this.latestReliableStreamChannel=ie.channel;break;case"stream.latest-try-once":this.latestTryOnceStreamChannel=ie.channel;break;case"heartbeat":return void(this.heartbeatChannel=ie.channel);default:return void this.dataChannelNotifier(ie.channel)}this.setupChannel(ie.channel)},this.pingUpdateTimeout=setInterval(()=>{const{reliableStreamChannel:ie}=this;ie&&this.sendSystemMessage(ie,{type:"ping"})},this.pingUpdateTimeoutMs),this.streamsInfoUpdateTimeout=setInterval(()=>{const{latestTtlStreamChannel:ie}=this;ie&&this.sendSystemMessage(ie,{type:"streams-info"})},this.streamsInfoUpdateTimeoutMs),this.reassemblyTableCleanupTimeout=setInterval(()=>{const ie=new Date().getTime();this.reassemblyTableLastTimestamp.forEach((he,de,me)=>{ie>de+this.reassemblyTimeoutMs&&this.reassemblyTable.delete(he)})},this.reassemblyTableCleanupMs),this.heartbeatTimeout=setInterval(()=>{const{heartbeatChannel:ie}=this;ie&&ie.readyState==="open"&&ie.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,ge=(()=>{try{return JSON.parse(z.getPayload())}catch{return}})();if(!ge)return void A.a.error("Received unparseable signal.");A.a.debug("Handling signal",{description:ge});const{sdp:ie,type:he}=ge;if(!ie||!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: ${ie}`);else{if(he==="offer"){if(de!=="stable")return void A.a.warn("Received offer SDP when signaling is ongoing.");yield Z.setRemoteDescription(ge);const fe=yield Z.createAnswer();yield Z.setLocalDescription(fe);const ue=z.clone();return te==null||te("Answer Received",ue),ue.setPayload(JSON.stringify(fe)),ue.setReceiverId(z.getSenderId()),ue.setSenderId(z.getReceiverId()),ue}if(he==="answer"){if(de==="stable")return void A.a.warn("Received answer SDP when signaling hasn't started.");yield Z.setRemoteDescription(ge)}}else A.a.warn(`Received SDP when already connected: ${ie}`)})}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:ge}=this;return(z==null?void 0:z.readyState)==="open"&&(Z==null?void 0:Z.readyState)==="open"&&(te==null?void 0:te.readyState)==="open"&&(ge==null?void 0:ge.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:ge,latestReliableStreamChannel:ie}=this;z.close(),Z==null||Z.close(),te==null||te.close(),ge==null||ge.close(),ie==null||ie.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 ge=te.find(me=>me.type==="transport");if(!ge)return;const ie=te.find(me=>(me.type==="candidate-pair"||me.type==="candidatepair")&&me.id===ge.selectedCandidatePairId);if(!ie)return;const he=te.find(me=>me.id===ie.localCandidateId),de=te.find(me=>me.id===ie.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:ge,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:ge}=this,{peerConnection:ie,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(ge)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;ie.onicecandidate=()=>{this.hasIceCandidate=!0},ie.oniceconnectionstatechange=()=>W(this,void 0,void 0,function*(){const Oe=ie.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 ie.setLocalDescription(yield ie.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:ie.getConfiguration().iceTransportPolicy,waitTime:Oe}),me==null||me("ICE gathering partially completed",{sessionId:de,iceTransportPolicy:ie.getConfiguration().iceTransportPolicy,waitTime:Oe});break}if(ie.iceGatheringState==="complete"){A.a.debug("ICE gathering complete",{iceTransportPolicy:ie.getConfiguration().iceTransportPolicy,waitTime:Oe}),me==null||me("ICE gathering completed",{sessionId:de,iceTransportPolicy:ie.getConfiguration().iceTransportPolicy,waitTime:Oe});break}yield Object(u.a)(.1*l.a.second)}const ue=(Z=this.peerConnection.getConfiguration().iceServers)!==null&&Z!==void 0?Z:[];for(const Oe of ue)Oe.credentialType=void 0;const _e=JSON.stringify(ue),Se=new D.Signal;return Se.setPayload(JSON.stringify(ie.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"),Se.setSessionType(D.SessionType.TELEOP),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 ge=z.localDescription;if(ge)return A.a.debug("Sending LAN offer signal with description",{description:ge}),ge;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(ge){return void A.a.warn("Failed to encode RTC message",{error:ge})}try{z.send(te),this.sessionMetrics&&this.sessionMetrics.incrementLocalSent(Z)}catch(ge){A.a.warn("Failed to send message to channel",{error:ge,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(ge){return void A.a.warn("Received unparseable message on RTC stream data channel",{error:ge,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:ge}=this.config.baseConfig;this.lastMessageTimestamp=new Date().getTime(),Z=function(ie){switch(ie.header.stream.streamType){case"twist":const{twist:he}=ie.payload;if(!he)throw Error("twist not in payload of RTC message with type twist");return{header:ie.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}=ie.payload;if(!de)throw Error("pose not in payload of RTC message with type pose");return{header:ie.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}=ie.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:ie.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:ue}=ie.payload;if(!ue)throw Error("point not in payload of RTC message with type point");return{header:ie.header,payload:{point:Object.assign({x:0,y:0,z:0},ue)}};default:return ie}}(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(ge,Z)}receiveChannelMessageChunk(z,Z){const te=this.reassemblyTable.get(Z.id)||[];if(te.push(Z),te.length===Z.total){const ge=function(ie){const he=ie.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 ge&&this.receiveChannelMessage(z,ge),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,ge;const{config:ie}=this,{baseConfig:he}=ie,{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,ue=(te=Z.payload.streamsInfo)===null||te===void 0?void 0:te.timestamp;return!!ue&&(fe==null||fe.updateRemoteMessagesCounts(Z),(ge=he.onStreamsInfoUpdate)===null||ge===void 0||ge.call(he,de,ue),!0);case"stream-control":return!0;default:return!1}}sendSystemMessage(z,Z){var te;const{localUserId:ge,localPeerId:ie}=this.config.baseConfig;if(z.readyState!=="open")return;const he={entityId:ge!=null?ge:ie,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(ge,ie){function he(fe){try{me(te.next(fe))}catch(ue){ie(ue)}}function de(fe){try{me(te.throw(fe))}catch(ue){ie(ue)}}function me(fe){var ue;fe.done?ge(fe.value):(ue=fe.value,ue instanceof Z?ue:new Z(function(_e){_e(ue)})).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 ge=this.getActiveConnection(z);ge?ge.isReady()?ge.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,ge,ie;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:ue}=this;if(!me||!fe||!ue)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(ue,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=(ge=Pe==null?void 0:Pe.getSessionId())===null||ge===void 0?void 0:ge.getValue(),De=(ie=Pe==null?void 0:Pe.getSessionCreatedTimestamp())===null||ie===void 0?void 0:ie.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 ge=new b(z),ie=new ee(yield this.createRTCPeerConnection([]),{baseConfig:{isOffer:!0,isLan:!0,receive:(fe,ue)=>this.config.receive(fe,ue),onStreamsInfoUpdate:this.config.onStreamsInfoUpdate?(fe,ue)=>{var _e,Se;return(Se=(_e=this.config).onStreamsInfoUpdate)===null||Se===void 0?void 0:Se.call(_e,fe,ue)}: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 ie.getLanOffer();if(!he)return A.a.warn("Could not generate LAN offer"),!1;const de=yield ge.postLanRtcOffer({offer:JSON.stringify(he)}),me=new RTCSessionDescription(JSON.parse(de.answer));return yield ie.handleLanAnswer(me),this.localConnections.push(ie),Object(T.v4)()})}getConnections(){return[...this.connections,...this.localConnections]}createCustomDataChannel(z,Z,te,ge,ie){const he=this.getActiveConnection(z);if(he&&this.isConnectionInitiator.has(he)){const me=he.peerConnection.createDataChannel("custom."+Z,te);return ge&&(me.binaryType="arraybuffer"),ie(z,me),()=>{}}const de=(me,fe)=>{z===me&&fe.label==="custom."+Z&&ie(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(ie){A.a.warn("Error when getting peers",{error:ie})}}))();if(!Z)return[];const te=Z.getPeersList();if(!te)return[];const ge=ie=>{var he,de;return(de=(he=ie.getPeerCreatedTimestamp())===null||he===void 0?void 0:he.getValue())!==null&&de!==void 0?de:0};return te.sort((ie,he)=>ge(he)-ge(ie)).map(ie=>J(ie))})}getSessions(){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(ie){A.a.warn("Error when getting peers",{error:ie})}}))();if(!Z)return{};const te=Z.getPeersList(),ge={};for(const ie of te)ge[ie.getPeerId()]=ie.getSessionIdsList();return ge})}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 ge=new D.DeletePeerRequest;ge.setPeerId(Z.getPeerId()),yield te.deletePeer(ge,yield this.getMetadata({}))}catch(ge){return void A.a.warn("Error deleting local peer",{error:ge})}}))()})}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(ge){throw new Error(`Was not able to create peer: ${ge}`)}}))(),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:ge}=this;ge&&ge.cancel();const ie=new D.ReceiveSignalStreamRequest;ie.setPeerId(Z.getPeerId());const he=yield(()=>re(this,void 0,void 0,function*(){try{return z.receiveSignalStream(ie,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,ue,_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:(ue=Z.getUserId())===null||ue===void 0?void 0:ue.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 ge=Z==null?void 0:Z.rtcIceTransportPolicy,ie=Z==null?void 0:Z.rtcIceServerProtocol,he=(fe,ue)=>typeof fe=="string"?fe.endsWith(`transport=${ue}`):fe.some(_e=>_e.endsWith(`transport=${ue}`)),de=z.filter(fe=>{return ge!=="relay"||(typeof(ue=fe.urls)=="string"?ue.startsWith("turn:"):ue.some(_e=>_e.startsWith("turn:")));var ue}).filter(fe=>ie!=="udp"||he(fe.urls,"udp")).filter(fe=>ie!=="tcp"||he(fe.urls,"tcp")),me=(te=this.config.alternateRTCPeerConnection)!==null&&te!==void 0?te:window.RTCPeerConnection;if(!me)throw new Error("RTCPeerConnection class not found. WebRTC must be enabled.");return new me(Object.assign({iceServers:de,iceTransportPolicy:ge},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,ge=this.connections.filter(de=>de.getSessionId).map(de=>M(de.getSessionId()));te.setSessionIdsList(ge);const ie=new D.RefreshPeerRequest;ie.setPeer(te);try{yield Z.refreshPeer(ie,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 ge=(yield this.config.signalingClient.getIceServers(new D.GetIceServersRequest,yield this.getMetadata({}))).getIceServers();this.iceServers=JSON.parse(ge),this.iceServersLastUpdate=te}catch(ge){A.a.warn("Error in updateIceServers",{error:ge})}})}setupHandlers(z){const{peerConnection:Z}=z,te=z.getSessionCreatedTimestamp();Z.onconnectionstatechange=()=>re(this,void 0,void 0,function*(){const ge=Z.connectionState;if(te)switch(ge){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:ge}=z,ie=ge===!1?void 0:new Date().getTime()+te;return{authorization:yield Z(),deadline:ie}})}}},,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 envDev=urlParams$1.get("formant_dev");envDev&&(FORMANT_API_URL="https://api-dev.formant.io");const envStage=urlParams$1.get("formant_stage");envStage&&(FORMANT_API_URL="https://api-stage.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 Ee=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 Ee.loginWithToken(i.authentication.accessToken,i.authentication.refreshToken),i.authentication}catch(n){return Ee.waitingForAuth.forEach(i=>i(!1)),Ee.waitingForAuth=[],Promise.reject(n)}}static async loginWithToken(t,r){const n=JSON.parse(atob(t.split(".")[1]));try{let i;if(Ee.isShareToken=n["formant:claims"]&&n["formant:claims"].type=="share",n["formant:claims"]&&(Ee.currentOrganization=n["formant:claims"].organizationId),n["custom:organization_id"]&&(Ee.currentOrganization=n["custom:organization_id"]),Ee.isShareToken||(i=n.sub),n["formant:claims"]&&n["formant:claims"].userId&&(i=n["formant:claims"].userId),i){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);Ee.currentUser=s}Ee.token=t,Ee.waitingForAuth.forEach(g=>g(!0))}catch(i){console.error(i),Ee.waitingForAuth.forEach(g=>g(!1))}Ee.waitingForAuth=[],r&&(Ee.refreshToken=r,setInterval(async()=>{if(Ee.refreshToken){const g=await(await fetch(`${FORMANT_API_URL}/v1/admin/auth/refresh`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({refreshToken:Ee.refreshToken})})).json();Ee.token=g.authentication.accessToken}},1e3*60*60))}static isAuthenticated(){return Ee.token!==void 0}static getCurrentUser(){return Ee.currentUser}static async waitTilAuthenticated(){return Ee.token!==void 0?!0:new Promise(t=>{Ee.waitingForAuth.push(function(r){t(r)})})}static async listenForRefresh(){App.addAccessTokenRefreshListener(t=>{this.loginWithToken(t)}),setInterval(async()=>{App.refreshAuthToken()},1e3*60*60)}};let Authentication=Ee;Ce(Authentication,"token"),Ce(Authentication,"refreshToken"),Ce(Authentication,"currentUser"),Ce(Authentication,"currentOrganization"),Ce(Authentication,"isShareToken",!1),Ce(Authentication,"defaultDeviceId"),Ce(Authentication,"waitingForAuth",[]);class DataChannel{constructor(t){Ce(this,"ready",!1);Ce(this,"listeners",[]);Ce(this,"binaryListeners",[]);Ce(this,"error");Ce(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){Ce(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){Ce(this,"currentListeners",[]);Ce(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){Ce(this,"channel");Ce(this,"requestIdToResponseMap",new Map);this.device=t,this.channel_name=r,this.timeout=n}}class BinaryRequestDataChannel extends RequestDataChannel{constructor(){super(...arguments);Ce(this,"RESPONSE_SUCCESS_BYTE",0);Ce(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){Ce(this,"rtcClient");Ce(this,"realtimeListeners",[]);Ce(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 isInRealtimeSession(){let t=await Fleet.getPeers(),r=await Fleet.getRealtimeSessions(),n=t.find(i=>i.deviceId===this.id);return n?r[n.id].length>0:!1}async getAvailableCommands(){return(await(await fetch(`${FORMANT_API_URL}/v1/admin/command-templates/`,{method:"GET",headers:{"Content-Type":"application/json",Authorization:"Bearer "+Authentication.token}})).json()).items.map(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 i=(await(await fetch(`${FORMANT_API_URL}/v1/admin/device-details/query`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:"Bearer "+Authentication.token}})).json()).items.find(s=>s.id===Ae.defaultDeviceId).name,g=new Device(Ae.defaultDeviceId,i,defined(Authentication.currentOrganization));return Ae.knownContext.push(new WeakRef(g)),g}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 getPeers(){if(!Authentication.token)throw new Error("Not authenticated");return await 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:()=>{}}).getPeers()}static async getRealtimeSessions(){if(!Authentication.token)throw new Error("Not authenticated");return await 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:()=>{}}).getSessions()}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;Ce(Fleet,"defaultDeviceId"),Ce(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"});
|
|
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(ge,ie){function he(fe){try{me(te.next(fe))}catch(ue){ie(ue)}}function de(fe){try{me(te.throw(fe))}catch(ue){ie(ue)}}function me(fe){var ue;fe.done?ge(fe.value):(ue=fe.value,ue instanceof Z?ue:new Z(function(_e){_e(ue)})).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:ge}){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:ge})})})}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,roleId:te})})})}getFeatures(z){return i(this,void 0,void 0,function*(){return(yield this.fetch("auth/features",{token:z})).features})}}var s=function(oe,z,Z,te){return new(Z||(Z=Promise))(function(ge,ie){function he(fe){try{me(te.next(fe))}catch(ue){ie(ue)}}function de(fe){try{me(te.throw(fe))}catch(ue){ie(ue)}}function me(fe){var ue;fe.done?ge(fe.value):(ue=fe.value,ue instanceof Z?ue:new Z(function(_e){_e(ue)})).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(11),m=r(21),R=r(102),y=function(oe,z,Z,te){return new(Z||(Z=Promise))(function(ge,ie){function he(fe){try{me(te.next(fe))}catch(ue){ie(ue)}}function de(fe){try{me(te.throw(fe))}catch(ue){ie(ue)}}function me(fe){var ue;fe.done?ge(fe.value):(ue=fe.value,ue instanceof Z?ue:new Z(function(_e){_e(ue)})).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 ge=this.stringify(z);this.cache.set(ge,Z,te),this.expireRejectedPromiseValues&&Promise.resolve(Z).catch(()=>y(this,void 0,void 0,function*(){yield Object(u.a)(this.rejectedPromiseValueTtl),this.cache.peek(ge)===Z&&this.cache.del(ge)}))}}var c=function(oe,z,Z,te){return new(Z||(Z=Promise))(function(ge,ie){function he(fe){try{me(te.next(fe))}catch(ue){ie(ue)}}function de(fe){try{me(te.throw(fe))}catch(ue){ie(ue)}}function me(fe){var ue;fe.done?ge(fe.value):(ue=fe.value,ue instanceof Z?ue:new Z(function(_e){_e(ue)})).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(ge,ie){function he(fe){try{me(te.next(fe))}catch(ue){ie(ue)}}function de(fe){try{me(te.throw(fe))}catch(ue){ie(ue)}}function me(fe){var ue;fe.done?ge(fe.value):(ue=fe.value,ue instanceof Z?ue:new Z(function(_e){_e(ue)})).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(ge,ie){function he(fe){try{me(te.next(fe))}catch(ue){ie(ue)}}function de(fe){try{me(te.throw(fe))}catch(ue){ie(ue)}}function me(fe){var ue;fe.done?ge(fe.value):(ue=fe.value,ue instanceof Z?ue:new Z(function(_e){_e(ue)})).then(he,de)}me((te=te.apply(oe,z||[])).next())})};function N({func:oe,delay:z,immediate:Z}){let te=!1,ge=setTimeout(function he(){return p(this,void 0,void 0,function*(){if(te)return;const de=new Date().getTime();try{ie=oe(),yield ie}finally{if(!te){const me=new Date().getTime();ge=setTimeout(he,Math.max(z-(me-de),0))}}})},Z?0:z),ie=Promise.resolve();return{stop(){return p(this,void 0,void 0,function*(){te=!0,clearTimeout(ge),yield ie})}}}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(ge,ie){function he(fe){try{me(te.next(fe))}catch(ue){ie(ue)}}function de(fe){try{me(te.throw(fe))}catch(ue){ie(ue)}}function me(fe){var ue;fe.done?ge(fe.value):(ue=fe.value,ue instanceof Z?ue:new Z(function(_e){_e(ue)})).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:ge}=Z,ie=te/ge;return Object.assign(Object.assign({},Z),{average:ie})}))})}}var d=function(oe,z,Z,te){return new(Z||(Z=Promise))(function(ge,ie){function he(fe){try{me(te.next(fe))}catch(ue){ie(ue)}}function de(fe){try{me(te.throw(fe))}catch(ue){ie(ue)}}function me(fe){var ue;fe.done?ge(fe.value):(ue=fe.value,ue instanceof Z?ue:new Z(function(_e){_e(ue)})).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:ge,count:ie}=this.buffer[oe];this.buffer[oe]={min:Math.min(Z,z),max:Math.max(te,z),sum:ge+z,count:ie+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(),ge=O();return this.aggregate(oe,ge-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(8),L=r(22),T=r(103),C=r(36),U=function(oe,z,Z,te){return new(Z||(Z=Promise))(function(ge,ie){function he(fe){try{me(te.next(fe))}catch(ue){ie(ue)}}function de(fe){try{me(te.throw(fe))}catch(ue){ie(ue)}}function me(fe){var ue;fe.done?ge(fe.value):(ue=fe.value,ue instanceof Z?ue:new Z(function(_e){_e(ue)})).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(ge,ie){function he(fe){try{me(te.next(fe))}catch(ue){ie(ue)}}function de(fe){try{me(te.throw(fe))}catch(ue){ie(ue)}}function me(fe){var ue;fe.done?ge(fe.value):(ue=fe.value,ue instanceof Z?ue:new Z(function(_e){_e(ue)})).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(ge=>{var ie,he;return{streamId:ge,sentCount:(ie=Z.get(ge))!==null&&ie!==void 0?ie:0,receivedCount:(he=te.get(ge))!==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),ge=Z.get(te)||0;if(ge===0){const{streamName:ie,streamType:he}=z.header.stream;A.a.debug("RTC client received first message for stream",{streamName:ie,streamType:he})}Z.set(te,ge+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:ge,localReceived:ie,remoteSent:he,remoteReceived:de}=this.counts,me=[...new Set([...ge.keys(),...ie.keys()])].reduce((fe,ue)=>{const _e=ge.get(ue),Se=ie.get(ue),Oe=he.get(ue),Pe=de.get(ue);return Object.assign(Object.assign({},fe),{[`local-${ue}-sent`]:_e,[`local-${ue}-received`]:Se,[`remote-${ue}-sent`]:Oe,[`remote-${ue}-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(ge,ie){function he(fe){try{me(te.next(fe))}catch(ue){ie(ue)}}function de(fe){try{me(te.throw(fe))}catch(ue){ie(ue)}}function me(fe){var ue;fe.done?ge(fe.value):(ue=fe.value,ue instanceof Z?ue:new Z(function(_e){_e(ue)})).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:ge}=Z.baseConfig;ge?this.initializeChannels(z):z.ondatachannel=ie=>{switch(ie.channel.label){case"stream.latest-ttl":this.latestTtlStreamChannel=ie.channel;break;case"stream.reliable":this.reliableStreamChannel=ie.channel;break;case"stream.latest-reliable":this.latestReliableStreamChannel=ie.channel;break;case"stream.latest-try-once":this.latestTryOnceStreamChannel=ie.channel;break;case"heartbeat":return void(this.heartbeatChannel=ie.channel);default:return void this.dataChannelNotifier(ie.channel)}this.setupChannel(ie.channel)},this.pingUpdateTimeout=setInterval(()=>{const{reliableStreamChannel:ie}=this;ie&&this.sendSystemMessage(ie,{type:"ping"})},this.pingUpdateTimeoutMs),this.streamsInfoUpdateTimeout=setInterval(()=>{const{latestTtlStreamChannel:ie}=this;ie&&this.sendSystemMessage(ie,{type:"streams-info"})},this.streamsInfoUpdateTimeoutMs),this.reassemblyTableCleanupTimeout=setInterval(()=>{const ie=new Date().getTime();this.reassemblyTableLastTimestamp.forEach((he,de,me)=>{ie>de+this.reassemblyTimeoutMs&&this.reassemblyTable.delete(he)})},this.reassemblyTableCleanupMs),this.heartbeatTimeout=setInterval(()=>{const{heartbeatChannel:ie}=this;ie&&ie.readyState==="open"&&ie.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,ge=(()=>{try{return JSON.parse(z.getPayload())}catch{return}})();if(!ge)return void A.a.error("Received unparseable signal.");A.a.debug("Handling signal",{description:ge});const{sdp:ie,type:he}=ge;if(!ie||!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: ${ie}`);else{if(he==="offer"){if(de!=="stable")return void A.a.warn("Received offer SDP when signaling is ongoing.");yield Z.setRemoteDescription(ge);const fe=yield Z.createAnswer();yield Z.setLocalDescription(fe);const ue=z.clone();return te==null||te("Answer Received",ue),ue.setPayload(JSON.stringify(fe)),ue.setReceiverId(z.getSenderId()),ue.setSenderId(z.getReceiverId()),ue}if(he==="answer"){if(de==="stable")return void A.a.warn("Received answer SDP when signaling hasn't started.");yield Z.setRemoteDescription(ge)}}else A.a.warn(`Received SDP when already connected: ${ie}`)})}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:ge}=this;return(z==null?void 0:z.readyState)==="open"&&(Z==null?void 0:Z.readyState)==="open"&&(te==null?void 0:te.readyState)==="open"&&(ge==null?void 0:ge.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:ge,latestReliableStreamChannel:ie}=this;z.close(),Z==null||Z.close(),te==null||te.close(),ge==null||ge.close(),ie==null||ie.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 ge=te.find(me=>me.type==="transport");if(!ge)return;const ie=te.find(me=>(me.type==="candidate-pair"||me.type==="candidatepair")&&me.id===ge.selectedCandidatePairId);if(!ie)return;const he=te.find(me=>me.id===ie.localCandidateId),de=te.find(me=>me.id===ie.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:ge,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:ge}=this,{peerConnection:ie,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(ge)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;ie.onicecandidate=()=>{this.hasIceCandidate=!0},ie.oniceconnectionstatechange=()=>W(this,void 0,void 0,function*(){const Oe=ie.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 ie.setLocalDescription(yield ie.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:ie.getConfiguration().iceTransportPolicy,waitTime:Oe}),me==null||me("ICE gathering partially completed",{sessionId:de,iceTransportPolicy:ie.getConfiguration().iceTransportPolicy,waitTime:Oe});break}if(ie.iceGatheringState==="complete"){A.a.debug("ICE gathering complete",{iceTransportPolicy:ie.getConfiguration().iceTransportPolicy,waitTime:Oe}),me==null||me("ICE gathering completed",{sessionId:de,iceTransportPolicy:ie.getConfiguration().iceTransportPolicy,waitTime:Oe});break}yield Object(u.a)(.1*l.a.second)}const ue=(Z=this.peerConnection.getConfiguration().iceServers)!==null&&Z!==void 0?Z:[];for(const Oe of ue)Oe.credentialType=void 0;const _e=JSON.stringify(ue),Se=new D.Signal;return Se.setPayload(JSON.stringify(ie.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"),Se.setSessionType(D.SessionType.TELEOP),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 ge=z.localDescription;if(ge)return A.a.debug("Sending LAN offer signal with description",{description:ge}),ge;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(ge){return void A.a.warn("Failed to encode RTC message",{error:ge})}try{z.send(te),this.sessionMetrics&&this.sessionMetrics.incrementLocalSent(Z)}catch(ge){A.a.warn("Failed to send message to channel",{error:ge,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(ge){return void A.a.warn("Received unparseable message on RTC stream data channel",{error:ge,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:ge}=this.config.baseConfig;this.lastMessageTimestamp=new Date().getTime(),Z=function(ie){switch(ie.header.stream.streamType){case"twist":const{twist:he}=ie.payload;if(!he)throw Error("twist not in payload of RTC message with type twist");return{header:ie.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}=ie.payload;if(!de)throw Error("pose not in payload of RTC message with type pose");return{header:ie.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}=ie.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:ie.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:ue}=ie.payload;if(!ue)throw Error("point not in payload of RTC message with type point");return{header:ie.header,payload:{point:Object.assign({x:0,y:0,z:0},ue)}};default:return ie}}(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(ge,Z)}receiveChannelMessageChunk(z,Z){const te=this.reassemblyTable.get(Z.id)||[];if(te.push(Z),te.length===Z.total){const ge=function(ie){const he=ie.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 ge&&this.receiveChannelMessage(z,ge),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,ge;const{config:ie}=this,{baseConfig:he}=ie,{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,ue=(te=Z.payload.streamsInfo)===null||te===void 0?void 0:te.timestamp;return!!ue&&(fe==null||fe.updateRemoteMessagesCounts(Z),(ge=he.onStreamsInfoUpdate)===null||ge===void 0||ge.call(he,de,ue),!0);case"stream-control":return!0;default:return!1}}sendSystemMessage(z,Z){var te;const{localUserId:ge,localPeerId:ie}=this.config.baseConfig;if(z.readyState!=="open")return;const he={entityId:ge!=null?ge:ie,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(ge,ie){function he(fe){try{me(te.next(fe))}catch(ue){ie(ue)}}function de(fe){try{me(te.throw(fe))}catch(ue){ie(ue)}}function me(fe){var ue;fe.done?ge(fe.value):(ue=fe.value,ue instanceof Z?ue:new Z(function(_e){_e(ue)})).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 ge=this.getActiveConnection(z);ge?ge.isReady()?ge.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,ge,ie;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:ue}=this;if(!me||!fe||!ue)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(ue,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=(ge=Pe==null?void 0:Pe.getSessionId())===null||ge===void 0?void 0:ge.getValue(),De=(ie=Pe==null?void 0:Pe.getSessionCreatedTimestamp())===null||ie===void 0?void 0:ie.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 ge=new b(z),ie=new ee(yield this.createRTCPeerConnection([]),{baseConfig:{isOffer:!0,isLan:!0,receive:(fe,ue)=>this.config.receive(fe,ue),onStreamsInfoUpdate:this.config.onStreamsInfoUpdate?(fe,ue)=>{var _e,Se;return(Se=(_e=this.config).onStreamsInfoUpdate)===null||Se===void 0?void 0:Se.call(_e,fe,ue)}: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 ie.getLanOffer();if(!he)return A.a.warn("Could not generate LAN offer"),!1;const de=yield ge.postLanRtcOffer({offer:JSON.stringify(he)}),me=new RTCSessionDescription(JSON.parse(de.answer));return yield ie.handleLanAnswer(me),this.localConnections.push(ie),Object(T.v4)()})}getConnections(){return[...this.connections,...this.localConnections]}createCustomDataChannel(z,Z,te,ge,ie){const he=this.getActiveConnection(z);if(he&&this.isConnectionInitiator.has(he)){const me=he.peerConnection.createDataChannel("custom."+Z,te);return ge&&(me.binaryType="arraybuffer"),ie(z,me),()=>{}}const de=(me,fe)=>{z===me&&fe.label==="custom."+Z&&ie(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(ie){A.a.warn("Error when getting peers",{error:ie})}}))();if(!Z)return[];const te=Z.getPeersList();if(!te)return[];const ge=ie=>{var he,de;return(de=(he=ie.getPeerCreatedTimestamp())===null||he===void 0?void 0:he.getValue())!==null&&de!==void 0?de:0};return te.sort((ie,he)=>ge(he)-ge(ie)).map(ie=>J(ie))})}getSessions(){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(ie){A.a.warn("Error when getting peers",{error:ie})}}))();if(!Z)return{};const te=Z.getPeersList(),ge={};for(const ie of te)ge[ie.getPeerId()]=ie.getSessionIdsList();return ge})}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 ge=new D.DeletePeerRequest;ge.setPeerId(Z.getPeerId()),yield te.deletePeer(ge,yield this.getMetadata({}))}catch(ge){return void A.a.warn("Error deleting local peer",{error:ge})}}))()})}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(ge){throw new Error(`Was not able to create peer: ${JSON.stringify(ge)}`)}}))(),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:ge}=this;ge&&ge.cancel();const ie=new D.ReceiveSignalStreamRequest;ie.setPeerId(Z.getPeerId());const he=yield(()=>re(this,void 0,void 0,function*(){try{return z.receiveSignalStream(ie,yield this.getMetadata({hasDeadline:!1}))}catch(de){throw new Error(`Unable to create receive signal stream: ${JSON.stringify(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,ue,_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:(ue=Z.getUserId())===null||ue===void 0?void 0:ue.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 ge=Z==null?void 0:Z.rtcIceTransportPolicy,ie=Z==null?void 0:Z.rtcIceServerProtocol,he=(fe,ue)=>typeof fe=="string"?fe.endsWith(`transport=${ue}`):fe.some(_e=>_e.endsWith(`transport=${ue}`)),de=z.filter(fe=>{return ge!=="relay"||(typeof(ue=fe.urls)=="string"?ue.startsWith("turn:"):ue.some(_e=>_e.startsWith("turn:")));var ue}).filter(fe=>ie!=="udp"||he(fe.urls,"udp")).filter(fe=>ie!=="tcp"||he(fe.urls,"tcp")),me=(te=this.config.alternateRTCPeerConnection)!==null&&te!==void 0?te:window.RTCPeerConnection;if(!me)throw new Error("RTCPeerConnection class not found. WebRTC must be enabled.");return new me(Object.assign({iceServers:de,iceTransportPolicy:ge},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,ge=this.connections.filter(de=>de.getSessionId).map(de=>M(de.getSessionId()));te.setSessionIdsList(ge);const ie=new D.RefreshPeerRequest;ie.setPeer(te);try{yield Z.refreshPeer(ie,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 ge=(yield this.config.signalingClient.getIceServers(new D.GetIceServersRequest,yield this.getMetadata({}))).getIceServers();this.iceServers=JSON.parse(ge),this.iceServersLastUpdate=te}catch(ge){A.a.warn("Error in updateIceServers",{error:ge})}})}setupHandlers(z){const{peerConnection:Z}=z,te=z.getSessionCreatedTimestamp();Z.onconnectionstatechange=()=>re(this,void 0,void 0,function*(){const ge=Z.connectionState;if(te)switch(ge){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:ge}=z,ie=ge===!1?void 0:new Date().getTime()+te;return{authorization:yield Z(),deadline:ie}})}}},,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 envDev=urlParams$1.get("formant_dev");envDev&&(FORMANT_API_URL="https://api-dev.formant.io");const envStage=urlParams$1.get("formant_stage");envStage&&(FORMANT_API_URL="https://api-stage.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 Ee=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 Ee.loginWithToken(i.authentication.accessToken,i.authentication.refreshToken),i.authentication}catch(n){return Ee.waitingForAuth.forEach(i=>i(!1)),Ee.waitingForAuth=[],Promise.reject(n)}}static async loginWithToken(t,r){const n=JSON.parse(atob(t.split(".")[1]));try{let i;if(Ee.isShareToken=n["formant:claims"]&&n["formant:claims"].type=="share",n["formant:claims"]&&(Ee.currentOrganization=n["formant:claims"].organizationId),n["custom:organization_id"]&&(Ee.currentOrganization=n["custom:organization_id"]),Ee.isShareToken||(i=n.sub),n["formant:claims"]&&n["formant:claims"].userId&&(i=n["formant:claims"].userId),i){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);Ee.currentUser=s}Ee.token=t,Ee.waitingForAuth.forEach(g=>g(!0))}catch(i){console.error(i),Ee.waitingForAuth.forEach(g=>g(!1))}Ee.waitingForAuth=[],r&&(Ee.refreshToken=r,setInterval(async()=>{if(Ee.refreshToken){const g=await(await fetch(`${FORMANT_API_URL}/v1/admin/auth/refresh`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({refreshToken:Ee.refreshToken})})).json();Ee.token=g.authentication.accessToken}},1e3*60*60))}static isAuthenticated(){return Ee.token!==void 0}static getCurrentUser(){return Ee.currentUser}static async waitTilAuthenticated(){return Ee.token!==void 0?!0:new Promise(t=>{Ee.waitingForAuth.push(function(r){t(r)})})}static async listenForRefresh(){App.addAccessTokenRefreshListener(t=>{this.loginWithToken(t)}),setInterval(async()=>{App.refreshAuthToken()},1e3*60*60)}};let Authentication=Ee;Ce(Authentication,"token"),Ce(Authentication,"refreshToken"),Ce(Authentication,"currentUser"),Ce(Authentication,"currentOrganization"),Ce(Authentication,"isShareToken",!1),Ce(Authentication,"defaultDeviceId"),Ce(Authentication,"waitingForAuth",[]);class DataChannel{constructor(t){Ce(this,"ready",!1);Ce(this,"listeners",[]);Ce(this,"binaryListeners",[]);Ce(this,"error");Ce(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){Ce(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){Ce(this,"currentListeners",[]);Ce(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){Ce(this,"channel");Ce(this,"requestIdToResponseMap",new Map);this.device=t,this.channel_name=r,this.timeout=n}}class BinaryRequestDataChannel extends RequestDataChannel{constructor(){super(...arguments);Ce(this,"RESPONSE_SUCCESS_BYTE",0);Ce(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){Ce(this,"rtcClient");Ce(this,"realtimeListeners",[]);Ce(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 isInRealtimeSession(){let t=await Fleet.getPeers(),r=await Fleet.getRealtimeSessions(),n=t.find(i=>i.deviceId===this.id);return n?r[n.id].length>0:!1}async getAvailableCommands(){return(await(await fetch(`${FORMANT_API_URL}/v1/admin/command-templates/`,{method:"GET",headers:{"Content-Type":"application/json",Authorization:"Bearer "+Authentication.token}})).json()).items.map(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 i=(await(await fetch(`${FORMANT_API_URL}/v1/admin/device-details/query`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:"Bearer "+Authentication.token}})).json()).items.find(s=>s.id===Ae.defaultDeviceId).name,g=new Device(Ae.defaultDeviceId,i,defined(Authentication.currentOrganization));return Ae.knownContext.push(new WeakRef(g)),g}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 getPeers(){if(!Authentication.token)throw new Error("Not authenticated");return await 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:()=>{}}).getPeers()}static async getRealtimeSessions(){if(!Authentication.token)throw new Error("Not authenticated");return await 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:()=>{}}).getSessions()}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]}static async queryTelemetry(t){if(!Authentication.token)throw new Error("Not authenticated");return(await(await fetch(`${FORMANT_API_URL}/v1/queries/queries`,{method:"POST",body:JSON.stringify(t),headers:{"Content-Type":"application/json",Authorization:"Bearer "+Authentication.token}})).json()).items}static async queryEvents(t){if(!Authentication.token)throw new Error("Not authenticated");return(await(await fetch(`${FORMANT_API_URL}/v1/admin/events/query`,{method:"POST",body:JSON.stringify(t),headers:{"Content-Type":"application/json",Authorization:"Bearer "+Authentication.token}})).json()).items}};let Fleet=Ae;Ce(Fleet,"defaultDeviceId"),Ce(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"});
|
|
@@ -1,5 +1,9 @@
|
|
|
1
1
|
import { Device } from "./Device";
|
|
2
2
|
import { IRtcPeer } from "@formant/realtime-sdk/dist/model/IRtcPeer";
|
|
3
|
+
import { IEventQuery } from "./model/IEventQuery";
|
|
4
|
+
import { IEvent } from "./model/IEvent";
|
|
5
|
+
import { IQuery } from "./model/IQuery";
|
|
6
|
+
import { IStreamData } from "./model/IStreamData";
|
|
3
7
|
export interface User {
|
|
4
8
|
firstName: string;
|
|
5
9
|
lastName: string;
|
|
@@ -34,4 +38,6 @@ export declare class Fleet {
|
|
|
34
38
|
[key in string]: string[];
|
|
35
39
|
}): Promise<TelemetryResult[]>;
|
|
36
40
|
static getFileUrl(uuid: string): Promise<string>;
|
|
41
|
+
static queryTelemetry(query: IQuery): Promise<IStreamData<keyof import("./model/IStreamTypeMap").IStreamTypeMap>[]>;
|
|
42
|
+
static queryEvents(query: IEventQuery): Promise<IEvent[]>;
|
|
37
43
|
}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export declare type AggregateLevel = "year" | "month" | "week" | "day" | "hour" | "minute" | "second";
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export declare type EventSortableColumn = "device.name" | "time";
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export declare type HexRgbColor = string;
|
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
import { IBaseEvent } from "./IBaseEvent";
|
|
2
|
+
import { IsoDate } from "./IsoDate";
|
|
3
|
+
import { ISpreadsheetIdRange } from "./ISpreadsheetIdRange";
|
|
4
|
+
import { ITaggedUsers } from "./ITaggedUsers";
|
|
5
|
+
import { Uuid } from "./Uuid";
|
|
6
|
+
export interface IAnnotation extends IBaseEvent<"annotation"> {
|
|
7
|
+
editedAt?: IsoDate;
|
|
8
|
+
userId: Uuid;
|
|
9
|
+
annotationTemplateId: Uuid;
|
|
10
|
+
taggedUsers?: ITaggedUsers | null;
|
|
11
|
+
publishedTo?: ISpreadsheetIdRange;
|
|
12
|
+
note?: string | null;
|
|
13
|
+
}
|
|
@@ -0,0 +1,19 @@
|
|
|
1
|
+
import { EventType } from "./EventType";
|
|
2
|
+
import { IBaseEntity } from "./IBaseEntity";
|
|
3
|
+
import { IsoDate } from "./IsoDate";
|
|
4
|
+
import { ITags } from "./ITags";
|
|
5
|
+
import { StreamType } from "./StreamType";
|
|
6
|
+
import { Uuid } from "./Uuid";
|
|
7
|
+
export interface IBaseEvent<T extends EventType = EventType> extends IBaseEntity {
|
|
8
|
+
type?: T;
|
|
9
|
+
organizationId?: Uuid;
|
|
10
|
+
time: IsoDate;
|
|
11
|
+
endTime?: IsoDate | null;
|
|
12
|
+
message: string;
|
|
13
|
+
viewed?: boolean;
|
|
14
|
+
deviceId?: Uuid;
|
|
15
|
+
streamName?: string;
|
|
16
|
+
streamType?: StreamType;
|
|
17
|
+
tags?: ITags;
|
|
18
|
+
notificationEnabled?: boolean;
|
|
19
|
+
}
|