@formant/data-sdk 1.37.0 → 1.38.0

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.
@@ -59,7 +59,7 @@ In order to be iterable, non-array objects must have a [Symbol.iterator]() metho
59
59
  `))},c.prototype.close=function(){this.transport.close&&this.transport.close(),this.transport.__winstonError&&(this.transport.removeListener("error",this.transport.__winstonError),this.transport.__winstonError=null)}},function(e,t,n){function r(s){return(r=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(c){return typeof c}:function(c){return c&&typeof Symbol=="function"&&c.constructor===Symbol&&c!==Symbol.prototype?"symbol":typeof c})(s)}function l(s,c){for(var o=0;o<c.length;o++){var d=c[o];d.enumerable=d.enumerable||!1,d.configurable=!0,"value"in d&&(d.writable=!0),Object.defineProperty(s,d.key,d)}}e.exports=function(){function s(d){if(function(u,U){if(!(u instanceof U))throw new TypeError("Cannot call a class as a function")}(this,s),!d)throw new Error("Logger is required for profiling.");this.logger=d,this.start=Date.now()}var c,o;return c=s,(o=[{key:"done",value:function(){for(var d=arguments.length,u=new Array(d),U=0;U<d;U++)u[U]=arguments[U];typeof u[u.length-1]=="function"&&(console.warn("Callback function no longer supported as of winston@3.0.0"),u.pop());var B=r(u[u.length-1])==="object"?u.pop():{};return B.level=B.level||"info",B.durationMs=Date.now()-this.start,this.logger.write(B)}}])&&l(c.prototype,o),Object.defineProperty(c,"prototype",{writable:!1}),s}()},function(e,t,n){const r=n(213),{MESSAGE:l}=n(3),s=n(29);function c(o,d){return typeof d=="bigint"?d.toString():d}e.exports=r((o,d)=>{const u=s.configure(d);return o[l]=u(o,d.replacer||c,d.space),o})},function(e,t,n){class r extends Error{constructor(s){super(`Format functions must be synchronous taking a two arguments: (info, opts)
60
60
  Found: ${s.toString().split(`
61
61
  `)[0]}
62
- `),Error.captureStackTrace(this,r)}}e.exports=l=>{if(l.length>2)throw new r(l);function s(o={}){this.options=o}function c(o){return new s(o)}return s.prototype.transform=l,c.Format=s,c}},function(e,t,n){function r(c,o){if(!(c instanceof o))throw new TypeError("Cannot call a class as a function")}function l(c,o){for(var d=0;d<o.length;d++){var u=o[d];u.enumerable=u.enumerable||!1,u.configurable=!0,"value"in u&&(u.writable=!0),Object.defineProperty(c,u.key,u)}}var s=n(88);e.exports=function(){function c(){var u=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};r(this,c),this.loggers=new Map,this.options=u}var o,d;return o=c,(d=[{key:"add",value:function(u,U){var B=this;if(!this.loggers.has(u)){var R=(U=Object.assign({},U||this.options)).transports||this.options.transports;U.transports=R?R.slice():[];var p=s(U);p.on("close",function(){return B._delete(u)}),this.loggers.set(u,p)}return this.loggers.get(u)}},{key:"get",value:function(u,U){return this.add(u,U)}},{key:"has",value:function(u){return!!this.loggers.has(u)}},{key:"close",value:function(u){var U=this;if(u)return this._removeLogger(u);this.loggers.forEach(function(B,R){return U._removeLogger(R)})}},{key:"_removeLogger",value:function(u){this.loggers.has(u)&&(this.loggers.get(u).close(),this._delete(u))}},{key:"_delete",value:function(u){this.loggers.delete(u)}}])&&l(o.prototype,d),Object.defineProperty(o,"prototype",{writable:!1}),c}()},function(e,t,n){(function(r){const l=n(51),s=/^([A-Za-z0-9+/]{4})*([A-Za-z0-9+/]{4}|[A-Za-z0-9+/]{3}=|[A-Za-z0-9+/]{2}==)$/;e.exports=function(c,o,d,u){let U,B,R=!1,p=!1;const g=n(94);function h(D){u(o,D)}function m(D,y){let b=`"${o}" ${y}`;throw D&&(b=`${b}`),B&&(b=`${b}. An example of a valid value would be: ${B}`),new l(b)}const N={convertFromBase64:function(){return h("marking for base64 conversion"),R=!0,N},default:function(D){if(typeof D=="number")U=D.toString();else if(Array.isArray(D)||typeof D=="object"&&D!==null)U=JSON.stringify(D);else{if(typeof D!="string")throw new l("values passed to default() must be of Number, String, Array, or Object type");U=D}return h(`setting default value to "${U}"`),N},required:function(D){return D===void 0?(h("marked as required"),p=!0):(h(`setting required flag to ${D}`),p=D),N},example:function(D){return B=D,N}};return Object.entries({...g,...d}).forEach(([D,y])=>{N[D]=function(b){return function(){let F=c[o];if(h(`will be read from the environment using "${b.name}" accessor`),F===void 0)if(U===void 0&&p)h("was not found in the environment, but is required to be set"),m(void 0,"is a required variable, but it was not set");else{if(U===void 0)return void h("was not found in the environment, but is not required. returning undefined");h(`was not found in the environment, parsing default value "${U}" instead`),F=U}p&&(h("verifying variable value is not an empty string"),F.trim().length===0&&m(void 0,"is a required variable, but its value was empty")),R&&(h("verifying variable is a valid base64 string"),F.match(s)||m(F,"should be a valid base64 string if using convertFromBase64"),h("converting from base64 to utf8 string"),F=r.from(F,"base64").toString());const v=[F].concat(Array.prototype.slice.call(arguments));try{h(`passing value "${F}" to "${b.name}" accessor`);const j=b.apply(b,v);return h(`parsed successfully, returning ${j}`),j}catch(j){m(F,j.message)}}}(y)}),N}}).call(this,n(5).Buffer)},function(e,t,n){const r=n(34);e.exports=function(l,s){return s=s||",",l.length?r(l).split(s).filter(Boolean):[]}},function(e,t,n){e.exports=function(r){const l=r.toLowerCase();if(l!=="false"&&l!=="true")throw new Error('should be either "true", "false", "TRUE", or "FALSE"');return l!=="false"}},function(e,t,n){e.exports=function(r){const l=r.toLowerCase();if(["false","0","true","1"].indexOf(l)===-1)throw new Error('should be either "true", "false", "TRUE", "FALSE", 1, or 0');return!(l==="0"||l==="false")}},function(e,t,n){const r=n(95);e.exports=function(l){var s=r(l);if(s>65535)throw new Error("cannot assign a port number greater than 65535");return s}},function(e,t,n){const r=n(34);e.exports=function(l,s){const c=r(l);if(s.indexOf(c)<0)throw new Error(`should be one of [${s.join(", ")}]`);return c}},function(e,t,n){const r=n(53);e.exports=function(l){const s=r(l);if(s>0)throw new Error("should be a negative float");return s}},function(e,t,n){const r=n(53);e.exports=function(l){const s=r(l);if(s<0)throw new Error("should be a positive float");return s}},function(e,t,n){const r=n(52);e.exports=function(l){const s=r(l);if(s>0)throw new Error("should be a negative integer");return s}},function(e,t,n){const r=n(54);e.exports=function(l){var s=r(l);if(!Array.isArray(s))throw new Error("should be a parseable JSON Array");return s}},function(e,t,n){const r=n(54);e.exports=function(l){var s=r(l);if(Array.isArray(s))throw new Error("should be a parseable JSON Object");return s}},function(e,t,n){e.exports=function(r,l){try{RegExp(void 0,l)}catch{throw new Error("invalid regexp flags")}try{return new RegExp(r,l)}catch{throw new Error("should be a valid regexp")}}},function(e,t,n){const r=n(96);e.exports=function(l){return r(l).toString()}},function(e,t,n){const r=n(34),l=/^(?:[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*|"(?:[\u0001-\u0008\u000b\u000c\u000e-\u001f\u0021\u0023-\u005b\u005d-\u007f]|\\[\u0001-\u0009\u000b\u000c\u000e-\u007f])*")@(?:(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?|\[(?:(?:(2(5[0-5]|[0-4][0-9])|1[0-9][0-9]|[1-9]?[0-9]))\.){3}(?:(2(5[0-5]|[0-4][0-9])|1[0-9][0-9]|[1-9]?[0-9])|[a-z0-9-]*[a-z0-9]:(?:[\u0001-\u0008\u000b\u000c\u000e-\u001f\u0021-\u005a\u0053-\u007f]|\\[\u0001-\u0009\u000b\u000c\u000e-\u007f])+)\])$/;e.exports=function(s){const c=r(s);if(!l.test(c))throw new Error("should be a valid email address");return c}},function(e,t,n){e.exports=function(r,l){return function(s,c){l&&l.match(/prod|production/)||r(`env-var (${s}): ${c}`)}}},function(e,t,n){(function(r){(function(){var l,s,c,o,d,u;typeof performance!="undefined"&&performance!==null&&performance.now?e.exports=function(){return performance.now()}:r!=null&&r.hrtime?(e.exports=function(){return(l()-d)/1e6},s=r.hrtime,o=(l=function(){var U;return 1e9*(U=s())[0]+U[1]})(),u=1e9*r.uptime(),d=o-u):Date.now?(e.exports=function(){return Date.now()-c},c=Date.now()):(e.exports=function(){return new Date().getTime()-c},c=new Date().getTime())}).call(this)}).call(this,n(2))},function(e,t,n){(function(r){(function(l){function s(o){if((o=o===void 0?"utf-8":o)!=="utf-8")throw new RangeError("Failed to construct 'TextEncoder': The encoding label provided ('"+o+"') is invalid.")}function c(o,d){if(d=d===void 0?{fatal:!1}:d,(o=o===void 0?"utf-8":o)!=="utf-8")throw new RangeError("Failed to construct 'TextDecoder': The encoding label provided ('"+o+"') is invalid.");if(d.fatal)throw Error("Failed to construct 'TextDecoder': the 'fatal' option is unsupported.")}if(l.TextEncoder&&l.TextDecoder)return!1;Object.defineProperty(s.prototype,"encoding",{value:"utf-8"}),s.prototype.encode=function(o,d){if((d=d===void 0?{stream:!1}:d).stream)throw Error("Failed to encode: the 'stream' option is unsupported.");d=0;for(var u=o.length,U=0,B=Math.max(32,u+(u>>1)+7),R=new Uint8Array(B>>3<<3);d<u;){var p=o.charCodeAt(d++);if(55296<=p&&56319>=p){if(d<u){var g=o.charCodeAt(d);(64512&g)==56320&&(++d,p=((1023&p)<<10)+(1023&g)+65536)}if(55296<=p&&56319>=p)continue}if(U+4>R.length&&(B+=8,B=(B*=1+d/o.length*2)>>3<<3,(g=new Uint8Array(B)).set(R),R=g),(4294967168&p)==0)R[U++]=p;else{if(!(4294965248&p))R[U++]=p>>6&31|192;else if(!(4294901760&p))R[U++]=p>>12&15|224,R[U++]=p>>6&63|128;else{if(4292870144&p)continue;R[U++]=p>>18&7|240,R[U++]=p>>12&63|128,R[U++]=p>>6&63|128}R[U++]=63&p|128}}return R.slice(0,U)},Object.defineProperty(c.prototype,"encoding",{value:"utf-8"}),Object.defineProperty(c.prototype,"fatal",{value:!1}),Object.defineProperty(c.prototype,"ignoreBOM",{value:!1}),c.prototype.decode=function(o,d){if((d=d===void 0?{stream:!1}:d).stream)throw Error("Failed to decode: the 'stream' option is unsupported.");d=0;for(var u=(o=new Uint8Array(o)).length,U=[];d<u;){var B=o[d++];if(B===0)break;if(!(128&B))U.push(B);else if((224&B)==192){var R=63&o[d++];U.push((31&B)<<6|R)}else if((240&B)==224){R=63&o[d++];var p=63&o[d++];U.push((31&B)<<12|R<<6|p)}else(248&B)==240&&(65535<(B=(7&B)<<18|(R=63&o[d++])<<12|(p=63&o[d++])<<6|63&o[d++])&&(B-=65536,U.push(B>>>10&1023|55296),B=56320|1023&B),U.push(B))}return String.fromCharCode.apply(null,U)},l.TextEncoder=s,l.TextDecoder=c})(typeof window!="undefined"?window:r!==void 0?r:this)}).call(this,n(6))},function(e,t,n){n.r(t),n.d(t,"AuthClient",function(){return s}),n.d(t,"RtcSignalingClient",function(){return o}),n.d(t,"Credentials",function(){return I}),n.d(t,"SignalingPromiseClient",function(){return W.SignalingPromiseClient}),n.d(t,"RtcClient",function(){return At}),n.d(t,"RtcClientV1",function(){return Nt}),n.d(t,"createRtcStreamMessage",function(){return et});var r=n(26),l=function(Re,A,x,q){return new(x||(x=Promise))(function(oe,se){function de(Ue){try{pe(q.next(Ue))}catch(le){se(le)}}function he(Ue){try{pe(q.throw(Ue))}catch(le){se(le)}}function pe(Ue){var le;Ue.done?oe(Ue.value):(le=Ue.value,le instanceof x?le:new x(function(me){me(le)})).then(de,he)}pe((q=q.apply(Re,A||[])).next())})};class s extends r.a{adminSignup(A,x){return l(this,void 0,void 0,function*(){return yield this.fetch("auth/admin-signup",{token:x,method:"POST",body:A})})}login(A){return l(this,void 0,void 0,function*(){return yield this.fetch("auth/login",{method:"POST",body:A,allowUnsafeRetries:!0})})}loginWithGoogleToken(A){return l(this,void 0,void 0,function*(){return yield this.fetch("auth/login-google",{method:"POST",body:A,allowUnsafeRetries:!0})})}refresh(A,x){return l(this,void 0,void 0,function*(){return yield this.fetch("auth/refresh",{method:"POST",body:{refreshToken:A,tokenExpirationSeconds:x},allowUnsafeRetries:!0})})}respondToNewPasswordRequiredChallenge(A){return l(this,void 0,void 0,function*(){return yield this.fetch("auth/respond-to-new-password-required-challenge",{method:"POST",body:A})})}forgotPassword(A){return l(this,void 0,void 0,function*(){return yield this.fetch("auth/forgot-password",{method:"POST",body:{email:A}})})}confirmForgotPassword(A){return l(this,void 0,void 0,function*(){return yield this.fetch("auth/confirm-forgot-password",{method:"POST",body:A})})}resendInvitation(A){return l(this,void 0,void 0,function*(){return yield this.fetch("auth/resend-invitation",{method:"POST",body:{email:A}})})}changePassword({token:A,refreshToken:x,currentPassword:q,newPassword:oe}){return l(this,void 0,void 0,function*(){return yield this.fetch("auth/change-password",{token:A,method:"POST",body:{refreshToken:x,currentPassword:q,newPassword:oe}})})}getDeviceCredentials(A){return l(this,void 0,void 0,function*(){return yield this.fetch("auth/device-credentials",{token:A,method:"POST",allowUnsafeRetries:!0})})}impersonate(A,x){return l(this,void 0,void 0,function*(){return yield this.fetch("auth/impersonate",{token:A,method:"POST",allowUnsafeRetries:!0,body:{userId:x}})})}createServiceAccount(A,x,q,oe){return l(this,void 0,void 0,function*(){return yield this.fetch("auth/service-account",{token:A,method:"POST",allowUnsafeRetries:!0,body:{name:x,roleId:q,tags:oe}})})}getFeatures(A){return l(this,void 0,void 0,function*(){return(yield this.fetch("auth/features",{token:A})).features})}}var c=function(Re,A,x,q){return new(x||(x=Promise))(function(oe,se){function de(Ue){try{pe(q.next(Ue))}catch(le){se(le)}}function he(Ue){try{pe(q.throw(Ue))}catch(le){se(le)}}function pe(Ue){var le;Ue.done?oe(Ue.value):(le=Ue.value,le instanceof x?le:new x(function(me){me(le)})).then(de,he)}pe((q=q.apply(Re,A||[])).next())})};class o extends r.a{createPeer(A,x){return c(this,void 0,void 0,function*(){return yield this.fetch("peers",{token:A,method:"POST",body:x})})}getPeers(A){return c(this,void 0,void 0,function*(){return(yield this.fetch("peers",{token:A})).items})}refreshPeer(A,x){return c(this,void 0,void 0,function*(){yield this.fetch(`peers/${x}/refresh`,{token:A,method:"POST",allowUnsafeRetries:!0})})}createSession(A,x){return c(this,void 0,void 0,function*(){return yield this.fetch("sessions",{token:A,method:"POST",body:x})})}refreshSession(A,x){return c(this,void 0,void 0,function*(){yield this.fetch(`sessions/${x}/refresh`,{token:A,method:"POST",allowUnsafeRetries:!0})})}deleteSession(A,x){return c(this,void 0,void 0,function*(){yield this.fetch(`sessions/${x}`,{token:A,method:"DELETE",allowUnsafeRetries:!0})})}getSessions(A){return c(this,void 0,void 0,function*(){return(yield this.fetch("sessions",{token:A})).items})}getIceServers(A){return c(this,void 0,void 0,function*(){return(yield this.fetch("ice-servers",{token:A})).items})}addSignals(A,x,q){return c(this,void 0,void 0,function*(){yield this.fetch(`sessions/${x}/add-signals`,{token:A,method:"POST",body:q})})}takeSignals(A,x){return c(this,void 0,void 0,function*(){return(yield this.fetch(`sessions/${x}/take-signals`,{token:A,method:"POST"})).items})}}var d=n(1),u=n(9),U=n(15),B=n.n(U),R=n(102),p=n.n(R),g=n(4),h=n(0),m=function(Re,A,x,q){return new(x||(x=Promise))(function(oe,se){function de(Ue){try{pe(q.next(Ue))}catch(le){se(le)}}function he(Ue){try{pe(q.throw(Ue))}catch(le){se(le)}}function pe(Ue){var le;Ue.done?oe(Ue.value):(le=Ue.value,le instanceof x?le:new x(function(me){me(le)})).then(de,he)}pe((q=q.apply(Re,A||[])).next())})};class N extends class{constructor(A,x){this.type=A,this.name=x}}{constructor(A){super("simple","LogReporter"),this.message=A}send(A){return m(this,void 0,void 0,function*(){var x,q;h.a.debug(this.message,(x=A.reduce((oe,se)=>Object.assign(Object.assign({},oe),{[se.name]:se.stat}),{}),q=oe=>{const{sum:se,count:de}=oe,he=se/de;return Object.assign(Object.assign({},oe),{average:he})},Object.keys(x).reduce((oe,se)=>Object.assign(Object.assign({},oe),{[se]:q(x[se])}),{})))})}}var D=n(40);function y(Re){return!!Re.match(/^[a-zA-Z0-9-_.,:?'"()@\/\\#$+ ]{1,255}$/)}var b=function(Re,A,x,q){return new(x||(x=Promise))(function(oe,se){function de(Ue){try{pe(q.next(Ue))}catch(le){se(le)}}function he(Ue){try{pe(q.throw(Ue))}catch(le){se(le)}}function pe(Ue){var le;Ue.done?oe(Ue.value):(le=Ue.value,le instanceof x?le:new x(function(me){me(le)})).then(de,he)}pe((q=q.apply(Re,A||[])).next())})};function F({func:Re,delay:A,immediate:x=!1}){let q=!1,oe=setTimeout(function de(){return b(this,void 0,void 0,function*(){if(q)return;const he=new Date().getTime();try{se=Re(),yield se}finally{if(!q){const pe=new Date().getTime();oe=setTimeout(de,Math.max(A-(pe-he),0))}}})},x?0:A),se=Promise.resolve();return{stop(){return b(this,void 0,void 0,function*(){q=!0,clearTimeout(oe),yield se})}}}var v=function(Re,A,x,q){return new(x||(x=Promise))(function(oe,se){function de(Ue){try{pe(q.next(Ue))}catch(le){se(le)}}function he(Ue){try{pe(q.throw(Ue))}catch(le){se(le)}}function pe(Ue){var le;Ue.done?oe(Ue.value):(le=Ue.value,le instanceof x?le:new x(function(me){me(le)})).then(de,he)}pe((q=q.apply(Re,A||[])).next())})};const j=n(230);class K{constructor(A){this.buffer={},this.reporters=[],this.flushInterval=F({func:()=>this.flushStats(),delay:K.samplePeriodMs}),this.tags=this.filterTags((A==null?void 0:A.tags)||{app:g.a,version:g.j,namespace:g.i,instanceId:D.a})}shutdown(){return v(this,void 0,void 0,function*(){yield this.flushInterval.stop(),yield this.flushStats(),yield Object(u.a)(2*d.a.second)})}aggregate(A,x,q){this.addToBuffer(this.buffer,this.encodeKey({metric:A,tags:this.filterTags(q||{})}),typeof x=="number"?{min:x,max:x,sum:x,count:1}:x)}increment(A,x){this.aggregate(A,1,x)}timer(A,x,q){return v(this,void 0,void 0,function*(){const oe=j(),se=yield x(),de=j();return this.aggregate(A,de-oe,q),se})}registerStatsReporter(A){this.reporters.push(A)}setTag(A,x){const q=this.filterTags({[A]:x});this.tags=Object.assign(Object.assign({},this.tags),q)}addToBuffer(A,x,q){if(A[x]){const{min:oe,max:se,sum:de,count:he}=A[x];A[x]={min:Math.min(oe,q.min),max:Math.max(se,q.max),sum:de+q.sum,count:he+q.count}}else A[x]=q}write(A){return v(this,void 0,void 0,function*(){yield Promise.all(this.reporters.map(x=>v(this,void 0,void 0,function*(){let q;const oe={};switch(x.type){case"simple":for(const[de,he]of Object.entries(A)){const{metric:pe}=this.decodeKey(de);this.addToBuffer(oe,this.encodeKey({metric:pe}),he)}q=oe;break;case"tagged":q=A;break;default:(function(de){throw new Error(`Unreachable type encountered (${de})`)})(x.type)}const se=Object.entries(q);if(se.length>0)return x.send(se.map(([de,he])=>{const{metric:pe,tags:Ue}=this.decodeKey(de);return{name:pe,tags:Object.assign(Object.assign({},Ue),this.tags),stat:he}}),K.samplePeriodMs).catch(de=>{h.a.debug(`Failed to write stats to ${x.name}`,{error:de})})})))})}flushStats(){return v(this,void 0,void 0,function*(){yield this.write(this.buffer),this.buffer={}})}encodeKey(A){return B()(Object.assign(Object.assign({},A),Object.keys(A.tags||{}).length>0?{tags:A.tags}:{}))}decodeKey(A){return JSON.parse(A)}filterTags(A){return Object.entries(A||{}).reduce((x,[q,oe])=>(y(q)&&y(oe)&&(x[q]=oe),x),{})}}K.samplePeriodMs=5*d.a.minute;const f=!!g.c,Q=new K;f||["local","on-prem"].includes(g.i)||Q.registerStatsReporter(new N("stats"));var P=function(Re,A,x,q){return new(x||(x=Promise))(function(oe,se){function de(Ue){try{pe(q.next(Ue))}catch(le){se(le)}}function he(Ue){try{pe(q.throw(Ue))}catch(le){se(le)}}function pe(Ue){var le;Ue.done?oe(Ue.value):(le=Ue.value,le instanceof x?le:new x(function(me){me(le)})).then(de,he)}pe((q=q.apply(Re,A||[])).next())})};class w extends class{constructor(A){this.options=A,this.cache=new p.a(Object.assign(Object.assign(Object.assign({},A.dispose||A.disposeAfter?{ttlAutopurge:!0}:{}),A),{dispose:(...x)=>{var q;x[2]==="evict"&&Q.increment("lru-eviction",{name:A.name}),(q=A.dispose)===null||q===void 0||q.call(A,...x)},disposeAfter:(...x)=>{var q;this.updateStats(),(q=A.disposeAfter)===null||q===void 0||q.call(A,...x)}})),this.stringify=A.fastStringify?JSON.stringify:B.a}set(A,x,q){const oe=this.stringify(A);if(!this.cache.set(oe,x,{ttl:q})){const se=this.cache.sizeCalculation?this.cache.sizeCalculation(x,oe):"unknown";throw Error(`Value too large (${se} > ${this.cache.max})`)}this.updateStats()}get(A){const{name:x}=this.options,q=this.stringify(A),oe=this.cache.getRemainingTTL(q);return oe<=0?Q.increment("cache-miss",{name:x}):oe!==1/0&&Q.aggregate("cache-item-ttl",oe,{name:x}),this.cache.get(q)}delete(A){this.cache.delete(this.stringify(A))}peek(A){return this.cache.peek(this.stringify(A))}size(){return this.cache.size}clear(){this.cache.clear()}forEach(A){this.cache.forEach(A)}purgeStale(){return this.cache.purgeStale()}updateStats(){const{name:A}=this.options;Q.aggregate("cache-item-count",this.cache.size,{name:A}),this.cache.calculatedSize!==void 0&&Q.aggregate("cache-length",this.cache.calculatedSize,{name:A})}}{constructor(A){if(super(A),this.expireRejectedPromiseValues=A.expireRejectedPromiseValues===void 0||A.expireRejectedPromiseValues,this.rejectedPromiseValueTtl=A.rejectedPromiseValueTtl!==void 0?A.rejectedPromiseValueTtl:d.a.second,this.rejectedPromiseValueTtl<0)throw new Error("rejectedPromiseValueTtl must not be negative")}set(A,x,q){super.set(A,x,q),this.expireRejectedPromiseValues&&x.catch(()=>P(this,void 0,void 0,function*(){yield Object(u.a)(this.rejectedPromiseValueTtl),this.peek(A)===x&&this.delete(A)}))}}var V=function(Re,A,x,q){return new(x||(x=Promise))(function(oe,se){function de(Ue){try{pe(q.next(Ue))}catch(le){se(le)}}function he(Ue){try{pe(q.throw(Ue))}catch(le){se(le)}}function pe(Ue){var le;Ue.done?oe(Ue.value):(le=Ue.value,le instanceof x?le:new x(function(me){me(le)})).then(de,he)}pe((q=q.apply(Re,A||[])).next())})};class I{constructor(A,x,q){this.authClient=A,this.email=x,this.password=q,this.tokenTtlMs=1*d.a.hour,this.tokenCache=new w({name:"Credentials-tokenCache",max:100,ttl:this.tokenTtlMs-5*d.a.minute,fastStringify:!0})}getToken(){return V(this,void 0,void 0,function*(){let A=this.tokenCache.get(this.email);return A||(A=(()=>V(this,void 0,void 0,function*(){const{authentication:x}=yield this.authClient.login({email:this.email,password:this.password,tokenExpirationSeconds:this.tokenTtlMs/d.a.second});if(!x)throw new Error("User account not verified.");return x.accessToken}))(),this.tokenCache.set(this.email,A)),A})}}var W=n(97),k=n(17),T=n(233),Z=n(41),O=function(Re,A,x,q){return new(x||(x=Promise))(function(oe,se){function de(Ue){try{pe(q.next(Ue))}catch(le){se(le)}}function he(Ue){try{pe(q.throw(Ue))}catch(le){se(le)}}function pe(Ue){var le;Ue.done?oe(Ue.value):(le=Ue.value,le instanceof x?le:new x(function(me){me(le)})).then(de,he)}pe((q=q.apply(Re,A||[])).next())})};class E extends Z.a{constructor(A){super(A)}postLanRtcOffer(A){return O(this,void 0,void 0,function*(){return yield this.fetch("v1/lan-rtc-offer",{method:"POST",body:A})})}}var L=function(Re,A,x,q){return new(x||(x=Promise))(function(oe,se){function de(Ue){try{pe(q.next(Ue))}catch(le){se(le)}}function he(Ue){try{pe(q.throw(Ue))}catch(le){se(le)}}function pe(Ue){var le;Ue.done?oe(Ue.value):(le=Ue.value,le instanceof x?le:new x(function(me){me(le)})).then(de,he)}pe((q=q.apply(Re,A||[])).next())})};function G(Re){return L(this,void 0,void 0,function*(){return(yield Promise.all(Re.map(A=>A.catch(x=>x)))).filter(A=>A instanceof Error)})}function $(Re,A){if(Re===void 0)throw new Error(`Value is undefined${A?`: ${A}`:""}`)}function ee(Re,A){if(Re===null)throw new Error(`Value is null${A?`: ${A}`:""}`)}function te(Re){return $(Re),Re}function M(Re,A){const x=Re.reduce((q,oe)=>[...q,...oe.urls],[]).filter(q=>C(q,A)).sort(q=>S(q,"udp")?-1:0).shift();if(x)return Object.assign(Object.assign({},te(Re.find(q=>q.urls.includes(x)))),{urls:[x]})}function C(Re,A){switch(A){case"stun":return/^stuns?:/.test(Re);case"turn":return/^turns?:/.test(Re)}}function S(Re,A){return Re.endsWith(`transport=${A}`)}var _=n(10);class z extends Error{constructor(A,x){super(`Deadline expired after ${A}ms + ${x}ms`)}}class X{static withDeadline(A,x){const q=new Promise((oe,se)=>{setTimeout(()=>{se(new z(x,this.grpcCallDeadlineSlopMs))},x+this.grpcCallDeadlineSlopMs)});return Promise.race([A,q])}}X.grpcCallDeadlineSlopMs=500*d.a.millisecond;var H=n(27);const ne={ordered:!1,maxPacketLifeTime:300*d.a.millisecond},ie={ordered:!0},ce={ordered:!0},Se={ordered:!1,maxRetransmits:0},Te={ordered:!1,maxRetransmits:0},ye=Re=>"received"in Re&&Re.received!==void 0,we=Re=>!("received"in Re)||Re.received===void 0,be=2*d.a.second;function Ee(Re,A={}){const x=Array.from(Re.values()),q=x.filter(ye),oe=q.length>0,se=Math.max(...q.map(Ue=>Ue.received));let de;if(oe){const Ue=x.length,le=q.length,me=q.map(Ze=>Ze.received-Ze.sent),{standardDeviation:Je,mean:We,jitter:je}=function(Ze){const Me=Ze.length;if(Me===0)return{mean:NaN,standardDeviation:-1,jitter:NaN};const ze=Ze.reduce((Ke,st)=>Ke+st,0)/Me,Ye=Math.sqrt(Ze.map(Ke=>Math.pow(Ke-ze,2)).reduce((Ke,st)=>Ke+st)/Me);if(Me===1)return{mean:ze,standardDeviation:Ye,jitter:NaN};let Xe=0;for(let Ke=1;Ke<Me;Ke++)Xe+=Math.abs(Ze[Ke]-Ze[Ke-1]);return{mean:ze,standardDeviation:Ye,jitter:Xe/(Me-1)}}(me),Pe=x.filter(Ze=>Ze.sent<se-be),He=Pe.filter(we),qe=He.length===0?0:He.length/Pe.length;de={pingsSent:Ue,pongsReceived:le,average:We,standardDeviation:Je,jitter:je,max:Math.max(...me),min:Math.min(...me),loss:qe}}else de=null;const{temporalNow:he=Date.now()}=A,pe=(oe?se:he)-4*be;return Array.from(Re.entries()).forEach(Ue=>{const[le,me]=Ue;me.sent<pe&&Re.delete(le)}),de}function _e({entityId:Re,streamName:A,streamType:x}){return`${Re}.${A}.${x}`}var Ae=function(Re,A,x,q){return new(x||(x=Promise))(function(oe,se){function de(Ue){try{pe(q.next(Ue))}catch(le){se(le)}}function he(Ue){try{pe(q.throw(Ue))}catch(le){se(le)}}function pe(Ue){var le;Ue.done?oe(Ue.value):(le=Ue.value,le instanceof x?le:new x(function(me){me(le)})).then(de,he)}pe((q=q.apply(Re,A||[])).next())})};class Le{constructor(A,x){this.counts={localSent:new Map,localReceived:new Map,remoteSent:new Map,remoteReceived:new Map},this.sessionId=A,this.connection=x}updateRemoteMessagesCounts(A){if(A.payload.streamsInfo){this.counts.remoteSent=new Map,this.counts.remoteReceived=new Map;for(const x of A.payload.streamsInfo.items)this.counts.remoteSent.set(x.streamId,x.sentCount),this.counts.remoteReceived.set(x.streamId,x.receivedCount)}}getLocalStreamsInfo(A){const{localSent:x,localReceived:q}=this.counts;return{items:[...new Set([...x.keys(),...q.keys()])].map(oe=>{var se,de;return{streamId:oe,sentCount:(se=x.get(oe))!==null&&se!==void 0?se:0,receivedCount:(de=q.get(oe))!==null&&de!==void 0?de:0}}),timestamp:A}}incrementLocalSent(A){const{localSent:x}=this.counts,q=_e(A.header.stream);x.set(q,(x.get(q)||0)+1)}incrementLocalReceived(A){const{localReceived:x}=this.counts,q=_e(A.header.stream),oe=x.get(q)||0;if(oe===0){const{streamName:se,streamType:de}=A.header.stream;h.a.debug("RTC client received first message for stream",{streamName:se,streamType:de})}x.set(q,oe+1)}uploadMetrics(){return Ae(this,void 0,void 0,function*(){const{sessionId:A}=this,x=yield this.connection.peerConnection.getStats(),q={};x.forEach(Ue=>q[Ue.id]=Ue),h.a.debug("rtc-stats",Object.assign(Object.assign({},q),{sessionId:A}));const{localSent:oe,localReceived:se,remoteSent:de,remoteReceived:he}=this.counts,pe=[...new Set([...oe.keys(),...se.keys()])].reduce((Ue,le)=>{const me=oe.get(le),Je=se.get(le),We=de.get(le),je=he.get(le);return Object.assign(Object.assign({},Ue),{[`local-${le}-sent`]:me,[`local-${le}-received`]:Je,[`remote-${le}-sent`]:We,[`remote-${le}-received`]:je})},{sessionId:A});h.a.debug("rtc-message-report",Object.assign({deviceId:this.connection.getRemoteDeviceId()},pe))})}}function et(Re,A,x){return{header:{stream:Re,created:Date.now(),frameId:x||""},payload:A}}function Qt(Re){const A=Re.localCandidate.candidateType,x=Re.remoteCandidate.candidateType;return A==="host"&&x==="host"?"local":A==="relay"||x==="relay"?"TURN":"STUN"}function Rt(Re){return new Set(["disconnected","failed","closed"]).has(Re.iceConnectionState)}function Et(Re){switch(Re.header.stream.streamType){case"twist":{const{twist:A}=Re.payload;if(!A)throw Error("twist not in payload of RTC message with type twist");return{header:Re.header,payload:{twist:{linear:Object.assign({x:0,y:0,z:0},A.linear),angular:Object.assign({x:0,y:0,z:0},A.angular)}}}}case"pose":{const{pose:A}=Re.payload;if(!A)throw Error("pose not in payload of RTC message with type pose");return{header:Re.header,payload:{pose:{translation:Object.assign({x:0,y:0,z:0},A.translation),rotation:Object.assign({x:0,y:0,z:0,w:0},A.rotation)}}}}case"pose-with-covariance":{const{poseWithCovariance:A}=Re.payload;if(!A)throw Error("poseWithCovariance not in payload of RTC message with type pose-with-covariance");const x=new Array(36).fill(0);return A.covariance.forEach((q,oe)=>{if(oe>=36)throw Error("covariance contains more than 36 elements");x[oe]=q}),{header:Re.header,payload:{poseWithCovariance:{pose:{translation:Object.assign({x:0,y:0,z:0},A.pose.translation),rotation:Object.assign({x:0,y:0,z:0,w:0},A.pose.rotation)},covariance:x}}}}case"point":{const{point:A}=Re.payload;if(!A)throw Error("point not in payload of RTC message with type point");return{header:Re.header,payload:{point:Object.assign({x:0,y:0,z:0},A)}}}default:return Re}}var ot=function(Re,A,x,q){return new(x||(x=Promise))(function(oe,se){function de(Ue){try{pe(q.next(Ue))}catch(le){se(le)}}function he(Ue){try{pe(q.throw(Ue))}catch(le){se(le)}}function pe(Ue){var le;Ue.done?oe(Ue.value):(le=Ue.value,le instanceof x?le:new x(function(me){me(le)})).then(de,he)}pe((q=q.apply(Re,A||[])).next())})};class gt{get peerConnection(){return ee(this._peerConnection,"RTCPeerConnection is closed!"),this._peerConnection}constructor(A,x,q,oe){this.iceServers=x,this.config=q,this.dataChannelNotifier=oe,this.connectTimeoutMs=20*d.a.second,this.iceGatheringTimeoutMs=3*d.a.second,this.pingUpdateTimeoutMs=1*d.a.second,this.pingV2UpdateTimeoutMs=250*d.a.millisecond,this.pingV2MetricsGatherTimeoutMs=1*d.a.second,this.streamsInfoUpdateTimeoutMs=2*d.a.second,this.reassemblyTimeoutMs=500*d.a.millisecond,this.reassemblyTableCleanupMs=1*d.a.second,this.heartbeatTimeoutMs=20*d.a.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.closeCalled=!1,this.gotOffer=!1,this.hasIceCandidate=!1,this.pingV2Map=new Map,this.sendPingV2=()=>{const{latestTryOnceStreamChannel:de}=this;if(!de)return;const he=new Date().getTime(),pe=Object(T.a)();this.sendSystemMessage(de,{type:"ping-v2",payload:{timestamp:he,id:pe}}),this.pingV2Map.set(pe,{sent:he})},this.gatherPingV2Metrics=()=>{const de=Ee(this.pingV2Map);if(de){const he=this.getRemoteDeviceId();this.pingInfo=de,Q.aggregate("rtc-ping-average",de.average,Object.assign({},he?{deviceId:he}:{})),Q.aggregate("rtc-ping-loss",de.loss,Object.assign({},he?{deviceId:he}:{})),Q.aggregate("rtc-jitter",de.jitter,Object.assign({},he?{deviceId:he}:{}))}},this._peerConnection=A;const{isOffer:se}=q.baseConfig;se?this.initializeChannels(A):A.ondatachannel=de=>{switch(de.channel.label){case"stream.latest-ttl":this.latestTtlStreamChannel=de.channel;break;case"stream.reliable":this.reliableStreamChannel=de.channel;break;case"stream.latest-reliable":this.latestReliableStreamChannel=de.channel;break;case"stream.latest-try-once":this.latestTryOnceStreamChannel=de.channel;break;case"heartbeat":return void(this.heartbeatChannel=de.channel);default:return void this.dataChannelNotifier(de.channel)}this.setupChannel(de.channel)},this.pingUpdateTimeout=setInterval(()=>{const{reliableStreamChannel:de}=this;de&&this.sendSystemMessage(de,{type:"ping"})},this.pingUpdateTimeoutMs),this.pingV2UpdateTimeout=setInterval(this.sendPingV2,this.pingV2UpdateTimeoutMs),this.pingV2MetricsGatherTimeout=setInterval(this.gatherPingV2Metrics,this.pingV2MetricsGatherTimeoutMs),this.streamsInfoUpdateTimeout=setInterval(()=>{const{latestTtlStreamChannel:de}=this;de&&this.sendSystemMessage(de,{type:"streams-info"})},this.streamsInfoUpdateTimeoutMs),this.reassemblyTableCleanupTimeout=setInterval(()=>{const de=new Date().getTime();this.reassemblyTableLastTimestamp.forEach((he,pe,Ue)=>{de>pe+this.reassemblyTimeoutMs&&this.reassemblyTable.delete(he)})},this.reassemblyTableCleanupMs),this.heartbeatTimeout=setInterval(()=>{const{heartbeatChannel:de}=this;de&&de.readyState==="open"&&de.send(new Uint8Array([1]))},this.heartbeatTimeoutMs)}handleSignal(A){return ot(this,void 0,void 0,function*(){const{peerConnection:x}=this,{track:q}=this.config.baseConfig,oe=(()=>{try{return JSON.parse(A.getPayload())}catch{return}})();if(!oe)return void h.a.error("Received unparseable signal.");h.a.debug("Handling signal",{description:oe});const{sdp:se,type:de}=oe;if(!se||!de)return void h.a.warn("Received non-SDP signal");const{signalingState:he,connectionState:pe}=x;if(he!=="stable"||pe!=="connected")if(x.remoteDescription)h.a.warn(`Received SDP after remote description was set: ${se}`);else{if(de==="offer"){if(he!=="stable")return void h.a.warn("Received offer SDP when signaling is ongoing.");yield x.setRemoteDescription(oe);const Ue=yield x.createAnswer();yield x.setLocalDescription(Ue);const le=A.clone();return q==null||q("Answer Received",le),le.setPayload(JSON.stringify(Ue)),le.setReceiverId(A.getSenderId()),le.setSenderId(A.getReceiverId()),le}if(de==="answer"){if(he==="stable")return void h.a.warn("Received answer SDP when signaling hasn't started.");yield x.setRemoteDescription(oe)}}else h.a.warn(`Received SDP when already connected: ${se}`)})}send(A,x){const q=this.getChannelFromLabel(x.channelLabel);q?this.sendOnChannel(q,A):h.a.warn("Send called with unexpected channel label",{channelLabel:x.channelLabel})}controlRemoteStream(A){var x;this.sendSystemMessage((ee(x=this.reliableStreamChannel),x),{type:"stream-control",streamControl:A})}isActive(){return new Set(["new","checking","connected","completed"]).has(this.peerConnection.iceConnectionState)||this.isReady()}isReady(){const{reliableStreamChannel:A,latestTtlStreamChannel:x,latestTryOnceStreamChannel:q,latestReliableStreamChannel:oe}=this;return(A==null?void 0:A.readyState)==="open"&&(x==null?void 0:x.readyState)==="open"&&(q==null?void 0:q.readyState)==="open"&&(oe==null?void 0:oe.readyState)==="open"}close(){var A,x,q,oe,se,de,he;return ot(this,void 0,void 0,function*(){this.closeCalled||(this.closeCalled=!0,yield(A=this.sessionMetrics)===null||A===void 0?void 0:A.uploadMetrics(),ct(this.pingUpdateTimeout),ct(this.pingV2UpdateTimeout),ct(this.pingV2MetricsGatherTimeout),ct(this.reassemblyTableCleanupTimeout),ct(this.streamsInfoUpdateTimeout),ct(this.heartbeatTimeout),(x=this._peerConnection)===null||x===void 0||x.close(),(q=this.heartbeatChannel)===null||q===void 0||q.close(),(oe=this.latestReliableStreamChannel)===null||oe===void 0||oe.close(),(se=this.latestTryOnceStreamChannel)===null||se===void 0||se.close(),(de=this.latestTtlStreamChannel)===null||de===void 0||de.close(),(he=this.reliableStreamChannel)===null||he===void 0||he.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 A;return(A=this.config.remoteConfig)===null||A===void 0?void 0:A.sessionCreatedTimestamp}setSessionCreatedTimestamp(A){this.config.remoteConfig&&(this.config.remoteConfig.sessionCreatedTimestamp=A)}getSessionId(){var A;return(A=this.config.remoteConfig)===null||A===void 0?void 0:A.sessionId}setSessionId(A){this.config.remoteConfig&&(this.config.remoteConfig.sessionId=A,this.sessionMetrics=new Le(A,this))}getRemotePeerId(){return this.config.baseConfig.remotePeerId}getRemoteDeviceId(){var A;return(A=this.config.baseConfig)===null||A===void 0?void 0:A.remoteDeviceId}setRemoteDeviceId(A){this.config.baseConfig.remoteDeviceId=A}getSessionMetricsMessageCounts(){var A;return(A=this.sessionMetrics)===null||A===void 0?void 0:A.counts}getConnectionStatsInfo(){return ot(this,void 0,void 0,function*(){const{peerConnection:A}=this;if(!A)return;const x=yield A.getStats(null),q=[];x.forEach(pe=>{q.push(pe)});const oe=q.find(pe=>pe.type==="transport");if(!oe)return;const se=q.find(pe=>(pe.type==="candidate-pair"||pe.type==="candidatepair")&&pe.id===oe.selectedCandidatePairId);if(!se)return;const de=q.find(pe=>pe.id===se.localCandidateId),he=q.find(pe=>pe.id===se.remoteCandidateId);return de&&he&&(de.address=de.address||de.ip,he.address=he.address||he.ip,de.address!==void 0&&he.address!==void 0)?{transport:oe,localCandidate:de,remoteCandidate:he}:void 0})}initializeChannels(A){this.heartbeatChannel=A.createDataChannel("heartbeat",Te),this.heartbeatChannel.binaryType="arraybuffer",this.latestTtlStreamChannel=A.createDataChannel("stream.latest-ttl",ne),this.latestTtlStreamChannel.binaryType="arraybuffer",this.reliableStreamChannel=A.createDataChannel("stream.reliable",ie),this.reliableStreamChannel.binaryType="arraybuffer",this.latestReliableStreamChannel=A.createDataChannel("stream.latest-reliable",ce),this.latestReliableStreamChannel.binaryType="arraybuffer",this.latestTryOnceStreamChannel=A.createDataChannel("stream.latest-try-once",Se),this.latestTryOnceStreamChannel.binaryType="arraybuffer",this.setupChannel(this.latestTtlStreamChannel),this.setupChannel(this.reliableStreamChannel),this.setupChannel(this.latestReliableStreamChannel),this.setupChannel(this.latestTryOnceStreamChannel)}getOffer(){var A,x;return ot(this,void 0,void 0,function*(){const{gotOffer:q}=this,{peerConnection:oe,config:se}=this;if(this.config.baseConfig.isLan)throw new Error('"getOffer" method can only be called with internet connections. LAN connections should call the "getLanOffer" method.');const de=(A=this.config.remoteConfig)===null||A===void 0?void 0:A.sessionId;if(q)return void h.a.debug("Failed to generate offer because gotOffer was already called.");if(this.gotOffer=!0,Rt(this.peerConnection))return void h.a.debug("Failed to generate offer because the peer connection was inactive.");const he=se.baseConfig.track;oe.onicecandidate=()=>{this.hasIceCandidate=!0},oe.oniceconnectionstatechange=()=>ot(this,void 0,void 0,function*(){const We=oe.iceConnectionState;if(We==="connected"||We==="completed"){const je=yield this.getConnectionStatsInfo(),Pe=je?Qt(je):void 0;h.a.info(`ICE connection state changed to ${We}`,{sessionId:de,connectionStatsInfo:je,iceMode:Pe}),he==null||he("ICE connection state change",{iceConnectionState:We,sessionId:de,connectionStatsInfo:je,iceMode:Pe})}}),yield oe.setLocalDescription(yield oe.createOffer());const pe=oe.getConfiguration?oe.getConfiguration().iceTransportPolicy:"all",Ue=new Date().getTime();for(;;){const We=new Date().getTime()-Ue;if(We>this.connectTimeoutMs)return void h.a.debug("Failed to generate offer because ICE gathering timed out.");if(We>this.iceGatheringTimeoutMs&&this.hasIceCandidate){h.a.debug("ICE gathering partially completed; proceeding",{iceTransportPolicy:pe,waitTime:We}),he==null||he("ICE gathering partially completed",{sessionId:de,iceTransportPolicy:pe,waitTime:We});break}if(oe.iceGatheringState==="complete"){h.a.debug("ICE gathering complete",{iceTransportPolicy:pe,waitTime:We}),he==null||he("ICE gathering completed",{sessionId:de,iceTransportPolicy:pe,waitTime:We});break}yield Object(u.a)(.1*d.a.second)}const le=(x=this.iceServers)!==null&&x!==void 0?x:[];for(const We of le)"credentialType"in We&&(We.credentialType=void 0);const me=JSON.stringify(le),Je=new _.Signal;return Je.setPayload(JSON.stringify(oe.localDescription)),Je.setSenderId(this.config.baseConfig.localPeerId),Je.setReceiverId(this.config.baseConfig.remotePeerId),Je.setIceServers(me),Je.setIceTransportPolicy(pe!=null?pe:"all"),this.config.baseConfig.sessionType!==void 0?Je.setSessionType(this.config.baseConfig.sessionType):Je.setSessionType(_.SessionType.TELEOP),h.a.debug("Sending offer signal with description",{description:Je.getPayload()}),Je})}getLanOffer(){return ot(this,void 0,void 0,function*(){const{peerConnection:A,gotOffer:x}=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(x)return void h.a.debug("Failed to generate offer because gotOffer was already called.");if(this.gotOffer=!0,Rt(this.peerConnection))return void h.a.debug("Failed to generate offer because the peer connection was inactive.");yield A.setLocalDescription(yield A.createOffer());const q=new Date().getTime();for(;;){if(new Date().getTime()-q>this.iceGatheringTimeoutMs)return void h.a.debug("Failed to generate offer because ICE gathering timed out.");if(A.iceGatheringState==="complete")break;yield Object(u.a)(.1*d.a.second)}const oe=A.localDescription;if(oe)return h.a.debug("Sending LAN offer signal with description",{description:oe}),oe;h.a.error("Failed to generate LAN offer description")})}handleLanAnswer(A){return ot(this,void 0,void 0,function*(){const{peerConnection:x}=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 x.setRemoteDescription(A)})}getChannelFromLabel(A){switch(A){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(A,x){var q;let oe;try{oe=Object(H.encode)(JSON.stringify(x))}catch(se){return void h.a.warn("Failed to encode RTC message",{error:se})}try{A.send(oe),(q=this.sessionMetrics)===null||q===void 0||q.incrementLocalSent(x)}catch(se){h.a.warn("Failed to send message to channel",{error:se,channel:A.label})}}channelNotRecognized(A){return A!==this.latestTtlStreamChannel&&A!==this.latestReliableStreamChannel&&A!==this.latestTryOnceStreamChannel&&A!==this.reliableStreamChannel}setupChannel(A){A.onmessage=x=>{if(this.channelNotRecognized(A))return void h.a.warn("Received message on unrecognized data channel.");let q;try{q=JSON.parse(Object(H.decode)(x.data))}catch(oe){return void h.a.warn("Received unparseable message on RTC stream data channel",{error:oe,channel:A.label})}q.communicationType==="message-chunk"?this.receiveChannelMessageChunk(A,q):this.receiveChannelMessage(A,q)},A.onerror=x=>{h.a.warn(`Channel error: ${x.error}`,{error:x.error,sessionId:this.getSessionId(),channelLabel:A.label})},A.onopen=()=>{h.a.debug("Channel opened",{sessionId:this.getSessionId(),channelLabel:A.label})},A.onclose=()=>{const x={bufferedAmount:A.bufferedAmount,sessionId:this.getSessionId(),channelLabel:A.label};this.closeCalled===!1?h.a.debug("Unexpected channel closed",x):h.a.debug("Channel closed",x)}}receiveChannelMessage(A,x){var q;const{config:oe}=this,{remotePeerId:se}=this.config.baseConfig;this.lastMessageTimestamp=new Date().getTime(),x=Et(x),(q=this.sessionMetrics)===null||q===void 0||q.incrementLocalReceived(x),this.handleSystemMessage(A,x)||(A===this.latestTryOnceStreamChannel||A===this.latestTtlStreamChannel||A===this.latestReliableStreamChannel)&&!this.isLatestMessage(x)||oe.baseConfig.receive(se,x)}receiveChannelMessageChunk(A,x){const q=this.reassemblyTable.get(x.id)||[];if(q.push(x),q.length===x.total){const oe=function(se){const de=se.sort((he,pe)=>he.seq<pe.seq?-1:1).map(he=>he.part).reduce((he,pe)=>he+pe);try{return JSON.parse(de)}catch{return void h.a.warn("Could not reassemble RTC message chunks")}}(q);return oe&&this.receiveChannelMessage(A,oe),void this.reassemblyTable.delete(x.id)}this.reassemblyTable.set(x.id,q),this.reassemblyTableLastTimestamp.set(x.id,new Date().getTime())}handleSystemMessage(A,x){var q,oe;const{config:se}=this,{baseConfig:de}=se,{remotePeerId:he,remoteDeviceId:pe}=de;switch(x.header.stream.streamType){case"ping":return this.sendSystemMessage(A,{type:"pong",timestamp:te(x.payload.ping)}),!0;case"pong":{const Ue=new Date().getTime()-te(x.payload.pong);return this.pingTimeMs=Ue,Q.aggregate("rtc-ping-time",Ue,Object.assign({},pe?{deviceId:pe}:{})),!0}case"ping-v2":return this.sendPingV2(),!0;case"pong-v2":{const Ue=te(x.payload.pongV2),le=this.pingV2Map.get(Ue.id);return(le==null?void 0:le.sent)!==Ue.timestamp&&h.a.warn("Pong timestamp doesn't match stored value",{currentEntry:le,pong:Ue}),this.pingV2Map.set(Ue.id,{sent:Ue.timestamp,received:new Date().getTime()}),!0}case"streams-info":{const{sessionMetrics:Ue}=this,le=(q=x.payload.streamsInfo)===null||q===void 0?void 0:q.timestamp;return!!le&&(Ue==null||Ue.updateRemoteMessagesCounts(x),(oe=de.onStreamsInfoUpdate)===null||oe===void 0||oe.call(de,he,le),!0)}case"stream-control":return!0;default:return!1}}sendSystemMessage(A,x){var q;const{localUserId:oe,localPeerId:se}=this.config.baseConfig;if(A.readyState!=="open")return;const de={entityId:oe!=null?oe:se,streamName:`$.${x.type}`,streamType:x.type};let he;switch(x.type){case"ping":he={ping:new Date().getTime()};break;case"pong":he={pong:x.timestamp};break;case"ping-v2":he={pingV2:x.payload};break;case"pong-v2":he={pongV2:x.payload};break;case"stream-control":he={streamControl:x.streamControl};break;case"streams-info":he={streamsInfo:(q=this.sessionMetrics)===null||q===void 0?void 0:q.getLocalStreamsInfo(new Date().getTime())}}this.sendOnChannel(A,et(de,he))}isLatestMessage(A){const x=_e(A.header.stream),q=(this.streamLatestTimestamp.get(x)||0)<=A.header.created;return q&&this.streamLatestTimestamp.set(x,A.header.created),q}}function ct(Re){Re&&clearInterval(Re)}function kt(){h.a.debug("forceGarbageCollection() triggered"),queueMicrotask(()=>{let Re=document.createElement("img");Re.src=window.URL.createObjectURL(new Blob([new ArrayBuffer(5e7)])),Re.onerror=function(){window.URL.revokeObjectURL(this.src),Re=null}})}function Wt(Re){try{return Re instanceof Error?`${Re.name}: ${Re.message}`:typeof Re=="object"?JSON.stringify(Re):String(Re)}catch{return"Unknown error"}}function vt(Re){var A,x;return{userId:(A=Re.getUserId())===null||A===void 0?void 0:A.getValue(),deviceId:(x=Re.getDeviceId())===null||x===void 0?void 0:x.getValue(),organizationId:Re.getOrganizationId(),id:Re.getPeerId(),capabilities:[],capabilitySet:{}}}var De=function(Re,A,x,q){return new(x||(x=Promise))(function(oe,se){function de(Ue){try{pe(q.next(Ue))}catch(le){se(le)}}function he(Ue){try{pe(q.throw(Ue))}catch(le){se(le)}}function pe(Ue){var le;Ue.done?oe(Ue.value):(le=Ue.value,le instanceof x?le:new x(function(me){me(le)})).then(de,he)}pe((q=q.apply(Re,A||[])).next())})};const dt=Re=>Re.map(A=>Object.assign(Object.assign(Object.assign({},A),A.username?{username:"<REDACTED>"}:null),A.credential?{credential:"<REDACTED>"}:null));class At{constructor(A){this.config=A,this.grpcCallDeadline=5*d.a.second,this.refreshIntervalDelayMs=2*d.a.second,this.iceServersTtl=30*d.a.minute,this.connections=[],this.localConnections=[],this.isConnectionInitiator=new WeakSet,this.isOutgoingConnection=new Set,this.peerDataChannelListeners=[],this.rtcInstancesConstructed=0,this.statsLoopsExecuted=0;const{refreshIntervalDelayMs:x}=this;this.refreshInterval=F({func:()=>De(this,void 0,void 0,function*(){try{yield this.update()}catch(q){h.a.warn("RTC refresh failed",{error:q})}}),delay:x,immediate:!0})}send(A,x,q){const oe=this.getActiveConnection(A);oe?oe.isReady()?oe.send(x,q):h.a.warn("Send called with unready connection."):h.a.warn("Send called with no connection.")}controlRemoteStream(A,x){const q=this.getActiveConnection(A);q?q.isReady()?q.controlRemoteStream(x):h.a.warn("controlRemoteStream called with unready connection."):h.a.warn("controlRemoteStream called with no connection.")}getLocalPeer(){return De(this,void 0,void 0,function*(){for(;!this.localPeer;)yield Object(u.a)(.1*d.a.second);return vt(this.localPeer)})}connect(A,x){var q,oe,se;return De(this,void 0,void 0,function*(){if(this.config.lanOnlyMode===!0)throw new Error("connect method called in local only mode.");const{track:de,signalingClient:he}=this.config,{localPeer:pe,receiveSignalStream:Ue,iceServers:le}=this;if(!pe||!Ue||!le)return void h.a.warn("Connect called prior to local peer, receiveSignalStream, and ICE servers ready");if(this.getActiveConnection(A))return void h.a.warn("Connect called for peer with existing connection.");if(this.isOutgoingConnection.has(A))return void h.a.warn("Connect called for peer with an existing outgoing connection offer.");this.isOutgoingConnection.add(A);const me=function(Ze,Me,ze){const{rtcIceTransportPolicies:Ye,rtcIceServerProtocol:Xe,useAllServers:Ke}=Me||{},st=Ze.map(at=>Object.assign(Object.assign({},at),{urls:at.urls.filter(ht=>{const Zt=(Ye===void 0||Ye.some(Tt=>C(ht,Tt)))&&(Xe===void 0||S(ht,Xe));return Zt||h.a.debug(`Ignoring ICE server: ${ht}`,{organizationId:ze}),Zt})})).filter(({urls:at})=>at.filter(ht=>ht).length>0);return Ke?st:[M(st,"stun"),M(st,"turn")].filter(at=>at!==void 0).map(at=>te(at))}(le,x);h.a.debug("Received ICE servers:",dt(le)),h.a.debug("Using ICE servers:",dt(me));const Je=new gt(yield this.createRTCPeerConnection(me),me,{baseConfig:{isOffer:!0,isLan:!1,receive:(Ze,Me)=>this.config.receive(Ze,Me),onStreamsInfoUpdate:this.config.onStreamsInfoUpdate?(Ze,Me)=>{var ze,Ye;return(Ye=(ze=this.config).onStreamsInfoUpdate)===null||Ye===void 0?void 0:Ye.call(ze,Ze,Me)}:void 0,track:this.config.lanOnlyMode?void 0:this.config.track,localUserId:(q=pe.getUserId())===null||q===void 0?void 0:q.getValue(),localPeerId:pe.getPeerId(),remotePeerId:A,sessionType:this.config.sessionType},remoteConfig:{}},Ze=>this.onCustomDataChannel(A,Ze)),We=yield Je.getOffer();if(!We)return h.a.error("Failed to generate offer."),void this.isOutgoingConnection.delete(A);h.a.debug("Sending offer."),de==null||de("Sending offer",We);const je=new _.SendSignalRequest;je.setSignal(We);const Pe=yield(()=>De(this,void 0,void 0,function*(){try{return yield X.withDeadline(he.sendSignal(je,yield this.getMetadata()),this.grpcCallDeadline)}catch(Ze){h.a.warn("Error when sending signal",{error:Ze})}}))();if(!this.isOutgoingConnection.has(A))return void h.a.debug("No offer set after receiving offer signal response.");h.a.debug("Offer sent.");const He=(oe=Pe==null?void 0:Pe.getSessionId())===null||oe===void 0?void 0:oe.getValue(),qe=(se=Pe==null?void 0:Pe.getSessionCreatedTimestamp())===null||se===void 0?void 0:se.getValue();return He&&qe?(Je.setSessionId(He),Je.setSessionCreatedTimestamp(qe),this.isOutgoingConnection.delete(A),this.connections.push(Je),this.isConnectionInitiator.add(Je),this.setupHandlers(Je),He):(h.a.warn("No session ID or no session created timestamp on send signal response."),void this.isOutgoingConnection.delete(A))})}connectLan(A){var x,q;return De(this,void 0,void 0,function*(){const oe=new E(A),se=new gt(yield this.createRTCPeerConnection([]),[],{baseConfig:{isOffer:!0,isLan:!0,receive:(Ue,le)=>this.config.receive(Ue,le),onStreamsInfoUpdate:this.config.onStreamsInfoUpdate?(Ue,le)=>{var me,Je;return(Je=(me=this.config).onStreamsInfoUpdate)===null||Je===void 0?void 0:Je.call(me,Ue,le)}:void 0,track:this.config.lanOnlyMode?void 0:this.config.track,localUserId:(q=(x=this.localPeer)===null||x===void 0?void 0:x.getUserId())===null||q===void 0?void 0:q.getValue(),localPeerId:"lan_client",remotePeerId:A}},Ue=>this.onCustomDataChannel(A,Ue)),de=yield se.getLanOffer();if(!de)return h.a.warn("Could not generate LAN offer"),!1;const he=yield oe.postLanRtcOffer({offer:JSON.stringify(de)}),pe=new RTCSessionDescription(JSON.parse(he.answer));return yield se.handleLanAnswer(pe),this.localConnections.push(se),this.isConnectionInitiator.add(se),Object(T.a)()})}getConnections(){return[...this.connections,...this.localConnections]}createCustomDataChannel(A,x,q,oe,se){const de=this.getActiveConnection(A);if(de&&this.isConnectionInitiator.has(de)){const pe=de.peerConnection.createDataChannel("custom."+x,q);return oe&&(pe.binaryType="arraybuffer"),se(A,pe),()=>{}}const he=(pe,Ue)=>{A===pe&&Ue.label==="custom."+x&&se(A,Ue)};return this.peerDataChannelListeners.push(he),()=>{this.peerDataChannelListeners=this.peerDataChannelListeners.filter(pe=>pe!==he)}}onCustomDataChannel(A,x){this.peerDataChannelListeners.forEach(q=>q(A,x))}getConnectionStatus(A){if(this.isOutgoingConnection.has(A))return"connecting";const x=this.getActiveConnection(A);return x?x.isReady()?"connected":"connecting":"disconnected"}getConnectionStatsInfo(A){return De(this,void 0,void 0,function*(){const x=this.getActiveConnection(A);if(x)return yield x.getConnectionStatsInfo()})}disconnect(A){return De(this,void 0,void 0,function*(){const x=this.getActiveConnection(A);x&&(yield x.close(),this.connections=this.connections.filter(q=>q!==x),this.localConnections=this.localConnections.filter(q=>q!==x))})}getPeers(){return De(this,void 0,void 0,function*(){if(this.config.lanOnlyMode)throw new Error("getPeers method cannot be used in local-only mode.");const{signalingClient:A}=this.config,x=yield(()=>De(this,void 0,void 0,function*(){try{return yield X.withDeadline(A.getPeers(new _.GetPeersRequest,yield this.getMetadata()),this.grpcCallDeadline)}catch(se){h.a.warn("Error when getting peers",{error:se})}}))();if(!x)return[];const q=x.getPeersList();if(!q)return[];const oe=se=>{var de,he;return(he=(de=se.getPeerCreatedTimestamp())===null||de===void 0?void 0:de.getValue())!==null&&he!==void 0?he:0};return q.sort((se,de)=>oe(de)-oe(se)).map(se=>vt(se))})}getSessions(){return De(this,void 0,void 0,function*(){if(this.config.lanOnlyMode)throw new Error("getPeers method cannot be used in local-only mode.");const{signalingClient:A}=this.config,x=yield(()=>De(this,void 0,void 0,function*(){try{return yield X.withDeadline(A.getPeers(new _.GetPeersRequest,yield this.getMetadata()),this.grpcCallDeadline)}catch(se){h.a.warn("Error when getting peers",{error:se})}}))();if(!x)return{};const q=x.getPeersList(),oe={};for(const se of q)oe[se.getPeerId()]=se.getSessionIdsList();return oe})}getPing(A){const x=this.getActiveConnection(A);if(x)return x.getPing();h.a.warn("Attempted to get ping time from inactive peer.")}getPingInfo(A){const x=this.getActiveConnection(A);if(x)return x.getPingInfo();h.a.warn("Attempted to get ping time from inactive peer.")}getLastMessageTimestamp(A){const x=this.getActiveConnection(A);if(x)return x.getLastMessageTimestamp();h.a.warn("Attempted to get last message time from inactive peer.")}getSessionMetricsMessageCounts(A){const x=this.getActiveConnection(A);if(x)return x.getSessionMetricsMessageCounts();h.a.warn("Attempted to get session metrics counts from inactive peer.")}isReady(){if(this.config.lanOnlyMode)return!0;const{localPeer:A,receiveSignalStream:x,iceServers:q}=this;return!!(A&&x&&q)}shutdown(){return De(this,void 0,void 0,function*(){h.a.info("Shutdown called on RTC client"),yield this.refreshInterval.stop(),this.receiveSignalStream&&this.receiveSignalStream.cancel();const A=this.connections;this.connections=[],yield this.closeConnections(A);const x=this.localConnections;this.localConnections=[],yield this.closeConnections(x),this.isOutgoingConnection.clear(),this.peerDataChannelListeners=[];const{localPeer:q}=this;if(!q||this.config.lanOnlyMode)return;const{signalingClient:oe}=this.config;yield(()=>De(this,void 0,void 0,function*(){try{const se=new _.DeletePeerRequest;se.setPeerId(q.getPeerId()),yield X.withDeadline(oe.deletePeer(se,yield this.getMetadata()),this.grpcCallDeadline)}catch(se){return void h.a.warn("Error deleting local peer",{error:se})}}))()})}createPeer(){return De(this,void 0,void 0,function*(){if(this.config.lanOnlyMode)throw new Error("createPeer method cannot be used in local-only mode.");const{signalingClient:A}=this.config,x=yield(()=>De(this,void 0,void 0,function*(){try{return yield X.withDeadline(A.createPeer(new _.CreatePeerRequest,yield this.getMetadata()),this.grpcCallDeadline)}catch(oe){const se=oe;h.a.debug("createPeer failed",{error:se});const de=Wt(se);throw new Error(`Was not able to create peer: ${de}`)}}))(),q=x==null?void 0:x.getPeer();if(!q)throw new Error("Response did not provide peer.");return this.localPeer=q})}createReceiveSignalStream(){return De(this,void 0,void 0,function*(){if(this.config.lanOnlyMode)throw new Error("createReceiveSignalStream method cannot be used in local-only mode.");const{signalingClient:A}=this.config,{localPeer:x,iceServers:q}=this;if(!x||!q)return;const{receiveSignalStream:oe}=this;oe&&oe.cancel();const se=new _.ReceiveSignalStreamRequest;se.setPeerId(x.getPeerId());const de=yield(()=>De(this,void 0,void 0,function*(){try{return A.receiveSignalStream(se,yield this.getMetadata({hasDeadline:!1}))}catch(he){h.a.debug("createReceiveSignalStream failed",{error:he});const pe=Wt(he);throw new Error(`Unable to create receive signal stream: ${pe}`)}}))();if(!de)throw new Error("Response did not provide stream.");return de.on("data",he=>De(this,void 0,void 0,function*(){var pe,Ue,le,me;const Je=he.getSignal(),We=(pe=Je==null?void 0:Je.getSessionId())===null||pe===void 0?void 0:pe.getValue(),je=Je==null?void 0:Je.getSenderId(),Pe=Je==null?void 0:Je.getReceiverId(),He=(Ue=Je==null?void 0:Je.getSessionCreatedTimestamp())===null||Ue===void 0?void 0:Ue.getValue();if(!(Je&&We&&je&&Pe&&He))return void h.a.warn("Received signal with missing information.");const qe=this.getActiveConnection(je);if(qe)if(qe.getSessionId()!==We){if(h.a.debug("Received signal: different session for a peer we're already connected to."),(qe.getSessionCreatedTimestamp()||0)>He)return;const Ze=new gt(yield this.createRTCPeerConnection(q),q,{baseConfig:{isOffer:!1,isLan:!1,receive:(Me,ze)=>this.config.receive(Me,ze),onStreamsInfoUpdate:this.config.onStreamsInfoUpdate?(Me,ze)=>{var Ye,Xe;return(Xe=(Ye=this.config).onStreamsInfoUpdate)===null||Xe===void 0?void 0:Xe.call(Ye,Me,ze)}:void 0,track:this.config.lanOnlyMode?void 0:this.config.track,localPeerId:x.getPeerId(),localUserId:(me=x.getUserId())===null||me===void 0?void 0:me.getValue(),remotePeerId:je},remoteConfig:{sessionId:We,sessionCreatedTimestamp:He}},Me=>this.onCustomDataChannel(je,Me));yield Ze.handleSignal(Je),this.connections.push(Ze)}else h.a.debug("Received signal: for an existing connection."),yield qe.handleSignal(Je);else{h.a.debug("Received signal: new connection.");const Ze=new gt(yield this.createRTCPeerConnection(q),q,{baseConfig:{isOffer:!1,isLan:!1,receive:(Me,ze)=>this.config.receive(Me,ze),onStreamsInfoUpdate:this.config.onStreamsInfoUpdate?(Me,ze)=>{var Ye,Xe;return(Xe=(Ye=this.config).onStreamsInfoUpdate)===null||Xe===void 0?void 0:Xe.call(Ye,Me,ze)}:void 0,track:this.config.lanOnlyMode?void 0:this.config.track,localPeerId:x.getPeerId(),localUserId:(le=x.getUserId())===null||le===void 0?void 0:le.getValue(),remotePeerId:je},remoteConfig:{sessionId:We,sessionCreatedTimestamp:He}},Me=>this.onCustomDataChannel(je,Me));yield Ze.handleSignal(Je),this.connections.push(Ze)}})),de.on("end",()=>{de.cancel(),this.receiveSignalStream=void 0}),de.on("error",he=>{switch(he.code){case k.StatusCode.CANCELLED:case k.StatusCode.UNAVAILABLE:case k.StatusCode.UNKNOWN:h.a.debug("Receive signal stream error",{error:he});break;case k.StatusCode.UNAUTHENTICATED:h.a.warn("Receive signal stream error",{error:he});break;default:h.a.error("Receive signal stream error",{error:he})}de.cancel(),this.receiveSignalStream=void 0}),this.receiveSignalStream=de})}createRTCPeerConnection(A){var x;return De(this,void 0,void 0,function*(){const q=(x=this.config.alternateRTCPeerConnection)!==null&&x!==void 0?x:window.RTCPeerConnection;if(!q)throw function(){const{userAgent:oe}=navigator;return oe.includes("Firefox/")?"Firefox":oe.includes("Edg/")?"Edge":oe.includes("Chrome/")?"Chrome":oe.includes("Safari/")?"Safari":oe.includes("MSIE/")||oe.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||kt();try{return new q({iceServers:A})}catch(oe){throw h.a.debug(`Failed to create RTCPeerConnection: ${this.rtcInstancesConstructed} total allocated`),oe}})}closeConnections(A){return De(this,void 0,void 0,function*(){const x=yield G(A.map(q=>De(this,void 0,void 0,function*(){yield q.close()})));for(const q of x)h.a.warn("Request to close session failed",{error:q})})}getActiveConnection(A){return this.getConnections().find(x=>x.getRemotePeerId()===A&&x.isActive())}update(){var A;return De(this,void 0,void 0,function*(){if(this.localConnections=this.localConnections.filter(me=>me.isActive()),this.config.lanOnlyMode)return;const{signalingClient:x}=this.config;if(!this.localPeer||!this.receiveSignalStream||!this.iceServers){const me=[];return this.localPeer||me.push(this.createPeer()),this.iceServers||me.push(this.updateIceServers()),yield Promise.all(me),void(this.receiveSignalStream||(yield this.createReceiveSignalStream()))}const[q,oe]=(se=this.connections,de=me=>me.isActive(),se.reduce((me,Je,We,je)=>{const[Pe,He]=me;return(de(Je,We,je)?Pe:He).push(Je),me},[[],[]]));var se,de;yield this.closeConnections(oe),this.connections=q,this.gatherConnectionStats().catch(me=>{h.a.warn("Error calling gatherConnectionStats",{error:me})}),this.statsLoopsExecuted++;const{localPeer:he}=this,pe=this.connections.filter(me=>me.getSessionId).map(me=>te(me.getSessionId()));he.setSessionIdsList(pe);const Ue=new _.RefreshPeerRequest;Ue.setPeer(he);try{yield X.withDeadline(x.refreshPeer(Ue,yield this.getMetadata()),this.grpcCallDeadline)}catch(me){me instanceof k.RpcError&&me.code===k.StatusCode.NOT_FOUND?(h.a.warn("Peer expired, creating new peer",{peerId:he.getPeerId()}),yield this.reset()):h.a.warn("Error calling RefreshPeer",{error:me})}const le=yield this.getPeers();for(const me of this.connections)me.setRemoteDeviceId((A=le.find(Je=>Je.id===me.getRemotePeerId()))===null||A===void 0?void 0:A.deviceId)})}gatherConnectionStats(){return De(this,void 0,void 0,function*(){if(this.statsLoopsExecuted%10!=0||this.connections.length!==1)return;const A=yield this.connections[0].getConnectionStatsInfo(),x=A?Qt(A):void 0;x?(h.a.info(`Detected RTC connection type: ${x}`),Q.setTag("rtc-connection-type",x)):Q.setTag("rtc-connection-type","unknown")})}reset(){return De(this,void 0,void 0,function*(){yield this.closeConnections(this.connections),this.connections=[],this.isOutgoingConnection.clear(),yield this.createPeer(),yield this.createReceiveSignalStream()})}updateIceServers(){return De(this,void 0,void 0,function*(){if(this.config.lanOnlyMode)return;const{iceServersLastUpdate:A,iceServersTtl:x}=this,q=new Date().getTime();if(!A||q-A>x)try{const oe=(yield X.withDeadline(this.config.signalingClient.getIceServers(new _.GetIceServersRequest,yield this.getMetadata()),this.grpcCallDeadline)).getIceServers();this.iceServers=JSON.parse(oe),this.iceServersLastUpdate=q}catch(oe){h.a.warn("Error in updateIceServers",{error:oe})}})}setupHandlers(A){const{peerConnection:x}=A,q=A.getSessionCreatedTimestamp();x.onconnectionstatechange=()=>De(this,void 0,void 0,function*(){const oe=x.connectionState;if(!q)return;const se=A.getRemoteDeviceId();switch(oe){case"connected":Q.aggregate("rtc-connect-time",new Date().getTime()-q,Object.assign({},se?{deviceId:se}:{}));break;case"failed":Q.increment("rtc-connect-failed",Object.assign({},se?{deviceId:se}:{}))}})}getMetadata(A={}){return De(this,void 0,void 0,function*(){if(this.config.lanOnlyMode)throw new Error("getMetadata method cannot be called in local-only mode");const{getToken:x}=this.config,{grpcCallDeadline:q}=this,{hasDeadline:oe=!0}=A,se=oe?{deadline:(Date.now()+q).toString(10)}:null;try{const de=yield x();return Object.assign({authorization:de},se)}catch(de){throw h.a.error("getToken() failed",{error:de}),new Error("Cannot get authorization token")}})}}var tt=n(12),Ft=n(11),Bt=function(Re,A,x,q){return new(x||(x=Promise))(function(oe,se){function de(Ue){try{pe(q.next(Ue))}catch(le){se(le)}}function he(Ue){try{pe(q.throw(Ue))}catch(le){se(le)}}function pe(Ue){var le;Ue.done?oe(Ue.value):(le=Ue.value,le instanceof x?le:new x(function(me){me(le)})).then(de,he)}pe((q=q.apply(Re,A||[])).next())})};class It{constructor(A,x){this.sentMessagesCounts=new Map,this.receivedMessagesCounts=new Map,this.sessionId=A,this.connection=x}incrementMessageSent(A){const x=_e(A.header.stream);this.sentMessagesCounts.set(x,(this.sentMessagesCounts.get(x)||0)+1)}incrementMessageReceived(A){const x=_e(A.header.stream);this.receivedMessagesCounts.set(x,(this.receivedMessagesCounts.get(x)||0)+1)}uploadMetrics(){return Bt(this,void 0,void 0,function*(){const{sessionId:A}=this,x=yield this.connection.peerConnection.getStats(),q={};x.forEach(se=>q[se.id]=se),h.a.debug("rtc-stats",Object.assign(Object.assign({},q),{sessionId:A}));const oe=[...new Set(Array.from(this.sentMessagesCounts.keys()).concat(Array.from(this.receivedMessagesCounts.keys())))].reduce((se,de)=>{const he=this.sentMessagesCounts.get(de),pe=this.receivedMessagesCounts.get(de);return Object.assign(Object.assign({},se),{[`${de}-sent`]:he,[`${de}-received`]:pe})},{sessionId:A});h.a.debug("rtc-message-report",oe)})}}function Ct(Re,A){return _e(Re)===_e(A)}var nt=function(Re,A,x,q){return new(x||(x=Promise))(function(oe,se){function de(Ue){try{pe(q.next(Ue))}catch(le){se(le)}}function he(Ue){try{pe(q.throw(Ue))}catch(le){se(le)}}function pe(Ue){var le;Ue.done?oe(Ue.value):(le=Ue.value,le instanceof x?le:new x(function(me){me(le)})).then(de,he)}pe((q=q.apply(Re,A||[])).next())})};class St{constructor(A,x){this.peerConnection=A,this.config=x,this.connectTimeoutMs=10*d.a.second,this.gatherIceTimeoutMs=5*d.a.second,this.pingUpdateTimeoutMs=2*d.a.second,this.streamLatestTimestamp=new Map,this.closeCalled=!1,this.connectCalled=!1,this.sentOffer=!1,this.receivedIceCandidate=!1;const{isOffer:q}=x;q?this.initializeChannels(A):A.ondatachannel=oe=>{switch(oe.channel.label){case"stream.latest-ttl":this.latestTtlStreamChannel=oe.channel;break;case"stream.reliable":this.reliableStreamChannel=oe.channel;break;case"stream.latest-reliable":this.latestReliableStreamChannel=oe.channel;break;case"stream.latest-try-once":this.latestTryOnceStreamChannel=oe.channel}this.setupChannel(oe.channel)},this.sessionMetrics=new It(this.getSessionId(),this)}connect(){return nt(this,void 0,void 0,function*(){if(this.connectCalled)return;this.connectCalled=!0,this.pingUpdateTimeout=setInterval(()=>{const{reliableStreamChannel:oe}=this;oe&&this.sendSystemMessage(oe,{type:"ping"})},this.pingUpdateTimeoutMs),this.connectTimeout=setTimeout(()=>nt(this,void 0,void 0,function*(){this.isReady()||(h.a.warn("RTC connect timed out, closing connection"),yield this.close())}),this.connectTimeoutMs);const{peerConnection:A,config:{isOffer:x,sessionId:q}}=this;if(x){const oe=yield A.createOffer();yield A.setLocalDescription(oe)}x&&(this.gatherIceTimeout=setTimeout(()=>nt(this,void 0,void 0,function*(){this.sentOffer||(h.a.warn("ICE gathering timed out"),this.receivedIceCandidate?(h.a.warn("Attempting to connect with partial ICE candidate pool"),yield this.sendOffer()):yield this.close())}),this.gatherIceTimeoutMs),A.onicecandidate=oe=>nt(this,void 0,void 0,function*(){oe.candidate?this.receivedIceCandidate=!0:yield this.sendOffer()}),A.onicegatheringstatechange=()=>nt(this,void 0,void 0,function*(){A.iceGatheringState==="complete"&&(yield this.sendOffer())}),A.onnegotiationneeded=()=>{h.a.debug("Negotiation needed",{sessionId:q})})})}handleSignal(A){return nt(this,void 0,void 0,function*(){const{peerConnection:x,config:{sessionId:q,sendSignal:oe}}=this,{description:se}=JSON.parse(A.payload);if(h.a.debug("Handling signal",{sessionId:q,description:JSON.stringify(se)}),se)if(x.signalingState!=="stable"||x.connectionState!=="connected")if(x.remoteDescription)h.a.warn(`Received SDP signal during negotiation when remote description is already set: ${JSON.stringify(A)}`);else if(se.type==="offer"){yield x.setRemoteDescription(se);const de=yield x.createAnswer();yield x.setLocalDescription(de),yield oe({payload:JSON.stringify({description:de})})}else se.type==="answer"&&(yield x.setRemoteDescription(se));else h.a.warn(`Received SDP signal when signaling is stable and connected: ${JSON.stringify(A)}`);else h.a.warn(`Received non-SDP signal: ${JSON.stringify(A)}`)})}send(A,x){const q=this.getChannelFromLabel(x.channelLabel);q?this.sendOnChannel(q,A):h.a.warn("Send called with unexpected channel label",{channelLabel:x.channelLabel})}controlRemoteStream(A){this.sendSystemMessage(te(this.reliableStreamChannel),{type:"stream-control",streamControl:A})}isActive(){return new Set(["new","connecting","connected"]).has(this.peerConnection.connectionState)}isReady(){const{peerConnection:A,latestTtlStreamChannel:x,reliableStreamChannel:q,latestTryOnceStreamChannel:oe}=this;return!!(q&&x&&oe)&&A.connectionState==="connected"&&q.readyState==="open"&&x.readyState==="open"&&oe.readyState==="open"}isClosed(){const{peerConnection:A,reliableStreamChannel:x,latestTryOnceStreamChannel:q,latestTtlStreamChannel:oe}=this;return!(A.connectionState!=="closed"||x!==void 0&&x.readyState!=="closed"||q!==void 0&&q.readyState!=="closed"||oe!==void 0&&oe.readyState!=="closed")}needsClosing(){const{peerConnection:A,latestTtlStreamChannel:x,reliableStreamChannel:q,latestTryOnceStreamChannel:oe}=this;if(this.isClosed())return!1;const se=new Set(["closing","closed"]),de=he=>he&&se.has(he.readyState);return Rt(A)||de(x)||de(q)||de(oe)}close(){return nt(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(A){this.latestTtlStreamChannel=A.createDataChannel("stream.latest-ttl",ne),this.reliableStreamChannel=A.createDataChannel("stream.reliable",ie),this.latestReliableStreamChannel=A.createDataChannel("stream.latest-reliable",ce),this.latestTryOnceStreamChannel=A.createDataChannel("stream.latest-try-once",Se),this.setupChannel(this.latestTtlStreamChannel),this.setupChannel(this.reliableStreamChannel),this.setupChannel(this.latestReliableStreamChannel),this.setupChannel(this.latestTryOnceStreamChannel)}sendOffer(){return nt(this,void 0,void 0,function*(){if(this.sentOffer||(this.sentOffer=!0,Rt(this.peerConnection)))return;const{peerConnection:A,config:{sendSignal:x}}=this,q=yield A.createOffer();yield A.setLocalDescription(q);const oe={payload:JSON.stringify({description:q})};yield x(oe)})}getChannelFromLabel(A){switch(A){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(A,x){let q;try{q=Object(H.encode)(JSON.stringify(x))}catch(oe){return void h.a.warn("Failed to encode RTC message",{error:oe})}try{A.send(q),this.sessionMetrics.incrementMessageSent(x)}catch(oe){h.a.warn("Failed to send message to channel",{error:oe,channel:A.label})}}channelNotRecognized(A){return A!==this.latestTtlStreamChannel&&A!==this.latestReliableStreamChannel&&A!==this.latestTryOnceStreamChannel&&A!==this.reliableStreamChannel}setupChannel(A){A.onmessage=x=>{if(this.channelNotRecognized(A))return void h.a.warn("Received message on unrecognized data channel.");let q;try{q=JSON.parse(Object(H.decode)(x.data))}catch(oe){return void h.a.warn("Received unparseable RTC message",{error:oe,channel:A.label})}if(this.lastMessageTimestamp=new Date().getTime(),q=Et(q),this.sessionMetrics.incrementMessageReceived(q),!this.handleSystemMessage(A,q)){if(!this.hasCapabilities(q))return void h.a.warn("Received RTC message that was not within the capability scope of the connection.");(A===this.latestTryOnceStreamChannel||A===this.latestTtlStreamChannel||A===this.latestReliableStreamChannel)&&!this.isLatestMessage(q)||this.config.receive(this.config.remotePeer.id,q)}},A.onerror=x=>{h.a.warn(`Channel error: ${x.error}`,{error:x.error,sessionId:this.getSessionId(),channelLabel:A.label})},A.onopen=()=>{h.a.debug("Channel opened",{sessionId:this.getSessionId(),channelLabel:A.label})},A.onclose=()=>{const x={bufferedAmount:A.bufferedAmount,sessionId:this.getSessionId(),channelLabel:A.label};this.closeCalled===!1?h.a.debug("Unexpected channel closed",x):h.a.debug("Channel closed",x)}}handleSystemMessage(A,x){switch(x.header.stream.streamType){case"ping":return this.sendSystemMessage(A,{type:"pong",timestamp:te(x.payload.ping)}),!0;case"pong":{const q=new Date().getTime()-te(x.payload.pong);return this.pingTimeMs=q,Q.aggregate("rtc-ping-time",q),!0}case"stream-control":return!0;default:return!1}}sendSystemMessage(A,x){if(A.readyState!=="open")return;const q={entityId:te(this.config.localPeer.deviceId||this.config.localPeer.userId),streamName:`$.${x.type}`,streamType:x.type};let oe;switch(x.type){case"ping":oe={ping:new Date().getTime()};break;case"pong":oe={pong:x.timestamp};break;case"stream-control":oe={streamControl:x.streamControl}}this.sendOnChannel(A,et(q,oe))}hasCapabilities(A){var x,q;const{localPeer:oe,remotePeer:se}=this.config,de=(x=oe.capabilitySet.streaming)===null||x===void 0?void 0:x.streams,he=de&&de.some(le=>le.receive&&Ct(le.stream,A.header.stream)),pe=(q=se.capabilitySet.streaming)===null||q===void 0?void 0:q.streams,Ue=pe&&pe.some(le=>le.send&&Ct(le.stream,A.header.stream));return he||Ue}isLatestMessage(A){const x=_e(A.header.stream),q=(this.streamLatestTimestamp.get(x)||0)<=A.header.created;return q&&this.streamLatestTimestamp.set(x,A.header.created),q}}var Oe=function(Re,A,x,q){return new(x||(x=Promise))(function(oe,se){function de(Ue){try{pe(q.next(Ue))}catch(le){se(le)}}function he(Ue){try{pe(q.throw(Ue))}catch(le){se(le)}}function pe(Ue){var le;Ue.done?oe(Ue.value):(le=Ue.value,le instanceof x?le:new x(function(me){me(le)})).then(de,he)}pe((q=q.apply(Re,A||[])).next())})};class Nt{constructor(A){this.config=A,this.connections=[],this.connectingSessions=new Map,this.rtcInstancesConstructed=0,this.updateInterval=F({func:()=>Oe(this,void 0,void 0,function*(){try{yield this.update()}catch(x){h.a.warn("RTC update failed",{error:x})}}),delay:250*d.a.millisecond,immediate:!0}),this.localPeer=this.createPeer()}send(A,x,q){const oe=this.getActiveConnection(A);oe?oe.isReady()?oe.send(x,q):h.a.warn("Attempted to send with an active connection to that peer which was not yet ready."):h.a.warn("Attempted to send with no active connection to that peer.")}controlRemoteStream(A,x){const q=this.getActiveConnection(A);q?q.isReady()?q.controlRemoteStream(x):h.a.warn("Attempted to control remote stream with an active connection to that peer which was not yet ready."):h.a.warn("Attempted to control remote stream with no active connection to that peer.")}connect(A){return Oe(this,void 0,void 0,function*(){const x=yield this.getLocalPeer();if(this.getActiveConnection(A))return void h.a.warn("Attempted to connect to peer with an already active connection.");let q;try{q=yield this.config.signalingClient.createSession(yield this.config.getToken(),{offerPeerId:x.id,answerPeerId:A})}catch(oe){Object(tt.a)(oe,Ft.a,se=>se.statusCode===404),h.a.warn("Attempted to connect to peer that does not exist.")}if(q)for(this.connectingSessions.set(q.id,new Date().getTime()),yield this.connectToSession(q);;)switch(yield Object(u.a)(.1),this.getConnectionStatus(A)){case"connecting":continue;case"connected":return q.id;case"disconnected":return}})}getConnectionStatus(A){const x=this.getActiveConnection(A);return x?x.isReady()?"connected":"connecting":"disconnected"}getIceMode(A){const x=this.getActiveConnection(A);if(x)return x.iceMode}disconnect(A){return Oe(this,void 0,void 0,function*(){const x=this.getActiveConnection(A);x&&(yield this.closeConnection(x))})}getLocalPeer(){return Oe(this,void 0,void 0,function*(){return yield this.localPeer})}getPeers(){return Oe(this,void 0,void 0,function*(){return yield this.config.signalingClient.getPeers(yield this.config.getToken())})}getPing(A){const x=this.getActiveConnection(A);if(x)return x.getPing();h.a.warn("Attempted to get ping time from inactive peer.")}getLastMessageTimestamp(A){const x=this.getActiveConnection(A);if(x)return x.getLastMessageTimestamp();h.a.warn("Attempted to get ping time from inactive peer.")}shutdown(){return Oe(this,void 0,void 0,function*(){yield this.updateInterval.stop();const A=this.connections;this.connections=[],yield this.closeConnections(A)})}closeConnection(A){return Oe(this,void 0,void 0,function*(){this.connectingSessions.delete(A.getSessionId()),yield A.close();try{yield this.config.signalingClient.deleteSession(yield this.config.getToken(),A.getSessionId())}catch(x){Object(tt.a)(x,Ft.a,q=>q.statusCode===404)}})}getSessions(){return Oe(this,void 0,void 0,function*(){const A=yield this.getLocalPeer();return(yield this.config.signalingClient.getSessions(yield this.config.getToken())).filter(x=>x.offer.peer.id===A.id||x.answer.peer.id===A.id)})}createPeer(){return Oe(this,void 0,void 0,function*(){return yield this.config.signalingClient.createPeer(yield this.config.getToken(),{capabilitySet:this.config.capabilitySet||{}})})}createRTCPeerConnection(A={}){return Oe(this,void 0,void 0,function*(){const x=this.config.alternateRTCPeerConnection||RTCPeerConnection;this.rtcInstancesConstructed++,this.rtcInstancesConstructed%20||kt();try{return new x(Object.assign({iceServers:yield this.config.signalingClient.getIceServers(yield this.config.getToken())},A))}catch(q){throw h.a.debug(`Failed to create RTCPeerConnection: ${this.rtcInstancesConstructed} total allocated`),q}})}closeConnections(A){return Oe(this,void 0,void 0,function*(){const x=yield G(A.map(q=>Oe(this,void 0,void 0,function*(){yield this.closeConnection(q)})));for(const q of x)h.a.warn("Request to close session failed",{error:q})})}reset(){return Oe(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(A){return this.connections.find(x=>x.getRemotePeer().id===A&&x.isActive())}update(){return Oe(this,void 0,void 0,function*(){const A=yield this.getLocalPeer();try{yield this.config.signalingClient.refreshPeer(yield this.config.getToken(),A.id)}catch(x){Object(tt.a)(x,Ft.a,q=>q.statusCode===404),h.a.warn("Peer expired, creating new peer",{peerId:A.id}),yield this.reset()}yield this.handleSessions(yield this.getSessions())})}handleSessions(A){return Oe(this,void 0,void 0,function*(){yield this.syncConnectionsAndSessions(A);const x=A.map(q=>({session:q,connection:this.connections.find(oe=>oe.getSessionId()===q.id)}));yield Promise.all(x.map(({session:q,connection:oe})=>Oe(this,void 0,void 0,function*(){return yield this.maintainConnection(q,oe)})))})}syncConnectionsAndSessions(A){return Oe(this,void 0,void 0,function*(){const x=new Set(A.map(se=>se.id)),q=se=>x.has(se.getSessionId())||this.connectingSessions.has(se.getSessionId());this.connections=this.connections.filter(se=>q(se));const oe=this.connections.filter(se=>!q(se)||se.needsClosing());yield Promise.all(oe.map(se=>Oe(this,void 0,void 0,function*(){yield this.closeConnection(se)})))})}maintainConnection(A,x){return Oe(this,void 0,void 0,function*(){const q=yield this.getLocalPeer(),oe=A.offer.peer.id===q.id;if(x){if(x.isReady())try{yield this.config.signalingClient.refreshSession(yield this.config.getToken(),A.id)}catch(se){Object(tt.a)(se,Ft.a,de=>de.statusCode===404),h.a.debug("Refresh session not found",{sessionId:A.id})}else if(x.isActive())try{yield this.consumeSignals(x)}catch(se){h.a.warn("Failed to ingest signals, closing connection",{error:se}),yield this.closeConnection(x)}}else{if(oe)return;yield this.connectToSession(A)}})}connectToSession(A){return Oe(this,void 0,void 0,function*(){const x=yield this.getLocalPeer(),q=A.offer.peer.id===x.id,oe=yield this.createRTCPeerConnection(),se=new St(oe,{localPeer:q?A.offer.peer:A.answer.peer,remotePeer:q?A.answer.peer:A.offer.peer,sessionId:A.id,isOffer:q,sendSignal:de=>this.sendSignal(A.id,de),receive:(de,he)=>this.config.receive(de,he)});if(this.connections.find(de=>de.getSessionId()===A.id))return h.a.warn("connectToSession called on a session that already has a connection.",{sessionId:A.id}),void(yield se.close());this.setupHandlers(se),this.connections.push(se);try{yield se.connect()}catch(de){h.a.warn("Failed to handle negotiation, closing connection",{error:de}),yield this.closeConnection(se)}})}setupHandlers(A){const{peerConnection:x}=A,q=A.getSessionId();x.onconnectionstatechange=()=>Oe(this,void 0,void 0,function*(){const oe=this.connectingSessions.get(q);if(oe===void 0)return;const se=x.connectionState;switch(Rt(x)&&this.connectingSessions.delete(q),se){case"connected":{this.connectingSessions.delete(q);const de=new Date().getTime()-oe;Q.aggregate("rtc-connect-time",de);break}case"failed":Q.increment("rtc-connect-failed"),yield this.closeConnection(A)}})}consumeSignals(A){return Oe(this,void 0,void 0,function*(){let x=[];try{x=yield this.config.signalingClient.takeSignals(yield this.config.getToken(),A.getSessionId())}catch(q){Object(tt.a)(q,Ft.a,oe=>oe.statusCode===404)}for(const q of x)yield A.handleSignal(q)})}sendSignal(A,x){return Oe(this,void 0,void 0,function*(){try{yield this.config.signalingClient.addSignals(yield this.config.getToken(),A,{signals:[x]})}catch(q){Object(tt.a)(q,Ft.a,oe=>oe.statusCode===404)}})}}},function(e,t,n){var r={randomUUID:typeof crypto!="undefined"&&crypto.randomUUID&&crypto.randomUUID.bind(crypto)};let l;const s=new Uint8Array(16);function c(){if(!l&&(l=typeof crypto!="undefined"&&crypto.getRandomValues&&crypto.getRandomValues.bind(crypto),!l))throw new Error("crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported");return l(s)}const o=[];for(let u=0;u<256;++u)o.push((u+256).toString(16).slice(1));function d(u,U=0){return(o[u[U+0]]+o[u[U+1]]+o[u[U+2]]+o[u[U+3]]+"-"+o[u[U+4]]+o[u[U+5]]+"-"+o[u[U+6]]+o[u[U+7]]+"-"+o[u[U+8]]+o[u[U+9]]+"-"+o[u[U+10]]+o[u[U+11]]+o[u[U+12]]+o[u[U+13]]+o[u[U+14]]+o[u[U+15]]).toLowerCase()}t.a=function(u,U,B){if(r.randomUUID&&!U&&!u)return r.randomUUID();const R=(u=u||{}).random||(u.rng||c)();if(R[6]=15&R[6]|64,R[8]=63&R[8]|128,U){B=B||0;for(let p=0;p<16;++p)U[B+p]=R[p];return U}return d(R)}},,function(e,t,n){n.r(t),n.d(t,"LogClient",function(){return o});var r=n(26),l=n(12),s=n(11),c=function(d,u,U,B){return new(U||(U=Promise))(function(R,p){function g(N){try{m(B.next(N))}catch(D){p(D)}}function h(N){try{m(B.throw(N))}catch(D){p(D)}}function m(N){var D;N.done?R(N.value):(D=N.value,D instanceof U?D:new U(function(y){y(D)})).then(g,h)}m((B=B.apply(d,u||[])).next())})};class o extends r.a{log(u){return c(this,void 0,void 0,function*(){const U=o.token;try{yield this.fetch("logs",{token:U,method:"POST",body:{logs:u},allowUnsafeRetries:!0})}catch(B){Object(l.a)(B,s.a,R=>R.statusCode===401&&U!==void 0),o.token===U&&delete o.token,yield this.log(u)}})}}}])})})(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");var Sn;class RtcClientPool{constructor(t){Fe(this,Sn,null);Fe(this,"createClient");Fe(this,"ttlMs");Fe(this,"proxyHandler");Fe(this,"proxyReceivers",new Map);Fe(this,"teardownTimeout",null);Fe(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:(l,s,c)=>{switch(s){case"shutdown":return()=>this.releaseInstance(c);default:return Reflect.get(l,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)}}Sn=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(FORMANT_API_URL),getToken,sessionType:SessionTypes.UNKNOWN,receive:e})}),[SessionTypes.TELEOP]:new RtcClientPool({ttlMs:2500,createClient:e=>new distExports.RtcClient({signalingClient:new distExports.SignalingPromiseClient(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(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(FORMANT_API_URL),getToken,sessionType:SessionTypes.OBSERVE,receive:e})}),[SessionTypes.HEADLESS]:new RtcClientPool({ttlMs:2500,createClient:e=>new distExports.RtcClient({signalingClient:new distExports.SignalingPromiseClient(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};class CaptureStream{constructor(t){Fe(this,"token");this.captureSession=t}async ingestJSON(t){if(!this.token){const r=await(await fetch(`${FORMANT_API_URL}/v1/admin/capture-sessions/${this.captureSession.code}/authenticate`,{method:"POST"})).json();this.token=r.token}await fetch(`${FORMANT_API_URL}/v1/ingest`,{method:"POST",body:JSON.stringify({deviceId:this.captureSession.deviceId,name:this.captureSession.streamName,type:"json",points:[[Date.now(),JSON.stringify(t)]]}),headers:{"Content-Type":"application/json",Authorization:"Bearer "+this.token}})}}function delay(e){return new Promise(t=>setTimeout(t,e))}const isRtcPeer=e=>e!==void 0&&e.capabilities!==void 0&&e.capabilitySet!==void 0;class DataChannel{constructor(t){Fe(this,"ready",!1);Fe(this,"listeners",[]);Fe(this,"openListeners",[]);Fe(this,"closeListeners",[]);Fe(this,"errorListeners",[]);Fe(this,"binaryListeners",[]);Fe(this,"error");Fe(this,"decoder",new TextDecoder);this.dataChannel=t,this.dataChannel.binaryType="arraybuffer",this.dataChannel.onopen=()=>{this.setReady()},this.dataChannel.onclose=()=>{this.ready=!1,this.closeListeners.forEach(n=>n())},this.dataChannel.onerror=n=>{console.error(n),this.error="An error occurred in DataChannel",this.errorListeners.forEach(r=>r(n))},this.dataChannel.onmessage=n=>{this.listeners.forEach(r=>{const l=new Uint8Array(n.data),s=this.decoder.decode(l);r(s)}),this.binaryListeners.forEach(r=>{r(new Uint8Array(n.data))})}}setReady(){this.ready=!0,this.openListeners.forEach(t=>t())}addOpenListener(t){this.openListeners.push(t)}removeOpenListener(t){this.openListeners=this.openListeners.filter(n=>n!==t)}addCloseListener(t){this.closeListeners.push(t)}removeCloseListener(t){this.closeListeners=this.closeListeners.filter(n=>n!==t)}addErrorListener(t){this.errorListeners.push(t)}removeErrorListener(t){this.errorListeners=this.errorListeners.filter(n=>n!==t)}async waitTilReady(){return this.ready?!0:new Promise((n,r)=>{let l=setInterval(()=>{this.dataChannel.readyState==="open"&&this.setReady(),this.ready&&(clearInterval(l),n(!0)),this.error&&r(this.error)},10)})}send(t){if(!this.ready)throw new Error("Connection has been closed");this.dataChannel.send(t)}sendBinary(t){if(!this.ready)throw new Error("Connection has been closed");this.dataChannel.send(t)}addListener(t){this.listeners.push(t)}removeListener(t){const n=this.listeners.indexOf(t);if(n===-1)throw new Error("Could not find data channel listener to remove");if(this.error)throw new Error(this.error);this.listeners.splice(n,1)}addBinaryListener(t){this.binaryListeners.push(t)}removeBinaryListener(t){const n=this.binaryListeners.indexOf(t);if(n===-1)throw new Error("Could not find data channel listener to remove");if(this.error)throw new Error(this.error);this.binaryListeners.splice(n,1)}}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 l(d,u,U){this.fn=d,this.context=u,this.once=U||!1}function s(d,u,U,B,R){if(typeof U!="function")throw new TypeError("The listener must be a function");var p=new l(U,B||d,R),g=n?n+u:u;return d._events[g]?d._events[g].fn?d._events[g]=[d._events[g],p]:d._events[g].push(p):(d._events[g]=p,d._eventsCount++),d}function c(d,u){--d._eventsCount===0?d._events=new r:delete d._events[u]}function o(){this._events=new r,this._eventsCount=0}o.prototype.eventNames=function(){var u=[],U,B;if(this._eventsCount===0)return u;for(B in U=this._events)t.call(U,B)&&u.push(n?B.slice(1):B);return Object.getOwnPropertySymbols?u.concat(Object.getOwnPropertySymbols(U)):u},o.prototype.listeners=function(u){var U=n?n+u:u,B=this._events[U];if(!B)return[];if(B.fn)return[B.fn];for(var R=0,p=B.length,g=new Array(p);R<p;R++)g[R]=B[R].fn;return g},o.prototype.listenerCount=function(u){var U=n?n+u:u,B=this._events[U];return B?B.fn?1:B.length:0},o.prototype.emit=function(u,U,B,R,p,g){var h=n?n+u:u;if(!this._events[h])return!1;var m=this._events[h],N=arguments.length,D,y;if(m.fn){switch(m.once&&this.removeListener(u,m.fn,void 0,!0),N){case 1:return m.fn.call(m.context),!0;case 2:return m.fn.call(m.context,U),!0;case 3:return m.fn.call(m.context,U,B),!0;case 4:return m.fn.call(m.context,U,B,R),!0;case 5:return m.fn.call(m.context,U,B,R,p),!0;case 6:return m.fn.call(m.context,U,B,R,p,g),!0}for(y=1,D=new Array(N-1);y<N;y++)D[y-1]=arguments[y];m.fn.apply(m.context,D)}else{var b=m.length,F;for(y=0;y<b;y++)switch(m[y].once&&this.removeListener(u,m[y].fn,void 0,!0),N){case 1:m[y].fn.call(m[y].context);break;case 2:m[y].fn.call(m[y].context,U);break;case 3:m[y].fn.call(m[y].context,U,B);break;case 4:m[y].fn.call(m[y].context,U,B,R);break;default:if(!D)for(F=1,D=new Array(N-1);F<N;F++)D[F-1]=arguments[F];m[y].fn.apply(m[y].context,D)}}return!0},o.prototype.on=function(u,U,B){return s(this,u,U,B,!1)},o.prototype.once=function(u,U,B){return s(this,u,U,B,!0)},o.prototype.removeListener=function(u,U,B,R){var p=n?n+u:u;if(!this._events[p])return this;if(!U)return c(this,p),this;var g=this._events[p];if(g.fn)g.fn===U&&(!R||g.once)&&(!B||g.context===B)&&c(this,p);else{for(var h=0,m=[],N=g.length;h<N;h++)(g[h].fn!==U||R&&!g[h].once||B&&g[h].context!==B)&&m.push(g[h]);m.length?this._events[p]=m.length===1?m[0]:m:c(this,p)}return this},o.prototype.removeAllListeners=function(u){var U;return u?(U=n?n+u:u,this._events[U]&&c(this,U)):(this._events=new r,this._eventsCount=0),this},o.prototype.off=o.prototype.removeListener,o.prototype.addListener=o.prototype.on,o.prefixed=n,o.EventEmitter=o,e.exports=o})(eventemitter3);var eventemitter3Exports=eventemitter3.exports;const EventEmitter=getDefaultExportFromCjs(eventemitter3Exports);class Manipulator{constructor(t,n){Fe(this,"currentListeners",[]);Fe(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){Fe(this,"channel");Fe(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);Fe(this,"RESPONSE_SUCCESS_BYTE",0);Fe(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 l=n.slice(0,16).toString();if(l.length===0)throw new Error("Invalid response");const s=n.slice(16);if(s.length===0)throw new Error("Invalid response");this.requestIdToResponseMap.has(l)&&this.requestIdToResponseMap.set(l,s)})}async request(n){if(this.channel||await this.initialize(),!this.channel)throw new Error("Failed to create channel");const{channel:r,requestIdToResponseMap:l,timeout:s}=this;await r.waitTilReady();const c=this.generateBinaryId(),o=c.toString();l.set(o,!0),r.sendBinary(new Uint8Array([...c,...n]));const d=new Date().getTime();for(;new Date().getTime()<d+s;)if(await delay(50),l.has(o)){const u=l.get(o);if(u!==!0){l.delete(o);const U=u[0]===this.RESPONSE_SUCCESS_BYTE,B=u.slice(1);if(U)return B;throw console.error({name:"AdapterError",message:this.decoder.decode(B)}),new Error("Binary request datachannel adapter error")}}throw l.delete(o),console.error({name:"TimeoutError",message:`Request timed out after ${s/1e3} seconds`}),new Error("Binary request data channel request timed out")}}class TextRequestDataChannel extends RequestDataChannel{generateTextId(){return Math.random().toString(36).substring(2)+"-"+Math.random().toString(36).substring(2)}async initialize(){this.channel=await this.device.createCustomDataChannel(this.channel_name),this.channel.addListener(t=>{const n=JSON.parse(t),{id:r,data:l,error:s}=n;if(!r)throw new Error("Invalid response");if(!l&&!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:l}=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+l;)if(await delay(50),r.has(s)){const o=r.get(s);if(o!==!0){r.delete(s);const{data:d,error:u}=o;if(d)return d;if(u)throw console.error({name:"AdapterError",message:u}),new Error("Text request datachannel adapter error")}}throw r.delete(s),console.error({name:"TimeoutError",message:`Request timed out after ${l/1e3} seconds`}),new Error("Text request datachannel request timed out")}}class BaseDevice extends EventEmitter{constructor(){super(...arguments);Fe(this,"rtcClient");Fe(this,"remoteDevicePeerId",null);Fe(this,"realtimeListeners",[]);Fe(this,"connectionMonitorInterval");Fe(this,"handleMessage",(n,r)=>{this.realtimeListeners.forEach(l=>l(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")}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 l;const n=await this.getConfiguration(),r=[];for(const s of(l=n.teleop.rosStreams)!=null?l:[])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 l,s,c,o,d,u;const n=await this.getConfiguration(),r=[];for(const U of(s=(l=n.teleop)==null?void 0:l.hardwareStreams)!=null?s:[])U.rtcStreamType==="h264-video-frame"&&r.push({name:U.name});for(const U of(o=(c=n.teleop)==null?void 0:c.rosStreams)!=null?o:[])U.topicType=="formant/H264VideoFrame"&&r.push({name:U.topicName}),(U.topicType==="sensor_msgs/Image"||U.topicType==="sensor_msgs/CompressedImage")&&U.encodeVideo&&r.push({name:U.topicName});for(const U of(u=(d=n.teleop)==null?void 0:d.customStreams)!=null?u:[])U.rtcStreamType==="h264-video-frame"&&r.push({name:U.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"),l=await this.getRemotePeer();r.controlRemoteStream(defined$1(l).id,{streamName:n.name,enable:!0,pipeline:"rtc"})}async stopListeningToRealtimeVideo(n){const r=defined$1(this.rtcClient,"Realtime connection has not been started"),l=await this.getRemotePeer();r.controlRemoteStream(defined$1(l).id,{streamName:n.name,enable:!1,pipeline:"rtc"})}async startListeningToRealtimeDataStream(n){const r=defined$1(this.rtcClient,"Realtime connection has not been started"),l=await this.getRemotePeer();r.controlRemoteStream(defined$1(l).id,{streamName:n.name,enable:!0,pipeline:"rtc"})}async stopListeningToRealtimeDataStream(n){const r=defined$1(this.rtcClient,"Realtime connection has not been started"),l=await this.getRemotePeer();r.controlRemoteStream(defined$1(l).id,{streamName:n.name,enable:!1,pipeline:"rtc"})}async enableRealtimeTelemetryPriorityIngestion(n){const r=defined$1(this.rtcClient,"Realtime connection has not been started"),l=await this.getRemotePeer();r.controlRemoteStream(defined$1(l).id,{streamName:n,enablePriorityUpload:!0,pipeline:"telemetry"})}async disableRealtimeTelemetryPriorityIngestion(n){const r=defined$1(this.rtcClient,"Realtime connection has not been started"),l=await this.getRemotePeer();r.controlRemoteStream(defined$1(l).id,{streamName:n,enablePriorityUpload:!1,pipeline:"telemetry"})}async changeStreamAudioType(n,r){const l=defined$1(this.rtcClient,"Realtime connection has not been started"),s=await this.getRemotePeer();l.controlRemoteStream(defined$1(s).id,{streamName:n,setAudioFormat:r})}async createCustomDataChannel(n,r){const l=defined$1(this.rtcClient,"Realtime connection has not been started"),s=await this.getRemotePeer(),c=await new Promise(o=>{l.createCustomDataChannel(defined$1(s).id,n,{ordered:!0,...r},!1,(d,u)=>{const U=new DataChannel(u);o(U)})});return await c.waitTilReady(),c}async sendRealtimeMessage(n,r={channelLabel:"stream.reliable"}){const l=defined$1(this.rtcClient,"Realtime connection has not been started"),s=await this.getRemotePeer();l.send(defined$1(s).id,n,r)}async getRealtimeAudioStreams(){var l,s,c,o,d,u;const n=await this.getConfiguration(),r=[];for(const U of(s=(l=n.teleop)==null?void 0:l.hardwareStreams)!=null?s:[])U.rtcStreamType==="audio-chunk"&&r.push({name:U.name});for(const U of(o=(c=n.teleop)==null?void 0:c.rosStreams)!=null?o:[])U.topicType=="audio_common_msgs/AudioData"&&r.push({name:U.topicName});for(const U of(u=(d=n.teleop)==null?void 0:d.customStreams)!=null?u:[])U.rtcStreamType==="audio-chunk"&&r.push({name:U.name});return r}}/*! pako 2.1.0 https://github.com/nodeca/pako @license (MIT AND Zlib) */const Z_FIXED$1=4,Z_BINARY=0,Z_TEXT=1,Z_UNKNOWN$1=2;function zero$1(e){let t=e.length;for(;--t>=0;)e[t]=0}const STORED_BLOCK=0,STATIC_TREES=1,DYN_TREES=2,MIN_MATCH$1=3,MAX_MATCH$1=258,LENGTH_CODES$1=29,LITERALS$1=256,L_CODES$1=LITERALS$1+1+LENGTH_CODES$1,D_CODES$1=30,BL_CODES$1=19,HEAP_SIZE$1=2*L_CODES$1+1,MAX_BITS$1=15,Buf_size=16,MAX_BL_BITS=7,END_BLOCK=256,REP_3_6=16,REPZ_3_10=17,REPZ_11_138=18,extra_lbits=new Uint8Array([0,0,0,0,0,0,0,0,1,1,1,1,2,2,2,2,3,3,3,3,4,4,4,4,5,5,5,5,0]),extra_dbits=new Uint8Array([0,0,0,0,1,1,2,2,3,3,4,4,5,5,6,6,7,7,8,8,9,9,10,10,11,11,12,12,13,13]),extra_blbits=new Uint8Array([0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,2,3,7]),bl_order=new Uint8Array([16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15]),DIST_CODE_LEN=512,static_ltree=new Array((L_CODES$1+2)*2);zero$1(static_ltree);const static_dtree=new Array(D_CODES$1*2);zero$1(static_dtree);const _dist_code=new Array(DIST_CODE_LEN);zero$1(_dist_code);const _length_code=new Array(MAX_MATCH$1-MIN_MATCH$1+1);zero$1(_length_code);const base_length=new Array(LENGTH_CODES$1);zero$1(base_length);const base_dist=new Array(D_CODES$1);zero$1(base_dist);function StaticTreeDesc(e,t,n,r,l){this.static_tree=e,this.extra_bits=t,this.extra_base=n,this.elems=r,this.max_length=l,this.has_stree=e&&e.length}let static_l_desc,static_d_desc,static_bl_desc;function TreeDesc(e,t){this.dyn_tree=e,this.max_code=0,this.stat_desc=t}const d_code=e=>e<256?_dist_code[e]:_dist_code[256+(e>>>7)],put_short=(e,t)=>{e.pending_buf[e.pending++]=t&255,e.pending_buf[e.pending++]=t>>>8&255},send_bits=(e,t,n)=>{e.bi_valid>Buf_size-n?(e.bi_buf|=t<<e.bi_valid&65535,put_short(e,e.bi_buf),e.bi_buf=t>>Buf_size-e.bi_valid,e.bi_valid+=n-Buf_size):(e.bi_buf|=t<<e.bi_valid&65535,e.bi_valid+=n)},send_code=(e,t,n)=>{send_bits(e,n[t*2],n[t*2+1])},bi_reverse=(e,t)=>{let n=0;do n|=e&1,e>>>=1,n<<=1;while(--t>0);return n>>>1},bi_flush=e=>{e.bi_valid===16?(put_short(e,e.bi_buf),e.bi_buf=0,e.bi_valid=0):e.bi_valid>=8&&(e.pending_buf[e.pending++]=e.bi_buf&255,e.bi_buf>>=8,e.bi_valid-=8)},gen_bitlen=(e,t)=>{const n=t.dyn_tree,r=t.max_code,l=t.stat_desc.static_tree,s=t.stat_desc.has_stree,c=t.stat_desc.extra_bits,o=t.stat_desc.extra_base,d=t.stat_desc.max_length;let u,U,B,R,p,g,h=0;for(R=0;R<=MAX_BITS$1;R++)e.bl_count[R]=0;for(n[e.heap[e.heap_max]*2+1]=0,u=e.heap_max+1;u<HEAP_SIZE$1;u++)U=e.heap[u],R=n[n[U*2+1]*2+1]+1,R>d&&(R=d,h++),n[U*2+1]=R,!(U>r)&&(e.bl_count[R]++,p=0,U>=o&&(p=c[U-o]),g=n[U*2],e.opt_len+=g*(R+p),s&&(e.static_len+=g*(l[U*2+1]+p)));if(h!==0){do{for(R=d-1;e.bl_count[R]===0;)R--;e.bl_count[R]--,e.bl_count[R+1]+=2,e.bl_count[d]--,h-=2}while(h>0);for(R=d;R!==0;R--)for(U=e.bl_count[R];U!==0;)B=e.heap[--u],!(B>r)&&(n[B*2+1]!==R&&(e.opt_len+=(R-n[B*2+1])*n[B*2],n[B*2+1]=R),U--)}},gen_codes=(e,t,n)=>{const r=new Array(MAX_BITS$1+1);let l=0,s,c;for(s=1;s<=MAX_BITS$1;s++)l=l+n[s-1]<<1,r[s]=l;for(c=0;c<=t;c++){let o=e[c*2+1];o!==0&&(e[c*2]=bi_reverse(r[o]++,o))}},tr_static_init=()=>{let e,t,n,r,l;const s=new Array(MAX_BITS$1+1);for(n=0,r=0;r<LENGTH_CODES$1-1;r++)for(base_length[r]=n,e=0;e<1<<extra_lbits[r];e++)_length_code[n++]=r;for(_length_code[n-1]=r,l=0,r=0;r<16;r++)for(base_dist[r]=l,e=0;e<1<<extra_dbits[r];e++)_dist_code[l++]=r;for(l>>=7;r<D_CODES$1;r++)for(base_dist[r]=l<<7,e=0;e<1<<extra_dbits[r]-7;e++)_dist_code[256+l++]=r;for(t=0;t<=MAX_BITS$1;t++)s[t]=0;for(e=0;e<=143;)static_ltree[e*2+1]=8,e++,s[8]++;for(;e<=255;)static_ltree[e*2+1]=9,e++,s[9]++;for(;e<=279;)static_ltree[e*2+1]=7,e++,s[7]++;for(;e<=287;)static_ltree[e*2+1]=8,e++,s[8]++;for(gen_codes(static_ltree,L_CODES$1+1,s),e=0;e<D_CODES$1;e++)static_dtree[e*2+1]=5,static_dtree[e*2]=bi_reverse(e,5);static_l_desc=new StaticTreeDesc(static_ltree,extra_lbits,LITERALS$1+1,L_CODES$1,MAX_BITS$1),static_d_desc=new StaticTreeDesc(static_dtree,extra_dbits,0,D_CODES$1,MAX_BITS$1),static_bl_desc=new StaticTreeDesc(new Array(0),extra_blbits,0,BL_CODES$1,MAX_BL_BITS)},init_block=e=>{let t;for(t=0;t<L_CODES$1;t++)e.dyn_ltree[t*2]=0;for(t=0;t<D_CODES$1;t++)e.dyn_dtree[t*2]=0;for(t=0;t<BL_CODES$1;t++)e.bl_tree[t*2]=0;e.dyn_ltree[END_BLOCK*2]=1,e.opt_len=e.static_len=0,e.sym_next=e.matches=0},bi_windup=e=>{e.bi_valid>8?put_short(e,e.bi_buf):e.bi_valid>0&&(e.pending_buf[e.pending++]=e.bi_buf),e.bi_buf=0,e.bi_valid=0},smaller=(e,t,n,r)=>{const l=t*2,s=n*2;return e[l]<e[s]||e[l]===e[s]&&r[t]<=r[n]},pqdownheap=(e,t,n)=>{const r=e.heap[n];let l=n<<1;for(;l<=e.heap_len&&(l<e.heap_len&&smaller(t,e.heap[l+1],e.heap[l],e.depth)&&l++,!smaller(t,r,e.heap[l],e.depth));)e.heap[n]=e.heap[l],n=l,l<<=1;e.heap[n]=r},compress_block=(e,t,n)=>{let r,l,s=0,c,o;if(e.sym_next!==0)do r=e.pending_buf[e.sym_buf+s++]&255,r+=(e.pending_buf[e.sym_buf+s++]&255)<<8,l=e.pending_buf[e.sym_buf+s++],r===0?send_code(e,l,t):(c=_length_code[l],send_code(e,c+LITERALS$1+1,t),o=extra_lbits[c],o!==0&&(l-=base_length[c],send_bits(e,l,o)),r--,c=d_code(r),send_code(e,c,n),o=extra_dbits[c],o!==0&&(r-=base_dist[c],send_bits(e,r,o)));while(s<e.sym_next);send_code(e,END_BLOCK,t)},build_tree=(e,t)=>{const n=t.dyn_tree,r=t.stat_desc.static_tree,l=t.stat_desc.has_stree,s=t.stat_desc.elems;let c,o,d=-1,u;for(e.heap_len=0,e.heap_max=HEAP_SIZE$1,c=0;c<s;c++)n[c*2]!==0?(e.heap[++e.heap_len]=d=c,e.depth[c]=0):n[c*2+1]=0;for(;e.heap_len<2;)u=e.heap[++e.heap_len]=d<2?++d:0,n[u*2]=1,e.depth[u]=0,e.opt_len--,l&&(e.static_len-=r[u*2+1]);for(t.max_code=d,c=e.heap_len>>1;c>=1;c--)pqdownheap(e,n,c);u=s;do c=e.heap[1],e.heap[1]=e.heap[e.heap_len--],pqdownheap(e,n,1),o=e.heap[1],e.heap[--e.heap_max]=c,e.heap[--e.heap_max]=o,n[u*2]=n[c*2]+n[o*2],e.depth[u]=(e.depth[c]>=e.depth[o]?e.depth[c]:e.depth[o])+1,n[c*2+1]=n[o*2+1]=u,e.heap[1]=u++,pqdownheap(e,n,1);while(e.heap_len>=2);e.heap[--e.heap_max]=e.heap[1],gen_bitlen(e,t),gen_codes(n,d,e.bl_count)},scan_tree=(e,t,n)=>{let r,l=-1,s,c=t[0*2+1],o=0,d=7,u=4;for(c===0&&(d=138,u=3),t[(n+1)*2+1]=65535,r=0;r<=n;r++)s=c,c=t[(r+1)*2+1],!(++o<d&&s===c)&&(o<u?e.bl_tree[s*2]+=o:s!==0?(s!==l&&e.bl_tree[s*2]++,e.bl_tree[REP_3_6*2]++):o<=10?e.bl_tree[REPZ_3_10*2]++:e.bl_tree[REPZ_11_138*2]++,o=0,l=s,c===0?(d=138,u=3):s===c?(d=6,u=3):(d=7,u=4))},send_tree=(e,t,n)=>{let r,l=-1,s,c=t[0*2+1],o=0,d=7,u=4;for(c===0&&(d=138,u=3),r=0;r<=n;r++)if(s=c,c=t[(r+1)*2+1],!(++o<d&&s===c)){if(o<u)do send_code(e,s,e.bl_tree);while(--o!==0);else s!==0?(s!==l&&(send_code(e,s,e.bl_tree),o--),send_code(e,REP_3_6,e.bl_tree),send_bits(e,o-3,2)):o<=10?(send_code(e,REPZ_3_10,e.bl_tree),send_bits(e,o-3,3)):(send_code(e,REPZ_11_138,e.bl_tree),send_bits(e,o-11,7));o=0,l=s,c===0?(d=138,u=3):s===c?(d=6,u=3):(d=7,u=4)}},build_bl_tree=e=>{let t;for(scan_tree(e,e.dyn_ltree,e.l_desc.max_code),scan_tree(e,e.dyn_dtree,e.d_desc.max_code),build_tree(e,e.bl_desc),t=BL_CODES$1-1;t>=3&&e.bl_tree[bl_order[t]*2+1]===0;t--);return e.opt_len+=3*(t+1)+5+5+4,t},send_all_trees=(e,t,n,r)=>{let l;for(send_bits(e,t-257,5),send_bits(e,n-1,5),send_bits(e,r-4,4),l=0;l<r;l++)send_bits(e,e.bl_tree[bl_order[l]*2+1],3);send_tree(e,e.dyn_ltree,t-1),send_tree(e,e.dyn_dtree,n-1)},detect_data_type=e=>{let t=4093624447,n;for(n=0;n<=31;n++,t>>>=1)if(t&1&&e.dyn_ltree[n*2]!==0)return Z_BINARY;if(e.dyn_ltree[9*2]!==0||e.dyn_ltree[10*2]!==0||e.dyn_ltree[13*2]!==0)return Z_TEXT;for(n=32;n<LITERALS$1;n++)if(e.dyn_ltree[n*2]!==0)return Z_TEXT;return Z_BINARY};let static_init_done=!1;const _tr_init$1=e=>{static_init_done||(tr_static_init(),static_init_done=!0),e.l_desc=new TreeDesc(e.dyn_ltree,static_l_desc),e.d_desc=new TreeDesc(e.dyn_dtree,static_d_desc),e.bl_desc=new TreeDesc(e.bl_tree,static_bl_desc),e.bi_buf=0,e.bi_valid=0,init_block(e)},_tr_stored_block$1=(e,t,n,r)=>{send_bits(e,(STORED_BLOCK<<1)+(r?1:0),3),bi_windup(e),put_short(e,n),put_short(e,~n),n&&e.pending_buf.set(e.window.subarray(t,t+n),e.pending),e.pending+=n},_tr_align$1=e=>{send_bits(e,STATIC_TREES<<1,3),send_code(e,END_BLOCK,static_ltree),bi_flush(e)},_tr_flush_block$1=(e,t,n,r)=>{let l,s,c=0;e.level>0?(e.strm.data_type===Z_UNKNOWN$1&&(e.strm.data_type=detect_data_type(e)),build_tree(e,e.l_desc),build_tree(e,e.d_desc),c=build_bl_tree(e),l=e.opt_len+3+7>>>3,s=e.static_len+3+7>>>3,s<=l&&(l=s)):l=s=n+5,n+4<=l&&t!==-1?_tr_stored_block$1(e,t,n,r):e.strategy===Z_FIXED$1||s===l?(send_bits(e,(STATIC_TREES<<1)+(r?1:0),3),compress_block(e,static_ltree,static_dtree)):(send_bits(e,(DYN_TREES<<1)+(r?1:0),3),send_all_trees(e,e.l_desc.max_code+1,e.d_desc.max_code+1,c+1),compress_block(e,e.dyn_ltree,e.dyn_dtree)),init_block(e),r&&bi_windup(e)},_tr_tally$1=(e,t,n)=>(e.pending_buf[e.sym_buf+e.sym_next++]=t,e.pending_buf[e.sym_buf+e.sym_next++]=t>>8,e.pending_buf[e.sym_buf+e.sym_next++]=n,t===0?e.dyn_ltree[n*2]++:(e.matches++,t--,e.dyn_ltree[(_length_code[n]+LITERALS$1+1)*2]++,e.dyn_dtree[d_code(t)*2]++),e.sym_next===e.sym_end);var _tr_init_1=_tr_init$1,_tr_stored_block_1=_tr_stored_block$1,_tr_flush_block_1=_tr_flush_block$1,_tr_tally_1=_tr_tally$1,_tr_align_1=_tr_align$1,trees={_tr_init:_tr_init_1,_tr_stored_block:_tr_stored_block_1,_tr_flush_block:_tr_flush_block_1,_tr_tally:_tr_tally_1,_tr_align:_tr_align_1};const adler32=(e,t,n,r)=>{let l=e&65535|0,s=e>>>16&65535|0,c=0;for(;n!==0;){c=n>2e3?2e3:n,n-=c;do l=l+t[r++]|0,s=s+l|0;while(--c);l%=65521,s%=65521}return l|s<<16|0};var adler32_1=adler32;const makeTable=()=>{let e,t=[];for(var n=0;n<256;n++){e=n;for(var r=0;r<8;r++)e=e&1?3988292384^e>>>1:e>>>1;t[n]=e}return t},crcTable=new Uint32Array(makeTable()),crc32=(e,t,n,r)=>{const l=crcTable,s=r+n;e^=-1;for(let c=r;c<s;c++)e=e>>>8^l[(e^t[c])&255];return e^-1};var crc32_1=crc32,messages={2:"need dictionary",1:"stream end",0:"","-1":"file error","-2":"stream error","-3":"data error","-4":"insufficient memory","-5":"buffer error","-6":"incompatible version"},constants$2={Z_NO_FLUSH:0,Z_PARTIAL_FLUSH:1,Z_SYNC_FLUSH:2,Z_FULL_FLUSH:3,Z_FINISH:4,Z_BLOCK:5,Z_TREES:6,Z_OK:0,Z_STREAM_END:1,Z_NEED_DICT:2,Z_ERRNO:-1,Z_STREAM_ERROR:-2,Z_DATA_ERROR:-3,Z_MEM_ERROR:-4,Z_BUF_ERROR:-5,Z_NO_COMPRESSION:0,Z_BEST_SPEED:1,Z_BEST_COMPRESSION:9,Z_DEFAULT_COMPRESSION:-1,Z_FILTERED:1,Z_HUFFMAN_ONLY:2,Z_RLE:3,Z_FIXED:4,Z_DEFAULT_STRATEGY:0,Z_BINARY:0,Z_TEXT:1,Z_UNKNOWN:2,Z_DEFLATED:8};const{_tr_init,_tr_stored_block,_tr_flush_block,_tr_tally,_tr_align}=trees,{Z_NO_FLUSH:Z_NO_FLUSH$2,Z_PARTIAL_FLUSH,Z_FULL_FLUSH:Z_FULL_FLUSH$1,Z_FINISH:Z_FINISH$3,Z_BLOCK:Z_BLOCK$1,Z_OK:Z_OK$3,Z_STREAM_END:Z_STREAM_END$3,Z_STREAM_ERROR:Z_STREAM_ERROR$2,Z_DATA_ERROR:Z_DATA_ERROR$2,Z_BUF_ERROR:Z_BUF_ERROR$1,Z_DEFAULT_COMPRESSION:Z_DEFAULT_COMPRESSION$1,Z_FILTERED,Z_HUFFMAN_ONLY,Z_RLE,Z_FIXED,Z_DEFAULT_STRATEGY:Z_DEFAULT_STRATEGY$1,Z_UNKNOWN,Z_DEFLATED:Z_DEFLATED$2}=constants$2,MAX_MEM_LEVEL=9,MAX_WBITS$1=15,DEF_MEM_LEVEL=8,LENGTH_CODES=29,LITERALS=256,L_CODES=LITERALS+1+LENGTH_CODES,D_CODES=30,BL_CODES=19,HEAP_SIZE=2*L_CODES+1,MAX_BITS=15,MIN_MATCH=3,MAX_MATCH=258,MIN_LOOKAHEAD=MAX_MATCH+MIN_MATCH+1,PRESET_DICT=32,INIT_STATE=42,GZIP_STATE=57,EXTRA_STATE=69,NAME_STATE=73,COMMENT_STATE=91,HCRC_STATE=103,BUSY_STATE=113,FINISH_STATE=666,BS_NEED_MORE=1,BS_BLOCK_DONE=2,BS_FINISH_STARTED=3,BS_FINISH_DONE=4,OS_CODE=3,err=(e,t)=>(e.msg=messages[t],t),rank=e=>e*2-(e>4?9:0),zero=e=>{let t=e.length;for(;--t>=0;)e[t]=0},slide_hash=e=>{let t,n,r,l=e.w_size;t=e.hash_size,r=t;do n=e.head[--r],e.head[r]=n>=l?n-l:0;while(--t);t=l,r=t;do n=e.prev[--r],e.prev[r]=n>=l?n-l:0;while(--t)};let HASH_ZLIB=(e,t,n)=>(t<<e.hash_shift^n)&e.hash_mask,HASH=HASH_ZLIB;const flush_pending=e=>{const t=e.state;let n=t.pending;n>e.avail_out&&(n=e.avail_out),n!==0&&(e.output.set(t.pending_buf.subarray(t.pending_out,t.pending_out+n),e.next_out),e.next_out+=n,t.pending_out+=n,e.total_out+=n,e.avail_out-=n,t.pending-=n,t.pending===0&&(t.pending_out=0))},flush_block_only=(e,t)=>{_tr_flush_block(e,e.block_start>=0?e.block_start:-1,e.strstart-e.block_start,t),e.block_start=e.strstart,flush_pending(e.strm)},put_byte=(e,t)=>{e.pending_buf[e.pending++]=t},putShortMSB=(e,t)=>{e.pending_buf[e.pending++]=t>>>8&255,e.pending_buf[e.pending++]=t&255},read_buf=(e,t,n,r)=>{let l=e.avail_in;return l>r&&(l=r),l===0?0:(e.avail_in-=l,t.set(e.input.subarray(e.next_in,e.next_in+l),n),e.state.wrap===1?e.adler=adler32_1(e.adler,t,l,n):e.state.wrap===2&&(e.adler=crc32_1(e.adler,t,l,n)),e.next_in+=l,e.total_in+=l,l)},longest_match=(e,t)=>{let n=e.max_chain_length,r=e.strstart,l,s,c=e.prev_length,o=e.nice_match;const d=e.strstart>e.w_size-MIN_LOOKAHEAD?e.strstart-(e.w_size-MIN_LOOKAHEAD):0,u=e.window,U=e.w_mask,B=e.prev,R=e.strstart+MAX_MATCH;let p=u[r+c-1],g=u[r+c];e.prev_length>=e.good_match&&(n>>=2),o>e.lookahead&&(o=e.lookahead);do if(l=t,!(u[l+c]!==g||u[l+c-1]!==p||u[l]!==u[r]||u[++l]!==u[r+1])){r+=2,l++;do;while(u[++r]===u[++l]&&u[++r]===u[++l]&&u[++r]===u[++l]&&u[++r]===u[++l]&&u[++r]===u[++l]&&u[++r]===u[++l]&&u[++r]===u[++l]&&u[++r]===u[++l]&&r<R);if(s=MAX_MATCH-(R-r),r=R-MAX_MATCH,s>c){if(e.match_start=t,c=s,s>=o)break;p=u[r+c-1],g=u[r+c]}}while((t=B[t&U])>d&&--n!==0);return c<=e.lookahead?c:e.lookahead},fill_window=e=>{const t=e.w_size;let n,r,l;do{if(r=e.window_size-e.lookahead-e.strstart,e.strstart>=t+(t-MIN_LOOKAHEAD)&&(e.window.set(e.window.subarray(t,t+t-r),0),e.match_start-=t,e.strstart-=t,e.block_start-=t,e.insert>e.strstart&&(e.insert=e.strstart),slide_hash(e),r+=t),e.strm.avail_in===0)break;if(n=read_buf(e.strm,e.window,e.strstart+e.lookahead,r),e.lookahead+=n,e.lookahead+e.insert>=MIN_MATCH)for(l=e.strstart-e.insert,e.ins_h=e.window[l],e.ins_h=HASH(e,e.ins_h,e.window[l+1]);e.insert&&(e.ins_h=HASH(e,e.ins_h,e.window[l+MIN_MATCH-1]),e.prev[l&e.w_mask]=e.head[e.ins_h],e.head[e.ins_h]=l,l++,e.insert--,!(e.lookahead+e.insert<MIN_MATCH)););}while(e.lookahead<MIN_LOOKAHEAD&&e.strm.avail_in!==0)},deflate_stored=(e,t)=>{let n=e.pending_buf_size-5>e.w_size?e.w_size:e.pending_buf_size-5,r,l,s,c=0,o=e.strm.avail_in;do{if(r=65535,s=e.bi_valid+42>>3,e.strm.avail_out<s||(s=e.strm.avail_out-s,l=e.strstart-e.block_start,r>l+e.strm.avail_in&&(r=l+e.strm.avail_in),r>s&&(r=s),r<n&&(r===0&&t!==Z_FINISH$3||t===Z_NO_FLUSH$2||r!==l+e.strm.avail_in)))break;c=t===Z_FINISH$3&&r===l+e.strm.avail_in?1:0,_tr_stored_block(e,0,0,c),e.pending_buf[e.pending-4]=r,e.pending_buf[e.pending-3]=r>>8,e.pending_buf[e.pending-2]=~r,e.pending_buf[e.pending-1]=~r>>8,flush_pending(e.strm),l&&(l>r&&(l=r),e.strm.output.set(e.window.subarray(e.block_start,e.block_start+l),e.strm.next_out),e.strm.next_out+=l,e.strm.avail_out-=l,e.strm.total_out+=l,e.block_start+=l,r-=l),r&&(read_buf(e.strm,e.strm.output,e.strm.next_out,r),e.strm.next_out+=r,e.strm.avail_out-=r,e.strm.total_out+=r)}while(c===0);return o-=e.strm.avail_in,o&&(o>=e.w_size?(e.matches=2,e.window.set(e.strm.input.subarray(e.strm.next_in-e.w_size,e.strm.next_in),0),e.strstart=e.w_size,e.insert=e.strstart):(e.window_size-e.strstart<=o&&(e.strstart-=e.w_size,e.window.set(e.window.subarray(e.w_size,e.w_size+e.strstart),0),e.matches<2&&e.matches++,e.insert>e.strstart&&(e.insert=e.strstart)),e.window.set(e.strm.input.subarray(e.strm.next_in-o,e.strm.next_in),e.strstart),e.strstart+=o,e.insert+=o>e.w_size-e.insert?e.w_size-e.insert:o),e.block_start=e.strstart),e.high_water<e.strstart&&(e.high_water=e.strstart),c?BS_FINISH_DONE:t!==Z_NO_FLUSH$2&&t!==Z_FINISH$3&&e.strm.avail_in===0&&e.strstart===e.block_start?BS_BLOCK_DONE:(s=e.window_size-e.strstart,e.strm.avail_in>s&&e.block_start>=e.w_size&&(e.block_start-=e.w_size,e.strstart-=e.w_size,e.window.set(e.window.subarray(e.w_size,e.w_size+e.strstart),0),e.matches<2&&e.matches++,s+=e.w_size,e.insert>e.strstart&&(e.insert=e.strstart)),s>e.strm.avail_in&&(s=e.strm.avail_in),s&&(read_buf(e.strm,e.window,e.strstart,s),e.strstart+=s,e.insert+=s>e.w_size-e.insert?e.w_size-e.insert:s),e.high_water<e.strstart&&(e.high_water=e.strstart),s=e.bi_valid+42>>3,s=e.pending_buf_size-s>65535?65535:e.pending_buf_size-s,n=s>e.w_size?e.w_size:s,l=e.strstart-e.block_start,(l>=n||(l||t===Z_FINISH$3)&&t!==Z_NO_FLUSH$2&&e.strm.avail_in===0&&l<=s)&&(r=l>s?s:l,c=t===Z_FINISH$3&&e.strm.avail_in===0&&r===l?1:0,_tr_stored_block(e,e.block_start,r,c),e.block_start+=r,flush_pending(e.strm)),c?BS_FINISH_STARTED:BS_NEED_MORE)},deflate_fast=(e,t)=>{let n,r;for(;;){if(e.lookahead<MIN_LOOKAHEAD){if(fill_window(e),e.lookahead<MIN_LOOKAHEAD&&t===Z_NO_FLUSH$2)return BS_NEED_MORE;if(e.lookahead===0)break}if(n=0,e.lookahead>=MIN_MATCH&&(e.ins_h=HASH(e,e.ins_h,e.window[e.strstart+MIN_MATCH-1]),n=e.prev[e.strstart&e.w_mask]=e.head[e.ins_h],e.head[e.ins_h]=e.strstart),n!==0&&e.strstart-n<=e.w_size-MIN_LOOKAHEAD&&(e.match_length=longest_match(e,n)),e.match_length>=MIN_MATCH)if(r=_tr_tally(e,e.strstart-e.match_start,e.match_length-MIN_MATCH),e.lookahead-=e.match_length,e.match_length<=e.max_lazy_match&&e.lookahead>=MIN_MATCH){e.match_length--;do e.strstart++,e.ins_h=HASH(e,e.ins_h,e.window[e.strstart+MIN_MATCH-1]),n=e.prev[e.strstart&e.w_mask]=e.head[e.ins_h],e.head[e.ins_h]=e.strstart;while(--e.match_length!==0);e.strstart++}else e.strstart+=e.match_length,e.match_length=0,e.ins_h=e.window[e.strstart],e.ins_h=HASH(e,e.ins_h,e.window[e.strstart+1]);else r=_tr_tally(e,0,e.window[e.strstart]),e.lookahead--,e.strstart++;if(r&&(flush_block_only(e,!1),e.strm.avail_out===0))return BS_NEED_MORE}return e.insert=e.strstart<MIN_MATCH-1?e.strstart:MIN_MATCH-1,t===Z_FINISH$3?(flush_block_only(e,!0),e.strm.avail_out===0?BS_FINISH_STARTED:BS_FINISH_DONE):e.sym_next&&(flush_block_only(e,!1),e.strm.avail_out===0)?BS_NEED_MORE:BS_BLOCK_DONE},deflate_slow=(e,t)=>{let n,r,l;for(;;){if(e.lookahead<MIN_LOOKAHEAD){if(fill_window(e),e.lookahead<MIN_LOOKAHEAD&&t===Z_NO_FLUSH$2)return BS_NEED_MORE;if(e.lookahead===0)break}if(n=0,e.lookahead>=MIN_MATCH&&(e.ins_h=HASH(e,e.ins_h,e.window[e.strstart+MIN_MATCH-1]),n=e.prev[e.strstart&e.w_mask]=e.head[e.ins_h],e.head[e.ins_h]=e.strstart),e.prev_length=e.match_length,e.prev_match=e.match_start,e.match_length=MIN_MATCH-1,n!==0&&e.prev_length<e.max_lazy_match&&e.strstart-n<=e.w_size-MIN_LOOKAHEAD&&(e.match_length=longest_match(e,n),e.match_length<=5&&(e.strategy===Z_FILTERED||e.match_length===MIN_MATCH&&e.strstart-e.match_start>4096)&&(e.match_length=MIN_MATCH-1)),e.prev_length>=MIN_MATCH&&e.match_length<=e.prev_length){l=e.strstart+e.lookahead-MIN_MATCH,r=_tr_tally(e,e.strstart-1-e.prev_match,e.prev_length-MIN_MATCH),e.lookahead-=e.prev_length-1,e.prev_length-=2;do++e.strstart<=l&&(e.ins_h=HASH(e,e.ins_h,e.window[e.strstart+MIN_MATCH-1]),n=e.prev[e.strstart&e.w_mask]=e.head[e.ins_h],e.head[e.ins_h]=e.strstart);while(--e.prev_length!==0);if(e.match_available=0,e.match_length=MIN_MATCH-1,e.strstart++,r&&(flush_block_only(e,!1),e.strm.avail_out===0))return BS_NEED_MORE}else if(e.match_available){if(r=_tr_tally(e,0,e.window[e.strstart-1]),r&&flush_block_only(e,!1),e.strstart++,e.lookahead--,e.strm.avail_out===0)return BS_NEED_MORE}else e.match_available=1,e.strstart++,e.lookahead--}return e.match_available&&(r=_tr_tally(e,0,e.window[e.strstart-1]),e.match_available=0),e.insert=e.strstart<MIN_MATCH-1?e.strstart:MIN_MATCH-1,t===Z_FINISH$3?(flush_block_only(e,!0),e.strm.avail_out===0?BS_FINISH_STARTED:BS_FINISH_DONE):e.sym_next&&(flush_block_only(e,!1),e.strm.avail_out===0)?BS_NEED_MORE:BS_BLOCK_DONE},deflate_rle=(e,t)=>{let n,r,l,s;const c=e.window;for(;;){if(e.lookahead<=MAX_MATCH){if(fill_window(e),e.lookahead<=MAX_MATCH&&t===Z_NO_FLUSH$2)return BS_NEED_MORE;if(e.lookahead===0)break}if(e.match_length=0,e.lookahead>=MIN_MATCH&&e.strstart>0&&(l=e.strstart-1,r=c[l],r===c[++l]&&r===c[++l]&&r===c[++l])){s=e.strstart+MAX_MATCH;do;while(r===c[++l]&&r===c[++l]&&r===c[++l]&&r===c[++l]&&r===c[++l]&&r===c[++l]&&r===c[++l]&&r===c[++l]&&l<s);e.match_length=MAX_MATCH-(s-l),e.match_length>e.lookahead&&(e.match_length=e.lookahead)}if(e.match_length>=MIN_MATCH?(n=_tr_tally(e,1,e.match_length-MIN_MATCH),e.lookahead-=e.match_length,e.strstart+=e.match_length,e.match_length=0):(n=_tr_tally(e,0,e.window[e.strstart]),e.lookahead--,e.strstart++),n&&(flush_block_only(e,!1),e.strm.avail_out===0))return BS_NEED_MORE}return e.insert=0,t===Z_FINISH$3?(flush_block_only(e,!0),e.strm.avail_out===0?BS_FINISH_STARTED:BS_FINISH_DONE):e.sym_next&&(flush_block_only(e,!1),e.strm.avail_out===0)?BS_NEED_MORE:BS_BLOCK_DONE},deflate_huff=(e,t)=>{let n;for(;;){if(e.lookahead===0&&(fill_window(e),e.lookahead===0)){if(t===Z_NO_FLUSH$2)return BS_NEED_MORE;break}if(e.match_length=0,n=_tr_tally(e,0,e.window[e.strstart]),e.lookahead--,e.strstart++,n&&(flush_block_only(e,!1),e.strm.avail_out===0))return BS_NEED_MORE}return e.insert=0,t===Z_FINISH$3?(flush_block_only(e,!0),e.strm.avail_out===0?BS_FINISH_STARTED:BS_FINISH_DONE):e.sym_next&&(flush_block_only(e,!1),e.strm.avail_out===0)?BS_NEED_MORE:BS_BLOCK_DONE};function Config(e,t,n,r,l){this.good_length=e,this.max_lazy=t,this.nice_length=n,this.max_chain=r,this.func=l}const configuration_table=[new Config(0,0,0,0,deflate_stored),new Config(4,4,8,4,deflate_fast),new Config(4,5,16,8,deflate_fast),new Config(4,6,32,32,deflate_fast),new Config(4,4,16,16,deflate_slow),new Config(8,16,32,32,deflate_slow),new Config(8,16,128,128,deflate_slow),new Config(8,32,128,256,deflate_slow),new Config(32,128,258,1024,deflate_slow),new Config(32,258,258,4096,deflate_slow)],lm_init=e=>{e.window_size=2*e.w_size,zero(e.head),e.max_lazy_match=configuration_table[e.level].max_lazy,e.good_match=configuration_table[e.level].good_length,e.nice_match=configuration_table[e.level].nice_length,e.max_chain_length=configuration_table[e.level].max_chain,e.strstart=0,e.block_start=0,e.lookahead=0,e.insert=0,e.match_length=e.prev_length=MIN_MATCH-1,e.match_available=0,e.ins_h=0};function DeflateState(){this.strm=null,this.status=0,this.pending_buf=null,this.pending_buf_size=0,this.pending_out=0,this.pending=0,this.wrap=0,this.gzhead=null,this.gzindex=0,this.method=Z_DEFLATED$2,this.last_flush=-1,this.w_size=0,this.w_bits=0,this.w_mask=0,this.window=null,this.window_size=0,this.prev=null,this.head=null,this.ins_h=0,this.hash_size=0,this.hash_bits=0,this.hash_mask=0,this.hash_shift=0,this.block_start=0,this.match_length=0,this.prev_match=0,this.match_available=0,this.strstart=0,this.match_start=0,this.lookahead=0,this.prev_length=0,this.max_chain_length=0,this.max_lazy_match=0,this.level=0,this.strategy=0,this.good_match=0,this.nice_match=0,this.dyn_ltree=new Uint16Array(HEAP_SIZE*2),this.dyn_dtree=new Uint16Array((2*D_CODES+1)*2),this.bl_tree=new Uint16Array((2*BL_CODES+1)*2),zero(this.dyn_ltree),zero(this.dyn_dtree),zero(this.bl_tree),this.l_desc=null,this.d_desc=null,this.bl_desc=null,this.bl_count=new Uint16Array(MAX_BITS+1),this.heap=new Uint16Array(2*L_CODES+1),zero(this.heap),this.heap_len=0,this.heap_max=0,this.depth=new Uint16Array(2*L_CODES+1),zero(this.depth),this.sym_buf=0,this.lit_bufsize=0,this.sym_next=0,this.sym_end=0,this.opt_len=0,this.static_len=0,this.matches=0,this.insert=0,this.bi_buf=0,this.bi_valid=0}const deflateStateCheck=e=>{if(!e)return 1;const t=e.state;return!t||t.strm!==e||t.status!==INIT_STATE&&t.status!==GZIP_STATE&&t.status!==EXTRA_STATE&&t.status!==NAME_STATE&&t.status!==COMMENT_STATE&&t.status!==HCRC_STATE&&t.status!==BUSY_STATE&&t.status!==FINISH_STATE?1:0},deflateResetKeep=e=>{if(deflateStateCheck(e))return err(e,Z_STREAM_ERROR$2);e.total_in=e.total_out=0,e.data_type=Z_UNKNOWN;const t=e.state;return t.pending=0,t.pending_out=0,t.wrap<0&&(t.wrap=-t.wrap),t.status=t.wrap===2?GZIP_STATE:t.wrap?INIT_STATE:BUSY_STATE,e.adler=t.wrap===2?0:1,t.last_flush=-2,_tr_init(t),Z_OK$3},deflateReset=e=>{const t=deflateResetKeep(e);return t===Z_OK$3&&lm_init(e.state),t},deflateSetHeader=(e,t)=>deflateStateCheck(e)||e.state.wrap!==2?Z_STREAM_ERROR$2:(e.state.gzhead=t,Z_OK$3),deflateInit2=(e,t,n,r,l,s)=>{if(!e)return Z_STREAM_ERROR$2;let c=1;if(t===Z_DEFAULT_COMPRESSION$1&&(t=6),r<0?(c=0,r=-r):r>15&&(c=2,r-=16),l<1||l>MAX_MEM_LEVEL||n!==Z_DEFLATED$2||r<8||r>15||t<0||t>9||s<0||s>Z_FIXED||r===8&&c!==1)return err(e,Z_STREAM_ERROR$2);r===8&&(r=9);const o=new DeflateState;return e.state=o,o.strm=e,o.status=INIT_STATE,o.wrap=c,o.gzhead=null,o.w_bits=r,o.w_size=1<<o.w_bits,o.w_mask=o.w_size-1,o.hash_bits=l+7,o.hash_size=1<<o.hash_bits,o.hash_mask=o.hash_size-1,o.hash_shift=~~((o.hash_bits+MIN_MATCH-1)/MIN_MATCH),o.window=new Uint8Array(o.w_size*2),o.head=new Uint16Array(o.hash_size),o.prev=new Uint16Array(o.w_size),o.lit_bufsize=1<<l+6,o.pending_buf_size=o.lit_bufsize*4,o.pending_buf=new Uint8Array(o.pending_buf_size),o.sym_buf=o.lit_bufsize,o.sym_end=(o.lit_bufsize-1)*3,o.level=t,o.strategy=s,o.method=n,deflateReset(e)},deflateInit=(e,t)=>deflateInit2(e,t,Z_DEFLATED$2,MAX_WBITS$1,DEF_MEM_LEVEL,Z_DEFAULT_STRATEGY$1),deflate$2=(e,t)=>{if(deflateStateCheck(e)||t>Z_BLOCK$1||t<0)return e?err(e,Z_STREAM_ERROR$2):Z_STREAM_ERROR$2;const n=e.state;if(!e.output||e.avail_in!==0&&!e.input||n.status===FINISH_STATE&&t!==Z_FINISH$3)return err(e,e.avail_out===0?Z_BUF_ERROR$1:Z_STREAM_ERROR$2);const r=n.last_flush;if(n.last_flush=t,n.pending!==0){if(flush_pending(e),e.avail_out===0)return n.last_flush=-1,Z_OK$3}else if(e.avail_in===0&&rank(t)<=rank(r)&&t!==Z_FINISH$3)return err(e,Z_BUF_ERROR$1);if(n.status===FINISH_STATE&&e.avail_in!==0)return err(e,Z_BUF_ERROR$1);if(n.status===INIT_STATE&&n.wrap===0&&(n.status=BUSY_STATE),n.status===INIT_STATE){let l=Z_DEFLATED$2+(n.w_bits-8<<4)<<8,s=-1;if(n.strategy>=Z_HUFFMAN_ONLY||n.level<2?s=0:n.level<6?s=1:n.level===6?s=2:s=3,l|=s<<6,n.strstart!==0&&(l|=PRESET_DICT),l+=31-l%31,putShortMSB(n,l),n.strstart!==0&&(putShortMSB(n,e.adler>>>16),putShortMSB(n,e.adler&65535)),e.adler=1,n.status=BUSY_STATE,flush_pending(e),n.pending!==0)return n.last_flush=-1,Z_OK$3}if(n.status===GZIP_STATE){if(e.adler=0,put_byte(n,31),put_byte(n,139),put_byte(n,8),n.gzhead)put_byte(n,(n.gzhead.text?1:0)+(n.gzhead.hcrc?2:0)+(n.gzhead.extra?4:0)+(n.gzhead.name?8:0)+(n.gzhead.comment?16:0)),put_byte(n,n.gzhead.time&255),put_byte(n,n.gzhead.time>>8&255),put_byte(n,n.gzhead.time>>16&255),put_byte(n,n.gzhead.time>>24&255),put_byte(n,n.level===9?2:n.strategy>=Z_HUFFMAN_ONLY||n.level<2?4:0),put_byte(n,n.gzhead.os&255),n.gzhead.extra&&n.gzhead.extra.length&&(put_byte(n,n.gzhead.extra.length&255),put_byte(n,n.gzhead.extra.length>>8&255)),n.gzhead.hcrc&&(e.adler=crc32_1(e.adler,n.pending_buf,n.pending,0)),n.gzindex=0,n.status=EXTRA_STATE;else if(put_byte(n,0),put_byte(n,0),put_byte(n,0),put_byte(n,0),put_byte(n,0),put_byte(n,n.level===9?2:n.strategy>=Z_HUFFMAN_ONLY||n.level<2?4:0),put_byte(n,OS_CODE),n.status=BUSY_STATE,flush_pending(e),n.pending!==0)return n.last_flush=-1,Z_OK$3}if(n.status===EXTRA_STATE){if(n.gzhead.extra){let l=n.pending,s=(n.gzhead.extra.length&65535)-n.gzindex;for(;n.pending+s>n.pending_buf_size;){let o=n.pending_buf_size-n.pending;if(n.pending_buf.set(n.gzhead.extra.subarray(n.gzindex,n.gzindex+o),n.pending),n.pending=n.pending_buf_size,n.gzhead.hcrc&&n.pending>l&&(e.adler=crc32_1(e.adler,n.pending_buf,n.pending-l,l)),n.gzindex+=o,flush_pending(e),n.pending!==0)return n.last_flush=-1,Z_OK$3;l=0,s-=o}let c=new Uint8Array(n.gzhead.extra);n.pending_buf.set(c.subarray(n.gzindex,n.gzindex+s),n.pending),n.pending+=s,n.gzhead.hcrc&&n.pending>l&&(e.adler=crc32_1(e.adler,n.pending_buf,n.pending-l,l)),n.gzindex=0}n.status=NAME_STATE}if(n.status===NAME_STATE){if(n.gzhead.name){let l=n.pending,s;do{if(n.pending===n.pending_buf_size){if(n.gzhead.hcrc&&n.pending>l&&(e.adler=crc32_1(e.adler,n.pending_buf,n.pending-l,l)),flush_pending(e),n.pending!==0)return n.last_flush=-1,Z_OK$3;l=0}n.gzindex<n.gzhead.name.length?s=n.gzhead.name.charCodeAt(n.gzindex++)&255:s=0,put_byte(n,s)}while(s!==0);n.gzhead.hcrc&&n.pending>l&&(e.adler=crc32_1(e.adler,n.pending_buf,n.pending-l,l)),n.gzindex=0}n.status=COMMENT_STATE}if(n.status===COMMENT_STATE){if(n.gzhead.comment){let l=n.pending,s;do{if(n.pending===n.pending_buf_size){if(n.gzhead.hcrc&&n.pending>l&&(e.adler=crc32_1(e.adler,n.pending_buf,n.pending-l,l)),flush_pending(e),n.pending!==0)return n.last_flush=-1,Z_OK$3;l=0}n.gzindex<n.gzhead.comment.length?s=n.gzhead.comment.charCodeAt(n.gzindex++)&255:s=0,put_byte(n,s)}while(s!==0);n.gzhead.hcrc&&n.pending>l&&(e.adler=crc32_1(e.adler,n.pending_buf,n.pending-l,l))}n.status=HCRC_STATE}if(n.status===HCRC_STATE){if(n.gzhead.hcrc){if(n.pending+2>n.pending_buf_size&&(flush_pending(e),n.pending!==0))return n.last_flush=-1,Z_OK$3;put_byte(n,e.adler&255),put_byte(n,e.adler>>8&255),e.adler=0}if(n.status=BUSY_STATE,flush_pending(e),n.pending!==0)return n.last_flush=-1,Z_OK$3}if(e.avail_in!==0||n.lookahead!==0||t!==Z_NO_FLUSH$2&&n.status!==FINISH_STATE){let l=n.level===0?deflate_stored(n,t):n.strategy===Z_HUFFMAN_ONLY?deflate_huff(n,t):n.strategy===Z_RLE?deflate_rle(n,t):configuration_table[n.level].func(n,t);if((l===BS_FINISH_STARTED||l===BS_FINISH_DONE)&&(n.status=FINISH_STATE),l===BS_NEED_MORE||l===BS_FINISH_STARTED)return e.avail_out===0&&(n.last_flush=-1),Z_OK$3;if(l===BS_BLOCK_DONE&&(t===Z_PARTIAL_FLUSH?_tr_align(n):t!==Z_BLOCK$1&&(_tr_stored_block(n,0,0,!1),t===Z_FULL_FLUSH$1&&(zero(n.head),n.lookahead===0&&(n.strstart=0,n.block_start=0,n.insert=0))),flush_pending(e),e.avail_out===0))return n.last_flush=-1,Z_OK$3}return t!==Z_FINISH$3?Z_OK$3:n.wrap<=0?Z_STREAM_END$3:(n.wrap===2?(put_byte(n,e.adler&255),put_byte(n,e.adler>>8&255),put_byte(n,e.adler>>16&255),put_byte(n,e.adler>>24&255),put_byte(n,e.total_in&255),put_byte(n,e.total_in>>8&255),put_byte(n,e.total_in>>16&255),put_byte(n,e.total_in>>24&255)):(putShortMSB(n,e.adler>>>16),putShortMSB(n,e.adler&65535)),flush_pending(e),n.wrap>0&&(n.wrap=-n.wrap),n.pending!==0?Z_OK$3:Z_STREAM_END$3)},deflateEnd=e=>{if(deflateStateCheck(e))return Z_STREAM_ERROR$2;const t=e.state.status;return e.state=null,t===BUSY_STATE?err(e,Z_DATA_ERROR$2):Z_OK$3},deflateSetDictionary=(e,t)=>{let n=t.length;if(deflateStateCheck(e))return Z_STREAM_ERROR$2;const r=e.state,l=r.wrap;if(l===2||l===1&&r.status!==INIT_STATE||r.lookahead)return Z_STREAM_ERROR$2;if(l===1&&(e.adler=adler32_1(e.adler,t,n,0)),r.wrap=0,n>=r.w_size){l===0&&(zero(r.head),r.strstart=0,r.block_start=0,r.insert=0);let d=new Uint8Array(r.w_size);d.set(t.subarray(n-r.w_size,n),0),t=d,n=r.w_size}const s=e.avail_in,c=e.next_in,o=e.input;for(e.avail_in=n,e.next_in=0,e.input=t,fill_window(r);r.lookahead>=MIN_MATCH;){let d=r.strstart,u=r.lookahead-(MIN_MATCH-1);do r.ins_h=HASH(r,r.ins_h,r.window[d+MIN_MATCH-1]),r.prev[d&r.w_mask]=r.head[r.ins_h],r.head[r.ins_h]=d,d++;while(--u);r.strstart=d,r.lookahead=MIN_MATCH-1,fill_window(r)}return r.strstart+=r.lookahead,r.block_start=r.strstart,r.insert=r.lookahead,r.lookahead=0,r.match_length=r.prev_length=MIN_MATCH-1,r.match_available=0,e.next_in=c,e.input=o,e.avail_in=s,r.wrap=l,Z_OK$3};var deflateInit_1=deflateInit,deflateInit2_1=deflateInit2,deflateReset_1=deflateReset,deflateResetKeep_1=deflateResetKeep,deflateSetHeader_1=deflateSetHeader,deflate_2$1=deflate$2,deflateEnd_1=deflateEnd,deflateSetDictionary_1=deflateSetDictionary,deflateInfo="pako deflate (from Nodeca project)",deflate_1$2={deflateInit:deflateInit_1,deflateInit2:deflateInit2_1,deflateReset:deflateReset_1,deflateResetKeep:deflateResetKeep_1,deflateSetHeader:deflateSetHeader_1,deflate:deflate_2$1,deflateEnd:deflateEnd_1,deflateSetDictionary:deflateSetDictionary_1,deflateInfo};const _has=(e,t)=>Object.prototype.hasOwnProperty.call(e,t);var assign=function(e){const t=Array.prototype.slice.call(arguments,1);for(;t.length;){const n=t.shift();if(n){if(typeof n!="object")throw new TypeError(n+"must be non-object");for(const r in n)_has(n,r)&&(e[r]=n[r])}}return e},flattenChunks=e=>{let t=0;for(let r=0,l=e.length;r<l;r++)t+=e[r].length;const n=new Uint8Array(t);for(let r=0,l=0,s=e.length;r<s;r++){let c=e[r];n.set(c,l),l+=c.length}return n},common={assign,flattenChunks};let STR_APPLY_UIA_OK=!0;try{String.fromCharCode.apply(null,new Uint8Array(1))}catch(e){STR_APPLY_UIA_OK=!1}const _utf8len=new Uint8Array(256);for(let e=0;e<256;e++)_utf8len[e]=e>=252?6:e>=248?5:e>=240?4:e>=224?3:e>=192?2:1;_utf8len[254]=_utf8len[254]=1;var string2buf=e=>{if(typeof TextEncoder=="function"&&TextEncoder.prototype.encode)return new TextEncoder().encode(e);let t,n,r,l,s,c=e.length,o=0;for(l=0;l<c;l++)n=e.charCodeAt(l),(n&64512)===55296&&l+1<c&&(r=e.charCodeAt(l+1),(r&64512)===56320&&(n=65536+(n-55296<<10)+(r-56320),l++)),o+=n<128?1:n<2048?2:n<65536?3:4;for(t=new Uint8Array(o),s=0,l=0;s<o;l++)n=e.charCodeAt(l),(n&64512)===55296&&l+1<c&&(r=e.charCodeAt(l+1),(r&64512)===56320&&(n=65536+(n-55296<<10)+(r-56320),l++)),n<128?t[s++]=n:n<2048?(t[s++]=192|n>>>6,t[s++]=128|n&63):n<65536?(t[s++]=224|n>>>12,t[s++]=128|n>>>6&63,t[s++]=128|n&63):(t[s++]=240|n>>>18,t[s++]=128|n>>>12&63,t[s++]=128|n>>>6&63,t[s++]=128|n&63);return t};const buf2binstring=(e,t)=>{if(t<65534&&e.subarray&&STR_APPLY_UIA_OK)return String.fromCharCode.apply(null,e.length===t?e:e.subarray(0,t));let n="";for(let r=0;r<t;r++)n+=String.fromCharCode(e[r]);return n};var buf2string=(e,t)=>{const n=t||e.length;if(typeof TextDecoder=="function"&&TextDecoder.prototype.decode)return new TextDecoder().decode(e.subarray(0,t));let r,l;const s=new Array(n*2);for(l=0,r=0;r<n;){let c=e[r++];if(c<128){s[l++]=c;continue}let o=_utf8len[c];if(o>4){s[l++]=65533,r+=o-1;continue}for(c&=o===2?31:o===3?15:7;o>1&&r<n;)c=c<<6|e[r++]&63,o--;if(o>1){s[l++]=65533;continue}c<65536?s[l++]=c:(c-=65536,s[l++]=55296|c>>10&1023,s[l++]=56320|c&1023)}return buf2binstring(s,l)},utf8border=(e,t)=>{t=t||e.length,t>e.length&&(t=e.length);let n=t-1;for(;n>=0&&(e[n]&192)===128;)n--;return n<0||n===0?t:n+_utf8len[e[n]]>t?n:t},strings={string2buf,buf2string,utf8border};function ZStream(){this.input=null,this.next_in=0,this.avail_in=0,this.total_in=0,this.output=null,this.next_out=0,this.avail_out=0,this.total_out=0,this.msg="",this.state=null,this.data_type=2,this.adler=0}var zstream=ZStream;const toString$1=Object.prototype.toString,{Z_NO_FLUSH:Z_NO_FLUSH$1,Z_SYNC_FLUSH,Z_FULL_FLUSH,Z_FINISH:Z_FINISH$2,Z_OK:Z_OK$2,Z_STREAM_END:Z_STREAM_END$2,Z_DEFAULT_COMPRESSION,Z_DEFAULT_STRATEGY,Z_DEFLATED:Z_DEFLATED$1}=constants$2;function Deflate$1(e){this.options=common.assign({level:Z_DEFAULT_COMPRESSION,method:Z_DEFLATED$1,chunkSize:16384,windowBits:15,memLevel:8,strategy:Z_DEFAULT_STRATEGY},e||{});let t=this.options;t.raw&&t.windowBits>0?t.windowBits=-t.windowBits:t.gzip&&t.windowBits>0&&t.windowBits<16&&(t.windowBits+=16),this.err=0,this.msg="",this.ended=!1,this.chunks=[],this.strm=new zstream,this.strm.avail_out=0;let n=deflate_1$2.deflateInit2(this.strm,t.level,t.method,t.windowBits,t.memLevel,t.strategy);if(n!==Z_OK$2)throw new Error(messages[n]);if(t.header&&deflate_1$2.deflateSetHeader(this.strm,t.header),t.dictionary){let r;if(typeof t.dictionary=="string"?r=strings.string2buf(t.dictionary):toString$1.call(t.dictionary)==="[object ArrayBuffer]"?r=new Uint8Array(t.dictionary):r=t.dictionary,n=deflate_1$2.deflateSetDictionary(this.strm,r),n!==Z_OK$2)throw new Error(messages[n]);this._dict_set=!0}}Deflate$1.prototype.push=function(e,t){const n=this.strm,r=this.options.chunkSize;let l,s;if(this.ended)return!1;for(t===~~t?s=t:s=t===!0?Z_FINISH$2:Z_NO_FLUSH$1,typeof e=="string"?n.input=strings.string2buf(e):toString$1.call(e)==="[object ArrayBuffer]"?n.input=new Uint8Array(e):n.input=e,n.next_in=0,n.avail_in=n.input.length;;){if(n.avail_out===0&&(n.output=new Uint8Array(r),n.next_out=0,n.avail_out=r),(s===Z_SYNC_FLUSH||s===Z_FULL_FLUSH)&&n.avail_out<=6){this.onData(n.output.subarray(0,n.next_out)),n.avail_out=0;continue}if(l=deflate_1$2.deflate(n,s),l===Z_STREAM_END$2)return n.next_out>0&&this.onData(n.output.subarray(0,n.next_out)),l=deflate_1$2.deflateEnd(this.strm),this.onEnd(l),this.ended=!0,l===Z_OK$2;if(n.avail_out===0){this.onData(n.output);continue}if(s>0&&n.next_out>0){this.onData(n.output.subarray(0,n.next_out)),n.avail_out=0;continue}if(n.avail_in===0)break}return!0};Deflate$1.prototype.onData=function(e){this.chunks.push(e)};Deflate$1.prototype.onEnd=function(e){e===Z_OK$2&&(this.result=common.flattenChunks(this.chunks)),this.chunks=[],this.err=e,this.msg=this.strm.msg};function deflate$1(e,t){const n=new Deflate$1(t);if(n.push(e,!0),n.err)throw n.msg||messages[n.err];return n.result}function deflateRaw$1(e,t){return t=t||{},t.raw=!0,deflate$1(e,t)}function gzip$1(e,t){return t=t||{},t.gzip=!0,deflate$1(e,t)}var Deflate_1$1=Deflate$1,deflate_2=deflate$1,deflateRaw_1$1=deflateRaw$1,gzip_1$1=gzip$1,constants$1=constants$2,deflate_1$1={Deflate:Deflate_1$1,deflate:deflate_2,deflateRaw:deflateRaw_1$1,gzip:gzip_1$1,constants:constants$1};const BAD$1=16209,TYPE$1=16191;var inffast=function e(t,n){let r,l,s,c,o,d,u,U,B,R,p,g,h,m,N,D,y,b,F,v,j,K,f,Q;const P=t.state;r=t.next_in,f=t.input,l=r+(t.avail_in-5),s=t.next_out,Q=t.output,c=s-(n-t.avail_out),o=s+(t.avail_out-257),d=P.dmax,u=P.wsize,U=P.whave,B=P.wnext,R=P.window,p=P.hold,g=P.bits,h=P.lencode,m=P.distcode,N=(1<<P.lenbits)-1,D=(1<<P.distbits)-1;e:do{g<15&&(p+=f[r++]<<g,g+=8,p+=f[r++]<<g,g+=8),y=h[p&N];t:for(;;){if(b=y>>>24,p>>>=b,g-=b,b=y>>>16&255,b===0)Q[s++]=y&65535;else if(b&16){F=y&65535,b&=15,b&&(g<b&&(p+=f[r++]<<g,g+=8),F+=p&(1<<b)-1,p>>>=b,g-=b),g<15&&(p+=f[r++]<<g,g+=8,p+=f[r++]<<g,g+=8),y=m[p&D];n:for(;;){if(b=y>>>24,p>>>=b,g-=b,b=y>>>16&255,b&16){if(v=y&65535,b&=15,g<b&&(p+=f[r++]<<g,g+=8,g<b&&(p+=f[r++]<<g,g+=8)),v+=p&(1<<b)-1,v>d){t.msg="invalid distance too far back",P.mode=BAD$1;break e}if(p>>>=b,g-=b,b=s-c,v>b){if(b=v-b,b>U&&P.sane){t.msg="invalid distance too far back",P.mode=BAD$1;break e}if(j=0,K=R,B===0){if(j+=u-b,b<F){F-=b;do Q[s++]=R[j++];while(--b);j=s-v,K=Q}}else if(B<b){if(j+=u+B-b,b-=B,b<F){F-=b;do Q[s++]=R[j++];while(--b);if(j=0,B<F){b=B,F-=b;do Q[s++]=R[j++];while(--b);j=s-v,K=Q}}}else if(j+=B-b,b<F){F-=b;do Q[s++]=R[j++];while(--b);j=s-v,K=Q}for(;F>2;)Q[s++]=K[j++],Q[s++]=K[j++],Q[s++]=K[j++],F-=3;F&&(Q[s++]=K[j++],F>1&&(Q[s++]=K[j++]))}else{j=s-v;do Q[s++]=Q[j++],Q[s++]=Q[j++],Q[s++]=Q[j++],F-=3;while(F>2);F&&(Q[s++]=Q[j++],F>1&&(Q[s++]=Q[j++]))}}else if(b&64){t.msg="invalid distance code",P.mode=BAD$1;break e}else{y=m[(y&65535)+(p&(1<<b)-1)];continue n}break}}else if(b&64)if(b&32){P.mode=TYPE$1;break e}else{t.msg="invalid literal/length code",P.mode=BAD$1;break e}else{y=h[(y&65535)+(p&(1<<b)-1)];continue t}break}}while(r<l&&s<o);F=g>>3,r-=F,g-=F<<3,p&=(1<<g)-1,t.next_in=r,t.next_out=s,t.avail_in=r<l?5+(l-r):5-(r-l),t.avail_out=s<o?257+(o-s):257-(s-o),P.hold=p,P.bits=g};const MAXBITS=15,ENOUGH_LENS$1=852,ENOUGH_DISTS$1=592,CODES$1=0,LENS$1=1,DISTS$1=2,lbase=new Uint16Array([3,4,5,6,7,8,9,10,11,13,15,17,19,23,27,31,35,43,51,59,67,83,99,115,131,163,195,227,258,0,0]),lext=new Uint8Array([16,16,16,16,16,16,16,16,17,17,17,17,18,18,18,18,19,19,19,19,20,20,20,20,21,21,21,21,16,72,78]),dbase=new Uint16Array([1,2,3,4,5,7,9,13,17,25,33,49,65,97,129,193,257,385,513,769,1025,1537,2049,3073,4097,6145,8193,12289,16385,24577,0,0]),dext=new Uint8Array([16,16,16,16,17,17,18,18,19,19,20,20,21,21,22,22,23,23,24,24,25,25,26,26,27,27,28,28,29,29,64,64]),inflate_table=(e,t,n,r,l,s,c,o)=>{const d=o.bits;let u=0,U=0,B=0,R=0,p=0,g=0,h=0,m=0,N=0,D=0,y,b,F,v,j,K=null,f;const Q=new Uint16Array(MAXBITS+1),P=new Uint16Array(MAXBITS+1);let w=null,V,I,W;for(u=0;u<=MAXBITS;u++)Q[u]=0;for(U=0;U<r;U++)Q[t[n+U]]++;for(p=d,R=MAXBITS;R>=1&&Q[R]===0;R--);if(p>R&&(p=R),R===0)return l[s++]=1<<24|64<<16|0,l[s++]=1<<24|64<<16|0,o.bits=1,0;for(B=1;B<R&&Q[B]===0;B++);for(p<B&&(p=B),m=1,u=1;u<=MAXBITS;u++)if(m<<=1,m-=Q[u],m<0)return-1;if(m>0&&(e===CODES$1||R!==1))return-1;for(P[1]=0,u=1;u<MAXBITS;u++)P[u+1]=P[u]+Q[u];for(U=0;U<r;U++)t[n+U]!==0&&(c[P[t[n+U]]++]=U);if(e===CODES$1?(K=w=c,f=20):e===LENS$1?(K=lbase,w=lext,f=257):(K=dbase,w=dext,f=0),D=0,U=0,u=B,j=s,g=p,h=0,F=-1,N=1<<p,v=N-1,e===LENS$1&&N>ENOUGH_LENS$1||e===DISTS$1&&N>ENOUGH_DISTS$1)return 1;for(;;){V=u-h,c[U]+1<f?(I=0,W=c[U]):c[U]>=f?(I=w[c[U]-f],W=K[c[U]-f]):(I=32+64,W=0),y=1<<u-h,b=1<<g,B=b;do b-=y,l[j+(D>>h)+b]=V<<24|I<<16|W|0;while(b!==0);for(y=1<<u-1;D&y;)y>>=1;if(y!==0?(D&=y-1,D+=y):D=0,U++,--Q[u]===0){if(u===R)break;u=t[n+c[U]]}if(u>p&&(D&v)!==F){for(h===0&&(h=p),j+=B,g=u-h,m=1<<g;g+h<R&&(m-=Q[g+h],!(m<=0));)g++,m<<=1;if(N+=1<<g,e===LENS$1&&N>ENOUGH_LENS$1||e===DISTS$1&&N>ENOUGH_DISTS$1)return 1;F=D&v,l[F]=p<<24|g<<16|j-s|0}}return D!==0&&(l[j+D]=u-h<<24|64<<16|0),o.bits=p,0};var inftrees=inflate_table;const CODES=0,LENS=1,DISTS=2,{Z_FINISH:Z_FINISH$1,Z_BLOCK,Z_TREES,Z_OK:Z_OK$1,Z_STREAM_END:Z_STREAM_END$1,Z_NEED_DICT:Z_NEED_DICT$1,Z_STREAM_ERROR:Z_STREAM_ERROR$1,Z_DATA_ERROR:Z_DATA_ERROR$1,Z_MEM_ERROR:Z_MEM_ERROR$1,Z_BUF_ERROR,Z_DEFLATED}=constants$2,HEAD=16180,FLAGS=16181,TIME=16182,OS=16183,EXLEN=16184,EXTRA=16185,NAME=16186,COMMENT=16187,HCRC=16188,DICTID=16189,DICT=16190,TYPE=16191,TYPEDO=16192,STORED=16193,COPY_=16194,COPY=16195,TABLE=16196,LENLENS=16197,CODELENS=16198,LEN_=16199,LEN=16200,LENEXT=16201,DIST=16202,DISTEXT=16203,MATCH=16204,LIT=16205,CHECK=16206,LENGTH=16207,DONE=16208,BAD=16209,MEM=16210,SYNC=16211,ENOUGH_LENS=852,ENOUGH_DISTS=592,MAX_WBITS=15,DEF_WBITS=MAX_WBITS,zswap32=e=>(e>>>24&255)+(e>>>8&65280)+((e&65280)<<8)+((e&255)<<24);function InflateState(){this.strm=null,this.mode=0,this.last=!1,this.wrap=0,this.havedict=!1,this.flags=0,this.dmax=0,this.check=0,this.total=0,this.head=null,this.wbits=0,this.wsize=0,this.whave=0,this.wnext=0,this.window=null,this.hold=0,this.bits=0,this.length=0,this.offset=0,this.extra=0,this.lencode=null,this.distcode=null,this.lenbits=0,this.distbits=0,this.ncode=0,this.nlen=0,this.ndist=0,this.have=0,this.next=null,this.lens=new Uint16Array(320),this.work=new Uint16Array(288),this.lendyn=null,this.distdyn=null,this.sane=0,this.back=0,this.was=0}const inflateStateCheck=e=>{if(!e)return 1;const t=e.state;return!t||t.strm!==e||t.mode<HEAD||t.mode>SYNC?1:0},inflateResetKeep=e=>{if(inflateStateCheck(e))return Z_STREAM_ERROR$1;const t=e.state;return e.total_in=e.total_out=t.total=0,e.msg="",t.wrap&&(e.adler=t.wrap&1),t.mode=HEAD,t.last=0,t.havedict=0,t.flags=-1,t.dmax=32768,t.head=null,t.hold=0,t.bits=0,t.lencode=t.lendyn=new Int32Array(ENOUGH_LENS),t.distcode=t.distdyn=new Int32Array(ENOUGH_DISTS),t.sane=1,t.back=-1,Z_OK$1},inflateReset=e=>{if(inflateStateCheck(e))return Z_STREAM_ERROR$1;const t=e.state;return t.wsize=0,t.whave=0,t.wnext=0,inflateResetKeep(e)},inflateReset2=(e,t)=>{let n;if(inflateStateCheck(e))return Z_STREAM_ERROR$1;const r=e.state;return t<0?(n=0,t=-t):(n=(t>>4)+5,t<48&&(t&=15)),t&&(t<8||t>15)?Z_STREAM_ERROR$1:(r.window!==null&&r.wbits!==t&&(r.window=null),r.wrap=n,r.wbits=t,inflateReset(e))},inflateInit2=(e,t)=>{if(!e)return Z_STREAM_ERROR$1;const n=new InflateState;e.state=n,n.strm=e,n.window=null,n.mode=HEAD;const r=inflateReset2(e,t);return r!==Z_OK$1&&(e.state=null),r},inflateInit=e=>inflateInit2(e,DEF_WBITS);let virgin=!0,lenfix,distfix;const fixedtables=e=>{if(virgin){lenfix=new Int32Array(512),distfix=new Int32Array(32);let t=0;for(;t<144;)e.lens[t++]=8;for(;t<256;)e.lens[t++]=9;for(;t<280;)e.lens[t++]=7;for(;t<288;)e.lens[t++]=8;for(inftrees(LENS,e.lens,0,288,lenfix,0,e.work,{bits:9}),t=0;t<32;)e.lens[t++]=5;inftrees(DISTS,e.lens,0,32,distfix,0,e.work,{bits:5}),virgin=!1}e.lencode=lenfix,e.lenbits=9,e.distcode=distfix,e.distbits=5},updatewindow=(e,t,n,r)=>{let l;const s=e.state;return s.window===null&&(s.wsize=1<<s.wbits,s.wnext=0,s.whave=0,s.window=new Uint8Array(s.wsize)),r>=s.wsize?(s.window.set(t.subarray(n-s.wsize,n),0),s.wnext=0,s.whave=s.wsize):(l=s.wsize-s.wnext,l>r&&(l=r),s.window.set(t.subarray(n-r,n-r+l),s.wnext),r-=l,r?(s.window.set(t.subarray(n-r,n),0),s.wnext=r,s.whave=s.wsize):(s.wnext+=l,s.wnext===s.wsize&&(s.wnext=0),s.whave<s.wsize&&(s.whave+=l))),0},inflate$2=(e,t)=>{let n,r,l,s,c,o,d,u,U,B,R,p,g,h,m=0,N,D,y,b,F,v,j,K;const f=new Uint8Array(4);let Q,P;const w=new Uint8Array([16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15]);if(inflateStateCheck(e)||!e.output||!e.input&&e.avail_in!==0)return Z_STREAM_ERROR$1;n=e.state,n.mode===TYPE&&(n.mode=TYPEDO),c=e.next_out,l=e.output,d=e.avail_out,s=e.next_in,r=e.input,o=e.avail_in,u=n.hold,U=n.bits,B=o,R=d,K=Z_OK$1;e:for(;;)switch(n.mode){case HEAD:if(n.wrap===0){n.mode=TYPEDO;break}for(;U<16;){if(o===0)break e;o--,u+=r[s++]<<U,U+=8}if(n.wrap&2&&u===35615){n.wbits===0&&(n.wbits=15),n.check=0,f[0]=u&255,f[1]=u>>>8&255,n.check=crc32_1(n.check,f,2,0),u=0,U=0,n.mode=FLAGS;break}if(n.head&&(n.head.done=!1),!(n.wrap&1)||(((u&255)<<8)+(u>>8))%31){e.msg="incorrect header check",n.mode=BAD;break}if((u&15)!==Z_DEFLATED){e.msg="unknown compression method",n.mode=BAD;break}if(u>>>=4,U-=4,j=(u&15)+8,n.wbits===0&&(n.wbits=j),j>15||j>n.wbits){e.msg="invalid window size",n.mode=BAD;break}n.dmax=1<<n.wbits,n.flags=0,e.adler=n.check=1,n.mode=u&512?DICTID:TYPE,u=0,U=0;break;case FLAGS:for(;U<16;){if(o===0)break e;o--,u+=r[s++]<<U,U+=8}if(n.flags=u,(n.flags&255)!==Z_DEFLATED){e.msg="unknown compression method",n.mode=BAD;break}if(n.flags&57344){e.msg="unknown header flags set",n.mode=BAD;break}n.head&&(n.head.text=u>>8&1),n.flags&512&&n.wrap&4&&(f[0]=u&255,f[1]=u>>>8&255,n.check=crc32_1(n.check,f,2,0)),u=0,U=0,n.mode=TIME;case TIME:for(;U<32;){if(o===0)break e;o--,u+=r[s++]<<U,U+=8}n.head&&(n.head.time=u),n.flags&512&&n.wrap&4&&(f[0]=u&255,f[1]=u>>>8&255,f[2]=u>>>16&255,f[3]=u>>>24&255,n.check=crc32_1(n.check,f,4,0)),u=0,U=0,n.mode=OS;case OS:for(;U<16;){if(o===0)break e;o--,u+=r[s++]<<U,U+=8}n.head&&(n.head.xflags=u&255,n.head.os=u>>8),n.flags&512&&n.wrap&4&&(f[0]=u&255,f[1]=u>>>8&255,n.check=crc32_1(n.check,f,2,0)),u=0,U=0,n.mode=EXLEN;case EXLEN:if(n.flags&1024){for(;U<16;){if(o===0)break e;o--,u+=r[s++]<<U,U+=8}n.length=u,n.head&&(n.head.extra_len=u),n.flags&512&&n.wrap&4&&(f[0]=u&255,f[1]=u>>>8&255,n.check=crc32_1(n.check,f,2,0)),u=0,U=0}else n.head&&(n.head.extra=null);n.mode=EXTRA;case EXTRA:if(n.flags&1024&&(p=n.length,p>o&&(p=o),p&&(n.head&&(j=n.head.extra_len-n.length,n.head.extra||(n.head.extra=new Uint8Array(n.head.extra_len)),n.head.extra.set(r.subarray(s,s+p),j)),n.flags&512&&n.wrap&4&&(n.check=crc32_1(n.check,r,p,s)),o-=p,s+=p,n.length-=p),n.length))break e;n.length=0,n.mode=NAME;case NAME:if(n.flags&2048){if(o===0)break e;p=0;do j=r[s+p++],n.head&&j&&n.length<65536&&(n.head.name+=String.fromCharCode(j));while(j&&p<o);if(n.flags&512&&n.wrap&4&&(n.check=crc32_1(n.check,r,p,s)),o-=p,s+=p,j)break e}else n.head&&(n.head.name=null);n.length=0,n.mode=COMMENT;case COMMENT:if(n.flags&4096){if(o===0)break e;p=0;do j=r[s+p++],n.head&&j&&n.length<65536&&(n.head.comment+=String.fromCharCode(j));while(j&&p<o);if(n.flags&512&&n.wrap&4&&(n.check=crc32_1(n.check,r,p,s)),o-=p,s+=p,j)break e}else n.head&&(n.head.comment=null);n.mode=HCRC;case HCRC:if(n.flags&512){for(;U<16;){if(o===0)break e;o--,u+=r[s++]<<U,U+=8}if(n.wrap&4&&u!==(n.check&65535)){e.msg="header crc mismatch",n.mode=BAD;break}u=0,U=0}n.head&&(n.head.hcrc=n.flags>>9&1,n.head.done=!0),e.adler=n.check=0,n.mode=TYPE;break;case DICTID:for(;U<32;){if(o===0)break e;o--,u+=r[s++]<<U,U+=8}e.adler=n.check=zswap32(u),u=0,U=0,n.mode=DICT;case DICT:if(n.havedict===0)return e.next_out=c,e.avail_out=d,e.next_in=s,e.avail_in=o,n.hold=u,n.bits=U,Z_NEED_DICT$1;e.adler=n.check=1,n.mode=TYPE;case TYPE:if(t===Z_BLOCK||t===Z_TREES)break e;case TYPEDO:if(n.last){u>>>=U&7,U-=U&7,n.mode=CHECK;break}for(;U<3;){if(o===0)break e;o--,u+=r[s++]<<U,U+=8}switch(n.last=u&1,u>>>=1,U-=1,u&3){case 0:n.mode=STORED;break;case 1:if(fixedtables(n),n.mode=LEN_,t===Z_TREES){u>>>=2,U-=2;break e}break;case 2:n.mode=TABLE;break;case 3:e.msg="invalid block type",n.mode=BAD}u>>>=2,U-=2;break;case STORED:for(u>>>=U&7,U-=U&7;U<32;){if(o===0)break e;o--,u+=r[s++]<<U,U+=8}if((u&65535)!==(u>>>16^65535)){e.msg="invalid stored block lengths",n.mode=BAD;break}if(n.length=u&65535,u=0,U=0,n.mode=COPY_,t===Z_TREES)break e;case COPY_:n.mode=COPY;case COPY:if(p=n.length,p){if(p>o&&(p=o),p>d&&(p=d),p===0)break e;l.set(r.subarray(s,s+p),c),o-=p,s+=p,d-=p,c+=p,n.length-=p;break}n.mode=TYPE;break;case TABLE:for(;U<14;){if(o===0)break e;o--,u+=r[s++]<<U,U+=8}if(n.nlen=(u&31)+257,u>>>=5,U-=5,n.ndist=(u&31)+1,u>>>=5,U-=5,n.ncode=(u&15)+4,u>>>=4,U-=4,n.nlen>286||n.ndist>30){e.msg="too many length or distance symbols",n.mode=BAD;break}n.have=0,n.mode=LENLENS;case LENLENS:for(;n.have<n.ncode;){for(;U<3;){if(o===0)break e;o--,u+=r[s++]<<U,U+=8}n.lens[w[n.have++]]=u&7,u>>>=3,U-=3}for(;n.have<19;)n.lens[w[n.have++]]=0;if(n.lencode=n.lendyn,n.lenbits=7,Q={bits:n.lenbits},K=inftrees(CODES,n.lens,0,19,n.lencode,0,n.work,Q),n.lenbits=Q.bits,K){e.msg="invalid code lengths set",n.mode=BAD;break}n.have=0,n.mode=CODELENS;case CODELENS:for(;n.have<n.nlen+n.ndist;){for(;m=n.lencode[u&(1<<n.lenbits)-1],N=m>>>24,D=m>>>16&255,y=m&65535,!(N<=U);){if(o===0)break e;o--,u+=r[s++]<<U,U+=8}if(y<16)u>>>=N,U-=N,n.lens[n.have++]=y;else{if(y===16){for(P=N+2;U<P;){if(o===0)break e;o--,u+=r[s++]<<U,U+=8}if(u>>>=N,U-=N,n.have===0){e.msg="invalid bit length repeat",n.mode=BAD;break}j=n.lens[n.have-1],p=3+(u&3),u>>>=2,U-=2}else if(y===17){for(P=N+3;U<P;){if(o===0)break e;o--,u+=r[s++]<<U,U+=8}u>>>=N,U-=N,j=0,p=3+(u&7),u>>>=3,U-=3}else{for(P=N+7;U<P;){if(o===0)break e;o--,u+=r[s++]<<U,U+=8}u>>>=N,U-=N,j=0,p=11+(u&127),u>>>=7,U-=7}if(n.have+p>n.nlen+n.ndist){e.msg="invalid bit length repeat",n.mode=BAD;break}for(;p--;)n.lens[n.have++]=j}}if(n.mode===BAD)break;if(n.lens[256]===0){e.msg="invalid code -- missing end-of-block",n.mode=BAD;break}if(n.lenbits=9,Q={bits:n.lenbits},K=inftrees(LENS,n.lens,0,n.nlen,n.lencode,0,n.work,Q),n.lenbits=Q.bits,K){e.msg="invalid literal/lengths set",n.mode=BAD;break}if(n.distbits=6,n.distcode=n.distdyn,Q={bits:n.distbits},K=inftrees(DISTS,n.lens,n.nlen,n.ndist,n.distcode,0,n.work,Q),n.distbits=Q.bits,K){e.msg="invalid distances set",n.mode=BAD;break}if(n.mode=LEN_,t===Z_TREES)break e;case LEN_:n.mode=LEN;case LEN:if(o>=6&&d>=258){e.next_out=c,e.avail_out=d,e.next_in=s,e.avail_in=o,n.hold=u,n.bits=U,inffast(e,R),c=e.next_out,l=e.output,d=e.avail_out,s=e.next_in,r=e.input,o=e.avail_in,u=n.hold,U=n.bits,n.mode===TYPE&&(n.back=-1);break}for(n.back=0;m=n.lencode[u&(1<<n.lenbits)-1],N=m>>>24,D=m>>>16&255,y=m&65535,!(N<=U);){if(o===0)break e;o--,u+=r[s++]<<U,U+=8}if(D&&!(D&240)){for(b=N,F=D,v=y;m=n.lencode[v+((u&(1<<b+F)-1)>>b)],N=m>>>24,D=m>>>16&255,y=m&65535,!(b+N<=U);){if(o===0)break e;o--,u+=r[s++]<<U,U+=8}u>>>=b,U-=b,n.back+=b}if(u>>>=N,U-=N,n.back+=N,n.length=y,D===0){n.mode=LIT;break}if(D&32){n.back=-1,n.mode=TYPE;break}if(D&64){e.msg="invalid literal/length code",n.mode=BAD;break}n.extra=D&15,n.mode=LENEXT;case LENEXT:if(n.extra){for(P=n.extra;U<P;){if(o===0)break e;o--,u+=r[s++]<<U,U+=8}n.length+=u&(1<<n.extra)-1,u>>>=n.extra,U-=n.extra,n.back+=n.extra}n.was=n.length,n.mode=DIST;case DIST:for(;m=n.distcode[u&(1<<n.distbits)-1],N=m>>>24,D=m>>>16&255,y=m&65535,!(N<=U);){if(o===0)break e;o--,u+=r[s++]<<U,U+=8}if(!(D&240)){for(b=N,F=D,v=y;m=n.distcode[v+((u&(1<<b+F)-1)>>b)],N=m>>>24,D=m>>>16&255,y=m&65535,!(b+N<=U);){if(o===0)break e;o--,u+=r[s++]<<U,U+=8}u>>>=b,U-=b,n.back+=b}if(u>>>=N,U-=N,n.back+=N,D&64){e.msg="invalid distance code",n.mode=BAD;break}n.offset=y,n.extra=D&15,n.mode=DISTEXT;case DISTEXT:if(n.extra){for(P=n.extra;U<P;){if(o===0)break e;o--,u+=r[s++]<<U,U+=8}n.offset+=u&(1<<n.extra)-1,u>>>=n.extra,U-=n.extra,n.back+=n.extra}if(n.offset>n.dmax){e.msg="invalid distance too far back",n.mode=BAD;break}n.mode=MATCH;case MATCH:if(d===0)break e;if(p=R-d,n.offset>p){if(p=n.offset-p,p>n.whave&&n.sane){e.msg="invalid distance too far back",n.mode=BAD;break}p>n.wnext?(p-=n.wnext,g=n.wsize-p):g=n.wnext-p,p>n.length&&(p=n.length),h=n.window}else h=l,g=c-n.offset,p=n.length;p>d&&(p=d),d-=p,n.length-=p;do l[c++]=h[g++];while(--p);n.length===0&&(n.mode=LEN);break;case LIT:if(d===0)break e;l[c++]=n.length,d--,n.mode=LEN;break;case CHECK:if(n.wrap){for(;U<32;){if(o===0)break e;o--,u|=r[s++]<<U,U+=8}if(R-=d,e.total_out+=R,n.total+=R,n.wrap&4&&R&&(e.adler=n.check=n.flags?crc32_1(n.check,l,R,c-R):adler32_1(n.check,l,R,c-R)),R=d,n.wrap&4&&(n.flags?u:zswap32(u))!==n.check){e.msg="incorrect data check",n.mode=BAD;break}u=0,U=0}n.mode=LENGTH;case LENGTH:if(n.wrap&&n.flags){for(;U<32;){if(o===0)break e;o--,u+=r[s++]<<U,U+=8}if(n.wrap&4&&u!==(n.total&4294967295)){e.msg="incorrect length check",n.mode=BAD;break}u=0,U=0}n.mode=DONE;case DONE:K=Z_STREAM_END$1;break e;case BAD:K=Z_DATA_ERROR$1;break e;case MEM:return Z_MEM_ERROR$1;case SYNC:default:return Z_STREAM_ERROR$1}return e.next_out=c,e.avail_out=d,e.next_in=s,e.avail_in=o,n.hold=u,n.bits=U,(n.wsize||R!==e.avail_out&&n.mode<BAD&&(n.mode<CHECK||t!==Z_FINISH$1))&&updatewindow(e,e.output,e.next_out,R-e.avail_out),B-=e.avail_in,R-=e.avail_out,e.total_in+=B,e.total_out+=R,n.total+=R,n.wrap&4&&R&&(e.adler=n.check=n.flags?crc32_1(n.check,l,R,e.next_out-R):adler32_1(n.check,l,R,e.next_out-R)),e.data_type=n.bits+(n.last?64:0)+(n.mode===TYPE?128:0)+(n.mode===LEN_||n.mode===COPY_?256:0),(B===0&&R===0||t===Z_FINISH$1)&&K===Z_OK$1&&(K=Z_BUF_ERROR),K},inflateEnd=e=>{if(inflateStateCheck(e))return Z_STREAM_ERROR$1;let t=e.state;return t.window&&(t.window=null),e.state=null,Z_OK$1},inflateGetHeader=(e,t)=>{if(inflateStateCheck(e))return Z_STREAM_ERROR$1;const n=e.state;return n.wrap&2?(n.head=t,t.done=!1,Z_OK$1):Z_STREAM_ERROR$1},inflateSetDictionary=(e,t)=>{const n=t.length;let r,l,s;return inflateStateCheck(e)||(r=e.state,r.wrap!==0&&r.mode!==DICT)?Z_STREAM_ERROR$1:r.mode===DICT&&(l=1,l=adler32_1(l,t,n,0),l!==r.check)?Z_DATA_ERROR$1:(s=updatewindow(e,t,n,n),s?(r.mode=MEM,Z_MEM_ERROR$1):(r.havedict=1,Z_OK$1))};var inflateReset_1=inflateReset,inflateReset2_1=inflateReset2,inflateResetKeep_1=inflateResetKeep,inflateInit_1=inflateInit,inflateInit2_1=inflateInit2,inflate_2$1=inflate$2,inflateEnd_1=inflateEnd,inflateGetHeader_1=inflateGetHeader,inflateSetDictionary_1=inflateSetDictionary,inflateInfo="pako inflate (from Nodeca project)",inflate_1$2={inflateReset:inflateReset_1,inflateReset2:inflateReset2_1,inflateResetKeep:inflateResetKeep_1,inflateInit:inflateInit_1,inflateInit2:inflateInit2_1,inflate:inflate_2$1,inflateEnd:inflateEnd_1,inflateGetHeader:inflateGetHeader_1,inflateSetDictionary:inflateSetDictionary_1,inflateInfo};function GZheader(){this.text=0,this.time=0,this.xflags=0,this.os=0,this.extra=null,this.extra_len=0,this.name="",this.comment="",this.hcrc=0,this.done=!1}var gzheader=GZheader;const toString=Object.prototype.toString,{Z_NO_FLUSH,Z_FINISH,Z_OK,Z_STREAM_END,Z_NEED_DICT,Z_STREAM_ERROR,Z_DATA_ERROR,Z_MEM_ERROR}=constants$2;function Inflate$1(e){this.options=common.assign({chunkSize:1024*64,windowBits:15,to:""},e||{});const t=this.options;t.raw&&t.windowBits>=0&&t.windowBits<16&&(t.windowBits=-t.windowBits,t.windowBits===0&&(t.windowBits=-15)),t.windowBits>=0&&t.windowBits<16&&!(e&&e.windowBits)&&(t.windowBits+=32),t.windowBits>15&&t.windowBits<48&&(t.windowBits&15||(t.windowBits|=15)),this.err=0,this.msg="",this.ended=!1,this.chunks=[],this.strm=new zstream,this.strm.avail_out=0;let n=inflate_1$2.inflateInit2(this.strm,t.windowBits);if(n!==Z_OK)throw new Error(messages[n]);if(this.header=new gzheader,inflate_1$2.inflateGetHeader(this.strm,this.header),t.dictionary&&(typeof t.dictionary=="string"?t.dictionary=strings.string2buf(t.dictionary):toString.call(t.dictionary)==="[object ArrayBuffer]"&&(t.dictionary=new Uint8Array(t.dictionary)),t.raw&&(n=inflate_1$2.inflateSetDictionary(this.strm,t.dictionary),n!==Z_OK)))throw new Error(messages[n])}Inflate$1.prototype.push=function(e,t){const n=this.strm,r=this.options.chunkSize,l=this.options.dictionary;let s,c,o;if(this.ended)return!1;for(t===~~t?c=t:c=t===!0?Z_FINISH:Z_NO_FLUSH,toString.call(e)==="[object ArrayBuffer]"?n.input=new Uint8Array(e):n.input=e,n.next_in=0,n.avail_in=n.input.length;;){for(n.avail_out===0&&(n.output=new Uint8Array(r),n.next_out=0,n.avail_out=r),s=inflate_1$2.inflate(n,c),s===Z_NEED_DICT&&l&&(s=inflate_1$2.inflateSetDictionary(n,l),s===Z_OK?s=inflate_1$2.inflate(n,c):s===Z_DATA_ERROR&&(s=Z_NEED_DICT));n.avail_in>0&&s===Z_STREAM_END&&n.state.wrap>0&&e[n.next_in]!==0;)inflate_1$2.inflateReset(n),s=inflate_1$2.inflate(n,c);switch(s){case Z_STREAM_ERROR:case Z_DATA_ERROR:case Z_NEED_DICT:case Z_MEM_ERROR:return this.onEnd(s),this.ended=!0,!1}if(o=n.avail_out,n.next_out&&(n.avail_out===0||s===Z_STREAM_END))if(this.options.to==="string"){let d=strings.utf8border(n.output,n.next_out),u=n.next_out-d,U=strings.buf2string(n.output,d);n.next_out=u,n.avail_out=r-u,u&&n.output.set(n.output.subarray(d,d+u),0),this.onData(U)}else this.onData(n.output.length===n.next_out?n.output:n.output.subarray(0,n.next_out));if(!(s===Z_OK&&o===0)){if(s===Z_STREAM_END)return s=inflate_1$2.inflateEnd(this.strm),this.onEnd(s),this.ended=!0,!0;if(n.avail_in===0)break}}return!0};Inflate$1.prototype.onData=function(e){this.chunks.push(e)};Inflate$1.prototype.onEnd=function(e){e===Z_OK&&(this.options.to==="string"?this.result=this.chunks.join(""):this.result=common.flattenChunks(this.chunks)),this.chunks=[],this.err=e,this.msg=this.strm.msg};const{Deflate,deflate,deflateRaw,gzip}=deflate_1$1;var deflate_1=deflate,fromByteArray_1=fromByteArray,lookup=[],code="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";for(var i=0,len=code.length;i<len;++i)lookup[i]=code[i];function tripletToBase64(e){return lookup[e>>18&63]+lookup[e>>12&63]+lookup[e>>6&63]+lookup[e&63]}function encodeChunk(e,t,n){for(var r,l=[],s=t;s<n;s+=3)r=(e[s]<<16&16711680)+(e[s+1]<<8&65280)+(e[s+2]&255),l.push(tripletToBase64(r));return l.join("")}function fromByteArray(e){for(var t,n=e.length,r=n%3,l=[],s=16383,c=0,o=n-r;c<o;c+=s)l.push(encodeChunk(e,c,c+s>o?o:c+s));return r===1?(t=e[n-1],l.push(lookup[t>>2]+lookup[t<<4&63]+"==")):r===2&&(t=(e[n-2]<<8)+e[n-1],l.push(lookup[t>>10]+lookup[t>>4&63]+lookup[t<<2&63]+"=")),l.join("")}const encoder=new TextEncoder;new TextDecoder;function serializeHash(e){const t=JSON.stringify(e),n=encoder.encode(t),r=deflate_1(n);return fromByteArray_1(r)}async function getViews(){if(!Authentication.token)throw new Error("Not authenticated");return(await(await fetch(`${FORMANT_API_URL}/v1/admin/views`,{method:"GET",headers:{"Content-Type":"application/json",Authorization:"Bearer "+Authentication.token}})).json()).items}async function createShareLink(e,t){if(!Authentication.token)throw new Error("Not authenticated");const r=(await getViews()).filter(o=>o.name===t);if(r.length===0)return console.warn("View does not exist or it is misspell"),null;const l=await fetch(`${FORMANT_API_URL}/v1/admin/shares`,{method:"POST",body:JSON.stringify(e),headers:{"Content-Type":"application/json",Authorization:"Bearer "+Authentication.token}}),s=FORMANT_API_URL.replace("api","app"),{code:c}=await l.json();return`${s}/shares/${c}#${serializeHash({viewId:r[0].id})}`}const vailableAggregationIntervals=["day","week","month","year","hour","minute","quarter"],aggregateFunctions=["interval","start","end","sub","get"];function getVariance(e){return e.count<2?0:e.sumOfSquares/(e.count-1)}function getStandardDeviation(e){return Math.sqrt(getVariance(e))}function getMax(e){return e.max}function getMin(e){return e.min}function getAverage(e){return e.count===0?-1:e.sum/e.count}function getSum(e){return e.sum}function getCount(e){return e.count}const aggregateFunctionMap={min:getMin,max:getMax,"standard deviation":getStandardDeviation,average:getAverage,sum:getSum,count:getCount},aggregateByDateFunctions={day:{interval:eachDayOfInterval,start:startOfDay,end:endOfDay,sub:subDays,get:getDay},week:{interval:eachWeekOfInterval,start:startOfWeek,end:endOfWeek,sub:subWeeks,get:getWeek},month:{interval:eachMonthOfInterval,start:startOfMonth,end:endOfMonth,sub:subMonths,get:getMonth},year:{interval:eachYearOfInterval,start:startOfYear,end:endOfYear,sub:subYears,get:getYear},hour:{interval:eachHourOfInterval,start:startOfHour,end:endOfHour,sub:subHours,get:getHours},minute:{interval:eachMinuteOfInterval,start:startOfMinute,end:endOfMinute,sub:subMinutes,get:getMinutes},quarter:{interval:eachQuarterOfInterval,start:startOfQuarter,end:endOfQuarter,sub:subQuarters,get:getQuarter}},formatTimeFrameText=(e,t)=>e.split("/")[0]+"/"+e.split("/")[1]+"–"+t.split("/")[0]+"/"+t.split("/")[1];async function queryEvents(e){if(!Authentication.token)throw new Error("Not authenticated");return(await(await fetch(`${FORMANT_API_URL}/v1/admin/events/query`,{method:"POST",body:JSON.stringify(e),headers:{"Content-Type":"application/json",Authorization:"Bearer "+Authentication.token}})).json()).items}async function eventsCounter(e,t,n,r,l){const s=aggregateByDateFunctions[t];return await Promise.all(Array(n).fill(0).map(async(c,o)=>{const d=new Date(r),u=s.sub(s.start(d),n-o-1),U=s.sub(s.end(d),n-o-1),B=formatTimeFrameText(u.toLocaleDateString(),U.toLocaleDateString()),R=await queryEvents({...l,eventTypes:e,start:new Date(u).toISOString(),end:new Date(U).toISOString()});return{date:B,events:R}}))}async function getAnnotationCount(e,t){return(await queryEvents({...e,eventTypes:["annotation"]})).filter(s=>!!s.tags&&Object.keys(s.tags).includes(t)).reduce((s,c)=>{const o=c.tags[t];return o in s?(s[o]+=1,s):(s[o]=1,s)},{})}async function getAnnotationCountByIntervals(e,t,n){const{end:r,start:l}=e,c=aggregateByDateFunctions[n].interval({start:new Date(l),end:new Date(r)}),o=c.map((u,U)=>{const B=new Date(u).toISOString(),R=U===c.length-1?new Date(Date.now()).toISOString():new Date(c[U+1]);return getAnnotationCount({...e,start:B,end:R},t)}),d=await Promise.all(o);return c.map((u,U)=>({date:new Date(u).toISOString(),annotations:d[U]}))}async function getTelemetry(e,t,n,r,l,s){let c=e;Array.isArray(e)||(c=[e]);let o=t;return Array.isArray(t)||(o=[t]),(await(await fetch(`${FORMANT_API_URL}/v1/queries/queries`,{method:"POST",body:JSON.stringify({deviceIds:c,end:r.toISOString(),names:o,start:n.toISOString(),tags:l,latestOnly:s}),headers:{"Content-Type":"application/json",Authorization:"Bearer "+Authentication.token}})).json()).items}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 getPeers(){if(!Authentication.token)throw new Error("Not authenticated");const e=defaultRtcClientPool.get();try{return await e.getPeers()}finally{await e.shutdown()}}async function createDevice(e){if(!Authentication.token)throw new Error("Not authenticated");return await(await fetch(`${FORMANT_API_URL}/v1/admin/devices`,{method:"POST",body:JSON.stringify(e),headers:{"Content-Type":"application/json",Authorization:"Bearer "+Authentication.token}})).json()}async function patchDevice(e,t){if(!Authentication.token)throw new Error("Not authenticated");return await(await fetch(`${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 getDevicesData(){if(!Authentication.token)throw new Error("Not authenticated");return(await(await fetch(`${FORMANT_API_URL}/v1/admin/device-details/query`,{method:"POST",body:JSON.stringify({enabled:!0,type:"default"}),headers:{"Content-Type":"application/json",Authorization:"Bearer "+Authentication.token}})).json()).items}async function queryDevicesData(e){if(!Authentication.token)throw new Error("Not authenticated");return(await(await fetch(`${FORMANT_API_URL}/v1/admin/devices/query`,{method:"POST",body:JSON.stringify(e),headers:{"Content-Type":"application/json",Authorization:"Bearer "+Authentication.token}})).json()).items}async function disableDevice(e){if(!Authentication.token)throw new Error("Not authenticated");return await(await fetch(`${FORMANT_API_URL}/v1/admin/devices/${e}/disable`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:"Bearer "+Authentication.token}})).json()}class Device extends BaseDevice{constructor(t,n,r,l){super(),this.id=t,this.name=n,this.organizationId=r,this.tags=l}async getLatestTelemetry(){return(await(await fetch(`${FORMANT_API_URL}/v1/queries/stream-current-value`,{method:"POST",body:JSON.stringify({deviceIds:[this.id]}),headers:{"Content-Type":"application/json",Authorization:"Bearer "+Authentication.token}})).json()).items}async getConfiguration(t=!1){let n=await fetch(`${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 l=t?r.desiredConfigurationVersion:r.state.reportedConfiguration.version;return n=await fetch(`${FORMANT_API_URL}/v1/admin/devices/${this.id}/configurations/${l}`,{method:"GET",headers:{"Content-Type":"application/json",Authorization:"Bearer "+Authentication.token}}),(await n.json()).document}async getAgentVersion(){var r;const n=await(await fetch(`${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(`${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:l=3}=typeof t=="number"?{sessionType:t}:t,c=getRtcClientPool({sessionType:n}).get(this.handleMessage);let o=!1;const d=new Promise((U,B)=>setTimeout(()=>{o=!0,B(new Error("Connection timed out: the connection could not be finalized in time, possibly due to network issues or misconfigured settings."))},r)),u=async()=>{if("isReady"in c)for(;!c.isReady();)this.assertNotCancelled(o),await delay(100);const U=await this.getRemoteDevicePeerId(c);this.assertNotCancelled(o);let B;for(let p=0;p<l&&(B=await c.connect(U),!B);p++)delay(100),this.assertNotCancelled(o);if(!B)throw new Error(`Session could not be created: exhausted ${l} retries`);let R=0;for(;!o&&c.getConnectionStatus(U)!=="connected";)await delay(100),R+=1;return this.assertNotCancelled(o),console.debug(`${new Date().toISOString()} :: Connection completed after ${R} retries`),U};return Promise.race([u(),d]).then(U=>{this.remoteDevicePeerId=U,this.initConnectionMonitoring(),this.rtcClient=c,this.emit("connect")}).catch(U=>{throw console.debug(`${new Date().toISOString()} :: Connection failed: %o`,U),this.remoteDevicePeerId=null,c.shutdown().catch(B=>{console.error("rtcClient cannot shutdown: %o",B)}),this.emit("connection_failed",U),U})}async getRemoteDevicePeerId(t){const r=(await t.getPeers()).find(l=>l.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(l=>l.getRemotePeerId()===this.remoteDevicePeerId&&l.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(l=>l.deviceId===this.id);return r?n[r.id].length>0:!1}async getAvailableCommands(){return(await(await fetch(`${FORMANT_API_URL}/v1/admin/command-templates/`,{method:"GET",headers:{"Content-Type":"application/json",Authorization:"Bearer "+Authentication.token}})).json()).items.map(r=>({name:r.name,id:r.id,command:r.command,description:r.description,parameterEnabled:r.parameterEnabled,parameterValue:r.parameterValue,parameterMeta:r.parameterMeta,enabled:r.enabled,tags:r.tags}))}async sendCommand(t,n,r,l){var U;const c=(await this.getAvailableCommands()).find(B=>B.name===t);if(!c)throw new Error(`Could not find command with name "${t}"`);let o="";n===void 0?c.parameterEnabled&&c.parameterValue&&(o=c.parameterValue):o=n;let d={value:o,scrubberTime:(r||new Date).toISOString(),meta:{...c.parameterMeta,...l}};return await fetch(`${FORMANT_API_URL}/v1/admin/commands`,{method:"POST",body:JSON.stringify({commandTemplateId:c.id,organizationId:this.organizationId,deviceId:this.id,command:c.command,parameter:d,userId:(U=Authentication.currentUser)==null?void 0:U.id}),headers:{"Content-Type":"application/json",Authorization:"Bearer "+Authentication.token}})}async getCommand(t){return await fetch(`${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(`${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,l,s,c,o){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,l,o)}async getTelemetryStreams(){var o,d;const t=await this.getConfiguration(),n=await fetch(`${FORMANT_API_URL}/v1/queries/metadata/stream-names`,{method:"POST",body:JSON.stringify({deviceIds:[this.id]}),headers:{"Content-Type":"application/json",Authorization:"Bearer "+Authentication.token}}),r=[],l=[];return(d=(o=t.telemetry)==null?void 0:o.streams)==null||d.forEach(u=>{u.disabled!==!0&&r.push(u.name),u.onDemand===!0&&l.push(u.name)}),console.log(l),(await n.json()).items.filter(u=>!r.includes(u)).map(u=>({name:u,onDemand:l.includes(u)}))}async createInterventionRequest(t,n,r,l){return await(await fetch(`${FORMANT_API_URL}/v1/admin/intervention-requests`,{method:"POST",body:JSON.stringify({message:t,interventionType:n,time:new Date().toISOString(),deviceId:this.id,tags:l,data:r}),headers:{"Content-Type":"application/json",Authorization:"Bearer "+Authentication.token}})).json()}async addInterventionResponse(t,n,r){return await(await fetch(`${FORMANT_API_URL}/v1/admin/intervention-responses`,{method:"POST",body:JSON.stringify({interventionId:t,interventionType:n,data:r}),headers:{"Content-Type":"application/json",Authorization:"Bearer "+Authentication.token}})).json()}async getAnnotationCount(t,n){return await 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,l,s){return await eventsCounter(t,n,r,l,{...s,deviceIds:[this.id]})}async createShareLink(t,n){return t.scope.deviceIds=[this.id],await createShareLink(t,n)}}Fe(Device,"createDevice",createDevice),Fe(Device,"patchDevice",patchDevice),Fe(Device,"getDevicesData",getDevicesData),Fe(Device,"queryDevicesData",queryDevicesData),Fe(Device,"disableDevice",disableDevice);class PeerDevice extends BaseDevice{constructor(n){super();Fe(this,"id");Fe(this,"telemetryStreamActive",!1);Fe(this,"streamTelemetry",{});this.peerUrl=n}async getLatestTelemetry(){this.telemetryStreamActive||this.subscribeToTelemetry();const n=this.streamTelemetry;return Object.entries(n).map(([l,s])=>({deviceId:this.id,streamName:l,streamType:"json",currentValue:s,currentValueTime:s.timestamp,tags:{}}))}async getTelemetry(n,r,l,s,c,o,d){if(Array.isArray(n))throw new Error("Multiple stream names not supported");if(s)throw new Error("Tags not supported");if(d&&c===void 0)c=1;else if(d&&c!==void 0)throw new Error("latestOnly and limit cannot be used together");let u=`${this.peerUrl}/v1/querydatapoints?stream_name=${n}&start=${r.toISOString()}&end=${l.toISOString()}`;return c!=null&&c>0&&(u+=`&limit=${c}`),o!=null&&o>=0&&(u+=`&offset=${o}`),(await(await fetch(u)).json()).results}subscribeToTelemetry(){this.telemetryStreamActive=!0;let n=0;const r=new XMLHttpRequest;r.responseType="text",r.addEventListener("error",l=>{this.handleXHRError("error")}),r.addEventListener("abort",l=>{this.handleXHRError("abort")}),r.addEventListener("timeout",l=>{this.handleXHRError("timeout")}),r.addEventListener("readystatechange",l=>{r.readyState===XMLHttpRequest.DONE&&this.handleXHRError("closed")}),r.addEventListener("progress",l=>{const s=l.loaded,c=s-n;n=s,r.responseText.substr(-c).split(`
62
+ `),Error.captureStackTrace(this,r)}}e.exports=l=>{if(l.length>2)throw new r(l);function s(o={}){this.options=o}function c(o){return new s(o)}return s.prototype.transform=l,c.Format=s,c}},function(e,t,n){function r(c,o){if(!(c instanceof o))throw new TypeError("Cannot call a class as a function")}function l(c,o){for(var d=0;d<o.length;d++){var u=o[d];u.enumerable=u.enumerable||!1,u.configurable=!0,"value"in u&&(u.writable=!0),Object.defineProperty(c,u.key,u)}}var s=n(88);e.exports=function(){function c(){var u=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};r(this,c),this.loggers=new Map,this.options=u}var o,d;return o=c,(d=[{key:"add",value:function(u,U){var B=this;if(!this.loggers.has(u)){var R=(U=Object.assign({},U||this.options)).transports||this.options.transports;U.transports=R?R.slice():[];var p=s(U);p.on("close",function(){return B._delete(u)}),this.loggers.set(u,p)}return this.loggers.get(u)}},{key:"get",value:function(u,U){return this.add(u,U)}},{key:"has",value:function(u){return!!this.loggers.has(u)}},{key:"close",value:function(u){var U=this;if(u)return this._removeLogger(u);this.loggers.forEach(function(B,R){return U._removeLogger(R)})}},{key:"_removeLogger",value:function(u){this.loggers.has(u)&&(this.loggers.get(u).close(),this._delete(u))}},{key:"_delete",value:function(u){this.loggers.delete(u)}}])&&l(o.prototype,d),Object.defineProperty(o,"prototype",{writable:!1}),c}()},function(e,t,n){(function(r){const l=n(51),s=/^([A-Za-z0-9+/]{4})*([A-Za-z0-9+/]{4}|[A-Za-z0-9+/]{3}=|[A-Za-z0-9+/]{2}==)$/;e.exports=function(c,o,d,u){let U,B,R=!1,p=!1;const g=n(94);function h(D){u(o,D)}function m(D,y){let b=`"${o}" ${y}`;throw D&&(b=`${b}`),B&&(b=`${b}. An example of a valid value would be: ${B}`),new l(b)}const N={convertFromBase64:function(){return h("marking for base64 conversion"),R=!0,N},default:function(D){if(typeof D=="number")U=D.toString();else if(Array.isArray(D)||typeof D=="object"&&D!==null)U=JSON.stringify(D);else{if(typeof D!="string")throw new l("values passed to default() must be of Number, String, Array, or Object type");U=D}return h(`setting default value to "${U}"`),N},required:function(D){return D===void 0?(h("marked as required"),p=!0):(h(`setting required flag to ${D}`),p=D),N},example:function(D){return B=D,N}};return Object.entries({...g,...d}).forEach(([D,y])=>{N[D]=function(b){return function(){let F=c[o];if(h(`will be read from the environment using "${b.name}" accessor`),F===void 0)if(U===void 0&&p)h("was not found in the environment, but is required to be set"),m(void 0,"is a required variable, but it was not set");else{if(U===void 0)return void h("was not found in the environment, but is not required. returning undefined");h(`was not found in the environment, parsing default value "${U}" instead`),F=U}p&&(h("verifying variable value is not an empty string"),F.trim().length===0&&m(void 0,"is a required variable, but its value was empty")),R&&(h("verifying variable is a valid base64 string"),F.match(s)||m(F,"should be a valid base64 string if using convertFromBase64"),h("converting from base64 to utf8 string"),F=r.from(F,"base64").toString());const v=[F].concat(Array.prototype.slice.call(arguments));try{h(`passing value "${F}" to "${b.name}" accessor`);const j=b.apply(b,v);return h(`parsed successfully, returning ${j}`),j}catch(j){m(F,j.message)}}}(y)}),N}}).call(this,n(5).Buffer)},function(e,t,n){const r=n(34);e.exports=function(l,s){return s=s||",",l.length?r(l).split(s).filter(Boolean):[]}},function(e,t,n){e.exports=function(r){const l=r.toLowerCase();if(l!=="false"&&l!=="true")throw new Error('should be either "true", "false", "TRUE", or "FALSE"');return l!=="false"}},function(e,t,n){e.exports=function(r){const l=r.toLowerCase();if(["false","0","true","1"].indexOf(l)===-1)throw new Error('should be either "true", "false", "TRUE", "FALSE", 1, or 0');return!(l==="0"||l==="false")}},function(e,t,n){const r=n(95);e.exports=function(l){var s=r(l);if(s>65535)throw new Error("cannot assign a port number greater than 65535");return s}},function(e,t,n){const r=n(34);e.exports=function(l,s){const c=r(l);if(s.indexOf(c)<0)throw new Error(`should be one of [${s.join(", ")}]`);return c}},function(e,t,n){const r=n(53);e.exports=function(l){const s=r(l);if(s>0)throw new Error("should be a negative float");return s}},function(e,t,n){const r=n(53);e.exports=function(l){const s=r(l);if(s<0)throw new Error("should be a positive float");return s}},function(e,t,n){const r=n(52);e.exports=function(l){const s=r(l);if(s>0)throw new Error("should be a negative integer");return s}},function(e,t,n){const r=n(54);e.exports=function(l){var s=r(l);if(!Array.isArray(s))throw new Error("should be a parseable JSON Array");return s}},function(e,t,n){const r=n(54);e.exports=function(l){var s=r(l);if(Array.isArray(s))throw new Error("should be a parseable JSON Object");return s}},function(e,t,n){e.exports=function(r,l){try{RegExp(void 0,l)}catch{throw new Error("invalid regexp flags")}try{return new RegExp(r,l)}catch{throw new Error("should be a valid regexp")}}},function(e,t,n){const r=n(96);e.exports=function(l){return r(l).toString()}},function(e,t,n){const r=n(34),l=/^(?:[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*|"(?:[\u0001-\u0008\u000b\u000c\u000e-\u001f\u0021\u0023-\u005b\u005d-\u007f]|\\[\u0001-\u0009\u000b\u000c\u000e-\u007f])*")@(?:(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?|\[(?:(?:(2(5[0-5]|[0-4][0-9])|1[0-9][0-9]|[1-9]?[0-9]))\.){3}(?:(2(5[0-5]|[0-4][0-9])|1[0-9][0-9]|[1-9]?[0-9])|[a-z0-9-]*[a-z0-9]:(?:[\u0001-\u0008\u000b\u000c\u000e-\u001f\u0021-\u005a\u0053-\u007f]|\\[\u0001-\u0009\u000b\u000c\u000e-\u007f])+)\])$/;e.exports=function(s){const c=r(s);if(!l.test(c))throw new Error("should be a valid email address");return c}},function(e,t,n){e.exports=function(r,l){return function(s,c){l&&l.match(/prod|production/)||r(`env-var (${s}): ${c}`)}}},function(e,t,n){(function(r){(function(){var l,s,c,o,d,u;typeof performance!="undefined"&&performance!==null&&performance.now?e.exports=function(){return performance.now()}:r!=null&&r.hrtime?(e.exports=function(){return(l()-d)/1e6},s=r.hrtime,o=(l=function(){var U;return 1e9*(U=s())[0]+U[1]})(),u=1e9*r.uptime(),d=o-u):Date.now?(e.exports=function(){return Date.now()-c},c=Date.now()):(e.exports=function(){return new Date().getTime()-c},c=new Date().getTime())}).call(this)}).call(this,n(2))},function(e,t,n){(function(r){(function(l){function s(o){if((o=o===void 0?"utf-8":o)!=="utf-8")throw new RangeError("Failed to construct 'TextEncoder': The encoding label provided ('"+o+"') is invalid.")}function c(o,d){if(d=d===void 0?{fatal:!1}:d,(o=o===void 0?"utf-8":o)!=="utf-8")throw new RangeError("Failed to construct 'TextDecoder': The encoding label provided ('"+o+"') is invalid.");if(d.fatal)throw Error("Failed to construct 'TextDecoder': the 'fatal' option is unsupported.")}if(l.TextEncoder&&l.TextDecoder)return!1;Object.defineProperty(s.prototype,"encoding",{value:"utf-8"}),s.prototype.encode=function(o,d){if((d=d===void 0?{stream:!1}:d).stream)throw Error("Failed to encode: the 'stream' option is unsupported.");d=0;for(var u=o.length,U=0,B=Math.max(32,u+(u>>1)+7),R=new Uint8Array(B>>3<<3);d<u;){var p=o.charCodeAt(d++);if(55296<=p&&56319>=p){if(d<u){var g=o.charCodeAt(d);(64512&g)==56320&&(++d,p=((1023&p)<<10)+(1023&g)+65536)}if(55296<=p&&56319>=p)continue}if(U+4>R.length&&(B+=8,B=(B*=1+d/o.length*2)>>3<<3,(g=new Uint8Array(B)).set(R),R=g),(4294967168&p)==0)R[U++]=p;else{if(!(4294965248&p))R[U++]=p>>6&31|192;else if(!(4294901760&p))R[U++]=p>>12&15|224,R[U++]=p>>6&63|128;else{if(4292870144&p)continue;R[U++]=p>>18&7|240,R[U++]=p>>12&63|128,R[U++]=p>>6&63|128}R[U++]=63&p|128}}return R.slice(0,U)},Object.defineProperty(c.prototype,"encoding",{value:"utf-8"}),Object.defineProperty(c.prototype,"fatal",{value:!1}),Object.defineProperty(c.prototype,"ignoreBOM",{value:!1}),c.prototype.decode=function(o,d){if((d=d===void 0?{stream:!1}:d).stream)throw Error("Failed to decode: the 'stream' option is unsupported.");d=0;for(var u=(o=new Uint8Array(o)).length,U=[];d<u;){var B=o[d++];if(B===0)break;if(!(128&B))U.push(B);else if((224&B)==192){var R=63&o[d++];U.push((31&B)<<6|R)}else if((240&B)==224){R=63&o[d++];var p=63&o[d++];U.push((31&B)<<12|R<<6|p)}else(248&B)==240&&(65535<(B=(7&B)<<18|(R=63&o[d++])<<12|(p=63&o[d++])<<6|63&o[d++])&&(B-=65536,U.push(B>>>10&1023|55296),B=56320|1023&B),U.push(B))}return String.fromCharCode.apply(null,U)},l.TextEncoder=s,l.TextDecoder=c})(typeof window!="undefined"?window:r!==void 0?r:this)}).call(this,n(6))},function(e,t,n){n.r(t),n.d(t,"AuthClient",function(){return s}),n.d(t,"RtcSignalingClient",function(){return o}),n.d(t,"Credentials",function(){return I}),n.d(t,"SignalingPromiseClient",function(){return W.SignalingPromiseClient}),n.d(t,"RtcClient",function(){return At}),n.d(t,"RtcClientV1",function(){return Nt}),n.d(t,"createRtcStreamMessage",function(){return et});var r=n(26),l=function(Re,A,x,q){return new(x||(x=Promise))(function(oe,se){function de(Ue){try{pe(q.next(Ue))}catch(le){se(le)}}function he(Ue){try{pe(q.throw(Ue))}catch(le){se(le)}}function pe(Ue){var le;Ue.done?oe(Ue.value):(le=Ue.value,le instanceof x?le:new x(function(me){me(le)})).then(de,he)}pe((q=q.apply(Re,A||[])).next())})};class s extends r.a{adminSignup(A,x){return l(this,void 0,void 0,function*(){return yield this.fetch("auth/admin-signup",{token:x,method:"POST",body:A})})}login(A){return l(this,void 0,void 0,function*(){return yield this.fetch("auth/login",{method:"POST",body:A,allowUnsafeRetries:!0})})}loginWithGoogleToken(A){return l(this,void 0,void 0,function*(){return yield this.fetch("auth/login-google",{method:"POST",body:A,allowUnsafeRetries:!0})})}refresh(A,x){return l(this,void 0,void 0,function*(){return yield this.fetch("auth/refresh",{method:"POST",body:{refreshToken:A,tokenExpirationSeconds:x},allowUnsafeRetries:!0})})}respondToNewPasswordRequiredChallenge(A){return l(this,void 0,void 0,function*(){return yield this.fetch("auth/respond-to-new-password-required-challenge",{method:"POST",body:A})})}forgotPassword(A){return l(this,void 0,void 0,function*(){return yield this.fetch("auth/forgot-password",{method:"POST",body:{email:A}})})}confirmForgotPassword(A){return l(this,void 0,void 0,function*(){return yield this.fetch("auth/confirm-forgot-password",{method:"POST",body:A})})}resendInvitation(A){return l(this,void 0,void 0,function*(){return yield this.fetch("auth/resend-invitation",{method:"POST",body:{email:A}})})}changePassword({token:A,refreshToken:x,currentPassword:q,newPassword:oe}){return l(this,void 0,void 0,function*(){return yield this.fetch("auth/change-password",{token:A,method:"POST",body:{refreshToken:x,currentPassword:q,newPassword:oe}})})}getDeviceCredentials(A){return l(this,void 0,void 0,function*(){return yield this.fetch("auth/device-credentials",{token:A,method:"POST",allowUnsafeRetries:!0})})}impersonate(A,x){return l(this,void 0,void 0,function*(){return yield this.fetch("auth/impersonate",{token:A,method:"POST",allowUnsafeRetries:!0,body:{userId:x}})})}createServiceAccount(A,x,q,oe){return l(this,void 0,void 0,function*(){return yield this.fetch("auth/service-account",{token:A,method:"POST",allowUnsafeRetries:!0,body:{name:x,roleId:q,tags:oe}})})}getFeatures(A){return l(this,void 0,void 0,function*(){return(yield this.fetch("auth/features",{token:A})).features})}}var c=function(Re,A,x,q){return new(x||(x=Promise))(function(oe,se){function de(Ue){try{pe(q.next(Ue))}catch(le){se(le)}}function he(Ue){try{pe(q.throw(Ue))}catch(le){se(le)}}function pe(Ue){var le;Ue.done?oe(Ue.value):(le=Ue.value,le instanceof x?le:new x(function(me){me(le)})).then(de,he)}pe((q=q.apply(Re,A||[])).next())})};class o extends r.a{createPeer(A,x){return c(this,void 0,void 0,function*(){return yield this.fetch("peers",{token:A,method:"POST",body:x})})}getPeers(A){return c(this,void 0,void 0,function*(){return(yield this.fetch("peers",{token:A})).items})}refreshPeer(A,x){return c(this,void 0,void 0,function*(){yield this.fetch(`peers/${x}/refresh`,{token:A,method:"POST",allowUnsafeRetries:!0})})}createSession(A,x){return c(this,void 0,void 0,function*(){return yield this.fetch("sessions",{token:A,method:"POST",body:x})})}refreshSession(A,x){return c(this,void 0,void 0,function*(){yield this.fetch(`sessions/${x}/refresh`,{token:A,method:"POST",allowUnsafeRetries:!0})})}deleteSession(A,x){return c(this,void 0,void 0,function*(){yield this.fetch(`sessions/${x}`,{token:A,method:"DELETE",allowUnsafeRetries:!0})})}getSessions(A){return c(this,void 0,void 0,function*(){return(yield this.fetch("sessions",{token:A})).items})}getIceServers(A){return c(this,void 0,void 0,function*(){return(yield this.fetch("ice-servers",{token:A})).items})}addSignals(A,x,q){return c(this,void 0,void 0,function*(){yield this.fetch(`sessions/${x}/add-signals`,{token:A,method:"POST",body:q})})}takeSignals(A,x){return c(this,void 0,void 0,function*(){return(yield this.fetch(`sessions/${x}/take-signals`,{token:A,method:"POST"})).items})}}var d=n(1),u=n(9),U=n(15),B=n.n(U),R=n(102),p=n.n(R),g=n(4),h=n(0),m=function(Re,A,x,q){return new(x||(x=Promise))(function(oe,se){function de(Ue){try{pe(q.next(Ue))}catch(le){se(le)}}function he(Ue){try{pe(q.throw(Ue))}catch(le){se(le)}}function pe(Ue){var le;Ue.done?oe(Ue.value):(le=Ue.value,le instanceof x?le:new x(function(me){me(le)})).then(de,he)}pe((q=q.apply(Re,A||[])).next())})};class N extends class{constructor(A,x){this.type=A,this.name=x}}{constructor(A){super("simple","LogReporter"),this.message=A}send(A){return m(this,void 0,void 0,function*(){var x,q;h.a.debug(this.message,(x=A.reduce((oe,se)=>Object.assign(Object.assign({},oe),{[se.name]:se.stat}),{}),q=oe=>{const{sum:se,count:de}=oe,he=se/de;return Object.assign(Object.assign({},oe),{average:he})},Object.keys(x).reduce((oe,se)=>Object.assign(Object.assign({},oe),{[se]:q(x[se])}),{})))})}}var D=n(40);function y(Re){return!!Re.match(/^[a-zA-Z0-9-_.,:?'"()@\/\\#$+ ]{1,255}$/)}var b=function(Re,A,x,q){return new(x||(x=Promise))(function(oe,se){function de(Ue){try{pe(q.next(Ue))}catch(le){se(le)}}function he(Ue){try{pe(q.throw(Ue))}catch(le){se(le)}}function pe(Ue){var le;Ue.done?oe(Ue.value):(le=Ue.value,le instanceof x?le:new x(function(me){me(le)})).then(de,he)}pe((q=q.apply(Re,A||[])).next())})};function F({func:Re,delay:A,immediate:x=!1}){let q=!1,oe=setTimeout(function de(){return b(this,void 0,void 0,function*(){if(q)return;const he=new Date().getTime();try{se=Re(),yield se}finally{if(!q){const pe=new Date().getTime();oe=setTimeout(de,Math.max(A-(pe-he),0))}}})},x?0:A),se=Promise.resolve();return{stop(){return b(this,void 0,void 0,function*(){q=!0,clearTimeout(oe),yield se})}}}var v=function(Re,A,x,q){return new(x||(x=Promise))(function(oe,se){function de(Ue){try{pe(q.next(Ue))}catch(le){se(le)}}function he(Ue){try{pe(q.throw(Ue))}catch(le){se(le)}}function pe(Ue){var le;Ue.done?oe(Ue.value):(le=Ue.value,le instanceof x?le:new x(function(me){me(le)})).then(de,he)}pe((q=q.apply(Re,A||[])).next())})};const j=n(230);class K{constructor(A){this.buffer={},this.reporters=[],this.flushInterval=F({func:()=>this.flushStats(),delay:K.samplePeriodMs}),this.tags=this.filterTags((A==null?void 0:A.tags)||{app:g.a,version:g.j,namespace:g.i,instanceId:D.a})}shutdown(){return v(this,void 0,void 0,function*(){yield this.flushInterval.stop(),yield this.flushStats(),yield Object(u.a)(2*d.a.second)})}aggregate(A,x,q){this.addToBuffer(this.buffer,this.encodeKey({metric:A,tags:this.filterTags(q||{})}),typeof x=="number"?{min:x,max:x,sum:x,count:1}:x)}increment(A,x){this.aggregate(A,1,x)}timer(A,x,q){return v(this,void 0,void 0,function*(){const oe=j(),se=yield x(),de=j();return this.aggregate(A,de-oe,q),se})}registerStatsReporter(A){this.reporters.push(A)}setTag(A,x){const q=this.filterTags({[A]:x});this.tags=Object.assign(Object.assign({},this.tags),q)}addToBuffer(A,x,q){if(A[x]){const{min:oe,max:se,sum:de,count:he}=A[x];A[x]={min:Math.min(oe,q.min),max:Math.max(se,q.max),sum:de+q.sum,count:he+q.count}}else A[x]=q}write(A){return v(this,void 0,void 0,function*(){yield Promise.all(this.reporters.map(x=>v(this,void 0,void 0,function*(){let q;const oe={};switch(x.type){case"simple":for(const[de,he]of Object.entries(A)){const{metric:pe}=this.decodeKey(de);this.addToBuffer(oe,this.encodeKey({metric:pe}),he)}q=oe;break;case"tagged":q=A;break;default:(function(de){throw new Error(`Unreachable type encountered (${de})`)})(x.type)}const se=Object.entries(q);if(se.length>0)return x.send(se.map(([de,he])=>{const{metric:pe,tags:Ue}=this.decodeKey(de);return{name:pe,tags:Object.assign(Object.assign({},Ue),this.tags),stat:he}}),K.samplePeriodMs).catch(de=>{h.a.debug(`Failed to write stats to ${x.name}`,{error:de})})})))})}flushStats(){return v(this,void 0,void 0,function*(){yield this.write(this.buffer),this.buffer={}})}encodeKey(A){return B()(Object.assign(Object.assign({},A),Object.keys(A.tags||{}).length>0?{tags:A.tags}:{}))}decodeKey(A){return JSON.parse(A)}filterTags(A){return Object.entries(A||{}).reduce((x,[q,oe])=>(y(q)&&y(oe)&&(x[q]=oe),x),{})}}K.samplePeriodMs=5*d.a.minute;const f=!!g.c,Q=new K;f||["local","on-prem"].includes(g.i)||Q.registerStatsReporter(new N("stats"));var P=function(Re,A,x,q){return new(x||(x=Promise))(function(oe,se){function de(Ue){try{pe(q.next(Ue))}catch(le){se(le)}}function he(Ue){try{pe(q.throw(Ue))}catch(le){se(le)}}function pe(Ue){var le;Ue.done?oe(Ue.value):(le=Ue.value,le instanceof x?le:new x(function(me){me(le)})).then(de,he)}pe((q=q.apply(Re,A||[])).next())})};class w extends class{constructor(A){this.options=A,this.cache=new p.a(Object.assign(Object.assign(Object.assign({},A.dispose||A.disposeAfter?{ttlAutopurge:!0}:{}),A),{dispose:(...x)=>{var q;x[2]==="evict"&&Q.increment("lru-eviction",{name:A.name}),(q=A.dispose)===null||q===void 0||q.call(A,...x)},disposeAfter:(...x)=>{var q;this.updateStats(),(q=A.disposeAfter)===null||q===void 0||q.call(A,...x)}})),this.stringify=A.fastStringify?JSON.stringify:B.a}set(A,x,q){const oe=this.stringify(A);if(!this.cache.set(oe,x,{ttl:q})){const se=this.cache.sizeCalculation?this.cache.sizeCalculation(x,oe):"unknown";throw Error(`Value too large (${se} > ${this.cache.max})`)}this.updateStats()}get(A){const{name:x}=this.options,q=this.stringify(A),oe=this.cache.getRemainingTTL(q);return oe<=0?Q.increment("cache-miss",{name:x}):oe!==1/0&&Q.aggregate("cache-item-ttl",oe,{name:x}),this.cache.get(q)}delete(A){this.cache.delete(this.stringify(A))}peek(A){return this.cache.peek(this.stringify(A))}size(){return this.cache.size}clear(){this.cache.clear()}forEach(A){this.cache.forEach(A)}purgeStale(){return this.cache.purgeStale()}updateStats(){const{name:A}=this.options;Q.aggregate("cache-item-count",this.cache.size,{name:A}),this.cache.calculatedSize!==void 0&&Q.aggregate("cache-length",this.cache.calculatedSize,{name:A})}}{constructor(A){if(super(A),this.expireRejectedPromiseValues=A.expireRejectedPromiseValues===void 0||A.expireRejectedPromiseValues,this.rejectedPromiseValueTtl=A.rejectedPromiseValueTtl!==void 0?A.rejectedPromiseValueTtl:d.a.second,this.rejectedPromiseValueTtl<0)throw new Error("rejectedPromiseValueTtl must not be negative")}set(A,x,q){super.set(A,x,q),this.expireRejectedPromiseValues&&x.catch(()=>P(this,void 0,void 0,function*(){yield Object(u.a)(this.rejectedPromiseValueTtl),this.peek(A)===x&&this.delete(A)}))}}var V=function(Re,A,x,q){return new(x||(x=Promise))(function(oe,se){function de(Ue){try{pe(q.next(Ue))}catch(le){se(le)}}function he(Ue){try{pe(q.throw(Ue))}catch(le){se(le)}}function pe(Ue){var le;Ue.done?oe(Ue.value):(le=Ue.value,le instanceof x?le:new x(function(me){me(le)})).then(de,he)}pe((q=q.apply(Re,A||[])).next())})};class I{constructor(A,x,q){this.authClient=A,this.email=x,this.password=q,this.tokenTtlMs=1*d.a.hour,this.tokenCache=new w({name:"Credentials-tokenCache",max:100,ttl:this.tokenTtlMs-5*d.a.minute,fastStringify:!0})}getToken(){return V(this,void 0,void 0,function*(){let A=this.tokenCache.get(this.email);return A||(A=(()=>V(this,void 0,void 0,function*(){const{authentication:x}=yield this.authClient.login({email:this.email,password:this.password,tokenExpirationSeconds:this.tokenTtlMs/d.a.second});if(!x)throw new Error("User account not verified.");return x.accessToken}))(),this.tokenCache.set(this.email,A)),A})}}var W=n(97),k=n(17),T=n(233),Z=n(41),O=function(Re,A,x,q){return new(x||(x=Promise))(function(oe,se){function de(Ue){try{pe(q.next(Ue))}catch(le){se(le)}}function he(Ue){try{pe(q.throw(Ue))}catch(le){se(le)}}function pe(Ue){var le;Ue.done?oe(Ue.value):(le=Ue.value,le instanceof x?le:new x(function(me){me(le)})).then(de,he)}pe((q=q.apply(Re,A||[])).next())})};class E extends Z.a{constructor(A){super(A)}postLanRtcOffer(A){return O(this,void 0,void 0,function*(){return yield this.fetch("v1/lan-rtc-offer",{method:"POST",body:A})})}}var L=function(Re,A,x,q){return new(x||(x=Promise))(function(oe,se){function de(Ue){try{pe(q.next(Ue))}catch(le){se(le)}}function he(Ue){try{pe(q.throw(Ue))}catch(le){se(le)}}function pe(Ue){var le;Ue.done?oe(Ue.value):(le=Ue.value,le instanceof x?le:new x(function(me){me(le)})).then(de,he)}pe((q=q.apply(Re,A||[])).next())})};function G(Re){return L(this,void 0,void 0,function*(){return(yield Promise.all(Re.map(A=>A.catch(x=>x)))).filter(A=>A instanceof Error)})}function $(Re,A){if(Re===void 0)throw new Error(`Value is undefined${A?`: ${A}`:""}`)}function ee(Re,A){if(Re===null)throw new Error(`Value is null${A?`: ${A}`:""}`)}function te(Re){return $(Re),Re}function M(Re,A){const x=Re.reduce((q,oe)=>[...q,...oe.urls],[]).filter(q=>C(q,A)).sort(q=>S(q,"udp")?-1:0).shift();if(x)return Object.assign(Object.assign({},te(Re.find(q=>q.urls.includes(x)))),{urls:[x]})}function C(Re,A){switch(A){case"stun":return/^stuns?:/.test(Re);case"turn":return/^turns?:/.test(Re)}}function S(Re,A){return Re.endsWith(`transport=${A}`)}var _=n(10);class z extends Error{constructor(A,x){super(`Deadline expired after ${A}ms + ${x}ms`)}}class X{static withDeadline(A,x){const q=new Promise((oe,se)=>{setTimeout(()=>{se(new z(x,this.grpcCallDeadlineSlopMs))},x+this.grpcCallDeadlineSlopMs)});return Promise.race([A,q])}}X.grpcCallDeadlineSlopMs=500*d.a.millisecond;var H=n(27);const ne={ordered:!1,maxPacketLifeTime:300*d.a.millisecond},ie={ordered:!0},ce={ordered:!0},Se={ordered:!1,maxRetransmits:0},Te={ordered:!1,maxRetransmits:0},ye=Re=>"received"in Re&&Re.received!==void 0,we=Re=>!("received"in Re)||Re.received===void 0,be=2*d.a.second;function Ee(Re,A={}){const x=Array.from(Re.values()),q=x.filter(ye),oe=q.length>0,se=Math.max(...q.map(Ue=>Ue.received));let de;if(oe){const Ue=x.length,le=q.length,me=q.map(Ze=>Ze.received-Ze.sent),{standardDeviation:Je,mean:We,jitter:je}=function(Ze){const Me=Ze.length;if(Me===0)return{mean:NaN,standardDeviation:-1,jitter:NaN};const ze=Ze.reduce((Ke,st)=>Ke+st,0)/Me,Ye=Math.sqrt(Ze.map(Ke=>Math.pow(Ke-ze,2)).reduce((Ke,st)=>Ke+st)/Me);if(Me===1)return{mean:ze,standardDeviation:Ye,jitter:NaN};let Xe=0;for(let Ke=1;Ke<Me;Ke++)Xe+=Math.abs(Ze[Ke]-Ze[Ke-1]);return{mean:ze,standardDeviation:Ye,jitter:Xe/(Me-1)}}(me),Pe=x.filter(Ze=>Ze.sent<se-be),He=Pe.filter(we),qe=He.length===0?0:He.length/Pe.length;de={pingsSent:Ue,pongsReceived:le,average:We,standardDeviation:Je,jitter:je,max:Math.max(...me),min:Math.min(...me),loss:qe}}else de=null;const{temporalNow:he=Date.now()}=A,pe=(oe?se:he)-4*be;return Array.from(Re.entries()).forEach(Ue=>{const[le,me]=Ue;me.sent<pe&&Re.delete(le)}),de}function _e({entityId:Re,streamName:A,streamType:x}){return`${Re}.${A}.${x}`}var Ae=function(Re,A,x,q){return new(x||(x=Promise))(function(oe,se){function de(Ue){try{pe(q.next(Ue))}catch(le){se(le)}}function he(Ue){try{pe(q.throw(Ue))}catch(le){se(le)}}function pe(Ue){var le;Ue.done?oe(Ue.value):(le=Ue.value,le instanceof x?le:new x(function(me){me(le)})).then(de,he)}pe((q=q.apply(Re,A||[])).next())})};class Le{constructor(A,x){this.counts={localSent:new Map,localReceived:new Map,remoteSent:new Map,remoteReceived:new Map},this.sessionId=A,this.connection=x}updateRemoteMessagesCounts(A){if(A.payload.streamsInfo){this.counts.remoteSent=new Map,this.counts.remoteReceived=new Map;for(const x of A.payload.streamsInfo.items)this.counts.remoteSent.set(x.streamId,x.sentCount),this.counts.remoteReceived.set(x.streamId,x.receivedCount)}}getLocalStreamsInfo(A){const{localSent:x,localReceived:q}=this.counts;return{items:[...new Set([...x.keys(),...q.keys()])].map(oe=>{var se,de;return{streamId:oe,sentCount:(se=x.get(oe))!==null&&se!==void 0?se:0,receivedCount:(de=q.get(oe))!==null&&de!==void 0?de:0}}),timestamp:A}}incrementLocalSent(A){const{localSent:x}=this.counts,q=_e(A.header.stream);x.set(q,(x.get(q)||0)+1)}incrementLocalReceived(A){const{localReceived:x}=this.counts,q=_e(A.header.stream),oe=x.get(q)||0;if(oe===0){const{streamName:se,streamType:de}=A.header.stream;h.a.debug("RTC client received first message for stream",{streamName:se,streamType:de})}x.set(q,oe+1)}uploadMetrics(){return Ae(this,void 0,void 0,function*(){const{sessionId:A}=this,x=yield this.connection.peerConnection.getStats(),q={};x.forEach(Ue=>q[Ue.id]=Ue),h.a.debug("rtc-stats",Object.assign(Object.assign({},q),{sessionId:A}));const{localSent:oe,localReceived:se,remoteSent:de,remoteReceived:he}=this.counts,pe=[...new Set([...oe.keys(),...se.keys()])].reduce((Ue,le)=>{const me=oe.get(le),Je=se.get(le),We=de.get(le),je=he.get(le);return Object.assign(Object.assign({},Ue),{[`local-${le}-sent`]:me,[`local-${le}-received`]:Je,[`remote-${le}-sent`]:We,[`remote-${le}-received`]:je})},{sessionId:A});h.a.debug("rtc-message-report",Object.assign({deviceId:this.connection.getRemoteDeviceId()},pe))})}}function et(Re,A,x){return{header:{stream:Re,created:Date.now(),frameId:x||""},payload:A}}function Qt(Re){const A=Re.localCandidate.candidateType,x=Re.remoteCandidate.candidateType;return A==="host"&&x==="host"?"local":A==="relay"||x==="relay"?"TURN":"STUN"}function Rt(Re){return new Set(["disconnected","failed","closed"]).has(Re.iceConnectionState)}function Et(Re){switch(Re.header.stream.streamType){case"twist":{const{twist:A}=Re.payload;if(!A)throw Error("twist not in payload of RTC message with type twist");return{header:Re.header,payload:{twist:{linear:Object.assign({x:0,y:0,z:0},A.linear),angular:Object.assign({x:0,y:0,z:0},A.angular)}}}}case"pose":{const{pose:A}=Re.payload;if(!A)throw Error("pose not in payload of RTC message with type pose");return{header:Re.header,payload:{pose:{translation:Object.assign({x:0,y:0,z:0},A.translation),rotation:Object.assign({x:0,y:0,z:0,w:0},A.rotation)}}}}case"pose-with-covariance":{const{poseWithCovariance:A}=Re.payload;if(!A)throw Error("poseWithCovariance not in payload of RTC message with type pose-with-covariance");const x=new Array(36).fill(0);return A.covariance.forEach((q,oe)=>{if(oe>=36)throw Error("covariance contains more than 36 elements");x[oe]=q}),{header:Re.header,payload:{poseWithCovariance:{pose:{translation:Object.assign({x:0,y:0,z:0},A.pose.translation),rotation:Object.assign({x:0,y:0,z:0,w:0},A.pose.rotation)},covariance:x}}}}case"point":{const{point:A}=Re.payload;if(!A)throw Error("point not in payload of RTC message with type point");return{header:Re.header,payload:{point:Object.assign({x:0,y:0,z:0},A)}}}default:return Re}}var ot=function(Re,A,x,q){return new(x||(x=Promise))(function(oe,se){function de(Ue){try{pe(q.next(Ue))}catch(le){se(le)}}function he(Ue){try{pe(q.throw(Ue))}catch(le){se(le)}}function pe(Ue){var le;Ue.done?oe(Ue.value):(le=Ue.value,le instanceof x?le:new x(function(me){me(le)})).then(de,he)}pe((q=q.apply(Re,A||[])).next())})};class gt{get peerConnection(){return ee(this._peerConnection,"RTCPeerConnection is closed!"),this._peerConnection}constructor(A,x,q,oe){this.iceServers=x,this.config=q,this.dataChannelNotifier=oe,this.connectTimeoutMs=20*d.a.second,this.iceGatheringTimeoutMs=3*d.a.second,this.pingUpdateTimeoutMs=1*d.a.second,this.pingV2UpdateTimeoutMs=250*d.a.millisecond,this.pingV2MetricsGatherTimeoutMs=1*d.a.second,this.streamsInfoUpdateTimeoutMs=2*d.a.second,this.reassemblyTimeoutMs=500*d.a.millisecond,this.reassemblyTableCleanupMs=1*d.a.second,this.heartbeatTimeoutMs=20*d.a.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.closeCalled=!1,this.gotOffer=!1,this.hasIceCandidate=!1,this.pingV2Map=new Map,this.sendPingV2=()=>{const{latestTryOnceStreamChannel:de}=this;if(!de)return;const he=new Date().getTime(),pe=Object(T.a)();this.sendSystemMessage(de,{type:"ping-v2",payload:{timestamp:he,id:pe}}),this.pingV2Map.set(pe,{sent:he})},this.gatherPingV2Metrics=()=>{const de=Ee(this.pingV2Map);if(de){const he=this.getRemoteDeviceId();this.pingInfo=de,Q.aggregate("rtc-ping-average",de.average,Object.assign({},he?{deviceId:he}:{})),Q.aggregate("rtc-ping-loss",de.loss,Object.assign({},he?{deviceId:he}:{})),Q.aggregate("rtc-jitter",de.jitter,Object.assign({},he?{deviceId:he}:{}))}},this._peerConnection=A;const{isOffer:se}=q.baseConfig;se?this.initializeChannels(A):A.ondatachannel=de=>{switch(de.channel.label){case"stream.latest-ttl":this.latestTtlStreamChannel=de.channel;break;case"stream.reliable":this.reliableStreamChannel=de.channel;break;case"stream.latest-reliable":this.latestReliableStreamChannel=de.channel;break;case"stream.latest-try-once":this.latestTryOnceStreamChannel=de.channel;break;case"heartbeat":return void(this.heartbeatChannel=de.channel);default:return void this.dataChannelNotifier(de.channel)}this.setupChannel(de.channel)},this.pingUpdateTimeout=setInterval(()=>{const{reliableStreamChannel:de}=this;de&&this.sendSystemMessage(de,{type:"ping"})},this.pingUpdateTimeoutMs),this.pingV2UpdateTimeout=setInterval(this.sendPingV2,this.pingV2UpdateTimeoutMs),this.pingV2MetricsGatherTimeout=setInterval(this.gatherPingV2Metrics,this.pingV2MetricsGatherTimeoutMs),this.streamsInfoUpdateTimeout=setInterval(()=>{const{latestTtlStreamChannel:de}=this;de&&this.sendSystemMessage(de,{type:"streams-info"})},this.streamsInfoUpdateTimeoutMs),this.reassemblyTableCleanupTimeout=setInterval(()=>{const de=new Date().getTime();this.reassemblyTableLastTimestamp.forEach((he,pe,Ue)=>{de>pe+this.reassemblyTimeoutMs&&this.reassemblyTable.delete(he)})},this.reassemblyTableCleanupMs),this.heartbeatTimeout=setInterval(()=>{const{heartbeatChannel:de}=this;de&&de.readyState==="open"&&de.send(new Uint8Array([1]))},this.heartbeatTimeoutMs)}handleSignal(A){return ot(this,void 0,void 0,function*(){const{peerConnection:x}=this,{track:q}=this.config.baseConfig,oe=(()=>{try{return JSON.parse(A.getPayload())}catch{return}})();if(!oe)return void h.a.error("Received unparseable signal.");h.a.debug("Handling signal",{description:oe});const{sdp:se,type:de}=oe;if(!se||!de)return void h.a.warn("Received non-SDP signal");const{signalingState:he,connectionState:pe}=x;if(he!=="stable"||pe!=="connected")if(x.remoteDescription)h.a.warn(`Received SDP after remote description was set: ${se}`);else{if(de==="offer"){if(he!=="stable")return void h.a.warn("Received offer SDP when signaling is ongoing.");yield x.setRemoteDescription(oe);const Ue=yield x.createAnswer();yield x.setLocalDescription(Ue);const le=A.clone();return q==null||q("Answer Received",le),le.setPayload(JSON.stringify(Ue)),le.setReceiverId(A.getSenderId()),le.setSenderId(A.getReceiverId()),le}if(de==="answer"){if(he==="stable")return void h.a.warn("Received answer SDP when signaling hasn't started.");yield x.setRemoteDescription(oe)}}else h.a.warn(`Received SDP when already connected: ${se}`)})}send(A,x){const q=this.getChannelFromLabel(x.channelLabel);q?this.sendOnChannel(q,A):h.a.warn("Send called with unexpected channel label",{channelLabel:x.channelLabel})}controlRemoteStream(A){var x;this.sendSystemMessage((ee(x=this.reliableStreamChannel),x),{type:"stream-control",streamControl:A})}isActive(){return new Set(["new","checking","connected","completed"]).has(this.peerConnection.iceConnectionState)||this.isReady()}isReady(){const{reliableStreamChannel:A,latestTtlStreamChannel:x,latestTryOnceStreamChannel:q,latestReliableStreamChannel:oe}=this;return(A==null?void 0:A.readyState)==="open"&&(x==null?void 0:x.readyState)==="open"&&(q==null?void 0:q.readyState)==="open"&&(oe==null?void 0:oe.readyState)==="open"}close(){var A,x,q,oe,se,de,he;return ot(this,void 0,void 0,function*(){this.closeCalled||(this.closeCalled=!0,yield(A=this.sessionMetrics)===null||A===void 0?void 0:A.uploadMetrics(),ct(this.pingUpdateTimeout),ct(this.pingV2UpdateTimeout),ct(this.pingV2MetricsGatherTimeout),ct(this.reassemblyTableCleanupTimeout),ct(this.streamsInfoUpdateTimeout),ct(this.heartbeatTimeout),(x=this._peerConnection)===null||x===void 0||x.close(),(q=this.heartbeatChannel)===null||q===void 0||q.close(),(oe=this.latestReliableStreamChannel)===null||oe===void 0||oe.close(),(se=this.latestTryOnceStreamChannel)===null||se===void 0||se.close(),(de=this.latestTtlStreamChannel)===null||de===void 0||de.close(),(he=this.reliableStreamChannel)===null||he===void 0||he.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 A;return(A=this.config.remoteConfig)===null||A===void 0?void 0:A.sessionCreatedTimestamp}setSessionCreatedTimestamp(A){this.config.remoteConfig&&(this.config.remoteConfig.sessionCreatedTimestamp=A)}getSessionId(){var A;return(A=this.config.remoteConfig)===null||A===void 0?void 0:A.sessionId}setSessionId(A){this.config.remoteConfig&&(this.config.remoteConfig.sessionId=A,this.sessionMetrics=new Le(A,this))}getRemotePeerId(){return this.config.baseConfig.remotePeerId}getRemoteDeviceId(){var A;return(A=this.config.baseConfig)===null||A===void 0?void 0:A.remoteDeviceId}setRemoteDeviceId(A){this.config.baseConfig.remoteDeviceId=A}getSessionMetricsMessageCounts(){var A;return(A=this.sessionMetrics)===null||A===void 0?void 0:A.counts}getConnectionStatsInfo(){return ot(this,void 0,void 0,function*(){const{peerConnection:A}=this;if(!A)return;const x=yield A.getStats(null),q=[];x.forEach(pe=>{q.push(pe)});const oe=q.find(pe=>pe.type==="transport");if(!oe)return;const se=q.find(pe=>(pe.type==="candidate-pair"||pe.type==="candidatepair")&&pe.id===oe.selectedCandidatePairId);if(!se)return;const de=q.find(pe=>pe.id===se.localCandidateId),he=q.find(pe=>pe.id===se.remoteCandidateId);return de&&he&&(de.address=de.address||de.ip,he.address=he.address||he.ip,de.address!==void 0&&he.address!==void 0)?{transport:oe,localCandidate:de,remoteCandidate:he}:void 0})}initializeChannels(A){this.heartbeatChannel=A.createDataChannel("heartbeat",Te),this.heartbeatChannel.binaryType="arraybuffer",this.latestTtlStreamChannel=A.createDataChannel("stream.latest-ttl",ne),this.latestTtlStreamChannel.binaryType="arraybuffer",this.reliableStreamChannel=A.createDataChannel("stream.reliable",ie),this.reliableStreamChannel.binaryType="arraybuffer",this.latestReliableStreamChannel=A.createDataChannel("stream.latest-reliable",ce),this.latestReliableStreamChannel.binaryType="arraybuffer",this.latestTryOnceStreamChannel=A.createDataChannel("stream.latest-try-once",Se),this.latestTryOnceStreamChannel.binaryType="arraybuffer",this.setupChannel(this.latestTtlStreamChannel),this.setupChannel(this.reliableStreamChannel),this.setupChannel(this.latestReliableStreamChannel),this.setupChannel(this.latestTryOnceStreamChannel)}getOffer(){var A,x;return ot(this,void 0,void 0,function*(){const{gotOffer:q}=this,{peerConnection:oe,config:se}=this;if(this.config.baseConfig.isLan)throw new Error('"getOffer" method can only be called with internet connections. LAN connections should call the "getLanOffer" method.');const de=(A=this.config.remoteConfig)===null||A===void 0?void 0:A.sessionId;if(q)return void h.a.debug("Failed to generate offer because gotOffer was already called.");if(this.gotOffer=!0,Rt(this.peerConnection))return void h.a.debug("Failed to generate offer because the peer connection was inactive.");const he=se.baseConfig.track;oe.onicecandidate=()=>{this.hasIceCandidate=!0},oe.oniceconnectionstatechange=()=>ot(this,void 0,void 0,function*(){const We=oe.iceConnectionState;if(We==="connected"||We==="completed"){const je=yield this.getConnectionStatsInfo(),Pe=je?Qt(je):void 0;h.a.info(`ICE connection state changed to ${We}`,{sessionId:de,connectionStatsInfo:je,iceMode:Pe}),he==null||he("ICE connection state change",{iceConnectionState:We,sessionId:de,connectionStatsInfo:je,iceMode:Pe})}}),yield oe.setLocalDescription(yield oe.createOffer());const pe=oe.getConfiguration?oe.getConfiguration().iceTransportPolicy:"all",Ue=new Date().getTime();for(;;){const We=new Date().getTime()-Ue;if(We>this.connectTimeoutMs)return void h.a.debug("Failed to generate offer because ICE gathering timed out.");if(We>this.iceGatheringTimeoutMs&&this.hasIceCandidate){h.a.debug("ICE gathering partially completed; proceeding",{iceTransportPolicy:pe,waitTime:We}),he==null||he("ICE gathering partially completed",{sessionId:de,iceTransportPolicy:pe,waitTime:We});break}if(oe.iceGatheringState==="complete"){h.a.debug("ICE gathering complete",{iceTransportPolicy:pe,waitTime:We}),he==null||he("ICE gathering completed",{sessionId:de,iceTransportPolicy:pe,waitTime:We});break}yield Object(u.a)(.1*d.a.second)}const le=(x=this.iceServers)!==null&&x!==void 0?x:[];for(const We of le)"credentialType"in We&&(We.credentialType=void 0);const me=JSON.stringify(le),Je=new _.Signal;return Je.setPayload(JSON.stringify(oe.localDescription)),Je.setSenderId(this.config.baseConfig.localPeerId),Je.setReceiverId(this.config.baseConfig.remotePeerId),Je.setIceServers(me),Je.setIceTransportPolicy(pe!=null?pe:"all"),this.config.baseConfig.sessionType!==void 0?Je.setSessionType(this.config.baseConfig.sessionType):Je.setSessionType(_.SessionType.TELEOP),h.a.debug("Sending offer signal with description",{description:Je.getPayload()}),Je})}getLanOffer(){return ot(this,void 0,void 0,function*(){const{peerConnection:A,gotOffer:x}=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(x)return void h.a.debug("Failed to generate offer because gotOffer was already called.");if(this.gotOffer=!0,Rt(this.peerConnection))return void h.a.debug("Failed to generate offer because the peer connection was inactive.");yield A.setLocalDescription(yield A.createOffer());const q=new Date().getTime();for(;;){if(new Date().getTime()-q>this.iceGatheringTimeoutMs)return void h.a.debug("Failed to generate offer because ICE gathering timed out.");if(A.iceGatheringState==="complete")break;yield Object(u.a)(.1*d.a.second)}const oe=A.localDescription;if(oe)return h.a.debug("Sending LAN offer signal with description",{description:oe}),oe;h.a.error("Failed to generate LAN offer description")})}handleLanAnswer(A){return ot(this,void 0,void 0,function*(){const{peerConnection:x}=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 x.setRemoteDescription(A)})}getChannelFromLabel(A){switch(A){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(A,x){var q;let oe;try{oe=Object(H.encode)(JSON.stringify(x))}catch(se){return void h.a.warn("Failed to encode RTC message",{error:se})}try{A.send(oe),(q=this.sessionMetrics)===null||q===void 0||q.incrementLocalSent(x)}catch(se){h.a.warn("Failed to send message to channel",{error:se,channel:A.label})}}channelNotRecognized(A){return A!==this.latestTtlStreamChannel&&A!==this.latestReliableStreamChannel&&A!==this.latestTryOnceStreamChannel&&A!==this.reliableStreamChannel}setupChannel(A){A.onmessage=x=>{if(this.channelNotRecognized(A))return void h.a.warn("Received message on unrecognized data channel.");let q;try{q=JSON.parse(Object(H.decode)(x.data))}catch(oe){return void h.a.warn("Received unparseable message on RTC stream data channel",{error:oe,channel:A.label})}q.communicationType==="message-chunk"?this.receiveChannelMessageChunk(A,q):this.receiveChannelMessage(A,q)},A.onerror=x=>{h.a.warn(`Channel error: ${x.error}`,{error:x.error,sessionId:this.getSessionId(),channelLabel:A.label})},A.onopen=()=>{h.a.debug("Channel opened",{sessionId:this.getSessionId(),channelLabel:A.label})},A.onclose=()=>{const x={bufferedAmount:A.bufferedAmount,sessionId:this.getSessionId(),channelLabel:A.label};this.closeCalled===!1?h.a.debug("Unexpected channel closed",x):h.a.debug("Channel closed",x)}}receiveChannelMessage(A,x){var q;const{config:oe}=this,{remotePeerId:se}=this.config.baseConfig;this.lastMessageTimestamp=new Date().getTime(),x=Et(x),(q=this.sessionMetrics)===null||q===void 0||q.incrementLocalReceived(x),this.handleSystemMessage(A,x)||(A===this.latestTryOnceStreamChannel||A===this.latestTtlStreamChannel||A===this.latestReliableStreamChannel)&&!this.isLatestMessage(x)||oe.baseConfig.receive(se,x)}receiveChannelMessageChunk(A,x){const q=this.reassemblyTable.get(x.id)||[];if(q.push(x),q.length===x.total){const oe=function(se){const de=se.sort((he,pe)=>he.seq<pe.seq?-1:1).map(he=>he.part).reduce((he,pe)=>he+pe);try{return JSON.parse(de)}catch{return void h.a.warn("Could not reassemble RTC message chunks")}}(q);return oe&&this.receiveChannelMessage(A,oe),void this.reassemblyTable.delete(x.id)}this.reassemblyTable.set(x.id,q),this.reassemblyTableLastTimestamp.set(x.id,new Date().getTime())}handleSystemMessage(A,x){var q,oe;const{config:se}=this,{baseConfig:de}=se,{remotePeerId:he,remoteDeviceId:pe}=de;switch(x.header.stream.streamType){case"ping":return this.sendSystemMessage(A,{type:"pong",timestamp:te(x.payload.ping)}),!0;case"pong":{const Ue=new Date().getTime()-te(x.payload.pong);return this.pingTimeMs=Ue,Q.aggregate("rtc-ping-time",Ue,Object.assign({},pe?{deviceId:pe}:{})),!0}case"ping-v2":return this.sendPingV2(),!0;case"pong-v2":{const Ue=te(x.payload.pongV2),le=this.pingV2Map.get(Ue.id);return(le==null?void 0:le.sent)!==Ue.timestamp&&h.a.warn("Pong timestamp doesn't match stored value",{currentEntry:le,pong:Ue}),this.pingV2Map.set(Ue.id,{sent:Ue.timestamp,received:new Date().getTime()}),!0}case"streams-info":{const{sessionMetrics:Ue}=this,le=(q=x.payload.streamsInfo)===null||q===void 0?void 0:q.timestamp;return!!le&&(Ue==null||Ue.updateRemoteMessagesCounts(x),(oe=de.onStreamsInfoUpdate)===null||oe===void 0||oe.call(de,he,le),!0)}case"stream-control":return!0;default:return!1}}sendSystemMessage(A,x){var q;const{localUserId:oe,localPeerId:se}=this.config.baseConfig;if(A.readyState!=="open")return;const de={entityId:oe!=null?oe:se,streamName:`$.${x.type}`,streamType:x.type};let he;switch(x.type){case"ping":he={ping:new Date().getTime()};break;case"pong":he={pong:x.timestamp};break;case"ping-v2":he={pingV2:x.payload};break;case"pong-v2":he={pongV2:x.payload};break;case"stream-control":he={streamControl:x.streamControl};break;case"streams-info":he={streamsInfo:(q=this.sessionMetrics)===null||q===void 0?void 0:q.getLocalStreamsInfo(new Date().getTime())}}this.sendOnChannel(A,et(de,he))}isLatestMessage(A){const x=_e(A.header.stream),q=(this.streamLatestTimestamp.get(x)||0)<=A.header.created;return q&&this.streamLatestTimestamp.set(x,A.header.created),q}}function ct(Re){Re&&clearInterval(Re)}function kt(){h.a.debug("forceGarbageCollection() triggered"),queueMicrotask(()=>{let Re=document.createElement("img");Re.src=window.URL.createObjectURL(new Blob([new ArrayBuffer(5e7)])),Re.onerror=function(){window.URL.revokeObjectURL(this.src),Re=null}})}function Wt(Re){try{return Re instanceof Error?`${Re.name}: ${Re.message}`:typeof Re=="object"?JSON.stringify(Re):String(Re)}catch{return"Unknown error"}}function vt(Re){var A,x;return{userId:(A=Re.getUserId())===null||A===void 0?void 0:A.getValue(),deviceId:(x=Re.getDeviceId())===null||x===void 0?void 0:x.getValue(),organizationId:Re.getOrganizationId(),id:Re.getPeerId(),capabilities:[],capabilitySet:{}}}var De=function(Re,A,x,q){return new(x||(x=Promise))(function(oe,se){function de(Ue){try{pe(q.next(Ue))}catch(le){se(le)}}function he(Ue){try{pe(q.throw(Ue))}catch(le){se(le)}}function pe(Ue){var le;Ue.done?oe(Ue.value):(le=Ue.value,le instanceof x?le:new x(function(me){me(le)})).then(de,he)}pe((q=q.apply(Re,A||[])).next())})};const dt=Re=>Re.map(A=>Object.assign(Object.assign(Object.assign({},A),A.username?{username:"<REDACTED>"}:null),A.credential?{credential:"<REDACTED>"}:null));class At{constructor(A){this.config=A,this.grpcCallDeadline=5*d.a.second,this.refreshIntervalDelayMs=2*d.a.second,this.iceServersTtl=30*d.a.minute,this.connections=[],this.localConnections=[],this.isConnectionInitiator=new WeakSet,this.isOutgoingConnection=new Set,this.peerDataChannelListeners=[],this.rtcInstancesConstructed=0,this.statsLoopsExecuted=0;const{refreshIntervalDelayMs:x}=this;this.refreshInterval=F({func:()=>De(this,void 0,void 0,function*(){try{yield this.update()}catch(q){h.a.warn("RTC refresh failed",{error:q})}}),delay:x,immediate:!0})}send(A,x,q){const oe=this.getActiveConnection(A);oe?oe.isReady()?oe.send(x,q):h.a.warn("Send called with unready connection."):h.a.warn("Send called with no connection.")}controlRemoteStream(A,x){const q=this.getActiveConnection(A);q?q.isReady()?q.controlRemoteStream(x):h.a.warn("controlRemoteStream called with unready connection."):h.a.warn("controlRemoteStream called with no connection.")}getLocalPeer(){return De(this,void 0,void 0,function*(){for(;!this.localPeer;)yield Object(u.a)(.1*d.a.second);return vt(this.localPeer)})}connect(A,x){var q,oe,se;return De(this,void 0,void 0,function*(){if(this.config.lanOnlyMode===!0)throw new Error("connect method called in local only mode.");const{track:de,signalingClient:he}=this.config,{localPeer:pe,receiveSignalStream:Ue,iceServers:le}=this;if(!pe||!Ue||!le)return void h.a.warn("Connect called prior to local peer, receiveSignalStream, and ICE servers ready");if(this.getActiveConnection(A))return void h.a.warn("Connect called for peer with existing connection.");if(this.isOutgoingConnection.has(A))return void h.a.warn("Connect called for peer with an existing outgoing connection offer.");this.isOutgoingConnection.add(A);const me=function(Ze,Me,ze){const{rtcIceTransportPolicies:Ye,rtcIceServerProtocol:Xe,useAllServers:Ke}=Me||{},st=Ze.map(at=>Object.assign(Object.assign({},at),{urls:at.urls.filter(ht=>{const Zt=(Ye===void 0||Ye.some(Tt=>C(ht,Tt)))&&(Xe===void 0||S(ht,Xe));return Zt||h.a.debug(`Ignoring ICE server: ${ht}`,{organizationId:ze}),Zt})})).filter(({urls:at})=>at.filter(ht=>ht).length>0);return Ke?st:[M(st,"stun"),M(st,"turn")].filter(at=>at!==void 0).map(at=>te(at))}(le,x);h.a.debug("Received ICE servers:",dt(le)),h.a.debug("Using ICE servers:",dt(me));const Je=new gt(yield this.createRTCPeerConnection(me),me,{baseConfig:{isOffer:!0,isLan:!1,receive:(Ze,Me)=>this.config.receive(Ze,Me),onStreamsInfoUpdate:this.config.onStreamsInfoUpdate?(Ze,Me)=>{var ze,Ye;return(Ye=(ze=this.config).onStreamsInfoUpdate)===null||Ye===void 0?void 0:Ye.call(ze,Ze,Me)}:void 0,track:this.config.lanOnlyMode?void 0:this.config.track,localUserId:(q=pe.getUserId())===null||q===void 0?void 0:q.getValue(),localPeerId:pe.getPeerId(),remotePeerId:A,sessionType:this.config.sessionType},remoteConfig:{}},Ze=>this.onCustomDataChannel(A,Ze)),We=yield Je.getOffer();if(!We)return h.a.error("Failed to generate offer."),void this.isOutgoingConnection.delete(A);h.a.debug("Sending offer."),de==null||de("Sending offer",We);const je=new _.SendSignalRequest;je.setSignal(We);const Pe=yield(()=>De(this,void 0,void 0,function*(){try{return yield X.withDeadline(he.sendSignal(je,yield this.getMetadata()),this.grpcCallDeadline)}catch(Ze){h.a.warn("Error when sending signal",{error:Ze})}}))();if(!this.isOutgoingConnection.has(A))return void h.a.debug("No offer set after receiving offer signal response.");h.a.debug("Offer sent.");const He=(oe=Pe==null?void 0:Pe.getSessionId())===null||oe===void 0?void 0:oe.getValue(),qe=(se=Pe==null?void 0:Pe.getSessionCreatedTimestamp())===null||se===void 0?void 0:se.getValue();return He&&qe?(Je.setSessionId(He),Je.setSessionCreatedTimestamp(qe),this.isOutgoingConnection.delete(A),this.connections.push(Je),this.isConnectionInitiator.add(Je),this.setupHandlers(Je),He):(h.a.warn("No session ID or no session created timestamp on send signal response."),void this.isOutgoingConnection.delete(A))})}connectLan(A){var x,q;return De(this,void 0,void 0,function*(){const oe=new E(A),se=new gt(yield this.createRTCPeerConnection([]),[],{baseConfig:{isOffer:!0,isLan:!0,receive:(Ue,le)=>this.config.receive(Ue,le),onStreamsInfoUpdate:this.config.onStreamsInfoUpdate?(Ue,le)=>{var me,Je;return(Je=(me=this.config).onStreamsInfoUpdate)===null||Je===void 0?void 0:Je.call(me,Ue,le)}:void 0,track:this.config.lanOnlyMode?void 0:this.config.track,localUserId:(q=(x=this.localPeer)===null||x===void 0?void 0:x.getUserId())===null||q===void 0?void 0:q.getValue(),localPeerId:"lan_client",remotePeerId:A}},Ue=>this.onCustomDataChannel(A,Ue)),de=yield se.getLanOffer();if(!de)return h.a.warn("Could not generate LAN offer"),!1;const he=yield oe.postLanRtcOffer({offer:JSON.stringify(de)}),pe=new RTCSessionDescription(JSON.parse(he.answer));return yield se.handleLanAnswer(pe),this.localConnections.push(se),this.isConnectionInitiator.add(se),Object(T.a)()})}getConnections(){return[...this.connections,...this.localConnections]}createCustomDataChannel(A,x,q,oe,se){const de=this.getActiveConnection(A);if(de&&this.isConnectionInitiator.has(de)){const pe=de.peerConnection.createDataChannel("custom."+x,q);return oe&&(pe.binaryType="arraybuffer"),se(A,pe),()=>{}}const he=(pe,Ue)=>{A===pe&&Ue.label==="custom."+x&&se(A,Ue)};return this.peerDataChannelListeners.push(he),()=>{this.peerDataChannelListeners=this.peerDataChannelListeners.filter(pe=>pe!==he)}}onCustomDataChannel(A,x){this.peerDataChannelListeners.forEach(q=>q(A,x))}getConnectionStatus(A){if(this.isOutgoingConnection.has(A))return"connecting";const x=this.getActiveConnection(A);return x?x.isReady()?"connected":"connecting":"disconnected"}getConnectionStatsInfo(A){return De(this,void 0,void 0,function*(){const x=this.getActiveConnection(A);if(x)return yield x.getConnectionStatsInfo()})}disconnect(A){return De(this,void 0,void 0,function*(){const x=this.getActiveConnection(A);x&&(yield x.close(),this.connections=this.connections.filter(q=>q!==x),this.localConnections=this.localConnections.filter(q=>q!==x))})}getPeers(){return De(this,void 0,void 0,function*(){if(this.config.lanOnlyMode)throw new Error("getPeers method cannot be used in local-only mode.");const{signalingClient:A}=this.config,x=yield(()=>De(this,void 0,void 0,function*(){try{return yield X.withDeadline(A.getPeers(new _.GetPeersRequest,yield this.getMetadata()),this.grpcCallDeadline)}catch(se){h.a.warn("Error when getting peers",{error:se})}}))();if(!x)return[];const q=x.getPeersList();if(!q)return[];const oe=se=>{var de,he;return(he=(de=se.getPeerCreatedTimestamp())===null||de===void 0?void 0:de.getValue())!==null&&he!==void 0?he:0};return q.sort((se,de)=>oe(de)-oe(se)).map(se=>vt(se))})}getSessions(){return De(this,void 0,void 0,function*(){if(this.config.lanOnlyMode)throw new Error("getPeers method cannot be used in local-only mode.");const{signalingClient:A}=this.config,x=yield(()=>De(this,void 0,void 0,function*(){try{return yield X.withDeadline(A.getPeers(new _.GetPeersRequest,yield this.getMetadata()),this.grpcCallDeadline)}catch(se){h.a.warn("Error when getting peers",{error:se})}}))();if(!x)return{};const q=x.getPeersList(),oe={};for(const se of q)oe[se.getPeerId()]=se.getSessionIdsList();return oe})}getPing(A){const x=this.getActiveConnection(A);if(x)return x.getPing();h.a.warn("Attempted to get ping time from inactive peer.")}getPingInfo(A){const x=this.getActiveConnection(A);if(x)return x.getPingInfo();h.a.warn("Attempted to get ping time from inactive peer.")}getLastMessageTimestamp(A){const x=this.getActiveConnection(A);if(x)return x.getLastMessageTimestamp();h.a.warn("Attempted to get last message time from inactive peer.")}getSessionMetricsMessageCounts(A){const x=this.getActiveConnection(A);if(x)return x.getSessionMetricsMessageCounts();h.a.warn("Attempted to get session metrics counts from inactive peer.")}isReady(){if(this.config.lanOnlyMode)return!0;const{localPeer:A,receiveSignalStream:x,iceServers:q}=this;return!!(A&&x&&q)}shutdown(){return De(this,void 0,void 0,function*(){h.a.info("Shutdown called on RTC client"),yield this.refreshInterval.stop(),this.receiveSignalStream&&this.receiveSignalStream.cancel();const A=this.connections;this.connections=[],yield this.closeConnections(A);const x=this.localConnections;this.localConnections=[],yield this.closeConnections(x),this.isOutgoingConnection.clear(),this.peerDataChannelListeners=[];const{localPeer:q}=this;if(!q||this.config.lanOnlyMode)return;const{signalingClient:oe}=this.config;yield(()=>De(this,void 0,void 0,function*(){try{const se=new _.DeletePeerRequest;se.setPeerId(q.getPeerId()),yield X.withDeadline(oe.deletePeer(se,yield this.getMetadata()),this.grpcCallDeadline)}catch(se){return void h.a.warn("Error deleting local peer",{error:se})}}))()})}createPeer(){return De(this,void 0,void 0,function*(){if(this.config.lanOnlyMode)throw new Error("createPeer method cannot be used in local-only mode.");const{signalingClient:A}=this.config,x=yield(()=>De(this,void 0,void 0,function*(){try{return yield X.withDeadline(A.createPeer(new _.CreatePeerRequest,yield this.getMetadata()),this.grpcCallDeadline)}catch(oe){const se=oe;h.a.debug("createPeer failed",{error:se});const de=Wt(se);throw new Error(`Was not able to create peer: ${de}`)}}))(),q=x==null?void 0:x.getPeer();if(!q)throw new Error("Response did not provide peer.");return this.localPeer=q})}createReceiveSignalStream(){return De(this,void 0,void 0,function*(){if(this.config.lanOnlyMode)throw new Error("createReceiveSignalStream method cannot be used in local-only mode.");const{signalingClient:A}=this.config,{localPeer:x,iceServers:q}=this;if(!x||!q)return;const{receiveSignalStream:oe}=this;oe&&oe.cancel();const se=new _.ReceiveSignalStreamRequest;se.setPeerId(x.getPeerId());const de=yield(()=>De(this,void 0,void 0,function*(){try{return A.receiveSignalStream(se,yield this.getMetadata({hasDeadline:!1}))}catch(he){h.a.debug("createReceiveSignalStream failed",{error:he});const pe=Wt(he);throw new Error(`Unable to create receive signal stream: ${pe}`)}}))();if(!de)throw new Error("Response did not provide stream.");return de.on("data",he=>De(this,void 0,void 0,function*(){var pe,Ue,le,me;const Je=he.getSignal(),We=(pe=Je==null?void 0:Je.getSessionId())===null||pe===void 0?void 0:pe.getValue(),je=Je==null?void 0:Je.getSenderId(),Pe=Je==null?void 0:Je.getReceiverId(),He=(Ue=Je==null?void 0:Je.getSessionCreatedTimestamp())===null||Ue===void 0?void 0:Ue.getValue();if(!(Je&&We&&je&&Pe&&He))return void h.a.warn("Received signal with missing information.");const qe=this.getActiveConnection(je);if(qe)if(qe.getSessionId()!==We){if(h.a.debug("Received signal: different session for a peer we're already connected to."),(qe.getSessionCreatedTimestamp()||0)>He)return;const Ze=new gt(yield this.createRTCPeerConnection(q),q,{baseConfig:{isOffer:!1,isLan:!1,receive:(Me,ze)=>this.config.receive(Me,ze),onStreamsInfoUpdate:this.config.onStreamsInfoUpdate?(Me,ze)=>{var Ye,Xe;return(Xe=(Ye=this.config).onStreamsInfoUpdate)===null||Xe===void 0?void 0:Xe.call(Ye,Me,ze)}:void 0,track:this.config.lanOnlyMode?void 0:this.config.track,localPeerId:x.getPeerId(),localUserId:(me=x.getUserId())===null||me===void 0?void 0:me.getValue(),remotePeerId:je},remoteConfig:{sessionId:We,sessionCreatedTimestamp:He}},Me=>this.onCustomDataChannel(je,Me));yield Ze.handleSignal(Je),this.connections.push(Ze)}else h.a.debug("Received signal: for an existing connection."),yield qe.handleSignal(Je);else{h.a.debug("Received signal: new connection.");const Ze=new gt(yield this.createRTCPeerConnection(q),q,{baseConfig:{isOffer:!1,isLan:!1,receive:(Me,ze)=>this.config.receive(Me,ze),onStreamsInfoUpdate:this.config.onStreamsInfoUpdate?(Me,ze)=>{var Ye,Xe;return(Xe=(Ye=this.config).onStreamsInfoUpdate)===null||Xe===void 0?void 0:Xe.call(Ye,Me,ze)}:void 0,track:this.config.lanOnlyMode?void 0:this.config.track,localPeerId:x.getPeerId(),localUserId:(le=x.getUserId())===null||le===void 0?void 0:le.getValue(),remotePeerId:je},remoteConfig:{sessionId:We,sessionCreatedTimestamp:He}},Me=>this.onCustomDataChannel(je,Me));yield Ze.handleSignal(Je),this.connections.push(Ze)}})),de.on("end",()=>{de.cancel(),this.receiveSignalStream=void 0}),de.on("error",he=>{switch(he.code){case k.StatusCode.CANCELLED:case k.StatusCode.UNAVAILABLE:case k.StatusCode.UNKNOWN:h.a.debug("Receive signal stream error",{error:he});break;case k.StatusCode.UNAUTHENTICATED:h.a.warn("Receive signal stream error",{error:he});break;default:h.a.error("Receive signal stream error",{error:he})}de.cancel(),this.receiveSignalStream=void 0}),this.receiveSignalStream=de})}createRTCPeerConnection(A){var x;return De(this,void 0,void 0,function*(){const q=(x=this.config.alternateRTCPeerConnection)!==null&&x!==void 0?x:window.RTCPeerConnection;if(!q)throw function(){const{userAgent:oe}=navigator;return oe.includes("Firefox/")?"Firefox":oe.includes("Edg/")?"Edge":oe.includes("Chrome/")?"Chrome":oe.includes("Safari/")?"Safari":oe.includes("MSIE/")||oe.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||kt();try{return new q({iceServers:A})}catch(oe){throw h.a.debug(`Failed to create RTCPeerConnection: ${this.rtcInstancesConstructed} total allocated`),oe}})}closeConnections(A){return De(this,void 0,void 0,function*(){const x=yield G(A.map(q=>De(this,void 0,void 0,function*(){yield q.close()})));for(const q of x)h.a.warn("Request to close session failed",{error:q})})}getActiveConnection(A){return this.getConnections().find(x=>x.getRemotePeerId()===A&&x.isActive())}update(){var A;return De(this,void 0,void 0,function*(){if(this.localConnections=this.localConnections.filter(me=>me.isActive()),this.config.lanOnlyMode)return;const{signalingClient:x}=this.config;if(!this.localPeer||!this.receiveSignalStream||!this.iceServers){const me=[];return this.localPeer||me.push(this.createPeer()),this.iceServers||me.push(this.updateIceServers()),yield Promise.all(me),void(this.receiveSignalStream||(yield this.createReceiveSignalStream()))}const[q,oe]=(se=this.connections,de=me=>me.isActive(),se.reduce((me,Je,We,je)=>{const[Pe,He]=me;return(de(Je,We,je)?Pe:He).push(Je),me},[[],[]]));var se,de;yield this.closeConnections(oe),this.connections=q,this.gatherConnectionStats().catch(me=>{h.a.warn("Error calling gatherConnectionStats",{error:me})}),this.statsLoopsExecuted++;const{localPeer:he}=this,pe=this.connections.filter(me=>me.getSessionId).map(me=>te(me.getSessionId()));he.setSessionIdsList(pe);const Ue=new _.RefreshPeerRequest;Ue.setPeer(he);try{yield X.withDeadline(x.refreshPeer(Ue,yield this.getMetadata()),this.grpcCallDeadline)}catch(me){me instanceof k.RpcError&&me.code===k.StatusCode.NOT_FOUND?(h.a.warn("Peer expired, creating new peer",{peerId:he.getPeerId()}),yield this.reset()):h.a.warn("Error calling RefreshPeer",{error:me})}const le=yield this.getPeers();for(const me of this.connections)me.setRemoteDeviceId((A=le.find(Je=>Je.id===me.getRemotePeerId()))===null||A===void 0?void 0:A.deviceId)})}gatherConnectionStats(){return De(this,void 0,void 0,function*(){if(this.statsLoopsExecuted%10!=0||this.connections.length!==1)return;const A=yield this.connections[0].getConnectionStatsInfo(),x=A?Qt(A):void 0;x?(h.a.info(`Detected RTC connection type: ${x}`),Q.setTag("rtc-connection-type",x)):Q.setTag("rtc-connection-type","unknown")})}reset(){return De(this,void 0,void 0,function*(){yield this.closeConnections(this.connections),this.connections=[],this.isOutgoingConnection.clear(),yield this.createPeer(),yield this.createReceiveSignalStream()})}updateIceServers(){return De(this,void 0,void 0,function*(){if(this.config.lanOnlyMode)return;const{iceServersLastUpdate:A,iceServersTtl:x}=this,q=new Date().getTime();if(!A||q-A>x)try{const oe=(yield X.withDeadline(this.config.signalingClient.getIceServers(new _.GetIceServersRequest,yield this.getMetadata()),this.grpcCallDeadline)).getIceServers();this.iceServers=JSON.parse(oe),this.iceServersLastUpdate=q}catch(oe){h.a.warn("Error in updateIceServers",{error:oe})}})}setupHandlers(A){const{peerConnection:x}=A,q=A.getSessionCreatedTimestamp();x.onconnectionstatechange=()=>De(this,void 0,void 0,function*(){const oe=x.connectionState;if(!q)return;const se=A.getRemoteDeviceId();switch(oe){case"connected":Q.aggregate("rtc-connect-time",new Date().getTime()-q,Object.assign({},se?{deviceId:se}:{}));break;case"failed":Q.increment("rtc-connect-failed",Object.assign({},se?{deviceId:se}:{}))}})}getMetadata(A={}){return De(this,void 0,void 0,function*(){if(this.config.lanOnlyMode)throw new Error("getMetadata method cannot be called in local-only mode");const{getToken:x}=this.config,{grpcCallDeadline:q}=this,{hasDeadline:oe=!0}=A,se=oe?{deadline:(Date.now()+q).toString(10)}:null;try{const de=yield x();return Object.assign({authorization:de},se)}catch(de){throw h.a.error("getToken() failed",{error:de}),new Error("Cannot get authorization token")}})}}var tt=n(12),Ft=n(11),Bt=function(Re,A,x,q){return new(x||(x=Promise))(function(oe,se){function de(Ue){try{pe(q.next(Ue))}catch(le){se(le)}}function he(Ue){try{pe(q.throw(Ue))}catch(le){se(le)}}function pe(Ue){var le;Ue.done?oe(Ue.value):(le=Ue.value,le instanceof x?le:new x(function(me){me(le)})).then(de,he)}pe((q=q.apply(Re,A||[])).next())})};class It{constructor(A,x){this.sentMessagesCounts=new Map,this.receivedMessagesCounts=new Map,this.sessionId=A,this.connection=x}incrementMessageSent(A){const x=_e(A.header.stream);this.sentMessagesCounts.set(x,(this.sentMessagesCounts.get(x)||0)+1)}incrementMessageReceived(A){const x=_e(A.header.stream);this.receivedMessagesCounts.set(x,(this.receivedMessagesCounts.get(x)||0)+1)}uploadMetrics(){return Bt(this,void 0,void 0,function*(){const{sessionId:A}=this,x=yield this.connection.peerConnection.getStats(),q={};x.forEach(se=>q[se.id]=se),h.a.debug("rtc-stats",Object.assign(Object.assign({},q),{sessionId:A}));const oe=[...new Set(Array.from(this.sentMessagesCounts.keys()).concat(Array.from(this.receivedMessagesCounts.keys())))].reduce((se,de)=>{const he=this.sentMessagesCounts.get(de),pe=this.receivedMessagesCounts.get(de);return Object.assign(Object.assign({},se),{[`${de}-sent`]:he,[`${de}-received`]:pe})},{sessionId:A});h.a.debug("rtc-message-report",oe)})}}function Ct(Re,A){return _e(Re)===_e(A)}var nt=function(Re,A,x,q){return new(x||(x=Promise))(function(oe,se){function de(Ue){try{pe(q.next(Ue))}catch(le){se(le)}}function he(Ue){try{pe(q.throw(Ue))}catch(le){se(le)}}function pe(Ue){var le;Ue.done?oe(Ue.value):(le=Ue.value,le instanceof x?le:new x(function(me){me(le)})).then(de,he)}pe((q=q.apply(Re,A||[])).next())})};class St{constructor(A,x){this.peerConnection=A,this.config=x,this.connectTimeoutMs=10*d.a.second,this.gatherIceTimeoutMs=5*d.a.second,this.pingUpdateTimeoutMs=2*d.a.second,this.streamLatestTimestamp=new Map,this.closeCalled=!1,this.connectCalled=!1,this.sentOffer=!1,this.receivedIceCandidate=!1;const{isOffer:q}=x;q?this.initializeChannels(A):A.ondatachannel=oe=>{switch(oe.channel.label){case"stream.latest-ttl":this.latestTtlStreamChannel=oe.channel;break;case"stream.reliable":this.reliableStreamChannel=oe.channel;break;case"stream.latest-reliable":this.latestReliableStreamChannel=oe.channel;break;case"stream.latest-try-once":this.latestTryOnceStreamChannel=oe.channel}this.setupChannel(oe.channel)},this.sessionMetrics=new It(this.getSessionId(),this)}connect(){return nt(this,void 0,void 0,function*(){if(this.connectCalled)return;this.connectCalled=!0,this.pingUpdateTimeout=setInterval(()=>{const{reliableStreamChannel:oe}=this;oe&&this.sendSystemMessage(oe,{type:"ping"})},this.pingUpdateTimeoutMs),this.connectTimeout=setTimeout(()=>nt(this,void 0,void 0,function*(){this.isReady()||(h.a.warn("RTC connect timed out, closing connection"),yield this.close())}),this.connectTimeoutMs);const{peerConnection:A,config:{isOffer:x,sessionId:q}}=this;if(x){const oe=yield A.createOffer();yield A.setLocalDescription(oe)}x&&(this.gatherIceTimeout=setTimeout(()=>nt(this,void 0,void 0,function*(){this.sentOffer||(h.a.warn("ICE gathering timed out"),this.receivedIceCandidate?(h.a.warn("Attempting to connect with partial ICE candidate pool"),yield this.sendOffer()):yield this.close())}),this.gatherIceTimeoutMs),A.onicecandidate=oe=>nt(this,void 0,void 0,function*(){oe.candidate?this.receivedIceCandidate=!0:yield this.sendOffer()}),A.onicegatheringstatechange=()=>nt(this,void 0,void 0,function*(){A.iceGatheringState==="complete"&&(yield this.sendOffer())}),A.onnegotiationneeded=()=>{h.a.debug("Negotiation needed",{sessionId:q})})})}handleSignal(A){return nt(this,void 0,void 0,function*(){const{peerConnection:x,config:{sessionId:q,sendSignal:oe}}=this,{description:se}=JSON.parse(A.payload);if(h.a.debug("Handling signal",{sessionId:q,description:JSON.stringify(se)}),se)if(x.signalingState!=="stable"||x.connectionState!=="connected")if(x.remoteDescription)h.a.warn(`Received SDP signal during negotiation when remote description is already set: ${JSON.stringify(A)}`);else if(se.type==="offer"){yield x.setRemoteDescription(se);const de=yield x.createAnswer();yield x.setLocalDescription(de),yield oe({payload:JSON.stringify({description:de})})}else se.type==="answer"&&(yield x.setRemoteDescription(se));else h.a.warn(`Received SDP signal when signaling is stable and connected: ${JSON.stringify(A)}`);else h.a.warn(`Received non-SDP signal: ${JSON.stringify(A)}`)})}send(A,x){const q=this.getChannelFromLabel(x.channelLabel);q?this.sendOnChannel(q,A):h.a.warn("Send called with unexpected channel label",{channelLabel:x.channelLabel})}controlRemoteStream(A){this.sendSystemMessage(te(this.reliableStreamChannel),{type:"stream-control",streamControl:A})}isActive(){return new Set(["new","connecting","connected"]).has(this.peerConnection.connectionState)}isReady(){const{peerConnection:A,latestTtlStreamChannel:x,reliableStreamChannel:q,latestTryOnceStreamChannel:oe}=this;return!!(q&&x&&oe)&&A.connectionState==="connected"&&q.readyState==="open"&&x.readyState==="open"&&oe.readyState==="open"}isClosed(){const{peerConnection:A,reliableStreamChannel:x,latestTryOnceStreamChannel:q,latestTtlStreamChannel:oe}=this;return!(A.connectionState!=="closed"||x!==void 0&&x.readyState!=="closed"||q!==void 0&&q.readyState!=="closed"||oe!==void 0&&oe.readyState!=="closed")}needsClosing(){const{peerConnection:A,latestTtlStreamChannel:x,reliableStreamChannel:q,latestTryOnceStreamChannel:oe}=this;if(this.isClosed())return!1;const se=new Set(["closing","closed"]),de=he=>he&&se.has(he.readyState);return Rt(A)||de(x)||de(q)||de(oe)}close(){return nt(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(A){this.latestTtlStreamChannel=A.createDataChannel("stream.latest-ttl",ne),this.reliableStreamChannel=A.createDataChannel("stream.reliable",ie),this.latestReliableStreamChannel=A.createDataChannel("stream.latest-reliable",ce),this.latestTryOnceStreamChannel=A.createDataChannel("stream.latest-try-once",Se),this.setupChannel(this.latestTtlStreamChannel),this.setupChannel(this.reliableStreamChannel),this.setupChannel(this.latestReliableStreamChannel),this.setupChannel(this.latestTryOnceStreamChannel)}sendOffer(){return nt(this,void 0,void 0,function*(){if(this.sentOffer||(this.sentOffer=!0,Rt(this.peerConnection)))return;const{peerConnection:A,config:{sendSignal:x}}=this,q=yield A.createOffer();yield A.setLocalDescription(q);const oe={payload:JSON.stringify({description:q})};yield x(oe)})}getChannelFromLabel(A){switch(A){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(A,x){let q;try{q=Object(H.encode)(JSON.stringify(x))}catch(oe){return void h.a.warn("Failed to encode RTC message",{error:oe})}try{A.send(q),this.sessionMetrics.incrementMessageSent(x)}catch(oe){h.a.warn("Failed to send message to channel",{error:oe,channel:A.label})}}channelNotRecognized(A){return A!==this.latestTtlStreamChannel&&A!==this.latestReliableStreamChannel&&A!==this.latestTryOnceStreamChannel&&A!==this.reliableStreamChannel}setupChannel(A){A.onmessage=x=>{if(this.channelNotRecognized(A))return void h.a.warn("Received message on unrecognized data channel.");let q;try{q=JSON.parse(Object(H.decode)(x.data))}catch(oe){return void h.a.warn("Received unparseable RTC message",{error:oe,channel:A.label})}if(this.lastMessageTimestamp=new Date().getTime(),q=Et(q),this.sessionMetrics.incrementMessageReceived(q),!this.handleSystemMessage(A,q)){if(!this.hasCapabilities(q))return void h.a.warn("Received RTC message that was not within the capability scope of the connection.");(A===this.latestTryOnceStreamChannel||A===this.latestTtlStreamChannel||A===this.latestReliableStreamChannel)&&!this.isLatestMessage(q)||this.config.receive(this.config.remotePeer.id,q)}},A.onerror=x=>{h.a.warn(`Channel error: ${x.error}`,{error:x.error,sessionId:this.getSessionId(),channelLabel:A.label})},A.onopen=()=>{h.a.debug("Channel opened",{sessionId:this.getSessionId(),channelLabel:A.label})},A.onclose=()=>{const x={bufferedAmount:A.bufferedAmount,sessionId:this.getSessionId(),channelLabel:A.label};this.closeCalled===!1?h.a.debug("Unexpected channel closed",x):h.a.debug("Channel closed",x)}}handleSystemMessage(A,x){switch(x.header.stream.streamType){case"ping":return this.sendSystemMessage(A,{type:"pong",timestamp:te(x.payload.ping)}),!0;case"pong":{const q=new Date().getTime()-te(x.payload.pong);return this.pingTimeMs=q,Q.aggregate("rtc-ping-time",q),!0}case"stream-control":return!0;default:return!1}}sendSystemMessage(A,x){if(A.readyState!=="open")return;const q={entityId:te(this.config.localPeer.deviceId||this.config.localPeer.userId),streamName:`$.${x.type}`,streamType:x.type};let oe;switch(x.type){case"ping":oe={ping:new Date().getTime()};break;case"pong":oe={pong:x.timestamp};break;case"stream-control":oe={streamControl:x.streamControl}}this.sendOnChannel(A,et(q,oe))}hasCapabilities(A){var x,q;const{localPeer:oe,remotePeer:se}=this.config,de=(x=oe.capabilitySet.streaming)===null||x===void 0?void 0:x.streams,he=de&&de.some(le=>le.receive&&Ct(le.stream,A.header.stream)),pe=(q=se.capabilitySet.streaming)===null||q===void 0?void 0:q.streams,Ue=pe&&pe.some(le=>le.send&&Ct(le.stream,A.header.stream));return he||Ue}isLatestMessage(A){const x=_e(A.header.stream),q=(this.streamLatestTimestamp.get(x)||0)<=A.header.created;return q&&this.streamLatestTimestamp.set(x,A.header.created),q}}var Oe=function(Re,A,x,q){return new(x||(x=Promise))(function(oe,se){function de(Ue){try{pe(q.next(Ue))}catch(le){se(le)}}function he(Ue){try{pe(q.throw(Ue))}catch(le){se(le)}}function pe(Ue){var le;Ue.done?oe(Ue.value):(le=Ue.value,le instanceof x?le:new x(function(me){me(le)})).then(de,he)}pe((q=q.apply(Re,A||[])).next())})};class Nt{constructor(A){this.config=A,this.connections=[],this.connectingSessions=new Map,this.rtcInstancesConstructed=0,this.updateInterval=F({func:()=>Oe(this,void 0,void 0,function*(){try{yield this.update()}catch(x){h.a.warn("RTC update failed",{error:x})}}),delay:250*d.a.millisecond,immediate:!0}),this.localPeer=this.createPeer()}send(A,x,q){const oe=this.getActiveConnection(A);oe?oe.isReady()?oe.send(x,q):h.a.warn("Attempted to send with an active connection to that peer which was not yet ready."):h.a.warn("Attempted to send with no active connection to that peer.")}controlRemoteStream(A,x){const q=this.getActiveConnection(A);q?q.isReady()?q.controlRemoteStream(x):h.a.warn("Attempted to control remote stream with an active connection to that peer which was not yet ready."):h.a.warn("Attempted to control remote stream with no active connection to that peer.")}connect(A){return Oe(this,void 0,void 0,function*(){const x=yield this.getLocalPeer();if(this.getActiveConnection(A))return void h.a.warn("Attempted to connect to peer with an already active connection.");let q;try{q=yield this.config.signalingClient.createSession(yield this.config.getToken(),{offerPeerId:x.id,answerPeerId:A})}catch(oe){Object(tt.a)(oe,Ft.a,se=>se.statusCode===404),h.a.warn("Attempted to connect to peer that does not exist.")}if(q)for(this.connectingSessions.set(q.id,new Date().getTime()),yield this.connectToSession(q);;)switch(yield Object(u.a)(.1),this.getConnectionStatus(A)){case"connecting":continue;case"connected":return q.id;case"disconnected":return}})}getConnectionStatus(A){const x=this.getActiveConnection(A);return x?x.isReady()?"connected":"connecting":"disconnected"}getIceMode(A){const x=this.getActiveConnection(A);if(x)return x.iceMode}disconnect(A){return Oe(this,void 0,void 0,function*(){const x=this.getActiveConnection(A);x&&(yield this.closeConnection(x))})}getLocalPeer(){return Oe(this,void 0,void 0,function*(){return yield this.localPeer})}getPeers(){return Oe(this,void 0,void 0,function*(){return yield this.config.signalingClient.getPeers(yield this.config.getToken())})}getPing(A){const x=this.getActiveConnection(A);if(x)return x.getPing();h.a.warn("Attempted to get ping time from inactive peer.")}getLastMessageTimestamp(A){const x=this.getActiveConnection(A);if(x)return x.getLastMessageTimestamp();h.a.warn("Attempted to get ping time from inactive peer.")}shutdown(){return Oe(this,void 0,void 0,function*(){yield this.updateInterval.stop();const A=this.connections;this.connections=[],yield this.closeConnections(A)})}closeConnection(A){return Oe(this,void 0,void 0,function*(){this.connectingSessions.delete(A.getSessionId()),yield A.close();try{yield this.config.signalingClient.deleteSession(yield this.config.getToken(),A.getSessionId())}catch(x){Object(tt.a)(x,Ft.a,q=>q.statusCode===404)}})}getSessions(){return Oe(this,void 0,void 0,function*(){const A=yield this.getLocalPeer();return(yield this.config.signalingClient.getSessions(yield this.config.getToken())).filter(x=>x.offer.peer.id===A.id||x.answer.peer.id===A.id)})}createPeer(){return Oe(this,void 0,void 0,function*(){return yield this.config.signalingClient.createPeer(yield this.config.getToken(),{capabilitySet:this.config.capabilitySet||{}})})}createRTCPeerConnection(A={}){return Oe(this,void 0,void 0,function*(){const x=this.config.alternateRTCPeerConnection||RTCPeerConnection;this.rtcInstancesConstructed++,this.rtcInstancesConstructed%20||kt();try{return new x(Object.assign({iceServers:yield this.config.signalingClient.getIceServers(yield this.config.getToken())},A))}catch(q){throw h.a.debug(`Failed to create RTCPeerConnection: ${this.rtcInstancesConstructed} total allocated`),q}})}closeConnections(A){return Oe(this,void 0,void 0,function*(){const x=yield G(A.map(q=>Oe(this,void 0,void 0,function*(){yield this.closeConnection(q)})));for(const q of x)h.a.warn("Request to close session failed",{error:q})})}reset(){return Oe(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(A){return this.connections.find(x=>x.getRemotePeer().id===A&&x.isActive())}update(){return Oe(this,void 0,void 0,function*(){const A=yield this.getLocalPeer();try{yield this.config.signalingClient.refreshPeer(yield this.config.getToken(),A.id)}catch(x){Object(tt.a)(x,Ft.a,q=>q.statusCode===404),h.a.warn("Peer expired, creating new peer",{peerId:A.id}),yield this.reset()}yield this.handleSessions(yield this.getSessions())})}handleSessions(A){return Oe(this,void 0,void 0,function*(){yield this.syncConnectionsAndSessions(A);const x=A.map(q=>({session:q,connection:this.connections.find(oe=>oe.getSessionId()===q.id)}));yield Promise.all(x.map(({session:q,connection:oe})=>Oe(this,void 0,void 0,function*(){return yield this.maintainConnection(q,oe)})))})}syncConnectionsAndSessions(A){return Oe(this,void 0,void 0,function*(){const x=new Set(A.map(se=>se.id)),q=se=>x.has(se.getSessionId())||this.connectingSessions.has(se.getSessionId());this.connections=this.connections.filter(se=>q(se));const oe=this.connections.filter(se=>!q(se)||se.needsClosing());yield Promise.all(oe.map(se=>Oe(this,void 0,void 0,function*(){yield this.closeConnection(se)})))})}maintainConnection(A,x){return Oe(this,void 0,void 0,function*(){const q=yield this.getLocalPeer(),oe=A.offer.peer.id===q.id;if(x){if(x.isReady())try{yield this.config.signalingClient.refreshSession(yield this.config.getToken(),A.id)}catch(se){Object(tt.a)(se,Ft.a,de=>de.statusCode===404),h.a.debug("Refresh session not found",{sessionId:A.id})}else if(x.isActive())try{yield this.consumeSignals(x)}catch(se){h.a.warn("Failed to ingest signals, closing connection",{error:se}),yield this.closeConnection(x)}}else{if(oe)return;yield this.connectToSession(A)}})}connectToSession(A){return Oe(this,void 0,void 0,function*(){const x=yield this.getLocalPeer(),q=A.offer.peer.id===x.id,oe=yield this.createRTCPeerConnection(),se=new St(oe,{localPeer:q?A.offer.peer:A.answer.peer,remotePeer:q?A.answer.peer:A.offer.peer,sessionId:A.id,isOffer:q,sendSignal:de=>this.sendSignal(A.id,de),receive:(de,he)=>this.config.receive(de,he)});if(this.connections.find(de=>de.getSessionId()===A.id))return h.a.warn("connectToSession called on a session that already has a connection.",{sessionId:A.id}),void(yield se.close());this.setupHandlers(se),this.connections.push(se);try{yield se.connect()}catch(de){h.a.warn("Failed to handle negotiation, closing connection",{error:de}),yield this.closeConnection(se)}})}setupHandlers(A){const{peerConnection:x}=A,q=A.getSessionId();x.onconnectionstatechange=()=>Oe(this,void 0,void 0,function*(){const oe=this.connectingSessions.get(q);if(oe===void 0)return;const se=x.connectionState;switch(Rt(x)&&this.connectingSessions.delete(q),se){case"connected":{this.connectingSessions.delete(q);const de=new Date().getTime()-oe;Q.aggregate("rtc-connect-time",de);break}case"failed":Q.increment("rtc-connect-failed"),yield this.closeConnection(A)}})}consumeSignals(A){return Oe(this,void 0,void 0,function*(){let x=[];try{x=yield this.config.signalingClient.takeSignals(yield this.config.getToken(),A.getSessionId())}catch(q){Object(tt.a)(q,Ft.a,oe=>oe.statusCode===404)}for(const q of x)yield A.handleSignal(q)})}sendSignal(A,x){return Oe(this,void 0,void 0,function*(){try{yield this.config.signalingClient.addSignals(yield this.config.getToken(),A,{signals:[x]})}catch(q){Object(tt.a)(q,Ft.a,oe=>oe.statusCode===404)}})}}},function(e,t,n){var r={randomUUID:typeof crypto!="undefined"&&crypto.randomUUID&&crypto.randomUUID.bind(crypto)};let l;const s=new Uint8Array(16);function c(){if(!l&&(l=typeof crypto!="undefined"&&crypto.getRandomValues&&crypto.getRandomValues.bind(crypto),!l))throw new Error("crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported");return l(s)}const o=[];for(let u=0;u<256;++u)o.push((u+256).toString(16).slice(1));function d(u,U=0){return(o[u[U+0]]+o[u[U+1]]+o[u[U+2]]+o[u[U+3]]+"-"+o[u[U+4]]+o[u[U+5]]+"-"+o[u[U+6]]+o[u[U+7]]+"-"+o[u[U+8]]+o[u[U+9]]+"-"+o[u[U+10]]+o[u[U+11]]+o[u[U+12]]+o[u[U+13]]+o[u[U+14]]+o[u[U+15]]).toLowerCase()}t.a=function(u,U,B){if(r.randomUUID&&!U&&!u)return r.randomUUID();const R=(u=u||{}).random||(u.rng||c)();if(R[6]=15&R[6]|64,R[8]=63&R[8]|128,U){B=B||0;for(let p=0;p<16;++p)U[B+p]=R[p];return U}return d(R)}},,function(e,t,n){n.r(t),n.d(t,"LogClient",function(){return o});var r=n(26),l=n(12),s=n(11),c=function(d,u,U,B){return new(U||(U=Promise))(function(R,p){function g(N){try{m(B.next(N))}catch(D){p(D)}}function h(N){try{m(B.throw(N))}catch(D){p(D)}}function m(N){var D;N.done?R(N.value):(D=N.value,D instanceof U?D:new U(function(y){y(D)})).then(g,h)}m((B=B.apply(d,u||[])).next())})};class o extends r.a{log(u){return c(this,void 0,void 0,function*(){const U=o.token;try{yield this.fetch("logs",{token:U,method:"POST",body:{logs:u},allowUnsafeRetries:!0})}catch(B){Object(l.a)(B,s.a,R=>R.statusCode===401&&U!==void 0),o.token===U&&delete o.token,yield this.log(u)}})}}}])})})(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");var Sn;class RtcClientPool{constructor(t){Fe(this,Sn,null);Fe(this,"createClient");Fe(this,"ttlMs");Fe(this,"proxyHandler");Fe(this,"proxyReceivers",new Map);Fe(this,"teardownTimeout",null);Fe(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:(l,s,c)=>{switch(s){case"shutdown":return()=>this.releaseInstance(c);default:return Reflect.get(l,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)}}Sn=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(FORMANT_API_URL),getToken,sessionType:SessionTypes.UNKNOWN,receive:e})}),[SessionTypes.TELEOP]:new RtcClientPool({ttlMs:2500,createClient:e=>new distExports.RtcClient({signalingClient:new distExports.SignalingPromiseClient(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(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(FORMANT_API_URL),getToken,sessionType:SessionTypes.OBSERVE,receive:e})}),[SessionTypes.HEADLESS]:new RtcClientPool({ttlMs:2500,createClient:e=>new distExports.RtcClient({signalingClient:new distExports.SignalingPromiseClient(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};class CaptureStream{constructor(t){Fe(this,"token");this.captureSession=t}async ingestJSON(t){if(!this.token){const r=await(await fetch(`${FORMANT_API_URL}/v1/admin/capture-sessions/${this.captureSession.code}/authenticate`,{method:"POST"})).json();this.token=r.token}await fetch(`${FORMANT_API_URL}/v1/ingest`,{method:"POST",body:JSON.stringify({deviceId:this.captureSession.deviceId,name:this.captureSession.streamName,type:"json",points:[[Date.now(),JSON.stringify(t)]]}),headers:{"Content-Type":"application/json",Authorization:"Bearer "+this.token}})}}function delay(e){return new Promise(t=>setTimeout(t,e))}const isRtcPeer=e=>e!==void 0&&e.capabilities!==void 0&&e.capabilitySet!==void 0;class DataChannel{constructor(t){Fe(this,"ready",!1);Fe(this,"listeners",[]);Fe(this,"openListeners",[]);Fe(this,"closeListeners",[]);Fe(this,"errorListeners",[]);Fe(this,"binaryListeners",[]);Fe(this,"error");Fe(this,"decoder",new TextDecoder);this.dataChannel=t,this.dataChannel.binaryType="arraybuffer",this.dataChannel.onopen=()=>{this.setReady()},this.dataChannel.onclose=()=>{this.ready=!1,this.closeListeners.forEach(n=>n())},this.dataChannel.onerror=n=>{console.error(n),this.error="An error occurred in DataChannel",this.errorListeners.forEach(r=>r(n))},this.dataChannel.onmessage=n=>{this.listeners.forEach(r=>{const l=new Uint8Array(n.data),s=this.decoder.decode(l);r(s)}),this.binaryListeners.forEach(r=>{r(new Uint8Array(n.data))})}}setReady(){this.ready=!0,this.openListeners.forEach(t=>t())}addOpenListener(t){this.openListeners.push(t)}removeOpenListener(t){this.openListeners=this.openListeners.filter(n=>n!==t)}addCloseListener(t){this.closeListeners.push(t)}removeCloseListener(t){this.closeListeners=this.closeListeners.filter(n=>n!==t)}addErrorListener(t){this.errorListeners.push(t)}removeErrorListener(t){this.errorListeners=this.errorListeners.filter(n=>n!==t)}async waitTilReady(){return this.ready?!0:new Promise((n,r)=>{let l=setInterval(()=>{this.dataChannel.readyState==="open"&&this.setReady(),this.ready&&(clearInterval(l),n(!0)),this.error&&r(this.error)},10)})}send(t){if(!this.ready)throw new Error("Connection has been closed");this.dataChannel.send(t)}sendBinary(t){if(!this.ready)throw new Error("Connection has been closed");this.dataChannel.send(t)}addListener(t){this.listeners.push(t)}removeListener(t){const n=this.listeners.indexOf(t);if(n===-1)throw new Error("Could not find data channel listener to remove");if(this.error)throw new Error(this.error);this.listeners.splice(n,1)}addBinaryListener(t){this.binaryListeners.push(t)}removeBinaryListener(t){const n=this.binaryListeners.indexOf(t);if(n===-1)throw new Error("Could not find data channel listener to remove");if(this.error)throw new Error(this.error);this.binaryListeners.splice(n,1)}}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 l(d,u,U){this.fn=d,this.context=u,this.once=U||!1}function s(d,u,U,B,R){if(typeof U!="function")throw new TypeError("The listener must be a function");var p=new l(U,B||d,R),g=n?n+u:u;return d._events[g]?d._events[g].fn?d._events[g]=[d._events[g],p]:d._events[g].push(p):(d._events[g]=p,d._eventsCount++),d}function c(d,u){--d._eventsCount===0?d._events=new r:delete d._events[u]}function o(){this._events=new r,this._eventsCount=0}o.prototype.eventNames=function(){var u=[],U,B;if(this._eventsCount===0)return u;for(B in U=this._events)t.call(U,B)&&u.push(n?B.slice(1):B);return Object.getOwnPropertySymbols?u.concat(Object.getOwnPropertySymbols(U)):u},o.prototype.listeners=function(u){var U=n?n+u:u,B=this._events[U];if(!B)return[];if(B.fn)return[B.fn];for(var R=0,p=B.length,g=new Array(p);R<p;R++)g[R]=B[R].fn;return g},o.prototype.listenerCount=function(u){var U=n?n+u:u,B=this._events[U];return B?B.fn?1:B.length:0},o.prototype.emit=function(u,U,B,R,p,g){var h=n?n+u:u;if(!this._events[h])return!1;var m=this._events[h],N=arguments.length,D,y;if(m.fn){switch(m.once&&this.removeListener(u,m.fn,void 0,!0),N){case 1:return m.fn.call(m.context),!0;case 2:return m.fn.call(m.context,U),!0;case 3:return m.fn.call(m.context,U,B),!0;case 4:return m.fn.call(m.context,U,B,R),!0;case 5:return m.fn.call(m.context,U,B,R,p),!0;case 6:return m.fn.call(m.context,U,B,R,p,g),!0}for(y=1,D=new Array(N-1);y<N;y++)D[y-1]=arguments[y];m.fn.apply(m.context,D)}else{var b=m.length,F;for(y=0;y<b;y++)switch(m[y].once&&this.removeListener(u,m[y].fn,void 0,!0),N){case 1:m[y].fn.call(m[y].context);break;case 2:m[y].fn.call(m[y].context,U);break;case 3:m[y].fn.call(m[y].context,U,B);break;case 4:m[y].fn.call(m[y].context,U,B,R);break;default:if(!D)for(F=1,D=new Array(N-1);F<N;F++)D[F-1]=arguments[F];m[y].fn.apply(m[y].context,D)}}return!0},o.prototype.on=function(u,U,B){return s(this,u,U,B,!1)},o.prototype.once=function(u,U,B){return s(this,u,U,B,!0)},o.prototype.removeListener=function(u,U,B,R){var p=n?n+u:u;if(!this._events[p])return this;if(!U)return c(this,p),this;var g=this._events[p];if(g.fn)g.fn===U&&(!R||g.once)&&(!B||g.context===B)&&c(this,p);else{for(var h=0,m=[],N=g.length;h<N;h++)(g[h].fn!==U||R&&!g[h].once||B&&g[h].context!==B)&&m.push(g[h]);m.length?this._events[p]=m.length===1?m[0]:m:c(this,p)}return this},o.prototype.removeAllListeners=function(u){var U;return u?(U=n?n+u:u,this._events[U]&&c(this,U)):(this._events=new r,this._eventsCount=0),this},o.prototype.off=o.prototype.removeListener,o.prototype.addListener=o.prototype.on,o.prefixed=n,o.EventEmitter=o,e.exports=o})(eventemitter3);var eventemitter3Exports=eventemitter3.exports;const EventEmitter=getDefaultExportFromCjs(eventemitter3Exports);class Manipulator{constructor(t,n){Fe(this,"currentListeners",[]);Fe(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){Fe(this,"channel");Fe(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);Fe(this,"RESPONSE_SUCCESS_BYTE",0);Fe(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 l=n.slice(0,16).toString();if(l.length===0)throw new Error("Invalid response");const s=n.slice(16);if(s.length===0)throw new Error("Invalid response");this.requestIdToResponseMap.has(l)&&this.requestIdToResponseMap.set(l,s)})}async request(n){if(this.channel||await this.initialize(),!this.channel)throw new Error("Failed to create channel");const{channel:r,requestIdToResponseMap:l,timeout:s}=this;await r.waitTilReady();const c=this.generateBinaryId(),o=c.toString();l.set(o,!0),r.sendBinary(new Uint8Array([...c,...n]));const d=new Date().getTime();for(;new Date().getTime()<d+s;)if(await delay(50),l.has(o)){const u=l.get(o);if(u!==!0){l.delete(o);const U=u[0]===this.RESPONSE_SUCCESS_BYTE,B=u.slice(1);if(U)return B;throw console.error({name:"AdapterError",message:this.decoder.decode(B)}),new Error("Binary request datachannel adapter error")}}throw l.delete(o),console.error({name:"TimeoutError",message:`Request timed out after ${s/1e3} seconds`}),new Error("Binary request data channel request timed out")}}class TextRequestDataChannel extends RequestDataChannel{generateTextId(){return Math.random().toString(36).substring(2)+"-"+Math.random().toString(36).substring(2)}async initialize(){this.channel=await this.device.createCustomDataChannel(this.channel_name),this.channel.addListener(t=>{const n=JSON.parse(t),{id:r,data:l,error:s}=n;if(!r)throw new Error("Invalid response");if(!l&&!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:l}=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+l;)if(await delay(50),r.has(s)){const o=r.get(s);if(o!==!0){r.delete(s);const{data:d,error:u}=o;if(d)return d;if(u)throw console.error({name:"AdapterError",message:u}),new Error("Text request datachannel adapter error")}}throw r.delete(s),console.error({name:"TimeoutError",message:`Request timed out after ${l/1e3} seconds`}),new Error("Text request datachannel request timed out")}}class BaseDevice extends EventEmitter{constructor(){super(...arguments);Fe(this,"rtcClient");Fe(this,"remoteDevicePeerId",null);Fe(this,"realtimeListeners",[]);Fe(this,"connectionMonitorInterval");Fe(this,"handleMessage",(n,r)=>{this.realtimeListeners.forEach(l=>l(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")}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 l;const n=await this.getConfiguration(),r=[];for(const s of(l=n.teleop.rosStreams)!=null?l:[])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 l,s,c,o,d,u;const n=await this.getConfiguration(),r=[];for(const U of(s=(l=n.teleop)==null?void 0:l.hardwareStreams)!=null?s:[])U.rtcStreamType==="h264-video-frame"&&r.push({name:U.name});for(const U of(o=(c=n.teleop)==null?void 0:c.rosStreams)!=null?o:[])U.topicType=="formant/H264VideoFrame"&&r.push({name:U.topicName}),(U.topicType==="sensor_msgs/Image"||U.topicType==="sensor_msgs/CompressedImage")&&U.encodeVideo&&r.push({name:U.topicName});for(const U of(u=(d=n.teleop)==null?void 0:d.customStreams)!=null?u:[])U.rtcStreamType==="h264-video-frame"&&r.push({name:U.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"),l=await this.getRemotePeer();r.controlRemoteStream(defined$1(l).id,{streamName:n.name,enable:!0,pipeline:"rtc"})}async stopListeningToRealtimeVideo(n){const r=defined$1(this.rtcClient,"Realtime connection has not been started"),l=await this.getRemotePeer();r.controlRemoteStream(defined$1(l).id,{streamName:n.name,enable:!1,pipeline:"rtc"})}async startListeningToRealtimeDataStream(n){const r=defined$1(this.rtcClient,"Realtime connection has not been started"),l=await this.getRemotePeer();r.controlRemoteStream(defined$1(l).id,{streamName:n.name,enable:!0,pipeline:"rtc"})}async stopListeningToRealtimeDataStream(n){const r=defined$1(this.rtcClient,"Realtime connection has not been started"),l=await this.getRemotePeer();r.controlRemoteStream(defined$1(l).id,{streamName:n.name,enable:!1,pipeline:"rtc"})}async enableRealtimeTelemetryPriorityIngestion(n){const r=defined$1(this.rtcClient,"Realtime connection has not been started"),l=await this.getRemotePeer();r.controlRemoteStream(defined$1(l).id,{streamName:n,enablePriorityUpload:!0,pipeline:"telemetry"})}async disableRealtimeTelemetryPriorityIngestion(n){const r=defined$1(this.rtcClient,"Realtime connection has not been started"),l=await this.getRemotePeer();r.controlRemoteStream(defined$1(l).id,{streamName:n,enablePriorityUpload:!1,pipeline:"telemetry"})}async changeStreamAudioType(n,r){const l=defined$1(this.rtcClient,"Realtime connection has not been started"),s=await this.getRemotePeer();l.controlRemoteStream(defined$1(s).id,{streamName:n,setAudioFormat:r})}async createCustomDataChannel(n,r){const l=defined$1(this.rtcClient,"Realtime connection has not been started"),s=await this.getRemotePeer(),c=await new Promise(o=>{l.createCustomDataChannel(defined$1(s).id,n,{ordered:!0,...r},!1,(d,u)=>{const U=new DataChannel(u);o(U)})});return await c.waitTilReady(),c}async sendRealtimeMessage(n,r={channelLabel:"stream.reliable"}){const l=defined$1(this.rtcClient,"Realtime connection has not been started"),s=await this.getRemotePeer();l.send(defined$1(s).id,n,r)}async getRealtimeAudioStreams(){var l,s,c,o,d,u;const n=await this.getConfiguration(),r=[];for(const U of(s=(l=n.teleop)==null?void 0:l.hardwareStreams)!=null?s:[])U.rtcStreamType==="audio-chunk"&&r.push({name:U.name});for(const U of(o=(c=n.teleop)==null?void 0:c.rosStreams)!=null?o:[])U.topicType=="audio_common_msgs/AudioData"&&r.push({name:U.topicName});for(const U of(u=(d=n.teleop)==null?void 0:d.customStreams)!=null?u:[])U.rtcStreamType==="audio-chunk"&&r.push({name:U.name});return r}}/*! pako 2.1.0 https://github.com/nodeca/pako @license (MIT AND Zlib) */const Z_FIXED$1=4,Z_BINARY=0,Z_TEXT=1,Z_UNKNOWN$1=2;function zero$1(e){let t=e.length;for(;--t>=0;)e[t]=0}const STORED_BLOCK=0,STATIC_TREES=1,DYN_TREES=2,MIN_MATCH$1=3,MAX_MATCH$1=258,LENGTH_CODES$1=29,LITERALS$1=256,L_CODES$1=LITERALS$1+1+LENGTH_CODES$1,D_CODES$1=30,BL_CODES$1=19,HEAP_SIZE$1=2*L_CODES$1+1,MAX_BITS$1=15,Buf_size=16,MAX_BL_BITS=7,END_BLOCK=256,REP_3_6=16,REPZ_3_10=17,REPZ_11_138=18,extra_lbits=new Uint8Array([0,0,0,0,0,0,0,0,1,1,1,1,2,2,2,2,3,3,3,3,4,4,4,4,5,5,5,5,0]),extra_dbits=new Uint8Array([0,0,0,0,1,1,2,2,3,3,4,4,5,5,6,6,7,7,8,8,9,9,10,10,11,11,12,12,13,13]),extra_blbits=new Uint8Array([0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,2,3,7]),bl_order=new Uint8Array([16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15]),DIST_CODE_LEN=512,static_ltree=new Array((L_CODES$1+2)*2);zero$1(static_ltree);const static_dtree=new Array(D_CODES$1*2);zero$1(static_dtree);const _dist_code=new Array(DIST_CODE_LEN);zero$1(_dist_code);const _length_code=new Array(MAX_MATCH$1-MIN_MATCH$1+1);zero$1(_length_code);const base_length=new Array(LENGTH_CODES$1);zero$1(base_length);const base_dist=new Array(D_CODES$1);zero$1(base_dist);function StaticTreeDesc(e,t,n,r,l){this.static_tree=e,this.extra_bits=t,this.extra_base=n,this.elems=r,this.max_length=l,this.has_stree=e&&e.length}let static_l_desc,static_d_desc,static_bl_desc;function TreeDesc(e,t){this.dyn_tree=e,this.max_code=0,this.stat_desc=t}const d_code=e=>e<256?_dist_code[e]:_dist_code[256+(e>>>7)],put_short=(e,t)=>{e.pending_buf[e.pending++]=t&255,e.pending_buf[e.pending++]=t>>>8&255},send_bits=(e,t,n)=>{e.bi_valid>Buf_size-n?(e.bi_buf|=t<<e.bi_valid&65535,put_short(e,e.bi_buf),e.bi_buf=t>>Buf_size-e.bi_valid,e.bi_valid+=n-Buf_size):(e.bi_buf|=t<<e.bi_valid&65535,e.bi_valid+=n)},send_code=(e,t,n)=>{send_bits(e,n[t*2],n[t*2+1])},bi_reverse=(e,t)=>{let n=0;do n|=e&1,e>>>=1,n<<=1;while(--t>0);return n>>>1},bi_flush=e=>{e.bi_valid===16?(put_short(e,e.bi_buf),e.bi_buf=0,e.bi_valid=0):e.bi_valid>=8&&(e.pending_buf[e.pending++]=e.bi_buf&255,e.bi_buf>>=8,e.bi_valid-=8)},gen_bitlen=(e,t)=>{const n=t.dyn_tree,r=t.max_code,l=t.stat_desc.static_tree,s=t.stat_desc.has_stree,c=t.stat_desc.extra_bits,o=t.stat_desc.extra_base,d=t.stat_desc.max_length;let u,U,B,R,p,g,h=0;for(R=0;R<=MAX_BITS$1;R++)e.bl_count[R]=0;for(n[e.heap[e.heap_max]*2+1]=0,u=e.heap_max+1;u<HEAP_SIZE$1;u++)U=e.heap[u],R=n[n[U*2+1]*2+1]+1,R>d&&(R=d,h++),n[U*2+1]=R,!(U>r)&&(e.bl_count[R]++,p=0,U>=o&&(p=c[U-o]),g=n[U*2],e.opt_len+=g*(R+p),s&&(e.static_len+=g*(l[U*2+1]+p)));if(h!==0){do{for(R=d-1;e.bl_count[R]===0;)R--;e.bl_count[R]--,e.bl_count[R+1]+=2,e.bl_count[d]--,h-=2}while(h>0);for(R=d;R!==0;R--)for(U=e.bl_count[R];U!==0;)B=e.heap[--u],!(B>r)&&(n[B*2+1]!==R&&(e.opt_len+=(R-n[B*2+1])*n[B*2],n[B*2+1]=R),U--)}},gen_codes=(e,t,n)=>{const r=new Array(MAX_BITS$1+1);let l=0,s,c;for(s=1;s<=MAX_BITS$1;s++)l=l+n[s-1]<<1,r[s]=l;for(c=0;c<=t;c++){let o=e[c*2+1];o!==0&&(e[c*2]=bi_reverse(r[o]++,o))}},tr_static_init=()=>{let e,t,n,r,l;const s=new Array(MAX_BITS$1+1);for(n=0,r=0;r<LENGTH_CODES$1-1;r++)for(base_length[r]=n,e=0;e<1<<extra_lbits[r];e++)_length_code[n++]=r;for(_length_code[n-1]=r,l=0,r=0;r<16;r++)for(base_dist[r]=l,e=0;e<1<<extra_dbits[r];e++)_dist_code[l++]=r;for(l>>=7;r<D_CODES$1;r++)for(base_dist[r]=l<<7,e=0;e<1<<extra_dbits[r]-7;e++)_dist_code[256+l++]=r;for(t=0;t<=MAX_BITS$1;t++)s[t]=0;for(e=0;e<=143;)static_ltree[e*2+1]=8,e++,s[8]++;for(;e<=255;)static_ltree[e*2+1]=9,e++,s[9]++;for(;e<=279;)static_ltree[e*2+1]=7,e++,s[7]++;for(;e<=287;)static_ltree[e*2+1]=8,e++,s[8]++;for(gen_codes(static_ltree,L_CODES$1+1,s),e=0;e<D_CODES$1;e++)static_dtree[e*2+1]=5,static_dtree[e*2]=bi_reverse(e,5);static_l_desc=new StaticTreeDesc(static_ltree,extra_lbits,LITERALS$1+1,L_CODES$1,MAX_BITS$1),static_d_desc=new StaticTreeDesc(static_dtree,extra_dbits,0,D_CODES$1,MAX_BITS$1),static_bl_desc=new StaticTreeDesc(new Array(0),extra_blbits,0,BL_CODES$1,MAX_BL_BITS)},init_block=e=>{let t;for(t=0;t<L_CODES$1;t++)e.dyn_ltree[t*2]=0;for(t=0;t<D_CODES$1;t++)e.dyn_dtree[t*2]=0;for(t=0;t<BL_CODES$1;t++)e.bl_tree[t*2]=0;e.dyn_ltree[END_BLOCK*2]=1,e.opt_len=e.static_len=0,e.sym_next=e.matches=0},bi_windup=e=>{e.bi_valid>8?put_short(e,e.bi_buf):e.bi_valid>0&&(e.pending_buf[e.pending++]=e.bi_buf),e.bi_buf=0,e.bi_valid=0},smaller=(e,t,n,r)=>{const l=t*2,s=n*2;return e[l]<e[s]||e[l]===e[s]&&r[t]<=r[n]},pqdownheap=(e,t,n)=>{const r=e.heap[n];let l=n<<1;for(;l<=e.heap_len&&(l<e.heap_len&&smaller(t,e.heap[l+1],e.heap[l],e.depth)&&l++,!smaller(t,r,e.heap[l],e.depth));)e.heap[n]=e.heap[l],n=l,l<<=1;e.heap[n]=r},compress_block=(e,t,n)=>{let r,l,s=0,c,o;if(e.sym_next!==0)do r=e.pending_buf[e.sym_buf+s++]&255,r+=(e.pending_buf[e.sym_buf+s++]&255)<<8,l=e.pending_buf[e.sym_buf+s++],r===0?send_code(e,l,t):(c=_length_code[l],send_code(e,c+LITERALS$1+1,t),o=extra_lbits[c],o!==0&&(l-=base_length[c],send_bits(e,l,o)),r--,c=d_code(r),send_code(e,c,n),o=extra_dbits[c],o!==0&&(r-=base_dist[c],send_bits(e,r,o)));while(s<e.sym_next);send_code(e,END_BLOCK,t)},build_tree=(e,t)=>{const n=t.dyn_tree,r=t.stat_desc.static_tree,l=t.stat_desc.has_stree,s=t.stat_desc.elems;let c,o,d=-1,u;for(e.heap_len=0,e.heap_max=HEAP_SIZE$1,c=0;c<s;c++)n[c*2]!==0?(e.heap[++e.heap_len]=d=c,e.depth[c]=0):n[c*2+1]=0;for(;e.heap_len<2;)u=e.heap[++e.heap_len]=d<2?++d:0,n[u*2]=1,e.depth[u]=0,e.opt_len--,l&&(e.static_len-=r[u*2+1]);for(t.max_code=d,c=e.heap_len>>1;c>=1;c--)pqdownheap(e,n,c);u=s;do c=e.heap[1],e.heap[1]=e.heap[e.heap_len--],pqdownheap(e,n,1),o=e.heap[1],e.heap[--e.heap_max]=c,e.heap[--e.heap_max]=o,n[u*2]=n[c*2]+n[o*2],e.depth[u]=(e.depth[c]>=e.depth[o]?e.depth[c]:e.depth[o])+1,n[c*2+1]=n[o*2+1]=u,e.heap[1]=u++,pqdownheap(e,n,1);while(e.heap_len>=2);e.heap[--e.heap_max]=e.heap[1],gen_bitlen(e,t),gen_codes(n,d,e.bl_count)},scan_tree=(e,t,n)=>{let r,l=-1,s,c=t[0*2+1],o=0,d=7,u=4;for(c===0&&(d=138,u=3),t[(n+1)*2+1]=65535,r=0;r<=n;r++)s=c,c=t[(r+1)*2+1],!(++o<d&&s===c)&&(o<u?e.bl_tree[s*2]+=o:s!==0?(s!==l&&e.bl_tree[s*2]++,e.bl_tree[REP_3_6*2]++):o<=10?e.bl_tree[REPZ_3_10*2]++:e.bl_tree[REPZ_11_138*2]++,o=0,l=s,c===0?(d=138,u=3):s===c?(d=6,u=3):(d=7,u=4))},send_tree=(e,t,n)=>{let r,l=-1,s,c=t[0*2+1],o=0,d=7,u=4;for(c===0&&(d=138,u=3),r=0;r<=n;r++)if(s=c,c=t[(r+1)*2+1],!(++o<d&&s===c)){if(o<u)do send_code(e,s,e.bl_tree);while(--o!==0);else s!==0?(s!==l&&(send_code(e,s,e.bl_tree),o--),send_code(e,REP_3_6,e.bl_tree),send_bits(e,o-3,2)):o<=10?(send_code(e,REPZ_3_10,e.bl_tree),send_bits(e,o-3,3)):(send_code(e,REPZ_11_138,e.bl_tree),send_bits(e,o-11,7));o=0,l=s,c===0?(d=138,u=3):s===c?(d=6,u=3):(d=7,u=4)}},build_bl_tree=e=>{let t;for(scan_tree(e,e.dyn_ltree,e.l_desc.max_code),scan_tree(e,e.dyn_dtree,e.d_desc.max_code),build_tree(e,e.bl_desc),t=BL_CODES$1-1;t>=3&&e.bl_tree[bl_order[t]*2+1]===0;t--);return e.opt_len+=3*(t+1)+5+5+4,t},send_all_trees=(e,t,n,r)=>{let l;for(send_bits(e,t-257,5),send_bits(e,n-1,5),send_bits(e,r-4,4),l=0;l<r;l++)send_bits(e,e.bl_tree[bl_order[l]*2+1],3);send_tree(e,e.dyn_ltree,t-1),send_tree(e,e.dyn_dtree,n-1)},detect_data_type=e=>{let t=4093624447,n;for(n=0;n<=31;n++,t>>>=1)if(t&1&&e.dyn_ltree[n*2]!==0)return Z_BINARY;if(e.dyn_ltree[9*2]!==0||e.dyn_ltree[10*2]!==0||e.dyn_ltree[13*2]!==0)return Z_TEXT;for(n=32;n<LITERALS$1;n++)if(e.dyn_ltree[n*2]!==0)return Z_TEXT;return Z_BINARY};let static_init_done=!1;const _tr_init$1=e=>{static_init_done||(tr_static_init(),static_init_done=!0),e.l_desc=new TreeDesc(e.dyn_ltree,static_l_desc),e.d_desc=new TreeDesc(e.dyn_dtree,static_d_desc),e.bl_desc=new TreeDesc(e.bl_tree,static_bl_desc),e.bi_buf=0,e.bi_valid=0,init_block(e)},_tr_stored_block$1=(e,t,n,r)=>{send_bits(e,(STORED_BLOCK<<1)+(r?1:0),3),bi_windup(e),put_short(e,n),put_short(e,~n),n&&e.pending_buf.set(e.window.subarray(t,t+n),e.pending),e.pending+=n},_tr_align$1=e=>{send_bits(e,STATIC_TREES<<1,3),send_code(e,END_BLOCK,static_ltree),bi_flush(e)},_tr_flush_block$1=(e,t,n,r)=>{let l,s,c=0;e.level>0?(e.strm.data_type===Z_UNKNOWN$1&&(e.strm.data_type=detect_data_type(e)),build_tree(e,e.l_desc),build_tree(e,e.d_desc),c=build_bl_tree(e),l=e.opt_len+3+7>>>3,s=e.static_len+3+7>>>3,s<=l&&(l=s)):l=s=n+5,n+4<=l&&t!==-1?_tr_stored_block$1(e,t,n,r):e.strategy===Z_FIXED$1||s===l?(send_bits(e,(STATIC_TREES<<1)+(r?1:0),3),compress_block(e,static_ltree,static_dtree)):(send_bits(e,(DYN_TREES<<1)+(r?1:0),3),send_all_trees(e,e.l_desc.max_code+1,e.d_desc.max_code+1,c+1),compress_block(e,e.dyn_ltree,e.dyn_dtree)),init_block(e),r&&bi_windup(e)},_tr_tally$1=(e,t,n)=>(e.pending_buf[e.sym_buf+e.sym_next++]=t,e.pending_buf[e.sym_buf+e.sym_next++]=t>>8,e.pending_buf[e.sym_buf+e.sym_next++]=n,t===0?e.dyn_ltree[n*2]++:(e.matches++,t--,e.dyn_ltree[(_length_code[n]+LITERALS$1+1)*2]++,e.dyn_dtree[d_code(t)*2]++),e.sym_next===e.sym_end);var _tr_init_1=_tr_init$1,_tr_stored_block_1=_tr_stored_block$1,_tr_flush_block_1=_tr_flush_block$1,_tr_tally_1=_tr_tally$1,_tr_align_1=_tr_align$1,trees={_tr_init:_tr_init_1,_tr_stored_block:_tr_stored_block_1,_tr_flush_block:_tr_flush_block_1,_tr_tally:_tr_tally_1,_tr_align:_tr_align_1};const adler32=(e,t,n,r)=>{let l=e&65535|0,s=e>>>16&65535|0,c=0;for(;n!==0;){c=n>2e3?2e3:n,n-=c;do l=l+t[r++]|0,s=s+l|0;while(--c);l%=65521,s%=65521}return l|s<<16|0};var adler32_1=adler32;const makeTable=()=>{let e,t=[];for(var n=0;n<256;n++){e=n;for(var r=0;r<8;r++)e=e&1?3988292384^e>>>1:e>>>1;t[n]=e}return t},crcTable=new Uint32Array(makeTable()),crc32=(e,t,n,r)=>{const l=crcTable,s=r+n;e^=-1;for(let c=r;c<s;c++)e=e>>>8^l[(e^t[c])&255];return e^-1};var crc32_1=crc32,messages={2:"need dictionary",1:"stream end",0:"","-1":"file error","-2":"stream error","-3":"data error","-4":"insufficient memory","-5":"buffer error","-6":"incompatible version"},constants$2={Z_NO_FLUSH:0,Z_PARTIAL_FLUSH:1,Z_SYNC_FLUSH:2,Z_FULL_FLUSH:3,Z_FINISH:4,Z_BLOCK:5,Z_TREES:6,Z_OK:0,Z_STREAM_END:1,Z_NEED_DICT:2,Z_ERRNO:-1,Z_STREAM_ERROR:-2,Z_DATA_ERROR:-3,Z_MEM_ERROR:-4,Z_BUF_ERROR:-5,Z_NO_COMPRESSION:0,Z_BEST_SPEED:1,Z_BEST_COMPRESSION:9,Z_DEFAULT_COMPRESSION:-1,Z_FILTERED:1,Z_HUFFMAN_ONLY:2,Z_RLE:3,Z_FIXED:4,Z_DEFAULT_STRATEGY:0,Z_BINARY:0,Z_TEXT:1,Z_UNKNOWN:2,Z_DEFLATED:8};const{_tr_init,_tr_stored_block,_tr_flush_block,_tr_tally,_tr_align}=trees,{Z_NO_FLUSH:Z_NO_FLUSH$2,Z_PARTIAL_FLUSH,Z_FULL_FLUSH:Z_FULL_FLUSH$1,Z_FINISH:Z_FINISH$3,Z_BLOCK:Z_BLOCK$1,Z_OK:Z_OK$3,Z_STREAM_END:Z_STREAM_END$3,Z_STREAM_ERROR:Z_STREAM_ERROR$2,Z_DATA_ERROR:Z_DATA_ERROR$2,Z_BUF_ERROR:Z_BUF_ERROR$1,Z_DEFAULT_COMPRESSION:Z_DEFAULT_COMPRESSION$1,Z_FILTERED,Z_HUFFMAN_ONLY,Z_RLE,Z_FIXED,Z_DEFAULT_STRATEGY:Z_DEFAULT_STRATEGY$1,Z_UNKNOWN,Z_DEFLATED:Z_DEFLATED$2}=constants$2,MAX_MEM_LEVEL=9,MAX_WBITS$1=15,DEF_MEM_LEVEL=8,LENGTH_CODES=29,LITERALS=256,L_CODES=LITERALS+1+LENGTH_CODES,D_CODES=30,BL_CODES=19,HEAP_SIZE=2*L_CODES+1,MAX_BITS=15,MIN_MATCH=3,MAX_MATCH=258,MIN_LOOKAHEAD=MAX_MATCH+MIN_MATCH+1,PRESET_DICT=32,INIT_STATE=42,GZIP_STATE=57,EXTRA_STATE=69,NAME_STATE=73,COMMENT_STATE=91,HCRC_STATE=103,BUSY_STATE=113,FINISH_STATE=666,BS_NEED_MORE=1,BS_BLOCK_DONE=2,BS_FINISH_STARTED=3,BS_FINISH_DONE=4,OS_CODE=3,err=(e,t)=>(e.msg=messages[t],t),rank=e=>e*2-(e>4?9:0),zero=e=>{let t=e.length;for(;--t>=0;)e[t]=0},slide_hash=e=>{let t,n,r,l=e.w_size;t=e.hash_size,r=t;do n=e.head[--r],e.head[r]=n>=l?n-l:0;while(--t);t=l,r=t;do n=e.prev[--r],e.prev[r]=n>=l?n-l:0;while(--t)};let HASH_ZLIB=(e,t,n)=>(t<<e.hash_shift^n)&e.hash_mask,HASH=HASH_ZLIB;const flush_pending=e=>{const t=e.state;let n=t.pending;n>e.avail_out&&(n=e.avail_out),n!==0&&(e.output.set(t.pending_buf.subarray(t.pending_out,t.pending_out+n),e.next_out),e.next_out+=n,t.pending_out+=n,e.total_out+=n,e.avail_out-=n,t.pending-=n,t.pending===0&&(t.pending_out=0))},flush_block_only=(e,t)=>{_tr_flush_block(e,e.block_start>=0?e.block_start:-1,e.strstart-e.block_start,t),e.block_start=e.strstart,flush_pending(e.strm)},put_byte=(e,t)=>{e.pending_buf[e.pending++]=t},putShortMSB=(e,t)=>{e.pending_buf[e.pending++]=t>>>8&255,e.pending_buf[e.pending++]=t&255},read_buf=(e,t,n,r)=>{let l=e.avail_in;return l>r&&(l=r),l===0?0:(e.avail_in-=l,t.set(e.input.subarray(e.next_in,e.next_in+l),n),e.state.wrap===1?e.adler=adler32_1(e.adler,t,l,n):e.state.wrap===2&&(e.adler=crc32_1(e.adler,t,l,n)),e.next_in+=l,e.total_in+=l,l)},longest_match=(e,t)=>{let n=e.max_chain_length,r=e.strstart,l,s,c=e.prev_length,o=e.nice_match;const d=e.strstart>e.w_size-MIN_LOOKAHEAD?e.strstart-(e.w_size-MIN_LOOKAHEAD):0,u=e.window,U=e.w_mask,B=e.prev,R=e.strstart+MAX_MATCH;let p=u[r+c-1],g=u[r+c];e.prev_length>=e.good_match&&(n>>=2),o>e.lookahead&&(o=e.lookahead);do if(l=t,!(u[l+c]!==g||u[l+c-1]!==p||u[l]!==u[r]||u[++l]!==u[r+1])){r+=2,l++;do;while(u[++r]===u[++l]&&u[++r]===u[++l]&&u[++r]===u[++l]&&u[++r]===u[++l]&&u[++r]===u[++l]&&u[++r]===u[++l]&&u[++r]===u[++l]&&u[++r]===u[++l]&&r<R);if(s=MAX_MATCH-(R-r),r=R-MAX_MATCH,s>c){if(e.match_start=t,c=s,s>=o)break;p=u[r+c-1],g=u[r+c]}}while((t=B[t&U])>d&&--n!==0);return c<=e.lookahead?c:e.lookahead},fill_window=e=>{const t=e.w_size;let n,r,l;do{if(r=e.window_size-e.lookahead-e.strstart,e.strstart>=t+(t-MIN_LOOKAHEAD)&&(e.window.set(e.window.subarray(t,t+t-r),0),e.match_start-=t,e.strstart-=t,e.block_start-=t,e.insert>e.strstart&&(e.insert=e.strstart),slide_hash(e),r+=t),e.strm.avail_in===0)break;if(n=read_buf(e.strm,e.window,e.strstart+e.lookahead,r),e.lookahead+=n,e.lookahead+e.insert>=MIN_MATCH)for(l=e.strstart-e.insert,e.ins_h=e.window[l],e.ins_h=HASH(e,e.ins_h,e.window[l+1]);e.insert&&(e.ins_h=HASH(e,e.ins_h,e.window[l+MIN_MATCH-1]),e.prev[l&e.w_mask]=e.head[e.ins_h],e.head[e.ins_h]=l,l++,e.insert--,!(e.lookahead+e.insert<MIN_MATCH)););}while(e.lookahead<MIN_LOOKAHEAD&&e.strm.avail_in!==0)},deflate_stored=(e,t)=>{let n=e.pending_buf_size-5>e.w_size?e.w_size:e.pending_buf_size-5,r,l,s,c=0,o=e.strm.avail_in;do{if(r=65535,s=e.bi_valid+42>>3,e.strm.avail_out<s||(s=e.strm.avail_out-s,l=e.strstart-e.block_start,r>l+e.strm.avail_in&&(r=l+e.strm.avail_in),r>s&&(r=s),r<n&&(r===0&&t!==Z_FINISH$3||t===Z_NO_FLUSH$2||r!==l+e.strm.avail_in)))break;c=t===Z_FINISH$3&&r===l+e.strm.avail_in?1:0,_tr_stored_block(e,0,0,c),e.pending_buf[e.pending-4]=r,e.pending_buf[e.pending-3]=r>>8,e.pending_buf[e.pending-2]=~r,e.pending_buf[e.pending-1]=~r>>8,flush_pending(e.strm),l&&(l>r&&(l=r),e.strm.output.set(e.window.subarray(e.block_start,e.block_start+l),e.strm.next_out),e.strm.next_out+=l,e.strm.avail_out-=l,e.strm.total_out+=l,e.block_start+=l,r-=l),r&&(read_buf(e.strm,e.strm.output,e.strm.next_out,r),e.strm.next_out+=r,e.strm.avail_out-=r,e.strm.total_out+=r)}while(c===0);return o-=e.strm.avail_in,o&&(o>=e.w_size?(e.matches=2,e.window.set(e.strm.input.subarray(e.strm.next_in-e.w_size,e.strm.next_in),0),e.strstart=e.w_size,e.insert=e.strstart):(e.window_size-e.strstart<=o&&(e.strstart-=e.w_size,e.window.set(e.window.subarray(e.w_size,e.w_size+e.strstart),0),e.matches<2&&e.matches++,e.insert>e.strstart&&(e.insert=e.strstart)),e.window.set(e.strm.input.subarray(e.strm.next_in-o,e.strm.next_in),e.strstart),e.strstart+=o,e.insert+=o>e.w_size-e.insert?e.w_size-e.insert:o),e.block_start=e.strstart),e.high_water<e.strstart&&(e.high_water=e.strstart),c?BS_FINISH_DONE:t!==Z_NO_FLUSH$2&&t!==Z_FINISH$3&&e.strm.avail_in===0&&e.strstart===e.block_start?BS_BLOCK_DONE:(s=e.window_size-e.strstart,e.strm.avail_in>s&&e.block_start>=e.w_size&&(e.block_start-=e.w_size,e.strstart-=e.w_size,e.window.set(e.window.subarray(e.w_size,e.w_size+e.strstart),0),e.matches<2&&e.matches++,s+=e.w_size,e.insert>e.strstart&&(e.insert=e.strstart)),s>e.strm.avail_in&&(s=e.strm.avail_in),s&&(read_buf(e.strm,e.window,e.strstart,s),e.strstart+=s,e.insert+=s>e.w_size-e.insert?e.w_size-e.insert:s),e.high_water<e.strstart&&(e.high_water=e.strstart),s=e.bi_valid+42>>3,s=e.pending_buf_size-s>65535?65535:e.pending_buf_size-s,n=s>e.w_size?e.w_size:s,l=e.strstart-e.block_start,(l>=n||(l||t===Z_FINISH$3)&&t!==Z_NO_FLUSH$2&&e.strm.avail_in===0&&l<=s)&&(r=l>s?s:l,c=t===Z_FINISH$3&&e.strm.avail_in===0&&r===l?1:0,_tr_stored_block(e,e.block_start,r,c),e.block_start+=r,flush_pending(e.strm)),c?BS_FINISH_STARTED:BS_NEED_MORE)},deflate_fast=(e,t)=>{let n,r;for(;;){if(e.lookahead<MIN_LOOKAHEAD){if(fill_window(e),e.lookahead<MIN_LOOKAHEAD&&t===Z_NO_FLUSH$2)return BS_NEED_MORE;if(e.lookahead===0)break}if(n=0,e.lookahead>=MIN_MATCH&&(e.ins_h=HASH(e,e.ins_h,e.window[e.strstart+MIN_MATCH-1]),n=e.prev[e.strstart&e.w_mask]=e.head[e.ins_h],e.head[e.ins_h]=e.strstart),n!==0&&e.strstart-n<=e.w_size-MIN_LOOKAHEAD&&(e.match_length=longest_match(e,n)),e.match_length>=MIN_MATCH)if(r=_tr_tally(e,e.strstart-e.match_start,e.match_length-MIN_MATCH),e.lookahead-=e.match_length,e.match_length<=e.max_lazy_match&&e.lookahead>=MIN_MATCH){e.match_length--;do e.strstart++,e.ins_h=HASH(e,e.ins_h,e.window[e.strstart+MIN_MATCH-1]),n=e.prev[e.strstart&e.w_mask]=e.head[e.ins_h],e.head[e.ins_h]=e.strstart;while(--e.match_length!==0);e.strstart++}else e.strstart+=e.match_length,e.match_length=0,e.ins_h=e.window[e.strstart],e.ins_h=HASH(e,e.ins_h,e.window[e.strstart+1]);else r=_tr_tally(e,0,e.window[e.strstart]),e.lookahead--,e.strstart++;if(r&&(flush_block_only(e,!1),e.strm.avail_out===0))return BS_NEED_MORE}return e.insert=e.strstart<MIN_MATCH-1?e.strstart:MIN_MATCH-1,t===Z_FINISH$3?(flush_block_only(e,!0),e.strm.avail_out===0?BS_FINISH_STARTED:BS_FINISH_DONE):e.sym_next&&(flush_block_only(e,!1),e.strm.avail_out===0)?BS_NEED_MORE:BS_BLOCK_DONE},deflate_slow=(e,t)=>{let n,r,l;for(;;){if(e.lookahead<MIN_LOOKAHEAD){if(fill_window(e),e.lookahead<MIN_LOOKAHEAD&&t===Z_NO_FLUSH$2)return BS_NEED_MORE;if(e.lookahead===0)break}if(n=0,e.lookahead>=MIN_MATCH&&(e.ins_h=HASH(e,e.ins_h,e.window[e.strstart+MIN_MATCH-1]),n=e.prev[e.strstart&e.w_mask]=e.head[e.ins_h],e.head[e.ins_h]=e.strstart),e.prev_length=e.match_length,e.prev_match=e.match_start,e.match_length=MIN_MATCH-1,n!==0&&e.prev_length<e.max_lazy_match&&e.strstart-n<=e.w_size-MIN_LOOKAHEAD&&(e.match_length=longest_match(e,n),e.match_length<=5&&(e.strategy===Z_FILTERED||e.match_length===MIN_MATCH&&e.strstart-e.match_start>4096)&&(e.match_length=MIN_MATCH-1)),e.prev_length>=MIN_MATCH&&e.match_length<=e.prev_length){l=e.strstart+e.lookahead-MIN_MATCH,r=_tr_tally(e,e.strstart-1-e.prev_match,e.prev_length-MIN_MATCH),e.lookahead-=e.prev_length-1,e.prev_length-=2;do++e.strstart<=l&&(e.ins_h=HASH(e,e.ins_h,e.window[e.strstart+MIN_MATCH-1]),n=e.prev[e.strstart&e.w_mask]=e.head[e.ins_h],e.head[e.ins_h]=e.strstart);while(--e.prev_length!==0);if(e.match_available=0,e.match_length=MIN_MATCH-1,e.strstart++,r&&(flush_block_only(e,!1),e.strm.avail_out===0))return BS_NEED_MORE}else if(e.match_available){if(r=_tr_tally(e,0,e.window[e.strstart-1]),r&&flush_block_only(e,!1),e.strstart++,e.lookahead--,e.strm.avail_out===0)return BS_NEED_MORE}else e.match_available=1,e.strstart++,e.lookahead--}return e.match_available&&(r=_tr_tally(e,0,e.window[e.strstart-1]),e.match_available=0),e.insert=e.strstart<MIN_MATCH-1?e.strstart:MIN_MATCH-1,t===Z_FINISH$3?(flush_block_only(e,!0),e.strm.avail_out===0?BS_FINISH_STARTED:BS_FINISH_DONE):e.sym_next&&(flush_block_only(e,!1),e.strm.avail_out===0)?BS_NEED_MORE:BS_BLOCK_DONE},deflate_rle=(e,t)=>{let n,r,l,s;const c=e.window;for(;;){if(e.lookahead<=MAX_MATCH){if(fill_window(e),e.lookahead<=MAX_MATCH&&t===Z_NO_FLUSH$2)return BS_NEED_MORE;if(e.lookahead===0)break}if(e.match_length=0,e.lookahead>=MIN_MATCH&&e.strstart>0&&(l=e.strstart-1,r=c[l],r===c[++l]&&r===c[++l]&&r===c[++l])){s=e.strstart+MAX_MATCH;do;while(r===c[++l]&&r===c[++l]&&r===c[++l]&&r===c[++l]&&r===c[++l]&&r===c[++l]&&r===c[++l]&&r===c[++l]&&l<s);e.match_length=MAX_MATCH-(s-l),e.match_length>e.lookahead&&(e.match_length=e.lookahead)}if(e.match_length>=MIN_MATCH?(n=_tr_tally(e,1,e.match_length-MIN_MATCH),e.lookahead-=e.match_length,e.strstart+=e.match_length,e.match_length=0):(n=_tr_tally(e,0,e.window[e.strstart]),e.lookahead--,e.strstart++),n&&(flush_block_only(e,!1),e.strm.avail_out===0))return BS_NEED_MORE}return e.insert=0,t===Z_FINISH$3?(flush_block_only(e,!0),e.strm.avail_out===0?BS_FINISH_STARTED:BS_FINISH_DONE):e.sym_next&&(flush_block_only(e,!1),e.strm.avail_out===0)?BS_NEED_MORE:BS_BLOCK_DONE},deflate_huff=(e,t)=>{let n;for(;;){if(e.lookahead===0&&(fill_window(e),e.lookahead===0)){if(t===Z_NO_FLUSH$2)return BS_NEED_MORE;break}if(e.match_length=0,n=_tr_tally(e,0,e.window[e.strstart]),e.lookahead--,e.strstart++,n&&(flush_block_only(e,!1),e.strm.avail_out===0))return BS_NEED_MORE}return e.insert=0,t===Z_FINISH$3?(flush_block_only(e,!0),e.strm.avail_out===0?BS_FINISH_STARTED:BS_FINISH_DONE):e.sym_next&&(flush_block_only(e,!1),e.strm.avail_out===0)?BS_NEED_MORE:BS_BLOCK_DONE};function Config(e,t,n,r,l){this.good_length=e,this.max_lazy=t,this.nice_length=n,this.max_chain=r,this.func=l}const configuration_table=[new Config(0,0,0,0,deflate_stored),new Config(4,4,8,4,deflate_fast),new Config(4,5,16,8,deflate_fast),new Config(4,6,32,32,deflate_fast),new Config(4,4,16,16,deflate_slow),new Config(8,16,32,32,deflate_slow),new Config(8,16,128,128,deflate_slow),new Config(8,32,128,256,deflate_slow),new Config(32,128,258,1024,deflate_slow),new Config(32,258,258,4096,deflate_slow)],lm_init=e=>{e.window_size=2*e.w_size,zero(e.head),e.max_lazy_match=configuration_table[e.level].max_lazy,e.good_match=configuration_table[e.level].good_length,e.nice_match=configuration_table[e.level].nice_length,e.max_chain_length=configuration_table[e.level].max_chain,e.strstart=0,e.block_start=0,e.lookahead=0,e.insert=0,e.match_length=e.prev_length=MIN_MATCH-1,e.match_available=0,e.ins_h=0};function DeflateState(){this.strm=null,this.status=0,this.pending_buf=null,this.pending_buf_size=0,this.pending_out=0,this.pending=0,this.wrap=0,this.gzhead=null,this.gzindex=0,this.method=Z_DEFLATED$2,this.last_flush=-1,this.w_size=0,this.w_bits=0,this.w_mask=0,this.window=null,this.window_size=0,this.prev=null,this.head=null,this.ins_h=0,this.hash_size=0,this.hash_bits=0,this.hash_mask=0,this.hash_shift=0,this.block_start=0,this.match_length=0,this.prev_match=0,this.match_available=0,this.strstart=0,this.match_start=0,this.lookahead=0,this.prev_length=0,this.max_chain_length=0,this.max_lazy_match=0,this.level=0,this.strategy=0,this.good_match=0,this.nice_match=0,this.dyn_ltree=new Uint16Array(HEAP_SIZE*2),this.dyn_dtree=new Uint16Array((2*D_CODES+1)*2),this.bl_tree=new Uint16Array((2*BL_CODES+1)*2),zero(this.dyn_ltree),zero(this.dyn_dtree),zero(this.bl_tree),this.l_desc=null,this.d_desc=null,this.bl_desc=null,this.bl_count=new Uint16Array(MAX_BITS+1),this.heap=new Uint16Array(2*L_CODES+1),zero(this.heap),this.heap_len=0,this.heap_max=0,this.depth=new Uint16Array(2*L_CODES+1),zero(this.depth),this.sym_buf=0,this.lit_bufsize=0,this.sym_next=0,this.sym_end=0,this.opt_len=0,this.static_len=0,this.matches=0,this.insert=0,this.bi_buf=0,this.bi_valid=0}const deflateStateCheck=e=>{if(!e)return 1;const t=e.state;return!t||t.strm!==e||t.status!==INIT_STATE&&t.status!==GZIP_STATE&&t.status!==EXTRA_STATE&&t.status!==NAME_STATE&&t.status!==COMMENT_STATE&&t.status!==HCRC_STATE&&t.status!==BUSY_STATE&&t.status!==FINISH_STATE?1:0},deflateResetKeep=e=>{if(deflateStateCheck(e))return err(e,Z_STREAM_ERROR$2);e.total_in=e.total_out=0,e.data_type=Z_UNKNOWN;const t=e.state;return t.pending=0,t.pending_out=0,t.wrap<0&&(t.wrap=-t.wrap),t.status=t.wrap===2?GZIP_STATE:t.wrap?INIT_STATE:BUSY_STATE,e.adler=t.wrap===2?0:1,t.last_flush=-2,_tr_init(t),Z_OK$3},deflateReset=e=>{const t=deflateResetKeep(e);return t===Z_OK$3&&lm_init(e.state),t},deflateSetHeader=(e,t)=>deflateStateCheck(e)||e.state.wrap!==2?Z_STREAM_ERROR$2:(e.state.gzhead=t,Z_OK$3),deflateInit2=(e,t,n,r,l,s)=>{if(!e)return Z_STREAM_ERROR$2;let c=1;if(t===Z_DEFAULT_COMPRESSION$1&&(t=6),r<0?(c=0,r=-r):r>15&&(c=2,r-=16),l<1||l>MAX_MEM_LEVEL||n!==Z_DEFLATED$2||r<8||r>15||t<0||t>9||s<0||s>Z_FIXED||r===8&&c!==1)return err(e,Z_STREAM_ERROR$2);r===8&&(r=9);const o=new DeflateState;return e.state=o,o.strm=e,o.status=INIT_STATE,o.wrap=c,o.gzhead=null,o.w_bits=r,o.w_size=1<<o.w_bits,o.w_mask=o.w_size-1,o.hash_bits=l+7,o.hash_size=1<<o.hash_bits,o.hash_mask=o.hash_size-1,o.hash_shift=~~((o.hash_bits+MIN_MATCH-1)/MIN_MATCH),o.window=new Uint8Array(o.w_size*2),o.head=new Uint16Array(o.hash_size),o.prev=new Uint16Array(o.w_size),o.lit_bufsize=1<<l+6,o.pending_buf_size=o.lit_bufsize*4,o.pending_buf=new Uint8Array(o.pending_buf_size),o.sym_buf=o.lit_bufsize,o.sym_end=(o.lit_bufsize-1)*3,o.level=t,o.strategy=s,o.method=n,deflateReset(e)},deflateInit=(e,t)=>deflateInit2(e,t,Z_DEFLATED$2,MAX_WBITS$1,DEF_MEM_LEVEL,Z_DEFAULT_STRATEGY$1),deflate$2=(e,t)=>{if(deflateStateCheck(e)||t>Z_BLOCK$1||t<0)return e?err(e,Z_STREAM_ERROR$2):Z_STREAM_ERROR$2;const n=e.state;if(!e.output||e.avail_in!==0&&!e.input||n.status===FINISH_STATE&&t!==Z_FINISH$3)return err(e,e.avail_out===0?Z_BUF_ERROR$1:Z_STREAM_ERROR$2);const r=n.last_flush;if(n.last_flush=t,n.pending!==0){if(flush_pending(e),e.avail_out===0)return n.last_flush=-1,Z_OK$3}else if(e.avail_in===0&&rank(t)<=rank(r)&&t!==Z_FINISH$3)return err(e,Z_BUF_ERROR$1);if(n.status===FINISH_STATE&&e.avail_in!==0)return err(e,Z_BUF_ERROR$1);if(n.status===INIT_STATE&&n.wrap===0&&(n.status=BUSY_STATE),n.status===INIT_STATE){let l=Z_DEFLATED$2+(n.w_bits-8<<4)<<8,s=-1;if(n.strategy>=Z_HUFFMAN_ONLY||n.level<2?s=0:n.level<6?s=1:n.level===6?s=2:s=3,l|=s<<6,n.strstart!==0&&(l|=PRESET_DICT),l+=31-l%31,putShortMSB(n,l),n.strstart!==0&&(putShortMSB(n,e.adler>>>16),putShortMSB(n,e.adler&65535)),e.adler=1,n.status=BUSY_STATE,flush_pending(e),n.pending!==0)return n.last_flush=-1,Z_OK$3}if(n.status===GZIP_STATE){if(e.adler=0,put_byte(n,31),put_byte(n,139),put_byte(n,8),n.gzhead)put_byte(n,(n.gzhead.text?1:0)+(n.gzhead.hcrc?2:0)+(n.gzhead.extra?4:0)+(n.gzhead.name?8:0)+(n.gzhead.comment?16:0)),put_byte(n,n.gzhead.time&255),put_byte(n,n.gzhead.time>>8&255),put_byte(n,n.gzhead.time>>16&255),put_byte(n,n.gzhead.time>>24&255),put_byte(n,n.level===9?2:n.strategy>=Z_HUFFMAN_ONLY||n.level<2?4:0),put_byte(n,n.gzhead.os&255),n.gzhead.extra&&n.gzhead.extra.length&&(put_byte(n,n.gzhead.extra.length&255),put_byte(n,n.gzhead.extra.length>>8&255)),n.gzhead.hcrc&&(e.adler=crc32_1(e.adler,n.pending_buf,n.pending,0)),n.gzindex=0,n.status=EXTRA_STATE;else if(put_byte(n,0),put_byte(n,0),put_byte(n,0),put_byte(n,0),put_byte(n,0),put_byte(n,n.level===9?2:n.strategy>=Z_HUFFMAN_ONLY||n.level<2?4:0),put_byte(n,OS_CODE),n.status=BUSY_STATE,flush_pending(e),n.pending!==0)return n.last_flush=-1,Z_OK$3}if(n.status===EXTRA_STATE){if(n.gzhead.extra){let l=n.pending,s=(n.gzhead.extra.length&65535)-n.gzindex;for(;n.pending+s>n.pending_buf_size;){let o=n.pending_buf_size-n.pending;if(n.pending_buf.set(n.gzhead.extra.subarray(n.gzindex,n.gzindex+o),n.pending),n.pending=n.pending_buf_size,n.gzhead.hcrc&&n.pending>l&&(e.adler=crc32_1(e.adler,n.pending_buf,n.pending-l,l)),n.gzindex+=o,flush_pending(e),n.pending!==0)return n.last_flush=-1,Z_OK$3;l=0,s-=o}let c=new Uint8Array(n.gzhead.extra);n.pending_buf.set(c.subarray(n.gzindex,n.gzindex+s),n.pending),n.pending+=s,n.gzhead.hcrc&&n.pending>l&&(e.adler=crc32_1(e.adler,n.pending_buf,n.pending-l,l)),n.gzindex=0}n.status=NAME_STATE}if(n.status===NAME_STATE){if(n.gzhead.name){let l=n.pending,s;do{if(n.pending===n.pending_buf_size){if(n.gzhead.hcrc&&n.pending>l&&(e.adler=crc32_1(e.adler,n.pending_buf,n.pending-l,l)),flush_pending(e),n.pending!==0)return n.last_flush=-1,Z_OK$3;l=0}n.gzindex<n.gzhead.name.length?s=n.gzhead.name.charCodeAt(n.gzindex++)&255:s=0,put_byte(n,s)}while(s!==0);n.gzhead.hcrc&&n.pending>l&&(e.adler=crc32_1(e.adler,n.pending_buf,n.pending-l,l)),n.gzindex=0}n.status=COMMENT_STATE}if(n.status===COMMENT_STATE){if(n.gzhead.comment){let l=n.pending,s;do{if(n.pending===n.pending_buf_size){if(n.gzhead.hcrc&&n.pending>l&&(e.adler=crc32_1(e.adler,n.pending_buf,n.pending-l,l)),flush_pending(e),n.pending!==0)return n.last_flush=-1,Z_OK$3;l=0}n.gzindex<n.gzhead.comment.length?s=n.gzhead.comment.charCodeAt(n.gzindex++)&255:s=0,put_byte(n,s)}while(s!==0);n.gzhead.hcrc&&n.pending>l&&(e.adler=crc32_1(e.adler,n.pending_buf,n.pending-l,l))}n.status=HCRC_STATE}if(n.status===HCRC_STATE){if(n.gzhead.hcrc){if(n.pending+2>n.pending_buf_size&&(flush_pending(e),n.pending!==0))return n.last_flush=-1,Z_OK$3;put_byte(n,e.adler&255),put_byte(n,e.adler>>8&255),e.adler=0}if(n.status=BUSY_STATE,flush_pending(e),n.pending!==0)return n.last_flush=-1,Z_OK$3}if(e.avail_in!==0||n.lookahead!==0||t!==Z_NO_FLUSH$2&&n.status!==FINISH_STATE){let l=n.level===0?deflate_stored(n,t):n.strategy===Z_HUFFMAN_ONLY?deflate_huff(n,t):n.strategy===Z_RLE?deflate_rle(n,t):configuration_table[n.level].func(n,t);if((l===BS_FINISH_STARTED||l===BS_FINISH_DONE)&&(n.status=FINISH_STATE),l===BS_NEED_MORE||l===BS_FINISH_STARTED)return e.avail_out===0&&(n.last_flush=-1),Z_OK$3;if(l===BS_BLOCK_DONE&&(t===Z_PARTIAL_FLUSH?_tr_align(n):t!==Z_BLOCK$1&&(_tr_stored_block(n,0,0,!1),t===Z_FULL_FLUSH$1&&(zero(n.head),n.lookahead===0&&(n.strstart=0,n.block_start=0,n.insert=0))),flush_pending(e),e.avail_out===0))return n.last_flush=-1,Z_OK$3}return t!==Z_FINISH$3?Z_OK$3:n.wrap<=0?Z_STREAM_END$3:(n.wrap===2?(put_byte(n,e.adler&255),put_byte(n,e.adler>>8&255),put_byte(n,e.adler>>16&255),put_byte(n,e.adler>>24&255),put_byte(n,e.total_in&255),put_byte(n,e.total_in>>8&255),put_byte(n,e.total_in>>16&255),put_byte(n,e.total_in>>24&255)):(putShortMSB(n,e.adler>>>16),putShortMSB(n,e.adler&65535)),flush_pending(e),n.wrap>0&&(n.wrap=-n.wrap),n.pending!==0?Z_OK$3:Z_STREAM_END$3)},deflateEnd=e=>{if(deflateStateCheck(e))return Z_STREAM_ERROR$2;const t=e.state.status;return e.state=null,t===BUSY_STATE?err(e,Z_DATA_ERROR$2):Z_OK$3},deflateSetDictionary=(e,t)=>{let n=t.length;if(deflateStateCheck(e))return Z_STREAM_ERROR$2;const r=e.state,l=r.wrap;if(l===2||l===1&&r.status!==INIT_STATE||r.lookahead)return Z_STREAM_ERROR$2;if(l===1&&(e.adler=adler32_1(e.adler,t,n,0)),r.wrap=0,n>=r.w_size){l===0&&(zero(r.head),r.strstart=0,r.block_start=0,r.insert=0);let d=new Uint8Array(r.w_size);d.set(t.subarray(n-r.w_size,n),0),t=d,n=r.w_size}const s=e.avail_in,c=e.next_in,o=e.input;for(e.avail_in=n,e.next_in=0,e.input=t,fill_window(r);r.lookahead>=MIN_MATCH;){let d=r.strstart,u=r.lookahead-(MIN_MATCH-1);do r.ins_h=HASH(r,r.ins_h,r.window[d+MIN_MATCH-1]),r.prev[d&r.w_mask]=r.head[r.ins_h],r.head[r.ins_h]=d,d++;while(--u);r.strstart=d,r.lookahead=MIN_MATCH-1,fill_window(r)}return r.strstart+=r.lookahead,r.block_start=r.strstart,r.insert=r.lookahead,r.lookahead=0,r.match_length=r.prev_length=MIN_MATCH-1,r.match_available=0,e.next_in=c,e.input=o,e.avail_in=s,r.wrap=l,Z_OK$3};var deflateInit_1=deflateInit,deflateInit2_1=deflateInit2,deflateReset_1=deflateReset,deflateResetKeep_1=deflateResetKeep,deflateSetHeader_1=deflateSetHeader,deflate_2$1=deflate$2,deflateEnd_1=deflateEnd,deflateSetDictionary_1=deflateSetDictionary,deflateInfo="pako deflate (from Nodeca project)",deflate_1$2={deflateInit:deflateInit_1,deflateInit2:deflateInit2_1,deflateReset:deflateReset_1,deflateResetKeep:deflateResetKeep_1,deflateSetHeader:deflateSetHeader_1,deflate:deflate_2$1,deflateEnd:deflateEnd_1,deflateSetDictionary:deflateSetDictionary_1,deflateInfo};const _has=(e,t)=>Object.prototype.hasOwnProperty.call(e,t);var assign=function(e){const t=Array.prototype.slice.call(arguments,1);for(;t.length;){const n=t.shift();if(n){if(typeof n!="object")throw new TypeError(n+"must be non-object");for(const r in n)_has(n,r)&&(e[r]=n[r])}}return e},flattenChunks=e=>{let t=0;for(let r=0,l=e.length;r<l;r++)t+=e[r].length;const n=new Uint8Array(t);for(let r=0,l=0,s=e.length;r<s;r++){let c=e[r];n.set(c,l),l+=c.length}return n},common={assign,flattenChunks};let STR_APPLY_UIA_OK=!0;try{String.fromCharCode.apply(null,new Uint8Array(1))}catch(e){STR_APPLY_UIA_OK=!1}const _utf8len=new Uint8Array(256);for(let e=0;e<256;e++)_utf8len[e]=e>=252?6:e>=248?5:e>=240?4:e>=224?3:e>=192?2:1;_utf8len[254]=_utf8len[254]=1;var string2buf=e=>{if(typeof TextEncoder=="function"&&TextEncoder.prototype.encode)return new TextEncoder().encode(e);let t,n,r,l,s,c=e.length,o=0;for(l=0;l<c;l++)n=e.charCodeAt(l),(n&64512)===55296&&l+1<c&&(r=e.charCodeAt(l+1),(r&64512)===56320&&(n=65536+(n-55296<<10)+(r-56320),l++)),o+=n<128?1:n<2048?2:n<65536?3:4;for(t=new Uint8Array(o),s=0,l=0;s<o;l++)n=e.charCodeAt(l),(n&64512)===55296&&l+1<c&&(r=e.charCodeAt(l+1),(r&64512)===56320&&(n=65536+(n-55296<<10)+(r-56320),l++)),n<128?t[s++]=n:n<2048?(t[s++]=192|n>>>6,t[s++]=128|n&63):n<65536?(t[s++]=224|n>>>12,t[s++]=128|n>>>6&63,t[s++]=128|n&63):(t[s++]=240|n>>>18,t[s++]=128|n>>>12&63,t[s++]=128|n>>>6&63,t[s++]=128|n&63);return t};const buf2binstring=(e,t)=>{if(t<65534&&e.subarray&&STR_APPLY_UIA_OK)return String.fromCharCode.apply(null,e.length===t?e:e.subarray(0,t));let n="";for(let r=0;r<t;r++)n+=String.fromCharCode(e[r]);return n};var buf2string=(e,t)=>{const n=t||e.length;if(typeof TextDecoder=="function"&&TextDecoder.prototype.decode)return new TextDecoder().decode(e.subarray(0,t));let r,l;const s=new Array(n*2);for(l=0,r=0;r<n;){let c=e[r++];if(c<128){s[l++]=c;continue}let o=_utf8len[c];if(o>4){s[l++]=65533,r+=o-1;continue}for(c&=o===2?31:o===3?15:7;o>1&&r<n;)c=c<<6|e[r++]&63,o--;if(o>1){s[l++]=65533;continue}c<65536?s[l++]=c:(c-=65536,s[l++]=55296|c>>10&1023,s[l++]=56320|c&1023)}return buf2binstring(s,l)},utf8border=(e,t)=>{t=t||e.length,t>e.length&&(t=e.length);let n=t-1;for(;n>=0&&(e[n]&192)===128;)n--;return n<0||n===0?t:n+_utf8len[e[n]]>t?n:t},strings={string2buf,buf2string,utf8border};function ZStream(){this.input=null,this.next_in=0,this.avail_in=0,this.total_in=0,this.output=null,this.next_out=0,this.avail_out=0,this.total_out=0,this.msg="",this.state=null,this.data_type=2,this.adler=0}var zstream=ZStream;const toString$1=Object.prototype.toString,{Z_NO_FLUSH:Z_NO_FLUSH$1,Z_SYNC_FLUSH,Z_FULL_FLUSH,Z_FINISH:Z_FINISH$2,Z_OK:Z_OK$2,Z_STREAM_END:Z_STREAM_END$2,Z_DEFAULT_COMPRESSION,Z_DEFAULT_STRATEGY,Z_DEFLATED:Z_DEFLATED$1}=constants$2;function Deflate$1(e){this.options=common.assign({level:Z_DEFAULT_COMPRESSION,method:Z_DEFLATED$1,chunkSize:16384,windowBits:15,memLevel:8,strategy:Z_DEFAULT_STRATEGY},e||{});let t=this.options;t.raw&&t.windowBits>0?t.windowBits=-t.windowBits:t.gzip&&t.windowBits>0&&t.windowBits<16&&(t.windowBits+=16),this.err=0,this.msg="",this.ended=!1,this.chunks=[],this.strm=new zstream,this.strm.avail_out=0;let n=deflate_1$2.deflateInit2(this.strm,t.level,t.method,t.windowBits,t.memLevel,t.strategy);if(n!==Z_OK$2)throw new Error(messages[n]);if(t.header&&deflate_1$2.deflateSetHeader(this.strm,t.header),t.dictionary){let r;if(typeof t.dictionary=="string"?r=strings.string2buf(t.dictionary):toString$1.call(t.dictionary)==="[object ArrayBuffer]"?r=new Uint8Array(t.dictionary):r=t.dictionary,n=deflate_1$2.deflateSetDictionary(this.strm,r),n!==Z_OK$2)throw new Error(messages[n]);this._dict_set=!0}}Deflate$1.prototype.push=function(e,t){const n=this.strm,r=this.options.chunkSize;let l,s;if(this.ended)return!1;for(t===~~t?s=t:s=t===!0?Z_FINISH$2:Z_NO_FLUSH$1,typeof e=="string"?n.input=strings.string2buf(e):toString$1.call(e)==="[object ArrayBuffer]"?n.input=new Uint8Array(e):n.input=e,n.next_in=0,n.avail_in=n.input.length;;){if(n.avail_out===0&&(n.output=new Uint8Array(r),n.next_out=0,n.avail_out=r),(s===Z_SYNC_FLUSH||s===Z_FULL_FLUSH)&&n.avail_out<=6){this.onData(n.output.subarray(0,n.next_out)),n.avail_out=0;continue}if(l=deflate_1$2.deflate(n,s),l===Z_STREAM_END$2)return n.next_out>0&&this.onData(n.output.subarray(0,n.next_out)),l=deflate_1$2.deflateEnd(this.strm),this.onEnd(l),this.ended=!0,l===Z_OK$2;if(n.avail_out===0){this.onData(n.output);continue}if(s>0&&n.next_out>0){this.onData(n.output.subarray(0,n.next_out)),n.avail_out=0;continue}if(n.avail_in===0)break}return!0};Deflate$1.prototype.onData=function(e){this.chunks.push(e)};Deflate$1.prototype.onEnd=function(e){e===Z_OK$2&&(this.result=common.flattenChunks(this.chunks)),this.chunks=[],this.err=e,this.msg=this.strm.msg};function deflate$1(e,t){const n=new Deflate$1(t);if(n.push(e,!0),n.err)throw n.msg||messages[n.err];return n.result}function deflateRaw$1(e,t){return t=t||{},t.raw=!0,deflate$1(e,t)}function gzip$1(e,t){return t=t||{},t.gzip=!0,deflate$1(e,t)}var Deflate_1$1=Deflate$1,deflate_2=deflate$1,deflateRaw_1$1=deflateRaw$1,gzip_1$1=gzip$1,constants$1=constants$2,deflate_1$1={Deflate:Deflate_1$1,deflate:deflate_2,deflateRaw:deflateRaw_1$1,gzip:gzip_1$1,constants:constants$1};const BAD$1=16209,TYPE$1=16191;var inffast=function e(t,n){let r,l,s,c,o,d,u,U,B,R,p,g,h,m,N,D,y,b,F,v,j,K,f,Q;const P=t.state;r=t.next_in,f=t.input,l=r+(t.avail_in-5),s=t.next_out,Q=t.output,c=s-(n-t.avail_out),o=s+(t.avail_out-257),d=P.dmax,u=P.wsize,U=P.whave,B=P.wnext,R=P.window,p=P.hold,g=P.bits,h=P.lencode,m=P.distcode,N=(1<<P.lenbits)-1,D=(1<<P.distbits)-1;e:do{g<15&&(p+=f[r++]<<g,g+=8,p+=f[r++]<<g,g+=8),y=h[p&N];t:for(;;){if(b=y>>>24,p>>>=b,g-=b,b=y>>>16&255,b===0)Q[s++]=y&65535;else if(b&16){F=y&65535,b&=15,b&&(g<b&&(p+=f[r++]<<g,g+=8),F+=p&(1<<b)-1,p>>>=b,g-=b),g<15&&(p+=f[r++]<<g,g+=8,p+=f[r++]<<g,g+=8),y=m[p&D];n:for(;;){if(b=y>>>24,p>>>=b,g-=b,b=y>>>16&255,b&16){if(v=y&65535,b&=15,g<b&&(p+=f[r++]<<g,g+=8,g<b&&(p+=f[r++]<<g,g+=8)),v+=p&(1<<b)-1,v>d){t.msg="invalid distance too far back",P.mode=BAD$1;break e}if(p>>>=b,g-=b,b=s-c,v>b){if(b=v-b,b>U&&P.sane){t.msg="invalid distance too far back",P.mode=BAD$1;break e}if(j=0,K=R,B===0){if(j+=u-b,b<F){F-=b;do Q[s++]=R[j++];while(--b);j=s-v,K=Q}}else if(B<b){if(j+=u+B-b,b-=B,b<F){F-=b;do Q[s++]=R[j++];while(--b);if(j=0,B<F){b=B,F-=b;do Q[s++]=R[j++];while(--b);j=s-v,K=Q}}}else if(j+=B-b,b<F){F-=b;do Q[s++]=R[j++];while(--b);j=s-v,K=Q}for(;F>2;)Q[s++]=K[j++],Q[s++]=K[j++],Q[s++]=K[j++],F-=3;F&&(Q[s++]=K[j++],F>1&&(Q[s++]=K[j++]))}else{j=s-v;do Q[s++]=Q[j++],Q[s++]=Q[j++],Q[s++]=Q[j++],F-=3;while(F>2);F&&(Q[s++]=Q[j++],F>1&&(Q[s++]=Q[j++]))}}else if(b&64){t.msg="invalid distance code",P.mode=BAD$1;break e}else{y=m[(y&65535)+(p&(1<<b)-1)];continue n}break}}else if(b&64)if(b&32){P.mode=TYPE$1;break e}else{t.msg="invalid literal/length code",P.mode=BAD$1;break e}else{y=h[(y&65535)+(p&(1<<b)-1)];continue t}break}}while(r<l&&s<o);F=g>>3,r-=F,g-=F<<3,p&=(1<<g)-1,t.next_in=r,t.next_out=s,t.avail_in=r<l?5+(l-r):5-(r-l),t.avail_out=s<o?257+(o-s):257-(s-o),P.hold=p,P.bits=g};const MAXBITS=15,ENOUGH_LENS$1=852,ENOUGH_DISTS$1=592,CODES$1=0,LENS$1=1,DISTS$1=2,lbase=new Uint16Array([3,4,5,6,7,8,9,10,11,13,15,17,19,23,27,31,35,43,51,59,67,83,99,115,131,163,195,227,258,0,0]),lext=new Uint8Array([16,16,16,16,16,16,16,16,17,17,17,17,18,18,18,18,19,19,19,19,20,20,20,20,21,21,21,21,16,72,78]),dbase=new Uint16Array([1,2,3,4,5,7,9,13,17,25,33,49,65,97,129,193,257,385,513,769,1025,1537,2049,3073,4097,6145,8193,12289,16385,24577,0,0]),dext=new Uint8Array([16,16,16,16,17,17,18,18,19,19,20,20,21,21,22,22,23,23,24,24,25,25,26,26,27,27,28,28,29,29,64,64]),inflate_table=(e,t,n,r,l,s,c,o)=>{const d=o.bits;let u=0,U=0,B=0,R=0,p=0,g=0,h=0,m=0,N=0,D=0,y,b,F,v,j,K=null,f;const Q=new Uint16Array(MAXBITS+1),P=new Uint16Array(MAXBITS+1);let w=null,V,I,W;for(u=0;u<=MAXBITS;u++)Q[u]=0;for(U=0;U<r;U++)Q[t[n+U]]++;for(p=d,R=MAXBITS;R>=1&&Q[R]===0;R--);if(p>R&&(p=R),R===0)return l[s++]=1<<24|64<<16|0,l[s++]=1<<24|64<<16|0,o.bits=1,0;for(B=1;B<R&&Q[B]===0;B++);for(p<B&&(p=B),m=1,u=1;u<=MAXBITS;u++)if(m<<=1,m-=Q[u],m<0)return-1;if(m>0&&(e===CODES$1||R!==1))return-1;for(P[1]=0,u=1;u<MAXBITS;u++)P[u+1]=P[u]+Q[u];for(U=0;U<r;U++)t[n+U]!==0&&(c[P[t[n+U]]++]=U);if(e===CODES$1?(K=w=c,f=20):e===LENS$1?(K=lbase,w=lext,f=257):(K=dbase,w=dext,f=0),D=0,U=0,u=B,j=s,g=p,h=0,F=-1,N=1<<p,v=N-1,e===LENS$1&&N>ENOUGH_LENS$1||e===DISTS$1&&N>ENOUGH_DISTS$1)return 1;for(;;){V=u-h,c[U]+1<f?(I=0,W=c[U]):c[U]>=f?(I=w[c[U]-f],W=K[c[U]-f]):(I=32+64,W=0),y=1<<u-h,b=1<<g,B=b;do b-=y,l[j+(D>>h)+b]=V<<24|I<<16|W|0;while(b!==0);for(y=1<<u-1;D&y;)y>>=1;if(y!==0?(D&=y-1,D+=y):D=0,U++,--Q[u]===0){if(u===R)break;u=t[n+c[U]]}if(u>p&&(D&v)!==F){for(h===0&&(h=p),j+=B,g=u-h,m=1<<g;g+h<R&&(m-=Q[g+h],!(m<=0));)g++,m<<=1;if(N+=1<<g,e===LENS$1&&N>ENOUGH_LENS$1||e===DISTS$1&&N>ENOUGH_DISTS$1)return 1;F=D&v,l[F]=p<<24|g<<16|j-s|0}}return D!==0&&(l[j+D]=u-h<<24|64<<16|0),o.bits=p,0};var inftrees=inflate_table;const CODES=0,LENS=1,DISTS=2,{Z_FINISH:Z_FINISH$1,Z_BLOCK,Z_TREES,Z_OK:Z_OK$1,Z_STREAM_END:Z_STREAM_END$1,Z_NEED_DICT:Z_NEED_DICT$1,Z_STREAM_ERROR:Z_STREAM_ERROR$1,Z_DATA_ERROR:Z_DATA_ERROR$1,Z_MEM_ERROR:Z_MEM_ERROR$1,Z_BUF_ERROR,Z_DEFLATED}=constants$2,HEAD=16180,FLAGS=16181,TIME=16182,OS=16183,EXLEN=16184,EXTRA=16185,NAME=16186,COMMENT=16187,HCRC=16188,DICTID=16189,DICT=16190,TYPE=16191,TYPEDO=16192,STORED=16193,COPY_=16194,COPY=16195,TABLE=16196,LENLENS=16197,CODELENS=16198,LEN_=16199,LEN=16200,LENEXT=16201,DIST=16202,DISTEXT=16203,MATCH=16204,LIT=16205,CHECK=16206,LENGTH=16207,DONE=16208,BAD=16209,MEM=16210,SYNC=16211,ENOUGH_LENS=852,ENOUGH_DISTS=592,MAX_WBITS=15,DEF_WBITS=MAX_WBITS,zswap32=e=>(e>>>24&255)+(e>>>8&65280)+((e&65280)<<8)+((e&255)<<24);function InflateState(){this.strm=null,this.mode=0,this.last=!1,this.wrap=0,this.havedict=!1,this.flags=0,this.dmax=0,this.check=0,this.total=0,this.head=null,this.wbits=0,this.wsize=0,this.whave=0,this.wnext=0,this.window=null,this.hold=0,this.bits=0,this.length=0,this.offset=0,this.extra=0,this.lencode=null,this.distcode=null,this.lenbits=0,this.distbits=0,this.ncode=0,this.nlen=0,this.ndist=0,this.have=0,this.next=null,this.lens=new Uint16Array(320),this.work=new Uint16Array(288),this.lendyn=null,this.distdyn=null,this.sane=0,this.back=0,this.was=0}const inflateStateCheck=e=>{if(!e)return 1;const t=e.state;return!t||t.strm!==e||t.mode<HEAD||t.mode>SYNC?1:0},inflateResetKeep=e=>{if(inflateStateCheck(e))return Z_STREAM_ERROR$1;const t=e.state;return e.total_in=e.total_out=t.total=0,e.msg="",t.wrap&&(e.adler=t.wrap&1),t.mode=HEAD,t.last=0,t.havedict=0,t.flags=-1,t.dmax=32768,t.head=null,t.hold=0,t.bits=0,t.lencode=t.lendyn=new Int32Array(ENOUGH_LENS),t.distcode=t.distdyn=new Int32Array(ENOUGH_DISTS),t.sane=1,t.back=-1,Z_OK$1},inflateReset=e=>{if(inflateStateCheck(e))return Z_STREAM_ERROR$1;const t=e.state;return t.wsize=0,t.whave=0,t.wnext=0,inflateResetKeep(e)},inflateReset2=(e,t)=>{let n;if(inflateStateCheck(e))return Z_STREAM_ERROR$1;const r=e.state;return t<0?(n=0,t=-t):(n=(t>>4)+5,t<48&&(t&=15)),t&&(t<8||t>15)?Z_STREAM_ERROR$1:(r.window!==null&&r.wbits!==t&&(r.window=null),r.wrap=n,r.wbits=t,inflateReset(e))},inflateInit2=(e,t)=>{if(!e)return Z_STREAM_ERROR$1;const n=new InflateState;e.state=n,n.strm=e,n.window=null,n.mode=HEAD;const r=inflateReset2(e,t);return r!==Z_OK$1&&(e.state=null),r},inflateInit=e=>inflateInit2(e,DEF_WBITS);let virgin=!0,lenfix,distfix;const fixedtables=e=>{if(virgin){lenfix=new Int32Array(512),distfix=new Int32Array(32);let t=0;for(;t<144;)e.lens[t++]=8;for(;t<256;)e.lens[t++]=9;for(;t<280;)e.lens[t++]=7;for(;t<288;)e.lens[t++]=8;for(inftrees(LENS,e.lens,0,288,lenfix,0,e.work,{bits:9}),t=0;t<32;)e.lens[t++]=5;inftrees(DISTS,e.lens,0,32,distfix,0,e.work,{bits:5}),virgin=!1}e.lencode=lenfix,e.lenbits=9,e.distcode=distfix,e.distbits=5},updatewindow=(e,t,n,r)=>{let l;const s=e.state;return s.window===null&&(s.wsize=1<<s.wbits,s.wnext=0,s.whave=0,s.window=new Uint8Array(s.wsize)),r>=s.wsize?(s.window.set(t.subarray(n-s.wsize,n),0),s.wnext=0,s.whave=s.wsize):(l=s.wsize-s.wnext,l>r&&(l=r),s.window.set(t.subarray(n-r,n-r+l),s.wnext),r-=l,r?(s.window.set(t.subarray(n-r,n),0),s.wnext=r,s.whave=s.wsize):(s.wnext+=l,s.wnext===s.wsize&&(s.wnext=0),s.whave<s.wsize&&(s.whave+=l))),0},inflate$2=(e,t)=>{let n,r,l,s,c,o,d,u,U,B,R,p,g,h,m=0,N,D,y,b,F,v,j,K;const f=new Uint8Array(4);let Q,P;const w=new Uint8Array([16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15]);if(inflateStateCheck(e)||!e.output||!e.input&&e.avail_in!==0)return Z_STREAM_ERROR$1;n=e.state,n.mode===TYPE&&(n.mode=TYPEDO),c=e.next_out,l=e.output,d=e.avail_out,s=e.next_in,r=e.input,o=e.avail_in,u=n.hold,U=n.bits,B=o,R=d,K=Z_OK$1;e:for(;;)switch(n.mode){case HEAD:if(n.wrap===0){n.mode=TYPEDO;break}for(;U<16;){if(o===0)break e;o--,u+=r[s++]<<U,U+=8}if(n.wrap&2&&u===35615){n.wbits===0&&(n.wbits=15),n.check=0,f[0]=u&255,f[1]=u>>>8&255,n.check=crc32_1(n.check,f,2,0),u=0,U=0,n.mode=FLAGS;break}if(n.head&&(n.head.done=!1),!(n.wrap&1)||(((u&255)<<8)+(u>>8))%31){e.msg="incorrect header check",n.mode=BAD;break}if((u&15)!==Z_DEFLATED){e.msg="unknown compression method",n.mode=BAD;break}if(u>>>=4,U-=4,j=(u&15)+8,n.wbits===0&&(n.wbits=j),j>15||j>n.wbits){e.msg="invalid window size",n.mode=BAD;break}n.dmax=1<<n.wbits,n.flags=0,e.adler=n.check=1,n.mode=u&512?DICTID:TYPE,u=0,U=0;break;case FLAGS:for(;U<16;){if(o===0)break e;o--,u+=r[s++]<<U,U+=8}if(n.flags=u,(n.flags&255)!==Z_DEFLATED){e.msg="unknown compression method",n.mode=BAD;break}if(n.flags&57344){e.msg="unknown header flags set",n.mode=BAD;break}n.head&&(n.head.text=u>>8&1),n.flags&512&&n.wrap&4&&(f[0]=u&255,f[1]=u>>>8&255,n.check=crc32_1(n.check,f,2,0)),u=0,U=0,n.mode=TIME;case TIME:for(;U<32;){if(o===0)break e;o--,u+=r[s++]<<U,U+=8}n.head&&(n.head.time=u),n.flags&512&&n.wrap&4&&(f[0]=u&255,f[1]=u>>>8&255,f[2]=u>>>16&255,f[3]=u>>>24&255,n.check=crc32_1(n.check,f,4,0)),u=0,U=0,n.mode=OS;case OS:for(;U<16;){if(o===0)break e;o--,u+=r[s++]<<U,U+=8}n.head&&(n.head.xflags=u&255,n.head.os=u>>8),n.flags&512&&n.wrap&4&&(f[0]=u&255,f[1]=u>>>8&255,n.check=crc32_1(n.check,f,2,0)),u=0,U=0,n.mode=EXLEN;case EXLEN:if(n.flags&1024){for(;U<16;){if(o===0)break e;o--,u+=r[s++]<<U,U+=8}n.length=u,n.head&&(n.head.extra_len=u),n.flags&512&&n.wrap&4&&(f[0]=u&255,f[1]=u>>>8&255,n.check=crc32_1(n.check,f,2,0)),u=0,U=0}else n.head&&(n.head.extra=null);n.mode=EXTRA;case EXTRA:if(n.flags&1024&&(p=n.length,p>o&&(p=o),p&&(n.head&&(j=n.head.extra_len-n.length,n.head.extra||(n.head.extra=new Uint8Array(n.head.extra_len)),n.head.extra.set(r.subarray(s,s+p),j)),n.flags&512&&n.wrap&4&&(n.check=crc32_1(n.check,r,p,s)),o-=p,s+=p,n.length-=p),n.length))break e;n.length=0,n.mode=NAME;case NAME:if(n.flags&2048){if(o===0)break e;p=0;do j=r[s+p++],n.head&&j&&n.length<65536&&(n.head.name+=String.fromCharCode(j));while(j&&p<o);if(n.flags&512&&n.wrap&4&&(n.check=crc32_1(n.check,r,p,s)),o-=p,s+=p,j)break e}else n.head&&(n.head.name=null);n.length=0,n.mode=COMMENT;case COMMENT:if(n.flags&4096){if(o===0)break e;p=0;do j=r[s+p++],n.head&&j&&n.length<65536&&(n.head.comment+=String.fromCharCode(j));while(j&&p<o);if(n.flags&512&&n.wrap&4&&(n.check=crc32_1(n.check,r,p,s)),o-=p,s+=p,j)break e}else n.head&&(n.head.comment=null);n.mode=HCRC;case HCRC:if(n.flags&512){for(;U<16;){if(o===0)break e;o--,u+=r[s++]<<U,U+=8}if(n.wrap&4&&u!==(n.check&65535)){e.msg="header crc mismatch",n.mode=BAD;break}u=0,U=0}n.head&&(n.head.hcrc=n.flags>>9&1,n.head.done=!0),e.adler=n.check=0,n.mode=TYPE;break;case DICTID:for(;U<32;){if(o===0)break e;o--,u+=r[s++]<<U,U+=8}e.adler=n.check=zswap32(u),u=0,U=0,n.mode=DICT;case DICT:if(n.havedict===0)return e.next_out=c,e.avail_out=d,e.next_in=s,e.avail_in=o,n.hold=u,n.bits=U,Z_NEED_DICT$1;e.adler=n.check=1,n.mode=TYPE;case TYPE:if(t===Z_BLOCK||t===Z_TREES)break e;case TYPEDO:if(n.last){u>>>=U&7,U-=U&7,n.mode=CHECK;break}for(;U<3;){if(o===0)break e;o--,u+=r[s++]<<U,U+=8}switch(n.last=u&1,u>>>=1,U-=1,u&3){case 0:n.mode=STORED;break;case 1:if(fixedtables(n),n.mode=LEN_,t===Z_TREES){u>>>=2,U-=2;break e}break;case 2:n.mode=TABLE;break;case 3:e.msg="invalid block type",n.mode=BAD}u>>>=2,U-=2;break;case STORED:for(u>>>=U&7,U-=U&7;U<32;){if(o===0)break e;o--,u+=r[s++]<<U,U+=8}if((u&65535)!==(u>>>16^65535)){e.msg="invalid stored block lengths",n.mode=BAD;break}if(n.length=u&65535,u=0,U=0,n.mode=COPY_,t===Z_TREES)break e;case COPY_:n.mode=COPY;case COPY:if(p=n.length,p){if(p>o&&(p=o),p>d&&(p=d),p===0)break e;l.set(r.subarray(s,s+p),c),o-=p,s+=p,d-=p,c+=p,n.length-=p;break}n.mode=TYPE;break;case TABLE:for(;U<14;){if(o===0)break e;o--,u+=r[s++]<<U,U+=8}if(n.nlen=(u&31)+257,u>>>=5,U-=5,n.ndist=(u&31)+1,u>>>=5,U-=5,n.ncode=(u&15)+4,u>>>=4,U-=4,n.nlen>286||n.ndist>30){e.msg="too many length or distance symbols",n.mode=BAD;break}n.have=0,n.mode=LENLENS;case LENLENS:for(;n.have<n.ncode;){for(;U<3;){if(o===0)break e;o--,u+=r[s++]<<U,U+=8}n.lens[w[n.have++]]=u&7,u>>>=3,U-=3}for(;n.have<19;)n.lens[w[n.have++]]=0;if(n.lencode=n.lendyn,n.lenbits=7,Q={bits:n.lenbits},K=inftrees(CODES,n.lens,0,19,n.lencode,0,n.work,Q),n.lenbits=Q.bits,K){e.msg="invalid code lengths set",n.mode=BAD;break}n.have=0,n.mode=CODELENS;case CODELENS:for(;n.have<n.nlen+n.ndist;){for(;m=n.lencode[u&(1<<n.lenbits)-1],N=m>>>24,D=m>>>16&255,y=m&65535,!(N<=U);){if(o===0)break e;o--,u+=r[s++]<<U,U+=8}if(y<16)u>>>=N,U-=N,n.lens[n.have++]=y;else{if(y===16){for(P=N+2;U<P;){if(o===0)break e;o--,u+=r[s++]<<U,U+=8}if(u>>>=N,U-=N,n.have===0){e.msg="invalid bit length repeat",n.mode=BAD;break}j=n.lens[n.have-1],p=3+(u&3),u>>>=2,U-=2}else if(y===17){for(P=N+3;U<P;){if(o===0)break e;o--,u+=r[s++]<<U,U+=8}u>>>=N,U-=N,j=0,p=3+(u&7),u>>>=3,U-=3}else{for(P=N+7;U<P;){if(o===0)break e;o--,u+=r[s++]<<U,U+=8}u>>>=N,U-=N,j=0,p=11+(u&127),u>>>=7,U-=7}if(n.have+p>n.nlen+n.ndist){e.msg="invalid bit length repeat",n.mode=BAD;break}for(;p--;)n.lens[n.have++]=j}}if(n.mode===BAD)break;if(n.lens[256]===0){e.msg="invalid code -- missing end-of-block",n.mode=BAD;break}if(n.lenbits=9,Q={bits:n.lenbits},K=inftrees(LENS,n.lens,0,n.nlen,n.lencode,0,n.work,Q),n.lenbits=Q.bits,K){e.msg="invalid literal/lengths set",n.mode=BAD;break}if(n.distbits=6,n.distcode=n.distdyn,Q={bits:n.distbits},K=inftrees(DISTS,n.lens,n.nlen,n.ndist,n.distcode,0,n.work,Q),n.distbits=Q.bits,K){e.msg="invalid distances set",n.mode=BAD;break}if(n.mode=LEN_,t===Z_TREES)break e;case LEN_:n.mode=LEN;case LEN:if(o>=6&&d>=258){e.next_out=c,e.avail_out=d,e.next_in=s,e.avail_in=o,n.hold=u,n.bits=U,inffast(e,R),c=e.next_out,l=e.output,d=e.avail_out,s=e.next_in,r=e.input,o=e.avail_in,u=n.hold,U=n.bits,n.mode===TYPE&&(n.back=-1);break}for(n.back=0;m=n.lencode[u&(1<<n.lenbits)-1],N=m>>>24,D=m>>>16&255,y=m&65535,!(N<=U);){if(o===0)break e;o--,u+=r[s++]<<U,U+=8}if(D&&!(D&240)){for(b=N,F=D,v=y;m=n.lencode[v+((u&(1<<b+F)-1)>>b)],N=m>>>24,D=m>>>16&255,y=m&65535,!(b+N<=U);){if(o===0)break e;o--,u+=r[s++]<<U,U+=8}u>>>=b,U-=b,n.back+=b}if(u>>>=N,U-=N,n.back+=N,n.length=y,D===0){n.mode=LIT;break}if(D&32){n.back=-1,n.mode=TYPE;break}if(D&64){e.msg="invalid literal/length code",n.mode=BAD;break}n.extra=D&15,n.mode=LENEXT;case LENEXT:if(n.extra){for(P=n.extra;U<P;){if(o===0)break e;o--,u+=r[s++]<<U,U+=8}n.length+=u&(1<<n.extra)-1,u>>>=n.extra,U-=n.extra,n.back+=n.extra}n.was=n.length,n.mode=DIST;case DIST:for(;m=n.distcode[u&(1<<n.distbits)-1],N=m>>>24,D=m>>>16&255,y=m&65535,!(N<=U);){if(o===0)break e;o--,u+=r[s++]<<U,U+=8}if(!(D&240)){for(b=N,F=D,v=y;m=n.distcode[v+((u&(1<<b+F)-1)>>b)],N=m>>>24,D=m>>>16&255,y=m&65535,!(b+N<=U);){if(o===0)break e;o--,u+=r[s++]<<U,U+=8}u>>>=b,U-=b,n.back+=b}if(u>>>=N,U-=N,n.back+=N,D&64){e.msg="invalid distance code",n.mode=BAD;break}n.offset=y,n.extra=D&15,n.mode=DISTEXT;case DISTEXT:if(n.extra){for(P=n.extra;U<P;){if(o===0)break e;o--,u+=r[s++]<<U,U+=8}n.offset+=u&(1<<n.extra)-1,u>>>=n.extra,U-=n.extra,n.back+=n.extra}if(n.offset>n.dmax){e.msg="invalid distance too far back",n.mode=BAD;break}n.mode=MATCH;case MATCH:if(d===0)break e;if(p=R-d,n.offset>p){if(p=n.offset-p,p>n.whave&&n.sane){e.msg="invalid distance too far back",n.mode=BAD;break}p>n.wnext?(p-=n.wnext,g=n.wsize-p):g=n.wnext-p,p>n.length&&(p=n.length),h=n.window}else h=l,g=c-n.offset,p=n.length;p>d&&(p=d),d-=p,n.length-=p;do l[c++]=h[g++];while(--p);n.length===0&&(n.mode=LEN);break;case LIT:if(d===0)break e;l[c++]=n.length,d--,n.mode=LEN;break;case CHECK:if(n.wrap){for(;U<32;){if(o===0)break e;o--,u|=r[s++]<<U,U+=8}if(R-=d,e.total_out+=R,n.total+=R,n.wrap&4&&R&&(e.adler=n.check=n.flags?crc32_1(n.check,l,R,c-R):adler32_1(n.check,l,R,c-R)),R=d,n.wrap&4&&(n.flags?u:zswap32(u))!==n.check){e.msg="incorrect data check",n.mode=BAD;break}u=0,U=0}n.mode=LENGTH;case LENGTH:if(n.wrap&&n.flags){for(;U<32;){if(o===0)break e;o--,u+=r[s++]<<U,U+=8}if(n.wrap&4&&u!==(n.total&4294967295)){e.msg="incorrect length check",n.mode=BAD;break}u=0,U=0}n.mode=DONE;case DONE:K=Z_STREAM_END$1;break e;case BAD:K=Z_DATA_ERROR$1;break e;case MEM:return Z_MEM_ERROR$1;case SYNC:default:return Z_STREAM_ERROR$1}return e.next_out=c,e.avail_out=d,e.next_in=s,e.avail_in=o,n.hold=u,n.bits=U,(n.wsize||R!==e.avail_out&&n.mode<BAD&&(n.mode<CHECK||t!==Z_FINISH$1))&&updatewindow(e,e.output,e.next_out,R-e.avail_out),B-=e.avail_in,R-=e.avail_out,e.total_in+=B,e.total_out+=R,n.total+=R,n.wrap&4&&R&&(e.adler=n.check=n.flags?crc32_1(n.check,l,R,e.next_out-R):adler32_1(n.check,l,R,e.next_out-R)),e.data_type=n.bits+(n.last?64:0)+(n.mode===TYPE?128:0)+(n.mode===LEN_||n.mode===COPY_?256:0),(B===0&&R===0||t===Z_FINISH$1)&&K===Z_OK$1&&(K=Z_BUF_ERROR),K},inflateEnd=e=>{if(inflateStateCheck(e))return Z_STREAM_ERROR$1;let t=e.state;return t.window&&(t.window=null),e.state=null,Z_OK$1},inflateGetHeader=(e,t)=>{if(inflateStateCheck(e))return Z_STREAM_ERROR$1;const n=e.state;return n.wrap&2?(n.head=t,t.done=!1,Z_OK$1):Z_STREAM_ERROR$1},inflateSetDictionary=(e,t)=>{const n=t.length;let r,l,s;return inflateStateCheck(e)||(r=e.state,r.wrap!==0&&r.mode!==DICT)?Z_STREAM_ERROR$1:r.mode===DICT&&(l=1,l=adler32_1(l,t,n,0),l!==r.check)?Z_DATA_ERROR$1:(s=updatewindow(e,t,n,n),s?(r.mode=MEM,Z_MEM_ERROR$1):(r.havedict=1,Z_OK$1))};var inflateReset_1=inflateReset,inflateReset2_1=inflateReset2,inflateResetKeep_1=inflateResetKeep,inflateInit_1=inflateInit,inflateInit2_1=inflateInit2,inflate_2$1=inflate$2,inflateEnd_1=inflateEnd,inflateGetHeader_1=inflateGetHeader,inflateSetDictionary_1=inflateSetDictionary,inflateInfo="pako inflate (from Nodeca project)",inflate_1$2={inflateReset:inflateReset_1,inflateReset2:inflateReset2_1,inflateResetKeep:inflateResetKeep_1,inflateInit:inflateInit_1,inflateInit2:inflateInit2_1,inflate:inflate_2$1,inflateEnd:inflateEnd_1,inflateGetHeader:inflateGetHeader_1,inflateSetDictionary:inflateSetDictionary_1,inflateInfo};function GZheader(){this.text=0,this.time=0,this.xflags=0,this.os=0,this.extra=null,this.extra_len=0,this.name="",this.comment="",this.hcrc=0,this.done=!1}var gzheader=GZheader;const toString=Object.prototype.toString,{Z_NO_FLUSH,Z_FINISH,Z_OK,Z_STREAM_END,Z_NEED_DICT,Z_STREAM_ERROR,Z_DATA_ERROR,Z_MEM_ERROR}=constants$2;function Inflate$1(e){this.options=common.assign({chunkSize:1024*64,windowBits:15,to:""},e||{});const t=this.options;t.raw&&t.windowBits>=0&&t.windowBits<16&&(t.windowBits=-t.windowBits,t.windowBits===0&&(t.windowBits=-15)),t.windowBits>=0&&t.windowBits<16&&!(e&&e.windowBits)&&(t.windowBits+=32),t.windowBits>15&&t.windowBits<48&&(t.windowBits&15||(t.windowBits|=15)),this.err=0,this.msg="",this.ended=!1,this.chunks=[],this.strm=new zstream,this.strm.avail_out=0;let n=inflate_1$2.inflateInit2(this.strm,t.windowBits);if(n!==Z_OK)throw new Error(messages[n]);if(this.header=new gzheader,inflate_1$2.inflateGetHeader(this.strm,this.header),t.dictionary&&(typeof t.dictionary=="string"?t.dictionary=strings.string2buf(t.dictionary):toString.call(t.dictionary)==="[object ArrayBuffer]"&&(t.dictionary=new Uint8Array(t.dictionary)),t.raw&&(n=inflate_1$2.inflateSetDictionary(this.strm,t.dictionary),n!==Z_OK)))throw new Error(messages[n])}Inflate$1.prototype.push=function(e,t){const n=this.strm,r=this.options.chunkSize,l=this.options.dictionary;let s,c,o;if(this.ended)return!1;for(t===~~t?c=t:c=t===!0?Z_FINISH:Z_NO_FLUSH,toString.call(e)==="[object ArrayBuffer]"?n.input=new Uint8Array(e):n.input=e,n.next_in=0,n.avail_in=n.input.length;;){for(n.avail_out===0&&(n.output=new Uint8Array(r),n.next_out=0,n.avail_out=r),s=inflate_1$2.inflate(n,c),s===Z_NEED_DICT&&l&&(s=inflate_1$2.inflateSetDictionary(n,l),s===Z_OK?s=inflate_1$2.inflate(n,c):s===Z_DATA_ERROR&&(s=Z_NEED_DICT));n.avail_in>0&&s===Z_STREAM_END&&n.state.wrap>0&&e[n.next_in]!==0;)inflate_1$2.inflateReset(n),s=inflate_1$2.inflate(n,c);switch(s){case Z_STREAM_ERROR:case Z_DATA_ERROR:case Z_NEED_DICT:case Z_MEM_ERROR:return this.onEnd(s),this.ended=!0,!1}if(o=n.avail_out,n.next_out&&(n.avail_out===0||s===Z_STREAM_END))if(this.options.to==="string"){let d=strings.utf8border(n.output,n.next_out),u=n.next_out-d,U=strings.buf2string(n.output,d);n.next_out=u,n.avail_out=r-u,u&&n.output.set(n.output.subarray(d,d+u),0),this.onData(U)}else this.onData(n.output.length===n.next_out?n.output:n.output.subarray(0,n.next_out));if(!(s===Z_OK&&o===0)){if(s===Z_STREAM_END)return s=inflate_1$2.inflateEnd(this.strm),this.onEnd(s),this.ended=!0,!0;if(n.avail_in===0)break}}return!0};Inflate$1.prototype.onData=function(e){this.chunks.push(e)};Inflate$1.prototype.onEnd=function(e){e===Z_OK&&(this.options.to==="string"?this.result=this.chunks.join(""):this.result=common.flattenChunks(this.chunks)),this.chunks=[],this.err=e,this.msg=this.strm.msg};const{Deflate,deflate,deflateRaw,gzip}=deflate_1$1;var deflate_1=deflate,fromByteArray_1=fromByteArray,lookup=[],code="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";for(var i=0,len=code.length;i<len;++i)lookup[i]=code[i];function tripletToBase64(e){return lookup[e>>18&63]+lookup[e>>12&63]+lookup[e>>6&63]+lookup[e&63]}function encodeChunk(e,t,n){for(var r,l=[],s=t;s<n;s+=3)r=(e[s]<<16&16711680)+(e[s+1]<<8&65280)+(e[s+2]&255),l.push(tripletToBase64(r));return l.join("")}function fromByteArray(e){for(var t,n=e.length,r=n%3,l=[],s=16383,c=0,o=n-r;c<o;c+=s)l.push(encodeChunk(e,c,c+s>o?o:c+s));return r===1?(t=e[n-1],l.push(lookup[t>>2]+lookup[t<<4&63]+"==")):r===2&&(t=(e[n-2]<<8)+e[n-1],l.push(lookup[t>>10]+lookup[t>>4&63]+lookup[t<<2&63]+"=")),l.join("")}const encoder=new TextEncoder;new TextDecoder;function serializeHash(e){const t=JSON.stringify(e),n=encoder.encode(t),r=deflate_1(n);return fromByteArray_1(r)}async function getViews(){if(!Authentication.token)throw new Error("Not authenticated");return(await(await fetch(`${FORMANT_API_URL}/v1/admin/views`,{method:"GET",headers:{"Content-Type":"application/json",Authorization:"Bearer "+Authentication.token}})).json()).items}async function createShareLink(e,t){if(!Authentication.token)throw new Error("Not authenticated");const r=(await getViews()).filter(o=>o.name===t);if(r.length===0)return console.warn("View does not exist or it is misspell"),null;const l=await fetch(`${FORMANT_API_URL}/v1/admin/shares`,{method:"POST",body:JSON.stringify(e),headers:{"Content-Type":"application/json",Authorization:"Bearer "+Authentication.token}}),s=FORMANT_API_URL.replace("api","app"),{code:c}=await l.json();return`${s}/shares/${c}#${serializeHash({viewId:r[0].id})}`}const vailableAggregationIntervals=["day","week","month","year","hour","minute","quarter"],aggregateFunctions=["interval","start","end","sub","get"];function getVariance(e){return e.count<2?0:e.sumOfSquares/(e.count-1)}function getStandardDeviation(e){return Math.sqrt(getVariance(e))}function getMax(e){return e.max}function getMin(e){return e.min}function getAverage(e){return e.count===0?-1:e.sum/e.count}function getSum(e){return e.sum}function getCount(e){return e.count}const aggregateFunctionMap={min:getMin,max:getMax,"standard deviation":getStandardDeviation,average:getAverage,sum:getSum,count:getCount},aggregateByDateFunctions={day:{interval:eachDayOfInterval,start:startOfDay,end:endOfDay,sub:subDays,get:getDay},week:{interval:eachWeekOfInterval,start:startOfWeek,end:endOfWeek,sub:subWeeks,get:getWeek},month:{interval:eachMonthOfInterval,start:startOfMonth,end:endOfMonth,sub:subMonths,get:getMonth},year:{interval:eachYearOfInterval,start:startOfYear,end:endOfYear,sub:subYears,get:getYear},hour:{interval:eachHourOfInterval,start:startOfHour,end:endOfHour,sub:subHours,get:getHours},minute:{interval:eachMinuteOfInterval,start:startOfMinute,end:endOfMinute,sub:subMinutes,get:getMinutes},quarter:{interval:eachQuarterOfInterval,start:startOfQuarter,end:endOfQuarter,sub:subQuarters,get:getQuarter}},formatTimeFrameText=(e,t)=>e.split("/")[0]+"/"+e.split("/")[1]+"–"+t.split("/")[0]+"/"+t.split("/")[1];async function queryEvents(e){if(!Authentication.token)throw new Error("Not authenticated");return(await(await fetch(`${FORMANT_API_URL}/v1/admin/events/query`,{method:"POST",body:JSON.stringify(e),headers:{"Content-Type":"application/json",Authorization:"Bearer "+Authentication.token}})).json()).items}async function eventsCounter(e,t,n,r,l){const s=aggregateByDateFunctions[t];return await Promise.all(Array(n).fill(0).map(async(c,o)=>{const d=new Date(r),u=s.sub(s.start(d),n-o-1),U=s.sub(s.end(d),n-o-1),B=formatTimeFrameText(u.toLocaleDateString(),U.toLocaleDateString()),R=await queryEvents({...l,eventTypes:e,start:new Date(u).toISOString(),end:new Date(U).toISOString()});return{date:B,events:R}}))}async function getAnnotationCount(e,t){return(await queryEvents({...e,eventTypes:["annotation"]})).filter(s=>!!s.tags&&Object.keys(s.tags).includes(t)).reduce((s,c)=>{const o=c.tags[t];return o in s?(s[o]+=1,s):(s[o]=1,s)},{})}async function getAnnotationCountByIntervals(e,t,n){const{end:r,start:l}=e,c=aggregateByDateFunctions[n].interval({start:new Date(l),end:new Date(r)}),o=c.map((u,U)=>{const B=new Date(u).toISOString(),R=U===c.length-1?new Date(Date.now()).toISOString():new Date(c[U+1]);return getAnnotationCount({...e,start:B,end:R},t)}),d=await Promise.all(o);return c.map((u,U)=>({date:new Date(u).toISOString(),annotations:d[U]}))}async function getTelemetry(e,t,n,r,l,s){let c=e;Array.isArray(e)||(c=[e]);let o=t;return Array.isArray(t)||(o=[t]),(await(await fetch(`${FORMANT_API_URL}/v1/queries/queries`,{method:"POST",body:JSON.stringify({deviceIds:c,end:r.toISOString(),names:o,start:n.toISOString(),tags:l,latestOnly:s}),headers:{"Content-Type":"application/json",Authorization:"Bearer "+Authentication.token}})).json()).items}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 getPeers(){if(!Authentication.token)throw new Error("Not authenticated");const e=defaultRtcClientPool.get();try{return await e.getPeers()}finally{await e.shutdown()}}async function createDevice(e){if(!Authentication.token)throw new Error("Not authenticated");return await(await fetch(`${FORMANT_API_URL}/v1/admin/devices`,{method:"POST",body:JSON.stringify(e),headers:{"Content-Type":"application/json",Authorization:"Bearer "+Authentication.token}})).json()}async function patchDevice(e,t){if(!Authentication.token)throw new Error("Not authenticated");return await(await fetch(`${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 getDevicesData(){if(!Authentication.token)throw new Error("Not authenticated");return(await(await fetch(`${FORMANT_API_URL}/v1/admin/device-details/query`,{method:"POST",body:JSON.stringify({enabled:!0,type:"default"}),headers:{"Content-Type":"application/json",Authorization:"Bearer "+Authentication.token}})).json()).items}async function queryDevicesData(e){if(!Authentication.token)throw new Error("Not authenticated");return(await(await fetch(`${FORMANT_API_URL}/v1/admin/devices/query`,{method:"POST",body:JSON.stringify(e),headers:{"Content-Type":"application/json",Authorization:"Bearer "+Authentication.token}})).json()).items}async function disableDevice(e){if(!Authentication.token)throw new Error("Not authenticated");return await(await fetch(`${FORMANT_API_URL}/v1/admin/devices/${e}/disable`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:"Bearer "+Authentication.token}})).json()}class Device extends BaseDevice{constructor(t,n,r,l){super(),this.id=t,this.name=n,this.organizationId=r,this.tags=l}async getLatestTelemetry(){return(await(await fetch(`${FORMANT_API_URL}/v1/queries/stream-current-value`,{method:"POST",body:JSON.stringify({deviceIds:[this.id]}),headers:{"Content-Type":"application/json",Authorization:"Bearer "+Authentication.token}})).json()).items}async getConfiguration(t=!1){let n=await fetch(`${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 l=t?r.desiredConfigurationVersion:r.state.reportedConfiguration.version;return n=await fetch(`${FORMANT_API_URL}/v1/admin/devices/${this.id}/configurations/${l}`,{method:"GET",headers:{"Content-Type":"application/json",Authorization:"Bearer "+Authentication.token}}),(await n.json()).document}async getAgentVersion(){var r;const n=await(await fetch(`${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(`${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:l=3}=typeof t=="number"?{sessionType:t}:t,c=getRtcClientPool({sessionType:n}).get(this.handleMessage);let o=!1;const d=new Promise((U,B)=>setTimeout(()=>{o=!0,B(new Error("Connection timed out: the connection could not be finalized in time, possibly due to network issues or misconfigured settings."))},r)),u=async()=>{if("isReady"in c)for(;!c.isReady();)this.assertNotCancelled(o),await delay(100);const U=await this.getRemoteDevicePeerId(c);this.assertNotCancelled(o);let B;for(let p=0;p<l&&(B=await c.connect(U),!B);p++)delay(100),this.assertNotCancelled(o);if(!B)throw new Error(`Session could not be created: exhausted ${l} retries`);let R=0;for(;!o&&c.getConnectionStatus(U)!=="connected";)await delay(100),R+=1;return this.assertNotCancelled(o),console.debug(`${new Date().toISOString()} :: Connection completed after ${R} retries`),U};return Promise.race([u(),d]).then(U=>{this.remoteDevicePeerId=U,this.initConnectionMonitoring(),this.rtcClient=c,this.emit("connect")}).catch(U=>{throw console.debug(`${new Date().toISOString()} :: Connection failed: %o`,U),this.remoteDevicePeerId=null,c.shutdown().catch(B=>{console.error("rtcClient cannot shutdown: %o",B)}),this.emit("connection_failed",U),U})}async getRemoteDevicePeerId(t){const r=(await t.getPeers()).find(l=>l.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(l=>l.getRemotePeerId()===this.remoteDevicePeerId&&l.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(l=>l.deviceId===this.id);return r?n[r.id].length>0:!1}async getAvailableCommands(){return(await(await fetch(`${FORMANT_API_URL}/v1/admin/command-templates/`,{method:"GET",headers:{"Content-Type":"application/json",Authorization:"Bearer "+Authentication.token}})).json()).items.map(r=>({name:r.name,id:r.id,command:r.command,description:r.description,parameterEnabled:r.parameterEnabled,parameterValue:r.parameterValue,parameterMeta:r.parameterMeta,enabled:r.enabled,tags:r.tags}))}async sendCommand(t,n,r,l){var U;const c=(await this.getAvailableCommands()).find(B=>B.name===t);if(!c)throw new Error(`Could not find command with name "${t}"`);let o="";n===void 0?c.parameterEnabled&&c.parameterValue&&(o=c.parameterValue):o=n;let d={value:o,scrubberTime:(r||new Date).toISOString(),meta:{...c.parameterMeta,...l}};return await fetch(`${FORMANT_API_URL}/v1/admin/commands`,{method:"POST",body:JSON.stringify({commandTemplateId:c.id,organizationId:this.organizationId,deviceId:this.id,command:c.command,parameter:d,userId:(U=Authentication.currentUser)==null?void 0:U.id}),headers:{"Content-Type":"application/json",Authorization:"Bearer "+Authentication.token}})}async getCommand(t){return await fetch(`${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(`${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,l,s,c,o){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,l,o)}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 o,d;const t=await this.getConfiguration(),n=await fetch(`${FORMANT_API_URL}/v1/queries/metadata/stream-names`,{method:"POST",body:JSON.stringify({deviceIds:[this.id]}),headers:{"Content-Type":"application/json",Authorization:"Bearer "+Authentication.token}}),r=[],l=[];return(d=(o=t.telemetry)==null?void 0:o.streams)==null||d.forEach(u=>{u.disabled!==!0&&r.push(u.name),u.onDemand===!0&&l.push(u.name)}),console.log(l),(await n.json()).items.filter(u=>!r.includes(u)).map(u=>({name:u,onDemand:l.includes(u)}))}async createInterventionRequest(t,n,r,l){return await(await fetch(`${FORMANT_API_URL}/v1/admin/intervention-requests`,{method:"POST",body:JSON.stringify({message:t,interventionType:n,time:new Date().toISOString(),deviceId:this.id,tags:l,data:r}),headers:{"Content-Type":"application/json",Authorization:"Bearer "+Authentication.token}})).json()}async addInterventionResponse(t,n,r){return await(await fetch(`${FORMANT_API_URL}/v1/admin/intervention-responses`,{method:"POST",body:JSON.stringify({interventionId:t,interventionType:n,data:r}),headers:{"Content-Type":"application/json",Authorization:"Bearer "+Authentication.token}})).json()}async getAnnotationCount(t,n){return await 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,l,s){return await eventsCounter(t,n,r,l,{...s,deviceIds:[this.id]})}async createShareLink(t,n){return t.scope.deviceIds=[this.id],await createShareLink(t,n)}}Fe(Device,"createDevice",createDevice),Fe(Device,"patchDevice",patchDevice),Fe(Device,"getDevicesData",getDevicesData),Fe(Device,"queryDevicesData",queryDevicesData),Fe(Device,"disableDevice",disableDevice);class PeerDevice extends BaseDevice{constructor(n){super();Fe(this,"id");Fe(this,"telemetryStreamActive",!1);Fe(this,"streamTelemetry",{});this.peerUrl=n}async getLatestTelemetry(){this.telemetryStreamActive||this.subscribeToTelemetry();const n=this.streamTelemetry;return Object.entries(n).map(([l,s])=>({deviceId:this.id,streamName:l,streamType:"json",currentValue:s,currentValueTime:s.timestamp,tags:{}}))}async getTelemetry(n,r,l,s,c,o,d){if(Array.isArray(n))throw new Error("Multiple stream names not supported");if(s)throw new Error("Tags not supported");if(d&&c===void 0)c=1;else if(d&&c!==void 0)throw new Error("latestOnly and limit cannot be used together");let u=`${this.peerUrl}/v1/querydatapoints?stream_name=${n}&start=${r.toISOString()}&end=${l.toISOString()}`;c!=null&&c>0&&(u+=`&limit=${c}`),o!=null&&o>=0&&(u+=`&offset=${o}`);const B=await(await fetch(u)).json(),R=[];for(const p of B.results){const g=parseInt(p.timestamp),h=p.tags.data_type;delete p.tags.data_type,R.push({deviceId:this.id,name:p.stream,points:[[g,this.getPointPayload(h,p)]],tags:p.tags,type:h})}return R.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 l=`${this.peerUrl}/v1/queryevents?start=${n.start}&end=${n.end}`;n.count!=null&&n.count>0&&(l+=`&limit=${n.count}`),n.offset!=null&&n.offset>=0&&(l+=`&offset=${n.offset}`);const c=await(await fetch(l)).json(),o=[];for(const d of c.results){const u=parseInt(d.timestamp),U={deviceId:this.id,time:new Date(u).toISOString(),message:d.message,notificationEnabled:d.notificationEnabled};d.id!==""&&(U.id=d.id),d.type!==""&&(U.type=d.type),d.streamName!==""&&(U.streamName=d.streamName),d.streamType!==""&&(U.streamType=d.streamType),d.severity!==""&&(U.severity=d.severity.toLowerCase()),d.tags&&(U.tags=d.tags),d.endTimestamp!=="0"&&(U.endTime=new Date(parseInt(d.endTimestamp)).toISOString()),o.push(U)}return o.reverse()}checkKeysAndThrow(n,r){const l=r.filter(s=>s in n);if(l.length>0)throw new Error(`Filters not currently supported: ${l.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 l=[],s=[];for(const c of r.bitset.bits)l.push(c.key),s.push(c.value);return{keys:l,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",l=>{this.handleXHRError("error")}),r.addEventListener("abort",l=>{this.handleXHRError("abort")}),r.addEventListener("timeout",l=>{this.handleXHRError("timeout")}),r.addEventListener("readystatechange",l=>{r.readyState===XMLHttpRequest.DONE&&this.handleXHRError("closed")}),r.addEventListener("progress",l=>{const s=l.loaded,c=s-n;n=s,r.responseText.substr(-c).split(`
63
63
  `).forEach(u=>{var U;if(u.length>0){const B=JSON.parse(u);if((U=B.result)!=null&&U.datapoint){const R=B.result.datapoint,p=R.stream;delete R.stream,this.streamTelemetry[p]=R}}})}),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 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(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,l,s){const c={value:r,scrubberTime:(l||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(`${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(`${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(`${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(`${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(`${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(`${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(`${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(`${FORMANT_API_URL}/v1/admin/groups/`+t,{headers:{"Content-Type":"application/json",Authorization:"Bearer "+Authentication.token}}),{tagKey:r,tagValue:l}=await n.json();return await queryDevices({tags:{[r]:[l]},enabled:!0,type:"default"})}async function getDevice(e){if(!Authentication.token)throw new Error("Not authenticated");const n=await(await fetch(`${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(`${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(`${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(`${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(`${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(`${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(`${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(l=>!!l);return t.length===0?[]:(await(await fetch(`${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(`${FORMANT_API_URL}/v1/queries/online-devices`,{method:"GET",headers:{"Content-Type":"application/json",Authorization:"Bearer "+Authentication.token}})).json()).items;return(await getDevices()).filter(l=>n.includes(l.id))}async function getRealtimeDevices(){if(!Authentication.token)throw new Error("Not authenticated");const n=(await(await fetch(`${FORMANT_API_URL}/v1/signaling/peers`,{method:"GET",headers:{"Content-Type":"application/json",Authorization:"Bearer "+Authentication.token}})).json()).items.map(l=>l.deviceId);return(await getDevices()).filter(l=>n.includes(l.id))}async function getStreams(){if(!Authentication.token)throw new Error("Not authenticated");return(await(await fetch(`${FORMANT_API_URL}/v1/admin/streams`,{method:"GET",headers:{"Content-Type":"application/json",Authorization:"Bearer "+Authentication.token}})).json()).items.filter(n=>n.enabled)}async function getTaskReportRows(e){if(!Authentication.token)throw new Error("Not authenticated");return await(await fetch(`${FORMANT_API_URL}/v1/queries/analytics/task-report-rows`,{method:"POST",body:JSON.stringify(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(`${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(`${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(`${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(`${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(`${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(`${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(`${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(`${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(`${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(`${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 ft=class{static async setDefaultDevice(t){ft.defaultDeviceId=t}static async getCurrentDevice(){if(!Authentication.token)throw new Error("Not authenticated");if(!ft.defaultDeviceId)throw new Error("No known default device");const r=(await(await fetch(`${FORMANT_API_URL}/v1/admin/device-details/query`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:"Bearer "+Authentication.token}})).json()).items.find(c=>c.id===ft.defaultDeviceId),l=r.name,s=new Device(ft.defaultDeviceId,l,defined$1(Authentication.currentOrganization),r.tags);return ft.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 ft.knownContext.push(new WeakRef(n)),n}};let Fleet=ft;Fe(Fleet,"defaultDeviceId"),Fe(Fleet,"knownContext",[]),Fe(Fleet,"createFleet",createFleet),Fe(Fleet,"listFleets",listFleets),Fe(Fleet,"getFleet",getFleet),Fe(Fleet,"patchFleet",patchFleet),Fe(Fleet,"deleteFleet",deleteFleet),Fe(Fleet,"addDeviceToFleet",addDeviceToFleet),Fe(Fleet,"getFleetDevices",getFleetDevices),Fe(Fleet,"aggregateTelemetry",aggregateTelemetry),Fe(Fleet,"createShareLink",createShareLink),Fe(Fleet,"eventsCounter",eventsCounter),Fe(Fleet,"getAnalyticStreams",getAnalyticStreams),Fe(Fleet,"getAnalyticsModules",getAnalyticsModules),Fe(Fleet,"getAnalyticsRows",getAnalyticsRows),Fe(Fleet,"getAnnotationCount",getAnnotationCount),Fe(Fleet,"getAnnotationCountByIntervals",getAnnotationCountByIntervals),Fe(Fleet,"getCurrentGroup",getCurrentGroup),Fe(Fleet,"getDevices",getDevices),Fe(Fleet,"getEvent",getEvent),Fe(Fleet,"getFileUrl",getFileUrl),Fe(Fleet,"getInterventions",getInterventions),Fe(Fleet,"getLatestTelemetry",getLatestTelemetry),Fe(Fleet,"getOnlineDevices",getOnlineDevices),Fe(Fleet,"getPeers",getPeers),Fe(Fleet,"getRealtimeDevices",getRealtimeDevices),Fe(Fleet,"getRealtimeSessions",getRealtimeSessions),Fe(Fleet,"getStreams",getStreams),Fe(Fleet,"getTaskReportRows",getTaskReportRows),Fe(Fleet,"getTaskReportTables",getTaskReportTables),Fe(Fleet,"getTelemetry",getTelemetry),Fe(Fleet,"getViews",getViews),Fe(Fleet,"patchStream",patchStream),Fe(Fleet,"patchView",patchView),Fe(Fleet,"queryAnalytics",queryAnalytics),Fe(Fleet,"queryDevices",queryDevices),Fe(Fleet,"queryEvents",queryEvents),Fe(Fleet,"queryTelemetry",queryTelemetry),Fe(Fleet,"getAllEventTriggerGroup",getAllEventTriggerGroup),Fe(Fleet,"getEventTriggerGroup",getEventTriggerGroup),Fe(Fleet,"patchEventTriggergroup",patchEventTriggerGroup);class KeyValue{static async set(t,n,r){try{const l=await fetch(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 l.json();if(l.status!==200)throw new Error(s.message)}catch(l){throw l}}static async get(t){try{const n=await fetch(FORMANT_API_URL+`/v1/admin/key-value/${t}`,{method:"GET",headers:{"Content-Type":"application/json",Authorization:"Bearer "+Authentication.token}}),r=await n.json();if(n.status!==200)throw new Error(r.message);return r.value}catch(n){throw n}}static async list(){try{const t=await fetch(FORMANT_API_URL+"/v1/admin/key-value",{method:"GET",headers:{"Content-Type":"application/json",Authorization:"Bearer "+Authentication.token}}),n=await t.json();if(t.status!==200)throw new Error(n.message);return n.items}catch(t){throw t}}static async delete(t){try{if(!(await fetch(FORMANT_API_URL+`/v1/admin/key-value/${t}`,{method:"DELETE",headers:{"Content-Type":"application/json",Authorization:"Bearer "+Authentication.token}})).ok)throw new Error("Unable to handle request");return}catch(n){throw n}}static async query(t){try{const n=await fetch(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}}}function stringToArrayBuffer(e){return Uint8Array.from(base64Exports.decode(e),t=>t.charCodeAt(0))}function fork$1(e){}function browser(){const{userAgent:e}=navigator;return e?e.includes("Firefox/")?"Firefox":e.includes("Edg/")?"Edge":e.includes("Chrome/")?"Chrome":e.includes("Safari/")?"Safari":e.includes("MSIE/")||e.includes("Trident/")?"IE":"Other":"Other"}const rtcAudioChunkStreamType="audio-chunk";class AudioPlayer{constructor(t,n){Fe(this,"muted",!1);Fe(this,"hasReceivedData",!1);Fe(this,"audioContext");Fe(this,"chunks",[]);Fe(this,"isPlaying",!1);Fe(this,"startTime",0);Fe(this,"lastChunkOffset",0);Fe(this,"bufferSize",3);Fe(this,"receive",async t=>{var c;const n=(c=t.payload.audioChunk)==null?void 0:c.chunk_data;if(!n)return;this.hasReceivedData||(this.hasReceivedData=!0);const{audioContext:r,muted:l}=this;if(!r||t.header.stream.streamType!==rtcAudioChunkStreamType||l!==!1)return;const s=stringToArrayBuffer(n);try{await r.decodeAudioData(s.buffer,this.scheduleChunk)}catch(o){console.warn("Error decoding audio buffer, changing audioWireFormat on agent",{error:o}),this.changeAudioWireFormat("wav")}});Fe(this,"scheduleChunk",t=>{const{audioContext:n}=this;if(!n)return;(this.chunks.length>this.bufferSize||this.isPlaying===!1)&&(this.chunks.forEach(l=>{l.stop()}),this.isPlaying=!1,this.chunks=[]);const r=this.createChunk(t);r&&r.buffer&&(this.isPlaying===!1&&(this.startTime=n.currentTime,this.lastChunkOffset=0,this.isPlaying=!0),r.start(this.startTime+this.lastChunkOffset,0,t.duration),this.lastChunkOffset+=r.buffer.duration,this.chunks.push(r))});this.device=t,this.stream=n,this.device.startListeningToRealtimeDataStream(n),this.device.addRealtimeListener((l,s)=>{this.receive(s)}),browser()==="Safari"||browser()==="IE"?this.changeAudioWireFormat("wav"):this.changeAudioWireFormat("opus");const r=window.AudioContext||window.webkitAudioContext;this.audioContext=new r}async play(){var t,n;((t=this.audioContext)==null?void 0:t.state)==="suspended"&&await((n=this.audioContext)==null?void 0:n.resume()),this.muted=!1}async pause(){await this.audioContext.suspend(),this.muted=!0}destroy(){this.device.stopListeningToRealtimeDataStream(this.stream)}createChunk(t){const{audioContext:n}=this;if(!n)return;const r=n.createBufferSource();return r.buffer=t,r.connect(n.destination),r.loop=!1,r.onended=l=>{this.chunks.splice(this.chunks.indexOf(r),1),this.chunks.length===0&&(this.isPlaying=!1)},r}changeAudioWireFormat(t){const{stream:n}=this;(async()=>await this.device.changeStreamAudioType(n.name,t))()}}class Account{static async listAccounts(){if(!Authentication.token)throw new Error("Not authenticated");return(await(await fetch(`${FORMANT_API_URL}/v1/admin/accounts`,{method:"GET",headers:{"Content-Type":"application/json",Authorization:"Bearer "+Authentication.token}})).json()).items}static async createAccounts(t){if(!Authentication.token)throw new Error("Not authenticated");return await(await fetch(`${FORMANT_API_URL}/v1/admin/accounts`,{method:"POST",body:JSON.stringify(t),headers:{"Content-Type":"application/json",Authorization:"Bearer "+Authentication.token}})).json()}static async getAccount(t){if(!Authentication.token)throw new Error("Not authenticated");return await(await fetch(`${FORMANT_API_URL}/v1/admin/accounts/${t}`,{method:"GET",headers:{"Content-Type":"application/json",Authorization:"Bearer "+Authentication.token}})).json()}static async patchAccount(t,n){if(!Authentication.token)throw new Error("Not authenticated");return await(await fetch(`${FORMANT_API_URL}/v1/admin/accounts/${t}`,{method:"PATCH",body:JSON.stringify(n),headers:{"Content-Type":"application/json",Authorization:"Bearer "+Authentication.token}})).json()}static async deleteAccount(t){if(!Authentication.token)throw new Error("Not authenticated");if(!(await fetch(`${FORMANT_API_URL}/v1/admin/accounts/${t}`,{method:"DELETE",headers:{"Content-Type":"application/json",Authorization:"Bearer "+Authentication.token}})).ok)throw new Error("Unable to delete account")}static async getAccountTree(t){if(!Authentication.token)throw new Error("Not authenticated");return await(await fetch(`${FORMANT_API_URL}/v1/admin/accounts/${t}/tree`,{method:"GET",headers:{"Content-Type":"application/json",Authorization:"Bearer "+Authentication.token}})).json()}}class Role{static async listRoles(){if(!Authentication.token)throw new Error("Not authenticated");return(await(await fetch(`${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(`${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(`${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(`${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(`${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(`${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(`${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(`${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(`${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(`${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}})}}const accessLevels=["viewer","operator","administrator"],viewer="viewer",operator="operator",administrator="administrator",aggregateLevels=["year","month","week","day","hour","minute"],annotationTypes=["tag","sheet","user"],eventTypes=["triggered-event","datapoint-event","device-online","device-offline","intervention-request","teleop-session-record","port-forwarding-session-record","command-request","command-response","command-delivery","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 signaling_pb={};(function(e){var t=require$$0,n=t,r=typeof globalThis!="undefined"&&globalThis||typeof window!="undefined"&&window||typeof r!="undefined"&&r||typeof self!="undefined"&&self||function(){return this}.call(null)||Function("return this")(),l=require$$1;n.object.extend(proto,l),n.exportSymbol("proto.v1.signaling.api.CreatePeerRequest",null,r),n.exportSymbol("proto.v1.signaling.api.CreatePeerResponse",null,r),n.exportSymbol("proto.v1.signaling.api.DeletePeerRequest",null,r),n.exportSymbol("proto.v1.signaling.api.DeletePeerResponse",null,r),n.exportSymbol("proto.v1.signaling.api.GetHealthRequest",null,r),n.exportSymbol("proto.v1.signaling.api.GetHealthResponse",null,r),n.exportSymbol("proto.v1.signaling.api.GetIceServersRequest",null,r),n.exportSymbol("proto.v1.signaling.api.GetIceServersResponse",null,r),n.exportSymbol("proto.v1.signaling.api.GetPeersRequest",null,r),n.exportSymbol("proto.v1.signaling.api.GetPeersResponse",null,r),n.exportSymbol("proto.v1.signaling.api.GetSessionsRequest",null,r),n.exportSymbol("proto.v1.signaling.api.GetSessionsResponse",null,r),n.exportSymbol("proto.v1.signaling.api.Peer",null,r),n.exportSymbol("proto.v1.signaling.api.ReceiveSignalStreamRequest",null,r),n.exportSymbol("proto.v1.signaling.api.ReceiveSignalStreamResponse",null,r),n.exportSymbol("proto.v1.signaling.api.RefreshPeerRequest",null,r),n.exportSymbol("proto.v1.signaling.api.RefreshPeerResponse",null,r),n.exportSymbol("proto.v1.signaling.api.RtcSession",null,r),n.exportSymbol("proto.v1.signaling.api.SendSignalRequest",null,r),n.exportSymbol("proto.v1.signaling.api.SendSignalResponse",null,r),n.exportSymbol("proto.v1.signaling.api.SessionType",null,r),n.exportSymbol("proto.v1.signaling.api.Signal",null,r),proto.v1.signaling.api.Peer=function(s){t.Message.initialize(this,s,0,-1,proto.v1.signaling.api.Peer.repeatedFields_,null)},n.inherits(proto.v1.signaling.api.Peer,t.Message),n.DEBUG&&!COMPILED&&(proto.v1.signaling.api.Peer.displayName="proto.v1.signaling.api.Peer"),proto.v1.signaling.api.Signal=function(s){t.Message.initialize(this,s,0,-1,null,null)},n.inherits(proto.v1.signaling.api.Signal,t.Message),n.DEBUG&&!COMPILED&&(proto.v1.signaling.api.Signal.displayName="proto.v1.signaling.api.Signal"),proto.v1.signaling.api.RtcSession=function(s){t.Message.initialize(this,s,0,-1,null,null)},n.inherits(proto.v1.signaling.api.RtcSession,t.Message),n.DEBUG&&!COMPILED&&(proto.v1.signaling.api.RtcSession.displayName="proto.v1.signaling.api.RtcSession"),proto.v1.signaling.api.GetSessionsRequest=function(s){t.Message.initialize(this,s,0,-1,null,null)},n.inherits(proto.v1.signaling.api.GetSessionsRequest,t.Message),n.DEBUG&&!COMPILED&&(proto.v1.signaling.api.GetSessionsRequest.displayName="proto.v1.signaling.api.GetSessionsRequest"),proto.v1.signaling.api.GetSessionsResponse=function(s){t.Message.initialize(this,s,0,-1,proto.v1.signaling.api.GetSessionsResponse.repeatedFields_,null)},n.inherits(proto.v1.signaling.api.GetSessionsResponse,t.Message),n.DEBUG&&!COMPILED&&(proto.v1.signaling.api.GetSessionsResponse.displayName="proto.v1.signaling.api.GetSessionsResponse"),proto.v1.signaling.api.GetHealthRequest=function(s){t.Message.initialize(this,s,0,-1,null,null)},n.inherits(proto.v1.signaling.api.GetHealthRequest,t.Message),n.DEBUG&&!COMPILED&&(proto.v1.signaling.api.GetHealthRequest.displayName="proto.v1.signaling.api.GetHealthRequest"),proto.v1.signaling.api.GetHealthResponse=function(s){t.Message.initialize(this,s,0,-1,null,null)},n.inherits(proto.v1.signaling.api.GetHealthResponse,t.Message),n.DEBUG&&!COMPILED&&(proto.v1.signaling.api.GetHealthResponse.displayName="proto.v1.signaling.api.GetHealthResponse"),proto.v1.signaling.api.CreatePeerRequest=function(s){t.Message.initialize(this,s,0,-1,null,null)},n.inherits(proto.v1.signaling.api.CreatePeerRequest,t.Message),n.DEBUG&&!COMPILED&&(proto.v1.signaling.api.CreatePeerRequest.displayName="proto.v1.signaling.api.CreatePeerRequest"),proto.v1.signaling.api.CreatePeerResponse=function(s){t.Message.initialize(this,s,0,-1,null,null)},n.inherits(proto.v1.signaling.api.CreatePeerResponse,t.Message),n.DEBUG&&!COMPILED&&(proto.v1.signaling.api.CreatePeerResponse.displayName="proto.v1.signaling.api.CreatePeerResponse"),proto.v1.signaling.api.DeletePeerRequest=function(s){t.Message.initialize(this,s,0,-1,null,null)},n.inherits(proto.v1.signaling.api.DeletePeerRequest,t.Message),n.DEBUG&&!COMPILED&&(proto.v1.signaling.api.DeletePeerRequest.displayName="proto.v1.signaling.api.DeletePeerRequest"),proto.v1.signaling.api.DeletePeerResponse=function(s){t.Message.initialize(this,s,0,-1,null,null)},n.inherits(proto.v1.signaling.api.DeletePeerResponse,t.Message),n.DEBUG&&!COMPILED&&(proto.v1.signaling.api.DeletePeerResponse.displayName="proto.v1.signaling.api.DeletePeerResponse"),proto.v1.signaling.api.RefreshPeerRequest=function(s){t.Message.initialize(this,s,0,-1,null,null)},n.inherits(proto.v1.signaling.api.RefreshPeerRequest,t.Message),n.DEBUG&&!COMPILED&&(proto.v1.signaling.api.RefreshPeerRequest.displayName="proto.v1.signaling.api.RefreshPeerRequest"),proto.v1.signaling.api.RefreshPeerResponse=function(s){t.Message.initialize(this,s,0,-1,null,null)},n.inherits(proto.v1.signaling.api.RefreshPeerResponse,t.Message),n.DEBUG&&!COMPILED&&(proto.v1.signaling.api.RefreshPeerResponse.displayName="proto.v1.signaling.api.RefreshPeerResponse"),proto.v1.signaling.api.GetPeersRequest=function(s){t.Message.initialize(this,s,0,-1,null,null)},n.inherits(proto.v1.signaling.api.GetPeersRequest,t.Message),n.DEBUG&&!COMPILED&&(proto.v1.signaling.api.GetPeersRequest.displayName="proto.v1.signaling.api.GetPeersRequest"),proto.v1.signaling.api.GetPeersResponse=function(s){t.Message.initialize(this,s,0,-1,proto.v1.signaling.api.GetPeersResponse.repeatedFields_,null)},n.inherits(proto.v1.signaling.api.GetPeersResponse,t.Message),n.DEBUG&&!COMPILED&&(proto.v1.signaling.api.GetPeersResponse.displayName="proto.v1.signaling.api.GetPeersResponse"),proto.v1.signaling.api.GetIceServersRequest=function(s){t.Message.initialize(this,s,0,-1,null,null)},n.inherits(proto.v1.signaling.api.GetIceServersRequest,t.Message),n.DEBUG&&!COMPILED&&(proto.v1.signaling.api.GetIceServersRequest.displayName="proto.v1.signaling.api.GetIceServersRequest"),proto.v1.signaling.api.GetIceServersResponse=function(s){t.Message.initialize(this,s,0,-1,null,null)},n.inherits(proto.v1.signaling.api.GetIceServersResponse,t.Message),n.DEBUG&&!COMPILED&&(proto.v1.signaling.api.GetIceServersResponse.displayName="proto.v1.signaling.api.GetIceServersResponse"),proto.v1.signaling.api.SendSignalRequest=function(s){t.Message.initialize(this,s,0,-1,null,null)},n.inherits(proto.v1.signaling.api.SendSignalRequest,t.Message),n.DEBUG&&!COMPILED&&(proto.v1.signaling.api.SendSignalRequest.displayName="proto.v1.signaling.api.SendSignalRequest"),proto.v1.signaling.api.SendSignalResponse=function(s){t.Message.initialize(this,s,0,-1,null,null)},n.inherits(proto.v1.signaling.api.SendSignalResponse,t.Message),n.DEBUG&&!COMPILED&&(proto.v1.signaling.api.SendSignalResponse.displayName="proto.v1.signaling.api.SendSignalResponse"),proto.v1.signaling.api.ReceiveSignalStreamRequest=function(s){t.Message.initialize(this,s,0,-1,null,null)},n.inherits(proto.v1.signaling.api.ReceiveSignalStreamRequest,t.Message),n.DEBUG&&!COMPILED&&(proto.v1.signaling.api.ReceiveSignalStreamRequest.displayName="proto.v1.signaling.api.ReceiveSignalStreamRequest"),proto.v1.signaling.api.ReceiveSignalStreamResponse=function(s){t.Message.initialize(this,s,0,-1,null,null)},n.inherits(proto.v1.signaling.api.ReceiveSignalStreamResponse,t.Message),n.DEBUG&&!COMPILED&&(proto.v1.signaling.api.ReceiveSignalStreamResponse.displayName="proto.v1.signaling.api.ReceiveSignalStreamResponse"),proto.v1.signaling.api.Peer.repeatedFields_=[5],t.Message.GENERATE_TO_OBJECT&&(proto.v1.signaling.api.Peer.prototype.toObject=function(s){return proto.v1.signaling.api.Peer.toObject(s,this)},proto.v1.signaling.api.Peer.toObject=function(s,c){var o,d={peerId:t.Message.getFieldWithDefault(c,1,""),organizationId:t.Message.getFieldWithDefault(c,2,""),userId:(o=c.getUserId())&&l.StringValue.toObject(s,o),deviceId:(o=c.getDeviceId())&&l.StringValue.toObject(s,o),sessionIdsList:(o=t.Message.getRepeatedField(c,5))==null?void 0:o,peerCreatedTimestamp:(o=c.getPeerCreatedTimestamp())&&l.Int64Value.toObject(s,o)};return s&&(d.$jspbMessageInstance=c),d}),proto.v1.signaling.api.Peer.deserializeBinary=function(s){var c=new t.BinaryReader(s),o=new proto.v1.signaling.api.Peer;return proto.v1.signaling.api.Peer.deserializeBinaryFromReader(o,c)},proto.v1.signaling.api.Peer.deserializeBinaryFromReader=function(s,c){for(;c.nextField()&&!c.isEndGroup();){var o=c.getFieldNumber();switch(o){case 1:var d=c.readString();s.setPeerId(d);break;case 2:var d=c.readString();s.setOrganizationId(d);break;case 3:var d=new l.StringValue;c.readMessage(d,l.StringValue.deserializeBinaryFromReader),s.setUserId(d);break;case 4:var d=new l.StringValue;c.readMessage(d,l.StringValue.deserializeBinaryFromReader),s.setDeviceId(d);break;case 5:var d=c.readString();s.addSessionIds(d);break;case 6:var d=new l.Int64Value;c.readMessage(d,l.Int64Value.deserializeBinaryFromReader),s.setPeerCreatedTimestamp(d);break;default:c.skipField();break}}return s},proto.v1.signaling.api.Peer.prototype.serializeBinary=function(){var s=new t.BinaryWriter;return proto.v1.signaling.api.Peer.serializeBinaryToWriter(this,s),s.getResultBuffer()},proto.v1.signaling.api.Peer.serializeBinaryToWriter=function(s,c){var o=void 0;o=s.getPeerId(),o.length>0&&c.writeString(1,o),o=s.getOrganizationId(),o.length>0&&c.writeString(2,o),o=s.getUserId(),o!=null&&c.writeMessage(3,o,l.StringValue.serializeBinaryToWriter),o=s.getDeviceId(),o!=null&&c.writeMessage(4,o,l.StringValue.serializeBinaryToWriter),o=s.getSessionIdsList(),o.length>0&&c.writeRepeatedString(5,o),o=s.getPeerCreatedTimestamp(),o!=null&&c.writeMessage(6,o,l.Int64Value.serializeBinaryToWriter)},proto.v1.signaling.api.Peer.prototype.getPeerId=function(){return t.Message.getFieldWithDefault(this,1,"")},proto.v1.signaling.api.Peer.prototype.setPeerId=function(s){return t.Message.setProto3StringField(this,1,s)},proto.v1.signaling.api.Peer.prototype.getOrganizationId=function(){return t.Message.getFieldWithDefault(this,2,"")},proto.v1.signaling.api.Peer.prototype.setOrganizationId=function(s){return t.Message.setProto3StringField(this,2,s)},proto.v1.signaling.api.Peer.prototype.getUserId=function(){return t.Message.getWrapperField(this,l.StringValue,3)},proto.v1.signaling.api.Peer.prototype.setUserId=function(s){return t.Message.setWrapperField(this,3,s)},proto.v1.signaling.api.Peer.prototype.clearUserId=function(){return this.setUserId(void 0)},proto.v1.signaling.api.Peer.prototype.hasUserId=function(){return t.Message.getField(this,3)!=null},proto.v1.signaling.api.Peer.prototype.getDeviceId=function(){return t.Message.getWrapperField(this,l.StringValue,4)},proto.v1.signaling.api.Peer.prototype.setDeviceId=function(s){return t.Message.setWrapperField(this,4,s)},proto.v1.signaling.api.Peer.prototype.clearDeviceId=function(){return this.setDeviceId(void 0)},proto.v1.signaling.api.Peer.prototype.hasDeviceId=function(){return t.Message.getField(this,4)!=null},proto.v1.signaling.api.Peer.prototype.getSessionIdsList=function(){return t.Message.getRepeatedField(this,5)},proto.v1.signaling.api.Peer.prototype.setSessionIdsList=function(s){return t.Message.setField(this,5,s||[])},proto.v1.signaling.api.Peer.prototype.addSessionIds=function(s,c){return t.Message.addToRepeatedField(this,5,s,c)},proto.v1.signaling.api.Peer.prototype.clearSessionIdsList=function(){return this.setSessionIdsList([])},proto.v1.signaling.api.Peer.prototype.getPeerCreatedTimestamp=function(){return t.Message.getWrapperField(this,l.Int64Value,6)},proto.v1.signaling.api.Peer.prototype.setPeerCreatedTimestamp=function(s){return t.Message.setWrapperField(this,6,s)},proto.v1.signaling.api.Peer.prototype.clearPeerCreatedTimestamp=function(){return this.setPeerCreatedTimestamp(void 0)},proto.v1.signaling.api.Peer.prototype.hasPeerCreatedTimestamp=function(){return t.Message.getField(this,6)!=null},t.Message.GENERATE_TO_OBJECT&&(proto.v1.signaling.api.Signal.prototype.toObject=function(s){return proto.v1.signaling.api.Signal.toObject(s,this)},proto.v1.signaling.api.Signal.toObject=function(s,c){var o,d={sessionId:(o=c.getSessionId())&&l.StringValue.toObject(s,o),sessionCreatedTimestamp:(o=c.getSessionCreatedTimestamp())&&l.Int64Value.toObject(s,o),senderId:t.Message.getFieldWithDefault(c,3,""),receiverId:t.Message.getFieldWithDefault(c,4,""),payload:t.Message.getFieldWithDefault(c,5,""),iceServers:t.Message.getFieldWithDefault(c,6,""),iceTransportPolicy:t.Message.getFieldWithDefault(c,7,""),sessionType:t.Message.getFieldWithDefault(c,8,0)};return s&&(d.$jspbMessageInstance=c),d}),proto.v1.signaling.api.Signal.deserializeBinary=function(s){var c=new t.BinaryReader(s),o=new proto.v1.signaling.api.Signal;return proto.v1.signaling.api.Signal.deserializeBinaryFromReader(o,c)},proto.v1.signaling.api.Signal.deserializeBinaryFromReader=function(s,c){for(;c.nextField()&&!c.isEndGroup();){var o=c.getFieldNumber();switch(o){case 1:var d=new l.StringValue;c.readMessage(d,l.StringValue.deserializeBinaryFromReader),s.setSessionId(d);break;case 2:var d=new l.Int64Value;c.readMessage(d,l.Int64Value.deserializeBinaryFromReader),s.setSessionCreatedTimestamp(d);break;case 3:var d=c.readString();s.setSenderId(d);break;case 4:var d=c.readString();s.setReceiverId(d);break;case 5:var d=c.readString();s.setPayload(d);break;case 6:var d=c.readString();s.setIceServers(d);break;case 7:var d=c.readString();s.setIceTransportPolicy(d);break;case 8:var d=c.readEnum();s.setSessionType(d);break;default:c.skipField();break}}return s},proto.v1.signaling.api.Signal.prototype.serializeBinary=function(){var s=new t.BinaryWriter;return proto.v1.signaling.api.Signal.serializeBinaryToWriter(this,s),s.getResultBuffer()},proto.v1.signaling.api.Signal.serializeBinaryToWriter=function(s,c){var o=void 0;o=s.getSessionId(),o!=null&&c.writeMessage(1,o,l.StringValue.serializeBinaryToWriter),o=s.getSessionCreatedTimestamp(),o!=null&&c.writeMessage(2,o,l.Int64Value.serializeBinaryToWriter),o=s.getSenderId(),o.length>0&&c.writeString(3,o),o=s.getReceiverId(),o.length>0&&c.writeString(4,o),o=s.getPayload(),o.length>0&&c.writeString(5,o),o=s.getIceServers(),o.length>0&&c.writeString(6,o),o=s.getIceTransportPolicy(),o.length>0&&c.writeString(7,o),o=s.getSessionType(),o!==0&&c.writeEnum(8,o)},proto.v1.signaling.api.Signal.prototype.getSessionId=function(){return t.Message.getWrapperField(this,l.StringValue,1)},proto.v1.signaling.api.Signal.prototype.setSessionId=function(s){return t.Message.setWrapperField(this,1,s)},proto.v1.signaling.api.Signal.prototype.clearSessionId=function(){return this.setSessionId(void 0)},proto.v1.signaling.api.Signal.prototype.hasSessionId=function(){return t.Message.getField(this,1)!=null},proto.v1.signaling.api.Signal.prototype.getSessionCreatedTimestamp=function(){return t.Message.getWrapperField(this,l.Int64Value,2)},proto.v1.signaling.api.Signal.prototype.setSessionCreatedTimestamp=function(s){return t.Message.setWrapperField(this,2,s)},proto.v1.signaling.api.Signal.prototype.clearSessionCreatedTimestamp=function(){return this.setSessionCreatedTimestamp(void 0)},proto.v1.signaling.api.Signal.prototype.hasSessionCreatedTimestamp=function(){return t.Message.getField(this,2)!=null},proto.v1.signaling.api.Signal.prototype.getSenderId=function(){return t.Message.getFieldWithDefault(this,3,"")},proto.v1.signaling.api.Signal.prototype.setSenderId=function(s){return t.Message.setProto3StringField(this,3,s)},proto.v1.signaling.api.Signal.prototype.getReceiverId=function(){return t.Message.getFieldWithDefault(this,4,"")},proto.v1.signaling.api.Signal.prototype.setReceiverId=function(s){return t.Message.setProto3StringField(this,4,s)},proto.v1.signaling.api.Signal.prototype.getPayload=function(){return t.Message.getFieldWithDefault(this,5,"")},proto.v1.signaling.api.Signal.prototype.setPayload=function(s){return t.Message.setProto3StringField(this,5,s)},proto.v1.signaling.api.Signal.prototype.getIceServers=function(){return t.Message.getFieldWithDefault(this,6,"")},proto.v1.signaling.api.Signal.prototype.setIceServers=function(s){return t.Message.setProto3StringField(this,6,s)},proto.v1.signaling.api.Signal.prototype.getIceTransportPolicy=function(){return t.Message.getFieldWithDefault(this,7,"")},proto.v1.signaling.api.Signal.prototype.setIceTransportPolicy=function(s){return t.Message.setProto3StringField(this,7,s)},proto.v1.signaling.api.Signal.prototype.getSessionType=function(){return t.Message.getFieldWithDefault(this,8,0)},proto.v1.signaling.api.Signal.prototype.setSessionType=function(s){return t.Message.setProto3EnumField(this,8,s)},t.Message.GENERATE_TO_OBJECT&&(proto.v1.signaling.api.RtcSession.prototype.toObject=function(s){return proto.v1.signaling.api.RtcSession.toObject(s,this)},proto.v1.signaling.api.RtcSession.toObject=function(s,c){var o={sessionId:t.Message.getFieldWithDefault(c,1,""),offerPeerId:t.Message.getFieldWithDefault(c,2,""),answerPeerId:t.Message.getFieldWithDefault(c,3,""),organizationId:t.Message.getFieldWithDefault(c,4,""),sessionType:t.Message.getFieldWithDefault(c,5,"")};return s&&(o.$jspbMessageInstance=c),o}),proto.v1.signaling.api.RtcSession.deserializeBinary=function(s){var c=new t.BinaryReader(s),o=new proto.v1.signaling.api.RtcSession;return proto.v1.signaling.api.RtcSession.deserializeBinaryFromReader(o,c)},proto.v1.signaling.api.RtcSession.deserializeBinaryFromReader=function(s,c){for(;c.nextField()&&!c.isEndGroup();){var o=c.getFieldNumber();switch(o){case 1:var d=c.readString();s.setSessionId(d);break;case 2:var d=c.readString();s.setOfferPeerId(d);break;case 3:var d=c.readString();s.setAnswerPeerId(d);break;case 4:var d=c.readString();s.setOrganizationId(d);break;case 5:var d=c.readString();s.setSessionType(d);break;default:c.skipField();break}}return s},proto.v1.signaling.api.RtcSession.prototype.serializeBinary=function(){var s=new t.BinaryWriter;return proto.v1.signaling.api.RtcSession.serializeBinaryToWriter(this,s),s.getResultBuffer()},proto.v1.signaling.api.RtcSession.serializeBinaryToWriter=function(s,c){var o=void 0;o=s.getSessionId(),o.length>0&&c.writeString(1,o),o=s.getOfferPeerId(),o.length>0&&c.writeString(2,o),o=s.getAnswerPeerId(),o.length>0&&c.writeString(3,o),o=s.getOrganizationId(),o.length>0&&c.writeString(4,o),o=s.getSessionType(),o.length>0&&c.writeString(5,o)},proto.v1.signaling.api.RtcSession.prototype.getSessionId=function(){return t.Message.getFieldWithDefault(this,1,"")},proto.v1.signaling.api.RtcSession.prototype.setSessionId=function(s){return t.Message.setProto3StringField(this,1,s)},proto.v1.signaling.api.RtcSession.prototype.getOfferPeerId=function(){return t.Message.getFieldWithDefault(this,2,"")},proto.v1.signaling.api.RtcSession.prototype.setOfferPeerId=function(s){return t.Message.setProto3StringField(this,2,s)},proto.v1.signaling.api.RtcSession.prototype.getAnswerPeerId=function(){return t.Message.getFieldWithDefault(this,3,"")},proto.v1.signaling.api.RtcSession.prototype.setAnswerPeerId=function(s){return t.Message.setProto3StringField(this,3,s)},proto.v1.signaling.api.RtcSession.prototype.getOrganizationId=function(){return t.Message.getFieldWithDefault(this,4,"")},proto.v1.signaling.api.RtcSession.prototype.setOrganizationId=function(s){return t.Message.setProto3StringField(this,4,s)},proto.v1.signaling.api.RtcSession.prototype.getSessionType=function(){return t.Message.getFieldWithDefault(this,5,"")},proto.v1.signaling.api.RtcSession.prototype.setSessionType=function(s){return t.Message.setProto3StringField(this,5,s)},t.Message.GENERATE_TO_OBJECT&&(proto.v1.signaling.api.GetSessionsRequest.prototype.toObject=function(s){return proto.v1.signaling.api.GetSessionsRequest.toObject(s,this)},proto.v1.signaling.api.GetSessionsRequest.toObject=function(s,c){var o={};return s&&(o.$jspbMessageInstance=c),o}),proto.v1.signaling.api.GetSessionsRequest.deserializeBinary=function(s){var c=new t.BinaryReader(s),o=new proto.v1.signaling.api.GetSessionsRequest;return proto.v1.signaling.api.GetSessionsRequest.deserializeBinaryFromReader(o,c)},proto.v1.signaling.api.GetSessionsRequest.deserializeBinaryFromReader=function(s,c){for(;c.nextField()&&!c.isEndGroup();){var o=c.getFieldNumber();switch(o){default:c.skipField();break}}return s},proto.v1.signaling.api.GetSessionsRequest.prototype.serializeBinary=function(){var s=new t.BinaryWriter;return proto.v1.signaling.api.GetSessionsRequest.serializeBinaryToWriter(this,s),s.getResultBuffer()},proto.v1.signaling.api.GetSessionsRequest.serializeBinaryToWriter=function(s,c){},proto.v1.signaling.api.GetSessionsResponse.repeatedFields_=[1],t.Message.GENERATE_TO_OBJECT&&(proto.v1.signaling.api.GetSessionsResponse.prototype.toObject=function(s){return proto.v1.signaling.api.GetSessionsResponse.toObject(s,this)},proto.v1.signaling.api.GetSessionsResponse.toObject=function(s,c){var o={sessionsList:t.Message.toObjectList(c.getSessionsList(),proto.v1.signaling.api.RtcSession.toObject,s)};return s&&(o.$jspbMessageInstance=c),o}),proto.v1.signaling.api.GetSessionsResponse.deserializeBinary=function(s){var c=new t.BinaryReader(s),o=new proto.v1.signaling.api.GetSessionsResponse;return proto.v1.signaling.api.GetSessionsResponse.deserializeBinaryFromReader(o,c)},proto.v1.signaling.api.GetSessionsResponse.deserializeBinaryFromReader=function(s,c){for(;c.nextField()&&!c.isEndGroup();){var o=c.getFieldNumber();switch(o){case 1:var d=new proto.v1.signaling.api.RtcSession;c.readMessage(d,proto.v1.signaling.api.RtcSession.deserializeBinaryFromReader),s.addSessions(d);break;default:c.skipField();break}}return s},proto.v1.signaling.api.GetSessionsResponse.prototype.serializeBinary=function(){var s=new t.BinaryWriter;return proto.v1.signaling.api.GetSessionsResponse.serializeBinaryToWriter(this,s),s.getResultBuffer()},proto.v1.signaling.api.GetSessionsResponse.serializeBinaryToWriter=function(s,c){var o=void 0;o=s.getSessionsList(),o.length>0&&c.writeRepeatedMessage(1,o,proto.v1.signaling.api.RtcSession.serializeBinaryToWriter)},proto.v1.signaling.api.GetSessionsResponse.prototype.getSessionsList=function(){return t.Message.getRepeatedWrapperField(this,proto.v1.signaling.api.RtcSession,1)},proto.v1.signaling.api.GetSessionsResponse.prototype.setSessionsList=function(s){return t.Message.setRepeatedWrapperField(this,1,s)},proto.v1.signaling.api.GetSessionsResponse.prototype.addSessions=function(s,c){return t.Message.addToRepeatedWrapperField(this,1,s,proto.v1.signaling.api.RtcSession,c)},proto.v1.signaling.api.GetSessionsResponse.prototype.clearSessionsList=function(){return this.setSessionsList([])},t.Message.GENERATE_TO_OBJECT&&(proto.v1.signaling.api.GetHealthRequest.prototype.toObject=function(s){return proto.v1.signaling.api.GetHealthRequest.toObject(s,this)},proto.v1.signaling.api.GetHealthRequest.toObject=function(s,c){var o={};return s&&(o.$jspbMessageInstance=c),o}),proto.v1.signaling.api.GetHealthRequest.deserializeBinary=function(s){var c=new t.BinaryReader(s),o=new proto.v1.signaling.api.GetHealthRequest;return proto.v1.signaling.api.GetHealthRequest.deserializeBinaryFromReader(o,c)},proto.v1.signaling.api.GetHealthRequest.deserializeBinaryFromReader=function(s,c){for(;c.nextField()&&!c.isEndGroup();){var o=c.getFieldNumber();switch(o){default:c.skipField();break}}return s},proto.v1.signaling.api.GetHealthRequest.prototype.serializeBinary=function(){var s=new t.BinaryWriter;return proto.v1.signaling.api.GetHealthRequest.serializeBinaryToWriter(this,s),s.getResultBuffer()},proto.v1.signaling.api.GetHealthRequest.serializeBinaryToWriter=function(s,c){},t.Message.GENERATE_TO_OBJECT&&(proto.v1.signaling.api.GetHealthResponse.prototype.toObject=function(s){return proto.v1.signaling.api.GetHealthResponse.toObject(s,this)},proto.v1.signaling.api.GetHealthResponse.toObject=function(s,c){var o={version:t.Message.getFieldWithDefault(c,1,"")};return s&&(o.$jspbMessageInstance=c),o}),proto.v1.signaling.api.GetHealthResponse.deserializeBinary=function(s){var c=new t.BinaryReader(s),o=new proto.v1.signaling.api.GetHealthResponse;return proto.v1.signaling.api.GetHealthResponse.deserializeBinaryFromReader(o,c)},proto.v1.signaling.api.GetHealthResponse.deserializeBinaryFromReader=function(s,c){for(;c.nextField()&&!c.isEndGroup();){var o=c.getFieldNumber();switch(o){case 1:var d=c.readString();s.setVersion(d);break;default:c.skipField();break}}return s},proto.v1.signaling.api.GetHealthResponse.prototype.serializeBinary=function(){var s=new t.BinaryWriter;return proto.v1.signaling.api.GetHealthResponse.serializeBinaryToWriter(this,s),s.getResultBuffer()},proto.v1.signaling.api.GetHealthResponse.serializeBinaryToWriter=function(s,c){var o=void 0;o=s.getVersion(),o.length>0&&c.writeString(1,o)},proto.v1.signaling.api.GetHealthResponse.prototype.getVersion=function(){return t.Message.getFieldWithDefault(this,1,"")},proto.v1.signaling.api.GetHealthResponse.prototype.setVersion=function(s){return t.Message.setProto3StringField(this,1,s)},t.Message.GENERATE_TO_OBJECT&&(proto.v1.signaling.api.CreatePeerRequest.prototype.toObject=function(s){return proto.v1.signaling.api.CreatePeerRequest.toObject(s,this)},proto.v1.signaling.api.CreatePeerRequest.toObject=function(s,c){var o={};return s&&(o.$jspbMessageInstance=c),o}),proto.v1.signaling.api.CreatePeerRequest.deserializeBinary=function(s){var c=new t.BinaryReader(s),o=new proto.v1.signaling.api.CreatePeerRequest;return proto.v1.signaling.api.CreatePeerRequest.deserializeBinaryFromReader(o,c)},proto.v1.signaling.api.CreatePeerRequest.deserializeBinaryFromReader=function(s,c){for(;c.nextField()&&!c.isEndGroup();){var o=c.getFieldNumber();switch(o){default:c.skipField();break}}return s},proto.v1.signaling.api.CreatePeerRequest.prototype.serializeBinary=function(){var s=new t.BinaryWriter;return proto.v1.signaling.api.CreatePeerRequest.serializeBinaryToWriter(this,s),s.getResultBuffer()},proto.v1.signaling.api.CreatePeerRequest.serializeBinaryToWriter=function(s,c){},t.Message.GENERATE_TO_OBJECT&&(proto.v1.signaling.api.CreatePeerResponse.prototype.toObject=function(s){return proto.v1.signaling.api.CreatePeerResponse.toObject(s,this)},proto.v1.signaling.api.CreatePeerResponse.toObject=function(s,c){var o,d={peer:(o=c.getPeer())&&proto.v1.signaling.api.Peer.toObject(s,o)};return s&&(d.$jspbMessageInstance=c),d}),proto.v1.signaling.api.CreatePeerResponse.deserializeBinary=function(s){var c=new t.BinaryReader(s),o=new proto.v1.signaling.api.CreatePeerResponse;return proto.v1.signaling.api.CreatePeerResponse.deserializeBinaryFromReader(o,c)},proto.v1.signaling.api.CreatePeerResponse.deserializeBinaryFromReader=function(s,c){for(;c.nextField()&&!c.isEndGroup();){var o=c.getFieldNumber();switch(o){case 1:var d=new proto.v1.signaling.api.Peer;c.readMessage(d,proto.v1.signaling.api.Peer.deserializeBinaryFromReader),s.setPeer(d);break;default:c.skipField();break}}return s},proto.v1.signaling.api.CreatePeerResponse.prototype.serializeBinary=function(){var s=new t.BinaryWriter;return proto.v1.signaling.api.CreatePeerResponse.serializeBinaryToWriter(this,s),s.getResultBuffer()},proto.v1.signaling.api.CreatePeerResponse.serializeBinaryToWriter=function(s,c){var o=void 0;o=s.getPeer(),o!=null&&c.writeMessage(1,o,proto.v1.signaling.api.Peer.serializeBinaryToWriter)},proto.v1.signaling.api.CreatePeerResponse.prototype.getPeer=function(){return t.Message.getWrapperField(this,proto.v1.signaling.api.Peer,1)},proto.v1.signaling.api.CreatePeerResponse.prototype.setPeer=function(s){return t.Message.setWrapperField(this,1,s)},proto.v1.signaling.api.CreatePeerResponse.prototype.clearPeer=function(){return this.setPeer(void 0)},proto.v1.signaling.api.CreatePeerResponse.prototype.hasPeer=function(){return t.Message.getField(this,1)!=null},t.Message.GENERATE_TO_OBJECT&&(proto.v1.signaling.api.DeletePeerRequest.prototype.toObject=function(s){return proto.v1.signaling.api.DeletePeerRequest.toObject(s,this)},proto.v1.signaling.api.DeletePeerRequest.toObject=function(s,c){var o={peerId:t.Message.getFieldWithDefault(c,1,"")};return s&&(o.$jspbMessageInstance=c),o}),proto.v1.signaling.api.DeletePeerRequest.deserializeBinary=function(s){var c=new t.BinaryReader(s),o=new proto.v1.signaling.api.DeletePeerRequest;return proto.v1.signaling.api.DeletePeerRequest.deserializeBinaryFromReader(o,c)},proto.v1.signaling.api.DeletePeerRequest.deserializeBinaryFromReader=function(s,c){for(;c.nextField()&&!c.isEndGroup();){var o=c.getFieldNumber();switch(o){case 1:var d=c.readString();s.setPeerId(d);break;default:c.skipField();break}}return s},proto.v1.signaling.api.DeletePeerRequest.prototype.serializeBinary=function(){var s=new t.BinaryWriter;return proto.v1.signaling.api.DeletePeerRequest.serializeBinaryToWriter(this,s),s.getResultBuffer()},proto.v1.signaling.api.DeletePeerRequest.serializeBinaryToWriter=function(s,c){var o=void 0;o=s.getPeerId(),o.length>0&&c.writeString(1,o)},proto.v1.signaling.api.DeletePeerRequest.prototype.getPeerId=function(){return t.Message.getFieldWithDefault(this,1,"")},proto.v1.signaling.api.DeletePeerRequest.prototype.setPeerId=function(s){return t.Message.setProto3StringField(this,1,s)},t.Message.GENERATE_TO_OBJECT&&(proto.v1.signaling.api.DeletePeerResponse.prototype.toObject=function(s){return proto.v1.signaling.api.DeletePeerResponse.toObject(s,this)},proto.v1.signaling.api.DeletePeerResponse.toObject=function(s,c){var o={};return s&&(o.$jspbMessageInstance=c),o}),proto.v1.signaling.api.DeletePeerResponse.deserializeBinary=function(s){var c=new t.BinaryReader(s),o=new proto.v1.signaling.api.DeletePeerResponse;return proto.v1.signaling.api.DeletePeerResponse.deserializeBinaryFromReader(o,c)},proto.v1.signaling.api.DeletePeerResponse.deserializeBinaryFromReader=function(s,c){for(;c.nextField()&&!c.isEndGroup();){var o=c.getFieldNumber();switch(o){default:c.skipField();break}}return s},proto.v1.signaling.api.DeletePeerResponse.prototype.serializeBinary=function(){var s=new t.BinaryWriter;return proto.v1.signaling.api.DeletePeerResponse.serializeBinaryToWriter(this,s),s.getResultBuffer()},proto.v1.signaling.api.DeletePeerResponse.serializeBinaryToWriter=function(s,c){},t.Message.GENERATE_TO_OBJECT&&(proto.v1.signaling.api.RefreshPeerRequest.prototype.toObject=function(s){return proto.v1.signaling.api.RefreshPeerRequest.toObject(s,this)},proto.v1.signaling.api.RefreshPeerRequest.toObject=function(s,c){var o,d={peer:(o=c.getPeer())&&proto.v1.signaling.api.Peer.toObject(s,o)};return s&&(d.$jspbMessageInstance=c),d}),proto.v1.signaling.api.RefreshPeerRequest.deserializeBinary=function(s){var c=new t.BinaryReader(s),o=new proto.v1.signaling.api.RefreshPeerRequest;return proto.v1.signaling.api.RefreshPeerRequest.deserializeBinaryFromReader(o,c)},proto.v1.signaling.api.RefreshPeerRequest.deserializeBinaryFromReader=function(s,c){for(;c.nextField()&&!c.isEndGroup();){var o=c.getFieldNumber();switch(o){case 1:var d=new proto.v1.signaling.api.Peer;c.readMessage(d,proto.v1.signaling.api.Peer.deserializeBinaryFromReader),s.setPeer(d);break;default:c.skipField();break}}return s},proto.v1.signaling.api.RefreshPeerRequest.prototype.serializeBinary=function(){var s=new t.BinaryWriter;return proto.v1.signaling.api.RefreshPeerRequest.serializeBinaryToWriter(this,s),s.getResultBuffer()},proto.v1.signaling.api.RefreshPeerRequest.serializeBinaryToWriter=function(s,c){var o=void 0;o=s.getPeer(),o!=null&&c.writeMessage(1,o,proto.v1.signaling.api.Peer.serializeBinaryToWriter)},proto.v1.signaling.api.RefreshPeerRequest.prototype.getPeer=function(){return t.Message.getWrapperField(this,proto.v1.signaling.api.Peer,1)},proto.v1.signaling.api.RefreshPeerRequest.prototype.setPeer=function(s){return t.Message.setWrapperField(this,1,s)},proto.v1.signaling.api.RefreshPeerRequest.prototype.clearPeer=function(){return this.setPeer(void 0)},proto.v1.signaling.api.RefreshPeerRequest.prototype.hasPeer=function(){return t.Message.getField(this,1)!=null},t.Message.GENERATE_TO_OBJECT&&(proto.v1.signaling.api.RefreshPeerResponse.prototype.toObject=function(s){return proto.v1.signaling.api.RefreshPeerResponse.toObject(s,this)},proto.v1.signaling.api.RefreshPeerResponse.toObject=function(s,c){var o={};return s&&(o.$jspbMessageInstance=c),o}),proto.v1.signaling.api.RefreshPeerResponse.deserializeBinary=function(s){var c=new t.BinaryReader(s),o=new proto.v1.signaling.api.RefreshPeerResponse;return proto.v1.signaling.api.RefreshPeerResponse.deserializeBinaryFromReader(o,c)},proto.v1.signaling.api.RefreshPeerResponse.deserializeBinaryFromReader=function(s,c){for(;c.nextField()&&!c.isEndGroup();){var o=c.getFieldNumber();switch(o){default:c.skipField();break}}return s},proto.v1.signaling.api.RefreshPeerResponse.prototype.serializeBinary=function(){var s=new t.BinaryWriter;return proto.v1.signaling.api.RefreshPeerResponse.serializeBinaryToWriter(this,s),s.getResultBuffer()},proto.v1.signaling.api.RefreshPeerResponse.serializeBinaryToWriter=function(s,c){},t.Message.GENERATE_TO_OBJECT&&(proto.v1.signaling.api.GetPeersRequest.prototype.toObject=function(s){return proto.v1.signaling.api.GetPeersRequest.toObject(s,this)},proto.v1.signaling.api.GetPeersRequest.toObject=function(s,c){var o={};return s&&(o.$jspbMessageInstance=c),o}),proto.v1.signaling.api.GetPeersRequest.deserializeBinary=function(s){var c=new t.BinaryReader(s),o=new proto.v1.signaling.api.GetPeersRequest;return proto.v1.signaling.api.GetPeersRequest.deserializeBinaryFromReader(o,c)},proto.v1.signaling.api.GetPeersRequest.deserializeBinaryFromReader=function(s,c){for(;c.nextField()&&!c.isEndGroup();){var o=c.getFieldNumber();switch(o){default:c.skipField();break}}return s},proto.v1.signaling.api.GetPeersRequest.prototype.serializeBinary=function(){var s=new t.BinaryWriter;return proto.v1.signaling.api.GetPeersRequest.serializeBinaryToWriter(this,s),s.getResultBuffer()},proto.v1.signaling.api.GetPeersRequest.serializeBinaryToWriter=function(s,c){},proto.v1.signaling.api.GetPeersResponse.repeatedFields_=[1],t.Message.GENERATE_TO_OBJECT&&(proto.v1.signaling.api.GetPeersResponse.prototype.toObject=function(s){return proto.v1.signaling.api.GetPeersResponse.toObject(s,this)},proto.v1.signaling.api.GetPeersResponse.toObject=function(s,c){var o={peersList:t.Message.toObjectList(c.getPeersList(),proto.v1.signaling.api.Peer.toObject,s)};return s&&(o.$jspbMessageInstance=c),o}),proto.v1.signaling.api.GetPeersResponse.deserializeBinary=function(s){var c=new t.BinaryReader(s),o=new proto.v1.signaling.api.GetPeersResponse;return proto.v1.signaling.api.GetPeersResponse.deserializeBinaryFromReader(o,c)},proto.v1.signaling.api.GetPeersResponse.deserializeBinaryFromReader=function(s,c){for(;c.nextField()&&!c.isEndGroup();){var o=c.getFieldNumber();switch(o){case 1:var d=new proto.v1.signaling.api.Peer;c.readMessage(d,proto.v1.signaling.api.Peer.deserializeBinaryFromReader),s.addPeers(d);break;default:c.skipField();break}}return s},proto.v1.signaling.api.GetPeersResponse.prototype.serializeBinary=function(){var s=new t.BinaryWriter;return proto.v1.signaling.api.GetPeersResponse.serializeBinaryToWriter(this,s),s.getResultBuffer()},proto.v1.signaling.api.GetPeersResponse.serializeBinaryToWriter=function(s,c){var o=void 0;o=s.getPeersList(),o.length>0&&c.writeRepeatedMessage(1,o,proto.v1.signaling.api.Peer.serializeBinaryToWriter)},proto.v1.signaling.api.GetPeersResponse.prototype.getPeersList=function(){return t.Message.getRepeatedWrapperField(this,proto.v1.signaling.api.Peer,1)},proto.v1.signaling.api.GetPeersResponse.prototype.setPeersList=function(s){return t.Message.setRepeatedWrapperField(this,1,s)},proto.v1.signaling.api.GetPeersResponse.prototype.addPeers=function(s,c){return t.Message.addToRepeatedWrapperField(this,1,s,proto.v1.signaling.api.Peer,c)},proto.v1.signaling.api.GetPeersResponse.prototype.clearPeersList=function(){return this.setPeersList([])},t.Message.GENERATE_TO_OBJECT&&(proto.v1.signaling.api.GetIceServersRequest.prototype.toObject=function(s){return proto.v1.signaling.api.GetIceServersRequest.toObject(s,this)},proto.v1.signaling.api.GetIceServersRequest.toObject=function(s,c){var o={};return s&&(o.$jspbMessageInstance=c),o}),proto.v1.signaling.api.GetIceServersRequest.deserializeBinary=function(s){var c=new t.BinaryReader(s),o=new proto.v1.signaling.api.GetIceServersRequest;return proto.v1.signaling.api.GetIceServersRequest.deserializeBinaryFromReader(o,c)},proto.v1.signaling.api.GetIceServersRequest.deserializeBinaryFromReader=function(s,c){for(;c.nextField()&&!c.isEndGroup();){var o=c.getFieldNumber();switch(o){default:c.skipField();break}}return s},proto.v1.signaling.api.GetIceServersRequest.prototype.serializeBinary=function(){var s=new t.BinaryWriter;return proto.v1.signaling.api.GetIceServersRequest.serializeBinaryToWriter(this,s),s.getResultBuffer()},proto.v1.signaling.api.GetIceServersRequest.serializeBinaryToWriter=function(s,c){},t.Message.GENERATE_TO_OBJECT&&(proto.v1.signaling.api.GetIceServersResponse.prototype.toObject=function(s){return proto.v1.signaling.api.GetIceServersResponse.toObject(s,this)},proto.v1.signaling.api.GetIceServersResponse.toObject=function(s,c){var o={iceServers:t.Message.getFieldWithDefault(c,1,"")};return s&&(o.$jspbMessageInstance=c),o}),proto.v1.signaling.api.GetIceServersResponse.deserializeBinary=function(s){var c=new t.BinaryReader(s),o=new proto.v1.signaling.api.GetIceServersResponse;return proto.v1.signaling.api.GetIceServersResponse.deserializeBinaryFromReader(o,c)},proto.v1.signaling.api.GetIceServersResponse.deserializeBinaryFromReader=function(s,c){for(;c.nextField()&&!c.isEndGroup();){var o=c.getFieldNumber();switch(o){case 1:var d=c.readString();s.setIceServers(d);break;default:c.skipField();break}}return s},proto.v1.signaling.api.GetIceServersResponse.prototype.serializeBinary=function(){var s=new t.BinaryWriter;return proto.v1.signaling.api.GetIceServersResponse.serializeBinaryToWriter(this,s),s.getResultBuffer()},proto.v1.signaling.api.GetIceServersResponse.serializeBinaryToWriter=function(s,c){var o=void 0;o=s.getIceServers(),o.length>0&&c.writeString(1,o)},proto.v1.signaling.api.GetIceServersResponse.prototype.getIceServers=function(){return t.Message.getFieldWithDefault(this,1,"")},proto.v1.signaling.api.GetIceServersResponse.prototype.setIceServers=function(s){return t.Message.setProto3StringField(this,1,s)},t.Message.GENERATE_TO_OBJECT&&(proto.v1.signaling.api.SendSignalRequest.prototype.toObject=function(s){return proto.v1.signaling.api.SendSignalRequest.toObject(s,this)},proto.v1.signaling.api.SendSignalRequest.toObject=function(s,c){var o,d={signal:(o=c.getSignal())&&proto.v1.signaling.api.Signal.toObject(s,o)};return s&&(d.$jspbMessageInstance=c),d}),proto.v1.signaling.api.SendSignalRequest.deserializeBinary=function(s){var c=new t.BinaryReader(s),o=new proto.v1.signaling.api.SendSignalRequest;return proto.v1.signaling.api.SendSignalRequest.deserializeBinaryFromReader(o,c)},proto.v1.signaling.api.SendSignalRequest.deserializeBinaryFromReader=function(s,c){for(;c.nextField()&&!c.isEndGroup();){var o=c.getFieldNumber();switch(o){case 1:var d=new proto.v1.signaling.api.Signal;c.readMessage(d,proto.v1.signaling.api.Signal.deserializeBinaryFromReader),s.setSignal(d);break;default:c.skipField();break}}return s},proto.v1.signaling.api.SendSignalRequest.prototype.serializeBinary=function(){var s=new t.BinaryWriter;return proto.v1.signaling.api.SendSignalRequest.serializeBinaryToWriter(this,s),s.getResultBuffer()},proto.v1.signaling.api.SendSignalRequest.serializeBinaryToWriter=function(s,c){var o=void 0;o=s.getSignal(),o!=null&&c.writeMessage(1,o,proto.v1.signaling.api.Signal.serializeBinaryToWriter)},proto.v1.signaling.api.SendSignalRequest.prototype.getSignal=function(){return t.Message.getWrapperField(this,proto.v1.signaling.api.Signal,1)},proto.v1.signaling.api.SendSignalRequest.prototype.setSignal=function(s){return t.Message.setWrapperField(this,1,s)},proto.v1.signaling.api.SendSignalRequest.prototype.clearSignal=function(){return this.setSignal(void 0)},proto.v1.signaling.api.SendSignalRequest.prototype.hasSignal=function(){return t.Message.getField(this,1)!=null},t.Message.GENERATE_TO_OBJECT&&(proto.v1.signaling.api.SendSignalResponse.prototype.toObject=function(s){return proto.v1.signaling.api.SendSignalResponse.toObject(s,this)},proto.v1.signaling.api.SendSignalResponse.toObject=function(s,c){var o,d={sessionId:(o=c.getSessionId())&&l.StringValue.toObject(s,o),sessionCreatedTimestamp:(o=c.getSessionCreatedTimestamp())&&l.Int64Value.toObject(s,o)};return s&&(d.$jspbMessageInstance=c),d}),proto.v1.signaling.api.SendSignalResponse.deserializeBinary=function(s){var c=new t.BinaryReader(s),o=new proto.v1.signaling.api.SendSignalResponse;return proto.v1.signaling.api.SendSignalResponse.deserializeBinaryFromReader(o,c)},proto.v1.signaling.api.SendSignalResponse.deserializeBinaryFromReader=function(s,c){for(;c.nextField()&&!c.isEndGroup();){var o=c.getFieldNumber();switch(o){case 1:var d=new l.StringValue;c.readMessage(d,l.StringValue.deserializeBinaryFromReader),s.setSessionId(d);break;case 2:var d=new l.Int64Value;c.readMessage(d,l.Int64Value.deserializeBinaryFromReader),s.setSessionCreatedTimestamp(d);break;default:c.skipField();break}}return s},proto.v1.signaling.api.SendSignalResponse.prototype.serializeBinary=function(){var s=new t.BinaryWriter;return proto.v1.signaling.api.SendSignalResponse.serializeBinaryToWriter(this,s),s.getResultBuffer()},proto.v1.signaling.api.SendSignalResponse.serializeBinaryToWriter=function(s,c){var o=void 0;o=s.getSessionId(),o!=null&&c.writeMessage(1,o,l.StringValue.serializeBinaryToWriter),o=s.getSessionCreatedTimestamp(),o!=null&&c.writeMessage(2,o,l.Int64Value.serializeBinaryToWriter)},proto.v1.signaling.api.SendSignalResponse.prototype.getSessionId=function(){return t.Message.getWrapperField(this,l.StringValue,1)},proto.v1.signaling.api.SendSignalResponse.prototype.setSessionId=function(s){return t.Message.setWrapperField(this,1,s)},proto.v1.signaling.api.SendSignalResponse.prototype.clearSessionId=function(){return this.setSessionId(void 0)},proto.v1.signaling.api.SendSignalResponse.prototype.hasSessionId=function(){return t.Message.getField(this,1)!=null},proto.v1.signaling.api.SendSignalResponse.prototype.getSessionCreatedTimestamp=function(){return t.Message.getWrapperField(this,l.Int64Value,2)},proto.v1.signaling.api.SendSignalResponse.prototype.setSessionCreatedTimestamp=function(s){return t.Message.setWrapperField(this,2,s)},proto.v1.signaling.api.SendSignalResponse.prototype.clearSessionCreatedTimestamp=function(){return this.setSessionCreatedTimestamp(void 0)},proto.v1.signaling.api.SendSignalResponse.prototype.hasSessionCreatedTimestamp=function(){return t.Message.getField(this,2)!=null},t.Message.GENERATE_TO_OBJECT&&(proto.v1.signaling.api.ReceiveSignalStreamRequest.prototype.toObject=function(s){return proto.v1.signaling.api.ReceiveSignalStreamRequest.toObject(s,this)},proto.v1.signaling.api.ReceiveSignalStreamRequest.toObject=function(s,c){var o={peerId:t.Message.getFieldWithDefault(c,1,"")};return s&&(o.$jspbMessageInstance=c),o}),proto.v1.signaling.api.ReceiveSignalStreamRequest.deserializeBinary=function(s){var c=new t.BinaryReader(s),o=new proto.v1.signaling.api.ReceiveSignalStreamRequest;return proto.v1.signaling.api.ReceiveSignalStreamRequest.deserializeBinaryFromReader(o,c)},proto.v1.signaling.api.ReceiveSignalStreamRequest.deserializeBinaryFromReader=function(s,c){for(;c.nextField()&&!c.isEndGroup();){var o=c.getFieldNumber();switch(o){case 1:var d=c.readString();s.setPeerId(d);break;default:c.skipField();break}}return s},proto.v1.signaling.api.ReceiveSignalStreamRequest.prototype.serializeBinary=function(){var s=new t.BinaryWriter;return proto.v1.signaling.api.ReceiveSignalStreamRequest.serializeBinaryToWriter(this,s),s.getResultBuffer()},proto.v1.signaling.api.ReceiveSignalStreamRequest.serializeBinaryToWriter=function(s,c){var o=void 0;o=s.getPeerId(),o.length>0&&c.writeString(1,o)},proto.v1.signaling.api.ReceiveSignalStreamRequest.prototype.getPeerId=function(){return t.Message.getFieldWithDefault(this,1,"")},proto.v1.signaling.api.ReceiveSignalStreamRequest.prototype.setPeerId=function(s){return t.Message.setProto3StringField(this,1,s)},t.Message.GENERATE_TO_OBJECT&&(proto.v1.signaling.api.ReceiveSignalStreamResponse.prototype.toObject=function(s){return proto.v1.signaling.api.ReceiveSignalStreamResponse.toObject(s,this)},proto.v1.signaling.api.ReceiveSignalStreamResponse.toObject=function(s,c){var o,d={signal:(o=c.getSignal())&&proto.v1.signaling.api.Signal.toObject(s,o)};return s&&(d.$jspbMessageInstance=c),d}),proto.v1.signaling.api.ReceiveSignalStreamResponse.deserializeBinary=function(s){var c=new t.BinaryReader(s),o=new proto.v1.signaling.api.ReceiveSignalStreamResponse;return proto.v1.signaling.api.ReceiveSignalStreamResponse.deserializeBinaryFromReader(o,c)},proto.v1.signaling.api.ReceiveSignalStreamResponse.deserializeBinaryFromReader=function(s,c){for(;c.nextField()&&!c.isEndGroup();){var o=c.getFieldNumber();switch(o){case 1:var d=new proto.v1.signaling.api.Signal;c.readMessage(d,proto.v1.signaling.api.Signal.deserializeBinaryFromReader),s.setSignal(d);break;default:c.skipField();break}}return s},proto.v1.signaling.api.ReceiveSignalStreamResponse.prototype.serializeBinary=function(){var s=new t.BinaryWriter;return proto.v1.signaling.api.ReceiveSignalStreamResponse.serializeBinaryToWriter(this,s),s.getResultBuffer()},proto.v1.signaling.api.ReceiveSignalStreamResponse.serializeBinaryToWriter=function(s,c){var o=void 0;o=s.getSignal(),o!=null&&c.writeMessage(1,o,proto.v1.signaling.api.Signal.serializeBinaryToWriter)},proto.v1.signaling.api.ReceiveSignalStreamResponse.prototype.getSignal=function(){return t.Message.getWrapperField(this,proto.v1.signaling.api.Signal,1)},proto.v1.signaling.api.ReceiveSignalStreamResponse.prototype.setSignal=function(s){return t.Message.setWrapperField(this,1,s)},proto.v1.signaling.api.ReceiveSignalStreamResponse.prototype.clearSignal=function(){return this.setSignal(void 0)},proto.v1.signaling.api.ReceiveSignalStreamResponse.prototype.hasSignal=function(){return t.Message.getField(this,1)!=null},proto.v1.signaling.api.SessionType={UNKNOWN:0,TELEOP:1,PORT_FORWARD:2,OBSERVE:3,HEADLESS:4},n.object.extend(e,proto.v1.signaling.api)})(signaling_pb);function defined(e,t){if(e!==void 0)return e;throw new Error(t||"Value is undefined")}const encodedJs$2="dmFyIFI9T2JqZWN0LmRlZmluZVByb3BlcnR5O3ZhciBHPShNLGIseCk9PmIgaW4gTT9SKE0sYix7ZW51bWVyYWJsZTohMCxjb25maWd1cmFibGU6ITAsd3JpdGFibGU6ITAsdmFsdWU6eH0pOk1bYl09eDt2YXIgST0oTSxiLHgpPT4oRyhNLHR5cGVvZiBiIT0ic3ltYm9sIj9iKyIiOmIseCkseCk7KGZ1bmN0aW9uKCl7InVzZSBzdHJpY3QiO2NvbnN0IFM9e21pbGxpc2Vjb25kOjEsc2Vjb25kOjFlMyxtaW51dGU6NmU0LGhvdXI6MzZlNSxkYXk6ODY0ZTUsd2Vlazo2MDQ4ZTUsbW9udGg6MjU5MmU2LHllYXI6MzE1MzZlNn07ZnVuY3Rpb24gcShvKXt9Y2xhc3MgX3tjb25zdHJ1Y3Rvcih7Y2FwYWNpdHk6dCx0aW1lb3V0Om59PXt9KXtJKHRoaXMsImVudHJpZXMiLG5ldyBNYXApO0kodGhpcywibWV0YWRhdGEiLG5ldyBNYXApO0kodGhpcywiY2FwYWNpdHkiKTtJKHRoaXMsInRpbWVvdXQiKTt0aGlzLmNhcGFjaXR5PXR8fDFlNCx0aGlzLnRpbWVvdXQ9bnx8Uy5taW51dGV9Z2V0KHQsbil7Y29uc3QgZT10aGlzLmtleVRvQ2FjaGVLZXkodCksYz10aGlzLmVudHJpZXMuZ2V0KGUpLGk9dGhpcy5tZXRhZGF0YS5nZXQoZSk7cmV0dXJuKGM9PT12b2lkIDB8fGkmJihpPT1udWxsP3ZvaWQgMDppLmV4cGlyYXRpb24uZ2V0VGltZSgpKTxEYXRlLm5vdygpKSYmIShpIT1udWxsJiZpLmdlbmVyYXRpbmcpJiZuJiZ0aGlzLmdlbmVyYXRlKHQsbigpKSxjPT09dm9pZCAwJiZpJiZpLmxhc3RWYWx1ZSE9PXZvaWQgMD9pLmxhc3RWYWx1ZTpjfXNldCh0LG4pe2NvbnN0IGU9dGhpcy5rZXlUb0NhY2hlS2V5KHQpO3RoaXMubWV0YWRhdGEuc2V0KGUse2dlbmVyYXRpbmc6ITEsZXhwaXJhdGlvbjpuZXcgRGF0ZShEYXRlLm5vdygpK3RoaXMudGltZW91dCksbGFzdFZhbHVlOm59KSx0aGlzLmVudHJpZXMuc2V0KGUsbiksdGhpcy5tZXRhZGF0YS5zaXplPnRoaXMuY2FwYWNpdHkmJnRoaXMuZGVsZXRlT2xkZXN0RW50cnkoKX1jbGVhcigpe3RoaXMuZW50cmllcy5jbGVhcigpLFsuLi50aGlzLm1ldGFkYXRhLnZhbHVlcygpXS5mb3JFYWNoKHQ9PnQuZ2VuZXJhdGluZz0hMSl9Y2xlYXJLZXkodCl7dGhpcy5tZXRhZGF0YS5kZWxldGUodCksdGhpcy5lbnRyaWVzLmRlbGV0ZSh0KX1rZXlUb0NhY2hlS2V5KHQpe3JldHVybiBKU09OLnN0cmluZ2lmeSh0KX1kZWxldGVPbGRlc3RFbnRyeSgpe2lmKHRoaXMubWV0YWRhdGEuc2l6ZTwxKXJldHVybjtjb25zdFt0XT1bLi4udGhpcy5tZXRhZGF0YS5lbnRyaWVzKCldLnJlZHVjZSgoW24sZV0sW2MsaV0pPT5pLmV4cGlyYXRpb24uZ2V0VGltZSgpPGUuZXhwaXJhdGlvbi5nZXRUaW1lKCk/W2MsaV06W24sZV0pO3RoaXMuY2xlYXJLZXkodCl9Z2VuZXJhdGUodCxuKXtjb25zdCBlPXRoaXMua2V5VG9DYWNoZUtleSh0KSxjPXRoaXMubWV0YWRhdGEuZ2V0KGUpfHx7fTt0aGlzLm1ldGFkYXRhLnNldChlLHsuLi5jLGdlbmVyYXRpbmc6ITAsZXhwaXJhdGlvbjpuZXcgRGF0ZShEYXRlLm5vdygpK3RoaXMudGltZW91dCl9KSxzZXRUaW1lb3V0KCgpPT57bi50aGVuKGk9Pntjb25zdCByPXRoaXMubWV0YWRhdGEuZ2V0KGUpOyEociE9bnVsbCYmci5nZW5lcmF0aW5nKXx8dGhpcy5zZXQodCxpKX0pfSwwKX19LyoqCiAqIExaRiBjb21wcmVzc2lvbi9kZWNvbXByZXNzaW9uIG1vZHVsZS4gUG9ydGVkIGZyb20gdGhlIEMKICogaW1wbGVtZW50YXRpb24gb2YgbGlibHpmLCBzcGVjZmljYWxseSBsemZfYy5jIGFuZCBsemZfZC5jCiAqIEBsaWNlbnNlIEJTRC0yLUNsYXVzZQogKi9mdW5jdGlvbiBLKG8pe3ZhciB0PW5ldyBVaW50OEFycmF5KG8pLG49W10sZT0wLGM9MDtkb3t2YXIgaT10W2UrK107aWYoaTwxPDw1KXtpZihpKyssZStpPnQubGVuZ3RoKXRocm93IG5ldyBFcnJvcigiSW52YWxpZCBpbnB1dCIpO2Zvcig7aS0tOyluW2MrK109dFtlKytdfWVsc2V7dmFyIHI9aT4+NSxmPWMtKChpJjMxKTw8OCktMTtpZihlPj10Lmxlbmd0aCl0aHJvdyBuZXcgRXJyb3IoIkludmFsaWQgaW5wdXQiKTtpZihyPT03JiYocis9dFtlKytdLGU+PXQubGVuZ3RoKSl0aHJvdyBuZXcgRXJyb3IoIkludmFsaWQgaW5wdXQiKTtpZihmLT10W2UrK10sZjwwKXRocm93IG5ldyBFcnJvcigiSW52YWxpZCBpbnB1dCIpO3IrPTI7ZG8gbltjKytdPW5bZisrXTt3aGlsZSgtLXIpfX13aGlsZShlPHQubGVuZ3RoKTtpZih0eXBlb2YgQnVmZmVyIT0idW5kZWZpbmVkIilyZXR1cm4gbmV3IEJ1ZmZlcihuKTt2YXIgdT1uZXcgVWludDhBcnJheShuLmxlbmd0aCk7cmV0dXJuIHUuc2V0KG4pLHV9ZnVuY3Rpb24gTyhvKXt2YXIgdD0xNixuPTE8PHQsZT0xPDwxMyxjPSgxPDw4KSsoMTw8MyksaT0xPDw1O2Z1bmN0aW9uIHIodixUKXtyZXR1cm4gdltUXTw8OHx2W1QrMV19ZnVuY3Rpb24gZih2LFQsUCl7cmV0dXJuIHY8PDh8VFtQKzJdfWZ1bmN0aW9uIHUodil7cmV0dXJuIHYqNTA2ODMyODI5Pj4zMi10LTgmbi0xfWZvcih2YXIgcz1uZXcgVWludDhBcnJheShvKSxhPVtdLGQ9bmV3IFVpbnQzMkFycmF5KG4pLHk9cy5sZW5ndGgsaD0wLGc9cihzLGgpLHA9MSxsPTA7aDx5LTI7KXtnPWYoZyxvLGgpO3ZhciB6PXUoZyksbT1kW3pdO2Rbel09aDt2YXIgRTtpZihtPGgmJihFPWgtbS0xKTxlJiZtPjAmJnNbbSsyXT09c1toKzJdJiZzW20rMV09PXNbaCsxXSYmc1ttXT09c1toXSl7dmFyIHc9MixGPXktaC13O0Y9Rj5jP2M6RixhW3AtbC0xXT1sLTEmMjU1LGw9PTAmJihwLT0xKTtkbyB3Kys7d2hpbGUodzxGJiZzW20rd109PXNbaCt3XSk7aWYody09MixoKyssdzw3P2FbcCsrXT0oRT4+OCkrKHc8PDUpJjI1NTooYVtwKytdPShFPj44KSsoNzw8NSkmMjU1LGFbcCsrXT13LTcmMjU1KSxhW3ArK109RSYyNTUsbD0wLHArKyxoKz13KzEsaD49eS0yKWJyZWFrOy0taCwtLWgsZz1yKHMsaCksZz1mKGcscyxoKSxkW3UoZyldPWgrKyxnPWYoZyxzLGgpLGRbdShnKV09aCsrfWVsc2UgbCsrLGFbcCsrXT1zW2grK10sbD09aSYmKGFbcC1sLTFdPWwtMSYyNTUsbD0wLHArKyl9Zm9yKDtoPHk7KWwrKyxhW3ArK109c1toKytdLGw9PWkmJihhW3AtbC0xXT1sLTEmMjU1LGw9MCxwKyspO2lmKGwhPTAmJihhW3AtbC0xXT1sLTEmMjU1KSx0eXBlb2YgQnVmZmVyIT0idW5kZWZpbmVkIilyZXR1cm4gbmV3IEJ1ZmZlcihhKTt2YXIgVT1uZXcgVWludDhBcnJheShhLmxlbmd0aCk7cmV0dXJuIFUuc2V0KGEpLFV9dmFyIEI9e2RlY29tcHJlc3M6Syxjb21wcmVzczpPfTtjb25zdCBDPShvLHQpPT50PD1vP1tdOm5ldyBBcnJheSh0LW8pLmZpbGwoMCkubWFwKChuLGUpPT5lK28pLEE9ITA7ZnVuY3Rpb24gSChvKXtjb25zdCB0PWF0b2Iobyksbj10Lmxlbmd0aCxlPW5ldyBVaW50OEFycmF5KG4pO2ZvcihsZXQgYz0wO2M8bjtjKz0xKWVbY109dC5jaGFyQ29kZUF0KGMpO3JldHVybiBlLmJ1ZmZlcn1mdW5jdGlvbiBMKG8pe2NvbnN0IHQ9bmV3IFVpbnQ4QXJyYXkobyk7bGV0IG49IiIsZT0wO2Zvcig7ZTx0Lmxlbmd0aCYmbi5zZWFyY2goL1tcclxuXURBVEFccyhcUyopXHMvaSk9PT0tMTtlKz0xKW4rPVN0cmluZy5mcm9tQ2hhckNvZGUodFtlXSk7cmV0dXJue2JvZHk6by5zbGljZShlKSxoZWFkZXI6bi5yZXBsYWNlKC8jLiovZ2ksIiIpfX1mdW5jdGlvbiBWKG8pe2NvbnN0IG49bmV3IFVpbnQzMkFycmF5KG8sMCwyKVswXTtyZXR1cm4gbj09PTA/bmV3IEFycmF5QnVmZmVyKDApOkIuZGVjb21wcmVzcyhuZXcgVWludDhBcnJheShvLDgsbikpLmJ1ZmZlcn1mdW5jdGlvbiBrKG8pe2NvbnN0e2hlYWRlcjp0LGJvZHk6bn09TChvKSxlPS9WRVJTSU9OICguKikvaS5leGVjKHQpO2lmKGU9PT1udWxsKXRocm93IG5ldyBFcnJvcihgTWlzc2luZyB2ZXJzaW9uLiBIZWFkZXIgJHt0fWApO2NvbnN0IGM9ZVsxXSxpPS9GSUVMRFMgKC4qKS9pLmV4ZWModCk7aWYoIWkpdGhyb3cgbmV3IEVycm9yKCJNaXNzaW5nIGZpZWxkcyIpO2NvbnN0IHI9aVsxXS5zcGxpdCgiICIpLGY9L1NJWkUgKC4qKS9pLmV4ZWModCk7aWYoIWYpdGhyb3cgbmV3IEVycm9yKCJNaXNzaW5nIHNpemUiKTtjb25zdCB1PWZbMV0uc3BsaXQoIiAiKS5tYXAodj0+cGFyc2VJbnQodiwxMCkpLHM9L1RZUEUgKC4qKS9pLmV4ZWModCk7aWYoIXMpdGhyb3cgbmV3IEVycm9yKCJNaXNzaW5nIHR5cGUiKTtjb25zdCBhPXNbMV0uc3BsaXQoIiAiKSxkPS9DT1VOVCAoLiopL2kuZXhlYyh0KTtsZXQgeTtkJiYoeT1kWzFdLnNwbGl0KCIgIikubWFwKHY9PnBhcnNlSW50KHYsMTApKSk7Y29uc3QgaD15fHxyLm1hcCh2PT4xKSxnPS9XSURUSCAoLiopL2kuZXhlYyh0KTtpZighZyl0aHJvdyBuZXcgRXJyb3IoIk1pc3Npbmcgd2lkdGgiKTtjb25zdCBwPXBhcnNlSW50KGdbMV0sMTApLGw9L0hFSUdIVCAoLiopL2kuZXhlYyh0KTtpZighbCl0aHJvdyBuZXcgRXJyb3IoIk1pc3NpbmcgaGVpZ2h0Iik7Y29uc3Qgej1wYXJzZUludChsWzFdLDEwKSxtPS9QT0lOVFMgKC4qKS9pLmV4ZWModCk7bGV0IEU7bSYmKEU9cGFyc2VJbnQobVsxXSwxMCkpO2NvbnN0IHc9RXx8cCp6LEY9L0RBVEEgKC4qKS9pLmV4ZWModCk7aWYoIUYpdGhyb3cgbmV3IEVycm9yKCJNaXNzaW5nIGRhdGEiKTtjb25zdCBVPUZbMV07cmV0dXJue2JvZHk6bixoZWFkZXI6e2NvdW50OmgsZGF0YTpVLGZpZWxkczpyLGhlaWdodDp6LHBvaW50czp3LHNpemU6dSx0eXBlOmEsdmVyc2lvbjpjLHdpZHRoOnB9fX1mdW5jdGlvbiBOKG8pe2NvbnN0IHQ9e307cmV0dXJuIG8uZmllbGRzLnJlZHVjZSgoe29mZnNldHM6bixzaXplOmV9LGMsaSk9PntsZXQgcj1lO3JldHVybiBjPT09IngiJiYobi54PXIpLGM9PT0ieSImJihuLnk9ciksYz09PSJ6IiYmKG4uej1yKSxjPT09InJnYiImJihuLnJnYj1yKSxjPT09InJnYmEiJiYobi5yZ2JhPXIpLGM9PT0iaW50ZW5zaXR5IiYmKG4uaW50ZW5zaXR5PXIpLG8uZGF0YT09PSJhc2NpaSI/cis9MTpvLmRhdGE9PT0iYmluYXJ5Ij9yKz1vLnNpemVbaV0qby5jb3VudFtpXTpvLmRhdGE9PT0iYmluYXJ5X2NvbXByZXNzZWQiJiYocis9by5zaXplW2ldKm8uY291bnRbaV0qby5wb2ludHMpLHtvZmZzZXRzOm4sc2l6ZTpyfX0se29mZnNldHM6dCxzaXplOjB9KX1mdW5jdGlvbiBEKG8pe2NvbnN0e2hlYWRlcjp0LGJvZHk6bn09ayhvKSx7b2Zmc2V0czplLHNpemU6Y309Tih0KTtsZXQgaTtlLnghPT12b2lkIDAmJmUueSE9PXZvaWQgMCYmZS56IT09dm9pZCAwJiYoaT1uZXcgRmxvYXQzMkFycmF5KHQucG9pbnRzKjMpKTtsZXQgcjsoZS5yZ2IhPT12b2lkIDB8fGUucmdiYSE9PXZvaWQgMCkmJihyPW5ldyBGbG9hdDMyQXJyYXkodC5wb2ludHMqNCkpO2xldCBmO2lmKGUuaW50ZW5zaXR5IT09dm9pZCAwJiYoZj1uZXcgRmxvYXQzMkFycmF5KHQucG9pbnRzKSksdC5kYXRhPT09ImFzY2lpIilTdHJpbmcuZnJvbUNoYXJDb2RlKC4uLm5ldyBVaW50OEFycmF5KG4pKS5zcGxpdChgCmApLmZvckVhY2goKGEsZCk9Pntjb25zdCB5PWEuc3BsaXQoIiAiKTtpZihpIT09dm9pZCAwJiYoaVtkKjMrMF09cGFyc2VGbG9hdCh5W2UueHx8MF0pLGlbZCozKzFdPXBhcnNlRmxvYXQoeVtlLnl8fDBdKSxpW2QqMysyXT1wYXJzZUZsb2F0KHlbZS56fHwwXSkpLHIhPT12b2lkIDApe2NvbnN0IGg9bmV3IEludDMyQXJyYXkoW3BhcnNlSW50KHlbZS5yZ2J8fGUucmdiYXx8MF0sMTApXSksZz1uZXcgRGF0YVZpZXcoaC5idWZmZXIsMCk7cltkKjMrMF09Zy5nZXRVaW50OCgyKS8yNTUscltkKjMrMV09Zy5nZXRVaW50OCgxKS8yNTUscltkKjMrMl09Zy5nZXRVaW50OCgwKS8yNTV9ZiE9PXZvaWQgMCYmKGZbZF09cGFyc2VGbG9hdCh5W2UuaW50ZW5zaXR5fHwwXSkpfSk7ZWxzZSBpZih0LmRhdGE9PT0iYmluYXJ5Iil7Y29uc3QgdT1uZXcgRGF0YVZpZXcobik7QygwLHQucG9pbnRzKS5mb3JFYWNoKHM9Pntjb25zdCBhPWMqcztpZihpIT09dm9pZCAwJiYoaVtzKjMrMF09dS5nZXRGbG9hdDMyKGErKGUueHx8MCksQSksaVtzKjMrMV09dS5nZXRGbG9hdDMyKGErKGUueXx8MCksQSksaVtzKjMrMl09dS5nZXRGbG9hdDMyKGErKGUuenx8MCksQSkpLHIhPT12b2lkIDApe2NvbnN0IGQ9YSsoZS5yZ2J8fGUucmdiYXx8MCk7ZCsyPD11LmJ5dGVMZW5ndGgmJihyW3MqNCswXT11LmdldFVpbnQ4KGQrMikvMjU1LHJbcyo0KzFdPXUuZ2V0VWludDgoZCsxKS8yNTUscltzKjQrMl09dS5nZXRVaW50OChkKzApLzI1NSxyW3MqNCszXT0xKX1mIT09dm9pZCAwJiYoZltzXT11LmdldEZsb2F0MzIoYSsoZS5pbnRlbnNpdHl8fDApLEEpKX0pfWVsc2UgaWYodC5kYXRhPT09ImJpbmFyeV9jb21wcmVzc2VkIil7Y29uc3QgdT1WKG4pLHM9bmV3IERhdGFWaWV3KHUpO0MoMCx0LnBvaW50cykuZm9yRWFjaChhPT57aWYoaSE9PXZvaWQgMCYmKGlbYSozKzBdPXMuZ2V0RmxvYXQzMigoZS54fHwwKSthKjQsQSksaVthKjMrMV09cy5nZXRGbG9hdDMyKChlLnl8fDApK2EqNCxBKSxpW2EqMysyXT1zLmdldEZsb2F0MzIoKGUuenx8MCkrYSo0LEEpKSxyIT09dm9pZCAwKXtjb25zdCBkPShlLnJnYnx8ZS5yZ2JhfHwwKSthKjQ7ZCsyPD1zLmJ5dGVMZW5ndGgmJihyW2EqNCswXT1zLmdldFVpbnQ4KGQrMikvMjU1LHJbYSo0KzFdPXMuZ2V0VWludDgoZCsxKS8yNTUsclthKjQrMl09cy5nZXRVaW50OChkKzApLzI1NSxyW2EqNCszXT0xKX1mIT09dm9pZCAwJiYoZlthXT1zLmdldEZsb2F0MzIoKGUuaW50ZW5zaXR5fHwwKSthKjQsQSkpfSl9cmV0dXJue2NvbG9yczpyLGhlYWRlcjp0LGludGVuc2l0eTpmLHBvc2l0aW9uczppfX1mdW5jdGlvbiBYKG8pe3JldHVybiBEKEgobykpfWNvbnN0IFo9bmV3IF8oe2NhcGFjaXR5OjFlMyx0aW1lb3V0OjEqUy5taW51dGV9KTtvbm1lc3NhZ2U9YXN5bmMgbz0+e2NvbnN0e3VybDp0LGlkOm4scG9pbnRDbG91ZDplfT1vLmRhdGE7aWYodCl7Y29uc3QgYz1aLmdldCh0LGFzeW5jKCk9PkQoYXdhaXQgZmV0Y2godCx7bW9kZToiY29ycyJ9KS50aGVuKHI9PnIuYXJyYXlCdWZmZXIoKSkpKTtjJiZwb3N0TWVzc2FnZSh7dXJsOnQscGNkOmN9KX1pZihuJiZlKXtjb25zdCBjPVgoZSk7cG9zdE1lc3NhZ2Uoe2lkOm4scGNkOmN9KX19fSkoKTsKLy8jIHNvdXJjZU1hcHBpbmdVUkw9UGNkTG9hZGVyV29ya2VyLWVhYWMwYjMxLmpzLm1hcAo=",blob$2=typeof window!="undefined"&&window.Blob&&new Blob([atob(encodedJs$2)],{type:"text/javascript;charset=utf-8"});function WorkerWrapper$2(){let e;try{if(e=blob$2&&(window.URL||window.webkitURL).createObjectURL(blob$2),!e)throw"";return new Worker(e)}catch{return new Worker("data:application/javascript;base64,"+encodedJs$2)}finally{e&&(window.URL||window.webkitURL).revokeObjectURL(e)}}const encodedJs$1="dmFyIGw9T2JqZWN0LmRlZmluZVByb3BlcnR5O3ZhciBnPShjLG4sbyk9Pm4gaW4gYz9sKGMsbix7ZW51bWVyYWJsZTohMCxjb25maWd1cmFibGU6ITAsd3JpdGFibGU6ITAsdmFsdWU6b30pOmNbbl09bzt2YXIgcj0oYyxuLG8pPT4oZyhjLHR5cGVvZiBuIT0ic3ltYm9sIj9uKyIiOm4sbyksbyk7KGZ1bmN0aW9uKCl7InVzZSBzdHJpY3QiO2NvbnN0IHU9e21pbGxpc2Vjb25kOjEsc2Vjb25kOjFlMyxtaW51dGU6NmU0LGhvdXI6MzZlNSxkYXk6ODY0ZTUsd2Vlazo2MDQ4ZTUsbW9udGg6MjU5MmU2LHllYXI6MzE1MzZlNn07ZnVuY3Rpb24geChoKXt9Y2xhc3MgbXtjb25zdHJ1Y3Rvcih7Y2FwYWNpdHk6ZSx0aW1lb3V0OnN9PXt9KXtyKHRoaXMsImVudHJpZXMiLG5ldyBNYXApO3IodGhpcywibWV0YWRhdGEiLG5ldyBNYXApO3IodGhpcywiY2FwYWNpdHkiKTtyKHRoaXMsInRpbWVvdXQiKTt0aGlzLmNhcGFjaXR5PWV8fDFlNCx0aGlzLnRpbWVvdXQ9c3x8dS5taW51dGV9Z2V0KGUscyl7Y29uc3QgYT10aGlzLmtleVRvQ2FjaGVLZXkoZSksaT10aGlzLmVudHJpZXMuZ2V0KGEpLHQ9dGhpcy5tZXRhZGF0YS5nZXQoYSk7cmV0dXJuKGk9PT12b2lkIDB8fHQmJih0PT1udWxsP3ZvaWQgMDp0LmV4cGlyYXRpb24uZ2V0VGltZSgpKTxEYXRlLm5vdygpKSYmISh0IT1udWxsJiZ0LmdlbmVyYXRpbmcpJiZzJiZ0aGlzLmdlbmVyYXRlKGUscygpKSxpPT09dm9pZCAwJiZ0JiZ0Lmxhc3RWYWx1ZSE9PXZvaWQgMD90Lmxhc3RWYWx1ZTppfXNldChlLHMpe2NvbnN0IGE9dGhpcy5rZXlUb0NhY2hlS2V5KGUpO3RoaXMubWV0YWRhdGEuc2V0KGEse2dlbmVyYXRpbmc6ITEsZXhwaXJhdGlvbjpuZXcgRGF0ZShEYXRlLm5vdygpK3RoaXMudGltZW91dCksbGFzdFZhbHVlOnN9KSx0aGlzLmVudHJpZXMuc2V0KGEscyksdGhpcy5tZXRhZGF0YS5zaXplPnRoaXMuY2FwYWNpdHkmJnRoaXMuZGVsZXRlT2xkZXN0RW50cnkoKX1jbGVhcigpe3RoaXMuZW50cmllcy5jbGVhcigpLFsuLi50aGlzLm1ldGFkYXRhLnZhbHVlcygpXS5mb3JFYWNoKGU9PmUuZ2VuZXJhdGluZz0hMSl9Y2xlYXJLZXkoZSl7dGhpcy5tZXRhZGF0YS5kZWxldGUoZSksdGhpcy5lbnRyaWVzLmRlbGV0ZShlKX1rZXlUb0NhY2hlS2V5KGUpe3JldHVybiBKU09OLnN0cmluZ2lmeShlKX1kZWxldGVPbGRlc3RFbnRyeSgpe2lmKHRoaXMubWV0YWRhdGEuc2l6ZTwxKXJldHVybjtjb25zdFtlXT1bLi4udGhpcy5tZXRhZGF0YS5lbnRyaWVzKCldLnJlZHVjZSgoW3MsYV0sW2ksdF0pPT50LmV4cGlyYXRpb24uZ2V0VGltZSgpPGEuZXhwaXJhdGlvbi5nZXRUaW1lKCk/W2ksdF06W3MsYV0pO3RoaXMuY2xlYXJLZXkoZSl9Z2VuZXJhdGUoZSxzKXtjb25zdCBhPXRoaXMua2V5VG9DYWNoZUtleShlKSxpPXRoaXMubWV0YWRhdGEuZ2V0KGEpfHx7fTt0aGlzLm1ldGFkYXRhLnNldChhLHsuLi5pLGdlbmVyYXRpbmc6ITAsZXhwaXJhdGlvbjpuZXcgRGF0ZShEYXRlLm5vdygpK3RoaXMudGltZW91dCl9KSxzZXRUaW1lb3V0KCgpPT57cy50aGVuKHQ9Pntjb25zdCBkPXRoaXMubWV0YWRhdGEuZ2V0KGEpOyEoZCE9bnVsbCYmZC5nZW5lcmF0aW5nKXx8dGhpcy5zZXQoZSx0KX0pfSwwKX19Y29uc3QgeT1uZXcgbSh7Y2FwYWNpdHk6MWUzLHRpbWVvdXQ6MSp1Lm1pbnV0ZX0pO29ubWVzc2FnZT1hc3luYyBoPT57Y29uc3R7dXJsOmV9PWguZGF0YTtpZihlKXtjb25zdCBzPXkuZ2V0KGUsYXN5bmMoKT0+YXdhaXQgZmV0Y2goZSx7bW9kZToiY29ycyJ9KS50aGVuKGk9PmkuanNvbigpKSk7cyYmcG9zdE1lc3NhZ2Uoe3VybDplLHJlc3BvbnNlOnN9KX19fSkoKTsKLy8jIHNvdXJjZU1hcHBpbmdVUkw9RGF0YUZldGNoV29ya2VyLTBhMTY4OTMzLmpzLm1hcAo=",blob$1=typeof window!="undefined"&&window.Blob&&new Blob([atob(encodedJs$1)],{type:"text/javascript;charset=utf-8"});function WorkerWrapper$1(){let e;try{if(e=blob$1&&(window.URL||window.webkitURL).createObjectURL(blob$1),!e)throw"";return new Worker(e)}catch{return new Worker("data:application/javascript;base64,"+encodedJs$1)}finally{e&&(window.URL||window.webkitURL).revokeObjectURL(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 o=new Error(`${c.error}`);o.cause=c.error,console.warn("H264 worker failure",{error:o}),this.onError(c.index);return}this.onReceive(c)});var l;this.worker=t,(l=this.worker)==null||l.addEventListener("message",this.onReceiveMessage),this.onReceive=n,this.onError=r}post(t,n,r,l){var s;(s=this.worker)==null||s.postMessage({timestamp:t,encodedFrame:n,flags:r,index:l})}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:l,texturePosBuffer:s,textureRef:c}=this;n.viewport(0,0,l,r);const o=new Float32Array([1,0,0,0,1,1,0,1]);return n.bindBuffer(n.ARRAY_BUFFER,s),n.bufferData(n.ARRAY_BUFFER,o,n.DYNAMIC_DRAW),n.activeTexture(n.TEXTURE0),n.bindTexture(n.TEXTURE_2D,c),n.texImage2D(n.TEXTURE_2D,0,n.LUMINANCE,l,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=`
64
64
  attribute vec4 vertexPos;
65
65
  attribute vec4 texturePos;