@formant/data-sdk 1.78.2 → 1.79.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.
@@ -1,4 +1,4 @@
1
- "use strict";var Rn=Object.defineProperty;var Bn=(e,t,n)=>t in e?Rn(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n;var he=(e,t,n)=>(Bn(e,typeof t!="symbol"?t+"":t,n),n);Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const DEFAULT_FORMANT_API_URL="https://api.formant.io";function whichFormantApiUrl(e,t,n){try{if(t.get("formant_prod"))return"https://api.formant.io";if(t.get("formant_stage"))return"https://api-stage.formant.io";if(t.get("formant_dev"))return"https://api-dev.formant.io";if(t.get("formant_local"))return"https://api.formant.local";if(t.get("formant_url")){const r=t.get("formant_url");if(r!==null)try{return new URL(r).origin}catch{console.warn(`Ignoring malformed \`formant_url\` url parameter: ${r}`)}}if(n){if(n.includes("app-dev.formant.io")||n.includes("localhost"))return"https://api-dev.formant.io";if(n.includes("app-stage.formant.io"))return"https://api-stage.formant.io";if(n.includes("app.formant.io"))return"https://api.formant.io"}}catch{}if(n){if(n.includes("app-dev.formant.io"))return"https://api-dev.formant.io";if(n.includes("app-stage.formant.io"))return"https://api-stage.formant.io";if(n.includes("app.formant.io"))return"https://api.formant.io"}return typeof e!="undefined"&&"FORMANT_API_URL"in e&&typeof e.FORMANT_API_URL=="string"?e.FORMANT_API_URL:DEFAULT_FORMANT_API_URL}exports.FORMANT_API_URL=whichFormantApiUrl(typeof window!="undefined"?window:globalThis,new URLSearchParams(typeof window!="undefined"&&window.location?window.location.search:void 0),typeof window!="undefined"&&window.location?window.location.host:void 0);const setFormantApiUrl=e=>{exports.FORMANT_API_URL=e};function addAccessTokenRefreshListener(e){function t(n){const r=n.data;r.type==="auth_token"&&e(r.token)}return window.addEventListener("message",t),()=>{window.removeEventListener("message",t)}}function getCurrentModuleContext(){return typeof window!="undefined"&&window.location?new URLSearchParams(window.location.search).get("module"):null}function sendAppMessage(e){if(!(window&&window.parent))throw new Error("cannot send message to non-existent parent");window.parent.postMessage(e,"*")}function refreshAuthToken(){const e=getCurrentModuleContext();if(!e)throw new Error("No module context");sendAppMessage({type:"refresh_auth_token",module:e})}var commonjsGlobal=typeof globalThis!="undefined"?globalThis:typeof window!="undefined"?window:typeof global!="undefined"?global:typeof self!="undefined"?self:{};function getDefaultExportFromCjs(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}var base64={exports:{}};/*! https://mths.be/base64 v1.0.0 by @mathias | MIT license */base64.exports;(function(e,t){(function(n){var r=t,o=e&&e.exports==r&&e,s=typeof commonjsGlobal=="object"&&commonjsGlobal;(s.global===s||s.window===s)&&(n=s);var g=function(p){this.message=p};g.prototype=new Error,g.prototype.name="InvalidCharacterError";var l=function(p){throw new g(p)},u="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",c=/[\t\n\f\r ]/g,d=function(p){p=String(p).replace(c,"");var U=p.length;U%4==0&&(p=p.replace(/==?$/,""),U=p.length),(U%4==1||/[^+a-zA-Z0-9/]/.test(p))&&l("Invalid character: the string to be decoded is not correctly encoded.");for(var E=0,M,W,y="",m=-1;++m<U;)W=u.indexOf(p.charAt(m)),M=E%4?M*64+W:W,E++%4&&(y+=String.fromCharCode(255&M>>(-2*E&6)));return y},B=function(p){p=String(p),/[^\0-\xFF]/.test(p)&&l("The string to be encoded contains characters outside of the Latin1 range.");for(var U=p.length%3,E="",M=-1,W,y,m,h,T=p.length-U;++M<T;)W=p.charCodeAt(M)<<16,y=p.charCodeAt(++M)<<8,m=p.charCodeAt(++M),h=W+y+m,E+=u.charAt(h>>18&63)+u.charAt(h>>12&63)+u.charAt(h>>6&63)+u.charAt(h&63);return U==2?(W=p.charCodeAt(M)<<8,y=p.charCodeAt(++M),h=W+y,E+=u.charAt(h>>10)+u.charAt(h>>4&63)+u.charAt(h<<2&63)+"="):U==1&&(h=p.charCodeAt(M),E+=u.charAt(h>>2)+u.charAt(h<<4&63)+"=="),E},Q={encode:B,decode:d,version:"1.0.0"};if(r&&!r.nodeType)if(o)o.exports=Q;else for(var f in Q)Q.hasOwnProperty(f)&&(r[f]=Q[f]);else n.base64=Q})(commonjsGlobal)})(base64,base64.exports);var base64Exports=base64.exports;class LoginFailureError extends Error{constructor(n){super("login failed");he(this,"reason");this.reason=n,this.name="LoginFailureError",Object.setPrototypeOf(this,new.target.prototype)}}class LoginChallengedError extends Error{constructor(n){super("login challenged");he(this,"challenge");this.challenge=n,this.name="LoginChallengedError",Object.setPrototypeOf(this,new.target.prototype)}}class AuthenticationStore{constructor({apiUrl:t,refreshAuthToken:n,addAccessTokenRefreshListener:r}){he(this,"_refreshToken");he(this,"_isShareToken",!1);he(this,"_currentOrganization");he(this,"_currentUser");he(this,"_defaultDeviceId");he(this,"_token");he(this,"_waitingForAuth",new Set);he(this,"_refreshTimer");he(this,"_apiUrl");he(this,"_refreshAuthToken");he(this,"_addAccessTokenRefreshListener");this._apiUrl=t,this._refreshAuthToken=n,this._addAccessTokenRefreshListener=r}set apiUrl(t){this._apiUrl=t,setFormantApiUrl(t)}get apiUrl(){return this._apiUrl}get token(){return this._token}get currentUser(){return this._currentUser}get currentOrganization(){return this._currentOrganization}get defaultDeviceId(){return this._defaultDeviceId}get refreshToken(){return this._refreshToken}get isShareToken(){return this._isShareToken}async login(t,n,r={}){const{advanced:o=!1}=r;try{const s=await fetch(`${this._apiUrl}/v1/admin/auth/login`,{method:"POST",body:JSON.stringify({email:t,password:n}),headers:{"Content-Type":"application/json"}}),g=await s.json();if(s.status!==200)throw new LoginFailureError(g.message);if("challenge"in g)throw new LoginChallengedError(g.challenge);const{authentication:l}=g;return await this.loginWithToken(l.accessToken,l.refreshToken),o?{result:"success",authentication:l}:l}catch(s){if(o||console.error("login() failed",{err:s}),this._waitingForAuth.forEach(g=>g(!1)),this._waitingForAuth.clear(),!o)throw s;return s instanceof LoginChallengedError?{result:"challenged",challenge:s.challenge}:{result:"failure",reason:s instanceof LoginFailureError?s.reason:s instanceof Error?s.message:String(s)}}}async loginWithToken(t,n,r=!1){var s;const o=JSON.parse(base64Exports.decode(t.split(".")[1]));try{let g;if(this._isShareToken=o["formant:claims"]&&o["formant:claims"].type=="share",o["formant:claims"]&&(this._currentOrganization=o["formant:claims"].organizationId),o["custom:organization_id"]&&(this._currentOrganization=o["custom:organization_id"]),this._isShareToken||(g=o.sub),o["formant:claims"]&&o["formant:claims"].userId&&(g=o["formant:claims"].userId),g&&((s=this._currentUser)==null?void 0:s.id)!==g&&!r){const l=await fetch(`${this._apiUrl}/v1/admin/users/${g}`,{method:"GET",headers:{"Content-Type":"application/json",Authorization:"Bearer "+t}}),u=await l.json();if(l.status!==200)throw new Error(u.message);this._currentUser=u}this._token=t,this._waitingForAuth.forEach(l=>l(!0))}catch(g){console.error("loginWithToken() failed",{err:g}),this._waitingForAuth.forEach(l=>l(!1))}finally{this._waitingForAuth.clear()}n&&(this._refreshToken=n,setInterval(async()=>{if(this._refreshToken){const l=await(await fetch(`${this._apiUrl}/v1/admin/auth/refresh`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({refreshToken:this._refreshToken})})).json();this._token=l.authentication.accessToken}},1e3*60*60))}isAuthenticated(){return this._token!==void 0}async loginToPeer(t,n,r){if((await fetch(`${t}/login`,{method:"POST",body:JSON.stringify({username:n,password:r}),headers:{"Content-Type":"application/json"}})).status!==200)throw new LoginFailureError("Invalid authentication")}getCurrentUser(){return this._currentUser}async waitTilAuthenticated(){return this.token!==void 0?!0:new Promise(t=>{this._waitingForAuth.add(t)})}async listenForRefresh(){const n=()=>{this._refreshTimer=void 0,this._refreshAuthToken()};this._addAccessTokenRefreshListener(r=>{this._refreshTimer&&clearTimeout(this._refreshTimer),this._refreshTimer=setTimeout(n,36e5),this.loginWithToken(r)}),this._refreshTimer=setTimeout(n,36e5)}async forgotPassword(t){await fetch(`${this._apiUrl}/v1/admin/auth/forgot-password`,{method:"POST",body:JSON.stringify({email:t}),headers:{"Content-Type":"application/json"}})}async confirmForgotPassword(t){return(await fetch(`${this._apiUrl}/v1/admin/auth/confirm-forgot-password`,{method:"POST",body:JSON.stringify(t),headers:{"Content-Type":"application/json"}})).ok}async respondToNewPasswordRequiredChallenge(t){const n=await fetch(`${this._apiUrl}/v1/admin/auth/respond-to-new-password-required-challenge`,{method:"POST",body:JSON.stringify(t),headers:{"Content-Type":"application/json"}});if(n.ok)return await n.json();throw new Error("respond-to-new-password-required-challenge failed")}async loginWithGoogle(t){return await(await fetch(`${this._apiUrl}/v1/admin/auth/login-google`,{method:"POST",body:JSON.stringify(t),headers:{"Content-Type":"application/json"}})).json()}async refresh(t){const r=await(await fetch(`${this._apiUrl}/v1/admin/auth/refresh`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({refreshToken:t})})).json();await this.loginWithToken(r.authentication.accessToken,t)}async checkSso(t,n){return await(await fetch(`${this._apiUrl}/v1/admin/auth/check-sso`,{method:"POST",body:JSON.stringify({email:t,allowUserAutoCreation:n}),headers:{"Content-Type":"application/json"}})).json()}async loginWithSso(t,n){const o=await(await fetch(`${this._apiUrl}/v1/admin/auth/login-sso`,{method:"POST",body:JSON.stringify({token:t,refreshToken:n}),headers:{"Content-Type":"application/json"}})).json();if(!o.authentication)throw new Error("Failed to login with SSO");return await this.loginWithToken(o.authentication.accessToken,o.authentication.refreshToken)}}const Authentication=new AuthenticationStore({apiUrl:exports.FORMANT_API_URL,refreshAuthToken,addAccessTokenRefreshListener});class Account{static async listAccounts(){if(!Authentication.token)throw new Error("Not authenticated");return(await(await fetch(`${exports.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(`${exports.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(`${exports.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(`${exports.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(`${exports.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(`${exports.FORMANT_API_URL}/v1/admin/accounts/${t}/tree`,{method:"GET",headers:{"Content-Type":"application/json",Authorization:"Bearer "+Authentication.token}})).json()}}async function getModuleConfiguration(e){return(await(await fetch(`${exports.FORMANT_API_URL}/v1/admin/module-configurations/${e}`,{headers:{"Content-Type":"application/json",Authorization:"Bearer "+Authentication.token}})).json()).configuration}function disableAnalyticsBottomBar(){sendAppMessage({type:"hide_analytics_date_picker"})}function goToDevice(e){sendAppMessage({type:"go_to_device",deviceId:e})}function goToTime(e){sendAppMessage({type:"go_to_time",time:e.getTime()})}function requestModuleData(){const e=getCurrentModuleContext();if(!e)throw new Error("No module context");sendAppMessage({type:"request_module_data",module:e})}function sendChannelData(e,t){const n=getCurrentModuleContext();if(!n)throw new Error("No module context");sendAppMessage({type:"send_channel_data",source:n,channel:e,data:t})}function setModuleDateTimeRange(e,t){const n=getCurrentModuleContext();if(!n)throw new Error("No module context");sendAppMessage({type:"set_module_data_time_range",module:n,before:e,after:t||0})}function setupModuleMenus(e){const t=getCurrentModuleContext();if(!t)throw new Error("No module context");sendAppMessage({type:"setup_module_menus",module:t,menus:e})}function showMessage(e){sendAppMessage({type:"show_message",message:e})}function addChannelDataListener(e,t){const n=r=>{const o=r.data;o.type==="channel_data"&&o.channel===e&&t({source:o.source,data:o.data})};return window.addEventListener("message",n),()=>window.removeEventListener("message",n)}function addMenuListener(e){const t=n=>{const r=n.data;r.type==="module_menu_item_clicked"&&e(r.menu)};return window.addEventListener("message",t),()=>window.removeEventListener("message",t)}function addModuleConfigurationListener(e){const t=n=>{const r=n.data;r.type==="module_configuration"&&e(r)};return window.addEventListener("message",t),()=>window.removeEventListener("message",t)}function addModuleDataListener(e){const t=getCurrentModuleContext();t&&sendAppMessage({type:"request_module_data",module:t});const n=r=>{const o=r.data;o.type==="module_data"&&e({streams:o.streams,time:o.time,queryRange:o.queryRange})};return window.addEventListener("message",n),()=>window.removeEventListener("message",n)}function addOverviewDeviceListener(e){sendAppMessage({type:"request_devices"});const t=n=>{const r=n.data;r.type==="overview_devices"&&e(r.data)};return window.addEventListener("message",t),()=>window.removeEventListener("message",t)}function _typeof(e){return _typeof=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(t){return typeof t}:function(t){return t&&typeof Symbol=="function"&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},_typeof(e)}function toInteger(e){if(e===null||e===!0||e===!1)return NaN;var t=Number(e);return isNaN(t)?t:t<0?Math.ceil(t):Math.floor(t)}function requiredArgs(e,t){if(t.length<e)throw new TypeError(e+" argument"+(e>1?"s":"")+" required, but only "+t.length+" present")}function toDate(e){requiredArgs(1,arguments);var t=Object.prototype.toString.call(e);return e instanceof Date||_typeof(e)==="object"&&t==="[object Date]"?new Date(e.getTime()):typeof e=="number"||t==="[object Number]"?new Date(e):((typeof e=="string"||t==="[object String]")&&typeof console!="undefined"&&(console.warn("Starting with v2.0.0-beta.1 date-fns doesn't accept strings as date arguments. Please use `parseISO` to parse strings. See: https://github.com/date-fns/date-fns/blob/master/docs/upgradeGuide.md#string-arguments"),console.warn(new Error().stack)),new Date(NaN))}function addDays(e,t){requiredArgs(2,arguments);var n=toDate(e),r=toInteger(t);return isNaN(r)?new Date(NaN):(r&&n.setDate(n.getDate()+r),n)}function addMonths(e,t){requiredArgs(2,arguments);var n=toDate(e),r=toInteger(t);if(isNaN(r))return new Date(NaN);if(!r)return n;var o=n.getDate(),s=new Date(n.getTime());s.setMonth(n.getMonth()+r+1,0);var g=s.getDate();return o>=g?s:(n.setFullYear(s.getFullYear(),s.getMonth(),o),n)}function addMilliseconds(e,t){requiredArgs(2,arguments);var n=toDate(e).getTime(),r=toInteger(t);return new Date(n+r)}var MILLISECONDS_IN_HOUR=36e5;function addHours(e,t){requiredArgs(2,arguments);var n=toInteger(t);return addMilliseconds(e,n*MILLISECONDS_IN_HOUR)}var defaultOptions={};function getDefaultOptions(){return defaultOptions}function startOfWeek(e,t){var n,r,o,s,g,l,u,c;requiredArgs(1,arguments);var d=getDefaultOptions(),B=toInteger((n=(r=(o=(s=t==null?void 0:t.weekStartsOn)!==null&&s!==void 0?s:t==null||(g=t.locale)===null||g===void 0||(l=g.options)===null||l===void 0?void 0:l.weekStartsOn)!==null&&o!==void 0?o:d.weekStartsOn)!==null&&r!==void 0?r:(u=d.locale)===null||u===void 0||(c=u.options)===null||c===void 0?void 0:c.weekStartsOn)!==null&&n!==void 0?n:0);if(!(B>=0&&B<=6))throw new RangeError("weekStartsOn must be between 0 and 6 inclusively");var Q=toDate(e),f=Q.getDay(),p=(f<B?7:0)+f-B;return Q.setDate(Q.getDate()-p),Q.setHours(0,0,0,0),Q}function startOfDay(e){requiredArgs(1,arguments);var t=toDate(e);return t.setHours(0,0,0,0),t}var MILLISECONDS_IN_MINUTE=6e4;function addMinutes(e,t){requiredArgs(2,arguments);var n=toInteger(t);return addMilliseconds(e,n*MILLISECONDS_IN_MINUTE)}function addQuarters(e,t){requiredArgs(2,arguments);var n=toInteger(t),r=n*3;return addMonths(e,r)}function addSeconds(e,t){requiredArgs(2,arguments);var n=toInteger(t);return addMilliseconds(e,n*1e3)}function addWeeks(e,t){requiredArgs(2,arguments);var n=toInteger(t),r=n*7;return addDays(e,r)}function addYears(e,t){requiredArgs(2,arguments);var n=toInteger(t);return addMonths(e,n*12)}function getQuarter(e){requiredArgs(1,arguments);var t=toDate(e),n=Math.floor(t.getMonth()/3)+1;return n}var roundingMap={ceil:Math.ceil,round:Math.round,floor:Math.floor,trunc:function(t){return t<0?Math.ceil(t):Math.floor(t)}},defaultRoundingMethod="trunc";function getRoundingMethod(e){return e?roundingMap[e]:roundingMap[defaultRoundingMethod]}function endOfDay(e){requiredArgs(1,arguments);var t=toDate(e);return t.setHours(23,59,59,999),t}function endOfMonth(e){requiredArgs(1,arguments);var t=toDate(e),n=t.getMonth();return t.setFullYear(t.getFullYear(),n+1,0),t.setHours(23,59,59,999),t}function eachDayOfInterval(e,t){var n;requiredArgs(1,arguments);var r=e||{},o=toDate(r.start),s=toDate(r.end),g=s.getTime();if(!(o.getTime()<=g))throw new RangeError("Invalid interval");var l=[],u=o;u.setHours(0,0,0,0);var c=Number((n=t==null?void 0:t.step)!==null&&n!==void 0?n:1);if(c<1||isNaN(c))throw new RangeError("`options.step` must be a number greater than 1");for(;u.getTime()<=g;)l.push(toDate(u)),u.setDate(u.getDate()+c),u.setHours(0,0,0,0);return l}function eachHourOfInterval(e,t){var n;requiredArgs(1,arguments);var r=e||{},o=toDate(r.start),s=toDate(r.end),g=o.getTime(),l=s.getTime();if(!(g<=l))throw new RangeError("Invalid interval");var u=[],c=o;c.setMinutes(0,0,0);var d=Number((n=t==null?void 0:t.step)!==null&&n!==void 0?n:1);if(d<1||isNaN(d))throw new RangeError("`options.step` must be a number greater than 1");for(;c.getTime()<=l;)u.push(toDate(c)),c=addHours(c,d);return u}function startOfMinute(e){requiredArgs(1,arguments);var t=toDate(e);return t.setSeconds(0,0),t}function eachMinuteOfInterval(e,t){var n;requiredArgs(1,arguments);var r=startOfMinute(toDate(e.start)),o=toDate(e.end),s=r.getTime(),g=o.getTime();if(s>=g)throw new RangeError("Invalid interval");var l=[],u=r,c=Number((n=t==null?void 0:t.step)!==null&&n!==void 0?n:1);if(c<1||isNaN(c))throw new RangeError("`options.step` must be a number equal to or greater than 1");for(;u.getTime()<=g;)l.push(toDate(u)),u=addMinutes(u,c);return l}function eachMonthOfInterval(e){requiredArgs(1,arguments);var t=e||{},n=toDate(t.start),r=toDate(t.end),o=r.getTime(),s=[];if(!(n.getTime()<=o))throw new RangeError("Invalid interval");var g=n;for(g.setHours(0,0,0,0),g.setDate(1);g.getTime()<=o;)s.push(toDate(g)),g.setMonth(g.getMonth()+1);return s}function startOfQuarter(e){requiredArgs(1,arguments);var t=toDate(e),n=t.getMonth(),r=n-n%3;return t.setMonth(r,1),t.setHours(0,0,0,0),t}function eachQuarterOfInterval(e){requiredArgs(1,arguments);var t=e||{},n=toDate(t.start),r=toDate(t.end),o=r.getTime();if(!(n.getTime()<=o))throw new RangeError("Invalid interval");var s=startOfQuarter(n),g=startOfQuarter(r);o=g.getTime();for(var l=[],u=s;u.getTime()<=o;)l.push(toDate(u)),u=addQuarters(u,1);return l}function eachWeekOfInterval(e,t){requiredArgs(1,arguments);var n=e||{},r=toDate(n.start),o=toDate(n.end),s=o.getTime();if(!(r.getTime()<=s))throw new RangeError("Invalid interval");var g=startOfWeek(r,t),l=startOfWeek(o,t);g.setHours(15),l.setHours(15),s=l.getTime();for(var u=[],c=g;c.getTime()<=s;)c.setHours(0),u.push(toDate(c)),c=addWeeks(c,1),c.setHours(15);return u}function startOfMonth(e){requiredArgs(1,arguments);var t=toDate(e);return t.setDate(1),t.setHours(0,0,0,0),t}function endOfYear(e){requiredArgs(1,arguments);var t=toDate(e),n=t.getFullYear();return t.setFullYear(n+1,0,0),t.setHours(23,59,59,999),t}function startOfYear(e){requiredArgs(1,arguments);var t=toDate(e),n=new Date(0);return n.setFullYear(t.getFullYear(),0,1),n.setHours(0,0,0,0),n}function eachYearOfInterval(e){requiredArgs(1,arguments);var t=e||{},n=toDate(t.start),r=toDate(t.end),o=r.getTime();if(!(n.getTime()<=o))throw new RangeError("Invalid interval");var s=[],g=n;for(g.setHours(0,0,0,0),g.setMonth(0,1);g.getTime()<=o;)s.push(toDate(g)),g.setFullYear(g.getFullYear()+1);return s}function endOfHour(e){requiredArgs(1,arguments);var t=toDate(e);return t.setMinutes(59,59,999),t}function endOfWeek(e,t){var n,r,o,s,g,l,u,c;requiredArgs(1,arguments);var d=getDefaultOptions(),B=toInteger((n=(r=(o=(s=t==null?void 0:t.weekStartsOn)!==null&&s!==void 0?s:t==null||(g=t.locale)===null||g===void 0||(l=g.options)===null||l===void 0?void 0:l.weekStartsOn)!==null&&o!==void 0?o:d.weekStartsOn)!==null&&r!==void 0?r:(u=d.locale)===null||u===void 0||(c=u.options)===null||c===void 0?void 0:c.weekStartsOn)!==null&&n!==void 0?n:0);if(!(B>=0&&B<=6))throw new RangeError("weekStartsOn must be between 0 and 6 inclusively");var Q=toDate(e),f=Q.getDay(),p=(f<B?-7:0)+6-(f-B);return Q.setDate(Q.getDate()+p),Q.setHours(23,59,59,999),Q}function endOfMinute(e){requiredArgs(1,arguments);var t=toDate(e);return t.setSeconds(59,999),t}function endOfQuarter(e){requiredArgs(1,arguments);var t=toDate(e),n=t.getMonth(),r=n-n%3+3;return t.setMonth(r,0),t.setHours(23,59,59,999),t}function getDay(e){requiredArgs(1,arguments);var t=toDate(e),n=t.getDay();return n}function getHours(e){requiredArgs(1,arguments);var t=toDate(e),n=t.getHours();return n}function getMinutes(e){requiredArgs(1,arguments);var t=toDate(e),n=t.getMinutes();return n}function getMonth(e){requiredArgs(1,arguments);var t=toDate(e),n=t.getMonth();return n}function getWeekYear(e,t){var n,r,o,s,g,l,u,c;requiredArgs(1,arguments);var d=toDate(e),B=d.getFullYear(),Q=getDefaultOptions(),f=toInteger((n=(r=(o=(s=t==null?void 0:t.firstWeekContainsDate)!==null&&s!==void 0?s:t==null||(g=t.locale)===null||g===void 0||(l=g.options)===null||l===void 0?void 0:l.firstWeekContainsDate)!==null&&o!==void 0?o:Q.firstWeekContainsDate)!==null&&r!==void 0?r:(u=Q.locale)===null||u===void 0||(c=u.options)===null||c===void 0?void 0:c.firstWeekContainsDate)!==null&&n!==void 0?n:1);if(!(f>=1&&f<=7))throw new RangeError("firstWeekContainsDate must be between 1 and 7 inclusively");var p=new Date(0);p.setFullYear(B+1,0,f),p.setHours(0,0,0,0);var U=startOfWeek(p,t),E=new Date(0);E.setFullYear(B,0,f),E.setHours(0,0,0,0);var M=startOfWeek(E,t);return d.getTime()>=U.getTime()?B+1:d.getTime()>=M.getTime()?B:B-1}function startOfWeekYear(e,t){var n,r,o,s,g,l,u,c;requiredArgs(1,arguments);var d=getDefaultOptions(),B=toInteger((n=(r=(o=(s=t==null?void 0:t.firstWeekContainsDate)!==null&&s!==void 0?s:t==null||(g=t.locale)===null||g===void 0||(l=g.options)===null||l===void 0?void 0:l.firstWeekContainsDate)!==null&&o!==void 0?o:d.firstWeekContainsDate)!==null&&r!==void 0?r:(u=d.locale)===null||u===void 0||(c=u.options)===null||c===void 0?void 0:c.firstWeekContainsDate)!==null&&n!==void 0?n:1),Q=getWeekYear(e,t),f=new Date(0);f.setFullYear(Q,0,B),f.setHours(0,0,0,0);var p=startOfWeek(f,t);return p}var MILLISECONDS_IN_WEEK=6048e5;function getWeek(e,t){requiredArgs(1,arguments);var n=toDate(e),r=startOfWeek(n,t).getTime()-startOfWeekYear(n,t).getTime();return Math.round(r/MILLISECONDS_IN_WEEK)+1}function getYear(e){return requiredArgs(1,arguments),toDate(e).getFullYear()}function startOfHour(e){requiredArgs(1,arguments);var t=toDate(e);return t.setMinutes(0,0,0),t}function subDays(e,t){requiredArgs(2,arguments);var n=toInteger(t);return addDays(e,-n)}function roundToNearestMinutes(e,t){var n;if(arguments.length<1)throw new TypeError("1 argument required, but only none provided present");var r=toInteger((n=t==null?void 0:t.nearestTo)!==null&&n!==void 0?n:1);if(r<1||r>30)throw new RangeError("`options.nearestTo` must be between 1 and 30");var o=toDate(e),s=o.getSeconds(),g=o.getMinutes()+s/60,l=getRoundingMethod(t==null?void 0:t.roundingMethod),u=l(g/r)*r,c=g%r,d=Math.round(c/r)*r;return new Date(o.getFullYear(),o.getMonth(),o.getDate(),o.getHours(),u+d)}function subMonths(e,t){requiredArgs(2,arguments);var n=toInteger(t);return addMonths(e,-n)}function subHours(e,t){requiredArgs(2,arguments);var n=toInteger(t);return addHours(e,-n)}function subMinutes(e,t){requiredArgs(2,arguments);var n=toInteger(t);return addMinutes(e,-n)}function subQuarters(e,t){requiredArgs(2,arguments);var n=toInteger(t);return addQuarters(e,-n)}function subWeeks(e,t){requiredArgs(2,arguments);var n=toInteger(t);return addWeeks(e,-n)}function subYears(e,t){requiredArgs(2,arguments);var n=toInteger(t);return addYears(e,-n)}const millisecond$2=1,second$2=1e3,minute$2=60*second$2,hour$2=60*minute$2,day$2=24*hour$2,week$2=7*day$2,month$2=30*day$2,year$2=365*day$2,duration$2={millisecond:millisecond$2,second:second$2,minute:minute$2,hour:hour$2,day:day$2,week:week$2,month:month$2,year:year$2};function filterDataByType$1(e,t){return e.filter(n=>t.includes(n.type))}function filterDataByTime$1(e,t,n){const r=t.getTime(),o=n.getTime();return e.map(s=>({...s,points:s.points.filter(([g])=>g>=r&&g<o)})).filter(({points:s})=>s.length>0)}let StoreCache$1=class{constructor({capacity:t,timeout:n}={}){he(this,"entries",new Map);he(this,"metadata",new Map);he(this,"capacity");he(this,"staleIntervalMs");this.capacity=t||1e4,this.staleIntervalMs=n||duration$2.minute}get(t,n){const r=this.keyToCacheKey(t);return this.isStale(r)&&!this.isGenerating(r)&&n&&this.generate(t,n),this.entries.get(r)}set(t,n){const r=this.keyToCacheKey(t);this.metadata.set(r,{generating:!1,staleAt:performance.now()+this.staleIntervalMs});const o=this.entries.get(r);JSON.stringify(o)===JSON.stringify(n)||(this.entries.set(r,n),this.enforceMaxSize())}clear(){this.entries.clear(),[...this.metadata.values()].forEach(t=>t.generating=!1)}clearKey(t){this.metadata.delete(t),this.entries.delete(t)}keyToCacheKey(t){return JSON.stringify(t)}enforceMaxSize(){for(;this.metadata.size>this.capacity&&this.metadata.size>0;){const[t]=[...this.metadata.entries()].reduce(([n,r],[o,s])=>s.staleAt<r.staleAt?[o,s]:[n,r]);this.clearKey(t)}}isStale(t){const n=this.metadata.get(t);return n?(n==null?void 0:n.staleAt)<performance.now():!0}isGenerating(t){const n=this.metadata.get(t);return n?n.generating:!1}generate(t,n){const r=this.keyToCacheKey(t),o=this.metadata.get(r)||{},s=n().then(g=>{const l=this.metadata.get(r);return(l==null?void 0:l.generating)!==s||this.set(t,g),g}).catch(g=>{throw this.metadata.delete(r),g});this.metadata.set(r,{...o,generating:s,staleAt:performance.now()+this.staleIntervalMs})}};async function queryTelemetry(e){if(!Authentication.token)throw new Error("Not authenticated");return(await(await fetch(`${exports.FORMANT_API_URL}/v1/queries/queries`,{method:"POST",body:JSON.stringify(e),headers:{"Content-Type":"application/json",Authorization:"Bearer "+Authentication.token}})).json()).items}let QueryStore$1=class{constructor(){he(this,"queryStoreCache",new StoreCache$1({capacity:1e4,timeout:20*duration$2.second}));he(this,"liveQueryStoreCache",new StoreCache$1({capacity:1e4,timeout:200*duration$2.millisecond}))}moduleQuery(t,n,r,o,s,g=!1){const l={...t,names:[...n],types:[...r]},u=this.query(l,o,s,g);return u===void 0||u==="too much data"?u:filterDataByType$1(u,r)}query(t,n,r,o=!1){const s={...t,start:startOfMinute(n).toISOString(),end:o?r.toISOString():addMinutes(roundToNearestMinutes(r),1).toISOString(),latestOnly:o},g=r>addSeconds(new Date,-20);let l;return g?l=this.liveQueryCache(s):l=this.queryCache(s),!l||l==="too much data"||o?l:filterDataByTime$1(l,n,r)}queryCache(t){return this.queryStoreCache.get(t,async()=>{try{return await queryTelemetry(t)}catch(n){throw n}})}liveQueryCache(t){return this.liveQueryStoreCache.get(t,async()=>{try{return await queryTelemetry(t)}catch(n){throw n}})}};const queryStore=new QueryStore$1;function addStreamListener(e,t,n){const r=o=>{const s=o.data;if(s.type==="module_data"){const{start:g,end:l}=s.queryRange;n(queryStore.moduleQuery({},e,t,new Date(g),new Date(l),!1))}};return window.addEventListener("message",r),()=>window.removeEventListener("message",r)}async function getDate(e,t,n){return new Promise(r=>{sendAppMessage({type:"request_date",minTime:t,maxTime:n,time:e});const o=s=>{const g=s.data;g.type==="date_response"&&(window.removeEventListener("message",o),r(g.data))};window.addEventListener("message",o)})}async function prompt(e,t){return new Promise(n=>{const r=Math.random().toString();sendAppMessage({type:"prompt",promptId:r,schema:e,okText:t==null?void 0:t.okText,cancelText:t==null?void 0:t.cancelText});const o=s=>{const g=s.data;g.type==="prompt_response"&&g.promptId===r&&n(g.data),window.removeEventListener("message",o)};window.addEventListener("message",o)})}const Yt=class{static isModule(){return getCurrentModuleContext()!==null}static async getCurrentModuleConfiguration(){let t=new URLSearchParams("");typeof window!="undefined"&&window.location&&(t=new URLSearchParams(window.location.search));const n=t.get("configuration");if(!(n===null||n.trim()===""))return getModuleConfiguration(n.trim())}static get isOnline(){return Yt._isOnline}static listenForConnectionEvents(){const t=n=>{const{data:r}=n;r.type==="formant_online"&&(this._isOnline=r.online)};return window.addEventListener("message",t),()=>window.removeEventListener("message",t)}static checkConnection(t=1e3){return new Promise((n,r)=>{const o=setTimeout(()=>r(new Error("deadline expired: took too long")),t),s=g=>{window.removeEventListener("message",s),clearTimeout(o);const{data:l}=g;l.type==="formant_online"&&(this._isOnline=l.online,n(l.online))};window.addEventListener("message",s),sendAppMessage({type:"formant_online"})})}static waitForConnection(t=5e3){let n=!1;const r=new Promise((g,l)=>{setTimeout(()=>{n=!0,l(new Error("deadline expired: took too long"))},t)}),o=g=>new Promise(l=>setTimeout(l,g)),s=async()=>{for(await o(50);!n&&!(this.isOnline||await this.checkConnection);)await o(500)};return Promise.race([r,s()])}};let App=Yt;he(App,"getCurrentModuleContext",getCurrentModuleContext),he(App,"disableAnalyticsBottomBar",disableAnalyticsBottomBar),he(App,"goToDevice",goToDevice),he(App,"goToTime",goToTime),he(App,"refreshAuthToken",refreshAuthToken),he(App,"requestModuleData",requestModuleData),he(App,"sendChannelData",sendChannelData),he(App,"setModuleDateTimeRange",setModuleDateTimeRange),he(App,"setupModuleMenus",setupModuleMenus),he(App,"showMessage",showMessage),he(App,"addAccessTokenRefreshListener",addAccessTokenRefreshListener),he(App,"addChannelDataListener",addChannelDataListener),he(App,"addMenuListener",addMenuListener),he(App,"addModuleConfigurationListener",addModuleConfigurationListener),he(App,"addModuleDataListener",addModuleDataListener),he(App,"addOverviewDeviceListener",addOverviewDeviceListener),he(App,"addStreamListener",addStreamListener),he(App,"getDate",getDate),he(App,"prompt",prompt),he(App,"_isOnline",null);function stringToArrayBuffer(e){return Uint8Array.from(base64Exports.decode(e),t=>t.charCodeAt(0))}function fork$1(e){}function browser(){const{userAgent:e}=navigator;return e?e.includes("Firefox/")?"Firefox":e.includes("Edg/")?"Edge":e.includes("Chrome/")?"Chrome":e.includes("Safari/")?"Safari":e.includes("MSIE/")||e.includes("Trident/")?"IE":"Other":"Other"}const rtcAudioChunkStreamType="audio-chunk";class AudioPlayer{constructor(t,n){he(this,"muted",!1);he(this,"hasReceivedData",!1);he(this,"audioContext");he(this,"chunks",[]);he(this,"isPlaying",!1);he(this,"startTime",0);he(this,"lastChunkOffset",0);he(this,"bufferSize",3);he(this,"receive",async t=>{var g;const n=(g=t.payload.audioChunk)==null?void 0:g.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 s=stringToArrayBuffer(n);try{await r.decodeAudioData(s.buffer,this.scheduleChunk)}catch(l){console.warn("Error decoding audio buffer, changing audioWireFormat on agent",{error:l}),this.changeAudioWireFormat("wav")}});he(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,s)=>{this.receive(s)}),browser()==="Safari"||browser()==="IE"?this.changeAudioWireFormat("wav"):this.changeAudioWireFormat("opus");const r=window.AudioContext||window.webkitAudioContext;this.audioContext=new r}async play(){var t,n;((t=this.audioContext)==null?void 0:t.state)==="suspended"&&await((n=this.audioContext)==null?void 0:n.resume()),this.muted=!1}async pause(){await this.audioContext.suspend(),this.muted=!0}destroy(){this.device.stopListeningToRealtimeDataStream(this.stream)}createChunk(t){const{audioContext:n}=this;if(!n)return;const r=n.createBufferSource();return r.buffer=t,r.connect(n.destination),r.loop=!1,r.onended=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 CaptureStream{constructor(t){he(this,"token");this.captureSession=t}async ingestJSON(t){if(!this.token){const r=await(await fetch(`${exports.FORMANT_API_URL}/v1/admin/capture-sessions/${this.captureSession.code}/authenticate`,{method:"POST"})).json();this.token=r.token}await fetch(`${exports.FORMANT_API_URL}/v1/ingest`,{method:"POST",body:JSON.stringify({deviceId:this.captureSession.deviceId,name:this.captureSession.streamName,type:"json",points:[[Date.now(),JSON.stringify(t)]]}),headers:{"Content-Type":"application/json",Authorization:"Bearer "+this.token}})}}class DataChannel{constructor(t){he(this,"ready",!1);he(this,"listeners",[]);he(this,"openListeners",[]);he(this,"closeListeners",[]);he(this,"errorListeners",[]);he(this,"binaryListeners",[]);he(this,"error");he(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),s=this.decoder.decode(o);r(s)}),this.binaryListeners.forEach(r=>{r(new Uint8Array(n.data))})}}setReady(){this.ready=!0,this.openListeners.forEach(t=>t())}addOpenListener(t){this.openListeners.push(t)}removeOpenListener(t){this.openListeners=this.openListeners.filter(n=>n!==t)}addCloseListener(t){this.closeListeners.push(t)}removeCloseListener(t){this.closeListeners=this.closeListeners.filter(n=>n!==t)}addErrorListener(t){this.errorListeners.push(t)}removeErrorListener(t){this.errorListeners=this.errorListeners.filter(n=>n!==t)}async waitTilReady(){return this.ready?!0:new Promise((n,r)=>{let 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 dist={exports:{}};/*! For license information please see index.js.LICENSE.txt */(function(module,exports){(function(e,t){module.exports=t()})(window,function(){return function(e){function t(c){for(var d,B,Q=c[0],f=c[1],p=0,U=[];p<Q.length;p++)B=Q[p],Object.prototype.hasOwnProperty.call(r,B)&&r[B]&&U.push(r[B][0]),r[B]=0;for(d in f)Object.prototype.hasOwnProperty.call(f,d)&&(e[d]=f[d]);for(u&&u(c);U.length;)U.shift()()}var n={},r={0:0};function o(c){if(n[c])return n[c].exports;var d=n[c]={i:c,l:!1,exports:{}};return e[c].call(d.exports,d,d.exports,o),d.l=!0,d.exports}o.e=function(){return Promise.resolve()},o.m=e,o.c=n,o.d=function(c,d,B){o.o(c,d)||Object.defineProperty(c,d,{enumerable:!0,get:B})},o.r=function(c){typeof Symbol!="undefined"&&Symbol.toStringTag&&Object.defineProperty(c,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(c,"__esModule",{value:!0})},o.t=function(c,d){if(1&d&&(c=o(c)),8&d||4&d&&typeof c=="object"&&c&&c.__esModule)return c;var B=Object.create(null);if(o.r(B),Object.defineProperty(B,"default",{enumerable:!0,value:c}),2&d&&typeof c!="string")for(var Q in c)o.d(B,Q,function(f){return c[f]}.bind(null,Q));return B},o.n=function(c){var d=c&&c.__esModule?function(){return c.default}:function(){return c};return o.d(d,"a",d),d},o.o=function(c,d){return Object.prototype.hasOwnProperty.call(c,d)},o.p="",o.oe=function(c){throw console.error(c),c};var s=window.webpackJsonpFormantRealtimeSDK=window.webpackJsonpFormantRealtimeSDK||[],g=s.push.bind(s);s.push=t,s=s.slice();for(var l=0;l<s.length;l++)t(s[l]);var u=g;return o(o.s=233)}([function(e,t,n){n.d(t,"a",function(){return V});var r=n(16),o=n(55),s=n(15),g=n.n(s),l=n(18);function u(K,Y){if(Y.length<K)throw new TypeError(K+" argument"+(K>1?"s":"")+" required, but only "+Y.length+" present")}function c(K){if(K===null||K===!0||K===!1)return NaN;var Y=Number(K);return isNaN(Y)?Y:Y<0?Math.ceil(Y):Math.floor(Y)}var d={dateTimeDelimiter:/[T ]/,timeZoneDelimiter:/[Z ]/i,timezone:/([Z+-].*)$/},B=/^-?(?:(\d{3})|(\d{2})(?:-?(\d{2}))?|W(\d{2})(?:-?(\d{1}))?|)$/,Q=/^(\d{2}(?:[.,]\d*)?)(?::?(\d{2}(?:[.,]\d*)?))?(?::?(\d{2}(?:[.,]\d*)?))?$/,f=/^([+-])(\d{2})(?::?(\d{2}))?$/;function p(K){var Y,te={},oe=K.split(d.dateTimeDelimiter);if(oe.length>2)return te;if(/:/.test(oe[0])?Y=oe[0]:(te.date=oe[0],Y=oe[1],d.timeZoneDelimiter.test(te.date)&&(te.date=K.split(d.timeZoneDelimiter)[0],Y=K.substr(te.date.length,K.length))),Y){var ge=d.timezone.exec(Y);ge?(te.time=Y.replace(ge[1],""),te.timezone=ge[1]):te.time=Y}return te}function U(K,Y){var te=new RegExp("^(?:(\\d{4}|[+-]\\d{"+(4+Y)+"})|(\\d{2}|[+-]\\d{"+(2+Y)+"})$)"),oe=K.match(te);if(!oe)return{year:NaN,restDateString:""};var ge=oe[1]?parseInt(oe[1]):null,Se=oe[2]?parseInt(oe[2]):null;return{year:Se===null?ge:100*Se,restDateString:K.slice((oe[1]||oe[2]).length)}}function E(K,Y){if(Y===null)return new Date(NaN);var te=K.match(B);if(!te)return new Date(NaN);var oe=!!te[4],ge=M(te[1]),Se=M(te[2])-1,ve=M(te[3]),ye=M(te[4]),Je=M(te[5])-1;if(oe)return function(be,we,Ze){return we>=1&&we<=53&&Ze>=0&&Ze<=6}(0,ye,Je)?function(be,we,Ze){var Oe=new Date(0);Oe.setUTCFullYear(be,0,4);var it=Oe.getUTCDay()||7,mt=7*(we-1)+Ze+1-it;return Oe.setUTCDate(Oe.getUTCDate()+mt),Oe}(Y,ye,Je):new Date(NaN);var Ee=new Date(0);return function(be,we,Ze){return we>=0&&we<=11&&Ze>=1&&Ze<=(h[we]||(T(be)?29:28))}(Y,Se,ve)&&function(be,we){return we>=1&&we<=(T(be)?366:365)}(Y,ge)?(Ee.setUTCFullYear(Y,Se,Math.max(ge,ve)),Ee):new Date(NaN)}function M(K){return K?parseInt(K):1}function W(K){var Y=K.match(Q);if(!Y)return NaN;var te=y(Y[1]),oe=y(Y[2]),ge=y(Y[3]);return function(Se,ve,ye){return Se===24?ve===0&&ye===0:ye>=0&&ye<60&&ve>=0&&ve<60&&Se>=0&&Se<25}(te,oe,ge)?36e5*te+6e4*oe+1e3*ge:NaN}function y(K){return K&&parseFloat(K.replace(",","."))||0}function m(K){if(K==="Z")return 0;var Y=K.match(f);if(!Y)return 0;var te=Y[1]==="+"?-1:1,oe=parseInt(Y[2]),ge=Y[3]&&parseInt(Y[3])||0;return function(Se,ve){return ve>=0&&ve<=59}(0,ge)?te*(36e5*oe+6e4*ge):NaN}var h=[31,null,31,30,31,30,31,31,30,31,30,31];function T(K){return K%400==0||K%4==0&&K%100!=0}var I=n(40);function X(K){return u(1,arguments),K instanceof Date||Object(I.a)(K)==="object"&&Object.prototype.toString.call(K)==="[object Date]"}function F(K){u(1,arguments);var Y=Object.prototype.toString.call(K);return K instanceof Date||Object(I.a)(K)==="object"&&Y==="[object Date]"?new Date(K.getTime()):typeof K=="number"||Y==="[object Number]"?new Date(K):(typeof K!="string"&&Y!=="[object String]"||typeof console=="undefined"||(console.warn("Starting with v2.0.0-beta.1 date-fns doesn't accept strings as date arguments. Please use `parseISO` to parse strings. See: https://github.com/date-fns/date-fns/blob/master/docs/upgradeGuide.md#string-arguments"),console.warn(new Error().stack)),new Date(NaN))}function R(K){const Y=function(te,oe){var ge;u(1,arguments);var Se=c((ge=oe==null?void 0:oe.additionalDigits)!==null&&ge!==void 0?ge:2);if(Se!==2&&Se!==1&&Se!==0)throw new RangeError("additionalDigits must be 0, 1 or 2");if(typeof te!="string"&&Object.prototype.toString.call(te)!=="[object String]")return new Date(NaN);var ve,ye=p(te);if(ye.date){var Je=U(ye.date,Se);ve=E(Je.restDateString,Je.year)}if(!ve||isNaN(ve.getTime()))return new Date(NaN);var Ee,be=ve.getTime(),we=0;if(ye.time&&(we=W(ye.time),isNaN(we)))return new Date(NaN);if(!ye.timezone){var Ze=new Date(be+we),Oe=new Date(0);return Oe.setFullYear(Ze.getUTCFullYear(),Ze.getUTCMonth(),Ze.getUTCDate()),Oe.setHours(Ze.getUTCHours(),Ze.getUTCMinutes(),Ze.getUTCSeconds(),Ze.getUTCMilliseconds()),Oe}return Ee=m(ye.timezone),isNaN(Ee)?new Date(NaN):new Date(be+we+Ee)}(K);if(!function(te){if(u(1,arguments),!X(te)&&typeof te!="number")return!1;var oe=F(te);return!isNaN(Number(oe))}(Y))throw new Error(`Invalid ISO 8601 date string (${K})`);return Y}const x=Math.pow(2,20),w=x;var _=n(3),j=n(28);function C(K){return g()(K,{cycles:!0})}var J=function(K,Y){var te={};for(var oe in K)Object.prototype.hasOwnProperty.call(K,oe)&&Y.indexOf(oe)<0&&(te[oe]=K[oe]);if(K!=null&&typeof Object.getOwnPropertySymbols=="function"){var ge=0;for(oe=Object.getOwnPropertySymbols(K);ge<oe.length;ge++)Y.indexOf(oe[ge])<0&&Object.prototype.propertyIsEnumerable.call(K,oe[ge])&&(te[oe[ge]]=K[oe[ge]])}return te};function v(K,Y={}){const{redacted:te=!0}=Y,oe=Je=>te?Object(j.a)(Je):Je;if(!K.stack)return{message:C(oe(K))};const{name:ge,message:Se,stack:ve}=K,ye=J(K,["name","message","stack"]);return{name:ge,message:Se!==void 0?Se:C(oe(K)),stack:ve,meta:ye&&Object.keys(ye).length===0?void 0:oe(ye)}}function D(K,Y={}){const{message:te,stack:oe,meta:ge}=v(K,Y);return`${oe||te||""}${ge&&Object.keys(ge).length>0?" -- "+C(ge):""}`}var A=n(236);const b=Object(A.a)();var P=n(14),z=n.n(P),$=function(K,Y,te,oe){return new(te||(te=Promise))(function(ge,Se){function ve(Ee){try{Je(oe.next(Ee))}catch(be){Se(be)}}function ye(Ee){try{Je(oe.throw(Ee))}catch(be){Se(be)}}function Je(Ee){var be;Ee.done?ge(Ee.value):(be=Ee.value,be instanceof te?be:new te(function(we){we(be)})).then(ve,ye)}Je((oe=oe.apply(K,Y||[])).next())})},ee=function(K,Y){var te={};for(var oe in K)Object.prototype.hasOwnProperty.call(K,oe)&&Y.indexOf(oe)<0&&(te[oe]=K[oe]);if(K!=null&&typeof Object.getOwnPropertySymbols=="function"){var ge=0;for(oe=Object.getOwnPropertySymbols(K);ge<oe.length;ge++)Y.indexOf(oe[ge])<0&&Object.prototype.propertyIsEnumerable.call(K,oe[ge])&&(te[oe[ge]]=K[oe[ge]])}return te};class re extends z.a{constructor(Y,te){super(),this.endpoint=Y,this.metadata=te,this.logClient=this.getLogClient()}getLogClient(){return $(this,void 0,void 0,function*(){const{LogClient:Y}=yield Promise.resolve().then(n.bind(null,235));return new Y(this.endpoint)})}log(Y,te){return $(this,void 0,void 0,function*(){const{level:oe,message:ge,error:Se}=Y,ve=ee(Y,["level","message","error"]);this.emit("logged");try{yield(yield this.logClient).log([{timestamp:new Date().toISOString(),level:oe,message:(""+ge).substring(0,1e3),error:Se!==void 0?v(Se):void 0,meta:Object.assign(Object.assign({},ve),this.metadata)}])}catch(ye){console.error("Failed to log to log-api: "+D(ye))}te()})}}var O=function(K,Y){var te={};for(var oe in K)Object.prototype.hasOwnProperty.call(K,oe)&&Y.indexOf(oe)<0&&(te[oe]=K[oe]);if(K!=null&&typeof Object.getOwnPropertySymbols=="function"){var ge=0;for(oe=Object.getOwnPropertySymbols(K);ge<oe.length;ge++)Y.indexOf(oe[ge])<0&&Object.prototype.propertyIsEnumerable.call(K,oe[ge])&&(te[oe[ge]]=K[oe[ge]])}return te};const k={app:_.a,namespace:_.j,buildTag:_.c,instanceId:b},S=_.f?l.format.printf(K=>{var{timestamp:Y,level:te,message:oe,error:ge}=K,Se=O(K,["timestamp","level","message","error"]);const ve=Object.assign(Object.assign({timestamp:Y?R(Y).getTime():new Date().getTime(),level:te.toUpperCase(),message:oe},ge?{error:v(ge)}:{}),{meta:Object.assign(Object.assign({},k),Se)});return g()(ve,{cycles:!0})}):l.format.printf(K=>{var{timestamp:Y,level:te,message:oe,error:ge}=K,Se=O(K,["timestamp","level","message","error"]);let ve=`${Y||new Date().toISOString()} ${te.toUpperCase()}: ${oe} `;return Object.keys(Se).length>0&&(ve+=g()(Se,{cycles:!0})),ge&&(ve+=`
1
+ "use strict";var Rn=Object.defineProperty;var Bn=(e,t,n)=>t in e?Rn(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n;var he=(e,t,n)=>(Bn(e,typeof t!="symbol"?t+"":t,n),n);Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const DEFAULT_FORMANT_API_URL="https://api.formant.io";function whichFormantApiUrl(e,t,n){try{if(t.get("formant_prod"))return"https://api.formant.io";if(t.get("formant_stage"))return"https://api-stage.formant.io";if(t.get("formant_dev"))return"https://api-dev.formant.io";if(t.get("formant_local"))return"https://api.formant.local";if(t.get("formant_url")){const r=t.get("formant_url");if(r!==null)try{return new URL(r).origin}catch{console.warn(`Ignoring malformed \`formant_url\` url parameter: ${r}`)}}if(n){if(n.includes("app-dev.formant.io")||n.includes("localhost"))return"https://api-dev.formant.io";if(n.includes("app-stage.formant.io"))return"https://api-stage.formant.io";if(n.includes("app.formant.io"))return"https://api.formant.io"}}catch{}if(n){if(n.includes("app-dev.formant.io"))return"https://api-dev.formant.io";if(n.includes("app-stage.formant.io"))return"https://api-stage.formant.io";if(n.includes("app.formant.io"))return"https://api.formant.io"}return typeof e!="undefined"&&"FORMANT_API_URL"in e&&typeof e.FORMANT_API_URL=="string"?e.FORMANT_API_URL:DEFAULT_FORMANT_API_URL}exports.FORMANT_API_URL=whichFormantApiUrl(typeof window!="undefined"?window:globalThis,new URLSearchParams(typeof window!="undefined"&&window.location?window.location.search:void 0),typeof window!="undefined"&&window.location?window.location.host:void 0);const setFormantApiUrl=e=>{exports.FORMANT_API_URL=e};function addAccessTokenRefreshListener(e){function t(n){const r=n.data;r.type==="auth_token"&&e(r.token)}return window.addEventListener("message",t),()=>{window.removeEventListener("message",t)}}function getCurrentModuleContext(){return typeof window!="undefined"&&window.location?new URLSearchParams(window.location.search).get("module"):null}function sendAppMessage(e){if(!(window&&window.parent))throw new Error("cannot send message to non-existent parent");window.parent.postMessage(e,"*")}function refreshAuthToken(){const e=getCurrentModuleContext();if(!e)throw new Error("No module context");sendAppMessage({type:"refresh_auth_token",module:e})}var commonjsGlobal=typeof globalThis!="undefined"?globalThis:typeof window!="undefined"?window:typeof global!="undefined"?global:typeof self!="undefined"?self:{};function getDefaultExportFromCjs(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}var base64={exports:{}};/*! https://mths.be/base64 v1.0.0 by @mathias | MIT license */base64.exports;(function(e,t){(function(n){var r=t,o=e&&e.exports==r&&e,s=typeof commonjsGlobal=="object"&&commonjsGlobal;(s.global===s||s.window===s)&&(n=s);var g=function(p){this.message=p};g.prototype=new Error,g.prototype.name="InvalidCharacterError";var l=function(p){throw new g(p)},u="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",c=/[\t\n\f\r ]/g,d=function(p){p=String(p).replace(c,"");var U=p.length;U%4==0&&(p=p.replace(/==?$/,""),U=p.length),(U%4==1||/[^+a-zA-Z0-9/]/.test(p))&&l("Invalid character: the string to be decoded is not correctly encoded.");for(var E=0,M,W,y="",m=-1;++m<U;)W=u.indexOf(p.charAt(m)),M=E%4?M*64+W:W,E++%4&&(y+=String.fromCharCode(255&M>>(-2*E&6)));return y},B=function(p){p=String(p),/[^\0-\xFF]/.test(p)&&l("The string to be encoded contains characters outside of the Latin1 range.");for(var U=p.length%3,E="",M=-1,W,y,m,h,T=p.length-U;++M<T;)W=p.charCodeAt(M)<<16,y=p.charCodeAt(++M)<<8,m=p.charCodeAt(++M),h=W+y+m,E+=u.charAt(h>>18&63)+u.charAt(h>>12&63)+u.charAt(h>>6&63)+u.charAt(h&63);return U==2?(W=p.charCodeAt(M)<<8,y=p.charCodeAt(++M),h=W+y,E+=u.charAt(h>>10)+u.charAt(h>>4&63)+u.charAt(h<<2&63)+"="):U==1&&(h=p.charCodeAt(M),E+=u.charAt(h>>2)+u.charAt(h<<4&63)+"=="),E},Q={encode:B,decode:d,version:"1.0.0"};if(r&&!r.nodeType)if(o)o.exports=Q;else for(var f in Q)Q.hasOwnProperty(f)&&(r[f]=Q[f]);else n.base64=Q})(commonjsGlobal)})(base64,base64.exports);var base64Exports=base64.exports;class LoginFailureError extends Error{constructor(n){super("login failed");he(this,"reason");this.reason=n,this.name="LoginFailureError",Object.setPrototypeOf(this,new.target.prototype)}}class LoginChallengedError extends Error{constructor(n){super("login challenged");he(this,"challenge");this.challenge=n,this.name="LoginChallengedError",Object.setPrototypeOf(this,new.target.prototype)}}class AuthenticationStore{constructor({apiUrl:t,refreshAuthToken:n,addAccessTokenRefreshListener:r}){he(this,"_refreshToken");he(this,"_isShareToken",!1);he(this,"_currentOrganization");he(this,"_currentUser");he(this,"_defaultDeviceId");he(this,"_token");he(this,"_waitingForAuth",new Set);he(this,"_refreshTimer");he(this,"_apiUrl");he(this,"_refreshAuthToken");he(this,"_addAccessTokenRefreshListener");this._apiUrl=t,this._refreshAuthToken=n,this._addAccessTokenRefreshListener=r}set apiUrl(t){this._apiUrl=t,setFormantApiUrl(t)}get apiUrl(){return this._apiUrl}get token(){return this._token}get currentUser(){return this._currentUser}get currentOrganization(){return this._currentOrganization}get defaultDeviceId(){return this._defaultDeviceId}get refreshToken(){return this._refreshToken}get isShareToken(){return this._isShareToken}async login(t,n,r={}){const{advanced:o=!1}=r;try{const s=await fetch(`${this._apiUrl}/v1/admin/auth/login`,{method:"POST",body:JSON.stringify({email:t,password:n}),headers:{"Content-Type":"application/json"}}),g=await s.json();if(s.status!==200)throw new LoginFailureError(g.message);if("challenge"in g)throw new LoginChallengedError(g.challenge);const{authentication:l}=g;return await this.loginWithToken(l.accessToken,l.refreshToken),o?{result:"success",authentication:l}:l}catch(s){if(o||console.error("login() failed",{err:s}),this._waitingForAuth.forEach(g=>g(!1)),this._waitingForAuth.clear(),!o)throw s;return s instanceof LoginChallengedError?{result:"challenged",challenge:s.challenge}:{result:"failure",reason:s instanceof LoginFailureError?s.reason:s instanceof Error?s.message:String(s)}}}async loginWithToken(t,n){var o;const r=JSON.parse(base64Exports.decode(t.split(".")[1]));try{let s;if(this._isShareToken=r["formant:claims"]&&r["formant:claims"].type=="share",r["formant:claims"]&&(this._currentOrganization=r["formant:claims"].organizationId),r["custom:organization_id"]&&(this._currentOrganization=r["custom:organization_id"]),this._isShareToken||(s=r.sub),r["formant:claims"]&&r["formant:claims"].userId&&(s=r["formant:claims"].userId),s&&((o=this._currentUser)==null?void 0:o.id)!==s){const g=await fetch(`${this._apiUrl}/v1/admin/users/${s}`,{method:"GET",headers:{"Content-Type":"application/json",Authorization:"Bearer "+t}}),l=await g.json();if(g.status===404)this._currentUser=void 0;else{if(g.status!==200)throw new Error(l.message);this._currentUser=l}}this._token=t,this._waitingForAuth.forEach(g=>g(!0))}catch(s){console.error("loginWithToken() failed",{err:s}),this._waitingForAuth.forEach(g=>g(!1))}finally{this._waitingForAuth.clear()}n&&(this._refreshToken=n,setInterval(async()=>{if(this._refreshToken){const g=await(await fetch(`${this._apiUrl}/v1/admin/auth/refresh`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({refreshToken:this._refreshToken})})).json();this._token=g.authentication.accessToken}},1e3*60*60))}isAuthenticated(){return this._token!==void 0}async loginToPeer(t,n,r){if((await fetch(`${t}/login`,{method:"POST",body:JSON.stringify({username:n,password:r}),headers:{"Content-Type":"application/json"}})).status!==200)throw new LoginFailureError("Invalid authentication")}getCurrentUser(){return this._currentUser}async waitTilAuthenticated(){return this.token!==void 0?!0:new Promise(t=>{this._waitingForAuth.add(t)})}async listenForRefresh(){const n=()=>{this._refreshTimer=void 0,this._refreshAuthToken()};this._addAccessTokenRefreshListener(r=>{this._refreshTimer&&clearTimeout(this._refreshTimer),this._refreshTimer=setTimeout(n,36e5),this.loginWithToken(r)}),this._refreshTimer=setTimeout(n,36e5)}async forgotPassword(t){await fetch(`${this._apiUrl}/v1/admin/auth/forgot-password`,{method:"POST",body:JSON.stringify({email:t}),headers:{"Content-Type":"application/json"}})}async confirmForgotPassword(t){return(await fetch(`${this._apiUrl}/v1/admin/auth/confirm-forgot-password`,{method:"POST",body:JSON.stringify(t),headers:{"Content-Type":"application/json"}})).ok}async respondToNewPasswordRequiredChallenge(t){const n=await fetch(`${this._apiUrl}/v1/admin/auth/respond-to-new-password-required-challenge`,{method:"POST",body:JSON.stringify(t),headers:{"Content-Type":"application/json"}});if(n.ok)return await n.json();throw new Error("respond-to-new-password-required-challenge failed")}async loginWithGoogle(t){return await(await fetch(`${this._apiUrl}/v1/admin/auth/login-google`,{method:"POST",body:JSON.stringify(t),headers:{"Content-Type":"application/json"}})).json()}async refresh(t){const r=await(await fetch(`${this._apiUrl}/v1/admin/auth/refresh`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({refreshToken:t})})).json();await this.loginWithToken(r.authentication.accessToken,t)}async checkSso(t,n){return await(await fetch(`${this._apiUrl}/v1/admin/auth/check-sso`,{method:"POST",body:JSON.stringify({email:t,allowUserAutoCreation:n}),headers:{"Content-Type":"application/json"}})).json()}async loginWithSso(t,n){const o=await(await fetch(`${this._apiUrl}/v1/admin/auth/login-sso`,{method:"POST",body:JSON.stringify({token:t,refreshToken:n}),headers:{"Content-Type":"application/json"}})).json();if(!o.authentication)throw new Error("Failed to login with SSO");return await this.loginWithToken(o.authentication.accessToken,o.authentication.refreshToken)}}const Authentication=new AuthenticationStore({apiUrl:exports.FORMANT_API_URL,refreshAuthToken,addAccessTokenRefreshListener});class Account{static async listAccounts(){if(!Authentication.token)throw new Error("Not authenticated");return(await(await fetch(`${exports.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(`${exports.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(`${exports.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(`${exports.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(`${exports.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(`${exports.FORMANT_API_URL}/v1/admin/accounts/${t}/tree`,{method:"GET",headers:{"Content-Type":"application/json",Authorization:"Bearer "+Authentication.token}})).json()}}async function getModuleConfiguration(e){return(await(await fetch(`${exports.FORMANT_API_URL}/v1/admin/module-configurations/${e}`,{headers:{"Content-Type":"application/json",Authorization:"Bearer "+Authentication.token}})).json()).configuration}function disableAnalyticsBottomBar(){sendAppMessage({type:"hide_analytics_date_picker"})}function goToDevice(e){sendAppMessage({type:"go_to_device",deviceId:e})}function goToTime(e){sendAppMessage({type:"go_to_time",time:e.getTime()})}function requestModuleData(){const e=getCurrentModuleContext();if(!e)throw new Error("No module context");sendAppMessage({type:"request_module_data",module:e})}function sendChannelData(e,t){const n=getCurrentModuleContext();if(!n)throw new Error("No module context");sendAppMessage({type:"send_channel_data",source:n,channel:e,data:t})}function setModuleDateTimeRange(e,t){const n=getCurrentModuleContext();if(!n)throw new Error("No module context");sendAppMessage({type:"set_module_data_time_range",module:n,before:e,after:t||0})}function setupModuleMenus(e){const t=getCurrentModuleContext();if(!t)throw new Error("No module context");sendAppMessage({type:"setup_module_menus",module:t,menus:e})}function showMessage(e){sendAppMessage({type:"show_message",message:e})}function addChannelDataListener(e,t){const n=r=>{const o=r.data;o.type==="channel_data"&&o.channel===e&&t({source:o.source,data:o.data})};return window.addEventListener("message",n),()=>window.removeEventListener("message",n)}function addMenuListener(e){const t=n=>{const r=n.data;r.type==="module_menu_item_clicked"&&e(r.menu)};return window.addEventListener("message",t),()=>window.removeEventListener("message",t)}function addModuleConfigurationListener(e){const t=n=>{const r=n.data;r.type==="module_configuration"&&e(r)};return window.addEventListener("message",t),()=>window.removeEventListener("message",t)}function addModuleDataListener(e){const t=getCurrentModuleContext();t&&sendAppMessage({type:"request_module_data",module:t});const n=r=>{const o=r.data;o.type==="module_data"&&e({streams:o.streams,time:o.time,queryRange:o.queryRange})};return window.addEventListener("message",n),()=>window.removeEventListener("message",n)}function addOverviewDeviceListener(e){sendAppMessage({type:"request_devices"});const t=n=>{const r=n.data;r.type==="overview_devices"&&e(r.data)};return window.addEventListener("message",t),()=>window.removeEventListener("message",t)}function _typeof(e){return _typeof=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(t){return typeof t}:function(t){return t&&typeof Symbol=="function"&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},_typeof(e)}function toInteger(e){if(e===null||e===!0||e===!1)return NaN;var t=Number(e);return isNaN(t)?t:t<0?Math.ceil(t):Math.floor(t)}function requiredArgs(e,t){if(t.length<e)throw new TypeError(e+" argument"+(e>1?"s":"")+" required, but only "+t.length+" present")}function toDate(e){requiredArgs(1,arguments);var t=Object.prototype.toString.call(e);return e instanceof Date||_typeof(e)==="object"&&t==="[object Date]"?new Date(e.getTime()):typeof e=="number"||t==="[object Number]"?new Date(e):((typeof e=="string"||t==="[object String]")&&typeof console!="undefined"&&(console.warn("Starting with v2.0.0-beta.1 date-fns doesn't accept strings as date arguments. Please use `parseISO` to parse strings. See: https://github.com/date-fns/date-fns/blob/master/docs/upgradeGuide.md#string-arguments"),console.warn(new Error().stack)),new Date(NaN))}function addDays(e,t){requiredArgs(2,arguments);var n=toDate(e),r=toInteger(t);return isNaN(r)?new Date(NaN):(r&&n.setDate(n.getDate()+r),n)}function addMonths(e,t){requiredArgs(2,arguments);var n=toDate(e),r=toInteger(t);if(isNaN(r))return new Date(NaN);if(!r)return n;var o=n.getDate(),s=new Date(n.getTime());s.setMonth(n.getMonth()+r+1,0);var g=s.getDate();return o>=g?s:(n.setFullYear(s.getFullYear(),s.getMonth(),o),n)}function addMilliseconds(e,t){requiredArgs(2,arguments);var n=toDate(e).getTime(),r=toInteger(t);return new Date(n+r)}var MILLISECONDS_IN_HOUR=36e5;function addHours(e,t){requiredArgs(2,arguments);var n=toInteger(t);return addMilliseconds(e,n*MILLISECONDS_IN_HOUR)}var defaultOptions={};function getDefaultOptions(){return defaultOptions}function startOfWeek(e,t){var n,r,o,s,g,l,u,c;requiredArgs(1,arguments);var d=getDefaultOptions(),B=toInteger((n=(r=(o=(s=t==null?void 0:t.weekStartsOn)!==null&&s!==void 0?s:t==null||(g=t.locale)===null||g===void 0||(l=g.options)===null||l===void 0?void 0:l.weekStartsOn)!==null&&o!==void 0?o:d.weekStartsOn)!==null&&r!==void 0?r:(u=d.locale)===null||u===void 0||(c=u.options)===null||c===void 0?void 0:c.weekStartsOn)!==null&&n!==void 0?n:0);if(!(B>=0&&B<=6))throw new RangeError("weekStartsOn must be between 0 and 6 inclusively");var Q=toDate(e),f=Q.getDay(),p=(f<B?7:0)+f-B;return Q.setDate(Q.getDate()-p),Q.setHours(0,0,0,0),Q}function startOfDay(e){requiredArgs(1,arguments);var t=toDate(e);return t.setHours(0,0,0,0),t}var MILLISECONDS_IN_MINUTE=6e4;function addMinutes(e,t){requiredArgs(2,arguments);var n=toInteger(t);return addMilliseconds(e,n*MILLISECONDS_IN_MINUTE)}function addQuarters(e,t){requiredArgs(2,arguments);var n=toInteger(t),r=n*3;return addMonths(e,r)}function addSeconds(e,t){requiredArgs(2,arguments);var n=toInteger(t);return addMilliseconds(e,n*1e3)}function addWeeks(e,t){requiredArgs(2,arguments);var n=toInteger(t),r=n*7;return addDays(e,r)}function addYears(e,t){requiredArgs(2,arguments);var n=toInteger(t);return addMonths(e,n*12)}function getQuarter(e){requiredArgs(1,arguments);var t=toDate(e),n=Math.floor(t.getMonth()/3)+1;return n}var roundingMap={ceil:Math.ceil,round:Math.round,floor:Math.floor,trunc:function(t){return t<0?Math.ceil(t):Math.floor(t)}},defaultRoundingMethod="trunc";function getRoundingMethod(e){return e?roundingMap[e]:roundingMap[defaultRoundingMethod]}function endOfDay(e){requiredArgs(1,arguments);var t=toDate(e);return t.setHours(23,59,59,999),t}function endOfMonth(e){requiredArgs(1,arguments);var t=toDate(e),n=t.getMonth();return t.setFullYear(t.getFullYear(),n+1,0),t.setHours(23,59,59,999),t}function eachDayOfInterval(e,t){var n;requiredArgs(1,arguments);var r=e||{},o=toDate(r.start),s=toDate(r.end),g=s.getTime();if(!(o.getTime()<=g))throw new RangeError("Invalid interval");var l=[],u=o;u.setHours(0,0,0,0);var c=Number((n=t==null?void 0:t.step)!==null&&n!==void 0?n:1);if(c<1||isNaN(c))throw new RangeError("`options.step` must be a number greater than 1");for(;u.getTime()<=g;)l.push(toDate(u)),u.setDate(u.getDate()+c),u.setHours(0,0,0,0);return l}function eachHourOfInterval(e,t){var n;requiredArgs(1,arguments);var r=e||{},o=toDate(r.start),s=toDate(r.end),g=o.getTime(),l=s.getTime();if(!(g<=l))throw new RangeError("Invalid interval");var u=[],c=o;c.setMinutes(0,0,0);var d=Number((n=t==null?void 0:t.step)!==null&&n!==void 0?n:1);if(d<1||isNaN(d))throw new RangeError("`options.step` must be a number greater than 1");for(;c.getTime()<=l;)u.push(toDate(c)),c=addHours(c,d);return u}function startOfMinute(e){requiredArgs(1,arguments);var t=toDate(e);return t.setSeconds(0,0),t}function eachMinuteOfInterval(e,t){var n;requiredArgs(1,arguments);var r=startOfMinute(toDate(e.start)),o=toDate(e.end),s=r.getTime(),g=o.getTime();if(s>=g)throw new RangeError("Invalid interval");var l=[],u=r,c=Number((n=t==null?void 0:t.step)!==null&&n!==void 0?n:1);if(c<1||isNaN(c))throw new RangeError("`options.step` must be a number equal to or greater than 1");for(;u.getTime()<=g;)l.push(toDate(u)),u=addMinutes(u,c);return l}function eachMonthOfInterval(e){requiredArgs(1,arguments);var t=e||{},n=toDate(t.start),r=toDate(t.end),o=r.getTime(),s=[];if(!(n.getTime()<=o))throw new RangeError("Invalid interval");var g=n;for(g.setHours(0,0,0,0),g.setDate(1);g.getTime()<=o;)s.push(toDate(g)),g.setMonth(g.getMonth()+1);return s}function startOfQuarter(e){requiredArgs(1,arguments);var t=toDate(e),n=t.getMonth(),r=n-n%3;return t.setMonth(r,1),t.setHours(0,0,0,0),t}function eachQuarterOfInterval(e){requiredArgs(1,arguments);var t=e||{},n=toDate(t.start),r=toDate(t.end),o=r.getTime();if(!(n.getTime()<=o))throw new RangeError("Invalid interval");var s=startOfQuarter(n),g=startOfQuarter(r);o=g.getTime();for(var l=[],u=s;u.getTime()<=o;)l.push(toDate(u)),u=addQuarters(u,1);return l}function eachWeekOfInterval(e,t){requiredArgs(1,arguments);var n=e||{},r=toDate(n.start),o=toDate(n.end),s=o.getTime();if(!(r.getTime()<=s))throw new RangeError("Invalid interval");var g=startOfWeek(r,t),l=startOfWeek(o,t);g.setHours(15),l.setHours(15),s=l.getTime();for(var u=[],c=g;c.getTime()<=s;)c.setHours(0),u.push(toDate(c)),c=addWeeks(c,1),c.setHours(15);return u}function startOfMonth(e){requiredArgs(1,arguments);var t=toDate(e);return t.setDate(1),t.setHours(0,0,0,0),t}function endOfYear(e){requiredArgs(1,arguments);var t=toDate(e),n=t.getFullYear();return t.setFullYear(n+1,0,0),t.setHours(23,59,59,999),t}function startOfYear(e){requiredArgs(1,arguments);var t=toDate(e),n=new Date(0);return n.setFullYear(t.getFullYear(),0,1),n.setHours(0,0,0,0),n}function eachYearOfInterval(e){requiredArgs(1,arguments);var t=e||{},n=toDate(t.start),r=toDate(t.end),o=r.getTime();if(!(n.getTime()<=o))throw new RangeError("Invalid interval");var s=[],g=n;for(g.setHours(0,0,0,0),g.setMonth(0,1);g.getTime()<=o;)s.push(toDate(g)),g.setFullYear(g.getFullYear()+1);return s}function endOfHour(e){requiredArgs(1,arguments);var t=toDate(e);return t.setMinutes(59,59,999),t}function endOfWeek(e,t){var n,r,o,s,g,l,u,c;requiredArgs(1,arguments);var d=getDefaultOptions(),B=toInteger((n=(r=(o=(s=t==null?void 0:t.weekStartsOn)!==null&&s!==void 0?s:t==null||(g=t.locale)===null||g===void 0||(l=g.options)===null||l===void 0?void 0:l.weekStartsOn)!==null&&o!==void 0?o:d.weekStartsOn)!==null&&r!==void 0?r:(u=d.locale)===null||u===void 0||(c=u.options)===null||c===void 0?void 0:c.weekStartsOn)!==null&&n!==void 0?n:0);if(!(B>=0&&B<=6))throw new RangeError("weekStartsOn must be between 0 and 6 inclusively");var Q=toDate(e),f=Q.getDay(),p=(f<B?-7:0)+6-(f-B);return Q.setDate(Q.getDate()+p),Q.setHours(23,59,59,999),Q}function endOfMinute(e){requiredArgs(1,arguments);var t=toDate(e);return t.setSeconds(59,999),t}function endOfQuarter(e){requiredArgs(1,arguments);var t=toDate(e),n=t.getMonth(),r=n-n%3+3;return t.setMonth(r,0),t.setHours(23,59,59,999),t}function getDay(e){requiredArgs(1,arguments);var t=toDate(e),n=t.getDay();return n}function getHours(e){requiredArgs(1,arguments);var t=toDate(e),n=t.getHours();return n}function getMinutes(e){requiredArgs(1,arguments);var t=toDate(e),n=t.getMinutes();return n}function getMonth(e){requiredArgs(1,arguments);var t=toDate(e),n=t.getMonth();return n}function getWeekYear(e,t){var n,r,o,s,g,l,u,c;requiredArgs(1,arguments);var d=toDate(e),B=d.getFullYear(),Q=getDefaultOptions(),f=toInteger((n=(r=(o=(s=t==null?void 0:t.firstWeekContainsDate)!==null&&s!==void 0?s:t==null||(g=t.locale)===null||g===void 0||(l=g.options)===null||l===void 0?void 0:l.firstWeekContainsDate)!==null&&o!==void 0?o:Q.firstWeekContainsDate)!==null&&r!==void 0?r:(u=Q.locale)===null||u===void 0||(c=u.options)===null||c===void 0?void 0:c.firstWeekContainsDate)!==null&&n!==void 0?n:1);if(!(f>=1&&f<=7))throw new RangeError("firstWeekContainsDate must be between 1 and 7 inclusively");var p=new Date(0);p.setFullYear(B+1,0,f),p.setHours(0,0,0,0);var U=startOfWeek(p,t),E=new Date(0);E.setFullYear(B,0,f),E.setHours(0,0,0,0);var M=startOfWeek(E,t);return d.getTime()>=U.getTime()?B+1:d.getTime()>=M.getTime()?B:B-1}function startOfWeekYear(e,t){var n,r,o,s,g,l,u,c;requiredArgs(1,arguments);var d=getDefaultOptions(),B=toInteger((n=(r=(o=(s=t==null?void 0:t.firstWeekContainsDate)!==null&&s!==void 0?s:t==null||(g=t.locale)===null||g===void 0||(l=g.options)===null||l===void 0?void 0:l.firstWeekContainsDate)!==null&&o!==void 0?o:d.firstWeekContainsDate)!==null&&r!==void 0?r:(u=d.locale)===null||u===void 0||(c=u.options)===null||c===void 0?void 0:c.firstWeekContainsDate)!==null&&n!==void 0?n:1),Q=getWeekYear(e,t),f=new Date(0);f.setFullYear(Q,0,B),f.setHours(0,0,0,0);var p=startOfWeek(f,t);return p}var MILLISECONDS_IN_WEEK=6048e5;function getWeek(e,t){requiredArgs(1,arguments);var n=toDate(e),r=startOfWeek(n,t).getTime()-startOfWeekYear(n,t).getTime();return Math.round(r/MILLISECONDS_IN_WEEK)+1}function getYear(e){return requiredArgs(1,arguments),toDate(e).getFullYear()}function startOfHour(e){requiredArgs(1,arguments);var t=toDate(e);return t.setMinutes(0,0,0),t}function subDays(e,t){requiredArgs(2,arguments);var n=toInteger(t);return addDays(e,-n)}function roundToNearestMinutes(e,t){var n;if(arguments.length<1)throw new TypeError("1 argument required, but only none provided present");var r=toInteger((n=t==null?void 0:t.nearestTo)!==null&&n!==void 0?n:1);if(r<1||r>30)throw new RangeError("`options.nearestTo` must be between 1 and 30");var o=toDate(e),s=o.getSeconds(),g=o.getMinutes()+s/60,l=getRoundingMethod(t==null?void 0:t.roundingMethod),u=l(g/r)*r,c=g%r,d=Math.round(c/r)*r;return new Date(o.getFullYear(),o.getMonth(),o.getDate(),o.getHours(),u+d)}function subMonths(e,t){requiredArgs(2,arguments);var n=toInteger(t);return addMonths(e,-n)}function subHours(e,t){requiredArgs(2,arguments);var n=toInteger(t);return addHours(e,-n)}function subMinutes(e,t){requiredArgs(2,arguments);var n=toInteger(t);return addMinutes(e,-n)}function subQuarters(e,t){requiredArgs(2,arguments);var n=toInteger(t);return addQuarters(e,-n)}function subWeeks(e,t){requiredArgs(2,arguments);var n=toInteger(t);return addWeeks(e,-n)}function subYears(e,t){requiredArgs(2,arguments);var n=toInteger(t);return addYears(e,-n)}const millisecond$2=1,second$2=1e3,minute$2=60*second$2,hour$2=60*minute$2,day$2=24*hour$2,week$2=7*day$2,month$2=30*day$2,year$2=365*day$2,duration$2={millisecond:millisecond$2,second:second$2,minute:minute$2,hour:hour$2,day:day$2,week:week$2,month:month$2,year:year$2};function filterDataByType$1(e,t){return e.filter(n=>t.includes(n.type))}function filterDataByTime$1(e,t,n){const r=t.getTime(),o=n.getTime();return e.map(s=>({...s,points:s.points.filter(([g])=>g>=r&&g<o)})).filter(({points:s})=>s.length>0)}let StoreCache$1=class{constructor({capacity:t,timeout:n}={}){he(this,"entries",new Map);he(this,"metadata",new Map);he(this,"capacity");he(this,"staleIntervalMs");this.capacity=t||1e4,this.staleIntervalMs=n||duration$2.minute}get(t,n){const r=this.keyToCacheKey(t);return this.isStale(r)&&!this.isGenerating(r)&&n&&this.generate(t,n),this.entries.get(r)}set(t,n){const r=this.keyToCacheKey(t);this.metadata.set(r,{generating:!1,staleAt:performance.now()+this.staleIntervalMs});const o=this.entries.get(r);JSON.stringify(o)===JSON.stringify(n)||(this.entries.set(r,n),this.enforceMaxSize())}clear(){this.entries.clear(),[...this.metadata.values()].forEach(t=>t.generating=!1)}clearKey(t){this.metadata.delete(t),this.entries.delete(t)}keyToCacheKey(t){return JSON.stringify(t)}enforceMaxSize(){for(;this.metadata.size>this.capacity&&this.metadata.size>0;){const[t]=[...this.metadata.entries()].reduce(([n,r],[o,s])=>s.staleAt<r.staleAt?[o,s]:[n,r]);this.clearKey(t)}}isStale(t){const n=this.metadata.get(t);return n?(n==null?void 0:n.staleAt)<performance.now():!0}isGenerating(t){const n=this.metadata.get(t);return n?n.generating:!1}generate(t,n){const r=this.keyToCacheKey(t),o=this.metadata.get(r)||{},s=n().then(g=>{const l=this.metadata.get(r);return(l==null?void 0:l.generating)!==s||this.set(t,g),g}).catch(g=>{throw this.metadata.delete(r),g});this.metadata.set(r,{...o,generating:s,staleAt:performance.now()+this.staleIntervalMs})}};async function queryTelemetry(e){if(!Authentication.token)throw new Error("Not authenticated");return(await(await fetch(`${exports.FORMANT_API_URL}/v1/queries/queries`,{method:"POST",body:JSON.stringify(e),headers:{"Content-Type":"application/json",Authorization:"Bearer "+Authentication.token}})).json()).items}let QueryStore$1=class{constructor(){he(this,"queryStoreCache",new StoreCache$1({capacity:1e4,timeout:20*duration$2.second}));he(this,"liveQueryStoreCache",new StoreCache$1({capacity:1e4,timeout:200*duration$2.millisecond}))}moduleQuery(t,n,r,o,s,g=!1){const l={...t,names:[...n],types:[...r]},u=this.query(l,o,s,g);return u===void 0||u==="too much data"?u:filterDataByType$1(u,r)}query(t,n,r,o=!1){const s={...t,start:startOfMinute(n).toISOString(),end:o?r.toISOString():addMinutes(roundToNearestMinutes(r),1).toISOString(),latestOnly:o},g=r>addSeconds(new Date,-20);let l;return g?l=this.liveQueryCache(s):l=this.queryCache(s),!l||l==="too much data"||o?l:filterDataByTime$1(l,n,r)}queryCache(t){return this.queryStoreCache.get(t,async()=>{try{return await queryTelemetry(t)}catch(n){throw n}})}liveQueryCache(t){return this.liveQueryStoreCache.get(t,async()=>{try{return await queryTelemetry(t)}catch(n){throw n}})}};const queryStore=new QueryStore$1;function addStreamListener(e,t,n){const r=o=>{const s=o.data;if(s.type==="module_data"){const{start:g,end:l}=s.queryRange;n(queryStore.moduleQuery({},e,t,new Date(g),new Date(l),!1))}};return window.addEventListener("message",r),()=>window.removeEventListener("message",r)}async function getDate(e,t,n){return new Promise(r=>{sendAppMessage({type:"request_date",minTime:t,maxTime:n,time:e});const o=s=>{const g=s.data;g.type==="date_response"&&(window.removeEventListener("message",o),r(g.data))};window.addEventListener("message",o)})}async function prompt(e,t){return new Promise(n=>{const r=Math.random().toString();sendAppMessage({type:"prompt",promptId:r,schema:e,okText:t==null?void 0:t.okText,cancelText:t==null?void 0:t.cancelText});const o=s=>{const g=s.data;g.type==="prompt_response"&&g.promptId===r&&n(g.data),window.removeEventListener("message",o)};window.addEventListener("message",o)})}const Yt=class{static isModule(){return getCurrentModuleContext()!==null}static async getCurrentModuleConfiguration(){let t=new URLSearchParams("");typeof window!="undefined"&&window.location&&(t=new URLSearchParams(window.location.search));const n=t.get("configuration");if(!(n===null||n.trim()===""))return getModuleConfiguration(n.trim())}static get isOnline(){return Yt._isOnline}static listenForConnectionEvents(){const t=n=>{const{data:r}=n;r.type==="formant_online"&&(this._isOnline=r.online)};return window.addEventListener("message",t),()=>window.removeEventListener("message",t)}static checkConnection(t=1e3){return new Promise((n,r)=>{const o=setTimeout(()=>r(new Error("deadline expired: took too long")),t),s=g=>{window.removeEventListener("message",s),clearTimeout(o);const{data:l}=g;l.type==="formant_online"&&(this._isOnline=l.online,n(l.online))};window.addEventListener("message",s),sendAppMessage({type:"formant_online"})})}static waitForConnection(t=5e3){let n=!1;const r=new Promise((g,l)=>{setTimeout(()=>{n=!0,l(new Error("deadline expired: took too long"))},t)}),o=g=>new Promise(l=>setTimeout(l,g)),s=async()=>{for(await o(50);!n&&!(this.isOnline||await this.checkConnection);)await o(500)};return Promise.race([r,s()])}};let App=Yt;he(App,"getCurrentModuleContext",getCurrentModuleContext),he(App,"disableAnalyticsBottomBar",disableAnalyticsBottomBar),he(App,"goToDevice",goToDevice),he(App,"goToTime",goToTime),he(App,"refreshAuthToken",refreshAuthToken),he(App,"requestModuleData",requestModuleData),he(App,"sendChannelData",sendChannelData),he(App,"setModuleDateTimeRange",setModuleDateTimeRange),he(App,"setupModuleMenus",setupModuleMenus),he(App,"showMessage",showMessage),he(App,"addAccessTokenRefreshListener",addAccessTokenRefreshListener),he(App,"addChannelDataListener",addChannelDataListener),he(App,"addMenuListener",addMenuListener),he(App,"addModuleConfigurationListener",addModuleConfigurationListener),he(App,"addModuleDataListener",addModuleDataListener),he(App,"addOverviewDeviceListener",addOverviewDeviceListener),he(App,"addStreamListener",addStreamListener),he(App,"getDate",getDate),he(App,"prompt",prompt),he(App,"_isOnline",null);function stringToArrayBuffer(e){return Uint8Array.from(base64Exports.decode(e),t=>t.charCodeAt(0))}function fork$1(e){}function browser(){const{userAgent:e}=navigator;return e?e.includes("Firefox/")?"Firefox":e.includes("Edg/")?"Edge":e.includes("Chrome/")?"Chrome":e.includes("Safari/")?"Safari":e.includes("MSIE/")||e.includes("Trident/")?"IE":"Other":"Other"}const rtcAudioChunkStreamType="audio-chunk";class AudioPlayer{constructor(t,n){he(this,"muted",!1);he(this,"hasReceivedData",!1);he(this,"audioContext");he(this,"chunks",[]);he(this,"isPlaying",!1);he(this,"startTime",0);he(this,"lastChunkOffset",0);he(this,"bufferSize",3);he(this,"receive",async t=>{var g;const n=(g=t.payload.audioChunk)==null?void 0:g.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 s=stringToArrayBuffer(n);try{await r.decodeAudioData(s.buffer,this.scheduleChunk)}catch(l){console.warn("Error decoding audio buffer, changing audioWireFormat on agent",{error:l}),this.changeAudioWireFormat("wav")}});he(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,s)=>{this.receive(s)}),browser()==="Safari"||browser()==="IE"?this.changeAudioWireFormat("wav"):this.changeAudioWireFormat("opus");const r=window.AudioContext||window.webkitAudioContext;this.audioContext=new r}async play(){var t,n;((t=this.audioContext)==null?void 0:t.state)==="suspended"&&await((n=this.audioContext)==null?void 0:n.resume()),this.muted=!1}async pause(){await this.audioContext.suspend(),this.muted=!0}destroy(){this.device.stopListeningToRealtimeDataStream(this.stream)}createChunk(t){const{audioContext:n}=this;if(!n)return;const r=n.createBufferSource();return r.buffer=t,r.connect(n.destination),r.loop=!1,r.onended=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 CaptureStream{constructor(t){he(this,"token");this.captureSession=t}async ingestJSON(t){if(!this.token){const r=await(await fetch(`${exports.FORMANT_API_URL}/v1/admin/capture-sessions/${this.captureSession.code}/authenticate`,{method:"POST"})).json();this.token=r.token}await fetch(`${exports.FORMANT_API_URL}/v1/ingest`,{method:"POST",body:JSON.stringify({deviceId:this.captureSession.deviceId,name:this.captureSession.streamName,type:"json",points:[[Date.now(),JSON.stringify(t)]]}),headers:{"Content-Type":"application/json",Authorization:"Bearer "+this.token}})}}class DataChannel{constructor(t){he(this,"ready",!1);he(this,"listeners",[]);he(this,"openListeners",[]);he(this,"closeListeners",[]);he(this,"errorListeners",[]);he(this,"binaryListeners",[]);he(this,"error");he(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),s=this.decoder.decode(o);r(s)}),this.binaryListeners.forEach(r=>{r(new Uint8Array(n.data))})}}setReady(){this.ready=!0,this.openListeners.forEach(t=>t())}addOpenListener(t){this.openListeners.push(t)}removeOpenListener(t){this.openListeners=this.openListeners.filter(n=>n!==t)}addCloseListener(t){this.closeListeners.push(t)}removeCloseListener(t){this.closeListeners=this.closeListeners.filter(n=>n!==t)}addErrorListener(t){this.errorListeners.push(t)}removeErrorListener(t){this.errorListeners=this.errorListeners.filter(n=>n!==t)}async waitTilReady(){return this.ready?!0:new Promise((n,r)=>{let 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)}}function defined$1(e,t){if(e!==void 0)return e;throw new Error(t||"Value is undefined")}function notNull(e,t){if(e!==null)return e;throw new Error(t||"Value is null")}function definedAndNotNull(e,t){return notNull(defined$1(e,t),t)}function delay(e){return new Promise(t=>setTimeout(t,e))}async function createDevice(e){if(!Authentication.token)throw new Error("Not authenticated");return await(await fetch(`${exports.FORMANT_API_URL}/v1/admin/devices`,{method:"POST",body:JSON.stringify(e),headers:{"Content-Type":"application/json",Authorization:"Bearer "+Authentication.token}})).json()}/*! 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,s=t.stat_desc.has_stree,g=t.stat_desc.extra_bits,l=t.stat_desc.extra_base,u=t.stat_desc.max_length;let c,d,B,Q,f,p,U=0;for(Q=0;Q<=MAX_BITS$1;Q++)e.bl_count[Q]=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],Q=n[n[d*2+1]*2+1]+1,Q>u&&(Q=u,U++),n[d*2+1]=Q,!(d>r)&&(e.bl_count[Q]++,f=0,d>=l&&(f=g[d-l]),p=n[d*2],e.opt_len+=p*(Q+f),s&&(e.static_len+=p*(o[d*2+1]+f)));if(U!==0){do{for(Q=u-1;e.bl_count[Q]===0;)Q--;e.bl_count[Q]--,e.bl_count[Q+1]+=2,e.bl_count[u]--,U-=2}while(U>0);for(Q=u;Q!==0;Q--)for(d=e.bl_count[Q];d!==0;)B=e.heap[--c],!(B>r)&&(n[B*2+1]!==Q&&(e.opt_len+=(Q-n[B*2+1])*n[B*2],n[B*2+1]=Q),d--)}},gen_codes=(e,t,n)=>{const r=new Array(MAX_BITS$1+1);let o=0,s,g;for(s=1;s<=MAX_BITS$1;s++)o=o+n[s-1]<<1,r[s]=o;for(g=0;g<=t;g++){let l=e[g*2+1];l!==0&&(e[g*2]=bi_reverse(r[l]++,l))}},tr_static_init=()=>{let e,t,n,r,o;const s=new Array(MAX_BITS$1+1);for(n=0,r=0;r<LENGTH_CODES$1-1;r++)for(base_length[r]=n,e=0;e<1<<extra_lbits[r];e++)_length_code[n++]=r;for(_length_code[n-1]=r,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++)s[t]=0;for(e=0;e<=143;)static_ltree[e*2+1]=8,e++,s[8]++;for(;e<=255;)static_ltree[e*2+1]=9,e++,s[9]++;for(;e<=279;)static_ltree[e*2+1]=7,e++,s[7]++;for(;e<=287;)static_ltree[e*2+1]=8,e++,s[8]++;for(gen_codes(static_ltree,L_CODES$1+1,s),e=0;e<D_CODES$1;e++)static_dtree[e*2+1]=5,static_dtree[e*2]=bi_reverse(e,5);static_l_desc=new StaticTreeDesc(static_ltree,extra_lbits,LITERALS$1+1,L_CODES$1,MAX_BITS$1),static_d_desc=new StaticTreeDesc(static_dtree,extra_dbits,0,D_CODES$1,MAX_BITS$1),static_bl_desc=new StaticTreeDesc(new Array(0),extra_blbits,0,BL_CODES$1,MAX_BL_BITS)},init_block=e=>{let t;for(t=0;t<L_CODES$1;t++)e.dyn_ltree[t*2]=0;for(t=0;t<D_CODES$1;t++)e.dyn_dtree[t*2]=0;for(t=0;t<BL_CODES$1;t++)e.bl_tree[t*2]=0;e.dyn_ltree[END_BLOCK*2]=1,e.opt_len=e.static_len=0,e.sym_next=e.matches=0},bi_windup=e=>{e.bi_valid>8?put_short(e,e.bi_buf):e.bi_valid>0&&(e.pending_buf[e.pending++]=e.bi_buf),e.bi_buf=0,e.bi_valid=0},smaller=(e,t,n,r)=>{const o=t*2,s=n*2;return e[o]<e[s]||e[o]===e[s]&&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,s=0,g,l;if(e.sym_next!==0)do r=e.pending_buf[e.sym_buf+s++]&255,r+=(e.pending_buf[e.sym_buf+s++]&255)<<8,o=e.pending_buf[e.sym_buf+s++],r===0?send_code(e,o,t):(g=_length_code[o],send_code(e,g+LITERALS$1+1,t),l=extra_lbits[g],l!==0&&(o-=base_length[g],send_bits(e,o,l)),r--,g=d_code(r),send_code(e,g,n),l=extra_dbits[g],l!==0&&(r-=base_dist[g],send_bits(e,r,l)));while(s<e.sym_next);send_code(e,END_BLOCK,t)},build_tree=(e,t)=>{const n=t.dyn_tree,r=t.stat_desc.static_tree,o=t.stat_desc.has_stree,s=t.stat_desc.elems;let g,l,u=-1,c;for(e.heap_len=0,e.heap_max=HEAP_SIZE$1,g=0;g<s;g++)n[g*2]!==0?(e.heap[++e.heap_len]=u=g,e.depth[g]=0):n[g*2+1]=0;for(;e.heap_len<2;)c=e.heap[++e.heap_len]=u<2?++u:0,n[c*2]=1,e.depth[c]=0,e.opt_len--,o&&(e.static_len-=r[c*2+1]);for(t.max_code=u,g=e.heap_len>>1;g>=1;g--)pqdownheap(e,n,g);c=s;do g=e.heap[1],e.heap[1]=e.heap[e.heap_len--],pqdownheap(e,n,1),l=e.heap[1],e.heap[--e.heap_max]=g,e.heap[--e.heap_max]=l,n[c*2]=n[g*2]+n[l*2],e.depth[c]=(e.depth[g]>=e.depth[l]?e.depth[g]:e.depth[l])+1,n[g*2+1]=n[l*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,u,e.bl_count)},scan_tree=(e,t,n)=>{let r,o=-1,s,g=t[0*2+1],l=0,u=7,c=4;for(g===0&&(u=138,c=3),t[(n+1)*2+1]=65535,r=0;r<=n;r++)s=g,g=t[(r+1)*2+1],!(++l<u&&s===g)&&(l<c?e.bl_tree[s*2]+=l:s!==0?(s!==o&&e.bl_tree[s*2]++,e.bl_tree[REP_3_6*2]++):l<=10?e.bl_tree[REPZ_3_10*2]++:e.bl_tree[REPZ_11_138*2]++,l=0,o=s,g===0?(u=138,c=3):s===g?(u=6,c=3):(u=7,c=4))},send_tree=(e,t,n)=>{let r,o=-1,s,g=t[0*2+1],l=0,u=7,c=4;for(g===0&&(u=138,c=3),r=0;r<=n;r++)if(s=g,g=t[(r+1)*2+1],!(++l<u&&s===g)){if(l<c)do send_code(e,s,e.bl_tree);while(--l!==0);else s!==0?(s!==o&&(send_code(e,s,e.bl_tree),l--),send_code(e,REP_3_6,e.bl_tree),send_bits(e,l-3,2)):l<=10?(send_code(e,REPZ_3_10,e.bl_tree),send_bits(e,l-3,3)):(send_code(e,REPZ_11_138,e.bl_tree),send_bits(e,l-11,7));l=0,o=s,g===0?(u=138,c=3):s===g?(u=6,c=3):(u=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,s,g=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),g=build_bl_tree(e),o=e.opt_len+3+7>>>3,s=e.static_len+3+7>>>3,s<=o&&(o=s)):o=s=n+5,n+4<=o&&t!==-1?_tr_stored_block$1(e,t,n,r):e.strategy===Z_FIXED$1||s===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,g+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,s=e>>>16&65535|0,g=0;for(;n!==0;){g=n>2e3?2e3:n,n-=g;do o=o+t[r++]|0,s=s+o|0;while(--g);o%=65521,s%=65521}return o|s<<16|0};var adler32_1=adler32;const makeTable=()=>{let e,t=[];for(var n=0;n<256;n++){e=n;for(var r=0;r<8;r++)e=e&1?3988292384^e>>>1:e>>>1;t[n]=e}return t},crcTable=new Uint32Array(makeTable()),crc32=(e,t,n,r)=>{const o=crcTable,s=r+n;e^=-1;for(let g=r;g<s;g++)e=e>>>8^o[(e^t[g])&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,s,g=e.prev_length,l=e.nice_match;const u=e.strstart>e.w_size-MIN_LOOKAHEAD?e.strstart-(e.w_size-MIN_LOOKAHEAD):0,c=e.window,d=e.w_mask,B=e.prev,Q=e.strstart+MAX_MATCH;let f=c[r+g-1],p=c[r+g];e.prev_length>=e.good_match&&(n>>=2),l>e.lookahead&&(l=e.lookahead);do if(o=t,!(c[o+g]!==p||c[o+g-1]!==f||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<Q);if(s=MAX_MATCH-(Q-r),r=Q-MAX_MATCH,s>g){if(e.match_start=t,g=s,s>=l)break;f=c[r+g-1],p=c[r+g]}}while((t=B[t&d])>u&&--n!==0);return g<=e.lookahead?g: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,s,g=0,l=e.strm.avail_in;do{if(r=65535,s=e.bi_valid+42>>3,e.strm.avail_out<s||(s=e.strm.avail_out-s,o=e.strstart-e.block_start,r>o+e.strm.avail_in&&(r=o+e.strm.avail_in),r>s&&(r=s),r<n&&(r===0&&t!==Z_FINISH$3||t===Z_NO_FLUSH$2||r!==o+e.strm.avail_in)))break;g=t===Z_FINISH$3&&r===o+e.strm.avail_in?1:0,_tr_stored_block(e,0,0,g),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(g===0);return l-=e.strm.avail_in,l&&(l>=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<=l&&(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-l,e.strm.next_in),e.strstart),e.strstart+=l,e.insert+=l>e.w_size-e.insert?e.w_size-e.insert:l),e.block_start=e.strstart),e.high_water<e.strstart&&(e.high_water=e.strstart),g?BS_FINISH_DONE:t!==Z_NO_FLUSH$2&&t!==Z_FINISH$3&&e.strm.avail_in===0&&e.strstart===e.block_start?BS_BLOCK_DONE:(s=e.window_size-e.strstart,e.strm.avail_in>s&&e.block_start>=e.w_size&&(e.block_start-=e.w_size,e.strstart-=e.w_size,e.window.set(e.window.subarray(e.w_size,e.w_size+e.strstart),0),e.matches<2&&e.matches++,s+=e.w_size,e.insert>e.strstart&&(e.insert=e.strstart)),s>e.strm.avail_in&&(s=e.strm.avail_in),s&&(read_buf(e.strm,e.window,e.strstart,s),e.strstart+=s,e.insert+=s>e.w_size-e.insert?e.w_size-e.insert:s),e.high_water<e.strstart&&(e.high_water=e.strstart),s=e.bi_valid+42>>3,s=e.pending_buf_size-s>65535?65535:e.pending_buf_size-s,n=s>e.w_size?e.w_size:s,o=e.strstart-e.block_start,(o>=n||(o||t===Z_FINISH$3)&&t!==Z_NO_FLUSH$2&&e.strm.avail_in===0&&o<=s)&&(r=o>s?s:o,g=t===Z_FINISH$3&&e.strm.avail_in===0&&r===o?1:0,_tr_stored_block(e,e.block_start,r,g),e.block_start+=r,flush_pending(e.strm)),g?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,s;const g=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=g[o],r===g[++o]&&r===g[++o]&&r===g[++o])){s=e.strstart+MAX_MATCH;do;while(r===g[++o]&&r===g[++o]&&r===g[++o]&&r===g[++o]&&r===g[++o]&&r===g[++o]&&r===g[++o]&&r===g[++o]&&o<s);e.match_length=MAX_MATCH-(s-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,s)=>{if(!e)return Z_STREAM_ERROR$2;let g=1;if(t===Z_DEFAULT_COMPRESSION$1&&(t=6),r<0?(g=0,r=-r):r>15&&(g=2,r-=16),o<1||o>MAX_MEM_LEVEL||n!==Z_DEFLATED$2||r<8||r>15||t<0||t>9||s<0||s>Z_FIXED||r===8&&g!==1)return err(e,Z_STREAM_ERROR$2);r===8&&(r=9);const l=new DeflateState;return e.state=l,l.strm=e,l.status=INIT_STATE,l.wrap=g,l.gzhead=null,l.w_bits=r,l.w_size=1<<l.w_bits,l.w_mask=l.w_size-1,l.hash_bits=o+7,l.hash_size=1<<l.hash_bits,l.hash_mask=l.hash_size-1,l.hash_shift=~~((l.hash_bits+MIN_MATCH-1)/MIN_MATCH),l.window=new Uint8Array(l.w_size*2),l.head=new Uint16Array(l.hash_size),l.prev=new Uint16Array(l.w_size),l.lit_bufsize=1<<o+6,l.pending_buf_size=l.lit_bufsize*4,l.pending_buf=new Uint8Array(l.pending_buf_size),l.sym_buf=l.lit_bufsize,l.sym_end=(l.lit_bufsize-1)*3,l.level=t,l.strategy=s,l.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,s=-1;if(n.strategy>=Z_HUFFMAN_ONLY||n.level<2?s=0:n.level<6?s=1:n.level===6?s=2:s=3,o|=s<<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,s=(n.gzhead.extra.length&65535)-n.gzindex;for(;n.pending+s>n.pending_buf_size;){let l=n.pending_buf_size-n.pending;if(n.pending_buf.set(n.gzhead.extra.subarray(n.gzindex,n.gzindex+l),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+=l,flush_pending(e),n.pending!==0)return n.last_flush=-1,Z_OK$3;o=0,s-=l}let g=new Uint8Array(n.gzhead.extra);n.pending_buf.set(g.subarray(n.gzindex,n.gzindex+s),n.pending),n.pending+=s,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,s;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?s=n.gzhead.name.charCodeAt(n.gzindex++)&255:s=0,put_byte(n,s)}while(s!==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,s;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?s=n.gzhead.comment.charCodeAt(n.gzindex++)&255:s=0,put_byte(n,s)}while(s!==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 u=new Uint8Array(r.w_size);u.set(t.subarray(n-r.w_size,n),0),t=u,n=r.w_size}const s=e.avail_in,g=e.next_in,l=e.input;for(e.avail_in=n,e.next_in=0,e.input=t,fill_window(r);r.lookahead>=MIN_MATCH;){let u=r.strstart,c=r.lookahead-(MIN_MATCH-1);do r.ins_h=HASH(r,r.ins_h,r.window[u+MIN_MATCH-1]),r.prev[u&r.w_mask]=r.head[r.ins_h],r.head[r.ins_h]=u,u++;while(--c);r.strstart=u,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=g,e.input=l,e.avail_in=s,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,s=e.length;r<s;r++){let g=e[r];n.set(g,o),o+=g.length}return n},common={assign,flattenChunks};let STR_APPLY_UIA_OK=!0;try{String.fromCharCode.apply(null,new Uint8Array(1))}catch{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,s,g=e.length,l=0;for(o=0;o<g;o++)n=e.charCodeAt(o),(n&64512)===55296&&o+1<g&&(r=e.charCodeAt(o+1),(r&64512)===56320&&(n=65536+(n-55296<<10)+(r-56320),o++)),l+=n<128?1:n<2048?2:n<65536?3:4;for(t=new Uint8Array(l),s=0,o=0;s<l;o++)n=e.charCodeAt(o),(n&64512)===55296&&o+1<g&&(r=e.charCodeAt(o+1),(r&64512)===56320&&(n=65536+(n-55296<<10)+(r-56320),o++)),n<128?t[s++]=n:n<2048?(t[s++]=192|n>>>6,t[s++]=128|n&63):n<65536?(t[s++]=224|n>>>12,t[s++]=128|n>>>6&63,t[s++]=128|n&63):(t[s++]=240|n>>>18,t[s++]=128|n>>>12&63,t[s++]=128|n>>>6&63,t[s++]=128|n&63);return t};const buf2binstring=(e,t)=>{if(t<65534&&e.subarray&&STR_APPLY_UIA_OK)return String.fromCharCode.apply(null,e.length===t?e:e.subarray(0,t));let n="";for(let r=0;r<t;r++)n+=String.fromCharCode(e[r]);return n};var buf2string=(e,t)=>{const n=t||e.length;if(typeof TextDecoder=="function"&&TextDecoder.prototype.decode)return new TextDecoder().decode(e.subarray(0,t));let r,o;const s=new Array(n*2);for(o=0,r=0;r<n;){let g=e[r++];if(g<128){s[o++]=g;continue}let l=_utf8len[g];if(l>4){s[o++]=65533,r+=l-1;continue}for(g&=l===2?31:l===3?15:7;l>1&&r<n;)g=g<<6|e[r++]&63,l--;if(l>1){s[o++]=65533;continue}g<65536?s[o++]=g:(g-=65536,s[o++]=55296|g>>10&1023,s[o++]=56320|g&1023)}return buf2binstring(s,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,s;if(this.ended)return!1;for(t===~~t?s=t:s=t===!0?Z_FINISH$2:Z_NO_FLUSH$1,typeof e=="string"?n.input=strings.string2buf(e):toString$1.call(e)==="[object ArrayBuffer]"?n.input=new Uint8Array(e):n.input=e,n.next_in=0,n.avail_in=n.input.length;;){if(n.avail_out===0&&(n.output=new Uint8Array(r),n.next_out=0,n.avail_out=r),(s===Z_SYNC_FLUSH||s===Z_FULL_FLUSH)&&n.avail_out<=6){this.onData(n.output.subarray(0,n.next_out)),n.avail_out=0;continue}if(o=deflate_1$2.deflate(n,s),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(s>0&&n.next_out>0){this.onData(n.output.subarray(0,n.next_out)),n.avail_out=0;continue}if(n.avail_in===0)break}return!0};Deflate$1.prototype.onData=function(e){this.chunks.push(e)};Deflate$1.prototype.onEnd=function(e){e===Z_OK$2&&(this.result=common.flattenChunks(this.chunks)),this.chunks=[],this.err=e,this.msg=this.strm.msg};function deflate$1(e,t){const n=new Deflate$1(t);if(n.push(e,!0),n.err)throw n.msg||messages[n.err];return n.result}function deflateRaw$1(e,t){return t=t||{},t.raw=!0,deflate$1(e,t)}function gzip$1(e,t){return t=t||{},t.gzip=!0,deflate$1(e,t)}var Deflate_1$1=Deflate$1,deflate_2=deflate$1,deflateRaw_1$1=deflateRaw$1,gzip_1$1=gzip$1,constants$1=constants$2,deflate_1$1={Deflate:Deflate_1$1,deflate:deflate_2,deflateRaw:deflateRaw_1$1,gzip:gzip_1$1,constants:constants$1};const BAD$1=16209,TYPE$1=16191;var inffast=function(t,n){let r,o,s,g,l,u,c,d,B,Q,f,p,U,E,M,W,y,m,h,T,I,X,F,R;const x=t.state;r=t.next_in,F=t.input,o=r+(t.avail_in-5),s=t.next_out,R=t.output,g=s-(n-t.avail_out),l=s+(t.avail_out-257),u=x.dmax,c=x.wsize,d=x.whave,B=x.wnext,Q=x.window,f=x.hold,p=x.bits,U=x.lencode,E=x.distcode,M=(1<<x.lenbits)-1,W=(1<<x.distbits)-1;e:do{p<15&&(f+=F[r++]<<p,p+=8,f+=F[r++]<<p,p+=8),y=U[f&M];t:for(;;){if(m=y>>>24,f>>>=m,p-=m,m=y>>>16&255,m===0)R[s++]=y&65535;else if(m&16){h=y&65535,m&=15,m&&(p<m&&(f+=F[r++]<<p,p+=8),h+=f&(1<<m)-1,f>>>=m,p-=m),p<15&&(f+=F[r++]<<p,p+=8,f+=F[r++]<<p,p+=8),y=E[f&W];n:for(;;){if(m=y>>>24,f>>>=m,p-=m,m=y>>>16&255,m&16){if(T=y&65535,m&=15,p<m&&(f+=F[r++]<<p,p+=8,p<m&&(f+=F[r++]<<p,p+=8)),T+=f&(1<<m)-1,T>u){t.msg="invalid distance too far back",x.mode=BAD$1;break e}if(f>>>=m,p-=m,m=s-g,T>m){if(m=T-m,m>d&&x.sane){t.msg="invalid distance too far back",x.mode=BAD$1;break e}if(I=0,X=Q,B===0){if(I+=c-m,m<h){h-=m;do R[s++]=Q[I++];while(--m);I=s-T,X=R}}else if(B<m){if(I+=c+B-m,m-=B,m<h){h-=m;do R[s++]=Q[I++];while(--m);if(I=0,B<h){m=B,h-=m;do R[s++]=Q[I++];while(--m);I=s-T,X=R}}}else if(I+=B-m,m<h){h-=m;do R[s++]=Q[I++];while(--m);I=s-T,X=R}for(;h>2;)R[s++]=X[I++],R[s++]=X[I++],R[s++]=X[I++],h-=3;h&&(R[s++]=X[I++],h>1&&(R[s++]=X[I++]))}else{I=s-T;do R[s++]=R[I++],R[s++]=R[I++],R[s++]=R[I++],h-=3;while(h>2);h&&(R[s++]=R[I++],h>1&&(R[s++]=R[I++]))}}else if(m&64){t.msg="invalid distance code",x.mode=BAD$1;break e}else{y=E[(y&65535)+(f&(1<<m)-1)];continue n}break}}else if(m&64)if(m&32){x.mode=TYPE$1;break e}else{t.msg="invalid literal/length code",x.mode=BAD$1;break e}else{y=U[(y&65535)+(f&(1<<m)-1)];continue t}break}}while(r<o&&s<l);h=p>>3,r-=h,p-=h<<3,f&=(1<<p)-1,t.next_in=r,t.next_out=s,t.avail_in=r<o?5+(o-r):5-(r-o),t.avail_out=s<l?257+(l-s):257-(s-l),x.hold=f,x.bits=p};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,s,g,l)=>{const u=l.bits;let c=0,d=0,B=0,Q=0,f=0,p=0,U=0,E=0,M=0,W=0,y,m,h,T,I,X=null,F;const R=new Uint16Array(MAXBITS+1),x=new Uint16Array(MAXBITS+1);let w=null,_,j,C;for(c=0;c<=MAXBITS;c++)R[c]=0;for(d=0;d<r;d++)R[t[n+d]]++;for(f=u,Q=MAXBITS;Q>=1&&R[Q]===0;Q--);if(f>Q&&(f=Q),Q===0)return o[s++]=1<<24|64<<16|0,o[s++]=1<<24|64<<16|0,l.bits=1,0;for(B=1;B<Q&&R[B]===0;B++);for(f<B&&(f=B),E=1,c=1;c<=MAXBITS;c++)if(E<<=1,E-=R[c],E<0)return-1;if(E>0&&(e===CODES$1||Q!==1))return-1;for(x[1]=0,c=1;c<MAXBITS;c++)x[c+1]=x[c]+R[c];for(d=0;d<r;d++)t[n+d]!==0&&(g[x[t[n+d]]++]=d);if(e===CODES$1?(X=w=g,F=20):e===LENS$1?(X=lbase,w=lext,F=257):(X=dbase,w=dext,F=0),W=0,d=0,c=B,I=s,p=f,U=0,h=-1,M=1<<f,T=M-1,e===LENS$1&&M>ENOUGH_LENS$1||e===DISTS$1&&M>ENOUGH_DISTS$1)return 1;for(;;){_=c-U,g[d]+1<F?(j=0,C=g[d]):g[d]>=F?(j=w[g[d]-F],C=X[g[d]-F]):(j=32+64,C=0),y=1<<c-U,m=1<<p,B=m;do m-=y,o[I+(W>>U)+m]=_<<24|j<<16|C|0;while(m!==0);for(y=1<<c-1;W&y;)y>>=1;if(y!==0?(W&=y-1,W+=y):W=0,d++,--R[c]===0){if(c===Q)break;c=t[n+g[d]]}if(c>f&&(W&T)!==h){for(U===0&&(U=f),I+=B,p=c-U,E=1<<p;p+U<Q&&(E-=R[p+U],!(E<=0));)p++,E<<=1;if(M+=1<<p,e===LENS$1&&M>ENOUGH_LENS$1||e===DISTS$1&&M>ENOUGH_DISTS$1)return 1;h=W&T,o[h]=f<<24|p<<16|I-s|0}}return W!==0&&(o[I+W]=c-U<<24|64<<16|0),l.bits=f,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 s=e.state;return s.window===null&&(s.wsize=1<<s.wbits,s.wnext=0,s.whave=0,s.window=new Uint8Array(s.wsize)),r>=s.wsize?(s.window.set(t.subarray(n-s.wsize,n),0),s.wnext=0,s.whave=s.wsize):(o=s.wsize-s.wnext,o>r&&(o=r),s.window.set(t.subarray(n-r,n-r+o),s.wnext),r-=o,r?(s.window.set(t.subarray(n-r,n),0),s.wnext=r,s.whave=s.wsize):(s.wnext+=o,s.wnext===s.wsize&&(s.wnext=0),s.whave<s.wsize&&(s.whave+=o))),0},inflate$2=(e,t)=>{let n,r,o,s,g,l,u,c,d,B,Q,f,p,U,E=0,M,W,y,m,h,T,I,X;const F=new Uint8Array(4);let R,x;const w=new Uint8Array([16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15]);if(inflateStateCheck(e)||!e.output||!e.input&&e.avail_in!==0)return Z_STREAM_ERROR$1;n=e.state,n.mode===TYPE&&(n.mode=TYPEDO),g=e.next_out,o=e.output,u=e.avail_out,s=e.next_in,r=e.input,l=e.avail_in,c=n.hold,d=n.bits,B=l,Q=u,X=Z_OK$1;e:for(;;)switch(n.mode){case HEAD:if(n.wrap===0){n.mode=TYPEDO;break}for(;d<16;){if(l===0)break e;l--,c+=r[s++]<<d,d+=8}if(n.wrap&2&&c===35615){n.wbits===0&&(n.wbits=15),n.check=0,F[0]=c&255,F[1]=c>>>8&255,n.check=crc32_1(n.check,F,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,I=(c&15)+8,n.wbits===0&&(n.wbits=I),I>15||I>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(l===0)break e;l--,c+=r[s++]<<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&&(F[0]=c&255,F[1]=c>>>8&255,n.check=crc32_1(n.check,F,2,0)),c=0,d=0,n.mode=TIME;case TIME:for(;d<32;){if(l===0)break e;l--,c+=r[s++]<<d,d+=8}n.head&&(n.head.time=c),n.flags&512&&n.wrap&4&&(F[0]=c&255,F[1]=c>>>8&255,F[2]=c>>>16&255,F[3]=c>>>24&255,n.check=crc32_1(n.check,F,4,0)),c=0,d=0,n.mode=OS;case OS:for(;d<16;){if(l===0)break e;l--,c+=r[s++]<<d,d+=8}n.head&&(n.head.xflags=c&255,n.head.os=c>>8),n.flags&512&&n.wrap&4&&(F[0]=c&255,F[1]=c>>>8&255,n.check=crc32_1(n.check,F,2,0)),c=0,d=0,n.mode=EXLEN;case EXLEN:if(n.flags&1024){for(;d<16;){if(l===0)break e;l--,c+=r[s++]<<d,d+=8}n.length=c,n.head&&(n.head.extra_len=c),n.flags&512&&n.wrap&4&&(F[0]=c&255,F[1]=c>>>8&255,n.check=crc32_1(n.check,F,2,0)),c=0,d=0}else n.head&&(n.head.extra=null);n.mode=EXTRA;case EXTRA:if(n.flags&1024&&(f=n.length,f>l&&(f=l),f&&(n.head&&(I=n.head.extra_len-n.length,n.head.extra||(n.head.extra=new Uint8Array(n.head.extra_len)),n.head.extra.set(r.subarray(s,s+f),I)),n.flags&512&&n.wrap&4&&(n.check=crc32_1(n.check,r,f,s)),l-=f,s+=f,n.length-=f),n.length))break e;n.length=0,n.mode=NAME;case NAME:if(n.flags&2048){if(l===0)break e;f=0;do I=r[s+f++],n.head&&I&&n.length<65536&&(n.head.name+=String.fromCharCode(I));while(I&&f<l);if(n.flags&512&&n.wrap&4&&(n.check=crc32_1(n.check,r,f,s)),l-=f,s+=f,I)break e}else n.head&&(n.head.name=null);n.length=0,n.mode=COMMENT;case COMMENT:if(n.flags&4096){if(l===0)break e;f=0;do I=r[s+f++],n.head&&I&&n.length<65536&&(n.head.comment+=String.fromCharCode(I));while(I&&f<l);if(n.flags&512&&n.wrap&4&&(n.check=crc32_1(n.check,r,f,s)),l-=f,s+=f,I)break e}else n.head&&(n.head.comment=null);n.mode=HCRC;case HCRC:if(n.flags&512){for(;d<16;){if(l===0)break e;l--,c+=r[s++]<<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(l===0)break e;l--,c+=r[s++]<<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=g,e.avail_out=u,e.next_in=s,e.avail_in=l,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(l===0)break e;l--,c+=r[s++]<<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(l===0)break e;l--,c+=r[s++]<<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(f=n.length,f){if(f>l&&(f=l),f>u&&(f=u),f===0)break e;o.set(r.subarray(s,s+f),g),l-=f,s+=f,u-=f,g+=f,n.length-=f;break}n.mode=TYPE;break;case TABLE:for(;d<14;){if(l===0)break e;l--,c+=r[s++]<<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(l===0)break e;l--,c+=r[s++]<<d,d+=8}n.lens[w[n.have++]]=c&7,c>>>=3,d-=3}for(;n.have<19;)n.lens[w[n.have++]]=0;if(n.lencode=n.lendyn,n.lenbits=7,R={bits:n.lenbits},X=inftrees(CODES,n.lens,0,19,n.lencode,0,n.work,R),n.lenbits=R.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(;E=n.lencode[c&(1<<n.lenbits)-1],M=E>>>24,W=E>>>16&255,y=E&65535,!(M<=d);){if(l===0)break e;l--,c+=r[s++]<<d,d+=8}if(y<16)c>>>=M,d-=M,n.lens[n.have++]=y;else{if(y===16){for(x=M+2;d<x;){if(l===0)break e;l--,c+=r[s++]<<d,d+=8}if(c>>>=M,d-=M,n.have===0){e.msg="invalid bit length repeat",n.mode=BAD;break}I=n.lens[n.have-1],f=3+(c&3),c>>>=2,d-=2}else if(y===17){for(x=M+3;d<x;){if(l===0)break e;l--,c+=r[s++]<<d,d+=8}c>>>=M,d-=M,I=0,f=3+(c&7),c>>>=3,d-=3}else{for(x=M+7;d<x;){if(l===0)break e;l--,c+=r[s++]<<d,d+=8}c>>>=M,d-=M,I=0,f=11+(c&127),c>>>=7,d-=7}if(n.have+f>n.nlen+n.ndist){e.msg="invalid bit length repeat",n.mode=BAD;break}for(;f--;)n.lens[n.have++]=I}}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,R={bits:n.lenbits},X=inftrees(LENS,n.lens,0,n.nlen,n.lencode,0,n.work,R),n.lenbits=R.bits,X){e.msg="invalid literal/lengths set",n.mode=BAD;break}if(n.distbits=6,n.distcode=n.distdyn,R={bits:n.distbits},X=inftrees(DISTS,n.lens,n.nlen,n.ndist,n.distcode,0,n.work,R),n.distbits=R.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(l>=6&&u>=258){e.next_out=g,e.avail_out=u,e.next_in=s,e.avail_in=l,n.hold=c,n.bits=d,inffast(e,Q),g=e.next_out,o=e.output,u=e.avail_out,s=e.next_in,r=e.input,l=e.avail_in,c=n.hold,d=n.bits,n.mode===TYPE&&(n.back=-1);break}for(n.back=0;E=n.lencode[c&(1<<n.lenbits)-1],M=E>>>24,W=E>>>16&255,y=E&65535,!(M<=d);){if(l===0)break e;l--,c+=r[s++]<<d,d+=8}if(W&&!(W&240)){for(m=M,h=W,T=y;E=n.lencode[T+((c&(1<<m+h)-1)>>m)],M=E>>>24,W=E>>>16&255,y=E&65535,!(m+M<=d);){if(l===0)break e;l--,c+=r[s++]<<d,d+=8}c>>>=m,d-=m,n.back+=m}if(c>>>=M,d-=M,n.back+=M,n.length=y,W===0){n.mode=LIT;break}if(W&32){n.back=-1,n.mode=TYPE;break}if(W&64){e.msg="invalid literal/length code",n.mode=BAD;break}n.extra=W&15,n.mode=LENEXT;case LENEXT:if(n.extra){for(x=n.extra;d<x;){if(l===0)break e;l--,c+=r[s++]<<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(;E=n.distcode[c&(1<<n.distbits)-1],M=E>>>24,W=E>>>16&255,y=E&65535,!(M<=d);){if(l===0)break e;l--,c+=r[s++]<<d,d+=8}if(!(W&240)){for(m=M,h=W,T=y;E=n.distcode[T+((c&(1<<m+h)-1)>>m)],M=E>>>24,W=E>>>16&255,y=E&65535,!(m+M<=d);){if(l===0)break e;l--,c+=r[s++]<<d,d+=8}c>>>=m,d-=m,n.back+=m}if(c>>>=M,d-=M,n.back+=M,W&64){e.msg="invalid distance code",n.mode=BAD;break}n.offset=y,n.extra=W&15,n.mode=DISTEXT;case DISTEXT:if(n.extra){for(x=n.extra;d<x;){if(l===0)break e;l--,c+=r[s++]<<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(u===0)break e;if(f=Q-u,n.offset>f){if(f=n.offset-f,f>n.whave&&n.sane){e.msg="invalid distance too far back",n.mode=BAD;break}f>n.wnext?(f-=n.wnext,p=n.wsize-f):p=n.wnext-f,f>n.length&&(f=n.length),U=n.window}else U=o,p=g-n.offset,f=n.length;f>u&&(f=u),u-=f,n.length-=f;do o[g++]=U[p++];while(--f);n.length===0&&(n.mode=LEN);break;case LIT:if(u===0)break e;o[g++]=n.length,u--,n.mode=LEN;break;case CHECK:if(n.wrap){for(;d<32;){if(l===0)break e;l--,c|=r[s++]<<d,d+=8}if(Q-=u,e.total_out+=Q,n.total+=Q,n.wrap&4&&Q&&(e.adler=n.check=n.flags?crc32_1(n.check,o,Q,g-Q):adler32_1(n.check,o,Q,g-Q)),Q=u,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(l===0)break e;l--,c+=r[s++]<<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=g,e.avail_out=u,e.next_in=s,e.avail_in=l,n.hold=c,n.bits=d,(n.wsize||Q!==e.avail_out&&n.mode<BAD&&(n.mode<CHECK||t!==Z_FINISH$1))&&updatewindow(e,e.output,e.next_out,Q-e.avail_out),B-=e.avail_in,Q-=e.avail_out,e.total_in+=B,e.total_out+=Q,n.total+=Q,n.wrap&4&&Q&&(e.adler=n.check=n.flags?crc32_1(n.check,o,Q,e.next_out-Q):adler32_1(n.check,o,Q,e.next_out-Q)),e.data_type=n.bits+(n.last?64:0)+(n.mode===TYPE?128:0)+(n.mode===LEN_||n.mode===COPY_?256:0),(B===0&&Q===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,s;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:(s=updatewindow(e,t,n,n),s?(r.mode=MEM,Z_MEM_ERROR$1):(r.havedict=1,Z_OK$1))};var inflateReset_1=inflateReset,inflateReset2_1=inflateReset2,inflateResetKeep_1=inflateResetKeep,inflateInit_1=inflateInit,inflateInit2_1=inflateInit2,inflate_2$1=inflate$2,inflateEnd_1=inflateEnd,inflateGetHeader_1=inflateGetHeader,inflateSetDictionary_1=inflateSetDictionary,inflateInfo="pako inflate (from Nodeca project)",inflate_1$2={inflateReset:inflateReset_1,inflateReset2:inflateReset2_1,inflateResetKeep:inflateResetKeep_1,inflateInit:inflateInit_1,inflateInit2:inflateInit2_1,inflate:inflate_2$1,inflateEnd:inflateEnd_1,inflateGetHeader:inflateGetHeader_1,inflateSetDictionary:inflateSetDictionary_1,inflateInfo};function GZheader(){this.text=0,this.time=0,this.xflags=0,this.os=0,this.extra=null,this.extra_len=0,this.name="",this.comment="",this.hcrc=0,this.done=!1}var gzheader=GZheader;const toString=Object.prototype.toString,{Z_NO_FLUSH,Z_FINISH,Z_OK,Z_STREAM_END,Z_NEED_DICT,Z_STREAM_ERROR,Z_DATA_ERROR,Z_MEM_ERROR}=constants$2;function Inflate$1(e){this.options=common.assign({chunkSize:1024*64,windowBits:15,to:""},e||{});const t=this.options;t.raw&&t.windowBits>=0&&t.windowBits<16&&(t.windowBits=-t.windowBits,t.windowBits===0&&(t.windowBits=-15)),t.windowBits>=0&&t.windowBits<16&&!(e&&e.windowBits)&&(t.windowBits+=32),t.windowBits>15&&t.windowBits<48&&(t.windowBits&15||(t.windowBits|=15)),this.err=0,this.msg="",this.ended=!1,this.chunks=[],this.strm=new zstream,this.strm.avail_out=0;let n=inflate_1$2.inflateInit2(this.strm,t.windowBits);if(n!==Z_OK)throw new Error(messages[n]);if(this.header=new gzheader,inflate_1$2.inflateGetHeader(this.strm,this.header),t.dictionary&&(typeof t.dictionary=="string"?t.dictionary=strings.string2buf(t.dictionary):toString.call(t.dictionary)==="[object ArrayBuffer]"&&(t.dictionary=new Uint8Array(t.dictionary)),t.raw&&(n=inflate_1$2.inflateSetDictionary(this.strm,t.dictionary),n!==Z_OK)))throw new Error(messages[n])}Inflate$1.prototype.push=function(e,t){const n=this.strm,r=this.options.chunkSize,o=this.options.dictionary;let s,g,l;if(this.ended)return!1;for(t===~~t?g=t:g=t===!0?Z_FINISH:Z_NO_FLUSH,toString.call(e)==="[object ArrayBuffer]"?n.input=new Uint8Array(e):n.input=e,n.next_in=0,n.avail_in=n.input.length;;){for(n.avail_out===0&&(n.output=new Uint8Array(r),n.next_out=0,n.avail_out=r),s=inflate_1$2.inflate(n,g),s===Z_NEED_DICT&&o&&(s=inflate_1$2.inflateSetDictionary(n,o),s===Z_OK?s=inflate_1$2.inflate(n,g):s===Z_DATA_ERROR&&(s=Z_NEED_DICT));n.avail_in>0&&s===Z_STREAM_END&&n.state.wrap>0&&e[n.next_in]!==0;)inflate_1$2.inflateReset(n),s=inflate_1$2.inflate(n,g);switch(s){case Z_STREAM_ERROR:case Z_DATA_ERROR:case Z_NEED_DICT:case Z_MEM_ERROR:return this.onEnd(s),this.ended=!0,!1}if(l=n.avail_out,n.next_out&&(n.avail_out===0||s===Z_STREAM_END))if(this.options.to==="string"){let u=strings.utf8border(n.output,n.next_out),c=n.next_out-u,d=strings.buf2string(n.output,u);n.next_out=c,n.avail_out=r-c,c&&n.output.set(n.output.subarray(u,u+c),0),this.onData(d)}else this.onData(n.output.length===n.next_out?n.output:n.output.subarray(0,n.next_out));if(!(s===Z_OK&&l===0)){if(s===Z_STREAM_END)return s=inflate_1$2.inflateEnd(this.strm),this.onEnd(s),this.ended=!0,!0;if(n.avail_in===0)break}}return!0};Inflate$1.prototype.onData=function(e){this.chunks.push(e)};Inflate$1.prototype.onEnd=function(e){e===Z_OK&&(this.options.to==="string"?this.result=this.chunks.join(""):this.result=common.flattenChunks(this.chunks)),this.chunks=[],this.err=e,this.msg=this.strm.msg};const{Deflate,deflate,deflateRaw,gzip}=deflate_1$1;var deflate_1=deflate,fromByteArray_1=fromByteArray,lookup=[],code="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";for(var i=0,len=code.length;i<len;++i)lookup[i]=code[i];function tripletToBase64(e){return lookup[e>>18&63]+lookup[e>>12&63]+lookup[e>>6&63]+lookup[e&63]}function encodeChunk(e,t,n){for(var r,o=[],s=t;s<n;s+=3)r=(e[s]<<16&16711680)+(e[s+1]<<8&65280)+(e[s+2]&255),o.push(tripletToBase64(r));return o.join("")}function fromByteArray(e){for(var t,n=e.length,r=n%3,o=[],s=16383,g=0,l=n-r;g<l;g+=s)o.push(encodeChunk(e,g,g+s>l?l:g+s));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(`${exports.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(l=>l.name===t);if(r.length===0)return console.warn("View does not exist or it is misspell"),null;const o=await fetch(`${exports.FORMANT_API_URL}/v1/admin/shares`,{method:"POST",body:JSON.stringify(e),headers:{"Content-Type":"application/json",Authorization:"Bearer "+Authentication.token}}),s=exports.FORMANT_API_URL.replace("api","app"),{code:g}=await o.json();return`${s}/shares/${g}#${serializeHash({viewId:r[0].id})}`}async function disableDevice(e){if(!Authentication.token)throw new Error("Not authenticated");return await(await fetch(`${exports.FORMANT_API_URL}/v1/admin/devices/${e}/disable`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:"Bearer "+Authentication.token}})).json()}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(`${exports.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 s=aggregateByDateFunctions[t];return await Promise.all(Array(n).fill(0).map(async(g,l)=>{const u=new Date(r),c=s.sub(s.start(u),n-l-1),d=s.sub(s.end(u),n-l-1),B=formatTimeFrameText(c.toLocaleDateString(),d.toLocaleDateString()),Q=await queryEvents({...o,eventTypes:e,start:new Date(c).toISOString(),end:new Date(d).toISOString()});return{date:B,events:Q}}))}async function getAnnotationCount(e,t){return(await queryEvents({...e,eventTypes:["annotation"]})).filter(s=>!!s.tags&&Object.keys(s.tags).includes(t)).reduce((s,g)=>{const l=g.tags[t];return l in s?(s[l]+=1,s):(s[l]=1,s)},{})}async function getAnnotationCountByIntervals(e,t,n){const{end:r,start:o}=e,g=aggregateByDateFunctions[n].interval({start:new Date(o),end:new Date(r)}),l=g.map((c,d)=>{const B=new Date(c).toISOString(),Q=d===g.length-1?new Date(Date.now()).toISOString():new Date(g[d+1]);return getAnnotationCount({...e,start:B,end:Q},t)}),u=await Promise.all(l);return g.map((c,d)=>({date:new Date(c).toISOString(),annotations:u[d]}))}async function getDevicesData(){if(!Authentication.token)throw new Error("Not authenticated");return(await(await fetch(`${exports.FORMANT_API_URL}/v1/admin/device-details/query`,{method:"POST",body:JSON.stringify({enabled:!0,type:"default"}),headers:{"Content-Type":"application/json",Authorization:"Bearer "+Authentication.token}})).json()).items}var dist={exports:{}};/*! For license information please see index.js.LICENSE.txt */(function(module,exports){(function(e,t){module.exports=t()})(window,function(){return function(e){function t(c){for(var d,B,Q=c[0],f=c[1],p=0,U=[];p<Q.length;p++)B=Q[p],Object.prototype.hasOwnProperty.call(r,B)&&r[B]&&U.push(r[B][0]),r[B]=0;for(d in f)Object.prototype.hasOwnProperty.call(f,d)&&(e[d]=f[d]);for(u&&u(c);U.length;)U.shift()()}var n={},r={0:0};function o(c){if(n[c])return n[c].exports;var d=n[c]={i:c,l:!1,exports:{}};return e[c].call(d.exports,d,d.exports,o),d.l=!0,d.exports}o.e=function(){return Promise.resolve()},o.m=e,o.c=n,o.d=function(c,d,B){o.o(c,d)||Object.defineProperty(c,d,{enumerable:!0,get:B})},o.r=function(c){typeof Symbol!="undefined"&&Symbol.toStringTag&&Object.defineProperty(c,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(c,"__esModule",{value:!0})},o.t=function(c,d){if(1&d&&(c=o(c)),8&d||4&d&&typeof c=="object"&&c&&c.__esModule)return c;var B=Object.create(null);if(o.r(B),Object.defineProperty(B,"default",{enumerable:!0,value:c}),2&d&&typeof c!="string")for(var Q in c)o.d(B,Q,function(f){return c[f]}.bind(null,Q));return B},o.n=function(c){var d=c&&c.__esModule?function(){return c.default}:function(){return c};return o.d(d,"a",d),d},o.o=function(c,d){return Object.prototype.hasOwnProperty.call(c,d)},o.p="",o.oe=function(c){throw console.error(c),c};var s=window.webpackJsonpFormantRealtimeSDK=window.webpackJsonpFormantRealtimeSDK||[],g=s.push.bind(s);s.push=t,s=s.slice();for(var l=0;l<s.length;l++)t(s[l]);var u=g;return o(o.s=233)}([function(e,t,n){n.d(t,"a",function(){return V});var r=n(16),o=n(55),s=n(15),g=n.n(s),l=n(18);function u(K,Y){if(Y.length<K)throw new TypeError(K+" argument"+(K>1?"s":"")+" required, but only "+Y.length+" present")}function c(K){if(K===null||K===!0||K===!1)return NaN;var Y=Number(K);return isNaN(Y)?Y:Y<0?Math.ceil(Y):Math.floor(Y)}var d={dateTimeDelimiter:/[T ]/,timeZoneDelimiter:/[Z ]/i,timezone:/([Z+-].*)$/},B=/^-?(?:(\d{3})|(\d{2})(?:-?(\d{2}))?|W(\d{2})(?:-?(\d{1}))?|)$/,Q=/^(\d{2}(?:[.,]\d*)?)(?::?(\d{2}(?:[.,]\d*)?))?(?::?(\d{2}(?:[.,]\d*)?))?$/,f=/^([+-])(\d{2})(?::?(\d{2}))?$/;function p(K){var Y,te={},oe=K.split(d.dateTimeDelimiter);if(oe.length>2)return te;if(/:/.test(oe[0])?Y=oe[0]:(te.date=oe[0],Y=oe[1],d.timeZoneDelimiter.test(te.date)&&(te.date=K.split(d.timeZoneDelimiter)[0],Y=K.substr(te.date.length,K.length))),Y){var ge=d.timezone.exec(Y);ge?(te.time=Y.replace(ge[1],""),te.timezone=ge[1]):te.time=Y}return te}function U(K,Y){var te=new RegExp("^(?:(\\d{4}|[+-]\\d{"+(4+Y)+"})|(\\d{2}|[+-]\\d{"+(2+Y)+"})$)"),oe=K.match(te);if(!oe)return{year:NaN,restDateString:""};var ge=oe[1]?parseInt(oe[1]):null,Se=oe[2]?parseInt(oe[2]):null;return{year:Se===null?ge:100*Se,restDateString:K.slice((oe[1]||oe[2]).length)}}function E(K,Y){if(Y===null)return new Date(NaN);var te=K.match(B);if(!te)return new Date(NaN);var oe=!!te[4],ge=M(te[1]),Se=M(te[2])-1,ve=M(te[3]),ye=M(te[4]),Je=M(te[5])-1;if(oe)return function(be,we,Ze){return we>=1&&we<=53&&Ze>=0&&Ze<=6}(0,ye,Je)?function(be,we,Ze){var Oe=new Date(0);Oe.setUTCFullYear(be,0,4);var it=Oe.getUTCDay()||7,mt=7*(we-1)+Ze+1-it;return Oe.setUTCDate(Oe.getUTCDate()+mt),Oe}(Y,ye,Je):new Date(NaN);var Ee=new Date(0);return function(be,we,Ze){return we>=0&&we<=11&&Ze>=1&&Ze<=(h[we]||(T(be)?29:28))}(Y,Se,ve)&&function(be,we){return we>=1&&we<=(T(be)?366:365)}(Y,ge)?(Ee.setUTCFullYear(Y,Se,Math.max(ge,ve)),Ee):new Date(NaN)}function M(K){return K?parseInt(K):1}function W(K){var Y=K.match(Q);if(!Y)return NaN;var te=y(Y[1]),oe=y(Y[2]),ge=y(Y[3]);return function(Se,ve,ye){return Se===24?ve===0&&ye===0:ye>=0&&ye<60&&ve>=0&&ve<60&&Se>=0&&Se<25}(te,oe,ge)?36e5*te+6e4*oe+1e3*ge:NaN}function y(K){return K&&parseFloat(K.replace(",","."))||0}function m(K){if(K==="Z")return 0;var Y=K.match(f);if(!Y)return 0;var te=Y[1]==="+"?-1:1,oe=parseInt(Y[2]),ge=Y[3]&&parseInt(Y[3])||0;return function(Se,ve){return ve>=0&&ve<=59}(0,ge)?te*(36e5*oe+6e4*ge):NaN}var h=[31,null,31,30,31,30,31,31,30,31,30,31];function T(K){return K%400==0||K%4==0&&K%100!=0}var I=n(40);function X(K){return u(1,arguments),K instanceof Date||Object(I.a)(K)==="object"&&Object.prototype.toString.call(K)==="[object Date]"}function F(K){u(1,arguments);var Y=Object.prototype.toString.call(K);return K instanceof Date||Object(I.a)(K)==="object"&&Y==="[object Date]"?new Date(K.getTime()):typeof K=="number"||Y==="[object Number]"?new Date(K):(typeof K!="string"&&Y!=="[object String]"||typeof console=="undefined"||(console.warn("Starting with v2.0.0-beta.1 date-fns doesn't accept strings as date arguments. Please use `parseISO` to parse strings. See: https://github.com/date-fns/date-fns/blob/master/docs/upgradeGuide.md#string-arguments"),console.warn(new Error().stack)),new Date(NaN))}function R(K){const Y=function(te,oe){var ge;u(1,arguments);var Se=c((ge=oe==null?void 0:oe.additionalDigits)!==null&&ge!==void 0?ge:2);if(Se!==2&&Se!==1&&Se!==0)throw new RangeError("additionalDigits must be 0, 1 or 2");if(typeof te!="string"&&Object.prototype.toString.call(te)!=="[object String]")return new Date(NaN);var ve,ye=p(te);if(ye.date){var Je=U(ye.date,Se);ve=E(Je.restDateString,Je.year)}if(!ve||isNaN(ve.getTime()))return new Date(NaN);var Ee,be=ve.getTime(),we=0;if(ye.time&&(we=W(ye.time),isNaN(we)))return new Date(NaN);if(!ye.timezone){var Ze=new Date(be+we),Oe=new Date(0);return Oe.setFullYear(Ze.getUTCFullYear(),Ze.getUTCMonth(),Ze.getUTCDate()),Oe.setHours(Ze.getUTCHours(),Ze.getUTCMinutes(),Ze.getUTCSeconds(),Ze.getUTCMilliseconds()),Oe}return Ee=m(ye.timezone),isNaN(Ee)?new Date(NaN):new Date(be+we+Ee)}(K);if(!function(te){if(u(1,arguments),!X(te)&&typeof te!="number")return!1;var oe=F(te);return!isNaN(Number(oe))}(Y))throw new Error(`Invalid ISO 8601 date string (${K})`);return Y}const x=Math.pow(2,20),w=x;var _=n(3),j=n(28);function C(K){return g()(K,{cycles:!0})}var J=function(K,Y){var te={};for(var oe in K)Object.prototype.hasOwnProperty.call(K,oe)&&Y.indexOf(oe)<0&&(te[oe]=K[oe]);if(K!=null&&typeof Object.getOwnPropertySymbols=="function"){var ge=0;for(oe=Object.getOwnPropertySymbols(K);ge<oe.length;ge++)Y.indexOf(oe[ge])<0&&Object.prototype.propertyIsEnumerable.call(K,oe[ge])&&(te[oe[ge]]=K[oe[ge]])}return te};function v(K,Y={}){const{redacted:te=!0}=Y,oe=Je=>te?Object(j.a)(Je):Je;if(!K.stack)return{message:C(oe(K))};const{name:ge,message:Se,stack:ve}=K,ye=J(K,["name","message","stack"]);return{name:ge,message:Se!==void 0?Se:C(oe(K)),stack:ve,meta:ye&&Object.keys(ye).length===0?void 0:oe(ye)}}function D(K,Y={}){const{message:te,stack:oe,meta:ge}=v(K,Y);return`${oe||te||""}${ge&&Object.keys(ge).length>0?" -- "+C(ge):""}`}var A=n(236);const b=Object(A.a)();var P=n(14),z=n.n(P),$=function(K,Y,te,oe){return new(te||(te=Promise))(function(ge,Se){function ve(Ee){try{Je(oe.next(Ee))}catch(be){Se(be)}}function ye(Ee){try{Je(oe.throw(Ee))}catch(be){Se(be)}}function Je(Ee){var be;Ee.done?ge(Ee.value):(be=Ee.value,be instanceof te?be:new te(function(we){we(be)})).then(ve,ye)}Je((oe=oe.apply(K,Y||[])).next())})},ee=function(K,Y){var te={};for(var oe in K)Object.prototype.hasOwnProperty.call(K,oe)&&Y.indexOf(oe)<0&&(te[oe]=K[oe]);if(K!=null&&typeof Object.getOwnPropertySymbols=="function"){var ge=0;for(oe=Object.getOwnPropertySymbols(K);ge<oe.length;ge++)Y.indexOf(oe[ge])<0&&Object.prototype.propertyIsEnumerable.call(K,oe[ge])&&(te[oe[ge]]=K[oe[ge]])}return te};class re extends z.a{constructor(Y,te){super(),this.endpoint=Y,this.metadata=te,this.logClient=this.getLogClient()}getLogClient(){return $(this,void 0,void 0,function*(){const{LogClient:Y}=yield Promise.resolve().then(n.bind(null,235));return new Y(this.endpoint)})}log(Y,te){return $(this,void 0,void 0,function*(){const{level:oe,message:ge,error:Se}=Y,ve=ee(Y,["level","message","error"]);this.emit("logged");try{yield(yield this.logClient).log([{timestamp:new Date().toISOString(),level:oe,message:(""+ge).substring(0,1e3),error:Se!==void 0?v(Se):void 0,meta:Object.assign(Object.assign({},ve),this.metadata)}])}catch(ye){console.error("Failed to log to log-api: "+D(ye))}te()})}}var O=function(K,Y){var te={};for(var oe in K)Object.prototype.hasOwnProperty.call(K,oe)&&Y.indexOf(oe)<0&&(te[oe]=K[oe]);if(K!=null&&typeof Object.getOwnPropertySymbols=="function"){var ge=0;for(oe=Object.getOwnPropertySymbols(K);ge<oe.length;ge++)Y.indexOf(oe[ge])<0&&Object.prototype.propertyIsEnumerable.call(K,oe[ge])&&(te[oe[ge]]=K[oe[ge]])}return te};const k={app:_.a,namespace:_.j,buildTag:_.c,instanceId:b},S=_.f?l.format.printf(K=>{var{timestamp:Y,level:te,message:oe,error:ge}=K,Se=O(K,["timestamp","level","message","error"]);const ve=Object.assign(Object.assign({timestamp:Y?R(Y).getTime():new Date().getTime(),level:te.toUpperCase(),message:oe},ge?{error:v(ge)}:{}),{meta:Object.assign(Object.assign({},k),Se)});return g()(ve,{cycles:!0})}):l.format.printf(K=>{var{timestamp:Y,level:te,message:oe,error:ge}=K,Se=O(K,["timestamp","level","message","error"]);let ve=`${Y||new Date().toISOString()} ${te.toUpperCase()}: ${oe} `;return Object.keys(Se).length>0&&(ve+=g()(Se,{cycles:!0})),ge&&(ve+=`
2
2
  `+D(ge)),ve}),V=Object(l.createLogger)({level:_.g});if(V.add(new l.transports.Console({format:S,level:"debug"})),V.transports.forEach(K=>{K.silent=!_.h}),_.e&&V.add(new re(_.e,k)),_.i){const K=o.resolve(r.tmpdir(),`silly-${_.a}.log`);V.debug("Logging silly logs to file",{filename:K}),V.add(new l.transports.File({filename:K,maxsize:1*w,maxFiles:10,format:l.format.combine((G="silly",Object(l.format)(Y=>Y.level===G&&Y)()),S),level:"silly"}))}var G},function(e,t,n){n.d(t,"a",function(){return o});const r=864e5,o={millisecond:1,second:1e3,minute:6e4,hour:36e5,day:r,week:6048e5,month:2592e6,year:31536e6}},function(e,t){var n,r,o=e.exports={};function s(){throw new Error("setTimeout has not been defined")}function g(){throw new Error("clearTimeout has not been defined")}function l(E){if(n===setTimeout)return setTimeout(E,0);if((n===s||!n)&&setTimeout)return n=setTimeout,setTimeout(E,0);try{return n(E,0)}catch{try{return n.call(null,E,0)}catch{return n.call(this,E,0)}}}(function(){try{n=typeof setTimeout=="function"?setTimeout:s}catch{n=s}try{r=typeof clearTimeout=="function"?clearTimeout:g}catch{r=g}})();var u,c=[],d=!1,B=-1;function Q(){d&&u&&(d=!1,u.length?c=u.concat(c):B=-1,c.length&&f())}function f(){if(!d){var E=l(Q);d=!0;for(var M=c.length;M;){for(u=c,c=[];++B<M;)u&&u[B].run();B=-1,M=c.length}u=null,d=!1,function(W){if(r===clearTimeout)return clearTimeout(W);if((r===g||!r)&&clearTimeout)return r=clearTimeout,clearTimeout(W);try{r(W)}catch{try{return r.call(null,W)}catch{return r.call(this,W)}}}(E)}}function p(E,M){this.fun=E,this.array=M}function U(){}o.nextTick=function(E){var M=new Array(arguments.length-1);if(arguments.length>1)for(var W=1;W<arguments.length;W++)M[W-1]=arguments[W];c.push(new p(E,M)),c.length!==1||d||l(f)},p.prototype.run=function(){this.fun.apply(null,this.array)},o.title="browser",o.browser=!0,o.env={},o.argv=[],o.version="",o.versions={},o.on=U,o.addListener=U,o.once=U,o.off=U,o.removeListener=U,o.removeAllListeners=U,o.emit=U,o.prependListener=U,o.prependOnceListener=U,o.listeners=function(E){return[]},o.binding=function(E){throw new Error("process.binding is not supported")},o.cwd=function(){return"/"},o.chdir=function(E){throw new Error("process.chdir is not supported")},o.umask=function(){return 0}},function(e,t,n){(function(r){n.d(t,"a",function(){return g}),n.d(t,"j",function(){return l}),n.d(t,"k",function(){return u}),n.d(t,"c",function(){return c}),n.d(t,"g",function(){return d}),n.d(t,"f",function(){return B}),n.d(t,"h",function(){return Q}),n.d(t,"e",function(){return f}),n.d(t,"d",function(){return p}),n.d(t,"i",function(){return U}),n.d(t,"b",function(){return E});var o=n(100);const s=o.from({ENVIRONMENT:r.env.ENV,AGGREGATE_LEVEL:r.env.AGGREGATE_LEVEL,API_ENDPOINT:r.env.API_ENDPOINT,APP:"realtime-sdk",APP_PATH:r.env.APP_PATH,BUILD_TAG:r.env.BUILD_TAG,ENABLE_SELF_SERVE:r.env.ENABLE_SELF_SERVE,ENABLE_SENTRY:r.env.ENABLE_SENTRY,ENABLE_SENTRY_PROFILING:r.env.ENABLE_SENTRY_PROFILING,GIT_COMMIT:r.env.GIT_COMMIT,JEST_WORKER_ID:r.env.JEST_WORKER_ID,LOG_API_ENDPOINT:r.env.LOG_API_ENDPOINT,LOG_JSON:"false",LOG_LEVEL:r.env.LOG_LEVEL,LOG_TO_CONSOLE:r.env.LOG_TO_CONSOLE,LOG_TO_FILE:r.env.LOG_TO_FILE,NAMESPACE:"production",SENTRY_DSN:r.env.SENTRY_DSN,SHEET_EXPORT_MAX_ROW_COUNT:r.env.SHEET_EXPORT_MAX_ROW_COUNT,STABLE_AGENT_VERSION:r.env.STABLE_AGENT_VERSION,VERSION:r.env.VERSION,AUDIT_LOGS_ENABLED:r.env.AUDIT_LOGS_ENABLED}),g=(s.get("ENVIRONMENT").default("").asString(),s.get("APP").default("").asString()),l=(s.get("APP_PATH").default("").asString(),s.get("API_ENDPOINT").default("").asString(),s.get("NAMESPACE").default("").asString()),u=s.get("VERSION").default("").asString(),c=s.get("BUILD_TAG").default("").asString(),d=(s.get("GIT_COMMIT").default("").asString(),s.get("ENABLE_SENTRY").default("false").asBool(),s.get("ENABLE_SENTRY_PROFILING").default("false").asBool(),s.get("SENTRY_DSN").default("").asString(),s.get("LOG_LEVEL").default("debug").asString()),B=s.get("LOG_JSON").default("true").asBool(),Q=s.get("LOG_TO_CONSOLE").default("true").asBool(),f=(s.get("STABLE_AGENT_VERSION").default("").asString(),s.get("LOG_API_ENDPOINT").asString()),p=s.get("JEST_WORKER_ID").asString(),U=(s.get("SHEET_EXPORT_MAX_ROW_COUNT").default("10000").asIntPositive(),s.get("LOG_TO_FILE").default("false").asBoolStrict()),E=(s.get("ENABLE_SELF_SERVE").default("true").asBoolStrict(),s.get("AGGREGATE_LEVEL").default("hour").asEnum(["day","hour","minute"]),s.get("AUDIT_LOGS_ENABLED").default("true").asBoolStrict())}).call(this,n(2))},function(e,t,n){Object.defineProperty(t,"LEVEL",{value:Symbol.for("level")}),Object.defineProperty(t,"MESSAGE",{value:Symbol.for("message")}),Object.defineProperty(t,"SPLAT",{value:Symbol.for("splat")}),Object.defineProperty(t,"configs",{value:n(115)})},function(e,t,n){(function(r){var o=n(140),s=n(141),g=n(142);function l(){return c.TYPED_ARRAY_SUPPORT?2147483647:1073741823}function u(S,V){if(l()<V)throw new RangeError("Invalid typed array length");return c.TYPED_ARRAY_SUPPORT?(S=new Uint8Array(V)).__proto__=c.prototype:(S===null&&(S=new c(V)),S.length=V),S}function c(S,V,G){if(!(c.TYPED_ARRAY_SUPPORT||this instanceof c))return new c(S,V,G);if(typeof S=="number"){if(typeof V=="string")throw new Error("If encoding is specified then the first argument must be a string");return Q(this,S)}return d(this,S,V,G)}function d(S,V,G,K){if(typeof V=="number")throw new TypeError('"value" argument must not be a number');return typeof ArrayBuffer!="undefined"&&V instanceof ArrayBuffer?function(Y,te,oe,ge){if(te.byteLength,oe<0||te.byteLength<oe)throw new RangeError("'offset' is out of bounds");if(te.byteLength<oe+(ge||0))throw new RangeError("'length' is out of bounds");return te=oe===void 0&&ge===void 0?new Uint8Array(te):ge===void 0?new Uint8Array(te,oe):new Uint8Array(te,oe,ge),c.TYPED_ARRAY_SUPPORT?(Y=te).__proto__=c.prototype:Y=f(Y,te),Y}(S,V,G,K):typeof V=="string"?function(Y,te,oe){if(typeof oe=="string"&&oe!==""||(oe="utf8"),!c.isEncoding(oe))throw new TypeError('"encoding" must be a valid string encoding');var ge=0|U(te,oe),Se=(Y=u(Y,ge)).write(te,oe);return Se!==ge&&(Y=Y.slice(0,Se)),Y}(S,V,G):function(Y,te){if(c.isBuffer(te)){var oe=0|p(te.length);return(Y=u(Y,oe)).length===0||te.copy(Y,0,0,oe),Y}if(te){if(typeof ArrayBuffer!="undefined"&&te.buffer instanceof ArrayBuffer||"length"in te)return typeof te.length!="number"||(ge=te.length)!=ge?u(Y,0):f(Y,te);if(te.type==="Buffer"&&g(te.data))return f(Y,te.data)}var ge;throw new TypeError("First argument must be a string, Buffer, ArrayBuffer, Array, or array-like object.")}(S,V)}function B(S){if(typeof S!="number")throw new TypeError('"size" argument must be a number');if(S<0)throw new RangeError('"size" argument must not be negative')}function Q(S,V){if(B(V),S=u(S,V<0?0:0|p(V)),!c.TYPED_ARRAY_SUPPORT)for(var G=0;G<V;++G)S[G]=0;return S}function f(S,V){var G=V.length<0?0:0|p(V.length);S=u(S,G);for(var K=0;K<G;K+=1)S[K]=255&V[K];return S}function p(S){if(S>=l())throw new RangeError("Attempt to allocate Buffer larger than maximum size: 0x"+l().toString(16)+" bytes");return 0|S}function U(S,V){if(c.isBuffer(S))return S.length;if(typeof ArrayBuffer!="undefined"&&typeof ArrayBuffer.isView=="function"&&(ArrayBuffer.isView(S)||S instanceof ArrayBuffer))return S.byteLength;typeof S!="string"&&(S=""+S);var G=S.length;if(G===0)return 0;for(var K=!1;;)switch(V){case"ascii":case"latin1":case"binary":return G;case"utf8":case"utf-8":case void 0:return re(S).length;case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return 2*G;case"hex":return G>>>1;case"base64":return O(S).length;default:if(K)return re(S).length;V=(""+V).toLowerCase(),K=!0}}function E(S,V,G){var K=!1;if((V===void 0||V<0)&&(V=0),V>this.length||((G===void 0||G>this.length)&&(G=this.length),G<=0)||(G>>>=0)<=(V>>>=0))return"";for(S||(S="utf8");;)switch(S){case"hex":return j(this,V,G);case"utf8":case"utf-8":return x(this,V,G);case"ascii":return w(this,V,G);case"latin1":case"binary":return _(this,V,G);case"base64":return R(this,V,G);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return C(this,V,G);default:if(K)throw new TypeError("Unknown encoding: "+S);S=(S+"").toLowerCase(),K=!0}}function M(S,V,G){var K=S[V];S[V]=S[G],S[G]=K}function W(S,V,G,K,Y){if(S.length===0)return-1;if(typeof G=="string"?(K=G,G=0):G>2147483647?G=2147483647:G<-2147483648&&(G=-2147483648),G=+G,isNaN(G)&&(G=Y?0:S.length-1),G<0&&(G=S.length+G),G>=S.length){if(Y)return-1;G=S.length-1}else if(G<0){if(!Y)return-1;G=0}if(typeof V=="string"&&(V=c.from(V,K)),c.isBuffer(V))return V.length===0?-1:y(S,V,G,K,Y);if(typeof V=="number")return V&=255,c.TYPED_ARRAY_SUPPORT&&typeof Uint8Array.prototype.indexOf=="function"?Y?Uint8Array.prototype.indexOf.call(S,V,G):Uint8Array.prototype.lastIndexOf.call(S,V,G):y(S,[V],G,K,Y);throw new TypeError("val must be string, number or Buffer")}function y(S,V,G,K,Y){var te,oe=1,ge=S.length,Se=V.length;if(K!==void 0&&((K=String(K).toLowerCase())==="ucs2"||K==="ucs-2"||K==="utf16le"||K==="utf-16le")){if(S.length<2||V.length<2)return-1;oe=2,ge/=2,Se/=2,G/=2}function ve(be,we){return oe===1?be[we]:be.readUInt16BE(we*oe)}if(Y){var ye=-1;for(te=G;te<ge;te++)if(ve(S,te)===ve(V,ye===-1?0:te-ye)){if(ye===-1&&(ye=te),te-ye+1===Se)return ye*oe}else ye!==-1&&(te-=te-ye),ye=-1}else for(G+Se>ge&&(G=ge-Se),te=G;te>=0;te--){for(var Je=!0,Ee=0;Ee<Se;Ee++)if(ve(S,te+Ee)!==ve(V,Ee)){Je=!1;break}if(Je)return te}return-1}function m(S,V,G,K){G=Number(G)||0;var Y=S.length-G;K?(K=Number(K))>Y&&(K=Y):K=Y;var te=V.length;if(te%2!=0)throw new TypeError("Invalid hex string");K>te/2&&(K=te/2);for(var oe=0;oe<K;++oe){var ge=parseInt(V.substr(2*oe,2),16);if(isNaN(ge))return oe;S[G+oe]=ge}return oe}function h(S,V,G,K){return k(re(V,S.length-G),S,G,K)}function T(S,V,G,K){return k(function(Y){for(var te=[],oe=0;oe<Y.length;++oe)te.push(255&Y.charCodeAt(oe));return te}(V),S,G,K)}function I(S,V,G,K){return T(S,V,G,K)}function X(S,V,G,K){return k(O(V),S,G,K)}function F(S,V,G,K){return k(function(Y,te){for(var oe,ge,Se,ve=[],ye=0;ye<Y.length&&!((te-=2)<0);++ye)oe=Y.charCodeAt(ye),ge=oe>>8,Se=oe%256,ve.push(Se),ve.push(ge);return ve}(V,S.length-G),S,G,K)}function R(S,V,G){return V===0&&G===S.length?o.fromByteArray(S):o.fromByteArray(S.slice(V,G))}function x(S,V,G){G=Math.min(S.length,G);for(var K=[],Y=V;Y<G;){var te,oe,ge,Se,ve=S[Y],ye=null,Je=ve>239?4:ve>223?3:ve>191?2:1;if(Y+Je<=G)switch(Je){case 1:ve<128&&(ye=ve);break;case 2:(192&(te=S[Y+1]))==128&&(Se=(31&ve)<<6|63&te)>127&&(ye=Se);break;case 3:te=S[Y+1],oe=S[Y+2],(192&te)==128&&(192&oe)==128&&(Se=(15&ve)<<12|(63&te)<<6|63&oe)>2047&&(Se<55296||Se>57343)&&(ye=Se);break;case 4:te=S[Y+1],oe=S[Y+2],ge=S[Y+3],(192&te)==128&&(192&oe)==128&&(192&ge)==128&&(Se=(15&ve)<<18|(63&te)<<12|(63&oe)<<6|63&ge)>65535&&Se<1114112&&(ye=Se)}ye===null?(ye=65533,Je=1):ye>65535&&(ye-=65536,K.push(ye>>>10&1023|55296),ye=56320|1023&ye),K.push(ye),Y+=Je}return function(Ee){var be=Ee.length;if(be<=4096)return String.fromCharCode.apply(String,Ee);for(var we="",Ze=0;Ze<be;)we+=String.fromCharCode.apply(String,Ee.slice(Ze,Ze+=4096));return we}(K)}t.Buffer=c,t.SlowBuffer=function(S){return+S!=S&&(S=0),c.alloc(+S)},t.INSPECT_MAX_BYTES=50,c.TYPED_ARRAY_SUPPORT=r.TYPED_ARRAY_SUPPORT!==void 0?r.TYPED_ARRAY_SUPPORT:function(){try{var S=new Uint8Array(1);return S.__proto__={__proto__:Uint8Array.prototype,foo:function(){return 42}},S.foo()===42&&typeof S.subarray=="function"&&S.subarray(1,1).byteLength===0}catch{return!1}}(),t.kMaxLength=l(),c.poolSize=8192,c._augment=function(S){return S.__proto__=c.prototype,S},c.from=function(S,V,G){return d(null,S,V,G)},c.TYPED_ARRAY_SUPPORT&&(c.prototype.__proto__=Uint8Array.prototype,c.__proto__=Uint8Array,typeof Symbol!="undefined"&&Symbol.species&&c[Symbol.species]===c&&Object.defineProperty(c,Symbol.species,{value:null,configurable:!0})),c.alloc=function(S,V,G){return function(K,Y,te,oe){return B(Y),Y<=0?u(K,Y):te!==void 0?typeof oe=="string"?u(K,Y).fill(te,oe):u(K,Y).fill(te):u(K,Y)}(null,S,V,G)},c.allocUnsafe=function(S){return Q(null,S)},c.allocUnsafeSlow=function(S){return Q(null,S)},c.isBuffer=function(S){return!(S==null||!S._isBuffer)},c.compare=function(S,V){if(!c.isBuffer(S)||!c.isBuffer(V))throw new TypeError("Arguments must be Buffers");if(S===V)return 0;for(var G=S.length,K=V.length,Y=0,te=Math.min(G,K);Y<te;++Y)if(S[Y]!==V[Y]){G=S[Y],K=V[Y];break}return G<K?-1:K<G?1:0},c.isEncoding=function(S){switch(String(S).toLowerCase()){case"hex":case"utf8":case"utf-8":case"ascii":case"latin1":case"binary":case"base64":case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return!0;default:return!1}},c.concat=function(S,V){if(!g(S))throw new TypeError('"list" argument must be an Array of Buffers');if(S.length===0)return c.alloc(0);var G;if(V===void 0)for(V=0,G=0;G<S.length;++G)V+=S[G].length;var K=c.allocUnsafe(V),Y=0;for(G=0;G<S.length;++G){var te=S[G];if(!c.isBuffer(te))throw new TypeError('"list" argument must be an Array of Buffers');te.copy(K,Y),Y+=te.length}return K},c.byteLength=U,c.prototype._isBuffer=!0,c.prototype.swap16=function(){var S=this.length;if(S%2!=0)throw new RangeError("Buffer size must be a multiple of 16-bits");for(var V=0;V<S;V+=2)M(this,V,V+1);return this},c.prototype.swap32=function(){var S=this.length;if(S%4!=0)throw new RangeError("Buffer size must be a multiple of 32-bits");for(var V=0;V<S;V+=4)M(this,V,V+3),M(this,V+1,V+2);return this},c.prototype.swap64=function(){var S=this.length;if(S%8!=0)throw new RangeError("Buffer size must be a multiple of 64-bits");for(var V=0;V<S;V+=8)M(this,V,V+7),M(this,V+1,V+6),M(this,V+2,V+5),M(this,V+3,V+4);return this},c.prototype.toString=function(){var S=0|this.length;return S===0?"":arguments.length===0?x(this,0,S):E.apply(this,arguments)},c.prototype.equals=function(S){if(!c.isBuffer(S))throw new TypeError("Argument must be a Buffer");return this===S||c.compare(this,S)===0},c.prototype.inspect=function(){var S="",V=t.INSPECT_MAX_BYTES;return this.length>0&&(S=this.toString("hex",0,V).match(/.{2}/g).join(" "),this.length>V&&(S+=" ... ")),"<Buffer "+S+">"},c.prototype.compare=function(S,V,G,K,Y){if(!c.isBuffer(S))throw new TypeError("Argument must be a Buffer");if(V===void 0&&(V=0),G===void 0&&(G=S?S.length:0),K===void 0&&(K=0),Y===void 0&&(Y=this.length),V<0||G>S.length||K<0||Y>this.length)throw new RangeError("out of range index");if(K>=Y&&V>=G)return 0;if(K>=Y)return-1;if(V>=G)return 1;if(this===S)return 0;for(var te=(Y>>>=0)-(K>>>=0),oe=(G>>>=0)-(V>>>=0),ge=Math.min(te,oe),Se=this.slice(K,Y),ve=S.slice(V,G),ye=0;ye<ge;++ye)if(Se[ye]!==ve[ye]){te=Se[ye],oe=ve[ye];break}return te<oe?-1:oe<te?1:0},c.prototype.includes=function(S,V,G){return this.indexOf(S,V,G)!==-1},c.prototype.indexOf=function(S,V,G){return W(this,S,V,G,!0)},c.prototype.lastIndexOf=function(S,V,G){return W(this,S,V,G,!1)},c.prototype.write=function(S,V,G,K){if(V===void 0)K="utf8",G=this.length,V=0;else if(G===void 0&&typeof V=="string")K=V,G=this.length,V=0;else{if(!isFinite(V))throw new Error("Buffer.write(string, encoding, offset[, length]) is no longer supported");V|=0,isFinite(G)?(G|=0,K===void 0&&(K="utf8")):(K=G,G=void 0)}var Y=this.length-V;if((G===void 0||G>Y)&&(G=Y),S.length>0&&(G<0||V<0)||V>this.length)throw new RangeError("Attempt to write outside buffer bounds");K||(K="utf8");for(var te=!1;;)switch(K){case"hex":return m(this,S,V,G);case"utf8":case"utf-8":return h(this,S,V,G);case"ascii":return T(this,S,V,G);case"latin1":case"binary":return I(this,S,V,G);case"base64":return X(this,S,V,G);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return F(this,S,V,G);default:if(te)throw new TypeError("Unknown encoding: "+K);K=(""+K).toLowerCase(),te=!0}},c.prototype.toJSON=function(){return{type:"Buffer",data:Array.prototype.slice.call(this._arr||this,0)}};function w(S,V,G){var K="";G=Math.min(S.length,G);for(var Y=V;Y<G;++Y)K+=String.fromCharCode(127&S[Y]);return K}function _(S,V,G){var K="";G=Math.min(S.length,G);for(var Y=V;Y<G;++Y)K+=String.fromCharCode(S[Y]);return K}function j(S,V,G){var K=S.length;(!V||V<0)&&(V=0),(!G||G<0||G>K)&&(G=K);for(var Y="",te=V;te<G;++te)Y+=ee(S[te]);return Y}function C(S,V,G){for(var K=S.slice(V,G),Y="",te=0;te<K.length;te+=2)Y+=String.fromCharCode(K[te]+256*K[te+1]);return Y}function J(S,V,G){if(S%1!=0||S<0)throw new RangeError("offset is not uint");if(S+V>G)throw new RangeError("Trying to access beyond buffer length")}function v(S,V,G,K,Y,te){if(!c.isBuffer(S))throw new TypeError('"buffer" argument must be a Buffer instance');if(V>Y||V<te)throw new RangeError('"value" argument is out of bounds');if(G+K>S.length)throw new RangeError("Index out of range")}function D(S,V,G,K){V<0&&(V=65535+V+1);for(var Y=0,te=Math.min(S.length-G,2);Y<te;++Y)S[G+Y]=(V&255<<8*(K?Y:1-Y))>>>8*(K?Y:1-Y)}function A(S,V,G,K){V<0&&(V=4294967295+V+1);for(var Y=0,te=Math.min(S.length-G,4);Y<te;++Y)S[G+Y]=V>>>8*(K?Y:3-Y)&255}function b(S,V,G,K,Y,te){if(G+K>S.length)throw new RangeError("Index out of range");if(G<0)throw new RangeError("Index out of range")}function P(S,V,G,K,Y){return Y||b(S,0,G,4),s.write(S,V,G,K,23,4),G+4}function z(S,V,G,K,Y){return Y||b(S,0,G,8),s.write(S,V,G,K,52,8),G+8}c.prototype.slice=function(S,V){var G,K=this.length;if((S=~~S)<0?(S+=K)<0&&(S=0):S>K&&(S=K),(V=V===void 0?K:~~V)<0?(V+=K)<0&&(V=0):V>K&&(V=K),V<S&&(V=S),c.TYPED_ARRAY_SUPPORT)(G=this.subarray(S,V)).__proto__=c.prototype;else{var Y=V-S;G=new c(Y,void 0);for(var te=0;te<Y;++te)G[te]=this[te+S]}return G},c.prototype.readUIntLE=function(S,V,G){S|=0,V|=0,G||J(S,V,this.length);for(var K=this[S],Y=1,te=0;++te<V&&(Y*=256);)K+=this[S+te]*Y;return K},c.prototype.readUIntBE=function(S,V,G){S|=0,V|=0,G||J(S,V,this.length);for(var K=this[S+--V],Y=1;V>0&&(Y*=256);)K+=this[S+--V]*Y;return K},c.prototype.readUInt8=function(S,V){return V||J(S,1,this.length),this[S]},c.prototype.readUInt16LE=function(S,V){return V||J(S,2,this.length),this[S]|this[S+1]<<8},c.prototype.readUInt16BE=function(S,V){return V||J(S,2,this.length),this[S]<<8|this[S+1]},c.prototype.readUInt32LE=function(S,V){return V||J(S,4,this.length),(this[S]|this[S+1]<<8|this[S+2]<<16)+16777216*this[S+3]},c.prototype.readUInt32BE=function(S,V){return V||J(S,4,this.length),16777216*this[S]+(this[S+1]<<16|this[S+2]<<8|this[S+3])},c.prototype.readIntLE=function(S,V,G){S|=0,V|=0,G||J(S,V,this.length);for(var K=this[S],Y=1,te=0;++te<V&&(Y*=256);)K+=this[S+te]*Y;return K>=(Y*=128)&&(K-=Math.pow(2,8*V)),K},c.prototype.readIntBE=function(S,V,G){S|=0,V|=0,G||J(S,V,this.length);for(var K=V,Y=1,te=this[S+--K];K>0&&(Y*=256);)te+=this[S+--K]*Y;return te>=(Y*=128)&&(te-=Math.pow(2,8*V)),te},c.prototype.readInt8=function(S,V){return V||J(S,1,this.length),128&this[S]?-1*(255-this[S]+1):this[S]},c.prototype.readInt16LE=function(S,V){V||J(S,2,this.length);var G=this[S]|this[S+1]<<8;return 32768&G?4294901760|G:G},c.prototype.readInt16BE=function(S,V){V||J(S,2,this.length);var G=this[S+1]|this[S]<<8;return 32768&G?4294901760|G:G},c.prototype.readInt32LE=function(S,V){return V||J(S,4,this.length),this[S]|this[S+1]<<8|this[S+2]<<16|this[S+3]<<24},c.prototype.readInt32BE=function(S,V){return V||J(S,4,this.length),this[S]<<24|this[S+1]<<16|this[S+2]<<8|this[S+3]},c.prototype.readFloatLE=function(S,V){return V||J(S,4,this.length),s.read(this,S,!0,23,4)},c.prototype.readFloatBE=function(S,V){return V||J(S,4,this.length),s.read(this,S,!1,23,4)},c.prototype.readDoubleLE=function(S,V){return V||J(S,8,this.length),s.read(this,S,!0,52,8)},c.prototype.readDoubleBE=function(S,V){return V||J(S,8,this.length),s.read(this,S,!1,52,8)},c.prototype.writeUIntLE=function(S,V,G,K){S=+S,V|=0,G|=0,K||v(this,S,V,G,Math.pow(2,8*G)-1,0);var Y=1,te=0;for(this[V]=255&S;++te<G&&(Y*=256);)this[V+te]=S/Y&255;return V+G},c.prototype.writeUIntBE=function(S,V,G,K){S=+S,V|=0,G|=0,K||v(this,S,V,G,Math.pow(2,8*G)-1,0);var Y=G-1,te=1;for(this[V+Y]=255&S;--Y>=0&&(te*=256);)this[V+Y]=S/te&255;return V+G},c.prototype.writeUInt8=function(S,V,G){return S=+S,V|=0,G||v(this,S,V,1,255,0),c.TYPED_ARRAY_SUPPORT||(S=Math.floor(S)),this[V]=255&S,V+1},c.prototype.writeUInt16LE=function(S,V,G){return S=+S,V|=0,G||v(this,S,V,2,65535,0),c.TYPED_ARRAY_SUPPORT?(this[V]=255&S,this[V+1]=S>>>8):D(this,S,V,!0),V+2},c.prototype.writeUInt16BE=function(S,V,G){return S=+S,V|=0,G||v(this,S,V,2,65535,0),c.TYPED_ARRAY_SUPPORT?(this[V]=S>>>8,this[V+1]=255&S):D(this,S,V,!1),V+2},c.prototype.writeUInt32LE=function(S,V,G){return S=+S,V|=0,G||v(this,S,V,4,4294967295,0),c.TYPED_ARRAY_SUPPORT?(this[V+3]=S>>>24,this[V+2]=S>>>16,this[V+1]=S>>>8,this[V]=255&S):A(this,S,V,!0),V+4},c.prototype.writeUInt32BE=function(S,V,G){return S=+S,V|=0,G||v(this,S,V,4,4294967295,0),c.TYPED_ARRAY_SUPPORT?(this[V]=S>>>24,this[V+1]=S>>>16,this[V+2]=S>>>8,this[V+3]=255&S):A(this,S,V,!1),V+4},c.prototype.writeIntLE=function(S,V,G,K){if(S=+S,V|=0,!K){var Y=Math.pow(2,8*G-1);v(this,S,V,G,Y-1,-Y)}var te=0,oe=1,ge=0;for(this[V]=255&S;++te<G&&(oe*=256);)S<0&&ge===0&&this[V+te-1]!==0&&(ge=1),this[V+te]=(S/oe>>0)-ge&255;return V+G},c.prototype.writeIntBE=function(S,V,G,K){if(S=+S,V|=0,!K){var Y=Math.pow(2,8*G-1);v(this,S,V,G,Y-1,-Y)}var te=G-1,oe=1,ge=0;for(this[V+te]=255&S;--te>=0&&(oe*=256);)S<0&&ge===0&&this[V+te+1]!==0&&(ge=1),this[V+te]=(S/oe>>0)-ge&255;return V+G},c.prototype.writeInt8=function(S,V,G){return S=+S,V|=0,G||v(this,S,V,1,127,-128),c.TYPED_ARRAY_SUPPORT||(S=Math.floor(S)),S<0&&(S=255+S+1),this[V]=255&S,V+1},c.prototype.writeInt16LE=function(S,V,G){return S=+S,V|=0,G||v(this,S,V,2,32767,-32768),c.TYPED_ARRAY_SUPPORT?(this[V]=255&S,this[V+1]=S>>>8):D(this,S,V,!0),V+2},c.prototype.writeInt16BE=function(S,V,G){return S=+S,V|=0,G||v(this,S,V,2,32767,-32768),c.TYPED_ARRAY_SUPPORT?(this[V]=S>>>8,this[V+1]=255&S):D(this,S,V,!1),V+2},c.prototype.writeInt32LE=function(S,V,G){return S=+S,V|=0,G||v(this,S,V,4,2147483647,-2147483648),c.TYPED_ARRAY_SUPPORT?(this[V]=255&S,this[V+1]=S>>>8,this[V+2]=S>>>16,this[V+3]=S>>>24):A(this,S,V,!0),V+4},c.prototype.writeInt32BE=function(S,V,G){return S=+S,V|=0,G||v(this,S,V,4,2147483647,-2147483648),S<0&&(S=4294967295+S+1),c.TYPED_ARRAY_SUPPORT?(this[V]=S>>>24,this[V+1]=S>>>16,this[V+2]=S>>>8,this[V+3]=255&S):A(this,S,V,!1),V+4},c.prototype.writeFloatLE=function(S,V,G){return P(this,S,V,!0,G)},c.prototype.writeFloatBE=function(S,V,G){return P(this,S,V,!1,G)},c.prototype.writeDoubleLE=function(S,V,G){return z(this,S,V,!0,G)},c.prototype.writeDoubleBE=function(S,V,G){return z(this,S,V,!1,G)},c.prototype.copy=function(S,V,G,K){if(G||(G=0),K||K===0||(K=this.length),V>=S.length&&(V=S.length),V||(V=0),K>0&&K<G&&(K=G),K===G||S.length===0||this.length===0)return 0;if(V<0)throw new RangeError("targetStart out of bounds");if(G<0||G>=this.length)throw new RangeError("sourceStart out of bounds");if(K<0)throw new RangeError("sourceEnd out of bounds");K>this.length&&(K=this.length),S.length-V<K-G&&(K=S.length-V+G);var Y,te=K-G;if(this===S&&G<V&&V<K)for(Y=te-1;Y>=0;--Y)S[Y+V]=this[Y+G];else if(te<1e3||!c.TYPED_ARRAY_SUPPORT)for(Y=0;Y<te;++Y)S[Y+V]=this[Y+G];else Uint8Array.prototype.set.call(S,this.subarray(G,G+te),V);return te},c.prototype.fill=function(S,V,G,K){if(typeof S=="string"){if(typeof V=="string"?(K=V,V=0,G=this.length):typeof G=="string"&&(K=G,G=this.length),S.length===1){var Y=S.charCodeAt(0);Y<256&&(S=Y)}if(K!==void 0&&typeof K!="string")throw new TypeError("encoding must be a string");if(typeof K=="string"&&!c.isEncoding(K))throw new TypeError("Unknown encoding: "+K)}else typeof S=="number"&&(S&=255);if(V<0||this.length<V||this.length<G)throw new RangeError("Out of range index");if(G<=V)return this;var te;if(V>>>=0,G=G===void 0?this.length:G>>>0,S||(S=0),typeof S=="number")for(te=V;te<G;++te)this[te]=S;else{var oe=c.isBuffer(S)?S:re(new c(S,K).toString()),ge=oe.length;for(te=0;te<G-V;++te)this[te+V]=oe[te%ge]}return this};var $=/[^+\/0-9A-Za-z-_]/g;function ee(S){return S<16?"0"+S.toString(16):S.toString(16)}function re(S,V){var G;V=V||1/0;for(var K=S.length,Y=null,te=[],oe=0;oe<K;++oe){if((G=S.charCodeAt(oe))>55295&&G<57344){if(!Y){if(G>56319){(V-=3)>-1&&te.push(239,191,189);continue}if(oe+1===K){(V-=3)>-1&&te.push(239,191,189);continue}Y=G;continue}if(G<56320){(V-=3)>-1&&te.push(239,191,189),Y=G;continue}G=65536+(Y-55296<<10|G-56320)}else Y&&(V-=3)>-1&&te.push(239,191,189);if(Y=null,G<128){if((V-=1)<0)break;te.push(G)}else if(G<2048){if((V-=2)<0)break;te.push(G>>6|192,63&G|128)}else if(G<65536){if((V-=3)<0)break;te.push(G>>12|224,G>>6&63|128,63&G|128)}else{if(!(G<1114112))throw new Error("Invalid code point");if((V-=4)<0)break;te.push(G>>18|240,G>>12&63|128,G>>6&63|128,63&G|128)}}return te}function O(S){return o.toByteArray(function(V){if((V=function(G){return G.trim?G.trim():G.replace(/^\s+|\s+$/g,"")}(V).replace($,"")).length<2)return"";for(;V.length%4!=0;)V+="=";return V}(S))}function k(S,V,G,K){for(var Y=0;Y<K&&!(Y+G>=V.length||Y>=S.length);++Y)V[Y+G]=S[Y];return Y}}).call(this,n(6))},function(e,t){var n;n=function(){return this}();try{n=n||new Function("return this")()}catch{typeof window=="object"&&(n=window)}e.exports=n},function(e,t){typeof Object.create=="function"?e.exports=function(n,r){r&&(n.super_=r,n.prototype=Object.create(r.prototype,{constructor:{value:n,enumerable:!1,writable:!0,configurable:!0}}))}:e.exports=function(n,r){if(r){n.super_=r;var o=function(){};o.prototype=r.prototype,n.prototype=new o,n.prototype.constructor=n}}},function(e,t,n){function r(Q){return(r=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(f){return typeof f}:function(f){return f&&typeof Symbol=="function"&&f.constructor===Symbol&&f!==Symbol.prototype?"symbol":typeof f})(Q)}function o(Q,f){if(f&&(r(f)==="object"||typeof f=="function"))return f;if(f!==void 0)throw new TypeError("Derived constructors may only return object or undefined");return s(Q)}function s(Q){if(Q===void 0)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return Q}function g(Q){var f=typeof Map=="function"?new Map:void 0;return(g=function(p){if(p===null||(U=p,Function.toString.call(U).indexOf("[native code]")===-1))return p;var U;if(typeof p!="function")throw new TypeError("Super expression must either be null or a function");if(f!==void 0){if(f.has(p))return f.get(p);f.set(p,E)}function E(){return l(p,arguments,d(this).constructor)}return E.prototype=Object.create(p.prototype,{constructor:{value:E,enumerable:!1,writable:!0,configurable:!0}}),c(E,p)})(Q)}function l(Q,f,p){return(l=u()?Reflect.construct.bind():function(U,E,M){var W=[null];W.push.apply(W,E);var y=new(Function.bind.apply(U,W));return M&&c(y,M.prototype),y}).apply(null,arguments)}function u(){if(typeof Reflect=="undefined"||!Reflect.construct||Reflect.construct.sham)return!1;if(typeof Proxy=="function")return!0;try{return Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],function(){})),!0}catch{return!1}}function c(Q,f){return(c=Object.setPrototypeOf?Object.setPrototypeOf.bind():function(p,U){return p.__proto__=U,p})(Q,f)}function d(Q){return(d=Object.setPrototypeOf?Object.getPrototypeOf.bind():function(f){return f.__proto__||Object.getPrototypeOf(f)})(Q)}var B=function(Q){(function(W,y){if(typeof y!="function"&&y!==null)throw new TypeError("Super expression must either be null or a function");W.prototype=Object.create(y&&y.prototype,{constructor:{value:W,writable:!0,configurable:!0}}),Object.defineProperty(W,"prototype",{writable:!1}),y&&c(W,y)})(M,Q);var f,p,U,E=(f=M,p=u(),function(){var W,y=d(f);if(p){var m=d(this).constructor;W=Reflect.construct(y,arguments,m)}else W=y.apply(this,arguments);return o(this,W)});function M(W){var y;return function(m,h){if(!(m instanceof h))throw new TypeError("Cannot call a class as a function")}(this,M),y=E.call(this,`Format functions must be synchronous taking a two arguments: (info, opts)
3
3
  Found: `.concat(W.toString().split(`
4
4
  `)[0],`
@@ -59,7 +59,7 @@ In order to be iterable, non-array objects must have a [Symbol.iterator]() metho
59
59
  `))},g.prototype.close=function(){this.transport.close&&this.transport.close(),this.transport.__winstonError&&(this.transport.removeListener("error",this.transport.__winstonError),this.transport.__winstonError=null)}},function(e,t,n){function r(s){return(r=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(g){return typeof g}:function(g){return g&&typeof Symbol=="function"&&g.constructor===Symbol&&g!==Symbol.prototype?"symbol":typeof g})(s)}function o(s,g){for(var l=0;l<g.length;l++){var u=g[l];u.enumerable=u.enumerable||!1,u.configurable=!0,"value"in u&&(u.writable=!0),Object.defineProperty(s,u.key,u)}}e.exports=function(){function s(u){if(function(c,d){if(!(c instanceof d))throw new TypeError("Cannot call a class as a function")}(this,s),!u)throw new Error("Logger is required for profiling.");this.logger=u,this.start=Date.now()}var g,l;return g=s,(l=[{key:"done",value:function(){for(var u=arguments.length,c=new Array(u),d=0;d<u;d++)c[d]=arguments[d];typeof c[c.length-1]=="function"&&(console.warn("Callback function no longer supported as of winston@3.0.0"),c.pop());var B=r(c[c.length-1])==="object"?c.pop():{};return B.level=B.level||"info",B.durationMs=Date.now()-this.start,this.logger.write(B)}}])&&o(g.prototype,l),Object.defineProperty(g,"prototype",{writable:!1}),s}()},function(e,t,n){const r=n(214),{MESSAGE:o}=n(4),s=n(29);function g(l,u){return typeof u=="bigint"?u.toString():u}e.exports=r((l,u)=>{const c=s.configure(u);return l[o]=c(l,u.replacer||g,u.space),l})},function(e,t,n){class r extends Error{constructor(s){super(`Format functions must be synchronous taking a two arguments: (info, opts)
60
60
  Found: ${s.toString().split(`
61
61
  `)[0]}
62
- `),Error.captureStackTrace(this,r)}}e.exports=o=>{if(o.length>2)throw new r(o);function s(l={}){this.options=l}function g(l){return new s(l)}return s.prototype.transform=o,g.Format=s,g}},function(e,t,n){function r(g,l){if(!(g instanceof l))throw new TypeError("Cannot call a class as a function")}function o(g,l){for(var u=0;u<l.length;u++){var c=l[u];c.enumerable=c.enumerable||!1,c.configurable=!0,"value"in c&&(c.writable=!0),Object.defineProperty(g,c.key,c)}}var s=n(87);e.exports=function(){function g(){var c=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};r(this,g),this.loggers=new Map,this.options=c}var l,u;return l=g,(u=[{key:"add",value:function(c,d){var B=this;if(!this.loggers.has(c)){var Q=(d=Object.assign({},d||this.options)).transports||this.options.transports;d.transports=Q?Q.slice():[];var f=s(d);f.on("close",function(){return B._delete(c)}),this.loggers.set(c,f)}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(B,Q){return d._removeLogger(Q)})}},{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(l.prototype,u),Object.defineProperty(l,"prototype",{writable:!1}),g}()},function(e,t,n){(function(r){const o=n(51),s=/^([A-Za-z0-9+/]{4})*([A-Za-z0-9+/]{4}|[A-Za-z0-9+/]{3}=|[A-Za-z0-9+/]{2}==)$/;e.exports=function(g,l,u,c){let d,B,Q=!1,f=!1;const p=n(93);function U(W){c(l,W)}function E(W,y){let m=`"${l}" ${y}`;throw W&&(m=""+m),B&&(m=`${m}. An example of a valid value would be: ${B}`),new o(m)}const M={convertFromBase64:function(){return U("marking for base64 conversion"),Q=!0,M},default:function(W){if(typeof W=="number")d=W.toString();else if(Array.isArray(W)||typeof W=="object"&&W!==null)d=JSON.stringify(W);else{if(typeof W!="string")throw new o("values passed to default() must be of Number, String, Array, or Object type");d=W}return U(`setting default value to "${d}"`),M},required:function(W){return W===void 0?(U("marked as required"),f=!0):(U("setting required flag to "+W),f=W),M},example:function(W){return B=W,M}};return Object.entries({...p,...u}).forEach(([W,y])=>{M[W]=function(m){return function(){let h=g[l];if(U(`will be read from the environment using "${m.name}" accessor`),h===void 0)if(d===void 0&&f)U("was not found in the environment, but is required to be set"),E(void 0,"is a required variable, but it was not set");else{if(d===void 0)return void U("was not found in the environment, but is not required. returning undefined");U(`was not found in the environment, parsing default value "${d}" instead`),h=d}f&&(U("verifying variable value is not an empty string"),h.trim().length===0&&E(void 0,"is a required variable, but its value was empty")),Q&&(U("verifying variable is a valid base64 string"),h.match(s)||E(h,"should be a valid base64 string if using convertFromBase64"),U("converting from base64 to utf8 string"),h=r.from(h,"base64").toString());const T=[h].concat(Array.prototype.slice.call(arguments));try{U(`passing value "${h}" to "${m.name}" accessor`);const I=m.apply(m,T);return U("parsed successfully, returning "+I),I}catch(I){E(h,I.message)}}}(y)}),M}}).call(this,n(5).Buffer)},function(e,t,n){const r=n(34);e.exports=function(o,s){return s=s||",",o.length?r(o).split(s).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(94);e.exports=function(o){var s=r(o);if(s>65535)throw new Error("cannot assign a port number greater than 65535");return s}},function(e,t,n){const r=n(34);e.exports=function(o,s){const g=r(o);if(s.indexOf(g)<0)throw new Error(`should be one of [${s.join(", ")}]`);return g}},function(e,t,n){const r=n(53);e.exports=function(o){const s=r(o);if(s>0)throw new Error("should be a negative float");return s}},function(e,t,n){const r=n(53);e.exports=function(o){const s=r(o);if(s<0)throw new Error("should be a positive float");return s}},function(e,t,n){const r=n(52);e.exports=function(o){const s=r(o);if(s>0)throw new Error("should be a negative integer");return s}},function(e,t,n){const r=n(54);e.exports=function(o){var s=r(o);if(!Array.isArray(s))throw new Error("should be a parseable JSON Array");return s}},function(e,t,n){const r=n(54);e.exports=function(o){var s=r(o);if(Array.isArray(s))throw new Error("should be a parseable JSON Object");return s}},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(95);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(s){const g=r(s);if(!o.test(g))throw new Error("should be a valid email address");return g}},function(e,t,n){e.exports=function(r,o){return function(s,g){o&&o.match(/prod|production/)||r(`env-var (${s}): ${g}`)}}},function(e,t,n){(function(r){(function(){var o,s,g,l,u,c;typeof performance!="undefined"&&performance!==null&&performance.now?e.exports=function(){return performance.now()}:r!=null&&r.hrtime?(e.exports=function(){return(o()-u)/1e6},s=r.hrtime,l=(o=function(){var d;return 1e9*(d=s())[0]+d[1]})(),c=1e9*r.uptime(),u=l-c):Date.now?(e.exports=function(){return Date.now()-g},g=Date.now()):(e.exports=function(){return new Date().getTime()-g},g=new Date().getTime())}).call(this)}).call(this,n(2))},function(e,t,n){(function(r){(function(o){function s(l){if((l=l===void 0?"utf-8":l)!=="utf-8")throw new RangeError("Failed to construct 'TextEncoder': The encoding label provided ('"+l+"') is invalid.")}function g(l,u){if(u=u===void 0?{fatal:!1}:u,(l=l===void 0?"utf-8":l)!=="utf-8")throw new RangeError("Failed to construct 'TextDecoder': The encoding label provided ('"+l+"') is invalid.");if(u.fatal)throw Error("Failed to construct 'TextDecoder': the 'fatal' option is unsupported.")}if(o.TextEncoder&&o.TextDecoder)return!1;Object.defineProperty(s.prototype,"encoding",{value:"utf-8"}),s.prototype.encode=function(l,u){if((u=u===void 0?{stream:!1}:u).stream)throw Error("Failed to encode: the 'stream' option is unsupported.");u=0;for(var c=l.length,d=0,B=Math.max(32,c+(c>>1)+7),Q=new Uint8Array(B>>3<<3);u<c;){var f=l.charCodeAt(u++);if(55296<=f&&56319>=f){if(u<c){var p=l.charCodeAt(u);(64512&p)==56320&&(++u,f=((1023&f)<<10)+(1023&p)+65536)}if(55296<=f&&56319>=f)continue}if(d+4>Q.length&&(B+=8,B=(B*=1+u/l.length*2)>>3<<3,(p=new Uint8Array(B)).set(Q),Q=p),(4294967168&f)==0)Q[d++]=f;else{if(!(4294965248&f))Q[d++]=f>>6&31|192;else if(!(4294901760&f))Q[d++]=f>>12&15|224,Q[d++]=f>>6&63|128;else{if(4292870144&f)continue;Q[d++]=f>>18&7|240,Q[d++]=f>>12&63|128,Q[d++]=f>>6&63|128}Q[d++]=63&f|128}}return Q.slice(0,d)},Object.defineProperty(g.prototype,"encoding",{value:"utf-8"}),Object.defineProperty(g.prototype,"fatal",{value:!1}),Object.defineProperty(g.prototype,"ignoreBOM",{value:!1}),g.prototype.decode=function(l,u){if((u=u===void 0?{stream:!1}:u).stream)throw Error("Failed to decode: the 'stream' option is unsupported.");u=0;for(var c=(l=new Uint8Array(l)).length,d=[];u<c;){var B=l[u++];if(B===0)break;if(!(128&B))d.push(B);else if((224&B)==192){var Q=63&l[u++];d.push((31&B)<<6|Q)}else if((240&B)==224){Q=63&l[u++];var f=63&l[u++];d.push((31&B)<<12|Q<<6|f)}else(248&B)==240&&(65535<(B=(7&B)<<18|(Q=63&l[u++])<<12|(f=63&l[u++])<<6|63&l[u++])&&(B-=65536,d.push(B>>>10&1023|55296),B=56320|1023&B),d.push(B))}return String.fromCharCode.apply(null,d)},o.TextEncoder=s,o.TextDecoder=g})(typeof window!="undefined"?window:r!==void 0?r:this)}).call(this,n(6))},function(e,t,n){n.r(t),n.d(t,"AuthClient",function(){return s}),n.d(t,"RtcSignalingClient",function(){return l}),n.d(t,"Credentials",function(){return C}),n.d(t,"SignalingPromiseClient",function(){return J.SignalingPromiseClient}),n.d(t,"RtcClient",function(){return It}),n.d(t,"RtcClientV1",function(){return Ct}),n.d(t,"createRtcStreamMessage",function(){return wt});var r=n(26),o=function(Re,Z,L,q){return new(L||(L=Promise))(function(ie,se){function ue(ce){try{Ue(q.next(ce))}catch(le){se(le)}}function fe(ce){try{Ue(q.throw(ce))}catch(le){se(le)}}function Ue(ce){var le;ce.done?ie(ce.value):(le=ce.value,le instanceof L?le:new L(function(me){me(le)})).then(ue,fe)}Ue((q=q.apply(Re,Z||[])).next())})};class s extends r.a{adminSignup(Z,L){return o(this,void 0,void 0,function*(){return yield this.fetch("auth/admin-signup",{token:L,method:"POST",body:Z})})}login(Z){return o(this,void 0,void 0,function*(){return yield this.fetch("auth/login",{method:"POST",body:Z,allowUnsafeRetries:!0})})}loginWithGoogleToken(Z){return o(this,void 0,void 0,function*(){return yield this.fetch("auth/login-google",{method:"POST",body:Z,allowUnsafeRetries:!0})})}refresh(Z,L){return o(this,void 0,void 0,function*(){return yield this.fetch("auth/refresh",{method:"POST",body:{refreshToken:Z,tokenExpirationSeconds:L},allowUnsafeRetries:!0})})}respondToNewPasswordRequiredChallenge(Z){return o(this,void 0,void 0,function*(){return yield this.fetch("auth/respond-to-new-password-required-challenge",{method:"POST",body:Z})})}forgotPassword(Z){return o(this,void 0,void 0,function*(){return yield this.fetch("auth/forgot-password",{method:"POST",body:{email:Z}})})}confirmForgotPassword(Z){return o(this,void 0,void 0,function*(){return yield this.fetch("auth/confirm-forgot-password",{method:"POST",body:Z})})}resendInvitation(Z){return o(this,void 0,void 0,function*(){return yield this.fetch("auth/resend-invitation",{method:"POST",body:{email:Z}})})}changePassword({token:Z,refreshToken:L,currentPassword:q,newPassword:ie}){return o(this,void 0,void 0,function*(){return yield this.fetch("auth/change-password",{token:Z,method:"POST",body:{refreshToken:L,currentPassword:q,newPassword:ie}})})}getDeviceCredentials(Z){return o(this,void 0,void 0,function*(){return yield this.fetch("auth/device-credentials",{token:Z,method:"POST",allowUnsafeRetries:!0})})}impersonate(Z,L){return o(this,void 0,void 0,function*(){return yield this.fetch("auth/impersonate",{token:Z,method:"POST",allowUnsafeRetries:!0,body:{userId:L}})})}createServiceAccount(Z,L,q,ie){return o(this,void 0,void 0,function*(){return yield this.fetch("auth/service-account",{token:Z,method:"POST",allowUnsafeRetries:!0,body:{name:L,roleId:q,tags:ie}})})}getFeatures(Z){return o(this,void 0,void 0,function*(){return(yield this.fetch("auth/features",{token:Z})).features})}checkSso(Z,L){return o(this,void 0,void 0,function*(){return yield this.fetch("auth/check-sso",{method:"POST",body:{email:Z,allowUserAutoCreation:L}})})}loginWithSso(Z,L){return o(this,void 0,void 0,function*(){return yield this.fetch("auth/login-sso",{method:"POST",body:{token:Z,refreshToken:L}})})}}var g=function(Re,Z,L,q){return new(L||(L=Promise))(function(ie,se){function ue(ce){try{Ue(q.next(ce))}catch(le){se(le)}}function fe(ce){try{Ue(q.throw(ce))}catch(le){se(le)}}function Ue(ce){var le;ce.done?ie(ce.value):(le=ce.value,le instanceof L?le:new L(function(me){me(le)})).then(ue,fe)}Ue((q=q.apply(Re,Z||[])).next())})};class l extends r.a{createPeer(Z,L){return g(this,void 0,void 0,function*(){return yield this.fetch("peers",{token:Z,method:"POST",body:L})})}getPeers(Z){return g(this,void 0,void 0,function*(){return(yield this.fetch("peers",{token:Z})).items})}refreshPeer(Z,L){return g(this,void 0,void 0,function*(){yield this.fetch(`peers/${L}/refresh`,{token:Z,method:"POST",allowUnsafeRetries:!0})})}createSession(Z,L){return g(this,void 0,void 0,function*(){return yield this.fetch("sessions",{token:Z,method:"POST",body:L})})}refreshSession(Z,L){return g(this,void 0,void 0,function*(){yield this.fetch(`sessions/${L}/refresh`,{token:Z,method:"POST",allowUnsafeRetries:!0})})}deleteSession(Z,L){return g(this,void 0,void 0,function*(){yield this.fetch("sessions/"+L,{token:Z,method:"DELETE",allowUnsafeRetries:!0})})}getSessions(Z){return g(this,void 0,void 0,function*(){return(yield this.fetch("sessions",{token:Z})).items})}getIceServers(Z){return g(this,void 0,void 0,function*(){return(yield this.fetch("ice-servers",{token:Z})).items})}addSignals(Z,L,q){return g(this,void 0,void 0,function*(){yield this.fetch(`sessions/${L}/add-signals`,{token:Z,method:"POST",body:q})})}takeSignals(Z,L){return g(this,void 0,void 0,function*(){return(yield this.fetch(`sessions/${L}/take-signals`,{token:Z,method:"POST"})).items})}}var u=n(1),c=n(9),d=n(15),B=n.n(d),Q=n(101),f=n.n(Q),p=n(3),U=n(0),E=function(Re,Z,L,q){return new(L||(L=Promise))(function(ie,se){function ue(ce){try{Ue(q.next(ce))}catch(le){se(le)}}function fe(ce){try{Ue(q.throw(ce))}catch(le){se(le)}}function Ue(ce){var le;ce.done?ie(ce.value):(le=ce.value,le instanceof L?le:new L(function(me){me(le)})).then(ue,fe)}Ue((q=q.apply(Re,Z||[])).next())})};class M extends class{constructor(Z,L){this.type=Z,this.name=L}}{constructor(Z){super("simple","LogReporter"),this.message=Z}send(Z){return E(this,void 0,void 0,function*(){var L,q;U.a.debug(this.message,(L=Z.reduce((ie,se)=>Object.assign(Object.assign({},ie),{[se.name]:se.stat}),{}),q=ie=>{const{sum:se,count:ue}=ie,fe=se/ue;return Object.assign(Object.assign({},ie),{average:fe})},Object.keys(L).reduce((ie,se)=>Object.assign(Object.assign({},ie),{[se]:q(L[se])}),{})))})}}const W=/^[a-zA-Z0-9-_.,:?'"()@\/\\#$+ ]{1,255}$/,y=/^[*a-zA-Z0-9-_.,:?'"()@\/\\#$+ ]{1,255}$/;function m(Re,Z=!1){return!!(Re!=null&&Re.match(Z?y:W))}var h=function(Re,Z,L,q){return new(L||(L=Promise))(function(ie,se){function ue(ce){try{Ue(q.next(ce))}catch(le){se(le)}}function fe(ce){try{Ue(q.throw(ce))}catch(le){se(le)}}function Ue(ce){var le;ce.done?ie(ce.value):(le=ce.value,le instanceof L?le:new L(function(me){me(le)})).then(ue,fe)}Ue((q=q.apply(Re,Z||[])).next())})};function T({func:Re,delay:Z,immediate:L=!1}){let q=!1,ie=setTimeout(function ue(){return h(this,void 0,void 0,function*(){if(q)return;const fe=new Date().getTime();try{se=Re(),yield se}finally{if(!q){const Ue=new Date().getTime();ie=setTimeout(ue,Math.max(Z-(Ue-fe),0))}}})},L?0:Z),se=Promise.resolve();return{stop(){return h(this,void 0,void 0,function*(){q=!0,clearTimeout(ie),yield se})}}}var I=function(Re,Z,L,q){return new(L||(L=Promise))(function(ie,se){function ue(ce){try{Ue(q.next(ce))}catch(le){se(le)}}function fe(ce){try{Ue(q.throw(ce))}catch(le){se(le)}}function Ue(ce){var le;ce.done?ie(ce.value):(le=ce.value,le instanceof L?le:new L(function(me){me(le)})).then(ue,fe)}Ue((q=q.apply(Re,Z||[])).next())})};const X=n(231);class F{constructor(Z){this.buffer={},this.reporters=[],this.flushInterval=T({func:()=>this.flushStats(),delay:F.samplePeriodMs}),this.tags=this.filterTags((Z==null?void 0:Z.tags)||{app:p.a,version:p.k,namespace:p.j})}shutdown(){return I(this,void 0,void 0,function*(){yield this.flushInterval.stop(),yield this.flushStats(),yield Object(c.a)(2*u.a.second)})}aggregate(Z,L,q){this.addToBuffer(this.buffer,this.encodeKey({metric:Z,tags:this.filterTags(q||{})}),typeof L=="number"?{min:L,max:L,sum:L,count:1}:L)}increment(Z,L){this.aggregate(Z,1,L)}timer(Z,L,q){return I(this,void 0,void 0,function*(){const ie=X(),se=yield L(),ue=X();return this.aggregate(Z,ue-ie,q),se})}registerStatsReporter(Z){this.reporters.push(Z)}setTag(Z,L){const q=this.filterTags({[Z]:L});this.tags=Object.assign(Object.assign({},this.tags),q)}addToBuffer(Z,L,q){if(Z[L]){const{min:ie,max:se,sum:ue,count:fe}=Z[L];Z[L]={min:Math.min(ie,q.min),max:Math.max(se,q.max),sum:ue+q.sum,count:fe+q.count}}else Z[L]=q}write(Z){return I(this,void 0,void 0,function*(){yield Promise.all(this.reporters.map(L=>I(this,void 0,void 0,function*(){let q;const ie={};switch(L.type){case"simple":for(const[ue,fe]of Object.entries(Z)){const{metric:Ue}=this.decodeKey(ue);this.addToBuffer(ie,this.encodeKey({metric:Ue}),fe)}q=ie;break;case"tagged":q=Z;break;default:(function(ue){throw new Error(`Unreachable type encountered (${ue})`)})(L.type)}const se=Object.entries(q);if(se.length>0)return L.send(se.map(([ue,fe])=>{const{metric:Ue,tags:ce}=this.decodeKey(ue);return{name:Ue,tags:Object.assign(Object.assign({},ce),this.tags),stat:fe}}),F.samplePeriodMs).catch(ue=>{U.a.debug("Failed to write stats to "+L.name,{error:ue})})})))})}flushStats(){return I(this,void 0,void 0,function*(){yield this.write(this.buffer),this.buffer={}})}encodeKey(Z){return B()(Object.assign(Object.assign({},Z),Object.keys(Z.tags||{}).length>0?{tags:Z.tags}:{}))}decodeKey(Z){return JSON.parse(Z)}filterTags(Z){return Object.entries(Z||{}).reduce((L,[q,ie])=>(m(q)&&m(ie)&&(L[q]=ie),L),{})}}F.samplePeriodMs=5*u.a.minute;const R=!!p.d,x=new F;R||["local","on-prem"].includes(p.j)||x.registerStatsReporter(new M("stats"));var w=function(Re,Z,L,q){return new(L||(L=Promise))(function(ie,se){function ue(ce){try{Ue(q.next(ce))}catch(le){se(le)}}function fe(ce){try{Ue(q.throw(ce))}catch(le){se(le)}}function Ue(ce){var le;ce.done?ie(ce.value):(le=ce.value,le instanceof L?le:new L(function(me){me(le)})).then(ue,fe)}Ue((q=q.apply(Re,Z||[])).next())})};class _ extends class{constructor(Z){this.options=Z,this.cache=new f.a(Object.assign(Object.assign(Object.assign({},Z.dispose||Z.disposeAfter?{ttlAutopurge:!0}:{}),Z),{dispose:(...L)=>{var q;L[2]==="evict"&&x.increment("lru-eviction",{name:Z.name}),(q=Z.dispose)===null||q===void 0||q.call(Z,...L)},disposeAfter:(...L)=>{var q;this.updateStats(),(q=Z.disposeAfter)===null||q===void 0||q.call(Z,...L)}})),this.stringify=Z.fastStringify?JSON.stringify:B.a}set(Z,L,q){const ie=this.stringify(Z);if(!this.cache.set(ie,L,{ttl:q})){const se=this.cache.sizeCalculation?this.cache.sizeCalculation(L,ie):"unknown";throw Error(`Value too large (${se} > ${this.cache.max})`)}this.updateStats()}get(Z){const{name:L}=this.options,q=this.stringify(Z),ie=this.cache.getRemainingTTL(q);return ie<=0?x.increment("cache-miss",{name:L}):ie!==1/0&&x.aggregate("cache-item-ttl",ie,{name:L}),this.cache.get(q)}delete(Z){this.cache.delete(this.stringify(Z))}peek(Z){return this.cache.peek(this.stringify(Z))}size(){return this.cache.size}clear(){this.cache.clear()}forEach(Z){this.cache.forEach(Z)}purgeStale(){return this.cache.purgeStale()}updateStats(){const{name:Z}=this.options;x.aggregate("cache-item-count",this.cache.size,{name:Z}),this.cache.calculatedSize!==void 0&&x.aggregate("cache-length",this.cache.calculatedSize,{name:Z})}}{constructor(Z){if(super(Z),this.expireRejectedPromiseValues=Z.expireRejectedPromiseValues===void 0||Z.expireRejectedPromiseValues,this.rejectedPromiseValueTtl=Z.rejectedPromiseValueTtl!==void 0?Z.rejectedPromiseValueTtl:u.a.second,this.rejectedPromiseValueTtl<0)throw new Error("rejectedPromiseValueTtl must not be negative")}set(Z,L,q){super.set(Z,L,q),this.expireRejectedPromiseValues&&L.catch(()=>w(this,void 0,void 0,function*(){yield Object(c.a)(this.rejectedPromiseValueTtl),this.peek(Z)===L&&this.delete(Z)}))}}var j=function(Re,Z,L,q){return new(L||(L=Promise))(function(ie,se){function ue(ce){try{Ue(q.next(ce))}catch(le){se(le)}}function fe(ce){try{Ue(q.throw(ce))}catch(le){se(le)}}function Ue(ce){var le;ce.done?ie(ce.value):(le=ce.value,le instanceof L?le:new L(function(me){me(le)})).then(ue,fe)}Ue((q=q.apply(Re,Z||[])).next())})};class C{constructor(Z,L,q){this.authClient=Z,this.email=L,this.password=q,this.tokenTtlMs=1*u.a.hour,this.tokenCache=new _({name:"Credentials-tokenCache",max:100,ttl:this.tokenTtlMs-5*u.a.minute,fastStringify:!0})}getToken(){return j(this,void 0,void 0,function*(){let Z=this.tokenCache.get(this.email);return Z||(Z=(()=>j(this,void 0,void 0,function*(){const{authentication:L}=yield this.authClient.login({email:this.email,password:this.password,tokenExpirationSeconds:this.tokenTtlMs/u.a.second});if(!L)throw new Error("User account not verified.");return L.accessToken}))(),this.tokenCache.set(this.email,Z)),Z})}}var J=n(96),v=n(17),D=n(236),A=n(41),b=function(Re,Z,L,q){return new(L||(L=Promise))(function(ie,se){function ue(ce){try{Ue(q.next(ce))}catch(le){se(le)}}function fe(ce){try{Ue(q.throw(ce))}catch(le){se(le)}}function Ue(ce){var le;ce.done?ie(ce.value):(le=ce.value,le instanceof L?le:new L(function(me){me(le)})).then(ue,fe)}Ue((q=q.apply(Re,Z||[])).next())})};class P extends A.a{constructor(Z){super(Z)}postLanRtcOffer(Z){return b(this,void 0,void 0,function*(){return yield this.fetch("v1/lan-rtc-offer",{method:"POST",body:Z})})}}var z=function(Re,Z,L,q){return new(L||(L=Promise))(function(ie,se){function ue(ce){try{Ue(q.next(ce))}catch(le){se(le)}}function fe(ce){try{Ue(q.throw(ce))}catch(le){se(le)}}function Ue(ce){var le;ce.done?ie(ce.value):(le=ce.value,le instanceof L?le:new L(function(me){me(le)})).then(ue,fe)}Ue((q=q.apply(Re,Z||[])).next())})};function $(Re){return z(this,void 0,void 0,function*(){return(yield Promise.all(Re.map(Z=>Z.catch(L=>L)))).filter(Z=>Z instanceof Error)})}function ee(Re,Z){if(Re===void 0)throw new Error("Value is undefined"+(Z?": "+Z:""))}function re(Re,Z){if(Re===null)throw new Error("Value is null"+(Z?": "+Z:""))}function O(Re){return ee(Re),Re}function k(Re,Z){const L=Re.reduce((q,ie)=>[...q,...ie.urls],[]).filter(q=>S(q,Z)).sort(q=>V(q,"udp")?-1:0).shift();if(L)return Object.assign(Object.assign({},O(Re.find(q=>q.urls.includes(L)))),{urls:[L]})}function S(Re,Z){switch(Z){case"stun":return/^stuns?:/.test(Re);case"turn":return/^turns?:/.test(Re)}}function V(Re,Z){return Re.endsWith("transport="+Z)}var G=n(10);class K extends Error{constructor(Z,L){super(`Deadline expired after ${Z}ms + ${L}ms`)}}class Y{static withDeadline(Z,L){const q=new Promise((ie,se)=>{setTimeout(()=>{se(new K(L,this.grpcCallDeadlineSlopMs))},L+this.grpcCallDeadlineSlopMs)});return Promise.race([Z,q])}}Y.grpcCallDeadlineSlopMs=500*u.a.millisecond;var te=n(27);const oe={ordered:!1,maxPacketLifeTime:300*u.a.millisecond},ge={ordered:!0},Se={ordered:!0},ve={ordered:!1,maxRetransmits:0},ye={ordered:!1,maxRetransmits:0},Je=Re=>"received"in Re&&Re.received!==void 0,Ee=Re=>!("received"in Re)||Re.received===void 0,be=2*u.a.second,we=10*u.a.second;function Ze(Re,Z={}){const L=Array.from(Re.values()),q=L.filter(Je),ie=q.length>0,se=Math.max(...L.map(le=>le.sent)),ue=Math.max(...q.map(le=>le.received));let fe;if(ie){const le=Date.now()-se<=u.a.millisecond?L.length-1:L.length,me=q.length>le?le:q.length,Ve=q.map(Me=>Me.received-Me.sent),{standardDeviation:Ce,mean:xe,jitter:He}=function(Me){const Le=Me.length;if(Le===0)return{mean:NaN,standardDeviation:-1,jitter:NaN};const Ge=Me.reduce((Xe,$e)=>Xe+$e,0)/Le,Ke=Math.sqrt(Me.map(Xe=>Math.pow(Xe-Ge,2)).reduce((Xe,$e)=>Xe+$e)/Le);if(Le===1)return{mean:Ge,standardDeviation:Ke,jitter:NaN};let Rt=0;for(let Xe=1;Xe<Le;Xe++)Rt+=Math.abs(Me[Xe]-Me[Xe-1]);return{mean:Ge,standardDeviation:Ke,jitter:Rt/(Le-1)}}(Ve),Ye=L.filter(Me=>Me.sent<ue-be),qe=Ye.filter(Ee),Pe=qe.length===0?0:qe.length/Ye.length;fe={pingsSent:le,pongsReceived:me,average:xe,standardDeviation:Ce,jitter:He,max:Math.max(...Ve),min:Math.min(...Ve),loss:Pe}}else fe=null;const{temporalNow:Ue=Date.now()}=Z,ce=(ie?ue:Ue)-we;return Array.from(Re.entries()).forEach(le=>{const[me,Ve]=le;Ve.sent<ce&&Re.delete(me)}),fe}function Oe({entityId:Re,streamName:Z,streamType:L}){return`${Re}.${Z}.${L}`}var it=function(Re,Z,L,q){return new(L||(L=Promise))(function(ie,se){function ue(ce){try{Ue(q.next(ce))}catch(le){se(le)}}function fe(ce){try{Ue(q.throw(ce))}catch(le){se(le)}}function Ue(ce){var le;ce.done?ie(ce.value):(le=ce.value,le instanceof L?le:new L(function(me){me(le)})).then(ue,fe)}Ue((q=q.apply(Re,Z||[])).next())})};class mt{constructor(Z,L){this.counts={localSent:new Map,localReceived:new Map,remoteSent:new Map,remoteReceived:new Map},this.sessionId=Z,this.connection=L}updateRemoteMessagesCounts(Z){if(Z.payload.streamsInfo){this.counts.remoteSent=new Map,this.counts.remoteReceived=new Map;for(const L of Z.payload.streamsInfo.items)this.counts.remoteSent.set(L.streamId,L.sentCount),this.counts.remoteReceived.set(L.streamId,L.receivedCount)}}getLocalStreamsInfo(Z){const{localSent:L,localReceived:q}=this.counts;return{items:[...new Set([...L.keys(),...q.keys()])].map(ie=>{var se,ue;return{streamId:ie,sentCount:(se=L.get(ie))!==null&&se!==void 0?se:0,receivedCount:(ue=q.get(ie))!==null&&ue!==void 0?ue:0}}),timestamp:Z}}incrementLocalSent(Z){const{localSent:L}=this.counts,q=Oe(Z.header.stream);L.set(q,(L.get(q)||0)+1)}incrementLocalReceived(Z){const{localReceived:L}=this.counts,q=Oe(Z.header.stream),ie=L.get(q)||0;if(ie===0){const{streamName:se,streamType:ue}=Z.header.stream;U.a.debug("RTC client received first message for stream",{streamName:se,streamType:ue})}L.set(q,ie+1)}uploadMetrics(){return it(this,void 0,void 0,function*(){const{sessionId:Z}=this,L=yield this.connection.peerConnection.getStats(),q={};L.forEach(ce=>q[ce.id]=ce),U.a.debug("rtc-stats",Object.assign(Object.assign({},q),{sessionId:Z}));const{localSent:ie,localReceived:se,remoteSent:ue,remoteReceived:fe}=this.counts,Ue=[...new Set([...ie.keys(),...se.keys()])].reduce((ce,le)=>{const me=ie.get(le),Ve=se.get(le),Ce=ue.get(le),xe=fe.get(le);return Object.assign(Object.assign({},ce),{[`local-${le}-sent`]:me,[`local-${le}-received`]:Ve,[`remote-${le}-sent`]:Ce,[`remote-${le}-received`]:xe})},{sessionId:Z});U.a.debug("rtc-message-report",Object.assign({deviceId:this.connection.getRemoteDeviceId()},Ue))})}}function wt(Re,Z,L){return{header:{stream:Re,created:Date.now(),frameId:L||""},payload:Z}}function bt(Re){const Z=Re.localCandidate.candidateType,L=Re.remoteCandidate.candidateType;return Z==="host"&&L==="host"?"local":Z==="relay"||L==="relay"?"TURN":"STUN"}function gt(Re){return new Set(["disconnected","failed","closed"]).has(Re.iceConnectionState)}function Et(Re){switch(Re.header.stream.streamType){case"twist":{const{twist:Z}=Re.payload;if(!Z)throw Error("twist not in payload of RTC message with type twist");return{header:Re.header,payload:{twist:{linear:Object.assign({x:0,y:0,z:0},Z.linear),angular:Object.assign({x:0,y:0,z:0},Z.angular)}}}}case"pose":{const{pose:Z}=Re.payload;if(!Z)throw Error("pose not in payload of RTC message with type pose");return{header:Re.header,payload:{pose:{translation:Object.assign({x:0,y:0,z:0},Z.translation),rotation:Object.assign({x:0,y:0,z:0,w:0},Z.rotation)}}}}case"pose-with-covariance":{const{poseWithCovariance:Z}=Re.payload;if(!Z)throw Error("poseWithCovariance not in payload of RTC message with type pose-with-covariance");const L=new Array(36).fill(0);return Z.covariance.forEach((q,ie)=>{if(ie>=36)throw Error("covariance contains more than 36 elements");L[ie]=q}),{header:Re.header,payload:{poseWithCovariance:{pose:{translation:Object.assign({x:0,y:0,z:0},Z.pose.translation),rotation:Object.assign({x:0,y:0,z:0,w:0},Z.pose.rotation)},covariance:L}}}}case"point":{const{point:Z}=Re.payload;if(!Z)throw Error("point not in payload of RTC message with type point");return{header:Re.header,payload:{point:Object.assign({x:0,y:0,z:0},Z)}}}default:return Re}}var at=function(Re,Z,L,q){return new(L||(L=Promise))(function(ie,se){function ue(ce){try{Ue(q.next(ce))}catch(le){se(le)}}function fe(ce){try{Ue(q.throw(ce))}catch(le){se(le)}}function Ue(ce){var le;ce.done?ie(ce.value):(le=ce.value,le instanceof L?le:new L(function(me){me(le)})).then(ue,fe)}Ue((q=q.apply(Re,Z||[])).next())})};class Tt{get peerConnection(){return re(this._peerConnection,"RTCPeerConnection is closed!"),this._peerConnection}constructor(Z,L,q,ie){this.iceServers=L,this.config=q,this.dataChannelNotifier=ie,this.connectTimeoutMs=20*u.a.second,this.iceGatheringTimeoutMs=3*u.a.second,this.pingUpdateTimeoutMs=1*u.a.second,this.pingV2UpdateTimeoutMs=250*u.a.millisecond,this.pingV2MetricsGatherTimeoutMs=1*u.a.second,this.streamsInfoUpdateTimeoutMs=2*u.a.second,this.reassemblyTimeoutMs=500*u.a.millisecond,this.reassemblyTableCleanupMs=1*u.a.second,this.heartbeatTimeoutMs=20*u.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:ue}=this;if(!ue)return;const fe=new Date().getTime(),Ue=Object(D.a)();this.sendSystemMessage(ue,{type:"ping-v2",payload:{timestamp:fe,id:Ue}}),this.pingV2Map.set(Ue,{sent:fe})},this.gatherPingV2Metrics=()=>{const ue=Ze(this.pingV2Map);if(ue){const fe=this.getRemoteDeviceId();this.pingInfo=ue,x.aggregate("rtc-ping-average",ue.average,Object.assign({},fe?{deviceId:fe}:{})),x.aggregate("rtc-ping-loss",ue.loss,Object.assign({},fe?{deviceId:fe}:{})),x.aggregate("rtc-jitter",ue.jitter,Object.assign({},fe?{deviceId:fe}:{}))}},this._peerConnection=Z;const{isOffer:se}=q.baseConfig;se?this.initializeChannels(Z):Z.ondatachannel=ue=>{switch(ue.channel.label){case"stream.latest-ttl":this.latestTtlStreamChannel=ue.channel;break;case"stream.reliable":this.reliableStreamChannel=ue.channel;break;case"stream.latest-reliable":this.latestReliableStreamChannel=ue.channel;break;case"stream.latest-try-once":this.latestTryOnceStreamChannel=ue.channel;break;case"heartbeat":return void(this.heartbeatChannel=ue.channel);default:return void this.dataChannelNotifier(ue.channel)}this.setupChannel(ue.channel)},this.pingUpdateTimeout=setInterval(()=>{const{reliableStreamChannel:ue}=this;ue&&this.sendSystemMessage(ue,{type:"ping"})},this.pingUpdateTimeoutMs),this.pingV2UpdateTimeout=setInterval(this.sendPingV2,this.pingV2UpdateTimeoutMs),this.pingV2MetricsGatherTimeout=setInterval(this.gatherPingV2Metrics,this.pingV2MetricsGatherTimeoutMs),this.streamsInfoUpdateTimeout=setInterval(()=>{const{latestTtlStreamChannel:ue}=this;ue&&this.sendSystemMessage(ue,{type:"streams-info"})},this.streamsInfoUpdateTimeoutMs),this.reassemblyTableCleanupTimeout=setInterval(()=>{const ue=new Date().getTime();this.reassemblyTableLastTimestamp.forEach((fe,Ue,ce)=>{ue>Ue+this.reassemblyTimeoutMs&&this.reassemblyTable.delete(fe)})},this.reassemblyTableCleanupMs),this.heartbeatTimeout=setInterval(()=>{const{heartbeatChannel:ue}=this;ue&&ue.readyState==="open"&&ue.send(new Uint8Array([1]))},this.heartbeatTimeoutMs)}handleSignal(Z){return at(this,void 0,void 0,function*(){const{peerConnection:L}=this,{track:q}=this.config.baseConfig,ie=(()=>{try{return JSON.parse(Z.getPayload())}catch{return}})();if(!ie)return void U.a.error("Received unparseable signal.");U.a.debug("Handling signal",{description:ie});const{sdp:se,type:ue}=ie;if(!se||!ue)return void U.a.warn("Received non-SDP signal");const{signalingState:fe,connectionState:Ue}=L;if(fe!=="stable"||Ue!=="connected")if(L.remoteDescription)U.a.warn("Received SDP after remote description was set: "+se);else{if(ue==="offer"){if(fe!=="stable")return void U.a.warn("Received offer SDP when signaling is ongoing.");yield L.setRemoteDescription(ie);const ce=yield L.createAnswer();yield L.setLocalDescription(ce);const le=Z.clone();return q==null||q("Answer Received",le),le.setPayload(JSON.stringify(ce)),le.setReceiverId(Z.getSenderId()),le.setSenderId(Z.getReceiverId()),le}if(ue==="answer"){if(fe==="stable")return void U.a.warn("Received answer SDP when signaling hasn't started.");yield L.setRemoteDescription(ie)}}else U.a.warn("Received SDP when already connected: "+se)})}send(Z,L){const q=this.getChannelFromLabel(L.channelLabel);q?this.sendOnChannel(q,Z):U.a.warn("Send called with unexpected channel label",{channelLabel:L.channelLabel})}controlRemoteStream(Z){var L;this.sendSystemMessage((re(L=this.reliableStreamChannel),L),{type:"stream-control",streamControl:Z})}isActive(){return new Set(["new","checking","connected","completed"]).has(this.peerConnection.iceConnectionState)||this.isReady()}isReady(){const{reliableStreamChannel:Z,latestTtlStreamChannel:L,latestTryOnceStreamChannel:q,latestReliableStreamChannel:ie}=this;return(Z==null?void 0:Z.readyState)==="open"&&(L==null?void 0:L.readyState)==="open"&&(q==null?void 0:q.readyState)==="open"&&(ie==null?void 0:ie.readyState)==="open"}close(){var Z,L,q,ie,se,ue,fe;return at(this,void 0,void 0,function*(){this.closeCalled||(this.closeCalled=!0,yield(Z=this.sessionMetrics)===null||Z===void 0?void 0:Z.uploadMetrics(),pt(this.pingUpdateTimeout),pt(this.pingV2UpdateTimeout),pt(this.pingV2MetricsGatherTimeout),pt(this.reassemblyTableCleanupTimeout),pt(this.streamsInfoUpdateTimeout),pt(this.heartbeatTimeout),(L=this._peerConnection)===null||L===void 0||L.close(),(q=this.heartbeatChannel)===null||q===void 0||q.close(),(ie=this.latestReliableStreamChannel)===null||ie===void 0||ie.close(),(se=this.latestTryOnceStreamChannel)===null||se===void 0||se.close(),(ue=this.latestTtlStreamChannel)===null||ue===void 0||ue.close(),(fe=this.reliableStreamChannel)===null||fe===void 0||fe.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 Z;return(Z=this.config.remoteConfig)===null||Z===void 0?void 0:Z.sessionCreatedTimestamp}setSessionCreatedTimestamp(Z){this.config.remoteConfig&&(this.config.remoteConfig.sessionCreatedTimestamp=Z)}getSessionId(){var Z;return(Z=this.config.remoteConfig)===null||Z===void 0?void 0:Z.sessionId}setSessionId(Z){this.config.remoteConfig&&(this.config.remoteConfig.sessionId=Z,this.sessionMetrics=new mt(Z,this))}getRemotePeerId(){return this.config.baseConfig.remotePeerId}getRemoteDeviceId(){var Z;return(Z=this.config.baseConfig)===null||Z===void 0?void 0:Z.remoteDeviceId}setRemoteDeviceId(Z){this.config.baseConfig.remoteDeviceId=Z}getSessionMetricsMessageCounts(){var Z;return(Z=this.sessionMetrics)===null||Z===void 0?void 0:Z.counts}getConnectionStatsInfo(){return at(this,void 0,void 0,function*(){const{peerConnection:Z}=this;if(!Z)return;const L=yield Z.getStats(null),q=[];L.forEach(Ue=>{q.push(Ue)});const ie=q.find(Ue=>Ue.type==="transport");if(!ie)return;const se=q.find(Ue=>(Ue.type==="candidate-pair"||Ue.type==="candidatepair")&&Ue.id===ie.selectedCandidatePairId);if(!se)return;const ue=q.find(Ue=>Ue.id===se.localCandidateId),fe=q.find(Ue=>Ue.id===se.remoteCandidateId);return ue&&fe&&(ue.address=ue.address||ue.ip,fe.address=fe.address||fe.ip,ue.address!==void 0&&fe.address!==void 0)?{transport:ie,localCandidate:ue,remoteCandidate:fe,candidatePair:se}:void 0})}initializeChannels(Z){this.heartbeatChannel=Z.createDataChannel("heartbeat",ye),this.heartbeatChannel.binaryType="arraybuffer",this.latestTtlStreamChannel=Z.createDataChannel("stream.latest-ttl",oe),this.latestTtlStreamChannel.binaryType="arraybuffer",this.reliableStreamChannel=Z.createDataChannel("stream.reliable",ge),this.reliableStreamChannel.binaryType="arraybuffer",this.latestReliableStreamChannel=Z.createDataChannel("stream.latest-reliable",Se),this.latestReliableStreamChannel.binaryType="arraybuffer",this.latestTryOnceStreamChannel=Z.createDataChannel("stream.latest-try-once",ve),this.latestTryOnceStreamChannel.binaryType="arraybuffer",this.setupChannel(this.latestTtlStreamChannel),this.setupChannel(this.reliableStreamChannel),this.setupChannel(this.latestReliableStreamChannel),this.setupChannel(this.latestTryOnceStreamChannel)}getOffer(){var Z,L;return at(this,void 0,void 0,function*(){const{gotOffer:q}=this,{peerConnection:ie,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 ue=(Z=this.config.remoteConfig)===null||Z===void 0?void 0:Z.sessionId;if(q)return void U.a.debug("Failed to generate offer because gotOffer was already called.");if(this.gotOffer=!0,gt(this.peerConnection))return void U.a.debug("Failed to generate offer because the peer connection was inactive.");const fe=se.baseConfig.track;ie.onicecandidate=()=>{this.hasIceCandidate=!0},ie.oniceconnectionstatechange=()=>at(this,void 0,void 0,function*(){const Ce=ie.iceConnectionState;if(Ce==="connected"||Ce==="completed"){const xe=yield this.getConnectionStatsInfo(),He=xe?bt(xe):void 0;U.a.info("ICE connection state changed to "+Ce,{sessionId:ue,connectionStatsInfo:xe,iceMode:He}),fe==null||fe("ICE connection state change",{iceConnectionState:Ce,sessionId:ue,connectionStatsInfo:xe,iceMode:He})}}),yield ie.setLocalDescription(yield ie.createOffer());const Ue=ie.getConfiguration?ie.getConfiguration().iceTransportPolicy:"all",ce=new Date().getTime();for(;;){const Ce=new Date().getTime()-ce;if(Ce>this.connectTimeoutMs)return void U.a.debug("Failed to generate offer because ICE gathering timed out.");if(Ce>this.iceGatheringTimeoutMs&&this.hasIceCandidate){U.a.debug("ICE gathering partially completed; proceeding",{iceTransportPolicy:Ue,waitTime:Ce}),fe==null||fe("ICE gathering partially completed",{sessionId:ue,iceTransportPolicy:Ue,waitTime:Ce});break}if(ie.iceGatheringState==="complete"){U.a.debug("ICE gathering complete",{iceTransportPolicy:Ue,waitTime:Ce}),fe==null||fe("ICE gathering completed",{sessionId:ue,iceTransportPolicy:Ue,waitTime:Ce});break}yield Object(c.a)(.1*u.a.second)}const le=(L=this.iceServers)!==null&&L!==void 0?L:[];for(const Ce of le)"credentialType"in Ce&&(Ce.credentialType=void 0);const me=JSON.stringify(le),Ve=new G.Signal;return Ve.setPayload(JSON.stringify(ie.localDescription)),Ve.setSenderId(this.config.baseConfig.localPeerId),Ve.setReceiverId(this.config.baseConfig.remotePeerId),Ve.setIceServers(me),Ve.setIceTransportPolicy(Ue!=null?Ue:"all"),this.config.baseConfig.sessionType!==void 0?Ve.setSessionType(this.config.baseConfig.sessionType):Ve.setSessionType(G.SessionType.TELEOP),U.a.debug("Sending offer signal with description",{description:Ve.getPayload()}),Ve})}getLanOffer(){return at(this,void 0,void 0,function*(){const{peerConnection:Z,gotOffer:L}=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(L)return void U.a.debug("Failed to generate offer because gotOffer was already called.");if(this.gotOffer=!0,gt(this.peerConnection))return void U.a.debug("Failed to generate offer because the peer connection was inactive.");yield Z.setLocalDescription(yield Z.createOffer());const q=new Date().getTime();for(;;){if(new Date().getTime()-q>this.iceGatheringTimeoutMs)return void U.a.debug("Failed to generate offer because ICE gathering timed out.");if(Z.iceGatheringState==="complete")break;yield Object(c.a)(.1*u.a.second)}const ie=Z.localDescription;if(ie)return U.a.debug("Sending LAN offer signal with description",{description:ie}),ie;U.a.error("Failed to generate LAN offer description")})}handleLanAnswer(Z){return at(this,void 0,void 0,function*(){const{peerConnection:L}=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 L.setRemoteDescription(Z)})}getChannelFromLabel(Z){switch(Z){case"stream.latest-ttl":return this.latestTtlStreamChannel;case"stream.reliable":return this.reliableStreamChannel;case"stream.latest-reliable":return this.latestReliableStreamChannel;case"stream.latest-try-once":return this.latestTryOnceStreamChannel}}sendOnChannel(Z,L){var q;let ie;try{ie=Object(te.encode)(JSON.stringify(L))}catch(se){return void U.a.warn("Failed to encode RTC message",{error:se})}try{Z.send(ie),(q=this.sessionMetrics)===null||q===void 0||q.incrementLocalSent(L)}catch(se){U.a.warn("Failed to send message to channel",{error:se,channel:Z.label})}}channelNotRecognized(Z){return Z!==this.latestTtlStreamChannel&&Z!==this.latestReliableStreamChannel&&Z!==this.latestTryOnceStreamChannel&&Z!==this.reliableStreamChannel}setupChannel(Z){Z.onmessage=L=>{if(this.channelNotRecognized(Z))return void U.a.warn("Received message on unrecognized data channel.");let q;try{q=JSON.parse(Object(te.decode)(L.data))}catch(ie){return void U.a.warn("Received unparseable message on RTC stream data channel",{error:ie,channel:Z.label})}q.communicationType==="message-chunk"?this.receiveChannelMessageChunk(Z,q):this.receiveChannelMessage(Z,q)},Z.onerror=L=>{U.a.warn("Channel error: "+L.error,{error:L.error,sessionId:this.getSessionId(),channelLabel:Z.label})},Z.onopen=()=>{U.a.debug("Channel opened",{sessionId:this.getSessionId(),channelLabel:Z.label})},Z.onclose=()=>{const L={bufferedAmount:Z.bufferedAmount,sessionId:this.getSessionId(),channelLabel:Z.label};this.closeCalled===!1?U.a.debug("Unexpected channel closed",L):U.a.debug("Channel closed",L)}}receiveChannelMessage(Z,L){var q;const{config:ie}=this,{remotePeerId:se}=this.config.baseConfig;this.lastMessageTimestamp=new Date().getTime(),L=Et(L),(q=this.sessionMetrics)===null||q===void 0||q.incrementLocalReceived(L),!this.handleSystemMessage(Z,L)&&((Z===this.latestTryOnceStreamChannel||Z===this.latestTtlStreamChannel||Z===this.latestReliableStreamChannel)&&!this.isLatestMessage(L)||ie.baseConfig.receive(se,L))}receiveChannelMessageChunk(Z,L){const q=this.reassemblyTable.get(L.id)||[];if(q.push(L),q.length===L.total){const ie=function(se){const ue=se.sort((fe,Ue)=>fe.seq<Ue.seq?-1:1).map(fe=>fe.part).reduce((fe,Ue)=>fe+Ue);try{return JSON.parse(ue)}catch{return void U.a.warn("Could not reassemble RTC message chunks")}}(q);return ie&&this.receiveChannelMessage(Z,ie),void this.reassemblyTable.delete(L.id)}this.reassemblyTable.set(L.id,q),this.reassemblyTableLastTimestamp.set(L.id,new Date().getTime())}handleSystemMessage(Z,L){var q,ie;const{config:se}=this,{baseConfig:ue}=se,{remotePeerId:fe,remoteDeviceId:Ue}=ue;switch(L.header.stream.streamType){case"ping":return this.sendSystemMessage(Z,{type:"pong",timestamp:O(L.payload.ping)}),!0;case"pong":{const ce=new Date().getTime()-O(L.payload.pong);return this.pingTimeMs=ce,x.aggregate("rtc-ping-time",ce,Object.assign({},Ue?{deviceId:Ue}:{})),!0}case"ping-v2":return this.sendPingV2(),!0;case"pong-v2":{const ce=O(L.payload.pongV2),le=this.pingV2Map.get(ce.id);return(le==null?void 0:le.sent)!==ce.timestamp&&U.a.warn("Pong timestamp doesn't match stored value",{currentEntry:le,pong:ce}),this.pingV2Map.set(ce.id,{sent:ce.timestamp,received:new Date().getTime()}),!0}case"streams-info":{const{sessionMetrics:ce}=this,le=(q=L.payload.streamsInfo)===null||q===void 0?void 0:q.timestamp;return!!le&&(ce==null||ce.updateRemoteMessagesCounts(L),(ie=ue.onStreamsInfoUpdate)===null||ie===void 0||ie.call(ue,fe,le),!0)}case"stream-control":return!0;default:return!1}}sendSystemMessage(Z,L){var q;const{localUserId:ie,localPeerId:se}=this.config.baseConfig;if(Z.readyState!=="open")return;const ue={entityId:ie!=null?ie:se,streamName:"$."+L.type,streamType:L.type};let fe;switch(L.type){case"ping":fe={ping:new Date().getTime()};break;case"pong":fe={pong:L.timestamp};break;case"ping-v2":fe={pingV2:L.payload};break;case"pong-v2":fe={pongV2:L.payload};break;case"stream-control":fe={streamControl:L.streamControl};break;case"streams-info":fe={streamsInfo:(q=this.sessionMetrics)===null||q===void 0?void 0:q.getLocalStreamsInfo(new Date().getTime())}}this.sendOnChannel(Z,wt(ue,fe))}isLatestMessage(Z){const L=Oe(Z.header.stream),q=(this.streamLatestTimestamp.get(L)||0)<=Z.header.created;return q&&this.streamLatestTimestamp.set(L,Z.header.created),q}}function pt(Re){Re&&clearInterval(Re)}function vt(){U.a.debug("forceGarbageCollection() triggered"),queueMicrotask(()=>{let Re=document.createElement("img");Re.src=window.URL.createObjectURL(new Blob([new ArrayBuffer(5e7)])),Re.onerror=function(){window.URL.revokeObjectURL(this.src),Re=null}})}function Ot(Re){try{return Re instanceof Error?`${Re.name}: ${Re.message}`:typeof Re=="object"?JSON.stringify(Re):String(Re)}catch{return"Unknown error"}}function ut(Re){var Z,L;return{userId:(Z=Re.getUserId())===null||Z===void 0?void 0:Z.getValue(),deviceId:(L=Re.getDeviceId())===null||L===void 0?void 0:L.getValue(),organizationId:Re.getOrganizationId(),id:Re.getPeerId(),capabilities:[],capabilitySet:{}}}var De=function(Re,Z,L,q){return new(L||(L=Promise))(function(ie,se){function ue(ce){try{Ue(q.next(ce))}catch(le){se(le)}}function fe(ce){try{Ue(q.throw(ce))}catch(le){se(le)}}function Ue(ce){var le;ce.done?ie(ce.value):(le=ce.value,le instanceof L?le:new L(function(me){me(le)})).then(ue,fe)}Ue((q=q.apply(Re,Z||[])).next())})};const ht=Re=>Re.map(Z=>Object.assign(Object.assign(Object.assign({},Z),Z.username?{username:"<REDACTED>"}:null),Z.credential?{credential:"<REDACTED>"}:null));class It{constructor(Z){this.config=Z,this.grpcCallDeadline=5*u.a.second,this.refreshIntervalDelayMs=2*u.a.second,this.iceServersTtl=30*u.a.minute,this.connections=[],this.localConnections=[],this.isConnectionInitiator=new WeakSet,this.isOutgoingConnection=new Set,this.peerDataChannelListeners=[],this.rtcInstancesConstructed=0,this.statsLoopsExecuted=0;const{refreshIntervalDelayMs:L}=this;this.refreshInterval=T({func:()=>De(this,void 0,void 0,function*(){try{yield this.update()}catch(q){U.a.warn("RTC refresh failed",{error:q})}}),delay:L,immediate:!0})}send(Z,L,q){const ie=this.getActiveConnection(Z);ie?ie.isReady()?ie.send(L,q):U.a.warn("Send called with unready connection."):U.a.warn("Send called with no connection.")}controlRemoteStream(Z,L){const q=this.getActiveConnection(Z);q?q.isReady()?q.controlRemoteStream(L):U.a.warn("controlRemoteStream called with unready connection."):U.a.warn("controlRemoteStream called with no connection.")}getLocalPeer(){return De(this,void 0,void 0,function*(){for(;!this.localPeer;)yield Object(c.a)(.1*u.a.second);return ut(this.localPeer)})}connect(Z,L){var q,ie,se;return De(this,void 0,void 0,function*(){if(this.config.lanOnlyMode===!0)throw new Error("connect method called in local only mode.");const{track:ue,signalingClient:fe}=this.config,{localPeer:Ue,receiveSignalStream:ce,iceServers:le}=this;if(!Ue||!ce||!le)return void U.a.warn("Connect called prior to local peer, receiveSignalStream, and ICE servers ready");if(this.getActiveConnection(Z))return void U.a.warn("Connect called for peer with existing connection.");if(this.isOutgoingConnection.has(Z))return void U.a.warn("Connect called for peer with an existing outgoing connection offer.");this.isOutgoingConnection.add(Z);const me=function(Pe,Me,Le){const{rtcIceTransportPolicies:Ge,rtcIceServerProtocol:Ke,useAllServers:Rt}=Me||{},Xe=Pe.map($e=>Object.assign(Object.assign({},$e),{urls:$e.urls.filter(st=>{const _t=(Ge===void 0||Ge.some(kt=>S(st,kt)))&&(Ke===void 0||V(st,Ke));return _t||U.a.debug("Ignoring ICE server: "+st,{organizationId:Le}),_t})})).filter(({urls:$e})=>$e.filter(st=>st).length>0);return Rt?Xe:[k(Xe,"stun"),k(Xe,"turn")].filter($e=>$e!==void 0).map($e=>O($e))}(le,L);U.a.debug("Received ICE servers:",ht(le)),U.a.debug("Using ICE servers:",ht(me));const Ve=new Tt(yield this.createRTCPeerConnection(me),me,{baseConfig:{isOffer:!0,isLan:!1,receive:(Pe,Me)=>this.config.receive(Pe,Me),onStreamsInfoUpdate:this.config.onStreamsInfoUpdate?(Pe,Me)=>{var Le,Ge;return(Ge=(Le=this.config).onStreamsInfoUpdate)===null||Ge===void 0?void 0:Ge.call(Le,Pe,Me)}:void 0,track:this.config.lanOnlyMode?void 0:this.config.track,localUserId:(q=Ue.getUserId())===null||q===void 0?void 0:q.getValue(),localPeerId:Ue.getPeerId(),remotePeerId:Z,sessionType:this.config.sessionType},remoteConfig:{}},Pe=>this.onCustomDataChannel(Z,Pe)),Ce=yield Ve.getOffer();if(!Ce)return U.a.error("Failed to generate offer."),void this.isOutgoingConnection.delete(Z);U.a.debug("Sending offer."),ue==null||ue("Sending offer",Ce);const xe=new G.SendSignalRequest;xe.setSignal(Ce);const He=yield(()=>De(this,void 0,void 0,function*(){try{return yield Y.withDeadline(fe.sendSignal(xe,yield this.getMetadata()),this.grpcCallDeadline)}catch(Pe){U.a.warn("Error when sending signal",{error:Pe})}}))();if(!this.isOutgoingConnection.has(Z))return void U.a.debug("No offer set after receiving offer signal response.");U.a.debug("Offer sent.");const Ye=(ie=He==null?void 0:He.getSessionId())===null||ie===void 0?void 0:ie.getValue(),qe=(se=He==null?void 0:He.getSessionCreatedTimestamp())===null||se===void 0?void 0:se.getValue();return Ye&&qe?(Ve.setSessionId(Ye),Ve.setSessionCreatedTimestamp(qe),this.isOutgoingConnection.delete(Z),this.connections.push(Ve),this.isConnectionInitiator.add(Ve),this.setupHandlers(Ve),Ye):(U.a.warn("No session ID or no session created timestamp on send signal response."),void this.isOutgoingConnection.delete(Z))})}connectLan(Z){var L,q;return De(this,void 0,void 0,function*(){const ie=new P(Z),se=new Tt(yield this.createRTCPeerConnection([]),[],{baseConfig:{isOffer:!0,isLan:!0,receive:(ce,le)=>this.config.receive(ce,le),onStreamsInfoUpdate:this.config.onStreamsInfoUpdate?(ce,le)=>{var me,Ve;return(Ve=(me=this.config).onStreamsInfoUpdate)===null||Ve===void 0?void 0:Ve.call(me,ce,le)}:void 0,track:this.config.lanOnlyMode?void 0:this.config.track,localUserId:(q=(L=this.localPeer)===null||L===void 0?void 0:L.getUserId())===null||q===void 0?void 0:q.getValue(),localPeerId:"lan_client",remotePeerId:Z}},ce=>this.onCustomDataChannel(Z,ce)),ue=yield se.getLanOffer();if(!ue)return U.a.warn("Could not generate LAN offer"),!1;const fe=yield ie.postLanRtcOffer({offer:JSON.stringify(ue)}),Ue=new RTCSessionDescription(JSON.parse(fe.answer));return yield se.handleLanAnswer(Ue),this.localConnections.push(se),this.isConnectionInitiator.add(se),Object(D.a)()})}getConnections(){return[...this.connections,...this.localConnections]}createCustomDataChannel(Z,L,q,ie,se){const ue=this.getActiveConnection(Z);if(ue&&this.isConnectionInitiator.has(ue)){const Ue=ue.peerConnection.createDataChannel("custom."+L,q);return ie&&(Ue.binaryType="arraybuffer"),se(Z,Ue),()=>{}}const fe=(Ue,ce)=>{Z===Ue&&ce.label==="custom."+L&&se(Z,ce)};return this.peerDataChannelListeners.push(fe),()=>{this.peerDataChannelListeners=this.peerDataChannelListeners.filter(Ue=>Ue!==fe)}}onCustomDataChannel(Z,L){this.peerDataChannelListeners.forEach(q=>q(Z,L))}getConnectionStatus(Z){if(this.isOutgoingConnection.has(Z))return"connecting";const L=this.getActiveConnection(Z);return L?L.isReady()?"connected":"connecting":"disconnected"}getConnectionStatsInfo(Z){return De(this,void 0,void 0,function*(){const L=this.getActiveConnection(Z);if(L)return yield L.getConnectionStatsInfo()})}disconnect(Z){return De(this,void 0,void 0,function*(){const L=this.getActiveConnection(Z);L&&(yield L.close(),this.connections=this.connections.filter(q=>q!==L),this.localConnections=this.localConnections.filter(q=>q!==L))})}getPeers(){return De(this,void 0,void 0,function*(){if(this.config.lanOnlyMode)throw new Error("getPeers method cannot be used in local-only mode.");const{signalingClient:Z}=this.config,L=yield(()=>De(this,void 0,void 0,function*(){try{return yield Y.withDeadline(Z.getPeers(new G.GetPeersRequest,yield this.getMetadata()),this.grpcCallDeadline)}catch(se){U.a.warn("Error when getting peers",{error:se})}}))();if(!L)return[];const q=L.getPeersList();if(!q)return[];const ie=se=>{var ue,fe;return(fe=(ue=se.getPeerCreatedTimestamp())===null||ue===void 0?void 0:ue.getValue())!==null&&fe!==void 0?fe:0};return q.sort((se,ue)=>ie(ue)-ie(se)).map(se=>ut(se))})}getSessions(){return De(this,void 0,void 0,function*(){if(this.config.lanOnlyMode)throw new Error("getPeers method cannot be used in local-only mode.");const{signalingClient:Z}=this.config,L=yield(()=>De(this,void 0,void 0,function*(){try{return yield Y.withDeadline(Z.getPeers(new G.GetPeersRequest,yield this.getMetadata()),this.grpcCallDeadline)}catch(se){U.a.warn("Error when getting peers",{error:se})}}))();if(!L)return{};const q=L.getPeersList(),ie={};for(const se of q)ie[se.getPeerId()]=se.getSessionIdsList();return ie})}getPing(Z){const L=this.getActiveConnection(Z);if(L)return L.getPing();U.a.warn("Attempted to get ping time from inactive peer.")}getPingInfo(Z){const L=this.getActiveConnection(Z);if(L)return L.getPingInfo();U.a.warn("Attempted to get ping time from inactive peer.")}getLastMessageTimestamp(Z){const L=this.getActiveConnection(Z);if(L)return L.getLastMessageTimestamp();U.a.warn("Attempted to get last message time from inactive peer.")}getSessionMetricsMessageCounts(Z){const L=this.getActiveConnection(Z);if(L)return L.getSessionMetricsMessageCounts();U.a.warn("Attempted to get session metrics counts from inactive peer.")}isReady(){if(this.config.lanOnlyMode)return!0;const{localPeer:Z,receiveSignalStream:L,iceServers:q}=this;return!!(Z&&L&&q)}shutdown(){return De(this,void 0,void 0,function*(){yield this.refreshInterval.stop(),this.receiveSignalStream&&this.receiveSignalStream.cancel();const Z=this.connections;this.connections=[],yield this.closeConnections(Z);const L=this.localConnections;this.localConnections=[],yield this.closeConnections(L),this.isOutgoingConnection.clear(),this.peerDataChannelListeners=[];const{localPeer:q}=this;if(!q||this.config.lanOnlyMode)return;const{signalingClient:ie}=this.config;yield(()=>De(this,void 0,void 0,function*(){try{const se=new G.DeletePeerRequest;se.setPeerId(q.getPeerId()),yield Y.withDeadline(ie.deletePeer(se,yield this.getMetadata()),this.grpcCallDeadline)}catch(se){return void U.a.warn("Error deleting local peer",{error:se})}}))()})}createPeer(){return De(this,void 0,void 0,function*(){if(this.config.lanOnlyMode)throw new Error("createPeer method cannot be used in local-only mode.");const{signalingClient:Z}=this.config,L=yield(()=>De(this,void 0,void 0,function*(){try{return yield Y.withDeadline(Z.createPeer(new G.CreatePeerRequest,yield this.getMetadata()),this.grpcCallDeadline)}catch(ie){const se=ie;U.a.debug("createPeer failed",{error:se});const ue=Ot(se);throw new Error("Was not able to create peer: "+ue)}}))(),q=L==null?void 0:L.getPeer();if(!q)throw new Error("Response did not provide peer.");return this.localPeer=q})}createReceiveSignalStream(){return De(this,void 0,void 0,function*(){if(this.config.lanOnlyMode)throw new Error("createReceiveSignalStream method cannot be used in local-only mode.");const{signalingClient:Z}=this.config,{localPeer:L,iceServers:q}=this;if(!L||!q)return;const{receiveSignalStream:ie}=this;ie&&ie.cancel();const se=new G.ReceiveSignalStreamRequest;se.setPeerId(L.getPeerId());const ue=yield(()=>De(this,void 0,void 0,function*(){try{return Z.receiveSignalStream(se,yield this.getMetadata({hasDeadline:!1}))}catch(fe){U.a.debug("createReceiveSignalStream failed",{error:fe});const Ue=Ot(fe);throw new Error("Unable to create receive signal stream: "+Ue)}}))();if(!ue)throw new Error("Response did not provide stream.");return ue.on("data",fe=>De(this,void 0,void 0,function*(){var Ue,ce,le,me;const Ve=fe.getSignal(),Ce=(Ue=Ve==null?void 0:Ve.getSessionId())===null||Ue===void 0?void 0:Ue.getValue(),xe=Ve==null?void 0:Ve.getSenderId(),He=Ve==null?void 0:Ve.getReceiverId(),Ye=(ce=Ve==null?void 0:Ve.getSessionCreatedTimestamp())===null||ce===void 0?void 0:ce.getValue();if(!(Ve&&Ce&&xe&&He&&Ye))return void U.a.warn("Received signal with missing information.");const qe=this.getActiveConnection(xe);if(qe)if(qe.getSessionId()!==Ce){if(U.a.debug("Received signal: different session for a peer we're already connected to."),(qe.getSessionCreatedTimestamp()||0)>Ye)return;const Pe=new Tt(yield this.createRTCPeerConnection(q),q,{baseConfig:{isOffer:!1,isLan:!1,receive:(Me,Le)=>this.config.receive(Me,Le),onStreamsInfoUpdate:this.config.onStreamsInfoUpdate?(Me,Le)=>{var Ge,Ke;return(Ke=(Ge=this.config).onStreamsInfoUpdate)===null||Ke===void 0?void 0:Ke.call(Ge,Me,Le)}:void 0,track:this.config.lanOnlyMode?void 0:this.config.track,localPeerId:L.getPeerId(),localUserId:(me=L.getUserId())===null||me===void 0?void 0:me.getValue(),remotePeerId:xe},remoteConfig:{sessionId:Ce,sessionCreatedTimestamp:Ye}},Me=>this.onCustomDataChannel(xe,Me));yield Pe.handleSignal(Ve),this.connections.push(Pe)}else U.a.debug("Received signal: for an existing connection."),yield qe.handleSignal(Ve);else{U.a.debug("Received signal: new connection.");const Pe=new Tt(yield this.createRTCPeerConnection(q),q,{baseConfig:{isOffer:!1,isLan:!1,receive:(Me,Le)=>this.config.receive(Me,Le),onStreamsInfoUpdate:this.config.onStreamsInfoUpdate?(Me,Le)=>{var Ge,Ke;return(Ke=(Ge=this.config).onStreamsInfoUpdate)===null||Ke===void 0?void 0:Ke.call(Ge,Me,Le)}:void 0,track:this.config.lanOnlyMode?void 0:this.config.track,localPeerId:L.getPeerId(),localUserId:(le=L.getUserId())===null||le===void 0?void 0:le.getValue(),remotePeerId:xe},remoteConfig:{sessionId:Ce,sessionCreatedTimestamp:Ye}},Me=>this.onCustomDataChannel(xe,Me));yield Pe.handleSignal(Ve),this.connections.push(Pe)}})),ue.on("end",()=>{ue.cancel(),this.receiveSignalStream=void 0}),ue.on("error",fe=>{switch(fe.code){case v.StatusCode.CANCELLED:case v.StatusCode.UNAVAILABLE:case v.StatusCode.UNKNOWN:U.a.debug("Receive signal stream error",{error:fe});break;case v.StatusCode.UNAUTHENTICATED:U.a.warn("Receive signal stream error",{error:fe});break;default:U.a.error("Receive signal stream error",{error:fe})}ue.cancel(),this.receiveSignalStream=void 0}),this.receiveSignalStream=ue})}createRTCPeerConnection(Z){var L;return De(this,void 0,void 0,function*(){const q=(L=this.config.alternateRTCPeerConnection)!==null&&L!==void 0?L:window.RTCPeerConnection;if(!q)throw function(){if(typeof navigator=="undefined")throw new Error("not a browser");const{userAgent:ie}=navigator;return ie.includes("Firefox/")?"Firefox":ie.includes("Edg/")?"Edge":ie.includes("Chrome/")?"Chrome":ie.includes("Safari/")?"Safari":ie.includes("MSIE/")||ie.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||vt();try{return new q({iceServers:Z})}catch(ie){throw U.a.debug(`Failed to create RTCPeerConnection: ${this.rtcInstancesConstructed} total allocated`),ie}})}closeConnections(Z){return De(this,void 0,void 0,function*(){const L=yield $(Z.map(q=>De(this,void 0,void 0,function*(){yield q.close()})));for(const q of L)U.a.warn("Request to close session failed",{error:q})})}getActiveConnection(Z){return this.getConnections().find(L=>L.getRemotePeerId()===Z&&L.isActive())}update(){var Z;return De(this,void 0,void 0,function*(){if(this.localConnections=this.localConnections.filter(me=>me.isActive()),this.config.lanOnlyMode)return;const{signalingClient:L}=this.config;if(!this.localPeer||!this.receiveSignalStream||!this.iceServers){const me=[];return this.localPeer||me.push(this.createPeer()),this.iceServers||me.push(this.updateIceServers()),yield Promise.all(me),void(this.receiveSignalStream||(yield this.createReceiveSignalStream()))}const[q,ie]=(se=this.connections,ue=me=>me.isActive(),se.reduce((me,Ve,Ce,xe)=>{const[He,Ye]=me;return(ue(Ve,Ce,xe)?He:Ye).push(Ve),me},[[],[]]));var se,ue;yield this.closeConnections(ie),this.connections=q,this.gatherConnectionStats().catch(me=>{U.a.warn("Error calling gatherConnectionStats",{error:me})}),this.statsLoopsExecuted++;const{localPeer:fe}=this,Ue=this.connections.filter(me=>me.getSessionId).map(me=>O(me.getSessionId()));fe.setSessionIdsList(Ue);const ce=new G.RefreshPeerRequest;ce.setPeer(fe);try{yield Y.withDeadline(L.refreshPeer(ce,yield this.getMetadata()),this.grpcCallDeadline)}catch(me){me instanceof v.RpcError&&me.code===v.StatusCode.NOT_FOUND?(U.a.warn("Peer expired, creating new peer",{peerId:fe.getPeerId()}),yield this.reset()):U.a.warn("Error calling RefreshPeer",{error:me})}const le=yield this.getPeers();for(const me of this.connections)me.setRemoteDeviceId((Z=le.find(Ve=>Ve.id===me.getRemotePeerId()))===null||Z===void 0?void 0:Z.deviceId)})}gatherConnectionStats(){return De(this,void 0,void 0,function*(){if(this.statsLoopsExecuted%10!=0||this.connections.length!==1)return;const Z=yield this.connections[0].getConnectionStatsInfo(),L=Z?bt(Z):void 0;L?x.setTag("rtc-connection-type",L):x.setTag("rtc-connection-type","unknown")})}reset(){return De(this,void 0,void 0,function*(){yield this.closeConnections(this.connections),this.connections=[],this.isOutgoingConnection.clear(),yield this.createPeer(),yield this.createReceiveSignalStream()})}updateIceServers(){return De(this,void 0,void 0,function*(){if(this.config.lanOnlyMode)return;const{iceServersLastUpdate:Z,iceServersTtl:L}=this,q=new Date().getTime();if(!Z||q-Z>L)try{const ie=(yield Y.withDeadline(this.config.signalingClient.getIceServers(new G.GetIceServersRequest,yield this.getMetadata()),this.grpcCallDeadline)).getIceServers();this.iceServers=JSON.parse(ie),this.iceServersLastUpdate=q}catch(ie){U.a.warn("Error in updateIceServers",{error:ie})}})}setupHandlers(Z){const{peerConnection:L}=Z,q=Z.getSessionCreatedTimestamp();L.onconnectionstatechange=()=>De(this,void 0,void 0,function*(){const ie=L.connectionState;if(!q)return;const se=Z.getRemoteDeviceId();switch(ie){case"connected":x.aggregate("rtc-connect-time",new Date().getTime()-q,Object.assign({},se?{deviceId:se}:{}));break;case"failed":x.increment("rtc-connect-failed",Object.assign({},se?{deviceId:se}:{}))}})}getMetadata(Z={}){return De(this,void 0,void 0,function*(){if(this.config.lanOnlyMode)throw new Error("getMetadata method cannot be called in local-only mode");const{getToken:L}=this.config,{grpcCallDeadline:q}=this,{hasDeadline:ie=!0}=Z,se=ie?{deadline:(Date.now()+q).toString(10)}:null;try{const ue=yield L();return Object.assign({authorization:ue},se)}catch(ue){throw U.a.error("getToken() failed",{error:ue}),new Error("Cannot get authorization token")}})}}var tt=n(12),Ut=n(11),xt=function(Re,Z,L,q){return new(L||(L=Promise))(function(ie,se){function ue(ce){try{Ue(q.next(ce))}catch(le){se(le)}}function fe(ce){try{Ue(q.throw(ce))}catch(le){se(le)}}function Ue(ce){var le;ce.done?ie(ce.value):(le=ce.value,le instanceof L?le:new L(function(me){me(le)})).then(ue,fe)}Ue((q=q.apply(Re,Z||[])).next())})};class Jt{constructor(Z,L){this.sentMessagesCounts=new Map,this.receivedMessagesCounts=new Map,this.sessionId=Z,this.connection=L}incrementMessageSent(Z){const L=Oe(Z.header.stream);this.sentMessagesCounts.set(L,(this.sentMessagesCounts.get(L)||0)+1)}incrementMessageReceived(Z){const L=Oe(Z.header.stream);this.receivedMessagesCounts.set(L,(this.receivedMessagesCounts.get(L)||0)+1)}uploadMetrics(){return xt(this,void 0,void 0,function*(){const{sessionId:Z}=this,L=yield this.connection.peerConnection.getStats(),q={};L.forEach(se=>q[se.id]=se),U.a.debug("rtc-stats",Object.assign(Object.assign({},q),{sessionId:Z}));const ie=[...new Set(Array.from(this.sentMessagesCounts.keys()).concat(Array.from(this.receivedMessagesCounts.keys())))].reduce((se,ue)=>{const fe=this.sentMessagesCounts.get(ue),Ue=this.receivedMessagesCounts.get(ue);return Object.assign(Object.assign({},se),{[ue+"-sent"]:fe,[ue+"-received"]:Ue})},{sessionId:Z});U.a.debug("rtc-message-report",ie)})}}function ft(Re,Z){return Oe(Re)===Oe(Z)}var nt=function(Re,Z,L,q){return new(L||(L=Promise))(function(ie,se){function ue(ce){try{Ue(q.next(ce))}catch(le){se(le)}}function fe(ce){try{Ue(q.throw(ce))}catch(le){se(le)}}function Ue(ce){var le;ce.done?ie(ce.value):(le=ce.value,le instanceof L?le:new L(function(me){me(le)})).then(ue,fe)}Ue((q=q.apply(Re,Z||[])).next())})};class Wt{constructor(Z,L){this.peerConnection=Z,this.config=L,this.connectTimeoutMs=10*u.a.second,this.gatherIceTimeoutMs=5*u.a.second,this.pingUpdateTimeoutMs=2*u.a.second,this.streamLatestTimestamp=new Map,this.closeCalled=!1,this.connectCalled=!1,this.sentOffer=!1,this.receivedIceCandidate=!1;const{isOffer:q}=L;q?this.initializeChannels(Z):Z.ondatachannel=ie=>{switch(ie.channel.label){case"stream.latest-ttl":this.latestTtlStreamChannel=ie.channel;break;case"stream.reliable":this.reliableStreamChannel=ie.channel;break;case"stream.latest-reliable":this.latestReliableStreamChannel=ie.channel;break;case"stream.latest-try-once":this.latestTryOnceStreamChannel=ie.channel}this.setupChannel(ie.channel)},this.sessionMetrics=new Jt(this.getSessionId(),this)}connect(){return nt(this,void 0,void 0,function*(){if(this.connectCalled)return;this.connectCalled=!0,this.pingUpdateTimeout=setInterval(()=>{const{reliableStreamChannel:ie}=this;ie&&this.sendSystemMessage(ie,{type:"ping"})},this.pingUpdateTimeoutMs),this.connectTimeout=setTimeout(()=>nt(this,void 0,void 0,function*(){this.isReady()||(U.a.warn("RTC connect timed out, closing connection"),yield this.close())}),this.connectTimeoutMs);const{peerConnection:Z,config:{isOffer:L,sessionId:q}}=this;if(L){const ie=yield Z.createOffer();yield Z.setLocalDescription(ie)}L&&(this.gatherIceTimeout=setTimeout(()=>nt(this,void 0,void 0,function*(){this.sentOffer||(U.a.warn("ICE gathering timed out"),this.receivedIceCandidate?(U.a.warn("Attempting to connect with partial ICE candidate pool"),yield this.sendOffer()):yield this.close())}),this.gatherIceTimeoutMs),Z.onicecandidate=ie=>nt(this,void 0,void 0,function*(){ie.candidate?this.receivedIceCandidate=!0:yield this.sendOffer()}),Z.onicegatheringstatechange=()=>nt(this,void 0,void 0,function*(){Z.iceGatheringState==="complete"&&(yield this.sendOffer())}),Z.onnegotiationneeded=()=>{U.a.debug("Negotiation needed",{sessionId:q})})})}handleSignal(Z){return nt(this,void 0,void 0,function*(){const{peerConnection:L,config:{sessionId:q,sendSignal:ie}}=this,{description:se}=JSON.parse(Z.payload);if(U.a.debug("Handling signal",{sessionId:q,description:JSON.stringify(se)}),se)if(L.signalingState!=="stable"||L.connectionState!=="connected")if(L.remoteDescription)U.a.warn("Received SDP signal during negotiation when remote description is already set: "+JSON.stringify(Z));else if(se.type==="offer"){yield L.setRemoteDescription(se);const ue=yield L.createAnswer();yield L.setLocalDescription(ue),yield ie({payload:JSON.stringify({description:ue})})}else se.type==="answer"&&(yield L.setRemoteDescription(se));else U.a.warn("Received SDP signal when signaling is stable and connected: "+JSON.stringify(Z));else U.a.warn("Received non-SDP signal: "+JSON.stringify(Z))})}send(Z,L){const q=this.getChannelFromLabel(L.channelLabel);q?this.sendOnChannel(q,Z):U.a.warn("Send called with unexpected channel label",{channelLabel:L.channelLabel})}controlRemoteStream(Z){this.sendSystemMessage(O(this.reliableStreamChannel),{type:"stream-control",streamControl:Z})}isActive(){return new Set(["new","connecting","connected"]).has(this.peerConnection.connectionState)}isReady(){const{peerConnection:Z,latestTtlStreamChannel:L,reliableStreamChannel:q,latestTryOnceStreamChannel:ie}=this;return!!(q&&L&&ie)&&Z.connectionState==="connected"&&q.readyState==="open"&&L.readyState==="open"&&ie.readyState==="open"}isClosed(){const{peerConnection:Z,reliableStreamChannel:L,latestTryOnceStreamChannel:q,latestTtlStreamChannel:ie}=this;return!(Z.connectionState!=="closed"||L!==void 0&&L.readyState!=="closed"||q!==void 0&&q.readyState!=="closed"||ie!==void 0&&ie.readyState!=="closed")}needsClosing(){const{peerConnection:Z,latestTtlStreamChannel:L,reliableStreamChannel:q,latestTryOnceStreamChannel:ie}=this;if(this.isClosed())return!1;const se=new Set(["closing","closed"]),ue=fe=>fe&&se.has(fe.readyState);return gt(Z)||ue(L)||ue(q)||ue(ie)}close(){return nt(this,void 0,void 0,function*(){this.closeCalled||(this.closeCalled=!0,yield this.sessionMetrics.uploadMetrics(),this.pingUpdateTimeout&&clearInterval(this.pingUpdateTimeout),this.connectTimeout&&clearTimeout(this.connectTimeout),this.gatherIceTimeout&&clearTimeout(this.gatherIceTimeout),this.peerConnection.close())})}getPing(){return this.pingTimeMs}getLastMessageTimestamp(){return this.lastMessageTimestamp}getSessionId(){return this.config.sessionId}getRemotePeer(){return this.config.remotePeer}initializeChannels(Z){this.latestTtlStreamChannel=Z.createDataChannel("stream.latest-ttl",oe),this.reliableStreamChannel=Z.createDataChannel("stream.reliable",ge),this.latestReliableStreamChannel=Z.createDataChannel("stream.latest-reliable",Se),this.latestTryOnceStreamChannel=Z.createDataChannel("stream.latest-try-once",ve),this.setupChannel(this.latestTtlStreamChannel),this.setupChannel(this.reliableStreamChannel),this.setupChannel(this.latestReliableStreamChannel),this.setupChannel(this.latestTryOnceStreamChannel)}sendOffer(){return nt(this,void 0,void 0,function*(){if(this.sentOffer||(this.sentOffer=!0,gt(this.peerConnection)))return;const{peerConnection:Z,config:{sendSignal:L}}=this,q=yield Z.createOffer();yield Z.setLocalDescription(q);const ie={payload:JSON.stringify({description:q})};yield L(ie)})}getChannelFromLabel(Z){switch(Z){case"stream.latest-ttl":return this.latestTtlStreamChannel;case"stream.reliable":return this.reliableStreamChannel;case"stream.latest-reliable":return this.latestReliableStreamChannel;case"stream.latest-try-once":return this.latestTryOnceStreamChannel}}sendOnChannel(Z,L){let q;try{q=Object(te.encode)(JSON.stringify(L))}catch(ie){return void U.a.warn("Failed to encode RTC message",{error:ie})}try{Z.send(q),this.sessionMetrics.incrementMessageSent(L)}catch(ie){U.a.warn("Failed to send message to channel",{error:ie,channel:Z.label})}}channelNotRecognized(Z){return Z!==this.latestTtlStreamChannel&&Z!==this.latestReliableStreamChannel&&Z!==this.latestTryOnceStreamChannel&&Z!==this.reliableStreamChannel}setupChannel(Z){Z.onmessage=L=>{if(this.channelNotRecognized(Z))return void U.a.warn("Received message on unrecognized data channel.");let q;try{q=JSON.parse(Object(te.decode)(L.data))}catch(ie){return void U.a.warn("Received unparseable RTC message",{error:ie,channel:Z.label})}if(this.lastMessageTimestamp=new Date().getTime(),q=Et(q),this.sessionMetrics.incrementMessageReceived(q),!this.handleSystemMessage(Z,q)){if(!this.hasCapabilities(q))return void U.a.warn("Received RTC message that was not within the capability scope of the connection.");(Z===this.latestTryOnceStreamChannel||Z===this.latestTtlStreamChannel||Z===this.latestReliableStreamChannel)&&!this.isLatestMessage(q)||this.config.receive(this.config.remotePeer.id,q)}},Z.onerror=L=>{U.a.warn("Channel error: "+L.error,{error:L.error,sessionId:this.getSessionId(),channelLabel:Z.label})},Z.onopen=()=>{U.a.debug("Channel opened",{sessionId:this.getSessionId(),channelLabel:Z.label})},Z.onclose=()=>{const L={bufferedAmount:Z.bufferedAmount,sessionId:this.getSessionId(),channelLabel:Z.label};this.closeCalled===!1?U.a.debug("Unexpected channel closed",L):U.a.debug("Channel closed",L)}}handleSystemMessage(Z,L){switch(L.header.stream.streamType){case"ping":return this.sendSystemMessage(Z,{type:"pong",timestamp:O(L.payload.ping)}),!0;case"pong":{const q=new Date().getTime()-O(L.payload.pong);return this.pingTimeMs=q,x.aggregate("rtc-ping-time",q),!0}case"stream-control":return!0;default:return!1}}sendSystemMessage(Z,L){if(Z.readyState!=="open")return;const q={entityId:O(this.config.localPeer.deviceId||this.config.localPeer.userId),streamName:"$."+L.type,streamType:L.type};let ie;switch(L.type){case"ping":ie={ping:new Date().getTime()};break;case"pong":ie={pong:L.timestamp};break;case"stream-control":ie={streamControl:L.streamControl}}this.sendOnChannel(Z,wt(q,ie))}hasCapabilities(Z){var L,q;const{localPeer:ie,remotePeer:se}=this.config,ue=(L=ie.capabilitySet.streaming)===null||L===void 0?void 0:L.streams,fe=ue&&ue.some(le=>le.receive&&ft(le.stream,Z.header.stream)),Ue=(q=se.capabilitySet.streaming)===null||q===void 0?void 0:q.streams,ce=Ue&&Ue.some(le=>le.send&&ft(le.stream,Z.header.stream));return fe||ce}isLatestMessage(Z){const L=Oe(Z.header.stream),q=(this.streamLatestTimestamp.get(L)||0)<=Z.header.created;return q&&this.streamLatestTimestamp.set(L,Z.header.created),q}}var Ae=function(Re,Z,L,q){return new(L||(L=Promise))(function(ie,se){function ue(ce){try{Ue(q.next(ce))}catch(le){se(le)}}function fe(ce){try{Ue(q.throw(ce))}catch(le){se(le)}}function Ue(ce){var le;ce.done?ie(ce.value):(le=ce.value,le instanceof L?le:new L(function(me){me(le)})).then(ue,fe)}Ue((q=q.apply(Re,Z||[])).next())})};class Ct{constructor(Z){this.config=Z,this.connections=[],this.connectingSessions=new Map,this.rtcInstancesConstructed=0,this.updateInterval=T({func:()=>Ae(this,void 0,void 0,function*(){try{yield this.update()}catch(L){U.a.warn("RTC update failed",{error:L})}}),delay:250*u.a.millisecond,immediate:!0}),this.localPeer=this.createPeer()}send(Z,L,q){const ie=this.getActiveConnection(Z);ie?ie.isReady()?ie.send(L,q):U.a.warn("Attempted to send with an active connection to that peer which was not yet ready."):U.a.warn("Attempted to send with no active connection to that peer.")}controlRemoteStream(Z,L){const q=this.getActiveConnection(Z);q?q.isReady()?q.controlRemoteStream(L):U.a.warn("Attempted to control remote stream with an active connection to that peer which was not yet ready."):U.a.warn("Attempted to control remote stream with no active connection to that peer.")}connect(Z){return Ae(this,void 0,void 0,function*(){const L=yield this.getLocalPeer();if(this.getActiveConnection(Z))return void U.a.warn("Attempted to connect to peer with an already active connection.");let q;try{q=yield this.config.signalingClient.createSession(yield this.config.getToken(),{offerPeerId:L.id,answerPeerId:Z})}catch(ie){Object(tt.a)(ie,Ut.a,se=>se.statusCode===404),U.a.warn("Attempted to connect to peer that does not exist.")}if(q)for(this.connectingSessions.set(q.id,new Date().getTime()),yield this.connectToSession(q);;)switch(yield Object(c.a)(.1),this.getConnectionStatus(Z)){case"connecting":continue;case"connected":return q.id;case"disconnected":return}})}getConnectionStatus(Z){const L=this.getActiveConnection(Z);return L?L.isReady()?"connected":"connecting":"disconnected"}getIceMode(Z){const L=this.getActiveConnection(Z);if(L)return L.iceMode}disconnect(Z){return Ae(this,void 0,void 0,function*(){const L=this.getActiveConnection(Z);L&&(yield this.closeConnection(L))})}getLocalPeer(){return Ae(this,void 0,void 0,function*(){return yield this.localPeer})}getPeers(){return Ae(this,void 0,void 0,function*(){return yield this.config.signalingClient.getPeers(yield this.config.getToken())})}getPing(Z){const L=this.getActiveConnection(Z);if(L)return L.getPing();U.a.warn("Attempted to get ping time from inactive peer.")}getLastMessageTimestamp(Z){const L=this.getActiveConnection(Z);if(L)return L.getLastMessageTimestamp();U.a.warn("Attempted to get ping time from inactive peer.")}shutdown(){return Ae(this,void 0,void 0,function*(){yield this.updateInterval.stop();const Z=this.connections;this.connections=[],yield this.closeConnections(Z)})}closeConnection(Z){return Ae(this,void 0,void 0,function*(){this.connectingSessions.delete(Z.getSessionId()),yield Z.close();try{yield this.config.signalingClient.deleteSession(yield this.config.getToken(),Z.getSessionId())}catch(L){Object(tt.a)(L,Ut.a,q=>q.statusCode===404)}})}getSessions(){return Ae(this,void 0,void 0,function*(){const Z=yield this.getLocalPeer();return(yield this.config.signalingClient.getSessions(yield this.config.getToken())).filter(L=>L.offer.peer.id===Z.id||L.answer.peer.id===Z.id)})}createPeer(){return Ae(this,void 0,void 0,function*(){return yield this.config.signalingClient.createPeer(yield this.config.getToken(),{capabilitySet:this.config.capabilitySet||{}})})}createRTCPeerConnection(Z={}){return Ae(this,void 0,void 0,function*(){const L=this.config.alternateRTCPeerConnection||RTCPeerConnection;this.rtcInstancesConstructed++,this.rtcInstancesConstructed%20||vt();try{return new L(Object.assign({iceServers:yield this.config.signalingClient.getIceServers(yield this.config.getToken())},Z))}catch(q){throw U.a.debug(`Failed to create RTCPeerConnection: ${this.rtcInstancesConstructed} total allocated`),q}})}closeConnections(Z){return Ae(this,void 0,void 0,function*(){const L=yield $(Z.map(q=>Ae(this,void 0,void 0,function*(){yield this.closeConnection(q)})));for(const q of L)U.a.warn("Request to close session failed",{error:q})})}reset(){return Ae(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(Z){return this.connections.find(L=>L.getRemotePeer().id===Z&&L.isActive())}update(){return Ae(this,void 0,void 0,function*(){const Z=yield this.getLocalPeer();try{yield this.config.signalingClient.refreshPeer(yield this.config.getToken(),Z.id)}catch(L){Object(tt.a)(L,Ut.a,q=>q.statusCode===404),U.a.warn("Peer expired, creating new peer",{peerId:Z.id}),yield this.reset()}yield this.handleSessions(yield this.getSessions())})}handleSessions(Z){return Ae(this,void 0,void 0,function*(){yield this.syncConnectionsAndSessions(Z);const L=Z.map(q=>({session:q,connection:this.connections.find(ie=>ie.getSessionId()===q.id)}));yield Promise.all(L.map(({session:q,connection:ie})=>Ae(this,void 0,void 0,function*(){return yield this.maintainConnection(q,ie)})))})}syncConnectionsAndSessions(Z){return Ae(this,void 0,void 0,function*(){const L=new Set(Z.map(se=>se.id)),q=se=>L.has(se.getSessionId())||this.connectingSessions.has(se.getSessionId());this.connections=this.connections.filter(se=>q(se));const ie=this.connections.filter(se=>!q(se)||se.needsClosing());yield Promise.all(ie.map(se=>Ae(this,void 0,void 0,function*(){yield this.closeConnection(se)})))})}maintainConnection(Z,L){return Ae(this,void 0,void 0,function*(){const q=yield this.getLocalPeer(),ie=Z.offer.peer.id===q.id;if(L){if(L.isReady())try{yield this.config.signalingClient.refreshSession(yield this.config.getToken(),Z.id)}catch(se){Object(tt.a)(se,Ut.a,ue=>ue.statusCode===404),U.a.debug("Refresh session not found",{sessionId:Z.id})}else if(L.isActive())try{yield this.consumeSignals(L)}catch(se){U.a.warn("Failed to ingest signals, closing connection",{error:se}),yield this.closeConnection(L)}}else{if(ie)return;yield this.connectToSession(Z)}})}connectToSession(Z){return Ae(this,void 0,void 0,function*(){const L=yield this.getLocalPeer(),q=Z.offer.peer.id===L.id,ie=yield this.createRTCPeerConnection(),se=new Wt(ie,{localPeer:q?Z.offer.peer:Z.answer.peer,remotePeer:q?Z.answer.peer:Z.offer.peer,sessionId:Z.id,isOffer:q,sendSignal:ue=>this.sendSignal(Z.id,ue),receive:(ue,fe)=>this.config.receive(ue,fe)});if(this.connections.find(ue=>ue.getSessionId()===Z.id))return U.a.warn("connectToSession called on a session that already has a connection.",{sessionId:Z.id}),void(yield se.close());this.setupHandlers(se),this.connections.push(se);try{yield se.connect()}catch(ue){U.a.warn("Failed to handle negotiation, closing connection",{error:ue}),yield this.closeConnection(se)}})}setupHandlers(Z){const{peerConnection:L}=Z,q=Z.getSessionId();L.onconnectionstatechange=()=>Ae(this,void 0,void 0,function*(){const ie=this.connectingSessions.get(q);if(ie===void 0)return;const se=L.connectionState;switch(gt(L)&&this.connectingSessions.delete(q),se){case"connected":{this.connectingSessions.delete(q);const ue=new Date().getTime()-ie;x.aggregate("rtc-connect-time",ue);break}case"failed":x.increment("rtc-connect-failed"),yield this.closeConnection(Z)}})}consumeSignals(Z){return Ae(this,void 0,void 0,function*(){let L=[];try{L=yield this.config.signalingClient.takeSignals(yield this.config.getToken(),Z.getSessionId())}catch(q){Object(tt.a)(q,Ut.a,ie=>ie.statusCode===404)}for(const q of L)yield Z.handleSignal(q)})}sendSignal(Z,L){return Ae(this,void 0,void 0,function*(){try{yield this.config.signalingClient.addSignals(yield this.config.getToken(),Z,{signals:[L]})}catch(q){Object(tt.a)(q,Ut.a,ie=>ie.statusCode===404)}})}}},,function(e,t,n){n.r(t),n.d(t,"LogClient",function(){return l});var r=n(26),o=n(12),s=n(11),g=function(u,c,d,B){return new(d||(d=Promise))(function(Q,f){function p(M){try{E(B.next(M))}catch(W){f(W)}}function U(M){try{E(B.throw(M))}catch(W){f(W)}}function E(M){var W;M.done?Q(M.value):(W=M.value,W instanceof d?W:new d(function(y){y(W)})).then(p,U)}E((B=B.apply(u,c||[])).next())})};class l extends r.a{log(c){return g(this,void 0,void 0,function*(){const d=l.token;try{yield this.fetch("logs",{token:d,method:"POST",body:{logs:c},allowUnsafeRetries:!0})}catch(B){Object(o.a)(B,s.a,Q=>Q.statusCode===401&&d!==void 0),l.token===d&&delete l.token,yield this.log(c)}})}}},function(e,t,n){var r={randomUUID:typeof crypto!="undefined"&&crypto.randomUUID&&crypto.randomUUID.bind(crypto)};let o;const s=new Uint8Array(16);function g(){if(!o&&(o=typeof crypto!="undefined"&&crypto.getRandomValues&&crypto.getRandomValues.bind(crypto),!o))throw new Error("crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported");return o(s)}const l=[];for(let c=0;c<256;++c)l.push((c+256).toString(16).slice(1));function u(c,d=0){return(l[c[d+0]]+l[c[d+1]]+l[c[d+2]]+l[c[d+3]]+"-"+l[c[d+4]]+l[c[d+5]]+"-"+l[c[d+6]]+l[c[d+7]]+"-"+l[c[d+8]]+l[c[d+9]]+"-"+l[c[d+10]]+l[c[d+11]]+l[c[d+12]]+l[c[d+13]]+l[c[d+14]]+l[c[d+15]]).toLowerCase()}t.a=function(c,d,B){if(r.randomUUID&&!d&&!c)return r.randomUUID();const Q=(c=c||{}).random||(c.rng||g)();if(Q[6]=15&Q[6]|64,Q[8]=63&Q[8]|128,d){B=B||0;for(let f=0;f<16;++f)d[B+f]=Q[f];return d}return u(Q)}}])})})(dist);var distExports=dist.exports;const SessionTypes={UNKNOWN:0,TELEOP:1,PORT_FORWARD:2,OBSERVE:3,HEADLESS:4},SessionTypeConstants={...SessionTypes,Unknown:SessionTypes.UNKNOWN,Teleop:SessionTypes.TELEOP,PortForward:SessionTypes.PORT_FORWARD,Observe:SessionTypes.OBSERVE,Headless:SessionTypes.HEADLESS,unknown:SessionTypes.UNKNOWN,teleop:SessionTypes.TELEOP,portForward:SessionTypes.PORT_FORWARD,observe:SessionTypes.OBSERVE,headless:SessionTypes.HEADLESS},singleton=Symbol("RtcClientPool.instance");var Sn;class RtcClientPool{constructor(t){he(this,Sn,null);he(this,"createClient");he(this,"ttlMs");he(this,"proxyHandler");he(this,"proxyReceivers",new Map);he(this,"teardownTimeout",null);he(this,"dispatch",(t,n)=>{this.proxyReceivers.forEach(r=>r==null?void 0:r(t,n))});const{createClient:n,ttlMs:r=0}=t;this.createClient=n,this.ttlMs=Math.max(r,0),this.proxyHandler={get:(o,s,g)=>{switch(s){case"shutdown":return()=>this.releaseInstance(g);default:return Reflect.get(o,s,g)}}}}get isActive(){return this[singleton]!==null}get size(){return this.proxyReceivers.size}get(t){const n=new Proxy(this.allocate(),this.proxyHandler);return this.proxyReceivers.set(n,t!=null?t:null),n}allocate(){if(this[singleton])return this.teardownTimeout&&(clearTimeout(this.teardownTimeout),this.teardownTimeout=null),this[singleton];const t=this.createClient(this.dispatch);return this[singleton]=t,t}async teardown(){const t=this[singleton];if(!t){console.warn("singleton has already been shutdown!");return}try{await t.shutdown()}finally{this[singleton]=null}}async releaseInstance(t){return this.proxyReceivers.delete(t)?this.proxyReceivers.size!==0?!1:(!this.teardownTimeout&&Number.isFinite(this.ttlMs)&&(this.ttlMs===0?await this.teardown():this.teardownTimeout=setTimeout(()=>{this.teardown().catch(n=>console.error("teardown failed",{err:n})).finally(()=>this.teardownTimeout=null)},this.ttlMs)),!0):(console.warn("this instance has already been released!"),!1)}}Sn=singleton;function defined$1(e,t){if(e!==void 0)return e;throw new Error(t||"Value is undefined")}function notNull(e,t){if(e!==null)return e;throw new Error(t||"Value is null")}function definedAndNotNull(e,t){return notNull(defined$1(e,t),t)}const getToken=async()=>defined$1(Authentication.token,"Realtime when user isn't authorized"),EnumRtcClientPools={[SessionTypes.UNKNOWN]:new RtcClientPool({ttlMs:2500,createClient:e=>new distExports.RtcClient({signalingClient:new distExports.SignalingPromiseClient(exports.FORMANT_API_URL),getToken,sessionType:SessionTypes.UNKNOWN,receive:e})}),[SessionTypes.TELEOP]:new RtcClientPool({ttlMs:2500,createClient:e=>new distExports.RtcClient({signalingClient:new distExports.SignalingPromiseClient(exports.FORMANT_API_URL),getToken,sessionType:SessionTypes.TELEOP,receive:e})}),[SessionTypes.PORT_FORWARD]:new RtcClientPool({ttlMs:2500,createClient:e=>new distExports.RtcClient({signalingClient:new distExports.SignalingPromiseClient(exports.FORMANT_API_URL),getToken,sessionType:SessionTypes.PORT_FORWARD,receive:e})}),[SessionTypes.OBSERVE]:new RtcClientPool({ttlMs:2500,createClient:e=>new distExports.RtcClient({signalingClient:new distExports.SignalingPromiseClient(exports.FORMANT_API_URL),getToken,sessionType:SessionTypes.OBSERVE,receive:e})}),[SessionTypes.HEADLESS]:new RtcClientPool({ttlMs:2500,createClient:e=>new distExports.RtcClient({signalingClient:new distExports.SignalingPromiseClient(exports.FORMANT_API_URL),getToken,sessionType:SessionTypes.HEADLESS,receive:e})})},AppRtcClientPools={...EnumRtcClientPools,unknown:EnumRtcClientPools[SessionTypes.UNKNOWN],teleop:EnumRtcClientPools[SessionTypes.TELEOP],portForward:EnumRtcClientPools[SessionTypes.PORT_FORWARD],observe:EnumRtcClientPools[SessionTypes.OBSERVE],headless:EnumRtcClientPools[SessionTypes.HEADLESS]},defaultRtcClientPool=EnumRtcClientPools[SessionTypes.TELEOP],getRtcClientPool=e=>{const{sessionType:t}=e;return t?AppRtcClientPools[t]:defaultRtcClientPool};function delay(e){return new Promise(t=>setTimeout(t,e))}const isRtcPeer=e=>e!==void 0&&e.capabilities!==void 0&&e.capabilitySet!==void 0;var eventemitter3={exports:{}};(function(e){var t=Object.prototype.hasOwnProperty,n="~";function r(){}Object.create&&(r.prototype=Object.create(null),new r().__proto__||(n=!1));function o(u,c,d){this.fn=u,this.context=c,this.once=d||!1}function s(u,c,d,B,Q){if(typeof d!="function")throw new TypeError("The listener must be a function");var f=new o(d,B||u,Q),p=n?n+c:c;return u._events[p]?u._events[p].fn?u._events[p]=[u._events[p],f]:u._events[p].push(f):(u._events[p]=f,u._eventsCount++),u}function g(u,c){--u._eventsCount===0?u._events=new r:delete u._events[c]}function l(){this._events=new r,this._eventsCount=0}l.prototype.eventNames=function(){var c=[],d,B;if(this._eventsCount===0)return c;for(B in d=this._events)t.call(d,B)&&c.push(n?B.slice(1):B);return Object.getOwnPropertySymbols?c.concat(Object.getOwnPropertySymbols(d)):c},l.prototype.listeners=function(c){var d=n?n+c:c,B=this._events[d];if(!B)return[];if(B.fn)return[B.fn];for(var Q=0,f=B.length,p=new Array(f);Q<f;Q++)p[Q]=B[Q].fn;return p},l.prototype.listenerCount=function(c){var d=n?n+c:c,B=this._events[d];return B?B.fn?1:B.length:0},l.prototype.emit=function(c,d,B,Q,f,p){var U=n?n+c:c;if(!this._events[U])return!1;var E=this._events[U],M=arguments.length,W,y;if(E.fn){switch(E.once&&this.removeListener(c,E.fn,void 0,!0),M){case 1:return E.fn.call(E.context),!0;case 2:return E.fn.call(E.context,d),!0;case 3:return E.fn.call(E.context,d,B),!0;case 4:return E.fn.call(E.context,d,B,Q),!0;case 5:return E.fn.call(E.context,d,B,Q,f),!0;case 6:return E.fn.call(E.context,d,B,Q,f,p),!0}for(y=1,W=new Array(M-1);y<M;y++)W[y-1]=arguments[y];E.fn.apply(E.context,W)}else{var m=E.length,h;for(y=0;y<m;y++)switch(E[y].once&&this.removeListener(c,E[y].fn,void 0,!0),M){case 1:E[y].fn.call(E[y].context);break;case 2:E[y].fn.call(E[y].context,d);break;case 3:E[y].fn.call(E[y].context,d,B);break;case 4:E[y].fn.call(E[y].context,d,B,Q);break;default:if(!W)for(h=1,W=new Array(M-1);h<M;h++)W[h-1]=arguments[h];E[y].fn.apply(E[y].context,W)}}return!0},l.prototype.on=function(c,d,B){return s(this,c,d,B,!1)},l.prototype.once=function(c,d,B){return s(this,c,d,B,!0)},l.prototype.removeListener=function(c,d,B,Q){var f=n?n+c:c;if(!this._events[f])return this;if(!d)return g(this,f),this;var p=this._events[f];if(p.fn)p.fn===d&&(!Q||p.once)&&(!B||p.context===B)&&g(this,f);else{for(var U=0,E=[],M=p.length;U<M;U++)(p[U].fn!==d||Q&&!p[U].once||B&&p[U].context!==B)&&E.push(p[U]);E.length?this._events[f]=E.length===1?E[0]:E:g(this,f)}return this},l.prototype.removeAllListeners=function(c){var d;return c?(d=n?n+c:c,this._events[d]&&g(this,d)):(this._events=new r,this._eventsCount=0),this},l.prototype.off=l.prototype.removeListener,l.prototype.addListener=l.prototype.on,l.prefixed=n,l.EventEmitter=l,e.exports=l})(eventemitter3);var eventemitter3Exports=eventemitter3.exports;const EventEmitter=getDefaultExportFromCjs(eventemitter3Exports);class Manipulator{constructor(t,n){he(this,"currentListeners",[]);he(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){he(this,"channel");he(this,"requestIdToResponseMap",new Map);this.device=t,this.channel_name=n,this.timeout=r}addOpenListener(t){defined$1(this.channel,"channel not initalized").addOpenListener(t)}removeOpenListener(t){defined$1(this.channel,"channel not initalized").removeOpenListener(t)}addCloseListener(t){defined$1(this.channel,"channel not initalized").addCloseListener(t)}removeCloseListener(t){defined$1(this.channel,"channel not initalized").removeCloseListener(t)}addErrorListener(t){defined$1(this.channel,"channel not initalized").addErrorListener(t)}removeErrorListener(t){defined$1(this.channel,"channel not initalized").removeErrorListener(t)}}class BinaryRequestDataChannel extends RequestDataChannel{constructor(){super(...arguments);he(this,"RESPONSE_SUCCESS_BYTE",0);he(this,"decoder",new TextDecoder)}generateBinaryId(){const n=new Uint8Array(16);for(let r=0;r<n.length;r++)n[r]=Math.floor(Math.random()*256);return n}async initialize(){this.channel=await this.device.createCustomDataChannel(this.channel_name),this.channel.addBinaryListener(n=>{const o=n.slice(0,16).toString();if(o.length===0)throw new Error("Invalid response");const s=n.slice(16);if(s.length===0)throw new Error("Invalid response");this.requestIdToResponseMap.has(o)&&this.requestIdToResponseMap.set(o,s)})}async request(n){if(this.channel||await this.initialize(),!this.channel)throw new Error("Failed to create channel");const{channel:r,requestIdToResponseMap:o,timeout:s}=this;await r.waitTilReady();const g=this.generateBinaryId(),l=g.toString();o.set(l,!0),r.sendBinary(new Uint8Array([...g,...n]));const u=new Date().getTime();for(;new Date().getTime()<u+s;)if(await delay(50),o.has(l)){const c=o.get(l);if(c!==!0){o.delete(l);const d=c[0]===this.RESPONSE_SUCCESS_BYTE,B=c.slice(1);if(d)return B;throw console.error({name:"AdapterError",message:this.decoder.decode(B)}),new Error("Binary request datachannel adapter error")}}throw o.delete(l),console.error({name:"TimeoutError",message:`Request timed out after ${s/1e3} seconds`}),new Error("Binary request data channel request timed out")}}class TextRequestDataChannel extends RequestDataChannel{generateTextId(){return Math.random().toString(36).substring(2)+"-"+Math.random().toString(36).substring(2)}async initialize(){this.channel=await this.device.createCustomDataChannel(this.channel_name),this.channel.addListener(t=>{const n=JSON.parse(t),{id:r,data:o,error:s}=n;if(!r)throw new Error("Invalid response");if(!o&&!s)throw new Error("Invalid response");this.requestIdToResponseMap.has(r)&&this.requestIdToResponseMap.set(r,n)})}async request(t){if(this.channel||await this.initialize(),!this.channel)throw new Error("Failed to create channel");const{channel:n,requestIdToResponseMap:r,timeout:o}=this;await n.waitTilReady();const s=this.generateTextId();r.set(s,!0),n.send(JSON.stringify({id:s,data:t}));const g=new Date().getTime();for(;new Date().getTime()<g+o;)if(await delay(50),r.has(s)){const l=r.get(s);if(l!==!0){r.delete(s);const{data:u,error:c}=l;if(u)return u;if(c)throw console.error({name:"AdapterError",message:c}),new Error("Text request datachannel adapter error")}}throw r.delete(s),console.error({name:"TimeoutError",message:`Request timed out after ${o/1e3} seconds`}),new Error("Text request datachannel request timed out")}}class BaseDevice extends EventEmitter{constructor(){super(...arguments);he(this,"rtcClient");he(this,"remoteDevicePeerId",null);he(this,"realtimeListeners",[]);he(this,"connectionMonitorInterval");he(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(){var o;const n=await this.getConfiguration(),r=[];for(const s of(o=n.teleop.rosStreams)!=null?o:[])s.topicType=="sensor_msgs/JointState"&&r.push(new Manipulator(this,{currentJointStateStream:{name:s.topicName},plannedJointStateStream:s.plannedTopic?{name:s.plannedTopic}:void 0,planValidStream:s.planValidTopic?{name:s.planValidTopic}:void 0,endEffectorStream:s.endEffectorTopic?{name:s.endEffectorTopic}:void 0,endEffectorLinkName:s.endEffectorLinkName,baseReferenceFrame:s.baseReferenceFrame,localFrame:s.localFrame}));return r}async getRealtimeVideoStreams(){var o,s,g,l,u,c;const n=await this.getConfiguration(),r=[];for(const d of(s=(o=n.teleop)==null?void 0:o.hardwareStreams)!=null?s:[])d.rtcStreamType==="h264-video-frame"&&r.push({name:d.name});for(const d of(l=(g=n.teleop)==null?void 0:g.rosStreams)!=null?l:[])d.topicType=="formant/H264VideoFrame"&&r.push({name:d.topicName}),(d.topicType==="sensor_msgs/Image"||d.topicType==="sensor_msgs/CompressedImage")&&d.encodeVideo&&r.push({name:d.topicName});for(const d of(c=(u=n.teleop)==null?void 0:u.customStreams)!=null?c:[])d.rtcStreamType==="h264-video-frame"&&r.push({name:d.name});return r}createCustomRequestDataChannel(n,r=3e3){return new TextRequestDataChannel(this,n,r)}createCustomBinaryRequestDataChannel(n,r=3e3){return new BinaryRequestDataChannel(this,n,r)}async startListeningToRealtimeVideo(n){const r=defined$1(this.rtcClient,"Realtime connection has not been started"),o=await this.getRemotePeer();r.controlRemoteStream(defined$1(o).id,{streamName:n.name,enable:!0,pipeline:"rtc"})}async stopListeningToRealtimeVideo(n){const r=defined$1(this.rtcClient,"Realtime connection has not been started"),o=await this.getRemotePeer();r.controlRemoteStream(defined$1(o).id,{streamName:n.name,enable:!1,pipeline:"rtc"})}async startListeningToRealtimeDataStream(n){const r=defined$1(this.rtcClient,"Realtime connection has not been started"),o=await this.getRemotePeer();r.controlRemoteStream(defined$1(o).id,{streamName:n.name,enable:!0,pipeline:"rtc"})}async stopListeningToRealtimeDataStream(n){const r=defined$1(this.rtcClient,"Realtime connection has not been started"),o=await this.getRemotePeer();r.controlRemoteStream(defined$1(o).id,{streamName:n.name,enable:!1,pipeline:"rtc"})}async enableRealtimeTelemetryPriorityIngestion(n){const r=defined$1(this.rtcClient,"Realtime connection has not been started"),o=await this.getRemotePeer();r.controlRemoteStream(defined$1(o).id,{streamName:n,enablePriorityUpload:!0,pipeline:"telemetry"})}async disableRealtimeTelemetryPriorityIngestion(n){const r=defined$1(this.rtcClient,"Realtime connection has not been started"),o=await this.getRemotePeer();r.controlRemoteStream(defined$1(o).id,{streamName:n,enablePriorityUpload:!1,pipeline:"telemetry"})}async changeStreamAudioType(n,r){const o=defined$1(this.rtcClient,"Realtime connection has not been started"),s=await this.getRemotePeer();o.controlRemoteStream(defined$1(s).id,{streamName:n,setAudioFormat:r})}async createCustomDataChannel(n,r){const o=defined$1(this.rtcClient,"Realtime connection has not been started"),s=await this.getRemotePeer(),g=await new Promise(l=>{o.createCustomDataChannel(defined$1(s).id,n,{ordered:!0,...r},!1,(u,c)=>{const d=new DataChannel(c);l(d)})});return await g.waitTilReady(),g}async sendRealtimeMessage(n,r={channelLabel:"stream.reliable"}){const o=defined$1(this.rtcClient,"Realtime connection has not been started"),s=await this.getRemotePeer();o.send(defined$1(s).id,n,r)}async getRealtimeAudioStreams(){var o,s,g,l,u,c;const n=await this.getConfiguration(),r=[];for(const d of(s=(o=n.teleop)==null?void 0:o.hardwareStreams)!=null?s:[])d.rtcStreamType==="audio-chunk"&&r.push({name:d.name});for(const d of(l=(g=n.teleop)==null?void 0:g.rosStreams)!=null?l:[])d.topicType=="audio_common_msgs/AudioData"&&r.push({name:d.topicName});for(const d of(c=(u=n.teleop)==null?void 0:u.customStreams)!=null?c:[])d.rtcStreamType==="audio-chunk"&&r.push({name:d.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,s=t.stat_desc.has_stree,g=t.stat_desc.extra_bits,l=t.stat_desc.extra_base,u=t.stat_desc.max_length;let c,d,B,Q,f,p,U=0;for(Q=0;Q<=MAX_BITS$1;Q++)e.bl_count[Q]=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],Q=n[n[d*2+1]*2+1]+1,Q>u&&(Q=u,U++),n[d*2+1]=Q,!(d>r)&&(e.bl_count[Q]++,f=0,d>=l&&(f=g[d-l]),p=n[d*2],e.opt_len+=p*(Q+f),s&&(e.static_len+=p*(o[d*2+1]+f)));if(U!==0){do{for(Q=u-1;e.bl_count[Q]===0;)Q--;e.bl_count[Q]--,e.bl_count[Q+1]+=2,e.bl_count[u]--,U-=2}while(U>0);for(Q=u;Q!==0;Q--)for(d=e.bl_count[Q];d!==0;)B=e.heap[--c],!(B>r)&&(n[B*2+1]!==Q&&(e.opt_len+=(Q-n[B*2+1])*n[B*2],n[B*2+1]=Q),d--)}},gen_codes=(e,t,n)=>{const r=new Array(MAX_BITS$1+1);let o=0,s,g;for(s=1;s<=MAX_BITS$1;s++)o=o+n[s-1]<<1,r[s]=o;for(g=0;g<=t;g++){let l=e[g*2+1];l!==0&&(e[g*2]=bi_reverse(r[l]++,l))}},tr_static_init=()=>{let e,t,n,r,o;const s=new Array(MAX_BITS$1+1);for(n=0,r=0;r<LENGTH_CODES$1-1;r++)for(base_length[r]=n,e=0;e<1<<extra_lbits[r];e++)_length_code[n++]=r;for(_length_code[n-1]=r,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++)s[t]=0;for(e=0;e<=143;)static_ltree[e*2+1]=8,e++,s[8]++;for(;e<=255;)static_ltree[e*2+1]=9,e++,s[9]++;for(;e<=279;)static_ltree[e*2+1]=7,e++,s[7]++;for(;e<=287;)static_ltree[e*2+1]=8,e++,s[8]++;for(gen_codes(static_ltree,L_CODES$1+1,s),e=0;e<D_CODES$1;e++)static_dtree[e*2+1]=5,static_dtree[e*2]=bi_reverse(e,5);static_l_desc=new StaticTreeDesc(static_ltree,extra_lbits,LITERALS$1+1,L_CODES$1,MAX_BITS$1),static_d_desc=new StaticTreeDesc(static_dtree,extra_dbits,0,D_CODES$1,MAX_BITS$1),static_bl_desc=new StaticTreeDesc(new Array(0),extra_blbits,0,BL_CODES$1,MAX_BL_BITS)},init_block=e=>{let t;for(t=0;t<L_CODES$1;t++)e.dyn_ltree[t*2]=0;for(t=0;t<D_CODES$1;t++)e.dyn_dtree[t*2]=0;for(t=0;t<BL_CODES$1;t++)e.bl_tree[t*2]=0;e.dyn_ltree[END_BLOCK*2]=1,e.opt_len=e.static_len=0,e.sym_next=e.matches=0},bi_windup=e=>{e.bi_valid>8?put_short(e,e.bi_buf):e.bi_valid>0&&(e.pending_buf[e.pending++]=e.bi_buf),e.bi_buf=0,e.bi_valid=0},smaller=(e,t,n,r)=>{const o=t*2,s=n*2;return e[o]<e[s]||e[o]===e[s]&&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,s=0,g,l;if(e.sym_next!==0)do r=e.pending_buf[e.sym_buf+s++]&255,r+=(e.pending_buf[e.sym_buf+s++]&255)<<8,o=e.pending_buf[e.sym_buf+s++],r===0?send_code(e,o,t):(g=_length_code[o],send_code(e,g+LITERALS$1+1,t),l=extra_lbits[g],l!==0&&(o-=base_length[g],send_bits(e,o,l)),r--,g=d_code(r),send_code(e,g,n),l=extra_dbits[g],l!==0&&(r-=base_dist[g],send_bits(e,r,l)));while(s<e.sym_next);send_code(e,END_BLOCK,t)},build_tree=(e,t)=>{const n=t.dyn_tree,r=t.stat_desc.static_tree,o=t.stat_desc.has_stree,s=t.stat_desc.elems;let g,l,u=-1,c;for(e.heap_len=0,e.heap_max=HEAP_SIZE$1,g=0;g<s;g++)n[g*2]!==0?(e.heap[++e.heap_len]=u=g,e.depth[g]=0):n[g*2+1]=0;for(;e.heap_len<2;)c=e.heap[++e.heap_len]=u<2?++u:0,n[c*2]=1,e.depth[c]=0,e.opt_len--,o&&(e.static_len-=r[c*2+1]);for(t.max_code=u,g=e.heap_len>>1;g>=1;g--)pqdownheap(e,n,g);c=s;do g=e.heap[1],e.heap[1]=e.heap[e.heap_len--],pqdownheap(e,n,1),l=e.heap[1],e.heap[--e.heap_max]=g,e.heap[--e.heap_max]=l,n[c*2]=n[g*2]+n[l*2],e.depth[c]=(e.depth[g]>=e.depth[l]?e.depth[g]:e.depth[l])+1,n[g*2+1]=n[l*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,u,e.bl_count)},scan_tree=(e,t,n)=>{let r,o=-1,s,g=t[0*2+1],l=0,u=7,c=4;for(g===0&&(u=138,c=3),t[(n+1)*2+1]=65535,r=0;r<=n;r++)s=g,g=t[(r+1)*2+1],!(++l<u&&s===g)&&(l<c?e.bl_tree[s*2]+=l:s!==0?(s!==o&&e.bl_tree[s*2]++,e.bl_tree[REP_3_6*2]++):l<=10?e.bl_tree[REPZ_3_10*2]++:e.bl_tree[REPZ_11_138*2]++,l=0,o=s,g===0?(u=138,c=3):s===g?(u=6,c=3):(u=7,c=4))},send_tree=(e,t,n)=>{let r,o=-1,s,g=t[0*2+1],l=0,u=7,c=4;for(g===0&&(u=138,c=3),r=0;r<=n;r++)if(s=g,g=t[(r+1)*2+1],!(++l<u&&s===g)){if(l<c)do send_code(e,s,e.bl_tree);while(--l!==0);else s!==0?(s!==o&&(send_code(e,s,e.bl_tree),l--),send_code(e,REP_3_6,e.bl_tree),send_bits(e,l-3,2)):l<=10?(send_code(e,REPZ_3_10,e.bl_tree),send_bits(e,l-3,3)):(send_code(e,REPZ_11_138,e.bl_tree),send_bits(e,l-11,7));l=0,o=s,g===0?(u=138,c=3):s===g?(u=6,c=3):(u=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,s,g=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),g=build_bl_tree(e),o=e.opt_len+3+7>>>3,s=e.static_len+3+7>>>3,s<=o&&(o=s)):o=s=n+5,n+4<=o&&t!==-1?_tr_stored_block$1(e,t,n,r):e.strategy===Z_FIXED$1||s===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,g+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,s=e>>>16&65535|0,g=0;for(;n!==0;){g=n>2e3?2e3:n,n-=g;do o=o+t[r++]|0,s=s+o|0;while(--g);o%=65521,s%=65521}return o|s<<16|0};var adler32_1=adler32;const makeTable=()=>{let e,t=[];for(var n=0;n<256;n++){e=n;for(var r=0;r<8;r++)e=e&1?3988292384^e>>>1:e>>>1;t[n]=e}return t},crcTable=new Uint32Array(makeTable()),crc32=(e,t,n,r)=>{const o=crcTable,s=r+n;e^=-1;for(let g=r;g<s;g++)e=e>>>8^o[(e^t[g])&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,s,g=e.prev_length,l=e.nice_match;const u=e.strstart>e.w_size-MIN_LOOKAHEAD?e.strstart-(e.w_size-MIN_LOOKAHEAD):0,c=e.window,d=e.w_mask,B=e.prev,Q=e.strstart+MAX_MATCH;let f=c[r+g-1],p=c[r+g];e.prev_length>=e.good_match&&(n>>=2),l>e.lookahead&&(l=e.lookahead);do if(o=t,!(c[o+g]!==p||c[o+g-1]!==f||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<Q);if(s=MAX_MATCH-(Q-r),r=Q-MAX_MATCH,s>g){if(e.match_start=t,g=s,s>=l)break;f=c[r+g-1],p=c[r+g]}}while((t=B[t&d])>u&&--n!==0);return g<=e.lookahead?g: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,s,g=0,l=e.strm.avail_in;do{if(r=65535,s=e.bi_valid+42>>3,e.strm.avail_out<s||(s=e.strm.avail_out-s,o=e.strstart-e.block_start,r>o+e.strm.avail_in&&(r=o+e.strm.avail_in),r>s&&(r=s),r<n&&(r===0&&t!==Z_FINISH$3||t===Z_NO_FLUSH$2||r!==o+e.strm.avail_in)))break;g=t===Z_FINISH$3&&r===o+e.strm.avail_in?1:0,_tr_stored_block(e,0,0,g),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(g===0);return l-=e.strm.avail_in,l&&(l>=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<=l&&(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-l,e.strm.next_in),e.strstart),e.strstart+=l,e.insert+=l>e.w_size-e.insert?e.w_size-e.insert:l),e.block_start=e.strstart),e.high_water<e.strstart&&(e.high_water=e.strstart),g?BS_FINISH_DONE:t!==Z_NO_FLUSH$2&&t!==Z_FINISH$3&&e.strm.avail_in===0&&e.strstart===e.block_start?BS_BLOCK_DONE:(s=e.window_size-e.strstart,e.strm.avail_in>s&&e.block_start>=e.w_size&&(e.block_start-=e.w_size,e.strstart-=e.w_size,e.window.set(e.window.subarray(e.w_size,e.w_size+e.strstart),0),e.matches<2&&e.matches++,s+=e.w_size,e.insert>e.strstart&&(e.insert=e.strstart)),s>e.strm.avail_in&&(s=e.strm.avail_in),s&&(read_buf(e.strm,e.window,e.strstart,s),e.strstart+=s,e.insert+=s>e.w_size-e.insert?e.w_size-e.insert:s),e.high_water<e.strstart&&(e.high_water=e.strstart),s=e.bi_valid+42>>3,s=e.pending_buf_size-s>65535?65535:e.pending_buf_size-s,n=s>e.w_size?e.w_size:s,o=e.strstart-e.block_start,(o>=n||(o||t===Z_FINISH$3)&&t!==Z_NO_FLUSH$2&&e.strm.avail_in===0&&o<=s)&&(r=o>s?s:o,g=t===Z_FINISH$3&&e.strm.avail_in===0&&r===o?1:0,_tr_stored_block(e,e.block_start,r,g),e.block_start+=r,flush_pending(e.strm)),g?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,s;const g=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=g[o],r===g[++o]&&r===g[++o]&&r===g[++o])){s=e.strstart+MAX_MATCH;do;while(r===g[++o]&&r===g[++o]&&r===g[++o]&&r===g[++o]&&r===g[++o]&&r===g[++o]&&r===g[++o]&&r===g[++o]&&o<s);e.match_length=MAX_MATCH-(s-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,s)=>{if(!e)return Z_STREAM_ERROR$2;let g=1;if(t===Z_DEFAULT_COMPRESSION$1&&(t=6),r<0?(g=0,r=-r):r>15&&(g=2,r-=16),o<1||o>MAX_MEM_LEVEL||n!==Z_DEFLATED$2||r<8||r>15||t<0||t>9||s<0||s>Z_FIXED||r===8&&g!==1)return err(e,Z_STREAM_ERROR$2);r===8&&(r=9);const l=new DeflateState;return e.state=l,l.strm=e,l.status=INIT_STATE,l.wrap=g,l.gzhead=null,l.w_bits=r,l.w_size=1<<l.w_bits,l.w_mask=l.w_size-1,l.hash_bits=o+7,l.hash_size=1<<l.hash_bits,l.hash_mask=l.hash_size-1,l.hash_shift=~~((l.hash_bits+MIN_MATCH-1)/MIN_MATCH),l.window=new Uint8Array(l.w_size*2),l.head=new Uint16Array(l.hash_size),l.prev=new Uint16Array(l.w_size),l.lit_bufsize=1<<o+6,l.pending_buf_size=l.lit_bufsize*4,l.pending_buf=new Uint8Array(l.pending_buf_size),l.sym_buf=l.lit_bufsize,l.sym_end=(l.lit_bufsize-1)*3,l.level=t,l.strategy=s,l.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,s=-1;if(n.strategy>=Z_HUFFMAN_ONLY||n.level<2?s=0:n.level<6?s=1:n.level===6?s=2:s=3,o|=s<<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,s=(n.gzhead.extra.length&65535)-n.gzindex;for(;n.pending+s>n.pending_buf_size;){let l=n.pending_buf_size-n.pending;if(n.pending_buf.set(n.gzhead.extra.subarray(n.gzindex,n.gzindex+l),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+=l,flush_pending(e),n.pending!==0)return n.last_flush=-1,Z_OK$3;o=0,s-=l}let g=new Uint8Array(n.gzhead.extra);n.pending_buf.set(g.subarray(n.gzindex,n.gzindex+s),n.pending),n.pending+=s,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,s;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?s=n.gzhead.name.charCodeAt(n.gzindex++)&255:s=0,put_byte(n,s)}while(s!==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,s;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?s=n.gzhead.comment.charCodeAt(n.gzindex++)&255:s=0,put_byte(n,s)}while(s!==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 u=new Uint8Array(r.w_size);u.set(t.subarray(n-r.w_size,n),0),t=u,n=r.w_size}const s=e.avail_in,g=e.next_in,l=e.input;for(e.avail_in=n,e.next_in=0,e.input=t,fill_window(r);r.lookahead>=MIN_MATCH;){let u=r.strstart,c=r.lookahead-(MIN_MATCH-1);do r.ins_h=HASH(r,r.ins_h,r.window[u+MIN_MATCH-1]),r.prev[u&r.w_mask]=r.head[r.ins_h],r.head[r.ins_h]=u,u++;while(--c);r.strstart=u,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=g,e.input=l,e.avail_in=s,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,s=e.length;r<s;r++){let g=e[r];n.set(g,o),o+=g.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,s,g=e.length,l=0;for(o=0;o<g;o++)n=e.charCodeAt(o),(n&64512)===55296&&o+1<g&&(r=e.charCodeAt(o+1),(r&64512)===56320&&(n=65536+(n-55296<<10)+(r-56320),o++)),l+=n<128?1:n<2048?2:n<65536?3:4;for(t=new Uint8Array(l),s=0,o=0;s<l;o++)n=e.charCodeAt(o),(n&64512)===55296&&o+1<g&&(r=e.charCodeAt(o+1),(r&64512)===56320&&(n=65536+(n-55296<<10)+(r-56320),o++)),n<128?t[s++]=n:n<2048?(t[s++]=192|n>>>6,t[s++]=128|n&63):n<65536?(t[s++]=224|n>>>12,t[s++]=128|n>>>6&63,t[s++]=128|n&63):(t[s++]=240|n>>>18,t[s++]=128|n>>>12&63,t[s++]=128|n>>>6&63,t[s++]=128|n&63);return t};const buf2binstring=(e,t)=>{if(t<65534&&e.subarray&&STR_APPLY_UIA_OK)return String.fromCharCode.apply(null,e.length===t?e:e.subarray(0,t));let n="";for(let r=0;r<t;r++)n+=String.fromCharCode(e[r]);return n};var buf2string=(e,t)=>{const n=t||e.length;if(typeof TextDecoder=="function"&&TextDecoder.prototype.decode)return new TextDecoder().decode(e.subarray(0,t));let r,o;const s=new Array(n*2);for(o=0,r=0;r<n;){let g=e[r++];if(g<128){s[o++]=g;continue}let l=_utf8len[g];if(l>4){s[o++]=65533,r+=l-1;continue}for(g&=l===2?31:l===3?15:7;l>1&&r<n;)g=g<<6|e[r++]&63,l--;if(l>1){s[o++]=65533;continue}g<65536?s[o++]=g:(g-=65536,s[o++]=55296|g>>10&1023,s[o++]=56320|g&1023)}return buf2binstring(s,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,s;if(this.ended)return!1;for(t===~~t?s=t:s=t===!0?Z_FINISH$2:Z_NO_FLUSH$1,typeof e=="string"?n.input=strings.string2buf(e):toString$1.call(e)==="[object ArrayBuffer]"?n.input=new Uint8Array(e):n.input=e,n.next_in=0,n.avail_in=n.input.length;;){if(n.avail_out===0&&(n.output=new Uint8Array(r),n.next_out=0,n.avail_out=r),(s===Z_SYNC_FLUSH||s===Z_FULL_FLUSH)&&n.avail_out<=6){this.onData(n.output.subarray(0,n.next_out)),n.avail_out=0;continue}if(o=deflate_1$2.deflate(n,s),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(s>0&&n.next_out>0){this.onData(n.output.subarray(0,n.next_out)),n.avail_out=0;continue}if(n.avail_in===0)break}return!0};Deflate$1.prototype.onData=function(e){this.chunks.push(e)};Deflate$1.prototype.onEnd=function(e){e===Z_OK$2&&(this.result=common.flattenChunks(this.chunks)),this.chunks=[],this.err=e,this.msg=this.strm.msg};function deflate$1(e,t){const n=new Deflate$1(t);if(n.push(e,!0),n.err)throw n.msg||messages[n.err];return n.result}function deflateRaw$1(e,t){return t=t||{},t.raw=!0,deflate$1(e,t)}function gzip$1(e,t){return t=t||{},t.gzip=!0,deflate$1(e,t)}var Deflate_1$1=Deflate$1,deflate_2=deflate$1,deflateRaw_1$1=deflateRaw$1,gzip_1$1=gzip$1,constants$1=constants$2,deflate_1$1={Deflate:Deflate_1$1,deflate:deflate_2,deflateRaw:deflateRaw_1$1,gzip:gzip_1$1,constants:constants$1};const BAD$1=16209,TYPE$1=16191;var inffast=function e(t,n){let r,o,s,g,l,u,c,d,B,Q,f,p,U,E,M,W,y,m,h,T,I,X,F,R;const x=t.state;r=t.next_in,F=t.input,o=r+(t.avail_in-5),s=t.next_out,R=t.output,g=s-(n-t.avail_out),l=s+(t.avail_out-257),u=x.dmax,c=x.wsize,d=x.whave,B=x.wnext,Q=x.window,f=x.hold,p=x.bits,U=x.lencode,E=x.distcode,M=(1<<x.lenbits)-1,W=(1<<x.distbits)-1;e:do{p<15&&(f+=F[r++]<<p,p+=8,f+=F[r++]<<p,p+=8),y=U[f&M];t:for(;;){if(m=y>>>24,f>>>=m,p-=m,m=y>>>16&255,m===0)R[s++]=y&65535;else if(m&16){h=y&65535,m&=15,m&&(p<m&&(f+=F[r++]<<p,p+=8),h+=f&(1<<m)-1,f>>>=m,p-=m),p<15&&(f+=F[r++]<<p,p+=8,f+=F[r++]<<p,p+=8),y=E[f&W];n:for(;;){if(m=y>>>24,f>>>=m,p-=m,m=y>>>16&255,m&16){if(T=y&65535,m&=15,p<m&&(f+=F[r++]<<p,p+=8,p<m&&(f+=F[r++]<<p,p+=8)),T+=f&(1<<m)-1,T>u){t.msg="invalid distance too far back",x.mode=BAD$1;break e}if(f>>>=m,p-=m,m=s-g,T>m){if(m=T-m,m>d&&x.sane){t.msg="invalid distance too far back",x.mode=BAD$1;break e}if(I=0,X=Q,B===0){if(I+=c-m,m<h){h-=m;do R[s++]=Q[I++];while(--m);I=s-T,X=R}}else if(B<m){if(I+=c+B-m,m-=B,m<h){h-=m;do R[s++]=Q[I++];while(--m);if(I=0,B<h){m=B,h-=m;do R[s++]=Q[I++];while(--m);I=s-T,X=R}}}else if(I+=B-m,m<h){h-=m;do R[s++]=Q[I++];while(--m);I=s-T,X=R}for(;h>2;)R[s++]=X[I++],R[s++]=X[I++],R[s++]=X[I++],h-=3;h&&(R[s++]=X[I++],h>1&&(R[s++]=X[I++]))}else{I=s-T;do R[s++]=R[I++],R[s++]=R[I++],R[s++]=R[I++],h-=3;while(h>2);h&&(R[s++]=R[I++],h>1&&(R[s++]=R[I++]))}}else if(m&64){t.msg="invalid distance code",x.mode=BAD$1;break e}else{y=E[(y&65535)+(f&(1<<m)-1)];continue n}break}}else if(m&64)if(m&32){x.mode=TYPE$1;break e}else{t.msg="invalid literal/length code",x.mode=BAD$1;break e}else{y=U[(y&65535)+(f&(1<<m)-1)];continue t}break}}while(r<o&&s<l);h=p>>3,r-=h,p-=h<<3,f&=(1<<p)-1,t.next_in=r,t.next_out=s,t.avail_in=r<o?5+(o-r):5-(r-o),t.avail_out=s<l?257+(l-s):257-(s-l),x.hold=f,x.bits=p};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,s,g,l)=>{const u=l.bits;let c=0,d=0,B=0,Q=0,f=0,p=0,U=0,E=0,M=0,W=0,y,m,h,T,I,X=null,F;const R=new Uint16Array(MAXBITS+1),x=new Uint16Array(MAXBITS+1);let w=null,_,j,C;for(c=0;c<=MAXBITS;c++)R[c]=0;for(d=0;d<r;d++)R[t[n+d]]++;for(f=u,Q=MAXBITS;Q>=1&&R[Q]===0;Q--);if(f>Q&&(f=Q),Q===0)return o[s++]=1<<24|64<<16|0,o[s++]=1<<24|64<<16|0,l.bits=1,0;for(B=1;B<Q&&R[B]===0;B++);for(f<B&&(f=B),E=1,c=1;c<=MAXBITS;c++)if(E<<=1,E-=R[c],E<0)return-1;if(E>0&&(e===CODES$1||Q!==1))return-1;for(x[1]=0,c=1;c<MAXBITS;c++)x[c+1]=x[c]+R[c];for(d=0;d<r;d++)t[n+d]!==0&&(g[x[t[n+d]]++]=d);if(e===CODES$1?(X=w=g,F=20):e===LENS$1?(X=lbase,w=lext,F=257):(X=dbase,w=dext,F=0),W=0,d=0,c=B,I=s,p=f,U=0,h=-1,M=1<<f,T=M-1,e===LENS$1&&M>ENOUGH_LENS$1||e===DISTS$1&&M>ENOUGH_DISTS$1)return 1;for(;;){_=c-U,g[d]+1<F?(j=0,C=g[d]):g[d]>=F?(j=w[g[d]-F],C=X[g[d]-F]):(j=32+64,C=0),y=1<<c-U,m=1<<p,B=m;do m-=y,o[I+(W>>U)+m]=_<<24|j<<16|C|0;while(m!==0);for(y=1<<c-1;W&y;)y>>=1;if(y!==0?(W&=y-1,W+=y):W=0,d++,--R[c]===0){if(c===Q)break;c=t[n+g[d]]}if(c>f&&(W&T)!==h){for(U===0&&(U=f),I+=B,p=c-U,E=1<<p;p+U<Q&&(E-=R[p+U],!(E<=0));)p++,E<<=1;if(M+=1<<p,e===LENS$1&&M>ENOUGH_LENS$1||e===DISTS$1&&M>ENOUGH_DISTS$1)return 1;h=W&T,o[h]=f<<24|p<<16|I-s|0}}return W!==0&&(o[I+W]=c-U<<24|64<<16|0),l.bits=f,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 s=e.state;return s.window===null&&(s.wsize=1<<s.wbits,s.wnext=0,s.whave=0,s.window=new Uint8Array(s.wsize)),r>=s.wsize?(s.window.set(t.subarray(n-s.wsize,n),0),s.wnext=0,s.whave=s.wsize):(o=s.wsize-s.wnext,o>r&&(o=r),s.window.set(t.subarray(n-r,n-r+o),s.wnext),r-=o,r?(s.window.set(t.subarray(n-r,n),0),s.wnext=r,s.whave=s.wsize):(s.wnext+=o,s.wnext===s.wsize&&(s.wnext=0),s.whave<s.wsize&&(s.whave+=o))),0},inflate$2=(e,t)=>{let n,r,o,s,g,l,u,c,d,B,Q,f,p,U,E=0,M,W,y,m,h,T,I,X;const F=new Uint8Array(4);let R,x;const w=new Uint8Array([16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15]);if(inflateStateCheck(e)||!e.output||!e.input&&e.avail_in!==0)return Z_STREAM_ERROR$1;n=e.state,n.mode===TYPE&&(n.mode=TYPEDO),g=e.next_out,o=e.output,u=e.avail_out,s=e.next_in,r=e.input,l=e.avail_in,c=n.hold,d=n.bits,B=l,Q=u,X=Z_OK$1;e:for(;;)switch(n.mode){case HEAD:if(n.wrap===0){n.mode=TYPEDO;break}for(;d<16;){if(l===0)break e;l--,c+=r[s++]<<d,d+=8}if(n.wrap&2&&c===35615){n.wbits===0&&(n.wbits=15),n.check=0,F[0]=c&255,F[1]=c>>>8&255,n.check=crc32_1(n.check,F,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,I=(c&15)+8,n.wbits===0&&(n.wbits=I),I>15||I>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(l===0)break e;l--,c+=r[s++]<<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&&(F[0]=c&255,F[1]=c>>>8&255,n.check=crc32_1(n.check,F,2,0)),c=0,d=0,n.mode=TIME;case TIME:for(;d<32;){if(l===0)break e;l--,c+=r[s++]<<d,d+=8}n.head&&(n.head.time=c),n.flags&512&&n.wrap&4&&(F[0]=c&255,F[1]=c>>>8&255,F[2]=c>>>16&255,F[3]=c>>>24&255,n.check=crc32_1(n.check,F,4,0)),c=0,d=0,n.mode=OS;case OS:for(;d<16;){if(l===0)break e;l--,c+=r[s++]<<d,d+=8}n.head&&(n.head.xflags=c&255,n.head.os=c>>8),n.flags&512&&n.wrap&4&&(F[0]=c&255,F[1]=c>>>8&255,n.check=crc32_1(n.check,F,2,0)),c=0,d=0,n.mode=EXLEN;case EXLEN:if(n.flags&1024){for(;d<16;){if(l===0)break e;l--,c+=r[s++]<<d,d+=8}n.length=c,n.head&&(n.head.extra_len=c),n.flags&512&&n.wrap&4&&(F[0]=c&255,F[1]=c>>>8&255,n.check=crc32_1(n.check,F,2,0)),c=0,d=0}else n.head&&(n.head.extra=null);n.mode=EXTRA;case EXTRA:if(n.flags&1024&&(f=n.length,f>l&&(f=l),f&&(n.head&&(I=n.head.extra_len-n.length,n.head.extra||(n.head.extra=new Uint8Array(n.head.extra_len)),n.head.extra.set(r.subarray(s,s+f),I)),n.flags&512&&n.wrap&4&&(n.check=crc32_1(n.check,r,f,s)),l-=f,s+=f,n.length-=f),n.length))break e;n.length=0,n.mode=NAME;case NAME:if(n.flags&2048){if(l===0)break e;f=0;do I=r[s+f++],n.head&&I&&n.length<65536&&(n.head.name+=String.fromCharCode(I));while(I&&f<l);if(n.flags&512&&n.wrap&4&&(n.check=crc32_1(n.check,r,f,s)),l-=f,s+=f,I)break e}else n.head&&(n.head.name=null);n.length=0,n.mode=COMMENT;case COMMENT:if(n.flags&4096){if(l===0)break e;f=0;do I=r[s+f++],n.head&&I&&n.length<65536&&(n.head.comment+=String.fromCharCode(I));while(I&&f<l);if(n.flags&512&&n.wrap&4&&(n.check=crc32_1(n.check,r,f,s)),l-=f,s+=f,I)break e}else n.head&&(n.head.comment=null);n.mode=HCRC;case HCRC:if(n.flags&512){for(;d<16;){if(l===0)break e;l--,c+=r[s++]<<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(l===0)break e;l--,c+=r[s++]<<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=g,e.avail_out=u,e.next_in=s,e.avail_in=l,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(l===0)break e;l--,c+=r[s++]<<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(l===0)break e;l--,c+=r[s++]<<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(f=n.length,f){if(f>l&&(f=l),f>u&&(f=u),f===0)break e;o.set(r.subarray(s,s+f),g),l-=f,s+=f,u-=f,g+=f,n.length-=f;break}n.mode=TYPE;break;case TABLE:for(;d<14;){if(l===0)break e;l--,c+=r[s++]<<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(l===0)break e;l--,c+=r[s++]<<d,d+=8}n.lens[w[n.have++]]=c&7,c>>>=3,d-=3}for(;n.have<19;)n.lens[w[n.have++]]=0;if(n.lencode=n.lendyn,n.lenbits=7,R={bits:n.lenbits},X=inftrees(CODES,n.lens,0,19,n.lencode,0,n.work,R),n.lenbits=R.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(;E=n.lencode[c&(1<<n.lenbits)-1],M=E>>>24,W=E>>>16&255,y=E&65535,!(M<=d);){if(l===0)break e;l--,c+=r[s++]<<d,d+=8}if(y<16)c>>>=M,d-=M,n.lens[n.have++]=y;else{if(y===16){for(x=M+2;d<x;){if(l===0)break e;l--,c+=r[s++]<<d,d+=8}if(c>>>=M,d-=M,n.have===0){e.msg="invalid bit length repeat",n.mode=BAD;break}I=n.lens[n.have-1],f=3+(c&3),c>>>=2,d-=2}else if(y===17){for(x=M+3;d<x;){if(l===0)break e;l--,c+=r[s++]<<d,d+=8}c>>>=M,d-=M,I=0,f=3+(c&7),c>>>=3,d-=3}else{for(x=M+7;d<x;){if(l===0)break e;l--,c+=r[s++]<<d,d+=8}c>>>=M,d-=M,I=0,f=11+(c&127),c>>>=7,d-=7}if(n.have+f>n.nlen+n.ndist){e.msg="invalid bit length repeat",n.mode=BAD;break}for(;f--;)n.lens[n.have++]=I}}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,R={bits:n.lenbits},X=inftrees(LENS,n.lens,0,n.nlen,n.lencode,0,n.work,R),n.lenbits=R.bits,X){e.msg="invalid literal/lengths set",n.mode=BAD;break}if(n.distbits=6,n.distcode=n.distdyn,R={bits:n.distbits},X=inftrees(DISTS,n.lens,n.nlen,n.ndist,n.distcode,0,n.work,R),n.distbits=R.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(l>=6&&u>=258){e.next_out=g,e.avail_out=u,e.next_in=s,e.avail_in=l,n.hold=c,n.bits=d,inffast(e,Q),g=e.next_out,o=e.output,u=e.avail_out,s=e.next_in,r=e.input,l=e.avail_in,c=n.hold,d=n.bits,n.mode===TYPE&&(n.back=-1);break}for(n.back=0;E=n.lencode[c&(1<<n.lenbits)-1],M=E>>>24,W=E>>>16&255,y=E&65535,!(M<=d);){if(l===0)break e;l--,c+=r[s++]<<d,d+=8}if(W&&!(W&240)){for(m=M,h=W,T=y;E=n.lencode[T+((c&(1<<m+h)-1)>>m)],M=E>>>24,W=E>>>16&255,y=E&65535,!(m+M<=d);){if(l===0)break e;l--,c+=r[s++]<<d,d+=8}c>>>=m,d-=m,n.back+=m}if(c>>>=M,d-=M,n.back+=M,n.length=y,W===0){n.mode=LIT;break}if(W&32){n.back=-1,n.mode=TYPE;break}if(W&64){e.msg="invalid literal/length code",n.mode=BAD;break}n.extra=W&15,n.mode=LENEXT;case LENEXT:if(n.extra){for(x=n.extra;d<x;){if(l===0)break e;l--,c+=r[s++]<<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(;E=n.distcode[c&(1<<n.distbits)-1],M=E>>>24,W=E>>>16&255,y=E&65535,!(M<=d);){if(l===0)break e;l--,c+=r[s++]<<d,d+=8}if(!(W&240)){for(m=M,h=W,T=y;E=n.distcode[T+((c&(1<<m+h)-1)>>m)],M=E>>>24,W=E>>>16&255,y=E&65535,!(m+M<=d);){if(l===0)break e;l--,c+=r[s++]<<d,d+=8}c>>>=m,d-=m,n.back+=m}if(c>>>=M,d-=M,n.back+=M,W&64){e.msg="invalid distance code",n.mode=BAD;break}n.offset=y,n.extra=W&15,n.mode=DISTEXT;case DISTEXT:if(n.extra){for(x=n.extra;d<x;){if(l===0)break e;l--,c+=r[s++]<<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(u===0)break e;if(f=Q-u,n.offset>f){if(f=n.offset-f,f>n.whave&&n.sane){e.msg="invalid distance too far back",n.mode=BAD;break}f>n.wnext?(f-=n.wnext,p=n.wsize-f):p=n.wnext-f,f>n.length&&(f=n.length),U=n.window}else U=o,p=g-n.offset,f=n.length;f>u&&(f=u),u-=f,n.length-=f;do o[g++]=U[p++];while(--f);n.length===0&&(n.mode=LEN);break;case LIT:if(u===0)break e;o[g++]=n.length,u--,n.mode=LEN;break;case CHECK:if(n.wrap){for(;d<32;){if(l===0)break e;l--,c|=r[s++]<<d,d+=8}if(Q-=u,e.total_out+=Q,n.total+=Q,n.wrap&4&&Q&&(e.adler=n.check=n.flags?crc32_1(n.check,o,Q,g-Q):adler32_1(n.check,o,Q,g-Q)),Q=u,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(l===0)break e;l--,c+=r[s++]<<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=g,e.avail_out=u,e.next_in=s,e.avail_in=l,n.hold=c,n.bits=d,(n.wsize||Q!==e.avail_out&&n.mode<BAD&&(n.mode<CHECK||t!==Z_FINISH$1))&&updatewindow(e,e.output,e.next_out,Q-e.avail_out),B-=e.avail_in,Q-=e.avail_out,e.total_in+=B,e.total_out+=Q,n.total+=Q,n.wrap&4&&Q&&(e.adler=n.check=n.flags?crc32_1(n.check,o,Q,e.next_out-Q):adler32_1(n.check,o,Q,e.next_out-Q)),e.data_type=n.bits+(n.last?64:0)+(n.mode===TYPE?128:0)+(n.mode===LEN_||n.mode===COPY_?256:0),(B===0&&Q===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,s;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:(s=updatewindow(e,t,n,n),s?(r.mode=MEM,Z_MEM_ERROR$1):(r.havedict=1,Z_OK$1))};var inflateReset_1=inflateReset,inflateReset2_1=inflateReset2,inflateResetKeep_1=inflateResetKeep,inflateInit_1=inflateInit,inflateInit2_1=inflateInit2,inflate_2$1=inflate$2,inflateEnd_1=inflateEnd,inflateGetHeader_1=inflateGetHeader,inflateSetDictionary_1=inflateSetDictionary,inflateInfo="pako inflate (from Nodeca project)",inflate_1$2={inflateReset:inflateReset_1,inflateReset2:inflateReset2_1,inflateResetKeep:inflateResetKeep_1,inflateInit:inflateInit_1,inflateInit2:inflateInit2_1,inflate:inflate_2$1,inflateEnd:inflateEnd_1,inflateGetHeader:inflateGetHeader_1,inflateSetDictionary:inflateSetDictionary_1,inflateInfo};function GZheader(){this.text=0,this.time=0,this.xflags=0,this.os=0,this.extra=null,this.extra_len=0,this.name="",this.comment="",this.hcrc=0,this.done=!1}var gzheader=GZheader;const toString=Object.prototype.toString,{Z_NO_FLUSH,Z_FINISH,Z_OK,Z_STREAM_END,Z_NEED_DICT,Z_STREAM_ERROR,Z_DATA_ERROR,Z_MEM_ERROR}=constants$2;function Inflate$1(e){this.options=common.assign({chunkSize:1024*64,windowBits:15,to:""},e||{});const t=this.options;t.raw&&t.windowBits>=0&&t.windowBits<16&&(t.windowBits=-t.windowBits,t.windowBits===0&&(t.windowBits=-15)),t.windowBits>=0&&t.windowBits<16&&!(e&&e.windowBits)&&(t.windowBits+=32),t.windowBits>15&&t.windowBits<48&&(t.windowBits&15||(t.windowBits|=15)),this.err=0,this.msg="",this.ended=!1,this.chunks=[],this.strm=new zstream,this.strm.avail_out=0;let n=inflate_1$2.inflateInit2(this.strm,t.windowBits);if(n!==Z_OK)throw new Error(messages[n]);if(this.header=new gzheader,inflate_1$2.inflateGetHeader(this.strm,this.header),t.dictionary&&(typeof t.dictionary=="string"?t.dictionary=strings.string2buf(t.dictionary):toString.call(t.dictionary)==="[object ArrayBuffer]"&&(t.dictionary=new Uint8Array(t.dictionary)),t.raw&&(n=inflate_1$2.inflateSetDictionary(this.strm,t.dictionary),n!==Z_OK)))throw new Error(messages[n])}Inflate$1.prototype.push=function(e,t){const n=this.strm,r=this.options.chunkSize,o=this.options.dictionary;let s,g,l;if(this.ended)return!1;for(t===~~t?g=t:g=t===!0?Z_FINISH:Z_NO_FLUSH,toString.call(e)==="[object ArrayBuffer]"?n.input=new Uint8Array(e):n.input=e,n.next_in=0,n.avail_in=n.input.length;;){for(n.avail_out===0&&(n.output=new Uint8Array(r),n.next_out=0,n.avail_out=r),s=inflate_1$2.inflate(n,g),s===Z_NEED_DICT&&o&&(s=inflate_1$2.inflateSetDictionary(n,o),s===Z_OK?s=inflate_1$2.inflate(n,g):s===Z_DATA_ERROR&&(s=Z_NEED_DICT));n.avail_in>0&&s===Z_STREAM_END&&n.state.wrap>0&&e[n.next_in]!==0;)inflate_1$2.inflateReset(n),s=inflate_1$2.inflate(n,g);switch(s){case Z_STREAM_ERROR:case Z_DATA_ERROR:case Z_NEED_DICT:case Z_MEM_ERROR:return this.onEnd(s),this.ended=!0,!1}if(l=n.avail_out,n.next_out&&(n.avail_out===0||s===Z_STREAM_END))if(this.options.to==="string"){let u=strings.utf8border(n.output,n.next_out),c=n.next_out-u,d=strings.buf2string(n.output,u);n.next_out=c,n.avail_out=r-c,c&&n.output.set(n.output.subarray(u,u+c),0),this.onData(d)}else this.onData(n.output.length===n.next_out?n.output:n.output.subarray(0,n.next_out));if(!(s===Z_OK&&l===0)){if(s===Z_STREAM_END)return s=inflate_1$2.inflateEnd(this.strm),this.onEnd(s),this.ended=!0,!0;if(n.avail_in===0)break}}return!0};Inflate$1.prototype.onData=function(e){this.chunks.push(e)};Inflate$1.prototype.onEnd=function(e){e===Z_OK&&(this.options.to==="string"?this.result=this.chunks.join(""):this.result=common.flattenChunks(this.chunks)),this.chunks=[],this.err=e,this.msg=this.strm.msg};const{Deflate,deflate,deflateRaw,gzip}=deflate_1$1;var deflate_1=deflate,fromByteArray_1=fromByteArray,lookup=[],code="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";for(var i=0,len=code.length;i<len;++i)lookup[i]=code[i];function tripletToBase64(e){return lookup[e>>18&63]+lookup[e>>12&63]+lookup[e>>6&63]+lookup[e&63]}function encodeChunk(e,t,n){for(var r,o=[],s=t;s<n;s+=3)r=(e[s]<<16&16711680)+(e[s+1]<<8&65280)+(e[s+2]&255),o.push(tripletToBase64(r));return o.join("")}function fromByteArray(e){for(var t,n=e.length,r=n%3,o=[],s=16383,g=0,l=n-r;g<l;g+=s)o.push(encodeChunk(e,g,g+s>l?l:g+s));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(`${exports.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(l=>l.name===t);if(r.length===0)return console.warn("View does not exist or it is misspell"),null;const o=await fetch(`${exports.FORMANT_API_URL}/v1/admin/shares`,{method:"POST",body:JSON.stringify(e),headers:{"Content-Type":"application/json",Authorization:"Bearer "+Authentication.token}}),s=exports.FORMANT_API_URL.replace("api","app"),{code:g}=await o.json();return`${s}/shares/${g}#${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(`${exports.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 s=aggregateByDateFunctions[t];return await Promise.all(Array(n).fill(0).map(async(g,l)=>{const u=new Date(r),c=s.sub(s.start(u),n-l-1),d=s.sub(s.end(u),n-l-1),B=formatTimeFrameText(c.toLocaleDateString(),d.toLocaleDateString()),Q=await queryEvents({...o,eventTypes:e,start:new Date(c).toISOString(),end:new Date(d).toISOString()});return{date:B,events:Q}}))}async function getAnnotationCount(e,t){return(await queryEvents({...e,eventTypes:["annotation"]})).filter(s=>!!s.tags&&Object.keys(s.tags).includes(t)).reduce((s,g)=>{const l=g.tags[t];return l in s?(s[l]+=1,s):(s[l]=1,s)},{})}async function getAnnotationCountByIntervals(e,t,n){const{end:r,start:o}=e,g=aggregateByDateFunctions[n].interval({start:new Date(o),end:new Date(r)}),l=g.map((c,d)=>{const B=new Date(c).toISOString(),Q=d===g.length-1?new Date(Date.now()).toISOString():new Date(g[d+1]);return getAnnotationCount({...e,start:B,end:Q},t)}),u=await Promise.all(l);return g.map((c,d)=>({date:new Date(c).toISOString(),annotations:u[d]}))}async function getTelemetry(e,t,n,r,o,s){let g=e;Array.isArray(e)||(g=[e]);let l=t;return Array.isArray(t)||(l=[t]),(await(await fetch(`${exports.FORMANT_API_URL}/v1/queries/queries`,{method:"POST",body:JSON.stringify({deviceIds:g,end:r.toISOString(),names:l,start:n.toISOString(),tags:o,latestOnly:s}),headers:{"Content-Type":"application/json",Authorization:"Bearer "+Authentication.token}})).json()).items}async function 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(`${exports.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(`${exports.FORMANT_API_URL}/v1/admin/devices/${e}`,{method:"PATCH",body:JSON.stringify(t),headers:{"Content-Type":"application/json",Authorization:"Bearer "+Authentication.token}})).json()}async function getDevicesData(){if(!Authentication.token)throw new Error("Not authenticated");return(await(await fetch(`${exports.FORMANT_API_URL}/v1/admin/device-details/query`,{method:"POST",body:JSON.stringify({enabled:!0,type:"default"}),headers:{"Content-Type":"application/json",Authorization:"Bearer "+Authentication.token}})).json()).items}async function queryDevicesData(e){if(!Authentication.token)throw new Error("Not authenticated");return(await(await fetch(`${exports.FORMANT_API_URL}/v1/admin/devices/query`,{method:"POST",body:JSON.stringify(e),headers:{"Content-Type":"application/json",Authorization:"Bearer "+Authentication.token}})).json()).items}async function disableDevice(e){if(!Authentication.token)throw new Error("Not authenticated");return await(await fetch(`${exports.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(`${exports.FORMANT_API_URL}/v1/queries/stream-current-value`,{method:"POST",body:JSON.stringify({deviceIds:[this.id]}),headers:{"Content-Type":"application/json",Authorization:"Bearer "+Authentication.token}})).json()).items}async getConfiguration(t=!1){let n=await fetch(`${exports.FORMANT_API_URL}/v1/admin/devices/${this.id}`,{method:"GET",headers:{"Content-Type":"application/json",Authorization:"Bearer "+Authentication.token}});const r=await n.json();if(!r.state.reportedConfiguration)throw new Error("Device has no configuration, has it ever been turned on?");const o=t?r.desiredConfigurationVersion:r.state.reportedConfiguration.version;return n=await fetch(`${exports.FORMANT_API_URL}/v1/admin/devices/${this.id}/configurations/${o}`,{method:"GET",headers:{"Content-Type":"application/json",Authorization:"Bearer "+Authentication.token}}),(await n.json()).document}async getAgentVersion(){var r;const n=await(await fetch(`${exports.FORMANT_API_URL}/v1/admin/devices/${this.id}`,{method:"GET",headers:{"Content-Type":"application/json",Authorization:"Bearer "+Authentication.token}})).json();return(r=n==null?void 0:n.state)==null?void 0:r.agentVersion}async getFileUrl(t){return(await(await fetch(`${exports.FORMANT_API_URL}/v1/admin/files/query`,{method:"POST",body:JSON.stringify({fileIds:[t]}),headers:{"Content-Type":"application/json",Authorization:"Bearer "+Authentication.token}})).json()).fileUrls}async startRealtimeConnection(t={}){if(console.debug(`${new Date().toISOString()} :: Connection start requested`),this.rtcClient&&this.connectionMonitorInterval!==void 0)throw new Error(`Already created realtime connection to device ${this.id}`);this.rtcClient&&console.warn("overwriting existing rtcClient due to missing connectionMonitorInterval");const{sessionType:n,deadlineMs:r=1e4,maxConnectRetries:o=3}=typeof t=="number"?{sessionType:t}:t,g=getRtcClientPool({sessionType:n}).get(this.handleMessage);let l=!1;const u=new Promise((d,B)=>setTimeout(()=>{l=!0,B(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 g)for(;!g.isReady();)this.assertNotCancelled(l),await delay(100);const d=await this.getRemoteDevicePeerId(g);this.assertNotCancelled(l);let B;for(let f=0;f<o&&(B=await g.connect(d),!B);f++)delay(100),this.assertNotCancelled(l);if(!B)throw new Error(`Session could not be created: exhausted ${o} retries`);let Q=0;for(;!l&&g.getConnectionStatus(d)!=="connected";)await delay(100),Q+=1;return this.assertNotCancelled(l),console.debug(`${new Date().toISOString()} :: Connection completed after ${Q} retries`),d};return Promise.race([c(),u]).then(d=>{this.remoteDevicePeerId=d,this.initConnectionMonitoring(),this.rtcClient=g,this.emit("connect")}).catch(d=>{throw console.debug(`${new Date().toISOString()} :: Connection failed: %o`,d),this.remoteDevicePeerId=null,g.shutdown().catch(B=>{console.error("rtcClient cannot shutdown: %o",B)}),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$1(this.rtcClient,"Realtime connection has not been started").getPeers()).find(r=>r.deviceId===this.id);return defined$1(n,"Could not find remote peer for device "+this.id)}async stopRealtimeConnection(){let t=!1;if(this.rtcClient){this.stopConnectionMonitoring(),this.remoteDevicePeerId?(await this.rtcClient.disconnect(this.remoteDevicePeerId),this.remoteDevicePeerId=null):t=!0;try{await this.rtcClient.shutdown()}finally{this.rtcClient=void 0}}if(t)throw new Error(`Realtime connection hasn't been started for ${this.id}`)}async isInRealtimeSession(){const t=await getPeers(),n=await getRealtimeSessions(),r=t.find(o=>o.deviceId===this.id);return r?n[r.id].length>0:!1}async getAvailableCommands(){return(await(await fetch(`${exports.FORMANT_API_URL}/v1/admin/command-templates/`,{method:"GET",headers:{"Content-Type":"application/json",Authorization:"Bearer "+Authentication.token}})).json()).items.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 g=(await this.getAvailableCommands()).find(B=>B.name===t);if(!g)throw new Error(`Could not find command with name "${t}"`);let l="";n===void 0?g.parameterEnabled&&g.parameterValue&&(l=g.parameterValue):l=n;let u={value:l,scrubberTime:(r||new Date).toISOString(),meta:{...g.parameterMeta,...o}};return await fetch(`${exports.FORMANT_API_URL}/v1/admin/commands`,{method:"POST",body:JSON.stringify({commandTemplateId:g.id,organizationId:this.organizationId,deviceId:this.id,command:g.command,parameter:u,userId:(d=Authentication.currentUser)==null?void 0:d.id}),headers:{"Content-Type":"application/json",Authorization:"Bearer "+Authentication.token}})}async getCommand(t){return await fetch(`${exports.FORMANT_API_URL}/v1/admin/commands/${t}`,{method:"GET",headers:{"Content-Type":"application/json",Authorization:"Bearer "+Authentication.token}})}async createCaptureStream(t){const r=await(await fetch(`${exports.FORMANT_API_URL}/v1/admin/capture-sessions`,{method:"POST",body:JSON.stringify({deviceId:this.id,streamName:t,tags:{}}),headers:{"Content-Type":"application/json",Authorization:"Bearer "+Authentication.token}})).json();return new CaptureStream(r)}async getTelemetry(t,n,r,o,s,g,l){if(s!==void 0||g!==void 0)throw new Error("Limit and offset are not supported in this method");return await getTelemetry(this.id,t,n,r,o,l)}async queryEvents(t){if(t.deviceIds)throw new Error("Cannot filter multiple devices via Device class");return t.deviceIds=[this.id],queryEvents(t)}async getTelemetryStreams(){var l,u;const t=await this.getConfiguration(),n=await fetch(`${exports.FORMANT_API_URL}/v1/queries/metadata/stream-names`,{method:"POST",body:JSON.stringify({deviceIds:[this.id]}),headers:{"Content-Type":"application/json",Authorization:"Bearer "+Authentication.token}}),r=[],o=[];return(u=(l=t.telemetry)==null?void 0:l.streams)==null||u.forEach(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(`${exports.FORMANT_API_URL}/v1/admin/intervention-requests`,{method:"POST",body:JSON.stringify({message:t,interventionType:n,time:new Date().toISOString(),deviceId:this.id,tags:o,data:r}),headers:{"Content-Type":"application/json",Authorization:"Bearer "+Authentication.token}})).json()}async addInterventionResponse(t,n,r){return await(await fetch(`${exports.FORMANT_API_URL}/v1/admin/intervention-responses`,{method:"POST",body:JSON.stringify({interventionId:t,interventionType:n,data:r}),headers:{"Content-Type":"application/json",Authorization:"Bearer "+Authentication.token}})).json()}async getAnnotationCount(t,n){return await getAnnotationCount({...t,deviceIds:[this.id]},n)}async getAnnotationCountByIntervals(t,n,r){return await getAnnotationCountByIntervals({...t,deviceIds:[this.id]},n,r)}async eventsCounter(t,n,r,o,s){return await eventsCounter(t,n,r,o,{...s,deviceIds:[this.id]})}async createShareLink(t,n){return t.scope.deviceIds=[this.id],await createShareLink(t,n)}}he(Device,"createDevice",createDevice),he(Device,"patchDevice",patchDevice),he(Device,"getDevicesData",getDevicesData),he(Device,"queryDevicesData",queryDevicesData),he(Device,"disableDevice",disableDevice);class PeerDevice extends BaseDevice{constructor(n){super();he(this,"id");he(this,"telemetryStreamActive",!1);he(this,"streamTelemetry",{});this.peerUrl=n}async getLatestTelemetry(){this.telemetryStreamActive||this.subscribeToTelemetry();const n=this.streamTelemetry;return Object.entries(n).map(([o,s])=>({deviceId:this.id,streamName:o,streamType:"json",currentValue:s,currentValueTime:s.timestamp,tags:{}}))}async getTelemetry(n,r,o,s,g,l,u){if(Array.isArray(n))throw new Error("Multiple stream names not supported");if(s)throw new Error("Tags not supported");if(u&&g===void 0)g=1;else if(u&&g!==void 0)throw new Error("latestOnly and limit cannot be used together");let c=`${this.peerUrl}/v1/querydatapoints?stream_name=${n}&start=${r.toISOString()}&end=${o.toISOString()}`;g!=null&&g>0&&(c+=`&limit=${g}`),l!=null&&l>=0&&(c+=`&offset=${l}`);const B=await(await fetch(c)).json(),Q=[];for(const f of B.results){const p=parseInt(f.timestamp),U=f.tags.data_type;delete f.tags.data_type,Q.push({deviceId:this.id,name:f.stream,points:[[p,this.getPointPayload(U,f)]],tags:f.tags,type:U})}return Q.reverse()}async queryEvents(n){const r=["id","viewed","keyword","message","sort","eventTypes","notificationEnabled","userIds","annotationTemplateIds","disableNullMatches","severities","deviceIds","names","types","tags","notNames"];this.checkKeysAndThrow(n,r);let o=`${this.peerUrl}/v1/queryevents?start=${n.start}&end=${n.end}`;n.count!=null&&n.count>0&&(o+=`&limit=${n.count}`),n.offset!=null&&n.offset>=0&&(o+=`&offset=${n.offset}`);const g=await(await fetch(o)).json(),l=[];for(const u of g.results){const c=parseInt(u.timestamp),d={deviceId:this.id,time:new Date(c).toISOString(),message:u.message,notificationEnabled:u.notificationEnabled,type:u.type,tags:u.tags};u.id!==""&&(d.id=u.id),u.type!==""&&(d.type=u.type),u.streamName!==""&&(d.streamName=u.streamName),u.streamType!==""&&(d.streamType=u.streamType),u.severity!==""&&(d.severity=u.severity.toLowerCase()),u.tags&&(d.tags=u.tags),u.endTimestamp!=="0"&&(d.endTime=new Date(parseInt(u.endTimestamp)).toISOString()),l.push(d)}return l.reverse()}checkKeysAndThrow(n,r){const o=r.filter(s=>s in n);if(o.length>0)throw new Error(`Filters not currently supported: ${o.join(", ")}.`)}getPointPayload(n,r){switch(n){case"numeric":return r.numeric.value;case"numeric set":return r.numericSet.numerics;case"text":return r.text.value;case"json":return r.json.value;case"bitset":const o=[],s=[];for(const g of r.bitset.bits)o.push(g.key),s.push(g.value);return{keys:o,values:s};case"location":return r.location;case"health":return r.health;case"battery":return r.battery;default:return{}}}subscribeToTelemetry(){this.telemetryStreamActive=!0;let n=0;const r=new XMLHttpRequest;r.responseType="text",r.addEventListener("error",o=>{this.handleXHRError("error")}),r.addEventListener("abort",o=>{this.handleXHRError("abort")}),r.addEventListener("timeout",o=>{this.handleXHRError("timeout")}),r.addEventListener("readystatechange",o=>{r.readyState===XMLHttpRequest.DONE&&this.handleXHRError("closed")}),r.addEventListener("progress",o=>{const s=o.loaded,g=s-n;n=s,r.responseText.substr(-g).split(`
62
+ `),Error.captureStackTrace(this,r)}}e.exports=o=>{if(o.length>2)throw new r(o);function s(l={}){this.options=l}function g(l){return new s(l)}return s.prototype.transform=o,g.Format=s,g}},function(e,t,n){function r(g,l){if(!(g instanceof l))throw new TypeError("Cannot call a class as a function")}function o(g,l){for(var u=0;u<l.length;u++){var c=l[u];c.enumerable=c.enumerable||!1,c.configurable=!0,"value"in c&&(c.writable=!0),Object.defineProperty(g,c.key,c)}}var s=n(87);e.exports=function(){function g(){var c=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};r(this,g),this.loggers=new Map,this.options=c}var l,u;return l=g,(u=[{key:"add",value:function(c,d){var B=this;if(!this.loggers.has(c)){var Q=(d=Object.assign({},d||this.options)).transports||this.options.transports;d.transports=Q?Q.slice():[];var f=s(d);f.on("close",function(){return B._delete(c)}),this.loggers.set(c,f)}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(B,Q){return d._removeLogger(Q)})}},{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(l.prototype,u),Object.defineProperty(l,"prototype",{writable:!1}),g}()},function(e,t,n){(function(r){const o=n(51),s=/^([A-Za-z0-9+/]{4})*([A-Za-z0-9+/]{4}|[A-Za-z0-9+/]{3}=|[A-Za-z0-9+/]{2}==)$/;e.exports=function(g,l,u,c){let d,B,Q=!1,f=!1;const p=n(93);function U(W){c(l,W)}function E(W,y){let m=`"${l}" ${y}`;throw W&&(m=""+m),B&&(m=`${m}. An example of a valid value would be: ${B}`),new o(m)}const M={convertFromBase64:function(){return U("marking for base64 conversion"),Q=!0,M},default:function(W){if(typeof W=="number")d=W.toString();else if(Array.isArray(W)||typeof W=="object"&&W!==null)d=JSON.stringify(W);else{if(typeof W!="string")throw new o("values passed to default() must be of Number, String, Array, or Object type");d=W}return U(`setting default value to "${d}"`),M},required:function(W){return W===void 0?(U("marked as required"),f=!0):(U("setting required flag to "+W),f=W),M},example:function(W){return B=W,M}};return Object.entries({...p,...u}).forEach(([W,y])=>{M[W]=function(m){return function(){let h=g[l];if(U(`will be read from the environment using "${m.name}" accessor`),h===void 0)if(d===void 0&&f)U("was not found in the environment, but is required to be set"),E(void 0,"is a required variable, but it was not set");else{if(d===void 0)return void U("was not found in the environment, but is not required. returning undefined");U(`was not found in the environment, parsing default value "${d}" instead`),h=d}f&&(U("verifying variable value is not an empty string"),h.trim().length===0&&E(void 0,"is a required variable, but its value was empty")),Q&&(U("verifying variable is a valid base64 string"),h.match(s)||E(h,"should be a valid base64 string if using convertFromBase64"),U("converting from base64 to utf8 string"),h=r.from(h,"base64").toString());const T=[h].concat(Array.prototype.slice.call(arguments));try{U(`passing value "${h}" to "${m.name}" accessor`);const I=m.apply(m,T);return U("parsed successfully, returning "+I),I}catch(I){E(h,I.message)}}}(y)}),M}}).call(this,n(5).Buffer)},function(e,t,n){const r=n(34);e.exports=function(o,s){return s=s||",",o.length?r(o).split(s).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(94);e.exports=function(o){var s=r(o);if(s>65535)throw new Error("cannot assign a port number greater than 65535");return s}},function(e,t,n){const r=n(34);e.exports=function(o,s){const g=r(o);if(s.indexOf(g)<0)throw new Error(`should be one of [${s.join(", ")}]`);return g}},function(e,t,n){const r=n(53);e.exports=function(o){const s=r(o);if(s>0)throw new Error("should be a negative float");return s}},function(e,t,n){const r=n(53);e.exports=function(o){const s=r(o);if(s<0)throw new Error("should be a positive float");return s}},function(e,t,n){const r=n(52);e.exports=function(o){const s=r(o);if(s>0)throw new Error("should be a negative integer");return s}},function(e,t,n){const r=n(54);e.exports=function(o){var s=r(o);if(!Array.isArray(s))throw new Error("should be a parseable JSON Array");return s}},function(e,t,n){const r=n(54);e.exports=function(o){var s=r(o);if(Array.isArray(s))throw new Error("should be a parseable JSON Object");return s}},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(95);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(s){const g=r(s);if(!o.test(g))throw new Error("should be a valid email address");return g}},function(e,t,n){e.exports=function(r,o){return function(s,g){o&&o.match(/prod|production/)||r(`env-var (${s}): ${g}`)}}},function(e,t,n){(function(r){(function(){var o,s,g,l,u,c;typeof performance!="undefined"&&performance!==null&&performance.now?e.exports=function(){return performance.now()}:r!=null&&r.hrtime?(e.exports=function(){return(o()-u)/1e6},s=r.hrtime,l=(o=function(){var d;return 1e9*(d=s())[0]+d[1]})(),c=1e9*r.uptime(),u=l-c):Date.now?(e.exports=function(){return Date.now()-g},g=Date.now()):(e.exports=function(){return new Date().getTime()-g},g=new Date().getTime())}).call(this)}).call(this,n(2))},function(e,t,n){(function(r){(function(o){function s(l){if((l=l===void 0?"utf-8":l)!=="utf-8")throw new RangeError("Failed to construct 'TextEncoder': The encoding label provided ('"+l+"') is invalid.")}function g(l,u){if(u=u===void 0?{fatal:!1}:u,(l=l===void 0?"utf-8":l)!=="utf-8")throw new RangeError("Failed to construct 'TextDecoder': The encoding label provided ('"+l+"') is invalid.");if(u.fatal)throw Error("Failed to construct 'TextDecoder': the 'fatal' option is unsupported.")}if(o.TextEncoder&&o.TextDecoder)return!1;Object.defineProperty(s.prototype,"encoding",{value:"utf-8"}),s.prototype.encode=function(l,u){if((u=u===void 0?{stream:!1}:u).stream)throw Error("Failed to encode: the 'stream' option is unsupported.");u=0;for(var c=l.length,d=0,B=Math.max(32,c+(c>>1)+7),Q=new Uint8Array(B>>3<<3);u<c;){var f=l.charCodeAt(u++);if(55296<=f&&56319>=f){if(u<c){var p=l.charCodeAt(u);(64512&p)==56320&&(++u,f=((1023&f)<<10)+(1023&p)+65536)}if(55296<=f&&56319>=f)continue}if(d+4>Q.length&&(B+=8,B=(B*=1+u/l.length*2)>>3<<3,(p=new Uint8Array(B)).set(Q),Q=p),(4294967168&f)==0)Q[d++]=f;else{if(!(4294965248&f))Q[d++]=f>>6&31|192;else if(!(4294901760&f))Q[d++]=f>>12&15|224,Q[d++]=f>>6&63|128;else{if(4292870144&f)continue;Q[d++]=f>>18&7|240,Q[d++]=f>>12&63|128,Q[d++]=f>>6&63|128}Q[d++]=63&f|128}}return Q.slice(0,d)},Object.defineProperty(g.prototype,"encoding",{value:"utf-8"}),Object.defineProperty(g.prototype,"fatal",{value:!1}),Object.defineProperty(g.prototype,"ignoreBOM",{value:!1}),g.prototype.decode=function(l,u){if((u=u===void 0?{stream:!1}:u).stream)throw Error("Failed to decode: the 'stream' option is unsupported.");u=0;for(var c=(l=new Uint8Array(l)).length,d=[];u<c;){var B=l[u++];if(B===0)break;if(!(128&B))d.push(B);else if((224&B)==192){var Q=63&l[u++];d.push((31&B)<<6|Q)}else if((240&B)==224){Q=63&l[u++];var f=63&l[u++];d.push((31&B)<<12|Q<<6|f)}else(248&B)==240&&(65535<(B=(7&B)<<18|(Q=63&l[u++])<<12|(f=63&l[u++])<<6|63&l[u++])&&(B-=65536,d.push(B>>>10&1023|55296),B=56320|1023&B),d.push(B))}return String.fromCharCode.apply(null,d)},o.TextEncoder=s,o.TextDecoder=g})(typeof window!="undefined"?window:r!==void 0?r:this)}).call(this,n(6))},function(e,t,n){n.r(t),n.d(t,"AuthClient",function(){return s}),n.d(t,"RtcSignalingClient",function(){return l}),n.d(t,"Credentials",function(){return C}),n.d(t,"SignalingPromiseClient",function(){return J.SignalingPromiseClient}),n.d(t,"RtcClient",function(){return It}),n.d(t,"RtcClientV1",function(){return Ct}),n.d(t,"createRtcStreamMessage",function(){return wt});var r=n(26),o=function(Re,Z,L,q){return new(L||(L=Promise))(function(ie,se){function ue(ce){try{Ue(q.next(ce))}catch(le){se(le)}}function fe(ce){try{Ue(q.throw(ce))}catch(le){se(le)}}function Ue(ce){var le;ce.done?ie(ce.value):(le=ce.value,le instanceof L?le:new L(function(me){me(le)})).then(ue,fe)}Ue((q=q.apply(Re,Z||[])).next())})};class s extends r.a{adminSignup(Z,L){return o(this,void 0,void 0,function*(){return yield this.fetch("auth/admin-signup",{token:L,method:"POST",body:Z})})}login(Z){return o(this,void 0,void 0,function*(){return yield this.fetch("auth/login",{method:"POST",body:Z,allowUnsafeRetries:!0})})}loginWithGoogleToken(Z){return o(this,void 0,void 0,function*(){return yield this.fetch("auth/login-google",{method:"POST",body:Z,allowUnsafeRetries:!0})})}refresh(Z,L){return o(this,void 0,void 0,function*(){return yield this.fetch("auth/refresh",{method:"POST",body:{refreshToken:Z,tokenExpirationSeconds:L},allowUnsafeRetries:!0})})}respondToNewPasswordRequiredChallenge(Z){return o(this,void 0,void 0,function*(){return yield this.fetch("auth/respond-to-new-password-required-challenge",{method:"POST",body:Z})})}forgotPassword(Z){return o(this,void 0,void 0,function*(){return yield this.fetch("auth/forgot-password",{method:"POST",body:{email:Z}})})}confirmForgotPassword(Z){return o(this,void 0,void 0,function*(){return yield this.fetch("auth/confirm-forgot-password",{method:"POST",body:Z})})}resendInvitation(Z){return o(this,void 0,void 0,function*(){return yield this.fetch("auth/resend-invitation",{method:"POST",body:{email:Z}})})}changePassword({token:Z,refreshToken:L,currentPassword:q,newPassword:ie}){return o(this,void 0,void 0,function*(){return yield this.fetch("auth/change-password",{token:Z,method:"POST",body:{refreshToken:L,currentPassword:q,newPassword:ie}})})}getDeviceCredentials(Z){return o(this,void 0,void 0,function*(){return yield this.fetch("auth/device-credentials",{token:Z,method:"POST",allowUnsafeRetries:!0})})}impersonate(Z,L){return o(this,void 0,void 0,function*(){return yield this.fetch("auth/impersonate",{token:Z,method:"POST",allowUnsafeRetries:!0,body:{userId:L}})})}createServiceAccount(Z,L,q,ie){return o(this,void 0,void 0,function*(){return yield this.fetch("auth/service-account",{token:Z,method:"POST",allowUnsafeRetries:!0,body:{name:L,roleId:q,tags:ie}})})}getFeatures(Z){return o(this,void 0,void 0,function*(){return(yield this.fetch("auth/features",{token:Z})).features})}checkSso(Z,L){return o(this,void 0,void 0,function*(){return yield this.fetch("auth/check-sso",{method:"POST",body:{email:Z,allowUserAutoCreation:L}})})}loginWithSso(Z,L){return o(this,void 0,void 0,function*(){return yield this.fetch("auth/login-sso",{method:"POST",body:{token:Z,refreshToken:L}})})}}var g=function(Re,Z,L,q){return new(L||(L=Promise))(function(ie,se){function ue(ce){try{Ue(q.next(ce))}catch(le){se(le)}}function fe(ce){try{Ue(q.throw(ce))}catch(le){se(le)}}function Ue(ce){var le;ce.done?ie(ce.value):(le=ce.value,le instanceof L?le:new L(function(me){me(le)})).then(ue,fe)}Ue((q=q.apply(Re,Z||[])).next())})};class l extends r.a{createPeer(Z,L){return g(this,void 0,void 0,function*(){return yield this.fetch("peers",{token:Z,method:"POST",body:L})})}getPeers(Z){return g(this,void 0,void 0,function*(){return(yield this.fetch("peers",{token:Z})).items})}refreshPeer(Z,L){return g(this,void 0,void 0,function*(){yield this.fetch(`peers/${L}/refresh`,{token:Z,method:"POST",allowUnsafeRetries:!0})})}createSession(Z,L){return g(this,void 0,void 0,function*(){return yield this.fetch("sessions",{token:Z,method:"POST",body:L})})}refreshSession(Z,L){return g(this,void 0,void 0,function*(){yield this.fetch(`sessions/${L}/refresh`,{token:Z,method:"POST",allowUnsafeRetries:!0})})}deleteSession(Z,L){return g(this,void 0,void 0,function*(){yield this.fetch("sessions/"+L,{token:Z,method:"DELETE",allowUnsafeRetries:!0})})}getSessions(Z){return g(this,void 0,void 0,function*(){return(yield this.fetch("sessions",{token:Z})).items})}getIceServers(Z){return g(this,void 0,void 0,function*(){return(yield this.fetch("ice-servers",{token:Z})).items})}addSignals(Z,L,q){return g(this,void 0,void 0,function*(){yield this.fetch(`sessions/${L}/add-signals`,{token:Z,method:"POST",body:q})})}takeSignals(Z,L){return g(this,void 0,void 0,function*(){return(yield this.fetch(`sessions/${L}/take-signals`,{token:Z,method:"POST"})).items})}}var u=n(1),c=n(9),d=n(15),B=n.n(d),Q=n(101),f=n.n(Q),p=n(3),U=n(0),E=function(Re,Z,L,q){return new(L||(L=Promise))(function(ie,se){function ue(ce){try{Ue(q.next(ce))}catch(le){se(le)}}function fe(ce){try{Ue(q.throw(ce))}catch(le){se(le)}}function Ue(ce){var le;ce.done?ie(ce.value):(le=ce.value,le instanceof L?le:new L(function(me){me(le)})).then(ue,fe)}Ue((q=q.apply(Re,Z||[])).next())})};class M extends class{constructor(Z,L){this.type=Z,this.name=L}}{constructor(Z){super("simple","LogReporter"),this.message=Z}send(Z){return E(this,void 0,void 0,function*(){var L,q;U.a.debug(this.message,(L=Z.reduce((ie,se)=>Object.assign(Object.assign({},ie),{[se.name]:se.stat}),{}),q=ie=>{const{sum:se,count:ue}=ie,fe=se/ue;return Object.assign(Object.assign({},ie),{average:fe})},Object.keys(L).reduce((ie,se)=>Object.assign(Object.assign({},ie),{[se]:q(L[se])}),{})))})}}const W=/^[a-zA-Z0-9-_.,:?'"()@\/\\#$+ ]{1,255}$/,y=/^[*a-zA-Z0-9-_.,:?'"()@\/\\#$+ ]{1,255}$/;function m(Re,Z=!1){return!!(Re!=null&&Re.match(Z?y:W))}var h=function(Re,Z,L,q){return new(L||(L=Promise))(function(ie,se){function ue(ce){try{Ue(q.next(ce))}catch(le){se(le)}}function fe(ce){try{Ue(q.throw(ce))}catch(le){se(le)}}function Ue(ce){var le;ce.done?ie(ce.value):(le=ce.value,le instanceof L?le:new L(function(me){me(le)})).then(ue,fe)}Ue((q=q.apply(Re,Z||[])).next())})};function T({func:Re,delay:Z,immediate:L=!1}){let q=!1,ie=setTimeout(function ue(){return h(this,void 0,void 0,function*(){if(q)return;const fe=new Date().getTime();try{se=Re(),yield se}finally{if(!q){const Ue=new Date().getTime();ie=setTimeout(ue,Math.max(Z-(Ue-fe),0))}}})},L?0:Z),se=Promise.resolve();return{stop(){return h(this,void 0,void 0,function*(){q=!0,clearTimeout(ie),yield se})}}}var I=function(Re,Z,L,q){return new(L||(L=Promise))(function(ie,se){function ue(ce){try{Ue(q.next(ce))}catch(le){se(le)}}function fe(ce){try{Ue(q.throw(ce))}catch(le){se(le)}}function Ue(ce){var le;ce.done?ie(ce.value):(le=ce.value,le instanceof L?le:new L(function(me){me(le)})).then(ue,fe)}Ue((q=q.apply(Re,Z||[])).next())})};const X=n(231);class F{constructor(Z){this.buffer={},this.reporters=[],this.flushInterval=T({func:()=>this.flushStats(),delay:F.samplePeriodMs}),this.tags=this.filterTags((Z==null?void 0:Z.tags)||{app:p.a,version:p.k,namespace:p.j})}shutdown(){return I(this,void 0,void 0,function*(){yield this.flushInterval.stop(),yield this.flushStats(),yield Object(c.a)(2*u.a.second)})}aggregate(Z,L,q){this.addToBuffer(this.buffer,this.encodeKey({metric:Z,tags:this.filterTags(q||{})}),typeof L=="number"?{min:L,max:L,sum:L,count:1}:L)}increment(Z,L){this.aggregate(Z,1,L)}timer(Z,L,q){return I(this,void 0,void 0,function*(){const ie=X(),se=yield L(),ue=X();return this.aggregate(Z,ue-ie,q),se})}registerStatsReporter(Z){this.reporters.push(Z)}setTag(Z,L){const q=this.filterTags({[Z]:L});this.tags=Object.assign(Object.assign({},this.tags),q)}addToBuffer(Z,L,q){if(Z[L]){const{min:ie,max:se,sum:ue,count:fe}=Z[L];Z[L]={min:Math.min(ie,q.min),max:Math.max(se,q.max),sum:ue+q.sum,count:fe+q.count}}else Z[L]=q}write(Z){return I(this,void 0,void 0,function*(){yield Promise.all(this.reporters.map(L=>I(this,void 0,void 0,function*(){let q;const ie={};switch(L.type){case"simple":for(const[ue,fe]of Object.entries(Z)){const{metric:Ue}=this.decodeKey(ue);this.addToBuffer(ie,this.encodeKey({metric:Ue}),fe)}q=ie;break;case"tagged":q=Z;break;default:(function(ue){throw new Error(`Unreachable type encountered (${ue})`)})(L.type)}const se=Object.entries(q);if(se.length>0)return L.send(se.map(([ue,fe])=>{const{metric:Ue,tags:ce}=this.decodeKey(ue);return{name:Ue,tags:Object.assign(Object.assign({},ce),this.tags),stat:fe}}),F.samplePeriodMs).catch(ue=>{U.a.debug("Failed to write stats to "+L.name,{error:ue})})})))})}flushStats(){return I(this,void 0,void 0,function*(){yield this.write(this.buffer),this.buffer={}})}encodeKey(Z){return B()(Object.assign(Object.assign({},Z),Object.keys(Z.tags||{}).length>0?{tags:Z.tags}:{}))}decodeKey(Z){return JSON.parse(Z)}filterTags(Z){return Object.entries(Z||{}).reduce((L,[q,ie])=>(m(q)&&m(ie)&&(L[q]=ie),L),{})}}F.samplePeriodMs=5*u.a.minute;const R=!!p.d,x=new F;R||["local","on-prem"].includes(p.j)||x.registerStatsReporter(new M("stats"));var w=function(Re,Z,L,q){return new(L||(L=Promise))(function(ie,se){function ue(ce){try{Ue(q.next(ce))}catch(le){se(le)}}function fe(ce){try{Ue(q.throw(ce))}catch(le){se(le)}}function Ue(ce){var le;ce.done?ie(ce.value):(le=ce.value,le instanceof L?le:new L(function(me){me(le)})).then(ue,fe)}Ue((q=q.apply(Re,Z||[])).next())})};class _ extends class{constructor(Z){this.options=Z,this.cache=new f.a(Object.assign(Object.assign(Object.assign({},Z.dispose||Z.disposeAfter?{ttlAutopurge:!0}:{}),Z),{dispose:(...L)=>{var q;L[2]==="evict"&&x.increment("lru-eviction",{name:Z.name}),(q=Z.dispose)===null||q===void 0||q.call(Z,...L)},disposeAfter:(...L)=>{var q;this.updateStats(),(q=Z.disposeAfter)===null||q===void 0||q.call(Z,...L)}})),this.stringify=Z.fastStringify?JSON.stringify:B.a}set(Z,L,q){const ie=this.stringify(Z);if(!this.cache.set(ie,L,{ttl:q})){const se=this.cache.sizeCalculation?this.cache.sizeCalculation(L,ie):"unknown";throw Error(`Value too large (${se} > ${this.cache.max})`)}this.updateStats()}get(Z){const{name:L}=this.options,q=this.stringify(Z),ie=this.cache.getRemainingTTL(q);return ie<=0?x.increment("cache-miss",{name:L}):ie!==1/0&&x.aggregate("cache-item-ttl",ie,{name:L}),this.cache.get(q)}delete(Z){this.cache.delete(this.stringify(Z))}peek(Z){return this.cache.peek(this.stringify(Z))}size(){return this.cache.size}clear(){this.cache.clear()}forEach(Z){this.cache.forEach(Z)}purgeStale(){return this.cache.purgeStale()}updateStats(){const{name:Z}=this.options;x.aggregate("cache-item-count",this.cache.size,{name:Z}),this.cache.calculatedSize!==void 0&&x.aggregate("cache-length",this.cache.calculatedSize,{name:Z})}}{constructor(Z){if(super(Z),this.expireRejectedPromiseValues=Z.expireRejectedPromiseValues===void 0||Z.expireRejectedPromiseValues,this.rejectedPromiseValueTtl=Z.rejectedPromiseValueTtl!==void 0?Z.rejectedPromiseValueTtl:u.a.second,this.rejectedPromiseValueTtl<0)throw new Error("rejectedPromiseValueTtl must not be negative")}set(Z,L,q){super.set(Z,L,q),this.expireRejectedPromiseValues&&L.catch(()=>w(this,void 0,void 0,function*(){yield Object(c.a)(this.rejectedPromiseValueTtl),this.peek(Z)===L&&this.delete(Z)}))}}var j=function(Re,Z,L,q){return new(L||(L=Promise))(function(ie,se){function ue(ce){try{Ue(q.next(ce))}catch(le){se(le)}}function fe(ce){try{Ue(q.throw(ce))}catch(le){se(le)}}function Ue(ce){var le;ce.done?ie(ce.value):(le=ce.value,le instanceof L?le:new L(function(me){me(le)})).then(ue,fe)}Ue((q=q.apply(Re,Z||[])).next())})};class C{constructor(Z,L,q){this.authClient=Z,this.email=L,this.password=q,this.tokenTtlMs=1*u.a.hour,this.tokenCache=new _({name:"Credentials-tokenCache",max:100,ttl:this.tokenTtlMs-5*u.a.minute,fastStringify:!0})}getToken(){return j(this,void 0,void 0,function*(){let Z=this.tokenCache.get(this.email);return Z||(Z=(()=>j(this,void 0,void 0,function*(){const{authentication:L}=yield this.authClient.login({email:this.email,password:this.password,tokenExpirationSeconds:this.tokenTtlMs/u.a.second});if(!L)throw new Error("User account not verified.");return L.accessToken}))(),this.tokenCache.set(this.email,Z)),Z})}}var J=n(96),v=n(17),D=n(236),A=n(41),b=function(Re,Z,L,q){return new(L||(L=Promise))(function(ie,se){function ue(ce){try{Ue(q.next(ce))}catch(le){se(le)}}function fe(ce){try{Ue(q.throw(ce))}catch(le){se(le)}}function Ue(ce){var le;ce.done?ie(ce.value):(le=ce.value,le instanceof L?le:new L(function(me){me(le)})).then(ue,fe)}Ue((q=q.apply(Re,Z||[])).next())})};class P extends A.a{constructor(Z){super(Z)}postLanRtcOffer(Z){return b(this,void 0,void 0,function*(){return yield this.fetch("v1/lan-rtc-offer",{method:"POST",body:Z})})}}var z=function(Re,Z,L,q){return new(L||(L=Promise))(function(ie,se){function ue(ce){try{Ue(q.next(ce))}catch(le){se(le)}}function fe(ce){try{Ue(q.throw(ce))}catch(le){se(le)}}function Ue(ce){var le;ce.done?ie(ce.value):(le=ce.value,le instanceof L?le:new L(function(me){me(le)})).then(ue,fe)}Ue((q=q.apply(Re,Z||[])).next())})};function $(Re){return z(this,void 0,void 0,function*(){return(yield Promise.all(Re.map(Z=>Z.catch(L=>L)))).filter(Z=>Z instanceof Error)})}function ee(Re,Z){if(Re===void 0)throw new Error("Value is undefined"+(Z?": "+Z:""))}function re(Re,Z){if(Re===null)throw new Error("Value is null"+(Z?": "+Z:""))}function O(Re){return ee(Re),Re}function k(Re,Z){const L=Re.reduce((q,ie)=>[...q,...ie.urls],[]).filter(q=>S(q,Z)).sort(q=>V(q,"udp")?-1:0).shift();if(L)return Object.assign(Object.assign({},O(Re.find(q=>q.urls.includes(L)))),{urls:[L]})}function S(Re,Z){switch(Z){case"stun":return/^stuns?:/.test(Re);case"turn":return/^turns?:/.test(Re)}}function V(Re,Z){return Re.endsWith("transport="+Z)}var G=n(10);class K extends Error{constructor(Z,L){super(`Deadline expired after ${Z}ms + ${L}ms`)}}class Y{static withDeadline(Z,L){const q=new Promise((ie,se)=>{setTimeout(()=>{se(new K(L,this.grpcCallDeadlineSlopMs))},L+this.grpcCallDeadlineSlopMs)});return Promise.race([Z,q])}}Y.grpcCallDeadlineSlopMs=500*u.a.millisecond;var te=n(27);const oe={ordered:!1,maxPacketLifeTime:300*u.a.millisecond},ge={ordered:!0},Se={ordered:!0},ve={ordered:!1,maxRetransmits:0},ye={ordered:!1,maxRetransmits:0},Je=Re=>"received"in Re&&Re.received!==void 0,Ee=Re=>!("received"in Re)||Re.received===void 0,be=2*u.a.second,we=10*u.a.second;function Ze(Re,Z={}){const L=Array.from(Re.values()),q=L.filter(Je),ie=q.length>0,se=Math.max(...L.map(le=>le.sent)),ue=Math.max(...q.map(le=>le.received));let fe;if(ie){const le=Date.now()-se<=u.a.millisecond?L.length-1:L.length,me=q.length>le?le:q.length,Ve=q.map(Me=>Me.received-Me.sent),{standardDeviation:Ce,mean:xe,jitter:He}=function(Me){const Le=Me.length;if(Le===0)return{mean:NaN,standardDeviation:-1,jitter:NaN};const Ge=Me.reduce((Xe,$e)=>Xe+$e,0)/Le,Ke=Math.sqrt(Me.map(Xe=>Math.pow(Xe-Ge,2)).reduce((Xe,$e)=>Xe+$e)/Le);if(Le===1)return{mean:Ge,standardDeviation:Ke,jitter:NaN};let Rt=0;for(let Xe=1;Xe<Le;Xe++)Rt+=Math.abs(Me[Xe]-Me[Xe-1]);return{mean:Ge,standardDeviation:Ke,jitter:Rt/(Le-1)}}(Ve),Ye=L.filter(Me=>Me.sent<ue-be),qe=Ye.filter(Ee),Pe=qe.length===0?0:qe.length/Ye.length;fe={pingsSent:le,pongsReceived:me,average:xe,standardDeviation:Ce,jitter:He,max:Math.max(...Ve),min:Math.min(...Ve),loss:Pe}}else fe=null;const{temporalNow:Ue=Date.now()}=Z,ce=(ie?ue:Ue)-we;return Array.from(Re.entries()).forEach(le=>{const[me,Ve]=le;Ve.sent<ce&&Re.delete(me)}),fe}function Oe({entityId:Re,streamName:Z,streamType:L}){return`${Re}.${Z}.${L}`}var it=function(Re,Z,L,q){return new(L||(L=Promise))(function(ie,se){function ue(ce){try{Ue(q.next(ce))}catch(le){se(le)}}function fe(ce){try{Ue(q.throw(ce))}catch(le){se(le)}}function Ue(ce){var le;ce.done?ie(ce.value):(le=ce.value,le instanceof L?le:new L(function(me){me(le)})).then(ue,fe)}Ue((q=q.apply(Re,Z||[])).next())})};class mt{constructor(Z,L){this.counts={localSent:new Map,localReceived:new Map,remoteSent:new Map,remoteReceived:new Map},this.sessionId=Z,this.connection=L}updateRemoteMessagesCounts(Z){if(Z.payload.streamsInfo){this.counts.remoteSent=new Map,this.counts.remoteReceived=new Map;for(const L of Z.payload.streamsInfo.items)this.counts.remoteSent.set(L.streamId,L.sentCount),this.counts.remoteReceived.set(L.streamId,L.receivedCount)}}getLocalStreamsInfo(Z){const{localSent:L,localReceived:q}=this.counts;return{items:[...new Set([...L.keys(),...q.keys()])].map(ie=>{var se,ue;return{streamId:ie,sentCount:(se=L.get(ie))!==null&&se!==void 0?se:0,receivedCount:(ue=q.get(ie))!==null&&ue!==void 0?ue:0}}),timestamp:Z}}incrementLocalSent(Z){const{localSent:L}=this.counts,q=Oe(Z.header.stream);L.set(q,(L.get(q)||0)+1)}incrementLocalReceived(Z){const{localReceived:L}=this.counts,q=Oe(Z.header.stream),ie=L.get(q)||0;if(ie===0){const{streamName:se,streamType:ue}=Z.header.stream;U.a.debug("RTC client received first message for stream",{streamName:se,streamType:ue})}L.set(q,ie+1)}uploadMetrics(){return it(this,void 0,void 0,function*(){const{sessionId:Z}=this,L=yield this.connection.peerConnection.getStats(),q={};L.forEach(ce=>q[ce.id]=ce),U.a.debug("rtc-stats",Object.assign(Object.assign({},q),{sessionId:Z}));const{localSent:ie,localReceived:se,remoteSent:ue,remoteReceived:fe}=this.counts,Ue=[...new Set([...ie.keys(),...se.keys()])].reduce((ce,le)=>{const me=ie.get(le),Ve=se.get(le),Ce=ue.get(le),xe=fe.get(le);return Object.assign(Object.assign({},ce),{[`local-${le}-sent`]:me,[`local-${le}-received`]:Ve,[`remote-${le}-sent`]:Ce,[`remote-${le}-received`]:xe})},{sessionId:Z});U.a.debug("rtc-message-report",Object.assign({deviceId:this.connection.getRemoteDeviceId()},Ue))})}}function wt(Re,Z,L){return{header:{stream:Re,created:Date.now(),frameId:L||""},payload:Z}}function bt(Re){const Z=Re.localCandidate.candidateType,L=Re.remoteCandidate.candidateType;return Z==="host"&&L==="host"?"local":Z==="relay"||L==="relay"?"TURN":"STUN"}function gt(Re){return new Set(["disconnected","failed","closed"]).has(Re.iceConnectionState)}function Et(Re){switch(Re.header.stream.streamType){case"twist":{const{twist:Z}=Re.payload;if(!Z)throw Error("twist not in payload of RTC message with type twist");return{header:Re.header,payload:{twist:{linear:Object.assign({x:0,y:0,z:0},Z.linear),angular:Object.assign({x:0,y:0,z:0},Z.angular)}}}}case"pose":{const{pose:Z}=Re.payload;if(!Z)throw Error("pose not in payload of RTC message with type pose");return{header:Re.header,payload:{pose:{translation:Object.assign({x:0,y:0,z:0},Z.translation),rotation:Object.assign({x:0,y:0,z:0,w:0},Z.rotation)}}}}case"pose-with-covariance":{const{poseWithCovariance:Z}=Re.payload;if(!Z)throw Error("poseWithCovariance not in payload of RTC message with type pose-with-covariance");const L=new Array(36).fill(0);return Z.covariance.forEach((q,ie)=>{if(ie>=36)throw Error("covariance contains more than 36 elements");L[ie]=q}),{header:Re.header,payload:{poseWithCovariance:{pose:{translation:Object.assign({x:0,y:0,z:0},Z.pose.translation),rotation:Object.assign({x:0,y:0,z:0,w:0},Z.pose.rotation)},covariance:L}}}}case"point":{const{point:Z}=Re.payload;if(!Z)throw Error("point not in payload of RTC message with type point");return{header:Re.header,payload:{point:Object.assign({x:0,y:0,z:0},Z)}}}default:return Re}}var at=function(Re,Z,L,q){return new(L||(L=Promise))(function(ie,se){function ue(ce){try{Ue(q.next(ce))}catch(le){se(le)}}function fe(ce){try{Ue(q.throw(ce))}catch(le){se(le)}}function Ue(ce){var le;ce.done?ie(ce.value):(le=ce.value,le instanceof L?le:new L(function(me){me(le)})).then(ue,fe)}Ue((q=q.apply(Re,Z||[])).next())})};class Tt{get peerConnection(){return re(this._peerConnection,"RTCPeerConnection is closed!"),this._peerConnection}constructor(Z,L,q,ie){this.iceServers=L,this.config=q,this.dataChannelNotifier=ie,this.connectTimeoutMs=20*u.a.second,this.iceGatheringTimeoutMs=3*u.a.second,this.pingUpdateTimeoutMs=1*u.a.second,this.pingV2UpdateTimeoutMs=250*u.a.millisecond,this.pingV2MetricsGatherTimeoutMs=1*u.a.second,this.streamsInfoUpdateTimeoutMs=2*u.a.second,this.reassemblyTimeoutMs=500*u.a.millisecond,this.reassemblyTableCleanupMs=1*u.a.second,this.heartbeatTimeoutMs=20*u.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:ue}=this;if(!ue)return;const fe=new Date().getTime(),Ue=Object(D.a)();this.sendSystemMessage(ue,{type:"ping-v2",payload:{timestamp:fe,id:Ue}}),this.pingV2Map.set(Ue,{sent:fe})},this.gatherPingV2Metrics=()=>{const ue=Ze(this.pingV2Map);if(ue){const fe=this.getRemoteDeviceId();this.pingInfo=ue,x.aggregate("rtc-ping-average",ue.average,Object.assign({},fe?{deviceId:fe}:{})),x.aggregate("rtc-ping-loss",ue.loss,Object.assign({},fe?{deviceId:fe}:{})),x.aggregate("rtc-jitter",ue.jitter,Object.assign({},fe?{deviceId:fe}:{}))}},this._peerConnection=Z;const{isOffer:se}=q.baseConfig;se?this.initializeChannels(Z):Z.ondatachannel=ue=>{switch(ue.channel.label){case"stream.latest-ttl":this.latestTtlStreamChannel=ue.channel;break;case"stream.reliable":this.reliableStreamChannel=ue.channel;break;case"stream.latest-reliable":this.latestReliableStreamChannel=ue.channel;break;case"stream.latest-try-once":this.latestTryOnceStreamChannel=ue.channel;break;case"heartbeat":return void(this.heartbeatChannel=ue.channel);default:return void this.dataChannelNotifier(ue.channel)}this.setupChannel(ue.channel)},this.pingUpdateTimeout=setInterval(()=>{const{reliableStreamChannel:ue}=this;ue&&this.sendSystemMessage(ue,{type:"ping"})},this.pingUpdateTimeoutMs),this.pingV2UpdateTimeout=setInterval(this.sendPingV2,this.pingV2UpdateTimeoutMs),this.pingV2MetricsGatherTimeout=setInterval(this.gatherPingV2Metrics,this.pingV2MetricsGatherTimeoutMs),this.streamsInfoUpdateTimeout=setInterval(()=>{const{latestTtlStreamChannel:ue}=this;ue&&this.sendSystemMessage(ue,{type:"streams-info"})},this.streamsInfoUpdateTimeoutMs),this.reassemblyTableCleanupTimeout=setInterval(()=>{const ue=new Date().getTime();this.reassemblyTableLastTimestamp.forEach((fe,Ue,ce)=>{ue>Ue+this.reassemblyTimeoutMs&&this.reassemblyTable.delete(fe)})},this.reassemblyTableCleanupMs),this.heartbeatTimeout=setInterval(()=>{const{heartbeatChannel:ue}=this;ue&&ue.readyState==="open"&&ue.send(new Uint8Array([1]))},this.heartbeatTimeoutMs)}handleSignal(Z){return at(this,void 0,void 0,function*(){const{peerConnection:L}=this,{track:q}=this.config.baseConfig,ie=(()=>{try{return JSON.parse(Z.getPayload())}catch{return}})();if(!ie)return void U.a.error("Received unparseable signal.");U.a.debug("Handling signal",{description:ie});const{sdp:se,type:ue}=ie;if(!se||!ue)return void U.a.warn("Received non-SDP signal");const{signalingState:fe,connectionState:Ue}=L;if(fe!=="stable"||Ue!=="connected")if(L.remoteDescription)U.a.warn("Received SDP after remote description was set: "+se);else{if(ue==="offer"){if(fe!=="stable")return void U.a.warn("Received offer SDP when signaling is ongoing.");yield L.setRemoteDescription(ie);const ce=yield L.createAnswer();yield L.setLocalDescription(ce);const le=Z.clone();return q==null||q("Answer Received",le),le.setPayload(JSON.stringify(ce)),le.setReceiverId(Z.getSenderId()),le.setSenderId(Z.getReceiverId()),le}if(ue==="answer"){if(fe==="stable")return void U.a.warn("Received answer SDP when signaling hasn't started.");yield L.setRemoteDescription(ie)}}else U.a.warn("Received SDP when already connected: "+se)})}send(Z,L){const q=this.getChannelFromLabel(L.channelLabel);q?this.sendOnChannel(q,Z):U.a.warn("Send called with unexpected channel label",{channelLabel:L.channelLabel})}controlRemoteStream(Z){var L;this.sendSystemMessage((re(L=this.reliableStreamChannel),L),{type:"stream-control",streamControl:Z})}isActive(){return new Set(["new","checking","connected","completed"]).has(this.peerConnection.iceConnectionState)||this.isReady()}isReady(){const{reliableStreamChannel:Z,latestTtlStreamChannel:L,latestTryOnceStreamChannel:q,latestReliableStreamChannel:ie}=this;return(Z==null?void 0:Z.readyState)==="open"&&(L==null?void 0:L.readyState)==="open"&&(q==null?void 0:q.readyState)==="open"&&(ie==null?void 0:ie.readyState)==="open"}close(){var Z,L,q,ie,se,ue,fe;return at(this,void 0,void 0,function*(){this.closeCalled||(this.closeCalled=!0,yield(Z=this.sessionMetrics)===null||Z===void 0?void 0:Z.uploadMetrics(),pt(this.pingUpdateTimeout),pt(this.pingV2UpdateTimeout),pt(this.pingV2MetricsGatherTimeout),pt(this.reassemblyTableCleanupTimeout),pt(this.streamsInfoUpdateTimeout),pt(this.heartbeatTimeout),(L=this._peerConnection)===null||L===void 0||L.close(),(q=this.heartbeatChannel)===null||q===void 0||q.close(),(ie=this.latestReliableStreamChannel)===null||ie===void 0||ie.close(),(se=this.latestTryOnceStreamChannel)===null||se===void 0||se.close(),(ue=this.latestTtlStreamChannel)===null||ue===void 0||ue.close(),(fe=this.reliableStreamChannel)===null||fe===void 0||fe.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 Z;return(Z=this.config.remoteConfig)===null||Z===void 0?void 0:Z.sessionCreatedTimestamp}setSessionCreatedTimestamp(Z){this.config.remoteConfig&&(this.config.remoteConfig.sessionCreatedTimestamp=Z)}getSessionId(){var Z;return(Z=this.config.remoteConfig)===null||Z===void 0?void 0:Z.sessionId}setSessionId(Z){this.config.remoteConfig&&(this.config.remoteConfig.sessionId=Z,this.sessionMetrics=new mt(Z,this))}getRemotePeerId(){return this.config.baseConfig.remotePeerId}getRemoteDeviceId(){var Z;return(Z=this.config.baseConfig)===null||Z===void 0?void 0:Z.remoteDeviceId}setRemoteDeviceId(Z){this.config.baseConfig.remoteDeviceId=Z}getSessionMetricsMessageCounts(){var Z;return(Z=this.sessionMetrics)===null||Z===void 0?void 0:Z.counts}getConnectionStatsInfo(){return at(this,void 0,void 0,function*(){const{peerConnection:Z}=this;if(!Z)return;const L=yield Z.getStats(null),q=[];L.forEach(Ue=>{q.push(Ue)});const ie=q.find(Ue=>Ue.type==="transport");if(!ie)return;const se=q.find(Ue=>(Ue.type==="candidate-pair"||Ue.type==="candidatepair")&&Ue.id===ie.selectedCandidatePairId);if(!se)return;const ue=q.find(Ue=>Ue.id===se.localCandidateId),fe=q.find(Ue=>Ue.id===se.remoteCandidateId);return ue&&fe&&(ue.address=ue.address||ue.ip,fe.address=fe.address||fe.ip,ue.address!==void 0&&fe.address!==void 0)?{transport:ie,localCandidate:ue,remoteCandidate:fe,candidatePair:se}:void 0})}initializeChannels(Z){this.heartbeatChannel=Z.createDataChannel("heartbeat",ye),this.heartbeatChannel.binaryType="arraybuffer",this.latestTtlStreamChannel=Z.createDataChannel("stream.latest-ttl",oe),this.latestTtlStreamChannel.binaryType="arraybuffer",this.reliableStreamChannel=Z.createDataChannel("stream.reliable",ge),this.reliableStreamChannel.binaryType="arraybuffer",this.latestReliableStreamChannel=Z.createDataChannel("stream.latest-reliable",Se),this.latestReliableStreamChannel.binaryType="arraybuffer",this.latestTryOnceStreamChannel=Z.createDataChannel("stream.latest-try-once",ve),this.latestTryOnceStreamChannel.binaryType="arraybuffer",this.setupChannel(this.latestTtlStreamChannel),this.setupChannel(this.reliableStreamChannel),this.setupChannel(this.latestReliableStreamChannel),this.setupChannel(this.latestTryOnceStreamChannel)}getOffer(){var Z,L;return at(this,void 0,void 0,function*(){const{gotOffer:q}=this,{peerConnection:ie,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 ue=(Z=this.config.remoteConfig)===null||Z===void 0?void 0:Z.sessionId;if(q)return void U.a.debug("Failed to generate offer because gotOffer was already called.");if(this.gotOffer=!0,gt(this.peerConnection))return void U.a.debug("Failed to generate offer because the peer connection was inactive.");const fe=se.baseConfig.track;ie.onicecandidate=()=>{this.hasIceCandidate=!0},ie.oniceconnectionstatechange=()=>at(this,void 0,void 0,function*(){const Ce=ie.iceConnectionState;if(Ce==="connected"||Ce==="completed"){const xe=yield this.getConnectionStatsInfo(),He=xe?bt(xe):void 0;U.a.info("ICE connection state changed to "+Ce,{sessionId:ue,connectionStatsInfo:xe,iceMode:He}),fe==null||fe("ICE connection state change",{iceConnectionState:Ce,sessionId:ue,connectionStatsInfo:xe,iceMode:He})}}),yield ie.setLocalDescription(yield ie.createOffer());const Ue=ie.getConfiguration?ie.getConfiguration().iceTransportPolicy:"all",ce=new Date().getTime();for(;;){const Ce=new Date().getTime()-ce;if(Ce>this.connectTimeoutMs)return void U.a.debug("Failed to generate offer because ICE gathering timed out.");if(Ce>this.iceGatheringTimeoutMs&&this.hasIceCandidate){U.a.debug("ICE gathering partially completed; proceeding",{iceTransportPolicy:Ue,waitTime:Ce}),fe==null||fe("ICE gathering partially completed",{sessionId:ue,iceTransportPolicy:Ue,waitTime:Ce});break}if(ie.iceGatheringState==="complete"){U.a.debug("ICE gathering complete",{iceTransportPolicy:Ue,waitTime:Ce}),fe==null||fe("ICE gathering completed",{sessionId:ue,iceTransportPolicy:Ue,waitTime:Ce});break}yield Object(c.a)(.1*u.a.second)}const le=(L=this.iceServers)!==null&&L!==void 0?L:[];for(const Ce of le)"credentialType"in Ce&&(Ce.credentialType=void 0);const me=JSON.stringify(le),Ve=new G.Signal;return Ve.setPayload(JSON.stringify(ie.localDescription)),Ve.setSenderId(this.config.baseConfig.localPeerId),Ve.setReceiverId(this.config.baseConfig.remotePeerId),Ve.setIceServers(me),Ve.setIceTransportPolicy(Ue!=null?Ue:"all"),this.config.baseConfig.sessionType!==void 0?Ve.setSessionType(this.config.baseConfig.sessionType):Ve.setSessionType(G.SessionType.TELEOP),U.a.debug("Sending offer signal with description",{description:Ve.getPayload()}),Ve})}getLanOffer(){return at(this,void 0,void 0,function*(){const{peerConnection:Z,gotOffer:L}=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(L)return void U.a.debug("Failed to generate offer because gotOffer was already called.");if(this.gotOffer=!0,gt(this.peerConnection))return void U.a.debug("Failed to generate offer because the peer connection was inactive.");yield Z.setLocalDescription(yield Z.createOffer());const q=new Date().getTime();for(;;){if(new Date().getTime()-q>this.iceGatheringTimeoutMs)return void U.a.debug("Failed to generate offer because ICE gathering timed out.");if(Z.iceGatheringState==="complete")break;yield Object(c.a)(.1*u.a.second)}const ie=Z.localDescription;if(ie)return U.a.debug("Sending LAN offer signal with description",{description:ie}),ie;U.a.error("Failed to generate LAN offer description")})}handleLanAnswer(Z){return at(this,void 0,void 0,function*(){const{peerConnection:L}=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 L.setRemoteDescription(Z)})}getChannelFromLabel(Z){switch(Z){case"stream.latest-ttl":return this.latestTtlStreamChannel;case"stream.reliable":return this.reliableStreamChannel;case"stream.latest-reliable":return this.latestReliableStreamChannel;case"stream.latest-try-once":return this.latestTryOnceStreamChannel}}sendOnChannel(Z,L){var q;let ie;try{ie=Object(te.encode)(JSON.stringify(L))}catch(se){return void U.a.warn("Failed to encode RTC message",{error:se})}try{Z.send(ie),(q=this.sessionMetrics)===null||q===void 0||q.incrementLocalSent(L)}catch(se){U.a.warn("Failed to send message to channel",{error:se,channel:Z.label})}}channelNotRecognized(Z){return Z!==this.latestTtlStreamChannel&&Z!==this.latestReliableStreamChannel&&Z!==this.latestTryOnceStreamChannel&&Z!==this.reliableStreamChannel}setupChannel(Z){Z.onmessage=L=>{if(this.channelNotRecognized(Z))return void U.a.warn("Received message on unrecognized data channel.");let q;try{q=JSON.parse(Object(te.decode)(L.data))}catch(ie){return void U.a.warn("Received unparseable message on RTC stream data channel",{error:ie,channel:Z.label})}q.communicationType==="message-chunk"?this.receiveChannelMessageChunk(Z,q):this.receiveChannelMessage(Z,q)},Z.onerror=L=>{U.a.warn("Channel error: "+L.error,{error:L.error,sessionId:this.getSessionId(),channelLabel:Z.label})},Z.onopen=()=>{U.a.debug("Channel opened",{sessionId:this.getSessionId(),channelLabel:Z.label})},Z.onclose=()=>{const L={bufferedAmount:Z.bufferedAmount,sessionId:this.getSessionId(),channelLabel:Z.label};this.closeCalled===!1?U.a.debug("Unexpected channel closed",L):U.a.debug("Channel closed",L)}}receiveChannelMessage(Z,L){var q;const{config:ie}=this,{remotePeerId:se}=this.config.baseConfig;this.lastMessageTimestamp=new Date().getTime(),L=Et(L),(q=this.sessionMetrics)===null||q===void 0||q.incrementLocalReceived(L),!this.handleSystemMessage(Z,L)&&((Z===this.latestTryOnceStreamChannel||Z===this.latestTtlStreamChannel||Z===this.latestReliableStreamChannel)&&!this.isLatestMessage(L)||ie.baseConfig.receive(se,L))}receiveChannelMessageChunk(Z,L){const q=this.reassemblyTable.get(L.id)||[];if(q.push(L),q.length===L.total){const ie=function(se){const ue=se.sort((fe,Ue)=>fe.seq<Ue.seq?-1:1).map(fe=>fe.part).reduce((fe,Ue)=>fe+Ue);try{return JSON.parse(ue)}catch{return void U.a.warn("Could not reassemble RTC message chunks")}}(q);return ie&&this.receiveChannelMessage(Z,ie),void this.reassemblyTable.delete(L.id)}this.reassemblyTable.set(L.id,q),this.reassemblyTableLastTimestamp.set(L.id,new Date().getTime())}handleSystemMessage(Z,L){var q,ie;const{config:se}=this,{baseConfig:ue}=se,{remotePeerId:fe,remoteDeviceId:Ue}=ue;switch(L.header.stream.streamType){case"ping":return this.sendSystemMessage(Z,{type:"pong",timestamp:O(L.payload.ping)}),!0;case"pong":{const ce=new Date().getTime()-O(L.payload.pong);return this.pingTimeMs=ce,x.aggregate("rtc-ping-time",ce,Object.assign({},Ue?{deviceId:Ue}:{})),!0}case"ping-v2":return this.sendPingV2(),!0;case"pong-v2":{const ce=O(L.payload.pongV2),le=this.pingV2Map.get(ce.id);return(le==null?void 0:le.sent)!==ce.timestamp&&U.a.warn("Pong timestamp doesn't match stored value",{currentEntry:le,pong:ce}),this.pingV2Map.set(ce.id,{sent:ce.timestamp,received:new Date().getTime()}),!0}case"streams-info":{const{sessionMetrics:ce}=this,le=(q=L.payload.streamsInfo)===null||q===void 0?void 0:q.timestamp;return!!le&&(ce==null||ce.updateRemoteMessagesCounts(L),(ie=ue.onStreamsInfoUpdate)===null||ie===void 0||ie.call(ue,fe,le),!0)}case"stream-control":return!0;default:return!1}}sendSystemMessage(Z,L){var q;const{localUserId:ie,localPeerId:se}=this.config.baseConfig;if(Z.readyState!=="open")return;const ue={entityId:ie!=null?ie:se,streamName:"$."+L.type,streamType:L.type};let fe;switch(L.type){case"ping":fe={ping:new Date().getTime()};break;case"pong":fe={pong:L.timestamp};break;case"ping-v2":fe={pingV2:L.payload};break;case"pong-v2":fe={pongV2:L.payload};break;case"stream-control":fe={streamControl:L.streamControl};break;case"streams-info":fe={streamsInfo:(q=this.sessionMetrics)===null||q===void 0?void 0:q.getLocalStreamsInfo(new Date().getTime())}}this.sendOnChannel(Z,wt(ue,fe))}isLatestMessage(Z){const L=Oe(Z.header.stream),q=(this.streamLatestTimestamp.get(L)||0)<=Z.header.created;return q&&this.streamLatestTimestamp.set(L,Z.header.created),q}}function pt(Re){Re&&clearInterval(Re)}function vt(){U.a.debug("forceGarbageCollection() triggered"),queueMicrotask(()=>{let Re=document.createElement("img");Re.src=window.URL.createObjectURL(new Blob([new ArrayBuffer(5e7)])),Re.onerror=function(){window.URL.revokeObjectURL(this.src),Re=null}})}function Ot(Re){try{return Re instanceof Error?`${Re.name}: ${Re.message}`:typeof Re=="object"?JSON.stringify(Re):String(Re)}catch{return"Unknown error"}}function ut(Re){var Z,L;return{userId:(Z=Re.getUserId())===null||Z===void 0?void 0:Z.getValue(),deviceId:(L=Re.getDeviceId())===null||L===void 0?void 0:L.getValue(),organizationId:Re.getOrganizationId(),id:Re.getPeerId(),capabilities:[],capabilitySet:{}}}var De=function(Re,Z,L,q){return new(L||(L=Promise))(function(ie,se){function ue(ce){try{Ue(q.next(ce))}catch(le){se(le)}}function fe(ce){try{Ue(q.throw(ce))}catch(le){se(le)}}function Ue(ce){var le;ce.done?ie(ce.value):(le=ce.value,le instanceof L?le:new L(function(me){me(le)})).then(ue,fe)}Ue((q=q.apply(Re,Z||[])).next())})};const ht=Re=>Re.map(Z=>Object.assign(Object.assign(Object.assign({},Z),Z.username?{username:"<REDACTED>"}:null),Z.credential?{credential:"<REDACTED>"}:null));class It{constructor(Z){this.config=Z,this.grpcCallDeadline=5*u.a.second,this.refreshIntervalDelayMs=2*u.a.second,this.iceServersTtl=30*u.a.minute,this.connections=[],this.localConnections=[],this.isConnectionInitiator=new WeakSet,this.isOutgoingConnection=new Set,this.peerDataChannelListeners=[],this.rtcInstancesConstructed=0,this.statsLoopsExecuted=0;const{refreshIntervalDelayMs:L}=this;this.refreshInterval=T({func:()=>De(this,void 0,void 0,function*(){try{yield this.update()}catch(q){U.a.warn("RTC refresh failed",{error:q})}}),delay:L,immediate:!0})}send(Z,L,q){const ie=this.getActiveConnection(Z);ie?ie.isReady()?ie.send(L,q):U.a.warn("Send called with unready connection."):U.a.warn("Send called with no connection.")}controlRemoteStream(Z,L){const q=this.getActiveConnection(Z);q?q.isReady()?q.controlRemoteStream(L):U.a.warn("controlRemoteStream called with unready connection."):U.a.warn("controlRemoteStream called with no connection.")}getLocalPeer(){return De(this,void 0,void 0,function*(){for(;!this.localPeer;)yield Object(c.a)(.1*u.a.second);return ut(this.localPeer)})}connect(Z,L){var q,ie,se;return De(this,void 0,void 0,function*(){if(this.config.lanOnlyMode===!0)throw new Error("connect method called in local only mode.");const{track:ue,signalingClient:fe}=this.config,{localPeer:Ue,receiveSignalStream:ce,iceServers:le}=this;if(!Ue||!ce||!le)return void U.a.warn("Connect called prior to local peer, receiveSignalStream, and ICE servers ready");if(this.getActiveConnection(Z))return void U.a.warn("Connect called for peer with existing connection.");if(this.isOutgoingConnection.has(Z))return void U.a.warn("Connect called for peer with an existing outgoing connection offer.");this.isOutgoingConnection.add(Z);const me=function(Pe,Me,Le){const{rtcIceTransportPolicies:Ge,rtcIceServerProtocol:Ke,useAllServers:Rt}=Me||{},Xe=Pe.map($e=>Object.assign(Object.assign({},$e),{urls:$e.urls.filter(st=>{const _t=(Ge===void 0||Ge.some(kt=>S(st,kt)))&&(Ke===void 0||V(st,Ke));return _t||U.a.debug("Ignoring ICE server: "+st,{organizationId:Le}),_t})})).filter(({urls:$e})=>$e.filter(st=>st).length>0);return Rt?Xe:[k(Xe,"stun"),k(Xe,"turn")].filter($e=>$e!==void 0).map($e=>O($e))}(le,L);U.a.debug("Received ICE servers:",ht(le)),U.a.debug("Using ICE servers:",ht(me));const Ve=new Tt(yield this.createRTCPeerConnection(me),me,{baseConfig:{isOffer:!0,isLan:!1,receive:(Pe,Me)=>this.config.receive(Pe,Me),onStreamsInfoUpdate:this.config.onStreamsInfoUpdate?(Pe,Me)=>{var Le,Ge;return(Ge=(Le=this.config).onStreamsInfoUpdate)===null||Ge===void 0?void 0:Ge.call(Le,Pe,Me)}:void 0,track:this.config.lanOnlyMode?void 0:this.config.track,localUserId:(q=Ue.getUserId())===null||q===void 0?void 0:q.getValue(),localPeerId:Ue.getPeerId(),remotePeerId:Z,sessionType:this.config.sessionType},remoteConfig:{}},Pe=>this.onCustomDataChannel(Z,Pe)),Ce=yield Ve.getOffer();if(!Ce)return U.a.error("Failed to generate offer."),void this.isOutgoingConnection.delete(Z);U.a.debug("Sending offer."),ue==null||ue("Sending offer",Ce);const xe=new G.SendSignalRequest;xe.setSignal(Ce);const He=yield(()=>De(this,void 0,void 0,function*(){try{return yield Y.withDeadline(fe.sendSignal(xe,yield this.getMetadata()),this.grpcCallDeadline)}catch(Pe){U.a.warn("Error when sending signal",{error:Pe})}}))();if(!this.isOutgoingConnection.has(Z))return void U.a.debug("No offer set after receiving offer signal response.");U.a.debug("Offer sent.");const Ye=(ie=He==null?void 0:He.getSessionId())===null||ie===void 0?void 0:ie.getValue(),qe=(se=He==null?void 0:He.getSessionCreatedTimestamp())===null||se===void 0?void 0:se.getValue();return Ye&&qe?(Ve.setSessionId(Ye),Ve.setSessionCreatedTimestamp(qe),this.isOutgoingConnection.delete(Z),this.connections.push(Ve),this.isConnectionInitiator.add(Ve),this.setupHandlers(Ve),Ye):(U.a.warn("No session ID or no session created timestamp on send signal response."),void this.isOutgoingConnection.delete(Z))})}connectLan(Z){var L,q;return De(this,void 0,void 0,function*(){const ie=new P(Z),se=new Tt(yield this.createRTCPeerConnection([]),[],{baseConfig:{isOffer:!0,isLan:!0,receive:(ce,le)=>this.config.receive(ce,le),onStreamsInfoUpdate:this.config.onStreamsInfoUpdate?(ce,le)=>{var me,Ve;return(Ve=(me=this.config).onStreamsInfoUpdate)===null||Ve===void 0?void 0:Ve.call(me,ce,le)}:void 0,track:this.config.lanOnlyMode?void 0:this.config.track,localUserId:(q=(L=this.localPeer)===null||L===void 0?void 0:L.getUserId())===null||q===void 0?void 0:q.getValue(),localPeerId:"lan_client",remotePeerId:Z}},ce=>this.onCustomDataChannel(Z,ce)),ue=yield se.getLanOffer();if(!ue)return U.a.warn("Could not generate LAN offer"),!1;const fe=yield ie.postLanRtcOffer({offer:JSON.stringify(ue)}),Ue=new RTCSessionDescription(JSON.parse(fe.answer));return yield se.handleLanAnswer(Ue),this.localConnections.push(se),this.isConnectionInitiator.add(se),Object(D.a)()})}getConnections(){return[...this.connections,...this.localConnections]}createCustomDataChannel(Z,L,q,ie,se){const ue=this.getActiveConnection(Z);if(ue&&this.isConnectionInitiator.has(ue)){const Ue=ue.peerConnection.createDataChannel("custom."+L,q);return ie&&(Ue.binaryType="arraybuffer"),se(Z,Ue),()=>{}}const fe=(Ue,ce)=>{Z===Ue&&ce.label==="custom."+L&&se(Z,ce)};return this.peerDataChannelListeners.push(fe),()=>{this.peerDataChannelListeners=this.peerDataChannelListeners.filter(Ue=>Ue!==fe)}}onCustomDataChannel(Z,L){this.peerDataChannelListeners.forEach(q=>q(Z,L))}getConnectionStatus(Z){if(this.isOutgoingConnection.has(Z))return"connecting";const L=this.getActiveConnection(Z);return L?L.isReady()?"connected":"connecting":"disconnected"}getConnectionStatsInfo(Z){return De(this,void 0,void 0,function*(){const L=this.getActiveConnection(Z);if(L)return yield L.getConnectionStatsInfo()})}disconnect(Z){return De(this,void 0,void 0,function*(){const L=this.getActiveConnection(Z);L&&(yield L.close(),this.connections=this.connections.filter(q=>q!==L),this.localConnections=this.localConnections.filter(q=>q!==L))})}getPeers(){return De(this,void 0,void 0,function*(){if(this.config.lanOnlyMode)throw new Error("getPeers method cannot be used in local-only mode.");const{signalingClient:Z}=this.config,L=yield(()=>De(this,void 0,void 0,function*(){try{return yield Y.withDeadline(Z.getPeers(new G.GetPeersRequest,yield this.getMetadata()),this.grpcCallDeadline)}catch(se){U.a.warn("Error when getting peers",{error:se})}}))();if(!L)return[];const q=L.getPeersList();if(!q)return[];const ie=se=>{var ue,fe;return(fe=(ue=se.getPeerCreatedTimestamp())===null||ue===void 0?void 0:ue.getValue())!==null&&fe!==void 0?fe:0};return q.sort((se,ue)=>ie(ue)-ie(se)).map(se=>ut(se))})}getSessions(){return De(this,void 0,void 0,function*(){if(this.config.lanOnlyMode)throw new Error("getPeers method cannot be used in local-only mode.");const{signalingClient:Z}=this.config,L=yield(()=>De(this,void 0,void 0,function*(){try{return yield Y.withDeadline(Z.getPeers(new G.GetPeersRequest,yield this.getMetadata()),this.grpcCallDeadline)}catch(se){U.a.warn("Error when getting peers",{error:se})}}))();if(!L)return{};const q=L.getPeersList(),ie={};for(const se of q)ie[se.getPeerId()]=se.getSessionIdsList();return ie})}getPing(Z){const L=this.getActiveConnection(Z);if(L)return L.getPing();U.a.warn("Attempted to get ping time from inactive peer.")}getPingInfo(Z){const L=this.getActiveConnection(Z);if(L)return L.getPingInfo();U.a.warn("Attempted to get ping time from inactive peer.")}getLastMessageTimestamp(Z){const L=this.getActiveConnection(Z);if(L)return L.getLastMessageTimestamp();U.a.warn("Attempted to get last message time from inactive peer.")}getSessionMetricsMessageCounts(Z){const L=this.getActiveConnection(Z);if(L)return L.getSessionMetricsMessageCounts();U.a.warn("Attempted to get session metrics counts from inactive peer.")}isReady(){if(this.config.lanOnlyMode)return!0;const{localPeer:Z,receiveSignalStream:L,iceServers:q}=this;return!!(Z&&L&&q)}shutdown(){return De(this,void 0,void 0,function*(){yield this.refreshInterval.stop(),this.receiveSignalStream&&this.receiveSignalStream.cancel();const Z=this.connections;this.connections=[],yield this.closeConnections(Z);const L=this.localConnections;this.localConnections=[],yield this.closeConnections(L),this.isOutgoingConnection.clear(),this.peerDataChannelListeners=[];const{localPeer:q}=this;if(!q||this.config.lanOnlyMode)return;const{signalingClient:ie}=this.config;yield(()=>De(this,void 0,void 0,function*(){try{const se=new G.DeletePeerRequest;se.setPeerId(q.getPeerId()),yield Y.withDeadline(ie.deletePeer(se,yield this.getMetadata()),this.grpcCallDeadline)}catch(se){return void U.a.warn("Error deleting local peer",{error:se})}}))()})}createPeer(){return De(this,void 0,void 0,function*(){if(this.config.lanOnlyMode)throw new Error("createPeer method cannot be used in local-only mode.");const{signalingClient:Z}=this.config,L=yield(()=>De(this,void 0,void 0,function*(){try{return yield Y.withDeadline(Z.createPeer(new G.CreatePeerRequest,yield this.getMetadata()),this.grpcCallDeadline)}catch(ie){const se=ie;U.a.debug("createPeer failed",{error:se});const ue=Ot(se);throw new Error("Was not able to create peer: "+ue)}}))(),q=L==null?void 0:L.getPeer();if(!q)throw new Error("Response did not provide peer.");return this.localPeer=q})}createReceiveSignalStream(){return De(this,void 0,void 0,function*(){if(this.config.lanOnlyMode)throw new Error("createReceiveSignalStream method cannot be used in local-only mode.");const{signalingClient:Z}=this.config,{localPeer:L,iceServers:q}=this;if(!L||!q)return;const{receiveSignalStream:ie}=this;ie&&ie.cancel();const se=new G.ReceiveSignalStreamRequest;se.setPeerId(L.getPeerId());const ue=yield(()=>De(this,void 0,void 0,function*(){try{return Z.receiveSignalStream(se,yield this.getMetadata({hasDeadline:!1}))}catch(fe){U.a.debug("createReceiveSignalStream failed",{error:fe});const Ue=Ot(fe);throw new Error("Unable to create receive signal stream: "+Ue)}}))();if(!ue)throw new Error("Response did not provide stream.");return ue.on("data",fe=>De(this,void 0,void 0,function*(){var Ue,ce,le,me;const Ve=fe.getSignal(),Ce=(Ue=Ve==null?void 0:Ve.getSessionId())===null||Ue===void 0?void 0:Ue.getValue(),xe=Ve==null?void 0:Ve.getSenderId(),He=Ve==null?void 0:Ve.getReceiverId(),Ye=(ce=Ve==null?void 0:Ve.getSessionCreatedTimestamp())===null||ce===void 0?void 0:ce.getValue();if(!(Ve&&Ce&&xe&&He&&Ye))return void U.a.warn("Received signal with missing information.");const qe=this.getActiveConnection(xe);if(qe)if(qe.getSessionId()!==Ce){if(U.a.debug("Received signal: different session for a peer we're already connected to."),(qe.getSessionCreatedTimestamp()||0)>Ye)return;const Pe=new Tt(yield this.createRTCPeerConnection(q),q,{baseConfig:{isOffer:!1,isLan:!1,receive:(Me,Le)=>this.config.receive(Me,Le),onStreamsInfoUpdate:this.config.onStreamsInfoUpdate?(Me,Le)=>{var Ge,Ke;return(Ke=(Ge=this.config).onStreamsInfoUpdate)===null||Ke===void 0?void 0:Ke.call(Ge,Me,Le)}:void 0,track:this.config.lanOnlyMode?void 0:this.config.track,localPeerId:L.getPeerId(),localUserId:(me=L.getUserId())===null||me===void 0?void 0:me.getValue(),remotePeerId:xe},remoteConfig:{sessionId:Ce,sessionCreatedTimestamp:Ye}},Me=>this.onCustomDataChannel(xe,Me));yield Pe.handleSignal(Ve),this.connections.push(Pe)}else U.a.debug("Received signal: for an existing connection."),yield qe.handleSignal(Ve);else{U.a.debug("Received signal: new connection.");const Pe=new Tt(yield this.createRTCPeerConnection(q),q,{baseConfig:{isOffer:!1,isLan:!1,receive:(Me,Le)=>this.config.receive(Me,Le),onStreamsInfoUpdate:this.config.onStreamsInfoUpdate?(Me,Le)=>{var Ge,Ke;return(Ke=(Ge=this.config).onStreamsInfoUpdate)===null||Ke===void 0?void 0:Ke.call(Ge,Me,Le)}:void 0,track:this.config.lanOnlyMode?void 0:this.config.track,localPeerId:L.getPeerId(),localUserId:(le=L.getUserId())===null||le===void 0?void 0:le.getValue(),remotePeerId:xe},remoteConfig:{sessionId:Ce,sessionCreatedTimestamp:Ye}},Me=>this.onCustomDataChannel(xe,Me));yield Pe.handleSignal(Ve),this.connections.push(Pe)}})),ue.on("end",()=>{ue.cancel(),this.receiveSignalStream=void 0}),ue.on("error",fe=>{switch(fe.code){case v.StatusCode.CANCELLED:case v.StatusCode.UNAVAILABLE:case v.StatusCode.UNKNOWN:U.a.debug("Receive signal stream error",{error:fe});break;case v.StatusCode.UNAUTHENTICATED:U.a.warn("Receive signal stream error",{error:fe});break;default:U.a.error("Receive signal stream error",{error:fe})}ue.cancel(),this.receiveSignalStream=void 0}),this.receiveSignalStream=ue})}createRTCPeerConnection(Z){var L;return De(this,void 0,void 0,function*(){const q=(L=this.config.alternateRTCPeerConnection)!==null&&L!==void 0?L:window.RTCPeerConnection;if(!q)throw function(){if(typeof navigator=="undefined")throw new Error("not a browser");const{userAgent:ie}=navigator;return ie.includes("Firefox/")?"Firefox":ie.includes("Edg/")?"Edge":ie.includes("Chrome/")?"Chrome":ie.includes("Safari/")?"Safari":ie.includes("MSIE/")||ie.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||vt();try{return new q({iceServers:Z})}catch(ie){throw U.a.debug(`Failed to create RTCPeerConnection: ${this.rtcInstancesConstructed} total allocated`),ie}})}closeConnections(Z){return De(this,void 0,void 0,function*(){const L=yield $(Z.map(q=>De(this,void 0,void 0,function*(){yield q.close()})));for(const q of L)U.a.warn("Request to close session failed",{error:q})})}getActiveConnection(Z){return this.getConnections().find(L=>L.getRemotePeerId()===Z&&L.isActive())}update(){var Z;return De(this,void 0,void 0,function*(){if(this.localConnections=this.localConnections.filter(me=>me.isActive()),this.config.lanOnlyMode)return;const{signalingClient:L}=this.config;if(!this.localPeer||!this.receiveSignalStream||!this.iceServers){const me=[];return this.localPeer||me.push(this.createPeer()),this.iceServers||me.push(this.updateIceServers()),yield Promise.all(me),void(this.receiveSignalStream||(yield this.createReceiveSignalStream()))}const[q,ie]=(se=this.connections,ue=me=>me.isActive(),se.reduce((me,Ve,Ce,xe)=>{const[He,Ye]=me;return(ue(Ve,Ce,xe)?He:Ye).push(Ve),me},[[],[]]));var se,ue;yield this.closeConnections(ie),this.connections=q,this.gatherConnectionStats().catch(me=>{U.a.warn("Error calling gatherConnectionStats",{error:me})}),this.statsLoopsExecuted++;const{localPeer:fe}=this,Ue=this.connections.filter(me=>me.getSessionId).map(me=>O(me.getSessionId()));fe.setSessionIdsList(Ue);const ce=new G.RefreshPeerRequest;ce.setPeer(fe);try{yield Y.withDeadline(L.refreshPeer(ce,yield this.getMetadata()),this.grpcCallDeadline)}catch(me){me instanceof v.RpcError&&me.code===v.StatusCode.NOT_FOUND?(U.a.warn("Peer expired, creating new peer",{peerId:fe.getPeerId()}),yield this.reset()):U.a.warn("Error calling RefreshPeer",{error:me})}const le=yield this.getPeers();for(const me of this.connections)me.setRemoteDeviceId((Z=le.find(Ve=>Ve.id===me.getRemotePeerId()))===null||Z===void 0?void 0:Z.deviceId)})}gatherConnectionStats(){return De(this,void 0,void 0,function*(){if(this.statsLoopsExecuted%10!=0||this.connections.length!==1)return;const Z=yield this.connections[0].getConnectionStatsInfo(),L=Z?bt(Z):void 0;L?x.setTag("rtc-connection-type",L):x.setTag("rtc-connection-type","unknown")})}reset(){return De(this,void 0,void 0,function*(){yield this.closeConnections(this.connections),this.connections=[],this.isOutgoingConnection.clear(),yield this.createPeer(),yield this.createReceiveSignalStream()})}updateIceServers(){return De(this,void 0,void 0,function*(){if(this.config.lanOnlyMode)return;const{iceServersLastUpdate:Z,iceServersTtl:L}=this,q=new Date().getTime();if(!Z||q-Z>L)try{const ie=(yield Y.withDeadline(this.config.signalingClient.getIceServers(new G.GetIceServersRequest,yield this.getMetadata()),this.grpcCallDeadline)).getIceServers();this.iceServers=JSON.parse(ie),this.iceServersLastUpdate=q}catch(ie){U.a.warn("Error in updateIceServers",{error:ie})}})}setupHandlers(Z){const{peerConnection:L}=Z,q=Z.getSessionCreatedTimestamp();L.onconnectionstatechange=()=>De(this,void 0,void 0,function*(){const ie=L.connectionState;if(!q)return;const se=Z.getRemoteDeviceId();switch(ie){case"connected":x.aggregate("rtc-connect-time",new Date().getTime()-q,Object.assign({},se?{deviceId:se}:{}));break;case"failed":x.increment("rtc-connect-failed",Object.assign({},se?{deviceId:se}:{}))}})}getMetadata(Z={}){return De(this,void 0,void 0,function*(){if(this.config.lanOnlyMode)throw new Error("getMetadata method cannot be called in local-only mode");const{getToken:L}=this.config,{grpcCallDeadline:q}=this,{hasDeadline:ie=!0}=Z,se=ie?{deadline:(Date.now()+q).toString(10)}:null;try{const ue=yield L();return Object.assign({authorization:ue},se)}catch(ue){throw U.a.error("getToken() failed",{error:ue}),new Error("Cannot get authorization token")}})}}var tt=n(12),Ut=n(11),xt=function(Re,Z,L,q){return new(L||(L=Promise))(function(ie,se){function ue(ce){try{Ue(q.next(ce))}catch(le){se(le)}}function fe(ce){try{Ue(q.throw(ce))}catch(le){se(le)}}function Ue(ce){var le;ce.done?ie(ce.value):(le=ce.value,le instanceof L?le:new L(function(me){me(le)})).then(ue,fe)}Ue((q=q.apply(Re,Z||[])).next())})};class Jt{constructor(Z,L){this.sentMessagesCounts=new Map,this.receivedMessagesCounts=new Map,this.sessionId=Z,this.connection=L}incrementMessageSent(Z){const L=Oe(Z.header.stream);this.sentMessagesCounts.set(L,(this.sentMessagesCounts.get(L)||0)+1)}incrementMessageReceived(Z){const L=Oe(Z.header.stream);this.receivedMessagesCounts.set(L,(this.receivedMessagesCounts.get(L)||0)+1)}uploadMetrics(){return xt(this,void 0,void 0,function*(){const{sessionId:Z}=this,L=yield this.connection.peerConnection.getStats(),q={};L.forEach(se=>q[se.id]=se),U.a.debug("rtc-stats",Object.assign(Object.assign({},q),{sessionId:Z}));const ie=[...new Set(Array.from(this.sentMessagesCounts.keys()).concat(Array.from(this.receivedMessagesCounts.keys())))].reduce((se,ue)=>{const fe=this.sentMessagesCounts.get(ue),Ue=this.receivedMessagesCounts.get(ue);return Object.assign(Object.assign({},se),{[ue+"-sent"]:fe,[ue+"-received"]:Ue})},{sessionId:Z});U.a.debug("rtc-message-report",ie)})}}function ft(Re,Z){return Oe(Re)===Oe(Z)}var nt=function(Re,Z,L,q){return new(L||(L=Promise))(function(ie,se){function ue(ce){try{Ue(q.next(ce))}catch(le){se(le)}}function fe(ce){try{Ue(q.throw(ce))}catch(le){se(le)}}function Ue(ce){var le;ce.done?ie(ce.value):(le=ce.value,le instanceof L?le:new L(function(me){me(le)})).then(ue,fe)}Ue((q=q.apply(Re,Z||[])).next())})};class Wt{constructor(Z,L){this.peerConnection=Z,this.config=L,this.connectTimeoutMs=10*u.a.second,this.gatherIceTimeoutMs=5*u.a.second,this.pingUpdateTimeoutMs=2*u.a.second,this.streamLatestTimestamp=new Map,this.closeCalled=!1,this.connectCalled=!1,this.sentOffer=!1,this.receivedIceCandidate=!1;const{isOffer:q}=L;q?this.initializeChannels(Z):Z.ondatachannel=ie=>{switch(ie.channel.label){case"stream.latest-ttl":this.latestTtlStreamChannel=ie.channel;break;case"stream.reliable":this.reliableStreamChannel=ie.channel;break;case"stream.latest-reliable":this.latestReliableStreamChannel=ie.channel;break;case"stream.latest-try-once":this.latestTryOnceStreamChannel=ie.channel}this.setupChannel(ie.channel)},this.sessionMetrics=new Jt(this.getSessionId(),this)}connect(){return nt(this,void 0,void 0,function*(){if(this.connectCalled)return;this.connectCalled=!0,this.pingUpdateTimeout=setInterval(()=>{const{reliableStreamChannel:ie}=this;ie&&this.sendSystemMessage(ie,{type:"ping"})},this.pingUpdateTimeoutMs),this.connectTimeout=setTimeout(()=>nt(this,void 0,void 0,function*(){this.isReady()||(U.a.warn("RTC connect timed out, closing connection"),yield this.close())}),this.connectTimeoutMs);const{peerConnection:Z,config:{isOffer:L,sessionId:q}}=this;if(L){const ie=yield Z.createOffer();yield Z.setLocalDescription(ie)}L&&(this.gatherIceTimeout=setTimeout(()=>nt(this,void 0,void 0,function*(){this.sentOffer||(U.a.warn("ICE gathering timed out"),this.receivedIceCandidate?(U.a.warn("Attempting to connect with partial ICE candidate pool"),yield this.sendOffer()):yield this.close())}),this.gatherIceTimeoutMs),Z.onicecandidate=ie=>nt(this,void 0,void 0,function*(){ie.candidate?this.receivedIceCandidate=!0:yield this.sendOffer()}),Z.onicegatheringstatechange=()=>nt(this,void 0,void 0,function*(){Z.iceGatheringState==="complete"&&(yield this.sendOffer())}),Z.onnegotiationneeded=()=>{U.a.debug("Negotiation needed",{sessionId:q})})})}handleSignal(Z){return nt(this,void 0,void 0,function*(){const{peerConnection:L,config:{sessionId:q,sendSignal:ie}}=this,{description:se}=JSON.parse(Z.payload);if(U.a.debug("Handling signal",{sessionId:q,description:JSON.stringify(se)}),se)if(L.signalingState!=="stable"||L.connectionState!=="connected")if(L.remoteDescription)U.a.warn("Received SDP signal during negotiation when remote description is already set: "+JSON.stringify(Z));else if(se.type==="offer"){yield L.setRemoteDescription(se);const ue=yield L.createAnswer();yield L.setLocalDescription(ue),yield ie({payload:JSON.stringify({description:ue})})}else se.type==="answer"&&(yield L.setRemoteDescription(se));else U.a.warn("Received SDP signal when signaling is stable and connected: "+JSON.stringify(Z));else U.a.warn("Received non-SDP signal: "+JSON.stringify(Z))})}send(Z,L){const q=this.getChannelFromLabel(L.channelLabel);q?this.sendOnChannel(q,Z):U.a.warn("Send called with unexpected channel label",{channelLabel:L.channelLabel})}controlRemoteStream(Z){this.sendSystemMessage(O(this.reliableStreamChannel),{type:"stream-control",streamControl:Z})}isActive(){return new Set(["new","connecting","connected"]).has(this.peerConnection.connectionState)}isReady(){const{peerConnection:Z,latestTtlStreamChannel:L,reliableStreamChannel:q,latestTryOnceStreamChannel:ie}=this;return!!(q&&L&&ie)&&Z.connectionState==="connected"&&q.readyState==="open"&&L.readyState==="open"&&ie.readyState==="open"}isClosed(){const{peerConnection:Z,reliableStreamChannel:L,latestTryOnceStreamChannel:q,latestTtlStreamChannel:ie}=this;return!(Z.connectionState!=="closed"||L!==void 0&&L.readyState!=="closed"||q!==void 0&&q.readyState!=="closed"||ie!==void 0&&ie.readyState!=="closed")}needsClosing(){const{peerConnection:Z,latestTtlStreamChannel:L,reliableStreamChannel:q,latestTryOnceStreamChannel:ie}=this;if(this.isClosed())return!1;const se=new Set(["closing","closed"]),ue=fe=>fe&&se.has(fe.readyState);return gt(Z)||ue(L)||ue(q)||ue(ie)}close(){return nt(this,void 0,void 0,function*(){this.closeCalled||(this.closeCalled=!0,yield this.sessionMetrics.uploadMetrics(),this.pingUpdateTimeout&&clearInterval(this.pingUpdateTimeout),this.connectTimeout&&clearTimeout(this.connectTimeout),this.gatherIceTimeout&&clearTimeout(this.gatherIceTimeout),this.peerConnection.close())})}getPing(){return this.pingTimeMs}getLastMessageTimestamp(){return this.lastMessageTimestamp}getSessionId(){return this.config.sessionId}getRemotePeer(){return this.config.remotePeer}initializeChannels(Z){this.latestTtlStreamChannel=Z.createDataChannel("stream.latest-ttl",oe),this.reliableStreamChannel=Z.createDataChannel("stream.reliable",ge),this.latestReliableStreamChannel=Z.createDataChannel("stream.latest-reliable",Se),this.latestTryOnceStreamChannel=Z.createDataChannel("stream.latest-try-once",ve),this.setupChannel(this.latestTtlStreamChannel),this.setupChannel(this.reliableStreamChannel),this.setupChannel(this.latestReliableStreamChannel),this.setupChannel(this.latestTryOnceStreamChannel)}sendOffer(){return nt(this,void 0,void 0,function*(){if(this.sentOffer||(this.sentOffer=!0,gt(this.peerConnection)))return;const{peerConnection:Z,config:{sendSignal:L}}=this,q=yield Z.createOffer();yield Z.setLocalDescription(q);const ie={payload:JSON.stringify({description:q})};yield L(ie)})}getChannelFromLabel(Z){switch(Z){case"stream.latest-ttl":return this.latestTtlStreamChannel;case"stream.reliable":return this.reliableStreamChannel;case"stream.latest-reliable":return this.latestReliableStreamChannel;case"stream.latest-try-once":return this.latestTryOnceStreamChannel}}sendOnChannel(Z,L){let q;try{q=Object(te.encode)(JSON.stringify(L))}catch(ie){return void U.a.warn("Failed to encode RTC message",{error:ie})}try{Z.send(q),this.sessionMetrics.incrementMessageSent(L)}catch(ie){U.a.warn("Failed to send message to channel",{error:ie,channel:Z.label})}}channelNotRecognized(Z){return Z!==this.latestTtlStreamChannel&&Z!==this.latestReliableStreamChannel&&Z!==this.latestTryOnceStreamChannel&&Z!==this.reliableStreamChannel}setupChannel(Z){Z.onmessage=L=>{if(this.channelNotRecognized(Z))return void U.a.warn("Received message on unrecognized data channel.");let q;try{q=JSON.parse(Object(te.decode)(L.data))}catch(ie){return void U.a.warn("Received unparseable RTC message",{error:ie,channel:Z.label})}if(this.lastMessageTimestamp=new Date().getTime(),q=Et(q),this.sessionMetrics.incrementMessageReceived(q),!this.handleSystemMessage(Z,q)){if(!this.hasCapabilities(q))return void U.a.warn("Received RTC message that was not within the capability scope of the connection.");(Z===this.latestTryOnceStreamChannel||Z===this.latestTtlStreamChannel||Z===this.latestReliableStreamChannel)&&!this.isLatestMessage(q)||this.config.receive(this.config.remotePeer.id,q)}},Z.onerror=L=>{U.a.warn("Channel error: "+L.error,{error:L.error,sessionId:this.getSessionId(),channelLabel:Z.label})},Z.onopen=()=>{U.a.debug("Channel opened",{sessionId:this.getSessionId(),channelLabel:Z.label})},Z.onclose=()=>{const L={bufferedAmount:Z.bufferedAmount,sessionId:this.getSessionId(),channelLabel:Z.label};this.closeCalled===!1?U.a.debug("Unexpected channel closed",L):U.a.debug("Channel closed",L)}}handleSystemMessage(Z,L){switch(L.header.stream.streamType){case"ping":return this.sendSystemMessage(Z,{type:"pong",timestamp:O(L.payload.ping)}),!0;case"pong":{const q=new Date().getTime()-O(L.payload.pong);return this.pingTimeMs=q,x.aggregate("rtc-ping-time",q),!0}case"stream-control":return!0;default:return!1}}sendSystemMessage(Z,L){if(Z.readyState!=="open")return;const q={entityId:O(this.config.localPeer.deviceId||this.config.localPeer.userId),streamName:"$."+L.type,streamType:L.type};let ie;switch(L.type){case"ping":ie={ping:new Date().getTime()};break;case"pong":ie={pong:L.timestamp};break;case"stream-control":ie={streamControl:L.streamControl}}this.sendOnChannel(Z,wt(q,ie))}hasCapabilities(Z){var L,q;const{localPeer:ie,remotePeer:se}=this.config,ue=(L=ie.capabilitySet.streaming)===null||L===void 0?void 0:L.streams,fe=ue&&ue.some(le=>le.receive&&ft(le.stream,Z.header.stream)),Ue=(q=se.capabilitySet.streaming)===null||q===void 0?void 0:q.streams,ce=Ue&&Ue.some(le=>le.send&&ft(le.stream,Z.header.stream));return fe||ce}isLatestMessage(Z){const L=Oe(Z.header.stream),q=(this.streamLatestTimestamp.get(L)||0)<=Z.header.created;return q&&this.streamLatestTimestamp.set(L,Z.header.created),q}}var Ae=function(Re,Z,L,q){return new(L||(L=Promise))(function(ie,se){function ue(ce){try{Ue(q.next(ce))}catch(le){se(le)}}function fe(ce){try{Ue(q.throw(ce))}catch(le){se(le)}}function Ue(ce){var le;ce.done?ie(ce.value):(le=ce.value,le instanceof L?le:new L(function(me){me(le)})).then(ue,fe)}Ue((q=q.apply(Re,Z||[])).next())})};class Ct{constructor(Z){this.config=Z,this.connections=[],this.connectingSessions=new Map,this.rtcInstancesConstructed=0,this.updateInterval=T({func:()=>Ae(this,void 0,void 0,function*(){try{yield this.update()}catch(L){U.a.warn("RTC update failed",{error:L})}}),delay:250*u.a.millisecond,immediate:!0}),this.localPeer=this.createPeer()}send(Z,L,q){const ie=this.getActiveConnection(Z);ie?ie.isReady()?ie.send(L,q):U.a.warn("Attempted to send with an active connection to that peer which was not yet ready."):U.a.warn("Attempted to send with no active connection to that peer.")}controlRemoteStream(Z,L){const q=this.getActiveConnection(Z);q?q.isReady()?q.controlRemoteStream(L):U.a.warn("Attempted to control remote stream with an active connection to that peer which was not yet ready."):U.a.warn("Attempted to control remote stream with no active connection to that peer.")}connect(Z){return Ae(this,void 0,void 0,function*(){const L=yield this.getLocalPeer();if(this.getActiveConnection(Z))return void U.a.warn("Attempted to connect to peer with an already active connection.");let q;try{q=yield this.config.signalingClient.createSession(yield this.config.getToken(),{offerPeerId:L.id,answerPeerId:Z})}catch(ie){Object(tt.a)(ie,Ut.a,se=>se.statusCode===404),U.a.warn("Attempted to connect to peer that does not exist.")}if(q)for(this.connectingSessions.set(q.id,new Date().getTime()),yield this.connectToSession(q);;)switch(yield Object(c.a)(.1),this.getConnectionStatus(Z)){case"connecting":continue;case"connected":return q.id;case"disconnected":return}})}getConnectionStatus(Z){const L=this.getActiveConnection(Z);return L?L.isReady()?"connected":"connecting":"disconnected"}getIceMode(Z){const L=this.getActiveConnection(Z);if(L)return L.iceMode}disconnect(Z){return Ae(this,void 0,void 0,function*(){const L=this.getActiveConnection(Z);L&&(yield this.closeConnection(L))})}getLocalPeer(){return Ae(this,void 0,void 0,function*(){return yield this.localPeer})}getPeers(){return Ae(this,void 0,void 0,function*(){return yield this.config.signalingClient.getPeers(yield this.config.getToken())})}getPing(Z){const L=this.getActiveConnection(Z);if(L)return L.getPing();U.a.warn("Attempted to get ping time from inactive peer.")}getLastMessageTimestamp(Z){const L=this.getActiveConnection(Z);if(L)return L.getLastMessageTimestamp();U.a.warn("Attempted to get ping time from inactive peer.")}shutdown(){return Ae(this,void 0,void 0,function*(){yield this.updateInterval.stop();const Z=this.connections;this.connections=[],yield this.closeConnections(Z)})}closeConnection(Z){return Ae(this,void 0,void 0,function*(){this.connectingSessions.delete(Z.getSessionId()),yield Z.close();try{yield this.config.signalingClient.deleteSession(yield this.config.getToken(),Z.getSessionId())}catch(L){Object(tt.a)(L,Ut.a,q=>q.statusCode===404)}})}getSessions(){return Ae(this,void 0,void 0,function*(){const Z=yield this.getLocalPeer();return(yield this.config.signalingClient.getSessions(yield this.config.getToken())).filter(L=>L.offer.peer.id===Z.id||L.answer.peer.id===Z.id)})}createPeer(){return Ae(this,void 0,void 0,function*(){return yield this.config.signalingClient.createPeer(yield this.config.getToken(),{capabilitySet:this.config.capabilitySet||{}})})}createRTCPeerConnection(Z={}){return Ae(this,void 0,void 0,function*(){const L=this.config.alternateRTCPeerConnection||RTCPeerConnection;this.rtcInstancesConstructed++,this.rtcInstancesConstructed%20||vt();try{return new L(Object.assign({iceServers:yield this.config.signalingClient.getIceServers(yield this.config.getToken())},Z))}catch(q){throw U.a.debug(`Failed to create RTCPeerConnection: ${this.rtcInstancesConstructed} total allocated`),q}})}closeConnections(Z){return Ae(this,void 0,void 0,function*(){const L=yield $(Z.map(q=>Ae(this,void 0,void 0,function*(){yield this.closeConnection(q)})));for(const q of L)U.a.warn("Request to close session failed",{error:q})})}reset(){return Ae(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(Z){return this.connections.find(L=>L.getRemotePeer().id===Z&&L.isActive())}update(){return Ae(this,void 0,void 0,function*(){const Z=yield this.getLocalPeer();try{yield this.config.signalingClient.refreshPeer(yield this.config.getToken(),Z.id)}catch(L){Object(tt.a)(L,Ut.a,q=>q.statusCode===404),U.a.warn("Peer expired, creating new peer",{peerId:Z.id}),yield this.reset()}yield this.handleSessions(yield this.getSessions())})}handleSessions(Z){return Ae(this,void 0,void 0,function*(){yield this.syncConnectionsAndSessions(Z);const L=Z.map(q=>({session:q,connection:this.connections.find(ie=>ie.getSessionId()===q.id)}));yield Promise.all(L.map(({session:q,connection:ie})=>Ae(this,void 0,void 0,function*(){return yield this.maintainConnection(q,ie)})))})}syncConnectionsAndSessions(Z){return Ae(this,void 0,void 0,function*(){const L=new Set(Z.map(se=>se.id)),q=se=>L.has(se.getSessionId())||this.connectingSessions.has(se.getSessionId());this.connections=this.connections.filter(se=>q(se));const ie=this.connections.filter(se=>!q(se)||se.needsClosing());yield Promise.all(ie.map(se=>Ae(this,void 0,void 0,function*(){yield this.closeConnection(se)})))})}maintainConnection(Z,L){return Ae(this,void 0,void 0,function*(){const q=yield this.getLocalPeer(),ie=Z.offer.peer.id===q.id;if(L){if(L.isReady())try{yield this.config.signalingClient.refreshSession(yield this.config.getToken(),Z.id)}catch(se){Object(tt.a)(se,Ut.a,ue=>ue.statusCode===404),U.a.debug("Refresh session not found",{sessionId:Z.id})}else if(L.isActive())try{yield this.consumeSignals(L)}catch(se){U.a.warn("Failed to ingest signals, closing connection",{error:se}),yield this.closeConnection(L)}}else{if(ie)return;yield this.connectToSession(Z)}})}connectToSession(Z){return Ae(this,void 0,void 0,function*(){const L=yield this.getLocalPeer(),q=Z.offer.peer.id===L.id,ie=yield this.createRTCPeerConnection(),se=new Wt(ie,{localPeer:q?Z.offer.peer:Z.answer.peer,remotePeer:q?Z.answer.peer:Z.offer.peer,sessionId:Z.id,isOffer:q,sendSignal:ue=>this.sendSignal(Z.id,ue),receive:(ue,fe)=>this.config.receive(ue,fe)});if(this.connections.find(ue=>ue.getSessionId()===Z.id))return U.a.warn("connectToSession called on a session that already has a connection.",{sessionId:Z.id}),void(yield se.close());this.setupHandlers(se),this.connections.push(se);try{yield se.connect()}catch(ue){U.a.warn("Failed to handle negotiation, closing connection",{error:ue}),yield this.closeConnection(se)}})}setupHandlers(Z){const{peerConnection:L}=Z,q=Z.getSessionId();L.onconnectionstatechange=()=>Ae(this,void 0,void 0,function*(){const ie=this.connectingSessions.get(q);if(ie===void 0)return;const se=L.connectionState;switch(gt(L)&&this.connectingSessions.delete(q),se){case"connected":{this.connectingSessions.delete(q);const ue=new Date().getTime()-ie;x.aggregate("rtc-connect-time",ue);break}case"failed":x.increment("rtc-connect-failed"),yield this.closeConnection(Z)}})}consumeSignals(Z){return Ae(this,void 0,void 0,function*(){let L=[];try{L=yield this.config.signalingClient.takeSignals(yield this.config.getToken(),Z.getSessionId())}catch(q){Object(tt.a)(q,Ut.a,ie=>ie.statusCode===404)}for(const q of L)yield Z.handleSignal(q)})}sendSignal(Z,L){return Ae(this,void 0,void 0,function*(){try{yield this.config.signalingClient.addSignals(yield this.config.getToken(),Z,{signals:[L]})}catch(q){Object(tt.a)(q,Ut.a,ie=>ie.statusCode===404)}})}}},,function(e,t,n){n.r(t),n.d(t,"LogClient",function(){return l});var r=n(26),o=n(12),s=n(11),g=function(u,c,d,B){return new(d||(d=Promise))(function(Q,f){function p(M){try{E(B.next(M))}catch(W){f(W)}}function U(M){try{E(B.throw(M))}catch(W){f(W)}}function E(M){var W;M.done?Q(M.value):(W=M.value,W instanceof d?W:new d(function(y){y(W)})).then(p,U)}E((B=B.apply(u,c||[])).next())})};class l extends r.a{log(c){return g(this,void 0,void 0,function*(){const d=l.token;try{yield this.fetch("logs",{token:d,method:"POST",body:{logs:c},allowUnsafeRetries:!0})}catch(B){Object(o.a)(B,s.a,Q=>Q.statusCode===401&&d!==void 0),l.token===d&&delete l.token,yield this.log(c)}})}}},function(e,t,n){var r={randomUUID:typeof crypto!="undefined"&&crypto.randomUUID&&crypto.randomUUID.bind(crypto)};let o;const s=new Uint8Array(16);function g(){if(!o&&(o=typeof crypto!="undefined"&&crypto.getRandomValues&&crypto.getRandomValues.bind(crypto),!o))throw new Error("crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported");return o(s)}const l=[];for(let c=0;c<256;++c)l.push((c+256).toString(16).slice(1));function u(c,d=0){return(l[c[d+0]]+l[c[d+1]]+l[c[d+2]]+l[c[d+3]]+"-"+l[c[d+4]]+l[c[d+5]]+"-"+l[c[d+6]]+l[c[d+7]]+"-"+l[c[d+8]]+l[c[d+9]]+"-"+l[c[d+10]]+l[c[d+11]]+l[c[d+12]]+l[c[d+13]]+l[c[d+14]]+l[c[d+15]]).toLowerCase()}t.a=function(c,d,B){if(r.randomUUID&&!d&&!c)return r.randomUUID();const Q=(c=c||{}).random||(c.rng||g)();if(Q[6]=15&Q[6]|64,Q[8]=63&Q[8]|128,d){B=B||0;for(let f=0;f<16;++f)d[B+f]=Q[f];return d}return u(Q)}}])})})(dist);var distExports=dist.exports;const SessionTypes={UNKNOWN:0,TELEOP:1,PORT_FORWARD:2,OBSERVE:3,HEADLESS:4},SessionTypeConstants={...SessionTypes,Unknown:SessionTypes.UNKNOWN,Teleop:SessionTypes.TELEOP,PortForward:SessionTypes.PORT_FORWARD,Observe:SessionTypes.OBSERVE,Headless:SessionTypes.HEADLESS,unknown:SessionTypes.UNKNOWN,teleop:SessionTypes.TELEOP,portForward:SessionTypes.PORT_FORWARD,observe:SessionTypes.OBSERVE,headless:SessionTypes.HEADLESS},singleton=Symbol("RtcClientPool.instance");var Sn;class RtcClientPool{constructor(t){he(this,Sn,null);he(this,"createClient");he(this,"ttlMs");he(this,"proxyHandler");he(this,"proxyReceivers",new Map);he(this,"teardownTimeout",null);he(this,"dispatch",(t,n)=>{this.proxyReceivers.forEach(r=>r==null?void 0:r(t,n))});const{createClient:n,ttlMs:r=0}=t;this.createClient=n,this.ttlMs=Math.max(r,0),this.proxyHandler={get:(o,s,g)=>{switch(s){case"shutdown":return()=>this.releaseInstance(g);default:return Reflect.get(o,s,g)}}}}get isActive(){return this[singleton]!==null}get size(){return this.proxyReceivers.size}get(t){const n=new Proxy(this.allocate(),this.proxyHandler);return this.proxyReceivers.set(n,t!=null?t:null),n}allocate(){if(this[singleton])return this.teardownTimeout&&(clearTimeout(this.teardownTimeout),this.teardownTimeout=null),this[singleton];const t=this.createClient(this.dispatch);return this[singleton]=t,t}async teardown(){const t=this[singleton];if(!t){console.warn("singleton has already been shutdown!");return}try{await t.shutdown()}finally{this[singleton]=null}}async releaseInstance(t){return this.proxyReceivers.delete(t)?this.proxyReceivers.size!==0?!1:(!this.teardownTimeout&&Number.isFinite(this.ttlMs)&&(this.ttlMs===0?await this.teardown():this.teardownTimeout=setTimeout(()=>{this.teardown().catch(n=>console.error("teardown failed",{err:n})).finally(()=>this.teardownTimeout=null)},this.ttlMs)),!0):(console.warn("this instance has already been released!"),!1)}}Sn=singleton;const getToken=async()=>defined$1(Authentication.token,"Realtime when user isn't authorized"),EnumRtcClientPools={[SessionTypes.UNKNOWN]:new RtcClientPool({ttlMs:2500,createClient:e=>new distExports.RtcClient({signalingClient:new distExports.SignalingPromiseClient(exports.FORMANT_API_URL),getToken,sessionType:SessionTypes.UNKNOWN,receive:e})}),[SessionTypes.TELEOP]:new RtcClientPool({ttlMs:2500,createClient:e=>new distExports.RtcClient({signalingClient:new distExports.SignalingPromiseClient(exports.FORMANT_API_URL),getToken,sessionType:SessionTypes.TELEOP,receive:e})}),[SessionTypes.PORT_FORWARD]:new RtcClientPool({ttlMs:2500,createClient:e=>new distExports.RtcClient({signalingClient:new distExports.SignalingPromiseClient(exports.FORMANT_API_URL),getToken,sessionType:SessionTypes.PORT_FORWARD,receive:e})}),[SessionTypes.OBSERVE]:new RtcClientPool({ttlMs:2500,createClient:e=>new distExports.RtcClient({signalingClient:new distExports.SignalingPromiseClient(exports.FORMANT_API_URL),getToken,sessionType:SessionTypes.OBSERVE,receive:e})}),[SessionTypes.HEADLESS]:new RtcClientPool({ttlMs:2500,createClient:e=>new distExports.RtcClient({signalingClient:new distExports.SignalingPromiseClient(exports.FORMANT_API_URL),getToken,sessionType:SessionTypes.HEADLESS,receive:e})})},AppRtcClientPools={...EnumRtcClientPools,unknown:EnumRtcClientPools[SessionTypes.UNKNOWN],teleop:EnumRtcClientPools[SessionTypes.TELEOP],portForward:EnumRtcClientPools[SessionTypes.PORT_FORWARD],observe:EnumRtcClientPools[SessionTypes.OBSERVE],headless:EnumRtcClientPools[SessionTypes.HEADLESS]},defaultRtcClientPool=EnumRtcClientPools[SessionTypes.TELEOP],getRtcClientPool=e=>{const{sessionType:t}=e;return t?AppRtcClientPools[t]:defaultRtcClientPool};async function getPeers(){if(!Authentication.token)throw new Error("Not authenticated");const e=defaultRtcClientPool.get();try{return await e.getPeers()}finally{await e.shutdown()}}async function getRealtimeSessions(){if(!Authentication.token)throw new Error("Not authenticated");const e=defaultRtcClientPool.get();try{return await e.getSessions()}finally{await e.shutdown()}}async function getTelemetry(e,t,n,r,o,s){let g=e;Array.isArray(e)||(g=[e]);let l=t;return Array.isArray(t)||(l=[t]),(await(await fetch(`${exports.FORMANT_API_URL}/v1/queries/queries`,{method:"POST",body:JSON.stringify({deviceIds:g,end:r.toISOString(),names:l,start:n.toISOString(),tags:o,latestOnly:s}),headers:{"Content-Type":"application/json",Authorization:"Bearer "+Authentication.token}})).json()).items}async function patchDevice(e,t){if(!Authentication.token)throw new Error("Not authenticated");return await(await fetch(`${exports.FORMANT_API_URL}/v1/admin/devices/${e}`,{method:"PATCH",body:JSON.stringify(t),headers:{"Content-Type":"application/json",Authorization:"Bearer "+Authentication.token}})).json()}async function queryDevicesData(e){if(!Authentication.token)throw new Error("Not authenticated");return(await(await fetch(`${exports.FORMANT_API_URL}/v1/admin/devices/query`,{method:"POST",body:JSON.stringify(e),headers:{"Content-Type":"application/json",Authorization:"Bearer "+Authentication.token}})).json()).items}const isRtcPeer=e=>e!==void 0&&e.capabilities!==void 0&&e.capabilitySet!==void 0;var eventemitter3={exports:{}};(function(e){var t=Object.prototype.hasOwnProperty,n="~";function r(){}Object.create&&(r.prototype=Object.create(null),new r().__proto__||(n=!1));function o(u,c,d){this.fn=u,this.context=c,this.once=d||!1}function s(u,c,d,B,Q){if(typeof d!="function")throw new TypeError("The listener must be a function");var f=new o(d,B||u,Q),p=n?n+c:c;return u._events[p]?u._events[p].fn?u._events[p]=[u._events[p],f]:u._events[p].push(f):(u._events[p]=f,u._eventsCount++),u}function g(u,c){--u._eventsCount===0?u._events=new r:delete u._events[c]}function l(){this._events=new r,this._eventsCount=0}l.prototype.eventNames=function(){var c=[],d,B;if(this._eventsCount===0)return c;for(B in d=this._events)t.call(d,B)&&c.push(n?B.slice(1):B);return Object.getOwnPropertySymbols?c.concat(Object.getOwnPropertySymbols(d)):c},l.prototype.listeners=function(c){var d=n?n+c:c,B=this._events[d];if(!B)return[];if(B.fn)return[B.fn];for(var Q=0,f=B.length,p=new Array(f);Q<f;Q++)p[Q]=B[Q].fn;return p},l.prototype.listenerCount=function(c){var d=n?n+c:c,B=this._events[d];return B?B.fn?1:B.length:0},l.prototype.emit=function(c,d,B,Q,f,p){var U=n?n+c:c;if(!this._events[U])return!1;var E=this._events[U],M=arguments.length,W,y;if(E.fn){switch(E.once&&this.removeListener(c,E.fn,void 0,!0),M){case 1:return E.fn.call(E.context),!0;case 2:return E.fn.call(E.context,d),!0;case 3:return E.fn.call(E.context,d,B),!0;case 4:return E.fn.call(E.context,d,B,Q),!0;case 5:return E.fn.call(E.context,d,B,Q,f),!0;case 6:return E.fn.call(E.context,d,B,Q,f,p),!0}for(y=1,W=new Array(M-1);y<M;y++)W[y-1]=arguments[y];E.fn.apply(E.context,W)}else{var m=E.length,h;for(y=0;y<m;y++)switch(E[y].once&&this.removeListener(c,E[y].fn,void 0,!0),M){case 1:E[y].fn.call(E[y].context);break;case 2:E[y].fn.call(E[y].context,d);break;case 3:E[y].fn.call(E[y].context,d,B);break;case 4:E[y].fn.call(E[y].context,d,B,Q);break;default:if(!W)for(h=1,W=new Array(M-1);h<M;h++)W[h-1]=arguments[h];E[y].fn.apply(E[y].context,W)}}return!0},l.prototype.on=function(c,d,B){return s(this,c,d,B,!1)},l.prototype.once=function(c,d,B){return s(this,c,d,B,!0)},l.prototype.removeListener=function(c,d,B,Q){var f=n?n+c:c;if(!this._events[f])return this;if(!d)return g(this,f),this;var p=this._events[f];if(p.fn)p.fn===d&&(!Q||p.once)&&(!B||p.context===B)&&g(this,f);else{for(var U=0,E=[],M=p.length;U<M;U++)(p[U].fn!==d||Q&&!p[U].once||B&&p[U].context!==B)&&E.push(p[U]);E.length?this._events[f]=E.length===1?E[0]:E:g(this,f)}return this},l.prototype.removeAllListeners=function(c){var d;return c?(d=n?n+c:c,this._events[d]&&g(this,d)):(this._events=new r,this._eventsCount=0),this},l.prototype.off=l.prototype.removeListener,l.prototype.addListener=l.prototype.on,l.prefixed=n,l.EventEmitter=l,e.exports=l})(eventemitter3);var eventemitter3Exports=eventemitter3.exports;const EventEmitter=getDefaultExportFromCjs(eventemitter3Exports);class Manipulator{constructor(t,n){he(this,"currentListeners",[]);he(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){he(this,"channel");he(this,"requestIdToResponseMap",new Map);this.device=t,this.channel_name=n,this.timeout=r}addOpenListener(t){defined$1(this.channel,"channel not initalized").addOpenListener(t)}removeOpenListener(t){defined$1(this.channel,"channel not initalized").removeOpenListener(t)}addCloseListener(t){defined$1(this.channel,"channel not initalized").addCloseListener(t)}removeCloseListener(t){defined$1(this.channel,"channel not initalized").removeCloseListener(t)}addErrorListener(t){defined$1(this.channel,"channel not initalized").addErrorListener(t)}removeErrorListener(t){defined$1(this.channel,"channel not initalized").removeErrorListener(t)}}class BinaryRequestDataChannel extends RequestDataChannel{constructor(){super(...arguments);he(this,"RESPONSE_SUCCESS_BYTE",0);he(this,"decoder",new TextDecoder)}generateBinaryId(){const n=new Uint8Array(16);for(let r=0;r<n.length;r++)n[r]=Math.floor(Math.random()*256);return n}async initialize(){this.channel=await this.device.createCustomDataChannel(this.channel_name),this.channel.addBinaryListener(n=>{const o=n.slice(0,16).toString();if(o.length===0)throw new Error("Invalid response");const s=n.slice(16);if(s.length===0)throw new Error("Invalid response");this.requestIdToResponseMap.has(o)&&this.requestIdToResponseMap.set(o,s)})}async request(n){if(this.channel||await this.initialize(),!this.channel)throw new Error("Failed to create channel");const{channel:r,requestIdToResponseMap:o,timeout:s}=this;await r.waitTilReady();const g=this.generateBinaryId(),l=g.toString();o.set(l,!0),r.sendBinary(new Uint8Array([...g,...n]));const u=new Date().getTime();for(;new Date().getTime()<u+s;)if(await delay(50),o.has(l)){const c=o.get(l);if(c!==!0){o.delete(l);const d=c[0]===this.RESPONSE_SUCCESS_BYTE,B=c.slice(1);if(d)return B;throw console.error({name:"AdapterError",message:this.decoder.decode(B)}),new Error("Binary request datachannel adapter error")}}throw o.delete(l),console.error({name:"TimeoutError",message:`Request timed out after ${s/1e3} seconds`}),new Error("Binary request data channel request timed out")}}class TextRequestDataChannel extends RequestDataChannel{generateTextId(){return Math.random().toString(36).substring(2)+"-"+Math.random().toString(36).substring(2)}async initialize(){this.channel=await this.device.createCustomDataChannel(this.channel_name),this.channel.addListener(t=>{const n=JSON.parse(t),{id:r,data:o,error:s}=n;if(!r)throw new Error("Invalid response");if(!o&&!s)throw new Error("Invalid response");this.requestIdToResponseMap.has(r)&&this.requestIdToResponseMap.set(r,n)})}async request(t){if(this.channel||await this.initialize(),!this.channel)throw new Error("Failed to create channel");const{channel:n,requestIdToResponseMap:r,timeout:o}=this;await n.waitTilReady();const s=this.generateTextId();r.set(s,!0),n.send(JSON.stringify({id:s,data:t}));const g=new Date().getTime();for(;new Date().getTime()<g+o;)if(await delay(50),r.has(s)){const l=r.get(s);if(l!==!0){r.delete(s);const{data:u,error:c}=l;if(u)return u;if(c)throw console.error({name:"AdapterError",message:c}),new Error("Text request datachannel adapter error")}}throw r.delete(s),console.error({name:"TimeoutError",message:`Request timed out after ${o/1e3} seconds`}),new Error("Text request datachannel request timed out")}}class BaseDevice extends EventEmitter{constructor(){super(...arguments);he(this,"rtcClient");he(this,"remoteDevicePeerId",null);he(this,"realtimeListeners",[]);he(this,"connectionMonitorInterval");he(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(){var o;const n=await this.getConfiguration(),r=[];for(const s of(o=n.teleop.rosStreams)!=null?o:[])s.topicType=="sensor_msgs/JointState"&&r.push(new Manipulator(this,{currentJointStateStream:{name:s.topicName},plannedJointStateStream:s.plannedTopic?{name:s.plannedTopic}:void 0,planValidStream:s.planValidTopic?{name:s.planValidTopic}:void 0,endEffectorStream:s.endEffectorTopic?{name:s.endEffectorTopic}:void 0,endEffectorLinkName:s.endEffectorLinkName,baseReferenceFrame:s.baseReferenceFrame,localFrame:s.localFrame}));return r}async getRealtimeVideoStreams(){var o,s,g,l,u,c;const n=await this.getConfiguration(),r=[];for(const d of(s=(o=n.teleop)==null?void 0:o.hardwareStreams)!=null?s:[])d.rtcStreamType==="h264-video-frame"&&r.push({name:d.name});for(const d of(l=(g=n.teleop)==null?void 0:g.rosStreams)!=null?l:[])d.topicType=="formant/H264VideoFrame"&&r.push({name:d.topicName}),(d.topicType==="sensor_msgs/Image"||d.topicType==="sensor_msgs/CompressedImage")&&d.encodeVideo&&r.push({name:d.topicName});for(const d of(c=(u=n.teleop)==null?void 0:u.customStreams)!=null?c:[])d.rtcStreamType==="h264-video-frame"&&r.push({name:d.name});return r}createCustomRequestDataChannel(n,r=3e3){return new TextRequestDataChannel(this,n,r)}createCustomBinaryRequestDataChannel(n,r=3e3){return new BinaryRequestDataChannel(this,n,r)}async startListeningToRealtimeVideo(n){const r=defined$1(this.rtcClient,"Realtime connection has not been started"),o=await this.getRemotePeer();r.controlRemoteStream(defined$1(o).id,{streamName:n.name,enable:!0,pipeline:"rtc"})}async stopListeningToRealtimeVideo(n){const r=defined$1(this.rtcClient,"Realtime connection has not been started"),o=await this.getRemotePeer();r.controlRemoteStream(defined$1(o).id,{streamName:n.name,enable:!1,pipeline:"rtc"})}async startListeningToRealtimeDataStream(n){const r=defined$1(this.rtcClient,"Realtime connection has not been started"),o=await this.getRemotePeer();r.controlRemoteStream(defined$1(o).id,{streamName:n.name,enable:!0,pipeline:"rtc"})}async stopListeningToRealtimeDataStream(n){const r=defined$1(this.rtcClient,"Realtime connection has not been started"),o=await this.getRemotePeer();r.controlRemoteStream(defined$1(o).id,{streamName:n.name,enable:!1,pipeline:"rtc"})}async enableRealtimeTelemetryPriorityIngestion(n){const r=defined$1(this.rtcClient,"Realtime connection has not been started"),o=await this.getRemotePeer();r.controlRemoteStream(defined$1(o).id,{streamName:n,enablePriorityUpload:!0,pipeline:"telemetry"})}async disableRealtimeTelemetryPriorityIngestion(n){const r=defined$1(this.rtcClient,"Realtime connection has not been started"),o=await this.getRemotePeer();r.controlRemoteStream(defined$1(o).id,{streamName:n,enablePriorityUpload:!1,pipeline:"telemetry"})}async changeStreamAudioType(n,r){const o=defined$1(this.rtcClient,"Realtime connection has not been started"),s=await this.getRemotePeer();o.controlRemoteStream(defined$1(s).id,{streamName:n,setAudioFormat:r})}async createCustomDataChannel(n,r){const o=defined$1(this.rtcClient,"Realtime connection has not been started"),s=await this.getRemotePeer(),g=await new Promise(l=>{o.createCustomDataChannel(defined$1(s).id,n,{ordered:!0,...r},!1,(u,c)=>{const d=new DataChannel(c);l(d)})});return await g.waitTilReady(),g}async sendRealtimeMessage(n,r={channelLabel:"stream.reliable"}){const o=defined$1(this.rtcClient,"Realtime connection has not been started"),s=await this.getRemotePeer();o.send(defined$1(s).id,n,r)}async getRealtimeAudioStreams(){var o,s,g,l,u,c;const n=await this.getConfiguration(),r=[];for(const d of(s=(o=n.teleop)==null?void 0:o.hardwareStreams)!=null?s:[])d.rtcStreamType==="audio-chunk"&&r.push({name:d.name});for(const d of(l=(g=n.teleop)==null?void 0:g.rosStreams)!=null?l:[])d.topicType=="audio_common_msgs/AudioData"&&r.push({name:d.topicName});for(const d of(c=(u=n.teleop)==null?void 0:u.customStreams)!=null?c:[])d.rtcStreamType==="audio-chunk"&&r.push({name:d.name});return r}}class Device extends BaseDevice{constructor(t,n,r,o){super(),this.id=t,this.name=n,this.organizationId=r,this.tags=o}async getLatestTelemetry(){return(await(await fetch(`${exports.FORMANT_API_URL}/v1/queries/stream-current-value`,{method:"POST",body:JSON.stringify({deviceIds:[this.id]}),headers:{"Content-Type":"application/json",Authorization:"Bearer "+Authentication.token}})).json()).items}async getConfiguration(t=!1){let n=await fetch(`${exports.FORMANT_API_URL}/v1/admin/devices/${this.id}`,{method:"GET",headers:{"Content-Type":"application/json",Authorization:"Bearer "+Authentication.token}});const r=await n.json();if(!r.state.reportedConfiguration)throw new Error("Device has no configuration, has it ever been turned on?");const o=t?r.desiredConfigurationVersion:r.state.reportedConfiguration.version;return n=await fetch(`${exports.FORMANT_API_URL}/v1/admin/devices/${this.id}/configurations/${o}`,{method:"GET",headers:{"Content-Type":"application/json",Authorization:"Bearer "+Authentication.token}}),(await n.json()).document}async getAgentVersion(){var r;const n=await(await fetch(`${exports.FORMANT_API_URL}/v1/admin/devices/${this.id}`,{method:"GET",headers:{"Content-Type":"application/json",Authorization:"Bearer "+Authentication.token}})).json();return(r=n==null?void 0:n.state)==null?void 0:r.agentVersion}async getFileUrl(t){return(await(await fetch(`${exports.FORMANT_API_URL}/v1/admin/files/query`,{method:"POST",body:JSON.stringify({fileIds:[t]}),headers:{"Content-Type":"application/json",Authorization:"Bearer "+Authentication.token}})).json()).fileUrls}async startRealtimeConnection(t={}){if(console.debug(`${new Date().toISOString()} :: Connection start requested`),this.rtcClient&&this.connectionMonitorInterval!==void 0)throw new Error(`Already created realtime connection to device ${this.id}`);this.rtcClient&&console.warn("overwriting existing rtcClient due to missing connectionMonitorInterval");const{sessionType:n,deadlineMs:r=1e4,maxConnectRetries:o=3}=typeof t=="number"?{sessionType:t}:t,g=getRtcClientPool({sessionType:n}).get(this.handleMessage);let l=!1;const u=new Promise((d,B)=>setTimeout(()=>{l=!0,B(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 g)for(;!g.isReady();)this.assertNotCancelled(l),await delay(100);const d=await this.getRemoteDevicePeerId(g);this.assertNotCancelled(l);let B;for(let f=0;f<o&&(B=await g.connect(d),!B);f++)delay(100),this.assertNotCancelled(l);if(!B)throw new Error(`Session could not be created: exhausted ${o} retries`);let Q=0;for(;!l&&g.getConnectionStatus(d)!=="connected";)await delay(100),Q+=1;return this.assertNotCancelled(l),console.debug(`${new Date().toISOString()} :: Connection completed after ${Q} retries`),d};return Promise.race([c(),u]).then(d=>{this.remoteDevicePeerId=d,this.initConnectionMonitoring(),this.rtcClient=g,this.emit("connect")}).catch(d=>{throw console.debug(`${new Date().toISOString()} :: Connection failed: %o`,d),this.remoteDevicePeerId=null,g.shutdown().catch(B=>{console.error("rtcClient cannot shutdown: %o",B)}),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$1(this.rtcClient,"Realtime connection has not been started").getPeers()).find(r=>r.deviceId===this.id);return defined$1(n,"Could not find remote peer for device "+this.id)}async stopRealtimeConnection(){let t=!1;if(this.rtcClient){this.stopConnectionMonitoring(),this.remoteDevicePeerId?(await this.rtcClient.disconnect(this.remoteDevicePeerId),this.remoteDevicePeerId=null):t=!0;try{await this.rtcClient.shutdown()}finally{this.rtcClient=void 0}}if(t)throw new Error(`Realtime connection hasn't been started for ${this.id}`)}async isInRealtimeSession(){const t=await getPeers(),n=await getRealtimeSessions(),r=t.find(o=>o.deviceId===this.id);return r?n[r.id].length>0:!1}async getAvailableCommands(t=!0){return(await(await fetch(`${exports.FORMANT_API_URL}/v1/admin/command-templates/`,{method:"GET",headers:{"Content-Type":"application/json",Authorization:"Bearer "+Authentication.token}})).json()).items.map(o=>({name:o.name,id:o.id,command:o.command,description:o.description,parameterEnabled:o.parameterEnabled,parameterValue:o.parameterValue,parameterMeta:o.parameterMeta,enabled:o.enabled,tags:o.tags})).filter(o=>t?!0:o.enabled)}async sendCommand(t,n,r,o,s){var B;const l=(await this.getAvailableCommands(!1)).find(Q=>s?Q.id===s:Q.name===t);if(!l)throw new Error(`Could not find command with name "${t}"`);let u="";n===void 0?l.parameterEnabled&&l.parameterValue&&(u=l.parameterValue):u=n;let c={value:u,scrubberTime:(r||new Date).toISOString(),meta:{...l.parameterMeta,...o}};return await fetch(`${exports.FORMANT_API_URL}/v1/admin/commands`,{method:"POST",body:JSON.stringify({commandTemplateId:l.id,organizationId:this.organizationId,deviceId:this.id,command:l.command,parameter:c,userId:(B=Authentication.currentUser)==null?void 0:B.id}),headers:{"Content-Type":"application/json",Authorization:"Bearer "+Authentication.token}})}async getCommand(t){return await fetch(`${exports.FORMANT_API_URL}/v1/admin/commands/${t}`,{method:"GET",headers:{"Content-Type":"application/json",Authorization:"Bearer "+Authentication.token}})}async createCaptureStream(t){const r=await(await fetch(`${exports.FORMANT_API_URL}/v1/admin/capture-sessions`,{method:"POST",body:JSON.stringify({deviceId:this.id,streamName:t,tags:{}}),headers:{"Content-Type":"application/json",Authorization:"Bearer "+Authentication.token}})).json();return new CaptureStream(r)}async getTelemetry(t,n,r,o,s,g,l){if(s!==void 0||g!==void 0)throw new Error("Limit and offset are not supported in this method");return await getTelemetry(this.id,t,n,r,o,l)}async queryEvents(t){if(t.deviceIds)throw new Error("Cannot filter multiple devices via Device class");return t.deviceIds=[this.id],queryEvents(t)}async getTelemetryStreams(){var l,u;const t=await this.getConfiguration(),n=await fetch(`${exports.FORMANT_API_URL}/v1/queries/metadata/stream-names`,{method:"POST",body:JSON.stringify({deviceIds:[this.id]}),headers:{"Content-Type":"application/json",Authorization:"Bearer "+Authentication.token}}),r=[],o=[];return(u=(l=t.telemetry)==null?void 0:l.streams)==null||u.forEach(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(`${exports.FORMANT_API_URL}/v1/admin/intervention-requests`,{method:"POST",body:JSON.stringify({message:t,interventionType:n,time:new Date().toISOString(),deviceId:this.id,tags:o,data:r}),headers:{"Content-Type":"application/json",Authorization:"Bearer "+Authentication.token}})).json()}async addInterventionResponse(t,n,r){return await(await fetch(`${exports.FORMANT_API_URL}/v1/admin/intervention-responses`,{method:"POST",body:JSON.stringify({interventionId:t,interventionType:n,data:r}),headers:{"Content-Type":"application/json",Authorization:"Bearer "+Authentication.token}})).json()}async getAnnotationCount(t,n){return await getAnnotationCount({...t,deviceIds:[this.id]},n)}async getAnnotationCountByIntervals(t,n,r){return await getAnnotationCountByIntervals({...t,deviceIds:[this.id]},n,r)}async eventsCounter(t,n,r,o,s){return await eventsCounter(t,n,r,o,{...s,deviceIds:[this.id]})}async createShareLink(t,n){return t.scope.deviceIds=[this.id],await createShareLink(t,n)}}he(Device,"createDevice",createDevice),he(Device,"patchDevice",patchDevice),he(Device,"getDevicesData",getDevicesData),he(Device,"queryDevicesData",queryDevicesData),he(Device,"disableDevice",disableDevice);class PeerDevice extends BaseDevice{constructor(n){super();he(this,"id");he(this,"telemetryStreamActive",!1);he(this,"streamTelemetry",{});this.peerUrl=n}async getLatestTelemetry(){this.telemetryStreamActive||this.subscribeToTelemetry();const n=this.streamTelemetry;return Object.entries(n).map(([o,s])=>({deviceId:this.id,streamName:o,streamType:"json",currentValue:s,currentValueTime:s.timestamp,tags:{}}))}async getTelemetry(n,r,o,s,g,l,u){if(Array.isArray(n))throw new Error("Multiple stream names not supported");if(s)throw new Error("Tags not supported");if(u&&g===void 0)g=1;else if(u&&g!==void 0)throw new Error("latestOnly and limit cannot be used together");let c=`${this.peerUrl}/v1/querydatapoints?stream_name=${n}&start=${r.toISOString()}&end=${o.toISOString()}`;g!=null&&g>0&&(c+=`&limit=${g}`),l!=null&&l>=0&&(c+=`&offset=${l}`);const B=await(await fetch(c)).json(),Q=[];for(const f of B.results){const p=parseInt(f.timestamp),U=f.tags.data_type;delete f.tags.data_type,Q.push({deviceId:this.id,name:f.stream,points:[[p,this.getPointPayload(U,f)]],tags:f.tags,type:U})}return Q.reverse()}async queryEvents(n){const r=["id","viewed","keyword","message","sort","eventTypes","notificationEnabled","userIds","annotationTemplateIds","disableNullMatches","severities","deviceIds","names","types","tags","notNames"];this.checkKeysAndThrow(n,r);let o=`${this.peerUrl}/v1/queryevents?start=${n.start}&end=${n.end}`;n.count!=null&&n.count>0&&(o+=`&limit=${n.count}`),n.offset!=null&&n.offset>=0&&(o+=`&offset=${n.offset}`);const g=await(await fetch(o)).json(),l=[];for(const u of g.results){const c=parseInt(u.timestamp),d={deviceId:this.id,time:new Date(c).toISOString(),message:u.message,notificationEnabled:u.notificationEnabled,type:u.type,tags:u.tags};u.id!==""&&(d.id=u.id),u.type!==""&&(d.type=u.type),u.streamName!==""&&(d.streamName=u.streamName),u.streamType!==""&&(d.streamType=u.streamType),u.severity!==""&&(d.severity=u.severity.toLowerCase()),u.tags&&(d.tags=u.tags),u.endTimestamp!=="0"&&(d.endTime=new Date(parseInt(u.endTimestamp)).toISOString()),l.push(d)}return l.reverse()}checkKeysAndThrow(n,r){const o=r.filter(s=>s in n);if(o.length>0)throw new Error(`Filters not currently supported: ${o.join(", ")}.`)}getPointPayload(n,r){switch(n){case"numeric":return r.numeric.value;case"numeric set":return r.numericSet.numerics;case"text":return r.text.value;case"json":return r.json.value;case"bitset":const o=[],s=[];for(const g of r.bitset.bits)o.push(g.key),s.push(g.value);return{keys:o,values:s};case"location":return r.location;case"health":return r.health;case"battery":return r.battery;default:return{}}}subscribeToTelemetry(){this.telemetryStreamActive=!0;let n=0;const r=new XMLHttpRequest;r.responseType="text",r.addEventListener("error",o=>{this.handleXHRError("error")}),r.addEventListener("abort",o=>{this.handleXHRError("abort")}),r.addEventListener("timeout",o=>{this.handleXHRError("timeout")}),r.addEventListener("readystatechange",o=>{r.readyState===XMLHttpRequest.DONE&&this.handleXHRError("closed")}),r.addEventListener("progress",o=>{const s=o.loaded,g=s-n;n=s,r.responseText.substr(-g).split(`
63
63
  `).forEach(c=>{var d;if(c.length>0){const B=JSON.parse(c);if((d=B.result)!=null&&d.datapoint){const Q=B.result.datapoint,f=Q.stream;delete Q.stream,this.streamTelemetry[f]=Q}}})}),r.open("POST",`${this.peerUrl}/v1/telemetry`),r.send()}handleXHRError(n){console.warn(`Telemetry stream ended: ${n}`),this.telemetryStreamActive=!1}async getDeviceId(){return(await(await fetch(`${this.peerUrl}/v1/config`)).json()).configuration.id}async getConfiguration(){return(await(await fetch(`${this.peerUrl}/v1/config`)).json()).configuration.document}async getViews(){return(await(await fetch(`${this.peerUrl}/v1/views`)).json()).views}async startRealtimeConnection(n){if(console.debug(`${new Date().toISOString()} :: Connection start requested`),this.rtcClient&&this.connectionMonitorInterval!==void 0)throw new Error(`Already created realtime connection to device ${this.id}`);this.rtcClient&&console.warn("overwriting existing rtcClient due to missing connectionMonitorInterval");const r=new distExports.RtcClient({lanOnlyMode:!0,receive:this.handleMessage,sessionType:n});for(await r.connectLan(this.peerUrl);r.getConnectionStatus(this.peerUrl)!=="connected";)await delay(100);this.rtcClient=r,this.initConnectionMonitoring()}initConnectionMonitoring(){this.connectionMonitorInterval=setInterval(async()=>{let n=!1;this.rtcClient&&this.rtcClient.getConnectionStatus(this.peerUrl)!=="connected"&&(console.debug(`${new Date().toISOString()} :: data channel closed`),n=!0),(!this.rtcClient||n)&&(this.emit("disconnect"),this.stopRealtimeConnection().catch(r=>{console.error(r)}))},1e3)}async getRemotePeer(){return{id:this.peerUrl,organizationId:"",deviceId:this.id,capabilities:[],capabilitySet:{}}}async stopRealtimeConnection(){let n=!1;if(this.rtcClient){this.stopConnectionMonitoring(),this.id?(await this.rtcClient.disconnect(this.id),this.remoteDevicePeerId=null):n=!0;try{await this.rtcClient.shutdown()}finally{this.rtcClient=void 0}}if(n)throw new Error(`Realtime connection hasn't been started for ${this.id}`)}async getCommandMetadata(){return(await fetch(`${this.peerUrl}/v1/commands`)).json()}async sendCommand(n,r,o,s){const g={value:r,scrubberTime:(o||new Date).toISOString(),meta:s};return await fetch(`${this.peerUrl}/v1/enqueue-command`,{method:"POST",body:JSON.stringify({command:n,parameter:g}),headers:{"Content-Type":"application/json"}})}}async function addDeviceToFleet(e,t){if(!Authentication.token)throw new Error("Not authenticated");return await(await fetch(`${exports.FORMANT_API_URL}/v1/admin/devices/${e}`,{method:"PATCH",body:JSON.stringify({fleetId:t}),headers:{"Content-Type":"application/json",Authorization:"Bearer "+Authentication.token}})).json()}async function aggregateTelemetry(e){if(!Authentication.token)throw new Error("Not authenticated");return(await(await fetch(`${exports.FORMANT_API_URL}/v1/queries/queries`,{method:"POST",body:JSON.stringify(e),headers:{"Content-Type":"application/json",Authorization:"Bearer "+Authentication.token}})).json()).aggregates}async function deleteFleet(e){if(!Authentication.token)throw new Error("Not authenticated");await fetch(`${exports.FORMANT_API_URL}/v1/admin/fleets/${e}`,{method:"DELETE",headers:{"Content-Type":"application/json",Authorization:"Bearer "+Authentication.token}})}async function getAnalyticStreams(){if(!Authentication.token)throw new Error("Not authenticated");return(await(await fetch(`${exports.FORMANT_API_URL}/v1/queries/analytics/streams`,{method:"GET",headers:{"Content-Type":"application/json",Authorization:"Bearer "+Authentication.token}})).json()).items}async function getAnalyticsModules(){if(!Authentication.token)throw new Error("Not authenticated");return(await(await fetch(`${exports.FORMANT_API_URL}/v1/admin/analytics-modules`,{method:"GET",headers:{"Content-Type":"application/json",Authorization:"Bearer "+Authentication.token}})).json()).items}async function getAnalyticsRows(e){if(!Authentication.token)throw new Error("Not authenticated");return await(await fetch(`${exports.FORMANT_API_URL}/v1/queries/analytics/rows`,{method:"POST",body:JSON.stringify(e),headers:{"Content-Type":"application/json",Authorization:"Bearer "+Authentication.token}})).json()}async function queryDevices(e){if(!Authentication.token)throw new Error("Not authenticated");return(await(await fetch(`${exports.FORMANT_API_URL}/v1/admin/devices/query`,{method:"POST",body:JSON.stringify(e),headers:{"Content-Type":"application/json",Authorization:"Bearer "+Authentication.token}})).json()).items.map(r=>new Device(r.id,r.name,r.organizationId,r.tags))}async function getCurrentGroup(){if(!Authentication.token)throw new Error("Not authenticated");let e=new URLSearchParams("");typeof window!="undefined"&&window.location&&(e=new URLSearchParams(window.location.search));const t=e.get("group");if(t===null||t.trim()==="")return;const n=await fetch(`${exports.FORMANT_API_URL}/v1/admin/groups/`+t,{headers:{"Content-Type":"application/json",Authorization:"Bearer "+Authentication.token}}),{tagKey:r,tagValue:o}=await n.json();return await queryDevices({tags:{[r]:[o]},enabled:!0,type:"default"})}async function getDevice(e){if(!Authentication.token)throw new Error("Not authenticated");const n=await(await fetch(`${exports.FORMANT_API_URL}/v1/admin/devices/${e}`,{method:"GET",headers:{"Content-Type":"application/json",Authorization:"Bearer "+Authentication.token}})).json(),r=n.name;return new Device(e,r,n.organizationId,n.tags)}async function getDevices(){if(!Authentication.token)throw new Error("Not authenticated");const t=await(await fetch(`${exports.FORMANT_API_URL}/v1/admin/device-details/query`,{method:"POST",body:JSON.stringify({enabled:!0,type:"default"}),headers:{"Content-Type":"application/json",Authorization:"Bearer "+Authentication.token}})).json();return t.items,t.items.map(n=>new Device(n.id,n.name,defined$1(Authentication.currentOrganization),n.tags))}async function getEvent(e){if(!Authentication.token)throw new Error("Not authenticated");return(await(await fetch(`${exports.FORMANT_API_URL}/v1/admin/events/query/id=${e}`,{method:"GET",headers:{"Content-Type":"application/json",Authorization:"Bearer "+Authentication.token}})).json()).items}async function getFileUrl(e){const n=await(await fetch(`${exports.FORMANT_API_URL}/v1/admin/files/query`,{method:"POST",body:JSON.stringify({fileIds:[e]}),headers:{"Content-Type":"application/json",Authorization:"Bearer "+Authentication.token}})).json();if(n.fileUrls.length===0)throw new Error("File not found");return n.fileUrls[0]}async function getFleet(e){if(!Authentication.token)throw new Error("Not authenticated");return await(await fetch(`${exports.FORMANT_API_URL}/v1/admin/fleets/${e}`,{method:"GET",headers:{"Content-Type":"application/json",Authorization:"Bearer "+Authentication.token}})).json()}async function getFleetDevices(e){if(!Authentication.token)throw new Error("Not authenticated");return(await(await fetch(`${exports.FORMANT_API_URL}/v1/admin/fleets/${e}/devices`,{method:"GET",headers:{"Content-Type":"application/json",Authorization:"Bearer "+Authentication.token}})).json()).items}async function getInterventions(){if(!Authentication.token)throw new Error("Not authenticated");return(await(await fetch(`${exports.FORMANT_API_URL}/v1/admin/intervention-requests`,{method:"GET",headers:{"Content-Type":"application/json",Authorization:"Bearer "+Authentication.token}})).json()).items}async function getLatestTelemetry(...e){const t=e.flat().filter(o=>!!o);return t.length===0?[]:(await(await fetch(`${exports.FORMANT_API_URL}/v1/queries/stream-current-value`,{method:"POST",body:JSON.stringify({deviceIds:t}),headers:{"Content-Type":"application/json",Authorization:"Bearer "+Authentication.token}})).json()).items}async function getOnlineDevices(){if(!Authentication.token)throw new Error("Not authenticated");const n=(await(await fetch(`${exports.FORMANT_API_URL}/v1/queries/online-devices`,{method:"GET",headers:{"Content-Type":"application/json",Authorization:"Bearer "+Authentication.token}})).json()).items;return(await getDevices()).filter(o=>n.includes(o.id))}async function getRealtimeDevices(){if(!Authentication.token)throw new Error("Not authenticated");const n=(await(await fetch(`${exports.FORMANT_API_URL}/v1/signaling/peers`,{method:"GET",headers:{"Content-Type":"application/json",Authorization:"Bearer "+Authentication.token}})).json()).items.map(o=>o.deviceId);return(await getDevices()).filter(o=>n.includes(o.id))}async function getStreams(){if(!Authentication.token)throw new Error("Not authenticated");return(await(await fetch(`${exports.FORMANT_API_URL}/v1/admin/streams`,{method:"GET",headers:{"Content-Type":"application/json",Authorization:"Bearer "+Authentication.token}})).json()).items.filter(n=>n.enabled)}async function getTaskReportRows(e){if(!Authentication.token)throw new Error("Not authenticated");return await(await fetch(`${exports.FORMANT_API_URL}/v1/queries/analytics/task-report-rows`,{method:"POST",body:JSON.stringify(e),headers:{"Content-Type":"application/json",Authorization:"Bearer "+Authentication.token}})).json()}async function getTaskReportTables(){if(!Authentication.token)throw new Error("Not authenticated");return(await(await fetch(`${exports.FORMANT_API_URL}/v1/queries/analytics/task-reports`,{method:"GET",headers:{"Content-Type":"application/json",Authorization:"Bearer "+Authentication.token}})).json()).items}async function listFleets(){if(!Authentication.token)throw new Error("Not authenticated");return(await(await fetch(`${exports.FORMANT_API_URL}/v1/admin/fleets`,{method:"GET",headers:{"Content-Type":"application/json",Authorization:"Bearer "+Authentication.token}})).json()).items}async function patchFleet(e,t){if(!Authentication.token)throw new Error("Not authenticated");return await(await fetch(`${exports.FORMANT_API_URL}/v1/admin/fleets/${e}`,{method:"PATCH",body:JSON.stringify(t),headers:{"Content-Type":"application/json",Authorization:"Bearer "+Authentication.token}})).json()}async function patchStream(e){if(!Authentication.token)throw new Error("Not authenticated");return await(await fetch(`${exports.FORMANT_API_URL}/v1/admin/streams/${e.id}`,{method:"PATCH",body:JSON.stringify(e),headers:{"Content-Type":"application/json",Authorization:"Bearer "+Authentication.token}})).json()}async function patchView(e){if(!Authentication.token)throw new Error("Not authenticated");return await(await fetch(`${exports.FORMANT_API_URL}/v1/admin/views/${e.id}`,{method:"PATCH",body:JSON.stringify(e),headers:{"Content-Type":"application/json",Authorization:"Bearer "+Authentication.token}})).json()}async function queryAnalytics(e){if(!Authentication.token)throw new Error("Not authenticated");return await(await fetch(`${exports.FORMANT_API_URL}/v1/queries/analytics`,{method:"POST",body:JSON.stringify(e),headers:{"Content-Type":"application/json",Authorization:"Bearer "+Authentication.token}})).json()}async function createFleet(e){if(!Authentication.token)throw new Error("Not authenticated");return await(await fetch(`${exports.FORMANT_API_URL}/v1/admin/fleets`,{method:"POST",body:JSON.stringify(e),headers:{"Content-Type":"application/json",Authorization:"Bearer "+Authentication.token}})).json()}async function getAllEventTriggerGroup(){if(!Authentication.token)throw new Error("Not authenticated");return(await(await fetch(`${exports.FORMANT_API_URL}/v1/admin/event-trigger-groups`,{method:"GET",headers:{"Content-Type":"application/json",Authorization:"Bearer "+Authentication.token}})).json()).items}async function getEventTriggerGroup(e){if(!Authentication.token)throw new Error("Not authenticated");return await(await fetch(`${exports.FORMANT_API_URL}/v1/admin/event-trigger-groups/${e}`,{method:"GET",headers:{"Content-Type":"application/json",Authorization:"Bearer "+Authentication.token}})).json()}async function patchEventTriggerGroup(e,t){if(!Authentication.token)throw new Error("Not authenticated");return await(await fetch(`${exports.FORMANT_API_URL}/v1/admin/event-trigger-groups/${e}`,{method:"PATCH",body:JSON.stringify(t),headers:{"Content-Type":"application/json",Authorization:"Bearer "+Authentication.token}})).json()}const Qt=class{static async setDefaultDevice(t){Qt.defaultDeviceId=t}static async getCurrentDevice(){if(!Authentication.token)throw new Error("Not authenticated");if(!Qt.defaultDeviceId)throw new Error("No known default device");const r=(await(await fetch(`${exports.FORMANT_API_URL}/v1/admin/device-details/query`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:"Bearer "+Authentication.token}})).json()).items.find(g=>g.id===Qt.defaultDeviceId),o=r.name,s=new Device(Qt.defaultDeviceId,o,defined$1(Authentication.currentOrganization),r.tags);return Qt.knownContext.push(new WeakRef(s)),s}static async getPeerDevice(t){const n=new PeerDevice(t);return n.id=await n.getDeviceId(),n}static async getDevice(t){const n=await getDevice(t);return Qt.knownContext.push(new WeakRef(n)),n}};let Fleet=Qt;he(Fleet,"defaultDeviceId"),he(Fleet,"knownContext",[]),he(Fleet,"createFleet",createFleet),he(Fleet,"listFleets",listFleets),he(Fleet,"getFleet",getFleet),he(Fleet,"patchFleet",patchFleet),he(Fleet,"deleteFleet",deleteFleet),he(Fleet,"addDeviceToFleet",addDeviceToFleet),he(Fleet,"getFleetDevices",getFleetDevices),he(Fleet,"aggregateTelemetry",aggregateTelemetry),he(Fleet,"createShareLink",createShareLink),he(Fleet,"eventsCounter",eventsCounter),he(Fleet,"getAnalyticStreams",getAnalyticStreams),he(Fleet,"getAnalyticsModules",getAnalyticsModules),he(Fleet,"getAnalyticsRows",getAnalyticsRows),he(Fleet,"getAnnotationCount",getAnnotationCount),he(Fleet,"getAnnotationCountByIntervals",getAnnotationCountByIntervals),he(Fleet,"getCurrentGroup",getCurrentGroup),he(Fleet,"getDevices",getDevices),he(Fleet,"getEvent",getEvent),he(Fleet,"getFileUrl",getFileUrl),he(Fleet,"getInterventions",getInterventions),he(Fleet,"getLatestTelemetry",getLatestTelemetry),he(Fleet,"getOnlineDevices",getOnlineDevices),he(Fleet,"getPeers",getPeers),he(Fleet,"getRealtimeDevices",getRealtimeDevices),he(Fleet,"getRealtimeSessions",getRealtimeSessions),he(Fleet,"getStreams",getStreams),he(Fleet,"getTaskReportRows",getTaskReportRows),he(Fleet,"getTaskReportTables",getTaskReportTables),he(Fleet,"getTelemetry",getTelemetry),he(Fleet,"getViews",getViews),he(Fleet,"patchStream",patchStream),he(Fleet,"patchView",patchView),he(Fleet,"queryAnalytics",queryAnalytics),he(Fleet,"queryDevices",queryDevices),he(Fleet,"queryEvents",queryEvents),he(Fleet,"queryTelemetry",queryTelemetry),he(Fleet,"getAllEventTriggerGroup",getAllEventTriggerGroup),he(Fleet,"getEventTriggerGroup",getEventTriggerGroup),he(Fleet,"patchEventTriggergroup",patchEventTriggerGroup);class KeyValue{static async set(t,n,r){try{const o=await fetch(exports.FORMANT_API_URL+"/v1/admin/key-value",{method:"POST",body:JSON.stringify({organizationId:defined$1(Authentication.currentUser).organizationId,key:t,value:n,tags:r}),headers:{"Content-Type":"application/json",Authorization:"Bearer "+Authentication.token}}),s=await o.json();if(o.status!==200)throw new Error(s.message)}catch(o){throw o}}static async get(t){try{const n=await fetch(exports.FORMANT_API_URL+`/v1/admin/key-value/${t}`,{method:"GET",headers:{"Content-Type":"application/json",Authorization:"Bearer "+Authentication.token}}),r=await n.json();if(n.status!==200)throw new Error(r.message);return r.value}catch(n){throw n}}static async list(){try{const t=await fetch(exports.FORMANT_API_URL+"/v1/admin/key-value",{method:"GET",headers:{"Content-Type":"application/json",Authorization:"Bearer "+Authentication.token}}),n=await t.json();if(t.status!==200)throw new Error(n.message);return n.items}catch(t){throw t}}static async delete(t){try{if(!(await fetch(exports.FORMANT_API_URL+`/v1/admin/key-value/${t}`,{method:"DELETE",headers:{"Content-Type":"application/json",Authorization:"Bearer "+Authentication.token}})).ok)throw new Error("Unable to handle request");return}catch(n){throw n}}static async query(t){try{const n=await fetch(exports.FORMANT_API_URL+"/v1/admin/key-value/query",{method:"POST",body:JSON.stringify({keys:t}),headers:{"Content-Type":"application/json",Authorization:"Bearer "+Authentication.token}});if(!n.ok)throw new Error("Unable to handle request");return(await n.json()).items}catch(n){throw n}}}class Role{static async listRoles(){if(!Authentication.token)throw new Error("Not authenticated");return(await(await fetch(`${exports.FORMANT_API_URL}/v1/admin/roles`,{method:"GET",headers:{"Content-Type":"application/json",Authorization:"Bearer "+Authentication.token}})).json()).items}static async createRole(t){if(!Authentication.token)throw new Error("Not authenticated");return await(await fetch(`${exports.FORMANT_API_URL}/v1/admin/roles`,{method:"POST",body:JSON.stringify(t),headers:{"Content-Type":"application/json",Authorization:"Bearer "+Authentication.token}})).json()}static async getRole(t){if(!Authentication.token)throw new Error("Not authenticated");return await(await fetch(`${exports.FORMANT_API_URL}/v1/admin/roles/${t}`,{method:"GET",headers:{"Content-Type":"application/json",Authorization:"Bearer "+Authentication.token}})).json()}static async patchRole(t,n){if(!Authentication.token)throw new Error("Not authenticated");return await(await fetch(`${exports.FORMANT_API_URL}/v1/admin/roles/${t}`,{method:"PATCH",body:JSON.stringify(n),headers:{"Content-Type":"application/json",Authorization:"Bearer "+Authentication.token}})).json()}static async deleteRole(t){if(!Authentication.token)throw new Error("Not authenticated");await fetch(`${exports.FORMANT_API_URL}/v1/admin/roles/${t}`,{method:"DELETE",headers:{"Content-Type":"application/json",Authorization:"Bearer "+Authentication.token}})}}class User{static async listUsers(){if(!Authentication.token)throw new Error("Not authenticated");return(await(await fetch(`${exports.FORMANT_API_URL}/v1/admin/users`,{method:"GET",headers:{"Content-Type":"application/json",Authorization:"Bearer "+Authentication.token}})).json()).items}static async createUser(t){if(!Authentication.token)throw new Error("Not authenticated");return await(await fetch(`${exports.FORMANT_API_URL}/v1/admin/users`,{method:"POST",body:JSON.stringify(t),headers:{"Content-Type":"application/json",Authorization:"Bearer "+Authentication.token}})).json()}static async getUser(t){if(!Authentication.token)throw new Error("Not authenticated");return await(await fetch(`${exports.FORMANT_API_URL}/v1/admin/users/${t}`,{method:"GET",headers:{"Content-Type":"application/json",Authorization:"Bearer "+Authentication.token}})).json()}static async patchUser(t,n){if(!Authentication.token)throw new Error("Not authenticated");return await(await fetch(`${exports.FORMANT_API_URL}/v1/admin/users/${t}`,{method:"PATCH",body:JSON.stringify(n),headers:{"Content-Type":"application/json",Authorization:"Bearer "+Authentication.token}})).json()}static async deleteUser(t){if(!Authentication.token)throw new Error("Not authenticated");await fetch(`${exports.FORMANT_API_URL}/v1/admin/users/${t}`,{method:"PATCH",body:JSON.stringify({enabled:!1,roleId:null,teamId:null}),headers:{"Content-Type":"application/json",Authorization:"Bearer "+Authentication.token}})}}async function request(e,t){if(!Authentication.token)throw new Error("Not authenticated");const n=await fetch(`${exports.FORMANT_API_URL}/v1${e}`,{...t,headers:{"Content-Type":"application/json",Authorization:`Bearer ${Authentication.token}`,...t==null?void 0:t.headers}});if(!n.ok)throw new Error(`Error: ${n.statusText}`);return n.status===204||n.headers.get("content-length")==="0"?null:await n.json()}async function fetchTeleopViews(){return(await request("/admin/teleop-views")).items}async function getTeleopView(e){return await request(`/admin/teleop-views/${e}`)}async function createTeleopView(e){return await request("/admin/teleop-views",{method:"POST",body:JSON.stringify(e)})}async function updateTeleopView(e,t){return await request(`/admin/teleop-views/${e}`,{method:"PATCH",body:JSON.stringify(t)})}async function deleteTeleopView(e){await request(`/admin/teleop-views/${e}`,{method:"DELETE"})}class Views{constructor(){}}he(Views,"createTeleopView",createTeleopView),he(Views,"updateTeleopView",updateTeleopView),he(Views,"deleteTeleopView",deleteTeleopView),he(Views,"getTeleopView",getTeleopView),he(Views,"fetchTeleopViews",fetchTeleopViews);const viewer="viewer",operator="operator",administrator="administrator",accessLevels=["viewer","operator","administrator"],aggregateLevels=["year","month","week","day","hour","minute"],annotationTypes=["tag","sheet","user"],eventTypes=["triggered-event","datapoint-event","device-online","device-offline","intervention-request","teleop-session-record","port-forwarding-session-record","command-request","command-response","command-delivery","intervention-response","custom","comment","system","annotation","task-summary","stateful"],healthStatuses=["unknown","operational","offline","error"],interventionTypes=["selection","labeling","teleop"],severities=["info","warning","error","critical"],videoMimeTypes=["video/mp4"],timeout=e=>new Promise(t=>setTimeout(t,e*1e3));try{const e=typeof window!="undefined"&&window.location?new URLSearchParams(window.location.search):new URLSearchParams(""),t=e.get("device");t&&Fleet.setDefaultDevice(t);const n=e.get("auth");n&&Authentication.loginWithToken(n),e.get("module")&&Authentication.listenForRefresh(),typeof window!="undefined"&&App.listenForConnectionEvents()}catch(e){}var __defProp=Object.defineProperty,__defProps=Object.defineProperties,__getOwnPropDescs=Object.getOwnPropertyDescriptors,__getOwnPropSymbols=Object.getOwnPropertySymbols,__hasOwnProp=Object.prototype.hasOwnProperty,__propIsEnum=Object.prototype.propertyIsEnumerable,__defNormalProp=(e,t,n)=>t in e?__defProp(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n,__spreadValues=(e,t)=>{for(var n in t||(t={}))__hasOwnProp.call(t,n)&&__defNormalProp(e,n,t[n]);if(__getOwnPropSymbols)for(var n of __getOwnPropSymbols(t))__propIsEnum.call(t,n)&&__defNormalProp(e,n,t[n]);return e},__spreadProps=(e,t)=>__defProps(e,__getOwnPropDescs(t)),__publicField=(e,t,n)=>(__defNormalProp(e,typeof t!="symbol"?t+"":t,n),n);const millisecond$1=1,second$1=1e3,minute$1=60*second$1,hour$1=60*minute$1,day$1=24*hour$1,week$1=7*day$1,month$1=30*day$1,year$1=365*day$1,duration$1={millisecond:millisecond$1,second:second$1,minute:minute$1,hour:hour$1,day:day$1,week:week$1,month:month$1,year:year$1};class H264Decoder{constructor(t,n,r){__publicField(this,"worker"),__publicField(this,"onReceive"),__publicField(this,"onError"),__publicField(this,"onReceiveMessage",s=>{const{data:g}=s;if(g.error){const l=new Error(`${g.error}`);l.cause=g.error,console.warn("H264 worker failure",{error:l}),this.onError(g.index);return}this.onReceive(g)});var o;this.worker=t,(o=this.worker)==null||o.addEventListener("message",this.onReceiveMessage),this.onReceive=n,this.onError=r}post(t,n,r,o){var s;(s=this.worker)==null||s.postMessage({timestamp:t,encodedFrame:n,flags:r,index:o})}release(){var t,n;(t=this.worker)==null||t.removeEventListener("message",this.onReceiveMessage),(n=this.worker)==null||n.terminate(),this.worker=void 0}}class YUVCanvas{constructor(t){__publicField(this,"gl"),__publicField(this,"program"),__publicField(this,"texturePosBuffer"),__publicField(this,"textureRef"),__publicField(this,"height",0),__publicField(this,"width",0),this.gl=t,this.program=this.initProgram();const{texturePosBuffer:n}=this.initBuffers();this.texturePosBuffer=n;const{textureRef:r}=this.initTextures();this.textureRef=r}draw(t){const{gl:n,height:r,width:o,texturePosBuffer:s,textureRef:g}=this;n.viewport(0,0,o,r);const l=new Float32Array([1,0,0,0,1,1,0,1]);return n.bindBuffer(n.ARRAY_BUFFER,s),n.bufferData(n.ARRAY_BUFFER,l,n.DYNAMIC_DRAW),n.activeTexture(n.TEXTURE0),n.bindTexture(n.TEXTURE_2D,g),n.texImage2D(n.TEXTURE_2D,0,n.LUMINANCE,o,r+r/2,0,n.LUMINANCE,n.UNSIGNED_BYTE,t),n.drawArrays(n.TRIANGLE_STRIP,0,4),n.getError()}initProgram(){const{gl:t}=this,n=`
64
64
  attribute vec4 vertexPos;
65
65
  attribute vec4 texturePos;