@formant/data-sdk 1.81.2 → 1.81.6

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.
@@ -124,7 +124,7 @@ ${j}`),E.pop(),`{${te}}`}case"number":return isFinite(W)?String(W):U?U(W):"null"
124
124
  `),stack:S&&S.stack,exception:!0,date:new Date().toString(),process:this.getProcessInfo(),os:this.getOsInfo(),trace:this.getTrace(S)}}},{key:"getProcessInfo",value:function(){return{pid:process.pid,uid:process.getuid?process.getuid():null,gid:process.getgid?process.getgid():null,cwd:process.cwd(),execPath:process.execPath,version:process.version,argv:process.argv,memoryUsage:process.memoryUsage()}}},{key:"getOsInfo",value:function(){return{loadavg:c.loadavg(),uptime:c.uptime()}}},{key:"getTrace",value:function(S){return(S?h.parse(S):h.get()).map(function(U){return{column:U.getColumnNumber(),file:U.getFileName(),function:U.getFunctionName(),line:U.getLineNumber(),method:U.getMethodName(),native:U.isNative()}})}},{key:"_addHandler",value:function(S){if(!this.handlers.has(S)){S.handleExceptions=!0;var U=new R(S);this.handlers.set(S,U),this.logger.pipe(U)}}},{key:"_uncaughtException",value:function(S){var U,b=this.getAllInfo(S),T=this._getExceptionHandlers(),F=typeof this.logger.exitOnError=="function"?this.logger.exitOnError(S):this.logger.exitOnError;function w(){u("doExit",F),u("process._exiting",process._exiting),F&&!process._exiting&&(U&&clearTimeout(U),process.exit(1))}if(!T.length&&F&&(console.warn("winston: exitOnError cannot be true with no exception handlers."),console.warn("winston: not exiting process."),F=!1),!T||T.length===0)return process.nextTick(w);l(T,function(B,Y){var A=d(Y),L=B.transport||B;function m(H){return function(){u(H),A()}}L._ending=!0,L.once("finish",m("finished")),L.once("error",m("error"))},function(){return F&&w()}),this.logger.log(b),F&&(U=setTimeout(w,3e3))}},{key:"_getExceptionHandlers",value:function(){return this.logger.transports.filter(function(S){return(S.transport||S).handleExceptions})}}])&&o(y.prototype,Q),f&&o(y,f),Object.defineProperty(y,"prototype",{writable:!1}),y;var y,Q,f}()},9422:(e,t,n)=>{function r(h){return(r=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(R){return typeof R}:function(R){return R&&typeof Symbol=="function"&&R.constructor===Symbol&&R!==Symbol.prototype?"symbol":typeof R})(h)}function o(h,R){for(var y=0;y<R.length;y++){var Q=R[y];Q.enumerable=Q.enumerable||!1,Q.configurable=!0,"value"in Q&&(Q.writable=!0),Object.defineProperty(h,s(Q.key),Q)}}function s(h){var R=function(y,Q){if(r(y)!="object"||!y)return y;var f=y[Symbol.toPrimitive];if(f!==void 0){var S=f.call(y,Q||"default");if(r(S)!="object")return S;throw new TypeError("@@toPrimitive must return a primitive value.")}return(Q==="string"?String:Number)(y)}(h,"string");return r(R)=="symbol"?R:R+""}function c(h,R,y){return R=l(R),function(Q,f){if(f&&(r(f)=="object"||typeof f=="function"))return f;if(f!==void 0)throw new TypeError("Derived constructors may only return object or undefined");return function(S){if(S===void 0)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return S}(Q)}(h,function(){try{var Q=!Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],function(){}))}catch{}return function(){return!!Q}()}()?Reflect.construct(R,y||[],l(h).constructor):R.apply(h,y))}function l(h){return(l=Object.setPrototypeOf?Object.getPrototypeOf.bind():function(R){return R.__proto__||Object.getPrototypeOf(R)})(h)}function u(h,R){return(u=Object.setPrototypeOf?Object.setPrototypeOf.bind():function(y,Q){return y.__proto__=Q,y})(h,R)}var d=n(4156).Writable;e.exports=function(h){function R(S){var U;if(function(b,T){if(!(b instanceof T))throw new TypeError("Cannot call a class as a function")}(this,R),U=c(this,R,[{objectMode:!0}]),!S)throw new Error("ExceptionStream requires a TransportStream instance.");return U.handleExceptions=!0,U.transport=S,U}return function(S,U){if(typeof U!="function"&&U!==null)throw new TypeError("Super expression must either be null or a function");S.prototype=Object.create(U&&U.prototype,{constructor:{value:S,writable:!0,configurable:!0}}),Object.defineProperty(S,"prototype",{writable:!1}),U&&u(S,U)}(R,h),y=R,(Q=[{key:"_write",value:function(S,U,b){return S.exception?this.transport.log(S,b):(b(),!0)}}])&&o(y.prototype,Q),f&&o(y,f),Object.defineProperty(y,"prototype",{writable:!1}),y;var y,Q,f}(d)},2162:(e,t,n)=>{function r(W,E,v){return(E=c(E))in W?Object.defineProperty(W,E,{value:v,enumerable:!0,configurable:!0,writable:!0}):W[E]=v,W}function o(W){return(o=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(E){return typeof E}:function(E){return E&&typeof Symbol=="function"&&E.constructor===Symbol&&E!==Symbol.prototype?"symbol":typeof E})(W)}function s(W,E){for(var v=0;v<E.length;v++){var k=E[v];k.enumerable=k.enumerable||!1,k.configurable=!0,"value"in k&&(k.writable=!0),Object.defineProperty(W,c(k.key),k)}}function c(W){var E=function(v,k){if(o(v)!="object"||!v)return v;var j=v[Symbol.toPrimitive];if(j!==void 0){var _=j.call(v,k||"default");if(o(_)!="object")return _;throw new TypeError("@@toPrimitive must return a primitive value.")}return(k==="string"?String:Number)(v)}(W,"string");return o(E)=="symbol"?E:E+""}function l(W,E,v){return E=u(E),function(k,j){if(j&&(o(j)=="object"||typeof j=="function"))return j;if(j!==void 0)throw new TypeError("Derived constructors may only return object or undefined");return function(_){if(_===void 0)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return _}(k)}(W,function(){try{var k=!Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],function(){}))}catch{}return function(){return!!k}()}()?Reflect.construct(E,v||[],u(W).constructor):E.apply(W,v))}function u(W){return(u=Object.setPrototypeOf?Object.getPrototypeOf.bind():function(E){return E.__proto__||Object.getPrototypeOf(E)})(W)}function d(W,E){return(d=Object.setPrototypeOf?Object.setPrototypeOf.bind():function(v,k){return v.__proto__=k,v})(W,E)}var h=n(4156),R=h.Stream,y=h.Transform,Q=n(5236),f=n(4966),S=f.LEVEL,U=f.SPLAT,b=n(6605),T=n(8624),F=n(8846),w=n(1127),B=n(2535),Y=n(1735).warn,A=n(9127),L=/%[scdjifoO%]/g,m=function(W){function E(_){var M;return function($,te){if(!($ instanceof te))throw new TypeError("Cannot call a class as a function")}(this,E),(M=l(this,E,[{objectMode:!0}])).configure(_),M}return function(_,M){if(typeof M!="function"&&M!==null)throw new TypeError("Super expression must either be null or a function");_.prototype=Object.create(M&&M.prototype,{constructor:{value:_,writable:!0,configurable:!0}}),Object.defineProperty(_,"prototype",{writable:!1}),M&&d(_,M)}(E,W),v=E,(k=[{key:"child",value:function(_){var M=this;return Object.create(M,{write:{value:function($){var te=Object.assign({},_,$);$ instanceof Error&&(te.stack=$.stack,te.message=$.message),M.write(te)}}})}},{key:"configure",value:function(){var _=this,M=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{},$=M.silent,te=M.format,P=M.defaultMeta,q=M.levels,ie=M.level,ee=ie===void 0?"info":ie,x=M.exitOnError,z=x===void 0||x,oe=M.transports,ce=M.colors,re=M.emitErrs,se=M.formatters,ne=M.padLevels,he=M.rewriters,me=M.stripColors,Qe=M.exceptionHandlers,Ve=M.rejectionHandlers;if(this.transports.length&&this.clear(),this.silent=$,this.format=te||this.format||n(2598)(),this.defaultMeta=P||null,this.levels=q||this.levels||A.npm.levels,this.level=ee,this.exceptions&&this.exceptions.unhandle(),this.rejections&&this.rejections.unhandle(),this.exceptions=new T(this),this.rejections=new F(this),this.profilers={},this.exitOnError=z,oe&&(oe=Array.isArray(oe)?oe:[oe]).forEach(function(We){return _.add(We)}),ce||re||se||ne||he||me)throw new Error(["{ colors, emitErrs, formatters, padLevels, rewriters, stripColors } were removed in winston@3.0.0.","Use a custom winston.format(function) instead.","See: https://github.com/winstonjs/winston/tree/master/UPGRADE-3.0.md"].join(`
125
125
  `));Qe&&this.exceptions.handle(Qe),Ve&&this.rejections.handle(Ve)}},{key:"isLevelEnabled",value:function(_){var M=this,$=H(this.levels,_);if($===null)return!1;var te=H(this.levels,this.level);return te!==null&&(this.transports&&this.transports.length!==0?this.transports.findIndex(function(P){var q=H(M.levels,P.level);return q===null&&(q=te),q>=$})!==-1:te>=$)}},{key:"log",value:function(_,M){for(var $=arguments.length,te=new Array($>2?$-2:0),P=2;P<$;P++)te[P-2]=arguments[P];if(arguments.length===1)return _[S]=_.level,this._addDefaultMeta(_),this.write(_),this;if(arguments.length===2)return M&&o(M)==="object"?(M[S]=M.level=_,this._addDefaultMeta(M),this.write(M),this):(M=r(r(r({},S,_),"level",_),"message",M),this._addDefaultMeta(M),this.write(M),this);var q=te[0];if(o(q)==="object"&&q!==null){var ie=M&&M.match&&M.match(L);if(!ie){var ee=Object.assign({},this.defaultMeta,q,r(r(r(r({},S,_),U,te),"level",_),"message",M));return q.message&&(ee.message="".concat(ee.message," ").concat(q.message)),q.stack&&(ee.stack=q.stack),this.write(ee),this}}return this.write(Object.assign({},this.defaultMeta,r(r(r(r({},S,_),U,te),"level",_),"message",M))),this}},{key:"_transform",value:function(_,M,$){if(this.silent)return $();_[S]||(_[S]=_.level),this.levels[_[S]]||this.levels[_[S]]===0||console.error("[winston] Unknown logger level: %s",_[S]),this._readableState.pipes||console.error("[winston] Attempt to write logs with no transports, which can increase memory usage: %j",_);try{this.push(this.format.transform(_,this.format.options))}finally{this._writableState.sync=!1,$()}}},{key:"_final",value:function(_){var M=this.transports.slice();Q(M,function($,te){if(!$||$.finished)return setImmediate(te);$.once("finish",te),$.end()},_)}},{key:"add",value:function(_){var M=!b(_)||_.log.length>2?new w({transport:_}):_;if(!M._writableState||!M._writableState.objectMode)throw new Error("Transports must WritableStreams in objectMode. Set { objectMode: true }.");return this._onEvent("error",M),this._onEvent("warn",M),this.pipe(M),_.handleExceptions&&this.exceptions.handle(),_.handleRejections&&this.rejections.handle(),this}},{key:"remove",value:function(_){if(!_)return this;var M=_;return(!b(_)||_.log.length>2)&&(M=this.transports.filter(function($){return $.transport===_})[0]),M&&this.unpipe(M),this}},{key:"clear",value:function(){return this.unpipe(),this}},{key:"close",value:function(){return this.exceptions.unhandle(),this.rejections.unhandle(),this.clear(),this.emit("close"),this}},{key:"setLevels",value:function(){Y.deprecated("setLevels")}},{key:"query",value:function(_,M){typeof _=="function"&&(M=_,_={}),_=_||{};var $={},te=Object.assign({},_.query||{});Q(this.transports.filter(function(P){return!!P.query}),function(P,q){(function(ie,ee){_.query&&typeof ie.formatQuery=="function"&&(_.query=ie.formatQuery(te)),ie.query(_,function(x,z){if(x)return ee(x);typeof ie.formatResults=="function"&&(z=ie.formatResults(z,_.format)),ee(null,z)})})(P,function(ie,ee){q&&((ee=ie||ee)&&($[P.name]=ee),q()),q=null})},function(){return M(null,$)})}},{key:"stream",value:function(){var _=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{},M=new R,$=[];return M._streams=$,M.destroy=function(){for(var te=$.length;te--;)$[te].destroy()},this.transports.filter(function(te){return!!te.stream}).forEach(function(te){var P=te.stream(_);P&&($.push(P),P.on("log",function(q){q.transport=q.transport||[],q.transport.push(te.name),M.emit("log",q)}),P.on("error",function(q){q.transport=q.transport||[],q.transport.push(te.name),M.emit("error",q)}))}),M}},{key:"startTimer",value:function(){return new B(this)}},{key:"profile",value:function(_){var M=Date.now();if(this.profilers[_]){var $=this.profilers[_];delete this.profilers[_];for(var te=arguments.length,P=new Array(te>1?te-1:0),q=1;q<te;q++)P[q-1]=arguments[q];typeof P[P.length-2]=="function"&&(console.warn("Callback function no longer supported as of winston@3.0.0"),P.pop());var ie=o(P[P.length-1])==="object"?P.pop():{};return ie.level=ie.level||"info",ie.durationMs=M-$,ie.message=ie.message||_,this.write(ie)}return this.profilers[_]=M,this}},{key:"handleExceptions",value:function(){var _;console.warn("Deprecated: .handleExceptions() will be removed in winston@4. Use .exceptions.handle()"),(_=this.exceptions).handle.apply(_,arguments)}},{key:"unhandleExceptions",value:function(){var _;console.warn("Deprecated: .unhandleExceptions() will be removed in winston@4. Use .exceptions.unhandle()"),(_=this.exceptions).unhandle.apply(_,arguments)}},{key:"cli",value:function(){throw new Error(["Logger.cli() was removed in winston@3.0.0","Use a custom winston.formats.cli() instead.","See: https://github.com/winstonjs/winston/tree/master/UPGRADE-3.0.md"].join(`
126
126
  `))}},{key:"_onEvent",value:function(_,M){M["__winston"+_]||(M["__winston"+_]=function($){_!=="error"||this.transports.includes(M)||this.add(M),this.emit(_,$,M)}.bind(this),M.on(_,M["__winston"+_]))}},{key:"_addDefaultMeta",value:function(_){this.defaultMeta&&Object.assign(_,this.defaultMeta)}}])&&s(v.prototype,k),j&&s(v,j),Object.defineProperty(v,"prototype",{writable:!1}),v;var v,k,j}(y);function H(W,E){var v=W[E];return v||v===0?v:null}Object.defineProperty(m.prototype,"transports",{configurable:!1,enumerable:!0,get:function(){var W=this._readableState.pipes;return Array.isArray(W)?W:[W].filter(Boolean)}}),e.exports=m},2535:(e,t,n)=>{function r(l){return(r=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(u){return typeof u}:function(u){return u&&typeof Symbol=="function"&&u.constructor===Symbol&&u!==Symbol.prototype?"symbol":typeof u})(l)}function o(l,u){for(var d=0;d<u.length;d++){var h=u[d];h.enumerable=h.enumerable||!1,h.configurable=!0,"value"in h&&(h.writable=!0),Object.defineProperty(l,s(h.key),h)}}function s(l){var u=function(d,h){if(r(d)!="object"||!d)return d;var R=d[Symbol.toPrimitive];if(R!==void 0){var y=R.call(d,h||"default");if(r(y)!="object")return y;throw new TypeError("@@toPrimitive must return a primitive value.")}return(h==="string"?String:Number)(d)}(l,"string");return r(u)=="symbol"?u:u+""}var c=function(){return l=function h(R){(function(Q,f){if(!(Q instanceof f))throw new TypeError("Cannot call a class as a function")})(this,h);var y=n(2162);if(r(R)!=="object"||Array.isArray(R)||!(R instanceof y))throw new Error("Logger is required for profiling");this.logger=R,this.start=Date.now()},(u=[{key:"done",value:function(){for(var h=arguments.length,R=new Array(h),y=0;y<h;y++)R[y]=arguments[y];typeof R[R.length-1]=="function"&&(console.warn("Callback function no longer supported as of winston@3.0.0"),R.pop());var Q=r(R[R.length-1])==="object"?R.pop():{};return Q.level=Q.level||"info",Q.durationMs=Date.now()-this.start,this.logger.write(Q)}}])&&o(l.prototype,u),d&&o(l,d),Object.defineProperty(l,"prototype",{writable:!1}),l;var l,u,d}();e.exports=c},8846:(e,t,n)=>{function r(y){return(r=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(Q){return typeof Q}:function(Q){return Q&&typeof Symbol=="function"&&Q.constructor===Symbol&&Q!==Symbol.prototype?"symbol":typeof Q})(y)}function o(y,Q){for(var f=0;f<Q.length;f++){var S=Q[f];S.enumerable=S.enumerable||!1,S.configurable=!0,"value"in S&&(S.writable=!0),Object.defineProperty(y,s(S.key),S)}}function s(y){var Q=function(f,S){if(r(f)!="object"||!f)return f;var U=f[Symbol.toPrimitive];if(U!==void 0){var b=U.call(f,S||"default");if(r(b)!="object")return b;throw new TypeError("@@toPrimitive must return a primitive value.")}return(S==="string"?String:Number)(f)}(y,"string");return r(Q)=="symbol"?Q:Q+""}var c=n(2213),l=n(5236),u=n(7147)("winston:rejection"),d=n(960),h=n(5082),R=n(888);e.exports=function(){return y=function S(U){if(function(b,T){if(!(b instanceof T))throw new TypeError("Cannot call a class as a function")}(this,S),!U)throw new Error("Logger is required to handle rejections");this.logger=U,this.handlers=new Map},(Q=[{key:"handle",value:function(){for(var S=this,U=arguments.length,b=new Array(U),T=0;T<U;T++)b[T]=arguments[T];b.forEach(function(F){if(Array.isArray(F))return F.forEach(function(w){return S._addHandler(w)});S._addHandler(F)}),this.catcher||(this.catcher=this._unhandledRejection.bind(this),process.on("unhandledRejection",this.catcher))}},{key:"unhandle",value:function(){var S=this;this.catcher&&(process.removeListener("unhandledRejection",this.catcher),this.catcher=!1,Array.from(this.handlers.values()).forEach(function(U){return S.logger.unpipe(U)}))}},{key:"getAllInfo",value:function(S){var U=null;return S&&(U=typeof S=="string"?S:S.message),{error:S,level:"error",message:["unhandledRejection: ".concat(U||"(no error message)"),S&&S.stack||" No stack trace"].join(`
127
- `),stack:S&&S.stack,rejection:!0,date:new Date().toString(),process:this.getProcessInfo(),os:this.getOsInfo(),trace:this.getTrace(S)}}},{key:"getProcessInfo",value:function(){return{pid:process.pid,uid:process.getuid?process.getuid():null,gid:process.getgid?process.getgid():null,cwd:process.cwd(),execPath:process.execPath,version:process.version,argv:process.argv,memoryUsage:process.memoryUsage()}}},{key:"getOsInfo",value:function(){return{loadavg:c.loadavg(),uptime:c.uptime()}}},{key:"getTrace",value:function(S){return(S?h.parse(S):h.get()).map(function(U){return{column:U.getColumnNumber(),file:U.getFileName(),function:U.getFunctionName(),line:U.getLineNumber(),method:U.getMethodName(),native:U.isNative()}})}},{key:"_addHandler",value:function(S){if(!this.handlers.has(S)){S.handleRejections=!0;var U=new R(S);this.handlers.set(S,U),this.logger.pipe(U)}}},{key:"_unhandledRejection",value:function(S){var U,b=this.getAllInfo(S),T=this._getRejectionHandlers(),F=typeof this.logger.exitOnError=="function"?this.logger.exitOnError(S):this.logger.exitOnError;function w(){u("doExit",F),u("process._exiting",process._exiting),F&&!process._exiting&&(U&&clearTimeout(U),process.exit(1))}if(!T.length&&F&&(console.warn("winston: exitOnError cannot be true with no rejection handlers."),console.warn("winston: not exiting process."),F=!1),!T||T.length===0)return process.nextTick(w);l(T,function(B,Y){var A=d(Y),L=B.transport||B;function m(H){return function(){u(H),A()}}L._ending=!0,L.once("finish",m("finished")),L.once("error",m("error"))},function(){return F&&w()}),this.logger.log(b),F&&(U=setTimeout(w,3e3))}},{key:"_getRejectionHandlers",value:function(){return this.logger.transports.filter(function(S){return(S.transport||S).handleRejections})}}])&&o(y.prototype,Q),f&&o(y,f),Object.defineProperty(y,"prototype",{writable:!1}),y;var y,Q,f}()},888:(e,t,n)=>{function r(h){return(r=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(R){return typeof R}:function(R){return R&&typeof Symbol=="function"&&R.constructor===Symbol&&R!==Symbol.prototype?"symbol":typeof R})(h)}function o(h,R){for(var y=0;y<R.length;y++){var Q=R[y];Q.enumerable=Q.enumerable||!1,Q.configurable=!0,"value"in Q&&(Q.writable=!0),Object.defineProperty(h,s(Q.key),Q)}}function s(h){var R=function(y,Q){if(r(y)!="object"||!y)return y;var f=y[Symbol.toPrimitive];if(f!==void 0){var S=f.call(y,Q||"default");if(r(S)!="object")return S;throw new TypeError("@@toPrimitive must return a primitive value.")}return(Q==="string"?String:Number)(y)}(h,"string");return r(R)=="symbol"?R:R+""}function c(h,R,y){return R=l(R),function(Q,f){if(f&&(r(f)=="object"||typeof f=="function"))return f;if(f!==void 0)throw new TypeError("Derived constructors may only return object or undefined");return function(S){if(S===void 0)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return S}(Q)}(h,function(){try{var Q=!Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],function(){}))}catch{}return function(){return!!Q}()}()?Reflect.construct(R,y||[],l(h).constructor):R.apply(h,y))}function l(h){return(l=Object.setPrototypeOf?Object.getPrototypeOf.bind():function(R){return R.__proto__||Object.getPrototypeOf(R)})(h)}function u(h,R){return(u=Object.setPrototypeOf?Object.setPrototypeOf.bind():function(y,Q){return y.__proto__=Q,y})(h,R)}var d=n(4156).Writable;e.exports=function(h){function R(S){var U;if(function(b,T){if(!(b instanceof T))throw new TypeError("Cannot call a class as a function")}(this,R),U=c(this,R,[{objectMode:!0}]),!S)throw new Error("RejectionStream requires a TransportStream instance.");return U.handleRejections=!0,U.transport=S,U}return function(S,U){if(typeof U!="function"&&U!==null)throw new TypeError("Super expression must either be null or a function");S.prototype=Object.create(U&&U.prototype,{constructor:{value:S,writable:!0,configurable:!0}}),Object.defineProperty(S,"prototype",{writable:!1}),U&&u(S,U)}(R,h),y=R,(Q=[{key:"_write",value:function(S,U,b){return S.rejection?this.transport.log(S,b):(b(),!0)}}])&&o(y.prototype,Q),f&&o(y,f),Object.defineProperty(y,"prototype",{writable:!1}),y;var y,Q,f}(d)},2879:(e,t,n)=>{var r=n(2627),o=n(8888).StringDecoder,s=n(4156).Stream;function c(){}e.exports=function(l,u){var d=Buffer.alloc(65536),h=new o("utf8"),R=new s,y="",Q=0,f=0;return l.start===-1&&delete l.start,R.readable=!0,R.destroy=function(){R.destroyed=!0,R.emit("end"),R.emit("close")},r.open(l.file,"a+","0644",function(S,U){if(S)return u?u(S):R.emit("error",S),void R.destroy();(function b(){if(!R.destroyed)return r.read(U,d,0,d.length,Q,function(T,F){if(T)return u?u(T):R.emit("error",T),void R.destroy();if(!F)return y&&((l.start==null||f>l.start)&&(u?u(null,y):R.emit("line",y)),f++,y=""),setTimeout(b,1e3);var w=h.write(d.slice(0,F));u||R.emit("data",w);for(var B=(w=(y+w).split(/\n+/)).length-1,Y=0;Y<B;Y++)(l.start==null||f>l.start)&&(u?u(null,w[Y]):R.emit("line",w[Y])),f++;return y=w[B],Q+=F,b()});r.close(U,c)})()}),u?R.destroy:R}},810:(e,t,n)=>{function r(S){return(r=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(U){return typeof U}:function(U){return U&&typeof Symbol=="function"&&U.constructor===Symbol&&U!==Symbol.prototype?"symbol":typeof U})(S)}function o(S,U){if(!(S instanceof U))throw new TypeError("Cannot call a class as a function")}function s(S,U){for(var b=0;b<U.length;b++){var T=U[b];T.enumerable=T.enumerable||!1,T.configurable=!0,"value"in T&&(T.writable=!0),Object.defineProperty(S,c(T.key),T)}}function c(S){var U=function(b,T){if(r(b)!="object"||!b)return b;var F=b[Symbol.toPrimitive];if(F!==void 0){var w=F.call(b,T||"default");if(r(w)!="object")return w;throw new TypeError("@@toPrimitive must return a primitive value.")}return(T==="string"?String:Number)(b)}(S,"string");return r(U)=="symbol"?U:U+""}function l(S,U,b){return U=u(U),function(T,F){if(F&&(r(F)=="object"||typeof F=="function"))return F;if(F!==void 0)throw new TypeError("Derived constructors may only return object or undefined");return function(w){if(w===void 0)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return w}(T)}(S,function(){try{var T=!Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],function(){}))}catch{}return function(){return!!T}()}()?Reflect.construct(U,b||[],u(S).constructor):U.apply(S,b))}function u(S){return(u=Object.setPrototypeOf?Object.getPrototypeOf.bind():function(U){return U.__proto__||Object.getPrototypeOf(U)})(S)}function d(S,U){return(d=Object.setPrototypeOf?Object.setPrototypeOf.bind():function(b,T){return b.__proto__=T,b})(S,U)}var h=n(2213),R=n(4966),y=R.LEVEL,Q=R.MESSAGE,f=n(6155);e.exports=function(S){function U(){var w,B=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};return o(this,U),(w=l(this,U,[B])).name=B.name||"console",w.stderrLevels=w._stringArrayToSet(B.stderrLevels),w.consoleWarnLevels=w._stringArrayToSet(B.consoleWarnLevels),w.eol=typeof B.eol=="string"?B.eol:h.EOL,w.forceConsole=B.forceConsole||!1,w._consoleLog=console.log.bind(console),w._consoleWarn=console.warn.bind(console),w._consoleError=console.error.bind(console),w.setMaxListeners(30),w}return function(w,B){if(typeof B!="function"&&B!==null)throw new TypeError("Super expression must either be null or a function");w.prototype=Object.create(B&&B.prototype,{constructor:{value:w,writable:!0,configurable:!0}}),Object.defineProperty(w,"prototype",{writable:!1}),B&&d(w,B)}(U,S),b=U,(T=[{key:"log",value:function(w,B){var Y=this;return setImmediate(function(){return Y.emit("logged",w)}),this.stderrLevels[w[y]]?(console._stderr&&!this.forceConsole?console._stderr.write("".concat(w[Q]).concat(this.eol)):this._consoleError(w[Q]),void(B&&B())):this.consoleWarnLevels[w[y]]?(console._stderr&&!this.forceConsole?console._stderr.write("".concat(w[Q]).concat(this.eol)):this._consoleWarn(w[Q]),void(B&&B())):(console._stdout&&!this.forceConsole?console._stdout.write("".concat(w[Q]).concat(this.eol)):this._consoleLog(w[Q]),void(B&&B()))}},{key:"_stringArrayToSet",value:function(w,B){if(!w)return{};if(B=B||"Cannot make set from type other than Array of string elements",!Array.isArray(w))throw new Error(B);return w.reduce(function(Y,A){if(typeof A!="string")throw new Error(B);return Y[A]=!0,Y},{})}}])&&s(b.prototype,T),F&&s(b,F),Object.defineProperty(b,"prototype",{writable:!1}),b;var b,T,F}(f)},3329:(e,t,n)=>{function r(Y){return(r=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(A){return typeof A}:function(A){return A&&typeof Symbol=="function"&&A.constructor===Symbol&&A!==Symbol.prototype?"symbol":typeof A})(Y)}function o(Y,A){if(!(Y instanceof A))throw new TypeError("Cannot call a class as a function")}function s(Y,A){for(var L=0;L<A.length;L++){var m=A[L];m.enumerable=m.enumerable||!1,m.configurable=!0,"value"in m&&(m.writable=!0),Object.defineProperty(Y,c(m.key),m)}}function c(Y){var A=function(L,m){if(r(L)!="object"||!L)return L;var H=L[Symbol.toPrimitive];if(H!==void 0){var W=H.call(L,m||"default");if(r(W)!="object")return W;throw new TypeError("@@toPrimitive must return a primitive value.")}return(m==="string"?String:Number)(L)}(Y,"string");return r(A)=="symbol"?A:A+""}function l(Y,A,L){return A=u(A),function(m,H){if(H&&(r(H)=="object"||typeof H=="function"))return H;if(H!==void 0)throw new TypeError("Derived constructors may only return object or undefined");return function(W){if(W===void 0)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return W}(m)}(Y,function(){try{var m=!Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],function(){}))}catch{}return function(){return!!m}()}()?Reflect.construct(A,L||[],u(Y).constructor):A.apply(Y,L))}function u(Y){return(u=Object.setPrototypeOf?Object.getPrototypeOf.bind():function(A){return A.__proto__||Object.getPrototypeOf(A)})(Y)}function d(Y,A){return(d=Object.setPrototypeOf?Object.setPrototypeOf.bind():function(L,m){return L.__proto__=m,L})(Y,A)}var h=n(9256),R=n(8558),y=n(481),Q=n(7946),f=n(4966).MESSAGE,S=n(4156),U=S.Stream,b=S.PassThrough,T=n(6155),F=n(7147)("winston:file"),w=n(2213),B=n(2879);e.exports=function(Y){function A(){var W,E=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};function v(k){for(var j=arguments.length,_=new Array(j>1?j-1:0),M=1;M<j;M++)_[M-1]=arguments[M];_.slice(1).forEach(function($){if(E[$])throw new Error("Cannot set ".concat($," and ").concat(k," together"))})}if(o(this,A),(W=l(this,A,[E])).name=E.name||"file",W._stream=new b,W._stream.setMaxListeners(30),W._onError=W._onError.bind(W),E.filename||E.dirname)v("filename or dirname","stream"),W._basename=W.filename=E.filename?R.basename(E.filename):"winston.log",W.dirname=E.dirname||R.dirname(E.filename),W.options=E.options||{flags:"a"};else{if(!E.stream)throw new Error("Cannot log to file without filename or stream.");console.warn("options.stream will be removed in winston@4. Use winston.transports.Stream"),v("stream","filename","maxsize"),W._dest=W._stream.pipe(W._setupStream(E.stream)),W.dirname=R.dirname(W._dest.path)}return W.maxsize=E.maxsize||null,W.rotationFormat=E.rotationFormat||!1,W.zippedArchive=E.zippedArchive||!1,W.maxFiles=E.maxFiles||null,W.eol=typeof E.eol=="string"?E.eol:w.EOL,W.tailable=E.tailable||!1,W.lazy=E.lazy||!1,W._size=0,W._pendingSize=0,W._created=0,W._drain=!1,W._opening=!1,W._ending=!1,W._fileExist=!1,W.dirname&&W._createLogDirIfNotExist(W.dirname),W.lazy||W.open(),W}return function(W,E){if(typeof E!="function"&&E!==null)throw new TypeError("Super expression must either be null or a function");W.prototype=Object.create(E&&E.prototype,{constructor:{value:W,writable:!0,configurable:!0}}),Object.defineProperty(W,"prototype",{writable:!1}),E&&d(W,E)}(A,Y),L=A,(m=[{key:"finishIfEnding",value:function(){var W=this;this._ending&&(this._opening?this.once("open",function(){W._stream.once("finish",function(){return W.emit("finish")}),setImmediate(function(){return W._stream.end()})}):(this._stream.once("finish",function(){return W.emit("finish")}),setImmediate(function(){return W._stream.end()})))}},{key:"log",value:function(W){var E=this,v=arguments.length>1&&arguments[1]!==void 0?arguments[1]:function(){};if(this.silent)return v(),!0;if(this._drain)this._stream.once("drain",function(){E._drain=!1,E.log(W,v)});else{if(!this._rotate){if(this.lazy){if(!this._fileExist)return this._opening||this.open(),void this.once("open",function(){E._fileExist=!0,E.log(W,v)});if(this._needsNewFile(this._pendingSize))return void this._dest.once("close",function(){E._opening||E.open(),E.once("open",function(){E.log(W,v)})})}var k="".concat(W[f]).concat(this.eol),j=Buffer.byteLength(k);this._pendingSize+=j,this._opening&&!this.rotatedWhileOpening&&this._needsNewFile(this._size+this._pendingSize)&&(this.rotatedWhileOpening=!0);var _=this._stream.write(k,M.bind(this));return _?v():(this._drain=!0,this._stream.once("drain",function(){E._drain=!1,v()})),F("written",_,this._drain),this.finishIfEnding(),_}this._stream.once("rotate",function(){E._rotate=!1,E.log(W,v)})}function M(){var $=this;this._size+=j,this._pendingSize-=j,F("logged %s %s",this._size,k),this.emit("logged",W),this._rotate||this._opening||this._needsNewFile()&&(this.lazy?this._endStream(function(){$.emit("fileclosed")}):(this._rotate=!0,this._endStream(function(){return $._rotateFile()})))}}},{key:"query",value:function(W,E){typeof W=="function"&&(E=W,W={}),W=function(te){return(te=te||{}).rows=te.rows||te.limit||10,te.start=te.start||0,te.until=te.until||new Date,r(te.until)!=="object"&&(te.until=new Date(te.until)),te.from=te.from||te.until-864e5,r(te.from)!=="object"&&(te.from=new Date(te.from)),te.order=te.order||"desc",te}(W);var v=R.join(this.dirname,this.filename),k="",j=[],_=0,M=h.createReadStream(v,{encoding:"utf8"});function $(te,P){try{var q=JSON.parse(te);(function(ie){if(ie&&r(ie)==="object"){var ee=new Date(ie.timestamp);if(!(W.from&&ee<W.from||W.until&&ee>W.until||W.level&&W.level!==ie.level))return!0}})(q)&&function(ie){W.rows&&j.length>=W.rows&&W.order!=="desc"?M.readable&&M.destroy():(W.fields&&(ie=W.fields.reduce(function(ee,x){return ee[x]=ie[x],ee},{})),W.order==="desc"&&j.length>=W.rows&&j.shift(),j.push(ie))}(q)}catch(ie){P||M.emit("error",ie)}}M.on("error",function(te){if(M.readable&&M.destroy(),E)return te.code!=="ENOENT"?E(te):E(null,j)}),M.on("data",function(te){for(var P=(te=(k+te).split(/\n+/)).length-1,q=0;q<P;q++)(!W.start||_>=W.start)&&$(te[q]),_++;k=te[P]}),M.on("close",function(){k&&$(k,!0),W.order==="desc"&&(j=j.reverse()),E&&E(null,j)})}},{key:"stream",value:function(){var W=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{},E=R.join(this.dirname,this.filename),v=new U,k={file:E,start:W.start};return v.destroy=B(k,function(j,_){if(j)return v.emit("error",j);try{v.emit("data",_),_=JSON.parse(_),v.emit("log",_)}catch(M){v.emit("error",M)}}),v}},{key:"open",value:function(){var W=this;this.filename&&(this._opening||(this._opening=!0,this.stat(function(E,v){if(E)return W.emit("error",E);F("stat done: %s { size: %s }",W.filename,v),W._size=v,W._dest=W._createStream(W._stream),W._opening=!1,W.once("open",function(){W._stream.emit("rotate")||(W._rotate=!1)})})))}},{key:"stat",value:function(W){var E=this,v=this._getFile(),k=R.join(this.dirname,v);h.stat(k,function(j,_){return j&&j.code==="ENOENT"?(F("ENOENT ok",k),E.filename=v,W(null,0)):j?(F("err ".concat(j.code," ").concat(k)),W(j)):!_||E._needsNewFile(_.size)?E._incFile(function(){return E.stat(W)}):(E.filename=v,void W(null,_.size))})}},{key:"close",value:function(W){var E=this;this._stream&&this._stream.end(function(){W&&W(),E.emit("flush"),E.emit("closed")})}},{key:"_needsNewFile",value:function(W){return W=W||this._size,this.maxsize&&W>=this.maxsize}},{key:"_onError",value:function(W){this.emit("error",W)}},{key:"_setupStream",value:function(W){return W.on("error",this._onError),W}},{key:"_cleanupStream",value:function(W){return W.removeListener("error",this._onError),W.destroy(),W}},{key:"_rotateFile",value:function(){var W=this;this._incFile(function(){return W.open()})}},{key:"_endStream",value:function(){var W=this,E=arguments.length>0&&arguments[0]!==void 0?arguments[0]:function(){};this._dest?(this._stream.unpipe(this._dest),this._dest.end(function(){W._cleanupStream(W._dest),E()})):E()}},{key:"_createStream",value:function(W){var E=this,v=R.join(this.dirname,this.filename);F("create stream start",v,this.options);var k=h.createWriteStream(v,this.options).on("error",function(j){return F(j)}).on("close",function(){return F("close",k.path,k.bytesWritten)}).on("open",function(){F("file open ok",v),E.emit("open",v),W.pipe(k),E.rotatedWhileOpening&&(E._stream=new b,E._stream.setMaxListeners(30),E._rotateFile(),E.rotatedWhileOpening=!1,E._cleanupStream(k),W.end())});return F("create stream ok",v),k}},{key:"_incFile",value:function(W){F("_incFile",this.filename);var E=R.extname(this._basename),v=R.basename(this._basename,E),k=[];this.zippedArchive&&k.push(function(j){var _=this._created>0&&!this.tailable?this._created:"";this._compressFile(R.join(this.dirname,"".concat(v).concat(_).concat(E)),R.join(this.dirname,"".concat(v).concat(_).concat(E,".gz")),j)}.bind(this)),k.push(function(j){this.tailable?this._checkMaxFilesTailable(E,v,j):(this._created+=1,this._checkMaxFilesIncrementing(E,v,j))}.bind(this)),y(k,W)}},{key:"_getFile",value:function(){var W=R.extname(this._basename),E=R.basename(this._basename,W),v=this.rotationFormat?this.rotationFormat():this._created;return!this.tailable&&this._created?"".concat(E).concat(v).concat(W):"".concat(E).concat(W)}},{key:"_checkMaxFilesIncrementing",value:function(W,E,v){if(!this.maxFiles||this._created<this.maxFiles)return setImmediate(v);var k=this._created-this.maxFiles,j=k!==0?k:"",_=this.zippedArchive?".gz":"",M="".concat(E).concat(j).concat(W).concat(_),$=R.join(this.dirname,M);h.unlink($,v)}},{key:"_checkMaxFilesTailable",value:function(W,E,v){var k=this,j=[];if(this.maxFiles){for(var _=this.zippedArchive?".gz":"",M=this.maxFiles-1;M>1;M--)j.push(function($,te){var P=this,q="".concat(E).concat($-1).concat(W).concat(_),ie=R.join(this.dirname,q);h.exists(ie,function(ee){if(!ee)return te(null);q="".concat(E).concat($).concat(W).concat(_),h.rename(ie,R.join(P.dirname,q),te)})}.bind(this,M));y(j,function(){h.rename(R.join(k.dirname,"".concat(E).concat(W).concat(_)),R.join(k.dirname,"".concat(E,"1").concat(W).concat(_)),v)})}}},{key:"_compressFile",value:function(W,E,v){h.access(W,h.F_OK,function(k){if(k)return v();var j=Q.createGzip(),_=h.createReadStream(W),M=h.createWriteStream(E);M.on("finish",function(){h.unlink(W,v)}),_.pipe(j).pipe(M)})}},{key:"_createLogDirIfNotExist",value:function(W){h.existsSync(W)||h.mkdirSync(W,{recursive:!0})}}])&&s(L.prototype,m),H&&s(L,H),Object.defineProperty(L,"prototype",{writable:!1}),L;var L,m,H}(T)},7543:(e,t,n)=>{function r(T){return(r=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(F){return typeof F}:function(F){return F&&typeof Symbol=="function"&&F.constructor===Symbol&&F!==Symbol.prototype?"symbol":typeof F})(T)}function o(T,F){var w=Object.keys(T);if(Object.getOwnPropertySymbols){var B=Object.getOwnPropertySymbols(T);F&&(B=B.filter(function(Y){return Object.getOwnPropertyDescriptor(T,Y).enumerable})),w.push.apply(w,B)}return w}function s(T){for(var F=1;F<arguments.length;F++){var w=arguments[F]!=null?arguments[F]:{};F%2?o(Object(w),!0).forEach(function(B){c(T,B,w[B])}):Object.getOwnPropertyDescriptors?Object.defineProperties(T,Object.getOwnPropertyDescriptors(w)):o(Object(w)).forEach(function(B){Object.defineProperty(T,B,Object.getOwnPropertyDescriptor(w,B))})}return T}function c(T,F,w){return(F=d(F))in T?Object.defineProperty(T,F,{value:w,enumerable:!0,configurable:!0,writable:!0}):T[F]=w,T}function l(T,F){if(!(T instanceof F))throw new TypeError("Cannot call a class as a function")}function u(T,F){for(var w=0;w<F.length;w++){var B=F[w];B.enumerable=B.enumerable||!1,B.configurable=!0,"value"in B&&(B.writable=!0),Object.defineProperty(T,d(B.key),B)}}function d(T){var F=function(w,B){if(r(w)!="object"||!w)return w;var Y=w[Symbol.toPrimitive];if(Y!==void 0){var A=Y.call(w,B||"default");if(r(A)!="object")return A;throw new TypeError("@@toPrimitive must return a primitive value.")}return(B==="string"?String:Number)(w)}(T,"string");return r(F)=="symbol"?F:F+""}function h(T,F,w){return F=R(F),function(B,Y){if(Y&&(r(Y)=="object"||typeof Y=="function"))return Y;if(Y!==void 0)throw new TypeError("Derived constructors may only return object or undefined");return function(A){if(A===void 0)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return A}(B)}(T,function(){try{var B=!Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],function(){}))}catch{}return function(){return!!B}()}()?Reflect.construct(F,w||[],R(T).constructor):F.apply(T,w))}function R(T){return(R=Object.setPrototypeOf?Object.getPrototypeOf.bind():function(F){return F.__proto__||Object.getPrototypeOf(F)})(T)}function y(T,F){return(y=Object.setPrototypeOf?Object.setPrototypeOf.bind():function(w,B){return w.__proto__=B,w})(T,F)}var Q=n(4865),f=n(7500),S=n(4156).Stream,U=n(6155),b=n(1145).configure;e.exports=function(T){function F(){var A,L=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};return l(this,F),(A=h(this,F,[L])).options=L,A.name=L.name||"http",A.ssl=!!L.ssl,A.host=L.host||"localhost",A.port=L.port,A.auth=L.auth,A.path=L.path||"",A.maximumDepth=L.maximumDepth,A.agent=L.agent,A.headers=L.headers||{},A.headers["content-type"]="application/json",A.batch=L.batch||!1,A.batchInterval=L.batchInterval||5e3,A.batchCount=L.batchCount||10,A.batchOptions=[],A.batchTimeoutID=-1,A.batchCallback={},A.port||(A.port=A.ssl?443:80),A}return function(A,L){if(typeof L!="function"&&L!==null)throw new TypeError("Super expression must either be null or a function");A.prototype=Object.create(L&&L.prototype,{constructor:{value:A,writable:!0,configurable:!0}}),Object.defineProperty(A,"prototype",{writable:!1}),L&&y(A,L)}(F,T),w=F,(B=[{key:"log",value:function(A,L){var m=this;this._request(A,null,null,function(H,W){W&&W.statusCode!==200&&(H=new Error("Invalid HTTP Status Code: ".concat(W.statusCode))),H?m.emit("warn",H):m.emit("logged",A)}),L&&setImmediate(L)}},{key:"query",value:function(A,L){typeof A=="function"&&(L=A,A={});var m=(A={method:"query",params:this.normalizeQuery(A)}).params.auth||null;delete A.params.auth;var H=A.params.path||null;delete A.params.path,this._request(A,m,H,function(W,E,v){if(E&&E.statusCode!==200&&(W=new Error("Invalid HTTP Status Code: ".concat(E.statusCode))),W)return L(W);if(typeof v=="string")try{v=JSON.parse(v)}catch(k){return L(k)}L(null,v)})}},{key:"stream",value:function(){var A=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{},L=new S,m=(A={method:"stream",params:A}).params.path||null;delete A.params.path;var H=A.params.auth||null;delete A.params.auth;var W="",E=this._request(A,H,m);return L.destroy=function(){return E.destroy()},E.on("data",function(v){for(var k=(v=(W+v).split(/\n+/)).length-1,j=0;j<k;j++)try{L.emit("log",JSON.parse(v[j]))}catch(_){L.emit("error",_)}W=v[k]}),E.on("error",function(v){return L.emit("error",v)}),L}},{key:"_request",value:function(A,L,m,H){A=A||{},L=L||this.auth,m=m||this.path||"",this.batch?this._doBatch(A,H,L,m):this._doRequest(A,H,L,m)}},{key:"_doBatch",value:function(A,L,m,H){if(this.batchOptions.push(A),this.batchOptions.length===1){var W=this;this.batchCallback=L,this.batchTimeoutID=setTimeout(function(){W.batchTimeoutID=-1,W._doBatchRequest(W.batchCallback,m,H)},this.batchInterval)}this.batchOptions.length===this.batchCount&&this._doBatchRequest(this.batchCallback,m,H)}},{key:"_doBatchRequest",value:function(A,L,m){this.batchTimeoutID>0&&(clearTimeout(this.batchTimeoutID),this.batchTimeoutID=-1);var H=this.batchOptions.slice();this.batchOptions=[],this._doRequest(H,A,L,m)}},{key:"_doRequest",value:function(A,L,m,H){var W=Object.assign({},this.headers);m&&m.bearer&&(W.Authorization="Bearer ".concat(m.bearer));var E=(this.ssl?f:Q).request(s(s({},this.options),{},{method:"POST",host:this.host,port:this.port,path:"/".concat(H.replace(/^\//,"")),headers:W,auth:m&&m.username&&m.password?"".concat(m.username,":").concat(m.password):"",agent:this.agent}));E.on("error",L),E.on("response",function(k){return k.on("end",function(){return L(null,k)}).resume()});var v=b(s({},this.maximumDepth&&{maximumDepth:this.maximumDepth}));E.end(Buffer.from(v(A,this.options.replacer),"utf8"))}}])&&u(w.prototype,B),Y&&u(w,Y),Object.defineProperty(w,"prototype",{writable:!1}),w;var w,B,Y}(U)},3307:(e,t,n)=>{Object.defineProperty(t,"Console",{configurable:!0,enumerable:!0,get:function(){return n(810)}}),Object.defineProperty(t,"File",{configurable:!0,enumerable:!0,get:function(){return n(3329)}}),Object.defineProperty(t,"Http",{configurable:!0,enumerable:!0,get:function(){return n(7543)}}),Object.defineProperty(t,"Stream",{configurable:!0,enumerable:!0,get:function(){return n(4149)}})},4149:(e,t,n)=>{function r(f){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})(f)}function o(f,S){if(!(f instanceof S))throw new TypeError("Cannot call a class as a function")}function s(f,S){for(var U=0;U<S.length;U++){var b=S[U];b.enumerable=b.enumerable||!1,b.configurable=!0,"value"in b&&(b.writable=!0),Object.defineProperty(f,c(b.key),b)}}function c(f){var S=function(U,b){if(r(U)!="object"||!U)return U;var T=U[Symbol.toPrimitive];if(T!==void 0){var F=T.call(U,b||"default");if(r(F)!="object")return F;throw new TypeError("@@toPrimitive must return a primitive value.")}return(b==="string"?String:Number)(U)}(f,"string");return r(S)=="symbol"?S:S+""}function l(f,S,U){return S=u(S),function(b,T){if(T&&(r(T)=="object"||typeof T=="function"))return T;if(T!==void 0)throw new TypeError("Derived constructors may only return object or undefined");return function(F){if(F===void 0)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return F}(b)}(f,function(){try{var b=!Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],function(){}))}catch{}return function(){return!!b}()}()?Reflect.construct(S,U||[],u(f).constructor):S.apply(f,U))}function u(f){return(u=Object.setPrototypeOf?Object.getPrototypeOf.bind():function(S){return S.__proto__||Object.getPrototypeOf(S)})(f)}function d(f,S){return(d=Object.setPrototypeOf?Object.setPrototypeOf.bind():function(U,b){return U.__proto__=b,U})(f,S)}var h=n(6605),R=n(4966).MESSAGE,y=n(2213),Q=n(6155);e.exports=function(f){function S(){var F,w=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};if(o(this,S),F=l(this,S,[w]),!w.stream||!h(w.stream))throw new Error("options.stream is required.");return F._stream=w.stream,F._stream.setMaxListeners(1/0),F.isObjectMode=w.stream._writableState.objectMode,F.eol=typeof w.eol=="string"?w.eol:y.EOL,F}return function(F,w){if(typeof w!="function"&&w!==null)throw new TypeError("Super expression must either be null or a function");F.prototype=Object.create(w&&w.prototype,{constructor:{value:F,writable:!0,configurable:!0}}),Object.defineProperty(F,"prototype",{writable:!1}),w&&d(F,w)}(S,f),U=S,(b=[{key:"log",value:function(F,w){var B=this;if(setImmediate(function(){return B.emit("logged",F)}),this.isObjectMode)return this._stream.write(F),void(w&&w());this._stream.write("".concat(F[R]).concat(this.eol)),w&&w()}}])&&s(U.prototype,b),T&&s(U,T),Object.defineProperty(U,"prototype",{writable:!1}),U;var U,b,T}(Q)},3227:e=>{e.exports=function(){for(var n={},r=0;r<arguments.length;r++){var o=arguments[r];for(var s in o)t.call(o,s)&&(n[s]=o[s])}return n};var t=Object.prototype.hasOwnProperty},3804:(e,t,n)=>{const r={};r.web=n(5949),n(8052);const o={v1:{}};o.v1.signaling={},o.v1.signaling.api=n(4620),o.v1.signaling.api.SignalingClient=function(f,S,U){U||(U={}),U.format="text",this.client_=new r.web.GrpcWebClientBase(U),this.hostname_=f.replace(/\/+$/,"")},o.v1.signaling.api.SignalingPromiseClient=function(f,S,U){U||(U={}),U.format="text",this.client_=new r.web.GrpcWebClientBase(U),this.hostname_=f.replace(/\/+$/,"")};const s=new r.web.MethodDescriptor("/v1.signaling.api.Signaling/GetHealth",r.web.MethodType.UNARY,o.v1.signaling.api.GetHealthRequest,o.v1.signaling.api.GetHealthResponse,function(f){return f.serializeBinary()},o.v1.signaling.api.GetHealthResponse.deserializeBinary);o.v1.signaling.api.SignalingClient.prototype.getHealth=function(f,S,U){return this.client_.rpcCall(this.hostname_+"/v1.signaling.api.Signaling/GetHealth",f,S||{},s,U)},o.v1.signaling.api.SignalingPromiseClient.prototype.getHealth=function(f,S){return this.client_.unaryCall(this.hostname_+"/v1.signaling.api.Signaling/GetHealth",f,S||{},s)};const c=new r.web.MethodDescriptor("/v1.signaling.api.Signaling/CreatePeer",r.web.MethodType.UNARY,o.v1.signaling.api.CreatePeerRequest,o.v1.signaling.api.CreatePeerResponse,function(f){return f.serializeBinary()},o.v1.signaling.api.CreatePeerResponse.deserializeBinary);o.v1.signaling.api.SignalingClient.prototype.createPeer=function(f,S,U){return this.client_.rpcCall(this.hostname_+"/v1.signaling.api.Signaling/CreatePeer",f,S||{},c,U)},o.v1.signaling.api.SignalingPromiseClient.prototype.createPeer=function(f,S){return this.client_.unaryCall(this.hostname_+"/v1.signaling.api.Signaling/CreatePeer",f,S||{},c)};const l=new r.web.MethodDescriptor("/v1.signaling.api.Signaling/DeletePeer",r.web.MethodType.UNARY,o.v1.signaling.api.DeletePeerRequest,o.v1.signaling.api.DeletePeerResponse,function(f){return f.serializeBinary()},o.v1.signaling.api.DeletePeerResponse.deserializeBinary);o.v1.signaling.api.SignalingClient.prototype.deletePeer=function(f,S,U){return this.client_.rpcCall(this.hostname_+"/v1.signaling.api.Signaling/DeletePeer",f,S||{},l,U)},o.v1.signaling.api.SignalingPromiseClient.prototype.deletePeer=function(f,S){return this.client_.unaryCall(this.hostname_+"/v1.signaling.api.Signaling/DeletePeer",f,S||{},l)};const u=new r.web.MethodDescriptor("/v1.signaling.api.Signaling/RefreshPeer",r.web.MethodType.UNARY,o.v1.signaling.api.RefreshPeerRequest,o.v1.signaling.api.RefreshPeerResponse,function(f){return f.serializeBinary()},o.v1.signaling.api.RefreshPeerResponse.deserializeBinary);o.v1.signaling.api.SignalingClient.prototype.refreshPeer=function(f,S,U){return this.client_.rpcCall(this.hostname_+"/v1.signaling.api.Signaling/RefreshPeer",f,S||{},u,U)},o.v1.signaling.api.SignalingPromiseClient.prototype.refreshPeer=function(f,S){return this.client_.unaryCall(this.hostname_+"/v1.signaling.api.Signaling/RefreshPeer",f,S||{},u)};const d=new r.web.MethodDescriptor("/v1.signaling.api.Signaling/GetPeers",r.web.MethodType.UNARY,o.v1.signaling.api.GetPeersRequest,o.v1.signaling.api.GetPeersResponse,function(f){return f.serializeBinary()},o.v1.signaling.api.GetPeersResponse.deserializeBinary);o.v1.signaling.api.SignalingClient.prototype.getPeers=function(f,S,U){return this.client_.rpcCall(this.hostname_+"/v1.signaling.api.Signaling/GetPeers",f,S||{},d,U)},o.v1.signaling.api.SignalingPromiseClient.prototype.getPeers=function(f,S){return this.client_.unaryCall(this.hostname_+"/v1.signaling.api.Signaling/GetPeers",f,S||{},d)};const h=new r.web.MethodDescriptor("/v1.signaling.api.Signaling/GetIceServers",r.web.MethodType.UNARY,o.v1.signaling.api.GetIceServersRequest,o.v1.signaling.api.GetIceServersResponse,function(f){return f.serializeBinary()},o.v1.signaling.api.GetIceServersResponse.deserializeBinary);o.v1.signaling.api.SignalingClient.prototype.getIceServers=function(f,S,U){return this.client_.rpcCall(this.hostname_+"/v1.signaling.api.Signaling/GetIceServers",f,S||{},h,U)},o.v1.signaling.api.SignalingPromiseClient.prototype.getIceServers=function(f,S){return this.client_.unaryCall(this.hostname_+"/v1.signaling.api.Signaling/GetIceServers",f,S||{},h)};const R=new r.web.MethodDescriptor("/v1.signaling.api.Signaling/SendSignal",r.web.MethodType.UNARY,o.v1.signaling.api.SendSignalRequest,o.v1.signaling.api.SendSignalResponse,function(f){return f.serializeBinary()},o.v1.signaling.api.SendSignalResponse.deserializeBinary);o.v1.signaling.api.SignalingClient.prototype.sendSignal=function(f,S,U){return this.client_.rpcCall(this.hostname_+"/v1.signaling.api.Signaling/SendSignal",f,S||{},R,U)},o.v1.signaling.api.SignalingPromiseClient.prototype.sendSignal=function(f,S){return this.client_.unaryCall(this.hostname_+"/v1.signaling.api.Signaling/SendSignal",f,S||{},R)};const y=new r.web.MethodDescriptor("/v1.signaling.api.Signaling/ReceiveSignalStream",r.web.MethodType.SERVER_STREAMING,o.v1.signaling.api.ReceiveSignalStreamRequest,o.v1.signaling.api.ReceiveSignalStreamResponse,function(f){return f.serializeBinary()},o.v1.signaling.api.ReceiveSignalStreamResponse.deserializeBinary);o.v1.signaling.api.SignalingClient.prototype.receiveSignalStream=function(f,S){return this.client_.serverStreaming(this.hostname_+"/v1.signaling.api.Signaling/ReceiveSignalStream",f,S||{},y)},o.v1.signaling.api.SignalingPromiseClient.prototype.receiveSignalStream=function(f,S){return this.client_.serverStreaming(this.hostname_+"/v1.signaling.api.Signaling/ReceiveSignalStream",f,S||{},y)};const Q=new r.web.MethodDescriptor("/v1.signaling.api.Signaling/GetSessions",r.web.MethodType.UNARY,o.v1.signaling.api.GetSessionsRequest,o.v1.signaling.api.GetSessionsResponse,function(f){return f.serializeBinary()},o.v1.signaling.api.GetSessionsResponse.deserializeBinary);o.v1.signaling.api.SignalingClient.prototype.getSessions=function(f,S,U){return this.client_.rpcCall(this.hostname_+"/v1.signaling.api.Signaling/GetSessions",f,S||{},Q,U)},o.v1.signaling.api.SignalingPromiseClient.prototype.getSessions=function(f,S){return this.client_.unaryCall(this.hostname_+"/v1.signaling.api.Signaling/GetSessions",f,S||{},Q)},e.exports=o.v1.signaling.api},4620:(e,t,n)=>{var r=n(7186),o=r,s=typeof globalThis!="undefined"&&globalThis||typeof window!="undefined"&&window||s!==void 0&&s||typeof self!="undefined"&&self||function(){return this}.call(null)||Function("return this")(),c=n(8052);o.object.extend(proto,c),o.exportSymbol("proto.v1.signaling.api.CreatePeerRequest",null,s),o.exportSymbol("proto.v1.signaling.api.CreatePeerResponse",null,s),o.exportSymbol("proto.v1.signaling.api.DeletePeerRequest",null,s),o.exportSymbol("proto.v1.signaling.api.DeletePeerResponse",null,s),o.exportSymbol("proto.v1.signaling.api.GetHealthRequest",null,s),o.exportSymbol("proto.v1.signaling.api.GetHealthResponse",null,s),o.exportSymbol("proto.v1.signaling.api.GetIceServersRequest",null,s),o.exportSymbol("proto.v1.signaling.api.GetIceServersResponse",null,s),o.exportSymbol("proto.v1.signaling.api.GetPeersRequest",null,s),o.exportSymbol("proto.v1.signaling.api.GetPeersResponse",null,s),o.exportSymbol("proto.v1.signaling.api.GetSessionsRequest",null,s),o.exportSymbol("proto.v1.signaling.api.GetSessionsResponse",null,s),o.exportSymbol("proto.v1.signaling.api.Peer",null,s),o.exportSymbol("proto.v1.signaling.api.ReceiveSignalStreamRequest",null,s),o.exportSymbol("proto.v1.signaling.api.ReceiveSignalStreamResponse",null,s),o.exportSymbol("proto.v1.signaling.api.RefreshPeerRequest",null,s),o.exportSymbol("proto.v1.signaling.api.RefreshPeerResponse",null,s),o.exportSymbol("proto.v1.signaling.api.RtcSession",null,s),o.exportSymbol("proto.v1.signaling.api.SendSignalRequest",null,s),o.exportSymbol("proto.v1.signaling.api.SendSignalResponse",null,s),o.exportSymbol("proto.v1.signaling.api.SessionType",null,s),o.exportSymbol("proto.v1.signaling.api.Signal",null,s),proto.v1.signaling.api.Peer=function(l){r.Message.initialize(this,l,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(l){r.Message.initialize(this,l,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.RtcSession=function(l){r.Message.initialize(this,l,0,-1,null,null)},o.inherits(proto.v1.signaling.api.RtcSession,r.Message),o.DEBUG&&!COMPILED&&(proto.v1.signaling.api.RtcSession.displayName="proto.v1.signaling.api.RtcSession"),proto.v1.signaling.api.GetSessionsRequest=function(l){r.Message.initialize(this,l,0,-1,null,null)},o.inherits(proto.v1.signaling.api.GetSessionsRequest,r.Message),o.DEBUG&&!COMPILED&&(proto.v1.signaling.api.GetSessionsRequest.displayName="proto.v1.signaling.api.GetSessionsRequest"),proto.v1.signaling.api.GetSessionsResponse=function(l){r.Message.initialize(this,l,0,-1,proto.v1.signaling.api.GetSessionsResponse.repeatedFields_,null)},o.inherits(proto.v1.signaling.api.GetSessionsResponse,r.Message),o.DEBUG&&!COMPILED&&(proto.v1.signaling.api.GetSessionsResponse.displayName="proto.v1.signaling.api.GetSessionsResponse"),proto.v1.signaling.api.GetHealthRequest=function(l){r.Message.initialize(this,l,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(l){r.Message.initialize(this,l,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(l){r.Message.initialize(this,l,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(l){r.Message.initialize(this,l,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(l){r.Message.initialize(this,l,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(l){r.Message.initialize(this,l,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(l){r.Message.initialize(this,l,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(l){r.Message.initialize(this,l,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(l){r.Message.initialize(this,l,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(l){r.Message.initialize(this,l,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(l){r.Message.initialize(this,l,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(l){r.Message.initialize(this,l,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(l){r.Message.initialize(this,l,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(l){r.Message.initialize(this,l,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(l){r.Message.initialize(this,l,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(l){r.Message.initialize(this,l,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(l){return proto.v1.signaling.api.Peer.toObject(l,this)},proto.v1.signaling.api.Peer.toObject=function(l,u){var d,h={peerId:r.Message.getFieldWithDefault(u,1,""),organizationId:r.Message.getFieldWithDefault(u,2,""),userId:(d=u.getUserId())&&c.StringValue.toObject(l,d),deviceId:(d=u.getDeviceId())&&c.StringValue.toObject(l,d),sessionIdsList:(d=r.Message.getRepeatedField(u,5))==null?void 0:d,peerCreatedTimestamp:(d=u.getPeerCreatedTimestamp())&&c.Int64Value.toObject(l,d)};return l&&(h.$jspbMessageInstance=u),h}),proto.v1.signaling.api.Peer.deserializeBinary=function(l){var u=new r.BinaryReader(l),d=new proto.v1.signaling.api.Peer;return proto.v1.signaling.api.Peer.deserializeBinaryFromReader(d,u)},proto.v1.signaling.api.Peer.deserializeBinaryFromReader=function(l,u){for(;u.nextField()&&!u.isEndGroup();)switch(u.getFieldNumber()){case 1:var d=u.readString();l.setPeerId(d);break;case 2:d=u.readString(),l.setOrganizationId(d);break;case 3:d=new c.StringValue,u.readMessage(d,c.StringValue.deserializeBinaryFromReader),l.setUserId(d);break;case 4:d=new c.StringValue,u.readMessage(d,c.StringValue.deserializeBinaryFromReader),l.setDeviceId(d);break;case 5:d=u.readString(),l.addSessionIds(d);break;case 6:d=new c.Int64Value,u.readMessage(d,c.Int64Value.deserializeBinaryFromReader),l.setPeerCreatedTimestamp(d);break;default:u.skipField()}return l},proto.v1.signaling.api.Peer.prototype.serializeBinary=function(){var l=new r.BinaryWriter;return proto.v1.signaling.api.Peer.serializeBinaryToWriter(this,l),l.getResultBuffer()},proto.v1.signaling.api.Peer.serializeBinaryToWriter=function(l,u){var d=void 0;(d=l.getPeerId()).length>0&&u.writeString(1,d),(d=l.getOrganizationId()).length>0&&u.writeString(2,d),(d=l.getUserId())!=null&&u.writeMessage(3,d,c.StringValue.serializeBinaryToWriter),(d=l.getDeviceId())!=null&&u.writeMessage(4,d,c.StringValue.serializeBinaryToWriter),(d=l.getSessionIdsList()).length>0&&u.writeRepeatedString(5,d),(d=l.getPeerCreatedTimestamp())!=null&&u.writeMessage(6,d,c.Int64Value.serializeBinaryToWriter)},proto.v1.signaling.api.Peer.prototype.getPeerId=function(){return r.Message.getFieldWithDefault(this,1,"")},proto.v1.signaling.api.Peer.prototype.setPeerId=function(l){return r.Message.setProto3StringField(this,1,l)},proto.v1.signaling.api.Peer.prototype.getOrganizationId=function(){return r.Message.getFieldWithDefault(this,2,"")},proto.v1.signaling.api.Peer.prototype.setOrganizationId=function(l){return r.Message.setProto3StringField(this,2,l)},proto.v1.signaling.api.Peer.prototype.getUserId=function(){return r.Message.getWrapperField(this,c.StringValue,3)},proto.v1.signaling.api.Peer.prototype.setUserId=function(l){return r.Message.setWrapperField(this,3,l)},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,c.StringValue,4)},proto.v1.signaling.api.Peer.prototype.setDeviceId=function(l){return r.Message.setWrapperField(this,4,l)},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(l){return r.Message.setField(this,5,l||[])},proto.v1.signaling.api.Peer.prototype.addSessionIds=function(l,u){return r.Message.addToRepeatedField(this,5,l,u)},proto.v1.signaling.api.Peer.prototype.clearSessionIdsList=function(){return this.setSessionIdsList([])},proto.v1.signaling.api.Peer.prototype.getPeerCreatedTimestamp=function(){return r.Message.getWrapperField(this,c.Int64Value,6)},proto.v1.signaling.api.Peer.prototype.setPeerCreatedTimestamp=function(l){return r.Message.setWrapperField(this,6,l)},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(l){return proto.v1.signaling.api.Signal.toObject(l,this)},proto.v1.signaling.api.Signal.toObject=function(l,u){var d,h={sessionId:(d=u.getSessionId())&&c.StringValue.toObject(l,d),sessionCreatedTimestamp:(d=u.getSessionCreatedTimestamp())&&c.Int64Value.toObject(l,d),senderId:r.Message.getFieldWithDefault(u,3,""),receiverId:r.Message.getFieldWithDefault(u,4,""),payload:r.Message.getFieldWithDefault(u,5,""),iceServers:r.Message.getFieldWithDefault(u,6,""),iceTransportPolicy:r.Message.getFieldWithDefault(u,7,""),sessionType:r.Message.getFieldWithDefault(u,8,0)};return l&&(h.$jspbMessageInstance=u),h}),proto.v1.signaling.api.Signal.deserializeBinary=function(l){var u=new r.BinaryReader(l),d=new proto.v1.signaling.api.Signal;return proto.v1.signaling.api.Signal.deserializeBinaryFromReader(d,u)},proto.v1.signaling.api.Signal.deserializeBinaryFromReader=function(l,u){for(;u.nextField()&&!u.isEndGroup();)switch(u.getFieldNumber()){case 1:var d=new c.StringValue;u.readMessage(d,c.StringValue.deserializeBinaryFromReader),l.setSessionId(d);break;case 2:d=new c.Int64Value,u.readMessage(d,c.Int64Value.deserializeBinaryFromReader),l.setSessionCreatedTimestamp(d);break;case 3:d=u.readString(),l.setSenderId(d);break;case 4:d=u.readString(),l.setReceiverId(d);break;case 5:d=u.readString(),l.setPayload(d);break;case 6:d=u.readString(),l.setIceServers(d);break;case 7:d=u.readString(),l.setIceTransportPolicy(d);break;case 8:d=u.readEnum(),l.setSessionType(d);break;default:u.skipField()}return l},proto.v1.signaling.api.Signal.prototype.serializeBinary=function(){var l=new r.BinaryWriter;return proto.v1.signaling.api.Signal.serializeBinaryToWriter(this,l),l.getResultBuffer()},proto.v1.signaling.api.Signal.serializeBinaryToWriter=function(l,u){var d=void 0;(d=l.getSessionId())!=null&&u.writeMessage(1,d,c.StringValue.serializeBinaryToWriter),(d=l.getSessionCreatedTimestamp())!=null&&u.writeMessage(2,d,c.Int64Value.serializeBinaryToWriter),(d=l.getSenderId()).length>0&&u.writeString(3,d),(d=l.getReceiverId()).length>0&&u.writeString(4,d),(d=l.getPayload()).length>0&&u.writeString(5,d),(d=l.getIceServers()).length>0&&u.writeString(6,d),(d=l.getIceTransportPolicy()).length>0&&u.writeString(7,d),(d=l.getSessionType())!==0&&u.writeEnum(8,d)},proto.v1.signaling.api.Signal.prototype.getSessionId=function(){return r.Message.getWrapperField(this,c.StringValue,1)},proto.v1.signaling.api.Signal.prototype.setSessionId=function(l){return r.Message.setWrapperField(this,1,l)},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,c.Int64Value,2)},proto.v1.signaling.api.Signal.prototype.setSessionCreatedTimestamp=function(l){return r.Message.setWrapperField(this,2,l)},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(l){return r.Message.setProto3StringField(this,3,l)},proto.v1.signaling.api.Signal.prototype.getReceiverId=function(){return r.Message.getFieldWithDefault(this,4,"")},proto.v1.signaling.api.Signal.prototype.setReceiverId=function(l){return r.Message.setProto3StringField(this,4,l)},proto.v1.signaling.api.Signal.prototype.getPayload=function(){return r.Message.getFieldWithDefault(this,5,"")},proto.v1.signaling.api.Signal.prototype.setPayload=function(l){return r.Message.setProto3StringField(this,5,l)},proto.v1.signaling.api.Signal.prototype.getIceServers=function(){return r.Message.getFieldWithDefault(this,6,"")},proto.v1.signaling.api.Signal.prototype.setIceServers=function(l){return r.Message.setProto3StringField(this,6,l)},proto.v1.signaling.api.Signal.prototype.getIceTransportPolicy=function(){return r.Message.getFieldWithDefault(this,7,"")},proto.v1.signaling.api.Signal.prototype.setIceTransportPolicy=function(l){return r.Message.setProto3StringField(this,7,l)},proto.v1.signaling.api.Signal.prototype.getSessionType=function(){return r.Message.getFieldWithDefault(this,8,0)},proto.v1.signaling.api.Signal.prototype.setSessionType=function(l){return r.Message.setProto3EnumField(this,8,l)},r.Message.GENERATE_TO_OBJECT&&(proto.v1.signaling.api.RtcSession.prototype.toObject=function(l){return proto.v1.signaling.api.RtcSession.toObject(l,this)},proto.v1.signaling.api.RtcSession.toObject=function(l,u){var d={sessionId:r.Message.getFieldWithDefault(u,1,""),offerPeerId:r.Message.getFieldWithDefault(u,2,""),answerPeerId:r.Message.getFieldWithDefault(u,3,""),organizationId:r.Message.getFieldWithDefault(u,4,""),sessionType:r.Message.getFieldWithDefault(u,5,"")};return l&&(d.$jspbMessageInstance=u),d}),proto.v1.signaling.api.RtcSession.deserializeBinary=function(l){var u=new r.BinaryReader(l),d=new proto.v1.signaling.api.RtcSession;return proto.v1.signaling.api.RtcSession.deserializeBinaryFromReader(d,u)},proto.v1.signaling.api.RtcSession.deserializeBinaryFromReader=function(l,u){for(;u.nextField()&&!u.isEndGroup();)switch(u.getFieldNumber()){case 1:var d=u.readString();l.setSessionId(d);break;case 2:d=u.readString(),l.setOfferPeerId(d);break;case 3:d=u.readString(),l.setAnswerPeerId(d);break;case 4:d=u.readString(),l.setOrganizationId(d);break;case 5:d=u.readString(),l.setSessionType(d);break;default:u.skipField()}return l},proto.v1.signaling.api.RtcSession.prototype.serializeBinary=function(){var l=new r.BinaryWriter;return proto.v1.signaling.api.RtcSession.serializeBinaryToWriter(this,l),l.getResultBuffer()},proto.v1.signaling.api.RtcSession.serializeBinaryToWriter=function(l,u){var d=void 0;(d=l.getSessionId()).length>0&&u.writeString(1,d),(d=l.getOfferPeerId()).length>0&&u.writeString(2,d),(d=l.getAnswerPeerId()).length>0&&u.writeString(3,d),(d=l.getOrganizationId()).length>0&&u.writeString(4,d),(d=l.getSessionType()).length>0&&u.writeString(5,d)},proto.v1.signaling.api.RtcSession.prototype.getSessionId=function(){return r.Message.getFieldWithDefault(this,1,"")},proto.v1.signaling.api.RtcSession.prototype.setSessionId=function(l){return r.Message.setProto3StringField(this,1,l)},proto.v1.signaling.api.RtcSession.prototype.getOfferPeerId=function(){return r.Message.getFieldWithDefault(this,2,"")},proto.v1.signaling.api.RtcSession.prototype.setOfferPeerId=function(l){return r.Message.setProto3StringField(this,2,l)},proto.v1.signaling.api.RtcSession.prototype.getAnswerPeerId=function(){return r.Message.getFieldWithDefault(this,3,"")},proto.v1.signaling.api.RtcSession.prototype.setAnswerPeerId=function(l){return r.Message.setProto3StringField(this,3,l)},proto.v1.signaling.api.RtcSession.prototype.getOrganizationId=function(){return r.Message.getFieldWithDefault(this,4,"")},proto.v1.signaling.api.RtcSession.prototype.setOrganizationId=function(l){return r.Message.setProto3StringField(this,4,l)},proto.v1.signaling.api.RtcSession.prototype.getSessionType=function(){return r.Message.getFieldWithDefault(this,5,"")},proto.v1.signaling.api.RtcSession.prototype.setSessionType=function(l){return r.Message.setProto3StringField(this,5,l)},r.Message.GENERATE_TO_OBJECT&&(proto.v1.signaling.api.GetSessionsRequest.prototype.toObject=function(l){return proto.v1.signaling.api.GetSessionsRequest.toObject(l,this)},proto.v1.signaling.api.GetSessionsRequest.toObject=function(l,u){var d={};return l&&(d.$jspbMessageInstance=u),d}),proto.v1.signaling.api.GetSessionsRequest.deserializeBinary=function(l){var u=new r.BinaryReader(l),d=new proto.v1.signaling.api.GetSessionsRequest;return proto.v1.signaling.api.GetSessionsRequest.deserializeBinaryFromReader(d,u)},proto.v1.signaling.api.GetSessionsRequest.deserializeBinaryFromReader=function(l,u){for(;u.nextField()&&!u.isEndGroup();)u.getFieldNumber(),u.skipField();return l},proto.v1.signaling.api.GetSessionsRequest.prototype.serializeBinary=function(){var l=new r.BinaryWriter;return proto.v1.signaling.api.GetSessionsRequest.serializeBinaryToWriter(this,l),l.getResultBuffer()},proto.v1.signaling.api.GetSessionsRequest.serializeBinaryToWriter=function(l,u){},proto.v1.signaling.api.GetSessionsResponse.repeatedFields_=[1],r.Message.GENERATE_TO_OBJECT&&(proto.v1.signaling.api.GetSessionsResponse.prototype.toObject=function(l){return proto.v1.signaling.api.GetSessionsResponse.toObject(l,this)},proto.v1.signaling.api.GetSessionsResponse.toObject=function(l,u){var d={sessionsList:r.Message.toObjectList(u.getSessionsList(),proto.v1.signaling.api.RtcSession.toObject,l)};return l&&(d.$jspbMessageInstance=u),d}),proto.v1.signaling.api.GetSessionsResponse.deserializeBinary=function(l){var u=new r.BinaryReader(l),d=new proto.v1.signaling.api.GetSessionsResponse;return proto.v1.signaling.api.GetSessionsResponse.deserializeBinaryFromReader(d,u)},proto.v1.signaling.api.GetSessionsResponse.deserializeBinaryFromReader=function(l,u){for(;u.nextField()&&!u.isEndGroup();)switch(u.getFieldNumber()){case 1:var d=new proto.v1.signaling.api.RtcSession;u.readMessage(d,proto.v1.signaling.api.RtcSession.deserializeBinaryFromReader),l.addSessions(d);break;default:u.skipField()}return l},proto.v1.signaling.api.GetSessionsResponse.prototype.serializeBinary=function(){var l=new r.BinaryWriter;return proto.v1.signaling.api.GetSessionsResponse.serializeBinaryToWriter(this,l),l.getResultBuffer()},proto.v1.signaling.api.GetSessionsResponse.serializeBinaryToWriter=function(l,u){var d;(d=l.getSessionsList()).length>0&&u.writeRepeatedMessage(1,d,proto.v1.signaling.api.RtcSession.serializeBinaryToWriter)},proto.v1.signaling.api.GetSessionsResponse.prototype.getSessionsList=function(){return r.Message.getRepeatedWrapperField(this,proto.v1.signaling.api.RtcSession,1)},proto.v1.signaling.api.GetSessionsResponse.prototype.setSessionsList=function(l){return r.Message.setRepeatedWrapperField(this,1,l)},proto.v1.signaling.api.GetSessionsResponse.prototype.addSessions=function(l,u){return r.Message.addToRepeatedWrapperField(this,1,l,proto.v1.signaling.api.RtcSession,u)},proto.v1.signaling.api.GetSessionsResponse.prototype.clearSessionsList=function(){return this.setSessionsList([])},r.Message.GENERATE_TO_OBJECT&&(proto.v1.signaling.api.GetHealthRequest.prototype.toObject=function(l){return proto.v1.signaling.api.GetHealthRequest.toObject(l,this)},proto.v1.signaling.api.GetHealthRequest.toObject=function(l,u){var d={};return l&&(d.$jspbMessageInstance=u),d}),proto.v1.signaling.api.GetHealthRequest.deserializeBinary=function(l){var u=new r.BinaryReader(l),d=new proto.v1.signaling.api.GetHealthRequest;return proto.v1.signaling.api.GetHealthRequest.deserializeBinaryFromReader(d,u)},proto.v1.signaling.api.GetHealthRequest.deserializeBinaryFromReader=function(l,u){for(;u.nextField()&&!u.isEndGroup();)u.getFieldNumber(),u.skipField();return l},proto.v1.signaling.api.GetHealthRequest.prototype.serializeBinary=function(){var l=new r.BinaryWriter;return proto.v1.signaling.api.GetHealthRequest.serializeBinaryToWriter(this,l),l.getResultBuffer()},proto.v1.signaling.api.GetHealthRequest.serializeBinaryToWriter=function(l,u){},r.Message.GENERATE_TO_OBJECT&&(proto.v1.signaling.api.GetHealthResponse.prototype.toObject=function(l){return proto.v1.signaling.api.GetHealthResponse.toObject(l,this)},proto.v1.signaling.api.GetHealthResponse.toObject=function(l,u){var d={version:r.Message.getFieldWithDefault(u,1,"")};return l&&(d.$jspbMessageInstance=u),d}),proto.v1.signaling.api.GetHealthResponse.deserializeBinary=function(l){var u=new r.BinaryReader(l),d=new proto.v1.signaling.api.GetHealthResponse;return proto.v1.signaling.api.GetHealthResponse.deserializeBinaryFromReader(d,u)},proto.v1.signaling.api.GetHealthResponse.deserializeBinaryFromReader=function(l,u){for(;u.nextField()&&!u.isEndGroup();)switch(u.getFieldNumber()){case 1:var d=u.readString();l.setVersion(d);break;default:u.skipField()}return l},proto.v1.signaling.api.GetHealthResponse.prototype.serializeBinary=function(){var l=new r.BinaryWriter;return proto.v1.signaling.api.GetHealthResponse.serializeBinaryToWriter(this,l),l.getResultBuffer()},proto.v1.signaling.api.GetHealthResponse.serializeBinaryToWriter=function(l,u){var d;(d=l.getVersion()).length>0&&u.writeString(1,d)},proto.v1.signaling.api.GetHealthResponse.prototype.getVersion=function(){return r.Message.getFieldWithDefault(this,1,"")},proto.v1.signaling.api.GetHealthResponse.prototype.setVersion=function(l){return r.Message.setProto3StringField(this,1,l)},r.Message.GENERATE_TO_OBJECT&&(proto.v1.signaling.api.CreatePeerRequest.prototype.toObject=function(l){return proto.v1.signaling.api.CreatePeerRequest.toObject(l,this)},proto.v1.signaling.api.CreatePeerRequest.toObject=function(l,u){var d={};return l&&(d.$jspbMessageInstance=u),d}),proto.v1.signaling.api.CreatePeerRequest.deserializeBinary=function(l){var u=new r.BinaryReader(l),d=new proto.v1.signaling.api.CreatePeerRequest;return proto.v1.signaling.api.CreatePeerRequest.deserializeBinaryFromReader(d,u)},proto.v1.signaling.api.CreatePeerRequest.deserializeBinaryFromReader=function(l,u){for(;u.nextField()&&!u.isEndGroup();)u.getFieldNumber(),u.skipField();return l},proto.v1.signaling.api.CreatePeerRequest.prototype.serializeBinary=function(){var l=new r.BinaryWriter;return proto.v1.signaling.api.CreatePeerRequest.serializeBinaryToWriter(this,l),l.getResultBuffer()},proto.v1.signaling.api.CreatePeerRequest.serializeBinaryToWriter=function(l,u){},r.Message.GENERATE_TO_OBJECT&&(proto.v1.signaling.api.CreatePeerResponse.prototype.toObject=function(l){return proto.v1.signaling.api.CreatePeerResponse.toObject(l,this)},proto.v1.signaling.api.CreatePeerResponse.toObject=function(l,u){var d,h={peer:(d=u.getPeer())&&proto.v1.signaling.api.Peer.toObject(l,d)};return l&&(h.$jspbMessageInstance=u),h}),proto.v1.signaling.api.CreatePeerResponse.deserializeBinary=function(l){var u=new r.BinaryReader(l),d=new proto.v1.signaling.api.CreatePeerResponse;return proto.v1.signaling.api.CreatePeerResponse.deserializeBinaryFromReader(d,u)},proto.v1.signaling.api.CreatePeerResponse.deserializeBinaryFromReader=function(l,u){for(;u.nextField()&&!u.isEndGroup();)switch(u.getFieldNumber()){case 1:var d=new proto.v1.signaling.api.Peer;u.readMessage(d,proto.v1.signaling.api.Peer.deserializeBinaryFromReader),l.setPeer(d);break;default:u.skipField()}return l},proto.v1.signaling.api.CreatePeerResponse.prototype.serializeBinary=function(){var l=new r.BinaryWriter;return proto.v1.signaling.api.CreatePeerResponse.serializeBinaryToWriter(this,l),l.getResultBuffer()},proto.v1.signaling.api.CreatePeerResponse.serializeBinaryToWriter=function(l,u){var d;(d=l.getPeer())!=null&&u.writeMessage(1,d,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(l){return r.Message.setWrapperField(this,1,l)},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(l){return proto.v1.signaling.api.DeletePeerRequest.toObject(l,this)},proto.v1.signaling.api.DeletePeerRequest.toObject=function(l,u){var d={peerId:r.Message.getFieldWithDefault(u,1,"")};return l&&(d.$jspbMessageInstance=u),d}),proto.v1.signaling.api.DeletePeerRequest.deserializeBinary=function(l){var u=new r.BinaryReader(l),d=new proto.v1.signaling.api.DeletePeerRequest;return proto.v1.signaling.api.DeletePeerRequest.deserializeBinaryFromReader(d,u)},proto.v1.signaling.api.DeletePeerRequest.deserializeBinaryFromReader=function(l,u){for(;u.nextField()&&!u.isEndGroup();)switch(u.getFieldNumber()){case 1:var d=u.readString();l.setPeerId(d);break;default:u.skipField()}return l},proto.v1.signaling.api.DeletePeerRequest.prototype.serializeBinary=function(){var l=new r.BinaryWriter;return proto.v1.signaling.api.DeletePeerRequest.serializeBinaryToWriter(this,l),l.getResultBuffer()},proto.v1.signaling.api.DeletePeerRequest.serializeBinaryToWriter=function(l,u){var d;(d=l.getPeerId()).length>0&&u.writeString(1,d)},proto.v1.signaling.api.DeletePeerRequest.prototype.getPeerId=function(){return r.Message.getFieldWithDefault(this,1,"")},proto.v1.signaling.api.DeletePeerRequest.prototype.setPeerId=function(l){return r.Message.setProto3StringField(this,1,l)},r.Message.GENERATE_TO_OBJECT&&(proto.v1.signaling.api.DeletePeerResponse.prototype.toObject=function(l){return proto.v1.signaling.api.DeletePeerResponse.toObject(l,this)},proto.v1.signaling.api.DeletePeerResponse.toObject=function(l,u){var d={};return l&&(d.$jspbMessageInstance=u),d}),proto.v1.signaling.api.DeletePeerResponse.deserializeBinary=function(l){var u=new r.BinaryReader(l),d=new proto.v1.signaling.api.DeletePeerResponse;return proto.v1.signaling.api.DeletePeerResponse.deserializeBinaryFromReader(d,u)},proto.v1.signaling.api.DeletePeerResponse.deserializeBinaryFromReader=function(l,u){for(;u.nextField()&&!u.isEndGroup();)u.getFieldNumber(),u.skipField();return l},proto.v1.signaling.api.DeletePeerResponse.prototype.serializeBinary=function(){var l=new r.BinaryWriter;return proto.v1.signaling.api.DeletePeerResponse.serializeBinaryToWriter(this,l),l.getResultBuffer()},proto.v1.signaling.api.DeletePeerResponse.serializeBinaryToWriter=function(l,u){},r.Message.GENERATE_TO_OBJECT&&(proto.v1.signaling.api.RefreshPeerRequest.prototype.toObject=function(l){return proto.v1.signaling.api.RefreshPeerRequest.toObject(l,this)},proto.v1.signaling.api.RefreshPeerRequest.toObject=function(l,u){var d,h={peer:(d=u.getPeer())&&proto.v1.signaling.api.Peer.toObject(l,d)};return l&&(h.$jspbMessageInstance=u),h}),proto.v1.signaling.api.RefreshPeerRequest.deserializeBinary=function(l){var u=new r.BinaryReader(l),d=new proto.v1.signaling.api.RefreshPeerRequest;return proto.v1.signaling.api.RefreshPeerRequest.deserializeBinaryFromReader(d,u)},proto.v1.signaling.api.RefreshPeerRequest.deserializeBinaryFromReader=function(l,u){for(;u.nextField()&&!u.isEndGroup();)switch(u.getFieldNumber()){case 1:var d=new proto.v1.signaling.api.Peer;u.readMessage(d,proto.v1.signaling.api.Peer.deserializeBinaryFromReader),l.setPeer(d);break;default:u.skipField()}return l},proto.v1.signaling.api.RefreshPeerRequest.prototype.serializeBinary=function(){var l=new r.BinaryWriter;return proto.v1.signaling.api.RefreshPeerRequest.serializeBinaryToWriter(this,l),l.getResultBuffer()},proto.v1.signaling.api.RefreshPeerRequest.serializeBinaryToWriter=function(l,u){var d;(d=l.getPeer())!=null&&u.writeMessage(1,d,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(l){return r.Message.setWrapperField(this,1,l)},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(l){return proto.v1.signaling.api.RefreshPeerResponse.toObject(l,this)},proto.v1.signaling.api.RefreshPeerResponse.toObject=function(l,u){var d={};return l&&(d.$jspbMessageInstance=u),d}),proto.v1.signaling.api.RefreshPeerResponse.deserializeBinary=function(l){var u=new r.BinaryReader(l),d=new proto.v1.signaling.api.RefreshPeerResponse;return proto.v1.signaling.api.RefreshPeerResponse.deserializeBinaryFromReader(d,u)},proto.v1.signaling.api.RefreshPeerResponse.deserializeBinaryFromReader=function(l,u){for(;u.nextField()&&!u.isEndGroup();)u.getFieldNumber(),u.skipField();return l},proto.v1.signaling.api.RefreshPeerResponse.prototype.serializeBinary=function(){var l=new r.BinaryWriter;return proto.v1.signaling.api.RefreshPeerResponse.serializeBinaryToWriter(this,l),l.getResultBuffer()},proto.v1.signaling.api.RefreshPeerResponse.serializeBinaryToWriter=function(l,u){},r.Message.GENERATE_TO_OBJECT&&(proto.v1.signaling.api.GetPeersRequest.prototype.toObject=function(l){return proto.v1.signaling.api.GetPeersRequest.toObject(l,this)},proto.v1.signaling.api.GetPeersRequest.toObject=function(l,u){var d={};return l&&(d.$jspbMessageInstance=u),d}),proto.v1.signaling.api.GetPeersRequest.deserializeBinary=function(l){var u=new r.BinaryReader(l),d=new proto.v1.signaling.api.GetPeersRequest;return proto.v1.signaling.api.GetPeersRequest.deserializeBinaryFromReader(d,u)},proto.v1.signaling.api.GetPeersRequest.deserializeBinaryFromReader=function(l,u){for(;u.nextField()&&!u.isEndGroup();)u.getFieldNumber(),u.skipField();return l},proto.v1.signaling.api.GetPeersRequest.prototype.serializeBinary=function(){var l=new r.BinaryWriter;return proto.v1.signaling.api.GetPeersRequest.serializeBinaryToWriter(this,l),l.getResultBuffer()},proto.v1.signaling.api.GetPeersRequest.serializeBinaryToWriter=function(l,u){},proto.v1.signaling.api.GetPeersResponse.repeatedFields_=[1],r.Message.GENERATE_TO_OBJECT&&(proto.v1.signaling.api.GetPeersResponse.prototype.toObject=function(l){return proto.v1.signaling.api.GetPeersResponse.toObject(l,this)},proto.v1.signaling.api.GetPeersResponse.toObject=function(l,u){var d={peersList:r.Message.toObjectList(u.getPeersList(),proto.v1.signaling.api.Peer.toObject,l)};return l&&(d.$jspbMessageInstance=u),d}),proto.v1.signaling.api.GetPeersResponse.deserializeBinary=function(l){var u=new r.BinaryReader(l),d=new proto.v1.signaling.api.GetPeersResponse;return proto.v1.signaling.api.GetPeersResponse.deserializeBinaryFromReader(d,u)},proto.v1.signaling.api.GetPeersResponse.deserializeBinaryFromReader=function(l,u){for(;u.nextField()&&!u.isEndGroup();)switch(u.getFieldNumber()){case 1:var d=new proto.v1.signaling.api.Peer;u.readMessage(d,proto.v1.signaling.api.Peer.deserializeBinaryFromReader),l.addPeers(d);break;default:u.skipField()}return l},proto.v1.signaling.api.GetPeersResponse.prototype.serializeBinary=function(){var l=new r.BinaryWriter;return proto.v1.signaling.api.GetPeersResponse.serializeBinaryToWriter(this,l),l.getResultBuffer()},proto.v1.signaling.api.GetPeersResponse.serializeBinaryToWriter=function(l,u){var d;(d=l.getPeersList()).length>0&&u.writeRepeatedMessage(1,d,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(l){return r.Message.setRepeatedWrapperField(this,1,l)},proto.v1.signaling.api.GetPeersResponse.prototype.addPeers=function(l,u){return r.Message.addToRepeatedWrapperField(this,1,l,proto.v1.signaling.api.Peer,u)},proto.v1.signaling.api.GetPeersResponse.prototype.clearPeersList=function(){return this.setPeersList([])},r.Message.GENERATE_TO_OBJECT&&(proto.v1.signaling.api.GetIceServersRequest.prototype.toObject=function(l){return proto.v1.signaling.api.GetIceServersRequest.toObject(l,this)},proto.v1.signaling.api.GetIceServersRequest.toObject=function(l,u){var d={};return l&&(d.$jspbMessageInstance=u),d}),proto.v1.signaling.api.GetIceServersRequest.deserializeBinary=function(l){var u=new r.BinaryReader(l),d=new proto.v1.signaling.api.GetIceServersRequest;return proto.v1.signaling.api.GetIceServersRequest.deserializeBinaryFromReader(d,u)},proto.v1.signaling.api.GetIceServersRequest.deserializeBinaryFromReader=function(l,u){for(;u.nextField()&&!u.isEndGroup();)u.getFieldNumber(),u.skipField();return l},proto.v1.signaling.api.GetIceServersRequest.prototype.serializeBinary=function(){var l=new r.BinaryWriter;return proto.v1.signaling.api.GetIceServersRequest.serializeBinaryToWriter(this,l),l.getResultBuffer()},proto.v1.signaling.api.GetIceServersRequest.serializeBinaryToWriter=function(l,u){},r.Message.GENERATE_TO_OBJECT&&(proto.v1.signaling.api.GetIceServersResponse.prototype.toObject=function(l){return proto.v1.signaling.api.GetIceServersResponse.toObject(l,this)},proto.v1.signaling.api.GetIceServersResponse.toObject=function(l,u){var d={iceServers:r.Message.getFieldWithDefault(u,1,"")};return l&&(d.$jspbMessageInstance=u),d}),proto.v1.signaling.api.GetIceServersResponse.deserializeBinary=function(l){var u=new r.BinaryReader(l),d=new proto.v1.signaling.api.GetIceServersResponse;return proto.v1.signaling.api.GetIceServersResponse.deserializeBinaryFromReader(d,u)},proto.v1.signaling.api.GetIceServersResponse.deserializeBinaryFromReader=function(l,u){for(;u.nextField()&&!u.isEndGroup();)switch(u.getFieldNumber()){case 1:var d=u.readString();l.setIceServers(d);break;default:u.skipField()}return l},proto.v1.signaling.api.GetIceServersResponse.prototype.serializeBinary=function(){var l=new r.BinaryWriter;return proto.v1.signaling.api.GetIceServersResponse.serializeBinaryToWriter(this,l),l.getResultBuffer()},proto.v1.signaling.api.GetIceServersResponse.serializeBinaryToWriter=function(l,u){var d;(d=l.getIceServers()).length>0&&u.writeString(1,d)},proto.v1.signaling.api.GetIceServersResponse.prototype.getIceServers=function(){return r.Message.getFieldWithDefault(this,1,"")},proto.v1.signaling.api.GetIceServersResponse.prototype.setIceServers=function(l){return r.Message.setProto3StringField(this,1,l)},r.Message.GENERATE_TO_OBJECT&&(proto.v1.signaling.api.SendSignalRequest.prototype.toObject=function(l){return proto.v1.signaling.api.SendSignalRequest.toObject(l,this)},proto.v1.signaling.api.SendSignalRequest.toObject=function(l,u){var d,h={signal:(d=u.getSignal())&&proto.v1.signaling.api.Signal.toObject(l,d)};return l&&(h.$jspbMessageInstance=u),h}),proto.v1.signaling.api.SendSignalRequest.deserializeBinary=function(l){var u=new r.BinaryReader(l),d=new proto.v1.signaling.api.SendSignalRequest;return proto.v1.signaling.api.SendSignalRequest.deserializeBinaryFromReader(d,u)},proto.v1.signaling.api.SendSignalRequest.deserializeBinaryFromReader=function(l,u){for(;u.nextField()&&!u.isEndGroup();)switch(u.getFieldNumber()){case 1:var d=new proto.v1.signaling.api.Signal;u.readMessage(d,proto.v1.signaling.api.Signal.deserializeBinaryFromReader),l.setSignal(d);break;default:u.skipField()}return l},proto.v1.signaling.api.SendSignalRequest.prototype.serializeBinary=function(){var l=new r.BinaryWriter;return proto.v1.signaling.api.SendSignalRequest.serializeBinaryToWriter(this,l),l.getResultBuffer()},proto.v1.signaling.api.SendSignalRequest.serializeBinaryToWriter=function(l,u){var d;(d=l.getSignal())!=null&&u.writeMessage(1,d,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(l){return r.Message.setWrapperField(this,1,l)},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(l){return proto.v1.signaling.api.SendSignalResponse.toObject(l,this)},proto.v1.signaling.api.SendSignalResponse.toObject=function(l,u){var d,h={sessionId:(d=u.getSessionId())&&c.StringValue.toObject(l,d),sessionCreatedTimestamp:(d=u.getSessionCreatedTimestamp())&&c.Int64Value.toObject(l,d)};return l&&(h.$jspbMessageInstance=u),h}),proto.v1.signaling.api.SendSignalResponse.deserializeBinary=function(l){var u=new r.BinaryReader(l),d=new proto.v1.signaling.api.SendSignalResponse;return proto.v1.signaling.api.SendSignalResponse.deserializeBinaryFromReader(d,u)},proto.v1.signaling.api.SendSignalResponse.deserializeBinaryFromReader=function(l,u){for(;u.nextField()&&!u.isEndGroup();)switch(u.getFieldNumber()){case 1:var d=new c.StringValue;u.readMessage(d,c.StringValue.deserializeBinaryFromReader),l.setSessionId(d);break;case 2:d=new c.Int64Value,u.readMessage(d,c.Int64Value.deserializeBinaryFromReader),l.setSessionCreatedTimestamp(d);break;default:u.skipField()}return l},proto.v1.signaling.api.SendSignalResponse.prototype.serializeBinary=function(){var l=new r.BinaryWriter;return proto.v1.signaling.api.SendSignalResponse.serializeBinaryToWriter(this,l),l.getResultBuffer()},proto.v1.signaling.api.SendSignalResponse.serializeBinaryToWriter=function(l,u){var d=void 0;(d=l.getSessionId())!=null&&u.writeMessage(1,d,c.StringValue.serializeBinaryToWriter),(d=l.getSessionCreatedTimestamp())!=null&&u.writeMessage(2,d,c.Int64Value.serializeBinaryToWriter)},proto.v1.signaling.api.SendSignalResponse.prototype.getSessionId=function(){return r.Message.getWrapperField(this,c.StringValue,1)},proto.v1.signaling.api.SendSignalResponse.prototype.setSessionId=function(l){return r.Message.setWrapperField(this,1,l)},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,c.Int64Value,2)},proto.v1.signaling.api.SendSignalResponse.prototype.setSessionCreatedTimestamp=function(l){return r.Message.setWrapperField(this,2,l)},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(l){return proto.v1.signaling.api.ReceiveSignalStreamRequest.toObject(l,this)},proto.v1.signaling.api.ReceiveSignalStreamRequest.toObject=function(l,u){var d={peerId:r.Message.getFieldWithDefault(u,1,"")};return l&&(d.$jspbMessageInstance=u),d}),proto.v1.signaling.api.ReceiveSignalStreamRequest.deserializeBinary=function(l){var u=new r.BinaryReader(l),d=new proto.v1.signaling.api.ReceiveSignalStreamRequest;return proto.v1.signaling.api.ReceiveSignalStreamRequest.deserializeBinaryFromReader(d,u)},proto.v1.signaling.api.ReceiveSignalStreamRequest.deserializeBinaryFromReader=function(l,u){for(;u.nextField()&&!u.isEndGroup();)switch(u.getFieldNumber()){case 1:var d=u.readString();l.setPeerId(d);break;default:u.skipField()}return l},proto.v1.signaling.api.ReceiveSignalStreamRequest.prototype.serializeBinary=function(){var l=new r.BinaryWriter;return proto.v1.signaling.api.ReceiveSignalStreamRequest.serializeBinaryToWriter(this,l),l.getResultBuffer()},proto.v1.signaling.api.ReceiveSignalStreamRequest.serializeBinaryToWriter=function(l,u){var d;(d=l.getPeerId()).length>0&&u.writeString(1,d)},proto.v1.signaling.api.ReceiveSignalStreamRequest.prototype.getPeerId=function(){return r.Message.getFieldWithDefault(this,1,"")},proto.v1.signaling.api.ReceiveSignalStreamRequest.prototype.setPeerId=function(l){return r.Message.setProto3StringField(this,1,l)},r.Message.GENERATE_TO_OBJECT&&(proto.v1.signaling.api.ReceiveSignalStreamResponse.prototype.toObject=function(l){return proto.v1.signaling.api.ReceiveSignalStreamResponse.toObject(l,this)},proto.v1.signaling.api.ReceiveSignalStreamResponse.toObject=function(l,u){var d,h={signal:(d=u.getSignal())&&proto.v1.signaling.api.Signal.toObject(l,d)};return l&&(h.$jspbMessageInstance=u),h}),proto.v1.signaling.api.ReceiveSignalStreamResponse.deserializeBinary=function(l){var u=new r.BinaryReader(l),d=new proto.v1.signaling.api.ReceiveSignalStreamResponse;return proto.v1.signaling.api.ReceiveSignalStreamResponse.deserializeBinaryFromReader(d,u)},proto.v1.signaling.api.ReceiveSignalStreamResponse.deserializeBinaryFromReader=function(l,u){for(;u.nextField()&&!u.isEndGroup();)switch(u.getFieldNumber()){case 1:var d=new proto.v1.signaling.api.Signal;u.readMessage(d,proto.v1.signaling.api.Signal.deserializeBinaryFromReader),l.setSignal(d);break;default:u.skipField()}return l},proto.v1.signaling.api.ReceiveSignalStreamResponse.prototype.serializeBinary=function(){var l=new r.BinaryWriter;return proto.v1.signaling.api.ReceiveSignalStreamResponse.serializeBinaryToWriter(this,l),l.getResultBuffer()},proto.v1.signaling.api.ReceiveSignalStreamResponse.serializeBinaryToWriter=function(l,u){var d;(d=l.getSignal())!=null&&u.writeMessage(1,d,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(l){return r.Message.setWrapperField(this,1,l)},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,HEADLESS:4},o.object.extend(t,proto.v1.signaling.api)},3449:(e,t,n)=>{const r={...n(4620),...n(3804)};e.exports=r},6973:()=>{},3011:()=>{},3951:()=>{},9256:()=>{},2627:()=>{},4834:(e,t,n)=>{var r=n(9501),o=typeof globalThis=="undefined"?n.g:globalThis;e.exports=function(){for(var s=[],c=0;c<r.length;c++)typeof o[r[c]]=="function"&&(s[s.length]=r[c]);return s}},7241:e=>{e.exports={version:"3.14.2"}}},__webpack_module_cache__={};function __webpack_require__(e){var t=__webpack_module_cache__[e];if(t!==void 0)return t.exports;var n=__webpack_module_cache__[e]={id:e,loaded:!1,exports:{}};return __webpack_modules__[e].call(n.exports,n,n.exports,__webpack_require__),n.loaded=!0,n.exports}__webpack_require__.n=e=>{var t=e&&e.__esModule?()=>e.default:()=>e;return __webpack_require__.d(t,{a:t}),t},__webpack_require__.d=(e,t)=>{for(var n in t)__webpack_require__.o(t,n)&&!__webpack_require__.o(e,n)&&Object.defineProperty(e,n,{enumerable:!0,get:t[n]})},__webpack_require__.g=function(){if(typeof globalThis=="object")return globalThis;try{return this||new Function("return this")()}catch{if(typeof window=="object")return window}}(),__webpack_require__.o=(e,t)=>Object.prototype.hasOwnProperty.call(e,t),__webpack_require__.r=e=>{typeof Symbol!="undefined"&&Symbol.toStringTag&&Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(e,"__esModule",{value:!0})},__webpack_require__.nmd=e=>(e.paths=[],e.children||(e.children=[]),e);var __webpack_exports__={};return(()=>{__webpack_require__.r(__webpack_exports__),__webpack_require__.d(__webpack_exports__,{AuthClient:()=>n,Credentials:()=>z,RtcClient:()=>Lt,RtcClientV1:()=>Ge,RtcSignalingClient:()=>ce,SignalingPromiseClient:()=>re.SignalingPromiseClient,createRtcStreamMessage:()=>bt});var e=__webpack_require__(6331),t=function(Ee,N,C,G){return new(C||(C=Promise))(function(Z,pe){function Ue(Se){try{Re(G.next(Se))}catch(fe){pe(fe)}}function ve(Se){try{Re(G.throw(Se))}catch(fe){pe(fe)}}function Re(Se){var fe;Se.done?Z(Se.value):(fe=Se.value,fe instanceof C?fe:new C(function(p){p(fe)})).then(Ue,ve)}Re((G=G.apply(Ee,N||[])).next())})};class n extends e.S{adminSignup(N,C){return t(this,void 0,void 0,function*(){return yield this.fetch("auth/admin-signup",{token:C,method:"POST",body:N})})}login(N){return t(this,void 0,void 0,function*(){return yield this.fetch("auth/login",{method:"POST",body:N,allowUnsafeRetries:!0})})}loginWithGoogleToken(N){return t(this,void 0,void 0,function*(){return yield this.fetch("auth/login-google",{method:"POST",body:N,allowUnsafeRetries:!0})})}refresh(N,C){return t(this,void 0,void 0,function*(){return yield this.fetch("auth/refresh",{method:"POST",body:{refreshToken:N,tokenExpirationSeconds:C},allowUnsafeRetries:!0})})}respondToNewPasswordRequiredChallenge(N){return t(this,void 0,void 0,function*(){return yield this.fetch("auth/respond-to-new-password-required-challenge",{method:"POST",body:N})})}forgotPassword(N){return t(this,void 0,void 0,function*(){return yield this.fetch("auth/forgot-password",{method:"POST",body:{email:N}})})}confirmForgotPassword(N){return t(this,void 0,void 0,function*(){return yield this.fetch("auth/confirm-forgot-password",{method:"POST",body:N})})}resendInvitation(N){return t(this,void 0,void 0,function*(){return yield this.fetch("auth/resend-invitation",{method:"POST",body:{email:N}})})}changePassword(N){return t(this,arguments,void 0,function*({token:C,refreshToken:G,currentPassword:Z,newPassword:pe}){return yield this.fetch("auth/change-password",{token:C,method:"POST",body:{refreshToken:G,currentPassword:Z,newPassword:pe}})})}getDeviceCredentials(N){return t(this,void 0,void 0,function*(){return yield this.fetch("auth/device-credentials",{token:N,method:"POST",allowUnsafeRetries:!0})})}impersonate(N,C){return t(this,void 0,void 0,function*(){return yield this.fetch("auth/impersonate",{token:N,method:"POST",allowUnsafeRetries:!0,body:{userId:C}})})}createServiceAccount(N,C,G,Z,pe){return t(this,void 0,void 0,function*(){return yield this.fetch("auth/service-account",{token:N,method:"POST",allowUnsafeRetries:!0,body:{name:C,roleId:G,tags:Z,description:pe}})})}getFeatures(N){return t(this,void 0,void 0,function*(){return(yield this.fetch("auth/features",{token:N})).features})}checkSso(N,C){return t(this,void 0,void 0,function*(){return yield this.fetch("auth/check-sso",{method:"POST",body:{email:N,allowUserAutoCreation:C}})})}loginWithSso(N,C){return t(this,void 0,void 0,function*(){return yield this.fetch("auth/login-sso",{method:"POST",body:{token:N,refreshToken:C}})})}}var r=__webpack_require__(3778),o=__webpack_require__(7221),s=__webpack_require__(6075),c=__webpack_require__.n(s);const l=typeof performance=="object"&&performance&&typeof performance.now=="function"?performance:Date,u=typeof AbortController=="function"?AbortController:class{constructor(){this.signal=new R}abort(Ee=new Error("This operation was aborted")){this.signal.reason=this.signal.reason||Ee,this.signal.aborted=!0,this.signal.dispatchEvent({type:"abort",target:this.signal})}},d=typeof AbortSignal=="function",h=typeof u.AbortSignal=="function",R=d?AbortSignal:h?u.AbortController:class{constructor(){this.reason=void 0,this.aborted=!1,this._listeners=[]}dispatchEvent(Ee){Ee.type==="abort"&&(this.aborted=!0,this.onabort(Ee),this._listeners.forEach(N=>N(Ee),this))}onabort(){}addEventListener(Ee,N){Ee==="abort"&&this._listeners.push(N)}removeEventListener(Ee,N){Ee==="abort"&&(this._listeners=this._listeners.filter(C=>C!==N))}},y=new Set,Q=(Ee,N)=>{const C="LRU_CACHE_OPTION_"+Ee;U(C)&&b(C,Ee+" option","options."+N,Y)},f=(Ee,N)=>{const C="LRU_CACHE_METHOD_"+Ee;if(U(C)){const{prototype:G}=Y,{get:Z}=Object.getOwnPropertyDescriptor(G,Ee);b(C,Ee+" method",`cache.${N}()`,Z)}},S=(...Ee)=>{typeof process=="object"&&process&&typeof process.emitWarning=="function"?process.emitWarning(...Ee):console.error(...Ee)},U=Ee=>!y.has(Ee),b=(Ee,N,C,G)=>{y.add(Ee),S(`The ${N} is deprecated. Please use ${C} instead.`,"DeprecationWarning",Ee,G)},T=Ee=>Ee&&Ee===Math.floor(Ee)&&Ee>0&&isFinite(Ee),F=Ee=>T(Ee)?Ee<=Math.pow(2,8)?Uint8Array:Ee<=Math.pow(2,16)?Uint16Array:Ee<=Math.pow(2,32)?Uint32Array:Ee<=Number.MAX_SAFE_INTEGER?w:null:null;class w extends Array{constructor(N){super(N),this.fill(0)}}class B{constructor(N){if(N===0)return[];const C=F(N);this.heap=new C(N),this.length=0}push(N){this.heap[this.length++]=N}pop(){return this.heap[--this.length]}}class Y{constructor(N={}){const{max:C=0,ttl:G,ttlResolution:Z=1,ttlAutopurge:pe,updateAgeOnGet:Ue,updateAgeOnHas:ve,allowStale:Re,dispose:Se,disposeAfter:fe,noDisposeOnSet:p,noUpdateTTL:g,maxSize:V=0,maxEntrySize:X=0,sizeCalculation:ue,fetchMethod:be,fetchContext:Ce,noDeleteOnFetchRejection:Ae,noDeleteOnStaleGet:Le,allowStaleOnFetchRejection:Ke,allowStaleOnFetchAbort:at,ignoreFetchAbort:gt}=N,{length:Ut,maxAge:it,stale:lt}=N instanceof Y?{}:N;if(C!==0&&!T(C))throw new TypeError("max option must be a nonnegative integer");const _t=C?F(C):Array;if(!_t)throw new Error("invalid max value: "+C);if(this.max=C,this.maxSize=V,this.maxEntrySize=X||this.maxSize,this.sizeCalculation=ue||Ut,this.sizeCalculation){if(!this.maxSize&&!this.maxEntrySize)throw new TypeError("cannot set sizeCalculation without setting maxSize or maxEntrySize");if(typeof this.sizeCalculation!="function")throw new TypeError("sizeCalculation set to non-function")}if(this.fetchMethod=be||null,this.fetchMethod&&typeof this.fetchMethod!="function")throw new TypeError("fetchMethod must be a function if specified");if(this.fetchContext=Ce,!this.fetchMethod&&Ce!==void 0)throw new TypeError("cannot set fetchContext without fetchMethod");if(this.keyMap=new Map,this.keyList=new Array(C).fill(null),this.valList=new Array(C).fill(null),this.next=new _t(C),this.prev=new _t(C),this.head=0,this.tail=0,this.free=new B(C),this.initialFill=1,this.size=0,typeof Se=="function"&&(this.dispose=Se),typeof fe=="function"?(this.disposeAfter=fe,this.disposed=[]):(this.disposeAfter=null,this.disposed=null),this.noDisposeOnSet=!!p,this.noUpdateTTL=!!g,this.noDeleteOnFetchRejection=!!Ae,this.allowStaleOnFetchRejection=!!Ke,this.allowStaleOnFetchAbort=!!at,this.ignoreFetchAbort=!!gt,this.maxEntrySize!==0){if(this.maxSize!==0&&!T(this.maxSize))throw new TypeError("maxSize must be a positive integer if specified");if(!T(this.maxEntrySize))throw new TypeError("maxEntrySize must be a positive integer if specified");this.initializeSizeTracking()}if(this.allowStale=!!Re||!!lt,this.noDeleteOnStaleGet=!!Le,this.updateAgeOnGet=!!Ue,this.updateAgeOnHas=!!ve,this.ttlResolution=T(Z)||Z===0?Z:1,this.ttlAutopurge=!!pe,this.ttl=G||it||0,this.ttl){if(!T(this.ttl))throw new TypeError("ttl must be a positive integer if specified");this.initializeTTLTracking()}if(this.max===0&&this.ttl===0&&this.maxSize===0)throw new TypeError("At least one of max, maxSize, or ttl is required");if(!this.ttlAutopurge&&!this.max&&!this.maxSize){const At="LRU_CACHE_UNBOUNDED";U(At)&&(y.add(At),S("TTL caching without ttlAutopurge, max, or maxSize can result in unbounded memory consumption.","UnboundedCacheWarning",At,Y))}lt&&Q("stale","allowStale"),it&&Q("maxAge","ttl"),Ut&&Q("length","sizeCalculation")}getRemainingTTL(N){return this.has(N,{updateAgeOnHas:!1})?1/0:0}initializeTTLTracking(){this.ttls=new w(this.max),this.starts=new w(this.max),this.setItemTTL=(G,Z,pe=l.now())=>{if(this.starts[G]=Z!==0?pe:0,this.ttls[G]=Z,Z!==0&&this.ttlAutopurge){const Ue=setTimeout(()=>{this.isStale(G)&&this.delete(this.keyList[G])},Z+1);Ue.unref&&Ue.unref()}},this.updateItemAge=G=>{this.starts[G]=this.ttls[G]!==0?l.now():0},this.statusTTL=(G,Z)=>{G&&(G.ttl=this.ttls[Z],G.start=this.starts[Z],G.now=N||C(),G.remainingTTL=G.now+G.ttl-G.start)};let N=0;const C=()=>{const G=l.now();if(this.ttlResolution>0){N=G;const Z=setTimeout(()=>N=0,this.ttlResolution);Z.unref&&Z.unref()}return G};this.getRemainingTTL=G=>{const Z=this.keyMap.get(G);return Z===void 0?0:this.ttls[Z]===0||this.starts[Z]===0?1/0:this.starts[Z]+this.ttls[Z]-(N||C())},this.isStale=G=>this.ttls[G]!==0&&this.starts[G]!==0&&(N||C())-this.starts[G]>this.ttls[G]}updateItemAge(N){}statusTTL(N,C){}setItemTTL(N,C,G){}isStale(N){return!1}initializeSizeTracking(){this.calculatedSize=0,this.sizes=new w(this.max),this.removeItemSize=N=>{this.calculatedSize-=this.sizes[N],this.sizes[N]=0},this.requireSize=(N,C,G,Z)=>{if(this.isBackgroundFetch(C))return 0;if(!T(G)){if(!Z)throw new TypeError("invalid size value (must be positive integer). When maxSize or maxEntrySize is used, sizeCalculation or size must be set.");if(typeof Z!="function")throw new TypeError("sizeCalculation must be a function");if(G=Z(C,N),!T(G))throw new TypeError("sizeCalculation return invalid (expect positive integer)")}return G},this.addItemSize=(N,C,G)=>{if(this.sizes[N]=C,this.maxSize){const Z=this.maxSize-this.sizes[N];for(;this.calculatedSize>Z;)this.evict(!0)}this.calculatedSize+=this.sizes[N],G&&(G.entrySize=C,G.totalCalculatedSize=this.calculatedSize)}}removeItemSize(N){}addItemSize(N,C){}requireSize(N,C,G,Z){if(G||Z)throw new TypeError("cannot set size without setting maxSize or maxEntrySize on cache")}*indexes({allowStale:N=this.allowStale}={}){if(this.size)for(let C=this.tail;this.isValidIndex(C)&&(!N&&this.isStale(C)||(yield C),C!==this.head);)C=this.prev[C]}*rindexes({allowStale:N=this.allowStale}={}){if(this.size)for(let C=this.head;this.isValidIndex(C)&&(!N&&this.isStale(C)||(yield C),C!==this.tail);)C=this.next[C]}isValidIndex(N){return N!==void 0&&this.keyMap.get(this.keyList[N])===N}*entries(){for(const N of this.indexes())this.valList[N]===void 0||this.keyList[N]===void 0||this.isBackgroundFetch(this.valList[N])||(yield[this.keyList[N],this.valList[N]])}*rentries(){for(const N of this.rindexes())this.valList[N]===void 0||this.keyList[N]===void 0||this.isBackgroundFetch(this.valList[N])||(yield[this.keyList[N],this.valList[N]])}*keys(){for(const N of this.indexes())this.keyList[N]===void 0||this.isBackgroundFetch(this.valList[N])||(yield this.keyList[N])}*rkeys(){for(const N of this.rindexes())this.keyList[N]===void 0||this.isBackgroundFetch(this.valList[N])||(yield this.keyList[N])}*values(){for(const N of this.indexes())this.valList[N]===void 0||this.isBackgroundFetch(this.valList[N])||(yield this.valList[N])}*rvalues(){for(const N of this.rindexes())this.valList[N]===void 0||this.isBackgroundFetch(this.valList[N])||(yield this.valList[N])}[Symbol.iterator](){return this.entries()}find(N,C){for(const G of this.indexes()){const Z=this.valList[G],pe=this.isBackgroundFetch(Z)?Z.__staleWhileFetching:Z;if(pe!==void 0&&N(pe,this.keyList[G],this))return this.get(this.keyList[G],C)}}forEach(N,C=this){for(const G of this.indexes()){const Z=this.valList[G],pe=this.isBackgroundFetch(Z)?Z.__staleWhileFetching:Z;pe!==void 0&&N.call(C,pe,this.keyList[G],this)}}rforEach(N,C=this){for(const G of this.rindexes()){const Z=this.valList[G],pe=this.isBackgroundFetch(Z)?Z.__staleWhileFetching:Z;pe!==void 0&&N.call(C,pe,this.keyList[G],this)}}get prune(){return f("prune","purgeStale"),this.purgeStale}purgeStale(){let N=!1;for(const C of this.rindexes({allowStale:!0}))this.isStale(C)&&(this.delete(this.keyList[C]),N=!0);return N}dump(){const N=[];for(const C of this.indexes({allowStale:!0})){const G=this.keyList[C],Z=this.valList[C],pe=this.isBackgroundFetch(Z)?Z.__staleWhileFetching:Z;if(pe===void 0)continue;const Ue={value:pe};if(this.ttls){Ue.ttl=this.ttls[C];const ve=l.now()-this.starts[C];Ue.start=Math.floor(Date.now()-ve)}this.sizes&&(Ue.size=this.sizes[C]),N.unshift([G,Ue])}return N}load(N){this.clear();for(const[C,G]of N){if(G.start){const Z=Date.now()-G.start;G.start=l.now()-Z}this.set(C,G.value,G)}}dispose(N,C,G){}set(N,C,{ttl:G=this.ttl,start:Z,noDisposeOnSet:pe=this.noDisposeOnSet,size:Ue=0,sizeCalculation:ve=this.sizeCalculation,noUpdateTTL:Re=this.noUpdateTTL,status:Se}={}){if(Ue=this.requireSize(N,C,Ue,ve),this.maxEntrySize&&Ue>this.maxEntrySize)return Se&&(Se.set="miss",Se.maxEntrySizeExceeded=!0),this.delete(N),this;let fe=this.size===0?void 0:this.keyMap.get(N);if(fe===void 0)fe=this.newIndex(),this.keyList[fe]=N,this.valList[fe]=C,this.keyMap.set(N,fe),this.next[this.tail]=fe,this.prev[fe]=this.tail,this.tail=fe,this.size++,this.addItemSize(fe,Ue,Se),Se&&(Se.set="add"),Re=!1;else{this.moveToTail(fe);const p=this.valList[fe];if(C!==p){if(this.isBackgroundFetch(p)?p.__abortController.abort(new Error("replaced")):pe||(this.dispose(p,N,"set"),this.disposeAfter&&this.disposed.push([p,N,"set"])),this.removeItemSize(fe),this.valList[fe]=C,this.addItemSize(fe,Ue,Se),Se){Se.set="replace";const g=p&&this.isBackgroundFetch(p)?p.__staleWhileFetching:p;g!==void 0&&(Se.oldValue=g)}}else Se&&(Se.set="update")}if(G===0||this.ttl!==0||this.ttls||this.initializeTTLTracking(),Re||this.setItemTTL(fe,G,Z),this.statusTTL(Se,fe),this.disposeAfter)for(;this.disposed.length;)this.disposeAfter(...this.disposed.shift());return this}newIndex(){return this.size===0?this.tail:this.size===this.max&&this.max!==0?this.evict(!1):this.free.length!==0?this.free.pop():this.initialFill++}pop(){if(this.size){const N=this.valList[this.head];return this.evict(!0),N}}evict(N){const C=this.head,G=this.keyList[C],Z=this.valList[C];return this.isBackgroundFetch(Z)?Z.__abortController.abort(new Error("evicted")):(this.dispose(Z,G,"evict"),this.disposeAfter&&this.disposed.push([Z,G,"evict"])),this.removeItemSize(C),N&&(this.keyList[C]=null,this.valList[C]=null,this.free.push(C)),this.head=this.next[C],this.keyMap.delete(G),this.size--,C}has(N,{updateAgeOnHas:C=this.updateAgeOnHas,status:G}={}){const Z=this.keyMap.get(N);if(Z!==void 0){if(!this.isStale(Z))return C&&this.updateItemAge(Z),G&&(G.has="hit"),this.statusTTL(G,Z),!0;G&&(G.has="stale",this.statusTTL(G,Z))}else G&&(G.has="miss");return!1}peek(N,{allowStale:C=this.allowStale}={}){const G=this.keyMap.get(N);if(G!==void 0&&(C||!this.isStale(G))){const Z=this.valList[G];return this.isBackgroundFetch(Z)?Z.__staleWhileFetching:Z}}backgroundFetch(N,C,G,Z){const pe=C===void 0?void 0:this.valList[C];if(this.isBackgroundFetch(pe))return pe;const Ue=new u;G.signal&&G.signal.addEventListener("abort",()=>Ue.abort(G.signal.reason));const ve={signal:Ue.signal,options:G,context:Z},Re=(p,g=!1)=>{const{aborted:V}=Ue.signal,X=G.ignoreFetchAbort&&p!==void 0;return G.status&&(V&&!g?(G.status.fetchAborted=!0,G.status.fetchError=Ue.signal.reason,X&&(G.status.fetchAbortIgnored=!0)):G.status.fetchResolved=!0),!V||X||g?(this.valList[C]===fe&&(p===void 0?fe.__staleWhileFetching?this.valList[C]=fe.__staleWhileFetching:this.delete(N):(G.status&&(G.status.fetchUpdated=!0),this.set(N,p,ve.options))),p):Se(Ue.signal.reason)},Se=p=>{const{aborted:g}=Ue.signal,V=g&&G.allowStaleOnFetchAbort,X=V||G.allowStaleOnFetchRejection,ue=X||G.noDeleteOnFetchRejection;if(this.valList[C]===fe&&(!ue||fe.__staleWhileFetching===void 0?this.delete(N):V||(this.valList[C]=fe.__staleWhileFetching)),X)return G.status&&fe.__staleWhileFetching!==void 0&&(G.status.returnedStale=!0),fe.__staleWhileFetching;if(fe.__returned===fe)throw p};G.status&&(G.status.fetchDispatched=!0);const fe=new Promise((p,g)=>{this.fetchMethod(N,pe,ve).then(V=>p(V),g),Ue.signal.addEventListener("abort",()=>{G.ignoreFetchAbort&&!G.allowStaleOnFetchAbort||(p(),G.allowStaleOnFetchAbort&&(p=V=>Re(V,!0)))})}).then(Re,p=>(G.status&&(G.status.fetchRejected=!0,G.status.fetchError=p),Se(p)));return fe.__abortController=Ue,fe.__staleWhileFetching=pe,fe.__returned=null,C===void 0?(this.set(N,fe,{...ve.options,status:void 0}),C=this.keyMap.get(N)):this.valList[C]=fe,fe}isBackgroundFetch(N){return N&&typeof N=="object"&&typeof N.then=="function"&&Object.prototype.hasOwnProperty.call(N,"__staleWhileFetching")&&Object.prototype.hasOwnProperty.call(N,"__returned")&&(N.__returned===N||N.__returned===null)}async fetch(N,{allowStale:C=this.allowStale,updateAgeOnGet:G=this.updateAgeOnGet,noDeleteOnStaleGet:Z=this.noDeleteOnStaleGet,ttl:pe=this.ttl,noDisposeOnSet:Ue=this.noDisposeOnSet,size:ve=0,sizeCalculation:Re=this.sizeCalculation,noUpdateTTL:Se=this.noUpdateTTL,noDeleteOnFetchRejection:fe=this.noDeleteOnFetchRejection,allowStaleOnFetchRejection:p=this.allowStaleOnFetchRejection,ignoreFetchAbort:g=this.ignoreFetchAbort,allowStaleOnFetchAbort:V=this.allowStaleOnFetchAbort,fetchContext:X=this.fetchContext,forceRefresh:ue=!1,status:be,signal:Ce}={}){if(!this.fetchMethod)return be&&(be.fetch="get"),this.get(N,{allowStale:C,updateAgeOnGet:G,noDeleteOnStaleGet:Z,status:be});const Ae={allowStale:C,updateAgeOnGet:G,noDeleteOnStaleGet:Z,ttl:pe,noDisposeOnSet:Ue,size:ve,sizeCalculation:Re,noUpdateTTL:Se,noDeleteOnFetchRejection:fe,allowStaleOnFetchRejection:p,allowStaleOnFetchAbort:V,ignoreFetchAbort:g,status:be,signal:Ce};let Le=this.keyMap.get(N);if(Le===void 0){be&&(be.fetch="miss");const Ke=this.backgroundFetch(N,Le,Ae,X);return Ke.__returned=Ke}{const Ke=this.valList[Le];if(this.isBackgroundFetch(Ke)){const lt=C&&Ke.__staleWhileFetching!==void 0;return be&&(be.fetch="inflight",lt&&(be.returnedStale=!0)),lt?Ke.__staleWhileFetching:Ke.__returned=Ke}const at=this.isStale(Le);if(!ue&&!at)return be&&(be.fetch="hit"),this.moveToTail(Le),G&&this.updateItemAge(Le),this.statusTTL(be,Le),Ke;const gt=this.backgroundFetch(N,Le,Ae,X),Ut=gt.__staleWhileFetching!==void 0,it=Ut&&C;return be&&(be.fetch=Ut&&at?"stale":"refresh",it&&at&&(be.returnedStale=!0)),it?gt.__staleWhileFetching:gt.__returned=gt}}get(N,{allowStale:C=this.allowStale,updateAgeOnGet:G=this.updateAgeOnGet,noDeleteOnStaleGet:Z=this.noDeleteOnStaleGet,status:pe}={}){const Ue=this.keyMap.get(N);if(Ue!==void 0){const ve=this.valList[Ue],Re=this.isBackgroundFetch(ve);return this.statusTTL(pe,Ue),this.isStale(Ue)?(pe&&(pe.get="stale"),Re?(pe&&(pe.returnedStale=C&&ve.__staleWhileFetching!==void 0),C?ve.__staleWhileFetching:void 0):(Z||this.delete(N),pe&&(pe.returnedStale=C),C?ve:void 0)):(pe&&(pe.get="hit"),Re?ve.__staleWhileFetching:(this.moveToTail(Ue),G&&this.updateItemAge(Ue),ve))}pe&&(pe.get="miss")}connect(N,C){this.prev[C]=N,this.next[N]=C}moveToTail(N){N!==this.tail&&(N===this.head?this.head=this.next[N]:this.connect(this.prev[N],this.next[N]),this.connect(this.tail,N),this.tail=N)}get del(){return f("del","delete"),this.delete}delete(N){let C=!1;if(this.size!==0){const G=this.keyMap.get(N);if(G!==void 0)if(C=!0,this.size===1)this.clear();else{this.removeItemSize(G);const Z=this.valList[G];this.isBackgroundFetch(Z)?Z.__abortController.abort(new Error("deleted")):(this.dispose(Z,N,"delete"),this.disposeAfter&&this.disposed.push([Z,N,"delete"])),this.keyMap.delete(N),this.keyList[G]=null,this.valList[G]=null,G===this.tail?this.tail=this.prev[G]:G===this.head?this.head=this.next[G]:(this.next[this.prev[G]]=this.next[G],this.prev[this.next[G]]=this.prev[G]),this.size--,this.free.push(G)}}if(this.disposed)for(;this.disposed.length;)this.disposeAfter(...this.disposed.shift());return C}clear(){for(const N of this.rindexes({allowStale:!0})){const C=this.valList[N];if(this.isBackgroundFetch(C))C.__abortController.abort(new Error("deleted"));else{const G=this.keyList[N];this.dispose(C,G,"delete"),this.disposeAfter&&this.disposed.push([C,G,"delete"])}}if(this.keyMap.clear(),this.valList.fill(null),this.keyList.fill(null),this.ttls&&(this.ttls.fill(0),this.starts.fill(0)),this.sizes&&this.sizes.fill(0),this.head=0,this.tail=0,this.initialFill=1,this.free.length=0,this.calculatedSize=0,this.size=0,this.disposed)for(;this.disposed.length;)this.disposeAfter(...this.disposed.shift())}get reset(){return f("reset","clear"),this.clear}get length(){return((N,C)=>{const G="LRU_CACHE_PROPERTY_"+N;if(U(G)){const{prototype:Z}=Y,{get:pe}=Object.getOwnPropertyDescriptor(Z,N);b(G,N+" property","cache."+C,pe)}})("length","size"),this.size}static get AbortController(){return u}static get AbortSignal(){return R}}const A=Y;var L=__webpack_require__(2273),m=__webpack_require__(1597),H=function(Ee,N,C,G){return new(C||(C=Promise))(function(Z,pe){function Ue(Se){try{Re(G.next(Se))}catch(fe){pe(fe)}}function ve(Se){try{Re(G.throw(Se))}catch(fe){pe(fe)}}function Re(Se){var fe;Se.done?Z(Se.value):(fe=Se.value,fe instanceof C?fe:new C(function(p){p(fe)})).then(Ue,ve)}Re((G=G.apply(Ee,N||[])).next())})};class W extends class{constructor(N,C){this.type=N,this.name=C}}{constructor(N){super("simple","LogReporter"),this.message=N}send(N){return H(this,void 0,void 0,function*(){var C,G;m.vF.debug(this.message,(C=N.reduce((Z,pe)=>Object.assign(Object.assign({},Z),{[pe.name]:pe.stat}),{}),G=Z=>{const{sum:pe,count:Ue}=Z,ve=pe/Ue;return Object.assign(Object.assign({},Z),{average:ve})},Object.keys(C).reduce((Z,pe)=>Object.assign(Object.assign({},Z),{[pe]:G(C[pe])}),{})))})}}var E=__webpack_require__(8758),v=__webpack_require__.n(E);const k=/^[a-zA-Z0-9-_.,:?'"()@\/#$+ ]{1,255}$/;function j(Ee,N){return!!Ee&&(N!=null&&N.allowStar&&Ee[0]==="*"?Ee==="*":k.test(Ee))}var _=function(Ee,N,C,G){return new(C||(C=Promise))(function(Z,pe){function Ue(Se){try{Re(G.next(Se))}catch(fe){pe(fe)}}function ve(Se){try{Re(G.throw(Se))}catch(fe){pe(fe)}}function Re(Se){var fe;Se.done?Z(Se.value):(fe=Se.value,fe instanceof C?fe:new C(function(p){p(fe)})).then(Ue,ve)}Re((G=G.apply(Ee,N||[])).next())})};function M({func:Ee,delay:N,immediate:C=!0}){let G=!1,Z=setTimeout(function Ue(){return _(this,void 0,void 0,function*(){if(G)return;const ve=new Date().getTime();try{pe=Ee(),yield pe}finally{if(!G){const Re=new Date().getTime();Z=setTimeout(Ue,Math.max(N-(Re-ve),0))}}})},C?0:N),pe=Promise.resolve();return{stop(){return _(this,void 0,void 0,function*(){G=!0,clearTimeout(Z),yield pe})},pending(){return _(this,void 0,void 0,function*(){yield pe})}}}var $=function(Ee,N,C,G){return new(C||(C=Promise))(function(Z,pe){function Ue(Se){try{Re(G.next(Se))}catch(fe){pe(fe)}}function ve(Se){try{Re(G.throw(Se))}catch(fe){pe(fe)}}function Re(Se){var fe;Se.done?Z(Se.value):(fe=Se.value,fe instanceof C?fe:new C(function(p){p(fe)})).then(Ue,ve)}Re((G=G.apply(Ee,N||[])).next())})};class te{constructor(N){this.buffer={},this.reporters=[],this.flushInterval=M({func:()=>this.flushStats(),delay:te.samplePeriodMs}),this.tags=this.filterTags((N==null?void 0:N.tags)||{app:L.yA,version:L.rE,namespace:L.MF})}shutdown(){return $(this,void 0,void 0,function*(){yield this.flushInterval.stop(),yield this.flushStats(),yield(0,o.c)(2*r.p.second)})}aggregate(N,C,G){this.addToBuffer(this.buffer,this.encodeKey({metric:N,tags:this.filterTags(G||{})}),typeof C=="number"?{min:C,max:C,sum:C,count:1}:C)}increment(N,C){this.aggregate(N,1,C)}timer(N,C,G){return $(this,void 0,void 0,function*(){const Z=v()(),pe=yield C(),Ue=v()();return this.aggregate(N,Ue-Z,G),pe})}registerStatsReporter(N){this.reporters.push(N)}setTag(N,C){const G=this.filterTags({[N]:C});this.tags=Object.assign(Object.assign({},this.tags),G)}addToBuffer(N,C,G){if(N[C]){const{min:Z,max:pe,sum:Ue,count:ve}=N[C];N[C]={min:Math.min(Z,G.min),max:Math.max(pe,G.max),sum:Ue+G.sum,count:ve+G.count}}else N[C]=G}write(N){return $(this,void 0,void 0,function*(){yield Promise.all(this.reporters.map(C=>$(this,void 0,void 0,function*(){let G;const Z={};switch(C.type){case"simple":for(const[Ue,ve]of Object.entries(N)){const{metric:Re}=this.decodeKey(Ue);this.addToBuffer(Z,this.encodeKey({metric:Re}),ve)}G=Z;break;case"tagged":G=N;break;default:(function(Ue){throw new Error(`Unreachable type encountered (${Ue})`)})(C.type)}const pe=Object.entries(G);if(pe.length>0)return C.send(pe.map(([Ue,ve])=>{const{metric:Re,tags:Se}=this.decodeKey(Ue);return{name:Re,tags:Object.assign(Object.assign({},Se),this.tags),stat:ve}}),te.samplePeriodMs).catch(Ue=>{m.vF.debug("Failed to write stats to "+C.name,{error:Ue})})})))})}flushStats(){return $(this,void 0,void 0,function*(){yield this.write(this.buffer),this.buffer={}})}encodeKey(N){return c()(Object.assign(Object.assign({},N),Object.keys(N.tags||{}).length>0?{tags:N.tags}:{}))}decodeKey(N){return JSON.parse(N)}filterTags(N){return Object.entries(N||{}).reduce((C,[G,Z])=>(j(G)&&j(Z)&&(C[G]=Z),C),{})}}te.samplePeriodMs=5*r.p.minute;const P=!!L.op,q=new te;P||["local","on-prem"].includes(L.MF)||q.registerStatsReporter(new W("stats"));var ie=function(Ee,N,C,G){return new(C||(C=Promise))(function(Z,pe){function Ue(Se){try{Re(G.next(Se))}catch(fe){pe(fe)}}function ve(Se){try{Re(G.throw(Se))}catch(fe){pe(fe)}}function Re(Se){var fe;Se.done?Z(Se.value):(fe=Se.value,fe instanceof C?fe:new C(function(p){p(fe)})).then(Ue,ve)}Re((G=G.apply(Ee,N||[])).next())})};class ee extends class{constructor(N){this.options=N,this.cache=new A(Object.assign(Object.assign(Object.assign({},N.dispose||N.disposeAfter?{ttlAutopurge:!0}:{}),N),{dispose:(...C)=>{var G;C[2]==="evict"&&q.increment("lru-eviction",{name:N.name}),(G=N.dispose)===null||G===void 0||G.call(N,...C)},disposeAfter:(...C)=>{var G;this.updateStats(),(G=N.disposeAfter)===null||G===void 0||G.call(N,...C)}})),this.stringify=N.fastStringify?JSON.stringify:c()}set(N,C,G){const Z=this.stringify(N);if(!this.cache.set(Z,C,{ttl:G})){const pe=this.cache.sizeCalculation?this.cache.sizeCalculation(C,Z):"unknown";throw Error(`Value too large (${pe} > ${this.cache.max})`)}this.updateStats()}get(N){const{name:C}=this.options,G=this.stringify(N),Z=this.cache.getRemainingTTL(G);return Z<=0?q.increment("cache-miss",{name:C}):Z!==1/0&&q.aggregate("cache-item-ttl",Z,{name:C}),this.cache.get(G)}delete(N){this.cache.delete(this.stringify(N))}peek(N){return this.cache.peek(this.stringify(N))}size(){return this.cache.size}clear(){this.cache.clear()}forEach(N){this.cache.forEach(N)}purgeStale(){return this.cache.purgeStale()}updateStats(){const{name:N}=this.options;q.aggregate("cache-item-count",this.cache.size,{name:N}),this.cache.calculatedSize!==void 0&&q.aggregate("cache-length",this.cache.calculatedSize,{name:N})}}{constructor(N){if(super(N),this.expireRejectedPromiseValues=N.expireRejectedPromiseValues===void 0||N.expireRejectedPromiseValues,this.rejectedPromiseValueTtl=N.rejectedPromiseValueTtl!==void 0?N.rejectedPromiseValueTtl:r.p.second,this.rejectedPromiseValueTtl<0)throw new Error("rejectedPromiseValueTtl must not be negative")}set(N,C,G){super.set(N,C,G),this.expireRejectedPromiseValues&&C.catch(()=>ie(this,void 0,void 0,function*(){yield(0,o.c)(this.rejectedPromiseValueTtl),this.peek(N)===C&&this.delete(N)}))}}var x=function(Ee,N,C,G){return new(C||(C=Promise))(function(Z,pe){function Ue(Se){try{Re(G.next(Se))}catch(fe){pe(fe)}}function ve(Se){try{Re(G.throw(Se))}catch(fe){pe(fe)}}function Re(Se){var fe;Se.done?Z(Se.value):(fe=Se.value,fe instanceof C?fe:new C(function(p){p(fe)})).then(Ue,ve)}Re((G=G.apply(Ee,N||[])).next())})};class z{constructor(N,C,G){this.authClient=N,this.email=C,this.password=G,this.tokenTtlMs=1*r.p.hour,this.tokenCache=new ee({name:"Credentials-tokenCache",max:100,ttl:this.tokenTtlMs-5*r.p.minute,fastStringify:!0})}getToken(){return x(this,void 0,void 0,function*(){let N=this.tokenCache.get(this.email);return N||(N=(()=>x(this,void 0,void 0,function*(){const{authentication:C}=yield this.authClient.login({email:this.email,password:this.password,tokenExpirationSeconds:this.tokenTtlMs/r.p.second});if(!C)throw new Error("User account not verified.");return C.accessToken}))(),this.tokenCache.set(this.email,N)),N})}}var oe=function(Ee,N,C,G){return new(C||(C=Promise))(function(Z,pe){function Ue(Se){try{Re(G.next(Se))}catch(fe){pe(fe)}}function ve(Se){try{Re(G.throw(Se))}catch(fe){pe(fe)}}function Re(Se){var fe;Se.done?Z(Se.value):(fe=Se.value,fe instanceof C?fe:new C(function(p){p(fe)})).then(Ue,ve)}Re((G=G.apply(Ee,N||[])).next())})};class ce extends e.S{createPeer(N,C){return oe(this,void 0,void 0,function*(){return yield this.fetch("peers",{token:N,method:"POST",body:C})})}getPeers(N){return oe(this,void 0,void 0,function*(){return(yield this.fetch("peers",{token:N})).items})}refreshPeer(N,C){return oe(this,void 0,void 0,function*(){yield this.fetch(`peers/${C}/refresh`,{token:N,method:"POST",allowUnsafeRetries:!0})})}createSession(N,C){return oe(this,void 0,void 0,function*(){return yield this.fetch("sessions",{token:N,method:"POST",body:C})})}refreshSession(N,C){return oe(this,void 0,void 0,function*(){yield this.fetch(`sessions/${C}/refresh`,{token:N,method:"POST",allowUnsafeRetries:!0})})}deleteSession(N,C){return oe(this,void 0,void 0,function*(){yield this.fetch("sessions/"+C,{token:N,method:"DELETE",allowUnsafeRetries:!0})})}getSessions(N){return oe(this,void 0,void 0,function*(){return(yield this.fetch("sessions",{token:N})).items})}getIceServers(N){return oe(this,void 0,void 0,function*(){return(yield this.fetch("ice-servers",{token:N})).items})}addSignals(N,C,G){return oe(this,void 0,void 0,function*(){yield this.fetch(`sessions/${C}/add-signals`,{token:N,method:"POST",body:G})})}takeSignals(N,C){return oe(this,void 0,void 0,function*(){return(yield this.fetch(`sessions/${C}/take-signals`,{token:N,method:"POST"})).items})}}var re=__webpack_require__(3449),se=__webpack_require__(5949),ne=__webpack_require__(2964),he=__webpack_require__(7396),me=function(Ee,N,C,G){return new(C||(C=Promise))(function(Z,pe){function Ue(Se){try{Re(G.next(Se))}catch(fe){pe(fe)}}function ve(Se){try{Re(G.throw(Se))}catch(fe){pe(fe)}}function Re(Se){var fe;Se.done?Z(Se.value):(fe=Se.value,fe instanceof C?fe:new C(function(p){p(fe)})).then(Ue,ve)}Re((G=G.apply(Ee,N||[])).next())})};class Qe extends he.V{constructor(N){super(N)}postLanRtcOffer(N){return me(this,void 0,void 0,function*(){return yield this.fetch("v1/lan-rtc-offer",{method:"POST",body:N})})}}var Ve=function(Ee,N,C,G){return new(C||(C=Promise))(function(Z,pe){function Ue(Se){try{Re(G.next(Se))}catch(fe){pe(fe)}}function ve(Se){try{Re(G.throw(Se))}catch(fe){pe(fe)}}function Re(Se){var fe;Se.done?Z(Se.value):(fe=Se.value,fe instanceof C?fe:new C(function(p){p(fe)})).then(Ue,ve)}Re((G=G.apply(Ee,N||[])).next())})};function We(Ee){return Ve(this,void 0,void 0,function*(){return(yield Promise.all(Ee.map(N=>N.catch(C=>C)))).filter(N=>N instanceof Error)})}function J(Ee,N){if(Ee===void 0)throw new Error("Value is undefined"+(N?": "+N:""))}function O(Ee,N){if(Ee===null)throw new Error("Value is null"+(N?": "+N:""))}function I(Ee){return J(Ee),Ee}function ae(Ee,N){const C=Ee.reduce((G,Z)=>[...G,...Z.urls],[]).filter(G=>ge(G,N)).sort(G=>Fe(G,"udp")?-1:0).shift();if(C)return Object.assign(Object.assign({},I(Ee.find(G=>G.urls.includes(C)))),{urls:[C]})}function ge(Ee,N){switch(N){case"stun":return/^stuns?:/.test(Ee);case"turn":return/^turns?:/.test(Ee)}}function Fe(Ee,N){return Ee.endsWith("transport="+N)}var ye=__webpack_require__(7207);class Oe extends Error{constructor(N,C){super(`Deadline expired after ${N}ms + ${C}ms`)}}class Ie{static withDeadline(N,C){const G=new Promise((Z,pe)=>{setTimeout(()=>{pe(new Oe(C,this.grpcCallDeadlineSlopMs))},C+this.grpcCallDeadlineSlopMs)});return Promise.race([N,G])}}Ie.grpcCallDeadlineSlopMs=500*r.p.millisecond;var Pe=__webpack_require__(8311);const ze={ordered:!1,maxPacketLifeTime:300*r.p.millisecond},qe={ordered:!0},pt={ordered:!0},dt={ordered:!1,maxRetransmits:0},vt={ordered:!1,maxRetransmits:0},Ne=Ee=>"received"in Ee&&Ee.received!==void 0,ft=Ee=>!("received"in Ee)||Ee.received===void 0,Ft=2*r.p.second,de=10*r.p.second;function ht(Ee,N={}){const C=Array.from(Ee.values()),G=C.filter(Ne),Z=G.length>0,pe=Math.max(...C.map(fe=>fe.sent)),Ue=Math.max(...G.map(fe=>fe.received));let ve;if(Z){const fe=Date.now()-pe<=r.p.millisecond?C.length-1:C.length,p=G.length>fe?fe:G.length,g=G.map(Le=>Le.received-Le.sent),{standardDeviation:V,mean:X,jitter:ue}=function(Le){const Ke=Le.length;if(Ke===0)return{mean:NaN,standardDeviation:-1,jitter:NaN};const at=Le.reduce((it,lt)=>it+lt,0)/Ke,gt=Math.sqrt(Le.map(it=>Math.pow(it-at,2)).reduce((it,lt)=>it+lt)/Ke);if(Ke===1)return{mean:at,standardDeviation:gt,jitter:NaN};let Ut=0;for(let it=1;it<Ke;it++)Ut+=Math.abs(Le[it]-Le[it-1]);return{mean:at,standardDeviation:gt,jitter:Ut/(Ke-1)}}(g),be=C.filter(Le=>Le.sent<Ue-Ft),Ce=be.filter(ft),Ae=Ce.length===0?0:Ce.length/be.length;ve={pingsSent:fe,pongsReceived:p,average:X,standardDeviation:V,jitter:ue,max:Math.max(...g),min:Math.min(...g),loss:Ae}}else ve=null;const{temporalNow:Re=Date.now()}=N,Se=(Z?Ue:Re)-de;return Array.from(Ee.entries()).forEach(fe=>{const[p,g]=fe;g.sent<Se&&Ee.delete(p)}),ve}function mt({entityId:Ee,streamName:N,streamType:C}){return`${Ee}.${N}.${C}`}var nt=function(Ee,N,C,G){return new(C||(C=Promise))(function(Z,pe){function Ue(Se){try{Re(G.next(Se))}catch(fe){pe(fe)}}function ve(Se){try{Re(G.throw(Se))}catch(fe){pe(fe)}}function Re(Se){var fe;Se.done?Z(Se.value):(fe=Se.value,fe instanceof C?fe:new C(function(p){p(fe)})).then(Ue,ve)}Re((G=G.apply(Ee,N||[])).next())})};class Dt{constructor(N,C){this.counts={localSent:new Map,localReceived:new Map,remoteSent:new Map,remoteReceived:new Map},this.sessionId=N,this.connection=C}updateRemoteMessagesCounts(N){if(N.payload.streamsInfo){this.counts.remoteSent=new Map,this.counts.remoteReceived=new Map;for(const C of N.payload.streamsInfo.items)this.counts.remoteSent.set(C.streamId,C.sentCount),this.counts.remoteReceived.set(C.streamId,C.receivedCount)}}getLocalStreamsInfo(N){const{localSent:C,localReceived:G}=this.counts;return{items:[...new Set([...C.keys(),...G.keys()])].map(Z=>{var pe,Ue;return{streamId:Z,sentCount:(pe=C.get(Z))!==null&&pe!==void 0?pe:0,receivedCount:(Ue=G.get(Z))!==null&&Ue!==void 0?Ue:0}}),timestamp:N}}incrementLocalSent(N){const{localSent:C}=this.counts,G=mt(N.header.stream);C.set(G,(C.get(G)||0)+1)}incrementLocalReceived(N){const{localReceived:C}=this.counts,G=mt(N.header.stream),Z=C.get(G)||0;if(Z===0){const{streamName:pe,streamType:Ue}=N.header.stream;m.vF.debug("RTC client received first message for stream",{streamName:pe,streamType:Ue})}C.set(G,Z+1)}uploadMetrics(){return nt(this,void 0,void 0,function*(){const{sessionId:N}=this,C=yield this.connection.peerConnection.getStats(),G={};C.forEach(Se=>G[Se.id]=Se),m.vF.debug("rtc-stats",Object.assign(Object.assign({},G),{sessionId:N}));const{localSent:Z,localReceived:pe,remoteSent:Ue,remoteReceived:ve}=this.counts,Re=[...new Set([...Z.keys(),...pe.keys()])].reduce((Se,fe)=>{const p=Z.get(fe),g=pe.get(fe),V=Ue.get(fe),X=ve.get(fe);return Object.assign(Object.assign({},Se),{[`local-${fe}-sent`]:p,[`local-${fe}-received`]:g,[`remote-${fe}-sent`]:V,[`remote-${fe}-received`]:X})},{sessionId:N});m.vF.debug("rtc-message-report",Object.assign({deviceId:this.connection.getRemoteDeviceId()},Re))})}}var kt=__webpack_require__(7186);function je(Ee){if(Ee.byteLength<4)return!1;const N=new Uint8Array(Ee);return N[0]===72&&N[1]===50&&N[2]===54&&N[3]===52}function Mt(Ee){if(Ee.byteLength<4)return!1;const N=new Uint8Array(Ee);return N[0]===66&&N[1]===67&&N[2]===72&&N[3]===75}function Et(Ee){if(!je(Ee))throw new Error("Data is not a binary H264 message");const N=new DataView(Ee),C=Number(N.getBigUint64(4,!1)),G=N.getUint16(12,!1),Z=new Uint8Array(Ee,14,G),pe=14+G;return{communicationType:"binary-h264",timestamp:C,streamName:new TextDecoder().decode(Z),frame:function(Ue){const ve=new kt.BinaryReader(new Uint8Array(Ue));let Re=0,Se=0,fe="";try{for(;ve.nextField()&&!ve.isEndGroup();)switch(ve.getFieldNumber()){case 1:Re=ve.readInt32();break;case 2:Se=ve.readInt32();break;case 3:{const p=ve.readBytes();fe=btoa(String.fromCharCode(...p));break}default:ve.skipField()}return{index:Re,flags:Se,frame_data:fe}}catch(p){throw new Error("Failed to decode H264VideoFrame: "+p)}}(Ee.slice(pe))}}function bt(Ee,N,C){return{header:{stream:Ee,created:Date.now(),frameId:C||""},payload:N}}function Wt(Ee){const N=Ee.localCandidate.candidateType,C=Ee.remoteCandidate.candidateType;return N==="host"&&C==="host"?"local":N==="relay"||C==="relay"?"TURN":"STUN"}function Ze(Ee){return new Set(["disconnected","failed","closed"]).has(Ee.iceConnectionState)}function et(Ee){switch(Ee.header.stream.streamType){case"twist":{const{twist:N}=Ee.payload;if(!N)throw Error("twist not in payload of RTC message with type twist");return{header:Ee.header,payload:{twist:{linear:Object.assign({x:0,y:0,z:0},N.linear),angular:Object.assign({x:0,y:0,z:0},N.angular)}}}}case"pose":{const{pose:N}=Ee.payload;if(!N)throw Error("pose not in payload of RTC message with type pose");return{header:Ee.header,payload:{pose:{translation:Object.assign({x:0,y:0,z:0},N.translation),rotation:Object.assign({x:0,y:0,z:0,w:0},N.rotation)}}}}case"pose-with-covariance":{const{poseWithCovariance:N}=Ee.payload;if(!N)throw Error("poseWithCovariance not in payload of RTC message with type pose-with-covariance");const C=new Array(36).fill(0);return N.covariance.forEach((G,Z)=>{if(Z>=36)throw Error("covariance contains more than 36 elements");C[Z]=G}),{header:Ee.header,payload:{poseWithCovariance:{pose:{translation:Object.assign({x:0,y:0,z:0},N.pose.translation),rotation:Object.assign({x:0,y:0,z:0,w:0},N.pose.rotation)},covariance:C}}}}case"point":{const{point:N}=Ee.payload;if(!N)throw Error("point not in payload of RTC message with type point");return{header:Ee.header,payload:{point:Object.assign({x:0,y:0,z:0},N)}}}default:return Ee}}var st=function(Ee,N,C,G){return new(C||(C=Promise))(function(Z,pe){function Ue(Se){try{Re(G.next(Se))}catch(fe){pe(fe)}}function ve(Se){try{Re(G.throw(Se))}catch(fe){pe(fe)}}function Re(Se){var fe;Se.done?Z(Se.value):(fe=Se.value,fe instanceof C?fe:new C(function(p){p(fe)})).then(Ue,ve)}Re((G=G.apply(Ee,N||[])).next())})};class Bt{get peerConnection(){return O(this._peerConnection,"RTCPeerConnection is closed!"),this._peerConnection}constructor(N,C,G,Z){this.iceServers=C,this.config=G,this.dataChannelNotifier=Z,this.connectTimeoutMs=20*r.p.second,this.iceGatheringTimeoutMs=3*r.p.second,this.pingUpdateTimeoutMs=1*r.p.second,this.pingV2UpdateTimeoutMs=250*r.p.millisecond,this.pingV2MetricsGatherTimeoutMs=1*r.p.second,this.streamsInfoUpdateTimeoutMs=2*r.p.second,this.reassemblyTimeoutMs=500*r.p.millisecond,this.reassemblyTableCleanupMs=1*r.p.second,this.heartbeatTimeoutMs=20*r.p.millisecond,this._peerConnection=null,this.heartbeatChannel=null,this.latestTtlStreamChannel=null,this.reliableStreamChannel=null,this.latestReliableStreamChannel=null,this.latestTryOnceStreamChannel=null,this.streamLatestTimestamp=new Map,this.reassemblyTable=new Map,this.reassemblyTableLastTimestamp=new Map,this.binaryReassemblyTable=new Map,this.binaryReassemblyTableLastTimestamp=new Map,this.closeCalled=!1,this.gotOffer=!1,this.hasIceCandidate=!1,this.pingV2Map=new Map,this.sendPingV2=()=>{const{latestTryOnceStreamChannel:Ue}=this;if(!Ue)return;const ve=new Date().getTime(),Re=(0,ne.A)();this.sendSystemMessage(Ue,{type:"ping-v2",payload:{timestamp:ve,id:Re}}),this.pingV2Map.set(Re,{sent:ve})},this.gatherPingV2Metrics=()=>{const Ue=ht(this.pingV2Map);if(Ue){const ve=this.getRemoteDeviceId();this.pingInfo=Ue,q.aggregate("rtc-ping-average",Ue.average,Object.assign({},ve?{deviceId:ve}:{})),q.aggregate("rtc-ping-loss",Ue.loss,Object.assign({},ve?{deviceId:ve}:{})),q.aggregate("rtc-jitter",Ue.jitter,Object.assign({},ve?{deviceId:ve}:{}))}},this._peerConnection=N;const{isOffer:pe}=G.baseConfig;pe?this.initializeChannels(N):N.ondatachannel=Ue=>{switch(Ue.channel.label){case"stream.latest-ttl":this.latestTtlStreamChannel=Ue.channel;break;case"stream.reliable":this.reliableStreamChannel=Ue.channel;break;case"stream.latest-reliable":this.latestReliableStreamChannel=Ue.channel;break;case"stream.latest-try-once":this.latestTryOnceStreamChannel=Ue.channel;break;case"heartbeat":return void(this.heartbeatChannel=Ue.channel);default:return void this.dataChannelNotifier(Ue.channel)}this.setupChannel(Ue.channel)},this.pingUpdateTimeout=setInterval(()=>{const{reliableStreamChannel:Ue}=this;Ue&&this.sendSystemMessage(Ue,{type:"ping"})},this.pingUpdateTimeoutMs),this.pingV2UpdateTimeout=setInterval(this.sendPingV2,this.pingV2UpdateTimeoutMs),this.pingV2MetricsGatherTimeout=setInterval(this.gatherPingV2Metrics,this.pingV2MetricsGatherTimeoutMs),this.streamsInfoUpdateTimeout=setInterval(()=>{const{latestTtlStreamChannel:Ue}=this;Ue&&this.sendSystemMessage(Ue,{type:"streams-info"})},this.streamsInfoUpdateTimeoutMs),this.reassemblyTableCleanupTimeout=setInterval(()=>{const Ue=new Date().getTime();this.reassemblyTableLastTimestamp.forEach((ve,Re,Se)=>{Ue>Re+this.reassemblyTimeoutMs&&this.reassemblyTable.delete(ve)})},this.reassemblyTableCleanupMs),this.heartbeatTimeout=setInterval(()=>{const{heartbeatChannel:Ue}=this;if(!Ue||Ue.readyState!=="open")return;const ve=new Uint8Array([1]);Ue.send(ve.buffer)},this.heartbeatTimeoutMs)}handleSignal(N){return st(this,void 0,void 0,function*(){const{peerConnection:C}=this,{track:G}=this.config.baseConfig,Z=(()=>{try{return JSON.parse(N.getPayload())}catch{return}})();if(!Z)return void m.vF.error("Received unparseable signal.");m.vF.debug("Handling signal",{description:Z});const{sdp:pe,type:Ue}=Z;if(!pe||!Ue)return void m.vF.warn("Received non-SDP signal");const{signalingState:ve,connectionState:Re}=C;if(ve!=="stable"||Re!=="connected")if(C.remoteDescription)m.vF.warn("Received SDP after remote description was set: "+pe);else{if(Ue==="offer"){if(ve!=="stable")return void m.vF.warn("Received offer SDP when signaling is ongoing.");yield C.setRemoteDescription(Z);const Se=yield C.createAnswer();yield C.setLocalDescription(Se);const fe=N.clone();return G==null||G("Answer Received",fe),fe.setPayload(JSON.stringify(Se)),fe.setReceiverId(N.getSenderId()),fe.setSenderId(N.getReceiverId()),fe}if(Ue==="answer"){if(ve==="stable")return void m.vF.warn("Received answer SDP when signaling hasn't started.");yield C.setRemoteDescription(Z)}}else m.vF.warn("Received SDP when already connected: "+pe)})}send(N,C){const G=this.getChannelFromLabel(C.channelLabel);G?this.sendOnChannel(G,N):m.vF.warn("Send called with unexpected channel label",{channelLabel:C.channelLabel})}controlRemoteStream(N){var C;this.sendSystemMessage((O(C=this.reliableStreamChannel),C),{type:"stream-control",streamControl:N})}isActive(){return new Set(["new","checking","connected","completed"]).has(this.peerConnection.iceConnectionState)||this.isReady()}isReady(){const{reliableStreamChannel:N,latestTtlStreamChannel:C,latestTryOnceStreamChannel:G,latestReliableStreamChannel:Z}=this;return(N==null?void 0:N.readyState)==="open"&&(C==null?void 0:C.readyState)==="open"&&(G==null?void 0:G.readyState)==="open"&&(Z==null?void 0:Z.readyState)==="open"}close(){return st(this,void 0,void 0,function*(){var N,C,G,Z,pe,Ue,ve;this.closeCalled||(this.closeCalled=!0,yield(N=this.sessionMetrics)===null||N===void 0?void 0:N.uploadMetrics(),wt(this.pingUpdateTimeout),wt(this.pingV2UpdateTimeout),wt(this.pingV2MetricsGatherTimeout),wt(this.reassemblyTableCleanupTimeout),wt(this.streamsInfoUpdateTimeout),wt(this.heartbeatTimeout),(C=this._peerConnection)===null||C===void 0||C.close(),(G=this.heartbeatChannel)===null||G===void 0||G.close(),(Z=this.latestReliableStreamChannel)===null||Z===void 0||Z.close(),(pe=this.latestTryOnceStreamChannel)===null||pe===void 0||pe.close(),(Ue=this.latestTtlStreamChannel)===null||Ue===void 0||Ue.close(),(ve=this.reliableStreamChannel)===null||ve===void 0||ve.close(),this._peerConnection=null,this.heartbeatChannel=null,this.latestReliableStreamChannel=null,this.latestTryOnceStreamChannel=null,this.latestTtlStreamChannel=null,this.reliableStreamChannel=null)})}getPing(){return this.pingTimeMs}getPingInfo(){return this.pingInfo}getLastMessageTimestamp(){return this.lastMessageTimestamp}getSessionCreatedTimestamp(){var N;return(N=this.config.remoteConfig)===null||N===void 0?void 0:N.sessionCreatedTimestamp}setSessionCreatedTimestamp(N){this.config.remoteConfig&&(this.config.remoteConfig.sessionCreatedTimestamp=N)}getSessionId(){var N;return(N=this.config.remoteConfig)===null||N===void 0?void 0:N.sessionId}setSessionId(N){this.config.remoteConfig&&(this.config.remoteConfig.sessionId=N,this.sessionMetrics=new Dt(N,this))}getRemotePeerId(){return this.config.baseConfig.remotePeerId}getRemoteDeviceId(){var N;return(N=this.config.baseConfig)===null||N===void 0?void 0:N.remoteDeviceId}setRemoteDeviceId(N){this.config.baseConfig.remoteDeviceId=N}getSessionMetricsMessageCounts(){var N;return(N=this.sessionMetrics)===null||N===void 0?void 0:N.counts}getConnectionStatsInfo(){return st(this,void 0,void 0,function*(){const{peerConnection:N}=this;if(!N)return;const C=yield N.getStats(null),G=[];C.forEach(Re=>{G.push(Re)});const Z=G.find(Re=>Re.type==="transport");if(!Z)return;const pe=G.find(Re=>(Re.type==="candidate-pair"||Re.type==="candidatepair")&&Re.id===Z.selectedCandidatePairId);if(!pe)return;const Ue=G.find(Re=>Re.id===pe.localCandidateId),ve=G.find(Re=>Re.id===pe.remoteCandidateId);return Ue&&ve&&(Ue.address=Ue.address||Ue.ip,ve.address=ve.address||ve.ip,Ue.address!==void 0&&ve.address!==void 0)?{transport:Z,localCandidate:Ue,remoteCandidate:ve,candidatePair:pe}:void 0})}initializeChannels(N){this.heartbeatChannel=N.createDataChannel("heartbeat",vt),this.heartbeatChannel.binaryType="arraybuffer",this.latestTtlStreamChannel=N.createDataChannel("stream.latest-ttl",ze),this.latestTtlStreamChannel.binaryType="arraybuffer",this.reliableStreamChannel=N.createDataChannel("stream.reliable",qe),this.reliableStreamChannel.binaryType="arraybuffer",this.latestReliableStreamChannel=N.createDataChannel("stream.latest-reliable",pt),this.latestReliableStreamChannel.binaryType="arraybuffer",this.latestTryOnceStreamChannel=N.createDataChannel("stream.latest-try-once",dt),this.latestTryOnceStreamChannel.binaryType="arraybuffer",this.setupChannel(this.latestTtlStreamChannel),this.setupChannel(this.reliableStreamChannel),this.setupChannel(this.latestReliableStreamChannel),this.setupChannel(this.latestTryOnceStreamChannel)}getOffer(){return st(this,void 0,void 0,function*(){var N,C;const{gotOffer:G}=this,{peerConnection:Z,config:pe}=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 Ue=(N=this.config.remoteConfig)===null||N===void 0?void 0:N.sessionId;if(G)return void m.vF.debug("Failed to generate offer because gotOffer was already called.");if(this.gotOffer=!0,Ze(this.peerConnection))return void m.vF.debug("Failed to generate offer because the peer connection was inactive.");const ve=pe.baseConfig.track;Z.onicecandidate=()=>{this.hasIceCandidate=!0},Z.oniceconnectionstatechange=()=>st(this,void 0,void 0,function*(){const V=Z.iceConnectionState;if(V==="connected"||V==="completed"){const X=yield this.getConnectionStatsInfo(),ue=X?Wt(X):void 0;m.vF.info("ICE connection state changed to "+V,{sessionId:Ue,connectionStatsInfo:X,iceMode:ue}),ve==null||ve("ICE connection state change",{iceConnectionState:V,sessionId:Ue,connectionStatsInfo:X,iceMode:ue})}}),yield Z.setLocalDescription(yield Z.createOffer());const Re=Z.getConfiguration?Z.getConfiguration().iceTransportPolicy:"all",Se=new Date().getTime();for(;;){const V=new Date().getTime()-Se;if(V>this.connectTimeoutMs)return void m.vF.debug("Failed to generate offer because ICE gathering timed out.");if(V>this.iceGatheringTimeoutMs&&this.hasIceCandidate){m.vF.debug("ICE gathering partially completed; proceeding",{iceTransportPolicy:Re,waitTime:V}),ve==null||ve("ICE gathering partially completed",{sessionId:Ue,iceTransportPolicy:Re,waitTime:V});break}if(Z.iceGatheringState==="complete"){m.vF.debug("ICE gathering complete",{iceTransportPolicy:Re,waitTime:V}),ve==null||ve("ICE gathering completed",{sessionId:Ue,iceTransportPolicy:Re,waitTime:V});break}yield(0,o.c)(.1*r.p.second)}const fe=(C=this.iceServers)!==null&&C!==void 0?C:[];for(const V of fe)"credentialType"in V&&(V.credentialType=void 0);const p=JSON.stringify(fe),g=new re.Signal;return g.setPayload(JSON.stringify(Z.localDescription)),g.setSenderId(this.config.baseConfig.localPeerId),g.setReceiverId(this.config.baseConfig.remotePeerId),g.setIceServers(p),g.setIceTransportPolicy(Re!=null?Re:"all"),this.config.baseConfig.sessionType!==void 0?g.setSessionType(this.config.baseConfig.sessionType):g.setSessionType(re.SessionType.TELEOP),m.vF.debug("Sending offer signal with description",{description:g.getPayload()}),g})}getLanOffer(){return st(this,void 0,void 0,function*(){const{peerConnection:N,gotOffer:C}=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(C)return void m.vF.debug("Failed to generate offer because gotOffer was already called.");if(this.gotOffer=!0,Ze(this.peerConnection))return void m.vF.debug("Failed to generate offer because the peer connection was inactive.");yield N.setLocalDescription(yield N.createOffer());const G=new Date().getTime();for(;;){if(new Date().getTime()-G>this.iceGatheringTimeoutMs)return void m.vF.debug("Failed to generate offer because ICE gathering timed out.");if(N.iceGatheringState==="complete")break;yield(0,o.c)(.1*r.p.second)}const Z=N.localDescription;if(Z)return m.vF.debug("Sending LAN offer signal with description",{description:Z}),Z;m.vF.error("Failed to generate LAN offer description")})}handleLanAnswer(N){return st(this,void 0,void 0,function*(){const{peerConnection:C}=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 C.setRemoteDescription(N)})}getChannelFromLabel(N){switch(N){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(N,C){var G;let Z;try{Z=(0,Pe.encode)(JSON.stringify(C))}catch(pe){return void m.vF.warn("Failed to encode RTC message",{error:pe})}try{const pe=new Uint8Array(Z);N.send(pe.buffer),(G=this.sessionMetrics)===null||G===void 0||G.incrementLocalSent(C)}catch(pe){m.vF.warn("Failed to send message to channel",{error:pe,channel:N.label})}}channelNotRecognized(N){return N!==this.latestTtlStreamChannel&&N!==this.latestReliableStreamChannel&&N!==this.latestTryOnceStreamChannel&&N!==this.reliableStreamChannel}setupChannel(N){N.onmessage=C=>{var G,Z,pe,Ue;if(this.channelNotRecognized(N))return void m.vF.warn("Received message on unrecognized data channel.");let ve;if(C.data instanceof ArrayBuffer)try{if(je(C.data)){const Se=Et(C.data);return void this.receiveBinaryH264Message(N,Se)}if(Mt(C.data)){const Se=function(fe){if(!Mt(fe))throw new Error("Data is not a binary chunk message");const p=new DataView(fe);return{communicationType:"binary-chunk",chunkId:p.getUint32(4,!1),sequence:p.getUint32(8,!1),total:p.getUint32(12,!1),data:new Uint8Array(fe.slice(16))}}(C.data);return void this.receiveBinaryChunkMessage(N,Se)}const Re=(0,Pe.decode)(new Uint8Array(C.data));ve=JSON.parse(Re)}catch(Re){return void m.vF.warn("Received unparseable binary message on RTC stream data channel",{error:Re,channel:N.label})}else try{const Re=typeof C.data=="string"?C.data:(0,Pe.decode)(C.data instanceof ArrayBuffer?new Uint8Array(C.data):C.data);ve=JSON.parse(Re)}catch(Re){return void m.vF.warn("Received unparseable JSON message on RTC stream data channel",{error:Re,channel:N.label})}if(ve.communicationType==="message-chunk")this.receiveChannelMessageChunk(N,ve);else{const Re=ve;if(!((G=Re.payload)===null||G===void 0)&&G.h264VideoFrame){const Se={communicationType:"binary-h264",timestamp:((Z=Re.header)===null||Z===void 0?void 0:Z.created)||Date.now(),streamName:((Ue=(pe=Re.header)===null||pe===void 0?void 0:pe.stream)===null||Ue===void 0?void 0:Ue.streamName)||N.label,frame:Re.payload.h264VideoFrame};this.receiveBinaryH264Message(N,Se)}else this.receiveChannelMessage(N,Re)}},N.onerror=C=>{m.vF.warn("Channel error: "+C.error,{error:C.error,sessionId:this.getSessionId(),channelLabel:N.label})},N.onopen=()=>{m.vF.debug("Channel opened",{sessionId:this.getSessionId(),channelLabel:N.label})},N.onclose=()=>{const C={bufferedAmount:N.bufferedAmount,sessionId:this.getSessionId(),channelLabel:N.label};this.closeCalled===!1?m.vF.debug("Unexpected channel closed",C):m.vF.debug("Channel closed",C)}}receiveChannelMessage(N,C){var G;const{config:Z}=this,{remotePeerId:pe}=this.config.baseConfig;this.lastMessageTimestamp=new Date().getTime(),C=et(C),(G=this.sessionMetrics)===null||G===void 0||G.incrementLocalReceived(C),!this.handleSystemMessage(N,C)&&((N===this.latestTryOnceStreamChannel||N===this.latestTtlStreamChannel||N===this.latestReliableStreamChannel)&&!this.isLatestMessage(C)||Z.baseConfig.receive(pe,C))}receiveChannelMessageChunk(N,C){const G=this.reassemblyTable.get(C.id)||[];if(G.push(C),G.length===C.total){const Z=function(pe){const Ue=pe.sort((ve,Re)=>ve.seq<Re.seq?-1:1).map(ve=>ve.part).reduce((ve,Re)=>ve+Re);try{return JSON.parse(Ue)}catch{return void m.vF.warn("Could not reassemble RTC message chunks")}}(G);return Z&&this.receiveChannelMessage(N,Z),void this.reassemblyTable.delete(C.id)}this.reassemblyTable.set(C.id,G),this.reassemblyTableLastTimestamp.set(C.id,new Date().getTime())}receiveBinaryH264Message(N,C){const G={communicationType:"message",header:{stream:{entityId:this.config.baseConfig.remoteDeviceId||this.config.baseConfig.remotePeerId||"",streamName:C.streamName,streamType:"h264-video-frame"},created:C.timestamp,frameId:""},payload:{h264VideoFrame:C.frame}};this.receiveChannelMessage(N,G)}receiveBinaryChunkMessage(N,C){const G=C.chunkId,Z=this.binaryReassemblyTable.get(G)||new Map;if(Z.set(C.sequence,C.data),Z.size===C.total){let pe=0;for(const Re of Z.values())pe+=Re.length;const Ue=new Uint8Array(pe);let ve=0;for(let Re=0;Re<C.total;Re++){const Se=Z.get(Re);Se&&(Ue.set(Se,ve),ve+=Se.length)}try{if(je(Ue.buffer)){const Re=Et(Ue.buffer);this.receiveBinaryH264Message(N,Re)}}catch(Re){m.vF.warn("Failed to parse reassembled binary message",{error:Re,chunkId:G,channel:N.label})}return this.binaryReassemblyTable.delete(G),void this.binaryReassemblyTableLastTimestamp.delete(G)}this.binaryReassemblyTable.set(G,Z),this.binaryReassemblyTableLastTimestamp.set(G,new Date().getTime())}handleSystemMessage(N,C){var G,Z;const{config:pe}=this,{baseConfig:Ue}=pe,{remotePeerId:ve,remoteDeviceId:Re}=Ue;switch(C.header.stream.streamType){case"ping":return this.sendSystemMessage(N,{type:"pong",timestamp:I(C.payload.ping)}),!0;case"pong":{const Se=new Date().getTime()-I(C.payload.pong);return this.pingTimeMs=Se,q.aggregate("rtc-ping-time",Se,Object.assign({},Re?{deviceId:Re}:{})),!0}case"ping-v2":return this.sendPingV2(),!0;case"pong-v2":{const Se=I(C.payload.pongV2),fe=this.pingV2Map.get(Se.id);return(fe==null?void 0:fe.sent)!==Se.timestamp&&m.vF.warn("Pong timestamp doesn't match stored value",{currentEntry:fe,pong:Se}),this.pingV2Map.set(Se.id,{sent:Se.timestamp,received:new Date().getTime()}),!0}case"streams-info":{const{sessionMetrics:Se}=this,fe=(G=C.payload.streamsInfo)===null||G===void 0?void 0:G.timestamp;return!!fe&&(Se==null||Se.updateRemoteMessagesCounts(C),(Z=Ue.onStreamsInfoUpdate)===null||Z===void 0||Z.call(Ue,ve,fe),!0)}case"stream-control":return!0;default:return!1}}sendSystemMessage(N,C){var G;const{localUserId:Z,localPeerId:pe}=this.config.baseConfig;if(N.readyState!=="open")return;const Ue={entityId:Z!=null?Z:pe,streamName:"$."+C.type,streamType:C.type};let ve;switch(C.type){case"ping":ve={ping:new Date().getTime()};break;case"pong":ve={pong:C.timestamp};break;case"ping-v2":ve={pingV2:C.payload};break;case"pong-v2":ve={pongV2:C.payload};break;case"stream-control":ve={streamControl:C.streamControl};break;case"streams-info":ve={streamsInfo:(G=this.sessionMetrics)===null||G===void 0?void 0:G.getLocalStreamsInfo(new Date().getTime())}}this.sendOnChannel(N,bt(Ue,ve))}isLatestMessage(N){const C=mt(N.header.stream),G=(this.streamLatestTimestamp.get(C)||0)<=N.header.created;return G&&this.streamLatestTimestamp.set(C,N.header.created),G}}function wt(Ee){Ee&&clearInterval(Ee)}function zt(){m.vF.debug("forceGarbageCollection() triggered"),queueMicrotask(()=>{let Ee=document.createElement("img");Ee.src=window.URL.createObjectURL(new Blob([new ArrayBuffer(5e7)])),Ee.onerror=function(){window.URL.revokeObjectURL(this.src),Ee=null}})}function Gt(Ee){try{return Ee instanceof Error?`${Ee.name}: ${Ee.message}`:typeof Ee=="object"?JSON.stringify(Ee):String(Ee)}catch{return"Unknown error"}}function Nt(Ee){var N,C;return{userId:(N=Ee.getUserId())===null||N===void 0?void 0:N.getValue(),deviceId:(C=Ee.getDeviceId())===null||C===void 0?void 0:C.getValue(),organizationId:Ee.getOrganizationId(),id:Ee.getPeerId(),capabilities:[],capabilitySet:{}}}var $e=function(Ee,N,C,G){return new(C||(C=Promise))(function(Z,pe){function Ue(Se){try{Re(G.next(Se))}catch(fe){pe(fe)}}function ve(Se){try{Re(G.throw(Se))}catch(fe){pe(fe)}}function Re(Se){var fe;Se.done?Z(Se.value):(fe=Se.value,fe instanceof C?fe:new C(function(p){p(fe)})).then(Ue,ve)}Re((G=G.apply(Ee,N||[])).next())})};const xt=Ee=>Ee.map(N=>Object.assign(Object.assign(Object.assign({},N),N.username?{username:"<REDACTED>"}:null),N.credential?{credential:"<REDACTED>"}:null));class Lt{constructor(N){this.config=N,this.grpcCallDeadline=5*r.p.second,this.refreshIntervalDelayMs=2*r.p.second,this.iceServersTtl=30*r.p.minute,this.connections=[],this.localConnections=[],this.isConnectionInitiator=new WeakSet,this.isOutgoingConnection=new Set,this.peerDataChannelListeners=[],this.rtcInstancesConstructed=0,this.statsLoopsExecuted=0;const{refreshIntervalDelayMs:C}=this;this.refreshInterval=M({func:()=>$e(this,void 0,void 0,function*(){try{yield this.update()}catch(G){m.vF.warn("RTC refresh failed",{error:G})}}),delay:C})}send(N,C,G){const Z=this.getActiveConnection(N);Z?Z.isReady()?Z.send(C,G):m.vF.warn("Send called with unready connection."):m.vF.warn("Send called with no connection.")}controlRemoteStream(N,C){const G=this.getActiveConnection(N);G?G.isReady()?G.controlRemoteStream(C):m.vF.warn("controlRemoteStream called with unready connection."):m.vF.warn("controlRemoteStream called with no connection.")}getLocalPeer(){return $e(this,void 0,void 0,function*(){for(;!this.localPeer;)yield(0,o.c)(.1*r.p.second);return Nt(this.localPeer)})}connect(N,C){return $e(this,void 0,void 0,function*(){var G,Z,pe;if(this.config.lanOnlyMode===!0)throw new Error("connect method called in local only mode.");const{track:Ue,signalingClient:ve}=this.config,{localPeer:Re,receiveSignalStream:Se,iceServers:fe}=this;if(!Re||!Se||!fe)return void m.vF.warn("Connect called prior to local peer, receiveSignalStream, and ICE servers ready");if(this.getActiveConnection(N))return void m.vF.warn("Connect called for peer with existing connection.");if(this.isOutgoingConnection.has(N))return void m.vF.warn("Connect called for peer with an existing outgoing connection offer.");this.isOutgoingConnection.add(N);const p=function(Ae,Le,Ke){const{rtcIceTransportPolicies:at,rtcIceServerProtocol:gt,useAllServers:Ut}=Le||{},it=Ae.map(lt=>Object.assign(Object.assign({},lt),{urls:lt.urls.filter(_t=>{const At=(at===void 0||at.some(Yt=>ge(_t,Yt)))&&(gt===void 0||Fe(_t,gt));return At||m.vF.debug("Ignoring ICE server: "+_t,{organizationId:Ke}),At})})).filter(({urls:lt})=>lt.filter(_t=>_t).length>0);return Ut?it:[ae(it,"stun"),ae(it,"turn")].filter(lt=>lt!==void 0).map(lt=>I(lt))}(fe,C);m.vF.debug("Received ICE servers:",xt(fe)),m.vF.debug("Using ICE servers:",xt(p));const g=new Bt(yield this.createRTCPeerConnection(p),p,{baseConfig:{isOffer:!0,isLan:!1,receive:(Ae,Le)=>this.config.receive(Ae,Le),onStreamsInfoUpdate:this.config.onStreamsInfoUpdate?(Ae,Le)=>{var Ke,at;return(at=(Ke=this.config).onStreamsInfoUpdate)===null||at===void 0?void 0:at.call(Ke,Ae,Le)}:void 0,track:this.config.lanOnlyMode?void 0:this.config.track,localUserId:(G=Re.getUserId())===null||G===void 0?void 0:G.getValue(),localPeerId:Re.getPeerId(),remotePeerId:N,sessionType:this.config.sessionType},remoteConfig:{}},Ae=>this.onCustomDataChannel(N,Ae)),V=yield g.getOffer();if(!V)return m.vF.error("Failed to generate offer."),void this.isOutgoingConnection.delete(N);m.vF.debug("Sending offer."),Ue==null||Ue("Sending offer",(0,ye.x)(V));const X=new re.SendSignalRequest;X.setSignal(V);const ue=yield(()=>$e(this,void 0,void 0,function*(){try{return yield Ie.withDeadline(ve.sendSignal(X,yield this.getMetadata()),this.grpcCallDeadline)}catch(Ae){m.vF.warn("Error when sending signal",{error:Ae})}}))();if(!this.isOutgoingConnection.has(N))return void m.vF.debug("No offer set after receiving offer signal response.");m.vF.debug("Offer sent.");const be=(Z=ue==null?void 0:ue.getSessionId())===null||Z===void 0?void 0:Z.getValue(),Ce=(pe=ue==null?void 0:ue.getSessionCreatedTimestamp())===null||pe===void 0?void 0:pe.getValue();return be&&Ce?(g.setSessionId(be),g.setSessionCreatedTimestamp(Ce),this.isOutgoingConnection.delete(N),this.connections.push(g),this.isConnectionInitiator.add(g),this.setupHandlers(g),be):(m.vF.warn("No session ID or no session created timestamp on send signal response."),void this.isOutgoingConnection.delete(N))})}connectLan(N){return $e(this,void 0,void 0,function*(){var C,G;const Z=new Qe(N),pe=new Bt(yield this.createRTCPeerConnection([]),[],{baseConfig:{isOffer:!0,isLan:!0,receive:(Se,fe)=>this.config.receive(Se,fe),onStreamsInfoUpdate:this.config.onStreamsInfoUpdate?(Se,fe)=>{var p,g;return(g=(p=this.config).onStreamsInfoUpdate)===null||g===void 0?void 0:g.call(p,Se,fe)}:void 0,track:this.config.lanOnlyMode?void 0:this.config.track,localUserId:(G=(C=this.localPeer)===null||C===void 0?void 0:C.getUserId())===null||G===void 0?void 0:G.getValue(),localPeerId:"lan_client",remotePeerId:N}},Se=>this.onCustomDataChannel(N,Se)),Ue=yield pe.getLanOffer();if(!Ue)return m.vF.warn("Could not generate LAN offer"),!1;const ve=yield Z.postLanRtcOffer({offer:JSON.stringify(Ue)}),Re=new RTCSessionDescription(JSON.parse(ve.answer));return yield pe.handleLanAnswer(Re),this.localConnections.push(pe),this.isConnectionInitiator.add(pe),(0,ne.A)()})}getConnections(){return[...this.connections,...this.localConnections]}createCustomDataChannel(N,C,G,Z,pe){const Ue=this.getActiveConnection(N);if(Ue&&this.isConnectionInitiator.has(Ue)){const Re=Ue.peerConnection.createDataChannel("custom."+C,G);return Z&&(Re.binaryType="arraybuffer"),pe(N,Re),()=>{}}const ve=(Re,Se)=>{N===Re&&Se.label==="custom."+C&&pe(N,Se)};return this.peerDataChannelListeners.push(ve),()=>{this.peerDataChannelListeners=this.peerDataChannelListeners.filter(Re=>Re!==ve)}}onCustomDataChannel(N,C){this.peerDataChannelListeners.forEach(G=>G(N,C))}getConnectionStatus(N){if(this.isOutgoingConnection.has(N))return"connecting";const C=this.getActiveConnection(N);return C?C.isReady()?"connected":"connecting":"disconnected"}getConnectionStatsInfo(N){return $e(this,void 0,void 0,function*(){const C=this.getActiveConnection(N);if(C)return yield C.getConnectionStatsInfo()})}disconnect(N){return $e(this,void 0,void 0,function*(){const C=this.getActiveConnection(N);C&&(yield C.close(),this.connections=this.connections.filter(G=>G!==C),this.localConnections=this.localConnections.filter(G=>G!==C))})}getPeers(){return $e(this,void 0,void 0,function*(){if(this.config.lanOnlyMode)throw new Error("getPeers method cannot be used in local-only mode.");const{signalingClient:N}=this.config,C=yield(()=>$e(this,void 0,void 0,function*(){try{return yield Ie.withDeadline(N.getPeers(new re.GetPeersRequest,yield this.getMetadata()),this.grpcCallDeadline)}catch(pe){m.vF.warn("Error when getting peers",{error:pe})}}))();if(!C)return[];const G=C.getPeersList();if(!G)return[];const Z=pe=>{var Ue,ve;return(ve=(Ue=pe.getPeerCreatedTimestamp())===null||Ue===void 0?void 0:Ue.getValue())!==null&&ve!==void 0?ve:0};return G.sort((pe,Ue)=>Z(Ue)-Z(pe)).map(pe=>Nt(pe))})}getSessions(){return $e(this,void 0,void 0,function*(){if(this.config.lanOnlyMode)throw new Error("getPeers method cannot be used in local-only mode.");const{signalingClient:N}=this.config,C=yield(()=>$e(this,void 0,void 0,function*(){try{return yield Ie.withDeadline(N.getPeers(new re.GetPeersRequest,yield this.getMetadata()),this.grpcCallDeadline)}catch(pe){m.vF.warn("Error when getting peers",{error:pe})}}))();if(!C)return{};const G=C.getPeersList(),Z={};for(const pe of G)Z[pe.getPeerId()]=pe.getSessionIdsList();return Z})}getPing(N){const C=this.getActiveConnection(N);if(C)return C.getPing();m.vF.warn("Attempted to get ping time from inactive peer.")}getPingInfo(N){const C=this.getActiveConnection(N);if(C)return C.getPingInfo();m.vF.warn("Attempted to get ping time from inactive peer.")}getLastMessageTimestamp(N){const C=this.getActiveConnection(N);if(C)return C.getLastMessageTimestamp();m.vF.warn("Attempted to get last message time from inactive peer.")}getSessionMetricsMessageCounts(N){const C=this.getActiveConnection(N);if(C)return C.getSessionMetricsMessageCounts();m.vF.warn("Attempted to get session metrics counts from inactive peer.")}isReady(){if(this.config.lanOnlyMode)return!0;const{localPeer:N,receiveSignalStream:C,iceServers:G}=this;return!!(N&&C&&G)}shutdown(){return $e(this,void 0,void 0,function*(){yield this.refreshInterval.stop(),this.receiveSignalStream&&this.receiveSignalStream.cancel();const N=this.connections;this.connections=[],yield this.closeConnections(N);const C=this.localConnections;this.localConnections=[],yield this.closeConnections(C),this.isOutgoingConnection.clear(),this.peerDataChannelListeners=[];const{localPeer:G}=this;if(!G||this.config.lanOnlyMode)return;const{signalingClient:Z}=this.config;yield(()=>$e(this,void 0,void 0,function*(){try{const pe=new re.DeletePeerRequest;pe.setPeerId(G.getPeerId()),yield Ie.withDeadline(Z.deletePeer(pe,yield this.getMetadata()),this.grpcCallDeadline)}catch(pe){return void m.vF.warn("Error deleting local peer",{error:pe})}}))()})}createPeer(){return $e(this,void 0,void 0,function*(){if(this.config.lanOnlyMode)throw new Error("createPeer method cannot be used in local-only mode.");const{signalingClient:N}=this.config,C=yield(()=>$e(this,void 0,void 0,function*(){try{return yield Ie.withDeadline(N.createPeer(new re.CreatePeerRequest,yield this.getMetadata()),this.grpcCallDeadline)}catch(Z){const pe=Z;m.vF.debug("createPeer failed",{error:pe});const Ue=Gt(pe);throw new Error("Was not able to create peer: "+Ue)}}))(),G=C==null?void 0:C.getPeer();if(!G)throw new Error("Response did not provide peer.");return this.localPeer=G})}createReceiveSignalStream(){return $e(this,void 0,void 0,function*(){if(this.config.lanOnlyMode)throw new Error("createReceiveSignalStream method cannot be used in local-only mode.");const{signalingClient:N}=this.config,{localPeer:C,iceServers:G}=this;if(!C||!G)return;const{receiveSignalStream:Z}=this;Z&&Z.cancel();const pe=new re.ReceiveSignalStreamRequest;pe.setPeerId(C.getPeerId());const Ue=yield(()=>$e(this,void 0,void 0,function*(){try{return N.receiveSignalStream(pe,yield this.getMetadata({hasDeadline:!1}))}catch(ve){m.vF.debug("createReceiveSignalStream failed",{error:ve});const Re=Gt(ve);throw new Error("Unable to create receive signal stream: "+Re)}}))();if(!Ue)throw new Error("Response did not provide stream.");return Ue.on("data",ve=>$e(this,void 0,void 0,function*(){var Re,Se,fe,p;const g=ve.getSignal(),V=(Re=g==null?void 0:g.getSessionId())===null||Re===void 0?void 0:Re.getValue(),X=g==null?void 0:g.getSenderId(),ue=g==null?void 0:g.getReceiverId(),be=(Se=g==null?void 0:g.getSessionCreatedTimestamp())===null||Se===void 0?void 0:Se.getValue();if(!(g&&V&&X&&ue&&be))return void m.vF.warn("Received signal with missing information.");const Ce=this.getActiveConnection(X);if(Ce)if(Ce.getSessionId()!==V){if(m.vF.debug("Received signal: different session for a peer we're already connected to."),(Ce.getSessionCreatedTimestamp()||0)>be)return;const Ae=new Bt(yield this.createRTCPeerConnection(G),G,{baseConfig:{isOffer:!1,isLan:!1,receive:(Le,Ke)=>this.config.receive(Le,Ke),onStreamsInfoUpdate:this.config.onStreamsInfoUpdate?(Le,Ke)=>{var at,gt;return(gt=(at=this.config).onStreamsInfoUpdate)===null||gt===void 0?void 0:gt.call(at,Le,Ke)}:void 0,track:this.config.lanOnlyMode?void 0:this.config.track,localPeerId:C.getPeerId(),localUserId:(p=C.getUserId())===null||p===void 0?void 0:p.getValue(),remotePeerId:X},remoteConfig:{sessionId:V,sessionCreatedTimestamp:be}},Le=>this.onCustomDataChannel(X,Le));yield Ae.handleSignal(g),this.connections.push(Ae)}else m.vF.debug("Received signal: for an existing connection."),yield Ce.handleSignal(g);else{m.vF.debug("Received signal: new connection.");const Ae=new Bt(yield this.createRTCPeerConnection(G),G,{baseConfig:{isOffer:!1,isLan:!1,receive:(Le,Ke)=>this.config.receive(Le,Ke),onStreamsInfoUpdate:this.config.onStreamsInfoUpdate?(Le,Ke)=>{var at,gt;return(gt=(at=this.config).onStreamsInfoUpdate)===null||gt===void 0?void 0:gt.call(at,Le,Ke)}:void 0,track:this.config.lanOnlyMode?void 0:this.config.track,localPeerId:C.getPeerId(),localUserId:(fe=C.getUserId())===null||fe===void 0?void 0:fe.getValue(),remotePeerId:X},remoteConfig:{sessionId:V,sessionCreatedTimestamp:be}},Le=>this.onCustomDataChannel(X,Le));yield Ae.handleSignal(g),this.connections.push(Ae)}})),Ue.on("end",()=>{Ue.cancel(),this.receiveSignalStream=void 0}),Ue.on("error",ve=>{switch(ve.code){case se.StatusCode.CANCELLED:case se.StatusCode.UNAVAILABLE:case se.StatusCode.UNKNOWN:m.vF.debug("Receive signal stream error",{error:ve});break;case se.StatusCode.UNAUTHENTICATED:m.vF.warn("Receive signal stream error",{error:ve});break;default:m.vF.error("Receive signal stream error",{error:ve})}Ue.cancel(),this.receiveSignalStream=void 0}),this.receiveSignalStream=Ue})}createRTCPeerConnection(N){return $e(this,void 0,void 0,function*(){var C;const G=(C=this.config.alternateRTCPeerConnection)!==null&&C!==void 0?C:window.RTCPeerConnection;if(!G)throw function(){if(typeof navigator=="undefined")throw new Error("not a browser");const{userAgent:Z}=navigator;return Z.includes("Firefox/")?"Firefox":Z.includes("Edg/")?"Edge":Z.includes("Chrome/")?"Chrome":Z.includes("Safari/")?"Safari":Z.includes("MSIE/")||Z.includes("Trident/")?"IE":"Other"}()!=="Chrome"?new Error("WebRTC is not enabled. Please try again with the latest version of Google Chrome."):new Error("WebRTC is not enabled. Please ensure WebRTC is not disabled by ad blocking software.");this.rtcInstancesConstructed++,this.rtcInstancesConstructed%20||zt();try{return new G({iceServers:N})}catch(Z){throw m.vF.debug(`Failed to create RTCPeerConnection: ${this.rtcInstancesConstructed} total allocated`),Z}})}closeConnections(N){return $e(this,void 0,void 0,function*(){const C=yield We(N.map(G=>$e(this,void 0,void 0,function*(){yield G.close()})));for(const G of C)m.vF.warn("Request to close session failed",{error:G})})}getActiveConnection(N){return this.getConnections().find(C=>C.getRemotePeerId()===N&&C.isActive())}update(){return $e(this,void 0,void 0,function*(){var N;if(this.localConnections=this.localConnections.filter(p=>p.isActive()),this.config.lanOnlyMode)return;const{signalingClient:C}=this.config;if(!this.localPeer||!this.receiveSignalStream||!this.iceServers){const p=[];return this.localPeer||p.push(this.createPeer()),this.iceServers||p.push(this.updateIceServers()),yield Promise.all(p),void(this.receiveSignalStream||(yield this.createReceiveSignalStream()))}const[G,Z]=(pe=this.connections,Ue=p=>p.isActive(),pe.reduce((p,g,V,X)=>{const[ue,be]=p;return(Ue(g,V,X)?ue:be).push(g),p},[[],[]]));var pe,Ue;yield this.closeConnections(Z),this.connections=G,this.gatherConnectionStats().catch(p=>{m.vF.warn("Error calling gatherConnectionStats",{error:p})}),this.statsLoopsExecuted++;const{localPeer:ve}=this,Re=this.connections.filter(p=>p.getSessionId).map(p=>I(p.getSessionId()));ve.setSessionIdsList(Re);const Se=new re.RefreshPeerRequest;Se.setPeer(ve);try{yield Ie.withDeadline(C.refreshPeer(Se,yield this.getMetadata()),this.grpcCallDeadline)}catch(p){p instanceof se.RpcError&&p.code===se.StatusCode.NOT_FOUND?(m.vF.warn("Peer expired, creating new peer",{peerId:ve.getPeerId()}),yield this.reset()):m.vF.warn("Error calling RefreshPeer",{error:p})}const fe=yield this.getPeers();for(const p of this.connections)p.setRemoteDeviceId((N=fe.find(g=>g.id===p.getRemotePeerId()))===null||N===void 0?void 0:N.deviceId)})}gatherConnectionStats(){return $e(this,void 0,void 0,function*(){if(this.statsLoopsExecuted%10!=0||this.connections.length!==1)return;const N=yield this.connections[0].getConnectionStatsInfo(),C=N?Wt(N):void 0;C?q.setTag("rtc-connection-type",C):q.setTag("rtc-connection-type","unknown")})}reset(){return $e(this,void 0,void 0,function*(){yield this.closeConnections(this.connections),this.connections=[],this.isOutgoingConnection.clear(),yield this.createPeer(),yield this.createReceiveSignalStream()})}updateIceServers(){return $e(this,void 0,void 0,function*(){if(this.config.lanOnlyMode)return;const{iceServersLastUpdate:N,iceServersTtl:C}=this,G=new Date().getTime();if(!N||G-N>C)try{const Z=(yield Ie.withDeadline(this.config.signalingClient.getIceServers(new re.GetIceServersRequest,yield this.getMetadata()),this.grpcCallDeadline)).getIceServers();this.iceServers=JSON.parse(Z),this.iceServersLastUpdate=G}catch(Z){m.vF.warn("Error in updateIceServers",{error:Z})}})}setupHandlers(N){const{peerConnection:C}=N,G=N.getSessionCreatedTimestamp();C.onconnectionstatechange=()=>$e(this,void 0,void 0,function*(){const Z=C.connectionState;if(!G)return;const pe=N.getRemoteDeviceId();switch(Z){case"connected":q.aggregate("rtc-connect-time",new Date().getTime()-G,Object.assign({},pe?{deviceId:pe}:{}));break;case"failed":q.increment("rtc-connect-failed",Object.assign({},pe?{deviceId:pe}:{}))}})}getMetadata(){return $e(this,arguments,void 0,function*(N={}){if(this.config.lanOnlyMode)throw new Error("getMetadata method cannot be called in local-only mode");const{getToken:C}=this.config,{grpcCallDeadline:G}=this,{hasDeadline:Z=!0}=N,pe=Z?{deadline:(Date.now()+G).toString(10)}:null;try{const Ue=yield C();return Object.assign({authorization:Ue},pe)}catch(Ue){throw m.vF.error("getToken() failed",{error:Ue}),new Error("Cannot get authorization token")}})}}var Tt=__webpack_require__(3721),Qt=__webpack_require__(7197),Ht=function(Ee,N,C,G){return new(C||(C=Promise))(function(Z,pe){function Ue(Se){try{Re(G.next(Se))}catch(fe){pe(fe)}}function ve(Se){try{Re(G.throw(Se))}catch(fe){pe(fe)}}function Re(Se){var fe;Se.done?Z(Se.value):(fe=Se.value,fe instanceof C?fe:new C(function(p){p(fe)})).then(Ue,ve)}Re((G=G.apply(Ee,N||[])).next())})};class Ot{constructor(N,C){this.sentMessagesCounts=new Map,this.receivedMessagesCounts=new Map,this.sessionId=N,this.connection=C}incrementMessageSent(N){const C=mt(N.header.stream);this.sentMessagesCounts.set(C,(this.sentMessagesCounts.get(C)||0)+1)}incrementMessageReceived(N){const C=mt(N.header.stream);this.receivedMessagesCounts.set(C,(this.receivedMessagesCounts.get(C)||0)+1)}uploadMetrics(){return Ht(this,void 0,void 0,function*(){const{sessionId:N}=this,C=yield this.connection.peerConnection.getStats(),G={};C.forEach(pe=>G[pe.id]=pe),m.vF.debug("rtc-stats",Object.assign(Object.assign({},G),{sessionId:N}));const Z=[...new Set(Array.from(this.sentMessagesCounts.keys()).concat(Array.from(this.receivedMessagesCounts.keys())))].reduce((pe,Ue)=>{const ve=this.sentMessagesCounts.get(Ue),Re=this.receivedMessagesCounts.get(Ue);return Object.assign(Object.assign({},pe),{[Ue+"-sent"]:ve,[Ue+"-received"]:Re})},{sessionId:N});m.vF.debug("rtc-message-report",Z)})}}function jt(Ee,N){return mt(Ee)===mt(N)}var yt=function(Ee,N,C,G){return new(C||(C=Promise))(function(Z,pe){function Ue(Se){try{Re(G.next(Se))}catch(fe){pe(fe)}}function ve(Se){try{Re(G.throw(Se))}catch(fe){pe(fe)}}function Re(Se){var fe;Se.done?Z(Se.value):(fe=Se.value,fe instanceof C?fe:new C(function(p){p(fe)})).then(Ue,ve)}Re((G=G.apply(Ee,N||[])).next())})};class Vt{constructor(N,C){this.peerConnection=N,this.config=C,this.connectTimeoutMs=10*r.p.second,this.gatherIceTimeoutMs=5*r.p.second,this.pingUpdateTimeoutMs=2*r.p.second,this.streamLatestTimestamp=new Map,this.closeCalled=!1,this.connectCalled=!1,this.sentOffer=!1,this.receivedIceCandidate=!1;const{isOffer:G}=C;G?this.initializeChannels(N):N.ondatachannel=Z=>{switch(Z.channel.label){case"stream.latest-ttl":this.latestTtlStreamChannel=Z.channel;break;case"stream.reliable":this.reliableStreamChannel=Z.channel;break;case"stream.latest-reliable":this.latestReliableStreamChannel=Z.channel;break;case"stream.latest-try-once":this.latestTryOnceStreamChannel=Z.channel}this.setupChannel(Z.channel)},this.sessionMetrics=new Ot(this.getSessionId(),this)}connect(){return yt(this,void 0,void 0,function*(){if(this.connectCalled)return;this.connectCalled=!0,this.pingUpdateTimeout=setInterval(()=>{const{reliableStreamChannel:Z}=this;Z&&this.sendSystemMessage(Z,{type:"ping"})},this.pingUpdateTimeoutMs),this.connectTimeout=setTimeout(()=>yt(this,void 0,void 0,function*(){this.isReady()||(m.vF.warn("RTC connect timed out, closing connection"),yield this.close())}),this.connectTimeoutMs);const{peerConnection:N,config:{isOffer:C,sessionId:G}}=this;if(C){const Z=yield N.createOffer();yield N.setLocalDescription(Z)}C&&(this.gatherIceTimeout=setTimeout(()=>yt(this,void 0,void 0,function*(){this.sentOffer||(m.vF.warn("ICE gathering timed out"),this.receivedIceCandidate?(m.vF.warn("Attempting to connect with partial ICE candidate pool"),yield this.sendOffer()):yield this.close())}),this.gatherIceTimeoutMs),N.onicecandidate=Z=>yt(this,void 0,void 0,function*(){Z.candidate?this.receivedIceCandidate=!0:yield this.sendOffer()}),N.onicegatheringstatechange=()=>yt(this,void 0,void 0,function*(){N.iceGatheringState==="complete"&&(yield this.sendOffer())}),N.onnegotiationneeded=()=>{m.vF.debug("Negotiation needed",{sessionId:G})})})}handleSignal(N){return yt(this,void 0,void 0,function*(){const{peerConnection:C,config:{sessionId:G,sendSignal:Z}}=this,{description:pe}=JSON.parse(N.payload);if(m.vF.debug("Handling signal",{sessionId:G,description:JSON.stringify(pe)}),pe)if(C.signalingState!=="stable"||C.connectionState!=="connected")if(C.remoteDescription)m.vF.warn("Received SDP signal during negotiation when remote description is already set: "+JSON.stringify(N));else if(pe.type==="offer"){yield C.setRemoteDescription(pe);const Ue=yield C.createAnswer();yield C.setLocalDescription(Ue),yield Z({payload:JSON.stringify({description:Ue})})}else pe.type==="answer"&&(yield C.setRemoteDescription(pe));else m.vF.warn("Received SDP signal when signaling is stable and connected: "+JSON.stringify(N));else m.vF.warn("Received non-SDP signal: "+JSON.stringify(N))})}send(N,C){const G=this.getChannelFromLabel(C.channelLabel);G?this.sendOnChannel(G,N):m.vF.warn("Send called with unexpected channel label",{channelLabel:C.channelLabel})}controlRemoteStream(N){this.sendSystemMessage(I(this.reliableStreamChannel),{type:"stream-control",streamControl:N})}isActive(){return new Set(["new","connecting","connected"]).has(this.peerConnection.connectionState)}isReady(){const{peerConnection:N,latestTtlStreamChannel:C,reliableStreamChannel:G,latestTryOnceStreamChannel:Z}=this;return!!(G&&C&&Z)&&N.connectionState==="connected"&&G.readyState==="open"&&C.readyState==="open"&&Z.readyState==="open"}isClosed(){const{peerConnection:N,reliableStreamChannel:C,latestTryOnceStreamChannel:G,latestTtlStreamChannel:Z}=this;return!(N.connectionState!=="closed"||C!==void 0&&C.readyState!=="closed"||G!==void 0&&G.readyState!=="closed"||Z!==void 0&&Z.readyState!=="closed")}needsClosing(){const{peerConnection:N,latestTtlStreamChannel:C,reliableStreamChannel:G,latestTryOnceStreamChannel:Z}=this;if(this.isClosed())return!1;const pe=new Set(["closing","closed"]),Ue=ve=>ve&&pe.has(ve.readyState);return Ze(N)||Ue(C)||Ue(G)||Ue(Z)}close(){return yt(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(N){this.latestTtlStreamChannel=N.createDataChannel("stream.latest-ttl",ze),this.reliableStreamChannel=N.createDataChannel("stream.reliable",qe),this.latestReliableStreamChannel=N.createDataChannel("stream.latest-reliable",pt),this.latestTryOnceStreamChannel=N.createDataChannel("stream.latest-try-once",dt),this.setupChannel(this.latestTtlStreamChannel),this.setupChannel(this.reliableStreamChannel),this.setupChannel(this.latestReliableStreamChannel),this.setupChannel(this.latestTryOnceStreamChannel)}sendOffer(){return yt(this,void 0,void 0,function*(){if(this.sentOffer||(this.sentOffer=!0,Ze(this.peerConnection)))return;const{peerConnection:N,config:{sendSignal:C}}=this,G=yield N.createOffer();yield N.setLocalDescription(G);const Z={payload:JSON.stringify({description:G})};yield C(Z)})}getChannelFromLabel(N){switch(N){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(N,C){let G;try{G=(0,Pe.encode)(JSON.stringify(C))}catch(Z){return void m.vF.warn("Failed to encode RTC message",{error:Z})}try{N.send(G),this.sessionMetrics.incrementMessageSent(C)}catch(Z){m.vF.warn("Failed to send message to channel",{error:Z,channel:N.label})}}channelNotRecognized(N){return N!==this.latestTtlStreamChannel&&N!==this.latestReliableStreamChannel&&N!==this.latestTryOnceStreamChannel&&N!==this.reliableStreamChannel}setupChannel(N){N.onmessage=C=>{if(this.channelNotRecognized(N))return void m.vF.warn("Received message on unrecognized data channel.");let G;try{G=JSON.parse((0,Pe.decode)(C.data))}catch(Z){return void m.vF.warn("Received unparseable RTC message",{error:Z,channel:N.label})}if(this.lastMessageTimestamp=new Date().getTime(),G=et(G),this.sessionMetrics.incrementMessageReceived(G),!this.handleSystemMessage(N,G)){if(!this.hasCapabilities(G))return void m.vF.warn("Received RTC message that was not within the capability scope of the connection.");(N===this.latestTryOnceStreamChannel||N===this.latestTtlStreamChannel||N===this.latestReliableStreamChannel)&&!this.isLatestMessage(G)||this.config.receive(this.config.remotePeer.id,G)}},N.onerror=C=>{m.vF.warn("Channel error: "+C.error,{error:C.error,sessionId:this.getSessionId(),channelLabel:N.label})},N.onopen=()=>{m.vF.debug("Channel opened",{sessionId:this.getSessionId(),channelLabel:N.label})},N.onclose=()=>{const C={bufferedAmount:N.bufferedAmount,sessionId:this.getSessionId(),channelLabel:N.label};this.closeCalled===!1?m.vF.debug("Unexpected channel closed",C):m.vF.debug("Channel closed",C)}}handleSystemMessage(N,C){switch(C.header.stream.streamType){case"ping":return this.sendSystemMessage(N,{type:"pong",timestamp:I(C.payload.ping)}),!0;case"pong":{const G=new Date().getTime()-I(C.payload.pong);return this.pingTimeMs=G,q.aggregate("rtc-ping-time",G),!0}case"stream-control":return!0;default:return!1}}sendSystemMessage(N,C){if(N.readyState!=="open")return;const G={entityId:I(this.config.localPeer.deviceId||this.config.localPeer.userId),streamName:"$."+C.type,streamType:C.type};let Z;switch(C.type){case"ping":Z={ping:new Date().getTime()};break;case"pong":Z={pong:C.timestamp};break;case"stream-control":Z={streamControl:C.streamControl}}this.sendOnChannel(N,bt(G,Z))}hasCapabilities(N){var C,G;const{localPeer:Z,remotePeer:pe}=this.config,Ue=(C=Z.capabilitySet.streaming)===null||C===void 0?void 0:C.streams,ve=Ue&&Ue.some(fe=>fe.receive&&jt(fe.stream,N.header.stream)),Re=(G=pe.capabilitySet.streaming)===null||G===void 0?void 0:G.streams,Se=Re&&Re.some(fe=>fe.send&&jt(fe.stream,N.header.stream));return ve||Se}isLatestMessage(N){const C=mt(N.header.stream),G=(this.streamLatestTimestamp.get(C)||0)<=N.header.created;return G&&this.streamLatestTimestamp.set(C,N.header.created),G}}var De=function(Ee,N,C,G){return new(C||(C=Promise))(function(Z,pe){function Ue(Se){try{Re(G.next(Se))}catch(fe){pe(fe)}}function ve(Se){try{Re(G.throw(Se))}catch(fe){pe(fe)}}function Re(Se){var fe;Se.done?Z(Se.value):(fe=Se.value,fe instanceof C?fe:new C(function(p){p(fe)})).then(Ue,ve)}Re((G=G.apply(Ee,N||[])).next())})};class Ge{constructor(N){this.config=N,this.connections=[],this.connectingSessions=new Map,this.rtcInstancesConstructed=0,this.updateInterval=M({func:()=>De(this,void 0,void 0,function*(){try{yield this.update()}catch(C){m.vF.warn("RTC update failed",{error:C})}}),delay:250*r.p.millisecond}),this.localPeer=this.createPeer()}send(N,C,G){const Z=this.getActiveConnection(N);Z?Z.isReady()?Z.send(C,G):m.vF.warn("Attempted to send with an active connection to that peer which was not yet ready."):m.vF.warn("Attempted to send with no active connection to that peer.")}controlRemoteStream(N,C){const G=this.getActiveConnection(N);G?G.isReady()?G.controlRemoteStream(C):m.vF.warn("Attempted to control remote stream with an active connection to that peer which was not yet ready."):m.vF.warn("Attempted to control remote stream with no active connection to that peer.")}connect(N){return De(this,void 0,void 0,function*(){const C=yield this.getLocalPeer();if(this.getActiveConnection(N))return void m.vF.warn("Attempted to connect to peer with an already active connection.");let G;try{G=yield this.config.signalingClient.createSession(yield this.config.getToken(),{offerPeerId:C.id,answerPeerId:N})}catch(Z){(0,Tt.e)(Z,Qt.o,pe=>pe.statusCode===404),m.vF.warn("Attempted to connect to peer that does not exist.")}if(G)for(this.connectingSessions.set(G.id,new Date().getTime()),yield this.connectToSession(G);;)switch(yield(0,o.c)(.1),this.getConnectionStatus(N)){case"connecting":continue;case"connected":return G.id;case"disconnected":return}})}getConnectionStatus(N){const C=this.getActiveConnection(N);return C?C.isReady()?"connected":"connecting":"disconnected"}getIceMode(N){const C=this.getActiveConnection(N);if(C)return C.iceMode}disconnect(N){return De(this,void 0,void 0,function*(){const C=this.getActiveConnection(N);C&&(yield this.closeConnection(C))})}getLocalPeer(){return De(this,void 0,void 0,function*(){return yield this.localPeer})}getPeers(){return De(this,void 0,void 0,function*(){return yield this.config.signalingClient.getPeers(yield this.config.getToken())})}getPing(N){const C=this.getActiveConnection(N);if(C)return C.getPing();m.vF.warn("Attempted to get ping time from inactive peer.")}getLastMessageTimestamp(N){const C=this.getActiveConnection(N);if(C)return C.getLastMessageTimestamp();m.vF.warn("Attempted to get ping time from inactive peer.")}shutdown(){return De(this,void 0,void 0,function*(){yield this.updateInterval.stop();const N=this.connections;this.connections=[],yield this.closeConnections(N)})}closeConnection(N){return De(this,void 0,void 0,function*(){this.connectingSessions.delete(N.getSessionId()),yield N.close();try{yield this.config.signalingClient.deleteSession(yield this.config.getToken(),N.getSessionId())}catch(C){(0,Tt.e)(C,Qt.o,G=>G.statusCode===404)}})}getSessions(){return De(this,void 0,void 0,function*(){const N=yield this.getLocalPeer();return(yield this.config.signalingClient.getSessions(yield this.config.getToken())).filter(C=>C.offer.peer.id===N.id||C.answer.peer.id===N.id)})}createPeer(){return De(this,void 0,void 0,function*(){return yield this.config.signalingClient.createPeer(yield this.config.getToken(),{capabilitySet:this.config.capabilitySet||{}})})}createRTCPeerConnection(){return De(this,arguments,void 0,function*(N={}){const C=this.config.alternateRTCPeerConnection||RTCPeerConnection;this.rtcInstancesConstructed++,this.rtcInstancesConstructed%20||zt();try{return new C(Object.assign({iceServers:yield this.config.signalingClient.getIceServers(yield this.config.getToken())},N))}catch(G){throw m.vF.debug(`Failed to create RTCPeerConnection: ${this.rtcInstancesConstructed} total allocated`),G}})}closeConnections(N){return De(this,void 0,void 0,function*(){const C=yield We(N.map(G=>De(this,void 0,void 0,function*(){yield this.closeConnection(G)})));for(const G of C)m.vF.warn("Request to close session failed",{error:G})})}reset(){return De(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(N){return this.connections.find(C=>C.getRemotePeer().id===N&&C.isActive())}update(){return De(this,void 0,void 0,function*(){const N=yield this.getLocalPeer();try{yield this.config.signalingClient.refreshPeer(yield this.config.getToken(),N.id)}catch(C){(0,Tt.e)(C,Qt.o,G=>G.statusCode===404),m.vF.warn("Peer expired, creating new peer",{peerId:N.id}),yield this.reset()}yield this.handleSessions(yield this.getSessions())})}handleSessions(N){return De(this,void 0,void 0,function*(){yield this.syncConnectionsAndSessions(N);const C=N.map(G=>({session:G,connection:this.connections.find(Z=>Z.getSessionId()===G.id)}));yield Promise.all(C.map(G=>De(this,[G],void 0,function*({session:Z,connection:pe}){return yield this.maintainConnection(Z,pe)})))})}syncConnectionsAndSessions(N){return De(this,void 0,void 0,function*(){const C=new Set(N.map(pe=>pe.id)),G=pe=>C.has(pe.getSessionId())||this.connectingSessions.has(pe.getSessionId());this.connections=this.connections.filter(pe=>G(pe));const Z=this.connections.filter(pe=>!G(pe)||pe.needsClosing());yield Promise.all(Z.map(pe=>De(this,void 0,void 0,function*(){yield this.closeConnection(pe)})))})}maintainConnection(N,C){return De(this,void 0,void 0,function*(){const G=yield this.getLocalPeer(),Z=N.offer.peer.id===G.id;if(C){if(C.isReady())try{yield this.config.signalingClient.refreshSession(yield this.config.getToken(),N.id)}catch(pe){(0,Tt.e)(pe,Qt.o,Ue=>Ue.statusCode===404),m.vF.debug("Refresh session not found",{sessionId:N.id})}else if(C.isActive())try{yield this.consumeSignals(C)}catch(pe){m.vF.warn("Failed to ingest signals, closing connection",{error:pe}),yield this.closeConnection(C)}}else{if(Z)return;yield this.connectToSession(N)}})}connectToSession(N){return De(this,void 0,void 0,function*(){const C=yield this.getLocalPeer(),G=N.offer.peer.id===C.id,Z=yield this.createRTCPeerConnection(),pe=new Vt(Z,{localPeer:G?N.offer.peer:N.answer.peer,remotePeer:G?N.answer.peer:N.offer.peer,sessionId:N.id,isOffer:G,sendSignal:Ue=>this.sendSignal(N.id,Ue),receive:(Ue,ve)=>this.config.receive(Ue,ve)});if(this.connections.find(Ue=>Ue.getSessionId()===N.id))return m.vF.warn("connectToSession called on a session that already has a connection.",{sessionId:N.id}),void(yield pe.close());this.setupHandlers(pe),this.connections.push(pe);try{yield pe.connect()}catch(Ue){m.vF.warn("Failed to handle negotiation, closing connection",{error:Ue}),yield this.closeConnection(pe)}})}setupHandlers(N){const{peerConnection:C}=N,G=N.getSessionId();C.onconnectionstatechange=()=>De(this,void 0,void 0,function*(){const Z=this.connectingSessions.get(G);if(Z===void 0)return;const pe=C.connectionState;switch(Ze(C)&&this.connectingSessions.delete(G),pe){case"connected":{this.connectingSessions.delete(G);const Ue=new Date().getTime()-Z;q.aggregate("rtc-connect-time",Ue);break}case"failed":q.increment("rtc-connect-failed"),yield this.closeConnection(N)}})}consumeSignals(N){return De(this,void 0,void 0,function*(){let C=[];try{C=yield this.config.signalingClient.takeSignals(yield this.config.getToken(),N.getSessionId())}catch(G){(0,Tt.e)(G,Qt.o,Z=>Z.statusCode===404)}for(const G of C)yield N.handleSignal(G)})}sendSignal(N,C){return De(this,void 0,void 0,function*(){try{yield this.config.signalingClient.addSignals(yield this.config.getToken(),N,{signals:[C]})}catch(G){(0,Tt.e)(G,Qt.o,Z=>Z.statusCode===404)}})}}})(),__webpack_exports__})())})(dist);var distExports=dist.exports;const SessionTypes={UNKNOWN:0,TELEOP:1,PORT_FORWARD:2,OBSERVE:3,HEADLESS:4},SessionTypeConstants={...SessionTypes,Unknown:SessionTypes.UNKNOWN,Teleop:SessionTypes.TELEOP,PortForward:SessionTypes.PORT_FORWARD,Observe:SessionTypes.OBSERVE,Headless:SessionTypes.HEADLESS,unknown:SessionTypes.UNKNOWN,teleop:SessionTypes.TELEOP,portForward:SessionTypes.PORT_FORWARD,observe:SessionTypes.OBSERVE,headless:SessionTypes.HEADLESS},singleton=Symbol("RtcClientPool.instance");class RtcClientPool{constructor(t){_e(this,Jt,null);_e(this,"createClient");_e(this,"ttlMs");_e(this,"proxyHandler");_e(this,"proxyReceivers",new Map);_e(this,"teardownTimeout",null);_e(this,"dispatch",(t,n)=>{this.proxyReceivers.forEach(r=>r==null?void 0:r(t,n))});const{createClient:n,ttlMs:r=0}=t;this.createClient=n,this.ttlMs=Math.max(r,0),this.proxyHandler={get:(o,s,c)=>{switch(s){case"shutdown":return()=>this.releaseInstance(c);default:return Reflect.get(o,s,c)}}}}get isActive(){return this[singleton]!==null}get size(){return this.proxyReceivers.size}get(t){const n=new Proxy(this.allocate(),this.proxyHandler);return this.proxyReceivers.set(n,t!=null?t:null),n}allocate(){if(this[singleton])return this.teardownTimeout&&(clearTimeout(this.teardownTimeout),this.teardownTimeout=null),this[singleton];const t=this.createClient(this.dispatch);return this[singleton]=t,t}async teardown(){const t=this[singleton];if(!t){console.warn("singleton has already been shutdown!");return}try{await t.shutdown()}finally{this[singleton]=null}}async releaseInstance(t){return this.proxyReceivers.delete(t)?this.proxyReceivers.size!==0?!1:(!this.teardownTimeout&&Number.isFinite(this.ttlMs)&&(this.ttlMs===0?await this.teardown():this.teardownTimeout=setTimeout(()=>{this.teardown().catch(n=>console.error("teardown failed",{err:n})).finally(()=>this.teardownTimeout=null)},this.ttlMs)),!0):(console.warn("this instance has already been released!"),!1)}}Jt=singleton;const getToken=async()=>defined$1(Authentication.token,"Realtime when user isn't authorized"),EnumRtcClientPools={[SessionTypes.UNKNOWN]:new RtcClientPool({ttlMs:2500,createClient:e=>new distExports.RtcClient({signalingClient:new distExports.SignalingPromiseClient(exports.FORMANT_API_URL),getToken,sessionType:SessionTypes.UNKNOWN,receive:e})}),[SessionTypes.TELEOP]:new RtcClientPool({ttlMs:2500,createClient:e=>new distExports.RtcClient({signalingClient:new distExports.SignalingPromiseClient(exports.FORMANT_API_URL),getToken,sessionType:SessionTypes.TELEOP,receive:e})}),[SessionTypes.PORT_FORWARD]:new RtcClientPool({ttlMs:2500,createClient:e=>new distExports.RtcClient({signalingClient:new distExports.SignalingPromiseClient(exports.FORMANT_API_URL),getToken,sessionType:SessionTypes.PORT_FORWARD,receive:e})}),[SessionTypes.OBSERVE]:new RtcClientPool({ttlMs:2500,createClient:e=>new distExports.RtcClient({signalingClient:new distExports.SignalingPromiseClient(exports.FORMANT_API_URL),getToken,sessionType:SessionTypes.OBSERVE,receive:e})}),[SessionTypes.HEADLESS]:new RtcClientPool({ttlMs:2500,createClient:e=>new distExports.RtcClient({signalingClient:new distExports.SignalingPromiseClient(exports.FORMANT_API_URL),getToken,sessionType:SessionTypes.HEADLESS,receive:e})})},AppRtcClientPools={...EnumRtcClientPools,unknown:EnumRtcClientPools[SessionTypes.UNKNOWN],teleop:EnumRtcClientPools[SessionTypes.TELEOP],portForward:EnumRtcClientPools[SessionTypes.PORT_FORWARD],observe:EnumRtcClientPools[SessionTypes.OBSERVE],headless:EnumRtcClientPools[SessionTypes.HEADLESS]},defaultRtcClientPool=EnumRtcClientPools[SessionTypes.TELEOP],getRtcClientPool=e=>{const{sessionType:t}=e;return t?AppRtcClientPools[t]:defaultRtcClientPool};async function getPeers(){if(!Authentication.token)throw new Error("Not authenticated");const e=defaultRtcClientPool.get();try{return await e.getPeers()}finally{await e.shutdown()}}async function getRealtimeSessions(){if(!Authentication.token)throw new Error("Not authenticated");const e=defaultRtcClientPool.get();try{return await e.getSessions()}finally{await e.shutdown()}}async function getTelemetry(e,t,n,r,o,s){let c=e;Array.isArray(e)||(c=[e]);let l=t;return Array.isArray(t)||(l=[t]),(await(await fetch(`${exports.FORMANT_API_URL}/v1/queries/queries`,{method:"POST",body:JSON.stringify({deviceIds:c,end:r.toISOString(),names:l,start:n.toISOString(),tags:o,latestOnly:s}),headers:{"Content-Type":"application/json",Authorization:"Bearer "+Authentication.token}})).json()).items}async function patchDevice(e,t){if(!Authentication.token)throw new Error("Not authenticated");return await(await fetch(`${exports.FORMANT_API_URL}/v1/admin/devices/${e}`,{method:"PATCH",body:JSON.stringify(t),headers:{"Content-Type":"application/json",Authorization:"Bearer "+Authentication.token}})).json()}async function queryDevicesData(e){if(!Authentication.token)throw new Error("Not authenticated");return(await(await fetch(`${exports.FORMANT_API_URL}/v1/admin/devices/query`,{method:"POST",body:JSON.stringify(e),headers:{"Content-Type":"application/json",Authorization:"Bearer "+Authentication.token}})).json()).items}const isRtcPeer=e=>e!==void 0&&e.capabilities!==void 0&&e.capabilitySet!==void 0;var eventemitter3={exports:{}};(function(e){var t=Object.prototype.hasOwnProperty,n="~";function r(){}Object.create&&(r.prototype=Object.create(null),new r().__proto__||(n=!1));function o(u,d,h){this.fn=u,this.context=d,this.once=h||!1}function s(u,d,h,R,y){if(typeof h!="function")throw new TypeError("The listener must be a function");var Q=new o(h,R||u,y),f=n?n+d:d;return u._events[f]?u._events[f].fn?u._events[f]=[u._events[f],Q]:u._events[f].push(Q):(u._events[f]=Q,u._eventsCount++),u}function c(u,d){--u._eventsCount===0?u._events=new r:delete u._events[d]}function l(){this._events=new r,this._eventsCount=0}l.prototype.eventNames=function(){var d=[],h,R;if(this._eventsCount===0)return d;for(R in h=this._events)t.call(h,R)&&d.push(n?R.slice(1):R);return Object.getOwnPropertySymbols?d.concat(Object.getOwnPropertySymbols(h)):d},l.prototype.listeners=function(d){var h=n?n+d:d,R=this._events[h];if(!R)return[];if(R.fn)return[R.fn];for(var y=0,Q=R.length,f=new Array(Q);y<Q;y++)f[y]=R[y].fn;return f},l.prototype.listenerCount=function(d){var h=n?n+d:d,R=this._events[h];return R?R.fn?1:R.length:0},l.prototype.emit=function(d,h,R,y,Q,f){var S=n?n+d:d;if(!this._events[S])return!1;var U=this._events[S],b=arguments.length,T,F;if(U.fn){switch(U.once&&this.removeListener(d,U.fn,void 0,!0),b){case 1:return U.fn.call(U.context),!0;case 2:return U.fn.call(U.context,h),!0;case 3:return U.fn.call(U.context,h,R),!0;case 4:return U.fn.call(U.context,h,R,y),!0;case 5:return U.fn.call(U.context,h,R,y,Q),!0;case 6:return U.fn.call(U.context,h,R,y,Q,f),!0}for(F=1,T=new Array(b-1);F<b;F++)T[F-1]=arguments[F];U.fn.apply(U.context,T)}else{var w=U.length,B;for(F=0;F<w;F++)switch(U[F].once&&this.removeListener(d,U[F].fn,void 0,!0),b){case 1:U[F].fn.call(U[F].context);break;case 2:U[F].fn.call(U[F].context,h);break;case 3:U[F].fn.call(U[F].context,h,R);break;case 4:U[F].fn.call(U[F].context,h,R,y);break;default:if(!T)for(B=1,T=new Array(b-1);B<b;B++)T[B-1]=arguments[B];U[F].fn.apply(U[F].context,T)}}return!0},l.prototype.on=function(d,h,R){return s(this,d,h,R,!1)},l.prototype.once=function(d,h,R){return s(this,d,h,R,!0)},l.prototype.removeListener=function(d,h,R,y){var Q=n?n+d:d;if(!this._events[Q])return this;if(!h)return c(this,Q),this;var f=this._events[Q];if(f.fn)f.fn===h&&(!y||f.once)&&(!R||f.context===R)&&c(this,Q);else{for(var S=0,U=[],b=f.length;S<b;S++)(f[S].fn!==h||y&&!f[S].once||R&&f[S].context!==R)&&U.push(f[S]);U.length?this._events[Q]=U.length===1?U[0]:U:c(this,Q)}return this},l.prototype.removeAllListeners=function(d){var h;return d?(h=n?n+d:d,this._events[h]&&c(this,h)):(this._events=new r,this._eventsCount=0),this},l.prototype.off=l.prototype.removeListener,l.prototype.addListener=l.prototype.on,l.prefixed=n,l.EventEmitter=l,e.exports=l})(eventemitter3);var eventemitter3Exports=eventemitter3.exports;const EventEmitter=getDefaultExportFromCjs(eventemitter3Exports);class Manipulator{constructor(t,n){_e(this,"currentListeners",[]);_e(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){_e(this,"channel");_e(this,"requestIdToResponseMap",new Map);this.device=t,this.channel_name=n,this.timeout=r}addOpenListener(t){defined$1(this.channel,"channel not initalized").addOpenListener(t)}removeOpenListener(t){defined$1(this.channel,"channel not initalized").removeOpenListener(t)}addCloseListener(t){defined$1(this.channel,"channel not initalized").addCloseListener(t)}removeCloseListener(t){defined$1(this.channel,"channel not initalized").removeCloseListener(t)}addErrorListener(t){defined$1(this.channel,"channel not initalized").addErrorListener(t)}removeErrorListener(t){defined$1(this.channel,"channel not initalized").removeErrorListener(t)}}class BinaryRequestDataChannel extends RequestDataChannel{constructor(){super(...arguments);_e(this,"RESPONSE_SUCCESS_BYTE",0);_e(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 s=n.slice(16);if(s.length===0)throw new Error("Invalid response");this.requestIdToResponseMap.has(o)&&this.requestIdToResponseMap.set(o,s)})}async request(n){if(this.channel||await this.initialize(),!this.channel)throw new Error("Failed to create channel");const{channel:r,requestIdToResponseMap:o,timeout:s}=this;await r.waitTilReady();const c=this.generateBinaryId(),l=c.toString();o.set(l,!0),r.sendBinary(new Uint8Array([...c,...n]));const u=new Date().getTime();for(;new Date().getTime()<u+s;)if(await delay$1(50),o.has(l)){const d=o.get(l);if(d!==!0){o.delete(l);const h=d[0]===this.RESPONSE_SUCCESS_BYTE,R=d.slice(1);if(h)return R;throw console.error({name:"AdapterError",message:this.decoder.decode(R)}),new Error("Binary request datachannel adapter error")}}throw o.delete(l),console.error({name:"TimeoutError",message:`Request timed out after ${s/1e3} seconds`}),new Error("Binary request data channel request timed out")}}class TextRequestDataChannel extends RequestDataChannel{generateTextId(){return Math.random().toString(36).substring(2)+"-"+Math.random().toString(36).substring(2)}async initialize(){this.channel=await this.device.createCustomDataChannel(this.channel_name),this.channel.addListener(t=>{const n=JSON.parse(t),{id:r,data:o,error:s}=n;if(!r)throw new Error("Invalid response");if(!o&&!s)throw new Error("Invalid response");this.requestIdToResponseMap.has(r)&&this.requestIdToResponseMap.set(r,n)})}async request(t){if(this.channel||await this.initialize(),!this.channel)throw new Error("Failed to create channel");const{channel:n,requestIdToResponseMap:r,timeout:o}=this;await n.waitTilReady();const s=this.generateTextId();r.set(s,!0),n.send(JSON.stringify({id:s,data:t}));const c=new Date().getTime();for(;new Date().getTime()<c+o;)if(await delay$1(50),r.has(s)){const l=r.get(s);if(l!==!0){r.delete(s);const{data:u,error:d}=l;if(u)return u;if(d)throw console.error({name:"AdapterError",message:d}),new Error("Text request datachannel adapter error")}}throw r.delete(s),console.error({name:"TimeoutError",message:`Request timed out after ${o/1e3} seconds`}),new Error("Text request datachannel request timed out")}}class BaseDevice extends EventEmitter{constructor(){super(...arguments);_e(this,"rtcClient");_e(this,"remoteDevicePeerId",null);_e(this,"realtimeListeners",[]);_e(this,"connectionMonitorInterval");_e(this,"handleMessage",(n,r)=>{this.realtimeListeners.forEach(o=>o(n,r))})}stopConnectionMonitoring(){clearInterval(this.connectionMonitorInterval),this.connectionMonitorInterval=void 0}assertNotCancelled(n){if(n)throw new Error("Cancelled by deadline")}getRealtimeStatus(){if(this.rtcClient&&this.remoteDevicePeerId)return this.rtcClient.getConnectionStatus(this.remoteDevicePeerId);throw new Error("Realtime connection hasn't been started")}getRealtimePingInfo(){if(this.rtcClient&&this.remoteDevicePeerId)return this.rtcClient.getPingInfo(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")}addRealtimeListener(n){this.realtimeListeners.push(n)}removeRealtimeListener(n){const r=this.realtimeListeners.indexOf(n);if(r===-1)throw new Error("Could not find realtime listener to remove");this.realtimeListeners.splice(r,1)}async getRealtimeManipulators(){var o;const n=await this.getConfiguration(),r=[];for(const s of(o=n.teleop.rosStreams)!=null?o:[])s.topicType=="sensor_msgs/JointState"&&r.push(new Manipulator(this,{currentJointStateStream:{name:s.topicName},plannedJointStateStream:s.plannedTopic?{name:s.plannedTopic}:void 0,planValidStream:s.planValidTopic?{name:s.planValidTopic}:void 0,endEffectorStream:s.endEffectorTopic?{name:s.endEffectorTopic}:void 0,endEffectorLinkName:s.endEffectorLinkName,baseReferenceFrame:s.baseReferenceFrame,localFrame:s.localFrame}));return r}async getRealtimeVideoStreams(){var o,s,c,l,u,d;const n=await this.getConfiguration(),r=[];for(const h of(s=(o=n.teleop)==null?void 0:o.hardwareStreams)!=null?s:[])h.rtcStreamType==="h264-video-frame"&&r.push({name:h.name});for(const h of(l=(c=n.teleop)==null?void 0:c.rosStreams)!=null?l:[])h.topicType=="formant/H264VideoFrame"&&r.push({name:h.topicName}),(h.topicType==="sensor_msgs/Image"||h.topicType==="sensor_msgs/CompressedImage")&&h.encodeVideo&&r.push({name:h.topicName});for(const h of(d=(u=n.teleop)==null?void 0:u.customStreams)!=null?d:[])h.rtcStreamType==="h264-video-frame"&&r.push({name:h.name});return r}createCustomRequestDataChannel(n,r=3e3){return new TextRequestDataChannel(this,n,r)}createCustomBinaryRequestDataChannel(n,r=3e3){return new BinaryRequestDataChannel(this,n,r)}async startListeningToRealtimeVideo(n){const r=defined$1(this.rtcClient,"Realtime connection has not been started"),o=await this.getRemotePeer();r.controlRemoteStream(defined$1(o).id,{streamName:n.name,enable:!0,pipeline:"rtc"})}async stopListeningToRealtimeVideo(n){const r=defined$1(this.rtcClient,"Realtime connection has not been started"),o=await this.getRemotePeer();r.controlRemoteStream(defined$1(o).id,{streamName:n.name,enable:!1,pipeline:"rtc"})}async startListeningToRealtimeDataStream(n){const r=defined$1(this.rtcClient,"Realtime connection has not been started"),o=await this.getRemotePeer();r.controlRemoteStream(defined$1(o).id,{streamName:n.name,enable:!0,pipeline:"rtc"})}async stopListeningToRealtimeDataStream(n){const r=defined$1(this.rtcClient,"Realtime connection has not been started"),o=await this.getRemotePeer();r.controlRemoteStream(defined$1(o).id,{streamName:n.name,enable:!1,pipeline:"rtc"})}async enableRealtimeTelemetryPriorityIngestion(n){const r=defined$1(this.rtcClient,"Realtime connection has not been started"),o=await this.getRemotePeer();r.controlRemoteStream(defined$1(o).id,{streamName:n,enablePriorityUpload:!0,pipeline:"telemetry"})}async disableRealtimeTelemetryPriorityIngestion(n){const r=defined$1(this.rtcClient,"Realtime connection has not been started"),o=await this.getRemotePeer();r.controlRemoteStream(defined$1(o).id,{streamName:n,enablePriorityUpload:!1,pipeline:"telemetry"})}async changeStreamAudioType(n,r){const o=defined$1(this.rtcClient,"Realtime connection has not been started"),s=await this.getRemotePeer();o.controlRemoteStream(defined$1(s).id,{streamName:n,setAudioFormat:r})}async createCustomDataChannel(n,r){const o=defined$1(this.rtcClient,"Realtime connection has not been started"),s=await this.getRemotePeer(),c=await new Promise(l=>{o.createCustomDataChannel(defined$1(s).id,n,{ordered:!0,...r},!1,(u,d)=>{const h=new DataChannel(d);l(h)})});return await c.waitTilReady(),c}async sendRealtimeMessage(n,r={channelLabel:"stream.reliable"}){const o=defined$1(this.rtcClient,"Realtime connection has not been started"),s=await this.getRemotePeer();o.send(defined$1(s).id,n,r)}async getRealtimeAudioStreams(){var o,s,c,l,u,d;const n=await this.getConfiguration(),r=[];for(const h of(s=(o=n.teleop)==null?void 0:o.hardwareStreams)!=null?s:[])h.rtcStreamType==="audio-chunk"&&r.push({name:h.name});for(const h of(l=(c=n.teleop)==null?void 0:c.rosStreams)!=null?l:[])h.topicType=="audio_common_msgs/AudioData"&&r.push({name:h.topicName});for(const h of(d=(u=n.teleop)==null?void 0:u.customStreams)!=null?d:[])h.rtcStreamType==="audio-chunk"&&r.push({name:h.name});return r}}class Device extends BaseDevice{constructor(t,n,r,o){super(),this.id=t,this.name=n,this.organizationId=r,this.tags=o}async getLatestTelemetry(){return(await(await fetch(`${exports.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(t=!1){let n=await fetch(`${exports.FORMANT_API_URL}/v1/admin/devices/${this.id}`,{method:"GET",headers:{"Content-Type":"application/json",Authorization:"Bearer "+Authentication.token}});const r=await n.json();if(!r.state.reportedConfiguration)throw new Error("Device has no configuration, has it ever been turned on?");const o=t?r.desiredConfigurationVersion:r.state.reportedConfiguration.version;return n=await fetch(`${exports.FORMANT_API_URL}/v1/admin/devices/${this.id}/configurations/${o}`,{method:"GET",headers:{"Content-Type":"application/json",Authorization:"Bearer "+Authentication.token}}),(await n.json()).document}async getAgentVersion(){var r;const n=await(await fetch(`${exports.FORMANT_API_URL}/v1/admin/devices/${this.id}`,{method:"GET",headers:{"Content-Type":"application/json",Authorization:"Bearer "+Authentication.token}})).json();return(r=n==null?void 0:n.state)==null?void 0:r.agentVersion}async getFileUrl(t){return(await(await fetch(`${exports.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}async startRealtimeConnection(t={}){if(console.debug(`${new Date().toISOString()} :: Connection start requested`),this.rtcClient&&this.connectionMonitorInterval!==void 0)throw new Error(`Already created realtime connection to device ${this.id}`);this.rtcClient&&console.warn("overwriting existing rtcClient due to missing connectionMonitorInterval");const{sessionType:n,deadlineMs:r=1e4,maxConnectRetries:o=3}=typeof t=="number"?{sessionType:t}:t,c=getRtcClientPool({sessionType:n}).get(this.handleMessage);this.rtcClient=c;let l=!1;const u=new Promise((h,R)=>setTimeout(()=>{l=!0,R(new Error("Connection timed out: the connection could not be finalized in time, possibly due to network issues or misconfigured settings."))},r)),d=async()=>{if("isReady"in c)for(;!c.isReady();)this.assertNotCancelled(l),await delay$1(100);const h=await this.getRemoteDevicePeerId(c);this.assertNotCancelled(l);let R;for(let Q=0;Q<o&&(R=await c.connect(h),!R);Q++)delay$1(100),this.assertNotCancelled(l);if(!R)throw new Error(`Session could not be created: exhausted ${o} retries`);let y=0;for(;!l&&c.getConnectionStatus(h)!=="connected";)await delay$1(100),y+=1;return this.assertNotCancelled(l),console.debug(`${new Date().toISOString()} :: Connection completed after ${y} retries`),h};return Promise.race([d(),u]).then(h=>{this.remoteDevicePeerId=h,this.initConnectionMonitoring(),this.emit("connect")}).catch(h=>{throw console.debug(`${new Date().toISOString()} :: Connection failed: %o`,h),this.rtcClient=void 0,this.remoteDevicePeerId=null,c.shutdown().catch(R=>{console.error("rtcClient cannot shutdown: %o",R)}),this.emit("connection_failed",h),h})}async getRemoteDevicePeerId(t){const r=(await t.getPeers()).find(o=>o.deviceId===this.id);if(!isRtcPeer(r))throw new Error("Cannot find peer, is the robot offline?");return r.id}initConnectionMonitoring(){this.connectionMonitorInterval=setInterval(async()=>{let t=!1;if(this.rtcClient){const r=this.rtcClient.getConnections().find(o=>o.getRemotePeerId()===this.remoteDevicePeerId&&o.isActive());(r===void 0||!r.isReady())&&(console.debug(`${new Date().toISOString()} :: data channel closed`),t=!0)}(!this.rtcClient||!this.remoteDevicePeerId||await this.rtcClient.getConnectionStatsInfo(this.remoteDevicePeerId)===void 0||t)&&(this.emit("disconnect"),this.stopRealtimeConnection().catch(n=>{console.error(n)}))},1e3)}async getRemotePeer(){const n=(await defined$1(this.rtcClient,"Realtime connection has not been started").getPeers()).find(r=>r.deviceId===this.id);return defined$1(n,"Could not find remote peer for device "+this.id)}async stopRealtimeConnection(){let t=!1;if(this.rtcClient){this.stopConnectionMonitoring(),this.remoteDevicePeerId?(await this.rtcClient.disconnect(this.remoteDevicePeerId),this.remoteDevicePeerId=null):t=!0;try{await this.rtcClient.shutdown()}finally{this.rtcClient=void 0}}if(t)throw new Error(`Realtime connection hasn't been started for ${this.id}`)}async isInRealtimeSession(){const t=await getPeers(),n=await getRealtimeSessions(),r=t.find(o=>o.deviceId===this.id);return r?n[r.id].length>0:!1}async getAvailableCommands(t=!0){return(await(await fetch(`${exports.FORMANT_API_URL}/v1/admin/command-templates/`,{method:"GET",headers:{"Content-Type":"application/json",Authorization:"Bearer "+Authentication.token}})).json()).items.filter(o=>t?!0:o.enabled)}async sendCommand(t,n,r,o,s){var R;const l=(await this.getAvailableCommands(!1)).find(y=>s?y.id===s:y.name===t);if(!l)throw new Error(`Could not find command with name "${t}"`);let u="";n===void 0?l.parameterEnabled&&l.parameterValue&&(u=l.parameterValue):u=n;const d={value:u,scrubberTime:(r||new Date).toISOString(),meta:{...l.parameterMeta,...o}};return await fetch(`${exports.FORMANT_API_URL}/v1/admin/commands`,{method:"POST",body:JSON.stringify({commandTemplateId:l.id,organizationId:this.organizationId,deviceId:this.id,command:l.command,parameter:d,userId:(R=Authentication.currentUser)==null?void 0:R.id}),headers:{"Content-Type":"application/json",Authorization:"Bearer "+Authentication.token}})}async getCommand(t){return await fetch(`${exports.FORMANT_API_URL}/v1/admin/commands/${t}`,{method:"GET",headers:{"Content-Type":"application/json",Authorization:"Bearer "+Authentication.token}})}async createCaptureStream(t){const r=await(await fetch(`${exports.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,s,c,l){if(s!==void 0||c!==void 0)throw new Error("Limit and offset are not supported in this method");return await getTelemetry(this.id,t,n,r,o,l)}async queryEvents(t){if(t.deviceIds)throw new Error("Cannot filter multiple devices via Device class");return t.deviceIds=[this.id],queryEvents(t)}async getTelemetryStreams(){var l,u;const t=await this.getConfiguration(),n=await fetch(`${exports.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(u=(l=t.telemetry)==null?void 0:l.streams)==null||u.forEach(d=>{d.disabled!==!0&&r.push(d.name),d.onDemand===!0&&o.push(d.name)}),console.log(o),(await n.json()).items.filter(d=>!r.includes(d)).map(d=>({name:d,onDemand:o.includes(d)}))}async createInterventionRequest(t,n,r,o){return await(await fetch(`${exports.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(`${exports.FORMANT_API_URL}/v1/admin/intervention-responses`,{method:"POST",body:JSON.stringify({interventionId:t,interventionType:n,data:r}),headers:{"Content-Type":"application/json",Authorization:"Bearer "+Authentication.token}})).json()}async getAnnotationCount(t,n){return await getAnnotationCount({...t,deviceIds:[this.id]},n)}async getAnnotationCountByIntervals(t,n,r){return await getAnnotationCountByIntervals({...t,deviceIds:[this.id]},n,r)}async eventsCounter(t,n,r,o,s){return await eventsCounter(t,n,r,o,{...s,deviceIds:[this.id]})}async createShareLink(t,n){return t.scope.deviceIds=[this.id],await createShareLink(t,n)}}_e(Device,"createDevice",createDevice),_e(Device,"patchDevice",patchDevice),_e(Device,"getDevicesData",getDevicesData),_e(Device,"queryDevicesData",queryDevicesData),_e(Device,"disableDevice",disableDevice);class PeerDevice extends BaseDevice{constructor(n){super();_e(this,"id");_e(this,"telemetryStreamActive",!1);_e(this,"streamTelemetry",{});this.peerUrl=n}async getLatestTelemetry(){this.telemetryStreamActive||this.subscribeToTelemetry();const n=this.streamTelemetry;return Object.entries(n).map(([o,s])=>({deviceId:this.id,streamName:o,streamType:"json",currentValue:s,currentValueTime:s.timestamp,tags:{}}))}async getTelemetry(n,r,o,s,c,l,u){if(Array.isArray(n))throw new Error("Multiple stream names not supported");if(s)throw new Error("Tags not supported");if(u&&c===void 0)c=1;else if(u&&c!==void 0)throw new Error("latestOnly and limit cannot be used together");let d=`${this.peerUrl}/v1/querydatapoints?stream_name=${n}&start=${r.toISOString()}&end=${o.toISOString()}`;c!=null&&c>0&&(d+=`&limit=${c}`),l!=null&&l>=0&&(d+=`&offset=${l}`);const R=await(await fetch(d)).json(),y=[];for(const Q of R.results){const f=parseInt(Q.timestamp),S=Q.tags.data_type;delete Q.tags.data_type,y.push({deviceId:this.id,name:Q.stream,points:[[f,this.getPointPayload(S,Q)]],tags:Q.tags,type:S})}return y.reverse()}async queryEvents(n){const r=["id","viewed","keyword","message","sort","eventTypes","notificationEnabled","userIds","annotationTemplateIds","disableNullMatches","severities","deviceIds","names","types","tags","notNames"];this.checkKeysAndThrow(n,r);let o=`${this.peerUrl}/v1/queryevents?start=${n.start}&end=${n.end}`;n.count!=null&&n.count>0&&(o+=`&limit=${n.count}`),n.offset!=null&&n.offset>=0&&(o+=`&offset=${n.offset}`);const c=await(await fetch(o)).json(),l=[];for(const u of c.results){const d=parseInt(u.timestamp),h={deviceId:this.id,time:new Date(d).toISOString(),message:u.message,notificationEnabled:u.notificationEnabled,type:u.type,tags:u.tags};u.id!==""&&(h.id=u.id),u.type!==""&&(h.type=u.type),u.streamName!==""&&(h.streamName=u.streamName),u.streamType!==""&&(h.streamType=u.streamType),u.severity!==""&&(h.severity=u.severity.toLowerCase()),u.tags&&(h.tags=u.tags),u.endTimestamp!=="0"&&(h.endTime=new Date(parseInt(u.endTimestamp)).toISOString()),l.push(h)}return l.reverse()}checkKeysAndThrow(n,r){const o=r.filter(s=>s in n);if(o.length>0)throw new Error(`Filters not currently supported: ${o.join(", ")}.`)}getPointPayload(n,r){switch(n){case"numeric":return r.numeric.value;case"numeric set":return r.numericSet.numerics;case"text":return r.text.value;case"json":return r.json.value;case"bitset":const o=[],s=[];for(const c of r.bitset.bits)o.push(c.key),s.push(c.value);return{keys:o,values:s};case"location":return r.location;case"health":return r.health;case"battery":return r.battery;default:return{}}}subscribeToTelemetry(){this.telemetryStreamActive=!0;let n=0;const r=new XMLHttpRequest;r.responseType="text",r.addEventListener("error",o=>{this.handleXHRError("error")}),r.addEventListener("abort",o=>{this.handleXHRError("abort")}),r.addEventListener("timeout",o=>{this.handleXHRError("timeout")}),r.addEventListener("readystatechange",o=>{r.readyState===XMLHttpRequest.DONE&&this.handleXHRError("closed")}),r.addEventListener("progress",o=>{const s=o.loaded,c=s-n;n=s,r.responseText.substr(-c).split(`
127
+ `),stack:S&&S.stack,rejection:!0,date:new Date().toString(),process:this.getProcessInfo(),os:this.getOsInfo(),trace:this.getTrace(S)}}},{key:"getProcessInfo",value:function(){return{pid:process.pid,uid:process.getuid?process.getuid():null,gid:process.getgid?process.getgid():null,cwd:process.cwd(),execPath:process.execPath,version:process.version,argv:process.argv,memoryUsage:process.memoryUsage()}}},{key:"getOsInfo",value:function(){return{loadavg:c.loadavg(),uptime:c.uptime()}}},{key:"getTrace",value:function(S){return(S?h.parse(S):h.get()).map(function(U){return{column:U.getColumnNumber(),file:U.getFileName(),function:U.getFunctionName(),line:U.getLineNumber(),method:U.getMethodName(),native:U.isNative()}})}},{key:"_addHandler",value:function(S){if(!this.handlers.has(S)){S.handleRejections=!0;var U=new R(S);this.handlers.set(S,U),this.logger.pipe(U)}}},{key:"_unhandledRejection",value:function(S){var U,b=this.getAllInfo(S),T=this._getRejectionHandlers(),F=typeof this.logger.exitOnError=="function"?this.logger.exitOnError(S):this.logger.exitOnError;function w(){u("doExit",F),u("process._exiting",process._exiting),F&&!process._exiting&&(U&&clearTimeout(U),process.exit(1))}if(!T.length&&F&&(console.warn("winston: exitOnError cannot be true with no rejection handlers."),console.warn("winston: not exiting process."),F=!1),!T||T.length===0)return process.nextTick(w);l(T,function(B,Y){var A=d(Y),L=B.transport||B;function m(H){return function(){u(H),A()}}L._ending=!0,L.once("finish",m("finished")),L.once("error",m("error"))},function(){return F&&w()}),this.logger.log(b),F&&(U=setTimeout(w,3e3))}},{key:"_getRejectionHandlers",value:function(){return this.logger.transports.filter(function(S){return(S.transport||S).handleRejections})}}])&&o(y.prototype,Q),f&&o(y,f),Object.defineProperty(y,"prototype",{writable:!1}),y;var y,Q,f}()},888:(e,t,n)=>{function r(h){return(r=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(R){return typeof R}:function(R){return R&&typeof Symbol=="function"&&R.constructor===Symbol&&R!==Symbol.prototype?"symbol":typeof R})(h)}function o(h,R){for(var y=0;y<R.length;y++){var Q=R[y];Q.enumerable=Q.enumerable||!1,Q.configurable=!0,"value"in Q&&(Q.writable=!0),Object.defineProperty(h,s(Q.key),Q)}}function s(h){var R=function(y,Q){if(r(y)!="object"||!y)return y;var f=y[Symbol.toPrimitive];if(f!==void 0){var S=f.call(y,Q||"default");if(r(S)!="object")return S;throw new TypeError("@@toPrimitive must return a primitive value.")}return(Q==="string"?String:Number)(y)}(h,"string");return r(R)=="symbol"?R:R+""}function c(h,R,y){return R=l(R),function(Q,f){if(f&&(r(f)=="object"||typeof f=="function"))return f;if(f!==void 0)throw new TypeError("Derived constructors may only return object or undefined");return function(S){if(S===void 0)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return S}(Q)}(h,function(){try{var Q=!Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],function(){}))}catch{}return function(){return!!Q}()}()?Reflect.construct(R,y||[],l(h).constructor):R.apply(h,y))}function l(h){return(l=Object.setPrototypeOf?Object.getPrototypeOf.bind():function(R){return R.__proto__||Object.getPrototypeOf(R)})(h)}function u(h,R){return(u=Object.setPrototypeOf?Object.setPrototypeOf.bind():function(y,Q){return y.__proto__=Q,y})(h,R)}var d=n(4156).Writable;e.exports=function(h){function R(S){var U;if(function(b,T){if(!(b instanceof T))throw new TypeError("Cannot call a class as a function")}(this,R),U=c(this,R,[{objectMode:!0}]),!S)throw new Error("RejectionStream requires a TransportStream instance.");return U.handleRejections=!0,U.transport=S,U}return function(S,U){if(typeof U!="function"&&U!==null)throw new TypeError("Super expression must either be null or a function");S.prototype=Object.create(U&&U.prototype,{constructor:{value:S,writable:!0,configurable:!0}}),Object.defineProperty(S,"prototype",{writable:!1}),U&&u(S,U)}(R,h),y=R,(Q=[{key:"_write",value:function(S,U,b){return S.rejection?this.transport.log(S,b):(b(),!0)}}])&&o(y.prototype,Q),f&&o(y,f),Object.defineProperty(y,"prototype",{writable:!1}),y;var y,Q,f}(d)},2879:(e,t,n)=>{var r=n(2627),o=n(8888).StringDecoder,s=n(4156).Stream;function c(){}e.exports=function(l,u){var d=Buffer.alloc(65536),h=new o("utf8"),R=new s,y="",Q=0,f=0;return l.start===-1&&delete l.start,R.readable=!0,R.destroy=function(){R.destroyed=!0,R.emit("end"),R.emit("close")},r.open(l.file,"a+","0644",function(S,U){if(S)return u?u(S):R.emit("error",S),void R.destroy();(function b(){if(!R.destroyed)return r.read(U,d,0,d.length,Q,function(T,F){if(T)return u?u(T):R.emit("error",T),void R.destroy();if(!F)return y&&((l.start==null||f>l.start)&&(u?u(null,y):R.emit("line",y)),f++,y=""),setTimeout(b,1e3);var w=h.write(d.slice(0,F));u||R.emit("data",w);for(var B=(w=(y+w).split(/\n+/)).length-1,Y=0;Y<B;Y++)(l.start==null||f>l.start)&&(u?u(null,w[Y]):R.emit("line",w[Y])),f++;return y=w[B],Q+=F,b()});r.close(U,c)})()}),u?R.destroy:R}},810:(e,t,n)=>{function r(S){return(r=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(U){return typeof U}:function(U){return U&&typeof Symbol=="function"&&U.constructor===Symbol&&U!==Symbol.prototype?"symbol":typeof U})(S)}function o(S,U){if(!(S instanceof U))throw new TypeError("Cannot call a class as a function")}function s(S,U){for(var b=0;b<U.length;b++){var T=U[b];T.enumerable=T.enumerable||!1,T.configurable=!0,"value"in T&&(T.writable=!0),Object.defineProperty(S,c(T.key),T)}}function c(S){var U=function(b,T){if(r(b)!="object"||!b)return b;var F=b[Symbol.toPrimitive];if(F!==void 0){var w=F.call(b,T||"default");if(r(w)!="object")return w;throw new TypeError("@@toPrimitive must return a primitive value.")}return(T==="string"?String:Number)(b)}(S,"string");return r(U)=="symbol"?U:U+""}function l(S,U,b){return U=u(U),function(T,F){if(F&&(r(F)=="object"||typeof F=="function"))return F;if(F!==void 0)throw new TypeError("Derived constructors may only return object or undefined");return function(w){if(w===void 0)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return w}(T)}(S,function(){try{var T=!Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],function(){}))}catch{}return function(){return!!T}()}()?Reflect.construct(U,b||[],u(S).constructor):U.apply(S,b))}function u(S){return(u=Object.setPrototypeOf?Object.getPrototypeOf.bind():function(U){return U.__proto__||Object.getPrototypeOf(U)})(S)}function d(S,U){return(d=Object.setPrototypeOf?Object.setPrototypeOf.bind():function(b,T){return b.__proto__=T,b})(S,U)}var h=n(2213),R=n(4966),y=R.LEVEL,Q=R.MESSAGE,f=n(6155);e.exports=function(S){function U(){var w,B=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};return o(this,U),(w=l(this,U,[B])).name=B.name||"console",w.stderrLevels=w._stringArrayToSet(B.stderrLevels),w.consoleWarnLevels=w._stringArrayToSet(B.consoleWarnLevels),w.eol=typeof B.eol=="string"?B.eol:h.EOL,w.forceConsole=B.forceConsole||!1,w._consoleLog=console.log.bind(console),w._consoleWarn=console.warn.bind(console),w._consoleError=console.error.bind(console),w.setMaxListeners(30),w}return function(w,B){if(typeof B!="function"&&B!==null)throw new TypeError("Super expression must either be null or a function");w.prototype=Object.create(B&&B.prototype,{constructor:{value:w,writable:!0,configurable:!0}}),Object.defineProperty(w,"prototype",{writable:!1}),B&&d(w,B)}(U,S),b=U,(T=[{key:"log",value:function(w,B){var Y=this;return setImmediate(function(){return Y.emit("logged",w)}),this.stderrLevels[w[y]]?(console._stderr&&!this.forceConsole?console._stderr.write("".concat(w[Q]).concat(this.eol)):this._consoleError(w[Q]),void(B&&B())):this.consoleWarnLevels[w[y]]?(console._stderr&&!this.forceConsole?console._stderr.write("".concat(w[Q]).concat(this.eol)):this._consoleWarn(w[Q]),void(B&&B())):(console._stdout&&!this.forceConsole?console._stdout.write("".concat(w[Q]).concat(this.eol)):this._consoleLog(w[Q]),void(B&&B()))}},{key:"_stringArrayToSet",value:function(w,B){if(!w)return{};if(B=B||"Cannot make set from type other than Array of string elements",!Array.isArray(w))throw new Error(B);return w.reduce(function(Y,A){if(typeof A!="string")throw new Error(B);return Y[A]=!0,Y},{})}}])&&s(b.prototype,T),F&&s(b,F),Object.defineProperty(b,"prototype",{writable:!1}),b;var b,T,F}(f)},3329:(e,t,n)=>{function r(Y){return(r=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(A){return typeof A}:function(A){return A&&typeof Symbol=="function"&&A.constructor===Symbol&&A!==Symbol.prototype?"symbol":typeof A})(Y)}function o(Y,A){if(!(Y instanceof A))throw new TypeError("Cannot call a class as a function")}function s(Y,A){for(var L=0;L<A.length;L++){var m=A[L];m.enumerable=m.enumerable||!1,m.configurable=!0,"value"in m&&(m.writable=!0),Object.defineProperty(Y,c(m.key),m)}}function c(Y){var A=function(L,m){if(r(L)!="object"||!L)return L;var H=L[Symbol.toPrimitive];if(H!==void 0){var W=H.call(L,m||"default");if(r(W)!="object")return W;throw new TypeError("@@toPrimitive must return a primitive value.")}return(m==="string"?String:Number)(L)}(Y,"string");return r(A)=="symbol"?A:A+""}function l(Y,A,L){return A=u(A),function(m,H){if(H&&(r(H)=="object"||typeof H=="function"))return H;if(H!==void 0)throw new TypeError("Derived constructors may only return object or undefined");return function(W){if(W===void 0)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return W}(m)}(Y,function(){try{var m=!Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],function(){}))}catch{}return function(){return!!m}()}()?Reflect.construct(A,L||[],u(Y).constructor):A.apply(Y,L))}function u(Y){return(u=Object.setPrototypeOf?Object.getPrototypeOf.bind():function(A){return A.__proto__||Object.getPrototypeOf(A)})(Y)}function d(Y,A){return(d=Object.setPrototypeOf?Object.setPrototypeOf.bind():function(L,m){return L.__proto__=m,L})(Y,A)}var h=n(9256),R=n(8558),y=n(481),Q=n(7946),f=n(4966).MESSAGE,S=n(4156),U=S.Stream,b=S.PassThrough,T=n(6155),F=n(7147)("winston:file"),w=n(2213),B=n(2879);e.exports=function(Y){function A(){var W,E=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};function v(k){for(var j=arguments.length,_=new Array(j>1?j-1:0),M=1;M<j;M++)_[M-1]=arguments[M];_.slice(1).forEach(function($){if(E[$])throw new Error("Cannot set ".concat($," and ").concat(k," together"))})}if(o(this,A),(W=l(this,A,[E])).name=E.name||"file",W._stream=new b,W._stream.setMaxListeners(30),W._onError=W._onError.bind(W),E.filename||E.dirname)v("filename or dirname","stream"),W._basename=W.filename=E.filename?R.basename(E.filename):"winston.log",W.dirname=E.dirname||R.dirname(E.filename),W.options=E.options||{flags:"a"};else{if(!E.stream)throw new Error("Cannot log to file without filename or stream.");console.warn("options.stream will be removed in winston@4. Use winston.transports.Stream"),v("stream","filename","maxsize"),W._dest=W._stream.pipe(W._setupStream(E.stream)),W.dirname=R.dirname(W._dest.path)}return W.maxsize=E.maxsize||null,W.rotationFormat=E.rotationFormat||!1,W.zippedArchive=E.zippedArchive||!1,W.maxFiles=E.maxFiles||null,W.eol=typeof E.eol=="string"?E.eol:w.EOL,W.tailable=E.tailable||!1,W.lazy=E.lazy||!1,W._size=0,W._pendingSize=0,W._created=0,W._drain=!1,W._opening=!1,W._ending=!1,W._fileExist=!1,W.dirname&&W._createLogDirIfNotExist(W.dirname),W.lazy||W.open(),W}return function(W,E){if(typeof E!="function"&&E!==null)throw new TypeError("Super expression must either be null or a function");W.prototype=Object.create(E&&E.prototype,{constructor:{value:W,writable:!0,configurable:!0}}),Object.defineProperty(W,"prototype",{writable:!1}),E&&d(W,E)}(A,Y),L=A,(m=[{key:"finishIfEnding",value:function(){var W=this;this._ending&&(this._opening?this.once("open",function(){W._stream.once("finish",function(){return W.emit("finish")}),setImmediate(function(){return W._stream.end()})}):(this._stream.once("finish",function(){return W.emit("finish")}),setImmediate(function(){return W._stream.end()})))}},{key:"log",value:function(W){var E=this,v=arguments.length>1&&arguments[1]!==void 0?arguments[1]:function(){};if(this.silent)return v(),!0;if(this._drain)this._stream.once("drain",function(){E._drain=!1,E.log(W,v)});else{if(!this._rotate){if(this.lazy){if(!this._fileExist)return this._opening||this.open(),void this.once("open",function(){E._fileExist=!0,E.log(W,v)});if(this._needsNewFile(this._pendingSize))return void this._dest.once("close",function(){E._opening||E.open(),E.once("open",function(){E.log(W,v)})})}var k="".concat(W[f]).concat(this.eol),j=Buffer.byteLength(k);this._pendingSize+=j,this._opening&&!this.rotatedWhileOpening&&this._needsNewFile(this._size+this._pendingSize)&&(this.rotatedWhileOpening=!0);var _=this._stream.write(k,M.bind(this));return _?v():(this._drain=!0,this._stream.once("drain",function(){E._drain=!1,v()})),F("written",_,this._drain),this.finishIfEnding(),_}this._stream.once("rotate",function(){E._rotate=!1,E.log(W,v)})}function M(){var $=this;this._size+=j,this._pendingSize-=j,F("logged %s %s",this._size,k),this.emit("logged",W),this._rotate||this._opening||this._needsNewFile()&&(this.lazy?this._endStream(function(){$.emit("fileclosed")}):(this._rotate=!0,this._endStream(function(){return $._rotateFile()})))}}},{key:"query",value:function(W,E){typeof W=="function"&&(E=W,W={}),W=function(te){return(te=te||{}).rows=te.rows||te.limit||10,te.start=te.start||0,te.until=te.until||new Date,r(te.until)!=="object"&&(te.until=new Date(te.until)),te.from=te.from||te.until-864e5,r(te.from)!=="object"&&(te.from=new Date(te.from)),te.order=te.order||"desc",te}(W);var v=R.join(this.dirname,this.filename),k="",j=[],_=0,M=h.createReadStream(v,{encoding:"utf8"});function $(te,P){try{var q=JSON.parse(te);(function(ie){if(ie&&r(ie)==="object"){var ee=new Date(ie.timestamp);if(!(W.from&&ee<W.from||W.until&&ee>W.until||W.level&&W.level!==ie.level))return!0}})(q)&&function(ie){W.rows&&j.length>=W.rows&&W.order!=="desc"?M.readable&&M.destroy():(W.fields&&(ie=W.fields.reduce(function(ee,x){return ee[x]=ie[x],ee},{})),W.order==="desc"&&j.length>=W.rows&&j.shift(),j.push(ie))}(q)}catch(ie){P||M.emit("error",ie)}}M.on("error",function(te){if(M.readable&&M.destroy(),E)return te.code!=="ENOENT"?E(te):E(null,j)}),M.on("data",function(te){for(var P=(te=(k+te).split(/\n+/)).length-1,q=0;q<P;q++)(!W.start||_>=W.start)&&$(te[q]),_++;k=te[P]}),M.on("close",function(){k&&$(k,!0),W.order==="desc"&&(j=j.reverse()),E&&E(null,j)})}},{key:"stream",value:function(){var W=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{},E=R.join(this.dirname,this.filename),v=new U,k={file:E,start:W.start};return v.destroy=B(k,function(j,_){if(j)return v.emit("error",j);try{v.emit("data",_),_=JSON.parse(_),v.emit("log",_)}catch(M){v.emit("error",M)}}),v}},{key:"open",value:function(){var W=this;this.filename&&(this._opening||(this._opening=!0,this.stat(function(E,v){if(E)return W.emit("error",E);F("stat done: %s { size: %s }",W.filename,v),W._size=v,W._dest=W._createStream(W._stream),W._opening=!1,W.once("open",function(){W._stream.emit("rotate")||(W._rotate=!1)})})))}},{key:"stat",value:function(W){var E=this,v=this._getFile(),k=R.join(this.dirname,v);h.stat(k,function(j,_){return j&&j.code==="ENOENT"?(F("ENOENT ok",k),E.filename=v,W(null,0)):j?(F("err ".concat(j.code," ").concat(k)),W(j)):!_||E._needsNewFile(_.size)?E._incFile(function(){return E.stat(W)}):(E.filename=v,void W(null,_.size))})}},{key:"close",value:function(W){var E=this;this._stream&&this._stream.end(function(){W&&W(),E.emit("flush"),E.emit("closed")})}},{key:"_needsNewFile",value:function(W){return W=W||this._size,this.maxsize&&W>=this.maxsize}},{key:"_onError",value:function(W){this.emit("error",W)}},{key:"_setupStream",value:function(W){return W.on("error",this._onError),W}},{key:"_cleanupStream",value:function(W){return W.removeListener("error",this._onError),W.destroy(),W}},{key:"_rotateFile",value:function(){var W=this;this._incFile(function(){return W.open()})}},{key:"_endStream",value:function(){var W=this,E=arguments.length>0&&arguments[0]!==void 0?arguments[0]:function(){};this._dest?(this._stream.unpipe(this._dest),this._dest.end(function(){W._cleanupStream(W._dest),E()})):E()}},{key:"_createStream",value:function(W){var E=this,v=R.join(this.dirname,this.filename);F("create stream start",v,this.options);var k=h.createWriteStream(v,this.options).on("error",function(j){return F(j)}).on("close",function(){return F("close",k.path,k.bytesWritten)}).on("open",function(){F("file open ok",v),E.emit("open",v),W.pipe(k),E.rotatedWhileOpening&&(E._stream=new b,E._stream.setMaxListeners(30),E._rotateFile(),E.rotatedWhileOpening=!1,E._cleanupStream(k),W.end())});return F("create stream ok",v),k}},{key:"_incFile",value:function(W){F("_incFile",this.filename);var E=R.extname(this._basename),v=R.basename(this._basename,E),k=[];this.zippedArchive&&k.push(function(j){var _=this._created>0&&!this.tailable?this._created:"";this._compressFile(R.join(this.dirname,"".concat(v).concat(_).concat(E)),R.join(this.dirname,"".concat(v).concat(_).concat(E,".gz")),j)}.bind(this)),k.push(function(j){this.tailable?this._checkMaxFilesTailable(E,v,j):(this._created+=1,this._checkMaxFilesIncrementing(E,v,j))}.bind(this)),y(k,W)}},{key:"_getFile",value:function(){var W=R.extname(this._basename),E=R.basename(this._basename,W),v=this.rotationFormat?this.rotationFormat():this._created;return!this.tailable&&this._created?"".concat(E).concat(v).concat(W):"".concat(E).concat(W)}},{key:"_checkMaxFilesIncrementing",value:function(W,E,v){if(!this.maxFiles||this._created<this.maxFiles)return setImmediate(v);var k=this._created-this.maxFiles,j=k!==0?k:"",_=this.zippedArchive?".gz":"",M="".concat(E).concat(j).concat(W).concat(_),$=R.join(this.dirname,M);h.unlink($,v)}},{key:"_checkMaxFilesTailable",value:function(W,E,v){var k=this,j=[];if(this.maxFiles){for(var _=this.zippedArchive?".gz":"",M=this.maxFiles-1;M>1;M--)j.push(function($,te){var P=this,q="".concat(E).concat($-1).concat(W).concat(_),ie=R.join(this.dirname,q);h.exists(ie,function(ee){if(!ee)return te(null);q="".concat(E).concat($).concat(W).concat(_),h.rename(ie,R.join(P.dirname,q),te)})}.bind(this,M));y(j,function(){h.rename(R.join(k.dirname,"".concat(E).concat(W).concat(_)),R.join(k.dirname,"".concat(E,"1").concat(W).concat(_)),v)})}}},{key:"_compressFile",value:function(W,E,v){h.access(W,h.F_OK,function(k){if(k)return v();var j=Q.createGzip(),_=h.createReadStream(W),M=h.createWriteStream(E);M.on("finish",function(){h.unlink(W,v)}),_.pipe(j).pipe(M)})}},{key:"_createLogDirIfNotExist",value:function(W){h.existsSync(W)||h.mkdirSync(W,{recursive:!0})}}])&&s(L.prototype,m),H&&s(L,H),Object.defineProperty(L,"prototype",{writable:!1}),L;var L,m,H}(T)},7543:(e,t,n)=>{function r(T){return(r=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(F){return typeof F}:function(F){return F&&typeof Symbol=="function"&&F.constructor===Symbol&&F!==Symbol.prototype?"symbol":typeof F})(T)}function o(T,F){var w=Object.keys(T);if(Object.getOwnPropertySymbols){var B=Object.getOwnPropertySymbols(T);F&&(B=B.filter(function(Y){return Object.getOwnPropertyDescriptor(T,Y).enumerable})),w.push.apply(w,B)}return w}function s(T){for(var F=1;F<arguments.length;F++){var w=arguments[F]!=null?arguments[F]:{};F%2?o(Object(w),!0).forEach(function(B){c(T,B,w[B])}):Object.getOwnPropertyDescriptors?Object.defineProperties(T,Object.getOwnPropertyDescriptors(w)):o(Object(w)).forEach(function(B){Object.defineProperty(T,B,Object.getOwnPropertyDescriptor(w,B))})}return T}function c(T,F,w){return(F=d(F))in T?Object.defineProperty(T,F,{value:w,enumerable:!0,configurable:!0,writable:!0}):T[F]=w,T}function l(T,F){if(!(T instanceof F))throw new TypeError("Cannot call a class as a function")}function u(T,F){for(var w=0;w<F.length;w++){var B=F[w];B.enumerable=B.enumerable||!1,B.configurable=!0,"value"in B&&(B.writable=!0),Object.defineProperty(T,d(B.key),B)}}function d(T){var F=function(w,B){if(r(w)!="object"||!w)return w;var Y=w[Symbol.toPrimitive];if(Y!==void 0){var A=Y.call(w,B||"default");if(r(A)!="object")return A;throw new TypeError("@@toPrimitive must return a primitive value.")}return(B==="string"?String:Number)(w)}(T,"string");return r(F)=="symbol"?F:F+""}function h(T,F,w){return F=R(F),function(B,Y){if(Y&&(r(Y)=="object"||typeof Y=="function"))return Y;if(Y!==void 0)throw new TypeError("Derived constructors may only return object or undefined");return function(A){if(A===void 0)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return A}(B)}(T,function(){try{var B=!Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],function(){}))}catch{}return function(){return!!B}()}()?Reflect.construct(F,w||[],R(T).constructor):F.apply(T,w))}function R(T){return(R=Object.setPrototypeOf?Object.getPrototypeOf.bind():function(F){return F.__proto__||Object.getPrototypeOf(F)})(T)}function y(T,F){return(y=Object.setPrototypeOf?Object.setPrototypeOf.bind():function(w,B){return w.__proto__=B,w})(T,F)}var Q=n(4865),f=n(7500),S=n(4156).Stream,U=n(6155),b=n(1145).configure;e.exports=function(T){function F(){var A,L=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};return l(this,F),(A=h(this,F,[L])).options=L,A.name=L.name||"http",A.ssl=!!L.ssl,A.host=L.host||"localhost",A.port=L.port,A.auth=L.auth,A.path=L.path||"",A.maximumDepth=L.maximumDepth,A.agent=L.agent,A.headers=L.headers||{},A.headers["content-type"]="application/json",A.batch=L.batch||!1,A.batchInterval=L.batchInterval||5e3,A.batchCount=L.batchCount||10,A.batchOptions=[],A.batchTimeoutID=-1,A.batchCallback={},A.port||(A.port=A.ssl?443:80),A}return function(A,L){if(typeof L!="function"&&L!==null)throw new TypeError("Super expression must either be null or a function");A.prototype=Object.create(L&&L.prototype,{constructor:{value:A,writable:!0,configurable:!0}}),Object.defineProperty(A,"prototype",{writable:!1}),L&&y(A,L)}(F,T),w=F,(B=[{key:"log",value:function(A,L){var m=this;this._request(A,null,null,function(H,W){W&&W.statusCode!==200&&(H=new Error("Invalid HTTP Status Code: ".concat(W.statusCode))),H?m.emit("warn",H):m.emit("logged",A)}),L&&setImmediate(L)}},{key:"query",value:function(A,L){typeof A=="function"&&(L=A,A={});var m=(A={method:"query",params:this.normalizeQuery(A)}).params.auth||null;delete A.params.auth;var H=A.params.path||null;delete A.params.path,this._request(A,m,H,function(W,E,v){if(E&&E.statusCode!==200&&(W=new Error("Invalid HTTP Status Code: ".concat(E.statusCode))),W)return L(W);if(typeof v=="string")try{v=JSON.parse(v)}catch(k){return L(k)}L(null,v)})}},{key:"stream",value:function(){var A=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{},L=new S,m=(A={method:"stream",params:A}).params.path||null;delete A.params.path;var H=A.params.auth||null;delete A.params.auth;var W="",E=this._request(A,H,m);return L.destroy=function(){return E.destroy()},E.on("data",function(v){for(var k=(v=(W+v).split(/\n+/)).length-1,j=0;j<k;j++)try{L.emit("log",JSON.parse(v[j]))}catch(_){L.emit("error",_)}W=v[k]}),E.on("error",function(v){return L.emit("error",v)}),L}},{key:"_request",value:function(A,L,m,H){A=A||{},L=L||this.auth,m=m||this.path||"",this.batch?this._doBatch(A,H,L,m):this._doRequest(A,H,L,m)}},{key:"_doBatch",value:function(A,L,m,H){if(this.batchOptions.push(A),this.batchOptions.length===1){var W=this;this.batchCallback=L,this.batchTimeoutID=setTimeout(function(){W.batchTimeoutID=-1,W._doBatchRequest(W.batchCallback,m,H)},this.batchInterval)}this.batchOptions.length===this.batchCount&&this._doBatchRequest(this.batchCallback,m,H)}},{key:"_doBatchRequest",value:function(A,L,m){this.batchTimeoutID>0&&(clearTimeout(this.batchTimeoutID),this.batchTimeoutID=-1);var H=this.batchOptions.slice();this.batchOptions=[],this._doRequest(H,A,L,m)}},{key:"_doRequest",value:function(A,L,m,H){var W=Object.assign({},this.headers);m&&m.bearer&&(W.Authorization="Bearer ".concat(m.bearer));var E=(this.ssl?f:Q).request(s(s({},this.options),{},{method:"POST",host:this.host,port:this.port,path:"/".concat(H.replace(/^\//,"")),headers:W,auth:m&&m.username&&m.password?"".concat(m.username,":").concat(m.password):"",agent:this.agent}));E.on("error",L),E.on("response",function(k){return k.on("end",function(){return L(null,k)}).resume()});var v=b(s({},this.maximumDepth&&{maximumDepth:this.maximumDepth}));E.end(Buffer.from(v(A,this.options.replacer),"utf8"))}}])&&u(w.prototype,B),Y&&u(w,Y),Object.defineProperty(w,"prototype",{writable:!1}),w;var w,B,Y}(U)},3307:(e,t,n)=>{Object.defineProperty(t,"Console",{configurable:!0,enumerable:!0,get:function(){return n(810)}}),Object.defineProperty(t,"File",{configurable:!0,enumerable:!0,get:function(){return n(3329)}}),Object.defineProperty(t,"Http",{configurable:!0,enumerable:!0,get:function(){return n(7543)}}),Object.defineProperty(t,"Stream",{configurable:!0,enumerable:!0,get:function(){return n(4149)}})},4149:(e,t,n)=>{function r(f){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})(f)}function o(f,S){if(!(f instanceof S))throw new TypeError("Cannot call a class as a function")}function s(f,S){for(var U=0;U<S.length;U++){var b=S[U];b.enumerable=b.enumerable||!1,b.configurable=!0,"value"in b&&(b.writable=!0),Object.defineProperty(f,c(b.key),b)}}function c(f){var S=function(U,b){if(r(U)!="object"||!U)return U;var T=U[Symbol.toPrimitive];if(T!==void 0){var F=T.call(U,b||"default");if(r(F)!="object")return F;throw new TypeError("@@toPrimitive must return a primitive value.")}return(b==="string"?String:Number)(U)}(f,"string");return r(S)=="symbol"?S:S+""}function l(f,S,U){return S=u(S),function(b,T){if(T&&(r(T)=="object"||typeof T=="function"))return T;if(T!==void 0)throw new TypeError("Derived constructors may only return object or undefined");return function(F){if(F===void 0)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return F}(b)}(f,function(){try{var b=!Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],function(){}))}catch{}return function(){return!!b}()}()?Reflect.construct(S,U||[],u(f).constructor):S.apply(f,U))}function u(f){return(u=Object.setPrototypeOf?Object.getPrototypeOf.bind():function(S){return S.__proto__||Object.getPrototypeOf(S)})(f)}function d(f,S){return(d=Object.setPrototypeOf?Object.setPrototypeOf.bind():function(U,b){return U.__proto__=b,U})(f,S)}var h=n(6605),R=n(4966).MESSAGE,y=n(2213),Q=n(6155);e.exports=function(f){function S(){var F,w=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};if(o(this,S),F=l(this,S,[w]),!w.stream||!h(w.stream))throw new Error("options.stream is required.");return F._stream=w.stream,F._stream.setMaxListeners(1/0),F.isObjectMode=w.stream._writableState.objectMode,F.eol=typeof w.eol=="string"?w.eol:y.EOL,F}return function(F,w){if(typeof w!="function"&&w!==null)throw new TypeError("Super expression must either be null or a function");F.prototype=Object.create(w&&w.prototype,{constructor:{value:F,writable:!0,configurable:!0}}),Object.defineProperty(F,"prototype",{writable:!1}),w&&d(F,w)}(S,f),U=S,(b=[{key:"log",value:function(F,w){var B=this;if(setImmediate(function(){return B.emit("logged",F)}),this.isObjectMode)return this._stream.write(F),void(w&&w());this._stream.write("".concat(F[R]).concat(this.eol)),w&&w()}}])&&s(U.prototype,b),T&&s(U,T),Object.defineProperty(U,"prototype",{writable:!1}),U;var U,b,T}(Q)},3227:e=>{e.exports=function(){for(var n={},r=0;r<arguments.length;r++){var o=arguments[r];for(var s in o)t.call(o,s)&&(n[s]=o[s])}return n};var t=Object.prototype.hasOwnProperty},3804:(e,t,n)=>{const r={};r.web=n(5949),n(8052);const o={v1:{}};o.v1.signaling={},o.v1.signaling.api=n(4620),o.v1.signaling.api.SignalingClient=function(f,S,U){U||(U={}),U.format="text",this.client_=new r.web.GrpcWebClientBase(U),this.hostname_=f.replace(/\/+$/,"")},o.v1.signaling.api.SignalingPromiseClient=function(f,S,U){U||(U={}),U.format="text",this.client_=new r.web.GrpcWebClientBase(U),this.hostname_=f.replace(/\/+$/,"")};const s=new r.web.MethodDescriptor("/v1.signaling.api.Signaling/GetHealth",r.web.MethodType.UNARY,o.v1.signaling.api.GetHealthRequest,o.v1.signaling.api.GetHealthResponse,function(f){return f.serializeBinary()},o.v1.signaling.api.GetHealthResponse.deserializeBinary);o.v1.signaling.api.SignalingClient.prototype.getHealth=function(f,S,U){return this.client_.rpcCall(this.hostname_+"/v1.signaling.api.Signaling/GetHealth",f,S||{},s,U)},o.v1.signaling.api.SignalingPromiseClient.prototype.getHealth=function(f,S){return this.client_.unaryCall(this.hostname_+"/v1.signaling.api.Signaling/GetHealth",f,S||{},s)};const c=new r.web.MethodDescriptor("/v1.signaling.api.Signaling/CreatePeer",r.web.MethodType.UNARY,o.v1.signaling.api.CreatePeerRequest,o.v1.signaling.api.CreatePeerResponse,function(f){return f.serializeBinary()},o.v1.signaling.api.CreatePeerResponse.deserializeBinary);o.v1.signaling.api.SignalingClient.prototype.createPeer=function(f,S,U){return this.client_.rpcCall(this.hostname_+"/v1.signaling.api.Signaling/CreatePeer",f,S||{},c,U)},o.v1.signaling.api.SignalingPromiseClient.prototype.createPeer=function(f,S){return this.client_.unaryCall(this.hostname_+"/v1.signaling.api.Signaling/CreatePeer",f,S||{},c)};const l=new r.web.MethodDescriptor("/v1.signaling.api.Signaling/DeletePeer",r.web.MethodType.UNARY,o.v1.signaling.api.DeletePeerRequest,o.v1.signaling.api.DeletePeerResponse,function(f){return f.serializeBinary()},o.v1.signaling.api.DeletePeerResponse.deserializeBinary);o.v1.signaling.api.SignalingClient.prototype.deletePeer=function(f,S,U){return this.client_.rpcCall(this.hostname_+"/v1.signaling.api.Signaling/DeletePeer",f,S||{},l,U)},o.v1.signaling.api.SignalingPromiseClient.prototype.deletePeer=function(f,S){return this.client_.unaryCall(this.hostname_+"/v1.signaling.api.Signaling/DeletePeer",f,S||{},l)};const u=new r.web.MethodDescriptor("/v1.signaling.api.Signaling/RefreshPeer",r.web.MethodType.UNARY,o.v1.signaling.api.RefreshPeerRequest,o.v1.signaling.api.RefreshPeerResponse,function(f){return f.serializeBinary()},o.v1.signaling.api.RefreshPeerResponse.deserializeBinary);o.v1.signaling.api.SignalingClient.prototype.refreshPeer=function(f,S,U){return this.client_.rpcCall(this.hostname_+"/v1.signaling.api.Signaling/RefreshPeer",f,S||{},u,U)},o.v1.signaling.api.SignalingPromiseClient.prototype.refreshPeer=function(f,S){return this.client_.unaryCall(this.hostname_+"/v1.signaling.api.Signaling/RefreshPeer",f,S||{},u)};const d=new r.web.MethodDescriptor("/v1.signaling.api.Signaling/GetPeers",r.web.MethodType.UNARY,o.v1.signaling.api.GetPeersRequest,o.v1.signaling.api.GetPeersResponse,function(f){return f.serializeBinary()},o.v1.signaling.api.GetPeersResponse.deserializeBinary);o.v1.signaling.api.SignalingClient.prototype.getPeers=function(f,S,U){return this.client_.rpcCall(this.hostname_+"/v1.signaling.api.Signaling/GetPeers",f,S||{},d,U)},o.v1.signaling.api.SignalingPromiseClient.prototype.getPeers=function(f,S){return this.client_.unaryCall(this.hostname_+"/v1.signaling.api.Signaling/GetPeers",f,S||{},d)};const h=new r.web.MethodDescriptor("/v1.signaling.api.Signaling/GetIceServers",r.web.MethodType.UNARY,o.v1.signaling.api.GetIceServersRequest,o.v1.signaling.api.GetIceServersResponse,function(f){return f.serializeBinary()},o.v1.signaling.api.GetIceServersResponse.deserializeBinary);o.v1.signaling.api.SignalingClient.prototype.getIceServers=function(f,S,U){return this.client_.rpcCall(this.hostname_+"/v1.signaling.api.Signaling/GetIceServers",f,S||{},h,U)},o.v1.signaling.api.SignalingPromiseClient.prototype.getIceServers=function(f,S){return this.client_.unaryCall(this.hostname_+"/v1.signaling.api.Signaling/GetIceServers",f,S||{},h)};const R=new r.web.MethodDescriptor("/v1.signaling.api.Signaling/SendSignal",r.web.MethodType.UNARY,o.v1.signaling.api.SendSignalRequest,o.v1.signaling.api.SendSignalResponse,function(f){return f.serializeBinary()},o.v1.signaling.api.SendSignalResponse.deserializeBinary);o.v1.signaling.api.SignalingClient.prototype.sendSignal=function(f,S,U){return this.client_.rpcCall(this.hostname_+"/v1.signaling.api.Signaling/SendSignal",f,S||{},R,U)},o.v1.signaling.api.SignalingPromiseClient.prototype.sendSignal=function(f,S){return this.client_.unaryCall(this.hostname_+"/v1.signaling.api.Signaling/SendSignal",f,S||{},R)};const y=new r.web.MethodDescriptor("/v1.signaling.api.Signaling/ReceiveSignalStream",r.web.MethodType.SERVER_STREAMING,o.v1.signaling.api.ReceiveSignalStreamRequest,o.v1.signaling.api.ReceiveSignalStreamResponse,function(f){return f.serializeBinary()},o.v1.signaling.api.ReceiveSignalStreamResponse.deserializeBinary);o.v1.signaling.api.SignalingClient.prototype.receiveSignalStream=function(f,S){return this.client_.serverStreaming(this.hostname_+"/v1.signaling.api.Signaling/ReceiveSignalStream",f,S||{},y)},o.v1.signaling.api.SignalingPromiseClient.prototype.receiveSignalStream=function(f,S){return this.client_.serverStreaming(this.hostname_+"/v1.signaling.api.Signaling/ReceiveSignalStream",f,S||{},y)};const Q=new r.web.MethodDescriptor("/v1.signaling.api.Signaling/GetSessions",r.web.MethodType.UNARY,o.v1.signaling.api.GetSessionsRequest,o.v1.signaling.api.GetSessionsResponse,function(f){return f.serializeBinary()},o.v1.signaling.api.GetSessionsResponse.deserializeBinary);o.v1.signaling.api.SignalingClient.prototype.getSessions=function(f,S,U){return this.client_.rpcCall(this.hostname_+"/v1.signaling.api.Signaling/GetSessions",f,S||{},Q,U)},o.v1.signaling.api.SignalingPromiseClient.prototype.getSessions=function(f,S){return this.client_.unaryCall(this.hostname_+"/v1.signaling.api.Signaling/GetSessions",f,S||{},Q)},e.exports=o.v1.signaling.api},4620:(e,t,n)=>{var r=n(7186),o=r,s=typeof globalThis!="undefined"&&globalThis||typeof window!="undefined"&&window||s!==void 0&&s||typeof self!="undefined"&&self||function(){return this}.call(null)||Function("return this")(),c=n(8052);o.object.extend(proto,c),o.exportSymbol("proto.v1.signaling.api.CreatePeerRequest",null,s),o.exportSymbol("proto.v1.signaling.api.CreatePeerResponse",null,s),o.exportSymbol("proto.v1.signaling.api.DeletePeerRequest",null,s),o.exportSymbol("proto.v1.signaling.api.DeletePeerResponse",null,s),o.exportSymbol("proto.v1.signaling.api.GetHealthRequest",null,s),o.exportSymbol("proto.v1.signaling.api.GetHealthResponse",null,s),o.exportSymbol("proto.v1.signaling.api.GetIceServersRequest",null,s),o.exportSymbol("proto.v1.signaling.api.GetIceServersResponse",null,s),o.exportSymbol("proto.v1.signaling.api.GetPeersRequest",null,s),o.exportSymbol("proto.v1.signaling.api.GetPeersResponse",null,s),o.exportSymbol("proto.v1.signaling.api.GetSessionsRequest",null,s),o.exportSymbol("proto.v1.signaling.api.GetSessionsResponse",null,s),o.exportSymbol("proto.v1.signaling.api.Peer",null,s),o.exportSymbol("proto.v1.signaling.api.ReceiveSignalStreamRequest",null,s),o.exportSymbol("proto.v1.signaling.api.ReceiveSignalStreamResponse",null,s),o.exportSymbol("proto.v1.signaling.api.RefreshPeerRequest",null,s),o.exportSymbol("proto.v1.signaling.api.RefreshPeerResponse",null,s),o.exportSymbol("proto.v1.signaling.api.RtcSession",null,s),o.exportSymbol("proto.v1.signaling.api.SendSignalRequest",null,s),o.exportSymbol("proto.v1.signaling.api.SendSignalResponse",null,s),o.exportSymbol("proto.v1.signaling.api.SessionType",null,s),o.exportSymbol("proto.v1.signaling.api.Signal",null,s),proto.v1.signaling.api.Peer=function(l){r.Message.initialize(this,l,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(l){r.Message.initialize(this,l,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.RtcSession=function(l){r.Message.initialize(this,l,0,-1,null,null)},o.inherits(proto.v1.signaling.api.RtcSession,r.Message),o.DEBUG&&!COMPILED&&(proto.v1.signaling.api.RtcSession.displayName="proto.v1.signaling.api.RtcSession"),proto.v1.signaling.api.GetSessionsRequest=function(l){r.Message.initialize(this,l,0,-1,null,null)},o.inherits(proto.v1.signaling.api.GetSessionsRequest,r.Message),o.DEBUG&&!COMPILED&&(proto.v1.signaling.api.GetSessionsRequest.displayName="proto.v1.signaling.api.GetSessionsRequest"),proto.v1.signaling.api.GetSessionsResponse=function(l){r.Message.initialize(this,l,0,-1,proto.v1.signaling.api.GetSessionsResponse.repeatedFields_,null)},o.inherits(proto.v1.signaling.api.GetSessionsResponse,r.Message),o.DEBUG&&!COMPILED&&(proto.v1.signaling.api.GetSessionsResponse.displayName="proto.v1.signaling.api.GetSessionsResponse"),proto.v1.signaling.api.GetHealthRequest=function(l){r.Message.initialize(this,l,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(l){r.Message.initialize(this,l,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(l){r.Message.initialize(this,l,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(l){r.Message.initialize(this,l,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(l){r.Message.initialize(this,l,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(l){r.Message.initialize(this,l,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(l){r.Message.initialize(this,l,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(l){r.Message.initialize(this,l,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(l){r.Message.initialize(this,l,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(l){r.Message.initialize(this,l,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(l){r.Message.initialize(this,l,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(l){r.Message.initialize(this,l,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(l){r.Message.initialize(this,l,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(l){r.Message.initialize(this,l,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(l){r.Message.initialize(this,l,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(l){r.Message.initialize(this,l,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(l){return proto.v1.signaling.api.Peer.toObject(l,this)},proto.v1.signaling.api.Peer.toObject=function(l,u){var d,h={peerId:r.Message.getFieldWithDefault(u,1,""),organizationId:r.Message.getFieldWithDefault(u,2,""),userId:(d=u.getUserId())&&c.StringValue.toObject(l,d),deviceId:(d=u.getDeviceId())&&c.StringValue.toObject(l,d),sessionIdsList:(d=r.Message.getRepeatedField(u,5))==null?void 0:d,peerCreatedTimestamp:(d=u.getPeerCreatedTimestamp())&&c.Int64Value.toObject(l,d)};return l&&(h.$jspbMessageInstance=u),h}),proto.v1.signaling.api.Peer.deserializeBinary=function(l){var u=new r.BinaryReader(l),d=new proto.v1.signaling.api.Peer;return proto.v1.signaling.api.Peer.deserializeBinaryFromReader(d,u)},proto.v1.signaling.api.Peer.deserializeBinaryFromReader=function(l,u){for(;u.nextField()&&!u.isEndGroup();)switch(u.getFieldNumber()){case 1:var d=u.readString();l.setPeerId(d);break;case 2:d=u.readString(),l.setOrganizationId(d);break;case 3:d=new c.StringValue,u.readMessage(d,c.StringValue.deserializeBinaryFromReader),l.setUserId(d);break;case 4:d=new c.StringValue,u.readMessage(d,c.StringValue.deserializeBinaryFromReader),l.setDeviceId(d);break;case 5:d=u.readString(),l.addSessionIds(d);break;case 6:d=new c.Int64Value,u.readMessage(d,c.Int64Value.deserializeBinaryFromReader),l.setPeerCreatedTimestamp(d);break;default:u.skipField()}return l},proto.v1.signaling.api.Peer.prototype.serializeBinary=function(){var l=new r.BinaryWriter;return proto.v1.signaling.api.Peer.serializeBinaryToWriter(this,l),l.getResultBuffer()},proto.v1.signaling.api.Peer.serializeBinaryToWriter=function(l,u){var d=void 0;(d=l.getPeerId()).length>0&&u.writeString(1,d),(d=l.getOrganizationId()).length>0&&u.writeString(2,d),(d=l.getUserId())!=null&&u.writeMessage(3,d,c.StringValue.serializeBinaryToWriter),(d=l.getDeviceId())!=null&&u.writeMessage(4,d,c.StringValue.serializeBinaryToWriter),(d=l.getSessionIdsList()).length>0&&u.writeRepeatedString(5,d),(d=l.getPeerCreatedTimestamp())!=null&&u.writeMessage(6,d,c.Int64Value.serializeBinaryToWriter)},proto.v1.signaling.api.Peer.prototype.getPeerId=function(){return r.Message.getFieldWithDefault(this,1,"")},proto.v1.signaling.api.Peer.prototype.setPeerId=function(l){return r.Message.setProto3StringField(this,1,l)},proto.v1.signaling.api.Peer.prototype.getOrganizationId=function(){return r.Message.getFieldWithDefault(this,2,"")},proto.v1.signaling.api.Peer.prototype.setOrganizationId=function(l){return r.Message.setProto3StringField(this,2,l)},proto.v1.signaling.api.Peer.prototype.getUserId=function(){return r.Message.getWrapperField(this,c.StringValue,3)},proto.v1.signaling.api.Peer.prototype.setUserId=function(l){return r.Message.setWrapperField(this,3,l)},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,c.StringValue,4)},proto.v1.signaling.api.Peer.prototype.setDeviceId=function(l){return r.Message.setWrapperField(this,4,l)},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(l){return r.Message.setField(this,5,l||[])},proto.v1.signaling.api.Peer.prototype.addSessionIds=function(l,u){return r.Message.addToRepeatedField(this,5,l,u)},proto.v1.signaling.api.Peer.prototype.clearSessionIdsList=function(){return this.setSessionIdsList([])},proto.v1.signaling.api.Peer.prototype.getPeerCreatedTimestamp=function(){return r.Message.getWrapperField(this,c.Int64Value,6)},proto.v1.signaling.api.Peer.prototype.setPeerCreatedTimestamp=function(l){return r.Message.setWrapperField(this,6,l)},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(l){return proto.v1.signaling.api.Signal.toObject(l,this)},proto.v1.signaling.api.Signal.toObject=function(l,u){var d,h={sessionId:(d=u.getSessionId())&&c.StringValue.toObject(l,d),sessionCreatedTimestamp:(d=u.getSessionCreatedTimestamp())&&c.Int64Value.toObject(l,d),senderId:r.Message.getFieldWithDefault(u,3,""),receiverId:r.Message.getFieldWithDefault(u,4,""),payload:r.Message.getFieldWithDefault(u,5,""),iceServers:r.Message.getFieldWithDefault(u,6,""),iceTransportPolicy:r.Message.getFieldWithDefault(u,7,""),sessionType:r.Message.getFieldWithDefault(u,8,0)};return l&&(h.$jspbMessageInstance=u),h}),proto.v1.signaling.api.Signal.deserializeBinary=function(l){var u=new r.BinaryReader(l),d=new proto.v1.signaling.api.Signal;return proto.v1.signaling.api.Signal.deserializeBinaryFromReader(d,u)},proto.v1.signaling.api.Signal.deserializeBinaryFromReader=function(l,u){for(;u.nextField()&&!u.isEndGroup();)switch(u.getFieldNumber()){case 1:var d=new c.StringValue;u.readMessage(d,c.StringValue.deserializeBinaryFromReader),l.setSessionId(d);break;case 2:d=new c.Int64Value,u.readMessage(d,c.Int64Value.deserializeBinaryFromReader),l.setSessionCreatedTimestamp(d);break;case 3:d=u.readString(),l.setSenderId(d);break;case 4:d=u.readString(),l.setReceiverId(d);break;case 5:d=u.readString(),l.setPayload(d);break;case 6:d=u.readString(),l.setIceServers(d);break;case 7:d=u.readString(),l.setIceTransportPolicy(d);break;case 8:d=u.readEnum(),l.setSessionType(d);break;default:u.skipField()}return l},proto.v1.signaling.api.Signal.prototype.serializeBinary=function(){var l=new r.BinaryWriter;return proto.v1.signaling.api.Signal.serializeBinaryToWriter(this,l),l.getResultBuffer()},proto.v1.signaling.api.Signal.serializeBinaryToWriter=function(l,u){var d=void 0;(d=l.getSessionId())!=null&&u.writeMessage(1,d,c.StringValue.serializeBinaryToWriter),(d=l.getSessionCreatedTimestamp())!=null&&u.writeMessage(2,d,c.Int64Value.serializeBinaryToWriter),(d=l.getSenderId()).length>0&&u.writeString(3,d),(d=l.getReceiverId()).length>0&&u.writeString(4,d),(d=l.getPayload()).length>0&&u.writeString(5,d),(d=l.getIceServers()).length>0&&u.writeString(6,d),(d=l.getIceTransportPolicy()).length>0&&u.writeString(7,d),(d=l.getSessionType())!==0&&u.writeEnum(8,d)},proto.v1.signaling.api.Signal.prototype.getSessionId=function(){return r.Message.getWrapperField(this,c.StringValue,1)},proto.v1.signaling.api.Signal.prototype.setSessionId=function(l){return r.Message.setWrapperField(this,1,l)},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,c.Int64Value,2)},proto.v1.signaling.api.Signal.prototype.setSessionCreatedTimestamp=function(l){return r.Message.setWrapperField(this,2,l)},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(l){return r.Message.setProto3StringField(this,3,l)},proto.v1.signaling.api.Signal.prototype.getReceiverId=function(){return r.Message.getFieldWithDefault(this,4,"")},proto.v1.signaling.api.Signal.prototype.setReceiverId=function(l){return r.Message.setProto3StringField(this,4,l)},proto.v1.signaling.api.Signal.prototype.getPayload=function(){return r.Message.getFieldWithDefault(this,5,"")},proto.v1.signaling.api.Signal.prototype.setPayload=function(l){return r.Message.setProto3StringField(this,5,l)},proto.v1.signaling.api.Signal.prototype.getIceServers=function(){return r.Message.getFieldWithDefault(this,6,"")},proto.v1.signaling.api.Signal.prototype.setIceServers=function(l){return r.Message.setProto3StringField(this,6,l)},proto.v1.signaling.api.Signal.prototype.getIceTransportPolicy=function(){return r.Message.getFieldWithDefault(this,7,"")},proto.v1.signaling.api.Signal.prototype.setIceTransportPolicy=function(l){return r.Message.setProto3StringField(this,7,l)},proto.v1.signaling.api.Signal.prototype.getSessionType=function(){return r.Message.getFieldWithDefault(this,8,0)},proto.v1.signaling.api.Signal.prototype.setSessionType=function(l){return r.Message.setProto3EnumField(this,8,l)},r.Message.GENERATE_TO_OBJECT&&(proto.v1.signaling.api.RtcSession.prototype.toObject=function(l){return proto.v1.signaling.api.RtcSession.toObject(l,this)},proto.v1.signaling.api.RtcSession.toObject=function(l,u){var d={sessionId:r.Message.getFieldWithDefault(u,1,""),offerPeerId:r.Message.getFieldWithDefault(u,2,""),answerPeerId:r.Message.getFieldWithDefault(u,3,""),organizationId:r.Message.getFieldWithDefault(u,4,""),sessionType:r.Message.getFieldWithDefault(u,5,"")};return l&&(d.$jspbMessageInstance=u),d}),proto.v1.signaling.api.RtcSession.deserializeBinary=function(l){var u=new r.BinaryReader(l),d=new proto.v1.signaling.api.RtcSession;return proto.v1.signaling.api.RtcSession.deserializeBinaryFromReader(d,u)},proto.v1.signaling.api.RtcSession.deserializeBinaryFromReader=function(l,u){for(;u.nextField()&&!u.isEndGroup();)switch(u.getFieldNumber()){case 1:var d=u.readString();l.setSessionId(d);break;case 2:d=u.readString(),l.setOfferPeerId(d);break;case 3:d=u.readString(),l.setAnswerPeerId(d);break;case 4:d=u.readString(),l.setOrganizationId(d);break;case 5:d=u.readString(),l.setSessionType(d);break;default:u.skipField()}return l},proto.v1.signaling.api.RtcSession.prototype.serializeBinary=function(){var l=new r.BinaryWriter;return proto.v1.signaling.api.RtcSession.serializeBinaryToWriter(this,l),l.getResultBuffer()},proto.v1.signaling.api.RtcSession.serializeBinaryToWriter=function(l,u){var d=void 0;(d=l.getSessionId()).length>0&&u.writeString(1,d),(d=l.getOfferPeerId()).length>0&&u.writeString(2,d),(d=l.getAnswerPeerId()).length>0&&u.writeString(3,d),(d=l.getOrganizationId()).length>0&&u.writeString(4,d),(d=l.getSessionType()).length>0&&u.writeString(5,d)},proto.v1.signaling.api.RtcSession.prototype.getSessionId=function(){return r.Message.getFieldWithDefault(this,1,"")},proto.v1.signaling.api.RtcSession.prototype.setSessionId=function(l){return r.Message.setProto3StringField(this,1,l)},proto.v1.signaling.api.RtcSession.prototype.getOfferPeerId=function(){return r.Message.getFieldWithDefault(this,2,"")},proto.v1.signaling.api.RtcSession.prototype.setOfferPeerId=function(l){return r.Message.setProto3StringField(this,2,l)},proto.v1.signaling.api.RtcSession.prototype.getAnswerPeerId=function(){return r.Message.getFieldWithDefault(this,3,"")},proto.v1.signaling.api.RtcSession.prototype.setAnswerPeerId=function(l){return r.Message.setProto3StringField(this,3,l)},proto.v1.signaling.api.RtcSession.prototype.getOrganizationId=function(){return r.Message.getFieldWithDefault(this,4,"")},proto.v1.signaling.api.RtcSession.prototype.setOrganizationId=function(l){return r.Message.setProto3StringField(this,4,l)},proto.v1.signaling.api.RtcSession.prototype.getSessionType=function(){return r.Message.getFieldWithDefault(this,5,"")},proto.v1.signaling.api.RtcSession.prototype.setSessionType=function(l){return r.Message.setProto3StringField(this,5,l)},r.Message.GENERATE_TO_OBJECT&&(proto.v1.signaling.api.GetSessionsRequest.prototype.toObject=function(l){return proto.v1.signaling.api.GetSessionsRequest.toObject(l,this)},proto.v1.signaling.api.GetSessionsRequest.toObject=function(l,u){var d={};return l&&(d.$jspbMessageInstance=u),d}),proto.v1.signaling.api.GetSessionsRequest.deserializeBinary=function(l){var u=new r.BinaryReader(l),d=new proto.v1.signaling.api.GetSessionsRequest;return proto.v1.signaling.api.GetSessionsRequest.deserializeBinaryFromReader(d,u)},proto.v1.signaling.api.GetSessionsRequest.deserializeBinaryFromReader=function(l,u){for(;u.nextField()&&!u.isEndGroup();)u.getFieldNumber(),u.skipField();return l},proto.v1.signaling.api.GetSessionsRequest.prototype.serializeBinary=function(){var l=new r.BinaryWriter;return proto.v1.signaling.api.GetSessionsRequest.serializeBinaryToWriter(this,l),l.getResultBuffer()},proto.v1.signaling.api.GetSessionsRequest.serializeBinaryToWriter=function(l,u){},proto.v1.signaling.api.GetSessionsResponse.repeatedFields_=[1],r.Message.GENERATE_TO_OBJECT&&(proto.v1.signaling.api.GetSessionsResponse.prototype.toObject=function(l){return proto.v1.signaling.api.GetSessionsResponse.toObject(l,this)},proto.v1.signaling.api.GetSessionsResponse.toObject=function(l,u){var d={sessionsList:r.Message.toObjectList(u.getSessionsList(),proto.v1.signaling.api.RtcSession.toObject,l)};return l&&(d.$jspbMessageInstance=u),d}),proto.v1.signaling.api.GetSessionsResponse.deserializeBinary=function(l){var u=new r.BinaryReader(l),d=new proto.v1.signaling.api.GetSessionsResponse;return proto.v1.signaling.api.GetSessionsResponse.deserializeBinaryFromReader(d,u)},proto.v1.signaling.api.GetSessionsResponse.deserializeBinaryFromReader=function(l,u){for(;u.nextField()&&!u.isEndGroup();)switch(u.getFieldNumber()){case 1:var d=new proto.v1.signaling.api.RtcSession;u.readMessage(d,proto.v1.signaling.api.RtcSession.deserializeBinaryFromReader),l.addSessions(d);break;default:u.skipField()}return l},proto.v1.signaling.api.GetSessionsResponse.prototype.serializeBinary=function(){var l=new r.BinaryWriter;return proto.v1.signaling.api.GetSessionsResponse.serializeBinaryToWriter(this,l),l.getResultBuffer()},proto.v1.signaling.api.GetSessionsResponse.serializeBinaryToWriter=function(l,u){var d;(d=l.getSessionsList()).length>0&&u.writeRepeatedMessage(1,d,proto.v1.signaling.api.RtcSession.serializeBinaryToWriter)},proto.v1.signaling.api.GetSessionsResponse.prototype.getSessionsList=function(){return r.Message.getRepeatedWrapperField(this,proto.v1.signaling.api.RtcSession,1)},proto.v1.signaling.api.GetSessionsResponse.prototype.setSessionsList=function(l){return r.Message.setRepeatedWrapperField(this,1,l)},proto.v1.signaling.api.GetSessionsResponse.prototype.addSessions=function(l,u){return r.Message.addToRepeatedWrapperField(this,1,l,proto.v1.signaling.api.RtcSession,u)},proto.v1.signaling.api.GetSessionsResponse.prototype.clearSessionsList=function(){return this.setSessionsList([])},r.Message.GENERATE_TO_OBJECT&&(proto.v1.signaling.api.GetHealthRequest.prototype.toObject=function(l){return proto.v1.signaling.api.GetHealthRequest.toObject(l,this)},proto.v1.signaling.api.GetHealthRequest.toObject=function(l,u){var d={};return l&&(d.$jspbMessageInstance=u),d}),proto.v1.signaling.api.GetHealthRequest.deserializeBinary=function(l){var u=new r.BinaryReader(l),d=new proto.v1.signaling.api.GetHealthRequest;return proto.v1.signaling.api.GetHealthRequest.deserializeBinaryFromReader(d,u)},proto.v1.signaling.api.GetHealthRequest.deserializeBinaryFromReader=function(l,u){for(;u.nextField()&&!u.isEndGroup();)u.getFieldNumber(),u.skipField();return l},proto.v1.signaling.api.GetHealthRequest.prototype.serializeBinary=function(){var l=new r.BinaryWriter;return proto.v1.signaling.api.GetHealthRequest.serializeBinaryToWriter(this,l),l.getResultBuffer()},proto.v1.signaling.api.GetHealthRequest.serializeBinaryToWriter=function(l,u){},r.Message.GENERATE_TO_OBJECT&&(proto.v1.signaling.api.GetHealthResponse.prototype.toObject=function(l){return proto.v1.signaling.api.GetHealthResponse.toObject(l,this)},proto.v1.signaling.api.GetHealthResponse.toObject=function(l,u){var d={version:r.Message.getFieldWithDefault(u,1,"")};return l&&(d.$jspbMessageInstance=u),d}),proto.v1.signaling.api.GetHealthResponse.deserializeBinary=function(l){var u=new r.BinaryReader(l),d=new proto.v1.signaling.api.GetHealthResponse;return proto.v1.signaling.api.GetHealthResponse.deserializeBinaryFromReader(d,u)},proto.v1.signaling.api.GetHealthResponse.deserializeBinaryFromReader=function(l,u){for(;u.nextField()&&!u.isEndGroup();)switch(u.getFieldNumber()){case 1:var d=u.readString();l.setVersion(d);break;default:u.skipField()}return l},proto.v1.signaling.api.GetHealthResponse.prototype.serializeBinary=function(){var l=new r.BinaryWriter;return proto.v1.signaling.api.GetHealthResponse.serializeBinaryToWriter(this,l),l.getResultBuffer()},proto.v1.signaling.api.GetHealthResponse.serializeBinaryToWriter=function(l,u){var d;(d=l.getVersion()).length>0&&u.writeString(1,d)},proto.v1.signaling.api.GetHealthResponse.prototype.getVersion=function(){return r.Message.getFieldWithDefault(this,1,"")},proto.v1.signaling.api.GetHealthResponse.prototype.setVersion=function(l){return r.Message.setProto3StringField(this,1,l)},r.Message.GENERATE_TO_OBJECT&&(proto.v1.signaling.api.CreatePeerRequest.prototype.toObject=function(l){return proto.v1.signaling.api.CreatePeerRequest.toObject(l,this)},proto.v1.signaling.api.CreatePeerRequest.toObject=function(l,u){var d={};return l&&(d.$jspbMessageInstance=u),d}),proto.v1.signaling.api.CreatePeerRequest.deserializeBinary=function(l){var u=new r.BinaryReader(l),d=new proto.v1.signaling.api.CreatePeerRequest;return proto.v1.signaling.api.CreatePeerRequest.deserializeBinaryFromReader(d,u)},proto.v1.signaling.api.CreatePeerRequest.deserializeBinaryFromReader=function(l,u){for(;u.nextField()&&!u.isEndGroup();)u.getFieldNumber(),u.skipField();return l},proto.v1.signaling.api.CreatePeerRequest.prototype.serializeBinary=function(){var l=new r.BinaryWriter;return proto.v1.signaling.api.CreatePeerRequest.serializeBinaryToWriter(this,l),l.getResultBuffer()},proto.v1.signaling.api.CreatePeerRequest.serializeBinaryToWriter=function(l,u){},r.Message.GENERATE_TO_OBJECT&&(proto.v1.signaling.api.CreatePeerResponse.prototype.toObject=function(l){return proto.v1.signaling.api.CreatePeerResponse.toObject(l,this)},proto.v1.signaling.api.CreatePeerResponse.toObject=function(l,u){var d,h={peer:(d=u.getPeer())&&proto.v1.signaling.api.Peer.toObject(l,d)};return l&&(h.$jspbMessageInstance=u),h}),proto.v1.signaling.api.CreatePeerResponse.deserializeBinary=function(l){var u=new r.BinaryReader(l),d=new proto.v1.signaling.api.CreatePeerResponse;return proto.v1.signaling.api.CreatePeerResponse.deserializeBinaryFromReader(d,u)},proto.v1.signaling.api.CreatePeerResponse.deserializeBinaryFromReader=function(l,u){for(;u.nextField()&&!u.isEndGroup();)switch(u.getFieldNumber()){case 1:var d=new proto.v1.signaling.api.Peer;u.readMessage(d,proto.v1.signaling.api.Peer.deserializeBinaryFromReader),l.setPeer(d);break;default:u.skipField()}return l},proto.v1.signaling.api.CreatePeerResponse.prototype.serializeBinary=function(){var l=new r.BinaryWriter;return proto.v1.signaling.api.CreatePeerResponse.serializeBinaryToWriter(this,l),l.getResultBuffer()},proto.v1.signaling.api.CreatePeerResponse.serializeBinaryToWriter=function(l,u){var d;(d=l.getPeer())!=null&&u.writeMessage(1,d,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(l){return r.Message.setWrapperField(this,1,l)},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(l){return proto.v1.signaling.api.DeletePeerRequest.toObject(l,this)},proto.v1.signaling.api.DeletePeerRequest.toObject=function(l,u){var d={peerId:r.Message.getFieldWithDefault(u,1,"")};return l&&(d.$jspbMessageInstance=u),d}),proto.v1.signaling.api.DeletePeerRequest.deserializeBinary=function(l){var u=new r.BinaryReader(l),d=new proto.v1.signaling.api.DeletePeerRequest;return proto.v1.signaling.api.DeletePeerRequest.deserializeBinaryFromReader(d,u)},proto.v1.signaling.api.DeletePeerRequest.deserializeBinaryFromReader=function(l,u){for(;u.nextField()&&!u.isEndGroup();)switch(u.getFieldNumber()){case 1:var d=u.readString();l.setPeerId(d);break;default:u.skipField()}return l},proto.v1.signaling.api.DeletePeerRequest.prototype.serializeBinary=function(){var l=new r.BinaryWriter;return proto.v1.signaling.api.DeletePeerRequest.serializeBinaryToWriter(this,l),l.getResultBuffer()},proto.v1.signaling.api.DeletePeerRequest.serializeBinaryToWriter=function(l,u){var d;(d=l.getPeerId()).length>0&&u.writeString(1,d)},proto.v1.signaling.api.DeletePeerRequest.prototype.getPeerId=function(){return r.Message.getFieldWithDefault(this,1,"")},proto.v1.signaling.api.DeletePeerRequest.prototype.setPeerId=function(l){return r.Message.setProto3StringField(this,1,l)},r.Message.GENERATE_TO_OBJECT&&(proto.v1.signaling.api.DeletePeerResponse.prototype.toObject=function(l){return proto.v1.signaling.api.DeletePeerResponse.toObject(l,this)},proto.v1.signaling.api.DeletePeerResponse.toObject=function(l,u){var d={};return l&&(d.$jspbMessageInstance=u),d}),proto.v1.signaling.api.DeletePeerResponse.deserializeBinary=function(l){var u=new r.BinaryReader(l),d=new proto.v1.signaling.api.DeletePeerResponse;return proto.v1.signaling.api.DeletePeerResponse.deserializeBinaryFromReader(d,u)},proto.v1.signaling.api.DeletePeerResponse.deserializeBinaryFromReader=function(l,u){for(;u.nextField()&&!u.isEndGroup();)u.getFieldNumber(),u.skipField();return l},proto.v1.signaling.api.DeletePeerResponse.prototype.serializeBinary=function(){var l=new r.BinaryWriter;return proto.v1.signaling.api.DeletePeerResponse.serializeBinaryToWriter(this,l),l.getResultBuffer()},proto.v1.signaling.api.DeletePeerResponse.serializeBinaryToWriter=function(l,u){},r.Message.GENERATE_TO_OBJECT&&(proto.v1.signaling.api.RefreshPeerRequest.prototype.toObject=function(l){return proto.v1.signaling.api.RefreshPeerRequest.toObject(l,this)},proto.v1.signaling.api.RefreshPeerRequest.toObject=function(l,u){var d,h={peer:(d=u.getPeer())&&proto.v1.signaling.api.Peer.toObject(l,d)};return l&&(h.$jspbMessageInstance=u),h}),proto.v1.signaling.api.RefreshPeerRequest.deserializeBinary=function(l){var u=new r.BinaryReader(l),d=new proto.v1.signaling.api.RefreshPeerRequest;return proto.v1.signaling.api.RefreshPeerRequest.deserializeBinaryFromReader(d,u)},proto.v1.signaling.api.RefreshPeerRequest.deserializeBinaryFromReader=function(l,u){for(;u.nextField()&&!u.isEndGroup();)switch(u.getFieldNumber()){case 1:var d=new proto.v1.signaling.api.Peer;u.readMessage(d,proto.v1.signaling.api.Peer.deserializeBinaryFromReader),l.setPeer(d);break;default:u.skipField()}return l},proto.v1.signaling.api.RefreshPeerRequest.prototype.serializeBinary=function(){var l=new r.BinaryWriter;return proto.v1.signaling.api.RefreshPeerRequest.serializeBinaryToWriter(this,l),l.getResultBuffer()},proto.v1.signaling.api.RefreshPeerRequest.serializeBinaryToWriter=function(l,u){var d;(d=l.getPeer())!=null&&u.writeMessage(1,d,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(l){return r.Message.setWrapperField(this,1,l)},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(l){return proto.v1.signaling.api.RefreshPeerResponse.toObject(l,this)},proto.v1.signaling.api.RefreshPeerResponse.toObject=function(l,u){var d={};return l&&(d.$jspbMessageInstance=u),d}),proto.v1.signaling.api.RefreshPeerResponse.deserializeBinary=function(l){var u=new r.BinaryReader(l),d=new proto.v1.signaling.api.RefreshPeerResponse;return proto.v1.signaling.api.RefreshPeerResponse.deserializeBinaryFromReader(d,u)},proto.v1.signaling.api.RefreshPeerResponse.deserializeBinaryFromReader=function(l,u){for(;u.nextField()&&!u.isEndGroup();)u.getFieldNumber(),u.skipField();return l},proto.v1.signaling.api.RefreshPeerResponse.prototype.serializeBinary=function(){var l=new r.BinaryWriter;return proto.v1.signaling.api.RefreshPeerResponse.serializeBinaryToWriter(this,l),l.getResultBuffer()},proto.v1.signaling.api.RefreshPeerResponse.serializeBinaryToWriter=function(l,u){},r.Message.GENERATE_TO_OBJECT&&(proto.v1.signaling.api.GetPeersRequest.prototype.toObject=function(l){return proto.v1.signaling.api.GetPeersRequest.toObject(l,this)},proto.v1.signaling.api.GetPeersRequest.toObject=function(l,u){var d={};return l&&(d.$jspbMessageInstance=u),d}),proto.v1.signaling.api.GetPeersRequest.deserializeBinary=function(l){var u=new r.BinaryReader(l),d=new proto.v1.signaling.api.GetPeersRequest;return proto.v1.signaling.api.GetPeersRequest.deserializeBinaryFromReader(d,u)},proto.v1.signaling.api.GetPeersRequest.deserializeBinaryFromReader=function(l,u){for(;u.nextField()&&!u.isEndGroup();)u.getFieldNumber(),u.skipField();return l},proto.v1.signaling.api.GetPeersRequest.prototype.serializeBinary=function(){var l=new r.BinaryWriter;return proto.v1.signaling.api.GetPeersRequest.serializeBinaryToWriter(this,l),l.getResultBuffer()},proto.v1.signaling.api.GetPeersRequest.serializeBinaryToWriter=function(l,u){},proto.v1.signaling.api.GetPeersResponse.repeatedFields_=[1],r.Message.GENERATE_TO_OBJECT&&(proto.v1.signaling.api.GetPeersResponse.prototype.toObject=function(l){return proto.v1.signaling.api.GetPeersResponse.toObject(l,this)},proto.v1.signaling.api.GetPeersResponse.toObject=function(l,u){var d={peersList:r.Message.toObjectList(u.getPeersList(),proto.v1.signaling.api.Peer.toObject,l)};return l&&(d.$jspbMessageInstance=u),d}),proto.v1.signaling.api.GetPeersResponse.deserializeBinary=function(l){var u=new r.BinaryReader(l),d=new proto.v1.signaling.api.GetPeersResponse;return proto.v1.signaling.api.GetPeersResponse.deserializeBinaryFromReader(d,u)},proto.v1.signaling.api.GetPeersResponse.deserializeBinaryFromReader=function(l,u){for(;u.nextField()&&!u.isEndGroup();)switch(u.getFieldNumber()){case 1:var d=new proto.v1.signaling.api.Peer;u.readMessage(d,proto.v1.signaling.api.Peer.deserializeBinaryFromReader),l.addPeers(d);break;default:u.skipField()}return l},proto.v1.signaling.api.GetPeersResponse.prototype.serializeBinary=function(){var l=new r.BinaryWriter;return proto.v1.signaling.api.GetPeersResponse.serializeBinaryToWriter(this,l),l.getResultBuffer()},proto.v1.signaling.api.GetPeersResponse.serializeBinaryToWriter=function(l,u){var d;(d=l.getPeersList()).length>0&&u.writeRepeatedMessage(1,d,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(l){return r.Message.setRepeatedWrapperField(this,1,l)},proto.v1.signaling.api.GetPeersResponse.prototype.addPeers=function(l,u){return r.Message.addToRepeatedWrapperField(this,1,l,proto.v1.signaling.api.Peer,u)},proto.v1.signaling.api.GetPeersResponse.prototype.clearPeersList=function(){return this.setPeersList([])},r.Message.GENERATE_TO_OBJECT&&(proto.v1.signaling.api.GetIceServersRequest.prototype.toObject=function(l){return proto.v1.signaling.api.GetIceServersRequest.toObject(l,this)},proto.v1.signaling.api.GetIceServersRequest.toObject=function(l,u){var d={};return l&&(d.$jspbMessageInstance=u),d}),proto.v1.signaling.api.GetIceServersRequest.deserializeBinary=function(l){var u=new r.BinaryReader(l),d=new proto.v1.signaling.api.GetIceServersRequest;return proto.v1.signaling.api.GetIceServersRequest.deserializeBinaryFromReader(d,u)},proto.v1.signaling.api.GetIceServersRequest.deserializeBinaryFromReader=function(l,u){for(;u.nextField()&&!u.isEndGroup();)u.getFieldNumber(),u.skipField();return l},proto.v1.signaling.api.GetIceServersRequest.prototype.serializeBinary=function(){var l=new r.BinaryWriter;return proto.v1.signaling.api.GetIceServersRequest.serializeBinaryToWriter(this,l),l.getResultBuffer()},proto.v1.signaling.api.GetIceServersRequest.serializeBinaryToWriter=function(l,u){},r.Message.GENERATE_TO_OBJECT&&(proto.v1.signaling.api.GetIceServersResponse.prototype.toObject=function(l){return proto.v1.signaling.api.GetIceServersResponse.toObject(l,this)},proto.v1.signaling.api.GetIceServersResponse.toObject=function(l,u){var d={iceServers:r.Message.getFieldWithDefault(u,1,"")};return l&&(d.$jspbMessageInstance=u),d}),proto.v1.signaling.api.GetIceServersResponse.deserializeBinary=function(l){var u=new r.BinaryReader(l),d=new proto.v1.signaling.api.GetIceServersResponse;return proto.v1.signaling.api.GetIceServersResponse.deserializeBinaryFromReader(d,u)},proto.v1.signaling.api.GetIceServersResponse.deserializeBinaryFromReader=function(l,u){for(;u.nextField()&&!u.isEndGroup();)switch(u.getFieldNumber()){case 1:var d=u.readString();l.setIceServers(d);break;default:u.skipField()}return l},proto.v1.signaling.api.GetIceServersResponse.prototype.serializeBinary=function(){var l=new r.BinaryWriter;return proto.v1.signaling.api.GetIceServersResponse.serializeBinaryToWriter(this,l),l.getResultBuffer()},proto.v1.signaling.api.GetIceServersResponse.serializeBinaryToWriter=function(l,u){var d;(d=l.getIceServers()).length>0&&u.writeString(1,d)},proto.v1.signaling.api.GetIceServersResponse.prototype.getIceServers=function(){return r.Message.getFieldWithDefault(this,1,"")},proto.v1.signaling.api.GetIceServersResponse.prototype.setIceServers=function(l){return r.Message.setProto3StringField(this,1,l)},r.Message.GENERATE_TO_OBJECT&&(proto.v1.signaling.api.SendSignalRequest.prototype.toObject=function(l){return proto.v1.signaling.api.SendSignalRequest.toObject(l,this)},proto.v1.signaling.api.SendSignalRequest.toObject=function(l,u){var d,h={signal:(d=u.getSignal())&&proto.v1.signaling.api.Signal.toObject(l,d)};return l&&(h.$jspbMessageInstance=u),h}),proto.v1.signaling.api.SendSignalRequest.deserializeBinary=function(l){var u=new r.BinaryReader(l),d=new proto.v1.signaling.api.SendSignalRequest;return proto.v1.signaling.api.SendSignalRequest.deserializeBinaryFromReader(d,u)},proto.v1.signaling.api.SendSignalRequest.deserializeBinaryFromReader=function(l,u){for(;u.nextField()&&!u.isEndGroup();)switch(u.getFieldNumber()){case 1:var d=new proto.v1.signaling.api.Signal;u.readMessage(d,proto.v1.signaling.api.Signal.deserializeBinaryFromReader),l.setSignal(d);break;default:u.skipField()}return l},proto.v1.signaling.api.SendSignalRequest.prototype.serializeBinary=function(){var l=new r.BinaryWriter;return proto.v1.signaling.api.SendSignalRequest.serializeBinaryToWriter(this,l),l.getResultBuffer()},proto.v1.signaling.api.SendSignalRequest.serializeBinaryToWriter=function(l,u){var d;(d=l.getSignal())!=null&&u.writeMessage(1,d,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(l){return r.Message.setWrapperField(this,1,l)},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(l){return proto.v1.signaling.api.SendSignalResponse.toObject(l,this)},proto.v1.signaling.api.SendSignalResponse.toObject=function(l,u){var d,h={sessionId:(d=u.getSessionId())&&c.StringValue.toObject(l,d),sessionCreatedTimestamp:(d=u.getSessionCreatedTimestamp())&&c.Int64Value.toObject(l,d)};return l&&(h.$jspbMessageInstance=u),h}),proto.v1.signaling.api.SendSignalResponse.deserializeBinary=function(l){var u=new r.BinaryReader(l),d=new proto.v1.signaling.api.SendSignalResponse;return proto.v1.signaling.api.SendSignalResponse.deserializeBinaryFromReader(d,u)},proto.v1.signaling.api.SendSignalResponse.deserializeBinaryFromReader=function(l,u){for(;u.nextField()&&!u.isEndGroup();)switch(u.getFieldNumber()){case 1:var d=new c.StringValue;u.readMessage(d,c.StringValue.deserializeBinaryFromReader),l.setSessionId(d);break;case 2:d=new c.Int64Value,u.readMessage(d,c.Int64Value.deserializeBinaryFromReader),l.setSessionCreatedTimestamp(d);break;default:u.skipField()}return l},proto.v1.signaling.api.SendSignalResponse.prototype.serializeBinary=function(){var l=new r.BinaryWriter;return proto.v1.signaling.api.SendSignalResponse.serializeBinaryToWriter(this,l),l.getResultBuffer()},proto.v1.signaling.api.SendSignalResponse.serializeBinaryToWriter=function(l,u){var d=void 0;(d=l.getSessionId())!=null&&u.writeMessage(1,d,c.StringValue.serializeBinaryToWriter),(d=l.getSessionCreatedTimestamp())!=null&&u.writeMessage(2,d,c.Int64Value.serializeBinaryToWriter)},proto.v1.signaling.api.SendSignalResponse.prototype.getSessionId=function(){return r.Message.getWrapperField(this,c.StringValue,1)},proto.v1.signaling.api.SendSignalResponse.prototype.setSessionId=function(l){return r.Message.setWrapperField(this,1,l)},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,c.Int64Value,2)},proto.v1.signaling.api.SendSignalResponse.prototype.setSessionCreatedTimestamp=function(l){return r.Message.setWrapperField(this,2,l)},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(l){return proto.v1.signaling.api.ReceiveSignalStreamRequest.toObject(l,this)},proto.v1.signaling.api.ReceiveSignalStreamRequest.toObject=function(l,u){var d={peerId:r.Message.getFieldWithDefault(u,1,"")};return l&&(d.$jspbMessageInstance=u),d}),proto.v1.signaling.api.ReceiveSignalStreamRequest.deserializeBinary=function(l){var u=new r.BinaryReader(l),d=new proto.v1.signaling.api.ReceiveSignalStreamRequest;return proto.v1.signaling.api.ReceiveSignalStreamRequest.deserializeBinaryFromReader(d,u)},proto.v1.signaling.api.ReceiveSignalStreamRequest.deserializeBinaryFromReader=function(l,u){for(;u.nextField()&&!u.isEndGroup();)switch(u.getFieldNumber()){case 1:var d=u.readString();l.setPeerId(d);break;default:u.skipField()}return l},proto.v1.signaling.api.ReceiveSignalStreamRequest.prototype.serializeBinary=function(){var l=new r.BinaryWriter;return proto.v1.signaling.api.ReceiveSignalStreamRequest.serializeBinaryToWriter(this,l),l.getResultBuffer()},proto.v1.signaling.api.ReceiveSignalStreamRequest.serializeBinaryToWriter=function(l,u){var d;(d=l.getPeerId()).length>0&&u.writeString(1,d)},proto.v1.signaling.api.ReceiveSignalStreamRequest.prototype.getPeerId=function(){return r.Message.getFieldWithDefault(this,1,"")},proto.v1.signaling.api.ReceiveSignalStreamRequest.prototype.setPeerId=function(l){return r.Message.setProto3StringField(this,1,l)},r.Message.GENERATE_TO_OBJECT&&(proto.v1.signaling.api.ReceiveSignalStreamResponse.prototype.toObject=function(l){return proto.v1.signaling.api.ReceiveSignalStreamResponse.toObject(l,this)},proto.v1.signaling.api.ReceiveSignalStreamResponse.toObject=function(l,u){var d,h={signal:(d=u.getSignal())&&proto.v1.signaling.api.Signal.toObject(l,d)};return l&&(h.$jspbMessageInstance=u),h}),proto.v1.signaling.api.ReceiveSignalStreamResponse.deserializeBinary=function(l){var u=new r.BinaryReader(l),d=new proto.v1.signaling.api.ReceiveSignalStreamResponse;return proto.v1.signaling.api.ReceiveSignalStreamResponse.deserializeBinaryFromReader(d,u)},proto.v1.signaling.api.ReceiveSignalStreamResponse.deserializeBinaryFromReader=function(l,u){for(;u.nextField()&&!u.isEndGroup();)switch(u.getFieldNumber()){case 1:var d=new proto.v1.signaling.api.Signal;u.readMessage(d,proto.v1.signaling.api.Signal.deserializeBinaryFromReader),l.setSignal(d);break;default:u.skipField()}return l},proto.v1.signaling.api.ReceiveSignalStreamResponse.prototype.serializeBinary=function(){var l=new r.BinaryWriter;return proto.v1.signaling.api.ReceiveSignalStreamResponse.serializeBinaryToWriter(this,l),l.getResultBuffer()},proto.v1.signaling.api.ReceiveSignalStreamResponse.serializeBinaryToWriter=function(l,u){var d;(d=l.getSignal())!=null&&u.writeMessage(1,d,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(l){return r.Message.setWrapperField(this,1,l)},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,HEADLESS:4},o.object.extend(t,proto.v1.signaling.api)},3449:(e,t,n)=>{const r={...n(4620),...n(3804)};e.exports=r},6973:()=>{},3011:()=>{},3951:()=>{},9256:()=>{},2627:()=>{},4834:(e,t,n)=>{var r=n(9501),o=typeof globalThis=="undefined"?n.g:globalThis;e.exports=function(){for(var s=[],c=0;c<r.length;c++)typeof o[r[c]]=="function"&&(s[s.length]=r[c]);return s}},7241:e=>{e.exports={version:"3.14.2"}}},__webpack_module_cache__={};function __webpack_require__(e){var t=__webpack_module_cache__[e];if(t!==void 0)return t.exports;var n=__webpack_module_cache__[e]={id:e,loaded:!1,exports:{}};return __webpack_modules__[e].call(n.exports,n,n.exports,__webpack_require__),n.loaded=!0,n.exports}__webpack_require__.n=e=>{var t=e&&e.__esModule?()=>e.default:()=>e;return __webpack_require__.d(t,{a:t}),t},__webpack_require__.d=(e,t)=>{for(var n in t)__webpack_require__.o(t,n)&&!__webpack_require__.o(e,n)&&Object.defineProperty(e,n,{enumerable:!0,get:t[n]})},__webpack_require__.g=function(){if(typeof globalThis=="object")return globalThis;try{return this||new Function("return this")()}catch{if(typeof window=="object")return window}}(),__webpack_require__.o=(e,t)=>Object.prototype.hasOwnProperty.call(e,t),__webpack_require__.r=e=>{typeof Symbol!="undefined"&&Symbol.toStringTag&&Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(e,"__esModule",{value:!0})},__webpack_require__.nmd=e=>(e.paths=[],e.children||(e.children=[]),e);var __webpack_exports__={};return(()=>{__webpack_require__.r(__webpack_exports__),__webpack_require__.d(__webpack_exports__,{AuthClient:()=>n,Credentials:()=>z,RtcClient:()=>Lt,RtcClientV1:()=>Ge,RtcSignalingClient:()=>ce,SignalingPromiseClient:()=>re.SignalingPromiseClient,createRtcStreamMessage:()=>bt});var e=__webpack_require__(6331),t=function(Ee,N,C,G){return new(C||(C=Promise))(function(Z,pe){function Ue(Se){try{Re(G.next(Se))}catch(fe){pe(fe)}}function ve(Se){try{Re(G.throw(Se))}catch(fe){pe(fe)}}function Re(Se){var fe;Se.done?Z(Se.value):(fe=Se.value,fe instanceof C?fe:new C(function(p){p(fe)})).then(Ue,ve)}Re((G=G.apply(Ee,N||[])).next())})};class n extends e.S{adminSignup(N,C){return t(this,void 0,void 0,function*(){return yield this.fetch("auth/admin-signup",{token:C,method:"POST",body:N})})}login(N){return t(this,void 0,void 0,function*(){return yield this.fetch("auth/login",{method:"POST",body:N,allowUnsafeRetries:!0})})}loginWithGoogleToken(N){return t(this,void 0,void 0,function*(){return yield this.fetch("auth/login-google",{method:"POST",body:N,allowUnsafeRetries:!0})})}refresh(N,C){return t(this,void 0,void 0,function*(){return yield this.fetch("auth/refresh",{method:"POST",body:{refreshToken:N,tokenExpirationSeconds:C},allowUnsafeRetries:!0})})}respondToNewPasswordRequiredChallenge(N){return t(this,void 0,void 0,function*(){return yield this.fetch("auth/respond-to-new-password-required-challenge",{method:"POST",body:N})})}forgotPassword(N){return t(this,void 0,void 0,function*(){return yield this.fetch("auth/forgot-password",{method:"POST",body:{email:N}})})}confirmForgotPassword(N){return t(this,void 0,void 0,function*(){return yield this.fetch("auth/confirm-forgot-password",{method:"POST",body:N})})}resendInvitation(N){return t(this,void 0,void 0,function*(){return yield this.fetch("auth/resend-invitation",{method:"POST",body:{email:N}})})}changePassword(N){return t(this,arguments,void 0,function*({token:C,refreshToken:G,currentPassword:Z,newPassword:pe}){return yield this.fetch("auth/change-password",{token:C,method:"POST",body:{refreshToken:G,currentPassword:Z,newPassword:pe}})})}getDeviceCredentials(N){return t(this,void 0,void 0,function*(){return yield this.fetch("auth/device-credentials",{token:N,method:"POST",allowUnsafeRetries:!0})})}impersonate(N,C){return t(this,void 0,void 0,function*(){return yield this.fetch("auth/impersonate",{token:N,method:"POST",allowUnsafeRetries:!0,body:{userId:C}})})}createServiceAccount(N,C,G,Z,pe){return t(this,void 0,void 0,function*(){return yield this.fetch("auth/service-account",{token:N,method:"POST",allowUnsafeRetries:!0,body:{name:C,roleId:G,tags:Z,description:pe}})})}getFeatures(N){return t(this,void 0,void 0,function*(){return(yield this.fetch("auth/features",{token:N})).features})}checkSso(N,C){return t(this,void 0,void 0,function*(){return yield this.fetch("auth/check-sso",{method:"POST",body:{email:N,allowUserAutoCreation:C}})})}loginWithSso(N,C){return t(this,void 0,void 0,function*(){return yield this.fetch("auth/login-sso",{method:"POST",body:{token:N,refreshToken:C}})})}}var r=__webpack_require__(3778),o=__webpack_require__(7221),s=__webpack_require__(6075),c=__webpack_require__.n(s);const l=typeof performance=="object"&&performance&&typeof performance.now=="function"?performance:Date,u=typeof AbortController=="function"?AbortController:class{constructor(){this.signal=new R}abort(Ee=new Error("This operation was aborted")){this.signal.reason=this.signal.reason||Ee,this.signal.aborted=!0,this.signal.dispatchEvent({type:"abort",target:this.signal})}},d=typeof AbortSignal=="function",h=typeof u.AbortSignal=="function",R=d?AbortSignal:h?u.AbortController:class{constructor(){this.reason=void 0,this.aborted=!1,this._listeners=[]}dispatchEvent(Ee){Ee.type==="abort"&&(this.aborted=!0,this.onabort(Ee),this._listeners.forEach(N=>N(Ee),this))}onabort(){}addEventListener(Ee,N){Ee==="abort"&&this._listeners.push(N)}removeEventListener(Ee,N){Ee==="abort"&&(this._listeners=this._listeners.filter(C=>C!==N))}},y=new Set,Q=(Ee,N)=>{const C="LRU_CACHE_OPTION_"+Ee;U(C)&&b(C,Ee+" option","options."+N,Y)},f=(Ee,N)=>{const C="LRU_CACHE_METHOD_"+Ee;if(U(C)){const{prototype:G}=Y,{get:Z}=Object.getOwnPropertyDescriptor(G,Ee);b(C,Ee+" method",`cache.${N}()`,Z)}},S=(...Ee)=>{typeof process=="object"&&process&&typeof process.emitWarning=="function"?process.emitWarning(...Ee):console.error(...Ee)},U=Ee=>!y.has(Ee),b=(Ee,N,C,G)=>{y.add(Ee),S(`The ${N} is deprecated. Please use ${C} instead.`,"DeprecationWarning",Ee,G)},T=Ee=>Ee&&Ee===Math.floor(Ee)&&Ee>0&&isFinite(Ee),F=Ee=>T(Ee)?Ee<=Math.pow(2,8)?Uint8Array:Ee<=Math.pow(2,16)?Uint16Array:Ee<=Math.pow(2,32)?Uint32Array:Ee<=Number.MAX_SAFE_INTEGER?w:null:null;class w extends Array{constructor(N){super(N),this.fill(0)}}class B{constructor(N){if(N===0)return[];const C=F(N);this.heap=new C(N),this.length=0}push(N){this.heap[this.length++]=N}pop(){return this.heap[--this.length]}}class Y{constructor(N={}){const{max:C=0,ttl:G,ttlResolution:Z=1,ttlAutopurge:pe,updateAgeOnGet:Ue,updateAgeOnHas:ve,allowStale:Re,dispose:Se,disposeAfter:fe,noDisposeOnSet:p,noUpdateTTL:g,maxSize:V=0,maxEntrySize:X=0,sizeCalculation:ue,fetchMethod:be,fetchContext:Ce,noDeleteOnFetchRejection:Ae,noDeleteOnStaleGet:Le,allowStaleOnFetchRejection:Ke,allowStaleOnFetchAbort:at,ignoreFetchAbort:gt}=N,{length:Ut,maxAge:it,stale:lt}=N instanceof Y?{}:N;if(C!==0&&!T(C))throw new TypeError("max option must be a nonnegative integer");const _t=C?F(C):Array;if(!_t)throw new Error("invalid max value: "+C);if(this.max=C,this.maxSize=V,this.maxEntrySize=X||this.maxSize,this.sizeCalculation=ue||Ut,this.sizeCalculation){if(!this.maxSize&&!this.maxEntrySize)throw new TypeError("cannot set sizeCalculation without setting maxSize or maxEntrySize");if(typeof this.sizeCalculation!="function")throw new TypeError("sizeCalculation set to non-function")}if(this.fetchMethod=be||null,this.fetchMethod&&typeof this.fetchMethod!="function")throw new TypeError("fetchMethod must be a function if specified");if(this.fetchContext=Ce,!this.fetchMethod&&Ce!==void 0)throw new TypeError("cannot set fetchContext without fetchMethod");if(this.keyMap=new Map,this.keyList=new Array(C).fill(null),this.valList=new Array(C).fill(null),this.next=new _t(C),this.prev=new _t(C),this.head=0,this.tail=0,this.free=new B(C),this.initialFill=1,this.size=0,typeof Se=="function"&&(this.dispose=Se),typeof fe=="function"?(this.disposeAfter=fe,this.disposed=[]):(this.disposeAfter=null,this.disposed=null),this.noDisposeOnSet=!!p,this.noUpdateTTL=!!g,this.noDeleteOnFetchRejection=!!Ae,this.allowStaleOnFetchRejection=!!Ke,this.allowStaleOnFetchAbort=!!at,this.ignoreFetchAbort=!!gt,this.maxEntrySize!==0){if(this.maxSize!==0&&!T(this.maxSize))throw new TypeError("maxSize must be a positive integer if specified");if(!T(this.maxEntrySize))throw new TypeError("maxEntrySize must be a positive integer if specified");this.initializeSizeTracking()}if(this.allowStale=!!Re||!!lt,this.noDeleteOnStaleGet=!!Le,this.updateAgeOnGet=!!Ue,this.updateAgeOnHas=!!ve,this.ttlResolution=T(Z)||Z===0?Z:1,this.ttlAutopurge=!!pe,this.ttl=G||it||0,this.ttl){if(!T(this.ttl))throw new TypeError("ttl must be a positive integer if specified");this.initializeTTLTracking()}if(this.max===0&&this.ttl===0&&this.maxSize===0)throw new TypeError("At least one of max, maxSize, or ttl is required");if(!this.ttlAutopurge&&!this.max&&!this.maxSize){const At="LRU_CACHE_UNBOUNDED";U(At)&&(y.add(At),S("TTL caching without ttlAutopurge, max, or maxSize can result in unbounded memory consumption.","UnboundedCacheWarning",At,Y))}lt&&Q("stale","allowStale"),it&&Q("maxAge","ttl"),Ut&&Q("length","sizeCalculation")}getRemainingTTL(N){return this.has(N,{updateAgeOnHas:!1})?1/0:0}initializeTTLTracking(){this.ttls=new w(this.max),this.starts=new w(this.max),this.setItemTTL=(G,Z,pe=l.now())=>{if(this.starts[G]=Z!==0?pe:0,this.ttls[G]=Z,Z!==0&&this.ttlAutopurge){const Ue=setTimeout(()=>{this.isStale(G)&&this.delete(this.keyList[G])},Z+1);Ue.unref&&Ue.unref()}},this.updateItemAge=G=>{this.starts[G]=this.ttls[G]!==0?l.now():0},this.statusTTL=(G,Z)=>{G&&(G.ttl=this.ttls[Z],G.start=this.starts[Z],G.now=N||C(),G.remainingTTL=G.now+G.ttl-G.start)};let N=0;const C=()=>{const G=l.now();if(this.ttlResolution>0){N=G;const Z=setTimeout(()=>N=0,this.ttlResolution);Z.unref&&Z.unref()}return G};this.getRemainingTTL=G=>{const Z=this.keyMap.get(G);return Z===void 0?0:this.ttls[Z]===0||this.starts[Z]===0?1/0:this.starts[Z]+this.ttls[Z]-(N||C())},this.isStale=G=>this.ttls[G]!==0&&this.starts[G]!==0&&(N||C())-this.starts[G]>this.ttls[G]}updateItemAge(N){}statusTTL(N,C){}setItemTTL(N,C,G){}isStale(N){return!1}initializeSizeTracking(){this.calculatedSize=0,this.sizes=new w(this.max),this.removeItemSize=N=>{this.calculatedSize-=this.sizes[N],this.sizes[N]=0},this.requireSize=(N,C,G,Z)=>{if(this.isBackgroundFetch(C))return 0;if(!T(G)){if(!Z)throw new TypeError("invalid size value (must be positive integer). When maxSize or maxEntrySize is used, sizeCalculation or size must be set.");if(typeof Z!="function")throw new TypeError("sizeCalculation must be a function");if(G=Z(C,N),!T(G))throw new TypeError("sizeCalculation return invalid (expect positive integer)")}return G},this.addItemSize=(N,C,G)=>{if(this.sizes[N]=C,this.maxSize){const Z=this.maxSize-this.sizes[N];for(;this.calculatedSize>Z;)this.evict(!0)}this.calculatedSize+=this.sizes[N],G&&(G.entrySize=C,G.totalCalculatedSize=this.calculatedSize)}}removeItemSize(N){}addItemSize(N,C){}requireSize(N,C,G,Z){if(G||Z)throw new TypeError("cannot set size without setting maxSize or maxEntrySize on cache")}*indexes({allowStale:N=this.allowStale}={}){if(this.size)for(let C=this.tail;this.isValidIndex(C)&&(!N&&this.isStale(C)||(yield C),C!==this.head);)C=this.prev[C]}*rindexes({allowStale:N=this.allowStale}={}){if(this.size)for(let C=this.head;this.isValidIndex(C)&&(!N&&this.isStale(C)||(yield C),C!==this.tail);)C=this.next[C]}isValidIndex(N){return N!==void 0&&this.keyMap.get(this.keyList[N])===N}*entries(){for(const N of this.indexes())this.valList[N]===void 0||this.keyList[N]===void 0||this.isBackgroundFetch(this.valList[N])||(yield[this.keyList[N],this.valList[N]])}*rentries(){for(const N of this.rindexes())this.valList[N]===void 0||this.keyList[N]===void 0||this.isBackgroundFetch(this.valList[N])||(yield[this.keyList[N],this.valList[N]])}*keys(){for(const N of this.indexes())this.keyList[N]===void 0||this.isBackgroundFetch(this.valList[N])||(yield this.keyList[N])}*rkeys(){for(const N of this.rindexes())this.keyList[N]===void 0||this.isBackgroundFetch(this.valList[N])||(yield this.keyList[N])}*values(){for(const N of this.indexes())this.valList[N]===void 0||this.isBackgroundFetch(this.valList[N])||(yield this.valList[N])}*rvalues(){for(const N of this.rindexes())this.valList[N]===void 0||this.isBackgroundFetch(this.valList[N])||(yield this.valList[N])}[Symbol.iterator](){return this.entries()}find(N,C){for(const G of this.indexes()){const Z=this.valList[G],pe=this.isBackgroundFetch(Z)?Z.__staleWhileFetching:Z;if(pe!==void 0&&N(pe,this.keyList[G],this))return this.get(this.keyList[G],C)}}forEach(N,C=this){for(const G of this.indexes()){const Z=this.valList[G],pe=this.isBackgroundFetch(Z)?Z.__staleWhileFetching:Z;pe!==void 0&&N.call(C,pe,this.keyList[G],this)}}rforEach(N,C=this){for(const G of this.rindexes()){const Z=this.valList[G],pe=this.isBackgroundFetch(Z)?Z.__staleWhileFetching:Z;pe!==void 0&&N.call(C,pe,this.keyList[G],this)}}get prune(){return f("prune","purgeStale"),this.purgeStale}purgeStale(){let N=!1;for(const C of this.rindexes({allowStale:!0}))this.isStale(C)&&(this.delete(this.keyList[C]),N=!0);return N}dump(){const N=[];for(const C of this.indexes({allowStale:!0})){const G=this.keyList[C],Z=this.valList[C],pe=this.isBackgroundFetch(Z)?Z.__staleWhileFetching:Z;if(pe===void 0)continue;const Ue={value:pe};if(this.ttls){Ue.ttl=this.ttls[C];const ve=l.now()-this.starts[C];Ue.start=Math.floor(Date.now()-ve)}this.sizes&&(Ue.size=this.sizes[C]),N.unshift([G,Ue])}return N}load(N){this.clear();for(const[C,G]of N){if(G.start){const Z=Date.now()-G.start;G.start=l.now()-Z}this.set(C,G.value,G)}}dispose(N,C,G){}set(N,C,{ttl:G=this.ttl,start:Z,noDisposeOnSet:pe=this.noDisposeOnSet,size:Ue=0,sizeCalculation:ve=this.sizeCalculation,noUpdateTTL:Re=this.noUpdateTTL,status:Se}={}){if(Ue=this.requireSize(N,C,Ue,ve),this.maxEntrySize&&Ue>this.maxEntrySize)return Se&&(Se.set="miss",Se.maxEntrySizeExceeded=!0),this.delete(N),this;let fe=this.size===0?void 0:this.keyMap.get(N);if(fe===void 0)fe=this.newIndex(),this.keyList[fe]=N,this.valList[fe]=C,this.keyMap.set(N,fe),this.next[this.tail]=fe,this.prev[fe]=this.tail,this.tail=fe,this.size++,this.addItemSize(fe,Ue,Se),Se&&(Se.set="add"),Re=!1;else{this.moveToTail(fe);const p=this.valList[fe];if(C!==p){if(this.isBackgroundFetch(p)?p.__abortController.abort(new Error("replaced")):pe||(this.dispose(p,N,"set"),this.disposeAfter&&this.disposed.push([p,N,"set"])),this.removeItemSize(fe),this.valList[fe]=C,this.addItemSize(fe,Ue,Se),Se){Se.set="replace";const g=p&&this.isBackgroundFetch(p)?p.__staleWhileFetching:p;g!==void 0&&(Se.oldValue=g)}}else Se&&(Se.set="update")}if(G===0||this.ttl!==0||this.ttls||this.initializeTTLTracking(),Re||this.setItemTTL(fe,G,Z),this.statusTTL(Se,fe),this.disposeAfter)for(;this.disposed.length;)this.disposeAfter(...this.disposed.shift());return this}newIndex(){return this.size===0?this.tail:this.size===this.max&&this.max!==0?this.evict(!1):this.free.length!==0?this.free.pop():this.initialFill++}pop(){if(this.size){const N=this.valList[this.head];return this.evict(!0),N}}evict(N){const C=this.head,G=this.keyList[C],Z=this.valList[C];return this.isBackgroundFetch(Z)?Z.__abortController.abort(new Error("evicted")):(this.dispose(Z,G,"evict"),this.disposeAfter&&this.disposed.push([Z,G,"evict"])),this.removeItemSize(C),N&&(this.keyList[C]=null,this.valList[C]=null,this.free.push(C)),this.head=this.next[C],this.keyMap.delete(G),this.size--,C}has(N,{updateAgeOnHas:C=this.updateAgeOnHas,status:G}={}){const Z=this.keyMap.get(N);if(Z!==void 0){if(!this.isStale(Z))return C&&this.updateItemAge(Z),G&&(G.has="hit"),this.statusTTL(G,Z),!0;G&&(G.has="stale",this.statusTTL(G,Z))}else G&&(G.has="miss");return!1}peek(N,{allowStale:C=this.allowStale}={}){const G=this.keyMap.get(N);if(G!==void 0&&(C||!this.isStale(G))){const Z=this.valList[G];return this.isBackgroundFetch(Z)?Z.__staleWhileFetching:Z}}backgroundFetch(N,C,G,Z){const pe=C===void 0?void 0:this.valList[C];if(this.isBackgroundFetch(pe))return pe;const Ue=new u;G.signal&&G.signal.addEventListener("abort",()=>Ue.abort(G.signal.reason));const ve={signal:Ue.signal,options:G,context:Z},Re=(p,g=!1)=>{const{aborted:V}=Ue.signal,X=G.ignoreFetchAbort&&p!==void 0;return G.status&&(V&&!g?(G.status.fetchAborted=!0,G.status.fetchError=Ue.signal.reason,X&&(G.status.fetchAbortIgnored=!0)):G.status.fetchResolved=!0),!V||X||g?(this.valList[C]===fe&&(p===void 0?fe.__staleWhileFetching?this.valList[C]=fe.__staleWhileFetching:this.delete(N):(G.status&&(G.status.fetchUpdated=!0),this.set(N,p,ve.options))),p):Se(Ue.signal.reason)},Se=p=>{const{aborted:g}=Ue.signal,V=g&&G.allowStaleOnFetchAbort,X=V||G.allowStaleOnFetchRejection,ue=X||G.noDeleteOnFetchRejection;if(this.valList[C]===fe&&(!ue||fe.__staleWhileFetching===void 0?this.delete(N):V||(this.valList[C]=fe.__staleWhileFetching)),X)return G.status&&fe.__staleWhileFetching!==void 0&&(G.status.returnedStale=!0),fe.__staleWhileFetching;if(fe.__returned===fe)throw p};G.status&&(G.status.fetchDispatched=!0);const fe=new Promise((p,g)=>{this.fetchMethod(N,pe,ve).then(V=>p(V),g),Ue.signal.addEventListener("abort",()=>{G.ignoreFetchAbort&&!G.allowStaleOnFetchAbort||(p(),G.allowStaleOnFetchAbort&&(p=V=>Re(V,!0)))})}).then(Re,p=>(G.status&&(G.status.fetchRejected=!0,G.status.fetchError=p),Se(p)));return fe.__abortController=Ue,fe.__staleWhileFetching=pe,fe.__returned=null,C===void 0?(this.set(N,fe,{...ve.options,status:void 0}),C=this.keyMap.get(N)):this.valList[C]=fe,fe}isBackgroundFetch(N){return N&&typeof N=="object"&&typeof N.then=="function"&&Object.prototype.hasOwnProperty.call(N,"__staleWhileFetching")&&Object.prototype.hasOwnProperty.call(N,"__returned")&&(N.__returned===N||N.__returned===null)}async fetch(N,{allowStale:C=this.allowStale,updateAgeOnGet:G=this.updateAgeOnGet,noDeleteOnStaleGet:Z=this.noDeleteOnStaleGet,ttl:pe=this.ttl,noDisposeOnSet:Ue=this.noDisposeOnSet,size:ve=0,sizeCalculation:Re=this.sizeCalculation,noUpdateTTL:Se=this.noUpdateTTL,noDeleteOnFetchRejection:fe=this.noDeleteOnFetchRejection,allowStaleOnFetchRejection:p=this.allowStaleOnFetchRejection,ignoreFetchAbort:g=this.ignoreFetchAbort,allowStaleOnFetchAbort:V=this.allowStaleOnFetchAbort,fetchContext:X=this.fetchContext,forceRefresh:ue=!1,status:be,signal:Ce}={}){if(!this.fetchMethod)return be&&(be.fetch="get"),this.get(N,{allowStale:C,updateAgeOnGet:G,noDeleteOnStaleGet:Z,status:be});const Ae={allowStale:C,updateAgeOnGet:G,noDeleteOnStaleGet:Z,ttl:pe,noDisposeOnSet:Ue,size:ve,sizeCalculation:Re,noUpdateTTL:Se,noDeleteOnFetchRejection:fe,allowStaleOnFetchRejection:p,allowStaleOnFetchAbort:V,ignoreFetchAbort:g,status:be,signal:Ce};let Le=this.keyMap.get(N);if(Le===void 0){be&&(be.fetch="miss");const Ke=this.backgroundFetch(N,Le,Ae,X);return Ke.__returned=Ke}{const Ke=this.valList[Le];if(this.isBackgroundFetch(Ke)){const lt=C&&Ke.__staleWhileFetching!==void 0;return be&&(be.fetch="inflight",lt&&(be.returnedStale=!0)),lt?Ke.__staleWhileFetching:Ke.__returned=Ke}const at=this.isStale(Le);if(!ue&&!at)return be&&(be.fetch="hit"),this.moveToTail(Le),G&&this.updateItemAge(Le),this.statusTTL(be,Le),Ke;const gt=this.backgroundFetch(N,Le,Ae,X),Ut=gt.__staleWhileFetching!==void 0,it=Ut&&C;return be&&(be.fetch=Ut&&at?"stale":"refresh",it&&at&&(be.returnedStale=!0)),it?gt.__staleWhileFetching:gt.__returned=gt}}get(N,{allowStale:C=this.allowStale,updateAgeOnGet:G=this.updateAgeOnGet,noDeleteOnStaleGet:Z=this.noDeleteOnStaleGet,status:pe}={}){const Ue=this.keyMap.get(N);if(Ue!==void 0){const ve=this.valList[Ue],Re=this.isBackgroundFetch(ve);return this.statusTTL(pe,Ue),this.isStale(Ue)?(pe&&(pe.get="stale"),Re?(pe&&(pe.returnedStale=C&&ve.__staleWhileFetching!==void 0),C?ve.__staleWhileFetching:void 0):(Z||this.delete(N),pe&&(pe.returnedStale=C),C?ve:void 0)):(pe&&(pe.get="hit"),Re?ve.__staleWhileFetching:(this.moveToTail(Ue),G&&this.updateItemAge(Ue),ve))}pe&&(pe.get="miss")}connect(N,C){this.prev[C]=N,this.next[N]=C}moveToTail(N){N!==this.tail&&(N===this.head?this.head=this.next[N]:this.connect(this.prev[N],this.next[N]),this.connect(this.tail,N),this.tail=N)}get del(){return f("del","delete"),this.delete}delete(N){let C=!1;if(this.size!==0){const G=this.keyMap.get(N);if(G!==void 0)if(C=!0,this.size===1)this.clear();else{this.removeItemSize(G);const Z=this.valList[G];this.isBackgroundFetch(Z)?Z.__abortController.abort(new Error("deleted")):(this.dispose(Z,N,"delete"),this.disposeAfter&&this.disposed.push([Z,N,"delete"])),this.keyMap.delete(N),this.keyList[G]=null,this.valList[G]=null,G===this.tail?this.tail=this.prev[G]:G===this.head?this.head=this.next[G]:(this.next[this.prev[G]]=this.next[G],this.prev[this.next[G]]=this.prev[G]),this.size--,this.free.push(G)}}if(this.disposed)for(;this.disposed.length;)this.disposeAfter(...this.disposed.shift());return C}clear(){for(const N of this.rindexes({allowStale:!0})){const C=this.valList[N];if(this.isBackgroundFetch(C))C.__abortController.abort(new Error("deleted"));else{const G=this.keyList[N];this.dispose(C,G,"delete"),this.disposeAfter&&this.disposed.push([C,G,"delete"])}}if(this.keyMap.clear(),this.valList.fill(null),this.keyList.fill(null),this.ttls&&(this.ttls.fill(0),this.starts.fill(0)),this.sizes&&this.sizes.fill(0),this.head=0,this.tail=0,this.initialFill=1,this.free.length=0,this.calculatedSize=0,this.size=0,this.disposed)for(;this.disposed.length;)this.disposeAfter(...this.disposed.shift())}get reset(){return f("reset","clear"),this.clear}get length(){return((N,C)=>{const G="LRU_CACHE_PROPERTY_"+N;if(U(G)){const{prototype:Z}=Y,{get:pe}=Object.getOwnPropertyDescriptor(Z,N);b(G,N+" property","cache."+C,pe)}})("length","size"),this.size}static get AbortController(){return u}static get AbortSignal(){return R}}const A=Y;var L=__webpack_require__(2273),m=__webpack_require__(1597),H=function(Ee,N,C,G){return new(C||(C=Promise))(function(Z,pe){function Ue(Se){try{Re(G.next(Se))}catch(fe){pe(fe)}}function ve(Se){try{Re(G.throw(Se))}catch(fe){pe(fe)}}function Re(Se){var fe;Se.done?Z(Se.value):(fe=Se.value,fe instanceof C?fe:new C(function(p){p(fe)})).then(Ue,ve)}Re((G=G.apply(Ee,N||[])).next())})};class W extends class{constructor(N,C){this.type=N,this.name=C}}{constructor(N){super("simple","LogReporter"),this.message=N}send(N){return H(this,void 0,void 0,function*(){var C,G;m.vF.debug(this.message,(C=N.reduce((Z,pe)=>Object.assign(Object.assign({},Z),{[pe.name]:pe.stat}),{}),G=Z=>{const{sum:pe,count:Ue}=Z,ve=pe/Ue;return Object.assign(Object.assign({},Z),{average:ve})},Object.keys(C).reduce((Z,pe)=>Object.assign(Object.assign({},Z),{[pe]:G(C[pe])}),{})))})}}var E=__webpack_require__(8758),v=__webpack_require__.n(E);const k=/^[a-zA-Z0-9-_.,:?'"()@\/#$+ ]{1,255}$/;function j(Ee,N){return!!Ee&&(N!=null&&N.allowStar&&Ee[0]==="*"?Ee==="*":k.test(Ee))}var _=function(Ee,N,C,G){return new(C||(C=Promise))(function(Z,pe){function Ue(Se){try{Re(G.next(Se))}catch(fe){pe(fe)}}function ve(Se){try{Re(G.throw(Se))}catch(fe){pe(fe)}}function Re(Se){var fe;Se.done?Z(Se.value):(fe=Se.value,fe instanceof C?fe:new C(function(p){p(fe)})).then(Ue,ve)}Re((G=G.apply(Ee,N||[])).next())})};function M({func:Ee,delay:N,immediate:C=!0}){let G=!1,Z=setTimeout(function Ue(){return _(this,void 0,void 0,function*(){if(G)return;const ve=new Date().getTime();try{pe=Ee(),yield pe}finally{if(!G){const Re=new Date().getTime();Z=setTimeout(Ue,Math.max(N-(Re-ve),0))}}})},C?0:N),pe=Promise.resolve();return{stop(){return _(this,void 0,void 0,function*(){G=!0,clearTimeout(Z),yield pe})},pending(){return _(this,void 0,void 0,function*(){yield pe})}}}var $=function(Ee,N,C,G){return new(C||(C=Promise))(function(Z,pe){function Ue(Se){try{Re(G.next(Se))}catch(fe){pe(fe)}}function ve(Se){try{Re(G.throw(Se))}catch(fe){pe(fe)}}function Re(Se){var fe;Se.done?Z(Se.value):(fe=Se.value,fe instanceof C?fe:new C(function(p){p(fe)})).then(Ue,ve)}Re((G=G.apply(Ee,N||[])).next())})};class te{constructor(N){this.buffer={},this.reporters=[],this.flushInterval=M({func:()=>this.flushStats(),delay:te.samplePeriodMs}),this.tags=this.filterTags((N==null?void 0:N.tags)||{app:L.yA,version:L.rE,namespace:L.MF})}shutdown(){return $(this,void 0,void 0,function*(){yield this.flushInterval.stop(),yield this.flushStats(),yield(0,o.c)(2*r.p.second)})}aggregate(N,C,G){this.addToBuffer(this.buffer,this.encodeKey({metric:N,tags:this.filterTags(G||{})}),typeof C=="number"?{min:C,max:C,sum:C,count:1}:C)}increment(N,C){this.aggregate(N,1,C)}timer(N,C,G){return $(this,void 0,void 0,function*(){const Z=v()(),pe=yield C(),Ue=v()();return this.aggregate(N,Ue-Z,G),pe})}registerStatsReporter(N){this.reporters.push(N)}setTag(N,C){const G=this.filterTags({[N]:C});this.tags=Object.assign(Object.assign({},this.tags),G)}addToBuffer(N,C,G){if(N[C]){const{min:Z,max:pe,sum:Ue,count:ve}=N[C];N[C]={min:Math.min(Z,G.min),max:Math.max(pe,G.max),sum:Ue+G.sum,count:ve+G.count}}else N[C]=G}write(N){return $(this,void 0,void 0,function*(){yield Promise.all(this.reporters.map(C=>$(this,void 0,void 0,function*(){let G;const Z={};switch(C.type){case"simple":for(const[Ue,ve]of Object.entries(N)){const{metric:Re}=this.decodeKey(Ue);this.addToBuffer(Z,this.encodeKey({metric:Re}),ve)}G=Z;break;case"tagged":G=N;break;default:(function(Ue){throw new Error(`Unreachable type encountered (${Ue})`)})(C.type)}const pe=Object.entries(G);if(pe.length>0)return C.send(pe.map(([Ue,ve])=>{const{metric:Re,tags:Se}=this.decodeKey(Ue);return{name:Re,tags:Object.assign(Object.assign({},Se),this.tags),stat:ve}}),te.samplePeriodMs).catch(Ue=>{m.vF.debug("Failed to write stats to "+C.name,{error:Ue})})})))})}flushStats(){return $(this,void 0,void 0,function*(){yield this.write(this.buffer),this.buffer={}})}encodeKey(N){return c()(Object.assign(Object.assign({},N),Object.keys(N.tags||{}).length>0?{tags:N.tags}:{}))}decodeKey(N){return JSON.parse(N)}filterTags(N){return Object.entries(N||{}).reduce((C,[G,Z])=>(j(G)&&j(Z)&&(C[G]=Z),C),{})}}te.samplePeriodMs=5*r.p.minute;const P=!!L.op,q=new te;P||["local","on-prem"].includes(L.MF)||q.registerStatsReporter(new W("stats"));var ie=function(Ee,N,C,G){return new(C||(C=Promise))(function(Z,pe){function Ue(Se){try{Re(G.next(Se))}catch(fe){pe(fe)}}function ve(Se){try{Re(G.throw(Se))}catch(fe){pe(fe)}}function Re(Se){var fe;Se.done?Z(Se.value):(fe=Se.value,fe instanceof C?fe:new C(function(p){p(fe)})).then(Ue,ve)}Re((G=G.apply(Ee,N||[])).next())})};class ee extends class{constructor(N){this.options=N,this.cache=new A(Object.assign(Object.assign(Object.assign({},N.dispose||N.disposeAfter?{ttlAutopurge:!0}:{}),N),{dispose:(...C)=>{var G;C[2]==="evict"&&q.increment("lru-eviction",{name:N.name}),(G=N.dispose)===null||G===void 0||G.call(N,...C)},disposeAfter:(...C)=>{var G;this.updateStats(),(G=N.disposeAfter)===null||G===void 0||G.call(N,...C)}})),this.stringify=N.fastStringify?JSON.stringify:c()}set(N,C,G){const Z=this.stringify(N);if(!this.cache.set(Z,C,{ttl:G})){const pe=this.cache.sizeCalculation?this.cache.sizeCalculation(C,Z):"unknown";throw Error(`Value too large (${pe} > ${this.cache.max})`)}this.updateStats()}get(N){const{name:C}=this.options,G=this.stringify(N),Z=this.cache.getRemainingTTL(G);return Z<=0?q.increment("cache-miss",{name:C}):Z!==1/0&&q.aggregate("cache-item-ttl",Z,{name:C}),this.cache.get(G)}delete(N){this.cache.delete(this.stringify(N))}peek(N){return this.cache.peek(this.stringify(N))}size(){return this.cache.size}clear(){this.cache.clear()}forEach(N){this.cache.forEach(N)}purgeStale(){return this.cache.purgeStale()}updateStats(){const{name:N}=this.options;q.aggregate("cache-item-count",this.cache.size,{name:N}),this.cache.calculatedSize!==void 0&&q.aggregate("cache-length",this.cache.calculatedSize,{name:N})}}{constructor(N){if(super(N),this.expireRejectedPromiseValues=N.expireRejectedPromiseValues===void 0||N.expireRejectedPromiseValues,this.rejectedPromiseValueTtl=N.rejectedPromiseValueTtl!==void 0?N.rejectedPromiseValueTtl:r.p.second,this.rejectedPromiseValueTtl<0)throw new Error("rejectedPromiseValueTtl must not be negative")}set(N,C,G){super.set(N,C,G),this.expireRejectedPromiseValues&&C.catch(()=>ie(this,void 0,void 0,function*(){yield(0,o.c)(this.rejectedPromiseValueTtl),this.peek(N)===C&&this.delete(N)}))}}var x=function(Ee,N,C,G){return new(C||(C=Promise))(function(Z,pe){function Ue(Se){try{Re(G.next(Se))}catch(fe){pe(fe)}}function ve(Se){try{Re(G.throw(Se))}catch(fe){pe(fe)}}function Re(Se){var fe;Se.done?Z(Se.value):(fe=Se.value,fe instanceof C?fe:new C(function(p){p(fe)})).then(Ue,ve)}Re((G=G.apply(Ee,N||[])).next())})};class z{constructor(N,C,G){this.authClient=N,this.email=C,this.password=G,this.tokenTtlMs=1*r.p.hour,this.tokenCache=new ee({name:"Credentials-tokenCache",max:100,ttl:this.tokenTtlMs-5*r.p.minute,fastStringify:!0})}getToken(){return x(this,void 0,void 0,function*(){let N=this.tokenCache.get(this.email);return N||(N=(()=>x(this,void 0,void 0,function*(){const{authentication:C}=yield this.authClient.login({email:this.email,password:this.password,tokenExpirationSeconds:this.tokenTtlMs/r.p.second});if(!C)throw new Error("User account not verified.");return C.accessToken}))(),this.tokenCache.set(this.email,N)),N})}}var oe=function(Ee,N,C,G){return new(C||(C=Promise))(function(Z,pe){function Ue(Se){try{Re(G.next(Se))}catch(fe){pe(fe)}}function ve(Se){try{Re(G.throw(Se))}catch(fe){pe(fe)}}function Re(Se){var fe;Se.done?Z(Se.value):(fe=Se.value,fe instanceof C?fe:new C(function(p){p(fe)})).then(Ue,ve)}Re((G=G.apply(Ee,N||[])).next())})};class ce extends e.S{createPeer(N,C){return oe(this,void 0,void 0,function*(){return yield this.fetch("peers",{token:N,method:"POST",body:C})})}getPeers(N){return oe(this,void 0,void 0,function*(){return(yield this.fetch("peers",{token:N})).items})}refreshPeer(N,C){return oe(this,void 0,void 0,function*(){yield this.fetch(`peers/${C}/refresh`,{token:N,method:"POST",allowUnsafeRetries:!0})})}createSession(N,C){return oe(this,void 0,void 0,function*(){return yield this.fetch("sessions",{token:N,method:"POST",body:C})})}refreshSession(N,C){return oe(this,void 0,void 0,function*(){yield this.fetch(`sessions/${C}/refresh`,{token:N,method:"POST",allowUnsafeRetries:!0})})}deleteSession(N,C){return oe(this,void 0,void 0,function*(){yield this.fetch("sessions/"+C,{token:N,method:"DELETE",allowUnsafeRetries:!0})})}getSessions(N){return oe(this,void 0,void 0,function*(){return(yield this.fetch("sessions",{token:N})).items})}getIceServers(N){return oe(this,void 0,void 0,function*(){return(yield this.fetch("ice-servers",{token:N})).items})}addSignals(N,C,G){return oe(this,void 0,void 0,function*(){yield this.fetch(`sessions/${C}/add-signals`,{token:N,method:"POST",body:G})})}takeSignals(N,C){return oe(this,void 0,void 0,function*(){return(yield this.fetch(`sessions/${C}/take-signals`,{token:N,method:"POST"})).items})}}var re=__webpack_require__(3449),se=__webpack_require__(5949),ne=__webpack_require__(2964),he=__webpack_require__(7396),me=function(Ee,N,C,G){return new(C||(C=Promise))(function(Z,pe){function Ue(Se){try{Re(G.next(Se))}catch(fe){pe(fe)}}function ve(Se){try{Re(G.throw(Se))}catch(fe){pe(fe)}}function Re(Se){var fe;Se.done?Z(Se.value):(fe=Se.value,fe instanceof C?fe:new C(function(p){p(fe)})).then(Ue,ve)}Re((G=G.apply(Ee,N||[])).next())})};class Qe extends he.V{constructor(N){super(N)}postLanRtcOffer(N){return me(this,void 0,void 0,function*(){return yield this.fetch("v1/lan-rtc-offer",{method:"POST",body:N})})}}var Ve=function(Ee,N,C,G){return new(C||(C=Promise))(function(Z,pe){function Ue(Se){try{Re(G.next(Se))}catch(fe){pe(fe)}}function ve(Se){try{Re(G.throw(Se))}catch(fe){pe(fe)}}function Re(Se){var fe;Se.done?Z(Se.value):(fe=Se.value,fe instanceof C?fe:new C(function(p){p(fe)})).then(Ue,ve)}Re((G=G.apply(Ee,N||[])).next())})};function We(Ee){return Ve(this,void 0,void 0,function*(){return(yield Promise.all(Ee.map(N=>N.catch(C=>C)))).filter(N=>N instanceof Error)})}function J(Ee,N){if(Ee===void 0)throw new Error("Value is undefined"+(N?": "+N:""))}function O(Ee,N){if(Ee===null)throw new Error("Value is null"+(N?": "+N:""))}function I(Ee){return J(Ee),Ee}function ae(Ee,N){const C=Ee.reduce((G,Z)=>[...G,...Z.urls],[]).filter(G=>ge(G,N)).sort(G=>Fe(G,"udp")?-1:0).shift();if(C)return Object.assign(Object.assign({},I(Ee.find(G=>G.urls.includes(C)))),{urls:[C]})}function ge(Ee,N){switch(N){case"stun":return/^stuns?:/.test(Ee);case"turn":return/^turns?:/.test(Ee)}}function Fe(Ee,N){return Ee.endsWith("transport="+N)}var ye=__webpack_require__(7207);class Oe extends Error{constructor(N,C){super(`Deadline expired after ${N}ms + ${C}ms`)}}class Ie{static withDeadline(N,C){const G=new Promise((Z,pe)=>{setTimeout(()=>{pe(new Oe(C,this.grpcCallDeadlineSlopMs))},C+this.grpcCallDeadlineSlopMs)});return Promise.race([N,G])}}Ie.grpcCallDeadlineSlopMs=500*r.p.millisecond;var Pe=__webpack_require__(8311);const ze={ordered:!1,maxPacketLifeTime:300*r.p.millisecond},qe={ordered:!0},pt={ordered:!0},dt={ordered:!1,maxRetransmits:0},vt={ordered:!1,maxRetransmits:0},Ne=Ee=>"received"in Ee&&Ee.received!==void 0,ft=Ee=>!("received"in Ee)||Ee.received===void 0,Ft=2*r.p.second,de=10*r.p.second;function ht(Ee,N={}){const C=Array.from(Ee.values()),G=C.filter(Ne),Z=G.length>0,pe=Math.max(...C.map(fe=>fe.sent)),Ue=Math.max(...G.map(fe=>fe.received));let ve;if(Z){const fe=Date.now()-pe<=r.p.millisecond?C.length-1:C.length,p=G.length>fe?fe:G.length,g=G.map(Le=>Le.received-Le.sent),{standardDeviation:V,mean:X,jitter:ue}=function(Le){const Ke=Le.length;if(Ke===0)return{mean:NaN,standardDeviation:-1,jitter:NaN};const at=Le.reduce((it,lt)=>it+lt,0)/Ke,gt=Math.sqrt(Le.map(it=>Math.pow(it-at,2)).reduce((it,lt)=>it+lt)/Ke);if(Ke===1)return{mean:at,standardDeviation:gt,jitter:NaN};let Ut=0;for(let it=1;it<Ke;it++)Ut+=Math.abs(Le[it]-Le[it-1]);return{mean:at,standardDeviation:gt,jitter:Ut/(Ke-1)}}(g),be=C.filter(Le=>Le.sent<Ue-Ft),Ce=be.filter(ft),Ae=Ce.length===0?0:Ce.length/be.length;ve={pingsSent:fe,pongsReceived:p,average:X,standardDeviation:V,jitter:ue,max:Math.max(...g),min:Math.min(...g),loss:Ae}}else ve=null;const{temporalNow:Re=Date.now()}=N,Se=(Z?Ue:Re)-de;return Array.from(Ee.entries()).forEach(fe=>{const[p,g]=fe;g.sent<Se&&Ee.delete(p)}),ve}function mt({entityId:Ee,streamName:N,streamType:C}){return`${Ee}.${N}.${C}`}var nt=function(Ee,N,C,G){return new(C||(C=Promise))(function(Z,pe){function Ue(Se){try{Re(G.next(Se))}catch(fe){pe(fe)}}function ve(Se){try{Re(G.throw(Se))}catch(fe){pe(fe)}}function Re(Se){var fe;Se.done?Z(Se.value):(fe=Se.value,fe instanceof C?fe:new C(function(p){p(fe)})).then(Ue,ve)}Re((G=G.apply(Ee,N||[])).next())})};class Dt{constructor(N,C){this.counts={localSent:new Map,localReceived:new Map,remoteSent:new Map,remoteReceived:new Map},this.sessionId=N,this.connection=C}updateRemoteMessagesCounts(N){if(N.payload.streamsInfo){this.counts.remoteSent=new Map,this.counts.remoteReceived=new Map;for(const C of N.payload.streamsInfo.items)this.counts.remoteSent.set(C.streamId,C.sentCount),this.counts.remoteReceived.set(C.streamId,C.receivedCount)}}getLocalStreamsInfo(N){const{localSent:C,localReceived:G}=this.counts;return{items:[...new Set([...C.keys(),...G.keys()])].map(Z=>{var pe,Ue;return{streamId:Z,sentCount:(pe=C.get(Z))!==null&&pe!==void 0?pe:0,receivedCount:(Ue=G.get(Z))!==null&&Ue!==void 0?Ue:0}}),timestamp:N}}incrementLocalSent(N){const{localSent:C}=this.counts,G=mt(N.header.stream);C.set(G,(C.get(G)||0)+1)}incrementLocalReceived(N){const{localReceived:C}=this.counts,G=mt(N.header.stream),Z=C.get(G)||0;if(Z===0){const{streamName:pe,streamType:Ue}=N.header.stream;m.vF.debug("RTC client received first message for stream",{streamName:pe,streamType:Ue})}C.set(G,Z+1)}uploadMetrics(){return nt(this,void 0,void 0,function*(){const{sessionId:N}=this,C=yield this.connection.peerConnection.getStats(),G={};C.forEach(Se=>G[Se.id]=Se),m.vF.debug("rtc-stats",Object.assign(Object.assign({},G),{sessionId:N}));const{localSent:Z,localReceived:pe,remoteSent:Ue,remoteReceived:ve}=this.counts,Re=[...new Set([...Z.keys(),...pe.keys()])].reduce((Se,fe)=>{const p=Z.get(fe),g=pe.get(fe),V=Ue.get(fe),X=ve.get(fe);return Object.assign(Object.assign({},Se),{[`local-${fe}-sent`]:p,[`local-${fe}-received`]:g,[`remote-${fe}-sent`]:V,[`remote-${fe}-received`]:X})},{sessionId:N});m.vF.debug("rtc-message-report",Object.assign({deviceId:this.connection.getRemoteDeviceId()},Re))})}}var kt=__webpack_require__(7186);function je(Ee){if(Ee.byteLength<4)return!1;const N=new Uint8Array(Ee);return N[0]===72&&N[1]===50&&N[2]===54&&N[3]===52}function Mt(Ee){if(Ee.byteLength<4)return!1;const N=new Uint8Array(Ee);return N[0]===66&&N[1]===67&&N[2]===72&&N[3]===75}function Et(Ee){if(!je(Ee))throw new Error("Data is not a binary H264 message");const N=new DataView(Ee),C=Number(N.getBigUint64(4,!1)),G=N.getUint16(12,!1),Z=new Uint8Array(Ee,14,G),pe=14+G;return{communicationType:"binary-h264",timestamp:C,streamName:new TextDecoder().decode(Z),frame:function(Ue){const ve=new kt.BinaryReader(new Uint8Array(Ue));let Re=0,Se=0,fe="";try{for(;ve.nextField()&&!ve.isEndGroup();)switch(ve.getFieldNumber()){case 1:Re=ve.readInt32();break;case 2:Se=ve.readInt32();break;case 3:{const p=ve.readBytes();fe=btoa(String.fromCharCode(...p));break}default:ve.skipField()}return{index:Re,flags:Se,frame_data:fe}}catch(p){throw new Error("Failed to decode H264VideoFrame: "+p)}}(Ee.slice(pe))}}function bt(Ee,N,C){return{header:{stream:Ee,created:Date.now(),frameId:C||""},payload:N}}function Wt(Ee){const N=Ee.localCandidate.candidateType,C=Ee.remoteCandidate.candidateType;return N==="host"&&C==="host"?"local":N==="relay"||C==="relay"?"TURN":"STUN"}function Ze(Ee){return new Set(["disconnected","failed","closed"]).has(Ee.iceConnectionState)}function et(Ee){switch(Ee.header.stream.streamType){case"twist":{const{twist:N}=Ee.payload;if(!N)throw Error("twist not in payload of RTC message with type twist");return{header:Ee.header,payload:{twist:{linear:Object.assign({x:0,y:0,z:0},N.linear),angular:Object.assign({x:0,y:0,z:0},N.angular)}}}}case"pose":{const{pose:N}=Ee.payload;if(!N)throw Error("pose not in payload of RTC message with type pose");return{header:Ee.header,payload:{pose:{translation:Object.assign({x:0,y:0,z:0},N.translation),rotation:Object.assign({x:0,y:0,z:0,w:0},N.rotation)}}}}case"pose-with-covariance":{const{poseWithCovariance:N}=Ee.payload;if(!N)throw Error("poseWithCovariance not in payload of RTC message with type pose-with-covariance");const C=new Array(36).fill(0);return N.covariance.forEach((G,Z)=>{if(Z>=36)throw Error("covariance contains more than 36 elements");C[Z]=G}),{header:Ee.header,payload:{poseWithCovariance:{pose:{translation:Object.assign({x:0,y:0,z:0},N.pose.translation),rotation:Object.assign({x:0,y:0,z:0,w:0},N.pose.rotation)},covariance:C}}}}case"point":{const{point:N}=Ee.payload;if(!N)throw Error("point not in payload of RTC message with type point");return{header:Ee.header,payload:{point:Object.assign({x:0,y:0,z:0},N)}}}default:return Ee}}var st=function(Ee,N,C,G){return new(C||(C=Promise))(function(Z,pe){function Ue(Se){try{Re(G.next(Se))}catch(fe){pe(fe)}}function ve(Se){try{Re(G.throw(Se))}catch(fe){pe(fe)}}function Re(Se){var fe;Se.done?Z(Se.value):(fe=Se.value,fe instanceof C?fe:new C(function(p){p(fe)})).then(Ue,ve)}Re((G=G.apply(Ee,N||[])).next())})};class Bt{get peerConnection(){return O(this._peerConnection,"RTCPeerConnection is closed!"),this._peerConnection}constructor(N,C,G,Z){this.iceServers=C,this.config=G,this.dataChannelNotifier=Z,this.connectTimeoutMs=20*r.p.second,this.iceGatheringTimeoutMs=3*r.p.second,this.pingUpdateTimeoutMs=1*r.p.second,this.pingV2UpdateTimeoutMs=250*r.p.millisecond,this.pingV2MetricsGatherTimeoutMs=1*r.p.second,this.streamsInfoUpdateTimeoutMs=2*r.p.second,this.reassemblyTimeoutMs=500*r.p.millisecond,this.reassemblyTableCleanupMs=1*r.p.second,this.heartbeatTimeoutMs=20*r.p.millisecond,this._peerConnection=null,this.heartbeatChannel=null,this.latestTtlStreamChannel=null,this.reliableStreamChannel=null,this.latestReliableStreamChannel=null,this.latestTryOnceStreamChannel=null,this.streamLatestTimestamp=new Map,this.reassemblyTable=new Map,this.reassemblyTableLastTimestamp=new Map,this.binaryReassemblyTable=new Map,this.binaryReassemblyTableLastTimestamp=new Map,this.closeCalled=!1,this.gotOffer=!1,this.hasIceCandidate=!1,this.pingV2Map=new Map,this.sendPingV2=()=>{const{latestTryOnceStreamChannel:Ue}=this;if(!Ue)return;const ve=new Date().getTime(),Re=(0,ne.A)();this.sendSystemMessage(Ue,{type:"ping-v2",payload:{timestamp:ve,id:Re}}),this.pingV2Map.set(Re,{sent:ve})},this.gatherPingV2Metrics=()=>{const Ue=ht(this.pingV2Map);if(Ue){const ve=this.getRemoteDeviceId();this.pingInfo=Ue,q.aggregate("rtc-ping-average",Ue.average,Object.assign({},ve?{deviceId:ve}:{})),q.aggregate("rtc-ping-loss",Ue.loss,Object.assign({},ve?{deviceId:ve}:{})),q.aggregate("rtc-jitter",Ue.jitter,Object.assign({},ve?{deviceId:ve}:{}))}},this._peerConnection=N;const{isOffer:pe}=G.baseConfig;pe?this.initializeChannels(N):N.ondatachannel=Ue=>{switch(Ue.channel.label){case"stream.latest-ttl":this.latestTtlStreamChannel=Ue.channel;break;case"stream.reliable":this.reliableStreamChannel=Ue.channel;break;case"stream.latest-reliable":this.latestReliableStreamChannel=Ue.channel;break;case"stream.latest-try-once":this.latestTryOnceStreamChannel=Ue.channel;break;case"heartbeat":return void(this.heartbeatChannel=Ue.channel);default:return void this.dataChannelNotifier(Ue.channel)}this.setupChannel(Ue.channel)},this.pingUpdateTimeout=setInterval(()=>{const{reliableStreamChannel:Ue}=this;Ue&&this.sendSystemMessage(Ue,{type:"ping"})},this.pingUpdateTimeoutMs),this.pingV2UpdateTimeout=setInterval(this.sendPingV2,this.pingV2UpdateTimeoutMs),this.pingV2MetricsGatherTimeout=setInterval(this.gatherPingV2Metrics,this.pingV2MetricsGatherTimeoutMs),this.streamsInfoUpdateTimeout=setInterval(()=>{const{latestTtlStreamChannel:Ue}=this;Ue&&this.sendSystemMessage(Ue,{type:"streams-info"})},this.streamsInfoUpdateTimeoutMs),this.reassemblyTableCleanupTimeout=setInterval(()=>{const Ue=new Date().getTime();this.reassemblyTableLastTimestamp.forEach((ve,Re,Se)=>{Ue>Re+this.reassemblyTimeoutMs&&this.reassemblyTable.delete(ve)})},this.reassemblyTableCleanupMs),this.heartbeatTimeout=setInterval(()=>{const{heartbeatChannel:Ue}=this;if(!Ue||Ue.readyState!=="open")return;const ve=new Uint8Array([1]);Ue.send(ve.buffer)},this.heartbeatTimeoutMs)}handleSignal(N){return st(this,void 0,void 0,function*(){const{peerConnection:C}=this,{track:G}=this.config.baseConfig,Z=(()=>{try{return JSON.parse(N.getPayload())}catch{return}})();if(!Z)return void m.vF.error("Received unparseable signal.");m.vF.debug("Handling signal",{description:Z});const{sdp:pe,type:Ue}=Z;if(!pe||!Ue)return void m.vF.warn("Received non-SDP signal");const{signalingState:ve,connectionState:Re}=C;if(ve!=="stable"||Re!=="connected")if(C.remoteDescription)m.vF.warn("Received SDP after remote description was set: "+pe);else{if(Ue==="offer"){if(ve!=="stable")return void m.vF.warn("Received offer SDP when signaling is ongoing.");yield C.setRemoteDescription(Z);const Se=yield C.createAnswer();yield C.setLocalDescription(Se);const fe=N.clone();return G==null||G("Answer Received",fe),fe.setPayload(JSON.stringify(Se)),fe.setReceiverId(N.getSenderId()),fe.setSenderId(N.getReceiverId()),fe}if(Ue==="answer"){if(ve==="stable")return void m.vF.warn("Received answer SDP when signaling hasn't started.");yield C.setRemoteDescription(Z)}}else m.vF.warn("Received SDP when already connected: "+pe)})}send(N,C){const G=this.getChannelFromLabel(C.channelLabel);G?this.sendOnChannel(G,N):m.vF.warn("Send called with unexpected channel label",{channelLabel:C.channelLabel})}controlRemoteStream(N){var C;this.sendSystemMessage((O(C=this.reliableStreamChannel),C),{type:"stream-control",streamControl:N})}isActive(){return new Set(["new","checking","connected","completed"]).has(this.peerConnection.iceConnectionState)||this.isReady()}isReady(){const{reliableStreamChannel:N,latestTtlStreamChannel:C,latestTryOnceStreamChannel:G,latestReliableStreamChannel:Z}=this;return(N==null?void 0:N.readyState)==="open"&&(C==null?void 0:C.readyState)==="open"&&(G==null?void 0:G.readyState)==="open"&&(Z==null?void 0:Z.readyState)==="open"}close(){return st(this,void 0,void 0,function*(){var N,C,G,Z,pe,Ue,ve;this.closeCalled||(this.closeCalled=!0,yield(N=this.sessionMetrics)===null||N===void 0?void 0:N.uploadMetrics(),wt(this.pingUpdateTimeout),wt(this.pingV2UpdateTimeout),wt(this.pingV2MetricsGatherTimeout),wt(this.reassemblyTableCleanupTimeout),wt(this.streamsInfoUpdateTimeout),wt(this.heartbeatTimeout),(C=this._peerConnection)===null||C===void 0||C.close(),(G=this.heartbeatChannel)===null||G===void 0||G.close(),(Z=this.latestReliableStreamChannel)===null||Z===void 0||Z.close(),(pe=this.latestTryOnceStreamChannel)===null||pe===void 0||pe.close(),(Ue=this.latestTtlStreamChannel)===null||Ue===void 0||Ue.close(),(ve=this.reliableStreamChannel)===null||ve===void 0||ve.close(),this._peerConnection=null,this.heartbeatChannel=null,this.latestReliableStreamChannel=null,this.latestTryOnceStreamChannel=null,this.latestTtlStreamChannel=null,this.reliableStreamChannel=null)})}getPing(){return this.pingTimeMs}getPingInfo(){return this.pingInfo}getLastMessageTimestamp(){return this.lastMessageTimestamp}getSessionCreatedTimestamp(){var N;return(N=this.config.remoteConfig)===null||N===void 0?void 0:N.sessionCreatedTimestamp}setSessionCreatedTimestamp(N){this.config.remoteConfig&&(this.config.remoteConfig.sessionCreatedTimestamp=N)}getSessionId(){var N;return(N=this.config.remoteConfig)===null||N===void 0?void 0:N.sessionId}setSessionId(N){this.config.remoteConfig&&(this.config.remoteConfig.sessionId=N,this.sessionMetrics=new Dt(N,this))}getRemotePeerId(){return this.config.baseConfig.remotePeerId}getRemoteDeviceId(){var N;return(N=this.config.baseConfig)===null||N===void 0?void 0:N.remoteDeviceId}setRemoteDeviceId(N){this.config.baseConfig.remoteDeviceId=N}getSessionMetricsMessageCounts(){var N;return(N=this.sessionMetrics)===null||N===void 0?void 0:N.counts}getConnectionStatsInfo(){return st(this,void 0,void 0,function*(){const{peerConnection:N}=this;if(!N)return;const C=yield N.getStats(null),G=[];C.forEach(Re=>{G.push(Re)});const Z=G.find(Re=>Re.type==="transport");if(!Z)return;const pe=G.find(Re=>(Re.type==="candidate-pair"||Re.type==="candidatepair")&&Re.id===Z.selectedCandidatePairId);if(!pe)return;const Ue=G.find(Re=>Re.id===pe.localCandidateId),ve=G.find(Re=>Re.id===pe.remoteCandidateId);return Ue&&ve&&(Ue.address=Ue.address||Ue.ip,ve.address=ve.address||ve.ip,Ue.address!==void 0&&ve.address!==void 0)?{transport:Z,localCandidate:Ue,remoteCandidate:ve,candidatePair:pe}:void 0})}initializeChannels(N){this.heartbeatChannel=N.createDataChannel("heartbeat",vt),this.heartbeatChannel.binaryType="arraybuffer",this.latestTtlStreamChannel=N.createDataChannel("stream.latest-ttl",ze),this.latestTtlStreamChannel.binaryType="arraybuffer",this.reliableStreamChannel=N.createDataChannel("stream.reliable",qe),this.reliableStreamChannel.binaryType="arraybuffer",this.latestReliableStreamChannel=N.createDataChannel("stream.latest-reliable",pt),this.latestReliableStreamChannel.binaryType="arraybuffer",this.latestTryOnceStreamChannel=N.createDataChannel("stream.latest-try-once",dt),this.latestTryOnceStreamChannel.binaryType="arraybuffer",this.setupChannel(this.latestTtlStreamChannel),this.setupChannel(this.reliableStreamChannel),this.setupChannel(this.latestReliableStreamChannel),this.setupChannel(this.latestTryOnceStreamChannel)}getOffer(){return st(this,void 0,void 0,function*(){var N,C;const{gotOffer:G}=this,{peerConnection:Z,config:pe}=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 Ue=(N=this.config.remoteConfig)===null||N===void 0?void 0:N.sessionId;if(G)return void m.vF.debug("Failed to generate offer because gotOffer was already called.");if(this.gotOffer=!0,Ze(this.peerConnection))return void m.vF.debug("Failed to generate offer because the peer connection was inactive.");const ve=pe.baseConfig.track;Z.onicecandidate=()=>{this.hasIceCandidate=!0},Z.oniceconnectionstatechange=()=>st(this,void 0,void 0,function*(){const V=Z.iceConnectionState;if(V==="connected"||V==="completed"){const X=yield this.getConnectionStatsInfo(),ue=X?Wt(X):void 0;m.vF.info("ICE connection state changed to "+V,{sessionId:Ue,connectionStatsInfo:X,iceMode:ue}),ve==null||ve("ICE connection state change",{iceConnectionState:V,sessionId:Ue,connectionStatsInfo:X,iceMode:ue})}}),yield Z.setLocalDescription(yield Z.createOffer());const Re=Z.getConfiguration?Z.getConfiguration().iceTransportPolicy:"all",Se=new Date().getTime();for(;;){const V=new Date().getTime()-Se;if(V>this.connectTimeoutMs)return void m.vF.debug("Failed to generate offer because ICE gathering timed out.");if(V>this.iceGatheringTimeoutMs&&this.hasIceCandidate){m.vF.debug("ICE gathering partially completed; proceeding",{iceTransportPolicy:Re,waitTime:V}),ve==null||ve("ICE gathering partially completed",{sessionId:Ue,iceTransportPolicy:Re,waitTime:V});break}if(Z.iceGatheringState==="complete"){m.vF.debug("ICE gathering complete",{iceTransportPolicy:Re,waitTime:V}),ve==null||ve("ICE gathering completed",{sessionId:Ue,iceTransportPolicy:Re,waitTime:V});break}yield(0,o.c)(.1*r.p.second)}const fe=(C=this.iceServers)!==null&&C!==void 0?C:[];for(const V of fe)"credentialType"in V&&(V.credentialType=void 0);const p=JSON.stringify(fe),g=new re.Signal;return g.setPayload(JSON.stringify(Z.localDescription)),g.setSenderId(this.config.baseConfig.localPeerId),g.setReceiverId(this.config.baseConfig.remotePeerId),g.setIceServers(p),g.setIceTransportPolicy(Re!=null?Re:"all"),this.config.baseConfig.sessionType!==void 0?g.setSessionType(this.config.baseConfig.sessionType):g.setSessionType(re.SessionType.TELEOP),m.vF.debug("Sending offer signal with description",{description:g.getPayload()}),g})}getLanOffer(){return st(this,void 0,void 0,function*(){const{peerConnection:N,gotOffer:C}=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(C)return void m.vF.debug("Failed to generate offer because gotOffer was already called.");if(this.gotOffer=!0,Ze(this.peerConnection))return void m.vF.debug("Failed to generate offer because the peer connection was inactive.");yield N.setLocalDescription(yield N.createOffer());const G=new Date().getTime();for(;;){if(new Date().getTime()-G>this.iceGatheringTimeoutMs)return void m.vF.debug("Failed to generate offer because ICE gathering timed out.");if(N.iceGatheringState==="complete")break;yield(0,o.c)(.1*r.p.second)}const Z=N.localDescription;if(Z)return m.vF.debug("Sending LAN offer signal with description",{description:Z}),Z;m.vF.error("Failed to generate LAN offer description")})}handleLanAnswer(N){return st(this,void 0,void 0,function*(){const{peerConnection:C}=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 C.setRemoteDescription(N)})}getChannelFromLabel(N){switch(N){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(N,C){var G;let Z;try{Z=(0,Pe.encode)(JSON.stringify(C))}catch(pe){return void m.vF.warn("Failed to encode RTC message",{error:pe})}try{const pe=new Uint8Array(Z);N.send(pe.buffer),(G=this.sessionMetrics)===null||G===void 0||G.incrementLocalSent(C)}catch(pe){m.vF.warn("Failed to send message to channel",{error:pe,channel:N.label})}}channelNotRecognized(N){return N!==this.latestTtlStreamChannel&&N!==this.latestReliableStreamChannel&&N!==this.latestTryOnceStreamChannel&&N!==this.reliableStreamChannel}setupChannel(N){N.onmessage=C=>{var G,Z,pe,Ue;if(this.channelNotRecognized(N))return void m.vF.warn("Received message on unrecognized data channel.");let ve;if(C.data instanceof ArrayBuffer)try{if(je(C.data)){const Se=Et(C.data);return void this.receiveBinaryH264Message(N,Se)}if(Mt(C.data)){const Se=function(fe){if(!Mt(fe))throw new Error("Data is not a binary chunk message");const p=new DataView(fe);return{communicationType:"binary-chunk",chunkId:p.getUint32(4,!1),sequence:p.getUint32(8,!1),total:p.getUint32(12,!1),data:new Uint8Array(fe.slice(16))}}(C.data);return void this.receiveBinaryChunkMessage(N,Se)}const Re=(0,Pe.decode)(new Uint8Array(C.data));ve=JSON.parse(Re)}catch(Re){return void m.vF.warn("Received unparseable binary message on RTC stream data channel",{error:Re,channel:N.label})}else try{const Re=typeof C.data=="string"?C.data:(0,Pe.decode)(C.data instanceof ArrayBuffer?new Uint8Array(C.data):C.data);ve=JSON.parse(Re)}catch(Re){return void m.vF.warn("Received unparseable JSON message on RTC stream data channel",{error:Re,channel:N.label})}if(ve.communicationType==="message-chunk")this.receiveChannelMessageChunk(N,ve);else{const Re=ve;if(!((G=Re.payload)===null||G===void 0)&&G.h264VideoFrame){const Se={communicationType:"binary-h264",timestamp:((Z=Re.header)===null||Z===void 0?void 0:Z.created)||Date.now(),streamName:((Ue=(pe=Re.header)===null||pe===void 0?void 0:pe.stream)===null||Ue===void 0?void 0:Ue.streamName)||N.label,frame:Re.payload.h264VideoFrame};this.receiveBinaryH264Message(N,Se)}else this.receiveChannelMessage(N,Re)}},N.onerror=C=>{m.vF.warn("Channel error: "+C.error,{error:C.error,sessionId:this.getSessionId(),channelLabel:N.label})},N.onopen=()=>{m.vF.debug("Channel opened",{sessionId:this.getSessionId(),channelLabel:N.label})},N.onclose=()=>{const C={bufferedAmount:N.bufferedAmount,sessionId:this.getSessionId(),channelLabel:N.label};this.closeCalled===!1?m.vF.debug("Unexpected channel closed",C):m.vF.debug("Channel closed",C)}}receiveChannelMessage(N,C){var G;const{config:Z}=this,{remotePeerId:pe}=this.config.baseConfig;this.lastMessageTimestamp=new Date().getTime(),C=et(C),(G=this.sessionMetrics)===null||G===void 0||G.incrementLocalReceived(C),!this.handleSystemMessage(N,C)&&((N===this.latestTryOnceStreamChannel||N===this.latestTtlStreamChannel||N===this.latestReliableStreamChannel)&&!this.isLatestMessage(C)||Z.baseConfig.receive(pe,C))}receiveChannelMessageChunk(N,C){const G=this.reassemblyTable.get(C.id)||[];if(G.push(C),G.length===C.total){const Z=function(pe){const Ue=pe.sort((ve,Re)=>ve.seq<Re.seq?-1:1).map(ve=>ve.part).reduce((ve,Re)=>ve+Re);try{return JSON.parse(Ue)}catch{return void m.vF.warn("Could not reassemble RTC message chunks")}}(G);return Z&&this.receiveChannelMessage(N,Z),void this.reassemblyTable.delete(C.id)}this.reassemblyTable.set(C.id,G),this.reassemblyTableLastTimestamp.set(C.id,new Date().getTime())}receiveBinaryH264Message(N,C){const G={communicationType:"message",header:{stream:{entityId:this.config.baseConfig.remoteDeviceId||this.config.baseConfig.remotePeerId||"",streamName:C.streamName,streamType:"h264-video-frame"},created:C.timestamp,frameId:""},payload:{h264VideoFrame:C.frame}};this.receiveChannelMessage(N,G)}receiveBinaryChunkMessage(N,C){const G=C.chunkId,Z=this.binaryReassemblyTable.get(G)||new Map;if(Z.set(C.sequence,C.data),Z.size===C.total){let pe=0;for(const Re of Z.values())pe+=Re.length;const Ue=new Uint8Array(pe);let ve=0;for(let Re=0;Re<C.total;Re++){const Se=Z.get(Re);Se&&(Ue.set(Se,ve),ve+=Se.length)}try{if(je(Ue.buffer)){const Re=Et(Ue.buffer);this.receiveBinaryH264Message(N,Re)}}catch(Re){m.vF.warn("Failed to parse reassembled binary message",{error:Re,chunkId:G,channel:N.label})}return this.binaryReassemblyTable.delete(G),void this.binaryReassemblyTableLastTimestamp.delete(G)}this.binaryReassemblyTable.set(G,Z),this.binaryReassemblyTableLastTimestamp.set(G,new Date().getTime())}handleSystemMessage(N,C){var G,Z;const{config:pe}=this,{baseConfig:Ue}=pe,{remotePeerId:ve,remoteDeviceId:Re}=Ue;switch(C.header.stream.streamType){case"ping":return this.sendSystemMessage(N,{type:"pong",timestamp:I(C.payload.ping)}),!0;case"pong":{const Se=new Date().getTime()-I(C.payload.pong);return this.pingTimeMs=Se,q.aggregate("rtc-ping-time",Se,Object.assign({},Re?{deviceId:Re}:{})),!0}case"ping-v2":return this.sendPingV2(),!0;case"pong-v2":{const Se=I(C.payload.pongV2),fe=this.pingV2Map.get(Se.id);return(fe==null?void 0:fe.sent)!==Se.timestamp&&m.vF.warn("Pong timestamp doesn't match stored value",{currentEntry:fe,pong:Se}),this.pingV2Map.set(Se.id,{sent:Se.timestamp,received:new Date().getTime()}),!0}case"streams-info":{const{sessionMetrics:Se}=this,fe=(G=C.payload.streamsInfo)===null||G===void 0?void 0:G.timestamp;return!!fe&&(Se==null||Se.updateRemoteMessagesCounts(C),(Z=Ue.onStreamsInfoUpdate)===null||Z===void 0||Z.call(Ue,ve,fe),!0)}case"stream-control":return!0;default:return!1}}sendSystemMessage(N,C){var G;const{localUserId:Z,localPeerId:pe}=this.config.baseConfig;if(N.readyState!=="open")return;const Ue={entityId:Z!=null?Z:pe,streamName:"$."+C.type,streamType:C.type};let ve;switch(C.type){case"ping":ve={ping:new Date().getTime()};break;case"pong":ve={pong:C.timestamp};break;case"ping-v2":ve={pingV2:C.payload};break;case"pong-v2":ve={pongV2:C.payload};break;case"stream-control":ve={streamControl:C.streamControl};break;case"streams-info":ve={streamsInfo:(G=this.sessionMetrics)===null||G===void 0?void 0:G.getLocalStreamsInfo(new Date().getTime())}}this.sendOnChannel(N,bt(Ue,ve))}isLatestMessage(N){const C=mt(N.header.stream),G=(this.streamLatestTimestamp.get(C)||0)<=N.header.created;return G&&this.streamLatestTimestamp.set(C,N.header.created),G}}function wt(Ee){Ee&&clearInterval(Ee)}function zt(){m.vF.debug("forceGarbageCollection() triggered"),queueMicrotask(()=>{let Ee=document.createElement("img");Ee.src=window.URL.createObjectURL(new Blob([new ArrayBuffer(5e7)])),Ee.onerror=function(){window.URL.revokeObjectURL(this.src),Ee=null}})}function Gt(Ee){try{return Ee instanceof Error?`${Ee.name}: ${Ee.message}`:typeof Ee=="object"?JSON.stringify(Ee):String(Ee)}catch{return"Unknown error"}}function Nt(Ee){var N,C;return{userId:(N=Ee.getUserId())===null||N===void 0?void 0:N.getValue(),deviceId:(C=Ee.getDeviceId())===null||C===void 0?void 0:C.getValue(),organizationId:Ee.getOrganizationId(),id:Ee.getPeerId(),capabilities:[],capabilitySet:{}}}var $e=function(Ee,N,C,G){return new(C||(C=Promise))(function(Z,pe){function Ue(Se){try{Re(G.next(Se))}catch(fe){pe(fe)}}function ve(Se){try{Re(G.throw(Se))}catch(fe){pe(fe)}}function Re(Se){var fe;Se.done?Z(Se.value):(fe=Se.value,fe instanceof C?fe:new C(function(p){p(fe)})).then(Ue,ve)}Re((G=G.apply(Ee,N||[])).next())})};const xt=Ee=>Ee.map(N=>Object.assign(Object.assign(Object.assign({},N),N.username?{username:"<REDACTED>"}:null),N.credential?{credential:"<REDACTED>"}:null));class Lt{constructor(N){this.config=N,this.grpcCallDeadline=5*r.p.second,this.refreshIntervalDelayMs=2*r.p.second,this.iceServersTtl=30*r.p.minute,this.connections=[],this.localConnections=[],this.isConnectionInitiator=new WeakSet,this.isOutgoingConnection=new Set,this.peerDataChannelListeners=[],this.rtcInstancesConstructed=0,this.statsLoopsExecuted=0;const{refreshIntervalDelayMs:C}=this;this.refreshInterval=M({func:()=>$e(this,void 0,void 0,function*(){try{yield this.update()}catch(G){m.vF.warn("RTC refresh failed",{error:G})}}),delay:C})}send(N,C,G){const Z=this.getActiveConnection(N);Z?Z.isReady()?Z.send(C,G):m.vF.warn("Send called with unready connection."):m.vF.warn("Send called with no connection.")}controlRemoteStream(N,C){const G=this.getActiveConnection(N);G?G.isReady()?G.controlRemoteStream(C):m.vF.warn("controlRemoteStream called with unready connection."):m.vF.warn("controlRemoteStream called with no connection.")}getLocalPeer(){return $e(this,void 0,void 0,function*(){for(;!this.localPeer;)yield(0,o.c)(.1*r.p.second);return Nt(this.localPeer)})}connect(N,C){return $e(this,void 0,void 0,function*(){var G,Z,pe;if(this.config.lanOnlyMode===!0)throw new Error("connect method called in local only mode.");const{track:Ue,signalingClient:ve}=this.config,{localPeer:Re,receiveSignalStream:Se,iceServers:fe}=this;if(!Re||!Se||!fe)return void m.vF.warn("Connect called prior to local peer, receiveSignalStream, and ICE servers ready");if(this.getActiveConnection(N))return void m.vF.warn("Connect called for peer with existing connection.");if(this.isOutgoingConnection.has(N))return void m.vF.warn("Connect called for peer with an existing outgoing connection offer.");this.isOutgoingConnection.add(N);const p=function(Ae,Le,Ke){const{rtcIceTransportPolicies:at,rtcIceServerProtocol:gt,useAllServers:Ut}=Le||{},it=Ae.map(lt=>Object.assign(Object.assign({},lt),{urls:lt.urls.filter(_t=>{const At=(at===void 0||at.some(Yt=>ge(_t,Yt)))&&(gt===void 0||Fe(_t,gt));return At||m.vF.debug("Ignoring ICE server: "+_t,{organizationId:Ke}),At})})).filter(({urls:lt})=>lt.filter(_t=>_t).length>0);return Ut?it:[ae(it,"stun"),ae(it,"turn")].filter(lt=>lt!==void 0).map(lt=>I(lt))}(fe,C);m.vF.debug("Received ICE servers:",xt(fe)),m.vF.debug("Using ICE servers:",xt(p));const g=new Bt(yield this.createRTCPeerConnection(p),p,{baseConfig:{isOffer:!0,isLan:!1,receive:(Ae,Le)=>this.config.receive(Ae,Le),onStreamsInfoUpdate:this.config.onStreamsInfoUpdate?(Ae,Le)=>{var Ke,at;return(at=(Ke=this.config).onStreamsInfoUpdate)===null||at===void 0?void 0:at.call(Ke,Ae,Le)}:void 0,track:this.config.lanOnlyMode?void 0:this.config.track,localUserId:(G=Re.getUserId())===null||G===void 0?void 0:G.getValue(),localPeerId:Re.getPeerId(),remotePeerId:N,sessionType:this.config.sessionType},remoteConfig:{}},Ae=>this.onCustomDataChannel(N,Ae)),V=yield g.getOffer();if(!V)return m.vF.error("Failed to generate offer."),void this.isOutgoingConnection.delete(N);m.vF.debug("Sending offer."),Ue==null||Ue("Sending offer",(0,ye.x)(V));const X=new re.SendSignalRequest;X.setSignal(V);const ue=yield(()=>$e(this,void 0,void 0,function*(){try{return yield Ie.withDeadline(ve.sendSignal(X,yield this.getMetadata()),this.grpcCallDeadline)}catch(Ae){m.vF.warn("Error when sending signal",{error:Ae})}}))();if(!this.isOutgoingConnection.has(N))return void m.vF.debug("No offer set after receiving offer signal response.");m.vF.debug("Offer sent.");const be=(Z=ue==null?void 0:ue.getSessionId())===null||Z===void 0?void 0:Z.getValue(),Ce=(pe=ue==null?void 0:ue.getSessionCreatedTimestamp())===null||pe===void 0?void 0:pe.getValue();return be&&Ce?(g.setSessionId(be),g.setSessionCreatedTimestamp(Ce),this.isOutgoingConnection.delete(N),this.connections.push(g),this.isConnectionInitiator.add(g),this.setupHandlers(g),be):(m.vF.warn("No session ID or no session created timestamp on send signal response."),void this.isOutgoingConnection.delete(N))})}connectLan(N){return $e(this,void 0,void 0,function*(){var C,G;const Z=new Qe(N),pe=new Bt(yield this.createRTCPeerConnection([]),[],{baseConfig:{isOffer:!0,isLan:!0,receive:(Se,fe)=>this.config.receive(Se,fe),onStreamsInfoUpdate:this.config.onStreamsInfoUpdate?(Se,fe)=>{var p,g;return(g=(p=this.config).onStreamsInfoUpdate)===null||g===void 0?void 0:g.call(p,Se,fe)}:void 0,track:this.config.lanOnlyMode?void 0:this.config.track,localUserId:(G=(C=this.localPeer)===null||C===void 0?void 0:C.getUserId())===null||G===void 0?void 0:G.getValue(),localPeerId:"lan_client",remotePeerId:N}},Se=>this.onCustomDataChannel(N,Se)),Ue=yield pe.getLanOffer();if(!Ue)return m.vF.warn("Could not generate LAN offer"),!1;const ve=yield Z.postLanRtcOffer({offer:JSON.stringify(Ue)}),Re=new RTCSessionDescription(JSON.parse(ve.answer));return yield pe.handleLanAnswer(Re),this.localConnections.push(pe),this.isConnectionInitiator.add(pe),(0,ne.A)()})}getConnections(){return[...this.connections,...this.localConnections]}createCustomDataChannel(N,C,G,Z,pe){const Ue=this.getActiveConnection(N);if(Ue&&this.isConnectionInitiator.has(Ue)){const Re=Ue.peerConnection.createDataChannel("custom."+C,G);return Z&&(Re.binaryType="arraybuffer"),pe(N,Re),()=>{}}const ve=(Re,Se)=>{N===Re&&Se.label==="custom."+C&&pe(N,Se)};return this.peerDataChannelListeners.push(ve),()=>{this.peerDataChannelListeners=this.peerDataChannelListeners.filter(Re=>Re!==ve)}}onCustomDataChannel(N,C){this.peerDataChannelListeners.forEach(G=>G(N,C))}getConnectionStatus(N){if(this.isOutgoingConnection.has(N))return"connecting";const C=this.getActiveConnection(N);return C?C.isReady()?"connected":"connecting":"disconnected"}getConnectionStatsInfo(N){return $e(this,void 0,void 0,function*(){const C=this.getActiveConnection(N);if(C)return yield C.getConnectionStatsInfo()})}disconnect(N){return $e(this,void 0,void 0,function*(){const C=this.getActiveConnection(N);C&&(yield C.close(),this.connections=this.connections.filter(G=>G!==C),this.localConnections=this.localConnections.filter(G=>G!==C))})}getPeers(){return $e(this,void 0,void 0,function*(){if(this.config.lanOnlyMode)throw new Error("getPeers method cannot be used in local-only mode.");const{signalingClient:N}=this.config,C=yield(()=>$e(this,void 0,void 0,function*(){try{return yield Ie.withDeadline(N.getPeers(new re.GetPeersRequest,yield this.getMetadata()),this.grpcCallDeadline)}catch(pe){m.vF.warn("Error when getting peers",{error:pe})}}))();if(!C)return[];const G=C.getPeersList();if(!G)return[];const Z=pe=>{var Ue,ve;return(ve=(Ue=pe.getPeerCreatedTimestamp())===null||Ue===void 0?void 0:Ue.getValue())!==null&&ve!==void 0?ve:0};return G.sort((pe,Ue)=>Z(Ue)-Z(pe)).map(pe=>Nt(pe))})}getSessions(){return $e(this,void 0,void 0,function*(){if(this.config.lanOnlyMode)throw new Error("getPeers method cannot be used in local-only mode.");const{signalingClient:N}=this.config,C=yield(()=>$e(this,void 0,void 0,function*(){try{return yield Ie.withDeadline(N.getPeers(new re.GetPeersRequest,yield this.getMetadata()),this.grpcCallDeadline)}catch(pe){m.vF.warn("Error when getting peers",{error:pe})}}))();if(!C)return{};const G=C.getPeersList(),Z={};for(const pe of G)Z[pe.getPeerId()]=pe.getSessionIdsList();return Z})}getPing(N){const C=this.getActiveConnection(N);if(C)return C.getPing();m.vF.warn("Attempted to get ping time from inactive peer.")}getPingInfo(N){const C=this.getActiveConnection(N);if(C)return C.getPingInfo();m.vF.warn("Attempted to get ping time from inactive peer.")}getLastMessageTimestamp(N){const C=this.getActiveConnection(N);if(C)return C.getLastMessageTimestamp();m.vF.warn("Attempted to get last message time from inactive peer.")}getSessionMetricsMessageCounts(N){const C=this.getActiveConnection(N);if(C)return C.getSessionMetricsMessageCounts();m.vF.warn("Attempted to get session metrics counts from inactive peer.")}isReady(){if(this.config.lanOnlyMode)return!0;const{localPeer:N,receiveSignalStream:C,iceServers:G}=this;return!!(N&&C&&G)}shutdown(){return $e(this,void 0,void 0,function*(){yield this.refreshInterval.stop(),this.receiveSignalStream&&this.receiveSignalStream.cancel();const N=this.connections;this.connections=[],yield this.closeConnections(N);const C=this.localConnections;this.localConnections=[],yield this.closeConnections(C),this.isOutgoingConnection.clear(),this.peerDataChannelListeners=[];const{localPeer:G}=this;if(!G||this.config.lanOnlyMode)return;const{signalingClient:Z}=this.config;yield(()=>$e(this,void 0,void 0,function*(){try{const pe=new re.DeletePeerRequest;pe.setPeerId(G.getPeerId()),yield Ie.withDeadline(Z.deletePeer(pe,yield this.getMetadata()),this.grpcCallDeadline)}catch(pe){return void m.vF.warn("Error deleting local peer",{error:pe})}}))()})}createPeer(){return $e(this,void 0,void 0,function*(){if(this.config.lanOnlyMode)throw new Error("createPeer method cannot be used in local-only mode.");const{signalingClient:N}=this.config,C=yield(()=>$e(this,void 0,void 0,function*(){try{return yield Ie.withDeadline(N.createPeer(new re.CreatePeerRequest,yield this.getMetadata()),this.grpcCallDeadline)}catch(Z){const pe=Z;m.vF.debug("createPeer failed",{error:pe});const Ue=Gt(pe);throw new Error("Was not able to create peer: "+Ue)}}))(),G=C==null?void 0:C.getPeer();if(!G)throw new Error("Response did not provide peer.");return this.localPeer=G})}createReceiveSignalStream(){return $e(this,void 0,void 0,function*(){if(this.config.lanOnlyMode)throw new Error("createReceiveSignalStream method cannot be used in local-only mode.");const{signalingClient:N}=this.config,{localPeer:C,iceServers:G}=this;if(!C||!G)return;const{receiveSignalStream:Z}=this;Z&&Z.cancel();const pe=new re.ReceiveSignalStreamRequest;pe.setPeerId(C.getPeerId());const Ue=yield(()=>$e(this,void 0,void 0,function*(){try{return N.receiveSignalStream(pe,yield this.getMetadata({hasDeadline:!1}))}catch(ve){m.vF.debug("createReceiveSignalStream failed",{error:ve});const Re=Gt(ve);throw new Error("Unable to create receive signal stream: "+Re)}}))();if(!Ue)throw new Error("Response did not provide stream.");return Ue.on("data",ve=>$e(this,void 0,void 0,function*(){var Re,Se,fe,p;const g=ve.getSignal(),V=(Re=g==null?void 0:g.getSessionId())===null||Re===void 0?void 0:Re.getValue(),X=g==null?void 0:g.getSenderId(),ue=g==null?void 0:g.getReceiverId(),be=(Se=g==null?void 0:g.getSessionCreatedTimestamp())===null||Se===void 0?void 0:Se.getValue();if(!(g&&V&&X&&ue&&be))return void m.vF.warn("Received signal with missing information.");const Ce=this.getActiveConnection(X);if(Ce)if(Ce.getSessionId()!==V){if(m.vF.debug("Received signal: different session for a peer we're already connected to."),(Ce.getSessionCreatedTimestamp()||0)>be)return;const Ae=new Bt(yield this.createRTCPeerConnection(G),G,{baseConfig:{isOffer:!1,isLan:!1,receive:(Le,Ke)=>this.config.receive(Le,Ke),onStreamsInfoUpdate:this.config.onStreamsInfoUpdate?(Le,Ke)=>{var at,gt;return(gt=(at=this.config).onStreamsInfoUpdate)===null||gt===void 0?void 0:gt.call(at,Le,Ke)}:void 0,track:this.config.lanOnlyMode?void 0:this.config.track,localPeerId:C.getPeerId(),localUserId:(p=C.getUserId())===null||p===void 0?void 0:p.getValue(),remotePeerId:X},remoteConfig:{sessionId:V,sessionCreatedTimestamp:be}},Le=>this.onCustomDataChannel(X,Le));yield Ae.handleSignal(g),this.connections.push(Ae)}else m.vF.debug("Received signal: for an existing connection."),yield Ce.handleSignal(g);else{m.vF.debug("Received signal: new connection.");const Ae=new Bt(yield this.createRTCPeerConnection(G),G,{baseConfig:{isOffer:!1,isLan:!1,receive:(Le,Ke)=>this.config.receive(Le,Ke),onStreamsInfoUpdate:this.config.onStreamsInfoUpdate?(Le,Ke)=>{var at,gt;return(gt=(at=this.config).onStreamsInfoUpdate)===null||gt===void 0?void 0:gt.call(at,Le,Ke)}:void 0,track:this.config.lanOnlyMode?void 0:this.config.track,localPeerId:C.getPeerId(),localUserId:(fe=C.getUserId())===null||fe===void 0?void 0:fe.getValue(),remotePeerId:X},remoteConfig:{sessionId:V,sessionCreatedTimestamp:be}},Le=>this.onCustomDataChannel(X,Le));yield Ae.handleSignal(g),this.connections.push(Ae)}})),Ue.on("end",()=>{Ue.cancel(),this.receiveSignalStream=void 0}),Ue.on("error",ve=>{switch(ve.code){case se.StatusCode.CANCELLED:case se.StatusCode.UNAVAILABLE:case se.StatusCode.UNKNOWN:m.vF.debug("Receive signal stream error",{error:ve});break;case se.StatusCode.UNAUTHENTICATED:m.vF.warn("Receive signal stream error",{error:ve});break;default:m.vF.error("Receive signal stream error",{error:ve})}Ue.cancel(),this.receiveSignalStream=void 0}),this.receiveSignalStream=Ue})}createRTCPeerConnection(N){return $e(this,void 0,void 0,function*(){var C;const G=(C=this.config.alternateRTCPeerConnection)!==null&&C!==void 0?C:window.RTCPeerConnection;if(!G)throw function(){if(typeof navigator=="undefined")throw new Error("not a browser");const{userAgent:Z}=navigator;return Z.includes("Firefox/")?"Firefox":Z.includes("Edg/")?"Edge":Z.includes("Chrome/")?"Chrome":Z.includes("Safari/")?"Safari":Z.includes("MSIE/")||Z.includes("Trident/")?"IE":"Other"}()!=="Chrome"?new Error("WebRTC is not enabled. Please try again with the latest version of Google Chrome."):new Error("WebRTC is not enabled. Please ensure WebRTC is not disabled by ad blocking software.");this.rtcInstancesConstructed++,this.rtcInstancesConstructed%20||zt();try{return new G({iceServers:N})}catch(Z){throw m.vF.debug(`Failed to create RTCPeerConnection: ${this.rtcInstancesConstructed} total allocated`),Z}})}closeConnections(N){return $e(this,void 0,void 0,function*(){const C=yield We(N.map(G=>$e(this,void 0,void 0,function*(){yield G.close()})));for(const G of C)m.vF.warn("Request to close session failed",{error:G})})}getActiveConnection(N){return this.getConnections().find(C=>C.getRemotePeerId()===N&&C.isActive())}update(){return $e(this,void 0,void 0,function*(){var N;if(this.localConnections=this.localConnections.filter(p=>p.isActive()),this.config.lanOnlyMode)return;const{signalingClient:C}=this.config;if(!this.localPeer||!this.receiveSignalStream||!this.iceServers){const p=[];return this.localPeer||p.push(this.createPeer()),this.iceServers||p.push(this.updateIceServers()),yield Promise.all(p),void(this.receiveSignalStream||(yield this.createReceiveSignalStream()))}const[G,Z]=(pe=this.connections,Ue=p=>p.isActive(),pe.reduce((p,g,V,X)=>{const[ue,be]=p;return(Ue(g,V,X)?ue:be).push(g),p},[[],[]]));var pe,Ue;yield this.closeConnections(Z),this.connections=G,this.gatherConnectionStats().catch(p=>{m.vF.warn("Error calling gatherConnectionStats",{error:p})}),this.statsLoopsExecuted++;const{localPeer:ve}=this,Re=this.connections.filter(p=>p.getSessionId).map(p=>I(p.getSessionId()));ve.setSessionIdsList(Re);const Se=new re.RefreshPeerRequest;Se.setPeer(ve);try{yield Ie.withDeadline(C.refreshPeer(Se,yield this.getMetadata()),this.grpcCallDeadline)}catch(p){p instanceof se.RpcError&&p.code===se.StatusCode.NOT_FOUND?(m.vF.warn("Peer expired, creating new peer",{peerId:ve.getPeerId()}),yield this.reset()):m.vF.warn("Error calling RefreshPeer",{error:p})}const fe=yield this.getPeers();for(const p of this.connections)p.setRemoteDeviceId((N=fe.find(g=>g.id===p.getRemotePeerId()))===null||N===void 0?void 0:N.deviceId)})}gatherConnectionStats(){return $e(this,void 0,void 0,function*(){if(this.statsLoopsExecuted%10!=0||this.connections.length!==1)return;const N=yield this.connections[0].getConnectionStatsInfo(),C=N?Wt(N):void 0;C?q.setTag("rtc-connection-type",C):q.setTag("rtc-connection-type","unknown")})}reset(){return $e(this,void 0,void 0,function*(){yield this.closeConnections(this.connections),this.connections=[],this.isOutgoingConnection.clear(),yield this.createPeer(),yield this.createReceiveSignalStream()})}updateIceServers(){return $e(this,void 0,void 0,function*(){if(this.config.lanOnlyMode)return;const{iceServersLastUpdate:N,iceServersTtl:C}=this,G=new Date().getTime();if(!N||G-N>C)try{const Z=(yield Ie.withDeadline(this.config.signalingClient.getIceServers(new re.GetIceServersRequest,yield this.getMetadata()),this.grpcCallDeadline)).getIceServers();this.iceServers=JSON.parse(Z),this.iceServersLastUpdate=G}catch(Z){m.vF.warn("Error in updateIceServers",{error:Z})}})}setupHandlers(N){const{peerConnection:C}=N,G=N.getSessionCreatedTimestamp();C.onconnectionstatechange=()=>$e(this,void 0,void 0,function*(){const Z=C.connectionState;if(!G)return;const pe=N.getRemoteDeviceId();switch(Z){case"connected":q.aggregate("rtc-connect-time",new Date().getTime()-G,Object.assign({},pe?{deviceId:pe}:{}));break;case"failed":q.increment("rtc-connect-failed",Object.assign({},pe?{deviceId:pe}:{}))}})}getMetadata(){return $e(this,arguments,void 0,function*(N={}){if(this.config.lanOnlyMode)throw new Error("getMetadata method cannot be called in local-only mode");const{getToken:C}=this.config,{grpcCallDeadline:G}=this,{hasDeadline:Z=!0}=N,pe=Z?{deadline:(Date.now()+G).toString(10)}:null;try{const Ue=yield C();return Object.assign({authorization:Ue},pe)}catch(Ue){throw m.vF.error("getToken() failed",{error:Ue}),new Error("Cannot get authorization token")}})}}var Tt=__webpack_require__(3721),Qt=__webpack_require__(7197),Ht=function(Ee,N,C,G){return new(C||(C=Promise))(function(Z,pe){function Ue(Se){try{Re(G.next(Se))}catch(fe){pe(fe)}}function ve(Se){try{Re(G.throw(Se))}catch(fe){pe(fe)}}function Re(Se){var fe;Se.done?Z(Se.value):(fe=Se.value,fe instanceof C?fe:new C(function(p){p(fe)})).then(Ue,ve)}Re((G=G.apply(Ee,N||[])).next())})};class Ot{constructor(N,C){this.sentMessagesCounts=new Map,this.receivedMessagesCounts=new Map,this.sessionId=N,this.connection=C}incrementMessageSent(N){const C=mt(N.header.stream);this.sentMessagesCounts.set(C,(this.sentMessagesCounts.get(C)||0)+1)}incrementMessageReceived(N){const C=mt(N.header.stream);this.receivedMessagesCounts.set(C,(this.receivedMessagesCounts.get(C)||0)+1)}uploadMetrics(){return Ht(this,void 0,void 0,function*(){const{sessionId:N}=this,C=yield this.connection.peerConnection.getStats(),G={};C.forEach(pe=>G[pe.id]=pe),m.vF.debug("rtc-stats",Object.assign(Object.assign({},G),{sessionId:N}));const Z=[...new Set(Array.from(this.sentMessagesCounts.keys()).concat(Array.from(this.receivedMessagesCounts.keys())))].reduce((pe,Ue)=>{const ve=this.sentMessagesCounts.get(Ue),Re=this.receivedMessagesCounts.get(Ue);return Object.assign(Object.assign({},pe),{[Ue+"-sent"]:ve,[Ue+"-received"]:Re})},{sessionId:N});m.vF.debug("rtc-message-report",Z)})}}function jt(Ee,N){return mt(Ee)===mt(N)}var yt=function(Ee,N,C,G){return new(C||(C=Promise))(function(Z,pe){function Ue(Se){try{Re(G.next(Se))}catch(fe){pe(fe)}}function ve(Se){try{Re(G.throw(Se))}catch(fe){pe(fe)}}function Re(Se){var fe;Se.done?Z(Se.value):(fe=Se.value,fe instanceof C?fe:new C(function(p){p(fe)})).then(Ue,ve)}Re((G=G.apply(Ee,N||[])).next())})};class Vt{constructor(N,C){this.peerConnection=N,this.config=C,this.connectTimeoutMs=10*r.p.second,this.gatherIceTimeoutMs=5*r.p.second,this.pingUpdateTimeoutMs=2*r.p.second,this.streamLatestTimestamp=new Map,this.closeCalled=!1,this.connectCalled=!1,this.sentOffer=!1,this.receivedIceCandidate=!1;const{isOffer:G}=C;G?this.initializeChannels(N):N.ondatachannel=Z=>{switch(Z.channel.label){case"stream.latest-ttl":this.latestTtlStreamChannel=Z.channel;break;case"stream.reliable":this.reliableStreamChannel=Z.channel;break;case"stream.latest-reliable":this.latestReliableStreamChannel=Z.channel;break;case"stream.latest-try-once":this.latestTryOnceStreamChannel=Z.channel}this.setupChannel(Z.channel)},this.sessionMetrics=new Ot(this.getSessionId(),this)}connect(){return yt(this,void 0,void 0,function*(){if(this.connectCalled)return;this.connectCalled=!0,this.pingUpdateTimeout=setInterval(()=>{const{reliableStreamChannel:Z}=this;Z&&this.sendSystemMessage(Z,{type:"ping"})},this.pingUpdateTimeoutMs),this.connectTimeout=setTimeout(()=>yt(this,void 0,void 0,function*(){this.isReady()||(m.vF.warn("RTC connect timed out, closing connection"),yield this.close())}),this.connectTimeoutMs);const{peerConnection:N,config:{isOffer:C,sessionId:G}}=this;if(C){const Z=yield N.createOffer();yield N.setLocalDescription(Z)}C&&(this.gatherIceTimeout=setTimeout(()=>yt(this,void 0,void 0,function*(){this.sentOffer||(m.vF.warn("ICE gathering timed out"),this.receivedIceCandidate?(m.vF.warn("Attempting to connect with partial ICE candidate pool"),yield this.sendOffer()):yield this.close())}),this.gatherIceTimeoutMs),N.onicecandidate=Z=>yt(this,void 0,void 0,function*(){Z.candidate?this.receivedIceCandidate=!0:yield this.sendOffer()}),N.onicegatheringstatechange=()=>yt(this,void 0,void 0,function*(){N.iceGatheringState==="complete"&&(yield this.sendOffer())}),N.onnegotiationneeded=()=>{m.vF.debug("Negotiation needed",{sessionId:G})})})}handleSignal(N){return yt(this,void 0,void 0,function*(){const{peerConnection:C,config:{sessionId:G,sendSignal:Z}}=this,{description:pe}=JSON.parse(N.payload);if(m.vF.debug("Handling signal",{sessionId:G,description:JSON.stringify(pe)}),pe)if(C.signalingState!=="stable"||C.connectionState!=="connected")if(C.remoteDescription)m.vF.warn("Received SDP signal during negotiation when remote description is already set: "+JSON.stringify(N));else if(pe.type==="offer"){yield C.setRemoteDescription(pe);const Ue=yield C.createAnswer();yield C.setLocalDescription(Ue),yield Z({payload:JSON.stringify({description:Ue})})}else pe.type==="answer"&&(yield C.setRemoteDescription(pe));else m.vF.warn("Received SDP signal when signaling is stable and connected: "+JSON.stringify(N));else m.vF.warn("Received non-SDP signal: "+JSON.stringify(N))})}send(N,C){const G=this.getChannelFromLabel(C.channelLabel);G?this.sendOnChannel(G,N):m.vF.warn("Send called with unexpected channel label",{channelLabel:C.channelLabel})}controlRemoteStream(N){this.sendSystemMessage(I(this.reliableStreamChannel),{type:"stream-control",streamControl:N})}isActive(){return new Set(["new","connecting","connected"]).has(this.peerConnection.connectionState)}isReady(){const{peerConnection:N,latestTtlStreamChannel:C,reliableStreamChannel:G,latestTryOnceStreamChannel:Z}=this;return!!(G&&C&&Z)&&N.connectionState==="connected"&&G.readyState==="open"&&C.readyState==="open"&&Z.readyState==="open"}isClosed(){const{peerConnection:N,reliableStreamChannel:C,latestTryOnceStreamChannel:G,latestTtlStreamChannel:Z}=this;return!(N.connectionState!=="closed"||C!==void 0&&C.readyState!=="closed"||G!==void 0&&G.readyState!=="closed"||Z!==void 0&&Z.readyState!=="closed")}needsClosing(){const{peerConnection:N,latestTtlStreamChannel:C,reliableStreamChannel:G,latestTryOnceStreamChannel:Z}=this;if(this.isClosed())return!1;const pe=new Set(["closing","closed"]),Ue=ve=>ve&&pe.has(ve.readyState);return Ze(N)||Ue(C)||Ue(G)||Ue(Z)}close(){return yt(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(N){this.latestTtlStreamChannel=N.createDataChannel("stream.latest-ttl",ze),this.reliableStreamChannel=N.createDataChannel("stream.reliable",qe),this.latestReliableStreamChannel=N.createDataChannel("stream.latest-reliable",pt),this.latestTryOnceStreamChannel=N.createDataChannel("stream.latest-try-once",dt),this.setupChannel(this.latestTtlStreamChannel),this.setupChannel(this.reliableStreamChannel),this.setupChannel(this.latestReliableStreamChannel),this.setupChannel(this.latestTryOnceStreamChannel)}sendOffer(){return yt(this,void 0,void 0,function*(){if(this.sentOffer||(this.sentOffer=!0,Ze(this.peerConnection)))return;const{peerConnection:N,config:{sendSignal:C}}=this,G=yield N.createOffer();yield N.setLocalDescription(G);const Z={payload:JSON.stringify({description:G})};yield C(Z)})}getChannelFromLabel(N){switch(N){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(N,C){let G;try{G=(0,Pe.encode)(JSON.stringify(C))}catch(Z){return void m.vF.warn("Failed to encode RTC message",{error:Z})}try{N.send(G),this.sessionMetrics.incrementMessageSent(C)}catch(Z){m.vF.warn("Failed to send message to channel",{error:Z,channel:N.label})}}channelNotRecognized(N){return N!==this.latestTtlStreamChannel&&N!==this.latestReliableStreamChannel&&N!==this.latestTryOnceStreamChannel&&N!==this.reliableStreamChannel}setupChannel(N){N.onmessage=C=>{if(this.channelNotRecognized(N))return void m.vF.warn("Received message on unrecognized data channel.");let G;try{G=JSON.parse((0,Pe.decode)(C.data))}catch(Z){return void m.vF.warn("Received unparseable RTC message",{error:Z,channel:N.label})}if(this.lastMessageTimestamp=new Date().getTime(),G=et(G),this.sessionMetrics.incrementMessageReceived(G),!this.handleSystemMessage(N,G)){if(!this.hasCapabilities(G))return void m.vF.warn("Received RTC message that was not within the capability scope of the connection.");(N===this.latestTryOnceStreamChannel||N===this.latestTtlStreamChannel||N===this.latestReliableStreamChannel)&&!this.isLatestMessage(G)||this.config.receive(this.config.remotePeer.id,G)}},N.onerror=C=>{m.vF.warn("Channel error: "+C.error,{error:C.error,sessionId:this.getSessionId(),channelLabel:N.label})},N.onopen=()=>{m.vF.debug("Channel opened",{sessionId:this.getSessionId(),channelLabel:N.label})},N.onclose=()=>{const C={bufferedAmount:N.bufferedAmount,sessionId:this.getSessionId(),channelLabel:N.label};this.closeCalled===!1?m.vF.debug("Unexpected channel closed",C):m.vF.debug("Channel closed",C)}}handleSystemMessage(N,C){switch(C.header.stream.streamType){case"ping":return this.sendSystemMessage(N,{type:"pong",timestamp:I(C.payload.ping)}),!0;case"pong":{const G=new Date().getTime()-I(C.payload.pong);return this.pingTimeMs=G,q.aggregate("rtc-ping-time",G),!0}case"stream-control":return!0;default:return!1}}sendSystemMessage(N,C){if(N.readyState!=="open")return;const G={entityId:I(this.config.localPeer.deviceId||this.config.localPeer.userId),streamName:"$."+C.type,streamType:C.type};let Z;switch(C.type){case"ping":Z={ping:new Date().getTime()};break;case"pong":Z={pong:C.timestamp};break;case"stream-control":Z={streamControl:C.streamControl}}this.sendOnChannel(N,bt(G,Z))}hasCapabilities(N){var C,G;const{localPeer:Z,remotePeer:pe}=this.config,Ue=(C=Z.capabilitySet.streaming)===null||C===void 0?void 0:C.streams,ve=Ue&&Ue.some(fe=>fe.receive&&jt(fe.stream,N.header.stream)),Re=(G=pe.capabilitySet.streaming)===null||G===void 0?void 0:G.streams,Se=Re&&Re.some(fe=>fe.send&&jt(fe.stream,N.header.stream));return ve||Se}isLatestMessage(N){const C=mt(N.header.stream),G=(this.streamLatestTimestamp.get(C)||0)<=N.header.created;return G&&this.streamLatestTimestamp.set(C,N.header.created),G}}var De=function(Ee,N,C,G){return new(C||(C=Promise))(function(Z,pe){function Ue(Se){try{Re(G.next(Se))}catch(fe){pe(fe)}}function ve(Se){try{Re(G.throw(Se))}catch(fe){pe(fe)}}function Re(Se){var fe;Se.done?Z(Se.value):(fe=Se.value,fe instanceof C?fe:new C(function(p){p(fe)})).then(Ue,ve)}Re((G=G.apply(Ee,N||[])).next())})};class Ge{constructor(N){this.config=N,this.connections=[],this.connectingSessions=new Map,this.rtcInstancesConstructed=0,this.updateInterval=M({func:()=>De(this,void 0,void 0,function*(){try{yield this.update()}catch(C){m.vF.warn("RTC update failed",{error:C})}}),delay:250*r.p.millisecond}),this.localPeer=this.createPeer()}send(N,C,G){const Z=this.getActiveConnection(N);Z?Z.isReady()?Z.send(C,G):m.vF.warn("Attempted to send with an active connection to that peer which was not yet ready."):m.vF.warn("Attempted to send with no active connection to that peer.")}controlRemoteStream(N,C){const G=this.getActiveConnection(N);G?G.isReady()?G.controlRemoteStream(C):m.vF.warn("Attempted to control remote stream with an active connection to that peer which was not yet ready."):m.vF.warn("Attempted to control remote stream with no active connection to that peer.")}connect(N){return De(this,void 0,void 0,function*(){const C=yield this.getLocalPeer();if(this.getActiveConnection(N))return void m.vF.warn("Attempted to connect to peer with an already active connection.");let G;try{G=yield this.config.signalingClient.createSession(yield this.config.getToken(),{offerPeerId:C.id,answerPeerId:N})}catch(Z){(0,Tt.e)(Z,Qt.o,pe=>pe.statusCode===404),m.vF.warn("Attempted to connect to peer that does not exist.")}if(G)for(this.connectingSessions.set(G.id,new Date().getTime()),yield this.connectToSession(G);;)switch(yield(0,o.c)(.1),this.getConnectionStatus(N)){case"connecting":continue;case"connected":return G.id;case"disconnected":return}})}getConnectionStatus(N){const C=this.getActiveConnection(N);return C?C.isReady()?"connected":"connecting":"disconnected"}getIceMode(N){const C=this.getActiveConnection(N);if(C)return C.iceMode}disconnect(N){return De(this,void 0,void 0,function*(){const C=this.getActiveConnection(N);C&&(yield this.closeConnection(C))})}getLocalPeer(){return De(this,void 0,void 0,function*(){return yield this.localPeer})}getPeers(){return De(this,void 0,void 0,function*(){return yield this.config.signalingClient.getPeers(yield this.config.getToken())})}getPing(N){const C=this.getActiveConnection(N);if(C)return C.getPing();m.vF.warn("Attempted to get ping time from inactive peer.")}getLastMessageTimestamp(N){const C=this.getActiveConnection(N);if(C)return C.getLastMessageTimestamp();m.vF.warn("Attempted to get ping time from inactive peer.")}shutdown(){return De(this,void 0,void 0,function*(){yield this.updateInterval.stop();const N=this.connections;this.connections=[],yield this.closeConnections(N)})}closeConnection(N){return De(this,void 0,void 0,function*(){this.connectingSessions.delete(N.getSessionId()),yield N.close();try{yield this.config.signalingClient.deleteSession(yield this.config.getToken(),N.getSessionId())}catch(C){(0,Tt.e)(C,Qt.o,G=>G.statusCode===404)}})}getSessions(){return De(this,void 0,void 0,function*(){const N=yield this.getLocalPeer();return(yield this.config.signalingClient.getSessions(yield this.config.getToken())).filter(C=>C.offer.peer.id===N.id||C.answer.peer.id===N.id)})}createPeer(){return De(this,void 0,void 0,function*(){return yield this.config.signalingClient.createPeer(yield this.config.getToken(),{capabilitySet:this.config.capabilitySet||{}})})}createRTCPeerConnection(){return De(this,arguments,void 0,function*(N={}){const C=this.config.alternateRTCPeerConnection||RTCPeerConnection;this.rtcInstancesConstructed++,this.rtcInstancesConstructed%20||zt();try{return new C(Object.assign({iceServers:yield this.config.signalingClient.getIceServers(yield this.config.getToken())},N))}catch(G){throw m.vF.debug(`Failed to create RTCPeerConnection: ${this.rtcInstancesConstructed} total allocated`),G}})}closeConnections(N){return De(this,void 0,void 0,function*(){const C=yield We(N.map(G=>De(this,void 0,void 0,function*(){yield this.closeConnection(G)})));for(const G of C)m.vF.warn("Request to close session failed",{error:G})})}reset(){return De(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(N){return this.connections.find(C=>C.getRemotePeer().id===N&&C.isActive())}update(){return De(this,void 0,void 0,function*(){const N=yield this.getLocalPeer();try{yield this.config.signalingClient.refreshPeer(yield this.config.getToken(),N.id)}catch(C){(0,Tt.e)(C,Qt.o,G=>G.statusCode===404),m.vF.warn("Peer expired, creating new peer",{peerId:N.id}),yield this.reset()}yield this.handleSessions(yield this.getSessions())})}handleSessions(N){return De(this,void 0,void 0,function*(){yield this.syncConnectionsAndSessions(N);const C=N.map(G=>({session:G,connection:this.connections.find(Z=>Z.getSessionId()===G.id)}));yield Promise.all(C.map(G=>De(this,[G],void 0,function*({session:Z,connection:pe}){return yield this.maintainConnection(Z,pe)})))})}syncConnectionsAndSessions(N){return De(this,void 0,void 0,function*(){const C=new Set(N.map(pe=>pe.id)),G=pe=>C.has(pe.getSessionId())||this.connectingSessions.has(pe.getSessionId());this.connections=this.connections.filter(pe=>G(pe));const Z=this.connections.filter(pe=>!G(pe)||pe.needsClosing());yield Promise.all(Z.map(pe=>De(this,void 0,void 0,function*(){yield this.closeConnection(pe)})))})}maintainConnection(N,C){return De(this,void 0,void 0,function*(){const G=yield this.getLocalPeer(),Z=N.offer.peer.id===G.id;if(C){if(C.isReady())try{yield this.config.signalingClient.refreshSession(yield this.config.getToken(),N.id)}catch(pe){(0,Tt.e)(pe,Qt.o,Ue=>Ue.statusCode===404),m.vF.debug("Refresh session not found",{sessionId:N.id})}else if(C.isActive())try{yield this.consumeSignals(C)}catch(pe){m.vF.warn("Failed to ingest signals, closing connection",{error:pe}),yield this.closeConnection(C)}}else{if(Z)return;yield this.connectToSession(N)}})}connectToSession(N){return De(this,void 0,void 0,function*(){const C=yield this.getLocalPeer(),G=N.offer.peer.id===C.id,Z=yield this.createRTCPeerConnection(),pe=new Vt(Z,{localPeer:G?N.offer.peer:N.answer.peer,remotePeer:G?N.answer.peer:N.offer.peer,sessionId:N.id,isOffer:G,sendSignal:Ue=>this.sendSignal(N.id,Ue),receive:(Ue,ve)=>this.config.receive(Ue,ve)});if(this.connections.find(Ue=>Ue.getSessionId()===N.id))return m.vF.warn("connectToSession called on a session that already has a connection.",{sessionId:N.id}),void(yield pe.close());this.setupHandlers(pe),this.connections.push(pe);try{yield pe.connect()}catch(Ue){m.vF.warn("Failed to handle negotiation, closing connection",{error:Ue}),yield this.closeConnection(pe)}})}setupHandlers(N){const{peerConnection:C}=N,G=N.getSessionId();C.onconnectionstatechange=()=>De(this,void 0,void 0,function*(){const Z=this.connectingSessions.get(G);if(Z===void 0)return;const pe=C.connectionState;switch(Ze(C)&&this.connectingSessions.delete(G),pe){case"connected":{this.connectingSessions.delete(G);const Ue=new Date().getTime()-Z;q.aggregate("rtc-connect-time",Ue);break}case"failed":q.increment("rtc-connect-failed"),yield this.closeConnection(N)}})}consumeSignals(N){return De(this,void 0,void 0,function*(){let C=[];try{C=yield this.config.signalingClient.takeSignals(yield this.config.getToken(),N.getSessionId())}catch(G){(0,Tt.e)(G,Qt.o,Z=>Z.statusCode===404)}for(const G of C)yield N.handleSignal(G)})}sendSignal(N,C){return De(this,void 0,void 0,function*(){try{yield this.config.signalingClient.addSignals(yield this.config.getToken(),N,{signals:[C]})}catch(G){(0,Tt.e)(G,Qt.o,Z=>Z.statusCode===404)}})}}})(),__webpack_exports__})())})(dist);var distExports=dist.exports;const SessionTypes={UNKNOWN:0,TELEOP:1,PORT_FORWARD:2,OBSERVE:3,HEADLESS:4},SessionTypeConstants={...SessionTypes,Unknown:SessionTypes.UNKNOWN,Teleop:SessionTypes.TELEOP,PortForward:SessionTypes.PORT_FORWARD,Observe:SessionTypes.OBSERVE,Headless:SessionTypes.HEADLESS,unknown:SessionTypes.UNKNOWN,teleop:SessionTypes.TELEOP,portForward:SessionTypes.PORT_FORWARD,observe:SessionTypes.OBSERVE,headless:SessionTypes.HEADLESS},singleton=Symbol("RtcClientPool.instance");class RtcClientPool{constructor(t){_e(this,Jt,null);_e(this,"createClient");_e(this,"ttlMs");_e(this,"proxyHandler");_e(this,"proxyReceivers",new Map);_e(this,"teardownTimeout",null);_e(this,"dispatch",(t,n)=>{this.proxyReceivers.forEach(r=>r==null?void 0:r(t,n))});const{createClient:n,ttlMs:r=0}=t;this.createClient=n,this.ttlMs=Math.max(r,0),this.proxyHandler={get:(o,s,c)=>{switch(s){case"shutdown":return()=>this.releaseInstance(c);default:return Reflect.get(o,s,c)}}}}get isActive(){return this[singleton]!==null}get size(){return this.proxyReceivers.size}get(t){const n=new Proxy(this.allocate(),this.proxyHandler);return this.proxyReceivers.set(n,t!=null?t:null),n}allocate(){if(this[singleton])return this.teardownTimeout&&(clearTimeout(this.teardownTimeout),this.teardownTimeout=null),this[singleton];const t=this.createClient(this.dispatch);return this[singleton]=t,t}async teardown(){const t=this[singleton];if(!t){console.warn("singleton has already been shutdown!");return}try{await t.shutdown()}finally{this[singleton]=null}}async releaseInstance(t){return this.proxyReceivers.delete(t)?this.proxyReceivers.size!==0?!1:(!this.teardownTimeout&&Number.isFinite(this.ttlMs)&&(this.ttlMs===0?await this.teardown():this.teardownTimeout=setTimeout(()=>{this.teardown().catch(n=>console.error("teardown failed",{err:n})).finally(()=>this.teardownTimeout=null)},this.ttlMs)),!0):(console.warn("this instance has already been released!"),!1)}}Jt=singleton;const getToken=async()=>defined$1(Authentication.token,"Realtime when user isn't authorized"),EnumRtcClientPools={[SessionTypes.UNKNOWN]:new RtcClientPool({ttlMs:2500,createClient:e=>new distExports.RtcClient({signalingClient:new distExports.SignalingPromiseClient(exports.FORMANT_API_URL),getToken,sessionType:SessionTypes.UNKNOWN,receive:e})}),[SessionTypes.TELEOP]:new RtcClientPool({ttlMs:2500,createClient:e=>new distExports.RtcClient({signalingClient:new distExports.SignalingPromiseClient(exports.FORMANT_API_URL),getToken,sessionType:SessionTypes.TELEOP,receive:e})}),[SessionTypes.PORT_FORWARD]:new RtcClientPool({ttlMs:2500,createClient:e=>new distExports.RtcClient({signalingClient:new distExports.SignalingPromiseClient(exports.FORMANT_API_URL),getToken,sessionType:SessionTypes.PORT_FORWARD,receive:e})}),[SessionTypes.OBSERVE]:new RtcClientPool({ttlMs:2500,createClient:e=>new distExports.RtcClient({signalingClient:new distExports.SignalingPromiseClient(exports.FORMANT_API_URL),getToken,sessionType:SessionTypes.OBSERVE,receive:e})}),[SessionTypes.HEADLESS]:new RtcClientPool({ttlMs:2500,createClient:e=>new distExports.RtcClient({signalingClient:new distExports.SignalingPromiseClient(exports.FORMANT_API_URL),getToken,sessionType:SessionTypes.HEADLESS,receive:e})})},AppRtcClientPools={...EnumRtcClientPools,unknown:EnumRtcClientPools[SessionTypes.UNKNOWN],teleop:EnumRtcClientPools[SessionTypes.TELEOP],portForward:EnumRtcClientPools[SessionTypes.PORT_FORWARD],observe:EnumRtcClientPools[SessionTypes.OBSERVE],headless:EnumRtcClientPools[SessionTypes.HEADLESS]},defaultRtcClientPool=EnumRtcClientPools[SessionTypes.TELEOP],getRtcClientPool=e=>{const{sessionType:t}=e;return t?AppRtcClientPools[t]:defaultRtcClientPool};async function getPeers(){if(!Authentication.token)throw new Error("Not authenticated");const e=defaultRtcClientPool.get();try{return await e.getPeers()}finally{await e.shutdown()}}async function getRealtimeSessions(){if(!Authentication.token)throw new Error("Not authenticated");const e=defaultRtcClientPool.get();try{return await e.getSessions()}finally{await e.shutdown()}}async function getTelemetry(e,t,n,r,o,s){let c=e;Array.isArray(e)||(c=[e]);let l=t;return Array.isArray(t)||(l=[t]),(await(await fetch(`${exports.FORMANT_API_URL}/v1/queries/queries`,{method:"POST",body:JSON.stringify({deviceIds:c,end:r.toISOString(),names:l,start:n.toISOString(),tags:o,latestOnly:s}),headers:{"Content-Type":"application/json",Authorization:"Bearer "+Authentication.token}})).json()).items}async function patchDevice(e,t){if(!Authentication.token)throw new Error("Not authenticated");return await(await fetch(`${exports.FORMANT_API_URL}/v1/admin/devices/${e}`,{method:"PATCH",body:JSON.stringify(t),headers:{"Content-Type":"application/json",Authorization:"Bearer "+Authentication.token}})).json()}async function queryDevicesData(e){if(!Authentication.token)throw new Error("Not authenticated");return(await(await fetch(`${exports.FORMANT_API_URL}/v1/admin/devices/query`,{method:"POST",body:JSON.stringify(e),headers:{"Content-Type":"application/json",Authorization:"Bearer "+Authentication.token}})).json()).items}const isRtcPeer=e=>e!==void 0&&e.capabilities!==void 0&&e.capabilitySet!==void 0;var eventemitter3={exports:{}};(function(e){var t=Object.prototype.hasOwnProperty,n="~";function r(){}Object.create&&(r.prototype=Object.create(null),new r().__proto__||(n=!1));function o(u,d,h){this.fn=u,this.context=d,this.once=h||!1}function s(u,d,h,R,y){if(typeof h!="function")throw new TypeError("The listener must be a function");var Q=new o(h,R||u,y),f=n?n+d:d;return u._events[f]?u._events[f].fn?u._events[f]=[u._events[f],Q]:u._events[f].push(Q):(u._events[f]=Q,u._eventsCount++),u}function c(u,d){--u._eventsCount===0?u._events=new r:delete u._events[d]}function l(){this._events=new r,this._eventsCount=0}l.prototype.eventNames=function(){var d=[],h,R;if(this._eventsCount===0)return d;for(R in h=this._events)t.call(h,R)&&d.push(n?R.slice(1):R);return Object.getOwnPropertySymbols?d.concat(Object.getOwnPropertySymbols(h)):d},l.prototype.listeners=function(d){var h=n?n+d:d,R=this._events[h];if(!R)return[];if(R.fn)return[R.fn];for(var y=0,Q=R.length,f=new Array(Q);y<Q;y++)f[y]=R[y].fn;return f},l.prototype.listenerCount=function(d){var h=n?n+d:d,R=this._events[h];return R?R.fn?1:R.length:0},l.prototype.emit=function(d,h,R,y,Q,f){var S=n?n+d:d;if(!this._events[S])return!1;var U=this._events[S],b=arguments.length,T,F;if(U.fn){switch(U.once&&this.removeListener(d,U.fn,void 0,!0),b){case 1:return U.fn.call(U.context),!0;case 2:return U.fn.call(U.context,h),!0;case 3:return U.fn.call(U.context,h,R),!0;case 4:return U.fn.call(U.context,h,R,y),!0;case 5:return U.fn.call(U.context,h,R,y,Q),!0;case 6:return U.fn.call(U.context,h,R,y,Q,f),!0}for(F=1,T=new Array(b-1);F<b;F++)T[F-1]=arguments[F];U.fn.apply(U.context,T)}else{var w=U.length,B;for(F=0;F<w;F++)switch(U[F].once&&this.removeListener(d,U[F].fn,void 0,!0),b){case 1:U[F].fn.call(U[F].context);break;case 2:U[F].fn.call(U[F].context,h);break;case 3:U[F].fn.call(U[F].context,h,R);break;case 4:U[F].fn.call(U[F].context,h,R,y);break;default:if(!T)for(B=1,T=new Array(b-1);B<b;B++)T[B-1]=arguments[B];U[F].fn.apply(U[F].context,T)}}return!0},l.prototype.on=function(d,h,R){return s(this,d,h,R,!1)},l.prototype.once=function(d,h,R){return s(this,d,h,R,!0)},l.prototype.removeListener=function(d,h,R,y){var Q=n?n+d:d;if(!this._events[Q])return this;if(!h)return c(this,Q),this;var f=this._events[Q];if(f.fn)f.fn===h&&(!y||f.once)&&(!R||f.context===R)&&c(this,Q);else{for(var S=0,U=[],b=f.length;S<b;S++)(f[S].fn!==h||y&&!f[S].once||R&&f[S].context!==R)&&U.push(f[S]);U.length?this._events[Q]=U.length===1?U[0]:U:c(this,Q)}return this},l.prototype.removeAllListeners=function(d){var h;return d?(h=n?n+d:d,this._events[h]&&c(this,h)):(this._events=new r,this._eventsCount=0),this},l.prototype.off=l.prototype.removeListener,l.prototype.addListener=l.prototype.on,l.prefixed=n,l.EventEmitter=l,e.exports=l})(eventemitter3);var eventemitter3Exports=eventemitter3.exports;const EventEmitter=getDefaultExportFromCjs(eventemitter3Exports);class Manipulator{constructor(t,n){_e(this,"currentListeners",[]);_e(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){_e(this,"channel");_e(this,"requestIdToResponseMap",new Map);this.device=t,this.channel_name=n,this.timeout=r}addOpenListener(t){defined$1(this.channel,"channel not initalized").addOpenListener(t)}removeOpenListener(t){defined$1(this.channel,"channel not initalized").removeOpenListener(t)}addCloseListener(t){defined$1(this.channel,"channel not initalized").addCloseListener(t)}removeCloseListener(t){defined$1(this.channel,"channel not initalized").removeCloseListener(t)}addErrorListener(t){defined$1(this.channel,"channel not initalized").addErrorListener(t)}removeErrorListener(t){defined$1(this.channel,"channel not initalized").removeErrorListener(t)}}class BinaryRequestDataChannel extends RequestDataChannel{constructor(){super(...arguments);_e(this,"RESPONSE_SUCCESS_BYTE",0);_e(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 s=n.slice(16);if(s.length===0)throw new Error("Invalid response");this.requestIdToResponseMap.has(o)&&this.requestIdToResponseMap.set(o,s)})}async request(n){if(this.channel||await this.initialize(),!this.channel)throw new Error("Failed to create channel");const{channel:r,requestIdToResponseMap:o,timeout:s}=this;await r.waitTilReady();const c=this.generateBinaryId(),l=c.toString();o.set(l,!0),r.sendBinary(new Uint8Array([...c,...n]));const u=new Date().getTime();for(;new Date().getTime()<u+s;)if(await delay$1(50),o.has(l)){const d=o.get(l);if(d!==!0){o.delete(l);const h=d[0]===this.RESPONSE_SUCCESS_BYTE,R=d.slice(1);if(h)return R;throw console.error({name:"AdapterError",message:this.decoder.decode(R)}),new Error("Binary request datachannel adapter error")}}throw o.delete(l),console.error({name:"TimeoutError",message:`Request timed out after ${s/1e3} seconds`}),new Error("Binary request data channel request timed out")}}class TextRequestDataChannel extends RequestDataChannel{generateTextId(){return Math.random().toString(36).substring(2)+"-"+Math.random().toString(36).substring(2)}async initialize(){this.channel=await this.device.createCustomDataChannel(this.channel_name),this.channel.addListener(t=>{const n=JSON.parse(t),{id:r,data:o,error:s}=n;if(!r)throw new Error("Invalid response");if(!o&&!s)throw new Error("Invalid response");this.requestIdToResponseMap.has(r)&&this.requestIdToResponseMap.set(r,n)})}async request(t){if(this.channel||await this.initialize(),!this.channel)throw new Error("Failed to create channel");const{channel:n,requestIdToResponseMap:r,timeout:o}=this;await n.waitTilReady();const s=this.generateTextId();r.set(s,!0),n.send(JSON.stringify({id:s,data:t}));const c=new Date().getTime();for(;new Date().getTime()<c+o;)if(await delay$1(50),r.has(s)){const l=r.get(s);if(l!==!0){r.delete(s);const{data:u,error:d}=l;if(u)return u;if(d)throw console.error({name:"AdapterError",message:d}),new Error("Text request datachannel adapter error")}}throw r.delete(s),console.error({name:"TimeoutError",message:`Request timed out after ${o/1e3} seconds`}),new Error("Text request datachannel request timed out")}}class BaseDevice extends EventEmitter{constructor(){super(...arguments);_e(this,"rtcClient");_e(this,"remoteDevicePeerId",null);_e(this,"realtimeListeners",[]);_e(this,"connectionMonitorInterval");_e(this,"handleMessage",(n,r)=>{this.realtimeListeners.forEach(o=>o(n,r))})}stopConnectionMonitoring(){clearInterval(this.connectionMonitorInterval),this.connectionMonitorInterval=void 0}assertNotCancelled(n){if(n)throw new Error("Cancelled by deadline")}getRealtimeStatus(){if(this.rtcClient&&this.remoteDevicePeerId)return this.rtcClient.getConnectionStatus(this.remoteDevicePeerId);throw new Error("Realtime connection hasn't been started")}getRealtimePingInfo(){if(this.rtcClient&&this.remoteDevicePeerId)return this.rtcClient.getPingInfo(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")}addRealtimeListener(n){this.realtimeListeners.push(n)}removeRealtimeListener(n){const r=this.realtimeListeners.indexOf(n);if(r===-1)throw new Error("Could not find realtime listener to remove");this.realtimeListeners.splice(r,1)}async getRealtimeManipulators(){var o;const n=await this.getConfiguration(),r=[];for(const s of(o=n.teleop.rosStreams)!=null?o:[])s.topicType=="sensor_msgs/JointState"&&r.push(new Manipulator(this,{currentJointStateStream:{name:s.topicName},plannedJointStateStream:s.plannedTopic?{name:s.plannedTopic}:void 0,planValidStream:s.planValidTopic?{name:s.planValidTopic}:void 0,endEffectorStream:s.endEffectorTopic?{name:s.endEffectorTopic}:void 0,endEffectorLinkName:s.endEffectorLinkName,baseReferenceFrame:s.baseReferenceFrame,localFrame:s.localFrame}));return r}async getRealtimeVideoStreams(){var o,s,c,l,u,d;const n=await this.getConfiguration(),r=[];for(const h of(s=(o=n.teleop)==null?void 0:o.hardwareStreams)!=null?s:[])h.rtcStreamType==="h264-video-frame"&&r.push({name:h.name});for(const h of(l=(c=n.teleop)==null?void 0:c.rosStreams)!=null?l:[])h.topicType=="formant/H264VideoFrame"&&r.push({name:h.topicName}),(h.topicType==="sensor_msgs/Image"||h.topicType==="sensor_msgs/CompressedImage")&&h.encodeVideo&&r.push({name:h.topicName});for(const h of(d=(u=n.teleop)==null?void 0:u.customStreams)!=null?d:[])h.rtcStreamType==="h264-video-frame"&&r.push({name:h.name});return r}createCustomRequestDataChannel(n,r=3e3){return new TextRequestDataChannel(this,n,r)}createCustomBinaryRequestDataChannel(n,r=3e3){return new BinaryRequestDataChannel(this,n,r)}async startListeningToRealtimeVideo(n){const r=defined$1(this.rtcClient,"Realtime connection has not been started"),o=await this.getRemotePeer();r.controlRemoteStream(defined$1(o).id,{streamName:n.name,enable:!0,pipeline:"rtc"})}async stopListeningToRealtimeVideo(n){const r=defined$1(this.rtcClient,"Realtime connection has not been started"),o=await this.getRemotePeer();r.controlRemoteStream(defined$1(o).id,{streamName:n.name,enable:!1,pipeline:"rtc"})}async startListeningToRealtimeDataStream(n){const r=defined$1(this.rtcClient,"Realtime connection has not been started"),o=await this.getRemotePeer();r.controlRemoteStream(defined$1(o).id,{streamName:n.name,enable:!0,pipeline:"rtc"})}async stopListeningToRealtimeDataStream(n){const r=defined$1(this.rtcClient,"Realtime connection has not been started"),o=await this.getRemotePeer();r.controlRemoteStream(defined$1(o).id,{streamName:n.name,enable:!1,pipeline:"rtc"})}async enableRealtimeTelemetryPriorityIngestion(n){const r=defined$1(this.rtcClient,"Realtime connection has not been started"),o=await this.getRemotePeer();r.controlRemoteStream(defined$1(o).id,{streamName:n,enablePriorityUpload:!0,pipeline:"telemetry"})}async disableRealtimeTelemetryPriorityIngestion(n){const r=defined$1(this.rtcClient,"Realtime connection has not been started"),o=await this.getRemotePeer();r.controlRemoteStream(defined$1(o).id,{streamName:n,enablePriorityUpload:!1,pipeline:"telemetry"})}async changeStreamAudioType(n,r){const o=defined$1(this.rtcClient,"Realtime connection has not been started"),s=await this.getRemotePeer();o.controlRemoteStream(defined$1(s).id,{streamName:n,setAudioFormat:r})}async createCustomDataChannel(n,r){const o=defined$1(this.rtcClient,"Realtime connection has not been started"),s=await this.getRemotePeer(),c=await new Promise(l=>{o.createCustomDataChannel(defined$1(s).id,n,{ordered:!0,...r},!1,(u,d)=>{const h=new DataChannel(d);l(h)})});return await c.waitTilReady(),c}async sendRealtimeMessage(n,r={channelLabel:"stream.reliable"}){const o=defined$1(this.rtcClient,"Realtime connection has not been started"),s=await this.getRemotePeer();o.send(defined$1(s).id,n,r)}async getRealtimeAudioStreams(){var o,s,c,l,u,d;const n=await this.getConfiguration(),r=[];for(const h of(s=(o=n.teleop)==null?void 0:o.hardwareStreams)!=null?s:[])h.rtcStreamType==="audio-chunk"&&r.push({name:h.name});for(const h of(l=(c=n.teleop)==null?void 0:c.rosStreams)!=null?l:[])h.topicType=="audio_common_msgs/AudioData"&&r.push({name:h.topicName});for(const h of(d=(u=n.teleop)==null?void 0:u.customStreams)!=null?d:[])h.rtcStreamType==="audio-chunk"&&r.push({name:h.name});return r}}class Device extends BaseDevice{constructor(t,n,r,o){super(),this.id=t,this.name=n,this.organizationId=r,this.tags=o}async getLatestTelemetry(){return(await(await fetch(`${exports.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(t=!1){let n=await fetch(`${exports.FORMANT_API_URL}/v1/admin/devices/${this.id}`,{method:"GET",headers:{"Content-Type":"application/json",Authorization:"Bearer "+Authentication.token}});const r=await n.json();if(!r.state.reportedConfiguration)throw new Error("Device has no configuration, has it ever been turned on?");const o=t?r.desiredConfigurationVersion:r.state.reportedConfiguration.version;return n=await fetch(`${exports.FORMANT_API_URL}/v1/admin/devices/${this.id}/configurations/${o}`,{method:"GET",headers:{"Content-Type":"application/json",Authorization:"Bearer "+Authentication.token}}),(await n.json()).document}async getAgentVersion(){var r;const n=await(await fetch(`${exports.FORMANT_API_URL}/v1/admin/devices/${this.id}`,{method:"GET",headers:{"Content-Type":"application/json",Authorization:"Bearer "+Authentication.token}})).json();return(r=n==null?void 0:n.state)==null?void 0:r.agentVersion}async getFileUrl(t){return(await(await fetch(`${exports.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}async startRealtimeConnection(t={}){if(console.debug(`${new Date().toISOString()} :: Connection start requested`),this.rtcClient&&this.connectionMonitorInterval!==void 0)throw new Error(`Already created realtime connection to device ${this.id}`);this.rtcClient&&console.warn("overwriting existing rtcClient due to missing connectionMonitorInterval");const{sessionType:n,deadlineMs:r=1e4,maxConnectRetries:o=3}=typeof t=="number"?{sessionType:t}:t,c=getRtcClientPool({sessionType:n}).get(this.handleMessage);let l=!1;const u=new Promise((h,R)=>setTimeout(()=>{l=!0,R(new Error("Connection timed out: the connection could not be finalized in time, possibly due to network issues or misconfigured settings."))},r)),d=async()=>{if("isReady"in c)for(;!c.isReady();)this.assertNotCancelled(l),await delay$1(100);const h=await this.getRemoteDevicePeerId(c);this.assertNotCancelled(l);let R;for(let Q=0;Q<o&&(R=await c.connect(h),!R);Q++)delay$1(100),this.assertNotCancelled(l);if(!R)throw new Error(`Session could not be created: exhausted ${o} retries`);let y=0;for(;!l&&c.getConnectionStatus(h)!=="connected";)await delay$1(100),y+=1;return this.assertNotCancelled(l),console.debug(`${new Date().toISOString()} :: Connection completed after ${y} retries`),h};return Promise.race([d(),u]).then(h=>{this.remoteDevicePeerId=h,this.initConnectionMonitoring(),this.rtcClient=c,this.emit("connect")}).catch(h=>{throw console.debug(`${new Date().toISOString()} :: Connection failed: %o`,h),this.remoteDevicePeerId=null,c.shutdown().catch(R=>{console.error("rtcClient cannot shutdown: %o",R)}),this.emit("connection_failed",h),h})}async getRemoteDevicePeerId(t){const r=(await t.getPeers()).find(o=>o.deviceId===this.id);if(!isRtcPeer(r))throw new Error("Cannot find peer, is the robot offline?");return r.id}initConnectionMonitoring(){this.connectionMonitorInterval=setInterval(async()=>{let t=!1;if(this.rtcClient){const r=this.rtcClient.getConnections().find(o=>o.getRemotePeerId()===this.remoteDevicePeerId&&o.isActive());(r===void 0||!r.isReady())&&(console.debug(`${new Date().toISOString()} :: data channel closed`),t=!0)}(!this.rtcClient||!this.remoteDevicePeerId||await this.rtcClient.getConnectionStatsInfo(this.remoteDevicePeerId)===void 0||t)&&(this.emit("disconnect"),this.stopRealtimeConnection().catch(n=>{console.error(n)}))},1e3)}async getRemotePeer(){const n=(await defined$1(this.rtcClient,"Realtime connection has not been started").getPeers()).find(r=>r.deviceId===this.id);return defined$1(n,"Could not find remote peer for device "+this.id)}async stopRealtimeConnection(){let t=!1;if(this.rtcClient){this.stopConnectionMonitoring(),this.remoteDevicePeerId?(await this.rtcClient.disconnect(this.remoteDevicePeerId),this.remoteDevicePeerId=null):t=!0;try{await this.rtcClient.shutdown()}finally{this.rtcClient=void 0}}if(t)throw new Error(`Realtime connection hasn't been started for ${this.id}`)}async isInRealtimeSession(){const t=await getPeers(),n=await getRealtimeSessions(),r=t.find(o=>o.deviceId===this.id);return r?n[r.id].length>0:!1}async getAvailableCommands(t=!0){return(await(await fetch(`${exports.FORMANT_API_URL}/v1/admin/command-templates/`,{method:"GET",headers:{"Content-Type":"application/json",Authorization:"Bearer "+Authentication.token}})).json()).items.filter(o=>t?!0:o.enabled)}async sendCommand(t,n,r,o,s){var R;const l=(await this.getAvailableCommands(!1)).find(y=>s?y.id===s:y.name===t);if(!l)throw new Error(`Could not find command with name "${t}"`);let u="";n===void 0?l.parameterEnabled&&l.parameterValue&&(u=l.parameterValue):u=n;let d={value:u,scrubberTime:(r||new Date).toISOString(),meta:{...l.parameterMeta,...o}};return await fetch(`${exports.FORMANT_API_URL}/v1/admin/commands`,{method:"POST",body:JSON.stringify({commandTemplateId:l.id,organizationId:this.organizationId,deviceId:this.id,command:l.command,parameter:d,userId:(R=Authentication.currentUser)==null?void 0:R.id}),headers:{"Content-Type":"application/json",Authorization:"Bearer "+Authentication.token}})}async getCommand(t){return await fetch(`${exports.FORMANT_API_URL}/v1/admin/commands/${t}`,{method:"GET",headers:{"Content-Type":"application/json",Authorization:"Bearer "+Authentication.token}})}async createCaptureStream(t){const r=await(await fetch(`${exports.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,s,c,l){if(s!==void 0||c!==void 0)throw new Error("Limit and offset are not supported in this method");return await getTelemetry(this.id,t,n,r,o,l)}async queryEvents(t){if(t.deviceIds)throw new Error("Cannot filter multiple devices via Device class");return t.deviceIds=[this.id],queryEvents(t)}async getTelemetryStreams(){var l,u;const t=await this.getConfiguration(),n=await fetch(`${exports.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(u=(l=t.telemetry)==null?void 0:l.streams)==null||u.forEach(d=>{d.disabled!==!0&&r.push(d.name),d.onDemand===!0&&o.push(d.name)}),console.log(o),(await n.json()).items.filter(d=>!r.includes(d)).map(d=>({name:d,onDemand:o.includes(d)}))}async createInterventionRequest(t,n,r,o){return await(await fetch(`${exports.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(`${exports.FORMANT_API_URL}/v1/admin/intervention-responses`,{method:"POST",body:JSON.stringify({interventionId:t,interventionType:n,data:r}),headers:{"Content-Type":"application/json",Authorization:"Bearer "+Authentication.token}})).json()}async getAnnotationCount(t,n){return await getAnnotationCount({...t,deviceIds:[this.id]},n)}async getAnnotationCountByIntervals(t,n,r){return await getAnnotationCountByIntervals({...t,deviceIds:[this.id]},n,r)}async eventsCounter(t,n,r,o,s){return await eventsCounter(t,n,r,o,{...s,deviceIds:[this.id]})}async createShareLink(t,n){return t.scope.deviceIds=[this.id],await createShareLink(t,n)}}_e(Device,"createDevice",createDevice),_e(Device,"patchDevice",patchDevice),_e(Device,"getDevicesData",getDevicesData),_e(Device,"queryDevicesData",queryDevicesData),_e(Device,"disableDevice",disableDevice);class PeerDevice extends BaseDevice{constructor(n){super();_e(this,"id");_e(this,"telemetryStreamActive",!1);_e(this,"streamTelemetry",{});this.peerUrl=n}async getLatestTelemetry(){this.telemetryStreamActive||this.subscribeToTelemetry();const n=this.streamTelemetry;return Object.entries(n).map(([o,s])=>({deviceId:this.id,streamName:o,streamType:"json",currentValue:s,currentValueTime:s.timestamp,tags:{}}))}async getTelemetry(n,r,o,s,c,l,u){if(Array.isArray(n))throw new Error("Multiple stream names not supported");if(s)throw new Error("Tags not supported");if(u&&c===void 0)c=1;else if(u&&c!==void 0)throw new Error("latestOnly and limit cannot be used together");let d=`${this.peerUrl}/v1/querydatapoints?stream_name=${n}&start=${r.toISOString()}&end=${o.toISOString()}`;c!=null&&c>0&&(d+=`&limit=${c}`),l!=null&&l>=0&&(d+=`&offset=${l}`);const R=await(await fetch(d)).json(),y=[];for(const Q of R.results){const f=parseInt(Q.timestamp),S=Q.tags.data_type;delete Q.tags.data_type,y.push({deviceId:this.id,name:Q.stream,points:[[f,this.getPointPayload(S,Q)]],tags:Q.tags,type:S})}return y.reverse()}async queryEvents(n){const r=["id","viewed","keyword","message","sort","eventTypes","notificationEnabled","userIds","annotationTemplateIds","disableNullMatches","severities","deviceIds","names","types","tags","notNames"];this.checkKeysAndThrow(n,r);let o=`${this.peerUrl}/v1/queryevents?start=${n.start}&end=${n.end}`;n.count!=null&&n.count>0&&(o+=`&limit=${n.count}`),n.offset!=null&&n.offset>=0&&(o+=`&offset=${n.offset}`);const c=await(await fetch(o)).json(),l=[];for(const u of c.results){const d=parseInt(u.timestamp),h={deviceId:this.id,time:new Date(d).toISOString(),message:u.message,notificationEnabled:u.notificationEnabled,type:u.type,tags:u.tags};u.id!==""&&(h.id=u.id),u.type!==""&&(h.type=u.type),u.streamName!==""&&(h.streamName=u.streamName),u.streamType!==""&&(h.streamType=u.streamType),u.severity!==""&&(h.severity=u.severity.toLowerCase()),u.tags&&(h.tags=u.tags),u.endTimestamp!=="0"&&(h.endTime=new Date(parseInt(u.endTimestamp)).toISOString()),l.push(h)}return l.reverse()}checkKeysAndThrow(n,r){const o=r.filter(s=>s in n);if(o.length>0)throw new Error(`Filters not currently supported: ${o.join(", ")}.`)}getPointPayload(n,r){switch(n){case"numeric":return r.numeric.value;case"numeric set":return r.numericSet.numerics;case"text":return r.text.value;case"json":return r.json.value;case"bitset":const o=[],s=[];for(const c of r.bitset.bits)o.push(c.key),s.push(c.value);return{keys:o,values:s};case"location":return r.location;case"health":return r.health;case"battery":return r.battery;default:return{}}}subscribeToTelemetry(){this.telemetryStreamActive=!0;let n=0;const r=new XMLHttpRequest;r.responseType="text",r.addEventListener("error",o=>{this.handleXHRError("error")}),r.addEventListener("abort",o=>{this.handleXHRError("abort")}),r.addEventListener("timeout",o=>{this.handleXHRError("timeout")}),r.addEventListener("readystatechange",o=>{r.readyState===XMLHttpRequest.DONE&&this.handleXHRError("closed")}),r.addEventListener("progress",o=>{const s=o.loaded,c=s-n;n=s,r.responseText.substr(-c).split(`
128
128
  `).forEach(d=>{var h;if(d.length>0){const R=JSON.parse(d);if((h=R.result)!=null&&h.datapoint){const y=R.result.datapoint,Q=y.stream;delete y.stream,this.streamTelemetry[Q]=y}}})}),r.open("POST",`${this.peerUrl}/v1/telemetry`),r.send()}handleXHRError(n){console.warn(`Telemetry stream ended: ${n}`),this.telemetryStreamActive=!1}async getDeviceId(){return(await(await fetch(`${this.peerUrl}/v1/config`)).json()).configuration.id}async getConfiguration(){return(await(await fetch(`${this.peerUrl}/v1/config`)).json()).configuration.document}async getViews(){return(await(await fetch(`${this.peerUrl}/v1/views`)).json()).views}async startRealtimeConnection(n){if(console.debug(`${new Date().toISOString()} :: Connection start requested`),this.rtcClient&&this.connectionMonitorInterval!==void 0)throw new Error(`Already created realtime connection to device ${this.id}`);this.rtcClient&&console.warn("overwriting existing rtcClient due to missing connectionMonitorInterval");const r=new distExports.RtcClient({lanOnlyMode:!0,receive:this.handleMessage,sessionType:n});for(await r.connectLan(this.peerUrl);r.getConnectionStatus(this.peerUrl)!=="connected";)await delay$1(100);this.rtcClient=r,this.initConnectionMonitoring()}initConnectionMonitoring(){this.connectionMonitorInterval=setInterval(async()=>{let n=!1;this.rtcClient&&this.rtcClient.getConnectionStatus(this.peerUrl)!=="connected"&&(console.debug(`${new Date().toISOString()} :: data channel closed`),n=!0),(!this.rtcClient||n)&&(this.emit("disconnect"),this.stopRealtimeConnection().catch(r=>{console.error(r)}))},1e3)}async getRemotePeer(){return{id:this.peerUrl,organizationId:"",deviceId:this.id,capabilities:[],capabilitySet:{}}}async stopRealtimeConnection(){let n=!1;if(this.rtcClient){this.stopConnectionMonitoring(),this.id?(await this.rtcClient.disconnect(this.id),this.remoteDevicePeerId=null):n=!0;try{await this.rtcClient.shutdown()}finally{this.rtcClient=void 0}}if(n)throw new Error(`Realtime connection hasn't been started for ${this.id}`)}async getCommandMetadata(){return(await fetch(`${this.peerUrl}/v1/commands`)).json()}async sendCommand(n,r,o,s){const c={value:r,scrubberTime:(o||new Date).toISOString(),meta:s};return await fetch(`${this.peerUrl}/v1/enqueue-command`,{method:"POST",body:JSON.stringify({command:n,parameter:c}),headers:{"Content-Type":"application/json"}})}}async function addDeviceToFleet(e,t){if(!Authentication.token)throw new Error("Not authenticated");return await(await fetch(`${exports.FORMANT_API_URL}/v1/admin/devices/${e}`,{method:"PATCH",body:JSON.stringify({fleetId:t}),headers:{"Content-Type":"application/json",Authorization:"Bearer "+Authentication.token}})).json()}async function aggregateTelemetry(e){if(!Authentication.token)throw new Error("Not authenticated");return(await(await fetch(`${exports.FORMANT_API_URL}/v1/queries/queries`,{method:"POST",body:JSON.stringify(e),headers:{"Content-Type":"application/json",Authorization:"Bearer "+Authentication.token}})).json()).aggregates}async function deleteFleet(e){if(!Authentication.token)throw new Error("Not authenticated");await fetch(`${exports.FORMANT_API_URL}/v1/admin/fleets/${e}`,{method:"DELETE",headers:{"Content-Type":"application/json",Authorization:"Bearer "+Authentication.token}})}async function getAnalyticStreams(){if(!Authentication.token)throw new Error("Not authenticated");return(await(await fetch(`${exports.FORMANT_API_URL}/v1/queries/analytics/streams`,{method:"GET",headers:{"Content-Type":"application/json",Authorization:"Bearer "+Authentication.token}})).json()).items}async function getAnalyticsModules(){if(!Authentication.token)throw new Error("Not authenticated");return(await(await fetch(`${exports.FORMANT_API_URL}/v1/admin/analytics-modules`,{method:"GET",headers:{"Content-Type":"application/json",Authorization:"Bearer "+Authentication.token}})).json()).items}async function getAnalyticsRows(e){if(!Authentication.token)throw new Error("Not authenticated");return await(await fetch(`${exports.FORMANT_API_URL}/v1/queries/analytics/rows`,{method:"POST",body:JSON.stringify(e),headers:{"Content-Type":"application/json",Authorization:"Bearer "+Authentication.token}})).json()}async function queryDevices(e){if(!Authentication.token)throw new Error("Not authenticated");return(await(await fetch(`${exports.FORMANT_API_URL}/v1/admin/devices/query`,{method:"POST",body:JSON.stringify(e),headers:{"Content-Type":"application/json",Authorization:"Bearer "+Authentication.token}})).json()).items.map(r=>new Device(r.id,r.name,r.organizationId,r.tags))}async function getCurrentGroup(){if(!Authentication.token)throw new Error("Not authenticated");let e=new URLSearchParams("");typeof window!="undefined"&&window.location&&(e=new URLSearchParams(window.location.search));const t=e.get("group");if(t===null||t.trim()==="")return;const n=await fetch(`${exports.FORMANT_API_URL}/v1/admin/groups/`+t,{headers:{"Content-Type":"application/json",Authorization:"Bearer "+Authentication.token}}),{tagKey:r,tagValue:o}=await n.json();return await queryDevices({tags:{[r]:[o]},enabled:!0,type:"default"})}async function getDevice(e){if(!Authentication.token)throw new Error("Not authenticated");const n=await(await fetch(`${exports.FORMANT_API_URL}/v1/admin/devices/${e}`,{method:"GET",headers:{"Content-Type":"application/json",Authorization:"Bearer "+Authentication.token}})).json(),r=n.name;return new Device(e,r,n.organizationId,n.tags)}async function getDevices(){if(!Authentication.token)throw new Error("Not authenticated");const t=await(await fetch(`${exports.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 t.items,t.items.map(n=>new Device(n.id,n.name,defined$1(Authentication.currentOrganization),n.tags))}async function getEvent(e){if(!Authentication.token)throw new Error("Not authenticated");return(await(await fetch(`${exports.FORMANT_API_URL}/v1/admin/events/query/id=${e}`,{method:"GET",headers:{"Content-Type":"application/json",Authorization:"Bearer "+Authentication.token}})).json()).items}async function getFileUrl(e){const n=await(await fetch(`${exports.FORMANT_API_URL}/v1/admin/files/query`,{method:"POST",body:JSON.stringify({fileIds:[e]}),headers:{"Content-Type":"application/json",Authorization:"Bearer "+Authentication.token}})).json();if(n.fileUrls.length===0)throw new Error("File not found");return n.fileUrls[0]}async function getFleet(e){if(!Authentication.token)throw new Error("Not authenticated");return await(await fetch(`${exports.FORMANT_API_URL}/v1/admin/fleets/${e}`,{method:"GET",headers:{"Content-Type":"application/json",Authorization:"Bearer "+Authentication.token}})).json()}async function getFleetDevices(e){if(!Authentication.token)throw new Error("Not authenticated");return(await(await fetch(`${exports.FORMANT_API_URL}/v1/admin/fleets/${e}/devices`,{method:"GET",headers:{"Content-Type":"application/json",Authorization:"Bearer "+Authentication.token}})).json()).items}async function getInterventions(){if(!Authentication.token)throw new Error("Not authenticated");return(await(await fetch(`${exports.FORMANT_API_URL}/v1/admin/intervention-requests`,{method:"GET",headers:{"Content-Type":"application/json",Authorization:"Bearer "+Authentication.token}})).json()).items}async function getLatestTelemetry(...e){const t=e.flat().filter(o=>!!o);return t.length===0?[]:(await(await fetch(`${exports.FORMANT_API_URL}/v1/queries/stream-current-value`,{method:"POST",body:JSON.stringify({deviceIds:t}),headers:{"Content-Type":"application/json",Authorization:"Bearer "+Authentication.token}})).json()).items}async function getOnlineDevices(){if(!Authentication.token)throw new Error("Not authenticated");const n=(await(await fetch(`${exports.FORMANT_API_URL}/v1/queries/online-devices`,{method:"GET",headers:{"Content-Type":"application/json",Authorization:"Bearer "+Authentication.token}})).json()).items;return(await getDevices()).filter(o=>n.includes(o.id))}async function getRealtimeDevices(){if(!Authentication.token)throw new Error("Not authenticated");const n=(await(await fetch(`${exports.FORMANT_API_URL}/v1/signaling/peers`,{method:"GET",headers:{"Content-Type":"application/json",Authorization:"Bearer "+Authentication.token}})).json()).items.map(o=>o.deviceId);return(await getDevices()).filter(o=>n.includes(o.id))}async function getStreams(){if(!Authentication.token)throw new Error("Not authenticated");return(await(await fetch(`${exports.FORMANT_API_URL}/v1/admin/streams`,{method:"GET",headers:{"Content-Type":"application/json",Authorization:"Bearer "+Authentication.token}})).json()).items.filter(n=>n.enabled)}async function getTaskReportRows(e){if(!Authentication.token)throw new Error("Not authenticated");return await(await fetch(`${exports.FORMANT_API_URL}/v1/queries/analytics/task-report-rows`,{method:"POST",body:JSON.stringify(e),headers:{"Content-Type":"application/json",Authorization:"Bearer "+Authentication.token}})).json()}async function getTaskReportTables(){if(!Authentication.token)throw new Error("Not authenticated");return(await(await fetch(`${exports.FORMANT_API_URL}/v1/queries/analytics/task-reports`,{method:"GET",headers:{"Content-Type":"application/json",Authorization:"Bearer "+Authentication.token}})).json()).items}async function listFleets(){if(!Authentication.token)throw new Error("Not authenticated");return(await(await fetch(`${exports.FORMANT_API_URL}/v1/admin/fleets`,{method:"GET",headers:{"Content-Type":"application/json",Authorization:"Bearer "+Authentication.token}})).json()).items}async function patchFleet(e,t){if(!Authentication.token)throw new Error("Not authenticated");return await(await fetch(`${exports.FORMANT_API_URL}/v1/admin/fleets/${e}`,{method:"PATCH",body:JSON.stringify(t),headers:{"Content-Type":"application/json",Authorization:"Bearer "+Authentication.token}})).json()}async function patchStream(e){if(!Authentication.token)throw new Error("Not authenticated");return await(await fetch(`${exports.FORMANT_API_URL}/v1/admin/streams/${e.id}`,{method:"PATCH",body:JSON.stringify(e),headers:{"Content-Type":"application/json",Authorization:"Bearer "+Authentication.token}})).json()}async function patchView(e){if(!Authentication.token)throw new Error("Not authenticated");return await(await fetch(`${exports.FORMANT_API_URL}/v1/admin/views/${e.id}`,{method:"PATCH",body:JSON.stringify(e),headers:{"Content-Type":"application/json",Authorization:"Bearer "+Authentication.token}})).json()}async function queryAnalytics(e){if(!Authentication.token)throw new Error("Not authenticated");return await(await fetch(`${exports.FORMANT_API_URL}/v1/queries/analytics`,{method:"POST",body:JSON.stringify(e),headers:{"Content-Type":"application/json",Authorization:"Bearer "+Authentication.token}})).json()}async function createFleet(e){if(!Authentication.token)throw new Error("Not authenticated");return await(await fetch(`${exports.FORMANT_API_URL}/v1/admin/fleets`,{method:"POST",body:JSON.stringify(e),headers:{"Content-Type":"application/json",Authorization:"Bearer "+Authentication.token}})).json()}async function getAllEventTriggerGroup(){if(!Authentication.token)throw new Error("Not authenticated");return(await(await fetch(`${exports.FORMANT_API_URL}/v1/admin/event-trigger-groups`,{method:"GET",headers:{"Content-Type":"application/json",Authorization:"Bearer "+Authentication.token}})).json()).items}async function getEventTriggerGroup(e){if(!Authentication.token)throw new Error("Not authenticated");return await(await fetch(`${exports.FORMANT_API_URL}/v1/admin/event-trigger-groups/${e}`,{method:"GET",headers:{"Content-Type":"application/json",Authorization:"Bearer "+Authentication.token}})).json()}async function patchEventTriggerGroup(e,t){if(!Authentication.token)throw new Error("Not authenticated");return await(await fetch(`${exports.FORMANT_API_URL}/v1/admin/event-trigger-groups/${e}`,{method:"PATCH",body:JSON.stringify(t),headers:{"Content-Type":"application/json",Authorization:"Bearer "+Authentication.token}})).json()}const Ye=class Ye{static async setDefaultDevice(t){Ye.defaultDeviceId=t}static async getCurrentDevice(){if(!Authentication.token)throw new Error("Not authenticated");if(!Ye.defaultDeviceId)throw new Error("No known default device");const r=(await(await fetch(`${exports.FORMANT_API_URL}/v1/admin/device-details/query`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:"Bearer "+Authentication.token}})).json()).items.find(c=>c.id===Ye.defaultDeviceId),o=r.name,s=new Device(Ye.defaultDeviceId,o,defined$1(Authentication.currentOrganization),r.tags);return Ye.knownContext.push(new WeakRef(s)),s}static async getPeerDevice(t){const n=new PeerDevice(t);return n.id=await n.getDeviceId(),n}static async getDevice(t){const n=await getDevice(t);return Ye.knownContext.push(new WeakRef(n)),n}};_e(Ye,"defaultDeviceId"),_e(Ye,"knownContext",[]),_e(Ye,"createFleet",createFleet),_e(Ye,"listFleets",listFleets),_e(Ye,"getFleet",getFleet),_e(Ye,"patchFleet",patchFleet),_e(Ye,"deleteFleet",deleteFleet),_e(Ye,"addDeviceToFleet",addDeviceToFleet),_e(Ye,"getFleetDevices",getFleetDevices),_e(Ye,"aggregateTelemetry",aggregateTelemetry),_e(Ye,"createShareLink",createShareLink),_e(Ye,"eventsCounter",eventsCounter),_e(Ye,"getAnalyticStreams",getAnalyticStreams),_e(Ye,"getAnalyticsModules",getAnalyticsModules),_e(Ye,"getAnalyticsRows",getAnalyticsRows),_e(Ye,"getAnnotationCount",getAnnotationCount),_e(Ye,"getAnnotationCountByIntervals",getAnnotationCountByIntervals),_e(Ye,"getCurrentGroup",getCurrentGroup),_e(Ye,"getDevices",getDevices),_e(Ye,"getEvent",getEvent),_e(Ye,"getFileUrl",getFileUrl),_e(Ye,"getInterventions",getInterventions),_e(Ye,"getLatestTelemetry",getLatestTelemetry),_e(Ye,"getOnlineDevices",getOnlineDevices),_e(Ye,"getPeers",getPeers),_e(Ye,"getRealtimeDevices",getRealtimeDevices),_e(Ye,"getRealtimeSessions",getRealtimeSessions),_e(Ye,"getStreams",getStreams),_e(Ye,"getTaskReportRows",getTaskReportRows),_e(Ye,"getTaskReportTables",getTaskReportTables),_e(Ye,"getTelemetry",getTelemetry),_e(Ye,"getViews",getViews),_e(Ye,"patchStream",patchStream),_e(Ye,"patchView",patchView),_e(Ye,"queryAnalytics",queryAnalytics),_e(Ye,"queryDevices",queryDevices),_e(Ye,"queryEvents",queryEvents),_e(Ye,"queryTelemetry",queryTelemetry),_e(Ye,"getAllEventTriggerGroup",getAllEventTriggerGroup),_e(Ye,"getEventTriggerGroup",getEventTriggerGroup),_e(Ye,"patchEventTriggergroup",patchEventTriggerGroup);let Fleet=Ye;class KeyValue{static async set(t,n,r){try{const o=await fetch(exports.FORMANT_API_URL+"/v1/admin/key-value",{method:"POST",body:JSON.stringify({organizationId:defined$1(Authentication.currentUser).organizationId,key:t,value:n,tags:r}),headers:{"Content-Type":"application/json",Authorization:"Bearer "+Authentication.token}}),s=await o.json();if(o.status!==200)throw new Error(s.message)}catch(o){throw o}}static async get(t){try{const n=await fetch(exports.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(exports.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(exports.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}}static async query(t){try{const n=await fetch(exports.FORMANT_API_URL+"/v1/admin/key-value/query",{method:"POST",body:JSON.stringify({keys:t}),headers:{"Content-Type":"application/json",Authorization:"Bearer "+Authentication.token}});if(!n.ok)throw new Error("Unable to handle request");return(await n.json()).items}catch(n){throw n}}}class Role{static async listRoles(){if(!Authentication.token)throw new Error("Not authenticated");return(await(await fetch(`${exports.FORMANT_API_URL}/v1/admin/roles`,{method:"GET",headers:{"Content-Type":"application/json",Authorization:"Bearer "+Authentication.token}})).json()).items}static async createRole(t){if(!Authentication.token)throw new Error("Not authenticated");return await(await fetch(`${exports.FORMANT_API_URL}/v1/admin/roles`,{method:"POST",body:JSON.stringify(t),headers:{"Content-Type":"application/json",Authorization:"Bearer "+Authentication.token}})).json()}static async getRole(t){if(!Authentication.token)throw new Error("Not authenticated");return await(await fetch(`${exports.FORMANT_API_URL}/v1/admin/roles/${t}`,{method:"GET",headers:{"Content-Type":"application/json",Authorization:"Bearer "+Authentication.token}})).json()}static async patchRole(t,n){if(!Authentication.token)throw new Error("Not authenticated");return await(await fetch(`${exports.FORMANT_API_URL}/v1/admin/roles/${t}`,{method:"PATCH",body:JSON.stringify(n),headers:{"Content-Type":"application/json",Authorization:"Bearer "+Authentication.token}})).json()}static async deleteRole(t){if(!Authentication.token)throw new Error("Not authenticated");await fetch(`${exports.FORMANT_API_URL}/v1/admin/roles/${t}`,{method:"DELETE",headers:{"Content-Type":"application/json",Authorization:"Bearer "+Authentication.token}})}}class User{static async listUsers(){if(!Authentication.token)throw new Error("Not authenticated");return(await(await fetch(`${exports.FORMANT_API_URL}/v1/admin/users`,{method:"GET",headers:{"Content-Type":"application/json",Authorization:"Bearer "+Authentication.token}})).json()).items}static async createUser(t){if(!Authentication.token)throw new Error("Not authenticated");return await(await fetch(`${exports.FORMANT_API_URL}/v1/admin/users`,{method:"POST",body:JSON.stringify(t),headers:{"Content-Type":"application/json",Authorization:"Bearer "+Authentication.token}})).json()}static async getUser(t){if(!Authentication.token)throw new Error("Not authenticated");return await(await fetch(`${exports.FORMANT_API_URL}/v1/admin/users/${t}`,{method:"GET",headers:{"Content-Type":"application/json",Authorization:"Bearer "+Authentication.token}})).json()}static async patchUser(t,n){if(!Authentication.token)throw new Error("Not authenticated");return await(await fetch(`${exports.FORMANT_API_URL}/v1/admin/users/${t}`,{method:"PATCH",body:JSON.stringify(n),headers:{"Content-Type":"application/json",Authorization:"Bearer "+Authentication.token}})).json()}static async deleteUser(t){if(!Authentication.token)throw new Error("Not authenticated");await fetch(`${exports.FORMANT_API_URL}/v1/admin/users/${t}`,{method:"PATCH",body:JSON.stringify({enabled:!1,roleId:null,teamId:null}),headers:{"Content-Type":"application/json",Authorization:"Bearer "+Authentication.token}})}}async function request(e,t){if(!Authentication.token)throw new Error("Not authenticated");const n=await fetch(`${exports.FORMANT_API_URL}/v1${e}`,{...t,headers:{"Content-Type":"application/json",Authorization:`Bearer ${Authentication.token}`,...t==null?void 0:t.headers}});if(!n.ok)throw new Error(`Error: ${n.statusText}`);return n.status===204||n.headers.get("content-length")==="0"?null:await n.json()}async function fetchTeleopViews(){return(await request("/admin/teleop-views")).items}async function getTeleopView(e){return await request(`/admin/teleop-views/${e}`)}async function createTeleopView(e){return await request("/admin/teleop-views",{method:"POST",body:JSON.stringify(e)})}async function updateTeleopView(e,t){return await request(`/admin/teleop-views/${e}`,{method:"PATCH",body:JSON.stringify(t)})}async function deleteTeleopView(e){await request(`/admin/teleop-views/${e}`,{method:"DELETE"})}class Views{constructor(){}}_e(Views,"createTeleopView",createTeleopView),_e(Views,"updateTeleopView",updateTeleopView),_e(Views,"deleteTeleopView",deleteTeleopView),_e(Views,"getTeleopView",getTeleopView),_e(Views,"fetchTeleopViews",fetchTeleopViews);const viewer="viewer",operator="operator",administrator="administrator",accessLevels=["viewer","operator","administrator"],aggregateLevels=["year","month","week","day","hour","minute"],annotationTypes=["tag","sheet","user"],eventTypes=["triggered-event","datapoint-event","device-online","device-offline","intervention-request","teleop-session-record","port-forwarding-session-record","command-request","command-response","command-delivery","intervention-response","custom","comment","system","annotation","task-summary","stateful"],healthStatuses=["unknown","operational","offline","error"],interventionTypes=["selection","labeling","teleop"],severities=["info","warning","error","critical"],videoMimeTypes=["video/mp4"],timeout=e=>new Promise(t=>setTimeout(t,e*1e3));try{const e=typeof window!="undefined"&&window.location?new URLSearchParams(window.location.search):new URLSearchParams(""),t=e.get("device");t&&Fleet.setDefaultDevice(t);const n=e.get("auth");n&&Authentication.loginWithToken(n),e.get("module")&&Authentication.listenForRefresh(),typeof window!="undefined"&&App.listenForConnectionEvents()}catch(e){}var __defProp=Object.defineProperty,__defProps=Object.defineProperties,__getOwnPropDescs=Object.getOwnPropertyDescriptors,__getOwnPropSymbols=Object.getOwnPropertySymbols,__hasOwnProp=Object.prototype.hasOwnProperty,__propIsEnum=Object.prototype.propertyIsEnumerable,__defNormalProp=(e,t,n)=>t in e?__defProp(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n,__spreadValues=(e,t)=>{for(var n in t||(t={}))__hasOwnProp.call(t,n)&&__defNormalProp(e,n,t[n]);if(__getOwnPropSymbols)for(var n of __getOwnPropSymbols(t))__propIsEnum.call(t,n)&&__defNormalProp(e,n,t[n]);return e},__spreadProps=(e,t)=>__defProps(e,__getOwnPropDescs(t)),__publicField=(e,t,n)=>(__defNormalProp(e,typeof t!="symbol"?t+"":t,n),n);const millisecond$1=1,second$1=1e3,minute$1=60*second$1,hour$1=60*minute$1,day$1=24*hour$1,week$1=7*day$1,month$1=30*day$1,year$1=365*day$1,duration$1={millisecond:millisecond$1,second:second$1,minute:minute$1,hour:hour$1,day:day$1,week:week$1,month:month$1,year:year$1};class H264Decoder{constructor(t,n,r){__publicField(this,"worker"),__publicField(this,"onReceive"),__publicField(this,"onError"),__publicField(this,"onReceiveMessage",s=>{const{data:c}=s;if(c.error){const l=new Error(`${c.error}`);l.cause=c.error,console.warn("H264 worker failure",{error:l}),this.onError(c.index);return}this.onReceive(c)});var o;this.worker=t,(o=this.worker)==null||o.addEventListener("message",this.onReceiveMessage),this.onReceive=n,this.onError=r}post(t,n,r,o){var s;(s=this.worker)==null||s.postMessage({timestamp:t,encodedFrame:n,flags:r,index:o})}release(){var t,n;(t=this.worker)==null||t.removeEventListener("message",this.onReceiveMessage),(n=this.worker)==null||n.terminate(),this.worker=void 0}}class YUVCanvas{constructor(t){__publicField(this,"gl"),__publicField(this,"program"),__publicField(this,"texturePosBuffer"),__publicField(this,"textureRef"),__publicField(this,"height",0),__publicField(this,"width",0),this.gl=t,this.program=this.initProgram();const{texturePosBuffer:n}=this.initBuffers();this.texturePosBuffer=n;const{textureRef:r}=this.initTextures();this.textureRef=r}draw(t){const{gl:n,height:r,width:o,texturePosBuffer:s,textureRef:c}=this;n.viewport(0,0,o,r);const l=new Float32Array([1,0,0,0,1,1,0,1]);return n.bindBuffer(n.ARRAY_BUFFER,s),n.bufferData(n.ARRAY_BUFFER,l,n.DYNAMIC_DRAW),n.activeTexture(n.TEXTURE0),n.bindTexture(n.TEXTURE_2D,c),n.texImage2D(n.TEXTURE_2D,0,n.LUMINANCE,o,r+r/2,0,n.LUMINANCE,n.UNSIGNED_BYTE,t),n.drawArrays(n.TRIANGLE_STRIP,0,4),n.getError()}initProgram(){const{gl:t}=this,n=`
129
129
  attribute vec4 vertexPos;
130
130
  attribute vec4 texturePos;