@formant/data-sdk 0.0.127 → 0.0.129

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.
@@ -4,6 +4,7 @@ var __publicField = (obj, key, value) => {
4
4
  __defNormalProp(obj, typeof key !== "symbol" ? key + "" : key, value);
5
5
  return value;
6
6
  };
7
+ import { startOfMinute, addMinutes, roundToNearestMinutes, addSeconds } from "date-fns";
7
8
  var dist = { exports: {} };
8
9
  /*! For license information please see index.js.LICENSE.txt */
9
10
  (function(module, exports) {
@@ -20701,106 +20702,31 @@ const _Fleet$1 = class {
20701
20702
  });
20702
20703
  return devices;
20703
20704
  }
20705
+ static async getAnnotationCount(query) {
20706
+ const tagKey = query.tagKey;
20707
+ delete query.tagKey, delete query.aggregate;
20708
+ const annotations = await this.queryEvents({
20709
+ ...query,
20710
+ eventTypes: ["annotation"]
20711
+ });
20712
+ const validAnnotations = annotations.filter(
20713
+ (_) => !!_.tags && Object.keys(_.tags).includes(tagKey)
20714
+ );
20715
+ const annotationCounter = validAnnotations.reduce((prev, current) => {
20716
+ const value = current.tags[tagKey];
20717
+ if (value in prev) {
20718
+ prev[value] += 1;
20719
+ return prev;
20720
+ }
20721
+ prev[value] = 1;
20722
+ return prev;
20723
+ }, {});
20724
+ return annotationCounter;
20725
+ }
20704
20726
  };
20705
20727
  let Fleet$1 = _Fleet$1;
20706
20728
  __publicField(Fleet$1, "defaultDeviceId");
20707
20729
  __publicField(Fleet$1, "knownContext", []);
20708
- function toInteger(dirtyNumber) {
20709
- if (dirtyNumber === null || dirtyNumber === true || dirtyNumber === false) {
20710
- return NaN;
20711
- }
20712
- var number = Number(dirtyNumber);
20713
- if (isNaN(number)) {
20714
- return number;
20715
- }
20716
- return number < 0 ? Math.ceil(number) : Math.floor(number);
20717
- }
20718
- function requiredArgs(required, args) {
20719
- if (args.length < required) {
20720
- throw new TypeError(required + " argument" + (required > 1 ? "s" : "") + " required, but only " + args.length + " present");
20721
- }
20722
- }
20723
- function _typeof(obj) {
20724
- "@babel/helpers - typeof";
20725
- if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") {
20726
- _typeof = function _typeof2(obj2) {
20727
- return typeof obj2;
20728
- };
20729
- } else {
20730
- _typeof = function _typeof2(obj2) {
20731
- return obj2 && typeof Symbol === "function" && obj2.constructor === Symbol && obj2 !== Symbol.prototype ? "symbol" : typeof obj2;
20732
- };
20733
- }
20734
- return _typeof(obj);
20735
- }
20736
- function toDate(argument) {
20737
- requiredArgs(1, arguments);
20738
- var argStr = Object.prototype.toString.call(argument);
20739
- if (argument instanceof Date || _typeof(argument) === "object" && argStr === "[object Date]") {
20740
- return new Date(argument.getTime());
20741
- } else if (typeof argument === "number" || argStr === "[object Number]") {
20742
- return new Date(argument);
20743
- } else {
20744
- if ((typeof argument === "string" || argStr === "[object String]") && typeof console !== "undefined") {
20745
- console.warn("Starting with v2.0.0-beta.1 date-fns doesn't accept strings as date arguments. Please use `parseISO` to parse strings. See: https://github.com/date-fns/date-fns/blob/master/docs/upgradeGuide.md#string-arguments");
20746
- console.warn(new Error().stack);
20747
- }
20748
- return new Date(NaN);
20749
- }
20750
- }
20751
- function addMilliseconds(dirtyDate, dirtyAmount) {
20752
- requiredArgs(2, arguments);
20753
- var timestamp = toDate(dirtyDate).getTime();
20754
- var amount = toInteger(dirtyAmount);
20755
- return new Date(timestamp + amount);
20756
- }
20757
- var MILLISECONDS_IN_MINUTE = 6e4;
20758
- function addMinutes(dirtyDate, dirtyAmount) {
20759
- requiredArgs(2, arguments);
20760
- var amount = toInteger(dirtyAmount);
20761
- return addMilliseconds(dirtyDate, amount * MILLISECONDS_IN_MINUTE);
20762
- }
20763
- function addSeconds(dirtyDate, dirtyAmount) {
20764
- requiredArgs(2, arguments);
20765
- var amount = toInteger(dirtyAmount);
20766
- return addMilliseconds(dirtyDate, amount * 1e3);
20767
- }
20768
- var roundingMap = {
20769
- ceil: Math.ceil,
20770
- round: Math.round,
20771
- floor: Math.floor,
20772
- trunc: function trunc(value) {
20773
- return value < 0 ? Math.ceil(value) : Math.floor(value);
20774
- }
20775
- };
20776
- var defaultRoundingMethod = "trunc";
20777
- function getRoundingMethod(method) {
20778
- return method ? roundingMap[method] : roundingMap[defaultRoundingMethod];
20779
- }
20780
- function startOfMinute(dirtyDate) {
20781
- requiredArgs(1, arguments);
20782
- var date = toDate(dirtyDate);
20783
- date.setSeconds(0, 0);
20784
- return date;
20785
- }
20786
- function roundToNearestMinutes(dirtyDate, options) {
20787
- var _options$nearestTo;
20788
- if (arguments.length < 1) {
20789
- throw new TypeError("1 argument required, but only none provided present");
20790
- }
20791
- var nearestTo = toInteger((_options$nearestTo = options === null || options === void 0 ? void 0 : options.nearestTo) !== null && _options$nearestTo !== void 0 ? _options$nearestTo : 1);
20792
- if (nearestTo < 1 || nearestTo > 30) {
20793
- throw new RangeError("`options.nearestTo` must be between 1 and 30");
20794
- }
20795
- var date = toDate(dirtyDate);
20796
- var seconds = date.getSeconds();
20797
- var minutes = date.getMinutes() + seconds / 60;
20798
- var roundingMethod = getRoundingMethod(options === null || options === void 0 ? void 0 : options.roundingMethod);
20799
- var roundedMinutes = roundingMethod(minutes / nearestTo) * nearestTo;
20800
- var remainderMinutes = minutes % nearestTo;
20801
- var addedMinutes = Math.round(remainderMinutes / nearestTo) * nearestTo;
20802
- return new Date(date.getFullYear(), date.getMonth(), date.getDate(), date.getHours(), roundedMinutes + addedMinutes);
20803
- }
20804
20730
  const millisecond = 1;
20805
20731
  const second = 1e3;
20806
20732
  const minute = 60 * second;
@@ -21636,6 +21562,27 @@ const _Fleet = class {
21636
21562
  });
21637
21563
  return devices;
21638
21564
  }
21565
+ static async getAnnotationCount(query) {
21566
+ const tagKey = query.tagKey;
21567
+ delete query.tagKey, delete query.aggregate;
21568
+ const annotations = await this.queryEvents({
21569
+ ...query,
21570
+ eventTypes: ["annotation"]
21571
+ });
21572
+ const validAnnotations = annotations.filter(
21573
+ (_) => !!_.tags && Object.keys(_.tags).includes(tagKey)
21574
+ );
21575
+ const annotationCounter = validAnnotations.reduce((prev, current) => {
21576
+ const value = current.tags[tagKey];
21577
+ if (value in prev) {
21578
+ prev[value] += 1;
21579
+ return prev;
21580
+ }
21581
+ prev[value] = 1;
21582
+ return prev;
21583
+ }, {});
21584
+ return annotationCounter;
21585
+ }
21639
21586
  };
21640
21587
  let Fleet = _Fleet;
21641
21588
  __publicField(Fleet, "defaultDeviceId");
@@ -1,4 +1,4 @@
1
- (function(He,Pe){typeof exports=="object"&&typeof module!="undefined"?Pe(exports):typeof define=="function"&&define.amd?define(["exports"],Pe):(He=typeof globalThis!="undefined"?globalThis:He||self,Pe(He.FormantDataSDK={}))})(this,function(exports){"use strict";var an=Object.defineProperty;var ln=(He,Pe,Xe)=>Pe in He?an(He,Pe,{enumerable:!0,configurable:!0,writable:!0,value:Xe}):He[Pe]=Xe;var Ae=(He,Pe,Xe)=>(ln(He,typeof Pe!="symbol"?Pe+"":Pe,Xe),Xe);var dist={exports:{}};/*! For license information please see index.js.LICENSE.txt */(function(module,exports){(function(e,t){module.exports=t()})(window,function(){return function(e){function t(u){for(var m,R,E=u[0],y=u[1],g=0,_=[];g<E.length;g++)R=E[g],Object.prototype.hasOwnProperty.call(r,R)&&r[R]&&_.push(r[R][0]),r[R]=0;for(m in y)Object.prototype.hasOwnProperty.call(y,m)&&(e[m]=y[m]);for(c&&c(u);_.length;)_.shift()()}var n={},r={0:0};function o(u){if(n[u])return n[u].exports;var m=n[u]={i:u,l:!1,exports:{}};return e[u].call(m.exports,m,m.exports,o),m.l=!0,m.exports}o.e=function(){return Promise.resolve()},o.m=e,o.c=n,o.d=function(u,m,R){o.o(u,m)||Object.defineProperty(u,m,{enumerable:!0,get:R})},o.r=function(u){typeof Symbol!="undefined"&&Symbol.toStringTag&&Object.defineProperty(u,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(u,"__esModule",{value:!0})},o.t=function(u,m){if(1&m&&(u=o(u)),8&m||4&m&&typeof u=="object"&&u&&u.__esModule)return u;var R=Object.create(null);if(o.r(R),Object.defineProperty(R,"default",{enumerable:!0,value:u}),2&m&&typeof u!="string")for(var E in u)o.d(R,E,function(y){return u[y]}.bind(null,E));return R},o.n=function(u){var m=u&&u.__esModule?function(){return u.default}:function(){return u};return o.d(m,"a",m),m},o.o=function(u,m){return Object.prototype.hasOwnProperty.call(u,m)},o.p="",o.oe=function(u){throw console.error(u),u};var l=window.webpackJsonpFormantRealtimeSDK=window.webpackJsonpFormantRealtimeSDK||[],s=l.push.bind(l);l.push=t,l=l.slice();for(var i=0;i<l.length;i++)t(l[i]);var c=s;return o(o.s=228)}([function(e,t,n){n.d(t,"a",function(){return H});var r=n(14),o=n.n(r),l=n(18),s=n(56),i=n(19);const c=Math.pow(2,20),u=c;function m(S,U){if(U.length<S)throw new TypeError(S+" argument"+(S>1?"s":"")+" required, but only "+U.length+" present")}function R(S){if(S===null||S===!0||S===!1)return NaN;var U=Number(S);return isNaN(U)?U:U<0?Math.ceil(U):Math.floor(U)}var E={dateTimeDelimiter:/[T ]/,timeZoneDelimiter:/[Z ]/i,timezone:/([Z+-].*)$/},y=/^-?(?:(\d{3})|(\d{2})(?:-?(\d{2}))?|W(\d{2})(?:-?(\d{1}))?|)$/,g=/^(\d{2}(?:[.,]\d*)?)(?::?(\d{2}(?:[.,]\d*)?))?(?::?(\d{2}(?:[.,]\d*)?))?$/,_=/^([+-])(\d{2})(?::?(\d{2}))?$/;function T(S){var U,J={},$=S.split(E.dateTimeDelimiter);if($.length>2)return J;if(/:/.test($[0])?U=$[0]:(J.date=$[0],U=$[1],E.timeZoneDelimiter.test(J.date)&&(J.date=S.split(E.timeZoneDelimiter)[0],U=S.substr(J.date.length,S.length))),U){var ne=E.timezone.exec(U);ne?(J.time=U.replace(ne[1],""),J.timezone=ne[1]):J.time=U}return J}function L(S,U){var J=new RegExp("^(?:(\\d{4}|[+-]\\d{"+(4+U)+"})|(\\d{2}|[+-]\\d{"+(2+U)+"})$)"),$=S.match(J);if(!$)return{year:NaN,restDateString:""};var ne=$[1]?parseInt($[1]):null,se=$[2]?parseInt($[2]):null;return{year:se===null?ne:100*se,restDateString:S.slice(($[1]||$[2]).length)}}function z(S,U){if(U===null)return new Date(NaN);var J=S.match(y);if(!J)return new Date(NaN);var $=!!J[4],ne=M(J[1]),se=M(J[2])-1,ge=M(J[3]),ve=M(J[4]),Oe=M(J[5])-1;if($)return function(Ce,Ee,Te){return Ee>=1&&Ee<=53&&Te>=0&&Te<=6}(0,ve,Oe)?function(Ce,Ee,Te){var De=new Date(0);De.setUTCFullYear(Ce,0,4);var qe=De.getUTCDay()||7,et=7*(Ee-1)+Te+1-qe;return De.setUTCDate(De.getUTCDate()+et),De}(U,ve,Oe):new Date(NaN);var Se=new Date(0);return function(Ce,Ee,Te){return Ee>=0&&Ee<=11&&Te>=1&&Te<=(Y[Ee]||(Z(Ce)?29:28))}(U,se,ge)&&function(Ce,Ee){return Ee>=1&&Ee<=(Z(Ce)?366:365)}(U,ne)?(Se.setUTCFullYear(U,se,Math.max(ne,ge)),Se):new Date(NaN)}function M(S){return S?parseInt(S):1}function A(S){var U=S.match(g);if(!U)return NaN;var J=f(U[1]),$=f(U[2]),ne=f(U[3]);return function(se,ge,ve){return se===24?ge===0&&ve===0:ve>=0&&ve<60&&ge>=0&&ge<60&&se>=0&&se<25}(J,$,ne)?36e5*J+6e4*$+1e3*ne:NaN}function f(S){return S&&parseFloat(S.replace(",","."))||0}function O(S){if(S==="Z")return 0;var U=S.match(_);if(!U)return 0;var J=U[1]==="+"?-1:1,$=parseInt(U[2]),ne=U[3]&&parseInt(U[3])||0;return function(se,ge){return ge>=0&&ge<=59}(0,ne)?J*(36e5*$+6e4*ne):NaN}var Y=[31,null,31,30,31,30,31,31,30,31,30,31];function Z(S){return S%400==0||S%4==0&&S%100!=0}function d(S){return m(1,arguments),S instanceof Date||typeof S=="object"&&Object.prototype.toString.call(S)==="[object Date]"}function p(S){m(1,arguments);var U=Object.prototype.toString.call(S);return S instanceof Date||typeof S=="object"&&U==="[object Date]"?new Date(S.getTime()):typeof S=="number"||U==="[object Number]"?new Date(S):(typeof S!="string"&&U!=="[object String]"||typeof console=="undefined"||(console.warn("Starting with v2.0.0-beta.1 date-fns doesn't accept strings as date arguments. Please use `parseISO` to parse strings. See: https://github.com/date-fns/date-fns/blob/master/docs/upgradeGuide.md#string-arguments"),console.warn(new Error().stack)),new Date(NaN))}function C(S){const U=function(J,$){var ne;m(1,arguments);var se=R((ne=$==null?void 0:$.additionalDigits)!==null&&ne!==void 0?ne:2);if(se!==2&&se!==1&&se!==0)throw new RangeError("additionalDigits must be 0, 1 or 2");if(typeof J!="string"&&Object.prototype.toString.call(J)!=="[object String]")return new Date(NaN);var ge,ve=T(J);if(ve.date){var Oe=L(ve.date,se);ge=z(Oe.restDateString,Oe.year)}if(!ge||isNaN(ge.getTime()))return new Date(NaN);var Se,Ce=ge.getTime(),Ee=0;if(ve.time&&(Ee=A(ve.time),isNaN(Ee)))return new Date(NaN);if(!ve.timezone){var Te=new Date(Ce+Ee),De=new Date(0);return De.setFullYear(Te.getUTCFullYear(),Te.getUTCMonth(),Te.getUTCDate()),De.setHours(Te.getUTCHours(),Te.getUTCMinutes(),Te.getUTCSeconds(),Te.getUTCMilliseconds()),De}return Se=O(ve.timezone),isNaN(Se)?new Date(NaN):new Date(Ce+Ee+Se)}(S);if(!function(J){if(m(1,arguments),!d(J)&&typeof J!="number")return!1;var $=p(J);return!isNaN(Number($))}(U))throw new Error(`Invalid ISO 8601 date string (${S})`);return U}var b=n(4),P=n(34);function F(S){return o()(S,{cycles:!0})}var D=function(S,U){var J={};for(var $ in S)Object.prototype.hasOwnProperty.call(S,$)&&U.indexOf($)<0&&(J[$]=S[$]);if(S!=null&&typeof Object.getOwnPropertySymbols=="function"){var ne=0;for($=Object.getOwnPropertySymbols(S);ne<$.length;ne++)U.indexOf($[ne])<0&&Object.prototype.propertyIsEnumerable.call(S,$[ne])&&(J[$[ne]]=S[$[ne]])}return J};function I(S,U={}){const J=ve=>U.redacted!==!1?Object(P.a)(ve):ve;if(!S.stack)return{message:F(J(S))};const{name:$,message:ne,stack:se}=S,ge=D(S,["name","message","stack"]);return{name:$,message:ne!==void 0?ne:F(J(S)),stack:se,meta:ge&&Object.keys(ge).length===0?void 0:J(ge)}}function N(S,U={}){const{message:J,stack:$,meta:ne}=I(S,U);return`${$||J||""}${ne&&Object.keys(ne).length>0?` -- ${F(ne)}`:""}`}var B=n(39),w=n(103),h=n.n(w),k=function(S,U,J,$){return new(J||(J=Promise))(function(ne,se){function ge(Se){try{Oe($.next(Se))}catch(Ce){se(Ce)}}function ve(Se){try{Oe($.throw(Se))}catch(Ce){se(Ce)}}function Oe(Se){var Ce;Se.done?ne(Se.value):(Ce=Se.value,Ce instanceof J?Ce:new J(function(Ee){Ee(Ce)})).then(ge,ve)}Oe(($=$.apply(S,U||[])).next())})},V=function(S,U){var J={};for(var $ in S)Object.prototype.hasOwnProperty.call(S,$)&&U.indexOf($)<0&&(J[$]=S[$]);if(S!=null&&typeof Object.getOwnPropertySymbols=="function"){var ne=0;for($=Object.getOwnPropertySymbols(S);ne<$.length;ne++)U.indexOf($[ne])<0&&Object.prototype.propertyIsEnumerable.call(S,$[ne])&&(J[$[ne]]=S[$[ne]])}return J};class X extends h.a{constructor(U,J){super(),this.endpoint=U,this.metadata=J,this.logClient=this.getLogClient()}getLogClient(){return k(this,void 0,void 0,function*(){const{LogClient:U}=yield Promise.resolve().then(n.bind(null,231));return new U(this.endpoint)})}log(U,J){return k(this,void 0,void 0,function*(){const{level:$,message:ne,error:se}=U,ge=V(U,["level","message","error"]);this.emit("logged");try{yield(yield this.logClient).log([{timestamp:new Date().toISOString(),level:$,message:`${ne}`.substring(0,1e3),error:se!==void 0?I(se):void 0,meta:Object.assign(Object.assign({},ge),this.metadata)}])}catch(ve){console.error(`Failed to log to log-api: ${N(ve)}`)}J()})}}var Q=function(S,U){var J={};for(var $ in S)Object.prototype.hasOwnProperty.call(S,$)&&U.indexOf($)<0&&(J[$]=S[$]);if(S!=null&&typeof Object.getOwnPropertySymbols=="function"){var ne=0;for($=Object.getOwnPropertySymbols(S);ne<$.length;ne++)U.indexOf($[ne])<0&&Object.prototype.propertyIsEnumerable.call(S,$[ne])&&(J[$[ne]]=S[$[ne]])}return J};const te={app:b.a,namespace:b.i,buildTag:b.b,instanceId:B.a},q=b.e?i.format.printf(S=>{var{timestamp:U,level:J,message:$,error:ne}=S,se=Q(S,["timestamp","level","message","error"]);const ge=Object.assign(Object.assign({timestamp:U?C(U).getTime():new Date().getTime(),level:J.toUpperCase(),message:$},ne?{error:I(ne)}:{}),{meta:Object.assign(Object.assign({},te),se)});return o()(ge,{cycles:!0})}):i.format.printf(S=>{var{timestamp:U,level:J,message:$,error:ne}=S,se=Q(S,["timestamp","level","message","error"]);let ge=`${U||new Date().toISOString()} ${J.toUpperCase()}: ${$} `;return Object.keys(se).length>0&&(ge+=o()(se,{cycles:!0})),ne&&(ge+=`
1
+ (function(He,Pe){typeof exports=="object"&&typeof module!="undefined"?Pe(exports,require("date-fns")):typeof define=="function"&&define.amd?define(["exports","date-fns"],Pe):(He=typeof globalThis!="undefined"?globalThis:He||self,Pe(He.FormantDataSDK={},He.dateFns))})(this,function(exports,dateFns){"use strict";var an=Object.defineProperty;var ln=(He,Pe,Xe)=>Pe in He?an(He,Pe,{enumerable:!0,configurable:!0,writable:!0,value:Xe}):He[Pe]=Xe;var Ae=(He,Pe,Xe)=>(ln(He,typeof Pe!="symbol"?Pe+"":Pe,Xe),Xe);var dist={exports:{}};/*! For license information please see index.js.LICENSE.txt */(function(module,exports){(function(e,t){module.exports=t()})(window,function(){return function(e){function t(u){for(var m,R,E=u[0],y=u[1],g=0,_=[];g<E.length;g++)R=E[g],Object.prototype.hasOwnProperty.call(r,R)&&r[R]&&_.push(r[R][0]),r[R]=0;for(m in y)Object.prototype.hasOwnProperty.call(y,m)&&(e[m]=y[m]);for(c&&c(u);_.length;)_.shift()()}var n={},r={0:0};function o(u){if(n[u])return n[u].exports;var m=n[u]={i:u,l:!1,exports:{}};return e[u].call(m.exports,m,m.exports,o),m.l=!0,m.exports}o.e=function(){return Promise.resolve()},o.m=e,o.c=n,o.d=function(u,m,R){o.o(u,m)||Object.defineProperty(u,m,{enumerable:!0,get:R})},o.r=function(u){typeof Symbol!="undefined"&&Symbol.toStringTag&&Object.defineProperty(u,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(u,"__esModule",{value:!0})},o.t=function(u,m){if(1&m&&(u=o(u)),8&m||4&m&&typeof u=="object"&&u&&u.__esModule)return u;var R=Object.create(null);if(o.r(R),Object.defineProperty(R,"default",{enumerable:!0,value:u}),2&m&&typeof u!="string")for(var E in u)o.d(R,E,function(y){return u[y]}.bind(null,E));return R},o.n=function(u){var m=u&&u.__esModule?function(){return u.default}:function(){return u};return o.d(m,"a",m),m},o.o=function(u,m){return Object.prototype.hasOwnProperty.call(u,m)},o.p="",o.oe=function(u){throw console.error(u),u};var l=window.webpackJsonpFormantRealtimeSDK=window.webpackJsonpFormantRealtimeSDK||[],s=l.push.bind(l);l.push=t,l=l.slice();for(var i=0;i<l.length;i++)t(l[i]);var c=s;return o(o.s=228)}([function(e,t,n){n.d(t,"a",function(){return H});var r=n(14),o=n.n(r),l=n(18),s=n(56),i=n(19);const c=Math.pow(2,20),u=c;function m(S,U){if(U.length<S)throw new TypeError(S+" argument"+(S>1?"s":"")+" required, but only "+U.length+" present")}function R(S){if(S===null||S===!0||S===!1)return NaN;var U=Number(S);return isNaN(U)?U:U<0?Math.ceil(U):Math.floor(U)}var E={dateTimeDelimiter:/[T ]/,timeZoneDelimiter:/[Z ]/i,timezone:/([Z+-].*)$/},y=/^-?(?:(\d{3})|(\d{2})(?:-?(\d{2}))?|W(\d{2})(?:-?(\d{1}))?|)$/,g=/^(\d{2}(?:[.,]\d*)?)(?::?(\d{2}(?:[.,]\d*)?))?(?::?(\d{2}(?:[.,]\d*)?))?$/,_=/^([+-])(\d{2})(?::?(\d{2}))?$/;function T(S){var U,J={},$=S.split(E.dateTimeDelimiter);if($.length>2)return J;if(/:/.test($[0])?U=$[0]:(J.date=$[0],U=$[1],E.timeZoneDelimiter.test(J.date)&&(J.date=S.split(E.timeZoneDelimiter)[0],U=S.substr(J.date.length,S.length))),U){var ne=E.timezone.exec(U);ne?(J.time=U.replace(ne[1],""),J.timezone=ne[1]):J.time=U}return J}function L(S,U){var J=new RegExp("^(?:(\\d{4}|[+-]\\d{"+(4+U)+"})|(\\d{2}|[+-]\\d{"+(2+U)+"})$)"),$=S.match(J);if(!$)return{year:NaN,restDateString:""};var ne=$[1]?parseInt($[1]):null,se=$[2]?parseInt($[2]):null;return{year:se===null?ne:100*se,restDateString:S.slice(($[1]||$[2]).length)}}function z(S,U){if(U===null)return new Date(NaN);var J=S.match(y);if(!J)return new Date(NaN);var $=!!J[4],ne=M(J[1]),se=M(J[2])-1,ge=M(J[3]),ve=M(J[4]),Oe=M(J[5])-1;if($)return function(Ce,Ee,Te){return Ee>=1&&Ee<=53&&Te>=0&&Te<=6}(0,ve,Oe)?function(Ce,Ee,Te){var De=new Date(0);De.setUTCFullYear(Ce,0,4);var qe=De.getUTCDay()||7,et=7*(Ee-1)+Te+1-qe;return De.setUTCDate(De.getUTCDate()+et),De}(U,ve,Oe):new Date(NaN);var Se=new Date(0);return function(Ce,Ee,Te){return Ee>=0&&Ee<=11&&Te>=1&&Te<=(Y[Ee]||(Z(Ce)?29:28))}(U,se,ge)&&function(Ce,Ee){return Ee>=1&&Ee<=(Z(Ce)?366:365)}(U,ne)?(Se.setUTCFullYear(U,se,Math.max(ne,ge)),Se):new Date(NaN)}function M(S){return S?parseInt(S):1}function A(S){var U=S.match(g);if(!U)return NaN;var J=f(U[1]),$=f(U[2]),ne=f(U[3]);return function(se,ge,ve){return se===24?ge===0&&ve===0:ve>=0&&ve<60&&ge>=0&&ge<60&&se>=0&&se<25}(J,$,ne)?36e5*J+6e4*$+1e3*ne:NaN}function f(S){return S&&parseFloat(S.replace(",","."))||0}function O(S){if(S==="Z")return 0;var U=S.match(_);if(!U)return 0;var J=U[1]==="+"?-1:1,$=parseInt(U[2]),ne=U[3]&&parseInt(U[3])||0;return function(se,ge){return ge>=0&&ge<=59}(0,ne)?J*(36e5*$+6e4*ne):NaN}var Y=[31,null,31,30,31,30,31,31,30,31,30,31];function Z(S){return S%400==0||S%4==0&&S%100!=0}function d(S){return m(1,arguments),S instanceof Date||typeof S=="object"&&Object.prototype.toString.call(S)==="[object Date]"}function p(S){m(1,arguments);var U=Object.prototype.toString.call(S);return S instanceof Date||typeof S=="object"&&U==="[object Date]"?new Date(S.getTime()):typeof S=="number"||U==="[object Number]"?new Date(S):(typeof S!="string"&&U!=="[object String]"||typeof console=="undefined"||(console.warn("Starting with v2.0.0-beta.1 date-fns doesn't accept strings as date arguments. Please use `parseISO` to parse strings. See: https://github.com/date-fns/date-fns/blob/master/docs/upgradeGuide.md#string-arguments"),console.warn(new Error().stack)),new Date(NaN))}function C(S){const U=function(J,$){var ne;m(1,arguments);var se=R((ne=$==null?void 0:$.additionalDigits)!==null&&ne!==void 0?ne:2);if(se!==2&&se!==1&&se!==0)throw new RangeError("additionalDigits must be 0, 1 or 2");if(typeof J!="string"&&Object.prototype.toString.call(J)!=="[object String]")return new Date(NaN);var ge,ve=T(J);if(ve.date){var Oe=L(ve.date,se);ge=z(Oe.restDateString,Oe.year)}if(!ge||isNaN(ge.getTime()))return new Date(NaN);var Se,Ce=ge.getTime(),Ee=0;if(ve.time&&(Ee=A(ve.time),isNaN(Ee)))return new Date(NaN);if(!ve.timezone){var Te=new Date(Ce+Ee),De=new Date(0);return De.setFullYear(Te.getUTCFullYear(),Te.getUTCMonth(),Te.getUTCDate()),De.setHours(Te.getUTCHours(),Te.getUTCMinutes(),Te.getUTCSeconds(),Te.getUTCMilliseconds()),De}return Se=O(ve.timezone),isNaN(Se)?new Date(NaN):new Date(Ce+Ee+Se)}(S);if(!function(J){if(m(1,arguments),!d(J)&&typeof J!="number")return!1;var $=p(J);return!isNaN(Number($))}(U))throw new Error(`Invalid ISO 8601 date string (${S})`);return U}var b=n(4),P=n(34);function F(S){return o()(S,{cycles:!0})}var D=function(S,U){var J={};for(var $ in S)Object.prototype.hasOwnProperty.call(S,$)&&U.indexOf($)<0&&(J[$]=S[$]);if(S!=null&&typeof Object.getOwnPropertySymbols=="function"){var ne=0;for($=Object.getOwnPropertySymbols(S);ne<$.length;ne++)U.indexOf($[ne])<0&&Object.prototype.propertyIsEnumerable.call(S,$[ne])&&(J[$[ne]]=S[$[ne]])}return J};function I(S,U={}){const J=ve=>U.redacted!==!1?Object(P.a)(ve):ve;if(!S.stack)return{message:F(J(S))};const{name:$,message:ne,stack:se}=S,ge=D(S,["name","message","stack"]);return{name:$,message:ne!==void 0?ne:F(J(S)),stack:se,meta:ge&&Object.keys(ge).length===0?void 0:J(ge)}}function N(S,U={}){const{message:J,stack:$,meta:ne}=I(S,U);return`${$||J||""}${ne&&Object.keys(ne).length>0?` -- ${F(ne)}`:""}`}var B=n(39),w=n(103),h=n.n(w),k=function(S,U,J,$){return new(J||(J=Promise))(function(ne,se){function ge(Se){try{Oe($.next(Se))}catch(Ce){se(Ce)}}function ve(Se){try{Oe($.throw(Se))}catch(Ce){se(Ce)}}function Oe(Se){var Ce;Se.done?ne(Se.value):(Ce=Se.value,Ce instanceof J?Ce:new J(function(Ee){Ee(Ce)})).then(ge,ve)}Oe(($=$.apply(S,U||[])).next())})},V=function(S,U){var J={};for(var $ in S)Object.prototype.hasOwnProperty.call(S,$)&&U.indexOf($)<0&&(J[$]=S[$]);if(S!=null&&typeof Object.getOwnPropertySymbols=="function"){var ne=0;for($=Object.getOwnPropertySymbols(S);ne<$.length;ne++)U.indexOf($[ne])<0&&Object.prototype.propertyIsEnumerable.call(S,$[ne])&&(J[$[ne]]=S[$[ne]])}return J};class X extends h.a{constructor(U,J){super(),this.endpoint=U,this.metadata=J,this.logClient=this.getLogClient()}getLogClient(){return k(this,void 0,void 0,function*(){const{LogClient:U}=yield Promise.resolve().then(n.bind(null,231));return new U(this.endpoint)})}log(U,J){return k(this,void 0,void 0,function*(){const{level:$,message:ne,error:se}=U,ge=V(U,["level","message","error"]);this.emit("logged");try{yield(yield this.logClient).log([{timestamp:new Date().toISOString(),level:$,message:`${ne}`.substring(0,1e3),error:se!==void 0?I(se):void 0,meta:Object.assign(Object.assign({},ge),this.metadata)}])}catch(ve){console.error(`Failed to log to log-api: ${N(ve)}`)}J()})}}var Q=function(S,U){var J={};for(var $ in S)Object.prototype.hasOwnProperty.call(S,$)&&U.indexOf($)<0&&(J[$]=S[$]);if(S!=null&&typeof Object.getOwnPropertySymbols=="function"){var ne=0;for($=Object.getOwnPropertySymbols(S);ne<$.length;ne++)U.indexOf($[ne])<0&&Object.prototype.propertyIsEnumerable.call(S,$[ne])&&(J[$[ne]]=S[$[ne]])}return J};const te={app:b.a,namespace:b.i,buildTag:b.b,instanceId:B.a},q=b.e?i.format.printf(S=>{var{timestamp:U,level:J,message:$,error:ne}=S,se=Q(S,["timestamp","level","message","error"]);const ge=Object.assign(Object.assign({timestamp:U?C(U).getTime():new Date().getTime(),level:J.toUpperCase(),message:$},ne?{error:I(ne)}:{}),{meta:Object.assign(Object.assign({},te),se)});return o()(ge,{cycles:!0})}):i.format.printf(S=>{var{timestamp:U,level:J,message:$,error:ne}=S,se=Q(S,["timestamp","level","message","error"]);let ge=`${U||new Date().toISOString()} ${J.toUpperCase()}: ${$} `;return Object.keys(se).length>0&&(ge+=o()(se,{cycles:!0})),ne&&(ge+=`
2
2
  ${N(ne)}`),ge}),H=Object(i.createLogger)({level:b.f});if(b.g&&H.add(new i.transports.Console({format:q,level:"debug"})),b.d&&H.add(new X(b.d,te)),b.h){const S=s.resolve(l.tmpdir(),`silly-${b.a}.log`);H.debug("Logging silly logs to file",{filename:S}),H.add(new i.transports.File({filename:S,maxsize:1*u,maxFiles:10,format:i.format.combine((v="silly",Object(i.format)(U=>U.level===v&&U)()),q),level:"silly"}))}var v},function(e,t,n){n.d(t,"a",function(){return r});const r={millisecond:1,second:1e3,minute:6e4,hour:36e5,day:864e5,week:6048e5,month:2592e6,year:31536e6}},function(e,t){var n,r,o=e.exports={};function l(){throw new Error("setTimeout has not been defined")}function s(){throw new Error("clearTimeout has not been defined")}function i(T){if(n===setTimeout)return setTimeout(T,0);if((n===l||!n)&&setTimeout)return n=setTimeout,setTimeout(T,0);try{return n(T,0)}catch{try{return n.call(null,T,0)}catch{return n.call(this,T,0)}}}(function(){try{n=typeof setTimeout=="function"?setTimeout:l}catch{n=l}try{r=typeof clearTimeout=="function"?clearTimeout:s}catch{r=s}})();var c,u=[],m=!1,R=-1;function E(){m&&c&&(m=!1,c.length?u=c.concat(u):R=-1,u.length&&y())}function y(){if(!m){var T=i(E);m=!0;for(var L=u.length;L;){for(c=u,u=[];++R<L;)c&&c[R].run();R=-1,L=u.length}c=null,m=!1,function(z){if(r===clearTimeout)return clearTimeout(z);if((r===s||!r)&&clearTimeout)return r=clearTimeout,clearTimeout(z);try{r(z)}catch{try{return r.call(null,z)}catch{return r.call(this,z)}}}(T)}}function g(T,L){this.fun=T,this.array=L}function _(){}o.nextTick=function(T){var L=new Array(arguments.length-1);if(arguments.length>1)for(var z=1;z<arguments.length;z++)L[z-1]=arguments[z];u.push(new g(T,L)),u.length!==1||m||i(y)},g.prototype.run=function(){this.fun.apply(null,this.array)},o.title="browser",o.browser=!0,o.env={},o.argv=[],o.version="",o.versions={},o.on=_,o.addListener=_,o.once=_,o.off=_,o.removeListener=_,o.removeAllListeners=_,o.emit=_,o.prependListener=_,o.prependOnceListener=_,o.listeners=function(T){return[]},o.binding=function(T){throw new Error("process.binding is not supported")},o.cwd=function(){return"/"},o.chdir=function(T){throw new Error("process.chdir is not supported")},o.umask=function(){return 0}},function(e,t,n){Object.defineProperty(t,"LEVEL",{value:Symbol.for("level")}),Object.defineProperty(t,"MESSAGE",{value:Symbol.for("message")}),Object.defineProperty(t,"SPLAT",{value:Symbol.for("splat")}),Object.defineProperty(t,"configs",{value:n(118)})},function(e,t,n){(function(r){n.d(t,"a",function(){return s}),n.d(t,"i",function(){return i}),n.d(t,"j",function(){return c}),n.d(t,"b",function(){return u}),n.d(t,"f",function(){return m}),n.d(t,"e",function(){return R}),n.d(t,"g",function(){return E}),n.d(t,"d",function(){return y}),n.d(t,"c",function(){return g}),n.d(t,"h",function(){return _});var o=n(102);const l=o.from({ENVIRONMENT:r.env.ENV,API_ENDPOINT:r.env.API_ENDPOINT,APP:"realtime-sdk",APP_PATH:r.env.APP_PATH,BUILD_TAG:r.env.BUILD_TAG,ENABLE_SELF_SERVE:r.env.ENABLE_SELF_SERVE,ENABLE_SENTRY:r.env.ENABLE_SENTRY,ENABLE_SENTRY_PROFILING:r.env.ENABLE_SENTRY_PROFILING,GIT_COMMIT:r.env.GIT_COMMIT,JEST_WORKER_ID:r.env.JEST_WORKER_ID,LOG_API_ENDPOINT:r.env.LOG_API_ENDPOINT,LOG_JSON:"false",LOG_LEVEL:r.env.LOG_LEVEL,LOG_TO_CONSOLE:r.env.LOG_TO_CONSOLE,LOG_TO_FILE:r.env.LOG_TO_FILE,NAMESPACE:"production",SENTRY_DSN:r.env.SENTRY_DSN,SHEET_EXPORT_MAX_ROW_COUNT:r.env.SHEET_EXPORT_MAX_ROW_COUNT,STABLE_AGENT_VERSION:r.env.STABLE_AGENT_VERSION,VERSION:r.env.VERSION}),s=(l.get("ENVIRONMENT").default("").asString(),l.get("APP").default("").asString()),i=(l.get("APP_PATH").default("").asString(),l.get("API_ENDPOINT").default("").asString(),l.get("NAMESPACE").default("").asString()),c=l.get("VERSION").default("").asString(),u=l.get("BUILD_TAG").default("").asString(),m=(l.get("GIT_COMMIT").default("").asString(),l.get("ENABLE_SENTRY").default("false").asBool(),l.get("ENABLE_SENTRY_PROFILING").default("false").asBool(),l.get("SENTRY_DSN").default("").asString(),l.get("LOG_LEVEL").default("debug").asString()),R=l.get("LOG_JSON").default("true").asBool(),E=l.get("LOG_TO_CONSOLE").default("true").asBool(),y=(l.get("STABLE_AGENT_VERSION").default("").asString(),l.get("LOG_API_ENDPOINT").asString()),g=l.get("JEST_WORKER_ID").asString(),_=(l.get("SHEET_EXPORT_MAX_ROW_COUNT").default("10000").asIntPositive(),l.get("LOG_TO_FILE").default("false").asBoolStrict());l.get("ENABLE_SELF_SERVE").default("true").asBoolStrict()}).call(this,n(2))},function(e,t,n){(function(r){var o=n(126),l=n(127),s=n(42);function i(){return u.TYPED_ARRAY_SUPPORT?2147483647:1073741823}function c(v,S){if(i()<S)throw new RangeError("Invalid typed array length");return u.TYPED_ARRAY_SUPPORT?(v=new Uint8Array(S)).__proto__=u.prototype:(v===null&&(v=new u(S)),v.length=S),v}function u(v,S,U){if(!(u.TYPED_ARRAY_SUPPORT||this instanceof u))return new u(v,S,U);if(typeof v=="number"){if(typeof S=="string")throw new Error("If encoding is specified then the first argument must be a string");return E(this,v)}return m(this,v,S,U)}function m(v,S,U,J){if(typeof S=="number")throw new TypeError('"value" argument must not be a number');return typeof ArrayBuffer!="undefined"&&S instanceof ArrayBuffer?function($,ne,se,ge){if(ne.byteLength,se<0||ne.byteLength<se)throw new RangeError("'offset' is out of bounds");if(ne.byteLength<se+(ge||0))throw new RangeError("'length' is out of bounds");return ne=se===void 0&&ge===void 0?new Uint8Array(ne):ge===void 0?new Uint8Array(ne,se):new Uint8Array(ne,se,ge),u.TYPED_ARRAY_SUPPORT?($=ne).__proto__=u.prototype:$=y($,ne),$}(v,S,U,J):typeof S=="string"?function($,ne,se){if(typeof se=="string"&&se!==""||(se="utf8"),!u.isEncoding(se))throw new TypeError('"encoding" must be a valid string encoding');var ge=0|_(ne,se),ve=($=c($,ge)).write(ne,se);return ve!==ge&&($=$.slice(0,ve)),$}(v,S,U):function($,ne){if(u.isBuffer(ne)){var se=0|g(ne.length);return($=c($,se)).length===0||ne.copy($,0,0,se),$}if(ne){if(typeof ArrayBuffer!="undefined"&&ne.buffer instanceof ArrayBuffer||"length"in ne)return typeof ne.length!="number"||(ge=ne.length)!=ge?c($,0):y($,ne);if(ne.type==="Buffer"&&s(ne.data))return y($,ne.data)}var ge;throw new TypeError("First argument must be a string, Buffer, ArrayBuffer, Array, or array-like object.")}(v,S)}function R(v){if(typeof v!="number")throw new TypeError('"size" argument must be a number');if(v<0)throw new RangeError('"size" argument must not be negative')}function E(v,S){if(R(S),v=c(v,S<0?0:0|g(S)),!u.TYPED_ARRAY_SUPPORT)for(var U=0;U<S;++U)v[U]=0;return v}function y(v,S){var U=S.length<0?0:0|g(S.length);v=c(v,U);for(var J=0;J<U;J+=1)v[J]=255&S[J];return v}function g(v){if(v>=i())throw new RangeError("Attempt to allocate Buffer larger than maximum size: 0x"+i().toString(16)+" bytes");return 0|v}function _(v,S){if(u.isBuffer(v))return v.length;if(typeof ArrayBuffer!="undefined"&&typeof ArrayBuffer.isView=="function"&&(ArrayBuffer.isView(v)||v instanceof ArrayBuffer))return v.byteLength;typeof v!="string"&&(v=""+v);var U=v.length;if(U===0)return 0;for(var J=!1;;)switch(S){case"ascii":case"latin1":case"binary":return U;case"utf8":case"utf-8":case void 0:return te(v).length;case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return 2*U;case"hex":return U>>>1;case"base64":return q(v).length;default:if(J)return te(v).length;S=(""+S).toLowerCase(),J=!0}}function T(v,S,U){var J=!1;if((S===void 0||S<0)&&(S=0),S>this.length||((U===void 0||U>this.length)&&(U=this.length),U<=0)||(U>>>=0)<=(S>>>=0))return"";for(v||(v="utf8");;)switch(v){case"hex":return F(this,S,U);case"utf8":case"utf-8":return C(this,S,U);case"ascii":return b(this,S,U);case"latin1":case"binary":return P(this,S,U);case"base64":return p(this,S,U);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return D(this,S,U);default:if(J)throw new TypeError("Unknown encoding: "+v);v=(v+"").toLowerCase(),J=!0}}function L(v,S,U){var J=v[S];v[S]=v[U],v[U]=J}function z(v,S,U,J,$){if(v.length===0)return-1;if(typeof U=="string"?(J=U,U=0):U>2147483647?U=2147483647:U<-2147483648&&(U=-2147483648),U=+U,isNaN(U)&&(U=$?0:v.length-1),U<0&&(U=v.length+U),U>=v.length){if($)return-1;U=v.length-1}else if(U<0){if(!$)return-1;U=0}if(typeof S=="string"&&(S=u.from(S,J)),u.isBuffer(S))return S.length===0?-1:M(v,S,U,J,$);if(typeof S=="number")return S&=255,u.TYPED_ARRAY_SUPPORT&&typeof Uint8Array.prototype.indexOf=="function"?$?Uint8Array.prototype.indexOf.call(v,S,U):Uint8Array.prototype.lastIndexOf.call(v,S,U):M(v,[S],U,J,$);throw new TypeError("val must be string, number or Buffer")}function M(v,S,U,J,$){var ne,se=1,ge=v.length,ve=S.length;if(J!==void 0&&((J=String(J).toLowerCase())==="ucs2"||J==="ucs-2"||J==="utf16le"||J==="utf-16le")){if(v.length<2||S.length<2)return-1;se=2,ge/=2,ve/=2,U/=2}function Oe(Te,De){return se===1?Te[De]:Te.readUInt16BE(De*se)}if($){var Se=-1;for(ne=U;ne<ge;ne++)if(Oe(v,ne)===Oe(S,Se===-1?0:ne-Se)){if(Se===-1&&(Se=ne),ne-Se+1===ve)return Se*se}else Se!==-1&&(ne-=ne-Se),Se=-1}else for(U+ve>ge&&(U=ge-ve),ne=U;ne>=0;ne--){for(var Ce=!0,Ee=0;Ee<ve;Ee++)if(Oe(v,ne+Ee)!==Oe(S,Ee)){Ce=!1;break}if(Ce)return ne}return-1}function A(v,S,U,J){U=Number(U)||0;var $=v.length-U;J?(J=Number(J))>$&&(J=$):J=$;var ne=S.length;if(ne%2!=0)throw new TypeError("Invalid hex string");J>ne/2&&(J=ne/2);for(var se=0;se<J;++se){var ge=parseInt(S.substr(2*se,2),16);if(isNaN(ge))return se;v[U+se]=ge}return se}function f(v,S,U,J){return H(te(S,v.length-U),v,U,J)}function O(v,S,U,J){return H(function($){for(var ne=[],se=0;se<$.length;++se)ne.push(255&$.charCodeAt(se));return ne}(S),v,U,J)}function Y(v,S,U,J){return O(v,S,U,J)}function Z(v,S,U,J){return H(q(S),v,U,J)}function d(v,S,U,J){return H(function($,ne){for(var se,ge,ve,Oe=[],Se=0;Se<$.length&&!((ne-=2)<0);++Se)se=$.charCodeAt(Se),ge=se>>8,ve=se%256,Oe.push(ve),Oe.push(ge);return Oe}(S,v.length-U),v,U,J)}function p(v,S,U){return S===0&&U===v.length?o.fromByteArray(v):o.fromByteArray(v.slice(S,U))}function C(v,S,U){U=Math.min(v.length,U);for(var J=[],$=S;$<U;){var ne,se,ge,ve,Oe=v[$],Se=null,Ce=Oe>239?4:Oe>223?3:Oe>191?2:1;if($+Ce<=U)switch(Ce){case 1:Oe<128&&(Se=Oe);break;case 2:(192&(ne=v[$+1]))==128&&(ve=(31&Oe)<<6|63&ne)>127&&(Se=ve);break;case 3:ne=v[$+1],se=v[$+2],(192&ne)==128&&(192&se)==128&&(ve=(15&Oe)<<12|(63&ne)<<6|63&se)>2047&&(ve<55296||ve>57343)&&(Se=ve);break;case 4:ne=v[$+1],se=v[$+2],ge=v[$+3],(192&ne)==128&&(192&se)==128&&(192&ge)==128&&(ve=(15&Oe)<<18|(63&ne)<<12|(63&se)<<6|63&ge)>65535&&ve<1114112&&(Se=ve)}Se===null?(Se=65533,Ce=1):Se>65535&&(Se-=65536,J.push(Se>>>10&1023|55296),Se=56320|1023&Se),J.push(Se),$+=Ce}return function(Ee){var Te=Ee.length;if(Te<=4096)return String.fromCharCode.apply(String,Ee);for(var De="",qe=0;qe<Te;)De+=String.fromCharCode.apply(String,Ee.slice(qe,qe+=4096));return De}(J)}t.Buffer=u,t.SlowBuffer=function(v){return+v!=v&&(v=0),u.alloc(+v)},t.INSPECT_MAX_BYTES=50,u.TYPED_ARRAY_SUPPORT=r.TYPED_ARRAY_SUPPORT!==void 0?r.TYPED_ARRAY_SUPPORT:function(){try{var v=new Uint8Array(1);return v.__proto__={__proto__:Uint8Array.prototype,foo:function(){return 42}},v.foo()===42&&typeof v.subarray=="function"&&v.subarray(1,1).byteLength===0}catch{return!1}}(),t.kMaxLength=i(),u.poolSize=8192,u._augment=function(v){return v.__proto__=u.prototype,v},u.from=function(v,S,U){return m(null,v,S,U)},u.TYPED_ARRAY_SUPPORT&&(u.prototype.__proto__=Uint8Array.prototype,u.__proto__=Uint8Array,typeof Symbol!="undefined"&&Symbol.species&&u[Symbol.species]===u&&Object.defineProperty(u,Symbol.species,{value:null,configurable:!0})),u.alloc=function(v,S,U){return function(J,$,ne,se){return R($),$<=0?c(J,$):ne!==void 0?typeof se=="string"?c(J,$).fill(ne,se):c(J,$).fill(ne):c(J,$)}(null,v,S,U)},u.allocUnsafe=function(v){return E(null,v)},u.allocUnsafeSlow=function(v){return E(null,v)},u.isBuffer=function(v){return!(v==null||!v._isBuffer)},u.compare=function(v,S){if(!u.isBuffer(v)||!u.isBuffer(S))throw new TypeError("Arguments must be Buffers");if(v===S)return 0;for(var U=v.length,J=S.length,$=0,ne=Math.min(U,J);$<ne;++$)if(v[$]!==S[$]){U=v[$],J=S[$];break}return U<J?-1:J<U?1:0},u.isEncoding=function(v){switch(String(v).toLowerCase()){case"hex":case"utf8":case"utf-8":case"ascii":case"latin1":case"binary":case"base64":case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return!0;default:return!1}},u.concat=function(v,S){if(!s(v))throw new TypeError('"list" argument must be an Array of Buffers');if(v.length===0)return u.alloc(0);var U;if(S===void 0)for(S=0,U=0;U<v.length;++U)S+=v[U].length;var J=u.allocUnsafe(S),$=0;for(U=0;U<v.length;++U){var ne=v[U];if(!u.isBuffer(ne))throw new TypeError('"list" argument must be an Array of Buffers');ne.copy(J,$),$+=ne.length}return J},u.byteLength=_,u.prototype._isBuffer=!0,u.prototype.swap16=function(){var v=this.length;if(v%2!=0)throw new RangeError("Buffer size must be a multiple of 16-bits");for(var S=0;S<v;S+=2)L(this,S,S+1);return this},u.prototype.swap32=function(){var v=this.length;if(v%4!=0)throw new RangeError("Buffer size must be a multiple of 32-bits");for(var S=0;S<v;S+=4)L(this,S,S+3),L(this,S+1,S+2);return this},u.prototype.swap64=function(){var v=this.length;if(v%8!=0)throw new RangeError("Buffer size must be a multiple of 64-bits");for(var S=0;S<v;S+=8)L(this,S,S+7),L(this,S+1,S+6),L(this,S+2,S+5),L(this,S+3,S+4);return this},u.prototype.toString=function(){var v=0|this.length;return v===0?"":arguments.length===0?C(this,0,v):T.apply(this,arguments)},u.prototype.equals=function(v){if(!u.isBuffer(v))throw new TypeError("Argument must be a Buffer");return this===v||u.compare(this,v)===0},u.prototype.inspect=function(){var v="",S=t.INSPECT_MAX_BYTES;return this.length>0&&(v=this.toString("hex",0,S).match(/.{2}/g).join(" "),this.length>S&&(v+=" ... ")),"<Buffer "+v+">"},u.prototype.compare=function(v,S,U,J,$){if(!u.isBuffer(v))throw new TypeError("Argument must be a Buffer");if(S===void 0&&(S=0),U===void 0&&(U=v?v.length:0),J===void 0&&(J=0),$===void 0&&($=this.length),S<0||U>v.length||J<0||$>this.length)throw new RangeError("out of range index");if(J>=$&&S>=U)return 0;if(J>=$)return-1;if(S>=U)return 1;if(this===v)return 0;for(var ne=($>>>=0)-(J>>>=0),se=(U>>>=0)-(S>>>=0),ge=Math.min(ne,se),ve=this.slice(J,$),Oe=v.slice(S,U),Se=0;Se<ge;++Se)if(ve[Se]!==Oe[Se]){ne=ve[Se],se=Oe[Se];break}return ne<se?-1:se<ne?1:0},u.prototype.includes=function(v,S,U){return this.indexOf(v,S,U)!==-1},u.prototype.indexOf=function(v,S,U){return z(this,v,S,U,!0)},u.prototype.lastIndexOf=function(v,S,U){return z(this,v,S,U,!1)},u.prototype.write=function(v,S,U,J){if(S===void 0)J="utf8",U=this.length,S=0;else if(U===void 0&&typeof S=="string")J=S,U=this.length,S=0;else{if(!isFinite(S))throw new Error("Buffer.write(string, encoding, offset[, length]) is no longer supported");S|=0,isFinite(U)?(U|=0,J===void 0&&(J="utf8")):(J=U,U=void 0)}var $=this.length-S;if((U===void 0||U>$)&&(U=$),v.length>0&&(U<0||S<0)||S>this.length)throw new RangeError("Attempt to write outside buffer bounds");J||(J="utf8");for(var ne=!1;;)switch(J){case"hex":return A(this,v,S,U);case"utf8":case"utf-8":return f(this,v,S,U);case"ascii":return O(this,v,S,U);case"latin1":case"binary":return Y(this,v,S,U);case"base64":return Z(this,v,S,U);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return d(this,v,S,U);default:if(ne)throw new TypeError("Unknown encoding: "+J);J=(""+J).toLowerCase(),ne=!0}},u.prototype.toJSON=function(){return{type:"Buffer",data:Array.prototype.slice.call(this._arr||this,0)}};function b(v,S,U){var J="";U=Math.min(v.length,U);for(var $=S;$<U;++$)J+=String.fromCharCode(127&v[$]);return J}function P(v,S,U){var J="";U=Math.min(v.length,U);for(var $=S;$<U;++$)J+=String.fromCharCode(v[$]);return J}function F(v,S,U){var J=v.length;(!S||S<0)&&(S=0),(!U||U<0||U>J)&&(U=J);for(var $="",ne=S;ne<U;++ne)$+=Q(v[ne]);return $}function D(v,S,U){for(var J=v.slice(S,U),$="",ne=0;ne<J.length;ne+=2)$+=String.fromCharCode(J[ne]+256*J[ne+1]);return $}function I(v,S,U){if(v%1!=0||v<0)throw new RangeError("offset is not uint");if(v+S>U)throw new RangeError("Trying to access beyond buffer length")}function N(v,S,U,J,$,ne){if(!u.isBuffer(v))throw new TypeError('"buffer" argument must be a Buffer instance');if(S>$||S<ne)throw new RangeError('"value" argument is out of bounds');if(U+J>v.length)throw new RangeError("Index out of range")}function B(v,S,U,J){S<0&&(S=65535+S+1);for(var $=0,ne=Math.min(v.length-U,2);$<ne;++$)v[U+$]=(S&255<<8*(J?$:1-$))>>>8*(J?$:1-$)}function w(v,S,U,J){S<0&&(S=4294967295+S+1);for(var $=0,ne=Math.min(v.length-U,4);$<ne;++$)v[U+$]=S>>>8*(J?$:3-$)&255}function h(v,S,U,J,$,ne){if(U+J>v.length)throw new RangeError("Index out of range");if(U<0)throw new RangeError("Index out of range")}function k(v,S,U,J,$){return $||h(v,0,U,4),l.write(v,S,U,J,23,4),U+4}function V(v,S,U,J,$){return $||h(v,0,U,8),l.write(v,S,U,J,52,8),U+8}u.prototype.slice=function(v,S){var U,J=this.length;if((v=~~v)<0?(v+=J)<0&&(v=0):v>J&&(v=J),(S=S===void 0?J:~~S)<0?(S+=J)<0&&(S=0):S>J&&(S=J),S<v&&(S=v),u.TYPED_ARRAY_SUPPORT)(U=this.subarray(v,S)).__proto__=u.prototype;else{var $=S-v;U=new u($,void 0);for(var ne=0;ne<$;++ne)U[ne]=this[ne+v]}return U},u.prototype.readUIntLE=function(v,S,U){v|=0,S|=0,U||I(v,S,this.length);for(var J=this[v],$=1,ne=0;++ne<S&&($*=256);)J+=this[v+ne]*$;return J},u.prototype.readUIntBE=function(v,S,U){v|=0,S|=0,U||I(v,S,this.length);for(var J=this[v+--S],$=1;S>0&&($*=256);)J+=this[v+--S]*$;return J},u.prototype.readUInt8=function(v,S){return S||I(v,1,this.length),this[v]},u.prototype.readUInt16LE=function(v,S){return S||I(v,2,this.length),this[v]|this[v+1]<<8},u.prototype.readUInt16BE=function(v,S){return S||I(v,2,this.length),this[v]<<8|this[v+1]},u.prototype.readUInt32LE=function(v,S){return S||I(v,4,this.length),(this[v]|this[v+1]<<8|this[v+2]<<16)+16777216*this[v+3]},u.prototype.readUInt32BE=function(v,S){return S||I(v,4,this.length),16777216*this[v]+(this[v+1]<<16|this[v+2]<<8|this[v+3])},u.prototype.readIntLE=function(v,S,U){v|=0,S|=0,U||I(v,S,this.length);for(var J=this[v],$=1,ne=0;++ne<S&&($*=256);)J+=this[v+ne]*$;return J>=($*=128)&&(J-=Math.pow(2,8*S)),J},u.prototype.readIntBE=function(v,S,U){v|=0,S|=0,U||I(v,S,this.length);for(var J=S,$=1,ne=this[v+--J];J>0&&($*=256);)ne+=this[v+--J]*$;return ne>=($*=128)&&(ne-=Math.pow(2,8*S)),ne},u.prototype.readInt8=function(v,S){return S||I(v,1,this.length),128&this[v]?-1*(255-this[v]+1):this[v]},u.prototype.readInt16LE=function(v,S){S||I(v,2,this.length);var U=this[v]|this[v+1]<<8;return 32768&U?4294901760|U:U},u.prototype.readInt16BE=function(v,S){S||I(v,2,this.length);var U=this[v+1]|this[v]<<8;return 32768&U?4294901760|U:U},u.prototype.readInt32LE=function(v,S){return S||I(v,4,this.length),this[v]|this[v+1]<<8|this[v+2]<<16|this[v+3]<<24},u.prototype.readInt32BE=function(v,S){return S||I(v,4,this.length),this[v]<<24|this[v+1]<<16|this[v+2]<<8|this[v+3]},u.prototype.readFloatLE=function(v,S){return S||I(v,4,this.length),l.read(this,v,!0,23,4)},u.prototype.readFloatBE=function(v,S){return S||I(v,4,this.length),l.read(this,v,!1,23,4)},u.prototype.readDoubleLE=function(v,S){return S||I(v,8,this.length),l.read(this,v,!0,52,8)},u.prototype.readDoubleBE=function(v,S){return S||I(v,8,this.length),l.read(this,v,!1,52,8)},u.prototype.writeUIntLE=function(v,S,U,J){v=+v,S|=0,U|=0,J||N(this,v,S,U,Math.pow(2,8*U)-1,0);var $=1,ne=0;for(this[S]=255&v;++ne<U&&($*=256);)this[S+ne]=v/$&255;return S+U},u.prototype.writeUIntBE=function(v,S,U,J){v=+v,S|=0,U|=0,J||N(this,v,S,U,Math.pow(2,8*U)-1,0);var $=U-1,ne=1;for(this[S+$]=255&v;--$>=0&&(ne*=256);)this[S+$]=v/ne&255;return S+U},u.prototype.writeUInt8=function(v,S,U){return v=+v,S|=0,U||N(this,v,S,1,255,0),u.TYPED_ARRAY_SUPPORT||(v=Math.floor(v)),this[S]=255&v,S+1},u.prototype.writeUInt16LE=function(v,S,U){return v=+v,S|=0,U||N(this,v,S,2,65535,0),u.TYPED_ARRAY_SUPPORT?(this[S]=255&v,this[S+1]=v>>>8):B(this,v,S,!0),S+2},u.prototype.writeUInt16BE=function(v,S,U){return v=+v,S|=0,U||N(this,v,S,2,65535,0),u.TYPED_ARRAY_SUPPORT?(this[S]=v>>>8,this[S+1]=255&v):B(this,v,S,!1),S+2},u.prototype.writeUInt32LE=function(v,S,U){return v=+v,S|=0,U||N(this,v,S,4,4294967295,0),u.TYPED_ARRAY_SUPPORT?(this[S+3]=v>>>24,this[S+2]=v>>>16,this[S+1]=v>>>8,this[S]=255&v):w(this,v,S,!0),S+4},u.prototype.writeUInt32BE=function(v,S,U){return v=+v,S|=0,U||N(this,v,S,4,4294967295,0),u.TYPED_ARRAY_SUPPORT?(this[S]=v>>>24,this[S+1]=v>>>16,this[S+2]=v>>>8,this[S+3]=255&v):w(this,v,S,!1),S+4},u.prototype.writeIntLE=function(v,S,U,J){if(v=+v,S|=0,!J){var $=Math.pow(2,8*U-1);N(this,v,S,U,$-1,-$)}var ne=0,se=1,ge=0;for(this[S]=255&v;++ne<U&&(se*=256);)v<0&&ge===0&&this[S+ne-1]!==0&&(ge=1),this[S+ne]=(v/se>>0)-ge&255;return S+U},u.prototype.writeIntBE=function(v,S,U,J){if(v=+v,S|=0,!J){var $=Math.pow(2,8*U-1);N(this,v,S,U,$-1,-$)}var ne=U-1,se=1,ge=0;for(this[S+ne]=255&v;--ne>=0&&(se*=256);)v<0&&ge===0&&this[S+ne+1]!==0&&(ge=1),this[S+ne]=(v/se>>0)-ge&255;return S+U},u.prototype.writeInt8=function(v,S,U){return v=+v,S|=0,U||N(this,v,S,1,127,-128),u.TYPED_ARRAY_SUPPORT||(v=Math.floor(v)),v<0&&(v=255+v+1),this[S]=255&v,S+1},u.prototype.writeInt16LE=function(v,S,U){return v=+v,S|=0,U||N(this,v,S,2,32767,-32768),u.TYPED_ARRAY_SUPPORT?(this[S]=255&v,this[S+1]=v>>>8):B(this,v,S,!0),S+2},u.prototype.writeInt16BE=function(v,S,U){return v=+v,S|=0,U||N(this,v,S,2,32767,-32768),u.TYPED_ARRAY_SUPPORT?(this[S]=v>>>8,this[S+1]=255&v):B(this,v,S,!1),S+2},u.prototype.writeInt32LE=function(v,S,U){return v=+v,S|=0,U||N(this,v,S,4,2147483647,-2147483648),u.TYPED_ARRAY_SUPPORT?(this[S]=255&v,this[S+1]=v>>>8,this[S+2]=v>>>16,this[S+3]=v>>>24):w(this,v,S,!0),S+4},u.prototype.writeInt32BE=function(v,S,U){return v=+v,S|=0,U||N(this,v,S,4,2147483647,-2147483648),v<0&&(v=4294967295+v+1),u.TYPED_ARRAY_SUPPORT?(this[S]=v>>>24,this[S+1]=v>>>16,this[S+2]=v>>>8,this[S+3]=255&v):w(this,v,S,!1),S+4},u.prototype.writeFloatLE=function(v,S,U){return k(this,v,S,!0,U)},u.prototype.writeFloatBE=function(v,S,U){return k(this,v,S,!1,U)},u.prototype.writeDoubleLE=function(v,S,U){return V(this,v,S,!0,U)},u.prototype.writeDoubleBE=function(v,S,U){return V(this,v,S,!1,U)},u.prototype.copy=function(v,S,U,J){if(U||(U=0),J||J===0||(J=this.length),S>=v.length&&(S=v.length),S||(S=0),J>0&&J<U&&(J=U),J===U||v.length===0||this.length===0)return 0;if(S<0)throw new RangeError("targetStart out of bounds");if(U<0||U>=this.length)throw new RangeError("sourceStart out of bounds");if(J<0)throw new RangeError("sourceEnd out of bounds");J>this.length&&(J=this.length),v.length-S<J-U&&(J=v.length-S+U);var $,ne=J-U;if(this===v&&U<S&&S<J)for($=ne-1;$>=0;--$)v[$+S]=this[$+U];else if(ne<1e3||!u.TYPED_ARRAY_SUPPORT)for($=0;$<ne;++$)v[$+S]=this[$+U];else Uint8Array.prototype.set.call(v,this.subarray(U,U+ne),S);return ne},u.prototype.fill=function(v,S,U,J){if(typeof v=="string"){if(typeof S=="string"?(J=S,S=0,U=this.length):typeof U=="string"&&(J=U,U=this.length),v.length===1){var $=v.charCodeAt(0);$<256&&(v=$)}if(J!==void 0&&typeof J!="string")throw new TypeError("encoding must be a string");if(typeof J=="string"&&!u.isEncoding(J))throw new TypeError("Unknown encoding: "+J)}else typeof v=="number"&&(v&=255);if(S<0||this.length<S||this.length<U)throw new RangeError("Out of range index");if(U<=S)return this;var ne;if(S>>>=0,U=U===void 0?this.length:U>>>0,v||(v=0),typeof v=="number")for(ne=S;ne<U;++ne)this[ne]=v;else{var se=u.isBuffer(v)?v:te(new u(v,J).toString()),ge=se.length;for(ne=0;ne<U-S;++ne)this[ne+S]=se[ne%ge]}return this};var X=/[^+\/0-9A-Za-z-_]/g;function Q(v){return v<16?"0"+v.toString(16):v.toString(16)}function te(v,S){var U;S=S||1/0;for(var J=v.length,$=null,ne=[],se=0;se<J;++se){if((U=v.charCodeAt(se))>55295&&U<57344){if(!$){if(U>56319){(S-=3)>-1&&ne.push(239,191,189);continue}if(se+1===J){(S-=3)>-1&&ne.push(239,191,189);continue}$=U;continue}if(U<56320){(S-=3)>-1&&ne.push(239,191,189),$=U;continue}U=65536+($-55296<<10|U-56320)}else $&&(S-=3)>-1&&ne.push(239,191,189);if($=null,U<128){if((S-=1)<0)break;ne.push(U)}else if(U<2048){if((S-=2)<0)break;ne.push(U>>6|192,63&U|128)}else if(U<65536){if((S-=3)<0)break;ne.push(U>>12|224,U>>6&63|128,63&U|128)}else{if(!(U<1114112))throw new Error("Invalid code point");if((S-=4)<0)break;ne.push(U>>18|240,U>>12&63|128,U>>6&63|128,63&U|128)}}return ne}function q(v){return o.toByteArray(function(S){if((S=function(U){return U.trim?U.trim():U.replace(/^\s+|\s+$/g,"")}(S).replace(X,"")).length<2)return"";for(;S.length%4!=0;)S+="=";return S}(v))}function H(v,S,U,J){for(var $=0;$<J&&!($+U>=S.length||$>=v.length);++$)S[$+U]=v[$];return $}}).call(this,n(6))},function(e,t){var n;n=function(){return this}();try{n=n||new Function("return this")()}catch{typeof window=="object"&&(n=window)}e.exports=n},function(e,t){typeof Object.create=="function"?e.exports=function(n,r){r&&(n.super_=r,n.prototype=Object.create(r.prototype,{constructor:{value:n,enumerable:!1,writable:!0,configurable:!0}}))}:e.exports=function(n,r){if(r){n.super_=r;var o=function(){};o.prototype=r.prototype,n.prototype=new o,n.prototype.constructor=n}}},function(e,t,n){n.d(t,"a",function(){return r});const r=o=>new Promise(l=>setTimeout(l,o||0))},function(e,t,n){var r=n(99),o=r,l=Function("return this")(),s=n(98);o.object.extend(proto,s),o.exportSymbol("proto.v1.signaling.api.CreatePeerRequest",null,l),o.exportSymbol("proto.v1.signaling.api.CreatePeerResponse",null,l),o.exportSymbol("proto.v1.signaling.api.DeletePeerRequest",null,l),o.exportSymbol("proto.v1.signaling.api.DeletePeerResponse",null,l),o.exportSymbol("proto.v1.signaling.api.GetHealthRequest",null,l),o.exportSymbol("proto.v1.signaling.api.GetHealthResponse",null,l),o.exportSymbol("proto.v1.signaling.api.GetIceServersRequest",null,l),o.exportSymbol("proto.v1.signaling.api.GetIceServersResponse",null,l),o.exportSymbol("proto.v1.signaling.api.GetPeersRequest",null,l),o.exportSymbol("proto.v1.signaling.api.GetPeersResponse",null,l),o.exportSymbol("proto.v1.signaling.api.Peer",null,l),o.exportSymbol("proto.v1.signaling.api.ReceiveSignalStreamRequest",null,l),o.exportSymbol("proto.v1.signaling.api.ReceiveSignalStreamResponse",null,l),o.exportSymbol("proto.v1.signaling.api.RefreshPeerRequest",null,l),o.exportSymbol("proto.v1.signaling.api.RefreshPeerResponse",null,l),o.exportSymbol("proto.v1.signaling.api.SendSignalRequest",null,l),o.exportSymbol("proto.v1.signaling.api.SendSignalResponse",null,l),o.exportSymbol("proto.v1.signaling.api.SessionType",null,l),o.exportSymbol("proto.v1.signaling.api.Signal",null,l),proto.v1.signaling.api.Peer=function(i){r.Message.initialize(this,i,0,-1,proto.v1.signaling.api.Peer.repeatedFields_,null)},o.inherits(proto.v1.signaling.api.Peer,r.Message),o.DEBUG&&!COMPILED&&(proto.v1.signaling.api.Peer.displayName="proto.v1.signaling.api.Peer"),proto.v1.signaling.api.Signal=function(i){r.Message.initialize(this,i,0,-1,null,null)},o.inherits(proto.v1.signaling.api.Signal,r.Message),o.DEBUG&&!COMPILED&&(proto.v1.signaling.api.Signal.displayName="proto.v1.signaling.api.Signal"),proto.v1.signaling.api.GetHealthRequest=function(i){r.Message.initialize(this,i,0,-1,null,null)},o.inherits(proto.v1.signaling.api.GetHealthRequest,r.Message),o.DEBUG&&!COMPILED&&(proto.v1.signaling.api.GetHealthRequest.displayName="proto.v1.signaling.api.GetHealthRequest"),proto.v1.signaling.api.GetHealthResponse=function(i){r.Message.initialize(this,i,0,-1,null,null)},o.inherits(proto.v1.signaling.api.GetHealthResponse,r.Message),o.DEBUG&&!COMPILED&&(proto.v1.signaling.api.GetHealthResponse.displayName="proto.v1.signaling.api.GetHealthResponse"),proto.v1.signaling.api.CreatePeerRequest=function(i){r.Message.initialize(this,i,0,-1,null,null)},o.inherits(proto.v1.signaling.api.CreatePeerRequest,r.Message),o.DEBUG&&!COMPILED&&(proto.v1.signaling.api.CreatePeerRequest.displayName="proto.v1.signaling.api.CreatePeerRequest"),proto.v1.signaling.api.CreatePeerResponse=function(i){r.Message.initialize(this,i,0,-1,null,null)},o.inherits(proto.v1.signaling.api.CreatePeerResponse,r.Message),o.DEBUG&&!COMPILED&&(proto.v1.signaling.api.CreatePeerResponse.displayName="proto.v1.signaling.api.CreatePeerResponse"),proto.v1.signaling.api.DeletePeerRequest=function(i){r.Message.initialize(this,i,0,-1,null,null)},o.inherits(proto.v1.signaling.api.DeletePeerRequest,r.Message),o.DEBUG&&!COMPILED&&(proto.v1.signaling.api.DeletePeerRequest.displayName="proto.v1.signaling.api.DeletePeerRequest"),proto.v1.signaling.api.DeletePeerResponse=function(i){r.Message.initialize(this,i,0,-1,null,null)},o.inherits(proto.v1.signaling.api.DeletePeerResponse,r.Message),o.DEBUG&&!COMPILED&&(proto.v1.signaling.api.DeletePeerResponse.displayName="proto.v1.signaling.api.DeletePeerResponse"),proto.v1.signaling.api.RefreshPeerRequest=function(i){r.Message.initialize(this,i,0,-1,null,null)},o.inherits(proto.v1.signaling.api.RefreshPeerRequest,r.Message),o.DEBUG&&!COMPILED&&(proto.v1.signaling.api.RefreshPeerRequest.displayName="proto.v1.signaling.api.RefreshPeerRequest"),proto.v1.signaling.api.RefreshPeerResponse=function(i){r.Message.initialize(this,i,0,-1,null,null)},o.inherits(proto.v1.signaling.api.RefreshPeerResponse,r.Message),o.DEBUG&&!COMPILED&&(proto.v1.signaling.api.RefreshPeerResponse.displayName="proto.v1.signaling.api.RefreshPeerResponse"),proto.v1.signaling.api.GetPeersRequest=function(i){r.Message.initialize(this,i,0,-1,null,null)},o.inherits(proto.v1.signaling.api.GetPeersRequest,r.Message),o.DEBUG&&!COMPILED&&(proto.v1.signaling.api.GetPeersRequest.displayName="proto.v1.signaling.api.GetPeersRequest"),proto.v1.signaling.api.GetPeersResponse=function(i){r.Message.initialize(this,i,0,-1,proto.v1.signaling.api.GetPeersResponse.repeatedFields_,null)},o.inherits(proto.v1.signaling.api.GetPeersResponse,r.Message),o.DEBUG&&!COMPILED&&(proto.v1.signaling.api.GetPeersResponse.displayName="proto.v1.signaling.api.GetPeersResponse"),proto.v1.signaling.api.GetIceServersRequest=function(i){r.Message.initialize(this,i,0,-1,null,null)},o.inherits(proto.v1.signaling.api.GetIceServersRequest,r.Message),o.DEBUG&&!COMPILED&&(proto.v1.signaling.api.GetIceServersRequest.displayName="proto.v1.signaling.api.GetIceServersRequest"),proto.v1.signaling.api.GetIceServersResponse=function(i){r.Message.initialize(this,i,0,-1,null,null)},o.inherits(proto.v1.signaling.api.GetIceServersResponse,r.Message),o.DEBUG&&!COMPILED&&(proto.v1.signaling.api.GetIceServersResponse.displayName="proto.v1.signaling.api.GetIceServersResponse"),proto.v1.signaling.api.SendSignalRequest=function(i){r.Message.initialize(this,i,0,-1,null,null)},o.inherits(proto.v1.signaling.api.SendSignalRequest,r.Message),o.DEBUG&&!COMPILED&&(proto.v1.signaling.api.SendSignalRequest.displayName="proto.v1.signaling.api.SendSignalRequest"),proto.v1.signaling.api.SendSignalResponse=function(i){r.Message.initialize(this,i,0,-1,null,null)},o.inherits(proto.v1.signaling.api.SendSignalResponse,r.Message),o.DEBUG&&!COMPILED&&(proto.v1.signaling.api.SendSignalResponse.displayName="proto.v1.signaling.api.SendSignalResponse"),proto.v1.signaling.api.ReceiveSignalStreamRequest=function(i){r.Message.initialize(this,i,0,-1,null,null)},o.inherits(proto.v1.signaling.api.ReceiveSignalStreamRequest,r.Message),o.DEBUG&&!COMPILED&&(proto.v1.signaling.api.ReceiveSignalStreamRequest.displayName="proto.v1.signaling.api.ReceiveSignalStreamRequest"),proto.v1.signaling.api.ReceiveSignalStreamResponse=function(i){r.Message.initialize(this,i,0,-1,null,null)},o.inherits(proto.v1.signaling.api.ReceiveSignalStreamResponse,r.Message),o.DEBUG&&!COMPILED&&(proto.v1.signaling.api.ReceiveSignalStreamResponse.displayName="proto.v1.signaling.api.ReceiveSignalStreamResponse"),proto.v1.signaling.api.Peer.repeatedFields_=[5],r.Message.GENERATE_TO_OBJECT&&(proto.v1.signaling.api.Peer.prototype.toObject=function(i){return proto.v1.signaling.api.Peer.toObject(i,this)},proto.v1.signaling.api.Peer.toObject=function(i,c){var u,m={peerId:r.Message.getFieldWithDefault(c,1,""),organizationId:r.Message.getFieldWithDefault(c,2,""),userId:(u=c.getUserId())&&s.StringValue.toObject(i,u),deviceId:(u=c.getDeviceId())&&s.StringValue.toObject(i,u),sessionIdsList:(u=r.Message.getRepeatedField(c,5))==null?void 0:u,peerCreatedTimestamp:(u=c.getPeerCreatedTimestamp())&&s.Int64Value.toObject(i,u)};return i&&(m.$jspbMessageInstance=c),m}),proto.v1.signaling.api.Peer.deserializeBinary=function(i){var c=new r.BinaryReader(i),u=new proto.v1.signaling.api.Peer;return proto.v1.signaling.api.Peer.deserializeBinaryFromReader(u,c)},proto.v1.signaling.api.Peer.deserializeBinaryFromReader=function(i,c){for(;c.nextField()&&!c.isEndGroup();)switch(c.getFieldNumber()){case 1:var u=c.readString();i.setPeerId(u);break;case 2:u=c.readString(),i.setOrganizationId(u);break;case 3:u=new s.StringValue,c.readMessage(u,s.StringValue.deserializeBinaryFromReader),i.setUserId(u);break;case 4:u=new s.StringValue,c.readMessage(u,s.StringValue.deserializeBinaryFromReader),i.setDeviceId(u);break;case 5:u=c.readString(),i.addSessionIds(u);break;case 6:u=new s.Int64Value,c.readMessage(u,s.Int64Value.deserializeBinaryFromReader),i.setPeerCreatedTimestamp(u);break;default:c.skipField()}return i},proto.v1.signaling.api.Peer.prototype.serializeBinary=function(){var i=new r.BinaryWriter;return proto.v1.signaling.api.Peer.serializeBinaryToWriter(this,i),i.getResultBuffer()},proto.v1.signaling.api.Peer.serializeBinaryToWriter=function(i,c){var u=void 0;(u=i.getPeerId()).length>0&&c.writeString(1,u),(u=i.getOrganizationId()).length>0&&c.writeString(2,u),(u=i.getUserId())!=null&&c.writeMessage(3,u,s.StringValue.serializeBinaryToWriter),(u=i.getDeviceId())!=null&&c.writeMessage(4,u,s.StringValue.serializeBinaryToWriter),(u=i.getSessionIdsList()).length>0&&c.writeRepeatedString(5,u),(u=i.getPeerCreatedTimestamp())!=null&&c.writeMessage(6,u,s.Int64Value.serializeBinaryToWriter)},proto.v1.signaling.api.Peer.prototype.getPeerId=function(){return r.Message.getFieldWithDefault(this,1,"")},proto.v1.signaling.api.Peer.prototype.setPeerId=function(i){return r.Message.setProto3StringField(this,1,i)},proto.v1.signaling.api.Peer.prototype.getOrganizationId=function(){return r.Message.getFieldWithDefault(this,2,"")},proto.v1.signaling.api.Peer.prototype.setOrganizationId=function(i){return r.Message.setProto3StringField(this,2,i)},proto.v1.signaling.api.Peer.prototype.getUserId=function(){return r.Message.getWrapperField(this,s.StringValue,3)},proto.v1.signaling.api.Peer.prototype.setUserId=function(i){return r.Message.setWrapperField(this,3,i)},proto.v1.signaling.api.Peer.prototype.clearUserId=function(){return this.setUserId(void 0)},proto.v1.signaling.api.Peer.prototype.hasUserId=function(){return r.Message.getField(this,3)!=null},proto.v1.signaling.api.Peer.prototype.getDeviceId=function(){return r.Message.getWrapperField(this,s.StringValue,4)},proto.v1.signaling.api.Peer.prototype.setDeviceId=function(i){return r.Message.setWrapperField(this,4,i)},proto.v1.signaling.api.Peer.prototype.clearDeviceId=function(){return this.setDeviceId(void 0)},proto.v1.signaling.api.Peer.prototype.hasDeviceId=function(){return r.Message.getField(this,4)!=null},proto.v1.signaling.api.Peer.prototype.getSessionIdsList=function(){return r.Message.getRepeatedField(this,5)},proto.v1.signaling.api.Peer.prototype.setSessionIdsList=function(i){return r.Message.setField(this,5,i||[])},proto.v1.signaling.api.Peer.prototype.addSessionIds=function(i,c){return r.Message.addToRepeatedField(this,5,i,c)},proto.v1.signaling.api.Peer.prototype.clearSessionIdsList=function(){return this.setSessionIdsList([])},proto.v1.signaling.api.Peer.prototype.getPeerCreatedTimestamp=function(){return r.Message.getWrapperField(this,s.Int64Value,6)},proto.v1.signaling.api.Peer.prototype.setPeerCreatedTimestamp=function(i){return r.Message.setWrapperField(this,6,i)},proto.v1.signaling.api.Peer.prototype.clearPeerCreatedTimestamp=function(){return this.setPeerCreatedTimestamp(void 0)},proto.v1.signaling.api.Peer.prototype.hasPeerCreatedTimestamp=function(){return r.Message.getField(this,6)!=null},r.Message.GENERATE_TO_OBJECT&&(proto.v1.signaling.api.Signal.prototype.toObject=function(i){return proto.v1.signaling.api.Signal.toObject(i,this)},proto.v1.signaling.api.Signal.toObject=function(i,c){var u,m={sessionId:(u=c.getSessionId())&&s.StringValue.toObject(i,u),sessionCreatedTimestamp:(u=c.getSessionCreatedTimestamp())&&s.Int64Value.toObject(i,u),senderId:r.Message.getFieldWithDefault(c,3,""),receiverId:r.Message.getFieldWithDefault(c,4,""),payload:r.Message.getFieldWithDefault(c,5,""),iceServers:r.Message.getFieldWithDefault(c,6,""),iceTransportPolicy:r.Message.getFieldWithDefault(c,7,""),sessionType:r.Message.getFieldWithDefault(c,8,0)};return i&&(m.$jspbMessageInstance=c),m}),proto.v1.signaling.api.Signal.deserializeBinary=function(i){var c=new r.BinaryReader(i),u=new proto.v1.signaling.api.Signal;return proto.v1.signaling.api.Signal.deserializeBinaryFromReader(u,c)},proto.v1.signaling.api.Signal.deserializeBinaryFromReader=function(i,c){for(;c.nextField()&&!c.isEndGroup();)switch(c.getFieldNumber()){case 1:var u=new s.StringValue;c.readMessage(u,s.StringValue.deserializeBinaryFromReader),i.setSessionId(u);break;case 2:u=new s.Int64Value,c.readMessage(u,s.Int64Value.deserializeBinaryFromReader),i.setSessionCreatedTimestamp(u);break;case 3:u=c.readString(),i.setSenderId(u);break;case 4:u=c.readString(),i.setReceiverId(u);break;case 5:u=c.readString(),i.setPayload(u);break;case 6:u=c.readString(),i.setIceServers(u);break;case 7:u=c.readString(),i.setIceTransportPolicy(u);break;case 8:u=c.readEnum(),i.setSessionType(u);break;default:c.skipField()}return i},proto.v1.signaling.api.Signal.prototype.serializeBinary=function(){var i=new r.BinaryWriter;return proto.v1.signaling.api.Signal.serializeBinaryToWriter(this,i),i.getResultBuffer()},proto.v1.signaling.api.Signal.serializeBinaryToWriter=function(i,c){var u=void 0;(u=i.getSessionId())!=null&&c.writeMessage(1,u,s.StringValue.serializeBinaryToWriter),(u=i.getSessionCreatedTimestamp())!=null&&c.writeMessage(2,u,s.Int64Value.serializeBinaryToWriter),(u=i.getSenderId()).length>0&&c.writeString(3,u),(u=i.getReceiverId()).length>0&&c.writeString(4,u),(u=i.getPayload()).length>0&&c.writeString(5,u),(u=i.getIceServers()).length>0&&c.writeString(6,u),(u=i.getIceTransportPolicy()).length>0&&c.writeString(7,u),(u=i.getSessionType())!==0&&c.writeEnum(8,u)},proto.v1.signaling.api.Signal.prototype.getSessionId=function(){return r.Message.getWrapperField(this,s.StringValue,1)},proto.v1.signaling.api.Signal.prototype.setSessionId=function(i){return r.Message.setWrapperField(this,1,i)},proto.v1.signaling.api.Signal.prototype.clearSessionId=function(){return this.setSessionId(void 0)},proto.v1.signaling.api.Signal.prototype.hasSessionId=function(){return r.Message.getField(this,1)!=null},proto.v1.signaling.api.Signal.prototype.getSessionCreatedTimestamp=function(){return r.Message.getWrapperField(this,s.Int64Value,2)},proto.v1.signaling.api.Signal.prototype.setSessionCreatedTimestamp=function(i){return r.Message.setWrapperField(this,2,i)},proto.v1.signaling.api.Signal.prototype.clearSessionCreatedTimestamp=function(){return this.setSessionCreatedTimestamp(void 0)},proto.v1.signaling.api.Signal.prototype.hasSessionCreatedTimestamp=function(){return r.Message.getField(this,2)!=null},proto.v1.signaling.api.Signal.prototype.getSenderId=function(){return r.Message.getFieldWithDefault(this,3,"")},proto.v1.signaling.api.Signal.prototype.setSenderId=function(i){return r.Message.setProto3StringField(this,3,i)},proto.v1.signaling.api.Signal.prototype.getReceiverId=function(){return r.Message.getFieldWithDefault(this,4,"")},proto.v1.signaling.api.Signal.prototype.setReceiverId=function(i){return r.Message.setProto3StringField(this,4,i)},proto.v1.signaling.api.Signal.prototype.getPayload=function(){return r.Message.getFieldWithDefault(this,5,"")},proto.v1.signaling.api.Signal.prototype.setPayload=function(i){return r.Message.setProto3StringField(this,5,i)},proto.v1.signaling.api.Signal.prototype.getIceServers=function(){return r.Message.getFieldWithDefault(this,6,"")},proto.v1.signaling.api.Signal.prototype.setIceServers=function(i){return r.Message.setProto3StringField(this,6,i)},proto.v1.signaling.api.Signal.prototype.getIceTransportPolicy=function(){return r.Message.getFieldWithDefault(this,7,"")},proto.v1.signaling.api.Signal.prototype.setIceTransportPolicy=function(i){return r.Message.setProto3StringField(this,7,i)},proto.v1.signaling.api.Signal.prototype.getSessionType=function(){return r.Message.getFieldWithDefault(this,8,0)},proto.v1.signaling.api.Signal.prototype.setSessionType=function(i){return r.Message.setProto3EnumField(this,8,i)},r.Message.GENERATE_TO_OBJECT&&(proto.v1.signaling.api.GetHealthRequest.prototype.toObject=function(i){return proto.v1.signaling.api.GetHealthRequest.toObject(i,this)},proto.v1.signaling.api.GetHealthRequest.toObject=function(i,c){var u={};return i&&(u.$jspbMessageInstance=c),u}),proto.v1.signaling.api.GetHealthRequest.deserializeBinary=function(i){var c=new r.BinaryReader(i),u=new proto.v1.signaling.api.GetHealthRequest;return proto.v1.signaling.api.GetHealthRequest.deserializeBinaryFromReader(u,c)},proto.v1.signaling.api.GetHealthRequest.deserializeBinaryFromReader=function(i,c){for(;c.nextField()&&!c.isEndGroup();)c.getFieldNumber(),c.skipField();return i},proto.v1.signaling.api.GetHealthRequest.prototype.serializeBinary=function(){var i=new r.BinaryWriter;return proto.v1.signaling.api.GetHealthRequest.serializeBinaryToWriter(this,i),i.getResultBuffer()},proto.v1.signaling.api.GetHealthRequest.serializeBinaryToWriter=function(i,c){},r.Message.GENERATE_TO_OBJECT&&(proto.v1.signaling.api.GetHealthResponse.prototype.toObject=function(i){return proto.v1.signaling.api.GetHealthResponse.toObject(i,this)},proto.v1.signaling.api.GetHealthResponse.toObject=function(i,c){var u={version:r.Message.getFieldWithDefault(c,1,"")};return i&&(u.$jspbMessageInstance=c),u}),proto.v1.signaling.api.GetHealthResponse.deserializeBinary=function(i){var c=new r.BinaryReader(i),u=new proto.v1.signaling.api.GetHealthResponse;return proto.v1.signaling.api.GetHealthResponse.deserializeBinaryFromReader(u,c)},proto.v1.signaling.api.GetHealthResponse.deserializeBinaryFromReader=function(i,c){for(;c.nextField()&&!c.isEndGroup();)switch(c.getFieldNumber()){case 1:var u=c.readString();i.setVersion(u);break;default:c.skipField()}return i},proto.v1.signaling.api.GetHealthResponse.prototype.serializeBinary=function(){var i=new r.BinaryWriter;return proto.v1.signaling.api.GetHealthResponse.serializeBinaryToWriter(this,i),i.getResultBuffer()},proto.v1.signaling.api.GetHealthResponse.serializeBinaryToWriter=function(i,c){var u;(u=i.getVersion()).length>0&&c.writeString(1,u)},proto.v1.signaling.api.GetHealthResponse.prototype.getVersion=function(){return r.Message.getFieldWithDefault(this,1,"")},proto.v1.signaling.api.GetHealthResponse.prototype.setVersion=function(i){return r.Message.setProto3StringField(this,1,i)},r.Message.GENERATE_TO_OBJECT&&(proto.v1.signaling.api.CreatePeerRequest.prototype.toObject=function(i){return proto.v1.signaling.api.CreatePeerRequest.toObject(i,this)},proto.v1.signaling.api.CreatePeerRequest.toObject=function(i,c){var u={};return i&&(u.$jspbMessageInstance=c),u}),proto.v1.signaling.api.CreatePeerRequest.deserializeBinary=function(i){var c=new r.BinaryReader(i),u=new proto.v1.signaling.api.CreatePeerRequest;return proto.v1.signaling.api.CreatePeerRequest.deserializeBinaryFromReader(u,c)},proto.v1.signaling.api.CreatePeerRequest.deserializeBinaryFromReader=function(i,c){for(;c.nextField()&&!c.isEndGroup();)c.getFieldNumber(),c.skipField();return i},proto.v1.signaling.api.CreatePeerRequest.prototype.serializeBinary=function(){var i=new r.BinaryWriter;return proto.v1.signaling.api.CreatePeerRequest.serializeBinaryToWriter(this,i),i.getResultBuffer()},proto.v1.signaling.api.CreatePeerRequest.serializeBinaryToWriter=function(i,c){},r.Message.GENERATE_TO_OBJECT&&(proto.v1.signaling.api.CreatePeerResponse.prototype.toObject=function(i){return proto.v1.signaling.api.CreatePeerResponse.toObject(i,this)},proto.v1.signaling.api.CreatePeerResponse.toObject=function(i,c){var u,m={peer:(u=c.getPeer())&&proto.v1.signaling.api.Peer.toObject(i,u)};return i&&(m.$jspbMessageInstance=c),m}),proto.v1.signaling.api.CreatePeerResponse.deserializeBinary=function(i){var c=new r.BinaryReader(i),u=new proto.v1.signaling.api.CreatePeerResponse;return proto.v1.signaling.api.CreatePeerResponse.deserializeBinaryFromReader(u,c)},proto.v1.signaling.api.CreatePeerResponse.deserializeBinaryFromReader=function(i,c){for(;c.nextField()&&!c.isEndGroup();)switch(c.getFieldNumber()){case 1:var u=new proto.v1.signaling.api.Peer;c.readMessage(u,proto.v1.signaling.api.Peer.deserializeBinaryFromReader),i.setPeer(u);break;default:c.skipField()}return i},proto.v1.signaling.api.CreatePeerResponse.prototype.serializeBinary=function(){var i=new r.BinaryWriter;return proto.v1.signaling.api.CreatePeerResponse.serializeBinaryToWriter(this,i),i.getResultBuffer()},proto.v1.signaling.api.CreatePeerResponse.serializeBinaryToWriter=function(i,c){var u;(u=i.getPeer())!=null&&c.writeMessage(1,u,proto.v1.signaling.api.Peer.serializeBinaryToWriter)},proto.v1.signaling.api.CreatePeerResponse.prototype.getPeer=function(){return r.Message.getWrapperField(this,proto.v1.signaling.api.Peer,1)},proto.v1.signaling.api.CreatePeerResponse.prototype.setPeer=function(i){return r.Message.setWrapperField(this,1,i)},proto.v1.signaling.api.CreatePeerResponse.prototype.clearPeer=function(){return this.setPeer(void 0)},proto.v1.signaling.api.CreatePeerResponse.prototype.hasPeer=function(){return r.Message.getField(this,1)!=null},r.Message.GENERATE_TO_OBJECT&&(proto.v1.signaling.api.DeletePeerRequest.prototype.toObject=function(i){return proto.v1.signaling.api.DeletePeerRequest.toObject(i,this)},proto.v1.signaling.api.DeletePeerRequest.toObject=function(i,c){var u={peerId:r.Message.getFieldWithDefault(c,1,"")};return i&&(u.$jspbMessageInstance=c),u}),proto.v1.signaling.api.DeletePeerRequest.deserializeBinary=function(i){var c=new r.BinaryReader(i),u=new proto.v1.signaling.api.DeletePeerRequest;return proto.v1.signaling.api.DeletePeerRequest.deserializeBinaryFromReader(u,c)},proto.v1.signaling.api.DeletePeerRequest.deserializeBinaryFromReader=function(i,c){for(;c.nextField()&&!c.isEndGroup();)switch(c.getFieldNumber()){case 1:var u=c.readString();i.setPeerId(u);break;default:c.skipField()}return i},proto.v1.signaling.api.DeletePeerRequest.prototype.serializeBinary=function(){var i=new r.BinaryWriter;return proto.v1.signaling.api.DeletePeerRequest.serializeBinaryToWriter(this,i),i.getResultBuffer()},proto.v1.signaling.api.DeletePeerRequest.serializeBinaryToWriter=function(i,c){var u;(u=i.getPeerId()).length>0&&c.writeString(1,u)},proto.v1.signaling.api.DeletePeerRequest.prototype.getPeerId=function(){return r.Message.getFieldWithDefault(this,1,"")},proto.v1.signaling.api.DeletePeerRequest.prototype.setPeerId=function(i){return r.Message.setProto3StringField(this,1,i)},r.Message.GENERATE_TO_OBJECT&&(proto.v1.signaling.api.DeletePeerResponse.prototype.toObject=function(i){return proto.v1.signaling.api.DeletePeerResponse.toObject(i,this)},proto.v1.signaling.api.DeletePeerResponse.toObject=function(i,c){var u={};return i&&(u.$jspbMessageInstance=c),u}),proto.v1.signaling.api.DeletePeerResponse.deserializeBinary=function(i){var c=new r.BinaryReader(i),u=new proto.v1.signaling.api.DeletePeerResponse;return proto.v1.signaling.api.DeletePeerResponse.deserializeBinaryFromReader(u,c)},proto.v1.signaling.api.DeletePeerResponse.deserializeBinaryFromReader=function(i,c){for(;c.nextField()&&!c.isEndGroup();)c.getFieldNumber(),c.skipField();return i},proto.v1.signaling.api.DeletePeerResponse.prototype.serializeBinary=function(){var i=new r.BinaryWriter;return proto.v1.signaling.api.DeletePeerResponse.serializeBinaryToWriter(this,i),i.getResultBuffer()},proto.v1.signaling.api.DeletePeerResponse.serializeBinaryToWriter=function(i,c){},r.Message.GENERATE_TO_OBJECT&&(proto.v1.signaling.api.RefreshPeerRequest.prototype.toObject=function(i){return proto.v1.signaling.api.RefreshPeerRequest.toObject(i,this)},proto.v1.signaling.api.RefreshPeerRequest.toObject=function(i,c){var u,m={peer:(u=c.getPeer())&&proto.v1.signaling.api.Peer.toObject(i,u)};return i&&(m.$jspbMessageInstance=c),m}),proto.v1.signaling.api.RefreshPeerRequest.deserializeBinary=function(i){var c=new r.BinaryReader(i),u=new proto.v1.signaling.api.RefreshPeerRequest;return proto.v1.signaling.api.RefreshPeerRequest.deserializeBinaryFromReader(u,c)},proto.v1.signaling.api.RefreshPeerRequest.deserializeBinaryFromReader=function(i,c){for(;c.nextField()&&!c.isEndGroup();)switch(c.getFieldNumber()){case 1:var u=new proto.v1.signaling.api.Peer;c.readMessage(u,proto.v1.signaling.api.Peer.deserializeBinaryFromReader),i.setPeer(u);break;default:c.skipField()}return i},proto.v1.signaling.api.RefreshPeerRequest.prototype.serializeBinary=function(){var i=new r.BinaryWriter;return proto.v1.signaling.api.RefreshPeerRequest.serializeBinaryToWriter(this,i),i.getResultBuffer()},proto.v1.signaling.api.RefreshPeerRequest.serializeBinaryToWriter=function(i,c){var u;(u=i.getPeer())!=null&&c.writeMessage(1,u,proto.v1.signaling.api.Peer.serializeBinaryToWriter)},proto.v1.signaling.api.RefreshPeerRequest.prototype.getPeer=function(){return r.Message.getWrapperField(this,proto.v1.signaling.api.Peer,1)},proto.v1.signaling.api.RefreshPeerRequest.prototype.setPeer=function(i){return r.Message.setWrapperField(this,1,i)},proto.v1.signaling.api.RefreshPeerRequest.prototype.clearPeer=function(){return this.setPeer(void 0)},proto.v1.signaling.api.RefreshPeerRequest.prototype.hasPeer=function(){return r.Message.getField(this,1)!=null},r.Message.GENERATE_TO_OBJECT&&(proto.v1.signaling.api.RefreshPeerResponse.prototype.toObject=function(i){return proto.v1.signaling.api.RefreshPeerResponse.toObject(i,this)},proto.v1.signaling.api.RefreshPeerResponse.toObject=function(i,c){var u={};return i&&(u.$jspbMessageInstance=c),u}),proto.v1.signaling.api.RefreshPeerResponse.deserializeBinary=function(i){var c=new r.BinaryReader(i),u=new proto.v1.signaling.api.RefreshPeerResponse;return proto.v1.signaling.api.RefreshPeerResponse.deserializeBinaryFromReader(u,c)},proto.v1.signaling.api.RefreshPeerResponse.deserializeBinaryFromReader=function(i,c){for(;c.nextField()&&!c.isEndGroup();)c.getFieldNumber(),c.skipField();return i},proto.v1.signaling.api.RefreshPeerResponse.prototype.serializeBinary=function(){var i=new r.BinaryWriter;return proto.v1.signaling.api.RefreshPeerResponse.serializeBinaryToWriter(this,i),i.getResultBuffer()},proto.v1.signaling.api.RefreshPeerResponse.serializeBinaryToWriter=function(i,c){},r.Message.GENERATE_TO_OBJECT&&(proto.v1.signaling.api.GetPeersRequest.prototype.toObject=function(i){return proto.v1.signaling.api.GetPeersRequest.toObject(i,this)},proto.v1.signaling.api.GetPeersRequest.toObject=function(i,c){var u={};return i&&(u.$jspbMessageInstance=c),u}),proto.v1.signaling.api.GetPeersRequest.deserializeBinary=function(i){var c=new r.BinaryReader(i),u=new proto.v1.signaling.api.GetPeersRequest;return proto.v1.signaling.api.GetPeersRequest.deserializeBinaryFromReader(u,c)},proto.v1.signaling.api.GetPeersRequest.deserializeBinaryFromReader=function(i,c){for(;c.nextField()&&!c.isEndGroup();)c.getFieldNumber(),c.skipField();return i},proto.v1.signaling.api.GetPeersRequest.prototype.serializeBinary=function(){var i=new r.BinaryWriter;return proto.v1.signaling.api.GetPeersRequest.serializeBinaryToWriter(this,i),i.getResultBuffer()},proto.v1.signaling.api.GetPeersRequest.serializeBinaryToWriter=function(i,c){},proto.v1.signaling.api.GetPeersResponse.repeatedFields_=[1],r.Message.GENERATE_TO_OBJECT&&(proto.v1.signaling.api.GetPeersResponse.prototype.toObject=function(i){return proto.v1.signaling.api.GetPeersResponse.toObject(i,this)},proto.v1.signaling.api.GetPeersResponse.toObject=function(i,c){var u={peersList:r.Message.toObjectList(c.getPeersList(),proto.v1.signaling.api.Peer.toObject,i)};return i&&(u.$jspbMessageInstance=c),u}),proto.v1.signaling.api.GetPeersResponse.deserializeBinary=function(i){var c=new r.BinaryReader(i),u=new proto.v1.signaling.api.GetPeersResponse;return proto.v1.signaling.api.GetPeersResponse.deserializeBinaryFromReader(u,c)},proto.v1.signaling.api.GetPeersResponse.deserializeBinaryFromReader=function(i,c){for(;c.nextField()&&!c.isEndGroup();)switch(c.getFieldNumber()){case 1:var u=new proto.v1.signaling.api.Peer;c.readMessage(u,proto.v1.signaling.api.Peer.deserializeBinaryFromReader),i.addPeers(u);break;default:c.skipField()}return i},proto.v1.signaling.api.GetPeersResponse.prototype.serializeBinary=function(){var i=new r.BinaryWriter;return proto.v1.signaling.api.GetPeersResponse.serializeBinaryToWriter(this,i),i.getResultBuffer()},proto.v1.signaling.api.GetPeersResponse.serializeBinaryToWriter=function(i,c){var u;(u=i.getPeersList()).length>0&&c.writeRepeatedMessage(1,u,proto.v1.signaling.api.Peer.serializeBinaryToWriter)},proto.v1.signaling.api.GetPeersResponse.prototype.getPeersList=function(){return r.Message.getRepeatedWrapperField(this,proto.v1.signaling.api.Peer,1)},proto.v1.signaling.api.GetPeersResponse.prototype.setPeersList=function(i){return r.Message.setRepeatedWrapperField(this,1,i)},proto.v1.signaling.api.GetPeersResponse.prototype.addPeers=function(i,c){return r.Message.addToRepeatedWrapperField(this,1,i,proto.v1.signaling.api.Peer,c)},proto.v1.signaling.api.GetPeersResponse.prototype.clearPeersList=function(){return this.setPeersList([])},r.Message.GENERATE_TO_OBJECT&&(proto.v1.signaling.api.GetIceServersRequest.prototype.toObject=function(i){return proto.v1.signaling.api.GetIceServersRequest.toObject(i,this)},proto.v1.signaling.api.GetIceServersRequest.toObject=function(i,c){var u={};return i&&(u.$jspbMessageInstance=c),u}),proto.v1.signaling.api.GetIceServersRequest.deserializeBinary=function(i){var c=new r.BinaryReader(i),u=new proto.v1.signaling.api.GetIceServersRequest;return proto.v1.signaling.api.GetIceServersRequest.deserializeBinaryFromReader(u,c)},proto.v1.signaling.api.GetIceServersRequest.deserializeBinaryFromReader=function(i,c){for(;c.nextField()&&!c.isEndGroup();)c.getFieldNumber(),c.skipField();return i},proto.v1.signaling.api.GetIceServersRequest.prototype.serializeBinary=function(){var i=new r.BinaryWriter;return proto.v1.signaling.api.GetIceServersRequest.serializeBinaryToWriter(this,i),i.getResultBuffer()},proto.v1.signaling.api.GetIceServersRequest.serializeBinaryToWriter=function(i,c){},r.Message.GENERATE_TO_OBJECT&&(proto.v1.signaling.api.GetIceServersResponse.prototype.toObject=function(i){return proto.v1.signaling.api.GetIceServersResponse.toObject(i,this)},proto.v1.signaling.api.GetIceServersResponse.toObject=function(i,c){var u={iceServers:r.Message.getFieldWithDefault(c,1,"")};return i&&(u.$jspbMessageInstance=c),u}),proto.v1.signaling.api.GetIceServersResponse.deserializeBinary=function(i){var c=new r.BinaryReader(i),u=new proto.v1.signaling.api.GetIceServersResponse;return proto.v1.signaling.api.GetIceServersResponse.deserializeBinaryFromReader(u,c)},proto.v1.signaling.api.GetIceServersResponse.deserializeBinaryFromReader=function(i,c){for(;c.nextField()&&!c.isEndGroup();)switch(c.getFieldNumber()){case 1:var u=c.readString();i.setIceServers(u);break;default:c.skipField()}return i},proto.v1.signaling.api.GetIceServersResponse.prototype.serializeBinary=function(){var i=new r.BinaryWriter;return proto.v1.signaling.api.GetIceServersResponse.serializeBinaryToWriter(this,i),i.getResultBuffer()},proto.v1.signaling.api.GetIceServersResponse.serializeBinaryToWriter=function(i,c){var u;(u=i.getIceServers()).length>0&&c.writeString(1,u)},proto.v1.signaling.api.GetIceServersResponse.prototype.getIceServers=function(){return r.Message.getFieldWithDefault(this,1,"")},proto.v1.signaling.api.GetIceServersResponse.prototype.setIceServers=function(i){return r.Message.setProto3StringField(this,1,i)},r.Message.GENERATE_TO_OBJECT&&(proto.v1.signaling.api.SendSignalRequest.prototype.toObject=function(i){return proto.v1.signaling.api.SendSignalRequest.toObject(i,this)},proto.v1.signaling.api.SendSignalRequest.toObject=function(i,c){var u,m={signal:(u=c.getSignal())&&proto.v1.signaling.api.Signal.toObject(i,u)};return i&&(m.$jspbMessageInstance=c),m}),proto.v1.signaling.api.SendSignalRequest.deserializeBinary=function(i){var c=new r.BinaryReader(i),u=new proto.v1.signaling.api.SendSignalRequest;return proto.v1.signaling.api.SendSignalRequest.deserializeBinaryFromReader(u,c)},proto.v1.signaling.api.SendSignalRequest.deserializeBinaryFromReader=function(i,c){for(;c.nextField()&&!c.isEndGroup();)switch(c.getFieldNumber()){case 1:var u=new proto.v1.signaling.api.Signal;c.readMessage(u,proto.v1.signaling.api.Signal.deserializeBinaryFromReader),i.setSignal(u);break;default:c.skipField()}return i},proto.v1.signaling.api.SendSignalRequest.prototype.serializeBinary=function(){var i=new r.BinaryWriter;return proto.v1.signaling.api.SendSignalRequest.serializeBinaryToWriter(this,i),i.getResultBuffer()},proto.v1.signaling.api.SendSignalRequest.serializeBinaryToWriter=function(i,c){var u;(u=i.getSignal())!=null&&c.writeMessage(1,u,proto.v1.signaling.api.Signal.serializeBinaryToWriter)},proto.v1.signaling.api.SendSignalRequest.prototype.getSignal=function(){return r.Message.getWrapperField(this,proto.v1.signaling.api.Signal,1)},proto.v1.signaling.api.SendSignalRequest.prototype.setSignal=function(i){return r.Message.setWrapperField(this,1,i)},proto.v1.signaling.api.SendSignalRequest.prototype.clearSignal=function(){return this.setSignal(void 0)},proto.v1.signaling.api.SendSignalRequest.prototype.hasSignal=function(){return r.Message.getField(this,1)!=null},r.Message.GENERATE_TO_OBJECT&&(proto.v1.signaling.api.SendSignalResponse.prototype.toObject=function(i){return proto.v1.signaling.api.SendSignalResponse.toObject(i,this)},proto.v1.signaling.api.SendSignalResponse.toObject=function(i,c){var u,m={sessionId:(u=c.getSessionId())&&s.StringValue.toObject(i,u),sessionCreatedTimestamp:(u=c.getSessionCreatedTimestamp())&&s.Int64Value.toObject(i,u)};return i&&(m.$jspbMessageInstance=c),m}),proto.v1.signaling.api.SendSignalResponse.deserializeBinary=function(i){var c=new r.BinaryReader(i),u=new proto.v1.signaling.api.SendSignalResponse;return proto.v1.signaling.api.SendSignalResponse.deserializeBinaryFromReader(u,c)},proto.v1.signaling.api.SendSignalResponse.deserializeBinaryFromReader=function(i,c){for(;c.nextField()&&!c.isEndGroup();)switch(c.getFieldNumber()){case 1:var u=new s.StringValue;c.readMessage(u,s.StringValue.deserializeBinaryFromReader),i.setSessionId(u);break;case 2:u=new s.Int64Value,c.readMessage(u,s.Int64Value.deserializeBinaryFromReader),i.setSessionCreatedTimestamp(u);break;default:c.skipField()}return i},proto.v1.signaling.api.SendSignalResponse.prototype.serializeBinary=function(){var i=new r.BinaryWriter;return proto.v1.signaling.api.SendSignalResponse.serializeBinaryToWriter(this,i),i.getResultBuffer()},proto.v1.signaling.api.SendSignalResponse.serializeBinaryToWriter=function(i,c){var u=void 0;(u=i.getSessionId())!=null&&c.writeMessage(1,u,s.StringValue.serializeBinaryToWriter),(u=i.getSessionCreatedTimestamp())!=null&&c.writeMessage(2,u,s.Int64Value.serializeBinaryToWriter)},proto.v1.signaling.api.SendSignalResponse.prototype.getSessionId=function(){return r.Message.getWrapperField(this,s.StringValue,1)},proto.v1.signaling.api.SendSignalResponse.prototype.setSessionId=function(i){return r.Message.setWrapperField(this,1,i)},proto.v1.signaling.api.SendSignalResponse.prototype.clearSessionId=function(){return this.setSessionId(void 0)},proto.v1.signaling.api.SendSignalResponse.prototype.hasSessionId=function(){return r.Message.getField(this,1)!=null},proto.v1.signaling.api.SendSignalResponse.prototype.getSessionCreatedTimestamp=function(){return r.Message.getWrapperField(this,s.Int64Value,2)},proto.v1.signaling.api.SendSignalResponse.prototype.setSessionCreatedTimestamp=function(i){return r.Message.setWrapperField(this,2,i)},proto.v1.signaling.api.SendSignalResponse.prototype.clearSessionCreatedTimestamp=function(){return this.setSessionCreatedTimestamp(void 0)},proto.v1.signaling.api.SendSignalResponse.prototype.hasSessionCreatedTimestamp=function(){return r.Message.getField(this,2)!=null},r.Message.GENERATE_TO_OBJECT&&(proto.v1.signaling.api.ReceiveSignalStreamRequest.prototype.toObject=function(i){return proto.v1.signaling.api.ReceiveSignalStreamRequest.toObject(i,this)},proto.v1.signaling.api.ReceiveSignalStreamRequest.toObject=function(i,c){var u={peerId:r.Message.getFieldWithDefault(c,1,"")};return i&&(u.$jspbMessageInstance=c),u}),proto.v1.signaling.api.ReceiveSignalStreamRequest.deserializeBinary=function(i){var c=new r.BinaryReader(i),u=new proto.v1.signaling.api.ReceiveSignalStreamRequest;return proto.v1.signaling.api.ReceiveSignalStreamRequest.deserializeBinaryFromReader(u,c)},proto.v1.signaling.api.ReceiveSignalStreamRequest.deserializeBinaryFromReader=function(i,c){for(;c.nextField()&&!c.isEndGroup();)switch(c.getFieldNumber()){case 1:var u=c.readString();i.setPeerId(u);break;default:c.skipField()}return i},proto.v1.signaling.api.ReceiveSignalStreamRequest.prototype.serializeBinary=function(){var i=new r.BinaryWriter;return proto.v1.signaling.api.ReceiveSignalStreamRequest.serializeBinaryToWriter(this,i),i.getResultBuffer()},proto.v1.signaling.api.ReceiveSignalStreamRequest.serializeBinaryToWriter=function(i,c){var u;(u=i.getPeerId()).length>0&&c.writeString(1,u)},proto.v1.signaling.api.ReceiveSignalStreamRequest.prototype.getPeerId=function(){return r.Message.getFieldWithDefault(this,1,"")},proto.v1.signaling.api.ReceiveSignalStreamRequest.prototype.setPeerId=function(i){return r.Message.setProto3StringField(this,1,i)},r.Message.GENERATE_TO_OBJECT&&(proto.v1.signaling.api.ReceiveSignalStreamResponse.prototype.toObject=function(i){return proto.v1.signaling.api.ReceiveSignalStreamResponse.toObject(i,this)},proto.v1.signaling.api.ReceiveSignalStreamResponse.toObject=function(i,c){var u,m={signal:(u=c.getSignal())&&proto.v1.signaling.api.Signal.toObject(i,u)};return i&&(m.$jspbMessageInstance=c),m}),proto.v1.signaling.api.ReceiveSignalStreamResponse.deserializeBinary=function(i){var c=new r.BinaryReader(i),u=new proto.v1.signaling.api.ReceiveSignalStreamResponse;return proto.v1.signaling.api.ReceiveSignalStreamResponse.deserializeBinaryFromReader(u,c)},proto.v1.signaling.api.ReceiveSignalStreamResponse.deserializeBinaryFromReader=function(i,c){for(;c.nextField()&&!c.isEndGroup();)switch(c.getFieldNumber()){case 1:var u=new proto.v1.signaling.api.Signal;c.readMessage(u,proto.v1.signaling.api.Signal.deserializeBinaryFromReader),i.setSignal(u);break;default:c.skipField()}return i},proto.v1.signaling.api.ReceiveSignalStreamResponse.prototype.serializeBinary=function(){var i=new r.BinaryWriter;return proto.v1.signaling.api.ReceiveSignalStreamResponse.serializeBinaryToWriter(this,i),i.getResultBuffer()},proto.v1.signaling.api.ReceiveSignalStreamResponse.serializeBinaryToWriter=function(i,c){var u;(u=i.getSignal())!=null&&c.writeMessage(1,u,proto.v1.signaling.api.Signal.serializeBinaryToWriter)},proto.v1.signaling.api.ReceiveSignalStreamResponse.prototype.getSignal=function(){return r.Message.getWrapperField(this,proto.v1.signaling.api.Signal,1)},proto.v1.signaling.api.ReceiveSignalStreamResponse.prototype.setSignal=function(i){return r.Message.setWrapperField(this,1,i)},proto.v1.signaling.api.ReceiveSignalStreamResponse.prototype.clearSignal=function(){return this.setSignal(void 0)},proto.v1.signaling.api.ReceiveSignalStreamResponse.prototype.hasSignal=function(){return r.Message.getField(this,1)!=null},proto.v1.signaling.api.SessionType={UNKNOWN:0,TELEOP:1,PORT_FORWARD:2,OBSERVE:3},o.object.extend(t,proto.v1.signaling.api)},function(e,t,n){function r(o,l,s=()=>!0){if(o instanceof l&&s(o))return o;throw o}n.d(t,"a",function(){return r})},function(e,t,n){n.d(t,"a",function(){return o});var r=n(34);class o extends Error{constructor(s,i,c,u,m={},R){super(`Unexpected response (${c}) for ${s} ${i}: ${JSON.stringify(R?Object(r.a)([...R.entries()].reduce((E,[y,g])=>(E[y]=g,E),{})):{})} -- ${JSON.stringify(Object(r.a)(u))}`),this.method=s,this.url=i,this.statusCode=c,this.body=u,this.validationErrors=m,this.headers=R}}},function(e,t,n){function r(E){return(r=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(y){return typeof y}:function(y){return y&&typeof Symbol=="function"&&y.constructor===Symbol&&y!==Symbol.prototype?"symbol":typeof y})(E)}function o(E,y){return!y||r(y)!=="object"&&typeof y!="function"?l(E):y}function l(E){if(E===void 0)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return E}function s(E){var y=typeof Map=="function"?new Map:void 0;return(s=function(g){if(g===null||(_=g,Function.toString.call(_).indexOf("[native code]")===-1))return g;var _;if(typeof g!="function")throw new TypeError("Super expression must either be null or a function");if(y!==void 0){if(y.has(g))return y.get(g);y.set(g,T)}function T(){return i(g,arguments,m(this).constructor)}return T.prototype=Object.create(g.prototype,{constructor:{value:T,enumerable:!1,writable:!0,configurable:!0}}),u(T,g)})(E)}function i(E,y,g){return(i=c()?Reflect.construct:function(_,T,L){var z=[null];z.push.apply(z,T);var M=new(Function.bind.apply(_,z));return L&&u(M,L.prototype),M}).apply(null,arguments)}function c(){if(typeof Reflect=="undefined"||!Reflect.construct||Reflect.construct.sham)return!1;if(typeof Proxy=="function")return!0;try{return Date.prototype.toString.call(Reflect.construct(Date,[],function(){})),!0}catch{return!1}}function u(E,y){return(u=Object.setPrototypeOf||function(g,_){return g.__proto__=_,g})(E,y)}function m(E){return(m=Object.setPrototypeOf?Object.getPrototypeOf:function(y){return y.__proto__||Object.getPrototypeOf(y)})(E)}var R=function(E){(function(L,z){if(typeof z!="function"&&z!==null)throw new TypeError("Super expression must either be null or a function");L.prototype=Object.create(z&&z.prototype,{constructor:{value:L,writable:!0,configurable:!0}}),z&&u(L,z)})(T,E);var y,g,_=(y=T,g=c(),function(){var L,z=m(y);if(g){var M=m(this).constructor;L=Reflect.construct(z,arguments,M)}else L=z.apply(this,arguments);return o(this,L)});function T(L){var z;return function(M,A){if(!(M instanceof A))throw new TypeError("Cannot call a class as a function")}(this,T),z=_.call(this,`Format functions must be synchronous taking a two arguments: (info, opts)
3
3
  Found: `.concat(L.toString().split(`
4
4
  `)[0],`
@@ -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,n){function r(l){return(r=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})(l)}function o(l,s){for(var i=0;i<s.length;i++){var c=s[i];c.enumerable=c.enumerable||!1,c.configurable=!0,"value"in c&&(c.writable=!0),Object.defineProperty(l,c.key,c)}}e.exports=function(){function l(c){if(function(u,m){if(!(u instanceof m))throw new TypeError("Cannot call a class as a function")}(this,l),!c)throw new Error("Logger is required for profiling.");this.logger=c,this.start=Date.now()}var s,i;return s=l,(i=[{key:"done",value:function(){for(var c=arguments.length,u=new Array(c),m=0;m<c;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=r(u[u.length-1])==="object"?u.pop():{};return R.level=R.level||"info",R.durationMs=Date.now()-this.start,this.logger.write(R)}}])&&o(s.prototype,i),l}()},function(e,t,n){(function(r){const o=n(209),{MESSAGE:l}=n(3),s=n(35);function i(c,u){return u instanceof r?u.toString("base64"):typeof u=="bigint"?u.toString():u}e.exports=o((c,u={})=>(c[l]=(u.stable?s.stableStringify:s)(c,u.replacer||i,u.space),c))}).call(this,n(5).Buffer)},function(e,t,n){class r extends Error{constructor(l){super(`Format functions must be synchronous taking a two arguments: (info, opts)
42
42
  Found: ${l.toString().split(`
43
43
  `)[0]}
44
- `),Error.captureStackTrace(this,r)}}e.exports=o=>{if(o.length>2)throw new r(o);function l(i={}){this.options=i}function s(i){return new l(i)}return l.prototype.transform=o,s.Format=l,s}},function(e,t,n){function r(s,i){if(!(s instanceof i))throw new TypeError("Cannot call a class as a function")}function o(s,i){for(var c=0;c<i.length;c++){var u=i[c];u.enumerable=u.enumerable||!1,u.configurable=!0,"value"in u&&(u.writable=!0),Object.defineProperty(s,u.key,u)}}var l=n(88);e.exports=function(){function s(){var u=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};r(this,s),this.loggers=new Map,this.options=u}var i,c;return i=s,(c=[{key:"add",value:function(u,m){var R=this;if(!this.loggers.has(u)){var E=(m=Object.assign({},m||this.options)).transports||this.options.transports;m.transports=E?E.slice():[];var y=l(m);y.on("close",function(){return R._delete(u)}),this.loggers.set(u,y)}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,E){return m._removeLogger(E)})}},{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)}}])&&o(i.prototype,c),s}()},function(e,t,n){(function(r){const o=n(52),l=/^([A-Za-z0-9+/]{4})*([A-Za-z0-9+/]{4}|[A-Za-z0-9+/]{3}=|[A-Za-z0-9+/]{2}==)$/;e.exports=function(s,i,c,u){let m,R,E=!1,y=!1;const g=n(94);function _(z){u(i,z)}function T(z,M){let A=`"${i}" ${M}`;throw z&&(A=`${A}`),R&&(A=`${A}. An example of a valid value would be: ${R}`),new o(A)}const L={convertFromBase64:function(){return _("marking for base64 conversion"),E=!0,L},default:function(z){if(typeof z=="number")m=z.toString();else if(Array.isArray(z)||typeof z=="object"&&z!==null)m=JSON.stringify(z);else{if(typeof z!="string")throw new o("values passed to default() must be of Number, String, Array, or Object type");m=z}return _(`setting default value to "${m}"`),L},required:function(z){return z===void 0?(_("marked as required"),y=!0):(_(`setting required flag to ${z}`),y=z),L},example:function(z){return R=z,L}};return Object.entries({...g,...c}).forEach(([z,M])=>{L[z]=function(A){return function(){let f=s[i];if(_(`will be read from the environment using "${A.name}" accessor`),f===void 0)if(m===void 0&&y)_("was not found in the environment, but is required to be set"),T(void 0,"is a required variable, but it was not set");else{if(m===void 0)return void _("was not found in the environment, but is not required. returning undefined");_(`was not found in the environment, parsing default value "${m}" instead`),f=m}y&&(_("verifying variable value is not an empty string"),f.trim().length===0&&T(void 0,"is a required variable, but its value was empty")),E&&(_("verifying variable is a valid base64 string"),f.match(l)||T(f,"should be a valid base64 string if using convertFromBase64"),_("converting from base64 to utf8 string"),f=r.from(f,"base64").toString());const O=[f].concat(Array.prototype.slice.call(arguments));try{_(`passing value "${f}" to "${A.name}" accessor`);const Y=A.apply(A,O);return _(`parsed successfully, returning ${Y}`),Y}catch(Y){T(f,Y.message)}}}(M)}),L}}).call(this,n(5).Buffer)},function(e,t,n){const r=n(33);e.exports=function(o,l){return l=l||",",o.length?r(o).split(l).filter(Boolean):[]}},function(e,t,n){e.exports=function(r){const o=r.toLowerCase();if(o!=="false"&&o!=="true")throw new Error('should be either "true", "false", "TRUE", or "FALSE"');return o!=="false"}},function(e,t,n){e.exports=function(r){const o=r.toLowerCase();if(["false","0","true","1"].indexOf(o)===-1)throw new Error('should be either "true", "false", "TRUE", "FALSE", 1, or 0');return!(o==="0"||o==="false")}},function(e,t,n){const r=n(95);e.exports=function(o){var l=r(o);if(l>65535)throw new Error("cannot assign a port number greater than 65535");return l}},function(e,t,n){const r=n(33);e.exports=function(o,l){const s=r(o);if(l.indexOf(s)<0)throw new Error(`should be one of [${l.join(", ")}]`);return s}},function(e,t,n){const r=n(54);e.exports=function(o){const l=r(o);if(l>0)throw new Error("should be a negative float");return l}},function(e,t,n){const r=n(54);e.exports=function(o){const l=r(o);if(l<0)throw new Error("should be a positive float");return l}},function(e,t,n){const r=n(53);e.exports=function(o){const l=r(o);if(l>0)throw new Error("should be a negative integer");return l}},function(e,t,n){const r=n(55);e.exports=function(o){var l=r(o);if(!Array.isArray(l))throw new Error("should be a parseable JSON Array");return l}},function(e,t,n){const r=n(55);e.exports=function(o){var l=r(o);if(Array.isArray(l))throw new Error("should be a parseable JSON Object");return l}},function(e,t,n){e.exports=function(r,o){try{RegExp(void 0,o)}catch{throw new Error("invalid regexp flags")}try{return new RegExp(r,o)}catch{throw new Error("should be a valid regexp")}}},function(e,t,n){const r=n(96);e.exports=function(o){return r(o).toString()}},function(e,t,n){const r=n(33),o=/^(?:[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*|"(?:[\u0001-\u0008\u000b\u000c\u000e-\u001f\u0021\u0023-\u005b\u005d-\u007f]|\\[\u0001-\u0009\u000b\u000c\u000e-\u007f])*")@(?:(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?|\[(?:(?:(2(5[0-5]|[0-4][0-9])|1[0-9][0-9]|[1-9]?[0-9]))\.){3}(?:(2(5[0-5]|[0-4][0-9])|1[0-9][0-9]|[1-9]?[0-9])|[a-z0-9-]*[a-z0-9]:(?:[\u0001-\u0008\u000b\u000c\u000e-\u001f\u0021-\u005a\u0053-\u007f]|\\[\u0001-\u0009\u000b\u000c\u000e-\u007f])+)\])$/;e.exports=function(l){const s=r(l);if(!o.test(s))throw new Error("should be a valid email address");return s}},function(e,t,n){e.exports=function(r,o){return function(l,s){o&&o.match(/prod|production/)||r(`env-var (${l}): ${s}`)}}},function(e,t,n){(function(r){(function(){var o,l,s,i,c,u;typeof performance!="undefined"&&performance!==null&&performance.now?e.exports=function(){return performance.now()}:r!=null&&r.hrtime?(e.exports=function(){return(o()-c)/1e6},l=r.hrtime,i=(o=function(){var m;return 1e9*(m=l())[0]+m[1]})(),u=1e9*r.uptime(),c=i-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,n(2))},function(e,t,n){(function(r){(function(o){function l(i){if((i=i===void 0?"utf-8":i)!=="utf-8")throw new RangeError("Failed to construct 'TextEncoder': The encoding label provided ('"+i+"') is invalid.")}function s(i,c){if(c=c===void 0?{fatal:!1}:c,(i=i===void 0?"utf-8":i)!=="utf-8")throw new RangeError("Failed to construct 'TextDecoder': The encoding label provided ('"+i+"') is invalid.");if(c.fatal)throw Error("Failed to construct 'TextDecoder': the 'fatal' option is unsupported.")}if(o.TextEncoder&&o.TextDecoder)return!1;Object.defineProperty(l.prototype,"encoding",{value:"utf-8"}),l.prototype.encode=function(i,c){if((c=c===void 0?{stream:!1}:c).stream)throw Error("Failed to encode: the 'stream' option is unsupported.");c=0;for(var u=i.length,m=0,R=Math.max(32,u+(u>>1)+7),E=new Uint8Array(R>>3<<3);c<u;){var y=i.charCodeAt(c++);if(55296<=y&&56319>=y){if(c<u){var g=i.charCodeAt(c);(64512&g)==56320&&(++c,y=((1023&y)<<10)+(1023&g)+65536)}if(55296<=y&&56319>=y)continue}if(m+4>E.length&&(R+=8,R=(R*=1+c/i.length*2)>>3<<3,(g=new Uint8Array(R)).set(E),E=g),(4294967168&y)==0)E[m++]=y;else{if((4294965248&y)==0)E[m++]=y>>6&31|192;else if((4294901760&y)==0)E[m++]=y>>12&15|224,E[m++]=y>>6&63|128;else{if((4292870144&y)!=0)continue;E[m++]=y>>18&7|240,E[m++]=y>>12&63|128,E[m++]=y>>6&63|128}E[m++]=63&y|128}}return E.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(i,c){if((c=c===void 0?{stream:!1}:c).stream)throw Error("Failed to decode: the 'stream' option is unsupported.");c=0;for(var u=(i=new Uint8Array(i)).length,m=[];c<u;){var R=i[c++];if(R===0)break;if((128&R)==0)m.push(R);else if((224&R)==192){var E=63&i[c++];m.push((31&R)<<6|E)}else if((240&R)==224){E=63&i[c++];var y=63&i[c++];m.push((31&R)<<12|E<<6|y)}else(248&R)==240&&(65535<(R=(7&R)<<18|(E=63&i[c++])<<12|(y=63&i[c++])<<6|63&i[c++])&&(R-=65536,m.push(R>>>10&1023|55296),R=56320|1023&R),m.push(R))}return String.fromCharCode.apply(null,m)},o.TextEncoder=l,o.TextDecoder=s})(typeof window!="undefined"?window:r!==void 0?r:this)}).call(this,n(6))},function(e,t,n){n.r(t),n.d(t,"AuthClient",function(){return l}),n.d(t,"RtcSignalingClient",function(){return i}),n.d(t,"Credentials",function(){return P}),n.d(t,"IRtcStream",function(){}),n.d(t,"SignalingPromiseClient",function(){return F.SignalingPromiseClient}),n.d(t,"IRtcClientConfigurationV1",function(){}),n.d(t,"IRtcClientConfiguration",function(){}),n.d(t,"IRtcConnectionStatsInfo",function(){}),n.d(t,"IRtcSendConfiguration",function(){}),n.d(t,"IRtcSessionMetricsMessageCounts",function(){}),n.d(t,"IRtcStreamMessage",function(){}),n.d(t,"IRtcStreamPayload",function(){}),n.d(t,"IStreamControl",function(){}),n.d(t,"RtcClient",function(){return _t}),n.d(t,"RtcClientV1",function(){return jt}),n.d(t,"createRtcStreamMessage",function(){return Ee});var r=n(28),o=function(ye,x,W,K){return new(W||(W=Promise))(function(re,oe){function he(ue){try{pe(K.next(ue))}catch(le){oe(le)}}function me(ue){try{pe(K.throw(ue))}catch(le){oe(le)}}function pe(ue){var le;ue.done?re(ue.value):(le=ue.value,le instanceof W?le:new W(function(Re){Re(le)})).then(he,me)}pe((K=K.apply(ye,x||[])).next())})};class l extends r.a{adminSignup(x,W){return o(this,void 0,void 0,function*(){return yield this.fetch("auth/admin-signup",{token:W,method:"POST",body:JSON.stringify(x)})})}login(x){return o(this,void 0,void 0,function*(){return yield this.fetch("auth/login",{method:"POST",body:JSON.stringify(x),allowUnsafeRetries:!0})})}loginWithGoogleToken(x){return o(this,void 0,void 0,function*(){return yield this.fetch("auth/login-google",{method:"POST",body:JSON.stringify(x),allowUnsafeRetries:!0})})}refresh(x,W){return o(this,void 0,void 0,function*(){return yield this.fetch("auth/refresh",{method:"POST",body:JSON.stringify({refreshToken:x,tokenExpirationSeconds:W}),allowUnsafeRetries:!0})})}respondToNewPasswordRequiredChallenge(x){return o(this,void 0,void 0,function*(){return yield this.fetch("auth/respond-to-new-password-required-challenge",{method:"POST",body:JSON.stringify(x)})})}forgotPassword(x){return o(this,void 0,void 0,function*(){return yield this.fetch("auth/forgot-password",{method:"POST",body:JSON.stringify({email:x})})})}confirmForgotPassword(x){return o(this,void 0,void 0,function*(){return yield this.fetch("auth/confirm-forgot-password",{method:"POST",body:JSON.stringify(x)})})}resendInvitation(x){return o(this,void 0,void 0,function*(){return yield this.fetch("auth/resend-invitation",{method:"POST",body:JSON.stringify({email:x})})})}changePassword({token:x,refreshToken:W,currentPassword:K,newPassword:re}){return o(this,void 0,void 0,function*(){return yield this.fetch("auth/change-password",{token:x,method:"POST",body:JSON.stringify({refreshToken:W,currentPassword:K,newPassword:re})})})}getDeviceCredentials(x){return o(this,void 0,void 0,function*(){return yield this.fetch("auth/device-credentials",{token:x,method:"POST",allowUnsafeRetries:!0})})}impersonate(x,W){return o(this,void 0,void 0,function*(){return yield this.fetch("auth/impersonate",{token:x,method:"POST",allowUnsafeRetries:!0,body:JSON.stringify({userId:W})})})}createServiceAccount(x,W,K,re){return o(this,void 0,void 0,function*(){return yield this.fetch("auth/service-account",{token:x,method:"POST",allowUnsafeRetries:!0,body:JSON.stringify({name:W,roleId:K,tags:re})})})}getFeatures(x){return o(this,void 0,void 0,function*(){return(yield this.fetch("auth/features",{token:x})).features})}}var s=function(ye,x,W,K){return new(W||(W=Promise))(function(re,oe){function he(ue){try{pe(K.next(ue))}catch(le){oe(le)}}function me(ue){try{pe(K.throw(ue))}catch(le){oe(le)}}function pe(ue){var le;ue.done?re(ue.value):(le=ue.value,le instanceof W?le:new W(function(Re){Re(le)})).then(he,me)}pe((K=K.apply(ye,x||[])).next())})};class i extends r.a{createPeer(x,W){return s(this,void 0,void 0,function*(){return yield this.fetch("peers",{token:x,method:"POST",body:JSON.stringify(W)})})}getPeers(x){return s(this,void 0,void 0,function*(){return(yield this.fetch("peers",{token:x})).items})}refreshPeer(x,W){return s(this,void 0,void 0,function*(){yield this.fetch(`peers/${W}/refresh`,{token:x,method:"POST",allowUnsafeRetries:!0})})}createSession(x,W){return s(this,void 0,void 0,function*(){return yield this.fetch("sessions",{token:x,method:"POST",body:JSON.stringify(W)})})}refreshSession(x,W){return s(this,void 0,void 0,function*(){yield this.fetch(`sessions/${W}/refresh`,{token:x,method:"POST",allowUnsafeRetries:!0})})}deleteSession(x,W){return s(this,void 0,void 0,function*(){yield this.fetch(`sessions/${W}`,{token:x,method:"DELETE",allowUnsafeRetries:!0})})}getSessions(x){return s(this,void 0,void 0,function*(){return(yield this.fetch("sessions",{token:x})).items})}getIceServers(x){return s(this,void 0,void 0,function*(){return(yield this.fetch("ice-servers",{token:x})).items})}addSignals(x,W,K){return s(this,void 0,void 0,function*(){yield this.fetch(`sessions/${W}/add-signals`,{token:x,method:"POST",body:JSON.stringify(K)})})}takeSignals(x,W){return s(this,void 0,void 0,function*(){return(yield this.fetch(`sessions/${W}/take-signals`,{token:x,method:"POST"})).items})}}var c=n(1),u=n(8),m=n(14),R=n.n(m),E=n(104),y=n.n(E),g=n(0),_=function(ye,x,W,K){return new(W||(W=Promise))(function(re,oe){function he(ue){try{pe(K.next(ue))}catch(le){oe(le)}}function me(ue){try{pe(K.throw(ue))}catch(le){oe(le)}}function pe(ue){var le;ue.done?re(ue.value):(le=ue.value,le instanceof W?le:new W(function(Re){Re(le)})).then(he,me)}pe((K=K.apply(ye,x||[])).next())})};class T{constructor(x){this.name="LogReporter",this.type="simple",this.message=x}send(x){return _(this,void 0,void 0,function*(){var W,K;g.a.info(this.message,(W=x.reduce((re,oe)=>Object.assign(Object.assign({},re),{[oe.name]:oe.stat}),{}),K=re=>{const{sum:oe,count:he}=re,me=oe/he;return Object.assign(Object.assign({},re),{average:me})},Object.keys(W).reduce((re,oe)=>Object.assign(Object.assign({},re),{[oe]:K(W[oe])}),{})))})}}var L=n(4),z=n(39);function M(ye){return!!ye.match(/^[a-zA-Z0-9-_.,:?'"()@\/\\#$+ ]{1,255}$/)}var A=function(ye,x,W,K){return new(W||(W=Promise))(function(re,oe){function he(ue){try{pe(K.next(ue))}catch(le){oe(le)}}function me(ue){try{pe(K.throw(ue))}catch(le){oe(le)}}function pe(ue){var le;ue.done?re(ue.value):(le=ue.value,le instanceof W?le:new W(function(Re){Re(le)})).then(he,me)}pe((K=K.apply(ye,x||[])).next())})};function f({func:ye,delay:x,immediate:W}){let K=!1,re=setTimeout(function he(){return A(this,void 0,void 0,function*(){if(K)return;const me=new Date().getTime();try{oe=ye(),yield oe}finally{if(!K){const pe=new Date().getTime();re=setTimeout(he,Math.max(x-(pe-me),0))}}})},W?0:x),oe=Promise.resolve();return{stop(){return A(this,void 0,void 0,function*(){K=!0,clearTimeout(re),yield oe})}}}var O=function(ye,x,W,K){return new(W||(W=Promise))(function(re,oe){function he(ue){try{pe(K.next(ue))}catch(le){oe(le)}}function me(ue){try{pe(K.throw(ue))}catch(le){oe(le)}}function pe(ue){var le;ue.done?re(ue.value):(le=ue.value,le instanceof W?le:new W(function(Re){Re(le)})).then(he,me)}pe((K=K.apply(ye,x||[])).next())})};const Y=n(226),Z=!!L.c,d=new class{constructor(ye){this.samplePeriodSeconds=60,this.buffer={},this.reporters=[],this.flushInterval=f({func:()=>this.flushStats(),delay:this.samplePeriodSeconds*c.a.second}),this.tags=this.filterTags((ye==null?void 0:ye.tags)||{app:L.a,version:L.j,namespace:L.i,instanceId:z.a})}shutdown(){return O(this,void 0,void 0,function*(){yield this.flushInterval.stop(),yield this.flushStats(),yield Object(u.a)(2*c.a.second)})}aggregate(ye,x,W){this.addToBuffer(this.buffer,this.encodeKey({metric:ye,tags:this.filterTags(W||{})}),typeof x=="number"?{min:x,max:x,sum:x,count:1}:x)}increment(ye,x){this.aggregate(ye,1,x)}timer(ye,x,W){return O(this,void 0,void 0,function*(){const K=Y(),re=yield x(),oe=Y();return this.aggregate(ye,oe-K,W),re})}registerStatsReporter(ye){this.reporters.push(ye)}setTag(ye,x){const W=this.filterTags({[ye]:x});this.tags=Object.assign(Object.assign({},this.tags),W)}addToBuffer(ye,x,W){if(ye[x]){const{min:K,max:re,sum:oe,count:he}=ye[x];ye[x]={min:Math.min(K,W.min),max:Math.max(re,W.max),sum:oe+W.sum,count:he+W.count}}else ye[x]=W}write(ye){return O(this,void 0,void 0,function*(){yield Promise.all(this.reporters.map(x=>O(this,void 0,void 0,function*(){let W;const K={};switch(x.type){case"simple":for(const[oe,he]of Object.entries(ye)){const{metric:me}=this.decodeKey(oe);this.addToBuffer(K,this.encodeKey({metric:me}),he)}W=K;break;case"tagged":W=ye;break;default:(function(oe){throw new Error(`Unreachable type encountered (${oe})`)})(x.type)}const re=Object.entries(W);if(re.length>0)return x.send(re.map(([oe,he])=>{const{metric:me,tags:pe}=this.decodeKey(oe);return{name:me,tags:Object.assign(Object.assign({},pe),this.tags),stat:he}}),this.samplePeriodSeconds).catch(oe=>{g.a.debug(`Failed to write stats to ${x.name}`,{error:oe})})})))})}flushStats(){return O(this,void 0,void 0,function*(){yield this.write(this.buffer),this.buffer={}})}encodeKey(ye){return R()(Object.assign(Object.assign({},ye),Object.keys(ye.tags||{}).length>0?{tags:ye.tags}:{}))}decodeKey(ye){return JSON.parse(ye)}filterTags(ye){return Object.entries(ye||{}).reduce((x,[W,K])=>(M(W)&&M(K)&&(x[W]=K),x),{})}};Z||["local","on-prem"].includes(L.i)||d.registerStatsReporter(new T("stats"));var p=function(ye,x,W,K){return new(W||(W=Promise))(function(re,oe){function he(ue){try{pe(K.next(ue))}catch(le){oe(le)}}function me(ue){try{pe(K.throw(ue))}catch(le){oe(le)}}function pe(ue){var le;ue.done?re(ue.value):(le=ue.value,le instanceof W?le:new W(function(Re){Re(le)})).then(he,me)}pe((K=K.apply(ye,x||[])).next())})};class C extends class{constructor(x){this.options=x,this.cache=new y.a(Object.assign(Object.assign(Object.assign({},x.dispose||x.disposeAfter?{ttlAutopurge:!0}:{}),x),{dispose:(...W)=>{var K;W[2]==="evict"&&d.increment("lru-eviction",{name:x.name}),(K=x.dispose)===null||K===void 0||K.call(x,...W)},disposeAfter:(...W)=>{var K;this.updateStats(),(K=x.disposeAfter)===null||K===void 0||K.call(x,...W)}})),this.stringify=x.fastStringify?JSON.stringify:R.a}set(x,W,K){const re=this.stringify(x);if(!this.cache.set(re,W,{ttl:K})){const oe=this.cache.sizeCalculation?this.cache.sizeCalculation(W,re):"unknown";throw Error(`Value too large (${oe} > ${this.cache.max})`)}this.updateStats()}get(x){const{name:W}=this.options,K=this.stringify(x),re=this.cache.getRemainingTTL(K);return re<=0?d.increment("cache-miss",{name:W}):re!==1/0&&d.aggregate("cache-item-ttl",re,{name:W}),this.cache.get(K)}delete(x){this.cache.delete(this.stringify(x))}peek(x){return this.cache.peek(this.stringify(x))}size(){return this.cache.size}clear(){this.cache.clear()}forEach(x){this.cache.forEach(x)}purgeStale(){return this.cache.purgeStale()}updateStats(){const{name:x}=this.options;d.aggregate("cache-item-count",this.cache.size,{name:x}),this.cache.calculatedSize!==void 0&&d.aggregate("cache-length",this.cache.calculatedSize,{name:x})}}{constructor(x){if(super(x),this.expireRejectedPromiseValues=x.expireRejectedPromiseValues===void 0||x.expireRejectedPromiseValues,this.rejectedPromiseValueTtl=x.rejectedPromiseValueTtl!==void 0?x.rejectedPromiseValueTtl:c.a.second,this.rejectedPromiseValueTtl<0)throw new Error("rejectedPromiseValueTtl must not be negative")}set(x,W,K){super.set(x,W,K),this.expireRejectedPromiseValues&&W.catch(()=>p(this,void 0,void 0,function*(){yield Object(u.a)(this.rejectedPromiseValueTtl),this.peek(x)===W&&this.delete(x)}))}}var b=function(ye,x,W,K){return new(W||(W=Promise))(function(re,oe){function he(ue){try{pe(K.next(ue))}catch(le){oe(le)}}function me(ue){try{pe(K.throw(ue))}catch(le){oe(le)}}function pe(ue){var le;ue.done?re(ue.value):(le=ue.value,le instanceof W?le:new W(function(Re){Re(le)})).then(he,me)}pe((K=K.apply(ye,x||[])).next())})};class P{constructor(x,W,K){this.authClient=x,this.email=W,this.password=K,this.tokenTtlMs=1*c.a.hour,this.tokenCache=new C({name:"Credentials-tokenCache",max:100,ttl:this.tokenTtlMs-5*c.a.minute,fastStringify:!0})}getToken(){return b(this,void 0,void 0,function*(){let x=this.tokenCache.get(this.email);return x||(x=(()=>b(this,void 0,void 0,function*(){const{authentication:W}=yield this.authClient.login({email:this.email,password:this.password,tokenExpirationSeconds:this.tokenTtlMs/c.a.second});if(!W)throw new Error("User account not verified.");return W.accessToken}))(),this.tokenCache.set(this.email,x)),x})}}var F=n(97),D=n(40),I=function(ye,x,W,K){return new(W||(W=Promise))(function(re,oe){function he(ue){try{pe(K.next(ue))}catch(le){oe(le)}}function me(ue){try{pe(K.throw(ue))}catch(le){oe(le)}}function pe(ue){var le;ue.done?re(ue.value):(le=ue.value,le instanceof W?le:new W(function(Re){Re(le)})).then(he,me)}pe((K=K.apply(ye,x||[])).next())})};class N extends D.a{constructor(x){super(x)}postLanRtcOffer(x){return I(this,void 0,void 0,function*(){return yield this.fetch("v1/lan-rtc-offer",{method:"POST",body:JSON.stringify(x)})})}}var B=function(ye,x,W,K){return new(W||(W=Promise))(function(re,oe){function he(ue){try{pe(K.next(ue))}catch(le){oe(le)}}function me(ue){try{pe(K.throw(ue))}catch(le){oe(le)}}function pe(ue){var le;ue.done?re(ue.value):(le=ue.value,le instanceof W?le:new W(function(Re){Re(le)})).then(he,me)}pe((K=K.apply(ye,x||[])).next())})};function w(ye){return B(this,void 0,void 0,function*(){return(yield Promise.all(ye.map(x=>x.catch(W=>W)))).filter(x=>x instanceof Error)})}function h(ye){if(ye!==void 0)return ye;throw new Error("Value is undefined")}function k(ye,x){const W=ye.reduce((K,re)=>[...K,...re.urls],[]).filter(K=>V(K,x)).sort(K=>X(K,"udp")?-1:0).shift();if(W)return Object.assign(Object.assign({},h(ye.find(K=>K.urls.includes(W)))),{urls:[W]})}function V(ye,x){switch(x){case"stun":return/^stuns?:/.test(ye);case"turn":return/^turns?:/.test(ye)}}function X(ye,x){return ye.endsWith(`transport=${x}`)}var Q=n(9),te=n(24),q=n(229),H=n(29);const v={ordered:!1,maxPacketLifeTime:300*c.a.millisecond},S={ordered:!0},U={ordered:!0},J={ordered:!1,maxRetransmits:0},$={ordered:!1,maxRetransmits:0},ne=ye=>"received"in ye&&ye.received!==void 0,se=ye=>!("received"in ye)||ye.received===void 0,ge=2*c.a.second;function ve(ye,x={}){const W=Array.from(ye.values()),K=W.filter(ne),re=K.length>0,oe=Math.max(...K.map(ue=>ue.received));let he;if(re){const ue=W.length,le=K.length,Re=K.map(je=>je.received-je.sent),{standardDeviation:Ie,mean:ke,jitter:Ve}=function(je){const Be=je.length;if(Be===0)return{mean:NaN,standardDeviation:-1,jitter:NaN};const $e=je.reduce((Je,it)=>Je+it,0)/Be,Ze=Math.sqrt(je.map(Je=>Math.pow(Je-$e,2)).reduce((Je,it)=>Je+it)/Be);let Ke=0;for(let Je=1;Je<Be;++Je)Ke+=Math.abs(je[Je]-je[Je-1]);return{mean:$e,standardDeviation:Ze,jitter:Ke/(Be-1)}}(Re),Qe=W.filter(je=>je.sent<oe-ge),Ye=Qe.filter(se),Ge=Ye.length===0?0:Ye.length/Qe.length;he={pingsSent:ue,pongsReceived:le,average:ke,standardDeviation:Ie,jitter:Ve,max:Math.max(...Re),min:Math.min(...Re),loss:Ge}}else he=null;const{temporalNow:me=Date.now()}=x,pe=(re?oe:me)-4*ge;return Array.from(ye.entries()).forEach(ue=>{const[le,Re]=ue;Re.sent<pe&&ye.delete(le)}),he}function Oe({entityId:ye,streamName:x,streamType:W}){return`${ye}.${x}.${W}`}var Se=function(ye,x,W,K){return new(W||(W=Promise))(function(re,oe){function he(ue){try{pe(K.next(ue))}catch(le){oe(le)}}function me(ue){try{pe(K.throw(ue))}catch(le){oe(le)}}function pe(ue){var le;ue.done?re(ue.value):(le=ue.value,le instanceof W?le:new W(function(Re){Re(le)})).then(he,me)}pe((K=K.apply(ye,x||[])).next())})};class Ce{constructor(x,W){this.sessionId=x,this.connection=W,this.counts={localSent:new Map,localReceived:new Map,remoteSent:new Map,remoteReceived:new Map},this.sessionId=x,this.connection=W}updateRemoteMessagesCounts(x){if(x.payload.streamsInfo){this.counts.remoteSent=new Map,this.counts.remoteReceived=new Map;for(const W of x.payload.streamsInfo.items)this.counts.remoteSent.set(W.streamId,W.sentCount),this.counts.remoteReceived.set(W.streamId,W.receivedCount)}}getLocalStreamsInfo(x){const{localSent:W,localReceived:K}=this.counts;return{items:[...new Set([...W.keys(),...K.keys()])].map(re=>{var oe,he;return{streamId:re,sentCount:(oe=W.get(re))!==null&&oe!==void 0?oe:0,receivedCount:(he=K.get(re))!==null&&he!==void 0?he:0}}),timestamp:x}}incrementLocalSent(x){const{localSent:W}=this.counts,K=Oe(x.header.stream);W.set(K,(W.get(K)||0)+1)}incrementLocalReceived(x){const{localReceived:W}=this.counts,K=Oe(x.header.stream),re=W.get(K)||0;if(re===0){const{streamName:oe,streamType:he}=x.header.stream;g.a.debug("RTC client received first message for stream",{streamName:oe,streamType:he})}W.set(K,re+1)}uploadMetrics(){return Se(this,void 0,void 0,function*(){const{sessionId:x}=this,W=yield this.connection.peerConnection.getStats(),K={};W.forEach(ue=>K[ue.id]=ue),g.a.debug("rtc-stats",Object.assign(Object.assign({},K),{sessionId:x}));const{localSent:re,localReceived:oe,remoteSent:he,remoteReceived:me}=this.counts,pe=[...new Set([...re.keys(),...oe.keys()])].reduce((ue,le)=>{const Re=re.get(le),Ie=oe.get(le),ke=he.get(le),Ve=me.get(le);return Object.assign(Object.assign({},ue),{[`local-${le}-sent`]:Re,[`local-${le}-received`]:Ie,[`remote-${le}-sent`]:ke,[`remote-${le}-received`]:Ve})},{sessionId:x});g.a.debug("rtc-message-report",Object.assign({deviceId:this.connection.getRemoteDeviceId()},pe))})}}function Ee(ye,x,W){return{header:{stream:ye,created:Date.now(),frameId:W||""},payload:x}}function Te(ye){return new Set(["disconnected","failed","closed"]).has(ye.iceConnectionState)}function De(ye){switch(ye.header.stream.streamType){case"twist":{const{twist:x}=ye.payload;if(!x)throw Error("twist not in payload of RTC message with type twist");return{header:ye.header,payload:{twist:{linear:Object.assign({x:0,y:0,z:0},x.linear),angular:Object.assign({x:0,y:0,z:0},x.angular)}}}}case"pose":{const{pose:x}=ye.payload;if(!x)throw Error("pose not in payload of RTC message with type pose");return{header:ye.header,payload:{pose:{translation:Object.assign({x:0,y:0,z:0},x.translation),rotation:Object.assign({x:0,y:0,z:0,w:0},x.rotation)}}}}case"pose-with-covariance":{const{poseWithCovariance:x}=ye.payload;if(!x)throw Error("poseWithCovariance not in payload of RTC message with type pose-with-covariance");const W=new Array(36).fill(0);return x.covariance.forEach((K,re)=>{if(re>=36)throw Error("covariance contains more than 36 elements");W[re]=K}),{header:ye.header,payload:{poseWithCovariance:{pose:{translation:Object.assign({x:0,y:0,z:0},x.pose.translation),rotation:Object.assign({x:0,y:0,z:0,w:0},x.pose.rotation)},covariance:W}}}}case"point":{const{point:x}=ye.payload;if(!x)throw Error("point not in payload of RTC message with type point");return{header:ye.header,payload:{point:Object.assign({x:0,y:0,z:0},x)}}}default:return ye}}var qe=function(ye,x,W,K){return new(W||(W=Promise))(function(re,oe){function he(ue){try{pe(K.next(ue))}catch(le){oe(le)}}function me(ue){try{pe(K.throw(ue))}catch(le){oe(le)}}function pe(ue){var le;ue.done?re(ue.value):(le=ue.value,le instanceof W?le:new W(function(Re){Re(le)})).then(he,me)}pe((K=K.apply(ye,x||[])).next())})};class et{constructor(x,W,K){this.peerConnection=x,this.config=W,this.dataChannelNotifier=K,this.connectTimeoutMs=20*c.a.second,this.iceGatheringTimeoutMs=15*c.a.second,this.pingUpdateTimeoutMs=1*c.a.second,this.pingV2UpdateTimeoutMs=250*c.a.millisecond,this.pingV2MetricsGatherTimeoutMs=1*c.a.second,this.streamsInfoUpdateTimeoutMs=2*c.a.second,this.reassemblyTimeoutMs=500*c.a.millisecond,this.reassemblyTableCleanupMs=1*c.a.second,this.heartbeatTimeoutMs=20*c.a.millisecond,this.streamLatestTimestamp=new Map,this.reassemblyTable=new Map,this.reassemblyTableLastTimestamp=new Map,this.closeCalled=!1,this.gotOffer=!1,this.hasIceCandidate=!1,this.pingV2Map=new Map,this.sendPingV2=()=>{const{latestTryOnceStreamChannel:oe}=this;if(!oe)return;const he=new Date().getTime(),me=Object(q.a)();this.sendSystemMessage(oe,{type:"ping-v2",payload:{timestamp:he,id:me}}),this.pingV2Map.set(me,{sent:he})},this.gatherPingV2Metrics=()=>{const oe=ve(this.pingV2Map);oe&&(this.pingInfo=oe,d.aggregate("rtc-ping-average",oe.average),d.aggregate("rtc-ping-loss",oe.loss),d.aggregate("rtc-jitter",oe.jitter))};const{isOffer:re}=W.baseConfig;re?this.initializeChannels(x):x.ondatachannel=oe=>{switch(oe.channel.label){case"stream.latest-ttl":this.latestTtlStreamChannel=oe.channel;break;case"stream.reliable":this.reliableStreamChannel=oe.channel;break;case"stream.latest-reliable":this.latestReliableStreamChannel=oe.channel;break;case"stream.latest-try-once":this.latestTryOnceStreamChannel=oe.channel;break;case"heartbeat":return void(this.heartbeatChannel=oe.channel);default:return void this.dataChannelNotifier(oe.channel)}this.setupChannel(oe.channel)},this.pingUpdateTimeout=setInterval(()=>{const{reliableStreamChannel:oe}=this;oe&&this.sendSystemMessage(oe,{type:"ping"})},this.pingUpdateTimeoutMs),this.pingV2UpdateTimeout=setInterval(this.sendPingV2,this.pingV2UpdateTimeoutMs),this.pingV2MetricsGatherTimeout=setInterval(this.gatherPingV2Metrics,this.pingV2MetricsGatherTimeoutMs),this.streamsInfoUpdateTimeout=setInterval(()=>{const{latestTtlStreamChannel:oe}=this;oe&&this.sendSystemMessage(oe,{type:"streams-info"})},this.streamsInfoUpdateTimeoutMs),this.reassemblyTableCleanupTimeout=setInterval(()=>{const oe=new Date().getTime();this.reassemblyTableLastTimestamp.forEach((he,me,pe)=>{oe>me+this.reassemblyTimeoutMs&&this.reassemblyTable.delete(he)})},this.reassemblyTableCleanupMs),this.heartbeatTimeout=setInterval(()=>{const{heartbeatChannel:oe}=this;oe&&oe.readyState==="open"&&oe.send(new Uint8Array([1]))},this.heartbeatTimeoutMs)}handleSignal(x){return qe(this,void 0,void 0,function*(){const{peerConnection:W}=this,{track:K}=this.config.baseConfig,re=(()=>{try{return JSON.parse(x.getPayload())}catch{return}})();if(!re)return void g.a.error("Received unparseable signal.");g.a.debug("Handling signal",{description:re});const{sdp:oe,type:he}=re;if(!oe||!he)return void g.a.warn("Received non-SDP signal");const{signalingState:me,connectionState:pe}=W;if(me!=="stable"||pe!=="connected")if(W.remoteDescription)g.a.warn(`Received SDP after remote description was set: ${oe}`);else{if(he==="offer"){if(me!=="stable")return void g.a.warn("Received offer SDP when signaling is ongoing.");yield W.setRemoteDescription(re);const ue=yield W.createAnswer();yield W.setLocalDescription(ue);const le=x.clone();return K==null||K("Answer Received",le),le.setPayload(JSON.stringify(ue)),le.setReceiverId(x.getSenderId()),le.setSenderId(x.getReceiverId()),le}if(he==="answer"){if(me==="stable")return void g.a.warn("Received answer SDP when signaling hasn't started.");yield W.setRemoteDescription(re)}}else g.a.warn(`Received SDP when already connected: ${oe}`)})}send(x,W){const K=this.getChannelFromLabel(W.channelLabel);K?this.sendOnChannel(K,x):g.a.warn("Send called with unexpected channel label",{channelLabel:W.channelLabel})}controlRemoteStream(x){this.sendSystemMessage(h(this.reliableStreamChannel),{type:"stream-control",streamControl:x})}isActive(){return new Set(["new","checking","connected","completed"]).has(this.peerConnection.iceConnectionState)||this.isReady()}isReady(){const{reliableStreamChannel:x,latestTtlStreamChannel:W,latestTryOnceStreamChannel:K,latestReliableStreamChannel:re}=this;return(x==null?void 0:x.readyState)==="open"&&(W==null?void 0:W.readyState)==="open"&&(K==null?void 0:K.readyState)==="open"&&(re==null?void 0:re.readyState)==="open"}close(){return qe(this,void 0,void 0,function*(){if(this.closeCalled)return;this.closeCalled=!0,this.sessionMetrics&&(yield this.sessionMetrics.uploadMetrics()),nt(this.pingUpdateTimeout),nt(this.pingV2UpdateTimeout),nt(this.pingV2MetricsGatherTimeout),nt(this.reassemblyTableCleanupTimeout),nt(this.streamsInfoUpdateTimeout),nt(this.heartbeatTimeout);const{peerConnection:x,reliableStreamChannel:W,latestTtlStreamChannel:K,latestTryOnceStreamChannel:re,latestReliableStreamChannel:oe}=this;x.close(),W==null||W.close(),K==null||K.close(),re==null||re.close(),oe==null||oe.close()})}getPing(){return this.pingTimeMs}getPingInfo(){return this.pingInfo}getLastMessageTimestamp(){return this.lastMessageTimestamp}getSessionCreatedTimestamp(){var x;return(x=this.config.remoteConfig)===null||x===void 0?void 0:x.sessionCreatedTimestamp}setSessionCreatedTimestamp(x){this.config.remoteConfig&&(this.config.remoteConfig.sessionCreatedTimestamp=x)}getSessionId(){var x;return(x=this.config.remoteConfig)===null||x===void 0?void 0:x.sessionId}setSessionId(x){this.config.remoteConfig&&(this.config.remoteConfig.sessionId=x,this.sessionMetrics=new Ce(x,this))}getRemotePeerId(){return this.config.baseConfig.remotePeerId}getRemoteDeviceId(){var x;return(x=this.config.baseConfig)===null||x===void 0?void 0:x.remoteDeviceId}setRemoteDeviceId(x){this.config.baseConfig.remoteDeviceId=x}getSessionMetricsMessageCounts(){var x;return(x=this.sessionMetrics)===null||x===void 0?void 0:x.counts}getConnectionStatsInfo(){return qe(this,void 0,void 0,function*(){const{peerConnection:x}=this;if(!x)return;const W=yield x.getStats(null),K=[];W.forEach(pe=>{K.push(pe)});const re=K.find(pe=>pe.type==="transport");if(!re)return;const oe=K.find(pe=>(pe.type==="candidate-pair"||pe.type==="candidatepair")&&pe.id===re.selectedCandidatePairId);if(!oe)return;const he=K.find(pe=>pe.id===oe.localCandidateId),me=K.find(pe=>pe.id===oe.remoteCandidateId);return he&&me&&(he.address=he.address||he.ip,me.address=me.address||me.ip,he.address!==void 0&&me.address!==void 0)?{transport:re,localCandidate:he,remoteCandidate:me}:void 0})}initializeChannels(x){this.heartbeatChannel=x.createDataChannel("heartbeat",$),this.heartbeatChannel.binaryType="arraybuffer",this.latestTtlStreamChannel=x.createDataChannel("stream.latest-ttl",v),this.latestTtlStreamChannel.binaryType="arraybuffer",this.reliableStreamChannel=x.createDataChannel("stream.reliable",S),this.reliableStreamChannel.binaryType="arraybuffer",this.latestReliableStreamChannel=x.createDataChannel("stream.latest-reliable",U),this.latestReliableStreamChannel.binaryType="arraybuffer",this.latestTryOnceStreamChannel=x.createDataChannel("stream.latest-try-once",J),this.latestTryOnceStreamChannel.binaryType="arraybuffer",this.setupChannel(this.latestTtlStreamChannel),this.setupChannel(this.reliableStreamChannel),this.setupChannel(this.latestReliableStreamChannel),this.setupChannel(this.latestTryOnceStreamChannel)}getOffer(){var x,W,K;return qe(this,void 0,void 0,function*(){const{gotOffer:re}=this,{peerConnection:oe,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 me=(x=this.config.remoteConfig)===null||x===void 0?void 0:x.sessionId;if(re)return void g.a.debug("Failed to generate offer because gotOffer was already called.");if(this.gotOffer=!0,Te(this.peerConnection))return void g.a.debug("Failed to generate offer because the peer connection was inactive.");const pe=he.baseConfig.track;oe.onicecandidate=()=>{this.hasIceCandidate=!0},oe.oniceconnectionstatechange=()=>qe(this,void 0,void 0,function*(){const ke=oe.iceConnectionState;if(ke==="connected"||ke==="completed"){const Ve=yield this.getConnectionStatsInfo(),Qe=Ve?function(Ye){const Ge=Ye.localCandidate.candidateType,je=Ye.remoteCandidate.candidateType;return Ge==="host"&&je==="host"?"local":Ge==="relay"||je==="relay"?"TURN":"STUN"}(Ve):void 0;g.a.info(`ICE connection state changed to ${ke}`,{sessionId:me,connectionStatsInfo:Ve,iceMode:Qe}),pe==null||pe("ICE connection state change",{iceConnectionState:ke,sessionId:me,connectionStatsInfo:Ve,iceMode:Qe})}}),yield oe.setLocalDescription(yield oe.createOffer());const ue=new Date().getTime();for(;;){const ke=new Date().getTime()-ue;if(ke>this.connectTimeoutMs)return void g.a.debug("Failed to generate offer because ICE gathering timed out.");if(ke>this.iceGatheringTimeoutMs&&this.hasIceCandidate){g.a.debug("ICE gathering partially completed; proceeding",{iceTransportPolicy:oe.getConfiguration().iceTransportPolicy,waitTime:ke}),pe==null||pe("ICE gathering partially completed",{sessionId:me,iceTransportPolicy:oe.getConfiguration().iceTransportPolicy,waitTime:ke});break}if(oe.iceGatheringState==="complete"){g.a.debug("ICE gathering complete",{iceTransportPolicy:oe.getConfiguration().iceTransportPolicy,waitTime:ke}),pe==null||pe("ICE gathering completed",{sessionId:me,iceTransportPolicy:oe.getConfiguration().iceTransportPolicy,waitTime:ke});break}yield Object(u.a)(.1*c.a.second)}const le=(W=this.peerConnection.getConfiguration().iceServers)!==null&&W!==void 0?W:[];for(const ke of le)ke.credentialType=void 0;const Re=JSON.stringify(le),Ie=new Q.Signal;return Ie.setPayload(JSON.stringify(oe.localDescription)),Ie.setSenderId(this.config.baseConfig.localPeerId),Ie.setReceiverId(this.config.baseConfig.remotePeerId),Ie.setIceServers(Re),Ie.setIceTransportPolicy((K=this.peerConnection.getConfiguration().iceTransportPolicy)!==null&&K!==void 0?K:"all"),this.config.baseConfig.sessionType!==void 0?Ie.setSessionType(this.config.baseConfig.sessionType):Ie.setSessionType(Q.SessionType.TELEOP),g.a.debug("Sending offer signal with description",{description:Ie.getPayload()}),Ie})}getLanOffer(){return qe(this,void 0,void 0,function*(){const{peerConnection:x,gotOffer:W}=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(W)return void g.a.debug("Failed to generate offer because gotOffer was already called.");if(this.gotOffer=!0,Te(this.peerConnection))return void g.a.debug("Failed to generate offer because the peer connection was inactive.");yield x.setLocalDescription(yield x.createOffer());const K=new Date().getTime();for(;;){if(new Date().getTime()-K>this.iceGatheringTimeoutMs)return void g.a.debug("Failed to generate offer because ICE gathering timed out.");if(x.iceGatheringState==="complete")break;yield Object(u.a)(.1*c.a.second)}const re=x.localDescription;if(re)return g.a.debug("Sending LAN offer signal with description",{description:re}),re;g.a.error("Failed to generate LAN offer description")})}handleLanAnswer(x){return qe(this,void 0,void 0,function*(){const{peerConnection:W}=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 W.setRemoteDescription(x)})}getChannelFromLabel(x){switch(x){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(x,W){let K;try{K=Object(H.encode)(JSON.stringify(W))}catch(re){return void g.a.warn("Failed to encode RTC message",{error:re})}try{x.send(K),this.sessionMetrics&&this.sessionMetrics.incrementLocalSent(W)}catch(re){g.a.warn("Failed to send message to channel",{error:re,channel:x.label})}}channelNotRecognized(x){return x!==this.latestTtlStreamChannel&&x!==this.latestReliableStreamChannel&&x!==this.latestTryOnceStreamChannel&&x!==this.reliableStreamChannel}setupChannel(x){x.onmessage=W=>{if(this.channelNotRecognized(x))return void g.a.warn("Received message on unrecognized data channel.");let K;try{K=JSON.parse(Object(H.decode)(W.data))}catch(re){return void g.a.warn("Received unparseable message on RTC stream data channel",{error:re,channel:x.label})}K.communicationType==="message-chunk"?this.receiveChannelMessageChunk(x,K):this.receiveChannelMessage(x,K)},x.onerror=W=>{g.a.warn(`Channel error: ${W.error}`,{error:W.error,sessionId:this.getSessionId(),channelLabel:x.label})},x.onopen=()=>{g.a.debug("Channel opened",{sessionId:this.getSessionId(),channelLabel:x.label})},x.onclose=()=>{const W={bufferedAmount:x.bufferedAmount,sessionId:this.getSessionId(),channelLabel:x.label};this.closeCalled===!1?g.a.debug("Unexpected channel closed",W):g.a.debug("Channel closed",W)}}receiveChannelMessage(x,W){const{config:K}=this,{remotePeerId:re}=this.config.baseConfig;this.lastMessageTimestamp=new Date().getTime(),W=De(W),this.sessionMetrics&&this.sessionMetrics.incrementLocalReceived(W),this.handleSystemMessage(x,W)||(x===this.latestTryOnceStreamChannel||x===this.latestTtlStreamChannel||x===this.latestReliableStreamChannel)&&!this.isLatestMessage(W)||K.baseConfig.receive(re,W)}receiveChannelMessageChunk(x,W){const K=this.reassemblyTable.get(W.id)||[];if(K.push(W),K.length===W.total){const re=function(oe){const he=oe.sort((me,pe)=>me.seq<pe.seq?-1:1).map(me=>me.part).reduce((me,pe)=>me+pe);try{return JSON.parse(he)}catch{return void g.a.warn("Could not reassemble RTC message chunks")}}(K);return re&&this.receiveChannelMessage(x,re),void this.reassemblyTable.delete(W.id)}this.reassemblyTable.set(W.id,K),this.reassemblyTableLastTimestamp.set(W.id,new Date().getTime())}handleSystemMessage(x,W){var K,re;const{config:oe}=this,{baseConfig:he}=oe,{remotePeerId:me}=he;switch(W.header.stream.streamType){case"ping":return this.sendSystemMessage(x,{type:"pong",timestamp:h(W.payload.ping)}),!0;case"pong":{const pe=new Date().getTime()-h(W.payload.pong);return this.pingTimeMs=pe,d.aggregate("rtc-ping-time",pe),!0}case"ping-v2":return this.sendPingV2(),!0;case"pong-v2":{const pe=h(W.payload.pongV2),ue=this.pingV2Map.get(pe.id);return(ue==null?void 0:ue.sent)!==pe.timestamp?(g.a.warn("Pong timestamp doesn't match stored value",{currentEntry:ue,pong:pe}),!0):(this.pingV2Map.set(pe.id,{sent:pe.timestamp,received:new Date().getTime()}),!0)}case"streams-info":{const{sessionMetrics:pe}=this,ue=(K=W.payload.streamsInfo)===null||K===void 0?void 0:K.timestamp;return!!ue&&(pe==null||pe.updateRemoteMessagesCounts(W),(re=he.onStreamsInfoUpdate)===null||re===void 0||re.call(he,me,ue),!0)}case"stream-control":return!0;default:return!1}}sendSystemMessage(x,W){var K;const{localUserId:re,localPeerId:oe}=this.config.baseConfig;if(x.readyState!=="open")return;const he={entityId:re!=null?re:oe,streamName:`$.${W.type}`,streamType:W.type};let me;switch(W.type){case"ping":me={ping:new Date().getTime()};break;case"pong":me={pong:W.timestamp};break;case"ping-v2":me={pingV2:W.payload};break;case"pong-v2":me={pongV2:W.payload};break;case"stream-control":me={streamControl:W.streamControl};break;case"streams-info":me={streamsInfo:(K=this.sessionMetrics)===null||K===void 0?void 0:K.getLocalStreamsInfo(new Date().getTime())}}this.sendOnChannel(x,Ee(he,me))}isLatestMessage(x){const W=Oe(x.header.stream),K=(this.streamLatestTimestamp.get(W)||0)<=x.header.created;return K&&this.streamLatestTimestamp.set(W,x.header.created),K}}function nt(ye){ye&&clearInterval(ye)}function Rt(ye){var x,W;return{userId:(x=ye.getUserId())===null||x===void 0?void 0:x.getValue(),deviceId:(W=ye.getDeviceId())===null||W===void 0?void 0:W.getValue(),organizationId:ye.getOrganizationId(),id:ye.getPeerId(),capabilities:[],capabilitySet:{}}}var Le=function(ye,x,W,K){return new(W||(W=Promise))(function(re,oe){function he(ue){try{pe(K.next(ue))}catch(le){oe(le)}}function me(ue){try{pe(K.throw(ue))}catch(le){oe(le)}}function pe(ue){var le;ue.done?re(ue.value):(le=ue.value,le instanceof W?le:new W(function(Re){Re(le)})).then(he,me)}pe((K=K.apply(ye,x||[])).next())})};class _t{constructor(x){this.config=x,this.grpcCallDeadline=5*c.a.second,this.refreshIntervalDelayMs=2*c.a.second,this.iceServersTtl=30*c.a.minute,this.connections=[],this.localConnections=[],this.isConnectionInitiator=new Map,this.isOutgoingConnection=new Map,this.peerDataChannelListeners=[];const{refreshIntervalDelayMs:W}=this;this.refreshInterval=f({func:()=>Le(this,void 0,void 0,function*(){try{yield this.update()}catch(K){g.a.warn("RTC refresh failed",{error:K})}}),delay:W,immediate:!0})}send(x,W,K){const re=this.getActiveConnection(x);re?re.isReady()?re.send(W,K):g.a.warn("Send called with unready connection."):g.a.warn("Send called with no connection.")}controlRemoteStream(x,W){const K=this.getActiveConnection(x);K?K.isReady()?K.controlRemoteStream(W):g.a.warn("controlRemoteStream called with unready connection."):g.a.warn("controlRemoteStream called with no connection.")}getLocalPeer(){return Le(this,void 0,void 0,function*(){for(;!this.localPeer;)yield Object(u.a)(.1*c.a.second);return Rt(this.localPeer)})}connect(x,W){var K,re,oe;return Le(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:me}=this.config,{localPeer:pe,receiveSignalStream:ue,iceServers:le}=this;if(!pe||!ue||!le)return void g.a.warn("Connect called prior to local peer, receiveSignalStream, and ICE servers ready");if(this.getActiveConnection(x))return void g.a.warn("Connect called for peer with existing connection.");if(this.isOutgoingConnection.get(x))return void g.a.warn("Connect called for peer with an existing outgoing connection offer.");this.isOutgoingConnection.set(x,!0);const Re=function(je,Be,$e){const{rtcIceTransportPolicies:Ze,rtcIceServerProtocol:Ke,useAllServers:Je}=Be||{},it=je.map(st=>Object.assign(Object.assign({},st),{urls:st.urls.filter(dt=>{const St=(Ze===void 0||Ze.some(wt=>V(dt,wt)))&&(Ke===void 0||X(dt,Ke));return St||g.a.debug(`Ignoring ICE server: ${dt}`,{organizationId:$e}),St})})).filter(({urls:st})=>st.filter(dt=>dt).length>0);return Je?it:[k(it,"stun"),k(it,"turn")].filter(st=>st!==void 0).map(st=>h(st))}(le,W);g.a.debug("Received ICE servers:",le),g.a.debug("Using ICE servers:",Re);const Ie=new et(yield this.createRTCPeerConnection(Re),{baseConfig:{isOffer:!0,isLan:!1,receive:(je,Be)=>this.config.receive(je,Be),onStreamsInfoUpdate:this.config.onStreamsInfoUpdate?(je,Be)=>{var $e,Ze;return(Ze=($e=this.config).onStreamsInfoUpdate)===null||Ze===void 0?void 0:Ze.call($e,je,Be)}:void 0,track:this.config.lanOnlyMode?void 0:this.config.track,localUserId:(K=pe.getUserId())===null||K===void 0?void 0:K.getValue(),localPeerId:pe.getPeerId(),remotePeerId:x,sessionType:this.config.sessionType},remoteConfig:{}},je=>this.onCustomDataChannel(x,je)),ke=yield Ie.getOffer();if(!ke)return g.a.error("Failed to generate offer."),void this.isOutgoingConnection.delete(x);g.a.debug("Sending offer."),he==null||he("Sending offer",ke);const Ve=new Q.SendSignalRequest;Ve.setSignal(ke);const Qe=yield(()=>Le(this,void 0,void 0,function*(){try{return yield me.sendSignal(Ve,yield this.getMetadata({}))}catch(je){g.a.warn("Error when sending signal",{error:je})}}))();if(!this.isOutgoingConnection.get(x))return void g.a.debug("No offer set after receiving offer signal response.");g.a.debug("Offer sent.");const Ye=(re=Qe==null?void 0:Qe.getSessionId())===null||re===void 0?void 0:re.getValue(),Ge=(oe=Qe==null?void 0:Qe.getSessionCreatedTimestamp())===null||oe===void 0?void 0:oe.getValue();return Ye&&Ge?(Ie.setSessionId(Ye),Ie.setSessionCreatedTimestamp(Ge),this.isOutgoingConnection.delete(x),this.connections.push(Ie),this.isConnectionInitiator.set(Ie,!0),this.setupHandlers(Ie),Ye):(g.a.warn("No session ID or no session created timestamp on send signal response."),void this.isOutgoingConnection.delete(x))})}connectLan(x){var W,K;return Le(this,void 0,void 0,function*(){const re=new N(x),oe=new et(yield this.createRTCPeerConnection([]),{baseConfig:{isOffer:!0,isLan:!0,receive:(ue,le)=>this.config.receive(ue,le),onStreamsInfoUpdate:this.config.onStreamsInfoUpdate?(ue,le)=>{var Re,Ie;return(Ie=(Re=this.config).onStreamsInfoUpdate)===null||Ie===void 0?void 0:Ie.call(Re,ue,le)}:void 0,track:this.config.lanOnlyMode?void 0:this.config.track,localUserId:(K=(W=this.localPeer)===null||W===void 0?void 0:W.getUserId())===null||K===void 0?void 0:K.getValue(),localPeerId:"lan_client",remotePeerId:x}},ue=>this.onCustomDataChannel(x,ue)),he=yield oe.getLanOffer();if(!he)return g.a.warn("Could not generate LAN offer"),!1;const me=yield re.postLanRtcOffer({offer:JSON.stringify(he)}),pe=new RTCSessionDescription(JSON.parse(me.answer));return yield oe.handleLanAnswer(pe),this.localConnections.push(oe),this.isConnectionInitiator.set(oe,!0),Object(q.a)()})}getConnections(){return[...this.connections,...this.localConnections]}createCustomDataChannel(x,W,K,re,oe){const he=this.getActiveConnection(x);if(he&&this.isConnectionInitiator.has(he)){const pe=he.peerConnection.createDataChannel("custom."+W,K);return re&&(pe.binaryType="arraybuffer"),oe(x,pe),()=>{}}const me=(pe,ue)=>{x===pe&&ue.label==="custom."+W&&oe(x,ue)};return this.peerDataChannelListeners.push(me),()=>{this.peerDataChannelListeners=this.peerDataChannelListeners.filter(pe=>pe!==me)}}onCustomDataChannel(x,W){this.peerDataChannelListeners.forEach(K=>K(x,W))}getConnectionStatus(x){if(this.isOutgoingConnection.get(x))return"connecting";const W=this.getActiveConnection(x);return W?W.isReady()?"connected":"connecting":"disconnected"}getConnectionStatsInfo(x){return Le(this,void 0,void 0,function*(){const W=this.getActiveConnection(x);if(W)return yield W.getConnectionStatsInfo()})}disconnect(x){return Le(this,void 0,void 0,function*(){const W=this.getActiveConnection(x);W&&(yield W.close())})}getPeers(){return Le(this,void 0,void 0,function*(){if(this.config.lanOnlyMode)throw new Error("getPeers method cannot be used in local-only mode.");const{signalingClient:x}=this.config,W=yield(()=>Le(this,void 0,void 0,function*(){try{return yield x.getPeers(new Q.GetPeersRequest,yield this.getMetadata({}))}catch(oe){g.a.warn("Error when getting peers",{error:oe})}}))();if(!W)return[];const K=W.getPeersList();if(!K)return[];const re=oe=>{var he,me;return(me=(he=oe.getPeerCreatedTimestamp())===null||he===void 0?void 0:he.getValue())!==null&&me!==void 0?me:0};return K.sort((oe,he)=>re(he)-re(oe)).map(oe=>Rt(oe))})}getSessions(){return Le(this,void 0,void 0,function*(){if(this.config.lanOnlyMode)throw new Error("getPeers method cannot be used in local-only mode.");const{signalingClient:x}=this.config,W=yield(()=>Le(this,void 0,void 0,function*(){try{return yield x.getPeers(new Q.GetPeersRequest,yield this.getMetadata({}))}catch(oe){g.a.warn("Error when getting peers",{error:oe})}}))();if(!W)return{};const K=W.getPeersList(),re={};for(const oe of K)re[oe.getPeerId()]=oe.getSessionIdsList();return re})}getPing(x){const W=this.getActiveConnection(x);if(W)return W.getPing();g.a.warn("Attempted to get ping time from inactive peer.")}getPingInfo(x){const W=this.getActiveConnection(x);if(W)return W.getPingInfo();g.a.warn("Attempted to get ping time from inactive peer.")}getLastMessageTimestamp(x){const W=this.getActiveConnection(x);if(W)return W.getLastMessageTimestamp();g.a.warn("Attempted to get last message time from inactive peer.")}getSessionMetricsMessageCounts(x){const W=this.getActiveConnection(x);if(W)return W.getSessionMetricsMessageCounts();g.a.warn("Attempted to get session metrics counts from inactive peer.")}isReady(){if(this.config.lanOnlyMode)return!0;const{localPeer:x,receiveSignalStream:W,iceServers:K}=this;return!!(x&&W&&K)}shutdown(){return Le(this,void 0,void 0,function*(){g.a.info("Shutdown called on RTC client"),yield this.refreshInterval.stop(),this.receiveSignalStream&&this.receiveSignalStream.cancel();const x=this.connections;this.connections=[],yield this.closeConnections(x);const{localPeer:W}=this;if(!W||this.config.lanOnlyMode)return;const{signalingClient:K}=this.config;yield(()=>Le(this,void 0,void 0,function*(){try{const re=new Q.DeletePeerRequest;re.setPeerId(W.getPeerId()),yield K.deletePeer(re,yield this.getMetadata({}))}catch(re){return void g.a.warn("Error deleting local peer",{error:re})}}))()})}createPeer(){return Le(this,void 0,void 0,function*(){if(this.config.lanOnlyMode)throw new Error("createPeer method cannot be used in local-only mode.");const{signalingClient:x}=this.config,W=yield(()=>Le(this,void 0,void 0,function*(){try{return yield x.createPeer(new Q.CreatePeerRequest,yield this.getMetadata({}))}catch(re){throw new Error(`Was not able to create peer: ${JSON.stringify(re)}`)}}))(),K=W==null?void 0:W.getPeer();if(!K)throw new Error("Response did not provide peer.");return this.localPeer=K})}createReceiveSignalStream(){return Le(this,void 0,void 0,function*(){if(this.config.lanOnlyMode)throw new Error("createReceiveSignalStream method cannot be used in local-only mode.");const{signalingClient:x}=this.config,{localPeer:W,iceServers:K}=this;if(!W||!K)return;const{receiveSignalStream:re}=this;re&&re.cancel();const oe=new Q.ReceiveSignalStreamRequest;oe.setPeerId(W.getPeerId());const he=yield(()=>Le(this,void 0,void 0,function*(){try{return x.receiveSignalStream(oe,yield this.getMetadata({hasDeadline:!1}))}catch(me){throw new Error(`Unable to create receive signal stream: ${JSON.stringify(me)}`)}}))();if(!he)throw new Error("Response did not provide stream.");return he.on("data",me=>Le(this,void 0,void 0,function*(){var pe,ue,le,Re;const Ie=me.getSignal(),ke=(pe=Ie==null?void 0:Ie.getSessionId())===null||pe===void 0?void 0:pe.getValue(),Ve=Ie==null?void 0:Ie.getSenderId(),Qe=Ie==null?void 0:Ie.getReceiverId(),Ye=(ue=Ie==null?void 0:Ie.getSessionCreatedTimestamp())===null||ue===void 0?void 0:ue.getValue();if(!(Ie&&ke&&Ve&&Qe&&Ye))return void g.a.warn("Received signal with missing information.");const Ge=this.getActiveConnection(Ve);if(Ge)if(Ge.getSessionId()!==ke){if(g.a.debug("Received signal: different session for a peer we're already connected to."),(Ge.getSessionCreatedTimestamp()||0)>Ye)return;const je=new et(yield this.createRTCPeerConnection(K),{baseConfig:{isOffer:!1,isLan:!1,receive:(Be,$e)=>this.config.receive(Be,$e),onStreamsInfoUpdate:this.config.onStreamsInfoUpdate?(Be,$e)=>{var Ze,Ke;return(Ke=(Ze=this.config).onStreamsInfoUpdate)===null||Ke===void 0?void 0:Ke.call(Ze,Be,$e)}:void 0,track:this.config.lanOnlyMode?void 0:this.config.track,localPeerId:W.getPeerId(),localUserId:(Re=W.getUserId())===null||Re===void 0?void 0:Re.getValue(),remotePeerId:Ve},remoteConfig:{sessionId:ke,sessionCreatedTimestamp:Ye}},Be=>this.onCustomDataChannel(Ve,Be));yield je.handleSignal(Ie),this.connections.push(je)}else g.a.debug("Received signal: for an existing connection."),yield Ge.handleSignal(Ie);else{g.a.debug("Received signal: new connection.");const je=new et(yield this.createRTCPeerConnection(K),{baseConfig:{isOffer:!1,isLan:!1,receive:(Be,$e)=>this.config.receive(Be,$e),onStreamsInfoUpdate:this.config.onStreamsInfoUpdate?(Be,$e)=>{var Ze,Ke;return(Ke=(Ze=this.config).onStreamsInfoUpdate)===null||Ke===void 0?void 0:Ke.call(Ze,Be,$e)}:void 0,track:this.config.lanOnlyMode?void 0:this.config.track,localPeerId:W.getPeerId(),localUserId:(le=W.getUserId())===null||le===void 0?void 0:le.getValue(),remotePeerId:Ve},remoteConfig:{sessionId:ke,sessionCreatedTimestamp:Ye}},Be=>this.onCustomDataChannel(Ve,Be));yield je.handleSignal(Ie),this.connections.push(je)}})),he.on("end",()=>{he.cancel(),this.receiveSignalStream=void 0}),he.on("error",me=>{switch(me.code){case te.StatusCode.CANCELLED:case te.StatusCode.UNAVAILABLE:case te.StatusCode.UNKNOWN:g.a.debug("Receive signal stream error",{error:me});break;case te.StatusCode.UNAUTHENTICATED:g.a.warn("Receive signal stream error",{error:me});break;default:g.a.error("Receive signal stream error",{error:me})}he.cancel(),this.receiveSignalStream=void 0}),this.receiveSignalStream=he})}createRTCPeerConnection(x){var W;return Le(this,void 0,void 0,function*(){const K=(W=this.config.alternateRTCPeerConnection)!==null&&W!==void 0?W:window.RTCPeerConnection;if(!K)throw function(){const{userAgent:re}=navigator;return re.includes("Firefox/")?"Firefox":re.includes("Edg/")?"Edge":re.includes("Chrome/")?"Chrome":re.includes("Safari/")?"Safari":re.includes("MSIE/")||re.includes("Trident/")?"IE":"Other"}()!=="Chrome"?new Error("WebRTC is not enabled. Please try again with the latest version of Google Chrome."):new Error("WebRTC is not enabled. Please ensure WebRTC is not disabled by ad blocking software.");return new K({iceServers:x})})}closeConnections(x){return Le(this,void 0,void 0,function*(){const W=yield w(x.map(K=>Le(this,void 0,void 0,function*(){yield K.close()})));for(const K of W)g.a.warn("Request to close session failed",{error:K})})}getActiveConnection(x){return this.getConnections().find(W=>W.getRemotePeerId()===x&&W.isActive())}update(){var x;return Le(this,void 0,void 0,function*(){if(this.localConnections=this.localConnections.filter(me=>me.isActive()),this.config.lanOnlyMode)return;const{signalingClient:W}=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(me=>!me.isActive())),this.connections=this.connections.filter(me=>me.isActive());const{localPeer:K}=this,re=this.connections.filter(me=>me.getSessionId).map(me=>h(me.getSessionId()));K.setSessionIdsList(re);const oe=new Q.RefreshPeerRequest;oe.setPeer(K);try{yield W.refreshPeer(oe,yield this.getMetadata({}))}catch(me){me.code===te.StatusCode.NOT_FOUND?(g.a.warn("Peer expired, creating new peer",{peerId:K.getPeerId()}),yield this.reset()):g.a.warn("Error calling RefreshPeer",{error:me})}const he=yield this.getPeers();for(const me of this.connections)me.setRemoteDeviceId((x=he.find(pe=>pe.id===me.getRemotePeerId()))===null||x===void 0?void 0:x.deviceId)})}reset(){return Le(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 Le(this,void 0,void 0,function*(){if(this.config.lanOnlyMode)return;const{iceServersLastUpdate:x,iceServersTtl:W}=this,K=new Date().getTime();if(!x||K-x>W)try{const re=(yield this.config.signalingClient.getIceServers(new Q.GetIceServersRequest,yield this.getMetadata({}))).getIceServers();this.iceServers=JSON.parse(re),this.iceServersLastUpdate=K}catch(re){g.a.warn("Error in updateIceServers",{error:re})}})}setupHandlers(x){const{peerConnection:W}=x,K=x.getSessionCreatedTimestamp();W.onconnectionstatechange=()=>Le(this,void 0,void 0,function*(){const re=W.connectionState;if(K)switch(re){case"connected":d.aggregate("rtc-connect-time",new Date().getTime()-K);break;case"failed":d.increment("rtc-connect-failed")}})}getMetadata(x){return Le(this,void 0,void 0,function*(){if(this.config.lanOnlyMode)throw new Error("getMetadata method cannot be called in local-only mode");const{getToken:W}=this.config,{grpcCallDeadline:K}=this,{hasDeadline:re}=x,oe=re===!1?void 0:new Date().getTime()+K;return{authorization:yield W(),deadline:oe}})}}var ft=n(10),ut=n(11),Ot=function(ye,x,W,K){return new(W||(W=Promise))(function(re,oe){function he(ue){try{pe(K.next(ue))}catch(le){oe(le)}}function me(ue){try{pe(K.throw(ue))}catch(le){oe(le)}}function pe(ue){var le;ue.done?re(ue.value):(le=ue.value,le instanceof W?le:new W(function(Re){Re(le)})).then(he,me)}pe((K=K.apply(ye,x||[])).next())})};class Ct{constructor(x,W){this.sessionId=x,this.connection=W,this.sentMessagesCounts=new Map,this.receivedMessagesCounts=new Map,this.sessionId=x,this.connection=W}incrementMessageSent(x){const W=Oe(x.header.stream);this.sentMessagesCounts.set(W,(this.sentMessagesCounts.get(W)||0)+1)}incrementMessageReceived(x){const W=Oe(x.header.stream);this.receivedMessagesCounts.set(W,(this.receivedMessagesCounts.get(W)||0)+1)}uploadMetrics(){return Ot(this,void 0,void 0,function*(){const{sessionId:x}=this,W=yield this.connection.peerConnection.getStats(),K={};W.forEach(oe=>K[oe.id]=oe),g.a.debug("rtc-stats",Object.assign(Object.assign({},K),{sessionId:x}));const re=[...new Set(Array.from(this.sentMessagesCounts.keys()).concat(Array.from(this.receivedMessagesCounts.keys())))].reduce((oe,he)=>{const me=this.sentMessagesCounts.get(he),pe=this.receivedMessagesCounts.get(he);return Object.assign(Object.assign({},oe),{[`${he}-sent`]:me,[`${he}-received`]:pe})},{sessionId:x});g.a.debug("rtc-message-report",re)})}}function ct(ye,x){return Oe(ye)===Oe(x)}var tt=function(ye,x,W,K){return new(W||(W=Promise))(function(re,oe){function he(ue){try{pe(K.next(ue))}catch(le){oe(le)}}function me(ue){try{pe(K.throw(ue))}catch(le){oe(le)}}function pe(ue){var le;ue.done?re(ue.value):(le=ue.value,le instanceof W?le:new W(function(Re){Re(le)})).then(he,me)}pe((K=K.apply(ye,x||[])).next())})};class It{constructor(x,W){this.peerConnection=x,this.config=W,this.connectTimeoutMs=10*c.a.second,this.gatherIceTimeoutMs=5*c.a.second,this.pingUpdateTimeoutMs=2*c.a.second,this.streamLatestTimestamp=new Map,this.closeCalled=!1,this.connectCalled=!1,this.sentOffer=!1,this.receivedIceCandidate=!1;const{isOffer:K}=W;K?this.initializeChannels(x):x.ondatachannel=re=>{switch(re.channel.label){case"stream.latest-ttl":this.latestTtlStreamChannel=re.channel;break;case"stream.reliable":this.reliableStreamChannel=re.channel;break;case"stream.latest-reliable":this.latestReliableStreamChannel=re.channel;break;case"stream.latest-try-once":this.latestTryOnceStreamChannel=re.channel}this.setupChannel(re.channel)},this.sessionMetrics=new Ct(this.getSessionId(),this)}connect(){return tt(this,void 0,void 0,function*(){if(this.connectCalled)return;this.connectCalled=!0,this.pingUpdateTimeout=setInterval(()=>{const{reliableStreamChannel:re}=this;re&&this.sendSystemMessage(re,{type:"ping"})},this.pingUpdateTimeoutMs),this.connectTimeout=setTimeout(()=>tt(this,void 0,void 0,function*(){this.isReady()||(g.a.warn("RTC connect timed out, closing connection"),yield this.close())}),this.connectTimeoutMs);const{peerConnection:x,config:{isOffer:W,sessionId:K}}=this;if(W){const re=yield x.createOffer();yield x.setLocalDescription(re)}W&&(this.gatherIceTimeout=setTimeout(()=>tt(this,void 0,void 0,function*(){this.sentOffer||(g.a.warn("ICE gathering timed out"),this.receivedIceCandidate?(g.a.warn("Attempting to connect with partial ICE candidate pool"),yield this.sendOffer()):yield this.close())}),this.gatherIceTimeoutMs),x.onicecandidate=re=>tt(this,void 0,void 0,function*(){re.candidate?this.receivedIceCandidate=!0:yield this.sendOffer()}),x.onicegatheringstatechange=()=>tt(this,void 0,void 0,function*(){x.iceGatheringState==="complete"&&(yield this.sendOffer())}),x.onnegotiationneeded=()=>{g.a.debug("Negotiation needed",{sessionId:K})})})}handleSignal(x){return tt(this,void 0,void 0,function*(){const{peerConnection:W,config:{sessionId:K,sendSignal:re}}=this,{description:oe}=JSON.parse(x.payload);if(g.a.debug("Handling signal",{sessionId:K,description:JSON.stringify(oe)}),oe)if(W.signalingState!=="stable"||W.connectionState!=="connected")if(W.remoteDescription)g.a.warn(`Received SDP signal during negotiation when remote description is already set: ${JSON.stringify(x)}`);else if(oe.type==="offer"){yield W.setRemoteDescription(oe);const he=yield W.createAnswer();yield W.setLocalDescription(he),yield re({payload:JSON.stringify({description:he})})}else oe.type==="answer"&&(yield W.setRemoteDescription(oe));else g.a.warn(`Received SDP signal when signaling is stable and connected: ${JSON.stringify(x)}`);else g.a.warn(`Received non-SDP signal: ${JSON.stringify(x)}`)})}send(x,W){const K=this.getChannelFromLabel(W.channelLabel);K?this.sendOnChannel(K,x):g.a.warn("Send called with unexpected channel label",{channelLabel:W.channelLabel})}controlRemoteStream(x){this.sendSystemMessage(h(this.reliableStreamChannel),{type:"stream-control",streamControl:x})}isActive(){return new Set(["new","connecting","connected"]).has(this.peerConnection.connectionState)}isReady(){const{peerConnection:x,latestTtlStreamChannel:W,reliableStreamChannel:K,latestTryOnceStreamChannel:re}=this;return!!(K&&W&&re)&&x.connectionState==="connected"&&K.readyState==="open"&&W.readyState==="open"&&re.readyState==="open"}isClosed(){const{peerConnection:x,reliableStreamChannel:W,latestTryOnceStreamChannel:K,latestTtlStreamChannel:re}=this;return!(x.connectionState!=="closed"||W!==void 0&&W.readyState!=="closed"||K!==void 0&&K.readyState!=="closed"||re!==void 0&&re.readyState!=="closed")}needsClosing(){const{peerConnection:x,latestTtlStreamChannel:W,reliableStreamChannel:K,latestTryOnceStreamChannel:re}=this;if(this.isClosed())return!1;const oe=new Set(["closing","closed"]),he=me=>me&&oe.has(me.readyState);return Te(x)||he(W)||he(K)||he(re)}close(){return tt(this,void 0,void 0,function*(){this.closeCalled||(this.closeCalled=!0,yield this.sessionMetrics.uploadMetrics(),this.pingUpdateTimeout&&clearInterval(this.pingUpdateTimeout),this.connectTimeout&&clearTimeout(this.connectTimeout),this.gatherIceTimeout&&clearTimeout(this.gatherIceTimeout),this.peerConnection.close())})}getPing(){return this.pingTimeMs}getLastMessageTimestamp(){return this.lastMessageTimestamp}getSessionId(){return this.config.sessionId}getRemotePeer(){return this.config.remotePeer}initializeChannels(x){this.latestTtlStreamChannel=x.createDataChannel("stream.latest-ttl",v),this.reliableStreamChannel=x.createDataChannel("stream.reliable",S),this.latestReliableStreamChannel=x.createDataChannel("stream.latest-reliable",U),this.latestTryOnceStreamChannel=x.createDataChannel("stream.latest-try-once",J),this.setupChannel(this.latestTtlStreamChannel),this.setupChannel(this.reliableStreamChannel),this.setupChannel(this.latestReliableStreamChannel),this.setupChannel(this.latestTryOnceStreamChannel)}sendOffer(){return tt(this,void 0,void 0,function*(){if(this.sentOffer||(this.sentOffer=!0,Te(this.peerConnection)))return;const{peerConnection:x,config:{sendSignal:W}}=this,K=yield x.createOffer();yield x.setLocalDescription(K);const re={payload:JSON.stringify({description:K})};yield W(re)})}getChannelFromLabel(x){switch(x){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(x,W){let K;try{K=Object(H.encode)(JSON.stringify(W))}catch(re){return void g.a.warn("Failed to encode RTC message",{error:re})}try{x.send(K),this.sessionMetrics.incrementMessageSent(W)}catch(re){g.a.warn("Failed to send message to channel",{error:re,channel:x.label})}}channelNotRecognized(x){return x!==this.latestTtlStreamChannel&&x!==this.latestReliableStreamChannel&&x!==this.latestTryOnceStreamChannel&&x!==this.reliableStreamChannel}setupChannel(x){x.onmessage=W=>{if(this.channelNotRecognized(x))return void g.a.warn("Received message on unrecognized data channel.");let K;try{K=JSON.parse(Object(H.decode)(W.data))}catch(re){return void g.a.warn("Received unparseable RTC message",{error:re,channel:x.label})}if(this.lastMessageTimestamp=new Date().getTime(),K=De(K),this.sessionMetrics.incrementMessageReceived(K),!this.handleSystemMessage(x,K)){if(!this.hasCapabilities(K))return void g.a.warn("Received RTC message that was not within the capability scope of the connection.");(x===this.latestTryOnceStreamChannel||x===this.latestTtlStreamChannel||x===this.latestReliableStreamChannel)&&!this.isLatestMessage(K)||this.config.receive(this.config.remotePeer.id,K)}},x.onerror=W=>{g.a.warn(`Channel error: ${W.error}`,{error:W.error,sessionId:this.getSessionId(),channelLabel:x.label})},x.onopen=()=>{g.a.debug("Channel opened",{sessionId:this.getSessionId(),channelLabel:x.label})},x.onclose=()=>{const W={bufferedAmount:x.bufferedAmount,sessionId:this.getSessionId(),channelLabel:x.label};this.closeCalled===!1?g.a.debug("Unexpected channel closed",W):g.a.debug("Channel closed",W)}}handleSystemMessage(x,W){switch(W.header.stream.streamType){case"ping":return this.sendSystemMessage(x,{type:"pong",timestamp:h(W.payload.ping)}),!0;case"pong":{const K=new Date().getTime()-h(W.payload.pong);return this.pingTimeMs=K,d.aggregate("rtc-ping-time",K),!0}case"stream-control":return!0;default:return!1}}sendSystemMessage(x,W){if(x.readyState!=="open")return;const K={entityId:h(this.config.localPeer.deviceId||this.config.localPeer.userId),streamName:`$.${W.type}`,streamType:W.type};let re;switch(W.type){case"ping":re={ping:new Date().getTime()};break;case"pong":re={pong:W.timestamp};break;case"stream-control":re={streamControl:W.streamControl}}this.sendOnChannel(x,Ee(K,re))}hasCapabilities(x){var W,K;const{localPeer:re,remotePeer:oe}=this.config,he=(W=re.capabilitySet.streaming)===null||W===void 0?void 0:W.streams,me=he&&he.some(le=>le.receive&&ct(le.stream,x.header.stream)),pe=(K=oe.capabilitySet.streaming)===null||K===void 0?void 0:K.streams,ue=pe&&pe.some(le=>le.send&&ct(le.stream,x.header.stream));return me||ue}isLatestMessage(x){const W=Oe(x.header.stream),K=(this.streamLatestTimestamp.get(W)||0)<=x.header.created;return K&&this.streamLatestTimestamp.set(W,x.header.created),K}}var Ue=function(ye,x,W,K){return new(W||(W=Promise))(function(re,oe){function he(ue){try{pe(K.next(ue))}catch(le){oe(le)}}function me(ue){try{pe(K.throw(ue))}catch(le){oe(le)}}function pe(ue){var le;ue.done?re(ue.value):(le=ue.value,le instanceof W?le:new W(function(Re){Re(le)})).then(he,me)}pe((K=K.apply(ye,x||[])).next())})};class jt{constructor(x){this.config=x,this.connections=[],this.connectingSessions=new Map,this.updateInterval=f({func:()=>Ue(this,void 0,void 0,function*(){try{yield this.update()}catch(W){g.a.warn("RTC update failed",{error:W})}}),delay:250*c.a.millisecond,immediate:!0}),this.localPeer=this.createPeer()}send(x,W,K){const re=this.getActiveConnection(x);re?re.isReady()?re.send(W,K):g.a.warn("Attempted to send with an active connection to that peer which was not yet ready."):g.a.warn("Attempted to send with no active connection to that peer.")}controlRemoteStream(x,W){const K=this.getActiveConnection(x);K?K.isReady()?K.controlRemoteStream(W):g.a.warn("Attempted to control remote stream with an active connection to that peer which was not yet ready."):g.a.warn("Attempted to control remote stream with no active connection to that peer.")}connect(x){return Ue(this,void 0,void 0,function*(){const W=yield this.getLocalPeer();if(this.getActiveConnection(x))return void g.a.warn("Attempted to connect to peer with an already active connection.");let K;try{K=yield this.config.signalingClient.createSession(yield this.config.getToken(),{offerPeerId:W.id,answerPeerId:x})}catch(re){Object(ft.a)(re,ut.a,oe=>oe.statusCode===404),g.a.warn("Attempted to connect to peer that does not exist.")}if(K)for(this.connectingSessions.set(K.id,new Date().getTime()),yield this.connectToSession(K);;)switch(yield Object(u.a)(.1),this.getConnectionStatus(x)){case"connecting":continue;case"connected":return K.id;case"disconnected":return}})}getConnectionStatus(x){const W=this.getActiveConnection(x);return W?W.isReady()?"connected":"connecting":"disconnected"}getIceMode(x){const W=this.getActiveConnection(x);if(W)return W.iceMode}disconnect(x){return Ue(this,void 0,void 0,function*(){const W=this.getActiveConnection(x);W&&(yield this.closeConnection(W))})}getLocalPeer(){return Ue(this,void 0,void 0,function*(){return yield this.localPeer})}getPeers(){return Ue(this,void 0,void 0,function*(){return yield this.config.signalingClient.getPeers(yield this.config.getToken())})}getPing(x){const W=this.getActiveConnection(x);if(W)return W.getPing();g.a.warn("Attempted to get ping time from inactive peer.")}getLastMessageTimestamp(x){const W=this.getActiveConnection(x);if(W)return W.getLastMessageTimestamp();g.a.warn("Attempted to get ping time from inactive peer.")}shutdown(){return Ue(this,void 0,void 0,function*(){yield this.updateInterval.stop();const x=this.connections;this.connections=[],yield this.closeConnections(x)})}closeConnection(x){return Ue(this,void 0,void 0,function*(){this.connectingSessions.delete(x.getSessionId()),yield x.close();try{yield this.config.signalingClient.deleteSession(yield this.config.getToken(),x.getSessionId())}catch(W){Object(ft.a)(W,ut.a,K=>K.statusCode===404)}})}getSessions(){return Ue(this,void 0,void 0,function*(){const x=yield this.getLocalPeer();return(yield this.config.signalingClient.getSessions(yield this.config.getToken())).filter(W=>W.offer.peer.id===x.id||W.answer.peer.id===x.id)})}createPeer(){return Ue(this,void 0,void 0,function*(){return yield this.config.signalingClient.createPeer(yield this.config.getToken(),{capabilitySet:this.config.capabilitySet||{}})})}createRTCPeerConnection(x={}){return Ue(this,void 0,void 0,function*(){return new(this.config.alternateRTCPeerConnection||RTCPeerConnection)(Object.assign({iceServers:yield this.config.signalingClient.getIceServers(yield this.config.getToken())},x))})}closeConnections(x){return Ue(this,void 0,void 0,function*(){const W=yield w(x.map(K=>Ue(this,void 0,void 0,function*(){yield this.closeConnection(K)})));for(const K of W)g.a.warn("Request to close session failed",{error:K})})}reset(){return Ue(this,void 0,void 0,function*(){yield this.closeConnections(this.connections),this.connections=[],this.connectingSessions=new Map,this.localPeer=this.createPeer(),yield this.localPeer})}getActiveConnection(x){return this.connections.find(W=>W.getRemotePeer().id===x&&W.isActive())}update(){return Ue(this,void 0,void 0,function*(){const x=yield this.getLocalPeer();try{yield this.config.signalingClient.refreshPeer(yield this.config.getToken(),x.id)}catch(W){Object(ft.a)(W,ut.a,K=>K.statusCode===404),g.a.warn("Peer expired, creating new peer",{peerId:x.id}),yield this.reset()}yield this.handleSessions(yield this.getSessions())})}handleSessions(x){return Ue(this,void 0,void 0,function*(){yield this.syncConnectionsAndSessions(x);const W=x.map(K=>({session:K,connection:this.connections.find(re=>re.getSessionId()===K.id)}));yield Promise.all(W.map(({session:K,connection:re})=>Ue(this,void 0,void 0,function*(){return yield this.maintainConnection(K,re)})))})}syncConnectionsAndSessions(x){return Ue(this,void 0,void 0,function*(){const W=new Set(x.map(oe=>oe.id)),K=oe=>W.has(oe.getSessionId())||this.connectingSessions.has(oe.getSessionId());this.connections=this.connections.filter(oe=>K(oe));const re=this.connections.filter(oe=>!K(oe)||oe.needsClosing());yield Promise.all(re.map(oe=>Ue(this,void 0,void 0,function*(){yield this.closeConnection(oe)})))})}maintainConnection(x,W){return Ue(this,void 0,void 0,function*(){const K=yield this.getLocalPeer(),re=x.offer.peer.id===K.id;if(W){if(W.isReady())try{yield this.config.signalingClient.refreshSession(yield this.config.getToken(),x.id)}catch(oe){Object(ft.a)(oe,ut.a,he=>he.statusCode===404),g.a.debug("Refresh session not found",{sessionId:x.id})}else if(W.isActive())try{yield this.consumeSignals(W)}catch(oe){g.a.warn("Failed to ingest signals, closing connection",{error:oe}),yield this.closeConnection(W)}}else{if(re)return;yield this.connectToSession(x)}})}connectToSession(x){return Ue(this,void 0,void 0,function*(){const W=yield this.getLocalPeer(),K=x.offer.peer.id===W.id,re=yield this.createRTCPeerConnection(),oe=new It(re,{localPeer:K?x.offer.peer:x.answer.peer,remotePeer:K?x.answer.peer:x.offer.peer,sessionId:x.id,isOffer:K,sendSignal:he=>this.sendSignal(x.id,he),receive:(he,me)=>this.config.receive(he,me)});if(this.connections.find(he=>he.getSessionId()===x.id))return g.a.warn("connectToSession called on a session that already has a connection.",{sessionId:x.id}),void(yield oe.close());this.setupHandlers(oe),this.connections.push(oe);try{yield oe.connect()}catch(he){g.a.warn("Failed to handle negotiation, closing connection",{error:he}),yield this.closeConnection(oe)}})}setupHandlers(x){const{peerConnection:W}=x,K=x.getSessionId();W.onconnectionstatechange=()=>Ue(this,void 0,void 0,function*(){const re=this.connectingSessions.get(K);if(re===void 0)return;const oe=W.connectionState;switch(Te(W)&&this.connectingSessions.delete(K),oe){case"connected":{this.connectingSessions.delete(K);const he=new Date().getTime()-re;d.aggregate("rtc-connect-time",he);break}case"failed":d.increment("rtc-connect-failed"),yield this.closeConnection(x)}})}consumeSignals(x){return Ue(this,void 0,void 0,function*(){let W=[];try{W=yield this.config.signalingClient.takeSignals(yield this.config.getToken(),x.getSessionId())}catch(K){Object(ft.a)(K,ut.a,re=>re.statusCode===404)}for(const K of W)yield x.handleSignal(K)})}sendSignal(x,W){return Ue(this,void 0,void 0,function*(){try{yield this.config.signalingClient.addSignals(yield this.config.getToken(),x,{signals:[W]})}catch(K){Object(ft.a)(K,ut.a,re=>re.statusCode===404)}})}}},function(e,t,n){var r={randomUUID:typeof crypto!="undefined"&&crypto.randomUUID&&crypto.randomUUID.bind(crypto)};let o;const l=new Uint8Array(16);function s(){if(!o&&(o=typeof crypto!="undefined"&&crypto.getRandomValues&&crypto.getRandomValues.bind(crypto),!o))throw new Error("crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported");return o(l)}const i=[];for(let u=0;u<256;++u)i.push((u+256).toString(16).slice(1));function c(u,m=0){return(i[u[m+0]]+i[u[m+1]]+i[u[m+2]]+i[u[m+3]]+"-"+i[u[m+4]]+i[u[m+5]]+"-"+i[u[m+6]]+i[u[m+7]]+"-"+i[u[m+8]]+i[u[m+9]]+"-"+i[u[m+10]]+i[u[m+11]]+i[u[m+12]]+i[u[m+13]]+i[u[m+14]]+i[u[m+15]]).toLowerCase()}t.a=function(u,m,R){if(r.randomUUID&&!m&&!u)return r.randomUUID();const E=(u=u||{}).random||(u.rng||s)();if(E[6]=15&E[6]|64,E[8]=63&E[8]|128,m){R=R||0;for(let y=0;y<16;++y)m[R+y]=E[y];return m}return c(E)}},,function(e,t,n){n.r(t),n.d(t,"LogClient",function(){return i});var r=n(28),o=n(10),l=n(11),s=function(c,u,m,R){return new(m||(m=Promise))(function(E,y){function g(L){try{T(R.next(L))}catch(z){y(z)}}function _(L){try{T(R.throw(L))}catch(z){y(z)}}function T(L){var z;L.done?E(L.value):(z=L.value,z instanceof m?z:new m(function(M){M(z)})).then(g,_)}T((R=R.apply(c,u||[])).next())})};class i extends r.a{log(u){return s(this,void 0,void 0,function*(){const m=i.token;try{yield this.fetch("logs",{token:m,method:"POST",body:JSON.stringify({logs:u}),allowUnsafeRetries:!0})}catch(R){Object(o.a)(R,l.a,E=>E.statusCode===401&&m!==void 0),i.token===m&&delete i.token,yield this.log(u)}})}}}])})})(dist);function defined(e,t){if(e!==void 0)return e;throw new Error(t||"Value is undefined")}let FORMANT_API_URL="https://api.formant.io";typeof window!="undefined"&&(FORMANT_API_URL=window.FORMANT_API_URL||FORMANT_API_URL);let urlParams$2=new URLSearchParams("");typeof window!="undefined"&&(urlParams$2=new URLSearchParams(window.location.search));const envDev=urlParams$2.get("formant_dev");envDev&&(FORMANT_API_URL="https://api-dev.formant.io");const envStage=urlParams$2.get("formant_stage");envStage&&(FORMANT_API_URL="https://api-stage.formant.io");const envLocal=urlParams$2.get("formant_local");envLocal&&(FORMANT_API_URL="https://api.formant.local");function delay(e){return new Promise(t=>setTimeout(t,e))}class DataChannel{constructor(t){Ae(this,"ready",!1);Ae(this,"listeners",[]);Ae(this,"openListeners",[]);Ae(this,"closeListeners",[]);Ae(this,"errorListeners",[]);Ae(this,"binaryListeners",[]);Ae(this,"error");Ae(this,"decoder",new TextDecoder);this.dataChannel=t,this.dataChannel.binaryType="arraybuffer",this.dataChannel.onopen=()=>{this.ready=!0,this.openListeners.forEach(n=>n())},this.dataChannel.onclose=()=>{this.ready=!1,this.closeListeners.forEach(n=>n())},this.dataChannel.onerror=n=>{console.error(n),this.error="An error occurred in DataChannel",this.errorListeners.forEach(r=>r(n))},this.dataChannel.onmessage=n=>{this.listeners.forEach(r=>{const o=new Uint8Array(n.data),l=this.decoder.decode(o);r(l)}),this.binaryListeners.forEach(r=>{r(new Uint8Array(n.data))})}}addOpenListener(t){this.openListeners.push(t)}removeOpenListener(t){this.openListeners=this.openListeners.filter(n=>n!==t)}addCloseListener(t){this.closeListeners.push(t)}removeCloseListener(t){this.closeListeners=this.closeListeners.filter(n=>n!==t)}addErrorListener(t){this.errorListeners.push(t)}removeErrorListener(t){this.errorListeners=this.errorListeners.filter(n=>n!==t)}async waitTilReady(){return this.ready?!0:new Promise((n,r)=>{let o=window.setInterval(()=>{this.ready&&(window.clearInterval(o),n(!0)),this.error&&r(this.error)},10)})}send(t){if(!this.ready)throw new Error("Connection has been closed");this.dataChannel.send(t)}sendBinary(t){if(!this.ready)throw new Error("Connection has been closed");this.dataChannel.send(t)}addListener(t){this.listeners.push(t)}removeListener(t){const n=this.listeners.indexOf(t);if(n===-1)throw new Error("Could not find data channel listener to remove");if(this.error)throw new Error(this.error);this.listeners.splice(n,1)}addBinaryListener(t){this.binaryListeners.push(t)}removeBinaryListener(t){const n=this.binaryListeners.indexOf(t);if(n===-1)throw new Error("Could not find data channel listener to remove");if(this.error)throw new Error(this.error);this.binaryListeners.splice(n,1)}}class CaptureStream{constructor(t){Ae(this,"token");this.captureSession=t}async ingestJSON(t){if(!this.token){const r=await(await fetch(`${FORMANT_API_URL}/v1/admin/capture-sessions/${this.captureSession.code}/authenticate`,{method:"POST"})).json();this.token=r.token}await fetch(`${FORMANT_API_URL}/v1/ingest`,{method:"POST",body:JSON.stringify({deviceId:this.captureSession.deviceId,name:this.captureSession.streamName,type:"json",points:[[Date.now(),JSON.stringify(t)]]}),headers:{"Content-Type":"application/json",Authorization:"Bearer "+this.token}})}}class Manipulator{constructor(t,n){Ae(this,"currentListeners",[]);Ae(this,"onRealtimeMessage",(t,n)=>{n.payload.jointState&&this.currentListeners.forEach(r=>{n.payload.jointState&&r(n.payload.jointState)})});this.device=t,this.config=n}async synchronize(){this.device.addRealtimeListener(this.onRealtimeMessage),this.device.startListeningToRealtimeDataStream(this.config.currentJointStateStream)}async desynchronize(){this.device.removeRealtimeListener(this.onRealtimeMessage),this.device.stopListeningToRealtimeDataStream(this.config.currentJointStateStream)}async addCurrentJointStateListener(t){this.currentListeners.push(t)}}class RequestDataChannel{constructor(t,n,r){Ae(this,"channel");Ae(this,"requestIdToResponseMap",new Map);this.device=t,this.channel_name=n,this.timeout=r}addOpenListener(t){defined(this.channel,"channel not initalized").addOpenListener(t)}removeOpenListener(t){defined(this.channel,"channel not initalized").removeOpenListener(t)}addCloseListener(t){defined(this.channel,"channel not initalized").addCloseListener(t)}removeCloseListener(t){defined(this.channel,"channel not initalized").removeCloseListener(t)}addErrorListener(t){defined(this.channel,"channel not initalized").addErrorListener(t)}removeErrorListener(t){defined(this.channel,"channel not initalized").removeErrorListener(t)}}class BinaryRequestDataChannel extends RequestDataChannel{constructor(){super(...arguments);Ae(this,"RESPONSE_SUCCESS_BYTE",0);Ae(this,"decoder",new TextDecoder)}generateBinaryId(){const n=new Uint8Array(16);for(let r=0;r<n.length;r++)n[r]=Math.floor(Math.random()*256);return n}async initialize(){this.channel=await this.device.createCustomDataChannel(this.channel_name),this.channel.addBinaryListener(n=>{const o=n.slice(0,16).toString();if(o.length===0)throw new Error("Invalid response");const l=n.slice(16);if(l.length===0)throw new Error("Invalid response");this.requestIdToResponseMap.has(o)&&this.requestIdToResponseMap.set(o,l)})}async request(n){if(this.channel||await this.initialize(),!this.channel)throw new Error("Failed to create channel");const{channel:r,requestIdToResponseMap:o,timeout:l}=this;await r.waitTilReady();const s=this.generateBinaryId(),i=s.toString();o.set(i,!0),r.sendBinary(new Uint8Array([...s,...n]));const c=new Date().getTime();for(;new Date().getTime()<c+l;)if(await delay(50),o.has(i)){const u=o.get(i);if(u!==!0){o.delete(i);const m=u[0]===this.RESPONSE_SUCCESS_BYTE,R=u.slice(1);if(m)return R;throw console.error({name:"AdapterError",message:this.decoder.decode(R)}),new Error("Binary request datachannel adapter error")}}throw o.delete(i),console.error({name:"TimeoutError",message:`Request timed out after ${l/1e3} seconds`}),new Error("Binary request data channel request timed out")}}class TextRequestDataChannel extends RequestDataChannel{generateTextId(){return Math.random().toString(36).substring(2)+"-"+Math.random().toString(36).substring(2)}async initialize(){this.channel=await this.device.createCustomDataChannel(this.channel_name),this.channel.addListener(t=>{const n=JSON.parse(t),{id:r,data:o,error:l}=n;if(!r)throw new Error("Invalid response");if(!o&&!l)throw new Error("Invalid response");this.requestIdToResponseMap.has(r)&&this.requestIdToResponseMap.set(r,n)})}async request(t){if(this.channel||await this.initialize(),!this.channel)throw new Error("Failed to create channel");const{channel:n,requestIdToResponseMap:r,timeout:o}=this;await n.waitTilReady();const l=this.generateTextId();r.set(l,!0),n.send(JSON.stringify({id:l,data:t}));const s=new Date().getTime();for(;new Date().getTime()<s+o;)if(await delay(50),r.has(l)){const i=r.get(l);if(i!==!0){r.delete(l);const{data:c,error:u}=i;if(c)return c;if(u)throw console.error({name:"AdapterError",message:u}),new Error("Text request datachannel adapter error")}}throw r.delete(l),console.error({name:"TimeoutError",message:`Request timed out after ${o/1e3} seconds`}),new Error("Text request datachannel request timed out")}}const urlParams$1=new URLSearchParams(window.location.search),rtcClientVersion=urlParams$1.get("rtc_client"),SessionType={Teleop:1,Observe:3};class Device{constructor(t,n,r){Ae(this,"rtcClient");Ae(this,"remoteDevicePeerId");Ae(this,"realtimeListeners",[]);Ae(this,"handleMessage",(t,n)=>{this.realtimeListeners.forEach(r=>r(t,n))});this.id=t,this.name=n,this.organizationId=r}async getLatestTelemetry(){return(await(await fetch(`${FORMANT_API_URL}/v1/queries/stream-current-value`,{method:"POST",body:JSON.stringify({deviceIds:[this.id]}),headers:{"Content-Type":"application/json",Authorization:"Bearer "+Authentication.token}})).json()).items}async getConfiguration(){let t=await fetch(`${FORMANT_API_URL}/v1/admin/devices/${this.id}`,{method:"GET",headers:{"Content-Type":"application/json",Authorization:"Bearer "+Authentication.token}});const n=await t.json();if(!n.state.reportedConfiguration)throw new Error("Device has no configuration, has it ever been turned on?");const r=n.state.reportedConfiguration.version;return t=await fetch(`${FORMANT_API_URL}/v1/admin/devices/${this.id}/configurations/${r}`,{method:"GET",headers:{"Content-Type":"application/json",Authorization:"Bearer "+Authentication.token}}),(await t.json()).document}async getFileUrl(t){return(await(await fetch(`${FORMANT_API_URL}/v1/admin/files/query`,{method:"POST",body:JSON.stringify({fileIds:[t]}),headers:{"Content-Type":"application/json",Authorization:"Bearer "+Authentication.token}})).json()).fileUrls}getRealtimeStatus(){if(this.rtcClient&&this.remoteDevicePeerId)return this.rtcClient.getConnectionStatus(this.remoteDevicePeerId);throw new Error(`Realtime connection hasn't been started for ${this.id}`)}getRealtimePing(){if(this.rtcClient&&this.remoteDevicePeerId)return this.rtcClient.getPing(this.remoteDevicePeerId);throw new Error(`Realtime connection hasn't been started for ${this.id}`)}async startRealtimeConnection(t){if(this.rtcClient)throw new Error(`Already created realtime connection to device ${this.id}`);{let n;if(rtcClientVersion==="1"?n=new dist.exports.RtcClientV1({signalingClient:new dist.exports.RtcSignalingClient(FORMANT_API_URL+"/v1/signaling"),getToken:async()=>defined(Authentication.token,"Realtime when user isn't authorized"),receive:this.handleMessage}):n=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,sessionType:t}),n.isReady)for(;!n.isReady();)await delay(100);const o=(await n.getPeers()).find(l=>l.deviceId===this.id);if(!o)throw new Error("Cannot find peer, is the robot offline?");for(this.remoteDevicePeerId=o.id,await n.connect(this.remoteDevicePeerId);n.getConnectionStatus(this.remoteDevicePeerId)!=="connected";)await delay(100);this.rtcClient=n}}async sendRealtimeMessage(t,n={channelLabel:"stream.reliable"}){const r=defined(this.rtcClient,"Realtime connection has not been started"),o=await this.getRemotePeer();r.send(defined(o).id,t,n)}addRealtimeListener(t){this.realtimeListeners.push(t)}removeRealtimeListener(t){const n=this.realtimeListeners.indexOf(t);if(n===-1)throw new Error("Could not find realtime listener to remove");this.realtimeListeners.splice(n,1)}async getRealtimeAudioStreams(){var r,o,l,s,i,c;const t=await this.getConfiguration(),n=[];for(const u of(o=(r=t.teleop)==null?void 0:r.hardwareStreams)!=null?o:[])u.rtcStreamType==="audio-chunk"&&n.push({name:u.name});for(const u of(s=(l=t.teleop)==null?void 0:l.rosStreams)!=null?s:[])u.topicType=="audio_common_msgs/AudioData"&&n.push({name:u.topicName});for(const u of(c=(i=t.teleop)==null?void 0:i.customStreams)!=null?c:[])u.rtcStreamType==="audio-chunk"&&n.push({name:u.name});return n}async getRealtimeVideoStreams(){var r,o,l,s,i,c;const t=await this.getConfiguration(),n=[];for(const u of(o=(r=t.teleop)==null?void 0:r.hardwareStreams)!=null?o:[])u.rtcStreamType==="h264-video-frame"&&n.push({name:u.name});for(const u of(s=(l=t.teleop)==null?void 0:l.rosStreams)!=null?s:[])u.topicType=="formant/H264VideoFrame"&&n.push({name:u.topicName});for(const u of(c=(i=t.teleop)==null?void 0:i.customStreams)!=null?c:[])u.rtcStreamType==="h264-video-frame"&&n.push({name:u.name});return n}async getRealtimeManipulators(){var r;const t=await this.getConfiguration(),n=[];for(const o of(r=t.teleop.rosStreams)!=null?r:[])o.topicType=="sensor_msgs/JointState"&&n.push(new Manipulator(this,{currentJointStateStream:{name:o.topicName},plannedJointStateStream:o.plannedTopic?{name:o.plannedTopic}:void 0,planValidStream:o.planValidTopic?{name:o.planValidTopic}:void 0,endEffectorStream:o.endEffectorTopic?{name:o.endEffectorTopic}:void 0,endEffectorLinkName:o.endEffectorLinkName,baseReferenceFrame:o.baseReferenceFrame,localFrame:o.localFrame}));return n}async startListeningToRealtimeVideo(t){const n=defined(this.rtcClient,"Realtime connection has not been started"),r=await this.getRemotePeer();n.controlRemoteStream(defined(r).id,{streamName:t.name,enable:!0,pipeline:"rtc"})}async stopListeningToRealtimeVideo(t){const n=defined(this.rtcClient,"Realtime connection has not been started"),r=await this.getRemotePeer();n.controlRemoteStream(defined(r).id,{streamName:t.name,enable:!1,pipeline:"rtc"})}async startListeningToRealtimeDataStream(t){const n=defined(this.rtcClient,"Realtime connection has not been started"),r=await this.getRemotePeer();n.controlRemoteStream(defined(r).id,{streamName:t.name,enable:!0,pipeline:"rtc"})}async stopListeningToRealtimeDataStream(t){const n=defined(this.rtcClient,"Realtime connection has not been started"),r=await this.getRemotePeer();n.controlRemoteStream(defined(r).id,{streamName:t.name,enable:!1,pipeline:"rtc"})}async enableRealtimeTelemetryPriorityIngestion(t){const n=defined(this.rtcClient,"Realtime connection has not been started"),r=await this.getRemotePeer();n.controlRemoteStream(defined(r).id,{streamName:t,enablePriorityUpload:!0,pipeline:"telemetry"})}async changeStreamAudioType(t,n){const r=defined(this.rtcClient,"Realtime connection has not been started"),o=await this.getRemotePeer();r.controlRemoteStream(defined(o).id,{streamName:t,setAudioFormat:n})}async disableRealtimeTelemetryPriorityIngestion(t){const n=defined(this.rtcClient,"Realtime connection has not been started"),r=await this.getRemotePeer();n.controlRemoteStream(defined(r).id,{streamName:t,enablePriorityUpload:!1,pipeline:"telemetry"})}async getRemotePeer(){const n=(await defined(this.rtcClient,"Realtime connection has not been started").getPeers()).find(r=>r.deviceId===this.id);return defined(n,"Could not find remote peer for device "+this.id)}async stopRealtimeConnection(){if(this.rtcClient)await this.rtcClient.disconnect(this.id);else throw new Error(`Realtime connection hasn't been started for ${this.id}`)}async isInRealtimeSession(){let t=await Fleet.getPeers(),n=await Fleet.getRealtimeSessions(),r=t.find(o=>o.deviceId===this.id);return r?n[r.id].length>0:!1}async getAvailableCommands(){return(await(await fetch(`${FORMANT_API_URL}/v1/admin/command-templates/`,{method:"GET",headers:{"Content-Type":"application/json",Authorization:"Bearer "+Authentication.token}})).json()).items.map(r=>({name:r.name,id:r.id,command:r.command,description:r.description,parameterEnabled:r.parameterEnabled,parameterValue:r.parameterValue,parameterMeta:r.parameterMeta,enabled:r.enabled}))}async sendCommand(t,n,r,o){var u;const s=(await this.getAvailableCommands()).find(m=>m.name===t);if(!s)throw new Error(`Could not find command with name "${t}"`);let i;if(n===void 0)if(s.parameterEnabled&&s.parameterValue)i=s.parameterValue;else throw new Error("Command has no default parameter value, you must provide one");else i=n;let c={value:i,scrubberTime:(r||new Date).toISOString(),meta:{...s.parameterMeta,...o}};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:c,userId:(u=Authentication.currentUser)==null?void 0:u.id}),headers:{"Content-Type":"application/json",Authorization:"Bearer "+Authentication.token}})}async createCustomDataChannel(t,n){if(rtcClientVersion==="1")throw new Error("createCustomDataChannel is not supported in rtcClientVersion 1");const r=defined(this.rtcClient,"Realtime connection has not been started"),o=await this.getRemotePeer(),l=await new Promise(s=>{r.createCustomDataChannel(defined(o).id,t,{ordered:!0,...n},!1,(i,c)=>{const u=new DataChannel(c);s(u)})});return await l.waitTilReady(),l}createCustomRequestDataChannel(t,n=3e3){return new TextRequestDataChannel(this,t,n)}createCustomBinaryRequestDataChannel(t,n=3e3){return new BinaryRequestDataChannel(this,t,n)}async createCaptureStream(t){const r=await(await fetch(`${FORMANT_API_URL}/v1/admin/capture-sessions`,{method:"POST",body:JSON.stringify({deviceId:this.id,streamName:t,tags:{}}),headers:{"Content-Type":"application/json",Authorization:"Bearer "+Authentication.token}})).json();return new CaptureStream(r)}async getTelemetry(t,n,r,o){return await Fleet.getTelemetry(this.id,t,n,r,o)}async getTelemetryStreams(){var i,c;const t=await this.getConfiguration(),n=await fetch(`${FORMANT_API_URL}/v1/queries/metadata/stream-names`,{method:"POST",body:JSON.stringify({deviceIds:[this.id]}),headers:{"Content-Type":"application/json",Authorization:"Bearer "+Authentication.token}}),r=[],o=[];return(c=(i=t.telemetry)==null?void 0:i.streams)==null||c.forEach(u=>{u.disabled!==!0&&r.push(u.name),u.onDemand===!0&&o.push(u.name)}),console.log(o),(await n.json()).items.filter(u=>!r.includes(u)).map(u=>({name:u,onDemand:o.includes(u)}))}async createInterventionRequest(t,n,r,o){return await(await fetch(`${FORMANT_API_URL}/v1/admin/intervention-requests`,{method:"POST",body:JSON.stringify({message:t,interventionType:n,time:new Date().toISOString(),deviceId:this.id,tags:o,data:r}),headers:{"Content-Type":"application/json",Authorization:"Bearer "+Authentication.token}})).json()}async addInterventionResponse(t,n,r){return await(await fetch(`${FORMANT_API_URL}/v1/admin/intervention-responses`,{method:"POST",body:JSON.stringify({interventionId:t,interventionType:n,data:r}),headers:{"Content-Type":"application/json",Authorization:"Bearer "+Authentication.token}})).json()}}class PeerDevice{constructor(t){Ae(this,"rtcClient");Ae(this,"remoteDevicePeerId");Ae(this,"realtimeListeners",[]);Ae(this,"id");Ae(this,"handleMessage",(t,n)=>{this.realtimeListeners.forEach(r=>r(t,n))});this.peerUrl=t}async getLatestTelemetry(){const n=await(await fetch(`${this.peerUrl}/telemetry`)).json();return Object.entries(n).map(([o,l])=>({deviceId:this.id,streamName:o,streamType:"json",currentValue:l,currentValueTime:l.timestamp,tags:{}}))}async getDeviceId(){return(await(await fetch(`${this.peerUrl}/configuration`)).json()).agent_config.id}async getConfiguration(){return(await(await fetch(`${this.peerUrl}/configuration`)).json()).agent_config.document}getRealtimeStatus(){if(this.rtcClient&&this.remoteDevicePeerId)return this.rtcClient.getConnectionStatus(this.remoteDevicePeerId);throw new Error("Realtime connection hasn't been started")}getRealtimePing(){if(this.rtcClient&&this.remoteDevicePeerId)return this.rtcClient.getPing(this.remoteDevicePeerId);throw new Error("Realtime connection hasn't been started")}async startRealtimeConnection(t){if(this.rtcClient)throw new Error(`Already created realtime connection to device ${this.id}`);{const n=new dist.exports.RtcClient({lanOnlyMode:!0,receive:this.handleMessage,sessionType:t});for(await n.connectLan(this.peerUrl);n.getConnectionStatus(this.peerUrl)!=="connected";)await delay(100);this.rtcClient=n}}addRealtimeListener(t){this.realtimeListeners.push(t)}removeRealtimeListener(t){const n=this.realtimeListeners.indexOf(t);if(n===-1)throw new Error("Could not find realtime listener to remove");this.realtimeListeners.splice(n,1)}async getRealtimeVideoStreams(){var r,o,l;const t=await this.getConfiguration(),n=[];for(const s of(r=t.teleop.hardwareStreams)!=null?r:[])s.rtcStreamType==="h264-video-frame"&&n.push({name:s.name});for(const s of(o=t.teleop.rosStreams)!=null?o:[])s.topicType=="formant/H264VideoFrame"&&n.push({name:s.topicName});for(const s of(l=t.teleop.customStreams)!=null?l:[])s.rtcStreamType==="h264-video-frame"&&n.push({name:s.name});return n}async getRealtimeManipulators(){var r;const t=await this.getConfiguration(),n=[];for(const o of(r=t.teleop.rosStreams)!=null?r:[])o.topicType=="sensor_msgs/JointState"&&n.push(new Manipulator(this,{currentJointStateStream:{name:o.topicName},plannedJointStateStream:o.plannedTopic?{name:o.plannedTopic}:void 0,planValidStream:o.planValidTopic?{name:o.planValidTopic}:void 0,endEffectorStream:o.endEffectorTopic?{name:o.endEffectorTopic}:void 0,endEffectorLinkName:o.endEffectorLinkName,baseReferenceFrame:o.baseReferenceFrame,localFrame:o.localFrame}));return n}async startListeningToRealtimeVideo(t){const n=defined(this.rtcClient,"Realtime connection has not been started"),r=await this.getRemotePeer();n.controlRemoteStream(defined(r).id,{streamName:t.name,enable:!0,pipeline:"rtc"})}async stopListeningToRealtimeVideo(t){const n=defined(this.rtcClient,"Realtime connection has not been started"),r=await this.getRemotePeer();n.controlRemoteStream(defined(r).id,{streamName:t.name,enable:!1,pipeline:"rtc"})}async startListeningToRealtimeDataStream(t){const n=defined(this.rtcClient,"Realtime connection has not been started"),r=await this.getRemotePeer();n.controlRemoteStream(defined(r).id,{streamName:t.name,enable:!0,pipeline:"rtc"})}async stopListeningToRealtimeDataStream(t){const n=defined(this.rtcClient,"Realtime connection has not been started"),r=await this.getRemotePeer();n.controlRemoteStream(defined(r).id,{streamName:t.name,enable:!1,pipeline:"rtc"})}async enableRealtimeTelemetryPriorityIngestion(t){const n=defined(this.rtcClient,"Realtime connection has not been started"),r=await this.getRemotePeer();n.controlRemoteStream(defined(r).id,{streamName:t,enablePriorityUpload:!0,pipeline:"telemetry"})}async disableRealtimeTelemetryPriorityIngestion(t){const n=defined(this.rtcClient,"Realtime connection has not been started"),r=await this.getRemotePeer();n.controlRemoteStream(defined(r).id,{streamName:t,enablePriorityUpload:!1,pipeline:"telemetry"})}async getRemotePeer(){return{id:this.peerUrl,organizationId:"",deviceId:this.id,capabilities:[],capabilitySet:{}}}async stopRealtimeConnection(){if(this.rtcClient)await this.rtcClient.disconnect(this.id);else throw new Error(`Realtime connection hasn't been started for ${this.id}`)}async createCustomDataChannel(t,n){const r=defined(this.rtcClient,"Realtime connection has not been started"),o=await this.getRemotePeer(),l=await new Promise(s=>{r.createCustomDataChannel(defined(o).id,t,{ordered:!0,...n},!1,(i,c)=>{const u=new DataChannel(c);s(u)})});return await l.waitTilReady(),l}createCustomRequestDataChannel(t,n=3e3){return new TextRequestDataChannel(this,t,n)}createCustomBinaryRequestDataChannel(t,n=3e3){return new BinaryRequestDataChannel(this,t,n)}}const He=class{static async setDefaultDevice(t){He.defaultDeviceId=t}static async getCurrentDevice(){if(!Authentication.token)throw new Error("Not authenticated");if(!He.defaultDeviceId)throw new Error("No known default device");const o=(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===He.defaultDeviceId).name,l=new Device(He.defaultDeviceId,o,defined(Authentication.currentOrganization));return He.knownContext.push(new WeakRef(l)),l}static async getPeerDevice(t){const n=new PeerDevice(t);return n.id=await n.getDeviceId(),n}static async getDevice(t){if(!Authentication.token)throw new Error("Not authenticated");const r=await(await fetch(`${FORMANT_API_URL}/v1/admin/devices/${t}`,{method:"GET",headers:{"Content-Type":"application/json",Authorization:"Bearer "+Authentication.token}})).json(),o=r.name,l=new Device(t,o,r.organizationId);return He.knownContext.push(new WeakRef(l)),l}static async getDevices(){if(!Authentication.token)throw new Error("Not authenticated");const n=await(await fetch(`${FORMANT_API_URL}/v1/admin/device-details/query`,{method:"POST",body:JSON.stringify({enabled:!0,type:"default"}),headers:{"Content-Type":"application/json",Authorization:"Bearer "+Authentication.token}})).json();return n.items,n.items.map(r=>new Device(r.id,r.name,r.organizationId))}static async queryDevices(t){if(!Authentication.token)throw new Error("Not authenticated");return(await(await fetch(`${FORMANT_API_URL}/v1/admin/devices/query`,{method:"POST",body:JSON.stringify(t),headers:{"Content-Type":"application/json",Authorization:"Bearer "+Authentication.token}})).json()).items.map(o=>new Device(o.id,o.name,o.organizationId))}static async getOnlineDevices(){if(!Authentication.token)throw new Error("Not authenticated");const r=(await(await fetch(`${FORMANT_API_URL}/v1/queries/online-devices`,{method:"GET",headers:{"Content-Type":"application/json",Authorization:"Bearer "+Authentication.token}})).json()).items;return(await He.getDevices()).filter(l=>r.includes(l.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 r=(await(await fetch(`${FORMANT_API_URL}/v1/signaling/peers`,{method:"GET",headers:{"Content-Type":"application/json",Authorization:"Bearer "+Authentication.token}})).json()).items.map(l=>l.deviceId);return(await He.getDevices()).filter(l=>r.includes(l.id))}static async getLatestTelemetry(t){let n=t;return t&&!Array.isArray(t)&&(t=[t]),(await(await fetch(`${FORMANT_API_URL}/v1/queries/stream-current-value`,{method:"POST",body:JSON.stringify({deviceIds:n}),headers:{"Content-Type":"application/json",Authorization:"Bearer "+Authentication.token}})).json()).items}static async getTelemetry(t,n,r,o,l){let s=t;Array.isArray(t)||(s=[t]);let i=n;return Array.isArray(n)||(i=[n]),(await(await fetch(`${FORMANT_API_URL}/v1/queries/queries`,{method:"POST",body:JSON.stringify({deviceIds:s,end:o.toISOString(),names:i,start:r.toISOString(),tags:l}),headers:{"Content-Type":"application/json",Authorization:"Bearer "+Authentication.token}})).json()).items}static async getFileUrl(t){const r=await(await fetch(`${FORMANT_API_URL}/v1/admin/files/query`,{method:"POST",body:JSON.stringify({fileIds:[t]}),headers:{"Content-Type":"application/json",Authorization:"Bearer "+Authentication.token}})).json();if(r.fileUrls.length===0)throw new Error("File not found");return r.fileUrls[0]}static async queryTelemetry(t){if(!Authentication.token)throw new Error("Not authenticated");return(await(await fetch(`${FORMANT_API_URL}/v1/queries/queries`,{method:"POST",body:JSON.stringify(t),headers:{"Content-Type":"application/json",Authorization:"Bearer "+Authentication.token}})).json()).items}static async aggregateTelemetry(t){if(!Authentication.token)throw new Error("Not authenticated");return(await(await fetch(`${FORMANT_API_URL}/v1/queries/queries`,{method:"POST",body:JSON.stringify(t),headers:{"Content-Type":"application/json",Authorization:"Bearer "+Authentication.token}})).json()).aggregates}static async queryEvents(t){if(!Authentication.token)throw new Error("Not authenticated");return(await(await fetch(`${FORMANT_API_URL}/v1/admin/events/query`,{method:"POST",body:JSON.stringify(t),headers:{"Content-Type":"application/json",Authorization:"Bearer "+Authentication.token}})).json()).items}static async getEvent(t){if(!Authentication.token)throw new Error("Not authenticated");return(await(await fetch(`${FORMANT_API_URL}/v1/admin/events/query/id=${t}`,{method:"GET",headers:{"Content-Type":"application/json",Authorization:"Bearer "+Authentication.token}})).json()).items}static async getInterventions(){if(!Authentication.token)throw new Error("Not authenticated");return(await(await fetch(`${FORMANT_API_URL}/v1/admin/intervention-requests`,{method:"GET",headers:{"Content-Type":"application/json",Authorization:"Bearer "+Authentication.token}})).json()).items}static async getCurrentGroup(){if(!Authentication.token)throw new Error("Not authenticated");let t=new URLSearchParams("");typeof window!="undefined"&&(t=new URLSearchParams(window.location.search));const n=t.get("group");if(n===null||n.trim()==="")return;const r=await fetch(`${FORMANT_API_URL}/v1/admin/groups/`+n,{headers:{"Content-Type":"application/json",Authorization:"Bearer "+Authentication.token}}),{tagKey:o,tagValue:l}=await r.json();return await this.queryDevices({tags:{[o]:[l]},enabled:!0,type:"default"})}};let Fleet$1=He;Ae(Fleet$1,"defaultDeviceId"),Ae(Fleet$1,"knownContext",[]);function toInteger(e){if(e===null||e===!0||e===!1)return NaN;var t=Number(e);return isNaN(t)?t:t<0?Math.ceil(t):Math.floor(t)}function requiredArgs(e,t){if(t.length<e)throw new TypeError(e+" argument"+(e>1?"s":"")+" required, but only "+t.length+" present")}function _typeof(e){return typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?_typeof=function(n){return typeof n}:_typeof=function(n){return n&&typeof Symbol=="function"&&n.constructor===Symbol&&n!==Symbol.prototype?"symbol":typeof n},_typeof(e)}function toDate(e){requiredArgs(1,arguments);var t=Object.prototype.toString.call(e);return e instanceof Date||_typeof(e)==="object"&&t==="[object Date]"?new Date(e.getTime()):typeof e=="number"||t==="[object Number]"?new Date(e):((typeof e=="string"||t==="[object String]")&&typeof console!="undefined"&&(console.warn("Starting with v2.0.0-beta.1 date-fns doesn't accept strings as date arguments. Please use `parseISO` to parse strings. See: https://github.com/date-fns/date-fns/blob/master/docs/upgradeGuide.md#string-arguments"),console.warn(new Error().stack)),new Date(NaN))}function addMilliseconds(e,t){requiredArgs(2,arguments);var n=toDate(e).getTime(),r=toInteger(t);return new Date(n+r)}var MILLISECONDS_IN_MINUTE=6e4;function addMinutes(e,t){requiredArgs(2,arguments);var n=toInteger(t);return addMilliseconds(e,n*MILLISECONDS_IN_MINUTE)}function addSeconds(e,t){requiredArgs(2,arguments);var n=toInteger(t);return addMilliseconds(e,n*1e3)}var roundingMap={ceil:Math.ceil,round:Math.round,floor:Math.floor,trunc:function e(t){return t<0?Math.ceil(t):Math.floor(t)}},defaultRoundingMethod="trunc";function getRoundingMethod(e){return e?roundingMap[e]:roundingMap[defaultRoundingMethod]}function startOfMinute(e){requiredArgs(1,arguments);var t=toDate(e);return t.setSeconds(0,0),t}function roundToNearestMinutes(e,t){var n;if(arguments.length<1)throw new TypeError("1 argument required, but only none provided present");var r=toInteger((n=t==null?void 0:t.nearestTo)!==null&&n!==void 0?n:1);if(r<1||r>30)throw new RangeError("`options.nearestTo` must be between 1 and 30");var o=toDate(e),l=o.getSeconds(),s=o.getMinutes()+l/60,i=getRoundingMethod(t==null?void 0:t.roundingMethod),c=i(s/r)*r,u=s%r,m=Math.round(u/r)*r;return new Date(o.getFullYear(),o.getMonth(),o.getDate(),o.getHours(),c+m)}const millisecond=1,second=1e3,minute=60*second,hour=60*minute,day=24*hour,week=7*day,month=30*day,year=365*day,duration={millisecond,second,minute,hour,day,week,month,year};function filterDataByType(e,t){return e.filter(n=>n.type===t)}function filterDataByTime(e,t,n){const r=t.getTime(),o=n.getTime();return e.map(l=>({...l,points:l.points.filter(([s])=>s>=r&&s<o)})).filter(({points:l})=>l.length>0)}function fork(e){}class StoreCache{constructor({capacity:t,timeout:n}={}){Ae(this,"entries",new Map);Ae(this,"metadata",new Map);Ae(this,"capacity");Ae(this,"timeout");this.capacity=t||1e4,this.timeout=n||duration.minute}get(t,n){const r=this.keyToCacheKey(t),o=this.entries.get(r),l=this.metadata.get(r);return(o===void 0||l&&(l==null?void 0:l.expiration.getTime())<Date.now())&&!(l!=null&&l.generating)&&n&&this.generate(t,n()),o===void 0&&l&&l.lastValue!==void 0?l.lastValue:o}set(t,n){const r=this.keyToCacheKey(t);this.metadata.set(r,{generating:!1,expiration:new Date(Date.now()+this.timeout),lastValue:n}),this.entries.set(r,n),this.metadata.size>this.capacity&&this.deleteOldestEntry()}clear(){this.entries.clear(),[...this.metadata.values()].forEach(t=>t.generating=!1)}clearKey(t){this.metadata.delete(t),this.entries.delete(t)}keyToCacheKey(t){return JSON.stringify(t)}deleteOldestEntry(){if(this.metadata.size<1)return;const[t]=[...this.metadata.entries()].reduce(([n,r],[o,l])=>l.expiration.getTime()<r.expiration.getTime()?[o,l]:[n,r]);this.clearKey(t)}generate(t,n){const r=this.keyToCacheKey(t),o=this.metadata.get(r)||{};this.metadata.set(r,{...o,generating:!0,expiration:new Date(Date.now()+this.timeout)}),setTimeout(()=>{n.then(l=>{const s=this.metadata.get(r);!(s!=null&&s.generating)||this.set(t,l)})},0)}}class QueryStore{constructor(){Ae(this,"queryStoreCache",new StoreCache({capacity:1e4,timeout:20*duration.second}));Ae(this,"liveQueryStoreCache",new StoreCache({capacity:1e4,timeout:200*duration.millisecond}))}moduleQuery(t,n,r,o,l,s=!1){const i={...t,names:[n],types:[r]},c=this.query(i,o,l,s);return c===void 0||c==="too much data"?c:filterDataByType(c,r)}query(t,n,r,o=!1){const l={...t,start:startOfMinute(n).toISOString(),end:o?r.toISOString():addMinutes(roundToNearestMinutes(r),1).toISOString(),latestOnly:o},s=r>addSeconds(new Date,-20);let i;return s?i=this.liveQueryCache(l):i=this.queryCache(l),!i||i==="too much data"||o?i:filterDataByTime(i,n,r)}queryCache(t){return this.queryStoreCache.get(t,async()=>{try{return await Fleet$1.queryTelemetry(t)}catch(n){throw n}})}liveQueryCache(t){return this.liveQueryStoreCache.get(t,async()=>{try{return await Fleet$1.queryTelemetry(t)}catch(n){throw n}})}}const queryStore=new QueryStore;class App{static sendAppMessage(t){window.parent.postMessage(t,"*")}static getCurrentModuleContext(){let t=new URLSearchParams("");return typeof window!="undefined"&&(t=new URLSearchParams(window.location.search)),t.get("module")}static async getCurrentModuleConfiguration(){let t=new URLSearchParams("");typeof window!="undefined"&&(t=new URLSearchParams(window.location.search));const n=t.get("configuration");return n===null||n.trim()===""?void 0:(await(await fetch(`${FORMANT_API_URL}/v1/admin/module-configurations/`+n,{headers:{"Content-Type":"application/json",Authorization:"Bearer "+Authentication.token}})).json()).configuration}static isModule(){return this.getCurrentModuleContext()!==null}static goToTime(t){this.sendAppMessage({type:"go_to_time",time:t.getTime()})}static goToDevice(t){this.sendAppMessage({type:"go_to_device",deviceId:t})}static showMessage(t){this.sendAppMessage({type:"show_message",message:t})}static requestModuleData(){const t=this.getCurrentModuleContext();if(!t)throw new Error("No module context");this.sendAppMessage({type:"request_module_data",module:t})}static setModuleDateTimeRange(t,n){const r=this.getCurrentModuleContext();if(!r)throw new Error("No module context");this.sendAppMessage({type:"set_module_data_time_range",module:r,before:t,after:n||0})}static refreshAuthToken(){const t=this.getCurrentModuleContext();if(!t)throw new Error("No module context");this.sendAppMessage({type:"refresh_auth_token",module:t})}static sendChannelData(t,n){const r=this.getCurrentModuleContext();if(!r)throw new Error("No module context");this.sendAppMessage({type:"send_channel_data",source:r,channel:t,data:n})}static setupModuleMenus(t){const n=this.getCurrentModuleContext();if(!n)throw new Error("No module context");this.sendAppMessage({type:"setup_module_menus",module:n,menus:t})}static addMenuListener(t){window.addEventListener("message",n=>{const r=n.data;r.type==="module_menu_item_clicked"&&t(r.menu)})}static addAccessTokenRefreshListener(t){window.addEventListener("message",n=>{const r=n.data;r.type==="auth_token"&&t(r.token)})}static addModuleDataListener(t){const n=this.getCurrentModuleContext();n&&this.sendAppMessage({type:"request_module_data",module:n}),window.addEventListener("message",r=>{const o=r.data;o.type==="module_data"&&t({streams:o.streams,time:o.time,queryRange:o.queryRange})})}static addStreamListener(t,n,r){const o=l=>{const s=l.data;if(s.type==="module_data"){const{start:i,end:c}=s.queryRange;r(queryStore.moduleQuery({},t,n,new Date(i),new Date(c),!1))}};return window.addEventListener("message",o),()=>window.removeEventListener("message",o)}static addModuleConfigurationListener(t){window.addEventListener("message",n=>{const r=n.data;r.type==="module_configuration"&&t(r)})}static addChannelDataListener(t,n){window.addEventListener("message",r=>{const o=r.data;o.type==="channel_data"&&o.channel===t&&n({source:o.source,data:o.data})})}static requestOverviewDevices(t){this.sendAppMessage({type:"request_devices"}),window.addEventListener("message",n=>{const r=n.data;t(r)})}static async prompt(t,n){return new Promise(r=>{const o=Math.random().toString();this.sendAppMessage({type:"prompt",promptId:o,schema:t,okText:n==null?void 0:n.okText,cancelText:n==null?void 0:n.cancelText});const l=s=>{const i=s.data;i.type==="prompt_response"&&i.promptId===o&&r(i.data),window.removeEventListener("message",l)};window.addEventListener("message",l)})}}const Pe=class{static async login(t,n){try{const r=await fetch(`${FORMANT_API_URL}/v1/admin/auth/login`,{method:"POST",body:JSON.stringify({email:t,password:n}),headers:{"Content-Type":"application/json"}}),o=await r.json();if(r.status!==200)throw new Error(o.message);return await Pe.loginWithToken(o.authentication.accessToken,o.authentication.refreshToken),o.authentication}catch(r){return Pe.waitingForAuth.forEach(o=>o(!1)),Pe.waitingForAuth=[],Promise.reject(r)}}static async loginWithToken(t,n){const r=JSON.parse(atob(t.split(".")[1]));try{let o;if(Pe.isShareToken=r["formant:claims"]&&r["formant:claims"].type=="share",r["formant:claims"]&&(Pe.currentOrganization=r["formant:claims"].organizationId),r["custom:organization_id"]&&(Pe.currentOrganization=r["custom:organization_id"]),Pe.isShareToken||(o=r.sub),r["formant:claims"]&&r["formant:claims"].userId&&(o=r["formant:claims"].userId),o){const l=await fetch(`${FORMANT_API_URL}/v1/admin/users/${o}`,{method:"GET",headers:{"Content-Type":"application/json",Authorization:"Bearer "+t}}),s=await l.json();if(l.status!==200)throw new Error(s.message);Pe.currentUser=s}Pe.token=t,Pe.waitingForAuth.forEach(l=>l(!0))}catch(o){console.error(o),Pe.waitingForAuth.forEach(l=>l(!1))}Pe.waitingForAuth=[],n&&(Pe.refreshToken=n,setInterval(async()=>{if(Pe.refreshToken){const l=await(await fetch(`${FORMANT_API_URL}/v1/admin/auth/refresh`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({refreshToken:Pe.refreshToken})})).json();Pe.token=l.authentication.accessToken}},1e3*60*60))}static isAuthenticated(){return Pe.token!==void 0}static getCurrentUser(){return Pe.currentUser}static async waitTilAuthenticated(){return Pe.token!==void 0?!0:new Promise(t=>{Pe.waitingForAuth.push(function(n){t(n)})})}static async listenForRefresh(){App.addAccessTokenRefreshListener(t=>{this.loginWithToken(t)}),setInterval(async()=>{App.refreshAuthToken()},1e3*60*60)}};let Authentication=Pe;Ae(Authentication,"token"),Ae(Authentication,"refreshToken"),Ae(Authentication,"currentUser"),Ae(Authentication,"currentOrganization"),Ae(Authentication,"isShareToken",!1),Ae(Authentication,"defaultDeviceId"),Ae(Authentication,"waitingForAuth",[]);const Xe=class{static async setDefaultDevice(t){Xe.defaultDeviceId=t}static async getCurrentDevice(){if(!Authentication.token)throw new Error("Not authenticated");if(!Xe.defaultDeviceId)throw new Error("No known default device");const o=(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===Xe.defaultDeviceId).name,l=new Device(Xe.defaultDeviceId,o,defined(Authentication.currentOrganization));return Xe.knownContext.push(new WeakRef(l)),l}static async getPeerDevice(t){const n=new PeerDevice(t);return n.id=await n.getDeviceId(),n}static async getDevice(t){if(!Authentication.token)throw new Error("Not authenticated");const r=await(await fetch(`${FORMANT_API_URL}/v1/admin/devices/${t}`,{method:"GET",headers:{"Content-Type":"application/json",Authorization:"Bearer "+Authentication.token}})).json(),o=r.name,l=new Device(t,o,r.organizationId);return Xe.knownContext.push(new WeakRef(l)),l}static async getDevices(){if(!Authentication.token)throw new Error("Not authenticated");const n=await(await fetch(`${FORMANT_API_URL}/v1/admin/device-details/query`,{method:"POST",body:JSON.stringify({enabled:!0,type:"default"}),headers:{"Content-Type":"application/json",Authorization:"Bearer "+Authentication.token}})).json();return n.items,n.items.map(r=>new Device(r.id,r.name,r.organizationId))}static async queryDevices(t){if(!Authentication.token)throw new Error("Not authenticated");return(await(await fetch(`${FORMANT_API_URL}/v1/admin/devices/query`,{method:"POST",body:JSON.stringify(t),headers:{"Content-Type":"application/json",Authorization:"Bearer "+Authentication.token}})).json()).items.map(o=>new Device(o.id,o.name,o.organizationId))}static async getOnlineDevices(){if(!Authentication.token)throw new Error("Not authenticated");const r=(await(await fetch(`${FORMANT_API_URL}/v1/queries/online-devices`,{method:"GET",headers:{"Content-Type":"application/json",Authorization:"Bearer "+Authentication.token}})).json()).items;return(await Xe.getDevices()).filter(l=>r.includes(l.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 r=(await(await fetch(`${FORMANT_API_URL}/v1/signaling/peers`,{method:"GET",headers:{"Content-Type":"application/json",Authorization:"Bearer "+Authentication.token}})).json()).items.map(l=>l.deviceId);return(await Xe.getDevices()).filter(l=>r.includes(l.id))}static async getLatestTelemetry(t){let n=t;return t&&!Array.isArray(t)&&(t=[t]),(await(await fetch(`${FORMANT_API_URL}/v1/queries/stream-current-value`,{method:"POST",body:JSON.stringify({deviceIds:n}),headers:{"Content-Type":"application/json",Authorization:"Bearer "+Authentication.token}})).json()).items}static async getTelemetry(t,n,r,o,l){let s=t;Array.isArray(t)||(s=[t]);let i=n;return Array.isArray(n)||(i=[n]),(await(await fetch(`${FORMANT_API_URL}/v1/queries/queries`,{method:"POST",body:JSON.stringify({deviceIds:s,end:o.toISOString(),names:i,start:r.toISOString(),tags:l}),headers:{"Content-Type":"application/json",Authorization:"Bearer "+Authentication.token}})).json()).items}static async getFileUrl(t){const r=await(await fetch(`${FORMANT_API_URL}/v1/admin/files/query`,{method:"POST",body:JSON.stringify({fileIds:[t]}),headers:{"Content-Type":"application/json",Authorization:"Bearer "+Authentication.token}})).json();if(r.fileUrls.length===0)throw new Error("File not found");return r.fileUrls[0]}static async queryTelemetry(t){if(!Authentication.token)throw new Error("Not authenticated");return(await(await fetch(`${FORMANT_API_URL}/v1/queries/queries`,{method:"POST",body:JSON.stringify(t),headers:{"Content-Type":"application/json",Authorization:"Bearer "+Authentication.token}})).json()).items}static async aggregateTelemetry(t){if(!Authentication.token)throw new Error("Not authenticated");return(await(await fetch(`${FORMANT_API_URL}/v1/queries/queries`,{method:"POST",body:JSON.stringify(t),headers:{"Content-Type":"application/json",Authorization:"Bearer "+Authentication.token}})).json()).aggregates}static async queryEvents(t){if(!Authentication.token)throw new Error("Not authenticated");return(await(await fetch(`${FORMANT_API_URL}/v1/admin/events/query`,{method:"POST",body:JSON.stringify(t),headers:{"Content-Type":"application/json",Authorization:"Bearer "+Authentication.token}})).json()).items}static async getEvent(t){if(!Authentication.token)throw new Error("Not authenticated");return(await(await fetch(`${FORMANT_API_URL}/v1/admin/events/query/id=${t}`,{method:"GET",headers:{"Content-Type":"application/json",Authorization:"Bearer "+Authentication.token}})).json()).items}static async getInterventions(){if(!Authentication.token)throw new Error("Not authenticated");return(await(await fetch(`${FORMANT_API_URL}/v1/admin/intervention-requests`,{method:"GET",headers:{"Content-Type":"application/json",Authorization:"Bearer "+Authentication.token}})).json()).items}static async getCurrentGroup(){if(!Authentication.token)throw new Error("Not authenticated");let t=new URLSearchParams("");typeof window!="undefined"&&(t=new URLSearchParams(window.location.search));const n=t.get("group");if(n===null||n.trim()==="")return;const r=await fetch(`${FORMANT_API_URL}/v1/admin/groups/`+n,{headers:{"Content-Type":"application/json",Authorization:"Bearer "+Authentication.token}}),{tagKey:o,tagValue:l}=await r.json();return await this.queryDevices({tags:{[o]:[l]},enabled:!0,type:"default"})}};let Fleet=Xe;Ae(Fleet,"defaultDeviceId"),Ae(Fleet,"knownContext",[]);class KeyValue{static async set(t,n){try{const r=await fetch(FORMANT_API_URL+"/v1/admin/key-value",{method:"POST",body:JSON.stringify({organizationId:defined(Authentication.currentUser).organizationId,key:t,value:n}),headers:{"Content-Type":"application/json",Authorization:"Bearer "+Authentication.token}}),o=await r.json();if(r.status!==200)throw new Error(o.message)}catch(r){throw r}}static async get(t){try{const n=await fetch(FORMANT_API_URL+`/v1/admin/key-value/${t}`,{method:"GET",headers:{"Content-Type":"application/json",Authorization:"Bearer "+Authentication.token}}),r=await n.json();if(n.status!==200)throw new Error(r.message);return r.value}catch(n){throw n}}static async list(){try{const t=await fetch(FORMANT_API_URL+"/v1/admin/key-value",{method:"GET",headers:{"Content-Type":"application/json",Authorization:"Bearer "+Authentication.token}}),n=await t.json();if(t.status!==200)throw new Error(n.message);return n.items}catch(t){throw t}}static async delete(t){try{if(!(await fetch(FORMANT_API_URL+`/v1/admin/key-value/${t}`,{method:"DELETE",headers:{"Content-Type":"application/json",Authorization:"Bearer "+Authentication.token}})).ok)throw new Error("Unable to handle request");return}catch(n){throw n}}}function getVariance(e){return e.count<2?0:e.sumOfSquares/(e.count-1)}function getStandardDeviation(e){return Math.sqrt(getVariance(e))}function getMax(e){return e.max}function getMin(e){return e.min}function getAverage(e){return e.count===0?-1:e.sum/e.count}function getSum(e){return e.sum}function getCount(e){return e.count}const aggregateFunctionMap={min:getMin,max:getMax,"standard deviation":getStandardDeviation,average:getAverage,sum:getSum,count:getCount};function getZeroINumericSet(){return{min:Number.MAX_SAFE_INTEGER,max:0,sum:0,count:0,sumOfSquares:0}}function reduceNumericStreamAggregates(e){return e.aggregates.reduce((t,n)=>{const r=n[1];return combineNumericAggregates(r,t)},getZeroINumericSet())}function reduceNumericSetStreamAggregates(e,t){var n;return(n=e.aggregates.reduce((r,o)=>{const l=o[1];return combineNumericSetAggregates(l,r)},{})[t])==null?void 0:n.value}function combineNumericAggregates(e,t){return{min:Math.min(e.min,t.min),max:Math.max(e.max,t.max),sum:e.sum+t.sum,count:e.count+t.count,sumOfSquares:e.sumOfSquares+t.sumOfSquares}}function combineNumericSetAggregates(e,t){return Object.keys(e).reduce((n,r)=>{var o,l;return{...n,[r]:{value:combineNumericAggregates(e[r].value,(l=(o=t[r])==null?void 0:o.value)!=null?l:getZeroINumericSet()),unit:e[r].unit}}},{})}function stringToArrayBuffer(e){return Uint8Array.from(atob(e),t=>t.charCodeAt(0))}function browser(){const{userAgent:e}=navigator;return e.includes("Firefox/")?"Firefox":e.includes("Edg/")?"Edge":e.includes("Chrome/")?"Chrome":e.includes("Safari/")?"Safari":e.includes("MSIE/")||e.includes("Trident/")?"IE":"Other"}const rtcAudioChunkStreamType="audio-chunk";class AudioPlayer{constructor(t,n){Ae(this,"muted",!1);Ae(this,"hasReceivedData",!1);Ae(this,"audioContext");Ae(this,"chunks",[]);Ae(this,"isPlaying",!1);Ae(this,"startTime",0);Ae(this,"lastChunkOffset",0);Ae(this,"bufferSize",3);Ae(this,"receive",async t=>{var s;const n=(s=t.payload.audioChunk)==null?void 0:s.chunk_data;if(!n)return;this.hasReceivedData||(this.hasReceivedData=!0);const{audioContext:r,muted:o}=this;if(!r||t.header.stream.streamType!==rtcAudioChunkStreamType||o!==!1)return;const l=stringToArrayBuffer(n);try{await r.decodeAudioData(l.buffer,this.scheduleChunk)}catch(i){console.warn("Error decoding audio buffer, changing audioWireFormat on agent",{error:i}),this.changeAudioWireFormat("wav")}});Ae(this,"scheduleChunk",t=>{const{audioContext:n}=this;if(!n)return;(this.chunks.length>this.bufferSize||this.isPlaying===!1)&&(this.chunks.forEach(o=>{o.stop()}),this.isPlaying=!1,this.chunks=[]);const r=this.createChunk(t);!r||!r.buffer||(this.isPlaying===!1&&(this.startTime=n.currentTime,this.lastChunkOffset=0,this.isPlaying=!0),r.start(this.startTime+this.lastChunkOffset,0,t.duration),this.lastChunkOffset+=r.buffer.duration,this.chunks.push(r))});this.device=t,this.stream=n,this.device.startListeningToRealtimeDataStream(n),this.device.addRealtimeListener((o,l)=>{this.receive(l)}),browser()==="Safari"||browser()==="IE"?this.changeAudioWireFormat("wav"):this.changeAudioWireFormat("opus");const r=window.AudioContext||window.webkitAudioContext;this.audioContext=new r}async play(){var t,n;((t=this.audioContext)==null?void 0:t.state)==="suspended"&&await((n=this.audioContext)==null?void 0:n.resume()),this.muted=!1}async pause(){await this.audioContext.suspend(),this.muted=!0}destroy(){this.device.stopListeningToRealtimeDataStream(this.stream)}createChunk(t){const{audioContext:n}=this;if(!n)return;const r=n.createBufferSource();return r.buffer=t,r.connect(n.destination),r.loop=!1,r.onended=o=>{this.chunks.splice(this.chunks.indexOf(r),1),this.chunks.length===0&&(this.isPlaying=!1)},r}changeAudioWireFormat(t){const{stream:n}=this;(async()=>await this.device.changeStreamAudioType(n.name,t))()}}const accessLevels=["viewer","operator","administrator"],viewer="viewer",operator="operator",administrator="administrator",aggregateLevels=["year","month","week","day","hour","minute"],annotationTypes=["tag","sheet","user"],eventTypes=["triggered-event","intervention-request","teleop-session-record","port-forwarding-session-record","command-request","command-response","command-delivery","custom","comment","system","annotation"],healthStatuses=["unknown","operational","offline","error"],interventionTypes=["selection","labeling","teleop"],severities=["info","warning","error","critical"],videoMimeTypes=["video/mp4"];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.AudioPlayer=AudioPlayer,exports.Authentication=Authentication,exports.BinaryRequestDataChannel=BinaryRequestDataChannel,exports.CaptureStream=CaptureStream,exports.DataChannel=DataChannel,exports.Device=Device,exports.Fleet=Fleet,exports.IRtcSendConfiguration=dist.exports.IRtcSendConfiguration,exports.IRtcStreamMessage=dist.exports.IRtcStreamMessage,exports.IRtcStreamPayload=dist.exports.IRtcStreamPayload,exports.KeyValue=KeyValue,exports.Manipulator=Manipulator,exports.PeerDevice=PeerDevice,exports.SessionType=SessionType,exports.TextRequestDataChannel=TextRequestDataChannel,exports.accessLevels=accessLevels,exports.administrator=administrator,exports.aggregateFunctionMap=aggregateFunctionMap,exports.aggregateLevels=aggregateLevels,exports.annotationTypes=annotationTypes,exports.combineNumericAggregates=combineNumericAggregates,exports.combineNumericSetAggregates=combineNumericSetAggregates,exports.eventTypes=eventTypes,exports.getAverage=getAverage,exports.getCount=getCount,exports.getMax=getMax,exports.getMin=getMin,exports.getStandardDeviation=getStandardDeviation,exports.getSum=getSum,exports.getVariance=getVariance,exports.getZeroINumericSet=getZeroINumericSet,exports.healthStatuses=healthStatuses,exports.interventionTypes=interventionTypes,exports.operator=operator,exports.reduceNumericSetStreamAggregates=reduceNumericSetStreamAggregates,exports.reduceNumericStreamAggregates=reduceNumericStreamAggregates,exports.severities=severities,exports.videoMimeTypes=videoMimeTypes,exports.viewer=viewer,Object.defineProperties(exports,{__esModule:{value:!0},[Symbol.toStringTag]:{value:"Module"}})});
44
+ `),Error.captureStackTrace(this,r)}}e.exports=o=>{if(o.length>2)throw new r(o);function l(i={}){this.options=i}function s(i){return new l(i)}return l.prototype.transform=o,s.Format=l,s}},function(e,t,n){function r(s,i){if(!(s instanceof i))throw new TypeError("Cannot call a class as a function")}function o(s,i){for(var c=0;c<i.length;c++){var u=i[c];u.enumerable=u.enumerable||!1,u.configurable=!0,"value"in u&&(u.writable=!0),Object.defineProperty(s,u.key,u)}}var l=n(88);e.exports=function(){function s(){var u=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};r(this,s),this.loggers=new Map,this.options=u}var i,c;return i=s,(c=[{key:"add",value:function(u,m){var R=this;if(!this.loggers.has(u)){var E=(m=Object.assign({},m||this.options)).transports||this.options.transports;m.transports=E?E.slice():[];var y=l(m);y.on("close",function(){return R._delete(u)}),this.loggers.set(u,y)}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,E){return m._removeLogger(E)})}},{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)}}])&&o(i.prototype,c),s}()},function(e,t,n){(function(r){const o=n(52),l=/^([A-Za-z0-9+/]{4})*([A-Za-z0-9+/]{4}|[A-Za-z0-9+/]{3}=|[A-Za-z0-9+/]{2}==)$/;e.exports=function(s,i,c,u){let m,R,E=!1,y=!1;const g=n(94);function _(z){u(i,z)}function T(z,M){let A=`"${i}" ${M}`;throw z&&(A=`${A}`),R&&(A=`${A}. An example of a valid value would be: ${R}`),new o(A)}const L={convertFromBase64:function(){return _("marking for base64 conversion"),E=!0,L},default:function(z){if(typeof z=="number")m=z.toString();else if(Array.isArray(z)||typeof z=="object"&&z!==null)m=JSON.stringify(z);else{if(typeof z!="string")throw new o("values passed to default() must be of Number, String, Array, or Object type");m=z}return _(`setting default value to "${m}"`),L},required:function(z){return z===void 0?(_("marked as required"),y=!0):(_(`setting required flag to ${z}`),y=z),L},example:function(z){return R=z,L}};return Object.entries({...g,...c}).forEach(([z,M])=>{L[z]=function(A){return function(){let f=s[i];if(_(`will be read from the environment using "${A.name}" accessor`),f===void 0)if(m===void 0&&y)_("was not found in the environment, but is required to be set"),T(void 0,"is a required variable, but it was not set");else{if(m===void 0)return void _("was not found in the environment, but is not required. returning undefined");_(`was not found in the environment, parsing default value "${m}" instead`),f=m}y&&(_("verifying variable value is not an empty string"),f.trim().length===0&&T(void 0,"is a required variable, but its value was empty")),E&&(_("verifying variable is a valid base64 string"),f.match(l)||T(f,"should be a valid base64 string if using convertFromBase64"),_("converting from base64 to utf8 string"),f=r.from(f,"base64").toString());const O=[f].concat(Array.prototype.slice.call(arguments));try{_(`passing value "${f}" to "${A.name}" accessor`);const Y=A.apply(A,O);return _(`parsed successfully, returning ${Y}`),Y}catch(Y){T(f,Y.message)}}}(M)}),L}}).call(this,n(5).Buffer)},function(e,t,n){const r=n(33);e.exports=function(o,l){return l=l||",",o.length?r(o).split(l).filter(Boolean):[]}},function(e,t,n){e.exports=function(r){const o=r.toLowerCase();if(o!=="false"&&o!=="true")throw new Error('should be either "true", "false", "TRUE", or "FALSE"');return o!=="false"}},function(e,t,n){e.exports=function(r){const o=r.toLowerCase();if(["false","0","true","1"].indexOf(o)===-1)throw new Error('should be either "true", "false", "TRUE", "FALSE", 1, or 0');return!(o==="0"||o==="false")}},function(e,t,n){const r=n(95);e.exports=function(o){var l=r(o);if(l>65535)throw new Error("cannot assign a port number greater than 65535");return l}},function(e,t,n){const r=n(33);e.exports=function(o,l){const s=r(o);if(l.indexOf(s)<0)throw new Error(`should be one of [${l.join(", ")}]`);return s}},function(e,t,n){const r=n(54);e.exports=function(o){const l=r(o);if(l>0)throw new Error("should be a negative float");return l}},function(e,t,n){const r=n(54);e.exports=function(o){const l=r(o);if(l<0)throw new Error("should be a positive float");return l}},function(e,t,n){const r=n(53);e.exports=function(o){const l=r(o);if(l>0)throw new Error("should be a negative integer");return l}},function(e,t,n){const r=n(55);e.exports=function(o){var l=r(o);if(!Array.isArray(l))throw new Error("should be a parseable JSON Array");return l}},function(e,t,n){const r=n(55);e.exports=function(o){var l=r(o);if(Array.isArray(l))throw new Error("should be a parseable JSON Object");return l}},function(e,t,n){e.exports=function(r,o){try{RegExp(void 0,o)}catch{throw new Error("invalid regexp flags")}try{return new RegExp(r,o)}catch{throw new Error("should be a valid regexp")}}},function(e,t,n){const r=n(96);e.exports=function(o){return r(o).toString()}},function(e,t,n){const r=n(33),o=/^(?:[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*|"(?:[\u0001-\u0008\u000b\u000c\u000e-\u001f\u0021\u0023-\u005b\u005d-\u007f]|\\[\u0001-\u0009\u000b\u000c\u000e-\u007f])*")@(?:(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?|\[(?:(?:(2(5[0-5]|[0-4][0-9])|1[0-9][0-9]|[1-9]?[0-9]))\.){3}(?:(2(5[0-5]|[0-4][0-9])|1[0-9][0-9]|[1-9]?[0-9])|[a-z0-9-]*[a-z0-9]:(?:[\u0001-\u0008\u000b\u000c\u000e-\u001f\u0021-\u005a\u0053-\u007f]|\\[\u0001-\u0009\u000b\u000c\u000e-\u007f])+)\])$/;e.exports=function(l){const s=r(l);if(!o.test(s))throw new Error("should be a valid email address");return s}},function(e,t,n){e.exports=function(r,o){return function(l,s){o&&o.match(/prod|production/)||r(`env-var (${l}): ${s}`)}}},function(e,t,n){(function(r){(function(){var o,l,s,i,c,u;typeof performance!="undefined"&&performance!==null&&performance.now?e.exports=function(){return performance.now()}:r!=null&&r.hrtime?(e.exports=function(){return(o()-c)/1e6},l=r.hrtime,i=(o=function(){var m;return 1e9*(m=l())[0]+m[1]})(),u=1e9*r.uptime(),c=i-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,n(2))},function(e,t,n){(function(r){(function(o){function l(i){if((i=i===void 0?"utf-8":i)!=="utf-8")throw new RangeError("Failed to construct 'TextEncoder': The encoding label provided ('"+i+"') is invalid.")}function s(i,c){if(c=c===void 0?{fatal:!1}:c,(i=i===void 0?"utf-8":i)!=="utf-8")throw new RangeError("Failed to construct 'TextDecoder': The encoding label provided ('"+i+"') is invalid.");if(c.fatal)throw Error("Failed to construct 'TextDecoder': the 'fatal' option is unsupported.")}if(o.TextEncoder&&o.TextDecoder)return!1;Object.defineProperty(l.prototype,"encoding",{value:"utf-8"}),l.prototype.encode=function(i,c){if((c=c===void 0?{stream:!1}:c).stream)throw Error("Failed to encode: the 'stream' option is unsupported.");c=0;for(var u=i.length,m=0,R=Math.max(32,u+(u>>1)+7),E=new Uint8Array(R>>3<<3);c<u;){var y=i.charCodeAt(c++);if(55296<=y&&56319>=y){if(c<u){var g=i.charCodeAt(c);(64512&g)==56320&&(++c,y=((1023&y)<<10)+(1023&g)+65536)}if(55296<=y&&56319>=y)continue}if(m+4>E.length&&(R+=8,R=(R*=1+c/i.length*2)>>3<<3,(g=new Uint8Array(R)).set(E),E=g),(4294967168&y)==0)E[m++]=y;else{if((4294965248&y)==0)E[m++]=y>>6&31|192;else if((4294901760&y)==0)E[m++]=y>>12&15|224,E[m++]=y>>6&63|128;else{if((4292870144&y)!=0)continue;E[m++]=y>>18&7|240,E[m++]=y>>12&63|128,E[m++]=y>>6&63|128}E[m++]=63&y|128}}return E.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(i,c){if((c=c===void 0?{stream:!1}:c).stream)throw Error("Failed to decode: the 'stream' option is unsupported.");c=0;for(var u=(i=new Uint8Array(i)).length,m=[];c<u;){var R=i[c++];if(R===0)break;if((128&R)==0)m.push(R);else if((224&R)==192){var E=63&i[c++];m.push((31&R)<<6|E)}else if((240&R)==224){E=63&i[c++];var y=63&i[c++];m.push((31&R)<<12|E<<6|y)}else(248&R)==240&&(65535<(R=(7&R)<<18|(E=63&i[c++])<<12|(y=63&i[c++])<<6|63&i[c++])&&(R-=65536,m.push(R>>>10&1023|55296),R=56320|1023&R),m.push(R))}return String.fromCharCode.apply(null,m)},o.TextEncoder=l,o.TextDecoder=s})(typeof window!="undefined"?window:r!==void 0?r:this)}).call(this,n(6))},function(e,t,n){n.r(t),n.d(t,"AuthClient",function(){return l}),n.d(t,"RtcSignalingClient",function(){return i}),n.d(t,"Credentials",function(){return P}),n.d(t,"IRtcStream",function(){}),n.d(t,"SignalingPromiseClient",function(){return F.SignalingPromiseClient}),n.d(t,"IRtcClientConfigurationV1",function(){}),n.d(t,"IRtcClientConfiguration",function(){}),n.d(t,"IRtcConnectionStatsInfo",function(){}),n.d(t,"IRtcSendConfiguration",function(){}),n.d(t,"IRtcSessionMetricsMessageCounts",function(){}),n.d(t,"IRtcStreamMessage",function(){}),n.d(t,"IRtcStreamPayload",function(){}),n.d(t,"IStreamControl",function(){}),n.d(t,"RtcClient",function(){return _t}),n.d(t,"RtcClientV1",function(){return jt}),n.d(t,"createRtcStreamMessage",function(){return Ee});var r=n(28),o=function(ye,x,W,K){return new(W||(W=Promise))(function(re,oe){function he(ue){try{pe(K.next(ue))}catch(le){oe(le)}}function me(ue){try{pe(K.throw(ue))}catch(le){oe(le)}}function pe(ue){var le;ue.done?re(ue.value):(le=ue.value,le instanceof W?le:new W(function(Re){Re(le)})).then(he,me)}pe((K=K.apply(ye,x||[])).next())})};class l extends r.a{adminSignup(x,W){return o(this,void 0,void 0,function*(){return yield this.fetch("auth/admin-signup",{token:W,method:"POST",body:JSON.stringify(x)})})}login(x){return o(this,void 0,void 0,function*(){return yield this.fetch("auth/login",{method:"POST",body:JSON.stringify(x),allowUnsafeRetries:!0})})}loginWithGoogleToken(x){return o(this,void 0,void 0,function*(){return yield this.fetch("auth/login-google",{method:"POST",body:JSON.stringify(x),allowUnsafeRetries:!0})})}refresh(x,W){return o(this,void 0,void 0,function*(){return yield this.fetch("auth/refresh",{method:"POST",body:JSON.stringify({refreshToken:x,tokenExpirationSeconds:W}),allowUnsafeRetries:!0})})}respondToNewPasswordRequiredChallenge(x){return o(this,void 0,void 0,function*(){return yield this.fetch("auth/respond-to-new-password-required-challenge",{method:"POST",body:JSON.stringify(x)})})}forgotPassword(x){return o(this,void 0,void 0,function*(){return yield this.fetch("auth/forgot-password",{method:"POST",body:JSON.stringify({email:x})})})}confirmForgotPassword(x){return o(this,void 0,void 0,function*(){return yield this.fetch("auth/confirm-forgot-password",{method:"POST",body:JSON.stringify(x)})})}resendInvitation(x){return o(this,void 0,void 0,function*(){return yield this.fetch("auth/resend-invitation",{method:"POST",body:JSON.stringify({email:x})})})}changePassword({token:x,refreshToken:W,currentPassword:K,newPassword:re}){return o(this,void 0,void 0,function*(){return yield this.fetch("auth/change-password",{token:x,method:"POST",body:JSON.stringify({refreshToken:W,currentPassword:K,newPassword:re})})})}getDeviceCredentials(x){return o(this,void 0,void 0,function*(){return yield this.fetch("auth/device-credentials",{token:x,method:"POST",allowUnsafeRetries:!0})})}impersonate(x,W){return o(this,void 0,void 0,function*(){return yield this.fetch("auth/impersonate",{token:x,method:"POST",allowUnsafeRetries:!0,body:JSON.stringify({userId:W})})})}createServiceAccount(x,W,K,re){return o(this,void 0,void 0,function*(){return yield this.fetch("auth/service-account",{token:x,method:"POST",allowUnsafeRetries:!0,body:JSON.stringify({name:W,roleId:K,tags:re})})})}getFeatures(x){return o(this,void 0,void 0,function*(){return(yield this.fetch("auth/features",{token:x})).features})}}var s=function(ye,x,W,K){return new(W||(W=Promise))(function(re,oe){function he(ue){try{pe(K.next(ue))}catch(le){oe(le)}}function me(ue){try{pe(K.throw(ue))}catch(le){oe(le)}}function pe(ue){var le;ue.done?re(ue.value):(le=ue.value,le instanceof W?le:new W(function(Re){Re(le)})).then(he,me)}pe((K=K.apply(ye,x||[])).next())})};class i extends r.a{createPeer(x,W){return s(this,void 0,void 0,function*(){return yield this.fetch("peers",{token:x,method:"POST",body:JSON.stringify(W)})})}getPeers(x){return s(this,void 0,void 0,function*(){return(yield this.fetch("peers",{token:x})).items})}refreshPeer(x,W){return s(this,void 0,void 0,function*(){yield this.fetch(`peers/${W}/refresh`,{token:x,method:"POST",allowUnsafeRetries:!0})})}createSession(x,W){return s(this,void 0,void 0,function*(){return yield this.fetch("sessions",{token:x,method:"POST",body:JSON.stringify(W)})})}refreshSession(x,W){return s(this,void 0,void 0,function*(){yield this.fetch(`sessions/${W}/refresh`,{token:x,method:"POST",allowUnsafeRetries:!0})})}deleteSession(x,W){return s(this,void 0,void 0,function*(){yield this.fetch(`sessions/${W}`,{token:x,method:"DELETE",allowUnsafeRetries:!0})})}getSessions(x){return s(this,void 0,void 0,function*(){return(yield this.fetch("sessions",{token:x})).items})}getIceServers(x){return s(this,void 0,void 0,function*(){return(yield this.fetch("ice-servers",{token:x})).items})}addSignals(x,W,K){return s(this,void 0,void 0,function*(){yield this.fetch(`sessions/${W}/add-signals`,{token:x,method:"POST",body:JSON.stringify(K)})})}takeSignals(x,W){return s(this,void 0,void 0,function*(){return(yield this.fetch(`sessions/${W}/take-signals`,{token:x,method:"POST"})).items})}}var c=n(1),u=n(8),m=n(14),R=n.n(m),E=n(104),y=n.n(E),g=n(0),_=function(ye,x,W,K){return new(W||(W=Promise))(function(re,oe){function he(ue){try{pe(K.next(ue))}catch(le){oe(le)}}function me(ue){try{pe(K.throw(ue))}catch(le){oe(le)}}function pe(ue){var le;ue.done?re(ue.value):(le=ue.value,le instanceof W?le:new W(function(Re){Re(le)})).then(he,me)}pe((K=K.apply(ye,x||[])).next())})};class T{constructor(x){this.name="LogReporter",this.type="simple",this.message=x}send(x){return _(this,void 0,void 0,function*(){var W,K;g.a.info(this.message,(W=x.reduce((re,oe)=>Object.assign(Object.assign({},re),{[oe.name]:oe.stat}),{}),K=re=>{const{sum:oe,count:he}=re,me=oe/he;return Object.assign(Object.assign({},re),{average:me})},Object.keys(W).reduce((re,oe)=>Object.assign(Object.assign({},re),{[oe]:K(W[oe])}),{})))})}}var L=n(4),z=n(39);function M(ye){return!!ye.match(/^[a-zA-Z0-9-_.,:?'"()@\/\\#$+ ]{1,255}$/)}var A=function(ye,x,W,K){return new(W||(W=Promise))(function(re,oe){function he(ue){try{pe(K.next(ue))}catch(le){oe(le)}}function me(ue){try{pe(K.throw(ue))}catch(le){oe(le)}}function pe(ue){var le;ue.done?re(ue.value):(le=ue.value,le instanceof W?le:new W(function(Re){Re(le)})).then(he,me)}pe((K=K.apply(ye,x||[])).next())})};function f({func:ye,delay:x,immediate:W}){let K=!1,re=setTimeout(function he(){return A(this,void 0,void 0,function*(){if(K)return;const me=new Date().getTime();try{oe=ye(),yield oe}finally{if(!K){const pe=new Date().getTime();re=setTimeout(he,Math.max(x-(pe-me),0))}}})},W?0:x),oe=Promise.resolve();return{stop(){return A(this,void 0,void 0,function*(){K=!0,clearTimeout(re),yield oe})}}}var O=function(ye,x,W,K){return new(W||(W=Promise))(function(re,oe){function he(ue){try{pe(K.next(ue))}catch(le){oe(le)}}function me(ue){try{pe(K.throw(ue))}catch(le){oe(le)}}function pe(ue){var le;ue.done?re(ue.value):(le=ue.value,le instanceof W?le:new W(function(Re){Re(le)})).then(he,me)}pe((K=K.apply(ye,x||[])).next())})};const Y=n(226),Z=!!L.c,d=new class{constructor(ye){this.samplePeriodSeconds=60,this.buffer={},this.reporters=[],this.flushInterval=f({func:()=>this.flushStats(),delay:this.samplePeriodSeconds*c.a.second}),this.tags=this.filterTags((ye==null?void 0:ye.tags)||{app:L.a,version:L.j,namespace:L.i,instanceId:z.a})}shutdown(){return O(this,void 0,void 0,function*(){yield this.flushInterval.stop(),yield this.flushStats(),yield Object(u.a)(2*c.a.second)})}aggregate(ye,x,W){this.addToBuffer(this.buffer,this.encodeKey({metric:ye,tags:this.filterTags(W||{})}),typeof x=="number"?{min:x,max:x,sum:x,count:1}:x)}increment(ye,x){this.aggregate(ye,1,x)}timer(ye,x,W){return O(this,void 0,void 0,function*(){const K=Y(),re=yield x(),oe=Y();return this.aggregate(ye,oe-K,W),re})}registerStatsReporter(ye){this.reporters.push(ye)}setTag(ye,x){const W=this.filterTags({[ye]:x});this.tags=Object.assign(Object.assign({},this.tags),W)}addToBuffer(ye,x,W){if(ye[x]){const{min:K,max:re,sum:oe,count:he}=ye[x];ye[x]={min:Math.min(K,W.min),max:Math.max(re,W.max),sum:oe+W.sum,count:he+W.count}}else ye[x]=W}write(ye){return O(this,void 0,void 0,function*(){yield Promise.all(this.reporters.map(x=>O(this,void 0,void 0,function*(){let W;const K={};switch(x.type){case"simple":for(const[oe,he]of Object.entries(ye)){const{metric:me}=this.decodeKey(oe);this.addToBuffer(K,this.encodeKey({metric:me}),he)}W=K;break;case"tagged":W=ye;break;default:(function(oe){throw new Error(`Unreachable type encountered (${oe})`)})(x.type)}const re=Object.entries(W);if(re.length>0)return x.send(re.map(([oe,he])=>{const{metric:me,tags:pe}=this.decodeKey(oe);return{name:me,tags:Object.assign(Object.assign({},pe),this.tags),stat:he}}),this.samplePeriodSeconds).catch(oe=>{g.a.debug(`Failed to write stats to ${x.name}`,{error:oe})})})))})}flushStats(){return O(this,void 0,void 0,function*(){yield this.write(this.buffer),this.buffer={}})}encodeKey(ye){return R()(Object.assign(Object.assign({},ye),Object.keys(ye.tags||{}).length>0?{tags:ye.tags}:{}))}decodeKey(ye){return JSON.parse(ye)}filterTags(ye){return Object.entries(ye||{}).reduce((x,[W,K])=>(M(W)&&M(K)&&(x[W]=K),x),{})}};Z||["local","on-prem"].includes(L.i)||d.registerStatsReporter(new T("stats"));var p=function(ye,x,W,K){return new(W||(W=Promise))(function(re,oe){function he(ue){try{pe(K.next(ue))}catch(le){oe(le)}}function me(ue){try{pe(K.throw(ue))}catch(le){oe(le)}}function pe(ue){var le;ue.done?re(ue.value):(le=ue.value,le instanceof W?le:new W(function(Re){Re(le)})).then(he,me)}pe((K=K.apply(ye,x||[])).next())})};class C extends class{constructor(x){this.options=x,this.cache=new y.a(Object.assign(Object.assign(Object.assign({},x.dispose||x.disposeAfter?{ttlAutopurge:!0}:{}),x),{dispose:(...W)=>{var K;W[2]==="evict"&&d.increment("lru-eviction",{name:x.name}),(K=x.dispose)===null||K===void 0||K.call(x,...W)},disposeAfter:(...W)=>{var K;this.updateStats(),(K=x.disposeAfter)===null||K===void 0||K.call(x,...W)}})),this.stringify=x.fastStringify?JSON.stringify:R.a}set(x,W,K){const re=this.stringify(x);if(!this.cache.set(re,W,{ttl:K})){const oe=this.cache.sizeCalculation?this.cache.sizeCalculation(W,re):"unknown";throw Error(`Value too large (${oe} > ${this.cache.max})`)}this.updateStats()}get(x){const{name:W}=this.options,K=this.stringify(x),re=this.cache.getRemainingTTL(K);return re<=0?d.increment("cache-miss",{name:W}):re!==1/0&&d.aggregate("cache-item-ttl",re,{name:W}),this.cache.get(K)}delete(x){this.cache.delete(this.stringify(x))}peek(x){return this.cache.peek(this.stringify(x))}size(){return this.cache.size}clear(){this.cache.clear()}forEach(x){this.cache.forEach(x)}purgeStale(){return this.cache.purgeStale()}updateStats(){const{name:x}=this.options;d.aggregate("cache-item-count",this.cache.size,{name:x}),this.cache.calculatedSize!==void 0&&d.aggregate("cache-length",this.cache.calculatedSize,{name:x})}}{constructor(x){if(super(x),this.expireRejectedPromiseValues=x.expireRejectedPromiseValues===void 0||x.expireRejectedPromiseValues,this.rejectedPromiseValueTtl=x.rejectedPromiseValueTtl!==void 0?x.rejectedPromiseValueTtl:c.a.second,this.rejectedPromiseValueTtl<0)throw new Error("rejectedPromiseValueTtl must not be negative")}set(x,W,K){super.set(x,W,K),this.expireRejectedPromiseValues&&W.catch(()=>p(this,void 0,void 0,function*(){yield Object(u.a)(this.rejectedPromiseValueTtl),this.peek(x)===W&&this.delete(x)}))}}var b=function(ye,x,W,K){return new(W||(W=Promise))(function(re,oe){function he(ue){try{pe(K.next(ue))}catch(le){oe(le)}}function me(ue){try{pe(K.throw(ue))}catch(le){oe(le)}}function pe(ue){var le;ue.done?re(ue.value):(le=ue.value,le instanceof W?le:new W(function(Re){Re(le)})).then(he,me)}pe((K=K.apply(ye,x||[])).next())})};class P{constructor(x,W,K){this.authClient=x,this.email=W,this.password=K,this.tokenTtlMs=1*c.a.hour,this.tokenCache=new C({name:"Credentials-tokenCache",max:100,ttl:this.tokenTtlMs-5*c.a.minute,fastStringify:!0})}getToken(){return b(this,void 0,void 0,function*(){let x=this.tokenCache.get(this.email);return x||(x=(()=>b(this,void 0,void 0,function*(){const{authentication:W}=yield this.authClient.login({email:this.email,password:this.password,tokenExpirationSeconds:this.tokenTtlMs/c.a.second});if(!W)throw new Error("User account not verified.");return W.accessToken}))(),this.tokenCache.set(this.email,x)),x})}}var F=n(97),D=n(40),I=function(ye,x,W,K){return new(W||(W=Promise))(function(re,oe){function he(ue){try{pe(K.next(ue))}catch(le){oe(le)}}function me(ue){try{pe(K.throw(ue))}catch(le){oe(le)}}function pe(ue){var le;ue.done?re(ue.value):(le=ue.value,le instanceof W?le:new W(function(Re){Re(le)})).then(he,me)}pe((K=K.apply(ye,x||[])).next())})};class N extends D.a{constructor(x){super(x)}postLanRtcOffer(x){return I(this,void 0,void 0,function*(){return yield this.fetch("v1/lan-rtc-offer",{method:"POST",body:JSON.stringify(x)})})}}var B=function(ye,x,W,K){return new(W||(W=Promise))(function(re,oe){function he(ue){try{pe(K.next(ue))}catch(le){oe(le)}}function me(ue){try{pe(K.throw(ue))}catch(le){oe(le)}}function pe(ue){var le;ue.done?re(ue.value):(le=ue.value,le instanceof W?le:new W(function(Re){Re(le)})).then(he,me)}pe((K=K.apply(ye,x||[])).next())})};function w(ye){return B(this,void 0,void 0,function*(){return(yield Promise.all(ye.map(x=>x.catch(W=>W)))).filter(x=>x instanceof Error)})}function h(ye){if(ye!==void 0)return ye;throw new Error("Value is undefined")}function k(ye,x){const W=ye.reduce((K,re)=>[...K,...re.urls],[]).filter(K=>V(K,x)).sort(K=>X(K,"udp")?-1:0).shift();if(W)return Object.assign(Object.assign({},h(ye.find(K=>K.urls.includes(W)))),{urls:[W]})}function V(ye,x){switch(x){case"stun":return/^stuns?:/.test(ye);case"turn":return/^turns?:/.test(ye)}}function X(ye,x){return ye.endsWith(`transport=${x}`)}var Q=n(9),te=n(24),q=n(229),H=n(29);const v={ordered:!1,maxPacketLifeTime:300*c.a.millisecond},S={ordered:!0},U={ordered:!0},J={ordered:!1,maxRetransmits:0},$={ordered:!1,maxRetransmits:0},ne=ye=>"received"in ye&&ye.received!==void 0,se=ye=>!("received"in ye)||ye.received===void 0,ge=2*c.a.second;function ve(ye,x={}){const W=Array.from(ye.values()),K=W.filter(ne),re=K.length>0,oe=Math.max(...K.map(ue=>ue.received));let he;if(re){const ue=W.length,le=K.length,Re=K.map(je=>je.received-je.sent),{standardDeviation:Ie,mean:ke,jitter:Ve}=function(je){const Be=je.length;if(Be===0)return{mean:NaN,standardDeviation:-1,jitter:NaN};const $e=je.reduce((Je,it)=>Je+it,0)/Be,Ze=Math.sqrt(je.map(Je=>Math.pow(Je-$e,2)).reduce((Je,it)=>Je+it)/Be);let Ke=0;for(let Je=1;Je<Be;++Je)Ke+=Math.abs(je[Je]-je[Je-1]);return{mean:$e,standardDeviation:Ze,jitter:Ke/(Be-1)}}(Re),Qe=W.filter(je=>je.sent<oe-ge),Ye=Qe.filter(se),Ge=Ye.length===0?0:Ye.length/Qe.length;he={pingsSent:ue,pongsReceived:le,average:ke,standardDeviation:Ie,jitter:Ve,max:Math.max(...Re),min:Math.min(...Re),loss:Ge}}else he=null;const{temporalNow:me=Date.now()}=x,pe=(re?oe:me)-4*ge;return Array.from(ye.entries()).forEach(ue=>{const[le,Re]=ue;Re.sent<pe&&ye.delete(le)}),he}function Oe({entityId:ye,streamName:x,streamType:W}){return`${ye}.${x}.${W}`}var Se=function(ye,x,W,K){return new(W||(W=Promise))(function(re,oe){function he(ue){try{pe(K.next(ue))}catch(le){oe(le)}}function me(ue){try{pe(K.throw(ue))}catch(le){oe(le)}}function pe(ue){var le;ue.done?re(ue.value):(le=ue.value,le instanceof W?le:new W(function(Re){Re(le)})).then(he,me)}pe((K=K.apply(ye,x||[])).next())})};class Ce{constructor(x,W){this.sessionId=x,this.connection=W,this.counts={localSent:new Map,localReceived:new Map,remoteSent:new Map,remoteReceived:new Map},this.sessionId=x,this.connection=W}updateRemoteMessagesCounts(x){if(x.payload.streamsInfo){this.counts.remoteSent=new Map,this.counts.remoteReceived=new Map;for(const W of x.payload.streamsInfo.items)this.counts.remoteSent.set(W.streamId,W.sentCount),this.counts.remoteReceived.set(W.streamId,W.receivedCount)}}getLocalStreamsInfo(x){const{localSent:W,localReceived:K}=this.counts;return{items:[...new Set([...W.keys(),...K.keys()])].map(re=>{var oe,he;return{streamId:re,sentCount:(oe=W.get(re))!==null&&oe!==void 0?oe:0,receivedCount:(he=K.get(re))!==null&&he!==void 0?he:0}}),timestamp:x}}incrementLocalSent(x){const{localSent:W}=this.counts,K=Oe(x.header.stream);W.set(K,(W.get(K)||0)+1)}incrementLocalReceived(x){const{localReceived:W}=this.counts,K=Oe(x.header.stream),re=W.get(K)||0;if(re===0){const{streamName:oe,streamType:he}=x.header.stream;g.a.debug("RTC client received first message for stream",{streamName:oe,streamType:he})}W.set(K,re+1)}uploadMetrics(){return Se(this,void 0,void 0,function*(){const{sessionId:x}=this,W=yield this.connection.peerConnection.getStats(),K={};W.forEach(ue=>K[ue.id]=ue),g.a.debug("rtc-stats",Object.assign(Object.assign({},K),{sessionId:x}));const{localSent:re,localReceived:oe,remoteSent:he,remoteReceived:me}=this.counts,pe=[...new Set([...re.keys(),...oe.keys()])].reduce((ue,le)=>{const Re=re.get(le),Ie=oe.get(le),ke=he.get(le),Ve=me.get(le);return Object.assign(Object.assign({},ue),{[`local-${le}-sent`]:Re,[`local-${le}-received`]:Ie,[`remote-${le}-sent`]:ke,[`remote-${le}-received`]:Ve})},{sessionId:x});g.a.debug("rtc-message-report",Object.assign({deviceId:this.connection.getRemoteDeviceId()},pe))})}}function Ee(ye,x,W){return{header:{stream:ye,created:Date.now(),frameId:W||""},payload:x}}function Te(ye){return new Set(["disconnected","failed","closed"]).has(ye.iceConnectionState)}function De(ye){switch(ye.header.stream.streamType){case"twist":{const{twist:x}=ye.payload;if(!x)throw Error("twist not in payload of RTC message with type twist");return{header:ye.header,payload:{twist:{linear:Object.assign({x:0,y:0,z:0},x.linear),angular:Object.assign({x:0,y:0,z:0},x.angular)}}}}case"pose":{const{pose:x}=ye.payload;if(!x)throw Error("pose not in payload of RTC message with type pose");return{header:ye.header,payload:{pose:{translation:Object.assign({x:0,y:0,z:0},x.translation),rotation:Object.assign({x:0,y:0,z:0,w:0},x.rotation)}}}}case"pose-with-covariance":{const{poseWithCovariance:x}=ye.payload;if(!x)throw Error("poseWithCovariance not in payload of RTC message with type pose-with-covariance");const W=new Array(36).fill(0);return x.covariance.forEach((K,re)=>{if(re>=36)throw Error("covariance contains more than 36 elements");W[re]=K}),{header:ye.header,payload:{poseWithCovariance:{pose:{translation:Object.assign({x:0,y:0,z:0},x.pose.translation),rotation:Object.assign({x:0,y:0,z:0,w:0},x.pose.rotation)},covariance:W}}}}case"point":{const{point:x}=ye.payload;if(!x)throw Error("point not in payload of RTC message with type point");return{header:ye.header,payload:{point:Object.assign({x:0,y:0,z:0},x)}}}default:return ye}}var qe=function(ye,x,W,K){return new(W||(W=Promise))(function(re,oe){function he(ue){try{pe(K.next(ue))}catch(le){oe(le)}}function me(ue){try{pe(K.throw(ue))}catch(le){oe(le)}}function pe(ue){var le;ue.done?re(ue.value):(le=ue.value,le instanceof W?le:new W(function(Re){Re(le)})).then(he,me)}pe((K=K.apply(ye,x||[])).next())})};class et{constructor(x,W,K){this.peerConnection=x,this.config=W,this.dataChannelNotifier=K,this.connectTimeoutMs=20*c.a.second,this.iceGatheringTimeoutMs=15*c.a.second,this.pingUpdateTimeoutMs=1*c.a.second,this.pingV2UpdateTimeoutMs=250*c.a.millisecond,this.pingV2MetricsGatherTimeoutMs=1*c.a.second,this.streamsInfoUpdateTimeoutMs=2*c.a.second,this.reassemblyTimeoutMs=500*c.a.millisecond,this.reassemblyTableCleanupMs=1*c.a.second,this.heartbeatTimeoutMs=20*c.a.millisecond,this.streamLatestTimestamp=new Map,this.reassemblyTable=new Map,this.reassemblyTableLastTimestamp=new Map,this.closeCalled=!1,this.gotOffer=!1,this.hasIceCandidate=!1,this.pingV2Map=new Map,this.sendPingV2=()=>{const{latestTryOnceStreamChannel:oe}=this;if(!oe)return;const he=new Date().getTime(),me=Object(q.a)();this.sendSystemMessage(oe,{type:"ping-v2",payload:{timestamp:he,id:me}}),this.pingV2Map.set(me,{sent:he})},this.gatherPingV2Metrics=()=>{const oe=ve(this.pingV2Map);oe&&(this.pingInfo=oe,d.aggregate("rtc-ping-average",oe.average),d.aggregate("rtc-ping-loss",oe.loss),d.aggregate("rtc-jitter",oe.jitter))};const{isOffer:re}=W.baseConfig;re?this.initializeChannels(x):x.ondatachannel=oe=>{switch(oe.channel.label){case"stream.latest-ttl":this.latestTtlStreamChannel=oe.channel;break;case"stream.reliable":this.reliableStreamChannel=oe.channel;break;case"stream.latest-reliable":this.latestReliableStreamChannel=oe.channel;break;case"stream.latest-try-once":this.latestTryOnceStreamChannel=oe.channel;break;case"heartbeat":return void(this.heartbeatChannel=oe.channel);default:return void this.dataChannelNotifier(oe.channel)}this.setupChannel(oe.channel)},this.pingUpdateTimeout=setInterval(()=>{const{reliableStreamChannel:oe}=this;oe&&this.sendSystemMessage(oe,{type:"ping"})},this.pingUpdateTimeoutMs),this.pingV2UpdateTimeout=setInterval(this.sendPingV2,this.pingV2UpdateTimeoutMs),this.pingV2MetricsGatherTimeout=setInterval(this.gatherPingV2Metrics,this.pingV2MetricsGatherTimeoutMs),this.streamsInfoUpdateTimeout=setInterval(()=>{const{latestTtlStreamChannel:oe}=this;oe&&this.sendSystemMessage(oe,{type:"streams-info"})},this.streamsInfoUpdateTimeoutMs),this.reassemblyTableCleanupTimeout=setInterval(()=>{const oe=new Date().getTime();this.reassemblyTableLastTimestamp.forEach((he,me,pe)=>{oe>me+this.reassemblyTimeoutMs&&this.reassemblyTable.delete(he)})},this.reassemblyTableCleanupMs),this.heartbeatTimeout=setInterval(()=>{const{heartbeatChannel:oe}=this;oe&&oe.readyState==="open"&&oe.send(new Uint8Array([1]))},this.heartbeatTimeoutMs)}handleSignal(x){return qe(this,void 0,void 0,function*(){const{peerConnection:W}=this,{track:K}=this.config.baseConfig,re=(()=>{try{return JSON.parse(x.getPayload())}catch{return}})();if(!re)return void g.a.error("Received unparseable signal.");g.a.debug("Handling signal",{description:re});const{sdp:oe,type:he}=re;if(!oe||!he)return void g.a.warn("Received non-SDP signal");const{signalingState:me,connectionState:pe}=W;if(me!=="stable"||pe!=="connected")if(W.remoteDescription)g.a.warn(`Received SDP after remote description was set: ${oe}`);else{if(he==="offer"){if(me!=="stable")return void g.a.warn("Received offer SDP when signaling is ongoing.");yield W.setRemoteDescription(re);const ue=yield W.createAnswer();yield W.setLocalDescription(ue);const le=x.clone();return K==null||K("Answer Received",le),le.setPayload(JSON.stringify(ue)),le.setReceiverId(x.getSenderId()),le.setSenderId(x.getReceiverId()),le}if(he==="answer"){if(me==="stable")return void g.a.warn("Received answer SDP when signaling hasn't started.");yield W.setRemoteDescription(re)}}else g.a.warn(`Received SDP when already connected: ${oe}`)})}send(x,W){const K=this.getChannelFromLabel(W.channelLabel);K?this.sendOnChannel(K,x):g.a.warn("Send called with unexpected channel label",{channelLabel:W.channelLabel})}controlRemoteStream(x){this.sendSystemMessage(h(this.reliableStreamChannel),{type:"stream-control",streamControl:x})}isActive(){return new Set(["new","checking","connected","completed"]).has(this.peerConnection.iceConnectionState)||this.isReady()}isReady(){const{reliableStreamChannel:x,latestTtlStreamChannel:W,latestTryOnceStreamChannel:K,latestReliableStreamChannel:re}=this;return(x==null?void 0:x.readyState)==="open"&&(W==null?void 0:W.readyState)==="open"&&(K==null?void 0:K.readyState)==="open"&&(re==null?void 0:re.readyState)==="open"}close(){return qe(this,void 0,void 0,function*(){if(this.closeCalled)return;this.closeCalled=!0,this.sessionMetrics&&(yield this.sessionMetrics.uploadMetrics()),nt(this.pingUpdateTimeout),nt(this.pingV2UpdateTimeout),nt(this.pingV2MetricsGatherTimeout),nt(this.reassemblyTableCleanupTimeout),nt(this.streamsInfoUpdateTimeout),nt(this.heartbeatTimeout);const{peerConnection:x,reliableStreamChannel:W,latestTtlStreamChannel:K,latestTryOnceStreamChannel:re,latestReliableStreamChannel:oe}=this;x.close(),W==null||W.close(),K==null||K.close(),re==null||re.close(),oe==null||oe.close()})}getPing(){return this.pingTimeMs}getPingInfo(){return this.pingInfo}getLastMessageTimestamp(){return this.lastMessageTimestamp}getSessionCreatedTimestamp(){var x;return(x=this.config.remoteConfig)===null||x===void 0?void 0:x.sessionCreatedTimestamp}setSessionCreatedTimestamp(x){this.config.remoteConfig&&(this.config.remoteConfig.sessionCreatedTimestamp=x)}getSessionId(){var x;return(x=this.config.remoteConfig)===null||x===void 0?void 0:x.sessionId}setSessionId(x){this.config.remoteConfig&&(this.config.remoteConfig.sessionId=x,this.sessionMetrics=new Ce(x,this))}getRemotePeerId(){return this.config.baseConfig.remotePeerId}getRemoteDeviceId(){var x;return(x=this.config.baseConfig)===null||x===void 0?void 0:x.remoteDeviceId}setRemoteDeviceId(x){this.config.baseConfig.remoteDeviceId=x}getSessionMetricsMessageCounts(){var x;return(x=this.sessionMetrics)===null||x===void 0?void 0:x.counts}getConnectionStatsInfo(){return qe(this,void 0,void 0,function*(){const{peerConnection:x}=this;if(!x)return;const W=yield x.getStats(null),K=[];W.forEach(pe=>{K.push(pe)});const re=K.find(pe=>pe.type==="transport");if(!re)return;const oe=K.find(pe=>(pe.type==="candidate-pair"||pe.type==="candidatepair")&&pe.id===re.selectedCandidatePairId);if(!oe)return;const he=K.find(pe=>pe.id===oe.localCandidateId),me=K.find(pe=>pe.id===oe.remoteCandidateId);return he&&me&&(he.address=he.address||he.ip,me.address=me.address||me.ip,he.address!==void 0&&me.address!==void 0)?{transport:re,localCandidate:he,remoteCandidate:me}:void 0})}initializeChannels(x){this.heartbeatChannel=x.createDataChannel("heartbeat",$),this.heartbeatChannel.binaryType="arraybuffer",this.latestTtlStreamChannel=x.createDataChannel("stream.latest-ttl",v),this.latestTtlStreamChannel.binaryType="arraybuffer",this.reliableStreamChannel=x.createDataChannel("stream.reliable",S),this.reliableStreamChannel.binaryType="arraybuffer",this.latestReliableStreamChannel=x.createDataChannel("stream.latest-reliable",U),this.latestReliableStreamChannel.binaryType="arraybuffer",this.latestTryOnceStreamChannel=x.createDataChannel("stream.latest-try-once",J),this.latestTryOnceStreamChannel.binaryType="arraybuffer",this.setupChannel(this.latestTtlStreamChannel),this.setupChannel(this.reliableStreamChannel),this.setupChannel(this.latestReliableStreamChannel),this.setupChannel(this.latestTryOnceStreamChannel)}getOffer(){var x,W,K;return qe(this,void 0,void 0,function*(){const{gotOffer:re}=this,{peerConnection:oe,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 me=(x=this.config.remoteConfig)===null||x===void 0?void 0:x.sessionId;if(re)return void g.a.debug("Failed to generate offer because gotOffer was already called.");if(this.gotOffer=!0,Te(this.peerConnection))return void g.a.debug("Failed to generate offer because the peer connection was inactive.");const pe=he.baseConfig.track;oe.onicecandidate=()=>{this.hasIceCandidate=!0},oe.oniceconnectionstatechange=()=>qe(this,void 0,void 0,function*(){const ke=oe.iceConnectionState;if(ke==="connected"||ke==="completed"){const Ve=yield this.getConnectionStatsInfo(),Qe=Ve?function(Ye){const Ge=Ye.localCandidate.candidateType,je=Ye.remoteCandidate.candidateType;return Ge==="host"&&je==="host"?"local":Ge==="relay"||je==="relay"?"TURN":"STUN"}(Ve):void 0;g.a.info(`ICE connection state changed to ${ke}`,{sessionId:me,connectionStatsInfo:Ve,iceMode:Qe}),pe==null||pe("ICE connection state change",{iceConnectionState:ke,sessionId:me,connectionStatsInfo:Ve,iceMode:Qe})}}),yield oe.setLocalDescription(yield oe.createOffer());const ue=new Date().getTime();for(;;){const ke=new Date().getTime()-ue;if(ke>this.connectTimeoutMs)return void g.a.debug("Failed to generate offer because ICE gathering timed out.");if(ke>this.iceGatheringTimeoutMs&&this.hasIceCandidate){g.a.debug("ICE gathering partially completed; proceeding",{iceTransportPolicy:oe.getConfiguration().iceTransportPolicy,waitTime:ke}),pe==null||pe("ICE gathering partially completed",{sessionId:me,iceTransportPolicy:oe.getConfiguration().iceTransportPolicy,waitTime:ke});break}if(oe.iceGatheringState==="complete"){g.a.debug("ICE gathering complete",{iceTransportPolicy:oe.getConfiguration().iceTransportPolicy,waitTime:ke}),pe==null||pe("ICE gathering completed",{sessionId:me,iceTransportPolicy:oe.getConfiguration().iceTransportPolicy,waitTime:ke});break}yield Object(u.a)(.1*c.a.second)}const le=(W=this.peerConnection.getConfiguration().iceServers)!==null&&W!==void 0?W:[];for(const ke of le)ke.credentialType=void 0;const Re=JSON.stringify(le),Ie=new Q.Signal;return Ie.setPayload(JSON.stringify(oe.localDescription)),Ie.setSenderId(this.config.baseConfig.localPeerId),Ie.setReceiverId(this.config.baseConfig.remotePeerId),Ie.setIceServers(Re),Ie.setIceTransportPolicy((K=this.peerConnection.getConfiguration().iceTransportPolicy)!==null&&K!==void 0?K:"all"),this.config.baseConfig.sessionType!==void 0?Ie.setSessionType(this.config.baseConfig.sessionType):Ie.setSessionType(Q.SessionType.TELEOP),g.a.debug("Sending offer signal with description",{description:Ie.getPayload()}),Ie})}getLanOffer(){return qe(this,void 0,void 0,function*(){const{peerConnection:x,gotOffer:W}=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(W)return void g.a.debug("Failed to generate offer because gotOffer was already called.");if(this.gotOffer=!0,Te(this.peerConnection))return void g.a.debug("Failed to generate offer because the peer connection was inactive.");yield x.setLocalDescription(yield x.createOffer());const K=new Date().getTime();for(;;){if(new Date().getTime()-K>this.iceGatheringTimeoutMs)return void g.a.debug("Failed to generate offer because ICE gathering timed out.");if(x.iceGatheringState==="complete")break;yield Object(u.a)(.1*c.a.second)}const re=x.localDescription;if(re)return g.a.debug("Sending LAN offer signal with description",{description:re}),re;g.a.error("Failed to generate LAN offer description")})}handleLanAnswer(x){return qe(this,void 0,void 0,function*(){const{peerConnection:W}=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 W.setRemoteDescription(x)})}getChannelFromLabel(x){switch(x){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(x,W){let K;try{K=Object(H.encode)(JSON.stringify(W))}catch(re){return void g.a.warn("Failed to encode RTC message",{error:re})}try{x.send(K),this.sessionMetrics&&this.sessionMetrics.incrementLocalSent(W)}catch(re){g.a.warn("Failed to send message to channel",{error:re,channel:x.label})}}channelNotRecognized(x){return x!==this.latestTtlStreamChannel&&x!==this.latestReliableStreamChannel&&x!==this.latestTryOnceStreamChannel&&x!==this.reliableStreamChannel}setupChannel(x){x.onmessage=W=>{if(this.channelNotRecognized(x))return void g.a.warn("Received message on unrecognized data channel.");let K;try{K=JSON.parse(Object(H.decode)(W.data))}catch(re){return void g.a.warn("Received unparseable message on RTC stream data channel",{error:re,channel:x.label})}K.communicationType==="message-chunk"?this.receiveChannelMessageChunk(x,K):this.receiveChannelMessage(x,K)},x.onerror=W=>{g.a.warn(`Channel error: ${W.error}`,{error:W.error,sessionId:this.getSessionId(),channelLabel:x.label})},x.onopen=()=>{g.a.debug("Channel opened",{sessionId:this.getSessionId(),channelLabel:x.label})},x.onclose=()=>{const W={bufferedAmount:x.bufferedAmount,sessionId:this.getSessionId(),channelLabel:x.label};this.closeCalled===!1?g.a.debug("Unexpected channel closed",W):g.a.debug("Channel closed",W)}}receiveChannelMessage(x,W){const{config:K}=this,{remotePeerId:re}=this.config.baseConfig;this.lastMessageTimestamp=new Date().getTime(),W=De(W),this.sessionMetrics&&this.sessionMetrics.incrementLocalReceived(W),this.handleSystemMessage(x,W)||(x===this.latestTryOnceStreamChannel||x===this.latestTtlStreamChannel||x===this.latestReliableStreamChannel)&&!this.isLatestMessage(W)||K.baseConfig.receive(re,W)}receiveChannelMessageChunk(x,W){const K=this.reassemblyTable.get(W.id)||[];if(K.push(W),K.length===W.total){const re=function(oe){const he=oe.sort((me,pe)=>me.seq<pe.seq?-1:1).map(me=>me.part).reduce((me,pe)=>me+pe);try{return JSON.parse(he)}catch{return void g.a.warn("Could not reassemble RTC message chunks")}}(K);return re&&this.receiveChannelMessage(x,re),void this.reassemblyTable.delete(W.id)}this.reassemblyTable.set(W.id,K),this.reassemblyTableLastTimestamp.set(W.id,new Date().getTime())}handleSystemMessage(x,W){var K,re;const{config:oe}=this,{baseConfig:he}=oe,{remotePeerId:me}=he;switch(W.header.stream.streamType){case"ping":return this.sendSystemMessage(x,{type:"pong",timestamp:h(W.payload.ping)}),!0;case"pong":{const pe=new Date().getTime()-h(W.payload.pong);return this.pingTimeMs=pe,d.aggregate("rtc-ping-time",pe),!0}case"ping-v2":return this.sendPingV2(),!0;case"pong-v2":{const pe=h(W.payload.pongV2),ue=this.pingV2Map.get(pe.id);return(ue==null?void 0:ue.sent)!==pe.timestamp?(g.a.warn("Pong timestamp doesn't match stored value",{currentEntry:ue,pong:pe}),!0):(this.pingV2Map.set(pe.id,{sent:pe.timestamp,received:new Date().getTime()}),!0)}case"streams-info":{const{sessionMetrics:pe}=this,ue=(K=W.payload.streamsInfo)===null||K===void 0?void 0:K.timestamp;return!!ue&&(pe==null||pe.updateRemoteMessagesCounts(W),(re=he.onStreamsInfoUpdate)===null||re===void 0||re.call(he,me,ue),!0)}case"stream-control":return!0;default:return!1}}sendSystemMessage(x,W){var K;const{localUserId:re,localPeerId:oe}=this.config.baseConfig;if(x.readyState!=="open")return;const he={entityId:re!=null?re:oe,streamName:`$.${W.type}`,streamType:W.type};let me;switch(W.type){case"ping":me={ping:new Date().getTime()};break;case"pong":me={pong:W.timestamp};break;case"ping-v2":me={pingV2:W.payload};break;case"pong-v2":me={pongV2:W.payload};break;case"stream-control":me={streamControl:W.streamControl};break;case"streams-info":me={streamsInfo:(K=this.sessionMetrics)===null||K===void 0?void 0:K.getLocalStreamsInfo(new Date().getTime())}}this.sendOnChannel(x,Ee(he,me))}isLatestMessage(x){const W=Oe(x.header.stream),K=(this.streamLatestTimestamp.get(W)||0)<=x.header.created;return K&&this.streamLatestTimestamp.set(W,x.header.created),K}}function nt(ye){ye&&clearInterval(ye)}function Rt(ye){var x,W;return{userId:(x=ye.getUserId())===null||x===void 0?void 0:x.getValue(),deviceId:(W=ye.getDeviceId())===null||W===void 0?void 0:W.getValue(),organizationId:ye.getOrganizationId(),id:ye.getPeerId(),capabilities:[],capabilitySet:{}}}var Le=function(ye,x,W,K){return new(W||(W=Promise))(function(re,oe){function he(ue){try{pe(K.next(ue))}catch(le){oe(le)}}function me(ue){try{pe(K.throw(ue))}catch(le){oe(le)}}function pe(ue){var le;ue.done?re(ue.value):(le=ue.value,le instanceof W?le:new W(function(Re){Re(le)})).then(he,me)}pe((K=K.apply(ye,x||[])).next())})};class _t{constructor(x){this.config=x,this.grpcCallDeadline=5*c.a.second,this.refreshIntervalDelayMs=2*c.a.second,this.iceServersTtl=30*c.a.minute,this.connections=[],this.localConnections=[],this.isConnectionInitiator=new Map,this.isOutgoingConnection=new Map,this.peerDataChannelListeners=[];const{refreshIntervalDelayMs:W}=this;this.refreshInterval=f({func:()=>Le(this,void 0,void 0,function*(){try{yield this.update()}catch(K){g.a.warn("RTC refresh failed",{error:K})}}),delay:W,immediate:!0})}send(x,W,K){const re=this.getActiveConnection(x);re?re.isReady()?re.send(W,K):g.a.warn("Send called with unready connection."):g.a.warn("Send called with no connection.")}controlRemoteStream(x,W){const K=this.getActiveConnection(x);K?K.isReady()?K.controlRemoteStream(W):g.a.warn("controlRemoteStream called with unready connection."):g.a.warn("controlRemoteStream called with no connection.")}getLocalPeer(){return Le(this,void 0,void 0,function*(){for(;!this.localPeer;)yield Object(u.a)(.1*c.a.second);return Rt(this.localPeer)})}connect(x,W){var K,re,oe;return Le(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:me}=this.config,{localPeer:pe,receiveSignalStream:ue,iceServers:le}=this;if(!pe||!ue||!le)return void g.a.warn("Connect called prior to local peer, receiveSignalStream, and ICE servers ready");if(this.getActiveConnection(x))return void g.a.warn("Connect called for peer with existing connection.");if(this.isOutgoingConnection.get(x))return void g.a.warn("Connect called for peer with an existing outgoing connection offer.");this.isOutgoingConnection.set(x,!0);const Re=function(je,Be,$e){const{rtcIceTransportPolicies:Ze,rtcIceServerProtocol:Ke,useAllServers:Je}=Be||{},it=je.map(st=>Object.assign(Object.assign({},st),{urls:st.urls.filter(dt=>{const St=(Ze===void 0||Ze.some(wt=>V(dt,wt)))&&(Ke===void 0||X(dt,Ke));return St||g.a.debug(`Ignoring ICE server: ${dt}`,{organizationId:$e}),St})})).filter(({urls:st})=>st.filter(dt=>dt).length>0);return Je?it:[k(it,"stun"),k(it,"turn")].filter(st=>st!==void 0).map(st=>h(st))}(le,W);g.a.debug("Received ICE servers:",le),g.a.debug("Using ICE servers:",Re);const Ie=new et(yield this.createRTCPeerConnection(Re),{baseConfig:{isOffer:!0,isLan:!1,receive:(je,Be)=>this.config.receive(je,Be),onStreamsInfoUpdate:this.config.onStreamsInfoUpdate?(je,Be)=>{var $e,Ze;return(Ze=($e=this.config).onStreamsInfoUpdate)===null||Ze===void 0?void 0:Ze.call($e,je,Be)}:void 0,track:this.config.lanOnlyMode?void 0:this.config.track,localUserId:(K=pe.getUserId())===null||K===void 0?void 0:K.getValue(),localPeerId:pe.getPeerId(),remotePeerId:x,sessionType:this.config.sessionType},remoteConfig:{}},je=>this.onCustomDataChannel(x,je)),ke=yield Ie.getOffer();if(!ke)return g.a.error("Failed to generate offer."),void this.isOutgoingConnection.delete(x);g.a.debug("Sending offer."),he==null||he("Sending offer",ke);const Ve=new Q.SendSignalRequest;Ve.setSignal(ke);const Qe=yield(()=>Le(this,void 0,void 0,function*(){try{return yield me.sendSignal(Ve,yield this.getMetadata({}))}catch(je){g.a.warn("Error when sending signal",{error:je})}}))();if(!this.isOutgoingConnection.get(x))return void g.a.debug("No offer set after receiving offer signal response.");g.a.debug("Offer sent.");const Ye=(re=Qe==null?void 0:Qe.getSessionId())===null||re===void 0?void 0:re.getValue(),Ge=(oe=Qe==null?void 0:Qe.getSessionCreatedTimestamp())===null||oe===void 0?void 0:oe.getValue();return Ye&&Ge?(Ie.setSessionId(Ye),Ie.setSessionCreatedTimestamp(Ge),this.isOutgoingConnection.delete(x),this.connections.push(Ie),this.isConnectionInitiator.set(Ie,!0),this.setupHandlers(Ie),Ye):(g.a.warn("No session ID or no session created timestamp on send signal response."),void this.isOutgoingConnection.delete(x))})}connectLan(x){var W,K;return Le(this,void 0,void 0,function*(){const re=new N(x),oe=new et(yield this.createRTCPeerConnection([]),{baseConfig:{isOffer:!0,isLan:!0,receive:(ue,le)=>this.config.receive(ue,le),onStreamsInfoUpdate:this.config.onStreamsInfoUpdate?(ue,le)=>{var Re,Ie;return(Ie=(Re=this.config).onStreamsInfoUpdate)===null||Ie===void 0?void 0:Ie.call(Re,ue,le)}:void 0,track:this.config.lanOnlyMode?void 0:this.config.track,localUserId:(K=(W=this.localPeer)===null||W===void 0?void 0:W.getUserId())===null||K===void 0?void 0:K.getValue(),localPeerId:"lan_client",remotePeerId:x}},ue=>this.onCustomDataChannel(x,ue)),he=yield oe.getLanOffer();if(!he)return g.a.warn("Could not generate LAN offer"),!1;const me=yield re.postLanRtcOffer({offer:JSON.stringify(he)}),pe=new RTCSessionDescription(JSON.parse(me.answer));return yield oe.handleLanAnswer(pe),this.localConnections.push(oe),this.isConnectionInitiator.set(oe,!0),Object(q.a)()})}getConnections(){return[...this.connections,...this.localConnections]}createCustomDataChannel(x,W,K,re,oe){const he=this.getActiveConnection(x);if(he&&this.isConnectionInitiator.has(he)){const pe=he.peerConnection.createDataChannel("custom."+W,K);return re&&(pe.binaryType="arraybuffer"),oe(x,pe),()=>{}}const me=(pe,ue)=>{x===pe&&ue.label==="custom."+W&&oe(x,ue)};return this.peerDataChannelListeners.push(me),()=>{this.peerDataChannelListeners=this.peerDataChannelListeners.filter(pe=>pe!==me)}}onCustomDataChannel(x,W){this.peerDataChannelListeners.forEach(K=>K(x,W))}getConnectionStatus(x){if(this.isOutgoingConnection.get(x))return"connecting";const W=this.getActiveConnection(x);return W?W.isReady()?"connected":"connecting":"disconnected"}getConnectionStatsInfo(x){return Le(this,void 0,void 0,function*(){const W=this.getActiveConnection(x);if(W)return yield W.getConnectionStatsInfo()})}disconnect(x){return Le(this,void 0,void 0,function*(){const W=this.getActiveConnection(x);W&&(yield W.close())})}getPeers(){return Le(this,void 0,void 0,function*(){if(this.config.lanOnlyMode)throw new Error("getPeers method cannot be used in local-only mode.");const{signalingClient:x}=this.config,W=yield(()=>Le(this,void 0,void 0,function*(){try{return yield x.getPeers(new Q.GetPeersRequest,yield this.getMetadata({}))}catch(oe){g.a.warn("Error when getting peers",{error:oe})}}))();if(!W)return[];const K=W.getPeersList();if(!K)return[];const re=oe=>{var he,me;return(me=(he=oe.getPeerCreatedTimestamp())===null||he===void 0?void 0:he.getValue())!==null&&me!==void 0?me:0};return K.sort((oe,he)=>re(he)-re(oe)).map(oe=>Rt(oe))})}getSessions(){return Le(this,void 0,void 0,function*(){if(this.config.lanOnlyMode)throw new Error("getPeers method cannot be used in local-only mode.");const{signalingClient:x}=this.config,W=yield(()=>Le(this,void 0,void 0,function*(){try{return yield x.getPeers(new Q.GetPeersRequest,yield this.getMetadata({}))}catch(oe){g.a.warn("Error when getting peers",{error:oe})}}))();if(!W)return{};const K=W.getPeersList(),re={};for(const oe of K)re[oe.getPeerId()]=oe.getSessionIdsList();return re})}getPing(x){const W=this.getActiveConnection(x);if(W)return W.getPing();g.a.warn("Attempted to get ping time from inactive peer.")}getPingInfo(x){const W=this.getActiveConnection(x);if(W)return W.getPingInfo();g.a.warn("Attempted to get ping time from inactive peer.")}getLastMessageTimestamp(x){const W=this.getActiveConnection(x);if(W)return W.getLastMessageTimestamp();g.a.warn("Attempted to get last message time from inactive peer.")}getSessionMetricsMessageCounts(x){const W=this.getActiveConnection(x);if(W)return W.getSessionMetricsMessageCounts();g.a.warn("Attempted to get session metrics counts from inactive peer.")}isReady(){if(this.config.lanOnlyMode)return!0;const{localPeer:x,receiveSignalStream:W,iceServers:K}=this;return!!(x&&W&&K)}shutdown(){return Le(this,void 0,void 0,function*(){g.a.info("Shutdown called on RTC client"),yield this.refreshInterval.stop(),this.receiveSignalStream&&this.receiveSignalStream.cancel();const x=this.connections;this.connections=[],yield this.closeConnections(x);const{localPeer:W}=this;if(!W||this.config.lanOnlyMode)return;const{signalingClient:K}=this.config;yield(()=>Le(this,void 0,void 0,function*(){try{const re=new Q.DeletePeerRequest;re.setPeerId(W.getPeerId()),yield K.deletePeer(re,yield this.getMetadata({}))}catch(re){return void g.a.warn("Error deleting local peer",{error:re})}}))()})}createPeer(){return Le(this,void 0,void 0,function*(){if(this.config.lanOnlyMode)throw new Error("createPeer method cannot be used in local-only mode.");const{signalingClient:x}=this.config,W=yield(()=>Le(this,void 0,void 0,function*(){try{return yield x.createPeer(new Q.CreatePeerRequest,yield this.getMetadata({}))}catch(re){throw new Error(`Was not able to create peer: ${JSON.stringify(re)}`)}}))(),K=W==null?void 0:W.getPeer();if(!K)throw new Error("Response did not provide peer.");return this.localPeer=K})}createReceiveSignalStream(){return Le(this,void 0,void 0,function*(){if(this.config.lanOnlyMode)throw new Error("createReceiveSignalStream method cannot be used in local-only mode.");const{signalingClient:x}=this.config,{localPeer:W,iceServers:K}=this;if(!W||!K)return;const{receiveSignalStream:re}=this;re&&re.cancel();const oe=new Q.ReceiveSignalStreamRequest;oe.setPeerId(W.getPeerId());const he=yield(()=>Le(this,void 0,void 0,function*(){try{return x.receiveSignalStream(oe,yield this.getMetadata({hasDeadline:!1}))}catch(me){throw new Error(`Unable to create receive signal stream: ${JSON.stringify(me)}`)}}))();if(!he)throw new Error("Response did not provide stream.");return he.on("data",me=>Le(this,void 0,void 0,function*(){var pe,ue,le,Re;const Ie=me.getSignal(),ke=(pe=Ie==null?void 0:Ie.getSessionId())===null||pe===void 0?void 0:pe.getValue(),Ve=Ie==null?void 0:Ie.getSenderId(),Qe=Ie==null?void 0:Ie.getReceiverId(),Ye=(ue=Ie==null?void 0:Ie.getSessionCreatedTimestamp())===null||ue===void 0?void 0:ue.getValue();if(!(Ie&&ke&&Ve&&Qe&&Ye))return void g.a.warn("Received signal with missing information.");const Ge=this.getActiveConnection(Ve);if(Ge)if(Ge.getSessionId()!==ke){if(g.a.debug("Received signal: different session for a peer we're already connected to."),(Ge.getSessionCreatedTimestamp()||0)>Ye)return;const je=new et(yield this.createRTCPeerConnection(K),{baseConfig:{isOffer:!1,isLan:!1,receive:(Be,$e)=>this.config.receive(Be,$e),onStreamsInfoUpdate:this.config.onStreamsInfoUpdate?(Be,$e)=>{var Ze,Ke;return(Ke=(Ze=this.config).onStreamsInfoUpdate)===null||Ke===void 0?void 0:Ke.call(Ze,Be,$e)}:void 0,track:this.config.lanOnlyMode?void 0:this.config.track,localPeerId:W.getPeerId(),localUserId:(Re=W.getUserId())===null||Re===void 0?void 0:Re.getValue(),remotePeerId:Ve},remoteConfig:{sessionId:ke,sessionCreatedTimestamp:Ye}},Be=>this.onCustomDataChannel(Ve,Be));yield je.handleSignal(Ie),this.connections.push(je)}else g.a.debug("Received signal: for an existing connection."),yield Ge.handleSignal(Ie);else{g.a.debug("Received signal: new connection.");const je=new et(yield this.createRTCPeerConnection(K),{baseConfig:{isOffer:!1,isLan:!1,receive:(Be,$e)=>this.config.receive(Be,$e),onStreamsInfoUpdate:this.config.onStreamsInfoUpdate?(Be,$e)=>{var Ze,Ke;return(Ke=(Ze=this.config).onStreamsInfoUpdate)===null||Ke===void 0?void 0:Ke.call(Ze,Be,$e)}:void 0,track:this.config.lanOnlyMode?void 0:this.config.track,localPeerId:W.getPeerId(),localUserId:(le=W.getUserId())===null||le===void 0?void 0:le.getValue(),remotePeerId:Ve},remoteConfig:{sessionId:ke,sessionCreatedTimestamp:Ye}},Be=>this.onCustomDataChannel(Ve,Be));yield je.handleSignal(Ie),this.connections.push(je)}})),he.on("end",()=>{he.cancel(),this.receiveSignalStream=void 0}),he.on("error",me=>{switch(me.code){case te.StatusCode.CANCELLED:case te.StatusCode.UNAVAILABLE:case te.StatusCode.UNKNOWN:g.a.debug("Receive signal stream error",{error:me});break;case te.StatusCode.UNAUTHENTICATED:g.a.warn("Receive signal stream error",{error:me});break;default:g.a.error("Receive signal stream error",{error:me})}he.cancel(),this.receiveSignalStream=void 0}),this.receiveSignalStream=he})}createRTCPeerConnection(x){var W;return Le(this,void 0,void 0,function*(){const K=(W=this.config.alternateRTCPeerConnection)!==null&&W!==void 0?W:window.RTCPeerConnection;if(!K)throw function(){const{userAgent:re}=navigator;return re.includes("Firefox/")?"Firefox":re.includes("Edg/")?"Edge":re.includes("Chrome/")?"Chrome":re.includes("Safari/")?"Safari":re.includes("MSIE/")||re.includes("Trident/")?"IE":"Other"}()!=="Chrome"?new Error("WebRTC is not enabled. Please try again with the latest version of Google Chrome."):new Error("WebRTC is not enabled. Please ensure WebRTC is not disabled by ad blocking software.");return new K({iceServers:x})})}closeConnections(x){return Le(this,void 0,void 0,function*(){const W=yield w(x.map(K=>Le(this,void 0,void 0,function*(){yield K.close()})));for(const K of W)g.a.warn("Request to close session failed",{error:K})})}getActiveConnection(x){return this.getConnections().find(W=>W.getRemotePeerId()===x&&W.isActive())}update(){var x;return Le(this,void 0,void 0,function*(){if(this.localConnections=this.localConnections.filter(me=>me.isActive()),this.config.lanOnlyMode)return;const{signalingClient:W}=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(me=>!me.isActive())),this.connections=this.connections.filter(me=>me.isActive());const{localPeer:K}=this,re=this.connections.filter(me=>me.getSessionId).map(me=>h(me.getSessionId()));K.setSessionIdsList(re);const oe=new Q.RefreshPeerRequest;oe.setPeer(K);try{yield W.refreshPeer(oe,yield this.getMetadata({}))}catch(me){me.code===te.StatusCode.NOT_FOUND?(g.a.warn("Peer expired, creating new peer",{peerId:K.getPeerId()}),yield this.reset()):g.a.warn("Error calling RefreshPeer",{error:me})}const he=yield this.getPeers();for(const me of this.connections)me.setRemoteDeviceId((x=he.find(pe=>pe.id===me.getRemotePeerId()))===null||x===void 0?void 0:x.deviceId)})}reset(){return Le(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 Le(this,void 0,void 0,function*(){if(this.config.lanOnlyMode)return;const{iceServersLastUpdate:x,iceServersTtl:W}=this,K=new Date().getTime();if(!x||K-x>W)try{const re=(yield this.config.signalingClient.getIceServers(new Q.GetIceServersRequest,yield this.getMetadata({}))).getIceServers();this.iceServers=JSON.parse(re),this.iceServersLastUpdate=K}catch(re){g.a.warn("Error in updateIceServers",{error:re})}})}setupHandlers(x){const{peerConnection:W}=x,K=x.getSessionCreatedTimestamp();W.onconnectionstatechange=()=>Le(this,void 0,void 0,function*(){const re=W.connectionState;if(K)switch(re){case"connected":d.aggregate("rtc-connect-time",new Date().getTime()-K);break;case"failed":d.increment("rtc-connect-failed")}})}getMetadata(x){return Le(this,void 0,void 0,function*(){if(this.config.lanOnlyMode)throw new Error("getMetadata method cannot be called in local-only mode");const{getToken:W}=this.config,{grpcCallDeadline:K}=this,{hasDeadline:re}=x,oe=re===!1?void 0:new Date().getTime()+K;return{authorization:yield W(),deadline:oe}})}}var ft=n(10),ut=n(11),Ot=function(ye,x,W,K){return new(W||(W=Promise))(function(re,oe){function he(ue){try{pe(K.next(ue))}catch(le){oe(le)}}function me(ue){try{pe(K.throw(ue))}catch(le){oe(le)}}function pe(ue){var le;ue.done?re(ue.value):(le=ue.value,le instanceof W?le:new W(function(Re){Re(le)})).then(he,me)}pe((K=K.apply(ye,x||[])).next())})};class Ct{constructor(x,W){this.sessionId=x,this.connection=W,this.sentMessagesCounts=new Map,this.receivedMessagesCounts=new Map,this.sessionId=x,this.connection=W}incrementMessageSent(x){const W=Oe(x.header.stream);this.sentMessagesCounts.set(W,(this.sentMessagesCounts.get(W)||0)+1)}incrementMessageReceived(x){const W=Oe(x.header.stream);this.receivedMessagesCounts.set(W,(this.receivedMessagesCounts.get(W)||0)+1)}uploadMetrics(){return Ot(this,void 0,void 0,function*(){const{sessionId:x}=this,W=yield this.connection.peerConnection.getStats(),K={};W.forEach(oe=>K[oe.id]=oe),g.a.debug("rtc-stats",Object.assign(Object.assign({},K),{sessionId:x}));const re=[...new Set(Array.from(this.sentMessagesCounts.keys()).concat(Array.from(this.receivedMessagesCounts.keys())))].reduce((oe,he)=>{const me=this.sentMessagesCounts.get(he),pe=this.receivedMessagesCounts.get(he);return Object.assign(Object.assign({},oe),{[`${he}-sent`]:me,[`${he}-received`]:pe})},{sessionId:x});g.a.debug("rtc-message-report",re)})}}function ct(ye,x){return Oe(ye)===Oe(x)}var tt=function(ye,x,W,K){return new(W||(W=Promise))(function(re,oe){function he(ue){try{pe(K.next(ue))}catch(le){oe(le)}}function me(ue){try{pe(K.throw(ue))}catch(le){oe(le)}}function pe(ue){var le;ue.done?re(ue.value):(le=ue.value,le instanceof W?le:new W(function(Re){Re(le)})).then(he,me)}pe((K=K.apply(ye,x||[])).next())})};class It{constructor(x,W){this.peerConnection=x,this.config=W,this.connectTimeoutMs=10*c.a.second,this.gatherIceTimeoutMs=5*c.a.second,this.pingUpdateTimeoutMs=2*c.a.second,this.streamLatestTimestamp=new Map,this.closeCalled=!1,this.connectCalled=!1,this.sentOffer=!1,this.receivedIceCandidate=!1;const{isOffer:K}=W;K?this.initializeChannels(x):x.ondatachannel=re=>{switch(re.channel.label){case"stream.latest-ttl":this.latestTtlStreamChannel=re.channel;break;case"stream.reliable":this.reliableStreamChannel=re.channel;break;case"stream.latest-reliable":this.latestReliableStreamChannel=re.channel;break;case"stream.latest-try-once":this.latestTryOnceStreamChannel=re.channel}this.setupChannel(re.channel)},this.sessionMetrics=new Ct(this.getSessionId(),this)}connect(){return tt(this,void 0,void 0,function*(){if(this.connectCalled)return;this.connectCalled=!0,this.pingUpdateTimeout=setInterval(()=>{const{reliableStreamChannel:re}=this;re&&this.sendSystemMessage(re,{type:"ping"})},this.pingUpdateTimeoutMs),this.connectTimeout=setTimeout(()=>tt(this,void 0,void 0,function*(){this.isReady()||(g.a.warn("RTC connect timed out, closing connection"),yield this.close())}),this.connectTimeoutMs);const{peerConnection:x,config:{isOffer:W,sessionId:K}}=this;if(W){const re=yield x.createOffer();yield x.setLocalDescription(re)}W&&(this.gatherIceTimeout=setTimeout(()=>tt(this,void 0,void 0,function*(){this.sentOffer||(g.a.warn("ICE gathering timed out"),this.receivedIceCandidate?(g.a.warn("Attempting to connect with partial ICE candidate pool"),yield this.sendOffer()):yield this.close())}),this.gatherIceTimeoutMs),x.onicecandidate=re=>tt(this,void 0,void 0,function*(){re.candidate?this.receivedIceCandidate=!0:yield this.sendOffer()}),x.onicegatheringstatechange=()=>tt(this,void 0,void 0,function*(){x.iceGatheringState==="complete"&&(yield this.sendOffer())}),x.onnegotiationneeded=()=>{g.a.debug("Negotiation needed",{sessionId:K})})})}handleSignal(x){return tt(this,void 0,void 0,function*(){const{peerConnection:W,config:{sessionId:K,sendSignal:re}}=this,{description:oe}=JSON.parse(x.payload);if(g.a.debug("Handling signal",{sessionId:K,description:JSON.stringify(oe)}),oe)if(W.signalingState!=="stable"||W.connectionState!=="connected")if(W.remoteDescription)g.a.warn(`Received SDP signal during negotiation when remote description is already set: ${JSON.stringify(x)}`);else if(oe.type==="offer"){yield W.setRemoteDescription(oe);const he=yield W.createAnswer();yield W.setLocalDescription(he),yield re({payload:JSON.stringify({description:he})})}else oe.type==="answer"&&(yield W.setRemoteDescription(oe));else g.a.warn(`Received SDP signal when signaling is stable and connected: ${JSON.stringify(x)}`);else g.a.warn(`Received non-SDP signal: ${JSON.stringify(x)}`)})}send(x,W){const K=this.getChannelFromLabel(W.channelLabel);K?this.sendOnChannel(K,x):g.a.warn("Send called with unexpected channel label",{channelLabel:W.channelLabel})}controlRemoteStream(x){this.sendSystemMessage(h(this.reliableStreamChannel),{type:"stream-control",streamControl:x})}isActive(){return new Set(["new","connecting","connected"]).has(this.peerConnection.connectionState)}isReady(){const{peerConnection:x,latestTtlStreamChannel:W,reliableStreamChannel:K,latestTryOnceStreamChannel:re}=this;return!!(K&&W&&re)&&x.connectionState==="connected"&&K.readyState==="open"&&W.readyState==="open"&&re.readyState==="open"}isClosed(){const{peerConnection:x,reliableStreamChannel:W,latestTryOnceStreamChannel:K,latestTtlStreamChannel:re}=this;return!(x.connectionState!=="closed"||W!==void 0&&W.readyState!=="closed"||K!==void 0&&K.readyState!=="closed"||re!==void 0&&re.readyState!=="closed")}needsClosing(){const{peerConnection:x,latestTtlStreamChannel:W,reliableStreamChannel:K,latestTryOnceStreamChannel:re}=this;if(this.isClosed())return!1;const oe=new Set(["closing","closed"]),he=me=>me&&oe.has(me.readyState);return Te(x)||he(W)||he(K)||he(re)}close(){return tt(this,void 0,void 0,function*(){this.closeCalled||(this.closeCalled=!0,yield this.sessionMetrics.uploadMetrics(),this.pingUpdateTimeout&&clearInterval(this.pingUpdateTimeout),this.connectTimeout&&clearTimeout(this.connectTimeout),this.gatherIceTimeout&&clearTimeout(this.gatherIceTimeout),this.peerConnection.close())})}getPing(){return this.pingTimeMs}getLastMessageTimestamp(){return this.lastMessageTimestamp}getSessionId(){return this.config.sessionId}getRemotePeer(){return this.config.remotePeer}initializeChannels(x){this.latestTtlStreamChannel=x.createDataChannel("stream.latest-ttl",v),this.reliableStreamChannel=x.createDataChannel("stream.reliable",S),this.latestReliableStreamChannel=x.createDataChannel("stream.latest-reliable",U),this.latestTryOnceStreamChannel=x.createDataChannel("stream.latest-try-once",J),this.setupChannel(this.latestTtlStreamChannel),this.setupChannel(this.reliableStreamChannel),this.setupChannel(this.latestReliableStreamChannel),this.setupChannel(this.latestTryOnceStreamChannel)}sendOffer(){return tt(this,void 0,void 0,function*(){if(this.sentOffer||(this.sentOffer=!0,Te(this.peerConnection)))return;const{peerConnection:x,config:{sendSignal:W}}=this,K=yield x.createOffer();yield x.setLocalDescription(K);const re={payload:JSON.stringify({description:K})};yield W(re)})}getChannelFromLabel(x){switch(x){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(x,W){let K;try{K=Object(H.encode)(JSON.stringify(W))}catch(re){return void g.a.warn("Failed to encode RTC message",{error:re})}try{x.send(K),this.sessionMetrics.incrementMessageSent(W)}catch(re){g.a.warn("Failed to send message to channel",{error:re,channel:x.label})}}channelNotRecognized(x){return x!==this.latestTtlStreamChannel&&x!==this.latestReliableStreamChannel&&x!==this.latestTryOnceStreamChannel&&x!==this.reliableStreamChannel}setupChannel(x){x.onmessage=W=>{if(this.channelNotRecognized(x))return void g.a.warn("Received message on unrecognized data channel.");let K;try{K=JSON.parse(Object(H.decode)(W.data))}catch(re){return void g.a.warn("Received unparseable RTC message",{error:re,channel:x.label})}if(this.lastMessageTimestamp=new Date().getTime(),K=De(K),this.sessionMetrics.incrementMessageReceived(K),!this.handleSystemMessage(x,K)){if(!this.hasCapabilities(K))return void g.a.warn("Received RTC message that was not within the capability scope of the connection.");(x===this.latestTryOnceStreamChannel||x===this.latestTtlStreamChannel||x===this.latestReliableStreamChannel)&&!this.isLatestMessage(K)||this.config.receive(this.config.remotePeer.id,K)}},x.onerror=W=>{g.a.warn(`Channel error: ${W.error}`,{error:W.error,sessionId:this.getSessionId(),channelLabel:x.label})},x.onopen=()=>{g.a.debug("Channel opened",{sessionId:this.getSessionId(),channelLabel:x.label})},x.onclose=()=>{const W={bufferedAmount:x.bufferedAmount,sessionId:this.getSessionId(),channelLabel:x.label};this.closeCalled===!1?g.a.debug("Unexpected channel closed",W):g.a.debug("Channel closed",W)}}handleSystemMessage(x,W){switch(W.header.stream.streamType){case"ping":return this.sendSystemMessage(x,{type:"pong",timestamp:h(W.payload.ping)}),!0;case"pong":{const K=new Date().getTime()-h(W.payload.pong);return this.pingTimeMs=K,d.aggregate("rtc-ping-time",K),!0}case"stream-control":return!0;default:return!1}}sendSystemMessage(x,W){if(x.readyState!=="open")return;const K={entityId:h(this.config.localPeer.deviceId||this.config.localPeer.userId),streamName:`$.${W.type}`,streamType:W.type};let re;switch(W.type){case"ping":re={ping:new Date().getTime()};break;case"pong":re={pong:W.timestamp};break;case"stream-control":re={streamControl:W.streamControl}}this.sendOnChannel(x,Ee(K,re))}hasCapabilities(x){var W,K;const{localPeer:re,remotePeer:oe}=this.config,he=(W=re.capabilitySet.streaming)===null||W===void 0?void 0:W.streams,me=he&&he.some(le=>le.receive&&ct(le.stream,x.header.stream)),pe=(K=oe.capabilitySet.streaming)===null||K===void 0?void 0:K.streams,ue=pe&&pe.some(le=>le.send&&ct(le.stream,x.header.stream));return me||ue}isLatestMessage(x){const W=Oe(x.header.stream),K=(this.streamLatestTimestamp.get(W)||0)<=x.header.created;return K&&this.streamLatestTimestamp.set(W,x.header.created),K}}var Ue=function(ye,x,W,K){return new(W||(W=Promise))(function(re,oe){function he(ue){try{pe(K.next(ue))}catch(le){oe(le)}}function me(ue){try{pe(K.throw(ue))}catch(le){oe(le)}}function pe(ue){var le;ue.done?re(ue.value):(le=ue.value,le instanceof W?le:new W(function(Re){Re(le)})).then(he,me)}pe((K=K.apply(ye,x||[])).next())})};class jt{constructor(x){this.config=x,this.connections=[],this.connectingSessions=new Map,this.updateInterval=f({func:()=>Ue(this,void 0,void 0,function*(){try{yield this.update()}catch(W){g.a.warn("RTC update failed",{error:W})}}),delay:250*c.a.millisecond,immediate:!0}),this.localPeer=this.createPeer()}send(x,W,K){const re=this.getActiveConnection(x);re?re.isReady()?re.send(W,K):g.a.warn("Attempted to send with an active connection to that peer which was not yet ready."):g.a.warn("Attempted to send with no active connection to that peer.")}controlRemoteStream(x,W){const K=this.getActiveConnection(x);K?K.isReady()?K.controlRemoteStream(W):g.a.warn("Attempted to control remote stream with an active connection to that peer which was not yet ready."):g.a.warn("Attempted to control remote stream with no active connection to that peer.")}connect(x){return Ue(this,void 0,void 0,function*(){const W=yield this.getLocalPeer();if(this.getActiveConnection(x))return void g.a.warn("Attempted to connect to peer with an already active connection.");let K;try{K=yield this.config.signalingClient.createSession(yield this.config.getToken(),{offerPeerId:W.id,answerPeerId:x})}catch(re){Object(ft.a)(re,ut.a,oe=>oe.statusCode===404),g.a.warn("Attempted to connect to peer that does not exist.")}if(K)for(this.connectingSessions.set(K.id,new Date().getTime()),yield this.connectToSession(K);;)switch(yield Object(u.a)(.1),this.getConnectionStatus(x)){case"connecting":continue;case"connected":return K.id;case"disconnected":return}})}getConnectionStatus(x){const W=this.getActiveConnection(x);return W?W.isReady()?"connected":"connecting":"disconnected"}getIceMode(x){const W=this.getActiveConnection(x);if(W)return W.iceMode}disconnect(x){return Ue(this,void 0,void 0,function*(){const W=this.getActiveConnection(x);W&&(yield this.closeConnection(W))})}getLocalPeer(){return Ue(this,void 0,void 0,function*(){return yield this.localPeer})}getPeers(){return Ue(this,void 0,void 0,function*(){return yield this.config.signalingClient.getPeers(yield this.config.getToken())})}getPing(x){const W=this.getActiveConnection(x);if(W)return W.getPing();g.a.warn("Attempted to get ping time from inactive peer.")}getLastMessageTimestamp(x){const W=this.getActiveConnection(x);if(W)return W.getLastMessageTimestamp();g.a.warn("Attempted to get ping time from inactive peer.")}shutdown(){return Ue(this,void 0,void 0,function*(){yield this.updateInterval.stop();const x=this.connections;this.connections=[],yield this.closeConnections(x)})}closeConnection(x){return Ue(this,void 0,void 0,function*(){this.connectingSessions.delete(x.getSessionId()),yield x.close();try{yield this.config.signalingClient.deleteSession(yield this.config.getToken(),x.getSessionId())}catch(W){Object(ft.a)(W,ut.a,K=>K.statusCode===404)}})}getSessions(){return Ue(this,void 0,void 0,function*(){const x=yield this.getLocalPeer();return(yield this.config.signalingClient.getSessions(yield this.config.getToken())).filter(W=>W.offer.peer.id===x.id||W.answer.peer.id===x.id)})}createPeer(){return Ue(this,void 0,void 0,function*(){return yield this.config.signalingClient.createPeer(yield this.config.getToken(),{capabilitySet:this.config.capabilitySet||{}})})}createRTCPeerConnection(x={}){return Ue(this,void 0,void 0,function*(){return new(this.config.alternateRTCPeerConnection||RTCPeerConnection)(Object.assign({iceServers:yield this.config.signalingClient.getIceServers(yield this.config.getToken())},x))})}closeConnections(x){return Ue(this,void 0,void 0,function*(){const W=yield w(x.map(K=>Ue(this,void 0,void 0,function*(){yield this.closeConnection(K)})));for(const K of W)g.a.warn("Request to close session failed",{error:K})})}reset(){return Ue(this,void 0,void 0,function*(){yield this.closeConnections(this.connections),this.connections=[],this.connectingSessions=new Map,this.localPeer=this.createPeer(),yield this.localPeer})}getActiveConnection(x){return this.connections.find(W=>W.getRemotePeer().id===x&&W.isActive())}update(){return Ue(this,void 0,void 0,function*(){const x=yield this.getLocalPeer();try{yield this.config.signalingClient.refreshPeer(yield this.config.getToken(),x.id)}catch(W){Object(ft.a)(W,ut.a,K=>K.statusCode===404),g.a.warn("Peer expired, creating new peer",{peerId:x.id}),yield this.reset()}yield this.handleSessions(yield this.getSessions())})}handleSessions(x){return Ue(this,void 0,void 0,function*(){yield this.syncConnectionsAndSessions(x);const W=x.map(K=>({session:K,connection:this.connections.find(re=>re.getSessionId()===K.id)}));yield Promise.all(W.map(({session:K,connection:re})=>Ue(this,void 0,void 0,function*(){return yield this.maintainConnection(K,re)})))})}syncConnectionsAndSessions(x){return Ue(this,void 0,void 0,function*(){const W=new Set(x.map(oe=>oe.id)),K=oe=>W.has(oe.getSessionId())||this.connectingSessions.has(oe.getSessionId());this.connections=this.connections.filter(oe=>K(oe));const re=this.connections.filter(oe=>!K(oe)||oe.needsClosing());yield Promise.all(re.map(oe=>Ue(this,void 0,void 0,function*(){yield this.closeConnection(oe)})))})}maintainConnection(x,W){return Ue(this,void 0,void 0,function*(){const K=yield this.getLocalPeer(),re=x.offer.peer.id===K.id;if(W){if(W.isReady())try{yield this.config.signalingClient.refreshSession(yield this.config.getToken(),x.id)}catch(oe){Object(ft.a)(oe,ut.a,he=>he.statusCode===404),g.a.debug("Refresh session not found",{sessionId:x.id})}else if(W.isActive())try{yield this.consumeSignals(W)}catch(oe){g.a.warn("Failed to ingest signals, closing connection",{error:oe}),yield this.closeConnection(W)}}else{if(re)return;yield this.connectToSession(x)}})}connectToSession(x){return Ue(this,void 0,void 0,function*(){const W=yield this.getLocalPeer(),K=x.offer.peer.id===W.id,re=yield this.createRTCPeerConnection(),oe=new It(re,{localPeer:K?x.offer.peer:x.answer.peer,remotePeer:K?x.answer.peer:x.offer.peer,sessionId:x.id,isOffer:K,sendSignal:he=>this.sendSignal(x.id,he),receive:(he,me)=>this.config.receive(he,me)});if(this.connections.find(he=>he.getSessionId()===x.id))return g.a.warn("connectToSession called on a session that already has a connection.",{sessionId:x.id}),void(yield oe.close());this.setupHandlers(oe),this.connections.push(oe);try{yield oe.connect()}catch(he){g.a.warn("Failed to handle negotiation, closing connection",{error:he}),yield this.closeConnection(oe)}})}setupHandlers(x){const{peerConnection:W}=x,K=x.getSessionId();W.onconnectionstatechange=()=>Ue(this,void 0,void 0,function*(){const re=this.connectingSessions.get(K);if(re===void 0)return;const oe=W.connectionState;switch(Te(W)&&this.connectingSessions.delete(K),oe){case"connected":{this.connectingSessions.delete(K);const he=new Date().getTime()-re;d.aggregate("rtc-connect-time",he);break}case"failed":d.increment("rtc-connect-failed"),yield this.closeConnection(x)}})}consumeSignals(x){return Ue(this,void 0,void 0,function*(){let W=[];try{W=yield this.config.signalingClient.takeSignals(yield this.config.getToken(),x.getSessionId())}catch(K){Object(ft.a)(K,ut.a,re=>re.statusCode===404)}for(const K of W)yield x.handleSignal(K)})}sendSignal(x,W){return Ue(this,void 0,void 0,function*(){try{yield this.config.signalingClient.addSignals(yield this.config.getToken(),x,{signals:[W]})}catch(K){Object(ft.a)(K,ut.a,re=>re.statusCode===404)}})}}},function(e,t,n){var r={randomUUID:typeof crypto!="undefined"&&crypto.randomUUID&&crypto.randomUUID.bind(crypto)};let o;const l=new Uint8Array(16);function s(){if(!o&&(o=typeof crypto!="undefined"&&crypto.getRandomValues&&crypto.getRandomValues.bind(crypto),!o))throw new Error("crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported");return o(l)}const i=[];for(let u=0;u<256;++u)i.push((u+256).toString(16).slice(1));function c(u,m=0){return(i[u[m+0]]+i[u[m+1]]+i[u[m+2]]+i[u[m+3]]+"-"+i[u[m+4]]+i[u[m+5]]+"-"+i[u[m+6]]+i[u[m+7]]+"-"+i[u[m+8]]+i[u[m+9]]+"-"+i[u[m+10]]+i[u[m+11]]+i[u[m+12]]+i[u[m+13]]+i[u[m+14]]+i[u[m+15]]).toLowerCase()}t.a=function(u,m,R){if(r.randomUUID&&!m&&!u)return r.randomUUID();const E=(u=u||{}).random||(u.rng||s)();if(E[6]=15&E[6]|64,E[8]=63&E[8]|128,m){R=R||0;for(let y=0;y<16;++y)m[R+y]=E[y];return m}return c(E)}},,function(e,t,n){n.r(t),n.d(t,"LogClient",function(){return i});var r=n(28),o=n(10),l=n(11),s=function(c,u,m,R){return new(m||(m=Promise))(function(E,y){function g(L){try{T(R.next(L))}catch(z){y(z)}}function _(L){try{T(R.throw(L))}catch(z){y(z)}}function T(L){var z;L.done?E(L.value):(z=L.value,z instanceof m?z:new m(function(M){M(z)})).then(g,_)}T((R=R.apply(c,u||[])).next())})};class i extends r.a{log(u){return s(this,void 0,void 0,function*(){const m=i.token;try{yield this.fetch("logs",{token:m,method:"POST",body:JSON.stringify({logs:u}),allowUnsafeRetries:!0})}catch(R){Object(o.a)(R,l.a,E=>E.statusCode===401&&m!==void 0),i.token===m&&delete i.token,yield this.log(u)}})}}}])})})(dist);function defined(e,t){if(e!==void 0)return e;throw new Error(t||"Value is undefined")}let FORMANT_API_URL="https://api.formant.io";typeof window!="undefined"&&(FORMANT_API_URL=window.FORMANT_API_URL||FORMANT_API_URL);let urlParams$2=new URLSearchParams("");typeof window!="undefined"&&(urlParams$2=new URLSearchParams(window.location.search));const envDev=urlParams$2.get("formant_dev");envDev&&(FORMANT_API_URL="https://api-dev.formant.io");const envStage=urlParams$2.get("formant_stage");envStage&&(FORMANT_API_URL="https://api-stage.formant.io");const envLocal=urlParams$2.get("formant_local");envLocal&&(FORMANT_API_URL="https://api.formant.local");function delay(e){return new Promise(t=>setTimeout(t,e))}class DataChannel{constructor(t){Ae(this,"ready",!1);Ae(this,"listeners",[]);Ae(this,"openListeners",[]);Ae(this,"closeListeners",[]);Ae(this,"errorListeners",[]);Ae(this,"binaryListeners",[]);Ae(this,"error");Ae(this,"decoder",new TextDecoder);this.dataChannel=t,this.dataChannel.binaryType="arraybuffer",this.dataChannel.onopen=()=>{this.ready=!0,this.openListeners.forEach(n=>n())},this.dataChannel.onclose=()=>{this.ready=!1,this.closeListeners.forEach(n=>n())},this.dataChannel.onerror=n=>{console.error(n),this.error="An error occurred in DataChannel",this.errorListeners.forEach(r=>r(n))},this.dataChannel.onmessage=n=>{this.listeners.forEach(r=>{const o=new Uint8Array(n.data),l=this.decoder.decode(o);r(l)}),this.binaryListeners.forEach(r=>{r(new Uint8Array(n.data))})}}addOpenListener(t){this.openListeners.push(t)}removeOpenListener(t){this.openListeners=this.openListeners.filter(n=>n!==t)}addCloseListener(t){this.closeListeners.push(t)}removeCloseListener(t){this.closeListeners=this.closeListeners.filter(n=>n!==t)}addErrorListener(t){this.errorListeners.push(t)}removeErrorListener(t){this.errorListeners=this.errorListeners.filter(n=>n!==t)}async waitTilReady(){return this.ready?!0:new Promise((n,r)=>{let o=window.setInterval(()=>{this.ready&&(window.clearInterval(o),n(!0)),this.error&&r(this.error)},10)})}send(t){if(!this.ready)throw new Error("Connection has been closed");this.dataChannel.send(t)}sendBinary(t){if(!this.ready)throw new Error("Connection has been closed");this.dataChannel.send(t)}addListener(t){this.listeners.push(t)}removeListener(t){const n=this.listeners.indexOf(t);if(n===-1)throw new Error("Could not find data channel listener to remove");if(this.error)throw new Error(this.error);this.listeners.splice(n,1)}addBinaryListener(t){this.binaryListeners.push(t)}removeBinaryListener(t){const n=this.binaryListeners.indexOf(t);if(n===-1)throw new Error("Could not find data channel listener to remove");if(this.error)throw new Error(this.error);this.binaryListeners.splice(n,1)}}class CaptureStream{constructor(t){Ae(this,"token");this.captureSession=t}async ingestJSON(t){if(!this.token){const r=await(await fetch(`${FORMANT_API_URL}/v1/admin/capture-sessions/${this.captureSession.code}/authenticate`,{method:"POST"})).json();this.token=r.token}await fetch(`${FORMANT_API_URL}/v1/ingest`,{method:"POST",body:JSON.stringify({deviceId:this.captureSession.deviceId,name:this.captureSession.streamName,type:"json",points:[[Date.now(),JSON.stringify(t)]]}),headers:{"Content-Type":"application/json",Authorization:"Bearer "+this.token}})}}class Manipulator{constructor(t,n){Ae(this,"currentListeners",[]);Ae(this,"onRealtimeMessage",(t,n)=>{n.payload.jointState&&this.currentListeners.forEach(r=>{n.payload.jointState&&r(n.payload.jointState)})});this.device=t,this.config=n}async synchronize(){this.device.addRealtimeListener(this.onRealtimeMessage),this.device.startListeningToRealtimeDataStream(this.config.currentJointStateStream)}async desynchronize(){this.device.removeRealtimeListener(this.onRealtimeMessage),this.device.stopListeningToRealtimeDataStream(this.config.currentJointStateStream)}async addCurrentJointStateListener(t){this.currentListeners.push(t)}}class RequestDataChannel{constructor(t,n,r){Ae(this,"channel");Ae(this,"requestIdToResponseMap",new Map);this.device=t,this.channel_name=n,this.timeout=r}addOpenListener(t){defined(this.channel,"channel not initalized").addOpenListener(t)}removeOpenListener(t){defined(this.channel,"channel not initalized").removeOpenListener(t)}addCloseListener(t){defined(this.channel,"channel not initalized").addCloseListener(t)}removeCloseListener(t){defined(this.channel,"channel not initalized").removeCloseListener(t)}addErrorListener(t){defined(this.channel,"channel not initalized").addErrorListener(t)}removeErrorListener(t){defined(this.channel,"channel not initalized").removeErrorListener(t)}}class BinaryRequestDataChannel extends RequestDataChannel{constructor(){super(...arguments);Ae(this,"RESPONSE_SUCCESS_BYTE",0);Ae(this,"decoder",new TextDecoder)}generateBinaryId(){const n=new Uint8Array(16);for(let r=0;r<n.length;r++)n[r]=Math.floor(Math.random()*256);return n}async initialize(){this.channel=await this.device.createCustomDataChannel(this.channel_name),this.channel.addBinaryListener(n=>{const o=n.slice(0,16).toString();if(o.length===0)throw new Error("Invalid response");const l=n.slice(16);if(l.length===0)throw new Error("Invalid response");this.requestIdToResponseMap.has(o)&&this.requestIdToResponseMap.set(o,l)})}async request(n){if(this.channel||await this.initialize(),!this.channel)throw new Error("Failed to create channel");const{channel:r,requestIdToResponseMap:o,timeout:l}=this;await r.waitTilReady();const s=this.generateBinaryId(),i=s.toString();o.set(i,!0),r.sendBinary(new Uint8Array([...s,...n]));const c=new Date().getTime();for(;new Date().getTime()<c+l;)if(await delay(50),o.has(i)){const u=o.get(i);if(u!==!0){o.delete(i);const m=u[0]===this.RESPONSE_SUCCESS_BYTE,R=u.slice(1);if(m)return R;throw console.error({name:"AdapterError",message:this.decoder.decode(R)}),new Error("Binary request datachannel adapter error")}}throw o.delete(i),console.error({name:"TimeoutError",message:`Request timed out after ${l/1e3} seconds`}),new Error("Binary request data channel request timed out")}}class TextRequestDataChannel extends RequestDataChannel{generateTextId(){return Math.random().toString(36).substring(2)+"-"+Math.random().toString(36).substring(2)}async initialize(){this.channel=await this.device.createCustomDataChannel(this.channel_name),this.channel.addListener(t=>{const n=JSON.parse(t),{id:r,data:o,error:l}=n;if(!r)throw new Error("Invalid response");if(!o&&!l)throw new Error("Invalid response");this.requestIdToResponseMap.has(r)&&this.requestIdToResponseMap.set(r,n)})}async request(t){if(this.channel||await this.initialize(),!this.channel)throw new Error("Failed to create channel");const{channel:n,requestIdToResponseMap:r,timeout:o}=this;await n.waitTilReady();const l=this.generateTextId();r.set(l,!0),n.send(JSON.stringify({id:l,data:t}));const s=new Date().getTime();for(;new Date().getTime()<s+o;)if(await delay(50),r.has(l)){const i=r.get(l);if(i!==!0){r.delete(l);const{data:c,error:u}=i;if(c)return c;if(u)throw console.error({name:"AdapterError",message:u}),new Error("Text request datachannel adapter error")}}throw r.delete(l),console.error({name:"TimeoutError",message:`Request timed out after ${o/1e3} seconds`}),new Error("Text request datachannel request timed out")}}const urlParams$1=new URLSearchParams(window.location.search),rtcClientVersion=urlParams$1.get("rtc_client"),SessionType={Teleop:1,Observe:3};class Device{constructor(t,n,r){Ae(this,"rtcClient");Ae(this,"remoteDevicePeerId");Ae(this,"realtimeListeners",[]);Ae(this,"handleMessage",(t,n)=>{this.realtimeListeners.forEach(r=>r(t,n))});this.id=t,this.name=n,this.organizationId=r}async getLatestTelemetry(){return(await(await fetch(`${FORMANT_API_URL}/v1/queries/stream-current-value`,{method:"POST",body:JSON.stringify({deviceIds:[this.id]}),headers:{"Content-Type":"application/json",Authorization:"Bearer "+Authentication.token}})).json()).items}async getConfiguration(){let t=await fetch(`${FORMANT_API_URL}/v1/admin/devices/${this.id}`,{method:"GET",headers:{"Content-Type":"application/json",Authorization:"Bearer "+Authentication.token}});const n=await t.json();if(!n.state.reportedConfiguration)throw new Error("Device has no configuration, has it ever been turned on?");const r=n.state.reportedConfiguration.version;return t=await fetch(`${FORMANT_API_URL}/v1/admin/devices/${this.id}/configurations/${r}`,{method:"GET",headers:{"Content-Type":"application/json",Authorization:"Bearer "+Authentication.token}}),(await t.json()).document}async getFileUrl(t){return(await(await fetch(`${FORMANT_API_URL}/v1/admin/files/query`,{method:"POST",body:JSON.stringify({fileIds:[t]}),headers:{"Content-Type":"application/json",Authorization:"Bearer "+Authentication.token}})).json()).fileUrls}getRealtimeStatus(){if(this.rtcClient&&this.remoteDevicePeerId)return this.rtcClient.getConnectionStatus(this.remoteDevicePeerId);throw new Error(`Realtime connection hasn't been started for ${this.id}`)}getRealtimePing(){if(this.rtcClient&&this.remoteDevicePeerId)return this.rtcClient.getPing(this.remoteDevicePeerId);throw new Error(`Realtime connection hasn't been started for ${this.id}`)}async startRealtimeConnection(t){if(this.rtcClient)throw new Error(`Already created realtime connection to device ${this.id}`);{let n;if(rtcClientVersion==="1"?n=new dist.exports.RtcClientV1({signalingClient:new dist.exports.RtcSignalingClient(FORMANT_API_URL+"/v1/signaling"),getToken:async()=>defined(Authentication.token,"Realtime when user isn't authorized"),receive:this.handleMessage}):n=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,sessionType:t}),n.isReady)for(;!n.isReady();)await delay(100);const o=(await n.getPeers()).find(l=>l.deviceId===this.id);if(!o)throw new Error("Cannot find peer, is the robot offline?");for(this.remoteDevicePeerId=o.id,await n.connect(this.remoteDevicePeerId);n.getConnectionStatus(this.remoteDevicePeerId)!=="connected";)await delay(100);this.rtcClient=n}}async sendRealtimeMessage(t,n={channelLabel:"stream.reliable"}){const r=defined(this.rtcClient,"Realtime connection has not been started"),o=await this.getRemotePeer();r.send(defined(o).id,t,n)}addRealtimeListener(t){this.realtimeListeners.push(t)}removeRealtimeListener(t){const n=this.realtimeListeners.indexOf(t);if(n===-1)throw new Error("Could not find realtime listener to remove");this.realtimeListeners.splice(n,1)}async getRealtimeAudioStreams(){var r,o,l,s,i,c;const t=await this.getConfiguration(),n=[];for(const u of(o=(r=t.teleop)==null?void 0:r.hardwareStreams)!=null?o:[])u.rtcStreamType==="audio-chunk"&&n.push({name:u.name});for(const u of(s=(l=t.teleop)==null?void 0:l.rosStreams)!=null?s:[])u.topicType=="audio_common_msgs/AudioData"&&n.push({name:u.topicName});for(const u of(c=(i=t.teleop)==null?void 0:i.customStreams)!=null?c:[])u.rtcStreamType==="audio-chunk"&&n.push({name:u.name});return n}async getRealtimeVideoStreams(){var r,o,l,s,i,c;const t=await this.getConfiguration(),n=[];for(const u of(o=(r=t.teleop)==null?void 0:r.hardwareStreams)!=null?o:[])u.rtcStreamType==="h264-video-frame"&&n.push({name:u.name});for(const u of(s=(l=t.teleop)==null?void 0:l.rosStreams)!=null?s:[])u.topicType=="formant/H264VideoFrame"&&n.push({name:u.topicName});for(const u of(c=(i=t.teleop)==null?void 0:i.customStreams)!=null?c:[])u.rtcStreamType==="h264-video-frame"&&n.push({name:u.name});return n}async getRealtimeManipulators(){var r;const t=await this.getConfiguration(),n=[];for(const o of(r=t.teleop.rosStreams)!=null?r:[])o.topicType=="sensor_msgs/JointState"&&n.push(new Manipulator(this,{currentJointStateStream:{name:o.topicName},plannedJointStateStream:o.plannedTopic?{name:o.plannedTopic}:void 0,planValidStream:o.planValidTopic?{name:o.planValidTopic}:void 0,endEffectorStream:o.endEffectorTopic?{name:o.endEffectorTopic}:void 0,endEffectorLinkName:o.endEffectorLinkName,baseReferenceFrame:o.baseReferenceFrame,localFrame:o.localFrame}));return n}async startListeningToRealtimeVideo(t){const n=defined(this.rtcClient,"Realtime connection has not been started"),r=await this.getRemotePeer();n.controlRemoteStream(defined(r).id,{streamName:t.name,enable:!0,pipeline:"rtc"})}async stopListeningToRealtimeVideo(t){const n=defined(this.rtcClient,"Realtime connection has not been started"),r=await this.getRemotePeer();n.controlRemoteStream(defined(r).id,{streamName:t.name,enable:!1,pipeline:"rtc"})}async startListeningToRealtimeDataStream(t){const n=defined(this.rtcClient,"Realtime connection has not been started"),r=await this.getRemotePeer();n.controlRemoteStream(defined(r).id,{streamName:t.name,enable:!0,pipeline:"rtc"})}async stopListeningToRealtimeDataStream(t){const n=defined(this.rtcClient,"Realtime connection has not been started"),r=await this.getRemotePeer();n.controlRemoteStream(defined(r).id,{streamName:t.name,enable:!1,pipeline:"rtc"})}async enableRealtimeTelemetryPriorityIngestion(t){const n=defined(this.rtcClient,"Realtime connection has not been started"),r=await this.getRemotePeer();n.controlRemoteStream(defined(r).id,{streamName:t,enablePriorityUpload:!0,pipeline:"telemetry"})}async changeStreamAudioType(t,n){const r=defined(this.rtcClient,"Realtime connection has not been started"),o=await this.getRemotePeer();r.controlRemoteStream(defined(o).id,{streamName:t,setAudioFormat:n})}async disableRealtimeTelemetryPriorityIngestion(t){const n=defined(this.rtcClient,"Realtime connection has not been started"),r=await this.getRemotePeer();n.controlRemoteStream(defined(r).id,{streamName:t,enablePriorityUpload:!1,pipeline:"telemetry"})}async getRemotePeer(){const n=(await defined(this.rtcClient,"Realtime connection has not been started").getPeers()).find(r=>r.deviceId===this.id);return defined(n,"Could not find remote peer for device "+this.id)}async stopRealtimeConnection(){if(this.rtcClient)await this.rtcClient.disconnect(this.id);else throw new Error(`Realtime connection hasn't been started for ${this.id}`)}async isInRealtimeSession(){let t=await Fleet.getPeers(),n=await Fleet.getRealtimeSessions(),r=t.find(o=>o.deviceId===this.id);return r?n[r.id].length>0:!1}async getAvailableCommands(){return(await(await fetch(`${FORMANT_API_URL}/v1/admin/command-templates/`,{method:"GET",headers:{"Content-Type":"application/json",Authorization:"Bearer "+Authentication.token}})).json()).items.map(r=>({name:r.name,id:r.id,command:r.command,description:r.description,parameterEnabled:r.parameterEnabled,parameterValue:r.parameterValue,parameterMeta:r.parameterMeta,enabled:r.enabled}))}async sendCommand(t,n,r,o){var u;const s=(await this.getAvailableCommands()).find(m=>m.name===t);if(!s)throw new Error(`Could not find command with name "${t}"`);let i;if(n===void 0)if(s.parameterEnabled&&s.parameterValue)i=s.parameterValue;else throw new Error("Command has no default parameter value, you must provide one");else i=n;let c={value:i,scrubberTime:(r||new Date).toISOString(),meta:{...s.parameterMeta,...o}};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:c,userId:(u=Authentication.currentUser)==null?void 0:u.id}),headers:{"Content-Type":"application/json",Authorization:"Bearer "+Authentication.token}})}async createCustomDataChannel(t,n){if(rtcClientVersion==="1")throw new Error("createCustomDataChannel is not supported in rtcClientVersion 1");const r=defined(this.rtcClient,"Realtime connection has not been started"),o=await this.getRemotePeer(),l=await new Promise(s=>{r.createCustomDataChannel(defined(o).id,t,{ordered:!0,...n},!1,(i,c)=>{const u=new DataChannel(c);s(u)})});return await l.waitTilReady(),l}createCustomRequestDataChannel(t,n=3e3){return new TextRequestDataChannel(this,t,n)}createCustomBinaryRequestDataChannel(t,n=3e3){return new BinaryRequestDataChannel(this,t,n)}async createCaptureStream(t){const r=await(await fetch(`${FORMANT_API_URL}/v1/admin/capture-sessions`,{method:"POST",body:JSON.stringify({deviceId:this.id,streamName:t,tags:{}}),headers:{"Content-Type":"application/json",Authorization:"Bearer "+Authentication.token}})).json();return new CaptureStream(r)}async getTelemetry(t,n,r,o){return await Fleet.getTelemetry(this.id,t,n,r,o)}async getTelemetryStreams(){var i,c;const t=await this.getConfiguration(),n=await fetch(`${FORMANT_API_URL}/v1/queries/metadata/stream-names`,{method:"POST",body:JSON.stringify({deviceIds:[this.id]}),headers:{"Content-Type":"application/json",Authorization:"Bearer "+Authentication.token}}),r=[],o=[];return(c=(i=t.telemetry)==null?void 0:i.streams)==null||c.forEach(u=>{u.disabled!==!0&&r.push(u.name),u.onDemand===!0&&o.push(u.name)}),console.log(o),(await n.json()).items.filter(u=>!r.includes(u)).map(u=>({name:u,onDemand:o.includes(u)}))}async createInterventionRequest(t,n,r,o){return await(await fetch(`${FORMANT_API_URL}/v1/admin/intervention-requests`,{method:"POST",body:JSON.stringify({message:t,interventionType:n,time:new Date().toISOString(),deviceId:this.id,tags:o,data:r}),headers:{"Content-Type":"application/json",Authorization:"Bearer "+Authentication.token}})).json()}async addInterventionResponse(t,n,r){return await(await fetch(`${FORMANT_API_URL}/v1/admin/intervention-responses`,{method:"POST",body:JSON.stringify({interventionId:t,interventionType:n,data:r}),headers:{"Content-Type":"application/json",Authorization:"Bearer "+Authentication.token}})).json()}}class PeerDevice{constructor(t){Ae(this,"rtcClient");Ae(this,"remoteDevicePeerId");Ae(this,"realtimeListeners",[]);Ae(this,"id");Ae(this,"handleMessage",(t,n)=>{this.realtimeListeners.forEach(r=>r(t,n))});this.peerUrl=t}async getLatestTelemetry(){const n=await(await fetch(`${this.peerUrl}/telemetry`)).json();return Object.entries(n).map(([o,l])=>({deviceId:this.id,streamName:o,streamType:"json",currentValue:l,currentValueTime:l.timestamp,tags:{}}))}async getDeviceId(){return(await(await fetch(`${this.peerUrl}/configuration`)).json()).agent_config.id}async getConfiguration(){return(await(await fetch(`${this.peerUrl}/configuration`)).json()).agent_config.document}getRealtimeStatus(){if(this.rtcClient&&this.remoteDevicePeerId)return this.rtcClient.getConnectionStatus(this.remoteDevicePeerId);throw new Error("Realtime connection hasn't been started")}getRealtimePing(){if(this.rtcClient&&this.remoteDevicePeerId)return this.rtcClient.getPing(this.remoteDevicePeerId);throw new Error("Realtime connection hasn't been started")}async startRealtimeConnection(t){if(this.rtcClient)throw new Error(`Already created realtime connection to device ${this.id}`);{const n=new dist.exports.RtcClient({lanOnlyMode:!0,receive:this.handleMessage,sessionType:t});for(await n.connectLan(this.peerUrl);n.getConnectionStatus(this.peerUrl)!=="connected";)await delay(100);this.rtcClient=n}}addRealtimeListener(t){this.realtimeListeners.push(t)}removeRealtimeListener(t){const n=this.realtimeListeners.indexOf(t);if(n===-1)throw new Error("Could not find realtime listener to remove");this.realtimeListeners.splice(n,1)}async getRealtimeVideoStreams(){var r,o,l;const t=await this.getConfiguration(),n=[];for(const s of(r=t.teleop.hardwareStreams)!=null?r:[])s.rtcStreamType==="h264-video-frame"&&n.push({name:s.name});for(const s of(o=t.teleop.rosStreams)!=null?o:[])s.topicType=="formant/H264VideoFrame"&&n.push({name:s.topicName});for(const s of(l=t.teleop.customStreams)!=null?l:[])s.rtcStreamType==="h264-video-frame"&&n.push({name:s.name});return n}async getRealtimeManipulators(){var r;const t=await this.getConfiguration(),n=[];for(const o of(r=t.teleop.rosStreams)!=null?r:[])o.topicType=="sensor_msgs/JointState"&&n.push(new Manipulator(this,{currentJointStateStream:{name:o.topicName},plannedJointStateStream:o.plannedTopic?{name:o.plannedTopic}:void 0,planValidStream:o.planValidTopic?{name:o.planValidTopic}:void 0,endEffectorStream:o.endEffectorTopic?{name:o.endEffectorTopic}:void 0,endEffectorLinkName:o.endEffectorLinkName,baseReferenceFrame:o.baseReferenceFrame,localFrame:o.localFrame}));return n}async startListeningToRealtimeVideo(t){const n=defined(this.rtcClient,"Realtime connection has not been started"),r=await this.getRemotePeer();n.controlRemoteStream(defined(r).id,{streamName:t.name,enable:!0,pipeline:"rtc"})}async stopListeningToRealtimeVideo(t){const n=defined(this.rtcClient,"Realtime connection has not been started"),r=await this.getRemotePeer();n.controlRemoteStream(defined(r).id,{streamName:t.name,enable:!1,pipeline:"rtc"})}async startListeningToRealtimeDataStream(t){const n=defined(this.rtcClient,"Realtime connection has not been started"),r=await this.getRemotePeer();n.controlRemoteStream(defined(r).id,{streamName:t.name,enable:!0,pipeline:"rtc"})}async stopListeningToRealtimeDataStream(t){const n=defined(this.rtcClient,"Realtime connection has not been started"),r=await this.getRemotePeer();n.controlRemoteStream(defined(r).id,{streamName:t.name,enable:!1,pipeline:"rtc"})}async enableRealtimeTelemetryPriorityIngestion(t){const n=defined(this.rtcClient,"Realtime connection has not been started"),r=await this.getRemotePeer();n.controlRemoteStream(defined(r).id,{streamName:t,enablePriorityUpload:!0,pipeline:"telemetry"})}async disableRealtimeTelemetryPriorityIngestion(t){const n=defined(this.rtcClient,"Realtime connection has not been started"),r=await this.getRemotePeer();n.controlRemoteStream(defined(r).id,{streamName:t,enablePriorityUpload:!1,pipeline:"telemetry"})}async getRemotePeer(){return{id:this.peerUrl,organizationId:"",deviceId:this.id,capabilities:[],capabilitySet:{}}}async stopRealtimeConnection(){if(this.rtcClient)await this.rtcClient.disconnect(this.id);else throw new Error(`Realtime connection hasn't been started for ${this.id}`)}async createCustomDataChannel(t,n){const r=defined(this.rtcClient,"Realtime connection has not been started"),o=await this.getRemotePeer(),l=await new Promise(s=>{r.createCustomDataChannel(defined(o).id,t,{ordered:!0,...n},!1,(i,c)=>{const u=new DataChannel(c);s(u)})});return await l.waitTilReady(),l}createCustomRequestDataChannel(t,n=3e3){return new TextRequestDataChannel(this,t,n)}createCustomBinaryRequestDataChannel(t,n=3e3){return new BinaryRequestDataChannel(this,t,n)}}const He=class{static async setDefaultDevice(t){He.defaultDeviceId=t}static async getCurrentDevice(){if(!Authentication.token)throw new Error("Not authenticated");if(!He.defaultDeviceId)throw new Error("No known default device");const o=(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===He.defaultDeviceId).name,l=new Device(He.defaultDeviceId,o,defined(Authentication.currentOrganization));return He.knownContext.push(new WeakRef(l)),l}static async getPeerDevice(t){const n=new PeerDevice(t);return n.id=await n.getDeviceId(),n}static async getDevice(t){if(!Authentication.token)throw new Error("Not authenticated");const r=await(await fetch(`${FORMANT_API_URL}/v1/admin/devices/${t}`,{method:"GET",headers:{"Content-Type":"application/json",Authorization:"Bearer "+Authentication.token}})).json(),o=r.name,l=new Device(t,o,r.organizationId);return He.knownContext.push(new WeakRef(l)),l}static async getDevices(){if(!Authentication.token)throw new Error("Not authenticated");const n=await(await fetch(`${FORMANT_API_URL}/v1/admin/device-details/query`,{method:"POST",body:JSON.stringify({enabled:!0,type:"default"}),headers:{"Content-Type":"application/json",Authorization:"Bearer "+Authentication.token}})).json();return n.items,n.items.map(r=>new Device(r.id,r.name,r.organizationId))}static async queryDevices(t){if(!Authentication.token)throw new Error("Not authenticated");return(await(await fetch(`${FORMANT_API_URL}/v1/admin/devices/query`,{method:"POST",body:JSON.stringify(t),headers:{"Content-Type":"application/json",Authorization:"Bearer "+Authentication.token}})).json()).items.map(o=>new Device(o.id,o.name,o.organizationId))}static async getOnlineDevices(){if(!Authentication.token)throw new Error("Not authenticated");const r=(await(await fetch(`${FORMANT_API_URL}/v1/queries/online-devices`,{method:"GET",headers:{"Content-Type":"application/json",Authorization:"Bearer "+Authentication.token}})).json()).items;return(await He.getDevices()).filter(l=>r.includes(l.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 r=(await(await fetch(`${FORMANT_API_URL}/v1/signaling/peers`,{method:"GET",headers:{"Content-Type":"application/json",Authorization:"Bearer "+Authentication.token}})).json()).items.map(l=>l.deviceId);return(await He.getDevices()).filter(l=>r.includes(l.id))}static async getLatestTelemetry(t){let n=t;return t&&!Array.isArray(t)&&(t=[t]),(await(await fetch(`${FORMANT_API_URL}/v1/queries/stream-current-value`,{method:"POST",body:JSON.stringify({deviceIds:n}),headers:{"Content-Type":"application/json",Authorization:"Bearer "+Authentication.token}})).json()).items}static async getTelemetry(t,n,r,o,l){let s=t;Array.isArray(t)||(s=[t]);let i=n;return Array.isArray(n)||(i=[n]),(await(await fetch(`${FORMANT_API_URL}/v1/queries/queries`,{method:"POST",body:JSON.stringify({deviceIds:s,end:o.toISOString(),names:i,start:r.toISOString(),tags:l}),headers:{"Content-Type":"application/json",Authorization:"Bearer "+Authentication.token}})).json()).items}static async getFileUrl(t){const r=await(await fetch(`${FORMANT_API_URL}/v1/admin/files/query`,{method:"POST",body:JSON.stringify({fileIds:[t]}),headers:{"Content-Type":"application/json",Authorization:"Bearer "+Authentication.token}})).json();if(r.fileUrls.length===0)throw new Error("File not found");return r.fileUrls[0]}static async queryTelemetry(t){if(!Authentication.token)throw new Error("Not authenticated");return(await(await fetch(`${FORMANT_API_URL}/v1/queries/queries`,{method:"POST",body:JSON.stringify(t),headers:{"Content-Type":"application/json",Authorization:"Bearer "+Authentication.token}})).json()).items}static async aggregateTelemetry(t){if(!Authentication.token)throw new Error("Not authenticated");return(await(await fetch(`${FORMANT_API_URL}/v1/queries/queries`,{method:"POST",body:JSON.stringify(t),headers:{"Content-Type":"application/json",Authorization:"Bearer "+Authentication.token}})).json()).aggregates}static async queryEvents(t){if(!Authentication.token)throw new Error("Not authenticated");return(await(await fetch(`${FORMANT_API_URL}/v1/admin/events/query`,{method:"POST",body:JSON.stringify(t),headers:{"Content-Type":"application/json",Authorization:"Bearer "+Authentication.token}})).json()).items}static async getEvent(t){if(!Authentication.token)throw new Error("Not authenticated");return(await(await fetch(`${FORMANT_API_URL}/v1/admin/events/query/id=${t}`,{method:"GET",headers:{"Content-Type":"application/json",Authorization:"Bearer "+Authentication.token}})).json()).items}static async getInterventions(){if(!Authentication.token)throw new Error("Not authenticated");return(await(await fetch(`${FORMANT_API_URL}/v1/admin/intervention-requests`,{method:"GET",headers:{"Content-Type":"application/json",Authorization:"Bearer "+Authentication.token}})).json()).items}static async getCurrentGroup(){if(!Authentication.token)throw new Error("Not authenticated");let t=new URLSearchParams("");typeof window!="undefined"&&(t=new URLSearchParams(window.location.search));const n=t.get("group");if(n===null||n.trim()==="")return;const r=await fetch(`${FORMANT_API_URL}/v1/admin/groups/`+n,{headers:{"Content-Type":"application/json",Authorization:"Bearer "+Authentication.token}}),{tagKey:o,tagValue:l}=await r.json();return await this.queryDevices({tags:{[o]:[l]},enabled:!0,type:"default"})}static async getAnnotationCount(t){const n=t.tagKey;return delete t.tagKey,delete t.aggregate,(await this.queryEvents({...t,eventTypes:["annotation"]})).filter(s=>!!s.tags&&Object.keys(s.tags).includes(n)).reduce((s,i)=>{const c=i.tags[n];return c in s?(s[c]+=1,s):(s[c]=1,s)},{})}};let Fleet$1=He;Ae(Fleet$1,"defaultDeviceId"),Ae(Fleet$1,"knownContext",[]);const millisecond=1,second=1e3,minute=60*second,hour=60*minute,day=24*hour,week=7*day,month=30*day,year=365*day,duration={millisecond,second,minute,hour,day,week,month,year};function filterDataByType(e,t){return e.filter(n=>n.type===t)}function filterDataByTime(e,t,n){const r=t.getTime(),o=n.getTime();return e.map(l=>({...l,points:l.points.filter(([s])=>s>=r&&s<o)})).filter(({points:l})=>l.length>0)}function fork(e){}class StoreCache{constructor({capacity:t,timeout:n}={}){Ae(this,"entries",new Map);Ae(this,"metadata",new Map);Ae(this,"capacity");Ae(this,"timeout");this.capacity=t||1e4,this.timeout=n||duration.minute}get(t,n){const r=this.keyToCacheKey(t),o=this.entries.get(r),l=this.metadata.get(r);return(o===void 0||l&&(l==null?void 0:l.expiration.getTime())<Date.now())&&!(l!=null&&l.generating)&&n&&this.generate(t,n()),o===void 0&&l&&l.lastValue!==void 0?l.lastValue:o}set(t,n){const r=this.keyToCacheKey(t);this.metadata.set(r,{generating:!1,expiration:new Date(Date.now()+this.timeout),lastValue:n}),this.entries.set(r,n),this.metadata.size>this.capacity&&this.deleteOldestEntry()}clear(){this.entries.clear(),[...this.metadata.values()].forEach(t=>t.generating=!1)}clearKey(t){this.metadata.delete(t),this.entries.delete(t)}keyToCacheKey(t){return JSON.stringify(t)}deleteOldestEntry(){if(this.metadata.size<1)return;const[t]=[...this.metadata.entries()].reduce(([n,r],[o,l])=>l.expiration.getTime()<r.expiration.getTime()?[o,l]:[n,r]);this.clearKey(t)}generate(t,n){const r=this.keyToCacheKey(t),o=this.metadata.get(r)||{};this.metadata.set(r,{...o,generating:!0,expiration:new Date(Date.now()+this.timeout)}),setTimeout(()=>{n.then(l=>{const s=this.metadata.get(r);!(s!=null&&s.generating)||this.set(t,l)})},0)}}class QueryStore{constructor(){Ae(this,"queryStoreCache",new StoreCache({capacity:1e4,timeout:20*duration.second}));Ae(this,"liveQueryStoreCache",new StoreCache({capacity:1e4,timeout:200*duration.millisecond}))}moduleQuery(t,n,r,o,l,s=!1){const i={...t,names:[n],types:[r]},c=this.query(i,o,l,s);return c===void 0||c==="too much data"?c:filterDataByType(c,r)}query(t,n,r,o=!1){const l={...t,start:dateFns.startOfMinute(n).toISOString(),end:o?r.toISOString():dateFns.addMinutes(dateFns.roundToNearestMinutes(r),1).toISOString(),latestOnly:o},s=r>dateFns.addSeconds(new Date,-20);let i;return s?i=this.liveQueryCache(l):i=this.queryCache(l),!i||i==="too much data"||o?i:filterDataByTime(i,n,r)}queryCache(t){return this.queryStoreCache.get(t,async()=>{try{return await Fleet$1.queryTelemetry(t)}catch(n){throw n}})}liveQueryCache(t){return this.liveQueryStoreCache.get(t,async()=>{try{return await Fleet$1.queryTelemetry(t)}catch(n){throw n}})}}const queryStore=new QueryStore;class App{static sendAppMessage(t){window.parent.postMessage(t,"*")}static getCurrentModuleContext(){let t=new URLSearchParams("");return typeof window!="undefined"&&(t=new URLSearchParams(window.location.search)),t.get("module")}static async getCurrentModuleConfiguration(){let t=new URLSearchParams("");typeof window!="undefined"&&(t=new URLSearchParams(window.location.search));const n=t.get("configuration");return n===null||n.trim()===""?void 0:(await(await fetch(`${FORMANT_API_URL}/v1/admin/module-configurations/`+n,{headers:{"Content-Type":"application/json",Authorization:"Bearer "+Authentication.token}})).json()).configuration}static isModule(){return this.getCurrentModuleContext()!==null}static goToTime(t){this.sendAppMessage({type:"go_to_time",time:t.getTime()})}static goToDevice(t){this.sendAppMessage({type:"go_to_device",deviceId:t})}static showMessage(t){this.sendAppMessage({type:"show_message",message:t})}static requestModuleData(){const t=this.getCurrentModuleContext();if(!t)throw new Error("No module context");this.sendAppMessage({type:"request_module_data",module:t})}static setModuleDateTimeRange(t,n){const r=this.getCurrentModuleContext();if(!r)throw new Error("No module context");this.sendAppMessage({type:"set_module_data_time_range",module:r,before:t,after:n||0})}static refreshAuthToken(){const t=this.getCurrentModuleContext();if(!t)throw new Error("No module context");this.sendAppMessage({type:"refresh_auth_token",module:t})}static sendChannelData(t,n){const r=this.getCurrentModuleContext();if(!r)throw new Error("No module context");this.sendAppMessage({type:"send_channel_data",source:r,channel:t,data:n})}static setupModuleMenus(t){const n=this.getCurrentModuleContext();if(!n)throw new Error("No module context");this.sendAppMessage({type:"setup_module_menus",module:n,menus:t})}static addMenuListener(t){window.addEventListener("message",n=>{const r=n.data;r.type==="module_menu_item_clicked"&&t(r.menu)})}static addAccessTokenRefreshListener(t){window.addEventListener("message",n=>{const r=n.data;r.type==="auth_token"&&t(r.token)})}static addModuleDataListener(t){const n=this.getCurrentModuleContext();n&&this.sendAppMessage({type:"request_module_data",module:n}),window.addEventListener("message",r=>{const o=r.data;o.type==="module_data"&&t({streams:o.streams,time:o.time,queryRange:o.queryRange})})}static addStreamListener(t,n,r){const o=l=>{const s=l.data;if(s.type==="module_data"){const{start:i,end:c}=s.queryRange;r(queryStore.moduleQuery({},t,n,new Date(i),new Date(c),!1))}};return window.addEventListener("message",o),()=>window.removeEventListener("message",o)}static addModuleConfigurationListener(t){window.addEventListener("message",n=>{const r=n.data;r.type==="module_configuration"&&t(r)})}static addChannelDataListener(t,n){window.addEventListener("message",r=>{const o=r.data;o.type==="channel_data"&&o.channel===t&&n({source:o.source,data:o.data})})}static requestOverviewDevices(t){this.sendAppMessage({type:"request_devices"}),window.addEventListener("message",n=>{const r=n.data;t(r)})}static async prompt(t,n){return new Promise(r=>{const o=Math.random().toString();this.sendAppMessage({type:"prompt",promptId:o,schema:t,okText:n==null?void 0:n.okText,cancelText:n==null?void 0:n.cancelText});const l=s=>{const i=s.data;i.type==="prompt_response"&&i.promptId===o&&r(i.data),window.removeEventListener("message",l)};window.addEventListener("message",l)})}}const Pe=class{static async login(t,n){try{const r=await fetch(`${FORMANT_API_URL}/v1/admin/auth/login`,{method:"POST",body:JSON.stringify({email:t,password:n}),headers:{"Content-Type":"application/json"}}),o=await r.json();if(r.status!==200)throw new Error(o.message);return await Pe.loginWithToken(o.authentication.accessToken,o.authentication.refreshToken),o.authentication}catch(r){return Pe.waitingForAuth.forEach(o=>o(!1)),Pe.waitingForAuth=[],Promise.reject(r)}}static async loginWithToken(t,n){const r=JSON.parse(atob(t.split(".")[1]));try{let o;if(Pe.isShareToken=r["formant:claims"]&&r["formant:claims"].type=="share",r["formant:claims"]&&(Pe.currentOrganization=r["formant:claims"].organizationId),r["custom:organization_id"]&&(Pe.currentOrganization=r["custom:organization_id"]),Pe.isShareToken||(o=r.sub),r["formant:claims"]&&r["formant:claims"].userId&&(o=r["formant:claims"].userId),o){const l=await fetch(`${FORMANT_API_URL}/v1/admin/users/${o}`,{method:"GET",headers:{"Content-Type":"application/json",Authorization:"Bearer "+t}}),s=await l.json();if(l.status!==200)throw new Error(s.message);Pe.currentUser=s}Pe.token=t,Pe.waitingForAuth.forEach(l=>l(!0))}catch(o){console.error(o),Pe.waitingForAuth.forEach(l=>l(!1))}Pe.waitingForAuth=[],n&&(Pe.refreshToken=n,setInterval(async()=>{if(Pe.refreshToken){const l=await(await fetch(`${FORMANT_API_URL}/v1/admin/auth/refresh`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({refreshToken:Pe.refreshToken})})).json();Pe.token=l.authentication.accessToken}},1e3*60*60))}static isAuthenticated(){return Pe.token!==void 0}static getCurrentUser(){return Pe.currentUser}static async waitTilAuthenticated(){return Pe.token!==void 0?!0:new Promise(t=>{Pe.waitingForAuth.push(function(n){t(n)})})}static async listenForRefresh(){App.addAccessTokenRefreshListener(t=>{this.loginWithToken(t)}),setInterval(async()=>{App.refreshAuthToken()},1e3*60*60)}};let Authentication=Pe;Ae(Authentication,"token"),Ae(Authentication,"refreshToken"),Ae(Authentication,"currentUser"),Ae(Authentication,"currentOrganization"),Ae(Authentication,"isShareToken",!1),Ae(Authentication,"defaultDeviceId"),Ae(Authentication,"waitingForAuth",[]);const Xe=class{static async setDefaultDevice(t){Xe.defaultDeviceId=t}static async getCurrentDevice(){if(!Authentication.token)throw new Error("Not authenticated");if(!Xe.defaultDeviceId)throw new Error("No known default device");const o=(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===Xe.defaultDeviceId).name,l=new Device(Xe.defaultDeviceId,o,defined(Authentication.currentOrganization));return Xe.knownContext.push(new WeakRef(l)),l}static async getPeerDevice(t){const n=new PeerDevice(t);return n.id=await n.getDeviceId(),n}static async getDevice(t){if(!Authentication.token)throw new Error("Not authenticated");const r=await(await fetch(`${FORMANT_API_URL}/v1/admin/devices/${t}`,{method:"GET",headers:{"Content-Type":"application/json",Authorization:"Bearer "+Authentication.token}})).json(),o=r.name,l=new Device(t,o,r.organizationId);return Xe.knownContext.push(new WeakRef(l)),l}static async getDevices(){if(!Authentication.token)throw new Error("Not authenticated");const n=await(await fetch(`${FORMANT_API_URL}/v1/admin/device-details/query`,{method:"POST",body:JSON.stringify({enabled:!0,type:"default"}),headers:{"Content-Type":"application/json",Authorization:"Bearer "+Authentication.token}})).json();return n.items,n.items.map(r=>new Device(r.id,r.name,r.organizationId))}static async queryDevices(t){if(!Authentication.token)throw new Error("Not authenticated");return(await(await fetch(`${FORMANT_API_URL}/v1/admin/devices/query`,{method:"POST",body:JSON.stringify(t),headers:{"Content-Type":"application/json",Authorization:"Bearer "+Authentication.token}})).json()).items.map(o=>new Device(o.id,o.name,o.organizationId))}static async getOnlineDevices(){if(!Authentication.token)throw new Error("Not authenticated");const r=(await(await fetch(`${FORMANT_API_URL}/v1/queries/online-devices`,{method:"GET",headers:{"Content-Type":"application/json",Authorization:"Bearer "+Authentication.token}})).json()).items;return(await Xe.getDevices()).filter(l=>r.includes(l.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 r=(await(await fetch(`${FORMANT_API_URL}/v1/signaling/peers`,{method:"GET",headers:{"Content-Type":"application/json",Authorization:"Bearer "+Authentication.token}})).json()).items.map(l=>l.deviceId);return(await Xe.getDevices()).filter(l=>r.includes(l.id))}static async getLatestTelemetry(t){let n=t;return t&&!Array.isArray(t)&&(t=[t]),(await(await fetch(`${FORMANT_API_URL}/v1/queries/stream-current-value`,{method:"POST",body:JSON.stringify({deviceIds:n}),headers:{"Content-Type":"application/json",Authorization:"Bearer "+Authentication.token}})).json()).items}static async getTelemetry(t,n,r,o,l){let s=t;Array.isArray(t)||(s=[t]);let i=n;return Array.isArray(n)||(i=[n]),(await(await fetch(`${FORMANT_API_URL}/v1/queries/queries`,{method:"POST",body:JSON.stringify({deviceIds:s,end:o.toISOString(),names:i,start:r.toISOString(),tags:l}),headers:{"Content-Type":"application/json",Authorization:"Bearer "+Authentication.token}})).json()).items}static async getFileUrl(t){const r=await(await fetch(`${FORMANT_API_URL}/v1/admin/files/query`,{method:"POST",body:JSON.stringify({fileIds:[t]}),headers:{"Content-Type":"application/json",Authorization:"Bearer "+Authentication.token}})).json();if(r.fileUrls.length===0)throw new Error("File not found");return r.fileUrls[0]}static async queryTelemetry(t){if(!Authentication.token)throw new Error("Not authenticated");return(await(await fetch(`${FORMANT_API_URL}/v1/queries/queries`,{method:"POST",body:JSON.stringify(t),headers:{"Content-Type":"application/json",Authorization:"Bearer "+Authentication.token}})).json()).items}static async aggregateTelemetry(t){if(!Authentication.token)throw new Error("Not authenticated");return(await(await fetch(`${FORMANT_API_URL}/v1/queries/queries`,{method:"POST",body:JSON.stringify(t),headers:{"Content-Type":"application/json",Authorization:"Bearer "+Authentication.token}})).json()).aggregates}static async queryEvents(t){if(!Authentication.token)throw new Error("Not authenticated");return(await(await fetch(`${FORMANT_API_URL}/v1/admin/events/query`,{method:"POST",body:JSON.stringify(t),headers:{"Content-Type":"application/json",Authorization:"Bearer "+Authentication.token}})).json()).items}static async getEvent(t){if(!Authentication.token)throw new Error("Not authenticated");return(await(await fetch(`${FORMANT_API_URL}/v1/admin/events/query/id=${t}`,{method:"GET",headers:{"Content-Type":"application/json",Authorization:"Bearer "+Authentication.token}})).json()).items}static async getInterventions(){if(!Authentication.token)throw new Error("Not authenticated");return(await(await fetch(`${FORMANT_API_URL}/v1/admin/intervention-requests`,{method:"GET",headers:{"Content-Type":"application/json",Authorization:"Bearer "+Authentication.token}})).json()).items}static async getCurrentGroup(){if(!Authentication.token)throw new Error("Not authenticated");let t=new URLSearchParams("");typeof window!="undefined"&&(t=new URLSearchParams(window.location.search));const n=t.get("group");if(n===null||n.trim()==="")return;const r=await fetch(`${FORMANT_API_URL}/v1/admin/groups/`+n,{headers:{"Content-Type":"application/json",Authorization:"Bearer "+Authentication.token}}),{tagKey:o,tagValue:l}=await r.json();return await this.queryDevices({tags:{[o]:[l]},enabled:!0,type:"default"})}static async getAnnotationCount(t){const n=t.tagKey;return delete t.tagKey,delete t.aggregate,(await this.queryEvents({...t,eventTypes:["annotation"]})).filter(s=>!!s.tags&&Object.keys(s.tags).includes(n)).reduce((s,i)=>{const c=i.tags[n];return c in s?(s[c]+=1,s):(s[c]=1,s)},{})}};let Fleet=Xe;Ae(Fleet,"defaultDeviceId"),Ae(Fleet,"knownContext",[]);class KeyValue{static async set(t,n){try{const r=await fetch(FORMANT_API_URL+"/v1/admin/key-value",{method:"POST",body:JSON.stringify({organizationId:defined(Authentication.currentUser).organizationId,key:t,value:n}),headers:{"Content-Type":"application/json",Authorization:"Bearer "+Authentication.token}}),o=await r.json();if(r.status!==200)throw new Error(o.message)}catch(r){throw r}}static async get(t){try{const n=await fetch(FORMANT_API_URL+`/v1/admin/key-value/${t}`,{method:"GET",headers:{"Content-Type":"application/json",Authorization:"Bearer "+Authentication.token}}),r=await n.json();if(n.status!==200)throw new Error(r.message);return r.value}catch(n){throw n}}static async list(){try{const t=await fetch(FORMANT_API_URL+"/v1/admin/key-value",{method:"GET",headers:{"Content-Type":"application/json",Authorization:"Bearer "+Authentication.token}}),n=await t.json();if(t.status!==200)throw new Error(n.message);return n.items}catch(t){throw t}}static async delete(t){try{if(!(await fetch(FORMANT_API_URL+`/v1/admin/key-value/${t}`,{method:"DELETE",headers:{"Content-Type":"application/json",Authorization:"Bearer "+Authentication.token}})).ok)throw new Error("Unable to handle request");return}catch(n){throw n}}}function getVariance(e){return e.count<2?0:e.sumOfSquares/(e.count-1)}function getStandardDeviation(e){return Math.sqrt(getVariance(e))}function getMax(e){return e.max}function getMin(e){return e.min}function getAverage(e){return e.count===0?-1:e.sum/e.count}function getSum(e){return e.sum}function getCount(e){return e.count}const aggregateFunctionMap={min:getMin,max:getMax,"standard deviation":getStandardDeviation,average:getAverage,sum:getSum,count:getCount};function getZeroINumericSet(){return{min:Number.MAX_SAFE_INTEGER,max:0,sum:0,count:0,sumOfSquares:0}}function reduceNumericStreamAggregates(e){return e.aggregates.reduce((t,n)=>{const r=n[1];return combineNumericAggregates(r,t)},getZeroINumericSet())}function reduceNumericSetStreamAggregates(e,t){var n;return(n=e.aggregates.reduce((r,o)=>{const l=o[1];return combineNumericSetAggregates(l,r)},{})[t])==null?void 0:n.value}function combineNumericAggregates(e,t){return{min:Math.min(e.min,t.min),max:Math.max(e.max,t.max),sum:e.sum+t.sum,count:e.count+t.count,sumOfSquares:e.sumOfSquares+t.sumOfSquares}}function combineNumericSetAggregates(e,t){return Object.keys(e).reduce((n,r)=>{var o,l;return{...n,[r]:{value:combineNumericAggregates(e[r].value,(l=(o=t[r])==null?void 0:o.value)!=null?l:getZeroINumericSet()),unit:e[r].unit}}},{})}function stringToArrayBuffer(e){return Uint8Array.from(atob(e),t=>t.charCodeAt(0))}function browser(){const{userAgent:e}=navigator;return e.includes("Firefox/")?"Firefox":e.includes("Edg/")?"Edge":e.includes("Chrome/")?"Chrome":e.includes("Safari/")?"Safari":e.includes("MSIE/")||e.includes("Trident/")?"IE":"Other"}const rtcAudioChunkStreamType="audio-chunk";class AudioPlayer{constructor(t,n){Ae(this,"muted",!1);Ae(this,"hasReceivedData",!1);Ae(this,"audioContext");Ae(this,"chunks",[]);Ae(this,"isPlaying",!1);Ae(this,"startTime",0);Ae(this,"lastChunkOffset",0);Ae(this,"bufferSize",3);Ae(this,"receive",async t=>{var s;const n=(s=t.payload.audioChunk)==null?void 0:s.chunk_data;if(!n)return;this.hasReceivedData||(this.hasReceivedData=!0);const{audioContext:r,muted:o}=this;if(!r||t.header.stream.streamType!==rtcAudioChunkStreamType||o!==!1)return;const l=stringToArrayBuffer(n);try{await r.decodeAudioData(l.buffer,this.scheduleChunk)}catch(i){console.warn("Error decoding audio buffer, changing audioWireFormat on agent",{error:i}),this.changeAudioWireFormat("wav")}});Ae(this,"scheduleChunk",t=>{const{audioContext:n}=this;if(!n)return;(this.chunks.length>this.bufferSize||this.isPlaying===!1)&&(this.chunks.forEach(o=>{o.stop()}),this.isPlaying=!1,this.chunks=[]);const r=this.createChunk(t);!r||!r.buffer||(this.isPlaying===!1&&(this.startTime=n.currentTime,this.lastChunkOffset=0,this.isPlaying=!0),r.start(this.startTime+this.lastChunkOffset,0,t.duration),this.lastChunkOffset+=r.buffer.duration,this.chunks.push(r))});this.device=t,this.stream=n,this.device.startListeningToRealtimeDataStream(n),this.device.addRealtimeListener((o,l)=>{this.receive(l)}),browser()==="Safari"||browser()==="IE"?this.changeAudioWireFormat("wav"):this.changeAudioWireFormat("opus");const r=window.AudioContext||window.webkitAudioContext;this.audioContext=new r}async play(){var t,n;((t=this.audioContext)==null?void 0:t.state)==="suspended"&&await((n=this.audioContext)==null?void 0:n.resume()),this.muted=!1}async pause(){await this.audioContext.suspend(),this.muted=!0}destroy(){this.device.stopListeningToRealtimeDataStream(this.stream)}createChunk(t){const{audioContext:n}=this;if(!n)return;const r=n.createBufferSource();return r.buffer=t,r.connect(n.destination),r.loop=!1,r.onended=o=>{this.chunks.splice(this.chunks.indexOf(r),1),this.chunks.length===0&&(this.isPlaying=!1)},r}changeAudioWireFormat(t){const{stream:n}=this;(async()=>await this.device.changeStreamAudioType(n.name,t))()}}const accessLevels=["viewer","operator","administrator"],viewer="viewer",operator="operator",administrator="administrator",aggregateLevels=["year","month","week","day","hour","minute"],annotationTypes=["tag","sheet","user"],eventTypes=["triggered-event","intervention-request","teleop-session-record","port-forwarding-session-record","command-request","command-response","command-delivery","custom","comment","system","annotation"],healthStatuses=["unknown","operational","offline","error"],interventionTypes=["selection","labeling","teleop"],severities=["info","warning","error","critical"],videoMimeTypes=["video/mp4"];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.AudioPlayer=AudioPlayer,exports.Authentication=Authentication,exports.BinaryRequestDataChannel=BinaryRequestDataChannel,exports.CaptureStream=CaptureStream,exports.DataChannel=DataChannel,exports.Device=Device,exports.Fleet=Fleet,exports.IRtcSendConfiguration=dist.exports.IRtcSendConfiguration,exports.IRtcStreamMessage=dist.exports.IRtcStreamMessage,exports.IRtcStreamPayload=dist.exports.IRtcStreamPayload,exports.KeyValue=KeyValue,exports.Manipulator=Manipulator,exports.PeerDevice=PeerDevice,exports.SessionType=SessionType,exports.TextRequestDataChannel=TextRequestDataChannel,exports.accessLevels=accessLevels,exports.administrator=administrator,exports.aggregateFunctionMap=aggregateFunctionMap,exports.aggregateLevels=aggregateLevels,exports.annotationTypes=annotationTypes,exports.combineNumericAggregates=combineNumericAggregates,exports.combineNumericSetAggregates=combineNumericSetAggregates,exports.eventTypes=eventTypes,exports.getAverage=getAverage,exports.getCount=getCount,exports.getMax=getMax,exports.getMin=getMin,exports.getStandardDeviation=getStandardDeviation,exports.getSum=getSum,exports.getVariance=getVariance,exports.getZeroINumericSet=getZeroINumericSet,exports.healthStatuses=healthStatuses,exports.interventionTypes=interventionTypes,exports.operator=operator,exports.reduceNumericSetStreamAggregates=reduceNumericSetStreamAggregates,exports.reduceNumericStreamAggregates=reduceNumericStreamAggregates,exports.severities=severities,exports.videoMimeTypes=videoMimeTypes,exports.viewer=viewer,Object.defineProperties(exports,{__esModule:{value:!0},[Symbol.toStringTag]:{value:"Module"}})});
@@ -7,6 +7,7 @@ import { IStreamAggregateData } from "./model/IStreamAggregateData";
7
7
  import { IStreamData } from "./model/IStreamData";
8
8
  import { PeerDevice } from "./PeerDevice";
9
9
  import { IDeviceQuery } from "./model/IDeviceQuery";
10
+ import { IAnnotationQuery } from "./model/IAnnotationQuery";
10
11
  export interface TelemetryResult {
11
12
  deviceId: string;
12
13
  name: string;
@@ -42,4 +43,7 @@ export declare class Fleet {
42
43
  static getEvent(uuid: string): Promise<IEvent>;
43
44
  static getInterventions(): Promise<IEvent[]>;
44
45
  static getCurrentGroup(): Promise<Device[] | undefined>;
46
+ static getAnnotationCount(query: IAnnotationQuery): Promise<{
47
+ [key: string]: number;
48
+ }>;
45
49
  }
@@ -112,5 +112,6 @@ export * from "./model/Uuid";
112
112
  export * from "./model/videoMimeTypes";
113
113
  export * from "./model/VideoMimeType";
114
114
  export * from "./model/IDeviceQuery";
115
+ export * from "./model/IAnnotationQuery";
115
116
  export { IRtcSendConfiguration, IRtcStreamMessage, IRtcStreamPayload, } from "@formant/realtime-sdk";
116
117
  export * from "./model/JsonSchema";
@@ -0,0 +1,7 @@
1
+ import { IEventQuery } from "./IEventQuery";
2
+ import { AggregateLevel } from "./AggregateLevel";
3
+ export interface IAnnotationQuery extends IEventQuery {
4
+ tagKey?: string;
5
+ annotationName?: string;
6
+ aggregate?: AggregateLevel;
7
+ }
@@ -1,6 +1,6 @@
1
1
  import { StreamType } from "./StreamType";
2
2
  export type FieldType = "string" | "integer" | "number" | "array" | "object" | "boolean";
3
- interface IJsonBaseSchema<T extends FieldType> {
3
+ export interface IJsonBaseSchema<T extends FieldType> {
4
4
  title?: string;
5
5
  description?: string;
6
6
  type: T;
@@ -8,7 +8,7 @@ interface IJsonBaseSchema<T extends FieldType> {
8
8
  $schema?: string;
9
9
  "$formant.visible.when"?: [string, "=", string];
10
10
  }
11
- interface IJsonBaseSchemaWithDefault<T extends FieldType, U> extends IJsonBaseSchema<T> {
11
+ export interface IJsonBaseSchemaWithDefault<T extends FieldType, U> extends IJsonBaseSchema<T> {
12
12
  default?: U;
13
13
  }
14
14
  export interface IPropertyObject {
@@ -26,7 +26,7 @@ export interface IJsonArraySchema extends IJsonBaseSchema<"array"> {
26
26
  "$formant.itemName"?: string;
27
27
  };
28
28
  }
29
- export interface IJsonStringSchema extends IJsonBaseSchema<"string"> {
29
+ export interface IJsonStringSchema extends IJsonBaseSchemaWithDefault<"string", string> {
30
30
  enum?: string[];
31
31
  "$formant.streams.byType"?: StreamType;
32
32
  "$formant.placeholder"?: string;
@@ -37,4 +37,3 @@ export type IJsonBooleanSchema = IJsonBaseSchemaWithDefault<"boolean", boolean>;
37
37
  export type IJsonIntegerSchema = IJsonBaseSchemaWithDefault<"integer", number>;
38
38
  export type IJsonNumberSchema = IJsonBaseSchemaWithDefault<"number", number>;
39
39
  export type JsonSchema = IJsonObjectSchema | IJsonStringSchema | IJsonArraySchema | IJsonBooleanSchema | IJsonIntegerSchema | IJsonNumberSchema;
40
- export {};
package/package.json CHANGED
@@ -18,7 +18,7 @@
18
18
  "require": "./dist/data-sdk.umd.js"
19
19
  }
20
20
  },
21
- "version": "0.0.127",
21
+ "version": "0.0.129",
22
22
  "scripts": {
23
23
  "dev": "vite --port 9146",
24
24
  "build": "tsc && vite build",