@aikaara/chat-sdk 0.9.5 → 0.9.6

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,11 +1,11 @@
1
- var AikaaraChat=(function(Ce){"use strict";class po{identifier;callbacks={};sendFn;constructor(e,t){this.identifier=e,this.sendFn=t}onReceived(e){return this.callbacks.received=e,this}onConnected(e){return this.callbacks.connected=e,this}onDisconnected(e){return this.callbacks.disconnected=e,this}onRejected(e){return this.callbacks.rejected=e,this}perform(e,t={}){this.sendFn({action:e,...t})}_notifyReceived(e){this.callbacks.received?.(e)}_notifyConnected(){this.callbacks.connected?.()}_notifyDisconnected(){this.callbacks.disconnected?.()}_notifyRejected(){this.callbacks.rejected?.()}}class Dr{ws=null;url;subscriptions=new Map;welcomePromise=null;pendingSubscriptions=new Map;constructor(e){this.url=e}connect(){return new Promise((e,t)=>{this.welcomePromise={resolve:e,reject:t},this.ws=new WebSocket(this.url),this.ws.onopen=()=>{},this.ws.onmessage=r=>{this.handleMessage(r)},this.ws.onerror=()=>{const r=new Error("WebSocket connection error");this.welcomePromise?.reject(r),this.welcomePromise=null},this.ws.onclose=()=>{this.subscriptions.forEach(r=>r._notifyDisconnected())}})}disconnect(){this.ws&&(this.ws.onclose=null,this.ws.close(),this.ws=null),this.subscriptions.forEach(e=>e._notifyDisconnected()),this.subscriptions.clear()}subscribe(e){const t=JSON.stringify(e),r=new po(t,a=>{this.send({command:"message",identifier:t,data:JSON.stringify(a)})});return this.subscriptions.set(t,r),this.send({command:"subscribe",identifier:t}),r}subscribeAsync(e){const t=this.subscribe(e),r=t.identifier;return new Promise((a,n)=>{this.pendingSubscriptions.set(r,{resolve:()=>a(t),reject:n}),setTimeout(()=>{this.pendingSubscriptions.has(r)&&(this.pendingSubscriptions.delete(r),n(new Error(`Subscription timeout for ${r}`)))},1e4)})}unsubscribe(e){this.send({command:"unsubscribe",identifier:e}),this.subscriptions.delete(e)}perform(e,t,r={}){this.send({command:"message",identifier:e,data:JSON.stringify({action:t,...r})})}get isConnected(){return this.ws?.readyState===WebSocket.OPEN}send(e){this.ws?.readyState===WebSocket.OPEN&&this.ws.send(JSON.stringify(e))}handleMessage(e){let t;try{t=JSON.parse(e.data)}catch{return}switch(t.type){case"welcome":this.welcomePromise?.resolve(),this.welcomePromise=null;break;case"ping":break;case"confirm_subscription":{const r=t.identifier;this.subscriptions.get(r)?._notifyConnected();const n=this.pendingSubscriptions.get(r);n&&(n.resolve(),this.pendingSubscriptions.delete(r));break}case"reject_subscription":{const r=t.identifier;this.subscriptions.get(r)?._notifyRejected(),this.subscriptions.delete(r);const n=this.pendingSubscriptions.get(r);n&&(n.reject(new Error(`Subscription rejected: ${r}`)),this.pendingSubscriptions.delete(r));break}case"disconnect":this.subscriptions.forEach(r=>r._notifyDisconnected());break;default:{t.identifier&&t.message!==void 0&&this.subscriptions.get(t.identifier)?._notifyReceived(t.message);break}}}}class Zt{handlers=new Map;on(e,t){return this.handlers.has(e)||this.handlers.set(e,new Set),this.handlers.get(e).add(t),()=>this.off(e,t)}off(e,t){this.handlers.get(e)?.delete(t)}emit(e,t){this.handlers.get(e)?.forEach(r=>{try{r(t)}catch(a){console.error(`Error in event handler for "${e}":`,a)}})}removeAllListeners(){this.handlers.clear()}}const zl=1e3,Kl=10,Vl=400,Gl=600,go="#6366f1",Yl=12,Ql="system-ui, -apple-system, sans-serif",mo="Type a message...",Jl="bottom-right",Xl="light",Zl={x:20,y:20},$r="aikaara_conversation_id";class bo extends Zt{client;config;state="disconnected";reconnectAttempt=0;reconnectTimer=null;constructor(e){super(),this.config=e;const t=this.buildWsUrl(e.baseUrl,e.userToken);this.client=new Dr(t)}async connect(){this.setState("connecting");try{await this.client.connect(),this.setState("connected"),this.reconnectAttempt=0}catch(e){if(this.setState("disconnected"),this.config.reconnect!==!1)this.scheduleReconnect();else throw e}}async disconnect(){this.clearReconnectTimer(),this.client.disconnect(),this.setState("disconnected")}subscribeToConversation(e){return this.client.subscribeAsync({channel:"ConversationChannel",conversation_id:e})}sendMessage(e,t){const r=JSON.stringify({channel:"ConversationChannel",conversation_id:e});this.client.perform(r,"send_message",{content:t})}sendUserEvent(e,t,r,a){const n=JSON.stringify({channel:"ConversationChannel",conversation_id:e});this.client.perform(n,"send_user_event",{event_key:t,...r&&{value:r},...a&&{source:a}})}get connectionState(){return this.state}setState(e){this.state!==e&&(this.state=e,this.emit("connection:state",e))}scheduleReconnect(){const e=this.config.maxReconnectAttempts??Kl;if(this.reconnectAttempt>=e){this.emit("error",new Error("Max reconnection attempts reached"));return}this.setState("reconnecting");const r=(this.config.reconnectInterval??zl)*Math.pow(2,this.reconnectAttempt);this.reconnectAttempt++,this.reconnectTimer=setTimeout(async()=>{try{const a=this.buildWsUrl(this.config.baseUrl,this.config.userToken);this.client=new Dr(a),await this.connect()}catch{}},r)}clearReconnectTimer(){this.reconnectTimer&&(clearTimeout(this.reconnectTimer),this.reconnectTimer=null)}buildWsUrl(e,t){if(this.config.wsUrl){const a=this.config.wsUrl.includes("?")?"&":"?";return`${this.config.wsUrl}${a}token=${t}`}return`${e.replace(/^http/,"ws")}/cable?token=${t}`}}class yo{baseUrl;apiKey;authToken;userToken;refreshHook=null;constructor(e,t,r,a){this.baseUrl=e,this.userToken=t,this.apiKey=r,this.authToken=a}setAuthRefreshHook(e){this.refreshHook=e}getAuthToken(){return this.authToken}setAuthToken(e){this.authToken=e}async createConversation(e){const t={conversation:{...e.extUid&&{ext_uid:e.extUid},...e.systemPromptId&&{system_prompt_id:e.systemPromptId},...e.channel&&{channel:e.channel},...e.title&&{title:e.title}}};return this.request("POST","/api/v1/conversations",t)}async updateContext(e,t){const r=this.authToken?`/dashboard/sidekick_conversations/${e}`:`/api/v1/conversations/${e}`;await this.request("PATCH",r,t)}async getMessages(e){return(await this.request("GET",`/api/v1/conversations/${e}/messages`)).map(this.mapMessage)}mapMessage(e){return{id:String(e.id),conversationId:String(e.conversation_id),role:e.role,content:e.content||"",toolCalls:e.tool_calls?.map(t=>({id:t.id,type:t.type,function:t.function})),toolCallResults:e.tool_call_results,tokensInput:e.tokens_input,tokensOutput:e.tokens_output,metadata:e.metadata,createdAt:e.created_at,status:"complete"}}async request(e,t,r){const a=`${this.baseUrl}${t}`;let n=await this.fetchWithHeaders(a,e,r);if(n.status===401&&this.refreshHook){let s=null;try{s=await this.refreshHook()}catch(o){console.warn("[aikaara-chat-sdk] auth refresh hook threw",o)}s&&(this.authToken=s,n=await this.fetchWithHeaders(a,e,r))}if(!n.ok){const s=await n.text();let o;try{const l=JSON.parse(s);o=l.error||l.message||s}catch{o=s}throw new Error(`API error ${n.status}: ${o}`)}const i=await n.json();if(i&&typeof i=="object"&&"success"in i){if(!i.success)throw new Error(`API error: ${i.message||"Request failed"}`);return i.data}return i}async fetchWithHeaders(e,t,r){const a={"Content-Type":"application/json",Accept:"application/json"};this.apiKey&&(a["X-Api-Key"]=this.apiKey),this.authToken&&(a.Authorization=`Bearer ${this.authToken}`);const n={method:t,headers:a};return r&&(n.body=JSON.stringify(r)),fetch(e,n)}}class vo{_messages=[];optimisticCounter=0;get messages(){return[...this._messages]}addOptimistic(e,t,r){const a={id:`optimistic_${++this.optimisticCounter}`,conversationId:r,role:e,content:t,createdAt:new Date().toISOString(),status:"sending"};return this._messages.push(a),a}reconcileOptimistic(e,t=3e4){const r=this._messages.findLast(a=>a.status==="sending"&&a.role===e.role&&a.content===e.content&&a.conversationId===e.conversationId&&Date.now()-new Date(a.createdAt).getTime()<t);return r?(r.status=e.status??"sent",r.externalId=e.externalId??e.id,e.template&&(r.template=e.template),e.attachments&&(r.attachments=e.attachments),e.metadata&&(r.metadata={...r.metadata??{},...e.metadata}),r):null}upsertRemoteMessage(e){const t=this.reconcileOptimistic(e);if(t)return{message:t,deduped:!0};const r=e.externalId?this._messages.find(n=>n.externalId&&n.externalId===e.externalId):void 0;if(r)return Object.assign(r,e,{id:r.id}),{message:r,deduped:!0};const a=ec(this._messages,e);return a?(Object.assign(a,e,{id:a.id}),{message:a,deduped:!0}):(this._messages.push(e),{message:e,deduped:!1})}updateMessageStatus(e,t){const r=this._messages.find(a=>a.externalId===e||a.id===e);return r&&(r.status=t),r}confirmOptimistic(e){const t=this._messages.find(r=>r.id===e);t&&(t.status="sent")}addStreamingMessage(e){const t={id:`streaming_${Date.now()}`,conversationId:e,role:"assistant",content:"",createdAt:new Date().toISOString(),status:"streaming"};return this._messages.push(t),t}updateStreaming(e){const t=this._messages.findLast(r=>r.status==="streaming");t&&(t.content=e)}appendToStreaming(e){const t=this._messages.findLast(r=>r.status==="streaming");t&&(t.content+=e)}get streamingContent(){return this._messages.findLast(t=>t.status==="streaming")?.content||""}finalizeStreaming(e){const t=this._messages.findLast(r=>r.status==="streaming");return t&&(t.status="complete",e&&(t.tokensInput=e.tokensInput,t.tokensOutput=e.tokensOutput)),t}addMessage(e){this._messages.push(e)}setMessages(e){this._messages=[...e]}clear(){this._messages=[]}}function ec(c,e,t=15e3){const r=e.attachments&&e.attachments[0],a=(e.metadata??{}).attributes;if(!(!!r||!!(a&&a.fileMessage)))return null;const i=ko(e),s=wo(e),o=_o(e);if(!i&&!s&&!o)return null;const l=new Date(e.createdAt).getTime();for(let u=c.length-1;u>=0;u--){const d=c[u],p=d.attachments&&d.attachments[0],y=(d.metadata??{}).attributes;if(!(!!p||!!(y&&y.fileMessage))||Math.abs(l-new Date(d.createdAt).getTime())>t)continue;const g=ko(d);if(i&&g&&i===g)return d;const b=wo(d);if(s&&b&&s===b)return d;const k=_o(d);if(o&&k&&o===k)return d}return null}function wo(c){const e=c.attachments&&c.attachments[0];if(e&&typeof e.fileUrl=="string")return e.fileUrl}function _o(c){const e=c.attachments&&c.attachments[0];if(e&&typeof e.fileName=="string")return e.fileName}function ko(c){const e=c.attachments&&c.attachments[0];if(e&&typeof e.cloudFileId=="string")return e.cloudFileId;const t=(c.metadata??{}).attributes;if(t&&typeof t.cloudFileId=="string")return t.cloudFileId}class So{_conversationId;persist;constructor(e,t=!0){this.persist=t,this._conversationId=e||this.loadFromStorage()}get conversationId(){return this._conversationId}set conversationId(e){this._conversationId=e,this.persist&&e&&this.saveToStorage(e)}clear(){if(this._conversationId=null,this.persist)try{localStorage.removeItem($r)}catch{}}loadFromStorage(){if(!this.persist)return null;try{return localStorage.getItem($r)}catch{return null}}saveToStorage(e){try{localStorage.setItem($r,e)}catch{}}}var Wr=Object.defineProperty,tc=Object.getOwnPropertyDescriptor,rc=Object.getOwnPropertyNames,nc=Object.prototype.hasOwnProperty,He=(c,e)=>()=>(c&&(e=c(c=0)),e),pe=(c,e)=>()=>(e||c((e={exports:{}}).exports,e),e.exports),Ct=(c,e)=>{for(var t in e)Wr(c,t,{get:e[t],enumerable:!0})},ic=(c,e,t,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let a of rc(e))!nc.call(c,a)&&a!==t&&Wr(c,a,{get:()=>e[a],enumerable:!(r=tc(e,a))||r.enumerable});return c},Pe=c=>ic(Wr({},"__esModule",{value:!0}),c),le=He(()=>{}),Me={};Ct(Me,{_debugEnd:()=>En,_debugProcess:()=>Sn,_events:()=>Dn,_eventsCount:()=>$n,_exiting:()=>cn,_fatalExceptions:()=>wn,_getActiveHandles:()=>Oo,_getActiveRequests:()=>Co,_kill:()=>fn,_linkedBinding:()=>Io,_maxListeners:()=>Fn,_preload_modules:()=>Nn,_rawDebug:()=>sn,_startProfilerIdleNotifier:()=>xn,_stopProfilerIdleNotifier:()=>An,_tickCallback:()=>kn,abort:()=>On,addListener:()=>Wn,allowedNodeEnvironmentFlags:()=>yn,arch:()=>zr,argv:()=>Gr,argv0:()=>Ln,assert:()=>Po,binding:()=>Zr,browser:()=>on,chdir:()=>rn,config:()=>un,cpuUsage:()=>$t,cwd:()=>tn,debugPort:()=>jn,default:()=>Qn,dlopen:()=>To,domain:()=>ln,emit:()=>Vn,emitWarning:()=>Xr,env:()=>Vr,execArgv:()=>Yr,execPath:()=>Rn,exit:()=>mn,features:()=>vn,hasUncaughtExceptionCaptureCallback:()=>Mo,hrtime:()=>er,kill:()=>gn,listeners:()=>jo,memoryUsage:()=>pn,moduleLoadList:()=>an,nextTick:()=>xo,off:()=>Hn,on:()=>nt,once:()=>qn,openStdin:()=>bn,pid:()=>Pn,platform:()=>Kr,ppid:()=>Mn,prependListener:()=>Gn,prependOnceListener:()=>Yn,reallyExit:()=>hn,release:()=>nn,removeAllListeners:()=>Kn,removeListener:()=>zn,resourceUsage:()=>dn,setSourceMapsEnabled:()=>Un,setUncaughtExceptionCaptureCallback:()=>_n,stderr:()=>Tn,stdin:()=>Cn,stdout:()=>In,title:()=>Hr,umask:()=>en,uptime:()=>Ro,version:()=>Qr,versions:()=>Jr});function qr(c){throw new Error("Node.js process "+c+" is not supported by JSPM core outside of Node.js")}function oc(){!wt||!_t||(wt=!1,_t.length?Ye=_t.concat(Ye):Dt=-1,Ye.length&&Eo())}function Eo(){if(!wt){var c=setTimeout(oc,0);wt=!0;for(var e=Ye.length;e;){for(_t=Ye,Ye=[];++Dt<e;)_t&&_t[Dt].run();Dt=-1,e=Ye.length}_t=null,wt=!1,clearTimeout(c)}}function xo(c){var e=new Array(arguments.length-1);if(arguments.length>1)for(var t=1;t<arguments.length;t++)e[t-1]=arguments[t];Ye.push(new Ao(c,e)),Ye.length===1&&!wt&&setTimeout(Eo,0)}function Ao(c,e){this.fun=c,this.array=e}function Be(){}function Io(c){qr("_linkedBinding")}function To(c){qr("dlopen")}function Co(){return[]}function Oo(){return[]}function Po(c,e){if(!c)throw new Error(e||"assertion error")}function Mo(){return!1}function Ro(){return it.now()/1e3}function er(c){var e=Math.floor((Date.now()-it.now())*.001),t=it.now()*.001,r=Math.floor(t)+e,a=Math.floor(t%1*1e9);return c&&(r=r-c[0],a=a-c[1],a<0&&(r--,a+=tr)),[r,a]}function nt(){return Qn}function jo(c){return[]}var Ye,wt,_t,Dt,Hr,zr,Kr,Vr,Gr,Yr,Qr,Jr,Xr,Zr,en,tn,rn,nn,on,sn,an,ln,cn,un,hn,fn,$t,dn,pn,gn,mn,bn,yn,vn,wn,_n,kn,Sn,En,xn,An,In,Tn,Cn,On,Pn,Mn,Rn,jn,Ln,Nn,Un,it,Bn,tr,Fn,Dn,$n,Wn,qn,Hn,zn,Kn,Vn,Gn,Yn,Qn,sc=He(()=>{le(),ue(),ce(),Ye=[],wt=!1,Dt=-1,Ao.prototype.run=function(){this.fun.apply(null,this.array)},Hr="browser",zr="x64",Kr="browser",Vr={PATH:"/usr/bin",LANG:typeof navigator<"u"?navigator.language+".UTF-8":void 0,PWD:"/",HOME:"/home",TMP:"/tmp"},Gr=["/usr/bin/node"],Yr=[],Qr="v16.8.0",Jr={},Xr=function(c,e){console.warn((e?e+": ":"")+c)},Zr=function(c){qr("binding")},en=function(c){return 0},tn=function(){return"/"},rn=function(c){},nn={name:"node",sourceUrl:"",headersUrl:"",libUrl:""},on=!0,sn=Be,an=[],ln={},cn=!1,un={},hn=Be,fn=Be,$t=function(){return{}},dn=$t,pn=$t,gn=Be,mn=Be,bn=Be,yn={},vn={inspector:!1,debug:!1,uv:!1,ipv6:!1,tls_alpn:!1,tls_sni:!1,tls_ocsp:!1,tls:!1,cached_builtins:!0},wn=Be,_n=Be,kn=Be,Sn=Be,En=Be,xn=Be,An=Be,In=void 0,Tn=void 0,Cn=void 0,On=Be,Pn=2,Mn=1,Rn="/bin/usr/node",jn=9229,Ln="node",Nn=[],Un=Be,it={now:typeof performance<"u"?performance.now.bind(performance):void 0,timing:typeof performance<"u"?performance.timing:void 0},it.now===void 0&&(Bn=Date.now(),it.timing&&it.timing.navigationStart&&(Bn=it.timing.navigationStart),it.now=()=>Date.now()-Bn),tr=1e9,er.bigint=function(c){var e=er(c);return typeof BigInt>"u"?e[0]*tr+e[1]:BigInt(e[0]*tr)+BigInt(e[1])},Fn=10,Dn={},$n=0,Wn=nt,qn=nt,Hn=nt,zn=nt,Kn=nt,Vn=Be,Gn=nt,Yn=nt,Qn={version:Qr,versions:Jr,arch:zr,platform:Kr,browser:on,release:nn,_rawDebug:sn,moduleLoadList:an,binding:Zr,_linkedBinding:Io,_events:Dn,_eventsCount:$n,_maxListeners:Fn,on:nt,addListener:Wn,once:qn,off:Hn,removeListener:zn,removeAllListeners:Kn,emit:Vn,prependListener:Gn,prependOnceListener:Yn,listeners:jo,domain:ln,_exiting:cn,config:un,dlopen:To,uptime:Ro,_getActiveRequests:Co,_getActiveHandles:Oo,reallyExit:hn,_kill:fn,cpuUsage:$t,resourceUsage:dn,memoryUsage:pn,kill:gn,exit:mn,openStdin:bn,allowedNodeEnvironmentFlags:yn,assert:Po,features:vn,_fatalExceptions:wn,setUncaughtExceptionCaptureCallback:_n,hasUncaughtExceptionCaptureCallback:Mo,emitWarning:Xr,nextTick:xo,_tickCallback:kn,_debugProcess:Sn,_debugEnd:En,_startProfilerIdleNotifier:xn,_stopProfilerIdleNotifier:An,stdout:In,stdin:Cn,stderr:Tn,abort:On,umask:en,chdir:rn,cwd:tn,env:Vr,title:Hr,argv:Gr,execArgv:Yr,pid:Pn,ppid:Mn,execPath:Rn,debugPort:jn,hrtime:er,argv0:Ln,_preload_modules:Nn,setSourceMapsEnabled:Un}}),ce=He(()=>{sc()});function ac(){if(Jn)return Ot;Jn=!0,Ot.byteLength=s,Ot.toByteArray=l,Ot.fromByteArray=p;for(var c=[],e=[],t=typeof Uint8Array<"u"?Uint8Array:Array,r="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",a=0,n=r.length;a<n;++a)c[a]=r[a],e[r.charCodeAt(a)]=a;e[45]=62,e[95]=63;function i(y){var f=y.length;if(f%4>0)throw new Error("Invalid string. Length must be a multiple of 4");var g=y.indexOf("=");g===-1&&(g=f);var b=g===f?0:4-g%4;return[g,b]}function s(y){var f=i(y),g=f[0],b=f[1];return(g+b)*3/4-b}function o(y,f,g){return(f+g)*3/4-g}function l(y){var f,g=i(y),b=g[0],k=g[1],m=new t(o(y,b,k)),w=0,E=k>0?b-4:b,v;for(v=0;v<E;v+=4)f=e[y.charCodeAt(v)]<<18|e[y.charCodeAt(v+1)]<<12|e[y.charCodeAt(v+2)]<<6|e[y.charCodeAt(v+3)],m[w++]=f>>16&255,m[w++]=f>>8&255,m[w++]=f&255;return k===2&&(f=e[y.charCodeAt(v)]<<2|e[y.charCodeAt(v+1)]>>4,m[w++]=f&255),k===1&&(f=e[y.charCodeAt(v)]<<10|e[y.charCodeAt(v+1)]<<4|e[y.charCodeAt(v+2)]>>2,m[w++]=f>>8&255,m[w++]=f&255),m}function u(y){return c[y>>18&63]+c[y>>12&63]+c[y>>6&63]+c[y&63]}function d(y,f,g){for(var b,k=[],m=f;m<g;m+=3)b=(y[m]<<16&16711680)+(y[m+1]<<8&65280)+(y[m+2]&255),k.push(u(b));return k.join("")}function p(y){for(var f,g=y.length,b=g%3,k=[],m=16383,w=0,E=g-b;w<E;w+=m)k.push(d(y,w,w+m>E?E:w+m));return b===1?(f=y[g-1],k.push(c[f>>2]+c[f<<4&63]+"==")):b===2&&(f=(y[g-2]<<8)+y[g-1],k.push(c[f>>10]+c[f>>4&63]+c[f<<2&63]+"=")),k.join("")}return Ot}function lc(){return Xn?Wt:(Xn=!0,Wt.read=function(c,e,t,r,a){var n,i,s=a*8-r-1,o=(1<<s)-1,l=o>>1,u=-7,d=t?a-1:0,p=t?-1:1,y=c[e+d];for(d+=p,n=y&(1<<-u)-1,y>>=-u,u+=s;u>0;n=n*256+c[e+d],d+=p,u-=8);for(i=n&(1<<-u)-1,n>>=-u,u+=r;u>0;i=i*256+c[e+d],d+=p,u-=8);if(n===0)n=1-l;else{if(n===o)return i?NaN:(y?-1:1)*(1/0);i=i+Math.pow(2,r),n=n-l}return(y?-1:1)*i*Math.pow(2,n-r)},Wt.write=function(c,e,t,r,a,n){var i,s,o,l=n*8-a-1,u=(1<<l)-1,d=u>>1,p=a===23?Math.pow(2,-24)-Math.pow(2,-77):0,y=r?0:n-1,f=r?1:-1,g=e<0||e===0&&1/e<0?1:0;for(e=Math.abs(e),isNaN(e)||e===1/0?(s=isNaN(e)?1:0,i=u):(i=Math.floor(Math.log(e)/Math.LN2),e*(o=Math.pow(2,-i))<1&&(i--,o*=2),i+d>=1?e+=p/o:e+=p*Math.pow(2,1-d),e*o>=2&&(i++,o/=2),i+d>=u?(s=0,i=u):i+d>=1?(s=(e*o-1)*Math.pow(2,a),i=i+d):(s=e*Math.pow(2,d-1)*Math.pow(2,a),i=0));a>=8;c[t+y]=s&255,y+=f,s/=256,a-=8);for(i=i<<a|s,l+=a;l>0;c[t+y]=i&255,y+=f,i/=256,l-=8);c[t+y-f]|=g*128},Wt)}function cc(){if(Zn)return dt;Zn=!0;let c=ac(),e=lc(),t=typeof Symbol=="function"&&typeof Symbol.for=="function"?Symbol.for("nodejs.util.inspect.custom"):null;dt.Buffer=i,dt.SlowBuffer=k,dt.INSPECT_MAX_BYTES=50;let r=2147483647;dt.kMaxLength=r,i.TYPED_ARRAY_SUPPORT=a(),!i.TYPED_ARRAY_SUPPORT&&typeof console<"u"&&typeof console.error=="function"&&console.error("This browser lacks typed array (Uint8Array) support which is required by `buffer` v5.x. Use `buffer` v4.x if you require old browser support.");function a(){try{let h=new Uint8Array(1),_={foo:function(){return 42}};return Object.setPrototypeOf(_,Uint8Array.prototype),Object.setPrototypeOf(h,_),h.foo()===42}catch{return!1}}Object.defineProperty(i.prototype,"parent",{enumerable:!0,get:function(){if(i.isBuffer(this))return this.buffer}}),Object.defineProperty(i.prototype,"offset",{enumerable:!0,get:function(){if(i.isBuffer(this))return this.byteOffset}});function n(h){if(h>r)throw new RangeError('The value "'+h+'" is invalid for option "size"');let _=new Uint8Array(h);return Object.setPrototypeOf(_,i.prototype),_}function i(h,_,A){if(typeof h=="number"){if(typeof _=="string")throw new TypeError('The "string" argument must be of type string. Received type number');return u(h)}return s(h,_,A)}i.poolSize=8192;function s(h,_,A){if(typeof h=="string")return d(h,_);if(ArrayBuffer.isView(h))return y(h);if(h==null)throw new TypeError("The first argument must be one of type string, Buffer, ArrayBuffer, Array, or Array-like Object. Received type "+typeof h);if(q(h,ArrayBuffer)||h&&q(h.buffer,ArrayBuffer)||typeof SharedArrayBuffer<"u"&&(q(h,SharedArrayBuffer)||h&&q(h.buffer,SharedArrayBuffer)))return f(h,_,A);if(typeof h=="number")throw new TypeError('The "value" argument must not be of type number. Received type number');let U=h.valueOf&&h.valueOf();if(U!=null&&U!==h)return i.from(U,_,A);let X=g(h);if(X)return X;if(typeof Symbol<"u"&&Symbol.toPrimitive!=null&&typeof h[Symbol.toPrimitive]=="function")return i.from(h[Symbol.toPrimitive]("string"),_,A);throw new TypeError("The first argument must be one of type string, Buffer, ArrayBuffer, Array, or Array-like Object. Received type "+typeof h)}i.from=function(h,_,A){return s(h,_,A)},Object.setPrototypeOf(i.prototype,Uint8Array.prototype),Object.setPrototypeOf(i,Uint8Array);function o(h){if(typeof h!="number")throw new TypeError('"size" argument must be of type number');if(h<0)throw new RangeError('The value "'+h+'" is invalid for option "size"')}function l(h,_,A){return o(h),h<=0?n(h):_!==void 0?typeof A=="string"?n(h).fill(_,A):n(h).fill(_):n(h)}i.alloc=function(h,_,A){return l(h,_,A)};function u(h){return o(h),n(h<0?0:b(h)|0)}i.allocUnsafe=function(h){return u(h)},i.allocUnsafeSlow=function(h){return u(h)};function d(h,_){if((typeof _!="string"||_==="")&&(_="utf8"),!i.isEncoding(_))throw new TypeError("Unknown encoding: "+_);let A=m(h,_)|0,U=n(A),X=U.write(h,_);return X!==A&&(U=U.slice(0,X)),U}function p(h){let _=h.length<0?0:b(h.length)|0,A=n(_);for(let U=0;U<_;U+=1)A[U]=h[U]&255;return A}function y(h){if(q(h,Uint8Array)){let _=new Uint8Array(h);return f(_.buffer,_.byteOffset,_.byteLength)}return p(h)}function f(h,_,A){if(_<0||h.byteLength<_)throw new RangeError('"offset" is outside of buffer bounds');if(h.byteLength<_+(A||0))throw new RangeError('"length" is outside of buffer bounds');let U;return _===void 0&&A===void 0?U=new Uint8Array(h):A===void 0?U=new Uint8Array(h,_):U=new Uint8Array(h,_,A),Object.setPrototypeOf(U,i.prototype),U}function g(h){if(i.isBuffer(h)){let _=b(h.length)|0,A=n(_);return A.length===0||h.copy(A,0,0,_),A}if(h.length!==void 0)return typeof h.length!="number"||ge(h.length)?n(0):p(h);if(h.type==="Buffer"&&Array.isArray(h.data))return p(h.data)}function b(h){if(h>=r)throw new RangeError("Attempt to allocate Buffer larger than maximum size: 0x"+r.toString(16)+" bytes");return h|0}function k(h){return+h!=h&&(h=0),i.alloc(+h)}i.isBuffer=function(h){return h!=null&&h._isBuffer===!0&&h!==i.prototype},i.compare=function(h,_){if(q(h,Uint8Array)&&(h=i.from(h,h.offset,h.byteLength)),q(_,Uint8Array)&&(_=i.from(_,_.offset,_.byteLength)),!i.isBuffer(h)||!i.isBuffer(_))throw new TypeError('The "buf1", "buf2" arguments must be one of type Buffer or Uint8Array');if(h===_)return 0;let A=h.length,U=_.length;for(let X=0,he=Math.min(A,U);X<he;++X)if(h[X]!==_[X]){A=h[X],U=_[X];break}return A<U?-1:U<A?1:0},i.isEncoding=function(h){switch(String(h).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}},i.concat=function(h,_){if(!Array.isArray(h))throw new TypeError('"list" argument must be an Array of Buffers');if(h.length===0)return i.alloc(0);let A;if(_===void 0)for(_=0,A=0;A<h.length;++A)_+=h[A].length;let U=i.allocUnsafe(_),X=0;for(A=0;A<h.length;++A){let he=h[A];if(q(he,Uint8Array))X+he.length>U.length?(i.isBuffer(he)||(he=i.from(he)),he.copy(U,X)):Uint8Array.prototype.set.call(U,he,X);else if(i.isBuffer(he))he.copy(U,X);else throw new TypeError('"list" argument must be an Array of Buffers');X+=he.length}return U};function m(h,_){if(i.isBuffer(h))return h.length;if(ArrayBuffer.isView(h)||q(h,ArrayBuffer))return h.byteLength;if(typeof h!="string")throw new TypeError('The "string" argument must be one of type string, Buffer, or ArrayBuffer. Received type '+typeof h);let A=h.length,U=arguments.length>2&&arguments[2]===!0;if(!U&&A===0)return 0;let X=!1;for(;;)switch(_){case"ascii":case"latin1":case"binary":return A;case"utf8":case"utf-8":return $(h).length;case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return A*2;case"hex":return A>>>1;case"base64":return de(h).length;default:if(X)return U?-1:$(h).length;_=(""+_).toLowerCase(),X=!0}}i.byteLength=m;function w(h,_,A){let U=!1;if((_===void 0||_<0)&&(_=0),_>this.length||((A===void 0||A>this.length)&&(A=this.length),A<=0)||(A>>>=0,_>>>=0,A<=_))return"";for(h||(h="utf8");;)switch(h){case"hex":return K(this,_,A);case"utf8":case"utf-8":return W(this,_,A);case"ascii":return ae(this,_,A);case"latin1":case"binary":return Y(this,_,A);case"base64":return T(this,_,A);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return re(this,_,A);default:if(U)throw new TypeError("Unknown encoding: "+h);h=(h+"").toLowerCase(),U=!0}}i.prototype._isBuffer=!0;function E(h,_,A){let U=h[_];h[_]=h[A],h[A]=U}i.prototype.swap16=function(){let h=this.length;if(h%2!==0)throw new RangeError("Buffer size must be a multiple of 16-bits");for(let _=0;_<h;_+=2)E(this,_,_+1);return this},i.prototype.swap32=function(){let h=this.length;if(h%4!==0)throw new RangeError("Buffer size must be a multiple of 32-bits");for(let _=0;_<h;_+=4)E(this,_,_+3),E(this,_+1,_+2);return this},i.prototype.swap64=function(){let h=this.length;if(h%8!==0)throw new RangeError("Buffer size must be a multiple of 64-bits");for(let _=0;_<h;_+=8)E(this,_,_+7),E(this,_+1,_+6),E(this,_+2,_+5),E(this,_+3,_+4);return this},i.prototype.toString=function(){let h=this.length;return h===0?"":arguments.length===0?W(this,0,h):w.apply(this,arguments)},i.prototype.toLocaleString=i.prototype.toString,i.prototype.equals=function(h){if(!i.isBuffer(h))throw new TypeError("Argument must be a Buffer");return this===h?!0:i.compare(this,h)===0},i.prototype.inspect=function(){let h="",_=dt.INSPECT_MAX_BYTES;return h=this.toString("hex",0,_).replace(/(.{2})/g,"$1 ").trim(),this.length>_&&(h+=" ... "),"<Buffer "+h+">"},t&&(i.prototype[t]=i.prototype.inspect),i.prototype.compare=function(h,_,A,U,X){if(q(h,Uint8Array)&&(h=i.from(h,h.offset,h.byteLength)),!i.isBuffer(h))throw new TypeError('The "target" argument must be one of type Buffer or Uint8Array. Received type '+typeof h);if(_===void 0&&(_=0),A===void 0&&(A=h?h.length:0),U===void 0&&(U=0),X===void 0&&(X=this.length),_<0||A>h.length||U<0||X>this.length)throw new RangeError("out of range index");if(U>=X&&_>=A)return 0;if(U>=X)return-1;if(_>=A)return 1;if(_>>>=0,A>>>=0,U>>>=0,X>>>=0,this===h)return 0;let he=X-U,ke=A-_,z=Math.min(he,ke),ie=this.slice(U,X),xe=h.slice(_,A);for(let Ae=0;Ae<z;++Ae)if(ie[Ae]!==xe[Ae]){he=ie[Ae],ke=xe[Ae];break}return he<ke?-1:ke<he?1:0};function v(h,_,A,U,X){if(h.length===0)return-1;if(typeof A=="string"?(U=A,A=0):A>2147483647?A=2147483647:A<-2147483648&&(A=-2147483648),A=+A,ge(A)&&(A=X?0:h.length-1),A<0&&(A=h.length+A),A>=h.length){if(X)return-1;A=h.length-1}else if(A<0)if(X)A=0;else return-1;if(typeof _=="string"&&(_=i.from(_,U)),i.isBuffer(_))return _.length===0?-1:x(h,_,A,U,X);if(typeof _=="number")return _=_&255,typeof Uint8Array.prototype.indexOf=="function"?X?Uint8Array.prototype.indexOf.call(h,_,A):Uint8Array.prototype.lastIndexOf.call(h,_,A):x(h,[_],A,U,X);throw new TypeError("val must be string, number or Buffer")}function x(h,_,A,U,X){let he=1,ke=h.length,z=_.length;if(U!==void 0&&(U=String(U).toLowerCase(),U==="ucs2"||U==="ucs-2"||U==="utf16le"||U==="utf-16le")){if(h.length<2||_.length<2)return-1;he=2,ke/=2,z/=2,A/=2}function ie(Ae,Ie){return he===1?Ae[Ie]:Ae.readUInt16BE(Ie*he)}let xe;if(X){let Ae=-1;for(xe=A;xe<ke;xe++)if(ie(h,xe)===ie(_,Ae===-1?0:xe-Ae)){if(Ae===-1&&(Ae=xe),xe-Ae+1===z)return Ae*he}else Ae!==-1&&(xe-=xe-Ae),Ae=-1}else for(A+z>ke&&(A=ke-z),xe=A;xe>=0;xe--){let Ae=!0;for(let Ie=0;Ie<z;Ie++)if(ie(h,xe+Ie)!==ie(_,Ie)){Ae=!1;break}if(Ae)return xe}return-1}i.prototype.includes=function(h,_,A){return this.indexOf(h,_,A)!==-1},i.prototype.indexOf=function(h,_,A){return v(this,h,_,A,!0)},i.prototype.lastIndexOf=function(h,_,A){return v(this,h,_,A,!1)};function S(h,_,A,U){A=Number(A)||0;let X=h.length-A;U?(U=Number(U),U>X&&(U=X)):U=X;let he=_.length;U>he/2&&(U=he/2);let ke;for(ke=0;ke<U;++ke){let z=parseInt(_.substr(ke*2,2),16);if(ge(z))return ke;h[A+ke]=z}return ke}function I(h,_,A,U){return ye($(_,h.length-A),h,A,U)}function M(h,_,A,U){return ye(ee(_),h,A,U)}function O(h,_,A,U){return ye(de(_),h,A,U)}function B(h,_,A,U){return ye(fe(_,h.length-A),h,A,U)}i.prototype.write=function(h,_,A,U){if(_===void 0)U="utf8",A=this.length,_=0;else if(A===void 0&&typeof _=="string")U=_,A=this.length,_=0;else if(isFinite(_))_=_>>>0,isFinite(A)?(A=A>>>0,U===void 0&&(U="utf8")):(U=A,A=void 0);else throw new Error("Buffer.write(string, encoding, offset[, length]) is no longer supported");let X=this.length-_;if((A===void 0||A>X)&&(A=X),h.length>0&&(A<0||_<0)||_>this.length)throw new RangeError("Attempt to write outside buffer bounds");U||(U="utf8");let he=!1;for(;;)switch(U){case"hex":return S(this,h,_,A);case"utf8":case"utf-8":return I(this,h,_,A);case"ascii":case"latin1":case"binary":return M(this,h,_,A);case"base64":return O(this,h,_,A);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return B(this,h,_,A);default:if(he)throw new TypeError("Unknown encoding: "+U);U=(""+U).toLowerCase(),he=!0}},i.prototype.toJSON=function(){return{type:"Buffer",data:Array.prototype.slice.call(this._arr||this,0)}};function T(h,_,A){return _===0&&A===h.length?c.fromByteArray(h):c.fromByteArray(h.slice(_,A))}function W(h,_,A){A=Math.min(h.length,A);let U=[],X=_;for(;X<A;){let he=h[X],ke=null,z=he>239?4:he>223?3:he>191?2:1;if(X+z<=A){let ie,xe,Ae,Ie;switch(z){case 1:he<128&&(ke=he);break;case 2:ie=h[X+1],(ie&192)===128&&(Ie=(he&31)<<6|ie&63,Ie>127&&(ke=Ie));break;case 3:ie=h[X+1],xe=h[X+2],(ie&192)===128&&(xe&192)===128&&(Ie=(he&15)<<12|(ie&63)<<6|xe&63,Ie>2047&&(Ie<55296||Ie>57343)&&(ke=Ie));break;case 4:ie=h[X+1],xe=h[X+2],Ae=h[X+3],(ie&192)===128&&(xe&192)===128&&(Ae&192)===128&&(Ie=(he&15)<<18|(ie&63)<<12|(xe&63)<<6|Ae&63,Ie>65535&&Ie<1114112&&(ke=Ie))}}ke===null?(ke=65533,z=1):ke>65535&&(ke-=65536,U.push(ke>>>10&1023|55296),ke=56320|ke&1023),U.push(ke),X+=z}return N(U)}let F=4096;function N(h){let _=h.length;if(_<=F)return String.fromCharCode.apply(String,h);let A="",U=0;for(;U<_;)A+=String.fromCharCode.apply(String,h.slice(U,U+=F));return A}function ae(h,_,A){let U="";A=Math.min(h.length,A);for(let X=_;X<A;++X)U+=String.fromCharCode(h[X]&127);return U}function Y(h,_,A){let U="";A=Math.min(h.length,A);for(let X=_;X<A;++X)U+=String.fromCharCode(h[X]);return U}function K(h,_,A){let U=h.length;(!_||_<0)&&(_=0),(!A||A<0||A>U)&&(A=U);let X="";for(let he=_;he<A;++he)X+=ve[h[he]];return X}function re(h,_,A){let U=h.slice(_,A),X="";for(let he=0;he<U.length-1;he+=2)X+=String.fromCharCode(U[he]+U[he+1]*256);return X}i.prototype.slice=function(h,_){let A=this.length;h=~~h,_=_===void 0?A:~~_,h<0?(h+=A,h<0&&(h=0)):h>A&&(h=A),_<0?(_+=A,_<0&&(_=0)):_>A&&(_=A),_<h&&(_=h);let U=this.subarray(h,_);return Object.setPrototypeOf(U,i.prototype),U};function D(h,_,A){if(h%1!==0||h<0)throw new RangeError("offset is not uint");if(h+_>A)throw new RangeError("Trying to access beyond buffer length")}i.prototype.readUintLE=i.prototype.readUIntLE=function(h,_,A){h=h>>>0,_=_>>>0,A||D(h,_,this.length);let U=this[h],X=1,he=0;for(;++he<_&&(X*=256);)U+=this[h+he]*X;return U},i.prototype.readUintBE=i.prototype.readUIntBE=function(h,_,A){h=h>>>0,_=_>>>0,A||D(h,_,this.length);let U=this[h+--_],X=1;for(;_>0&&(X*=256);)U+=this[h+--_]*X;return U},i.prototype.readUint8=i.prototype.readUInt8=function(h,_){return h=h>>>0,_||D(h,1,this.length),this[h]},i.prototype.readUint16LE=i.prototype.readUInt16LE=function(h,_){return h=h>>>0,_||D(h,2,this.length),this[h]|this[h+1]<<8},i.prototype.readUint16BE=i.prototype.readUInt16BE=function(h,_){return h=h>>>0,_||D(h,2,this.length),this[h]<<8|this[h+1]},i.prototype.readUint32LE=i.prototype.readUInt32LE=function(h,_){return h=h>>>0,_||D(h,4,this.length),(this[h]|this[h+1]<<8|this[h+2]<<16)+this[h+3]*16777216},i.prototype.readUint32BE=i.prototype.readUInt32BE=function(h,_){return h=h>>>0,_||D(h,4,this.length),this[h]*16777216+(this[h+1]<<16|this[h+2]<<8|this[h+3])},i.prototype.readBigUInt64LE=se(function(h){h=h>>>0,Q(h,"offset");let _=this[h],A=this[h+7];(_===void 0||A===void 0)&&me(h,this.length-8);let U=_+this[++h]*2**8+this[++h]*2**16+this[++h]*2**24,X=this[++h]+this[++h]*2**8+this[++h]*2**16+A*2**24;return BigInt(U)+(BigInt(X)<<BigInt(32))}),i.prototype.readBigUInt64BE=se(function(h){h=h>>>0,Q(h,"offset");let _=this[h],A=this[h+7];(_===void 0||A===void 0)&&me(h,this.length-8);let U=_*2**24+this[++h]*2**16+this[++h]*2**8+this[++h],X=this[++h]*2**24+this[++h]*2**16+this[++h]*2**8+A;return(BigInt(U)<<BigInt(32))+BigInt(X)}),i.prototype.readIntLE=function(h,_,A){h=h>>>0,_=_>>>0,A||D(h,_,this.length);let U=this[h],X=1,he=0;for(;++he<_&&(X*=256);)U+=this[h+he]*X;return X*=128,U>=X&&(U-=Math.pow(2,8*_)),U},i.prototype.readIntBE=function(h,_,A){h=h>>>0,_=_>>>0,A||D(h,_,this.length);let U=_,X=1,he=this[h+--U];for(;U>0&&(X*=256);)he+=this[h+--U]*X;return X*=128,he>=X&&(he-=Math.pow(2,8*_)),he},i.prototype.readInt8=function(h,_){return h=h>>>0,_||D(h,1,this.length),this[h]&128?(255-this[h]+1)*-1:this[h]},i.prototype.readInt16LE=function(h,_){h=h>>>0,_||D(h,2,this.length);let A=this[h]|this[h+1]<<8;return A&32768?A|4294901760:A},i.prototype.readInt16BE=function(h,_){h=h>>>0,_||D(h,2,this.length);let A=this[h+1]|this[h]<<8;return A&32768?A|4294901760:A},i.prototype.readInt32LE=function(h,_){return h=h>>>0,_||D(h,4,this.length),this[h]|this[h+1]<<8|this[h+2]<<16|this[h+3]<<24},i.prototype.readInt32BE=function(h,_){return h=h>>>0,_||D(h,4,this.length),this[h]<<24|this[h+1]<<16|this[h+2]<<8|this[h+3]},i.prototype.readBigInt64LE=se(function(h){h=h>>>0,Q(h,"offset");let _=this[h],A=this[h+7];(_===void 0||A===void 0)&&me(h,this.length-8);let U=this[h+4]+this[h+5]*2**8+this[h+6]*2**16+(A<<24);return(BigInt(U)<<BigInt(32))+BigInt(_+this[++h]*256+this[++h]*65536+this[++h]*16777216)}),i.prototype.readBigInt64BE=se(function(h){h=h>>>0,Q(h,"offset");let _=this[h],A=this[h+7];(_===void 0||A===void 0)&&me(h,this.length-8);let U=(_<<24)+this[++h]*2**16+this[++h]*2**8+this[++h];return(BigInt(U)<<BigInt(32))+BigInt(this[++h]*16777216+this[++h]*65536+this[++h]*256+A)}),i.prototype.readFloatLE=function(h,_){return h=h>>>0,_||D(h,4,this.length),e.read(this,h,!0,23,4)},i.prototype.readFloatBE=function(h,_){return h=h>>>0,_||D(h,4,this.length),e.read(this,h,!1,23,4)},i.prototype.readDoubleLE=function(h,_){return h=h>>>0,_||D(h,8,this.length),e.read(this,h,!0,52,8)},i.prototype.readDoubleBE=function(h,_){return h=h>>>0,_||D(h,8,this.length),e.read(this,h,!1,52,8)};function Z(h,_,A,U,X,he){if(!i.isBuffer(h))throw new TypeError('"buffer" argument must be a Buffer instance');if(_>X||_<he)throw new RangeError('"value" argument is out of bounds');if(A+U>h.length)throw new RangeError("Index out of range")}i.prototype.writeUintLE=i.prototype.writeUIntLE=function(h,_,A,U){if(h=+h,_=_>>>0,A=A>>>0,!U){let ke=Math.pow(2,8*A)-1;Z(this,h,_,A,ke,0)}let X=1,he=0;for(this[_]=h&255;++he<A&&(X*=256);)this[_+he]=h/X&255;return _+A},i.prototype.writeUintBE=i.prototype.writeUIntBE=function(h,_,A,U){if(h=+h,_=_>>>0,A=A>>>0,!U){let ke=Math.pow(2,8*A)-1;Z(this,h,_,A,ke,0)}let X=A-1,he=1;for(this[_+X]=h&255;--X>=0&&(he*=256);)this[_+X]=h/he&255;return _+A},i.prototype.writeUint8=i.prototype.writeUInt8=function(h,_,A){return h=+h,_=_>>>0,A||Z(this,h,_,1,255,0),this[_]=h&255,_+1},i.prototype.writeUint16LE=i.prototype.writeUInt16LE=function(h,_,A){return h=+h,_=_>>>0,A||Z(this,h,_,2,65535,0),this[_]=h&255,this[_+1]=h>>>8,_+2},i.prototype.writeUint16BE=i.prototype.writeUInt16BE=function(h,_,A){return h=+h,_=_>>>0,A||Z(this,h,_,2,65535,0),this[_]=h>>>8,this[_+1]=h&255,_+2},i.prototype.writeUint32LE=i.prototype.writeUInt32LE=function(h,_,A){return h=+h,_=_>>>0,A||Z(this,h,_,4,4294967295,0),this[_+3]=h>>>24,this[_+2]=h>>>16,this[_+1]=h>>>8,this[_]=h&255,_+4},i.prototype.writeUint32BE=i.prototype.writeUInt32BE=function(h,_,A){return h=+h,_=_>>>0,A||Z(this,h,_,4,4294967295,0),this[_]=h>>>24,this[_+1]=h>>>16,this[_+2]=h>>>8,this[_+3]=h&255,_+4};function P(h,_,A,U,X){G(_,U,X,h,A,7);let he=Number(_&BigInt(4294967295));h[A++]=he,he=he>>8,h[A++]=he,he=he>>8,h[A++]=he,he=he>>8,h[A++]=he;let ke=Number(_>>BigInt(32)&BigInt(4294967295));return h[A++]=ke,ke=ke>>8,h[A++]=ke,ke=ke>>8,h[A++]=ke,ke=ke>>8,h[A++]=ke,A}function J(h,_,A,U,X){G(_,U,X,h,A,7);let he=Number(_&BigInt(4294967295));h[A+7]=he,he=he>>8,h[A+6]=he,he=he>>8,h[A+5]=he,he=he>>8,h[A+4]=he;let ke=Number(_>>BigInt(32)&BigInt(4294967295));return h[A+3]=ke,ke=ke>>8,h[A+2]=ke,ke=ke>>8,h[A+1]=ke,ke=ke>>8,h[A]=ke,A+8}i.prototype.writeBigUInt64LE=se(function(h,_=0){return P(this,h,_,BigInt(0),BigInt("0xffffffffffffffff"))}),i.prototype.writeBigUInt64BE=se(function(h,_=0){return J(this,h,_,BigInt(0),BigInt("0xffffffffffffffff"))}),i.prototype.writeIntLE=function(h,_,A,U){if(h=+h,_=_>>>0,!U){let z=Math.pow(2,8*A-1);Z(this,h,_,A,z-1,-z)}let X=0,he=1,ke=0;for(this[_]=h&255;++X<A&&(he*=256);)h<0&&ke===0&&this[_+X-1]!==0&&(ke=1),this[_+X]=(h/he>>0)-ke&255;return _+A},i.prototype.writeIntBE=function(h,_,A,U){if(h=+h,_=_>>>0,!U){let z=Math.pow(2,8*A-1);Z(this,h,_,A,z-1,-z)}let X=A-1,he=1,ke=0;for(this[_+X]=h&255;--X>=0&&(he*=256);)h<0&&ke===0&&this[_+X+1]!==0&&(ke=1),this[_+X]=(h/he>>0)-ke&255;return _+A},i.prototype.writeInt8=function(h,_,A){return h=+h,_=_>>>0,A||Z(this,h,_,1,127,-128),h<0&&(h=255+h+1),this[_]=h&255,_+1},i.prototype.writeInt16LE=function(h,_,A){return h=+h,_=_>>>0,A||Z(this,h,_,2,32767,-32768),this[_]=h&255,this[_+1]=h>>>8,_+2},i.prototype.writeInt16BE=function(h,_,A){return h=+h,_=_>>>0,A||Z(this,h,_,2,32767,-32768),this[_]=h>>>8,this[_+1]=h&255,_+2},i.prototype.writeInt32LE=function(h,_,A){return h=+h,_=_>>>0,A||Z(this,h,_,4,2147483647,-2147483648),this[_]=h&255,this[_+1]=h>>>8,this[_+2]=h>>>16,this[_+3]=h>>>24,_+4},i.prototype.writeInt32BE=function(h,_,A){return h=+h,_=_>>>0,A||Z(this,h,_,4,2147483647,-2147483648),h<0&&(h=4294967295+h+1),this[_]=h>>>24,this[_+1]=h>>>16,this[_+2]=h>>>8,this[_+3]=h&255,_+4},i.prototype.writeBigInt64LE=se(function(h,_=0){return P(this,h,_,-BigInt("0x8000000000000000"),BigInt("0x7fffffffffffffff"))}),i.prototype.writeBigInt64BE=se(function(h,_=0){return J(this,h,_,-BigInt("0x8000000000000000"),BigInt("0x7fffffffffffffff"))});function be(h,_,A,U,X,he){if(A+U>h.length)throw new RangeError("Index out of range");if(A<0)throw new RangeError("Index out of range")}function te(h,_,A,U,X){return _=+_,A=A>>>0,X||be(h,_,A,4),e.write(h,_,A,U,23,4),A+4}i.prototype.writeFloatLE=function(h,_,A){return te(this,h,_,!0,A)},i.prototype.writeFloatBE=function(h,_,A){return te(this,h,_,!1,A)};function we(h,_,A,U,X){return _=+_,A=A>>>0,X||be(h,_,A,8),e.write(h,_,A,U,52,8),A+8}i.prototype.writeDoubleLE=function(h,_,A){return we(this,h,_,!0,A)},i.prototype.writeDoubleBE=function(h,_,A){return we(this,h,_,!1,A)},i.prototype.copy=function(h,_,A,U){if(!i.isBuffer(h))throw new TypeError("argument should be a Buffer");if(A||(A=0),!U&&U!==0&&(U=this.length),_>=h.length&&(_=h.length),_||(_=0),U>0&&U<A&&(U=A),U===A||h.length===0||this.length===0)return 0;if(_<0)throw new RangeError("targetStart out of bounds");if(A<0||A>=this.length)throw new RangeError("Index out of range");if(U<0)throw new RangeError("sourceEnd out of bounds");U>this.length&&(U=this.length),h.length-_<U-A&&(U=h.length-_+A);let X=U-A;return this===h&&typeof Uint8Array.prototype.copyWithin=="function"?this.copyWithin(_,A,U):Uint8Array.prototype.set.call(h,this.subarray(A,U),_),X},i.prototype.fill=function(h,_,A,U){if(typeof h=="string"){if(typeof _=="string"?(U=_,_=0,A=this.length):typeof A=="string"&&(U=A,A=this.length),U!==void 0&&typeof U!="string")throw new TypeError("encoding must be a string");if(typeof U=="string"&&!i.isEncoding(U))throw new TypeError("Unknown encoding: "+U);if(h.length===1){let he=h.charCodeAt(0);(U==="utf8"&&he<128||U==="latin1")&&(h=he)}}else typeof h=="number"?h=h&255:typeof h=="boolean"&&(h=Number(h));if(_<0||this.length<_||this.length<A)throw new RangeError("Out of range index");if(A<=_)return this;_=_>>>0,A=A===void 0?this.length:A>>>0,h||(h=0);let X;if(typeof h=="number")for(X=_;X<A;++X)this[X]=h;else{let he=i.isBuffer(h)?h:i.from(h,U),ke=he.length;if(ke===0)throw new TypeError('The value "'+h+'" is invalid for argument "value"');for(X=0;X<A-_;++X)this[X+_]=he[X%ke]}return this};let V={};function L(h,_,A){V[h]=class extends A{constructor(){super(),Object.defineProperty(this,"message",{value:_.apply(this,arguments),writable:!0,configurable:!0}),this.name=`${this.name} [${h}]`,this.stack,delete this.name}get code(){return h}set code(U){Object.defineProperty(this,"code",{configurable:!0,enumerable:!0,value:U,writable:!0})}toString(){return`${this.name} [${h}]: ${this.message}`}}}L("ERR_BUFFER_OUT_OF_BOUNDS",function(h){return h?`${h} is outside of buffer bounds`:"Attempt to access memory outside buffer bounds"},RangeError),L("ERR_INVALID_ARG_TYPE",function(h,_){return`The "${h}" argument must be of type number. Received type ${typeof _}`},TypeError),L("ERR_OUT_OF_RANGE",function(h,_,A){let U=`The value of "${h}" is out of range.`,X=A;return Number.isInteger(A)&&Math.abs(A)>4294967296?X=ne(String(A)):typeof A=="bigint"&&(X=String(A),(A>BigInt(2)**BigInt(32)||A<-(BigInt(2)**BigInt(32)))&&(X=ne(X)),X+="n"),U+=` It must be ${_}. Received ${X}`,U},RangeError);function ne(h){let _="",A=h.length,U=h[0]==="-"?1:0;for(;A>=U+4;A-=3)_=`_${h.slice(A-3,A)}${_}`;return`${h.slice(0,A)}${_}`}function H(h,_,A){Q(_,"offset"),(h[_]===void 0||h[_+A]===void 0)&&me(_,h.length-(A+1))}function G(h,_,A,U,X,he){if(h>A||h<_){let ke=typeof _=="bigint"?"n":"",z;throw _===0||_===BigInt(0)?z=`>= 0${ke} and < 2${ke} ** ${(he+1)*8}${ke}`:z=`>= -(2${ke} ** ${(he+1)*8-1}${ke}) and < 2 ** ${(he+1)*8-1}${ke}`,new V.ERR_OUT_OF_RANGE("value",z,h)}H(U,X,he)}function Q(h,_){if(typeof h!="number")throw new V.ERR_INVALID_ARG_TYPE(_,"number",h)}function me(h,_,A){throw Math.floor(h)!==h?(Q(h,A),new V.ERR_OUT_OF_RANGE("offset","an integer",h)):_<0?new V.ERR_BUFFER_OUT_OF_BOUNDS:new V.ERR_OUT_OF_RANGE("offset",`>= 0 and <= ${_}`,h)}let oe=/[^+/0-9A-Za-z-_]/g;function R(h){if(h=h.split("=")[0],h=h.trim().replace(oe,""),h.length<2)return"";for(;h.length%4!==0;)h=h+"=";return h}function $(h,_){_=_||1/0;let A,U=h.length,X=null,he=[];for(let ke=0;ke<U;++ke){if(A=h.charCodeAt(ke),A>55295&&A<57344){if(!X){if(A>56319){(_-=3)>-1&&he.push(239,191,189);continue}else if(ke+1===U){(_-=3)>-1&&he.push(239,191,189);continue}X=A;continue}if(A<56320){(_-=3)>-1&&he.push(239,191,189),X=A;continue}A=(X-55296<<10|A-56320)+65536}else X&&(_-=3)>-1&&he.push(239,191,189);if(X=null,A<128){if((_-=1)<0)break;he.push(A)}else if(A<2048){if((_-=2)<0)break;he.push(A>>6|192,A&63|128)}else if(A<65536){if((_-=3)<0)break;he.push(A>>12|224,A>>6&63|128,A&63|128)}else if(A<1114112){if((_-=4)<0)break;he.push(A>>18|240,A>>12&63|128,A>>6&63|128,A&63|128)}else throw new Error("Invalid code point")}return he}function ee(h){let _=[];for(let A=0;A<h.length;++A)_.push(h.charCodeAt(A)&255);return _}function fe(h,_){let A,U,X,he=[];for(let ke=0;ke<h.length&&!((_-=2)<0);++ke)A=h.charCodeAt(ke),U=A>>8,X=A%256,he.push(X),he.push(U);return he}function de(h){return c.toByteArray(R(h))}function ye(h,_,A,U){let X;for(X=0;X<U&&!(X+A>=_.length||X>=h.length);++X)_[X+A]=h[X];return X}function q(h,_){return h instanceof _||h!=null&&h.constructor!=null&&h.constructor.name!=null&&h.constructor.name===_.name}function ge(h){return h!==h}let ve=(function(){let h="0123456789abcdef",_=new Array(256);for(let A=0;A<16;++A){let U=A*16;for(let X=0;X<16;++X)_[U+X]=h[A]+h[X]}return _})();function se(h){return typeof BigInt>"u"?Te:h}function Te(){throw new Error("BigInt not supported")}return dt}var Ot,Jn,Wt,Xn,dt,Zn,uc=He(()=>{le(),ue(),ce(),Ot={},Jn=!1,Wt={},Xn=!1,dt={},Zn=!1}),Ne={};Ct(Ne,{Buffer:()=>rr,INSPECT_MAX_BYTES:()=>Lo,default:()=>ot,kMaxLength:()=>No});var ot,rr,Lo,No,Ue=He(()=>{le(),ue(),ce(),uc(),ot=cc(),ot.Buffer,ot.SlowBuffer,ot.INSPECT_MAX_BYTES,ot.kMaxLength,rr=ot.Buffer,Lo=ot.INSPECT_MAX_BYTES,No=ot.kMaxLength}),ue=He(()=>{Ue()}),je=pe((c,e)=>{le(),ue(),ce();var t=class extends Error{constructor(r){if(!Array.isArray(r))throw new TypeError(`Expected input to be an Array, got ${typeof r}`);let a="";for(let n=0;n<r.length;n++)a+=` ${r[n].stack}
2
- `;super(a),this.name="AggregateError",this.errors=r}};e.exports={AggregateError:t,ArrayIsArray(r){return Array.isArray(r)},ArrayPrototypeIncludes(r,a){return r.includes(a)},ArrayPrototypeIndexOf(r,a){return r.indexOf(a)},ArrayPrototypeJoin(r,a){return r.join(a)},ArrayPrototypeMap(r,a){return r.map(a)},ArrayPrototypePop(r,a){return r.pop(a)},ArrayPrototypePush(r,a){return r.push(a)},ArrayPrototypeSlice(r,a,n){return r.slice(a,n)},Error,FunctionPrototypeCall(r,a,...n){return r.call(a,...n)},FunctionPrototypeSymbolHasInstance(r,a){return Function.prototype[Symbol.hasInstance].call(r,a)},MathFloor:Math.floor,Number,NumberIsInteger:Number.isInteger,NumberIsNaN:Number.isNaN,NumberMAX_SAFE_INTEGER:Number.MAX_SAFE_INTEGER,NumberMIN_SAFE_INTEGER:Number.MIN_SAFE_INTEGER,NumberParseInt:Number.parseInt,ObjectDefineProperties(r,a){return Object.defineProperties(r,a)},ObjectDefineProperty(r,a,n){return Object.defineProperty(r,a,n)},ObjectGetOwnPropertyDescriptor(r,a){return Object.getOwnPropertyDescriptor(r,a)},ObjectKeys(r){return Object.keys(r)},ObjectSetPrototypeOf(r,a){return Object.setPrototypeOf(r,a)},Promise,PromisePrototypeCatch(r,a){return r.catch(a)},PromisePrototypeThen(r,a,n){return r.then(a,n)},PromiseReject(r){return Promise.reject(r)},PromiseResolve(r){return Promise.resolve(r)},ReflectApply:Reflect.apply,RegExpPrototypeTest(r,a){return r.test(a)},SafeSet:Set,String,StringPrototypeSlice(r,a,n){return r.slice(a,n)},StringPrototypeToLowerCase(r){return r.toLowerCase()},StringPrototypeToUpperCase(r){return r.toUpperCase()},StringPrototypeTrim(r){return r.trim()},Symbol,SymbolFor:Symbol.for,SymbolAsyncIterator:Symbol.asyncIterator,SymbolHasInstance:Symbol.hasInstance,SymbolIterator:Symbol.iterator,SymbolDispose:Symbol.dispose||Symbol("Symbol.dispose"),SymbolAsyncDispose:Symbol.asyncDispose||Symbol("Symbol.asyncDispose"),TypedArrayPrototypeSet(r,a,n){return r.set(a,n)},Boolean,Uint8Array}}),Uo=pe((c,e)=>{le(),ue(),ce(),e.exports={format(t,...r){return t.replace(/%([sdifj])/g,function(...[a,n]){let i=r.shift();return n==="f"?i.toFixed(6):n==="j"?JSON.stringify(i):n==="s"&&typeof i=="object"?`${i.constructor!==Object?i.constructor.name:""} {}`.trim():i.toString()})},inspect(t){switch(typeof t){case"string":if(t.includes("'"))if(t.includes('"')){if(!t.includes("`")&&!t.includes("${"))return`\`${t}\``}else return`"${t}"`;return`'${t}'`;case"number":return isNaN(t)?"NaN":Object.is(t,-0)?String(t):t;case"bigint":return`${String(t)}n`;case"boolean":case"undefined":return String(t);case"object":return"{}"}}}}),We=pe((c,e)=>{le(),ue(),ce();var{format:t,inspect:r}=Uo(),{AggregateError:a}=je(),n=globalThis.AggregateError||a,i=Symbol("kIsNodeError"),s=["string","function","number","object","Function","Object","boolean","bigint","symbol"],o=/^([A-Z][a-z0-9]*)+$/,l="__node_internal_",u={};function d(m,w){if(!m)throw new u.ERR_INTERNAL_ASSERTION(w)}function p(m){let w="",E=m.length,v=m[0]==="-"?1:0;for(;E>=v+4;E-=3)w=`_${m.slice(E-3,E)}${w}`;return`${m.slice(0,E)}${w}`}function y(m,w,E){if(typeof w=="function")return d(w.length<=E.length,`Code: ${m}; The provided arguments length (${E.length}) does not match the required ones (${w.length}).`),w(...E);let v=(w.match(/%[dfijoOs]/g)||[]).length;return d(v===E.length,`Code: ${m}; The provided arguments length (${E.length}) does not match the required ones (${v}).`),E.length===0?w:t(w,...E)}function f(m,w,E){E||(E=Error);class v extends E{constructor(...S){super(y(m,w,S))}toString(){return`${this.name} [${m}]: ${this.message}`}}Object.defineProperties(v.prototype,{name:{value:E.name,writable:!0,enumerable:!1,configurable:!0},toString:{value(){return`${this.name} [${m}]: ${this.message}`},writable:!0,enumerable:!1,configurable:!0}}),v.prototype.code=m,v.prototype[i]=!0,u[m]=v}function g(m){let w=l+m.name;return Object.defineProperty(m,"name",{value:w}),m}function b(m,w){if(m&&w&&m!==w){if(Array.isArray(w.errors))return w.errors.push(m),w;let E=new n([w,m],w.message);return E.code=w.code,E}return m||w}var k=class extends Error{constructor(m="The operation was aborted",w=void 0){if(w!==void 0&&typeof w!="object")throw new u.ERR_INVALID_ARG_TYPE("options","Object",w);super(m,w),this.code="ABORT_ERR",this.name="AbortError"}};f("ERR_ASSERTION","%s",Error),f("ERR_INVALID_ARG_TYPE",(m,w,E)=>{d(typeof m=="string","'name' must be a string"),Array.isArray(w)||(w=[w]);let v="The ";m.endsWith(" argument")?v+=`${m} `:v+=`"${m}" ${m.includes(".")?"property":"argument"} `,v+="must be ";let x=[],S=[],I=[];for(let O of w)d(typeof O=="string","All expected entries have to be of type string"),s.includes(O)?x.push(O.toLowerCase()):o.test(O)?S.push(O):(d(O!=="object",'The value "object" should be written as "Object"'),I.push(O));if(S.length>0){let O=x.indexOf("object");O!==-1&&(x.splice(x,O,1),S.push("Object"))}if(x.length>0){switch(x.length){case 1:v+=`of type ${x[0]}`;break;case 2:v+=`one of type ${x[0]} or ${x[1]}`;break;default:{let O=x.pop();v+=`one of type ${x.join(", ")}, or ${O}`}}(S.length>0||I.length>0)&&(v+=" or ")}if(S.length>0){switch(S.length){case 1:v+=`an instance of ${S[0]}`;break;case 2:v+=`an instance of ${S[0]} or ${S[1]}`;break;default:{let O=S.pop();v+=`an instance of ${S.join(", ")}, or ${O}`}}I.length>0&&(v+=" or ")}switch(I.length){case 0:break;case 1:I[0].toLowerCase()!==I[0]&&(v+="an "),v+=`${I[0]}`;break;case 2:v+=`one of ${I[0]} or ${I[1]}`;break;default:{let O=I.pop();v+=`one of ${I.join(", ")}, or ${O}`}}if(E==null)v+=`. Received ${E}`;else if(typeof E=="function"&&E.name)v+=`. Received function ${E.name}`;else if(typeof E=="object"){var M;if((M=E.constructor)!==null&&M!==void 0&&M.name)v+=`. Received an instance of ${E.constructor.name}`;else{let O=r(E,{depth:-1});v+=`. Received ${O}`}}else{let O=r(E,{colors:!1});O.length>25&&(O=`${O.slice(0,25)}...`),v+=`. Received type ${typeof E} (${O})`}return v},TypeError),f("ERR_INVALID_ARG_VALUE",(m,w,E="is invalid")=>{let v=r(w);return v.length>128&&(v=v.slice(0,128)+"..."),`The ${m.includes(".")?"property":"argument"} '${m}' ${E}. Received ${v}`},TypeError),f("ERR_INVALID_RETURN_VALUE",(m,w,E)=>{var v;let x=E!=null&&(v=E.constructor)!==null&&v!==void 0&&v.name?`instance of ${E.constructor.name}`:`type ${typeof E}`;return`Expected ${m} to be returned from the "${w}" function but got ${x}.`},TypeError),f("ERR_MISSING_ARGS",(...m)=>{d(m.length>0,"At least one arg needs to be specified");let w,E=m.length;switch(m=(Array.isArray(m)?m:[m]).map(v=>`"${v}"`).join(" or "),E){case 1:w+=`The ${m[0]} argument`;break;case 2:w+=`The ${m[0]} and ${m[1]} arguments`;break;default:{let v=m.pop();w+=`The ${m.join(", ")}, and ${v} arguments`}break}return`${w} must be specified`},TypeError),f("ERR_OUT_OF_RANGE",(m,w,E)=>{d(w,'Missing "range" argument');let v;if(Number.isInteger(E)&&Math.abs(E)>2**32)v=p(String(E));else if(typeof E=="bigint"){v=String(E);let x=BigInt(2)**BigInt(32);(E>x||E<-x)&&(v=p(v)),v+="n"}else v=r(E);return`The value of "${m}" is out of range. It must be ${w}. Received ${v}`},RangeError),f("ERR_MULTIPLE_CALLBACK","Callback called multiple times",Error),f("ERR_METHOD_NOT_IMPLEMENTED","The %s method is not implemented",Error),f("ERR_STREAM_ALREADY_FINISHED","Cannot call %s after a stream was finished",Error),f("ERR_STREAM_CANNOT_PIPE","Cannot pipe, not readable",Error),f("ERR_STREAM_DESTROYED","Cannot call %s after a stream was destroyed",Error),f("ERR_STREAM_NULL_VALUES","May not write null values to stream",TypeError),f("ERR_STREAM_PREMATURE_CLOSE","Premature close",Error),f("ERR_STREAM_PUSH_AFTER_EOF","stream.push() after EOF",Error),f("ERR_STREAM_UNSHIFT_AFTER_END_EVENT","stream.unshift() after end event",Error),f("ERR_STREAM_WRITE_AFTER_END","write after end",Error),f("ERR_UNKNOWN_ENCODING","Unknown encoding: %s",TypeError),e.exports={AbortError:k,aggregateTwoErrors:g(b),hideStackFrames:g,codes:u}}),qt=pe((c,e)=>{le(),ue(),ce();var{AbortController:t,AbortSignal:r}=typeof self<"u"?self:typeof window<"u"?window:void 0;e.exports=t,e.exports.AbortSignal=r,e.exports.default=t}),pt={};Ct(pt,{EventEmitter:()=>Bo,default:()=>Pt,defaultMaxListeners:()=>Fo,init:()=>Do,listenerCount:()=>$o,on:()=>Wo,once:()=>qo});function hc(){if(ei)return Ht;ei=!0;var c=typeof Reflect=="object"?Reflect:null,e=c&&typeof c.apply=="function"?c.apply:function(E,v,x){return Function.prototype.apply.call(E,v,x)},t;c&&typeof c.ownKeys=="function"?t=c.ownKeys:Object.getOwnPropertySymbols?t=function(E){return Object.getOwnPropertyNames(E).concat(Object.getOwnPropertySymbols(E))}:t=function(E){return Object.getOwnPropertyNames(E)};function r(E){console&&console.warn&&console.warn(E)}var a=Number.isNaN||function(E){return E!==E};function n(){n.init.call(this)}Ht=n,Ht.once=k,n.EventEmitter=n,n.prototype._events=void 0,n.prototype._eventsCount=0,n.prototype._maxListeners=void 0;var i=10;function s(E){if(typeof E!="function")throw new TypeError('The "listener" argument must be of type Function. Received type '+typeof E)}Object.defineProperty(n,"defaultMaxListeners",{enumerable:!0,get:function(){return i},set:function(E){if(typeof E!="number"||E<0||a(E))throw new RangeError('The value of "defaultMaxListeners" is out of range. It must be a non-negative number. Received '+E+".");i=E}}),n.init=function(){(this._events===void 0||this._events===Object.getPrototypeOf(this)._events)&&(this._events=Object.create(null),this._eventsCount=0),this._maxListeners=this._maxListeners||void 0},n.prototype.setMaxListeners=function(E){if(typeof E!="number"||E<0||a(E))throw new RangeError('The value of "n" is out of range. It must be a non-negative number. Received '+E+".");return this._maxListeners=E,this};function o(E){return E._maxListeners===void 0?n.defaultMaxListeners:E._maxListeners}n.prototype.getMaxListeners=function(){return o(this)},n.prototype.emit=function(E){for(var v=[],x=1;x<arguments.length;x++)v.push(arguments[x]);var S=E==="error",I=this._events;if(I!==void 0)S=S&&I.error===void 0;else if(!S)return!1;if(S){var M;if(v.length>0&&(M=v[0]),M instanceof Error)throw M;var O=new Error("Unhandled error."+(M?" ("+M.message+")":""));throw O.context=M,O}var B=I[E];if(B===void 0)return!1;if(typeof B=="function")e(B,this,v);else for(var T=B.length,W=f(B,T),x=0;x<T;++x)e(W[x],this,v);return!0};function l(E,v,x,S){var I,M,O;if(s(x),M=E._events,M===void 0?(M=E._events=Object.create(null),E._eventsCount=0):(M.newListener!==void 0&&(E.emit("newListener",v,x.listener?x.listener:x),M=E._events),O=M[v]),O===void 0)O=M[v]=x,++E._eventsCount;else if(typeof O=="function"?O=M[v]=S?[x,O]:[O,x]:S?O.unshift(x):O.push(x),I=o(E),I>0&&O.length>I&&!O.warned){O.warned=!0;var B=new Error("Possible EventEmitter memory leak detected. "+O.length+" "+String(v)+" listeners added. Use emitter.setMaxListeners() to increase limit");B.name="MaxListenersExceededWarning",B.emitter=E,B.type=v,B.count=O.length,r(B)}return E}n.prototype.addListener=function(E,v){return l(this,E,v,!1)},n.prototype.on=n.prototype.addListener,n.prototype.prependListener=function(E,v){return l(this,E,v,!0)};function u(){if(!this.fired)return this.target.removeListener(this.type,this.wrapFn),this.fired=!0,arguments.length===0?this.listener.call(this.target):this.listener.apply(this.target,arguments)}function d(E,v,x){var S={fired:!1,wrapFn:void 0,target:E,type:v,listener:x},I=u.bind(S);return I.listener=x,S.wrapFn=I,I}n.prototype.once=function(E,v){return s(v),this.on(E,d(this,E,v)),this},n.prototype.prependOnceListener=function(E,v){return s(v),this.prependListener(E,d(this,E,v)),this},n.prototype.removeListener=function(E,v){var x,S,I,M,O;if(s(v),S=this._events,S===void 0)return this;if(x=S[E],x===void 0)return this;if(x===v||x.listener===v)--this._eventsCount===0?this._events=Object.create(null):(delete S[E],S.removeListener&&this.emit("removeListener",E,x.listener||v));else if(typeof x!="function"){for(I=-1,M=x.length-1;M>=0;M--)if(x[M]===v||x[M].listener===v){O=x[M].listener,I=M;break}if(I<0)return this;I===0?x.shift():g(x,I),x.length===1&&(S[E]=x[0]),S.removeListener!==void 0&&this.emit("removeListener",E,O||v)}return this},n.prototype.off=n.prototype.removeListener,n.prototype.removeAllListeners=function(E){var v,x,S;if(x=this._events,x===void 0)return this;if(x.removeListener===void 0)return arguments.length===0?(this._events=Object.create(null),this._eventsCount=0):x[E]!==void 0&&(--this._eventsCount===0?this._events=Object.create(null):delete x[E]),this;if(arguments.length===0){var I=Object.keys(x),M;for(S=0;S<I.length;++S)M=I[S],M!=="removeListener"&&this.removeAllListeners(M);return this.removeAllListeners("removeListener"),this._events=Object.create(null),this._eventsCount=0,this}if(v=x[E],typeof v=="function")this.removeListener(E,v);else if(v!==void 0)for(S=v.length-1;S>=0;S--)this.removeListener(E,v[S]);return this};function p(E,v,x){var S=E._events;if(S===void 0)return[];var I=S[v];return I===void 0?[]:typeof I=="function"?x?[I.listener||I]:[I]:x?b(I):f(I,I.length)}n.prototype.listeners=function(E){return p(this,E,!0)},n.prototype.rawListeners=function(E){return p(this,E,!1)},n.listenerCount=function(E,v){return typeof E.listenerCount=="function"?E.listenerCount(v):y.call(E,v)},n.prototype.listenerCount=y;function y(E){var v=this._events;if(v!==void 0){var x=v[E];if(typeof x=="function")return 1;if(x!==void 0)return x.length}return 0}n.prototype.eventNames=function(){return this._eventsCount>0?t(this._events):[]};function f(E,v){for(var x=new Array(v),S=0;S<v;++S)x[S]=E[S];return x}function g(E,v){for(;v+1<E.length;v++)E[v]=E[v+1];E.pop()}function b(E){for(var v=new Array(E.length),x=0;x<v.length;++x)v[x]=E[x].listener||E[x];return v}function k(E,v){return new Promise(function(x,S){function I(O){E.removeListener(v,M),S(O)}function M(){typeof E.removeListener=="function"&&E.removeListener("error",I),x([].slice.call(arguments))}w(E,v,M,{once:!0}),v!=="error"&&m(E,I,{once:!0})})}function m(E,v,x){typeof E.on=="function"&&w(E,"error",v,x)}function w(E,v,x,S){if(typeof E.on=="function")S.once?E.once(v,x):E.on(v,x);else if(typeof E.addEventListener=="function")E.addEventListener(v,function I(M){S.once&&E.removeEventListener(v,I),x(M)});else throw new TypeError('The "emitter" argument must be of type EventEmitter. Received type '+typeof E)}return Ht}var Ht,ei,Pt,Bo,Fo,Do,$o,Wo,qo,kt=He(()=>{le(),ue(),ce(),Ht={},ei=!1,Pt=hc(),Pt.once,Pt.once=function(c,e){return new Promise((t,r)=>{function a(...i){n!==void 0&&c.removeListener("error",n),t(i)}let n;e!=="error"&&(n=i=>{c.removeListener(name,a),r(i)},c.once("error",n)),c.once(e,a)})},Pt.on=function(c,e){let t=[],r=[],a=null,n=!1,i={async next(){let l=t.shift();if(l)return createIterResult(l,!1);if(a){let u=Promise.reject(a);return a=null,u}return n?createIterResult(void 0,!0):new Promise((u,d)=>r.push({resolve:u,reject:d}))},async return(){c.removeListener(e,s),c.removeListener("error",o),n=!0;for(let l of r)l.resolve(createIterResult(void 0,!0));return createIterResult(void 0,!0)},throw(l){a=l,c.removeListener(e,s),c.removeListener("error",o)},[Symbol.asyncIterator](){return this}};return c.on(e,s),c.on("error",o),i;function s(...l){let u=r.shift();u?u.resolve(createIterResult(l,!1)):t.push(l)}function o(l){n=!0;let u=r.shift();u?u.reject(l):a=l,i.return()}},{EventEmitter:Bo,defaultMaxListeners:Fo,init:Do,listenerCount:$o,on:Wo,once:qo}=Pt}),ze=pe((c,e)=>{le(),ue(),ce();var t=(Ue(),Pe(Ne)),{format:r,inspect:a}=Uo(),{codes:{ERR_INVALID_ARG_TYPE:n}}=We(),{kResistStopPropagation:i,AggregateError:s,SymbolDispose:o}=je(),l=globalThis.AbortSignal||qt().AbortSignal,u=globalThis.AbortController||qt().AbortController,d=Object.getPrototypeOf(async function(){}).constructor,p=globalThis.Blob||t.Blob,y=typeof p<"u"?function(b){return b instanceof p}:function(b){return!1},f=(b,k)=>{if(b!==void 0&&(b===null||typeof b!="object"||!("aborted"in b)))throw new n(k,"AbortSignal",b)},g=(b,k)=>{if(typeof b!="function")throw new n(k,"Function",b)};e.exports={AggregateError:s,kEmptyObject:Object.freeze({}),once(b){let k=!1;return function(...m){k||(k=!0,b.apply(this,m))}},createDeferredPromise:function(){let b,k;return{promise:new Promise((m,w)=>{b=m,k=w}),resolve:b,reject:k}},promisify(b){return new Promise((k,m)=>{b((w,...E)=>w?m(w):k(...E))})},debuglog(){return function(){}},format:r,inspect:a,types:{isAsyncFunction(b){return b instanceof d},isArrayBufferView(b){return ArrayBuffer.isView(b)}},isBlob:y,deprecate(b,k){return b},addAbortListener:(kt(),Pe(pt)).addAbortListener||function(b,k){if(b===void 0)throw new n("signal","AbortSignal",b);f(b,"signal"),g(k,"listener");let m;return b.aborted?queueMicrotask(()=>k()):(b.addEventListener("abort",k,{__proto__:null,once:!0,[i]:!0}),m=()=>{b.removeEventListener("abort",k)}),{__proto__:null,[o](){var w;(w=m)===null||w===void 0||w()}}},AbortSignalAny:l.any||function(b){if(b.length===1)return b[0];let k=new u,m=()=>k.abort();return b.forEach(w=>{f(w,"signals"),w.addEventListener("abort",m,{once:!0})}),k.signal.addEventListener("abort",()=>{b.forEach(w=>w.removeEventListener("abort",m))},{once:!0}),k.signal}},e.exports.promisify.custom=Symbol.for("nodejs.util.promisify.custom")}),zt=pe((c,e)=>{le(),ue(),ce();var{ArrayIsArray:t,ArrayPrototypeIncludes:r,ArrayPrototypeJoin:a,ArrayPrototypeMap:n,NumberIsInteger:i,NumberIsNaN:s,NumberMAX_SAFE_INTEGER:o,NumberMIN_SAFE_INTEGER:l,NumberParseInt:u,ObjectPrototypeHasOwnProperty:d,RegExpPrototypeExec:p,String:y,StringPrototypeToUpperCase:f,StringPrototypeTrim:g}=je(),{hideStackFrames:b,codes:{ERR_SOCKET_BAD_PORT:k,ERR_INVALID_ARG_TYPE:m,ERR_INVALID_ARG_VALUE:w,ERR_OUT_OF_RANGE:E,ERR_UNKNOWN_SIGNAL:v}}=We(),{normalizeEncoding:x}=ze(),{isAsyncFunction:S,isArrayBufferView:I}=ze().types,M={};function O(q){return q===(q|0)}function B(q){return q===q>>>0}var T=/^[0-7]+$/,W="must be a 32-bit unsigned integer or an octal string";function F(q,ge,ve){if(typeof q>"u"&&(q=ve),typeof q=="string"){if(p(T,q)===null)throw new w(ge,q,W);q=u(q,8)}return Y(q,ge),q}var N=b((q,ge,ve=l,se=o)=>{if(typeof q!="number")throw new m(ge,"number",q);if(!i(q))throw new E(ge,"an integer",q);if(q<ve||q>se)throw new E(ge,`>= ${ve} && <= ${se}`,q)}),ae=b((q,ge,ve=-2147483648,se=2147483647)=>{if(typeof q!="number")throw new m(ge,"number",q);if(!i(q))throw new E(ge,"an integer",q);if(q<ve||q>se)throw new E(ge,`>= ${ve} && <= ${se}`,q)}),Y=b((q,ge,ve=!1)=>{if(typeof q!="number")throw new m(ge,"number",q);if(!i(q))throw new E(ge,"an integer",q);let se=ve?1:0,Te=4294967295;if(q<se||q>Te)throw new E(ge,`>= ${se} && <= ${Te}`,q)});function K(q,ge){if(typeof q!="string")throw new m(ge,"string",q)}function re(q,ge,ve=void 0,se){if(typeof q!="number")throw new m(ge,"number",q);if(ve!=null&&q<ve||se!=null&&q>se||(ve!=null||se!=null)&&s(q))throw new E(ge,`${ve!=null?`>= ${ve}`:""}${ve!=null&&se!=null?" && ":""}${se!=null?`<= ${se}`:""}`,q)}var D=b((q,ge,ve)=>{if(!r(ve,q)){let se="must be one of: "+a(n(ve,Te=>typeof Te=="string"?`'${Te}'`:y(Te)),", ");throw new w(ge,q,se)}});function Z(q,ge){if(typeof q!="boolean")throw new m(ge,"boolean",q)}function P(q,ge,ve){return q==null||!d(q,ge)?ve:q[ge]}var J=b((q,ge,ve=null)=>{let se=P(ve,"allowArray",!1),Te=P(ve,"allowFunction",!1);if(!P(ve,"nullable",!1)&&q===null||!se&&t(q)||typeof q!="object"&&(!Te||typeof q!="function"))throw new m(ge,"Object",q)}),be=b((q,ge)=>{if(q!=null&&typeof q!="object"&&typeof q!="function")throw new m(ge,"a dictionary",q)}),te=b((q,ge,ve=0)=>{if(!t(q))throw new m(ge,"Array",q);if(q.length<ve){let se=`must be longer than ${ve}`;throw new w(ge,q,se)}});function we(q,ge){te(q,ge);for(let ve=0;ve<q.length;ve++)K(q[ve],`${ge}[${ve}]`)}function V(q,ge){te(q,ge);for(let ve=0;ve<q.length;ve++)Z(q[ve],`${ge}[${ve}]`)}function L(q,ge){te(q,ge);for(let ve=0;ve<q.length;ve++){let se=q[ve],Te=`${ge}[${ve}]`;if(se==null)throw new m(Te,"AbortSignal",se);me(se,Te)}}function ne(q,ge="signal"){if(K(q,ge),M[q]===void 0)throw M[f(q)]!==void 0?new v(q+" (signals must use all capital letters)"):new v(q)}var H=b((q,ge="buffer")=>{if(!I(q))throw new m(ge,["Buffer","TypedArray","DataView"],q)});function G(q,ge){let ve=x(ge),se=q.length;if(ve==="hex"&&se%2!==0)throw new w("encoding",ge,`is invalid for data of length ${se}`)}function Q(q,ge="Port",ve=!0){if(typeof q!="number"&&typeof q!="string"||typeof q=="string"&&g(q).length===0||+q!==+q>>>0||q>65535||q===0&&!ve)throw new k(ge,q,ve);return q|0}var me=b((q,ge)=>{if(q!==void 0&&(q===null||typeof q!="object"||!("aborted"in q)))throw new m(ge,"AbortSignal",q)}),oe=b((q,ge)=>{if(typeof q!="function")throw new m(ge,"Function",q)}),R=b((q,ge)=>{if(typeof q!="function"||S(q))throw new m(ge,"Function",q)}),$=b((q,ge)=>{if(q!==void 0)throw new m(ge,"undefined",q)});function ee(q,ge,ve){if(!r(ve,q))throw new m(ge,`('${a(ve,"|")}')`,q)}var fe=/^(?:<[^>]*>)(?:\s*;\s*[^;"\s]+(?:=(")?[^;"\s]*\1)?)*$/;function de(q,ge){if(typeof q>"u"||!p(fe,q))throw new w(ge,q,'must be an array or string of format "</styles.css>; rel=preload; as=style"')}function ye(q){if(typeof q=="string")return de(q,"hints"),q;if(t(q)){let ge=q.length,ve="";if(ge===0)return ve;for(let se=0;se<ge;se++){let Te=q[se];de(Te,"hints"),ve+=Te,se!==ge-1&&(ve+=", ")}return ve}throw new w("hints",q,'must be an array or string of format "</styles.css>; rel=preload; as=style"')}e.exports={isInt32:O,isUint32:B,parseFileMode:F,validateArray:te,validateStringArray:we,validateBooleanArray:V,validateAbortSignalArray:L,validateBoolean:Z,validateBuffer:H,validateDictionary:be,validateEncoding:G,validateFunction:oe,validateInt32:ae,validateInteger:N,validateNumber:re,validateObject:J,validateOneOf:D,validatePlainFunction:R,validatePort:Q,validateSignalName:ne,validateString:K,validateUint32:Y,validateUndefined:$,validateUnion:ee,validateAbortSignal:me,validateLinkHeaderValue:ye}}),St=pe((c,e)=>{le(),ue(),ce();var t=e.exports={},r,a;function n(){throw new Error("setTimeout has not been defined")}function i(){throw new Error("clearTimeout has not been defined")}(function(){try{typeof setTimeout=="function"?r=setTimeout:r=n}catch{r=n}try{typeof clearTimeout=="function"?a=clearTimeout:a=i}catch{a=i}})();function s(k){if(r===setTimeout)return setTimeout(k,0);if((r===n||!r)&&setTimeout)return r=setTimeout,setTimeout(k,0);try{return r(k,0)}catch{try{return r.call(null,k,0)}catch{return r.call(this,k,0)}}}function o(k){if(a===clearTimeout)return clearTimeout(k);if((a===i||!a)&&clearTimeout)return a=clearTimeout,clearTimeout(k);try{return a(k)}catch{try{return a.call(null,k)}catch{return a.call(this,k)}}}var l=[],u=!1,d,p=-1;function y(){!u||!d||(u=!1,d.length?l=d.concat(l):p=-1,l.length&&f())}function f(){if(!u){var k=s(y);u=!0;for(var m=l.length;m;){for(d=l,l=[];++p<m;)d&&d[p].run();p=-1,m=l.length}d=null,u=!1,o(k)}}t.nextTick=function(k){var m=new Array(arguments.length-1);if(arguments.length>1)for(var w=1;w<arguments.length;w++)m[w-1]=arguments[w];l.push(new g(k,m)),l.length===1&&!u&&s(f)};function g(k,m){this.fun=k,this.array=m}g.prototype.run=function(){this.fun.apply(null,this.array)},t.title="browser",t.browser=!0,t.env={},t.argv=[],t.version="",t.versions={};function b(){}t.on=b,t.addListener=b,t.once=b,t.off=b,t.removeListener=b,t.removeAllListeners=b,t.emit=b,t.prependListener=b,t.prependOnceListener=b,t.listeners=function(k){return[]},t.binding=function(k){throw new Error("process.binding is not supported")},t.cwd=function(){return"/"},t.chdir=function(k){throw new Error("process.chdir is not supported")},t.umask=function(){return 0}}),st=pe((c,e)=>{le(),ue(),ce();var{SymbolAsyncIterator:t,SymbolIterator:r,SymbolFor:a}=je(),n=a("nodejs.stream.destroyed"),i=a("nodejs.stream.errored"),s=a("nodejs.stream.readable"),o=a("nodejs.stream.writable"),l=a("nodejs.stream.disturbed"),u=a("nodejs.webstream.isClosedPromise"),d=a("nodejs.webstream.controllerErrorFunction");function p(P,J=!1){var be;return!!(P&&typeof P.pipe=="function"&&typeof P.on=="function"&&(!J||typeof P.pause=="function"&&typeof P.resume=="function")&&(!P._writableState||((be=P._readableState)===null||be===void 0?void 0:be.readable)!==!1)&&(!P._writableState||P._readableState))}function y(P){var J;return!!(P&&typeof P.write=="function"&&typeof P.on=="function"&&(!P._readableState||((J=P._writableState)===null||J===void 0?void 0:J.writable)!==!1))}function f(P){return!!(P&&typeof P.pipe=="function"&&P._readableState&&typeof P.on=="function"&&typeof P.write=="function")}function g(P){return P&&(P._readableState||P._writableState||typeof P.write=="function"&&typeof P.on=="function"||typeof P.pipe=="function"&&typeof P.on=="function")}function b(P){return!!(P&&!g(P)&&typeof P.pipeThrough=="function"&&typeof P.getReader=="function"&&typeof P.cancel=="function")}function k(P){return!!(P&&!g(P)&&typeof P.getWriter=="function"&&typeof P.abort=="function")}function m(P){return!!(P&&!g(P)&&typeof P.readable=="object"&&typeof P.writable=="object")}function w(P){return b(P)||k(P)||m(P)}function E(P,J){return P==null?!1:J===!0?typeof P[t]=="function":J===!1?typeof P[r]=="function":typeof P[t]=="function"||typeof P[r]=="function"}function v(P){if(!g(P))return null;let J=P._writableState,be=P._readableState,te=J||be;return!!(P.destroyed||P[n]||te!=null&&te.destroyed)}function x(P){if(!y(P))return null;if(P.writableEnded===!0)return!0;let J=P._writableState;return J!=null&&J.errored?!1:typeof J?.ended!="boolean"?null:J.ended}function S(P,J){if(!y(P))return null;if(P.writableFinished===!0)return!0;let be=P._writableState;return be!=null&&be.errored?!1:typeof be?.finished!="boolean"?null:!!(be.finished||J===!1&&be.ended===!0&&be.length===0)}function I(P){if(!p(P))return null;if(P.readableEnded===!0)return!0;let J=P._readableState;return!J||J.errored?!1:typeof J?.ended!="boolean"?null:J.ended}function M(P,J){if(!p(P))return null;let be=P._readableState;return be!=null&&be.errored?!1:typeof be?.endEmitted!="boolean"?null:!!(be.endEmitted||J===!1&&be.ended===!0&&be.length===0)}function O(P){return P&&P[s]!=null?P[s]:typeof P?.readable!="boolean"?null:v(P)?!1:p(P)&&P.readable&&!M(P)}function B(P){return P&&P[o]!=null?P[o]:typeof P?.writable!="boolean"?null:v(P)?!1:y(P)&&P.writable&&!x(P)}function T(P,J){return g(P)?v(P)?!0:!(J?.readable!==!1&&O(P)||J?.writable!==!1&&B(P)):null}function W(P){var J,be;return g(P)?P.writableErrored?P.writableErrored:(J=(be=P._writableState)===null||be===void 0?void 0:be.errored)!==null&&J!==void 0?J:null:null}function F(P){var J,be;return g(P)?P.readableErrored?P.readableErrored:(J=(be=P._readableState)===null||be===void 0?void 0:be.errored)!==null&&J!==void 0?J:null:null}function N(P){if(!g(P))return null;if(typeof P.closed=="boolean")return P.closed;let J=P._writableState,be=P._readableState;return typeof J?.closed=="boolean"||typeof be?.closed=="boolean"?J?.closed||be?.closed:typeof P._closed=="boolean"&&ae(P)?P._closed:null}function ae(P){return typeof P._closed=="boolean"&&typeof P._defaultKeepAlive=="boolean"&&typeof P._removedConnection=="boolean"&&typeof P._removedContLen=="boolean"}function Y(P){return typeof P._sent100=="boolean"&&ae(P)}function K(P){var J;return typeof P._consuming=="boolean"&&typeof P._dumped=="boolean"&&((J=P.req)===null||J===void 0?void 0:J.upgradeOrConnect)===void 0}function re(P){if(!g(P))return null;let J=P._writableState,be=P._readableState,te=J||be;return!te&&Y(P)||!!(te&&te.autoDestroy&&te.emitClose&&te.closed===!1)}function D(P){var J;return!!(P&&((J=P[l])!==null&&J!==void 0?J:P.readableDidRead||P.readableAborted))}function Z(P){var J,be,te,we,V,L,ne,H,G,Q;return!!(P&&((J=(be=(te=(we=(V=(L=P[i])!==null&&L!==void 0?L:P.readableErrored)!==null&&V!==void 0?V:P.writableErrored)!==null&&we!==void 0?we:(ne=P._readableState)===null||ne===void 0?void 0:ne.errorEmitted)!==null&&te!==void 0?te:(H=P._writableState)===null||H===void 0?void 0:H.errorEmitted)!==null&&be!==void 0?be:(G=P._readableState)===null||G===void 0?void 0:G.errored)!==null&&J!==void 0?J:!((Q=P._writableState)===null||Q===void 0)&&Q.errored))}e.exports={isDestroyed:v,kIsDestroyed:n,isDisturbed:D,kIsDisturbed:l,isErrored:Z,kIsErrored:i,isReadable:O,kIsReadable:s,kIsClosedPromise:u,kControllerErrorFunction:d,kIsWritable:o,isClosed:N,isDuplexNodeStream:f,isFinished:T,isIterable:E,isReadableNodeStream:p,isReadableStream:b,isReadableEnded:I,isReadableFinished:M,isReadableErrored:F,isNodeStream:g,isWebStream:w,isWritable:B,isWritableNodeStream:y,isWritableStream:k,isWritableEnded:x,isWritableFinished:S,isWritableErrored:W,isServerRequest:K,isServerResponse:Y,willEmitClose:re,isTransformStream:m}}),gt=pe((c,e)=>{le(),ue(),ce();var t=St(),{AbortError:r,codes:a}=We(),{ERR_INVALID_ARG_TYPE:n,ERR_STREAM_PREMATURE_CLOSE:i}=a,{kEmptyObject:s,once:o}=ze(),{validateAbortSignal:l,validateFunction:u,validateObject:d,validateBoolean:p}=zt(),{Promise:y,PromisePrototypeThen:f,SymbolDispose:g}=je(),{isClosed:b,isReadable:k,isReadableNodeStream:m,isReadableStream:w,isReadableFinished:E,isReadableErrored:v,isWritable:x,isWritableNodeStream:S,isWritableStream:I,isWritableFinished:M,isWritableErrored:O,isNodeStream:B,willEmitClose:T,kIsClosedPromise:W}=st(),F;function N(D){return D.setHeader&&typeof D.abort=="function"}var ae=()=>{};function Y(D,Z,P){var J,be;if(arguments.length===2?(P=Z,Z=s):Z==null?Z=s:d(Z,"options"),u(P,"callback"),l(Z.signal,"options.signal"),P=o(P),w(D)||I(D))return K(D,Z,P);if(!B(D))throw new n("stream",["ReadableStream","WritableStream","Stream"],D);let te=(J=Z.readable)!==null&&J!==void 0?J:m(D),we=(be=Z.writable)!==null&&be!==void 0?be:S(D),V=D._writableState,L=D._readableState,ne=()=>{D.writable||Q()},H=T(D)&&m(D)===te&&S(D)===we,G=M(D,!1),Q=()=>{G=!0,D.destroyed&&(H=!1),!(H&&(!D.readable||te))&&(!te||me)&&P.call(D)},me=E(D,!1),oe=()=>{me=!0,D.destroyed&&(H=!1),!(H&&(!D.writable||we))&&(!we||G)&&P.call(D)},R=q=>{P.call(D,q)},$=b(D),ee=()=>{$=!0;let q=O(D)||v(D);if(q&&typeof q!="boolean")return P.call(D,q);if(te&&!me&&m(D,!0)&&!E(D,!1))return P.call(D,new i);if(we&&!G&&!M(D,!1))return P.call(D,new i);P.call(D)},fe=()=>{$=!0;let q=O(D)||v(D);if(q&&typeof q!="boolean")return P.call(D,q);P.call(D)},de=()=>{D.req.on("finish",Q)};N(D)?(D.on("complete",Q),H||D.on("abort",ee),D.req?de():D.on("request",de)):we&&!V&&(D.on("end",ne),D.on("close",ne)),!H&&typeof D.aborted=="boolean"&&D.on("aborted",ee),D.on("end",oe),D.on("finish",Q),Z.error!==!1&&D.on("error",R),D.on("close",ee),$?t.nextTick(ee):V!=null&&V.errorEmitted||L!=null&&L.errorEmitted?H||t.nextTick(fe):(!te&&(!H||k(D))&&(G||x(D)===!1)||!we&&(!H||x(D))&&(me||k(D)===!1)||L&&D.req&&D.aborted)&&t.nextTick(fe);let ye=()=>{P=ae,D.removeListener("aborted",ee),D.removeListener("complete",Q),D.removeListener("abort",ee),D.removeListener("request",de),D.req&&D.req.removeListener("finish",Q),D.removeListener("end",ne),D.removeListener("close",ne),D.removeListener("finish",Q),D.removeListener("end",oe),D.removeListener("error",R),D.removeListener("close",ee)};if(Z.signal&&!$){let q=()=>{let ge=P;ye(),ge.call(D,new r(void 0,{cause:Z.signal.reason}))};if(Z.signal.aborted)t.nextTick(q);else{F=F||ze().addAbortListener;let ge=F(Z.signal,q),ve=P;P=o((...se)=>{ge[g](),ve.apply(D,se)})}}return ye}function K(D,Z,P){let J=!1,be=ae;if(Z.signal)if(be=()=>{J=!0,P.call(D,new r(void 0,{cause:Z.signal.reason}))},Z.signal.aborted)t.nextTick(be);else{F=F||ze().addAbortListener;let we=F(Z.signal,be),V=P;P=o((...L)=>{we[g](),V.apply(D,L)})}let te=(...we)=>{J||t.nextTick(()=>P.apply(D,we))};return f(D[W].promise,te,te),ae}function re(D,Z){var P;let J=!1;return Z===null&&(Z=s),(P=Z)!==null&&P!==void 0&&P.cleanup&&(p(Z.cleanup,"cleanup"),J=Z.cleanup),new y((be,te)=>{let we=Y(D,Z,V=>{J&&we(),V?te(V):be()})})}e.exports=Y,e.exports.finished=re}),Mt=pe((c,e)=>{le(),ue(),ce();var t=St(),{aggregateTwoErrors:r,codes:{ERR_MULTIPLE_CALLBACK:a},AbortError:n}=We(),{Symbol:i}=je(),{kIsDestroyed:s,isDestroyed:o,isFinished:l,isServerRequest:u}=st(),d=i("kDestroy"),p=i("kConstruct");function y(T,W,F){T&&(T.stack,W&&!W.errored&&(W.errored=T),F&&!F.errored&&(F.errored=T))}function f(T,W){let F=this._readableState,N=this._writableState,ae=N||F;return N!=null&&N.destroyed||F!=null&&F.destroyed?(typeof W=="function"&&W(),this):(y(T,N,F),N&&(N.destroyed=!0),F&&(F.destroyed=!0),ae.constructed?g(this,T,W):this.once(d,function(Y){g(this,r(Y,T),W)}),this)}function g(T,W,F){let N=!1;function ae(Y){if(N)return;N=!0;let K=T._readableState,re=T._writableState;y(Y,re,K),re&&(re.closed=!0),K&&(K.closed=!0),typeof F=="function"&&F(Y),Y?t.nextTick(b,T,Y):t.nextTick(k,T)}try{T._destroy(W||null,ae)}catch(Y){ae(Y)}}function b(T,W){m(T,W),k(T)}function k(T){let W=T._readableState,F=T._writableState;F&&(F.closeEmitted=!0),W&&(W.closeEmitted=!0),(F!=null&&F.emitClose||W!=null&&W.emitClose)&&T.emit("close")}function m(T,W){let F=T._readableState,N=T._writableState;N!=null&&N.errorEmitted||F!=null&&F.errorEmitted||(N&&(N.errorEmitted=!0),F&&(F.errorEmitted=!0),T.emit("error",W))}function w(){let T=this._readableState,W=this._writableState;T&&(T.constructed=!0,T.closed=!1,T.closeEmitted=!1,T.destroyed=!1,T.errored=null,T.errorEmitted=!1,T.reading=!1,T.ended=T.readable===!1,T.endEmitted=T.readable===!1),W&&(W.constructed=!0,W.destroyed=!1,W.closed=!1,W.closeEmitted=!1,W.errored=null,W.errorEmitted=!1,W.finalCalled=!1,W.prefinished=!1,W.ended=W.writable===!1,W.ending=W.writable===!1,W.finished=W.writable===!1)}function E(T,W,F){let N=T._readableState,ae=T._writableState;if(ae!=null&&ae.destroyed||N!=null&&N.destroyed)return this;N!=null&&N.autoDestroy||ae!=null&&ae.autoDestroy?T.destroy(W):W&&(W.stack,ae&&!ae.errored&&(ae.errored=W),N&&!N.errored&&(N.errored=W),F?t.nextTick(m,T,W):m(T,W))}function v(T,W){if(typeof T._construct!="function")return;let F=T._readableState,N=T._writableState;F&&(F.constructed=!1),N&&(N.constructed=!1),T.once(p,W),!(T.listenerCount(p)>1)&&t.nextTick(x,T)}function x(T){let W=!1;function F(N){if(W){E(T,N??new a);return}W=!0;let ae=T._readableState,Y=T._writableState,K=Y||ae;ae&&(ae.constructed=!0),Y&&(Y.constructed=!0),K.destroyed?T.emit(d,N):N?E(T,N,!0):t.nextTick(S,T)}try{T._construct(N=>{t.nextTick(F,N)})}catch(N){t.nextTick(F,N)}}function S(T){T.emit(p)}function I(T){return T?.setHeader&&typeof T.abort=="function"}function M(T){T.emit("close")}function O(T,W){T.emit("error",W),t.nextTick(M,T)}function B(T,W){!T||o(T)||(!W&&!l(T)&&(W=new n),u(T)?(T.socket=null,T.destroy(W)):I(T)?T.abort():I(T.req)?T.req.abort():typeof T.destroy=="function"?T.destroy(W):typeof T.close=="function"?T.close():W?t.nextTick(O,T,W):t.nextTick(M,T),T.destroyed||(T[s]=!0))}e.exports={construct:v,destroyer:B,destroy:f,undestroy:w,errorOrDestroy:E}}),ti=pe((c,e)=>{le(),ue(),ce();var{ArrayIsArray:t,ObjectSetPrototypeOf:r}=je(),{EventEmitter:a}=(kt(),Pe(pt));function n(s){a.call(this,s)}r(n.prototype,a.prototype),r(n,a),n.prototype.pipe=function(s,o){let l=this;function u(k){s.writable&&s.write(k)===!1&&l.pause&&l.pause()}l.on("data",u);function d(){l.readable&&l.resume&&l.resume()}s.on("drain",d),!s._isStdio&&(!o||o.end!==!1)&&(l.on("end",y),l.on("close",f));let p=!1;function y(){p||(p=!0,s.end())}function f(){p||(p=!0,typeof s.destroy=="function"&&s.destroy())}function g(k){b(),a.listenerCount(this,"error")===0&&this.emit("error",k)}i(l,"error",g),i(s,"error",g);function b(){l.removeListener("data",u),s.removeListener("drain",d),l.removeListener("end",y),l.removeListener("close",f),l.removeListener("error",g),s.removeListener("error",g),l.removeListener("end",b),l.removeListener("close",b),s.removeListener("close",b)}return l.on("end",b),l.on("close",b),s.on("close",b),s.emit("pipe",l),s};function i(s,o,l){if(typeof s.prependListener=="function")return s.prependListener(o,l);!s._events||!s._events[o]?s.on(o,l):t(s._events[o])?s._events[o].unshift(l):s._events[o]=[l,s._events[o]]}e.exports={Stream:n,prependListener:i}}),nr=pe((c,e)=>{le(),ue(),ce();var{SymbolDispose:t}=je(),{AbortError:r,codes:a}=We(),{isNodeStream:n,isWebStream:i,kControllerErrorFunction:s}=st(),o=gt(),{ERR_INVALID_ARG_TYPE:l}=a,u,d=(p,y)=>{if(typeof p!="object"||!("aborted"in p))throw new l(y,"AbortSignal",p)};e.exports.addAbortSignal=function(p,y){if(d(p,"signal"),!n(y)&&!i(y))throw new l("stream",["ReadableStream","WritableStream","Stream"],y);return e.exports.addAbortSignalNoValidate(p,y)},e.exports.addAbortSignalNoValidate=function(p,y){if(typeof p!="object"||!("aborted"in p))return y;let f=n(y)?()=>{y.destroy(new r(void 0,{cause:p.reason}))}:()=>{y[s](new r(void 0,{cause:p.reason}))};if(p.aborted)f();else{u=u||ze().addAbortListener;let g=u(p,f);o(y,g[t])}return y}}),fc=pe((c,e)=>{le(),ue(),ce();var{StringPrototypeSlice:t,SymbolIterator:r,TypedArrayPrototypeSet:a,Uint8Array:n}=je(),{Buffer:i}=(Ue(),Pe(Ne)),{inspect:s}=ze();e.exports=class{constructor(){this.head=null,this.tail=null,this.length=0}push(o){let l={data:o,next:null};this.length>0?this.tail.next=l:this.head=l,this.tail=l,++this.length}unshift(o){let l={data:o,next:this.head};this.length===0&&(this.tail=l),this.head=l,++this.length}shift(){if(this.length===0)return;let o=this.head.data;return this.length===1?this.head=this.tail=null:this.head=this.head.next,--this.length,o}clear(){this.head=this.tail=null,this.length=0}join(o){if(this.length===0)return"";let l=this.head,u=""+l.data;for(;(l=l.next)!==null;)u+=o+l.data;return u}concat(o){if(this.length===0)return i.alloc(0);let l=i.allocUnsafe(o>>>0),u=this.head,d=0;for(;u;)a(l,u.data,d),d+=u.data.length,u=u.next;return l}consume(o,l){let u=this.head.data;if(o<u.length){let d=u.slice(0,o);return this.head.data=u.slice(o),d}return o===u.length?this.shift():l?this._getString(o):this._getBuffer(o)}first(){return this.head.data}*[r](){for(let o=this.head;o;o=o.next)yield o.data}_getString(o){let l="",u=this.head,d=0;do{let p=u.data;if(o>p.length)l+=p,o-=p.length;else{o===p.length?(l+=p,++d,u.next?this.head=u.next:this.head=this.tail=null):(l+=t(p,0,o),this.head=u,u.data=t(p,o));break}++d}while((u=u.next)!==null);return this.length-=d,l}_getBuffer(o){let l=i.allocUnsafe(o),u=o,d=this.head,p=0;do{let y=d.data;if(o>y.length)a(l,y,u-o),o-=y.length;else{o===y.length?(a(l,y,u-o),++p,d.next?this.head=d.next:this.head=this.tail=null):(a(l,new n(y.buffer,y.byteOffset,o),u-o),this.head=d,d.data=y.slice(o));break}++p}while((d=d.next)!==null);return this.length-=p,l}[Symbol.for("nodejs.util.inspect.custom")](o,l){return s(this,{...l,depth:0,customInspect:!1})}}}),ir=pe((c,e)=>{le(),ue(),ce();var{MathFloor:t,NumberIsInteger:r}=je(),{validateInteger:a}=zt(),{ERR_INVALID_ARG_VALUE:n}=We().codes,i=16*1024,s=16;function o(p,y,f){return p.highWaterMark!=null?p.highWaterMark:y?p[f]:null}function l(p){return p?s:i}function u(p,y){a(y,"value",0),p?s=y:i=y}function d(p,y,f,g){let b=o(y,g,f);if(b!=null){if(!r(b)||b<0){let k=g?`options.${f}`:"options.highWaterMark";throw new n(k,b)}return t(b)}return l(p.objectMode)}e.exports={getHighWaterMark:d,getDefaultHighWaterMark:l,setDefaultHighWaterMark:u}}),dc=pe((c,e)=>{le(),ue(),ce();var t=(Ue(),Pe(Ne)),r=t.Buffer;function a(i,s){for(var o in i)s[o]=i[o]}r.from&&r.alloc&&r.allocUnsafe&&r.allocUnsafeSlow?e.exports=t:(a(t,c),c.Buffer=n);function n(i,s,o){return r(i,s,o)}n.prototype=Object.create(r.prototype),a(r,n),n.from=function(i,s,o){if(typeof i=="number")throw new TypeError("Argument must not be a number");return r(i,s,o)},n.alloc=function(i,s,o){if(typeof i!="number")throw new TypeError("Argument must be a number");var l=r(i);return s!==void 0?typeof o=="string"?l.fill(s,o):l.fill(s):l.fill(0),l},n.allocUnsafe=function(i){if(typeof i!="number")throw new TypeError("Argument must be a number");return r(i)},n.allocUnsafeSlow=function(i){if(typeof i!="number")throw new TypeError("Argument must be a number");return t.SlowBuffer(i)}}),pc=pe(c=>{le(),ue(),ce();var e=dc().Buffer,t=e.isEncoding||function(m){switch(m=""+m,m&&m.toLowerCase()){case"hex":case"utf8":case"utf-8":case"ascii":case"binary":case"base64":case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":case"raw":return!0;default:return!1}};function r(m){if(!m)return"utf8";for(var w;;)switch(m){case"utf8":case"utf-8":return"utf8";case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return"utf16le";case"latin1":case"binary":return"latin1";case"base64":case"ascii":case"hex":return m;default:if(w)return;m=(""+m).toLowerCase(),w=!0}}function a(m){var w=r(m);if(typeof w!="string"&&(e.isEncoding===t||!t(m)))throw new Error("Unknown encoding: "+m);return w||m}c.StringDecoder=n;function n(m){this.encoding=a(m);var w;switch(this.encoding){case"utf16le":this.text=p,this.end=y,w=4;break;case"utf8":this.fillLast=l,w=4;break;case"base64":this.text=f,this.end=g,w=3;break;default:this.write=b,this.end=k;return}this.lastNeed=0,this.lastTotal=0,this.lastChar=e.allocUnsafe(w)}n.prototype.write=function(m){if(m.length===0)return"";var w,E;if(this.lastNeed){if(w=this.fillLast(m),w===void 0)return"";E=this.lastNeed,this.lastNeed=0}else E=0;return E<m.length?w?w+this.text(m,E):this.text(m,E):w||""},n.prototype.end=d,n.prototype.text=u,n.prototype.fillLast=function(m){if(this.lastNeed<=m.length)return m.copy(this.lastChar,this.lastTotal-this.lastNeed,0,this.lastNeed),this.lastChar.toString(this.encoding,0,this.lastTotal);m.copy(this.lastChar,this.lastTotal-this.lastNeed,0,m.length),this.lastNeed-=m.length};function i(m){return m<=127?0:m>>5===6?2:m>>4===14?3:m>>3===30?4:m>>6===2?-1:-2}function s(m,w,E){var v=w.length-1;if(v<E)return 0;var x=i(w[v]);return x>=0?(x>0&&(m.lastNeed=x-1),x):--v<E||x===-2?0:(x=i(w[v]),x>=0?(x>0&&(m.lastNeed=x-2),x):--v<E||x===-2?0:(x=i(w[v]),x>=0?(x>0&&(x===2?x=0:m.lastNeed=x-3),x):0))}function o(m,w,E){if((w[0]&192)!==128)return m.lastNeed=0,"�";if(m.lastNeed>1&&w.length>1){if((w[1]&192)!==128)return m.lastNeed=1,"�";if(m.lastNeed>2&&w.length>2&&(w[2]&192)!==128)return m.lastNeed=2,"�"}}function l(m){var w=this.lastTotal-this.lastNeed,E=o(this,m);if(E!==void 0)return E;if(this.lastNeed<=m.length)return m.copy(this.lastChar,w,0,this.lastNeed),this.lastChar.toString(this.encoding,0,this.lastTotal);m.copy(this.lastChar,w,0,m.length),this.lastNeed-=m.length}function u(m,w){var E=s(this,m,w);if(!this.lastNeed)return m.toString("utf8",w);this.lastTotal=E;var v=m.length-(E-this.lastNeed);return m.copy(this.lastChar,0,v),m.toString("utf8",w,v)}function d(m){var w=m&&m.length?this.write(m):"";return this.lastNeed?w+"�":w}function p(m,w){if((m.length-w)%2===0){var E=m.toString("utf16le",w);if(E){var v=E.charCodeAt(E.length-1);if(v>=55296&&v<=56319)return this.lastNeed=2,this.lastTotal=4,this.lastChar[0]=m[m.length-2],this.lastChar[1]=m[m.length-1],E.slice(0,-1)}return E}return this.lastNeed=1,this.lastTotal=2,this.lastChar[0]=m[m.length-1],m.toString("utf16le",w,m.length-1)}function y(m){var w=m&&m.length?this.write(m):"";if(this.lastNeed){var E=this.lastTotal-this.lastNeed;return w+this.lastChar.toString("utf16le",0,E)}return w}function f(m,w){var E=(m.length-w)%3;return E===0?m.toString("base64",w):(this.lastNeed=3-E,this.lastTotal=3,E===1?this.lastChar[0]=m[m.length-1]:(this.lastChar[0]=m[m.length-2],this.lastChar[1]=m[m.length-1]),m.toString("base64",w,m.length-E))}function g(m){var w=m&&m.length?this.write(m):"";return this.lastNeed?w+this.lastChar.toString("base64",0,3-this.lastNeed):w}function b(m){return m.toString(this.encoding)}function k(m){return m&&m.length?this.write(m):""}}),Ho=pe((c,e)=>{le(),ue(),ce();var t=St(),{PromisePrototypeThen:r,SymbolAsyncIterator:a,SymbolIterator:n}=je(),{Buffer:i}=(Ue(),Pe(Ne)),{ERR_INVALID_ARG_TYPE:s,ERR_STREAM_NULL_VALUES:o}=We().codes;function l(u,d,p){let y;if(typeof d=="string"||d instanceof i)return new u({objectMode:!0,...p,read(){this.push(d),this.push(null)}});let f;if(d&&d[a])f=!0,y=d[a]();else if(d&&d[n])f=!1,y=d[n]();else throw new s("iterable",["Iterable"],d);let g=new u({objectMode:!0,highWaterMark:1,...p}),b=!1;g._read=function(){b||(b=!0,m())},g._destroy=function(w,E){r(k(w),()=>t.nextTick(E,w),v=>t.nextTick(E,v||w))};async function k(w){let E=w!=null,v=typeof y.throw=="function";if(E&&v){let{value:x,done:S}=await y.throw(w);if(await x,S)return}if(typeof y.return=="function"){let{value:x}=await y.return();await x}}async function m(){for(;;){try{let{value:w,done:E}=f?await y.next():y.next();if(E)g.push(null);else{let v=w&&typeof w.then=="function"?await w:w;if(v===null)throw b=!1,new o;if(g.push(v))continue;b=!1}}catch(w){g.destroy(w)}break}}return g}e.exports=l}),or=pe((c,e)=>{le(),ue(),ce();var t=St(),{ArrayPrototypeIndexOf:r,NumberIsInteger:a,NumberIsNaN:n,NumberParseInt:i,ObjectDefineProperties:s,ObjectKeys:o,ObjectSetPrototypeOf:l,Promise:u,SafeSet:d,SymbolAsyncDispose:p,SymbolAsyncIterator:y,Symbol:f}=je();e.exports=se,se.ReadableState=ve;var{EventEmitter:g}=(kt(),Pe(pt)),{Stream:b,prependListener:k}=ti(),{Buffer:m}=(Ue(),Pe(Ne)),{addAbortSignal:w}=nr(),E=gt(),v=ze().debuglog("stream",C=>{v=C}),x=fc(),S=Mt(),{getHighWaterMark:I,getDefaultHighWaterMark:M}=ir(),{aggregateTwoErrors:O,codes:{ERR_INVALID_ARG_TYPE:B,ERR_METHOD_NOT_IMPLEMENTED:T,ERR_OUT_OF_RANGE:W,ERR_STREAM_PUSH_AFTER_EOF:F,ERR_STREAM_UNSHIFT_AFTER_END_EVENT:N},AbortError:ae}=We(),{validateObject:Y}=zt(),K=f("kPaused"),{StringDecoder:re}=pc(),D=Ho();l(se.prototype,b.prototype),l(se,b);var Z=()=>{},{errorOrDestroy:P}=S,J=1,be=2,te=4,we=8,V=16,L=32,ne=64,H=128,G=256,Q=512,me=1024,oe=2048,R=4096,$=8192,ee=16384,fe=32768,de=65536,ye=1<<17,q=1<<18;function ge(C){return{enumerable:!1,get(){return(this.state&C)!==0},set(j){j?this.state|=C:this.state&=~C}}}s(ve.prototype,{objectMode:ge(J),ended:ge(be),endEmitted:ge(te),reading:ge(we),constructed:ge(V),sync:ge(L),needReadable:ge(ne),emittedReadable:ge(H),readableListening:ge(G),resumeScheduled:ge(Q),errorEmitted:ge(me),emitClose:ge(oe),autoDestroy:ge(R),destroyed:ge($),closed:ge(ee),closeEmitted:ge(fe),multiAwaitDrain:ge(de),readingMore:ge(ye),dataEmitted:ge(q)});function ve(C,j,_e){typeof _e!="boolean"&&(_e=j instanceof at()),this.state=oe|R|V|L,C&&C.objectMode&&(this.state|=J),_e&&C&&C.readableObjectMode&&(this.state|=J),this.highWaterMark=C?I(this,C,"readableHighWaterMark",_e):M(!1),this.buffer=new x,this.length=0,this.pipes=[],this.flowing=null,this[K]=null,C&&C.emitClose===!1&&(this.state&=~oe),C&&C.autoDestroy===!1&&(this.state&=~R),this.errored=null,this.defaultEncoding=C&&C.defaultEncoding||"utf8",this.awaitDrainWriters=null,this.decoder=null,this.encoding=null,C&&C.encoding&&(this.decoder=new re(C.encoding),this.encoding=C.encoding)}function se(C){if(!(this instanceof se))return new se(C);let j=this instanceof at();this._readableState=new ve(C,this,j),C&&(typeof C.read=="function"&&(this._read=C.read),typeof C.destroy=="function"&&(this._destroy=C.destroy),typeof C.construct=="function"&&(this._construct=C.construct),C.signal&&!j&&w(C.signal,this)),b.call(this,C),S.construct(this,()=>{this._readableState.needReadable&&z(this,this._readableState)})}se.prototype.destroy=S.destroy,se.prototype._undestroy=S.undestroy,se.prototype._destroy=function(C,j){j(C)},se.prototype[g.captureRejectionSymbol]=function(C){this.destroy(C)},se.prototype[p]=function(){let C;return this.destroyed||(C=this.readableEnded?null:new ae,this.destroy(C)),new u((j,_e)=>E(this,Se=>Se&&Se!==C?_e(Se):j(null)))},se.prototype.push=function(C,j){return Te(this,C,j,!1)},se.prototype.unshift=function(C,j){return Te(this,C,j,!0)};function Te(C,j,_e,Se){v("readableAddChunk",j);let Ee=C._readableState,Le;if((Ee.state&J)===0&&(typeof j=="string"?(_e=_e||Ee.defaultEncoding,Ee.encoding!==_e&&(Se&&Ee.encoding?j=m.from(j,_e).toString(Ee.encoding):(j=m.from(j,_e),_e=""))):j instanceof m?_e="":b._isUint8Array(j)?(j=b._uint8ArrayToBuffer(j),_e=""):j!=null&&(Le=new B("chunk",["string","Buffer","Uint8Array"],j))),Le)P(C,Le);else if(j===null)Ee.state&=~we,X(C,Ee);else if((Ee.state&J)!==0||j&&j.length>0)if(Se)if((Ee.state&te)!==0)P(C,new N);else{if(Ee.destroyed||Ee.errored)return!1;h(C,Ee,j,!0)}else if(Ee.ended)P(C,new F);else{if(Ee.destroyed||Ee.errored)return!1;Ee.state&=~we,Ee.decoder&&!_e?(j=Ee.decoder.write(j),Ee.objectMode||j.length!==0?h(C,Ee,j,!1):z(C,Ee)):h(C,Ee,j,!1)}else Se||(Ee.state&=~we,z(C,Ee));return!Ee.ended&&(Ee.length<Ee.highWaterMark||Ee.length===0)}function h(C,j,_e,Se){j.flowing&&j.length===0&&!j.sync&&C.listenerCount("data")>0?((j.state&de)!==0?j.awaitDrainWriters.clear():j.awaitDrainWriters=null,j.dataEmitted=!0,C.emit("data",_e)):(j.length+=j.objectMode?1:_e.length,Se?j.buffer.unshift(_e):j.buffer.push(_e),(j.state&ne)!==0&&he(C)),z(C,j)}se.prototype.isPaused=function(){let C=this._readableState;return C[K]===!0||C.flowing===!1},se.prototype.setEncoding=function(C){let j=new re(C);this._readableState.decoder=j,this._readableState.encoding=this._readableState.decoder.encoding;let _e=this._readableState.buffer,Se="";for(let Ee of _e)Se+=j.write(Ee);return _e.clear(),Se!==""&&_e.push(Se),this._readableState.length=Se.length,this};var _=1073741824;function A(C){if(C>_)throw new W("size","<= 1GiB",C);return C--,C|=C>>>1,C|=C>>>2,C|=C>>>4,C|=C>>>8,C|=C>>>16,C++,C}function U(C,j){return C<=0||j.length===0&&j.ended?0:(j.state&J)!==0?1:n(C)?j.flowing&&j.length?j.buffer.first().length:j.length:C<=j.length?C:j.ended?j.length:0}se.prototype.read=function(C){v("read",C),C===void 0?C=NaN:a(C)||(C=i(C,10));let j=this._readableState,_e=C;if(C>j.highWaterMark&&(j.highWaterMark=A(C)),C!==0&&(j.state&=~H),C===0&&j.needReadable&&((j.highWaterMark!==0?j.length>=j.highWaterMark:j.length>0)||j.ended))return v("read: emitReadable",j.length,j.ended),j.length===0&&j.ended?et(this):he(this),null;if(C=U(C,j),C===0&&j.ended)return j.length===0&&et(this),null;let Se=(j.state&ne)!==0;if(v("need readable",Se),(j.length===0||j.length-C<j.highWaterMark)&&(Se=!0,v("length less than watermark",Se)),j.ended||j.reading||j.destroyed||j.errored||!j.constructed)Se=!1,v("reading, ended or constructing",Se);else if(Se){v("do read"),j.state|=we|L,j.length===0&&(j.state|=ne);try{this._read(j.highWaterMark)}catch(Le){P(this,Le)}j.state&=~L,j.reading||(C=U(_e,j))}let Ee;return C>0?Ee=Bt(C,j):Ee=null,Ee===null?(j.needReadable=j.length<=j.highWaterMark,C=0):(j.length-=C,j.multiAwaitDrain?j.awaitDrainWriters.clear():j.awaitDrainWriters=null),j.length===0&&(j.ended||(j.needReadable=!0),_e!==C&&j.ended&&et(this)),Ee!==null&&!j.errorEmitted&&!j.closeEmitted&&(j.dataEmitted=!0,this.emit("data",Ee)),Ee};function X(C,j){if(v("onEofChunk"),!j.ended){if(j.decoder){let _e=j.decoder.end();_e&&_e.length&&(j.buffer.push(_e),j.length+=j.objectMode?1:_e.length)}j.ended=!0,j.sync?he(C):(j.needReadable=!1,j.emittedReadable=!0,ke(C))}}function he(C){let j=C._readableState;v("emitReadable",j.needReadable,j.emittedReadable),j.needReadable=!1,j.emittedReadable||(v("emitReadable",j.flowing),j.emittedReadable=!0,t.nextTick(ke,C))}function ke(C){let j=C._readableState;v("emitReadable_",j.destroyed,j.length,j.ended),!j.destroyed&&!j.errored&&(j.length||j.ended)&&(C.emit("readable"),j.emittedReadable=!1),j.needReadable=!j.flowing&&!j.ended&&j.length<=j.highWaterMark,Xe(C)}function z(C,j){!j.readingMore&&j.constructed&&(j.readingMore=!0,t.nextTick(ie,C,j))}function ie(C,j){for(;!j.reading&&!j.ended&&(j.length<j.highWaterMark||j.flowing&&j.length===0);){let _e=j.length;if(v("maybeReadMore read 0"),C.read(0),_e===j.length)break}j.readingMore=!1}se.prototype._read=function(C){throw new T("_read()")},se.prototype.pipe=function(C,j){let _e=this,Se=this._readableState;Se.pipes.length===1&&(Se.multiAwaitDrain||(Se.multiAwaitDrain=!0,Se.awaitDrainWriters=new d(Se.awaitDrainWriters?[Se.awaitDrainWriters]:[]))),Se.pipes.push(C),v("pipe count=%d opts=%j",Se.pipes.length,j);let Ee=(!j||j.end!==!1)&&C!==t.stdout&&C!==t.stderr?qe:Tt;Se.endEmitted?t.nextTick(Ee):_e.once("end",Ee),C.on("unpipe",Le);function Le(rt,ft){v("onunpipe"),rt===_e&&ft&&ft.hasUnpiped===!1&&(ft.hasUnpiped=!0,Qt())}function qe(){v("onend"),C.end()}let Ge,Yt=!1;function Qt(){v("cleanup"),C.removeListener("close",tt),C.removeListener("finish",vt),Ge&&C.removeListener("drain",Ge),C.removeListener("error",It),C.removeListener("unpipe",Le),_e.removeListener("end",qe),_e.removeListener("end",Tt),_e.removeListener("data",Fr),Yt=!0,Ge&&Se.awaitDrainWriters&&(!C._writableState||C._writableState.needDrain)&&Ge()}function Jt(){Yt||(Se.pipes.length===1&&Se.pipes[0]===C?(v("false write response, pause",0),Se.awaitDrainWriters=C,Se.multiAwaitDrain=!1):Se.pipes.length>1&&Se.pipes.includes(C)&&(v("false write response, pause",Se.awaitDrainWriters.size),Se.awaitDrainWriters.add(C)),_e.pause()),Ge||(Ge=xe(_e,C),C.on("drain",Ge))}_e.on("data",Fr);function Fr(rt){v("ondata");let ft=C.write(rt);v("dest.write",ft),ft===!1&&Jt()}function It(rt){if(v("onerror",rt),Tt(),C.removeListener("error",It),C.listenerCount("error")===0){let ft=C._writableState||C._readableState;ft&&!ft.errorEmitted?P(C,rt):C.emit("error",rt)}}k(C,"error",It);function tt(){C.removeListener("finish",vt),Tt()}C.once("close",tt);function vt(){v("onfinish"),C.removeListener("close",tt),Tt()}C.once("finish",vt);function Tt(){v("unpipe"),_e.unpipe(C)}return C.emit("pipe",_e),C.writableNeedDrain===!0?Jt():Se.flowing||(v("pipe resume"),_e.resume()),C};function xe(C,j){return function(){let _e=C._readableState;_e.awaitDrainWriters===j?(v("pipeOnDrain",1),_e.awaitDrainWriters=null):_e.multiAwaitDrain&&(v("pipeOnDrain",_e.awaitDrainWriters.size),_e.awaitDrainWriters.delete(j)),(!_e.awaitDrainWriters||_e.awaitDrainWriters.size===0)&&C.listenerCount("data")&&C.resume()}}se.prototype.unpipe=function(C){let j=this._readableState,_e={hasUnpiped:!1};if(j.pipes.length===0)return this;if(!C){let Ee=j.pipes;j.pipes=[],this.pause();for(let Le=0;Le<Ee.length;Le++)Ee[Le].emit("unpipe",this,{hasUnpiped:!1});return this}let Se=r(j.pipes,C);return Se===-1?this:(j.pipes.splice(Se,1),j.pipes.length===0&&this.pause(),C.emit("unpipe",this,_e),this)},se.prototype.on=function(C,j){let _e=b.prototype.on.call(this,C,j),Se=this._readableState;return C==="data"?(Se.readableListening=this.listenerCount("readable")>0,Se.flowing!==!1&&this.resume()):C==="readable"&&!Se.endEmitted&&!Se.readableListening&&(Se.readableListening=Se.needReadable=!0,Se.flowing=!1,Se.emittedReadable=!1,v("on readable",Se.length,Se.reading),Se.length?he(this):Se.reading||t.nextTick(Ie,this)),_e},se.prototype.addListener=se.prototype.on,se.prototype.removeListener=function(C,j){let _e=b.prototype.removeListener.call(this,C,j);return C==="readable"&&t.nextTick(Ae,this),_e},se.prototype.off=se.prototype.removeListener,se.prototype.removeAllListeners=function(C){let j=b.prototype.removeAllListeners.apply(this,arguments);return(C==="readable"||C===void 0)&&t.nextTick(Ae,this),j};function Ae(C){let j=C._readableState;j.readableListening=C.listenerCount("readable")>0,j.resumeScheduled&&j[K]===!1?j.flowing=!0:C.listenerCount("data")>0?C.resume():j.readableListening||(j.flowing=null)}function Ie(C){v("readable nexttick read 0"),C.read(0)}se.prototype.resume=function(){let C=this._readableState;return C.flowing||(v("resume"),C.flowing=!C.readableListening,Oe(this,C)),C[K]=!1,this};function Oe(C,j){j.resumeScheduled||(j.resumeScheduled=!0,t.nextTick(Je,C,j))}function Je(C,j){v("resume",j.reading),j.reading||C.read(0),j.resumeScheduled=!1,C.emit("resume"),Xe(C),j.flowing&&!j.reading&&C.read(0)}se.prototype.pause=function(){return v("call pause flowing=%j",this._readableState.flowing),this._readableState.flowing!==!1&&(v("pause"),this._readableState.flowing=!1,this.emit("pause")),this._readableState[K]=!0,this};function Xe(C){let j=C._readableState;for(v("flow",j.flowing);j.flowing&&C.read()!==null;);}se.prototype.wrap=function(C){let j=!1;C.on("data",Se=>{!this.push(Se)&&C.pause&&(j=!0,C.pause())}),C.on("end",()=>{this.push(null)}),C.on("error",Se=>{P(this,Se)}),C.on("close",()=>{this.destroy()}),C.on("destroy",()=>{this.destroy()}),this._read=()=>{j&&C.resume&&(j=!1,C.resume())};let _e=o(C);for(let Se=1;Se<_e.length;Se++){let Ee=_e[Se];this[Ee]===void 0&&typeof C[Ee]=="function"&&(this[Ee]=C[Ee].bind(C))}return this},se.prototype[y]=function(){return $e(this)},se.prototype.iterator=function(C){return C!==void 0&&Y(C,"options"),$e(this,C)};function $e(C,j){typeof C.read!="function"&&(C=se.wrap(C,{objectMode:!0}));let _e=Ze(C,j);return _e.stream=C,_e}async function*Ze(C,j){let _e=Z;function Se(qe){this===C?(_e(),_e=Z):_e=qe}C.on("readable",Se);let Ee,Le=E(C,{writable:!1},qe=>{Ee=qe?O(Ee,qe):null,_e(),_e=Z});try{for(;;){let qe=C.destroyed?null:C.read();if(qe!==null)yield qe;else{if(Ee)throw Ee;if(Ee===null)return;await new u(Se)}}}catch(qe){throw Ee=O(Ee,qe),Ee}finally{(Ee||j?.destroyOnReturn!==!1)&&(Ee===void 0||C._readableState.autoDestroy)?S.destroyer(C,null):(C.off("readable",Se),Le())}}s(se.prototype,{readable:{__proto__:null,get(){let C=this._readableState;return!!C&&C.readable!==!1&&!C.destroyed&&!C.errorEmitted&&!C.endEmitted},set(C){this._readableState&&(this._readableState.readable=!!C)}},readableDidRead:{__proto__:null,enumerable:!1,get:function(){return this._readableState.dataEmitted}},readableAborted:{__proto__:null,enumerable:!1,get:function(){return!!(this._readableState.readable!==!1&&(this._readableState.destroyed||this._readableState.errored)&&!this._readableState.endEmitted)}},readableHighWaterMark:{__proto__:null,enumerable:!1,get:function(){return this._readableState.highWaterMark}},readableBuffer:{__proto__:null,enumerable:!1,get:function(){return this._readableState&&this._readableState.buffer}},readableFlowing:{__proto__:null,enumerable:!1,get:function(){return this._readableState.flowing},set:function(C){this._readableState&&(this._readableState.flowing=C)}},readableLength:{__proto__:null,enumerable:!1,get(){return this._readableState.length}},readableObjectMode:{__proto__:null,enumerable:!1,get(){return this._readableState?this._readableState.objectMode:!1}},readableEncoding:{__proto__:null,enumerable:!1,get(){return this._readableState?this._readableState.encoding:null}},errored:{__proto__:null,enumerable:!1,get(){return this._readableState?this._readableState.errored:null}},closed:{__proto__:null,get(){return this._readableState?this._readableState.closed:!1}},destroyed:{__proto__:null,enumerable:!1,get(){return this._readableState?this._readableState.destroyed:!1},set(C){this._readableState&&(this._readableState.destroyed=C)}},readableEnded:{__proto__:null,enumerable:!1,get(){return this._readableState?this._readableState.endEmitted:!1}}}),s(ve.prototype,{pipesCount:{__proto__:null,get(){return this.pipes.length}},paused:{__proto__:null,get(){return this[K]!==!1},set(C){this[K]=!!C}}}),se._fromList=Bt;function Bt(C,j){if(j.length===0)return null;let _e;return j.objectMode?_e=j.buffer.shift():!C||C>=j.length?(j.decoder?_e=j.buffer.join(""):j.buffer.length===1?_e=j.buffer.first():_e=j.buffer.concat(j.length),j.buffer.clear()):_e=j.buffer.consume(C,j.decoder),_e}function et(C){let j=C._readableState;v("endReadable",j.endEmitted),j.endEmitted||(j.ended=!0,t.nextTick(Ve,j,C))}function Ve(C,j){if(v("endReadableNT",C.endEmitted,C.length),!C.errored&&!C.closeEmitted&&!C.endEmitted&&C.length===0){if(C.endEmitted=!0,j.emit("end"),j.writable&&j.allowHalfOpen===!1)t.nextTick(Br,j);else if(C.autoDestroy){let _e=j._writableState;(!_e||_e.autoDestroy&&(_e.finished||_e.writable===!1))&&j.destroy()}}}function Br(C){C.writable&&!C.writableEnded&&!C.destroyed&&C.end()}se.from=function(C,j){return D(se,C,j)};var Ft;function Gt(){return Ft===void 0&&(Ft={}),Ft}se.fromWeb=function(C,j){return Gt().newStreamReadableFromReadableStream(C,j)},se.toWeb=function(C,j){return Gt().newReadableStreamFromStreamReadable(C,j)},se.wrap=function(C,j){var _e,Se;return new se({objectMode:(_e=(Se=C.readableObjectMode)!==null&&Se!==void 0?Se:C.objectMode)!==null&&_e!==void 0?_e:!0,...j,destroy(Ee,Le){S.destroyer(C,Ee),Le(Ee)}}).wrap(C)}}),ri=pe((c,e)=>{le(),ue(),ce();var t=St(),{ArrayPrototypeSlice:r,Error:a,FunctionPrototypeSymbolHasInstance:n,ObjectDefineProperty:i,ObjectDefineProperties:s,ObjectSetPrototypeOf:o,StringPrototypeToLowerCase:l,Symbol:u,SymbolHasInstance:d}=je();e.exports=Y,Y.WritableState=N;var{EventEmitter:p}=(kt(),Pe(pt)),y=ti().Stream,{Buffer:f}=(Ue(),Pe(Ne)),g=Mt(),{addAbortSignal:b}=nr(),{getHighWaterMark:k,getDefaultHighWaterMark:m}=ir(),{ERR_INVALID_ARG_TYPE:w,ERR_METHOD_NOT_IMPLEMENTED:E,ERR_MULTIPLE_CALLBACK:v,ERR_STREAM_CANNOT_PIPE:x,ERR_STREAM_DESTROYED:S,ERR_STREAM_ALREADY_FINISHED:I,ERR_STREAM_NULL_VALUES:M,ERR_STREAM_WRITE_AFTER_END:O,ERR_UNKNOWN_ENCODING:B}=We().codes,{errorOrDestroy:T}=g;o(Y.prototype,y.prototype),o(Y,y);function W(){}var F=u("kOnFinished");function N(R,$,ee){typeof ee!="boolean"&&(ee=$ instanceof at()),this.objectMode=!!(R&&R.objectMode),ee&&(this.objectMode=this.objectMode||!!(R&&R.writableObjectMode)),this.highWaterMark=R?k(this,R,"writableHighWaterMark",ee):m(!1),this.finalCalled=!1,this.needDrain=!1,this.ending=!1,this.ended=!1,this.finished=!1,this.destroyed=!1;let fe=!!(R&&R.decodeStrings===!1);this.decodeStrings=!fe,this.defaultEncoding=R&&R.defaultEncoding||"utf8",this.length=0,this.writing=!1,this.corked=0,this.sync=!0,this.bufferProcessing=!1,this.onwrite=P.bind(void 0,$),this.writecb=null,this.writelen=0,this.afterWriteTickInfo=null,ae(this),this.pendingcb=0,this.constructed=!0,this.prefinished=!1,this.errorEmitted=!1,this.emitClose=!R||R.emitClose!==!1,this.autoDestroy=!R||R.autoDestroy!==!1,this.errored=null,this.closed=!1,this.closeEmitted=!1,this[F]=[]}function ae(R){R.buffered=[],R.bufferedIndex=0,R.allBuffers=!0,R.allNoop=!0}N.prototype.getBuffer=function(){return r(this.buffered,this.bufferedIndex)},i(N.prototype,"bufferedRequestCount",{__proto__:null,get(){return this.buffered.length-this.bufferedIndex}});function Y(R){let $=this instanceof at();if(!$&&!n(Y,this))return new Y(R);this._writableState=new N(R,this,$),R&&(typeof R.write=="function"&&(this._write=R.write),typeof R.writev=="function"&&(this._writev=R.writev),typeof R.destroy=="function"&&(this._destroy=R.destroy),typeof R.final=="function"&&(this._final=R.final),typeof R.construct=="function"&&(this._construct=R.construct),R.signal&&b(R.signal,this)),y.call(this,R),g.construct(this,()=>{let ee=this._writableState;ee.writing||we(this,ee),H(this,ee)})}i(Y,d,{__proto__:null,value:function(R){return n(this,R)?!0:this!==Y?!1:R&&R._writableState instanceof N}}),Y.prototype.pipe=function(){T(this,new x)};function K(R,$,ee,fe){let de=R._writableState;if(typeof ee=="function")fe=ee,ee=de.defaultEncoding;else{if(!ee)ee=de.defaultEncoding;else if(ee!=="buffer"&&!f.isEncoding(ee))throw new B(ee);typeof fe!="function"&&(fe=W)}if($===null)throw new M;if(!de.objectMode)if(typeof $=="string")de.decodeStrings!==!1&&($=f.from($,ee),ee="buffer");else if($ instanceof f)ee="buffer";else if(y._isUint8Array($))$=y._uint8ArrayToBuffer($),ee="buffer";else throw new w("chunk",["string","Buffer","Uint8Array"],$);let ye;return de.ending?ye=new O:de.destroyed&&(ye=new S("write")),ye?(t.nextTick(fe,ye),T(R,ye,!0),ye):(de.pendingcb++,re(R,de,$,ee,fe))}Y.prototype.write=function(R,$,ee){return K(this,R,$,ee)===!0},Y.prototype.cork=function(){this._writableState.corked++},Y.prototype.uncork=function(){let R=this._writableState;R.corked&&(R.corked--,R.writing||we(this,R))},Y.prototype.setDefaultEncoding=function(R){if(typeof R=="string"&&(R=l(R)),!f.isEncoding(R))throw new B(R);return this._writableState.defaultEncoding=R,this};function re(R,$,ee,fe,de){let ye=$.objectMode?1:ee.length;$.length+=ye;let q=$.length<$.highWaterMark;return q||($.needDrain=!0),$.writing||$.corked||$.errored||!$.constructed?($.buffered.push({chunk:ee,encoding:fe,callback:de}),$.allBuffers&&fe!=="buffer"&&($.allBuffers=!1),$.allNoop&&de!==W&&($.allNoop=!1)):($.writelen=ye,$.writecb=de,$.writing=!0,$.sync=!0,R._write(ee,fe,$.onwrite),$.sync=!1),q&&!$.errored&&!$.destroyed}function D(R,$,ee,fe,de,ye,q){$.writelen=fe,$.writecb=q,$.writing=!0,$.sync=!0,$.destroyed?$.onwrite(new S("write")):ee?R._writev(de,$.onwrite):R._write(de,ye,$.onwrite),$.sync=!1}function Z(R,$,ee,fe){--$.pendingcb,fe(ee),te($),T(R,ee)}function P(R,$){let ee=R._writableState,fe=ee.sync,de=ee.writecb;if(typeof de!="function"){T(R,new v);return}ee.writing=!1,ee.writecb=null,ee.length-=ee.writelen,ee.writelen=0,$?($.stack,ee.errored||(ee.errored=$),R._readableState&&!R._readableState.errored&&(R._readableState.errored=$),fe?t.nextTick(Z,R,ee,$,de):Z(R,ee,$,de)):(ee.buffered.length>ee.bufferedIndex&&we(R,ee),fe?ee.afterWriteTickInfo!==null&&ee.afterWriteTickInfo.cb===de?ee.afterWriteTickInfo.count++:(ee.afterWriteTickInfo={count:1,cb:de,stream:R,state:ee},t.nextTick(J,ee.afterWriteTickInfo)):be(R,ee,1,de))}function J({stream:R,state:$,count:ee,cb:fe}){return $.afterWriteTickInfo=null,be(R,$,ee,fe)}function be(R,$,ee,fe){for(!$.ending&&!R.destroyed&&$.length===0&&$.needDrain&&($.needDrain=!1,R.emit("drain"));ee-- >0;)$.pendingcb--,fe();$.destroyed&&te($),H(R,$)}function te(R){if(R.writing)return;for(let de=R.bufferedIndex;de<R.buffered.length;++de){var $;let{chunk:ye,callback:q}=R.buffered[de],ge=R.objectMode?1:ye.length;R.length-=ge,q(($=R.errored)!==null&&$!==void 0?$:new S("write"))}let ee=R[F].splice(0);for(let de=0;de<ee.length;de++){var fe;ee[de]((fe=R.errored)!==null&&fe!==void 0?fe:new S("end"))}ae(R)}function we(R,$){if($.corked||$.bufferProcessing||$.destroyed||!$.constructed)return;let{buffered:ee,bufferedIndex:fe,objectMode:de}=$,ye=ee.length-fe;if(!ye)return;let q=fe;if($.bufferProcessing=!0,ye>1&&R._writev){$.pendingcb-=ye-1;let ge=$.allNoop?W:se=>{for(let Te=q;Te<ee.length;++Te)ee[Te].callback(se)},ve=$.allNoop&&q===0?ee:r(ee,q);ve.allBuffers=$.allBuffers,D(R,$,!0,$.length,ve,"",ge),ae($)}else{do{let{chunk:ge,encoding:ve,callback:se}=ee[q];ee[q++]=null;let Te=de?1:ge.length;D(R,$,!1,Te,ge,ve,se)}while(q<ee.length&&!$.writing);q===ee.length?ae($):q>256?(ee.splice(0,q),$.bufferedIndex=0):$.bufferedIndex=q}$.bufferProcessing=!1}Y.prototype._write=function(R,$,ee){if(this._writev)this._writev([{chunk:R,encoding:$}],ee);else throw new E("_write()")},Y.prototype._writev=null,Y.prototype.end=function(R,$,ee){let fe=this._writableState;typeof R=="function"?(ee=R,R=null,$=null):typeof $=="function"&&(ee=$,$=null);let de;if(R!=null){let ye=K(this,R,$);ye instanceof a&&(de=ye)}return fe.corked&&(fe.corked=1,this.uncork()),de||(!fe.errored&&!fe.ending?(fe.ending=!0,H(this,fe,!0),fe.ended=!0):fe.finished?de=new I("end"):fe.destroyed&&(de=new S("end"))),typeof ee=="function"&&(de||fe.finished?t.nextTick(ee,de):fe[F].push(ee)),this};function V(R){return R.ending&&!R.destroyed&&R.constructed&&R.length===0&&!R.errored&&R.buffered.length===0&&!R.finished&&!R.writing&&!R.errorEmitted&&!R.closeEmitted}function L(R,$){let ee=!1;function fe(de){if(ee){T(R,de??v());return}if(ee=!0,$.pendingcb--,de){let ye=$[F].splice(0);for(let q=0;q<ye.length;q++)ye[q](de);T(R,de,$.sync)}else V($)&&($.prefinished=!0,R.emit("prefinish"),$.pendingcb++,t.nextTick(G,R,$))}$.sync=!0,$.pendingcb++;try{R._final(fe)}catch(de){fe(de)}$.sync=!1}function ne(R,$){!$.prefinished&&!$.finalCalled&&(typeof R._final=="function"&&!$.destroyed?($.finalCalled=!0,L(R,$)):($.prefinished=!0,R.emit("prefinish")))}function H(R,$,ee){V($)&&(ne(R,$),$.pendingcb===0&&(ee?($.pendingcb++,t.nextTick((fe,de)=>{V(de)?G(fe,de):de.pendingcb--},R,$)):V($)&&($.pendingcb++,G(R,$))))}function G(R,$){$.pendingcb--,$.finished=!0;let ee=$[F].splice(0);for(let fe=0;fe<ee.length;fe++)ee[fe]();if(R.emit("finish"),$.autoDestroy){let fe=R._readableState;(!fe||fe.autoDestroy&&(fe.endEmitted||fe.readable===!1))&&R.destroy()}}s(Y.prototype,{closed:{__proto__:null,get(){return this._writableState?this._writableState.closed:!1}},destroyed:{__proto__:null,get(){return this._writableState?this._writableState.destroyed:!1},set(R){this._writableState&&(this._writableState.destroyed=R)}},writable:{__proto__:null,get(){let R=this._writableState;return!!R&&R.writable!==!1&&!R.destroyed&&!R.errored&&!R.ending&&!R.ended},set(R){this._writableState&&(this._writableState.writable=!!R)}},writableFinished:{__proto__:null,get(){return this._writableState?this._writableState.finished:!1}},writableObjectMode:{__proto__:null,get(){return this._writableState?this._writableState.objectMode:!1}},writableBuffer:{__proto__:null,get(){return this._writableState&&this._writableState.getBuffer()}},writableEnded:{__proto__:null,get(){return this._writableState?this._writableState.ending:!1}},writableNeedDrain:{__proto__:null,get(){let R=this._writableState;return R?!R.destroyed&&!R.ending&&R.needDrain:!1}},writableHighWaterMark:{__proto__:null,get(){return this._writableState&&this._writableState.highWaterMark}},writableCorked:{__proto__:null,get(){return this._writableState?this._writableState.corked:0}},writableLength:{__proto__:null,get(){return this._writableState&&this._writableState.length}},errored:{__proto__:null,enumerable:!1,get(){return this._writableState?this._writableState.errored:null}},writableAborted:{__proto__:null,enumerable:!1,get:function(){return!!(this._writableState.writable!==!1&&(this._writableState.destroyed||this._writableState.errored)&&!this._writableState.finished)}}});var Q=g.destroy;Y.prototype.destroy=function(R,$){let ee=this._writableState;return!ee.destroyed&&(ee.bufferedIndex<ee.buffered.length||ee[F].length)&&t.nextTick(te,ee),Q.call(this,R,$),this},Y.prototype._undestroy=g.undestroy,Y.prototype._destroy=function(R,$){$(R)},Y.prototype[p.captureRejectionSymbol]=function(R){this.destroy(R)};var me;function oe(){return me===void 0&&(me={}),me}Y.fromWeb=function(R,$){return oe().newStreamWritableFromWritableStream(R,$)},Y.toWeb=function(R){return oe().newWritableStreamFromStreamWritable(R)}}),gc=pe((c,e)=>{le(),ue(),ce();var t=St(),r=(Ue(),Pe(Ne)),{isReadable:a,isWritable:n,isIterable:i,isNodeStream:s,isReadableNodeStream:o,isWritableNodeStream:l,isDuplexNodeStream:u,isReadableStream:d,isWritableStream:p}=st(),y=gt(),{AbortError:f,codes:{ERR_INVALID_ARG_TYPE:g,ERR_INVALID_RETURN_VALUE:b}}=We(),{destroyer:k}=Mt(),m=at(),w=or(),E=ri(),{createDeferredPromise:v}=ze(),x=Ho(),S=globalThis.Blob||r.Blob,I=typeof S<"u"?function(F){return F instanceof S}:function(F){return!1},M=globalThis.AbortController||qt().AbortController,{FunctionPrototypeCall:O}=je(),B=class extends m{constructor(F){super(F),F?.readable===!1&&(this._readableState.readable=!1,this._readableState.ended=!0,this._readableState.endEmitted=!0),F?.writable===!1&&(this._writableState.writable=!1,this._writableState.ending=!0,this._writableState.ended=!0,this._writableState.finished=!0)}};e.exports=function F(N,ae){if(u(N))return N;if(o(N))return W({readable:N});if(l(N))return W({writable:N});if(s(N))return W({writable:!1,readable:!1});if(d(N))return W({readable:w.fromWeb(N)});if(p(N))return W({writable:E.fromWeb(N)});if(typeof N=="function"){let{value:K,write:re,final:D,destroy:Z}=T(N);if(i(K))return x(B,K,{objectMode:!0,write:re,final:D,destroy:Z});let P=K?.then;if(typeof P=="function"){let J,be=O(P,K,te=>{if(te!=null)throw new b("nully","body",te)},te=>{k(J,te)});return J=new B({objectMode:!0,readable:!1,write:re,final(te){D(async()=>{try{await be,t.nextTick(te,null)}catch(we){t.nextTick(te,we)}})},destroy:Z})}throw new b("Iterable, AsyncIterable or AsyncFunction",ae,K)}if(I(N))return F(N.arrayBuffer());if(i(N))return x(B,N,{objectMode:!0,writable:!1});if(d(N?.readable)&&p(N?.writable))return B.fromWeb(N);if(typeof N?.writable=="object"||typeof N?.readable=="object"){let K=N!=null&&N.readable?o(N?.readable)?N?.readable:F(N.readable):void 0,re=N!=null&&N.writable?l(N?.writable)?N?.writable:F(N.writable):void 0;return W({readable:K,writable:re})}let Y=N?.then;if(typeof Y=="function"){let K;return O(Y,N,re=>{re!=null&&K.push(re),K.push(null)},re=>{k(K,re)}),K=new B({objectMode:!0,writable:!1,read(){}})}throw new g(ae,["Blob","ReadableStream","WritableStream","Stream","Iterable","AsyncIterable","Function","{ readable, writable } pair","Promise"],N)};function T(F){let{promise:N,resolve:ae}=v(),Y=new M,K=Y.signal;return{value:F((async function*(){for(;;){let re=N;N=null;let{chunk:D,done:Z,cb:P}=await re;if(t.nextTick(P),Z)return;if(K.aborted)throw new f(void 0,{cause:K.reason});({promise:N,resolve:ae}=v()),yield D}})(),{signal:K}),write(re,D,Z){let P=ae;ae=null,P({chunk:re,done:!1,cb:Z})},final(re){let D=ae;ae=null,D({done:!0,cb:re})},destroy(re,D){Y.abort(),D(re)}}}function W(F){let N=F.readable&&typeof F.readable.read!="function"?w.wrap(F.readable):F.readable,ae=F.writable,Y=!!a(N),K=!!n(ae),re,D,Z,P,J;function be(te){let we=P;P=null,we?we(te):te&&J.destroy(te)}return J=new B({readableObjectMode:!!(N!=null&&N.readableObjectMode),writableObjectMode:!!(ae!=null&&ae.writableObjectMode),readable:Y,writable:K}),K&&(y(ae,te=>{K=!1,te&&k(N,te),be(te)}),J._write=function(te,we,V){ae.write(te,we)?V():re=V},J._final=function(te){ae.end(),D=te},ae.on("drain",function(){if(re){let te=re;re=null,te()}}),ae.on("finish",function(){if(D){let te=D;D=null,te()}})),Y&&(y(N,te=>{Y=!1,te&&k(N,te),be(te)}),N.on("readable",function(){if(Z){let te=Z;Z=null,te()}}),N.on("end",function(){J.push(null)}),J._read=function(){for(;;){let te=N.read();if(te===null){Z=J._read;return}if(!J.push(te))return}}),J._destroy=function(te,we){!te&&P!==null&&(te=new f),Z=null,re=null,D=null,P===null?we(te):(P=we,k(ae,te),k(N,te))},J}}),at=pe((c,e)=>{le(),ue(),ce();var{ObjectDefineProperties:t,ObjectGetOwnPropertyDescriptor:r,ObjectKeys:a,ObjectSetPrototypeOf:n}=je();e.exports=o;var i=or(),s=ri();n(o.prototype,i.prototype),n(o,i);{let p=a(s.prototype);for(let y=0;y<p.length;y++){let f=p[y];o.prototype[f]||(o.prototype[f]=s.prototype[f])}}function o(p){if(!(this instanceof o))return new o(p);i.call(this,p),s.call(this,p),p?(this.allowHalfOpen=p.allowHalfOpen!==!1,p.readable===!1&&(this._readableState.readable=!1,this._readableState.ended=!0,this._readableState.endEmitted=!0),p.writable===!1&&(this._writableState.writable=!1,this._writableState.ending=!0,this._writableState.ended=!0,this._writableState.finished=!0)):this.allowHalfOpen=!0}t(o.prototype,{writable:{__proto__:null,...r(s.prototype,"writable")},writableHighWaterMark:{__proto__:null,...r(s.prototype,"writableHighWaterMark")},writableObjectMode:{__proto__:null,...r(s.prototype,"writableObjectMode")},writableBuffer:{__proto__:null,...r(s.prototype,"writableBuffer")},writableLength:{__proto__:null,...r(s.prototype,"writableLength")},writableFinished:{__proto__:null,...r(s.prototype,"writableFinished")},writableCorked:{__proto__:null,...r(s.prototype,"writableCorked")},writableEnded:{__proto__:null,...r(s.prototype,"writableEnded")},writableNeedDrain:{__proto__:null,...r(s.prototype,"writableNeedDrain")},destroyed:{__proto__:null,get(){return this._readableState===void 0||this._writableState===void 0?!1:this._readableState.destroyed&&this._writableState.destroyed},set(p){this._readableState&&this._writableState&&(this._readableState.destroyed=p,this._writableState.destroyed=p)}}});var l;function u(){return l===void 0&&(l={}),l}o.fromWeb=function(p,y){return u().newStreamDuplexFromReadableWritablePair(p,y)},o.toWeb=function(p){return u().newReadableWritablePairFromDuplex(p)};var d;o.from=function(p){return d||(d=gc()),d(p,"body")}}),zo=pe((c,e)=>{le(),ue(),ce();var{ObjectSetPrototypeOf:t,Symbol:r}=je();e.exports=o;var{ERR_METHOD_NOT_IMPLEMENTED:a}=We().codes,n=at(),{getHighWaterMark:i}=ir();t(o.prototype,n.prototype),t(o,n);var s=r("kCallback");function o(d){if(!(this instanceof o))return new o(d);let p=d?i(this,d,"readableHighWaterMark",!0):null;p===0&&(d={...d,highWaterMark:null,readableHighWaterMark:p,writableHighWaterMark:d.writableHighWaterMark||0}),n.call(this,d),this._readableState.sync=!1,this[s]=null,d&&(typeof d.transform=="function"&&(this._transform=d.transform),typeof d.flush=="function"&&(this._flush=d.flush)),this.on("prefinish",u)}function l(d){typeof this._flush=="function"&&!this.destroyed?this._flush((p,y)=>{if(p){d?d(p):this.destroy(p);return}y!=null&&this.push(y),this.push(null),d&&d()}):(this.push(null),d&&d())}function u(){this._final!==l&&l.call(this)}o.prototype._final=l,o.prototype._transform=function(d,p,y){throw new a("_transform()")},o.prototype._write=function(d,p,y){let f=this._readableState,g=this._writableState,b=f.length;this._transform(d,p,(k,m)=>{if(k){y(k);return}m!=null&&this.push(m),g.ended||b===f.length||f.length<f.highWaterMark?y():this[s]=y})},o.prototype._read=function(){if(this[s]){let d=this[s];this[s]=null,d()}}}),Ko=pe((c,e)=>{le(),ue(),ce();var{ObjectSetPrototypeOf:t}=je();e.exports=a;var r=zo();t(a.prototype,r.prototype),t(a,r);function a(n){if(!(this instanceof a))return new a(n);r.call(this,n)}a.prototype._transform=function(n,i,s){s(null,n)}}),ni=pe((c,e)=>{le(),ue(),ce();var t=St(),{ArrayIsArray:r,Promise:a,SymbolAsyncIterator:n,SymbolDispose:i}=je(),s=gt(),{once:o}=ze(),l=Mt(),u=at(),{aggregateTwoErrors:d,codes:{ERR_INVALID_ARG_TYPE:p,ERR_INVALID_RETURN_VALUE:y,ERR_MISSING_ARGS:f,ERR_STREAM_DESTROYED:g,ERR_STREAM_PREMATURE_CLOSE:b},AbortError:k}=We(),{validateFunction:m,validateAbortSignal:w}=zt(),{isIterable:E,isReadable:v,isReadableNodeStream:x,isNodeStream:S,isTransformStream:I,isWebStream:M,isReadableStream:O,isReadableFinished:B}=st(),T=globalThis.AbortController||qt().AbortController,W,F,N;function ae(te,we,V){let L=!1;te.on("close",()=>{L=!0});let ne=s(te,{readable:we,writable:V},H=>{L=!H});return{destroy:H=>{L||(L=!0,l.destroyer(te,H||new g("pipe")))},cleanup:ne}}function Y(te){return m(te[te.length-1],"streams[stream.length - 1]"),te.pop()}function K(te){if(E(te))return te;if(x(te))return re(te);throw new p("val",["Readable","Iterable","AsyncIterable"],te)}async function*re(te){F||(F=or()),yield*F.prototype[n].call(te)}async function D(te,we,V,{end:L}){let ne,H=null,G=oe=>{if(oe&&(ne=oe),H){let R=H;H=null,R()}},Q=()=>new a((oe,R)=>{ne?R(ne):H=()=>{ne?R(ne):oe()}});we.on("drain",G);let me=s(we,{readable:!1},G);try{we.writableNeedDrain&&await Q();for await(let oe of te)we.write(oe)||await Q();L&&(we.end(),await Q()),V()}catch(oe){V(ne!==oe?d(ne,oe):oe)}finally{me(),we.off("drain",G)}}async function Z(te,we,V,{end:L}){I(we)&&(we=we.writable);let ne=we.getWriter();try{for await(let H of te)await ne.ready,ne.write(H).catch(()=>{});await ne.ready,L&&await ne.close(),V()}catch(H){try{await ne.abort(H),V(H)}catch(G){V(G)}}}function P(...te){return J(te,o(Y(te)))}function J(te,we,V){if(te.length===1&&r(te[0])&&(te=te[0]),te.length<2)throw new f("streams");let L=new T,ne=L.signal,H=V?.signal,G=[];w(H,"options.signal");function Q(){de(new k)}N=N||ze().addAbortListener;let me;H&&(me=N(H,Q));let oe,R,$=[],ee=0;function fe(ve){de(ve,--ee===0)}function de(ve,se){var Te;if(ve&&(!oe||oe.code==="ERR_STREAM_PREMATURE_CLOSE")&&(oe=ve),!(!oe&&!se)){for(;$.length;)$.shift()(oe);(Te=me)===null||Te===void 0||Te[i](),L.abort(),se&&(oe||G.forEach(h=>h()),t.nextTick(we,oe,R))}}let ye;for(let ve=0;ve<te.length;ve++){let se=te[ve],Te=ve<te.length-1,h=ve>0,_=Te||V?.end!==!1,A=ve===te.length-1;if(S(se)){let U=function(X){X&&X.name!=="AbortError"&&X.code!=="ERR_STREAM_PREMATURE_CLOSE"&&fe(X)};if(_){let{destroy:X,cleanup:he}=ae(se,Te,h);$.push(X),v(se)&&A&&G.push(he)}se.on("error",U),v(se)&&A&&G.push(()=>{se.removeListener("error",U)})}if(ve===0)if(typeof se=="function"){if(ye=se({signal:ne}),!E(ye))throw new y("Iterable, AsyncIterable or Stream","source",ye)}else E(se)||x(se)||I(se)?ye=se:ye=u.from(se);else if(typeof se=="function"){if(I(ye)){var q;ye=K((q=ye)===null||q===void 0?void 0:q.readable)}else ye=K(ye);if(ye=se(ye,{signal:ne}),Te){if(!E(ye,!0))throw new y("AsyncIterable",`transform[${ve-1}]`,ye)}else{var ge;W||(W=Ko());let U=new W({objectMode:!0}),X=(ge=ye)===null||ge===void 0?void 0:ge.then;if(typeof X=="function")ee++,X.call(ye,z=>{R=z,z!=null&&U.write(z),_&&U.end(),t.nextTick(fe)},z=>{U.destroy(z),t.nextTick(fe,z)});else if(E(ye,!0))ee++,D(ye,U,fe,{end:_});else if(O(ye)||I(ye)){let z=ye.readable||ye;ee++,D(z,U,fe,{end:_})}else throw new y("AsyncIterable or Promise","destination",ye);ye=U;let{destroy:he,cleanup:ke}=ae(ye,!1,!0);$.push(he),A&&G.push(ke)}}else if(S(se)){if(x(ye)){ee+=2;let U=be(ye,se,fe,{end:_});v(se)&&A&&G.push(U)}else if(I(ye)||O(ye)){let U=ye.readable||ye;ee++,D(U,se,fe,{end:_})}else if(E(ye))ee++,D(ye,se,fe,{end:_});else throw new p("val",["Readable","Iterable","AsyncIterable","ReadableStream","TransformStream"],ye);ye=se}else if(M(se)){if(x(ye))ee++,Z(K(ye),se,fe,{end:_});else if(O(ye)||E(ye))ee++,Z(ye,se,fe,{end:_});else if(I(ye))ee++,Z(ye.readable,se,fe,{end:_});else throw new p("val",["Readable","Iterable","AsyncIterable","ReadableStream","TransformStream"],ye);ye=se}else ye=u.from(se)}return(ne!=null&&ne.aborted||H!=null&&H.aborted)&&t.nextTick(Q),ye}function be(te,we,V,{end:L}){let ne=!1;if(we.on("close",()=>{ne||V(new b)}),te.pipe(we,{end:!1}),L){let H=function(){ne=!0,we.end()};B(te)?t.nextTick(H):te.once("end",H)}else V();return s(te,{readable:!0,writable:!1},H=>{let G=te._readableState;H&&H.code==="ERR_STREAM_PREMATURE_CLOSE"&&G&&G.ended&&!G.errored&&!G.errorEmitted?te.once("end",V).once("error",V):V(H)}),s(we,{readable:!1,writable:!0},V)}e.exports={pipelineImpl:J,pipeline:P}}),Vo=pe((c,e)=>{le(),ue(),ce();var{pipeline:t}=ni(),r=at(),{destroyer:a}=Mt(),{isNodeStream:n,isReadable:i,isWritable:s,isWebStream:o,isTransformStream:l,isWritableStream:u,isReadableStream:d}=st(),{AbortError:p,codes:{ERR_INVALID_ARG_VALUE:y,ERR_MISSING_ARGS:f}}=We(),g=gt();e.exports=function(...b){if(b.length===0)throw new f("streams");if(b.length===1)return r.from(b[0]);let k=[...b];if(typeof b[0]=="function"&&(b[0]=r.from(b[0])),typeof b[b.length-1]=="function"){let T=b.length-1;b[T]=r.from(b[T])}for(let T=0;T<b.length;++T)if(!(!n(b[T])&&!o(b[T]))){if(T<b.length-1&&!(i(b[T])||d(b[T])||l(b[T])))throw new y(`streams[${T}]`,k[T],"must be readable");if(T>0&&!(s(b[T])||u(b[T])||l(b[T])))throw new y(`streams[${T}]`,k[T],"must be writable")}let m,w,E,v,x;function S(T){let W=v;v=null,W?W(T):T?x.destroy(T):!B&&!O&&x.destroy()}let I=b[0],M=t(b,S),O=!!(s(I)||u(I)||l(I)),B=!!(i(M)||d(M)||l(M));if(x=new r({writableObjectMode:!!(I!=null&&I.writableObjectMode),readableObjectMode:!!(M!=null&&M.readableObjectMode),writable:O,readable:B}),O){if(n(I))x._write=function(W,F,N){I.write(W,F)?N():m=N},x._final=function(W){I.end(),w=W},I.on("drain",function(){if(m){let W=m;m=null,W()}});else if(o(I)){let W=(l(I)?I.writable:I).getWriter();x._write=async function(F,N,ae){try{await W.ready,W.write(F).catch(()=>{}),ae()}catch(Y){ae(Y)}},x._final=async function(F){try{await W.ready,W.close().catch(()=>{}),w=F}catch(N){F(N)}}}let T=l(M)?M.readable:M;g(T,()=>{if(w){let W=w;w=null,W()}})}if(B){if(n(M))M.on("readable",function(){if(E){let T=E;E=null,T()}}),M.on("end",function(){x.push(null)}),x._read=function(){for(;;){let T=M.read();if(T===null){E=x._read;return}if(!x.push(T))return}};else if(o(M)){let T=(l(M)?M.readable:M).getReader();x._read=async function(){for(;;)try{let{value:W,done:F}=await T.read();if(!x.push(W))return;if(F){x.push(null);return}}catch{return}}}}return x._destroy=function(T,W){!T&&v!==null&&(T=new p),E=null,m=null,w=null,v===null?W(T):(v=W,n(M)&&a(M,T))},x}}),mc=pe((c,e)=>{le(),ue(),ce();var t=globalThis.AbortController||qt().AbortController,{codes:{ERR_INVALID_ARG_VALUE:r,ERR_INVALID_ARG_TYPE:a,ERR_MISSING_ARGS:n,ERR_OUT_OF_RANGE:i},AbortError:s}=We(),{validateAbortSignal:o,validateInteger:l,validateObject:u}=zt(),d=je().Symbol("kWeak"),p=je().Symbol("kResistStopPropagation"),{finished:y}=gt(),f=Vo(),{addAbortSignalNoValidate:g}=nr(),{isWritable:b,isNodeStream:k}=st(),{deprecate:m}=ze(),{ArrayPrototypePush:w,Boolean:E,MathFloor:v,Number:x,NumberIsNaN:S,Promise:I,PromiseReject:M,PromiseResolve:O,PromisePrototypeThen:B,Symbol:T}=je(),W=T("kEmpty"),F=T("kEof");function N(H,G){if(G!=null&&u(G,"options"),G?.signal!=null&&o(G.signal,"options.signal"),k(H)&&!b(H))throw new r("stream",H,"must be writable");let Q=f(this,H);return G!=null&&G.signal&&g(G.signal,Q),Q}function ae(H,G){if(typeof H!="function")throw new a("fn",["Function","AsyncFunction"],H);G!=null&&u(G,"options"),G?.signal!=null&&o(G.signal,"options.signal");let Q=1;G?.concurrency!=null&&(Q=v(G.concurrency));let me=Q-1;return G?.highWaterMark!=null&&(me=v(G.highWaterMark)),l(Q,"options.concurrency",1),l(me,"options.highWaterMark",0),me+=Q,(async function*(){let oe=ze().AbortSignalAny([G?.signal].filter(E)),R=this,$=[],ee={signal:oe},fe,de,ye=!1,q=0;function ge(){ye=!0,ve()}function ve(){q-=1,se()}function se(){de&&!ye&&q<Q&&$.length<me&&(de(),de=null)}async function Te(){try{for await(let h of R){if(ye)return;if(oe.aborted)throw new s;try{if(h=H(h,ee),h===W)continue;h=O(h)}catch(_){h=M(_)}q+=1,B(h,ve,ge),$.push(h),fe&&(fe(),fe=null),!ye&&($.length>=me||q>=Q)&&await new I(_=>{de=_})}$.push(F)}catch(h){let _=M(h);B(_,ve,ge),$.push(_)}finally{ye=!0,fe&&(fe(),fe=null)}}Te();try{for(;;){for(;$.length>0;){let h=await $[0];if(h===F)return;if(oe.aborted)throw new s;h!==W&&(yield h),$.shift(),se()}await new I(h=>{fe=h})}}finally{ye=!0,de&&(de(),de=null)}}).call(this)}function Y(H=void 0){return H!=null&&u(H,"options"),H?.signal!=null&&o(H.signal,"options.signal"),(async function*(){let G=0;for await(let me of this){var Q;if(H!=null&&(Q=H.signal)!==null&&Q!==void 0&&Q.aborted)throw new s({cause:H.signal.reason});yield[G++,me]}}).call(this)}async function K(H,G=void 0){for await(let Q of P.call(this,H,G))return!0;return!1}async function re(H,G=void 0){if(typeof H!="function")throw new a("fn",["Function","AsyncFunction"],H);return!await K.call(this,async(...Q)=>!await H(...Q),G)}async function D(H,G){for await(let Q of P.call(this,H,G))return Q}async function Z(H,G){if(typeof H!="function")throw new a("fn",["Function","AsyncFunction"],H);async function Q(me,oe){return await H(me,oe),W}for await(let me of ae.call(this,Q,G));}function P(H,G){if(typeof H!="function")throw new a("fn",["Function","AsyncFunction"],H);async function Q(me,oe){return await H(me,oe)?me:W}return ae.call(this,Q,G)}var J=class extends n{constructor(){super("reduce"),this.message="Reduce of an empty stream requires an initial value"}};async function be(H,G,Q){var me;if(typeof H!="function")throw new a("reducer",["Function","AsyncFunction"],H);Q!=null&&u(Q,"options"),Q?.signal!=null&&o(Q.signal,"options.signal");let oe=arguments.length>1;if(Q!=null&&(me=Q.signal)!==null&&me!==void 0&&me.aborted){let de=new s(void 0,{cause:Q.signal.reason});throw this.once("error",()=>{}),await y(this.destroy(de)),de}let R=new t,$=R.signal;if(Q!=null&&Q.signal){let de={once:!0,[d]:this,[p]:!0};Q.signal.addEventListener("abort",()=>R.abort(),de)}let ee=!1;try{for await(let de of this){var fe;if(ee=!0,Q!=null&&(fe=Q.signal)!==null&&fe!==void 0&&fe.aborted)throw new s;oe?G=await H(G,de,{signal:$}):(G=de,oe=!0)}if(!ee&&!oe)throw new J}finally{R.abort()}return G}async function te(H){H!=null&&u(H,"options"),H?.signal!=null&&o(H.signal,"options.signal");let G=[];for await(let me of this){var Q;if(H!=null&&(Q=H.signal)!==null&&Q!==void 0&&Q.aborted)throw new s(void 0,{cause:H.signal.reason});w(G,me)}return G}function we(H,G){let Q=ae.call(this,H,G);return(async function*(){for await(let me of Q)yield*me}).call(this)}function V(H){if(H=x(H),S(H))return 0;if(H<0)throw new i("number",">= 0",H);return H}function L(H,G=void 0){return G!=null&&u(G,"options"),G?.signal!=null&&o(G.signal,"options.signal"),H=V(H),(async function*(){var Q;if(G!=null&&(Q=G.signal)!==null&&Q!==void 0&&Q.aborted)throw new s;for await(let oe of this){var me;if(G!=null&&(me=G.signal)!==null&&me!==void 0&&me.aborted)throw new s;H--<=0&&(yield oe)}}).call(this)}function ne(H,G=void 0){return G!=null&&u(G,"options"),G?.signal!=null&&o(G.signal,"options.signal"),H=V(H),(async function*(){var Q;if(G!=null&&(Q=G.signal)!==null&&Q!==void 0&&Q.aborted)throw new s;for await(let oe of this){var me;if(G!=null&&(me=G.signal)!==null&&me!==void 0&&me.aborted)throw new s;if(H-- >0&&(yield oe),H<=0)return}}).call(this)}e.exports.streamReturningOperators={asIndexedPairs:m(Y,"readable.asIndexedPairs will be removed in a future version."),drop:L,filter:P,flatMap:we,map:ae,take:ne,compose:N},e.exports.promiseReturningOperators={every:re,forEach:Z,reduce:be,toArray:te,some:K,find:D}}),Go=pe((c,e)=>{le(),ue(),ce();var{ArrayPrototypePop:t,Promise:r}=je(),{isIterable:a,isNodeStream:n,isWebStream:i}=st(),{pipelineImpl:s}=ni(),{finished:o}=gt();Yo();function l(...u){return new r((d,p)=>{let y,f,g=u[u.length-1];if(g&&typeof g=="object"&&!n(g)&&!a(g)&&!i(g)){let b=t(u);y=b.signal,f=b.end}s(u,(b,k)=>{b?p(b):d(k)},{signal:y,end:f})})}e.exports={finished:o,pipeline:l}}),Yo=pe((c,e)=>{le(),ue(),ce();var{Buffer:t}=(Ue(),Pe(Ne)),{ObjectDefineProperty:r,ObjectKeys:a,ReflectApply:n}=je(),{promisify:{custom:i}}=ze(),{streamReturningOperators:s,promiseReturningOperators:o}=mc(),{codes:{ERR_ILLEGAL_CONSTRUCTOR:l}}=We(),u=Vo(),{setDefaultHighWaterMark:d,getDefaultHighWaterMark:p}=ir(),{pipeline:y}=ni(),{destroyer:f}=Mt(),g=gt(),b=Go(),k=st(),m=e.exports=ti().Stream;m.isDestroyed=k.isDestroyed,m.isDisturbed=k.isDisturbed,m.isErrored=k.isErrored,m.isReadable=k.isReadable,m.isWritable=k.isWritable,m.Readable=or();for(let E of a(s)){let v=function(...S){if(new.target)throw l();return m.Readable.from(n(x,this,S))},x=s[E];r(v,"name",{__proto__:null,value:x.name}),r(v,"length",{__proto__:null,value:x.length}),r(m.Readable.prototype,E,{__proto__:null,value:v,enumerable:!1,configurable:!0,writable:!0})}for(let E of a(o)){let v=function(...S){if(new.target)throw l();return n(x,this,S)},x=o[E];r(v,"name",{__proto__:null,value:x.name}),r(v,"length",{__proto__:null,value:x.length}),r(m.Readable.prototype,E,{__proto__:null,value:v,enumerable:!1,configurable:!0,writable:!0})}m.Writable=ri(),m.Duplex=at(),m.Transform=zo(),m.PassThrough=Ko(),m.pipeline=y;var{addAbortSignal:w}=nr();m.addAbortSignal=w,m.finished=g,m.destroy=f,m.compose=u,m.setDefaultHighWaterMark=d,m.getDefaultHighWaterMark=p,r(m,"promises",{__proto__:null,configurable:!0,enumerable:!0,get(){return b}}),r(y,i,{__proto__:null,enumerable:!0,get(){return b.pipeline}}),r(g,i,{__proto__:null,enumerable:!0,get(){return b.finished}}),m.Stream=m,m._isUint8Array=function(E){return E instanceof Uint8Array},m._uint8ArrayToBuffer=function(E){return t.from(E.buffer,E.byteOffset,E.byteLength)}}),Et=pe((c,e)=>{le(),ue(),ce();var t=Yo(),r=Go(),a=t.Readable.destroy;e.exports=t.Readable,e.exports._uint8ArrayToBuffer=t._uint8ArrayToBuffer,e.exports._isUint8Array=t._isUint8Array,e.exports.isDisturbed=t.isDisturbed,e.exports.isErrored=t.isErrored,e.exports.isReadable=t.isReadable,e.exports.Readable=t.Readable,e.exports.Writable=t.Writable,e.exports.Duplex=t.Duplex,e.exports.Transform=t.Transform,e.exports.PassThrough=t.PassThrough,e.exports.addAbortSignal=t.addAbortSignal,e.exports.finished=t.finished,e.exports.destroy=t.destroy,e.exports.destroy=a,e.exports.pipeline=t.pipeline,e.exports.compose=t.compose,Object.defineProperty(t,"promises",{configurable:!0,enumerable:!0,get(){return r}}),e.exports.Stream=t.Stream,e.exports.default=e.exports}),bc=pe((c,e)=>{le(),ue(),ce(),typeof Object.create=="function"?e.exports=function(t,r){r&&(t.super_=r,t.prototype=Object.create(r.prototype,{constructor:{value:t,enumerable:!1,writable:!0,configurable:!0}}))}:e.exports=function(t,r){if(r){t.super_=r;var a=function(){};a.prototype=r.prototype,t.prototype=new a,t.prototype.constructor=t}}}),yc=pe((c,e)=>{le(),ue(),ce();var{Buffer:t}=(Ue(),Pe(Ne)),r=Symbol.for("BufferList");function a(n){if(!(this instanceof a))return new a(n);a._init.call(this,n)}a._init=function(n){Object.defineProperty(this,r,{value:!0}),this._bufs=[],this.length=0,n&&this.append(n)},a.prototype._new=function(n){return new a(n)},a.prototype._offset=function(n){if(n===0)return[0,0];let i=0;for(let s=0;s<this._bufs.length;s++){let o=i+this._bufs[s].length;if(n<o||s===this._bufs.length-1)return[s,n-i];i=o}},a.prototype._reverseOffset=function(n){let i=n[0],s=n[1];for(let o=0;o<i;o++)s+=this._bufs[o].length;return s},a.prototype.getBuffers=function(){return this._bufs},a.prototype.get=function(n){if(n>this.length||n<0)return;let i=this._offset(n);return this._bufs[i[0]][i[1]]},a.prototype.slice=function(n,i){return typeof n=="number"&&n<0&&(n+=this.length),typeof i=="number"&&i<0&&(i+=this.length),this.copy(null,0,n,i)},a.prototype.copy=function(n,i,s,o){if((typeof s!="number"||s<0)&&(s=0),(typeof o!="number"||o>this.length)&&(o=this.length),s>=this.length||o<=0)return n||t.alloc(0);let l=!!n,u=this._offset(s),d=o-s,p=d,y=l&&i||0,f=u[1];if(s===0&&o===this.length){if(!l)return this._bufs.length===1?this._bufs[0]:t.concat(this._bufs,this.length);for(let g=0;g<this._bufs.length;g++)this._bufs[g].copy(n,y),y+=this._bufs[g].length;return n}if(p<=this._bufs[u[0]].length-f)return l?this._bufs[u[0]].copy(n,i,f,f+p):this._bufs[u[0]].slice(f,f+p);l||(n=t.allocUnsafe(d));for(let g=u[0];g<this._bufs.length;g++){let b=this._bufs[g].length-f;if(p>b)this._bufs[g].copy(n,y,f),y+=b;else{this._bufs[g].copy(n,y,f,f+p),y+=b;break}p-=b,f&&(f=0)}return n.length>y?n.slice(0,y):n},a.prototype.shallowSlice=function(n,i){if(n=n||0,i=typeof i!="number"?this.length:i,n<0&&(n+=this.length),i<0&&(i+=this.length),n===i)return this._new();let s=this._offset(n),o=this._offset(i),l=this._bufs.slice(s[0],o[0]+1);return o[1]===0?l.pop():l[l.length-1]=l[l.length-1].slice(0,o[1]),s[1]!==0&&(l[0]=l[0].slice(s[1])),this._new(l)},a.prototype.toString=function(n,i,s){return this.slice(i,s).toString(n)},a.prototype.consume=function(n){if(n=Math.trunc(n),Number.isNaN(n)||n<=0)return this;for(;this._bufs.length;)if(n>=this._bufs[0].length)n-=this._bufs[0].length,this.length-=this._bufs[0].length,this._bufs.shift();else{this._bufs[0]=this._bufs[0].slice(n),this.length-=n;break}return this},a.prototype.duplicate=function(){let n=this._new();for(let i=0;i<this._bufs.length;i++)n.append(this._bufs[i]);return n},a.prototype.append=function(n){return this._attach(n,a.prototype._appendBuffer)},a.prototype.prepend=function(n){return this._attach(n,a.prototype._prependBuffer,!0)},a.prototype._attach=function(n,i,s){if(n==null)return this;if(n.buffer)i.call(this,t.from(n.buffer,n.byteOffset,n.byteLength));else if(Array.isArray(n)){let[o,l]=s?[n.length-1,-1]:[0,1];for(let u=o;u>=0&&u<n.length;u+=l)this._attach(n[u],i,s)}else if(this._isBufferList(n)){let[o,l]=s?[n._bufs.length-1,-1]:[0,1];for(let u=o;u>=0&&u<n._bufs.length;u+=l)this._attach(n._bufs[u],i,s)}else typeof n=="number"&&(n=n.toString()),i.call(this,t.from(n));return this},a.prototype._appendBuffer=function(n){this._bufs.push(n),this.length+=n.length},a.prototype._prependBuffer=function(n){this._bufs.unshift(n),this.length+=n.length},a.prototype.indexOf=function(n,i,s){if(s===void 0&&typeof i=="string"&&(s=i,i=void 0),typeof n=="function"||Array.isArray(n))throw new TypeError('The "value" argument must be one of type string, Buffer, BufferList, or Uint8Array.');if(typeof n=="number"?n=t.from([n]):typeof n=="string"?n=t.from(n,s):this._isBufferList(n)?n=n.slice():Array.isArray(n.buffer)?n=t.from(n.buffer,n.byteOffset,n.byteLength):t.isBuffer(n)||(n=t.from(n)),i=Number(i||0),isNaN(i)&&(i=0),i<0&&(i=this.length+i),i<0&&(i=0),n.length===0)return i>this.length?this.length:i;let o=this._offset(i),l=o[0],u=o[1];for(;l<this._bufs.length;l++){let d=this._bufs[l];for(;u<d.length;)if(d.length-u>=n.length){let p=d.indexOf(n,u);if(p!==-1)return this._reverseOffset([l,p]);u=d.length-n.length+1}else{let p=this._reverseOffset([l,u]);if(this._match(p,n))return p;u++}u=0}return-1},a.prototype._match=function(n,i){if(this.length-n<i.length)return!1;for(let s=0;s<i.length;s++)if(this.get(n+s)!==i[s])return!1;return!0},(function(){let n={readDoubleBE:8,readDoubleLE:8,readFloatBE:4,readFloatLE:4,readBigInt64BE:8,readBigInt64LE:8,readBigUInt64BE:8,readBigUInt64LE:8,readInt32BE:4,readInt32LE:4,readUInt32BE:4,readUInt32LE:4,readInt16BE:2,readInt16LE:2,readUInt16BE:2,readUInt16LE:2,readInt8:1,readUInt8:1,readIntBE:null,readIntLE:null,readUIntBE:null,readUIntLE:null};for(let i in n)(function(s){n[s]===null?a.prototype[s]=function(o,l){return this.slice(o,o+l)[s](0,l)}:a.prototype[s]=function(o=0){return this.slice(o,o+n[s])[s](0)}})(i)})(),a.prototype._isBufferList=function(n){return n instanceof a||a.isBufferList(n)},a.isBufferList=function(n){return n!=null&&n[r]},e.exports=a}),vc=pe((c,e)=>{le(),ue(),ce();var t=Et().Duplex,r=bc(),a=yc();function n(i){if(!(this instanceof n))return new n(i);if(typeof i=="function"){this._callback=i;let s=(function(o){this._callback&&(this._callback(o),this._callback=null)}).bind(this);this.on("pipe",function(o){o.on("error",s)}),this.on("unpipe",function(o){o.removeListener("error",s)}),i=null}a._init.call(this,i),t.call(this)}r(n,t),Object.assign(n.prototype,a.prototype),n.prototype._new=function(i){return new n(i)},n.prototype._write=function(i,s,o){this._appendBuffer(i),typeof o=="function"&&o()},n.prototype._read=function(i){if(!this.length)return this.push(null);i=Math.min(i,this.length),this.push(this.slice(0,i)),this.consume(i)},n.prototype.end=function(i){t.prototype.end.call(this,i),this._callback&&(this._callback(null,this.slice()),this._callback=null)},n.prototype._destroy=function(i,s){this._bufs.length=0,this.length=0,s(i)},n.prototype._isBufferList=function(i){return i instanceof n||i instanceof a||n.isBufferList(i)},n.isBufferList=a.isBufferList,e.exports=n,e.exports.BufferListStream=n,e.exports.BufferList=a}),wc=pe((c,e)=>{le(),ue(),ce();var t=class{constructor(){this.cmd=null,this.retain=!1,this.qos=0,this.dup=!1,this.length=-1,this.topic=null,this.payload=null}};e.exports=t}),Qo=pe((c,e)=>{le(),ue(),ce();var t=e.exports,{Buffer:r}=(Ue(),Pe(Ne));t.types={0:"reserved",1:"connect",2:"connack",3:"publish",4:"puback",5:"pubrec",6:"pubrel",7:"pubcomp",8:"subscribe",9:"suback",10:"unsubscribe",11:"unsuback",12:"pingreq",13:"pingresp",14:"disconnect",15:"auth"},t.requiredHeaderFlags={1:0,2:0,4:0,5:0,6:2,7:0,8:2,9:0,10:2,11:0,12:0,13:0,14:0,15:0},t.requiredHeaderFlagsErrors={};for(let n in t.requiredHeaderFlags){let i=t.requiredHeaderFlags[n];t.requiredHeaderFlagsErrors[n]="Invalid header flag bits, must be 0x"+i.toString(16)+" for "+t.types[n]+" packet"}t.codes={};for(let n in t.types){let i=t.types[n];t.codes[i]=n}t.CMD_SHIFT=4,t.CMD_MASK=240,t.DUP_MASK=8,t.QOS_MASK=3,t.QOS_SHIFT=1,t.RETAIN_MASK=1,t.VARBYTEINT_MASK=127,t.VARBYTEINT_FIN_MASK=128,t.VARBYTEINT_MAX=268435455,t.SESSIONPRESENT_MASK=1,t.SESSIONPRESENT_HEADER=r.from([t.SESSIONPRESENT_MASK]),t.CONNACK_HEADER=r.from([t.codes.connack<<t.CMD_SHIFT]),t.USERNAME_MASK=128,t.PASSWORD_MASK=64,t.WILL_RETAIN_MASK=32,t.WILL_QOS_MASK=24,t.WILL_QOS_SHIFT=3,t.WILL_FLAG_MASK=4,t.CLEAN_SESSION_MASK=2,t.CONNECT_HEADER=r.from([t.codes.connect<<t.CMD_SHIFT]),t.properties={sessionExpiryInterval:17,willDelayInterval:24,receiveMaximum:33,maximumPacketSize:39,topicAliasMaximum:34,requestResponseInformation:25,requestProblemInformation:23,userProperties:38,authenticationMethod:21,authenticationData:22,payloadFormatIndicator:1,messageExpiryInterval:2,contentType:3,responseTopic:8,correlationData:9,maximumQoS:36,retainAvailable:37,assignedClientIdentifier:18,reasonString:31,wildcardSubscriptionAvailable:40,subscriptionIdentifiersAvailable:41,sharedSubscriptionAvailable:42,serverKeepAlive:19,responseInformation:26,serverReference:28,topicAlias:35,subscriptionIdentifier:11},t.propertiesCodes={};for(let n in t.properties){let i=t.properties[n];t.propertiesCodes[i]=n}t.propertiesTypes={sessionExpiryInterval:"int32",willDelayInterval:"int32",receiveMaximum:"int16",maximumPacketSize:"int32",topicAliasMaximum:"int16",requestResponseInformation:"byte",requestProblemInformation:"byte",userProperties:"pair",authenticationMethod:"string",authenticationData:"binary",payloadFormatIndicator:"byte",messageExpiryInterval:"int32",contentType:"string",responseTopic:"string",correlationData:"binary",maximumQoS:"int8",retainAvailable:"byte",assignedClientIdentifier:"string",reasonString:"string",wildcardSubscriptionAvailable:"byte",subscriptionIdentifiersAvailable:"byte",sharedSubscriptionAvailable:"byte",serverKeepAlive:"int16",responseInformation:"string",serverReference:"string",topicAlias:"int16",subscriptionIdentifier:"var"};function a(n){return[0,1,2].map(i=>[0,1].map(s=>[0,1].map(o=>{let l=r.alloc(1);return l.writeUInt8(t.codes[n]<<t.CMD_SHIFT|(s?t.DUP_MASK:0)|i<<t.QOS_SHIFT|o,0,!0),l})))}t.PUBLISH_HEADER=a("publish"),t.SUBSCRIBE_HEADER=a("subscribe"),t.SUBSCRIBE_OPTIONS_QOS_MASK=3,t.SUBSCRIBE_OPTIONS_NL_MASK=1,t.SUBSCRIBE_OPTIONS_NL_SHIFT=2,t.SUBSCRIBE_OPTIONS_RAP_MASK=1,t.SUBSCRIBE_OPTIONS_RAP_SHIFT=3,t.SUBSCRIBE_OPTIONS_RH_MASK=3,t.SUBSCRIBE_OPTIONS_RH_SHIFT=4,t.SUBSCRIBE_OPTIONS_RH=[0,16,32],t.SUBSCRIBE_OPTIONS_NL=4,t.SUBSCRIBE_OPTIONS_RAP=8,t.SUBSCRIBE_OPTIONS_QOS=[0,1,2],t.UNSUBSCRIBE_HEADER=a("unsubscribe"),t.ACKS={unsuback:a("unsuback"),puback:a("puback"),pubcomp:a("pubcomp"),pubrel:a("pubrel"),pubrec:a("pubrec")},t.SUBACK_HEADER=r.from([t.codes.suback<<t.CMD_SHIFT]),t.VERSION3=r.from([3]),t.VERSION4=r.from([4]),t.VERSION5=r.from([5]),t.VERSION131=r.from([131]),t.VERSION132=r.from([132]),t.QOS=[0,1,2].map(n=>r.from([n])),t.EMPTY={pingreq:r.from([t.codes.pingreq<<4,0]),pingresp:r.from([t.codes.pingresp<<4,0]),disconnect:r.from([t.codes.disconnect<<4,0])},t.MQTT5_PUBACK_PUBREC_CODES={0:"Success",16:"No matching subscribers",128:"Unspecified error",131:"Implementation specific error",135:"Not authorized",144:"Topic Name invalid",145:"Packet identifier in use",151:"Quota exceeded",153:"Payload format invalid"},t.MQTT5_PUBREL_PUBCOMP_CODES={0:"Success",146:"Packet Identifier not found"},t.MQTT5_SUBACK_CODES={0:"Granted QoS 0",1:"Granted QoS 1",2:"Granted QoS 2",128:"Unspecified error",131:"Implementation specific error",135:"Not authorized",143:"Topic Filter invalid",145:"Packet Identifier in use",151:"Quota exceeded",158:"Shared Subscriptions not supported",161:"Subscription Identifiers not supported",162:"Wildcard Subscriptions not supported"},t.MQTT5_UNSUBACK_CODES={0:"Success",17:"No subscription existed",128:"Unspecified error",131:"Implementation specific error",135:"Not authorized",143:"Topic Filter invalid",145:"Packet Identifier in use"},t.MQTT5_DISCONNECT_CODES={0:"Normal disconnection",4:"Disconnect with Will Message",128:"Unspecified error",129:"Malformed Packet",130:"Protocol Error",131:"Implementation specific error",135:"Not authorized",137:"Server busy",139:"Server shutting down",141:"Keep Alive timeout",142:"Session taken over",143:"Topic Filter invalid",144:"Topic Name invalid",147:"Receive Maximum exceeded",148:"Topic Alias invalid",149:"Packet too large",150:"Message rate too high",151:"Quota exceeded",152:"Administrative action",153:"Payload format invalid",154:"Retain not supported",155:"QoS not supported",156:"Use another server",157:"Server moved",158:"Shared Subscriptions not supported",159:"Connection rate exceeded",160:"Maximum connect time",161:"Subscription Identifiers not supported",162:"Wildcard Subscriptions not supported"},t.MQTT5_AUTH_CODES={0:"Success",24:"Continue authentication",25:"Re-authenticate"}}),_c=pe((c,e)=>{le(),ue(),ce();var t=1e3,r=t*60,a=r*60,n=a*24,i=n*7,s=n*365.25;e.exports=function(p,y){y=y||{};var f=typeof p;if(f==="string"&&p.length>0)return o(p);if(f==="number"&&isFinite(p))return y.long?u(p):l(p);throw new Error("val is not a non-empty string or a valid number. val="+JSON.stringify(p))};function o(p){if(p=String(p),!(p.length>100)){var y=/^(-?(?:\d+)?\.?\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)?$/i.exec(p);if(y){var f=parseFloat(y[1]),g=(y[2]||"ms").toLowerCase();switch(g){case"years":case"year":case"yrs":case"yr":case"y":return f*s;case"weeks":case"week":case"w":return f*i;case"days":case"day":case"d":return f*n;case"hours":case"hour":case"hrs":case"hr":case"h":return f*a;case"minutes":case"minute":case"mins":case"min":case"m":return f*r;case"seconds":case"second":case"secs":case"sec":case"s":return f*t;case"milliseconds":case"millisecond":case"msecs":case"msec":case"ms":return f;default:return}}}}function l(p){var y=Math.abs(p);return y>=n?Math.round(p/n)+"d":y>=a?Math.round(p/a)+"h":y>=r?Math.round(p/r)+"m":y>=t?Math.round(p/t)+"s":p+"ms"}function u(p){var y=Math.abs(p);return y>=n?d(p,y,n,"day"):y>=a?d(p,y,a,"hour"):y>=r?d(p,y,r,"minute"):y>=t?d(p,y,t,"second"):p+" ms"}function d(p,y,f,g){var b=y>=f*1.5;return Math.round(p/f)+" "+g+(b?"s":"")}}),kc=pe((c,e)=>{le(),ue(),ce();function t(r){n.debug=n,n.default=n,n.coerce=d,n.disable=l,n.enable=s,n.enabled=u,n.humanize=_c(),n.destroy=p,Object.keys(r).forEach(y=>{n[y]=r[y]}),n.names=[],n.skips=[],n.formatters={};function a(y){let f=0;for(let g=0;g<y.length;g++)f=(f<<5)-f+y.charCodeAt(g),f|=0;return n.colors[Math.abs(f)%n.colors.length]}n.selectColor=a;function n(y){let f,g=null,b,k;function m(...w){if(!m.enabled)return;let E=m,v=Number(new Date),x=v-(f||v);E.diff=x,E.prev=f,E.curr=v,f=v,w[0]=n.coerce(w[0]),typeof w[0]!="string"&&w.unshift("%O");let S=0;w[0]=w[0].replace(/%([a-zA-Z%])/g,(I,M)=>{if(I==="%%")return"%";S++;let O=n.formatters[M];if(typeof O=="function"){let B=w[S];I=O.call(E,B),w.splice(S,1),S--}return I}),n.formatArgs.call(E,w),(E.log||n.log).apply(E,w)}return m.namespace=y,m.useColors=n.useColors(),m.color=n.selectColor(y),m.extend=i,m.destroy=n.destroy,Object.defineProperty(m,"enabled",{enumerable:!0,configurable:!1,get:()=>g!==null?g:(b!==n.namespaces&&(b=n.namespaces,k=n.enabled(y)),k),set:w=>{g=w}}),typeof n.init=="function"&&n.init(m),m}function i(y,f){let g=n(this.namespace+(typeof f>"u"?":":f)+y);return g.log=this.log,g}function s(y){n.save(y),n.namespaces=y,n.names=[],n.skips=[];let f=(typeof y=="string"?y:"").trim().replace(/\s+/g,",").split(",").filter(Boolean);for(let g of f)g[0]==="-"?n.skips.push(g.slice(1)):n.names.push(g)}function o(y,f){let g=0,b=0,k=-1,m=0;for(;g<y.length;)if(b<f.length&&(f[b]===y[g]||f[b]==="*"))f[b]==="*"?(k=b,m=g,b++):(g++,b++);else if(k!==-1)b=k+1,m++,g=m;else return!1;for(;b<f.length&&f[b]==="*";)b++;return b===f.length}function l(){let y=[...n.names,...n.skips.map(f=>"-"+f)].join(",");return n.enable(""),y}function u(y){for(let f of n.skips)if(o(y,f))return!1;for(let f of n.names)if(o(y,f))return!0;return!1}function d(y){return y instanceof Error?y.stack||y.message:y}function p(){console.warn("Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.")}return n.enable(n.load()),n}e.exports=t}),lt=pe((c,e)=>{le(),ue(),ce(),c.formatArgs=r,c.save=a,c.load=n,c.useColors=t,c.storage=i(),c.destroy=(()=>{let o=!1;return()=>{o||(o=!0,console.warn("Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`."))}})(),c.colors=["#0000CC","#0000FF","#0033CC","#0033FF","#0066CC","#0066FF","#0099CC","#0099FF","#00CC00","#00CC33","#00CC66","#00CC99","#00CCCC","#00CCFF","#3300CC","#3300FF","#3333CC","#3333FF","#3366CC","#3366FF","#3399CC","#3399FF","#33CC00","#33CC33","#33CC66","#33CC99","#33CCCC","#33CCFF","#6600CC","#6600FF","#6633CC","#6633FF","#66CC00","#66CC33","#9900CC","#9900FF","#9933CC","#9933FF","#99CC00","#99CC33","#CC0000","#CC0033","#CC0066","#CC0099","#CC00CC","#CC00FF","#CC3300","#CC3333","#CC3366","#CC3399","#CC33CC","#CC33FF","#CC6600","#CC6633","#CC9900","#CC9933","#CCCC00","#CCCC33","#FF0000","#FF0033","#FF0066","#FF0099","#FF00CC","#FF00FF","#FF3300","#FF3333","#FF3366","#FF3399","#FF33CC","#FF33FF","#FF6600","#FF6633","#FF9900","#FF9933","#FFCC00","#FFCC33"];function t(){if(typeof window<"u"&&window.process&&(window.process.type==="renderer"||window.process.__nwjs))return!0;if(typeof navigator<"u"&&navigator.userAgent&&navigator.userAgent.toLowerCase().match(/(edge|trident)\/(\d+)/))return!1;let o;return typeof document<"u"&&document.documentElement&&document.documentElement.style&&document.documentElement.style.WebkitAppearance||typeof window<"u"&&window.console&&(window.console.firebug||window.console.exception&&window.console.table)||typeof navigator<"u"&&navigator.userAgent&&(o=navigator.userAgent.toLowerCase().match(/firefox\/(\d+)/))&&parseInt(o[1],10)>=31||typeof navigator<"u"&&navigator.userAgent&&navigator.userAgent.toLowerCase().match(/applewebkit\/(\d+)/)}function r(o){if(o[0]=(this.useColors?"%c":"")+this.namespace+(this.useColors?" %c":" ")+o[0]+(this.useColors?"%c ":" ")+"+"+e.exports.humanize(this.diff),!this.useColors)return;let l="color: "+this.color;o.splice(1,0,l,"color: inherit");let u=0,d=0;o[0].replace(/%[a-zA-Z%]/g,p=>{p!=="%%"&&(u++,p==="%c"&&(d=u))}),o.splice(d,0,l)}c.log=console.debug||console.log||(()=>{});function a(o){try{o?c.storage.setItem("debug",o):c.storage.removeItem("debug")}catch{}}function n(){let o;try{o=c.storage.getItem("debug")||c.storage.getItem("DEBUG")}catch{}return!o&&typeof Me<"u"&&"env"in Me&&(o=Me.env.DEBUG),o}function i(){try{return localStorage}catch{}}e.exports=kc()(c);var{formatters:s}=e.exports;s.j=function(o){try{return JSON.stringify(o)}catch(l){return"[UnexpectedJSONParseError]: "+l.message}}}),Sc=pe((c,e)=>{le(),ue(),ce();var t=vc(),{EventEmitter:r}=(kt(),Pe(pt)),a=wc(),n=Qo(),i=lt()("mqtt-packet:parser"),s=class ho extends r{constructor(){super(),this.parser=this.constructor.parser}static parser(l){return this instanceof ho?(this.settings=l||{},this._states=["_parseHeader","_parseLength","_parsePayload","_newPacket"],this._resetState(),this):new ho().parser(l)}_resetState(){i("_resetState: resetting packet, error, _list, and _stateCounter"),this.packet=new a,this.error=null,this._list=t(),this._stateCounter=0}parse(l){for(this.error&&this._resetState(),this._list.append(l),i("parse: current state: %s",this._states[this._stateCounter]);(this.packet.length!==-1||this._list.length>0)&&this[this._states[this._stateCounter]]()&&!this.error;)this._stateCounter++,i("parse: state complete. _stateCounter is now: %d",this._stateCounter),i("parse: packet.length: %d, buffer list length: %d",this.packet.length,this._list.length),this._stateCounter>=this._states.length&&(this._stateCounter=0);return i("parse: exited while loop. packet: %d, buffer list length: %d",this.packet.length,this._list.length),this._list.length}_parseHeader(){let l=this._list.readUInt8(0),u=l>>n.CMD_SHIFT;this.packet.cmd=n.types[u];let d=l&15,p=n.requiredHeaderFlags[u];return p!=null&&d!==p?this._emitError(new Error(n.requiredHeaderFlagsErrors[u])):(this.packet.retain=(l&n.RETAIN_MASK)!==0,this.packet.qos=l>>n.QOS_SHIFT&n.QOS_MASK,this.packet.qos>2?this._emitError(new Error("Packet must not have both QoS bits set to 1")):(this.packet.dup=(l&n.DUP_MASK)!==0,i("_parseHeader: packet: %o",this.packet),this._list.consume(1),!0))}_parseLength(){let l=this._parseVarByteNum(!0);return l&&(this.packet.length=l.value,this._list.consume(l.bytes)),i("_parseLength %d",l.value),!!l}_parsePayload(){i("_parsePayload: payload %O",this._list);let l=!1;if(this.packet.length===0||this._list.length>=this.packet.length){switch(this._pos=0,this.packet.cmd){case"connect":this._parseConnect();break;case"connack":this._parseConnack();break;case"publish":this._parsePublish();break;case"puback":case"pubrec":case"pubrel":case"pubcomp":this._parseConfirmation();break;case"subscribe":this._parseSubscribe();break;case"suback":this._parseSuback();break;case"unsubscribe":this._parseUnsubscribe();break;case"unsuback":this._parseUnsuback();break;case"pingreq":case"pingresp":break;case"disconnect":this._parseDisconnect();break;case"auth":this._parseAuth();break;default:this._emitError(new Error("Not supported"))}l=!0}return i("_parsePayload complete result: %s",l),l}_parseConnect(){i("_parseConnect");let l,u,d,p,y={},f=this.packet,g=this._parseString();if(g===null)return this._emitError(new Error("Cannot parse protocolId"));if(g!=="MQTT"&&g!=="MQIsdp")return this._emitError(new Error("Invalid protocolId"));if(f.protocolId=g,this._pos>=this._list.length)return this._emitError(new Error("Packet too short"));if(f.protocolVersion=this._list.readUInt8(this._pos),f.protocolVersion>=128&&(f.bridgeMode=!0,f.protocolVersion=f.protocolVersion-128),f.protocolVersion!==3&&f.protocolVersion!==4&&f.protocolVersion!==5)return this._emitError(new Error("Invalid protocol version"));if(this._pos++,this._pos>=this._list.length)return this._emitError(new Error("Packet too short"));if(this._list.readUInt8(this._pos)&1)return this._emitError(new Error("Connect flag bit 0 must be 0, but got 1"));y.username=this._list.readUInt8(this._pos)&n.USERNAME_MASK,y.password=this._list.readUInt8(this._pos)&n.PASSWORD_MASK,y.will=this._list.readUInt8(this._pos)&n.WILL_FLAG_MASK;let b=!!(this._list.readUInt8(this._pos)&n.WILL_RETAIN_MASK),k=(this._list.readUInt8(this._pos)&n.WILL_QOS_MASK)>>n.WILL_QOS_SHIFT;if(y.will)f.will={},f.will.retain=b,f.will.qos=k;else{if(b)return this._emitError(new Error("Will Retain Flag must be set to zero when Will Flag is set to 0"));if(k)return this._emitError(new Error("Will QoS must be set to zero when Will Flag is set to 0"))}if(f.clean=(this._list.readUInt8(this._pos)&n.CLEAN_SESSION_MASK)!==0,this._pos++,f.keepalive=this._parseNum(),f.keepalive===-1)return this._emitError(new Error("Packet too short"));if(f.protocolVersion===5){let w=this._parseProperties();Object.getOwnPropertyNames(w).length&&(f.properties=w)}let m=this._parseString();if(m===null)return this._emitError(new Error("Packet too short"));if(f.clientId=m,i("_parseConnect: packet.clientId: %s",f.clientId),y.will){if(f.protocolVersion===5){let w=this._parseProperties();Object.getOwnPropertyNames(w).length&&(f.will.properties=w)}if(l=this._parseString(),l===null)return this._emitError(new Error("Cannot parse will topic"));if(f.will.topic=l,i("_parseConnect: packet.will.topic: %s",f.will.topic),u=this._parseBuffer(),u===null)return this._emitError(new Error("Cannot parse will payload"));f.will.payload=u,i("_parseConnect: packet.will.paylaod: %s",f.will.payload)}if(y.username){if(p=this._parseString(),p===null)return this._emitError(new Error("Cannot parse username"));f.username=p,i("_parseConnect: packet.username: %s",f.username)}if(y.password){if(d=this._parseBuffer(),d===null)return this._emitError(new Error("Cannot parse password"));f.password=d}return this.settings=f,i("_parseConnect: complete"),f}_parseConnack(){i("_parseConnack");let l=this.packet;if(this._list.length<1)return null;let u=this._list.readUInt8(this._pos++);if(u>1)return this._emitError(new Error("Invalid connack flags, bits 7-1 must be set to 0"));if(l.sessionPresent=!!(u&n.SESSIONPRESENT_MASK),this.settings.protocolVersion===5)this._list.length>=2?l.reasonCode=this._list.readUInt8(this._pos++):l.reasonCode=0;else{if(this._list.length<2)return null;l.returnCode=this._list.readUInt8(this._pos++)}if(l.returnCode===-1||l.reasonCode===-1)return this._emitError(new Error("Cannot parse return code"));if(this.settings.protocolVersion===5){let d=this._parseProperties();Object.getOwnPropertyNames(d).length&&(l.properties=d)}i("_parseConnack: complete")}_parsePublish(){i("_parsePublish");let l=this.packet;if(l.topic=this._parseString(),l.topic===null)return this._emitError(new Error("Cannot parse topic"));if(!(l.qos>0&&!this._parseMessageId())){if(this.settings.protocolVersion===5){let u=this._parseProperties();Object.getOwnPropertyNames(u).length&&(l.properties=u)}l.payload=this._list.slice(this._pos,l.length),i("_parsePublish: payload from buffer list: %o",l.payload)}}_parseSubscribe(){i("_parseSubscribe");let l=this.packet,u,d,p,y,f,g,b;if(l.subscriptions=[],!!this._parseMessageId()){if(this.settings.protocolVersion===5){let k=this._parseProperties();Object.getOwnPropertyNames(k).length&&(l.properties=k)}if(l.length<=0)return this._emitError(new Error("Malformed subscribe, no payload specified"));for(;this._pos<l.length;){if(u=this._parseString(),u===null)return this._emitError(new Error("Cannot parse topic"));if(this._pos>=l.length)return this._emitError(new Error("Malformed Subscribe Payload"));if(d=this._parseByte(),this.settings.protocolVersion===5){if(d&192)return this._emitError(new Error("Invalid subscribe topic flag bits, bits 7-6 must be 0"))}else if(d&252)return this._emitError(new Error("Invalid subscribe topic flag bits, bits 7-2 must be 0"));if(p=d&n.SUBSCRIBE_OPTIONS_QOS_MASK,p>2)return this._emitError(new Error("Invalid subscribe QoS, must be <= 2"));if(g=(d>>n.SUBSCRIBE_OPTIONS_NL_SHIFT&n.SUBSCRIBE_OPTIONS_NL_MASK)!==0,f=(d>>n.SUBSCRIBE_OPTIONS_RAP_SHIFT&n.SUBSCRIBE_OPTIONS_RAP_MASK)!==0,y=d>>n.SUBSCRIBE_OPTIONS_RH_SHIFT&n.SUBSCRIBE_OPTIONS_RH_MASK,y>2)return this._emitError(new Error("Invalid retain handling, must be <= 2"));b={topic:u,qos:p},this.settings.protocolVersion===5?(b.nl=g,b.rap=f,b.rh=y):this.settings.bridgeMode&&(b.rh=0,b.rap=!0,b.nl=!0),i("_parseSubscribe: push subscription `%s` to subscription",b),l.subscriptions.push(b)}}}_parseSuback(){i("_parseSuback");let l=this.packet;if(this.packet.granted=[],!!this._parseMessageId()){if(this.settings.protocolVersion===5){let u=this._parseProperties();Object.getOwnPropertyNames(u).length&&(l.properties=u)}if(l.length<=0)return this._emitError(new Error("Malformed suback, no payload specified"));for(;this._pos<this.packet.length;){let u=this._list.readUInt8(this._pos++);if(this.settings.protocolVersion===5){if(!n.MQTT5_SUBACK_CODES[u])return this._emitError(new Error("Invalid suback code"))}else if(u>2&&u!==128)return this._emitError(new Error("Invalid suback QoS, must be 0, 1, 2 or 128"));this.packet.granted.push(u)}}}_parseUnsubscribe(){i("_parseUnsubscribe");let l=this.packet;if(l.unsubscriptions=[],!!this._parseMessageId()){if(this.settings.protocolVersion===5){let u=this._parseProperties();Object.getOwnPropertyNames(u).length&&(l.properties=u)}if(l.length<=0)return this._emitError(new Error("Malformed unsubscribe, no payload specified"));for(;this._pos<l.length;){let u=this._parseString();if(u===null)return this._emitError(new Error("Cannot parse topic"));i("_parseUnsubscribe: push topic `%s` to unsubscriptions",u),l.unsubscriptions.push(u)}}}_parseUnsuback(){i("_parseUnsuback");let l=this.packet;if(!this._parseMessageId())return this._emitError(new Error("Cannot parse messageId"));if((this.settings.protocolVersion===3||this.settings.protocolVersion===4)&&l.length!==2)return this._emitError(new Error("Malformed unsuback, payload length must be 2"));if(l.length<=0)return this._emitError(new Error("Malformed unsuback, no payload specified"));if(this.settings.protocolVersion===5){let u=this._parseProperties();for(Object.getOwnPropertyNames(u).length&&(l.properties=u),l.granted=[];this._pos<this.packet.length;){let d=this._list.readUInt8(this._pos++);if(!n.MQTT5_UNSUBACK_CODES[d])return this._emitError(new Error("Invalid unsuback code"));this.packet.granted.push(d)}}}_parseConfirmation(){i("_parseConfirmation: packet.cmd: `%s`",this.packet.cmd);let l=this.packet;if(this._parseMessageId(),this.settings.protocolVersion===5){if(l.length>2){switch(l.reasonCode=this._parseByte(),this.packet.cmd){case"puback":case"pubrec":if(!n.MQTT5_PUBACK_PUBREC_CODES[l.reasonCode])return this._emitError(new Error("Invalid "+this.packet.cmd+" reason code"));break;case"pubrel":case"pubcomp":if(!n.MQTT5_PUBREL_PUBCOMP_CODES[l.reasonCode])return this._emitError(new Error("Invalid "+this.packet.cmd+" reason code"));break}i("_parseConfirmation: packet.reasonCode `%d`",l.reasonCode)}else l.reasonCode=0;if(l.length>3){let u=this._parseProperties();Object.getOwnPropertyNames(u).length&&(l.properties=u)}}return!0}_parseDisconnect(){let l=this.packet;if(i("_parseDisconnect"),this.settings.protocolVersion===5){this._list.length>0?(l.reasonCode=this._parseByte(),n.MQTT5_DISCONNECT_CODES[l.reasonCode]||this._emitError(new Error("Invalid disconnect reason code"))):l.reasonCode=0;let u=this._parseProperties();Object.getOwnPropertyNames(u).length&&(l.properties=u)}return i("_parseDisconnect result: true"),!0}_parseAuth(){i("_parseAuth");let l=this.packet;if(this.settings.protocolVersion!==5)return this._emitError(new Error("Not supported auth packet for this version MQTT"));if(l.reasonCode=this._parseByte(),!n.MQTT5_AUTH_CODES[l.reasonCode])return this._emitError(new Error("Invalid auth reason code"));let u=this._parseProperties();return Object.getOwnPropertyNames(u).length&&(l.properties=u),i("_parseAuth: result: true"),!0}_parseMessageId(){let l=this.packet;return l.messageId=this._parseNum(),l.messageId===null?(this._emitError(new Error("Cannot parse messageId")),!1):(i("_parseMessageId: packet.messageId %d",l.messageId),!0)}_parseString(l){let u=this._parseNum(),d=u+this._pos;if(u===-1||d>this._list.length||d>this.packet.length)return null;let p=this._list.toString("utf8",this._pos,d);return this._pos+=u,i("_parseString: result: %s",p),p}_parseStringPair(){return i("_parseStringPair"),{name:this._parseString(),value:this._parseString()}}_parseBuffer(){let l=this._parseNum(),u=l+this._pos;if(l===-1||u>this._list.length||u>this.packet.length)return null;let d=this._list.slice(this._pos,u);return this._pos+=l,i("_parseBuffer: result: %o",d),d}_parseNum(){if(this._list.length-this._pos<2)return-1;let l=this._list.readUInt16BE(this._pos);return this._pos+=2,i("_parseNum: result: %s",l),l}_parse4ByteNum(){if(this._list.length-this._pos<4)return-1;let l=this._list.readUInt32BE(this._pos);return this._pos+=4,i("_parse4ByteNum: result: %s",l),l}_parseVarByteNum(l){i("_parseVarByteNum");let u=4,d=0,p=1,y=0,f=!1,g,b=this._pos?this._pos:0;for(;d<u&&b+d<this._list.length;){if(g=this._list.readUInt8(b+d++),y+=p*(g&n.VARBYTEINT_MASK),p*=128,(g&n.VARBYTEINT_FIN_MASK)===0){f=!0;break}if(this._list.length<=d)break}return!f&&d===u&&this._list.length>=d&&this._emitError(new Error("Invalid variable byte integer")),b&&(this._pos+=d),f?l?f={bytes:d,value:y}:f=y:f=!1,i("_parseVarByteNum: result: %o",f),f}_parseByte(){let l;return this._pos<this._list.length&&(l=this._list.readUInt8(this._pos),this._pos++),i("_parseByte: result: %o",l),l}_parseByType(l){switch(i("_parseByType: type: %s",l),l){case"byte":return this._parseByte()!==0;case"int8":return this._parseByte();case"int16":return this._parseNum();case"int32":return this._parse4ByteNum();case"var":return this._parseVarByteNum();case"string":return this._parseString();case"pair":return this._parseStringPair();case"binary":return this._parseBuffer()}}_parseProperties(){i("_parseProperties");let l=this._parseVarByteNum(),u=this._pos+l,d={};for(;this._pos<u;){let p=this._parseByte();if(!p)return this._emitError(new Error("Cannot parse property code type")),!1;let y=n.propertiesCodes[p];if(!y)return this._emitError(new Error("Unknown property")),!1;if(y==="userProperties"){d[y]||(d[y]=Object.create(null));let f=this._parseByType(n.propertiesTypes[y]);if(d[y][f.name])if(Array.isArray(d[y][f.name]))d[y][f.name].push(f.value);else{let g=d[y][f.name];d[y][f.name]=[g],d[y][f.name].push(f.value)}else d[y][f.name]=f.value;continue}d[y]?Array.isArray(d[y])?d[y].push(this._parseByType(n.propertiesTypes[y])):(d[y]=[d[y]],d[y].push(this._parseByType(n.propertiesTypes[y]))):d[y]=this._parseByType(n.propertiesTypes[y])}return d}_newPacket(){return i("_newPacket"),this.packet&&(this._list.consume(this.packet.length),i("_newPacket: parser emit packet: packet.cmd: %s, packet.payload: %s, packet.length: %d",this.packet.cmd,this.packet.payload,this.packet.length),this.emit("packet",this.packet)),i("_newPacket: new packet"),this.packet=new a,this._pos=0,!0}_emitError(l){i("_emitError",l),this.error=l,this.emit("error",l)}};e.exports=s}),Ec=pe((c,e)=>{le(),ue(),ce();var{Buffer:t}=(Ue(),Pe(Ne)),r=65536,a={},n=t.isBuffer(t.from([1,2]).subarray(0,1));function i(u){let d=t.allocUnsafe(2);return d.writeUInt8(u>>8,0),d.writeUInt8(u&255,1),d}function s(){for(let u=0;u<r;u++)a[u]=i(u)}function o(u){let d=0,p=0,y=t.allocUnsafe(4);do d=u%128|0,u=u/128|0,u>0&&(d=d|128),y.writeUInt8(d,p++);while(u>0&&p<4);return u>0&&(p=0),n?y.subarray(0,p):y.slice(0,p)}function l(u){let d=t.allocUnsafe(4);return d.writeUInt32BE(u,0),d}e.exports={cache:a,generateCache:s,generateNumber:i,genBufVariableByteInt:o,generate4ByteBuffer:l}}),xc=pe((c,e)=>{le(),ue(),ce(),typeof Me>"u"||!Me.version||Me.version.indexOf("v0.")===0||Me.version.indexOf("v1.")===0&&Me.version.indexOf("v1.8.")!==0?e.exports={nextTick:t}:e.exports=Me;function t(r,a,n,i){if(typeof r!="function")throw new TypeError('"callback" argument must be a function');var s=arguments.length,o,l;switch(s){case 0:case 1:return Me.nextTick(r);case 2:return Me.nextTick(function(){r.call(null,a)});case 3:return Me.nextTick(function(){r.call(null,a,n)});case 4:return Me.nextTick(function(){r.call(null,a,n,i)});default:for(o=new Array(s-1),l=0;l<o.length;)o[l++]=arguments[l];return Me.nextTick(function(){r.apply(null,o)})}}}),Jo=pe((c,e)=>{le(),ue(),ce();var t=Qo(),{Buffer:r}=(Ue(),Pe(Ne)),a=r.allocUnsafe(0),n=r.from([0]),i=Ec(),s=xc().nextTick,o=lt()("mqtt-packet:writeToStream"),l=i.cache,u=i.generateNumber,d=i.generateCache,p=i.genBufVariableByteInt,y=i.generate4ByteBuffer,f=Y,g=!0;function b(V,L,ne){switch(o("generate called"),L.cork&&(L.cork(),s(k,L)),g&&(g=!1,d()),o("generate: packet.cmd: %s",V.cmd),V.cmd){case"connect":return m(V,L);case"connack":return w(V,L,ne);case"publish":return E(V,L,ne);case"puback":case"pubrec":case"pubrel":case"pubcomp":return v(V,L,ne);case"subscribe":return x(V,L,ne);case"suback":return S(V,L,ne);case"unsubscribe":return I(V,L,ne);case"unsuback":return M(V,L,ne);case"pingreq":case"pingresp":return O(V,L);case"disconnect":return B(V,L,ne);case"auth":return T(V,L,ne);default:return L.destroy(new Error("Unknown command")),!1}}Object.defineProperty(b,"cacheNumbers",{get(){return f===Y},set(V){V?((!l||Object.keys(l).length===0)&&(g=!0),f=Y):(g=!1,f=K)}});function k(V){V.uncork()}function m(V,L,ne){let H=V||{},G=H.protocolId||"MQTT",Q=H.protocolVersion||4,me=H.will,oe=H.clean,R=H.keepalive||0,$=H.clientId||"",ee=H.username,fe=H.password,de=H.properties;oe===void 0&&(oe=!0);let ye=0;if(typeof G!="string"&&!r.isBuffer(G))return L.destroy(new Error("Invalid protocolId")),!1;if(ye+=G.length+2,Q!==3&&Q!==4&&Q!==5)return L.destroy(new Error("Invalid protocol version")),!1;if(ye+=1,(typeof $=="string"||r.isBuffer($))&&($||Q>=4)&&($||oe))ye+=r.byteLength($)+2;else{if(Q<4)return L.destroy(new Error("clientId must be supplied before 3.1.1")),!1;if(oe*1===0)return L.destroy(new Error("clientId must be given if cleanSession set to 0")),!1}if(typeof R!="number"||R<0||R>65535||R%1!==0)return L.destroy(new Error("Invalid keepalive")),!1;ye+=2,ye+=1;let q,ge;if(Q===5){if(q=Z(L,de),!q)return!1;ye+=q.length}if(me){if(typeof me!="object")return L.destroy(new Error("Invalid will")),!1;if(!me.topic||typeof me.topic!="string")return L.destroy(new Error("Invalid will topic")),!1;if(ye+=r.byteLength(me.topic)+2,ye+=2,me.payload)if(me.payload.length>=0)typeof me.payload=="string"?ye+=r.byteLength(me.payload):ye+=me.payload.length;else return L.destroy(new Error("Invalid will payload")),!1;if(ge={},Q===5){if(ge=Z(L,me.properties),!ge)return!1;ye+=ge.length}}let ve=!1;if(ee!=null)if(we(ee))ve=!0,ye+=r.byteLength(ee)+2;else return L.destroy(new Error("Invalid username")),!1;if(fe!=null){if(!ve)return L.destroy(new Error("Username is required to use password")),!1;if(we(fe))ye+=te(fe)+2;else return L.destroy(new Error("Invalid password")),!1}L.write(t.CONNECT_HEADER),F(L,ye),D(L,G),H.bridgeMode&&(Q+=128),L.write(Q===131?t.VERSION131:Q===132?t.VERSION132:Q===4?t.VERSION4:Q===5?t.VERSION5:t.VERSION3);let se=0;return se|=ee!=null?t.USERNAME_MASK:0,se|=fe!=null?t.PASSWORD_MASK:0,se|=me&&me.retain?t.WILL_RETAIN_MASK:0,se|=me&&me.qos?me.qos<<t.WILL_QOS_SHIFT:0,se|=me?t.WILL_FLAG_MASK:0,se|=oe?t.CLEAN_SESSION_MASK:0,L.write(r.from([se])),f(L,R),Q===5&&q.write(),D(L,$),me&&(Q===5&&ge.write(),N(L,me.topic),D(L,me.payload)),ee!=null&&D(L,ee),fe!=null&&D(L,fe),!0}function w(V,L,ne){let H=ne?ne.protocolVersion:4,G=V||{},Q=H===5?G.reasonCode:G.returnCode,me=G.properties,oe=2;if(typeof Q!="number")return L.destroy(new Error("Invalid return code")),!1;let R=null;if(H===5){if(R=Z(L,me),!R)return!1;oe+=R.length}return L.write(t.CONNACK_HEADER),F(L,oe),L.write(G.sessionPresent?t.SESSIONPRESENT_HEADER:n),L.write(r.from([Q])),R?.write(),!0}function E(V,L,ne){o("publish: packet: %o",V);let H=ne?ne.protocolVersion:4,G=V||{},Q=G.qos||0,me=G.retain?t.RETAIN_MASK:0,oe=G.topic,R=G.payload||a,$=G.messageId,ee=G.properties,fe=0;if(typeof oe=="string")fe+=r.byteLength(oe)+2;else if(r.isBuffer(oe))fe+=oe.length+2;else return L.destroy(new Error("Invalid topic")),!1;if(r.isBuffer(R)?fe+=R.length:fe+=r.byteLength(R),Q&&typeof $!="number")return L.destroy(new Error("Invalid messageId")),!1;Q&&(fe+=2);let de=null;if(H===5){if(de=Z(L,ee),!de)return!1;fe+=de.length}return L.write(t.PUBLISH_HEADER[Q][G.dup?1:0][me?1:0]),F(L,fe),f(L,te(oe)),L.write(oe),Q>0&&f(L,$),de?.write(),o("publish: payload: %o",R),L.write(R)}function v(V,L,ne){let H=ne?ne.protocolVersion:4,G=V||{},Q=G.cmd||"puback",me=G.messageId,oe=G.dup&&Q==="pubrel"?t.DUP_MASK:0,R=0,$=G.reasonCode,ee=G.properties,fe=H===5?3:2;if(Q==="pubrel"&&(R=1),typeof me!="number")return L.destroy(new Error("Invalid messageId")),!1;let de=null;if(H===5&&typeof ee=="object"){if(de=P(L,ee,ne,fe),!de)return!1;fe+=de.length}return L.write(t.ACKS[Q][R][oe][0]),fe===3&&(fe+=$!==0?1:-1),F(L,fe),f(L,me),H===5&&fe!==2&&L.write(r.from([$])),de!==null?de.write():fe===4&&L.write(r.from([0])),!0}function x(V,L,ne){o("subscribe: packet: ");let H=ne?ne.protocolVersion:4,G=V||{},Q=G.dup?t.DUP_MASK:0,me=G.messageId,oe=G.subscriptions,R=G.properties,$=0;if(typeof me!="number")return L.destroy(new Error("Invalid messageId")),!1;$+=2;let ee=null;if(H===5){if(ee=Z(L,R),!ee)return!1;$+=ee.length}if(typeof oe=="object"&&oe.length)for(let de=0;de<oe.length;de+=1){let ye=oe[de].topic,q=oe[de].qos;if(typeof ye!="string")return L.destroy(new Error("Invalid subscriptions - invalid topic")),!1;if(typeof q!="number")return L.destroy(new Error("Invalid subscriptions - invalid qos")),!1;if(H===5){if(typeof(oe[de].nl||!1)!="boolean")return L.destroy(new Error("Invalid subscriptions - invalid No Local")),!1;if(typeof(oe[de].rap||!1)!="boolean")return L.destroy(new Error("Invalid subscriptions - invalid Retain as Published")),!1;let ge=oe[de].rh||0;if(typeof ge!="number"||ge>2)return L.destroy(new Error("Invalid subscriptions - invalid Retain Handling")),!1}$+=r.byteLength(ye)+2+1}else return L.destroy(new Error("Invalid subscriptions")),!1;o("subscribe: writing to stream: %o",t.SUBSCRIBE_HEADER),L.write(t.SUBSCRIBE_HEADER[1][Q?1:0][0]),F(L,$),f(L,me),ee!==null&&ee.write();let fe=!0;for(let de of oe){let ye=de.topic,q=de.qos,ge=+de.nl,ve=+de.rap,se=de.rh,Te;N(L,ye),Te=t.SUBSCRIBE_OPTIONS_QOS[q],H===5&&(Te|=ge?t.SUBSCRIBE_OPTIONS_NL:0,Te|=ve?t.SUBSCRIBE_OPTIONS_RAP:0,Te|=se?t.SUBSCRIBE_OPTIONS_RH[se]:0),fe=L.write(r.from([Te]))}return fe}function S(V,L,ne){let H=ne?ne.protocolVersion:4,G=V||{},Q=G.messageId,me=G.granted,oe=G.properties,R=0;if(typeof Q!="number")return L.destroy(new Error("Invalid messageId")),!1;if(R+=2,typeof me=="object"&&me.length)for(let ee=0;ee<me.length;ee+=1){if(typeof me[ee]!="number")return L.destroy(new Error("Invalid qos vector")),!1;R+=1}else return L.destroy(new Error("Invalid qos vector")),!1;let $=null;if(H===5){if($=P(L,oe,ne,R),!$)return!1;R+=$.length}return L.write(t.SUBACK_HEADER),F(L,R),f(L,Q),$!==null&&$.write(),L.write(r.from(me))}function I(V,L,ne){let H=ne?ne.protocolVersion:4,G=V||{},Q=G.messageId,me=G.dup?t.DUP_MASK:0,oe=G.unsubscriptions,R=G.properties,$=0;if(typeof Q!="number")return L.destroy(new Error("Invalid messageId")),!1;if($+=2,typeof oe=="object"&&oe.length)for(let de=0;de<oe.length;de+=1){if(typeof oe[de]!="string")return L.destroy(new Error("Invalid unsubscriptions")),!1;$+=r.byteLength(oe[de])+2}else return L.destroy(new Error("Invalid unsubscriptions")),!1;let ee=null;if(H===5){if(ee=Z(L,R),!ee)return!1;$+=ee.length}L.write(t.UNSUBSCRIBE_HEADER[1][me?1:0][0]),F(L,$),f(L,Q),ee!==null&&ee.write();let fe=!0;for(let de=0;de<oe.length;de++)fe=N(L,oe[de]);return fe}function M(V,L,ne){let H=ne?ne.protocolVersion:4,G=V||{},Q=G.messageId,me=G.dup?t.DUP_MASK:0,oe=G.granted,R=G.properties,$=G.cmd,ee=0,fe=2;if(typeof Q!="number")return L.destroy(new Error("Invalid messageId")),!1;if(H===5)if(typeof oe=="object"&&oe.length)for(let ye=0;ye<oe.length;ye+=1){if(typeof oe[ye]!="number")return L.destroy(new Error("Invalid qos vector")),!1;fe+=1}else return L.destroy(new Error("Invalid qos vector")),!1;let de=null;if(H===5){if(de=P(L,R,ne,fe),!de)return!1;fe+=de.length}return L.write(t.ACKS[$][ee][me][0]),F(L,fe),f(L,Q),de!==null&&de.write(),H===5&&L.write(r.from(oe)),!0}function O(V,L,ne){return L.write(t.EMPTY[V.cmd])}function B(V,L,ne){let H=ne?ne.protocolVersion:4,G=V||{},Q=G.reasonCode,me=G.properties,oe=H===5?1:0,R=null;if(H===5){if(R=P(L,me,ne,oe),!R)return!1;oe+=R.length}return L.write(r.from([t.codes.disconnect<<4])),F(L,oe),H===5&&L.write(r.from([Q])),R!==null&&R.write(),!0}function T(V,L,ne){let H=ne?ne.protocolVersion:4,G=V||{},Q=G.reasonCode,me=G.properties,oe=H===5?1:0;H!==5&&L.destroy(new Error("Invalid mqtt version for auth packet"));let R=P(L,me,ne,oe);return R?(oe+=R.length,L.write(r.from([t.codes.auth<<4])),F(L,oe),L.write(r.from([Q])),R!==null&&R.write(),!0):!1}var W={};function F(V,L){if(L>t.VARBYTEINT_MAX)return V.destroy(new Error(`Invalid variable byte integer: ${L}`)),!1;let ne=W[L];return ne||(ne=p(L),L<16384&&(W[L]=ne)),o("writeVarByteInt: writing to stream: %o",ne),V.write(ne)}function N(V,L){let ne=r.byteLength(L);return f(V,ne),o("writeString: %s",L),V.write(L,"utf8")}function ae(V,L,ne){N(V,L),N(V,ne)}function Y(V,L){return o("writeNumberCached: number: %d",L),o("writeNumberCached: %o",l[L]),V.write(l[L])}function K(V,L){let ne=u(L);return o("writeNumberGenerated: %o",ne),V.write(ne)}function re(V,L){let ne=y(L);return o("write4ByteNumber: %o",ne),V.write(ne)}function D(V,L){typeof L=="string"?N(V,L):L?(f(V,L.length),V.write(L)):f(V,0)}function Z(V,L){if(typeof L!="object"||L.length!=null)return{length:1,write(){be(V,{},0)}};let ne=0;function H(G,Q){let me=t.propertiesTypes[G],oe=0;switch(me){case"byte":{if(typeof Q!="boolean")return V.destroy(new Error(`Invalid ${G}: ${Q}`)),!1;oe+=2;break}case"int8":{if(typeof Q!="number"||Q<0||Q>255)return V.destroy(new Error(`Invalid ${G}: ${Q}`)),!1;oe+=2;break}case"binary":{if(Q&&Q===null)return V.destroy(new Error(`Invalid ${G}: ${Q}`)),!1;oe+=1+r.byteLength(Q)+2;break}case"int16":{if(typeof Q!="number"||Q<0||Q>65535)return V.destroy(new Error(`Invalid ${G}: ${Q}`)),!1;oe+=3;break}case"int32":{if(typeof Q!="number"||Q<0||Q>4294967295)return V.destroy(new Error(`Invalid ${G}: ${Q}`)),!1;oe+=5;break}case"var":{if(typeof Q!="number"||Q<0||Q>268435455)return V.destroy(new Error(`Invalid ${G}: ${Q}`)),!1;oe+=1+r.byteLength(p(Q));break}case"string":{if(typeof Q!="string")return V.destroy(new Error(`Invalid ${G}: ${Q}`)),!1;oe+=3+r.byteLength(Q.toString());break}case"pair":{if(typeof Q!="object")return V.destroy(new Error(`Invalid ${G}: ${Q}`)),!1;oe+=Object.getOwnPropertyNames(Q).reduce((R,$)=>{let ee=Q[$];return Array.isArray(ee)?R+=ee.reduce((fe,de)=>(fe+=3+r.byteLength($.toString())+2+r.byteLength(de.toString()),fe),0):R+=3+r.byteLength($.toString())+2+r.byteLength(Q[$].toString()),R},0);break}default:return V.destroy(new Error(`Invalid property ${G}: ${Q}`)),!1}return oe}if(L)for(let G in L){let Q=0,me=0,oe=L[G];if(oe!==void 0){if(Array.isArray(oe))for(let R=0;R<oe.length;R++){if(me=H(G,oe[R]),!me)return!1;Q+=me}else{if(me=H(G,oe),!me)return!1;Q=me}if(!Q)return!1;ne+=Q}}return{length:r.byteLength(p(ne))+ne,write(){be(V,L,ne)}}}function P(V,L,ne,H){let G=["reasonString","userProperties"],Q=ne&&ne.properties&&ne.properties.maximumPacketSize?ne.properties.maximumPacketSize:0,me=Z(V,L);if(Q)for(;H+me.length>Q;){let oe=G.shift();if(oe&&L[oe])delete L[oe],me=Z(V,L);else return!1}return me}function J(V,L,ne){switch(t.propertiesTypes[L]){case"byte":{V.write(r.from([t.properties[L]])),V.write(r.from([+ne]));break}case"int8":{V.write(r.from([t.properties[L]])),V.write(r.from([ne]));break}case"binary":{V.write(r.from([t.properties[L]])),D(V,ne);break}case"int16":{V.write(r.from([t.properties[L]])),f(V,ne);break}case"int32":{V.write(r.from([t.properties[L]])),re(V,ne);break}case"var":{V.write(r.from([t.properties[L]])),F(V,ne);break}case"string":{V.write(r.from([t.properties[L]])),N(V,ne);break}case"pair":{Object.getOwnPropertyNames(ne).forEach(H=>{let G=ne[H];Array.isArray(G)?G.forEach(Q=>{V.write(r.from([t.properties[L]])),ae(V,H.toString(),Q.toString())}):(V.write(r.from([t.properties[L]])),ae(V,H.toString(),G.toString()))});break}default:return V.destroy(new Error(`Invalid property ${L} value: ${ne}`)),!1}}function be(V,L,ne){F(V,ne);for(let H in L)if(Object.prototype.hasOwnProperty.call(L,H)&&L[H]!=null){let G=L[H];if(Array.isArray(G))for(let Q=0;Q<G.length;Q++)J(V,H,G[Q]);else J(V,H,G)}}function te(V){return V?V instanceof r?V.length:r.byteLength(V):0}function we(V){return typeof V=="string"||V instanceof r}e.exports=b}),Ac=pe((c,e)=>{le(),ue(),ce();var t=Jo(),{EventEmitter:r}=(kt(),Pe(pt)),{Buffer:a}=(Ue(),Pe(Ne));function n(s,o){let l=new i;return t(s,l,o),l.concat()}var i=class extends r{constructor(){super(),this._array=new Array(20),this._i=0}write(s){return this._array[this._i++]=s,!0}concat(){let s=0,o=new Array(this._array.length),l=this._array,u=0,d;for(d=0;d<l.length&&l[d]!==void 0;d++)typeof l[d]!="string"?o[d]=l[d].length:o[d]=a.byteLength(l[d]),s+=o[d];let p=a.allocUnsafe(s);for(d=0;d<l.length&&l[d]!==void 0;d++)typeof l[d]!="string"?(l[d].copy(p,u),u+=o[d]):(p.write(l[d],u),u+=o[d]);return p}destroy(s){s&&this.emit("error",s)}};e.exports=n}),Ic=pe(c=>{le(),ue(),ce(),c.parser=Sc().parser,c.generate=Ac(),c.writeToStream=Jo()}),Tc=pe((c,e)=>{le(),ue(),ce(),e.exports=r;function t(n){return n instanceof rr?rr.from(n):new n.constructor(n.buffer.slice(),n.byteOffset,n.length)}function r(n){if(n=n||{},n.circles)return a(n);let i=new Map;if(i.set(Date,d=>new Date(d)),i.set(Map,(d,p)=>new Map(o(Array.from(d),p))),i.set(Set,(d,p)=>new Set(o(Array.from(d),p))),n.constructorHandlers)for(let d of n.constructorHandlers)i.set(d[0],d[1]);let s=null;return n.proto?u:l;function o(d,p){let y=Object.keys(d),f=new Array(y.length);for(let g=0;g<y.length;g++){let b=y[g],k=d[b];typeof k!="object"||k===null?f[b]=k:k.constructor!==Object&&(s=i.get(k.constructor))?f[b]=s(k,p):ArrayBuffer.isView(k)?f[b]=t(k):f[b]=p(k)}return f}function l(d){if(typeof d!="object"||d===null)return d;if(Array.isArray(d))return o(d,l);if(d.constructor!==Object&&(s=i.get(d.constructor)))return s(d,l);let p={};for(let y in d){if(Object.hasOwnProperty.call(d,y)===!1)continue;let f=d[y];typeof f!="object"||f===null?p[y]=f:f.constructor!==Object&&(s=i.get(f.constructor))?p[y]=s(f,l):ArrayBuffer.isView(f)?p[y]=t(f):p[y]=l(f)}return p}function u(d){if(typeof d!="object"||d===null)return d;if(Array.isArray(d))return o(d,u);if(d.constructor!==Object&&(s=i.get(d.constructor)))return s(d,u);let p={};for(let y in d){let f=d[y];typeof f!="object"||f===null?p[y]=f:f.constructor!==Object&&(s=i.get(f.constructor))?p[y]=s(f,u):ArrayBuffer.isView(f)?p[y]=t(f):p[y]=u(f)}return p}}function a(n){let i=[],s=[],o=new Map;if(o.set(Date,y=>new Date(y)),o.set(Map,(y,f)=>new Map(u(Array.from(y),f))),o.set(Set,(y,f)=>new Set(u(Array.from(y),f))),n.constructorHandlers)for(let y of n.constructorHandlers)o.set(y[0],y[1]);let l=null;return n.proto?p:d;function u(y,f){let g=Object.keys(y),b=new Array(g.length);for(let k=0;k<g.length;k++){let m=g[k],w=y[m];if(typeof w!="object"||w===null)b[m]=w;else if(w.constructor!==Object&&(l=o.get(w.constructor)))b[m]=l(w,f);else if(ArrayBuffer.isView(w))b[m]=t(w);else{let E=i.indexOf(w);E!==-1?b[m]=s[E]:b[m]=f(w)}}return b}function d(y){if(typeof y!="object"||y===null)return y;if(Array.isArray(y))return u(y,d);if(y.constructor!==Object&&(l=o.get(y.constructor)))return l(y,d);let f={};i.push(y),s.push(f);for(let g in y){if(Object.hasOwnProperty.call(y,g)===!1)continue;let b=y[g];if(typeof b!="object"||b===null)f[g]=b;else if(b.constructor!==Object&&(l=o.get(b.constructor)))f[g]=l(b,d);else if(ArrayBuffer.isView(b))f[g]=t(b);else{let k=i.indexOf(b);k!==-1?f[g]=s[k]:f[g]=d(b)}}return i.pop(),s.pop(),f}function p(y){if(typeof y!="object"||y===null)return y;if(Array.isArray(y))return u(y,p);if(y.constructor!==Object&&(l=o.get(y.constructor)))return l(y,p);let f={};i.push(y),s.push(f);for(let g in y){let b=y[g];if(typeof b!="object"||b===null)f[g]=b;else if(b.constructor!==Object&&(l=o.get(b.constructor)))f[g]=l(b,p);else if(ArrayBuffer.isView(b))f[g]=t(b);else{let k=i.indexOf(b);k!==-1?f[g]=s[k]:f[g]=p(b)}}return i.pop(),s.pop(),f}}}),Cc=pe((c,e)=>{le(),ue(),ce(),e.exports=Tc()()}),Xo=pe(c=>{le(),ue(),ce(),Object.defineProperty(c,"__esModule",{value:!0}),c.validateTopic=e,c.validateTopics=t;function e(r){let a=r.split("/");for(let n=0;n<a.length;n++)if(a[n]!=="+"){if(a[n]==="#")return n===a.length-1;if(a[n].indexOf("+")!==-1||a[n].indexOf("#")!==-1)return!1}return!0}function t(r){if(r.length===0)return"empty_topic_list";for(let a=0;a<r.length;a++)if(!e(r[a]))return r[a];return null}}),Zo=pe(c=>{le(),ue(),ce(),Object.defineProperty(c,"__esModule",{value:!0});var e=Et(),t={objectMode:!0},r={clean:!0},a=class{options;_inflights;constructor(n){this.options=n||{},this.options={...r,...n},this._inflights=new Map}put(n,i){return this._inflights.set(n.messageId,n),i&&i(),this}createStream(){let n=new e.Readable(t),i=[],s=!1,o=0;return this._inflights.forEach((l,u)=>{i.push(l)}),n._read=()=>{!s&&o<i.length?n.push(i[o++]):n.push(null)},n.destroy=l=>{if(!s)return s=!0,setTimeout(()=>{n.emit("close")},0),n},n}del(n,i){let s=this._inflights.get(n.messageId);return s?(this._inflights.delete(n.messageId),i(null,s)):i&&i(new Error("missing packet")),this}get(n,i){let s=this._inflights.get(n.messageId);return s?i(null,s):i&&i(new Error("missing packet")),this}close(n){this.options.clean&&(this._inflights=null),n&&n()}};c.default=a}),Oc=pe(c=>{le(),ue(),ce(),Object.defineProperty(c,"__esModule",{value:!0});var e=[0,16,128,131,135,144,145,151,153],t=(r,a,n)=>{r.log("handlePublish: packet %o",a),n=typeof n<"u"?n:r.noop;let i=a.topic.toString(),s=a.payload,{qos:o}=a,{messageId:l}=a,{options:u}=r;if(r.options.protocolVersion===5){let d;if(a.properties&&(d=a.properties.topicAlias),typeof d<"u")if(i.length===0)if(d>0&&d<=65535){let p=r.topicAliasRecv.getTopicByAlias(d);if(p)i=p,r.log("handlePublish :: topic complemented by alias. topic: %s - alias: %d",i,d);else{r.log("handlePublish :: unregistered topic alias. alias: %d",d),r.emit("error",new Error("Received unregistered Topic Alias"));return}}else{r.log("handlePublish :: topic alias out of range. alias: %d",d),r.emit("error",new Error("Received Topic Alias is out of range"));return}else if(r.topicAliasRecv.put(i,d))r.log("handlePublish :: registered topic: %s - alias: %d",i,d);else{r.log("handlePublish :: topic alias out of range. alias: %d",d),r.emit("error",new Error("Received Topic Alias is out of range"));return}}switch(r.log("handlePublish: qos %d",o),o){case 2:{u.customHandleAcks(i,s,a,(d,p)=>{if(typeof d=="number"&&(p=d,d=null),d)return r.emit("error",d);if(e.indexOf(p)===-1)return r.emit("error",new Error("Wrong reason code for pubrec"));p?r._sendPacket({cmd:"pubrec",messageId:l,reasonCode:p},n):r.incomingStore.put(a,()=>{r._sendPacket({cmd:"pubrec",messageId:l},n)})});break}case 1:{u.customHandleAcks(i,s,a,(d,p)=>{if(typeof d=="number"&&(p=d,d=null),d)return r.emit("error",d);if(e.indexOf(p)===-1)return r.emit("error",new Error("Wrong reason code for puback"));p||r.emit("message",i,s,a),r.handleMessage(a,y=>{if(y)return n&&n(y);r._sendPacket({cmd:"puback",messageId:l,reasonCode:p},n)})});break}case 0:r.emit("message",i,s,a),r.handleMessage(a,n);break;default:r.log("handlePublish: unknown QoS. Doing nothing.");break}};c.default=t}),Pc=pe((c,e)=>{e.exports={version:"5.15.0"}}),Rt=pe(c=>{le(),ue(),ce(),Object.defineProperty(c,"__esModule",{value:!0}),c.MQTTJS_VERSION=c.nextTick=c.ErrorWithSubackPacket=c.ErrorWithReasonCode=void 0,c.applyMixin=r;var e=class Ll extends Error{code;constructor(n,i){super(n),this.code=i,Object.setPrototypeOf(this,Ll.prototype),Object.getPrototypeOf(this).name="ErrorWithReasonCode"}};c.ErrorWithReasonCode=e;var t=class Nl extends Error{packet;constructor(n,i){super(n),this.packet=i,Object.setPrototypeOf(this,Nl.prototype),Object.getPrototypeOf(this).name="ErrorWithSubackPacket"}};c.ErrorWithSubackPacket=t;function r(a,n,i=!1){let s=[n];for(;;){let o=s[0],l=Object.getPrototypeOf(o);if(l?.prototype)s.unshift(l);else break}for(let o of s)for(let l of Object.getOwnPropertyNames(o.prototype))(i||l!=="constructor")&&Object.defineProperty(a.prototype,l,Object.getOwnPropertyDescriptor(o.prototype,l)??Object.create(null))}c.nextTick=typeof Me?.nextTick=="function"?Me.nextTick:a=>{setTimeout(a,0)},c.MQTTJS_VERSION=Pc().version}),sr=pe(c=>{le(),ue(),ce(),Object.defineProperty(c,"__esModule",{value:!0}),c.ReasonCodes=void 0;var e=Rt();c.ReasonCodes={0:"",1:"Unacceptable protocol version",2:"Identifier rejected",3:"Server unavailable",4:"Bad username or password",5:"Not authorized",16:"No matching subscribers",17:"No subscription existed",128:"Unspecified error",129:"Malformed Packet",130:"Protocol Error",131:"Implementation specific error",132:"Unsupported Protocol Version",133:"Client Identifier not valid",134:"Bad User Name or Password",135:"Not authorized",136:"Server unavailable",137:"Server busy",138:"Banned",139:"Server shutting down",140:"Bad authentication method",141:"Keep Alive timeout",142:"Session taken over",143:"Topic Filter invalid",144:"Topic Name invalid",145:"Packet identifier in use",146:"Packet Identifier not found",147:"Receive Maximum exceeded",148:"Topic Alias invalid",149:"Packet too large",150:"Message rate too high",151:"Quota exceeded",152:"Administrative action",153:"Payload format invalid",154:"Retain not supported",155:"QoS not supported",156:"Use another server",157:"Server moved",158:"Shared Subscriptions not supported",159:"Connection rate exceeded",160:"Maximum connect time",161:"Subscription Identifiers not supported",162:"Wildcard Subscriptions not supported"};var t=(r,a)=>{let{messageId:n}=a,i=a.cmd,s=null,o=r.outgoing[n]?r.outgoing[n].cb:null,l=null;if(!o){r.log("_handleAck :: Server sent an ack in error. Ignoring.");return}switch(r.log("_handleAck :: packet type",i),i){case"pubcomp":case"puback":{let u=a.reasonCode;u&&u>0&&u!==16?(l=new e.ErrorWithReasonCode(`Publish error: ${c.ReasonCodes[u]}`,u),r._removeOutgoingAndStoreMessage(n,()=>{o(l,a)})):r._removeOutgoingAndStoreMessage(n,o);break}case"pubrec":{s={cmd:"pubrel",qos:2,messageId:n};let u=a.reasonCode;u&&u>0&&u!==16?(l=new e.ErrorWithReasonCode(`Publish error: ${c.ReasonCodes[u]}`,u),r._removeOutgoingAndStoreMessage(n,()=>{o(l,a)})):r._sendPacket(s);break}case"suback":{delete r.outgoing[n],r.messageIdProvider.deallocate(n);let u=a.granted;for(let d=0;d<u.length;d++){let p=u[d];if((p&128)!==0){l=new Error(`Subscribe error: ${c.ReasonCodes[p]}`),l.code=p;let y=r.messageIdToTopic[n];y&&y.forEach(f=>{delete r._resubscribeTopics[f]})}}delete r.messageIdToTopic[n],r._invokeStoreProcessingQueue(),o(l,a);break}case"unsuback":{delete r.outgoing[n],r.messageIdProvider.deallocate(n),r._invokeStoreProcessingQueue(),o(null,a);break}default:r.emit("error",new Error("unrecognized packet type"))}r.disconnecting&&Object.keys(r.outgoing).length===0&&r.emit("outgoingEmpty")};c.default=t}),Mc=pe(c=>{le(),ue(),ce(),Object.defineProperty(c,"__esModule",{value:!0});var e=Rt(),t=sr(),r=(a,n)=>{let{options:i}=a,s=i.protocolVersion,o=s===5?n.reasonCode:n.returnCode;if(s!==5){let l=new e.ErrorWithReasonCode(`Protocol error: Auth packets are only supported in MQTT 5. Your version:${s}`,o);a.emit("error",l);return}a.handleAuth(n,(l,u)=>{if(l){a.emit("error",l);return}if(o===24)a.reconnecting=!1,a._sendPacket(u);else{let d=new e.ErrorWithReasonCode(`Connection refused: ${t.ReasonCodes[o]}`,o);a.emit("error",d)}})};c.default=r}),Rc=pe(c=>{le(),ue(),ce(),Object.defineProperty(c,"__esModule",{value:!0}),c.LRUCache=void 0;var e=typeof performance=="object"&&performance&&typeof performance.now=="function"?performance:Date,t=new Set,r=typeof Me=="object"&&Me?Me:{},a=(y,f,g,b)=>{typeof r.emitWarning=="function"?r.emitWarning(y,f,g,b):console.error(`[${g}] ${f}: ${y}`)},n=globalThis.AbortController,i=globalThis.AbortSignal;if(typeof n>"u"){i=class{onabort;_onabort=[];reason;aborted=!1;addEventListener(g,b){this._onabort.push(b)}},n=class{constructor(){f()}signal=new i;abort(g){if(!this.signal.aborted){this.signal.reason=g,this.signal.aborted=!0;for(let b of this.signal._onabort)b(g);this.signal.onabort?.(g)}}};let y=r.env?.LRU_CACHE_IGNORE_AC_WARNING!=="1",f=()=>{y&&(y=!1,a("AbortController is not defined. If using lru-cache in node 14, load an AbortController polyfill from the `node-abort-controller` package. A minimal polyfill is provided for use by LRUCache.fetch(), but it should not be relied upon in other contexts (eg, passing it to other APIs that use AbortController/AbortSignal might have undesirable effects). You may disable this with LRU_CACHE_IGNORE_AC_WARNING=1 in the env.","NO_ABORT_CONTROLLER","ENOTSUP",f))}}var s=y=>!t.has(y),o=y=>y&&y===Math.floor(y)&&y>0&&isFinite(y),l=y=>o(y)?y<=Math.pow(2,8)?Uint8Array:y<=Math.pow(2,16)?Uint16Array:y<=Math.pow(2,32)?Uint32Array:y<=Number.MAX_SAFE_INTEGER?u:null:null,u=class extends Array{constructor(y){super(y),this.fill(0)}},d=class Xt{heap;length;static#l=!1;static create(f){let g=l(f);if(!g)return[];Xt.#l=!0;let b=new Xt(f,g);return Xt.#l=!1,b}constructor(f,g){if(!Xt.#l)throw new TypeError("instantiate Stack using Stack.create(n)");this.heap=new g(f),this.length=0}push(f){this.heap[this.length++]=f}pop(){return this.heap[--this.length]}},p=class Ul{#l;#h;#g;#m;#O;#P;ttl;ttlResolution;ttlAutopurge;updateAgeOnGet;updateAgeOnHas;allowStale;noDisposeOnSet;noUpdateTTL;maxEntrySize;sizeCalculation;noDeleteOnFetchRejection;noDeleteOnStaleGet;allowStaleOnFetchAbort;allowStaleOnFetchRejection;ignoreFetchAbort;#i;#b;#n;#r;#e;#c;#f;#a;#o;#y;#s;#v;#w;#d;#_;#A;#u;static unsafeExposeInternals(f){return{starts:f.#w,ttls:f.#d,sizes:f.#v,keyMap:f.#n,keyList:f.#r,valList:f.#e,next:f.#c,prev:f.#f,get head(){return f.#a},get tail(){return f.#o},free:f.#y,isBackgroundFetch:g=>f.#t(g),backgroundFetch:(g,b,k,m)=>f.#j(g,b,k,m),moveToTail:g=>f.#C(g),indexes:g=>f.#k(g),rindexes:g=>f.#S(g),isStale:g=>f.#p(g)}}get max(){return this.#l}get maxSize(){return this.#h}get calculatedSize(){return this.#b}get size(){return this.#i}get fetchMethod(){return this.#O}get memoMethod(){return this.#P}get dispose(){return this.#g}get disposeAfter(){return this.#m}constructor(f){let{max:g=0,ttl:b,ttlResolution:k=1,ttlAutopurge:m,updateAgeOnGet:w,updateAgeOnHas:E,allowStale:v,dispose:x,disposeAfter:S,noDisposeOnSet:I,noUpdateTTL:M,maxSize:O=0,maxEntrySize:B=0,sizeCalculation:T,fetchMethod:W,memoMethod:F,noDeleteOnFetchRejection:N,noDeleteOnStaleGet:ae,allowStaleOnFetchRejection:Y,allowStaleOnFetchAbort:K,ignoreFetchAbort:re}=f;if(g!==0&&!o(g))throw new TypeError("max option must be a nonnegative integer");let D=g?l(g):Array;if(!D)throw new Error("invalid max value: "+g);if(this.#l=g,this.#h=O,this.maxEntrySize=B||this.#h,this.sizeCalculation=T,this.sizeCalculation){if(!this.#h&&!this.maxEntrySize)throw new TypeError("cannot set sizeCalculation without setting maxSize or maxEntrySize");if(typeof this.sizeCalculation!="function")throw new TypeError("sizeCalculation set to non-function")}if(F!==void 0&&typeof F!="function")throw new TypeError("memoMethod must be a function if defined");if(this.#P=F,W!==void 0&&typeof W!="function")throw new TypeError("fetchMethod must be a function if specified");if(this.#O=W,this.#A=!!W,this.#n=new Map,this.#r=new Array(g).fill(void 0),this.#e=new Array(g).fill(void 0),this.#c=new D(g),this.#f=new D(g),this.#a=0,this.#o=0,this.#y=d.create(g),this.#i=0,this.#b=0,typeof x=="function"&&(this.#g=x),typeof S=="function"?(this.#m=S,this.#s=[]):(this.#m=void 0,this.#s=void 0),this.#_=!!this.#g,this.#u=!!this.#m,this.noDisposeOnSet=!!I,this.noUpdateTTL=!!M,this.noDeleteOnFetchRejection=!!N,this.allowStaleOnFetchRejection=!!Y,this.allowStaleOnFetchAbort=!!K,this.ignoreFetchAbort=!!re,this.maxEntrySize!==0){if(this.#h!==0&&!o(this.#h))throw new TypeError("maxSize must be a positive integer if specified");if(!o(this.maxEntrySize))throw new TypeError("maxEntrySize must be a positive integer if specified");this.#$()}if(this.allowStale=!!v,this.noDeleteOnStaleGet=!!ae,this.updateAgeOnGet=!!w,this.updateAgeOnHas=!!E,this.ttlResolution=o(k)||k===0?k:1,this.ttlAutopurge=!!m,this.ttl=b||0,this.ttl){if(!o(this.ttl))throw new TypeError("ttl must be a positive integer if specified");this.#L()}if(this.#l===0&&this.ttl===0&&this.#h===0)throw new TypeError("At least one of max, maxSize, or ttl is required");if(!this.ttlAutopurge&&!this.#l&&!this.#h){let Z="LRU_CACHE_UNBOUNDED";s(Z)&&(t.add(Z),a("TTL caching without ttlAutopurge, max, or maxSize can result in unbounded memory consumption.","UnboundedCacheWarning",Z,Ul))}}getRemainingTTL(f){return this.#n.has(f)?1/0:0}#L(){let f=new u(this.#l),g=new u(this.#l);this.#d=f,this.#w=g,this.#N=(m,w,E=e.now())=>{if(g[m]=w!==0?E:0,f[m]=w,w!==0&&this.ttlAutopurge){let v=setTimeout(()=>{this.#p(m)&&this.#E(this.#r[m],"expire")},w+1);v.unref&&v.unref()}},this.#I=m=>{g[m]=f[m]!==0?e.now():0},this.#x=(m,w)=>{if(f[w]){let E=f[w],v=g[w];if(!E||!v)return;m.ttl=E,m.start=v,m.now=b||k();let x=m.now-v;m.remainingTTL=E-x}};let b=0,k=()=>{let m=e.now();if(this.ttlResolution>0){b=m;let w=setTimeout(()=>b=0,this.ttlResolution);w.unref&&w.unref()}return m};this.getRemainingTTL=m=>{let w=this.#n.get(m);if(w===void 0)return 0;let E=f[w],v=g[w];if(!E||!v)return 1/0;let x=(b||k())-v;return E-x},this.#p=m=>{let w=g[m],E=f[m];return!!E&&!!w&&(b||k())-w>E}}#I=()=>{};#x=()=>{};#N=()=>{};#p=()=>!1;#$(){let f=new u(this.#l);this.#b=0,this.#v=f,this.#T=g=>{this.#b-=f[g],f[g]=0},this.#U=(g,b,k,m)=>{if(this.#t(b))return 0;if(!o(k))if(m){if(typeof m!="function")throw new TypeError("sizeCalculation must be a function");if(k=m(b,g),!o(k))throw new TypeError("sizeCalculation return invalid (expect positive integer)")}else throw new TypeError("invalid size value (must be positive integer). When maxSize or maxEntrySize is used, sizeCalculation or size must be set.");return k},this.#M=(g,b,k)=>{if(f[g]=b,this.#h){let m=this.#h-f[g];for(;this.#b>m;)this.#R(!0)}this.#b+=f[g],k&&(k.entrySize=b,k.totalCalculatedSize=this.#b)}}#T=f=>{};#M=(f,g,b)=>{};#U=(f,g,b,k)=>{if(b||k)throw new TypeError("cannot set size without setting maxSize or maxEntrySize on cache");return 0};*#k({allowStale:f=this.allowStale}={}){if(this.#i)for(let g=this.#o;!(!this.#B(g)||((f||!this.#p(g))&&(yield g),g===this.#a));)g=this.#f[g]}*#S({allowStale:f=this.allowStale}={}){if(this.#i)for(let g=this.#a;!(!this.#B(g)||((f||!this.#p(g))&&(yield g),g===this.#o));)g=this.#c[g]}#B(f){return f!==void 0&&this.#n.get(this.#r[f])===f}*entries(){for(let f of this.#k())this.#e[f]!==void 0&&this.#r[f]!==void 0&&!this.#t(this.#e[f])&&(yield[this.#r[f],this.#e[f]])}*rentries(){for(let f of this.#S())this.#e[f]!==void 0&&this.#r[f]!==void 0&&!this.#t(this.#e[f])&&(yield[this.#r[f],this.#e[f]])}*keys(){for(let f of this.#k()){let g=this.#r[f];g!==void 0&&!this.#t(this.#e[f])&&(yield g)}}*rkeys(){for(let f of this.#S()){let g=this.#r[f];g!==void 0&&!this.#t(this.#e[f])&&(yield g)}}*values(){for(let f of this.#k())this.#e[f]!==void 0&&!this.#t(this.#e[f])&&(yield this.#e[f])}*rvalues(){for(let f of this.#S())this.#e[f]!==void 0&&!this.#t(this.#e[f])&&(yield this.#e[f])}[Symbol.iterator](){return this.entries()}[Symbol.toStringTag]="LRUCache";find(f,g={}){for(let b of this.#k()){let k=this.#e[b],m=this.#t(k)?k.__staleWhileFetching:k;if(m!==void 0&&f(m,this.#r[b],this))return this.get(this.#r[b],g)}}forEach(f,g=this){for(let b of this.#k()){let k=this.#e[b],m=this.#t(k)?k.__staleWhileFetching:k;m!==void 0&&f.call(g,m,this.#r[b],this)}}rforEach(f,g=this){for(let b of this.#S()){let k=this.#e[b],m=this.#t(k)?k.__staleWhileFetching:k;m!==void 0&&f.call(g,m,this.#r[b],this)}}purgeStale(){let f=!1;for(let g of this.#S({allowStale:!0}))this.#p(g)&&(this.#E(this.#r[g],"expire"),f=!0);return f}info(f){let g=this.#n.get(f);if(g===void 0)return;let b=this.#e[g],k=this.#t(b)?b.__staleWhileFetching:b;if(k===void 0)return;let m={value:k};if(this.#d&&this.#w){let w=this.#d[g],E=this.#w[g];if(w&&E){let v=w-(e.now()-E);m.ttl=v,m.start=Date.now()}}return this.#v&&(m.size=this.#v[g]),m}dump(){let f=[];for(let g of this.#k({allowStale:!0})){let b=this.#r[g],k=this.#e[g],m=this.#t(k)?k.__staleWhileFetching:k;if(m===void 0||b===void 0)continue;let w={value:m};if(this.#d&&this.#w){w.ttl=this.#d[g];let E=e.now()-this.#w[g];w.start=Math.floor(Date.now()-E)}this.#v&&(w.size=this.#v[g]),f.unshift([b,w])}return f}load(f){this.clear();for(let[g,b]of f){if(b.start){let k=Date.now()-b.start;b.start=e.now()-k}this.set(g,b.value,b)}}set(f,g,b={}){if(g===void 0)return this.delete(f),this;let{ttl:k=this.ttl,start:m,noDisposeOnSet:w=this.noDisposeOnSet,sizeCalculation:E=this.sizeCalculation,status:v}=b,{noUpdateTTL:x=this.noUpdateTTL}=b,S=this.#U(f,g,b.size||0,E);if(this.maxEntrySize&&S>this.maxEntrySize)return v&&(v.set="miss",v.maxEntrySizeExceeded=!0),this.#E(f,"set"),this;let I=this.#i===0?void 0:this.#n.get(f);if(I===void 0)I=this.#i===0?this.#o:this.#y.length!==0?this.#y.pop():this.#i===this.#l?this.#R(!1):this.#i,this.#r[I]=f,this.#e[I]=g,this.#n.set(f,I),this.#c[this.#o]=I,this.#f[I]=this.#o,this.#o=I,this.#i++,this.#M(I,S,v),v&&(v.set="add"),x=!1;else{this.#C(I);let M=this.#e[I];if(g!==M){if(this.#A&&this.#t(M)){M.__abortController.abort(new Error("replaced"));let{__staleWhileFetching:O}=M;O!==void 0&&!w&&(this.#_&&this.#g?.(O,f,"set"),this.#u&&this.#s?.push([O,f,"set"]))}else w||(this.#_&&this.#g?.(M,f,"set"),this.#u&&this.#s?.push([M,f,"set"]));if(this.#T(I),this.#M(I,S,v),this.#e[I]=g,v){v.set="replace";let O=M&&this.#t(M)?M.__staleWhileFetching:M;O!==void 0&&(v.oldValue=O)}}else v&&(v.set="update")}if(k!==0&&!this.#d&&this.#L(),this.#d&&(x||this.#N(I,k,m),v&&this.#x(v,I)),!w&&this.#u&&this.#s){let M=this.#s,O;for(;O=M?.shift();)this.#m?.(...O)}return this}pop(){try{for(;this.#i;){let f=this.#e[this.#a];if(this.#R(!0),this.#t(f)){if(f.__staleWhileFetching)return f.__staleWhileFetching}else if(f!==void 0)return f}}finally{if(this.#u&&this.#s){let f=this.#s,g;for(;g=f?.shift();)this.#m?.(...g)}}}#R(f){let g=this.#a,b=this.#r[g],k=this.#e[g];return this.#A&&this.#t(k)?k.__abortController.abort(new Error("evicted")):(this.#_||this.#u)&&(this.#_&&this.#g?.(k,b,"evict"),this.#u&&this.#s?.push([k,b,"evict"])),this.#T(g),f&&(this.#r[g]=void 0,this.#e[g]=void 0,this.#y.push(g)),this.#i===1?(this.#a=this.#o=0,this.#y.length=0):this.#a=this.#c[g],this.#n.delete(b),this.#i--,g}has(f,g={}){let{updateAgeOnHas:b=this.updateAgeOnHas,status:k}=g,m=this.#n.get(f);if(m!==void 0){let w=this.#e[m];if(this.#t(w)&&w.__staleWhileFetching===void 0)return!1;if(this.#p(m))k&&(k.has="stale",this.#x(k,m));else return b&&this.#I(m),k&&(k.has="hit",this.#x(k,m)),!0}else k&&(k.has="miss");return!1}peek(f,g={}){let{allowStale:b=this.allowStale}=g,k=this.#n.get(f);if(k===void 0||!b&&this.#p(k))return;let m=this.#e[k];return this.#t(m)?m.__staleWhileFetching:m}#j(f,g,b,k){let m=g===void 0?void 0:this.#e[g];if(this.#t(m))return m;let w=new n,{signal:E}=b;E?.addEventListener("abort",()=>w.abort(E.reason),{signal:w.signal});let v={signal:w.signal,options:b,context:k},x=(T,W=!1)=>{let{aborted:F}=w.signal,N=b.ignoreFetchAbort&&T!==void 0;if(b.status&&(F&&!W?(b.status.fetchAborted=!0,b.status.fetchError=w.signal.reason,N&&(b.status.fetchAbortIgnored=!0)):b.status.fetchResolved=!0),F&&!N&&!W)return I(w.signal.reason);let ae=O;return this.#e[g]===O&&(T===void 0?ae.__staleWhileFetching?this.#e[g]=ae.__staleWhileFetching:this.#E(f,"fetch"):(b.status&&(b.status.fetchUpdated=!0),this.set(f,T,v.options))),T},S=T=>(b.status&&(b.status.fetchRejected=!0,b.status.fetchError=T),I(T)),I=T=>{let{aborted:W}=w.signal,F=W&&b.allowStaleOnFetchAbort,N=F||b.allowStaleOnFetchRejection,ae=N||b.noDeleteOnFetchRejection,Y=O;if(this.#e[g]===O&&(!ae||Y.__staleWhileFetching===void 0?this.#E(f,"fetch"):F||(this.#e[g]=Y.__staleWhileFetching)),N)return b.status&&Y.__staleWhileFetching!==void 0&&(b.status.returnedStale=!0),Y.__staleWhileFetching;if(Y.__returned===Y)throw T},M=(T,W)=>{let F=this.#O?.(f,m,v);F&&F instanceof Promise&&F.then(N=>T(N===void 0?void 0:N),W),w.signal.addEventListener("abort",()=>{(!b.ignoreFetchAbort||b.allowStaleOnFetchAbort)&&(T(void 0),b.allowStaleOnFetchAbort&&(T=N=>x(N,!0)))})};b.status&&(b.status.fetchDispatched=!0);let O=new Promise(M).then(x,S),B=Object.assign(O,{__abortController:w,__staleWhileFetching:m,__returned:void 0});return g===void 0?(this.set(f,B,{...v.options,status:void 0}),g=this.#n.get(f)):this.#e[g]=B,B}#t(f){if(!this.#A)return!1;let g=f;return!!g&&g instanceof Promise&&g.hasOwnProperty("__staleWhileFetching")&&g.__abortController instanceof n}async fetch(f,g={}){let{allowStale:b=this.allowStale,updateAgeOnGet:k=this.updateAgeOnGet,noDeleteOnStaleGet:m=this.noDeleteOnStaleGet,ttl:w=this.ttl,noDisposeOnSet:E=this.noDisposeOnSet,size:v=0,sizeCalculation:x=this.sizeCalculation,noUpdateTTL:S=this.noUpdateTTL,noDeleteOnFetchRejection:I=this.noDeleteOnFetchRejection,allowStaleOnFetchRejection:M=this.allowStaleOnFetchRejection,ignoreFetchAbort:O=this.ignoreFetchAbort,allowStaleOnFetchAbort:B=this.allowStaleOnFetchAbort,context:T,forceRefresh:W=!1,status:F,signal:N}=g;if(!this.#A)return F&&(F.fetch="get"),this.get(f,{allowStale:b,updateAgeOnGet:k,noDeleteOnStaleGet:m,status:F});let ae={allowStale:b,updateAgeOnGet:k,noDeleteOnStaleGet:m,ttl:w,noDisposeOnSet:E,size:v,sizeCalculation:x,noUpdateTTL:S,noDeleteOnFetchRejection:I,allowStaleOnFetchRejection:M,allowStaleOnFetchAbort:B,ignoreFetchAbort:O,status:F,signal:N},Y=this.#n.get(f);if(Y===void 0){F&&(F.fetch="miss");let K=this.#j(f,Y,ae,T);return K.__returned=K}else{let K=this.#e[Y];if(this.#t(K)){let P=b&&K.__staleWhileFetching!==void 0;return F&&(F.fetch="inflight",P&&(F.returnedStale=!0)),P?K.__staleWhileFetching:K.__returned=K}let re=this.#p(Y);if(!W&&!re)return F&&(F.fetch="hit"),this.#C(Y),k&&this.#I(Y),F&&this.#x(F,Y),K;let D=this.#j(f,Y,ae,T),Z=D.__staleWhileFetching!==void 0&&b;return F&&(F.fetch=re?"stale":"refresh",Z&&re&&(F.returnedStale=!0)),Z?D.__staleWhileFetching:D.__returned=D}}async forceFetch(f,g={}){let b=await this.fetch(f,g);if(b===void 0)throw new Error("fetch() returned undefined");return b}memo(f,g={}){let b=this.#P;if(!b)throw new Error("no memoMethod provided to constructor");let{context:k,forceRefresh:m,...w}=g,E=this.get(f,w);if(!m&&E!==void 0)return E;let v=b(f,E,{options:w,context:k});return this.set(f,v,w),v}get(f,g={}){let{allowStale:b=this.allowStale,updateAgeOnGet:k=this.updateAgeOnGet,noDeleteOnStaleGet:m=this.noDeleteOnStaleGet,status:w}=g,E=this.#n.get(f);if(E!==void 0){let v=this.#e[E],x=this.#t(v);return w&&this.#x(w,E),this.#p(E)?(w&&(w.get="stale"),x?(w&&b&&v.__staleWhileFetching!==void 0&&(w.returnedStale=!0),b?v.__staleWhileFetching:void 0):(m||this.#E(f,"expire"),w&&b&&(w.returnedStale=!0),b?v:void 0)):(w&&(w.get="hit"),x?v.__staleWhileFetching:(this.#C(E),k&&this.#I(E),v))}else w&&(w.get="miss")}#F(f,g){this.#f[g]=f,this.#c[f]=g}#C(f){f!==this.#o&&(f===this.#a?this.#a=this.#c[f]:this.#F(this.#f[f],this.#c[f]),this.#F(this.#o,f),this.#o=f)}delete(f){return this.#E(f,"delete")}#E(f,g){let b=!1;if(this.#i!==0){let k=this.#n.get(f);if(k!==void 0)if(b=!0,this.#i===1)this.#D(g);else{this.#T(k);let m=this.#e[k];if(this.#t(m)?m.__abortController.abort(new Error("deleted")):(this.#_||this.#u)&&(this.#_&&this.#g?.(m,f,g),this.#u&&this.#s?.push([m,f,g])),this.#n.delete(f),this.#r[k]=void 0,this.#e[k]=void 0,k===this.#o)this.#o=this.#f[k];else if(k===this.#a)this.#a=this.#c[k];else{let w=this.#f[k];this.#c[w]=this.#c[k];let E=this.#c[k];this.#f[E]=this.#f[k]}this.#i--,this.#y.push(k)}}if(this.#u&&this.#s?.length){let k=this.#s,m;for(;m=k?.shift();)this.#m?.(...m)}return b}clear(){return this.#D("delete")}#D(f){for(let g of this.#S({allowStale:!0})){let b=this.#e[g];if(this.#t(b))b.__abortController.abort(new Error("deleted"));else{let k=this.#r[g];this.#_&&this.#g?.(b,k,f),this.#u&&this.#s?.push([b,k,f])}}if(this.#n.clear(),this.#e.fill(void 0),this.#r.fill(void 0),this.#d&&this.#w&&(this.#d.fill(0),this.#w.fill(0)),this.#v&&this.#v.fill(0),this.#a=0,this.#o=0,this.#y.length=0,this.#b=0,this.#i=0,this.#u&&this.#s){let g=this.#s,b;for(;b=g?.shift();)this.#m?.(...b)}}};c.LRUCache=p}),ct=pe(c=>{le(),ue(),ce(),Object.defineProperty(c,"t",{value:!0}),c.ContainerIterator=c.Container=c.Base=void 0;var e=class{constructor(a=0){this.iteratorType=a}equals(a){return this.o===a.o}};c.ContainerIterator=e;var t=class{constructor(){this.i=0}get length(){return this.i}size(){return this.i}empty(){return this.i===0}};c.Base=t;var r=class extends t{};c.Container=r}),jc=pe(c=>{le(),ue(),ce(),Object.defineProperty(c,"t",{value:!0}),c.default=void 0;var e=ct(),t=class extends e.Base{constructor(a=[]){super(),this.S=[];let n=this;a.forEach(function(i){n.push(i)})}clear(){this.i=0,this.S=[]}push(a){return this.S.push(a),this.i+=1,this.i}pop(){if(this.i!==0)return this.i-=1,this.S.pop()}top(){return this.S[this.i-1]}},r=t;c.default=r}),Lc=pe(c=>{le(),ue(),ce(),Object.defineProperty(c,"t",{value:!0}),c.default=void 0;var e=ct(),t=class extends e.Base{constructor(a=[]){super(),this.j=0,this.q=[];let n=this;a.forEach(function(i){n.push(i)})}clear(){this.q=[],this.i=this.j=0}push(a){let n=this.q.length;if(this.j/n>.5&&this.j+this.i>=n&&n>4096){let i=this.i;for(let s=0;s<i;++s)this.q[s]=this.q[this.j+s];this.j=0,this.q[this.i]=a}else this.q[this.j+this.i]=a;return++this.i}pop(){if(this.i===0)return;let a=this.q[this.j++];return this.i-=1,a}front(){if(this.i!==0)return this.q[this.j]}},r=t;c.default=r}),Nc=pe(c=>{le(),ue(),ce(),Object.defineProperty(c,"t",{value:!0}),c.default=void 0;var e=ct(),t=class extends e.Base{constructor(a=[],n=function(s,o){return s>o?-1:s<o?1:0},i=!0){if(super(),this.v=n,Array.isArray(a))this.C=i?[...a]:a;else{this.C=[];let o=this;a.forEach(function(l){o.C.push(l)})}this.i=this.C.length;let s=this.i>>1;for(let o=this.i-1>>1;o>=0;--o)this.k(o,s)}m(a){let n=this.C[a];for(;a>0;){let i=a-1>>1,s=this.C[i];if(this.v(s,n)<=0)break;this.C[a]=s,a=i}this.C[a]=n}k(a,n){let i=this.C[a];for(;a<n;){let s=a<<1|1,o=s+1,l=this.C[s];if(o<this.i&&this.v(l,this.C[o])>0&&(s=o,l=this.C[o]),this.v(l,i)>=0)break;this.C[a]=l,a=s}this.C[a]=i}clear(){this.i=0,this.C.length=0}push(a){this.C.push(a),this.m(this.i),this.i+=1}pop(){if(this.i===0)return;let a=this.C[0],n=this.C.pop();return this.i-=1,this.i&&(this.C[0]=n,this.k(0,this.i>>1)),a}top(){return this.C[0]}find(a){return this.C.indexOf(a)>=0}remove(a){let n=this.C.indexOf(a);return n<0?!1:(n===0?this.pop():n===this.i-1?(this.C.pop(),this.i-=1):(this.C.splice(n,1,this.C.pop()),this.i-=1,this.m(n),this.k(n,this.i>>1)),!0)}updateItem(a){let n=this.C.indexOf(a);return n<0?!1:(this.m(n),this.k(n,this.i>>1),!0)}toArray(){return[...this.C]}},r=t;c.default=r}),ii=pe(c=>{le(),ue(),ce(),Object.defineProperty(c,"t",{value:!0}),c.default=void 0;var e=ct(),t=class extends e.Container{},r=t;c.default=r}),ut=pe(c=>{le(),ue(),ce(),Object.defineProperty(c,"t",{value:!0}),c.throwIteratorAccessError=e;function e(){throw new RangeError("Iterator access denied!")}}),es=pe(c=>{le(),ue(),ce(),Object.defineProperty(c,"t",{value:!0}),c.RandomIterator=void 0;var e=ct(),t=ut(),r=class extends e.ContainerIterator{constructor(a,n){super(n),this.o=a,this.iteratorType===0?(this.pre=function(){return this.o===0&&(0,t.throwIteratorAccessError)(),this.o-=1,this},this.next=function(){return this.o===this.container.size()&&(0,t.throwIteratorAccessError)(),this.o+=1,this}):(this.pre=function(){return this.o===this.container.size()-1&&(0,t.throwIteratorAccessError)(),this.o+=1,this},this.next=function(){return this.o===-1&&(0,t.throwIteratorAccessError)(),this.o-=1,this})}get pointer(){return this.container.getElementByPos(this.o)}set pointer(a){this.container.setElementByPos(this.o,a)}};c.RandomIterator=r}),Uc=pe(c=>{le(),ue(),ce(),Object.defineProperty(c,"t",{value:!0}),c.default=void 0;var e=r(ii()),t=es();function r(s){return s&&s.t?s:{default:s}}var a=class Bl extends t.RandomIterator{constructor(o,l,u){super(o,u),this.container=l}copy(){return new Bl(this.o,this.container,this.iteratorType)}},n=class extends e.default{constructor(s=[],o=!0){if(super(),Array.isArray(s))this.J=o?[...s]:s,this.i=s.length;else{this.J=[];let l=this;s.forEach(function(u){l.pushBack(u)})}}clear(){this.i=0,this.J.length=0}begin(){return new a(0,this)}end(){return new a(this.i,this)}rBegin(){return new a(this.i-1,this,1)}rEnd(){return new a(-1,this,1)}front(){return this.J[0]}back(){return this.J[this.i-1]}getElementByPos(s){if(s<0||s>this.i-1)throw new RangeError;return this.J[s]}eraseElementByPos(s){if(s<0||s>this.i-1)throw new RangeError;return this.J.splice(s,1),this.i-=1,this.i}eraseElementByValue(s){let o=0;for(let l=0;l<this.i;++l)this.J[l]!==s&&(this.J[o++]=this.J[l]);return this.i=this.J.length=o,this.i}eraseElementByIterator(s){let o=s.o;return s=s.next(),this.eraseElementByPos(o),s}pushBack(s){return this.J.push(s),this.i+=1,this.i}popBack(){if(this.i!==0)return this.i-=1,this.J.pop()}setElementByPos(s,o){if(s<0||s>this.i-1)throw new RangeError;this.J[s]=o}insert(s,o,l=1){if(s<0||s>this.i)throw new RangeError;return this.J.splice(s,0,...new Array(l).fill(o)),this.i+=l,this.i}find(s){for(let o=0;o<this.i;++o)if(this.J[o]===s)return new a(o,this);return this.end()}reverse(){this.J.reverse()}unique(){let s=1;for(let o=1;o<this.i;++o)this.J[o]!==this.J[o-1]&&(this.J[s++]=this.J[o]);return this.i=this.J.length=s,this.i}sort(s){this.J.sort(s)}forEach(s){for(let o=0;o<this.i;++o)s(this.J[o],o,this)}[Symbol.iterator](){return(function*(){yield*this.J}).bind(this)()}},i=n;c.default=i}),Bc=pe(c=>{le(),ue(),ce(),Object.defineProperty(c,"t",{value:!0}),c.default=void 0;var e=a(ii()),t=ct(),r=ut();function a(o){return o&&o.t?o:{default:o}}var n=class Fl extends t.ContainerIterator{constructor(l,u,d,p){super(p),this.o=l,this.h=u,this.container=d,this.iteratorType===0?(this.pre=function(){return this.o.L===this.h&&(0,r.throwIteratorAccessError)(),this.o=this.o.L,this},this.next=function(){return this.o===this.h&&(0,r.throwIteratorAccessError)(),this.o=this.o.B,this}):(this.pre=function(){return this.o.B===this.h&&(0,r.throwIteratorAccessError)(),this.o=this.o.B,this},this.next=function(){return this.o===this.h&&(0,r.throwIteratorAccessError)(),this.o=this.o.L,this})}get pointer(){return this.o===this.h&&(0,r.throwIteratorAccessError)(),this.o.l}set pointer(l){this.o===this.h&&(0,r.throwIteratorAccessError)(),this.o.l=l}copy(){return new Fl(this.o,this.h,this.container,this.iteratorType)}},i=class extends e.default{constructor(o=[]){super(),this.h={},this.p=this._=this.h.L=this.h.B=this.h;let l=this;o.forEach(function(u){l.pushBack(u)})}V(o){let{L:l,B:u}=o;l.B=u,u.L=l,o===this.p&&(this.p=u),o===this._&&(this._=l),this.i-=1}G(o,l){let u=l.B,d={l:o,L:l,B:u};l.B=d,u.L=d,l===this.h&&(this.p=d),u===this.h&&(this._=d),this.i+=1}clear(){this.i=0,this.p=this._=this.h.L=this.h.B=this.h}begin(){return new n(this.p,this.h,this)}end(){return new n(this.h,this.h,this)}rBegin(){return new n(this._,this.h,this,1)}rEnd(){return new n(this.h,this.h,this,1)}front(){return this.p.l}back(){return this._.l}getElementByPos(o){if(o<0||o>this.i-1)throw new RangeError;let l=this.p;for(;o--;)l=l.B;return l.l}eraseElementByPos(o){if(o<0||o>this.i-1)throw new RangeError;let l=this.p;for(;o--;)l=l.B;return this.V(l),this.i}eraseElementByValue(o){let l=this.p;for(;l!==this.h;)l.l===o&&this.V(l),l=l.B;return this.i}eraseElementByIterator(o){let l=o.o;return l===this.h&&(0,r.throwIteratorAccessError)(),o=o.next(),this.V(l),o}pushBack(o){return this.G(o,this._),this.i}popBack(){if(this.i===0)return;let o=this._.l;return this.V(this._),o}pushFront(o){return this.G(o,this.h),this.i}popFront(){if(this.i===0)return;let o=this.p.l;return this.V(this.p),o}setElementByPos(o,l){if(o<0||o>this.i-1)throw new RangeError;let u=this.p;for(;o--;)u=u.B;u.l=l}insert(o,l,u=1){if(o<0||o>this.i)throw new RangeError;if(u<=0)return this.i;if(o===0)for(;u--;)this.pushFront(l);else if(o===this.i)for(;u--;)this.pushBack(l);else{let d=this.p;for(let y=1;y<o;++y)d=d.B;let p=d.B;for(this.i+=u;u--;)d.B={l,L:d},d.B.L=d,d=d.B;d.B=p,p.L=d}return this.i}find(o){let l=this.p;for(;l!==this.h;){if(l.l===o)return new n(l,this.h,this);l=l.B}return this.end()}reverse(){if(this.i<=1)return;let o=this.p,l=this._,u=0;for(;u<<1<this.i;){let d=o.l;o.l=l.l,l.l=d,o=o.B,l=l.L,u+=1}}unique(){if(this.i<=1)return this.i;let o=this.p;for(;o!==this.h;){let l=o;for(;l.B!==this.h&&l.l===l.B.l;)l=l.B,this.i-=1;o.B=l.B,o.B.L=o,o=o.B}return this.i}sort(o){if(this.i<=1)return;let l=[];this.forEach(function(d){l.push(d)}),l.sort(o);let u=this.p;l.forEach(function(d){u.l=d,u=u.B})}merge(o){let l=this;if(this.i===0)o.forEach(function(u){l.pushBack(u)});else{let u=this.p;o.forEach(function(d){for(;u!==l.h&&u.l<=d;)u=u.B;l.G(d,u.L)})}return this.i}forEach(o){let l=this.p,u=0;for(;l!==this.h;)o(l.l,u++,this),l=l.B}[Symbol.iterator](){return(function*(){if(this.i===0)return;let o=this.p;for(;o!==this.h;)yield o.l,o=o.B}).bind(this)()}},s=i;c.default=s}),Fc=pe(c=>{le(),ue(),ce(),Object.defineProperty(c,"t",{value:!0}),c.default=void 0;var e=r(ii()),t=es();function r(s){return s&&s.t?s:{default:s}}var a=class Dl extends t.RandomIterator{constructor(o,l,u){super(o,u),this.container=l}copy(){return new Dl(this.o,this.container,this.iteratorType)}},n=class extends e.default{constructor(s=[],o=4096){super(),this.j=0,this.D=0,this.R=0,this.N=0,this.P=0,this.A=[];let l=(()=>{if(typeof s.length=="number")return s.length;if(typeof s.size=="number")return s.size;if(typeof s.size=="function")return s.size();throw new TypeError("Cannot get the length or size of the container")})();this.F=o,this.P=Math.max(Math.ceil(l/this.F),1);for(let p=0;p<this.P;++p)this.A.push(new Array(this.F));let u=Math.ceil(l/this.F);this.j=this.R=(this.P>>1)-(u>>1),this.D=this.N=this.F-l%this.F>>1;let d=this;s.forEach(function(p){d.pushBack(p)})}T(){let s=[],o=Math.max(this.P>>1,1);for(let l=0;l<o;++l)s[l]=new Array(this.F);for(let l=this.j;l<this.P;++l)s[s.length]=this.A[l];for(let l=0;l<this.R;++l)s[s.length]=this.A[l];s[s.length]=[...this.A[this.R]],this.j=o,this.R=s.length-1;for(let l=0;l<o;++l)s[s.length]=new Array(this.F);this.A=s,this.P=s.length}O(s){let o=this.D+s+1,l=o%this.F,u=l-1,d=this.j+(o-l)/this.F;return l===0&&(d-=1),d%=this.P,u<0&&(u+=this.F),{curNodeBucketIndex:d,curNodePointerIndex:u}}clear(){this.A=[new Array(this.F)],this.P=1,this.j=this.R=this.i=0,this.D=this.N=this.F>>1}begin(){return new a(0,this)}end(){return new a(this.i,this)}rBegin(){return new a(this.i-1,this,1)}rEnd(){return new a(-1,this,1)}front(){if(this.i!==0)return this.A[this.j][this.D]}back(){if(this.i!==0)return this.A[this.R][this.N]}pushBack(s){return this.i&&(this.N<this.F-1?this.N+=1:this.R<this.P-1?(this.R+=1,this.N=0):(this.R=0,this.N=0),this.R===this.j&&this.N===this.D&&this.T()),this.i+=1,this.A[this.R][this.N]=s,this.i}popBack(){if(this.i===0)return;let s=this.A[this.R][this.N];return this.i!==1&&(this.N>0?this.N-=1:this.R>0?(this.R-=1,this.N=this.F-1):(this.R=this.P-1,this.N=this.F-1)),this.i-=1,s}pushFront(s){return this.i&&(this.D>0?this.D-=1:this.j>0?(this.j-=1,this.D=this.F-1):(this.j=this.P-1,this.D=this.F-1),this.j===this.R&&this.D===this.N&&this.T()),this.i+=1,this.A[this.j][this.D]=s,this.i}popFront(){if(this.i===0)return;let s=this.A[this.j][this.D];return this.i!==1&&(this.D<this.F-1?this.D+=1:this.j<this.P-1?(this.j+=1,this.D=0):(this.j=0,this.D=0)),this.i-=1,s}getElementByPos(s){if(s<0||s>this.i-1)throw new RangeError;let{curNodeBucketIndex:o,curNodePointerIndex:l}=this.O(s);return this.A[o][l]}setElementByPos(s,o){if(s<0||s>this.i-1)throw new RangeError;let{curNodeBucketIndex:l,curNodePointerIndex:u}=this.O(s);this.A[l][u]=o}insert(s,o,l=1){if(s<0||s>this.i)throw new RangeError;if(s===0)for(;l--;)this.pushFront(o);else if(s===this.i)for(;l--;)this.pushBack(o);else{let u=[];for(let d=s;d<this.i;++d)u.push(this.getElementByPos(d));this.cut(s-1);for(let d=0;d<l;++d)this.pushBack(o);for(let d=0;d<u.length;++d)this.pushBack(u[d])}return this.i}cut(s){if(s<0)return this.clear(),0;let{curNodeBucketIndex:o,curNodePointerIndex:l}=this.O(s);return this.R=o,this.N=l,this.i=s+1,this.i}eraseElementByPos(s){if(s<0||s>this.i-1)throw new RangeError;if(s===0)this.popFront();else if(s===this.i-1)this.popBack();else{let o=[];for(let u=s+1;u<this.i;++u)o.push(this.getElementByPos(u));this.cut(s),this.popBack();let l=this;o.forEach(function(u){l.pushBack(u)})}return this.i}eraseElementByValue(s){if(this.i===0)return 0;let o=[];for(let u=0;u<this.i;++u){let d=this.getElementByPos(u);d!==s&&o.push(d)}let l=o.length;for(let u=0;u<l;++u)this.setElementByPos(u,o[u]);return this.cut(l-1)}eraseElementByIterator(s){let o=s.o;return this.eraseElementByPos(o),s=s.next(),s}find(s){for(let o=0;o<this.i;++o)if(this.getElementByPos(o)===s)return new a(o,this);return this.end()}reverse(){let s=0,o=this.i-1;for(;s<o;){let l=this.getElementByPos(s);this.setElementByPos(s,this.getElementByPos(o)),this.setElementByPos(o,l),s+=1,o-=1}}unique(){if(this.i<=1)return this.i;let s=1,o=this.getElementByPos(0);for(let l=1;l<this.i;++l){let u=this.getElementByPos(l);u!==o&&(o=u,this.setElementByPos(s++,u))}for(;this.i>s;)this.popBack();return this.i}sort(s){let o=[];for(let l=0;l<this.i;++l)o.push(this.getElementByPos(l));o.sort(s);for(let l=0;l<this.i;++l)this.setElementByPos(l,o[l])}shrinkToFit(){if(this.i===0)return;let s=[];this.forEach(function(o){s.push(o)}),this.P=Math.max(Math.ceil(this.i/this.F),1),this.i=this.j=this.R=this.D=this.N=0,this.A=[];for(let o=0;o<this.P;++o)this.A.push(new Array(this.F));for(let o=0;o<s.length;++o)this.pushBack(s[o])}forEach(s){for(let o=0;o<this.i;++o)s(this.getElementByPos(o),o,this)}[Symbol.iterator](){return(function*(){for(let s=0;s<this.i;++s)yield this.getElementByPos(s)}).bind(this)()}},i=n;c.default=i}),Dc=pe(c=>{le(),ue(),ce(),Object.defineProperty(c,"t",{value:!0}),c.TreeNodeEnableIndex=c.TreeNode=void 0;var e=class{constructor(r,a){this.ee=1,this.u=void 0,this.l=void 0,this.U=void 0,this.W=void 0,this.tt=void 0,this.u=r,this.l=a}L(){let r=this;if(r.ee===1&&r.tt.tt===r)r=r.W;else if(r.U)for(r=r.U;r.W;)r=r.W;else{let a=r.tt;for(;a.U===r;)r=a,a=r.tt;r=a}return r}B(){let r=this;if(r.W){for(r=r.W;r.U;)r=r.U;return r}else{let a=r.tt;for(;a.W===r;)r=a,a=r.tt;return r.W!==a?a:r}}te(){let r=this.tt,a=this.W,n=a.U;return r.tt===this?r.tt=a:r.U===this?r.U=a:r.W=a,a.tt=r,a.U=this,this.tt=a,this.W=n,n&&(n.tt=this),a}se(){let r=this.tt,a=this.U,n=a.W;return r.tt===this?r.tt=a:r.U===this?r.U=a:r.W=a,a.tt=r,a.W=this,this.tt=a,this.U=n,n&&(n.tt=this),a}};c.TreeNode=e;var t=class extends e{constructor(){super(...arguments),this.rt=1}te(){let r=super.te();return this.ie(),r.ie(),r}se(){let r=super.se();return this.ie(),r.ie(),r}ie(){this.rt=1,this.U&&(this.rt+=this.U.rt),this.W&&(this.rt+=this.W.rt)}};c.TreeNodeEnableIndex=t}),ts=pe(c=>{le(),ue(),ce(),Object.defineProperty(c,"t",{value:!0}),c.default=void 0;var e=Dc(),t=ct(),r=ut(),a=class extends t.Container{constructor(i=function(o,l){return o<l?-1:o>l?1:0},s=!1){super(),this.Y=void 0,this.v=i,s?(this.re=e.TreeNodeEnableIndex,this.M=function(o,l,u){let d=this.ne(o,l,u);if(d){let p=d.tt;for(;p!==this.h;)p.rt+=1,p=p.tt;let y=this.he(d);if(y){let{parentNode:f,grandParent:g,curNode:b}=y;f.ie(),g.ie(),b.ie()}}return this.i},this.V=function(o){let l=this.fe(o);for(;l!==this.h;)l.rt-=1,l=l.tt}):(this.re=e.TreeNode,this.M=function(o,l,u){let d=this.ne(o,l,u);return d&&this.he(d),this.i},this.V=this.fe),this.h=new this.re}X(i,s){let o=this.h;for(;i;){let l=this.v(i.u,s);if(l<0)i=i.W;else if(l>0)o=i,i=i.U;else return i}return o}Z(i,s){let o=this.h;for(;i;)this.v(i.u,s)<=0?i=i.W:(o=i,i=i.U);return o}$(i,s){let o=this.h;for(;i;){let l=this.v(i.u,s);if(l<0)o=i,i=i.W;else if(l>0)i=i.U;else return i}return o}rr(i,s){let o=this.h;for(;i;)this.v(i.u,s)<0?(o=i,i=i.W):i=i.U;return o}ue(i){for(;;){let s=i.tt;if(s===this.h)return;if(i.ee===1){i.ee=0;return}if(i===s.U){let o=s.W;if(o.ee===1)o.ee=0,s.ee=1,s===this.Y?this.Y=s.te():s.te();else if(o.W&&o.W.ee===1){o.ee=s.ee,s.ee=0,o.W.ee=0,s===this.Y?this.Y=s.te():s.te();return}else o.U&&o.U.ee===1?(o.ee=1,o.U.ee=0,o.se()):(o.ee=1,i=s)}else{let o=s.U;if(o.ee===1)o.ee=0,s.ee=1,s===this.Y?this.Y=s.se():s.se();else if(o.U&&o.U.ee===1){o.ee=s.ee,s.ee=0,o.U.ee=0,s===this.Y?this.Y=s.se():s.se();return}else o.W&&o.W.ee===1?(o.ee=1,o.W.ee=0,o.te()):(o.ee=1,i=s)}}}fe(i){if(this.i===1)return this.clear(),this.h;let s=i;for(;s.U||s.W;){if(s.W)for(s=s.W;s.U;)s=s.U;else s=s.U;[i.u,s.u]=[s.u,i.u],[i.l,s.l]=[s.l,i.l],i=s}this.h.U===s?this.h.U=s.tt:this.h.W===s&&(this.h.W=s.tt),this.ue(s);let o=s.tt;return s===o.U?o.U=void 0:o.W=void 0,this.i-=1,this.Y.ee=0,o}oe(i,s){return i===void 0?!1:this.oe(i.U,s)||s(i)?!0:this.oe(i.W,s)}he(i){for(;;){let s=i.tt;if(s.ee===0)return;let o=s.tt;if(s===o.U){let l=o.W;if(l&&l.ee===1){if(l.ee=s.ee=0,o===this.Y)return;o.ee=1,i=o;continue}else if(i===s.W){if(i.ee=0,i.U&&(i.U.tt=s),i.W&&(i.W.tt=o),s.W=i.U,o.U=i.W,i.U=s,i.W=o,o===this.Y)this.Y=i,this.h.tt=i;else{let u=o.tt;u.U===o?u.U=i:u.W=i}return i.tt=o.tt,s.tt=i,o.tt=i,o.ee=1,{parentNode:s,grandParent:o,curNode:i}}else s.ee=0,o===this.Y?this.Y=o.se():o.se(),o.ee=1}else{let l=o.U;if(l&&l.ee===1){if(l.ee=s.ee=0,o===this.Y)return;o.ee=1,i=o;continue}else if(i===s.U){if(i.ee=0,i.U&&(i.U.tt=o),i.W&&(i.W.tt=s),o.W=i.U,s.U=i.W,i.U=o,i.W=s,o===this.Y)this.Y=i,this.h.tt=i;else{let u=o.tt;u.U===o?u.U=i:u.W=i}return i.tt=o.tt,s.tt=i,o.tt=i,o.ee=1,{parentNode:s,grandParent:o,curNode:i}}else s.ee=0,o===this.Y?this.Y=o.te():o.te(),o.ee=1}return}}ne(i,s,o){if(this.Y===void 0){this.i+=1,this.Y=new this.re(i,s),this.Y.ee=0,this.Y.tt=this.h,this.h.tt=this.Y,this.h.U=this.Y,this.h.W=this.Y;return}let l,u=this.h.U,d=this.v(u.u,i);if(d===0){u.l=s;return}else if(d>0)u.U=new this.re(i,s),u.U.tt=u,l=u.U,this.h.U=l;else{let p=this.h.W,y=this.v(p.u,i);if(y===0){p.l=s;return}else if(y<0)p.W=new this.re(i,s),p.W.tt=p,l=p.W,this.h.W=l;else{if(o!==void 0){let f=o.o;if(f!==this.h){let g=this.v(f.u,i);if(g===0){f.l=s;return}else if(g>0){let b=f.L(),k=this.v(b.u,i);if(k===0){b.l=s;return}else k<0&&(l=new this.re(i,s),b.W===void 0?(b.W=l,l.tt=b):(f.U=l,l.tt=f))}}}if(l===void 0)for(l=this.Y;;){let f=this.v(l.u,i);if(f>0){if(l.U===void 0){l.U=new this.re(i,s),l.U.tt=l,l=l.U;break}l=l.U}else if(f<0){if(l.W===void 0){l.W=new this.re(i,s),l.W.tt=l,l=l.W;break}l=l.W}else{l.l=s;return}}}}return this.i+=1,l}I(i,s){for(;i;){let o=this.v(i.u,s);if(o<0)i=i.W;else if(o>0)i=i.U;else return i}return i||this.h}clear(){this.i=0,this.Y=void 0,this.h.tt=void 0,this.h.U=this.h.W=void 0}updateKeyByIterator(i,s){let o=i.o;if(o===this.h&&(0,r.throwIteratorAccessError)(),this.i===1)return o.u=s,!0;if(o===this.h.U)return this.v(o.B().u,s)>0?(o.u=s,!0):!1;if(o===this.h.W)return this.v(o.L().u,s)<0?(o.u=s,!0):!1;let l=o.L().u;if(this.v(l,s)>=0)return!1;let u=o.B().u;return this.v(u,s)<=0?!1:(o.u=s,!0)}eraseElementByPos(i){if(i<0||i>this.i-1)throw new RangeError;let s=0,o=this;return this.oe(this.Y,function(l){return i===s?(o.V(l),!0):(s+=1,!1)}),this.i}eraseElementByKey(i){if(this.i===0)return!1;let s=this.I(this.Y,i);return s===this.h?!1:(this.V(s),!0)}eraseElementByIterator(i){let s=i.o;s===this.h&&(0,r.throwIteratorAccessError)();let o=s.W===void 0;return i.iteratorType===0?o&&i.next():(!o||s.U===void 0)&&i.next(),this.V(s),i}forEach(i){let s=0;for(let o of this)i(o,s++,this)}getElementByPos(i){if(i<0||i>this.i-1)throw new RangeError;let s,o=0;for(let l of this){if(o===i){s=l;break}o+=1}return s}getHeight(){if(this.i===0)return 0;let i=function(s){return s?Math.max(i(s.U),i(s.W))+1:0};return i(this.Y)}},n=a;c.default=n}),rs=pe(c=>{le(),ue(),ce(),Object.defineProperty(c,"t",{value:!0}),c.default=void 0;var e=ct(),t=ut(),r=class extends e.ContainerIterator{constructor(n,i,s){super(s),this.o=n,this.h=i,this.iteratorType===0?(this.pre=function(){return this.o===this.h.U&&(0,t.throwIteratorAccessError)(),this.o=this.o.L(),this},this.next=function(){return this.o===this.h&&(0,t.throwIteratorAccessError)(),this.o=this.o.B(),this}):(this.pre=function(){return this.o===this.h.W&&(0,t.throwIteratorAccessError)(),this.o=this.o.B(),this},this.next=function(){return this.o===this.h&&(0,t.throwIteratorAccessError)(),this.o=this.o.L(),this})}get index(){let n=this.o,i=this.h.tt;if(n===this.h)return i?i.rt-1:0;let s=0;for(n.U&&(s+=n.U.rt);n!==i;){let o=n.tt;n===o.W&&(s+=1,o.U&&(s+=o.U.rt)),n=o}return s}},a=r;c.default=a}),$c=pe(c=>{le(),ue(),ce(),Object.defineProperty(c,"t",{value:!0}),c.default=void 0;var e=a(ts()),t=a(rs()),r=ut();function a(o){return o&&o.t?o:{default:o}}var n=class $l extends t.default{constructor(l,u,d,p){super(l,u,p),this.container=d}get pointer(){return this.o===this.h&&(0,r.throwIteratorAccessError)(),this.o.u}copy(){return new $l(this.o,this.h,this.container,this.iteratorType)}},i=class extends e.default{constructor(o=[],l,u){super(l,u);let d=this;o.forEach(function(p){d.insert(p)})}*K(o){o!==void 0&&(yield*this.K(o.U),yield o.u,yield*this.K(o.W))}begin(){return new n(this.h.U||this.h,this.h,this)}end(){return new n(this.h,this.h,this)}rBegin(){return new n(this.h.W||this.h,this.h,this,1)}rEnd(){return new n(this.h,this.h,this,1)}front(){return this.h.U?this.h.U.u:void 0}back(){return this.h.W?this.h.W.u:void 0}insert(o,l){return this.M(o,void 0,l)}find(o){let l=this.I(this.Y,o);return new n(l,this.h,this)}lowerBound(o){let l=this.X(this.Y,o);return new n(l,this.h,this)}upperBound(o){let l=this.Z(this.Y,o);return new n(l,this.h,this)}reverseLowerBound(o){let l=this.$(this.Y,o);return new n(l,this.h,this)}reverseUpperBound(o){let l=this.rr(this.Y,o);return new n(l,this.h,this)}union(o){let l=this;return o.forEach(function(u){l.insert(u)}),this.i}[Symbol.iterator](){return this.K(this.Y)}},s=i;c.default=s}),Wc=pe(c=>{le(),ue(),ce(),Object.defineProperty(c,"t",{value:!0}),c.default=void 0;var e=a(ts()),t=a(rs()),r=ut();function a(o){return o&&o.t?o:{default:o}}var n=class Wl extends t.default{constructor(l,u,d,p){super(l,u,p),this.container=d}get pointer(){this.o===this.h&&(0,r.throwIteratorAccessError)();let l=this;return new Proxy([],{get(u,d){if(d==="0")return l.o.u;if(d==="1")return l.o.l},set(u,d,p){if(d!=="1")throw new TypeError("props must be 1");return l.o.l=p,!0}})}copy(){return new Wl(this.o,this.h,this.container,this.iteratorType)}},i=class extends e.default{constructor(o=[],l,u){super(l,u);let d=this;o.forEach(function(p){d.setElement(p[0],p[1])})}*K(o){o!==void 0&&(yield*this.K(o.U),yield[o.u,o.l],yield*this.K(o.W))}begin(){return new n(this.h.U||this.h,this.h,this)}end(){return new n(this.h,this.h,this)}rBegin(){return new n(this.h.W||this.h,this.h,this,1)}rEnd(){return new n(this.h,this.h,this,1)}front(){if(this.i===0)return;let o=this.h.U;return[o.u,o.l]}back(){if(this.i===0)return;let o=this.h.W;return[o.u,o.l]}lowerBound(o){let l=this.X(this.Y,o);return new n(l,this.h,this)}upperBound(o){let l=this.Z(this.Y,o);return new n(l,this.h,this)}reverseLowerBound(o){let l=this.$(this.Y,o);return new n(l,this.h,this)}reverseUpperBound(o){let l=this.rr(this.Y,o);return new n(l,this.h,this)}setElement(o,l,u){return this.M(o,l,u)}find(o){let l=this.I(this.Y,o);return new n(l,this.h,this)}getElementByKey(o){return this.I(this.Y,o).l}union(o){let l=this;return o.forEach(function(u){l.setElement(u[0],u[1])}),this.i}[Symbol.iterator](){return this.K(this.Y)}},s=i;c.default=s}),ns=pe(c=>{le(),ue(),ce(),Object.defineProperty(c,"t",{value:!0}),c.default=e;function e(t){let r=typeof t;return r==="object"&&t!==null||r==="function"}}),is=pe(c=>{le(),ue(),ce(),Object.defineProperty(c,"t",{value:!0}),c.HashContainerIterator=c.HashContainer=void 0;var e=ct(),t=a(ns()),r=ut();function a(s){return s&&s.t?s:{default:s}}var n=class extends e.ContainerIterator{constructor(s,o,l){super(l),this.o=s,this.h=o,this.iteratorType===0?(this.pre=function(){return this.o.L===this.h&&(0,r.throwIteratorAccessError)(),this.o=this.o.L,this},this.next=function(){return this.o===this.h&&(0,r.throwIteratorAccessError)(),this.o=this.o.B,this}):(this.pre=function(){return this.o.B===this.h&&(0,r.throwIteratorAccessError)(),this.o=this.o.B,this},this.next=function(){return this.o===this.h&&(0,r.throwIteratorAccessError)(),this.o=this.o.L,this})}};c.HashContainerIterator=n;var i=class extends e.Container{constructor(){super(),this.H=[],this.g={},this.HASH_TAG=Symbol("@@HASH_TAG"),Object.setPrototypeOf(this.g,null),this.h={},this.h.L=this.h.B=this.p=this._=this.h}V(s){let{L:o,B:l}=s;o.B=l,l.L=o,s===this.p&&(this.p=l),s===this._&&(this._=o),this.i-=1}M(s,o,l){l===void 0&&(l=(0,t.default)(s));let u;if(l){let d=s[this.HASH_TAG];if(d!==void 0)return this.H[d].l=o,this.i;Object.defineProperty(s,this.HASH_TAG,{value:this.H.length,configurable:!0}),u={u:s,l:o,L:this._,B:this.h},this.H.push(u)}else{let d=this.g[s];if(d)return d.l=o,this.i;u={u:s,l:o,L:this._,B:this.h},this.g[s]=u}return this.i===0?(this.p=u,this.h.B=u):this._.B=u,this._=u,this.h.L=u,++this.i}I(s,o){if(o===void 0&&(o=(0,t.default)(s)),o){let l=s[this.HASH_TAG];return l===void 0?this.h:this.H[l]}else return this.g[s]||this.h}clear(){let s=this.HASH_TAG;this.H.forEach(function(o){delete o.u[s]}),this.H=[],this.g={},Object.setPrototypeOf(this.g,null),this.i=0,this.p=this._=this.h.L=this.h.B=this.h}eraseElementByKey(s,o){let l;if(o===void 0&&(o=(0,t.default)(s)),o){let u=s[this.HASH_TAG];if(u===void 0)return!1;delete s[this.HASH_TAG],l=this.H[u],delete this.H[u]}else{if(l=this.g[s],l===void 0)return!1;delete this.g[s]}return this.V(l),!0}eraseElementByIterator(s){let o=s.o;return o===this.h&&(0,r.throwIteratorAccessError)(),this.V(o),s.next()}eraseElementByPos(s){if(s<0||s>this.i-1)throw new RangeError;let o=this.p;for(;s--;)o=o.B;return this.V(o),this.i}};c.HashContainer=i}),qc=pe(c=>{le(),ue(),ce(),Object.defineProperty(c,"t",{value:!0}),c.default=void 0;var e=is(),t=ut(),r=class ql extends e.HashContainerIterator{constructor(s,o,l,u){super(s,o,u),this.container=l}get pointer(){return this.o===this.h&&(0,t.throwIteratorAccessError)(),this.o.u}copy(){return new ql(this.o,this.h,this.container,this.iteratorType)}},a=class extends e.HashContainer{constructor(i=[]){super();let s=this;i.forEach(function(o){s.insert(o)})}begin(){return new r(this.p,this.h,this)}end(){return new r(this.h,this.h,this)}rBegin(){return new r(this._,this.h,this,1)}rEnd(){return new r(this.h,this.h,this,1)}front(){return this.p.u}back(){return this._.u}insert(i,s){return this.M(i,void 0,s)}getElementByPos(i){if(i<0||i>this.i-1)throw new RangeError;let s=this.p;for(;i--;)s=s.B;return s.u}find(i,s){let o=this.I(i,s);return new r(o,this.h,this)}forEach(i){let s=0,o=this.p;for(;o!==this.h;)i(o.u,s++,this),o=o.B}[Symbol.iterator](){return(function*(){let i=this.p;for(;i!==this.h;)yield i.u,i=i.B}).bind(this)()}},n=a;c.default=n}),Hc=pe(c=>{le(),ue(),ce(),Object.defineProperty(c,"t",{value:!0}),c.default=void 0;var e=is(),t=a(ns()),r=ut();function a(o){return o&&o.t?o:{default:o}}var n=class Hl extends e.HashContainerIterator{constructor(l,u,d,p){super(l,u,p),this.container=d}get pointer(){this.o===this.h&&(0,r.throwIteratorAccessError)();let l=this;return new Proxy([],{get(u,d){if(d==="0")return l.o.u;if(d==="1")return l.o.l},set(u,d,p){if(d!=="1")throw new TypeError("props must be 1");return l.o.l=p,!0}})}copy(){return new Hl(this.o,this.h,this.container,this.iteratorType)}},i=class extends e.HashContainer{constructor(o=[]){super();let l=this;o.forEach(function(u){l.setElement(u[0],u[1])})}begin(){return new n(this.p,this.h,this)}end(){return new n(this.h,this.h,this)}rBegin(){return new n(this._,this.h,this,1)}rEnd(){return new n(this.h,this.h,this,1)}front(){if(this.i!==0)return[this.p.u,this.p.l]}back(){if(this.i!==0)return[this._.u,this._.l]}setElement(o,l,u){return this.M(o,l,u)}getElementByKey(o,l){if(l===void 0&&(l=(0,t.default)(o)),l){let d=o[this.HASH_TAG];return d!==void 0?this.H[d].l:void 0}let u=this.g[o];return u?u.l:void 0}getElementByPos(o){if(o<0||o>this.i-1)throw new RangeError;let l=this.p;for(;o--;)l=l.B;return[l.u,l.l]}find(o,l){let u=this.I(o,l);return new n(u,this.h,this)}forEach(o){let l=0,u=this.p;for(;u!==this.h;)o([u.u,u.l],l++,this),u=u.B}[Symbol.iterator](){return(function*(){let o=this.p;for(;o!==this.h;)yield[o.u,o.l],o=o.B}).bind(this)()}},s=i;c.default=s}),zc=pe(c=>{le(),ue(),ce(),Object.defineProperty(c,"t",{value:!0}),Object.defineProperty(c,"Deque",{enumerable:!0,get:function(){return i.default}}),Object.defineProperty(c,"HashMap",{enumerable:!0,get:function(){return u.default}}),Object.defineProperty(c,"HashSet",{enumerable:!0,get:function(){return l.default}}),Object.defineProperty(c,"LinkList",{enumerable:!0,get:function(){return n.default}}),Object.defineProperty(c,"OrderedMap",{enumerable:!0,get:function(){return o.default}}),Object.defineProperty(c,"OrderedSet",{enumerable:!0,get:function(){return s.default}}),Object.defineProperty(c,"PriorityQueue",{enumerable:!0,get:function(){return r.default}}),Object.defineProperty(c,"Queue",{enumerable:!0,get:function(){return t.default}}),Object.defineProperty(c,"Stack",{enumerable:!0,get:function(){return e.default}}),Object.defineProperty(c,"Vector",{enumerable:!0,get:function(){return a.default}});var e=d(jc()),t=d(Lc()),r=d(Nc()),a=d(Uc()),n=d(Bc()),i=d(Fc()),s=d($c()),o=d(Wc()),l=d(qc()),u=d(Hc());function d(p){return p&&p.t?p:{default:p}}}),Kc=pe((c,e)=>{le(),ue(),ce();var t=zc().OrderedSet,r=lt()("number-allocator:trace"),a=lt()("number-allocator:error");function n(s,o){this.low=s,this.high=o}n.prototype.equals=function(s){return this.low===s.low&&this.high===s.high},n.prototype.compare=function(s){return this.low<s.low&&this.high<s.low?-1:s.low<this.low&&s.high<this.low?1:0};function i(s,o){if(!(this instanceof i))return new i(s,o);this.min=s,this.max=o,this.ss=new t([],(l,u)=>l.compare(u)),r("Create"),this.clear()}i.prototype.firstVacant=function(){return this.ss.size()===0?null:this.ss.front().low},i.prototype.alloc=function(){if(this.ss.size()===0)return r("alloc():empty"),null;let s=this.ss.begin(),o=s.pointer.low,l=s.pointer.high,u=o;return u+1<=l?this.ss.updateKeyByIterator(s,new n(o+1,l)):this.ss.eraseElementByPos(0),r("alloc():"+u),u},i.prototype.use=function(s){let o=new n(s,s),l=this.ss.lowerBound(o);if(!l.equals(this.ss.end())){let u=l.pointer.low,d=l.pointer.high;return l.pointer.equals(o)?(this.ss.eraseElementByIterator(l),r("use():"+s),!0):u>s?!1:u===s?(this.ss.updateKeyByIterator(l,new n(u+1,d)),r("use():"+s),!0):d===s?(this.ss.updateKeyByIterator(l,new n(u,d-1)),r("use():"+s),!0):(this.ss.updateKeyByIterator(l,new n(s+1,d)),this.ss.insert(new n(u,s-1)),r("use():"+s),!0)}return r("use():failed"),!1},i.prototype.free=function(s){if(s<this.min||s>this.max){a("free():"+s+" is out of range");return}let o=new n(s,s),l=this.ss.upperBound(o);if(l.equals(this.ss.end())){if(l.equals(this.ss.begin())){this.ss.insert(o);return}l.pre();let u=l.pointer.high;l.pointer.high+1===s?this.ss.updateKeyByIterator(l,new n(u,s)):this.ss.insert(o)}else if(l.equals(this.ss.begin()))if(s+1===l.pointer.low){let u=l.pointer.high;this.ss.updateKeyByIterator(l,new n(s,u))}else this.ss.insert(o);else{let u=l.pointer.low,d=l.pointer.high;l.pre();let p=l.pointer.low;l.pointer.high+1===s?s+1===u?(this.ss.eraseElementByIterator(l),this.ss.updateKeyByIterator(l,new n(p,d))):this.ss.updateKeyByIterator(l,new n(p,s)):s+1===u?(this.ss.eraseElementByIterator(l.next()),this.ss.insert(new n(s,d))):this.ss.insert(o)}r("free():"+s)},i.prototype.clear=function(){r("clear()"),this.ss.clear(),this.ss.insert(new n(this.min,this.max))},i.prototype.intervalCount=function(){return this.ss.size()},i.prototype.dump=function(){console.log("length:"+this.ss.size());for(let s of this.ss)console.log(s)},e.exports=i}),os=pe((c,e)=>{le(),ue(),ce();var t=Kc();e.exports.NumberAllocator=t}),Vc=pe(c=>{le(),ue(),ce(),Object.defineProperty(c,"__esModule",{value:!0});var e=Rc(),t=os(),r=class{aliasToTopic;topicToAlias;max;numberAllocator;length;constructor(a){a>0&&(this.aliasToTopic=new e.LRUCache({max:a}),this.topicToAlias={},this.numberAllocator=new t.NumberAllocator(1,a),this.max=a,this.length=0)}put(a,n){if(n===0||n>this.max)return!1;let i=this.aliasToTopic.get(n);return i&&delete this.topicToAlias[i],this.aliasToTopic.set(n,a),this.topicToAlias[a]=n,this.numberAllocator.use(n),this.length=this.aliasToTopic.size,!0}getTopicByAlias(a){return this.aliasToTopic.get(a)}getAliasByTopic(a){let n=this.topicToAlias[a];return typeof n<"u"&&this.aliasToTopic.get(n),n}clear(){this.aliasToTopic.clear(),this.topicToAlias={},this.numberAllocator.clear(),this.length=0}getLruAlias(){return this.numberAllocator.firstVacant()||[...this.aliasToTopic.keys()][this.aliasToTopic.size-1]}};c.default=r}),Gc=pe(c=>{le(),ue(),ce();var e=c&&c.__importDefault||function(i){return i&&i.__esModule?i:{default:i}};Object.defineProperty(c,"__esModule",{value:!0});var t=sr(),r=e(Vc()),a=Rt(),n=(i,s)=>{i.log("_handleConnack");let{options:o}=i,l=o.protocolVersion===5?s.reasonCode:s.returnCode;if(clearTimeout(i.connackTimer),delete i.topicAliasSend,s.properties){if(s.properties.topicAliasMaximum){if(s.properties.topicAliasMaximum>65535){i.emit("error",new Error("topicAliasMaximum from broker is out of range"));return}s.properties.topicAliasMaximum>0&&(i.topicAliasSend=new r.default(s.properties.topicAliasMaximum))}s.properties.serverKeepAlive&&o.keepalive&&(o.keepalive=s.properties.serverKeepAlive),s.properties.maximumPacketSize&&(o.properties||(o.properties={}),o.properties.maximumPacketSize=s.properties.maximumPacketSize)}if(l===0)i.reconnecting=!1,i._onConnect(s);else if(l>0){let u=new a.ErrorWithReasonCode(`Connection refused: ${t.ReasonCodes[l]}`,l);i.emit("error",u),i.options.reconnectOnConnackError&&i._cleanUp(!0)}};c.default=n}),Yc=pe(c=>{le(),ue(),ce(),Object.defineProperty(c,"__esModule",{value:!0});var e=(t,r,a)=>{t.log("handling pubrel packet");let n=typeof a<"u"?a:t.noop,{messageId:i}=r,s={cmd:"pubcomp",messageId:i};t.incomingStore.get(r,(o,l)=>{o?t._sendPacket(s,n):(t.emit("message",l.topic,l.payload,l),t.handleMessage(l,u=>{if(u)return n(u);t.incomingStore.del(l,t.noop),t._sendPacket(s,n)}))})};c.default=e}),Qc=pe(c=>{le(),ue(),ce();var e=c&&c.__importDefault||function(o){return o&&o.__esModule?o:{default:o}};Object.defineProperty(c,"__esModule",{value:!0});var t=e(Oc()),r=e(Mc()),a=e(Gc()),n=e(sr()),i=e(Yc()),s=(o,l,u)=>{let{options:d}=o;if(d.protocolVersion===5&&d.properties&&d.properties.maximumPacketSize&&d.properties.maximumPacketSize<l.length)return o.emit("error",new Error(`exceeding packets size ${l.cmd}`)),o.end({reasonCode:149,properties:{reasonString:"Maximum packet size was exceeded"}}),o;switch(o.log("_handlePacket :: emitting packetreceive"),o.emit("packetreceive",l),l.cmd){case"publish":(0,t.default)(o,l,u);break;case"puback":case"pubrec":case"pubcomp":case"suback":case"unsuback":o.reschedulePing(),(0,n.default)(o,l),u();break;case"pubrel":o.reschedulePing(),(0,i.default)(o,l,u);break;case"connack":(0,a.default)(o,l),u();break;case"auth":o.reschedulePing(),(0,r.default)(o,l),u();break;case"pingresp":o.log("_handlePacket :: received pingresp"),o.reschedulePing(!0),u();break;case"disconnect":o.emit("disconnect",l),u();break;default:o.log("_handlePacket :: unknown command"),u();break}};c.default=s}),ss=pe(c=>{le(),ue(),ce(),Object.defineProperty(c,"__esModule",{value:!0});var e=class{nextId;constructor(){this.nextId=Math.max(1,Math.floor(Math.random()*65535))}allocate(){let t=this.nextId++;return this.nextId===65536&&(this.nextId=1),t}getLastAllocated(){return this.nextId===1?65535:this.nextId-1}register(t){return!0}deallocate(t){}clear(){}};c.default=e}),Jc=pe(c=>{le(),ue(),ce(),Object.defineProperty(c,"__esModule",{value:!0});var e=class{aliasToTopic;max;length;constructor(t){this.aliasToTopic={},this.max=t}put(t,r){return r===0||r>this.max?!1:(this.aliasToTopic[r]=t,this.length=Object.keys(this.aliasToTopic).length,!0)}getTopicByAlias(t){return this.aliasToTopic[t]}clear(){this.aliasToTopic={}}};c.default=e}),Xc=pe(c=>{le(),ue(),ce();var e=c&&c.__importDefault||function(n){return n&&n.__esModule?n:{default:n}};Object.defineProperty(c,"__esModule",{value:!0}),c.TypedEventEmitter=void 0;var t=e((kt(),Pe(pt))),r=Rt(),a=class{};c.TypedEventEmitter=a,(0,r.applyMixin)(a,t.default)}),ar=pe((c,e)=>{le(),ue(),ce();function t(r){"@babel/helpers - typeof";return e.exports=t=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(a){return typeof a}:function(a){return a&&typeof Symbol=="function"&&a.constructor===Symbol&&a!==Symbol.prototype?"symbol":typeof a},e.exports.__esModule=!0,e.exports.default=e.exports,t(r)}e.exports=t,e.exports.__esModule=!0,e.exports.default=e.exports}),Zc=pe((c,e)=>{le(),ue(),ce();var t=ar().default;function r(a,n){if(t(a)!="object"||!a)return a;var i=a[Symbol.toPrimitive];if(i!==void 0){var s=i.call(a,n||"default");if(t(s)!="object")return s;throw new TypeError("@@toPrimitive must return a primitive value.")}return(n==="string"?String:Number)(a)}e.exports=r,e.exports.__esModule=!0,e.exports.default=e.exports}),eu=pe((c,e)=>{le(),ue(),ce();var t=ar().default,r=Zc();function a(n){var i=r(n,"string");return t(i)=="symbol"?i:i+""}e.exports=a,e.exports.__esModule=!0,e.exports.default=e.exports}),tu=pe((c,e)=>{le(),ue(),ce();var t=eu();function r(a,n,i){return(n=t(n))in a?Object.defineProperty(a,n,{value:i,enumerable:!0,configurable:!0,writable:!0}):a[n]=i,a}e.exports=r,e.exports.__esModule=!0,e.exports.default=e.exports}),ru=pe((c,e)=>{le(),ue(),ce();function t(r){if(Array.isArray(r))return r}e.exports=t,e.exports.__esModule=!0,e.exports.default=e.exports}),nu=pe((c,e)=>{le(),ue(),ce();function t(r,a){var n=r==null?null:typeof Symbol<"u"&&r[Symbol.iterator]||r["@@iterator"];if(n!=null){var i,s,o,l,u=[],d=!0,p=!1;try{if(o=(n=n.call(r)).next,a===0){if(Object(n)!==n)return;d=!1}else for(;!(d=(i=o.call(n)).done)&&(u.push(i.value),u.length!==a);d=!0);}catch(y){p=!0,s=y}finally{try{if(!d&&n.return!=null&&(l=n.return(),Object(l)!==l))return}finally{if(p)throw s}}return u}}e.exports=t,e.exports.__esModule=!0,e.exports.default=e.exports}),iu=pe((c,e)=>{le(),ue(),ce();function t(r,a){(a==null||a>r.length)&&(a=r.length);for(var n=0,i=Array(a);n<a;n++)i[n]=r[n];return i}e.exports=t,e.exports.__esModule=!0,e.exports.default=e.exports}),ou=pe((c,e)=>{le(),ue(),ce();var t=iu();function r(a,n){if(a){if(typeof a=="string")return t(a,n);var i={}.toString.call(a).slice(8,-1);return i==="Object"&&a.constructor&&(i=a.constructor.name),i==="Map"||i==="Set"?Array.from(a):i==="Arguments"||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(i)?t(a,n):void 0}}e.exports=r,e.exports.__esModule=!0,e.exports.default=e.exports}),su=pe((c,e)=>{le(),ue(),ce();function t(){throw new TypeError(`Invalid attempt to destructure non-iterable instance.
3
- In order to be iterable, non-array objects must have a [Symbol.iterator]() method.`)}e.exports=t,e.exports.__esModule=!0,e.exports.default=e.exports}),au=pe((c,e)=>{le(),ue(),ce();var t=ru(),r=nu(),a=ou(),n=su();function i(s,o){return t(s)||r(s,o)||a(s,o)||n()}e.exports=i,e.exports.__esModule=!0,e.exports.default=e.exports}),as=pe((c,e)=>{le(),ue(),ce(),(function(t,r){typeof c=="object"&&typeof e<"u"?r(c):typeof define=="function"&&define.amd?define(["exports"],r):(t=typeof globalThis<"u"?globalThis:t||self,r(t.fastUniqueNumbers={}))})(c,function(t){var r=function(y){return function(f){var g=y(f);return f.add(g),g}},a=function(y){return function(f,g){return y.set(f,g),g}},n=Number.MAX_SAFE_INTEGER===void 0?9007199254740991:Number.MAX_SAFE_INTEGER,i=536870912,s=i*2,o=function(y,f){return function(g){var b=f.get(g),k=b===void 0?g.size:b<s?b+1:0;if(!g.has(k))return y(g,k);if(g.size<i){for(;g.has(k);)k=Math.floor(Math.random()*s);return y(g,k)}if(g.size>n)throw new Error("Congratulations, you created a collection of unique numbers which uses all available integers!");for(;g.has(k);)k=Math.floor(Math.random()*n);return y(g,k)}},l=new WeakMap,u=a(l),d=o(u,l),p=r(d);t.addUniqueNumber=p,t.generateUniqueNumber=d})}),lu=pe((c,e)=>{le(),ue(),ce();function t(a,n,i,s,o,l,u){try{var d=a[l](u),p=d.value}catch(y){return void i(y)}d.done?n(p):Promise.resolve(p).then(s,o)}function r(a){return function(){var n=this,i=arguments;return new Promise(function(s,o){var l=a.apply(n,i);function u(p){t(l,s,o,u,d,"next",p)}function d(p){t(l,s,o,u,d,"throw",p)}u(void 0)})}}e.exports=r,e.exports.__esModule=!0,e.exports.default=e.exports}),ls=pe((c,e)=>{le(),ue(),ce();function t(r,a){this.v=r,this.k=a}e.exports=t,e.exports.__esModule=!0,e.exports.default=e.exports}),cs=pe((c,e)=>{le(),ue(),ce();function t(r,a,n,i){var s=Object.defineProperty;try{s({},"",{})}catch{s=0}e.exports=t=function(o,l,u,d){function p(y,f){t(o,y,function(g){return this._invoke(y,f,g)})}l?s?s(o,l,{value:u,enumerable:!d,configurable:!d,writable:!d}):o[l]=u:(p("next",0),p("throw",1),p("return",2))},e.exports.__esModule=!0,e.exports.default=e.exports,t(r,a,n,i)}e.exports=t,e.exports.__esModule=!0,e.exports.default=e.exports}),us=pe((c,e)=>{le(),ue(),ce();var t=cs();function r(){var a,n,i=typeof Symbol=="function"?Symbol:{},s=i.iterator||"@@iterator",o=i.toStringTag||"@@toStringTag";function l(k,m,w,E){var v=m&&m.prototype instanceof d?m:d,x=Object.create(v.prototype);return t(x,"_invoke",(function(S,I,M){var O,B,T,W=0,F=M||[],N=!1,ae={p:0,n:0,v:a,a:Y,f:Y.bind(a,4),d:function(K,re){return O=K,B=0,T=a,ae.n=re,u}};function Y(K,re){for(B=K,T=re,n=0;!N&&W&&!D&&n<F.length;n++){var D,Z=F[n],P=ae.p,J=Z[2];K>3?(D=J===re)&&(T=Z[(B=Z[4])?5:(B=3,3)],Z[4]=Z[5]=a):Z[0]<=P&&((D=K<2&&P<Z[1])?(B=0,ae.v=re,ae.n=Z[1]):P<J&&(D=K<3||Z[0]>re||re>J)&&(Z[4]=K,Z[5]=re,ae.n=J,B=0))}if(D||K>1)return u;throw N=!0,re}return function(K,re,D){if(W>1)throw TypeError("Generator is already running");for(N&&re===1&&Y(re,D),B=re,T=D;(n=B<2?a:T)||!N;){O||(B?B<3?(B>1&&(ae.n=-1),Y(B,T)):ae.n=T:ae.v=T);try{if(W=2,O){if(B||(K="next"),n=O[K]){if(!(n=n.call(O,T)))throw TypeError("iterator result is not an object");if(!n.done)return n;T=n.value,B<2&&(B=0)}else B===1&&(n=O.return)&&n.call(O),B<2&&(T=TypeError("The iterator does not provide a '"+K+"' method"),B=1);O=a}else if((n=(N=ae.n<0)?T:S.call(I,ae))!==u)break}catch(Z){O=a,B=1,T=Z}finally{W=1}}return{value:n,done:N}}})(k,w,E),!0),x}var u={};function d(){}function p(){}function y(){}n=Object.getPrototypeOf;var f=[][s]?n(n([][s]())):(t(n={},s,function(){return this}),n),g=y.prototype=d.prototype=Object.create(f);function b(k){return Object.setPrototypeOf?Object.setPrototypeOf(k,y):(k.__proto__=y,t(k,o,"GeneratorFunction")),k.prototype=Object.create(g),k}return p.prototype=y,t(g,"constructor",y),t(y,"constructor",p),p.displayName="GeneratorFunction",t(y,o,"GeneratorFunction"),t(g),t(g,o,"Generator"),t(g,s,function(){return this}),t(g,"toString",function(){return"[object Generator]"}),(e.exports=r=function(){return{w:l,m:b}},e.exports.__esModule=!0,e.exports.default=e.exports)()}e.exports=r,e.exports.__esModule=!0,e.exports.default=e.exports}),hs=pe((c,e)=>{le(),ue(),ce();var t=ls(),r=cs();function a(n,i){function s(l,u,d,p){try{var y=n[l](u),f=y.value;return f instanceof t?i.resolve(f.v).then(function(g){s("next",g,d,p)},function(g){s("throw",g,d,p)}):i.resolve(f).then(function(g){y.value=g,d(y)},function(g){return s("throw",g,d,p)})}catch(g){p(g)}}var o;this.next||(r(a.prototype),r(a.prototype,typeof Symbol=="function"&&Symbol.asyncIterator||"@asyncIterator",function(){return this})),r(this,"_invoke",function(l,u,d){function p(){return new i(function(y,f){s(l,d,y,f)})}return o=o?o.then(p,p):p()},!0)}e.exports=a,e.exports.__esModule=!0,e.exports.default=e.exports}),fs=pe((c,e)=>{le(),ue(),ce();var t=us(),r=hs();function a(n,i,s,o,l){return new r(t().w(n,i,s,o),l||Promise)}e.exports=a,e.exports.__esModule=!0,e.exports.default=e.exports}),cu=pe((c,e)=>{le(),ue(),ce();var t=fs();function r(a,n,i,s,o){var l=t(a,n,i,s,o);return l.next().then(function(u){return u.done?u.value:l.next()})}e.exports=r,e.exports.__esModule=!0,e.exports.default=e.exports}),uu=pe((c,e)=>{le(),ue(),ce();function t(r){var a=Object(r),n=[];for(var i in a)n.unshift(i);return function s(){for(;n.length;)if((i=n.pop())in a)return s.value=i,s.done=!1,s;return s.done=!0,s}}e.exports=t,e.exports.__esModule=!0,e.exports.default=e.exports}),hu=pe((c,e)=>{le(),ue(),ce();var t=ar().default;function r(a){if(a!=null){var n=a[typeof Symbol=="function"&&Symbol.iterator||"@@iterator"],i=0;if(n)return n.call(a);if(typeof a.next=="function")return a;if(!isNaN(a.length))return{next:function(){return a&&i>=a.length&&(a=void 0),{value:a&&a[i++],done:!a}}}}throw new TypeError(t(a)+" is not iterable")}e.exports=r,e.exports.__esModule=!0,e.exports.default=e.exports}),fu=pe((c,e)=>{le(),ue(),ce();var t=ls(),r=us(),a=cu(),n=fs(),i=hs(),s=uu(),o=hu();function l(){var u=r(),d=u.m(l),p=(Object.getPrototypeOf?Object.getPrototypeOf(d):d.__proto__).constructor;function y(b){var k=typeof b=="function"&&b.constructor;return!!k&&(k===p||(k.displayName||k.name)==="GeneratorFunction")}var f={throw:1,return:2,break:3,continue:3};function g(b){var k,m;return function(w){k||(k={stop:function(){return m(w.a,2)},catch:function(){return w.v},abrupt:function(E,v){return m(w.a,f[E],v)},delegateYield:function(E,v,x){return k.resultName=v,m(w.d,o(E),x)},finish:function(E){return m(w.f,E)}},m=function(E,v,x){w.p=k.prev,w.n=k.next;try{return E(v,x)}finally{k.next=w.n}}),k.resultName&&(k[k.resultName]=w.v,k.resultName=void 0),k.sent=w.v,k.next=w.n;try{return b.call(this,k)}finally{w.p=k.prev,w.n=k.next}}}return(e.exports=l=function(){return{wrap:function(b,k,m,w){return u.w(g(b),k,m,w&&w.reverse())},isGeneratorFunction:y,mark:u.m,awrap:function(b,k){return new t(b,k)},AsyncIterator:i,async:function(b,k,m,w,E){return(y(k)?n:a)(g(b),k,m,w,E)},keys:s,values:o}},e.exports.__esModule=!0,e.exports.default=e.exports)()}e.exports=l,e.exports.__esModule=!0,e.exports.default=e.exports}),du=pe((c,e)=>{le(),ue(),ce();var t=fu()();e.exports=t;try{regeneratorRuntime=t}catch{typeof globalThis=="object"?globalThis.regeneratorRuntime=t:Function("r","regeneratorRuntime = r")(t)}}),pu=pe((c,e)=>{le(),ue(),ce(),(function(t,r){typeof c=="object"&&typeof e<"u"?r(c,tu(),au(),as(),lu(),du()):typeof define=="function"&&define.amd?define(["exports","@babel/runtime/helpers/defineProperty","@babel/runtime/helpers/slicedToArray","fast-unique-numbers","@babel/runtime/helpers/asyncToGenerator","@babel/runtime/regenerator"],r):(t=typeof globalThis<"u"?globalThis:t||self,r(t.brokerFactory={},t._defineProperty,t._slicedToArray,t.fastUniqueNumbers,t._asyncToGenerator,t._regeneratorRuntime))})(c,function(t,r,a,n,i,s){var o=function(m){return typeof m.start=="function"},l=new WeakMap;function u(m,w){var E=Object.keys(m);if(Object.getOwnPropertySymbols){var v=Object.getOwnPropertySymbols(m);w&&(v=v.filter(function(x){return Object.getOwnPropertyDescriptor(m,x).enumerable})),E.push.apply(E,v)}return E}function d(m){for(var w=1;w<arguments.length;w++){var E=arguments[w]!=null?arguments[w]:{};w%2?u(Object(E),!0).forEach(function(v){r(m,v,E[v])}):Object.getOwnPropertyDescriptors?Object.defineProperties(m,Object.getOwnPropertyDescriptors(E)):u(Object(E)).forEach(function(v){Object.defineProperty(m,v,Object.getOwnPropertyDescriptor(E,v))})}return m}var p=function(m){return d(d({},m),{},{connect:function(w){var E=w.call;return i(s.mark(function v(){var x,S,I,M;return s.wrap(function(O){for(;;)switch(O.prev=O.next){case 0:return x=new MessageChannel,S=x.port1,I=x.port2,O.next=1,E("connect",{port:S},[S]);case 1:return M=O.sent,l.set(I,M),O.abrupt("return",I);case 2:case"end":return O.stop()}},v)}))},disconnect:function(w){var E=w.call;return(function(){var v=i(s.mark(function x(S){var I;return s.wrap(function(M){for(;;)switch(M.prev=M.next){case 0:if(I=l.get(S),I!==void 0){M.next=1;break}throw new Error("The given port is not connected.");case 1:return M.next=2,E("disconnect",{portId:I});case 2:case"end":return M.stop()}},x)}));return function(x){return v.apply(this,arguments)}})()},isSupported:function(w){var E=w.call;return function(){return E("isSupported")}}})};function y(m,w){var E=Object.keys(m);if(Object.getOwnPropertySymbols){var v=Object.getOwnPropertySymbols(m);w&&(v=v.filter(function(x){return Object.getOwnPropertyDescriptor(m,x).enumerable})),E.push.apply(E,v)}return E}function f(m){for(var w=1;w<arguments.length;w++){var E=arguments[w]!=null?arguments[w]:{};w%2?y(Object(E),!0).forEach(function(v){r(m,v,E[v])}):Object.getOwnPropertyDescriptors?Object.defineProperties(m,Object.getOwnPropertyDescriptors(E)):y(Object(E)).forEach(function(v){Object.defineProperty(m,v,Object.getOwnPropertyDescriptor(E,v))})}return m}var g=new WeakMap,b=function(m){if(g.has(m))return g.get(m);var w=new Map;return g.set(m,w),w},k=function(m){var w=p(m);return function(E){var v=b(E);E.addEventListener("message",function(F){var N=F.data,ae=N.id;if(ae!==null&&v.has(ae)){var Y=v.get(ae),K=Y.reject,re=Y.resolve;v.delete(ae),N.error===void 0?re(N.result):K(new Error(N.error.message))}}),o(E)&&E.start();for(var x=function(F){var N=arguments.length>1&&arguments[1]!==void 0?arguments[1]:null,ae=arguments.length>2&&arguments[2]!==void 0?arguments[2]:[];return new Promise(function(Y,K){var re=n.generateUniqueNumber(v);v.set(re,{reject:K,resolve:Y}),N===null?E.postMessage({id:re,method:F},ae):E.postMessage({id:re,method:F,params:N},ae)})},S=function(F,N){var ae=arguments.length>2&&arguments[2]!==void 0?arguments[2]:[];E.postMessage({id:null,method:F,params:N},ae)},I={},M=0,O=Object.entries(w);M<O.length;M++){var B=a(O[M],2),T=B[0],W=B[1];I=f(f({},I),{},r({},T,W({call:x,notify:S})))}return f({},I)}};t.createBroker=k})}),gu=pe((c,e)=>{le(),ue(),ce(),(function(t,r){typeof c=="object"&&typeof e<"u"?r(c,ar(),pu(),as()):typeof define=="function"&&define.amd?define(["exports","@babel/runtime/helpers/typeof","broker-factory","fast-unique-numbers"],r):(t=typeof globalThis<"u"?globalThis:t||self,r(t.workerTimersBroker={},t._typeof,t.brokerFactory,t.fastUniqueNumbers))})(c,function(t,r,a,n){var i=new Map([[0,null]]),s=new Map([[0,null]]),o=a.createBroker({clearInterval:function(u){var d=u.call;return function(p){r(i.get(p))==="symbol"&&(i.set(p,null),d("clear",{timerId:p,timerType:"interval"}).then(function(){i.delete(p)}))}},clearTimeout:function(u){var d=u.call;return function(p){r(s.get(p))==="symbol"&&(s.set(p,null),d("clear",{timerId:p,timerType:"timeout"}).then(function(){s.delete(p)}))}},setInterval:function(u){var d=u.call;return function(p){for(var y=arguments.length>1&&arguments[1]!==void 0?arguments[1]:0,f=arguments.length,g=new Array(f>2?f-2:0),b=2;b<f;b++)g[b-2]=arguments[b];var k=Symbol(),m=n.generateUniqueNumber(i);i.set(m,k);var w=function(){return d("set",{delay:y,now:performance.timeOrigin+performance.now(),timerId:m,timerType:"interval"}).then(function(){var E=i.get(m);if(E===void 0)throw new Error("The timer is in an undefined state.");E===k&&(p.apply(void 0,g),i.get(m)===k&&w())})};return w(),m}},setTimeout:function(u){var d=u.call;return function(p){for(var y=arguments.length>1&&arguments[1]!==void 0?arguments[1]:0,f=arguments.length,g=new Array(f>2?f-2:0),b=2;b<f;b++)g[b-2]=arguments[b];var k=Symbol(),m=n.generateUniqueNumber(s);return s.set(m,k),d("set",{delay:y,now:performance.timeOrigin+performance.now(),timerId:m,timerType:"timeout"}).then(function(){var w=s.get(m);if(w===void 0)throw new Error("The timer is in an undefined state.");w===k&&(s.delete(m),p.apply(void 0,g))}),m}}}),l=function(u){var d=new Worker(u);return o(d)};t.load=l,t.wrap=o})}),mu=pe((c,e)=>{le(),ue(),ce(),(function(t,r){typeof c=="object"&&typeof e<"u"?r(c,gu()):typeof define=="function"&&define.amd?define(["exports","worker-timers-broker"],r):(t=typeof globalThis<"u"?globalThis:t||self,r(t.workerTimers={},t.workerTimersBroker))})(c,function(t,r){var a=function(d,p){var y=null;return function(){if(y!==null)return y;var f=new Blob([p],{type:"application/javascript; charset=utf-8"}),g=URL.createObjectURL(f);return y=d(g),setTimeout(function(){return URL.revokeObjectURL(g)}),y}},n=`(()=>{var e={45:(e,t,r)=>{var n=r(738).default;e.exports=function(e,t){if("object"!=n(e)||!e)return e;var r=e[Symbol.toPrimitive];if(void 0!==r){var o=r.call(e,t||"default");if("object"!=n(o))return o;throw new TypeError("@@toPrimitive must return a primitive value.")}return("string"===t?String:Number)(e)},e.exports.__esModule=!0,e.exports.default=e.exports},79:e=>{e.exports=function(e,t){(null==t||t>e.length)&&(t=e.length);for(var r=0,n=Array(t);r<t;r++)n[r]=e[r];return n},e.exports.__esModule=!0,e.exports.default=e.exports},122:(e,t,r)=>{var n=r(79);e.exports=function(e,t){if(e){if("string"==typeof e)return n(e,t);var r={}.toString.call(e).slice(8,-1);return"Object"===r&&e.constructor&&(r=e.constructor.name),"Map"===r||"Set"===r?Array.from(e):"Arguments"===r||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(r)?n(e,t):void 0}},e.exports.__esModule=!0,e.exports.default=e.exports},156:e=>{e.exports=function(e,t){var r=null==e?null:"undefined"!=typeof Symbol&&e[Symbol.iterator]||e["@@iterator"];if(null!=r){var n,o,u,a,i=[],s=!0,c=!1;try{if(u=(r=r.call(e)).next,0===t){if(Object(r)!==r)return;s=!1}else for(;!(s=(n=u.call(r)).done)&&(i.push(n.value),i.length!==t);s=!0);}catch(e){c=!0,o=e}finally{try{if(!s&&null!=r.return&&(a=r.return(),Object(a)!==a))return}finally{if(c)throw o}}return i}},e.exports.__esModule=!0,e.exports.default=e.exports},172:e=>{e.exports=function(e,t){this.v=e,this.k=t},e.exports.__esModule=!0,e.exports.default=e.exports},293:e=>{function t(e,t,r,n,o,u,a){try{var i=e[u](a),s=i.value}catch(e){return void r(e)}i.done?t(s):Promise.resolve(s).then(n,o)}e.exports=function(e){return function(){var r=this,n=arguments;return new Promise((function(o,u){var a=e.apply(r,n);function i(e){t(a,o,u,i,s,"next",e)}function s(e){t(a,o,u,i,s,"throw",e)}i(void 0)}))}},e.exports.__esModule=!0,e.exports.default=e.exports},373:e=>{e.exports=function(e){var t=Object(e),r=[];for(var n in t)r.unshift(n);return function e(){for(;r.length;)if((n=r.pop())in t)return e.value=n,e.done=!1,e;return e.done=!0,e}},e.exports.__esModule=!0,e.exports.default=e.exports},389:function(e,t){!function(e){"use strict";var t=function(e){return function(t){var r=e(t);return t.add(r),r}},r=function(e){return function(t,r){return e.set(t,r),r}},n=void 0===Number.MAX_SAFE_INTEGER?9007199254740991:Number.MAX_SAFE_INTEGER,o=536870912,u=2*o,a=function(e,t){return function(r){var a=t.get(r),i=void 0===a?r.size:a<u?a+1:0;if(!r.has(i))return e(r,i);if(r.size<o){for(;r.has(i);)i=Math.floor(Math.random()*u);return e(r,i)}if(r.size>n)throw new Error("Congratulations, you created a collection of unique numbers which uses all available integers!");for(;r.has(i);)i=Math.floor(Math.random()*n);return e(r,i)}},i=new WeakMap,s=r(i),c=a(s,i),f=t(c);e.addUniqueNumber=f,e.generateUniqueNumber=c}(t)},472:function(e,t,r){!function(e,t,r,n){"use strict";var o=function(e,t){return function(r){var o=t.get(r);if(void 0===o)return Promise.resolve(!1);var u=n(o,2),a=u[0],i=u[1];return e(a),t.delete(r),i(!1),Promise.resolve(!0)}},u=function(e,t){var r=function(n,o,u,a){var i=n-e.now();i>0?o.set(a,[t(r,i,n,o,u,a),u]):(o.delete(a),u(!0))};return r},a=function(e,t,r,n){return function(o,u,a){var i=o+u-t.timeOrigin,s=i-t.now();return new Promise((function(t){e.set(a,[r(n,s,i,e,t,a),t])}))}},i=new Map,s=o(globalThis.clearTimeout,i),c=new Map,f=o(globalThis.clearTimeout,c),l=u(performance,globalThis.setTimeout),p=a(i,performance,globalThis.setTimeout,l),d=a(c,performance,globalThis.setTimeout,l);r.createWorker(self,{clear:function(){var r=e(t.mark((function e(r){var n,o,u;return t.wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return n=r.timerId,o=r.timerType,e.next=1,"interval"===o?s(n):f(n);case 1:return u=e.sent,e.abrupt("return",{result:u});case 2:case"end":return e.stop()}}),e)})));function n(e){return r.apply(this,arguments)}return n}(),set:function(){var r=e(t.mark((function e(r){var n,o,u,a,i;return t.wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return n=r.delay,o=r.now,u=r.timerId,a=r.timerType,e.next=1,("interval"===a?p:d)(n,o,u);case 1:return i=e.sent,e.abrupt("return",{result:i});case 2:case"end":return e.stop()}}),e)})));function n(e){return r.apply(this,arguments)}return n}()})}(r(293),r(756),r(623),r(715))},546:e=>{function t(r,n,o,u){var a=Object.defineProperty;try{a({},"",{})}catch(r){a=0}e.exports=t=function(e,r,n,o){if(r)a?a(e,r,{value:n,enumerable:!o,configurable:!o,writable:!o}):e[r]=n;else{var u=function(r,n){t(e,r,(function(e){return this._invoke(r,n,e)}))};u("next",0),u("throw",1),u("return",2)}},e.exports.__esModule=!0,e.exports.default=e.exports,t(r,n,o,u)}e.exports=t,e.exports.__esModule=!0,e.exports.default=e.exports},579:(e,t,r)=>{var n=r(738).default;e.exports=function(e){if(null!=e){var t=e["function"==typeof Symbol&&Symbol.iterator||"@@iterator"],r=0;if(t)return t.call(e);if("function"==typeof e.next)return e;if(!isNaN(e.length))return{next:function(){return e&&r>=e.length&&(e=void 0),{value:e&&e[r++],done:!e}}}}throw new TypeError(n(e)+" is not iterable")},e.exports.__esModule=!0,e.exports.default=e.exports},623:function(e,t,r){!function(e,t,r,n,o){"use strict";var u={INTERNAL_ERROR:-32603,INVALID_PARAMS:-32602,METHOD_NOT_FOUND:-32601},a=function(e,t){return Object.assign(new Error(e),{status:t})},i=function(e){return a('The requested method called "'.concat(e,'" is not supported.'),u.METHOD_NOT_FOUND)},s=function(e){return a('The handler of the method called "'.concat(e,'" returned no required result.'),u.INTERNAL_ERROR)},c=function(e){return a('The handler of the method called "'.concat(e,'" returned an unexpected result.'),u.INTERNAL_ERROR)},f=function(e){return a('The specified parameter called "portId" with the given value "'.concat(e,'" does not identify a port connected to this worker.'),u.INVALID_PARAMS)},l=function(e,n){return function(){var o=t(r.mark((function t(o){var u,a,f,l,p,d,v,x,y,b,h,m,_,g,w;return r.wrap((function(t){for(;;)switch(t.prev=t.next){case 0:if(u=o.data,a=u.id,f=u.method,l=u.params,p=n[f],t.prev=1,void 0!==p){t.next=2;break}throw i(f);case 2:if(void 0!==(d=void 0===l?p():p(l))){t.next=3;break}throw s(f);case 3:if(!(d instanceof Promise)){t.next=5;break}return t.next=4,d;case 4:g=t.sent,t.next=6;break;case 5:g=d;case 6:if(v=g,null!==a){t.next=8;break}if(void 0===v.result){t.next=7;break}throw c(f);case 7:t.next=10;break;case 8:if(void 0!==v.result){t.next=9;break}throw c(f);case 9:x=v.result,y=v.transferables,b=void 0===y?[]:y,e.postMessage({id:a,result:x},b);case 10:t.next=12;break;case 11:t.prev=11,w=t.catch(1),h=w.message,m=w.status,_=void 0===m?-32603:m,e.postMessage({error:{code:_,message:h},id:a});case 12:case"end":return t.stop()}}),t,null,[[1,11]])})));return function(e){return o.apply(this,arguments)}}()},p=function(){return new Promise((function(e){var t=new ArrayBuffer(0),r=new MessageChannel,n=r.port1,o=r.port2;n.onmessage=function(t){var r=t.data;return e(null!==r)},o.postMessage(t,[t])}))};function d(e,t){var r=Object.keys(e);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(e);t&&(n=n.filter((function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable}))),r.push.apply(r,n)}return r}function v(e){for(var t=1;t<arguments.length;t++){var r=null!=arguments[t]?arguments[t]:{};t%2?d(Object(r),!0).forEach((function(t){n(e,t,r[t])})):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(r)):d(Object(r)).forEach((function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(r,t))}))}return e}var x=new Map,y=function(e,n,u){return v(v({},n),{},{connect:function(t){var r=t.port;r.start();var u=e(r,n),a=o.generateUniqueNumber(x);return x.set(a,(function(){u(),r.close(),x.delete(a)})),{result:a}},disconnect:function(e){var t=e.portId,r=x.get(t);if(void 0===r)throw f(t);return r(),{result:null}},isSupported:function(){var e=t(r.mark((function e(){var t,n,o;return r.wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return e.next=1,p();case 1:if(!e.sent){e.next=5;break}if(!((t=u())instanceof Promise)){e.next=3;break}return e.next=2,t;case 2:o=e.sent,e.next=4;break;case 3:o=t;case 4:return n=o,e.abrupt("return",{result:n});case 5:return e.abrupt("return",{result:!1});case 6:case"end":return e.stop()}}),e)})));function n(){return e.apply(this,arguments)}return n}()})},b=function(e,t){var r=y(b,t,arguments.length>2&&void 0!==arguments[2]?arguments[2]:function(){return!0}),n=l(e,r);return e.addEventListener("message",n),function(){return e.removeEventListener("message",n)}};e.createWorker=b,e.isSupported=p}(t,r(293),r(756),r(693),r(389))},633:(e,t,r)=>{var n=r(172),o=r(993),u=r(869),a=r(887),i=r(791),s=r(373),c=r(579);function f(){"use strict";var t=o(),r=t.m(f),l=(Object.getPrototypeOf?Object.getPrototypeOf(r):r.__proto__).constructor;function p(e){var t="function"==typeof e&&e.constructor;return!!t&&(t===l||"GeneratorFunction"===(t.displayName||t.name))}var d={throw:1,return:2,break:3,continue:3};function v(e){var t,r;return function(n){t||(t={stop:function(){return r(n.a,2)},catch:function(){return n.v},abrupt:function(e,t){return r(n.a,d[e],t)},delegateYield:function(e,o,u){return t.resultName=o,r(n.d,c(e),u)},finish:function(e){return r(n.f,e)}},r=function(e,r,o){n.p=t.prev,n.n=t.next;try{return e(r,o)}finally{t.next=n.n}}),t.resultName&&(t[t.resultName]=n.v,t.resultName=void 0),t.sent=n.v,t.next=n.n;try{return e.call(this,t)}finally{n.p=t.prev,n.n=t.next}}}return(e.exports=f=function(){return{wrap:function(e,r,n,o){return t.w(v(e),r,n,o&&o.reverse())},isGeneratorFunction:p,mark:t.m,awrap:function(e,t){return new n(e,t)},AsyncIterator:i,async:function(e,t,r,n,o){return(p(t)?a:u)(v(e),t,r,n,o)},keys:s,values:c}},e.exports.__esModule=!0,e.exports.default=e.exports)()}e.exports=f,e.exports.__esModule=!0,e.exports.default=e.exports},693:(e,t,r)=>{var n=r(736);e.exports=function(e,t,r){return(t=n(t))in e?Object.defineProperty(e,t,{value:r,enumerable:!0,configurable:!0,writable:!0}):e[t]=r,e},e.exports.__esModule=!0,e.exports.default=e.exports},715:(e,t,r)=>{var n=r(987),o=r(156),u=r(122),a=r(752);e.exports=function(e,t){return n(e)||o(e,t)||u(e,t)||a()},e.exports.__esModule=!0,e.exports.default=e.exports},736:(e,t,r)=>{var n=r(738).default,o=r(45);e.exports=function(e){var t=o(e,"string");return"symbol"==n(t)?t:t+""},e.exports.__esModule=!0,e.exports.default=e.exports},738:e=>{function t(r){return e.exports=t="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},e.exports.__esModule=!0,e.exports.default=e.exports,t(r)}e.exports=t,e.exports.__esModule=!0,e.exports.default=e.exports},752:e=>{e.exports=function(){throw new TypeError("Invalid attempt to destructure non-iterable instance.\\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")},e.exports.__esModule=!0,e.exports.default=e.exports},756:(e,t,r)=>{var n=r(633)();e.exports=n;try{regeneratorRuntime=n}catch(e){"object"==typeof globalThis?globalThis.regeneratorRuntime=n:Function("r","regeneratorRuntime = r")(n)}},791:(e,t,r)=>{var n=r(172),o=r(546);e.exports=function e(t,r){function u(e,o,a,i){try{var s=t[e](o),c=s.value;return c instanceof n?r.resolve(c.v).then((function(e){u("next",e,a,i)}),(function(e){u("throw",e,a,i)})):r.resolve(c).then((function(e){s.value=e,a(s)}),(function(e){return u("throw",e,a,i)}))}catch(e){i(e)}}var a;this.next||(o(e.prototype),o(e.prototype,"function"==typeof Symbol&&Symbol.asyncIterator||"@asyncIterator",(function(){return this}))),o(this,"_invoke",(function(e,t,n){function o(){return new r((function(t,r){u(e,n,t,r)}))}return a=a?a.then(o,o):o()}),!0)},e.exports.__esModule=!0,e.exports.default=e.exports},869:(e,t,r)=>{var n=r(887);e.exports=function(e,t,r,o,u){var a=n(e,t,r,o,u);return a.next().then((function(e){return e.done?e.value:a.next()}))},e.exports.__esModule=!0,e.exports.default=e.exports},887:(e,t,r)=>{var n=r(993),o=r(791);e.exports=function(e,t,r,u,a){return new o(n().w(e,t,r,u),a||Promise)},e.exports.__esModule=!0,e.exports.default=e.exports},987:e=>{e.exports=function(e){if(Array.isArray(e))return e},e.exports.__esModule=!0,e.exports.default=e.exports},993:(e,t,r)=>{var n=r(546);function o(){var t,r,u="function"==typeof Symbol?Symbol:{},a=u.iterator||"@@iterator",i=u.toStringTag||"@@toStringTag";function s(e,o,u,a){var i=o&&o.prototype instanceof f?o:f,s=Object.create(i.prototype);return n(s,"_invoke",function(e,n,o){var u,a,i,s=0,f=o||[],l=!1,p={p:0,n:0,v:t,a:d,f:d.bind(t,4),d:function(e,r){return u=e,a=0,i=t,p.n=r,c}};function d(e,n){for(a=e,i=n,r=0;!l&&s&&!o&&r<f.length;r++){var o,u=f[r],d=p.p,v=u[2];e>3?(o=v===n)&&(i=u[(a=u[4])?5:(a=3,3)],u[4]=u[5]=t):u[0]<=d&&((o=e<2&&d<u[1])?(a=0,p.v=n,p.n=u[1]):d<v&&(o=e<3||u[0]>n||n>v)&&(u[4]=e,u[5]=n,p.n=v,a=0))}if(o||e>1)return c;throw l=!0,n}return function(o,f,v){if(s>1)throw TypeError("Generator is already running");for(l&&1===f&&d(f,v),a=f,i=v;(r=a<2?t:i)||!l;){u||(a?a<3?(a>1&&(p.n=-1),d(a,i)):p.n=i:p.v=i);try{if(s=2,u){if(a||(o="next"),r=u[o]){if(!(r=r.call(u,i)))throw TypeError("iterator result is not an object");if(!r.done)return r;i=r.value,a<2&&(a=0)}else 1===a&&(r=u.return)&&r.call(u),a<2&&(i=TypeError("The iterator does not provide a '"+o+"' method"),a=1);u=t}else if((r=(l=p.n<0)?i:e.call(n,p))!==c)break}catch(e){u=t,a=1,i=e}finally{s=1}}return{value:r,done:l}}}(e,u,a),!0),s}var c={};function f(){}function l(){}function p(){}r=Object.getPrototypeOf;var d=[][a]?r(r([][a]())):(n(r={},a,(function(){return this})),r),v=p.prototype=f.prototype=Object.create(d);function x(e){return Object.setPrototypeOf?Object.setPrototypeOf(e,p):(e.__proto__=p,n(e,i,"GeneratorFunction")),e.prototype=Object.create(v),e}return l.prototype=p,n(v,"constructor",p),n(p,"constructor",l),l.displayName="GeneratorFunction",n(p,i,"GeneratorFunction"),n(v),n(v,i,"Generator"),n(v,a,(function(){return this})),n(v,"toString",(function(){return"[object Generator]"})),(e.exports=o=function(){return{w:s,m:x}},e.exports.__esModule=!0,e.exports.default=e.exports)()}e.exports=o,e.exports.__esModule=!0,e.exports.default=e.exports}},t={};function r(n){var o=t[n];if(void 0!==o)return o.exports;var u=t[n]={exports:{}};return e[n].call(u.exports,u,u.exports,r),u.exports}r.n=e=>{var t=e&&e.__esModule?()=>e.default:()=>e;return r.d(t,{a:t}),t},r.d=(e,t)=>{for(var n in t)r.o(t,n)&&!r.o(e,n)&&Object.defineProperty(e,n,{enumerable:!0,get:t[n]})},r.o=(e,t)=>Object.prototype.hasOwnProperty.call(e,t),(()=>{"use strict";r(472)})()})();`,i=a(r.load,n),s=function(d){return i().clearInterval(d)},o=function(d){return i().clearTimeout(d)},l=function(){var d;return(d=i()).setInterval.apply(d,arguments)},u=function(){var d;return(d=i()).setTimeout.apply(d,arguments)};t.clearInterval=s,t.clearTimeout=o,t.setInterval=l,t.setTimeout=u})}),lr=pe(c=>{le(),ue(),ce(),Object.defineProperty(c,"__esModule",{value:!0}),c.isReactNativeBrowser=c.isWebWorker=void 0;var e=()=>typeof window<"u"?typeof navigator<"u"&&navigator.userAgent?.toLowerCase().indexOf(" electron/")>-1&&Me?.versions?!Object.prototype.hasOwnProperty.call(Me.versions,"electron"):typeof window.document<"u":!1,t=()=>!!(typeof self=="object"&&self?.constructor?.name?.includes("WorkerGlobalScope")&&typeof Deno>"u"),r=()=>typeof navigator<"u"&&navigator.product==="ReactNative",a=e()||t()||r();c.isWebWorker=t(),c.isReactNativeBrowser=r(),c.default=a}),bu=pe(c=>{le(),ue(),ce();var e=c&&c.__createBinding||(Object.create?function(l,u,d,p){p===void 0&&(p=d);var y=Object.getOwnPropertyDescriptor(u,d);(!y||("get"in y?!u.__esModule:y.writable||y.configurable))&&(y={enumerable:!0,get:function(){return u[d]}}),Object.defineProperty(l,p,y)}:function(l,u,d,p){p===void 0&&(p=d),l[p]=u[d]}),t=c&&c.__setModuleDefault||(Object.create?function(l,u){Object.defineProperty(l,"default",{enumerable:!0,value:u})}:function(l,u){l.default=u}),r=c&&c.__importStar||(function(){var l=function(u){return l=Object.getOwnPropertyNames||function(d){var p=[];for(var y in d)Object.prototype.hasOwnProperty.call(d,y)&&(p[p.length]=y);return p},l(u)};return function(u){if(u&&u.__esModule)return u;var d={};if(u!=null)for(var p=l(u),y=0;y<p.length;y++)p[y]!=="default"&&e(d,u,p[y]);return t(d,u),d}})();Object.defineProperty(c,"__esModule",{value:!0});var a=mu(),n=r(lr()),i={set:a.setInterval,clear:a.clearInterval},s={set:(l,u)=>setInterval(l,u),clear:l=>clearInterval(l)},o=l=>{switch(l){case"native":return s;case"worker":return i;default:return n.default&&!n.isWebWorker&&!n.isReactNativeBrowser?i:s}};c.default=o}),ds=pe(c=>{le(),ue(),ce();var e=c&&c.__importDefault||function(a){return a&&a.__esModule?a:{default:a}};Object.defineProperty(c,"__esModule",{value:!0});var t=e(bu()),r=class{_keepalive;timerId;timer;destroyed=!1;counter;client;_keepaliveTimeoutTimestamp;_intervalEvery;get keepaliveTimeoutTimestamp(){return this._keepaliveTimeoutTimestamp}get intervalEvery(){return this._intervalEvery}get keepalive(){return this._keepalive}constructor(a,n){this.client=a,this.timer=typeof n=="object"&&"set"in n&&"clear"in n?n:(0,t.default)(n),this.setKeepalive(a.options.keepalive)}clear(){this.timerId&&(this.timer.clear(this.timerId),this.timerId=null)}setKeepalive(a){if(a*=1e3,isNaN(a)||a<=0||a>2147483647)throw new Error(`Keepalive value must be an integer between 0 and 2147483647. Provided value is ${a}`);this._keepalive=a,this.reschedule(),this.client.log(`KeepaliveManager: set keepalive to ${a}ms`)}destroy(){this.clear(),this.destroyed=!0}reschedule(){if(this.destroyed)return;this.clear(),this.counter=0;let a=Math.ceil(this._keepalive*1.5);this._keepaliveTimeoutTimestamp=Date.now()+a,this._intervalEvery=Math.ceil(this._keepalive/2),this.timerId=this.timer.set(()=>{this.destroyed||(this.counter+=1,this.counter===2?this.client.sendPing():this.counter>2&&this.client.onKeepaliveTimeout())},this._intervalEvery)}};c.default=r}),oi=pe(c=>{le(),ue(),ce();var e=c&&c.__createBinding||(Object.create?function(v,x,S,I){I===void 0&&(I=S);var M=Object.getOwnPropertyDescriptor(x,S);(!M||("get"in M?!x.__esModule:M.writable||M.configurable))&&(M={enumerable:!0,get:function(){return x[S]}}),Object.defineProperty(v,I,M)}:function(v,x,S,I){I===void 0&&(I=S),v[I]=x[S]}),t=c&&c.__setModuleDefault||(Object.create?function(v,x){Object.defineProperty(v,"default",{enumerable:!0,value:x})}:function(v,x){v.default=x}),r=c&&c.__importStar||(function(){var v=function(x){return v=Object.getOwnPropertyNames||function(S){var I=[];for(var M in S)Object.prototype.hasOwnProperty.call(S,M)&&(I[I.length]=M);return I},v(x)};return function(x){if(x&&x.__esModule)return x;var S={};if(x!=null)for(var I=v(x),M=0;M<I.length;M++)I[M]!=="default"&&e(S,x,I[M]);return t(S,x),S}})(),a=c&&c.__importDefault||function(v){return v&&v.__esModule?v:{default:v}};Object.defineProperty(c,"__esModule",{value:!0});var n=a(Ic()),i=Et(),s=a(Cc()),o=a(lt()),l=r(Xo()),u=a(Zo()),d=a(Qc()),p=a(ss()),y=a(Jc()),f=Rt(),g=Xc(),b=a(ds()),k=r(lr()),m=globalThis.setImmediate||((...v)=>{let x=v.shift();(0,f.nextTick)(()=>{x(...v)})}),w={keepalive:60,reschedulePings:!0,protocolId:"MQTT",protocolVersion:4,reconnectPeriod:1e3,connectTimeout:30*1e3,clean:!0,resubscribe:!0,subscribeBatchSize:null,writeCache:!0,timerVariant:"auto"},E=class fo extends g.TypedEventEmitter{static VERSION=f.MQTTJS_VERSION;connected;disconnecting;disconnected;reconnecting;incomingStore;outgoingStore;options;queueQoSZero;_reconnectCount;log;messageIdProvider;outgoing;messageIdToTopic;noop;keepaliveManager;stream;queue;streamBuilder;_resubscribeTopics;connackTimer;reconnectTimer;_storeProcessing;_packetIdsDuringStoreProcessing;_storeProcessingQueue;_firstConnection;topicAliasRecv;topicAliasSend;_deferredReconnect;connackPacket;static defaultId(){return`mqttjs_${Math.random().toString(16).substr(2,8)}`}constructor(x,S){super(),this.options=S||{};for(let I in w)typeof this.options[I]>"u"?this.options[I]=w[I]:this.options[I]=S[I];this.log=this.options.log||(0,o.default)("mqttjs:client"),this.noop=this._noop.bind(this),this.log("MqttClient :: version:",fo.VERSION),k.isWebWorker?this.log("MqttClient :: environment","webworker"):this.log("MqttClient :: environment",k.default?"browser":"node"),this.log("MqttClient :: options.protocol",S.protocol),this.log("MqttClient :: options.protocolVersion",S.protocolVersion),this.log("MqttClient :: options.username",S.username),this.log("MqttClient :: options.keepalive",S.keepalive),this.log("MqttClient :: options.reconnectPeriod",S.reconnectPeriod),this.log("MqttClient :: options.rejectUnauthorized",S.rejectUnauthorized),this.log("MqttClient :: options.properties.topicAliasMaximum",S.properties?S.properties.topicAliasMaximum:void 0),this.options.clientId=typeof S.clientId=="string"?S.clientId:fo.defaultId(),this.log("MqttClient :: clientId",this.options.clientId),this.options.customHandleAcks=S.protocolVersion===5&&S.customHandleAcks?S.customHandleAcks:(...I)=>{I[3](null,0)},this.options.writeCache||(n.default.writeToStream.cacheNumbers=!1),this.streamBuilder=x,this.messageIdProvider=typeof this.options.messageIdProvider>"u"?new p.default:this.options.messageIdProvider,this.outgoingStore=S.outgoingStore||new u.default,this.incomingStore=S.incomingStore||new u.default,this.queueQoSZero=S.queueQoSZero===void 0?!0:S.queueQoSZero,this._resubscribeTopics={},this.messageIdToTopic={},this.keepaliveManager=null,this.connected=!1,this.disconnecting=!1,this.reconnecting=!1,this.queue=[],this.connackTimer=null,this.reconnectTimer=null,this._storeProcessing=!1,this._packetIdsDuringStoreProcessing={},this._storeProcessingQueue=[],this.outgoing={},this._firstConnection=!0,S.properties&&S.properties.topicAliasMaximum>0&&(S.properties.topicAliasMaximum>65535?this.log("MqttClient :: options.properties.topicAliasMaximum is out of range"):this.topicAliasRecv=new y.default(S.properties.topicAliasMaximum)),this.on("connect",()=>{let{queue:I}=this,M=()=>{let O=I.shift();this.log("deliver :: entry %o",O);let B=null;if(!O){this._resubscribe();return}B=O.packet,this.log("deliver :: call _sendPacket for %o",B);let T=!0;B.messageId&&B.messageId!==0&&(this.messageIdProvider.register(B.messageId)||(T=!1)),T?this._sendPacket(B,W=>{O.cb&&O.cb(W),M()}):(this.log("messageId: %d has already used. The message is skipped and removed.",B.messageId),M())};this.log("connect :: sending queued packets"),M()}),this.on("close",()=>{this.log("close :: connected set to `false`"),this.connected=!1,this.log("close :: clearing connackTimer"),clearTimeout(this.connackTimer),this._destroyKeepaliveManager(),this.topicAliasRecv&&this.topicAliasRecv.clear(),this.log("close :: calling _setupReconnect"),this._setupReconnect()}),this.options.manualConnect||(this.log("MqttClient :: setting up stream"),this.connect())}handleAuth(x,S){S()}handleMessage(x,S){S()}_nextId(){return this.messageIdProvider.allocate()}getLastMessageId(){return this.messageIdProvider.getLastAllocated()}connect(){let x=new i.Writable,S=n.default.parser(this.options),I=null,M=[];this.log("connect :: calling method to clear reconnect"),this._clearReconnect(),this.disconnected&&!this.reconnecting&&(this.incomingStore=this.options.incomingStore||new u.default,this.outgoingStore=this.options.outgoingStore||new u.default,this.disconnecting=!1,this.disconnected=!1),this.log("connect :: using streamBuilder provided to client to create stream"),this.stream=this.streamBuilder(this),S.on("packet",F=>{this.log("parser :: on packet push to packets array."),M.push(F)});let O=()=>{this.log("work :: getting next packet in queue");let F=M.shift();if(F)this.log("work :: packet pulled from queue"),(0,d.default)(this,F,B);else{this.log("work :: no packets in queue");let N=I;I=null,this.log("work :: done flag is %s",!!N),N&&N()}},B=()=>{if(M.length)(0,f.nextTick)(O);else{let F=I;I=null,F()}};x._write=(F,N,ae)=>{I=ae,this.log("writable stream :: parsing buffer"),S.parse(F),O()};let T=F=>{this.log("streamErrorHandler :: error",F.message),F.code?(this.log("streamErrorHandler :: emitting error"),this.emit("error",F)):this.noop(F)};this.log("connect :: pipe stream to writable stream"),this.stream.pipe(x),this.stream.on("error",T),this.stream.on("close",()=>{this.log("(%s)stream :: on close",this.options.clientId),this._flushVolatile(),this.log("stream: emit close to MqttClient"),this.emit("close")}),this.log("connect: sending packet `connect`");let W={cmd:"connect",protocolId:this.options.protocolId,protocolVersion:this.options.protocolVersion,clean:this.options.clean,clientId:this.options.clientId,keepalive:this.options.keepalive,username:this.options.username,password:this.options.password,properties:this.options.properties};if(this.options.will&&(W.will={...this.options.will,payload:this.options.will?.payload}),this.topicAliasRecv&&(W.properties||(W.properties={}),this.topicAliasRecv&&(W.properties.topicAliasMaximum=this.topicAliasRecv.max)),this._writePacket(W),S.on("error",this.emit.bind(this,"error")),this.options.properties){if(!this.options.properties.authenticationMethod&&this.options.properties.authenticationData)return this.end(()=>this.emit("error",new Error("Packet has no Authentication Method"))),this;if(this.options.properties.authenticationMethod&&this.options.authPacket&&typeof this.options.authPacket=="object"){let F={cmd:"auth",reasonCode:0,...this.options.authPacket};this._writePacket(F)}}return this.stream.setMaxListeners(1e3),clearTimeout(this.connackTimer),this.connackTimer=setTimeout(()=>{this.log("!!connectTimeout hit!! Calling _cleanUp with force `true`"),this.emit("error",new Error("connack timeout")),this._cleanUp(!0)},this.options.connectTimeout),this}publish(x,S,I,M){this.log("publish :: message `%s` to topic `%s`",S,x);let{options:O}=this;typeof I=="function"&&(M=I,I=null),I=I||{},I={qos:0,retain:!1,dup:!1,...I};let{qos:B,retain:T,dup:W,properties:F,cbStorePut:N}=I;if(this._checkDisconnecting(M))return this;let ae=()=>{let Y=0;if((B===1||B===2)&&(Y=this._nextId(),Y===null))return this.log("No messageId left"),!1;let K={cmd:"publish",topic:x,payload:S,qos:B,retain:T,messageId:Y,dup:W};switch(O.protocolVersion===5&&(K.properties=F),this.log("publish :: qos",B),B){case 1:case 2:this.outgoing[K.messageId]={volatile:!1,cb:M||this.noop},this.log("MqttClient:publish: packet cmd: %s",K.cmd),this._sendPacket(K,void 0,N);break;default:this.log("MqttClient:publish: packet cmd: %s",K.cmd),this._sendPacket(K,M,N);break}return!0};return(this._storeProcessing||this._storeProcessingQueue.length>0||!ae())&&this._storeProcessingQueue.push({invoke:ae,cbStorePut:I.cbStorePut,callback:M}),this}publishAsync(x,S,I){return new Promise((M,O)=>{this.publish(x,S,I,(B,T)=>{B?O(B):M(T)})})}subscribe(x,S,I){let M=this.options.protocolVersion;typeof S=="function"&&(I=S),I=I||this.noop;let O=!1,B=[];typeof x=="string"?(x=[x],B=x):Array.isArray(x)?B=x:typeof x=="object"&&(O=x.resubscribe,delete x.resubscribe,B=Object.keys(x));let T=l.validateTopics(B);if(T!==null)return m(I,new Error(`Invalid topic ${T}`)),this;if(this._checkDisconnecting(I))return this.log("subscribe: discconecting true"),this;let W={qos:0};M===5&&(W.nl=!1,W.rap=!1,W.rh=0),S={...W,...S};let{properties:F}=S,N=[],ae=(re,D)=>{if(D=D||S,!Object.prototype.hasOwnProperty.call(this._resubscribeTopics,re)||this._resubscribeTopics[re].qos<D.qos||O){let Z={topic:re,qos:D.qos};M===5&&(Z.nl=D.nl,Z.rap=D.rap,Z.rh=D.rh,Z.properties=F),this.log("subscribe: pushing topic `%s` and qos `%s` to subs list",Z.topic,Z.qos),N.push(Z)}};if(Array.isArray(x)?x.forEach(re=>{this.log("subscribe: array topic %s",re),ae(re)}):Object.keys(x).forEach(re=>{this.log("subscribe: object topic %s, %o",re,x[re]),ae(re,x[re])}),!N.length)return I(null,[]),this;let Y=(re,D)=>{let Z={cmd:"subscribe",subscriptions:re,messageId:D};if(F&&(Z.properties=F),this.options.resubscribe){this.log("subscribe :: resubscribe true");let J=[];re.forEach(be=>{if(this.options.reconnectPeriod>0){let te={qos:be.qos};M===5&&(te.nl=be.nl||!1,te.rap=be.rap||!1,te.rh=be.rh||0,te.properties=be.properties),this._resubscribeTopics[be.topic]=te,J.push(be.topic)}}),this.messageIdToTopic[Z.messageId]=J}let P=new Promise((J,be)=>{this.outgoing[Z.messageId]={volatile:!0,cb(te,we){if(!te){let{granted:V}=we;for(let L=0;L<V.length;L+=1)re[L].qos=V[L]}te?be(new f.ErrorWithSubackPacket(te.message,we)):J(we)}}});return this.log("subscribe :: call _sendPacket"),this._sendPacket(Z),P},K=()=>{let re=this.options.subscribeBatchSize??N.length,D=[];for(let Z=0;Z<N.length;Z+=re){let P=N.slice(Z,Z+re),J=this._nextId();if(J===null)return this.log("No messageId left"),!1;D.push(Y(P,J))}return Promise.all(D).then(Z=>{I(null,N,Z.at(-1))}).catch(Z=>{I(Z,N,Z.packet)}),!0};return(this._storeProcessing||this._storeProcessingQueue.length>0||!K())&&this._storeProcessingQueue.push({invoke:K,callback:I}),this}subscribeAsync(x,S){return new Promise((I,M)=>{this.subscribe(x,S,(O,B)=>{O?M(O):I(B)})})}unsubscribe(x,S,I){typeof x=="string"&&(x=[x]),typeof S=="function"&&(I=S),I=I||this.noop;let M=l.validateTopics(x);if(M!==null)return m(I,new Error(`Invalid topic ${M}`)),this;if(this._checkDisconnecting(I))return this;let O=()=>{let B=this._nextId();if(B===null)return this.log("No messageId left"),!1;let T={cmd:"unsubscribe",messageId:B,unsubscriptions:[]};return typeof x=="string"?T.unsubscriptions=[x]:Array.isArray(x)&&(T.unsubscriptions=x),this.options.resubscribe&&T.unsubscriptions.forEach(W=>{delete this._resubscribeTopics[W]}),typeof S=="object"&&S.properties&&(T.properties=S.properties),this.outgoing[T.messageId]={volatile:!0,cb:I},this.log("unsubscribe: call _sendPacket"),this._sendPacket(T),!0};return(this._storeProcessing||this._storeProcessingQueue.length>0||!O())&&this._storeProcessingQueue.push({invoke:O,callback:I}),this}unsubscribeAsync(x,S){return new Promise((I,M)=>{this.unsubscribe(x,S,(O,B)=>{O?M(O):I(B)})})}end(x,S,I){this.log("end :: (%s)",this.options.clientId),(x==null||typeof x!="boolean")&&(I=I||S,S=x,x=!1),typeof S!="object"&&(I=I||S,S=null),this.log("end :: cb? %s",!!I),(!I||typeof I!="function")&&(I=this.noop);let M=()=>{this.log("end :: closeStores: closing incoming and outgoing stores"),this.disconnected=!0,this.incomingStore.close(B=>{this.outgoingStore.close(T=>{if(this.log("end :: closeStores: emitting end"),this.emit("end"),I){let W=B||T;this.log("end :: closeStores: invoking callback with args"),I(W)}})}),this._deferredReconnect?this._deferredReconnect():(this.options.reconnectPeriod===0||this.options.manualConnect)&&(this.disconnecting=!1)},O=()=>{this.log("end :: (%s) :: finish :: calling _cleanUp with force %s",this.options.clientId,x),this._cleanUp(x,()=>{this.log("end :: finish :: calling process.nextTick on closeStores"),(0,f.nextTick)(M)},S)};return this.disconnecting?(I(),this):(this._clearReconnect(),this.disconnecting=!0,!x&&Object.keys(this.outgoing).length>0?(this.log("end :: (%s) :: calling finish in 10ms once outgoing is empty",this.options.clientId),this.once("outgoingEmpty",setTimeout.bind(null,O,10))):(this.log("end :: (%s) :: immediately calling finish",this.options.clientId),O()),this)}endAsync(x,S){return new Promise((I,M)=>{this.end(x,S,O=>{O?M(O):I()})})}removeOutgoingMessage(x){if(this.outgoing[x]){let{cb:S}=this.outgoing[x];this._removeOutgoingAndStoreMessage(x,()=>{S(new Error("Message removed"))})}return this}reconnect(x){this.log("client reconnect");let S=()=>{x?(this.options.incomingStore=x.incomingStore,this.options.outgoingStore=x.outgoingStore):(this.options.incomingStore=null,this.options.outgoingStore=null),this.incomingStore=this.options.incomingStore||new u.default,this.outgoingStore=this.options.outgoingStore||new u.default,this.disconnecting=!1,this.disconnected=!1,this._deferredReconnect=null,this._reconnect()};return this.disconnecting&&!this.disconnected?this._deferredReconnect=S:S(),this}_flushVolatile(){this.outgoing&&(this.log("_flushVolatile :: deleting volatile messages from the queue and setting their callbacks as error function"),Object.keys(this.outgoing).forEach(x=>{this.outgoing[x].volatile&&typeof this.outgoing[x].cb=="function"&&(this.outgoing[x].cb(new Error("Connection closed")),delete this.outgoing[x])}))}_flush(){this.outgoing&&(this.log("_flush: queue exists? %b",!!this.outgoing),Object.keys(this.outgoing).forEach(x=>{typeof this.outgoing[x].cb=="function"&&(this.outgoing[x].cb(new Error("Connection closed")),delete this.outgoing[x])}))}_removeTopicAliasAndRecoverTopicName(x){let S;x.properties&&(S=x.properties.topicAlias);let I=x.topic.toString();if(this.log("_removeTopicAliasAndRecoverTopicName :: alias %d, topic %o",S,I),I.length===0){if(typeof S>"u")return new Error("Unregistered Topic Alias");if(I=this.topicAliasSend.getTopicByAlias(S),typeof I>"u")return new Error("Unregistered Topic Alias");x.topic=I}S&&delete x.properties.topicAlias}_checkDisconnecting(x){return this.disconnecting&&(x&&x!==this.noop?x(new Error("client disconnecting")):this.emit("error",new Error("client disconnecting"))),this.disconnecting}_reconnect(){this.log("_reconnect: emitting reconnect to client"),this.emit("reconnect"),this.connected?(this.end(()=>{this.connect()}),this.log("client already connected. disconnecting first.")):(this.log("_reconnect: calling connect"),this.connect())}_setupReconnect(){!this.disconnecting&&!this.reconnectTimer&&this.options.reconnectPeriod>0?(this.reconnecting||(this.log("_setupReconnect :: emit `offline` state"),this.emit("offline"),this.log("_setupReconnect :: set `reconnecting` to `true`"),this.reconnecting=!0),this.log("_setupReconnect :: setting reconnectTimer for %d ms",this.options.reconnectPeriod),this.reconnectTimer=setInterval(()=>{this.log("reconnectTimer :: reconnect triggered!"),this._reconnect()},this.options.reconnectPeriod)):this.log("_setupReconnect :: doing nothing...")}_clearReconnect(){this.log("_clearReconnect : clearing reconnect timer"),this.reconnectTimer&&(clearInterval(this.reconnectTimer),this.reconnectTimer=null)}_cleanUp(x,S,I={}){if(S&&(this.log("_cleanUp :: done callback provided for on stream close"),this.stream.on("close",S)),this.log("_cleanUp :: forced? %s",x),x)this.options.reconnectPeriod===0&&this.options.clean&&this._flush(),this.log("_cleanUp :: (%s) :: destroying stream",this.options.clientId),this.stream.destroy();else{let M={cmd:"disconnect",...I};this.log("_cleanUp :: (%s) :: call _sendPacket with disconnect packet",this.options.clientId),this._sendPacket(M,()=>{this.log("_cleanUp :: (%s) :: destroying stream",this.options.clientId),m(()=>{this.stream.end(()=>{this.log("_cleanUp :: (%s) :: stream destroyed",this.options.clientId)})})})}!this.disconnecting&&!this.reconnecting&&(this.log("_cleanUp :: client not disconnecting/reconnecting. Clearing and resetting reconnect."),this._clearReconnect(),this._setupReconnect()),this._destroyKeepaliveManager(),S&&!this.connected&&(this.log("_cleanUp :: (%s) :: removing stream `done` callback `close` listener",this.options.clientId),this.stream.removeListener("close",S),S())}_storeAndSend(x,S,I){this.log("storeAndSend :: store packet with cmd %s to outgoingStore",x.cmd);let M=x,O;if(M.cmd==="publish"&&(M=(0,s.default)(x),O=this._removeTopicAliasAndRecoverTopicName(M),O))return S&&S(O);this.outgoingStore.put(M,B=>{if(B)return S&&S(B);I(),this._writePacket(x,S)})}_applyTopicAlias(x){if(this.options.protocolVersion===5&&x.cmd==="publish"){let S;x.properties&&(S=x.properties.topicAlias);let I=x.topic.toString();if(this.topicAliasSend)if(S){if(I.length!==0&&(this.log("applyTopicAlias :: register topic: %s - alias: %d",I,S),!this.topicAliasSend.put(I,S)))return this.log("applyTopicAlias :: error out of range. topic: %s - alias: %d",I,S),new Error("Sending Topic Alias out of range")}else I.length!==0&&(this.options.autoAssignTopicAlias?(S=this.topicAliasSend.getAliasByTopic(I),S?(x.topic="",x.properties={...x.properties,topicAlias:S},this.log("applyTopicAlias :: auto assign(use) topic: %s - alias: %d",I,S)):(S=this.topicAliasSend.getLruAlias(),this.topicAliasSend.put(I,S),x.properties={...x.properties,topicAlias:S},this.log("applyTopicAlias :: auto assign topic: %s - alias: %d",I,S))):this.options.autoUseTopicAlias&&(S=this.topicAliasSend.getAliasByTopic(I),S&&(x.topic="",x.properties={...x.properties,topicAlias:S},this.log("applyTopicAlias :: auto use topic: %s - alias: %d",I,S))));else if(S)return this.log("applyTopicAlias :: error out of range. topic: %s - alias: %d",I,S),new Error("Sending Topic Alias out of range")}}_noop(x){this.log("noop ::",x)}_writePacket(x,S){this.log("_writePacket :: packet: %O",x),this.log("_writePacket :: emitting `packetsend`"),this.emit("packetsend",x),this.log("_writePacket :: writing to stream");let I=n.default.writeToStream(x,this.stream,this.options);this.log("_writePacket :: writeToStream result %s",I),!I&&S&&S!==this.noop?(this.log("_writePacket :: handle events on `drain` once through callback."),this.stream.once("drain",S)):S&&(this.log("_writePacket :: invoking cb"),S())}_sendPacket(x,S,I,M){this.log("_sendPacket :: (%s) :: start",this.options.clientId),I=I||this.noop,S=S||this.noop;let O=this._applyTopicAlias(x);if(O){S(O);return}if(!this.connected){if(x.cmd==="auth"){this._writePacket(x,S);return}this.log("_sendPacket :: client not connected. Storing packet offline."),this._storePacket(x,S,I);return}if(M){this._writePacket(x,S);return}switch(x.cmd){case"publish":break;case"pubrel":this._storeAndSend(x,S,I);return;default:this._writePacket(x,S);return}switch(x.qos){case 2:case 1:this._storeAndSend(x,S,I);break;default:this._writePacket(x,S);break}this.log("_sendPacket :: (%s) :: end",this.options.clientId)}_storePacket(x,S,I){this.log("_storePacket :: packet: %o",x),this.log("_storePacket :: cb? %s",!!S),I=I||this.noop;let M=x;if(M.cmd==="publish"){M=(0,s.default)(x);let B=this._removeTopicAliasAndRecoverTopicName(M);if(B)return S&&S(B)}let O=M.qos||0;O===0&&this.queueQoSZero||M.cmd!=="publish"?this.queue.push({packet:M,cb:S}):O>0?(S=this.outgoing[M.messageId]?this.outgoing[M.messageId].cb:null,this.outgoingStore.put(M,B=>{if(B)return S&&S(B);I()})):S&&S(new Error("No connection to broker"))}_setupKeepaliveManager(){this.log("_setupKeepaliveManager :: keepalive %d (seconds)",this.options.keepalive),!this.keepaliveManager&&this.options.keepalive&&(this.keepaliveManager=new b.default(this,this.options.timerVariant))}_destroyKeepaliveManager(){this.keepaliveManager&&(this.log("_destroyKeepaliveManager :: destroying keepalive manager"),this.keepaliveManager.destroy(),this.keepaliveManager=null)}reschedulePing(x=!1){this.keepaliveManager&&this.options.keepalive&&(x||this.options.reschedulePings)&&this._reschedulePing()}_reschedulePing(){this.log("_reschedulePing :: rescheduling ping"),this.keepaliveManager.reschedule()}sendPing(){this.log("_sendPing :: sending pingreq"),this._sendPacket({cmd:"pingreq"})}onKeepaliveTimeout(){this.emit("error",new Error("Keepalive timeout")),this.log("onKeepaliveTimeout :: calling _cleanUp with force true"),this._cleanUp(!0)}_resubscribe(){this.log("_resubscribe");let x=Object.keys(this._resubscribeTopics);if(!this._firstConnection&&(this.options.clean||this.options.protocolVersion>=4&&!this.connackPacket.sessionPresent)&&x.length>0)if(this.options.resubscribe)if(this.options.protocolVersion===5){this.log("_resubscribe: protocolVersion 5");for(let S=0;S<x.length;S++){let I={};I[x[S]]=this._resubscribeTopics[x[S]],I.resubscribe=!0,this.subscribe(I,{properties:I[x[S]].properties})}}else this._resubscribeTopics.resubscribe=!0,this.subscribe(this._resubscribeTopics);else this._resubscribeTopics={};this._firstConnection=!1}_onConnect(x){if(this.disconnected){this.emit("connect",x);return}this.connackPacket=x,this.messageIdProvider.clear(),this._setupKeepaliveManager(),this.connected=!0;let S=()=>{let I=this.outgoingStore.createStream(),M=()=>{I.destroy(),I=null,this._flushStoreProcessingQueue(),O()},O=()=>{this._storeProcessing=!1,this._packetIdsDuringStoreProcessing={}};this.once("close",M),I.on("error",T=>{O(),this._flushStoreProcessingQueue(),this.removeListener("close",M),this.emit("error",T)});let B=()=>{if(!I)return;let T=I.read(1),W;if(!T){I.once("readable",B);return}if(this._storeProcessing=!0,this._packetIdsDuringStoreProcessing[T.messageId]){B();return}!this.disconnecting&&!this.reconnectTimer?(W=this.outgoing[T.messageId]?this.outgoing[T.messageId].cb:null,this.outgoing[T.messageId]={volatile:!1,cb(F,N){W&&W(F,N),B()}},this._packetIdsDuringStoreProcessing[T.messageId]=!0,this.messageIdProvider.register(T.messageId)?this._sendPacket(T,void 0,void 0,!0):this.log("messageId: %d has already used.",T.messageId)):I.destroy&&I.destroy()};I.on("end",()=>{let T=!0;for(let W in this._packetIdsDuringStoreProcessing)if(!this._packetIdsDuringStoreProcessing[W]){T=!1;break}this.removeListener("close",M),T?(O(),this._invokeAllStoreProcessingQueue(),this.emit("connect",x)):S()}),B()};S()}_invokeStoreProcessingQueue(){if(!this._storeProcessing&&this._storeProcessingQueue.length>0){let x=this._storeProcessingQueue[0];if(x&&x.invoke())return this._storeProcessingQueue.shift(),!0}return!1}_invokeAllStoreProcessingQueue(){for(;this._invokeStoreProcessingQueue(););}_flushStoreProcessingQueue(){for(let x of this._storeProcessingQueue)x.cbStorePut&&x.cbStorePut(new Error("Connection closed")),x.callback&&x.callback(new Error("Connection closed"));this._storeProcessingQueue.splice(0)}_removeOutgoingAndStoreMessage(x,S){delete this.outgoing[x],this.outgoingStore.del({messageId:x},(I,M)=>{S(I,M),this.messageIdProvider.deallocate(x),this._invokeStoreProcessingQueue()})}};c.default=E}),yu=pe(c=>{le(),ue(),ce(),Object.defineProperty(c,"__esModule",{value:!0});var e=os(),t=class{numberAllocator;lastId;constructor(){this.numberAllocator=new e.NumberAllocator(1,65535)}allocate(){return this.lastId=this.numberAllocator.alloc(),this.lastId}getLastAllocated(){return this.lastId}register(r){return this.numberAllocator.use(r)}deallocate(r){this.numberAllocator.free(r)}clear(){this.numberAllocator.clear()}};c.default=t});function vu(){if(si)return cr;si=!0;let c=2147483647,e=36,t=1,r=26,a=38,n=700,i=72,s=128,o="-",l=/^xn--/,u=/[^\0-\x7F]/,d=/[\x2E\u3002\uFF0E\uFF61]/g,p={overflow:"Overflow: input needs wider integers to process","not-basic":"Illegal input >= 0x80 (not a basic code point)","invalid-input":"Invalid input"},y=e-t,f=Math.floor,g=String.fromCharCode;function b(O){throw new RangeError(p[O])}function k(O,B){let T=[],W=O.length;for(;W--;)T[W]=B(O[W]);return T}function m(O,B){let T=O.split("@"),W="";T.length>1&&(W=T[0]+"@",O=T[1]),O=O.replace(d,".");let F=O.split("."),N=k(F,B).join(".");return W+N}function w(O){let B=[],T=0,W=O.length;for(;T<W;){let F=O.charCodeAt(T++);if(F>=55296&&F<=56319&&T<W){let N=O.charCodeAt(T++);(N&64512)==56320?B.push(((F&1023)<<10)+(N&1023)+65536):(B.push(F),T--)}else B.push(F)}return B}let E=O=>String.fromCodePoint(...O),v=function(O){return O>=48&&O<58?26+(O-48):O>=65&&O<91?O-65:O>=97&&O<123?O-97:e},x=function(O,B){return O+22+75*(O<26)-((B!=0)<<5)},S=function(O,B,T){let W=0;for(O=T?f(O/n):O>>1,O+=f(O/B);O>y*r>>1;W+=e)O=f(O/y);return f(W+(y+1)*O/(O+a))},I=function(O){let B=[],T=O.length,W=0,F=s,N=i,ae=O.lastIndexOf(o);ae<0&&(ae=0);for(let Y=0;Y<ae;++Y)O.charCodeAt(Y)>=128&&b("not-basic"),B.push(O.charCodeAt(Y));for(let Y=ae>0?ae+1:0;Y<T;){let K=W;for(let D=1,Z=e;;Z+=e){Y>=T&&b("invalid-input");let P=v(O.charCodeAt(Y++));P>=e&&b("invalid-input"),P>f((c-W)/D)&&b("overflow"),W+=P*D;let J=Z<=N?t:Z>=N+r?r:Z-N;if(P<J)break;let be=e-J;D>f(c/be)&&b("overflow"),D*=be}let re=B.length+1;N=S(W-K,re,K==0),f(W/re)>c-F&&b("overflow"),F+=f(W/re),W%=re,B.splice(W++,0,F)}return String.fromCodePoint(...B)},M=function(O){let B=[];O=w(O);let T=O.length,W=s,F=0,N=i;for(let K of O)K<128&&B.push(g(K));let ae=B.length,Y=ae;for(ae&&B.push(o);Y<T;){let K=c;for(let D of O)D>=W&&D<K&&(K=D);let re=Y+1;K-W>f((c-F)/re)&&b("overflow"),F+=(K-W)*re,W=K;for(let D of O)if(D<W&&++F>c&&b("overflow"),D===W){let Z=F;for(let P=e;;P+=e){let J=P<=N?t:P>=N+r?r:P-N;if(Z<J)break;let be=Z-J,te=e-J;B.push(g(x(J+be%te,0))),Z=f(be/te)}B.push(g(x(Z,0))),N=S(F,re,Y===ae),F=0,++Y}++F,++W}return B.join("")};return cr={version:"2.3.1",ucs2:{decode:w,encode:E},decode:I,encode:M,toASCII:function(O){return m(O,function(B){return u.test(B)?"xn--"+M(B):B})},toUnicode:function(O){return m(O,function(B){return l.test(B)?I(B.slice(4).toLowerCase()):B})}},cr}var cr,si,mt,wu=He(()=>{le(),ue(),ce(),cr={},si=!1,mt=vu(),mt.decode,mt.encode,mt.toASCII,mt.toUnicode,mt.ucs2,mt.version});function _u(){return ui||(ui=!0,ci=function(){if(typeof Symbol!="function"||typeof Object.getOwnPropertySymbols!="function")return!1;if(typeof Symbol.iterator=="symbol")return!0;var c={},e=Symbol("test"),t=Object(e);if(typeof e=="string"||Object.prototype.toString.call(e)!=="[object Symbol]"||Object.prototype.toString.call(t)!=="[object Symbol]")return!1;var r=42;c[e]=r;for(e in c)return!1;if(typeof Object.keys=="function"&&Object.keys(c).length!==0||typeof Object.getOwnPropertyNames=="function"&&Object.getOwnPropertyNames(c).length!==0)return!1;var a=Object.getOwnPropertySymbols(c);if(a.length!==1||a[0]!==e||!Object.prototype.propertyIsEnumerable.call(c,e))return!1;if(typeof Object.getOwnPropertyDescriptor=="function"){var n=Object.getOwnPropertyDescriptor(c,e);if(n.value!==r||n.enumerable!==!0)return!1}return!0}),ci}function ku(){return fi||(fi=!0,hi=Error),hi}function Su(){return pi||(pi=!0,di=EvalError),di}function Eu(){return mi||(mi=!0,gi=RangeError),gi}function xu(){return yi||(yi=!0,bi=ReferenceError),bi}function ps(){return wi||(wi=!0,vi=SyntaxError),vi}function Kt(){return ki||(ki=!0,_i=TypeError),_i}function Au(){return Ei||(Ei=!0,Si=URIError),Si}function Iu(){if(xi)return ur;xi=!0;var c=typeof Symbol<"u"&&Symbol,e=_u();return ur=function(){return typeof c!="function"||typeof Symbol!="function"||typeof c("foo")!="symbol"||typeof Symbol("bar")!="symbol"?!1:e()},ur}function Tu(){if(Ai)return hr;Ai=!0;var c={__proto__:null,foo:{}},e=Object;return hr=function(){return{__proto__:c}.foo===c.foo&&!(c instanceof e)},hr}function Cu(){if(Ii)return fr;Ii=!0;var c="Function.prototype.bind called on incompatible ",e=Object.prototype.toString,t=Math.max,r="[object Function]",a=function(s,o){for(var l=[],u=0;u<s.length;u+=1)l[u]=s[u];for(var d=0;d<o.length;d+=1)l[d+s.length]=o[d];return l},n=function(s,o){for(var l=[],u=o,d=0;u<s.length;u+=1,d+=1)l[d]=s[u];return l},i=function(s,o){for(var l="",u=0;u<s.length;u+=1)l+=s[u],u+1<s.length&&(l+=o);return l};return fr=function(s){var o=this;if(typeof o!="function"||e.apply(o)!==r)throw new TypeError(c+o);for(var l=n(arguments,1),u,d=function(){if(this instanceof u){var b=o.apply(this,a(l,arguments));return Object(b)===b?b:this}return o.apply(s,a(l,arguments))},p=t(0,o.length-l.length),y=[],f=0;f<p;f++)y[f]="$"+f;if(u=Function("binder","return function ("+i(y,",")+"){ return binder.apply(this,arguments); }")(d),o.prototype){var g=function(){};g.prototype=o.prototype,u.prototype=new g,g.prototype=null}return u},fr}function ai(){if(Ti)return dr;Ti=!0;var c=Cu();return dr=Function.prototype.bind||c,dr}function Ou(){if(Ci)return pr;Ci=!0;var c=Function.prototype.call,e=Object.prototype.hasOwnProperty,t=ai();return pr=t.call(c,e),pr}function jt(){if(Oi)return gr;Oi=!0;var c,e=ku(),t=Su(),r=Eu(),a=xu(),n=ps(),i=Kt(),s=Au(),o=Function,l=function(Y){try{return o('"use strict"; return ('+Y+").constructor;")()}catch{}},u=Object.getOwnPropertyDescriptor;if(u)try{u({},"")}catch{u=null}var d=function(){throw new i},p=u?(function(){try{return arguments.callee,d}catch{try{return u(arguments,"callee").get}catch{return d}}})():d,y=Iu()(),f=Tu()(),g=Object.getPrototypeOf||(f?function(Y){return Y.__proto__}:null),b={},k=typeof Uint8Array>"u"||!g?c:g(Uint8Array),m={__proto__:null,"%AggregateError%":typeof AggregateError>"u"?c:AggregateError,"%Array%":Array,"%ArrayBuffer%":typeof ArrayBuffer>"u"?c:ArrayBuffer,"%ArrayIteratorPrototype%":y&&g?g([][Symbol.iterator]()):c,"%AsyncFromSyncIteratorPrototype%":c,"%AsyncFunction%":b,"%AsyncGenerator%":b,"%AsyncGeneratorFunction%":b,"%AsyncIteratorPrototype%":b,"%Atomics%":typeof Atomics>"u"?c:Atomics,"%BigInt%":typeof BigInt>"u"?c:BigInt,"%BigInt64Array%":typeof BigInt64Array>"u"?c:BigInt64Array,"%BigUint64Array%":typeof BigUint64Array>"u"?c:BigUint64Array,"%Boolean%":Boolean,"%DataView%":typeof DataView>"u"?c:DataView,"%Date%":Date,"%decodeURI%":decodeURI,"%decodeURIComponent%":decodeURIComponent,"%encodeURI%":encodeURI,"%encodeURIComponent%":encodeURIComponent,"%Error%":e,"%eval%":eval,"%EvalError%":t,"%Float32Array%":typeof Float32Array>"u"?c:Float32Array,"%Float64Array%":typeof Float64Array>"u"?c:Float64Array,"%FinalizationRegistry%":typeof FinalizationRegistry>"u"?c:FinalizationRegistry,"%Function%":o,"%GeneratorFunction%":b,"%Int8Array%":typeof Int8Array>"u"?c:Int8Array,"%Int16Array%":typeof Int16Array>"u"?c:Int16Array,"%Int32Array%":typeof Int32Array>"u"?c:Int32Array,"%isFinite%":isFinite,"%isNaN%":isNaN,"%IteratorPrototype%":y&&g?g(g([][Symbol.iterator]())):c,"%JSON%":typeof JSON=="object"?JSON:c,"%Map%":typeof Map>"u"?c:Map,"%MapIteratorPrototype%":typeof Map>"u"||!y||!g?c:g(new Map()[Symbol.iterator]()),"%Math%":Math,"%Number%":Number,"%Object%":Object,"%parseFloat%":parseFloat,"%parseInt%":parseInt,"%Promise%":typeof Promise>"u"?c:Promise,"%Proxy%":typeof Proxy>"u"?c:Proxy,"%RangeError%":r,"%ReferenceError%":a,"%Reflect%":typeof Reflect>"u"?c:Reflect,"%RegExp%":RegExp,"%Set%":typeof Set>"u"?c:Set,"%SetIteratorPrototype%":typeof Set>"u"||!y||!g?c:g(new Set()[Symbol.iterator]()),"%SharedArrayBuffer%":typeof SharedArrayBuffer>"u"?c:SharedArrayBuffer,"%String%":String,"%StringIteratorPrototype%":y&&g?g(""[Symbol.iterator]()):c,"%Symbol%":y?Symbol:c,"%SyntaxError%":n,"%ThrowTypeError%":p,"%TypedArray%":k,"%TypeError%":i,"%Uint8Array%":typeof Uint8Array>"u"?c:Uint8Array,"%Uint8ClampedArray%":typeof Uint8ClampedArray>"u"?c:Uint8ClampedArray,"%Uint16Array%":typeof Uint16Array>"u"?c:Uint16Array,"%Uint32Array%":typeof Uint32Array>"u"?c:Uint32Array,"%URIError%":s,"%WeakMap%":typeof WeakMap>"u"?c:WeakMap,"%WeakRef%":typeof WeakRef>"u"?c:WeakRef,"%WeakSet%":typeof WeakSet>"u"?c:WeakSet};if(g)try{null.error}catch(Y){var w=g(g(Y));m["%Error.prototype%"]=w}var E=function Y(K){var re;if(K==="%AsyncFunction%")re=l("async function () {}");else if(K==="%GeneratorFunction%")re=l("function* () {}");else if(K==="%AsyncGeneratorFunction%")re=l("async function* () {}");else if(K==="%AsyncGenerator%"){var D=Y("%AsyncGeneratorFunction%");D&&(re=D.prototype)}else if(K==="%AsyncIteratorPrototype%"){var Z=Y("%AsyncGenerator%");Z&&g&&(re=g(Z.prototype))}return m[K]=re,re},v={__proto__:null,"%ArrayBufferPrototype%":["ArrayBuffer","prototype"],"%ArrayPrototype%":["Array","prototype"],"%ArrayProto_entries%":["Array","prototype","entries"],"%ArrayProto_forEach%":["Array","prototype","forEach"],"%ArrayProto_keys%":["Array","prototype","keys"],"%ArrayProto_values%":["Array","prototype","values"],"%AsyncFunctionPrototype%":["AsyncFunction","prototype"],"%AsyncGenerator%":["AsyncGeneratorFunction","prototype"],"%AsyncGeneratorPrototype%":["AsyncGeneratorFunction","prototype","prototype"],"%BooleanPrototype%":["Boolean","prototype"],"%DataViewPrototype%":["DataView","prototype"],"%DatePrototype%":["Date","prototype"],"%ErrorPrototype%":["Error","prototype"],"%EvalErrorPrototype%":["EvalError","prototype"],"%Float32ArrayPrototype%":["Float32Array","prototype"],"%Float64ArrayPrototype%":["Float64Array","prototype"],"%FunctionPrototype%":["Function","prototype"],"%Generator%":["GeneratorFunction","prototype"],"%GeneratorPrototype%":["GeneratorFunction","prototype","prototype"],"%Int8ArrayPrototype%":["Int8Array","prototype"],"%Int16ArrayPrototype%":["Int16Array","prototype"],"%Int32ArrayPrototype%":["Int32Array","prototype"],"%JSONParse%":["JSON","parse"],"%JSONStringify%":["JSON","stringify"],"%MapPrototype%":["Map","prototype"],"%NumberPrototype%":["Number","prototype"],"%ObjectPrototype%":["Object","prototype"],"%ObjProto_toString%":["Object","prototype","toString"],"%ObjProto_valueOf%":["Object","prototype","valueOf"],"%PromisePrototype%":["Promise","prototype"],"%PromiseProto_then%":["Promise","prototype","then"],"%Promise_all%":["Promise","all"],"%Promise_reject%":["Promise","reject"],"%Promise_resolve%":["Promise","resolve"],"%RangeErrorPrototype%":["RangeError","prototype"],"%ReferenceErrorPrototype%":["ReferenceError","prototype"],"%RegExpPrototype%":["RegExp","prototype"],"%SetPrototype%":["Set","prototype"],"%SharedArrayBufferPrototype%":["SharedArrayBuffer","prototype"],"%StringPrototype%":["String","prototype"],"%SymbolPrototype%":["Symbol","prototype"],"%SyntaxErrorPrototype%":["SyntaxError","prototype"],"%TypedArrayPrototype%":["TypedArray","prototype"],"%TypeErrorPrototype%":["TypeError","prototype"],"%Uint8ArrayPrototype%":["Uint8Array","prototype"],"%Uint8ClampedArrayPrototype%":["Uint8ClampedArray","prototype"],"%Uint16ArrayPrototype%":["Uint16Array","prototype"],"%Uint32ArrayPrototype%":["Uint32Array","prototype"],"%URIErrorPrototype%":["URIError","prototype"],"%WeakMapPrototype%":["WeakMap","prototype"],"%WeakSetPrototype%":["WeakSet","prototype"]},x=ai(),S=Ou(),I=x.call(Function.call,Array.prototype.concat),M=x.call(Function.apply,Array.prototype.splice),O=x.call(Function.call,String.prototype.replace),B=x.call(Function.call,String.prototype.slice),T=x.call(Function.call,RegExp.prototype.exec),W=/[^%.[\]]+|\[(?:(-?\d+(?:\.\d+)?)|(["'])((?:(?!\2)[^\\]|\\.)*?)\2)\]|(?=(?:\.|\[\])(?:\.|\[\]|%$))/g,F=/\\(\\)?/g,N=function(Y){var K=B(Y,0,1),re=B(Y,-1);if(K==="%"&&re!=="%")throw new n("invalid intrinsic syntax, expected closing `%`");if(re==="%"&&K!=="%")throw new n("invalid intrinsic syntax, expected opening `%`");var D=[];return O(Y,W,function(Z,P,J,be){D[D.length]=J?O(be,F,"$1"):P||Z}),D},ae=function(Y,K){var re=Y,D;if(S(v,re)&&(D=v[re],re="%"+D[0]+"%"),S(m,re)){var Z=m[re];if(Z===b&&(Z=E(re)),typeof Z>"u"&&!K)throw new i("intrinsic "+Y+" exists, but is not available. Please file an issue!");return{alias:D,name:re,value:Z}}throw new n("intrinsic "+Y+" does not exist!")};return gr=function(Y,K){if(typeof Y!="string"||Y.length===0)throw new i("intrinsic name must be a non-empty string");if(arguments.length>1&&typeof K!="boolean")throw new i('"allowMissing" argument must be a boolean');if(T(/^%?[^%]*%?$/,Y)===null)throw new n("`%` may not be present anywhere but at the beginning and end of the intrinsic name");var re=N(Y),D=re.length>0?re[0]:"",Z=ae("%"+D+"%",K),P=Z.name,J=Z.value,be=!1,te=Z.alias;te&&(D=te[0],M(re,I([0,1],te)));for(var we=1,V=!0;we<re.length;we+=1){var L=re[we],ne=B(L,0,1),H=B(L,-1);if((ne==='"'||ne==="'"||ne==="`"||H==='"'||H==="'"||H==="`")&&ne!==H)throw new n("property names with quotes must have matching quotes");if((L==="constructor"||!V)&&(be=!0),D+="."+L,P="%"+D+"%",S(m,P))J=m[P];else if(J!=null){if(!(L in J)){if(!K)throw new i("base intrinsic for "+Y+" exists, but the property is not available.");return}if(u&&we+1>=re.length){var G=u(J,L);V=!!G,V&&"get"in G&&!("originalValue"in G.get)?J=G.get:J=J[L]}else V=S(J,L),J=J[L];V&&!be&&(m[P]=J)}}return J},gr}function li(){if(Pi)return mr;Pi=!0;var c=jt(),e=c("%Object.defineProperty%",!0)||!1;if(e)try{e({},"a",{value:1})}catch{e=!1}return mr=e,mr}function gs(){if(Mi)return br;Mi=!0;var c=jt(),e=c("%Object.getOwnPropertyDescriptor%",!0);if(e)try{e([],"length")}catch{e=null}return br=e,br}function Pu(){if(Ri)return yr;Ri=!0;var c=li(),e=ps(),t=Kt(),r=gs();return yr=function(a,n,i){if(!a||typeof a!="object"&&typeof a!="function")throw new t("`obj` must be an object or a function`");if(typeof n!="string"&&typeof n!="symbol")throw new t("`property` must be a string or a symbol`");if(arguments.length>3&&typeof arguments[3]!="boolean"&&arguments[3]!==null)throw new t("`nonEnumerable`, if provided, must be a boolean or null");if(arguments.length>4&&typeof arguments[4]!="boolean"&&arguments[4]!==null)throw new t("`nonWritable`, if provided, must be a boolean or null");if(arguments.length>5&&typeof arguments[5]!="boolean"&&arguments[5]!==null)throw new t("`nonConfigurable`, if provided, must be a boolean or null");if(arguments.length>6&&typeof arguments[6]!="boolean")throw new t("`loose`, if provided, must be a boolean");var s=arguments.length>3?arguments[3]:null,o=arguments.length>4?arguments[4]:null,l=arguments.length>5?arguments[5]:null,u=arguments.length>6?arguments[6]:!1,d=!!r&&r(a,n);if(c)c(a,n,{configurable:l===null&&d?d.configurable:!l,enumerable:s===null&&d?d.enumerable:!s,value:i,writable:o===null&&d?d.writable:!o});else if(u||!s&&!o&&!l)a[n]=i;else throw new e("This environment does not support defining a property as non-configurable, non-writable, or non-enumerable.")},yr}function Mu(){if(ji)return vr;ji=!0;var c=li(),e=function(){return!!c};return e.hasArrayLengthDefineBug=function(){if(!c)return null;try{return c([],"length",{value:1}).length!==1}catch{return!0}},vr=e,vr}function Ru(){if(Li)return wr;Li=!0;var c=jt(),e=Pu(),t=Mu()(),r=gs(),a=Kt(),n=c("%Math.floor%");return wr=function(i,s){if(typeof i!="function")throw new a("`fn` is not a function");if(typeof s!="number"||s<0||s>4294967295||n(s)!==s)throw new a("`length` must be a positive 32-bit integer");var o=arguments.length>2&&!!arguments[2],l=!0,u=!0;if("length"in i&&r){var d=r(i,"length");d&&!d.configurable&&(l=!1),d&&!d.writable&&(u=!1)}return(l||u||!o)&&(t?e(i,"length",s,!0,!0):e(i,"length",s)),i},wr}function ju(){if(Ni)return Lt;Ni=!0;var c=ai(),e=jt(),t=Ru(),r=Kt(),a=e("%Function.prototype.apply%"),n=e("%Function.prototype.call%"),i=e("%Reflect.apply%",!0)||c.call(n,a),s=li(),o=e("%Math.max%");Lt=function(u){if(typeof u!="function")throw new r("a function is required");var d=i(c,n,arguments);return t(d,1+o(0,u.length-(arguments.length-1)),!0)};var l=function(){return i(c,a,arguments)};return s?s(Lt,"apply",{value:l}):Lt.apply=l,Lt}function Lu(){if(Ui)return _r;Ui=!0;var c=jt(),e=ju(),t=e(c("String.prototype.indexOf"));return _r=function(r,a){var n=c(r,!!a);return typeof n=="function"&&t(r,".prototype.")>-1?e(n):n},_r}var ci,ui,hi,fi,di,pi,gi,mi,bi,yi,vi,wi,_i,ki,Si,Ei,ur,xi,hr,Ai,fr,Ii,dr,Ti,pr,Ci,gr,Oi,mr,Pi,br,Mi,yr,Ri,vr,ji,wr,Li,Lt,Ni,_r,Ui,Nu=He(()=>{le(),ue(),ce(),ci={},ui=!1,hi={},fi=!1,di={},pi=!1,gi={},mi=!1,bi={},yi=!1,vi={},wi=!1,_i={},ki=!1,Si={},Ei=!1,ur={},xi=!1,hr={},Ai=!1,fr={},Ii=!1,dr={},Ti=!1,pr={},Ci=!1,gr={},Oi=!1,mr={},Pi=!1,br={},Mi=!1,yr={},Ri=!1,vr={},ji=!1,wr={},Li=!1,Lt={},Ni=!1,_r={},Ui=!1});function Bi(c){throw new Error("Node.js process "+c+" is not supported by JSPM core outside of Node.js")}function Uu(){!xt||!At||(xt=!1,At.length?Qe=At.concat(Qe):Vt=-1,Qe.length&&ms())}function ms(){if(!xt){var c=setTimeout(Uu,0);xt=!0;for(var e=Qe.length;e;){for(At=Qe,Qe=[];++Vt<e;)At&&At[Vt].run();Vt=-1,e=Qe.length}At=null,xt=!1,clearTimeout(c)}}function Bu(c){var e=new Array(arguments.length-1);if(arguments.length>1)for(var t=1;t<arguments.length;t++)e[t-1]=arguments[t];Qe.push(new bs(c,e)),Qe.length===1&&!xt&&setTimeout(ms,0)}function bs(c,e){this.fun=c,this.array=e}function Fe(){}function Fu(c){Bi("_linkedBinding")}function Du(c){Bi("dlopen")}function $u(){return[]}function Wu(){return[]}function qu(c,e){if(!c)throw new Error(e||"assertion error")}function Hu(){return!1}function zu(){return ht.now()/1e3}function Fi(c){var e=Math.floor((Date.now()-ht.now())*.001),t=ht.now()*.001,r=Math.floor(t)+e,a=Math.floor(t%1*1e9);return c&&(r=r-c[0],a=a-c[1],a<0&&(r--,a+=Sr)),[r,a]}function bt(){return $i}function Ku(c){return[]}var Qe,xt,At,Vt,ys,vs,ws,_s,ks,Ss,Es,xs,As,Is,Ts,Cs,Os,Ps,Ms,Rs,js,Ls,Ns,Us,Bs,kr,Fs,Ds,$s,Ws,qs,Hs,zs,Ks,Vs,Gs,Ys,Qs,Js,Xs,Zs,ea,ta,ra,na,ia,oa,sa,aa,la,ca,ht,Di,Sr,ua,ha,fa,da,pa,ga,ma,ba,ya,va,wa,$i,_a=He(()=>{le(),ue(),ce(),Qe=[],xt=!1,Vt=-1,bs.prototype.run=function(){this.fun.apply(null,this.array)},ys="browser",vs="x64",ws="browser",_s={PATH:"/usr/bin",LANG:navigator.language+".UTF-8",PWD:"/",HOME:"/home",TMP:"/tmp"},ks=["/usr/bin/node"],Ss=[],Es="v16.8.0",xs={},As=function(c,e){console.warn((e?e+": ":"")+c)},Is=function(c){Bi("binding")},Ts=function(c){return 0},Cs=function(){return"/"},Os=function(c){},Ps={name:"node",sourceUrl:"",headersUrl:"",libUrl:""},Ms=Fe,Rs=[],js={},Ls=!1,Ns={},Us=Fe,Bs=Fe,kr=function(){return{}},Fs=kr,Ds=kr,$s=Fe,Ws=Fe,qs=Fe,Hs={},zs={inspector:!1,debug:!1,uv:!1,ipv6:!1,tls_alpn:!1,tls_sni:!1,tls_ocsp:!1,tls:!1,cached_builtins:!0},Ks=Fe,Vs=Fe,Gs=Fe,Ys=Fe,Qs=Fe,Js=Fe,Xs=Fe,Zs=void 0,ea=void 0,ta=void 0,ra=Fe,na=2,ia=1,oa="/bin/usr/node",sa=9229,aa="node",la=[],ca=Fe,ht={now:typeof performance<"u"?performance.now.bind(performance):void 0,timing:typeof performance<"u"?performance.timing:void 0},ht.now===void 0&&(Di=Date.now(),ht.timing&&ht.timing.navigationStart&&(Di=ht.timing.navigationStart),ht.now=()=>Date.now()-Di),Sr=1e9,Fi.bigint=function(c){var e=Fi(c);return typeof BigInt>"u"?e[0]*Sr+e[1]:BigInt(e[0]*Sr)+BigInt(e[1])},ua=10,ha={},fa=0,da=bt,pa=bt,ga=bt,ma=bt,ba=bt,ya=Fe,va=bt,wa=bt,$i={version:Es,versions:xs,arch:vs,platform:ws,release:Ps,_rawDebug:Ms,moduleLoadList:Rs,binding:Is,_linkedBinding:Fu,_events:ha,_eventsCount:fa,_maxListeners:ua,on:bt,addListener:da,once:pa,off:ga,removeListener:ma,removeAllListeners:ba,emit:ya,prependListener:va,prependOnceListener:wa,listeners:Ku,domain:js,_exiting:Ls,config:Ns,dlopen:Du,uptime:zu,_getActiveRequests:$u,_getActiveHandles:Wu,reallyExit:Us,_kill:Bs,cpuUsage:kr,resourceUsage:Fs,memoryUsage:Ds,kill:$s,exit:Ws,openStdin:qs,allowedNodeEnvironmentFlags:Hs,assert:qu,features:zs,_fatalExceptions:Ks,setUncaughtExceptionCaptureCallback:Vs,hasUncaughtExceptionCaptureCallback:Hu,emitWarning:As,nextTick:Bu,_tickCallback:Gs,_debugProcess:Ys,_debugEnd:Qs,_startProfilerIdleNotifier:Js,_stopProfilerIdleNotifier:Xs,stdout:Zs,stdin:ta,stderr:ea,abort:ra,umask:Ts,chdir:Os,cwd:Cs,env:_s,title:ys,argv:ks,execArgv:Ss,pid:na,ppid:ia,execPath:oa,debugPort:sa,hrtime:Fi,argv0:aa,_preload_modules:la,setSourceMapsEnabled:ca}});function Vu(){if(Wi)return Er;Wi=!0;var c=$i;function e(n){if(typeof n!="string")throw new TypeError("Path must be a string. Received "+JSON.stringify(n))}function t(n,i){for(var s="",o=0,l=-1,u=0,d,p=0;p<=n.length;++p){if(p<n.length)d=n.charCodeAt(p);else{if(d===47)break;d=47}if(d===47){if(!(l===p-1||u===1))if(l!==p-1&&u===2){if(s.length<2||o!==2||s.charCodeAt(s.length-1)!==46||s.charCodeAt(s.length-2)!==46){if(s.length>2){var y=s.lastIndexOf("/");if(y!==s.length-1){y===-1?(s="",o=0):(s=s.slice(0,y),o=s.length-1-s.lastIndexOf("/")),l=p,u=0;continue}}else if(s.length===2||s.length===1){s="",o=0,l=p,u=0;continue}}i&&(s.length>0?s+="/..":s="..",o=2)}else s.length>0?s+="/"+n.slice(l+1,p):s=n.slice(l+1,p),o=p-l-1;l=p,u=0}else d===46&&u!==-1?++u:u=-1}return s}function r(n,i){var s=i.dir||i.root,o=i.base||(i.name||"")+(i.ext||"");return s?s===i.root?s+o:s+n+o:o}var a={resolve:function(){for(var n="",i=!1,s,o=arguments.length-1;o>=-1&&!i;o--){var l;o>=0?l=arguments[o]:(s===void 0&&(s=c.cwd()),l=s),e(l),l.length!==0&&(n=l+"/"+n,i=l.charCodeAt(0)===47)}return n=t(n,!i),i?n.length>0?"/"+n:"/":n.length>0?n:"."},normalize:function(n){if(e(n),n.length===0)return".";var i=n.charCodeAt(0)===47,s=n.charCodeAt(n.length-1)===47;return n=t(n,!i),n.length===0&&!i&&(n="."),n.length>0&&s&&(n+="/"),i?"/"+n:n},isAbsolute:function(n){return e(n),n.length>0&&n.charCodeAt(0)===47},join:function(){if(arguments.length===0)return".";for(var n,i=0;i<arguments.length;++i){var s=arguments[i];e(s),s.length>0&&(n===void 0?n=s:n+="/"+s)}return n===void 0?".":a.normalize(n)},relative:function(n,i){if(e(n),e(i),n===i||(n=a.resolve(n),i=a.resolve(i),n===i))return"";for(var s=1;s<n.length&&n.charCodeAt(s)===47;++s);for(var o=n.length,l=o-s,u=1;u<i.length&&i.charCodeAt(u)===47;++u);for(var d=i.length,p=d-u,y=l<p?l:p,f=-1,g=0;g<=y;++g){if(g===y){if(p>y){if(i.charCodeAt(u+g)===47)return i.slice(u+g+1);if(g===0)return i.slice(u+g)}else l>y&&(n.charCodeAt(s+g)===47?f=g:g===0&&(f=0));break}var b=n.charCodeAt(s+g),k=i.charCodeAt(u+g);if(b!==k)break;b===47&&(f=g)}var m="";for(g=s+f+1;g<=o;++g)(g===o||n.charCodeAt(g)===47)&&(m.length===0?m+="..":m+="/..");return m.length>0?m+i.slice(u+f):(u+=f,i.charCodeAt(u)===47&&++u,i.slice(u))},_makeLong:function(n){return n},dirname:function(n){if(e(n),n.length===0)return".";for(var i=n.charCodeAt(0),s=i===47,o=-1,l=!0,u=n.length-1;u>=1;--u)if(i=n.charCodeAt(u),i===47){if(!l){o=u;break}}else l=!1;return o===-1?s?"/":".":s&&o===1?"//":n.slice(0,o)},basename:function(n,i){if(i!==void 0&&typeof i!="string")throw new TypeError('"ext" argument must be a string');e(n);var s=0,o=-1,l=!0,u;if(i!==void 0&&i.length>0&&i.length<=n.length){if(i.length===n.length&&i===n)return"";var d=i.length-1,p=-1;for(u=n.length-1;u>=0;--u){var y=n.charCodeAt(u);if(y===47){if(!l){s=u+1;break}}else p===-1&&(l=!1,p=u+1),d>=0&&(y===i.charCodeAt(d)?--d===-1&&(o=u):(d=-1,o=p))}return s===o?o=p:o===-1&&(o=n.length),n.slice(s,o)}else{for(u=n.length-1;u>=0;--u)if(n.charCodeAt(u)===47){if(!l){s=u+1;break}}else o===-1&&(l=!1,o=u+1);return o===-1?"":n.slice(s,o)}},extname:function(n){e(n);for(var i=-1,s=0,o=-1,l=!0,u=0,d=n.length-1;d>=0;--d){var p=n.charCodeAt(d);if(p===47){if(!l){s=d+1;break}continue}o===-1&&(l=!1,o=d+1),p===46?i===-1?i=d:u!==1&&(u=1):i!==-1&&(u=-1)}return i===-1||o===-1||u===0||u===1&&i===o-1&&i===s+1?"":n.slice(i,o)},format:function(n){if(n===null||typeof n!="object")throw new TypeError('The "pathObject" argument must be of type Object. Received type '+typeof n);return r("/",n)},parse:function(n){e(n);var i={root:"",dir:"",base:"",ext:"",name:""};if(n.length===0)return i;var s=n.charCodeAt(0),o=s===47,l;o?(i.root="/",l=1):l=0;for(var u=-1,d=0,p=-1,y=!0,f=n.length-1,g=0;f>=l;--f){if(s=n.charCodeAt(f),s===47){if(!y){d=f+1;break}continue}p===-1&&(y=!1,p=f+1),s===46?u===-1?u=f:g!==1&&(g=1):u!==-1&&(g=-1)}return u===-1||p===-1||g===0||g===1&&u===p-1&&u===d+1?p!==-1&&(d===0&&o?i.base=i.name=n.slice(1,p):i.base=i.name=n.slice(d,p)):(d===0&&o?(i.name=n.slice(1,u),i.base=n.slice(1,p)):(i.name=n.slice(d,u),i.base=n.slice(d,p)),i.ext=n.slice(u,p)),d>0?i.dir=n.slice(0,d-1):o&&(i.dir="/"),i},sep:"/",delimiter:":",win32:null,posix:null};return a.posix=a,Er=a,Er}var Er,Wi,qi,Gu=He(()=>{le(),ue(),ce(),_a(),Er={},Wi=!1,qi=Vu()}),ka={};Ct(ka,{URL:()=>Ra,Url:()=>Ta,default:()=>De,fileURLToPath:()=>Ea,format:()=>Ca,parse:()=>Ma,pathToFileURL:()=>xa,resolve:()=>Oa,resolveObject:()=>Pa});function Yu(){if(zi)return xr;zi=!0;var c=typeof Map=="function"&&Map.prototype,e=Object.getOwnPropertyDescriptor&&c?Object.getOwnPropertyDescriptor(Map.prototype,"size"):null,t=c&&e&&typeof e.get=="function"?e.get:null,r=c&&Map.prototype.forEach,a=typeof Set=="function"&&Set.prototype,n=Object.getOwnPropertyDescriptor&&a?Object.getOwnPropertyDescriptor(Set.prototype,"size"):null,i=a&&n&&typeof n.get=="function"?n.get:null,s=a&&Set.prototype.forEach,o=typeof WeakMap=="function"&&WeakMap.prototype,l=o?WeakMap.prototype.has:null,u=typeof WeakSet=="function"&&WeakSet.prototype,d=u?WeakSet.prototype.has:null,p=typeof WeakRef=="function"&&WeakRef.prototype,y=p?WeakRef.prototype.deref:null,f=Boolean.prototype.valueOf,g=Object.prototype.toString,b=Function.prototype.toString,k=String.prototype.match,m=String.prototype.slice,w=String.prototype.replace,E=String.prototype.toUpperCase,v=String.prototype.toLowerCase,x=RegExp.prototype.test,S=Array.prototype.concat,I=Array.prototype.join,M=Array.prototype.slice,O=Math.floor,B=typeof BigInt=="function"?BigInt.prototype.valueOf:null,T=Object.getOwnPropertySymbols,W=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?Symbol.prototype.toString:null,F=typeof Symbol=="function"&&typeof Symbol.iterator=="object",N=typeof Symbol=="function"&&Symbol.toStringTag&&(typeof Symbol.toStringTag===F||!0)?Symbol.toStringTag:null,ae=Object.prototype.propertyIsEnumerable,Y=(typeof Reflect=="function"?Reflect.getPrototypeOf:Object.getPrototypeOf)||([].__proto__===Array.prototype?function(z){return z.__proto__}:null);function K(z,ie){if(z===1/0||z===-1/0||z!==z||z&&z>-1e3&&z<1e3||x.call(/e/,ie))return ie;var xe=/[0-9](?=(?:[0-9]{3})+(?![0-9]))/g;if(typeof z=="number"){var Ae=z<0?-O(-z):O(z);if(Ae!==z){var Ie=String(Ae),Oe=m.call(ie,Ie.length+1);return w.call(Ie,xe,"$&_")+"."+w.call(w.call(Oe,/([0-9]{3})/g,"$&_"),/_$/,"")}}return w.call(ie,xe,"$&_")}var re=Aa,D=re.custom,Z=G(D)?D:null;xr=function z(ie,xe,Ae,Ie){var Oe=xe||{};if(oe(Oe,"quoteStyle")&&Oe.quoteStyle!=="single"&&Oe.quoteStyle!=="double")throw new TypeError('option "quoteStyle" must be "single" or "double"');if(oe(Oe,"maxStringLength")&&(typeof Oe.maxStringLength=="number"?Oe.maxStringLength<0&&Oe.maxStringLength!==1/0:Oe.maxStringLength!==null))throw new TypeError('option "maxStringLength", if provided, must be a positive integer, Infinity, or `null`');var Je=oe(Oe,"customInspect")?Oe.customInspect:!0;if(typeof Je!="boolean"&&Je!=="symbol")throw new TypeError("option \"customInspect\", if provided, must be `true`, `false`, or `'symbol'`");if(oe(Oe,"indent")&&Oe.indent!==null&&Oe.indent!==" "&&!(parseInt(Oe.indent,10)===Oe.indent&&Oe.indent>0))throw new TypeError('option "indent" must be "\\t", an integer > 0, or `null`');if(oe(Oe,"numericSeparator")&&typeof Oe.numericSeparator!="boolean")throw new TypeError('option "numericSeparator", if provided, must be `true` or `false`');var Xe=Oe.numericSeparator;if(typeof ie>"u")return"undefined";if(ie===null)return"null";if(typeof ie=="boolean")return ie?"true":"false";if(typeof ie=="string")return se(ie,Oe);if(typeof ie=="number"){if(ie===0)return 1/0/ie>0?"0":"-0";var $e=String(ie);return Xe?K(ie,$e):$e}if(typeof ie=="bigint"){var Ze=String(ie)+"n";return Xe?K(ie,Ze):Ze}var Bt=typeof Oe.depth>"u"?5:Oe.depth;if(typeof Ae>"u"&&(Ae=0),Ae>=Bt&&Bt>0&&typeof ie=="object")return be(ie)?"[Array]":"[Object]";var et=X(Oe,Ae);if(typeof Ie>"u")Ie=[];else if(ee(Ie,ie)>=0)return"[Circular]";function Ve(tt,vt,Tt){if(vt&&(Ie=M.call(Ie),Ie.push(vt)),Tt){var rt={depth:Oe.depth};return oe(Oe,"quoteStyle")&&(rt.quoteStyle=Oe.quoteStyle),z(tt,rt,Ae+1,Ie)}return z(tt,Oe,Ae+1,Ie)}if(typeof ie=="function"&&!we(ie)){var Br=$(ie),Ft=ke(ie,Ve);return"[Function"+(Br?": "+Br:" (anonymous)")+"]"+(Ft.length>0?" { "+I.call(Ft,", ")+" }":"")}if(G(ie)){var Gt=F?w.call(String(ie),/^(Symbol\(.*\))_[^)]*$/,"$1"):W.call(ie);return typeof ie=="object"&&!F?h(Gt):Gt}if(ve(ie)){for(var C="<"+v.call(String(ie.nodeName)),j=ie.attributes||[],_e=0;_e<j.length;_e++)C+=" "+j[_e].name+"="+P(J(j[_e].value),"double",Oe);return C+=">",ie.childNodes&&ie.childNodes.length&&(C+="..."),C+="</"+v.call(String(ie.nodeName))+">",C}if(be(ie)){if(ie.length===0)return"[]";var Se=ke(ie,Ve);return et&&!U(Se)?"["+he(Se,et)+"]":"[ "+I.call(Se,", ")+" ]"}if(V(ie)){var Ee=ke(ie,Ve);return!("cause"in Error.prototype)&&"cause"in ie&&!ae.call(ie,"cause")?"{ ["+String(ie)+"] "+I.call(S.call("[cause]: "+Ve(ie.cause),Ee),", ")+" }":Ee.length===0?"["+String(ie)+"]":"{ ["+String(ie)+"] "+I.call(Ee,", ")+" }"}if(typeof ie=="object"&&Je){if(Z&&typeof ie[Z]=="function"&&re)return re(ie,{depth:Bt-Ae});if(Je!=="symbol"&&typeof ie.inspect=="function")return ie.inspect()}if(fe(ie)){var Le=[];return r&&r.call(ie,function(tt,vt){Le.push(Ve(vt,ie,!0)+" => "+Ve(tt,ie))}),A("Map",t.call(ie),Le,et)}if(q(ie)){var qe=[];return s&&s.call(ie,function(tt){qe.push(Ve(tt,ie))}),A("Set",i.call(ie),qe,et)}if(de(ie))return _("WeakMap");if(ge(ie))return _("WeakSet");if(ye(ie))return _("WeakRef");if(ne(ie))return h(Ve(Number(ie)));if(Q(ie))return h(Ve(B.call(ie)));if(H(ie))return h(f.call(ie));if(L(ie))return h(Ve(String(ie)));if(typeof window<"u"&&ie===window)return"{ [object Window] }";if(typeof globalThis<"u"&&ie===globalThis||typeof Ar<"u"&&ie===Ar)return"{ [object globalThis] }";if(!te(ie)&&!we(ie)){var Ge=ke(ie,Ve),Yt=Y?Y(ie)===Object.prototype:ie instanceof Object||ie.constructor===Object,Qt=ie instanceof Object?"":"null prototype",Jt=!Yt&&N&&Object(ie)===ie&&N in ie?m.call(R(ie),8,-1):Qt?"Object":"",Fr=Yt||typeof ie.constructor!="function"?"":ie.constructor.name?ie.constructor.name+" ":"",It=Fr+(Jt||Qt?"["+I.call(S.call([],Jt||[],Qt||[]),": ")+"] ":"");return Ge.length===0?It+"{}":et?It+"{"+he(Ge,et)+"}":It+"{ "+I.call(Ge,", ")+" }"}return String(ie)};function P(z,ie,xe){var Ae=(xe.quoteStyle||ie)==="double"?'"':"'";return Ae+z+Ae}function J(z){return w.call(String(z),/"/g,"&quot;")}function be(z){return R(z)==="[object Array]"&&(!N||!(typeof z=="object"&&N in z))}function te(z){return R(z)==="[object Date]"&&(!N||!(typeof z=="object"&&N in z))}function we(z){return R(z)==="[object RegExp]"&&(!N||!(typeof z=="object"&&N in z))}function V(z){return R(z)==="[object Error]"&&(!N||!(typeof z=="object"&&N in z))}function L(z){return R(z)==="[object String]"&&(!N||!(typeof z=="object"&&N in z))}function ne(z){return R(z)==="[object Number]"&&(!N||!(typeof z=="object"&&N in z))}function H(z){return R(z)==="[object Boolean]"&&(!N||!(typeof z=="object"&&N in z))}function G(z){if(F)return z&&typeof z=="object"&&z instanceof Symbol;if(typeof z=="symbol")return!0;if(!z||typeof z!="object"||!W)return!1;try{return W.call(z),!0}catch{}return!1}function Q(z){if(!z||typeof z!="object"||!B)return!1;try{return B.call(z),!0}catch{}return!1}var me=Object.prototype.hasOwnProperty||function(z){return z in(this||Ar)};function oe(z,ie){return me.call(z,ie)}function R(z){return g.call(z)}function $(z){if(z.name)return z.name;var ie=k.call(b.call(z),/^function\s*([\w$]+)/);return ie?ie[1]:null}function ee(z,ie){if(z.indexOf)return z.indexOf(ie);for(var xe=0,Ae=z.length;xe<Ae;xe++)if(z[xe]===ie)return xe;return-1}function fe(z){if(!t||!z||typeof z!="object")return!1;try{t.call(z);try{i.call(z)}catch{return!0}return z instanceof Map}catch{}return!1}function de(z){if(!l||!z||typeof z!="object")return!1;try{l.call(z,l);try{d.call(z,d)}catch{return!0}return z instanceof WeakMap}catch{}return!1}function ye(z){if(!y||!z||typeof z!="object")return!1;try{return y.call(z),!0}catch{}return!1}function q(z){if(!i||!z||typeof z!="object")return!1;try{i.call(z);try{t.call(z)}catch{return!0}return z instanceof Set}catch{}return!1}function ge(z){if(!d||!z||typeof z!="object")return!1;try{d.call(z,d);try{l.call(z,l)}catch{return!0}return z instanceof WeakSet}catch{}return!1}function ve(z){return!z||typeof z!="object"?!1:typeof HTMLElement<"u"&&z instanceof HTMLElement?!0:typeof z.nodeName=="string"&&typeof z.getAttribute=="function"}function se(z,ie){if(z.length>ie.maxStringLength){var xe=z.length-ie.maxStringLength,Ae="... "+xe+" more character"+(xe>1?"s":"");return se(m.call(z,0,ie.maxStringLength),ie)+Ae}var Ie=w.call(w.call(z,/(['\\])/g,"\\$1"),/[\x00-\x1f]/g,Te);return P(Ie,"single",ie)}function Te(z){var ie=z.charCodeAt(0),xe={8:"b",9:"t",10:"n",12:"f",13:"r"}[ie];return xe?"\\"+xe:"\\x"+(ie<16?"0":"")+E.call(ie.toString(16))}function h(z){return"Object("+z+")"}function _(z){return z+" { ? }"}function A(z,ie,xe,Ae){var Ie=Ae?he(xe,Ae):I.call(xe,", ");return z+" ("+ie+") {"+Ie+"}"}function U(z){for(var ie=0;ie<z.length;ie++)if(ee(z[ie],`
1
+ var AikaaraChat=(function(Ce){"use strict";class po{identifier;callbacks={};sendFn;constructor(e,t){this.identifier=e,this.sendFn=t}onReceived(e){return this.callbacks.received=e,this}onConnected(e){return this.callbacks.connected=e,this}onDisconnected(e){return this.callbacks.disconnected=e,this}onRejected(e){return this.callbacks.rejected=e,this}perform(e,t={}){this.sendFn({action:e,...t})}_notifyReceived(e){this.callbacks.received?.(e)}_notifyConnected(){this.callbacks.connected?.()}_notifyDisconnected(){this.callbacks.disconnected?.()}_notifyRejected(){this.callbacks.rejected?.()}}class Dr{ws=null;url;subscriptions=new Map;welcomePromise=null;pendingSubscriptions=new Map;constructor(e){this.url=e}connect(){return new Promise((e,t)=>{this.welcomePromise={resolve:e,reject:t},this.ws=new WebSocket(this.url),this.ws.onopen=()=>{},this.ws.onmessage=r=>{this.handleMessage(r)},this.ws.onerror=()=>{const r=new Error("WebSocket connection error");this.welcomePromise?.reject(r),this.welcomePromise=null},this.ws.onclose=()=>{this.subscriptions.forEach(r=>r._notifyDisconnected())}})}disconnect(){this.ws&&(this.ws.onclose=null,this.ws.close(),this.ws=null),this.subscriptions.forEach(e=>e._notifyDisconnected()),this.subscriptions.clear()}subscribe(e){const t=JSON.stringify(e),r=new po(t,a=>{this.send({command:"message",identifier:t,data:JSON.stringify(a)})});return this.subscriptions.set(t,r),this.send({command:"subscribe",identifier:t}),r}subscribeAsync(e){const t=this.subscribe(e),r=t.identifier;return new Promise((a,n)=>{this.pendingSubscriptions.set(r,{resolve:()=>a(t),reject:n}),setTimeout(()=>{this.pendingSubscriptions.has(r)&&(this.pendingSubscriptions.delete(r),n(new Error(`Subscription timeout for ${r}`)))},1e4)})}unsubscribe(e){this.send({command:"unsubscribe",identifier:e}),this.subscriptions.delete(e)}perform(e,t,r={}){this.send({command:"message",identifier:e,data:JSON.stringify({action:t,...r})})}get isConnected(){return this.ws?.readyState===WebSocket.OPEN}send(e){this.ws?.readyState===WebSocket.OPEN&&this.ws.send(JSON.stringify(e))}handleMessage(e){let t;try{t=JSON.parse(e.data)}catch{return}switch(t.type){case"welcome":this.welcomePromise?.resolve(),this.welcomePromise=null;break;case"ping":break;case"confirm_subscription":{const r=t.identifier;this.subscriptions.get(r)?._notifyConnected();const n=this.pendingSubscriptions.get(r);n&&(n.resolve(),this.pendingSubscriptions.delete(r));break}case"reject_subscription":{const r=t.identifier;this.subscriptions.get(r)?._notifyRejected(),this.subscriptions.delete(r);const n=this.pendingSubscriptions.get(r);n&&(n.reject(new Error(`Subscription rejected: ${r}`)),this.pendingSubscriptions.delete(r));break}case"disconnect":this.subscriptions.forEach(r=>r._notifyDisconnected());break;default:{t.identifier&&t.message!==void 0&&this.subscriptions.get(t.identifier)?._notifyReceived(t.message);break}}}}class Zt{handlers=new Map;on(e,t){return this.handlers.has(e)||this.handlers.set(e,new Set),this.handlers.get(e).add(t),()=>this.off(e,t)}off(e,t){this.handlers.get(e)?.delete(t)}emit(e,t){this.handlers.get(e)?.forEach(r=>{try{r(t)}catch(a){console.error(`Error in event handler for "${e}":`,a)}})}removeAllListeners(){this.handlers.clear()}}const zl=1e3,Kl=10,Vl=400,Gl=600,go="#6366f1",Yl=12,Ql="system-ui, -apple-system, sans-serif",mo="Type a message...",Jl="bottom-right",Xl="light",Zl={x:20,y:20},$r="aikaara_conversation_id";class bo extends Zt{client;config;state="disconnected";reconnectAttempt=0;reconnectTimer=null;constructor(e){super(),this.config=e;const t=this.buildWsUrl(e.baseUrl,e.userToken);this.client=new Dr(t)}async connect(){this.setState("connecting");try{await this.client.connect(),this.setState("connected"),this.reconnectAttempt=0}catch(e){if(this.setState("disconnected"),this.config.reconnect!==!1)this.scheduleReconnect();else throw e}}async disconnect(){this.clearReconnectTimer(),this.client.disconnect(),this.setState("disconnected")}subscribeToConversation(e){return this.client.subscribeAsync({channel:"ConversationChannel",conversation_id:e})}sendMessage(e,t){const r=JSON.stringify({channel:"ConversationChannel",conversation_id:e});this.client.perform(r,"send_message",{content:t})}sendUserEvent(e,t,r,a){const n=JSON.stringify({channel:"ConversationChannel",conversation_id:e});this.client.perform(n,"send_user_event",{event_key:t,...r&&{value:r},...a&&{source:a}})}get connectionState(){return this.state}setState(e){this.state!==e&&(this.state=e,this.emit("connection:state",e))}scheduleReconnect(){const e=this.config.maxReconnectAttempts??Kl;if(this.reconnectAttempt>=e){this.emit("error",new Error("Max reconnection attempts reached"));return}this.setState("reconnecting");const r=(this.config.reconnectInterval??zl)*Math.pow(2,this.reconnectAttempt);this.reconnectAttempt++,this.reconnectTimer=setTimeout(async()=>{try{const a=this.buildWsUrl(this.config.baseUrl,this.config.userToken);this.client=new Dr(a),await this.connect()}catch{}},r)}clearReconnectTimer(){this.reconnectTimer&&(clearTimeout(this.reconnectTimer),this.reconnectTimer=null)}buildWsUrl(e,t){if(this.config.wsUrl){const a=this.config.wsUrl.includes("?")?"&":"?";return`${this.config.wsUrl}${a}token=${t}`}return`${e.replace(/^http/,"ws")}/cable?token=${t}`}}class yo{baseUrl;apiKey;authToken;userToken;refreshHook=null;constructor(e,t,r,a){this.baseUrl=e,this.userToken=t,this.apiKey=r,this.authToken=a}setAuthRefreshHook(e){this.refreshHook=e}getAuthToken(){return this.authToken}setAuthToken(e){this.authToken=e}async createConversation(e){const t={conversation:{...e.extUid&&{ext_uid:e.extUid},...e.systemPromptId&&{system_prompt_id:e.systemPromptId},...e.channel&&{channel:e.channel},...e.title&&{title:e.title}}};return this.request("POST","/api/v1/conversations",t)}async updateContext(e,t){const r=this.authToken?`/dashboard/sidekick_conversations/${e}`:`/api/v1/conversations/${e}`;await this.request("PATCH",r,t)}async getMessages(e){return(await this.request("GET",`/api/v1/conversations/${e}/messages`)).map(this.mapMessage)}mapMessage(e){return{id:String(e.id),conversationId:String(e.conversation_id),role:e.role,content:e.content||"",toolCalls:e.tool_calls?.map(t=>({id:t.id,type:t.type,function:t.function})),toolCallResults:e.tool_call_results,tokensInput:e.tokens_input,tokensOutput:e.tokens_output,metadata:e.metadata,createdAt:e.created_at,status:"complete"}}async request(e,t,r){const a=`${this.baseUrl}${t}`;let n=await this.fetchWithHeaders(a,e,r);if(n.status===401&&this.refreshHook){let s=null;try{s=await this.refreshHook()}catch(o){console.warn("[aikaara-chat-sdk] auth refresh hook threw",o)}s&&(this.authToken=s,n=await this.fetchWithHeaders(a,e,r))}if(!n.ok){const s=await n.text();let o;try{const l=JSON.parse(s);o=l.error||l.message||s}catch{o=s}throw new Error(`API error ${n.status}: ${o}`)}const i=await n.json();if(i&&typeof i=="object"&&"success"in i){if(!i.success)throw new Error(`API error: ${i.message||"Request failed"}`);return i.data}return i}async fetchWithHeaders(e,t,r){const a={"Content-Type":"application/json",Accept:"application/json"};this.apiKey&&(a["X-Api-Key"]=this.apiKey),this.authToken&&(a.Authorization=`Bearer ${this.authToken}`);const n={method:t,headers:a};return r&&(n.body=JSON.stringify(r)),fetch(e,n)}}class vo{_messages=[];optimisticCounter=0;get messages(){return[...this._messages]}addOptimistic(e,t,r){const a={id:`optimistic_${++this.optimisticCounter}`,conversationId:r,role:e,content:t,createdAt:new Date().toISOString(),status:"sending"};return this._messages.push(a),a}reconcileOptimistic(e,t=3e4){const r=this._messages.findLast(a=>a.status==="sending"&&a.role===e.role&&a.content===e.content&&a.conversationId===e.conversationId&&Date.now()-new Date(a.createdAt).getTime()<t);return r?(r.status=e.status??"sent",r.externalId=e.externalId??e.id,e.template&&(r.template=e.template),e.attachments&&(r.attachments=e.attachments),e.metadata&&(r.metadata={...r.metadata??{},...e.metadata}),r):null}upsertRemoteMessage(e){const t=this.reconcileOptimistic(e);if(t)return{message:t,deduped:!0};const r=e.externalId?this._messages.find(n=>n.externalId&&n.externalId===e.externalId):void 0;if(r)return Object.assign(r,e,{id:r.id}),{message:r,deduped:!0};const a=ec(this._messages,e);return a?(Object.assign(a,e,{id:a.id}),{message:a,deduped:!0}):(this._messages.push(e),{message:e,deduped:!1})}updateMessageStatus(e,t){const r=this._messages.find(a=>a.externalId===e||a.id===e);return r&&(r.status=t),r}confirmOptimistic(e){const t=this._messages.find(r=>r.id===e);t&&(t.status="sent")}addStreamingMessage(e){const t={id:`streaming_${Date.now()}`,conversationId:e,role:"assistant",content:"",createdAt:new Date().toISOString(),status:"streaming"};return this._messages.push(t),t}updateStreaming(e){const t=this._messages.findLast(r=>r.status==="streaming");t&&(t.content=e)}appendToStreaming(e){const t=this._messages.findLast(r=>r.status==="streaming");t&&(t.content+=e)}get streamingContent(){return this._messages.findLast(t=>t.status==="streaming")?.content||""}finalizeStreaming(e){const t=this._messages.findLast(r=>r.status==="streaming");return t&&(t.status="complete",e&&(t.tokensInput=e.tokensInput,t.tokensOutput=e.tokensOutput)),t}addMessage(e){this._messages.push(e)}setMessages(e){this._messages=[...e]}clear(){this._messages=[]}}function ec(c,e,t=15e3){const r=e.attachments&&e.attachments[0],a=(e.metadata??{}).attributes;if(!(!!r||!!(a&&a.fileMessage)))return null;const i=ko(e),s=wo(e),o=_o(e);if(!i&&!s&&!o)return null;const l=new Date(e.createdAt).getTime();for(let u=c.length-1;u>=0;u--){const d=c[u],p=d.attachments&&d.attachments[0],y=(d.metadata??{}).attributes;if(!(!!p||!!(y&&y.fileMessage))||Math.abs(l-new Date(d.createdAt).getTime())>t)continue;const m=ko(d);if(i&&m&&i===m)return d;const b=wo(d);if(s&&b&&s===b)return d;const k=_o(d);if(o&&k&&o===k)return d}return null}function wo(c){const e=c.attachments&&c.attachments[0];if(e&&typeof e.fileUrl=="string")return e.fileUrl}function _o(c){const e=c.attachments&&c.attachments[0];if(e&&typeof e.fileName=="string")return e.fileName}function ko(c){const e=c.attachments&&c.attachments[0];if(e&&typeof e.cloudFileId=="string")return e.cloudFileId;const t=(c.metadata??{}).attributes;if(t&&typeof t.cloudFileId=="string")return t.cloudFileId}class So{_conversationId;persist;constructor(e,t=!0){this.persist=t,this._conversationId=e||this.loadFromStorage()}get conversationId(){return this._conversationId}set conversationId(e){this._conversationId=e,this.persist&&e&&this.saveToStorage(e)}clear(){if(this._conversationId=null,this.persist)try{localStorage.removeItem($r)}catch{}}loadFromStorage(){if(!this.persist)return null;try{return localStorage.getItem($r)}catch{return null}}saveToStorage(e){try{localStorage.setItem($r,e)}catch{}}}var Wr=Object.defineProperty,tc=Object.getOwnPropertyDescriptor,rc=Object.getOwnPropertyNames,nc=Object.prototype.hasOwnProperty,He=(c,e)=>()=>(c&&(e=c(c=0)),e),pe=(c,e)=>()=>(e||c((e={exports:{}}).exports,e),e.exports),Ct=(c,e)=>{for(var t in e)Wr(c,t,{get:e[t],enumerable:!0})},ic=(c,e,t,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let a of rc(e))!nc.call(c,a)&&a!==t&&Wr(c,a,{get:()=>e[a],enumerable:!(r=tc(e,a))||r.enumerable});return c},Pe=c=>ic(Wr({},"__esModule",{value:!0}),c),le=He(()=>{}),Me={};Ct(Me,{_debugEnd:()=>En,_debugProcess:()=>Sn,_events:()=>Dn,_eventsCount:()=>$n,_exiting:()=>cn,_fatalExceptions:()=>wn,_getActiveHandles:()=>Oo,_getActiveRequests:()=>Co,_kill:()=>fn,_linkedBinding:()=>Io,_maxListeners:()=>Fn,_preload_modules:()=>Nn,_rawDebug:()=>sn,_startProfilerIdleNotifier:()=>xn,_stopProfilerIdleNotifier:()=>An,_tickCallback:()=>kn,abort:()=>On,addListener:()=>Wn,allowedNodeEnvironmentFlags:()=>yn,arch:()=>zr,argv:()=>Gr,argv0:()=>Ln,assert:()=>Po,binding:()=>Zr,browser:()=>on,chdir:()=>rn,config:()=>un,cpuUsage:()=>$t,cwd:()=>tn,debugPort:()=>jn,default:()=>Qn,dlopen:()=>To,domain:()=>ln,emit:()=>Vn,emitWarning:()=>Xr,env:()=>Vr,execArgv:()=>Yr,execPath:()=>Rn,exit:()=>mn,features:()=>vn,hasUncaughtExceptionCaptureCallback:()=>Mo,hrtime:()=>er,kill:()=>gn,listeners:()=>jo,memoryUsage:()=>pn,moduleLoadList:()=>an,nextTick:()=>xo,off:()=>Hn,on:()=>nt,once:()=>qn,openStdin:()=>bn,pid:()=>Pn,platform:()=>Kr,ppid:()=>Mn,prependListener:()=>Gn,prependOnceListener:()=>Yn,reallyExit:()=>hn,release:()=>nn,removeAllListeners:()=>Kn,removeListener:()=>zn,resourceUsage:()=>dn,setSourceMapsEnabled:()=>Un,setUncaughtExceptionCaptureCallback:()=>_n,stderr:()=>Tn,stdin:()=>Cn,stdout:()=>In,title:()=>Hr,umask:()=>en,uptime:()=>Ro,version:()=>Qr,versions:()=>Jr});function qr(c){throw new Error("Node.js process "+c+" is not supported by JSPM core outside of Node.js")}function oc(){!wt||!_t||(wt=!1,_t.length?Ye=_t.concat(Ye):Dt=-1,Ye.length&&Eo())}function Eo(){if(!wt){var c=setTimeout(oc,0);wt=!0;for(var e=Ye.length;e;){for(_t=Ye,Ye=[];++Dt<e;)_t&&_t[Dt].run();Dt=-1,e=Ye.length}_t=null,wt=!1,clearTimeout(c)}}function xo(c){var e=new Array(arguments.length-1);if(arguments.length>1)for(var t=1;t<arguments.length;t++)e[t-1]=arguments[t];Ye.push(new Ao(c,e)),Ye.length===1&&!wt&&setTimeout(Eo,0)}function Ao(c,e){this.fun=c,this.array=e}function Be(){}function Io(c){qr("_linkedBinding")}function To(c){qr("dlopen")}function Co(){return[]}function Oo(){return[]}function Po(c,e){if(!c)throw new Error(e||"assertion error")}function Mo(){return!1}function Ro(){return it.now()/1e3}function er(c){var e=Math.floor((Date.now()-it.now())*.001),t=it.now()*.001,r=Math.floor(t)+e,a=Math.floor(t%1*1e9);return c&&(r=r-c[0],a=a-c[1],a<0&&(r--,a+=tr)),[r,a]}function nt(){return Qn}function jo(c){return[]}var Ye,wt,_t,Dt,Hr,zr,Kr,Vr,Gr,Yr,Qr,Jr,Xr,Zr,en,tn,rn,nn,on,sn,an,ln,cn,un,hn,fn,$t,dn,pn,gn,mn,bn,yn,vn,wn,_n,kn,Sn,En,xn,An,In,Tn,Cn,On,Pn,Mn,Rn,jn,Ln,Nn,Un,it,Bn,tr,Fn,Dn,$n,Wn,qn,Hn,zn,Kn,Vn,Gn,Yn,Qn,sc=He(()=>{le(),ue(),ce(),Ye=[],wt=!1,Dt=-1,Ao.prototype.run=function(){this.fun.apply(null,this.array)},Hr="browser",zr="x64",Kr="browser",Vr={PATH:"/usr/bin",LANG:typeof navigator<"u"?navigator.language+".UTF-8":void 0,PWD:"/",HOME:"/home",TMP:"/tmp"},Gr=["/usr/bin/node"],Yr=[],Qr="v16.8.0",Jr={},Xr=function(c,e){console.warn((e?e+": ":"")+c)},Zr=function(c){qr("binding")},en=function(c){return 0},tn=function(){return"/"},rn=function(c){},nn={name:"node",sourceUrl:"",headersUrl:"",libUrl:""},on=!0,sn=Be,an=[],ln={},cn=!1,un={},hn=Be,fn=Be,$t=function(){return{}},dn=$t,pn=$t,gn=Be,mn=Be,bn=Be,yn={},vn={inspector:!1,debug:!1,uv:!1,ipv6:!1,tls_alpn:!1,tls_sni:!1,tls_ocsp:!1,tls:!1,cached_builtins:!0},wn=Be,_n=Be,kn=Be,Sn=Be,En=Be,xn=Be,An=Be,In=void 0,Tn=void 0,Cn=void 0,On=Be,Pn=2,Mn=1,Rn="/bin/usr/node",jn=9229,Ln="node",Nn=[],Un=Be,it={now:typeof performance<"u"?performance.now.bind(performance):void 0,timing:typeof performance<"u"?performance.timing:void 0},it.now===void 0&&(Bn=Date.now(),it.timing&&it.timing.navigationStart&&(Bn=it.timing.navigationStart),it.now=()=>Date.now()-Bn),tr=1e9,er.bigint=function(c){var e=er(c);return typeof BigInt>"u"?e[0]*tr+e[1]:BigInt(e[0]*tr)+BigInt(e[1])},Fn=10,Dn={},$n=0,Wn=nt,qn=nt,Hn=nt,zn=nt,Kn=nt,Vn=Be,Gn=nt,Yn=nt,Qn={version:Qr,versions:Jr,arch:zr,platform:Kr,browser:on,release:nn,_rawDebug:sn,moduleLoadList:an,binding:Zr,_linkedBinding:Io,_events:Dn,_eventsCount:$n,_maxListeners:Fn,on:nt,addListener:Wn,once:qn,off:Hn,removeListener:zn,removeAllListeners:Kn,emit:Vn,prependListener:Gn,prependOnceListener:Yn,listeners:jo,domain:ln,_exiting:cn,config:un,dlopen:To,uptime:Ro,_getActiveRequests:Co,_getActiveHandles:Oo,reallyExit:hn,_kill:fn,cpuUsage:$t,resourceUsage:dn,memoryUsage:pn,kill:gn,exit:mn,openStdin:bn,allowedNodeEnvironmentFlags:yn,assert:Po,features:vn,_fatalExceptions:wn,setUncaughtExceptionCaptureCallback:_n,hasUncaughtExceptionCaptureCallback:Mo,emitWarning:Xr,nextTick:xo,_tickCallback:kn,_debugProcess:Sn,_debugEnd:En,_startProfilerIdleNotifier:xn,_stopProfilerIdleNotifier:An,stdout:In,stdin:Cn,stderr:Tn,abort:On,umask:en,chdir:rn,cwd:tn,env:Vr,title:Hr,argv:Gr,execArgv:Yr,pid:Pn,ppid:Mn,execPath:Rn,debugPort:jn,hrtime:er,argv0:Ln,_preload_modules:Nn,setSourceMapsEnabled:Un}}),ce=He(()=>{sc()});function ac(){if(Jn)return Ot;Jn=!0,Ot.byteLength=s,Ot.toByteArray=l,Ot.fromByteArray=p;for(var c=[],e=[],t=typeof Uint8Array<"u"?Uint8Array:Array,r="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",a=0,n=r.length;a<n;++a)c[a]=r[a],e[r.charCodeAt(a)]=a;e[45]=62,e[95]=63;function i(y){var f=y.length;if(f%4>0)throw new Error("Invalid string. Length must be a multiple of 4");var m=y.indexOf("=");m===-1&&(m=f);var b=m===f?0:4-m%4;return[m,b]}function s(y){var f=i(y),m=f[0],b=f[1];return(m+b)*3/4-b}function o(y,f,m){return(f+m)*3/4-m}function l(y){var f,m=i(y),b=m[0],k=m[1],g=new t(o(y,b,k)),_=0,S=k>0?b-4:b,v;for(v=0;v<S;v+=4)f=e[y.charCodeAt(v)]<<18|e[y.charCodeAt(v+1)]<<12|e[y.charCodeAt(v+2)]<<6|e[y.charCodeAt(v+3)],g[_++]=f>>16&255,g[_++]=f>>8&255,g[_++]=f&255;return k===2&&(f=e[y.charCodeAt(v)]<<2|e[y.charCodeAt(v+1)]>>4,g[_++]=f&255),k===1&&(f=e[y.charCodeAt(v)]<<10|e[y.charCodeAt(v+1)]<<4|e[y.charCodeAt(v+2)]>>2,g[_++]=f>>8&255,g[_++]=f&255),g}function u(y){return c[y>>18&63]+c[y>>12&63]+c[y>>6&63]+c[y&63]}function d(y,f,m){for(var b,k=[],g=f;g<m;g+=3)b=(y[g]<<16&16711680)+(y[g+1]<<8&65280)+(y[g+2]&255),k.push(u(b));return k.join("")}function p(y){for(var f,m=y.length,b=m%3,k=[],g=16383,_=0,S=m-b;_<S;_+=g)k.push(d(y,_,_+g>S?S:_+g));return b===1?(f=y[m-1],k.push(c[f>>2]+c[f<<4&63]+"==")):b===2&&(f=(y[m-2]<<8)+y[m-1],k.push(c[f>>10]+c[f>>4&63]+c[f<<2&63]+"=")),k.join("")}return Ot}function lc(){return Xn?Wt:(Xn=!0,Wt.read=function(c,e,t,r,a){var n,i,s=a*8-r-1,o=(1<<s)-1,l=o>>1,u=-7,d=t?a-1:0,p=t?-1:1,y=c[e+d];for(d+=p,n=y&(1<<-u)-1,y>>=-u,u+=s;u>0;n=n*256+c[e+d],d+=p,u-=8);for(i=n&(1<<-u)-1,n>>=-u,u+=r;u>0;i=i*256+c[e+d],d+=p,u-=8);if(n===0)n=1-l;else{if(n===o)return i?NaN:(y?-1:1)*(1/0);i=i+Math.pow(2,r),n=n-l}return(y?-1:1)*i*Math.pow(2,n-r)},Wt.write=function(c,e,t,r,a,n){var i,s,o,l=n*8-a-1,u=(1<<l)-1,d=u>>1,p=a===23?Math.pow(2,-24)-Math.pow(2,-77):0,y=r?0:n-1,f=r?1:-1,m=e<0||e===0&&1/e<0?1:0;for(e=Math.abs(e),isNaN(e)||e===1/0?(s=isNaN(e)?1:0,i=u):(i=Math.floor(Math.log(e)/Math.LN2),e*(o=Math.pow(2,-i))<1&&(i--,o*=2),i+d>=1?e+=p/o:e+=p*Math.pow(2,1-d),e*o>=2&&(i++,o/=2),i+d>=u?(s=0,i=u):i+d>=1?(s=(e*o-1)*Math.pow(2,a),i=i+d):(s=e*Math.pow(2,d-1)*Math.pow(2,a),i=0));a>=8;c[t+y]=s&255,y+=f,s/=256,a-=8);for(i=i<<a|s,l+=a;l>0;c[t+y]=i&255,y+=f,i/=256,l-=8);c[t+y-f]|=m*128},Wt)}function cc(){if(Zn)return dt;Zn=!0;let c=ac(),e=lc(),t=typeof Symbol=="function"&&typeof Symbol.for=="function"?Symbol.for("nodejs.util.inspect.custom"):null;dt.Buffer=i,dt.SlowBuffer=k,dt.INSPECT_MAX_BYTES=50;let r=2147483647;dt.kMaxLength=r,i.TYPED_ARRAY_SUPPORT=a(),!i.TYPED_ARRAY_SUPPORT&&typeof console<"u"&&typeof console.error=="function"&&console.error("This browser lacks typed array (Uint8Array) support which is required by `buffer` v5.x. Use `buffer` v4.x if you require old browser support.");function a(){try{let h=new Uint8Array(1),w={foo:function(){return 42}};return Object.setPrototypeOf(w,Uint8Array.prototype),Object.setPrototypeOf(h,w),h.foo()===42}catch{return!1}}Object.defineProperty(i.prototype,"parent",{enumerable:!0,get:function(){if(i.isBuffer(this))return this.buffer}}),Object.defineProperty(i.prototype,"offset",{enumerable:!0,get:function(){if(i.isBuffer(this))return this.byteOffset}});function n(h){if(h>r)throw new RangeError('The value "'+h+'" is invalid for option "size"');let w=new Uint8Array(h);return Object.setPrototypeOf(w,i.prototype),w}function i(h,w,A){if(typeof h=="number"){if(typeof w=="string")throw new TypeError('The "string" argument must be of type string. Received type number');return u(h)}return s(h,w,A)}i.poolSize=8192;function s(h,w,A){if(typeof h=="string")return d(h,w);if(ArrayBuffer.isView(h))return y(h);if(h==null)throw new TypeError("The first argument must be one of type string, Buffer, ArrayBuffer, Array, or Array-like Object. Received type "+typeof h);if(q(h,ArrayBuffer)||h&&q(h.buffer,ArrayBuffer)||typeof SharedArrayBuffer<"u"&&(q(h,SharedArrayBuffer)||h&&q(h.buffer,SharedArrayBuffer)))return f(h,w,A);if(typeof h=="number")throw new TypeError('The "value" argument must not be of type number. Received type number');let U=h.valueOf&&h.valueOf();if(U!=null&&U!==h)return i.from(U,w,A);let X=m(h);if(X)return X;if(typeof Symbol<"u"&&Symbol.toPrimitive!=null&&typeof h[Symbol.toPrimitive]=="function")return i.from(h[Symbol.toPrimitive]("string"),w,A);throw new TypeError("The first argument must be one of type string, Buffer, ArrayBuffer, Array, or Array-like Object. Received type "+typeof h)}i.from=function(h,w,A){return s(h,w,A)},Object.setPrototypeOf(i.prototype,Uint8Array.prototype),Object.setPrototypeOf(i,Uint8Array);function o(h){if(typeof h!="number")throw new TypeError('"size" argument must be of type number');if(h<0)throw new RangeError('The value "'+h+'" is invalid for option "size"')}function l(h,w,A){return o(h),h<=0?n(h):w!==void 0?typeof A=="string"?n(h).fill(w,A):n(h).fill(w):n(h)}i.alloc=function(h,w,A){return l(h,w,A)};function u(h){return o(h),n(h<0?0:b(h)|0)}i.allocUnsafe=function(h){return u(h)},i.allocUnsafeSlow=function(h){return u(h)};function d(h,w){if((typeof w!="string"||w==="")&&(w="utf8"),!i.isEncoding(w))throw new TypeError("Unknown encoding: "+w);let A=g(h,w)|0,U=n(A),X=U.write(h,w);return X!==A&&(U=U.slice(0,X)),U}function p(h){let w=h.length<0?0:b(h.length)|0,A=n(w);for(let U=0;U<w;U+=1)A[U]=h[U]&255;return A}function y(h){if(q(h,Uint8Array)){let w=new Uint8Array(h);return f(w.buffer,w.byteOffset,w.byteLength)}return p(h)}function f(h,w,A){if(w<0||h.byteLength<w)throw new RangeError('"offset" is outside of buffer bounds');if(h.byteLength<w+(A||0))throw new RangeError('"length" is outside of buffer bounds');let U;return w===void 0&&A===void 0?U=new Uint8Array(h):A===void 0?U=new Uint8Array(h,w):U=new Uint8Array(h,w,A),Object.setPrototypeOf(U,i.prototype),U}function m(h){if(i.isBuffer(h)){let w=b(h.length)|0,A=n(w);return A.length===0||h.copy(A,0,0,w),A}if(h.length!==void 0)return typeof h.length!="number"||ge(h.length)?n(0):p(h);if(h.type==="Buffer"&&Array.isArray(h.data))return p(h.data)}function b(h){if(h>=r)throw new RangeError("Attempt to allocate Buffer larger than maximum size: 0x"+r.toString(16)+" bytes");return h|0}function k(h){return+h!=h&&(h=0),i.alloc(+h)}i.isBuffer=function(h){return h!=null&&h._isBuffer===!0&&h!==i.prototype},i.compare=function(h,w){if(q(h,Uint8Array)&&(h=i.from(h,h.offset,h.byteLength)),q(w,Uint8Array)&&(w=i.from(w,w.offset,w.byteLength)),!i.isBuffer(h)||!i.isBuffer(w))throw new TypeError('The "buf1", "buf2" arguments must be one of type Buffer or Uint8Array');if(h===w)return 0;let A=h.length,U=w.length;for(let X=0,he=Math.min(A,U);X<he;++X)if(h[X]!==w[X]){A=h[X],U=w[X];break}return A<U?-1:U<A?1:0},i.isEncoding=function(h){switch(String(h).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}},i.concat=function(h,w){if(!Array.isArray(h))throw new TypeError('"list" argument must be an Array of Buffers');if(h.length===0)return i.alloc(0);let A;if(w===void 0)for(w=0,A=0;A<h.length;++A)w+=h[A].length;let U=i.allocUnsafe(w),X=0;for(A=0;A<h.length;++A){let he=h[A];if(q(he,Uint8Array))X+he.length>U.length?(i.isBuffer(he)||(he=i.from(he)),he.copy(U,X)):Uint8Array.prototype.set.call(U,he,X);else if(i.isBuffer(he))he.copy(U,X);else throw new TypeError('"list" argument must be an Array of Buffers');X+=he.length}return U};function g(h,w){if(i.isBuffer(h))return h.length;if(ArrayBuffer.isView(h)||q(h,ArrayBuffer))return h.byteLength;if(typeof h!="string")throw new TypeError('The "string" argument must be one of type string, Buffer, or ArrayBuffer. Received type '+typeof h);let A=h.length,U=arguments.length>2&&arguments[2]===!0;if(!U&&A===0)return 0;let X=!1;for(;;)switch(w){case"ascii":case"latin1":case"binary":return A;case"utf8":case"utf-8":return $(h).length;case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return A*2;case"hex":return A>>>1;case"base64":return de(h).length;default:if(X)return U?-1:$(h).length;w=(""+w).toLowerCase(),X=!0}}i.byteLength=g;function _(h,w,A){let U=!1;if((w===void 0||w<0)&&(w=0),w>this.length||((A===void 0||A>this.length)&&(A=this.length),A<=0)||(A>>>=0,w>>>=0,A<=w))return"";for(h||(h="utf8");;)switch(h){case"hex":return K(this,w,A);case"utf8":case"utf-8":return W(this,w,A);case"ascii":return ae(this,w,A);case"latin1":case"binary":return Y(this,w,A);case"base64":return T(this,w,A);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return re(this,w,A);default:if(U)throw new TypeError("Unknown encoding: "+h);h=(h+"").toLowerCase(),U=!0}}i.prototype._isBuffer=!0;function S(h,w,A){let U=h[w];h[w]=h[A],h[A]=U}i.prototype.swap16=function(){let h=this.length;if(h%2!==0)throw new RangeError("Buffer size must be a multiple of 16-bits");for(let w=0;w<h;w+=2)S(this,w,w+1);return this},i.prototype.swap32=function(){let h=this.length;if(h%4!==0)throw new RangeError("Buffer size must be a multiple of 32-bits");for(let w=0;w<h;w+=4)S(this,w,w+3),S(this,w+1,w+2);return this},i.prototype.swap64=function(){let h=this.length;if(h%8!==0)throw new RangeError("Buffer size must be a multiple of 64-bits");for(let w=0;w<h;w+=8)S(this,w,w+7),S(this,w+1,w+6),S(this,w+2,w+5),S(this,w+3,w+4);return this},i.prototype.toString=function(){let h=this.length;return h===0?"":arguments.length===0?W(this,0,h):_.apply(this,arguments)},i.prototype.toLocaleString=i.prototype.toString,i.prototype.equals=function(h){if(!i.isBuffer(h))throw new TypeError("Argument must be a Buffer");return this===h?!0:i.compare(this,h)===0},i.prototype.inspect=function(){let h="",w=dt.INSPECT_MAX_BYTES;return h=this.toString("hex",0,w).replace(/(.{2})/g,"$1 ").trim(),this.length>w&&(h+=" ... "),"<Buffer "+h+">"},t&&(i.prototype[t]=i.prototype.inspect),i.prototype.compare=function(h,w,A,U,X){if(q(h,Uint8Array)&&(h=i.from(h,h.offset,h.byteLength)),!i.isBuffer(h))throw new TypeError('The "target" argument must be one of type Buffer or Uint8Array. Received type '+typeof h);if(w===void 0&&(w=0),A===void 0&&(A=h?h.length:0),U===void 0&&(U=0),X===void 0&&(X=this.length),w<0||A>h.length||U<0||X>this.length)throw new RangeError("out of range index");if(U>=X&&w>=A)return 0;if(U>=X)return-1;if(w>=A)return 1;if(w>>>=0,A>>>=0,U>>>=0,X>>>=0,this===h)return 0;let he=X-U,ke=A-w,z=Math.min(he,ke),ie=this.slice(U,X),xe=h.slice(w,A);for(let Ae=0;Ae<z;++Ae)if(ie[Ae]!==xe[Ae]){he=ie[Ae],ke=xe[Ae];break}return he<ke?-1:ke<he?1:0};function v(h,w,A,U,X){if(h.length===0)return-1;if(typeof A=="string"?(U=A,A=0):A>2147483647?A=2147483647:A<-2147483648&&(A=-2147483648),A=+A,ge(A)&&(A=X?0:h.length-1),A<0&&(A=h.length+A),A>=h.length){if(X)return-1;A=h.length-1}else if(A<0)if(X)A=0;else return-1;if(typeof w=="string"&&(w=i.from(w,U)),i.isBuffer(w))return w.length===0?-1:x(h,w,A,U,X);if(typeof w=="number")return w=w&255,typeof Uint8Array.prototype.indexOf=="function"?X?Uint8Array.prototype.indexOf.call(h,w,A):Uint8Array.prototype.lastIndexOf.call(h,w,A):x(h,[w],A,U,X);throw new TypeError("val must be string, number or Buffer")}function x(h,w,A,U,X){let he=1,ke=h.length,z=w.length;if(U!==void 0&&(U=String(U).toLowerCase(),U==="ucs2"||U==="ucs-2"||U==="utf16le"||U==="utf-16le")){if(h.length<2||w.length<2)return-1;he=2,ke/=2,z/=2,A/=2}function ie(Ae,Ie){return he===1?Ae[Ie]:Ae.readUInt16BE(Ie*he)}let xe;if(X){let Ae=-1;for(xe=A;xe<ke;xe++)if(ie(h,xe)===ie(w,Ae===-1?0:xe-Ae)){if(Ae===-1&&(Ae=xe),xe-Ae+1===z)return Ae*he}else Ae!==-1&&(xe-=xe-Ae),Ae=-1}else for(A+z>ke&&(A=ke-z),xe=A;xe>=0;xe--){let Ae=!0;for(let Ie=0;Ie<z;Ie++)if(ie(h,xe+Ie)!==ie(w,Ie)){Ae=!1;break}if(Ae)return xe}return-1}i.prototype.includes=function(h,w,A){return this.indexOf(h,w,A)!==-1},i.prototype.indexOf=function(h,w,A){return v(this,h,w,A,!0)},i.prototype.lastIndexOf=function(h,w,A){return v(this,h,w,A,!1)};function E(h,w,A,U){A=Number(A)||0;let X=h.length-A;U?(U=Number(U),U>X&&(U=X)):U=X;let he=w.length;U>he/2&&(U=he/2);let ke;for(ke=0;ke<U;++ke){let z=parseInt(w.substr(ke*2,2),16);if(ge(z))return ke;h[A+ke]=z}return ke}function I(h,w,A,U){return ye($(w,h.length-A),h,A,U)}function M(h,w,A,U){return ye(ee(w),h,A,U)}function O(h,w,A,U){return ye(de(w),h,A,U)}function B(h,w,A,U){return ye(fe(w,h.length-A),h,A,U)}i.prototype.write=function(h,w,A,U){if(w===void 0)U="utf8",A=this.length,w=0;else if(A===void 0&&typeof w=="string")U=w,A=this.length,w=0;else if(isFinite(w))w=w>>>0,isFinite(A)?(A=A>>>0,U===void 0&&(U="utf8")):(U=A,A=void 0);else throw new Error("Buffer.write(string, encoding, offset[, length]) is no longer supported");let X=this.length-w;if((A===void 0||A>X)&&(A=X),h.length>0&&(A<0||w<0)||w>this.length)throw new RangeError("Attempt to write outside buffer bounds");U||(U="utf8");let he=!1;for(;;)switch(U){case"hex":return E(this,h,w,A);case"utf8":case"utf-8":return I(this,h,w,A);case"ascii":case"latin1":case"binary":return M(this,h,w,A);case"base64":return O(this,h,w,A);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return B(this,h,w,A);default:if(he)throw new TypeError("Unknown encoding: "+U);U=(""+U).toLowerCase(),he=!0}},i.prototype.toJSON=function(){return{type:"Buffer",data:Array.prototype.slice.call(this._arr||this,0)}};function T(h,w,A){return w===0&&A===h.length?c.fromByteArray(h):c.fromByteArray(h.slice(w,A))}function W(h,w,A){A=Math.min(h.length,A);let U=[],X=w;for(;X<A;){let he=h[X],ke=null,z=he>239?4:he>223?3:he>191?2:1;if(X+z<=A){let ie,xe,Ae,Ie;switch(z){case 1:he<128&&(ke=he);break;case 2:ie=h[X+1],(ie&192)===128&&(Ie=(he&31)<<6|ie&63,Ie>127&&(ke=Ie));break;case 3:ie=h[X+1],xe=h[X+2],(ie&192)===128&&(xe&192)===128&&(Ie=(he&15)<<12|(ie&63)<<6|xe&63,Ie>2047&&(Ie<55296||Ie>57343)&&(ke=Ie));break;case 4:ie=h[X+1],xe=h[X+2],Ae=h[X+3],(ie&192)===128&&(xe&192)===128&&(Ae&192)===128&&(Ie=(he&15)<<18|(ie&63)<<12|(xe&63)<<6|Ae&63,Ie>65535&&Ie<1114112&&(ke=Ie))}}ke===null?(ke=65533,z=1):ke>65535&&(ke-=65536,U.push(ke>>>10&1023|55296),ke=56320|ke&1023),U.push(ke),X+=z}return N(U)}let F=4096;function N(h){let w=h.length;if(w<=F)return String.fromCharCode.apply(String,h);let A="",U=0;for(;U<w;)A+=String.fromCharCode.apply(String,h.slice(U,U+=F));return A}function ae(h,w,A){let U="";A=Math.min(h.length,A);for(let X=w;X<A;++X)U+=String.fromCharCode(h[X]&127);return U}function Y(h,w,A){let U="";A=Math.min(h.length,A);for(let X=w;X<A;++X)U+=String.fromCharCode(h[X]);return U}function K(h,w,A){let U=h.length;(!w||w<0)&&(w=0),(!A||A<0||A>U)&&(A=U);let X="";for(let he=w;he<A;++he)X+=ve[h[he]];return X}function re(h,w,A){let U=h.slice(w,A),X="";for(let he=0;he<U.length-1;he+=2)X+=String.fromCharCode(U[he]+U[he+1]*256);return X}i.prototype.slice=function(h,w){let A=this.length;h=~~h,w=w===void 0?A:~~w,h<0?(h+=A,h<0&&(h=0)):h>A&&(h=A),w<0?(w+=A,w<0&&(w=0)):w>A&&(w=A),w<h&&(w=h);let U=this.subarray(h,w);return Object.setPrototypeOf(U,i.prototype),U};function D(h,w,A){if(h%1!==0||h<0)throw new RangeError("offset is not uint");if(h+w>A)throw new RangeError("Trying to access beyond buffer length")}i.prototype.readUintLE=i.prototype.readUIntLE=function(h,w,A){h=h>>>0,w=w>>>0,A||D(h,w,this.length);let U=this[h],X=1,he=0;for(;++he<w&&(X*=256);)U+=this[h+he]*X;return U},i.prototype.readUintBE=i.prototype.readUIntBE=function(h,w,A){h=h>>>0,w=w>>>0,A||D(h,w,this.length);let U=this[h+--w],X=1;for(;w>0&&(X*=256);)U+=this[h+--w]*X;return U},i.prototype.readUint8=i.prototype.readUInt8=function(h,w){return h=h>>>0,w||D(h,1,this.length),this[h]},i.prototype.readUint16LE=i.prototype.readUInt16LE=function(h,w){return h=h>>>0,w||D(h,2,this.length),this[h]|this[h+1]<<8},i.prototype.readUint16BE=i.prototype.readUInt16BE=function(h,w){return h=h>>>0,w||D(h,2,this.length),this[h]<<8|this[h+1]},i.prototype.readUint32LE=i.prototype.readUInt32LE=function(h,w){return h=h>>>0,w||D(h,4,this.length),(this[h]|this[h+1]<<8|this[h+2]<<16)+this[h+3]*16777216},i.prototype.readUint32BE=i.prototype.readUInt32BE=function(h,w){return h=h>>>0,w||D(h,4,this.length),this[h]*16777216+(this[h+1]<<16|this[h+2]<<8|this[h+3])},i.prototype.readBigUInt64LE=se(function(h){h=h>>>0,Q(h,"offset");let w=this[h],A=this[h+7];(w===void 0||A===void 0)&&me(h,this.length-8);let U=w+this[++h]*2**8+this[++h]*2**16+this[++h]*2**24,X=this[++h]+this[++h]*2**8+this[++h]*2**16+A*2**24;return BigInt(U)+(BigInt(X)<<BigInt(32))}),i.prototype.readBigUInt64BE=se(function(h){h=h>>>0,Q(h,"offset");let w=this[h],A=this[h+7];(w===void 0||A===void 0)&&me(h,this.length-8);let U=w*2**24+this[++h]*2**16+this[++h]*2**8+this[++h],X=this[++h]*2**24+this[++h]*2**16+this[++h]*2**8+A;return(BigInt(U)<<BigInt(32))+BigInt(X)}),i.prototype.readIntLE=function(h,w,A){h=h>>>0,w=w>>>0,A||D(h,w,this.length);let U=this[h],X=1,he=0;for(;++he<w&&(X*=256);)U+=this[h+he]*X;return X*=128,U>=X&&(U-=Math.pow(2,8*w)),U},i.prototype.readIntBE=function(h,w,A){h=h>>>0,w=w>>>0,A||D(h,w,this.length);let U=w,X=1,he=this[h+--U];for(;U>0&&(X*=256);)he+=this[h+--U]*X;return X*=128,he>=X&&(he-=Math.pow(2,8*w)),he},i.prototype.readInt8=function(h,w){return h=h>>>0,w||D(h,1,this.length),this[h]&128?(255-this[h]+1)*-1:this[h]},i.prototype.readInt16LE=function(h,w){h=h>>>0,w||D(h,2,this.length);let A=this[h]|this[h+1]<<8;return A&32768?A|4294901760:A},i.prototype.readInt16BE=function(h,w){h=h>>>0,w||D(h,2,this.length);let A=this[h+1]|this[h]<<8;return A&32768?A|4294901760:A},i.prototype.readInt32LE=function(h,w){return h=h>>>0,w||D(h,4,this.length),this[h]|this[h+1]<<8|this[h+2]<<16|this[h+3]<<24},i.prototype.readInt32BE=function(h,w){return h=h>>>0,w||D(h,4,this.length),this[h]<<24|this[h+1]<<16|this[h+2]<<8|this[h+3]},i.prototype.readBigInt64LE=se(function(h){h=h>>>0,Q(h,"offset");let w=this[h],A=this[h+7];(w===void 0||A===void 0)&&me(h,this.length-8);let U=this[h+4]+this[h+5]*2**8+this[h+6]*2**16+(A<<24);return(BigInt(U)<<BigInt(32))+BigInt(w+this[++h]*256+this[++h]*65536+this[++h]*16777216)}),i.prototype.readBigInt64BE=se(function(h){h=h>>>0,Q(h,"offset");let w=this[h],A=this[h+7];(w===void 0||A===void 0)&&me(h,this.length-8);let U=(w<<24)+this[++h]*2**16+this[++h]*2**8+this[++h];return(BigInt(U)<<BigInt(32))+BigInt(this[++h]*16777216+this[++h]*65536+this[++h]*256+A)}),i.prototype.readFloatLE=function(h,w){return h=h>>>0,w||D(h,4,this.length),e.read(this,h,!0,23,4)},i.prototype.readFloatBE=function(h,w){return h=h>>>0,w||D(h,4,this.length),e.read(this,h,!1,23,4)},i.prototype.readDoubleLE=function(h,w){return h=h>>>0,w||D(h,8,this.length),e.read(this,h,!0,52,8)},i.prototype.readDoubleBE=function(h,w){return h=h>>>0,w||D(h,8,this.length),e.read(this,h,!1,52,8)};function Z(h,w,A,U,X,he){if(!i.isBuffer(h))throw new TypeError('"buffer" argument must be a Buffer instance');if(w>X||w<he)throw new RangeError('"value" argument is out of bounds');if(A+U>h.length)throw new RangeError("Index out of range")}i.prototype.writeUintLE=i.prototype.writeUIntLE=function(h,w,A,U){if(h=+h,w=w>>>0,A=A>>>0,!U){let ke=Math.pow(2,8*A)-1;Z(this,h,w,A,ke,0)}let X=1,he=0;for(this[w]=h&255;++he<A&&(X*=256);)this[w+he]=h/X&255;return w+A},i.prototype.writeUintBE=i.prototype.writeUIntBE=function(h,w,A,U){if(h=+h,w=w>>>0,A=A>>>0,!U){let ke=Math.pow(2,8*A)-1;Z(this,h,w,A,ke,0)}let X=A-1,he=1;for(this[w+X]=h&255;--X>=0&&(he*=256);)this[w+X]=h/he&255;return w+A},i.prototype.writeUint8=i.prototype.writeUInt8=function(h,w,A){return h=+h,w=w>>>0,A||Z(this,h,w,1,255,0),this[w]=h&255,w+1},i.prototype.writeUint16LE=i.prototype.writeUInt16LE=function(h,w,A){return h=+h,w=w>>>0,A||Z(this,h,w,2,65535,0),this[w]=h&255,this[w+1]=h>>>8,w+2},i.prototype.writeUint16BE=i.prototype.writeUInt16BE=function(h,w,A){return h=+h,w=w>>>0,A||Z(this,h,w,2,65535,0),this[w]=h>>>8,this[w+1]=h&255,w+2},i.prototype.writeUint32LE=i.prototype.writeUInt32LE=function(h,w,A){return h=+h,w=w>>>0,A||Z(this,h,w,4,4294967295,0),this[w+3]=h>>>24,this[w+2]=h>>>16,this[w+1]=h>>>8,this[w]=h&255,w+4},i.prototype.writeUint32BE=i.prototype.writeUInt32BE=function(h,w,A){return h=+h,w=w>>>0,A||Z(this,h,w,4,4294967295,0),this[w]=h>>>24,this[w+1]=h>>>16,this[w+2]=h>>>8,this[w+3]=h&255,w+4};function P(h,w,A,U,X){G(w,U,X,h,A,7);let he=Number(w&BigInt(4294967295));h[A++]=he,he=he>>8,h[A++]=he,he=he>>8,h[A++]=he,he=he>>8,h[A++]=he;let ke=Number(w>>BigInt(32)&BigInt(4294967295));return h[A++]=ke,ke=ke>>8,h[A++]=ke,ke=ke>>8,h[A++]=ke,ke=ke>>8,h[A++]=ke,A}function J(h,w,A,U,X){G(w,U,X,h,A,7);let he=Number(w&BigInt(4294967295));h[A+7]=he,he=he>>8,h[A+6]=he,he=he>>8,h[A+5]=he,he=he>>8,h[A+4]=he;let ke=Number(w>>BigInt(32)&BigInt(4294967295));return h[A+3]=ke,ke=ke>>8,h[A+2]=ke,ke=ke>>8,h[A+1]=ke,ke=ke>>8,h[A]=ke,A+8}i.prototype.writeBigUInt64LE=se(function(h,w=0){return P(this,h,w,BigInt(0),BigInt("0xffffffffffffffff"))}),i.prototype.writeBigUInt64BE=se(function(h,w=0){return J(this,h,w,BigInt(0),BigInt("0xffffffffffffffff"))}),i.prototype.writeIntLE=function(h,w,A,U){if(h=+h,w=w>>>0,!U){let z=Math.pow(2,8*A-1);Z(this,h,w,A,z-1,-z)}let X=0,he=1,ke=0;for(this[w]=h&255;++X<A&&(he*=256);)h<0&&ke===0&&this[w+X-1]!==0&&(ke=1),this[w+X]=(h/he>>0)-ke&255;return w+A},i.prototype.writeIntBE=function(h,w,A,U){if(h=+h,w=w>>>0,!U){let z=Math.pow(2,8*A-1);Z(this,h,w,A,z-1,-z)}let X=A-1,he=1,ke=0;for(this[w+X]=h&255;--X>=0&&(he*=256);)h<0&&ke===0&&this[w+X+1]!==0&&(ke=1),this[w+X]=(h/he>>0)-ke&255;return w+A},i.prototype.writeInt8=function(h,w,A){return h=+h,w=w>>>0,A||Z(this,h,w,1,127,-128),h<0&&(h=255+h+1),this[w]=h&255,w+1},i.prototype.writeInt16LE=function(h,w,A){return h=+h,w=w>>>0,A||Z(this,h,w,2,32767,-32768),this[w]=h&255,this[w+1]=h>>>8,w+2},i.prototype.writeInt16BE=function(h,w,A){return h=+h,w=w>>>0,A||Z(this,h,w,2,32767,-32768),this[w]=h>>>8,this[w+1]=h&255,w+2},i.prototype.writeInt32LE=function(h,w,A){return h=+h,w=w>>>0,A||Z(this,h,w,4,2147483647,-2147483648),this[w]=h&255,this[w+1]=h>>>8,this[w+2]=h>>>16,this[w+3]=h>>>24,w+4},i.prototype.writeInt32BE=function(h,w,A){return h=+h,w=w>>>0,A||Z(this,h,w,4,2147483647,-2147483648),h<0&&(h=4294967295+h+1),this[w]=h>>>24,this[w+1]=h>>>16,this[w+2]=h>>>8,this[w+3]=h&255,w+4},i.prototype.writeBigInt64LE=se(function(h,w=0){return P(this,h,w,-BigInt("0x8000000000000000"),BigInt("0x7fffffffffffffff"))}),i.prototype.writeBigInt64BE=se(function(h,w=0){return J(this,h,w,-BigInt("0x8000000000000000"),BigInt("0x7fffffffffffffff"))});function be(h,w,A,U,X,he){if(A+U>h.length)throw new RangeError("Index out of range");if(A<0)throw new RangeError("Index out of range")}function te(h,w,A,U,X){return w=+w,A=A>>>0,X||be(h,w,A,4),e.write(h,w,A,U,23,4),A+4}i.prototype.writeFloatLE=function(h,w,A){return te(this,h,w,!0,A)},i.prototype.writeFloatBE=function(h,w,A){return te(this,h,w,!1,A)};function we(h,w,A,U,X){return w=+w,A=A>>>0,X||be(h,w,A,8),e.write(h,w,A,U,52,8),A+8}i.prototype.writeDoubleLE=function(h,w,A){return we(this,h,w,!0,A)},i.prototype.writeDoubleBE=function(h,w,A){return we(this,h,w,!1,A)},i.prototype.copy=function(h,w,A,U){if(!i.isBuffer(h))throw new TypeError("argument should be a Buffer");if(A||(A=0),!U&&U!==0&&(U=this.length),w>=h.length&&(w=h.length),w||(w=0),U>0&&U<A&&(U=A),U===A||h.length===0||this.length===0)return 0;if(w<0)throw new RangeError("targetStart out of bounds");if(A<0||A>=this.length)throw new RangeError("Index out of range");if(U<0)throw new RangeError("sourceEnd out of bounds");U>this.length&&(U=this.length),h.length-w<U-A&&(U=h.length-w+A);let X=U-A;return this===h&&typeof Uint8Array.prototype.copyWithin=="function"?this.copyWithin(w,A,U):Uint8Array.prototype.set.call(h,this.subarray(A,U),w),X},i.prototype.fill=function(h,w,A,U){if(typeof h=="string"){if(typeof w=="string"?(U=w,w=0,A=this.length):typeof A=="string"&&(U=A,A=this.length),U!==void 0&&typeof U!="string")throw new TypeError("encoding must be a string");if(typeof U=="string"&&!i.isEncoding(U))throw new TypeError("Unknown encoding: "+U);if(h.length===1){let he=h.charCodeAt(0);(U==="utf8"&&he<128||U==="latin1")&&(h=he)}}else typeof h=="number"?h=h&255:typeof h=="boolean"&&(h=Number(h));if(w<0||this.length<w||this.length<A)throw new RangeError("Out of range index");if(A<=w)return this;w=w>>>0,A=A===void 0?this.length:A>>>0,h||(h=0);let X;if(typeof h=="number")for(X=w;X<A;++X)this[X]=h;else{let he=i.isBuffer(h)?h:i.from(h,U),ke=he.length;if(ke===0)throw new TypeError('The value "'+h+'" is invalid for argument "value"');for(X=0;X<A-w;++X)this[X+w]=he[X%ke]}return this};let V={};function L(h,w,A){V[h]=class extends A{constructor(){super(),Object.defineProperty(this,"message",{value:w.apply(this,arguments),writable:!0,configurable:!0}),this.name=`${this.name} [${h}]`,this.stack,delete this.name}get code(){return h}set code(U){Object.defineProperty(this,"code",{configurable:!0,enumerable:!0,value:U,writable:!0})}toString(){return`${this.name} [${h}]: ${this.message}`}}}L("ERR_BUFFER_OUT_OF_BOUNDS",function(h){return h?`${h} is outside of buffer bounds`:"Attempt to access memory outside buffer bounds"},RangeError),L("ERR_INVALID_ARG_TYPE",function(h,w){return`The "${h}" argument must be of type number. Received type ${typeof w}`},TypeError),L("ERR_OUT_OF_RANGE",function(h,w,A){let U=`The value of "${h}" is out of range.`,X=A;return Number.isInteger(A)&&Math.abs(A)>4294967296?X=ne(String(A)):typeof A=="bigint"&&(X=String(A),(A>BigInt(2)**BigInt(32)||A<-(BigInt(2)**BigInt(32)))&&(X=ne(X)),X+="n"),U+=` It must be ${w}. Received ${X}`,U},RangeError);function ne(h){let w="",A=h.length,U=h[0]==="-"?1:0;for(;A>=U+4;A-=3)w=`_${h.slice(A-3,A)}${w}`;return`${h.slice(0,A)}${w}`}function H(h,w,A){Q(w,"offset"),(h[w]===void 0||h[w+A]===void 0)&&me(w,h.length-(A+1))}function G(h,w,A,U,X,he){if(h>A||h<w){let ke=typeof w=="bigint"?"n":"",z;throw w===0||w===BigInt(0)?z=`>= 0${ke} and < 2${ke} ** ${(he+1)*8}${ke}`:z=`>= -(2${ke} ** ${(he+1)*8-1}${ke}) and < 2 ** ${(he+1)*8-1}${ke}`,new V.ERR_OUT_OF_RANGE("value",z,h)}H(U,X,he)}function Q(h,w){if(typeof h!="number")throw new V.ERR_INVALID_ARG_TYPE(w,"number",h)}function me(h,w,A){throw Math.floor(h)!==h?(Q(h,A),new V.ERR_OUT_OF_RANGE("offset","an integer",h)):w<0?new V.ERR_BUFFER_OUT_OF_BOUNDS:new V.ERR_OUT_OF_RANGE("offset",`>= 0 and <= ${w}`,h)}let oe=/[^+/0-9A-Za-z-_]/g;function R(h){if(h=h.split("=")[0],h=h.trim().replace(oe,""),h.length<2)return"";for(;h.length%4!==0;)h=h+"=";return h}function $(h,w){w=w||1/0;let A,U=h.length,X=null,he=[];for(let ke=0;ke<U;++ke){if(A=h.charCodeAt(ke),A>55295&&A<57344){if(!X){if(A>56319){(w-=3)>-1&&he.push(239,191,189);continue}else if(ke+1===U){(w-=3)>-1&&he.push(239,191,189);continue}X=A;continue}if(A<56320){(w-=3)>-1&&he.push(239,191,189),X=A;continue}A=(X-55296<<10|A-56320)+65536}else X&&(w-=3)>-1&&he.push(239,191,189);if(X=null,A<128){if((w-=1)<0)break;he.push(A)}else if(A<2048){if((w-=2)<0)break;he.push(A>>6|192,A&63|128)}else if(A<65536){if((w-=3)<0)break;he.push(A>>12|224,A>>6&63|128,A&63|128)}else if(A<1114112){if((w-=4)<0)break;he.push(A>>18|240,A>>12&63|128,A>>6&63|128,A&63|128)}else throw new Error("Invalid code point")}return he}function ee(h){let w=[];for(let A=0;A<h.length;++A)w.push(h.charCodeAt(A)&255);return w}function fe(h,w){let A,U,X,he=[];for(let ke=0;ke<h.length&&!((w-=2)<0);++ke)A=h.charCodeAt(ke),U=A>>8,X=A%256,he.push(X),he.push(U);return he}function de(h){return c.toByteArray(R(h))}function ye(h,w,A,U){let X;for(X=0;X<U&&!(X+A>=w.length||X>=h.length);++X)w[X+A]=h[X];return X}function q(h,w){return h instanceof w||h!=null&&h.constructor!=null&&h.constructor.name!=null&&h.constructor.name===w.name}function ge(h){return h!==h}let ve=(function(){let h="0123456789abcdef",w=new Array(256);for(let A=0;A<16;++A){let U=A*16;for(let X=0;X<16;++X)w[U+X]=h[A]+h[X]}return w})();function se(h){return typeof BigInt>"u"?Te:h}function Te(){throw new Error("BigInt not supported")}return dt}var Ot,Jn,Wt,Xn,dt,Zn,uc=He(()=>{le(),ue(),ce(),Ot={},Jn=!1,Wt={},Xn=!1,dt={},Zn=!1}),Ne={};Ct(Ne,{Buffer:()=>rr,INSPECT_MAX_BYTES:()=>Lo,default:()=>ot,kMaxLength:()=>No});var ot,rr,Lo,No,Ue=He(()=>{le(),ue(),ce(),uc(),ot=cc(),ot.Buffer,ot.SlowBuffer,ot.INSPECT_MAX_BYTES,ot.kMaxLength,rr=ot.Buffer,Lo=ot.INSPECT_MAX_BYTES,No=ot.kMaxLength}),ue=He(()=>{Ue()}),je=pe((c,e)=>{le(),ue(),ce();var t=class extends Error{constructor(r){if(!Array.isArray(r))throw new TypeError(`Expected input to be an Array, got ${typeof r}`);let a="";for(let n=0;n<r.length;n++)a+=` ${r[n].stack}
2
+ `;super(a),this.name="AggregateError",this.errors=r}};e.exports={AggregateError:t,ArrayIsArray(r){return Array.isArray(r)},ArrayPrototypeIncludes(r,a){return r.includes(a)},ArrayPrototypeIndexOf(r,a){return r.indexOf(a)},ArrayPrototypeJoin(r,a){return r.join(a)},ArrayPrototypeMap(r,a){return r.map(a)},ArrayPrototypePop(r,a){return r.pop(a)},ArrayPrototypePush(r,a){return r.push(a)},ArrayPrototypeSlice(r,a,n){return r.slice(a,n)},Error,FunctionPrototypeCall(r,a,...n){return r.call(a,...n)},FunctionPrototypeSymbolHasInstance(r,a){return Function.prototype[Symbol.hasInstance].call(r,a)},MathFloor:Math.floor,Number,NumberIsInteger:Number.isInteger,NumberIsNaN:Number.isNaN,NumberMAX_SAFE_INTEGER:Number.MAX_SAFE_INTEGER,NumberMIN_SAFE_INTEGER:Number.MIN_SAFE_INTEGER,NumberParseInt:Number.parseInt,ObjectDefineProperties(r,a){return Object.defineProperties(r,a)},ObjectDefineProperty(r,a,n){return Object.defineProperty(r,a,n)},ObjectGetOwnPropertyDescriptor(r,a){return Object.getOwnPropertyDescriptor(r,a)},ObjectKeys(r){return Object.keys(r)},ObjectSetPrototypeOf(r,a){return Object.setPrototypeOf(r,a)},Promise,PromisePrototypeCatch(r,a){return r.catch(a)},PromisePrototypeThen(r,a,n){return r.then(a,n)},PromiseReject(r){return Promise.reject(r)},PromiseResolve(r){return Promise.resolve(r)},ReflectApply:Reflect.apply,RegExpPrototypeTest(r,a){return r.test(a)},SafeSet:Set,String,StringPrototypeSlice(r,a,n){return r.slice(a,n)},StringPrototypeToLowerCase(r){return r.toLowerCase()},StringPrototypeToUpperCase(r){return r.toUpperCase()},StringPrototypeTrim(r){return r.trim()},Symbol,SymbolFor:Symbol.for,SymbolAsyncIterator:Symbol.asyncIterator,SymbolHasInstance:Symbol.hasInstance,SymbolIterator:Symbol.iterator,SymbolDispose:Symbol.dispose||Symbol("Symbol.dispose"),SymbolAsyncDispose:Symbol.asyncDispose||Symbol("Symbol.asyncDispose"),TypedArrayPrototypeSet(r,a,n){return r.set(a,n)},Boolean,Uint8Array}}),Uo=pe((c,e)=>{le(),ue(),ce(),e.exports={format(t,...r){return t.replace(/%([sdifj])/g,function(...[a,n]){let i=r.shift();return n==="f"?i.toFixed(6):n==="j"?JSON.stringify(i):n==="s"&&typeof i=="object"?`${i.constructor!==Object?i.constructor.name:""} {}`.trim():i.toString()})},inspect(t){switch(typeof t){case"string":if(t.includes("'"))if(t.includes('"')){if(!t.includes("`")&&!t.includes("${"))return`\`${t}\``}else return`"${t}"`;return`'${t}'`;case"number":return isNaN(t)?"NaN":Object.is(t,-0)?String(t):t;case"bigint":return`${String(t)}n`;case"boolean":case"undefined":return String(t);case"object":return"{}"}}}}),We=pe((c,e)=>{le(),ue(),ce();var{format:t,inspect:r}=Uo(),{AggregateError:a}=je(),n=globalThis.AggregateError||a,i=Symbol("kIsNodeError"),s=["string","function","number","object","Function","Object","boolean","bigint","symbol"],o=/^([A-Z][a-z0-9]*)+$/,l="__node_internal_",u={};function d(g,_){if(!g)throw new u.ERR_INTERNAL_ASSERTION(_)}function p(g){let _="",S=g.length,v=g[0]==="-"?1:0;for(;S>=v+4;S-=3)_=`_${g.slice(S-3,S)}${_}`;return`${g.slice(0,S)}${_}`}function y(g,_,S){if(typeof _=="function")return d(_.length<=S.length,`Code: ${g}; The provided arguments length (${S.length}) does not match the required ones (${_.length}).`),_(...S);let v=(_.match(/%[dfijoOs]/g)||[]).length;return d(v===S.length,`Code: ${g}; The provided arguments length (${S.length}) does not match the required ones (${v}).`),S.length===0?_:t(_,...S)}function f(g,_,S){S||(S=Error);class v extends S{constructor(...E){super(y(g,_,E))}toString(){return`${this.name} [${g}]: ${this.message}`}}Object.defineProperties(v.prototype,{name:{value:S.name,writable:!0,enumerable:!1,configurable:!0},toString:{value(){return`${this.name} [${g}]: ${this.message}`},writable:!0,enumerable:!1,configurable:!0}}),v.prototype.code=g,v.prototype[i]=!0,u[g]=v}function m(g){let _=l+g.name;return Object.defineProperty(g,"name",{value:_}),g}function b(g,_){if(g&&_&&g!==_){if(Array.isArray(_.errors))return _.errors.push(g),_;let S=new n([_,g],_.message);return S.code=_.code,S}return g||_}var k=class extends Error{constructor(g="The operation was aborted",_=void 0){if(_!==void 0&&typeof _!="object")throw new u.ERR_INVALID_ARG_TYPE("options","Object",_);super(g,_),this.code="ABORT_ERR",this.name="AbortError"}};f("ERR_ASSERTION","%s",Error),f("ERR_INVALID_ARG_TYPE",(g,_,S)=>{d(typeof g=="string","'name' must be a string"),Array.isArray(_)||(_=[_]);let v="The ";g.endsWith(" argument")?v+=`${g} `:v+=`"${g}" ${g.includes(".")?"property":"argument"} `,v+="must be ";let x=[],E=[],I=[];for(let O of _)d(typeof O=="string","All expected entries have to be of type string"),s.includes(O)?x.push(O.toLowerCase()):o.test(O)?E.push(O):(d(O!=="object",'The value "object" should be written as "Object"'),I.push(O));if(E.length>0){let O=x.indexOf("object");O!==-1&&(x.splice(x,O,1),E.push("Object"))}if(x.length>0){switch(x.length){case 1:v+=`of type ${x[0]}`;break;case 2:v+=`one of type ${x[0]} or ${x[1]}`;break;default:{let O=x.pop();v+=`one of type ${x.join(", ")}, or ${O}`}}(E.length>0||I.length>0)&&(v+=" or ")}if(E.length>0){switch(E.length){case 1:v+=`an instance of ${E[0]}`;break;case 2:v+=`an instance of ${E[0]} or ${E[1]}`;break;default:{let O=E.pop();v+=`an instance of ${E.join(", ")}, or ${O}`}}I.length>0&&(v+=" or ")}switch(I.length){case 0:break;case 1:I[0].toLowerCase()!==I[0]&&(v+="an "),v+=`${I[0]}`;break;case 2:v+=`one of ${I[0]} or ${I[1]}`;break;default:{let O=I.pop();v+=`one of ${I.join(", ")}, or ${O}`}}if(S==null)v+=`. Received ${S}`;else if(typeof S=="function"&&S.name)v+=`. Received function ${S.name}`;else if(typeof S=="object"){var M;if((M=S.constructor)!==null&&M!==void 0&&M.name)v+=`. Received an instance of ${S.constructor.name}`;else{let O=r(S,{depth:-1});v+=`. Received ${O}`}}else{let O=r(S,{colors:!1});O.length>25&&(O=`${O.slice(0,25)}...`),v+=`. Received type ${typeof S} (${O})`}return v},TypeError),f("ERR_INVALID_ARG_VALUE",(g,_,S="is invalid")=>{let v=r(_);return v.length>128&&(v=v.slice(0,128)+"..."),`The ${g.includes(".")?"property":"argument"} '${g}' ${S}. Received ${v}`},TypeError),f("ERR_INVALID_RETURN_VALUE",(g,_,S)=>{var v;let x=S!=null&&(v=S.constructor)!==null&&v!==void 0&&v.name?`instance of ${S.constructor.name}`:`type ${typeof S}`;return`Expected ${g} to be returned from the "${_}" function but got ${x}.`},TypeError),f("ERR_MISSING_ARGS",(...g)=>{d(g.length>0,"At least one arg needs to be specified");let _,S=g.length;switch(g=(Array.isArray(g)?g:[g]).map(v=>`"${v}"`).join(" or "),S){case 1:_+=`The ${g[0]} argument`;break;case 2:_+=`The ${g[0]} and ${g[1]} arguments`;break;default:{let v=g.pop();_+=`The ${g.join(", ")}, and ${v} arguments`}break}return`${_} must be specified`},TypeError),f("ERR_OUT_OF_RANGE",(g,_,S)=>{d(_,'Missing "range" argument');let v;if(Number.isInteger(S)&&Math.abs(S)>2**32)v=p(String(S));else if(typeof S=="bigint"){v=String(S);let x=BigInt(2)**BigInt(32);(S>x||S<-x)&&(v=p(v)),v+="n"}else v=r(S);return`The value of "${g}" is out of range. It must be ${_}. Received ${v}`},RangeError),f("ERR_MULTIPLE_CALLBACK","Callback called multiple times",Error),f("ERR_METHOD_NOT_IMPLEMENTED","The %s method is not implemented",Error),f("ERR_STREAM_ALREADY_FINISHED","Cannot call %s after a stream was finished",Error),f("ERR_STREAM_CANNOT_PIPE","Cannot pipe, not readable",Error),f("ERR_STREAM_DESTROYED","Cannot call %s after a stream was destroyed",Error),f("ERR_STREAM_NULL_VALUES","May not write null values to stream",TypeError),f("ERR_STREAM_PREMATURE_CLOSE","Premature close",Error),f("ERR_STREAM_PUSH_AFTER_EOF","stream.push() after EOF",Error),f("ERR_STREAM_UNSHIFT_AFTER_END_EVENT","stream.unshift() after end event",Error),f("ERR_STREAM_WRITE_AFTER_END","write after end",Error),f("ERR_UNKNOWN_ENCODING","Unknown encoding: %s",TypeError),e.exports={AbortError:k,aggregateTwoErrors:m(b),hideStackFrames:m,codes:u}}),qt=pe((c,e)=>{le(),ue(),ce();var{AbortController:t,AbortSignal:r}=typeof self<"u"?self:typeof window<"u"?window:void 0;e.exports=t,e.exports.AbortSignal=r,e.exports.default=t}),pt={};Ct(pt,{EventEmitter:()=>Bo,default:()=>Pt,defaultMaxListeners:()=>Fo,init:()=>Do,listenerCount:()=>$o,on:()=>Wo,once:()=>qo});function hc(){if(ei)return Ht;ei=!0;var c=typeof Reflect=="object"?Reflect:null,e=c&&typeof c.apply=="function"?c.apply:function(S,v,x){return Function.prototype.apply.call(S,v,x)},t;c&&typeof c.ownKeys=="function"?t=c.ownKeys:Object.getOwnPropertySymbols?t=function(S){return Object.getOwnPropertyNames(S).concat(Object.getOwnPropertySymbols(S))}:t=function(S){return Object.getOwnPropertyNames(S)};function r(S){console&&console.warn&&console.warn(S)}var a=Number.isNaN||function(S){return S!==S};function n(){n.init.call(this)}Ht=n,Ht.once=k,n.EventEmitter=n,n.prototype._events=void 0,n.prototype._eventsCount=0,n.prototype._maxListeners=void 0;var i=10;function s(S){if(typeof S!="function")throw new TypeError('The "listener" argument must be of type Function. Received type '+typeof S)}Object.defineProperty(n,"defaultMaxListeners",{enumerable:!0,get:function(){return i},set:function(S){if(typeof S!="number"||S<0||a(S))throw new RangeError('The value of "defaultMaxListeners" is out of range. It must be a non-negative number. Received '+S+".");i=S}}),n.init=function(){(this._events===void 0||this._events===Object.getPrototypeOf(this)._events)&&(this._events=Object.create(null),this._eventsCount=0),this._maxListeners=this._maxListeners||void 0},n.prototype.setMaxListeners=function(S){if(typeof S!="number"||S<0||a(S))throw new RangeError('The value of "n" is out of range. It must be a non-negative number. Received '+S+".");return this._maxListeners=S,this};function o(S){return S._maxListeners===void 0?n.defaultMaxListeners:S._maxListeners}n.prototype.getMaxListeners=function(){return o(this)},n.prototype.emit=function(S){for(var v=[],x=1;x<arguments.length;x++)v.push(arguments[x]);var E=S==="error",I=this._events;if(I!==void 0)E=E&&I.error===void 0;else if(!E)return!1;if(E){var M;if(v.length>0&&(M=v[0]),M instanceof Error)throw M;var O=new Error("Unhandled error."+(M?" ("+M.message+")":""));throw O.context=M,O}var B=I[S];if(B===void 0)return!1;if(typeof B=="function")e(B,this,v);else for(var T=B.length,W=f(B,T),x=0;x<T;++x)e(W[x],this,v);return!0};function l(S,v,x,E){var I,M,O;if(s(x),M=S._events,M===void 0?(M=S._events=Object.create(null),S._eventsCount=0):(M.newListener!==void 0&&(S.emit("newListener",v,x.listener?x.listener:x),M=S._events),O=M[v]),O===void 0)O=M[v]=x,++S._eventsCount;else if(typeof O=="function"?O=M[v]=E?[x,O]:[O,x]:E?O.unshift(x):O.push(x),I=o(S),I>0&&O.length>I&&!O.warned){O.warned=!0;var B=new Error("Possible EventEmitter memory leak detected. "+O.length+" "+String(v)+" listeners added. Use emitter.setMaxListeners() to increase limit");B.name="MaxListenersExceededWarning",B.emitter=S,B.type=v,B.count=O.length,r(B)}return S}n.prototype.addListener=function(S,v){return l(this,S,v,!1)},n.prototype.on=n.prototype.addListener,n.prototype.prependListener=function(S,v){return l(this,S,v,!0)};function u(){if(!this.fired)return this.target.removeListener(this.type,this.wrapFn),this.fired=!0,arguments.length===0?this.listener.call(this.target):this.listener.apply(this.target,arguments)}function d(S,v,x){var E={fired:!1,wrapFn:void 0,target:S,type:v,listener:x},I=u.bind(E);return I.listener=x,E.wrapFn=I,I}n.prototype.once=function(S,v){return s(v),this.on(S,d(this,S,v)),this},n.prototype.prependOnceListener=function(S,v){return s(v),this.prependListener(S,d(this,S,v)),this},n.prototype.removeListener=function(S,v){var x,E,I,M,O;if(s(v),E=this._events,E===void 0)return this;if(x=E[S],x===void 0)return this;if(x===v||x.listener===v)--this._eventsCount===0?this._events=Object.create(null):(delete E[S],E.removeListener&&this.emit("removeListener",S,x.listener||v));else if(typeof x!="function"){for(I=-1,M=x.length-1;M>=0;M--)if(x[M]===v||x[M].listener===v){O=x[M].listener,I=M;break}if(I<0)return this;I===0?x.shift():m(x,I),x.length===1&&(E[S]=x[0]),E.removeListener!==void 0&&this.emit("removeListener",S,O||v)}return this},n.prototype.off=n.prototype.removeListener,n.prototype.removeAllListeners=function(S){var v,x,E;if(x=this._events,x===void 0)return this;if(x.removeListener===void 0)return arguments.length===0?(this._events=Object.create(null),this._eventsCount=0):x[S]!==void 0&&(--this._eventsCount===0?this._events=Object.create(null):delete x[S]),this;if(arguments.length===0){var I=Object.keys(x),M;for(E=0;E<I.length;++E)M=I[E],M!=="removeListener"&&this.removeAllListeners(M);return this.removeAllListeners("removeListener"),this._events=Object.create(null),this._eventsCount=0,this}if(v=x[S],typeof v=="function")this.removeListener(S,v);else if(v!==void 0)for(E=v.length-1;E>=0;E--)this.removeListener(S,v[E]);return this};function p(S,v,x){var E=S._events;if(E===void 0)return[];var I=E[v];return I===void 0?[]:typeof I=="function"?x?[I.listener||I]:[I]:x?b(I):f(I,I.length)}n.prototype.listeners=function(S){return p(this,S,!0)},n.prototype.rawListeners=function(S){return p(this,S,!1)},n.listenerCount=function(S,v){return typeof S.listenerCount=="function"?S.listenerCount(v):y.call(S,v)},n.prototype.listenerCount=y;function y(S){var v=this._events;if(v!==void 0){var x=v[S];if(typeof x=="function")return 1;if(x!==void 0)return x.length}return 0}n.prototype.eventNames=function(){return this._eventsCount>0?t(this._events):[]};function f(S,v){for(var x=new Array(v),E=0;E<v;++E)x[E]=S[E];return x}function m(S,v){for(;v+1<S.length;v++)S[v]=S[v+1];S.pop()}function b(S){for(var v=new Array(S.length),x=0;x<v.length;++x)v[x]=S[x].listener||S[x];return v}function k(S,v){return new Promise(function(x,E){function I(O){S.removeListener(v,M),E(O)}function M(){typeof S.removeListener=="function"&&S.removeListener("error",I),x([].slice.call(arguments))}_(S,v,M,{once:!0}),v!=="error"&&g(S,I,{once:!0})})}function g(S,v,x){typeof S.on=="function"&&_(S,"error",v,x)}function _(S,v,x,E){if(typeof S.on=="function")E.once?S.once(v,x):S.on(v,x);else if(typeof S.addEventListener=="function")S.addEventListener(v,function I(M){E.once&&S.removeEventListener(v,I),x(M)});else throw new TypeError('The "emitter" argument must be of type EventEmitter. Received type '+typeof S)}return Ht}var Ht,ei,Pt,Bo,Fo,Do,$o,Wo,qo,kt=He(()=>{le(),ue(),ce(),Ht={},ei=!1,Pt=hc(),Pt.once,Pt.once=function(c,e){return new Promise((t,r)=>{function a(...i){n!==void 0&&c.removeListener("error",n),t(i)}let n;e!=="error"&&(n=i=>{c.removeListener(name,a),r(i)},c.once("error",n)),c.once(e,a)})},Pt.on=function(c,e){let t=[],r=[],a=null,n=!1,i={async next(){let l=t.shift();if(l)return createIterResult(l,!1);if(a){let u=Promise.reject(a);return a=null,u}return n?createIterResult(void 0,!0):new Promise((u,d)=>r.push({resolve:u,reject:d}))},async return(){c.removeListener(e,s),c.removeListener("error",o),n=!0;for(let l of r)l.resolve(createIterResult(void 0,!0));return createIterResult(void 0,!0)},throw(l){a=l,c.removeListener(e,s),c.removeListener("error",o)},[Symbol.asyncIterator](){return this}};return c.on(e,s),c.on("error",o),i;function s(...l){let u=r.shift();u?u.resolve(createIterResult(l,!1)):t.push(l)}function o(l){n=!0;let u=r.shift();u?u.reject(l):a=l,i.return()}},{EventEmitter:Bo,defaultMaxListeners:Fo,init:Do,listenerCount:$o,on:Wo,once:qo}=Pt}),ze=pe((c,e)=>{le(),ue(),ce();var t=(Ue(),Pe(Ne)),{format:r,inspect:a}=Uo(),{codes:{ERR_INVALID_ARG_TYPE:n}}=We(),{kResistStopPropagation:i,AggregateError:s,SymbolDispose:o}=je(),l=globalThis.AbortSignal||qt().AbortSignal,u=globalThis.AbortController||qt().AbortController,d=Object.getPrototypeOf(async function(){}).constructor,p=globalThis.Blob||t.Blob,y=typeof p<"u"?function(b){return b instanceof p}:function(b){return!1},f=(b,k)=>{if(b!==void 0&&(b===null||typeof b!="object"||!("aborted"in b)))throw new n(k,"AbortSignal",b)},m=(b,k)=>{if(typeof b!="function")throw new n(k,"Function",b)};e.exports={AggregateError:s,kEmptyObject:Object.freeze({}),once(b){let k=!1;return function(...g){k||(k=!0,b.apply(this,g))}},createDeferredPromise:function(){let b,k;return{promise:new Promise((g,_)=>{b=g,k=_}),resolve:b,reject:k}},promisify(b){return new Promise((k,g)=>{b((_,...S)=>_?g(_):k(...S))})},debuglog(){return function(){}},format:r,inspect:a,types:{isAsyncFunction(b){return b instanceof d},isArrayBufferView(b){return ArrayBuffer.isView(b)}},isBlob:y,deprecate(b,k){return b},addAbortListener:(kt(),Pe(pt)).addAbortListener||function(b,k){if(b===void 0)throw new n("signal","AbortSignal",b);f(b,"signal"),m(k,"listener");let g;return b.aborted?queueMicrotask(()=>k()):(b.addEventListener("abort",k,{__proto__:null,once:!0,[i]:!0}),g=()=>{b.removeEventListener("abort",k)}),{__proto__:null,[o](){var _;(_=g)===null||_===void 0||_()}}},AbortSignalAny:l.any||function(b){if(b.length===1)return b[0];let k=new u,g=()=>k.abort();return b.forEach(_=>{f(_,"signals"),_.addEventListener("abort",g,{once:!0})}),k.signal.addEventListener("abort",()=>{b.forEach(_=>_.removeEventListener("abort",g))},{once:!0}),k.signal}},e.exports.promisify.custom=Symbol.for("nodejs.util.promisify.custom")}),zt=pe((c,e)=>{le(),ue(),ce();var{ArrayIsArray:t,ArrayPrototypeIncludes:r,ArrayPrototypeJoin:a,ArrayPrototypeMap:n,NumberIsInteger:i,NumberIsNaN:s,NumberMAX_SAFE_INTEGER:o,NumberMIN_SAFE_INTEGER:l,NumberParseInt:u,ObjectPrototypeHasOwnProperty:d,RegExpPrototypeExec:p,String:y,StringPrototypeToUpperCase:f,StringPrototypeTrim:m}=je(),{hideStackFrames:b,codes:{ERR_SOCKET_BAD_PORT:k,ERR_INVALID_ARG_TYPE:g,ERR_INVALID_ARG_VALUE:_,ERR_OUT_OF_RANGE:S,ERR_UNKNOWN_SIGNAL:v}}=We(),{normalizeEncoding:x}=ze(),{isAsyncFunction:E,isArrayBufferView:I}=ze().types,M={};function O(q){return q===(q|0)}function B(q){return q===q>>>0}var T=/^[0-7]+$/,W="must be a 32-bit unsigned integer or an octal string";function F(q,ge,ve){if(typeof q>"u"&&(q=ve),typeof q=="string"){if(p(T,q)===null)throw new _(ge,q,W);q=u(q,8)}return Y(q,ge),q}var N=b((q,ge,ve=l,se=o)=>{if(typeof q!="number")throw new g(ge,"number",q);if(!i(q))throw new S(ge,"an integer",q);if(q<ve||q>se)throw new S(ge,`>= ${ve} && <= ${se}`,q)}),ae=b((q,ge,ve=-2147483648,se=2147483647)=>{if(typeof q!="number")throw new g(ge,"number",q);if(!i(q))throw new S(ge,"an integer",q);if(q<ve||q>se)throw new S(ge,`>= ${ve} && <= ${se}`,q)}),Y=b((q,ge,ve=!1)=>{if(typeof q!="number")throw new g(ge,"number",q);if(!i(q))throw new S(ge,"an integer",q);let se=ve?1:0,Te=4294967295;if(q<se||q>Te)throw new S(ge,`>= ${se} && <= ${Te}`,q)});function K(q,ge){if(typeof q!="string")throw new g(ge,"string",q)}function re(q,ge,ve=void 0,se){if(typeof q!="number")throw new g(ge,"number",q);if(ve!=null&&q<ve||se!=null&&q>se||(ve!=null||se!=null)&&s(q))throw new S(ge,`${ve!=null?`>= ${ve}`:""}${ve!=null&&se!=null?" && ":""}${se!=null?`<= ${se}`:""}`,q)}var D=b((q,ge,ve)=>{if(!r(ve,q)){let se="must be one of: "+a(n(ve,Te=>typeof Te=="string"?`'${Te}'`:y(Te)),", ");throw new _(ge,q,se)}});function Z(q,ge){if(typeof q!="boolean")throw new g(ge,"boolean",q)}function P(q,ge,ve){return q==null||!d(q,ge)?ve:q[ge]}var J=b((q,ge,ve=null)=>{let se=P(ve,"allowArray",!1),Te=P(ve,"allowFunction",!1);if(!P(ve,"nullable",!1)&&q===null||!se&&t(q)||typeof q!="object"&&(!Te||typeof q!="function"))throw new g(ge,"Object",q)}),be=b((q,ge)=>{if(q!=null&&typeof q!="object"&&typeof q!="function")throw new g(ge,"a dictionary",q)}),te=b((q,ge,ve=0)=>{if(!t(q))throw new g(ge,"Array",q);if(q.length<ve){let se=`must be longer than ${ve}`;throw new _(ge,q,se)}});function we(q,ge){te(q,ge);for(let ve=0;ve<q.length;ve++)K(q[ve],`${ge}[${ve}]`)}function V(q,ge){te(q,ge);for(let ve=0;ve<q.length;ve++)Z(q[ve],`${ge}[${ve}]`)}function L(q,ge){te(q,ge);for(let ve=0;ve<q.length;ve++){let se=q[ve],Te=`${ge}[${ve}]`;if(se==null)throw new g(Te,"AbortSignal",se);me(se,Te)}}function ne(q,ge="signal"){if(K(q,ge),M[q]===void 0)throw M[f(q)]!==void 0?new v(q+" (signals must use all capital letters)"):new v(q)}var H=b((q,ge="buffer")=>{if(!I(q))throw new g(ge,["Buffer","TypedArray","DataView"],q)});function G(q,ge){let ve=x(ge),se=q.length;if(ve==="hex"&&se%2!==0)throw new _("encoding",ge,`is invalid for data of length ${se}`)}function Q(q,ge="Port",ve=!0){if(typeof q!="number"&&typeof q!="string"||typeof q=="string"&&m(q).length===0||+q!==+q>>>0||q>65535||q===0&&!ve)throw new k(ge,q,ve);return q|0}var me=b((q,ge)=>{if(q!==void 0&&(q===null||typeof q!="object"||!("aborted"in q)))throw new g(ge,"AbortSignal",q)}),oe=b((q,ge)=>{if(typeof q!="function")throw new g(ge,"Function",q)}),R=b((q,ge)=>{if(typeof q!="function"||E(q))throw new g(ge,"Function",q)}),$=b((q,ge)=>{if(q!==void 0)throw new g(ge,"undefined",q)});function ee(q,ge,ve){if(!r(ve,q))throw new g(ge,`('${a(ve,"|")}')`,q)}var fe=/^(?:<[^>]*>)(?:\s*;\s*[^;"\s]+(?:=(")?[^;"\s]*\1)?)*$/;function de(q,ge){if(typeof q>"u"||!p(fe,q))throw new _(ge,q,'must be an array or string of format "</styles.css>; rel=preload; as=style"')}function ye(q){if(typeof q=="string")return de(q,"hints"),q;if(t(q)){let ge=q.length,ve="";if(ge===0)return ve;for(let se=0;se<ge;se++){let Te=q[se];de(Te,"hints"),ve+=Te,se!==ge-1&&(ve+=", ")}return ve}throw new _("hints",q,'must be an array or string of format "</styles.css>; rel=preload; as=style"')}e.exports={isInt32:O,isUint32:B,parseFileMode:F,validateArray:te,validateStringArray:we,validateBooleanArray:V,validateAbortSignalArray:L,validateBoolean:Z,validateBuffer:H,validateDictionary:be,validateEncoding:G,validateFunction:oe,validateInt32:ae,validateInteger:N,validateNumber:re,validateObject:J,validateOneOf:D,validatePlainFunction:R,validatePort:Q,validateSignalName:ne,validateString:K,validateUint32:Y,validateUndefined:$,validateUnion:ee,validateAbortSignal:me,validateLinkHeaderValue:ye}}),St=pe((c,e)=>{le(),ue(),ce();var t=e.exports={},r,a;function n(){throw new Error("setTimeout has not been defined")}function i(){throw new Error("clearTimeout has not been defined")}(function(){try{typeof setTimeout=="function"?r=setTimeout:r=n}catch{r=n}try{typeof clearTimeout=="function"?a=clearTimeout:a=i}catch{a=i}})();function s(k){if(r===setTimeout)return setTimeout(k,0);if((r===n||!r)&&setTimeout)return r=setTimeout,setTimeout(k,0);try{return r(k,0)}catch{try{return r.call(null,k,0)}catch{return r.call(this,k,0)}}}function o(k){if(a===clearTimeout)return clearTimeout(k);if((a===i||!a)&&clearTimeout)return a=clearTimeout,clearTimeout(k);try{return a(k)}catch{try{return a.call(null,k)}catch{return a.call(this,k)}}}var l=[],u=!1,d,p=-1;function y(){!u||!d||(u=!1,d.length?l=d.concat(l):p=-1,l.length&&f())}function f(){if(!u){var k=s(y);u=!0;for(var g=l.length;g;){for(d=l,l=[];++p<g;)d&&d[p].run();p=-1,g=l.length}d=null,u=!1,o(k)}}t.nextTick=function(k){var g=new Array(arguments.length-1);if(arguments.length>1)for(var _=1;_<arguments.length;_++)g[_-1]=arguments[_];l.push(new m(k,g)),l.length===1&&!u&&s(f)};function m(k,g){this.fun=k,this.array=g}m.prototype.run=function(){this.fun.apply(null,this.array)},t.title="browser",t.browser=!0,t.env={},t.argv=[],t.version="",t.versions={};function b(){}t.on=b,t.addListener=b,t.once=b,t.off=b,t.removeListener=b,t.removeAllListeners=b,t.emit=b,t.prependListener=b,t.prependOnceListener=b,t.listeners=function(k){return[]},t.binding=function(k){throw new Error("process.binding is not supported")},t.cwd=function(){return"/"},t.chdir=function(k){throw new Error("process.chdir is not supported")},t.umask=function(){return 0}}),st=pe((c,e)=>{le(),ue(),ce();var{SymbolAsyncIterator:t,SymbolIterator:r,SymbolFor:a}=je(),n=a("nodejs.stream.destroyed"),i=a("nodejs.stream.errored"),s=a("nodejs.stream.readable"),o=a("nodejs.stream.writable"),l=a("nodejs.stream.disturbed"),u=a("nodejs.webstream.isClosedPromise"),d=a("nodejs.webstream.controllerErrorFunction");function p(P,J=!1){var be;return!!(P&&typeof P.pipe=="function"&&typeof P.on=="function"&&(!J||typeof P.pause=="function"&&typeof P.resume=="function")&&(!P._writableState||((be=P._readableState)===null||be===void 0?void 0:be.readable)!==!1)&&(!P._writableState||P._readableState))}function y(P){var J;return!!(P&&typeof P.write=="function"&&typeof P.on=="function"&&(!P._readableState||((J=P._writableState)===null||J===void 0?void 0:J.writable)!==!1))}function f(P){return!!(P&&typeof P.pipe=="function"&&P._readableState&&typeof P.on=="function"&&typeof P.write=="function")}function m(P){return P&&(P._readableState||P._writableState||typeof P.write=="function"&&typeof P.on=="function"||typeof P.pipe=="function"&&typeof P.on=="function")}function b(P){return!!(P&&!m(P)&&typeof P.pipeThrough=="function"&&typeof P.getReader=="function"&&typeof P.cancel=="function")}function k(P){return!!(P&&!m(P)&&typeof P.getWriter=="function"&&typeof P.abort=="function")}function g(P){return!!(P&&!m(P)&&typeof P.readable=="object"&&typeof P.writable=="object")}function _(P){return b(P)||k(P)||g(P)}function S(P,J){return P==null?!1:J===!0?typeof P[t]=="function":J===!1?typeof P[r]=="function":typeof P[t]=="function"||typeof P[r]=="function"}function v(P){if(!m(P))return null;let J=P._writableState,be=P._readableState,te=J||be;return!!(P.destroyed||P[n]||te!=null&&te.destroyed)}function x(P){if(!y(P))return null;if(P.writableEnded===!0)return!0;let J=P._writableState;return J!=null&&J.errored?!1:typeof J?.ended!="boolean"?null:J.ended}function E(P,J){if(!y(P))return null;if(P.writableFinished===!0)return!0;let be=P._writableState;return be!=null&&be.errored?!1:typeof be?.finished!="boolean"?null:!!(be.finished||J===!1&&be.ended===!0&&be.length===0)}function I(P){if(!p(P))return null;if(P.readableEnded===!0)return!0;let J=P._readableState;return!J||J.errored?!1:typeof J?.ended!="boolean"?null:J.ended}function M(P,J){if(!p(P))return null;let be=P._readableState;return be!=null&&be.errored?!1:typeof be?.endEmitted!="boolean"?null:!!(be.endEmitted||J===!1&&be.ended===!0&&be.length===0)}function O(P){return P&&P[s]!=null?P[s]:typeof P?.readable!="boolean"?null:v(P)?!1:p(P)&&P.readable&&!M(P)}function B(P){return P&&P[o]!=null?P[o]:typeof P?.writable!="boolean"?null:v(P)?!1:y(P)&&P.writable&&!x(P)}function T(P,J){return m(P)?v(P)?!0:!(J?.readable!==!1&&O(P)||J?.writable!==!1&&B(P)):null}function W(P){var J,be;return m(P)?P.writableErrored?P.writableErrored:(J=(be=P._writableState)===null||be===void 0?void 0:be.errored)!==null&&J!==void 0?J:null:null}function F(P){var J,be;return m(P)?P.readableErrored?P.readableErrored:(J=(be=P._readableState)===null||be===void 0?void 0:be.errored)!==null&&J!==void 0?J:null:null}function N(P){if(!m(P))return null;if(typeof P.closed=="boolean")return P.closed;let J=P._writableState,be=P._readableState;return typeof J?.closed=="boolean"||typeof be?.closed=="boolean"?J?.closed||be?.closed:typeof P._closed=="boolean"&&ae(P)?P._closed:null}function ae(P){return typeof P._closed=="boolean"&&typeof P._defaultKeepAlive=="boolean"&&typeof P._removedConnection=="boolean"&&typeof P._removedContLen=="boolean"}function Y(P){return typeof P._sent100=="boolean"&&ae(P)}function K(P){var J;return typeof P._consuming=="boolean"&&typeof P._dumped=="boolean"&&((J=P.req)===null||J===void 0?void 0:J.upgradeOrConnect)===void 0}function re(P){if(!m(P))return null;let J=P._writableState,be=P._readableState,te=J||be;return!te&&Y(P)||!!(te&&te.autoDestroy&&te.emitClose&&te.closed===!1)}function D(P){var J;return!!(P&&((J=P[l])!==null&&J!==void 0?J:P.readableDidRead||P.readableAborted))}function Z(P){var J,be,te,we,V,L,ne,H,G,Q;return!!(P&&((J=(be=(te=(we=(V=(L=P[i])!==null&&L!==void 0?L:P.readableErrored)!==null&&V!==void 0?V:P.writableErrored)!==null&&we!==void 0?we:(ne=P._readableState)===null||ne===void 0?void 0:ne.errorEmitted)!==null&&te!==void 0?te:(H=P._writableState)===null||H===void 0?void 0:H.errorEmitted)!==null&&be!==void 0?be:(G=P._readableState)===null||G===void 0?void 0:G.errored)!==null&&J!==void 0?J:!((Q=P._writableState)===null||Q===void 0)&&Q.errored))}e.exports={isDestroyed:v,kIsDestroyed:n,isDisturbed:D,kIsDisturbed:l,isErrored:Z,kIsErrored:i,isReadable:O,kIsReadable:s,kIsClosedPromise:u,kControllerErrorFunction:d,kIsWritable:o,isClosed:N,isDuplexNodeStream:f,isFinished:T,isIterable:S,isReadableNodeStream:p,isReadableStream:b,isReadableEnded:I,isReadableFinished:M,isReadableErrored:F,isNodeStream:m,isWebStream:_,isWritable:B,isWritableNodeStream:y,isWritableStream:k,isWritableEnded:x,isWritableFinished:E,isWritableErrored:W,isServerRequest:K,isServerResponse:Y,willEmitClose:re,isTransformStream:g}}),gt=pe((c,e)=>{le(),ue(),ce();var t=St(),{AbortError:r,codes:a}=We(),{ERR_INVALID_ARG_TYPE:n,ERR_STREAM_PREMATURE_CLOSE:i}=a,{kEmptyObject:s,once:o}=ze(),{validateAbortSignal:l,validateFunction:u,validateObject:d,validateBoolean:p}=zt(),{Promise:y,PromisePrototypeThen:f,SymbolDispose:m}=je(),{isClosed:b,isReadable:k,isReadableNodeStream:g,isReadableStream:_,isReadableFinished:S,isReadableErrored:v,isWritable:x,isWritableNodeStream:E,isWritableStream:I,isWritableFinished:M,isWritableErrored:O,isNodeStream:B,willEmitClose:T,kIsClosedPromise:W}=st(),F;function N(D){return D.setHeader&&typeof D.abort=="function"}var ae=()=>{};function Y(D,Z,P){var J,be;if(arguments.length===2?(P=Z,Z=s):Z==null?Z=s:d(Z,"options"),u(P,"callback"),l(Z.signal,"options.signal"),P=o(P),_(D)||I(D))return K(D,Z,P);if(!B(D))throw new n("stream",["ReadableStream","WritableStream","Stream"],D);let te=(J=Z.readable)!==null&&J!==void 0?J:g(D),we=(be=Z.writable)!==null&&be!==void 0?be:E(D),V=D._writableState,L=D._readableState,ne=()=>{D.writable||Q()},H=T(D)&&g(D)===te&&E(D)===we,G=M(D,!1),Q=()=>{G=!0,D.destroyed&&(H=!1),!(H&&(!D.readable||te))&&(!te||me)&&P.call(D)},me=S(D,!1),oe=()=>{me=!0,D.destroyed&&(H=!1),!(H&&(!D.writable||we))&&(!we||G)&&P.call(D)},R=q=>{P.call(D,q)},$=b(D),ee=()=>{$=!0;let q=O(D)||v(D);if(q&&typeof q!="boolean")return P.call(D,q);if(te&&!me&&g(D,!0)&&!S(D,!1))return P.call(D,new i);if(we&&!G&&!M(D,!1))return P.call(D,new i);P.call(D)},fe=()=>{$=!0;let q=O(D)||v(D);if(q&&typeof q!="boolean")return P.call(D,q);P.call(D)},de=()=>{D.req.on("finish",Q)};N(D)?(D.on("complete",Q),H||D.on("abort",ee),D.req?de():D.on("request",de)):we&&!V&&(D.on("end",ne),D.on("close",ne)),!H&&typeof D.aborted=="boolean"&&D.on("aborted",ee),D.on("end",oe),D.on("finish",Q),Z.error!==!1&&D.on("error",R),D.on("close",ee),$?t.nextTick(ee):V!=null&&V.errorEmitted||L!=null&&L.errorEmitted?H||t.nextTick(fe):(!te&&(!H||k(D))&&(G||x(D)===!1)||!we&&(!H||x(D))&&(me||k(D)===!1)||L&&D.req&&D.aborted)&&t.nextTick(fe);let ye=()=>{P=ae,D.removeListener("aborted",ee),D.removeListener("complete",Q),D.removeListener("abort",ee),D.removeListener("request",de),D.req&&D.req.removeListener("finish",Q),D.removeListener("end",ne),D.removeListener("close",ne),D.removeListener("finish",Q),D.removeListener("end",oe),D.removeListener("error",R),D.removeListener("close",ee)};if(Z.signal&&!$){let q=()=>{let ge=P;ye(),ge.call(D,new r(void 0,{cause:Z.signal.reason}))};if(Z.signal.aborted)t.nextTick(q);else{F=F||ze().addAbortListener;let ge=F(Z.signal,q),ve=P;P=o((...se)=>{ge[m](),ve.apply(D,se)})}}return ye}function K(D,Z,P){let J=!1,be=ae;if(Z.signal)if(be=()=>{J=!0,P.call(D,new r(void 0,{cause:Z.signal.reason}))},Z.signal.aborted)t.nextTick(be);else{F=F||ze().addAbortListener;let we=F(Z.signal,be),V=P;P=o((...L)=>{we[m](),V.apply(D,L)})}let te=(...we)=>{J||t.nextTick(()=>P.apply(D,we))};return f(D[W].promise,te,te),ae}function re(D,Z){var P;let J=!1;return Z===null&&(Z=s),(P=Z)!==null&&P!==void 0&&P.cleanup&&(p(Z.cleanup,"cleanup"),J=Z.cleanup),new y((be,te)=>{let we=Y(D,Z,V=>{J&&we(),V?te(V):be()})})}e.exports=Y,e.exports.finished=re}),Mt=pe((c,e)=>{le(),ue(),ce();var t=St(),{aggregateTwoErrors:r,codes:{ERR_MULTIPLE_CALLBACK:a},AbortError:n}=We(),{Symbol:i}=je(),{kIsDestroyed:s,isDestroyed:o,isFinished:l,isServerRequest:u}=st(),d=i("kDestroy"),p=i("kConstruct");function y(T,W,F){T&&(T.stack,W&&!W.errored&&(W.errored=T),F&&!F.errored&&(F.errored=T))}function f(T,W){let F=this._readableState,N=this._writableState,ae=N||F;return N!=null&&N.destroyed||F!=null&&F.destroyed?(typeof W=="function"&&W(),this):(y(T,N,F),N&&(N.destroyed=!0),F&&(F.destroyed=!0),ae.constructed?m(this,T,W):this.once(d,function(Y){m(this,r(Y,T),W)}),this)}function m(T,W,F){let N=!1;function ae(Y){if(N)return;N=!0;let K=T._readableState,re=T._writableState;y(Y,re,K),re&&(re.closed=!0),K&&(K.closed=!0),typeof F=="function"&&F(Y),Y?t.nextTick(b,T,Y):t.nextTick(k,T)}try{T._destroy(W||null,ae)}catch(Y){ae(Y)}}function b(T,W){g(T,W),k(T)}function k(T){let W=T._readableState,F=T._writableState;F&&(F.closeEmitted=!0),W&&(W.closeEmitted=!0),(F!=null&&F.emitClose||W!=null&&W.emitClose)&&T.emit("close")}function g(T,W){let F=T._readableState,N=T._writableState;N!=null&&N.errorEmitted||F!=null&&F.errorEmitted||(N&&(N.errorEmitted=!0),F&&(F.errorEmitted=!0),T.emit("error",W))}function _(){let T=this._readableState,W=this._writableState;T&&(T.constructed=!0,T.closed=!1,T.closeEmitted=!1,T.destroyed=!1,T.errored=null,T.errorEmitted=!1,T.reading=!1,T.ended=T.readable===!1,T.endEmitted=T.readable===!1),W&&(W.constructed=!0,W.destroyed=!1,W.closed=!1,W.closeEmitted=!1,W.errored=null,W.errorEmitted=!1,W.finalCalled=!1,W.prefinished=!1,W.ended=W.writable===!1,W.ending=W.writable===!1,W.finished=W.writable===!1)}function S(T,W,F){let N=T._readableState,ae=T._writableState;if(ae!=null&&ae.destroyed||N!=null&&N.destroyed)return this;N!=null&&N.autoDestroy||ae!=null&&ae.autoDestroy?T.destroy(W):W&&(W.stack,ae&&!ae.errored&&(ae.errored=W),N&&!N.errored&&(N.errored=W),F?t.nextTick(g,T,W):g(T,W))}function v(T,W){if(typeof T._construct!="function")return;let F=T._readableState,N=T._writableState;F&&(F.constructed=!1),N&&(N.constructed=!1),T.once(p,W),!(T.listenerCount(p)>1)&&t.nextTick(x,T)}function x(T){let W=!1;function F(N){if(W){S(T,N??new a);return}W=!0;let ae=T._readableState,Y=T._writableState,K=Y||ae;ae&&(ae.constructed=!0),Y&&(Y.constructed=!0),K.destroyed?T.emit(d,N):N?S(T,N,!0):t.nextTick(E,T)}try{T._construct(N=>{t.nextTick(F,N)})}catch(N){t.nextTick(F,N)}}function E(T){T.emit(p)}function I(T){return T?.setHeader&&typeof T.abort=="function"}function M(T){T.emit("close")}function O(T,W){T.emit("error",W),t.nextTick(M,T)}function B(T,W){!T||o(T)||(!W&&!l(T)&&(W=new n),u(T)?(T.socket=null,T.destroy(W)):I(T)?T.abort():I(T.req)?T.req.abort():typeof T.destroy=="function"?T.destroy(W):typeof T.close=="function"?T.close():W?t.nextTick(O,T,W):t.nextTick(M,T),T.destroyed||(T[s]=!0))}e.exports={construct:v,destroyer:B,destroy:f,undestroy:_,errorOrDestroy:S}}),ti=pe((c,e)=>{le(),ue(),ce();var{ArrayIsArray:t,ObjectSetPrototypeOf:r}=je(),{EventEmitter:a}=(kt(),Pe(pt));function n(s){a.call(this,s)}r(n.prototype,a.prototype),r(n,a),n.prototype.pipe=function(s,o){let l=this;function u(k){s.writable&&s.write(k)===!1&&l.pause&&l.pause()}l.on("data",u);function d(){l.readable&&l.resume&&l.resume()}s.on("drain",d),!s._isStdio&&(!o||o.end!==!1)&&(l.on("end",y),l.on("close",f));let p=!1;function y(){p||(p=!0,s.end())}function f(){p||(p=!0,typeof s.destroy=="function"&&s.destroy())}function m(k){b(),a.listenerCount(this,"error")===0&&this.emit("error",k)}i(l,"error",m),i(s,"error",m);function b(){l.removeListener("data",u),s.removeListener("drain",d),l.removeListener("end",y),l.removeListener("close",f),l.removeListener("error",m),s.removeListener("error",m),l.removeListener("end",b),l.removeListener("close",b),s.removeListener("close",b)}return l.on("end",b),l.on("close",b),s.on("close",b),s.emit("pipe",l),s};function i(s,o,l){if(typeof s.prependListener=="function")return s.prependListener(o,l);!s._events||!s._events[o]?s.on(o,l):t(s._events[o])?s._events[o].unshift(l):s._events[o]=[l,s._events[o]]}e.exports={Stream:n,prependListener:i}}),nr=pe((c,e)=>{le(),ue(),ce();var{SymbolDispose:t}=je(),{AbortError:r,codes:a}=We(),{isNodeStream:n,isWebStream:i,kControllerErrorFunction:s}=st(),o=gt(),{ERR_INVALID_ARG_TYPE:l}=a,u,d=(p,y)=>{if(typeof p!="object"||!("aborted"in p))throw new l(y,"AbortSignal",p)};e.exports.addAbortSignal=function(p,y){if(d(p,"signal"),!n(y)&&!i(y))throw new l("stream",["ReadableStream","WritableStream","Stream"],y);return e.exports.addAbortSignalNoValidate(p,y)},e.exports.addAbortSignalNoValidate=function(p,y){if(typeof p!="object"||!("aborted"in p))return y;let f=n(y)?()=>{y.destroy(new r(void 0,{cause:p.reason}))}:()=>{y[s](new r(void 0,{cause:p.reason}))};if(p.aborted)f();else{u=u||ze().addAbortListener;let m=u(p,f);o(y,m[t])}return y}}),fc=pe((c,e)=>{le(),ue(),ce();var{StringPrototypeSlice:t,SymbolIterator:r,TypedArrayPrototypeSet:a,Uint8Array:n}=je(),{Buffer:i}=(Ue(),Pe(Ne)),{inspect:s}=ze();e.exports=class{constructor(){this.head=null,this.tail=null,this.length=0}push(o){let l={data:o,next:null};this.length>0?this.tail.next=l:this.head=l,this.tail=l,++this.length}unshift(o){let l={data:o,next:this.head};this.length===0&&(this.tail=l),this.head=l,++this.length}shift(){if(this.length===0)return;let o=this.head.data;return this.length===1?this.head=this.tail=null:this.head=this.head.next,--this.length,o}clear(){this.head=this.tail=null,this.length=0}join(o){if(this.length===0)return"";let l=this.head,u=""+l.data;for(;(l=l.next)!==null;)u+=o+l.data;return u}concat(o){if(this.length===0)return i.alloc(0);let l=i.allocUnsafe(o>>>0),u=this.head,d=0;for(;u;)a(l,u.data,d),d+=u.data.length,u=u.next;return l}consume(o,l){let u=this.head.data;if(o<u.length){let d=u.slice(0,o);return this.head.data=u.slice(o),d}return o===u.length?this.shift():l?this._getString(o):this._getBuffer(o)}first(){return this.head.data}*[r](){for(let o=this.head;o;o=o.next)yield o.data}_getString(o){let l="",u=this.head,d=0;do{let p=u.data;if(o>p.length)l+=p,o-=p.length;else{o===p.length?(l+=p,++d,u.next?this.head=u.next:this.head=this.tail=null):(l+=t(p,0,o),this.head=u,u.data=t(p,o));break}++d}while((u=u.next)!==null);return this.length-=d,l}_getBuffer(o){let l=i.allocUnsafe(o),u=o,d=this.head,p=0;do{let y=d.data;if(o>y.length)a(l,y,u-o),o-=y.length;else{o===y.length?(a(l,y,u-o),++p,d.next?this.head=d.next:this.head=this.tail=null):(a(l,new n(y.buffer,y.byteOffset,o),u-o),this.head=d,d.data=y.slice(o));break}++p}while((d=d.next)!==null);return this.length-=p,l}[Symbol.for("nodejs.util.inspect.custom")](o,l){return s(this,{...l,depth:0,customInspect:!1})}}}),ir=pe((c,e)=>{le(),ue(),ce();var{MathFloor:t,NumberIsInteger:r}=je(),{validateInteger:a}=zt(),{ERR_INVALID_ARG_VALUE:n}=We().codes,i=16*1024,s=16;function o(p,y,f){return p.highWaterMark!=null?p.highWaterMark:y?p[f]:null}function l(p){return p?s:i}function u(p,y){a(y,"value",0),p?s=y:i=y}function d(p,y,f,m){let b=o(y,m,f);if(b!=null){if(!r(b)||b<0){let k=m?`options.${f}`:"options.highWaterMark";throw new n(k,b)}return t(b)}return l(p.objectMode)}e.exports={getHighWaterMark:d,getDefaultHighWaterMark:l,setDefaultHighWaterMark:u}}),dc=pe((c,e)=>{le(),ue(),ce();var t=(Ue(),Pe(Ne)),r=t.Buffer;function a(i,s){for(var o in i)s[o]=i[o]}r.from&&r.alloc&&r.allocUnsafe&&r.allocUnsafeSlow?e.exports=t:(a(t,c),c.Buffer=n);function n(i,s,o){return r(i,s,o)}n.prototype=Object.create(r.prototype),a(r,n),n.from=function(i,s,o){if(typeof i=="number")throw new TypeError("Argument must not be a number");return r(i,s,o)},n.alloc=function(i,s,o){if(typeof i!="number")throw new TypeError("Argument must be a number");var l=r(i);return s!==void 0?typeof o=="string"?l.fill(s,o):l.fill(s):l.fill(0),l},n.allocUnsafe=function(i){if(typeof i!="number")throw new TypeError("Argument must be a number");return r(i)},n.allocUnsafeSlow=function(i){if(typeof i!="number")throw new TypeError("Argument must be a number");return t.SlowBuffer(i)}}),pc=pe(c=>{le(),ue(),ce();var e=dc().Buffer,t=e.isEncoding||function(g){switch(g=""+g,g&&g.toLowerCase()){case"hex":case"utf8":case"utf-8":case"ascii":case"binary":case"base64":case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":case"raw":return!0;default:return!1}};function r(g){if(!g)return"utf8";for(var _;;)switch(g){case"utf8":case"utf-8":return"utf8";case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return"utf16le";case"latin1":case"binary":return"latin1";case"base64":case"ascii":case"hex":return g;default:if(_)return;g=(""+g).toLowerCase(),_=!0}}function a(g){var _=r(g);if(typeof _!="string"&&(e.isEncoding===t||!t(g)))throw new Error("Unknown encoding: "+g);return _||g}c.StringDecoder=n;function n(g){this.encoding=a(g);var _;switch(this.encoding){case"utf16le":this.text=p,this.end=y,_=4;break;case"utf8":this.fillLast=l,_=4;break;case"base64":this.text=f,this.end=m,_=3;break;default:this.write=b,this.end=k;return}this.lastNeed=0,this.lastTotal=0,this.lastChar=e.allocUnsafe(_)}n.prototype.write=function(g){if(g.length===0)return"";var _,S;if(this.lastNeed){if(_=this.fillLast(g),_===void 0)return"";S=this.lastNeed,this.lastNeed=0}else S=0;return S<g.length?_?_+this.text(g,S):this.text(g,S):_||""},n.prototype.end=d,n.prototype.text=u,n.prototype.fillLast=function(g){if(this.lastNeed<=g.length)return g.copy(this.lastChar,this.lastTotal-this.lastNeed,0,this.lastNeed),this.lastChar.toString(this.encoding,0,this.lastTotal);g.copy(this.lastChar,this.lastTotal-this.lastNeed,0,g.length),this.lastNeed-=g.length};function i(g){return g<=127?0:g>>5===6?2:g>>4===14?3:g>>3===30?4:g>>6===2?-1:-2}function s(g,_,S){var v=_.length-1;if(v<S)return 0;var x=i(_[v]);return x>=0?(x>0&&(g.lastNeed=x-1),x):--v<S||x===-2?0:(x=i(_[v]),x>=0?(x>0&&(g.lastNeed=x-2),x):--v<S||x===-2?0:(x=i(_[v]),x>=0?(x>0&&(x===2?x=0:g.lastNeed=x-3),x):0))}function o(g,_,S){if((_[0]&192)!==128)return g.lastNeed=0,"�";if(g.lastNeed>1&&_.length>1){if((_[1]&192)!==128)return g.lastNeed=1,"�";if(g.lastNeed>2&&_.length>2&&(_[2]&192)!==128)return g.lastNeed=2,"�"}}function l(g){var _=this.lastTotal-this.lastNeed,S=o(this,g);if(S!==void 0)return S;if(this.lastNeed<=g.length)return g.copy(this.lastChar,_,0,this.lastNeed),this.lastChar.toString(this.encoding,0,this.lastTotal);g.copy(this.lastChar,_,0,g.length),this.lastNeed-=g.length}function u(g,_){var S=s(this,g,_);if(!this.lastNeed)return g.toString("utf8",_);this.lastTotal=S;var v=g.length-(S-this.lastNeed);return g.copy(this.lastChar,0,v),g.toString("utf8",_,v)}function d(g){var _=g&&g.length?this.write(g):"";return this.lastNeed?_+"�":_}function p(g,_){if((g.length-_)%2===0){var S=g.toString("utf16le",_);if(S){var v=S.charCodeAt(S.length-1);if(v>=55296&&v<=56319)return this.lastNeed=2,this.lastTotal=4,this.lastChar[0]=g[g.length-2],this.lastChar[1]=g[g.length-1],S.slice(0,-1)}return S}return this.lastNeed=1,this.lastTotal=2,this.lastChar[0]=g[g.length-1],g.toString("utf16le",_,g.length-1)}function y(g){var _=g&&g.length?this.write(g):"";if(this.lastNeed){var S=this.lastTotal-this.lastNeed;return _+this.lastChar.toString("utf16le",0,S)}return _}function f(g,_){var S=(g.length-_)%3;return S===0?g.toString("base64",_):(this.lastNeed=3-S,this.lastTotal=3,S===1?this.lastChar[0]=g[g.length-1]:(this.lastChar[0]=g[g.length-2],this.lastChar[1]=g[g.length-1]),g.toString("base64",_,g.length-S))}function m(g){var _=g&&g.length?this.write(g):"";return this.lastNeed?_+this.lastChar.toString("base64",0,3-this.lastNeed):_}function b(g){return g.toString(this.encoding)}function k(g){return g&&g.length?this.write(g):""}}),Ho=pe((c,e)=>{le(),ue(),ce();var t=St(),{PromisePrototypeThen:r,SymbolAsyncIterator:a,SymbolIterator:n}=je(),{Buffer:i}=(Ue(),Pe(Ne)),{ERR_INVALID_ARG_TYPE:s,ERR_STREAM_NULL_VALUES:o}=We().codes;function l(u,d,p){let y;if(typeof d=="string"||d instanceof i)return new u({objectMode:!0,...p,read(){this.push(d),this.push(null)}});let f;if(d&&d[a])f=!0,y=d[a]();else if(d&&d[n])f=!1,y=d[n]();else throw new s("iterable",["Iterable"],d);let m=new u({objectMode:!0,highWaterMark:1,...p}),b=!1;m._read=function(){b||(b=!0,g())},m._destroy=function(_,S){r(k(_),()=>t.nextTick(S,_),v=>t.nextTick(S,v||_))};async function k(_){let S=_!=null,v=typeof y.throw=="function";if(S&&v){let{value:x,done:E}=await y.throw(_);if(await x,E)return}if(typeof y.return=="function"){let{value:x}=await y.return();await x}}async function g(){for(;;){try{let{value:_,done:S}=f?await y.next():y.next();if(S)m.push(null);else{let v=_&&typeof _.then=="function"?await _:_;if(v===null)throw b=!1,new o;if(m.push(v))continue;b=!1}}catch(_){m.destroy(_)}break}}return m}e.exports=l}),or=pe((c,e)=>{le(),ue(),ce();var t=St(),{ArrayPrototypeIndexOf:r,NumberIsInteger:a,NumberIsNaN:n,NumberParseInt:i,ObjectDefineProperties:s,ObjectKeys:o,ObjectSetPrototypeOf:l,Promise:u,SafeSet:d,SymbolAsyncDispose:p,SymbolAsyncIterator:y,Symbol:f}=je();e.exports=se,se.ReadableState=ve;var{EventEmitter:m}=(kt(),Pe(pt)),{Stream:b,prependListener:k}=ti(),{Buffer:g}=(Ue(),Pe(Ne)),{addAbortSignal:_}=nr(),S=gt(),v=ze().debuglog("stream",C=>{v=C}),x=fc(),E=Mt(),{getHighWaterMark:I,getDefaultHighWaterMark:M}=ir(),{aggregateTwoErrors:O,codes:{ERR_INVALID_ARG_TYPE:B,ERR_METHOD_NOT_IMPLEMENTED:T,ERR_OUT_OF_RANGE:W,ERR_STREAM_PUSH_AFTER_EOF:F,ERR_STREAM_UNSHIFT_AFTER_END_EVENT:N},AbortError:ae}=We(),{validateObject:Y}=zt(),K=f("kPaused"),{StringDecoder:re}=pc(),D=Ho();l(se.prototype,b.prototype),l(se,b);var Z=()=>{},{errorOrDestroy:P}=E,J=1,be=2,te=4,we=8,V=16,L=32,ne=64,H=128,G=256,Q=512,me=1024,oe=2048,R=4096,$=8192,ee=16384,fe=32768,de=65536,ye=1<<17,q=1<<18;function ge(C){return{enumerable:!1,get(){return(this.state&C)!==0},set(j){j?this.state|=C:this.state&=~C}}}s(ve.prototype,{objectMode:ge(J),ended:ge(be),endEmitted:ge(te),reading:ge(we),constructed:ge(V),sync:ge(L),needReadable:ge(ne),emittedReadable:ge(H),readableListening:ge(G),resumeScheduled:ge(Q),errorEmitted:ge(me),emitClose:ge(oe),autoDestroy:ge(R),destroyed:ge($),closed:ge(ee),closeEmitted:ge(fe),multiAwaitDrain:ge(de),readingMore:ge(ye),dataEmitted:ge(q)});function ve(C,j,_e){typeof _e!="boolean"&&(_e=j instanceof at()),this.state=oe|R|V|L,C&&C.objectMode&&(this.state|=J),_e&&C&&C.readableObjectMode&&(this.state|=J),this.highWaterMark=C?I(this,C,"readableHighWaterMark",_e):M(!1),this.buffer=new x,this.length=0,this.pipes=[],this.flowing=null,this[K]=null,C&&C.emitClose===!1&&(this.state&=~oe),C&&C.autoDestroy===!1&&(this.state&=~R),this.errored=null,this.defaultEncoding=C&&C.defaultEncoding||"utf8",this.awaitDrainWriters=null,this.decoder=null,this.encoding=null,C&&C.encoding&&(this.decoder=new re(C.encoding),this.encoding=C.encoding)}function se(C){if(!(this instanceof se))return new se(C);let j=this instanceof at();this._readableState=new ve(C,this,j),C&&(typeof C.read=="function"&&(this._read=C.read),typeof C.destroy=="function"&&(this._destroy=C.destroy),typeof C.construct=="function"&&(this._construct=C.construct),C.signal&&!j&&_(C.signal,this)),b.call(this,C),E.construct(this,()=>{this._readableState.needReadable&&z(this,this._readableState)})}se.prototype.destroy=E.destroy,se.prototype._undestroy=E.undestroy,se.prototype._destroy=function(C,j){j(C)},se.prototype[m.captureRejectionSymbol]=function(C){this.destroy(C)},se.prototype[p]=function(){let C;return this.destroyed||(C=this.readableEnded?null:new ae,this.destroy(C)),new u((j,_e)=>S(this,Se=>Se&&Se!==C?_e(Se):j(null)))},se.prototype.push=function(C,j){return Te(this,C,j,!1)},se.prototype.unshift=function(C,j){return Te(this,C,j,!0)};function Te(C,j,_e,Se){v("readableAddChunk",j);let Ee=C._readableState,Le;if((Ee.state&J)===0&&(typeof j=="string"?(_e=_e||Ee.defaultEncoding,Ee.encoding!==_e&&(Se&&Ee.encoding?j=g.from(j,_e).toString(Ee.encoding):(j=g.from(j,_e),_e=""))):j instanceof g?_e="":b._isUint8Array(j)?(j=b._uint8ArrayToBuffer(j),_e=""):j!=null&&(Le=new B("chunk",["string","Buffer","Uint8Array"],j))),Le)P(C,Le);else if(j===null)Ee.state&=~we,X(C,Ee);else if((Ee.state&J)!==0||j&&j.length>0)if(Se)if((Ee.state&te)!==0)P(C,new N);else{if(Ee.destroyed||Ee.errored)return!1;h(C,Ee,j,!0)}else if(Ee.ended)P(C,new F);else{if(Ee.destroyed||Ee.errored)return!1;Ee.state&=~we,Ee.decoder&&!_e?(j=Ee.decoder.write(j),Ee.objectMode||j.length!==0?h(C,Ee,j,!1):z(C,Ee)):h(C,Ee,j,!1)}else Se||(Ee.state&=~we,z(C,Ee));return!Ee.ended&&(Ee.length<Ee.highWaterMark||Ee.length===0)}function h(C,j,_e,Se){j.flowing&&j.length===0&&!j.sync&&C.listenerCount("data")>0?((j.state&de)!==0?j.awaitDrainWriters.clear():j.awaitDrainWriters=null,j.dataEmitted=!0,C.emit("data",_e)):(j.length+=j.objectMode?1:_e.length,Se?j.buffer.unshift(_e):j.buffer.push(_e),(j.state&ne)!==0&&he(C)),z(C,j)}se.prototype.isPaused=function(){let C=this._readableState;return C[K]===!0||C.flowing===!1},se.prototype.setEncoding=function(C){let j=new re(C);this._readableState.decoder=j,this._readableState.encoding=this._readableState.decoder.encoding;let _e=this._readableState.buffer,Se="";for(let Ee of _e)Se+=j.write(Ee);return _e.clear(),Se!==""&&_e.push(Se),this._readableState.length=Se.length,this};var w=1073741824;function A(C){if(C>w)throw new W("size","<= 1GiB",C);return C--,C|=C>>>1,C|=C>>>2,C|=C>>>4,C|=C>>>8,C|=C>>>16,C++,C}function U(C,j){return C<=0||j.length===0&&j.ended?0:(j.state&J)!==0?1:n(C)?j.flowing&&j.length?j.buffer.first().length:j.length:C<=j.length?C:j.ended?j.length:0}se.prototype.read=function(C){v("read",C),C===void 0?C=NaN:a(C)||(C=i(C,10));let j=this._readableState,_e=C;if(C>j.highWaterMark&&(j.highWaterMark=A(C)),C!==0&&(j.state&=~H),C===0&&j.needReadable&&((j.highWaterMark!==0?j.length>=j.highWaterMark:j.length>0)||j.ended))return v("read: emitReadable",j.length,j.ended),j.length===0&&j.ended?et(this):he(this),null;if(C=U(C,j),C===0&&j.ended)return j.length===0&&et(this),null;let Se=(j.state&ne)!==0;if(v("need readable",Se),(j.length===0||j.length-C<j.highWaterMark)&&(Se=!0,v("length less than watermark",Se)),j.ended||j.reading||j.destroyed||j.errored||!j.constructed)Se=!1,v("reading, ended or constructing",Se);else if(Se){v("do read"),j.state|=we|L,j.length===0&&(j.state|=ne);try{this._read(j.highWaterMark)}catch(Le){P(this,Le)}j.state&=~L,j.reading||(C=U(_e,j))}let Ee;return C>0?Ee=Bt(C,j):Ee=null,Ee===null?(j.needReadable=j.length<=j.highWaterMark,C=0):(j.length-=C,j.multiAwaitDrain?j.awaitDrainWriters.clear():j.awaitDrainWriters=null),j.length===0&&(j.ended||(j.needReadable=!0),_e!==C&&j.ended&&et(this)),Ee!==null&&!j.errorEmitted&&!j.closeEmitted&&(j.dataEmitted=!0,this.emit("data",Ee)),Ee};function X(C,j){if(v("onEofChunk"),!j.ended){if(j.decoder){let _e=j.decoder.end();_e&&_e.length&&(j.buffer.push(_e),j.length+=j.objectMode?1:_e.length)}j.ended=!0,j.sync?he(C):(j.needReadable=!1,j.emittedReadable=!0,ke(C))}}function he(C){let j=C._readableState;v("emitReadable",j.needReadable,j.emittedReadable),j.needReadable=!1,j.emittedReadable||(v("emitReadable",j.flowing),j.emittedReadable=!0,t.nextTick(ke,C))}function ke(C){let j=C._readableState;v("emitReadable_",j.destroyed,j.length,j.ended),!j.destroyed&&!j.errored&&(j.length||j.ended)&&(C.emit("readable"),j.emittedReadable=!1),j.needReadable=!j.flowing&&!j.ended&&j.length<=j.highWaterMark,Xe(C)}function z(C,j){!j.readingMore&&j.constructed&&(j.readingMore=!0,t.nextTick(ie,C,j))}function ie(C,j){for(;!j.reading&&!j.ended&&(j.length<j.highWaterMark||j.flowing&&j.length===0);){let _e=j.length;if(v("maybeReadMore read 0"),C.read(0),_e===j.length)break}j.readingMore=!1}se.prototype._read=function(C){throw new T("_read()")},se.prototype.pipe=function(C,j){let _e=this,Se=this._readableState;Se.pipes.length===1&&(Se.multiAwaitDrain||(Se.multiAwaitDrain=!0,Se.awaitDrainWriters=new d(Se.awaitDrainWriters?[Se.awaitDrainWriters]:[]))),Se.pipes.push(C),v("pipe count=%d opts=%j",Se.pipes.length,j);let Ee=(!j||j.end!==!1)&&C!==t.stdout&&C!==t.stderr?qe:Tt;Se.endEmitted?t.nextTick(Ee):_e.once("end",Ee),C.on("unpipe",Le);function Le(rt,ft){v("onunpipe"),rt===_e&&ft&&ft.hasUnpiped===!1&&(ft.hasUnpiped=!0,Qt())}function qe(){v("onend"),C.end()}let Ge,Yt=!1;function Qt(){v("cleanup"),C.removeListener("close",tt),C.removeListener("finish",vt),Ge&&C.removeListener("drain",Ge),C.removeListener("error",It),C.removeListener("unpipe",Le),_e.removeListener("end",qe),_e.removeListener("end",Tt),_e.removeListener("data",Fr),Yt=!0,Ge&&Se.awaitDrainWriters&&(!C._writableState||C._writableState.needDrain)&&Ge()}function Jt(){Yt||(Se.pipes.length===1&&Se.pipes[0]===C?(v("false write response, pause",0),Se.awaitDrainWriters=C,Se.multiAwaitDrain=!1):Se.pipes.length>1&&Se.pipes.includes(C)&&(v("false write response, pause",Se.awaitDrainWriters.size),Se.awaitDrainWriters.add(C)),_e.pause()),Ge||(Ge=xe(_e,C),C.on("drain",Ge))}_e.on("data",Fr);function Fr(rt){v("ondata");let ft=C.write(rt);v("dest.write",ft),ft===!1&&Jt()}function It(rt){if(v("onerror",rt),Tt(),C.removeListener("error",It),C.listenerCount("error")===0){let ft=C._writableState||C._readableState;ft&&!ft.errorEmitted?P(C,rt):C.emit("error",rt)}}k(C,"error",It);function tt(){C.removeListener("finish",vt),Tt()}C.once("close",tt);function vt(){v("onfinish"),C.removeListener("close",tt),Tt()}C.once("finish",vt);function Tt(){v("unpipe"),_e.unpipe(C)}return C.emit("pipe",_e),C.writableNeedDrain===!0?Jt():Se.flowing||(v("pipe resume"),_e.resume()),C};function xe(C,j){return function(){let _e=C._readableState;_e.awaitDrainWriters===j?(v("pipeOnDrain",1),_e.awaitDrainWriters=null):_e.multiAwaitDrain&&(v("pipeOnDrain",_e.awaitDrainWriters.size),_e.awaitDrainWriters.delete(j)),(!_e.awaitDrainWriters||_e.awaitDrainWriters.size===0)&&C.listenerCount("data")&&C.resume()}}se.prototype.unpipe=function(C){let j=this._readableState,_e={hasUnpiped:!1};if(j.pipes.length===0)return this;if(!C){let Ee=j.pipes;j.pipes=[],this.pause();for(let Le=0;Le<Ee.length;Le++)Ee[Le].emit("unpipe",this,{hasUnpiped:!1});return this}let Se=r(j.pipes,C);return Se===-1?this:(j.pipes.splice(Se,1),j.pipes.length===0&&this.pause(),C.emit("unpipe",this,_e),this)},se.prototype.on=function(C,j){let _e=b.prototype.on.call(this,C,j),Se=this._readableState;return C==="data"?(Se.readableListening=this.listenerCount("readable")>0,Se.flowing!==!1&&this.resume()):C==="readable"&&!Se.endEmitted&&!Se.readableListening&&(Se.readableListening=Se.needReadable=!0,Se.flowing=!1,Se.emittedReadable=!1,v("on readable",Se.length,Se.reading),Se.length?he(this):Se.reading||t.nextTick(Ie,this)),_e},se.prototype.addListener=se.prototype.on,se.prototype.removeListener=function(C,j){let _e=b.prototype.removeListener.call(this,C,j);return C==="readable"&&t.nextTick(Ae,this),_e},se.prototype.off=se.prototype.removeListener,se.prototype.removeAllListeners=function(C){let j=b.prototype.removeAllListeners.apply(this,arguments);return(C==="readable"||C===void 0)&&t.nextTick(Ae,this),j};function Ae(C){let j=C._readableState;j.readableListening=C.listenerCount("readable")>0,j.resumeScheduled&&j[K]===!1?j.flowing=!0:C.listenerCount("data")>0?C.resume():j.readableListening||(j.flowing=null)}function Ie(C){v("readable nexttick read 0"),C.read(0)}se.prototype.resume=function(){let C=this._readableState;return C.flowing||(v("resume"),C.flowing=!C.readableListening,Oe(this,C)),C[K]=!1,this};function Oe(C,j){j.resumeScheduled||(j.resumeScheduled=!0,t.nextTick(Je,C,j))}function Je(C,j){v("resume",j.reading),j.reading||C.read(0),j.resumeScheduled=!1,C.emit("resume"),Xe(C),j.flowing&&!j.reading&&C.read(0)}se.prototype.pause=function(){return v("call pause flowing=%j",this._readableState.flowing),this._readableState.flowing!==!1&&(v("pause"),this._readableState.flowing=!1,this.emit("pause")),this._readableState[K]=!0,this};function Xe(C){let j=C._readableState;for(v("flow",j.flowing);j.flowing&&C.read()!==null;);}se.prototype.wrap=function(C){let j=!1;C.on("data",Se=>{!this.push(Se)&&C.pause&&(j=!0,C.pause())}),C.on("end",()=>{this.push(null)}),C.on("error",Se=>{P(this,Se)}),C.on("close",()=>{this.destroy()}),C.on("destroy",()=>{this.destroy()}),this._read=()=>{j&&C.resume&&(j=!1,C.resume())};let _e=o(C);for(let Se=1;Se<_e.length;Se++){let Ee=_e[Se];this[Ee]===void 0&&typeof C[Ee]=="function"&&(this[Ee]=C[Ee].bind(C))}return this},se.prototype[y]=function(){return $e(this)},se.prototype.iterator=function(C){return C!==void 0&&Y(C,"options"),$e(this,C)};function $e(C,j){typeof C.read!="function"&&(C=se.wrap(C,{objectMode:!0}));let _e=Ze(C,j);return _e.stream=C,_e}async function*Ze(C,j){let _e=Z;function Se(qe){this===C?(_e(),_e=Z):_e=qe}C.on("readable",Se);let Ee,Le=S(C,{writable:!1},qe=>{Ee=qe?O(Ee,qe):null,_e(),_e=Z});try{for(;;){let qe=C.destroyed?null:C.read();if(qe!==null)yield qe;else{if(Ee)throw Ee;if(Ee===null)return;await new u(Se)}}}catch(qe){throw Ee=O(Ee,qe),Ee}finally{(Ee||j?.destroyOnReturn!==!1)&&(Ee===void 0||C._readableState.autoDestroy)?E.destroyer(C,null):(C.off("readable",Se),Le())}}s(se.prototype,{readable:{__proto__:null,get(){let C=this._readableState;return!!C&&C.readable!==!1&&!C.destroyed&&!C.errorEmitted&&!C.endEmitted},set(C){this._readableState&&(this._readableState.readable=!!C)}},readableDidRead:{__proto__:null,enumerable:!1,get:function(){return this._readableState.dataEmitted}},readableAborted:{__proto__:null,enumerable:!1,get:function(){return!!(this._readableState.readable!==!1&&(this._readableState.destroyed||this._readableState.errored)&&!this._readableState.endEmitted)}},readableHighWaterMark:{__proto__:null,enumerable:!1,get:function(){return this._readableState.highWaterMark}},readableBuffer:{__proto__:null,enumerable:!1,get:function(){return this._readableState&&this._readableState.buffer}},readableFlowing:{__proto__:null,enumerable:!1,get:function(){return this._readableState.flowing},set:function(C){this._readableState&&(this._readableState.flowing=C)}},readableLength:{__proto__:null,enumerable:!1,get(){return this._readableState.length}},readableObjectMode:{__proto__:null,enumerable:!1,get(){return this._readableState?this._readableState.objectMode:!1}},readableEncoding:{__proto__:null,enumerable:!1,get(){return this._readableState?this._readableState.encoding:null}},errored:{__proto__:null,enumerable:!1,get(){return this._readableState?this._readableState.errored:null}},closed:{__proto__:null,get(){return this._readableState?this._readableState.closed:!1}},destroyed:{__proto__:null,enumerable:!1,get(){return this._readableState?this._readableState.destroyed:!1},set(C){this._readableState&&(this._readableState.destroyed=C)}},readableEnded:{__proto__:null,enumerable:!1,get(){return this._readableState?this._readableState.endEmitted:!1}}}),s(ve.prototype,{pipesCount:{__proto__:null,get(){return this.pipes.length}},paused:{__proto__:null,get(){return this[K]!==!1},set(C){this[K]=!!C}}}),se._fromList=Bt;function Bt(C,j){if(j.length===0)return null;let _e;return j.objectMode?_e=j.buffer.shift():!C||C>=j.length?(j.decoder?_e=j.buffer.join(""):j.buffer.length===1?_e=j.buffer.first():_e=j.buffer.concat(j.length),j.buffer.clear()):_e=j.buffer.consume(C,j.decoder),_e}function et(C){let j=C._readableState;v("endReadable",j.endEmitted),j.endEmitted||(j.ended=!0,t.nextTick(Ve,j,C))}function Ve(C,j){if(v("endReadableNT",C.endEmitted,C.length),!C.errored&&!C.closeEmitted&&!C.endEmitted&&C.length===0){if(C.endEmitted=!0,j.emit("end"),j.writable&&j.allowHalfOpen===!1)t.nextTick(Br,j);else if(C.autoDestroy){let _e=j._writableState;(!_e||_e.autoDestroy&&(_e.finished||_e.writable===!1))&&j.destroy()}}}function Br(C){C.writable&&!C.writableEnded&&!C.destroyed&&C.end()}se.from=function(C,j){return D(se,C,j)};var Ft;function Gt(){return Ft===void 0&&(Ft={}),Ft}se.fromWeb=function(C,j){return Gt().newStreamReadableFromReadableStream(C,j)},se.toWeb=function(C,j){return Gt().newReadableStreamFromStreamReadable(C,j)},se.wrap=function(C,j){var _e,Se;return new se({objectMode:(_e=(Se=C.readableObjectMode)!==null&&Se!==void 0?Se:C.objectMode)!==null&&_e!==void 0?_e:!0,...j,destroy(Ee,Le){E.destroyer(C,Ee),Le(Ee)}}).wrap(C)}}),ri=pe((c,e)=>{le(),ue(),ce();var t=St(),{ArrayPrototypeSlice:r,Error:a,FunctionPrototypeSymbolHasInstance:n,ObjectDefineProperty:i,ObjectDefineProperties:s,ObjectSetPrototypeOf:o,StringPrototypeToLowerCase:l,Symbol:u,SymbolHasInstance:d}=je();e.exports=Y,Y.WritableState=N;var{EventEmitter:p}=(kt(),Pe(pt)),y=ti().Stream,{Buffer:f}=(Ue(),Pe(Ne)),m=Mt(),{addAbortSignal:b}=nr(),{getHighWaterMark:k,getDefaultHighWaterMark:g}=ir(),{ERR_INVALID_ARG_TYPE:_,ERR_METHOD_NOT_IMPLEMENTED:S,ERR_MULTIPLE_CALLBACK:v,ERR_STREAM_CANNOT_PIPE:x,ERR_STREAM_DESTROYED:E,ERR_STREAM_ALREADY_FINISHED:I,ERR_STREAM_NULL_VALUES:M,ERR_STREAM_WRITE_AFTER_END:O,ERR_UNKNOWN_ENCODING:B}=We().codes,{errorOrDestroy:T}=m;o(Y.prototype,y.prototype),o(Y,y);function W(){}var F=u("kOnFinished");function N(R,$,ee){typeof ee!="boolean"&&(ee=$ instanceof at()),this.objectMode=!!(R&&R.objectMode),ee&&(this.objectMode=this.objectMode||!!(R&&R.writableObjectMode)),this.highWaterMark=R?k(this,R,"writableHighWaterMark",ee):g(!1),this.finalCalled=!1,this.needDrain=!1,this.ending=!1,this.ended=!1,this.finished=!1,this.destroyed=!1;let fe=!!(R&&R.decodeStrings===!1);this.decodeStrings=!fe,this.defaultEncoding=R&&R.defaultEncoding||"utf8",this.length=0,this.writing=!1,this.corked=0,this.sync=!0,this.bufferProcessing=!1,this.onwrite=P.bind(void 0,$),this.writecb=null,this.writelen=0,this.afterWriteTickInfo=null,ae(this),this.pendingcb=0,this.constructed=!0,this.prefinished=!1,this.errorEmitted=!1,this.emitClose=!R||R.emitClose!==!1,this.autoDestroy=!R||R.autoDestroy!==!1,this.errored=null,this.closed=!1,this.closeEmitted=!1,this[F]=[]}function ae(R){R.buffered=[],R.bufferedIndex=0,R.allBuffers=!0,R.allNoop=!0}N.prototype.getBuffer=function(){return r(this.buffered,this.bufferedIndex)},i(N.prototype,"bufferedRequestCount",{__proto__:null,get(){return this.buffered.length-this.bufferedIndex}});function Y(R){let $=this instanceof at();if(!$&&!n(Y,this))return new Y(R);this._writableState=new N(R,this,$),R&&(typeof R.write=="function"&&(this._write=R.write),typeof R.writev=="function"&&(this._writev=R.writev),typeof R.destroy=="function"&&(this._destroy=R.destroy),typeof R.final=="function"&&(this._final=R.final),typeof R.construct=="function"&&(this._construct=R.construct),R.signal&&b(R.signal,this)),y.call(this,R),m.construct(this,()=>{let ee=this._writableState;ee.writing||we(this,ee),H(this,ee)})}i(Y,d,{__proto__:null,value:function(R){return n(this,R)?!0:this!==Y?!1:R&&R._writableState instanceof N}}),Y.prototype.pipe=function(){T(this,new x)};function K(R,$,ee,fe){let de=R._writableState;if(typeof ee=="function")fe=ee,ee=de.defaultEncoding;else{if(!ee)ee=de.defaultEncoding;else if(ee!=="buffer"&&!f.isEncoding(ee))throw new B(ee);typeof fe!="function"&&(fe=W)}if($===null)throw new M;if(!de.objectMode)if(typeof $=="string")de.decodeStrings!==!1&&($=f.from($,ee),ee="buffer");else if($ instanceof f)ee="buffer";else if(y._isUint8Array($))$=y._uint8ArrayToBuffer($),ee="buffer";else throw new _("chunk",["string","Buffer","Uint8Array"],$);let ye;return de.ending?ye=new O:de.destroyed&&(ye=new E("write")),ye?(t.nextTick(fe,ye),T(R,ye,!0),ye):(de.pendingcb++,re(R,de,$,ee,fe))}Y.prototype.write=function(R,$,ee){return K(this,R,$,ee)===!0},Y.prototype.cork=function(){this._writableState.corked++},Y.prototype.uncork=function(){let R=this._writableState;R.corked&&(R.corked--,R.writing||we(this,R))},Y.prototype.setDefaultEncoding=function(R){if(typeof R=="string"&&(R=l(R)),!f.isEncoding(R))throw new B(R);return this._writableState.defaultEncoding=R,this};function re(R,$,ee,fe,de){let ye=$.objectMode?1:ee.length;$.length+=ye;let q=$.length<$.highWaterMark;return q||($.needDrain=!0),$.writing||$.corked||$.errored||!$.constructed?($.buffered.push({chunk:ee,encoding:fe,callback:de}),$.allBuffers&&fe!=="buffer"&&($.allBuffers=!1),$.allNoop&&de!==W&&($.allNoop=!1)):($.writelen=ye,$.writecb=de,$.writing=!0,$.sync=!0,R._write(ee,fe,$.onwrite),$.sync=!1),q&&!$.errored&&!$.destroyed}function D(R,$,ee,fe,de,ye,q){$.writelen=fe,$.writecb=q,$.writing=!0,$.sync=!0,$.destroyed?$.onwrite(new E("write")):ee?R._writev(de,$.onwrite):R._write(de,ye,$.onwrite),$.sync=!1}function Z(R,$,ee,fe){--$.pendingcb,fe(ee),te($),T(R,ee)}function P(R,$){let ee=R._writableState,fe=ee.sync,de=ee.writecb;if(typeof de!="function"){T(R,new v);return}ee.writing=!1,ee.writecb=null,ee.length-=ee.writelen,ee.writelen=0,$?($.stack,ee.errored||(ee.errored=$),R._readableState&&!R._readableState.errored&&(R._readableState.errored=$),fe?t.nextTick(Z,R,ee,$,de):Z(R,ee,$,de)):(ee.buffered.length>ee.bufferedIndex&&we(R,ee),fe?ee.afterWriteTickInfo!==null&&ee.afterWriteTickInfo.cb===de?ee.afterWriteTickInfo.count++:(ee.afterWriteTickInfo={count:1,cb:de,stream:R,state:ee},t.nextTick(J,ee.afterWriteTickInfo)):be(R,ee,1,de))}function J({stream:R,state:$,count:ee,cb:fe}){return $.afterWriteTickInfo=null,be(R,$,ee,fe)}function be(R,$,ee,fe){for(!$.ending&&!R.destroyed&&$.length===0&&$.needDrain&&($.needDrain=!1,R.emit("drain"));ee-- >0;)$.pendingcb--,fe();$.destroyed&&te($),H(R,$)}function te(R){if(R.writing)return;for(let de=R.bufferedIndex;de<R.buffered.length;++de){var $;let{chunk:ye,callback:q}=R.buffered[de],ge=R.objectMode?1:ye.length;R.length-=ge,q(($=R.errored)!==null&&$!==void 0?$:new E("write"))}let ee=R[F].splice(0);for(let de=0;de<ee.length;de++){var fe;ee[de]((fe=R.errored)!==null&&fe!==void 0?fe:new E("end"))}ae(R)}function we(R,$){if($.corked||$.bufferProcessing||$.destroyed||!$.constructed)return;let{buffered:ee,bufferedIndex:fe,objectMode:de}=$,ye=ee.length-fe;if(!ye)return;let q=fe;if($.bufferProcessing=!0,ye>1&&R._writev){$.pendingcb-=ye-1;let ge=$.allNoop?W:se=>{for(let Te=q;Te<ee.length;++Te)ee[Te].callback(se)},ve=$.allNoop&&q===0?ee:r(ee,q);ve.allBuffers=$.allBuffers,D(R,$,!0,$.length,ve,"",ge),ae($)}else{do{let{chunk:ge,encoding:ve,callback:se}=ee[q];ee[q++]=null;let Te=de?1:ge.length;D(R,$,!1,Te,ge,ve,se)}while(q<ee.length&&!$.writing);q===ee.length?ae($):q>256?(ee.splice(0,q),$.bufferedIndex=0):$.bufferedIndex=q}$.bufferProcessing=!1}Y.prototype._write=function(R,$,ee){if(this._writev)this._writev([{chunk:R,encoding:$}],ee);else throw new S("_write()")},Y.prototype._writev=null,Y.prototype.end=function(R,$,ee){let fe=this._writableState;typeof R=="function"?(ee=R,R=null,$=null):typeof $=="function"&&(ee=$,$=null);let de;if(R!=null){let ye=K(this,R,$);ye instanceof a&&(de=ye)}return fe.corked&&(fe.corked=1,this.uncork()),de||(!fe.errored&&!fe.ending?(fe.ending=!0,H(this,fe,!0),fe.ended=!0):fe.finished?de=new I("end"):fe.destroyed&&(de=new E("end"))),typeof ee=="function"&&(de||fe.finished?t.nextTick(ee,de):fe[F].push(ee)),this};function V(R){return R.ending&&!R.destroyed&&R.constructed&&R.length===0&&!R.errored&&R.buffered.length===0&&!R.finished&&!R.writing&&!R.errorEmitted&&!R.closeEmitted}function L(R,$){let ee=!1;function fe(de){if(ee){T(R,de??v());return}if(ee=!0,$.pendingcb--,de){let ye=$[F].splice(0);for(let q=0;q<ye.length;q++)ye[q](de);T(R,de,$.sync)}else V($)&&($.prefinished=!0,R.emit("prefinish"),$.pendingcb++,t.nextTick(G,R,$))}$.sync=!0,$.pendingcb++;try{R._final(fe)}catch(de){fe(de)}$.sync=!1}function ne(R,$){!$.prefinished&&!$.finalCalled&&(typeof R._final=="function"&&!$.destroyed?($.finalCalled=!0,L(R,$)):($.prefinished=!0,R.emit("prefinish")))}function H(R,$,ee){V($)&&(ne(R,$),$.pendingcb===0&&(ee?($.pendingcb++,t.nextTick((fe,de)=>{V(de)?G(fe,de):de.pendingcb--},R,$)):V($)&&($.pendingcb++,G(R,$))))}function G(R,$){$.pendingcb--,$.finished=!0;let ee=$[F].splice(0);for(let fe=0;fe<ee.length;fe++)ee[fe]();if(R.emit("finish"),$.autoDestroy){let fe=R._readableState;(!fe||fe.autoDestroy&&(fe.endEmitted||fe.readable===!1))&&R.destroy()}}s(Y.prototype,{closed:{__proto__:null,get(){return this._writableState?this._writableState.closed:!1}},destroyed:{__proto__:null,get(){return this._writableState?this._writableState.destroyed:!1},set(R){this._writableState&&(this._writableState.destroyed=R)}},writable:{__proto__:null,get(){let R=this._writableState;return!!R&&R.writable!==!1&&!R.destroyed&&!R.errored&&!R.ending&&!R.ended},set(R){this._writableState&&(this._writableState.writable=!!R)}},writableFinished:{__proto__:null,get(){return this._writableState?this._writableState.finished:!1}},writableObjectMode:{__proto__:null,get(){return this._writableState?this._writableState.objectMode:!1}},writableBuffer:{__proto__:null,get(){return this._writableState&&this._writableState.getBuffer()}},writableEnded:{__proto__:null,get(){return this._writableState?this._writableState.ending:!1}},writableNeedDrain:{__proto__:null,get(){let R=this._writableState;return R?!R.destroyed&&!R.ending&&R.needDrain:!1}},writableHighWaterMark:{__proto__:null,get(){return this._writableState&&this._writableState.highWaterMark}},writableCorked:{__proto__:null,get(){return this._writableState?this._writableState.corked:0}},writableLength:{__proto__:null,get(){return this._writableState&&this._writableState.length}},errored:{__proto__:null,enumerable:!1,get(){return this._writableState?this._writableState.errored:null}},writableAborted:{__proto__:null,enumerable:!1,get:function(){return!!(this._writableState.writable!==!1&&(this._writableState.destroyed||this._writableState.errored)&&!this._writableState.finished)}}});var Q=m.destroy;Y.prototype.destroy=function(R,$){let ee=this._writableState;return!ee.destroyed&&(ee.bufferedIndex<ee.buffered.length||ee[F].length)&&t.nextTick(te,ee),Q.call(this,R,$),this},Y.prototype._undestroy=m.undestroy,Y.prototype._destroy=function(R,$){$(R)},Y.prototype[p.captureRejectionSymbol]=function(R){this.destroy(R)};var me;function oe(){return me===void 0&&(me={}),me}Y.fromWeb=function(R,$){return oe().newStreamWritableFromWritableStream(R,$)},Y.toWeb=function(R){return oe().newWritableStreamFromStreamWritable(R)}}),gc=pe((c,e)=>{le(),ue(),ce();var t=St(),r=(Ue(),Pe(Ne)),{isReadable:a,isWritable:n,isIterable:i,isNodeStream:s,isReadableNodeStream:o,isWritableNodeStream:l,isDuplexNodeStream:u,isReadableStream:d,isWritableStream:p}=st(),y=gt(),{AbortError:f,codes:{ERR_INVALID_ARG_TYPE:m,ERR_INVALID_RETURN_VALUE:b}}=We(),{destroyer:k}=Mt(),g=at(),_=or(),S=ri(),{createDeferredPromise:v}=ze(),x=Ho(),E=globalThis.Blob||r.Blob,I=typeof E<"u"?function(F){return F instanceof E}:function(F){return!1},M=globalThis.AbortController||qt().AbortController,{FunctionPrototypeCall:O}=je(),B=class extends g{constructor(F){super(F),F?.readable===!1&&(this._readableState.readable=!1,this._readableState.ended=!0,this._readableState.endEmitted=!0),F?.writable===!1&&(this._writableState.writable=!1,this._writableState.ending=!0,this._writableState.ended=!0,this._writableState.finished=!0)}};e.exports=function F(N,ae){if(u(N))return N;if(o(N))return W({readable:N});if(l(N))return W({writable:N});if(s(N))return W({writable:!1,readable:!1});if(d(N))return W({readable:_.fromWeb(N)});if(p(N))return W({writable:S.fromWeb(N)});if(typeof N=="function"){let{value:K,write:re,final:D,destroy:Z}=T(N);if(i(K))return x(B,K,{objectMode:!0,write:re,final:D,destroy:Z});let P=K?.then;if(typeof P=="function"){let J,be=O(P,K,te=>{if(te!=null)throw new b("nully","body",te)},te=>{k(J,te)});return J=new B({objectMode:!0,readable:!1,write:re,final(te){D(async()=>{try{await be,t.nextTick(te,null)}catch(we){t.nextTick(te,we)}})},destroy:Z})}throw new b("Iterable, AsyncIterable or AsyncFunction",ae,K)}if(I(N))return F(N.arrayBuffer());if(i(N))return x(B,N,{objectMode:!0,writable:!1});if(d(N?.readable)&&p(N?.writable))return B.fromWeb(N);if(typeof N?.writable=="object"||typeof N?.readable=="object"){let K=N!=null&&N.readable?o(N?.readable)?N?.readable:F(N.readable):void 0,re=N!=null&&N.writable?l(N?.writable)?N?.writable:F(N.writable):void 0;return W({readable:K,writable:re})}let Y=N?.then;if(typeof Y=="function"){let K;return O(Y,N,re=>{re!=null&&K.push(re),K.push(null)},re=>{k(K,re)}),K=new B({objectMode:!0,writable:!1,read(){}})}throw new m(ae,["Blob","ReadableStream","WritableStream","Stream","Iterable","AsyncIterable","Function","{ readable, writable } pair","Promise"],N)};function T(F){let{promise:N,resolve:ae}=v(),Y=new M,K=Y.signal;return{value:F((async function*(){for(;;){let re=N;N=null;let{chunk:D,done:Z,cb:P}=await re;if(t.nextTick(P),Z)return;if(K.aborted)throw new f(void 0,{cause:K.reason});({promise:N,resolve:ae}=v()),yield D}})(),{signal:K}),write(re,D,Z){let P=ae;ae=null,P({chunk:re,done:!1,cb:Z})},final(re){let D=ae;ae=null,D({done:!0,cb:re})},destroy(re,D){Y.abort(),D(re)}}}function W(F){let N=F.readable&&typeof F.readable.read!="function"?_.wrap(F.readable):F.readable,ae=F.writable,Y=!!a(N),K=!!n(ae),re,D,Z,P,J;function be(te){let we=P;P=null,we?we(te):te&&J.destroy(te)}return J=new B({readableObjectMode:!!(N!=null&&N.readableObjectMode),writableObjectMode:!!(ae!=null&&ae.writableObjectMode),readable:Y,writable:K}),K&&(y(ae,te=>{K=!1,te&&k(N,te),be(te)}),J._write=function(te,we,V){ae.write(te,we)?V():re=V},J._final=function(te){ae.end(),D=te},ae.on("drain",function(){if(re){let te=re;re=null,te()}}),ae.on("finish",function(){if(D){let te=D;D=null,te()}})),Y&&(y(N,te=>{Y=!1,te&&k(N,te),be(te)}),N.on("readable",function(){if(Z){let te=Z;Z=null,te()}}),N.on("end",function(){J.push(null)}),J._read=function(){for(;;){let te=N.read();if(te===null){Z=J._read;return}if(!J.push(te))return}}),J._destroy=function(te,we){!te&&P!==null&&(te=new f),Z=null,re=null,D=null,P===null?we(te):(P=we,k(ae,te),k(N,te))},J}}),at=pe((c,e)=>{le(),ue(),ce();var{ObjectDefineProperties:t,ObjectGetOwnPropertyDescriptor:r,ObjectKeys:a,ObjectSetPrototypeOf:n}=je();e.exports=o;var i=or(),s=ri();n(o.prototype,i.prototype),n(o,i);{let p=a(s.prototype);for(let y=0;y<p.length;y++){let f=p[y];o.prototype[f]||(o.prototype[f]=s.prototype[f])}}function o(p){if(!(this instanceof o))return new o(p);i.call(this,p),s.call(this,p),p?(this.allowHalfOpen=p.allowHalfOpen!==!1,p.readable===!1&&(this._readableState.readable=!1,this._readableState.ended=!0,this._readableState.endEmitted=!0),p.writable===!1&&(this._writableState.writable=!1,this._writableState.ending=!0,this._writableState.ended=!0,this._writableState.finished=!0)):this.allowHalfOpen=!0}t(o.prototype,{writable:{__proto__:null,...r(s.prototype,"writable")},writableHighWaterMark:{__proto__:null,...r(s.prototype,"writableHighWaterMark")},writableObjectMode:{__proto__:null,...r(s.prototype,"writableObjectMode")},writableBuffer:{__proto__:null,...r(s.prototype,"writableBuffer")},writableLength:{__proto__:null,...r(s.prototype,"writableLength")},writableFinished:{__proto__:null,...r(s.prototype,"writableFinished")},writableCorked:{__proto__:null,...r(s.prototype,"writableCorked")},writableEnded:{__proto__:null,...r(s.prototype,"writableEnded")},writableNeedDrain:{__proto__:null,...r(s.prototype,"writableNeedDrain")},destroyed:{__proto__:null,get(){return this._readableState===void 0||this._writableState===void 0?!1:this._readableState.destroyed&&this._writableState.destroyed},set(p){this._readableState&&this._writableState&&(this._readableState.destroyed=p,this._writableState.destroyed=p)}}});var l;function u(){return l===void 0&&(l={}),l}o.fromWeb=function(p,y){return u().newStreamDuplexFromReadableWritablePair(p,y)},o.toWeb=function(p){return u().newReadableWritablePairFromDuplex(p)};var d;o.from=function(p){return d||(d=gc()),d(p,"body")}}),zo=pe((c,e)=>{le(),ue(),ce();var{ObjectSetPrototypeOf:t,Symbol:r}=je();e.exports=o;var{ERR_METHOD_NOT_IMPLEMENTED:a}=We().codes,n=at(),{getHighWaterMark:i}=ir();t(o.prototype,n.prototype),t(o,n);var s=r("kCallback");function o(d){if(!(this instanceof o))return new o(d);let p=d?i(this,d,"readableHighWaterMark",!0):null;p===0&&(d={...d,highWaterMark:null,readableHighWaterMark:p,writableHighWaterMark:d.writableHighWaterMark||0}),n.call(this,d),this._readableState.sync=!1,this[s]=null,d&&(typeof d.transform=="function"&&(this._transform=d.transform),typeof d.flush=="function"&&(this._flush=d.flush)),this.on("prefinish",u)}function l(d){typeof this._flush=="function"&&!this.destroyed?this._flush((p,y)=>{if(p){d?d(p):this.destroy(p);return}y!=null&&this.push(y),this.push(null),d&&d()}):(this.push(null),d&&d())}function u(){this._final!==l&&l.call(this)}o.prototype._final=l,o.prototype._transform=function(d,p,y){throw new a("_transform()")},o.prototype._write=function(d,p,y){let f=this._readableState,m=this._writableState,b=f.length;this._transform(d,p,(k,g)=>{if(k){y(k);return}g!=null&&this.push(g),m.ended||b===f.length||f.length<f.highWaterMark?y():this[s]=y})},o.prototype._read=function(){if(this[s]){let d=this[s];this[s]=null,d()}}}),Ko=pe((c,e)=>{le(),ue(),ce();var{ObjectSetPrototypeOf:t}=je();e.exports=a;var r=zo();t(a.prototype,r.prototype),t(a,r);function a(n){if(!(this instanceof a))return new a(n);r.call(this,n)}a.prototype._transform=function(n,i,s){s(null,n)}}),ni=pe((c,e)=>{le(),ue(),ce();var t=St(),{ArrayIsArray:r,Promise:a,SymbolAsyncIterator:n,SymbolDispose:i}=je(),s=gt(),{once:o}=ze(),l=Mt(),u=at(),{aggregateTwoErrors:d,codes:{ERR_INVALID_ARG_TYPE:p,ERR_INVALID_RETURN_VALUE:y,ERR_MISSING_ARGS:f,ERR_STREAM_DESTROYED:m,ERR_STREAM_PREMATURE_CLOSE:b},AbortError:k}=We(),{validateFunction:g,validateAbortSignal:_}=zt(),{isIterable:S,isReadable:v,isReadableNodeStream:x,isNodeStream:E,isTransformStream:I,isWebStream:M,isReadableStream:O,isReadableFinished:B}=st(),T=globalThis.AbortController||qt().AbortController,W,F,N;function ae(te,we,V){let L=!1;te.on("close",()=>{L=!0});let ne=s(te,{readable:we,writable:V},H=>{L=!H});return{destroy:H=>{L||(L=!0,l.destroyer(te,H||new m("pipe")))},cleanup:ne}}function Y(te){return g(te[te.length-1],"streams[stream.length - 1]"),te.pop()}function K(te){if(S(te))return te;if(x(te))return re(te);throw new p("val",["Readable","Iterable","AsyncIterable"],te)}async function*re(te){F||(F=or()),yield*F.prototype[n].call(te)}async function D(te,we,V,{end:L}){let ne,H=null,G=oe=>{if(oe&&(ne=oe),H){let R=H;H=null,R()}},Q=()=>new a((oe,R)=>{ne?R(ne):H=()=>{ne?R(ne):oe()}});we.on("drain",G);let me=s(we,{readable:!1},G);try{we.writableNeedDrain&&await Q();for await(let oe of te)we.write(oe)||await Q();L&&(we.end(),await Q()),V()}catch(oe){V(ne!==oe?d(ne,oe):oe)}finally{me(),we.off("drain",G)}}async function Z(te,we,V,{end:L}){I(we)&&(we=we.writable);let ne=we.getWriter();try{for await(let H of te)await ne.ready,ne.write(H).catch(()=>{});await ne.ready,L&&await ne.close(),V()}catch(H){try{await ne.abort(H),V(H)}catch(G){V(G)}}}function P(...te){return J(te,o(Y(te)))}function J(te,we,V){if(te.length===1&&r(te[0])&&(te=te[0]),te.length<2)throw new f("streams");let L=new T,ne=L.signal,H=V?.signal,G=[];_(H,"options.signal");function Q(){de(new k)}N=N||ze().addAbortListener;let me;H&&(me=N(H,Q));let oe,R,$=[],ee=0;function fe(ve){de(ve,--ee===0)}function de(ve,se){var Te;if(ve&&(!oe||oe.code==="ERR_STREAM_PREMATURE_CLOSE")&&(oe=ve),!(!oe&&!se)){for(;$.length;)$.shift()(oe);(Te=me)===null||Te===void 0||Te[i](),L.abort(),se&&(oe||G.forEach(h=>h()),t.nextTick(we,oe,R))}}let ye;for(let ve=0;ve<te.length;ve++){let se=te[ve],Te=ve<te.length-1,h=ve>0,w=Te||V?.end!==!1,A=ve===te.length-1;if(E(se)){let U=function(X){X&&X.name!=="AbortError"&&X.code!=="ERR_STREAM_PREMATURE_CLOSE"&&fe(X)};if(w){let{destroy:X,cleanup:he}=ae(se,Te,h);$.push(X),v(se)&&A&&G.push(he)}se.on("error",U),v(se)&&A&&G.push(()=>{se.removeListener("error",U)})}if(ve===0)if(typeof se=="function"){if(ye=se({signal:ne}),!S(ye))throw new y("Iterable, AsyncIterable or Stream","source",ye)}else S(se)||x(se)||I(se)?ye=se:ye=u.from(se);else if(typeof se=="function"){if(I(ye)){var q;ye=K((q=ye)===null||q===void 0?void 0:q.readable)}else ye=K(ye);if(ye=se(ye,{signal:ne}),Te){if(!S(ye,!0))throw new y("AsyncIterable",`transform[${ve-1}]`,ye)}else{var ge;W||(W=Ko());let U=new W({objectMode:!0}),X=(ge=ye)===null||ge===void 0?void 0:ge.then;if(typeof X=="function")ee++,X.call(ye,z=>{R=z,z!=null&&U.write(z),w&&U.end(),t.nextTick(fe)},z=>{U.destroy(z),t.nextTick(fe,z)});else if(S(ye,!0))ee++,D(ye,U,fe,{end:w});else if(O(ye)||I(ye)){let z=ye.readable||ye;ee++,D(z,U,fe,{end:w})}else throw new y("AsyncIterable or Promise","destination",ye);ye=U;let{destroy:he,cleanup:ke}=ae(ye,!1,!0);$.push(he),A&&G.push(ke)}}else if(E(se)){if(x(ye)){ee+=2;let U=be(ye,se,fe,{end:w});v(se)&&A&&G.push(U)}else if(I(ye)||O(ye)){let U=ye.readable||ye;ee++,D(U,se,fe,{end:w})}else if(S(ye))ee++,D(ye,se,fe,{end:w});else throw new p("val",["Readable","Iterable","AsyncIterable","ReadableStream","TransformStream"],ye);ye=se}else if(M(se)){if(x(ye))ee++,Z(K(ye),se,fe,{end:w});else if(O(ye)||S(ye))ee++,Z(ye,se,fe,{end:w});else if(I(ye))ee++,Z(ye.readable,se,fe,{end:w});else throw new p("val",["Readable","Iterable","AsyncIterable","ReadableStream","TransformStream"],ye);ye=se}else ye=u.from(se)}return(ne!=null&&ne.aborted||H!=null&&H.aborted)&&t.nextTick(Q),ye}function be(te,we,V,{end:L}){let ne=!1;if(we.on("close",()=>{ne||V(new b)}),te.pipe(we,{end:!1}),L){let H=function(){ne=!0,we.end()};B(te)?t.nextTick(H):te.once("end",H)}else V();return s(te,{readable:!0,writable:!1},H=>{let G=te._readableState;H&&H.code==="ERR_STREAM_PREMATURE_CLOSE"&&G&&G.ended&&!G.errored&&!G.errorEmitted?te.once("end",V).once("error",V):V(H)}),s(we,{readable:!1,writable:!0},V)}e.exports={pipelineImpl:J,pipeline:P}}),Vo=pe((c,e)=>{le(),ue(),ce();var{pipeline:t}=ni(),r=at(),{destroyer:a}=Mt(),{isNodeStream:n,isReadable:i,isWritable:s,isWebStream:o,isTransformStream:l,isWritableStream:u,isReadableStream:d}=st(),{AbortError:p,codes:{ERR_INVALID_ARG_VALUE:y,ERR_MISSING_ARGS:f}}=We(),m=gt();e.exports=function(...b){if(b.length===0)throw new f("streams");if(b.length===1)return r.from(b[0]);let k=[...b];if(typeof b[0]=="function"&&(b[0]=r.from(b[0])),typeof b[b.length-1]=="function"){let T=b.length-1;b[T]=r.from(b[T])}for(let T=0;T<b.length;++T)if(!(!n(b[T])&&!o(b[T]))){if(T<b.length-1&&!(i(b[T])||d(b[T])||l(b[T])))throw new y(`streams[${T}]`,k[T],"must be readable");if(T>0&&!(s(b[T])||u(b[T])||l(b[T])))throw new y(`streams[${T}]`,k[T],"must be writable")}let g,_,S,v,x;function E(T){let W=v;v=null,W?W(T):T?x.destroy(T):!B&&!O&&x.destroy()}let I=b[0],M=t(b,E),O=!!(s(I)||u(I)||l(I)),B=!!(i(M)||d(M)||l(M));if(x=new r({writableObjectMode:!!(I!=null&&I.writableObjectMode),readableObjectMode:!!(M!=null&&M.readableObjectMode),writable:O,readable:B}),O){if(n(I))x._write=function(W,F,N){I.write(W,F)?N():g=N},x._final=function(W){I.end(),_=W},I.on("drain",function(){if(g){let W=g;g=null,W()}});else if(o(I)){let W=(l(I)?I.writable:I).getWriter();x._write=async function(F,N,ae){try{await W.ready,W.write(F).catch(()=>{}),ae()}catch(Y){ae(Y)}},x._final=async function(F){try{await W.ready,W.close().catch(()=>{}),_=F}catch(N){F(N)}}}let T=l(M)?M.readable:M;m(T,()=>{if(_){let W=_;_=null,W()}})}if(B){if(n(M))M.on("readable",function(){if(S){let T=S;S=null,T()}}),M.on("end",function(){x.push(null)}),x._read=function(){for(;;){let T=M.read();if(T===null){S=x._read;return}if(!x.push(T))return}};else if(o(M)){let T=(l(M)?M.readable:M).getReader();x._read=async function(){for(;;)try{let{value:W,done:F}=await T.read();if(!x.push(W))return;if(F){x.push(null);return}}catch{return}}}}return x._destroy=function(T,W){!T&&v!==null&&(T=new p),S=null,g=null,_=null,v===null?W(T):(v=W,n(M)&&a(M,T))},x}}),mc=pe((c,e)=>{le(),ue(),ce();var t=globalThis.AbortController||qt().AbortController,{codes:{ERR_INVALID_ARG_VALUE:r,ERR_INVALID_ARG_TYPE:a,ERR_MISSING_ARGS:n,ERR_OUT_OF_RANGE:i},AbortError:s}=We(),{validateAbortSignal:o,validateInteger:l,validateObject:u}=zt(),d=je().Symbol("kWeak"),p=je().Symbol("kResistStopPropagation"),{finished:y}=gt(),f=Vo(),{addAbortSignalNoValidate:m}=nr(),{isWritable:b,isNodeStream:k}=st(),{deprecate:g}=ze(),{ArrayPrototypePush:_,Boolean:S,MathFloor:v,Number:x,NumberIsNaN:E,Promise:I,PromiseReject:M,PromiseResolve:O,PromisePrototypeThen:B,Symbol:T}=je(),W=T("kEmpty"),F=T("kEof");function N(H,G){if(G!=null&&u(G,"options"),G?.signal!=null&&o(G.signal,"options.signal"),k(H)&&!b(H))throw new r("stream",H,"must be writable");let Q=f(this,H);return G!=null&&G.signal&&m(G.signal,Q),Q}function ae(H,G){if(typeof H!="function")throw new a("fn",["Function","AsyncFunction"],H);G!=null&&u(G,"options"),G?.signal!=null&&o(G.signal,"options.signal");let Q=1;G?.concurrency!=null&&(Q=v(G.concurrency));let me=Q-1;return G?.highWaterMark!=null&&(me=v(G.highWaterMark)),l(Q,"options.concurrency",1),l(me,"options.highWaterMark",0),me+=Q,(async function*(){let oe=ze().AbortSignalAny([G?.signal].filter(S)),R=this,$=[],ee={signal:oe},fe,de,ye=!1,q=0;function ge(){ye=!0,ve()}function ve(){q-=1,se()}function se(){de&&!ye&&q<Q&&$.length<me&&(de(),de=null)}async function Te(){try{for await(let h of R){if(ye)return;if(oe.aborted)throw new s;try{if(h=H(h,ee),h===W)continue;h=O(h)}catch(w){h=M(w)}q+=1,B(h,ve,ge),$.push(h),fe&&(fe(),fe=null),!ye&&($.length>=me||q>=Q)&&await new I(w=>{de=w})}$.push(F)}catch(h){let w=M(h);B(w,ve,ge),$.push(w)}finally{ye=!0,fe&&(fe(),fe=null)}}Te();try{for(;;){for(;$.length>0;){let h=await $[0];if(h===F)return;if(oe.aborted)throw new s;h!==W&&(yield h),$.shift(),se()}await new I(h=>{fe=h})}}finally{ye=!0,de&&(de(),de=null)}}).call(this)}function Y(H=void 0){return H!=null&&u(H,"options"),H?.signal!=null&&o(H.signal,"options.signal"),(async function*(){let G=0;for await(let me of this){var Q;if(H!=null&&(Q=H.signal)!==null&&Q!==void 0&&Q.aborted)throw new s({cause:H.signal.reason});yield[G++,me]}}).call(this)}async function K(H,G=void 0){for await(let Q of P.call(this,H,G))return!0;return!1}async function re(H,G=void 0){if(typeof H!="function")throw new a("fn",["Function","AsyncFunction"],H);return!await K.call(this,async(...Q)=>!await H(...Q),G)}async function D(H,G){for await(let Q of P.call(this,H,G))return Q}async function Z(H,G){if(typeof H!="function")throw new a("fn",["Function","AsyncFunction"],H);async function Q(me,oe){return await H(me,oe),W}for await(let me of ae.call(this,Q,G));}function P(H,G){if(typeof H!="function")throw new a("fn",["Function","AsyncFunction"],H);async function Q(me,oe){return await H(me,oe)?me:W}return ae.call(this,Q,G)}var J=class extends n{constructor(){super("reduce"),this.message="Reduce of an empty stream requires an initial value"}};async function be(H,G,Q){var me;if(typeof H!="function")throw new a("reducer",["Function","AsyncFunction"],H);Q!=null&&u(Q,"options"),Q?.signal!=null&&o(Q.signal,"options.signal");let oe=arguments.length>1;if(Q!=null&&(me=Q.signal)!==null&&me!==void 0&&me.aborted){let de=new s(void 0,{cause:Q.signal.reason});throw this.once("error",()=>{}),await y(this.destroy(de)),de}let R=new t,$=R.signal;if(Q!=null&&Q.signal){let de={once:!0,[d]:this,[p]:!0};Q.signal.addEventListener("abort",()=>R.abort(),de)}let ee=!1;try{for await(let de of this){var fe;if(ee=!0,Q!=null&&(fe=Q.signal)!==null&&fe!==void 0&&fe.aborted)throw new s;oe?G=await H(G,de,{signal:$}):(G=de,oe=!0)}if(!ee&&!oe)throw new J}finally{R.abort()}return G}async function te(H){H!=null&&u(H,"options"),H?.signal!=null&&o(H.signal,"options.signal");let G=[];for await(let me of this){var Q;if(H!=null&&(Q=H.signal)!==null&&Q!==void 0&&Q.aborted)throw new s(void 0,{cause:H.signal.reason});_(G,me)}return G}function we(H,G){let Q=ae.call(this,H,G);return(async function*(){for await(let me of Q)yield*me}).call(this)}function V(H){if(H=x(H),E(H))return 0;if(H<0)throw new i("number",">= 0",H);return H}function L(H,G=void 0){return G!=null&&u(G,"options"),G?.signal!=null&&o(G.signal,"options.signal"),H=V(H),(async function*(){var Q;if(G!=null&&(Q=G.signal)!==null&&Q!==void 0&&Q.aborted)throw new s;for await(let oe of this){var me;if(G!=null&&(me=G.signal)!==null&&me!==void 0&&me.aborted)throw new s;H--<=0&&(yield oe)}}).call(this)}function ne(H,G=void 0){return G!=null&&u(G,"options"),G?.signal!=null&&o(G.signal,"options.signal"),H=V(H),(async function*(){var Q;if(G!=null&&(Q=G.signal)!==null&&Q!==void 0&&Q.aborted)throw new s;for await(let oe of this){var me;if(G!=null&&(me=G.signal)!==null&&me!==void 0&&me.aborted)throw new s;if(H-- >0&&(yield oe),H<=0)return}}).call(this)}e.exports.streamReturningOperators={asIndexedPairs:g(Y,"readable.asIndexedPairs will be removed in a future version."),drop:L,filter:P,flatMap:we,map:ae,take:ne,compose:N},e.exports.promiseReturningOperators={every:re,forEach:Z,reduce:be,toArray:te,some:K,find:D}}),Go=pe((c,e)=>{le(),ue(),ce();var{ArrayPrototypePop:t,Promise:r}=je(),{isIterable:a,isNodeStream:n,isWebStream:i}=st(),{pipelineImpl:s}=ni(),{finished:o}=gt();Yo();function l(...u){return new r((d,p)=>{let y,f,m=u[u.length-1];if(m&&typeof m=="object"&&!n(m)&&!a(m)&&!i(m)){let b=t(u);y=b.signal,f=b.end}s(u,(b,k)=>{b?p(b):d(k)},{signal:y,end:f})})}e.exports={finished:o,pipeline:l}}),Yo=pe((c,e)=>{le(),ue(),ce();var{Buffer:t}=(Ue(),Pe(Ne)),{ObjectDefineProperty:r,ObjectKeys:a,ReflectApply:n}=je(),{promisify:{custom:i}}=ze(),{streamReturningOperators:s,promiseReturningOperators:o}=mc(),{codes:{ERR_ILLEGAL_CONSTRUCTOR:l}}=We(),u=Vo(),{setDefaultHighWaterMark:d,getDefaultHighWaterMark:p}=ir(),{pipeline:y}=ni(),{destroyer:f}=Mt(),m=gt(),b=Go(),k=st(),g=e.exports=ti().Stream;g.isDestroyed=k.isDestroyed,g.isDisturbed=k.isDisturbed,g.isErrored=k.isErrored,g.isReadable=k.isReadable,g.isWritable=k.isWritable,g.Readable=or();for(let S of a(s)){let v=function(...E){if(new.target)throw l();return g.Readable.from(n(x,this,E))},x=s[S];r(v,"name",{__proto__:null,value:x.name}),r(v,"length",{__proto__:null,value:x.length}),r(g.Readable.prototype,S,{__proto__:null,value:v,enumerable:!1,configurable:!0,writable:!0})}for(let S of a(o)){let v=function(...E){if(new.target)throw l();return n(x,this,E)},x=o[S];r(v,"name",{__proto__:null,value:x.name}),r(v,"length",{__proto__:null,value:x.length}),r(g.Readable.prototype,S,{__proto__:null,value:v,enumerable:!1,configurable:!0,writable:!0})}g.Writable=ri(),g.Duplex=at(),g.Transform=zo(),g.PassThrough=Ko(),g.pipeline=y;var{addAbortSignal:_}=nr();g.addAbortSignal=_,g.finished=m,g.destroy=f,g.compose=u,g.setDefaultHighWaterMark=d,g.getDefaultHighWaterMark=p,r(g,"promises",{__proto__:null,configurable:!0,enumerable:!0,get(){return b}}),r(y,i,{__proto__:null,enumerable:!0,get(){return b.pipeline}}),r(m,i,{__proto__:null,enumerable:!0,get(){return b.finished}}),g.Stream=g,g._isUint8Array=function(S){return S instanceof Uint8Array},g._uint8ArrayToBuffer=function(S){return t.from(S.buffer,S.byteOffset,S.byteLength)}}),Et=pe((c,e)=>{le(),ue(),ce();var t=Yo(),r=Go(),a=t.Readable.destroy;e.exports=t.Readable,e.exports._uint8ArrayToBuffer=t._uint8ArrayToBuffer,e.exports._isUint8Array=t._isUint8Array,e.exports.isDisturbed=t.isDisturbed,e.exports.isErrored=t.isErrored,e.exports.isReadable=t.isReadable,e.exports.Readable=t.Readable,e.exports.Writable=t.Writable,e.exports.Duplex=t.Duplex,e.exports.Transform=t.Transform,e.exports.PassThrough=t.PassThrough,e.exports.addAbortSignal=t.addAbortSignal,e.exports.finished=t.finished,e.exports.destroy=t.destroy,e.exports.destroy=a,e.exports.pipeline=t.pipeline,e.exports.compose=t.compose,Object.defineProperty(t,"promises",{configurable:!0,enumerable:!0,get(){return r}}),e.exports.Stream=t.Stream,e.exports.default=e.exports}),bc=pe((c,e)=>{le(),ue(),ce(),typeof Object.create=="function"?e.exports=function(t,r){r&&(t.super_=r,t.prototype=Object.create(r.prototype,{constructor:{value:t,enumerable:!1,writable:!0,configurable:!0}}))}:e.exports=function(t,r){if(r){t.super_=r;var a=function(){};a.prototype=r.prototype,t.prototype=new a,t.prototype.constructor=t}}}),yc=pe((c,e)=>{le(),ue(),ce();var{Buffer:t}=(Ue(),Pe(Ne)),r=Symbol.for("BufferList");function a(n){if(!(this instanceof a))return new a(n);a._init.call(this,n)}a._init=function(n){Object.defineProperty(this,r,{value:!0}),this._bufs=[],this.length=0,n&&this.append(n)},a.prototype._new=function(n){return new a(n)},a.prototype._offset=function(n){if(n===0)return[0,0];let i=0;for(let s=0;s<this._bufs.length;s++){let o=i+this._bufs[s].length;if(n<o||s===this._bufs.length-1)return[s,n-i];i=o}},a.prototype._reverseOffset=function(n){let i=n[0],s=n[1];for(let o=0;o<i;o++)s+=this._bufs[o].length;return s},a.prototype.getBuffers=function(){return this._bufs},a.prototype.get=function(n){if(n>this.length||n<0)return;let i=this._offset(n);return this._bufs[i[0]][i[1]]},a.prototype.slice=function(n,i){return typeof n=="number"&&n<0&&(n+=this.length),typeof i=="number"&&i<0&&(i+=this.length),this.copy(null,0,n,i)},a.prototype.copy=function(n,i,s,o){if((typeof s!="number"||s<0)&&(s=0),(typeof o!="number"||o>this.length)&&(o=this.length),s>=this.length||o<=0)return n||t.alloc(0);let l=!!n,u=this._offset(s),d=o-s,p=d,y=l&&i||0,f=u[1];if(s===0&&o===this.length){if(!l)return this._bufs.length===1?this._bufs[0]:t.concat(this._bufs,this.length);for(let m=0;m<this._bufs.length;m++)this._bufs[m].copy(n,y),y+=this._bufs[m].length;return n}if(p<=this._bufs[u[0]].length-f)return l?this._bufs[u[0]].copy(n,i,f,f+p):this._bufs[u[0]].slice(f,f+p);l||(n=t.allocUnsafe(d));for(let m=u[0];m<this._bufs.length;m++){let b=this._bufs[m].length-f;if(p>b)this._bufs[m].copy(n,y,f),y+=b;else{this._bufs[m].copy(n,y,f,f+p),y+=b;break}p-=b,f&&(f=0)}return n.length>y?n.slice(0,y):n},a.prototype.shallowSlice=function(n,i){if(n=n||0,i=typeof i!="number"?this.length:i,n<0&&(n+=this.length),i<0&&(i+=this.length),n===i)return this._new();let s=this._offset(n),o=this._offset(i),l=this._bufs.slice(s[0],o[0]+1);return o[1]===0?l.pop():l[l.length-1]=l[l.length-1].slice(0,o[1]),s[1]!==0&&(l[0]=l[0].slice(s[1])),this._new(l)},a.prototype.toString=function(n,i,s){return this.slice(i,s).toString(n)},a.prototype.consume=function(n){if(n=Math.trunc(n),Number.isNaN(n)||n<=0)return this;for(;this._bufs.length;)if(n>=this._bufs[0].length)n-=this._bufs[0].length,this.length-=this._bufs[0].length,this._bufs.shift();else{this._bufs[0]=this._bufs[0].slice(n),this.length-=n;break}return this},a.prototype.duplicate=function(){let n=this._new();for(let i=0;i<this._bufs.length;i++)n.append(this._bufs[i]);return n},a.prototype.append=function(n){return this._attach(n,a.prototype._appendBuffer)},a.prototype.prepend=function(n){return this._attach(n,a.prototype._prependBuffer,!0)},a.prototype._attach=function(n,i,s){if(n==null)return this;if(n.buffer)i.call(this,t.from(n.buffer,n.byteOffset,n.byteLength));else if(Array.isArray(n)){let[o,l]=s?[n.length-1,-1]:[0,1];for(let u=o;u>=0&&u<n.length;u+=l)this._attach(n[u],i,s)}else if(this._isBufferList(n)){let[o,l]=s?[n._bufs.length-1,-1]:[0,1];for(let u=o;u>=0&&u<n._bufs.length;u+=l)this._attach(n._bufs[u],i,s)}else typeof n=="number"&&(n=n.toString()),i.call(this,t.from(n));return this},a.prototype._appendBuffer=function(n){this._bufs.push(n),this.length+=n.length},a.prototype._prependBuffer=function(n){this._bufs.unshift(n),this.length+=n.length},a.prototype.indexOf=function(n,i,s){if(s===void 0&&typeof i=="string"&&(s=i,i=void 0),typeof n=="function"||Array.isArray(n))throw new TypeError('The "value" argument must be one of type string, Buffer, BufferList, or Uint8Array.');if(typeof n=="number"?n=t.from([n]):typeof n=="string"?n=t.from(n,s):this._isBufferList(n)?n=n.slice():Array.isArray(n.buffer)?n=t.from(n.buffer,n.byteOffset,n.byteLength):t.isBuffer(n)||(n=t.from(n)),i=Number(i||0),isNaN(i)&&(i=0),i<0&&(i=this.length+i),i<0&&(i=0),n.length===0)return i>this.length?this.length:i;let o=this._offset(i),l=o[0],u=o[1];for(;l<this._bufs.length;l++){let d=this._bufs[l];for(;u<d.length;)if(d.length-u>=n.length){let p=d.indexOf(n,u);if(p!==-1)return this._reverseOffset([l,p]);u=d.length-n.length+1}else{let p=this._reverseOffset([l,u]);if(this._match(p,n))return p;u++}u=0}return-1},a.prototype._match=function(n,i){if(this.length-n<i.length)return!1;for(let s=0;s<i.length;s++)if(this.get(n+s)!==i[s])return!1;return!0},(function(){let n={readDoubleBE:8,readDoubleLE:8,readFloatBE:4,readFloatLE:4,readBigInt64BE:8,readBigInt64LE:8,readBigUInt64BE:8,readBigUInt64LE:8,readInt32BE:4,readInt32LE:4,readUInt32BE:4,readUInt32LE:4,readInt16BE:2,readInt16LE:2,readUInt16BE:2,readUInt16LE:2,readInt8:1,readUInt8:1,readIntBE:null,readIntLE:null,readUIntBE:null,readUIntLE:null};for(let i in n)(function(s){n[s]===null?a.prototype[s]=function(o,l){return this.slice(o,o+l)[s](0,l)}:a.prototype[s]=function(o=0){return this.slice(o,o+n[s])[s](0)}})(i)})(),a.prototype._isBufferList=function(n){return n instanceof a||a.isBufferList(n)},a.isBufferList=function(n){return n!=null&&n[r]},e.exports=a}),vc=pe((c,e)=>{le(),ue(),ce();var t=Et().Duplex,r=bc(),a=yc();function n(i){if(!(this instanceof n))return new n(i);if(typeof i=="function"){this._callback=i;let s=(function(o){this._callback&&(this._callback(o),this._callback=null)}).bind(this);this.on("pipe",function(o){o.on("error",s)}),this.on("unpipe",function(o){o.removeListener("error",s)}),i=null}a._init.call(this,i),t.call(this)}r(n,t),Object.assign(n.prototype,a.prototype),n.prototype._new=function(i){return new n(i)},n.prototype._write=function(i,s,o){this._appendBuffer(i),typeof o=="function"&&o()},n.prototype._read=function(i){if(!this.length)return this.push(null);i=Math.min(i,this.length),this.push(this.slice(0,i)),this.consume(i)},n.prototype.end=function(i){t.prototype.end.call(this,i),this._callback&&(this._callback(null,this.slice()),this._callback=null)},n.prototype._destroy=function(i,s){this._bufs.length=0,this.length=0,s(i)},n.prototype._isBufferList=function(i){return i instanceof n||i instanceof a||n.isBufferList(i)},n.isBufferList=a.isBufferList,e.exports=n,e.exports.BufferListStream=n,e.exports.BufferList=a}),wc=pe((c,e)=>{le(),ue(),ce();var t=class{constructor(){this.cmd=null,this.retain=!1,this.qos=0,this.dup=!1,this.length=-1,this.topic=null,this.payload=null}};e.exports=t}),Qo=pe((c,e)=>{le(),ue(),ce();var t=e.exports,{Buffer:r}=(Ue(),Pe(Ne));t.types={0:"reserved",1:"connect",2:"connack",3:"publish",4:"puback",5:"pubrec",6:"pubrel",7:"pubcomp",8:"subscribe",9:"suback",10:"unsubscribe",11:"unsuback",12:"pingreq",13:"pingresp",14:"disconnect",15:"auth"},t.requiredHeaderFlags={1:0,2:0,4:0,5:0,6:2,7:0,8:2,9:0,10:2,11:0,12:0,13:0,14:0,15:0},t.requiredHeaderFlagsErrors={};for(let n in t.requiredHeaderFlags){let i=t.requiredHeaderFlags[n];t.requiredHeaderFlagsErrors[n]="Invalid header flag bits, must be 0x"+i.toString(16)+" for "+t.types[n]+" packet"}t.codes={};for(let n in t.types){let i=t.types[n];t.codes[i]=n}t.CMD_SHIFT=4,t.CMD_MASK=240,t.DUP_MASK=8,t.QOS_MASK=3,t.QOS_SHIFT=1,t.RETAIN_MASK=1,t.VARBYTEINT_MASK=127,t.VARBYTEINT_FIN_MASK=128,t.VARBYTEINT_MAX=268435455,t.SESSIONPRESENT_MASK=1,t.SESSIONPRESENT_HEADER=r.from([t.SESSIONPRESENT_MASK]),t.CONNACK_HEADER=r.from([t.codes.connack<<t.CMD_SHIFT]),t.USERNAME_MASK=128,t.PASSWORD_MASK=64,t.WILL_RETAIN_MASK=32,t.WILL_QOS_MASK=24,t.WILL_QOS_SHIFT=3,t.WILL_FLAG_MASK=4,t.CLEAN_SESSION_MASK=2,t.CONNECT_HEADER=r.from([t.codes.connect<<t.CMD_SHIFT]),t.properties={sessionExpiryInterval:17,willDelayInterval:24,receiveMaximum:33,maximumPacketSize:39,topicAliasMaximum:34,requestResponseInformation:25,requestProblemInformation:23,userProperties:38,authenticationMethod:21,authenticationData:22,payloadFormatIndicator:1,messageExpiryInterval:2,contentType:3,responseTopic:8,correlationData:9,maximumQoS:36,retainAvailable:37,assignedClientIdentifier:18,reasonString:31,wildcardSubscriptionAvailable:40,subscriptionIdentifiersAvailable:41,sharedSubscriptionAvailable:42,serverKeepAlive:19,responseInformation:26,serverReference:28,topicAlias:35,subscriptionIdentifier:11},t.propertiesCodes={};for(let n in t.properties){let i=t.properties[n];t.propertiesCodes[i]=n}t.propertiesTypes={sessionExpiryInterval:"int32",willDelayInterval:"int32",receiveMaximum:"int16",maximumPacketSize:"int32",topicAliasMaximum:"int16",requestResponseInformation:"byte",requestProblemInformation:"byte",userProperties:"pair",authenticationMethod:"string",authenticationData:"binary",payloadFormatIndicator:"byte",messageExpiryInterval:"int32",contentType:"string",responseTopic:"string",correlationData:"binary",maximumQoS:"int8",retainAvailable:"byte",assignedClientIdentifier:"string",reasonString:"string",wildcardSubscriptionAvailable:"byte",subscriptionIdentifiersAvailable:"byte",sharedSubscriptionAvailable:"byte",serverKeepAlive:"int16",responseInformation:"string",serverReference:"string",topicAlias:"int16",subscriptionIdentifier:"var"};function a(n){return[0,1,2].map(i=>[0,1].map(s=>[0,1].map(o=>{let l=r.alloc(1);return l.writeUInt8(t.codes[n]<<t.CMD_SHIFT|(s?t.DUP_MASK:0)|i<<t.QOS_SHIFT|o,0,!0),l})))}t.PUBLISH_HEADER=a("publish"),t.SUBSCRIBE_HEADER=a("subscribe"),t.SUBSCRIBE_OPTIONS_QOS_MASK=3,t.SUBSCRIBE_OPTIONS_NL_MASK=1,t.SUBSCRIBE_OPTIONS_NL_SHIFT=2,t.SUBSCRIBE_OPTIONS_RAP_MASK=1,t.SUBSCRIBE_OPTIONS_RAP_SHIFT=3,t.SUBSCRIBE_OPTIONS_RH_MASK=3,t.SUBSCRIBE_OPTIONS_RH_SHIFT=4,t.SUBSCRIBE_OPTIONS_RH=[0,16,32],t.SUBSCRIBE_OPTIONS_NL=4,t.SUBSCRIBE_OPTIONS_RAP=8,t.SUBSCRIBE_OPTIONS_QOS=[0,1,2],t.UNSUBSCRIBE_HEADER=a("unsubscribe"),t.ACKS={unsuback:a("unsuback"),puback:a("puback"),pubcomp:a("pubcomp"),pubrel:a("pubrel"),pubrec:a("pubrec")},t.SUBACK_HEADER=r.from([t.codes.suback<<t.CMD_SHIFT]),t.VERSION3=r.from([3]),t.VERSION4=r.from([4]),t.VERSION5=r.from([5]),t.VERSION131=r.from([131]),t.VERSION132=r.from([132]),t.QOS=[0,1,2].map(n=>r.from([n])),t.EMPTY={pingreq:r.from([t.codes.pingreq<<4,0]),pingresp:r.from([t.codes.pingresp<<4,0]),disconnect:r.from([t.codes.disconnect<<4,0])},t.MQTT5_PUBACK_PUBREC_CODES={0:"Success",16:"No matching subscribers",128:"Unspecified error",131:"Implementation specific error",135:"Not authorized",144:"Topic Name invalid",145:"Packet identifier in use",151:"Quota exceeded",153:"Payload format invalid"},t.MQTT5_PUBREL_PUBCOMP_CODES={0:"Success",146:"Packet Identifier not found"},t.MQTT5_SUBACK_CODES={0:"Granted QoS 0",1:"Granted QoS 1",2:"Granted QoS 2",128:"Unspecified error",131:"Implementation specific error",135:"Not authorized",143:"Topic Filter invalid",145:"Packet Identifier in use",151:"Quota exceeded",158:"Shared Subscriptions not supported",161:"Subscription Identifiers not supported",162:"Wildcard Subscriptions not supported"},t.MQTT5_UNSUBACK_CODES={0:"Success",17:"No subscription existed",128:"Unspecified error",131:"Implementation specific error",135:"Not authorized",143:"Topic Filter invalid",145:"Packet Identifier in use"},t.MQTT5_DISCONNECT_CODES={0:"Normal disconnection",4:"Disconnect with Will Message",128:"Unspecified error",129:"Malformed Packet",130:"Protocol Error",131:"Implementation specific error",135:"Not authorized",137:"Server busy",139:"Server shutting down",141:"Keep Alive timeout",142:"Session taken over",143:"Topic Filter invalid",144:"Topic Name invalid",147:"Receive Maximum exceeded",148:"Topic Alias invalid",149:"Packet too large",150:"Message rate too high",151:"Quota exceeded",152:"Administrative action",153:"Payload format invalid",154:"Retain not supported",155:"QoS not supported",156:"Use another server",157:"Server moved",158:"Shared Subscriptions not supported",159:"Connection rate exceeded",160:"Maximum connect time",161:"Subscription Identifiers not supported",162:"Wildcard Subscriptions not supported"},t.MQTT5_AUTH_CODES={0:"Success",24:"Continue authentication",25:"Re-authenticate"}}),_c=pe((c,e)=>{le(),ue(),ce();var t=1e3,r=t*60,a=r*60,n=a*24,i=n*7,s=n*365.25;e.exports=function(p,y){y=y||{};var f=typeof p;if(f==="string"&&p.length>0)return o(p);if(f==="number"&&isFinite(p))return y.long?u(p):l(p);throw new Error("val is not a non-empty string or a valid number. val="+JSON.stringify(p))};function o(p){if(p=String(p),!(p.length>100)){var y=/^(-?(?:\d+)?\.?\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)?$/i.exec(p);if(y){var f=parseFloat(y[1]),m=(y[2]||"ms").toLowerCase();switch(m){case"years":case"year":case"yrs":case"yr":case"y":return f*s;case"weeks":case"week":case"w":return f*i;case"days":case"day":case"d":return f*n;case"hours":case"hour":case"hrs":case"hr":case"h":return f*a;case"minutes":case"minute":case"mins":case"min":case"m":return f*r;case"seconds":case"second":case"secs":case"sec":case"s":return f*t;case"milliseconds":case"millisecond":case"msecs":case"msec":case"ms":return f;default:return}}}}function l(p){var y=Math.abs(p);return y>=n?Math.round(p/n)+"d":y>=a?Math.round(p/a)+"h":y>=r?Math.round(p/r)+"m":y>=t?Math.round(p/t)+"s":p+"ms"}function u(p){var y=Math.abs(p);return y>=n?d(p,y,n,"day"):y>=a?d(p,y,a,"hour"):y>=r?d(p,y,r,"minute"):y>=t?d(p,y,t,"second"):p+" ms"}function d(p,y,f,m){var b=y>=f*1.5;return Math.round(p/f)+" "+m+(b?"s":"")}}),kc=pe((c,e)=>{le(),ue(),ce();function t(r){n.debug=n,n.default=n,n.coerce=d,n.disable=l,n.enable=s,n.enabled=u,n.humanize=_c(),n.destroy=p,Object.keys(r).forEach(y=>{n[y]=r[y]}),n.names=[],n.skips=[],n.formatters={};function a(y){let f=0;for(let m=0;m<y.length;m++)f=(f<<5)-f+y.charCodeAt(m),f|=0;return n.colors[Math.abs(f)%n.colors.length]}n.selectColor=a;function n(y){let f,m=null,b,k;function g(..._){if(!g.enabled)return;let S=g,v=Number(new Date),x=v-(f||v);S.diff=x,S.prev=f,S.curr=v,f=v,_[0]=n.coerce(_[0]),typeof _[0]!="string"&&_.unshift("%O");let E=0;_[0]=_[0].replace(/%([a-zA-Z%])/g,(I,M)=>{if(I==="%%")return"%";E++;let O=n.formatters[M];if(typeof O=="function"){let B=_[E];I=O.call(S,B),_.splice(E,1),E--}return I}),n.formatArgs.call(S,_),(S.log||n.log).apply(S,_)}return g.namespace=y,g.useColors=n.useColors(),g.color=n.selectColor(y),g.extend=i,g.destroy=n.destroy,Object.defineProperty(g,"enabled",{enumerable:!0,configurable:!1,get:()=>m!==null?m:(b!==n.namespaces&&(b=n.namespaces,k=n.enabled(y)),k),set:_=>{m=_}}),typeof n.init=="function"&&n.init(g),g}function i(y,f){let m=n(this.namespace+(typeof f>"u"?":":f)+y);return m.log=this.log,m}function s(y){n.save(y),n.namespaces=y,n.names=[],n.skips=[];let f=(typeof y=="string"?y:"").trim().replace(/\s+/g,",").split(",").filter(Boolean);for(let m of f)m[0]==="-"?n.skips.push(m.slice(1)):n.names.push(m)}function o(y,f){let m=0,b=0,k=-1,g=0;for(;m<y.length;)if(b<f.length&&(f[b]===y[m]||f[b]==="*"))f[b]==="*"?(k=b,g=m,b++):(m++,b++);else if(k!==-1)b=k+1,g++,m=g;else return!1;for(;b<f.length&&f[b]==="*";)b++;return b===f.length}function l(){let y=[...n.names,...n.skips.map(f=>"-"+f)].join(",");return n.enable(""),y}function u(y){for(let f of n.skips)if(o(y,f))return!1;for(let f of n.names)if(o(y,f))return!0;return!1}function d(y){return y instanceof Error?y.stack||y.message:y}function p(){console.warn("Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.")}return n.enable(n.load()),n}e.exports=t}),lt=pe((c,e)=>{le(),ue(),ce(),c.formatArgs=r,c.save=a,c.load=n,c.useColors=t,c.storage=i(),c.destroy=(()=>{let o=!1;return()=>{o||(o=!0,console.warn("Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`."))}})(),c.colors=["#0000CC","#0000FF","#0033CC","#0033FF","#0066CC","#0066FF","#0099CC","#0099FF","#00CC00","#00CC33","#00CC66","#00CC99","#00CCCC","#00CCFF","#3300CC","#3300FF","#3333CC","#3333FF","#3366CC","#3366FF","#3399CC","#3399FF","#33CC00","#33CC33","#33CC66","#33CC99","#33CCCC","#33CCFF","#6600CC","#6600FF","#6633CC","#6633FF","#66CC00","#66CC33","#9900CC","#9900FF","#9933CC","#9933FF","#99CC00","#99CC33","#CC0000","#CC0033","#CC0066","#CC0099","#CC00CC","#CC00FF","#CC3300","#CC3333","#CC3366","#CC3399","#CC33CC","#CC33FF","#CC6600","#CC6633","#CC9900","#CC9933","#CCCC00","#CCCC33","#FF0000","#FF0033","#FF0066","#FF0099","#FF00CC","#FF00FF","#FF3300","#FF3333","#FF3366","#FF3399","#FF33CC","#FF33FF","#FF6600","#FF6633","#FF9900","#FF9933","#FFCC00","#FFCC33"];function t(){if(typeof window<"u"&&window.process&&(window.process.type==="renderer"||window.process.__nwjs))return!0;if(typeof navigator<"u"&&navigator.userAgent&&navigator.userAgent.toLowerCase().match(/(edge|trident)\/(\d+)/))return!1;let o;return typeof document<"u"&&document.documentElement&&document.documentElement.style&&document.documentElement.style.WebkitAppearance||typeof window<"u"&&window.console&&(window.console.firebug||window.console.exception&&window.console.table)||typeof navigator<"u"&&navigator.userAgent&&(o=navigator.userAgent.toLowerCase().match(/firefox\/(\d+)/))&&parseInt(o[1],10)>=31||typeof navigator<"u"&&navigator.userAgent&&navigator.userAgent.toLowerCase().match(/applewebkit\/(\d+)/)}function r(o){if(o[0]=(this.useColors?"%c":"")+this.namespace+(this.useColors?" %c":" ")+o[0]+(this.useColors?"%c ":" ")+"+"+e.exports.humanize(this.diff),!this.useColors)return;let l="color: "+this.color;o.splice(1,0,l,"color: inherit");let u=0,d=0;o[0].replace(/%[a-zA-Z%]/g,p=>{p!=="%%"&&(u++,p==="%c"&&(d=u))}),o.splice(d,0,l)}c.log=console.debug||console.log||(()=>{});function a(o){try{o?c.storage.setItem("debug",o):c.storage.removeItem("debug")}catch{}}function n(){let o;try{o=c.storage.getItem("debug")||c.storage.getItem("DEBUG")}catch{}return!o&&typeof Me<"u"&&"env"in Me&&(o=Me.env.DEBUG),o}function i(){try{return localStorage}catch{}}e.exports=kc()(c);var{formatters:s}=e.exports;s.j=function(o){try{return JSON.stringify(o)}catch(l){return"[UnexpectedJSONParseError]: "+l.message}}}),Sc=pe((c,e)=>{le(),ue(),ce();var t=vc(),{EventEmitter:r}=(kt(),Pe(pt)),a=wc(),n=Qo(),i=lt()("mqtt-packet:parser"),s=class ho extends r{constructor(){super(),this.parser=this.constructor.parser}static parser(l){return this instanceof ho?(this.settings=l||{},this._states=["_parseHeader","_parseLength","_parsePayload","_newPacket"],this._resetState(),this):new ho().parser(l)}_resetState(){i("_resetState: resetting packet, error, _list, and _stateCounter"),this.packet=new a,this.error=null,this._list=t(),this._stateCounter=0}parse(l){for(this.error&&this._resetState(),this._list.append(l),i("parse: current state: %s",this._states[this._stateCounter]);(this.packet.length!==-1||this._list.length>0)&&this[this._states[this._stateCounter]]()&&!this.error;)this._stateCounter++,i("parse: state complete. _stateCounter is now: %d",this._stateCounter),i("parse: packet.length: %d, buffer list length: %d",this.packet.length,this._list.length),this._stateCounter>=this._states.length&&(this._stateCounter=0);return i("parse: exited while loop. packet: %d, buffer list length: %d",this.packet.length,this._list.length),this._list.length}_parseHeader(){let l=this._list.readUInt8(0),u=l>>n.CMD_SHIFT;this.packet.cmd=n.types[u];let d=l&15,p=n.requiredHeaderFlags[u];return p!=null&&d!==p?this._emitError(new Error(n.requiredHeaderFlagsErrors[u])):(this.packet.retain=(l&n.RETAIN_MASK)!==0,this.packet.qos=l>>n.QOS_SHIFT&n.QOS_MASK,this.packet.qos>2?this._emitError(new Error("Packet must not have both QoS bits set to 1")):(this.packet.dup=(l&n.DUP_MASK)!==0,i("_parseHeader: packet: %o",this.packet),this._list.consume(1),!0))}_parseLength(){let l=this._parseVarByteNum(!0);return l&&(this.packet.length=l.value,this._list.consume(l.bytes)),i("_parseLength %d",l.value),!!l}_parsePayload(){i("_parsePayload: payload %O",this._list);let l=!1;if(this.packet.length===0||this._list.length>=this.packet.length){switch(this._pos=0,this.packet.cmd){case"connect":this._parseConnect();break;case"connack":this._parseConnack();break;case"publish":this._parsePublish();break;case"puback":case"pubrec":case"pubrel":case"pubcomp":this._parseConfirmation();break;case"subscribe":this._parseSubscribe();break;case"suback":this._parseSuback();break;case"unsubscribe":this._parseUnsubscribe();break;case"unsuback":this._parseUnsuback();break;case"pingreq":case"pingresp":break;case"disconnect":this._parseDisconnect();break;case"auth":this._parseAuth();break;default:this._emitError(new Error("Not supported"))}l=!0}return i("_parsePayload complete result: %s",l),l}_parseConnect(){i("_parseConnect");let l,u,d,p,y={},f=this.packet,m=this._parseString();if(m===null)return this._emitError(new Error("Cannot parse protocolId"));if(m!=="MQTT"&&m!=="MQIsdp")return this._emitError(new Error("Invalid protocolId"));if(f.protocolId=m,this._pos>=this._list.length)return this._emitError(new Error("Packet too short"));if(f.protocolVersion=this._list.readUInt8(this._pos),f.protocolVersion>=128&&(f.bridgeMode=!0,f.protocolVersion=f.protocolVersion-128),f.protocolVersion!==3&&f.protocolVersion!==4&&f.protocolVersion!==5)return this._emitError(new Error("Invalid protocol version"));if(this._pos++,this._pos>=this._list.length)return this._emitError(new Error("Packet too short"));if(this._list.readUInt8(this._pos)&1)return this._emitError(new Error("Connect flag bit 0 must be 0, but got 1"));y.username=this._list.readUInt8(this._pos)&n.USERNAME_MASK,y.password=this._list.readUInt8(this._pos)&n.PASSWORD_MASK,y.will=this._list.readUInt8(this._pos)&n.WILL_FLAG_MASK;let b=!!(this._list.readUInt8(this._pos)&n.WILL_RETAIN_MASK),k=(this._list.readUInt8(this._pos)&n.WILL_QOS_MASK)>>n.WILL_QOS_SHIFT;if(y.will)f.will={},f.will.retain=b,f.will.qos=k;else{if(b)return this._emitError(new Error("Will Retain Flag must be set to zero when Will Flag is set to 0"));if(k)return this._emitError(new Error("Will QoS must be set to zero when Will Flag is set to 0"))}if(f.clean=(this._list.readUInt8(this._pos)&n.CLEAN_SESSION_MASK)!==0,this._pos++,f.keepalive=this._parseNum(),f.keepalive===-1)return this._emitError(new Error("Packet too short"));if(f.protocolVersion===5){let _=this._parseProperties();Object.getOwnPropertyNames(_).length&&(f.properties=_)}let g=this._parseString();if(g===null)return this._emitError(new Error("Packet too short"));if(f.clientId=g,i("_parseConnect: packet.clientId: %s",f.clientId),y.will){if(f.protocolVersion===5){let _=this._parseProperties();Object.getOwnPropertyNames(_).length&&(f.will.properties=_)}if(l=this._parseString(),l===null)return this._emitError(new Error("Cannot parse will topic"));if(f.will.topic=l,i("_parseConnect: packet.will.topic: %s",f.will.topic),u=this._parseBuffer(),u===null)return this._emitError(new Error("Cannot parse will payload"));f.will.payload=u,i("_parseConnect: packet.will.paylaod: %s",f.will.payload)}if(y.username){if(p=this._parseString(),p===null)return this._emitError(new Error("Cannot parse username"));f.username=p,i("_parseConnect: packet.username: %s",f.username)}if(y.password){if(d=this._parseBuffer(),d===null)return this._emitError(new Error("Cannot parse password"));f.password=d}return this.settings=f,i("_parseConnect: complete"),f}_parseConnack(){i("_parseConnack");let l=this.packet;if(this._list.length<1)return null;let u=this._list.readUInt8(this._pos++);if(u>1)return this._emitError(new Error("Invalid connack flags, bits 7-1 must be set to 0"));if(l.sessionPresent=!!(u&n.SESSIONPRESENT_MASK),this.settings.protocolVersion===5)this._list.length>=2?l.reasonCode=this._list.readUInt8(this._pos++):l.reasonCode=0;else{if(this._list.length<2)return null;l.returnCode=this._list.readUInt8(this._pos++)}if(l.returnCode===-1||l.reasonCode===-1)return this._emitError(new Error("Cannot parse return code"));if(this.settings.protocolVersion===5){let d=this._parseProperties();Object.getOwnPropertyNames(d).length&&(l.properties=d)}i("_parseConnack: complete")}_parsePublish(){i("_parsePublish");let l=this.packet;if(l.topic=this._parseString(),l.topic===null)return this._emitError(new Error("Cannot parse topic"));if(!(l.qos>0&&!this._parseMessageId())){if(this.settings.protocolVersion===5){let u=this._parseProperties();Object.getOwnPropertyNames(u).length&&(l.properties=u)}l.payload=this._list.slice(this._pos,l.length),i("_parsePublish: payload from buffer list: %o",l.payload)}}_parseSubscribe(){i("_parseSubscribe");let l=this.packet,u,d,p,y,f,m,b;if(l.subscriptions=[],!!this._parseMessageId()){if(this.settings.protocolVersion===5){let k=this._parseProperties();Object.getOwnPropertyNames(k).length&&(l.properties=k)}if(l.length<=0)return this._emitError(new Error("Malformed subscribe, no payload specified"));for(;this._pos<l.length;){if(u=this._parseString(),u===null)return this._emitError(new Error("Cannot parse topic"));if(this._pos>=l.length)return this._emitError(new Error("Malformed Subscribe Payload"));if(d=this._parseByte(),this.settings.protocolVersion===5){if(d&192)return this._emitError(new Error("Invalid subscribe topic flag bits, bits 7-6 must be 0"))}else if(d&252)return this._emitError(new Error("Invalid subscribe topic flag bits, bits 7-2 must be 0"));if(p=d&n.SUBSCRIBE_OPTIONS_QOS_MASK,p>2)return this._emitError(new Error("Invalid subscribe QoS, must be <= 2"));if(m=(d>>n.SUBSCRIBE_OPTIONS_NL_SHIFT&n.SUBSCRIBE_OPTIONS_NL_MASK)!==0,f=(d>>n.SUBSCRIBE_OPTIONS_RAP_SHIFT&n.SUBSCRIBE_OPTIONS_RAP_MASK)!==0,y=d>>n.SUBSCRIBE_OPTIONS_RH_SHIFT&n.SUBSCRIBE_OPTIONS_RH_MASK,y>2)return this._emitError(new Error("Invalid retain handling, must be <= 2"));b={topic:u,qos:p},this.settings.protocolVersion===5?(b.nl=m,b.rap=f,b.rh=y):this.settings.bridgeMode&&(b.rh=0,b.rap=!0,b.nl=!0),i("_parseSubscribe: push subscription `%s` to subscription",b),l.subscriptions.push(b)}}}_parseSuback(){i("_parseSuback");let l=this.packet;if(this.packet.granted=[],!!this._parseMessageId()){if(this.settings.protocolVersion===5){let u=this._parseProperties();Object.getOwnPropertyNames(u).length&&(l.properties=u)}if(l.length<=0)return this._emitError(new Error("Malformed suback, no payload specified"));for(;this._pos<this.packet.length;){let u=this._list.readUInt8(this._pos++);if(this.settings.protocolVersion===5){if(!n.MQTT5_SUBACK_CODES[u])return this._emitError(new Error("Invalid suback code"))}else if(u>2&&u!==128)return this._emitError(new Error("Invalid suback QoS, must be 0, 1, 2 or 128"));this.packet.granted.push(u)}}}_parseUnsubscribe(){i("_parseUnsubscribe");let l=this.packet;if(l.unsubscriptions=[],!!this._parseMessageId()){if(this.settings.protocolVersion===5){let u=this._parseProperties();Object.getOwnPropertyNames(u).length&&(l.properties=u)}if(l.length<=0)return this._emitError(new Error("Malformed unsubscribe, no payload specified"));for(;this._pos<l.length;){let u=this._parseString();if(u===null)return this._emitError(new Error("Cannot parse topic"));i("_parseUnsubscribe: push topic `%s` to unsubscriptions",u),l.unsubscriptions.push(u)}}}_parseUnsuback(){i("_parseUnsuback");let l=this.packet;if(!this._parseMessageId())return this._emitError(new Error("Cannot parse messageId"));if((this.settings.protocolVersion===3||this.settings.protocolVersion===4)&&l.length!==2)return this._emitError(new Error("Malformed unsuback, payload length must be 2"));if(l.length<=0)return this._emitError(new Error("Malformed unsuback, no payload specified"));if(this.settings.protocolVersion===5){let u=this._parseProperties();for(Object.getOwnPropertyNames(u).length&&(l.properties=u),l.granted=[];this._pos<this.packet.length;){let d=this._list.readUInt8(this._pos++);if(!n.MQTT5_UNSUBACK_CODES[d])return this._emitError(new Error("Invalid unsuback code"));this.packet.granted.push(d)}}}_parseConfirmation(){i("_parseConfirmation: packet.cmd: `%s`",this.packet.cmd);let l=this.packet;if(this._parseMessageId(),this.settings.protocolVersion===5){if(l.length>2){switch(l.reasonCode=this._parseByte(),this.packet.cmd){case"puback":case"pubrec":if(!n.MQTT5_PUBACK_PUBREC_CODES[l.reasonCode])return this._emitError(new Error("Invalid "+this.packet.cmd+" reason code"));break;case"pubrel":case"pubcomp":if(!n.MQTT5_PUBREL_PUBCOMP_CODES[l.reasonCode])return this._emitError(new Error("Invalid "+this.packet.cmd+" reason code"));break}i("_parseConfirmation: packet.reasonCode `%d`",l.reasonCode)}else l.reasonCode=0;if(l.length>3){let u=this._parseProperties();Object.getOwnPropertyNames(u).length&&(l.properties=u)}}return!0}_parseDisconnect(){let l=this.packet;if(i("_parseDisconnect"),this.settings.protocolVersion===5){this._list.length>0?(l.reasonCode=this._parseByte(),n.MQTT5_DISCONNECT_CODES[l.reasonCode]||this._emitError(new Error("Invalid disconnect reason code"))):l.reasonCode=0;let u=this._parseProperties();Object.getOwnPropertyNames(u).length&&(l.properties=u)}return i("_parseDisconnect result: true"),!0}_parseAuth(){i("_parseAuth");let l=this.packet;if(this.settings.protocolVersion!==5)return this._emitError(new Error("Not supported auth packet for this version MQTT"));if(l.reasonCode=this._parseByte(),!n.MQTT5_AUTH_CODES[l.reasonCode])return this._emitError(new Error("Invalid auth reason code"));let u=this._parseProperties();return Object.getOwnPropertyNames(u).length&&(l.properties=u),i("_parseAuth: result: true"),!0}_parseMessageId(){let l=this.packet;return l.messageId=this._parseNum(),l.messageId===null?(this._emitError(new Error("Cannot parse messageId")),!1):(i("_parseMessageId: packet.messageId %d",l.messageId),!0)}_parseString(l){let u=this._parseNum(),d=u+this._pos;if(u===-1||d>this._list.length||d>this.packet.length)return null;let p=this._list.toString("utf8",this._pos,d);return this._pos+=u,i("_parseString: result: %s",p),p}_parseStringPair(){return i("_parseStringPair"),{name:this._parseString(),value:this._parseString()}}_parseBuffer(){let l=this._parseNum(),u=l+this._pos;if(l===-1||u>this._list.length||u>this.packet.length)return null;let d=this._list.slice(this._pos,u);return this._pos+=l,i("_parseBuffer: result: %o",d),d}_parseNum(){if(this._list.length-this._pos<2)return-1;let l=this._list.readUInt16BE(this._pos);return this._pos+=2,i("_parseNum: result: %s",l),l}_parse4ByteNum(){if(this._list.length-this._pos<4)return-1;let l=this._list.readUInt32BE(this._pos);return this._pos+=4,i("_parse4ByteNum: result: %s",l),l}_parseVarByteNum(l){i("_parseVarByteNum");let u=4,d=0,p=1,y=0,f=!1,m,b=this._pos?this._pos:0;for(;d<u&&b+d<this._list.length;){if(m=this._list.readUInt8(b+d++),y+=p*(m&n.VARBYTEINT_MASK),p*=128,(m&n.VARBYTEINT_FIN_MASK)===0){f=!0;break}if(this._list.length<=d)break}return!f&&d===u&&this._list.length>=d&&this._emitError(new Error("Invalid variable byte integer")),b&&(this._pos+=d),f?l?f={bytes:d,value:y}:f=y:f=!1,i("_parseVarByteNum: result: %o",f),f}_parseByte(){let l;return this._pos<this._list.length&&(l=this._list.readUInt8(this._pos),this._pos++),i("_parseByte: result: %o",l),l}_parseByType(l){switch(i("_parseByType: type: %s",l),l){case"byte":return this._parseByte()!==0;case"int8":return this._parseByte();case"int16":return this._parseNum();case"int32":return this._parse4ByteNum();case"var":return this._parseVarByteNum();case"string":return this._parseString();case"pair":return this._parseStringPair();case"binary":return this._parseBuffer()}}_parseProperties(){i("_parseProperties");let l=this._parseVarByteNum(),u=this._pos+l,d={};for(;this._pos<u;){let p=this._parseByte();if(!p)return this._emitError(new Error("Cannot parse property code type")),!1;let y=n.propertiesCodes[p];if(!y)return this._emitError(new Error("Unknown property")),!1;if(y==="userProperties"){d[y]||(d[y]=Object.create(null));let f=this._parseByType(n.propertiesTypes[y]);if(d[y][f.name])if(Array.isArray(d[y][f.name]))d[y][f.name].push(f.value);else{let m=d[y][f.name];d[y][f.name]=[m],d[y][f.name].push(f.value)}else d[y][f.name]=f.value;continue}d[y]?Array.isArray(d[y])?d[y].push(this._parseByType(n.propertiesTypes[y])):(d[y]=[d[y]],d[y].push(this._parseByType(n.propertiesTypes[y]))):d[y]=this._parseByType(n.propertiesTypes[y])}return d}_newPacket(){return i("_newPacket"),this.packet&&(this._list.consume(this.packet.length),i("_newPacket: parser emit packet: packet.cmd: %s, packet.payload: %s, packet.length: %d",this.packet.cmd,this.packet.payload,this.packet.length),this.emit("packet",this.packet)),i("_newPacket: new packet"),this.packet=new a,this._pos=0,!0}_emitError(l){i("_emitError",l),this.error=l,this.emit("error",l)}};e.exports=s}),Ec=pe((c,e)=>{le(),ue(),ce();var{Buffer:t}=(Ue(),Pe(Ne)),r=65536,a={},n=t.isBuffer(t.from([1,2]).subarray(0,1));function i(u){let d=t.allocUnsafe(2);return d.writeUInt8(u>>8,0),d.writeUInt8(u&255,1),d}function s(){for(let u=0;u<r;u++)a[u]=i(u)}function o(u){let d=0,p=0,y=t.allocUnsafe(4);do d=u%128|0,u=u/128|0,u>0&&(d=d|128),y.writeUInt8(d,p++);while(u>0&&p<4);return u>0&&(p=0),n?y.subarray(0,p):y.slice(0,p)}function l(u){let d=t.allocUnsafe(4);return d.writeUInt32BE(u,0),d}e.exports={cache:a,generateCache:s,generateNumber:i,genBufVariableByteInt:o,generate4ByteBuffer:l}}),xc=pe((c,e)=>{le(),ue(),ce(),typeof Me>"u"||!Me.version||Me.version.indexOf("v0.")===0||Me.version.indexOf("v1.")===0&&Me.version.indexOf("v1.8.")!==0?e.exports={nextTick:t}:e.exports=Me;function t(r,a,n,i){if(typeof r!="function")throw new TypeError('"callback" argument must be a function');var s=arguments.length,o,l;switch(s){case 0:case 1:return Me.nextTick(r);case 2:return Me.nextTick(function(){r.call(null,a)});case 3:return Me.nextTick(function(){r.call(null,a,n)});case 4:return Me.nextTick(function(){r.call(null,a,n,i)});default:for(o=new Array(s-1),l=0;l<o.length;)o[l++]=arguments[l];return Me.nextTick(function(){r.apply(null,o)})}}}),Jo=pe((c,e)=>{le(),ue(),ce();var t=Qo(),{Buffer:r}=(Ue(),Pe(Ne)),a=r.allocUnsafe(0),n=r.from([0]),i=Ec(),s=xc().nextTick,o=lt()("mqtt-packet:writeToStream"),l=i.cache,u=i.generateNumber,d=i.generateCache,p=i.genBufVariableByteInt,y=i.generate4ByteBuffer,f=Y,m=!0;function b(V,L,ne){switch(o("generate called"),L.cork&&(L.cork(),s(k,L)),m&&(m=!1,d()),o("generate: packet.cmd: %s",V.cmd),V.cmd){case"connect":return g(V,L);case"connack":return _(V,L,ne);case"publish":return S(V,L,ne);case"puback":case"pubrec":case"pubrel":case"pubcomp":return v(V,L,ne);case"subscribe":return x(V,L,ne);case"suback":return E(V,L,ne);case"unsubscribe":return I(V,L,ne);case"unsuback":return M(V,L,ne);case"pingreq":case"pingresp":return O(V,L);case"disconnect":return B(V,L,ne);case"auth":return T(V,L,ne);default:return L.destroy(new Error("Unknown command")),!1}}Object.defineProperty(b,"cacheNumbers",{get(){return f===Y},set(V){V?((!l||Object.keys(l).length===0)&&(m=!0),f=Y):(m=!1,f=K)}});function k(V){V.uncork()}function g(V,L,ne){let H=V||{},G=H.protocolId||"MQTT",Q=H.protocolVersion||4,me=H.will,oe=H.clean,R=H.keepalive||0,$=H.clientId||"",ee=H.username,fe=H.password,de=H.properties;oe===void 0&&(oe=!0);let ye=0;if(typeof G!="string"&&!r.isBuffer(G))return L.destroy(new Error("Invalid protocolId")),!1;if(ye+=G.length+2,Q!==3&&Q!==4&&Q!==5)return L.destroy(new Error("Invalid protocol version")),!1;if(ye+=1,(typeof $=="string"||r.isBuffer($))&&($||Q>=4)&&($||oe))ye+=r.byteLength($)+2;else{if(Q<4)return L.destroy(new Error("clientId must be supplied before 3.1.1")),!1;if(oe*1===0)return L.destroy(new Error("clientId must be given if cleanSession set to 0")),!1}if(typeof R!="number"||R<0||R>65535||R%1!==0)return L.destroy(new Error("Invalid keepalive")),!1;ye+=2,ye+=1;let q,ge;if(Q===5){if(q=Z(L,de),!q)return!1;ye+=q.length}if(me){if(typeof me!="object")return L.destroy(new Error("Invalid will")),!1;if(!me.topic||typeof me.topic!="string")return L.destroy(new Error("Invalid will topic")),!1;if(ye+=r.byteLength(me.topic)+2,ye+=2,me.payload)if(me.payload.length>=0)typeof me.payload=="string"?ye+=r.byteLength(me.payload):ye+=me.payload.length;else return L.destroy(new Error("Invalid will payload")),!1;if(ge={},Q===5){if(ge=Z(L,me.properties),!ge)return!1;ye+=ge.length}}let ve=!1;if(ee!=null)if(we(ee))ve=!0,ye+=r.byteLength(ee)+2;else return L.destroy(new Error("Invalid username")),!1;if(fe!=null){if(!ve)return L.destroy(new Error("Username is required to use password")),!1;if(we(fe))ye+=te(fe)+2;else return L.destroy(new Error("Invalid password")),!1}L.write(t.CONNECT_HEADER),F(L,ye),D(L,G),H.bridgeMode&&(Q+=128),L.write(Q===131?t.VERSION131:Q===132?t.VERSION132:Q===4?t.VERSION4:Q===5?t.VERSION5:t.VERSION3);let se=0;return se|=ee!=null?t.USERNAME_MASK:0,se|=fe!=null?t.PASSWORD_MASK:0,se|=me&&me.retain?t.WILL_RETAIN_MASK:0,se|=me&&me.qos?me.qos<<t.WILL_QOS_SHIFT:0,se|=me?t.WILL_FLAG_MASK:0,se|=oe?t.CLEAN_SESSION_MASK:0,L.write(r.from([se])),f(L,R),Q===5&&q.write(),D(L,$),me&&(Q===5&&ge.write(),N(L,me.topic),D(L,me.payload)),ee!=null&&D(L,ee),fe!=null&&D(L,fe),!0}function _(V,L,ne){let H=ne?ne.protocolVersion:4,G=V||{},Q=H===5?G.reasonCode:G.returnCode,me=G.properties,oe=2;if(typeof Q!="number")return L.destroy(new Error("Invalid return code")),!1;let R=null;if(H===5){if(R=Z(L,me),!R)return!1;oe+=R.length}return L.write(t.CONNACK_HEADER),F(L,oe),L.write(G.sessionPresent?t.SESSIONPRESENT_HEADER:n),L.write(r.from([Q])),R?.write(),!0}function S(V,L,ne){o("publish: packet: %o",V);let H=ne?ne.protocolVersion:4,G=V||{},Q=G.qos||0,me=G.retain?t.RETAIN_MASK:0,oe=G.topic,R=G.payload||a,$=G.messageId,ee=G.properties,fe=0;if(typeof oe=="string")fe+=r.byteLength(oe)+2;else if(r.isBuffer(oe))fe+=oe.length+2;else return L.destroy(new Error("Invalid topic")),!1;if(r.isBuffer(R)?fe+=R.length:fe+=r.byteLength(R),Q&&typeof $!="number")return L.destroy(new Error("Invalid messageId")),!1;Q&&(fe+=2);let de=null;if(H===5){if(de=Z(L,ee),!de)return!1;fe+=de.length}return L.write(t.PUBLISH_HEADER[Q][G.dup?1:0][me?1:0]),F(L,fe),f(L,te(oe)),L.write(oe),Q>0&&f(L,$),de?.write(),o("publish: payload: %o",R),L.write(R)}function v(V,L,ne){let H=ne?ne.protocolVersion:4,G=V||{},Q=G.cmd||"puback",me=G.messageId,oe=G.dup&&Q==="pubrel"?t.DUP_MASK:0,R=0,$=G.reasonCode,ee=G.properties,fe=H===5?3:2;if(Q==="pubrel"&&(R=1),typeof me!="number")return L.destroy(new Error("Invalid messageId")),!1;let de=null;if(H===5&&typeof ee=="object"){if(de=P(L,ee,ne,fe),!de)return!1;fe+=de.length}return L.write(t.ACKS[Q][R][oe][0]),fe===3&&(fe+=$!==0?1:-1),F(L,fe),f(L,me),H===5&&fe!==2&&L.write(r.from([$])),de!==null?de.write():fe===4&&L.write(r.from([0])),!0}function x(V,L,ne){o("subscribe: packet: ");let H=ne?ne.protocolVersion:4,G=V||{},Q=G.dup?t.DUP_MASK:0,me=G.messageId,oe=G.subscriptions,R=G.properties,$=0;if(typeof me!="number")return L.destroy(new Error("Invalid messageId")),!1;$+=2;let ee=null;if(H===5){if(ee=Z(L,R),!ee)return!1;$+=ee.length}if(typeof oe=="object"&&oe.length)for(let de=0;de<oe.length;de+=1){let ye=oe[de].topic,q=oe[de].qos;if(typeof ye!="string")return L.destroy(new Error("Invalid subscriptions - invalid topic")),!1;if(typeof q!="number")return L.destroy(new Error("Invalid subscriptions - invalid qos")),!1;if(H===5){if(typeof(oe[de].nl||!1)!="boolean")return L.destroy(new Error("Invalid subscriptions - invalid No Local")),!1;if(typeof(oe[de].rap||!1)!="boolean")return L.destroy(new Error("Invalid subscriptions - invalid Retain as Published")),!1;let ge=oe[de].rh||0;if(typeof ge!="number"||ge>2)return L.destroy(new Error("Invalid subscriptions - invalid Retain Handling")),!1}$+=r.byteLength(ye)+2+1}else return L.destroy(new Error("Invalid subscriptions")),!1;o("subscribe: writing to stream: %o",t.SUBSCRIBE_HEADER),L.write(t.SUBSCRIBE_HEADER[1][Q?1:0][0]),F(L,$),f(L,me),ee!==null&&ee.write();let fe=!0;for(let de of oe){let ye=de.topic,q=de.qos,ge=+de.nl,ve=+de.rap,se=de.rh,Te;N(L,ye),Te=t.SUBSCRIBE_OPTIONS_QOS[q],H===5&&(Te|=ge?t.SUBSCRIBE_OPTIONS_NL:0,Te|=ve?t.SUBSCRIBE_OPTIONS_RAP:0,Te|=se?t.SUBSCRIBE_OPTIONS_RH[se]:0),fe=L.write(r.from([Te]))}return fe}function E(V,L,ne){let H=ne?ne.protocolVersion:4,G=V||{},Q=G.messageId,me=G.granted,oe=G.properties,R=0;if(typeof Q!="number")return L.destroy(new Error("Invalid messageId")),!1;if(R+=2,typeof me=="object"&&me.length)for(let ee=0;ee<me.length;ee+=1){if(typeof me[ee]!="number")return L.destroy(new Error("Invalid qos vector")),!1;R+=1}else return L.destroy(new Error("Invalid qos vector")),!1;let $=null;if(H===5){if($=P(L,oe,ne,R),!$)return!1;R+=$.length}return L.write(t.SUBACK_HEADER),F(L,R),f(L,Q),$!==null&&$.write(),L.write(r.from(me))}function I(V,L,ne){let H=ne?ne.protocolVersion:4,G=V||{},Q=G.messageId,me=G.dup?t.DUP_MASK:0,oe=G.unsubscriptions,R=G.properties,$=0;if(typeof Q!="number")return L.destroy(new Error("Invalid messageId")),!1;if($+=2,typeof oe=="object"&&oe.length)for(let de=0;de<oe.length;de+=1){if(typeof oe[de]!="string")return L.destroy(new Error("Invalid unsubscriptions")),!1;$+=r.byteLength(oe[de])+2}else return L.destroy(new Error("Invalid unsubscriptions")),!1;let ee=null;if(H===5){if(ee=Z(L,R),!ee)return!1;$+=ee.length}L.write(t.UNSUBSCRIBE_HEADER[1][me?1:0][0]),F(L,$),f(L,Q),ee!==null&&ee.write();let fe=!0;for(let de=0;de<oe.length;de++)fe=N(L,oe[de]);return fe}function M(V,L,ne){let H=ne?ne.protocolVersion:4,G=V||{},Q=G.messageId,me=G.dup?t.DUP_MASK:0,oe=G.granted,R=G.properties,$=G.cmd,ee=0,fe=2;if(typeof Q!="number")return L.destroy(new Error("Invalid messageId")),!1;if(H===5)if(typeof oe=="object"&&oe.length)for(let ye=0;ye<oe.length;ye+=1){if(typeof oe[ye]!="number")return L.destroy(new Error("Invalid qos vector")),!1;fe+=1}else return L.destroy(new Error("Invalid qos vector")),!1;let de=null;if(H===5){if(de=P(L,R,ne,fe),!de)return!1;fe+=de.length}return L.write(t.ACKS[$][ee][me][0]),F(L,fe),f(L,Q),de!==null&&de.write(),H===5&&L.write(r.from(oe)),!0}function O(V,L,ne){return L.write(t.EMPTY[V.cmd])}function B(V,L,ne){let H=ne?ne.protocolVersion:4,G=V||{},Q=G.reasonCode,me=G.properties,oe=H===5?1:0,R=null;if(H===5){if(R=P(L,me,ne,oe),!R)return!1;oe+=R.length}return L.write(r.from([t.codes.disconnect<<4])),F(L,oe),H===5&&L.write(r.from([Q])),R!==null&&R.write(),!0}function T(V,L,ne){let H=ne?ne.protocolVersion:4,G=V||{},Q=G.reasonCode,me=G.properties,oe=H===5?1:0;H!==5&&L.destroy(new Error("Invalid mqtt version for auth packet"));let R=P(L,me,ne,oe);return R?(oe+=R.length,L.write(r.from([t.codes.auth<<4])),F(L,oe),L.write(r.from([Q])),R!==null&&R.write(),!0):!1}var W={};function F(V,L){if(L>t.VARBYTEINT_MAX)return V.destroy(new Error(`Invalid variable byte integer: ${L}`)),!1;let ne=W[L];return ne||(ne=p(L),L<16384&&(W[L]=ne)),o("writeVarByteInt: writing to stream: %o",ne),V.write(ne)}function N(V,L){let ne=r.byteLength(L);return f(V,ne),o("writeString: %s",L),V.write(L,"utf8")}function ae(V,L,ne){N(V,L),N(V,ne)}function Y(V,L){return o("writeNumberCached: number: %d",L),o("writeNumberCached: %o",l[L]),V.write(l[L])}function K(V,L){let ne=u(L);return o("writeNumberGenerated: %o",ne),V.write(ne)}function re(V,L){let ne=y(L);return o("write4ByteNumber: %o",ne),V.write(ne)}function D(V,L){typeof L=="string"?N(V,L):L?(f(V,L.length),V.write(L)):f(V,0)}function Z(V,L){if(typeof L!="object"||L.length!=null)return{length:1,write(){be(V,{},0)}};let ne=0;function H(G,Q){let me=t.propertiesTypes[G],oe=0;switch(me){case"byte":{if(typeof Q!="boolean")return V.destroy(new Error(`Invalid ${G}: ${Q}`)),!1;oe+=2;break}case"int8":{if(typeof Q!="number"||Q<0||Q>255)return V.destroy(new Error(`Invalid ${G}: ${Q}`)),!1;oe+=2;break}case"binary":{if(Q&&Q===null)return V.destroy(new Error(`Invalid ${G}: ${Q}`)),!1;oe+=1+r.byteLength(Q)+2;break}case"int16":{if(typeof Q!="number"||Q<0||Q>65535)return V.destroy(new Error(`Invalid ${G}: ${Q}`)),!1;oe+=3;break}case"int32":{if(typeof Q!="number"||Q<0||Q>4294967295)return V.destroy(new Error(`Invalid ${G}: ${Q}`)),!1;oe+=5;break}case"var":{if(typeof Q!="number"||Q<0||Q>268435455)return V.destroy(new Error(`Invalid ${G}: ${Q}`)),!1;oe+=1+r.byteLength(p(Q));break}case"string":{if(typeof Q!="string")return V.destroy(new Error(`Invalid ${G}: ${Q}`)),!1;oe+=3+r.byteLength(Q.toString());break}case"pair":{if(typeof Q!="object")return V.destroy(new Error(`Invalid ${G}: ${Q}`)),!1;oe+=Object.getOwnPropertyNames(Q).reduce((R,$)=>{let ee=Q[$];return Array.isArray(ee)?R+=ee.reduce((fe,de)=>(fe+=3+r.byteLength($.toString())+2+r.byteLength(de.toString()),fe),0):R+=3+r.byteLength($.toString())+2+r.byteLength(Q[$].toString()),R},0);break}default:return V.destroy(new Error(`Invalid property ${G}: ${Q}`)),!1}return oe}if(L)for(let G in L){let Q=0,me=0,oe=L[G];if(oe!==void 0){if(Array.isArray(oe))for(let R=0;R<oe.length;R++){if(me=H(G,oe[R]),!me)return!1;Q+=me}else{if(me=H(G,oe),!me)return!1;Q=me}if(!Q)return!1;ne+=Q}}return{length:r.byteLength(p(ne))+ne,write(){be(V,L,ne)}}}function P(V,L,ne,H){let G=["reasonString","userProperties"],Q=ne&&ne.properties&&ne.properties.maximumPacketSize?ne.properties.maximumPacketSize:0,me=Z(V,L);if(Q)for(;H+me.length>Q;){let oe=G.shift();if(oe&&L[oe])delete L[oe],me=Z(V,L);else return!1}return me}function J(V,L,ne){switch(t.propertiesTypes[L]){case"byte":{V.write(r.from([t.properties[L]])),V.write(r.from([+ne]));break}case"int8":{V.write(r.from([t.properties[L]])),V.write(r.from([ne]));break}case"binary":{V.write(r.from([t.properties[L]])),D(V,ne);break}case"int16":{V.write(r.from([t.properties[L]])),f(V,ne);break}case"int32":{V.write(r.from([t.properties[L]])),re(V,ne);break}case"var":{V.write(r.from([t.properties[L]])),F(V,ne);break}case"string":{V.write(r.from([t.properties[L]])),N(V,ne);break}case"pair":{Object.getOwnPropertyNames(ne).forEach(H=>{let G=ne[H];Array.isArray(G)?G.forEach(Q=>{V.write(r.from([t.properties[L]])),ae(V,H.toString(),Q.toString())}):(V.write(r.from([t.properties[L]])),ae(V,H.toString(),G.toString()))});break}default:return V.destroy(new Error(`Invalid property ${L} value: ${ne}`)),!1}}function be(V,L,ne){F(V,ne);for(let H in L)if(Object.prototype.hasOwnProperty.call(L,H)&&L[H]!=null){let G=L[H];if(Array.isArray(G))for(let Q=0;Q<G.length;Q++)J(V,H,G[Q]);else J(V,H,G)}}function te(V){return V?V instanceof r?V.length:r.byteLength(V):0}function we(V){return typeof V=="string"||V instanceof r}e.exports=b}),Ac=pe((c,e)=>{le(),ue(),ce();var t=Jo(),{EventEmitter:r}=(kt(),Pe(pt)),{Buffer:a}=(Ue(),Pe(Ne));function n(s,o){let l=new i;return t(s,l,o),l.concat()}var i=class extends r{constructor(){super(),this._array=new Array(20),this._i=0}write(s){return this._array[this._i++]=s,!0}concat(){let s=0,o=new Array(this._array.length),l=this._array,u=0,d;for(d=0;d<l.length&&l[d]!==void 0;d++)typeof l[d]!="string"?o[d]=l[d].length:o[d]=a.byteLength(l[d]),s+=o[d];let p=a.allocUnsafe(s);for(d=0;d<l.length&&l[d]!==void 0;d++)typeof l[d]!="string"?(l[d].copy(p,u),u+=o[d]):(p.write(l[d],u),u+=o[d]);return p}destroy(s){s&&this.emit("error",s)}};e.exports=n}),Ic=pe(c=>{le(),ue(),ce(),c.parser=Sc().parser,c.generate=Ac(),c.writeToStream=Jo()}),Tc=pe((c,e)=>{le(),ue(),ce(),e.exports=r;function t(n){return n instanceof rr?rr.from(n):new n.constructor(n.buffer.slice(),n.byteOffset,n.length)}function r(n){if(n=n||{},n.circles)return a(n);let i=new Map;if(i.set(Date,d=>new Date(d)),i.set(Map,(d,p)=>new Map(o(Array.from(d),p))),i.set(Set,(d,p)=>new Set(o(Array.from(d),p))),n.constructorHandlers)for(let d of n.constructorHandlers)i.set(d[0],d[1]);let s=null;return n.proto?u:l;function o(d,p){let y=Object.keys(d),f=new Array(y.length);for(let m=0;m<y.length;m++){let b=y[m],k=d[b];typeof k!="object"||k===null?f[b]=k:k.constructor!==Object&&(s=i.get(k.constructor))?f[b]=s(k,p):ArrayBuffer.isView(k)?f[b]=t(k):f[b]=p(k)}return f}function l(d){if(typeof d!="object"||d===null)return d;if(Array.isArray(d))return o(d,l);if(d.constructor!==Object&&(s=i.get(d.constructor)))return s(d,l);let p={};for(let y in d){if(Object.hasOwnProperty.call(d,y)===!1)continue;let f=d[y];typeof f!="object"||f===null?p[y]=f:f.constructor!==Object&&(s=i.get(f.constructor))?p[y]=s(f,l):ArrayBuffer.isView(f)?p[y]=t(f):p[y]=l(f)}return p}function u(d){if(typeof d!="object"||d===null)return d;if(Array.isArray(d))return o(d,u);if(d.constructor!==Object&&(s=i.get(d.constructor)))return s(d,u);let p={};for(let y in d){let f=d[y];typeof f!="object"||f===null?p[y]=f:f.constructor!==Object&&(s=i.get(f.constructor))?p[y]=s(f,u):ArrayBuffer.isView(f)?p[y]=t(f):p[y]=u(f)}return p}}function a(n){let i=[],s=[],o=new Map;if(o.set(Date,y=>new Date(y)),o.set(Map,(y,f)=>new Map(u(Array.from(y),f))),o.set(Set,(y,f)=>new Set(u(Array.from(y),f))),n.constructorHandlers)for(let y of n.constructorHandlers)o.set(y[0],y[1]);let l=null;return n.proto?p:d;function u(y,f){let m=Object.keys(y),b=new Array(m.length);for(let k=0;k<m.length;k++){let g=m[k],_=y[g];if(typeof _!="object"||_===null)b[g]=_;else if(_.constructor!==Object&&(l=o.get(_.constructor)))b[g]=l(_,f);else if(ArrayBuffer.isView(_))b[g]=t(_);else{let S=i.indexOf(_);S!==-1?b[g]=s[S]:b[g]=f(_)}}return b}function d(y){if(typeof y!="object"||y===null)return y;if(Array.isArray(y))return u(y,d);if(y.constructor!==Object&&(l=o.get(y.constructor)))return l(y,d);let f={};i.push(y),s.push(f);for(let m in y){if(Object.hasOwnProperty.call(y,m)===!1)continue;let b=y[m];if(typeof b!="object"||b===null)f[m]=b;else if(b.constructor!==Object&&(l=o.get(b.constructor)))f[m]=l(b,d);else if(ArrayBuffer.isView(b))f[m]=t(b);else{let k=i.indexOf(b);k!==-1?f[m]=s[k]:f[m]=d(b)}}return i.pop(),s.pop(),f}function p(y){if(typeof y!="object"||y===null)return y;if(Array.isArray(y))return u(y,p);if(y.constructor!==Object&&(l=o.get(y.constructor)))return l(y,p);let f={};i.push(y),s.push(f);for(let m in y){let b=y[m];if(typeof b!="object"||b===null)f[m]=b;else if(b.constructor!==Object&&(l=o.get(b.constructor)))f[m]=l(b,p);else if(ArrayBuffer.isView(b))f[m]=t(b);else{let k=i.indexOf(b);k!==-1?f[m]=s[k]:f[m]=p(b)}}return i.pop(),s.pop(),f}}}),Cc=pe((c,e)=>{le(),ue(),ce(),e.exports=Tc()()}),Xo=pe(c=>{le(),ue(),ce(),Object.defineProperty(c,"__esModule",{value:!0}),c.validateTopic=e,c.validateTopics=t;function e(r){let a=r.split("/");for(let n=0;n<a.length;n++)if(a[n]!=="+"){if(a[n]==="#")return n===a.length-1;if(a[n].indexOf("+")!==-1||a[n].indexOf("#")!==-1)return!1}return!0}function t(r){if(r.length===0)return"empty_topic_list";for(let a=0;a<r.length;a++)if(!e(r[a]))return r[a];return null}}),Zo=pe(c=>{le(),ue(),ce(),Object.defineProperty(c,"__esModule",{value:!0});var e=Et(),t={objectMode:!0},r={clean:!0},a=class{options;_inflights;constructor(n){this.options=n||{},this.options={...r,...n},this._inflights=new Map}put(n,i){return this._inflights.set(n.messageId,n),i&&i(),this}createStream(){let n=new e.Readable(t),i=[],s=!1,o=0;return this._inflights.forEach((l,u)=>{i.push(l)}),n._read=()=>{!s&&o<i.length?n.push(i[o++]):n.push(null)},n.destroy=l=>{if(!s)return s=!0,setTimeout(()=>{n.emit("close")},0),n},n}del(n,i){let s=this._inflights.get(n.messageId);return s?(this._inflights.delete(n.messageId),i(null,s)):i&&i(new Error("missing packet")),this}get(n,i){let s=this._inflights.get(n.messageId);return s?i(null,s):i&&i(new Error("missing packet")),this}close(n){this.options.clean&&(this._inflights=null),n&&n()}};c.default=a}),Oc=pe(c=>{le(),ue(),ce(),Object.defineProperty(c,"__esModule",{value:!0});var e=[0,16,128,131,135,144,145,151,153],t=(r,a,n)=>{r.log("handlePublish: packet %o",a),n=typeof n<"u"?n:r.noop;let i=a.topic.toString(),s=a.payload,{qos:o}=a,{messageId:l}=a,{options:u}=r;if(r.options.protocolVersion===5){let d;if(a.properties&&(d=a.properties.topicAlias),typeof d<"u")if(i.length===0)if(d>0&&d<=65535){let p=r.topicAliasRecv.getTopicByAlias(d);if(p)i=p,r.log("handlePublish :: topic complemented by alias. topic: %s - alias: %d",i,d);else{r.log("handlePublish :: unregistered topic alias. alias: %d",d),r.emit("error",new Error("Received unregistered Topic Alias"));return}}else{r.log("handlePublish :: topic alias out of range. alias: %d",d),r.emit("error",new Error("Received Topic Alias is out of range"));return}else if(r.topicAliasRecv.put(i,d))r.log("handlePublish :: registered topic: %s - alias: %d",i,d);else{r.log("handlePublish :: topic alias out of range. alias: %d",d),r.emit("error",new Error("Received Topic Alias is out of range"));return}}switch(r.log("handlePublish: qos %d",o),o){case 2:{u.customHandleAcks(i,s,a,(d,p)=>{if(typeof d=="number"&&(p=d,d=null),d)return r.emit("error",d);if(e.indexOf(p)===-1)return r.emit("error",new Error("Wrong reason code for pubrec"));p?r._sendPacket({cmd:"pubrec",messageId:l,reasonCode:p},n):r.incomingStore.put(a,()=>{r._sendPacket({cmd:"pubrec",messageId:l},n)})});break}case 1:{u.customHandleAcks(i,s,a,(d,p)=>{if(typeof d=="number"&&(p=d,d=null),d)return r.emit("error",d);if(e.indexOf(p)===-1)return r.emit("error",new Error("Wrong reason code for puback"));p||r.emit("message",i,s,a),r.handleMessage(a,y=>{if(y)return n&&n(y);r._sendPacket({cmd:"puback",messageId:l,reasonCode:p},n)})});break}case 0:r.emit("message",i,s,a),r.handleMessage(a,n);break;default:r.log("handlePublish: unknown QoS. Doing nothing.");break}};c.default=t}),Pc=pe((c,e)=>{e.exports={version:"5.15.0"}}),Rt=pe(c=>{le(),ue(),ce(),Object.defineProperty(c,"__esModule",{value:!0}),c.MQTTJS_VERSION=c.nextTick=c.ErrorWithSubackPacket=c.ErrorWithReasonCode=void 0,c.applyMixin=r;var e=class Ll extends Error{code;constructor(n,i){super(n),this.code=i,Object.setPrototypeOf(this,Ll.prototype),Object.getPrototypeOf(this).name="ErrorWithReasonCode"}};c.ErrorWithReasonCode=e;var t=class Nl extends Error{packet;constructor(n,i){super(n),this.packet=i,Object.setPrototypeOf(this,Nl.prototype),Object.getPrototypeOf(this).name="ErrorWithSubackPacket"}};c.ErrorWithSubackPacket=t;function r(a,n,i=!1){let s=[n];for(;;){let o=s[0],l=Object.getPrototypeOf(o);if(l?.prototype)s.unshift(l);else break}for(let o of s)for(let l of Object.getOwnPropertyNames(o.prototype))(i||l!=="constructor")&&Object.defineProperty(a.prototype,l,Object.getOwnPropertyDescriptor(o.prototype,l)??Object.create(null))}c.nextTick=typeof Me?.nextTick=="function"?Me.nextTick:a=>{setTimeout(a,0)},c.MQTTJS_VERSION=Pc().version}),sr=pe(c=>{le(),ue(),ce(),Object.defineProperty(c,"__esModule",{value:!0}),c.ReasonCodes=void 0;var e=Rt();c.ReasonCodes={0:"",1:"Unacceptable protocol version",2:"Identifier rejected",3:"Server unavailable",4:"Bad username or password",5:"Not authorized",16:"No matching subscribers",17:"No subscription existed",128:"Unspecified error",129:"Malformed Packet",130:"Protocol Error",131:"Implementation specific error",132:"Unsupported Protocol Version",133:"Client Identifier not valid",134:"Bad User Name or Password",135:"Not authorized",136:"Server unavailable",137:"Server busy",138:"Banned",139:"Server shutting down",140:"Bad authentication method",141:"Keep Alive timeout",142:"Session taken over",143:"Topic Filter invalid",144:"Topic Name invalid",145:"Packet identifier in use",146:"Packet Identifier not found",147:"Receive Maximum exceeded",148:"Topic Alias invalid",149:"Packet too large",150:"Message rate too high",151:"Quota exceeded",152:"Administrative action",153:"Payload format invalid",154:"Retain not supported",155:"QoS not supported",156:"Use another server",157:"Server moved",158:"Shared Subscriptions not supported",159:"Connection rate exceeded",160:"Maximum connect time",161:"Subscription Identifiers not supported",162:"Wildcard Subscriptions not supported"};var t=(r,a)=>{let{messageId:n}=a,i=a.cmd,s=null,o=r.outgoing[n]?r.outgoing[n].cb:null,l=null;if(!o){r.log("_handleAck :: Server sent an ack in error. Ignoring.");return}switch(r.log("_handleAck :: packet type",i),i){case"pubcomp":case"puback":{let u=a.reasonCode;u&&u>0&&u!==16?(l=new e.ErrorWithReasonCode(`Publish error: ${c.ReasonCodes[u]}`,u),r._removeOutgoingAndStoreMessage(n,()=>{o(l,a)})):r._removeOutgoingAndStoreMessage(n,o);break}case"pubrec":{s={cmd:"pubrel",qos:2,messageId:n};let u=a.reasonCode;u&&u>0&&u!==16?(l=new e.ErrorWithReasonCode(`Publish error: ${c.ReasonCodes[u]}`,u),r._removeOutgoingAndStoreMessage(n,()=>{o(l,a)})):r._sendPacket(s);break}case"suback":{delete r.outgoing[n],r.messageIdProvider.deallocate(n);let u=a.granted;for(let d=0;d<u.length;d++){let p=u[d];if((p&128)!==0){l=new Error(`Subscribe error: ${c.ReasonCodes[p]}`),l.code=p;let y=r.messageIdToTopic[n];y&&y.forEach(f=>{delete r._resubscribeTopics[f]})}}delete r.messageIdToTopic[n],r._invokeStoreProcessingQueue(),o(l,a);break}case"unsuback":{delete r.outgoing[n],r.messageIdProvider.deallocate(n),r._invokeStoreProcessingQueue(),o(null,a);break}default:r.emit("error",new Error("unrecognized packet type"))}r.disconnecting&&Object.keys(r.outgoing).length===0&&r.emit("outgoingEmpty")};c.default=t}),Mc=pe(c=>{le(),ue(),ce(),Object.defineProperty(c,"__esModule",{value:!0});var e=Rt(),t=sr(),r=(a,n)=>{let{options:i}=a,s=i.protocolVersion,o=s===5?n.reasonCode:n.returnCode;if(s!==5){let l=new e.ErrorWithReasonCode(`Protocol error: Auth packets are only supported in MQTT 5. Your version:${s}`,o);a.emit("error",l);return}a.handleAuth(n,(l,u)=>{if(l){a.emit("error",l);return}if(o===24)a.reconnecting=!1,a._sendPacket(u);else{let d=new e.ErrorWithReasonCode(`Connection refused: ${t.ReasonCodes[o]}`,o);a.emit("error",d)}})};c.default=r}),Rc=pe(c=>{le(),ue(),ce(),Object.defineProperty(c,"__esModule",{value:!0}),c.LRUCache=void 0;var e=typeof performance=="object"&&performance&&typeof performance.now=="function"?performance:Date,t=new Set,r=typeof Me=="object"&&Me?Me:{},a=(y,f,m,b)=>{typeof r.emitWarning=="function"?r.emitWarning(y,f,m,b):console.error(`[${m}] ${f}: ${y}`)},n=globalThis.AbortController,i=globalThis.AbortSignal;if(typeof n>"u"){i=class{onabort;_onabort=[];reason;aborted=!1;addEventListener(m,b){this._onabort.push(b)}},n=class{constructor(){f()}signal=new i;abort(m){if(!this.signal.aborted){this.signal.reason=m,this.signal.aborted=!0;for(let b of this.signal._onabort)b(m);this.signal.onabort?.(m)}}};let y=r.env?.LRU_CACHE_IGNORE_AC_WARNING!=="1",f=()=>{y&&(y=!1,a("AbortController is not defined. If using lru-cache in node 14, load an AbortController polyfill from the `node-abort-controller` package. A minimal polyfill is provided for use by LRUCache.fetch(), but it should not be relied upon in other contexts (eg, passing it to other APIs that use AbortController/AbortSignal might have undesirable effects). You may disable this with LRU_CACHE_IGNORE_AC_WARNING=1 in the env.","NO_ABORT_CONTROLLER","ENOTSUP",f))}}var s=y=>!t.has(y),o=y=>y&&y===Math.floor(y)&&y>0&&isFinite(y),l=y=>o(y)?y<=Math.pow(2,8)?Uint8Array:y<=Math.pow(2,16)?Uint16Array:y<=Math.pow(2,32)?Uint32Array:y<=Number.MAX_SAFE_INTEGER?u:null:null,u=class extends Array{constructor(y){super(y),this.fill(0)}},d=class Xt{heap;length;static#l=!1;static create(f){let m=l(f);if(!m)return[];Xt.#l=!0;let b=new Xt(f,m);return Xt.#l=!1,b}constructor(f,m){if(!Xt.#l)throw new TypeError("instantiate Stack using Stack.create(n)");this.heap=new m(f),this.length=0}push(f){this.heap[this.length++]=f}pop(){return this.heap[--this.length]}},p=class Ul{#l;#h;#g;#m;#O;#P;ttl;ttlResolution;ttlAutopurge;updateAgeOnGet;updateAgeOnHas;allowStale;noDisposeOnSet;noUpdateTTL;maxEntrySize;sizeCalculation;noDeleteOnFetchRejection;noDeleteOnStaleGet;allowStaleOnFetchAbort;allowStaleOnFetchRejection;ignoreFetchAbort;#i;#b;#n;#r;#e;#c;#f;#a;#o;#y;#s;#v;#w;#d;#_;#A;#u;static unsafeExposeInternals(f){return{starts:f.#w,ttls:f.#d,sizes:f.#v,keyMap:f.#n,keyList:f.#r,valList:f.#e,next:f.#c,prev:f.#f,get head(){return f.#a},get tail(){return f.#o},free:f.#y,isBackgroundFetch:m=>f.#t(m),backgroundFetch:(m,b,k,g)=>f.#j(m,b,k,g),moveToTail:m=>f.#C(m),indexes:m=>f.#k(m),rindexes:m=>f.#S(m),isStale:m=>f.#p(m)}}get max(){return this.#l}get maxSize(){return this.#h}get calculatedSize(){return this.#b}get size(){return this.#i}get fetchMethod(){return this.#O}get memoMethod(){return this.#P}get dispose(){return this.#g}get disposeAfter(){return this.#m}constructor(f){let{max:m=0,ttl:b,ttlResolution:k=1,ttlAutopurge:g,updateAgeOnGet:_,updateAgeOnHas:S,allowStale:v,dispose:x,disposeAfter:E,noDisposeOnSet:I,noUpdateTTL:M,maxSize:O=0,maxEntrySize:B=0,sizeCalculation:T,fetchMethod:W,memoMethod:F,noDeleteOnFetchRejection:N,noDeleteOnStaleGet:ae,allowStaleOnFetchRejection:Y,allowStaleOnFetchAbort:K,ignoreFetchAbort:re}=f;if(m!==0&&!o(m))throw new TypeError("max option must be a nonnegative integer");let D=m?l(m):Array;if(!D)throw new Error("invalid max value: "+m);if(this.#l=m,this.#h=O,this.maxEntrySize=B||this.#h,this.sizeCalculation=T,this.sizeCalculation){if(!this.#h&&!this.maxEntrySize)throw new TypeError("cannot set sizeCalculation without setting maxSize or maxEntrySize");if(typeof this.sizeCalculation!="function")throw new TypeError("sizeCalculation set to non-function")}if(F!==void 0&&typeof F!="function")throw new TypeError("memoMethod must be a function if defined");if(this.#P=F,W!==void 0&&typeof W!="function")throw new TypeError("fetchMethod must be a function if specified");if(this.#O=W,this.#A=!!W,this.#n=new Map,this.#r=new Array(m).fill(void 0),this.#e=new Array(m).fill(void 0),this.#c=new D(m),this.#f=new D(m),this.#a=0,this.#o=0,this.#y=d.create(m),this.#i=0,this.#b=0,typeof x=="function"&&(this.#g=x),typeof E=="function"?(this.#m=E,this.#s=[]):(this.#m=void 0,this.#s=void 0),this.#_=!!this.#g,this.#u=!!this.#m,this.noDisposeOnSet=!!I,this.noUpdateTTL=!!M,this.noDeleteOnFetchRejection=!!N,this.allowStaleOnFetchRejection=!!Y,this.allowStaleOnFetchAbort=!!K,this.ignoreFetchAbort=!!re,this.maxEntrySize!==0){if(this.#h!==0&&!o(this.#h))throw new TypeError("maxSize must be a positive integer if specified");if(!o(this.maxEntrySize))throw new TypeError("maxEntrySize must be a positive integer if specified");this.#$()}if(this.allowStale=!!v,this.noDeleteOnStaleGet=!!ae,this.updateAgeOnGet=!!_,this.updateAgeOnHas=!!S,this.ttlResolution=o(k)||k===0?k:1,this.ttlAutopurge=!!g,this.ttl=b||0,this.ttl){if(!o(this.ttl))throw new TypeError("ttl must be a positive integer if specified");this.#L()}if(this.#l===0&&this.ttl===0&&this.#h===0)throw new TypeError("At least one of max, maxSize, or ttl is required");if(!this.ttlAutopurge&&!this.#l&&!this.#h){let Z="LRU_CACHE_UNBOUNDED";s(Z)&&(t.add(Z),a("TTL caching without ttlAutopurge, max, or maxSize can result in unbounded memory consumption.","UnboundedCacheWarning",Z,Ul))}}getRemainingTTL(f){return this.#n.has(f)?1/0:0}#L(){let f=new u(this.#l),m=new u(this.#l);this.#d=f,this.#w=m,this.#N=(g,_,S=e.now())=>{if(m[g]=_!==0?S:0,f[g]=_,_!==0&&this.ttlAutopurge){let v=setTimeout(()=>{this.#p(g)&&this.#E(this.#r[g],"expire")},_+1);v.unref&&v.unref()}},this.#I=g=>{m[g]=f[g]!==0?e.now():0},this.#x=(g,_)=>{if(f[_]){let S=f[_],v=m[_];if(!S||!v)return;g.ttl=S,g.start=v,g.now=b||k();let x=g.now-v;g.remainingTTL=S-x}};let b=0,k=()=>{let g=e.now();if(this.ttlResolution>0){b=g;let _=setTimeout(()=>b=0,this.ttlResolution);_.unref&&_.unref()}return g};this.getRemainingTTL=g=>{let _=this.#n.get(g);if(_===void 0)return 0;let S=f[_],v=m[_];if(!S||!v)return 1/0;let x=(b||k())-v;return S-x},this.#p=g=>{let _=m[g],S=f[g];return!!S&&!!_&&(b||k())-_>S}}#I=()=>{};#x=()=>{};#N=()=>{};#p=()=>!1;#$(){let f=new u(this.#l);this.#b=0,this.#v=f,this.#T=m=>{this.#b-=f[m],f[m]=0},this.#U=(m,b,k,g)=>{if(this.#t(b))return 0;if(!o(k))if(g){if(typeof g!="function")throw new TypeError("sizeCalculation must be a function");if(k=g(b,m),!o(k))throw new TypeError("sizeCalculation return invalid (expect positive integer)")}else throw new TypeError("invalid size value (must be positive integer). When maxSize or maxEntrySize is used, sizeCalculation or size must be set.");return k},this.#M=(m,b,k)=>{if(f[m]=b,this.#h){let g=this.#h-f[m];for(;this.#b>g;)this.#R(!0)}this.#b+=f[m],k&&(k.entrySize=b,k.totalCalculatedSize=this.#b)}}#T=f=>{};#M=(f,m,b)=>{};#U=(f,m,b,k)=>{if(b||k)throw new TypeError("cannot set size without setting maxSize or maxEntrySize on cache");return 0};*#k({allowStale:f=this.allowStale}={}){if(this.#i)for(let m=this.#o;!(!this.#B(m)||((f||!this.#p(m))&&(yield m),m===this.#a));)m=this.#f[m]}*#S({allowStale:f=this.allowStale}={}){if(this.#i)for(let m=this.#a;!(!this.#B(m)||((f||!this.#p(m))&&(yield m),m===this.#o));)m=this.#c[m]}#B(f){return f!==void 0&&this.#n.get(this.#r[f])===f}*entries(){for(let f of this.#k())this.#e[f]!==void 0&&this.#r[f]!==void 0&&!this.#t(this.#e[f])&&(yield[this.#r[f],this.#e[f]])}*rentries(){for(let f of this.#S())this.#e[f]!==void 0&&this.#r[f]!==void 0&&!this.#t(this.#e[f])&&(yield[this.#r[f],this.#e[f]])}*keys(){for(let f of this.#k()){let m=this.#r[f];m!==void 0&&!this.#t(this.#e[f])&&(yield m)}}*rkeys(){for(let f of this.#S()){let m=this.#r[f];m!==void 0&&!this.#t(this.#e[f])&&(yield m)}}*values(){for(let f of this.#k())this.#e[f]!==void 0&&!this.#t(this.#e[f])&&(yield this.#e[f])}*rvalues(){for(let f of this.#S())this.#e[f]!==void 0&&!this.#t(this.#e[f])&&(yield this.#e[f])}[Symbol.iterator](){return this.entries()}[Symbol.toStringTag]="LRUCache";find(f,m={}){for(let b of this.#k()){let k=this.#e[b],g=this.#t(k)?k.__staleWhileFetching:k;if(g!==void 0&&f(g,this.#r[b],this))return this.get(this.#r[b],m)}}forEach(f,m=this){for(let b of this.#k()){let k=this.#e[b],g=this.#t(k)?k.__staleWhileFetching:k;g!==void 0&&f.call(m,g,this.#r[b],this)}}rforEach(f,m=this){for(let b of this.#S()){let k=this.#e[b],g=this.#t(k)?k.__staleWhileFetching:k;g!==void 0&&f.call(m,g,this.#r[b],this)}}purgeStale(){let f=!1;for(let m of this.#S({allowStale:!0}))this.#p(m)&&(this.#E(this.#r[m],"expire"),f=!0);return f}info(f){let m=this.#n.get(f);if(m===void 0)return;let b=this.#e[m],k=this.#t(b)?b.__staleWhileFetching:b;if(k===void 0)return;let g={value:k};if(this.#d&&this.#w){let _=this.#d[m],S=this.#w[m];if(_&&S){let v=_-(e.now()-S);g.ttl=v,g.start=Date.now()}}return this.#v&&(g.size=this.#v[m]),g}dump(){let f=[];for(let m of this.#k({allowStale:!0})){let b=this.#r[m],k=this.#e[m],g=this.#t(k)?k.__staleWhileFetching:k;if(g===void 0||b===void 0)continue;let _={value:g};if(this.#d&&this.#w){_.ttl=this.#d[m];let S=e.now()-this.#w[m];_.start=Math.floor(Date.now()-S)}this.#v&&(_.size=this.#v[m]),f.unshift([b,_])}return f}load(f){this.clear();for(let[m,b]of f){if(b.start){let k=Date.now()-b.start;b.start=e.now()-k}this.set(m,b.value,b)}}set(f,m,b={}){if(m===void 0)return this.delete(f),this;let{ttl:k=this.ttl,start:g,noDisposeOnSet:_=this.noDisposeOnSet,sizeCalculation:S=this.sizeCalculation,status:v}=b,{noUpdateTTL:x=this.noUpdateTTL}=b,E=this.#U(f,m,b.size||0,S);if(this.maxEntrySize&&E>this.maxEntrySize)return v&&(v.set="miss",v.maxEntrySizeExceeded=!0),this.#E(f,"set"),this;let I=this.#i===0?void 0:this.#n.get(f);if(I===void 0)I=this.#i===0?this.#o:this.#y.length!==0?this.#y.pop():this.#i===this.#l?this.#R(!1):this.#i,this.#r[I]=f,this.#e[I]=m,this.#n.set(f,I),this.#c[this.#o]=I,this.#f[I]=this.#o,this.#o=I,this.#i++,this.#M(I,E,v),v&&(v.set="add"),x=!1;else{this.#C(I);let M=this.#e[I];if(m!==M){if(this.#A&&this.#t(M)){M.__abortController.abort(new Error("replaced"));let{__staleWhileFetching:O}=M;O!==void 0&&!_&&(this.#_&&this.#g?.(O,f,"set"),this.#u&&this.#s?.push([O,f,"set"]))}else _||(this.#_&&this.#g?.(M,f,"set"),this.#u&&this.#s?.push([M,f,"set"]));if(this.#T(I),this.#M(I,E,v),this.#e[I]=m,v){v.set="replace";let O=M&&this.#t(M)?M.__staleWhileFetching:M;O!==void 0&&(v.oldValue=O)}}else v&&(v.set="update")}if(k!==0&&!this.#d&&this.#L(),this.#d&&(x||this.#N(I,k,g),v&&this.#x(v,I)),!_&&this.#u&&this.#s){let M=this.#s,O;for(;O=M?.shift();)this.#m?.(...O)}return this}pop(){try{for(;this.#i;){let f=this.#e[this.#a];if(this.#R(!0),this.#t(f)){if(f.__staleWhileFetching)return f.__staleWhileFetching}else if(f!==void 0)return f}}finally{if(this.#u&&this.#s){let f=this.#s,m;for(;m=f?.shift();)this.#m?.(...m)}}}#R(f){let m=this.#a,b=this.#r[m],k=this.#e[m];return this.#A&&this.#t(k)?k.__abortController.abort(new Error("evicted")):(this.#_||this.#u)&&(this.#_&&this.#g?.(k,b,"evict"),this.#u&&this.#s?.push([k,b,"evict"])),this.#T(m),f&&(this.#r[m]=void 0,this.#e[m]=void 0,this.#y.push(m)),this.#i===1?(this.#a=this.#o=0,this.#y.length=0):this.#a=this.#c[m],this.#n.delete(b),this.#i--,m}has(f,m={}){let{updateAgeOnHas:b=this.updateAgeOnHas,status:k}=m,g=this.#n.get(f);if(g!==void 0){let _=this.#e[g];if(this.#t(_)&&_.__staleWhileFetching===void 0)return!1;if(this.#p(g))k&&(k.has="stale",this.#x(k,g));else return b&&this.#I(g),k&&(k.has="hit",this.#x(k,g)),!0}else k&&(k.has="miss");return!1}peek(f,m={}){let{allowStale:b=this.allowStale}=m,k=this.#n.get(f);if(k===void 0||!b&&this.#p(k))return;let g=this.#e[k];return this.#t(g)?g.__staleWhileFetching:g}#j(f,m,b,k){let g=m===void 0?void 0:this.#e[m];if(this.#t(g))return g;let _=new n,{signal:S}=b;S?.addEventListener("abort",()=>_.abort(S.reason),{signal:_.signal});let v={signal:_.signal,options:b,context:k},x=(T,W=!1)=>{let{aborted:F}=_.signal,N=b.ignoreFetchAbort&&T!==void 0;if(b.status&&(F&&!W?(b.status.fetchAborted=!0,b.status.fetchError=_.signal.reason,N&&(b.status.fetchAbortIgnored=!0)):b.status.fetchResolved=!0),F&&!N&&!W)return I(_.signal.reason);let ae=O;return this.#e[m]===O&&(T===void 0?ae.__staleWhileFetching?this.#e[m]=ae.__staleWhileFetching:this.#E(f,"fetch"):(b.status&&(b.status.fetchUpdated=!0),this.set(f,T,v.options))),T},E=T=>(b.status&&(b.status.fetchRejected=!0,b.status.fetchError=T),I(T)),I=T=>{let{aborted:W}=_.signal,F=W&&b.allowStaleOnFetchAbort,N=F||b.allowStaleOnFetchRejection,ae=N||b.noDeleteOnFetchRejection,Y=O;if(this.#e[m]===O&&(!ae||Y.__staleWhileFetching===void 0?this.#E(f,"fetch"):F||(this.#e[m]=Y.__staleWhileFetching)),N)return b.status&&Y.__staleWhileFetching!==void 0&&(b.status.returnedStale=!0),Y.__staleWhileFetching;if(Y.__returned===Y)throw T},M=(T,W)=>{let F=this.#O?.(f,g,v);F&&F instanceof Promise&&F.then(N=>T(N===void 0?void 0:N),W),_.signal.addEventListener("abort",()=>{(!b.ignoreFetchAbort||b.allowStaleOnFetchAbort)&&(T(void 0),b.allowStaleOnFetchAbort&&(T=N=>x(N,!0)))})};b.status&&(b.status.fetchDispatched=!0);let O=new Promise(M).then(x,E),B=Object.assign(O,{__abortController:_,__staleWhileFetching:g,__returned:void 0});return m===void 0?(this.set(f,B,{...v.options,status:void 0}),m=this.#n.get(f)):this.#e[m]=B,B}#t(f){if(!this.#A)return!1;let m=f;return!!m&&m instanceof Promise&&m.hasOwnProperty("__staleWhileFetching")&&m.__abortController instanceof n}async fetch(f,m={}){let{allowStale:b=this.allowStale,updateAgeOnGet:k=this.updateAgeOnGet,noDeleteOnStaleGet:g=this.noDeleteOnStaleGet,ttl:_=this.ttl,noDisposeOnSet:S=this.noDisposeOnSet,size:v=0,sizeCalculation:x=this.sizeCalculation,noUpdateTTL:E=this.noUpdateTTL,noDeleteOnFetchRejection:I=this.noDeleteOnFetchRejection,allowStaleOnFetchRejection:M=this.allowStaleOnFetchRejection,ignoreFetchAbort:O=this.ignoreFetchAbort,allowStaleOnFetchAbort:B=this.allowStaleOnFetchAbort,context:T,forceRefresh:W=!1,status:F,signal:N}=m;if(!this.#A)return F&&(F.fetch="get"),this.get(f,{allowStale:b,updateAgeOnGet:k,noDeleteOnStaleGet:g,status:F});let ae={allowStale:b,updateAgeOnGet:k,noDeleteOnStaleGet:g,ttl:_,noDisposeOnSet:S,size:v,sizeCalculation:x,noUpdateTTL:E,noDeleteOnFetchRejection:I,allowStaleOnFetchRejection:M,allowStaleOnFetchAbort:B,ignoreFetchAbort:O,status:F,signal:N},Y=this.#n.get(f);if(Y===void 0){F&&(F.fetch="miss");let K=this.#j(f,Y,ae,T);return K.__returned=K}else{let K=this.#e[Y];if(this.#t(K)){let P=b&&K.__staleWhileFetching!==void 0;return F&&(F.fetch="inflight",P&&(F.returnedStale=!0)),P?K.__staleWhileFetching:K.__returned=K}let re=this.#p(Y);if(!W&&!re)return F&&(F.fetch="hit"),this.#C(Y),k&&this.#I(Y),F&&this.#x(F,Y),K;let D=this.#j(f,Y,ae,T),Z=D.__staleWhileFetching!==void 0&&b;return F&&(F.fetch=re?"stale":"refresh",Z&&re&&(F.returnedStale=!0)),Z?D.__staleWhileFetching:D.__returned=D}}async forceFetch(f,m={}){let b=await this.fetch(f,m);if(b===void 0)throw new Error("fetch() returned undefined");return b}memo(f,m={}){let b=this.#P;if(!b)throw new Error("no memoMethod provided to constructor");let{context:k,forceRefresh:g,..._}=m,S=this.get(f,_);if(!g&&S!==void 0)return S;let v=b(f,S,{options:_,context:k});return this.set(f,v,_),v}get(f,m={}){let{allowStale:b=this.allowStale,updateAgeOnGet:k=this.updateAgeOnGet,noDeleteOnStaleGet:g=this.noDeleteOnStaleGet,status:_}=m,S=this.#n.get(f);if(S!==void 0){let v=this.#e[S],x=this.#t(v);return _&&this.#x(_,S),this.#p(S)?(_&&(_.get="stale"),x?(_&&b&&v.__staleWhileFetching!==void 0&&(_.returnedStale=!0),b?v.__staleWhileFetching:void 0):(g||this.#E(f,"expire"),_&&b&&(_.returnedStale=!0),b?v:void 0)):(_&&(_.get="hit"),x?v.__staleWhileFetching:(this.#C(S),k&&this.#I(S),v))}else _&&(_.get="miss")}#F(f,m){this.#f[m]=f,this.#c[f]=m}#C(f){f!==this.#o&&(f===this.#a?this.#a=this.#c[f]:this.#F(this.#f[f],this.#c[f]),this.#F(this.#o,f),this.#o=f)}delete(f){return this.#E(f,"delete")}#E(f,m){let b=!1;if(this.#i!==0){let k=this.#n.get(f);if(k!==void 0)if(b=!0,this.#i===1)this.#D(m);else{this.#T(k);let g=this.#e[k];if(this.#t(g)?g.__abortController.abort(new Error("deleted")):(this.#_||this.#u)&&(this.#_&&this.#g?.(g,f,m),this.#u&&this.#s?.push([g,f,m])),this.#n.delete(f),this.#r[k]=void 0,this.#e[k]=void 0,k===this.#o)this.#o=this.#f[k];else if(k===this.#a)this.#a=this.#c[k];else{let _=this.#f[k];this.#c[_]=this.#c[k];let S=this.#c[k];this.#f[S]=this.#f[k]}this.#i--,this.#y.push(k)}}if(this.#u&&this.#s?.length){let k=this.#s,g;for(;g=k?.shift();)this.#m?.(...g)}return b}clear(){return this.#D("delete")}#D(f){for(let m of this.#S({allowStale:!0})){let b=this.#e[m];if(this.#t(b))b.__abortController.abort(new Error("deleted"));else{let k=this.#r[m];this.#_&&this.#g?.(b,k,f),this.#u&&this.#s?.push([b,k,f])}}if(this.#n.clear(),this.#e.fill(void 0),this.#r.fill(void 0),this.#d&&this.#w&&(this.#d.fill(0),this.#w.fill(0)),this.#v&&this.#v.fill(0),this.#a=0,this.#o=0,this.#y.length=0,this.#b=0,this.#i=0,this.#u&&this.#s){let m=this.#s,b;for(;b=m?.shift();)this.#m?.(...b)}}};c.LRUCache=p}),ct=pe(c=>{le(),ue(),ce(),Object.defineProperty(c,"t",{value:!0}),c.ContainerIterator=c.Container=c.Base=void 0;var e=class{constructor(a=0){this.iteratorType=a}equals(a){return this.o===a.o}};c.ContainerIterator=e;var t=class{constructor(){this.i=0}get length(){return this.i}size(){return this.i}empty(){return this.i===0}};c.Base=t;var r=class extends t{};c.Container=r}),jc=pe(c=>{le(),ue(),ce(),Object.defineProperty(c,"t",{value:!0}),c.default=void 0;var e=ct(),t=class extends e.Base{constructor(a=[]){super(),this.S=[];let n=this;a.forEach(function(i){n.push(i)})}clear(){this.i=0,this.S=[]}push(a){return this.S.push(a),this.i+=1,this.i}pop(){if(this.i!==0)return this.i-=1,this.S.pop()}top(){return this.S[this.i-1]}},r=t;c.default=r}),Lc=pe(c=>{le(),ue(),ce(),Object.defineProperty(c,"t",{value:!0}),c.default=void 0;var e=ct(),t=class extends e.Base{constructor(a=[]){super(),this.j=0,this.q=[];let n=this;a.forEach(function(i){n.push(i)})}clear(){this.q=[],this.i=this.j=0}push(a){let n=this.q.length;if(this.j/n>.5&&this.j+this.i>=n&&n>4096){let i=this.i;for(let s=0;s<i;++s)this.q[s]=this.q[this.j+s];this.j=0,this.q[this.i]=a}else this.q[this.j+this.i]=a;return++this.i}pop(){if(this.i===0)return;let a=this.q[this.j++];return this.i-=1,a}front(){if(this.i!==0)return this.q[this.j]}},r=t;c.default=r}),Nc=pe(c=>{le(),ue(),ce(),Object.defineProperty(c,"t",{value:!0}),c.default=void 0;var e=ct(),t=class extends e.Base{constructor(a=[],n=function(s,o){return s>o?-1:s<o?1:0},i=!0){if(super(),this.v=n,Array.isArray(a))this.C=i?[...a]:a;else{this.C=[];let o=this;a.forEach(function(l){o.C.push(l)})}this.i=this.C.length;let s=this.i>>1;for(let o=this.i-1>>1;o>=0;--o)this.k(o,s)}m(a){let n=this.C[a];for(;a>0;){let i=a-1>>1,s=this.C[i];if(this.v(s,n)<=0)break;this.C[a]=s,a=i}this.C[a]=n}k(a,n){let i=this.C[a];for(;a<n;){let s=a<<1|1,o=s+1,l=this.C[s];if(o<this.i&&this.v(l,this.C[o])>0&&(s=o,l=this.C[o]),this.v(l,i)>=0)break;this.C[a]=l,a=s}this.C[a]=i}clear(){this.i=0,this.C.length=0}push(a){this.C.push(a),this.m(this.i),this.i+=1}pop(){if(this.i===0)return;let a=this.C[0],n=this.C.pop();return this.i-=1,this.i&&(this.C[0]=n,this.k(0,this.i>>1)),a}top(){return this.C[0]}find(a){return this.C.indexOf(a)>=0}remove(a){let n=this.C.indexOf(a);return n<0?!1:(n===0?this.pop():n===this.i-1?(this.C.pop(),this.i-=1):(this.C.splice(n,1,this.C.pop()),this.i-=1,this.m(n),this.k(n,this.i>>1)),!0)}updateItem(a){let n=this.C.indexOf(a);return n<0?!1:(this.m(n),this.k(n,this.i>>1),!0)}toArray(){return[...this.C]}},r=t;c.default=r}),ii=pe(c=>{le(),ue(),ce(),Object.defineProperty(c,"t",{value:!0}),c.default=void 0;var e=ct(),t=class extends e.Container{},r=t;c.default=r}),ut=pe(c=>{le(),ue(),ce(),Object.defineProperty(c,"t",{value:!0}),c.throwIteratorAccessError=e;function e(){throw new RangeError("Iterator access denied!")}}),es=pe(c=>{le(),ue(),ce(),Object.defineProperty(c,"t",{value:!0}),c.RandomIterator=void 0;var e=ct(),t=ut(),r=class extends e.ContainerIterator{constructor(a,n){super(n),this.o=a,this.iteratorType===0?(this.pre=function(){return this.o===0&&(0,t.throwIteratorAccessError)(),this.o-=1,this},this.next=function(){return this.o===this.container.size()&&(0,t.throwIteratorAccessError)(),this.o+=1,this}):(this.pre=function(){return this.o===this.container.size()-1&&(0,t.throwIteratorAccessError)(),this.o+=1,this},this.next=function(){return this.o===-1&&(0,t.throwIteratorAccessError)(),this.o-=1,this})}get pointer(){return this.container.getElementByPos(this.o)}set pointer(a){this.container.setElementByPos(this.o,a)}};c.RandomIterator=r}),Uc=pe(c=>{le(),ue(),ce(),Object.defineProperty(c,"t",{value:!0}),c.default=void 0;var e=r(ii()),t=es();function r(s){return s&&s.t?s:{default:s}}var a=class Bl extends t.RandomIterator{constructor(o,l,u){super(o,u),this.container=l}copy(){return new Bl(this.o,this.container,this.iteratorType)}},n=class extends e.default{constructor(s=[],o=!0){if(super(),Array.isArray(s))this.J=o?[...s]:s,this.i=s.length;else{this.J=[];let l=this;s.forEach(function(u){l.pushBack(u)})}}clear(){this.i=0,this.J.length=0}begin(){return new a(0,this)}end(){return new a(this.i,this)}rBegin(){return new a(this.i-1,this,1)}rEnd(){return new a(-1,this,1)}front(){return this.J[0]}back(){return this.J[this.i-1]}getElementByPos(s){if(s<0||s>this.i-1)throw new RangeError;return this.J[s]}eraseElementByPos(s){if(s<0||s>this.i-1)throw new RangeError;return this.J.splice(s,1),this.i-=1,this.i}eraseElementByValue(s){let o=0;for(let l=0;l<this.i;++l)this.J[l]!==s&&(this.J[o++]=this.J[l]);return this.i=this.J.length=o,this.i}eraseElementByIterator(s){let o=s.o;return s=s.next(),this.eraseElementByPos(o),s}pushBack(s){return this.J.push(s),this.i+=1,this.i}popBack(){if(this.i!==0)return this.i-=1,this.J.pop()}setElementByPos(s,o){if(s<0||s>this.i-1)throw new RangeError;this.J[s]=o}insert(s,o,l=1){if(s<0||s>this.i)throw new RangeError;return this.J.splice(s,0,...new Array(l).fill(o)),this.i+=l,this.i}find(s){for(let o=0;o<this.i;++o)if(this.J[o]===s)return new a(o,this);return this.end()}reverse(){this.J.reverse()}unique(){let s=1;for(let o=1;o<this.i;++o)this.J[o]!==this.J[o-1]&&(this.J[s++]=this.J[o]);return this.i=this.J.length=s,this.i}sort(s){this.J.sort(s)}forEach(s){for(let o=0;o<this.i;++o)s(this.J[o],o,this)}[Symbol.iterator](){return(function*(){yield*this.J}).bind(this)()}},i=n;c.default=i}),Bc=pe(c=>{le(),ue(),ce(),Object.defineProperty(c,"t",{value:!0}),c.default=void 0;var e=a(ii()),t=ct(),r=ut();function a(o){return o&&o.t?o:{default:o}}var n=class Fl extends t.ContainerIterator{constructor(l,u,d,p){super(p),this.o=l,this.h=u,this.container=d,this.iteratorType===0?(this.pre=function(){return this.o.L===this.h&&(0,r.throwIteratorAccessError)(),this.o=this.o.L,this},this.next=function(){return this.o===this.h&&(0,r.throwIteratorAccessError)(),this.o=this.o.B,this}):(this.pre=function(){return this.o.B===this.h&&(0,r.throwIteratorAccessError)(),this.o=this.o.B,this},this.next=function(){return this.o===this.h&&(0,r.throwIteratorAccessError)(),this.o=this.o.L,this})}get pointer(){return this.o===this.h&&(0,r.throwIteratorAccessError)(),this.o.l}set pointer(l){this.o===this.h&&(0,r.throwIteratorAccessError)(),this.o.l=l}copy(){return new Fl(this.o,this.h,this.container,this.iteratorType)}},i=class extends e.default{constructor(o=[]){super(),this.h={},this.p=this._=this.h.L=this.h.B=this.h;let l=this;o.forEach(function(u){l.pushBack(u)})}V(o){let{L:l,B:u}=o;l.B=u,u.L=l,o===this.p&&(this.p=u),o===this._&&(this._=l),this.i-=1}G(o,l){let u=l.B,d={l:o,L:l,B:u};l.B=d,u.L=d,l===this.h&&(this.p=d),u===this.h&&(this._=d),this.i+=1}clear(){this.i=0,this.p=this._=this.h.L=this.h.B=this.h}begin(){return new n(this.p,this.h,this)}end(){return new n(this.h,this.h,this)}rBegin(){return new n(this._,this.h,this,1)}rEnd(){return new n(this.h,this.h,this,1)}front(){return this.p.l}back(){return this._.l}getElementByPos(o){if(o<0||o>this.i-1)throw new RangeError;let l=this.p;for(;o--;)l=l.B;return l.l}eraseElementByPos(o){if(o<0||o>this.i-1)throw new RangeError;let l=this.p;for(;o--;)l=l.B;return this.V(l),this.i}eraseElementByValue(o){let l=this.p;for(;l!==this.h;)l.l===o&&this.V(l),l=l.B;return this.i}eraseElementByIterator(o){let l=o.o;return l===this.h&&(0,r.throwIteratorAccessError)(),o=o.next(),this.V(l),o}pushBack(o){return this.G(o,this._),this.i}popBack(){if(this.i===0)return;let o=this._.l;return this.V(this._),o}pushFront(o){return this.G(o,this.h),this.i}popFront(){if(this.i===0)return;let o=this.p.l;return this.V(this.p),o}setElementByPos(o,l){if(o<0||o>this.i-1)throw new RangeError;let u=this.p;for(;o--;)u=u.B;u.l=l}insert(o,l,u=1){if(o<0||o>this.i)throw new RangeError;if(u<=0)return this.i;if(o===0)for(;u--;)this.pushFront(l);else if(o===this.i)for(;u--;)this.pushBack(l);else{let d=this.p;for(let y=1;y<o;++y)d=d.B;let p=d.B;for(this.i+=u;u--;)d.B={l,L:d},d.B.L=d,d=d.B;d.B=p,p.L=d}return this.i}find(o){let l=this.p;for(;l!==this.h;){if(l.l===o)return new n(l,this.h,this);l=l.B}return this.end()}reverse(){if(this.i<=1)return;let o=this.p,l=this._,u=0;for(;u<<1<this.i;){let d=o.l;o.l=l.l,l.l=d,o=o.B,l=l.L,u+=1}}unique(){if(this.i<=1)return this.i;let o=this.p;for(;o!==this.h;){let l=o;for(;l.B!==this.h&&l.l===l.B.l;)l=l.B,this.i-=1;o.B=l.B,o.B.L=o,o=o.B}return this.i}sort(o){if(this.i<=1)return;let l=[];this.forEach(function(d){l.push(d)}),l.sort(o);let u=this.p;l.forEach(function(d){u.l=d,u=u.B})}merge(o){let l=this;if(this.i===0)o.forEach(function(u){l.pushBack(u)});else{let u=this.p;o.forEach(function(d){for(;u!==l.h&&u.l<=d;)u=u.B;l.G(d,u.L)})}return this.i}forEach(o){let l=this.p,u=0;for(;l!==this.h;)o(l.l,u++,this),l=l.B}[Symbol.iterator](){return(function*(){if(this.i===0)return;let o=this.p;for(;o!==this.h;)yield o.l,o=o.B}).bind(this)()}},s=i;c.default=s}),Fc=pe(c=>{le(),ue(),ce(),Object.defineProperty(c,"t",{value:!0}),c.default=void 0;var e=r(ii()),t=es();function r(s){return s&&s.t?s:{default:s}}var a=class Dl extends t.RandomIterator{constructor(o,l,u){super(o,u),this.container=l}copy(){return new Dl(this.o,this.container,this.iteratorType)}},n=class extends e.default{constructor(s=[],o=4096){super(),this.j=0,this.D=0,this.R=0,this.N=0,this.P=0,this.A=[];let l=(()=>{if(typeof s.length=="number")return s.length;if(typeof s.size=="number")return s.size;if(typeof s.size=="function")return s.size();throw new TypeError("Cannot get the length or size of the container")})();this.F=o,this.P=Math.max(Math.ceil(l/this.F),1);for(let p=0;p<this.P;++p)this.A.push(new Array(this.F));let u=Math.ceil(l/this.F);this.j=this.R=(this.P>>1)-(u>>1),this.D=this.N=this.F-l%this.F>>1;let d=this;s.forEach(function(p){d.pushBack(p)})}T(){let s=[],o=Math.max(this.P>>1,1);for(let l=0;l<o;++l)s[l]=new Array(this.F);for(let l=this.j;l<this.P;++l)s[s.length]=this.A[l];for(let l=0;l<this.R;++l)s[s.length]=this.A[l];s[s.length]=[...this.A[this.R]],this.j=o,this.R=s.length-1;for(let l=0;l<o;++l)s[s.length]=new Array(this.F);this.A=s,this.P=s.length}O(s){let o=this.D+s+1,l=o%this.F,u=l-1,d=this.j+(o-l)/this.F;return l===0&&(d-=1),d%=this.P,u<0&&(u+=this.F),{curNodeBucketIndex:d,curNodePointerIndex:u}}clear(){this.A=[new Array(this.F)],this.P=1,this.j=this.R=this.i=0,this.D=this.N=this.F>>1}begin(){return new a(0,this)}end(){return new a(this.i,this)}rBegin(){return new a(this.i-1,this,1)}rEnd(){return new a(-1,this,1)}front(){if(this.i!==0)return this.A[this.j][this.D]}back(){if(this.i!==0)return this.A[this.R][this.N]}pushBack(s){return this.i&&(this.N<this.F-1?this.N+=1:this.R<this.P-1?(this.R+=1,this.N=0):(this.R=0,this.N=0),this.R===this.j&&this.N===this.D&&this.T()),this.i+=1,this.A[this.R][this.N]=s,this.i}popBack(){if(this.i===0)return;let s=this.A[this.R][this.N];return this.i!==1&&(this.N>0?this.N-=1:this.R>0?(this.R-=1,this.N=this.F-1):(this.R=this.P-1,this.N=this.F-1)),this.i-=1,s}pushFront(s){return this.i&&(this.D>0?this.D-=1:this.j>0?(this.j-=1,this.D=this.F-1):(this.j=this.P-1,this.D=this.F-1),this.j===this.R&&this.D===this.N&&this.T()),this.i+=1,this.A[this.j][this.D]=s,this.i}popFront(){if(this.i===0)return;let s=this.A[this.j][this.D];return this.i!==1&&(this.D<this.F-1?this.D+=1:this.j<this.P-1?(this.j+=1,this.D=0):(this.j=0,this.D=0)),this.i-=1,s}getElementByPos(s){if(s<0||s>this.i-1)throw new RangeError;let{curNodeBucketIndex:o,curNodePointerIndex:l}=this.O(s);return this.A[o][l]}setElementByPos(s,o){if(s<0||s>this.i-1)throw new RangeError;let{curNodeBucketIndex:l,curNodePointerIndex:u}=this.O(s);this.A[l][u]=o}insert(s,o,l=1){if(s<0||s>this.i)throw new RangeError;if(s===0)for(;l--;)this.pushFront(o);else if(s===this.i)for(;l--;)this.pushBack(o);else{let u=[];for(let d=s;d<this.i;++d)u.push(this.getElementByPos(d));this.cut(s-1);for(let d=0;d<l;++d)this.pushBack(o);for(let d=0;d<u.length;++d)this.pushBack(u[d])}return this.i}cut(s){if(s<0)return this.clear(),0;let{curNodeBucketIndex:o,curNodePointerIndex:l}=this.O(s);return this.R=o,this.N=l,this.i=s+1,this.i}eraseElementByPos(s){if(s<0||s>this.i-1)throw new RangeError;if(s===0)this.popFront();else if(s===this.i-1)this.popBack();else{let o=[];for(let u=s+1;u<this.i;++u)o.push(this.getElementByPos(u));this.cut(s),this.popBack();let l=this;o.forEach(function(u){l.pushBack(u)})}return this.i}eraseElementByValue(s){if(this.i===0)return 0;let o=[];for(let u=0;u<this.i;++u){let d=this.getElementByPos(u);d!==s&&o.push(d)}let l=o.length;for(let u=0;u<l;++u)this.setElementByPos(u,o[u]);return this.cut(l-1)}eraseElementByIterator(s){let o=s.o;return this.eraseElementByPos(o),s=s.next(),s}find(s){for(let o=0;o<this.i;++o)if(this.getElementByPos(o)===s)return new a(o,this);return this.end()}reverse(){let s=0,o=this.i-1;for(;s<o;){let l=this.getElementByPos(s);this.setElementByPos(s,this.getElementByPos(o)),this.setElementByPos(o,l),s+=1,o-=1}}unique(){if(this.i<=1)return this.i;let s=1,o=this.getElementByPos(0);for(let l=1;l<this.i;++l){let u=this.getElementByPos(l);u!==o&&(o=u,this.setElementByPos(s++,u))}for(;this.i>s;)this.popBack();return this.i}sort(s){let o=[];for(let l=0;l<this.i;++l)o.push(this.getElementByPos(l));o.sort(s);for(let l=0;l<this.i;++l)this.setElementByPos(l,o[l])}shrinkToFit(){if(this.i===0)return;let s=[];this.forEach(function(o){s.push(o)}),this.P=Math.max(Math.ceil(this.i/this.F),1),this.i=this.j=this.R=this.D=this.N=0,this.A=[];for(let o=0;o<this.P;++o)this.A.push(new Array(this.F));for(let o=0;o<s.length;++o)this.pushBack(s[o])}forEach(s){for(let o=0;o<this.i;++o)s(this.getElementByPos(o),o,this)}[Symbol.iterator](){return(function*(){for(let s=0;s<this.i;++s)yield this.getElementByPos(s)}).bind(this)()}},i=n;c.default=i}),Dc=pe(c=>{le(),ue(),ce(),Object.defineProperty(c,"t",{value:!0}),c.TreeNodeEnableIndex=c.TreeNode=void 0;var e=class{constructor(r,a){this.ee=1,this.u=void 0,this.l=void 0,this.U=void 0,this.W=void 0,this.tt=void 0,this.u=r,this.l=a}L(){let r=this;if(r.ee===1&&r.tt.tt===r)r=r.W;else if(r.U)for(r=r.U;r.W;)r=r.W;else{let a=r.tt;for(;a.U===r;)r=a,a=r.tt;r=a}return r}B(){let r=this;if(r.W){for(r=r.W;r.U;)r=r.U;return r}else{let a=r.tt;for(;a.W===r;)r=a,a=r.tt;return r.W!==a?a:r}}te(){let r=this.tt,a=this.W,n=a.U;return r.tt===this?r.tt=a:r.U===this?r.U=a:r.W=a,a.tt=r,a.U=this,this.tt=a,this.W=n,n&&(n.tt=this),a}se(){let r=this.tt,a=this.U,n=a.W;return r.tt===this?r.tt=a:r.U===this?r.U=a:r.W=a,a.tt=r,a.W=this,this.tt=a,this.U=n,n&&(n.tt=this),a}};c.TreeNode=e;var t=class extends e{constructor(){super(...arguments),this.rt=1}te(){let r=super.te();return this.ie(),r.ie(),r}se(){let r=super.se();return this.ie(),r.ie(),r}ie(){this.rt=1,this.U&&(this.rt+=this.U.rt),this.W&&(this.rt+=this.W.rt)}};c.TreeNodeEnableIndex=t}),ts=pe(c=>{le(),ue(),ce(),Object.defineProperty(c,"t",{value:!0}),c.default=void 0;var e=Dc(),t=ct(),r=ut(),a=class extends t.Container{constructor(i=function(o,l){return o<l?-1:o>l?1:0},s=!1){super(),this.Y=void 0,this.v=i,s?(this.re=e.TreeNodeEnableIndex,this.M=function(o,l,u){let d=this.ne(o,l,u);if(d){let p=d.tt;for(;p!==this.h;)p.rt+=1,p=p.tt;let y=this.he(d);if(y){let{parentNode:f,grandParent:m,curNode:b}=y;f.ie(),m.ie(),b.ie()}}return this.i},this.V=function(o){let l=this.fe(o);for(;l!==this.h;)l.rt-=1,l=l.tt}):(this.re=e.TreeNode,this.M=function(o,l,u){let d=this.ne(o,l,u);return d&&this.he(d),this.i},this.V=this.fe),this.h=new this.re}X(i,s){let o=this.h;for(;i;){let l=this.v(i.u,s);if(l<0)i=i.W;else if(l>0)o=i,i=i.U;else return i}return o}Z(i,s){let o=this.h;for(;i;)this.v(i.u,s)<=0?i=i.W:(o=i,i=i.U);return o}$(i,s){let o=this.h;for(;i;){let l=this.v(i.u,s);if(l<0)o=i,i=i.W;else if(l>0)i=i.U;else return i}return o}rr(i,s){let o=this.h;for(;i;)this.v(i.u,s)<0?(o=i,i=i.W):i=i.U;return o}ue(i){for(;;){let s=i.tt;if(s===this.h)return;if(i.ee===1){i.ee=0;return}if(i===s.U){let o=s.W;if(o.ee===1)o.ee=0,s.ee=1,s===this.Y?this.Y=s.te():s.te();else if(o.W&&o.W.ee===1){o.ee=s.ee,s.ee=0,o.W.ee=0,s===this.Y?this.Y=s.te():s.te();return}else o.U&&o.U.ee===1?(o.ee=1,o.U.ee=0,o.se()):(o.ee=1,i=s)}else{let o=s.U;if(o.ee===1)o.ee=0,s.ee=1,s===this.Y?this.Y=s.se():s.se();else if(o.U&&o.U.ee===1){o.ee=s.ee,s.ee=0,o.U.ee=0,s===this.Y?this.Y=s.se():s.se();return}else o.W&&o.W.ee===1?(o.ee=1,o.W.ee=0,o.te()):(o.ee=1,i=s)}}}fe(i){if(this.i===1)return this.clear(),this.h;let s=i;for(;s.U||s.W;){if(s.W)for(s=s.W;s.U;)s=s.U;else s=s.U;[i.u,s.u]=[s.u,i.u],[i.l,s.l]=[s.l,i.l],i=s}this.h.U===s?this.h.U=s.tt:this.h.W===s&&(this.h.W=s.tt),this.ue(s);let o=s.tt;return s===o.U?o.U=void 0:o.W=void 0,this.i-=1,this.Y.ee=0,o}oe(i,s){return i===void 0?!1:this.oe(i.U,s)||s(i)?!0:this.oe(i.W,s)}he(i){for(;;){let s=i.tt;if(s.ee===0)return;let o=s.tt;if(s===o.U){let l=o.W;if(l&&l.ee===1){if(l.ee=s.ee=0,o===this.Y)return;o.ee=1,i=o;continue}else if(i===s.W){if(i.ee=0,i.U&&(i.U.tt=s),i.W&&(i.W.tt=o),s.W=i.U,o.U=i.W,i.U=s,i.W=o,o===this.Y)this.Y=i,this.h.tt=i;else{let u=o.tt;u.U===o?u.U=i:u.W=i}return i.tt=o.tt,s.tt=i,o.tt=i,o.ee=1,{parentNode:s,grandParent:o,curNode:i}}else s.ee=0,o===this.Y?this.Y=o.se():o.se(),o.ee=1}else{let l=o.U;if(l&&l.ee===1){if(l.ee=s.ee=0,o===this.Y)return;o.ee=1,i=o;continue}else if(i===s.U){if(i.ee=0,i.U&&(i.U.tt=o),i.W&&(i.W.tt=s),o.W=i.U,s.U=i.W,i.U=o,i.W=s,o===this.Y)this.Y=i,this.h.tt=i;else{let u=o.tt;u.U===o?u.U=i:u.W=i}return i.tt=o.tt,s.tt=i,o.tt=i,o.ee=1,{parentNode:s,grandParent:o,curNode:i}}else s.ee=0,o===this.Y?this.Y=o.te():o.te(),o.ee=1}return}}ne(i,s,o){if(this.Y===void 0){this.i+=1,this.Y=new this.re(i,s),this.Y.ee=0,this.Y.tt=this.h,this.h.tt=this.Y,this.h.U=this.Y,this.h.W=this.Y;return}let l,u=this.h.U,d=this.v(u.u,i);if(d===0){u.l=s;return}else if(d>0)u.U=new this.re(i,s),u.U.tt=u,l=u.U,this.h.U=l;else{let p=this.h.W,y=this.v(p.u,i);if(y===0){p.l=s;return}else if(y<0)p.W=new this.re(i,s),p.W.tt=p,l=p.W,this.h.W=l;else{if(o!==void 0){let f=o.o;if(f!==this.h){let m=this.v(f.u,i);if(m===0){f.l=s;return}else if(m>0){let b=f.L(),k=this.v(b.u,i);if(k===0){b.l=s;return}else k<0&&(l=new this.re(i,s),b.W===void 0?(b.W=l,l.tt=b):(f.U=l,l.tt=f))}}}if(l===void 0)for(l=this.Y;;){let f=this.v(l.u,i);if(f>0){if(l.U===void 0){l.U=new this.re(i,s),l.U.tt=l,l=l.U;break}l=l.U}else if(f<0){if(l.W===void 0){l.W=new this.re(i,s),l.W.tt=l,l=l.W;break}l=l.W}else{l.l=s;return}}}}return this.i+=1,l}I(i,s){for(;i;){let o=this.v(i.u,s);if(o<0)i=i.W;else if(o>0)i=i.U;else return i}return i||this.h}clear(){this.i=0,this.Y=void 0,this.h.tt=void 0,this.h.U=this.h.W=void 0}updateKeyByIterator(i,s){let o=i.o;if(o===this.h&&(0,r.throwIteratorAccessError)(),this.i===1)return o.u=s,!0;if(o===this.h.U)return this.v(o.B().u,s)>0?(o.u=s,!0):!1;if(o===this.h.W)return this.v(o.L().u,s)<0?(o.u=s,!0):!1;let l=o.L().u;if(this.v(l,s)>=0)return!1;let u=o.B().u;return this.v(u,s)<=0?!1:(o.u=s,!0)}eraseElementByPos(i){if(i<0||i>this.i-1)throw new RangeError;let s=0,o=this;return this.oe(this.Y,function(l){return i===s?(o.V(l),!0):(s+=1,!1)}),this.i}eraseElementByKey(i){if(this.i===0)return!1;let s=this.I(this.Y,i);return s===this.h?!1:(this.V(s),!0)}eraseElementByIterator(i){let s=i.o;s===this.h&&(0,r.throwIteratorAccessError)();let o=s.W===void 0;return i.iteratorType===0?o&&i.next():(!o||s.U===void 0)&&i.next(),this.V(s),i}forEach(i){let s=0;for(let o of this)i(o,s++,this)}getElementByPos(i){if(i<0||i>this.i-1)throw new RangeError;let s,o=0;for(let l of this){if(o===i){s=l;break}o+=1}return s}getHeight(){if(this.i===0)return 0;let i=function(s){return s?Math.max(i(s.U),i(s.W))+1:0};return i(this.Y)}},n=a;c.default=n}),rs=pe(c=>{le(),ue(),ce(),Object.defineProperty(c,"t",{value:!0}),c.default=void 0;var e=ct(),t=ut(),r=class extends e.ContainerIterator{constructor(n,i,s){super(s),this.o=n,this.h=i,this.iteratorType===0?(this.pre=function(){return this.o===this.h.U&&(0,t.throwIteratorAccessError)(),this.o=this.o.L(),this},this.next=function(){return this.o===this.h&&(0,t.throwIteratorAccessError)(),this.o=this.o.B(),this}):(this.pre=function(){return this.o===this.h.W&&(0,t.throwIteratorAccessError)(),this.o=this.o.B(),this},this.next=function(){return this.o===this.h&&(0,t.throwIteratorAccessError)(),this.o=this.o.L(),this})}get index(){let n=this.o,i=this.h.tt;if(n===this.h)return i?i.rt-1:0;let s=0;for(n.U&&(s+=n.U.rt);n!==i;){let o=n.tt;n===o.W&&(s+=1,o.U&&(s+=o.U.rt)),n=o}return s}},a=r;c.default=a}),$c=pe(c=>{le(),ue(),ce(),Object.defineProperty(c,"t",{value:!0}),c.default=void 0;var e=a(ts()),t=a(rs()),r=ut();function a(o){return o&&o.t?o:{default:o}}var n=class $l extends t.default{constructor(l,u,d,p){super(l,u,p),this.container=d}get pointer(){return this.o===this.h&&(0,r.throwIteratorAccessError)(),this.o.u}copy(){return new $l(this.o,this.h,this.container,this.iteratorType)}},i=class extends e.default{constructor(o=[],l,u){super(l,u);let d=this;o.forEach(function(p){d.insert(p)})}*K(o){o!==void 0&&(yield*this.K(o.U),yield o.u,yield*this.K(o.W))}begin(){return new n(this.h.U||this.h,this.h,this)}end(){return new n(this.h,this.h,this)}rBegin(){return new n(this.h.W||this.h,this.h,this,1)}rEnd(){return new n(this.h,this.h,this,1)}front(){return this.h.U?this.h.U.u:void 0}back(){return this.h.W?this.h.W.u:void 0}insert(o,l){return this.M(o,void 0,l)}find(o){let l=this.I(this.Y,o);return new n(l,this.h,this)}lowerBound(o){let l=this.X(this.Y,o);return new n(l,this.h,this)}upperBound(o){let l=this.Z(this.Y,o);return new n(l,this.h,this)}reverseLowerBound(o){let l=this.$(this.Y,o);return new n(l,this.h,this)}reverseUpperBound(o){let l=this.rr(this.Y,o);return new n(l,this.h,this)}union(o){let l=this;return o.forEach(function(u){l.insert(u)}),this.i}[Symbol.iterator](){return this.K(this.Y)}},s=i;c.default=s}),Wc=pe(c=>{le(),ue(),ce(),Object.defineProperty(c,"t",{value:!0}),c.default=void 0;var e=a(ts()),t=a(rs()),r=ut();function a(o){return o&&o.t?o:{default:o}}var n=class Wl extends t.default{constructor(l,u,d,p){super(l,u,p),this.container=d}get pointer(){this.o===this.h&&(0,r.throwIteratorAccessError)();let l=this;return new Proxy([],{get(u,d){if(d==="0")return l.o.u;if(d==="1")return l.o.l},set(u,d,p){if(d!=="1")throw new TypeError("props must be 1");return l.o.l=p,!0}})}copy(){return new Wl(this.o,this.h,this.container,this.iteratorType)}},i=class extends e.default{constructor(o=[],l,u){super(l,u);let d=this;o.forEach(function(p){d.setElement(p[0],p[1])})}*K(o){o!==void 0&&(yield*this.K(o.U),yield[o.u,o.l],yield*this.K(o.W))}begin(){return new n(this.h.U||this.h,this.h,this)}end(){return new n(this.h,this.h,this)}rBegin(){return new n(this.h.W||this.h,this.h,this,1)}rEnd(){return new n(this.h,this.h,this,1)}front(){if(this.i===0)return;let o=this.h.U;return[o.u,o.l]}back(){if(this.i===0)return;let o=this.h.W;return[o.u,o.l]}lowerBound(o){let l=this.X(this.Y,o);return new n(l,this.h,this)}upperBound(o){let l=this.Z(this.Y,o);return new n(l,this.h,this)}reverseLowerBound(o){let l=this.$(this.Y,o);return new n(l,this.h,this)}reverseUpperBound(o){let l=this.rr(this.Y,o);return new n(l,this.h,this)}setElement(o,l,u){return this.M(o,l,u)}find(o){let l=this.I(this.Y,o);return new n(l,this.h,this)}getElementByKey(o){return this.I(this.Y,o).l}union(o){let l=this;return o.forEach(function(u){l.setElement(u[0],u[1])}),this.i}[Symbol.iterator](){return this.K(this.Y)}},s=i;c.default=s}),ns=pe(c=>{le(),ue(),ce(),Object.defineProperty(c,"t",{value:!0}),c.default=e;function e(t){let r=typeof t;return r==="object"&&t!==null||r==="function"}}),is=pe(c=>{le(),ue(),ce(),Object.defineProperty(c,"t",{value:!0}),c.HashContainerIterator=c.HashContainer=void 0;var e=ct(),t=a(ns()),r=ut();function a(s){return s&&s.t?s:{default:s}}var n=class extends e.ContainerIterator{constructor(s,o,l){super(l),this.o=s,this.h=o,this.iteratorType===0?(this.pre=function(){return this.o.L===this.h&&(0,r.throwIteratorAccessError)(),this.o=this.o.L,this},this.next=function(){return this.o===this.h&&(0,r.throwIteratorAccessError)(),this.o=this.o.B,this}):(this.pre=function(){return this.o.B===this.h&&(0,r.throwIteratorAccessError)(),this.o=this.o.B,this},this.next=function(){return this.o===this.h&&(0,r.throwIteratorAccessError)(),this.o=this.o.L,this})}};c.HashContainerIterator=n;var i=class extends e.Container{constructor(){super(),this.H=[],this.g={},this.HASH_TAG=Symbol("@@HASH_TAG"),Object.setPrototypeOf(this.g,null),this.h={},this.h.L=this.h.B=this.p=this._=this.h}V(s){let{L:o,B:l}=s;o.B=l,l.L=o,s===this.p&&(this.p=l),s===this._&&(this._=o),this.i-=1}M(s,o,l){l===void 0&&(l=(0,t.default)(s));let u;if(l){let d=s[this.HASH_TAG];if(d!==void 0)return this.H[d].l=o,this.i;Object.defineProperty(s,this.HASH_TAG,{value:this.H.length,configurable:!0}),u={u:s,l:o,L:this._,B:this.h},this.H.push(u)}else{let d=this.g[s];if(d)return d.l=o,this.i;u={u:s,l:o,L:this._,B:this.h},this.g[s]=u}return this.i===0?(this.p=u,this.h.B=u):this._.B=u,this._=u,this.h.L=u,++this.i}I(s,o){if(o===void 0&&(o=(0,t.default)(s)),o){let l=s[this.HASH_TAG];return l===void 0?this.h:this.H[l]}else return this.g[s]||this.h}clear(){let s=this.HASH_TAG;this.H.forEach(function(o){delete o.u[s]}),this.H=[],this.g={},Object.setPrototypeOf(this.g,null),this.i=0,this.p=this._=this.h.L=this.h.B=this.h}eraseElementByKey(s,o){let l;if(o===void 0&&(o=(0,t.default)(s)),o){let u=s[this.HASH_TAG];if(u===void 0)return!1;delete s[this.HASH_TAG],l=this.H[u],delete this.H[u]}else{if(l=this.g[s],l===void 0)return!1;delete this.g[s]}return this.V(l),!0}eraseElementByIterator(s){let o=s.o;return o===this.h&&(0,r.throwIteratorAccessError)(),this.V(o),s.next()}eraseElementByPos(s){if(s<0||s>this.i-1)throw new RangeError;let o=this.p;for(;s--;)o=o.B;return this.V(o),this.i}};c.HashContainer=i}),qc=pe(c=>{le(),ue(),ce(),Object.defineProperty(c,"t",{value:!0}),c.default=void 0;var e=is(),t=ut(),r=class ql extends e.HashContainerIterator{constructor(s,o,l,u){super(s,o,u),this.container=l}get pointer(){return this.o===this.h&&(0,t.throwIteratorAccessError)(),this.o.u}copy(){return new ql(this.o,this.h,this.container,this.iteratorType)}},a=class extends e.HashContainer{constructor(i=[]){super();let s=this;i.forEach(function(o){s.insert(o)})}begin(){return new r(this.p,this.h,this)}end(){return new r(this.h,this.h,this)}rBegin(){return new r(this._,this.h,this,1)}rEnd(){return new r(this.h,this.h,this,1)}front(){return this.p.u}back(){return this._.u}insert(i,s){return this.M(i,void 0,s)}getElementByPos(i){if(i<0||i>this.i-1)throw new RangeError;let s=this.p;for(;i--;)s=s.B;return s.u}find(i,s){let o=this.I(i,s);return new r(o,this.h,this)}forEach(i){let s=0,o=this.p;for(;o!==this.h;)i(o.u,s++,this),o=o.B}[Symbol.iterator](){return(function*(){let i=this.p;for(;i!==this.h;)yield i.u,i=i.B}).bind(this)()}},n=a;c.default=n}),Hc=pe(c=>{le(),ue(),ce(),Object.defineProperty(c,"t",{value:!0}),c.default=void 0;var e=is(),t=a(ns()),r=ut();function a(o){return o&&o.t?o:{default:o}}var n=class Hl extends e.HashContainerIterator{constructor(l,u,d,p){super(l,u,p),this.container=d}get pointer(){this.o===this.h&&(0,r.throwIteratorAccessError)();let l=this;return new Proxy([],{get(u,d){if(d==="0")return l.o.u;if(d==="1")return l.o.l},set(u,d,p){if(d!=="1")throw new TypeError("props must be 1");return l.o.l=p,!0}})}copy(){return new Hl(this.o,this.h,this.container,this.iteratorType)}},i=class extends e.HashContainer{constructor(o=[]){super();let l=this;o.forEach(function(u){l.setElement(u[0],u[1])})}begin(){return new n(this.p,this.h,this)}end(){return new n(this.h,this.h,this)}rBegin(){return new n(this._,this.h,this,1)}rEnd(){return new n(this.h,this.h,this,1)}front(){if(this.i!==0)return[this.p.u,this.p.l]}back(){if(this.i!==0)return[this._.u,this._.l]}setElement(o,l,u){return this.M(o,l,u)}getElementByKey(o,l){if(l===void 0&&(l=(0,t.default)(o)),l){let d=o[this.HASH_TAG];return d!==void 0?this.H[d].l:void 0}let u=this.g[o];return u?u.l:void 0}getElementByPos(o){if(o<0||o>this.i-1)throw new RangeError;let l=this.p;for(;o--;)l=l.B;return[l.u,l.l]}find(o,l){let u=this.I(o,l);return new n(u,this.h,this)}forEach(o){let l=0,u=this.p;for(;u!==this.h;)o([u.u,u.l],l++,this),u=u.B}[Symbol.iterator](){return(function*(){let o=this.p;for(;o!==this.h;)yield[o.u,o.l],o=o.B}).bind(this)()}},s=i;c.default=s}),zc=pe(c=>{le(),ue(),ce(),Object.defineProperty(c,"t",{value:!0}),Object.defineProperty(c,"Deque",{enumerable:!0,get:function(){return i.default}}),Object.defineProperty(c,"HashMap",{enumerable:!0,get:function(){return u.default}}),Object.defineProperty(c,"HashSet",{enumerable:!0,get:function(){return l.default}}),Object.defineProperty(c,"LinkList",{enumerable:!0,get:function(){return n.default}}),Object.defineProperty(c,"OrderedMap",{enumerable:!0,get:function(){return o.default}}),Object.defineProperty(c,"OrderedSet",{enumerable:!0,get:function(){return s.default}}),Object.defineProperty(c,"PriorityQueue",{enumerable:!0,get:function(){return r.default}}),Object.defineProperty(c,"Queue",{enumerable:!0,get:function(){return t.default}}),Object.defineProperty(c,"Stack",{enumerable:!0,get:function(){return e.default}}),Object.defineProperty(c,"Vector",{enumerable:!0,get:function(){return a.default}});var e=d(jc()),t=d(Lc()),r=d(Nc()),a=d(Uc()),n=d(Bc()),i=d(Fc()),s=d($c()),o=d(Wc()),l=d(qc()),u=d(Hc());function d(p){return p&&p.t?p:{default:p}}}),Kc=pe((c,e)=>{le(),ue(),ce();var t=zc().OrderedSet,r=lt()("number-allocator:trace"),a=lt()("number-allocator:error");function n(s,o){this.low=s,this.high=o}n.prototype.equals=function(s){return this.low===s.low&&this.high===s.high},n.prototype.compare=function(s){return this.low<s.low&&this.high<s.low?-1:s.low<this.low&&s.high<this.low?1:0};function i(s,o){if(!(this instanceof i))return new i(s,o);this.min=s,this.max=o,this.ss=new t([],(l,u)=>l.compare(u)),r("Create"),this.clear()}i.prototype.firstVacant=function(){return this.ss.size()===0?null:this.ss.front().low},i.prototype.alloc=function(){if(this.ss.size()===0)return r("alloc():empty"),null;let s=this.ss.begin(),o=s.pointer.low,l=s.pointer.high,u=o;return u+1<=l?this.ss.updateKeyByIterator(s,new n(o+1,l)):this.ss.eraseElementByPos(0),r("alloc():"+u),u},i.prototype.use=function(s){let o=new n(s,s),l=this.ss.lowerBound(o);if(!l.equals(this.ss.end())){let u=l.pointer.low,d=l.pointer.high;return l.pointer.equals(o)?(this.ss.eraseElementByIterator(l),r("use():"+s),!0):u>s?!1:u===s?(this.ss.updateKeyByIterator(l,new n(u+1,d)),r("use():"+s),!0):d===s?(this.ss.updateKeyByIterator(l,new n(u,d-1)),r("use():"+s),!0):(this.ss.updateKeyByIterator(l,new n(s+1,d)),this.ss.insert(new n(u,s-1)),r("use():"+s),!0)}return r("use():failed"),!1},i.prototype.free=function(s){if(s<this.min||s>this.max){a("free():"+s+" is out of range");return}let o=new n(s,s),l=this.ss.upperBound(o);if(l.equals(this.ss.end())){if(l.equals(this.ss.begin())){this.ss.insert(o);return}l.pre();let u=l.pointer.high;l.pointer.high+1===s?this.ss.updateKeyByIterator(l,new n(u,s)):this.ss.insert(o)}else if(l.equals(this.ss.begin()))if(s+1===l.pointer.low){let u=l.pointer.high;this.ss.updateKeyByIterator(l,new n(s,u))}else this.ss.insert(o);else{let u=l.pointer.low,d=l.pointer.high;l.pre();let p=l.pointer.low;l.pointer.high+1===s?s+1===u?(this.ss.eraseElementByIterator(l),this.ss.updateKeyByIterator(l,new n(p,d))):this.ss.updateKeyByIterator(l,new n(p,s)):s+1===u?(this.ss.eraseElementByIterator(l.next()),this.ss.insert(new n(s,d))):this.ss.insert(o)}r("free():"+s)},i.prototype.clear=function(){r("clear()"),this.ss.clear(),this.ss.insert(new n(this.min,this.max))},i.prototype.intervalCount=function(){return this.ss.size()},i.prototype.dump=function(){console.log("length:"+this.ss.size());for(let s of this.ss)console.log(s)},e.exports=i}),os=pe((c,e)=>{le(),ue(),ce();var t=Kc();e.exports.NumberAllocator=t}),Vc=pe(c=>{le(),ue(),ce(),Object.defineProperty(c,"__esModule",{value:!0});var e=Rc(),t=os(),r=class{aliasToTopic;topicToAlias;max;numberAllocator;length;constructor(a){a>0&&(this.aliasToTopic=new e.LRUCache({max:a}),this.topicToAlias={},this.numberAllocator=new t.NumberAllocator(1,a),this.max=a,this.length=0)}put(a,n){if(n===0||n>this.max)return!1;let i=this.aliasToTopic.get(n);return i&&delete this.topicToAlias[i],this.aliasToTopic.set(n,a),this.topicToAlias[a]=n,this.numberAllocator.use(n),this.length=this.aliasToTopic.size,!0}getTopicByAlias(a){return this.aliasToTopic.get(a)}getAliasByTopic(a){let n=this.topicToAlias[a];return typeof n<"u"&&this.aliasToTopic.get(n),n}clear(){this.aliasToTopic.clear(),this.topicToAlias={},this.numberAllocator.clear(),this.length=0}getLruAlias(){return this.numberAllocator.firstVacant()||[...this.aliasToTopic.keys()][this.aliasToTopic.size-1]}};c.default=r}),Gc=pe(c=>{le(),ue(),ce();var e=c&&c.__importDefault||function(i){return i&&i.__esModule?i:{default:i}};Object.defineProperty(c,"__esModule",{value:!0});var t=sr(),r=e(Vc()),a=Rt(),n=(i,s)=>{i.log("_handleConnack");let{options:o}=i,l=o.protocolVersion===5?s.reasonCode:s.returnCode;if(clearTimeout(i.connackTimer),delete i.topicAliasSend,s.properties){if(s.properties.topicAliasMaximum){if(s.properties.topicAliasMaximum>65535){i.emit("error",new Error("topicAliasMaximum from broker is out of range"));return}s.properties.topicAliasMaximum>0&&(i.topicAliasSend=new r.default(s.properties.topicAliasMaximum))}s.properties.serverKeepAlive&&o.keepalive&&(o.keepalive=s.properties.serverKeepAlive),s.properties.maximumPacketSize&&(o.properties||(o.properties={}),o.properties.maximumPacketSize=s.properties.maximumPacketSize)}if(l===0)i.reconnecting=!1,i._onConnect(s);else if(l>0){let u=new a.ErrorWithReasonCode(`Connection refused: ${t.ReasonCodes[l]}`,l);i.emit("error",u),i.options.reconnectOnConnackError&&i._cleanUp(!0)}};c.default=n}),Yc=pe(c=>{le(),ue(),ce(),Object.defineProperty(c,"__esModule",{value:!0});var e=(t,r,a)=>{t.log("handling pubrel packet");let n=typeof a<"u"?a:t.noop,{messageId:i}=r,s={cmd:"pubcomp",messageId:i};t.incomingStore.get(r,(o,l)=>{o?t._sendPacket(s,n):(t.emit("message",l.topic,l.payload,l),t.handleMessage(l,u=>{if(u)return n(u);t.incomingStore.del(l,t.noop),t._sendPacket(s,n)}))})};c.default=e}),Qc=pe(c=>{le(),ue(),ce();var e=c&&c.__importDefault||function(o){return o&&o.__esModule?o:{default:o}};Object.defineProperty(c,"__esModule",{value:!0});var t=e(Oc()),r=e(Mc()),a=e(Gc()),n=e(sr()),i=e(Yc()),s=(o,l,u)=>{let{options:d}=o;if(d.protocolVersion===5&&d.properties&&d.properties.maximumPacketSize&&d.properties.maximumPacketSize<l.length)return o.emit("error",new Error(`exceeding packets size ${l.cmd}`)),o.end({reasonCode:149,properties:{reasonString:"Maximum packet size was exceeded"}}),o;switch(o.log("_handlePacket :: emitting packetreceive"),o.emit("packetreceive",l),l.cmd){case"publish":(0,t.default)(o,l,u);break;case"puback":case"pubrec":case"pubcomp":case"suback":case"unsuback":o.reschedulePing(),(0,n.default)(o,l),u();break;case"pubrel":o.reschedulePing(),(0,i.default)(o,l,u);break;case"connack":(0,a.default)(o,l),u();break;case"auth":o.reschedulePing(),(0,r.default)(o,l),u();break;case"pingresp":o.log("_handlePacket :: received pingresp"),o.reschedulePing(!0),u();break;case"disconnect":o.emit("disconnect",l),u();break;default:o.log("_handlePacket :: unknown command"),u();break}};c.default=s}),ss=pe(c=>{le(),ue(),ce(),Object.defineProperty(c,"__esModule",{value:!0});var e=class{nextId;constructor(){this.nextId=Math.max(1,Math.floor(Math.random()*65535))}allocate(){let t=this.nextId++;return this.nextId===65536&&(this.nextId=1),t}getLastAllocated(){return this.nextId===1?65535:this.nextId-1}register(t){return!0}deallocate(t){}clear(){}};c.default=e}),Jc=pe(c=>{le(),ue(),ce(),Object.defineProperty(c,"__esModule",{value:!0});var e=class{aliasToTopic;max;length;constructor(t){this.aliasToTopic={},this.max=t}put(t,r){return r===0||r>this.max?!1:(this.aliasToTopic[r]=t,this.length=Object.keys(this.aliasToTopic).length,!0)}getTopicByAlias(t){return this.aliasToTopic[t]}clear(){this.aliasToTopic={}}};c.default=e}),Xc=pe(c=>{le(),ue(),ce();var e=c&&c.__importDefault||function(n){return n&&n.__esModule?n:{default:n}};Object.defineProperty(c,"__esModule",{value:!0}),c.TypedEventEmitter=void 0;var t=e((kt(),Pe(pt))),r=Rt(),a=class{};c.TypedEventEmitter=a,(0,r.applyMixin)(a,t.default)}),ar=pe((c,e)=>{le(),ue(),ce();function t(r){"@babel/helpers - typeof";return e.exports=t=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(a){return typeof a}:function(a){return a&&typeof Symbol=="function"&&a.constructor===Symbol&&a!==Symbol.prototype?"symbol":typeof a},e.exports.__esModule=!0,e.exports.default=e.exports,t(r)}e.exports=t,e.exports.__esModule=!0,e.exports.default=e.exports}),Zc=pe((c,e)=>{le(),ue(),ce();var t=ar().default;function r(a,n){if(t(a)!="object"||!a)return a;var i=a[Symbol.toPrimitive];if(i!==void 0){var s=i.call(a,n||"default");if(t(s)!="object")return s;throw new TypeError("@@toPrimitive must return a primitive value.")}return(n==="string"?String:Number)(a)}e.exports=r,e.exports.__esModule=!0,e.exports.default=e.exports}),eu=pe((c,e)=>{le(),ue(),ce();var t=ar().default,r=Zc();function a(n){var i=r(n,"string");return t(i)=="symbol"?i:i+""}e.exports=a,e.exports.__esModule=!0,e.exports.default=e.exports}),tu=pe((c,e)=>{le(),ue(),ce();var t=eu();function r(a,n,i){return(n=t(n))in a?Object.defineProperty(a,n,{value:i,enumerable:!0,configurable:!0,writable:!0}):a[n]=i,a}e.exports=r,e.exports.__esModule=!0,e.exports.default=e.exports}),ru=pe((c,e)=>{le(),ue(),ce();function t(r){if(Array.isArray(r))return r}e.exports=t,e.exports.__esModule=!0,e.exports.default=e.exports}),nu=pe((c,e)=>{le(),ue(),ce();function t(r,a){var n=r==null?null:typeof Symbol<"u"&&r[Symbol.iterator]||r["@@iterator"];if(n!=null){var i,s,o,l,u=[],d=!0,p=!1;try{if(o=(n=n.call(r)).next,a===0){if(Object(n)!==n)return;d=!1}else for(;!(d=(i=o.call(n)).done)&&(u.push(i.value),u.length!==a);d=!0);}catch(y){p=!0,s=y}finally{try{if(!d&&n.return!=null&&(l=n.return(),Object(l)!==l))return}finally{if(p)throw s}}return u}}e.exports=t,e.exports.__esModule=!0,e.exports.default=e.exports}),iu=pe((c,e)=>{le(),ue(),ce();function t(r,a){(a==null||a>r.length)&&(a=r.length);for(var n=0,i=Array(a);n<a;n++)i[n]=r[n];return i}e.exports=t,e.exports.__esModule=!0,e.exports.default=e.exports}),ou=pe((c,e)=>{le(),ue(),ce();var t=iu();function r(a,n){if(a){if(typeof a=="string")return t(a,n);var i={}.toString.call(a).slice(8,-1);return i==="Object"&&a.constructor&&(i=a.constructor.name),i==="Map"||i==="Set"?Array.from(a):i==="Arguments"||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(i)?t(a,n):void 0}}e.exports=r,e.exports.__esModule=!0,e.exports.default=e.exports}),su=pe((c,e)=>{le(),ue(),ce();function t(){throw new TypeError(`Invalid attempt to destructure non-iterable instance.
3
+ In order to be iterable, non-array objects must have a [Symbol.iterator]() method.`)}e.exports=t,e.exports.__esModule=!0,e.exports.default=e.exports}),au=pe((c,e)=>{le(),ue(),ce();var t=ru(),r=nu(),a=ou(),n=su();function i(s,o){return t(s)||r(s,o)||a(s,o)||n()}e.exports=i,e.exports.__esModule=!0,e.exports.default=e.exports}),as=pe((c,e)=>{le(),ue(),ce(),(function(t,r){typeof c=="object"&&typeof e<"u"?r(c):typeof define=="function"&&define.amd?define(["exports"],r):(t=typeof globalThis<"u"?globalThis:t||self,r(t.fastUniqueNumbers={}))})(c,function(t){var r=function(y){return function(f){var m=y(f);return f.add(m),m}},a=function(y){return function(f,m){return y.set(f,m),m}},n=Number.MAX_SAFE_INTEGER===void 0?9007199254740991:Number.MAX_SAFE_INTEGER,i=536870912,s=i*2,o=function(y,f){return function(m){var b=f.get(m),k=b===void 0?m.size:b<s?b+1:0;if(!m.has(k))return y(m,k);if(m.size<i){for(;m.has(k);)k=Math.floor(Math.random()*s);return y(m,k)}if(m.size>n)throw new Error("Congratulations, you created a collection of unique numbers which uses all available integers!");for(;m.has(k);)k=Math.floor(Math.random()*n);return y(m,k)}},l=new WeakMap,u=a(l),d=o(u,l),p=r(d);t.addUniqueNumber=p,t.generateUniqueNumber=d})}),lu=pe((c,e)=>{le(),ue(),ce();function t(a,n,i,s,o,l,u){try{var d=a[l](u),p=d.value}catch(y){return void i(y)}d.done?n(p):Promise.resolve(p).then(s,o)}function r(a){return function(){var n=this,i=arguments;return new Promise(function(s,o){var l=a.apply(n,i);function u(p){t(l,s,o,u,d,"next",p)}function d(p){t(l,s,o,u,d,"throw",p)}u(void 0)})}}e.exports=r,e.exports.__esModule=!0,e.exports.default=e.exports}),ls=pe((c,e)=>{le(),ue(),ce();function t(r,a){this.v=r,this.k=a}e.exports=t,e.exports.__esModule=!0,e.exports.default=e.exports}),cs=pe((c,e)=>{le(),ue(),ce();function t(r,a,n,i){var s=Object.defineProperty;try{s({},"",{})}catch{s=0}e.exports=t=function(o,l,u,d){function p(y,f){t(o,y,function(m){return this._invoke(y,f,m)})}l?s?s(o,l,{value:u,enumerable:!d,configurable:!d,writable:!d}):o[l]=u:(p("next",0),p("throw",1),p("return",2))},e.exports.__esModule=!0,e.exports.default=e.exports,t(r,a,n,i)}e.exports=t,e.exports.__esModule=!0,e.exports.default=e.exports}),us=pe((c,e)=>{le(),ue(),ce();var t=cs();function r(){var a,n,i=typeof Symbol=="function"?Symbol:{},s=i.iterator||"@@iterator",o=i.toStringTag||"@@toStringTag";function l(k,g,_,S){var v=g&&g.prototype instanceof d?g:d,x=Object.create(v.prototype);return t(x,"_invoke",(function(E,I,M){var O,B,T,W=0,F=M||[],N=!1,ae={p:0,n:0,v:a,a:Y,f:Y.bind(a,4),d:function(K,re){return O=K,B=0,T=a,ae.n=re,u}};function Y(K,re){for(B=K,T=re,n=0;!N&&W&&!D&&n<F.length;n++){var D,Z=F[n],P=ae.p,J=Z[2];K>3?(D=J===re)&&(T=Z[(B=Z[4])?5:(B=3,3)],Z[4]=Z[5]=a):Z[0]<=P&&((D=K<2&&P<Z[1])?(B=0,ae.v=re,ae.n=Z[1]):P<J&&(D=K<3||Z[0]>re||re>J)&&(Z[4]=K,Z[5]=re,ae.n=J,B=0))}if(D||K>1)return u;throw N=!0,re}return function(K,re,D){if(W>1)throw TypeError("Generator is already running");for(N&&re===1&&Y(re,D),B=re,T=D;(n=B<2?a:T)||!N;){O||(B?B<3?(B>1&&(ae.n=-1),Y(B,T)):ae.n=T:ae.v=T);try{if(W=2,O){if(B||(K="next"),n=O[K]){if(!(n=n.call(O,T)))throw TypeError("iterator result is not an object");if(!n.done)return n;T=n.value,B<2&&(B=0)}else B===1&&(n=O.return)&&n.call(O),B<2&&(T=TypeError("The iterator does not provide a '"+K+"' method"),B=1);O=a}else if((n=(N=ae.n<0)?T:E.call(I,ae))!==u)break}catch(Z){O=a,B=1,T=Z}finally{W=1}}return{value:n,done:N}}})(k,_,S),!0),x}var u={};function d(){}function p(){}function y(){}n=Object.getPrototypeOf;var f=[][s]?n(n([][s]())):(t(n={},s,function(){return this}),n),m=y.prototype=d.prototype=Object.create(f);function b(k){return Object.setPrototypeOf?Object.setPrototypeOf(k,y):(k.__proto__=y,t(k,o,"GeneratorFunction")),k.prototype=Object.create(m),k}return p.prototype=y,t(m,"constructor",y),t(y,"constructor",p),p.displayName="GeneratorFunction",t(y,o,"GeneratorFunction"),t(m),t(m,o,"Generator"),t(m,s,function(){return this}),t(m,"toString",function(){return"[object Generator]"}),(e.exports=r=function(){return{w:l,m:b}},e.exports.__esModule=!0,e.exports.default=e.exports)()}e.exports=r,e.exports.__esModule=!0,e.exports.default=e.exports}),hs=pe((c,e)=>{le(),ue(),ce();var t=ls(),r=cs();function a(n,i){function s(l,u,d,p){try{var y=n[l](u),f=y.value;return f instanceof t?i.resolve(f.v).then(function(m){s("next",m,d,p)},function(m){s("throw",m,d,p)}):i.resolve(f).then(function(m){y.value=m,d(y)},function(m){return s("throw",m,d,p)})}catch(m){p(m)}}var o;this.next||(r(a.prototype),r(a.prototype,typeof Symbol=="function"&&Symbol.asyncIterator||"@asyncIterator",function(){return this})),r(this,"_invoke",function(l,u,d){function p(){return new i(function(y,f){s(l,d,y,f)})}return o=o?o.then(p,p):p()},!0)}e.exports=a,e.exports.__esModule=!0,e.exports.default=e.exports}),fs=pe((c,e)=>{le(),ue(),ce();var t=us(),r=hs();function a(n,i,s,o,l){return new r(t().w(n,i,s,o),l||Promise)}e.exports=a,e.exports.__esModule=!0,e.exports.default=e.exports}),cu=pe((c,e)=>{le(),ue(),ce();var t=fs();function r(a,n,i,s,o){var l=t(a,n,i,s,o);return l.next().then(function(u){return u.done?u.value:l.next()})}e.exports=r,e.exports.__esModule=!0,e.exports.default=e.exports}),uu=pe((c,e)=>{le(),ue(),ce();function t(r){var a=Object(r),n=[];for(var i in a)n.unshift(i);return function s(){for(;n.length;)if((i=n.pop())in a)return s.value=i,s.done=!1,s;return s.done=!0,s}}e.exports=t,e.exports.__esModule=!0,e.exports.default=e.exports}),hu=pe((c,e)=>{le(),ue(),ce();var t=ar().default;function r(a){if(a!=null){var n=a[typeof Symbol=="function"&&Symbol.iterator||"@@iterator"],i=0;if(n)return n.call(a);if(typeof a.next=="function")return a;if(!isNaN(a.length))return{next:function(){return a&&i>=a.length&&(a=void 0),{value:a&&a[i++],done:!a}}}}throw new TypeError(t(a)+" is not iterable")}e.exports=r,e.exports.__esModule=!0,e.exports.default=e.exports}),fu=pe((c,e)=>{le(),ue(),ce();var t=ls(),r=us(),a=cu(),n=fs(),i=hs(),s=uu(),o=hu();function l(){var u=r(),d=u.m(l),p=(Object.getPrototypeOf?Object.getPrototypeOf(d):d.__proto__).constructor;function y(b){var k=typeof b=="function"&&b.constructor;return!!k&&(k===p||(k.displayName||k.name)==="GeneratorFunction")}var f={throw:1,return:2,break:3,continue:3};function m(b){var k,g;return function(_){k||(k={stop:function(){return g(_.a,2)},catch:function(){return _.v},abrupt:function(S,v){return g(_.a,f[S],v)},delegateYield:function(S,v,x){return k.resultName=v,g(_.d,o(S),x)},finish:function(S){return g(_.f,S)}},g=function(S,v,x){_.p=k.prev,_.n=k.next;try{return S(v,x)}finally{k.next=_.n}}),k.resultName&&(k[k.resultName]=_.v,k.resultName=void 0),k.sent=_.v,k.next=_.n;try{return b.call(this,k)}finally{_.p=k.prev,_.n=k.next}}}return(e.exports=l=function(){return{wrap:function(b,k,g,_){return u.w(m(b),k,g,_&&_.reverse())},isGeneratorFunction:y,mark:u.m,awrap:function(b,k){return new t(b,k)},AsyncIterator:i,async:function(b,k,g,_,S){return(y(k)?n:a)(m(b),k,g,_,S)},keys:s,values:o}},e.exports.__esModule=!0,e.exports.default=e.exports)()}e.exports=l,e.exports.__esModule=!0,e.exports.default=e.exports}),du=pe((c,e)=>{le(),ue(),ce();var t=fu()();e.exports=t;try{regeneratorRuntime=t}catch{typeof globalThis=="object"?globalThis.regeneratorRuntime=t:Function("r","regeneratorRuntime = r")(t)}}),pu=pe((c,e)=>{le(),ue(),ce(),(function(t,r){typeof c=="object"&&typeof e<"u"?r(c,tu(),au(),as(),lu(),du()):typeof define=="function"&&define.amd?define(["exports","@babel/runtime/helpers/defineProperty","@babel/runtime/helpers/slicedToArray","fast-unique-numbers","@babel/runtime/helpers/asyncToGenerator","@babel/runtime/regenerator"],r):(t=typeof globalThis<"u"?globalThis:t||self,r(t.brokerFactory={},t._defineProperty,t._slicedToArray,t.fastUniqueNumbers,t._asyncToGenerator,t._regeneratorRuntime))})(c,function(t,r,a,n,i,s){var o=function(g){return typeof g.start=="function"},l=new WeakMap;function u(g,_){var S=Object.keys(g);if(Object.getOwnPropertySymbols){var v=Object.getOwnPropertySymbols(g);_&&(v=v.filter(function(x){return Object.getOwnPropertyDescriptor(g,x).enumerable})),S.push.apply(S,v)}return S}function d(g){for(var _=1;_<arguments.length;_++){var S=arguments[_]!=null?arguments[_]:{};_%2?u(Object(S),!0).forEach(function(v){r(g,v,S[v])}):Object.getOwnPropertyDescriptors?Object.defineProperties(g,Object.getOwnPropertyDescriptors(S)):u(Object(S)).forEach(function(v){Object.defineProperty(g,v,Object.getOwnPropertyDescriptor(S,v))})}return g}var p=function(g){return d(d({},g),{},{connect:function(_){var S=_.call;return i(s.mark(function v(){var x,E,I,M;return s.wrap(function(O){for(;;)switch(O.prev=O.next){case 0:return x=new MessageChannel,E=x.port1,I=x.port2,O.next=1,S("connect",{port:E},[E]);case 1:return M=O.sent,l.set(I,M),O.abrupt("return",I);case 2:case"end":return O.stop()}},v)}))},disconnect:function(_){var S=_.call;return(function(){var v=i(s.mark(function x(E){var I;return s.wrap(function(M){for(;;)switch(M.prev=M.next){case 0:if(I=l.get(E),I!==void 0){M.next=1;break}throw new Error("The given port is not connected.");case 1:return M.next=2,S("disconnect",{portId:I});case 2:case"end":return M.stop()}},x)}));return function(x){return v.apply(this,arguments)}})()},isSupported:function(_){var S=_.call;return function(){return S("isSupported")}}})};function y(g,_){var S=Object.keys(g);if(Object.getOwnPropertySymbols){var v=Object.getOwnPropertySymbols(g);_&&(v=v.filter(function(x){return Object.getOwnPropertyDescriptor(g,x).enumerable})),S.push.apply(S,v)}return S}function f(g){for(var _=1;_<arguments.length;_++){var S=arguments[_]!=null?arguments[_]:{};_%2?y(Object(S),!0).forEach(function(v){r(g,v,S[v])}):Object.getOwnPropertyDescriptors?Object.defineProperties(g,Object.getOwnPropertyDescriptors(S)):y(Object(S)).forEach(function(v){Object.defineProperty(g,v,Object.getOwnPropertyDescriptor(S,v))})}return g}var m=new WeakMap,b=function(g){if(m.has(g))return m.get(g);var _=new Map;return m.set(g,_),_},k=function(g){var _=p(g);return function(S){var v=b(S);S.addEventListener("message",function(F){var N=F.data,ae=N.id;if(ae!==null&&v.has(ae)){var Y=v.get(ae),K=Y.reject,re=Y.resolve;v.delete(ae),N.error===void 0?re(N.result):K(new Error(N.error.message))}}),o(S)&&S.start();for(var x=function(F){var N=arguments.length>1&&arguments[1]!==void 0?arguments[1]:null,ae=arguments.length>2&&arguments[2]!==void 0?arguments[2]:[];return new Promise(function(Y,K){var re=n.generateUniqueNumber(v);v.set(re,{reject:K,resolve:Y}),N===null?S.postMessage({id:re,method:F},ae):S.postMessage({id:re,method:F,params:N},ae)})},E=function(F,N){var ae=arguments.length>2&&arguments[2]!==void 0?arguments[2]:[];S.postMessage({id:null,method:F,params:N},ae)},I={},M=0,O=Object.entries(_);M<O.length;M++){var B=a(O[M],2),T=B[0],W=B[1];I=f(f({},I),{},r({},T,W({call:x,notify:E})))}return f({},I)}};t.createBroker=k})}),gu=pe((c,e)=>{le(),ue(),ce(),(function(t,r){typeof c=="object"&&typeof e<"u"?r(c,ar(),pu(),as()):typeof define=="function"&&define.amd?define(["exports","@babel/runtime/helpers/typeof","broker-factory","fast-unique-numbers"],r):(t=typeof globalThis<"u"?globalThis:t||self,r(t.workerTimersBroker={},t._typeof,t.brokerFactory,t.fastUniqueNumbers))})(c,function(t,r,a,n){var i=new Map([[0,null]]),s=new Map([[0,null]]),o=a.createBroker({clearInterval:function(u){var d=u.call;return function(p){r(i.get(p))==="symbol"&&(i.set(p,null),d("clear",{timerId:p,timerType:"interval"}).then(function(){i.delete(p)}))}},clearTimeout:function(u){var d=u.call;return function(p){r(s.get(p))==="symbol"&&(s.set(p,null),d("clear",{timerId:p,timerType:"timeout"}).then(function(){s.delete(p)}))}},setInterval:function(u){var d=u.call;return function(p){for(var y=arguments.length>1&&arguments[1]!==void 0?arguments[1]:0,f=arguments.length,m=new Array(f>2?f-2:0),b=2;b<f;b++)m[b-2]=arguments[b];var k=Symbol(),g=n.generateUniqueNumber(i);i.set(g,k);var _=function(){return d("set",{delay:y,now:performance.timeOrigin+performance.now(),timerId:g,timerType:"interval"}).then(function(){var S=i.get(g);if(S===void 0)throw new Error("The timer is in an undefined state.");S===k&&(p.apply(void 0,m),i.get(g)===k&&_())})};return _(),g}},setTimeout:function(u){var d=u.call;return function(p){for(var y=arguments.length>1&&arguments[1]!==void 0?arguments[1]:0,f=arguments.length,m=new Array(f>2?f-2:0),b=2;b<f;b++)m[b-2]=arguments[b];var k=Symbol(),g=n.generateUniqueNumber(s);return s.set(g,k),d("set",{delay:y,now:performance.timeOrigin+performance.now(),timerId:g,timerType:"timeout"}).then(function(){var _=s.get(g);if(_===void 0)throw new Error("The timer is in an undefined state.");_===k&&(s.delete(g),p.apply(void 0,m))}),g}}}),l=function(u){var d=new Worker(u);return o(d)};t.load=l,t.wrap=o})}),mu=pe((c,e)=>{le(),ue(),ce(),(function(t,r){typeof c=="object"&&typeof e<"u"?r(c,gu()):typeof define=="function"&&define.amd?define(["exports","worker-timers-broker"],r):(t=typeof globalThis<"u"?globalThis:t||self,r(t.workerTimers={},t.workerTimersBroker))})(c,function(t,r){var a=function(d,p){var y=null;return function(){if(y!==null)return y;var f=new Blob([p],{type:"application/javascript; charset=utf-8"}),m=URL.createObjectURL(f);return y=d(m),setTimeout(function(){return URL.revokeObjectURL(m)}),y}},n=`(()=>{var e={45:(e,t,r)=>{var n=r(738).default;e.exports=function(e,t){if("object"!=n(e)||!e)return e;var r=e[Symbol.toPrimitive];if(void 0!==r){var o=r.call(e,t||"default");if("object"!=n(o))return o;throw new TypeError("@@toPrimitive must return a primitive value.")}return("string"===t?String:Number)(e)},e.exports.__esModule=!0,e.exports.default=e.exports},79:e=>{e.exports=function(e,t){(null==t||t>e.length)&&(t=e.length);for(var r=0,n=Array(t);r<t;r++)n[r]=e[r];return n},e.exports.__esModule=!0,e.exports.default=e.exports},122:(e,t,r)=>{var n=r(79);e.exports=function(e,t){if(e){if("string"==typeof e)return n(e,t);var r={}.toString.call(e).slice(8,-1);return"Object"===r&&e.constructor&&(r=e.constructor.name),"Map"===r||"Set"===r?Array.from(e):"Arguments"===r||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(r)?n(e,t):void 0}},e.exports.__esModule=!0,e.exports.default=e.exports},156:e=>{e.exports=function(e,t){var r=null==e?null:"undefined"!=typeof Symbol&&e[Symbol.iterator]||e["@@iterator"];if(null!=r){var n,o,u,a,i=[],s=!0,c=!1;try{if(u=(r=r.call(e)).next,0===t){if(Object(r)!==r)return;s=!1}else for(;!(s=(n=u.call(r)).done)&&(i.push(n.value),i.length!==t);s=!0);}catch(e){c=!0,o=e}finally{try{if(!s&&null!=r.return&&(a=r.return(),Object(a)!==a))return}finally{if(c)throw o}}return i}},e.exports.__esModule=!0,e.exports.default=e.exports},172:e=>{e.exports=function(e,t){this.v=e,this.k=t},e.exports.__esModule=!0,e.exports.default=e.exports},293:e=>{function t(e,t,r,n,o,u,a){try{var i=e[u](a),s=i.value}catch(e){return void r(e)}i.done?t(s):Promise.resolve(s).then(n,o)}e.exports=function(e){return function(){var r=this,n=arguments;return new Promise((function(o,u){var a=e.apply(r,n);function i(e){t(a,o,u,i,s,"next",e)}function s(e){t(a,o,u,i,s,"throw",e)}i(void 0)}))}},e.exports.__esModule=!0,e.exports.default=e.exports},373:e=>{e.exports=function(e){var t=Object(e),r=[];for(var n in t)r.unshift(n);return function e(){for(;r.length;)if((n=r.pop())in t)return e.value=n,e.done=!1,e;return e.done=!0,e}},e.exports.__esModule=!0,e.exports.default=e.exports},389:function(e,t){!function(e){"use strict";var t=function(e){return function(t){var r=e(t);return t.add(r),r}},r=function(e){return function(t,r){return e.set(t,r),r}},n=void 0===Number.MAX_SAFE_INTEGER?9007199254740991:Number.MAX_SAFE_INTEGER,o=536870912,u=2*o,a=function(e,t){return function(r){var a=t.get(r),i=void 0===a?r.size:a<u?a+1:0;if(!r.has(i))return e(r,i);if(r.size<o){for(;r.has(i);)i=Math.floor(Math.random()*u);return e(r,i)}if(r.size>n)throw new Error("Congratulations, you created a collection of unique numbers which uses all available integers!");for(;r.has(i);)i=Math.floor(Math.random()*n);return e(r,i)}},i=new WeakMap,s=r(i),c=a(s,i),f=t(c);e.addUniqueNumber=f,e.generateUniqueNumber=c}(t)},472:function(e,t,r){!function(e,t,r,n){"use strict";var o=function(e,t){return function(r){var o=t.get(r);if(void 0===o)return Promise.resolve(!1);var u=n(o,2),a=u[0],i=u[1];return e(a),t.delete(r),i(!1),Promise.resolve(!0)}},u=function(e,t){var r=function(n,o,u,a){var i=n-e.now();i>0?o.set(a,[t(r,i,n,o,u,a),u]):(o.delete(a),u(!0))};return r},a=function(e,t,r,n){return function(o,u,a){var i=o+u-t.timeOrigin,s=i-t.now();return new Promise((function(t){e.set(a,[r(n,s,i,e,t,a),t])}))}},i=new Map,s=o(globalThis.clearTimeout,i),c=new Map,f=o(globalThis.clearTimeout,c),l=u(performance,globalThis.setTimeout),p=a(i,performance,globalThis.setTimeout,l),d=a(c,performance,globalThis.setTimeout,l);r.createWorker(self,{clear:function(){var r=e(t.mark((function e(r){var n,o,u;return t.wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return n=r.timerId,o=r.timerType,e.next=1,"interval"===o?s(n):f(n);case 1:return u=e.sent,e.abrupt("return",{result:u});case 2:case"end":return e.stop()}}),e)})));function n(e){return r.apply(this,arguments)}return n}(),set:function(){var r=e(t.mark((function e(r){var n,o,u,a,i;return t.wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return n=r.delay,o=r.now,u=r.timerId,a=r.timerType,e.next=1,("interval"===a?p:d)(n,o,u);case 1:return i=e.sent,e.abrupt("return",{result:i});case 2:case"end":return e.stop()}}),e)})));function n(e){return r.apply(this,arguments)}return n}()})}(r(293),r(756),r(623),r(715))},546:e=>{function t(r,n,o,u){var a=Object.defineProperty;try{a({},"",{})}catch(r){a=0}e.exports=t=function(e,r,n,o){if(r)a?a(e,r,{value:n,enumerable:!o,configurable:!o,writable:!o}):e[r]=n;else{var u=function(r,n){t(e,r,(function(e){return this._invoke(r,n,e)}))};u("next",0),u("throw",1),u("return",2)}},e.exports.__esModule=!0,e.exports.default=e.exports,t(r,n,o,u)}e.exports=t,e.exports.__esModule=!0,e.exports.default=e.exports},579:(e,t,r)=>{var n=r(738).default;e.exports=function(e){if(null!=e){var t=e["function"==typeof Symbol&&Symbol.iterator||"@@iterator"],r=0;if(t)return t.call(e);if("function"==typeof e.next)return e;if(!isNaN(e.length))return{next:function(){return e&&r>=e.length&&(e=void 0),{value:e&&e[r++],done:!e}}}}throw new TypeError(n(e)+" is not iterable")},e.exports.__esModule=!0,e.exports.default=e.exports},623:function(e,t,r){!function(e,t,r,n,o){"use strict";var u={INTERNAL_ERROR:-32603,INVALID_PARAMS:-32602,METHOD_NOT_FOUND:-32601},a=function(e,t){return Object.assign(new Error(e),{status:t})},i=function(e){return a('The requested method called "'.concat(e,'" is not supported.'),u.METHOD_NOT_FOUND)},s=function(e){return a('The handler of the method called "'.concat(e,'" returned no required result.'),u.INTERNAL_ERROR)},c=function(e){return a('The handler of the method called "'.concat(e,'" returned an unexpected result.'),u.INTERNAL_ERROR)},f=function(e){return a('The specified parameter called "portId" with the given value "'.concat(e,'" does not identify a port connected to this worker.'),u.INVALID_PARAMS)},l=function(e,n){return function(){var o=t(r.mark((function t(o){var u,a,f,l,p,d,v,x,y,b,h,m,_,g,w;return r.wrap((function(t){for(;;)switch(t.prev=t.next){case 0:if(u=o.data,a=u.id,f=u.method,l=u.params,p=n[f],t.prev=1,void 0!==p){t.next=2;break}throw i(f);case 2:if(void 0!==(d=void 0===l?p():p(l))){t.next=3;break}throw s(f);case 3:if(!(d instanceof Promise)){t.next=5;break}return t.next=4,d;case 4:g=t.sent,t.next=6;break;case 5:g=d;case 6:if(v=g,null!==a){t.next=8;break}if(void 0===v.result){t.next=7;break}throw c(f);case 7:t.next=10;break;case 8:if(void 0!==v.result){t.next=9;break}throw c(f);case 9:x=v.result,y=v.transferables,b=void 0===y?[]:y,e.postMessage({id:a,result:x},b);case 10:t.next=12;break;case 11:t.prev=11,w=t.catch(1),h=w.message,m=w.status,_=void 0===m?-32603:m,e.postMessage({error:{code:_,message:h},id:a});case 12:case"end":return t.stop()}}),t,null,[[1,11]])})));return function(e){return o.apply(this,arguments)}}()},p=function(){return new Promise((function(e){var t=new ArrayBuffer(0),r=new MessageChannel,n=r.port1,o=r.port2;n.onmessage=function(t){var r=t.data;return e(null!==r)},o.postMessage(t,[t])}))};function d(e,t){var r=Object.keys(e);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(e);t&&(n=n.filter((function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable}))),r.push.apply(r,n)}return r}function v(e){for(var t=1;t<arguments.length;t++){var r=null!=arguments[t]?arguments[t]:{};t%2?d(Object(r),!0).forEach((function(t){n(e,t,r[t])})):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(r)):d(Object(r)).forEach((function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(r,t))}))}return e}var x=new Map,y=function(e,n,u){return v(v({},n),{},{connect:function(t){var r=t.port;r.start();var u=e(r,n),a=o.generateUniqueNumber(x);return x.set(a,(function(){u(),r.close(),x.delete(a)})),{result:a}},disconnect:function(e){var t=e.portId,r=x.get(t);if(void 0===r)throw f(t);return r(),{result:null}},isSupported:function(){var e=t(r.mark((function e(){var t,n,o;return r.wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return e.next=1,p();case 1:if(!e.sent){e.next=5;break}if(!((t=u())instanceof Promise)){e.next=3;break}return e.next=2,t;case 2:o=e.sent,e.next=4;break;case 3:o=t;case 4:return n=o,e.abrupt("return",{result:n});case 5:return e.abrupt("return",{result:!1});case 6:case"end":return e.stop()}}),e)})));function n(){return e.apply(this,arguments)}return n}()})},b=function(e,t){var r=y(b,t,arguments.length>2&&void 0!==arguments[2]?arguments[2]:function(){return!0}),n=l(e,r);return e.addEventListener("message",n),function(){return e.removeEventListener("message",n)}};e.createWorker=b,e.isSupported=p}(t,r(293),r(756),r(693),r(389))},633:(e,t,r)=>{var n=r(172),o=r(993),u=r(869),a=r(887),i=r(791),s=r(373),c=r(579);function f(){"use strict";var t=o(),r=t.m(f),l=(Object.getPrototypeOf?Object.getPrototypeOf(r):r.__proto__).constructor;function p(e){var t="function"==typeof e&&e.constructor;return!!t&&(t===l||"GeneratorFunction"===(t.displayName||t.name))}var d={throw:1,return:2,break:3,continue:3};function v(e){var t,r;return function(n){t||(t={stop:function(){return r(n.a,2)},catch:function(){return n.v},abrupt:function(e,t){return r(n.a,d[e],t)},delegateYield:function(e,o,u){return t.resultName=o,r(n.d,c(e),u)},finish:function(e){return r(n.f,e)}},r=function(e,r,o){n.p=t.prev,n.n=t.next;try{return e(r,o)}finally{t.next=n.n}}),t.resultName&&(t[t.resultName]=n.v,t.resultName=void 0),t.sent=n.v,t.next=n.n;try{return e.call(this,t)}finally{n.p=t.prev,n.n=t.next}}}return(e.exports=f=function(){return{wrap:function(e,r,n,o){return t.w(v(e),r,n,o&&o.reverse())},isGeneratorFunction:p,mark:t.m,awrap:function(e,t){return new n(e,t)},AsyncIterator:i,async:function(e,t,r,n,o){return(p(t)?a:u)(v(e),t,r,n,o)},keys:s,values:c}},e.exports.__esModule=!0,e.exports.default=e.exports)()}e.exports=f,e.exports.__esModule=!0,e.exports.default=e.exports},693:(e,t,r)=>{var n=r(736);e.exports=function(e,t,r){return(t=n(t))in e?Object.defineProperty(e,t,{value:r,enumerable:!0,configurable:!0,writable:!0}):e[t]=r,e},e.exports.__esModule=!0,e.exports.default=e.exports},715:(e,t,r)=>{var n=r(987),o=r(156),u=r(122),a=r(752);e.exports=function(e,t){return n(e)||o(e,t)||u(e,t)||a()},e.exports.__esModule=!0,e.exports.default=e.exports},736:(e,t,r)=>{var n=r(738).default,o=r(45);e.exports=function(e){var t=o(e,"string");return"symbol"==n(t)?t:t+""},e.exports.__esModule=!0,e.exports.default=e.exports},738:e=>{function t(r){return e.exports=t="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},e.exports.__esModule=!0,e.exports.default=e.exports,t(r)}e.exports=t,e.exports.__esModule=!0,e.exports.default=e.exports},752:e=>{e.exports=function(){throw new TypeError("Invalid attempt to destructure non-iterable instance.\\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")},e.exports.__esModule=!0,e.exports.default=e.exports},756:(e,t,r)=>{var n=r(633)();e.exports=n;try{regeneratorRuntime=n}catch(e){"object"==typeof globalThis?globalThis.regeneratorRuntime=n:Function("r","regeneratorRuntime = r")(n)}},791:(e,t,r)=>{var n=r(172),o=r(546);e.exports=function e(t,r){function u(e,o,a,i){try{var s=t[e](o),c=s.value;return c instanceof n?r.resolve(c.v).then((function(e){u("next",e,a,i)}),(function(e){u("throw",e,a,i)})):r.resolve(c).then((function(e){s.value=e,a(s)}),(function(e){return u("throw",e,a,i)}))}catch(e){i(e)}}var a;this.next||(o(e.prototype),o(e.prototype,"function"==typeof Symbol&&Symbol.asyncIterator||"@asyncIterator",(function(){return this}))),o(this,"_invoke",(function(e,t,n){function o(){return new r((function(t,r){u(e,n,t,r)}))}return a=a?a.then(o,o):o()}),!0)},e.exports.__esModule=!0,e.exports.default=e.exports},869:(e,t,r)=>{var n=r(887);e.exports=function(e,t,r,o,u){var a=n(e,t,r,o,u);return a.next().then((function(e){return e.done?e.value:a.next()}))},e.exports.__esModule=!0,e.exports.default=e.exports},887:(e,t,r)=>{var n=r(993),o=r(791);e.exports=function(e,t,r,u,a){return new o(n().w(e,t,r,u),a||Promise)},e.exports.__esModule=!0,e.exports.default=e.exports},987:e=>{e.exports=function(e){if(Array.isArray(e))return e},e.exports.__esModule=!0,e.exports.default=e.exports},993:(e,t,r)=>{var n=r(546);function o(){var t,r,u="function"==typeof Symbol?Symbol:{},a=u.iterator||"@@iterator",i=u.toStringTag||"@@toStringTag";function s(e,o,u,a){var i=o&&o.prototype instanceof f?o:f,s=Object.create(i.prototype);return n(s,"_invoke",function(e,n,o){var u,a,i,s=0,f=o||[],l=!1,p={p:0,n:0,v:t,a:d,f:d.bind(t,4),d:function(e,r){return u=e,a=0,i=t,p.n=r,c}};function d(e,n){for(a=e,i=n,r=0;!l&&s&&!o&&r<f.length;r++){var o,u=f[r],d=p.p,v=u[2];e>3?(o=v===n)&&(i=u[(a=u[4])?5:(a=3,3)],u[4]=u[5]=t):u[0]<=d&&((o=e<2&&d<u[1])?(a=0,p.v=n,p.n=u[1]):d<v&&(o=e<3||u[0]>n||n>v)&&(u[4]=e,u[5]=n,p.n=v,a=0))}if(o||e>1)return c;throw l=!0,n}return function(o,f,v){if(s>1)throw TypeError("Generator is already running");for(l&&1===f&&d(f,v),a=f,i=v;(r=a<2?t:i)||!l;){u||(a?a<3?(a>1&&(p.n=-1),d(a,i)):p.n=i:p.v=i);try{if(s=2,u){if(a||(o="next"),r=u[o]){if(!(r=r.call(u,i)))throw TypeError("iterator result is not an object");if(!r.done)return r;i=r.value,a<2&&(a=0)}else 1===a&&(r=u.return)&&r.call(u),a<2&&(i=TypeError("The iterator does not provide a '"+o+"' method"),a=1);u=t}else if((r=(l=p.n<0)?i:e.call(n,p))!==c)break}catch(e){u=t,a=1,i=e}finally{s=1}}return{value:r,done:l}}}(e,u,a),!0),s}var c={};function f(){}function l(){}function p(){}r=Object.getPrototypeOf;var d=[][a]?r(r([][a]())):(n(r={},a,(function(){return this})),r),v=p.prototype=f.prototype=Object.create(d);function x(e){return Object.setPrototypeOf?Object.setPrototypeOf(e,p):(e.__proto__=p,n(e,i,"GeneratorFunction")),e.prototype=Object.create(v),e}return l.prototype=p,n(v,"constructor",p),n(p,"constructor",l),l.displayName="GeneratorFunction",n(p,i,"GeneratorFunction"),n(v),n(v,i,"Generator"),n(v,a,(function(){return this})),n(v,"toString",(function(){return"[object Generator]"})),(e.exports=o=function(){return{w:s,m:x}},e.exports.__esModule=!0,e.exports.default=e.exports)()}e.exports=o,e.exports.__esModule=!0,e.exports.default=e.exports}},t={};function r(n){var o=t[n];if(void 0!==o)return o.exports;var u=t[n]={exports:{}};return e[n].call(u.exports,u,u.exports,r),u.exports}r.n=e=>{var t=e&&e.__esModule?()=>e.default:()=>e;return r.d(t,{a:t}),t},r.d=(e,t)=>{for(var n in t)r.o(t,n)&&!r.o(e,n)&&Object.defineProperty(e,n,{enumerable:!0,get:t[n]})},r.o=(e,t)=>Object.prototype.hasOwnProperty.call(e,t),(()=>{"use strict";r(472)})()})();`,i=a(r.load,n),s=function(d){return i().clearInterval(d)},o=function(d){return i().clearTimeout(d)},l=function(){var d;return(d=i()).setInterval.apply(d,arguments)},u=function(){var d;return(d=i()).setTimeout.apply(d,arguments)};t.clearInterval=s,t.clearTimeout=o,t.setInterval=l,t.setTimeout=u})}),lr=pe(c=>{le(),ue(),ce(),Object.defineProperty(c,"__esModule",{value:!0}),c.isReactNativeBrowser=c.isWebWorker=void 0;var e=()=>typeof window<"u"?typeof navigator<"u"&&navigator.userAgent?.toLowerCase().indexOf(" electron/")>-1&&Me?.versions?!Object.prototype.hasOwnProperty.call(Me.versions,"electron"):typeof window.document<"u":!1,t=()=>!!(typeof self=="object"&&self?.constructor?.name?.includes("WorkerGlobalScope")&&typeof Deno>"u"),r=()=>typeof navigator<"u"&&navigator.product==="ReactNative",a=e()||t()||r();c.isWebWorker=t(),c.isReactNativeBrowser=r(),c.default=a}),bu=pe(c=>{le(),ue(),ce();var e=c&&c.__createBinding||(Object.create?function(l,u,d,p){p===void 0&&(p=d);var y=Object.getOwnPropertyDescriptor(u,d);(!y||("get"in y?!u.__esModule:y.writable||y.configurable))&&(y={enumerable:!0,get:function(){return u[d]}}),Object.defineProperty(l,p,y)}:function(l,u,d,p){p===void 0&&(p=d),l[p]=u[d]}),t=c&&c.__setModuleDefault||(Object.create?function(l,u){Object.defineProperty(l,"default",{enumerable:!0,value:u})}:function(l,u){l.default=u}),r=c&&c.__importStar||(function(){var l=function(u){return l=Object.getOwnPropertyNames||function(d){var p=[];for(var y in d)Object.prototype.hasOwnProperty.call(d,y)&&(p[p.length]=y);return p},l(u)};return function(u){if(u&&u.__esModule)return u;var d={};if(u!=null)for(var p=l(u),y=0;y<p.length;y++)p[y]!=="default"&&e(d,u,p[y]);return t(d,u),d}})();Object.defineProperty(c,"__esModule",{value:!0});var a=mu(),n=r(lr()),i={set:a.setInterval,clear:a.clearInterval},s={set:(l,u)=>setInterval(l,u),clear:l=>clearInterval(l)},o=l=>{switch(l){case"native":return s;case"worker":return i;default:return n.default&&!n.isWebWorker&&!n.isReactNativeBrowser?i:s}};c.default=o}),ds=pe(c=>{le(),ue(),ce();var e=c&&c.__importDefault||function(a){return a&&a.__esModule?a:{default:a}};Object.defineProperty(c,"__esModule",{value:!0});var t=e(bu()),r=class{_keepalive;timerId;timer;destroyed=!1;counter;client;_keepaliveTimeoutTimestamp;_intervalEvery;get keepaliveTimeoutTimestamp(){return this._keepaliveTimeoutTimestamp}get intervalEvery(){return this._intervalEvery}get keepalive(){return this._keepalive}constructor(a,n){this.client=a,this.timer=typeof n=="object"&&"set"in n&&"clear"in n?n:(0,t.default)(n),this.setKeepalive(a.options.keepalive)}clear(){this.timerId&&(this.timer.clear(this.timerId),this.timerId=null)}setKeepalive(a){if(a*=1e3,isNaN(a)||a<=0||a>2147483647)throw new Error(`Keepalive value must be an integer between 0 and 2147483647. Provided value is ${a}`);this._keepalive=a,this.reschedule(),this.client.log(`KeepaliveManager: set keepalive to ${a}ms`)}destroy(){this.clear(),this.destroyed=!0}reschedule(){if(this.destroyed)return;this.clear(),this.counter=0;let a=Math.ceil(this._keepalive*1.5);this._keepaliveTimeoutTimestamp=Date.now()+a,this._intervalEvery=Math.ceil(this._keepalive/2),this.timerId=this.timer.set(()=>{this.destroyed||(this.counter+=1,this.counter===2?this.client.sendPing():this.counter>2&&this.client.onKeepaliveTimeout())},this._intervalEvery)}};c.default=r}),oi=pe(c=>{le(),ue(),ce();var e=c&&c.__createBinding||(Object.create?function(v,x,E,I){I===void 0&&(I=E);var M=Object.getOwnPropertyDescriptor(x,E);(!M||("get"in M?!x.__esModule:M.writable||M.configurable))&&(M={enumerable:!0,get:function(){return x[E]}}),Object.defineProperty(v,I,M)}:function(v,x,E,I){I===void 0&&(I=E),v[I]=x[E]}),t=c&&c.__setModuleDefault||(Object.create?function(v,x){Object.defineProperty(v,"default",{enumerable:!0,value:x})}:function(v,x){v.default=x}),r=c&&c.__importStar||(function(){var v=function(x){return v=Object.getOwnPropertyNames||function(E){var I=[];for(var M in E)Object.prototype.hasOwnProperty.call(E,M)&&(I[I.length]=M);return I},v(x)};return function(x){if(x&&x.__esModule)return x;var E={};if(x!=null)for(var I=v(x),M=0;M<I.length;M++)I[M]!=="default"&&e(E,x,I[M]);return t(E,x),E}})(),a=c&&c.__importDefault||function(v){return v&&v.__esModule?v:{default:v}};Object.defineProperty(c,"__esModule",{value:!0});var n=a(Ic()),i=Et(),s=a(Cc()),o=a(lt()),l=r(Xo()),u=a(Zo()),d=a(Qc()),p=a(ss()),y=a(Jc()),f=Rt(),m=Xc(),b=a(ds()),k=r(lr()),g=globalThis.setImmediate||((...v)=>{let x=v.shift();(0,f.nextTick)(()=>{x(...v)})}),_={keepalive:60,reschedulePings:!0,protocolId:"MQTT",protocolVersion:4,reconnectPeriod:1e3,connectTimeout:30*1e3,clean:!0,resubscribe:!0,subscribeBatchSize:null,writeCache:!0,timerVariant:"auto"},S=class fo extends m.TypedEventEmitter{static VERSION=f.MQTTJS_VERSION;connected;disconnecting;disconnected;reconnecting;incomingStore;outgoingStore;options;queueQoSZero;_reconnectCount;log;messageIdProvider;outgoing;messageIdToTopic;noop;keepaliveManager;stream;queue;streamBuilder;_resubscribeTopics;connackTimer;reconnectTimer;_storeProcessing;_packetIdsDuringStoreProcessing;_storeProcessingQueue;_firstConnection;topicAliasRecv;topicAliasSend;_deferredReconnect;connackPacket;static defaultId(){return`mqttjs_${Math.random().toString(16).substr(2,8)}`}constructor(x,E){super(),this.options=E||{};for(let I in _)typeof this.options[I]>"u"?this.options[I]=_[I]:this.options[I]=E[I];this.log=this.options.log||(0,o.default)("mqttjs:client"),this.noop=this._noop.bind(this),this.log("MqttClient :: version:",fo.VERSION),k.isWebWorker?this.log("MqttClient :: environment","webworker"):this.log("MqttClient :: environment",k.default?"browser":"node"),this.log("MqttClient :: options.protocol",E.protocol),this.log("MqttClient :: options.protocolVersion",E.protocolVersion),this.log("MqttClient :: options.username",E.username),this.log("MqttClient :: options.keepalive",E.keepalive),this.log("MqttClient :: options.reconnectPeriod",E.reconnectPeriod),this.log("MqttClient :: options.rejectUnauthorized",E.rejectUnauthorized),this.log("MqttClient :: options.properties.topicAliasMaximum",E.properties?E.properties.topicAliasMaximum:void 0),this.options.clientId=typeof E.clientId=="string"?E.clientId:fo.defaultId(),this.log("MqttClient :: clientId",this.options.clientId),this.options.customHandleAcks=E.protocolVersion===5&&E.customHandleAcks?E.customHandleAcks:(...I)=>{I[3](null,0)},this.options.writeCache||(n.default.writeToStream.cacheNumbers=!1),this.streamBuilder=x,this.messageIdProvider=typeof this.options.messageIdProvider>"u"?new p.default:this.options.messageIdProvider,this.outgoingStore=E.outgoingStore||new u.default,this.incomingStore=E.incomingStore||new u.default,this.queueQoSZero=E.queueQoSZero===void 0?!0:E.queueQoSZero,this._resubscribeTopics={},this.messageIdToTopic={},this.keepaliveManager=null,this.connected=!1,this.disconnecting=!1,this.reconnecting=!1,this.queue=[],this.connackTimer=null,this.reconnectTimer=null,this._storeProcessing=!1,this._packetIdsDuringStoreProcessing={},this._storeProcessingQueue=[],this.outgoing={},this._firstConnection=!0,E.properties&&E.properties.topicAliasMaximum>0&&(E.properties.topicAliasMaximum>65535?this.log("MqttClient :: options.properties.topicAliasMaximum is out of range"):this.topicAliasRecv=new y.default(E.properties.topicAliasMaximum)),this.on("connect",()=>{let{queue:I}=this,M=()=>{let O=I.shift();this.log("deliver :: entry %o",O);let B=null;if(!O){this._resubscribe();return}B=O.packet,this.log("deliver :: call _sendPacket for %o",B);let T=!0;B.messageId&&B.messageId!==0&&(this.messageIdProvider.register(B.messageId)||(T=!1)),T?this._sendPacket(B,W=>{O.cb&&O.cb(W),M()}):(this.log("messageId: %d has already used. The message is skipped and removed.",B.messageId),M())};this.log("connect :: sending queued packets"),M()}),this.on("close",()=>{this.log("close :: connected set to `false`"),this.connected=!1,this.log("close :: clearing connackTimer"),clearTimeout(this.connackTimer),this._destroyKeepaliveManager(),this.topicAliasRecv&&this.topicAliasRecv.clear(),this.log("close :: calling _setupReconnect"),this._setupReconnect()}),this.options.manualConnect||(this.log("MqttClient :: setting up stream"),this.connect())}handleAuth(x,E){E()}handleMessage(x,E){E()}_nextId(){return this.messageIdProvider.allocate()}getLastMessageId(){return this.messageIdProvider.getLastAllocated()}connect(){let x=new i.Writable,E=n.default.parser(this.options),I=null,M=[];this.log("connect :: calling method to clear reconnect"),this._clearReconnect(),this.disconnected&&!this.reconnecting&&(this.incomingStore=this.options.incomingStore||new u.default,this.outgoingStore=this.options.outgoingStore||new u.default,this.disconnecting=!1,this.disconnected=!1),this.log("connect :: using streamBuilder provided to client to create stream"),this.stream=this.streamBuilder(this),E.on("packet",F=>{this.log("parser :: on packet push to packets array."),M.push(F)});let O=()=>{this.log("work :: getting next packet in queue");let F=M.shift();if(F)this.log("work :: packet pulled from queue"),(0,d.default)(this,F,B);else{this.log("work :: no packets in queue");let N=I;I=null,this.log("work :: done flag is %s",!!N),N&&N()}},B=()=>{if(M.length)(0,f.nextTick)(O);else{let F=I;I=null,F()}};x._write=(F,N,ae)=>{I=ae,this.log("writable stream :: parsing buffer"),E.parse(F),O()};let T=F=>{this.log("streamErrorHandler :: error",F.message),F.code?(this.log("streamErrorHandler :: emitting error"),this.emit("error",F)):this.noop(F)};this.log("connect :: pipe stream to writable stream"),this.stream.pipe(x),this.stream.on("error",T),this.stream.on("close",()=>{this.log("(%s)stream :: on close",this.options.clientId),this._flushVolatile(),this.log("stream: emit close to MqttClient"),this.emit("close")}),this.log("connect: sending packet `connect`");let W={cmd:"connect",protocolId:this.options.protocolId,protocolVersion:this.options.protocolVersion,clean:this.options.clean,clientId:this.options.clientId,keepalive:this.options.keepalive,username:this.options.username,password:this.options.password,properties:this.options.properties};if(this.options.will&&(W.will={...this.options.will,payload:this.options.will?.payload}),this.topicAliasRecv&&(W.properties||(W.properties={}),this.topicAliasRecv&&(W.properties.topicAliasMaximum=this.topicAliasRecv.max)),this._writePacket(W),E.on("error",this.emit.bind(this,"error")),this.options.properties){if(!this.options.properties.authenticationMethod&&this.options.properties.authenticationData)return this.end(()=>this.emit("error",new Error("Packet has no Authentication Method"))),this;if(this.options.properties.authenticationMethod&&this.options.authPacket&&typeof this.options.authPacket=="object"){let F={cmd:"auth",reasonCode:0,...this.options.authPacket};this._writePacket(F)}}return this.stream.setMaxListeners(1e3),clearTimeout(this.connackTimer),this.connackTimer=setTimeout(()=>{this.log("!!connectTimeout hit!! Calling _cleanUp with force `true`"),this.emit("error",new Error("connack timeout")),this._cleanUp(!0)},this.options.connectTimeout),this}publish(x,E,I,M){this.log("publish :: message `%s` to topic `%s`",E,x);let{options:O}=this;typeof I=="function"&&(M=I,I=null),I=I||{},I={qos:0,retain:!1,dup:!1,...I};let{qos:B,retain:T,dup:W,properties:F,cbStorePut:N}=I;if(this._checkDisconnecting(M))return this;let ae=()=>{let Y=0;if((B===1||B===2)&&(Y=this._nextId(),Y===null))return this.log("No messageId left"),!1;let K={cmd:"publish",topic:x,payload:E,qos:B,retain:T,messageId:Y,dup:W};switch(O.protocolVersion===5&&(K.properties=F),this.log("publish :: qos",B),B){case 1:case 2:this.outgoing[K.messageId]={volatile:!1,cb:M||this.noop},this.log("MqttClient:publish: packet cmd: %s",K.cmd),this._sendPacket(K,void 0,N);break;default:this.log("MqttClient:publish: packet cmd: %s",K.cmd),this._sendPacket(K,M,N);break}return!0};return(this._storeProcessing||this._storeProcessingQueue.length>0||!ae())&&this._storeProcessingQueue.push({invoke:ae,cbStorePut:I.cbStorePut,callback:M}),this}publishAsync(x,E,I){return new Promise((M,O)=>{this.publish(x,E,I,(B,T)=>{B?O(B):M(T)})})}subscribe(x,E,I){let M=this.options.protocolVersion;typeof E=="function"&&(I=E),I=I||this.noop;let O=!1,B=[];typeof x=="string"?(x=[x],B=x):Array.isArray(x)?B=x:typeof x=="object"&&(O=x.resubscribe,delete x.resubscribe,B=Object.keys(x));let T=l.validateTopics(B);if(T!==null)return g(I,new Error(`Invalid topic ${T}`)),this;if(this._checkDisconnecting(I))return this.log("subscribe: discconecting true"),this;let W={qos:0};M===5&&(W.nl=!1,W.rap=!1,W.rh=0),E={...W,...E};let{properties:F}=E,N=[],ae=(re,D)=>{if(D=D||E,!Object.prototype.hasOwnProperty.call(this._resubscribeTopics,re)||this._resubscribeTopics[re].qos<D.qos||O){let Z={topic:re,qos:D.qos};M===5&&(Z.nl=D.nl,Z.rap=D.rap,Z.rh=D.rh,Z.properties=F),this.log("subscribe: pushing topic `%s` and qos `%s` to subs list",Z.topic,Z.qos),N.push(Z)}};if(Array.isArray(x)?x.forEach(re=>{this.log("subscribe: array topic %s",re),ae(re)}):Object.keys(x).forEach(re=>{this.log("subscribe: object topic %s, %o",re,x[re]),ae(re,x[re])}),!N.length)return I(null,[]),this;let Y=(re,D)=>{let Z={cmd:"subscribe",subscriptions:re,messageId:D};if(F&&(Z.properties=F),this.options.resubscribe){this.log("subscribe :: resubscribe true");let J=[];re.forEach(be=>{if(this.options.reconnectPeriod>0){let te={qos:be.qos};M===5&&(te.nl=be.nl||!1,te.rap=be.rap||!1,te.rh=be.rh||0,te.properties=be.properties),this._resubscribeTopics[be.topic]=te,J.push(be.topic)}}),this.messageIdToTopic[Z.messageId]=J}let P=new Promise((J,be)=>{this.outgoing[Z.messageId]={volatile:!0,cb(te,we){if(!te){let{granted:V}=we;for(let L=0;L<V.length;L+=1)re[L].qos=V[L]}te?be(new f.ErrorWithSubackPacket(te.message,we)):J(we)}}});return this.log("subscribe :: call _sendPacket"),this._sendPacket(Z),P},K=()=>{let re=this.options.subscribeBatchSize??N.length,D=[];for(let Z=0;Z<N.length;Z+=re){let P=N.slice(Z,Z+re),J=this._nextId();if(J===null)return this.log("No messageId left"),!1;D.push(Y(P,J))}return Promise.all(D).then(Z=>{I(null,N,Z.at(-1))}).catch(Z=>{I(Z,N,Z.packet)}),!0};return(this._storeProcessing||this._storeProcessingQueue.length>0||!K())&&this._storeProcessingQueue.push({invoke:K,callback:I}),this}subscribeAsync(x,E){return new Promise((I,M)=>{this.subscribe(x,E,(O,B)=>{O?M(O):I(B)})})}unsubscribe(x,E,I){typeof x=="string"&&(x=[x]),typeof E=="function"&&(I=E),I=I||this.noop;let M=l.validateTopics(x);if(M!==null)return g(I,new Error(`Invalid topic ${M}`)),this;if(this._checkDisconnecting(I))return this;let O=()=>{let B=this._nextId();if(B===null)return this.log("No messageId left"),!1;let T={cmd:"unsubscribe",messageId:B,unsubscriptions:[]};return typeof x=="string"?T.unsubscriptions=[x]:Array.isArray(x)&&(T.unsubscriptions=x),this.options.resubscribe&&T.unsubscriptions.forEach(W=>{delete this._resubscribeTopics[W]}),typeof E=="object"&&E.properties&&(T.properties=E.properties),this.outgoing[T.messageId]={volatile:!0,cb:I},this.log("unsubscribe: call _sendPacket"),this._sendPacket(T),!0};return(this._storeProcessing||this._storeProcessingQueue.length>0||!O())&&this._storeProcessingQueue.push({invoke:O,callback:I}),this}unsubscribeAsync(x,E){return new Promise((I,M)=>{this.unsubscribe(x,E,(O,B)=>{O?M(O):I(B)})})}end(x,E,I){this.log("end :: (%s)",this.options.clientId),(x==null||typeof x!="boolean")&&(I=I||E,E=x,x=!1),typeof E!="object"&&(I=I||E,E=null),this.log("end :: cb? %s",!!I),(!I||typeof I!="function")&&(I=this.noop);let M=()=>{this.log("end :: closeStores: closing incoming and outgoing stores"),this.disconnected=!0,this.incomingStore.close(B=>{this.outgoingStore.close(T=>{if(this.log("end :: closeStores: emitting end"),this.emit("end"),I){let W=B||T;this.log("end :: closeStores: invoking callback with args"),I(W)}})}),this._deferredReconnect?this._deferredReconnect():(this.options.reconnectPeriod===0||this.options.manualConnect)&&(this.disconnecting=!1)},O=()=>{this.log("end :: (%s) :: finish :: calling _cleanUp with force %s",this.options.clientId,x),this._cleanUp(x,()=>{this.log("end :: finish :: calling process.nextTick on closeStores"),(0,f.nextTick)(M)},E)};return this.disconnecting?(I(),this):(this._clearReconnect(),this.disconnecting=!0,!x&&Object.keys(this.outgoing).length>0?(this.log("end :: (%s) :: calling finish in 10ms once outgoing is empty",this.options.clientId),this.once("outgoingEmpty",setTimeout.bind(null,O,10))):(this.log("end :: (%s) :: immediately calling finish",this.options.clientId),O()),this)}endAsync(x,E){return new Promise((I,M)=>{this.end(x,E,O=>{O?M(O):I()})})}removeOutgoingMessage(x){if(this.outgoing[x]){let{cb:E}=this.outgoing[x];this._removeOutgoingAndStoreMessage(x,()=>{E(new Error("Message removed"))})}return this}reconnect(x){this.log("client reconnect");let E=()=>{x?(this.options.incomingStore=x.incomingStore,this.options.outgoingStore=x.outgoingStore):(this.options.incomingStore=null,this.options.outgoingStore=null),this.incomingStore=this.options.incomingStore||new u.default,this.outgoingStore=this.options.outgoingStore||new u.default,this.disconnecting=!1,this.disconnected=!1,this._deferredReconnect=null,this._reconnect()};return this.disconnecting&&!this.disconnected?this._deferredReconnect=E:E(),this}_flushVolatile(){this.outgoing&&(this.log("_flushVolatile :: deleting volatile messages from the queue and setting their callbacks as error function"),Object.keys(this.outgoing).forEach(x=>{this.outgoing[x].volatile&&typeof this.outgoing[x].cb=="function"&&(this.outgoing[x].cb(new Error("Connection closed")),delete this.outgoing[x])}))}_flush(){this.outgoing&&(this.log("_flush: queue exists? %b",!!this.outgoing),Object.keys(this.outgoing).forEach(x=>{typeof this.outgoing[x].cb=="function"&&(this.outgoing[x].cb(new Error("Connection closed")),delete this.outgoing[x])}))}_removeTopicAliasAndRecoverTopicName(x){let E;x.properties&&(E=x.properties.topicAlias);let I=x.topic.toString();if(this.log("_removeTopicAliasAndRecoverTopicName :: alias %d, topic %o",E,I),I.length===0){if(typeof E>"u")return new Error("Unregistered Topic Alias");if(I=this.topicAliasSend.getTopicByAlias(E),typeof I>"u")return new Error("Unregistered Topic Alias");x.topic=I}E&&delete x.properties.topicAlias}_checkDisconnecting(x){return this.disconnecting&&(x&&x!==this.noop?x(new Error("client disconnecting")):this.emit("error",new Error("client disconnecting"))),this.disconnecting}_reconnect(){this.log("_reconnect: emitting reconnect to client"),this.emit("reconnect"),this.connected?(this.end(()=>{this.connect()}),this.log("client already connected. disconnecting first.")):(this.log("_reconnect: calling connect"),this.connect())}_setupReconnect(){!this.disconnecting&&!this.reconnectTimer&&this.options.reconnectPeriod>0?(this.reconnecting||(this.log("_setupReconnect :: emit `offline` state"),this.emit("offline"),this.log("_setupReconnect :: set `reconnecting` to `true`"),this.reconnecting=!0),this.log("_setupReconnect :: setting reconnectTimer for %d ms",this.options.reconnectPeriod),this.reconnectTimer=setInterval(()=>{this.log("reconnectTimer :: reconnect triggered!"),this._reconnect()},this.options.reconnectPeriod)):this.log("_setupReconnect :: doing nothing...")}_clearReconnect(){this.log("_clearReconnect : clearing reconnect timer"),this.reconnectTimer&&(clearInterval(this.reconnectTimer),this.reconnectTimer=null)}_cleanUp(x,E,I={}){if(E&&(this.log("_cleanUp :: done callback provided for on stream close"),this.stream.on("close",E)),this.log("_cleanUp :: forced? %s",x),x)this.options.reconnectPeriod===0&&this.options.clean&&this._flush(),this.log("_cleanUp :: (%s) :: destroying stream",this.options.clientId),this.stream.destroy();else{let M={cmd:"disconnect",...I};this.log("_cleanUp :: (%s) :: call _sendPacket with disconnect packet",this.options.clientId),this._sendPacket(M,()=>{this.log("_cleanUp :: (%s) :: destroying stream",this.options.clientId),g(()=>{this.stream.end(()=>{this.log("_cleanUp :: (%s) :: stream destroyed",this.options.clientId)})})})}!this.disconnecting&&!this.reconnecting&&(this.log("_cleanUp :: client not disconnecting/reconnecting. Clearing and resetting reconnect."),this._clearReconnect(),this._setupReconnect()),this._destroyKeepaliveManager(),E&&!this.connected&&(this.log("_cleanUp :: (%s) :: removing stream `done` callback `close` listener",this.options.clientId),this.stream.removeListener("close",E),E())}_storeAndSend(x,E,I){this.log("storeAndSend :: store packet with cmd %s to outgoingStore",x.cmd);let M=x,O;if(M.cmd==="publish"&&(M=(0,s.default)(x),O=this._removeTopicAliasAndRecoverTopicName(M),O))return E&&E(O);this.outgoingStore.put(M,B=>{if(B)return E&&E(B);I(),this._writePacket(x,E)})}_applyTopicAlias(x){if(this.options.protocolVersion===5&&x.cmd==="publish"){let E;x.properties&&(E=x.properties.topicAlias);let I=x.topic.toString();if(this.topicAliasSend)if(E){if(I.length!==0&&(this.log("applyTopicAlias :: register topic: %s - alias: %d",I,E),!this.topicAliasSend.put(I,E)))return this.log("applyTopicAlias :: error out of range. topic: %s - alias: %d",I,E),new Error("Sending Topic Alias out of range")}else I.length!==0&&(this.options.autoAssignTopicAlias?(E=this.topicAliasSend.getAliasByTopic(I),E?(x.topic="",x.properties={...x.properties,topicAlias:E},this.log("applyTopicAlias :: auto assign(use) topic: %s - alias: %d",I,E)):(E=this.topicAliasSend.getLruAlias(),this.topicAliasSend.put(I,E),x.properties={...x.properties,topicAlias:E},this.log("applyTopicAlias :: auto assign topic: %s - alias: %d",I,E))):this.options.autoUseTopicAlias&&(E=this.topicAliasSend.getAliasByTopic(I),E&&(x.topic="",x.properties={...x.properties,topicAlias:E},this.log("applyTopicAlias :: auto use topic: %s - alias: %d",I,E))));else if(E)return this.log("applyTopicAlias :: error out of range. topic: %s - alias: %d",I,E),new Error("Sending Topic Alias out of range")}}_noop(x){this.log("noop ::",x)}_writePacket(x,E){this.log("_writePacket :: packet: %O",x),this.log("_writePacket :: emitting `packetsend`"),this.emit("packetsend",x),this.log("_writePacket :: writing to stream");let I=n.default.writeToStream(x,this.stream,this.options);this.log("_writePacket :: writeToStream result %s",I),!I&&E&&E!==this.noop?(this.log("_writePacket :: handle events on `drain` once through callback."),this.stream.once("drain",E)):E&&(this.log("_writePacket :: invoking cb"),E())}_sendPacket(x,E,I,M){this.log("_sendPacket :: (%s) :: start",this.options.clientId),I=I||this.noop,E=E||this.noop;let O=this._applyTopicAlias(x);if(O){E(O);return}if(!this.connected){if(x.cmd==="auth"){this._writePacket(x,E);return}this.log("_sendPacket :: client not connected. Storing packet offline."),this._storePacket(x,E,I);return}if(M){this._writePacket(x,E);return}switch(x.cmd){case"publish":break;case"pubrel":this._storeAndSend(x,E,I);return;default:this._writePacket(x,E);return}switch(x.qos){case 2:case 1:this._storeAndSend(x,E,I);break;default:this._writePacket(x,E);break}this.log("_sendPacket :: (%s) :: end",this.options.clientId)}_storePacket(x,E,I){this.log("_storePacket :: packet: %o",x),this.log("_storePacket :: cb? %s",!!E),I=I||this.noop;let M=x;if(M.cmd==="publish"){M=(0,s.default)(x);let B=this._removeTopicAliasAndRecoverTopicName(M);if(B)return E&&E(B)}let O=M.qos||0;O===0&&this.queueQoSZero||M.cmd!=="publish"?this.queue.push({packet:M,cb:E}):O>0?(E=this.outgoing[M.messageId]?this.outgoing[M.messageId].cb:null,this.outgoingStore.put(M,B=>{if(B)return E&&E(B);I()})):E&&E(new Error("No connection to broker"))}_setupKeepaliveManager(){this.log("_setupKeepaliveManager :: keepalive %d (seconds)",this.options.keepalive),!this.keepaliveManager&&this.options.keepalive&&(this.keepaliveManager=new b.default(this,this.options.timerVariant))}_destroyKeepaliveManager(){this.keepaliveManager&&(this.log("_destroyKeepaliveManager :: destroying keepalive manager"),this.keepaliveManager.destroy(),this.keepaliveManager=null)}reschedulePing(x=!1){this.keepaliveManager&&this.options.keepalive&&(x||this.options.reschedulePings)&&this._reschedulePing()}_reschedulePing(){this.log("_reschedulePing :: rescheduling ping"),this.keepaliveManager.reschedule()}sendPing(){this.log("_sendPing :: sending pingreq"),this._sendPacket({cmd:"pingreq"})}onKeepaliveTimeout(){this.emit("error",new Error("Keepalive timeout")),this.log("onKeepaliveTimeout :: calling _cleanUp with force true"),this._cleanUp(!0)}_resubscribe(){this.log("_resubscribe");let x=Object.keys(this._resubscribeTopics);if(!this._firstConnection&&(this.options.clean||this.options.protocolVersion>=4&&!this.connackPacket.sessionPresent)&&x.length>0)if(this.options.resubscribe)if(this.options.protocolVersion===5){this.log("_resubscribe: protocolVersion 5");for(let E=0;E<x.length;E++){let I={};I[x[E]]=this._resubscribeTopics[x[E]],I.resubscribe=!0,this.subscribe(I,{properties:I[x[E]].properties})}}else this._resubscribeTopics.resubscribe=!0,this.subscribe(this._resubscribeTopics);else this._resubscribeTopics={};this._firstConnection=!1}_onConnect(x){if(this.disconnected){this.emit("connect",x);return}this.connackPacket=x,this.messageIdProvider.clear(),this._setupKeepaliveManager(),this.connected=!0;let E=()=>{let I=this.outgoingStore.createStream(),M=()=>{I.destroy(),I=null,this._flushStoreProcessingQueue(),O()},O=()=>{this._storeProcessing=!1,this._packetIdsDuringStoreProcessing={}};this.once("close",M),I.on("error",T=>{O(),this._flushStoreProcessingQueue(),this.removeListener("close",M),this.emit("error",T)});let B=()=>{if(!I)return;let T=I.read(1),W;if(!T){I.once("readable",B);return}if(this._storeProcessing=!0,this._packetIdsDuringStoreProcessing[T.messageId]){B();return}!this.disconnecting&&!this.reconnectTimer?(W=this.outgoing[T.messageId]?this.outgoing[T.messageId].cb:null,this.outgoing[T.messageId]={volatile:!1,cb(F,N){W&&W(F,N),B()}},this._packetIdsDuringStoreProcessing[T.messageId]=!0,this.messageIdProvider.register(T.messageId)?this._sendPacket(T,void 0,void 0,!0):this.log("messageId: %d has already used.",T.messageId)):I.destroy&&I.destroy()};I.on("end",()=>{let T=!0;for(let W in this._packetIdsDuringStoreProcessing)if(!this._packetIdsDuringStoreProcessing[W]){T=!1;break}this.removeListener("close",M),T?(O(),this._invokeAllStoreProcessingQueue(),this.emit("connect",x)):E()}),B()};E()}_invokeStoreProcessingQueue(){if(!this._storeProcessing&&this._storeProcessingQueue.length>0){let x=this._storeProcessingQueue[0];if(x&&x.invoke())return this._storeProcessingQueue.shift(),!0}return!1}_invokeAllStoreProcessingQueue(){for(;this._invokeStoreProcessingQueue(););}_flushStoreProcessingQueue(){for(let x of this._storeProcessingQueue)x.cbStorePut&&x.cbStorePut(new Error("Connection closed")),x.callback&&x.callback(new Error("Connection closed"));this._storeProcessingQueue.splice(0)}_removeOutgoingAndStoreMessage(x,E){delete this.outgoing[x],this.outgoingStore.del({messageId:x},(I,M)=>{E(I,M),this.messageIdProvider.deallocate(x),this._invokeStoreProcessingQueue()})}};c.default=S}),yu=pe(c=>{le(),ue(),ce(),Object.defineProperty(c,"__esModule",{value:!0});var e=os(),t=class{numberAllocator;lastId;constructor(){this.numberAllocator=new e.NumberAllocator(1,65535)}allocate(){return this.lastId=this.numberAllocator.alloc(),this.lastId}getLastAllocated(){return this.lastId}register(r){return this.numberAllocator.use(r)}deallocate(r){this.numberAllocator.free(r)}clear(){this.numberAllocator.clear()}};c.default=t});function vu(){if(si)return cr;si=!0;let c=2147483647,e=36,t=1,r=26,a=38,n=700,i=72,s=128,o="-",l=/^xn--/,u=/[^\0-\x7F]/,d=/[\x2E\u3002\uFF0E\uFF61]/g,p={overflow:"Overflow: input needs wider integers to process","not-basic":"Illegal input >= 0x80 (not a basic code point)","invalid-input":"Invalid input"},y=e-t,f=Math.floor,m=String.fromCharCode;function b(O){throw new RangeError(p[O])}function k(O,B){let T=[],W=O.length;for(;W--;)T[W]=B(O[W]);return T}function g(O,B){let T=O.split("@"),W="";T.length>1&&(W=T[0]+"@",O=T[1]),O=O.replace(d,".");let F=O.split("."),N=k(F,B).join(".");return W+N}function _(O){let B=[],T=0,W=O.length;for(;T<W;){let F=O.charCodeAt(T++);if(F>=55296&&F<=56319&&T<W){let N=O.charCodeAt(T++);(N&64512)==56320?B.push(((F&1023)<<10)+(N&1023)+65536):(B.push(F),T--)}else B.push(F)}return B}let S=O=>String.fromCodePoint(...O),v=function(O){return O>=48&&O<58?26+(O-48):O>=65&&O<91?O-65:O>=97&&O<123?O-97:e},x=function(O,B){return O+22+75*(O<26)-((B!=0)<<5)},E=function(O,B,T){let W=0;for(O=T?f(O/n):O>>1,O+=f(O/B);O>y*r>>1;W+=e)O=f(O/y);return f(W+(y+1)*O/(O+a))},I=function(O){let B=[],T=O.length,W=0,F=s,N=i,ae=O.lastIndexOf(o);ae<0&&(ae=0);for(let Y=0;Y<ae;++Y)O.charCodeAt(Y)>=128&&b("not-basic"),B.push(O.charCodeAt(Y));for(let Y=ae>0?ae+1:0;Y<T;){let K=W;for(let D=1,Z=e;;Z+=e){Y>=T&&b("invalid-input");let P=v(O.charCodeAt(Y++));P>=e&&b("invalid-input"),P>f((c-W)/D)&&b("overflow"),W+=P*D;let J=Z<=N?t:Z>=N+r?r:Z-N;if(P<J)break;let be=e-J;D>f(c/be)&&b("overflow"),D*=be}let re=B.length+1;N=E(W-K,re,K==0),f(W/re)>c-F&&b("overflow"),F+=f(W/re),W%=re,B.splice(W++,0,F)}return String.fromCodePoint(...B)},M=function(O){let B=[];O=_(O);let T=O.length,W=s,F=0,N=i;for(let K of O)K<128&&B.push(m(K));let ae=B.length,Y=ae;for(ae&&B.push(o);Y<T;){let K=c;for(let D of O)D>=W&&D<K&&(K=D);let re=Y+1;K-W>f((c-F)/re)&&b("overflow"),F+=(K-W)*re,W=K;for(let D of O)if(D<W&&++F>c&&b("overflow"),D===W){let Z=F;for(let P=e;;P+=e){let J=P<=N?t:P>=N+r?r:P-N;if(Z<J)break;let be=Z-J,te=e-J;B.push(m(x(J+be%te,0))),Z=f(be/te)}B.push(m(x(Z,0))),N=E(F,re,Y===ae),F=0,++Y}++F,++W}return B.join("")};return cr={version:"2.3.1",ucs2:{decode:_,encode:S},decode:I,encode:M,toASCII:function(O){return g(O,function(B){return u.test(B)?"xn--"+M(B):B})},toUnicode:function(O){return g(O,function(B){return l.test(B)?I(B.slice(4).toLowerCase()):B})}},cr}var cr,si,mt,wu=He(()=>{le(),ue(),ce(),cr={},si=!1,mt=vu(),mt.decode,mt.encode,mt.toASCII,mt.toUnicode,mt.ucs2,mt.version});function _u(){return ui||(ui=!0,ci=function(){if(typeof Symbol!="function"||typeof Object.getOwnPropertySymbols!="function")return!1;if(typeof Symbol.iterator=="symbol")return!0;var c={},e=Symbol("test"),t=Object(e);if(typeof e=="string"||Object.prototype.toString.call(e)!=="[object Symbol]"||Object.prototype.toString.call(t)!=="[object Symbol]")return!1;var r=42;c[e]=r;for(e in c)return!1;if(typeof Object.keys=="function"&&Object.keys(c).length!==0||typeof Object.getOwnPropertyNames=="function"&&Object.getOwnPropertyNames(c).length!==0)return!1;var a=Object.getOwnPropertySymbols(c);if(a.length!==1||a[0]!==e||!Object.prototype.propertyIsEnumerable.call(c,e))return!1;if(typeof Object.getOwnPropertyDescriptor=="function"){var n=Object.getOwnPropertyDescriptor(c,e);if(n.value!==r||n.enumerable!==!0)return!1}return!0}),ci}function ku(){return fi||(fi=!0,hi=Error),hi}function Su(){return pi||(pi=!0,di=EvalError),di}function Eu(){return mi||(mi=!0,gi=RangeError),gi}function xu(){return yi||(yi=!0,bi=ReferenceError),bi}function ps(){return wi||(wi=!0,vi=SyntaxError),vi}function Kt(){return ki||(ki=!0,_i=TypeError),_i}function Au(){return Ei||(Ei=!0,Si=URIError),Si}function Iu(){if(xi)return ur;xi=!0;var c=typeof Symbol<"u"&&Symbol,e=_u();return ur=function(){return typeof c!="function"||typeof Symbol!="function"||typeof c("foo")!="symbol"||typeof Symbol("bar")!="symbol"?!1:e()},ur}function Tu(){if(Ai)return hr;Ai=!0;var c={__proto__:null,foo:{}},e=Object;return hr=function(){return{__proto__:c}.foo===c.foo&&!(c instanceof e)},hr}function Cu(){if(Ii)return fr;Ii=!0;var c="Function.prototype.bind called on incompatible ",e=Object.prototype.toString,t=Math.max,r="[object Function]",a=function(s,o){for(var l=[],u=0;u<s.length;u+=1)l[u]=s[u];for(var d=0;d<o.length;d+=1)l[d+s.length]=o[d];return l},n=function(s,o){for(var l=[],u=o,d=0;u<s.length;u+=1,d+=1)l[d]=s[u];return l},i=function(s,o){for(var l="",u=0;u<s.length;u+=1)l+=s[u],u+1<s.length&&(l+=o);return l};return fr=function(s){var o=this;if(typeof o!="function"||e.apply(o)!==r)throw new TypeError(c+o);for(var l=n(arguments,1),u,d=function(){if(this instanceof u){var b=o.apply(this,a(l,arguments));return Object(b)===b?b:this}return o.apply(s,a(l,arguments))},p=t(0,o.length-l.length),y=[],f=0;f<p;f++)y[f]="$"+f;if(u=Function("binder","return function ("+i(y,",")+"){ return binder.apply(this,arguments); }")(d),o.prototype){var m=function(){};m.prototype=o.prototype,u.prototype=new m,m.prototype=null}return u},fr}function ai(){if(Ti)return dr;Ti=!0;var c=Cu();return dr=Function.prototype.bind||c,dr}function Ou(){if(Ci)return pr;Ci=!0;var c=Function.prototype.call,e=Object.prototype.hasOwnProperty,t=ai();return pr=t.call(c,e),pr}function jt(){if(Oi)return gr;Oi=!0;var c,e=ku(),t=Su(),r=Eu(),a=xu(),n=ps(),i=Kt(),s=Au(),o=Function,l=function(Y){try{return o('"use strict"; return ('+Y+").constructor;")()}catch{}},u=Object.getOwnPropertyDescriptor;if(u)try{u({},"")}catch{u=null}var d=function(){throw new i},p=u?(function(){try{return arguments.callee,d}catch{try{return u(arguments,"callee").get}catch{return d}}})():d,y=Iu()(),f=Tu()(),m=Object.getPrototypeOf||(f?function(Y){return Y.__proto__}:null),b={},k=typeof Uint8Array>"u"||!m?c:m(Uint8Array),g={__proto__:null,"%AggregateError%":typeof AggregateError>"u"?c:AggregateError,"%Array%":Array,"%ArrayBuffer%":typeof ArrayBuffer>"u"?c:ArrayBuffer,"%ArrayIteratorPrototype%":y&&m?m([][Symbol.iterator]()):c,"%AsyncFromSyncIteratorPrototype%":c,"%AsyncFunction%":b,"%AsyncGenerator%":b,"%AsyncGeneratorFunction%":b,"%AsyncIteratorPrototype%":b,"%Atomics%":typeof Atomics>"u"?c:Atomics,"%BigInt%":typeof BigInt>"u"?c:BigInt,"%BigInt64Array%":typeof BigInt64Array>"u"?c:BigInt64Array,"%BigUint64Array%":typeof BigUint64Array>"u"?c:BigUint64Array,"%Boolean%":Boolean,"%DataView%":typeof DataView>"u"?c:DataView,"%Date%":Date,"%decodeURI%":decodeURI,"%decodeURIComponent%":decodeURIComponent,"%encodeURI%":encodeURI,"%encodeURIComponent%":encodeURIComponent,"%Error%":e,"%eval%":eval,"%EvalError%":t,"%Float32Array%":typeof Float32Array>"u"?c:Float32Array,"%Float64Array%":typeof Float64Array>"u"?c:Float64Array,"%FinalizationRegistry%":typeof FinalizationRegistry>"u"?c:FinalizationRegistry,"%Function%":o,"%GeneratorFunction%":b,"%Int8Array%":typeof Int8Array>"u"?c:Int8Array,"%Int16Array%":typeof Int16Array>"u"?c:Int16Array,"%Int32Array%":typeof Int32Array>"u"?c:Int32Array,"%isFinite%":isFinite,"%isNaN%":isNaN,"%IteratorPrototype%":y&&m?m(m([][Symbol.iterator]())):c,"%JSON%":typeof JSON=="object"?JSON:c,"%Map%":typeof Map>"u"?c:Map,"%MapIteratorPrototype%":typeof Map>"u"||!y||!m?c:m(new Map()[Symbol.iterator]()),"%Math%":Math,"%Number%":Number,"%Object%":Object,"%parseFloat%":parseFloat,"%parseInt%":parseInt,"%Promise%":typeof Promise>"u"?c:Promise,"%Proxy%":typeof Proxy>"u"?c:Proxy,"%RangeError%":r,"%ReferenceError%":a,"%Reflect%":typeof Reflect>"u"?c:Reflect,"%RegExp%":RegExp,"%Set%":typeof Set>"u"?c:Set,"%SetIteratorPrototype%":typeof Set>"u"||!y||!m?c:m(new Set()[Symbol.iterator]()),"%SharedArrayBuffer%":typeof SharedArrayBuffer>"u"?c:SharedArrayBuffer,"%String%":String,"%StringIteratorPrototype%":y&&m?m(""[Symbol.iterator]()):c,"%Symbol%":y?Symbol:c,"%SyntaxError%":n,"%ThrowTypeError%":p,"%TypedArray%":k,"%TypeError%":i,"%Uint8Array%":typeof Uint8Array>"u"?c:Uint8Array,"%Uint8ClampedArray%":typeof Uint8ClampedArray>"u"?c:Uint8ClampedArray,"%Uint16Array%":typeof Uint16Array>"u"?c:Uint16Array,"%Uint32Array%":typeof Uint32Array>"u"?c:Uint32Array,"%URIError%":s,"%WeakMap%":typeof WeakMap>"u"?c:WeakMap,"%WeakRef%":typeof WeakRef>"u"?c:WeakRef,"%WeakSet%":typeof WeakSet>"u"?c:WeakSet};if(m)try{null.error}catch(Y){var _=m(m(Y));g["%Error.prototype%"]=_}var S=function Y(K){var re;if(K==="%AsyncFunction%")re=l("async function () {}");else if(K==="%GeneratorFunction%")re=l("function* () {}");else if(K==="%AsyncGeneratorFunction%")re=l("async function* () {}");else if(K==="%AsyncGenerator%"){var D=Y("%AsyncGeneratorFunction%");D&&(re=D.prototype)}else if(K==="%AsyncIteratorPrototype%"){var Z=Y("%AsyncGenerator%");Z&&m&&(re=m(Z.prototype))}return g[K]=re,re},v={__proto__:null,"%ArrayBufferPrototype%":["ArrayBuffer","prototype"],"%ArrayPrototype%":["Array","prototype"],"%ArrayProto_entries%":["Array","prototype","entries"],"%ArrayProto_forEach%":["Array","prototype","forEach"],"%ArrayProto_keys%":["Array","prototype","keys"],"%ArrayProto_values%":["Array","prototype","values"],"%AsyncFunctionPrototype%":["AsyncFunction","prototype"],"%AsyncGenerator%":["AsyncGeneratorFunction","prototype"],"%AsyncGeneratorPrototype%":["AsyncGeneratorFunction","prototype","prototype"],"%BooleanPrototype%":["Boolean","prototype"],"%DataViewPrototype%":["DataView","prototype"],"%DatePrototype%":["Date","prototype"],"%ErrorPrototype%":["Error","prototype"],"%EvalErrorPrototype%":["EvalError","prototype"],"%Float32ArrayPrototype%":["Float32Array","prototype"],"%Float64ArrayPrototype%":["Float64Array","prototype"],"%FunctionPrototype%":["Function","prototype"],"%Generator%":["GeneratorFunction","prototype"],"%GeneratorPrototype%":["GeneratorFunction","prototype","prototype"],"%Int8ArrayPrototype%":["Int8Array","prototype"],"%Int16ArrayPrototype%":["Int16Array","prototype"],"%Int32ArrayPrototype%":["Int32Array","prototype"],"%JSONParse%":["JSON","parse"],"%JSONStringify%":["JSON","stringify"],"%MapPrototype%":["Map","prototype"],"%NumberPrototype%":["Number","prototype"],"%ObjectPrototype%":["Object","prototype"],"%ObjProto_toString%":["Object","prototype","toString"],"%ObjProto_valueOf%":["Object","prototype","valueOf"],"%PromisePrototype%":["Promise","prototype"],"%PromiseProto_then%":["Promise","prototype","then"],"%Promise_all%":["Promise","all"],"%Promise_reject%":["Promise","reject"],"%Promise_resolve%":["Promise","resolve"],"%RangeErrorPrototype%":["RangeError","prototype"],"%ReferenceErrorPrototype%":["ReferenceError","prototype"],"%RegExpPrototype%":["RegExp","prototype"],"%SetPrototype%":["Set","prototype"],"%SharedArrayBufferPrototype%":["SharedArrayBuffer","prototype"],"%StringPrototype%":["String","prototype"],"%SymbolPrototype%":["Symbol","prototype"],"%SyntaxErrorPrototype%":["SyntaxError","prototype"],"%TypedArrayPrototype%":["TypedArray","prototype"],"%TypeErrorPrototype%":["TypeError","prototype"],"%Uint8ArrayPrototype%":["Uint8Array","prototype"],"%Uint8ClampedArrayPrototype%":["Uint8ClampedArray","prototype"],"%Uint16ArrayPrototype%":["Uint16Array","prototype"],"%Uint32ArrayPrototype%":["Uint32Array","prototype"],"%URIErrorPrototype%":["URIError","prototype"],"%WeakMapPrototype%":["WeakMap","prototype"],"%WeakSetPrototype%":["WeakSet","prototype"]},x=ai(),E=Ou(),I=x.call(Function.call,Array.prototype.concat),M=x.call(Function.apply,Array.prototype.splice),O=x.call(Function.call,String.prototype.replace),B=x.call(Function.call,String.prototype.slice),T=x.call(Function.call,RegExp.prototype.exec),W=/[^%.[\]]+|\[(?:(-?\d+(?:\.\d+)?)|(["'])((?:(?!\2)[^\\]|\\.)*?)\2)\]|(?=(?:\.|\[\])(?:\.|\[\]|%$))/g,F=/\\(\\)?/g,N=function(Y){var K=B(Y,0,1),re=B(Y,-1);if(K==="%"&&re!=="%")throw new n("invalid intrinsic syntax, expected closing `%`");if(re==="%"&&K!=="%")throw new n("invalid intrinsic syntax, expected opening `%`");var D=[];return O(Y,W,function(Z,P,J,be){D[D.length]=J?O(be,F,"$1"):P||Z}),D},ae=function(Y,K){var re=Y,D;if(E(v,re)&&(D=v[re],re="%"+D[0]+"%"),E(g,re)){var Z=g[re];if(Z===b&&(Z=S(re)),typeof Z>"u"&&!K)throw new i("intrinsic "+Y+" exists, but is not available. Please file an issue!");return{alias:D,name:re,value:Z}}throw new n("intrinsic "+Y+" does not exist!")};return gr=function(Y,K){if(typeof Y!="string"||Y.length===0)throw new i("intrinsic name must be a non-empty string");if(arguments.length>1&&typeof K!="boolean")throw new i('"allowMissing" argument must be a boolean');if(T(/^%?[^%]*%?$/,Y)===null)throw new n("`%` may not be present anywhere but at the beginning and end of the intrinsic name");var re=N(Y),D=re.length>0?re[0]:"",Z=ae("%"+D+"%",K),P=Z.name,J=Z.value,be=!1,te=Z.alias;te&&(D=te[0],M(re,I([0,1],te)));for(var we=1,V=!0;we<re.length;we+=1){var L=re[we],ne=B(L,0,1),H=B(L,-1);if((ne==='"'||ne==="'"||ne==="`"||H==='"'||H==="'"||H==="`")&&ne!==H)throw new n("property names with quotes must have matching quotes");if((L==="constructor"||!V)&&(be=!0),D+="."+L,P="%"+D+"%",E(g,P))J=g[P];else if(J!=null){if(!(L in J)){if(!K)throw new i("base intrinsic for "+Y+" exists, but the property is not available.");return}if(u&&we+1>=re.length){var G=u(J,L);V=!!G,V&&"get"in G&&!("originalValue"in G.get)?J=G.get:J=J[L]}else V=E(J,L),J=J[L];V&&!be&&(g[P]=J)}}return J},gr}function li(){if(Pi)return mr;Pi=!0;var c=jt(),e=c("%Object.defineProperty%",!0)||!1;if(e)try{e({},"a",{value:1})}catch{e=!1}return mr=e,mr}function gs(){if(Mi)return br;Mi=!0;var c=jt(),e=c("%Object.getOwnPropertyDescriptor%",!0);if(e)try{e([],"length")}catch{e=null}return br=e,br}function Pu(){if(Ri)return yr;Ri=!0;var c=li(),e=ps(),t=Kt(),r=gs();return yr=function(a,n,i){if(!a||typeof a!="object"&&typeof a!="function")throw new t("`obj` must be an object or a function`");if(typeof n!="string"&&typeof n!="symbol")throw new t("`property` must be a string or a symbol`");if(arguments.length>3&&typeof arguments[3]!="boolean"&&arguments[3]!==null)throw new t("`nonEnumerable`, if provided, must be a boolean or null");if(arguments.length>4&&typeof arguments[4]!="boolean"&&arguments[4]!==null)throw new t("`nonWritable`, if provided, must be a boolean or null");if(arguments.length>5&&typeof arguments[5]!="boolean"&&arguments[5]!==null)throw new t("`nonConfigurable`, if provided, must be a boolean or null");if(arguments.length>6&&typeof arguments[6]!="boolean")throw new t("`loose`, if provided, must be a boolean");var s=arguments.length>3?arguments[3]:null,o=arguments.length>4?arguments[4]:null,l=arguments.length>5?arguments[5]:null,u=arguments.length>6?arguments[6]:!1,d=!!r&&r(a,n);if(c)c(a,n,{configurable:l===null&&d?d.configurable:!l,enumerable:s===null&&d?d.enumerable:!s,value:i,writable:o===null&&d?d.writable:!o});else if(u||!s&&!o&&!l)a[n]=i;else throw new e("This environment does not support defining a property as non-configurable, non-writable, or non-enumerable.")},yr}function Mu(){if(ji)return vr;ji=!0;var c=li(),e=function(){return!!c};return e.hasArrayLengthDefineBug=function(){if(!c)return null;try{return c([],"length",{value:1}).length!==1}catch{return!0}},vr=e,vr}function Ru(){if(Li)return wr;Li=!0;var c=jt(),e=Pu(),t=Mu()(),r=gs(),a=Kt(),n=c("%Math.floor%");return wr=function(i,s){if(typeof i!="function")throw new a("`fn` is not a function");if(typeof s!="number"||s<0||s>4294967295||n(s)!==s)throw new a("`length` must be a positive 32-bit integer");var o=arguments.length>2&&!!arguments[2],l=!0,u=!0;if("length"in i&&r){var d=r(i,"length");d&&!d.configurable&&(l=!1),d&&!d.writable&&(u=!1)}return(l||u||!o)&&(t?e(i,"length",s,!0,!0):e(i,"length",s)),i},wr}function ju(){if(Ni)return Lt;Ni=!0;var c=ai(),e=jt(),t=Ru(),r=Kt(),a=e("%Function.prototype.apply%"),n=e("%Function.prototype.call%"),i=e("%Reflect.apply%",!0)||c.call(n,a),s=li(),o=e("%Math.max%");Lt=function(u){if(typeof u!="function")throw new r("a function is required");var d=i(c,n,arguments);return t(d,1+o(0,u.length-(arguments.length-1)),!0)};var l=function(){return i(c,a,arguments)};return s?s(Lt,"apply",{value:l}):Lt.apply=l,Lt}function Lu(){if(Ui)return _r;Ui=!0;var c=jt(),e=ju(),t=e(c("String.prototype.indexOf"));return _r=function(r,a){var n=c(r,!!a);return typeof n=="function"&&t(r,".prototype.")>-1?e(n):n},_r}var ci,ui,hi,fi,di,pi,gi,mi,bi,yi,vi,wi,_i,ki,Si,Ei,ur,xi,hr,Ai,fr,Ii,dr,Ti,pr,Ci,gr,Oi,mr,Pi,br,Mi,yr,Ri,vr,ji,wr,Li,Lt,Ni,_r,Ui,Nu=He(()=>{le(),ue(),ce(),ci={},ui=!1,hi={},fi=!1,di={},pi=!1,gi={},mi=!1,bi={},yi=!1,vi={},wi=!1,_i={},ki=!1,Si={},Ei=!1,ur={},xi=!1,hr={},Ai=!1,fr={},Ii=!1,dr={},Ti=!1,pr={},Ci=!1,gr={},Oi=!1,mr={},Pi=!1,br={},Mi=!1,yr={},Ri=!1,vr={},ji=!1,wr={},Li=!1,Lt={},Ni=!1,_r={},Ui=!1});function Bi(c){throw new Error("Node.js process "+c+" is not supported by JSPM core outside of Node.js")}function Uu(){!xt||!At||(xt=!1,At.length?Qe=At.concat(Qe):Vt=-1,Qe.length&&ms())}function ms(){if(!xt){var c=setTimeout(Uu,0);xt=!0;for(var e=Qe.length;e;){for(At=Qe,Qe=[];++Vt<e;)At&&At[Vt].run();Vt=-1,e=Qe.length}At=null,xt=!1,clearTimeout(c)}}function Bu(c){var e=new Array(arguments.length-1);if(arguments.length>1)for(var t=1;t<arguments.length;t++)e[t-1]=arguments[t];Qe.push(new bs(c,e)),Qe.length===1&&!xt&&setTimeout(ms,0)}function bs(c,e){this.fun=c,this.array=e}function Fe(){}function Fu(c){Bi("_linkedBinding")}function Du(c){Bi("dlopen")}function $u(){return[]}function Wu(){return[]}function qu(c,e){if(!c)throw new Error(e||"assertion error")}function Hu(){return!1}function zu(){return ht.now()/1e3}function Fi(c){var e=Math.floor((Date.now()-ht.now())*.001),t=ht.now()*.001,r=Math.floor(t)+e,a=Math.floor(t%1*1e9);return c&&(r=r-c[0],a=a-c[1],a<0&&(r--,a+=Sr)),[r,a]}function bt(){return $i}function Ku(c){return[]}var Qe,xt,At,Vt,ys,vs,ws,_s,ks,Ss,Es,xs,As,Is,Ts,Cs,Os,Ps,Ms,Rs,js,Ls,Ns,Us,Bs,kr,Fs,Ds,$s,Ws,qs,Hs,zs,Ks,Vs,Gs,Ys,Qs,Js,Xs,Zs,ea,ta,ra,na,ia,oa,sa,aa,la,ca,ht,Di,Sr,ua,ha,fa,da,pa,ga,ma,ba,ya,va,wa,$i,_a=He(()=>{le(),ue(),ce(),Qe=[],xt=!1,Vt=-1,bs.prototype.run=function(){this.fun.apply(null,this.array)},ys="browser",vs="x64",ws="browser",_s={PATH:"/usr/bin",LANG:navigator.language+".UTF-8",PWD:"/",HOME:"/home",TMP:"/tmp"},ks=["/usr/bin/node"],Ss=[],Es="v16.8.0",xs={},As=function(c,e){console.warn((e?e+": ":"")+c)},Is=function(c){Bi("binding")},Ts=function(c){return 0},Cs=function(){return"/"},Os=function(c){},Ps={name:"node",sourceUrl:"",headersUrl:"",libUrl:""},Ms=Fe,Rs=[],js={},Ls=!1,Ns={},Us=Fe,Bs=Fe,kr=function(){return{}},Fs=kr,Ds=kr,$s=Fe,Ws=Fe,qs=Fe,Hs={},zs={inspector:!1,debug:!1,uv:!1,ipv6:!1,tls_alpn:!1,tls_sni:!1,tls_ocsp:!1,tls:!1,cached_builtins:!0},Ks=Fe,Vs=Fe,Gs=Fe,Ys=Fe,Qs=Fe,Js=Fe,Xs=Fe,Zs=void 0,ea=void 0,ta=void 0,ra=Fe,na=2,ia=1,oa="/bin/usr/node",sa=9229,aa="node",la=[],ca=Fe,ht={now:typeof performance<"u"?performance.now.bind(performance):void 0,timing:typeof performance<"u"?performance.timing:void 0},ht.now===void 0&&(Di=Date.now(),ht.timing&&ht.timing.navigationStart&&(Di=ht.timing.navigationStart),ht.now=()=>Date.now()-Di),Sr=1e9,Fi.bigint=function(c){var e=Fi(c);return typeof BigInt>"u"?e[0]*Sr+e[1]:BigInt(e[0]*Sr)+BigInt(e[1])},ua=10,ha={},fa=0,da=bt,pa=bt,ga=bt,ma=bt,ba=bt,ya=Fe,va=bt,wa=bt,$i={version:Es,versions:xs,arch:vs,platform:ws,release:Ps,_rawDebug:Ms,moduleLoadList:Rs,binding:Is,_linkedBinding:Fu,_events:ha,_eventsCount:fa,_maxListeners:ua,on:bt,addListener:da,once:pa,off:ga,removeListener:ma,removeAllListeners:ba,emit:ya,prependListener:va,prependOnceListener:wa,listeners:Ku,domain:js,_exiting:Ls,config:Ns,dlopen:Du,uptime:zu,_getActiveRequests:$u,_getActiveHandles:Wu,reallyExit:Us,_kill:Bs,cpuUsage:kr,resourceUsage:Fs,memoryUsage:Ds,kill:$s,exit:Ws,openStdin:qs,allowedNodeEnvironmentFlags:Hs,assert:qu,features:zs,_fatalExceptions:Ks,setUncaughtExceptionCaptureCallback:Vs,hasUncaughtExceptionCaptureCallback:Hu,emitWarning:As,nextTick:Bu,_tickCallback:Gs,_debugProcess:Ys,_debugEnd:Qs,_startProfilerIdleNotifier:Js,_stopProfilerIdleNotifier:Xs,stdout:Zs,stdin:ta,stderr:ea,abort:ra,umask:Ts,chdir:Os,cwd:Cs,env:_s,title:ys,argv:ks,execArgv:Ss,pid:na,ppid:ia,execPath:oa,debugPort:sa,hrtime:Fi,argv0:aa,_preload_modules:la,setSourceMapsEnabled:ca}});function Vu(){if(Wi)return Er;Wi=!0;var c=$i;function e(n){if(typeof n!="string")throw new TypeError("Path must be a string. Received "+JSON.stringify(n))}function t(n,i){for(var s="",o=0,l=-1,u=0,d,p=0;p<=n.length;++p){if(p<n.length)d=n.charCodeAt(p);else{if(d===47)break;d=47}if(d===47){if(!(l===p-1||u===1))if(l!==p-1&&u===2){if(s.length<2||o!==2||s.charCodeAt(s.length-1)!==46||s.charCodeAt(s.length-2)!==46){if(s.length>2){var y=s.lastIndexOf("/");if(y!==s.length-1){y===-1?(s="",o=0):(s=s.slice(0,y),o=s.length-1-s.lastIndexOf("/")),l=p,u=0;continue}}else if(s.length===2||s.length===1){s="",o=0,l=p,u=0;continue}}i&&(s.length>0?s+="/..":s="..",o=2)}else s.length>0?s+="/"+n.slice(l+1,p):s=n.slice(l+1,p),o=p-l-1;l=p,u=0}else d===46&&u!==-1?++u:u=-1}return s}function r(n,i){var s=i.dir||i.root,o=i.base||(i.name||"")+(i.ext||"");return s?s===i.root?s+o:s+n+o:o}var a={resolve:function(){for(var n="",i=!1,s,o=arguments.length-1;o>=-1&&!i;o--){var l;o>=0?l=arguments[o]:(s===void 0&&(s=c.cwd()),l=s),e(l),l.length!==0&&(n=l+"/"+n,i=l.charCodeAt(0)===47)}return n=t(n,!i),i?n.length>0?"/"+n:"/":n.length>0?n:"."},normalize:function(n){if(e(n),n.length===0)return".";var i=n.charCodeAt(0)===47,s=n.charCodeAt(n.length-1)===47;return n=t(n,!i),n.length===0&&!i&&(n="."),n.length>0&&s&&(n+="/"),i?"/"+n:n},isAbsolute:function(n){return e(n),n.length>0&&n.charCodeAt(0)===47},join:function(){if(arguments.length===0)return".";for(var n,i=0;i<arguments.length;++i){var s=arguments[i];e(s),s.length>0&&(n===void 0?n=s:n+="/"+s)}return n===void 0?".":a.normalize(n)},relative:function(n,i){if(e(n),e(i),n===i||(n=a.resolve(n),i=a.resolve(i),n===i))return"";for(var s=1;s<n.length&&n.charCodeAt(s)===47;++s);for(var o=n.length,l=o-s,u=1;u<i.length&&i.charCodeAt(u)===47;++u);for(var d=i.length,p=d-u,y=l<p?l:p,f=-1,m=0;m<=y;++m){if(m===y){if(p>y){if(i.charCodeAt(u+m)===47)return i.slice(u+m+1);if(m===0)return i.slice(u+m)}else l>y&&(n.charCodeAt(s+m)===47?f=m:m===0&&(f=0));break}var b=n.charCodeAt(s+m),k=i.charCodeAt(u+m);if(b!==k)break;b===47&&(f=m)}var g="";for(m=s+f+1;m<=o;++m)(m===o||n.charCodeAt(m)===47)&&(g.length===0?g+="..":g+="/..");return g.length>0?g+i.slice(u+f):(u+=f,i.charCodeAt(u)===47&&++u,i.slice(u))},_makeLong:function(n){return n},dirname:function(n){if(e(n),n.length===0)return".";for(var i=n.charCodeAt(0),s=i===47,o=-1,l=!0,u=n.length-1;u>=1;--u)if(i=n.charCodeAt(u),i===47){if(!l){o=u;break}}else l=!1;return o===-1?s?"/":".":s&&o===1?"//":n.slice(0,o)},basename:function(n,i){if(i!==void 0&&typeof i!="string")throw new TypeError('"ext" argument must be a string');e(n);var s=0,o=-1,l=!0,u;if(i!==void 0&&i.length>0&&i.length<=n.length){if(i.length===n.length&&i===n)return"";var d=i.length-1,p=-1;for(u=n.length-1;u>=0;--u){var y=n.charCodeAt(u);if(y===47){if(!l){s=u+1;break}}else p===-1&&(l=!1,p=u+1),d>=0&&(y===i.charCodeAt(d)?--d===-1&&(o=u):(d=-1,o=p))}return s===o?o=p:o===-1&&(o=n.length),n.slice(s,o)}else{for(u=n.length-1;u>=0;--u)if(n.charCodeAt(u)===47){if(!l){s=u+1;break}}else o===-1&&(l=!1,o=u+1);return o===-1?"":n.slice(s,o)}},extname:function(n){e(n);for(var i=-1,s=0,o=-1,l=!0,u=0,d=n.length-1;d>=0;--d){var p=n.charCodeAt(d);if(p===47){if(!l){s=d+1;break}continue}o===-1&&(l=!1,o=d+1),p===46?i===-1?i=d:u!==1&&(u=1):i!==-1&&(u=-1)}return i===-1||o===-1||u===0||u===1&&i===o-1&&i===s+1?"":n.slice(i,o)},format:function(n){if(n===null||typeof n!="object")throw new TypeError('The "pathObject" argument must be of type Object. Received type '+typeof n);return r("/",n)},parse:function(n){e(n);var i={root:"",dir:"",base:"",ext:"",name:""};if(n.length===0)return i;var s=n.charCodeAt(0),o=s===47,l;o?(i.root="/",l=1):l=0;for(var u=-1,d=0,p=-1,y=!0,f=n.length-1,m=0;f>=l;--f){if(s=n.charCodeAt(f),s===47){if(!y){d=f+1;break}continue}p===-1&&(y=!1,p=f+1),s===46?u===-1?u=f:m!==1&&(m=1):u!==-1&&(m=-1)}return u===-1||p===-1||m===0||m===1&&u===p-1&&u===d+1?p!==-1&&(d===0&&o?i.base=i.name=n.slice(1,p):i.base=i.name=n.slice(d,p)):(d===0&&o?(i.name=n.slice(1,u),i.base=n.slice(1,p)):(i.name=n.slice(d,u),i.base=n.slice(d,p)),i.ext=n.slice(u,p)),d>0?i.dir=n.slice(0,d-1):o&&(i.dir="/"),i},sep:"/",delimiter:":",win32:null,posix:null};return a.posix=a,Er=a,Er}var Er,Wi,qi,Gu=He(()=>{le(),ue(),ce(),_a(),Er={},Wi=!1,qi=Vu()}),ka={};Ct(ka,{URL:()=>Ra,Url:()=>Ta,default:()=>De,fileURLToPath:()=>Ea,format:()=>Ca,parse:()=>Ma,pathToFileURL:()=>xa,resolve:()=>Oa,resolveObject:()=>Pa});function Yu(){if(zi)return xr;zi=!0;var c=typeof Map=="function"&&Map.prototype,e=Object.getOwnPropertyDescriptor&&c?Object.getOwnPropertyDescriptor(Map.prototype,"size"):null,t=c&&e&&typeof e.get=="function"?e.get:null,r=c&&Map.prototype.forEach,a=typeof Set=="function"&&Set.prototype,n=Object.getOwnPropertyDescriptor&&a?Object.getOwnPropertyDescriptor(Set.prototype,"size"):null,i=a&&n&&typeof n.get=="function"?n.get:null,s=a&&Set.prototype.forEach,o=typeof WeakMap=="function"&&WeakMap.prototype,l=o?WeakMap.prototype.has:null,u=typeof WeakSet=="function"&&WeakSet.prototype,d=u?WeakSet.prototype.has:null,p=typeof WeakRef=="function"&&WeakRef.prototype,y=p?WeakRef.prototype.deref:null,f=Boolean.prototype.valueOf,m=Object.prototype.toString,b=Function.prototype.toString,k=String.prototype.match,g=String.prototype.slice,_=String.prototype.replace,S=String.prototype.toUpperCase,v=String.prototype.toLowerCase,x=RegExp.prototype.test,E=Array.prototype.concat,I=Array.prototype.join,M=Array.prototype.slice,O=Math.floor,B=typeof BigInt=="function"?BigInt.prototype.valueOf:null,T=Object.getOwnPropertySymbols,W=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?Symbol.prototype.toString:null,F=typeof Symbol=="function"&&typeof Symbol.iterator=="object",N=typeof Symbol=="function"&&Symbol.toStringTag&&(typeof Symbol.toStringTag===F||!0)?Symbol.toStringTag:null,ae=Object.prototype.propertyIsEnumerable,Y=(typeof Reflect=="function"?Reflect.getPrototypeOf:Object.getPrototypeOf)||([].__proto__===Array.prototype?function(z){return z.__proto__}:null);function K(z,ie){if(z===1/0||z===-1/0||z!==z||z&&z>-1e3&&z<1e3||x.call(/e/,ie))return ie;var xe=/[0-9](?=(?:[0-9]{3})+(?![0-9]))/g;if(typeof z=="number"){var Ae=z<0?-O(-z):O(z);if(Ae!==z){var Ie=String(Ae),Oe=g.call(ie,Ie.length+1);return _.call(Ie,xe,"$&_")+"."+_.call(_.call(Oe,/([0-9]{3})/g,"$&_"),/_$/,"")}}return _.call(ie,xe,"$&_")}var re=Aa,D=re.custom,Z=G(D)?D:null;xr=function z(ie,xe,Ae,Ie){var Oe=xe||{};if(oe(Oe,"quoteStyle")&&Oe.quoteStyle!=="single"&&Oe.quoteStyle!=="double")throw new TypeError('option "quoteStyle" must be "single" or "double"');if(oe(Oe,"maxStringLength")&&(typeof Oe.maxStringLength=="number"?Oe.maxStringLength<0&&Oe.maxStringLength!==1/0:Oe.maxStringLength!==null))throw new TypeError('option "maxStringLength", if provided, must be a positive integer, Infinity, or `null`');var Je=oe(Oe,"customInspect")?Oe.customInspect:!0;if(typeof Je!="boolean"&&Je!=="symbol")throw new TypeError("option \"customInspect\", if provided, must be `true`, `false`, or `'symbol'`");if(oe(Oe,"indent")&&Oe.indent!==null&&Oe.indent!==" "&&!(parseInt(Oe.indent,10)===Oe.indent&&Oe.indent>0))throw new TypeError('option "indent" must be "\\t", an integer > 0, or `null`');if(oe(Oe,"numericSeparator")&&typeof Oe.numericSeparator!="boolean")throw new TypeError('option "numericSeparator", if provided, must be `true` or `false`');var Xe=Oe.numericSeparator;if(typeof ie>"u")return"undefined";if(ie===null)return"null";if(typeof ie=="boolean")return ie?"true":"false";if(typeof ie=="string")return se(ie,Oe);if(typeof ie=="number"){if(ie===0)return 1/0/ie>0?"0":"-0";var $e=String(ie);return Xe?K(ie,$e):$e}if(typeof ie=="bigint"){var Ze=String(ie)+"n";return Xe?K(ie,Ze):Ze}var Bt=typeof Oe.depth>"u"?5:Oe.depth;if(typeof Ae>"u"&&(Ae=0),Ae>=Bt&&Bt>0&&typeof ie=="object")return be(ie)?"[Array]":"[Object]";var et=X(Oe,Ae);if(typeof Ie>"u")Ie=[];else if(ee(Ie,ie)>=0)return"[Circular]";function Ve(tt,vt,Tt){if(vt&&(Ie=M.call(Ie),Ie.push(vt)),Tt){var rt={depth:Oe.depth};return oe(Oe,"quoteStyle")&&(rt.quoteStyle=Oe.quoteStyle),z(tt,rt,Ae+1,Ie)}return z(tt,Oe,Ae+1,Ie)}if(typeof ie=="function"&&!we(ie)){var Br=$(ie),Ft=ke(ie,Ve);return"[Function"+(Br?": "+Br:" (anonymous)")+"]"+(Ft.length>0?" { "+I.call(Ft,", ")+" }":"")}if(G(ie)){var Gt=F?_.call(String(ie),/^(Symbol\(.*\))_[^)]*$/,"$1"):W.call(ie);return typeof ie=="object"&&!F?h(Gt):Gt}if(ve(ie)){for(var C="<"+v.call(String(ie.nodeName)),j=ie.attributes||[],_e=0;_e<j.length;_e++)C+=" "+j[_e].name+"="+P(J(j[_e].value),"double",Oe);return C+=">",ie.childNodes&&ie.childNodes.length&&(C+="..."),C+="</"+v.call(String(ie.nodeName))+">",C}if(be(ie)){if(ie.length===0)return"[]";var Se=ke(ie,Ve);return et&&!U(Se)?"["+he(Se,et)+"]":"[ "+I.call(Se,", ")+" ]"}if(V(ie)){var Ee=ke(ie,Ve);return!("cause"in Error.prototype)&&"cause"in ie&&!ae.call(ie,"cause")?"{ ["+String(ie)+"] "+I.call(E.call("[cause]: "+Ve(ie.cause),Ee),", ")+" }":Ee.length===0?"["+String(ie)+"]":"{ ["+String(ie)+"] "+I.call(Ee,", ")+" }"}if(typeof ie=="object"&&Je){if(Z&&typeof ie[Z]=="function"&&re)return re(ie,{depth:Bt-Ae});if(Je!=="symbol"&&typeof ie.inspect=="function")return ie.inspect()}if(fe(ie)){var Le=[];return r&&r.call(ie,function(tt,vt){Le.push(Ve(vt,ie,!0)+" => "+Ve(tt,ie))}),A("Map",t.call(ie),Le,et)}if(q(ie)){var qe=[];return s&&s.call(ie,function(tt){qe.push(Ve(tt,ie))}),A("Set",i.call(ie),qe,et)}if(de(ie))return w("WeakMap");if(ge(ie))return w("WeakSet");if(ye(ie))return w("WeakRef");if(ne(ie))return h(Ve(Number(ie)));if(Q(ie))return h(Ve(B.call(ie)));if(H(ie))return h(f.call(ie));if(L(ie))return h(Ve(String(ie)));if(typeof window<"u"&&ie===window)return"{ [object Window] }";if(typeof globalThis<"u"&&ie===globalThis||typeof Ar<"u"&&ie===Ar)return"{ [object globalThis] }";if(!te(ie)&&!we(ie)){var Ge=ke(ie,Ve),Yt=Y?Y(ie)===Object.prototype:ie instanceof Object||ie.constructor===Object,Qt=ie instanceof Object?"":"null prototype",Jt=!Yt&&N&&Object(ie)===ie&&N in ie?g.call(R(ie),8,-1):Qt?"Object":"",Fr=Yt||typeof ie.constructor!="function"?"":ie.constructor.name?ie.constructor.name+" ":"",It=Fr+(Jt||Qt?"["+I.call(E.call([],Jt||[],Qt||[]),": ")+"] ":"");return Ge.length===0?It+"{}":et?It+"{"+he(Ge,et)+"}":It+"{ "+I.call(Ge,", ")+" }"}return String(ie)};function P(z,ie,xe){var Ae=(xe.quoteStyle||ie)==="double"?'"':"'";return Ae+z+Ae}function J(z){return _.call(String(z),/"/g,"&quot;")}function be(z){return R(z)==="[object Array]"&&(!N||!(typeof z=="object"&&N in z))}function te(z){return R(z)==="[object Date]"&&(!N||!(typeof z=="object"&&N in z))}function we(z){return R(z)==="[object RegExp]"&&(!N||!(typeof z=="object"&&N in z))}function V(z){return R(z)==="[object Error]"&&(!N||!(typeof z=="object"&&N in z))}function L(z){return R(z)==="[object String]"&&(!N||!(typeof z=="object"&&N in z))}function ne(z){return R(z)==="[object Number]"&&(!N||!(typeof z=="object"&&N in z))}function H(z){return R(z)==="[object Boolean]"&&(!N||!(typeof z=="object"&&N in z))}function G(z){if(F)return z&&typeof z=="object"&&z instanceof Symbol;if(typeof z=="symbol")return!0;if(!z||typeof z!="object"||!W)return!1;try{return W.call(z),!0}catch{}return!1}function Q(z){if(!z||typeof z!="object"||!B)return!1;try{return B.call(z),!0}catch{}return!1}var me=Object.prototype.hasOwnProperty||function(z){return z in(this||Ar)};function oe(z,ie){return me.call(z,ie)}function R(z){return m.call(z)}function $(z){if(z.name)return z.name;var ie=k.call(b.call(z),/^function\s*([\w$]+)/);return ie?ie[1]:null}function ee(z,ie){if(z.indexOf)return z.indexOf(ie);for(var xe=0,Ae=z.length;xe<Ae;xe++)if(z[xe]===ie)return xe;return-1}function fe(z){if(!t||!z||typeof z!="object")return!1;try{t.call(z);try{i.call(z)}catch{return!0}return z instanceof Map}catch{}return!1}function de(z){if(!l||!z||typeof z!="object")return!1;try{l.call(z,l);try{d.call(z,d)}catch{return!0}return z instanceof WeakMap}catch{}return!1}function ye(z){if(!y||!z||typeof z!="object")return!1;try{return y.call(z),!0}catch{}return!1}function q(z){if(!i||!z||typeof z!="object")return!1;try{i.call(z);try{t.call(z)}catch{return!0}return z instanceof Set}catch{}return!1}function ge(z){if(!d||!z||typeof z!="object")return!1;try{d.call(z,d);try{l.call(z,l)}catch{return!0}return z instanceof WeakSet}catch{}return!1}function ve(z){return!z||typeof z!="object"?!1:typeof HTMLElement<"u"&&z instanceof HTMLElement?!0:typeof z.nodeName=="string"&&typeof z.getAttribute=="function"}function se(z,ie){if(z.length>ie.maxStringLength){var xe=z.length-ie.maxStringLength,Ae="... "+xe+" more character"+(xe>1?"s":"");return se(g.call(z,0,ie.maxStringLength),ie)+Ae}var Ie=_.call(_.call(z,/(['\\])/g,"\\$1"),/[\x00-\x1f]/g,Te);return P(Ie,"single",ie)}function Te(z){var ie=z.charCodeAt(0),xe={8:"b",9:"t",10:"n",12:"f",13:"r"}[ie];return xe?"\\"+xe:"\\x"+(ie<16?"0":"")+S.call(ie.toString(16))}function h(z){return"Object("+z+")"}function w(z){return z+" { ? }"}function A(z,ie,xe,Ae){var Ie=Ae?he(xe,Ae):I.call(xe,", ");return z+" ("+ie+") {"+Ie+"}"}function U(z){for(var ie=0;ie<z.length;ie++)if(ee(z[ie],`
4
4
  `)>=0)return!1;return!0}function X(z,ie){var xe;if(z.indent===" ")xe=" ";else if(typeof z.indent=="number"&&z.indent>0)xe=I.call(Array(z.indent+1)," ");else return null;return{base:xe,prev:I.call(Array(ie+1),xe)}}function he(z,ie){if(z.length===0)return"";var xe=`
5
5
  `+ie.prev+ie.base;return xe+I.call(z,","+xe)+`
6
- `+ie.prev}function ke(z,ie){var xe=be(z),Ae=[];if(xe){Ae.length=z.length;for(var Ie=0;Ie<z.length;Ie++)Ae[Ie]=oe(z,Ie)?ie(z[Ie],z):""}var Oe=typeof T=="function"?T(z):[],Je;if(F){Je={};for(var Xe=0;Xe<Oe.length;Xe++)Je["$"+Oe[Xe]]=Oe[Xe]}for(var $e in z)oe(z,$e)&&(xe&&String(Number($e))===$e&&$e<z.length||F&&Je["$"+$e]instanceof Symbol||(x.call(/[^\w$]/,$e)?Ae.push(ie($e,z)+": "+ie(z[$e],z)):Ae.push($e+": "+ie(z[$e],z))));if(typeof T=="function")for(var Ze=0;Ze<Oe.length;Ze++)ae.call(z,Oe[Ze])&&Ae.push("["+ie(Oe[Ze])+"]: "+ie(z[Oe[Ze]],z));return Ae}return xr}function Qu(){if(Ki)return Ir;Ki=!0;var c=jt(),e=Lu(),t=Yu(),r=Kt(),a=c("%WeakMap%",!0),n=c("%Map%",!0),i=e("WeakMap.prototype.get",!0),s=e("WeakMap.prototype.set",!0),o=e("WeakMap.prototype.has",!0),l=e("Map.prototype.get",!0),u=e("Map.prototype.set",!0),d=e("Map.prototype.has",!0),p=function(b,k){for(var m=b,w;(w=m.next)!==null;m=w)if(w.key===k)return m.next=w.next,w.next=b.next,b.next=w,w},y=function(b,k){var m=p(b,k);return m&&m.value},f=function(b,k,m){var w=p(b,k);w?w.value=m:b.next={key:k,next:b.next,value:m}},g=function(b,k){return!!p(b,k)};return Ir=function(){var b,k,m,w={assert:function(E){if(!w.has(E))throw new r("Side channel does not contain "+t(E))},get:function(E){if(a&&E&&(typeof E=="object"||typeof E=="function")){if(b)return i(b,E)}else if(n){if(k)return l(k,E)}else if(m)return y(m,E)},has:function(E){if(a&&E&&(typeof E=="object"||typeof E=="function")){if(b)return o(b,E)}else if(n){if(k)return d(k,E)}else if(m)return g(m,E);return!1},set:function(E,v){a&&E&&(typeof E=="object"||typeof E=="function")?(b||(b=new a),s(b,E,v)):n?(k||(k=new n),u(k,E,v)):(m||(m={key:{},next:null}),f(m,E,v))}};return w},Ir}function Hi(){if(Vi)return Tr;Vi=!0;var c=String.prototype.replace,e=/%20/g,t={RFC1738:"RFC1738",RFC3986:"RFC3986"};return Tr={default:t.RFC3986,formatters:{RFC1738:function(r){return c.call(r,e,"+")},RFC3986:function(r){return String(r)}},RFC1738:t.RFC1738,RFC3986:t.RFC3986},Tr}function Sa(){if(Gi)return Cr;Gi=!0;var c=Hi(),e=Object.prototype.hasOwnProperty,t=Array.isArray,r=(function(){for(var b=[],k=0;k<256;++k)b.push("%"+((k<16?"0":"")+k.toString(16)).toUpperCase());return b})(),a=function(b){for(;b.length>1;){var k=b.pop(),m=k.obj[k.prop];if(t(m)){for(var w=[],E=0;E<m.length;++E)typeof m[E]<"u"&&w.push(m[E]);k.obj[k.prop]=w}}},n=function(b,k){for(var m=k&&k.plainObjects?Object.create(null):{},w=0;w<b.length;++w)typeof b[w]<"u"&&(m[w]=b[w]);return m},i=function b(k,m,w){if(!m)return k;if(typeof m!="object"){if(t(k))k.push(m);else if(k&&typeof k=="object")(w&&(w.plainObjects||w.allowPrototypes)||!e.call(Object.prototype,m))&&(k[m]=!0);else return[k,m];return k}if(!k||typeof k!="object")return[k].concat(m);var E=k;return t(k)&&!t(m)&&(E=n(k,w)),t(k)&&t(m)?(m.forEach(function(v,x){if(e.call(k,x)){var S=k[x];S&&typeof S=="object"&&v&&typeof v=="object"?k[x]=b(S,v,w):k.push(v)}else k[x]=v}),k):Object.keys(m).reduce(function(v,x){var S=m[x];return e.call(v,x)?v[x]=b(v[x],S,w):v[x]=S,v},E)},s=function(b,k){return Object.keys(k).reduce(function(m,w){return m[w]=k[w],m},b)},o=function(b,k,m){var w=b.replace(/\+/g," ");if(m==="iso-8859-1")return w.replace(/%[0-9a-f]{2}/gi,unescape);try{return decodeURIComponent(w)}catch{return w}},l=1024,u=function(b,k,m,w,E){if(b.length===0)return b;var v=b;if(typeof b=="symbol"?v=Symbol.prototype.toString.call(b):typeof b!="string"&&(v=String(b)),m==="iso-8859-1")return escape(v).replace(/%u[0-9a-f]{4}/gi,function(T){return"%26%23"+parseInt(T.slice(2),16)+"%3B"});for(var x="",S=0;S<v.length;S+=l){for(var I=v.length>=l?v.slice(S,S+l):v,M=[],O=0;O<I.length;++O){var B=I.charCodeAt(O);if(B===45||B===46||B===95||B===126||B>=48&&B<=57||B>=65&&B<=90||B>=97&&B<=122||E===c.RFC1738&&(B===40||B===41)){M[M.length]=I.charAt(O);continue}if(B<128){M[M.length]=r[B];continue}if(B<2048){M[M.length]=r[192|B>>6]+r[128|B&63];continue}if(B<55296||B>=57344){M[M.length]=r[224|B>>12]+r[128|B>>6&63]+r[128|B&63];continue}O+=1,B=65536+((B&1023)<<10|I.charCodeAt(O)&1023),M[M.length]=r[240|B>>18]+r[128|B>>12&63]+r[128|B>>6&63]+r[128|B&63]}x+=M.join("")}return x},d=function(b){for(var k=[{obj:{o:b},prop:"o"}],m=[],w=0;w<k.length;++w)for(var E=k[w],v=E.obj[E.prop],x=Object.keys(v),S=0;S<x.length;++S){var I=x[S],M=v[I];typeof M=="object"&&M!==null&&m.indexOf(M)===-1&&(k.push({obj:v,prop:I}),m.push(M))}return a(k),b},p=function(b){return Object.prototype.toString.call(b)==="[object RegExp]"},y=function(b){return!b||typeof b!="object"?!1:!!(b.constructor&&b.constructor.isBuffer&&b.constructor.isBuffer(b))},f=function(b,k){return[].concat(b,k)},g=function(b,k){if(t(b)){for(var m=[],w=0;w<b.length;w+=1)m.push(k(b[w]));return m}return k(b)};return Cr={arrayToObject:n,assign:s,combine:f,compact:d,decode:o,encode:u,isBuffer:y,isRegExp:p,maybeMap:g,merge:i},Cr}function Ju(){if(Yi)return Or;Yi=!0;var c=Qu(),e=Sa(),t=Hi(),r=Object.prototype.hasOwnProperty,a={brackets:function(g){return g+"[]"},comma:"comma",indices:function(g,b){return g+"["+b+"]"},repeat:function(g){return g}},n=Array.isArray,i=Array.prototype.push,s=function(g,b){i.apply(g,n(b)?b:[b])},o=Date.prototype.toISOString,l=t.default,u={addQueryPrefix:!1,allowDots:!1,allowEmptyArrays:!1,arrayFormat:"indices",charset:"utf-8",charsetSentinel:!1,delimiter:"&",encode:!0,encodeDotInKeys:!1,encoder:e.encode,encodeValuesOnly:!1,format:l,formatter:t.formatters[l],indices:!1,serializeDate:function(g){return o.call(g)},skipNulls:!1,strictNullHandling:!1},d=function(g){return typeof g=="string"||typeof g=="number"||typeof g=="boolean"||typeof g=="symbol"||typeof g=="bigint"},p={},y=function g(b,k,m,w,E,v,x,S,I,M,O,B,T,W,F,N,ae,Y){for(var K=b,re=Y,D=0,Z=!1;(re=re.get(p))!==void 0&&!Z;){var P=re.get(b);if(D+=1,typeof P<"u"){if(P===D)throw new RangeError("Cyclic object value");Z=!0}typeof re.get(p)>"u"&&(D=0)}if(typeof M=="function"?K=M(k,K):K instanceof Date?K=T(K):m==="comma"&&n(K)&&(K=e.maybeMap(K,function(R){return R instanceof Date?T(R):R})),K===null){if(v)return I&&!N?I(k,u.encoder,ae,"key",W):k;K=""}if(d(K)||e.isBuffer(K)){if(I){var J=N?k:I(k,u.encoder,ae,"key",W);return[F(J)+"="+F(I(K,u.encoder,ae,"value",W))]}return[F(k)+"="+F(String(K))]}var be=[];if(typeof K>"u")return be;var te;if(m==="comma"&&n(K))N&&I&&(K=e.maybeMap(K,I)),te=[{value:K.length>0?K.join(",")||null:void 0}];else if(n(M))te=M;else{var we=Object.keys(K);te=O?we.sort(O):we}var V=S?k.replace(/\./g,"%2E"):k,L=w&&n(K)&&K.length===1?V+"[]":V;if(E&&n(K)&&K.length===0)return L+"[]";for(var ne=0;ne<te.length;++ne){var H=te[ne],G=typeof H=="object"&&typeof H.value<"u"?H.value:K[H];if(!(x&&G===null)){var Q=B&&S?H.replace(/\./g,"%2E"):H,me=n(K)?typeof m=="function"?m(L,Q):L:L+(B?"."+Q:"["+Q+"]");Y.set(b,D);var oe=c();oe.set(p,Y),s(be,g(G,me,m,w,E,v,x,S,m==="comma"&&N&&n(K)?null:I,M,O,B,T,W,F,N,ae,oe))}}return be},f=function(g){if(!g)return u;if(typeof g.allowEmptyArrays<"u"&&typeof g.allowEmptyArrays!="boolean")throw new TypeError("`allowEmptyArrays` option can only be `true` or `false`, when provided");if(typeof g.encodeDotInKeys<"u"&&typeof g.encodeDotInKeys!="boolean")throw new TypeError("`encodeDotInKeys` option can only be `true` or `false`, when provided");if(g.encoder!==null&&typeof g.encoder<"u"&&typeof g.encoder!="function")throw new TypeError("Encoder has to be a function.");var b=g.charset||u.charset;if(typeof g.charset<"u"&&g.charset!=="utf-8"&&g.charset!=="iso-8859-1")throw new TypeError("The charset option must be either utf-8, iso-8859-1, or undefined");var k=t.default;if(typeof g.format<"u"){if(!r.call(t.formatters,g.format))throw new TypeError("Unknown format option provided.");k=g.format}var m=t.formatters[k],w=u.filter;(typeof g.filter=="function"||n(g.filter))&&(w=g.filter);var E;if(g.arrayFormat in a?E=g.arrayFormat:"indices"in g?E=g.indices?"indices":"repeat":E=u.arrayFormat,"commaRoundTrip"in g&&typeof g.commaRoundTrip!="boolean")throw new TypeError("`commaRoundTrip` must be a boolean, or absent");var v=typeof g.allowDots>"u"?g.encodeDotInKeys===!0?!0:u.allowDots:!!g.allowDots;return{addQueryPrefix:typeof g.addQueryPrefix=="boolean"?g.addQueryPrefix:u.addQueryPrefix,allowDots:v,allowEmptyArrays:typeof g.allowEmptyArrays=="boolean"?!!g.allowEmptyArrays:u.allowEmptyArrays,arrayFormat:E,charset:b,charsetSentinel:typeof g.charsetSentinel=="boolean"?g.charsetSentinel:u.charsetSentinel,commaRoundTrip:g.commaRoundTrip,delimiter:typeof g.delimiter>"u"?u.delimiter:g.delimiter,encode:typeof g.encode=="boolean"?g.encode:u.encode,encodeDotInKeys:typeof g.encodeDotInKeys=="boolean"?g.encodeDotInKeys:u.encodeDotInKeys,encoder:typeof g.encoder=="function"?g.encoder:u.encoder,encodeValuesOnly:typeof g.encodeValuesOnly=="boolean"?g.encodeValuesOnly:u.encodeValuesOnly,filter:w,format:k,formatter:m,serializeDate:typeof g.serializeDate=="function"?g.serializeDate:u.serializeDate,skipNulls:typeof g.skipNulls=="boolean"?g.skipNulls:u.skipNulls,sort:typeof g.sort=="function"?g.sort:null,strictNullHandling:typeof g.strictNullHandling=="boolean"?g.strictNullHandling:u.strictNullHandling}};return Or=function(g,b){var k=g,m=f(b),w,E;typeof m.filter=="function"?(E=m.filter,k=E("",k)):n(m.filter)&&(E=m.filter,w=E);var v=[];if(typeof k!="object"||k===null)return"";var x=a[m.arrayFormat],S=x==="comma"&&m.commaRoundTrip;w||(w=Object.keys(k)),m.sort&&w.sort(m.sort);for(var I=c(),M=0;M<w.length;++M){var O=w[M];m.skipNulls&&k[O]===null||s(v,y(k[O],O,x,S,m.allowEmptyArrays,m.strictNullHandling,m.skipNulls,m.encodeDotInKeys,m.encode?m.encoder:null,m.filter,m.sort,m.allowDots,m.serializeDate,m.format,m.formatter,m.encodeValuesOnly,m.charset,I))}var B=v.join(m.delimiter),T=m.addQueryPrefix===!0?"?":"";return m.charsetSentinel&&(m.charset==="iso-8859-1"?T+="utf8=%26%2310003%3B&":T+="utf8=%E2%9C%93&"),B.length>0?T+B:""},Or}function Xu(){if(Qi)return Pr;Qi=!0;var c=Sa(),e=Object.prototype.hasOwnProperty,t=Array.isArray,r={allowDots:!1,allowEmptyArrays:!1,allowPrototypes:!1,allowSparse:!1,arrayLimit:20,charset:"utf-8",charsetSentinel:!1,comma:!1,decodeDotInKeys:!1,decoder:c.decode,delimiter:"&",depth:5,duplicates:"combine",ignoreQueryPrefix:!1,interpretNumericEntities:!1,parameterLimit:1e3,parseArrays:!0,plainObjects:!1,strictDepth:!1,strictNullHandling:!1},a=function(p){return p.replace(/&#(\d+);/g,function(y,f){return String.fromCharCode(parseInt(f,10))})},n=function(p,y){return p&&typeof p=="string"&&y.comma&&p.indexOf(",")>-1?p.split(","):p},i="utf8=%26%2310003%3B",s="utf8=%E2%9C%93",o=function(p,y){var f={__proto__:null},g=y.ignoreQueryPrefix?p.replace(/^\?/,""):p;g=g.replace(/%5B/gi,"[").replace(/%5D/gi,"]");var b=y.parameterLimit===1/0?void 0:y.parameterLimit,k=g.split(y.delimiter,b),m=-1,w,E=y.charset;if(y.charsetSentinel)for(w=0;w<k.length;++w)k[w].indexOf("utf8=")===0&&(k[w]===s?E="utf-8":k[w]===i&&(E="iso-8859-1"),m=w,w=k.length);for(w=0;w<k.length;++w)if(w!==m){var v=k[w],x=v.indexOf("]="),S=x===-1?v.indexOf("="):x+1,I,M;S===-1?(I=y.decoder(v,r.decoder,E,"key"),M=y.strictNullHandling?null:""):(I=y.decoder(v.slice(0,S),r.decoder,E,"key"),M=c.maybeMap(n(v.slice(S+1),y),function(B){return y.decoder(B,r.decoder,E,"value")})),M&&y.interpretNumericEntities&&E==="iso-8859-1"&&(M=a(M)),v.indexOf("[]=")>-1&&(M=t(M)?[M]:M);var O=e.call(f,I);O&&y.duplicates==="combine"?f[I]=c.combine(f[I],M):(!O||y.duplicates==="last")&&(f[I]=M)}return f},l=function(p,y,f,g){for(var b=g?y:n(y,f),k=p.length-1;k>=0;--k){var m,w=p[k];if(w==="[]"&&f.parseArrays)m=f.allowEmptyArrays&&(b===""||f.strictNullHandling&&b===null)?[]:[].concat(b);else{m=f.plainObjects?Object.create(null):{};var E=w.charAt(0)==="["&&w.charAt(w.length-1)==="]"?w.slice(1,-1):w,v=f.decodeDotInKeys?E.replace(/%2E/g,"."):E,x=parseInt(v,10);!f.parseArrays&&v===""?m={0:b}:!isNaN(x)&&w!==v&&String(x)===v&&x>=0&&f.parseArrays&&x<=f.arrayLimit?(m=[],m[x]=b):v!=="__proto__"&&(m[v]=b)}b=m}return b},u=function(p,y,f,g){if(p){var b=f.allowDots?p.replace(/\.([^.[]+)/g,"[$1]"):p,k=/(\[[^[\]]*])/,m=/(\[[^[\]]*])/g,w=f.depth>0&&k.exec(b),E=w?b.slice(0,w.index):b,v=[];if(E){if(!f.plainObjects&&e.call(Object.prototype,E)&&!f.allowPrototypes)return;v.push(E)}for(var x=0;f.depth>0&&(w=m.exec(b))!==null&&x<f.depth;){if(x+=1,!f.plainObjects&&e.call(Object.prototype,w[1].slice(1,-1))&&!f.allowPrototypes)return;v.push(w[1])}if(w){if(f.strictDepth===!0)throw new RangeError("Input depth exceeded depth option of "+f.depth+" and strictDepth is true");v.push("["+b.slice(w.index)+"]")}return l(v,y,f,g)}},d=function(p){if(!p)return r;if(typeof p.allowEmptyArrays<"u"&&typeof p.allowEmptyArrays!="boolean")throw new TypeError("`allowEmptyArrays` option can only be `true` or `false`, when provided");if(typeof p.decodeDotInKeys<"u"&&typeof p.decodeDotInKeys!="boolean")throw new TypeError("`decodeDotInKeys` option can only be `true` or `false`, when provided");if(p.decoder!==null&&typeof p.decoder<"u"&&typeof p.decoder!="function")throw new TypeError("Decoder has to be a function.");if(typeof p.charset<"u"&&p.charset!=="utf-8"&&p.charset!=="iso-8859-1")throw new TypeError("The charset option must be either utf-8, iso-8859-1, or undefined");var y=typeof p.charset>"u"?r.charset:p.charset,f=typeof p.duplicates>"u"?r.duplicates:p.duplicates;if(f!=="combine"&&f!=="first"&&f!=="last")throw new TypeError("The duplicates option must be either combine, first, or last");var g=typeof p.allowDots>"u"?p.decodeDotInKeys===!0?!0:r.allowDots:!!p.allowDots;return{allowDots:g,allowEmptyArrays:typeof p.allowEmptyArrays=="boolean"?!!p.allowEmptyArrays:r.allowEmptyArrays,allowPrototypes:typeof p.allowPrototypes=="boolean"?p.allowPrototypes:r.allowPrototypes,allowSparse:typeof p.allowSparse=="boolean"?p.allowSparse:r.allowSparse,arrayLimit:typeof p.arrayLimit=="number"?p.arrayLimit:r.arrayLimit,charset:y,charsetSentinel:typeof p.charsetSentinel=="boolean"?p.charsetSentinel:r.charsetSentinel,comma:typeof p.comma=="boolean"?p.comma:r.comma,decodeDotInKeys:typeof p.decodeDotInKeys=="boolean"?p.decodeDotInKeys:r.decodeDotInKeys,decoder:typeof p.decoder=="function"?p.decoder:r.decoder,delimiter:typeof p.delimiter=="string"||c.isRegExp(p.delimiter)?p.delimiter:r.delimiter,depth:typeof p.depth=="number"||p.depth===!1?+p.depth:r.depth,duplicates:f,ignoreQueryPrefix:p.ignoreQueryPrefix===!0,interpretNumericEntities:typeof p.interpretNumericEntities=="boolean"?p.interpretNumericEntities:r.interpretNumericEntities,parameterLimit:typeof p.parameterLimit=="number"?p.parameterLimit:r.parameterLimit,parseArrays:p.parseArrays!==!1,plainObjects:typeof p.plainObjects=="boolean"?p.plainObjects:r.plainObjects,strictDepth:typeof p.strictDepth=="boolean"?!!p.strictDepth:r.strictDepth,strictNullHandling:typeof p.strictNullHandling=="boolean"?p.strictNullHandling:r.strictNullHandling}};return Pr=function(p,y){var f=d(y);if(p===""||p===null||typeof p>"u")return f.plainObjects?Object.create(null):{};for(var g=typeof p=="string"?o(p,f):p,b=f.plainObjects?Object.create(null):{},k=Object.keys(g),m=0;m<k.length;++m){var w=k[m],E=u(w,g[w],f,typeof p=="string");b=c.merge(b,E,f)}return f.allowSparse===!0?b:c.compact(b)},Pr}function Zu(){if(Ji)return Mr;Ji=!0;var c=Ju(),e=Xu(),t=Hi();return Mr={formats:t,parse:e,stringify:c},Mr}function eh(){if(Xi)return yt;Xi=!0;var c=mt;function e(){this.protocol=null,this.slashes=null,this.auth=null,this.host=null,this.port=null,this.hostname=null,this.hash=null,this.search=null,this.query=null,this.pathname=null,this.path=null,this.href=null}var t=/^([a-z0-9.+-]+:)/i,r=/:[0-9]*$/,a=/^(\/\/?(?!\/)[^?\s]*)(\?[^\s]*)?$/,n=["<",">",'"',"`"," ","\r",`
7
- `," "],i=["{","}","|","\\","^","`"].concat(n),s=["'"].concat(i),o=["%","/","?",";","#"].concat(s),l=["/","?","#"],u=255,d=/^[+a-z0-9A-Z_-]{0,63}$/,p=/^([+a-z0-9A-Z_-]{0,63})(.*)$/,y={javascript:!0,"javascript:":!0},f={javascript:!0,"javascript:":!0},g={http:!0,https:!0,ftp:!0,gopher:!0,file:!0,"http:":!0,"https:":!0,"ftp:":!0,"gopher:":!0,"file:":!0},b=Zu();function k(v,x,S){if(v&&typeof v=="object"&&v instanceof e)return v;var I=new e;return I.parse(v,x,S),I}e.prototype.parse=function(v,x,S){if(typeof v!="string")throw new TypeError("Parameter 'url' must be a string, not "+typeof v);var I=v.indexOf("?"),M=I!==-1&&I<v.indexOf("#")?"?":"#",O=v.split(M),B=/\\/g;O[0]=O[0].replace(B,"/"),v=O.join(M);var T=v;if(T=T.trim(),!S&&v.split("#").length===1){var W=a.exec(T);if(W)return this.path=T,this.href=T,this.pathname=W[1],W[2]?(this.search=W[2],x?this.query=b.parse(this.search.substr(1)):this.query=this.search.substr(1)):x&&(this.search="",this.query={}),this}var F=t.exec(T);if(F){F=F[0];var N=F.toLowerCase();this.protocol=N,T=T.substr(F.length)}if(S||F||T.match(/^\/\/[^@/]+@[^@/]+/)){var ae=T.substr(0,2)==="//";ae&&!(F&&f[F])&&(T=T.substr(2),this.slashes=!0)}if(!f[F]&&(ae||F&&!g[F])){for(var Y=-1,K=0;K<l.length;K++){var re=T.indexOf(l[K]);re!==-1&&(Y===-1||re<Y)&&(Y=re)}var D,Z;Y===-1?Z=T.lastIndexOf("@"):Z=T.lastIndexOf("@",Y),Z!==-1&&(D=T.slice(0,Z),T=T.slice(Z+1),this.auth=decodeURIComponent(D)),Y=-1;for(var K=0;K<o.length;K++){var re=T.indexOf(o[K]);re!==-1&&(Y===-1||re<Y)&&(Y=re)}Y===-1&&(Y=T.length),this.host=T.slice(0,Y),T=T.slice(Y),this.parseHost(),this.hostname=this.hostname||"";var P=this.hostname[0]==="["&&this.hostname[this.hostname.length-1]==="]";if(!P)for(var J=this.hostname.split(/\./),K=0,be=J.length;K<be;K++){var te=J[K];if(te&&!te.match(d)){for(var we="",V=0,L=te.length;V<L;V++)te.charCodeAt(V)>127?we+="x":we+=te[V];if(!we.match(d)){var ne=J.slice(0,K),H=J.slice(K+1),G=te.match(p);G&&(ne.push(G[1]),H.unshift(G[2])),H.length&&(T="/"+H.join(".")+T),this.hostname=ne.join(".");break}}}this.hostname.length>u?this.hostname="":this.hostname=this.hostname.toLowerCase(),P||(this.hostname=c.toASCII(this.hostname));var Q=this.port?":"+this.port:"",me=this.hostname||"";this.host=me+Q,this.href+=this.host,P&&(this.hostname=this.hostname.substr(1,this.hostname.length-2),T[0]!=="/"&&(T="/"+T))}if(!y[N])for(var K=0,be=s.length;K<be;K++){var oe=s[K];if(T.indexOf(oe)!==-1){var R=encodeURIComponent(oe);R===oe&&(R=escape(oe)),T=T.split(oe).join(R)}}var $=T.indexOf("#");$!==-1&&(this.hash=T.substr($),T=T.slice(0,$));var ee=T.indexOf("?");if(ee!==-1?(this.search=T.substr(ee),this.query=T.substr(ee+1),x&&(this.query=b.parse(this.query)),T=T.slice(0,ee)):x&&(this.search="",this.query={}),T&&(this.pathname=T),g[N]&&this.hostname&&!this.pathname&&(this.pathname="/"),this.pathname||this.search){var Q=this.pathname||"",fe=this.search||"";this.path=Q+fe}return this.href=this.format(),this};function m(v){return typeof v=="string"&&(v=k(v)),v instanceof e?v.format():e.prototype.format.call(v)}e.prototype.format=function(){var v=this.auth||"";v&&(v=encodeURIComponent(v),v=v.replace(/%3A/i,":"),v+="@");var x=this.protocol||"",S=this.pathname||"",I=this.hash||"",M=!1,O="";this.host?M=v+this.host:this.hostname&&(M=v+(this.hostname.indexOf(":")===-1?this.hostname:"["+this.hostname+"]"),this.port&&(M+=":"+this.port)),this.query&&typeof this.query=="object"&&Object.keys(this.query).length&&(O=b.stringify(this.query,{arrayFormat:"repeat",addQueryPrefix:!1}));var B=this.search||O&&"?"+O||"";return x&&x.substr(-1)!==":"&&(x+=":"),this.slashes||(!x||g[x])&&M!==!1?(M="//"+(M||""),S&&S.charAt(0)!=="/"&&(S="/"+S)):M||(M=""),I&&I.charAt(0)!=="#"&&(I="#"+I),B&&B.charAt(0)!=="?"&&(B="?"+B),S=S.replace(/[?#]/g,function(T){return encodeURIComponent(T)}),B=B.replace("#","%23"),x+M+S+B+I};function w(v,x){return k(v,!1,!0).resolve(x)}e.prototype.resolve=function(v){return this.resolveObject(k(v,!1,!0)).format()};function E(v,x){return v?k(v,!1,!0).resolveObject(x):x}return e.prototype.resolveObject=function(v){if(typeof v=="string"){var x=new e;x.parse(v,!1,!0),v=x}for(var S=new e,I=Object.keys(this),M=0;M<I.length;M++){var O=I[M];S[O]=this[O]}if(S.hash=v.hash,v.href==="")return S.href=S.format(),S;if(v.slashes&&!v.protocol){for(var B=Object.keys(v),T=0;T<B.length;T++){var W=B[T];W!=="protocol"&&(S[W]=v[W])}return g[S.protocol]&&S.hostname&&!S.pathname&&(S.pathname="/",S.path=S.pathname),S.href=S.format(),S}if(v.protocol&&v.protocol!==S.protocol){if(!g[v.protocol]){for(var F=Object.keys(v),N=0;N<F.length;N++){var ae=F[N];S[ae]=v[ae]}return S.href=S.format(),S}if(S.protocol=v.protocol,!v.host&&!f[v.protocol]){for(var be=(v.pathname||"").split("/");be.length&&!(v.host=be.shift()););v.host||(v.host=""),v.hostname||(v.hostname=""),be[0]!==""&&be.unshift(""),be.length<2&&be.unshift(""),S.pathname=be.join("/")}else S.pathname=v.pathname;if(S.search=v.search,S.query=v.query,S.host=v.host||"",S.auth=v.auth,S.hostname=v.hostname||v.host,S.port=v.port,S.pathname||S.search){var Y=S.pathname||"",K=S.search||"";S.path=Y+K}return S.slashes=S.slashes||v.slashes,S.href=S.format(),S}var re=S.pathname&&S.pathname.charAt(0)==="/",D=v.host||v.pathname&&v.pathname.charAt(0)==="/",Z=D||re||S.host&&v.pathname,P=Z,J=S.pathname&&S.pathname.split("/")||[],be=v.pathname&&v.pathname.split("/")||[],te=S.protocol&&!g[S.protocol];if(te&&(S.hostname="",S.port=null,S.host&&(J[0]===""?J[0]=S.host:J.unshift(S.host)),S.host="",v.protocol&&(v.hostname=null,v.port=null,v.host&&(be[0]===""?be[0]=v.host:be.unshift(v.host)),v.host=null),Z=Z&&(be[0]===""||J[0]==="")),D)S.host=v.host||v.host===""?v.host:S.host,S.hostname=v.hostname||v.hostname===""?v.hostname:S.hostname,S.search=v.search,S.query=v.query,J=be;else if(be.length)J||(J=[]),J.pop(),J=J.concat(be),S.search=v.search,S.query=v.query;else if(v.search!=null){if(te){S.host=J.shift(),S.hostname=S.host;var we=S.host&&S.host.indexOf("@")>0?S.host.split("@"):!1;we&&(S.auth=we.shift(),S.hostname=we.shift(),S.host=S.hostname)}return S.search=v.search,S.query=v.query,(S.pathname!==null||S.search!==null)&&(S.path=(S.pathname?S.pathname:"")+(S.search?S.search:"")),S.href=S.format(),S}if(!J.length)return S.pathname=null,S.search?S.path="/"+S.search:S.path=null,S.href=S.format(),S;for(var V=J.slice(-1)[0],L=(S.host||v.host||J.length>1)&&(V==="."||V==="..")||V==="",ne=0,H=J.length;H>=0;H--)V=J[H],V==="."?J.splice(H,1):V===".."?(J.splice(H,1),ne++):ne&&(J.splice(H,1),ne--);if(!Z&&!P)for(;ne--;ne)J.unshift("..");Z&&J[0]!==""&&(!J[0]||J[0].charAt(0)!=="/")&&J.unshift(""),L&&J.join("/").substr(-1)!=="/"&&J.push("");var G=J[0]===""||J[0]&&J[0].charAt(0)==="/";if(te){S.hostname=G?"":J.length?J.shift():"",S.host=S.hostname;var we=S.host&&S.host.indexOf("@")>0?S.host.split("@"):!1;we&&(S.auth=we.shift(),S.hostname=we.shift(),S.host=S.hostname)}return Z=Z||S.host&&J.length,Z&&!G&&J.unshift(""),J.length>0?S.pathname=J.join("/"):(S.pathname=null,S.path=null),(S.pathname!==null||S.search!==null)&&(S.path=(S.pathname?S.pathname:"")+(S.search?S.search:"")),S.auth=v.auth||S.auth,S.slashes=S.slashes||v.slashes,S.href=S.format(),S},e.prototype.parseHost=function(){var v=this.host,x=r.exec(v);x&&(x=x[0],x!==":"&&(this.port=x.substr(1)),v=v.substr(0,v.length-x.length)),v&&(this.hostname=v)},yt.parse=k,yt.resolve=w,yt.resolveObject=E,yt.format=m,yt.Url=e,yt}function Ea(c){if(typeof c=="string")c=new URL(c);else if(!(c instanceof URL))throw new Deno.errors.InvalidData("invalid argument path , must be a string or URL");if(c.protocol!=="file:")throw new Deno.errors.InvalidData("invalid url scheme");return Rr?th(c):rh(c)}function th(c){let e=c.hostname,t=c.pathname;for(let r=0;r<t.length;r++)if(t[r]==="%"){let a=t.codePointAt(r+2)||32;if(t[r+1]==="2"&&a===102||t[r+1]==="5"&&a===99)throw new Deno.errors.InvalidData("must not include encoded \\ or / characters")}if(t=t.replace(Ba,"\\"),t=decodeURIComponent(t),e!=="")return`\\\\${e}${t}`;{let r=t.codePointAt(1)|32,a=t[2];if(r<Na||r>Ua||a!==":")throw new Deno.errors.InvalidData("file url path must be absolute");return t.slice(1)}}function rh(c){if(c.hostname!=="")throw new Deno.errors.InvalidData("invalid file url hostname");let e=c.pathname;for(let t=0;t<e.length;t++)if(e[t]==="%"){let r=e.codePointAt(t+2)||32;if(e[t+1]==="2"&&r===102)throw new Deno.errors.InvalidData("must not include encoded / characters")}return decodeURIComponent(e)}function xa(c){let e=qi.resolve(c),t=c.charCodeAt(c.length-1);(t===La||Rr&&t===ja)&&e[e.length-1]!==qi.sep&&(e+="/");let r=new URL("file://");return e.includes("%")&&(e=e.replace(Fa,"%25")),!Rr&&e.includes("\\")&&(e=e.replace(Da,"%5C")),e.includes(`
8
- `)&&(e=e.replace($a,"%0A")),e.includes("\r")&&(e=e.replace(Wa,"%0D")),e.includes(" ")&&(e=e.replace(qa,"%09")),r.pathname=e,r}var Aa,xr,zi,Ar,Ir,Ki,Tr,Vi,Cr,Gi,Or,Yi,Pr,Qi,Mr,Ji,yt,Xi,De,Ia,Ta,Ca,Oa,Pa,Ma,Ra,ja,La,Na,Ua,Rr,Ba,Fa,Da,$a,Wa,qa,nh=He(()=>{le(),ue(),ce(),wu(),Nu(),Gu(),_a(),Aa=Object.freeze(Object.create(null)),xr={},zi=!1,Ar=typeof globalThis<"u"?globalThis:typeof self<"u"?self:global,Ir={},Ki=!1,Tr={},Vi=!1,Cr={},Gi=!1,Or={},Yi=!1,Pr={},Qi=!1,Mr={},Ji=!1,yt={},Xi=!1,De=eh(),De.parse,De.resolve,De.resolveObject,De.format,De.Url,Ia=typeof Deno<"u"?Deno.build.os==="windows"?"win32":Deno.build.os:void 0,De.URL=typeof URL<"u"?URL:null,De.pathToFileURL=xa,De.fileURLToPath=Ea,Ta=De.Url,Ca=De.format,Oa=De.resolve,Pa=De.resolveObject,Ma=De.parse,Ra=De.URL,ja=92,La=47,Na=97,Ua=122,Rr=Ia==="win32",Ba=/\//g,Fa=/%/g,Da=/\\/g,$a=/\n/g,Wa=/\r/g,qa=/\t/g}),ih=pe((c,e)=>{le(),ue(),ce(),e.exports=function(){throw new Error("ws does not work in the browser. Browser clients must use the native WebSocket object")}}),Zi=pe(c=>{le(),ue(),ce(),Object.defineProperty(c,"__esModule",{value:!0}),c.BufferedDuplex=void 0,c.writev=r;var e=Et(),t=(Ue(),Pe(Ne));function r(n,i){let s=new Array(n.length);for(let o=0;o<n.length;o++)typeof n[o].chunk=="string"?s[o]=t.Buffer.from(n[o].chunk,"utf8"):s[o]=n[o].chunk;this._write(t.Buffer.concat(s),"binary",i)}var a=class extends e.Duplex{socket;proxy;isSocketOpen;writeQueue;constructor(n,i,s){super({objectMode:!0}),this.proxy=i,this.socket=s,this.writeQueue=[],n.objectMode||(this._writev=r.bind(this)),this.isSocketOpen=!1,this.proxy.on("data",o=>{!this.destroyed&&this.readable&&this.push(o)})}_read(n){this.proxy.read(n)}_write(n,i,s){this.isSocketOpen?this.writeToProxy(n,i,s):this.writeQueue.push({chunk:n,encoding:i,cb:s})}_final(n){this.writeQueue=[],this.proxy.end(n)}_destroy(n,i){this.writeQueue=[],this.proxy.destroy(),i(n)}socketReady(){this.emit("connect"),this.isSocketOpen=!0,this.processWriteQueue()}writeToProxy(n,i,s){this.proxy.write(n,i)===!1?this.proxy.once("drain",s):s()}processWriteQueue(){for(;this.writeQueue.length>0;){let{chunk:n,encoding:i,cb:s}=this.writeQueue.shift();this.writeToProxy(n,i,s)}}};c.BufferedDuplex=a}),jr=pe(c=>{le(),ue(),ce();var e=c&&c.__importDefault||function(k){return k&&k.__esModule?k:{default:k}};Object.defineProperty(c,"__esModule",{value:!0}),c.streamBuilder=c.browserStreamBuilder=void 0;var t=(Ue(),Pe(Ne)),r=e(ih()),a=e(lt()),n=Et(),i=e(lr()),s=Zi(),o=(0,a.default)("mqttjs:ws"),l=["rejectUnauthorized","ca","cert","key","pfx","passphrase"];function u(k,m){let w=`${k.protocol}://${k.hostname}:${k.port}${k.path}`;return typeof k.transformWsUrl=="function"&&(w=k.transformWsUrl(w,k,m)),w}function d(k){let m=k;return k.port||(k.protocol==="wss"?m.port=443:m.port=80),k.path||(m.path="/"),k.wsOptions||(m.wsOptions={}),!i.default&&!k.forceNativeWebSocket&&k.protocol==="wss"&&l.forEach(w=>{Object.prototype.hasOwnProperty.call(k,w)&&!Object.prototype.hasOwnProperty.call(k.wsOptions,w)&&(m.wsOptions[w]=k[w])}),m}function p(k){let m=d(k);if(m.hostname||(m.hostname=m.host),!m.hostname){if(typeof document>"u")throw new Error("Could not determine host. Specify host manually.");let w=new URL(document.URL);m.hostname=w.hostname,m.port||(m.port=Number(w.port))}return m.objectMode===void 0&&(m.objectMode=!(m.binary===!0||m.binary===void 0)),m}function y(k,m,w){o("createWebSocket"),o(`protocol: ${w.protocolId} ${w.protocolVersion}`);let E=w.protocolId==="MQIsdp"&&w.protocolVersion===3?"mqttv3.1":"mqtt";o(`creating new Websocket for url: ${m} and protocol: ${E}`);let v;return w.createWebsocket?v=w.createWebsocket(m,[E],w):v=new r.default(m,[E],w.wsOptions),v}function f(k,m){let w=m.protocolId==="MQIsdp"&&m.protocolVersion===3?"mqttv3.1":"mqtt",E=u(m,k),v;return m.createWebsocket?v=m.createWebsocket(E,[w],m):v=new WebSocket(E,[w]),v.binaryType="arraybuffer",v}var g=(k,m)=>{o("streamBuilder");let w=d(m);w.hostname=w.hostname||w.host||"localhost";let E=u(w,k),v=y(k,E,w),x=r.default.createWebSocketStream(v,w.wsOptions);return x.url=E,v.on("close",()=>{x.destroy()}),x};c.streamBuilder=g;var b=(k,m)=>{o("browserStreamBuilder");let w,E=p(m).browserBufferSize||1024*512,v=m.browserBufferTimeout||1e3,x=!m.objectMode,S=f(k,m),I=O(m,N,ae);m.objectMode||(I._writev=s.writev.bind(I)),I.on("close",()=>{S.close()});let M=typeof S.addEventListener<"u";S.readyState===S.OPEN?(w=I,w.socket=S):(w=new s.BufferedDuplex(m,I,S),M?S.addEventListener("open",B):S.onopen=B),M?(S.addEventListener("close",T),S.addEventListener("error",W),S.addEventListener("message",F)):(S.onclose=T,S.onerror=W,S.onmessage=F);function O(Y,K,re){let D=new n.Transform({objectMode:Y.objectMode});return D._write=K,D._flush=re,D}function B(){o("WebSocket onOpen"),w instanceof s.BufferedDuplex&&w.socketReady()}function T(Y){o("WebSocket onClose",Y),w.end(),w.destroy()}function W(Y){o("WebSocket onError",Y);let K=new Error("WebSocket error");K.event=Y,w.destroy(K)}async function F(Y){if(!I||!I.readable||!I.writable)return;let{data:K}=Y;K instanceof ArrayBuffer?K=t.Buffer.from(K):K instanceof Blob?K=t.Buffer.from(await new Response(K).arrayBuffer()):K=t.Buffer.from(K,"utf8"),I.push(K)}function N(Y,K,re){if(S.bufferedAmount>E){setTimeout(N,v,Y,K,re);return}x&&typeof Y=="string"&&(Y=t.Buffer.from(Y,"utf8"));try{S.send(Y)}catch(D){return re(D)}re()}function ae(Y){S.close(),Y()}return w};c.browserStreamBuilder=b}),eo={};Ct(eo,{Server:()=>Re,Socket:()=>Re,Stream:()=>Re,_createServerHandle:()=>Re,_normalizeArgs:()=>Re,_setSimultaneousAccepts:()=>Re,connect:()=>Re,createConnection:()=>Re,createServer:()=>Re,default:()=>Ha,isIP:()=>Re,isIPv4:()=>Re,isIPv6:()=>Re});function Re(){throw new Error("Node.js net module is not supported by JSPM core outside of Node.js")}var Ha,za=He(()=>{le(),ue(),ce(),Ha={_createServerHandle:Re,_normalizeArgs:Re,_setSimultaneousAccepts:Re,connect:Re,createConnection:Re,createServer:Re,isIP:Re,isIPv4:Re,isIPv6:Re,Server:Re,Socket:Re,Stream:Re}}),Ka=pe((c,e)=>{le(),ue(),ce(),e.exports={}}),Va=pe(c=>{le(),ue(),ce();var e=c&&c.__importDefault||function(s){return s&&s.__esModule?s:{default:s}};Object.defineProperty(c,"__esModule",{value:!0});var t=e((za(),Pe(eo))),r=e(lt()),a=e(Ka()),n=(0,r.default)("mqttjs:tcp"),i=(s,o)=>{if(o.port=o.port||1883,o.hostname=o.hostname||o.host||"localhost",o.socksProxy)return(0,a.default)(o.hostname,o.port,o.socksProxy,{timeout:o.socksTimeout});let{port:l,path:u}=o,d=o.hostname;return n("port %d and host %s",l,d),t.default.createConnection({port:l,host:d,path:u})};c.default=i}),Ga={};Ct(Ga,{default:()=>Ya});var Ya,oh=He(()=>{le(),ue(),ce(),Ya={}}),Qa=pe(c=>{le(),ue(),ce();var e=c&&c.__importDefault||function(l){return l&&l.__esModule?l:{default:l}};Object.defineProperty(c,"__esModule",{value:!0});var t=(oh(),Pe(Ga)),r=e((za(),Pe(eo))),a=e(lt()),n=e(Ka()),i=(0,a.default)("mqttjs:tls");function s(l){let{host:u,port:d,socksProxy:p,...y}=l;if(p!==void 0){let f=(0,n.default)(u,d,p,{timeout:l.socksTimeout});return(0,t.connect)({...y,socket:f})}return(0,t.connect)(l)}var o=(l,u)=>{u.port=u.port||8883,u.host=u.hostname||u.host||"localhost",r.default.isIP(u.host)===0&&(u.servername=u.host),u.rejectUnauthorized=u.rejectUnauthorized!==!1,delete u.path,i("port %d host %s rejectUnauthorized %b",u.port,u.host,u.rejectUnauthorized);let d=s(u);d.on("secureConnect",()=>{u.rejectUnauthorized&&!d.authorized?d.emit("error",new Error("TLS not authorized")):d.removeListener("error",p)});function p(y){u.rejectUnauthorized&&l.emit("error",y),d.end()}return d.on("error",p),d};c.default=o}),Ja=pe(c=>{le(),ue(),ce(),Object.defineProperty(c,"__esModule",{value:!0});var e=(Ue(),Pe(Ne)),t=Et(),r=Zi(),a,n,i;function s(){let p=new t.Transform;return p._write=(y,f,g)=>{a.send({data:y.buffer,success(){g()},fail(b){g(new Error(b))}})},p._flush=y=>{a.close({success(){y()}})},p}function o(p){p.hostname||(p.hostname="localhost"),p.path||(p.path="/"),p.wsOptions||(p.wsOptions={})}function l(p,y){let f=p.protocol==="wxs"?"wss":"ws",g=`${f}://${p.hostname}${p.path}`;return p.port&&p.port!==80&&p.port!==443&&(g=`${f}://${p.hostname}:${p.port}${p.path}`),typeof p.transformWsUrl=="function"&&(g=p.transformWsUrl(g,p,y)),g}function u(){a.onOpen(()=>{i.socketReady()}),a.onMessage(p=>{let{data:y}=p;y instanceof ArrayBuffer?y=e.Buffer.from(y):y=e.Buffer.from(y,"utf8"),n.push(y)}),a.onClose(()=>{i.emit("close"),i.end(),i.destroy()}),a.onError(p=>{let y=new Error(p.errMsg);i.destroy(y)})}var d=(p,y)=>{if(y.hostname=y.hostname||y.host,!y.hostname)throw new Error("Could not determine host. Specify host manually.");let f=y.protocolId==="MQIsdp"&&y.protocolVersion===3?"mqttv3.1":"mqtt";o(y);let g=l(y,p);a=wx.connectSocket({url:g,protocols:[f]}),n=s(),i=new r.BufferedDuplex(y,n,a),i._destroy=(k,m)=>{a.close({success(){m&&m(k)}})};let b=i.destroy;return i.destroy=(k,m)=>(i.destroy=b,setTimeout(()=>{a.close({fail(){i._destroy(k,m)}})},0),i),u(),i};c.default=d}),Xa=pe(c=>{le(),ue(),ce(),Object.defineProperty(c,"__esModule",{value:!0});var e=(Ue(),Pe(Ne)),t=Et(),r=Zi(),a,n,i,s=!1;function o(){let y=new t.Transform;return y._write=(f,g,b)=>{a.sendSocketMessage({data:f.buffer,success(){b()},fail(){b(new Error)}})},y._flush=f=>{a.closeSocket({success(){f()}})},y}function l(y){y.hostname||(y.hostname="localhost"),y.path||(y.path="/"),y.wsOptions||(y.wsOptions={})}function u(y,f){let g=y.protocol==="alis"?"wss":"ws",b=`${g}://${y.hostname}${y.path}`;return y.port&&y.port!==80&&y.port!==443&&(b=`${g}://${y.hostname}:${y.port}${y.path}`),typeof y.transformWsUrl=="function"&&(b=y.transformWsUrl(b,y,f)),b}function d(){s||(s=!0,a.onSocketOpen(()=>{i.socketReady()}),a.onSocketMessage(y=>{if(typeof y.data=="string"){let f=e.Buffer.from(y.data,"base64");n.push(f)}else{let f=new FileReader;f.addEventListener("load",()=>{if(f.result instanceof ArrayBuffer){n.push(e.Buffer.from(f.result));return}n.push(e.Buffer.from(f.result,"utf-8"))}),f.readAsArrayBuffer(y.data)}}),a.onSocketClose(()=>{i.end(),i.destroy()}),a.onSocketError(y=>{i.destroy(y)}))}var p=(y,f)=>{if(f.hostname=f.hostname||f.host,!f.hostname)throw new Error("Could not determine host. Specify host manually.");let g=f.protocolId==="MQIsdp"&&f.protocolVersion===3?"mqttv3.1":"mqtt";l(f);let b=u(f,y);return a=f.my,a.connectSocket({url:b,protocols:g}),n=o(),i=new r.BufferedDuplex(f,n,a),d(),i};c.default=p}),sh=pe(c=>{le(),ue(),ce();var e=c&&c.__importDefault||function(d){return d&&d.__esModule?d:{default:d}};Object.defineProperty(c,"__esModule",{value:!0}),c.connectAsync=u;var t=e(lt()),r=e((nh(),Pe(ka))),a=e(oi()),n=e(lr());typeof Me?.nextTick!="function"&&(Me.nextTick=setImmediate);var i=(0,t.default)("mqttjs"),s=null;function o(d){let p;if(d.auth)if(p=d.auth.match(/^(.+):(.+)$/),p){let[,y,f]=p;d.username=y,d.password=f}else d.username=d.auth}function l(d,p){if(i("connecting to an MQTT broker..."),typeof d=="object"&&!p&&(p=d,d=""),p=p||{},d&&typeof d=="string"){let g=r.default.parse(d,!0),b={};if(g.port!=null&&(b.port=Number(g.port)),b.host=g.hostname,b.query=g.query,b.auth=g.auth,b.protocol=g.protocol,b.path=g.path,p={...b,...p},!p.protocol)throw new Error("Missing protocol");p.protocol=p.protocol.replace(/:$/,"")}if(p.unixSocket=p.unixSocket||p.protocol?.includes("+unix"),p.unixSocket?p.protocol=p.protocol.replace("+unix",""):!p.protocol?.startsWith("ws")&&!p.protocol?.startsWith("wx")&&delete p.path,o(p),p.query&&typeof p.query.clientId=="string"&&(p.clientId=p.query.clientId),n.default||p.unixSocket?p.socksProxy=void 0:p.socksProxy===void 0&&typeof Me<"u"&&(p.socksProxy=Me.env.MQTTJS_SOCKS_PROXY),p.cert&&p.key)if(p.protocol){if(["mqtts","wss","wxs","alis"].indexOf(p.protocol)===-1)switch(p.protocol){case"mqtt":p.protocol="mqtts";break;case"ws":p.protocol="wss";break;case"wx":p.protocol="wxs";break;case"ali":p.protocol="alis";break;default:throw new Error(`Unknown protocol for secure connection: "${p.protocol}"!`)}}else throw new Error("Missing secure protocol key");if(s||(s={},!n.default&&!p.forceNativeWebSocket?(s.ws=jr().streamBuilder,s.wss=jr().streamBuilder,s.mqtt=Va().default,s.tcp=Va().default,s.ssl=Qa().default,s.tls=s.ssl,s.mqtts=Qa().default):(s.ws=jr().browserStreamBuilder,s.wss=jr().browserStreamBuilder,s.wx=Ja().default,s.wxs=Ja().default,s.ali=Xa().default,s.alis=Xa().default)),!s[p.protocol]){let g=["mqtts","wss"].indexOf(p.protocol)!==-1;p.protocol=["mqtt","mqtts","ws","wss","wx","wxs","ali","alis"].filter((b,k)=>g&&k%2===0?!1:typeof s[b]=="function")[0]}if(p.clean===!1&&!p.clientId)throw new Error("Missing clientId for unclean clients");p.protocol&&(p.defaultProtocol=p.protocol);function y(g){return p.servers&&((!g._reconnectCount||g._reconnectCount===p.servers.length)&&(g._reconnectCount=0),p.host=p.servers[g._reconnectCount].host,p.port=p.servers[g._reconnectCount].port,p.protocol=p.servers[g._reconnectCount].protocol?p.servers[g._reconnectCount].protocol:p.defaultProtocol,p.hostname=p.host,g._reconnectCount++),i("calling streambuilder for",p.protocol),s[p.protocol](g,p)}let f=new a.default(y,p);return f.on("error",()=>{}),f}function u(d,p,y=!0){return new Promise((f,g)=>{let b=l(d,p),k={connect:w=>{m(),f(b)},end:()=>{m(),f(b)},error:w=>{m(),b.end(),g(w)}};y===!1&&(k.close=()=>{k.error(new Error("Couldn't connect to server"))});function m(){Object.keys(k).forEach(w=>{b.off(w,k[w])})}Object.keys(k).forEach(w=>{b.on(w,k[w])})})}c.default=l}),Za=pe(c=>{le(),ue(),ce();var e=c&&c.__createBinding||(Object.create?function(y,f,g,b){b===void 0&&(b=g);var k=Object.getOwnPropertyDescriptor(f,g);(!k||("get"in k?!f.__esModule:k.writable||k.configurable))&&(k={enumerable:!0,get:function(){return f[g]}}),Object.defineProperty(y,b,k)}:function(y,f,g,b){b===void 0&&(b=g),y[b]=f[g]}),t=c&&c.__setModuleDefault||(Object.create?function(y,f){Object.defineProperty(y,"default",{enumerable:!0,value:f})}:function(y,f){y.default=f}),r=c&&c.__importStar||(function(){var y=function(f){return y=Object.getOwnPropertyNames||function(g){var b=[];for(var k in g)Object.prototype.hasOwnProperty.call(g,k)&&(b[b.length]=k);return b},y(f)};return function(f){if(f&&f.__esModule)return f;var g={};if(f!=null)for(var b=y(f),k=0;k<b.length;k++)b[k]!=="default"&&e(g,f,b[k]);return t(g,f),g}})(),a=c&&c.__exportStar||function(y,f){for(var g in y)g!=="default"&&!Object.prototype.hasOwnProperty.call(f,g)&&e(f,y,g)},n=c&&c.__importDefault||function(y){return y&&y.__esModule?y:{default:y}};Object.defineProperty(c,"__esModule",{value:!0}),c.ReasonCodes=c.KeepaliveManager=c.UniqueMessageIdProvider=c.DefaultMessageIdProvider=c.Store=c.MqttClient=c.connectAsync=c.connect=c.Client=void 0;var i=n(oi());c.MqttClient=i.default;var s=n(ss());c.DefaultMessageIdProvider=s.default;var o=n(yu());c.UniqueMessageIdProvider=o.default;var l=n(Zo());c.Store=l.default;var u=r(sh());c.connect=u.default,Object.defineProperty(c,"connectAsync",{enumerable:!0,get:function(){return u.connectAsync}});var d=n(ds());c.KeepaliveManager=d.default,c.Client=i.default,a(oi(),c),a(Rt(),c),a(Xo(),c);var p=sr();Object.defineProperty(c,"ReasonCodes",{enumerable:!0,get:function(){return p.ReasonCodes}})}),ah=pe(c=>{le(),ue(),ce();var e=c&&c.__createBinding||(Object.create?function(i,s,o,l){l===void 0&&(l=o);var u=Object.getOwnPropertyDescriptor(s,o);(!u||("get"in u?!s.__esModule:u.writable||u.configurable))&&(u={enumerable:!0,get:function(){return s[o]}}),Object.defineProperty(i,l,u)}:function(i,s,o,l){l===void 0&&(l=o),i[l]=s[o]}),t=c&&c.__setModuleDefault||(Object.create?function(i,s){Object.defineProperty(i,"default",{enumerable:!0,value:s})}:function(i,s){i.default=s}),r=c&&c.__importStar||(function(){var i=function(s){return i=Object.getOwnPropertyNames||function(o){var l=[];for(var u in o)Object.prototype.hasOwnProperty.call(o,u)&&(l[l.length]=u);return l},i(s)};return function(s){if(s&&s.__esModule)return s;var o={};if(s!=null)for(var l=i(s),u=0;u<l.length;u++)l[u]!=="default"&&e(o,s,l[u]);return t(o,s),o}})(),a=c&&c.__exportStar||function(i,s){for(var o in i)o!=="default"&&!Object.prototype.hasOwnProperty.call(s,o)&&e(s,i,o)};Object.defineProperty(c,"__esModule",{value:!0});var n=r(Za());c.default=n,a(Za(),c)});const lh=ah();const ch={inbound:"apps/{appId}/users/{userId}/messages/{conversationId}/clientadded",inboundUpdate:"apps/{appId}/users/{userId}/messages/{conversationId}/{messageId}/update",outbound:"apps/{appId}/outgoing/users/{userId}/messages/{conversationId}/outgoing",presence:"apps/{appId}/users/{userId}/presence/{clientId}",wildcardSubscribe:"apps/{appId}/users/{userId}/#"},uh=300,hh={templateId:"7",type:"link",isDeepLink:!0},fh={channelType:"group",channel:"chat21",requestChannel:"chat21",platform:"WEBSITE",medium:"CHATBUDDY"};class el{client=null;config;currentToken;clientId;appId;topics;messageHandlers=[];stateHandlers=[];statusUpdateHandlers=[];subscribedTopics=new Set;reconnectAttempt=0;maxReconnectAttempts;reconnectMaxDelayMs;disposed=!1;reconnectTimer=null;inboundRegex;inboundUpdateRegex;constructor(e){this.config=e,this.currentToken=e.jwtToken,this.appId=e.appId??"tilechat",this.clientId=e.clientId??`aikaara_${e.userId}_${Date.now()}`,this.topics={...ch,...e.topicTemplates??{}},this.maxReconnectAttempts=e.maxReconnectAttempts??10,this.reconnectMaxDelayMs=e.reconnectMaxDelayMs??3e4,this.inboundRegex=this.buildTopicRegex(this.topics.inbound,["conversationId"]),this.inboundUpdateRegex=this.buildTopicRegex(this.topics.inboundUpdate,["conversationId","messageId"])}async connect(){if(this.disposed)return;const e=this.renderPresenceTopic(),t=this.config.presencePayloadDisconnected??{disconnected:!0},r={clientId:this.clientId,username:this.config.mqttUsername??"JWT",password:this.currentToken,clean:!0,reconnectPeriod:0,connectTimeout:this.config.connectTimeoutMs??1e4,keepalive:this.config.keepAliveSec??60,protocolVersion:this.config.protocolVersion??3,protocolId:this.config.protocolId??"MQIsdp"};return this.config.enablePresence!==!1&&(r.will={topic:e,payload:JSON.stringify(t),qos:0,retain:!1}),new Promise((a,n)=>{this.client=lh.connect(this.config.mqttEndpoint,r),this.client.on("connect",()=>{if(this.reconnectAttempt=0,this.debugLog("CONNECT",{endpoint:this.config.mqttEndpoint,clientId:this.clientId}),this.notifyStateChange(!0),this.config.enablePresence!==!1){const i=this.config.presencePayloadConnected??{connected:!0};this.client.publish(e,JSON.stringify(i),{qos:0,retain:!1}),this.debugLog("PUBLISH",{topic:e,payload:i})}a()}),this.client.on("message",(i,s)=>{this.dispatchInbound(i,s)}),this.client.on("close",()=>{this.debugLog("CLOSE",{}),this.notifyStateChange(!1),this.disposed||this.scheduleReconnect()}),this.client.on("error",i=>{this.debugLog("ERROR",{message:i.message}),this.reconnectAttempt===0&&n(i)}),this.client.on("packetsend",i=>{(i.cmd==="subscribe"||i.cmd==="unsubscribe"||i.cmd==="pingreq")&&this.debugLog(i.cmd.toUpperCase(),{topic:i.topic,packetId:i.messageId})})})}debugLog(e,t){if(!this.config.debug)return;const r={};for(const[a,n]of Object.entries(t))typeof n=="string"&&n.length>200?r[a]=`${n.slice(0,200)}…(${n.length})`:r[a]=n;console.info(`[tiledesk-mqtt] ${e}`,r)}subscribeWildcard(){if(!this.client)return;const e=this.renderTemplate(this.topics.wildcardSubscribe,{});this.subscribedTopics.has(e)||(this.client.subscribe(e,{qos:this.config.subscribeQos??2}),this.subscribedTopics.add(e))}subscribeToConversation(e){if(!this.client)return;if(this.config.wildcardSubscribe){this.subscribeWildcard();return}const t=this.renderInboundTopic(e);this.subscribedTopics.has(t)||(this.client.subscribe(t,{qos:this.config.subscribeQos??2}),this.subscribedTopics.add(t))}unsubscribeFromConversation(e){if(!this.client)return;const t=this.renderInboundTopic(e);this.subscribedTopics.has(t)&&(this.client.unsubscribe(t),this.subscribedTopics.delete(t))}publishMessage(e,t,r={}){if(!this.client)return;const a=this.buildOutgoingEnvelope(e,{text:t,type:"text",...r});this.publishEnvelope(e,a)}publishFileMessage(e,t){if(!this.client)return;const r={...hh,...this.config.fileTemplate??{},...dh(t)},a={metadata:{contentType:"300",templateId:r.templateId,payload:{...r.headerImgSrc?{headerImgSrc:r.headerImgSrc}:{},elements:[{description:t.description??t.fileName,action:{url:t.fileUrl,type:r.type??"link",isDeepLink:r.isDeepLink??!0}}]},...t.metadata??{}}},n={fileMessage:!0,...t.cloudFileId?{cloudFileId:t.cloudFileId}:{},...t.attributes??{}},i=this.buildOutgoingEnvelope(e,{text:JSON.stringify(a),type:"html",attributes:n,metadata:a.metadata});this.publishEnvelope(e,i)}publishRaw(e,t){this.client&&this.publishEnvelope(e,t)}publishReadReceipt(e,t,r=uh){if(!this.client)return;const a=this.renderTemplate(this.topics.inboundUpdate,{conversationId:e,messageId:t});this.client.publish(a,JSON.stringify({status:r}),{qos:this.config.publishQos??0,retain:!1})}publishChatInitiated(e,t={}){if(!this.client)return;const r=this.buildOutgoingEnvelope(e,{text:"CHAT_INITIATED",type:"text",attributes:{subtype:"info",...t}});this.publishEnvelope(e,r)}onMessage(e){return this.messageHandlers.push(e),()=>{this.messageHandlers=this.messageHandlers.filter(t=>t!==e)}}onStateChange(e){return this.stateHandlers.push(e),()=>{this.stateHandlers=this.stateHandlers.filter(t=>t!==e)}}onStatusUpdate(e){return this.statusUpdateHandlers.push(e),()=>{this.statusUpdateHandlers=this.statusUpdateHandlers.filter(t=>t!==e)}}disconnect(){this.disposed=!0,this.reconnectTimer&&(clearTimeout(this.reconnectTimer),this.reconnectTimer=null),this.client&&(this.subscribedTopics.forEach(e=>this.client.unsubscribe(e)),this.subscribedTopics.clear(),this.client.end(!0),this.client=null),this.messageHandlers=[],this.stateHandlers=[],this.statusUpdateHandlers=[]}get isConnected(){return this.client?.connected??!1}async scheduleReconnect(){if(this.reconnectAttempt>=this.maxReconnectAttempts||this.disposed)return;const e=Math.min(1e3*Math.pow(2,this.reconnectAttempt),this.reconnectMaxDelayMs);this.reconnectAttempt++,this.reconnectTimer=setTimeout(async()=>{if(!this.disposed){if(this.config.tokenProvider)try{this.currentToken=await this.config.tokenProvider()}catch{}try{await this.connect();const t=[...this.subscribedTopics];this.subscribedTopics.clear(),t.forEach(r=>{this.client&&(this.client.subscribe(r,{qos:this.config.subscribeQos??2}),this.subscribedTopics.add(r))})}catch{}}},e)}notifyStateChange(e){this.stateHandlers.forEach(t=>t(e))}dispatchInbound(e,t){const r=t.toString();let a=null;try{a=JSON.parse(r)}catch{this.debugLog("RECV (non-json)",{topic:e,raw:r});return}if(!a)return;this.debugLog("RECV",{topic:e,sender:a.sender,type:a.type,contentType:a.metadata?.contentType,templateId:a.metadata?.templateId,messageId:a.message_id,text:typeof a.text=="string"?a.text:void 0});const n=e.match(this.inboundUpdateRegex);if(n){const l=n.groups?.conversationId??"",u=n.groups?.messageId??"",d=typeof a.status=="number"?a.status:Number(a.status??0),p={conversationId:l,messageId:u,status:d,raw:a};this.statusUpdateHandlers.forEach(y=>y(p)),this.messageHandlers.forEach(y=>y(a,{topic:e,conversationId:l,messageId:u,kind:"update"}));return}const i=e.match(this.inboundRegex),s=i?.groups?.conversationId,o={topic:e,conversationId:s,messageId:typeof a.message_id=="string"?a.message_id:void 0,kind:i?"clientadded":"unknown"};this.messageHandlers.forEach(l=>l(a,o))}buildOutgoingEnvelope(e,t){const r={...fh,...this.config.messageDefaults??{}},a=this.config.senderFullname??this.config.userName??this.config.userId,n=this.config.recipientFullnameResolver?.(e),i={projectId:this.config.projectId,...r.departmentId?{departmentId:r.departmentId}:{},...this.config.userName?{userFullname:this.config.userName}:{},...r.channel?{channel:r.channel}:{},...r.requestChannel?{request_channel:r.requestChannel}:{},...r.attributes??{},...t.attributes??{}};return{type:"text",sender:this.config.userId,sender_fullname:a,senderFullname:a,recipient:e,...n?{recipient_fullname:n}:{},...r.channelType?{channel_type:r.channelType}:{},...r.medium?{medium:r.medium}:{},...r.platform?{platform:r.platform}:{},app_id:this.appId,timestamp:Date.now(),...t,attributes:i}}publishEnvelope(e,t){if(!this.client)return;const r=this.renderOutboundTopic(e);this.client.publish(r,JSON.stringify(t),{qos:this.config.publishQos??0,retain:this.config.publishRetain??!1}),this.debugLog("SEND",{topic:r,type:t.type,sender:t.sender,text:typeof t.text=="string"?t.text:void 0,contentType:t.metadata?.contentType,templateId:t.metadata?.templateId})}renderInboundTopic(e){return this.renderTemplate(this.topics.inbound,{conversationId:e})}renderOutboundTopic(e){return this.renderTemplate(this.topics.outbound,{conversationId:e})}renderPresenceTopic(){return this.renderTemplate(this.topics.presence,{})}renderTemplate(e,t){const r={appId:this.appId,userId:this.config.userId,projectId:this.config.projectId,clientId:this.clientId,...t};return e.replace(/\{(\w+)\}/g,(a,n)=>r[n]??"")}buildTopicRegex(e,t){const r=e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&").replace(/\\\{(\w+)\\\}/g,(a,n)=>{const i={appId:this.appId,userId:this.config.userId,projectId:this.config.projectId,clientId:this.clientId};if(t.includes(n))return`(?<${n}>[^/]+)`;const s=i[n];return s?s.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"):"[^/]+"});return new RegExp(`^${r}$`)}}function dh(c){const e={};for(const[t,r]of Object.entries(c))r!==void 0&&(e[t]=r);return e}function tl(c,e){return(c.sender??"").toString()===e}function rl(c,e){const t=(c.sender??"").toString(),r=e.systemSenders??["metadata","system"],a=e.botSenderPrefix??"bot_";return t?t===e.userId?"user":t.startsWith(a)?"assistant":r.includes(t)?"system":"agent":"system"}function to(c){const e={raw:c},t=c.metadata;if(t&&typeof t=="object"&&(typeof t.contentType=="string"&&(e.contentType=t.contentType),typeof t.templateId=="string"&&(e.templateId=t.templateId),t.payload!==void 0&&(e.payload=t.payload)),typeof c.text=="string"&&c.text.trim().startsWith("{"))try{const r=JSON.parse(c.text);typeof r.message=="string"&&(e.innerMessage=r.message);const a=r.metadata;a&&typeof a=="object"&&(!e.contentType&&typeof a.contentType=="string"&&(e.contentType=a.contentType),!e.templateId&&typeof a.templateId=="string"&&(e.templateId=a.templateId),e.payload===void 0&&a.payload!==void 0&&(e.payload=a.payload))}catch{}return e}function nl(c){const e=to(c);if(e.contentType!=="300")return null;const t=e.payload,r=t&&Array.isArray(t.elements)?t.elements:null;if(!r||r.length===0)return null;const a=r[0],n=a.action,i=n&&typeof n.url=="string"?n.url:void 0,s=typeof a.description=="string"?a.description:void 0,o=c.attributes,l=o&&typeof o.cloudFileId=="string"?o.cloudFileId:void 0;return!i&&!s?null:{fileName:s,fileUrl:i,cloudFileId:l,templateId:e.templateId}}function il(c,e,t){const r=rl(c,t),a=to(c),n=nl(c);let i="";a.innerMessage?i=a.innerMessage:typeof c.text=="string"&&(c.text.trim().startsWith("{")?a.contentType!=="300"&&(i=c.text):i=c.text);const s=typeof c.message_id=="string"?c.message_id:`td_${Date.now()}_${Math.random().toString(36).slice(2,8)}`,o=typeof c.timestamp=="number"?new Date(c.timestamp).toISOString():new Date().toISOString(),l=r==="assistant"?"assistant":r==="agent"?"agent":r==="system"?"system":"user",u=typeof c.status=="number"?ph(c.status):"delivered",d={id:s,externalId:s,conversationId:e,role:l,content:i,createdAt:o,status:u,metadata:{sender:c.sender,sender_fullname:c.sender_fullname??c.senderFullname,app_id:c.app_id,attributes:c.attributes}};return a.contentType&&(d.template={contentType:a.contentType,templateId:a.templateId,payload:a.payload}),n?.fileUrl&&(d.attachments=[{fileName:n.fileName??"file",fileUrl:n.fileUrl,cloudFileId:n.cloudFileId}]),{message:d,template:a}}function ph(c){return c<0?"error":c>=250?"read":c>=150?"delivered":"sent"}class ol extends Zt{connection=null;tiledesk=null;api;messageStore;conversationManager;subscription=null;config;mode;uploadAdapter;historyAdapter;tiledeskUnsubs=[];constructor(e,t){super(),this.config=e,this.mode=e.transport??"aikaara",this.uploadAdapter=t?.uploadAdapter??null,this.historyAdapter=t?.historyAdapter??null,this.api=new yo(e.baseUrl,e.userToken,e.apiKey,e.authToken),this.messageStore=new vo,this.conversationManager=new So(e.conversationId),this.usesAikaara()&&(this.connection=new bo(e),this.connection.on("connection:state",r=>{this.emit("connection:state",r),this.config.onConnectionStateChange?.(r)}),this.connection.on("error",r=>{this.emit("error",r),this.config.onError?.(r)})),this.usesTiledesk()&&this.initTiledeskTransport()}usesAikaara(){return this.mode==="aikaara"||this.mode==="dual"}usesTiledesk(){return this.mode==="tiledesk"||this.mode==="dual"}initTiledeskTransport(){const e=this.config.tiledesk,t=this.config.tiledeskIdentity;if(!e)throw new Error("AikaaraChatClient: tiledesk transport requires `config.tiledesk` (TiledeskTransportConfig)");if(!t?.userId)throw new Error("AikaaraChatClient: tiledesk transport requires `config.tiledeskIdentity.userId`");this.tiledesk=new el({...e,userId:t.userId,userName:t.userName??e.userName,senderFullname:t.senderFullname??e.senderFullname,messageDefaults:{...e.messageDefaults,departmentId:t.departmentId??e.messageDefaults?.departmentId}}),this.tiledeskUnsubs.push(this.tiledesk.onStateChange(r=>{const a=r?"connected":"disconnected";this.emit("connection:state",a),this.config.onConnectionStateChange?.(a)})),this.tiledeskUnsubs.push(this.tiledesk.onMessage((r,a)=>this.handleTiledeskMessage(r,a))),this.tiledeskUnsubs.push(this.tiledesk.onStatusUpdate(r=>this.handleTiledeskStatusUpdate(r)))}async connect(){if(this.usesAikaara()&&this.connection){if(await this.connection.connect(),!this.conversationManager.conversationId){const e=await this.api.createConversation({systemPromptId:this.config.systemPromptId,channel:this.config.channel||"widget",extUid:this.config.extUid});this.conversationManager.conversationId=String(e.id)}this.subscription=await this.connection.subscribeToConversation(this.conversationManager.conversationId),this.subscription.onReceived(e=>{this.handleBroadcast(e)}),await this.loadHistory()}if(this.usesTiledesk()&&this.tiledesk){await this.tiledesk.connect(),this.config.tiledesk?.wildcardSubscribe??!0?this.tiledesk.subscribeWildcard():this.conversationManager.conversationId&&this.tiledesk.subscribeToConversation(this.conversationManager.conversationId);const t=this.conversationManager.conversationId;if(t){const r=await this.hydrateTiledeskHistory(t),a=this.config.tiledesk?.autoInitiateOnEmpty??!0;r==="empty"&&a&&this.tiledesk.publishChatInitiated(t,this.config.tiledesk?.chatInitiatedAttributes??{})}}}async hydrateTiledeskHistory(e){if(!this.historyAdapter)return"unknown";const t=this.config.tiledeskIdentity?.userId??"";let r;try{r=await this.historyAdapter.fetchMessages(e,{userId:t,appId:this.config.tiledesk?.appId,projectId:this.config.tiledesk?.projectId})}catch(s){return this.config.onError?.(s instanceof Error?s:new Error(String(s))),"unknown"}if(!r.length)return"empty";const a=r.map(s=>il(s,e,{userId:t}).message).sort((s,o)=>new Date(s.createdAt).getTime()-new Date(o.createdAt).getTime()),n=this.messageStore.messages,i=[...a,...n.filter(s=>!a.some(o=>o.externalId&&o.externalId===s.externalId))];if(this.messageStore.setMessages(i),this.config.onMessage)for(const s of a)try{this.config.onMessage(s)}catch(o){console.warn("[aikaara-chat-sdk] onMessage threw on history replay",o)}return"has-history"}async sendMessage(e,t={}){const r=this.conversationManager.conversationId;if(!r)throw new Error("No active conversation");const a=this.messageStore.addOptimistic("user",e,r);this.emit("message:sent",a),this.config.onMessage?.(a);const n={};if(t.attributes&&(n.attributes=t.attributes),t.metadata&&(n.metadata=t.metadata),this.mode==="tiledesk"&&this.tiledesk){this.tiledesk.publishMessage(r,e,n);return}this.mode==="dual"&&this.tiledesk&&this.tiledesk.publishMessage(r,e,n),this.usesAikaara()&&this.connection&&this.connection.sendMessage(r,e)}async sendFile(e,t){if(!this.uploadAdapter)throw new Error("AikaaraChatClient: sendFile requires an UploadAdapter");const r=this.conversationManager.conversationId;if(!r)throw new Error("No active conversation");const a=await this.uploadAdapter.upload(e,{conversationId:r,userId:this.config.tiledeskIdentity?.userId??this.config.userToken,projectId:this.config.tiledesk?.projectId,appId:this.config.tiledesk?.appId});if(this.usesTiledesk()&&this.tiledesk){const n={fileName:a.fileName,fileUrl:a.url,cloudFileId:a.cloudFileId};this.tiledesk.publishFileMessage(r,n)}t?.caption&&await this.sendMessage(t.caption)}initiateTiledeskChat(e={}){const t=this.conversationManager.conversationId;!this.tiledesk||!t||this.tiledesk.publishChatInitiated(t,e)}markTiledeskRead(e){const t=this.conversationManager.conversationId;!this.tiledesk||!t||this.tiledesk.publishReadReceipt(t,e)}setUploadAdapter(e){this.uploadAdapter=e}async sendUserEvent(e,t,r){const a=this.conversationManager.conversationId;if(!a)throw new Error("No active conversation");this.connection&&this.connection.sendUserEvent(a,e,t,r)}async loadHistory(){const e=this.conversationManager.conversationId;if(!e)return[];try{const t=await this.api.getMessages(e);return this.messageStore.setMessages(t),t}catch{return[]}}get messages(){return this.messageStore.messages}get conversationId(){return this.conversationManager.conversationId}get isConnected(){if(this.mode==="tiledesk")return this.tiledesk?.isConnected??!1;if(this.mode==="dual"){const e=this.connection?.connectionState==="connected",t=this.tiledesk?.isConnected??!1;return e&&t}return this.connection?.connectionState==="connected"}async setContext(e){const t=this.conversationManager.conversationId;t&&await this.api.updateContext(t,{current_page:e.currentPage,entity_type:e.entityType,entity_id:e.entityId,project_id:e.projectId,available_routes:e.availableRoutes,custom_context:e.custom})}async disconnect(){this.subscription&&(this.subscription=null),this.connection&&await this.connection.disconnect(),this.tiledesk&&(this.tiledeskUnsubs.forEach(e=>e()),this.tiledeskUnsubs=[],this.tiledesk.disconnect(),this.tiledesk=null)}handleTiledeskMessage(e,t){if(t.kind==="update")return;const r=t.conversationId??this.conversationManager.conversationId;if(!r)return;const a=this.config.tiledeskIdentity?.userId??"",{message:n,template:i}=il(e,r,{userId:a,systemSenders:this.config.tiledesk?.messageDefaults?.attributes?.systemSenders});if(this.mode==="dual"&&n.role==="assistant")return;if(tl(e,a)){const l=this.messageStore.reconcileOptimistic(n);if(l){this.emit("message:updated",l);return}}const{message:s,deduped:o}=this.messageStore.upsertRemoteMessage(n);if(o?this.emit("message:updated",s):(this.emit("message:received",s),this.config.onMessage?.(s)),i.contentType){const l={messageId:s.id,conversationId:r,role:n.role==="tool"?"system":n.role,contentType:i.contentType,templateId:i.templateId,payload:i.payload,innerMessage:i.innerMessage,raw:e};this.config.onTemplateMessage?.(l)}}handleTiledeskStatusUpdate(e){e.status>=250?this.messageStore.updateMessageStatus(e.messageId,"read"):e.status>=150&&this.messageStore.updateMessageStatus(e.messageId,"delivered")}parseActionResult(e){try{const t=typeof e=="string"?JSON.parse(e):e;if(!t||typeof t!="object")return;t.navigate_to?this.emit("action:navigate",t):t.action==="edit_entity"?this.emit("action:edit_entity",t):t.action==="save_entity"?this.emit("action:save_entity",t):t.action==="test_tool"&&this.emit("action:test_tool",t)}catch{}}handleBroadcast(e){const t=this.conversationManager.conversationId;switch(e.type){case"status":{const r=e.status;this.emit("status",r),this.config.onStatusChange?.(r),r==="processing"&&this.emit("typing:start",void 0);break}case"error":{const r=new Error(e.message||"Unknown error");this.emit("error",r),this.config.onError?.(r);break}case"message_start":{if(e.role==="assistant"){const r=this.messageStore.addStreamingMessage(t);this.emit("stream:start",{messageId:r.id}),this.emit("typing:start",void 0)}break}case"message_update":{const r=e.delta||"",a=e.content||"";a?this.messageStore.updateStreaming(a):r&&this.messageStore.appendToStreaming(r);const n=this.messageStore.streamingContent;this.emit("stream:update",{delta:r,content:n}),this.config.onStreamUpdate?.(r,n);break}case"message_end":{const r=e.usage,a=this.messageStore.finalizeStreaming(r?{tokensInput:r.tokens_input||0,tokensOutput:r.tokens_output||0}:void 0);this.emit("typing:stop",void 0),a&&(this.emit("stream:end",{messageId:a.id,usage:r?{tokensInput:r.tokens_input||0,tokensOutput:r.tokens_output||0}:void 0}),this.emit("message:received",a),this.config.onMessage?.(a));break}case"message_queued":{const r=this.messageStore.messages.findLast(a=>a.status==="sending");r&&this.messageStore.confirmOptimistic(r.id);break}case"tool_execution_start":{this.emit("tool:start",{toolName:e.tool_name||"",args:e.args||{}}),this.emit("status",e.type);break}case"tool_execution_end":{this.emit("tool:end",{toolName:e.tool_name||"",result:e.result,isError:!!e.is_error}),this.emit("status",e.type),this.parseActionResult(e.result);break}case"tool_execution_update":case"agent_start":case"agent_end":case"turn_start":case"turn_end":case"auto_retry_start":case"auto_retry_end":case"cancelled":this.emit("status",e.type);break}}}class gh extends Zt{registration=null;pendingEdits=[];constructor(e){super(),this.setupListeners(e)}registerForm(e){this.registration=e;const t=this.pendingEdits.filter(r=>r.entity_type===e.entityType&&String(r.entity_id)===String(e.entityId));if(t.length>0){for(const r of t)e.onFieldUpdate(r.fields),this.emit("edit:applied",{entityType:r.entity_type,entityId:r.entity_id,fields:r.fields});this.pendingEdits=this.pendingEdits.filter(r=>!(r.entity_type===e.entityType&&String(r.entity_id)===String(e.entityId)))}}unregisterForm(e,t){this.registration?.entityType===e&&String(this.registration?.entityId)===String(t)&&(this.registration=null)}get currentForm(){return this.registration}pushFieldUpdates(e,t,r){this.registration&&this.registration.entityType===e&&String(this.registration.entityId)===String(t)?(this.registration.onFieldUpdate(r),this.emit("edit:applied",{entityType:e,entityId:t,fields:r})):(this.pendingEdits.push({action:"edit_entity",entity_type:e,entity_id:t,fields:r}),this.emit("edit:pending",{entityType:e,entityId:t,fields:r}))}async requestSave(){if(!this.registration)return{success:!1,error:"No form registered"};try{return await this.registration.onSave(),this.emit("save:success",{entityType:this.registration.entityType,entityId:this.registration.entityId}),{success:!0}}catch(e){const t=e instanceof Error?e.message:"Save failed";return this.emit("save:error",{entityType:this.registration.entityType,entityId:this.registration.entityId,error:t}),{success:!1,error:t}}}async requestTest(e){if(!this.registration?.onTest)return{success:!1,error:"Current form does not support testing"};try{return await this.registration.onTest(e),{success:!0}}catch(t){return{success:!1,error:t instanceof Error?t.message:"Test failed"}}}setupListeners(e){e.on("action:edit_entity",t=>{this.pushFieldUpdates(t.entity_type,t.entity_id,t.fields)}),e.on("action:save_entity",t=>{this.requestSave()}),e.on("action:test_tool",t=>{this.emit("test:triggered",{toolId:t.tool_id,parameters:t.parameters}),this.requestTest(t.parameters)})}}const sl={txt:"text/plain",pdf:"application/pdf",jpg:"image/jpeg",jpeg:"image/jpeg",png:"image/png",csv:"text/csv",doc:"application/msword",json:"application/json"};function mh(c){const e=c.lastIndexOf(".");return e<0||e===c.length-1?"":c.slice(e+1).toLowerCase()}function bh(c,e,t){const r=mh(c.name||"");if(r&&e&&e[r])return e[r];const a=c.type;return a&&a.trim().length>0?a:r&&sl[r]?sl[r]:t}function ro(c,e){return c.replace(/\{(\w+)\}/g,(t,r)=>e[r]??"")}function yh(c,e){const t=e.split(".");let r=c;for(const a of t)if(r&&typeof r=="object"&&a in r)r=r[a];else return"";return typeof r=="string"?r:""}function al(c){const e=c.signedUrlPath??"data.s3SignedUrl";return{async upload(t,r){const a=t.name||`upload-${Date.now()}`,n={fileName:a,userId:r.userId,requestId:r.conversationId,conversationId:r.conversationId},i=c.authHeader?await c.authHeader():void 0,s={accept:"application/json",...c.extraHeaders??{},...i?{authorization:i}:{}},o=ro(c.signEndpoint.includes("{")?c.signEndpoint:`${c.signEndpoint}?fileName={fileName}`,n),l=await fetch(o,{method:c.signMethod??"GET",headers:s});if(!l.ok)throw new Error(`Sign request failed: ${l.status}`);const u=await l.json().catch(()=>({})),d=yh(u,e);if(!d)throw new Error(`Sign response missing path "${e}"`);const p=bh(t,c.contentTypeMap,c.contentTypeFallback??"application/octet-stream"),y=c.s3HostRewrite?d.replace(/^https:\/\/[^/]+/i,c.s3HostRewrite):d,f=await fetch(y,{method:"PUT",headers:{"content-type":p},body:t});if(!f.ok){const b=await f.text().catch(()=>"");throw new Error(`S3 PUT failed: ${f.status} ${b.slice(0,200)}`)}if(c.registerEndpoint){const b=JSON.parse(ro(JSON.stringify(c.registerBody??{}),n)),k=await fetch(c.registerEndpoint,{method:"POST",headers:{...s,"content-type":"application/json"},body:JSON.stringify(b)});if(!k.ok){const m=await k.text().catch(()=>"");throw new Error(`Register failed: ${k.status} ${m.slice(0,200)}`)}}return{url:c.viewerTemplate?ro(c.viewerTemplate,n):d.split("?")[0],fileName:a,contentType:p,byteSize:t.size,meta:{requestId:r.conversationId}}}}}function no(c){return{async upload(e,t){const r=new FormData,a=c.fieldName??"file";r.append(a,e,e.name);const n=typeof c.extraFields=="function"?c.extraFields(t):c.extraFields;if(n)for(const[p,y]of Object.entries(n))r.append(p,y);r.append("conversationId",t.conversationId),r.append("userId",t.userId),t.projectId&&r.append("projectId",t.projectId);const i=typeof c.headers=="function"?await c.headers():c.headers??{},s=await fetch(c.endpoint,{method:c.method??"POST",body:r,headers:i,credentials:c.credentials});if(!s.ok)throw new Error(`Upload failed: ${s.status} ${s.statusText}`);const o=await s.json().catch(()=>({}));if(c.parseResponse)return c.parseResponse(o,t);const l=o,u=l.url??l.fileUrl??l.publicUrl,d=l.fileName??l.name??e.name;if(!u)throw new Error('Upload response missing "url" / "fileUrl" / "publicUrl"');return{url:u,fileName:d,cloudFileId:typeof l.cloudFileId=="string"?l.cloudFileId:void 0,relativePath:typeof l.path=="string"?l.path:void 0,contentType:typeof l.contentType=="string"?l.contentType:void 0,byteSize:typeof l.byteSize=="number"?l.byteSize:void 0,meta:l}}}}const vh="/tilechat/{userId}/conversations/{conversationId}/messages?pageSize={pageSize}";function ll(c){const e=c.apiBase.replace(/\/$/,""),t=c.pageSize??200,r=c.pathTemplate??vh;return{async fetchMessages(a,n){const i=r.replace("{userId}",encodeURIComponent(n.userId)).replace("{conversationId}",encodeURIComponent(a)).replace("{appId}",encodeURIComponent(n.appId??"tilechat")).replace("{projectId}",encodeURIComponent(n.projectId??"")).replace("{pageSize}",String(t)),s=i.startsWith("http")?i:`${e}${i.startsWith("/")?i:`/${i}`}`,o={accept:"application/json","content-type":"application/json",...c.extraHeaders??{}};if(c.getToken){const p=await c.getToken();p&&(o.authorization=p)}const l=await fetch(s,{method:"GET",headers:o}),u=await l.json().catch(()=>null);if(c.parseResponse&&u)return c.parseResponse(u);const d=u;if(d&&Array.isArray(d.result))return d.result;if(!l.ok)throw new Error(`History fetch failed: ${l.status} ${l.statusText}`);return[]}}}class wh{client;panel;bubble;header;messageList;input;errorBanner;isOpen=!1;isEmbed=!1;constructor(e,t,r){this.client=new ol(e,{uploadAdapter:r?.uploadAdapter,historyAdapter:r?.historyAdapter}),this.isEmbed=e.display==="embed",this.bubble=t.querySelector("aikaara-chat-bubble"),this.panel=t.querySelector(".aikaara-panel"),this.header=t.querySelector("aikaara-chat-header"),this.messageList=t.querySelector("aikaara-message-list"),this.input=t.querySelector("aikaara-chat-input"),this.errorBanner=t.querySelector("aikaara-error-banner"),e.welcomeMessage&&this.messageList.setWelcomeMessage(e.welcomeMessage),e.showTimestamps!==void 0&&this.messageList.setShowTimestamps(e.showTimestamps),(e.linkHandlers||e.getLinkBearer)&&this.messageList.setLinkConfig(e.linkHandlers??[],e.getLinkBearer),this.wireEvents()}async connect(){try{await this.client.connect(),this.messageList.renderMessages(this.client.messages)}catch{this.errorBanner.show("Failed to connect. Retrying...",5e3)}}async disconnect(){await this.client.disconnect()}wireEvents(){this.bubble?.addEventListener("toggle",()=>{this.togglePanel()}),this.isEmbed||this.header.addEventListener("header-close",()=>{this.togglePanel(!1)}),this.input.addEventListener("send",(e=>{this.handleSend(e.detail.content)})),this.input.addEventListener("file-pick",(e=>{this.handleFile(e.detail.file)})),this.client.on("message:sent",e=>{this.messageList.addMessage(e)}),this.client.on("stream:start",()=>{this.messageList.removeTypingIndicator();const e=this.client.messages[this.client.messages.length-1];e&&this.messageList.addMessage(e)}),this.client.on("stream:update",({content:e})=>{this.messageList.updateStreamingContent(e)}),this.client.on("stream:end",()=>{this.messageList.finalizeStreaming()}),this.client.on("typing:start",()=>{const e=this.client.messages,t=e[e.length-1];(!t||t.status!=="streaming")&&this.messageList.showTypingIndicator()}),this.client.on("typing:stop",()=>{this.messageList.removeTypingIndicator()}),this.client.on("connection:state",e=>{this.header.setStatus(e),e==="connected"?(this.errorBanner.hide(),this.input.disabled=!1):e==="reconnecting"?(this.errorBanner.show("Connection lost. Reconnecting..."),this.input.disabled=!0):e==="disconnected"&&(this.input.disabled=!0)}),this.client.on("error",e=>{this.errorBanner.show(e.message,5e3)}),this.client.on("message:received",e=>{this.messageList.upsertMessage(e)}),this.client.on("message:updated",e=>{this.messageList.upsertMessage(e)}),this.messageList.addEventListener("message-action",e=>{const t=e.detail;if(!t?.text)return;const r=this.client.config.templateActionAttributes??{},a=t.attributes?.action??{},n={...t.attributes,action:{...r,...a}};this.handleSend(t.text,n)})}async handleSend(e,t){try{await this.client.sendMessage(e,t?{attributes:t}:void 0)}catch{this.errorBanner.show("Failed to send message",3e3)}}async handleFile(e){this.input.uploading=!0;try{await this.client.sendFile(e)}catch(t){this.errorBanner.show(t instanceof Error?`Upload failed: ${t.message}`:"Upload failed",4e3)}finally{this.input.uploading=!1}}sendUserEvent(e,t,r){this.client.sendUserEvent(e,t,r)}getClient(){return this.client}togglePanel(e){this.isEmbed||(this.isOpen=e!==void 0?e:!this.isOpen,this.isOpen?(this.panel.removeAttribute("hidden"),requestAnimationFrame(()=>{this.panel.classList.remove("entering"),this.panel.classList.add("visible"),this.input.focus()})):(this.panel.classList.remove("visible"),this.panel.classList.add("entering"),setTimeout(()=>{this.panel.setAttribute("hidden","")},200)))}}class cl extends HTMLElement{shadow;controller=null;_config={};static get observedAttributes(){return["base-url","ws-url","user-token","api-key","title","subtitle","theme","primary-color","position","width","height","placeholder","welcome-message","avatar-url","display"]}constructor(){super(),this.shadow=this.attachShadow({mode:"open"})}connectedCallback(){this.render(),this.initController()}disconnectedCallback(){this.controller?.disconnect()}attributeChangedCallback(e,t,r){t!==r&&this.controller&&(this.render(),this.initController())}configure(e){this._config={...this._config,...e}}getConfig(){return{baseUrl:this.getAttribute("base-url")||this._config.baseUrl||"",wsUrl:this.getAttribute("ws-url")||this._config.wsUrl,userToken:this.getAttribute("user-token")||this._config.userToken||"",apiKey:this.getAttribute("api-key")||this._config.apiKey,title:this.getAttribute("title")||this._config.title||"Chat",subtitle:this.getAttribute("subtitle")||this._config.subtitle,theme:this.getAttribute("theme")||this._config.theme||Xl,primaryColor:this.getAttribute("primary-color")||this._config.primaryColor||go,position:this.getAttribute("position")||this._config.position||Jl,width:Number(this.getAttribute("width"))||this._config.width||Vl,height:Number(this.getAttribute("height"))||this._config.height||Gl,fontFamily:this._config.fontFamily||Ql,borderRadius:this._config.borderRadius??Yl,placeholder:this.getAttribute("placeholder")||this._config.placeholder||mo,welcomeMessage:this.getAttribute("welcome-message")||this._config.welcomeMessage,avatarUrl:this.getAttribute("avatar-url")||this._config.avatarUrl,showTimestamps:this._config.showTimestamps??!0,persistConversation:this._config.persistConversation??!0,showHeader:this._config.showHeader??!0,hideSystemMessages:this._config.hideSystemMessages,timestampFormat:this._config.timestampFormat,input:this._config.input,templateLayout:this._config.templateLayout,showBubble:this._config.showBubble??!0,display:(this.getAttribute("display")||this._config.display)??"popup",offset:this._config.offset||Zl,conversationId:this._config.conversationId,systemPromptId:this._config.systemPromptId,channel:this._config.channel,extUid:this._config.extUid,transport:this._config.transport,tiledesk:this._config.tiledesk,tiledeskIdentity:this._config.tiledeskIdentity,onMessage:this._config.onMessage,onStatusChange:this._config.onStatusChange,onError:this._config.onError,onStreamUpdate:this._config.onStreamUpdate,onConnectionStateChange:this._config.onConnectionStateChange,onTemplateMessage:this._config.onTemplateMessage,themeTokens:this._config.themeTokens,linkHandlers:this._config.linkHandlers,getLinkBearer:this._config.getLinkBearer}}propagateThemeToDocument(e,t,r,a){if(typeof document>"u")return;const n=document.documentElement,i=(s,o)=>{o!==void 0&&o!==""&&n.style.setProperty(`--aikaara-${s}`,o)};i("primary",e?.primary??t),i("primary-hover",e?.primaryHover),i("primary-contrast",e?.primaryContrast),i("surface",e?.surface),i("surface-muted",e?.surfaceMuted),i("border",e?.border),i("text",e?.text),i("text-muted",e?.textMuted),i("font",e?.font??a),i("radius",e?.radius!=null?`${e.radius}px`:r!=null?`${r}px`:void 0),i("bubble-radius",e?.bubbleRadius!=null?`${e.bubbleRadius}px`:void 0),i("button-radius",e?.buttonRadius!=null?`${e.buttonRadius}px`:void 0),i("user-bubble-bg",e?.userBubbleBg),i("user-bubble-text",e?.userBubbleText),i("bot-bubble-bg",e?.botBubbleBg),i("bot-bubble-text",e?.botBubbleText),i("modal-width",e?.modalWidth),i("modal-height",e?.modalHeight),i("modal-max-width",e?.modalMaxWidth),i("modal-max-height",e?.modalMaxHeight),i("modal-padding",e?.modalPadding)}themeVars(e){if(!e)return"";const t=a=>typeof a=="number"?`${a}px`:void 0,r={primary:e.primary,"primary-hover":e.primaryHover,"primary-contrast":e.primaryContrast,surface:e.surface,"surface-muted":e.surfaceMuted,border:e.border,text:e.text,"text-muted":e.textMuted,font:e.font,radius:t(e.radius),"bubble-radius":t(e.bubbleRadius),"button-radius":t(e.buttonRadius),"user-bubble-bg":e.userBubbleBg,"user-bubble-text":e.userBubbleText,"bot-bubble-bg":e.botBubbleBg,"bot-bubble-text":e.botBubbleText,"modal-width":e.modalWidth,"modal-height":e.modalHeight,"modal-max-width":e.modalMaxWidth,"modal-max-height":e.modalMaxHeight,"modal-padding":e.modalPadding};return Object.entries(r).filter(([,a])=>a!==void 0&&a!=="").map(([a,n])=>`--aikaara-${a}: ${n};`).join(`
6
+ `+ie.prev}function ke(z,ie){var xe=be(z),Ae=[];if(xe){Ae.length=z.length;for(var Ie=0;Ie<z.length;Ie++)Ae[Ie]=oe(z,Ie)?ie(z[Ie],z):""}var Oe=typeof T=="function"?T(z):[],Je;if(F){Je={};for(var Xe=0;Xe<Oe.length;Xe++)Je["$"+Oe[Xe]]=Oe[Xe]}for(var $e in z)oe(z,$e)&&(xe&&String(Number($e))===$e&&$e<z.length||F&&Je["$"+$e]instanceof Symbol||(x.call(/[^\w$]/,$e)?Ae.push(ie($e,z)+": "+ie(z[$e],z)):Ae.push($e+": "+ie(z[$e],z))));if(typeof T=="function")for(var Ze=0;Ze<Oe.length;Ze++)ae.call(z,Oe[Ze])&&Ae.push("["+ie(Oe[Ze])+"]: "+ie(z[Oe[Ze]],z));return Ae}return xr}function Qu(){if(Ki)return Ir;Ki=!0;var c=jt(),e=Lu(),t=Yu(),r=Kt(),a=c("%WeakMap%",!0),n=c("%Map%",!0),i=e("WeakMap.prototype.get",!0),s=e("WeakMap.prototype.set",!0),o=e("WeakMap.prototype.has",!0),l=e("Map.prototype.get",!0),u=e("Map.prototype.set",!0),d=e("Map.prototype.has",!0),p=function(b,k){for(var g=b,_;(_=g.next)!==null;g=_)if(_.key===k)return g.next=_.next,_.next=b.next,b.next=_,_},y=function(b,k){var g=p(b,k);return g&&g.value},f=function(b,k,g){var _=p(b,k);_?_.value=g:b.next={key:k,next:b.next,value:g}},m=function(b,k){return!!p(b,k)};return Ir=function(){var b,k,g,_={assert:function(S){if(!_.has(S))throw new r("Side channel does not contain "+t(S))},get:function(S){if(a&&S&&(typeof S=="object"||typeof S=="function")){if(b)return i(b,S)}else if(n){if(k)return l(k,S)}else if(g)return y(g,S)},has:function(S){if(a&&S&&(typeof S=="object"||typeof S=="function")){if(b)return o(b,S)}else if(n){if(k)return d(k,S)}else if(g)return m(g,S);return!1},set:function(S,v){a&&S&&(typeof S=="object"||typeof S=="function")?(b||(b=new a),s(b,S,v)):n?(k||(k=new n),u(k,S,v)):(g||(g={key:{},next:null}),f(g,S,v))}};return _},Ir}function Hi(){if(Vi)return Tr;Vi=!0;var c=String.prototype.replace,e=/%20/g,t={RFC1738:"RFC1738",RFC3986:"RFC3986"};return Tr={default:t.RFC3986,formatters:{RFC1738:function(r){return c.call(r,e,"+")},RFC3986:function(r){return String(r)}},RFC1738:t.RFC1738,RFC3986:t.RFC3986},Tr}function Sa(){if(Gi)return Cr;Gi=!0;var c=Hi(),e=Object.prototype.hasOwnProperty,t=Array.isArray,r=(function(){for(var b=[],k=0;k<256;++k)b.push("%"+((k<16?"0":"")+k.toString(16)).toUpperCase());return b})(),a=function(b){for(;b.length>1;){var k=b.pop(),g=k.obj[k.prop];if(t(g)){for(var _=[],S=0;S<g.length;++S)typeof g[S]<"u"&&_.push(g[S]);k.obj[k.prop]=_}}},n=function(b,k){for(var g=k&&k.plainObjects?Object.create(null):{},_=0;_<b.length;++_)typeof b[_]<"u"&&(g[_]=b[_]);return g},i=function b(k,g,_){if(!g)return k;if(typeof g!="object"){if(t(k))k.push(g);else if(k&&typeof k=="object")(_&&(_.plainObjects||_.allowPrototypes)||!e.call(Object.prototype,g))&&(k[g]=!0);else return[k,g];return k}if(!k||typeof k!="object")return[k].concat(g);var S=k;return t(k)&&!t(g)&&(S=n(k,_)),t(k)&&t(g)?(g.forEach(function(v,x){if(e.call(k,x)){var E=k[x];E&&typeof E=="object"&&v&&typeof v=="object"?k[x]=b(E,v,_):k.push(v)}else k[x]=v}),k):Object.keys(g).reduce(function(v,x){var E=g[x];return e.call(v,x)?v[x]=b(v[x],E,_):v[x]=E,v},S)},s=function(b,k){return Object.keys(k).reduce(function(g,_){return g[_]=k[_],g},b)},o=function(b,k,g){var _=b.replace(/\+/g," ");if(g==="iso-8859-1")return _.replace(/%[0-9a-f]{2}/gi,unescape);try{return decodeURIComponent(_)}catch{return _}},l=1024,u=function(b,k,g,_,S){if(b.length===0)return b;var v=b;if(typeof b=="symbol"?v=Symbol.prototype.toString.call(b):typeof b!="string"&&(v=String(b)),g==="iso-8859-1")return escape(v).replace(/%u[0-9a-f]{4}/gi,function(T){return"%26%23"+parseInt(T.slice(2),16)+"%3B"});for(var x="",E=0;E<v.length;E+=l){for(var I=v.length>=l?v.slice(E,E+l):v,M=[],O=0;O<I.length;++O){var B=I.charCodeAt(O);if(B===45||B===46||B===95||B===126||B>=48&&B<=57||B>=65&&B<=90||B>=97&&B<=122||S===c.RFC1738&&(B===40||B===41)){M[M.length]=I.charAt(O);continue}if(B<128){M[M.length]=r[B];continue}if(B<2048){M[M.length]=r[192|B>>6]+r[128|B&63];continue}if(B<55296||B>=57344){M[M.length]=r[224|B>>12]+r[128|B>>6&63]+r[128|B&63];continue}O+=1,B=65536+((B&1023)<<10|I.charCodeAt(O)&1023),M[M.length]=r[240|B>>18]+r[128|B>>12&63]+r[128|B>>6&63]+r[128|B&63]}x+=M.join("")}return x},d=function(b){for(var k=[{obj:{o:b},prop:"o"}],g=[],_=0;_<k.length;++_)for(var S=k[_],v=S.obj[S.prop],x=Object.keys(v),E=0;E<x.length;++E){var I=x[E],M=v[I];typeof M=="object"&&M!==null&&g.indexOf(M)===-1&&(k.push({obj:v,prop:I}),g.push(M))}return a(k),b},p=function(b){return Object.prototype.toString.call(b)==="[object RegExp]"},y=function(b){return!b||typeof b!="object"?!1:!!(b.constructor&&b.constructor.isBuffer&&b.constructor.isBuffer(b))},f=function(b,k){return[].concat(b,k)},m=function(b,k){if(t(b)){for(var g=[],_=0;_<b.length;_+=1)g.push(k(b[_]));return g}return k(b)};return Cr={arrayToObject:n,assign:s,combine:f,compact:d,decode:o,encode:u,isBuffer:y,isRegExp:p,maybeMap:m,merge:i},Cr}function Ju(){if(Yi)return Or;Yi=!0;var c=Qu(),e=Sa(),t=Hi(),r=Object.prototype.hasOwnProperty,a={brackets:function(m){return m+"[]"},comma:"comma",indices:function(m,b){return m+"["+b+"]"},repeat:function(m){return m}},n=Array.isArray,i=Array.prototype.push,s=function(m,b){i.apply(m,n(b)?b:[b])},o=Date.prototype.toISOString,l=t.default,u={addQueryPrefix:!1,allowDots:!1,allowEmptyArrays:!1,arrayFormat:"indices",charset:"utf-8",charsetSentinel:!1,delimiter:"&",encode:!0,encodeDotInKeys:!1,encoder:e.encode,encodeValuesOnly:!1,format:l,formatter:t.formatters[l],indices:!1,serializeDate:function(m){return o.call(m)},skipNulls:!1,strictNullHandling:!1},d=function(m){return typeof m=="string"||typeof m=="number"||typeof m=="boolean"||typeof m=="symbol"||typeof m=="bigint"},p={},y=function m(b,k,g,_,S,v,x,E,I,M,O,B,T,W,F,N,ae,Y){for(var K=b,re=Y,D=0,Z=!1;(re=re.get(p))!==void 0&&!Z;){var P=re.get(b);if(D+=1,typeof P<"u"){if(P===D)throw new RangeError("Cyclic object value");Z=!0}typeof re.get(p)>"u"&&(D=0)}if(typeof M=="function"?K=M(k,K):K instanceof Date?K=T(K):g==="comma"&&n(K)&&(K=e.maybeMap(K,function(R){return R instanceof Date?T(R):R})),K===null){if(v)return I&&!N?I(k,u.encoder,ae,"key",W):k;K=""}if(d(K)||e.isBuffer(K)){if(I){var J=N?k:I(k,u.encoder,ae,"key",W);return[F(J)+"="+F(I(K,u.encoder,ae,"value",W))]}return[F(k)+"="+F(String(K))]}var be=[];if(typeof K>"u")return be;var te;if(g==="comma"&&n(K))N&&I&&(K=e.maybeMap(K,I)),te=[{value:K.length>0?K.join(",")||null:void 0}];else if(n(M))te=M;else{var we=Object.keys(K);te=O?we.sort(O):we}var V=E?k.replace(/\./g,"%2E"):k,L=_&&n(K)&&K.length===1?V+"[]":V;if(S&&n(K)&&K.length===0)return L+"[]";for(var ne=0;ne<te.length;++ne){var H=te[ne],G=typeof H=="object"&&typeof H.value<"u"?H.value:K[H];if(!(x&&G===null)){var Q=B&&E?H.replace(/\./g,"%2E"):H,me=n(K)?typeof g=="function"?g(L,Q):L:L+(B?"."+Q:"["+Q+"]");Y.set(b,D);var oe=c();oe.set(p,Y),s(be,m(G,me,g,_,S,v,x,E,g==="comma"&&N&&n(K)?null:I,M,O,B,T,W,F,N,ae,oe))}}return be},f=function(m){if(!m)return u;if(typeof m.allowEmptyArrays<"u"&&typeof m.allowEmptyArrays!="boolean")throw new TypeError("`allowEmptyArrays` option can only be `true` or `false`, when provided");if(typeof m.encodeDotInKeys<"u"&&typeof m.encodeDotInKeys!="boolean")throw new TypeError("`encodeDotInKeys` option can only be `true` or `false`, when provided");if(m.encoder!==null&&typeof m.encoder<"u"&&typeof m.encoder!="function")throw new TypeError("Encoder has to be a function.");var b=m.charset||u.charset;if(typeof m.charset<"u"&&m.charset!=="utf-8"&&m.charset!=="iso-8859-1")throw new TypeError("The charset option must be either utf-8, iso-8859-1, or undefined");var k=t.default;if(typeof m.format<"u"){if(!r.call(t.formatters,m.format))throw new TypeError("Unknown format option provided.");k=m.format}var g=t.formatters[k],_=u.filter;(typeof m.filter=="function"||n(m.filter))&&(_=m.filter);var S;if(m.arrayFormat in a?S=m.arrayFormat:"indices"in m?S=m.indices?"indices":"repeat":S=u.arrayFormat,"commaRoundTrip"in m&&typeof m.commaRoundTrip!="boolean")throw new TypeError("`commaRoundTrip` must be a boolean, or absent");var v=typeof m.allowDots>"u"?m.encodeDotInKeys===!0?!0:u.allowDots:!!m.allowDots;return{addQueryPrefix:typeof m.addQueryPrefix=="boolean"?m.addQueryPrefix:u.addQueryPrefix,allowDots:v,allowEmptyArrays:typeof m.allowEmptyArrays=="boolean"?!!m.allowEmptyArrays:u.allowEmptyArrays,arrayFormat:S,charset:b,charsetSentinel:typeof m.charsetSentinel=="boolean"?m.charsetSentinel:u.charsetSentinel,commaRoundTrip:m.commaRoundTrip,delimiter:typeof m.delimiter>"u"?u.delimiter:m.delimiter,encode:typeof m.encode=="boolean"?m.encode:u.encode,encodeDotInKeys:typeof m.encodeDotInKeys=="boolean"?m.encodeDotInKeys:u.encodeDotInKeys,encoder:typeof m.encoder=="function"?m.encoder:u.encoder,encodeValuesOnly:typeof m.encodeValuesOnly=="boolean"?m.encodeValuesOnly:u.encodeValuesOnly,filter:_,format:k,formatter:g,serializeDate:typeof m.serializeDate=="function"?m.serializeDate:u.serializeDate,skipNulls:typeof m.skipNulls=="boolean"?m.skipNulls:u.skipNulls,sort:typeof m.sort=="function"?m.sort:null,strictNullHandling:typeof m.strictNullHandling=="boolean"?m.strictNullHandling:u.strictNullHandling}};return Or=function(m,b){var k=m,g=f(b),_,S;typeof g.filter=="function"?(S=g.filter,k=S("",k)):n(g.filter)&&(S=g.filter,_=S);var v=[];if(typeof k!="object"||k===null)return"";var x=a[g.arrayFormat],E=x==="comma"&&g.commaRoundTrip;_||(_=Object.keys(k)),g.sort&&_.sort(g.sort);for(var I=c(),M=0;M<_.length;++M){var O=_[M];g.skipNulls&&k[O]===null||s(v,y(k[O],O,x,E,g.allowEmptyArrays,g.strictNullHandling,g.skipNulls,g.encodeDotInKeys,g.encode?g.encoder:null,g.filter,g.sort,g.allowDots,g.serializeDate,g.format,g.formatter,g.encodeValuesOnly,g.charset,I))}var B=v.join(g.delimiter),T=g.addQueryPrefix===!0?"?":"";return g.charsetSentinel&&(g.charset==="iso-8859-1"?T+="utf8=%26%2310003%3B&":T+="utf8=%E2%9C%93&"),B.length>0?T+B:""},Or}function Xu(){if(Qi)return Pr;Qi=!0;var c=Sa(),e=Object.prototype.hasOwnProperty,t=Array.isArray,r={allowDots:!1,allowEmptyArrays:!1,allowPrototypes:!1,allowSparse:!1,arrayLimit:20,charset:"utf-8",charsetSentinel:!1,comma:!1,decodeDotInKeys:!1,decoder:c.decode,delimiter:"&",depth:5,duplicates:"combine",ignoreQueryPrefix:!1,interpretNumericEntities:!1,parameterLimit:1e3,parseArrays:!0,plainObjects:!1,strictDepth:!1,strictNullHandling:!1},a=function(p){return p.replace(/&#(\d+);/g,function(y,f){return String.fromCharCode(parseInt(f,10))})},n=function(p,y){return p&&typeof p=="string"&&y.comma&&p.indexOf(",")>-1?p.split(","):p},i="utf8=%26%2310003%3B",s="utf8=%E2%9C%93",o=function(p,y){var f={__proto__:null},m=y.ignoreQueryPrefix?p.replace(/^\?/,""):p;m=m.replace(/%5B/gi,"[").replace(/%5D/gi,"]");var b=y.parameterLimit===1/0?void 0:y.parameterLimit,k=m.split(y.delimiter,b),g=-1,_,S=y.charset;if(y.charsetSentinel)for(_=0;_<k.length;++_)k[_].indexOf("utf8=")===0&&(k[_]===s?S="utf-8":k[_]===i&&(S="iso-8859-1"),g=_,_=k.length);for(_=0;_<k.length;++_)if(_!==g){var v=k[_],x=v.indexOf("]="),E=x===-1?v.indexOf("="):x+1,I,M;E===-1?(I=y.decoder(v,r.decoder,S,"key"),M=y.strictNullHandling?null:""):(I=y.decoder(v.slice(0,E),r.decoder,S,"key"),M=c.maybeMap(n(v.slice(E+1),y),function(B){return y.decoder(B,r.decoder,S,"value")})),M&&y.interpretNumericEntities&&S==="iso-8859-1"&&(M=a(M)),v.indexOf("[]=")>-1&&(M=t(M)?[M]:M);var O=e.call(f,I);O&&y.duplicates==="combine"?f[I]=c.combine(f[I],M):(!O||y.duplicates==="last")&&(f[I]=M)}return f},l=function(p,y,f,m){for(var b=m?y:n(y,f),k=p.length-1;k>=0;--k){var g,_=p[k];if(_==="[]"&&f.parseArrays)g=f.allowEmptyArrays&&(b===""||f.strictNullHandling&&b===null)?[]:[].concat(b);else{g=f.plainObjects?Object.create(null):{};var S=_.charAt(0)==="["&&_.charAt(_.length-1)==="]"?_.slice(1,-1):_,v=f.decodeDotInKeys?S.replace(/%2E/g,"."):S,x=parseInt(v,10);!f.parseArrays&&v===""?g={0:b}:!isNaN(x)&&_!==v&&String(x)===v&&x>=0&&f.parseArrays&&x<=f.arrayLimit?(g=[],g[x]=b):v!=="__proto__"&&(g[v]=b)}b=g}return b},u=function(p,y,f,m){if(p){var b=f.allowDots?p.replace(/\.([^.[]+)/g,"[$1]"):p,k=/(\[[^[\]]*])/,g=/(\[[^[\]]*])/g,_=f.depth>0&&k.exec(b),S=_?b.slice(0,_.index):b,v=[];if(S){if(!f.plainObjects&&e.call(Object.prototype,S)&&!f.allowPrototypes)return;v.push(S)}for(var x=0;f.depth>0&&(_=g.exec(b))!==null&&x<f.depth;){if(x+=1,!f.plainObjects&&e.call(Object.prototype,_[1].slice(1,-1))&&!f.allowPrototypes)return;v.push(_[1])}if(_){if(f.strictDepth===!0)throw new RangeError("Input depth exceeded depth option of "+f.depth+" and strictDepth is true");v.push("["+b.slice(_.index)+"]")}return l(v,y,f,m)}},d=function(p){if(!p)return r;if(typeof p.allowEmptyArrays<"u"&&typeof p.allowEmptyArrays!="boolean")throw new TypeError("`allowEmptyArrays` option can only be `true` or `false`, when provided");if(typeof p.decodeDotInKeys<"u"&&typeof p.decodeDotInKeys!="boolean")throw new TypeError("`decodeDotInKeys` option can only be `true` or `false`, when provided");if(p.decoder!==null&&typeof p.decoder<"u"&&typeof p.decoder!="function")throw new TypeError("Decoder has to be a function.");if(typeof p.charset<"u"&&p.charset!=="utf-8"&&p.charset!=="iso-8859-1")throw new TypeError("The charset option must be either utf-8, iso-8859-1, or undefined");var y=typeof p.charset>"u"?r.charset:p.charset,f=typeof p.duplicates>"u"?r.duplicates:p.duplicates;if(f!=="combine"&&f!=="first"&&f!=="last")throw new TypeError("The duplicates option must be either combine, first, or last");var m=typeof p.allowDots>"u"?p.decodeDotInKeys===!0?!0:r.allowDots:!!p.allowDots;return{allowDots:m,allowEmptyArrays:typeof p.allowEmptyArrays=="boolean"?!!p.allowEmptyArrays:r.allowEmptyArrays,allowPrototypes:typeof p.allowPrototypes=="boolean"?p.allowPrototypes:r.allowPrototypes,allowSparse:typeof p.allowSparse=="boolean"?p.allowSparse:r.allowSparse,arrayLimit:typeof p.arrayLimit=="number"?p.arrayLimit:r.arrayLimit,charset:y,charsetSentinel:typeof p.charsetSentinel=="boolean"?p.charsetSentinel:r.charsetSentinel,comma:typeof p.comma=="boolean"?p.comma:r.comma,decodeDotInKeys:typeof p.decodeDotInKeys=="boolean"?p.decodeDotInKeys:r.decodeDotInKeys,decoder:typeof p.decoder=="function"?p.decoder:r.decoder,delimiter:typeof p.delimiter=="string"||c.isRegExp(p.delimiter)?p.delimiter:r.delimiter,depth:typeof p.depth=="number"||p.depth===!1?+p.depth:r.depth,duplicates:f,ignoreQueryPrefix:p.ignoreQueryPrefix===!0,interpretNumericEntities:typeof p.interpretNumericEntities=="boolean"?p.interpretNumericEntities:r.interpretNumericEntities,parameterLimit:typeof p.parameterLimit=="number"?p.parameterLimit:r.parameterLimit,parseArrays:p.parseArrays!==!1,plainObjects:typeof p.plainObjects=="boolean"?p.plainObjects:r.plainObjects,strictDepth:typeof p.strictDepth=="boolean"?!!p.strictDepth:r.strictDepth,strictNullHandling:typeof p.strictNullHandling=="boolean"?p.strictNullHandling:r.strictNullHandling}};return Pr=function(p,y){var f=d(y);if(p===""||p===null||typeof p>"u")return f.plainObjects?Object.create(null):{};for(var m=typeof p=="string"?o(p,f):p,b=f.plainObjects?Object.create(null):{},k=Object.keys(m),g=0;g<k.length;++g){var _=k[g],S=u(_,m[_],f,typeof p=="string");b=c.merge(b,S,f)}return f.allowSparse===!0?b:c.compact(b)},Pr}function Zu(){if(Ji)return Mr;Ji=!0;var c=Ju(),e=Xu(),t=Hi();return Mr={formats:t,parse:e,stringify:c},Mr}function eh(){if(Xi)return yt;Xi=!0;var c=mt;function e(){this.protocol=null,this.slashes=null,this.auth=null,this.host=null,this.port=null,this.hostname=null,this.hash=null,this.search=null,this.query=null,this.pathname=null,this.path=null,this.href=null}var t=/^([a-z0-9.+-]+:)/i,r=/:[0-9]*$/,a=/^(\/\/?(?!\/)[^?\s]*)(\?[^\s]*)?$/,n=["<",">",'"',"`"," ","\r",`
7
+ `," "],i=["{","}","|","\\","^","`"].concat(n),s=["'"].concat(i),o=["%","/","?",";","#"].concat(s),l=["/","?","#"],u=255,d=/^[+a-z0-9A-Z_-]{0,63}$/,p=/^([+a-z0-9A-Z_-]{0,63})(.*)$/,y={javascript:!0,"javascript:":!0},f={javascript:!0,"javascript:":!0},m={http:!0,https:!0,ftp:!0,gopher:!0,file:!0,"http:":!0,"https:":!0,"ftp:":!0,"gopher:":!0,"file:":!0},b=Zu();function k(v,x,E){if(v&&typeof v=="object"&&v instanceof e)return v;var I=new e;return I.parse(v,x,E),I}e.prototype.parse=function(v,x,E){if(typeof v!="string")throw new TypeError("Parameter 'url' must be a string, not "+typeof v);var I=v.indexOf("?"),M=I!==-1&&I<v.indexOf("#")?"?":"#",O=v.split(M),B=/\\/g;O[0]=O[0].replace(B,"/"),v=O.join(M);var T=v;if(T=T.trim(),!E&&v.split("#").length===1){var W=a.exec(T);if(W)return this.path=T,this.href=T,this.pathname=W[1],W[2]?(this.search=W[2],x?this.query=b.parse(this.search.substr(1)):this.query=this.search.substr(1)):x&&(this.search="",this.query={}),this}var F=t.exec(T);if(F){F=F[0];var N=F.toLowerCase();this.protocol=N,T=T.substr(F.length)}if(E||F||T.match(/^\/\/[^@/]+@[^@/]+/)){var ae=T.substr(0,2)==="//";ae&&!(F&&f[F])&&(T=T.substr(2),this.slashes=!0)}if(!f[F]&&(ae||F&&!m[F])){for(var Y=-1,K=0;K<l.length;K++){var re=T.indexOf(l[K]);re!==-1&&(Y===-1||re<Y)&&(Y=re)}var D,Z;Y===-1?Z=T.lastIndexOf("@"):Z=T.lastIndexOf("@",Y),Z!==-1&&(D=T.slice(0,Z),T=T.slice(Z+1),this.auth=decodeURIComponent(D)),Y=-1;for(var K=0;K<o.length;K++){var re=T.indexOf(o[K]);re!==-1&&(Y===-1||re<Y)&&(Y=re)}Y===-1&&(Y=T.length),this.host=T.slice(0,Y),T=T.slice(Y),this.parseHost(),this.hostname=this.hostname||"";var P=this.hostname[0]==="["&&this.hostname[this.hostname.length-1]==="]";if(!P)for(var J=this.hostname.split(/\./),K=0,be=J.length;K<be;K++){var te=J[K];if(te&&!te.match(d)){for(var we="",V=0,L=te.length;V<L;V++)te.charCodeAt(V)>127?we+="x":we+=te[V];if(!we.match(d)){var ne=J.slice(0,K),H=J.slice(K+1),G=te.match(p);G&&(ne.push(G[1]),H.unshift(G[2])),H.length&&(T="/"+H.join(".")+T),this.hostname=ne.join(".");break}}}this.hostname.length>u?this.hostname="":this.hostname=this.hostname.toLowerCase(),P||(this.hostname=c.toASCII(this.hostname));var Q=this.port?":"+this.port:"",me=this.hostname||"";this.host=me+Q,this.href+=this.host,P&&(this.hostname=this.hostname.substr(1,this.hostname.length-2),T[0]!=="/"&&(T="/"+T))}if(!y[N])for(var K=0,be=s.length;K<be;K++){var oe=s[K];if(T.indexOf(oe)!==-1){var R=encodeURIComponent(oe);R===oe&&(R=escape(oe)),T=T.split(oe).join(R)}}var $=T.indexOf("#");$!==-1&&(this.hash=T.substr($),T=T.slice(0,$));var ee=T.indexOf("?");if(ee!==-1?(this.search=T.substr(ee),this.query=T.substr(ee+1),x&&(this.query=b.parse(this.query)),T=T.slice(0,ee)):x&&(this.search="",this.query={}),T&&(this.pathname=T),m[N]&&this.hostname&&!this.pathname&&(this.pathname="/"),this.pathname||this.search){var Q=this.pathname||"",fe=this.search||"";this.path=Q+fe}return this.href=this.format(),this};function g(v){return typeof v=="string"&&(v=k(v)),v instanceof e?v.format():e.prototype.format.call(v)}e.prototype.format=function(){var v=this.auth||"";v&&(v=encodeURIComponent(v),v=v.replace(/%3A/i,":"),v+="@");var x=this.protocol||"",E=this.pathname||"",I=this.hash||"",M=!1,O="";this.host?M=v+this.host:this.hostname&&(M=v+(this.hostname.indexOf(":")===-1?this.hostname:"["+this.hostname+"]"),this.port&&(M+=":"+this.port)),this.query&&typeof this.query=="object"&&Object.keys(this.query).length&&(O=b.stringify(this.query,{arrayFormat:"repeat",addQueryPrefix:!1}));var B=this.search||O&&"?"+O||"";return x&&x.substr(-1)!==":"&&(x+=":"),this.slashes||(!x||m[x])&&M!==!1?(M="//"+(M||""),E&&E.charAt(0)!=="/"&&(E="/"+E)):M||(M=""),I&&I.charAt(0)!=="#"&&(I="#"+I),B&&B.charAt(0)!=="?"&&(B="?"+B),E=E.replace(/[?#]/g,function(T){return encodeURIComponent(T)}),B=B.replace("#","%23"),x+M+E+B+I};function _(v,x){return k(v,!1,!0).resolve(x)}e.prototype.resolve=function(v){return this.resolveObject(k(v,!1,!0)).format()};function S(v,x){return v?k(v,!1,!0).resolveObject(x):x}return e.prototype.resolveObject=function(v){if(typeof v=="string"){var x=new e;x.parse(v,!1,!0),v=x}for(var E=new e,I=Object.keys(this),M=0;M<I.length;M++){var O=I[M];E[O]=this[O]}if(E.hash=v.hash,v.href==="")return E.href=E.format(),E;if(v.slashes&&!v.protocol){for(var B=Object.keys(v),T=0;T<B.length;T++){var W=B[T];W!=="protocol"&&(E[W]=v[W])}return m[E.protocol]&&E.hostname&&!E.pathname&&(E.pathname="/",E.path=E.pathname),E.href=E.format(),E}if(v.protocol&&v.protocol!==E.protocol){if(!m[v.protocol]){for(var F=Object.keys(v),N=0;N<F.length;N++){var ae=F[N];E[ae]=v[ae]}return E.href=E.format(),E}if(E.protocol=v.protocol,!v.host&&!f[v.protocol]){for(var be=(v.pathname||"").split("/");be.length&&!(v.host=be.shift()););v.host||(v.host=""),v.hostname||(v.hostname=""),be[0]!==""&&be.unshift(""),be.length<2&&be.unshift(""),E.pathname=be.join("/")}else E.pathname=v.pathname;if(E.search=v.search,E.query=v.query,E.host=v.host||"",E.auth=v.auth,E.hostname=v.hostname||v.host,E.port=v.port,E.pathname||E.search){var Y=E.pathname||"",K=E.search||"";E.path=Y+K}return E.slashes=E.slashes||v.slashes,E.href=E.format(),E}var re=E.pathname&&E.pathname.charAt(0)==="/",D=v.host||v.pathname&&v.pathname.charAt(0)==="/",Z=D||re||E.host&&v.pathname,P=Z,J=E.pathname&&E.pathname.split("/")||[],be=v.pathname&&v.pathname.split("/")||[],te=E.protocol&&!m[E.protocol];if(te&&(E.hostname="",E.port=null,E.host&&(J[0]===""?J[0]=E.host:J.unshift(E.host)),E.host="",v.protocol&&(v.hostname=null,v.port=null,v.host&&(be[0]===""?be[0]=v.host:be.unshift(v.host)),v.host=null),Z=Z&&(be[0]===""||J[0]==="")),D)E.host=v.host||v.host===""?v.host:E.host,E.hostname=v.hostname||v.hostname===""?v.hostname:E.hostname,E.search=v.search,E.query=v.query,J=be;else if(be.length)J||(J=[]),J.pop(),J=J.concat(be),E.search=v.search,E.query=v.query;else if(v.search!=null){if(te){E.host=J.shift(),E.hostname=E.host;var we=E.host&&E.host.indexOf("@")>0?E.host.split("@"):!1;we&&(E.auth=we.shift(),E.hostname=we.shift(),E.host=E.hostname)}return E.search=v.search,E.query=v.query,(E.pathname!==null||E.search!==null)&&(E.path=(E.pathname?E.pathname:"")+(E.search?E.search:"")),E.href=E.format(),E}if(!J.length)return E.pathname=null,E.search?E.path="/"+E.search:E.path=null,E.href=E.format(),E;for(var V=J.slice(-1)[0],L=(E.host||v.host||J.length>1)&&(V==="."||V==="..")||V==="",ne=0,H=J.length;H>=0;H--)V=J[H],V==="."?J.splice(H,1):V===".."?(J.splice(H,1),ne++):ne&&(J.splice(H,1),ne--);if(!Z&&!P)for(;ne--;ne)J.unshift("..");Z&&J[0]!==""&&(!J[0]||J[0].charAt(0)!=="/")&&J.unshift(""),L&&J.join("/").substr(-1)!=="/"&&J.push("");var G=J[0]===""||J[0]&&J[0].charAt(0)==="/";if(te){E.hostname=G?"":J.length?J.shift():"",E.host=E.hostname;var we=E.host&&E.host.indexOf("@")>0?E.host.split("@"):!1;we&&(E.auth=we.shift(),E.hostname=we.shift(),E.host=E.hostname)}return Z=Z||E.host&&J.length,Z&&!G&&J.unshift(""),J.length>0?E.pathname=J.join("/"):(E.pathname=null,E.path=null),(E.pathname!==null||E.search!==null)&&(E.path=(E.pathname?E.pathname:"")+(E.search?E.search:"")),E.auth=v.auth||E.auth,E.slashes=E.slashes||v.slashes,E.href=E.format(),E},e.prototype.parseHost=function(){var v=this.host,x=r.exec(v);x&&(x=x[0],x!==":"&&(this.port=x.substr(1)),v=v.substr(0,v.length-x.length)),v&&(this.hostname=v)},yt.parse=k,yt.resolve=_,yt.resolveObject=S,yt.format=g,yt.Url=e,yt}function Ea(c){if(typeof c=="string")c=new URL(c);else if(!(c instanceof URL))throw new Deno.errors.InvalidData("invalid argument path , must be a string or URL");if(c.protocol!=="file:")throw new Deno.errors.InvalidData("invalid url scheme");return Rr?th(c):rh(c)}function th(c){let e=c.hostname,t=c.pathname;for(let r=0;r<t.length;r++)if(t[r]==="%"){let a=t.codePointAt(r+2)||32;if(t[r+1]==="2"&&a===102||t[r+1]==="5"&&a===99)throw new Deno.errors.InvalidData("must not include encoded \\ or / characters")}if(t=t.replace(Ba,"\\"),t=decodeURIComponent(t),e!=="")return`\\\\${e}${t}`;{let r=t.codePointAt(1)|32,a=t[2];if(r<Na||r>Ua||a!==":")throw new Deno.errors.InvalidData("file url path must be absolute");return t.slice(1)}}function rh(c){if(c.hostname!=="")throw new Deno.errors.InvalidData("invalid file url hostname");let e=c.pathname;for(let t=0;t<e.length;t++)if(e[t]==="%"){let r=e.codePointAt(t+2)||32;if(e[t+1]==="2"&&r===102)throw new Deno.errors.InvalidData("must not include encoded / characters")}return decodeURIComponent(e)}function xa(c){let e=qi.resolve(c),t=c.charCodeAt(c.length-1);(t===La||Rr&&t===ja)&&e[e.length-1]!==qi.sep&&(e+="/");let r=new URL("file://");return e.includes("%")&&(e=e.replace(Fa,"%25")),!Rr&&e.includes("\\")&&(e=e.replace(Da,"%5C")),e.includes(`
8
+ `)&&(e=e.replace($a,"%0A")),e.includes("\r")&&(e=e.replace(Wa,"%0D")),e.includes(" ")&&(e=e.replace(qa,"%09")),r.pathname=e,r}var Aa,xr,zi,Ar,Ir,Ki,Tr,Vi,Cr,Gi,Or,Yi,Pr,Qi,Mr,Ji,yt,Xi,De,Ia,Ta,Ca,Oa,Pa,Ma,Ra,ja,La,Na,Ua,Rr,Ba,Fa,Da,$a,Wa,qa,nh=He(()=>{le(),ue(),ce(),wu(),Nu(),Gu(),_a(),Aa=Object.freeze(Object.create(null)),xr={},zi=!1,Ar=typeof globalThis<"u"?globalThis:typeof self<"u"?self:global,Ir={},Ki=!1,Tr={},Vi=!1,Cr={},Gi=!1,Or={},Yi=!1,Pr={},Qi=!1,Mr={},Ji=!1,yt={},Xi=!1,De=eh(),De.parse,De.resolve,De.resolveObject,De.format,De.Url,Ia=typeof Deno<"u"?Deno.build.os==="windows"?"win32":Deno.build.os:void 0,De.URL=typeof URL<"u"?URL:null,De.pathToFileURL=xa,De.fileURLToPath=Ea,Ta=De.Url,Ca=De.format,Oa=De.resolve,Pa=De.resolveObject,Ma=De.parse,Ra=De.URL,ja=92,La=47,Na=97,Ua=122,Rr=Ia==="win32",Ba=/\//g,Fa=/%/g,Da=/\\/g,$a=/\n/g,Wa=/\r/g,qa=/\t/g}),ih=pe((c,e)=>{le(),ue(),ce(),e.exports=function(){throw new Error("ws does not work in the browser. Browser clients must use the native WebSocket object")}}),Zi=pe(c=>{le(),ue(),ce(),Object.defineProperty(c,"__esModule",{value:!0}),c.BufferedDuplex=void 0,c.writev=r;var e=Et(),t=(Ue(),Pe(Ne));function r(n,i){let s=new Array(n.length);for(let o=0;o<n.length;o++)typeof n[o].chunk=="string"?s[o]=t.Buffer.from(n[o].chunk,"utf8"):s[o]=n[o].chunk;this._write(t.Buffer.concat(s),"binary",i)}var a=class extends e.Duplex{socket;proxy;isSocketOpen;writeQueue;constructor(n,i,s){super({objectMode:!0}),this.proxy=i,this.socket=s,this.writeQueue=[],n.objectMode||(this._writev=r.bind(this)),this.isSocketOpen=!1,this.proxy.on("data",o=>{!this.destroyed&&this.readable&&this.push(o)})}_read(n){this.proxy.read(n)}_write(n,i,s){this.isSocketOpen?this.writeToProxy(n,i,s):this.writeQueue.push({chunk:n,encoding:i,cb:s})}_final(n){this.writeQueue=[],this.proxy.end(n)}_destroy(n,i){this.writeQueue=[],this.proxy.destroy(),i(n)}socketReady(){this.emit("connect"),this.isSocketOpen=!0,this.processWriteQueue()}writeToProxy(n,i,s){this.proxy.write(n,i)===!1?this.proxy.once("drain",s):s()}processWriteQueue(){for(;this.writeQueue.length>0;){let{chunk:n,encoding:i,cb:s}=this.writeQueue.shift();this.writeToProxy(n,i,s)}}};c.BufferedDuplex=a}),jr=pe(c=>{le(),ue(),ce();var e=c&&c.__importDefault||function(k){return k&&k.__esModule?k:{default:k}};Object.defineProperty(c,"__esModule",{value:!0}),c.streamBuilder=c.browserStreamBuilder=void 0;var t=(Ue(),Pe(Ne)),r=e(ih()),a=e(lt()),n=Et(),i=e(lr()),s=Zi(),o=(0,a.default)("mqttjs:ws"),l=["rejectUnauthorized","ca","cert","key","pfx","passphrase"];function u(k,g){let _=`${k.protocol}://${k.hostname}:${k.port}${k.path}`;return typeof k.transformWsUrl=="function"&&(_=k.transformWsUrl(_,k,g)),_}function d(k){let g=k;return k.port||(k.protocol==="wss"?g.port=443:g.port=80),k.path||(g.path="/"),k.wsOptions||(g.wsOptions={}),!i.default&&!k.forceNativeWebSocket&&k.protocol==="wss"&&l.forEach(_=>{Object.prototype.hasOwnProperty.call(k,_)&&!Object.prototype.hasOwnProperty.call(k.wsOptions,_)&&(g.wsOptions[_]=k[_])}),g}function p(k){let g=d(k);if(g.hostname||(g.hostname=g.host),!g.hostname){if(typeof document>"u")throw new Error("Could not determine host. Specify host manually.");let _=new URL(document.URL);g.hostname=_.hostname,g.port||(g.port=Number(_.port))}return g.objectMode===void 0&&(g.objectMode=!(g.binary===!0||g.binary===void 0)),g}function y(k,g,_){o("createWebSocket"),o(`protocol: ${_.protocolId} ${_.protocolVersion}`);let S=_.protocolId==="MQIsdp"&&_.protocolVersion===3?"mqttv3.1":"mqtt";o(`creating new Websocket for url: ${g} and protocol: ${S}`);let v;return _.createWebsocket?v=_.createWebsocket(g,[S],_):v=new r.default(g,[S],_.wsOptions),v}function f(k,g){let _=g.protocolId==="MQIsdp"&&g.protocolVersion===3?"mqttv3.1":"mqtt",S=u(g,k),v;return g.createWebsocket?v=g.createWebsocket(S,[_],g):v=new WebSocket(S,[_]),v.binaryType="arraybuffer",v}var m=(k,g)=>{o("streamBuilder");let _=d(g);_.hostname=_.hostname||_.host||"localhost";let S=u(_,k),v=y(k,S,_),x=r.default.createWebSocketStream(v,_.wsOptions);return x.url=S,v.on("close",()=>{x.destroy()}),x};c.streamBuilder=m;var b=(k,g)=>{o("browserStreamBuilder");let _,S=p(g).browserBufferSize||1024*512,v=g.browserBufferTimeout||1e3,x=!g.objectMode,E=f(k,g),I=O(g,N,ae);g.objectMode||(I._writev=s.writev.bind(I)),I.on("close",()=>{E.close()});let M=typeof E.addEventListener<"u";E.readyState===E.OPEN?(_=I,_.socket=E):(_=new s.BufferedDuplex(g,I,E),M?E.addEventListener("open",B):E.onopen=B),M?(E.addEventListener("close",T),E.addEventListener("error",W),E.addEventListener("message",F)):(E.onclose=T,E.onerror=W,E.onmessage=F);function O(Y,K,re){let D=new n.Transform({objectMode:Y.objectMode});return D._write=K,D._flush=re,D}function B(){o("WebSocket onOpen"),_ instanceof s.BufferedDuplex&&_.socketReady()}function T(Y){o("WebSocket onClose",Y),_.end(),_.destroy()}function W(Y){o("WebSocket onError",Y);let K=new Error("WebSocket error");K.event=Y,_.destroy(K)}async function F(Y){if(!I||!I.readable||!I.writable)return;let{data:K}=Y;K instanceof ArrayBuffer?K=t.Buffer.from(K):K instanceof Blob?K=t.Buffer.from(await new Response(K).arrayBuffer()):K=t.Buffer.from(K,"utf8"),I.push(K)}function N(Y,K,re){if(E.bufferedAmount>S){setTimeout(N,v,Y,K,re);return}x&&typeof Y=="string"&&(Y=t.Buffer.from(Y,"utf8"));try{E.send(Y)}catch(D){return re(D)}re()}function ae(Y){E.close(),Y()}return _};c.browserStreamBuilder=b}),eo={};Ct(eo,{Server:()=>Re,Socket:()=>Re,Stream:()=>Re,_createServerHandle:()=>Re,_normalizeArgs:()=>Re,_setSimultaneousAccepts:()=>Re,connect:()=>Re,createConnection:()=>Re,createServer:()=>Re,default:()=>Ha,isIP:()=>Re,isIPv4:()=>Re,isIPv6:()=>Re});function Re(){throw new Error("Node.js net module is not supported by JSPM core outside of Node.js")}var Ha,za=He(()=>{le(),ue(),ce(),Ha={_createServerHandle:Re,_normalizeArgs:Re,_setSimultaneousAccepts:Re,connect:Re,createConnection:Re,createServer:Re,isIP:Re,isIPv4:Re,isIPv6:Re,Server:Re,Socket:Re,Stream:Re}}),Ka=pe((c,e)=>{le(),ue(),ce(),e.exports={}}),Va=pe(c=>{le(),ue(),ce();var e=c&&c.__importDefault||function(s){return s&&s.__esModule?s:{default:s}};Object.defineProperty(c,"__esModule",{value:!0});var t=e((za(),Pe(eo))),r=e(lt()),a=e(Ka()),n=(0,r.default)("mqttjs:tcp"),i=(s,o)=>{if(o.port=o.port||1883,o.hostname=o.hostname||o.host||"localhost",o.socksProxy)return(0,a.default)(o.hostname,o.port,o.socksProxy,{timeout:o.socksTimeout});let{port:l,path:u}=o,d=o.hostname;return n("port %d and host %s",l,d),t.default.createConnection({port:l,host:d,path:u})};c.default=i}),Ga={};Ct(Ga,{default:()=>Ya});var Ya,oh=He(()=>{le(),ue(),ce(),Ya={}}),Qa=pe(c=>{le(),ue(),ce();var e=c&&c.__importDefault||function(l){return l&&l.__esModule?l:{default:l}};Object.defineProperty(c,"__esModule",{value:!0});var t=(oh(),Pe(Ga)),r=e((za(),Pe(eo))),a=e(lt()),n=e(Ka()),i=(0,a.default)("mqttjs:tls");function s(l){let{host:u,port:d,socksProxy:p,...y}=l;if(p!==void 0){let f=(0,n.default)(u,d,p,{timeout:l.socksTimeout});return(0,t.connect)({...y,socket:f})}return(0,t.connect)(l)}var o=(l,u)=>{u.port=u.port||8883,u.host=u.hostname||u.host||"localhost",r.default.isIP(u.host)===0&&(u.servername=u.host),u.rejectUnauthorized=u.rejectUnauthorized!==!1,delete u.path,i("port %d host %s rejectUnauthorized %b",u.port,u.host,u.rejectUnauthorized);let d=s(u);d.on("secureConnect",()=>{u.rejectUnauthorized&&!d.authorized?d.emit("error",new Error("TLS not authorized")):d.removeListener("error",p)});function p(y){u.rejectUnauthorized&&l.emit("error",y),d.end()}return d.on("error",p),d};c.default=o}),Ja=pe(c=>{le(),ue(),ce(),Object.defineProperty(c,"__esModule",{value:!0});var e=(Ue(),Pe(Ne)),t=Et(),r=Zi(),a,n,i;function s(){let p=new t.Transform;return p._write=(y,f,m)=>{a.send({data:y.buffer,success(){m()},fail(b){m(new Error(b))}})},p._flush=y=>{a.close({success(){y()}})},p}function o(p){p.hostname||(p.hostname="localhost"),p.path||(p.path="/"),p.wsOptions||(p.wsOptions={})}function l(p,y){let f=p.protocol==="wxs"?"wss":"ws",m=`${f}://${p.hostname}${p.path}`;return p.port&&p.port!==80&&p.port!==443&&(m=`${f}://${p.hostname}:${p.port}${p.path}`),typeof p.transformWsUrl=="function"&&(m=p.transformWsUrl(m,p,y)),m}function u(){a.onOpen(()=>{i.socketReady()}),a.onMessage(p=>{let{data:y}=p;y instanceof ArrayBuffer?y=e.Buffer.from(y):y=e.Buffer.from(y,"utf8"),n.push(y)}),a.onClose(()=>{i.emit("close"),i.end(),i.destroy()}),a.onError(p=>{let y=new Error(p.errMsg);i.destroy(y)})}var d=(p,y)=>{if(y.hostname=y.hostname||y.host,!y.hostname)throw new Error("Could not determine host. Specify host manually.");let f=y.protocolId==="MQIsdp"&&y.protocolVersion===3?"mqttv3.1":"mqtt";o(y);let m=l(y,p);a=wx.connectSocket({url:m,protocols:[f]}),n=s(),i=new r.BufferedDuplex(y,n,a),i._destroy=(k,g)=>{a.close({success(){g&&g(k)}})};let b=i.destroy;return i.destroy=(k,g)=>(i.destroy=b,setTimeout(()=>{a.close({fail(){i._destroy(k,g)}})},0),i),u(),i};c.default=d}),Xa=pe(c=>{le(),ue(),ce(),Object.defineProperty(c,"__esModule",{value:!0});var e=(Ue(),Pe(Ne)),t=Et(),r=Zi(),a,n,i,s=!1;function o(){let y=new t.Transform;return y._write=(f,m,b)=>{a.sendSocketMessage({data:f.buffer,success(){b()},fail(){b(new Error)}})},y._flush=f=>{a.closeSocket({success(){f()}})},y}function l(y){y.hostname||(y.hostname="localhost"),y.path||(y.path="/"),y.wsOptions||(y.wsOptions={})}function u(y,f){let m=y.protocol==="alis"?"wss":"ws",b=`${m}://${y.hostname}${y.path}`;return y.port&&y.port!==80&&y.port!==443&&(b=`${m}://${y.hostname}:${y.port}${y.path}`),typeof y.transformWsUrl=="function"&&(b=y.transformWsUrl(b,y,f)),b}function d(){s||(s=!0,a.onSocketOpen(()=>{i.socketReady()}),a.onSocketMessage(y=>{if(typeof y.data=="string"){let f=e.Buffer.from(y.data,"base64");n.push(f)}else{let f=new FileReader;f.addEventListener("load",()=>{if(f.result instanceof ArrayBuffer){n.push(e.Buffer.from(f.result));return}n.push(e.Buffer.from(f.result,"utf-8"))}),f.readAsArrayBuffer(y.data)}}),a.onSocketClose(()=>{i.end(),i.destroy()}),a.onSocketError(y=>{i.destroy(y)}))}var p=(y,f)=>{if(f.hostname=f.hostname||f.host,!f.hostname)throw new Error("Could not determine host. Specify host manually.");let m=f.protocolId==="MQIsdp"&&f.protocolVersion===3?"mqttv3.1":"mqtt";l(f);let b=u(f,y);return a=f.my,a.connectSocket({url:b,protocols:m}),n=o(),i=new r.BufferedDuplex(f,n,a),d(),i};c.default=p}),sh=pe(c=>{le(),ue(),ce();var e=c&&c.__importDefault||function(d){return d&&d.__esModule?d:{default:d}};Object.defineProperty(c,"__esModule",{value:!0}),c.connectAsync=u;var t=e(lt()),r=e((nh(),Pe(ka))),a=e(oi()),n=e(lr());typeof Me?.nextTick!="function"&&(Me.nextTick=setImmediate);var i=(0,t.default)("mqttjs"),s=null;function o(d){let p;if(d.auth)if(p=d.auth.match(/^(.+):(.+)$/),p){let[,y,f]=p;d.username=y,d.password=f}else d.username=d.auth}function l(d,p){if(i("connecting to an MQTT broker..."),typeof d=="object"&&!p&&(p=d,d=""),p=p||{},d&&typeof d=="string"){let m=r.default.parse(d,!0),b={};if(m.port!=null&&(b.port=Number(m.port)),b.host=m.hostname,b.query=m.query,b.auth=m.auth,b.protocol=m.protocol,b.path=m.path,p={...b,...p},!p.protocol)throw new Error("Missing protocol");p.protocol=p.protocol.replace(/:$/,"")}if(p.unixSocket=p.unixSocket||p.protocol?.includes("+unix"),p.unixSocket?p.protocol=p.protocol.replace("+unix",""):!p.protocol?.startsWith("ws")&&!p.protocol?.startsWith("wx")&&delete p.path,o(p),p.query&&typeof p.query.clientId=="string"&&(p.clientId=p.query.clientId),n.default||p.unixSocket?p.socksProxy=void 0:p.socksProxy===void 0&&typeof Me<"u"&&(p.socksProxy=Me.env.MQTTJS_SOCKS_PROXY),p.cert&&p.key)if(p.protocol){if(["mqtts","wss","wxs","alis"].indexOf(p.protocol)===-1)switch(p.protocol){case"mqtt":p.protocol="mqtts";break;case"ws":p.protocol="wss";break;case"wx":p.protocol="wxs";break;case"ali":p.protocol="alis";break;default:throw new Error(`Unknown protocol for secure connection: "${p.protocol}"!`)}}else throw new Error("Missing secure protocol key");if(s||(s={},!n.default&&!p.forceNativeWebSocket?(s.ws=jr().streamBuilder,s.wss=jr().streamBuilder,s.mqtt=Va().default,s.tcp=Va().default,s.ssl=Qa().default,s.tls=s.ssl,s.mqtts=Qa().default):(s.ws=jr().browserStreamBuilder,s.wss=jr().browserStreamBuilder,s.wx=Ja().default,s.wxs=Ja().default,s.ali=Xa().default,s.alis=Xa().default)),!s[p.protocol]){let m=["mqtts","wss"].indexOf(p.protocol)!==-1;p.protocol=["mqtt","mqtts","ws","wss","wx","wxs","ali","alis"].filter((b,k)=>m&&k%2===0?!1:typeof s[b]=="function")[0]}if(p.clean===!1&&!p.clientId)throw new Error("Missing clientId for unclean clients");p.protocol&&(p.defaultProtocol=p.protocol);function y(m){return p.servers&&((!m._reconnectCount||m._reconnectCount===p.servers.length)&&(m._reconnectCount=0),p.host=p.servers[m._reconnectCount].host,p.port=p.servers[m._reconnectCount].port,p.protocol=p.servers[m._reconnectCount].protocol?p.servers[m._reconnectCount].protocol:p.defaultProtocol,p.hostname=p.host,m._reconnectCount++),i("calling streambuilder for",p.protocol),s[p.protocol](m,p)}let f=new a.default(y,p);return f.on("error",()=>{}),f}function u(d,p,y=!0){return new Promise((f,m)=>{let b=l(d,p),k={connect:_=>{g(),f(b)},end:()=>{g(),f(b)},error:_=>{g(),b.end(),m(_)}};y===!1&&(k.close=()=>{k.error(new Error("Couldn't connect to server"))});function g(){Object.keys(k).forEach(_=>{b.off(_,k[_])})}Object.keys(k).forEach(_=>{b.on(_,k[_])})})}c.default=l}),Za=pe(c=>{le(),ue(),ce();var e=c&&c.__createBinding||(Object.create?function(y,f,m,b){b===void 0&&(b=m);var k=Object.getOwnPropertyDescriptor(f,m);(!k||("get"in k?!f.__esModule:k.writable||k.configurable))&&(k={enumerable:!0,get:function(){return f[m]}}),Object.defineProperty(y,b,k)}:function(y,f,m,b){b===void 0&&(b=m),y[b]=f[m]}),t=c&&c.__setModuleDefault||(Object.create?function(y,f){Object.defineProperty(y,"default",{enumerable:!0,value:f})}:function(y,f){y.default=f}),r=c&&c.__importStar||(function(){var y=function(f){return y=Object.getOwnPropertyNames||function(m){var b=[];for(var k in m)Object.prototype.hasOwnProperty.call(m,k)&&(b[b.length]=k);return b},y(f)};return function(f){if(f&&f.__esModule)return f;var m={};if(f!=null)for(var b=y(f),k=0;k<b.length;k++)b[k]!=="default"&&e(m,f,b[k]);return t(m,f),m}})(),a=c&&c.__exportStar||function(y,f){for(var m in y)m!=="default"&&!Object.prototype.hasOwnProperty.call(f,m)&&e(f,y,m)},n=c&&c.__importDefault||function(y){return y&&y.__esModule?y:{default:y}};Object.defineProperty(c,"__esModule",{value:!0}),c.ReasonCodes=c.KeepaliveManager=c.UniqueMessageIdProvider=c.DefaultMessageIdProvider=c.Store=c.MqttClient=c.connectAsync=c.connect=c.Client=void 0;var i=n(oi());c.MqttClient=i.default;var s=n(ss());c.DefaultMessageIdProvider=s.default;var o=n(yu());c.UniqueMessageIdProvider=o.default;var l=n(Zo());c.Store=l.default;var u=r(sh());c.connect=u.default,Object.defineProperty(c,"connectAsync",{enumerable:!0,get:function(){return u.connectAsync}});var d=n(ds());c.KeepaliveManager=d.default,c.Client=i.default,a(oi(),c),a(Rt(),c),a(Xo(),c);var p=sr();Object.defineProperty(c,"ReasonCodes",{enumerable:!0,get:function(){return p.ReasonCodes}})}),ah=pe(c=>{le(),ue(),ce();var e=c&&c.__createBinding||(Object.create?function(i,s,o,l){l===void 0&&(l=o);var u=Object.getOwnPropertyDescriptor(s,o);(!u||("get"in u?!s.__esModule:u.writable||u.configurable))&&(u={enumerable:!0,get:function(){return s[o]}}),Object.defineProperty(i,l,u)}:function(i,s,o,l){l===void 0&&(l=o),i[l]=s[o]}),t=c&&c.__setModuleDefault||(Object.create?function(i,s){Object.defineProperty(i,"default",{enumerable:!0,value:s})}:function(i,s){i.default=s}),r=c&&c.__importStar||(function(){var i=function(s){return i=Object.getOwnPropertyNames||function(o){var l=[];for(var u in o)Object.prototype.hasOwnProperty.call(o,u)&&(l[l.length]=u);return l},i(s)};return function(s){if(s&&s.__esModule)return s;var o={};if(s!=null)for(var l=i(s),u=0;u<l.length;u++)l[u]!=="default"&&e(o,s,l[u]);return t(o,s),o}})(),a=c&&c.__exportStar||function(i,s){for(var o in i)o!=="default"&&!Object.prototype.hasOwnProperty.call(s,o)&&e(s,i,o)};Object.defineProperty(c,"__esModule",{value:!0});var n=r(Za());c.default=n,a(Za(),c)});const lh=ah();const ch={inbound:"apps/{appId}/users/{userId}/messages/{conversationId}/clientadded",inboundUpdate:"apps/{appId}/users/{userId}/messages/{conversationId}/{messageId}/update",outbound:"apps/{appId}/outgoing/users/{userId}/messages/{conversationId}/outgoing",presence:"apps/{appId}/users/{userId}/presence/{clientId}",wildcardSubscribe:"apps/{appId}/users/{userId}/#"},uh=300,hh={templateId:"7",type:"link",isDeepLink:!0},fh={channelType:"group",channel:"chat21",requestChannel:"chat21",platform:"WEBSITE",medium:"CHATBUDDY"};class el{client=null;config;currentToken;clientId;appId;topics;messageHandlers=[];stateHandlers=[];statusUpdateHandlers=[];subscribedTopics=new Set;reconnectAttempt=0;maxReconnectAttempts;reconnectMaxDelayMs;disposed=!1;reconnectTimer=null;inboundRegex;inboundUpdateRegex;constructor(e){this.config=e,this.currentToken=e.jwtToken,this.appId=e.appId??"tilechat",this.clientId=e.clientId??`aikaara_${e.userId}_${Date.now()}`,this.topics={...ch,...e.topicTemplates??{}},this.maxReconnectAttempts=e.maxReconnectAttempts??10,this.reconnectMaxDelayMs=e.reconnectMaxDelayMs??3e4,this.inboundRegex=this.buildTopicRegex(this.topics.inbound,["conversationId"]),this.inboundUpdateRegex=this.buildTopicRegex(this.topics.inboundUpdate,["conversationId","messageId"])}async connect(){if(this.disposed)return;const e=this.renderPresenceTopic(),t=this.config.presencePayloadDisconnected??{disconnected:!0},r={clientId:this.clientId,username:this.config.mqttUsername??"JWT",password:this.currentToken,clean:!0,reconnectPeriod:0,connectTimeout:this.config.connectTimeoutMs??1e4,keepalive:this.config.keepAliveSec??60,protocolVersion:this.config.protocolVersion??3,protocolId:this.config.protocolId??"MQIsdp"};return this.config.enablePresence!==!1&&(r.will={topic:e,payload:JSON.stringify(t),qos:0,retain:!1}),new Promise((a,n)=>{this.client=lh.connect(this.config.mqttEndpoint,r),this.client.on("connect",()=>{if(this.reconnectAttempt=0,this.debugLog("CONNECT",{endpoint:this.config.mqttEndpoint,clientId:this.clientId}),this.notifyStateChange(!0),this.config.enablePresence!==!1){const i=this.config.presencePayloadConnected??{connected:!0};this.client.publish(e,JSON.stringify(i),{qos:0,retain:!1}),this.debugLog("PUBLISH",{topic:e,payload:i})}a()}),this.client.on("message",(i,s)=>{this.dispatchInbound(i,s)}),this.client.on("close",()=>{this.debugLog("CLOSE",{}),this.notifyStateChange(!1),this.disposed||this.scheduleReconnect()}),this.client.on("error",i=>{this.debugLog("ERROR",{message:i.message}),this.reconnectAttempt===0&&n(i)}),this.client.on("packetsend",i=>{(i.cmd==="subscribe"||i.cmd==="unsubscribe"||i.cmd==="pingreq")&&this.debugLog(i.cmd.toUpperCase(),{topic:i.topic,packetId:i.messageId})})})}debugLog(e,t){if(!this.config.debug)return;const r={};for(const[a,n]of Object.entries(t))typeof n=="string"&&n.length>200?r[a]=`${n.slice(0,200)}…(${n.length})`:r[a]=n;console.info(`[tiledesk-mqtt] ${e}`,r)}subscribeWildcard(){if(!this.client)return;const e=this.renderTemplate(this.topics.wildcardSubscribe,{});this.subscribedTopics.has(e)||(this.client.subscribe(e,{qos:this.config.subscribeQos??2}),this.subscribedTopics.add(e))}subscribeToConversation(e){if(!this.client)return;if(this.config.wildcardSubscribe){this.subscribeWildcard();return}const t=this.renderInboundTopic(e);this.subscribedTopics.has(t)||(this.client.subscribe(t,{qos:this.config.subscribeQos??2}),this.subscribedTopics.add(t))}unsubscribeFromConversation(e){if(!this.client)return;const t=this.renderInboundTopic(e);this.subscribedTopics.has(t)&&(this.client.unsubscribe(t),this.subscribedTopics.delete(t))}publishMessage(e,t,r={}){if(!this.client)return;const a=this.buildOutgoingEnvelope(e,{text:t,type:"text",...r});this.publishEnvelope(e,a)}publishFileMessage(e,t){if(!this.client)return;const r={...hh,...this.config.fileTemplate??{},...dh(t)},a={metadata:{contentType:"300",templateId:r.templateId,payload:{...r.headerImgSrc?{headerImgSrc:r.headerImgSrc}:{},elements:[{description:t.description??t.fileName,action:{url:t.fileUrl,type:r.type??"link",isDeepLink:r.isDeepLink??!0}}]},...t.metadata??{}}},n={fileMessage:!0,...t.cloudFileId?{cloudFileId:t.cloudFileId}:{},...t.attributes??{}},i=this.buildOutgoingEnvelope(e,{text:JSON.stringify(a),type:"html",attributes:n,metadata:a.metadata});this.publishEnvelope(e,i)}publishRaw(e,t){this.client&&this.publishEnvelope(e,t)}publishReadReceipt(e,t,r=uh){if(!this.client)return;const a=this.renderTemplate(this.topics.inboundUpdate,{conversationId:e,messageId:t});this.client.publish(a,JSON.stringify({status:r}),{qos:this.config.publishQos??0,retain:!1})}publishChatInitiated(e,t={}){if(!this.client)return;const r=this.buildOutgoingEnvelope(e,{text:"CHAT_INITIATED",type:"text",attributes:{subtype:"info",...t}});this.publishEnvelope(e,r)}onMessage(e){return this.messageHandlers.push(e),()=>{this.messageHandlers=this.messageHandlers.filter(t=>t!==e)}}onStateChange(e){return this.stateHandlers.push(e),()=>{this.stateHandlers=this.stateHandlers.filter(t=>t!==e)}}onStatusUpdate(e){return this.statusUpdateHandlers.push(e),()=>{this.statusUpdateHandlers=this.statusUpdateHandlers.filter(t=>t!==e)}}disconnect(){this.disposed=!0,this.reconnectTimer&&(clearTimeout(this.reconnectTimer),this.reconnectTimer=null),this.client&&(this.subscribedTopics.forEach(e=>this.client.unsubscribe(e)),this.subscribedTopics.clear(),this.client.end(!0),this.client=null),this.messageHandlers=[],this.stateHandlers=[],this.statusUpdateHandlers=[]}get isConnected(){return this.client?.connected??!1}async scheduleReconnect(){if(this.reconnectAttempt>=this.maxReconnectAttempts||this.disposed)return;const e=Math.min(1e3*Math.pow(2,this.reconnectAttempt),this.reconnectMaxDelayMs);this.reconnectAttempt++,this.reconnectTimer=setTimeout(async()=>{if(!this.disposed){if(this.config.tokenProvider)try{this.currentToken=await this.config.tokenProvider()}catch{}try{await this.connect();const t=[...this.subscribedTopics];this.subscribedTopics.clear(),t.forEach(r=>{this.client&&(this.client.subscribe(r,{qos:this.config.subscribeQos??2}),this.subscribedTopics.add(r))})}catch{}}},e)}notifyStateChange(e){this.stateHandlers.forEach(t=>t(e))}dispatchInbound(e,t){const r=t.toString();let a=null;try{a=JSON.parse(r)}catch{this.debugLog("RECV (non-json)",{topic:e,raw:r});return}if(!a)return;this.debugLog("RECV",{topic:e,sender:a.sender,type:a.type,contentType:a.metadata?.contentType,templateId:a.metadata?.templateId,messageId:a.message_id,text:typeof a.text=="string"?a.text:void 0});const n=e.match(this.inboundUpdateRegex);if(n){const l=n.groups?.conversationId??"",u=n.groups?.messageId??"",d=typeof a.status=="number"?a.status:Number(a.status??0),p={conversationId:l,messageId:u,status:d,raw:a};this.statusUpdateHandlers.forEach(y=>y(p)),this.messageHandlers.forEach(y=>y(a,{topic:e,conversationId:l,messageId:u,kind:"update"}));return}const i=e.match(this.inboundRegex),s=i?.groups?.conversationId,o={topic:e,conversationId:s,messageId:typeof a.message_id=="string"?a.message_id:void 0,kind:i?"clientadded":"unknown"};this.messageHandlers.forEach(l=>l(a,o))}buildOutgoingEnvelope(e,t){const r={...fh,...this.config.messageDefaults??{}},a=this.config.senderFullname??this.config.userName??this.config.userId,n=this.config.recipientFullnameResolver?.(e),i={projectId:this.config.projectId,...r.departmentId?{departmentId:r.departmentId}:{},...this.config.userName?{userFullname:this.config.userName}:{},...r.channel?{channel:r.channel}:{},...r.requestChannel?{request_channel:r.requestChannel}:{},...r.attributes??{},...t.attributes??{}};return{type:"text",sender:this.config.userId,sender_fullname:a,senderFullname:a,recipient:e,...n?{recipient_fullname:n}:{},...r.channelType?{channel_type:r.channelType}:{},...r.medium?{medium:r.medium}:{},...r.platform?{platform:r.platform}:{},app_id:this.appId,timestamp:Date.now(),...t,attributes:i}}publishEnvelope(e,t){if(!this.client)return;const r=this.renderOutboundTopic(e);this.client.publish(r,JSON.stringify(t),{qos:this.config.publishQos??0,retain:this.config.publishRetain??!1}),this.debugLog("SEND",{topic:r,type:t.type,sender:t.sender,text:typeof t.text=="string"?t.text:void 0,contentType:t.metadata?.contentType,templateId:t.metadata?.templateId})}renderInboundTopic(e){return this.renderTemplate(this.topics.inbound,{conversationId:e})}renderOutboundTopic(e){return this.renderTemplate(this.topics.outbound,{conversationId:e})}renderPresenceTopic(){return this.renderTemplate(this.topics.presence,{})}renderTemplate(e,t){const r={appId:this.appId,userId:this.config.userId,projectId:this.config.projectId,clientId:this.clientId,...t};return e.replace(/\{(\w+)\}/g,(a,n)=>r[n]??"")}buildTopicRegex(e,t){const r=e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&").replace(/\\\{(\w+)\\\}/g,(a,n)=>{const i={appId:this.appId,userId:this.config.userId,projectId:this.config.projectId,clientId:this.clientId};if(t.includes(n))return`(?<${n}>[^/]+)`;const s=i[n];return s?s.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"):"[^/]+"});return new RegExp(`^${r}$`)}}function dh(c){const e={};for(const[t,r]of Object.entries(c))r!==void 0&&(e[t]=r);return e}function tl(c,e){return(c.sender??"").toString()===e}function rl(c,e){const t=(c.sender??"").toString(),r=e.systemSenders??["metadata","system"],a=e.botSenderPrefix??"bot_";return t?t===e.userId?"user":t.startsWith(a)?"assistant":r.includes(t)?"system":"agent":"system"}function to(c){const e={raw:c},t=c.metadata;if(t&&typeof t=="object"&&(typeof t.contentType=="string"&&(e.contentType=t.contentType),typeof t.templateId=="string"&&(e.templateId=t.templateId),t.payload!==void 0&&(e.payload=t.payload)),typeof c.text=="string"&&c.text.trim().startsWith("{"))try{const r=JSON.parse(c.text);typeof r.message=="string"&&(e.innerMessage=r.message);const a=r.metadata;a&&typeof a=="object"&&(!e.contentType&&typeof a.contentType=="string"&&(e.contentType=a.contentType),!e.templateId&&typeof a.templateId=="string"&&(e.templateId=a.templateId),e.payload===void 0&&a.payload!==void 0&&(e.payload=a.payload))}catch{}return e}function nl(c){const e=to(c);if(e.contentType!=="300")return null;const t=e.payload,r=t&&Array.isArray(t.elements)?t.elements:null;if(!r||r.length===0)return null;const a=r[0],n=a.action,i=n&&typeof n.url=="string"?n.url:void 0,s=typeof a.description=="string"?a.description:void 0,o=c.attributes,l=o&&typeof o.cloudFileId=="string"?o.cloudFileId:void 0;return!i&&!s?null:{fileName:s,fileUrl:i,cloudFileId:l,templateId:e.templateId}}function il(c,e,t){const r=rl(c,t),a=to(c),n=nl(c);let i="";a.innerMessage?i=a.innerMessage:typeof c.text=="string"&&(c.text.trim().startsWith("{")?a.contentType!=="300"&&(i=c.text):i=c.text);const s=typeof c.message_id=="string"?c.message_id:`td_${Date.now()}_${Math.random().toString(36).slice(2,8)}`,o=typeof c.timestamp=="number"?new Date(c.timestamp).toISOString():new Date().toISOString(),l=r==="assistant"?"assistant":r==="agent"?"agent":r==="system"?"system":"user",u=typeof c.status=="number"?ph(c.status):"delivered",d={id:s,externalId:s,conversationId:e,role:l,content:i,createdAt:o,status:u,metadata:{sender:c.sender,sender_fullname:c.sender_fullname??c.senderFullname,app_id:c.app_id,attributes:c.attributes}};return a.contentType&&(d.template={contentType:a.contentType,templateId:a.templateId,payload:a.payload}),n?.fileUrl&&(d.attachments=[{fileName:n.fileName??"file",fileUrl:n.fileUrl,cloudFileId:n.cloudFileId}]),{message:d,template:a}}function ph(c){return c<0?"error":c>=250?"read":c>=150?"delivered":"sent"}class ol extends Zt{connection=null;tiledesk=null;api;messageStore;conversationManager;subscription=null;config;mode;uploadAdapter;historyAdapter;tiledeskUnsubs=[];constructor(e,t){super(),this.config=e,this.mode=e.transport??"aikaara",this.uploadAdapter=t?.uploadAdapter??null,this.historyAdapter=t?.historyAdapter??null,this.api=new yo(e.baseUrl,e.userToken,e.apiKey,e.authToken),this.messageStore=new vo,this.conversationManager=new So(e.conversationId),this.usesAikaara()&&(this.connection=new bo(e),this.connection.on("connection:state",r=>{this.emit("connection:state",r),this.config.onConnectionStateChange?.(r)}),this.connection.on("error",r=>{this.emit("error",r),this.config.onError?.(r)})),this.usesTiledesk()&&this.initTiledeskTransport()}usesAikaara(){return this.mode==="aikaara"||this.mode==="dual"}usesTiledesk(){return this.mode==="tiledesk"||this.mode==="dual"}initTiledeskTransport(){const e=this.config.tiledesk,t=this.config.tiledeskIdentity;if(!e)throw new Error("AikaaraChatClient: tiledesk transport requires `config.tiledesk` (TiledeskTransportConfig)");if(!t?.userId)throw new Error("AikaaraChatClient: tiledesk transport requires `config.tiledeskIdentity.userId`");this.tiledesk=new el({...e,userId:t.userId,userName:t.userName??e.userName,senderFullname:t.senderFullname??e.senderFullname,messageDefaults:{...e.messageDefaults,departmentId:t.departmentId??e.messageDefaults?.departmentId}}),this.tiledeskUnsubs.push(this.tiledesk.onStateChange(r=>{const a=r?"connected":"disconnected";this.emit("connection:state",a),this.config.onConnectionStateChange?.(a)})),this.tiledeskUnsubs.push(this.tiledesk.onMessage((r,a)=>this.handleTiledeskMessage(r,a))),this.tiledeskUnsubs.push(this.tiledesk.onStatusUpdate(r=>this.handleTiledeskStatusUpdate(r)))}async connect(){if(this.usesAikaara()&&this.connection){if(await this.connection.connect(),!this.conversationManager.conversationId){const e=await this.api.createConversation({systemPromptId:this.config.systemPromptId,channel:this.config.channel||"widget",extUid:this.config.extUid});this.conversationManager.conversationId=String(e.id)}this.subscription=await this.connection.subscribeToConversation(this.conversationManager.conversationId),this.subscription.onReceived(e=>{this.handleBroadcast(e)}),await this.loadHistory()}if(this.usesTiledesk()&&this.tiledesk){await this.tiledesk.connect(),this.config.tiledesk?.wildcardSubscribe??!0?this.tiledesk.subscribeWildcard():this.conversationManager.conversationId&&this.tiledesk.subscribeToConversation(this.conversationManager.conversationId);const t=this.conversationManager.conversationId;if(t){const r=await this.hydrateTiledeskHistory(t),a=this.config.tiledesk?.autoInitiateOnEmpty??!0;r==="empty"&&a&&this.tiledesk.publishChatInitiated(t,this.config.tiledesk?.chatInitiatedAttributes??{})}}}async hydrateTiledeskHistory(e){if(!this.historyAdapter)return"unknown";const t=this.config.tiledeskIdentity?.userId??"";let r;try{r=await this.historyAdapter.fetchMessages(e,{userId:t,appId:this.config.tiledesk?.appId,projectId:this.config.tiledesk?.projectId})}catch(s){return this.config.onError?.(s instanceof Error?s:new Error(String(s))),"unknown"}if(!r.length)return"empty";const a=r.map(s=>il(s,e,{userId:t}).message).sort((s,o)=>new Date(s.createdAt).getTime()-new Date(o.createdAt).getTime()),n=this.messageStore.messages,i=[...a,...n.filter(s=>!a.some(o=>o.externalId&&o.externalId===s.externalId))];if(this.messageStore.setMessages(i),this.config.onMessage)for(const s of a)try{this.config.onMessage(s)}catch(o){console.warn("[aikaara-chat-sdk] onMessage threw on history replay",o)}return"has-history"}async sendMessage(e,t={}){const r=this.conversationManager.conversationId;if(!r)throw new Error("No active conversation");const a=this.messageStore.addOptimistic("user",e,r);this.emit("message:sent",a),this.config.onMessage?.(a);const n={};if(t.attributes&&(n.attributes=t.attributes),t.metadata&&(n.metadata=t.metadata),this.mode==="tiledesk"&&this.tiledesk){this.tiledesk.publishMessage(r,e,n);return}this.mode==="dual"&&this.tiledesk&&this.tiledesk.publishMessage(r,e,n),this.usesAikaara()&&this.connection&&this.connection.sendMessage(r,e)}async sendFile(e,t){if(!this.uploadAdapter)throw new Error("AikaaraChatClient: sendFile requires an UploadAdapter");const r=this.conversationManager.conversationId;if(!r)throw new Error("No active conversation");const a=await this.uploadAdapter.upload(e,{conversationId:r,userId:this.config.tiledeskIdentity?.userId??this.config.userToken,projectId:this.config.tiledesk?.projectId,appId:this.config.tiledesk?.appId});if(this.usesTiledesk()&&this.tiledesk){const n={fileName:a.fileName,fileUrl:a.url,cloudFileId:a.cloudFileId};this.tiledesk.publishFileMessage(r,n)}t?.caption&&await this.sendMessage(t.caption)}initiateTiledeskChat(e={}){const t=this.conversationManager.conversationId;!this.tiledesk||!t||this.tiledesk.publishChatInitiated(t,e)}markTiledeskRead(e){const t=this.conversationManager.conversationId;!this.tiledesk||!t||this.tiledesk.publishReadReceipt(t,e)}setUploadAdapter(e){this.uploadAdapter=e}async sendUserEvent(e,t,r){const a=this.conversationManager.conversationId;if(!a)throw new Error("No active conversation");this.connection&&this.connection.sendUserEvent(a,e,t,r)}async loadHistory(){const e=this.conversationManager.conversationId;if(!e)return[];try{const t=await this.api.getMessages(e);return this.messageStore.setMessages(t),t}catch{return[]}}get messages(){return this.messageStore.messages}get conversationId(){return this.conversationManager.conversationId}get isConnected(){if(this.mode==="tiledesk")return this.tiledesk?.isConnected??!1;if(this.mode==="dual"){const e=this.connection?.connectionState==="connected",t=this.tiledesk?.isConnected??!1;return e&&t}return this.connection?.connectionState==="connected"}async setContext(e){const t=this.conversationManager.conversationId;t&&await this.api.updateContext(t,{current_page:e.currentPage,entity_type:e.entityType,entity_id:e.entityId,project_id:e.projectId,available_routes:e.availableRoutes,custom_context:e.custom})}async disconnect(){this.subscription&&(this.subscription=null),this.connection&&await this.connection.disconnect(),this.tiledesk&&(this.tiledeskUnsubs.forEach(e=>e()),this.tiledeskUnsubs=[],this.tiledesk.disconnect(),this.tiledesk=null)}handleTiledeskMessage(e,t){if(t.kind==="update")return;const r=t.conversationId??this.conversationManager.conversationId;if(!r)return;const a=this.config.tiledeskIdentity?.userId??"",{message:n,template:i}=il(e,r,{userId:a,systemSenders:this.config.tiledesk?.messageDefaults?.attributes?.systemSenders});if(this.mode==="dual"&&n.role==="assistant")return;if(tl(e,a)){const l=this.messageStore.reconcileOptimistic(n);if(l){this.emit("message:updated",l);return}}const{message:s,deduped:o}=this.messageStore.upsertRemoteMessage(n);if(o?this.emit("message:updated",s):(this.emit("message:received",s),this.config.onMessage?.(s)),i.contentType){const l={messageId:s.id,conversationId:r,role:n.role==="tool"?"system":n.role,contentType:i.contentType,templateId:i.templateId,payload:i.payload,innerMessage:i.innerMessage,raw:e};this.config.onTemplateMessage?.(l)}}handleTiledeskStatusUpdate(e){e.status>=250?this.messageStore.updateMessageStatus(e.messageId,"read"):e.status>=150&&this.messageStore.updateMessageStatus(e.messageId,"delivered")}parseActionResult(e){try{const t=typeof e=="string"?JSON.parse(e):e;if(!t||typeof t!="object")return;t.navigate_to?this.emit("action:navigate",t):t.action==="edit_entity"?this.emit("action:edit_entity",t):t.action==="save_entity"?this.emit("action:save_entity",t):t.action==="test_tool"&&this.emit("action:test_tool",t)}catch{}}handleBroadcast(e){const t=this.conversationManager.conversationId;switch(e.type){case"status":{const r=e.status;this.emit("status",r),this.config.onStatusChange?.(r),r==="processing"&&this.emit("typing:start",void 0);break}case"error":{const r=new Error(e.message||"Unknown error");this.emit("error",r),this.config.onError?.(r);break}case"message_start":{if(e.role==="assistant"){const r=this.messageStore.addStreamingMessage(t);this.emit("stream:start",{messageId:r.id}),this.emit("typing:start",void 0)}break}case"message_update":{const r=e.delta||"",a=e.content||"";a?this.messageStore.updateStreaming(a):r&&this.messageStore.appendToStreaming(r);const n=this.messageStore.streamingContent;this.emit("stream:update",{delta:r,content:n}),this.config.onStreamUpdate?.(r,n);break}case"message_end":{const r=e.usage,a=this.messageStore.finalizeStreaming(r?{tokensInput:r.tokens_input||0,tokensOutput:r.tokens_output||0}:void 0);this.emit("typing:stop",void 0),a&&(this.emit("stream:end",{messageId:a.id,usage:r?{tokensInput:r.tokens_input||0,tokensOutput:r.tokens_output||0}:void 0}),this.emit("message:received",a),this.config.onMessage?.(a));break}case"message_queued":{const r=this.messageStore.messages.findLast(a=>a.status==="sending");r&&this.messageStore.confirmOptimistic(r.id);break}case"tool_execution_start":{this.emit("tool:start",{toolName:e.tool_name||"",args:e.args||{}}),this.emit("status",e.type);break}case"tool_execution_end":{this.emit("tool:end",{toolName:e.tool_name||"",result:e.result,isError:!!e.is_error}),this.emit("status",e.type),this.parseActionResult(e.result);break}case"tool_execution_update":case"agent_start":case"agent_end":case"turn_start":case"turn_end":case"auto_retry_start":case"auto_retry_end":case"cancelled":this.emit("status",e.type);break}}}class gh extends Zt{registration=null;pendingEdits=[];constructor(e){super(),this.setupListeners(e)}registerForm(e){this.registration=e;const t=this.pendingEdits.filter(r=>r.entity_type===e.entityType&&String(r.entity_id)===String(e.entityId));if(t.length>0){for(const r of t)e.onFieldUpdate(r.fields),this.emit("edit:applied",{entityType:r.entity_type,entityId:r.entity_id,fields:r.fields});this.pendingEdits=this.pendingEdits.filter(r=>!(r.entity_type===e.entityType&&String(r.entity_id)===String(e.entityId)))}}unregisterForm(e,t){this.registration?.entityType===e&&String(this.registration?.entityId)===String(t)&&(this.registration=null)}get currentForm(){return this.registration}pushFieldUpdates(e,t,r){this.registration&&this.registration.entityType===e&&String(this.registration.entityId)===String(t)?(this.registration.onFieldUpdate(r),this.emit("edit:applied",{entityType:e,entityId:t,fields:r})):(this.pendingEdits.push({action:"edit_entity",entity_type:e,entity_id:t,fields:r}),this.emit("edit:pending",{entityType:e,entityId:t,fields:r}))}async requestSave(){if(!this.registration)return{success:!1,error:"No form registered"};try{return await this.registration.onSave(),this.emit("save:success",{entityType:this.registration.entityType,entityId:this.registration.entityId}),{success:!0}}catch(e){const t=e instanceof Error?e.message:"Save failed";return this.emit("save:error",{entityType:this.registration.entityType,entityId:this.registration.entityId,error:t}),{success:!1,error:t}}}async requestTest(e){if(!this.registration?.onTest)return{success:!1,error:"Current form does not support testing"};try{return await this.registration.onTest(e),{success:!0}}catch(t){return{success:!1,error:t instanceof Error?t.message:"Test failed"}}}setupListeners(e){e.on("action:edit_entity",t=>{this.pushFieldUpdates(t.entity_type,t.entity_id,t.fields)}),e.on("action:save_entity",t=>{this.requestSave()}),e.on("action:test_tool",t=>{this.emit("test:triggered",{toolId:t.tool_id,parameters:t.parameters}),this.requestTest(t.parameters)})}}const sl={txt:"text/plain",pdf:"application/pdf",jpg:"image/jpeg",jpeg:"image/jpeg",png:"image/png",csv:"text/csv",doc:"application/msword",json:"application/json"};function mh(c){const e=c.lastIndexOf(".");return e<0||e===c.length-1?"":c.slice(e+1).toLowerCase()}function bh(c,e,t){const r=mh(c.name||"");if(r&&e&&e[r])return e[r];const a=c.type;return a&&a.trim().length>0?a:r&&sl[r]?sl[r]:t}function ro(c,e){return c.replace(/\{(\w+)\}/g,(t,r)=>e[r]??"")}function yh(c,e){const t=e.split(".");let r=c;for(const a of t)if(r&&typeof r=="object"&&a in r)r=r[a];else return"";return typeof r=="string"?r:""}function al(c){const e=c.signedUrlPath??"data.s3SignedUrl";return{async upload(t,r){const a=t.name||`upload-${Date.now()}`,n={fileName:a,userId:r.userId,requestId:r.conversationId,conversationId:r.conversationId},i=c.authHeader?await c.authHeader():void 0,s={accept:"application/json",...c.extraHeaders??{},...i?{authorization:i}:{}},o=ro(c.signEndpoint.includes("{")?c.signEndpoint:`${c.signEndpoint}?fileName={fileName}`,n),l=await fetch(o,{method:c.signMethod??"GET",headers:s});if(!l.ok)throw new Error(`Sign request failed: ${l.status}`);const u=await l.json().catch(()=>({})),d=yh(u,e);if(!d)throw new Error(`Sign response missing path "${e}"`);const p=bh(t,c.contentTypeMap,c.contentTypeFallback??"application/octet-stream"),y=c.s3HostRewrite?d.replace(/^https:\/\/[^/]+/i,c.s3HostRewrite):d,f=await fetch(y,{method:"PUT",headers:{"content-type":p},body:t});if(!f.ok){const b=await f.text().catch(()=>"");throw new Error(`S3 PUT failed: ${f.status} ${b.slice(0,200)}`)}if(c.registerEndpoint){const b=JSON.parse(ro(JSON.stringify(c.registerBody??{}),n)),k=await fetch(c.registerEndpoint,{method:"POST",headers:{...s,"content-type":"application/json"},body:JSON.stringify(b)});if(!k.ok){const g=await k.text().catch(()=>"");throw new Error(`Register failed: ${k.status} ${g.slice(0,200)}`)}}return{url:c.viewerTemplate?ro(c.viewerTemplate,n):d.split("?")[0],fileName:a,contentType:p,byteSize:t.size,meta:{requestId:r.conversationId}}}}}function no(c){return{async upload(e,t){const r=new FormData,a=c.fieldName??"file";r.append(a,e,e.name);const n=typeof c.extraFields=="function"?c.extraFields(t):c.extraFields;if(n)for(const[p,y]of Object.entries(n))r.append(p,y);r.append("conversationId",t.conversationId),r.append("userId",t.userId),t.projectId&&r.append("projectId",t.projectId);const i=typeof c.headers=="function"?await c.headers():c.headers??{},s=await fetch(c.endpoint,{method:c.method??"POST",body:r,headers:i,credentials:c.credentials});if(!s.ok)throw new Error(`Upload failed: ${s.status} ${s.statusText}`);const o=await s.json().catch(()=>({}));if(c.parseResponse)return c.parseResponse(o,t);const l=o,u=l.url??l.fileUrl??l.publicUrl,d=l.fileName??l.name??e.name;if(!u)throw new Error('Upload response missing "url" / "fileUrl" / "publicUrl"');return{url:u,fileName:d,cloudFileId:typeof l.cloudFileId=="string"?l.cloudFileId:void 0,relativePath:typeof l.path=="string"?l.path:void 0,contentType:typeof l.contentType=="string"?l.contentType:void 0,byteSize:typeof l.byteSize=="number"?l.byteSize:void 0,meta:l}}}}const vh="/tilechat/{userId}/conversations/{conversationId}/messages?pageSize={pageSize}";function ll(c){const e=c.apiBase.replace(/\/$/,""),t=c.pageSize??200,r=c.pathTemplate??vh;return{async fetchMessages(a,n){const i=r.replace("{userId}",encodeURIComponent(n.userId)).replace("{conversationId}",encodeURIComponent(a)).replace("{appId}",encodeURIComponent(n.appId??"tilechat")).replace("{projectId}",encodeURIComponent(n.projectId??"")).replace("{pageSize}",String(t)),s=i.startsWith("http")?i:`${e}${i.startsWith("/")?i:`/${i}`}`,o={accept:"application/json","content-type":"application/json",...c.extraHeaders??{}};if(c.getToken){const p=await c.getToken();p&&(o.authorization=p)}const l=await fetch(s,{method:"GET",headers:o}),u=await l.json().catch(()=>null);if(c.parseResponse&&u)return c.parseResponse(u);const d=u;if(d&&Array.isArray(d.result))return d.result;if(!l.ok)throw new Error(`History fetch failed: ${l.status} ${l.statusText}`);return[]}}}class wh{client;panel;bubble;header;messageList;input;errorBanner;isOpen=!1;isEmbed=!1;constructor(e,t,r){this.client=new ol(e,{uploadAdapter:r?.uploadAdapter,historyAdapter:r?.historyAdapter}),this.isEmbed=e.display==="embed",this.bubble=t.querySelector("aikaara-chat-bubble"),this.panel=t.querySelector(".aikaara-panel"),this.header=t.querySelector("aikaara-chat-header"),this.messageList=t.querySelector("aikaara-message-list"),this.input=t.querySelector("aikaara-chat-input"),this.errorBanner=t.querySelector("aikaara-error-banner"),e.welcomeMessage&&this.messageList.setWelcomeMessage(e.welcomeMessage),e.showTimestamps!==void 0&&this.messageList.setShowTimestamps(e.showTimestamps),(e.linkHandlers||e.getLinkBearer)&&this.messageList.setLinkConfig(e.linkHandlers??[],e.getLinkBearer),this.wireEvents()}async connect(){try{await this.client.connect(),this.messageList.renderMessages(this.client.messages)}catch{this.errorBanner.show("Failed to connect. Retrying...",5e3)}}async disconnect(){await this.client.disconnect()}wireEvents(){this.bubble?.addEventListener("toggle",()=>{this.togglePanel()}),this.isEmbed||this.header.addEventListener("header-close",()=>{this.togglePanel(!1)}),this.input.addEventListener("send",(e=>{this.handleSend(e.detail.content)})),this.input.addEventListener("file-pick",(e=>{this.handleFile(e.detail.file)})),this.client.on("message:sent",e=>{this.messageList.addMessage(e)}),this.client.on("stream:start",()=>{this.messageList.removeTypingIndicator();const e=this.client.messages[this.client.messages.length-1];e&&this.messageList.addMessage(e)}),this.client.on("stream:update",({content:e})=>{this.messageList.updateStreamingContent(e)}),this.client.on("stream:end",()=>{this.messageList.finalizeStreaming()}),this.client.on("typing:start",()=>{const e=this.client.messages,t=e[e.length-1];(!t||t.status!=="streaming")&&this.messageList.showTypingIndicator()}),this.client.on("typing:stop",()=>{this.messageList.removeTypingIndicator()}),this.client.on("connection:state",e=>{this.header.setStatus(e),e==="connected"?(this.errorBanner.hide(),this.input.disabled=!1):e==="reconnecting"?(this.errorBanner.show("Connection lost. Reconnecting..."),this.input.disabled=!0):e==="disconnected"&&(this.input.disabled=!0)}),this.client.on("error",e=>{this.errorBanner.show(e.message,5e3)}),this.client.on("message:received",e=>{this.messageList.upsertMessage(e)}),this.client.on("message:updated",e=>{this.messageList.upsertMessage(e)}),this.messageList.addEventListener("message-action",e=>{const t=e.detail;if(!t?.text)return;const r=this.client.config.templateActionAttributes??{},a=t.attributes?.action??{},n={...t.attributes,action:{...r,...a}};this.handleSend(t.text,n)})}async handleSend(e,t){try{await this.client.sendMessage(e,t?{attributes:t}:void 0)}catch{this.errorBanner.show("Failed to send message",3e3)}}async handleFile(e){this.input.uploading=!0;try{await this.client.sendFile(e)}catch(t){this.errorBanner.show(t instanceof Error?`Upload failed: ${t.message}`:"Upload failed",4e3)}finally{this.input.uploading=!1}}sendUserEvent(e,t,r){this.client.sendUserEvent(e,t,r)}getClient(){return this.client}togglePanel(e){this.isEmbed||(this.isOpen=e!==void 0?e:!this.isOpen,this.isOpen?(this.panel.removeAttribute("hidden"),requestAnimationFrame(()=>{this.panel.classList.remove("entering"),this.panel.classList.add("visible"),this.input.focus()})):(this.panel.classList.remove("visible"),this.panel.classList.add("entering"),setTimeout(()=>{this.panel.setAttribute("hidden","")},200)))}}class cl extends HTMLElement{shadow;controller=null;_config={};static get observedAttributes(){return["base-url","ws-url","user-token","api-key","title","subtitle","theme","primary-color","position","width","height","placeholder","welcome-message","avatar-url","display"]}constructor(){super(),this.shadow=this.attachShadow({mode:"open"})}connectedCallback(){this.render(),this.initController()}disconnectedCallback(){this.controller?.disconnect()}attributeChangedCallback(e,t,r){t!==r&&this.controller&&(this.render(),this.initController())}configure(e){this._config={...this._config,...e}}getConfig(){return{baseUrl:this.getAttribute("base-url")||this._config.baseUrl||"",wsUrl:this.getAttribute("ws-url")||this._config.wsUrl,userToken:this.getAttribute("user-token")||this._config.userToken||"",apiKey:this.getAttribute("api-key")||this._config.apiKey,title:this.getAttribute("title")||this._config.title||"Chat",subtitle:this.getAttribute("subtitle")||this._config.subtitle,theme:this.getAttribute("theme")||this._config.theme||Xl,primaryColor:this.getAttribute("primary-color")||this._config.primaryColor||go,position:this.getAttribute("position")||this._config.position||Jl,width:Number(this.getAttribute("width"))||this._config.width||Vl,height:Number(this.getAttribute("height"))||this._config.height||Gl,fontFamily:this._config.fontFamily||Ql,borderRadius:this._config.borderRadius??Yl,placeholder:this.getAttribute("placeholder")||this._config.placeholder||mo,welcomeMessage:this.getAttribute("welcome-message")||this._config.welcomeMessage,avatarUrl:this.getAttribute("avatar-url")||this._config.avatarUrl,showTimestamps:this._config.showTimestamps??!0,persistConversation:this._config.persistConversation??!0,showHeader:this._config.showHeader??!0,hideSystemMessages:this._config.hideSystemMessages,timestampFormat:this._config.timestampFormat,input:this._config.input,templateLayout:this._config.templateLayout,showBubble:this._config.showBubble??!0,display:(this.getAttribute("display")||this._config.display)??"popup",offset:this._config.offset||Zl,conversationId:this._config.conversationId,systemPromptId:this._config.systemPromptId,channel:this._config.channel,extUid:this._config.extUid,transport:this._config.transport,tiledesk:this._config.tiledesk,tiledeskIdentity:this._config.tiledeskIdentity,onMessage:this._config.onMessage,onStatusChange:this._config.onStatusChange,onError:this._config.onError,onStreamUpdate:this._config.onStreamUpdate,onConnectionStateChange:this._config.onConnectionStateChange,onTemplateMessage:this._config.onTemplateMessage,themeTokens:this._config.themeTokens,linkHandlers:this._config.linkHandlers,getLinkBearer:this._config.getLinkBearer}}propagateThemeToDocument(e,t,r,a){if(typeof document>"u")return;const n=document.documentElement,i=(s,o)=>{o!==void 0&&o!==""&&n.style.setProperty(`--aikaara-${s}`,o)};i("primary",e?.primary??t),i("primary-hover",e?.primaryHover),i("primary-contrast",e?.primaryContrast),i("surface",e?.surface),i("surface-muted",e?.surfaceMuted),i("border",e?.border),i("text",e?.text),i("text-muted",e?.textMuted),i("font",e?.font??a),i("radius",e?.radius!=null?`${e.radius}px`:r!=null?`${r}px`:void 0),i("bubble-radius",e?.bubbleRadius!=null?`${e.bubbleRadius}px`:void 0),i("button-radius",e?.buttonRadius!=null?`${e.buttonRadius}px`:void 0),i("user-bubble-bg",e?.userBubbleBg),i("user-bubble-text",e?.userBubbleText),i("bot-bubble-bg",e?.botBubbleBg),i("bot-bubble-text",e?.botBubbleText),i("modal-width",e?.modalWidth),i("modal-height",e?.modalHeight),i("modal-max-width",e?.modalMaxWidth),i("modal-max-height",e?.modalMaxHeight),i("modal-padding",e?.modalPadding)}themeVars(e){if(!e)return"";const t=a=>typeof a=="number"?`${a}px`:void 0,r={primary:e.primary,"primary-hover":e.primaryHover,"primary-contrast":e.primaryContrast,surface:e.surface,"surface-muted":e.surfaceMuted,border:e.border,text:e.text,"text-muted":e.textMuted,font:e.font,radius:t(e.radius),"bubble-radius":t(e.bubbleRadius),"button-radius":t(e.buttonRadius),"user-bubble-bg":e.userBubbleBg,"user-bubble-text":e.userBubbleText,"bot-bubble-bg":e.botBubbleBg,"bot-bubble-text":e.botBubbleText,"modal-width":e.modalWidth,"modal-height":e.modalHeight,"modal-max-width":e.modalMaxWidth,"modal-max-height":e.modalMaxHeight,"modal-padding":e.modalPadding};return Object.entries(r).filter(([,a])=>a!==void 0&&a!=="").map(([a,n])=>`--aikaara-${a}: ${n};`).join(`
9
9
  `)}setUploadAdapter(e){this._config.uploadAdapter=e,this.controller?.getClient().setUploadAdapter(e)}setHistoryAdapter(e){this._config.historyAdapter=e}render(){const e=this.getConfig(),t=e.display==="embed";this.propagateThemeToDocument(e.themeTokens,e.primaryColor,e.borderRadius,e.fontFamily);const r=`
10
10
  font-family: var(--aikaara-font);
11
11
  position: fixed;
@@ -401,7 +401,7 @@ In order to be iterable, non-array objects must have a [Symbol.iterator]() metho
401
401
  }
402
402
  </style>
403
403
  <div class="message-list"></div>
404
- `,this.container=this.shadow.querySelector(".message-list"),this.welcomeMessage&&this.renderMessages([])}setWelcomeMessage(e){this.welcomeMessage=e}setShowTimestamps(e){this.showTimestamps=e}renderMessages(e){if(!this.container)return;if(this.container.innerHTML="",e.length===0&&this.welcomeMessage){this.container.innerHTML=`<div class="welcome">${Ut(Nt(this.welcomeMessage))}</div>`;return}const t=this.computeConsumedIds(e);for(const r of e)this.appendMessageElement(r,t.has(r.externalId??r.id));this.scrollToBottom()}computeConsumedIds(e){const t=new Set;let r=-1;for(let a=e.length-1;a>=0;a--)if(e[a].role==="user"){r=a;break}for(let a=0;a<e.length;a++){const n=e[a];if(n.role==="user"){const i=n.metadata?.attributes?.action;i?.message_id&&t.add(i.message_id)}n.role!=="user"&&n.template?.contentType&&a<r&&t.add(n.externalId??n.id)}return t}addMessage(e){const t=this.container.querySelector(".welcome");t&&t.remove(),this.appendMessageElement(e),this.scrollToBottom()}updateStreamingContent(e){const t=this.container.querySelector('[data-streaming="true"] .bubble');t&&(t.innerHTML=Ut(Nt(e)),t.classList.add("streaming-cursor"),this.scrollToBottom())}finalizeStreaming(){const e=this.container.querySelector('[data-streaming="true"]');e&&(e.removeAttribute("data-streaming"),e.querySelector(".bubble")?.classList.remove("streaming-cursor"))}showTypingIndicator(){this.removeTypingIndicator();const e=document.createElement("div");e.classList.add("typing-indicator"),e.setAttribute("data-typing","true"),e.innerHTML='<span class="dot"></span><span class="dot"></span><span class="dot"></span>',this.container.appendChild(e),this.scrollToBottom()}removeTypingIndicator(){this.container.querySelector('[data-typing="true"]')?.remove()}appendMessageElement(e,t=!1){if(e.role==="user"&&e.content?.trim()==="CHAT_INITIATED"||this.shouldHideMessage(e.content))return;if(e.role==="system"){const o=document.createElement("div");o.classList.add("message-wrap","system"),o.dataset.messageId=e.id,e.externalId&&(o.dataset.externalId=e.externalId);const l=document.createElement("aikaara-system-pill");l.setAttribute("text",e.content||""),this.showTimestamps&&e.createdAt&&l.setAttribute("subtext",this.formatTime(e.createdAt)),o.appendChild(l),this.container.appendChild(o);return}const r=document.createElement("div");r.classList.add("message-wrap",e.role),e.status==="streaming"&&r.setAttribute("data-streaming","true"),e.externalId&&(r.dataset.externalId=e.externalId),r.dataset.messageId=e.id;const a=document.createElement("div");a.classList.add("bubble",e.role);const i=!!e.template?.contentType&&e.role!=="user";e.role==="user"?a.textContent=e.content:i?e.content&&(a.innerHTML=Ut(Nt(e.content))):(a.innerHTML=Ut(Nt(e.content||"")),e.status==="streaming"&&a.classList.add("streaming-cursor"));let s=null;if(e.template?.contentType){const o=document.createElement("aikaara-template-renderer");o.setAttribute("content-type",e.template.contentType),e.template.templateId&&o.setAttribute("template-id",e.template.templateId);const l=e.externalId??e.id;l&&o.setAttribute("message-id",l),o.setPayload(e.template.payload),t&&(o.dataset.consumed="true"),this.templateLayout==="outside"?(o.classList.add("template-outside"),s=o):a.appendChild(o)}if(e.attachments?.length){const o=document.createElement("div");o.classList.add("attachments");for(const l of e.attachments){const u=document.createElement("a");u.classList.add("attachment"),u.href=l.fileUrl,u.target="_blank",u.rel="noopener noreferrer",u.textContent=`📎 ${l.fileName}`,o.appendChild(u)}a.appendChild(o)}if(r.appendChild(a),s&&r.appendChild(s),this.showTimestamps&&e.createdAt||e.role==="user"&&e.status){const o=document.createElement("div");if(o.classList.add("timestamp"),this.showTimestamps&&e.createdAt&&(o.textContent=this.formatTime(e.createdAt)),e.role==="user"&&e.status){const l=document.createElement("span");l.classList.add("status-tick"),e.status==="read"&&l.classList.add("read"),l.textContent={sending:" ○",sent:" ✓",delivered:" ✓✓",read:" ✓✓"}[e.status]??"",o.appendChild(l)}r.appendChild(o)}this.container.appendChild(r)}upsertMessage(e){const t=this.findRenderedMessage(e);t&&t.remove(),this.appendMessageElement(e),this.scrollToBottom()}findRenderedMessage(e){if(e.externalId){const t=this.container.querySelector(`[data-external-id="${CSS.escape(e.externalId)}"]`);if(t)return t}return this.container.querySelector(`[data-message-id="${CSS.escape(e.id)}"]`)}scrollToBottom(){requestAnimationFrame(()=>{this.container.scrollTop=this.container.scrollHeight})}formatTime(e){try{const t=new Date(e),r=t.toLocaleDateString(void 0,{month:"short",day:"2-digit"});switch(this.timestampFormat){case"datetime":return`${r}, ${t.toLocaleTimeString(void 0,{hour:"2-digit",minute:"2-digit"})}`;case"datetime-seconds":return`${r}, ${t.toLocaleTimeString(void 0,{hour:"2-digit",minute:"2-digit",second:"2-digit"})}`;case"datetime-24":return`${r}, ${t.toLocaleTimeString(void 0,{hour:"2-digit",minute:"2-digit",hour12:!1})}`;case"date":return r;case"relative":return xh(t);case"time-24":return t.toLocaleTimeString(void 0,{hour:"2-digit",minute:"2-digit",hour12:!1});case"time-seconds":return t.toLocaleTimeString(void 0,{hour:"2-digit",minute:"2-digit",second:"2-digit"});case"none":return"";default:return t.toLocaleTimeString(void 0,{hour:"2-digit",minute:"2-digit"})}}catch{return""}}async handleLinkClick(e,t){const r=this.linkHandlers.find(y=>Ah(e,y.match)),a=r?.target??"iframe";if(a==="tab"){window.open(e,"_blank","noopener,noreferrer");return}const n=this.getOrCreateModal(),i=r?.title??t??"Link";if(a==="iframe"||!r?.fetch||!r.render){requestAnimationFrame(()=>n.show?.(e,i));return}const s=Ih(e),o=pl(r.fetch.url,s),l={accept:"application/json",...r.fetch.headers??{}},u=r.fetch.authHeader??"session";if(u!=="none"&&this.getLinkBearer){const y=await this.getLinkBearer(u);y&&(l.authorization=`Bearer ${y}`)}const d={method:r.fetch.method??"GET",headers:l};r.fetch.body&&(l["content-type"]="application/json",d.body=JSON.stringify(io(r.fetch.body,s)));let p=null;try{const y=await fetch(o,d);y.ok&&(p=await y.json().catch(()=>null))}catch(y){console.warn("[aikaara-chat-sdk] linkHandler fetch failed",y)}requestAnimationFrame(()=>{n.showElement?.(r.render,i,y=>{const f=r.props??{setData:p};for(const[b,k]of Object.entries(f)){const m=y[b];typeof m=="function"&&m.call(y,k)}const g=b=>{const k=b,m=k.detail?.message??k.detail?.label;m&&(n.close?.(),this.dispatchEvent(new CustomEvent("message-action",{detail:{text:m,attributes:{...k.detail?.attributes??{}}},bubbles:!0,composed:!0})))};y.addEventListener("aikaara-plan-select",g),y.addEventListener("aikaara-select",g)})})}getOrCreateModal(){let e=document.querySelector("aikaara-link-modal");return e||(e=document.createElement("aikaara-link-modal"),document.body.appendChild(e)),e}}function Ah(c,e){const t=e.replace(/[.+^${}()|[\]\\]/g,"\\$&");return new RegExp("^"+t.replace(/\*/g,".*").replace(/\?/g,".")+"$","i").test(c)}function Ih(c){try{const e=new URL(c),t={};return e.searchParams.forEach((r,a)=>{t[a]=r}),t}catch{return{}}}function pl(c,e){return c.replace(/\{(\w+)\}/g,(t,r)=>e[r]??"")}function io(c,e){if(typeof c=="string")return pl(c,e);if(Array.isArray(c))return c.map(t=>io(t,e));if(c&&typeof c=="object"){const t={};for(const[r,a]of Object.entries(c))t[r]=io(a,e);return t}return c}class gl extends HTMLElement{shadow;templatePayload=null;attachments=[];static get observedAttributes(){return["role","content","timestamp","content-type","template-id","inner-message","message-id","status"]}constructor(){super(),this.shadow=this.attachShadow({mode:"open"})}connectedCallback(){this.render()}attributeChangedCallback(){this.render()}setTemplatePayload(e){this.templatePayload=e,this.render()}setAttachments(e){this.attachments=e,this.render()}render(){const e=this.getAttribute("role")||"user",t=this.getAttribute("content")||"",r=this.getAttribute("timestamp")||"",a=this.getAttribute("status")||"",n=this.getAttribute("content-type")||"",i=this.getAttribute("template-id")||"",s=this.getAttribute("inner-message")||"",o=e==="user"?document.createTextNode(t).textContent||"":Ut(Nt(t)),l=e==="user"&&a,u=a==="sending"?"○":a==="sent"?"✓":a==="delivered"||a==="read"?"✓✓":"";this.shadow.innerHTML=`
404
+ `,this.container=this.shadow.querySelector(".message-list"),this.welcomeMessage&&this.renderMessages([])}setWelcomeMessage(e){this.welcomeMessage=e}setShowTimestamps(e){this.showTimestamps=e}renderMessages(e){if(!this.container)return;if(this.container.innerHTML="",e.length===0&&this.welcomeMessage){this.container.innerHTML=`<div class="welcome">${Ut(Nt(this.welcomeMessage))}</div>`;return}const t=this.computeConsumedIds(e);for(const r of e)this.appendMessageElement(r,t.has(r.externalId??r.id));this.scrollToBottom()}computeConsumedIds(e){const t=new Set;let r=-1;for(let a=e.length-1;a>=0;a--)if(e[a].role==="user"){r=a;break}for(let a=0;a<e.length;a++){const n=e[a];if(n.role==="user"){const i=n.metadata?.attributes?.action;i?.message_id&&t.add(i.message_id)}n.role!=="user"&&n.template?.contentType&&a<r&&t.add(n.externalId??n.id)}return t}addMessage(e){const t=this.container.querySelector(".welcome");t&&t.remove(),this.appendMessageElement(e),this.scrollToBottom()}updateStreamingContent(e){const t=this.container.querySelector('[data-streaming="true"] .bubble');t&&(t.innerHTML=Ut(Nt(e)),t.classList.add("streaming-cursor"),this.scrollToBottom())}finalizeStreaming(){const e=this.container.querySelector('[data-streaming="true"]');e&&(e.removeAttribute("data-streaming"),e.querySelector(".bubble")?.classList.remove("streaming-cursor"))}showTypingIndicator(){this.removeTypingIndicator();const e=document.createElement("div");e.classList.add("typing-indicator"),e.setAttribute("data-typing","true"),e.innerHTML='<span class="dot"></span><span class="dot"></span><span class="dot"></span>',this.container.appendChild(e),this.scrollToBottom()}removeTypingIndicator(){this.container.querySelector('[data-typing="true"]')?.remove()}appendMessageElement(e,t=!1){if(e.role==="user"&&e.content?.trim()==="CHAT_INITIATED"||this.shouldHideMessage(e.content))return;if(e.role==="system"){const o=document.createElement("div");o.classList.add("message-wrap","system"),o.dataset.messageId=e.id,e.externalId&&(o.dataset.externalId=e.externalId);const l=document.createElement("aikaara-system-pill");l.setAttribute("text",e.content||""),this.showTimestamps&&e.createdAt&&l.setAttribute("subtext",this.formatTime(e.createdAt)),o.appendChild(l),this.container.appendChild(o);return}const r=document.createElement("div");r.classList.add("message-wrap",e.role),e.status==="streaming"&&r.setAttribute("data-streaming","true"),e.externalId&&(r.dataset.externalId=e.externalId),r.dataset.messageId=e.id;const a=document.createElement("div");a.classList.add("bubble",e.role);const i=!!e.template?.contentType&&e.role!=="user";e.role==="user"?a.textContent=e.content:i?e.content&&(a.innerHTML=Ut(Nt(e.content))):(a.innerHTML=Ut(Nt(e.content||"")),e.status==="streaming"&&a.classList.add("streaming-cursor"));let s=null;if(e.template?.contentType){const o=document.createElement("aikaara-template-renderer");o.setAttribute("content-type",e.template.contentType),e.template.templateId&&o.setAttribute("template-id",e.template.templateId);const l=e.externalId??e.id;l&&o.setAttribute("message-id",l),o.setPayload(e.template.payload),t&&(o.dataset.consumed="true"),this.templateLayout==="outside"?(o.classList.add("template-outside"),s=o):a.appendChild(o)}if(e.attachments?.length){const o=document.createElement("div");o.classList.add("attachments");for(const l of e.attachments){const u=document.createElement("a");u.classList.add("attachment"),u.href=l.fileUrl,u.target="_blank",u.rel="noopener noreferrer",u.textContent=`📎 ${l.fileName}`,o.appendChild(u)}a.appendChild(o)}if(r.appendChild(a),s&&r.appendChild(s),this.showTimestamps&&e.createdAt||e.role==="user"&&e.status){const o=document.createElement("div");if(o.classList.add("timestamp"),this.showTimestamps&&e.createdAt&&(o.textContent=this.formatTime(e.createdAt)),e.role==="user"&&e.status){const l=document.createElement("span");l.classList.add("status-tick"),e.status==="read"&&l.classList.add("read"),l.textContent={sending:" ○",sent:" ✓",delivered:" ✓✓",read:" ✓✓"}[e.status]??"",o.appendChild(l)}r.appendChild(o)}this.container.appendChild(r)}upsertMessage(e){const t=this.findRenderedMessage(e);t&&t.remove(),this.appendMessageElement(e),this.scrollToBottom()}findRenderedMessage(e){if(e.externalId){const t=this.container.querySelector(`[data-external-id="${CSS.escape(e.externalId)}"]`);if(t)return t}return this.container.querySelector(`[data-message-id="${CSS.escape(e.id)}"]`)}scrollToBottom(){requestAnimationFrame(()=>{this.container.scrollTop=this.container.scrollHeight})}formatTime(e){try{const t=new Date(e),r=t.toLocaleDateString(void 0,{month:"short",day:"2-digit"});switch(this.timestampFormat){case"datetime":return`${r}, ${t.toLocaleTimeString(void 0,{hour:"2-digit",minute:"2-digit"})}`;case"datetime-seconds":return`${r}, ${t.toLocaleTimeString(void 0,{hour:"2-digit",minute:"2-digit",second:"2-digit"})}`;case"datetime-24":return`${r}, ${t.toLocaleTimeString(void 0,{hour:"2-digit",minute:"2-digit",hour12:!1})}`;case"date":return r;case"relative":return xh(t);case"time-24":return t.toLocaleTimeString(void 0,{hour:"2-digit",minute:"2-digit",hour12:!1});case"time-seconds":return t.toLocaleTimeString(void 0,{hour:"2-digit",minute:"2-digit",second:"2-digit"});case"none":return"";default:return t.toLocaleTimeString(void 0,{hour:"2-digit",minute:"2-digit"})}}catch{return""}}async handleLinkClick(e,t){const r=this.linkHandlers.find(y=>Ah(e,y.match)),a=r?.target??"iframe";if(a==="tab"){window.open(e,"_blank","noopener,noreferrer");return}const n=this.getOrCreateModal(),i=r?.title??t??"Link";if(a==="iframe"||!r?.fetch||!r.render){requestAnimationFrame(()=>n.show?.(e,i));return}const s=Ih(e),o=pl(r.fetch.url,s),l={accept:"application/json",...r.fetch.headers??{}},u=r.fetch.authHeader??"session";if(u!=="none"&&this.getLinkBearer){const y=await this.getLinkBearer(u);y&&(l.authorization=`Bearer ${y}`)}const d={method:r.fetch.method??"GET",headers:l};r.fetch.body&&(l["content-type"]="application/json",d.body=JSON.stringify(io(r.fetch.body,s)));let p=null;try{const y=await fetch(o,d);y.ok&&(p=await y.json().catch(()=>null))}catch(y){console.warn("[aikaara-chat-sdk] linkHandler fetch failed",y)}requestAnimationFrame(()=>{n.showElement?.(r.render,i,y=>{const f=r.props??{setData:p};for(const[b,k]of Object.entries(f)){const g=y[b];typeof g=="function"&&g.call(y,k)}const m=b=>{const k=b,g=k.detail?.message??k.detail?.label;g&&(n.close?.(),this.dispatchEvent(new CustomEvent("message-action",{detail:{text:g,attributes:{...k.detail?.attributes??{}}},bubbles:!0,composed:!0})))};y.addEventListener("aikaara-plan-select",m),y.addEventListener("aikaara-select",m)})})}getOrCreateModal(){let e=document.querySelector("aikaara-link-modal");return e||(e=document.createElement("aikaara-link-modal"),document.body.appendChild(e)),e}}function Ah(c,e){const t=e.replace(/[.+^${}()|[\]\\]/g,"\\$&");return new RegExp("^"+t.replace(/\*/g,".*").replace(/\?/g,".")+"$","i").test(c)}function Ih(c){try{const e=new URL(c),t={};return e.searchParams.forEach((r,a)=>{t[a]=r}),t}catch{return{}}}function pl(c,e){return c.replace(/\{(\w+)\}/g,(t,r)=>e[r]??"")}function io(c,e){if(typeof c=="string")return pl(c,e);if(Array.isArray(c))return c.map(t=>io(t,e));if(c&&typeof c=="object"){const t={};for(const[r,a]of Object.entries(c))t[r]=io(a,e);return t}return c}class gl extends HTMLElement{shadow;templatePayload=null;attachments=[];static get observedAttributes(){return["role","content","timestamp","content-type","template-id","inner-message","message-id","status"]}constructor(){super(),this.shadow=this.attachShadow({mode:"open"})}connectedCallback(){this.render()}attributeChangedCallback(){this.render()}setTemplatePayload(e){this.templatePayload=e,this.render()}setAttachments(e){this.attachments=e,this.render()}render(){const e=this.getAttribute("role")||"user",t=this.getAttribute("content")||"",r=this.getAttribute("timestamp")||"",a=this.getAttribute("status")||"",n=this.getAttribute("content-type")||"",i=this.getAttribute("template-id")||"",s=this.getAttribute("inner-message")||"",o=e==="user"?document.createTextNode(t).textContent||"":Ut(Nt(t)),l=e==="user"&&a,u=a==="sending"?"○":a==="sent"?"✓":a==="delivered"||a==="read"?"✓✓":"";this.shadow.innerHTML=`
405
405
  <style>
406
406
  :host { display: flex; flex-direction: column; }
407
407
  :host([role="user"]) { align-items: flex-end; }
@@ -983,7 +983,7 @@ In order to be iterable, non-array objects must have a [Symbol.iterator]() metho
983
983
  <small>Tap to select</small>
984
984
  </button>`}).join("")}
985
985
  </div>
986
- `,this.shadow.querySelectorAll("button.action").forEach(r=>{r.addEventListener("click",()=>{const a=Number(r.dataset.col),n=e[a];n&&this.dispatchEvent(new CustomEvent("aikaara-plan-select",{detail:{planType:n.match[0],message:n.postback,label:n.label},bubbles:!0,composed:!0}))})})}}function ao(c){return c.replace(/[&<>"']/g,e=>({"&":"&amp;","<":"&lt;",">":"&gt;",'"':"&quot;","'":"&#39;"})[e])}function lo(){const c=[["aikaara-chat-widget",cl],["aikaara-chat-bubble",ul],["aikaara-chat-header",hl],["aikaara-message-list",dl],["aikaara-message-bubble",gl],["aikaara-chat-input",bl],["aikaara-typing-indicator",yl],["aikaara-streaming-message",vl],["aikaara-error-banner",wl],["aikaara-template-renderer",Ph],["aikaara-system-pill",jh],["aikaara-option-list",Lh],["aikaara-submit-action",Nh],["aikaara-modal-action",Bh],["aikaara-chat",Fh],["aikaara-link-modal",Dh],["aikaara-compare-plans",qh]];for(const[e,t]of c)customElements.get(e)||customElements.define(e,t)}lo();function co(c,e,t=""){if(!e)return t;const r=e.split(".");let a=c;for(const n of r)if(a&&typeof a=="object"&&n in a)a=a[n];else return t;return typeof a=="string"?a:t}function Hh(c){try{const e=c.split(".")[1];if(!e)return 0;const t=JSON.parse(atob(e.replace(/-/g,"+").replace(/_/g,"/")));return typeof t.exp=="number"?t.exp*1e3:0}catch{return 0}}async function Nr(c){return typeof c=="function"?await c():c}class El{constructor(e,t){this.descriptor=e,this.sessionToken=t}cache=null;inflight=null;reset(){this.cache=null,this.inflight=null}async get(){const e=this.descriptor.expiryBufferMs??6e4,t=Date.now();return this.cache&&this.cache.expiresAt>t+e?this.cache:this.inflight?this.inflight:(this.inflight=this.fetchOnce().finally(()=>{this.inflight=null}),this.inflight)}async fetchOnce(){const e=await Nr(this.sessionToken),t=this.descriptor.authHeader??"Authorization",r=this.descriptor.authHeaderTemplate??"Bearer {token}",a={accept:"application/json",...this.descriptor.headers??{},[t]:r.replace("{token}",e)},n=this.descriptor.method??"POST",i={method:n,headers:a};n==="POST"&&(a["content-type"]="application/json",i.body=JSON.stringify(this.descriptor.body??{}));const s=await fetch(this.descriptor.endpoint,i);if(!s.ok){const b=await s.text().catch(()=>"");throw new Error(`Session auth failed: ${s.status} ${b.slice(0,200)}`)}const o=await s.json().catch(()=>({})),l=co(o,this.descriptor.tokenPath??"data.token"),u=this.descriptor.tokenStripPrefix,d=u?l.replace(new RegExp(`^${u}`,"i"),"").trim():l;if(!d)throw new Error("Session auth response missing token");const p=co(o,this.descriptor.requestIdPath??"data.requestId"),y=this.cache?.requestId||p;if(!y)throw new Error("Session auth response missing requestId");const f=co(o,this.descriptor.fullNamePath??"data.fullName"),g=Hh(d)||Date.now()+3600*1e3;return this.cache={token:d,requestId:y,fullName:f,expiresAt:g},this.cache}}async function xl(c){const e={};for(const t of c.spec){const r=await zh(t,c.providers);if(r!==void 0&&r!=="")e[t.name]=r;else{if(t.required)throw new Error(`[aikaara-chat-sdk] SSO credential "${t.name}" is required but ${t.source}`+(t.key?`[${t.key}]`:"")+" returned no value");t.default!==void 0&&(e[t.name]=t.default)}}return e}async function zh(c,e){const t=c.key??c.name;switch(c.source){case"cookie":return Kh(t);case"localStorage":return Ur(()=>window.localStorage.getItem(t)??void 0);case"sessionStorage":return Ur(()=>window.sessionStorage.getItem(t)??void 0);case"url_param":return Ur(()=>new URL(window.location.href).searchParams.get(t)??void 0);case"header_meta":return Ur(()=>document.querySelector(`meta[name="${Vh(t)}"]`)?.content??void 0);case"callback":{const r=e?.[c.name];if(!r)return;const a=await r();return typeof a=="string"?a:void 0}default:return}}function Kh(c){if(typeof document>"u")return;const e=encodeURIComponent(c),t=document.cookie?document.cookie.split("; "):[];for(const r of t){const a=r.indexOf("=");if(a===-1)continue;const n=r.slice(0,a);if(n===c||n===e)try{return decodeURIComponent(r.slice(a+1))}catch{return r.slice(a+1)}}}function Ur(c){try{return c()}catch{return}}function Vh(c){return c.replace(/["\\]/g,"\\$&")}const Gh=1800;class Al{constructor(e){this.opts=e,this.cache=this.loadCache()}cache=null;inflight=null;reset(){this.cache=null,this.inflight=null,this.clearCache()}async get(e=!1){if(!e){const t=this.cache;if(t&&(!t.expiresAt||t.expiresAt>Date.now()))return t}return this.inflight?this.inflight:(this.inflight=this.exchange().finally(()=>{this.inflight=null}),this.inflight)}async exchange(){if(!this.opts.descriptor.collect||this.opts.descriptor.collect.length===0)throw new Error("[aikaara-chat-sdk] SsoExchangeAdapter.exchange() requires descriptor.sso.collect; v2 partner-token flow should be handled by TokenDiscoveryReader instead.");const e=await xl({spec:this.opts.descriptor.collect,providers:this.opts.providers}),t=JSON.stringify({credentials:e}),r={accept:"application/json","content-type":"application/json",...this.opts.descriptor.headers??{}};this.opts.descriptor.apiKey&&(r["X-Api-Key"]=this.opts.descriptor.apiKey);const a=this.opts.descriptor.exchangeEndpoint||this.opts.exchangeUrl;if(!a)throw new Error("[aikaara-chat-sdk] SSO exchange URL not resolved — set descriptor.sso.exchangeEndpoint or pass `exchangeUrl` (mountFromSlug derives it from configBase + slug).");const n=await fetch(a,{method:"POST",headers:r,body:t});if(!n.ok){const d=await n.text().catch(()=>"");throw new Error(`SSO exchange failed: ${n.status} ${d.slice(0,240)}`)}const s=(await n.json().catch(()=>({}))).user??{},o=String(s.ext_uid??s.extUid??""),l=String(s.token??s.user_token??s.userToken??"");if(!o)throw new Error("SSO exchange response missing user.ext_uid");if(!l)throw new Error("SSO exchange response missing user.token");const u={id:s.id,extUid:o,userToken:l,email:typeof s.email=="string"?s.email:void 0,displayName:typeof s.display_name=="string"?s.display_name:typeof s.displayName=="string"?s.displayName:void 0,properties:s.properties&&typeof s.properties=="object"?s.properties:void 0,expiresAt:this.computeExpiry()};return this.cache=u,this.persistCache(u),u}computeExpiry(){const e=this.opts.descriptor.cacheTtlSec??Gh;if(!(!this.opts.descriptor.cacheKey||e<=0))return Date.now()+e*1e3}loadCache(){const e=this.opts.descriptor.cacheKey;if(!e)return null;try{const t=window.localStorage.getItem(e);if(!t)return null;const r=JSON.parse(t);return r.expiresAt&&r.expiresAt<Date.now()?(window.localStorage.removeItem(e),null):r}catch{return null}}persistCache(e){const t=this.opts.descriptor.cacheKey;if(t)try{window.localStorage.setItem(t,JSON.stringify(e))}catch{}}clearCache(){const e=this.opts.descriptor.cacheKey;if(e)try{window.localStorage.removeItem(e)}catch{}}}const Yh=3e4,Qh=2e3,Jh=100;async function Il(c){const{descriptor:e}=c,t=e.tokenSourceConfig??{};switch(e.tokenSource){case"init":{if(!c.initToken)throw new Ke("init","No init token supplied to Aikaara.init({token})");return{token:c.initToken,source:"init"}}case"query":{const r=typeof t.key=="string"&&t.key?t.key:"token",a=Xh(r);if(!a)throw new Ke("query",`?${r}= not present`);return{token:a,source:"query"}}case"hash":{const r=typeof t.key=="string"&&t.key?t.key:"token",a=Zh(r);if(!a)throw new Ke("hash",`#${r}= not present`);return{token:a,source:"hash"}}case"postmsg":{const r=typeof t.type=="string"?t.type:"",a=typeof t.key=="string"&&t.key?t.key:"token",n=of(typeof t.origins=="string"?t.origins:""),i=typeof t.timeoutMs=="number"&&t.timeoutMs>0?t.timeoutMs:Yh;return{token:await nf({type:r,key:a,origins:n,timeoutMs:i}),source:"postmsg"}}case"cookie":{const r=typeof t.name=="string"&&t.name?t.name:"";if(!r)throw new Ke("cookie","cookie.name not configured");const a=ef(r);if(!a)throw new Ke("cookie",`cookie "${r}" not set`);return{token:a,source:"cookie"}}case"storage":{const r=t.store==="session"?"session":"local",a=typeof t.key=="string"&&t.key?t.key:"",n=typeof t.path=="string"?t.path:"";if(!a)throw new Ke("storage","storage.key not configured");const i=tf(r,a,n);if(!i)throw new Ke("storage",`${r}Storage["${a}"] not set`);return{token:i,source:"storage"}}case"global":{const r=typeof t.path=="string"?t.path:"";if(!r)throw new Ke("global","global.path not configured");const a=typeof t.timeoutMs=="number"&&t.timeoutMs>0?t.timeoutMs:Qh,n=typeof t.intervalMs=="number"&&t.intervalMs>0?t.intervalMs:Jh,i=await rf(r,a,n);if(!i)throw new Ke("global",`window.${r} not present`);return{token:i,source:"global"}}default:{const r=e.tokenSource;throw new Ke("unknown",`Unknown tokenSource ${JSON.stringify(r)}`)}}}class Tl{constructor(e){this.opts=e}cached=null;get descriptor(){return this.opts.descriptor}async get(){if(this.cached)return this.cached;const e=await Il(this.opts);return this.cached=e,e}async refresh(){return this.opts.descriptor.tokenSource==="init"?this.cached?this.cached:this.get():(this.cached=null,this.get())}}class Ke extends Error{constructor(e,t){super(`[aikaara-chat-sdk] token-discovery (${e}): ${t}`),this.source=e,this.name="TokenDiscoveryError"}}function Xh(c){if(!(typeof window>"u"))try{return new URL(window.location.href).searchParams.get(c)??void 0}catch{return}}function Zh(c){if(!(typeof window>"u"))try{const e=window.location.hash.replace(/^#/,"");return new URLSearchParams(e).get(c)??void 0}catch{return}}function ef(c){if(typeof document>"u")return;const e=encodeURIComponent(c),t=document.cookie?document.cookie.split("; "):[];for(const r of t){const a=r.indexOf("=");if(a===-1)continue;const n=r.slice(0,a);if(n===c||n===e)try{return decodeURIComponent(r.slice(a+1))}catch{return r.slice(a+1)}}}function tf(c,e,t){if(!(typeof window>"u"))try{const a=(c==="session"?window.sessionStorage:window.localStorage).getItem(e);if(a==null)return;if(!t)return a;let n;try{n=JSON.parse(a)}catch{return a}const i=Cl(n,t);return typeof i=="string"?i:void 0}catch{return}}async function rf(c,e,t){if(typeof window>"u")return;const r=Date.now()+e;for(;Date.now()<r;){const a=Cl(window,c);if(typeof a=="string"&&a.length>0)return a;if(typeof a=="function")try{const n=a();if(typeof n=="string"&&n.length>0)return n}catch{}await new Promise(n=>setTimeout(n,t))}}function nf(c){return new Promise((e,t)=>{if(typeof window>"u"){t(new Ke("postmsg","no window"));return}const r=()=>{window.removeEventListener("message",n),clearTimeout(a)},a=setTimeout(()=>{r(),t(new Ke("postmsg",`timeout after ${c.timeoutMs}ms`))},c.timeoutMs),n=i=>{if(c.origins.length>0&&!c.origins.includes(i.origin))return;const s=i.data;if(!s||typeof s!="object")return;const o=s;if(c.type&&o.type!==c.type)return;const l=o[c.key];typeof l=="string"&&l.length>0&&(r(),e(l))};window.addEventListener("message",n)})}function of(c){return c?c.split(/[,\s]+/).map(e=>e.trim()).filter(Boolean):[]}function Cl(c,e){if(!e)return c;const t=e.split(".").filter(Boolean);let r=c;for(const a of t)if(r&&typeof r=="object"&&a in r)r=r[a];else return;return r}function sf(){const c=typeof crypto<"u"?crypto:null;if(c?.randomUUID)return c.randomUUID();if(c?.getRandomValues){const e=new Uint8Array(16);c.getRandomValues(e),e[6]=e[6]&15|64,e[8]=e[8]&63|128;const t=[...e].map(r=>r.toString(16).padStart(2,"0")).join("");return`${t.slice(0,8)}-${t.slice(8,12)}-${t.slice(12,16)}-${t.slice(16,20)}-${t.slice(20)}`}return"xxxxxxxxxxxx4xxxyxxxxxxxxxxxxxxx".replace(/[xy]/g,e=>{const t=Math.random()*16|0;return(e==="x"?t:t&3|8).toString(16)})}const af="aikaara_chat:requestId";function uo(c,e){return`${af}:${c}:${e}`}function lf(c,e){try{return localStorage.getItem(uo(c,e))}catch{return null}}function cf(c,e,t){try{localStorage.setItem(uo(c,e),t)}catch{}}function uf(c,e){try{localStorage.removeItem(uo(c,e))}catch{}}async function hf(c,e){console.log("[aikaara-chat-sdk] preflight running",c.length,"steps");const t={userId:e.userId,projectId:e.projectId,slug:e.slug};if(e.identity)for(const[s,o]of Object.entries(e.identity))typeof o=="string"&&(t[s]=o);const r=s=>s.replace(/\{(\w+)\}/g,(o,l)=>l in t?t[l]:""),a=s=>{if(typeof s=="string")return r(s);if(Array.isArray(s))return s.map(a);if(s&&typeof s=="object"){const o={};for(const[l,u]of Object.entries(s))o[l]=a(u);return o}return s},n=await Nr(e.sessionToken),i=[800,1500,3e3,5e3,8e3];for(let s=0;s<c.length;s++){const o=c[s],l=r(o.url),u=o.method??(o.body?"POST":"GET"),d={accept:"application/json",...o.headers??{}};if((o.authHeader??"session")==="session"){const b=o.authHeaderTemplate??"Bearer {token}";d.authorization=b.replace("{token}",n)}const p={method:u,headers:d};o.body&&(d["content-type"]="application/json",p.body=JSON.stringify(a(o.body)));let y=0,f="",g=0;for(;;)try{const b=await fetch(l,p);if(b.ok)break;if(y=b.status,f=await b.text().catch(()=>""),g<i.length&&ff(y,f)){const m=i[g++];console.warn(`[aikaara-chat-sdk] preflight #${s} ${u} ${l} → ${y} (transient). Retry #${g} in ${m}ms.`),await new Promise(w=>setTimeout(w,m));continue}const k=`Preflight #${s} ${u} ${l} → ${y} ${f.slice(0,200)}`;if(o.soft){console.warn("[aikaara-chat-sdk]",k);break}throw new Error(k)}catch(b){if(g<i.length){const k=i[g++];console.warn(`[aikaara-chat-sdk] preflight #${s} threw, retry #${g} in ${k}ms`,b),await new Promise(m=>setTimeout(m,k));continue}if(o.soft){console.warn(`[aikaara-chat-sdk] preflight #${s} soft-failed:`,b);break}throw b}}}function ff(c,e){if(c===503||c===504||c===502)return!0;if(c===401||c===403)return e.trim().length===0;if(c===500){const t=e.toLowerCase();return t.includes("customernew")||t.includes("is null")||t.includes("not yet ready")}return!1}async function Ol(c,e){const t=await fetch(c,{method:"GET",headers:{accept:"application/json",...e??{}}});if(!t.ok){const a=await t.text().catch(()=>"");throw new Error(`Widget config fetch failed: ${t.status} ${t.statusText} ${a.slice(0,200)}`)}const r=await t.json();if(r&&typeof r=="object"){if("config"in r)return r.config;if("data"in r)return r.data}return r}function df(c,e){return c.replace("{projectId}",e).replace("{uuid}",sf().replace(/-/g,""))}function Pl(c){const e=c._preload;if(!Array.isArray(e)||e.length===0)return;const t=Array.from(new Set(e.map(r=>r&&typeof r=="object"?r.scriptUrl:null).filter(r=>typeof r=="string"&&r.length>0)));t.length!==0&&Promise.allSettled(t.map(r=>_l(r)))}async function Ml(c){const e={...c.config??(c.configUrl?await Ol(c.configUrl,c.configHeaders):{}),...c.overrides??{}};Pl(e);const t=e.transport??"tiledesk",r=e.tiledesk;if((t==="tiledesk"||t==="dual")&&!r)throw new Error("mount: descriptor.tiledesk is required for tiledesk/dual transport");const a=r?.projectId??"",n=c.identity.userId,i=c.forceNewConversation?null:lf(n,a),s=r?.requestIdTemplate??"support-group-{projectId}-{uuid}",o=c.conversationId??i??df(s,a);(!i||c.forceNewConversation)&&a&&cf(n,a,o);const l=await c.tokenProvider(),u=c.tokenProvider,d=c.historyTokenProvider??u,p=r?{mqttEndpoint:r.mqttEndpoint,jwtToken:l,userId:n,userName:c.identity.userName,projectId:r.projectId,appId:r.appId,mqttUsername:r.mqttUsername,protocolId:r.protocolId,protocolVersion:r.protocolVersion,keepAliveSec:r.keepAliveSec,connectTimeoutMs:r.connectTimeoutMs,maxReconnectAttempts:r.maxReconnectAttempts,reconnectMaxDelayMs:r.reconnectMaxDelayMs,wildcardSubscribe:r.wildcardSubscribe,enablePresence:r.enablePresence,autoInitiateOnEmpty:r.autoInitiateOnEmpty,chatInitiatedAttributes:r.chatInitiatedAttributes,messageDefaults:{...r.messageDefaults,...c.identity.departmentId?{departmentId:c.identity.departmentId}:r.messageDefaults?.departmentId?{departmentId:r.messageDefaults.departmentId}:{}},fileTemplate:r.fileTemplate,topicTemplates:r.topicTemplates,debug:r.debug,senderFullname:c.identity.senderFullname??c.identity.userName,tokenProvider:u}:void 0,y=c.uploadAdapter??(e.uploadEndpoint?no({endpoint:e.uploadEndpoint,fieldName:e.uploadFieldName,extraFields:e.uploadExtraFields}):void 0),f=c.historyAdapter??(e.historyApiBase?ll({apiBase:e.historyApiBase,pageSize:e.historyPageSize??200,pathTemplate:e.historyPathTemplate,extraHeaders:e.historyHeaders,getToken:d}):void 0),g={transport:t,baseUrl:"",userToken:c.userToken??n,conversationId:o,display:e.display??"embed",position:e.position,primaryColor:e.theme?.primary??e.primaryColor,title:e.title,subtitle:e.subtitle,avatarUrl:e.avatarUrl,width:e.width,height:e.height,borderRadius:e.theme?.radius??e.borderRadius,fontFamily:e.theme?.font??e.fontFamily,themeTokens:e.theme,linkHandlers:e.linkHandlers,getLinkBearer:c.getLinkBearer,welcomeMessage:e.welcomeMessage,placeholder:e.placeholder,showTimestamps:e.showTimestamps,persistConversation:e.persistConversation,showHeader:e.showHeader,hideSystemMessages:e.hideSystemMessages,timestampFormat:e.timestampFormat,input:e.input,templateLayout:e.templateLayout,tiledesk:p,tiledeskIdentity:{userId:n,userName:c.identity.userName,departmentId:c.identity.departmentId,senderFullname:c.identity.senderFullname??c.identity.userName},templateActionAttributes:e.templateActionAttributes,uploadAdapter:y,historyAdapter:f,onError:c.onError,onMessage:c.onMessage},b=document.createElement("aikaara-chat-widget");return b.configure(g),g.title&&b.setAttribute("title",g.title),g.primaryColor&&b.setAttribute("primary-color",g.primaryColor),g.display&&b.setAttribute("display",g.display),g.display==="embed"&&(b.style.cssText="display:flex;flex-direction:column;width:100%;height:100%;min-height:0;"),c.container.appendChild(b),{widget:b,requestId:o,config:g,destroy(){b.remove()}}}function pf(c){if(typeof c!="string")return c;const e=document.querySelector(c);if(!e)throw new Error(`mountFromSlug: container "${c}" not found`);return e}async function Rl(c){const e=(c.configBase??"https://api.aikaara.com").replace(/\/$/,""),t=`${e}/api/v1/widget_configs/${encodeURIComponent(c.slug)}`;let r=null;try{r=await Ol(t,c.configHeaders)}catch(w){if(!c.fallbackConfig)throw w;console.warn(`[aikaara-chat-sdk] Widget config fetch failed for slug "${c.slug}" — using fallbackConfig.`,w)}const a={...c.fallbackConfig??{},...r??{},...c.overrides??{}};if(Pl(a),a.templates&&Object.keys(a.templates).length>0){a.components={...a.components??{}};for(const[w,E]of Object.entries(a.templates)){const v=`template:${w}`;a.components[v]||!E?.scriptUrl||!E?.render||(a.components[v]={kind:"iife-element",scriptUrl:E.scriptUrl,tag:E.render,...E.props?{props:E.props}:{}})}}if(window.__aikaara_descriptor__={templates:a.templates,components:a.components,razorpay:a.razorpay,title:a.title},!a.auth)throw new Error(`mountFromSlug: widget_configs/${c.slug} descriptor must include "auth" block`);let n=null,i=c.user.id,s=c.user.name,o="",l=c.user.token,u=null;if(a.sso?.tokenSource){u=new Tl({descriptor:{provider:a.sso.provider,flow:a.sso.flow,skipLogin:a.sso.skipLogin,autoRefresh:a.sso.autoRefresh,tokenSource:a.sso.tokenSource,tokenSourceConfig:a.sso.tokenSourceConfig,fallback:a.sso.fallback,map:a.sso.map},initToken:c.user.partnerToken});const w=await u.get();l=async()=>(await u.get()).token,c.user.identity&&!c.user.identity.partnerToken&&(c.user.identity.partnerToken=w.token)}else if(a.sso&&a.sso.collect&&a.sso.collect.length>0){const w=`${e}/api/v1/projects/by-slug/${encodeURIComponent(c.slug)}/sso_exchange`;n=await new Al({descriptor:a.sso,providers:c.user.credentialProviders,exchangeUrl:w}).get(),i=n.extUid||i,s=s??n.displayName,o=n.userToken}a.preflight&&a.preflight.length&&await hf(a.preflight,{sessionToken:l,userId:i,projectId:a.tiledesk?.projectId??"",slug:c.slug,identity:c.user.identity});const d=new El(a.auth,l),p=await d.get(),y=p.fullName||s||i;window.__aikaara_runtime__={getChatJwt:async()=>(await d.get()).token,identity:c.user.identity,slug:c.slug};const f=u&&a.sso?.autoRefresh?async()=>{try{return await u.refresh(),d.reset(),(await d.get()).token}catch(w){return console.warn("[aikaara-chat-sdk] partner auto-refresh failed",w),null}}:null,g=a.upload,b=async()=>`Bearer ${g&&"tokenSource"in g&&g.tokenSource==="chat"?(await d.get()).token:await Nr(c.user.token)}`,k=c.hooks?.upload??(g&&g.mode==="presigned-3step"?al({...g,authHeader:b}):g&&g.mode==="direct"?no({endpoint:g.endpoint,fieldName:g.fieldName,extraFields:g.extraFields,headers:async()=>({authorization:await b()})}):void 0),m=await Ml({container:pf(c.container),config:a,userToken:o||void 0,identity:{userId:i,userName:y,departmentId:c.user.departmentId,senderFullname:y},tokenProvider:async()=>(await d.get()).token,historyTokenProvider:async()=>(await d.get()).token,uploadAdapter:k,historyAdapter:c.hooks?.history,conversationId:p.requestId,onError:c.hooks?.onError,onMessage:c.hooks?.onMessage,getLinkBearer:async w=>w==="none"?null:w==="chat"?(await d.get()).token:Nr(c.user.token)});return Object.assign(m,{fullName:y,requestId:p.requestId,descriptor:a,async refreshAuth(){d.reset(),await d.get()},async refreshPartnerAuth(){return f?f():null}})}function gf(c){lo();const e=document.createElement("aikaara-chat-widget"),t={baseUrl:"base-url",userToken:"user-token",apiKey:"api-key",title:"title",subtitle:"subtitle",theme:"theme",primaryColor:"primary-color",position:"position",width:"width",height:"height",placeholder:"placeholder",welcomeMessage:"welcome-message",avatarUrl:"avatar-url"};for(const[r,a]of Object.entries(t)){const n=c[r];n!=null&&e.setAttribute(a,String(n))}return e.configure(c),document.body.appendChild(e),e}function mf(){const c=document.querySelector("aikaara-chat-widget");c&&c.remove()}class jl extends HTMLElement{shadow;payload=null;constructor(){super(),this.shadow=this.attachShadow({mode:"open"})}connectedCallback(){this.render()}setPayload(e){this.payload=e,this.render()}render(){const e=this.payload;this.shadow.innerHTML=`
986
+ `,this.shadow.querySelectorAll("button.action").forEach(r=>{r.addEventListener("click",()=>{const a=Number(r.dataset.col),n=e[a];n&&this.dispatchEvent(new CustomEvent("aikaara-plan-select",{detail:{planType:n.match[0],message:n.postback,label:n.label},bubbles:!0,composed:!0}))})})}}function ao(c){return c.replace(/[&<>"']/g,e=>({"&":"&amp;","<":"&lt;",">":"&gt;",'"':"&quot;","'":"&#39;"})[e])}function lo(){const c=[["aikaara-chat-widget",cl],["aikaara-chat-bubble",ul],["aikaara-chat-header",hl],["aikaara-message-list",dl],["aikaara-message-bubble",gl],["aikaara-chat-input",bl],["aikaara-typing-indicator",yl],["aikaara-streaming-message",vl],["aikaara-error-banner",wl],["aikaara-template-renderer",Ph],["aikaara-system-pill",jh],["aikaara-option-list",Lh],["aikaara-submit-action",Nh],["aikaara-modal-action",Bh],["aikaara-chat",Fh],["aikaara-link-modal",Dh],["aikaara-compare-plans",qh]];for(const[e,t]of c)customElements.get(e)||customElements.define(e,t)}lo();function co(c,e,t=""){if(!e)return t;const r=e.split(".");let a=c;for(const n of r)if(a&&typeof a=="object"&&n in a)a=a[n];else return t;return typeof a=="string"?a:t}function Hh(c){try{const e=c.split(".")[1];if(!e)return 0;const t=JSON.parse(atob(e.replace(/-/g,"+").replace(/_/g,"/")));return typeof t.exp=="number"?t.exp*1e3:0}catch{return 0}}async function Nr(c){return typeof c=="function"?await c():c}class El{constructor(e,t){this.descriptor=e,this.sessionToken=t}cache=null;inflight=null;reset(){this.cache=null,this.inflight=null}async get(){const e=this.descriptor.expiryBufferMs??6e4,t=Date.now();return this.cache&&this.cache.expiresAt>t+e?this.cache:this.inflight?this.inflight:(this.inflight=this.fetchOnce().finally(()=>{this.inflight=null}),this.inflight)}async fetchOnce(){const e=await Nr(this.sessionToken),t=this.descriptor.authHeader??"Authorization",r=this.descriptor.authHeaderTemplate??"Bearer {token}",a={accept:"application/json",...this.descriptor.headers??{},[t]:r.replace("{token}",e)},n=this.descriptor.method??"POST",i={method:n,headers:a};n==="POST"&&(a["content-type"]="application/json",i.body=JSON.stringify(this.descriptor.body??{}));const s=await fetch(this.descriptor.endpoint,i);if(!s.ok){const b=await s.text().catch(()=>"");throw new Error(`Session auth failed: ${s.status} ${b.slice(0,200)}`)}const o=await s.json().catch(()=>({})),l=co(o,this.descriptor.tokenPath??"data.token"),u=this.descriptor.tokenStripPrefix,d=u?l.replace(new RegExp(`^${u}`,"i"),"").trim():l;if(!d)throw new Error("Session auth response missing token");const p=co(o,this.descriptor.requestIdPath??"data.requestId"),y=this.cache?.requestId||p;if(!y)throw new Error("Session auth response missing requestId");const f=co(o,this.descriptor.fullNamePath??"data.fullName"),m=Hh(d)||Date.now()+3600*1e3;return this.cache={token:d,requestId:y,fullName:f,expiresAt:m},this.cache}}async function xl(c){const e={};for(const t of c.spec){const r=await zh(t,c.providers);if(r!==void 0&&r!=="")e[t.name]=r;else{if(t.required)throw new Error(`[aikaara-chat-sdk] SSO credential "${t.name}" is required but ${t.source}`+(t.key?`[${t.key}]`:"")+" returned no value");t.default!==void 0&&(e[t.name]=t.default)}}return e}async function zh(c,e){const t=c.key??c.name;switch(c.source){case"cookie":return Kh(t);case"localStorage":return Ur(()=>window.localStorage.getItem(t)??void 0);case"sessionStorage":return Ur(()=>window.sessionStorage.getItem(t)??void 0);case"url_param":return Ur(()=>new URL(window.location.href).searchParams.get(t)??void 0);case"header_meta":return Ur(()=>document.querySelector(`meta[name="${Vh(t)}"]`)?.content??void 0);case"callback":{const r=e?.[c.name];if(!r)return;const a=await r();return typeof a=="string"?a:void 0}default:return}}function Kh(c){if(typeof document>"u")return;const e=encodeURIComponent(c),t=document.cookie?document.cookie.split("; "):[];for(const r of t){const a=r.indexOf("=");if(a===-1)continue;const n=r.slice(0,a);if(n===c||n===e)try{return decodeURIComponent(r.slice(a+1))}catch{return r.slice(a+1)}}}function Ur(c){try{return c()}catch{return}}function Vh(c){return c.replace(/["\\]/g,"\\$&")}const Gh=1800;class Al{constructor(e){this.opts=e,this.cache=this.loadCache()}cache=null;inflight=null;reset(){this.cache=null,this.inflight=null,this.clearCache()}async get(e=!1){if(!e){const t=this.cache;if(t&&(!t.expiresAt||t.expiresAt>Date.now()))return t}return this.inflight?this.inflight:(this.inflight=this.exchange().finally(()=>{this.inflight=null}),this.inflight)}async exchange(){if(!this.opts.descriptor.collect||this.opts.descriptor.collect.length===0)throw new Error("[aikaara-chat-sdk] SsoExchangeAdapter.exchange() requires descriptor.sso.collect; v2 partner-token flow should be handled by TokenDiscoveryReader instead.");const e=await xl({spec:this.opts.descriptor.collect,providers:this.opts.providers}),t=JSON.stringify({credentials:e}),r={accept:"application/json","content-type":"application/json",...this.opts.descriptor.headers??{}};this.opts.descriptor.apiKey&&(r["X-Api-Key"]=this.opts.descriptor.apiKey);const a=this.opts.descriptor.exchangeEndpoint||this.opts.exchangeUrl;if(!a)throw new Error("[aikaara-chat-sdk] SSO exchange URL not resolved — set descriptor.sso.exchangeEndpoint or pass `exchangeUrl` (mountFromSlug derives it from configBase + slug).");const n=await fetch(a,{method:"POST",headers:r,body:t});if(!n.ok){const d=await n.text().catch(()=>"");throw new Error(`SSO exchange failed: ${n.status} ${d.slice(0,240)}`)}const s=(await n.json().catch(()=>({}))).user??{},o=String(s.ext_uid??s.extUid??""),l=String(s.token??s.user_token??s.userToken??"");if(!o)throw new Error("SSO exchange response missing user.ext_uid");if(!l)throw new Error("SSO exchange response missing user.token");const u={id:s.id,extUid:o,userToken:l,email:typeof s.email=="string"?s.email:void 0,displayName:typeof s.display_name=="string"?s.display_name:typeof s.displayName=="string"?s.displayName:void 0,properties:s.properties&&typeof s.properties=="object"?s.properties:void 0,expiresAt:this.computeExpiry()};return this.cache=u,this.persistCache(u),u}computeExpiry(){const e=this.opts.descriptor.cacheTtlSec??Gh;if(!(!this.opts.descriptor.cacheKey||e<=0))return Date.now()+e*1e3}loadCache(){const e=this.opts.descriptor.cacheKey;if(!e)return null;try{const t=window.localStorage.getItem(e);if(!t)return null;const r=JSON.parse(t);return r.expiresAt&&r.expiresAt<Date.now()?(window.localStorage.removeItem(e),null):r}catch{return null}}persistCache(e){const t=this.opts.descriptor.cacheKey;if(t)try{window.localStorage.setItem(t,JSON.stringify(e))}catch{}}clearCache(){const e=this.opts.descriptor.cacheKey;if(e)try{window.localStorage.removeItem(e)}catch{}}}const Yh=3e4,Qh=2e3,Jh=100;async function Il(c){const{descriptor:e}=c,t=e.tokenSourceConfig??{};switch(e.tokenSource){case"init":{if(!c.initToken)throw new Ke("init","No init token supplied to Aikaara.init({token})");return{token:c.initToken,source:"init"}}case"query":{const r=typeof t.key=="string"&&t.key?t.key:"token",a=Xh(r);if(!a)throw new Ke("query",`?${r}= not present`);return{token:a,source:"query"}}case"hash":{const r=typeof t.key=="string"&&t.key?t.key:"token",a=Zh(r);if(!a)throw new Ke("hash",`#${r}= not present`);return{token:a,source:"hash"}}case"postmsg":{const r=typeof t.type=="string"?t.type:"",a=typeof t.key=="string"&&t.key?t.key:"token",n=of(typeof t.origins=="string"?t.origins:""),i=typeof t.timeoutMs=="number"&&t.timeoutMs>0?t.timeoutMs:Yh;return{token:await nf({type:r,key:a,origins:n,timeoutMs:i}),source:"postmsg"}}case"cookie":{const r=typeof t.name=="string"&&t.name?t.name:"";if(!r)throw new Ke("cookie","cookie.name not configured");const a=ef(r);if(!a)throw new Ke("cookie",`cookie "${r}" not set`);return{token:a,source:"cookie"}}case"storage":{const r=t.store==="session"?"session":"local",a=typeof t.key=="string"&&t.key?t.key:"",n=typeof t.path=="string"?t.path:"";if(!a)throw new Ke("storage","storage.key not configured");const i=tf(r,a,n);if(!i)throw new Ke("storage",`${r}Storage["${a}"] not set`);return{token:i,source:"storage"}}case"global":{const r=typeof t.path=="string"?t.path:"";if(!r)throw new Ke("global","global.path not configured");const a=typeof t.timeoutMs=="number"&&t.timeoutMs>0?t.timeoutMs:Qh,n=typeof t.intervalMs=="number"&&t.intervalMs>0?t.intervalMs:Jh,i=await rf(r,a,n);if(!i)throw new Ke("global",`window.${r} not present`);return{token:i,source:"global"}}default:{const r=e.tokenSource;throw new Ke("unknown",`Unknown tokenSource ${JSON.stringify(r)}`)}}}class Tl{constructor(e){this.opts=e}cached=null;get descriptor(){return this.opts.descriptor}async get(){if(this.cached)return this.cached;const e=await Il(this.opts);return this.cached=e,e}async refresh(){return this.opts.descriptor.tokenSource==="init"?this.cached?this.cached:this.get():(this.cached=null,this.get())}}class Ke extends Error{constructor(e,t){super(`[aikaara-chat-sdk] token-discovery (${e}): ${t}`),this.source=e,this.name="TokenDiscoveryError"}}function Xh(c){if(!(typeof window>"u"))try{return new URL(window.location.href).searchParams.get(c)??void 0}catch{return}}function Zh(c){if(!(typeof window>"u"))try{const e=window.location.hash.replace(/^#/,"");return new URLSearchParams(e).get(c)??void 0}catch{return}}function ef(c){if(typeof document>"u")return;const e=encodeURIComponent(c),t=document.cookie?document.cookie.split("; "):[];for(const r of t){const a=r.indexOf("=");if(a===-1)continue;const n=r.slice(0,a);if(n===c||n===e)try{return decodeURIComponent(r.slice(a+1))}catch{return r.slice(a+1)}}}function tf(c,e,t){if(!(typeof window>"u"))try{const a=(c==="session"?window.sessionStorage:window.localStorage).getItem(e);if(a==null)return;if(!t)return a;let n;try{n=JSON.parse(a)}catch{return a}const i=Cl(n,t);return typeof i=="string"?i:void 0}catch{return}}async function rf(c,e,t){if(typeof window>"u")return;const r=Date.now()+e;for(;Date.now()<r;){const a=Cl(window,c);if(typeof a=="string"&&a.length>0)return a;if(typeof a=="function")try{const n=a();if(typeof n=="string"&&n.length>0)return n}catch{}await new Promise(n=>setTimeout(n,t))}}function nf(c){return new Promise((e,t)=>{if(typeof window>"u"){t(new Ke("postmsg","no window"));return}const r=()=>{window.removeEventListener("message",n),clearTimeout(a)},a=setTimeout(()=>{r(),t(new Ke("postmsg",`timeout after ${c.timeoutMs}ms`))},c.timeoutMs),n=i=>{if(c.origins.length>0&&!c.origins.includes(i.origin))return;const s=i.data;if(!s||typeof s!="object")return;const o=s;if(c.type&&o.type!==c.type)return;const l=o[c.key];typeof l=="string"&&l.length>0&&(r(),e(l))};window.addEventListener("message",n)})}function of(c){return c?c.split(/[,\s]+/).map(e=>e.trim()).filter(Boolean):[]}function Cl(c,e){if(!e)return c;const t=e.split(".").filter(Boolean);let r=c;for(const a of t)if(r&&typeof r=="object"&&a in r)r=r[a];else return;return r}function sf(){const c=typeof crypto<"u"?crypto:null;if(c?.randomUUID)return c.randomUUID();if(c?.getRandomValues){const e=new Uint8Array(16);c.getRandomValues(e),e[6]=e[6]&15|64,e[8]=e[8]&63|128;const t=[...e].map(r=>r.toString(16).padStart(2,"0")).join("");return`${t.slice(0,8)}-${t.slice(8,12)}-${t.slice(12,16)}-${t.slice(16,20)}-${t.slice(20)}`}return"xxxxxxxxxxxx4xxxyxxxxxxxxxxxxxxx".replace(/[xy]/g,e=>{const t=Math.random()*16|0;return(e==="x"?t:t&3|8).toString(16)})}const af="aikaara_chat:requestId";function uo(c,e){return`${af}:${c}:${e}`}function lf(c,e){try{return localStorage.getItem(uo(c,e))}catch{return null}}function cf(c,e,t){try{localStorage.setItem(uo(c,e),t)}catch{}}function uf(c,e){try{localStorage.removeItem(uo(c,e))}catch{}}async function hf(c,e){console.log("[aikaara-chat-sdk] preflight running",c.length,"steps");const t={userId:e.userId,projectId:e.projectId,slug:e.slug};if(e.identity)for(const[s,o]of Object.entries(e.identity))typeof o=="string"&&(t[s]=o);const r=s=>s.replace(/\{(\w+)\}/g,(o,l)=>l in t?t[l]:""),a=s=>{if(typeof s=="string")return r(s);if(Array.isArray(s))return s.map(a);if(s&&typeof s=="object"){const o={};for(const[l,u]of Object.entries(s))o[l]=a(u);return o}return s},n=await Nr(e.sessionToken),i=[800,1500,3e3,5e3,8e3];for(let s=0;s<c.length;s++){const o=c[s],l=r(o.url),u=o.method??(o.body?"POST":"GET"),d={accept:"application/json",...o.headers??{}};if((o.authHeader??"session")==="session"){const b=o.authHeaderTemplate??"Bearer {token}";d.authorization=b.replace("{token}",n)}const p={method:u,headers:d};o.body&&(d["content-type"]="application/json",p.body=JSON.stringify(a(o.body)));let y=0,f="",m=0;for(;;)try{const b=await fetch(l,p);if(b.ok)break;if(y=b.status,f=await b.text().catch(()=>""),m<i.length&&ff(y,f)){const g=i[m++];console.warn(`[aikaara-chat-sdk] preflight #${s} ${u} ${l} → ${y} (transient). Retry #${m} in ${g}ms.`),await new Promise(_=>setTimeout(_,g));continue}const k=`Preflight #${s} ${u} ${l} → ${y} ${f.slice(0,200)}`;if(o.soft){console.warn("[aikaara-chat-sdk]",k);break}throw new Error(k)}catch(b){if(m<i.length){const k=i[m++];console.warn(`[aikaara-chat-sdk] preflight #${s} threw, retry #${m} in ${k}ms`,b),await new Promise(g=>setTimeout(g,k));continue}if(o.soft){console.warn(`[aikaara-chat-sdk] preflight #${s} soft-failed:`,b);break}throw b}}}function ff(c,e){if(c===503||c===504||c===502)return!0;if(c===401||c===403)return e.trim().length===0;if(c===500){const t=e.toLowerCase();return t.includes("customernew")||t.includes("is null")||t.includes("not yet ready")}return!1}async function Ol(c,e){const t=await fetch(c,{method:"GET",headers:{accept:"application/json",...e??{}}});if(!t.ok){const a=await t.text().catch(()=>"");throw new Error(`Widget config fetch failed: ${t.status} ${t.statusText} ${a.slice(0,200)}`)}const r=await t.json();if(r&&typeof r=="object"){if("config"in r)return r.config;if("data"in r)return r.data}return r}function df(c,e){return c.replace("{projectId}",e).replace("{uuid}",sf().replace(/-/g,""))}function Pl(c){const e=c._preload;if(!Array.isArray(e)||e.length===0)return;const t=Array.from(new Set(e.map(r=>r&&typeof r=="object"?r.scriptUrl:null).filter(r=>typeof r=="string"&&r.length>0)));t.length!==0&&Promise.allSettled(t.map(r=>_l(r)))}async function Ml(c){const e={...c.config??(c.configUrl?await Ol(c.configUrl,c.configHeaders):{}),...c.overrides??{}};Pl(e);const t=e.transport??"tiledesk",r=e.tiledesk;if((t==="tiledesk"||t==="dual")&&!r)throw new Error("mount: descriptor.tiledesk is required for tiledesk/dual transport");const a=r?.projectId??"",n=c.identity.userId,i=c.forceNewConversation?null:lf(n,a),s=r?.requestIdTemplate??"support-group-{projectId}-{uuid}",o=c.conversationId??i??df(s,a);(!i||c.forceNewConversation)&&a&&cf(n,a,o);const l=await c.tokenProvider(),u=c.tokenProvider,d=c.historyTokenProvider??u,p=r?{mqttEndpoint:r.mqttEndpoint,jwtToken:l,userId:n,userName:c.identity.userName,projectId:r.projectId,appId:r.appId,mqttUsername:r.mqttUsername,protocolId:r.protocolId,protocolVersion:r.protocolVersion,keepAliveSec:r.keepAliveSec,connectTimeoutMs:r.connectTimeoutMs,maxReconnectAttempts:r.maxReconnectAttempts,reconnectMaxDelayMs:r.reconnectMaxDelayMs,wildcardSubscribe:r.wildcardSubscribe,enablePresence:r.enablePresence,autoInitiateOnEmpty:r.autoInitiateOnEmpty,chatInitiatedAttributes:r.chatInitiatedAttributes,messageDefaults:{...r.messageDefaults,...c.identity.departmentId?{departmentId:c.identity.departmentId}:r.messageDefaults?.departmentId?{departmentId:r.messageDefaults.departmentId}:{}},fileTemplate:r.fileTemplate,topicTemplates:r.topicTemplates,debug:r.debug,senderFullname:c.identity.senderFullname??c.identity.userName,tokenProvider:u}:void 0,y=c.uploadAdapter??(e.uploadEndpoint?no({endpoint:e.uploadEndpoint,fieldName:e.uploadFieldName,extraFields:e.uploadExtraFields}):void 0),f=c.historyAdapter??(e.historyApiBase?ll({apiBase:e.historyApiBase,pageSize:e.historyPageSize??200,pathTemplate:e.historyPathTemplate,extraHeaders:e.historyHeaders,getToken:d}):void 0),m={transport:t,baseUrl:"",userToken:c.userToken??n,conversationId:o,display:e.display??"embed",position:e.position,primaryColor:e.theme?.primary??e.primaryColor,title:e.title,subtitle:e.subtitle,avatarUrl:e.avatarUrl,width:e.width,height:e.height,borderRadius:e.theme?.radius??e.borderRadius,fontFamily:e.theme?.font??e.fontFamily,themeTokens:e.theme,linkHandlers:e.linkHandlers,getLinkBearer:c.getLinkBearer,welcomeMessage:e.welcomeMessage,placeholder:e.placeholder,showTimestamps:e.showTimestamps,persistConversation:e.persistConversation,showHeader:e.showHeader,hideSystemMessages:e.hideSystemMessages,timestampFormat:e.timestampFormat,input:e.input,templateLayout:e.templateLayout,tiledesk:p,tiledeskIdentity:{userId:n,userName:c.identity.userName,departmentId:c.identity.departmentId,senderFullname:c.identity.senderFullname??c.identity.userName},templateActionAttributes:e.templateActionAttributes,uploadAdapter:y,historyAdapter:f,onError:c.onError,onMessage:c.onMessage},b=document.createElement("aikaara-chat-widget");return b.configure(m),m.title&&b.setAttribute("title",m.title),m.primaryColor&&b.setAttribute("primary-color",m.primaryColor),m.display&&b.setAttribute("display",m.display),m.display==="embed"&&(b.style.cssText="display:flex;flex-direction:column;width:100%;height:100%;min-height:0;"),c.container.appendChild(b),{widget:b,requestId:o,config:m,destroy(){b.remove()}}}function pf(c){if(typeof c!="string")return c;const e=document.querySelector(c);if(!e)throw new Error(`mountFromSlug: container "${c}" not found`);return e}async function Rl(c){const e=(c.configBase??"https://api.aikaara.com").replace(/\/$/,""),t=`${e}/api/v1/widget_configs/${encodeURIComponent(c.slug)}`;let r=null;try{r=await Ol(t,c.configHeaders)}catch(S){if(!c.fallbackConfig)throw S;console.warn(`[aikaara-chat-sdk] Widget config fetch failed for slug "${c.slug}" — using fallbackConfig.`,S)}const a={...c.fallbackConfig??{},...r??{},...c.overrides??{}};if(Pl(a),a.templates&&Object.keys(a.templates).length>0){a.components={...a.components??{}};for(const[S,v]of Object.entries(a.templates)){const x=`template:${S}`;a.components[x]||!v?.scriptUrl||!v?.render||(a.components[x]={kind:"iife-element",scriptUrl:v.scriptUrl,tag:v.render,...v.props?{props:v.props}:{}})}}const n=window;if(n.__aikaara_descriptor__={...n.__aikaara_descriptor__??{},templates:a.templates,components:a.components,razorpay:a.razorpay,title:a.title,cloud:a.cloud??n.__aikaara_descriptor__?.cloud,upload:a.upload??n.__aikaara_descriptor__?.upload,themeSource:a.themeSource??n.__aikaara_descriptor__?.themeSource},!a.auth)throw new Error(`mountFromSlug: widget_configs/${c.slug} descriptor must include "auth" block`);let i=null,s=c.user.id,o=c.user.name,l="",u=c.user.token,d=null;if(a.sso?.tokenSource){d=new Tl({descriptor:{provider:a.sso.provider,flow:a.sso.flow,skipLogin:a.sso.skipLogin,autoRefresh:a.sso.autoRefresh,tokenSource:a.sso.tokenSource,tokenSourceConfig:a.sso.tokenSourceConfig,fallback:a.sso.fallback,map:a.sso.map},initToken:c.user.partnerToken});const S=await d.get();u=async()=>(await d.get()).token,c.user.identity&&!c.user.identity.partnerToken&&(c.user.identity.partnerToken=S.token)}else if(a.sso&&a.sso.collect&&a.sso.collect.length>0){const S=`${e}/api/v1/projects/by-slug/${encodeURIComponent(c.slug)}/sso_exchange`;i=await new Al({descriptor:a.sso,providers:c.user.credentialProviders,exchangeUrl:S}).get(),s=i.extUid||s,o=o??i.displayName,l=i.userToken}a.preflight&&a.preflight.length&&await hf(a.preflight,{sessionToken:u,userId:s,projectId:a.tiledesk?.projectId??"",slug:c.slug,identity:c.user.identity});const p=new El(a.auth,u),y=await p.get(),f=y.fullName||o||s;window.__aikaara_runtime__={getChatJwt:async()=>(await p.get()).token,identity:c.user.identity,slug:c.slug};const m=d&&a.sso?.autoRefresh?async()=>{try{return await d.refresh(),p.reset(),(await p.get()).token}catch(S){return console.warn("[aikaara-chat-sdk] partner auto-refresh failed",S),null}}:null,b=a.upload,k=async()=>`Bearer ${b&&"tokenSource"in b&&b.tokenSource==="chat"?(await p.get()).token:await Nr(c.user.token)}`,g=c.hooks?.upload??(b&&b.mode==="presigned-3step"?al({...b,authHeader:k}):b&&b.mode==="direct"?no({endpoint:b.endpoint,fieldName:b.fieldName,extraFields:b.extraFields,headers:async()=>({authorization:await k()})}):void 0),_=await Ml({container:pf(c.container),config:a,userToken:l||void 0,identity:{userId:s,userName:f,departmentId:c.user.departmentId,senderFullname:f},tokenProvider:async()=>(await p.get()).token,historyTokenProvider:async()=>(await p.get()).token,uploadAdapter:g,historyAdapter:c.hooks?.history,conversationId:y.requestId,onError:c.hooks?.onError,onMessage:c.hooks?.onMessage,getLinkBearer:async S=>S==="none"?null:S==="chat"?(await p.get()).token:Nr(c.user.token)});return Object.assign(_,{fullName:f,requestId:y.requestId,descriptor:a,async refreshAuth(){p.reset(),await p.get()},async refreshPartnerAuth(){return m?m():null}})}function gf(c){lo();const e=document.createElement("aikaara-chat-widget"),t={baseUrl:"base-url",userToken:"user-token",apiKey:"api-key",title:"title",subtitle:"subtitle",theme:"theme",primaryColor:"primary-color",position:"position",width:"width",height:"height",placeholder:"placeholder",welcomeMessage:"welcome-message",avatarUrl:"avatar-url"};for(const[r,a]of Object.entries(t)){const n=c[r];n!=null&&e.setAttribute(a,String(n))}return e.configure(c),document.body.appendChild(e),e}function mf(){const c=document.querySelector("aikaara-chat-widget");c&&c.remove()}class jl extends HTMLElement{shadow;payload=null;constructor(){super(),this.shadow=this.attachShadow({mode:"open"})}connectedCallback(){this.render()}setPayload(e){this.payload=e,this.render()}render(){const e=this.payload;this.shadow.innerHTML=`
987
987
  <style>
988
988
  :host { display: block; margin-top: 8px; }
989
989
  button {