@formant/data-sdk 1.24.0 → 1.25.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.
- package/dist/data-sdk.cjs.js +1 -1
- package/dist/data-sdk.cjs.js.map +1 -1
- package/dist/data-sdk.es.js +3 -0
- package/dist/data-sdk.es.js.map +1 -1
- package/dist/data-sdk.es6.js +3 -0
- package/dist/data-sdk.umd.js +1 -1
- package/dist/types/data-sdk/src/devices/PeerDevice.d.ts +3 -0
- package/package.json +1 -1
package/dist/data-sdk.es6.js
CHANGED
|
@@ -24415,6 +24415,9 @@ class PeerDevice extends BaseDevice {
|
|
|
24415
24415
|
if (n)
|
|
24416
24416
|
throw new Error(`Realtime connection hasn't been started for ${this.id}`);
|
|
24417
24417
|
}
|
|
24418
|
+
async getCommandMetadata() {
|
|
24419
|
+
return (await fetch(`${this.peerUrl}/v1/commands`)).json();
|
|
24420
|
+
}
|
|
24418
24421
|
async sendCommand(n, r, o, l) {
|
|
24419
24422
|
const u = {
|
|
24420
24423
|
value: r,
|
package/dist/data-sdk.umd.js
CHANGED
|
@@ -60,4 +60,4 @@ In order to be iterable, non-array objects must have a [Symbol.iterator]() metho
|
|
|
60
60
|
Found: ${l.toString().split(`
|
|
61
61
|
`)[0]}
|
|
62
62
|
`),Error.captureStackTrace(this,r)}}e.exports=o=>{if(o.length>2)throw new r(o);function l(s={}){this.options=s}function u(s){return new l(s)}return l.prototype.transform=o,u.Format=l,u}},function(e,t,n){function r(u,s){if(!(u instanceof s))throw new TypeError("Cannot call a class as a function")}function o(u,s){for(var g=0;g<s.length;g++){var c=s[g];c.enumerable=c.enumerable||!1,c.configurable=!0,"value"in c&&(c.writable=!0),Object.defineProperty(u,c.key,c)}}var l=n(88);e.exports=function(){function u(){var c=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};r(this,u),this.loggers=new Map,this.options=c}var s,g;return s=u,(g=[{key:"add",value:function(c,d){var w=this;if(!this.loggers.has(c)){var v=(d=Object.assign({},d||this.options)).transports||this.options.transports;d.transports=v?v.slice():[];var y=l(d);y.on("close",function(){return w._delete(c)}),this.loggers.set(c,y)}return this.loggers.get(c)}},{key:"get",value:function(c,d){return this.add(c,d)}},{key:"has",value:function(c){return!!this.loggers.has(c)}},{key:"close",value:function(c){var d=this;if(c)return this._removeLogger(c);this.loggers.forEach(function(w,v){return d._removeLogger(v)})}},{key:"_removeLogger",value:function(c){this.loggers.has(c)&&(this.loggers.get(c).close(),this._delete(c))}},{key:"_delete",value:function(c){this.loggers.delete(c)}}])&&o(s.prototype,g),Object.defineProperty(s,"prototype",{writable:!1}),u}()},function(e,t,n){(function(r){const o=n(51),l=/^([A-Za-z0-9+/]{4})*([A-Za-z0-9+/]{4}|[A-Za-z0-9+/]{3}=|[A-Za-z0-9+/]{2}==)$/;e.exports=function(u,s,g,c){let d,w,v=!1,y=!1;const f=n(94);function p(B){c(s,B)}function S(B,E){let T=`"${s}" ${E}`;throw B&&(T=`${T}`),w&&(T=`${T}. An example of a valid value would be: ${w}`),new o(T)}const N={convertFromBase64:function(){return p("marking for base64 conversion"),v=!0,N},default:function(B){if(typeof B=="number")d=B.toString();else if(Array.isArray(B)||typeof B=="object"&&B!==null)d=JSON.stringify(B);else{if(typeof B!="string")throw new o("values passed to default() must be of Number, String, Array, or Object type");d=B}return p(`setting default value to "${d}"`),N},required:function(B){return B===void 0?(p("marked as required"),y=!0):(p(`setting required flag to ${B}`),y=B),N},example:function(B){return w=B,N}};return Object.entries({...f,...g}).forEach(([B,E])=>{N[B]=function(T){return function(){let h=u[s];if(p(`will be read from the environment using "${T.name}" accessor`),h===void 0)if(d===void 0&&y)p("was not found in the environment, but is required to be set"),S(void 0,"is a required variable, but it was not set");else{if(d===void 0)return void p("was not found in the environment, but is not required. returning undefined");p(`was not found in the environment, parsing default value "${d}" instead`),h=d}y&&(p("verifying variable value is not an empty string"),h.trim().length===0&&S(void 0,"is a required variable, but its value was empty")),v&&(p("verifying variable is a valid base64 string"),h.match(l)||S(h,"should be a valid base64 string if using convertFromBase64"),p("converting from base64 to utf8 string"),h=r.from(h,"base64").toString());const R=[h].concat(Array.prototype.slice.call(arguments));try{p(`passing value "${h}" to "${T.name}" accessor`);const W=T.apply(T,R);return p(`parsed successfully, returning ${W}`),W}catch(W){S(h,W.message)}}}(E)}),N}}).call(this,n(5).Buffer)},function(e,t,n){const r=n(34);e.exports=function(o,l){return l=l||",",o.length?r(o).split(l).filter(Boolean):[]}},function(e,t,n){e.exports=function(r){const o=r.toLowerCase();if(o!=="false"&&o!=="true")throw new Error('should be either "true", "false", "TRUE", or "FALSE"');return o!=="false"}},function(e,t,n){e.exports=function(r){const o=r.toLowerCase();if(["false","0","true","1"].indexOf(o)===-1)throw new Error('should be either "true", "false", "TRUE", "FALSE", 1, or 0');return!(o==="0"||o==="false")}},function(e,t,n){const r=n(95);e.exports=function(o){var l=r(o);if(l>65535)throw new Error("cannot assign a port number greater than 65535");return l}},function(e,t,n){const r=n(34);e.exports=function(o,l){const u=r(o);if(l.indexOf(u)<0)throw new Error(`should be one of [${l.join(", ")}]`);return u}},function(e,t,n){const r=n(53);e.exports=function(o){const l=r(o);if(l>0)throw new Error("should be a negative float");return l}},function(e,t,n){const r=n(53);e.exports=function(o){const l=r(o);if(l<0)throw new Error("should be a positive float");return l}},function(e,t,n){const r=n(52);e.exports=function(o){const l=r(o);if(l>0)throw new Error("should be a negative integer");return l}},function(e,t,n){const r=n(54);e.exports=function(o){var l=r(o);if(!Array.isArray(l))throw new Error("should be a parseable JSON Array");return l}},function(e,t,n){const r=n(54);e.exports=function(o){var l=r(o);if(Array.isArray(l))throw new Error("should be a parseable JSON Object");return l}},function(e,t,n){e.exports=function(r,o){try{RegExp(void 0,o)}catch{throw new Error("invalid regexp flags")}try{return new RegExp(r,o)}catch{throw new Error("should be a valid regexp")}}},function(e,t,n){const r=n(96);e.exports=function(o){return r(o).toString()}},function(e,t,n){const r=n(34),o=/^(?:[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*|"(?:[\u0001-\u0008\u000b\u000c\u000e-\u001f\u0021\u0023-\u005b\u005d-\u007f]|\\[\u0001-\u0009\u000b\u000c\u000e-\u007f])*")@(?:(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?|\[(?:(?:(2(5[0-5]|[0-4][0-9])|1[0-9][0-9]|[1-9]?[0-9]))\.){3}(?:(2(5[0-5]|[0-4][0-9])|1[0-9][0-9]|[1-9]?[0-9])|[a-z0-9-]*[a-z0-9]:(?:[\u0001-\u0008\u000b\u000c\u000e-\u001f\u0021-\u005a\u0053-\u007f]|\\[\u0001-\u0009\u000b\u000c\u000e-\u007f])+)\])$/;e.exports=function(l){const u=r(l);if(!o.test(u))throw new Error("should be a valid email address");return u}},function(e,t,n){e.exports=function(r,o){return function(l,u){o&&o.match(/prod|production/)||r(`env-var (${l}): ${u}`)}}},function(e,t,n){(function(r){(function(){var o,l,u,s,g,c;typeof performance<"u"&&performance!==null&&performance.now?e.exports=function(){return performance.now()}:r!=null&&r.hrtime?(e.exports=function(){return(o()-g)/1e6},l=r.hrtime,s=(o=function(){var d;return 1e9*(d=l())[0]+d[1]})(),c=1e9*r.uptime(),g=s-c):Date.now?(e.exports=function(){return Date.now()-u},u=Date.now()):(e.exports=function(){return new Date().getTime()-u},u=new Date().getTime())}).call(this)}).call(this,n(2))},function(e,t,n){(function(r){(function(o){function l(s){if((s=s===void 0?"utf-8":s)!=="utf-8")throw new RangeError("Failed to construct 'TextEncoder': The encoding label provided ('"+s+"') is invalid.")}function u(s,g){if(g=g===void 0?{fatal:!1}:g,(s=s===void 0?"utf-8":s)!=="utf-8")throw new RangeError("Failed to construct 'TextDecoder': The encoding label provided ('"+s+"') is invalid.");if(g.fatal)throw Error("Failed to construct 'TextDecoder': the 'fatal' option is unsupported.")}if(o.TextEncoder&&o.TextDecoder)return!1;Object.defineProperty(l.prototype,"encoding",{value:"utf-8"}),l.prototype.encode=function(s,g){if((g=g===void 0?{stream:!1}:g).stream)throw Error("Failed to encode: the 'stream' option is unsupported.");g=0;for(var c=s.length,d=0,w=Math.max(32,c+(c>>1)+7),v=new Uint8Array(w>>3<<3);g<c;){var y=s.charCodeAt(g++);if(55296<=y&&56319>=y){if(g<c){var f=s.charCodeAt(g);(64512&f)==56320&&(++g,y=((1023&y)<<10)+(1023&f)+65536)}if(55296<=y&&56319>=y)continue}if(d+4>v.length&&(w+=8,w=(w*=1+g/s.length*2)>>3<<3,(f=new Uint8Array(w)).set(v),v=f),(4294967168&y)==0)v[d++]=y;else{if(!(4294965248&y))v[d++]=y>>6&31|192;else if(!(4294901760&y))v[d++]=y>>12&15|224,v[d++]=y>>6&63|128;else{if(4292870144&y)continue;v[d++]=y>>18&7|240,v[d++]=y>>12&63|128,v[d++]=y>>6&63|128}v[d++]=63&y|128}}return v.slice(0,d)},Object.defineProperty(u.prototype,"encoding",{value:"utf-8"}),Object.defineProperty(u.prototype,"fatal",{value:!1}),Object.defineProperty(u.prototype,"ignoreBOM",{value:!1}),u.prototype.decode=function(s,g){if((g=g===void 0?{stream:!1}:g).stream)throw Error("Failed to decode: the 'stream' option is unsupported.");g=0;for(var c=(s=new Uint8Array(s)).length,d=[];g<c;){var w=s[g++];if(w===0)break;if(!(128&w))d.push(w);else if((224&w)==192){var v=63&s[g++];d.push((31&w)<<6|v)}else if((240&w)==224){v=63&s[g++];var y=63&s[g++];d.push((31&w)<<12|v<<6|y)}else(248&w)==240&&(65535<(w=(7&w)<<18|(v=63&s[g++])<<12|(y=63&s[g++])<<6|63&s[g++])&&(w-=65536,d.push(w>>>10&1023|55296),w=56320|1023&w),d.push(w))}return String.fromCharCode.apply(null,d)},o.TextEncoder=l,o.TextDecoder=u})(typeof window<"u"?window:r!==void 0?r:this)}).call(this,n(6))},function(e,t,n){n.r(t),n.d(t,"AuthClient",function(){return l}),n.d(t,"RtcSignalingClient",function(){return s}),n.d(t,"Credentials",function(){return z}),n.d(t,"SignalingPromiseClient",function(){return P.SignalingPromiseClient}),n.d(t,"RtcClient",function(){return Ht}),n.d(t,"RtcClientV1",function(){return Nt}),n.d(t,"createRtcStreamMessage",function(){return rt});var r=n(26),o=function(_e,F,H,J){return new(H||(H=Promise))(function(oe,se){function ce(fe){try{pe(J.next(fe))}catch(le){se(le)}}function he(fe){try{pe(J.throw(fe))}catch(le){se(le)}}function pe(fe){var le;fe.done?oe(fe.value):(le=fe.value,le instanceof H?le:new H(function(Se){Se(le)})).then(ce,he)}pe((J=J.apply(_e,F||[])).next())})};class l extends r.a{adminSignup(F,H){return o(this,void 0,void 0,function*(){return yield this.fetch("auth/admin-signup",{token:H,method:"POST",body:F})})}login(F){return o(this,void 0,void 0,function*(){return yield this.fetch("auth/login",{method:"POST",body:F,allowUnsafeRetries:!0})})}loginWithGoogleToken(F){return o(this,void 0,void 0,function*(){return yield this.fetch("auth/login-google",{method:"POST",body:F,allowUnsafeRetries:!0})})}refresh(F,H){return o(this,void 0,void 0,function*(){return yield this.fetch("auth/refresh",{method:"POST",body:{refreshToken:F,tokenExpirationSeconds:H},allowUnsafeRetries:!0})})}respondToNewPasswordRequiredChallenge(F){return o(this,void 0,void 0,function*(){return yield this.fetch("auth/respond-to-new-password-required-challenge",{method:"POST",body:F})})}forgotPassword(F){return o(this,void 0,void 0,function*(){return yield this.fetch("auth/forgot-password",{method:"POST",body:{email:F}})})}confirmForgotPassword(F){return o(this,void 0,void 0,function*(){return yield this.fetch("auth/confirm-forgot-password",{method:"POST",body:F})})}resendInvitation(F){return o(this,void 0,void 0,function*(){return yield this.fetch("auth/resend-invitation",{method:"POST",body:{email:F}})})}changePassword({token:F,refreshToken:H,currentPassword:J,newPassword:oe}){return o(this,void 0,void 0,function*(){return yield this.fetch("auth/change-password",{token:F,method:"POST",body:{refreshToken:H,currentPassword:J,newPassword:oe}})})}getDeviceCredentials(F){return o(this,void 0,void 0,function*(){return yield this.fetch("auth/device-credentials",{token:F,method:"POST",allowUnsafeRetries:!0})})}impersonate(F,H){return o(this,void 0,void 0,function*(){return yield this.fetch("auth/impersonate",{token:F,method:"POST",allowUnsafeRetries:!0,body:{userId:H}})})}createServiceAccount(F,H,J,oe){return o(this,void 0,void 0,function*(){return yield this.fetch("auth/service-account",{token:F,method:"POST",allowUnsafeRetries:!0,body:{name:H,roleId:J,tags:oe}})})}getFeatures(F){return o(this,void 0,void 0,function*(){return(yield this.fetch("auth/features",{token:F})).features})}}var u=function(_e,F,H,J){return new(H||(H=Promise))(function(oe,se){function ce(fe){try{pe(J.next(fe))}catch(le){se(le)}}function he(fe){try{pe(J.throw(fe))}catch(le){se(le)}}function pe(fe){var le;fe.done?oe(fe.value):(le=fe.value,le instanceof H?le:new H(function(Se){Se(le)})).then(ce,he)}pe((J=J.apply(_e,F||[])).next())})};class s extends r.a{createPeer(F,H){return u(this,void 0,void 0,function*(){return yield this.fetch("peers",{token:F,method:"POST",body:H})})}getPeers(F){return u(this,void 0,void 0,function*(){return(yield this.fetch("peers",{token:F})).items})}refreshPeer(F,H){return u(this,void 0,void 0,function*(){yield this.fetch(`peers/${H}/refresh`,{token:F,method:"POST",allowUnsafeRetries:!0})})}createSession(F,H){return u(this,void 0,void 0,function*(){return yield this.fetch("sessions",{token:F,method:"POST",body:H})})}refreshSession(F,H){return u(this,void 0,void 0,function*(){yield this.fetch(`sessions/${H}/refresh`,{token:F,method:"POST",allowUnsafeRetries:!0})})}deleteSession(F,H){return u(this,void 0,void 0,function*(){yield this.fetch(`sessions/${H}`,{token:F,method:"DELETE",allowUnsafeRetries:!0})})}getSessions(F){return u(this,void 0,void 0,function*(){return(yield this.fetch("sessions",{token:F})).items})}getIceServers(F){return u(this,void 0,void 0,function*(){return(yield this.fetch("ice-servers",{token:F})).items})}addSignals(F,H,J){return u(this,void 0,void 0,function*(){yield this.fetch(`sessions/${H}/add-signals`,{token:F,method:"POST",body:J})})}takeSignals(F,H){return u(this,void 0,void 0,function*(){return(yield this.fetch(`sessions/${H}/take-signals`,{token:F,method:"POST"})).items})}}var g=n(1),c=n(9),d=n(15),w=n.n(d),v=n(102),y=n.n(v),f=n(4),p=n(0),S=function(_e,F,H,J){return new(H||(H=Promise))(function(oe,se){function ce(fe){try{pe(J.next(fe))}catch(le){se(le)}}function he(fe){try{pe(J.throw(fe))}catch(le){se(le)}}function pe(fe){var le;fe.done?oe(fe.value):(le=fe.value,le instanceof H?le:new H(function(Se){Se(le)})).then(ce,he)}pe((J=J.apply(_e,F||[])).next())})};class N extends class{constructor(F,H){this.type=F,this.name=H}}{constructor(F){super("simple","LogReporter"),this.message=F}send(F){return S(this,void 0,void 0,function*(){var H,J;p.a.debug(this.message,(H=F.reduce((oe,se)=>Object.assign(Object.assign({},oe),{[se.name]:se.stat}),{}),J=oe=>{const{sum:se,count:ce}=oe,he=se/ce;return Object.assign(Object.assign({},oe),{average:he})},Object.keys(H).reduce((oe,se)=>Object.assign(Object.assign({},oe),{[se]:J(H[se])}),{})))})}}var B=n(40);function E(_e){return!!_e.match(/^[a-zA-Z0-9-_.,:?'"()@\/\\#$+ ]{1,255}$/)}var T=function(_e,F,H,J){return new(H||(H=Promise))(function(oe,se){function ce(fe){try{pe(J.next(fe))}catch(le){se(le)}}function he(fe){try{pe(J.throw(fe))}catch(le){se(le)}}function pe(fe){var le;fe.done?oe(fe.value):(le=fe.value,le instanceof H?le:new H(function(Se){Se(le)})).then(ce,he)}pe((J=J.apply(_e,F||[])).next())})};function h({func:_e,delay:F,immediate:H=!1}){let J=!1,oe=setTimeout(function ce(){return T(this,void 0,void 0,function*(){if(J)return;const he=new Date().getTime();try{se=_e(),yield se}finally{if(!J){const pe=new Date().getTime();oe=setTimeout(ce,Math.max(F-(pe-he),0))}}})},H?0:F),se=Promise.resolve();return{stop(){return T(this,void 0,void 0,function*(){J=!0,clearTimeout(oe),yield se})}}}var R=function(_e,F,H,J){return new(H||(H=Promise))(function(oe,se){function ce(fe){try{pe(J.next(fe))}catch(le){se(le)}}function he(fe){try{pe(J.throw(fe))}catch(le){se(le)}}function pe(fe){var le;fe.done?oe(fe.value):(le=fe.value,le instanceof H?le:new H(function(Se){Se(le)})).then(ce,he)}pe((J=J.apply(_e,F||[])).next())})};const W=n(230);class X{constructor(F){this.buffer={},this.reporters=[],this.flushInterval=h({func:()=>this.flushStats(),delay:X.samplePeriodMs}),this.tags=this.filterTags((F==null?void 0:F.tags)||{app:f.a,version:f.j,namespace:f.i,instanceId:B.a})}shutdown(){return R(this,void 0,void 0,function*(){yield this.flushInterval.stop(),yield this.flushStats(),yield Object(c.a)(2*g.a.second)})}aggregate(F,H,J){this.addToBuffer(this.buffer,this.encodeKey({metric:F,tags:this.filterTags(J||{})}),typeof H=="number"?{min:H,max:H,sum:H,count:1}:H)}increment(F,H){this.aggregate(F,1,H)}timer(F,H,J){return R(this,void 0,void 0,function*(){const oe=W(),se=yield H(),ce=W();return this.aggregate(F,ce-oe,J),se})}registerStatsReporter(F){this.reporters.push(F)}setTag(F,H){const J=this.filterTags({[F]:H});this.tags=Object.assign(Object.assign({},this.tags),J)}addToBuffer(F,H,J){if(F[H]){const{min:oe,max:se,sum:ce,count:he}=F[H];F[H]={min:Math.min(oe,J.min),max:Math.max(se,J.max),sum:ce+J.sum,count:he+J.count}}else F[H]=J}write(F){return R(this,void 0,void 0,function*(){yield Promise.all(this.reporters.map(H=>R(this,void 0,void 0,function*(){let J;const oe={};switch(H.type){case"simple":for(const[ce,he]of Object.entries(F)){const{metric:pe}=this.decodeKey(ce);this.addToBuffer(oe,this.encodeKey({metric:pe}),he)}J=oe;break;case"tagged":J=F;break;default:(function(ce){throw new Error(`Unreachable type encountered (${ce})`)})(H.type)}const se=Object.entries(J);if(se.length>0)return H.send(se.map(([ce,he])=>{const{metric:pe,tags:fe}=this.decodeKey(ce);return{name:pe,tags:Object.assign(Object.assign({},fe),this.tags),stat:he}}),X.samplePeriodMs).catch(ce=>{p.a.debug(`Failed to write stats to ${H.name}`,{error:ce})})})))})}flushStats(){return R(this,void 0,void 0,function*(){yield this.write(this.buffer),this.buffer={}})}encodeKey(F){return w()(Object.assign(Object.assign({},F),Object.keys(F.tags||{}).length>0?{tags:F.tags}:{}))}decodeKey(F){return JSON.parse(F)}filterTags(F){return Object.entries(F||{}).reduce((H,[J,oe])=>(E(J)&&E(oe)&&(H[J]=oe),H),{})}}X.samplePeriodMs=5*g.a.minute;const m=!!f.c,b=new X;m||["local","on-prem"].includes(f.i)||b.registerStatsReporter(new N("stats"));var G=function(_e,F,H,J){return new(H||(H=Promise))(function(oe,se){function ce(fe){try{pe(J.next(fe))}catch(le){se(le)}}function he(fe){try{pe(J.throw(fe))}catch(le){se(le)}}function pe(fe){var le;fe.done?oe(fe.value):(le=fe.value,le instanceof H?le:new H(function(Se){Se(le)})).then(ce,he)}pe((J=J.apply(_e,F||[])).next())})};class j extends class{constructor(F){this.options=F,this.cache=new y.a(Object.assign(Object.assign(Object.assign({},F.dispose||F.disposeAfter?{ttlAutopurge:!0}:{}),F),{dispose:(...H)=>{var J;H[2]==="evict"&&b.increment("lru-eviction",{name:F.name}),(J=F.dispose)===null||J===void 0||J.call(F,...H)},disposeAfter:(...H)=>{var J;this.updateStats(),(J=F.disposeAfter)===null||J===void 0||J.call(F,...H)}})),this.stringify=F.fastStringify?JSON.stringify:w.a}set(F,H,J){const oe=this.stringify(F);if(!this.cache.set(oe,H,{ttl:J})){const se=this.cache.sizeCalculation?this.cache.sizeCalculation(H,oe):"unknown";throw Error(`Value too large (${se} > ${this.cache.max})`)}this.updateStats()}get(F){const{name:H}=this.options,J=this.stringify(F),oe=this.cache.getRemainingTTL(J);return oe<=0?b.increment("cache-miss",{name:H}):oe!==1/0&&b.aggregate("cache-item-ttl",oe,{name:H}),this.cache.get(J)}delete(F){this.cache.delete(this.stringify(F))}peek(F){return this.cache.peek(this.stringify(F))}size(){return this.cache.size}clear(){this.cache.clear()}forEach(F){this.cache.forEach(F)}purgeStale(){return this.cache.purgeStale()}updateStats(){const{name:F}=this.options;b.aggregate("cache-item-count",this.cache.size,{name:F}),this.cache.calculatedSize!==void 0&&b.aggregate("cache-length",this.cache.calculatedSize,{name:F})}}{constructor(F){if(super(F),this.expireRejectedPromiseValues=F.expireRejectedPromiseValues===void 0||F.expireRejectedPromiseValues,this.rejectedPromiseValueTtl=F.rejectedPromiseValueTtl!==void 0?F.rejectedPromiseValueTtl:g.a.second,this.rejectedPromiseValueTtl<0)throw new Error("rejectedPromiseValueTtl must not be negative")}set(F,H,J){super.set(F,H,J),this.expireRejectedPromiseValues&&H.catch(()=>G(this,void 0,void 0,function*(){yield Object(c.a)(this.rejectedPromiseValueTtl),this.peek(F)===H&&this.delete(F)}))}}var C=function(_e,F,H,J){return new(H||(H=Promise))(function(oe,se){function ce(fe){try{pe(J.next(fe))}catch(le){se(le)}}function he(fe){try{pe(J.throw(fe))}catch(le){se(le)}}function pe(fe){var le;fe.done?oe(fe.value):(le=fe.value,le instanceof H?le:new H(function(Se){Se(le)})).then(ce,he)}pe((J=J.apply(_e,F||[])).next())})};class z{constructor(F,H,J){this.authClient=F,this.email=H,this.password=J,this.tokenTtlMs=1*g.a.hour,this.tokenCache=new j({name:"Credentials-tokenCache",max:100,ttl:this.tokenTtlMs-5*g.a.minute,fastStringify:!0})}getToken(){return C(this,void 0,void 0,function*(){let F=this.tokenCache.get(this.email);return F||(F=(()=>C(this,void 0,void 0,function*(){const{authentication:H}=yield this.authClient.login({email:this.email,password:this.password,tokenExpirationSeconds:this.tokenTtlMs/g.a.second});if(!H)throw new Error("User account not verified.");return H.accessToken}))(),this.tokenCache.set(this.email,F)),F})}}var P=n(97),D=n(17),O=n(233),L=n(41),U=function(_e,F,H,J){return new(H||(H=Promise))(function(oe,se){function ce(fe){try{pe(J.next(fe))}catch(le){se(le)}}function he(fe){try{pe(J.throw(fe))}catch(le){se(le)}}function pe(fe){var le;fe.done?oe(fe.value):(le=fe.value,le instanceof H?le:new H(function(Se){Se(le)})).then(ce,he)}pe((J=J.apply(_e,F||[])).next())})};class A extends L.a{constructor(F){super(F)}postLanRtcOffer(F){return U(this,void 0,void 0,function*(){return yield this.fetch("v1/lan-rtc-offer",{method:"POST",body:F})})}}var V=function(_e,F,H,J){return new(H||(H=Promise))(function(oe,se){function ce(fe){try{pe(J.next(fe))}catch(le){se(le)}}function he(fe){try{pe(J.throw(fe))}catch(le){se(le)}}function pe(fe){var le;fe.done?oe(fe.value):(le=fe.value,le instanceof H?le:new H(function(Se){Se(le)})).then(ce,he)}pe((J=J.apply(_e,F||[])).next())})};function q(_e){return V(this,void 0,void 0,function*(){return(yield Promise.all(_e.map(F=>F.catch(H=>H)))).filter(F=>F instanceof Error)})}function Q(_e,F){if(_e===void 0)throw new Error(`Value is undefined${F?`: ${F}`:""}`)}function ee(_e,F){if(_e===null)throw new Error(`Value is null${F?`: ${F}`:""}`)}function te(_e){return Q(_e),_e}function k(_e,F){const H=_e.reduce((J,oe)=>[...J,...oe.urls],[]).filter(J=>x(J,F)).sort(J=>_(J,"udp")?-1:0).shift();if(H)return Object.assign(Object.assign({},te(_e.find(J=>J.urls.includes(H)))),{urls:[H]})}function x(_e,F){switch(F){case"stun":return/^stuns?:/.test(_e);case"turn":return/^turns?:/.test(_e)}}function _(_e,F){return _e.endsWith(`transport=${F}`)}var I=n(10);class $ extends Error{constructor(F,H){super(`Deadline expired after ${F}ms + ${H}ms`)}}class K{static withDeadline(F,H){const J=new Promise((oe,se)=>{setTimeout(()=>{se(new $(H,this.grpcCallDeadlineSlopMs))},H+this.grpcCallDeadlineSlopMs)});return Promise.race([F,J])}}K.grpcCallDeadlineSlopMs=500*g.a.millisecond;var Y=n(27);const ne={ordered:!1,maxPacketLifeTime:300*g.a.millisecond},ie={ordered:!0},ue={ordered:!0},we={ordered:!1,maxRetransmits:0},Oe={ordered:!1,maxRetransmits:0},Ee=_e=>"received"in _e&&_e.received!==void 0,De=_e=>!("received"in _e)||_e.received===void 0,Te=2*g.a.second;function Ae(_e,F={}){const H=Array.from(_e.values()),J=H.filter(Ee),oe=J.length>0,se=Math.max(...J.map(fe=>fe.received));let ce;if(oe){const fe=H.length,le=J.length,Se=J.map(Be=>Be.received-Be.sent),{standardDeviation:Ne,mean:Le,jitter:Ge}=function(Be){const Fe=Be.length;if(Fe===0)return{mean:NaN,standardDeviation:-1,jitter:NaN};const Ze=Be.reduce((Qe,ct)=>Qe+ct,0)/Fe,Ke=Math.sqrt(Be.map(Qe=>Math.pow(Qe-Ze,2)).reduce((Qe,ct)=>Qe+ct)/Fe);if(Fe===1)return{mean:Ze,standardDeviation:Ke,jitter:NaN};let Je=0;for(let Qe=1;Qe<Fe;Qe++)Je+=Math.abs(Be[Qe]-Be[Qe-1]);return{mean:Ze,standardDeviation:Ke,jitter:Je/(Fe-1)}}(Se),qe=H.filter(Be=>Be.sent<se-Te),Xe=qe.filter(De),tt=Xe.length===0?0:Xe.length/qe.length;ce={pingsSent:fe,pongsReceived:le,average:Le,standardDeviation:Ne,jitter:Ge,max:Math.max(...Se),min:Math.min(...Se),loss:tt}}else ce=null;const{temporalNow:he=Date.now()}=F,pe=(oe?se:he)-4*Te;return Array.from(_e.entries()).forEach(fe=>{const[le,Se]=fe;Se.sent<pe&&_e.delete(le)}),ce}function Me({entityId:_e,streamName:F,streamType:H}){return`${_e}.${F}.${H}`}var He=function(_e,F,H,J){return new(H||(H=Promise))(function(oe,se){function ce(fe){try{pe(J.next(fe))}catch(le){se(le)}}function he(fe){try{pe(J.throw(fe))}catch(le){se(le)}}function pe(fe){var le;fe.done?oe(fe.value):(le=fe.value,le instanceof H?le:new H(function(Se){Se(le)})).then(ce,he)}pe((J=J.apply(_e,F||[])).next())})};class $e{constructor(F,H){this.counts={localSent:new Map,localReceived:new Map,remoteSent:new Map,remoteReceived:new Map},this.sessionId=F,this.connection=H}updateRemoteMessagesCounts(F){if(F.payload.streamsInfo){this.counts.remoteSent=new Map,this.counts.remoteReceived=new Map;for(const H of F.payload.streamsInfo.items)this.counts.remoteSent.set(H.streamId,H.sentCount),this.counts.remoteReceived.set(H.streamId,H.receivedCount)}}getLocalStreamsInfo(F){const{localSent:H,localReceived:J}=this.counts;return{items:[...new Set([...H.keys(),...J.keys()])].map(oe=>{var se,ce;return{streamId:oe,sentCount:(se=H.get(oe))!==null&&se!==void 0?se:0,receivedCount:(ce=J.get(oe))!==null&&ce!==void 0?ce:0}}),timestamp:F}}incrementLocalSent(F){const{localSent:H}=this.counts,J=Me(F.header.stream);H.set(J,(H.get(J)||0)+1)}incrementLocalReceived(F){const{localReceived:H}=this.counts,J=Me(F.header.stream),oe=H.get(J)||0;if(oe===0){const{streamName:se,streamType:ce}=F.header.stream;p.a.debug("RTC client received first message for stream",{streamName:se,streamType:ce})}H.set(J,oe+1)}uploadMetrics(){return He(this,void 0,void 0,function*(){const{sessionId:F}=this,H=yield this.connection.peerConnection.getStats(),J={};H.forEach(fe=>J[fe.id]=fe),p.a.debug("rtc-stats",Object.assign(Object.assign({},J),{sessionId:F}));const{localSent:oe,localReceived:se,remoteSent:ce,remoteReceived:he}=this.counts,pe=[...new Set([...oe.keys(),...se.keys()])].reduce((fe,le)=>{const Se=oe.get(le),Ne=se.get(le),Le=ce.get(le),Ge=he.get(le);return Object.assign(Object.assign({},fe),{[`local-${le}-sent`]:Se,[`local-${le}-received`]:Ne,[`remote-${le}-sent`]:Le,[`remote-${le}-received`]:Ge})},{sessionId:F});p.a.debug("rtc-message-report",Object.assign({deviceId:this.connection.getRemoteDeviceId()},pe))})}}function rt(_e,F,H){return{header:{stream:_e,created:Date.now(),frameId:H||""},payload:F}}function vt(_e){const F=_e.localCandidate.candidateType,H=_e.remoteCandidate.candidateType;return F==="host"&&H==="host"?"local":F==="relay"||H==="relay"?"TURN":"STUN"}function wt(_e){return new Set(["disconnected","failed","closed"]).has(_e.iceConnectionState)}function Ot(_e){switch(_e.header.stream.streamType){case"twist":{const{twist:F}=_e.payload;if(!F)throw Error("twist not in payload of RTC message with type twist");return{header:_e.header,payload:{twist:{linear:Object.assign({x:0,y:0,z:0},F.linear),angular:Object.assign({x:0,y:0,z:0},F.angular)}}}}case"pose":{const{pose:F}=_e.payload;if(!F)throw Error("pose not in payload of RTC message with type pose");return{header:_e.header,payload:{pose:{translation:Object.assign({x:0,y:0,z:0},F.translation),rotation:Object.assign({x:0,y:0,z:0,w:0},F.rotation)}}}}case"pose-with-covariance":{const{poseWithCovariance:F}=_e.payload;if(!F)throw Error("poseWithCovariance not in payload of RTC message with type pose-with-covariance");const H=new Array(36).fill(0);return F.covariance.forEach((J,oe)=>{if(oe>=36)throw Error("covariance contains more than 36 elements");H[oe]=J}),{header:_e.header,payload:{poseWithCovariance:{pose:{translation:Object.assign({x:0,y:0,z:0},F.pose.translation),rotation:Object.assign({x:0,y:0,z:0,w:0},F.pose.rotation)},covariance:H}}}}case"point":{const{point:F}=_e.payload;if(!F)throw Error("point not in payload of RTC message with type point");return{header:_e.header,payload:{point:Object.assign({x:0,y:0,z:0},F)}}}default:return _e}}var lt=function(_e,F,H,J){return new(H||(H=Promise))(function(oe,se){function ce(fe){try{pe(J.next(fe))}catch(le){se(le)}}function he(fe){try{pe(J.throw(fe))}catch(le){se(le)}}function pe(fe){var le;fe.done?oe(fe.value):(le=fe.value,le instanceof H?le:new H(function(Se){Se(le)})).then(ce,he)}pe((J=J.apply(_e,F||[])).next())})};class mt{get peerConnection(){return ee(this._peerConnection,"RTCPeerConnection is closed!"),this._peerConnection}constructor(F,H,J,oe){this.iceServers=H,this.config=J,this.dataChannelNotifier=oe,this.connectTimeoutMs=20*g.a.second,this.iceGatheringTimeoutMs=3*g.a.second,this.pingUpdateTimeoutMs=1*g.a.second,this.pingV2UpdateTimeoutMs=250*g.a.millisecond,this.pingV2MetricsGatherTimeoutMs=1*g.a.second,this.streamsInfoUpdateTimeoutMs=2*g.a.second,this.reassemblyTimeoutMs=500*g.a.millisecond,this.reassemblyTableCleanupMs=1*g.a.second,this.heartbeatTimeoutMs=20*g.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:ce}=this;if(!ce)return;const he=new Date().getTime(),pe=Object(O.a)();this.sendSystemMessage(ce,{type:"ping-v2",payload:{timestamp:he,id:pe}}),this.pingV2Map.set(pe,{sent:he})},this.gatherPingV2Metrics=()=>{const ce=Ae(this.pingV2Map);if(ce){const he=this.getRemoteDeviceId();this.pingInfo=ce,b.aggregate("rtc-ping-average",ce.average,Object.assign({},he?{deviceId:he}:{})),b.aggregate("rtc-ping-loss",ce.loss,Object.assign({},he?{deviceId:he}:{})),b.aggregate("rtc-jitter",ce.jitter,Object.assign({},he?{deviceId:he}:{}))}},this._peerConnection=F;const{isOffer:se}=J.baseConfig;se?this.initializeChannels(F):F.ondatachannel=ce=>{switch(ce.channel.label){case"stream.latest-ttl":this.latestTtlStreamChannel=ce.channel;break;case"stream.reliable":this.reliableStreamChannel=ce.channel;break;case"stream.latest-reliable":this.latestReliableStreamChannel=ce.channel;break;case"stream.latest-try-once":this.latestTryOnceStreamChannel=ce.channel;break;case"heartbeat":return void(this.heartbeatChannel=ce.channel);default:return void this.dataChannelNotifier(ce.channel)}this.setupChannel(ce.channel)},this.pingUpdateTimeout=setInterval(()=>{const{reliableStreamChannel:ce}=this;ce&&this.sendSystemMessage(ce,{type:"ping"})},this.pingUpdateTimeoutMs),this.pingV2UpdateTimeout=setInterval(this.sendPingV2,this.pingV2UpdateTimeoutMs),this.pingV2MetricsGatherTimeout=setInterval(this.gatherPingV2Metrics,this.pingV2MetricsGatherTimeoutMs),this.streamsInfoUpdateTimeout=setInterval(()=>{const{latestTtlStreamChannel:ce}=this;ce&&this.sendSystemMessage(ce,{type:"streams-info"})},this.streamsInfoUpdateTimeoutMs),this.reassemblyTableCleanupTimeout=setInterval(()=>{const ce=new Date().getTime();this.reassemblyTableLastTimestamp.forEach((he,pe,fe)=>{ce>pe+this.reassemblyTimeoutMs&&this.reassemblyTable.delete(he)})},this.reassemblyTableCleanupMs),this.heartbeatTimeout=setInterval(()=>{const{heartbeatChannel:ce}=this;ce&&ce.readyState==="open"&&ce.send(new Uint8Array([1]))},this.heartbeatTimeoutMs)}handleSignal(F){return lt(this,void 0,void 0,function*(){const{peerConnection:H}=this,{track:J}=this.config.baseConfig,oe=(()=>{try{return JSON.parse(F.getPayload())}catch{return}})();if(!oe)return void p.a.error("Received unparseable signal.");p.a.debug("Handling signal",{description:oe});const{sdp:se,type:ce}=oe;if(!se||!ce)return void p.a.warn("Received non-SDP signal");const{signalingState:he,connectionState:pe}=H;if(he!=="stable"||pe!=="connected")if(H.remoteDescription)p.a.warn(`Received SDP after remote description was set: ${se}`);else{if(ce==="offer"){if(he!=="stable")return void p.a.warn("Received offer SDP when signaling is ongoing.");yield H.setRemoteDescription(oe);const fe=yield H.createAnswer();yield H.setLocalDescription(fe);const le=F.clone();return J==null||J("Answer Received",le),le.setPayload(JSON.stringify(fe)),le.setReceiverId(F.getSenderId()),le.setSenderId(F.getReceiverId()),le}if(ce==="answer"){if(he==="stable")return void p.a.warn("Received answer SDP when signaling hasn't started.");yield H.setRemoteDescription(oe)}}else p.a.warn(`Received SDP when already connected: ${se}`)})}send(F,H){const J=this.getChannelFromLabel(H.channelLabel);J?this.sendOnChannel(J,F):p.a.warn("Send called with unexpected channel label",{channelLabel:H.channelLabel})}controlRemoteStream(F){var H;this.sendSystemMessage((ee(H=this.reliableStreamChannel),H),{type:"stream-control",streamControl:F})}isActive(){return new Set(["new","checking","connected","completed"]).has(this.peerConnection.iceConnectionState)||this.isReady()}isReady(){const{reliableStreamChannel:F,latestTtlStreamChannel:H,latestTryOnceStreamChannel:J,latestReliableStreamChannel:oe}=this;return(F==null?void 0:F.readyState)==="open"&&(H==null?void 0:H.readyState)==="open"&&(J==null?void 0:J.readyState)==="open"&&(oe==null?void 0:oe.readyState)==="open"}close(){var F,H,J,oe,se,ce,he;return lt(this,void 0,void 0,function*(){this.closeCalled||(this.closeCalled=!0,yield(F=this.sessionMetrics)===null||F===void 0?void 0:F.uploadMetrics(),ft(this.pingUpdateTimeout),ft(this.pingV2UpdateTimeout),ft(this.pingV2MetricsGatherTimeout),ft(this.reassemblyTableCleanupTimeout),ft(this.streamsInfoUpdateTimeout),ft(this.heartbeatTimeout),(H=this._peerConnection)===null||H===void 0||H.close(),(J=this.heartbeatChannel)===null||J===void 0||J.close(),(oe=this.latestReliableStreamChannel)===null||oe===void 0||oe.close(),(se=this.latestTryOnceStreamChannel)===null||se===void 0||se.close(),(ce=this.latestTtlStreamChannel)===null||ce===void 0||ce.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 F;return(F=this.config.remoteConfig)===null||F===void 0?void 0:F.sessionCreatedTimestamp}setSessionCreatedTimestamp(F){this.config.remoteConfig&&(this.config.remoteConfig.sessionCreatedTimestamp=F)}getSessionId(){var F;return(F=this.config.remoteConfig)===null||F===void 0?void 0:F.sessionId}setSessionId(F){this.config.remoteConfig&&(this.config.remoteConfig.sessionId=F,this.sessionMetrics=new $e(F,this))}getRemotePeerId(){return this.config.baseConfig.remotePeerId}getRemoteDeviceId(){var F;return(F=this.config.baseConfig)===null||F===void 0?void 0:F.remoteDeviceId}setRemoteDeviceId(F){this.config.baseConfig.remoteDeviceId=F}getSessionMetricsMessageCounts(){var F;return(F=this.sessionMetrics)===null||F===void 0?void 0:F.counts}getConnectionStatsInfo(){return lt(this,void 0,void 0,function*(){const{peerConnection:F}=this;if(!F)return;const H=yield F.getStats(null),J=[];H.forEach(pe=>{J.push(pe)});const oe=J.find(pe=>pe.type==="transport");if(!oe)return;const se=J.find(pe=>(pe.type==="candidate-pair"||pe.type==="candidatepair")&&pe.id===oe.selectedCandidatePairId);if(!se)return;const ce=J.find(pe=>pe.id===se.localCandidateId),he=J.find(pe=>pe.id===se.remoteCandidateId);return ce&&he&&(ce.address=ce.address||ce.ip,he.address=he.address||he.ip,ce.address!==void 0&&he.address!==void 0)?{transport:oe,localCandidate:ce,remoteCandidate:he}:void 0})}initializeChannels(F){this.heartbeatChannel=F.createDataChannel("heartbeat",Oe),this.heartbeatChannel.binaryType="arraybuffer",this.latestTtlStreamChannel=F.createDataChannel("stream.latest-ttl",ne),this.latestTtlStreamChannel.binaryType="arraybuffer",this.reliableStreamChannel=F.createDataChannel("stream.reliable",ie),this.reliableStreamChannel.binaryType="arraybuffer",this.latestReliableStreamChannel=F.createDataChannel("stream.latest-reliable",ue),this.latestReliableStreamChannel.binaryType="arraybuffer",this.latestTryOnceStreamChannel=F.createDataChannel("stream.latest-try-once",we),this.latestTryOnceStreamChannel.binaryType="arraybuffer",this.setupChannel(this.latestTtlStreamChannel),this.setupChannel(this.reliableStreamChannel),this.setupChannel(this.latestReliableStreamChannel),this.setupChannel(this.latestTryOnceStreamChannel)}getOffer(){var F,H;return lt(this,void 0,void 0,function*(){const{gotOffer:J}=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 ce=(F=this.config.remoteConfig)===null||F===void 0?void 0:F.sessionId;if(J)return void p.a.debug("Failed to generate offer because gotOffer was already called.");if(this.gotOffer=!0,wt(this.peerConnection))return void p.a.debug("Failed to generate offer because the peer connection was inactive.");const he=se.baseConfig.track;oe.onicecandidate=()=>{this.hasIceCandidate=!0},oe.oniceconnectionstatechange=()=>lt(this,void 0,void 0,function*(){const Le=oe.iceConnectionState;if(Le==="connected"||Le==="completed"){const Ge=yield this.getConnectionStatsInfo(),qe=Ge?vt(Ge):void 0;p.a.info(`ICE connection state changed to ${Le}`,{sessionId:ce,connectionStatsInfo:Ge,iceMode:qe}),he==null||he("ICE connection state change",{iceConnectionState:Le,sessionId:ce,connectionStatsInfo:Ge,iceMode:qe})}}),yield oe.setLocalDescription(yield oe.createOffer());const pe=oe.getConfiguration?oe.getConfiguration().iceTransportPolicy:"all",fe=new Date().getTime();for(;;){const Le=new Date().getTime()-fe;if(Le>this.connectTimeoutMs)return void p.a.debug("Failed to generate offer because ICE gathering timed out.");if(Le>this.iceGatheringTimeoutMs&&this.hasIceCandidate){p.a.debug("ICE gathering partially completed; proceeding",{iceTransportPolicy:pe,waitTime:Le}),he==null||he("ICE gathering partially completed",{sessionId:ce,iceTransportPolicy:pe,waitTime:Le});break}if(oe.iceGatheringState==="complete"){p.a.debug("ICE gathering complete",{iceTransportPolicy:pe,waitTime:Le}),he==null||he("ICE gathering completed",{sessionId:ce,iceTransportPolicy:pe,waitTime:Le});break}yield Object(c.a)(.1*g.a.second)}const le=(H=this.iceServers)!==null&&H!==void 0?H:[];for(const Le of le)"credentialType"in Le&&(Le.credentialType=void 0);const Se=JSON.stringify(le),Ne=new I.Signal;return Ne.setPayload(JSON.stringify(oe.localDescription)),Ne.setSenderId(this.config.baseConfig.localPeerId),Ne.setReceiverId(this.config.baseConfig.remotePeerId),Ne.setIceServers(Se),Ne.setIceTransportPolicy(pe??"all"),this.config.baseConfig.sessionType!==void 0?Ne.setSessionType(this.config.baseConfig.sessionType):Ne.setSessionType(I.SessionType.TELEOP),p.a.debug("Sending offer signal with description",{description:Ne.getPayload()}),Ne})}getLanOffer(){return lt(this,void 0,void 0,function*(){const{peerConnection:F,gotOffer:H}=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(H)return void p.a.debug("Failed to generate offer because gotOffer was already called.");if(this.gotOffer=!0,wt(this.peerConnection))return void p.a.debug("Failed to generate offer because the peer connection was inactive.");yield F.setLocalDescription(yield F.createOffer());const J=new Date().getTime();for(;;){if(new Date().getTime()-J>this.iceGatheringTimeoutMs)return void p.a.debug("Failed to generate offer because ICE gathering timed out.");if(F.iceGatheringState==="complete")break;yield Object(c.a)(.1*g.a.second)}const oe=F.localDescription;if(oe)return p.a.debug("Sending LAN offer signal with description",{description:oe}),oe;p.a.error("Failed to generate LAN offer description")})}handleLanAnswer(F){return lt(this,void 0,void 0,function*(){const{peerConnection:H}=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 H.setRemoteDescription(F)})}getChannelFromLabel(F){switch(F){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(F,H){var J;let oe;try{oe=Object(Y.encode)(JSON.stringify(H))}catch(se){return void p.a.warn("Failed to encode RTC message",{error:se})}try{F.send(oe),(J=this.sessionMetrics)===null||J===void 0||J.incrementLocalSent(H)}catch(se){p.a.warn("Failed to send message to channel",{error:se,channel:F.label})}}channelNotRecognized(F){return F!==this.latestTtlStreamChannel&&F!==this.latestReliableStreamChannel&&F!==this.latestTryOnceStreamChannel&&F!==this.reliableStreamChannel}setupChannel(F){F.onmessage=H=>{if(this.channelNotRecognized(F))return void p.a.warn("Received message on unrecognized data channel.");let J;try{J=JSON.parse(Object(Y.decode)(H.data))}catch(oe){return void p.a.warn("Received unparseable message on RTC stream data channel",{error:oe,channel:F.label})}J.communicationType==="message-chunk"?this.receiveChannelMessageChunk(F,J):this.receiveChannelMessage(F,J)},F.onerror=H=>{p.a.warn(`Channel error: ${H.error}`,{error:H.error,sessionId:this.getSessionId(),channelLabel:F.label})},F.onopen=()=>{p.a.debug("Channel opened",{sessionId:this.getSessionId(),channelLabel:F.label})},F.onclose=()=>{const H={bufferedAmount:F.bufferedAmount,sessionId:this.getSessionId(),channelLabel:F.label};this.closeCalled===!1?p.a.debug("Unexpected channel closed",H):p.a.debug("Channel closed",H)}}receiveChannelMessage(F,H){var J;const{config:oe}=this,{remotePeerId:se}=this.config.baseConfig;this.lastMessageTimestamp=new Date().getTime(),H=Ot(H),(J=this.sessionMetrics)===null||J===void 0||J.incrementLocalReceived(H),this.handleSystemMessage(F,H)||(F===this.latestTryOnceStreamChannel||F===this.latestTtlStreamChannel||F===this.latestReliableStreamChannel)&&!this.isLatestMessage(H)||oe.baseConfig.receive(se,H)}receiveChannelMessageChunk(F,H){const J=this.reassemblyTable.get(H.id)||[];if(J.push(H),J.length===H.total){const oe=function(se){const ce=se.sort((he,pe)=>he.seq<pe.seq?-1:1).map(he=>he.part).reduce((he,pe)=>he+pe);try{return JSON.parse(ce)}catch{return void p.a.warn("Could not reassemble RTC message chunks")}}(J);return oe&&this.receiveChannelMessage(F,oe),void this.reassemblyTable.delete(H.id)}this.reassemblyTable.set(H.id,J),this.reassemblyTableLastTimestamp.set(H.id,new Date().getTime())}handleSystemMessage(F,H){var J,oe;const{config:se}=this,{baseConfig:ce}=se,{remotePeerId:he,remoteDeviceId:pe}=ce;switch(H.header.stream.streamType){case"ping":return this.sendSystemMessage(F,{type:"pong",timestamp:te(H.payload.ping)}),!0;case"pong":{const fe=new Date().getTime()-te(H.payload.pong);return this.pingTimeMs=fe,b.aggregate("rtc-ping-time",fe,Object.assign({},pe?{deviceId:pe}:{})),!0}case"ping-v2":return this.sendPingV2(),!0;case"pong-v2":{const fe=te(H.payload.pongV2),le=this.pingV2Map.get(fe.id);return(le==null?void 0:le.sent)!==fe.timestamp&&p.a.warn("Pong timestamp doesn't match stored value",{currentEntry:le,pong:fe}),this.pingV2Map.set(fe.id,{sent:fe.timestamp,received:new Date().getTime()}),!0}case"streams-info":{const{sessionMetrics:fe}=this,le=(J=H.payload.streamsInfo)===null||J===void 0?void 0:J.timestamp;return!!le&&(fe==null||fe.updateRemoteMessagesCounts(H),(oe=ce.onStreamsInfoUpdate)===null||oe===void 0||oe.call(ce,he,le),!0)}case"stream-control":return!0;default:return!1}}sendSystemMessage(F,H){var J;const{localUserId:oe,localPeerId:se}=this.config.baseConfig;if(F.readyState!=="open")return;const ce={entityId:oe??se,streamName:`$.${H.type}`,streamType:H.type};let he;switch(H.type){case"ping":he={ping:new Date().getTime()};break;case"pong":he={pong:H.timestamp};break;case"ping-v2":he={pingV2:H.payload};break;case"pong-v2":he={pongV2:H.payload};break;case"stream-control":he={streamControl:H.streamControl};break;case"streams-info":he={streamsInfo:(J=this.sessionMetrics)===null||J===void 0?void 0:J.getLocalStreamsInfo(new Date().getTime())}}this.sendOnChannel(F,rt(ce,he))}isLatestMessage(F){const H=Me(F.header.stream),J=(this.streamLatestTimestamp.get(H)||0)<=F.header.created;return J&&this.streamLatestTimestamp.set(H,F.header.created),J}}function ft(_e){_e&&clearInterval(_e)}function xt(){p.a.debug("forceGarbageCollection() triggered"),queueMicrotask(()=>{let _e=document.createElement("img");_e.src=window.URL.createObjectURL(new Blob([new ArrayBuffer(5e7)])),_e.onerror=function(){window.URL.revokeObjectURL(this.src),_e=null}})}function Lt(_e){try{return _e instanceof Error?`${_e.name}: ${_e.message}`:typeof _e=="object"?JSON.stringify(_e):String(_e)}catch{return"Unknown error"}}function Ct(_e){var F,H;return{userId:(F=_e.getUserId())===null||F===void 0?void 0:F.getValue(),deviceId:(H=_e.getDeviceId())===null||H===void 0?void 0:H.getValue(),organizationId:_e.getOrganizationId(),id:_e.getPeerId(),capabilities:[],capabilitySet:{}}}var Ue=function(_e,F,H,J){return new(H||(H=Promise))(function(oe,se){function ce(fe){try{pe(J.next(fe))}catch(le){se(le)}}function he(fe){try{pe(J.throw(fe))}catch(le){se(le)}}function pe(fe){var le;fe.done?oe(fe.value):(le=fe.value,le instanceof H?le:new H(function(Se){Se(le)})).then(ce,he)}pe((J=J.apply(_e,F||[])).next())})};const dt=_e=>_e.map(F=>Object.assign(Object.assign(Object.assign({},F),F.username?{username:"<REDACTED>"}:null),F.credential?{credential:"<REDACTED>"}:null));class Ht{constructor(F){this.config=F,this.grpcCallDeadline=5*g.a.second,this.refreshIntervalDelayMs=2*g.a.second,this.iceServersTtl=30*g.a.minute,this.connections=[],this.localConnections=[],this.isConnectionInitiator=new WeakSet,this.isOutgoingConnection=new Set,this.peerDataChannelListeners=[],this.rtcInstancesConstructed=0,this.statsLoopsExecuted=0;const{refreshIntervalDelayMs:H}=this;this.refreshInterval=h({func:()=>Ue(this,void 0,void 0,function*(){try{yield this.update()}catch(J){p.a.warn("RTC refresh failed",{error:J})}}),delay:H,immediate:!0})}send(F,H,J){const oe=this.getActiveConnection(F);oe?oe.isReady()?oe.send(H,J):p.a.warn("Send called with unready connection."):p.a.warn("Send called with no connection.")}controlRemoteStream(F,H){const J=this.getActiveConnection(F);J?J.isReady()?J.controlRemoteStream(H):p.a.warn("controlRemoteStream called with unready connection."):p.a.warn("controlRemoteStream called with no connection.")}getLocalPeer(){return Ue(this,void 0,void 0,function*(){for(;!this.localPeer;)yield Object(c.a)(.1*g.a.second);return Ct(this.localPeer)})}connect(F,H){var J,oe,se;return Ue(this,void 0,void 0,function*(){if(this.config.lanOnlyMode===!0)throw new Error("connect method called in local only mode.");const{track:ce,signalingClient:he}=this.config,{localPeer:pe,receiveSignalStream:fe,iceServers:le}=this;if(!pe||!fe||!le)return void p.a.warn("Connect called prior to local peer, receiveSignalStream, and ICE servers ready");if(this.getActiveConnection(F))return void p.a.warn("Connect called for peer with existing connection.");if(this.isOutgoingConnection.has(F))return void p.a.warn("Connect called for peer with an existing outgoing connection offer.");this.isOutgoingConnection.add(F);const Se=function(Be,Fe,Ze){const{rtcIceTransportPolicies:Ke,rtcIceServerProtocol:Je,useAllServers:Qe}=Fe||{},ct=Be.map(ut=>Object.assign(Object.assign({},ut),{urls:ut.urls.filter(bt=>{const Bt=(Ke===void 0||Ke.some(It=>x(bt,It)))&&(Je===void 0||_(bt,Je));return Bt||p.a.debug(`Ignoring ICE server: ${bt}`,{organizationId:Ze}),Bt})})).filter(({urls:ut})=>ut.filter(bt=>bt).length>0);return Qe?ct:[k(ct,"stun"),k(ct,"turn")].filter(ut=>ut!==void 0).map(ut=>te(ut))}(le,H);p.a.debug("Received ICE servers:",dt(le)),p.a.debug("Using ICE servers:",dt(Se));const Ne=new mt(yield this.createRTCPeerConnection(Se),Se,{baseConfig:{isOffer:!0,isLan:!1,receive:(Be,Fe)=>this.config.receive(Be,Fe),onStreamsInfoUpdate:this.config.onStreamsInfoUpdate?(Be,Fe)=>{var Ze,Ke;return(Ke=(Ze=this.config).onStreamsInfoUpdate)===null||Ke===void 0?void 0:Ke.call(Ze,Be,Fe)}:void 0,track:this.config.lanOnlyMode?void 0:this.config.track,localUserId:(J=pe.getUserId())===null||J===void 0?void 0:J.getValue(),localPeerId:pe.getPeerId(),remotePeerId:F,sessionType:this.config.sessionType},remoteConfig:{}},Be=>this.onCustomDataChannel(F,Be)),Le=yield Ne.getOffer();if(!Le)return p.a.error("Failed to generate offer."),void this.isOutgoingConnection.delete(F);p.a.debug("Sending offer."),ce==null||ce("Sending offer",Le);const Ge=new I.SendSignalRequest;Ge.setSignal(Le);const qe=yield(()=>Ue(this,void 0,void 0,function*(){try{return yield K.withDeadline(he.sendSignal(Ge,yield this.getMetadata()),this.grpcCallDeadline)}catch(Be){p.a.warn("Error when sending signal",{error:Be})}}))();if(!this.isOutgoingConnection.has(F))return void p.a.debug("No offer set after receiving offer signal response.");p.a.debug("Offer sent.");const Xe=(oe=qe==null?void 0:qe.getSessionId())===null||oe===void 0?void 0:oe.getValue(),tt=(se=qe==null?void 0:qe.getSessionCreatedTimestamp())===null||se===void 0?void 0:se.getValue();return Xe&&tt?(Ne.setSessionId(Xe),Ne.setSessionCreatedTimestamp(tt),this.isOutgoingConnection.delete(F),this.connections.push(Ne),this.isConnectionInitiator.add(Ne),this.setupHandlers(Ne),Xe):(p.a.warn("No session ID or no session created timestamp on send signal response."),void this.isOutgoingConnection.delete(F))})}connectLan(F){var H,J;return Ue(this,void 0,void 0,function*(){const oe=new A(F),se=new mt(yield this.createRTCPeerConnection([]),[],{baseConfig:{isOffer:!0,isLan:!0,receive:(fe,le)=>this.config.receive(fe,le),onStreamsInfoUpdate:this.config.onStreamsInfoUpdate?(fe,le)=>{var Se,Ne;return(Ne=(Se=this.config).onStreamsInfoUpdate)===null||Ne===void 0?void 0:Ne.call(Se,fe,le)}:void 0,track:this.config.lanOnlyMode?void 0:this.config.track,localUserId:(J=(H=this.localPeer)===null||H===void 0?void 0:H.getUserId())===null||J===void 0?void 0:J.getValue(),localPeerId:"lan_client",remotePeerId:F}},fe=>this.onCustomDataChannel(F,fe)),ce=yield se.getLanOffer();if(!ce)return p.a.warn("Could not generate LAN offer"),!1;const he=yield oe.postLanRtcOffer({offer:JSON.stringify(ce)}),pe=new RTCSessionDescription(JSON.parse(he.answer));return yield se.handleLanAnswer(pe),this.localConnections.push(se),this.isConnectionInitiator.add(se),Object(O.a)()})}getConnections(){return[...this.connections,...this.localConnections]}createCustomDataChannel(F,H,J,oe,se){const ce=this.getActiveConnection(F);if(ce&&this.isConnectionInitiator.has(ce)){const pe=ce.peerConnection.createDataChannel("custom."+H,J);return oe&&(pe.binaryType="arraybuffer"),se(F,pe),()=>{}}const he=(pe,fe)=>{F===pe&&fe.label==="custom."+H&&se(F,fe)};return this.peerDataChannelListeners.push(he),()=>{this.peerDataChannelListeners=this.peerDataChannelListeners.filter(pe=>pe!==he)}}onCustomDataChannel(F,H){this.peerDataChannelListeners.forEach(J=>J(F,H))}getConnectionStatus(F){if(this.isOutgoingConnection.has(F))return"connecting";const H=this.getActiveConnection(F);return H?H.isReady()?"connected":"connecting":"disconnected"}getConnectionStatsInfo(F){return Ue(this,void 0,void 0,function*(){const H=this.getActiveConnection(F);if(H)return yield H.getConnectionStatsInfo()})}disconnect(F){return Ue(this,void 0,void 0,function*(){const H=this.getActiveConnection(F);H&&(yield H.close(),this.connections=this.connections.filter(J=>J!==H),this.localConnections=this.localConnections.filter(J=>J!==H))})}getPeers(){return Ue(this,void 0,void 0,function*(){if(this.config.lanOnlyMode)throw new Error("getPeers method cannot be used in local-only mode.");const{signalingClient:F}=this.config,H=yield(()=>Ue(this,void 0,void 0,function*(){try{return yield K.withDeadline(F.getPeers(new I.GetPeersRequest,yield this.getMetadata()),this.grpcCallDeadline)}catch(se){p.a.warn("Error when getting peers",{error:se})}}))();if(!H)return[];const J=H.getPeersList();if(!J)return[];const oe=se=>{var ce,he;return(he=(ce=se.getPeerCreatedTimestamp())===null||ce===void 0?void 0:ce.getValue())!==null&&he!==void 0?he:0};return J.sort((se,ce)=>oe(ce)-oe(se)).map(se=>Ct(se))})}getSessions(){return Ue(this,void 0,void 0,function*(){if(this.config.lanOnlyMode)throw new Error("getPeers method cannot be used in local-only mode.");const{signalingClient:F}=this.config,H=yield(()=>Ue(this,void 0,void 0,function*(){try{return yield K.withDeadline(F.getPeers(new I.GetPeersRequest,yield this.getMetadata()),this.grpcCallDeadline)}catch(se){p.a.warn("Error when getting peers",{error:se})}}))();if(!H)return{};const J=H.getPeersList(),oe={};for(const se of J)oe[se.getPeerId()]=se.getSessionIdsList();return oe})}getPing(F){const H=this.getActiveConnection(F);if(H)return H.getPing();p.a.warn("Attempted to get ping time from inactive peer.")}getPingInfo(F){const H=this.getActiveConnection(F);if(H)return H.getPingInfo();p.a.warn("Attempted to get ping time from inactive peer.")}getLastMessageTimestamp(F){const H=this.getActiveConnection(F);if(H)return H.getLastMessageTimestamp();p.a.warn("Attempted to get last message time from inactive peer.")}getSessionMetricsMessageCounts(F){const H=this.getActiveConnection(F);if(H)return H.getSessionMetricsMessageCounts();p.a.warn("Attempted to get session metrics counts from inactive peer.")}isReady(){if(this.config.lanOnlyMode)return!0;const{localPeer:F,receiveSignalStream:H,iceServers:J}=this;return!!(F&&H&&J)}shutdown(){return Ue(this,void 0,void 0,function*(){p.a.info("Shutdown called on RTC client"),yield this.refreshInterval.stop(),this.receiveSignalStream&&this.receiveSignalStream.cancel();const F=this.connections;this.connections=[],yield this.closeConnections(F);const H=this.localConnections;this.localConnections=[],yield this.closeConnections(H),this.isOutgoingConnection.clear(),this.peerDataChannelListeners=[];const{localPeer:J}=this;if(!J||this.config.lanOnlyMode)return;const{signalingClient:oe}=this.config;yield(()=>Ue(this,void 0,void 0,function*(){try{const se=new I.DeletePeerRequest;se.setPeerId(J.getPeerId()),yield K.withDeadline(oe.deletePeer(se,yield this.getMetadata()),this.grpcCallDeadline)}catch(se){return void p.a.warn("Error deleting local peer",{error:se})}}))()})}createPeer(){return Ue(this,void 0,void 0,function*(){if(this.config.lanOnlyMode)throw new Error("createPeer method cannot be used in local-only mode.");const{signalingClient:F}=this.config,H=yield(()=>Ue(this,void 0,void 0,function*(){try{return yield K.withDeadline(F.createPeer(new I.CreatePeerRequest,yield this.getMetadata()),this.grpcCallDeadline)}catch(oe){const se=oe;p.a.debug("createPeer failed",{error:se});const ce=Lt(se);throw new Error(`Was not able to create peer: ${ce}`)}}))(),J=H==null?void 0:H.getPeer();if(!J)throw new Error("Response did not provide peer.");return this.localPeer=J})}createReceiveSignalStream(){return Ue(this,void 0,void 0,function*(){if(this.config.lanOnlyMode)throw new Error("createReceiveSignalStream method cannot be used in local-only mode.");const{signalingClient:F}=this.config,{localPeer:H,iceServers:J}=this;if(!H||!J)return;const{receiveSignalStream:oe}=this;oe&&oe.cancel();const se=new I.ReceiveSignalStreamRequest;se.setPeerId(H.getPeerId());const ce=yield(()=>Ue(this,void 0,void 0,function*(){try{return F.receiveSignalStream(se,yield this.getMetadata({hasDeadline:!1}))}catch(he){p.a.debug("createReceiveSignalStream failed",{error:he});const pe=Lt(he);throw new Error(`Unable to create receive signal stream: ${pe}`)}}))();if(!ce)throw new Error("Response did not provide stream.");return ce.on("data",he=>Ue(this,void 0,void 0,function*(){var pe,fe,le,Se;const Ne=he.getSignal(),Le=(pe=Ne==null?void 0:Ne.getSessionId())===null||pe===void 0?void 0:pe.getValue(),Ge=Ne==null?void 0:Ne.getSenderId(),qe=Ne==null?void 0:Ne.getReceiverId(),Xe=(fe=Ne==null?void 0:Ne.getSessionCreatedTimestamp())===null||fe===void 0?void 0:fe.getValue();if(!(Ne&&Le&&Ge&&qe&&Xe))return void p.a.warn("Received signal with missing information.");const tt=this.getActiveConnection(Ge);if(tt)if(tt.getSessionId()!==Le){if(p.a.debug("Received signal: different session for a peer we're already connected to."),(tt.getSessionCreatedTimestamp()||0)>Xe)return;const Be=new mt(yield this.createRTCPeerConnection(J),J,{baseConfig:{isOffer:!1,isLan:!1,receive:(Fe,Ze)=>this.config.receive(Fe,Ze),onStreamsInfoUpdate:this.config.onStreamsInfoUpdate?(Fe,Ze)=>{var Ke,Je;return(Je=(Ke=this.config).onStreamsInfoUpdate)===null||Je===void 0?void 0:Je.call(Ke,Fe,Ze)}:void 0,track:this.config.lanOnlyMode?void 0:this.config.track,localPeerId:H.getPeerId(),localUserId:(Se=H.getUserId())===null||Se===void 0?void 0:Se.getValue(),remotePeerId:Ge},remoteConfig:{sessionId:Le,sessionCreatedTimestamp:Xe}},Fe=>this.onCustomDataChannel(Ge,Fe));yield Be.handleSignal(Ne),this.connections.push(Be)}else p.a.debug("Received signal: for an existing connection."),yield tt.handleSignal(Ne);else{p.a.debug("Received signal: new connection.");const Be=new mt(yield this.createRTCPeerConnection(J),J,{baseConfig:{isOffer:!1,isLan:!1,receive:(Fe,Ze)=>this.config.receive(Fe,Ze),onStreamsInfoUpdate:this.config.onStreamsInfoUpdate?(Fe,Ze)=>{var Ke,Je;return(Je=(Ke=this.config).onStreamsInfoUpdate)===null||Je===void 0?void 0:Je.call(Ke,Fe,Ze)}:void 0,track:this.config.lanOnlyMode?void 0:this.config.track,localPeerId:H.getPeerId(),localUserId:(le=H.getUserId())===null||le===void 0?void 0:le.getValue(),remotePeerId:Ge},remoteConfig:{sessionId:Le,sessionCreatedTimestamp:Xe}},Fe=>this.onCustomDataChannel(Ge,Fe));yield Be.handleSignal(Ne),this.connections.push(Be)}})),ce.on("end",()=>{ce.cancel(),this.receiveSignalStream=void 0}),ce.on("error",he=>{switch(he.code){case D.StatusCode.CANCELLED:case D.StatusCode.UNAVAILABLE:case D.StatusCode.UNKNOWN:p.a.debug("Receive signal stream error",{error:he});break;case D.StatusCode.UNAUTHENTICATED:p.a.warn("Receive signal stream error",{error:he});break;default:p.a.error("Receive signal stream error",{error:he})}ce.cancel(),this.receiveSignalStream=void 0}),this.receiveSignalStream=ce})}createRTCPeerConnection(F){var H;return Ue(this,void 0,void 0,function*(){const J=(H=this.config.alternateRTCPeerConnection)!==null&&H!==void 0?H:window.RTCPeerConnection;if(!J)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||xt();try{return new J({iceServers:F})}catch(oe){throw p.a.debug(`Failed to create RTCPeerConnection: ${this.rtcInstancesConstructed} total allocated`),oe}})}closeConnections(F){return Ue(this,void 0,void 0,function*(){const H=yield q(F.map(J=>Ue(this,void 0,void 0,function*(){yield J.close()})));for(const J of H)p.a.warn("Request to close session failed",{error:J})})}getActiveConnection(F){return this.getConnections().find(H=>H.getRemotePeerId()===F&&H.isActive())}update(){var F;return Ue(this,void 0,void 0,function*(){if(this.localConnections=this.localConnections.filter(Se=>Se.isActive()),this.config.lanOnlyMode)return;const{signalingClient:H}=this.config;if(!this.localPeer||!this.receiveSignalStream||!this.iceServers){const Se=[];return this.localPeer||Se.push(this.createPeer()),this.iceServers||Se.push(this.updateIceServers()),yield Promise.all(Se),void(this.receiveSignalStream||(yield this.createReceiveSignalStream()))}const[J,oe]=(se=this.connections,ce=Se=>Se.isActive(),se.reduce((Se,Ne,Le,Ge)=>{const[qe,Xe]=Se;return(ce(Ne,Le,Ge)?qe:Xe).push(Ne),Se},[[],[]]));var se,ce;yield this.closeConnections(oe),this.connections=J,this.gatherConnectionStats().catch(Se=>{p.a.warn("Error calling gatherConnectionStats",{error:Se})}),this.statsLoopsExecuted++;const{localPeer:he}=this,pe=this.connections.filter(Se=>Se.getSessionId).map(Se=>te(Se.getSessionId()));he.setSessionIdsList(pe);const fe=new I.RefreshPeerRequest;fe.setPeer(he);try{yield K.withDeadline(H.refreshPeer(fe,yield this.getMetadata()),this.grpcCallDeadline)}catch(Se){Se instanceof D.RpcError&&Se.code===D.StatusCode.NOT_FOUND?(p.a.warn("Peer expired, creating new peer",{peerId:he.getPeerId()}),yield this.reset()):p.a.warn("Error calling RefreshPeer",{error:Se})}const le=yield this.getPeers();for(const Se of this.connections)Se.setRemoteDeviceId((F=le.find(Ne=>Ne.id===Se.getRemotePeerId()))===null||F===void 0?void 0:F.deviceId)})}gatherConnectionStats(){return Ue(this,void 0,void 0,function*(){if(this.statsLoopsExecuted%10!=0||this.connections.length!==1)return;const F=yield this.connections[0].getConnectionStatsInfo(),H=F?vt(F):void 0;H?(p.a.info(`Detected RTC connection type: ${H}`),b.setTag("rtc-connection-type",H)):b.setTag("rtc-connection-type","unknown")})}reset(){return Ue(this,void 0,void 0,function*(){yield this.closeConnections(this.connections),this.connections=[],this.isOutgoingConnection.clear(),yield this.createPeer(),yield this.createReceiveSignalStream()})}updateIceServers(){return Ue(this,void 0,void 0,function*(){if(this.config.lanOnlyMode)return;const{iceServersLastUpdate:F,iceServersTtl:H}=this,J=new Date().getTime();if(!F||J-F>H)try{const oe=(yield K.withDeadline(this.config.signalingClient.getIceServers(new I.GetIceServersRequest,yield this.getMetadata()),this.grpcCallDeadline)).getIceServers();this.iceServers=JSON.parse(oe),this.iceServersLastUpdate=J}catch(oe){p.a.warn("Error in updateIceServers",{error:oe})}})}setupHandlers(F){const{peerConnection:H}=F,J=F.getSessionCreatedTimestamp();H.onconnectionstatechange=()=>Ue(this,void 0,void 0,function*(){const oe=H.connectionState;if(!J)return;const se=F.getRemoteDeviceId();switch(oe){case"connected":b.aggregate("rtc-connect-time",new Date().getTime()-J,Object.assign({},se?{deviceId:se}:{}));break;case"failed":b.increment("rtc-connect-failed",Object.assign({},se?{deviceId:se}:{}))}})}getMetadata(F={}){return Ue(this,void 0,void 0,function*(){if(this.config.lanOnlyMode)throw new Error("getMetadata method cannot be called in local-only mode");const{getToken:H}=this.config,{grpcCallDeadline:J}=this,{hasDeadline:oe=!0}=F,se=oe?{deadline:(Date.now()+J).toString(10)}:null;try{const ce=yield H();return Object.assign({authorization:ce},se)}catch(ce){throw p.a.error("getToken() failed",{error:ce}),new Error("Cannot get authorization token")}})}}var it=n(12),yt=n(11),St=function(_e,F,H,J){return new(H||(H=Promise))(function(oe,se){function ce(fe){try{pe(J.next(fe))}catch(le){se(le)}}function he(fe){try{pe(J.throw(fe))}catch(le){se(le)}}function pe(fe){var le;fe.done?oe(fe.value):(le=fe.value,le instanceof H?le:new H(function(Se){Se(le)})).then(ce,he)}pe((J=J.apply(_e,F||[])).next())})};class Wt{constructor(F,H){this.sentMessagesCounts=new Map,this.receivedMessagesCounts=new Map,this.sessionId=F,this.connection=H}incrementMessageSent(F){const H=Me(F.header.stream);this.sentMessagesCounts.set(H,(this.sentMessagesCounts.get(H)||0)+1)}incrementMessageReceived(F){const H=Me(F.header.stream);this.receivedMessagesCounts.set(H,(this.receivedMessagesCounts.get(H)||0)+1)}uploadMetrics(){return St(this,void 0,void 0,function*(){const{sessionId:F}=this,H=yield this.connection.peerConnection.getStats(),J={};H.forEach(se=>J[se.id]=se),p.a.debug("rtc-stats",Object.assign(Object.assign({},J),{sessionId:F}));const oe=[...new Set(Array.from(this.sentMessagesCounts.keys()).concat(Array.from(this.receivedMessagesCounts.keys())))].reduce((se,ce)=>{const he=this.sentMessagesCounts.get(ce),pe=this.receivedMessagesCounts.get(ce);return Object.assign(Object.assign({},se),{[`${ce}-sent`]:he,[`${ce}-received`]:pe})},{sessionId:F});p.a.debug("rtc-message-report",oe)})}}function kt(_e,F){return Me(_e)===Me(F)}var ot=function(_e,F,H,J){return new(H||(H=Promise))(function(oe,se){function ce(fe){try{pe(J.next(fe))}catch(le){se(le)}}function he(fe){try{pe(J.throw(fe))}catch(le){se(le)}}function pe(fe){var le;fe.done?oe(fe.value):(le=fe.value,le instanceof H?le:new H(function(Se){Se(le)})).then(ce,he)}pe((J=J.apply(_e,F||[])).next())})};class Et{constructor(F,H){this.peerConnection=F,this.config=H,this.connectTimeoutMs=10*g.a.second,this.gatherIceTimeoutMs=5*g.a.second,this.pingUpdateTimeoutMs=2*g.a.second,this.streamLatestTimestamp=new Map,this.closeCalled=!1,this.connectCalled=!1,this.sentOffer=!1,this.receivedIceCandidate=!1;const{isOffer:J}=H;J?this.initializeChannels(F):F.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 Wt(this.getSessionId(),this)}connect(){return ot(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(()=>ot(this,void 0,void 0,function*(){this.isReady()||(p.a.warn("RTC connect timed out, closing connection"),yield this.close())}),this.connectTimeoutMs);const{peerConnection:F,config:{isOffer:H,sessionId:J}}=this;if(H){const oe=yield F.createOffer();yield F.setLocalDescription(oe)}H&&(this.gatherIceTimeout=setTimeout(()=>ot(this,void 0,void 0,function*(){this.sentOffer||(p.a.warn("ICE gathering timed out"),this.receivedIceCandidate?(p.a.warn("Attempting to connect with partial ICE candidate pool"),yield this.sendOffer()):yield this.close())}),this.gatherIceTimeoutMs),F.onicecandidate=oe=>ot(this,void 0,void 0,function*(){oe.candidate?this.receivedIceCandidate=!0:yield this.sendOffer()}),F.onicegatheringstatechange=()=>ot(this,void 0,void 0,function*(){F.iceGatheringState==="complete"&&(yield this.sendOffer())}),F.onnegotiationneeded=()=>{p.a.debug("Negotiation needed",{sessionId:J})})})}handleSignal(F){return ot(this,void 0,void 0,function*(){const{peerConnection:H,config:{sessionId:J,sendSignal:oe}}=this,{description:se}=JSON.parse(F.payload);if(p.a.debug("Handling signal",{sessionId:J,description:JSON.stringify(se)}),se)if(H.signalingState!=="stable"||H.connectionState!=="connected")if(H.remoteDescription)p.a.warn(`Received SDP signal during negotiation when remote description is already set: ${JSON.stringify(F)}`);else if(se.type==="offer"){yield H.setRemoteDescription(se);const ce=yield H.createAnswer();yield H.setLocalDescription(ce),yield oe({payload:JSON.stringify({description:ce})})}else se.type==="answer"&&(yield H.setRemoteDescription(se));else p.a.warn(`Received SDP signal when signaling is stable and connected: ${JSON.stringify(F)}`);else p.a.warn(`Received non-SDP signal: ${JSON.stringify(F)}`)})}send(F,H){const J=this.getChannelFromLabel(H.channelLabel);J?this.sendOnChannel(J,F):p.a.warn("Send called with unexpected channel label",{channelLabel:H.channelLabel})}controlRemoteStream(F){this.sendSystemMessage(te(this.reliableStreamChannel),{type:"stream-control",streamControl:F})}isActive(){return new Set(["new","connecting","connected"]).has(this.peerConnection.connectionState)}isReady(){const{peerConnection:F,latestTtlStreamChannel:H,reliableStreamChannel:J,latestTryOnceStreamChannel:oe}=this;return!!(J&&H&&oe)&&F.connectionState==="connected"&&J.readyState==="open"&&H.readyState==="open"&&oe.readyState==="open"}isClosed(){const{peerConnection:F,reliableStreamChannel:H,latestTryOnceStreamChannel:J,latestTtlStreamChannel:oe}=this;return!(F.connectionState!=="closed"||H!==void 0&&H.readyState!=="closed"||J!==void 0&&J.readyState!=="closed"||oe!==void 0&&oe.readyState!=="closed")}needsClosing(){const{peerConnection:F,latestTtlStreamChannel:H,reliableStreamChannel:J,latestTryOnceStreamChannel:oe}=this;if(this.isClosed())return!1;const se=new Set(["closing","closed"]),ce=he=>he&&se.has(he.readyState);return wt(F)||ce(H)||ce(J)||ce(oe)}close(){return ot(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(F){this.latestTtlStreamChannel=F.createDataChannel("stream.latest-ttl",ne),this.reliableStreamChannel=F.createDataChannel("stream.reliable",ie),this.latestReliableStreamChannel=F.createDataChannel("stream.latest-reliable",ue),this.latestTryOnceStreamChannel=F.createDataChannel("stream.latest-try-once",we),this.setupChannel(this.latestTtlStreamChannel),this.setupChannel(this.reliableStreamChannel),this.setupChannel(this.latestReliableStreamChannel),this.setupChannel(this.latestTryOnceStreamChannel)}sendOffer(){return ot(this,void 0,void 0,function*(){if(this.sentOffer||(this.sentOffer=!0,wt(this.peerConnection)))return;const{peerConnection:F,config:{sendSignal:H}}=this,J=yield F.createOffer();yield F.setLocalDescription(J);const oe={payload:JSON.stringify({description:J})};yield H(oe)})}getChannelFromLabel(F){switch(F){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(F,H){let J;try{J=Object(Y.encode)(JSON.stringify(H))}catch(oe){return void p.a.warn("Failed to encode RTC message",{error:oe})}try{F.send(J),this.sessionMetrics.incrementMessageSent(H)}catch(oe){p.a.warn("Failed to send message to channel",{error:oe,channel:F.label})}}channelNotRecognized(F){return F!==this.latestTtlStreamChannel&&F!==this.latestReliableStreamChannel&&F!==this.latestTryOnceStreamChannel&&F!==this.reliableStreamChannel}setupChannel(F){F.onmessage=H=>{if(this.channelNotRecognized(F))return void p.a.warn("Received message on unrecognized data channel.");let J;try{J=JSON.parse(Object(Y.decode)(H.data))}catch(oe){return void p.a.warn("Received unparseable RTC message",{error:oe,channel:F.label})}if(this.lastMessageTimestamp=new Date().getTime(),J=Ot(J),this.sessionMetrics.incrementMessageReceived(J),!this.handleSystemMessage(F,J)){if(!this.hasCapabilities(J))return void p.a.warn("Received RTC message that was not within the capability scope of the connection.");(F===this.latestTryOnceStreamChannel||F===this.latestTtlStreamChannel||F===this.latestReliableStreamChannel)&&!this.isLatestMessage(J)||this.config.receive(this.config.remotePeer.id,J)}},F.onerror=H=>{p.a.warn(`Channel error: ${H.error}`,{error:H.error,sessionId:this.getSessionId(),channelLabel:F.label})},F.onopen=()=>{p.a.debug("Channel opened",{sessionId:this.getSessionId(),channelLabel:F.label})},F.onclose=()=>{const H={bufferedAmount:F.bufferedAmount,sessionId:this.getSessionId(),channelLabel:F.label};this.closeCalled===!1?p.a.debug("Unexpected channel closed",H):p.a.debug("Channel closed",H)}}handleSystemMessage(F,H){switch(H.header.stream.streamType){case"ping":return this.sendSystemMessage(F,{type:"pong",timestamp:te(H.payload.ping)}),!0;case"pong":{const J=new Date().getTime()-te(H.payload.pong);return this.pingTimeMs=J,b.aggregate("rtc-ping-time",J),!0}case"stream-control":return!0;default:return!1}}sendSystemMessage(F,H){if(F.readyState!=="open")return;const J={entityId:te(this.config.localPeer.deviceId||this.config.localPeer.userId),streamName:`$.${H.type}`,streamType:H.type};let oe;switch(H.type){case"ping":oe={ping:new Date().getTime()};break;case"pong":oe={pong:H.timestamp};break;case"stream-control":oe={streamControl:H.streamControl}}this.sendOnChannel(F,rt(J,oe))}hasCapabilities(F){var H,J;const{localPeer:oe,remotePeer:se}=this.config,ce=(H=oe.capabilitySet.streaming)===null||H===void 0?void 0:H.streams,he=ce&&ce.some(le=>le.receive&&kt(le.stream,F.header.stream)),pe=(J=se.capabilitySet.streaming)===null||J===void 0?void 0:J.streams,fe=pe&&pe.some(le=>le.send&&kt(le.stream,F.header.stream));return he||fe}isLatestMessage(F){const H=Me(F.header.stream),J=(this.streamLatestTimestamp.get(H)||0)<=F.header.created;return J&&this.streamLatestTimestamp.set(H,F.header.created),J}}var ze=function(_e,F,H,J){return new(H||(H=Promise))(function(oe,se){function ce(fe){try{pe(J.next(fe))}catch(le){se(le)}}function he(fe){try{pe(J.throw(fe))}catch(le){se(le)}}function pe(fe){var le;fe.done?oe(fe.value):(le=fe.value,le instanceof H?le:new H(function(Se){Se(le)})).then(ce,he)}pe((J=J.apply(_e,F||[])).next())})};class Nt{constructor(F){this.config=F,this.connections=[],this.connectingSessions=new Map,this.rtcInstancesConstructed=0,this.updateInterval=h({func:()=>ze(this,void 0,void 0,function*(){try{yield this.update()}catch(H){p.a.warn("RTC update failed",{error:H})}}),delay:250*g.a.millisecond,immediate:!0}),this.localPeer=this.createPeer()}send(F,H,J){const oe=this.getActiveConnection(F);oe?oe.isReady()?oe.send(H,J):p.a.warn("Attempted to send with an active connection to that peer which was not yet ready."):p.a.warn("Attempted to send with no active connection to that peer.")}controlRemoteStream(F,H){const J=this.getActiveConnection(F);J?J.isReady()?J.controlRemoteStream(H):p.a.warn("Attempted to control remote stream with an active connection to that peer which was not yet ready."):p.a.warn("Attempted to control remote stream with no active connection to that peer.")}connect(F){return ze(this,void 0,void 0,function*(){const H=yield this.getLocalPeer();if(this.getActiveConnection(F))return void p.a.warn("Attempted to connect to peer with an already active connection.");let J;try{J=yield this.config.signalingClient.createSession(yield this.config.getToken(),{offerPeerId:H.id,answerPeerId:F})}catch(oe){Object(it.a)(oe,yt.a,se=>se.statusCode===404),p.a.warn("Attempted to connect to peer that does not exist.")}if(J)for(this.connectingSessions.set(J.id,new Date().getTime()),yield this.connectToSession(J);;)switch(yield Object(c.a)(.1),this.getConnectionStatus(F)){case"connecting":continue;case"connected":return J.id;case"disconnected":return}})}getConnectionStatus(F){const H=this.getActiveConnection(F);return H?H.isReady()?"connected":"connecting":"disconnected"}getIceMode(F){const H=this.getActiveConnection(F);if(H)return H.iceMode}disconnect(F){return ze(this,void 0,void 0,function*(){const H=this.getActiveConnection(F);H&&(yield this.closeConnection(H))})}getLocalPeer(){return ze(this,void 0,void 0,function*(){return yield this.localPeer})}getPeers(){return ze(this,void 0,void 0,function*(){return yield this.config.signalingClient.getPeers(yield this.config.getToken())})}getPing(F){const H=this.getActiveConnection(F);if(H)return H.getPing();p.a.warn("Attempted to get ping time from inactive peer.")}getLastMessageTimestamp(F){const H=this.getActiveConnection(F);if(H)return H.getLastMessageTimestamp();p.a.warn("Attempted to get ping time from inactive peer.")}shutdown(){return ze(this,void 0,void 0,function*(){yield this.updateInterval.stop();const F=this.connections;this.connections=[],yield this.closeConnections(F)})}closeConnection(F){return ze(this,void 0,void 0,function*(){this.connectingSessions.delete(F.getSessionId()),yield F.close();try{yield this.config.signalingClient.deleteSession(yield this.config.getToken(),F.getSessionId())}catch(H){Object(it.a)(H,yt.a,J=>J.statusCode===404)}})}getSessions(){return ze(this,void 0,void 0,function*(){const F=yield this.getLocalPeer();return(yield this.config.signalingClient.getSessions(yield this.config.getToken())).filter(H=>H.offer.peer.id===F.id||H.answer.peer.id===F.id)})}createPeer(){return ze(this,void 0,void 0,function*(){return yield this.config.signalingClient.createPeer(yield this.config.getToken(),{capabilitySet:this.config.capabilitySet||{}})})}createRTCPeerConnection(F={}){return ze(this,void 0,void 0,function*(){const H=this.config.alternateRTCPeerConnection||RTCPeerConnection;this.rtcInstancesConstructed++,this.rtcInstancesConstructed%20||xt();try{return new H(Object.assign({iceServers:yield this.config.signalingClient.getIceServers(yield this.config.getToken())},F))}catch(J){throw p.a.debug(`Failed to create RTCPeerConnection: ${this.rtcInstancesConstructed} total allocated`),J}})}closeConnections(F){return ze(this,void 0,void 0,function*(){const H=yield q(F.map(J=>ze(this,void 0,void 0,function*(){yield this.closeConnection(J)})));for(const J of H)p.a.warn("Request to close session failed",{error:J})})}reset(){return ze(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(F){return this.connections.find(H=>H.getRemotePeer().id===F&&H.isActive())}update(){return ze(this,void 0,void 0,function*(){const F=yield this.getLocalPeer();try{yield this.config.signalingClient.refreshPeer(yield this.config.getToken(),F.id)}catch(H){Object(it.a)(H,yt.a,J=>J.statusCode===404),p.a.warn("Peer expired, creating new peer",{peerId:F.id}),yield this.reset()}yield this.handleSessions(yield this.getSessions())})}handleSessions(F){return ze(this,void 0,void 0,function*(){yield this.syncConnectionsAndSessions(F);const H=F.map(J=>({session:J,connection:this.connections.find(oe=>oe.getSessionId()===J.id)}));yield Promise.all(H.map(({session:J,connection:oe})=>ze(this,void 0,void 0,function*(){return yield this.maintainConnection(J,oe)})))})}syncConnectionsAndSessions(F){return ze(this,void 0,void 0,function*(){const H=new Set(F.map(se=>se.id)),J=se=>H.has(se.getSessionId())||this.connectingSessions.has(se.getSessionId());this.connections=this.connections.filter(se=>J(se));const oe=this.connections.filter(se=>!J(se)||se.needsClosing());yield Promise.all(oe.map(se=>ze(this,void 0,void 0,function*(){yield this.closeConnection(se)})))})}maintainConnection(F,H){return ze(this,void 0,void 0,function*(){const J=yield this.getLocalPeer(),oe=F.offer.peer.id===J.id;if(H){if(H.isReady())try{yield this.config.signalingClient.refreshSession(yield this.config.getToken(),F.id)}catch(se){Object(it.a)(se,yt.a,ce=>ce.statusCode===404),p.a.debug("Refresh session not found",{sessionId:F.id})}else if(H.isActive())try{yield this.consumeSignals(H)}catch(se){p.a.warn("Failed to ingest signals, closing connection",{error:se}),yield this.closeConnection(H)}}else{if(oe)return;yield this.connectToSession(F)}})}connectToSession(F){return ze(this,void 0,void 0,function*(){const H=yield this.getLocalPeer(),J=F.offer.peer.id===H.id,oe=yield this.createRTCPeerConnection(),se=new Et(oe,{localPeer:J?F.offer.peer:F.answer.peer,remotePeer:J?F.answer.peer:F.offer.peer,sessionId:F.id,isOffer:J,sendSignal:ce=>this.sendSignal(F.id,ce),receive:(ce,he)=>this.config.receive(ce,he)});if(this.connections.find(ce=>ce.getSessionId()===F.id))return p.a.warn("connectToSession called on a session that already has a connection.",{sessionId:F.id}),void(yield se.close());this.setupHandlers(se),this.connections.push(se);try{yield se.connect()}catch(ce){p.a.warn("Failed to handle negotiation, closing connection",{error:ce}),yield this.closeConnection(se)}})}setupHandlers(F){const{peerConnection:H}=F,J=F.getSessionId();H.onconnectionstatechange=()=>ze(this,void 0,void 0,function*(){const oe=this.connectingSessions.get(J);if(oe===void 0)return;const se=H.connectionState;switch(wt(H)&&this.connectingSessions.delete(J),se){case"connected":{this.connectingSessions.delete(J);const ce=new Date().getTime()-oe;b.aggregate("rtc-connect-time",ce);break}case"failed":b.increment("rtc-connect-failed"),yield this.closeConnection(F)}})}consumeSignals(F){return ze(this,void 0,void 0,function*(){let H=[];try{H=yield this.config.signalingClient.takeSignals(yield this.config.getToken(),F.getSessionId())}catch(J){Object(it.a)(J,yt.a,oe=>oe.statusCode===404)}for(const J of H)yield F.handleSignal(J)})}sendSignal(F,H){return ze(this,void 0,void 0,function*(){try{yield this.config.signalingClient.addSignals(yield this.config.getToken(),F,{signals:[H]})}catch(J){Object(it.a)(J,yt.a,oe=>oe.statusCode===404)}})}}},function(e,t,n){var r={randomUUID:typeof crypto<"u"&&crypto.randomUUID&&crypto.randomUUID.bind(crypto)};let o;const l=new Uint8Array(16);function u(){if(!o&&(o=typeof crypto<"u"&&crypto.getRandomValues&&crypto.getRandomValues.bind(crypto),!o))throw new Error("crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported");return o(l)}const s=[];for(let c=0;c<256;++c)s.push((c+256).toString(16).slice(1));function g(c,d=0){return(s[c[d+0]]+s[c[d+1]]+s[c[d+2]]+s[c[d+3]]+"-"+s[c[d+4]]+s[c[d+5]]+"-"+s[c[d+6]]+s[c[d+7]]+"-"+s[c[d+8]]+s[c[d+9]]+"-"+s[c[d+10]]+s[c[d+11]]+s[c[d+12]]+s[c[d+13]]+s[c[d+14]]+s[c[d+15]]).toLowerCase()}t.a=function(c,d,w){if(r.randomUUID&&!d&&!c)return r.randomUUID();const v=(c=c||{}).random||(c.rng||u)();if(v[6]=15&v[6]|64,v[8]=63&v[8]|128,d){w=w||0;for(let y=0;y<16;++y)d[w+y]=v[y];return d}return g(v)}},,function(e,t,n){n.r(t),n.d(t,"LogClient",function(){return s});var r=n(26),o=n(12),l=n(11),u=function(g,c,d,w){return new(d||(d=Promise))(function(v,y){function f(N){try{S(w.next(N))}catch(B){y(B)}}function p(N){try{S(w.throw(N))}catch(B){y(B)}}function S(N){var B;N.done?v(N.value):(B=N.value,B instanceof d?B:new d(function(E){E(B)})).then(f,p)}S((w=w.apply(g,c||[])).next())})};class s extends r.a{log(c){return u(this,void 0,void 0,function*(){const d=s.token;try{yield this.fetch("logs",{token:d,method:"POST",body:{logs:c},allowUnsafeRetries:!0})}catch(w){Object(o.a)(w,l.a,v=>v.statusCode===401&&d!==void 0),s.token===d&&delete s.token,yield this.log(c)}})}}}])})})(dist);var distExports=dist.exports;const SessionTypes={UNKNOWN:0,TELEOP:1,PORT_FORWARD:2,OBSERVE:3,HEADLESS:4},SessionTypeConstants={...SessionTypes,Unknown:SessionTypes.UNKNOWN,Teleop:SessionTypes.TELEOP,PortForward:SessionTypes.PORT_FORWARD,Observe:SessionTypes.OBSERVE,Headless:SessionTypes.HEADLESS,unknown:SessionTypes.UNKNOWN,teleop:SessionTypes.TELEOP,portForward:SessionTypes.PORT_FORWARD,observe:SessionTypes.OBSERVE,headless:SessionTypes.HEADLESS},singleton=Symbol("RtcClientPool.instance");class RtcClientPool{constructor(t){be(this,et,null);be(this,"createClient");be(this,"ttlMs");be(this,"proxyHandler");be(this,"proxyReceivers",new Map);be(this,"teardownTimeout",null);be(this,"dispatch",(t,n)=>{this.proxyReceivers.forEach(r=>r==null?void 0:r(t,n))});const{createClient:n,ttlMs:r=0}=t;this.createClient=n,this.ttlMs=Math.max(r,0),this.proxyHandler={get:(o,l,u)=>{switch(l){case"shutdown":return()=>this.releaseInstance(u);default:return Reflect.get(o,l,u)}}}}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),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)}}et=singleton;const getToken=async()=>defined(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){be(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){be(this,"ready",!1);be(this,"listeners",[]);be(this,"openListeners",[]);be(this,"closeListeners",[]);be(this,"errorListeners",[]);be(this,"binaryListeners",[]);be(this,"error");be(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 o=new Uint8Array(n.data),l=this.decoder.decode(o);r(l)}),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 o=setInterval(()=>{this.dataChannel.readyState==="open"&&this.setReady(),this.ready&&(clearInterval(o),n(!0)),this.error&&r(this.error)},10)})}send(t){if(!this.ready)throw new Error("Connection has been closed");this.dataChannel.send(t)}sendBinary(t){if(!this.ready)throw new Error("Connection has been closed");this.dataChannel.send(t)}addListener(t){this.listeners.push(t)}removeListener(t){const n=this.listeners.indexOf(t);if(n===-1)throw new Error("Could not find data channel listener to remove");if(this.error)throw new Error(this.error);this.listeners.splice(n,1)}addBinaryListener(t){this.binaryListeners.push(t)}removeBinaryListener(t){const n=this.binaryListeners.indexOf(t);if(n===-1)throw new Error("Could not find data channel listener to remove");if(this.error)throw new Error(this.error);this.binaryListeners.splice(n,1)}}var eventemitter3={exports:{}};(function(e){var t=Object.prototype.hasOwnProperty,n="~";function r(){}Object.create&&(r.prototype=Object.create(null),new r().__proto__||(n=!1));function o(g,c,d){this.fn=g,this.context=c,this.once=d||!1}function l(g,c,d,w,v){if(typeof d!="function")throw new TypeError("The listener must be a function");var y=new o(d,w||g,v),f=n?n+c:c;return g._events[f]?g._events[f].fn?g._events[f]=[g._events[f],y]:g._events[f].push(y):(g._events[f]=y,g._eventsCount++),g}function u(g,c){--g._eventsCount===0?g._events=new r:delete g._events[c]}function s(){this._events=new r,this._eventsCount=0}s.prototype.eventNames=function(){var c=[],d,w;if(this._eventsCount===0)return c;for(w in d=this._events)t.call(d,w)&&c.push(n?w.slice(1):w);return Object.getOwnPropertySymbols?c.concat(Object.getOwnPropertySymbols(d)):c},s.prototype.listeners=function(c){var d=n?n+c:c,w=this._events[d];if(!w)return[];if(w.fn)return[w.fn];for(var v=0,y=w.length,f=new Array(y);v<y;v++)f[v]=w[v].fn;return f},s.prototype.listenerCount=function(c){var d=n?n+c:c,w=this._events[d];return w?w.fn?1:w.length:0},s.prototype.emit=function(c,d,w,v,y,f){var p=n?n+c:c;if(!this._events[p])return!1;var S=this._events[p],N=arguments.length,B,E;if(S.fn){switch(S.once&&this.removeListener(c,S.fn,void 0,!0),N){case 1:return S.fn.call(S.context),!0;case 2:return S.fn.call(S.context,d),!0;case 3:return S.fn.call(S.context,d,w),!0;case 4:return S.fn.call(S.context,d,w,v),!0;case 5:return S.fn.call(S.context,d,w,v,y),!0;case 6:return S.fn.call(S.context,d,w,v,y,f),!0}for(E=1,B=new Array(N-1);E<N;E++)B[E-1]=arguments[E];S.fn.apply(S.context,B)}else{var T=S.length,h;for(E=0;E<T;E++)switch(S[E].once&&this.removeListener(c,S[E].fn,void 0,!0),N){case 1:S[E].fn.call(S[E].context);break;case 2:S[E].fn.call(S[E].context,d);break;case 3:S[E].fn.call(S[E].context,d,w);break;case 4:S[E].fn.call(S[E].context,d,w,v);break;default:if(!B)for(h=1,B=new Array(N-1);h<N;h++)B[h-1]=arguments[h];S[E].fn.apply(S[E].context,B)}}return!0},s.prototype.on=function(c,d,w){return l(this,c,d,w,!1)},s.prototype.once=function(c,d,w){return l(this,c,d,w,!0)},s.prototype.removeListener=function(c,d,w,v){var y=n?n+c:c;if(!this._events[y])return this;if(!d)return u(this,y),this;var f=this._events[y];if(f.fn)f.fn===d&&(!v||f.once)&&(!w||f.context===w)&&u(this,y);else{for(var p=0,S=[],N=f.length;p<N;p++)(f[p].fn!==d||v&&!f[p].once||w&&f[p].context!==w)&&S.push(f[p]);S.length?this._events[y]=S.length===1?S[0]:S:u(this,y)}return this},s.prototype.removeAllListeners=function(c){var d;return c?(d=n?n+c:c,this._events[d]&&u(this,d)):(this._events=new r,this._eventsCount=0),this},s.prototype.off=s.prototype.removeListener,s.prototype.addListener=s.prototype.on,s.prefixed=n,s.EventEmitter=s,e.exports=s})(eventemitter3);var eventemitter3Exports=eventemitter3.exports;const EventEmitter=getDefaultExportFromCjs(eventemitter3Exports);class Manipulator{constructor(t,n){be(this,"currentListeners",[]);be(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){be(this,"channel");be(this,"requestIdToResponseMap",new Map);this.device=t,this.channel_name=n,this.timeout=r}addOpenListener(t){defined(this.channel,"channel not initalized").addOpenListener(t)}removeOpenListener(t){defined(this.channel,"channel not initalized").removeOpenListener(t)}addCloseListener(t){defined(this.channel,"channel not initalized").addCloseListener(t)}removeCloseListener(t){defined(this.channel,"channel not initalized").removeCloseListener(t)}addErrorListener(t){defined(this.channel,"channel not initalized").addErrorListener(t)}removeErrorListener(t){defined(this.channel,"channel not initalized").removeErrorListener(t)}}class BinaryRequestDataChannel extends RequestDataChannel{constructor(){super(...arguments);be(this,"RESPONSE_SUCCESS_BYTE",0);be(this,"decoder",new TextDecoder)}generateBinaryId(){const n=new Uint8Array(16);for(let r=0;r<n.length;r++)n[r]=Math.floor(Math.random()*256);return n}async initialize(){this.channel=await this.device.createCustomDataChannel(this.channel_name),this.channel.addBinaryListener(n=>{const o=n.slice(0,16).toString();if(o.length===0)throw new Error("Invalid response");const l=n.slice(16);if(l.length===0)throw new Error("Invalid response");this.requestIdToResponseMap.has(o)&&this.requestIdToResponseMap.set(o,l)})}async request(n){if(this.channel||await this.initialize(),!this.channel)throw new Error("Failed to create channel");const{channel:r,requestIdToResponseMap:o,timeout:l}=this;await r.waitTilReady();const u=this.generateBinaryId(),s=u.toString();o.set(s,!0),r.sendBinary(new Uint8Array([...u,...n]));const g=new Date().getTime();for(;new Date().getTime()<g+l;)if(await delay(50),o.has(s)){const c=o.get(s);if(c!==!0){o.delete(s);const d=c[0]===this.RESPONSE_SUCCESS_BYTE,w=c.slice(1);if(d)return w;throw console.error({name:"AdapterError",message:this.decoder.decode(w)}),new Error("Binary request datachannel adapter error")}}throw o.delete(s),console.error({name:"TimeoutError",message:`Request timed out after ${l/1e3} seconds`}),new Error("Binary request data channel request timed out")}}class TextRequestDataChannel extends RequestDataChannel{generateTextId(){return Math.random().toString(36).substring(2)+"-"+Math.random().toString(36).substring(2)}async initialize(){this.channel=await this.device.createCustomDataChannel(this.channel_name),this.channel.addListener(t=>{const n=JSON.parse(t),{id:r,data:o,error:l}=n;if(!r)throw new Error("Invalid response");if(!o&&!l)throw new Error("Invalid response");this.requestIdToResponseMap.has(r)&&this.requestIdToResponseMap.set(r,n)})}async request(t){if(this.channel||await this.initialize(),!this.channel)throw new Error("Failed to create channel");const{channel:n,requestIdToResponseMap:r,timeout:o}=this;await n.waitTilReady();const l=this.generateTextId();r.set(l,!0),n.send(JSON.stringify({id:l,data:t}));const u=new Date().getTime();for(;new Date().getTime()<u+o;)if(await delay(50),r.has(l)){const s=r.get(l);if(s!==!0){r.delete(l);const{data:g,error:c}=s;if(g)return g;if(c)throw console.error({name:"AdapterError",message:c}),new Error("Text request datachannel adapter error")}}throw r.delete(l),console.error({name:"TimeoutError",message:`Request timed out after ${o/1e3} seconds`}),new Error("Text request datachannel request timed out")}}class BaseDevice extends EventEmitter{constructor(){super(...arguments);be(this,"rtcClient");be(this,"remoteDevicePeerId",null);be(this,"realtimeListeners",[]);be(this,"connectionMonitorInterval");be(this,"handleMessage",(n,r)=>{this.realtimeListeners.forEach(o=>o(n,r))})}stopConnectionMonitoring(){clearInterval(this.connectionMonitorInterval),this.connectionMonitorInterval=void 0}assertNotCancelled(n){if(n)throw new Error("Cancelled by deadline")}getRealtimeStatus(){if(this.rtcClient&&this.remoteDevicePeerId)return this.rtcClient.getConnectionStatus(this.remoteDevicePeerId);throw new Error("Realtime connection hasn't been started")}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(){const n=await this.getConfiguration(),r=[];for(const o of n.teleop.rosStreams??[])o.topicType=="sensor_msgs/JointState"&&r.push(new Manipulator(this,{currentJointStateStream:{name:o.topicName},plannedJointStateStream:o.plannedTopic?{name:o.plannedTopic}:void 0,planValidStream:o.planValidTopic?{name:o.planValidTopic}:void 0,endEffectorStream:o.endEffectorTopic?{name:o.endEffectorTopic}:void 0,endEffectorLinkName:o.endEffectorLinkName,baseReferenceFrame:o.baseReferenceFrame,localFrame:o.localFrame}));return r}async getRealtimeVideoStreams(){var o,l,u;const n=await this.getConfiguration(),r=[];for(const s of((o=n.teleop)==null?void 0:o.hardwareStreams)??[])s.rtcStreamType==="h264-video-frame"&&r.push({name:s.name});for(const s of((l=n.teleop)==null?void 0:l.rosStreams)??[])s.topicType=="formant/H264VideoFrame"&&r.push({name:s.topicName}),(s.topicType==="sensor_msgs/Image"||s.topicType==="sensor_msgs/CompressedImage")&&s.encodeVideo&&r.push({name:s.topicName});for(const s of((u=n.teleop)==null?void 0:u.customStreams)??[])s.rtcStreamType==="h264-video-frame"&&r.push({name:s.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(this.rtcClient,"Realtime connection has not been started"),o=await this.getRemotePeer();r.controlRemoteStream(defined(o).id,{streamName:n.name,enable:!0,pipeline:"rtc"})}async stopListeningToRealtimeVideo(n){const r=defined(this.rtcClient,"Realtime connection has not been started"),o=await this.getRemotePeer();r.controlRemoteStream(defined(o).id,{streamName:n.name,enable:!1,pipeline:"rtc"})}async startListeningToRealtimeDataStream(n){const r=defined(this.rtcClient,"Realtime connection has not been started"),o=await this.getRemotePeer();r.controlRemoteStream(defined(o).id,{streamName:n.name,enable:!0,pipeline:"rtc"})}async stopListeningToRealtimeDataStream(n){const r=defined(this.rtcClient,"Realtime connection has not been started"),o=await this.getRemotePeer();r.controlRemoteStream(defined(o).id,{streamName:n.name,enable:!1,pipeline:"rtc"})}async enableRealtimeTelemetryPriorityIngestion(n){const r=defined(this.rtcClient,"Realtime connection has not been started"),o=await this.getRemotePeer();r.controlRemoteStream(defined(o).id,{streamName:n,enablePriorityUpload:!0,pipeline:"telemetry"})}async disableRealtimeTelemetryPriorityIngestion(n){const r=defined(this.rtcClient,"Realtime connection has not been started"),o=await this.getRemotePeer();r.controlRemoteStream(defined(o).id,{streamName:n,enablePriorityUpload:!1,pipeline:"telemetry"})}async changeStreamAudioType(n,r){const o=defined(this.rtcClient,"Realtime connection has not been started"),l=await this.getRemotePeer();o.controlRemoteStream(defined(l).id,{streamName:n,setAudioFormat:r})}async createCustomDataChannel(n,r){const o=defined(this.rtcClient,"Realtime connection has not been started"),l=await this.getRemotePeer(),u=await new Promise(s=>{o.createCustomDataChannel(defined(l).id,n,{ordered:!0,...r},!1,(g,c)=>{const d=new DataChannel(c);s(d)})});return await u.waitTilReady(),u}async sendRealtimeMessage(n,r={channelLabel:"stream.reliable"}){const o=defined(this.rtcClient,"Realtime connection has not been started"),l=await this.getRemotePeer();o.send(defined(l).id,n,r)}async getRealtimeAudioStreams(){var o,l,u;const n=await this.getConfiguration(),r=[];for(const s of((o=n.teleop)==null?void 0:o.hardwareStreams)??[])s.rtcStreamType==="audio-chunk"&&r.push({name:s.name});for(const s of((l=n.teleop)==null?void 0:l.rosStreams)??[])s.topicType=="audio_common_msgs/AudioData"&&r.push({name:s.topicName});for(const s of((u=n.teleop)==null?void 0:u.customStreams)??[])s.rtcStreamType==="audio-chunk"&&r.push({name:s.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,o){this.static_tree=e,this.extra_bits=t,this.extra_base=n,this.elems=r,this.max_length=o,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,o=t.stat_desc.static_tree,l=t.stat_desc.has_stree,u=t.stat_desc.extra_bits,s=t.stat_desc.extra_base,g=t.stat_desc.max_length;let c,d,w,v,y,f,p=0;for(v=0;v<=MAX_BITS$1;v++)e.bl_count[v]=0;for(n[e.heap[e.heap_max]*2+1]=0,c=e.heap_max+1;c<HEAP_SIZE$1;c++)d=e.heap[c],v=n[n[d*2+1]*2+1]+1,v>g&&(v=g,p++),n[d*2+1]=v,!(d>r)&&(e.bl_count[v]++,y=0,d>=s&&(y=u[d-s]),f=n[d*2],e.opt_len+=f*(v+y),l&&(e.static_len+=f*(o[d*2+1]+y)));if(p!==0){do{for(v=g-1;e.bl_count[v]===0;)v--;e.bl_count[v]--,e.bl_count[v+1]+=2,e.bl_count[g]--,p-=2}while(p>0);for(v=g;v!==0;v--)for(d=e.bl_count[v];d!==0;)w=e.heap[--c],!(w>r)&&(n[w*2+1]!==v&&(e.opt_len+=(v-n[w*2+1])*n[w*2],n[w*2+1]=v),d--)}},gen_codes=(e,t,n)=>{const r=new Array(MAX_BITS$1+1);let o=0,l,u;for(l=1;l<=MAX_BITS$1;l++)o=o+n[l-1]<<1,r[l]=o;for(u=0;u<=t;u++){let s=e[u*2+1];s!==0&&(e[u*2]=bi_reverse(r[s]++,s))}},tr_static_init=()=>{let e,t,n,r,o;const l=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,o=0,r=0;r<16;r++)for(base_dist[r]=o,e=0;e<1<<extra_dbits[r];e++)_dist_code[o++]=r;for(o>>=7;r<D_CODES$1;r++)for(base_dist[r]=o<<7,e=0;e<1<<extra_dbits[r]-7;e++)_dist_code[256+o++]=r;for(t=0;t<=MAX_BITS$1;t++)l[t]=0;for(e=0;e<=143;)static_ltree[e*2+1]=8,e++,l[8]++;for(;e<=255;)static_ltree[e*2+1]=9,e++,l[9]++;for(;e<=279;)static_ltree[e*2+1]=7,e++,l[7]++;for(;e<=287;)static_ltree[e*2+1]=8,e++,l[8]++;for(gen_codes(static_ltree,L_CODES$1+1,l),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 o=t*2,l=n*2;return e[o]<e[l]||e[o]===e[l]&&r[t]<=r[n]},pqdownheap=(e,t,n)=>{const r=e.heap[n];let o=n<<1;for(;o<=e.heap_len&&(o<e.heap_len&&smaller(t,e.heap[o+1],e.heap[o],e.depth)&&o++,!smaller(t,r,e.heap[o],e.depth));)e.heap[n]=e.heap[o],n=o,o<<=1;e.heap[n]=r},compress_block=(e,t,n)=>{let r,o,l=0,u,s;if(e.sym_next!==0)do r=e.pending_buf[e.sym_buf+l++]&255,r+=(e.pending_buf[e.sym_buf+l++]&255)<<8,o=e.pending_buf[e.sym_buf+l++],r===0?send_code(e,o,t):(u=_length_code[o],send_code(e,u+LITERALS$1+1,t),s=extra_lbits[u],s!==0&&(o-=base_length[u],send_bits(e,o,s)),r--,u=d_code(r),send_code(e,u,n),s=extra_dbits[u],s!==0&&(r-=base_dist[u],send_bits(e,r,s)));while(l<e.sym_next);send_code(e,END_BLOCK,t)},build_tree=(e,t)=>{const n=t.dyn_tree,r=t.stat_desc.static_tree,o=t.stat_desc.has_stree,l=t.stat_desc.elems;let u,s,g=-1,c;for(e.heap_len=0,e.heap_max=HEAP_SIZE$1,u=0;u<l;u++)n[u*2]!==0?(e.heap[++e.heap_len]=g=u,e.depth[u]=0):n[u*2+1]=0;for(;e.heap_len<2;)c=e.heap[++e.heap_len]=g<2?++g:0,n[c*2]=1,e.depth[c]=0,e.opt_len--,o&&(e.static_len-=r[c*2+1]);for(t.max_code=g,u=e.heap_len>>1;u>=1;u--)pqdownheap(e,n,u);c=l;do u=e.heap[1],e.heap[1]=e.heap[e.heap_len--],pqdownheap(e,n,1),s=e.heap[1],e.heap[--e.heap_max]=u,e.heap[--e.heap_max]=s,n[c*2]=n[u*2]+n[s*2],e.depth[c]=(e.depth[u]>=e.depth[s]?e.depth[u]:e.depth[s])+1,n[u*2+1]=n[s*2+1]=c,e.heap[1]=c++,pqdownheap(e,n,1);while(e.heap_len>=2);e.heap[--e.heap_max]=e.heap[1],gen_bitlen(e,t),gen_codes(n,g,e.bl_count)},scan_tree=(e,t,n)=>{let r,o=-1,l,u=t[0*2+1],s=0,g=7,c=4;for(u===0&&(g=138,c=3),t[(n+1)*2+1]=65535,r=0;r<=n;r++)l=u,u=t[(r+1)*2+1],!(++s<g&&l===u)&&(s<c?e.bl_tree[l*2]+=s:l!==0?(l!==o&&e.bl_tree[l*2]++,e.bl_tree[REP_3_6*2]++):s<=10?e.bl_tree[REPZ_3_10*2]++:e.bl_tree[REPZ_11_138*2]++,s=0,o=l,u===0?(g=138,c=3):l===u?(g=6,c=3):(g=7,c=4))},send_tree=(e,t,n)=>{let r,o=-1,l,u=t[0*2+1],s=0,g=7,c=4;for(u===0&&(g=138,c=3),r=0;r<=n;r++)if(l=u,u=t[(r+1)*2+1],!(++s<g&&l===u)){if(s<c)do send_code(e,l,e.bl_tree);while(--s!==0);else l!==0?(l!==o&&(send_code(e,l,e.bl_tree),s--),send_code(e,REP_3_6,e.bl_tree),send_bits(e,s-3,2)):s<=10?(send_code(e,REPZ_3_10,e.bl_tree),send_bits(e,s-3,3)):(send_code(e,REPZ_11_138,e.bl_tree),send_bits(e,s-11,7));s=0,o=l,u===0?(g=138,c=3):l===u?(g=6,c=3):(g=7,c=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 o;for(send_bits(e,t-257,5),send_bits(e,n-1,5),send_bits(e,r-4,4),o=0;o<r;o++)send_bits(e,e.bl_tree[bl_order[o]*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 o,l,u=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),u=build_bl_tree(e),o=e.opt_len+3+7>>>3,l=e.static_len+3+7>>>3,l<=o&&(o=l)):o=l=n+5,n+4<=o&&t!==-1?_tr_stored_block$1(e,t,n,r):e.strategy===Z_FIXED$1||l===o?(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,u+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 o=e&65535|0,l=e>>>16&65535|0,u=0;for(;n!==0;){u=n>2e3?2e3:n,n-=u;do o=o+t[r++]|0,l=l+o|0;while(--u);o%=65521,l%=65521}return o|l<<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 o=crcTable,l=r+n;e^=-1;for(let u=r;u<l;u++)e=e>>>8^o[(e^t[u])&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,o=e.w_size;t=e.hash_size,r=t;do n=e.head[--r],e.head[r]=n>=o?n-o:0;while(--t);t=o,r=t;do n=e.prev[--r],e.prev[r]=n>=o?n-o: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 o=e.avail_in;return o>r&&(o=r),o===0?0:(e.avail_in-=o,t.set(e.input.subarray(e.next_in,e.next_in+o),n),e.state.wrap===1?e.adler=adler32_1(e.adler,t,o,n):e.state.wrap===2&&(e.adler=crc32_1(e.adler,t,o,n)),e.next_in+=o,e.total_in+=o,o)},longest_match=(e,t)=>{let n=e.max_chain_length,r=e.strstart,o,l,u=e.prev_length,s=e.nice_match;const g=e.strstart>e.w_size-MIN_LOOKAHEAD?e.strstart-(e.w_size-MIN_LOOKAHEAD):0,c=e.window,d=e.w_mask,w=e.prev,v=e.strstart+MAX_MATCH;let y=c[r+u-1],f=c[r+u];e.prev_length>=e.good_match&&(n>>=2),s>e.lookahead&&(s=e.lookahead);do if(o=t,!(c[o+u]!==f||c[o+u-1]!==y||c[o]!==c[r]||c[++o]!==c[r+1])){r+=2,o++;do;while(c[++r]===c[++o]&&c[++r]===c[++o]&&c[++r]===c[++o]&&c[++r]===c[++o]&&c[++r]===c[++o]&&c[++r]===c[++o]&&c[++r]===c[++o]&&c[++r]===c[++o]&&r<v);if(l=MAX_MATCH-(v-r),r=v-MAX_MATCH,l>u){if(e.match_start=t,u=l,l>=s)break;y=c[r+u-1],f=c[r+u]}}while((t=w[t&d])>g&&--n!==0);return u<=e.lookahead?u:e.lookahead},fill_window=e=>{const t=e.w_size;let n,r,o;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(o=e.strstart-e.insert,e.ins_h=e.window[o],e.ins_h=HASH(e,e.ins_h,e.window[o+1]);e.insert&&(e.ins_h=HASH(e,e.ins_h,e.window[o+MIN_MATCH-1]),e.prev[o&e.w_mask]=e.head[e.ins_h],e.head[e.ins_h]=o,o++,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,o,l,u=0,s=e.strm.avail_in;do{if(r=65535,l=e.bi_valid+42>>3,e.strm.avail_out<l||(l=e.strm.avail_out-l,o=e.strstart-e.block_start,r>o+e.strm.avail_in&&(r=o+e.strm.avail_in),r>l&&(r=l),r<n&&(r===0&&t!==Z_FINISH$3||t===Z_NO_FLUSH$2||r!==o+e.strm.avail_in)))break;u=t===Z_FINISH$3&&r===o+e.strm.avail_in?1:0,_tr_stored_block(e,0,0,u),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),o&&(o>r&&(o=r),e.strm.output.set(e.window.subarray(e.block_start,e.block_start+o),e.strm.next_out),e.strm.next_out+=o,e.strm.avail_out-=o,e.strm.total_out+=o,e.block_start+=o,r-=o),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(u===0);return s-=e.strm.avail_in,s&&(s>=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<=s&&(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-s,e.strm.next_in),e.strstart),e.strstart+=s,e.insert+=s>e.w_size-e.insert?e.w_size-e.insert:s),e.block_start=e.strstart),e.high_water<e.strstart&&(e.high_water=e.strstart),u?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:(l=e.window_size-e.strstart,e.strm.avail_in>l&&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++,l+=e.w_size,e.insert>e.strstart&&(e.insert=e.strstart)),l>e.strm.avail_in&&(l=e.strm.avail_in),l&&(read_buf(e.strm,e.window,e.strstart,l),e.strstart+=l,e.insert+=l>e.w_size-e.insert?e.w_size-e.insert:l),e.high_water<e.strstart&&(e.high_water=e.strstart),l=e.bi_valid+42>>3,l=e.pending_buf_size-l>65535?65535:e.pending_buf_size-l,n=l>e.w_size?e.w_size:l,o=e.strstart-e.block_start,(o>=n||(o||t===Z_FINISH$3)&&t!==Z_NO_FLUSH$2&&e.strm.avail_in===0&&o<=l)&&(r=o>l?l:o,u=t===Z_FINISH$3&&e.strm.avail_in===0&&r===o?1:0,_tr_stored_block(e,e.block_start,r,u),e.block_start+=r,flush_pending(e.strm)),u?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,o;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){o=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<=o&&(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,o,l;const u=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&&(o=e.strstart-1,r=u[o],r===u[++o]&&r===u[++o]&&r===u[++o])){l=e.strstart+MAX_MATCH;do;while(r===u[++o]&&r===u[++o]&&r===u[++o]&&r===u[++o]&&r===u[++o]&&r===u[++o]&&r===u[++o]&&r===u[++o]&&o<l);e.match_length=MAX_MATCH-(l-o),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,o){this.good_length=e,this.max_lazy=t,this.nice_length=n,this.max_chain=r,this.func=o}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,o,l)=>{if(!e)return Z_STREAM_ERROR$2;let u=1;if(t===Z_DEFAULT_COMPRESSION$1&&(t=6),r<0?(u=0,r=-r):r>15&&(u=2,r-=16),o<1||o>MAX_MEM_LEVEL||n!==Z_DEFLATED$2||r<8||r>15||t<0||t>9||l<0||l>Z_FIXED||r===8&&u!==1)return err(e,Z_STREAM_ERROR$2);r===8&&(r=9);const s=new DeflateState;return e.state=s,s.strm=e,s.status=INIT_STATE,s.wrap=u,s.gzhead=null,s.w_bits=r,s.w_size=1<<s.w_bits,s.w_mask=s.w_size-1,s.hash_bits=o+7,s.hash_size=1<<s.hash_bits,s.hash_mask=s.hash_size-1,s.hash_shift=~~((s.hash_bits+MIN_MATCH-1)/MIN_MATCH),s.window=new Uint8Array(s.w_size*2),s.head=new Uint16Array(s.hash_size),s.prev=new Uint16Array(s.w_size),s.lit_bufsize=1<<o+6,s.pending_buf_size=s.lit_bufsize*4,s.pending_buf=new Uint8Array(s.pending_buf_size),s.sym_buf=s.lit_bufsize,s.sym_end=(s.lit_bufsize-1)*3,s.level=t,s.strategy=l,s.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 o=Z_DEFLATED$2+(n.w_bits-8<<4)<<8,l=-1;if(n.strategy>=Z_HUFFMAN_ONLY||n.level<2?l=0:n.level<6?l=1:n.level===6?l=2:l=3,o|=l<<6,n.strstart!==0&&(o|=PRESET_DICT),o+=31-o%31,putShortMSB(n,o),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 o=n.pending,l=(n.gzhead.extra.length&65535)-n.gzindex;for(;n.pending+l>n.pending_buf_size;){let s=n.pending_buf_size-n.pending;if(n.pending_buf.set(n.gzhead.extra.subarray(n.gzindex,n.gzindex+s),n.pending),n.pending=n.pending_buf_size,n.gzhead.hcrc&&n.pending>o&&(e.adler=crc32_1(e.adler,n.pending_buf,n.pending-o,o)),n.gzindex+=s,flush_pending(e),n.pending!==0)return n.last_flush=-1,Z_OK$3;o=0,l-=s}let u=new Uint8Array(n.gzhead.extra);n.pending_buf.set(u.subarray(n.gzindex,n.gzindex+l),n.pending),n.pending+=l,n.gzhead.hcrc&&n.pending>o&&(e.adler=crc32_1(e.adler,n.pending_buf,n.pending-o,o)),n.gzindex=0}n.status=NAME_STATE}if(n.status===NAME_STATE){if(n.gzhead.name){let o=n.pending,l;do{if(n.pending===n.pending_buf_size){if(n.gzhead.hcrc&&n.pending>o&&(e.adler=crc32_1(e.adler,n.pending_buf,n.pending-o,o)),flush_pending(e),n.pending!==0)return n.last_flush=-1,Z_OK$3;o=0}n.gzindex<n.gzhead.name.length?l=n.gzhead.name.charCodeAt(n.gzindex++)&255:l=0,put_byte(n,l)}while(l!==0);n.gzhead.hcrc&&n.pending>o&&(e.adler=crc32_1(e.adler,n.pending_buf,n.pending-o,o)),n.gzindex=0}n.status=COMMENT_STATE}if(n.status===COMMENT_STATE){if(n.gzhead.comment){let o=n.pending,l;do{if(n.pending===n.pending_buf_size){if(n.gzhead.hcrc&&n.pending>o&&(e.adler=crc32_1(e.adler,n.pending_buf,n.pending-o,o)),flush_pending(e),n.pending!==0)return n.last_flush=-1,Z_OK$3;o=0}n.gzindex<n.gzhead.comment.length?l=n.gzhead.comment.charCodeAt(n.gzindex++)&255:l=0,put_byte(n,l)}while(l!==0);n.gzhead.hcrc&&n.pending>o&&(e.adler=crc32_1(e.adler,n.pending_buf,n.pending-o,o))}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 o=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((o===BS_FINISH_STARTED||o===BS_FINISH_DONE)&&(n.status=FINISH_STATE),o===BS_NEED_MORE||o===BS_FINISH_STARTED)return e.avail_out===0&&(n.last_flush=-1),Z_OK$3;if(o===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,o=r.wrap;if(o===2||o===1&&r.status!==INIT_STATE||r.lookahead)return Z_STREAM_ERROR$2;if(o===1&&(e.adler=adler32_1(e.adler,t,n,0)),r.wrap=0,n>=r.w_size){o===0&&(zero(r.head),r.strstart=0,r.block_start=0,r.insert=0);let g=new Uint8Array(r.w_size);g.set(t.subarray(n-r.w_size,n),0),t=g,n=r.w_size}const l=e.avail_in,u=e.next_in,s=e.input;for(e.avail_in=n,e.next_in=0,e.input=t,fill_window(r);r.lookahead>=MIN_MATCH;){let g=r.strstart,c=r.lookahead-(MIN_MATCH-1);do r.ins_h=HASH(r,r.ins_h,r.window[g+MIN_MATCH-1]),r.prev[g&r.w_mask]=r.head[r.ins_h],r.head[r.ins_h]=g,g++;while(--c);r.strstart=g,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=u,e.input=s,e.avail_in=l,r.wrap=o,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,o=e.length;r<o;r++)t+=e[r].length;const n=new Uint8Array(t);for(let r=0,o=0,l=e.length;r<l;r++){let u=e[r];n.set(u,o),o+=u.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,o,l,u=e.length,s=0;for(o=0;o<u;o++)n=e.charCodeAt(o),(n&64512)===55296&&o+1<u&&(r=e.charCodeAt(o+1),(r&64512)===56320&&(n=65536+(n-55296<<10)+(r-56320),o++)),s+=n<128?1:n<2048?2:n<65536?3:4;for(t=new Uint8Array(s),l=0,o=0;l<s;o++)n=e.charCodeAt(o),(n&64512)===55296&&o+1<u&&(r=e.charCodeAt(o+1),(r&64512)===56320&&(n=65536+(n-55296<<10)+(r-56320),o++)),n<128?t[l++]=n:n<2048?(t[l++]=192|n>>>6,t[l++]=128|n&63):n<65536?(t[l++]=224|n>>>12,t[l++]=128|n>>>6&63,t[l++]=128|n&63):(t[l++]=240|n>>>18,t[l++]=128|n>>>12&63,t[l++]=128|n>>>6&63,t[l++]=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,o;const l=new Array(n*2);for(o=0,r=0;r<n;){let u=e[r++];if(u<128){l[o++]=u;continue}let s=_utf8len[u];if(s>4){l[o++]=65533,r+=s-1;continue}for(u&=s===2?31:s===3?15:7;s>1&&r<n;)u=u<<6|e[r++]&63,s--;if(s>1){l[o++]=65533;continue}u<65536?l[o++]=u:(u-=65536,l[o++]=55296|u>>10&1023,l[o++]=56320|u&1023)}return buf2binstring(l,o)},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 o,l;if(this.ended)return!1;for(t===~~t?l=t:l=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),(l===Z_SYNC_FLUSH||l===Z_FULL_FLUSH)&&n.avail_out<=6){this.onData(n.output.subarray(0,n.next_out)),n.avail_out=0;continue}if(o=deflate_1$2.deflate(n,l),o===Z_STREAM_END$2)return n.next_out>0&&this.onData(n.output.subarray(0,n.next_out)),o=deflate_1$2.deflateEnd(this.strm),this.onEnd(o),this.ended=!0,o===Z_OK$2;if(n.avail_out===0){this.onData(n.output);continue}if(l>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,o,l,u,s,g,c,d,w,v,y,f,p,S,N,B,E,T,h,R,W,X,m,b;const G=t.state;r=t.next_in,m=t.input,o=r+(t.avail_in-5),l=t.next_out,b=t.output,u=l-(n-t.avail_out),s=l+(t.avail_out-257),g=G.dmax,c=G.wsize,d=G.whave,w=G.wnext,v=G.window,y=G.hold,f=G.bits,p=G.lencode,S=G.distcode,N=(1<<G.lenbits)-1,B=(1<<G.distbits)-1;e:do{f<15&&(y+=m[r++]<<f,f+=8,y+=m[r++]<<f,f+=8),E=p[y&N];t:for(;;){if(T=E>>>24,y>>>=T,f-=T,T=E>>>16&255,T===0)b[l++]=E&65535;else if(T&16){h=E&65535,T&=15,T&&(f<T&&(y+=m[r++]<<f,f+=8),h+=y&(1<<T)-1,y>>>=T,f-=T),f<15&&(y+=m[r++]<<f,f+=8,y+=m[r++]<<f,f+=8),E=S[y&B];n:for(;;){if(T=E>>>24,y>>>=T,f-=T,T=E>>>16&255,T&16){if(R=E&65535,T&=15,f<T&&(y+=m[r++]<<f,f+=8,f<T&&(y+=m[r++]<<f,f+=8)),R+=y&(1<<T)-1,R>g){t.msg="invalid distance too far back",G.mode=BAD$1;break e}if(y>>>=T,f-=T,T=l-u,R>T){if(T=R-T,T>d&&G.sane){t.msg="invalid distance too far back",G.mode=BAD$1;break e}if(W=0,X=v,w===0){if(W+=c-T,T<h){h-=T;do b[l++]=v[W++];while(--T);W=l-R,X=b}}else if(w<T){if(W+=c+w-T,T-=w,T<h){h-=T;do b[l++]=v[W++];while(--T);if(W=0,w<h){T=w,h-=T;do b[l++]=v[W++];while(--T);W=l-R,X=b}}}else if(W+=w-T,T<h){h-=T;do b[l++]=v[W++];while(--T);W=l-R,X=b}for(;h>2;)b[l++]=X[W++],b[l++]=X[W++],b[l++]=X[W++],h-=3;h&&(b[l++]=X[W++],h>1&&(b[l++]=X[W++]))}else{W=l-R;do b[l++]=b[W++],b[l++]=b[W++],b[l++]=b[W++],h-=3;while(h>2);h&&(b[l++]=b[W++],h>1&&(b[l++]=b[W++]))}}else if(T&64){t.msg="invalid distance code",G.mode=BAD$1;break e}else{E=S[(E&65535)+(y&(1<<T)-1)];continue n}break}}else if(T&64)if(T&32){G.mode=TYPE$1;break e}else{t.msg="invalid literal/length code",G.mode=BAD$1;break e}else{E=p[(E&65535)+(y&(1<<T)-1)];continue t}break}}while(r<o&&l<s);h=f>>3,r-=h,f-=h<<3,y&=(1<<f)-1,t.next_in=r,t.next_out=l,t.avail_in=r<o?5+(o-r):5-(r-o),t.avail_out=l<s?257+(s-l):257-(l-s),G.hold=y,G.bits=f};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,o,l,u,s)=>{const g=s.bits;let c=0,d=0,w=0,v=0,y=0,f=0,p=0,S=0,N=0,B=0,E,T,h,R,W,X=null,m;const b=new Uint16Array(MAXBITS+1),G=new Uint16Array(MAXBITS+1);let j=null,C,z,P;for(c=0;c<=MAXBITS;c++)b[c]=0;for(d=0;d<r;d++)b[t[n+d]]++;for(y=g,v=MAXBITS;v>=1&&b[v]===0;v--);if(y>v&&(y=v),v===0)return o[l++]=1<<24|64<<16|0,o[l++]=1<<24|64<<16|0,s.bits=1,0;for(w=1;w<v&&b[w]===0;w++);for(y<w&&(y=w),S=1,c=1;c<=MAXBITS;c++)if(S<<=1,S-=b[c],S<0)return-1;if(S>0&&(e===CODES$1||v!==1))return-1;for(G[1]=0,c=1;c<MAXBITS;c++)G[c+1]=G[c]+b[c];for(d=0;d<r;d++)t[n+d]!==0&&(u[G[t[n+d]]++]=d);if(e===CODES$1?(X=j=u,m=20):e===LENS$1?(X=lbase,j=lext,m=257):(X=dbase,j=dext,m=0),B=0,d=0,c=w,W=l,f=y,p=0,h=-1,N=1<<y,R=N-1,e===LENS$1&&N>ENOUGH_LENS$1||e===DISTS$1&&N>ENOUGH_DISTS$1)return 1;for(;;){C=c-p,u[d]+1<m?(z=0,P=u[d]):u[d]>=m?(z=j[u[d]-m],P=X[u[d]-m]):(z=32+64,P=0),E=1<<c-p,T=1<<f,w=T;do T-=E,o[W+(B>>p)+T]=C<<24|z<<16|P|0;while(T!==0);for(E=1<<c-1;B&E;)E>>=1;if(E!==0?(B&=E-1,B+=E):B=0,d++,--b[c]===0){if(c===v)break;c=t[n+u[d]]}if(c>y&&(B&R)!==h){for(p===0&&(p=y),W+=w,f=c-p,S=1<<f;f+p<v&&(S-=b[f+p],!(S<=0));)f++,S<<=1;if(N+=1<<f,e===LENS$1&&N>ENOUGH_LENS$1||e===DISTS$1&&N>ENOUGH_DISTS$1)return 1;h=B&R,o[h]=y<<24|f<<16|W-l|0}}return B!==0&&(o[W+B]=c-p<<24|64<<16|0),s.bits=y,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 o;const l=e.state;return l.window===null&&(l.wsize=1<<l.wbits,l.wnext=0,l.whave=0,l.window=new Uint8Array(l.wsize)),r>=l.wsize?(l.window.set(t.subarray(n-l.wsize,n),0),l.wnext=0,l.whave=l.wsize):(o=l.wsize-l.wnext,o>r&&(o=r),l.window.set(t.subarray(n-r,n-r+o),l.wnext),r-=o,r?(l.window.set(t.subarray(n-r,n),0),l.wnext=r,l.whave=l.wsize):(l.wnext+=o,l.wnext===l.wsize&&(l.wnext=0),l.whave<l.wsize&&(l.whave+=o))),0},inflate$2=(e,t)=>{let n,r,o,l,u,s,g,c,d,w,v,y,f,p,S=0,N,B,E,T,h,R,W,X;const m=new Uint8Array(4);let b,G;const j=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),u=e.next_out,o=e.output,g=e.avail_out,l=e.next_in,r=e.input,s=e.avail_in,c=n.hold,d=n.bits,w=s,v=g,X=Z_OK$1;e:for(;;)switch(n.mode){case HEAD:if(n.wrap===0){n.mode=TYPEDO;break}for(;d<16;){if(s===0)break e;s--,c+=r[l++]<<d,d+=8}if(n.wrap&2&&c===35615){n.wbits===0&&(n.wbits=15),n.check=0,m[0]=c&255,m[1]=c>>>8&255,n.check=crc32_1(n.check,m,2,0),c=0,d=0,n.mode=FLAGS;break}if(n.head&&(n.head.done=!1),!(n.wrap&1)||(((c&255)<<8)+(c>>8))%31){e.msg="incorrect header check",n.mode=BAD;break}if((c&15)!==Z_DEFLATED){e.msg="unknown compression method",n.mode=BAD;break}if(c>>>=4,d-=4,W=(c&15)+8,n.wbits===0&&(n.wbits=W),W>15||W>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=c&512?DICTID:TYPE,c=0,d=0;break;case FLAGS:for(;d<16;){if(s===0)break e;s--,c+=r[l++]<<d,d+=8}if(n.flags=c,(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=c>>8&1),n.flags&512&&n.wrap&4&&(m[0]=c&255,m[1]=c>>>8&255,n.check=crc32_1(n.check,m,2,0)),c=0,d=0,n.mode=TIME;case TIME:for(;d<32;){if(s===0)break e;s--,c+=r[l++]<<d,d+=8}n.head&&(n.head.time=c),n.flags&512&&n.wrap&4&&(m[0]=c&255,m[1]=c>>>8&255,m[2]=c>>>16&255,m[3]=c>>>24&255,n.check=crc32_1(n.check,m,4,0)),c=0,d=0,n.mode=OS;case OS:for(;d<16;){if(s===0)break e;s--,c+=r[l++]<<d,d+=8}n.head&&(n.head.xflags=c&255,n.head.os=c>>8),n.flags&512&&n.wrap&4&&(m[0]=c&255,m[1]=c>>>8&255,n.check=crc32_1(n.check,m,2,0)),c=0,d=0,n.mode=EXLEN;case EXLEN:if(n.flags&1024){for(;d<16;){if(s===0)break e;s--,c+=r[l++]<<d,d+=8}n.length=c,n.head&&(n.head.extra_len=c),n.flags&512&&n.wrap&4&&(m[0]=c&255,m[1]=c>>>8&255,n.check=crc32_1(n.check,m,2,0)),c=0,d=0}else n.head&&(n.head.extra=null);n.mode=EXTRA;case EXTRA:if(n.flags&1024&&(y=n.length,y>s&&(y=s),y&&(n.head&&(W=n.head.extra_len-n.length,n.head.extra||(n.head.extra=new Uint8Array(n.head.extra_len)),n.head.extra.set(r.subarray(l,l+y),W)),n.flags&512&&n.wrap&4&&(n.check=crc32_1(n.check,r,y,l)),s-=y,l+=y,n.length-=y),n.length))break e;n.length=0,n.mode=NAME;case NAME:if(n.flags&2048){if(s===0)break e;y=0;do W=r[l+y++],n.head&&W&&n.length<65536&&(n.head.name+=String.fromCharCode(W));while(W&&y<s);if(n.flags&512&&n.wrap&4&&(n.check=crc32_1(n.check,r,y,l)),s-=y,l+=y,W)break e}else n.head&&(n.head.name=null);n.length=0,n.mode=COMMENT;case COMMENT:if(n.flags&4096){if(s===0)break e;y=0;do W=r[l+y++],n.head&&W&&n.length<65536&&(n.head.comment+=String.fromCharCode(W));while(W&&y<s);if(n.flags&512&&n.wrap&4&&(n.check=crc32_1(n.check,r,y,l)),s-=y,l+=y,W)break e}else n.head&&(n.head.comment=null);n.mode=HCRC;case HCRC:if(n.flags&512){for(;d<16;){if(s===0)break e;s--,c+=r[l++]<<d,d+=8}if(n.wrap&4&&c!==(n.check&65535)){e.msg="header crc mismatch",n.mode=BAD;break}c=0,d=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(;d<32;){if(s===0)break e;s--,c+=r[l++]<<d,d+=8}e.adler=n.check=zswap32(c),c=0,d=0,n.mode=DICT;case DICT:if(n.havedict===0)return e.next_out=u,e.avail_out=g,e.next_in=l,e.avail_in=s,n.hold=c,n.bits=d,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){c>>>=d&7,d-=d&7,n.mode=CHECK;break}for(;d<3;){if(s===0)break e;s--,c+=r[l++]<<d,d+=8}switch(n.last=c&1,c>>>=1,d-=1,c&3){case 0:n.mode=STORED;break;case 1:if(fixedtables(n),n.mode=LEN_,t===Z_TREES){c>>>=2,d-=2;break e}break;case 2:n.mode=TABLE;break;case 3:e.msg="invalid block type",n.mode=BAD}c>>>=2,d-=2;break;case STORED:for(c>>>=d&7,d-=d&7;d<32;){if(s===0)break e;s--,c+=r[l++]<<d,d+=8}if((c&65535)!==(c>>>16^65535)){e.msg="invalid stored block lengths",n.mode=BAD;break}if(n.length=c&65535,c=0,d=0,n.mode=COPY_,t===Z_TREES)break e;case COPY_:n.mode=COPY;case COPY:if(y=n.length,y){if(y>s&&(y=s),y>g&&(y=g),y===0)break e;o.set(r.subarray(l,l+y),u),s-=y,l+=y,g-=y,u+=y,n.length-=y;break}n.mode=TYPE;break;case TABLE:for(;d<14;){if(s===0)break e;s--,c+=r[l++]<<d,d+=8}if(n.nlen=(c&31)+257,c>>>=5,d-=5,n.ndist=(c&31)+1,c>>>=5,d-=5,n.ncode=(c&15)+4,c>>>=4,d-=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(;d<3;){if(s===0)break e;s--,c+=r[l++]<<d,d+=8}n.lens[j[n.have++]]=c&7,c>>>=3,d-=3}for(;n.have<19;)n.lens[j[n.have++]]=0;if(n.lencode=n.lendyn,n.lenbits=7,b={bits:n.lenbits},X=inftrees(CODES,n.lens,0,19,n.lencode,0,n.work,b),n.lenbits=b.bits,X){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(;S=n.lencode[c&(1<<n.lenbits)-1],N=S>>>24,B=S>>>16&255,E=S&65535,!(N<=d);){if(s===0)break e;s--,c+=r[l++]<<d,d+=8}if(E<16)c>>>=N,d-=N,n.lens[n.have++]=E;else{if(E===16){for(G=N+2;d<G;){if(s===0)break e;s--,c+=r[l++]<<d,d+=8}if(c>>>=N,d-=N,n.have===0){e.msg="invalid bit length repeat",n.mode=BAD;break}W=n.lens[n.have-1],y=3+(c&3),c>>>=2,d-=2}else if(E===17){for(G=N+3;d<G;){if(s===0)break e;s--,c+=r[l++]<<d,d+=8}c>>>=N,d-=N,W=0,y=3+(c&7),c>>>=3,d-=3}else{for(G=N+7;d<G;){if(s===0)break e;s--,c+=r[l++]<<d,d+=8}c>>>=N,d-=N,W=0,y=11+(c&127),c>>>=7,d-=7}if(n.have+y>n.nlen+n.ndist){e.msg="invalid bit length repeat",n.mode=BAD;break}for(;y--;)n.lens[n.have++]=W}}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,b={bits:n.lenbits},X=inftrees(LENS,n.lens,0,n.nlen,n.lencode,0,n.work,b),n.lenbits=b.bits,X){e.msg="invalid literal/lengths set",n.mode=BAD;break}if(n.distbits=6,n.distcode=n.distdyn,b={bits:n.distbits},X=inftrees(DISTS,n.lens,n.nlen,n.ndist,n.distcode,0,n.work,b),n.distbits=b.bits,X){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(s>=6&&g>=258){e.next_out=u,e.avail_out=g,e.next_in=l,e.avail_in=s,n.hold=c,n.bits=d,inffast(e,v),u=e.next_out,o=e.output,g=e.avail_out,l=e.next_in,r=e.input,s=e.avail_in,c=n.hold,d=n.bits,n.mode===TYPE&&(n.back=-1);break}for(n.back=0;S=n.lencode[c&(1<<n.lenbits)-1],N=S>>>24,B=S>>>16&255,E=S&65535,!(N<=d);){if(s===0)break e;s--,c+=r[l++]<<d,d+=8}if(B&&!(B&240)){for(T=N,h=B,R=E;S=n.lencode[R+((c&(1<<T+h)-1)>>T)],N=S>>>24,B=S>>>16&255,E=S&65535,!(T+N<=d);){if(s===0)break e;s--,c+=r[l++]<<d,d+=8}c>>>=T,d-=T,n.back+=T}if(c>>>=N,d-=N,n.back+=N,n.length=E,B===0){n.mode=LIT;break}if(B&32){n.back=-1,n.mode=TYPE;break}if(B&64){e.msg="invalid literal/length code",n.mode=BAD;break}n.extra=B&15,n.mode=LENEXT;case LENEXT:if(n.extra){for(G=n.extra;d<G;){if(s===0)break e;s--,c+=r[l++]<<d,d+=8}n.length+=c&(1<<n.extra)-1,c>>>=n.extra,d-=n.extra,n.back+=n.extra}n.was=n.length,n.mode=DIST;case DIST:for(;S=n.distcode[c&(1<<n.distbits)-1],N=S>>>24,B=S>>>16&255,E=S&65535,!(N<=d);){if(s===0)break e;s--,c+=r[l++]<<d,d+=8}if(!(B&240)){for(T=N,h=B,R=E;S=n.distcode[R+((c&(1<<T+h)-1)>>T)],N=S>>>24,B=S>>>16&255,E=S&65535,!(T+N<=d);){if(s===0)break e;s--,c+=r[l++]<<d,d+=8}c>>>=T,d-=T,n.back+=T}if(c>>>=N,d-=N,n.back+=N,B&64){e.msg="invalid distance code",n.mode=BAD;break}n.offset=E,n.extra=B&15,n.mode=DISTEXT;case DISTEXT:if(n.extra){for(G=n.extra;d<G;){if(s===0)break e;s--,c+=r[l++]<<d,d+=8}n.offset+=c&(1<<n.extra)-1,c>>>=n.extra,d-=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(g===0)break e;if(y=v-g,n.offset>y){if(y=n.offset-y,y>n.whave&&n.sane){e.msg="invalid distance too far back",n.mode=BAD;break}y>n.wnext?(y-=n.wnext,f=n.wsize-y):f=n.wnext-y,y>n.length&&(y=n.length),p=n.window}else p=o,f=u-n.offset,y=n.length;y>g&&(y=g),g-=y,n.length-=y;do o[u++]=p[f++];while(--y);n.length===0&&(n.mode=LEN);break;case LIT:if(g===0)break e;o[u++]=n.length,g--,n.mode=LEN;break;case CHECK:if(n.wrap){for(;d<32;){if(s===0)break e;s--,c|=r[l++]<<d,d+=8}if(v-=g,e.total_out+=v,n.total+=v,n.wrap&4&&v&&(e.adler=n.check=n.flags?crc32_1(n.check,o,v,u-v):adler32_1(n.check,o,v,u-v)),v=g,n.wrap&4&&(n.flags?c:zswap32(c))!==n.check){e.msg="incorrect data check",n.mode=BAD;break}c=0,d=0}n.mode=LENGTH;case LENGTH:if(n.wrap&&n.flags){for(;d<32;){if(s===0)break e;s--,c+=r[l++]<<d,d+=8}if(n.wrap&4&&c!==(n.total&4294967295)){e.msg="incorrect length check",n.mode=BAD;break}c=0,d=0}n.mode=DONE;case DONE:X=Z_STREAM_END$1;break e;case BAD:X=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=u,e.avail_out=g,e.next_in=l,e.avail_in=s,n.hold=c,n.bits=d,(n.wsize||v!==e.avail_out&&n.mode<BAD&&(n.mode<CHECK||t!==Z_FINISH$1))&&updatewindow(e,e.output,e.next_out,v-e.avail_out),w-=e.avail_in,v-=e.avail_out,e.total_in+=w,e.total_out+=v,n.total+=v,n.wrap&4&&v&&(e.adler=n.check=n.flags?crc32_1(n.check,o,v,e.next_out-v):adler32_1(n.check,o,v,e.next_out-v)),e.data_type=n.bits+(n.last?64:0)+(n.mode===TYPE?128:0)+(n.mode===LEN_||n.mode===COPY_?256:0),(w===0&&v===0||t===Z_FINISH$1)&&X===Z_OK$1&&(X=Z_BUF_ERROR),X},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,o,l;return inflateStateCheck(e)||(r=e.state,r.wrap!==0&&r.mode!==DICT)?Z_STREAM_ERROR$1:r.mode===DICT&&(o=1,o=adler32_1(o,t,n,0),o!==r.check)?Z_DATA_ERROR$1:(l=updatewindow(e,t,n,n),l?(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,o=this.options.dictionary;let l,u,s;if(this.ended)return!1;for(t===~~t?u=t:u=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),l=inflate_1$2.inflate(n,u),l===Z_NEED_DICT&&o&&(l=inflate_1$2.inflateSetDictionary(n,o),l===Z_OK?l=inflate_1$2.inflate(n,u):l===Z_DATA_ERROR&&(l=Z_NEED_DICT));n.avail_in>0&&l===Z_STREAM_END&&n.state.wrap>0&&e[n.next_in]!==0;)inflate_1$2.inflateReset(n),l=inflate_1$2.inflate(n,u);switch(l){case Z_STREAM_ERROR:case Z_DATA_ERROR:case Z_NEED_DICT:case Z_MEM_ERROR:return this.onEnd(l),this.ended=!0,!1}if(s=n.avail_out,n.next_out&&(n.avail_out===0||l===Z_STREAM_END))if(this.options.to==="string"){let g=strings.utf8border(n.output,n.next_out),c=n.next_out-g,d=strings.buf2string(n.output,g);n.next_out=c,n.avail_out=r-c,c&&n.output.set(n.output.subarray(g,g+c),0),this.onData(d)}else this.onData(n.output.length===n.next_out?n.output:n.output.subarray(0,n.next_out));if(!(l===Z_OK&&s===0)){if(l===Z_STREAM_END)return l=inflate_1$2.inflateEnd(this.strm),this.onEnd(l),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;for(var deflate_1=deflate,fromByteArray_1=fromByteArray,lookup=[],code="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",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,o=[],l=t;l<n;l+=3)r=(e[l]<<16&16711680)+(e[l+1]<<8&65280)+(e[l+2]&255),o.push(tripletToBase64(r));return o.join("")}function fromByteArray(e){for(var t,n=e.length,r=n%3,o=[],l=16383,u=0,s=n-r;u<s;u+=l)o.push(encodeChunk(e,u,u+l>s?s:u+l));return r===1?(t=e[n-1],o.push(lookup[t>>2]+lookup[t<<4&63]+"==")):r===2&&(t=(e[n-2]<<8)+e[n-1],o.push(lookup[t>>10]+lookup[t>>4&63]+lookup[t<<2&63]+"=")),o.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(s=>s.name===t);if(r.length===0)return console.warn("View does not exist or it is misspell"),null;const o=await fetch(`${FORMANT_API_URL}/v1/admin/shares`,{method:"POST",body:JSON.stringify(e),headers:{"Content-Type":"application/json",Authorization:"Bearer "+Authentication.token}}),l=FORMANT_API_URL.replace("api","app"),{code:u}=await o.json();return`${l}/shares/${u}#${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,o){const l=aggregateByDateFunctions[t];return await Promise.all(Array(n).fill(0).map(async(u,s)=>{const g=new Date(r),c=l.sub(l.start(g),n-s-1),d=l.sub(l.end(g),n-s-1),w=formatTimeFrameText(c.toLocaleDateString(),d.toLocaleDateString()),v=await queryEvents({...o,eventTypes:e,start:new Date(c).toISOString(),end:new Date(d).toISOString()});return{date:w,events:v}}))}async function getAnnotationCount(e,t){return(await queryEvents({...e,eventTypes:["annotation"]})).filter(l=>!!l.tags&&Object.keys(l.tags).includes(t)).reduce((l,u)=>{const s=u.tags[t];return s in l?(l[s]+=1,l):(l[s]=1,l)},{})}async function getAnnotationCountByIntervals(e,t,n){const{end:r,start:o}=e,u=aggregateByDateFunctions[n].interval({start:new Date(o),end:new Date(r)}),s=u.map((c,d)=>{const w=new Date(c).toISOString(),v=d===u.length-1?new Date(Date.now()).toISOString():new Date(u[d+1]);return getAnnotationCount({...e,start:w,end:v},t)}),g=await Promise.all(s);return u.map((c,d)=>({date:new Date(c).toISOString(),annotations:g[d]}))}async function getTelemetry(e,t,n,r,o){let l=e;Array.isArray(e)||(l=[e]);let u=t;return Array.isArray(t)||(u=[t]),(await(await fetch(`${FORMANT_API_URL}/v1/queries/queries`,{method:"POST",body:JSON.stringify({deviceIds:l,end:r.toISOString(),names:u,start:n.toISOString(),tags:o}),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,o){super(),this.id=t,this.name=n,this.organizationId=r,this.tags=o}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 o=t?r.desiredConfigurationVersion:r.state.reportedConfiguration.version;return n=await fetch(`${FORMANT_API_URL}/v1/admin/devices/${this.id}/configurations/${o}`,{method:"GET",headers:{"Content-Type":"application/json",Authorization:"Bearer "+Authentication.token}}),(await n.json()).document}async getAgentVersion(){var r;const n=await(await fetch(`${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:o=3}=typeof t=="number"?{sessionType:t}:t,u=getRtcClientPool({sessionType:n}).get(this.handleMessage);let s=!1;const g=new Promise((d,w)=>setTimeout(()=>{s=!0,w(new Error("Connection timed out: the connection could not be finalized in time, possibly due to network issues or misconfigured settings."))},r)),c=async()=>{if("isReady"in u)for(;!u.isReady();)this.assertNotCancelled(s),await delay(100);const d=await this.getRemoteDevicePeerId(u);this.assertNotCancelled(s);let w;for(let y=0;y<o&&(w=await u.connect(d),!w);y++)delay(100),this.assertNotCancelled(s);if(!w)throw new Error(`Session could not be created: exhausted ${o} retries`);let v=0;for(;!s&&u.getConnectionStatus(d)!=="connected";)await delay(100),v+=1;return this.assertNotCancelled(s),console.debug(`${new Date().toISOString()} :: Connection completed after ${v} retries`),d};return Promise.race([c(),g]).then(d=>{this.remoteDevicePeerId=d,this.initConnectionMonitoring(),this.rtcClient=u,this.emit("connect")}).catch(d=>{throw console.debug(`${new Date().toISOString()} :: Connection failed: %o`,d),this.remoteDevicePeerId=null,u.shutdown().catch(w=>{console.error("rtcClient cannot shutdown: %o",w)}),this.emit("connection_failed",d),d})}async getRemoteDevicePeerId(t){const r=(await t.getPeers()).find(o=>o.deviceId===this.id);if(!isRtcPeer(r))throw new Error("Cannot find peer, is the robot offline?");return r.id}initConnectionMonitoring(){this.connectionMonitorInterval=setInterval(async()=>{let t=!1;if(this.rtcClient){const r=this.rtcClient.getConnections().find(o=>o.getRemotePeerId()===this.remoteDevicePeerId&&o.isActive());(r===void 0||!r.isReady())&&(console.debug(`${new Date().toISOString()} :: data channel closed`),t=!0)}(!this.rtcClient||!this.remoteDevicePeerId||await this.rtcClient.getConnectionStatsInfo(this.remoteDevicePeerId)===void 0||t)&&(this.emit("disconnect"),this.stopRealtimeConnection().catch(n=>{console.error(n)}))},1e3)}async getRemotePeer(){const n=(await defined(this.rtcClient,"Realtime connection has not been started").getPeers()).find(r=>r.deviceId===this.id);return defined(n,"Could not find remote peer for device "+this.id)}async stopRealtimeConnection(){let t=!1;if(this.rtcClient){this.stopConnectionMonitoring(),this.remoteDevicePeerId?(await this.rtcClient.disconnect(this.remoteDevicePeerId),this.remoteDevicePeerId=null):t=!0;try{await this.rtcClient.shutdown()}finally{this.rtcClient=void 0}}if(t)throw new Error(`Realtime connection hasn't been started for ${this.id}`)}async isInRealtimeSession(){const t=await getPeers(),n=await getRealtimeSessions(),r=t.find(o=>o.deviceId===this.id);return r?n[r.id].length>0:!1}async getAvailableCommands(){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,o){var d;const u=(await this.getAvailableCommands()).find(w=>w.name===t);if(!u)throw new Error(`Could not find command with name "${t}"`);let s="";n===void 0?u.parameterEnabled&&u.parameterValue&&(s=u.parameterValue):s=n;let g={value:s,scrubberTime:(r||new Date).toISOString(),meta:{...u.parameterMeta,...o}};return await fetch(`${FORMANT_API_URL}/v1/admin/commands`,{method:"POST",body:JSON.stringify({commandTemplateId:u.id,organizationId:this.organizationId,deviceId:this.id,command:u.command,parameter:g,userId:(d=Authentication.currentUser)==null?void 0:d.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,o){return await getTelemetry(this.id,t,n,r,o)}async getTelemetryStreams(){var s,g;const t=await this.getConfiguration(),n=await fetch(`${FORMANT_API_URL}/v1/queries/metadata/stream-names`,{method:"POST",body:JSON.stringify({deviceIds:[this.id]}),headers:{"Content-Type":"application/json",Authorization:"Bearer "+Authentication.token}}),r=[],o=[];return(g=(s=t.telemetry)==null?void 0:s.streams)==null||g.forEach(c=>{c.disabled!==!0&&r.push(c.name),c.onDemand===!0&&o.push(c.name)}),console.log(o),(await n.json()).items.filter(c=>!r.includes(c)).map(c=>({name:c,onDemand:o.includes(c)}))}async createInterventionRequest(t,n,r,o){return await(await fetch(`${FORMANT_API_URL}/v1/admin/intervention-requests`,{method:"POST",body:JSON.stringify({message:t,interventionType:n,time:new Date().toISOString(),deviceId:this.id,tags:o,data:r}),headers:{"Content-Type":"application/json",Authorization:"Bearer "+Authentication.token}})).json()}async addInterventionResponse(t,n,r){return await(await fetch(`${FORMANT_API_URL}/v1/admin/intervention-responses`,{method:"POST",body:JSON.stringify({interventionId:t,interventionType:n,data:r}),headers:{"Content-Type":"application/json",Authorization:"Bearer "+Authentication.token}})).json()}async getAnnotationCount(t,n){return await getAnnotationCount({...t,deviceIds:[this.id]},n)}async getAnnotationCountByIntervals(t,n,r){return await getAnnotationCountByIntervals({...t,deviceIds:[this.id]},n,r)}async eventsCounter(t,n,r,o,l){return await eventsCounter(t,n,r,o,{...l,deviceIds:[this.id]})}async createShareLink(t,n){return t.scope.deviceIds=[this.id],await createShareLink(t,n)}}be(Device,"createDevice",createDevice),be(Device,"patchDevice",patchDevice),be(Device,"getDevicesData",getDevicesData),be(Device,"queryDevicesData",queryDevicesData),be(Device,"disableDevice",disableDevice);class PeerDevice extends BaseDevice{constructor(n){super();be(this,"id");be(this,"telemetryStreamActive",!1);be(this,"streamTelemetry",{});this.peerUrl=n}async getLatestTelemetry(){this.telemetryStreamActive||this.subscribeToTelemetry();const n=this.streamTelemetry;return Object.entries(n).map(([o,l])=>({deviceId:this.id,streamName:o,streamType:"json",currentValue:l,currentValueTime:l.timestamp,tags:{}}))}subscribeToTelemetry(){this.telemetryStreamActive=!0;let n=0;const r=new XMLHttpRequest;r.responseType="text",r.addEventListener("error",o=>{this.handleXHRError("error")}),r.addEventListener("abort",o=>{this.handleXHRError("abort")}),r.addEventListener("timeout",o=>{this.handleXHRError("timeout")}),r.addEventListener("readystatechange",o=>{r.readyState===XMLHttpRequest.DONE&&this.handleXHRError("closed")}),r.addEventListener("progress",o=>{const l=o.loaded,u=l-n;n=l,r.responseText.substr(-u).split(`
|
|
63
|
-
`).forEach(c=>{var d;if(c.length>0){const w=JSON.parse(c);if((d=w.result)!=null&&d.datapoint){const v=w.result.datapoint,y=v.stream;delete v.stream,this.streamTelemetry[y]=v}}})}),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 sendCommand(n,r,o,l){const u={value:r,scrubberTime:(o||new Date).toISOString(),meta:l};return await fetch(`${this.peerUrl}/v1/enqueue-command`,{method:"POST",body:JSON.stringify({command:n,parameter:u}),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<"u"&&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:o}=await n.json();return await queryDevices({tags:{[r]:[o]},enabled:!0,type:"default"})}async function getDevice(e){if(!Authentication.token)throw new Error("Not authenticated");const n=await(await fetch(`${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(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(o=>!!o);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(o=>n.includes(o.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(o=>o.deviceId);return(await getDevices()).filter(o=>n.includes(o.id))}async function getStreams(){if(!Authentication.token)throw new Error("Not authenticated");return(await(await fetch(`${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 Ie=class Ie{static async setDefaultDevice(t){Ie.defaultDeviceId=t}static async getCurrentDevice(){if(!Authentication.token)throw new Error("Not authenticated");if(!Ie.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(u=>u.id===Ie.defaultDeviceId),o=r.name,l=new Device(Ie.defaultDeviceId,o,defined(Authentication.currentOrganization),r.tags);return Ie.knownContext.push(new WeakRef(l)),l}static async getPeerDevice(t){const n=new PeerDevice(t);return n.id=await n.getDeviceId(),n}static async getDevice(t){const n=await getDevice(t);return Ie.knownContext.push(new WeakRef(n)),n}};be(Ie,"defaultDeviceId"),be(Ie,"knownContext",[]),be(Ie,"createFleet",createFleet),be(Ie,"listFleets",listFleets),be(Ie,"getFleet",getFleet),be(Ie,"patchFleet",patchFleet),be(Ie,"deleteFleet",deleteFleet),be(Ie,"addDeviceToFleet",addDeviceToFleet),be(Ie,"getFleetDevices",getFleetDevices),be(Ie,"aggregateTelemetry",aggregateTelemetry),be(Ie,"createShareLink",createShareLink),be(Ie,"eventsCounter",eventsCounter),be(Ie,"getAnalyticStreams",getAnalyticStreams),be(Ie,"getAnalyticsModules",getAnalyticsModules),be(Ie,"getAnalyticsRows",getAnalyticsRows),be(Ie,"getAnnotationCount",getAnnotationCount),be(Ie,"getAnnotationCountByIntervals",getAnnotationCountByIntervals),be(Ie,"getCurrentGroup",getCurrentGroup),be(Ie,"getDevices",getDevices),be(Ie,"getEvent",getEvent),be(Ie,"getFileUrl",getFileUrl),be(Ie,"getInterventions",getInterventions),be(Ie,"getLatestTelemetry",getLatestTelemetry),be(Ie,"getOnlineDevices",getOnlineDevices),be(Ie,"getPeers",getPeers),be(Ie,"getRealtimeDevices",getRealtimeDevices),be(Ie,"getRealtimeSessions",getRealtimeSessions),be(Ie,"getStreams",getStreams),be(Ie,"getTaskReportRows",getTaskReportRows),be(Ie,"getTaskReportTables",getTaskReportTables),be(Ie,"getTelemetry",getTelemetry),be(Ie,"getViews",getViews),be(Ie,"patchStream",patchStream),be(Ie,"patchView",patchView),be(Ie,"queryAnalytics",queryAnalytics),be(Ie,"queryDevices",queryDevices),be(Ie,"queryEvents",queryEvents),be(Ie,"queryTelemetry",queryTelemetry),be(Ie,"getAllEventTriggerGroup",getAllEventTriggerGroup),be(Ie,"getEventTriggerGroup",getEventTriggerGroup),be(Ie,"patchEventTriggergroup",patchEventTriggerGroup);let Fleet=Ie;class KeyValue{static async set(t,n,r){try{const o=await fetch(FORMANT_API_URL+"/v1/admin/key-value",{method:"POST",body:JSON.stringify({organizationId:defined(Authentication.currentUser).organizationId,key:t,value:n,tags:r}),headers:{"Content-Type":"application/json",Authorization:"Bearer "+Authentication.token}}),l=await o.json();if(o.status!==200)throw new Error(l.message)}catch(o){throw o}}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(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){be(this,"muted",!1);be(this,"hasReceivedData",!1);be(this,"audioContext");be(this,"chunks",[]);be(this,"isPlaying",!1);be(this,"startTime",0);be(this,"lastChunkOffset",0);be(this,"bufferSize",3);be(this,"receive",async t=>{var u;const n=(u=t.payload.audioChunk)==null?void 0:u.chunk_data;if(!n)return;this.hasReceivedData||(this.hasReceivedData=!0);const{audioContext:r,muted:o}=this;if(!r||t.header.stream.streamType!==rtcAudioChunkStreamType||o!==!1)return;const l=stringToArrayBuffer(n);try{await r.decodeAudioData(l.buffer,this.scheduleChunk)}catch(s){console.warn("Error decoding audio buffer, changing audioWireFormat on agent",{error:s}),this.changeAudioWireFormat("wav")}});be(this,"scheduleChunk",t=>{const{audioContext:n}=this;if(!n)return;(this.chunks.length>this.bufferSize||this.isPlaying===!1)&&(this.chunks.forEach(o=>{o.stop()}),this.isPlaying=!1,this.chunks=[]);const r=this.createChunk(t);r&&r.buffer&&(this.isPlaying===!1&&(this.startTime=n.currentTime,this.lastChunkOffset=0,this.isPlaying=!0),r.start(this.startTime+this.lastChunkOffset,0,t.duration),this.lastChunkOffset+=r.buffer.duration,this.chunks.push(r))});this.device=t,this.stream=n,this.device.startListeningToRealtimeDataStream(n),this.device.addRealtimeListener((o,l)=>{this.receive(l)}),browser()==="Safari"||browser()==="IE"?this.changeAudioWireFormat("wav"):this.changeAudioWireFormat("opus");const r=window.AudioContext||window.webkitAudioContext;this.audioContext=new r}async play(){var t,n;((t=this.audioContext)==null?void 0:t.state)==="suspended"&&await((n=this.audioContext)==null?void 0:n.resume()),this.muted=!1}async pause(){await this.audioContext.suspend(),this.muted=!0}destroy(){this.device.stopListeningToRealtimeDataStream(this.stream)}createChunk(t){const{audioContext:n}=this;if(!n)return;const r=n.createBufferSource();return r.buffer=t,r.connect(n.destination),r.loop=!1,r.onended=o=>{this.chunks.splice(this.chunks.indexOf(r),1),this.chunks.length===0&&(this.isPlaying=!1)},r}changeAudioWireFormat(t){const{stream:n}=this;(async()=>await this.device.changeStreamAudioType(n.name,t))()}}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","intervention-request","teleop-session-record","port-forwarding-session-record","command-request","command-response","command-delivery","custom","comment","system","annotation"],healthStatuses=["unknown","operational","offline","error"],interventionTypes=["selection","labeling","teleop"],severities=["info","warning","error","critical"],videoMimeTypes=["video/mp4"],timeout=e=>new Promise(t=>setTimeout(t,e*1e3));try{const e=typeof window<"u"&&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<"u"&&App.listenForConnectionEvents()}catch(e){}exports.Account=Account,exports.App=App,exports.AudioPlayer=AudioPlayer,exports.Authentication=Authentication,exports.BinaryRequestDataChannel=BinaryRequestDataChannel,exports.CaptureStream=CaptureStream,exports.DataChannel=DataChannel,exports.Device=Device,exports.Fleet=Fleet,exports.KeyValue=KeyValue,exports.Manipulator=Manipulator,exports.PeerDevice=PeerDevice,exports.Role=Role,exports.SessionType=SessionTypeConstants,exports.TextRequestDataChannel=TextRequestDataChannel,exports.User=User,exports.accessLevels=accessLevels,exports.administrator=administrator,exports.aggregateByDateFunctions=aggregateByDateFunctions,exports.aggregateFunctionMap=aggregateFunctionMap,exports.aggregateFunctions=aggregateFunctions,exports.aggregateLevels=aggregateLevels,exports.annotationTypes=annotationTypes,exports.createRtcStreamMessage=distExports.createRtcStreamMessage,exports.eventTypes=eventTypes,exports.formatTimeFrameText=formatTimeFrameText,exports.getAverage=getAverage,exports.getCount=getCount,exports.getMax=getMax,exports.getMin=getMin,exports.getStandardDeviation=getStandardDeviation,exports.getSum=getSum,exports.getVariance=getVariance,exports.healthStatuses=healthStatuses,exports.interventionTypes=interventionTypes,exports.operator=operator,exports.severities=severities,exports.timeout=timeout,exports.vailableAggregationIntervals=vailableAggregationIntervals,exports.videoMimeTypes=videoMimeTypes,exports.viewer=viewer,Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"})});
|
|
63
|
+
`).forEach(c=>{var d;if(c.length>0){const w=JSON.parse(c);if((d=w.result)!=null&&d.datapoint){const v=w.result.datapoint,y=v.stream;delete v.stream,this.streamTelemetry[y]=v}}})}),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,o,l){const u={value:r,scrubberTime:(o||new Date).toISOString(),meta:l};return await fetch(`${this.peerUrl}/v1/enqueue-command`,{method:"POST",body:JSON.stringify({command:n,parameter:u}),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<"u"&&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:o}=await n.json();return await queryDevices({tags:{[r]:[o]},enabled:!0,type:"default"})}async function getDevice(e){if(!Authentication.token)throw new Error("Not authenticated");const n=await(await fetch(`${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(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(o=>!!o);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(o=>n.includes(o.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(o=>o.deviceId);return(await getDevices()).filter(o=>n.includes(o.id))}async function getStreams(){if(!Authentication.token)throw new Error("Not authenticated");return(await(await fetch(`${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 Ie=class Ie{static async setDefaultDevice(t){Ie.defaultDeviceId=t}static async getCurrentDevice(){if(!Authentication.token)throw new Error("Not authenticated");if(!Ie.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(u=>u.id===Ie.defaultDeviceId),o=r.name,l=new Device(Ie.defaultDeviceId,o,defined(Authentication.currentOrganization),r.tags);return Ie.knownContext.push(new WeakRef(l)),l}static async getPeerDevice(t){const n=new PeerDevice(t);return n.id=await n.getDeviceId(),n}static async getDevice(t){const n=await getDevice(t);return Ie.knownContext.push(new WeakRef(n)),n}};be(Ie,"defaultDeviceId"),be(Ie,"knownContext",[]),be(Ie,"createFleet",createFleet),be(Ie,"listFleets",listFleets),be(Ie,"getFleet",getFleet),be(Ie,"patchFleet",patchFleet),be(Ie,"deleteFleet",deleteFleet),be(Ie,"addDeviceToFleet",addDeviceToFleet),be(Ie,"getFleetDevices",getFleetDevices),be(Ie,"aggregateTelemetry",aggregateTelemetry),be(Ie,"createShareLink",createShareLink),be(Ie,"eventsCounter",eventsCounter),be(Ie,"getAnalyticStreams",getAnalyticStreams),be(Ie,"getAnalyticsModules",getAnalyticsModules),be(Ie,"getAnalyticsRows",getAnalyticsRows),be(Ie,"getAnnotationCount",getAnnotationCount),be(Ie,"getAnnotationCountByIntervals",getAnnotationCountByIntervals),be(Ie,"getCurrentGroup",getCurrentGroup),be(Ie,"getDevices",getDevices),be(Ie,"getEvent",getEvent),be(Ie,"getFileUrl",getFileUrl),be(Ie,"getInterventions",getInterventions),be(Ie,"getLatestTelemetry",getLatestTelemetry),be(Ie,"getOnlineDevices",getOnlineDevices),be(Ie,"getPeers",getPeers),be(Ie,"getRealtimeDevices",getRealtimeDevices),be(Ie,"getRealtimeSessions",getRealtimeSessions),be(Ie,"getStreams",getStreams),be(Ie,"getTaskReportRows",getTaskReportRows),be(Ie,"getTaskReportTables",getTaskReportTables),be(Ie,"getTelemetry",getTelemetry),be(Ie,"getViews",getViews),be(Ie,"patchStream",patchStream),be(Ie,"patchView",patchView),be(Ie,"queryAnalytics",queryAnalytics),be(Ie,"queryDevices",queryDevices),be(Ie,"queryEvents",queryEvents),be(Ie,"queryTelemetry",queryTelemetry),be(Ie,"getAllEventTriggerGroup",getAllEventTriggerGroup),be(Ie,"getEventTriggerGroup",getEventTriggerGroup),be(Ie,"patchEventTriggergroup",patchEventTriggerGroup);let Fleet=Ie;class KeyValue{static async set(t,n,r){try{const o=await fetch(FORMANT_API_URL+"/v1/admin/key-value",{method:"POST",body:JSON.stringify({organizationId:defined(Authentication.currentUser).organizationId,key:t,value:n,tags:r}),headers:{"Content-Type":"application/json",Authorization:"Bearer "+Authentication.token}}),l=await o.json();if(o.status!==200)throw new Error(l.message)}catch(o){throw o}}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(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){be(this,"muted",!1);be(this,"hasReceivedData",!1);be(this,"audioContext");be(this,"chunks",[]);be(this,"isPlaying",!1);be(this,"startTime",0);be(this,"lastChunkOffset",0);be(this,"bufferSize",3);be(this,"receive",async t=>{var u;const n=(u=t.payload.audioChunk)==null?void 0:u.chunk_data;if(!n)return;this.hasReceivedData||(this.hasReceivedData=!0);const{audioContext:r,muted:o}=this;if(!r||t.header.stream.streamType!==rtcAudioChunkStreamType||o!==!1)return;const l=stringToArrayBuffer(n);try{await r.decodeAudioData(l.buffer,this.scheduleChunk)}catch(s){console.warn("Error decoding audio buffer, changing audioWireFormat on agent",{error:s}),this.changeAudioWireFormat("wav")}});be(this,"scheduleChunk",t=>{const{audioContext:n}=this;if(!n)return;(this.chunks.length>this.bufferSize||this.isPlaying===!1)&&(this.chunks.forEach(o=>{o.stop()}),this.isPlaying=!1,this.chunks=[]);const r=this.createChunk(t);r&&r.buffer&&(this.isPlaying===!1&&(this.startTime=n.currentTime,this.lastChunkOffset=0,this.isPlaying=!0),r.start(this.startTime+this.lastChunkOffset,0,t.duration),this.lastChunkOffset+=r.buffer.duration,this.chunks.push(r))});this.device=t,this.stream=n,this.device.startListeningToRealtimeDataStream(n),this.device.addRealtimeListener((o,l)=>{this.receive(l)}),browser()==="Safari"||browser()==="IE"?this.changeAudioWireFormat("wav"):this.changeAudioWireFormat("opus");const r=window.AudioContext||window.webkitAudioContext;this.audioContext=new r}async play(){var t,n;((t=this.audioContext)==null?void 0:t.state)==="suspended"&&await((n=this.audioContext)==null?void 0:n.resume()),this.muted=!1}async pause(){await this.audioContext.suspend(),this.muted=!0}destroy(){this.device.stopListeningToRealtimeDataStream(this.stream)}createChunk(t){const{audioContext:n}=this;if(!n)return;const r=n.createBufferSource();return r.buffer=t,r.connect(n.destination),r.loop=!1,r.onended=o=>{this.chunks.splice(this.chunks.indexOf(r),1),this.chunks.length===0&&(this.isPlaying=!1)},r}changeAudioWireFormat(t){const{stream:n}=this;(async()=>await this.device.changeStreamAudioType(n.name,t))()}}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","intervention-request","teleop-session-record","port-forwarding-session-record","command-request","command-response","command-delivery","custom","comment","system","annotation"],healthStatuses=["unknown","operational","offline","error"],interventionTypes=["selection","labeling","teleop"],severities=["info","warning","error","critical"],videoMimeTypes=["video/mp4"],timeout=e=>new Promise(t=>setTimeout(t,e*1e3));try{const e=typeof window<"u"&&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<"u"&&App.listenForConnectionEvents()}catch(e){}exports.Account=Account,exports.App=App,exports.AudioPlayer=AudioPlayer,exports.Authentication=Authentication,exports.BinaryRequestDataChannel=BinaryRequestDataChannel,exports.CaptureStream=CaptureStream,exports.DataChannel=DataChannel,exports.Device=Device,exports.Fleet=Fleet,exports.KeyValue=KeyValue,exports.Manipulator=Manipulator,exports.PeerDevice=PeerDevice,exports.Role=Role,exports.SessionType=SessionTypeConstants,exports.TextRequestDataChannel=TextRequestDataChannel,exports.User=User,exports.accessLevels=accessLevels,exports.administrator=administrator,exports.aggregateByDateFunctions=aggregateByDateFunctions,exports.aggregateFunctionMap=aggregateFunctionMap,exports.aggregateFunctions=aggregateFunctions,exports.aggregateLevels=aggregateLevels,exports.annotationTypes=annotationTypes,exports.createRtcStreamMessage=distExports.createRtcStreamMessage,exports.eventTypes=eventTypes,exports.formatTimeFrameText=formatTimeFrameText,exports.getAverage=getAverage,exports.getCount=getCount,exports.getMax=getMax,exports.getMin=getMin,exports.getStandardDeviation=getStandardDeviation,exports.getSum=getSum,exports.getVariance=getVariance,exports.healthStatuses=healthStatuses,exports.interventionTypes=interventionTypes,exports.operator=operator,exports.severities=severities,exports.timeout=timeout,exports.vailableAggregationIntervals=vailableAggregationIntervals,exports.videoMimeTypes=videoMimeTypes,exports.viewer=viewer,Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"})});
|