@aikaara/chat-sdk 0.8.6 → 0.8.8

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
- "use strict";class Is{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 Vr{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 Is(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 Vi{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,ho="#6366f1",Yl=12,Ql="system-ui, -apple-system, sans-serif",fo="Type a message...",Jl="bottom-right",Xl="light",Zl={x:20,y:20},Br="aikaara_conversation_id";class Ts extends Vi{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 Vr(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 Vr(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 Cs{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 Os{_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(a=>a.externalId&&a.externalId===e.externalId):void 0;return r?(Object.assign(r,e,{id:r.id}),{message:r,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=[]}}class Ps{_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(Br)}catch{}}loadFromStorage(){if(!this.persist)return null;try{return localStorage.getItem(Br)}catch{return null}}saveToStorage(e){try{localStorage.setItem(Br,e)}catch{}}}var Gi=Object.defineProperty,ec=Object.getOwnPropertyDescriptor,tc=Object.getOwnPropertyNames,rc=Object.prototype.hasOwnProperty,He=(c,e)=>()=>(c&&(e=c(c=0)),e),pe=(c,e)=>()=>(e||c((e={exports:{}}).exports,e),e.exports),Lt=(c,e)=>{for(var t in e)Gi(c,t,{get:e[t],enumerable:!0})},nc=(c,e,t,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let a of tc(e))!rc.call(c,a)&&a!==t&&Gi(c,a,{get:()=>e[a],enumerable:!(r=ec(e,a))||r.enumerable});return c},Oe=c=>nc(Gi({},"__esModule",{value:!0}),c),le=He(()=>{}),Pe={};Lt(Pe,{_debugEnd:()=>Tn,_debugProcess:()=>In,_events:()=>qn,_eventsCount:()=>Hn,_exiting:()=>dn,_fatalExceptions:()=>En,_getActiveHandles:()=>Bs,_getActiveRequests:()=>Us,_kill:()=>mn,_linkedBinding:()=>Ls,_maxListeners:()=>Wn,_preload_modules:()=>Fn,_rawDebug:()=>un,_startProfilerIdleNotifier:()=>Cn,_stopProfilerIdleNotifier:()=>On,_tickCallback:()=>An,abort:()=>jn,addListener:()=>zn,allowedNodeEnvironmentFlags:()=>kn,arch:()=>Yr,argv:()=>Xr,argv0:()=>Dn,assert:()=>Ds,binding:()=>nn,browser:()=>cn,chdir:()=>an,config:()=>pn,cpuUsage:()=>qt,cwd:()=>sn,debugPort:()=>Bn,default:()=>Qi,dlopen:()=>Ns,domain:()=>fn,emit:()=>Qn,emitWarning:()=>rn,env:()=>Jr,execArgv:()=>Zr,execPath:()=>Un,exit:()=>wn,features:()=>Sn,hasUncaughtExceptionCaptureCallback:()=>Fs,hrtime:()=>ir,kill:()=>vn,listeners:()=>Ws,memoryUsage:()=>yn,moduleLoadList:()=>hn,nextTick:()=>Rs,off:()=>Vn,on:()=>nt,once:()=>Kn,openStdin:()=>_n,pid:()=>Ln,platform:()=>Qr,ppid:()=>Nn,prependListener:()=>Jn,prependOnceListener:()=>Xn,reallyExit:()=>gn,release:()=>ln,removeAllListeners:()=>Yn,removeListener:()=>Gn,resourceUsage:()=>bn,setSourceMapsEnabled:()=>$n,setUncaughtExceptionCaptureCallback:()=>xn,stderr:()=>Mn,stdin:()=>Rn,stdout:()=>Pn,title:()=>Gr,umask:()=>on,uptime:()=>$s,version:()=>en,versions:()=>tn});function Yi(c){throw new Error("Node.js process "+c+" is not supported by JSPM core outside of Node.js")}function ic(){!St||!_t||(St=!1,_t.length?et=_t.concat(et):Vt=-1,et.length&&Ms())}function Ms(){if(!St){var c=setTimeout(ic,0);St=!0;for(var e=et.length;e;){for(_t=et,et=[];++Vt<e;)_t&&_t[Vt].run();Vt=-1,e=et.length}_t=null,St=!1,clearTimeout(c)}}function Rs(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];et.push(new js(c,e)),et.length===1&&!St&&setTimeout(Ms,0)}function js(c,e){this.fun=c,this.array=e}function Be(){}function Ls(c){Yi("_linkedBinding")}function Ns(c){Yi("dlopen")}function Us(){return[]}function Bs(){return[]}function Ds(c,e){if(!c)throw new Error(e||"assertion error")}function Fs(){return!1}function $s(){return ot.now()/1e3}function ir(c){var e=Math.floor((Date.now()-ot.now())*.001),t=ot.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+=or)),[r,a]}function nt(){return Qi}function Ws(c){return[]}var et,St,_t,Vt,Gr,Yr,Qr,Jr,Xr,Zr,en,tn,rn,nn,on,sn,an,ln,cn,un,hn,fn,dn,pn,gn,mn,qt,bn,yn,vn,wn,_n,kn,Sn,En,xn,An,In,Tn,Cn,On,Pn,Mn,Rn,jn,Ln,Nn,Un,Bn,Dn,Fn,$n,ot,Dr,or,Wn,qn,Hn,zn,Kn,Vn,Gn,Yn,Qn,Jn,Xn,Qi,oc=He(()=>{le(),ue(),ce(),et=[],St=!1,Vt=-1,js.prototype.run=function(){this.fun.apply(null,this.array)},Gr="browser",Yr="x64",Qr="browser",Jr={PATH:"/usr/bin",LANG:typeof navigator<"u"?navigator.language+".UTF-8":void 0,PWD:"/",HOME:"/home",TMP:"/tmp"},Xr=["/usr/bin/node"],Zr=[],en="v16.8.0",tn={},rn=function(c,e){console.warn((e?e+": ":"")+c)},nn=function(c){Yi("binding")},on=function(c){return 0},sn=function(){return"/"},an=function(c){},ln={name:"node",sourceUrl:"",headersUrl:"",libUrl:""},cn=!0,un=Be,hn=[],fn={},dn=!1,pn={},gn=Be,mn=Be,qt=function(){return{}},bn=qt,yn=qt,vn=Be,wn=Be,_n=Be,kn={},Sn={inspector:!1,debug:!1,uv:!1,ipv6:!1,tls_alpn:!1,tls_sni:!1,tls_ocsp:!1,tls:!1,cached_builtins:!0},En=Be,xn=Be,An=Be,In=Be,Tn=Be,Cn=Be,On=Be,Pn=void 0,Mn=void 0,Rn=void 0,jn=Be,Ln=2,Nn=1,Un="/bin/usr/node",Bn=9229,Dn="node",Fn=[],$n=Be,ot={now:typeof performance<"u"?performance.now.bind(performance):void 0,timing:typeof performance<"u"?performance.timing:void 0},ot.now===void 0&&(Dr=Date.now(),ot.timing&&ot.timing.navigationStart&&(Dr=ot.timing.navigationStart),ot.now=()=>Date.now()-Dr),or=1e9,ir.bigint=function(c){var e=ir(c);return typeof BigInt>"u"?e[0]*or+e[1]:BigInt(e[0]*or)+BigInt(e[1])},Wn=10,qn={},Hn=0,zn=nt,Kn=nt,Vn=nt,Gn=nt,Yn=nt,Qn=Be,Jn=nt,Xn=nt,Qi={version:en,versions:tn,arch:Yr,platform:Qr,browser:cn,release:ln,_rawDebug:un,moduleLoadList:hn,binding:nn,_linkedBinding:Ls,_events:qn,_eventsCount:Hn,_maxListeners:Wn,on:nt,addListener:zn,once:Kn,off:Vn,removeListener:Gn,removeAllListeners:Yn,emit:Qn,prependListener:Jn,prependOnceListener:Xn,listeners:Ws,domain:fn,_exiting:dn,config:pn,dlopen:Ns,uptime:$s,_getActiveRequests:Us,_getActiveHandles:Bs,reallyExit:gn,_kill:mn,cpuUsage:qt,resourceUsage:bn,memoryUsage:yn,kill:vn,exit:wn,openStdin:_n,allowedNodeEnvironmentFlags:kn,assert:Ds,features:Sn,_fatalExceptions:En,setUncaughtExceptionCaptureCallback:xn,hasUncaughtExceptionCaptureCallback:Fs,emitWarning:rn,nextTick:Rs,_tickCallback:An,_debugProcess:In,_debugEnd:Tn,_startProfilerIdleNotifier:Cn,_stopProfilerIdleNotifier:On,stdout:Pn,stdin:Rn,stderr:Mn,abort:jn,umask:on,chdir:an,cwd:sn,env:Jr,title:Gr,argv:Xr,execArgv:Zr,pid:Ln,ppid:Nn,execPath:Un,debugPort:Bn,hrtime:ir,argv0:Dn,_preload_modules:Fn,setSourceMapsEnabled:$n}}),ce=He(()=>{oc()});function sc(){if(Zn)return Ot;Zn=!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(b){var f=b.length;if(f%4>0)throw new Error("Invalid string. Length must be a multiple of 4");var g=b.indexOf("=");g===-1&&(g=f);var y=g===f?0:4-g%4;return[g,y]}function s(b){var f=i(b),g=f[0],y=f[1];return(g+y)*3/4-y}function o(b,f,g){return(f+g)*3/4-g}function l(b){var f,g=i(b),y=g[0],k=g[1],m=new t(o(b,y,k)),w=0,E=k>0?y-4:y,v;for(v=0;v<E;v+=4)f=e[b.charCodeAt(v)]<<18|e[b.charCodeAt(v+1)]<<12|e[b.charCodeAt(v+2)]<<6|e[b.charCodeAt(v+3)],m[w++]=f>>16&255,m[w++]=f>>8&255,m[w++]=f&255;return k===2&&(f=e[b.charCodeAt(v)]<<2|e[b.charCodeAt(v+1)]>>4,m[w++]=f&255),k===1&&(f=e[b.charCodeAt(v)]<<10|e[b.charCodeAt(v+1)]<<4|e[b.charCodeAt(v+2)]>>2,m[w++]=f>>8&255,m[w++]=f&255),m}function u(b){return c[b>>18&63]+c[b>>12&63]+c[b>>6&63]+c[b&63]}function d(b,f,g){for(var y,k=[],m=f;m<g;m+=3)y=(b[m]<<16&16711680)+(b[m+1]<<8&65280)+(b[m+2]&255),k.push(u(y));return k.join("")}function p(b){for(var f,g=b.length,y=g%3,k=[],m=16383,w=0,E=g-y;w<E;w+=m)k.push(d(b,w,w+m>E?E:w+m));return y===1?(f=b[g-1],k.push(c[f>>2]+c[f<<4&63]+"==")):y===2&&(f=(b[g-2]<<8)+b[g-1],k.push(c[f>>10]+c[f>>4&63]+c[f<<2&63]+"=")),k.join("")}return Ot}function ac(){return ei?Ht:(ei=!0,Ht.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,b=c[e+d];for(d+=p,n=b&(1<<-u)-1,b>>=-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:(b?-1:1)*(1/0);i=i+Math.pow(2,r),n=n-l}return(b?-1:1)*i*Math.pow(2,n-r)},Ht.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,b=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+b]=s&255,b+=f,s/=256,a-=8);for(i=i<<a|s,l+=a;l>0;c[t+b]=i&255,b+=f,i/=256,l-=8);c[t+b-f]|=g*128},Ht)}function lc(){if(ti)return pt;ti=!0;let c=sc(),e=ac(),t=typeof Symbol=="function"&&typeof Symbol.for=="function"?Symbol.for("nodejs.util.inspect.custom"):null;pt.Buffer=i,pt.SlowBuffer=k,pt.INSPECT_MAX_BYTES=50;let r=2147483647;pt.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 b(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:y(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:y(h.length)|0,A=n(_);for(let U=0;U<_;U+=1)A[U]=h[U]&255;return A}function b(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 _=y(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 y(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="",_=pt.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 D=4096;function N(h){let _=h.length;if(_<=D)return String.fromCharCode.apply(String,h);let A="",U=0;for(;U<_;)A+=String.fromCharCode.apply(String,h.slice(U,U+=D));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 F(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||F(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||F(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,_||F(h,1,this.length),this[h]},i.prototype.readUint16LE=i.prototype.readUInt16LE=function(h,_){return h=h>>>0,_||F(h,2,this.length),this[h]|this[h+1]<<8},i.prototype.readUint16BE=i.prototype.readUInt16BE=function(h,_){return h=h>>>0,_||F(h,2,this.length),this[h]<<8|this[h+1]},i.prototype.readUint32LE=i.prototype.readUInt32LE=function(h,_){return h=h>>>0,_||F(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,_||F(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||F(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||F(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,_||F(h,1,this.length),this[h]&128?(255-this[h]+1)*-1:this[h]},i.prototype.readInt16LE=function(h,_){h=h>>>0,_||F(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,_||F(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,_||F(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,_||F(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]*2**8+this[++h]*2**16+this[++h]*2**24)}),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]*2**24+this[++h]*2**16+this[++h]*2**8+A)}),i.prototype.readFloatLE=function(h,_){return h=h>>>0,_||F(h,4,this.length),e.read(this,h,!0,23,4)},i.prototype.readFloatBE=function(h,_){return h=h>>>0,_||F(h,4,this.length),e.read(this,h,!1,23,4)},i.prototype.readDoubleLE=function(h,_){return h=h>>>0,_||F(h,8,this.length),e.read(this,h,!0,52,8)},i.prototype.readDoubleBE=function(h,_){return h=h>>>0,_||F(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)>2**32?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 pt}var Ot,Zn,Ht,ei,pt,ti,cc=He(()=>{le(),ue(),ce(),Ot={},Zn=!1,Ht={},ei=!1,pt={},ti=!1}),Le={};Lt(Le,{Buffer:()=>Cr,INSPECT_MAX_BYTES:()=>qs,default:()=>it,kMaxLength:()=>Hs});var it,Cr,qs,Hs,Ne=He(()=>{le(),ue(),ce(),cc(),it=lc(),it.Buffer,it.SlowBuffer,it.INSPECT_MAX_BYTES,it.kMaxLength,Cr=it.Buffer,qs=it.INSPECT_MAX_BYTES,Hs=it.kMaxLength}),ue=He(()=>{Ne()}),Re=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}}),zs=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}=zs(),{AggregateError:a}=Re(),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 b(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(b(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 y(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(y),hideStackFrames:g,codes:u}}),Yt=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}),bt={};Lt(bt,{EventEmitter:()=>Ks,default:()=>Pt,defaultMaxListeners:()=>Vs,init:()=>Gs,listenerCount:()=>Ys,on:()=>Qs,once:()=>Js});function uc(){if(ri)return zt;ri=!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)}zt=n,zt.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?y(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):b.call(E,v)},n.prototype.listenerCount=b;function b(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 y(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 zt}var zt,ri,Pt,Ks,Vs,Gs,Ys,Qs,Js,xt=He(()=>{le(),ue(),ce(),zt={},ri=!1,Pt=uc(),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:Ks,defaultMaxListeners:Vs,init:Gs,listenerCount:Ys,on:Qs,once:Js}=Pt}),qe=pe((c,e)=>{le(),ue(),ce();var t=(Ne(),Oe(Le)),{format:r,inspect:a}=zs(),{codes:{ERR_INVALID_ARG_TYPE:n}}=We(),{kResistStopPropagation:i,AggregateError:s,SymbolDispose:o}=Re(),l=globalThis.AbortSignal||Yt().AbortSignal,u=globalThis.AbortController||Yt().AbortController,d=Object.getPrototypeOf(async function(){}).constructor,p=globalThis.Blob||t.Blob,b=typeof p<"u"?function(y){return y instanceof p}:function(y){return!1},f=(y,k)=>{if(y!==void 0&&(y===null||typeof y!="object"||!("aborted"in y)))throw new n(k,"AbortSignal",y)},g=(y,k)=>{if(typeof y!="function")throw new n(k,"Function",y)};e.exports={AggregateError:s,kEmptyObject:Object.freeze({}),once(y){let k=!1;return function(...m){k||(k=!0,y.apply(this,m))}},createDeferredPromise:function(){let y,k;return{promise:new Promise((m,w)=>{y=m,k=w}),resolve:y,reject:k}},promisify(y){return new Promise((k,m)=>{y((w,...E)=>w?m(w):k(...E))})},debuglog(){return function(){}},format:r,inspect:a,types:{isAsyncFunction(y){return y instanceof d},isArrayBufferView(y){return ArrayBuffer.isView(y)}},isBlob:b,deprecate(y,k){return y},addAbortListener:(xt(),Oe(bt)).addAbortListener||function(y,k){if(y===void 0)throw new n("signal","AbortSignal",y);f(y,"signal"),g(k,"listener");let m;return y.aborted?queueMicrotask(()=>k()):(y.addEventListener("abort",k,{__proto__:null,once:!0,[i]:!0}),m=()=>{y.removeEventListener("abort",k)}),{__proto__:null,[o](){var w;(w=m)===null||w===void 0||w()}}},AbortSignalAny:l.any||function(y){if(y.length===1)return y[0];let k=new u,m=()=>k.abort();return y.forEach(w=>{f(w,"signals"),w.addEventListener("abort",m,{once:!0})}),k.signal.addEventListener("abort",()=>{y.forEach(w=>w.removeEventListener("abort",m))},{once:!0}),k.signal}},e.exports.promisify.custom=Symbol.for("nodejs.util.promisify.custom")}),Qt=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:b,StringPrototypeToUpperCase:f,StringPrototypeTrim:g}=Re(),{hideStackFrames:y,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}=qe(),{isAsyncFunction:S,isArrayBufferView:I}=qe().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 D(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=y((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=y((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=y((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 F=y((q,ge,ve)=>{if(!r(ve,q)){let se="must be one of: "+a(n(ve,Te=>typeof Te=="string"?`'${Te}'`:b(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=y((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=y((q,ge)=>{if(q!=null&&typeof q!="object"&&typeof q!="function")throw new m(ge,"a dictionary",q)}),te=y((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=y((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=y((q,ge)=>{if(q!==void 0&&(q===null||typeof q!="object"||!("aborted"in q)))throw new m(ge,"AbortSignal",q)}),oe=y((q,ge)=>{if(typeof q!="function")throw new m(ge,"Function",q)}),R=y((q,ge)=>{if(typeof q!="function"||S(q))throw new m(ge,"Function",q)}),$=y((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:D,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:F,validatePlainFunction:R,validatePort:Q,validateSignalName:ne,validateString:K,validateUint32:Y,validateUndefined:$,validateUnion:ee,validateAbortSignal:me,validateLinkHeaderValue:ye}}),At=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 b(){!u||!d||(u=!1,d.length?l=d.concat(l):p=-1,l.length&&f())}function f(){if(!u){var k=s(b);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 y(){}t.on=y,t.addListener=y,t.once=y,t.off=y,t.removeListener=y,t.removeAllListeners=y,t.emit=y,t.prependListener=y,t.prependOnceListener=y,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}}),ct=pe((c,e)=>{le(),ue(),ce();var{SymbolAsyncIterator:t,SymbolIterator:r,SymbolFor:a}=Re(),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 b(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 y(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 y(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(!b(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(!b(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:b(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 D(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 F(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:F,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:y,isReadableEnded:I,isReadableFinished:M,isReadableErrored:D,isNodeStream:g,isWebStream:w,isWritable:B,isWritableNodeStream:b,isWritableStream:k,isWritableEnded:x,isWritableFinished:S,isWritableErrored:W,isServerRequest:K,isServerResponse:Y,willEmitClose:re,isTransformStream:m}}),yt=pe((c,e)=>{le(),ue(),ce();var t=At(),{AbortError:r,codes:a}=We(),{ERR_INVALID_ARG_TYPE:n,ERR_STREAM_PREMATURE_CLOSE:i}=a,{kEmptyObject:s,once:o}=qe(),{validateAbortSignal:l,validateFunction:u,validateObject:d,validateBoolean:p}=Qt(),{Promise:b,PromisePrototypeThen:f,SymbolDispose:g}=Re(),{isClosed:y,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}=ct(),D;function N(F){return F.setHeader&&typeof F.abort=="function"}var ae=()=>{};function Y(F,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(F)||I(F))return K(F,Z,P);if(!B(F))throw new n("stream",["ReadableStream","WritableStream","Stream"],F);let te=(J=Z.readable)!==null&&J!==void 0?J:m(F),we=(be=Z.writable)!==null&&be!==void 0?be:S(F),V=F._writableState,L=F._readableState,ne=()=>{F.writable||Q()},H=T(F)&&m(F)===te&&S(F)===we,G=M(F,!1),Q=()=>{G=!0,F.destroyed&&(H=!1),!(H&&(!F.readable||te))&&(!te||me)&&P.call(F)},me=E(F,!1),oe=()=>{me=!0,F.destroyed&&(H=!1),!(H&&(!F.writable||we))&&(!we||G)&&P.call(F)},R=q=>{P.call(F,q)},$=y(F),ee=()=>{$=!0;let q=O(F)||v(F);if(q&&typeof q!="boolean")return P.call(F,q);if(te&&!me&&m(F,!0)&&!E(F,!1))return P.call(F,new i);if(we&&!G&&!M(F,!1))return P.call(F,new i);P.call(F)},fe=()=>{$=!0;let q=O(F)||v(F);if(q&&typeof q!="boolean")return P.call(F,q);P.call(F)},de=()=>{F.req.on("finish",Q)};N(F)?(F.on("complete",Q),H||F.on("abort",ee),F.req?de():F.on("request",de)):we&&!V&&(F.on("end",ne),F.on("close",ne)),!H&&typeof F.aborted=="boolean"&&F.on("aborted",ee),F.on("end",oe),F.on("finish",Q),Z.error!==!1&&F.on("error",R),F.on("close",ee),$?t.nextTick(ee):V!=null&&V.errorEmitted||L!=null&&L.errorEmitted?H||t.nextTick(fe):(!te&&(!H||k(F))&&(G||x(F)===!1)||!we&&(!H||x(F))&&(me||k(F)===!1)||L&&F.req&&F.aborted)&&t.nextTick(fe);let ye=()=>{P=ae,F.removeListener("aborted",ee),F.removeListener("complete",Q),F.removeListener("abort",ee),F.removeListener("request",de),F.req&&F.req.removeListener("finish",Q),F.removeListener("end",ne),F.removeListener("close",ne),F.removeListener("finish",Q),F.removeListener("end",oe),F.removeListener("error",R),F.removeListener("close",ee)};if(Z.signal&&!$){let q=()=>{let ge=P;ye(),ge.call(F,new r(void 0,{cause:Z.signal.reason}))};if(Z.signal.aborted)t.nextTick(q);else{D=D||qe().addAbortListener;let ge=D(Z.signal,q),ve=P;P=o((...se)=>{ge[g](),ve.apply(F,se)})}}return ye}function K(F,Z,P){let J=!1,be=ae;if(Z.signal)if(be=()=>{J=!0,P.call(F,new r(void 0,{cause:Z.signal.reason}))},Z.signal.aborted)t.nextTick(be);else{D=D||qe().addAbortListener;let we=D(Z.signal,be),V=P;P=o((...L)=>{we[g](),V.apply(F,L)})}let te=(...we)=>{J||t.nextTick(()=>P.apply(F,we))};return f(F[W].promise,te,te),ae}function re(F,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 b((be,te)=>{let we=Y(F,Z,V=>{J&&we(),V?te(V):be()})})}e.exports=Y,e.exports.finished=re}),Nt=pe((c,e)=>{le(),ue(),ce();var t=At(),{aggregateTwoErrors:r,codes:{ERR_MULTIPLE_CALLBACK:a},AbortError:n}=We(),{Symbol:i}=Re(),{kIsDestroyed:s,isDestroyed:o,isFinished:l,isServerRequest:u}=ct(),d=i("kDestroy"),p=i("kConstruct");function b(T,W,D){T&&(T.stack,W&&!W.errored&&(W.errored=T),D&&!D.errored&&(D.errored=T))}function f(T,W){let D=this._readableState,N=this._writableState,ae=N||D;return N!=null&&N.destroyed||D!=null&&D.destroyed?(typeof W=="function"&&W(),this):(b(T,N,D),N&&(N.destroyed=!0),D&&(D.destroyed=!0),ae.constructed?g(this,T,W):this.once(d,function(Y){g(this,r(Y,T),W)}),this)}function g(T,W,D){let N=!1;function ae(Y){if(N)return;N=!0;let K=T._readableState,re=T._writableState;b(Y,re,K),re&&(re.closed=!0),K&&(K.closed=!0),typeof D=="function"&&D(Y),Y?t.nextTick(y,T,Y):t.nextTick(k,T)}try{T._destroy(W||null,ae)}catch(Y){ae(Y)}}function y(T,W){m(T,W),k(T)}function k(T){let W=T._readableState,D=T._writableState;D&&(D.closeEmitted=!0),W&&(W.closeEmitted=!0),(D!=null&&D.emitClose||W!=null&&W.emitClose)&&T.emit("close")}function m(T,W){let D=T._readableState,N=T._writableState;N!=null&&N.errorEmitted||D!=null&&D.errorEmitted||(N&&(N.errorEmitted=!0),D&&(D.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,D){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),D?t.nextTick(m,T,W):m(T,W))}function v(T,W){if(typeof T._construct!="function")return;let D=T._readableState,N=T._writableState;D&&(D.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 D(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(D,N)})}catch(N){t.nextTick(D,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}}),Ji=pe((c,e)=>{le(),ue(),ce();var{ArrayIsArray:t,ObjectSetPrototypeOf:r}=Re(),{EventEmitter:a}=(xt(),Oe(bt));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",b),l.on("close",f));let p=!1;function b(){p||(p=!0,s.end())}function f(){p||(p=!0,typeof s.destroy=="function"&&s.destroy())}function g(k){y(),a.listenerCount(this,"error")===0&&this.emit("error",k)}i(l,"error",g),i(s,"error",g);function y(){l.removeListener("data",u),s.removeListener("drain",d),l.removeListener("end",b),l.removeListener("close",f),l.removeListener("error",g),s.removeListener("error",g),l.removeListener("end",y),l.removeListener("close",y),s.removeListener("close",y)}return l.on("end",y),l.on("close",y),s.on("close",y),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}}),Mr=pe((c,e)=>{le(),ue(),ce();var{SymbolDispose:t}=Re(),{AbortError:r,codes:a}=We(),{isNodeStream:n,isWebStream:i,kControllerErrorFunction:s}=ct(),o=yt(),{ERR_INVALID_ARG_TYPE:l}=a,u,d=(p,b)=>{if(typeof p!="object"||!("aborted"in p))throw new l(b,"AbortSignal",p)};e.exports.addAbortSignal=function(p,b){if(d(p,"signal"),!n(b)&&!i(b))throw new l("stream",["ReadableStream","WritableStream","Stream"],b);return e.exports.addAbortSignalNoValidate(p,b)},e.exports.addAbortSignalNoValidate=function(p,b){if(typeof p!="object"||!("aborted"in p))return b;let f=n(b)?()=>{b.destroy(new r(void 0,{cause:p.reason}))}:()=>{b[s](new r(void 0,{cause:p.reason}))};if(p.aborted)f();else{u=u||qe().addAbortListener;let g=u(p,f);o(b,g[t])}return b}}),hc=pe((c,e)=>{le(),ue(),ce();var{StringPrototypeSlice:t,SymbolIterator:r,TypedArrayPrototypeSet:a,Uint8Array:n}=Re(),{Buffer:i}=(Ne(),Oe(Le)),{inspect:s}=qe();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 b=d.data;if(o>b.length)a(l,b,u-o),o-=b.length;else{o===b.length?(a(l,b,u-o),++p,d.next?this.head=d.next:this.head=this.tail=null):(a(l,new n(b.buffer,b.byteOffset,o),u-o),this.head=d,d.data=b.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})}}}),Rr=pe((c,e)=>{le(),ue(),ce();var{MathFloor:t,NumberIsInteger:r}=Re(),{validateInteger:a}=Qt(),{ERR_INVALID_ARG_VALUE:n}=We().codes,i=16*1024,s=16;function o(p,b,f){return p.highWaterMark!=null?p.highWaterMark:b?p[f]:null}function l(p){return p?s:i}function u(p,b){a(b,"value",0),p?s=b:i=b}function d(p,b,f,g){let y=o(b,g,f);if(y!=null){if(!r(y)||y<0){let k=g?`options.${f}`:"options.highWaterMark";throw new n(k,y)}return t(y)}return l(p.objectMode)}e.exports={getHighWaterMark:d,getDefaultHighWaterMark:l,setDefaultHighWaterMark:u}}),fc=pe((c,e)=>{le(),ue(),ce();var t=(Ne(),Oe(Le)),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)}}),dc=pe(c=>{le(),ue(),ce();var e=fc().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=b,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=y,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 b(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 y(m){return m.toString(this.encoding)}function k(m){return m&&m.length?this.write(m):""}}),Xs=pe((c,e)=>{le(),ue(),ce();var t=At(),{PromisePrototypeThen:r,SymbolAsyncIterator:a,SymbolIterator:n}=Re(),{Buffer:i}=(Ne(),Oe(Le)),{ERR_INVALID_ARG_TYPE:s,ERR_STREAM_NULL_VALUES:o}=We().codes;function l(u,d,p){let b;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,b=d[a]();else if(d&&d[n])f=!1,b=d[n]();else throw new s("iterable",["Iterable"],d);let g=new u({objectMode:!0,highWaterMark:1,...p}),y=!1;g._read=function(){y||(y=!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 b.throw=="function";if(E&&v){let{value:x,done:S}=await b.throw(w);if(await x,S)return}if(typeof b.return=="function"){let{value:x}=await b.return();await x}}async function m(){for(;;){try{let{value:w,done:E}=f?await b.next():b.next();if(E)g.push(null);else{let v=w&&typeof w.then=="function"?await w:w;if(v===null)throw y=!1,new o;if(g.push(v))continue;y=!1}}catch(w){g.destroy(w)}break}}return g}e.exports=l}),jr=pe((c,e)=>{le(),ue(),ce();var t=At(),{ArrayPrototypeIndexOf:r,NumberIsInteger:a,NumberIsNaN:n,NumberParseInt:i,ObjectDefineProperties:s,ObjectKeys:o,ObjectSetPrototypeOf:l,Promise:u,SafeSet:d,SymbolAsyncDispose:p,SymbolAsyncIterator:b,Symbol:f}=Re();e.exports=se,se.ReadableState=ve;var{EventEmitter:g}=(xt(),Oe(bt)),{Stream:y,prependListener:k}=Ji(),{Buffer:m}=(Ne(),Oe(Le)),{addAbortSignal:w}=Mr(),E=yt(),v=qe().debuglog("stream",C=>{v=C}),x=hc(),S=Nt(),{getHighWaterMark:I,getDefaultHighWaterMark:M}=Rr(),{aggregateTwoErrors:O,codes:{ERR_INVALID_ARG_TYPE:B,ERR_METHOD_NOT_IMPLEMENTED:T,ERR_OUT_OF_RANGE:W,ERR_STREAM_PUSH_AFTER_EOF:D,ERR_STREAM_UNSHIFT_AFTER_END_EVENT:N},AbortError:ae}=We(),{validateObject:Y}=Qt(),K=f("kPaused"),{StringDecoder:re}=dc(),F=Xs();l(se.prototype,y.prototype),l(se,y);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)),y.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,je;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="":y._isUint8Array(j)?(j=y._uint8ArrayToBuffer(j),_e=""):j!=null&&(je=new B("chunk",["string","Buffer","Uint8Array"],j))),je)P(C,je);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 D);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?Je(this):he(this),null;if(C=U(C,j),C===0&&j.ended)return j.length===0&&Je(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(je){P(this,je)}j.state&=~L,j.reading||(C=U(_e,j))}let Ee;return C>0?Ee=Tt(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&&Je(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,Ye(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?$e:wt;Se.endEmitted?t.nextTick(Ee):_e.once("end",Ee),C.on("unpipe",je);function je(Ze,rt){v("onunpipe"),Ze===_e&&rt&&rt.hasUnpiped===!1&&(rt.hasUnpiped=!0,$t())}function $e(){v("onend"),C.end()}let Ve,Ft=!1;function $t(){v("cleanup"),C.removeListener("close",Xe),C.removeListener("finish",ft),Ve&&C.removeListener("drain",Ve),C.removeListener("error",vt),C.removeListener("unpipe",je),_e.removeListener("end",$e),_e.removeListener("end",wt),_e.removeListener("data",Zt),Ft=!0,Ve&&Se.awaitDrainWriters&&(!C._writableState||C._writableState.needDrain)&&Ve()}function Wt(){Ft||(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()),Ve||(Ve=xe(_e,C),C.on("drain",Ve))}_e.on("data",Zt);function Zt(Ze){v("ondata");let rt=C.write(Ze);v("dest.write",rt),rt===!1&&Wt()}function vt(Ze){if(v("onerror",Ze),wt(),C.removeListener("error",vt),C.listenerCount("error")===0){let rt=C._writableState||C._readableState;rt&&!rt.errorEmitted?P(C,Ze):C.emit("error",Ze)}}k(C,"error",vt);function Xe(){C.removeListener("finish",ft),wt()}C.once("close",Xe);function ft(){v("onfinish"),C.removeListener("close",Xe),wt()}C.once("finish",ft);function wt(){v("unpipe"),_e.unpipe(C)}return C.emit("pipe",_e),C.writableNeedDrain===!0?Wt():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 je=0;je<Ee.length;je++)Ee[je].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=y.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=y.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=y.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,Ce(this,C)),C[K]=!1,this};function Ce(C,j){j.resumeScheduled||(j.resumeScheduled=!0,t.nextTick(Ge,C,j))}function Ge(C,j){v("resume",j.reading),j.reading||C.read(0),j.resumeScheduled=!1,C.emit("resume"),Ye(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 Ye(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[b]=function(){return Ue(this)},se.prototype.iterator=function(C){return C!==void 0&&Y(C,"options"),Ue(this,C)};function Ue(C,j){typeof C.read!="function"&&(C=se.wrap(C,{objectMode:!0}));let _e=Qe(C,j);return _e.stream=C,_e}async function*Qe(C,j){let _e=Z;function Se($e){this===C?(_e(),_e=Z):_e=$e}C.on("readable",Se);let Ee,je=E(C,{writable:!1},$e=>{Ee=$e?O(Ee,$e):null,_e(),_e=Z});try{for(;;){let $e=C.destroyed?null:C.read();if($e!==null)yield $e;else{if(Ee)throw Ee;if(Ee===null)return;await new u(Se)}}}catch($e){throw Ee=O(Ee,$e),Ee}finally{(Ee||j?.destroyOnReturn!==!1)&&(Ee===void 0||C._readableState.autoDestroy)?S.destroyer(C,null):(C.off("readable",Se),je())}}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=Tt;function Tt(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 Je(C){let j=C._readableState;v("endReadable",j.endEmitted),j.endEmitted||(j.ended=!0,t.nextTick(ze,j,C))}function ze(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(Xt,j);else if(C.autoDestroy){let _e=j._writableState;(!_e||_e.autoDestroy&&(_e.finished||_e.writable===!1))&&j.destroy()}}}function Xt(C){C.writable&&!C.writableEnded&&!C.destroyed&&C.end()}se.from=function(C,j){return F(se,C,j)};var Ct;function Dt(){return Ct===void 0&&(Ct={}),Ct}se.fromWeb=function(C,j){return Dt().newStreamReadableFromReadableStream(C,j)},se.toWeb=function(C,j){return Dt().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,je){S.destroyer(C,Ee),je(Ee)}}).wrap(C)}}),Xi=pe((c,e)=>{le(),ue(),ce();var t=At(),{ArrayPrototypeSlice:r,Error:a,FunctionPrototypeSymbolHasInstance:n,ObjectDefineProperty:i,ObjectDefineProperties:s,ObjectSetPrototypeOf:o,StringPrototypeToLowerCase:l,Symbol:u,SymbolHasInstance:d}=Re();e.exports=Y,Y.WritableState=N;var{EventEmitter:p}=(xt(),Oe(bt)),b=Ji().Stream,{Buffer:f}=(Ne(),Oe(Le)),g=Nt(),{addAbortSignal:y}=Mr(),{getHighWaterMark:k,getDefaultHighWaterMark:m}=Rr(),{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,b.prototype),o(Y,b);function W(){}var D=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[D]=[]}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&&y(R.signal,this)),b.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(b._isUint8Array($))$=b._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 F(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[D].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,F(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;F(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[D].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=$[D].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=$[D].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[D].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)}}),pc=pe((c,e)=>{le(),ue(),ce();var t=At(),r=(Ne(),Oe(Le)),{isReadable:a,isWritable:n,isIterable:i,isNodeStream:s,isReadableNodeStream:o,isWritableNodeStream:l,isDuplexNodeStream:u,isReadableStream:d,isWritableStream:p}=ct(),b=yt(),{AbortError:f,codes:{ERR_INVALID_ARG_TYPE:g,ERR_INVALID_RETURN_VALUE:y}}=We(),{destroyer:k}=Nt(),m=at(),w=jr(),E=Xi(),{createDeferredPromise:v}=qe(),x=Xs(),S=globalThis.Blob||r.Blob,I=typeof S<"u"?function(D){return D instanceof S}:function(D){return!1},M=globalThis.AbortController||Yt().AbortController,{FunctionPrototypeCall:O}=Re(),B=class extends m{constructor(D){super(D),D?.readable===!1&&(this._readableState.readable=!1,this._readableState.ended=!0,this._readableState.endEmitted=!0),D?.writable===!1&&(this._writableState.writable=!1,this._writableState.ending=!0,this._writableState.ended=!0,this._writableState.finished=!0)}};e.exports=function D(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:F,destroy:Z}=T(N);if(i(K))return x(B,K,{objectMode:!0,write:re,final:F,destroy:Z});let P=K?.then;if(typeof P=="function"){let J,be=O(P,K,te=>{if(te!=null)throw new y("nully","body",te)},te=>{k(J,te)});return J=new B({objectMode:!0,readable:!1,write:re,final(te){F(async()=>{try{await be,t.nextTick(te,null)}catch(we){t.nextTick(te,we)}})},destroy:Z})}throw new y("Iterable, AsyncIterable or AsyncFunction",ae,K)}if(I(N))return D(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:D(N.readable):void 0,re=N!=null&&N.writable?l(N?.writable)?N?.writable:D(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(D){let{promise:N,resolve:ae}=v(),Y=new M,K=Y.signal;return{value:D((async function*(){for(;;){let re=N;N=null;let{chunk:F,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 F}})(),{signal:K}),write(re,F,Z){let P=ae;ae=null,P({chunk:re,done:!1,cb:Z})},final(re){let F=ae;ae=null,F({done:!0,cb:re})},destroy(re,F){Y.abort(),F(re)}}}function W(D){let N=D.readable&&typeof D.readable.read!="function"?w.wrap(D.readable):D.readable,ae=D.writable,Y=!!a(N),K=!!n(ae),re,F,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&&(b(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(),F=te},ae.on("drain",function(){if(re){let te=re;re=null,te()}}),ae.on("finish",function(){if(F){let te=F;F=null,te()}})),Y&&(b(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,F=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}=Re();e.exports=o;var i=jr(),s=Xi();n(o.prototype,i.prototype),n(o,i);{let p=a(s.prototype);for(let b=0;b<p.length;b++){let f=p[b];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,b){return u().newStreamDuplexFromReadableWritablePair(p,b)},o.toWeb=function(p){return u().newReadableWritablePairFromDuplex(p)};var d;o.from=function(p){return d||(d=pc()),d(p,"body")}}),Zs=pe((c,e)=>{le(),ue(),ce();var{ObjectSetPrototypeOf:t,Symbol:r}=Re();e.exports=o;var{ERR_METHOD_NOT_IMPLEMENTED:a}=We().codes,n=at(),{getHighWaterMark:i}=Rr();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,b)=>{if(p){d?d(p):this.destroy(p);return}b!=null&&this.push(b),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,b){throw new a("_transform()")},o.prototype._write=function(d,p,b){let f=this._readableState,g=this._writableState,y=f.length;this._transform(d,p,(k,m)=>{if(k){b(k);return}m!=null&&this.push(m),g.ended||y===f.length||f.length<f.highWaterMark?b():this[s]=b})},o.prototype._read=function(){if(this[s]){let d=this[s];this[s]=null,d()}}}),ea=pe((c,e)=>{le(),ue(),ce();var{ObjectSetPrototypeOf:t}=Re();e.exports=a;var r=Zs();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)}}),Zi=pe((c,e)=>{le(),ue(),ce();var t=At(),{ArrayIsArray:r,Promise:a,SymbolAsyncIterator:n,SymbolDispose:i}=Re(),s=yt(),{once:o}=qe(),l=Nt(),u=at(),{aggregateTwoErrors:d,codes:{ERR_INVALID_ARG_TYPE:p,ERR_INVALID_RETURN_VALUE:b,ERR_MISSING_ARGS:f,ERR_STREAM_DESTROYED:g,ERR_STREAM_PREMATURE_CLOSE:y},AbortError:k}=We(),{validateFunction:m,validateAbortSignal:w}=Qt(),{isIterable:E,isReadable:v,isReadableNodeStream:x,isNodeStream:S,isTransformStream:I,isWebStream:M,isReadableStream:O,isReadableFinished:B}=ct(),T=globalThis.AbortController||Yt().AbortController,W,D,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){D||(D=jr()),yield*D.prototype[n].call(te)}async function F(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||qe().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 b("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 b("AsyncIterable",`transform[${ve-1}]`,ye)}else{var ge;W||(W=ea());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++,F(ye,U,fe,{end:_});else if(O(ye)||I(ye)){let z=ye.readable||ye;ee++,F(z,U,fe,{end:_})}else throw new b("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++,F(U,se,fe,{end:_})}else if(E(ye))ee++,F(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 y)}),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}}),ta=pe((c,e)=>{le(),ue(),ce();var{pipeline:t}=Zi(),r=at(),{destroyer:a}=Nt(),{isNodeStream:n,isReadable:i,isWritable:s,isWebStream:o,isTransformStream:l,isWritableStream:u,isReadableStream:d}=ct(),{AbortError:p,codes:{ERR_INVALID_ARG_VALUE:b,ERR_MISSING_ARGS:f}}=We(),g=yt();e.exports=function(...y){if(y.length===0)throw new f("streams");if(y.length===1)return r.from(y[0]);let k=[...y];if(typeof y[0]=="function"&&(y[0]=r.from(y[0])),typeof y[y.length-1]=="function"){let T=y.length-1;y[T]=r.from(y[T])}for(let T=0;T<y.length;++T)if(!(!n(y[T])&&!o(y[T]))){if(T<y.length-1&&!(i(y[T])||d(y[T])||l(y[T])))throw new b(`streams[${T}]`,k[T],"must be readable");if(T>0&&!(s(y[T])||u(y[T])||l(y[T])))throw new b(`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=y[0],M=t(y,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,D,N){I.write(W,D)?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(D,N,ae){try{await W.ready,W.write(D).catch(()=>{}),ae()}catch(Y){ae(Y)}},x._final=async function(D){try{await W.ready,W.close().catch(()=>{}),w=D}catch(N){D(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:D}=await T.read();if(!x.push(W))return;if(D){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}}),gc=pe((c,e)=>{le(),ue(),ce();var t=globalThis.AbortController||Yt().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}=Qt(),d=Re().Symbol("kWeak"),p=Re().Symbol("kResistStopPropagation"),{finished:b}=yt(),f=ta(),{addAbortSignalNoValidate:g}=Mr(),{isWritable:y,isNodeStream:k}=ct(),{deprecate:m}=qe(),{ArrayPrototypePush:w,Boolean:E,MathFloor:v,Number:x,NumberIsNaN:S,Promise:I,PromiseReject:M,PromiseResolve:O,PromisePrototypeThen:B,Symbol:T}=Re(),W=T("kEmpty"),D=T("kEof");function N(H,G){if(G!=null&&u(G,"options"),G?.signal!=null&&o(G.signal,"options.signal"),k(H)&&!y(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=qe().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(D)}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===D)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 F(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 b(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:F}}),ra=pe((c,e)=>{le(),ue(),ce();var{ArrayPrototypePop:t,Promise:r}=Re(),{isIterable:a,isNodeStream:n,isWebStream:i}=ct(),{pipelineImpl:s}=Zi(),{finished:o}=yt();na();function l(...u){return new r((d,p)=>{let b,f,g=u[u.length-1];if(g&&typeof g=="object"&&!n(g)&&!a(g)&&!i(g)){let y=t(u);b=y.signal,f=y.end}s(u,(y,k)=>{y?p(y):d(k)},{signal:b,end:f})})}e.exports={finished:o,pipeline:l}}),na=pe((c,e)=>{le(),ue(),ce();var{Buffer:t}=(Ne(),Oe(Le)),{ObjectDefineProperty:r,ObjectKeys:a,ReflectApply:n}=Re(),{promisify:{custom:i}}=qe(),{streamReturningOperators:s,promiseReturningOperators:o}=gc(),{codes:{ERR_ILLEGAL_CONSTRUCTOR:l}}=We(),u=ta(),{setDefaultHighWaterMark:d,getDefaultHighWaterMark:p}=Rr(),{pipeline:b}=Zi(),{destroyer:f}=Nt(),g=yt(),y=ra(),k=ct(),m=e.exports=Ji().Stream;m.isDestroyed=k.isDestroyed,m.isDisturbed=k.isDisturbed,m.isErrored=k.isErrored,m.isReadable=k.isReadable,m.isWritable=k.isWritable,m.Readable=jr();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=Xi(),m.Duplex=at(),m.Transform=Zs(),m.PassThrough=ea(),m.pipeline=b;var{addAbortSignal:w}=Mr();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 y}}),r(b,i,{__proto__:null,enumerable:!0,get(){return y.pipeline}}),r(g,i,{__proto__:null,enumerable:!0,get(){return y.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)}}),It=pe((c,e)=>{le(),ue(),ce();var t=na(),r=ra(),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}),mc=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}}}),bc=pe((c,e)=>{le(),ue(),ce();var{Buffer:t}=(Ne(),Oe(Le)),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,b=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,b),b+=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 y=this._bufs[g].length-f;if(p>y)this._bufs[g].copy(n,b,f),b+=y;else{this._bufs[g].copy(n,b,f,f+p),b+=y;break}p-=y,f&&(f=0)}return n.length>b?n.slice(0,b):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}),yc=pe((c,e)=>{le(),ue(),ce();var t=It().Duplex,r=mc(),a=bc();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}),vc=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}),ia=pe((c,e)=>{le(),ue(),ce();var t=e.exports,{Buffer:r}=(Ne(),Oe(Le));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"}}),wc=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,b){b=b||{};var f=typeof p;if(f==="string"&&p.length>0)return o(p);if(f==="number"&&isFinite(p))return b.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 b=/^(-?(?:\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(b){var f=parseFloat(b[1]),g=(b[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 b=Math.abs(p);return b>=n?Math.round(p/n)+"d":b>=a?Math.round(p/a)+"h":b>=r?Math.round(p/r)+"m":b>=t?Math.round(p/t)+"s":p+"ms"}function u(p){var b=Math.abs(p);return b>=n?d(p,b,n,"day"):b>=a?d(p,b,a,"hour"):b>=r?d(p,b,r,"minute"):b>=t?d(p,b,t,"second"):p+" ms"}function d(p,b,f,g){var y=b>=f*1.5;return Math.round(p/f)+" "+g+(y?"s":"")}}),_c=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=wc(),n.destroy=p,Object.keys(r).forEach(b=>{n[b]=r[b]}),n.names=[],n.skips=[],n.formatters={};function a(b){let f=0;for(let g=0;g<b.length;g++)f=(f<<5)-f+b.charCodeAt(g),f|=0;return n.colors[Math.abs(f)%n.colors.length]}n.selectColor=a;function n(b){let f,g=null,y,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=b,m.useColors=n.useColors(),m.color=n.selectColor(b),m.extend=i,m.destroy=n.destroy,Object.defineProperty(m,"enabled",{enumerable:!0,configurable:!1,get:()=>g!==null?g:(y!==n.namespaces&&(y=n.namespaces,k=n.enabled(b)),k),set:w=>{g=w}}),typeof n.init=="function"&&n.init(m),m}function i(b,f){let g=n(this.namespace+(typeof f>"u"?":":f)+b);return g.log=this.log,g}function s(b){n.save(b),n.namespaces=b,n.names=[],n.skips=[];let f=(typeof b=="string"?b:"").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(b,f){let g=0,y=0,k=-1,m=0;for(;g<b.length;)if(y<f.length&&(f[y]===b[g]||f[y]==="*"))f[y]==="*"?(k=y,m=g,y++):(g++,y++);else if(k!==-1)y=k+1,m++,g=m;else return!1;for(;y<f.length&&f[y]==="*";)y++;return y===f.length}function l(){let b=[...n.names,...n.skips.map(f=>"-"+f)].join(",");return n.enable(""),b}function u(b){for(let f of n.skips)if(o(b,f))return!1;for(let f of n.names)if(o(b,f))return!0;return!1}function d(b){return b instanceof Error?b.stack||b.message:b}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 Pe<"u"&&"env"in Pe&&(o=Pe.env.DEBUG),o}function i(){try{return localStorage}catch{}}e.exports=_c()(c);var{formatters:s}=e.exports;s.j=function(o){try{return JSON.stringify(o)}catch(l){return"[UnexpectedJSONParseError]: "+l.message}}}),kc=pe((c,e)=>{le(),ue(),ce();var t=yc(),{EventEmitter:r}=(xt(),Oe(bt)),a=vc(),n=ia(),i=lt()("mqtt-packet:parser"),s=class ni extends r{constructor(){super(),this.parser=this.constructor.parser}static parser(l){return this instanceof ni?(this.settings=l||{},this._states=["_parseHeader","_parseLength","_parsePayload","_newPacket"],this._resetState(),this):new ni().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,b={},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"));b.username=this._list.readUInt8(this._pos)&n.USERNAME_MASK,b.password=this._list.readUInt8(this._pos)&n.PASSWORD_MASK,b.will=this._list.readUInt8(this._pos)&n.WILL_FLAG_MASK;let y=!!(this._list.readUInt8(this._pos)&n.WILL_RETAIN_MASK),k=(this._list.readUInt8(this._pos)&n.WILL_QOS_MASK)>>n.WILL_QOS_SHIFT;if(b.will)f.will={},f.will.retain=y,f.will.qos=k;else{if(y)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),b.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(b.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(b.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,b,f,g,y;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,b=d>>n.SUBSCRIBE_OPTIONS_RH_SHIFT&n.SUBSCRIBE_OPTIONS_RH_MASK,b>2)return this._emitError(new Error("Invalid retain handling, must be <= 2"));y={topic:u,qos:p},this.settings.protocolVersion===5?(y.nl=g,y.rap=f,y.rh=b):this.settings.bridgeMode&&(y.rh=0,y.rap=!0,y.nl=!0),i("_parseSubscribe: push subscription `%s` to subscription",y),l.subscriptions.push(y)}}}_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,b=0,f=!1,g,y=this._pos?this._pos:0;for(;d<u&&y+d<this._list.length;){if(g=this._list.readUInt8(y+d++),b+=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")),y&&(this._pos+=d),f?l?f={bytes:d,value:b}:f=b: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 b=n.propertiesCodes[p];if(!b)return this._emitError(new Error("Unknown property")),!1;if(b==="userProperties"){d[b]||(d[b]=Object.create(null));let f=this._parseByType(n.propertiesTypes[b]);if(d[b][f.name])if(Array.isArray(d[b][f.name]))d[b][f.name].push(f.value);else{let g=d[b][f.name];d[b][f.name]=[g],d[b][f.name].push(f.value)}else d[b][f.name]=f.value;continue}d[b]?Array.isArray(d[b])?d[b].push(this._parseByType(n.propertiesTypes[b])):(d[b]=[d[b]],d[b].push(this._parseByType(n.propertiesTypes[b]))):d[b]=this._parseByType(n.propertiesTypes[b])}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}),Sc=pe((c,e)=>{le(),ue(),ce();var{Buffer:t}=(Ne(),Oe(Le)),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,b=t.allocUnsafe(4);do d=u%128|0,u=u/128|0,u>0&&(d=d|128),b.writeUInt8(d,p++);while(u>0&&p<4);return u>0&&(p=0),n?b.subarray(0,p):b.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}}),Ec=pe((c,e)=>{le(),ue(),ce(),typeof Pe>"u"||!Pe.version||Pe.version.indexOf("v0.")===0||Pe.version.indexOf("v1.")===0&&Pe.version.indexOf("v1.8.")!==0?e.exports={nextTick:t}:e.exports=Pe;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 Pe.nextTick(r);case 2:return Pe.nextTick(function(){r.call(null,a)});case 3:return Pe.nextTick(function(){r.call(null,a,n)});case 4:return Pe.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 Pe.nextTick(function(){r.apply(null,o)})}}}),oa=pe((c,e)=>{le(),ue(),ce();var t=ia(),{Buffer:r}=(Ne(),Oe(Le)),a=r.allocUnsafe(0),n=r.from([0]),i=Sc(),s=Ec().nextTick,o=lt()("mqtt-packet:writeToStream"),l=i.cache,u=i.generateNumber,d=i.generateCache,p=i.genBufVariableByteInt,b=i.generate4ByteBuffer,f=Y,g=!0;function y(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(y,"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),D(L,ye),F(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(),F(L,$),me&&(Q===5&&ge.write(),N(L,me.topic),F(L,me.payload)),ee!=null&&F(L,ee),fe!=null&&F(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),D(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]),D(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),D(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]),D(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),D(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]),D(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]),D(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])),D(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])),D(L,oe),L.write(r.from([Q])),R!==null&&R.write(),!0):!1}var W={};function D(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=b(L);return o("write4ByteNumber: %o",ne),V.write(ne)}function F(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]])),F(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]])),D(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){D(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=y}),xc=pe((c,e)=>{le(),ue(),ce();var t=oa(),{EventEmitter:r}=(xt(),Oe(bt)),{Buffer:a}=(Ne(),Oe(Le));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}),Ac=pe(c=>{le(),ue(),ce(),c.parser=kc().parser,c.generate=xc(),c.writeToStream=oa()}),Ic=pe((c,e)=>{le(),ue(),ce(),e.exports=r;function t(n){return n instanceof Cr?Cr.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 b=Object.keys(d),f=new Array(b.length);for(let g=0;g<b.length;g++){let y=b[g],k=d[y];typeof k!="object"||k===null?f[y]=k:k.constructor!==Object&&(s=i.get(k.constructor))?f[y]=s(k,p):ArrayBuffer.isView(k)?f[y]=t(k):f[y]=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 b in d){if(Object.hasOwnProperty.call(d,b)===!1)continue;let f=d[b];typeof f!="object"||f===null?p[b]=f:f.constructor!==Object&&(s=i.get(f.constructor))?p[b]=s(f,l):ArrayBuffer.isView(f)?p[b]=t(f):p[b]=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 b in d){let f=d[b];typeof f!="object"||f===null?p[b]=f:f.constructor!==Object&&(s=i.get(f.constructor))?p[b]=s(f,u):ArrayBuffer.isView(f)?p[b]=t(f):p[b]=u(f)}return p}}function a(n){let i=[],s=[],o=new Map;if(o.set(Date,b=>new Date(b)),o.set(Map,(b,f)=>new Map(u(Array.from(b),f))),o.set(Set,(b,f)=>new Set(u(Array.from(b),f))),n.constructorHandlers)for(let b of n.constructorHandlers)o.set(b[0],b[1]);let l=null;return n.proto?p:d;function u(b,f){let g=Object.keys(b),y=new Array(g.length);for(let k=0;k<g.length;k++){let m=g[k],w=b[m];if(typeof w!="object"||w===null)y[m]=w;else if(w.constructor!==Object&&(l=o.get(w.constructor)))y[m]=l(w,f);else if(ArrayBuffer.isView(w))y[m]=t(w);else{let E=i.indexOf(w);E!==-1?y[m]=s[E]:y[m]=f(w)}}return y}function d(b){if(typeof b!="object"||b===null)return b;if(Array.isArray(b))return u(b,d);if(b.constructor!==Object&&(l=o.get(b.constructor)))return l(b,d);let f={};i.push(b),s.push(f);for(let g in b){if(Object.hasOwnProperty.call(b,g)===!1)continue;let y=b[g];if(typeof y!="object"||y===null)f[g]=y;else if(y.constructor!==Object&&(l=o.get(y.constructor)))f[g]=l(y,d);else if(ArrayBuffer.isView(y))f[g]=t(y);else{let k=i.indexOf(y);k!==-1?f[g]=s[k]:f[g]=d(y)}}return i.pop(),s.pop(),f}function p(b){if(typeof b!="object"||b===null)return b;if(Array.isArray(b))return u(b,p);if(b.constructor!==Object&&(l=o.get(b.constructor)))return l(b,p);let f={};i.push(b),s.push(f);for(let g in b){let y=b[g];if(typeof y!="object"||y===null)f[g]=y;else if(y.constructor!==Object&&(l=o.get(y.constructor)))f[g]=l(y,p);else if(ArrayBuffer.isView(y))f[g]=t(y);else{let k=i.indexOf(y);k!==-1?f[g]=s[k]:f[g]=p(y)}}return i.pop(),s.pop(),f}}}),Tc=pe((c,e)=>{le(),ue(),ce(),e.exports=Ic()()}),sa=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}}),aa=pe(c=>{le(),ue(),ce(),Object.defineProperty(c,"__esModule",{value:!0});var e=It(),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}),Cc=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,b=>{if(b)return n&&n(b);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}),Oc=pe((c,e)=>{e.exports={version:"5.15.0"}}),Ut=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 la extends Error{code;constructor(n,i){super(n),this.code=i,Object.setPrototypeOf(this,la.prototype),Object.getPrototypeOf(this).name="ErrorWithReasonCode"}};c.ErrorWithReasonCode=e;var t=class ca extends Error{packet;constructor(n,i){super(n),this.packet=i,Object.setPrototypeOf(this,ca.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 Pe?.nextTick=="function"?Pe.nextTick:a=>{setTimeout(a,0)},c.MQTTJS_VERSION=Oc().version}),Lr=pe(c=>{le(),ue(),ce(),Object.defineProperty(c,"__esModule",{value:!0}),c.ReasonCodes=void 0;var e=Ut();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 b=r.messageIdToTopic[n];b&&b.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}),Pc=pe(c=>{le(),ue(),ce(),Object.defineProperty(c,"__esModule",{value:!0});var e=Ut(),t=Lr(),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}),Mc=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 Pe=="object"&&Pe?Pe:{},a=(b,f,g,y)=>{typeof r.emitWarning=="function"?r.emitWarning(b,f,g,y):console.error(`[${g}] ${f}: ${b}`)},n=globalThis.AbortController,i=globalThis.AbortSignal;if(typeof n>"u"){i=class{onabort;_onabort=[];reason;aborted=!1;addEventListener(g,y){this._onabort.push(y)}},n=class{constructor(){f()}signal=new i;abort(g){if(!this.signal.aborted){this.signal.reason=g,this.signal.aborted=!0;for(let y of this.signal._onabort)y(g);this.signal.onabort?.(g)}}};let b=r.env?.LRU_CACHE_IGNORE_AC_WARNING!=="1",f=()=>{b&&(b=!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=b=>!t.has(b),o=b=>b&&b===Math.floor(b)&&b>0&&isFinite(b),l=b=>o(b)?b<=Math.pow(2,8)?Uint8Array:b<=Math.pow(2,16)?Uint16Array:b<=Math.pow(2,32)?Uint32Array:b<=Number.MAX_SAFE_INTEGER?u:null:null,u=class extends Array{constructor(b){super(b),this.fill(0)}},d=class Kt{heap;length;static#l=!1;static create(f){let g=l(f);if(!g)return[];Kt.#l=!0;let y=new Kt(f,g);return Kt.#l=!1,y}constructor(f,g){if(!Kt.#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 ua{#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,y,k,m)=>f.#j(g,y,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:y,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:D,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 F=g?l(g):Array;if(!F)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(D!==void 0&&typeof D!="function")throw new TypeError("memoMethod must be a function if defined");if(this.#P=D,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 F(g),this.#f=new F(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=y||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,ua))}}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=y||k();let x=m.now-v;m.remainingTTL=E-x}};let y=0,k=()=>{let m=e.now();if(this.ttlResolution>0){y=m;let w=setTimeout(()=>y=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=(y||k())-v;return E-x},this.#p=m=>{let w=g[m],E=f[m];return!!E&&!!w&&(y||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,y,k,m)=>{if(this.#t(y))return 0;if(!o(k))if(m){if(typeof m!="function")throw new TypeError("sizeCalculation must be a function");if(k=m(y,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,y,k)=>{if(f[g]=y,this.#h){let m=this.#h-f[g];for(;this.#b>m;)this.#R(!0)}this.#b+=f[g],k&&(k.entrySize=y,k.totalCalculatedSize=this.#b)}}#T=f=>{};#M=(f,g,y)=>{};#U=(f,g,y,k)=>{if(y||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 y of this.#k()){let k=this.#e[y],m=this.#t(k)?k.__staleWhileFetching:k;if(m!==void 0&&f(m,this.#r[y],this))return this.get(this.#r[y],g)}}forEach(f,g=this){for(let y of this.#k()){let k=this.#e[y],m=this.#t(k)?k.__staleWhileFetching:k;m!==void 0&&f.call(g,m,this.#r[y],this)}}rforEach(f,g=this){for(let y of this.#S()){let k=this.#e[y],m=this.#t(k)?k.__staleWhileFetching:k;m!==void 0&&f.call(g,m,this.#r[y],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 y=this.#e[g],k=this.#t(y)?y.__staleWhileFetching:y;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 y=this.#r[g],k=this.#e[g],m=this.#t(k)?k.__staleWhileFetching:k;if(m===void 0||y===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([y,w])}return f}load(f){this.clear();for(let[g,y]of f){if(y.start){let k=Date.now()-y.start;y.start=e.now()-k}this.set(g,y.value,y)}}set(f,g,y={}){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}=y,{noUpdateTTL:x=this.noUpdateTTL}=y,S=this.#U(f,g,y.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,y=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,y,"evict"),this.#u&&this.#s?.push([k,y,"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(y),this.#i--,g}has(f,g={}){let{updateAgeOnHas:y=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 y&&this.#I(m),k&&(k.has="hit",this.#x(k,m)),!0}else k&&(k.has="miss");return!1}peek(f,g={}){let{allowStale:y=this.allowStale}=g,k=this.#n.get(f);if(k===void 0||!y&&this.#p(k))return;let m=this.#e[k];return this.#t(m)?m.__staleWhileFetching:m}#j(f,g,y,k){let m=g===void 0?void 0:this.#e[g];if(this.#t(m))return m;let w=new n,{signal:E}=y;E?.addEventListener("abort",()=>w.abort(E.reason),{signal:w.signal});let v={signal:w.signal,options:y,context:k},x=(T,W=!1)=>{let{aborted:D}=w.signal,N=y.ignoreFetchAbort&&T!==void 0;if(y.status&&(D&&!W?(y.status.fetchAborted=!0,y.status.fetchError=w.signal.reason,N&&(y.status.fetchAbortIgnored=!0)):y.status.fetchResolved=!0),D&&!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"):(y.status&&(y.status.fetchUpdated=!0),this.set(f,T,v.options))),T},S=T=>(y.status&&(y.status.fetchRejected=!0,y.status.fetchError=T),I(T)),I=T=>{let{aborted:W}=w.signal,D=W&&y.allowStaleOnFetchAbort,N=D||y.allowStaleOnFetchRejection,ae=N||y.noDeleteOnFetchRejection,Y=O;if(this.#e[g]===O&&(!ae||Y.__staleWhileFetching===void 0?this.#E(f,"fetch"):D||(this.#e[g]=Y.__staleWhileFetching)),N)return y.status&&Y.__staleWhileFetching!==void 0&&(y.status.returnedStale=!0),Y.__staleWhileFetching;if(Y.__returned===Y)throw T},M=(T,W)=>{let D=this.#O?.(f,m,v);D&&D instanceof Promise&&D.then(N=>T(N===void 0?void 0:N),W),w.signal.addEventListener("abort",()=>{(!y.ignoreFetchAbort||y.allowStaleOnFetchAbort)&&(T(void 0),y.allowStaleOnFetchAbort&&(T=N=>x(N,!0)))})};y.status&&(y.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:y=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:D,signal:N}=g;if(!this.#A)return D&&(D.fetch="get"),this.get(f,{allowStale:y,updateAgeOnGet:k,noDeleteOnStaleGet:m,status:D});let ae={allowStale:y,updateAgeOnGet:k,noDeleteOnStaleGet:m,ttl:w,noDisposeOnSet:E,size:v,sizeCalculation:x,noUpdateTTL:S,noDeleteOnFetchRejection:I,allowStaleOnFetchRejection:M,allowStaleOnFetchAbort:B,ignoreFetchAbort:O,status:D,signal:N},Y=this.#n.get(f);if(Y===void 0){D&&(D.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=y&&K.__staleWhileFetching!==void 0;return D&&(D.fetch="inflight",P&&(D.returnedStale=!0)),P?K.__staleWhileFetching:K.__returned=K}let re=this.#p(Y);if(!W&&!re)return D&&(D.fetch="hit"),this.#C(Y),k&&this.#I(Y),D&&this.#x(D,Y),K;let F=this.#j(f,Y,ae,T),Z=F.__staleWhileFetching!==void 0&&y;return D&&(D.fetch=re?"stale":"refresh",Z&&re&&(D.returnedStale=!0)),Z?F.__staleWhileFetching:F.__returned=F}}async forceFetch(f,g={}){let y=await this.fetch(f,g);if(y===void 0)throw new Error("fetch() returned undefined");return y}memo(f,g={}){let y=this.#P;if(!y)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=y(f,E,{options:w,context:k});return this.set(f,v,w),v}get(f,g={}){let{allowStale:y=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&&y&&v.__staleWhileFetching!==void 0&&(w.returnedStale=!0),y?v.__staleWhileFetching:void 0):(m||this.#E(f,"expire"),w&&y&&(w.returnedStale=!0),y?v:void 0)):(w&&(w.get="hit"),x?v.__staleWhileFetching:(this.#C(E),k&&this.#I(E),v))}else w&&(w.get="miss")}#D(f,g){this.#f[g]=f,this.#c[f]=g}#C(f){f!==this.#o&&(f===this.#a?this.#a=this.#c[f]:this.#D(this.#f[f],this.#c[f]),this.#D(this.#o,f),this.#o=f)}delete(f){return this.#E(f,"delete")}#E(f,g){let y=!1;if(this.#i!==0){let k=this.#n.get(f);if(k!==void 0)if(y=!0,this.#i===1)this.#F(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 y}clear(){return this.#F("delete")}#F(f){for(let g of this.#S({allowStale:!0})){let y=this.#e[g];if(this.#t(y))y.__abortController.abort(new Error("deleted"));else{let k=this.#r[g];this.#_&&this.#g?.(y,k,f),this.#u&&this.#s?.push([y,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,y;for(;y=g?.shift();)this.#m?.(...y)}}};c.LRUCache=p}),ut=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}),Rc=pe(c=>{le(),ue(),ce(),Object.defineProperty(c,"t",{value:!0}),c.default=void 0;var e=ut(),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}),jc=pe(c=>{le(),ue(),ce(),Object.defineProperty(c,"t",{value:!0}),c.default=void 0;var e=ut(),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}),Lc=pe(c=>{le(),ue(),ce(),Object.defineProperty(c,"t",{value:!0}),c.default=void 0;var e=ut(),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}),eo=pe(c=>{le(),ue(),ce(),Object.defineProperty(c,"t",{value:!0}),c.default=void 0;var e=ut(),t=class extends e.Container{},r=t;c.default=r}),ht=pe(c=>{le(),ue(),ce(),Object.defineProperty(c,"t",{value:!0}),c.throwIteratorAccessError=e;function e(){throw new RangeError("Iterator access denied!")}}),ha=pe(c=>{le(),ue(),ce(),Object.defineProperty(c,"t",{value:!0}),c.RandomIterator=void 0;var e=ut(),t=ht(),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}),Nc=pe(c=>{le(),ue(),ce(),Object.defineProperty(c,"t",{value:!0}),c.default=void 0;var e=r(eo()),t=ha();function r(s){return s&&s.t?s:{default:s}}var a=class fa extends t.RandomIterator{constructor(o,l,u){super(o,u),this.container=l}copy(){return new fa(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}),Uc=pe(c=>{le(),ue(),ce(),Object.defineProperty(c,"t",{value:!0}),c.default=void 0;var e=a(eo()),t=ut(),r=ht();function a(o){return o&&o.t?o:{default:o}}var n=class da 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 da(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 b=1;b<o;++b)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}),Bc=pe(c=>{le(),ue(),ce(),Object.defineProperty(c,"t",{value:!0}),c.default=void 0;var e=r(eo()),t=ha();function r(s){return s&&s.t?s:{default:s}}var a=class pa extends t.RandomIterator{constructor(o,l,u){super(o,u),this.container=l}copy(){return new pa(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}),ga=pe(c=>{le(),ue(),ce(),Object.defineProperty(c,"t",{value:!0}),c.default=void 0;var e=Dc(),t=ut(),r=ht(),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 b=this.he(d);if(b){let{parentNode:f,grandParent:g,curNode:y}=b;f.ie(),g.ie(),y.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,b=this.v(p.u,i);if(b===0){p.l=s;return}else if(b<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 y=f.L(),k=this.v(y.u,i);if(k===0){y.l=s;return}else k<0&&(l=new this.re(i,s),y.W===void 0?(y.W=l,l.tt=y):(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}),ma=pe(c=>{le(),ue(),ce(),Object.defineProperty(c,"t",{value:!0}),c.default=void 0;var e=ut(),t=ht(),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}),Fc=pe(c=>{le(),ue(),ce(),Object.defineProperty(c,"t",{value:!0}),c.default=void 0;var e=a(ga()),t=a(ma()),r=ht();function a(o){return o&&o.t?o:{default:o}}var n=class ba 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 ba(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}),$c=pe(c=>{le(),ue(),ce(),Object.defineProperty(c,"t",{value:!0}),c.default=void 0;var e=a(ga()),t=a(ma()),r=ht();function a(o){return o&&o.t?o:{default:o}}var n=class ya 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 ya(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}),va=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"}}),wa=pe(c=>{le(),ue(),ce(),Object.defineProperty(c,"t",{value:!0}),c.HashContainerIterator=c.HashContainer=void 0;var e=ut(),t=a(va()),r=ht();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}),Wc=pe(c=>{le(),ue(),ce(),Object.defineProperty(c,"t",{value:!0}),c.default=void 0;var e=wa(),t=ht(),r=class _a 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 _a(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}),qc=pe(c=>{le(),ue(),ce(),Object.defineProperty(c,"t",{value:!0}),c.default=void 0;var e=wa(),t=a(va()),r=ht();function a(o){return o&&o.t?o:{default:o}}var n=class ka 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 ka(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}),Hc=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(Rc()),t=d(jc()),r=d(Lc()),a=d(Nc()),n=d(Uc()),i=d(Bc()),s=d(Fc()),o=d($c()),l=d(Wc()),u=d(qc());function d(p){return p&&p.t?p:{default:p}}}),zc=pe((c,e)=>{le(),ue(),ce();var t=Hc().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}),Sa=pe((c,e)=>{le(),ue(),ce();var t=zc();e.exports.NumberAllocator=t}),Kc=pe(c=>{le(),ue(),ce(),Object.defineProperty(c,"__esModule",{value:!0});var e=Mc(),t=Sa(),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}),Vc=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=Lr(),r=e(Kc()),a=Ut(),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}),Gc=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}),Yc=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(Cc()),r=e(Pc()),a=e(Vc()),n=e(Lr()),i=e(Gc()),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}),Ea=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}),Qc=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}),Jc=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((xt(),Oe(bt))),r=Ut(),a=class{};c.TypedEventEmitter=a,(0,r.applyMixin)(a,t.default)}),Nr=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}),Xc=pe((c,e)=>{le(),ue(),ce();var t=Nr().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}),Zc=pe((c,e)=>{le(),ue(),ce();var t=Nr().default,r=Xc();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}),eu=pe((c,e)=>{le(),ue(),ce();var t=Zc();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}),tu=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}),ru=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(b){p=!0,s=b}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}),nu=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}),iu=pe((c,e)=>{le(),ue(),ce();var t=nu();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}),ou=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}),su=pe((c,e)=>{le(),ue(),ce();var t=tu(),r=ru(),a=iu(),n=ou();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}),xa=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(b){return function(f){var g=b(f);return f.add(g),g}},a=function(b){return function(f,g){return b.set(f,g),g}},n=Number.MAX_SAFE_INTEGER===void 0?9007199254740991:Number.MAX_SAFE_INTEGER,i=536870912,s=i*2,o=function(b,f){return function(g){var y=f.get(g),k=y===void 0?g.size:y<s?y+1:0;if(!g.has(k))return b(g,k);if(g.size<i){for(;g.has(k);)k=Math.floor(Math.random()*s);return b(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 b(g,k)}},l=new WeakMap,u=a(l),d=o(u,l),p=r(d);t.addUniqueNumber=p,t.generateUniqueNumber=d})}),au=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(b){return void i(b)}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}),Aa=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}),Ia=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(b,f){t(o,b,function(g){return this._invoke(b,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}),Ta=pe((c,e)=>{le(),ue(),ce();var t=Ia();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,D=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&&!F&&n<D.length;n++){var F,Z=D[n],P=ae.p,J=Z[2];K>3?(F=J===re)&&(T=Z[(B=Z[4])?5:(B=3,3)],Z[4]=Z[5]=a):Z[0]<=P&&((F=K<2&&P<Z[1])?(B=0,ae.v=re,ae.n=Z[1]):P<J&&(F=K<3||Z[0]>re||re>J)&&(Z[4]=K,Z[5]=re,ae.n=J,B=0))}if(F||K>1)return u;throw N=!0,re}return function(K,re,F){if(W>1)throw TypeError("Generator is already running");for(N&&re===1&&Y(re,F),B=re,T=F;(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 b(){}n=Object.getPrototypeOf;var f=[][s]?n(n([][s]())):(t(n={},s,function(){return this}),n),g=b.prototype=d.prototype=Object.create(f);function y(k){return Object.setPrototypeOf?Object.setPrototypeOf(k,b):(k.__proto__=b,t(k,o,"GeneratorFunction")),k.prototype=Object.create(g),k}return p.prototype=b,t(g,"constructor",b),t(b,"constructor",p),p.displayName="GeneratorFunction",t(b,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:y}},e.exports.__esModule=!0,e.exports.default=e.exports)()}e.exports=r,e.exports.__esModule=!0,e.exports.default=e.exports}),Ca=pe((c,e)=>{le(),ue(),ce();var t=Aa(),r=Ia();function a(n,i){function s(l,u,d,p){try{var b=n[l](u),f=b.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){b.value=g,d(b)},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(b,f){s(l,d,b,f)})}return o=o?o.then(p,p):p()},!0)}e.exports=a,e.exports.__esModule=!0,e.exports.default=e.exports}),Oa=pe((c,e)=>{le(),ue(),ce();var t=Ta(),r=Ca();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}),lu=pe((c,e)=>{le(),ue(),ce();var t=Oa();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}),cu=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}),uu=pe((c,e)=>{le(),ue(),ce();var t=Nr().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}),hu=pe((c,e)=>{le(),ue(),ce();var t=Aa(),r=Ta(),a=lu(),n=Oa(),i=Ca(),s=cu(),o=uu();function l(){var u=r(),d=u.m(l),p=(Object.getPrototypeOf?Object.getPrototypeOf(d):d.__proto__).constructor;function b(y){var k=typeof y=="function"&&y.constructor;return!!k&&(k===p||(k.displayName||k.name)==="GeneratorFunction")}var f={throw:1,return:2,break:3,continue:3};function g(y){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 y.call(this,k)}finally{w.p=k.prev,w.n=k.next}}}return(e.exports=l=function(){return{wrap:function(y,k,m,w){return u.w(g(y),k,m,w&&w.reverse())},isGeneratorFunction:b,mark:u.m,awrap:function(y,k){return new t(y,k)},AsyncIterator:i,async:function(y,k,m,w,E){return(b(k)?n:a)(g(y),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}),fu=pe((c,e)=>{le(),ue(),ce();var t=hu()();e.exports=t;try{regeneratorRuntime=t}catch{typeof globalThis=="object"?globalThis.regeneratorRuntime=t:Function("r","regeneratorRuntime = r")(t)}}),du=pe((c,e)=>{le(),ue(),ce(),(function(t,r){typeof c=="object"&&typeof e<"u"?r(c,eu(),su(),xa(),au(),fu()):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 b(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?b(Object(E),!0).forEach(function(v){r(m,v,E[v])}):Object.getOwnPropertyDescriptors?Object.defineProperties(m,Object.getOwnPropertyDescriptors(E)):b(Object(E)).forEach(function(v){Object.defineProperty(m,v,Object.getOwnPropertyDescriptor(E,v))})}return m}var g=new WeakMap,y=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=y(E);E.addEventListener("message",function(D){var N=D.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(D){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:D},ae):E.postMessage({id:re,method:D,params:N},ae)})},S=function(D,N){var ae=arguments.length>2&&arguments[2]!==void 0?arguments[2]:[];E.postMessage({id:null,method:D,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})}),pu=pe((c,e)=>{le(),ue(),ce(),(function(t,r){typeof c=="object"&&typeof e<"u"?r(c,Nr(),du(),xa()):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 b=arguments.length>1&&arguments[1]!==void 0?arguments[1]:0,f=arguments.length,g=new Array(f>2?f-2:0),y=2;y<f;y++)g[y-2]=arguments[y];var k=Symbol(),m=n.generateUniqueNumber(i);i.set(m,k);var w=function(){return d("set",{delay:b,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 b=arguments.length>1&&arguments[1]!==void 0?arguments[1]:0,f=arguments.length,g=new Array(f>2?f-2:0),y=2;y<f;y++)g[y-2]=arguments[y];var k=Symbol(),m=n.generateUniqueNumber(s);return s.set(m,k),d("set",{delay:b,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})}),gu=pe((c,e)=>{le(),ue(),ce(),(function(t,r){typeof c=="object"&&typeof e<"u"?r(c,pu()):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 b=null;return function(){if(b!==null)return b;var f=new Blob([p],{type:"application/javascript; charset=utf-8"}),g=URL.createObjectURL(f);return b=d(g),setTimeout(function(){return URL.revokeObjectURL(g)}),b}},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})}),Ur=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&&Pe?.versions?!Object.prototype.hasOwnProperty.call(Pe.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}),mu=pe(c=>{le(),ue(),ce();var e=c&&c.__createBinding||(Object.create?function(l,u,d,p){p===void 0&&(p=d);var b=Object.getOwnPropertyDescriptor(u,d);(!b||("get"in b?!u.__esModule:b.writable||b.configurable))&&(b={enumerable:!0,get:function(){return u[d]}}),Object.defineProperty(l,p,b)}: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 b in d)Object.prototype.hasOwnProperty.call(d,b)&&(p[p.length]=b);return p},l(u)};return function(u){if(u&&u.__esModule)return u;var d={};if(u!=null)for(var p=l(u),b=0;b<p.length;b++)p[b]!=="default"&&e(d,u,p[b]);return t(d,u),d}})();Object.defineProperty(c,"__esModule",{value:!0});var a=gu(),n=r(Ur()),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}),Pa=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(mu()),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}),ii=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(Ac()),i=It(),s=a(Tc()),o=a(lt()),l=r(sa()),u=a(aa()),d=a(Yc()),p=a(Ea()),b=a(Qc()),f=Ut(),g=Jc(),y=a(Pa()),k=r(Ur()),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 oi 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:",oi.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:oi.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 b.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",D=>{this.log("parser :: on packet push to packets array."),M.push(D)});let O=()=>{this.log("work :: getting next packet in queue");let D=M.shift();if(D)this.log("work :: packet pulled from queue"),(0,d.default)(this,D,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 D=I;I=null,D()}};x._write=(D,N,ae)=>{I=ae,this.log("writable stream :: parsing buffer"),S.parse(D),O()};let T=D=>{this.log("streamErrorHandler :: error",D.message),D.code?(this.log("streamErrorHandler :: emitting error"),this.emit("error",D)):this.noop(D)};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 D={cmd:"auth",reasonCode:0,...this.options.authPacket};this._writePacket(D)}}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:D,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=D),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:D}=S,N=[],ae=(re,F)=>{if(F=F||S,!Object.prototype.hasOwnProperty.call(this._resubscribeTopics,re)||this._resubscribeTopics[re].qos<F.qos||O){let Z={topic:re,qos:F.qos};M===5&&(Z.nl=F.nl,Z.rap=F.rap,Z.rh=F.rh,Z.properties=D),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,F)=>{let Z={cmd:"subscribe",subscriptions:re,messageId:F};if(D&&(Z.properties=D),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,F=[];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;F.push(Y(P,J))}return Promise.all(F).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 y.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(D,N){W&&W(D,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}),bu=pe(c=>{le(),ue(),ce(),Object.defineProperty(c,"__esModule",{value:!0});var e=Sa(),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 yu(){if(si)return sr;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"},b=e-t,f=Math.floor,g=String.fromCharCode;function y(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 D=O.split("."),N=k(D,B).join(".");return W+N}function w(O){let B=[],T=0,W=O.length;for(;T<W;){let D=O.charCodeAt(T++);if(D>=55296&&D<=56319&&T<W){let N=O.charCodeAt(T++);(N&64512)==56320?B.push(((D&1023)<<10)+(N&1023)+65536):(B.push(D),T--)}else B.push(D)}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>b*r>>1;W+=e)O=f(O/b);return f(W+(b+1)*O/(O+a))},I=function(O){let B=[],T=O.length,W=0,D=s,N=i,ae=O.lastIndexOf(o);ae<0&&(ae=0);for(let Y=0;Y<ae;++Y)O.charCodeAt(Y)>=128&&y("not-basic"),B.push(O.charCodeAt(Y));for(let Y=ae>0?ae+1:0;Y<T;){let K=W;for(let F=1,Z=e;;Z+=e){Y>=T&&y("invalid-input");let P=v(O.charCodeAt(Y++));P>=e&&y("invalid-input"),P>f((c-W)/F)&&y("overflow"),W+=P*F;let J=Z<=N?t:Z>=N+r?r:Z-N;if(P<J)break;let be=e-J;F>f(c/be)&&y("overflow"),F*=be}let re=B.length+1;N=S(W-K,re,K==0),f(W/re)>c-D&&y("overflow"),D+=f(W/re),W%=re,B.splice(W++,0,D)}return String.fromCodePoint(...B)},M=function(O){let B=[];O=w(O);let T=O.length,W=s,D=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 F of O)F>=W&&F<K&&(K=F);let re=Y+1;K-W>f((c-D)/re)&&y("overflow"),D+=(K-W)*re,W=K;for(let F of O)if(F<W&&++D>c&&y("overflow"),F===W){let Z=D;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(D,re,Y===ae),D=0,++Y}++D,++W}return B.join("")};return sr={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})}},sr}var sr,si,gt,vu=He(()=>{le(),ue(),ce(),sr={},si=!1,gt=yu(),gt.decode,gt.encode,gt.toASCII,gt.toUnicode,gt.ucs2,gt.version});function wu(){return li||(li=!0,ai=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}),ai}function _u(){return ui||(ui=!0,ci=Error),ci}function ku(){return fi||(fi=!0,hi=EvalError),hi}function Su(){return pi||(pi=!0,di=RangeError),di}function Eu(){return mi||(mi=!0,gi=ReferenceError),gi}function Ma(){return yi||(yi=!0,bi=SyntaxError),bi}function Jt(){return wi||(wi=!0,vi=TypeError),vi}function xu(){return ki||(ki=!0,_i=URIError),_i}function Au(){if(Si)return ar;Si=!0;var c=typeof Symbol<"u"&&Symbol,e=wu();return ar=function(){return typeof c!="function"||typeof Symbol!="function"||typeof c("foo")!="symbol"||typeof Symbol("bar")!="symbol"?!1:e()},ar}function Iu(){if(Ei)return lr;Ei=!0;var c={__proto__:null,foo:{}},e=Object;return lr=function(){return{__proto__:c}.foo===c.foo&&!(c instanceof e)},lr}function Tu(){if(xi)return cr;xi=!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 cr=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 y=o.apply(this,a(l,arguments));return Object(y)===y?y:this}return o.apply(s,a(l,arguments))},p=t(0,o.length-l.length),b=[],f=0;f<p;f++)b[f]="$"+f;if(u=Function("binder","return function ("+i(b,",")+"){ return binder.apply(this,arguments); }")(d),o.prototype){var g=function(){};g.prototype=o.prototype,u.prototype=new g,g.prototype=null}return u},cr}function to(){if(Ai)return ur;Ai=!0;var c=Tu();return ur=Function.prototype.bind||c,ur}function Cu(){if(Ii)return hr;Ii=!0;var c=Function.prototype.call,e=Object.prototype.hasOwnProperty,t=to();return hr=t.call(c,e),hr}function Bt(){if(Ti)return fr;Ti=!0;var c,e=_u(),t=ku(),r=Su(),a=Eu(),n=Ma(),i=Jt(),s=xu(),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,b=Au()(),f=Iu()(),g=Object.getPrototypeOf||(f?function(Y){return Y.__proto__}:null),y={},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%":b&&g?g([][Symbol.iterator]()):c,"%AsyncFromSyncIteratorPrototype%":c,"%AsyncFunction%":y,"%AsyncGenerator%":y,"%AsyncGeneratorFunction%":y,"%AsyncIteratorPrototype%":y,"%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%":y,"%Int8Array%":typeof Int8Array>"u"?c:Int8Array,"%Int16Array%":typeof Int16Array>"u"?c:Int16Array,"%Int32Array%":typeof Int32Array>"u"?c:Int32Array,"%isFinite%":isFinite,"%isNaN%":isNaN,"%IteratorPrototype%":b&&g?g(g([][Symbol.iterator]())):c,"%JSON%":typeof JSON=="object"?JSON:c,"%Map%":typeof Map>"u"?c:Map,"%MapIteratorPrototype%":typeof Map>"u"||!b||!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"||!b||!g?c:g(new Set()[Symbol.iterator]()),"%SharedArrayBuffer%":typeof SharedArrayBuffer>"u"?c:SharedArrayBuffer,"%String%":String,"%StringIteratorPrototype%":b&&g?g(""[Symbol.iterator]()):c,"%Symbol%":b?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 F=Y("%AsyncGeneratorFunction%");F&&(re=F.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=to(),S=Cu(),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,D=/\\(\\)?/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 F=[];return O(Y,W,function(Z,P,J,be){F[F.length]=J?O(be,D,"$1"):P||Z}),F},ae=function(Y,K){var re=Y,F;if(S(v,re)&&(F=v[re],re="%"+F[0]+"%"),S(m,re)){var Z=m[re];if(Z===y&&(Z=E(re)),typeof Z>"u"&&!K)throw new i("intrinsic "+Y+" exists, but is not available. Please file an issue!");return{alias:F,name:re,value:Z}}throw new n("intrinsic "+Y+" does not exist!")};return fr=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),F=re.length>0?re[0]:"",Z=ae("%"+F+"%",K),P=Z.name,J=Z.value,be=!1,te=Z.alias;te&&(F=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),F+="."+L,P="%"+F+"%",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},fr}function ro(){if(Ci)return dr;Ci=!0;var c=Bt(),e=c("%Object.defineProperty%",!0)||!1;if(e)try{e({},"a",{value:1})}catch{e=!1}return dr=e,dr}function Ra(){if(Oi)return pr;Oi=!0;var c=Bt(),e=c("%Object.getOwnPropertyDescriptor%",!0);if(e)try{e([],"length")}catch{e=null}return pr=e,pr}function Ou(){if(Pi)return gr;Pi=!0;var c=ro(),e=Ma(),t=Jt(),r=Ra();return gr=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.")},gr}function Pu(){if(Mi)return mr;Mi=!0;var c=ro(),e=function(){return!!c};return e.hasArrayLengthDefineBug=function(){if(!c)return null;try{return c([],"length",{value:1}).length!==1}catch{return!0}},mr=e,mr}function Mu(){if(Ri)return br;Ri=!0;var c=Bt(),e=Ou(),t=Pu()(),r=Ra(),a=Jt(),n=c("%Math.floor%");return br=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},br}function Ru(){if(ji)return Mt;ji=!0;var c=to(),e=Bt(),t=Mu(),r=Jt(),a=e("%Function.prototype.apply%"),n=e("%Function.prototype.call%"),i=e("%Reflect.apply%",!0)||c.call(n,a),s=ro(),o=e("%Math.max%");Mt=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(Mt,"apply",{value:l}):Mt.apply=l,Mt}function ju(){if(Li)return yr;Li=!0;var c=Bt(),e=Ru(),t=e(c("String.prototype.indexOf"));return yr=function(r,a){var n=c(r,!!a);return typeof n=="function"&&t(r,".prototype.")>-1?e(n):n},yr}var ai,li,ci,ui,hi,fi,di,pi,gi,mi,bi,yi,vi,wi,_i,ki,ar,Si,lr,Ei,cr,xi,ur,Ai,hr,Ii,fr,Ti,dr,Ci,pr,Oi,gr,Pi,mr,Mi,br,Ri,Mt,ji,yr,Li,Lu=He(()=>{le(),ue(),ce(),ai={},li=!1,ci={},ui=!1,hi={},fi=!1,di={},pi=!1,gi={},mi=!1,bi={},yi=!1,vi={},wi=!1,_i={},ki=!1,ar={},Si=!1,lr={},Ei=!1,cr={},xi=!1,ur={},Ai=!1,hr={},Ii=!1,fr={},Ti=!1,dr={},Ci=!1,pr={},Oi=!1,gr={},Pi=!1,mr={},Mi=!1,br={},Ri=!1,Mt={},ji=!1,yr={},Li=!1});function no(c){throw new Error("Node.js process "+c+" is not supported by JSPM core outside of Node.js")}function Nu(){!Et||!kt||(Et=!1,kt.length?tt=kt.concat(tt):Gt=-1,tt.length&&ja())}function ja(){if(!Et){var c=setTimeout(Nu,0);Et=!0;for(var e=tt.length;e;){for(kt=tt,tt=[];++Gt<e;)kt&&kt[Gt].run();Gt=-1,e=tt.length}kt=null,Et=!1,clearTimeout(c)}}function Uu(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];tt.push(new La(c,e)),tt.length===1&&!Et&&setTimeout(ja,0)}function La(c,e){this.fun=c,this.array=e}function De(){}function Bu(c){no("_linkedBinding")}function Du(c){no("dlopen")}function Fu(){return[]}function $u(){return[]}function Wu(c,e){if(!c)throw new Error(e||"assertion error")}function qu(){return!1}function Hu(){return st.now()/1e3}function Fr(c){var e=Math.floor((Date.now()-st.now())*.001),t=st.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+=vr)),[r,a]}function dt(){return io}function zu(c){return[]}var tt,Et,kt,Gt,po,go,mo,bo,yo,vo,wo,_o,ko,So,Eo,xo,Ao,Io,To,Co,Oo,Po,Mo,Ro,jo,er,Lo,No,Uo,Bo,Do,Fo,$o,Wo,qo,Ho,zo,Ko,Vo,Go,Yo,Qo,Jo,Xo,Zo,es,ts,rs,ns,is,os,st,$r,vr,ss,as,ls,cs,us,hs,fs,ds,ps,gs,ms,io,Na=He(()=>{le(),ue(),ce(),tt=[],Et=!1,Gt=-1,La.prototype.run=function(){this.fun.apply(null,this.array)},po="browser",go="x64",mo="browser",bo={PATH:"/usr/bin",LANG:navigator.language+".UTF-8",PWD:"/",HOME:"/home",TMP:"/tmp"},yo=["/usr/bin/node"],vo=[],wo="v16.8.0",_o={},ko=function(c,e){console.warn((e?e+": ":"")+c)},So=function(c){no("binding")},Eo=function(c){return 0},xo=function(){return"/"},Ao=function(c){},Io={name:"node",sourceUrl:"",headersUrl:"",libUrl:""},To=De,Co=[],Oo={},Po=!1,Mo={},Ro=De,jo=De,er=function(){return{}},Lo=er,No=er,Uo=De,Bo=De,Do=De,Fo={},$o={inspector:!1,debug:!1,uv:!1,ipv6:!1,tls_alpn:!1,tls_sni:!1,tls_ocsp:!1,tls:!1,cached_builtins:!0},Wo=De,qo=De,Ho=De,zo=De,Ko=De,Vo=De,Go=De,Yo=void 0,Qo=void 0,Jo=void 0,Xo=De,Zo=2,es=1,ts="/bin/usr/node",rs=9229,ns="node",is=[],os=De,st={now:typeof performance<"u"?performance.now.bind(performance):void 0,timing:typeof performance<"u"?performance.timing:void 0},st.now===void 0&&($r=Date.now(),st.timing&&st.timing.navigationStart&&($r=st.timing.navigationStart),st.now=()=>Date.now()-$r),vr=1e9,Fr.bigint=function(c){var e=Fr(c);return typeof BigInt>"u"?e[0]*vr+e[1]:BigInt(e[0]*vr)+BigInt(e[1])},ss=10,as={},ls=0,cs=dt,us=dt,hs=dt,fs=dt,ds=dt,ps=De,gs=dt,ms=dt,io={version:wo,versions:_o,arch:go,platform:mo,release:Io,_rawDebug:To,moduleLoadList:Co,binding:So,_linkedBinding:Bu,_events:as,_eventsCount:ls,_maxListeners:ss,on:dt,addListener:cs,once:us,off:hs,removeListener:fs,removeAllListeners:ds,emit:ps,prependListener:gs,prependOnceListener:ms,listeners:zu,domain:Oo,_exiting:Po,config:Mo,dlopen:Du,uptime:Hu,_getActiveRequests:Fu,_getActiveHandles:$u,reallyExit:Ro,_kill:jo,cpuUsage:er,resourceUsage:Lo,memoryUsage:No,kill:Uo,exit:Bo,openStdin:Do,allowedNodeEnvironmentFlags:Fo,assert:Wu,features:$o,_fatalExceptions:Wo,setUncaughtExceptionCaptureCallback:qo,hasUncaughtExceptionCaptureCallback:qu,emitWarning:ko,nextTick:Uu,_tickCallback:Ho,_debugProcess:zo,_debugEnd:Ko,_startProfilerIdleNotifier:Vo,_stopProfilerIdleNotifier:Go,stdout:Yo,stdin:Jo,stderr:Qo,abort:Xo,umask:Eo,chdir:Ao,cwd:xo,env:bo,title:po,argv:yo,execArgv:vo,pid:Zo,ppid:es,execPath:ts,debugPort:rs,hrtime:Fr,argv0:ns,_preload_modules:is,setSourceMapsEnabled:os}});function Ku(){if(Ni)return wr;Ni=!0;var c=io;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 b=s.lastIndexOf("/");if(b!==s.length-1){b===-1?(s="",o=0):(s=s.slice(0,b),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,b=l<p?l:p,f=-1,g=0;g<=b;++g){if(g===b){if(p>b){if(i.charCodeAt(u+g)===47)return i.slice(u+g+1);if(g===0)return i.slice(u+g)}else l>b&&(n.charCodeAt(s+g)===47?f=g:g===0&&(f=0));break}var y=n.charCodeAt(s+g),k=i.charCodeAt(u+g);if(y!==k)break;y===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 b=n.charCodeAt(u);if(b===47){if(!l){s=u+1;break}}else p===-1&&(l=!1,p=u+1),d>=0&&(b===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,b=!0,f=n.length-1,g=0;f>=l;--f){if(s=n.charCodeAt(f),s===47){if(!b){d=f+1;break}continue}p===-1&&(b=!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,wr=a,wr}var wr,Ni,Ui,Vu=He(()=>{le(),ue(),ce(),Na(),wr={},Ni=!1,Ui=Ku()}),Ua={};Lt(Ua,{URL:()=>Va,Url:()=>Wa,default:()=>Fe,fileURLToPath:()=>Da,format:()=>qa,parse:()=>Ka,pathToFileURL:()=>Fa,resolve:()=>Ha,resolveObject:()=>za});function Gu(){if(Bi)return _r;Bi=!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,b=p?WeakRef.prototype.deref:null,f=Boolean.prototype.valueOf,g=Object.prototype.toString,y=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,D=typeof Symbol=="function"&&typeof Symbol.iterator=="object",N=typeof Symbol=="function"&&Symbol.toStringTag&&(typeof Symbol.toStringTag===D||!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),Ce=m.call(ie,Ie.length+1);return w.call(Ie,xe,"$&_")+"."+w.call(w.call(Ce,/([0-9]{3})/g,"$&_"),/_$/,"")}}return w.call(ie,xe,"$&_")}var re=$a,F=re.custom,Z=G(F)?F:null;_r=function z(ie,xe,Ae,Ie){var Ce=xe||{};if(oe(Ce,"quoteStyle")&&Ce.quoteStyle!=="single"&&Ce.quoteStyle!=="double")throw new TypeError('option "quoteStyle" must be "single" or "double"');if(oe(Ce,"maxStringLength")&&(typeof Ce.maxStringLength=="number"?Ce.maxStringLength<0&&Ce.maxStringLength!==1/0:Ce.maxStringLength!==null))throw new TypeError('option "maxStringLength", if provided, must be a positive integer, Infinity, or `null`');var Ge=oe(Ce,"customInspect")?Ce.customInspect:!0;if(typeof Ge!="boolean"&&Ge!=="symbol")throw new TypeError("option \"customInspect\", if provided, must be `true`, `false`, or `'symbol'`");if(oe(Ce,"indent")&&Ce.indent!==null&&Ce.indent!==" "&&!(parseInt(Ce.indent,10)===Ce.indent&&Ce.indent>0))throw new TypeError('option "indent" must be "\\t", an integer > 0, or `null`');if(oe(Ce,"numericSeparator")&&typeof Ce.numericSeparator!="boolean")throw new TypeError('option "numericSeparator", if provided, must be `true` or `false`');var Ye=Ce.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,Ce);if(typeof ie=="number"){if(ie===0)return 1/0/ie>0?"0":"-0";var Ue=String(ie);return Ye?K(ie,Ue):Ue}if(typeof ie=="bigint"){var Qe=String(ie)+"n";return Ye?K(ie,Qe):Qe}var Tt=typeof Ce.depth>"u"?5:Ce.depth;if(typeof Ae>"u"&&(Ae=0),Ae>=Tt&&Tt>0&&typeof ie=="object")return be(ie)?"[Array]":"[Object]";var Je=X(Ce,Ae);if(typeof Ie>"u")Ie=[];else if(ee(Ie,ie)>=0)return"[Circular]";function ze(Xe,ft,wt){if(ft&&(Ie=M.call(Ie),Ie.push(ft)),wt){var Ze={depth:Ce.depth};return oe(Ce,"quoteStyle")&&(Ze.quoteStyle=Ce.quoteStyle),z(Xe,Ze,Ae+1,Ie)}return z(Xe,Ce,Ae+1,Ie)}if(typeof ie=="function"&&!we(ie)){var Xt=$(ie),Ct=ke(ie,ze);return"[Function"+(Xt?": "+Xt:" (anonymous)")+"]"+(Ct.length>0?" { "+I.call(Ct,", ")+" }":"")}if(G(ie)){var Dt=D?w.call(String(ie),/^(Symbol\(.*\))_[^)]*$/,"$1"):W.call(ie);return typeof ie=="object"&&!D?h(Dt):Dt}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",Ce);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,ze);return Je&&!U(Se)?"["+he(Se,Je)+"]":"[ "+I.call(Se,", ")+" ]"}if(V(ie)){var Ee=ke(ie,ze);return!("cause"in Error.prototype)&&"cause"in ie&&!ae.call(ie,"cause")?"{ ["+String(ie)+"] "+I.call(S.call("[cause]: "+ze(ie.cause),Ee),", ")+" }":Ee.length===0?"["+String(ie)+"]":"{ ["+String(ie)+"] "+I.call(Ee,", ")+" }"}if(typeof ie=="object"&&Ge){if(Z&&typeof ie[Z]=="function"&&re)return re(ie,{depth:Tt-Ae});if(Ge!=="symbol"&&typeof ie.inspect=="function")return ie.inspect()}if(fe(ie)){var je=[];return r&&r.call(ie,function(Xe,ft){je.push(ze(ft,ie,!0)+" => "+ze(Xe,ie))}),A("Map",t.call(ie),je,Je)}if(q(ie)){var $e=[];return s&&s.call(ie,function(Xe){$e.push(ze(Xe,ie))}),A("Set",i.call(ie),$e,Je)}if(de(ie))return _("WeakMap");if(ge(ie))return _("WeakSet");if(ye(ie))return _("WeakRef");if(ne(ie))return h(ze(Number(ie)));if(Q(ie))return h(ze(B.call(ie)));if(H(ie))return h(f.call(ie));if(L(ie))return h(ze(String(ie)));if(typeof window<"u"&&ie===window)return"{ [object Window] }";if(typeof globalThis<"u"&&ie===globalThis||typeof kr<"u"&&ie===kr)return"{ [object globalThis] }";if(!te(ie)&&!we(ie)){var Ve=ke(ie,ze),Ft=Y?Y(ie)===Object.prototype:ie instanceof Object||ie.constructor===Object,$t=ie instanceof Object?"":"null prototype",Wt=!Ft&&N&&Object(ie)===ie&&N in ie?m.call(R(ie),8,-1):$t?"Object":"",Zt=Ft||typeof ie.constructor!="function"?"":ie.constructor.name?ie.constructor.name+" ":"",vt=Zt+(Wt||$t?"["+I.call(S.call([],Wt||[],$t||[]),": ")+"] ":"");return Ve.length===0?vt+"{}":Je?vt+"{"+he(Ve,Je)+"}":vt+"{ "+I.call(Ve,", ")+" }"}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(D)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||kr)};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(y.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(!b||!z||typeof z!="object")return!1;try{return b.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
+ "use strict";class Ts{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 Vr{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 Ts(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 Vi{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 Gl=1e3,Yl=10,Ql=400,Jl=600,ho="#6366f1",Xl=12,Zl="system-ui, -apple-system, sans-serif",fo="Type a message...",ec="bottom-right",tc="light",rc={x:20,y:20},Br="aikaara_conversation_id";class Cs extends Vi{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 Vr(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??Yl;if(this.reconnectAttempt>=e){this.emit("error",new Error("Max reconnection attempts reached"));return}this.setState("reconnecting");const r=(this.config.reconnectInterval??Gl)*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 Vr(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 Os{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 Ps{_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(a=>a.externalId&&a.externalId===e.externalId):void 0;return r?(Object.assign(r,e,{id:r.id}),{message:r,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=[]}}class Ms{_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(Br)}catch{}}loadFromStorage(){if(!this.persist)return null;try{return localStorage.getItem(Br)}catch{return null}}saveToStorage(e){try{localStorage.setItem(Br,e)}catch{}}}var Gi=Object.defineProperty,nc=Object.getOwnPropertyDescriptor,ic=Object.getOwnPropertyNames,oc=Object.prototype.hasOwnProperty,He=(c,e)=>()=>(c&&(e=c(c=0)),e),pe=(c,e)=>()=>(e||c((e={exports:{}}).exports,e),e.exports),Lt=(c,e)=>{for(var t in e)Gi(c,t,{get:e[t],enumerable:!0})},sc=(c,e,t,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let a of ic(e))!oc.call(c,a)&&a!==t&&Gi(c,a,{get:()=>e[a],enumerable:!(r=nc(e,a))||r.enumerable});return c},Oe=c=>sc(Gi({},"__esModule",{value:!0}),c),le=He(()=>{}),Pe={};Lt(Pe,{_debugEnd:()=>Tn,_debugProcess:()=>In,_events:()=>qn,_eventsCount:()=>Hn,_exiting:()=>dn,_fatalExceptions:()=>En,_getActiveHandles:()=>Ds,_getActiveRequests:()=>Bs,_kill:()=>mn,_linkedBinding:()=>Ns,_maxListeners:()=>Wn,_preload_modules:()=>Fn,_rawDebug:()=>un,_startProfilerIdleNotifier:()=>Cn,_stopProfilerIdleNotifier:()=>On,_tickCallback:()=>An,abort:()=>jn,addListener:()=>zn,allowedNodeEnvironmentFlags:()=>kn,arch:()=>Yr,argv:()=>Xr,argv0:()=>Dn,assert:()=>Fs,binding:()=>nn,browser:()=>cn,chdir:()=>an,config:()=>pn,cpuUsage:()=>qt,cwd:()=>sn,debugPort:()=>Bn,default:()=>Qi,dlopen:()=>Us,domain:()=>fn,emit:()=>Qn,emitWarning:()=>rn,env:()=>Jr,execArgv:()=>Zr,execPath:()=>Un,exit:()=>wn,features:()=>Sn,hasUncaughtExceptionCaptureCallback:()=>$s,hrtime:()=>ir,kill:()=>vn,listeners:()=>qs,memoryUsage:()=>yn,moduleLoadList:()=>hn,nextTick:()=>js,off:()=>Vn,on:()=>nt,once:()=>Kn,openStdin:()=>_n,pid:()=>Ln,platform:()=>Qr,ppid:()=>Nn,prependListener:()=>Jn,prependOnceListener:()=>Xn,reallyExit:()=>gn,release:()=>ln,removeAllListeners:()=>Yn,removeListener:()=>Gn,resourceUsage:()=>bn,setSourceMapsEnabled:()=>$n,setUncaughtExceptionCaptureCallback:()=>xn,stderr:()=>Mn,stdin:()=>Rn,stdout:()=>Pn,title:()=>Gr,umask:()=>on,uptime:()=>Ws,version:()=>en,versions:()=>tn});function Yi(c){throw new Error("Node.js process "+c+" is not supported by JSPM core outside of Node.js")}function ac(){!St||!_t||(St=!1,_t.length?et=_t.concat(et):Vt=-1,et.length&&Rs())}function Rs(){if(!St){var c=setTimeout(ac,0);St=!0;for(var e=et.length;e;){for(_t=et,et=[];++Vt<e;)_t&&_t[Vt].run();Vt=-1,e=et.length}_t=null,St=!1,clearTimeout(c)}}function js(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];et.push(new Ls(c,e)),et.length===1&&!St&&setTimeout(Rs,0)}function Ls(c,e){this.fun=c,this.array=e}function Be(){}function Ns(c){Yi("_linkedBinding")}function Us(c){Yi("dlopen")}function Bs(){return[]}function Ds(){return[]}function Fs(c,e){if(!c)throw new Error(e||"assertion error")}function $s(){return!1}function Ws(){return ot.now()/1e3}function ir(c){var e=Math.floor((Date.now()-ot.now())*.001),t=ot.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+=or)),[r,a]}function nt(){return Qi}function qs(c){return[]}var et,St,_t,Vt,Gr,Yr,Qr,Jr,Xr,Zr,en,tn,rn,nn,on,sn,an,ln,cn,un,hn,fn,dn,pn,gn,mn,qt,bn,yn,vn,wn,_n,kn,Sn,En,xn,An,In,Tn,Cn,On,Pn,Mn,Rn,jn,Ln,Nn,Un,Bn,Dn,Fn,$n,ot,Dr,or,Wn,qn,Hn,zn,Kn,Vn,Gn,Yn,Qn,Jn,Xn,Qi,lc=He(()=>{le(),ue(),ce(),et=[],St=!1,Vt=-1,Ls.prototype.run=function(){this.fun.apply(null,this.array)},Gr="browser",Yr="x64",Qr="browser",Jr={PATH:"/usr/bin",LANG:typeof navigator<"u"?navigator.language+".UTF-8":void 0,PWD:"/",HOME:"/home",TMP:"/tmp"},Xr=["/usr/bin/node"],Zr=[],en="v16.8.0",tn={},rn=function(c,e){console.warn((e?e+": ":"")+c)},nn=function(c){Yi("binding")},on=function(c){return 0},sn=function(){return"/"},an=function(c){},ln={name:"node",sourceUrl:"",headersUrl:"",libUrl:""},cn=!0,un=Be,hn=[],fn={},dn=!1,pn={},gn=Be,mn=Be,qt=function(){return{}},bn=qt,yn=qt,vn=Be,wn=Be,_n=Be,kn={},Sn={inspector:!1,debug:!1,uv:!1,ipv6:!1,tls_alpn:!1,tls_sni:!1,tls_ocsp:!1,tls:!1,cached_builtins:!0},En=Be,xn=Be,An=Be,In=Be,Tn=Be,Cn=Be,On=Be,Pn=void 0,Mn=void 0,Rn=void 0,jn=Be,Ln=2,Nn=1,Un="/bin/usr/node",Bn=9229,Dn="node",Fn=[],$n=Be,ot={now:typeof performance<"u"?performance.now.bind(performance):void 0,timing:typeof performance<"u"?performance.timing:void 0},ot.now===void 0&&(Dr=Date.now(),ot.timing&&ot.timing.navigationStart&&(Dr=ot.timing.navigationStart),ot.now=()=>Date.now()-Dr),or=1e9,ir.bigint=function(c){var e=ir(c);return typeof BigInt>"u"?e[0]*or+e[1]:BigInt(e[0]*or)+BigInt(e[1])},Wn=10,qn={},Hn=0,zn=nt,Kn=nt,Vn=nt,Gn=nt,Yn=nt,Qn=Be,Jn=nt,Xn=nt,Qi={version:en,versions:tn,arch:Yr,platform:Qr,browser:cn,release:ln,_rawDebug:un,moduleLoadList:hn,binding:nn,_linkedBinding:Ns,_events:qn,_eventsCount:Hn,_maxListeners:Wn,on:nt,addListener:zn,once:Kn,off:Vn,removeListener:Gn,removeAllListeners:Yn,emit:Qn,prependListener:Jn,prependOnceListener:Xn,listeners:qs,domain:fn,_exiting:dn,config:pn,dlopen:Us,uptime:Ws,_getActiveRequests:Bs,_getActiveHandles:Ds,reallyExit:gn,_kill:mn,cpuUsage:qt,resourceUsage:bn,memoryUsage:yn,kill:vn,exit:wn,openStdin:_n,allowedNodeEnvironmentFlags:kn,assert:Fs,features:Sn,_fatalExceptions:En,setUncaughtExceptionCaptureCallback:xn,hasUncaughtExceptionCaptureCallback:$s,emitWarning:rn,nextTick:js,_tickCallback:An,_debugProcess:In,_debugEnd:Tn,_startProfilerIdleNotifier:Cn,_stopProfilerIdleNotifier:On,stdout:Pn,stdin:Rn,stderr:Mn,abort:jn,umask:on,chdir:an,cwd:sn,env:Jr,title:Gr,argv:Xr,execArgv:Zr,pid:Ln,ppid:Nn,execPath:Un,debugPort:Bn,hrtime:ir,argv0:Dn,_preload_modules:Fn,setSourceMapsEnabled:$n}}),ce=He(()=>{lc()});function cc(){if(Zn)return Ot;Zn=!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 uc(){return ei?Ht:(ei=!0,Ht.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)},Ht.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},Ht)}function hc(){if(ti)return pt;ti=!0;let c=cc(),e=uc(),t=typeof Symbol=="function"&&typeof Symbol.for=="function"?Symbol.for("nodejs.util.inspect.custom"):null;pt.Buffer=i,pt.SlowBuffer=k,pt.INSPECT_MAX_BYTES=50;let r=2147483647;pt.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="",_=pt.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 D=4096;function N(h){let _=h.length;if(_<=D)return String.fromCharCode.apply(String,h);let A="",U=0;for(;U<_;)A+=String.fromCharCode.apply(String,h.slice(U,U+=D));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 F(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||F(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||F(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,_||F(h,1,this.length),this[h]},i.prototype.readUint16LE=i.prototype.readUInt16LE=function(h,_){return h=h>>>0,_||F(h,2,this.length),this[h]|this[h+1]<<8},i.prototype.readUint16BE=i.prototype.readUInt16BE=function(h,_){return h=h>>>0,_||F(h,2,this.length),this[h]<<8|this[h+1]},i.prototype.readUint32LE=i.prototype.readUInt32LE=function(h,_){return h=h>>>0,_||F(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,_||F(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||F(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||F(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,_||F(h,1,this.length),this[h]&128?(255-this[h]+1)*-1:this[h]},i.prototype.readInt16LE=function(h,_){h=h>>>0,_||F(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,_||F(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,_||F(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,_||F(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]*2**8+this[++h]*2**16+this[++h]*2**24)}),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]*2**24+this[++h]*2**16+this[++h]*2**8+A)}),i.prototype.readFloatLE=function(h,_){return h=h>>>0,_||F(h,4,this.length),e.read(this,h,!0,23,4)},i.prototype.readFloatBE=function(h,_){return h=h>>>0,_||F(h,4,this.length),e.read(this,h,!1,23,4)},i.prototype.readDoubleLE=function(h,_){return h=h>>>0,_||F(h,8,this.length),e.read(this,h,!0,52,8)},i.prototype.readDoubleBE=function(h,_){return h=h>>>0,_||F(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)>2**32?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 pt}var Ot,Zn,Ht,ei,pt,ti,fc=He(()=>{le(),ue(),ce(),Ot={},Zn=!1,Ht={},ei=!1,pt={},ti=!1}),Le={};Lt(Le,{Buffer:()=>Cr,INSPECT_MAX_BYTES:()=>Hs,default:()=>it,kMaxLength:()=>zs});var it,Cr,Hs,zs,Ne=He(()=>{le(),ue(),ce(),fc(),it=hc(),it.Buffer,it.SlowBuffer,it.INSPECT_MAX_BYTES,it.kMaxLength,Cr=it.Buffer,Hs=it.INSPECT_MAX_BYTES,zs=it.kMaxLength}),ue=He(()=>{Ne()}),Re=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}}),Ks=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}=Ks(),{AggregateError:a}=Re(),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}}),Yt=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}),bt={};Lt(bt,{EventEmitter:()=>Vs,default:()=>Pt,defaultMaxListeners:()=>Gs,init:()=>Ys,listenerCount:()=>Qs,on:()=>Js,once:()=>Xs});function dc(){if(ri)return zt;ri=!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)}zt=n,zt.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 zt}var zt,ri,Pt,Vs,Gs,Ys,Qs,Js,Xs,xt=He(()=>{le(),ue(),ce(),zt={},ri=!1,Pt=dc(),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:Vs,defaultMaxListeners:Gs,init:Ys,listenerCount:Qs,on:Js,once:Xs}=Pt}),qe=pe((c,e)=>{le(),ue(),ce();var t=(Ne(),Oe(Le)),{format:r,inspect:a}=Ks(),{codes:{ERR_INVALID_ARG_TYPE:n}}=We(),{kResistStopPropagation:i,AggregateError:s,SymbolDispose:o}=Re(),l=globalThis.AbortSignal||Yt().AbortSignal,u=globalThis.AbortController||Yt().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:(xt(),Oe(bt)).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")}),Qt=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}=Re(),{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}=qe(),{isAsyncFunction:S,isArrayBufferView:I}=qe().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 D(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 F=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:D,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:F,validatePlainFunction:R,validatePort:Q,validateSignalName:ne,validateString:K,validateUint32:Y,validateUndefined:$,validateUnion:ee,validateAbortSignal:me,validateLinkHeaderValue:ye}}),At=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}}),ct=pe((c,e)=>{le(),ue(),ce();var{SymbolAsyncIterator:t,SymbolIterator:r,SymbolFor:a}=Re(),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 D(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 F(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:F,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:D,isNodeStream:g,isWebStream:w,isWritable:B,isWritableNodeStream:y,isWritableStream:k,isWritableEnded:x,isWritableFinished:S,isWritableErrored:W,isServerRequest:K,isServerResponse:Y,willEmitClose:re,isTransformStream:m}}),yt=pe((c,e)=>{le(),ue(),ce();var t=At(),{AbortError:r,codes:a}=We(),{ERR_INVALID_ARG_TYPE:n,ERR_STREAM_PREMATURE_CLOSE:i}=a,{kEmptyObject:s,once:o}=qe(),{validateAbortSignal:l,validateFunction:u,validateObject:d,validateBoolean:p}=Qt(),{Promise:y,PromisePrototypeThen:f,SymbolDispose:g}=Re(),{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}=ct(),D;function N(F){return F.setHeader&&typeof F.abort=="function"}var ae=()=>{};function Y(F,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(F)||I(F))return K(F,Z,P);if(!B(F))throw new n("stream",["ReadableStream","WritableStream","Stream"],F);let te=(J=Z.readable)!==null&&J!==void 0?J:m(F),we=(be=Z.writable)!==null&&be!==void 0?be:S(F),V=F._writableState,L=F._readableState,ne=()=>{F.writable||Q()},H=T(F)&&m(F)===te&&S(F)===we,G=M(F,!1),Q=()=>{G=!0,F.destroyed&&(H=!1),!(H&&(!F.readable||te))&&(!te||me)&&P.call(F)},me=E(F,!1),oe=()=>{me=!0,F.destroyed&&(H=!1),!(H&&(!F.writable||we))&&(!we||G)&&P.call(F)},R=q=>{P.call(F,q)},$=b(F),ee=()=>{$=!0;let q=O(F)||v(F);if(q&&typeof q!="boolean")return P.call(F,q);if(te&&!me&&m(F,!0)&&!E(F,!1))return P.call(F,new i);if(we&&!G&&!M(F,!1))return P.call(F,new i);P.call(F)},fe=()=>{$=!0;let q=O(F)||v(F);if(q&&typeof q!="boolean")return P.call(F,q);P.call(F)},de=()=>{F.req.on("finish",Q)};N(F)?(F.on("complete",Q),H||F.on("abort",ee),F.req?de():F.on("request",de)):we&&!V&&(F.on("end",ne),F.on("close",ne)),!H&&typeof F.aborted=="boolean"&&F.on("aborted",ee),F.on("end",oe),F.on("finish",Q),Z.error!==!1&&F.on("error",R),F.on("close",ee),$?t.nextTick(ee):V!=null&&V.errorEmitted||L!=null&&L.errorEmitted?H||t.nextTick(fe):(!te&&(!H||k(F))&&(G||x(F)===!1)||!we&&(!H||x(F))&&(me||k(F)===!1)||L&&F.req&&F.aborted)&&t.nextTick(fe);let ye=()=>{P=ae,F.removeListener("aborted",ee),F.removeListener("complete",Q),F.removeListener("abort",ee),F.removeListener("request",de),F.req&&F.req.removeListener("finish",Q),F.removeListener("end",ne),F.removeListener("close",ne),F.removeListener("finish",Q),F.removeListener("end",oe),F.removeListener("error",R),F.removeListener("close",ee)};if(Z.signal&&!$){let q=()=>{let ge=P;ye(),ge.call(F,new r(void 0,{cause:Z.signal.reason}))};if(Z.signal.aborted)t.nextTick(q);else{D=D||qe().addAbortListener;let ge=D(Z.signal,q),ve=P;P=o((...se)=>{ge[g](),ve.apply(F,se)})}}return ye}function K(F,Z,P){let J=!1,be=ae;if(Z.signal)if(be=()=>{J=!0,P.call(F,new r(void 0,{cause:Z.signal.reason}))},Z.signal.aborted)t.nextTick(be);else{D=D||qe().addAbortListener;let we=D(Z.signal,be),V=P;P=o((...L)=>{we[g](),V.apply(F,L)})}let te=(...we)=>{J||t.nextTick(()=>P.apply(F,we))};return f(F[W].promise,te,te),ae}function re(F,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(F,Z,V=>{J&&we(),V?te(V):be()})})}e.exports=Y,e.exports.finished=re}),Nt=pe((c,e)=>{le(),ue(),ce();var t=At(),{aggregateTwoErrors:r,codes:{ERR_MULTIPLE_CALLBACK:a},AbortError:n}=We(),{Symbol:i}=Re(),{kIsDestroyed:s,isDestroyed:o,isFinished:l,isServerRequest:u}=ct(),d=i("kDestroy"),p=i("kConstruct");function y(T,W,D){T&&(T.stack,W&&!W.errored&&(W.errored=T),D&&!D.errored&&(D.errored=T))}function f(T,W){let D=this._readableState,N=this._writableState,ae=N||D;return N!=null&&N.destroyed||D!=null&&D.destroyed?(typeof W=="function"&&W(),this):(y(T,N,D),N&&(N.destroyed=!0),D&&(D.destroyed=!0),ae.constructed?g(this,T,W):this.once(d,function(Y){g(this,r(Y,T),W)}),this)}function g(T,W,D){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 D=="function"&&D(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,D=T._writableState;D&&(D.closeEmitted=!0),W&&(W.closeEmitted=!0),(D!=null&&D.emitClose||W!=null&&W.emitClose)&&T.emit("close")}function m(T,W){let D=T._readableState,N=T._writableState;N!=null&&N.errorEmitted||D!=null&&D.errorEmitted||(N&&(N.errorEmitted=!0),D&&(D.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,D){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),D?t.nextTick(m,T,W):m(T,W))}function v(T,W){if(typeof T._construct!="function")return;let D=T._readableState,N=T._writableState;D&&(D.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 D(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(D,N)})}catch(N){t.nextTick(D,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}}),Ji=pe((c,e)=>{le(),ue(),ce();var{ArrayIsArray:t,ObjectSetPrototypeOf:r}=Re(),{EventEmitter:a}=(xt(),Oe(bt));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}}),Mr=pe((c,e)=>{le(),ue(),ce();var{SymbolDispose:t}=Re(),{AbortError:r,codes:a}=We(),{isNodeStream:n,isWebStream:i,kControllerErrorFunction:s}=ct(),o=yt(),{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||qe().addAbortListener;let g=u(p,f);o(y,g[t])}return y}}),pc=pe((c,e)=>{le(),ue(),ce();var{StringPrototypeSlice:t,SymbolIterator:r,TypedArrayPrototypeSet:a,Uint8Array:n}=Re(),{Buffer:i}=(Ne(),Oe(Le)),{inspect:s}=qe();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})}}}),Rr=pe((c,e)=>{le(),ue(),ce();var{MathFloor:t,NumberIsInteger:r}=Re(),{validateInteger:a}=Qt(),{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}}),gc=pe((c,e)=>{le(),ue(),ce();var t=(Ne(),Oe(Le)),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)}}),mc=pe(c=>{le(),ue(),ce();var e=gc().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):""}}),Zs=pe((c,e)=>{le(),ue(),ce();var t=At(),{PromisePrototypeThen:r,SymbolAsyncIterator:a,SymbolIterator:n}=Re(),{Buffer:i}=(Ne(),Oe(Le)),{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}),jr=pe((c,e)=>{le(),ue(),ce();var t=At(),{ArrayPrototypeIndexOf:r,NumberIsInteger:a,NumberIsNaN:n,NumberParseInt:i,ObjectDefineProperties:s,ObjectKeys:o,ObjectSetPrototypeOf:l,Promise:u,SafeSet:d,SymbolAsyncDispose:p,SymbolAsyncIterator:y,Symbol:f}=Re();e.exports=se,se.ReadableState=ve;var{EventEmitter:g}=(xt(),Oe(bt)),{Stream:b,prependListener:k}=Ji(),{Buffer:m}=(Ne(),Oe(Le)),{addAbortSignal:w}=Mr(),E=yt(),v=qe().debuglog("stream",C=>{v=C}),x=pc(),S=Nt(),{getHighWaterMark:I,getDefaultHighWaterMark:M}=Rr(),{aggregateTwoErrors:O,codes:{ERR_INVALID_ARG_TYPE:B,ERR_METHOD_NOT_IMPLEMENTED:T,ERR_OUT_OF_RANGE:W,ERR_STREAM_PUSH_AFTER_EOF:D,ERR_STREAM_UNSHIFT_AFTER_END_EVENT:N},AbortError:ae}=We(),{validateObject:Y}=Qt(),K=f("kPaused"),{StringDecoder:re}=mc(),F=Zs();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,je;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&&(je=new B("chunk",["string","Buffer","Uint8Array"],j))),je)P(C,je);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 D);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?Je(this):he(this),null;if(C=U(C,j),C===0&&j.ended)return j.length===0&&Je(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(je){P(this,je)}j.state&=~L,j.reading||(C=U(_e,j))}let Ee;return C>0?Ee=Tt(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&&Je(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,Ye(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?$e:wt;Se.endEmitted?t.nextTick(Ee):_e.once("end",Ee),C.on("unpipe",je);function je(Ze,rt){v("onunpipe"),Ze===_e&&rt&&rt.hasUnpiped===!1&&(rt.hasUnpiped=!0,$t())}function $e(){v("onend"),C.end()}let Ve,Ft=!1;function $t(){v("cleanup"),C.removeListener("close",Xe),C.removeListener("finish",ft),Ve&&C.removeListener("drain",Ve),C.removeListener("error",vt),C.removeListener("unpipe",je),_e.removeListener("end",$e),_e.removeListener("end",wt),_e.removeListener("data",Zt),Ft=!0,Ve&&Se.awaitDrainWriters&&(!C._writableState||C._writableState.needDrain)&&Ve()}function Wt(){Ft||(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()),Ve||(Ve=xe(_e,C),C.on("drain",Ve))}_e.on("data",Zt);function Zt(Ze){v("ondata");let rt=C.write(Ze);v("dest.write",rt),rt===!1&&Wt()}function vt(Ze){if(v("onerror",Ze),wt(),C.removeListener("error",vt),C.listenerCount("error")===0){let rt=C._writableState||C._readableState;rt&&!rt.errorEmitted?P(C,Ze):C.emit("error",Ze)}}k(C,"error",vt);function Xe(){C.removeListener("finish",ft),wt()}C.once("close",Xe);function ft(){v("onfinish"),C.removeListener("close",Xe),wt()}C.once("finish",ft);function wt(){v("unpipe"),_e.unpipe(C)}return C.emit("pipe",_e),C.writableNeedDrain===!0?Wt():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 je=0;je<Ee.length;je++)Ee[je].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,Ce(this,C)),C[K]=!1,this};function Ce(C,j){j.resumeScheduled||(j.resumeScheduled=!0,t.nextTick(Ge,C,j))}function Ge(C,j){v("resume",j.reading),j.reading||C.read(0),j.resumeScheduled=!1,C.emit("resume"),Ye(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 Ye(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 Ue(this)},se.prototype.iterator=function(C){return C!==void 0&&Y(C,"options"),Ue(this,C)};function Ue(C,j){typeof C.read!="function"&&(C=se.wrap(C,{objectMode:!0}));let _e=Qe(C,j);return _e.stream=C,_e}async function*Qe(C,j){let _e=Z;function Se($e){this===C?(_e(),_e=Z):_e=$e}C.on("readable",Se);let Ee,je=E(C,{writable:!1},$e=>{Ee=$e?O(Ee,$e):null,_e(),_e=Z});try{for(;;){let $e=C.destroyed?null:C.read();if($e!==null)yield $e;else{if(Ee)throw Ee;if(Ee===null)return;await new u(Se)}}}catch($e){throw Ee=O(Ee,$e),Ee}finally{(Ee||j?.destroyOnReturn!==!1)&&(Ee===void 0||C._readableState.autoDestroy)?S.destroyer(C,null):(C.off("readable",Se),je())}}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=Tt;function Tt(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 Je(C){let j=C._readableState;v("endReadable",j.endEmitted),j.endEmitted||(j.ended=!0,t.nextTick(ze,j,C))}function ze(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(Xt,j);else if(C.autoDestroy){let _e=j._writableState;(!_e||_e.autoDestroy&&(_e.finished||_e.writable===!1))&&j.destroy()}}}function Xt(C){C.writable&&!C.writableEnded&&!C.destroyed&&C.end()}se.from=function(C,j){return F(se,C,j)};var Ct;function Dt(){return Ct===void 0&&(Ct={}),Ct}se.fromWeb=function(C,j){return Dt().newStreamReadableFromReadableStream(C,j)},se.toWeb=function(C,j){return Dt().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,je){S.destroyer(C,Ee),je(Ee)}}).wrap(C)}}),Xi=pe((c,e)=>{le(),ue(),ce();var t=At(),{ArrayPrototypeSlice:r,Error:a,FunctionPrototypeSymbolHasInstance:n,ObjectDefineProperty:i,ObjectDefineProperties:s,ObjectSetPrototypeOf:o,StringPrototypeToLowerCase:l,Symbol:u,SymbolHasInstance:d}=Re();e.exports=Y,Y.WritableState=N;var{EventEmitter:p}=(xt(),Oe(bt)),y=Ji().Stream,{Buffer:f}=(Ne(),Oe(Le)),g=Nt(),{addAbortSignal:b}=Mr(),{getHighWaterMark:k,getDefaultHighWaterMark:m}=Rr(),{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 D=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[D]=[]}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 F(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[D].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,F(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;F(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[D].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=$[D].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=$[D].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[D].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)}}),bc=pe((c,e)=>{le(),ue(),ce();var t=At(),r=(Ne(),Oe(Le)),{isReadable:a,isWritable:n,isIterable:i,isNodeStream:s,isReadableNodeStream:o,isWritableNodeStream:l,isDuplexNodeStream:u,isReadableStream:d,isWritableStream:p}=ct(),y=yt(),{AbortError:f,codes:{ERR_INVALID_ARG_TYPE:g,ERR_INVALID_RETURN_VALUE:b}}=We(),{destroyer:k}=Nt(),m=at(),w=jr(),E=Xi(),{createDeferredPromise:v}=qe(),x=Zs(),S=globalThis.Blob||r.Blob,I=typeof S<"u"?function(D){return D instanceof S}:function(D){return!1},M=globalThis.AbortController||Yt().AbortController,{FunctionPrototypeCall:O}=Re(),B=class extends m{constructor(D){super(D),D?.readable===!1&&(this._readableState.readable=!1,this._readableState.ended=!0,this._readableState.endEmitted=!0),D?.writable===!1&&(this._writableState.writable=!1,this._writableState.ending=!0,this._writableState.ended=!0,this._writableState.finished=!0)}};e.exports=function D(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:F,destroy:Z}=T(N);if(i(K))return x(B,K,{objectMode:!0,write:re,final:F,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){F(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 D(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:D(N.readable):void 0,re=N!=null&&N.writable?l(N?.writable)?N?.writable:D(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(D){let{promise:N,resolve:ae}=v(),Y=new M,K=Y.signal;return{value:D((async function*(){for(;;){let re=N;N=null;let{chunk:F,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 F}})(),{signal:K}),write(re,F,Z){let P=ae;ae=null,P({chunk:re,done:!1,cb:Z})},final(re){let F=ae;ae=null,F({done:!0,cb:re})},destroy(re,F){Y.abort(),F(re)}}}function W(D){let N=D.readable&&typeof D.readable.read!="function"?w.wrap(D.readable):D.readable,ae=D.writable,Y=!!a(N),K=!!n(ae),re,F,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(),F=te},ae.on("drain",function(){if(re){let te=re;re=null,te()}}),ae.on("finish",function(){if(F){let te=F;F=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,F=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}=Re();e.exports=o;var i=jr(),s=Xi();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=bc()),d(p,"body")}}),ea=pe((c,e)=>{le(),ue(),ce();var{ObjectSetPrototypeOf:t,Symbol:r}=Re();e.exports=o;var{ERR_METHOD_NOT_IMPLEMENTED:a}=We().codes,n=at(),{getHighWaterMark:i}=Rr();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()}}}),ta=pe((c,e)=>{le(),ue(),ce();var{ObjectSetPrototypeOf:t}=Re();e.exports=a;var r=ea();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)}}),Zi=pe((c,e)=>{le(),ue(),ce();var t=At(),{ArrayIsArray:r,Promise:a,SymbolAsyncIterator:n,SymbolDispose:i}=Re(),s=yt(),{once:o}=qe(),l=Nt(),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}=Qt(),{isIterable:E,isReadable:v,isReadableNodeStream:x,isNodeStream:S,isTransformStream:I,isWebStream:M,isReadableStream:O,isReadableFinished:B}=ct(),T=globalThis.AbortController||Yt().AbortController,W,D,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){D||(D=jr()),yield*D.prototype[n].call(te)}async function F(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||qe().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=ta());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++,F(ye,U,fe,{end:_});else if(O(ye)||I(ye)){let z=ye.readable||ye;ee++,F(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++,F(U,se,fe,{end:_})}else if(E(ye))ee++,F(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}}),ra=pe((c,e)=>{le(),ue(),ce();var{pipeline:t}=Zi(),r=at(),{destroyer:a}=Nt(),{isNodeStream:n,isReadable:i,isWritable:s,isWebStream:o,isTransformStream:l,isWritableStream:u,isReadableStream:d}=ct(),{AbortError:p,codes:{ERR_INVALID_ARG_VALUE:y,ERR_MISSING_ARGS:f}}=We(),g=yt();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,D,N){I.write(W,D)?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(D,N,ae){try{await W.ready,W.write(D).catch(()=>{}),ae()}catch(Y){ae(Y)}},x._final=async function(D){try{await W.ready,W.close().catch(()=>{}),w=D}catch(N){D(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:D}=await T.read();if(!x.push(W))return;if(D){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}}),yc=pe((c,e)=>{le(),ue(),ce();var t=globalThis.AbortController||Yt().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}=Qt(),d=Re().Symbol("kWeak"),p=Re().Symbol("kResistStopPropagation"),{finished:y}=yt(),f=ra(),{addAbortSignalNoValidate:g}=Mr(),{isWritable:b,isNodeStream:k}=ct(),{deprecate:m}=qe(),{ArrayPrototypePush:w,Boolean:E,MathFloor:v,Number:x,NumberIsNaN:S,Promise:I,PromiseReject:M,PromiseResolve:O,PromisePrototypeThen:B,Symbol:T}=Re(),W=T("kEmpty"),D=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=qe().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(D)}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===D)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 F(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:F}}),na=pe((c,e)=>{le(),ue(),ce();var{ArrayPrototypePop:t,Promise:r}=Re(),{isIterable:a,isNodeStream:n,isWebStream:i}=ct(),{pipelineImpl:s}=Zi(),{finished:o}=yt();ia();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}}),ia=pe((c,e)=>{le(),ue(),ce();var{Buffer:t}=(Ne(),Oe(Le)),{ObjectDefineProperty:r,ObjectKeys:a,ReflectApply:n}=Re(),{promisify:{custom:i}}=qe(),{streamReturningOperators:s,promiseReturningOperators:o}=yc(),{codes:{ERR_ILLEGAL_CONSTRUCTOR:l}}=We(),u=ra(),{setDefaultHighWaterMark:d,getDefaultHighWaterMark:p}=Rr(),{pipeline:y}=Zi(),{destroyer:f}=Nt(),g=yt(),b=na(),k=ct(),m=e.exports=Ji().Stream;m.isDestroyed=k.isDestroyed,m.isDisturbed=k.isDisturbed,m.isErrored=k.isErrored,m.isReadable=k.isReadable,m.isWritable=k.isWritable,m.Readable=jr();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=Xi(),m.Duplex=at(),m.Transform=ea(),m.PassThrough=ta(),m.pipeline=y;var{addAbortSignal:w}=Mr();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)}}),It=pe((c,e)=>{le(),ue(),ce();var t=ia(),r=na(),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}),vc=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}}}),wc=pe((c,e)=>{le(),ue(),ce();var{Buffer:t}=(Ne(),Oe(Le)),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}),_c=pe((c,e)=>{le(),ue(),ce();var t=It().Duplex,r=vc(),a=wc();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}),kc=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}),oa=pe((c,e)=>{le(),ue(),ce();var t=e.exports,{Buffer:r}=(Ne(),Oe(Le));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"}}),Sc=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":"")}}),Ec=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=Sc(),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 Pe<"u"&&"env"in Pe&&(o=Pe.env.DEBUG),o}function i(){try{return localStorage}catch{}}e.exports=Ec()(c);var{formatters:s}=e.exports;s.j=function(o){try{return JSON.stringify(o)}catch(l){return"[UnexpectedJSONParseError]: "+l.message}}}),xc=pe((c,e)=>{le(),ue(),ce();var t=_c(),{EventEmitter:r}=(xt(),Oe(bt)),a=kc(),n=oa(),i=lt()("mqtt-packet:parser"),s=class ni extends r{constructor(){super(),this.parser=this.constructor.parser}static parser(l){return this instanceof ni?(this.settings=l||{},this._states=["_parseHeader","_parseLength","_parsePayload","_newPacket"],this._resetState(),this):new ni().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}),Ac=pe((c,e)=>{le(),ue(),ce();var{Buffer:t}=(Ne(),Oe(Le)),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}}),Ic=pe((c,e)=>{le(),ue(),ce(),typeof Pe>"u"||!Pe.version||Pe.version.indexOf("v0.")===0||Pe.version.indexOf("v1.")===0&&Pe.version.indexOf("v1.8.")!==0?e.exports={nextTick:t}:e.exports=Pe;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 Pe.nextTick(r);case 2:return Pe.nextTick(function(){r.call(null,a)});case 3:return Pe.nextTick(function(){r.call(null,a,n)});case 4:return Pe.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 Pe.nextTick(function(){r.apply(null,o)})}}}),sa=pe((c,e)=>{le(),ue(),ce();var t=oa(),{Buffer:r}=(Ne(),Oe(Le)),a=r.allocUnsafe(0),n=r.from([0]),i=Ac(),s=Ic().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),D(L,ye),F(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(),F(L,$),me&&(Q===5&&ge.write(),N(L,me.topic),F(L,me.payload)),ee!=null&&F(L,ee),fe!=null&&F(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),D(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]),D(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),D(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]),D(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),D(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]),D(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]),D(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])),D(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])),D(L,oe),L.write(r.from([Q])),R!==null&&R.write(),!0):!1}var W={};function D(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 F(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]])),F(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]])),D(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){D(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}),Tc=pe((c,e)=>{le(),ue(),ce();var t=sa(),{EventEmitter:r}=(xt(),Oe(bt)),{Buffer:a}=(Ne(),Oe(Le));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}),Cc=pe(c=>{le(),ue(),ce(),c.parser=xc().parser,c.generate=Tc(),c.writeToStream=sa()}),Oc=pe((c,e)=>{le(),ue(),ce(),e.exports=r;function t(n){return n instanceof Cr?Cr.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}}}),Pc=pe((c,e)=>{le(),ue(),ce(),e.exports=Oc()()}),aa=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}}),la=pe(c=>{le(),ue(),ce(),Object.defineProperty(c,"__esModule",{value:!0});var e=It(),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}),Mc=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}),Rc=pe((c,e)=>{e.exports={version:"5.15.0"}}),Ut=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 ca extends Error{code;constructor(n,i){super(n),this.code=i,Object.setPrototypeOf(this,ca.prototype),Object.getPrototypeOf(this).name="ErrorWithReasonCode"}};c.ErrorWithReasonCode=e;var t=class ua extends Error{packet;constructor(n,i){super(n),this.packet=i,Object.setPrototypeOf(this,ua.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 Pe?.nextTick=="function"?Pe.nextTick:a=>{setTimeout(a,0)},c.MQTTJS_VERSION=Rc().version}),Lr=pe(c=>{le(),ue(),ce(),Object.defineProperty(c,"__esModule",{value:!0}),c.ReasonCodes=void 0;var e=Ut();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}),jc=pe(c=>{le(),ue(),ce(),Object.defineProperty(c,"__esModule",{value:!0});var e=Ut(),t=Lr(),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}),Lc=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 Pe=="object"&&Pe?Pe:{},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 Kt{heap;length;static#l=!1;static create(f){let g=l(f);if(!g)return[];Kt.#l=!0;let b=new Kt(f,g);return Kt.#l=!1,b}constructor(f,g){if(!Kt.#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 ha{#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:D,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 F=g?l(g):Array;if(!F)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(D!==void 0&&typeof D!="function")throw new TypeError("memoMethod must be a function if defined");if(this.#P=D,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 F(g),this.#f=new F(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,ha))}}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:D}=w.signal,N=b.ignoreFetchAbort&&T!==void 0;if(b.status&&(D&&!W?(b.status.fetchAborted=!0,b.status.fetchError=w.signal.reason,N&&(b.status.fetchAbortIgnored=!0)):b.status.fetchResolved=!0),D&&!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,D=W&&b.allowStaleOnFetchAbort,N=D||b.allowStaleOnFetchRejection,ae=N||b.noDeleteOnFetchRejection,Y=O;if(this.#e[g]===O&&(!ae||Y.__staleWhileFetching===void 0?this.#E(f,"fetch"):D||(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 D=this.#O?.(f,m,v);D&&D instanceof Promise&&D.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:D,signal:N}=g;if(!this.#A)return D&&(D.fetch="get"),this.get(f,{allowStale:b,updateAgeOnGet:k,noDeleteOnStaleGet:m,status:D});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:D,signal:N},Y=this.#n.get(f);if(Y===void 0){D&&(D.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 D&&(D.fetch="inflight",P&&(D.returnedStale=!0)),P?K.__staleWhileFetching:K.__returned=K}let re=this.#p(Y);if(!W&&!re)return D&&(D.fetch="hit"),this.#C(Y),k&&this.#I(Y),D&&this.#x(D,Y),K;let F=this.#j(f,Y,ae,T),Z=F.__staleWhileFetching!==void 0&&b;return D&&(D.fetch=re?"stale":"refresh",Z&&re&&(D.returnedStale=!0)),Z?F.__staleWhileFetching:F.__returned=F}}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")}#D(f,g){this.#f[g]=f,this.#c[f]=g}#C(f){f!==this.#o&&(f===this.#a?this.#a=this.#c[f]:this.#D(this.#f[f],this.#c[f]),this.#D(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.#F(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.#F("delete")}#F(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}),ut=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}),Nc=pe(c=>{le(),ue(),ce(),Object.defineProperty(c,"t",{value:!0}),c.default=void 0;var e=ut(),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}),Uc=pe(c=>{le(),ue(),ce(),Object.defineProperty(c,"t",{value:!0}),c.default=void 0;var e=ut(),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}),Bc=pe(c=>{le(),ue(),ce(),Object.defineProperty(c,"t",{value:!0}),c.default=void 0;var e=ut(),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}),eo=pe(c=>{le(),ue(),ce(),Object.defineProperty(c,"t",{value:!0}),c.default=void 0;var e=ut(),t=class extends e.Container{},r=t;c.default=r}),ht=pe(c=>{le(),ue(),ce(),Object.defineProperty(c,"t",{value:!0}),c.throwIteratorAccessError=e;function e(){throw new RangeError("Iterator access denied!")}}),fa=pe(c=>{le(),ue(),ce(),Object.defineProperty(c,"t",{value:!0}),c.RandomIterator=void 0;var e=ut(),t=ht(),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}),Dc=pe(c=>{le(),ue(),ce(),Object.defineProperty(c,"t",{value:!0}),c.default=void 0;var e=r(eo()),t=fa();function r(s){return s&&s.t?s:{default:s}}var a=class da extends t.RandomIterator{constructor(o,l,u){super(o,u),this.container=l}copy(){return new da(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}),Fc=pe(c=>{le(),ue(),ce(),Object.defineProperty(c,"t",{value:!0}),c.default=void 0;var e=a(eo()),t=ut(),r=ht();function a(o){return o&&o.t?o:{default:o}}var n=class pa 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 pa(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}),$c=pe(c=>{le(),ue(),ce(),Object.defineProperty(c,"t",{value:!0}),c.default=void 0;var e=r(eo()),t=fa();function r(s){return s&&s.t?s:{default:s}}var a=class ga extends t.RandomIterator{constructor(o,l,u){super(o,u),this.container=l}copy(){return new ga(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}),Wc=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}),ma=pe(c=>{le(),ue(),ce(),Object.defineProperty(c,"t",{value:!0}),c.default=void 0;var e=Wc(),t=ut(),r=ht(),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}),ba=pe(c=>{le(),ue(),ce(),Object.defineProperty(c,"t",{value:!0}),c.default=void 0;var e=ut(),t=ht(),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}),qc=pe(c=>{le(),ue(),ce(),Object.defineProperty(c,"t",{value:!0}),c.default=void 0;var e=a(ma()),t=a(ba()),r=ht();function a(o){return o&&o.t?o:{default:o}}var n=class ya 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 ya(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}),Hc=pe(c=>{le(),ue(),ce(),Object.defineProperty(c,"t",{value:!0}),c.default=void 0;var e=a(ma()),t=a(ba()),r=ht();function a(o){return o&&o.t?o:{default:o}}var n=class va 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 va(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}),wa=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"}}),_a=pe(c=>{le(),ue(),ce(),Object.defineProperty(c,"t",{value:!0}),c.HashContainerIterator=c.HashContainer=void 0;var e=ut(),t=a(wa()),r=ht();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}),zc=pe(c=>{le(),ue(),ce(),Object.defineProperty(c,"t",{value:!0}),c.default=void 0;var e=_a(),t=ht(),r=class ka 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 ka(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}),Kc=pe(c=>{le(),ue(),ce(),Object.defineProperty(c,"t",{value:!0}),c.default=void 0;var e=_a(),t=a(wa()),r=ht();function a(o){return o&&o.t?o:{default:o}}var n=class Sa 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 Sa(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}),Vc=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(Nc()),t=d(Uc()),r=d(Bc()),a=d(Dc()),n=d(Fc()),i=d($c()),s=d(qc()),o=d(Hc()),l=d(zc()),u=d(Kc());function d(p){return p&&p.t?p:{default:p}}}),Gc=pe((c,e)=>{le(),ue(),ce();var t=Vc().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}),Ea=pe((c,e)=>{le(),ue(),ce();var t=Gc();e.exports.NumberAllocator=t}),Yc=pe(c=>{le(),ue(),ce(),Object.defineProperty(c,"__esModule",{value:!0});var e=Lc(),t=Ea(),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}),Qc=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=Lr(),r=e(Yc()),a=Ut(),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}),Jc=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}),Xc=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(Mc()),r=e(jc()),a=e(Qc()),n=e(Lr()),i=e(Jc()),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}),xa=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}),Zc=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}),eu=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((xt(),Oe(bt))),r=Ut(),a=class{};c.TypedEventEmitter=a,(0,r.applyMixin)(a,t.default)}),Nr=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}),tu=pe((c,e)=>{le(),ue(),ce();var t=Nr().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}),ru=pe((c,e)=>{le(),ue(),ce();var t=Nr().default,r=tu();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}),nu=pe((c,e)=>{le(),ue(),ce();var t=ru();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}),iu=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}),ou=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}),su=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}),au=pe((c,e)=>{le(),ue(),ce();var t=su();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}),lu=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}),cu=pe((c,e)=>{le(),ue(),ce();var t=iu(),r=ou(),a=au(),n=lu();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}),Aa=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})}),uu=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}),Ia=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}),Ta=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}),Ca=pe((c,e)=>{le(),ue(),ce();var t=Ta();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,D=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&&!F&&n<D.length;n++){var F,Z=D[n],P=ae.p,J=Z[2];K>3?(F=J===re)&&(T=Z[(B=Z[4])?5:(B=3,3)],Z[4]=Z[5]=a):Z[0]<=P&&((F=K<2&&P<Z[1])?(B=0,ae.v=re,ae.n=Z[1]):P<J&&(F=K<3||Z[0]>re||re>J)&&(Z[4]=K,Z[5]=re,ae.n=J,B=0))}if(F||K>1)return u;throw N=!0,re}return function(K,re,F){if(W>1)throw TypeError("Generator is already running");for(N&&re===1&&Y(re,F),B=re,T=F;(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}),Oa=pe((c,e)=>{le(),ue(),ce();var t=Ia(),r=Ta();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}),Pa=pe((c,e)=>{le(),ue(),ce();var t=Ca(),r=Oa();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}),hu=pe((c,e)=>{le(),ue(),ce();var t=Pa();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}),fu=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}),du=pe((c,e)=>{le(),ue(),ce();var t=Nr().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}),pu=pe((c,e)=>{le(),ue(),ce();var t=Ia(),r=Ca(),a=hu(),n=Pa(),i=Oa(),s=fu(),o=du();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}),gu=pe((c,e)=>{le(),ue(),ce();var t=pu()();e.exports=t;try{regeneratorRuntime=t}catch{typeof globalThis=="object"?globalThis.regeneratorRuntime=t:Function("r","regeneratorRuntime = r")(t)}}),mu=pe((c,e)=>{le(),ue(),ce(),(function(t,r){typeof c=="object"&&typeof e<"u"?r(c,nu(),cu(),Aa(),uu(),gu()):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(D){var N=D.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(D){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:D},ae):E.postMessage({id:re,method:D,params:N},ae)})},S=function(D,N){var ae=arguments.length>2&&arguments[2]!==void 0?arguments[2]:[];E.postMessage({id:null,method:D,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})}),bu=pe((c,e)=>{le(),ue(),ce(),(function(t,r){typeof c=="object"&&typeof e<"u"?r(c,Nr(),mu(),Aa()):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})}),yu=pe((c,e)=>{le(),ue(),ce(),(function(t,r){typeof c=="object"&&typeof e<"u"?r(c,bu()):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})}),Ur=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&&Pe?.versions?!Object.prototype.hasOwnProperty.call(Pe.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}),vu=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=yu(),n=r(Ur()),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}),Ma=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(vu()),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}),ii=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(Cc()),i=It(),s=a(Pc()),o=a(lt()),l=r(aa()),u=a(la()),d=a(Xc()),p=a(xa()),y=a(Zc()),f=Ut(),g=eu(),b=a(Ma()),k=r(Ur()),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 oi 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:",oi.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:oi.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",D=>{this.log("parser :: on packet push to packets array."),M.push(D)});let O=()=>{this.log("work :: getting next packet in queue");let D=M.shift();if(D)this.log("work :: packet pulled from queue"),(0,d.default)(this,D,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 D=I;I=null,D()}};x._write=(D,N,ae)=>{I=ae,this.log("writable stream :: parsing buffer"),S.parse(D),O()};let T=D=>{this.log("streamErrorHandler :: error",D.message),D.code?(this.log("streamErrorHandler :: emitting error"),this.emit("error",D)):this.noop(D)};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 D={cmd:"auth",reasonCode:0,...this.options.authPacket};this._writePacket(D)}}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:D,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=D),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:D}=S,N=[],ae=(re,F)=>{if(F=F||S,!Object.prototype.hasOwnProperty.call(this._resubscribeTopics,re)||this._resubscribeTopics[re].qos<F.qos||O){let Z={topic:re,qos:F.qos};M===5&&(Z.nl=F.nl,Z.rap=F.rap,Z.rh=F.rh,Z.properties=D),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,F)=>{let Z={cmd:"subscribe",subscriptions:re,messageId:F};if(D&&(Z.properties=D),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,F=[];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;F.push(Y(P,J))}return Promise.all(F).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(D,N){W&&W(D,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}),wu=pe(c=>{le(),ue(),ce(),Object.defineProperty(c,"__esModule",{value:!0});var e=Ea(),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 _u(){if(si)return sr;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 D=O.split("."),N=k(D,B).join(".");return W+N}function w(O){let B=[],T=0,W=O.length;for(;T<W;){let D=O.charCodeAt(T++);if(D>=55296&&D<=56319&&T<W){let N=O.charCodeAt(T++);(N&64512)==56320?B.push(((D&1023)<<10)+(N&1023)+65536):(B.push(D),T--)}else B.push(D)}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,D=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 F=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)/F)&&b("overflow"),W+=P*F;let J=Z<=N?t:Z>=N+r?r:Z-N;if(P<J)break;let be=e-J;F>f(c/be)&&b("overflow"),F*=be}let re=B.length+1;N=S(W-K,re,K==0),f(W/re)>c-D&&b("overflow"),D+=f(W/re),W%=re,B.splice(W++,0,D)}return String.fromCodePoint(...B)},M=function(O){let B=[];O=w(O);let T=O.length,W=s,D=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 F of O)F>=W&&F<K&&(K=F);let re=Y+1;K-W>f((c-D)/re)&&b("overflow"),D+=(K-W)*re,W=K;for(let F of O)if(F<W&&++D>c&&b("overflow"),F===W){let Z=D;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(D,re,Y===ae),D=0,++Y}++D,++W}return B.join("")};return sr={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})}},sr}var sr,si,gt,ku=He(()=>{le(),ue(),ce(),sr={},si=!1,gt=_u(),gt.decode,gt.encode,gt.toASCII,gt.toUnicode,gt.ucs2,gt.version});function Su(){return li||(li=!0,ai=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}),ai}function Eu(){return ui||(ui=!0,ci=Error),ci}function xu(){return fi||(fi=!0,hi=EvalError),hi}function Au(){return pi||(pi=!0,di=RangeError),di}function Iu(){return mi||(mi=!0,gi=ReferenceError),gi}function Ra(){return yi||(yi=!0,bi=SyntaxError),bi}function Jt(){return wi||(wi=!0,vi=TypeError),vi}function Tu(){return ki||(ki=!0,_i=URIError),_i}function Cu(){if(Si)return ar;Si=!0;var c=typeof Symbol<"u"&&Symbol,e=Su();return ar=function(){return typeof c!="function"||typeof Symbol!="function"||typeof c("foo")!="symbol"||typeof Symbol("bar")!="symbol"?!1:e()},ar}function Ou(){if(Ei)return lr;Ei=!0;var c={__proto__:null,foo:{}},e=Object;return lr=function(){return{__proto__:c}.foo===c.foo&&!(c instanceof e)},lr}function Pu(){if(xi)return cr;xi=!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 cr=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},cr}function to(){if(Ai)return ur;Ai=!0;var c=Pu();return ur=Function.prototype.bind||c,ur}function Mu(){if(Ii)return hr;Ii=!0;var c=Function.prototype.call,e=Object.prototype.hasOwnProperty,t=to();return hr=t.call(c,e),hr}function Bt(){if(Ti)return fr;Ti=!0;var c,e=Eu(),t=xu(),r=Au(),a=Iu(),n=Ra(),i=Jt(),s=Tu(),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=Cu()(),f=Ou()(),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 F=Y("%AsyncGeneratorFunction%");F&&(re=F.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=to(),S=Mu(),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,D=/\\(\\)?/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 F=[];return O(Y,W,function(Z,P,J,be){F[F.length]=J?O(be,D,"$1"):P||Z}),F},ae=function(Y,K){var re=Y,F;if(S(v,re)&&(F=v[re],re="%"+F[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:F,name:re,value:Z}}throw new n("intrinsic "+Y+" does not exist!")};return fr=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),F=re.length>0?re[0]:"",Z=ae("%"+F+"%",K),P=Z.name,J=Z.value,be=!1,te=Z.alias;te&&(F=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),F+="."+L,P="%"+F+"%",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},fr}function ro(){if(Ci)return dr;Ci=!0;var c=Bt(),e=c("%Object.defineProperty%",!0)||!1;if(e)try{e({},"a",{value:1})}catch{e=!1}return dr=e,dr}function ja(){if(Oi)return pr;Oi=!0;var c=Bt(),e=c("%Object.getOwnPropertyDescriptor%",!0);if(e)try{e([],"length")}catch{e=null}return pr=e,pr}function Ru(){if(Pi)return gr;Pi=!0;var c=ro(),e=Ra(),t=Jt(),r=ja();return gr=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.")},gr}function ju(){if(Mi)return mr;Mi=!0;var c=ro(),e=function(){return!!c};return e.hasArrayLengthDefineBug=function(){if(!c)return null;try{return c([],"length",{value:1}).length!==1}catch{return!0}},mr=e,mr}function Lu(){if(Ri)return br;Ri=!0;var c=Bt(),e=Ru(),t=ju()(),r=ja(),a=Jt(),n=c("%Math.floor%");return br=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},br}function Nu(){if(ji)return Mt;ji=!0;var c=to(),e=Bt(),t=Lu(),r=Jt(),a=e("%Function.prototype.apply%"),n=e("%Function.prototype.call%"),i=e("%Reflect.apply%",!0)||c.call(n,a),s=ro(),o=e("%Math.max%");Mt=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(Mt,"apply",{value:l}):Mt.apply=l,Mt}function Uu(){if(Li)return yr;Li=!0;var c=Bt(),e=Nu(),t=e(c("String.prototype.indexOf"));return yr=function(r,a){var n=c(r,!!a);return typeof n=="function"&&t(r,".prototype.")>-1?e(n):n},yr}var ai,li,ci,ui,hi,fi,di,pi,gi,mi,bi,yi,vi,wi,_i,ki,ar,Si,lr,Ei,cr,xi,ur,Ai,hr,Ii,fr,Ti,dr,Ci,pr,Oi,gr,Pi,mr,Mi,br,Ri,Mt,ji,yr,Li,Bu=He(()=>{le(),ue(),ce(),ai={},li=!1,ci={},ui=!1,hi={},fi=!1,di={},pi=!1,gi={},mi=!1,bi={},yi=!1,vi={},wi=!1,_i={},ki=!1,ar={},Si=!1,lr={},Ei=!1,cr={},xi=!1,ur={},Ai=!1,hr={},Ii=!1,fr={},Ti=!1,dr={},Ci=!1,pr={},Oi=!1,gr={},Pi=!1,mr={},Mi=!1,br={},Ri=!1,Mt={},ji=!1,yr={},Li=!1});function no(c){throw new Error("Node.js process "+c+" is not supported by JSPM core outside of Node.js")}function Du(){!Et||!kt||(Et=!1,kt.length?tt=kt.concat(tt):Gt=-1,tt.length&&La())}function La(){if(!Et){var c=setTimeout(Du,0);Et=!0;for(var e=tt.length;e;){for(kt=tt,tt=[];++Gt<e;)kt&&kt[Gt].run();Gt=-1,e=tt.length}kt=null,Et=!1,clearTimeout(c)}}function Fu(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];tt.push(new Na(c,e)),tt.length===1&&!Et&&setTimeout(La,0)}function Na(c,e){this.fun=c,this.array=e}function De(){}function $u(c){no("_linkedBinding")}function Wu(c){no("dlopen")}function qu(){return[]}function Hu(){return[]}function zu(c,e){if(!c)throw new Error(e||"assertion error")}function Ku(){return!1}function Vu(){return st.now()/1e3}function Fr(c){var e=Math.floor((Date.now()-st.now())*.001),t=st.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+=vr)),[r,a]}function dt(){return io}function Gu(c){return[]}var tt,Et,kt,Gt,po,go,mo,bo,yo,vo,wo,_o,ko,So,Eo,xo,Ao,Io,To,Co,Oo,Po,Mo,Ro,jo,er,Lo,No,Uo,Bo,Do,Fo,$o,Wo,qo,Ho,zo,Ko,Vo,Go,Yo,Qo,Jo,Xo,Zo,es,ts,rs,ns,is,os,st,$r,vr,ss,as,ls,cs,us,hs,fs,ds,ps,gs,ms,io,Ua=He(()=>{le(),ue(),ce(),tt=[],Et=!1,Gt=-1,Na.prototype.run=function(){this.fun.apply(null,this.array)},po="browser",go="x64",mo="browser",bo={PATH:"/usr/bin",LANG:navigator.language+".UTF-8",PWD:"/",HOME:"/home",TMP:"/tmp"},yo=["/usr/bin/node"],vo=[],wo="v16.8.0",_o={},ko=function(c,e){console.warn((e?e+": ":"")+c)},So=function(c){no("binding")},Eo=function(c){return 0},xo=function(){return"/"},Ao=function(c){},Io={name:"node",sourceUrl:"",headersUrl:"",libUrl:""},To=De,Co=[],Oo={},Po=!1,Mo={},Ro=De,jo=De,er=function(){return{}},Lo=er,No=er,Uo=De,Bo=De,Do=De,Fo={},$o={inspector:!1,debug:!1,uv:!1,ipv6:!1,tls_alpn:!1,tls_sni:!1,tls_ocsp:!1,tls:!1,cached_builtins:!0},Wo=De,qo=De,Ho=De,zo=De,Ko=De,Vo=De,Go=De,Yo=void 0,Qo=void 0,Jo=void 0,Xo=De,Zo=2,es=1,ts="/bin/usr/node",rs=9229,ns="node",is=[],os=De,st={now:typeof performance<"u"?performance.now.bind(performance):void 0,timing:typeof performance<"u"?performance.timing:void 0},st.now===void 0&&($r=Date.now(),st.timing&&st.timing.navigationStart&&($r=st.timing.navigationStart),st.now=()=>Date.now()-$r),vr=1e9,Fr.bigint=function(c){var e=Fr(c);return typeof BigInt>"u"?e[0]*vr+e[1]:BigInt(e[0]*vr)+BigInt(e[1])},ss=10,as={},ls=0,cs=dt,us=dt,hs=dt,fs=dt,ds=dt,ps=De,gs=dt,ms=dt,io={version:wo,versions:_o,arch:go,platform:mo,release:Io,_rawDebug:To,moduleLoadList:Co,binding:So,_linkedBinding:$u,_events:as,_eventsCount:ls,_maxListeners:ss,on:dt,addListener:cs,once:us,off:hs,removeListener:fs,removeAllListeners:ds,emit:ps,prependListener:gs,prependOnceListener:ms,listeners:Gu,domain:Oo,_exiting:Po,config:Mo,dlopen:Wu,uptime:Vu,_getActiveRequests:qu,_getActiveHandles:Hu,reallyExit:Ro,_kill:jo,cpuUsage:er,resourceUsage:Lo,memoryUsage:No,kill:Uo,exit:Bo,openStdin:Do,allowedNodeEnvironmentFlags:Fo,assert:zu,features:$o,_fatalExceptions:Wo,setUncaughtExceptionCaptureCallback:qo,hasUncaughtExceptionCaptureCallback:Ku,emitWarning:ko,nextTick:Fu,_tickCallback:Ho,_debugProcess:zo,_debugEnd:Ko,_startProfilerIdleNotifier:Vo,_stopProfilerIdleNotifier:Go,stdout:Yo,stdin:Jo,stderr:Qo,abort:Xo,umask:Eo,chdir:Ao,cwd:xo,env:bo,title:po,argv:yo,execArgv:vo,pid:Zo,ppid:es,execPath:ts,debugPort:rs,hrtime:Fr,argv0:ns,_preload_modules:is,setSourceMapsEnabled:os}});function Yu(){if(Ni)return wr;Ni=!0;var c=io;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,wr=a,wr}var wr,Ni,Ui,Qu=He(()=>{le(),ue(),ce(),Ua(),wr={},Ni=!1,Ui=Yu()}),Ba={};Lt(Ba,{URL:()=>Ga,Url:()=>qa,default:()=>Fe,fileURLToPath:()=>Fa,format:()=>Ha,parse:()=>Va,pathToFileURL:()=>$a,resolve:()=>za,resolveObject:()=>Ka});function Ju(){if(Bi)return _r;Bi=!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,D=typeof Symbol=="function"&&typeof Symbol.iterator=="object",N=typeof Symbol=="function"&&Symbol.toStringTag&&(typeof Symbol.toStringTag===D||!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),Ce=m.call(ie,Ie.length+1);return w.call(Ie,xe,"$&_")+"."+w.call(w.call(Ce,/([0-9]{3})/g,"$&_"),/_$/,"")}}return w.call(ie,xe,"$&_")}var re=Wa,F=re.custom,Z=G(F)?F:null;_r=function z(ie,xe,Ae,Ie){var Ce=xe||{};if(oe(Ce,"quoteStyle")&&Ce.quoteStyle!=="single"&&Ce.quoteStyle!=="double")throw new TypeError('option "quoteStyle" must be "single" or "double"');if(oe(Ce,"maxStringLength")&&(typeof Ce.maxStringLength=="number"?Ce.maxStringLength<0&&Ce.maxStringLength!==1/0:Ce.maxStringLength!==null))throw new TypeError('option "maxStringLength", if provided, must be a positive integer, Infinity, or `null`');var Ge=oe(Ce,"customInspect")?Ce.customInspect:!0;if(typeof Ge!="boolean"&&Ge!=="symbol")throw new TypeError("option \"customInspect\", if provided, must be `true`, `false`, or `'symbol'`");if(oe(Ce,"indent")&&Ce.indent!==null&&Ce.indent!==" "&&!(parseInt(Ce.indent,10)===Ce.indent&&Ce.indent>0))throw new TypeError('option "indent" must be "\\t", an integer > 0, or `null`');if(oe(Ce,"numericSeparator")&&typeof Ce.numericSeparator!="boolean")throw new TypeError('option "numericSeparator", if provided, must be `true` or `false`');var Ye=Ce.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,Ce);if(typeof ie=="number"){if(ie===0)return 1/0/ie>0?"0":"-0";var Ue=String(ie);return Ye?K(ie,Ue):Ue}if(typeof ie=="bigint"){var Qe=String(ie)+"n";return Ye?K(ie,Qe):Qe}var Tt=typeof Ce.depth>"u"?5:Ce.depth;if(typeof Ae>"u"&&(Ae=0),Ae>=Tt&&Tt>0&&typeof ie=="object")return be(ie)?"[Array]":"[Object]";var Je=X(Ce,Ae);if(typeof Ie>"u")Ie=[];else if(ee(Ie,ie)>=0)return"[Circular]";function ze(Xe,ft,wt){if(ft&&(Ie=M.call(Ie),Ie.push(ft)),wt){var Ze={depth:Ce.depth};return oe(Ce,"quoteStyle")&&(Ze.quoteStyle=Ce.quoteStyle),z(Xe,Ze,Ae+1,Ie)}return z(Xe,Ce,Ae+1,Ie)}if(typeof ie=="function"&&!we(ie)){var Xt=$(ie),Ct=ke(ie,ze);return"[Function"+(Xt?": "+Xt:" (anonymous)")+"]"+(Ct.length>0?" { "+I.call(Ct,", ")+" }":"")}if(G(ie)){var Dt=D?w.call(String(ie),/^(Symbol\(.*\))_[^)]*$/,"$1"):W.call(ie);return typeof ie=="object"&&!D?h(Dt):Dt}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",Ce);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,ze);return Je&&!U(Se)?"["+he(Se,Je)+"]":"[ "+I.call(Se,", ")+" ]"}if(V(ie)){var Ee=ke(ie,ze);return!("cause"in Error.prototype)&&"cause"in ie&&!ae.call(ie,"cause")?"{ ["+String(ie)+"] "+I.call(S.call("[cause]: "+ze(ie.cause),Ee),", ")+" }":Ee.length===0?"["+String(ie)+"]":"{ ["+String(ie)+"] "+I.call(Ee,", ")+" }"}if(typeof ie=="object"&&Ge){if(Z&&typeof ie[Z]=="function"&&re)return re(ie,{depth:Tt-Ae});if(Ge!=="symbol"&&typeof ie.inspect=="function")return ie.inspect()}if(fe(ie)){var je=[];return r&&r.call(ie,function(Xe,ft){je.push(ze(ft,ie,!0)+" => "+ze(Xe,ie))}),A("Map",t.call(ie),je,Je)}if(q(ie)){var $e=[];return s&&s.call(ie,function(Xe){$e.push(ze(Xe,ie))}),A("Set",i.call(ie),$e,Je)}if(de(ie))return _("WeakMap");if(ge(ie))return _("WeakSet");if(ye(ie))return _("WeakRef");if(ne(ie))return h(ze(Number(ie)));if(Q(ie))return h(ze(B.call(ie)));if(H(ie))return h(f.call(ie));if(L(ie))return h(ze(String(ie)));if(typeof window<"u"&&ie===window)return"{ [object Window] }";if(typeof globalThis<"u"&&ie===globalThis||typeof kr<"u"&&ie===kr)return"{ [object globalThis] }";if(!te(ie)&&!we(ie)){var Ve=ke(ie,ze),Ft=Y?Y(ie)===Object.prototype:ie instanceof Object||ie.constructor===Object,$t=ie instanceof Object?"":"null prototype",Wt=!Ft&&N&&Object(ie)===ie&&N in ie?m.call(R(ie),8,-1):$t?"Object":"",Zt=Ft||typeof ie.constructor!="function"?"":ie.constructor.name?ie.constructor.name+" ":"",vt=Zt+(Wt||$t?"["+I.call(S.call([],Wt||[],$t||[]),": ")+"] ":"");return Ve.length===0?vt+"{}":Je?vt+"{"+he(Ve,Je)+"}":vt+"{ "+I.call(Ve,", ")+" }"}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(D)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||kr)};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],`
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 Ce=typeof T=="function"?T(z):[],Ge;if(D){Ge={};for(var Ye=0;Ye<Ce.length;Ye++)Ge["$"+Ce[Ye]]=Ce[Ye]}for(var Ue in z)oe(z,Ue)&&(xe&&String(Number(Ue))===Ue&&Ue<z.length||D&&Ge["$"+Ue]instanceof Symbol||(x.call(/[^\w$]/,Ue)?Ae.push(ie(Ue,z)+": "+ie(z[Ue],z)):Ae.push(Ue+": "+ie(z[Ue],z))));if(typeof T=="function")for(var Qe=0;Qe<Ce.length;Qe++)ae.call(z,Ce[Qe])&&Ae.push("["+ie(Ce[Qe])+"]: "+ie(z[Ce[Qe]],z));return Ae}return _r}function Yu(){if(Di)return Sr;Di=!0;var c=Bt(),e=ju(),t=Gu(),r=Jt(),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(y,k){for(var m=y,w;(w=m.next)!==null;m=w)if(w.key===k)return m.next=w.next,w.next=y.next,y.next=w,w},b=function(y,k){var m=p(y,k);return m&&m.value},f=function(y,k,m){var w=p(y,k);w?w.value=m:y.next={key:k,next:y.next,value:m}},g=function(y,k){return!!p(y,k)};return Sr=function(){var y,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(y)return i(y,E)}else if(n){if(k)return l(k,E)}else if(m)return b(m,E)},has:function(E){if(a&&E&&(typeof E=="object"||typeof E=="function")){if(y)return o(y,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")?(y||(y=new a),s(y,E,v)):n?(k||(k=new n),u(k,E,v)):(m||(m={key:{},next:null}),f(m,E,v))}};return w},Sr}function oo(){if(Fi)return Er;Fi=!0;var c=String.prototype.replace,e=/%20/g,t={RFC1738:"RFC1738",RFC3986:"RFC3986"};return Er={default:t.RFC3986,formatters:{RFC1738:function(r){return c.call(r,e,"+")},RFC3986:function(r){return String(r)}},RFC1738:t.RFC1738,RFC3986:t.RFC3986},Er}function Ba(){if($i)return xr;$i=!0;var c=oo(),e=Object.prototype.hasOwnProperty,t=Array.isArray,r=(function(){for(var y=[],k=0;k<256;++k)y.push("%"+((k<16?"0":"")+k.toString(16)).toUpperCase());return y})(),a=function(y){for(;y.length>1;){var k=y.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(y,k){for(var m=k&&k.plainObjects?Object.create(null):{},w=0;w<y.length;++w)typeof y[w]<"u"&&(m[w]=y[w]);return m},i=function y(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]=y(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]=y(v[x],S,w):v[x]=S,v},E)},s=function(y,k){return Object.keys(k).reduce(function(m,w){return m[w]=k[w],m},y)},o=function(y,k,m){var w=y.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(y,k,m,w,E){if(y.length===0)return y;var v=y;if(typeof y=="symbol"?v=Symbol.prototype.toString.call(y):typeof y!="string"&&(v=String(y)),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(y){for(var k=[{obj:{o:y},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),y},p=function(y){return Object.prototype.toString.call(y)==="[object RegExp]"},b=function(y){return!y||typeof y!="object"?!1:!!(y.constructor&&y.constructor.isBuffer&&y.constructor.isBuffer(y))},f=function(y,k){return[].concat(y,k)},g=function(y,k){if(t(y)){for(var m=[],w=0;w<y.length;w+=1)m.push(k(y[w]));return m}return k(y)};return xr={arrayToObject:n,assign:s,combine:f,compact:d,decode:o,encode:u,isBuffer:b,isRegExp:p,maybeMap:g,merge:i},xr}function Qu(){if(Wi)return Ar;Wi=!0;var c=Yu(),e=Ba(),t=oo(),r=Object.prototype.hasOwnProperty,a={brackets:function(g){return g+"[]"},comma:"comma",indices:function(g,y){return g+"["+y+"]"},repeat:function(g){return g}},n=Array.isArray,i=Array.prototype.push,s=function(g,y){i.apply(g,n(y)?y:[y])},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={},b=function g(y,k,m,w,E,v,x,S,I,M,O,B,T,W,D,N,ae,Y){for(var K=y,re=Y,F=0,Z=!1;(re=re.get(p))!==void 0&&!Z;){var P=re.get(y);if(F+=1,typeof P<"u"){if(P===F)throw new RangeError("Cyclic object value");Z=!0}typeof re.get(p)>"u"&&(F=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[D(J)+"="+D(I(K,u.encoder,ae,"value",W))]}return[D(k)+"="+D(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(y,F);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,D,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 y=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:y,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 Ar=function(g,y){var k=g,m=f(y),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,b(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:""},Ar}function Ju(){if(qi)return Ir;qi=!0;var c=Ba(),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(b,f){return String.fromCharCode(parseInt(f,10))})},n=function(p,b){return p&&typeof p=="string"&&b.comma&&p.indexOf(",")>-1?p.split(","):p},i="utf8=%26%2310003%3B",s="utf8=%E2%9C%93",o=function(p,b){var f={__proto__:null},g=b.ignoreQueryPrefix?p.replace(/^\?/,""):p;g=g.replace(/%5B/gi,"[").replace(/%5D/gi,"]");var y=b.parameterLimit===1/0?void 0:b.parameterLimit,k=g.split(b.delimiter,y),m=-1,w,E=b.charset;if(b.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=b.decoder(v,r.decoder,E,"key"),M=b.strictNullHandling?null:""):(I=b.decoder(v.slice(0,S),r.decoder,E,"key"),M=c.maybeMap(n(v.slice(S+1),b),function(B){return b.decoder(B,r.decoder,E,"value")})),M&&b.interpretNumericEntities&&E==="iso-8859-1"&&(M=a(M)),v.indexOf("[]=")>-1&&(M=t(M)?[M]:M);var O=e.call(f,I);O&&b.duplicates==="combine"?f[I]=c.combine(f[I],M):(!O||b.duplicates==="last")&&(f[I]=M)}return f},l=function(p,b,f,g){for(var y=g?b:n(b,f),k=p.length-1;k>=0;--k){var m,w=p[k];if(w==="[]"&&f.parseArrays)m=f.allowEmptyArrays&&(y===""||f.strictNullHandling&&y===null)?[]:[].concat(y);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:y}:!isNaN(x)&&w!==v&&String(x)===v&&x>=0&&f.parseArrays&&x<=f.arrayLimit?(m=[],m[x]=y):v!=="__proto__"&&(m[v]=y)}y=m}return y},u=function(p,b,f,g){if(p){var y=f.allowDots?p.replace(/\.([^.[]+)/g,"[$1]"):p,k=/(\[[^[\]]*])/,m=/(\[[^[\]]*])/g,w=f.depth>0&&k.exec(y),E=w?y.slice(0,w.index):y,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(y))!==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("["+y.slice(w.index)+"]")}return l(v,b,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 b=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:b,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 Ir=function(p,b){var f=d(b);if(p===""||p===null||typeof p>"u")return f.plainObjects?Object.create(null):{};for(var g=typeof p=="string"?o(p,f):p,y=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");y=c.merge(y,E,f)}return f.allowSparse===!0?y:c.compact(y)},Ir}function Xu(){if(Hi)return Tr;Hi=!0;var c=Qu(),e=Ju(),t=oo();return Tr={formats:t,parse:e,stringify:c},Tr}function Zu(){if(zi)return mt;zi=!0;var c=gt;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})(.*)$/,b={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},y=Xu();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=y.parse(this.search.substr(1)):this.query=this.search.substr(1)):x&&(this.search="",this.query={}),this}var D=t.exec(T);if(D){D=D[0];var N=D.toLowerCase();this.protocol=N,T=T.substr(D.length)}if(S||D||T.match(/^\/\/[^@/]+@[^@/]+/)){var ae=T.substr(0,2)==="//";ae&&!(D&&f[D])&&(T=T.substr(2),this.slashes=!0)}if(!f[D]&&(ae||D&&!g[D])){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 F,Z;Y===-1?Z=T.lastIndexOf("@"):Z=T.lastIndexOf("@",Y),Z!==-1&&(F=T.slice(0,Z),T=T.slice(Z+1),this.auth=decodeURIComponent(F)),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(!b[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=y.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=y.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 D=Object.keys(v),N=0;N<D.length;N++){var ae=D[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)==="/",F=v.host||v.pathname&&v.pathname.charAt(0)==="/",Z=F||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]==="")),F)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)},mt.parse=k,mt.resolve=w,mt.resolveObject=E,mt.format=m,mt.Url=e,mt}function Da(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 Or?eh(c):th(c)}function eh(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(Xa,"\\"),t=decodeURIComponent(t),e!=="")return`\\\\${e}${t}`;{let r=t.codePointAt(1)|32,a=t[2];if(r<Qa||r>Ja||a!==":")throw new Deno.errors.InvalidData("file url path must be absolute");return t.slice(1)}}function th(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 Fa(c){let e=Ui.resolve(c),t=c.charCodeAt(c.length-1);(t===Ya||Or&&t===Ga)&&e[e.length-1]!==Ui.sep&&(e+="/");let r=new URL("file://");return e.includes("%")&&(e=e.replace(Za,"%25")),!Or&&e.includes("\\")&&(e=e.replace(el,"%5C")),e.includes(`
8
- `)&&(e=e.replace(tl,"%0A")),e.includes("\r")&&(e=e.replace(rl,"%0D")),e.includes(" ")&&(e=e.replace(nl,"%09")),r.pathname=e,r}var $a,_r,Bi,kr,Sr,Di,Er,Fi,xr,$i,Ar,Wi,Ir,qi,Tr,Hi,mt,zi,Fe,bs,Wa,qa,Ha,za,Ka,Va,Ga,Ya,Qa,Ja,Or,Xa,Za,el,tl,rl,nl,rh=He(()=>{le(),ue(),ce(),vu(),Lu(),Vu(),Na(),$a=Object.freeze(Object.create(null)),_r={},Bi=!1,kr=typeof globalThis<"u"?globalThis:typeof self<"u"?self:global,Sr={},Di=!1,Er={},Fi=!1,xr={},$i=!1,Ar={},Wi=!1,Ir={},qi=!1,Tr={},Hi=!1,mt={},zi=!1,Fe=Zu(),Fe.parse,Fe.resolve,Fe.resolveObject,Fe.format,Fe.Url,bs=typeof Deno<"u"?Deno.build.os==="windows"?"win32":Deno.build.os:void 0,Fe.URL=typeof URL<"u"?URL:null,Fe.pathToFileURL=Fa,Fe.fileURLToPath=Da,Wa=Fe.Url,qa=Fe.format,Ha=Fe.resolve,za=Fe.resolveObject,Ka=Fe.parse,Va=Fe.URL,Ga=92,Ya=47,Qa=97,Ja=122,Or=bs==="win32",Xa=/\//g,Za=/%/g,el=/\\/g,tl=/\n/g,rl=/\r/g,nl=/\t/g}),nh=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")}}),so=pe(c=>{le(),ue(),ce(),Object.defineProperty(c,"__esModule",{value:!0}),c.BufferedDuplex=void 0,c.writev=r;var e=It(),t=(Ne(),Oe(Le));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}),tr=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=(Ne(),Oe(Le)),r=e(nh()),a=e(lt()),n=It(),i=e(Ur()),s=so(),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 b(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=b(k,E,w),x=r.default.createWebSocketStream(v,w.wsOptions);return x.url=E,v.on("close",()=>{x.destroy()}),x};c.streamBuilder=g;var y=(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",D)):(S.onclose=T,S.onerror=W,S.onmessage=D);function O(Y,K,re){let F=new n.Transform({objectMode:Y.objectMode});return F._write=K,F._flush=re,F}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 D(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(F){return re(F)}re()}function ae(Y){S.close(),Y()}return w};c.browserStreamBuilder=y}),ao={};Lt(ao,{Server:()=>Me,Socket:()=>Me,Stream:()=>Me,_createServerHandle:()=>Me,_normalizeArgs:()=>Me,_setSimultaneousAccepts:()=>Me,connect:()=>Me,createConnection:()=>Me,createServer:()=>Me,default:()=>il,isIP:()=>Me,isIPv4:()=>Me,isIPv6:()=>Me});function Me(){throw new Error("Node.js net module is not supported by JSPM core outside of Node.js")}var il,ol=He(()=>{le(),ue(),ce(),il={_createServerHandle:Me,_normalizeArgs:Me,_setSimultaneousAccepts:Me,connect:Me,createConnection:Me,createServer:Me,isIP:Me,isIPv4:Me,isIPv6:Me,Server:Me,Socket:Me,Stream:Me}}),sl=pe((c,e)=>{le(),ue(),ce(),e.exports={}}),ys=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((ol(),Oe(ao))),r=e(lt()),a=e(sl()),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}),al={};Lt(al,{default:()=>ll});var ll,ih=He(()=>{le(),ue(),ce(),ll={}}),vs=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=(ih(),Oe(al)),r=e((ol(),Oe(ao))),a=e(lt()),n=e(sl()),i=(0,a.default)("mqttjs:tls");function s(l){let{host:u,port:d,socksProxy:p,...b}=l;if(p!==void 0){let f=(0,n.default)(u,d,p,{timeout:l.socksTimeout});return(0,t.connect)({...b,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(b){u.rejectUnauthorized&&l.emit("error",b),d.end()}return d.on("error",p),d};c.default=o}),ws=pe(c=>{le(),ue(),ce(),Object.defineProperty(c,"__esModule",{value:!0});var e=(Ne(),Oe(Le)),t=It(),r=so(),a,n,i;function s(){let p=new t.Transform;return p._write=(b,f,g)=>{a.send({data:b.buffer,success(){g()},fail(y){g(new Error(y))}})},p._flush=b=>{a.close({success(){b()}})},p}function o(p){p.hostname||(p.hostname="localhost"),p.path||(p.path="/"),p.wsOptions||(p.wsOptions={})}function l(p,b){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,b)),g}function u(){a.onOpen(()=>{i.socketReady()}),a.onMessage(p=>{let{data:b}=p;b instanceof ArrayBuffer?b=e.Buffer.from(b):b=e.Buffer.from(b,"utf8"),n.push(b)}),a.onClose(()=>{i.emit("close"),i.end(),i.destroy()}),a.onError(p=>{let b=new Error(p.errMsg);i.destroy(b)})}var d=(p,b)=>{if(b.hostname=b.hostname||b.host,!b.hostname)throw new Error("Could not determine host. Specify host manually.");let f=b.protocolId==="MQIsdp"&&b.protocolVersion===3?"mqttv3.1":"mqtt";o(b);let g=l(b,p);a=wx.connectSocket({url:g,protocols:[f]}),n=s(),i=new r.BufferedDuplex(b,n,a),i._destroy=(k,m)=>{a.close({success(){m&&m(k)}})};let y=i.destroy;return i.destroy=(k,m)=>(i.destroy=y,setTimeout(()=>{a.close({fail(){i._destroy(k,m)}})},0),i),u(),i};c.default=d}),_s=pe(c=>{le(),ue(),ce(),Object.defineProperty(c,"__esModule",{value:!0});var e=(Ne(),Oe(Le)),t=It(),r=so(),a,n,i,s=!1;function o(){let b=new t.Transform;return b._write=(f,g,y)=>{a.sendSocketMessage({data:f.buffer,success(){y()},fail(){y(new Error)}})},b._flush=f=>{a.closeSocket({success(){f()}})},b}function l(b){b.hostname||(b.hostname="localhost"),b.path||(b.path="/"),b.wsOptions||(b.wsOptions={})}function u(b,f){let g=b.protocol==="alis"?"wss":"ws",y=`${g}://${b.hostname}${b.path}`;return b.port&&b.port!==80&&b.port!==443&&(y=`${g}://${b.hostname}:${b.port}${b.path}`),typeof b.transformWsUrl=="function"&&(y=b.transformWsUrl(y,b,f)),y}function d(){s||(s=!0,a.onSocketOpen(()=>{i.socketReady()}),a.onSocketMessage(b=>{if(typeof b.data=="string"){let f=e.Buffer.from(b.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(b.data)}}),a.onSocketClose(()=>{i.end(),i.destroy()}),a.onSocketError(b=>{i.destroy(b)}))}var p=(b,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 y=u(f,b);return a=f.my,a.connectSocket({url:y,protocols:g}),n=o(),i=new r.BufferedDuplex(f,n,a),d(),i};c.default=p}),oh=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((rh(),Oe(Ua))),a=e(ii()),n=e(Ur());typeof Pe?.nextTick!="function"&&(Pe.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[,b,f]=p;d.username=b,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),y={};if(g.port!=null&&(y.port=Number(g.port)),y.host=g.hostname,y.query=g.query,y.auth=g.auth,y.protocol=g.protocol,y.path=g.path,p={...y,...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 Pe<"u"&&(p.socksProxy=Pe.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=tr().streamBuilder,s.wss=tr().streamBuilder,s.mqtt=ys().default,s.tcp=ys().default,s.ssl=vs().default,s.tls=s.ssl,s.mqtts=vs().default):(s.ws=tr().browserStreamBuilder,s.wss=tr().browserStreamBuilder,s.wx=ws().default,s.wxs=ws().default,s.ali=_s().default,s.alis=_s().default)),!s[p.protocol]){let g=["mqtts","wss"].indexOf(p.protocol)!==-1;p.protocol=["mqtt","mqtts","ws","wss","wx","wxs","ali","alis"].filter((y,k)=>g&&k%2===0?!1:typeof s[y]=="function")[0]}if(p.clean===!1&&!p.clientId)throw new Error("Missing clientId for unclean clients");p.protocol&&(p.defaultProtocol=p.protocol);function b(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(b,p);return f.on("error",()=>{}),f}function u(d,p,b=!0){return new Promise((f,g)=>{let y=l(d,p),k={connect:w=>{m(),f(y)},end:()=>{m(),f(y)},error:w=>{m(),y.end(),g(w)}};b===!1&&(k.close=()=>{k.error(new Error("Couldn't connect to server"))});function m(){Object.keys(k).forEach(w=>{y.off(w,k[w])})}Object.keys(k).forEach(w=>{y.on(w,k[w])})})}c.default=l}),ks=pe(c=>{le(),ue(),ce();var e=c&&c.__createBinding||(Object.create?function(b,f,g,y){y===void 0&&(y=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(b,y,k)}:function(b,f,g,y){y===void 0&&(y=g),b[y]=f[g]}),t=c&&c.__setModuleDefault||(Object.create?function(b,f){Object.defineProperty(b,"default",{enumerable:!0,value:f})}:function(b,f){b.default=f}),r=c&&c.__importStar||(function(){var b=function(f){return b=Object.getOwnPropertyNames||function(g){var y=[];for(var k in g)Object.prototype.hasOwnProperty.call(g,k)&&(y[y.length]=k);return y},b(f)};return function(f){if(f&&f.__esModule)return f;var g={};if(f!=null)for(var y=b(f),k=0;k<y.length;k++)y[k]!=="default"&&e(g,f,y[k]);return t(g,f),g}})(),a=c&&c.__exportStar||function(b,f){for(var g in b)g!=="default"&&!Object.prototype.hasOwnProperty.call(f,g)&&e(f,b,g)},n=c&&c.__importDefault||function(b){return b&&b.__esModule?b:{default:b}};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(ii());c.MqttClient=i.default;var s=n(Ea());c.DefaultMessageIdProvider=s.default;var o=n(bu());c.UniqueMessageIdProvider=o.default;var l=n(aa());c.Store=l.default;var u=r(oh());c.connect=u.default,Object.defineProperty(c,"connectAsync",{enumerable:!0,get:function(){return u.connectAsync}});var d=n(Pa());c.KeepaliveManager=d.default,c.Client=i.default,a(ii(),c),a(Ut(),c),a(sa(),c);var p=Lr();Object.defineProperty(c,"ReasonCodes",{enumerable:!0,get:function(){return p.ReasonCodes}})}),sh=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(ks());c.default=n,a(ks(),c)});const ah=sh();const lh={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}/#"},ch=300,uh={templateId:"7",type:"link",isDeepLink:!0},hh={channelType:"group",channel:"chat21",requestChannel:"chat21",platform:"WEBSITE",medium:"CHATBUDDY"};class cl{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={...lh,...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=ah.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={...uh,...this.config.fileTemplate??{},...fh(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=ch){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(b=>b(p)),this.messageHandlers.forEach(b=>b(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={...hh,...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 fh(c){const e={};for(const[t,r]of Object.entries(c))r!==void 0&&(e[t]=r);return e}function ul(c,e){return(c.sender??"").toString()===e}function hl(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 lo(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 fl(c){const e=lo(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 Ss(c,e,t){const r=hl(c,t),a=lo(c),n=fl(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"?dh(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 dh(c){return c<0?"error":c>=250?"read":c>=150?"delivered":"sent"}class dl extends Vi{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 Cs(e.baseUrl,e.userToken,e.apiKey,e.authToken),this.messageStore=new Os,this.conversationManager=new Ps(e.conversationId),this.usesAikaara()&&(this.connection=new Ts(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 cl({...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=>Ss(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}=Ss(e,r,{userId:a,systemSenders:this.config.tiledesk?.messageDefaults?.attributes?.systemSenders});if(this.mode==="dual"&&n.role==="assistant")return;if(ul(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}}}function Wr(c,e){return c.replace(/\{(\w+)\}/g,(t,r)=>e[r]??"")}function ph(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 pl(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=Wr(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=ph(u,e);if(!d)throw new Error(`Sign response missing path "${e}"`);const p=c.s3HostRewrite?d.replace(/^https:\/\/[^/]+/i,c.s3HostRewrite):d,b=await fetch(p,{method:"PUT",headers:{"content-type":t.type||"application/octet-stream"},body:t});if(!b.ok){const g=await b.text().catch(()=>"");throw new Error(`S3 PUT failed: ${b.status} ${g.slice(0,200)}`)}if(c.registerEndpoint){const g=JSON.parse(Wr(JSON.stringify(c.registerBody??{}),n)),y=await fetch(c.registerEndpoint,{method:"POST",headers:{...s,"content-type":"application/json"},body:JSON.stringify(g)});if(!y.ok){const k=await y.text().catch(()=>"");throw new Error(`Register failed: ${y.status} ${k.slice(0,200)}`)}}return{url:c.viewerTemplate?Wr(c.viewerTemplate,n):d.split("?")[0],fileName:a,contentType:t.type,byteSize:t.size,meta:{requestId:r.conversationId}}}}}function co(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,b]of Object.entries(n))r.append(p,b);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 gh="/tilechat/{userId}/conversations/{conversationId}/messages?pageSize={pageSize}";function gl(c){const e=c.apiBase.replace(/\/$/,""),t=c.pageSize??200,r=c.pathTemplate??gh;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 mh{client;panel;bubble;header;messageList;input;errorBanner;isOpen=!1;isEmbed=!1;constructor(e,t,r){this.client=new dl(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 ml 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||ho,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||fo,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 Ce=typeof T=="function"?T(z):[],Ge;if(D){Ge={};for(var Ye=0;Ye<Ce.length;Ye++)Ge["$"+Ce[Ye]]=Ce[Ye]}for(var Ue in z)oe(z,Ue)&&(xe&&String(Number(Ue))===Ue&&Ue<z.length||D&&Ge["$"+Ue]instanceof Symbol||(x.call(/[^\w$]/,Ue)?Ae.push(ie(Ue,z)+": "+ie(z[Ue],z)):Ae.push(Ue+": "+ie(z[Ue],z))));if(typeof T=="function")for(var Qe=0;Qe<Ce.length;Qe++)ae.call(z,Ce[Qe])&&Ae.push("["+ie(Ce[Qe])+"]: "+ie(z[Ce[Qe]],z));return Ae}return _r}function Xu(){if(Di)return Sr;Di=!0;var c=Bt(),e=Uu(),t=Ju(),r=Jt(),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 Sr=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},Sr}function oo(){if(Fi)return Er;Fi=!0;var c=String.prototype.replace,e=/%20/g,t={RFC1738:"RFC1738",RFC3986:"RFC3986"};return Er={default:t.RFC3986,formatters:{RFC1738:function(r){return c.call(r,e,"+")},RFC3986:function(r){return String(r)}},RFC1738:t.RFC1738,RFC3986:t.RFC3986},Er}function Da(){if($i)return xr;$i=!0;var c=oo(),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 xr={arrayToObject:n,assign:s,combine:f,compact:d,decode:o,encode:u,isBuffer:y,isRegExp:p,maybeMap:g,merge:i},xr}function Zu(){if(Wi)return Ar;Wi=!0;var c=Xu(),e=Da(),t=oo(),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,D,N,ae,Y){for(var K=b,re=Y,F=0,Z=!1;(re=re.get(p))!==void 0&&!Z;){var P=re.get(b);if(F+=1,typeof P<"u"){if(P===F)throw new RangeError("Cyclic object value");Z=!0}typeof re.get(p)>"u"&&(F=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[D(J)+"="+D(I(K,u.encoder,ae,"value",W))]}return[D(k)+"="+D(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,F);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,D,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 Ar=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:""},Ar}function eh(){if(qi)return Ir;qi=!0;var c=Da(),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 Ir=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)},Ir}function th(){if(Hi)return Tr;Hi=!0;var c=Zu(),e=eh(),t=oo();return Tr={formats:t,parse:e,stringify:c},Tr}function rh(){if(zi)return mt;zi=!0;var c=gt;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=th();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 D=t.exec(T);if(D){D=D[0];var N=D.toLowerCase();this.protocol=N,T=T.substr(D.length)}if(S||D||T.match(/^\/\/[^@/]+@[^@/]+/)){var ae=T.substr(0,2)==="//";ae&&!(D&&f[D])&&(T=T.substr(2),this.slashes=!0)}if(!f[D]&&(ae||D&&!g[D])){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 F,Z;Y===-1?Z=T.lastIndexOf("@"):Z=T.lastIndexOf("@",Y),Z!==-1&&(F=T.slice(0,Z),T=T.slice(Z+1),this.auth=decodeURIComponent(F)),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 D=Object.keys(v),N=0;N<D.length;N++){var ae=D[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)==="/",F=v.host||v.pathname&&v.pathname.charAt(0)==="/",Z=F||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]==="")),F)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)},mt.parse=k,mt.resolve=w,mt.resolveObject=E,mt.format=m,mt.Url=e,mt}function Fa(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 Or?nh(c):ih(c)}function nh(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(Za,"\\"),t=decodeURIComponent(t),e!=="")return`\\\\${e}${t}`;{let r=t.codePointAt(1)|32,a=t[2];if(r<Ja||r>Xa||a!==":")throw new Deno.errors.InvalidData("file url path must be absolute");return t.slice(1)}}function ih(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 $a(c){let e=Ui.resolve(c),t=c.charCodeAt(c.length-1);(t===Qa||Or&&t===Ya)&&e[e.length-1]!==Ui.sep&&(e+="/");let r=new URL("file://");return e.includes("%")&&(e=e.replace(el,"%25")),!Or&&e.includes("\\")&&(e=e.replace(tl,"%5C")),e.includes(`
8
+ `)&&(e=e.replace(rl,"%0A")),e.includes("\r")&&(e=e.replace(nl,"%0D")),e.includes(" ")&&(e=e.replace(il,"%09")),r.pathname=e,r}var Wa,_r,Bi,kr,Sr,Di,Er,Fi,xr,$i,Ar,Wi,Ir,qi,Tr,Hi,mt,zi,Fe,bs,qa,Ha,za,Ka,Va,Ga,Ya,Qa,Ja,Xa,Or,Za,el,tl,rl,nl,il,oh=He(()=>{le(),ue(),ce(),ku(),Bu(),Qu(),Ua(),Wa=Object.freeze(Object.create(null)),_r={},Bi=!1,kr=typeof globalThis<"u"?globalThis:typeof self<"u"?self:global,Sr={},Di=!1,Er={},Fi=!1,xr={},$i=!1,Ar={},Wi=!1,Ir={},qi=!1,Tr={},Hi=!1,mt={},zi=!1,Fe=rh(),Fe.parse,Fe.resolve,Fe.resolveObject,Fe.format,Fe.Url,bs=typeof Deno<"u"?Deno.build.os==="windows"?"win32":Deno.build.os:void 0,Fe.URL=typeof URL<"u"?URL:null,Fe.pathToFileURL=$a,Fe.fileURLToPath=Fa,qa=Fe.Url,Ha=Fe.format,za=Fe.resolve,Ka=Fe.resolveObject,Va=Fe.parse,Ga=Fe.URL,Ya=92,Qa=47,Ja=97,Xa=122,Or=bs==="win32",Za=/\//g,el=/%/g,tl=/\\/g,rl=/\n/g,nl=/\r/g,il=/\t/g}),sh=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")}}),so=pe(c=>{le(),ue(),ce(),Object.defineProperty(c,"__esModule",{value:!0}),c.BufferedDuplex=void 0,c.writev=r;var e=It(),t=(Ne(),Oe(Le));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}),tr=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=(Ne(),Oe(Le)),r=e(sh()),a=e(lt()),n=It(),i=e(Ur()),s=so(),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",D)):(S.onclose=T,S.onerror=W,S.onmessage=D);function O(Y,K,re){let F=new n.Transform({objectMode:Y.objectMode});return F._write=K,F._flush=re,F}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 D(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(F){return re(F)}re()}function ae(Y){S.close(),Y()}return w};c.browserStreamBuilder=b}),ao={};Lt(ao,{Server:()=>Me,Socket:()=>Me,Stream:()=>Me,_createServerHandle:()=>Me,_normalizeArgs:()=>Me,_setSimultaneousAccepts:()=>Me,connect:()=>Me,createConnection:()=>Me,createServer:()=>Me,default:()=>ol,isIP:()=>Me,isIPv4:()=>Me,isIPv6:()=>Me});function Me(){throw new Error("Node.js net module is not supported by JSPM core outside of Node.js")}var ol,sl=He(()=>{le(),ue(),ce(),ol={_createServerHandle:Me,_normalizeArgs:Me,_setSimultaneousAccepts:Me,connect:Me,createConnection:Me,createServer:Me,isIP:Me,isIPv4:Me,isIPv6:Me,Server:Me,Socket:Me,Stream:Me}}),al=pe((c,e)=>{le(),ue(),ce(),e.exports={}}),ys=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((sl(),Oe(ao))),r=e(lt()),a=e(al()),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}),ll={};Lt(ll,{default:()=>cl});var cl,ah=He(()=>{le(),ue(),ce(),cl={}}),vs=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=(ah(),Oe(ll)),r=e((sl(),Oe(ao))),a=e(lt()),n=e(al()),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}),ws=pe(c=>{le(),ue(),ce(),Object.defineProperty(c,"__esModule",{value:!0});var e=(Ne(),Oe(Le)),t=It(),r=so(),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}),_s=pe(c=>{le(),ue(),ce(),Object.defineProperty(c,"__esModule",{value:!0});var e=(Ne(),Oe(Le)),t=It(),r=so(),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}),lh=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((oh(),Oe(Ba))),a=e(ii()),n=e(Ur());typeof Pe?.nextTick!="function"&&(Pe.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 Pe<"u"&&(p.socksProxy=Pe.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=tr().streamBuilder,s.wss=tr().streamBuilder,s.mqtt=ys().default,s.tcp=ys().default,s.ssl=vs().default,s.tls=s.ssl,s.mqtts=vs().default):(s.ws=tr().browserStreamBuilder,s.wss=tr().browserStreamBuilder,s.wx=ws().default,s.wxs=ws().default,s.ali=_s().default,s.alis=_s().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}),ks=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(ii());c.MqttClient=i.default;var s=n(xa());c.DefaultMessageIdProvider=s.default;var o=n(wu());c.UniqueMessageIdProvider=o.default;var l=n(la());c.Store=l.default;var u=r(lh());c.connect=u.default,Object.defineProperty(c,"connectAsync",{enumerable:!0,get:function(){return u.connectAsync}});var d=n(Ma());c.KeepaliveManager=d.default,c.Client=i.default,a(ii(),c),a(Ut(),c),a(aa(),c);var p=Lr();Object.defineProperty(c,"ReasonCodes",{enumerable:!0,get:function(){return p.ReasonCodes}})}),ch=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(ks());c.default=n,a(ks(),c)});const uh=ch();const hh={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}/#"},fh=300,dh={templateId:"7",type:"link",isDeepLink:!0},ph={channelType:"group",channel:"chat21",requestChannel:"chat21",platform:"WEBSITE",medium:"CHATBUDDY"};class ul{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={...hh,...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=uh.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={...dh,...this.config.fileTemplate??{},...gh(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=fh){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={...ph,...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 gh(c){const e={};for(const[t,r]of Object.entries(c))r!==void 0&&(e[t]=r);return e}function hl(c,e){return(c.sender??"").toString()===e}function fl(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 lo(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 dl(c){const e=lo(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 Ss(c,e,t){const r=fl(c,t),a=lo(c),n=dl(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"?mh(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 mh(c){return c<0?"error":c>=250?"read":c>=150?"delivered":"sent"}class pl extends Vi{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 Os(e.baseUrl,e.userToken,e.apiKey,e.authToken),this.messageStore=new Ps,this.conversationManager=new Ms(e.conversationId),this.usesAikaara()&&(this.connection=new Cs(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 ul({...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=>Ss(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}=Ss(e,r,{userId:a,systemSenders:this.config.tiledesk?.messageDefaults?.attributes?.systemSenders});if(this.mode==="dual"&&n.role==="assistant")return;if(hl(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}}}const Es={txt:"text/plain",pdf:"application/pdf",jpg:"image/jpeg",jpeg:"image/jpeg",png:"image/png",csv:"text/csv",doc:"application/msword",docx:"application/vnd.openxmlformats-officedocument.wordprocessingml.document",xls:"application/vnd.ms-excel",xlsx:"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",json:"application/json",zip:"application/zip"};function bh(c){const e=c.lastIndexOf(".");return e<0||e===c.length-1?"":c.slice(e+1).toLowerCase()}function yh(c,e,t){const r=c.type;if(r&&r.trim().length>0)return r;const a=bh(c.name||"");if(a){if(e&&e[a])return e[a];if(Es[a])return Es[a]}return t}function Wr(c,e){return c.replace(/\{(\w+)\}/g,(t,r)=>e[r]??"")}function vh(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 gl(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=Wr(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=vh(u,e);if(!d)throw new Error(`Sign response missing path "${e}"`);const p=yh(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(Wr(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?Wr(c.viewerTemplate,n):d.split("?")[0],fileName:a,contentType:p,byteSize:t.size,meta:{requestId:r.conversationId}}}}}function co(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 wh="/tilechat/{userId}/conversations/{conversationId}/messages?pageSize={pageSize}";function ml(c){const e=c.apiBase.replace(/\/$/,""),t=c.pageSize??200,r=c.pathTemplate??wh;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 _h{client;panel;bubble;header;messageList;input;errorBanner;isOpen=!1;isEmbed=!1;constructor(e,t,r){this.client=new pl(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 bl 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||tc,primaryColor:this.getAttribute("primary-color")||this._config.primaryColor||ho,position:this.getAttribute("position")||this._config.position||ec,width:Number(this.getAttribute("width"))||this._config.width||Ql,height:Number(this.getAttribute("height"))||this._config.height||Jl,fontFamily:this._config.fontFamily||Zl,borderRadius:this._config.borderRadius??Xl,placeholder:this.getAttribute("placeholder")||this._config.placeholder||fo,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||rc,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;
@@ -119,7 +119,7 @@ In order to be iterable, non-array objects must have a [Symbol.iterator]() metho
119
119
  ></aikaara-chat-input>
120
120
  <aikaara-error-banner></aikaara-error-banner>
121
121
  </div>
122
- `;const s=this.shadow.querySelector("aikaara-message-list");if(s){e.hideSystemMessages?.length&&s.setHideSystemMessages?.(e.hideSystemMessages),e.timestampFormat&&s.setTimestampFormat?.(e.timestampFormat);const o=e.templateLayout;o&&s.setTemplateLayout?.(o)}}async initController(){const e=this.getConfig(),t=e.transport??"aikaara";(t==="aikaara"||t==="dual")&&(!e.baseUrl||!e.userToken)||(this.controller?.disconnect(),this.controller=new mh(e,this.shadow,{uploadAdapter:this._config.uploadAdapter,historyAdapter:this._config.historyAdapter}),await this.controller.connect())}sendUserEvent(e,t,r){this.controller?.sendUserEvent(e,t,r)}getClient(){return this.controller?.getClient()??null}darkenColor(e){try{const t=parseInt(e.replace("#",""),16),r=Math.max(0,(t>>16)-20),a=Math.max(0,(t>>8&255)-20),n=Math.max(0,(t&255)-20);return`#${(r<<16|a<<8|n).toString(16).padStart(6,"0")}`}catch{return e}}}class bl extends HTMLElement{shadow;constructor(){super(),this.shadow=this.attachShadow({mode:"open"})}connectedCallback(){this.render(),this.shadow.querySelector(".bubble")?.addEventListener("click",()=>{this.dispatchEvent(new CustomEvent("toggle",{bubbles:!0,composed:!0}))})}render(){this.shadow.innerHTML=`
122
+ `;const s=this.shadow.querySelector("aikaara-message-list");if(s){e.hideSystemMessages?.length&&s.setHideSystemMessages?.(e.hideSystemMessages),e.timestampFormat&&s.setTimestampFormat?.(e.timestampFormat);const o=e.templateLayout;o&&s.setTemplateLayout?.(o)}}async initController(){const e=this.getConfig(),t=e.transport??"aikaara";(t==="aikaara"||t==="dual")&&(!e.baseUrl||!e.userToken)||(this.controller?.disconnect(),this.controller=new _h(e,this.shadow,{uploadAdapter:this._config.uploadAdapter,historyAdapter:this._config.historyAdapter}),await this.controller.connect())}sendUserEvent(e,t,r){this.controller?.sendUserEvent(e,t,r)}getClient(){return this.controller?.getClient()??null}darkenColor(e){try{const t=parseInt(e.replace("#",""),16),r=Math.max(0,(t>>16)-20),a=Math.max(0,(t>>8&255)-20),n=Math.max(0,(t&255)-20);return`#${(r<<16|a<<8|n).toString(16).padStart(6,"0")}`}catch{return e}}}class yl extends HTMLElement{shadow;constructor(){super(),this.shadow=this.attachShadow({mode:"open"})}connectedCallback(){this.render(),this.shadow.querySelector(".bubble")?.addEventListener("click",()=>{this.dispatchEvent(new CustomEvent("toggle",{bubbles:!0,composed:!0}))})}render(){this.shadow.innerHTML=`
123
123
  <style>
124
124
  .bubble {
125
125
  width: var(--aikaara-bubble-size, 60px);
@@ -154,7 +154,7 @@ In order to be iterable, non-array objects must have a [Symbol.iterator]() metho
154
154
  <path d="M21 15a2 2 0 0 1-2 2H7l-4 4V5a2 2 0 0 1 2-2h14a2 2 0 0 1 2 2z"/>
155
155
  </svg>
156
156
  </button>
157
- `}setIcon(e){const t=this.shadow.querySelector(".bubble");t&&(t.innerHTML=e)}}class yl extends HTMLElement{shadow;static get observedAttributes(){return["title","subtitle","avatar-url","status"]}constructor(){super(),this.shadow=this.attachShadow({mode:"open"})}connectedCallback(){this.render(),this.bindClose()}attributeChangedCallback(){this.render(),this.bindClose()}bindClose(){this.shadow.querySelector(".close-btn")?.addEventListener("click",()=>{this.dispatchEvent(new CustomEvent("header-close",{bubbles:!0,composed:!0}))})}render(){const e=this.getAttribute("title")||"Chat",t=this.getAttribute("subtitle")||"",r=this.getAttribute("avatar-url"),a=this.getAttribute("status")||"connected",n=a==="connected"?"#10b981":a==="connecting"||a==="reconnecting"?"#f59e0b":"#ef4444";this.shadow.innerHTML=`
157
+ `}setIcon(e){const t=this.shadow.querySelector(".bubble");t&&(t.innerHTML=e)}}class vl extends HTMLElement{shadow;static get observedAttributes(){return["title","subtitle","avatar-url","status"]}constructor(){super(),this.shadow=this.attachShadow({mode:"open"})}connectedCallback(){this.render(),this.bindClose()}attributeChangedCallback(){this.render(),this.bindClose()}bindClose(){this.shadow.querySelector(".close-btn")?.addEventListener("click",()=>{this.dispatchEvent(new CustomEvent("header-close",{bubbles:!0,composed:!0}))})}render(){const e=this.getAttribute("title")||"Chat",t=this.getAttribute("subtitle")||"",r=this.getAttribute("avatar-url"),a=this.getAttribute("status")||"connected",n=a==="connected"?"#10b981":a==="connecting"||a==="reconnecting"?"#f59e0b":"#ef4444";this.shadow.innerHTML=`
158
158
  <style>
159
159
  .header {
160
160
  display: flex;
@@ -248,7 +248,7 @@ In order to be iterable, non-array objects must have a [Symbol.iterator]() metho
248
248
  </svg>
249
249
  </button>
250
250
  </div>
251
- `}setStatus(e){this.setAttribute("status",e)}}const bh=/<\s*(br|i|b|em|strong|small|sub|sup|p|div|span|ul|ol|li|a|img|code|pre)\b/i;function Rt(c){if(bh.test(c))return c;let e=yh(c);return e=e.replace(/```(\w*)\n([\s\S]*?)```/g,(t,r,a)=>`<pre><code>${a.trim()}</code></pre>`),e=e.replace(/`([^`]+)`/g,"<code>$1</code>"),e=e.replace(/\*\*(.+?)\*\*/g,"<strong>$1</strong>"),e=e.replace(/\*(.+?)\*/g,"<em>$1</em>"),e=e.replace(/\[([^\]]+)\]\((https?:\/\/[^\s)]+)\)/g,'<a href="$2" target="_blank" rel="noopener noreferrer">$1</a>'),e=e.replace(/\n/g,"<br>"),e}function yh(c){const e={"&":"&amp;","<":"&lt;",">":"&gt;",'"':"&quot;","'":"&#039;"};return c.replace(/[&<>"']/g,t=>e[t])}const vh=new Set(["p","br","hr","strong","em","b","i","u","s","small","sub","sup","code","pre","a","img","ul","ol","li","blockquote","h1","h2","h3","h4","h5","h6","span","div","table","thead","tbody","tr","th","td"]),wh={a:new Set(["href","target","rel"]),img:new Set(["src","alt","width","height"]),code:new Set(["class"]),pre:new Set(["class"]),span:new Set(["class"]),div:new Set(["class"])};function jt(c){const e=document.createElement("template");return e.innerHTML=c,vl(e.content),e.innerHTML}function vl(c){const e=Array.from(c.childNodes);for(const t of e)if(t.nodeType===Node.ELEMENT_NODE){const r=t,a=r.tagName.toLowerCase();if(!vh.has(a)){const s=document.createTextNode(r.textContent||"");c.replaceChild(s,t);continue}const n=wh[a]||new Set,i=Array.from(r.attributes);for(const s of i)n.has(s.name)||r.removeAttribute(s.name);if(r.hasAttribute("href")){const s=r.getAttribute("href")||"";!s.startsWith("http://")&&!s.startsWith("https://")&&!s.startsWith("/")&&r.removeAttribute("href")}vl(t)}}class wl extends HTMLElement{shadow;container;welcomeMessage="";showTimestamps=!0;timestampFormat="time";hideSystemMessages=[];linkHandlers=[];getLinkBearer=null;setHideSystemMessages(e){this.hideSystemMessages=(e??[]).map(t=>t.toLowerCase())}setTimestampFormat(e){this.timestampFormat=e,e==="none"&&(this.showTimestamps=!1)}templateLayout="inside";setTemplateLayout(e){this.templateLayout=e}shouldHideMessage(e){if(!this.hideSystemMessages.length||!e)return!1;const t=e.trim().toLowerCase();return this.hideSystemMessages.some(r=>t.includes(r))}setLinkConfig(e,t){this.linkHandlers=e,this.getLinkBearer=t??null}constructor(){super(),this.shadow=this.attachShadow({mode:"open"})}connectedCallback(){this.addEventListener("template-action",e=>{const t=e.detail;this.dispatchEvent(new CustomEvent("message-action",{detail:t,bubbles:!0,composed:!0}))}),this.addEventListener("click",e=>{const t=e.composedPath?.()??[],r=t.find(n=>n&&n.tagName==="A");!r||!r.href||r.dataset.noModal!==void 0||t.some(n=>{if(!n||!n.classList)return!1;const i=n.classList;return i.contains("bubble")&&i.contains("user")})||/^https?:\/\//i.test(r.href)&&(e.preventDefault(),this.handleLinkClick(r.href,r.textContent?.trim()||void 0))}),this.shadow.innerHTML=`
251
+ `}setStatus(e){this.setAttribute("status",e)}}const kh=/<\s*(br|i|b|em|strong|small|sub|sup|p|div|span|ul|ol|li|a|img|code|pre)\b/i;function Rt(c){if(kh.test(c))return c;let e=Sh(c);return e=e.replace(/```(\w*)\n([\s\S]*?)```/g,(t,r,a)=>`<pre><code>${a.trim()}</code></pre>`),e=e.replace(/`([^`]+)`/g,"<code>$1</code>"),e=e.replace(/\*\*(.+?)\*\*/g,"<strong>$1</strong>"),e=e.replace(/\*(.+?)\*/g,"<em>$1</em>"),e=e.replace(/\[([^\]]+)\]\((https?:\/\/[^\s)]+)\)/g,'<a href="$2" target="_blank" rel="noopener noreferrer">$1</a>'),e=e.replace(/\n/g,"<br>"),e}function Sh(c){const e={"&":"&amp;","<":"&lt;",">":"&gt;",'"':"&quot;","'":"&#039;"};return c.replace(/[&<>"']/g,t=>e[t])}const Eh=new Set(["p","br","hr","strong","em","b","i","u","s","small","sub","sup","code","pre","a","img","ul","ol","li","blockquote","h1","h2","h3","h4","h5","h6","span","div","table","thead","tbody","tr","th","td"]),xh={a:new Set(["href","target","rel"]),img:new Set(["src","alt","width","height"]),code:new Set(["class"]),pre:new Set(["class"]),span:new Set(["class"]),div:new Set(["class"])};function jt(c){const e=document.createElement("template");return e.innerHTML=c,wl(e.content),e.innerHTML}function wl(c){const e=Array.from(c.childNodes);for(const t of e)if(t.nodeType===Node.ELEMENT_NODE){const r=t,a=r.tagName.toLowerCase();if(!Eh.has(a)){const s=document.createTextNode(r.textContent||"");c.replaceChild(s,t);continue}const n=xh[a]||new Set,i=Array.from(r.attributes);for(const s of i)n.has(s.name)||r.removeAttribute(s.name);if(r.hasAttribute("href")){const s=r.getAttribute("href")||"";!s.startsWith("http://")&&!s.startsWith("https://")&&!s.startsWith("/")&&r.removeAttribute("href")}wl(t)}}class _l extends HTMLElement{shadow;container;welcomeMessage="";showTimestamps=!0;timestampFormat="time";hideSystemMessages=[];linkHandlers=[];getLinkBearer=null;setHideSystemMessages(e){this.hideSystemMessages=(e??[]).map(t=>t.toLowerCase())}setTimestampFormat(e){this.timestampFormat=e,e==="none"&&(this.showTimestamps=!1)}templateLayout="inside";setTemplateLayout(e){this.templateLayout=e}shouldHideMessage(e){if(!this.hideSystemMessages.length||!e)return!1;const t=e.trim().toLowerCase();return this.hideSystemMessages.some(r=>t.includes(r))}setLinkConfig(e,t){this.linkHandlers=e,this.getLinkBearer=t??null}constructor(){super(),this.shadow=this.attachShadow({mode:"open"})}connectedCallback(){this.addEventListener("template-action",e=>{const t=e.detail;this.dispatchEvent(new CustomEvent("message-action",{detail:t,bubbles:!0,composed:!0}))}),this.addEventListener("click",e=>{const t=e.composedPath?.()??[],r=t.find(n=>n&&n.tagName==="A");!r||!r.href||r.dataset.noModal!==void 0||t.some(n=>{if(!n||!n.classList)return!1;const i=n.classList;return i.contains("bubble")&&i.contains("user")})||/^https?:\/\//i.test(r.href)&&(e.preventDefault(),this.handleLinkClick(r.href,r.textContent?.trim()||void 0))}),this.shadow.innerHTML=`
252
252
  <style>
253
253
  :host {
254
254
  display: flex;
@@ -398,7 +398,7 @@ In order to be iterable, non-array objects must have a [Symbol.iterator]() metho
398
398
  }
399
399
  </style>
400
400
  <div class="message-list"></div>
401
- `,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">${jt(Rt(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=jt(Rt(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=jt(Rt(e.content))):(a.innerHTML=jt(Rt(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);switch(this.timestampFormat){case"datetime":return`${t.toLocaleDateString(void 0,{month:"short",day:"2-digit"})}, ${t.toLocaleTimeString(void 0,{hour:"2-digit",minute:"2-digit"})}`;case"date":return t.toLocaleDateString(void 0,{month:"short",day:"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(b=>_h(e,b.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=kh(e),o=_l(r.fetch.url,s),l={accept:"application/json",...r.fetch.headers??{}},u=r.fetch.authHeader??"session";if(u!=="none"&&this.getLinkBearer){const b=await this.getLinkBearer(u);b&&(l.authorization=`Bearer ${b}`)}const d={method:r.fetch.method??"GET",headers:l};r.fetch.body&&(l["content-type"]="application/json",d.body=JSON.stringify(Ki(r.fetch.body,s)));let p=null;try{const b=await fetch(o,d);b.ok&&(p=await b.json().catch(()=>null))}catch(b){console.warn("[aikaara-chat-sdk] linkHandler fetch failed",b)}requestAnimationFrame(()=>{n.showElement?.(r.render,i,b=>{const f=r.props??{setData:p};for(const[y,k]of Object.entries(f)){const m=b[y];typeof m=="function"&&m.call(b,k)}const g=y=>{const k=y,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})))};b.addEventListener("aikaara-plan-select",g),b.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 _h(c,e){const t=e.replace(/[.+^${}()|[\]\\]/g,"\\$&");return new RegExp("^"+t.replace(/\*/g,".*").replace(/\?/g,".")+"$","i").test(c)}function kh(c){try{const e=new URL(c),t={};return e.searchParams.forEach((r,a)=>{t[a]=r}),t}catch{return{}}}function _l(c,e){return c.replace(/\{(\w+)\}/g,(t,r)=>e[r]??"")}function Ki(c,e){if(typeof c=="string")return _l(c,e);if(Array.isArray(c))return c.map(t=>Ki(t,e));if(c&&typeof c=="object"){const t={};for(const[r,a]of Object.entries(c))t[r]=Ki(a,e);return t}return c}class kl 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||"":jt(Rt(t)),l=e==="user"&&a,u=a==="sending"?"○":a==="sent"?"✓":a==="delivered"||a==="read"?"✓✓":"";this.shadow.innerHTML=`
401
+ `,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">${jt(Rt(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=jt(Rt(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=jt(Rt(e.content))):(a.innerHTML=jt(Rt(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);switch(this.timestampFormat){case"datetime":return`${t.toLocaleDateString(void 0,{month:"short",day:"2-digit"})}, ${t.toLocaleTimeString(void 0,{hour:"2-digit",minute:"2-digit"})}`;case"date":return t.toLocaleDateString(void 0,{month:"short",day:"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=kl(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(Ki(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 kl(c,e){return c.replace(/\{(\w+)\}/g,(t,r)=>e[r]??"")}function Ki(c,e){if(typeof c=="string")return kl(c,e);if(Array.isArray(c))return c.map(t=>Ki(t,e));if(c&&typeof c=="object"){const t={};for(const[r,a]of Object.entries(c))t[r]=Ki(a,e);return t}return c}class Sl 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||"":jt(Rt(t)),l=e==="user"&&a,u=a==="sending"?"○":a==="sent"?"✓":a==="delivered"||a==="read"?"✓✓":"";this.shadow.innerHTML=`
402
402
  <style>
403
403
  :host { display: flex; flex-direction: column; }
404
404
  :host([role="user"]) { align-items: flex-end; }
@@ -466,7 +466,7 @@ In order to be iterable, non-array objects must have a [Symbol.iterator]() metho
466
466
  ${n?`<aikaara-template-renderer
467
467
  content-type="${n}"
468
468
  template-id="${i}"
469
- inner-message="${Es(s)}"
469
+ inner-message="${xs(s)}"
470
470
  ></aikaara-template-renderer>`:""}
471
471
  ${this.renderAttachments()}
472
472
  </div>
@@ -475,9 +475,9 @@ In order to be iterable, non-array objects must have a [Symbol.iterator]() metho
475
475
  ${r}${l?`<span class="status">${u}</span>`:""}
476
476
  </div>
477
477
  `:""}
478
- `;const d=this.shadow.querySelector("aikaara-template-renderer");d&&this.templatePayload!==null&&d.setPayload(this.templatePayload,s),d&&d.addEventListener("template-action",p=>{this.dispatchEvent(new CustomEvent("message-action",{detail:p.detail,bubbles:!0,composed:!0}))})}renderAttachments(){return this.attachments.length?`<div class="attachments">${this.attachments.map(t=>`<a class="attachment" href="${Es(t.fileUrl)}" target="_blank" rel="noopener noreferrer">
479
- 📎 ${Sh(t.fileName)}
480
- </a>`).join("")}</div>`:""}}function Es(c){return String(c).replace(/[&<>"']/g,e=>({"&":"&amp;","<":"&lt;",">":"&gt;",'"':"&quot;","'":"&#39;"})[e])}function Sh(c){return String(c).replace(/[&<>]/g,e=>({"&":"&amp;","<":"&lt;",">":"&gt;"})[e])}class Sl extends HTMLElement{shadow;textarea;sendBtn;attachBtn;fileInput;_disabled=!1;_uploading=!1;constructor(){super(),this.shadow=this.attachShadow({mode:"open"})}static get observedAttributes(){return["placeholder","disable-attach","accept","multiple","attach-position","send-shape"]}connectedCallback(){const e=this.getAttribute("placeholder")||"Type a message...",t=!this.hasAttribute("disable-attach"),r=this.getAttribute("accept")??"",a=this.hasAttribute("multiple"),n=this.getAttribute("attach-position")==="right",i=this.getAttribute("send-shape")==="square",s=t?`
478
+ `;const d=this.shadow.querySelector("aikaara-template-renderer");d&&this.templatePayload!==null&&d.setPayload(this.templatePayload,s),d&&d.addEventListener("template-action",p=>{this.dispatchEvent(new CustomEvent("message-action",{detail:p.detail,bubbles:!0,composed:!0}))})}renderAttachments(){return this.attachments.length?`<div class="attachments">${this.attachments.map(t=>`<a class="attachment" href="${xs(t.fileUrl)}" target="_blank" rel="noopener noreferrer">
479
+ 📎 ${Th(t.fileName)}
480
+ </a>`).join("")}</div>`:""}}function xs(c){return String(c).replace(/[&<>"']/g,e=>({"&":"&amp;","<":"&lt;",">":"&gt;",'"':"&quot;","'":"&#39;"})[e])}function Th(c){return String(c).replace(/[&<>]/g,e=>({"&":"&amp;","<":"&lt;",">":"&gt;"})[e])}class El extends HTMLElement{shadow;textarea;sendBtn;attachBtn;fileInput;_disabled=!1;_uploading=!1;constructor(){super(),this.shadow=this.attachShadow({mode:"open"})}static get observedAttributes(){return["placeholder","disable-attach","accept","multiple","attach-position","send-shape"]}connectedCallback(){const e=this.getAttribute("placeholder")||"Type a message...",t=!this.hasAttribute("disable-attach"),r=this.getAttribute("accept")??"",a=this.hasAttribute("multiple"),n=this.getAttribute("attach-position")==="right",i=this.getAttribute("send-shape")==="square",s=t?`
481
481
  <button class="attach-btn" aria-label="Attach file" type="button">
482
482
  <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
483
483
  <path d="M21.44 11.05l-9.19 9.19a6 6 0 0 1-8.49-8.49l9.19-9.19a4 4 0 0 1 5.66 5.66l-9.2 9.19a2 2 0 0 1-2.83-2.83l8.49-8.48"/>
@@ -555,7 +555,7 @@ In order to be iterable, non-array objects must have a [Symbol.iterator]() metho
555
555
  ${n?s:""}
556
556
  ${o}
557
557
  </div>
558
- `,this.textarea=this.shadow.querySelector("textarea"),this.sendBtn=this.shadow.querySelector(".send-btn"),this.attachBtn=this.shadow.querySelector(".attach-btn"),this.fileInput=this.shadow.querySelector('input[type="file"]'),this.textarea.addEventListener("input",()=>{this.autoGrow(),this.refreshSendDisabled()}),this.textarea.addEventListener("keydown",u=>{u.key==="Enter"&&!u.shiftKey&&(u.preventDefault(),this.handleSend())}),this.sendBtn.addEventListener("click",()=>this.handleSend()),this.attachBtn?.addEventListener("click",()=>{this._disabled||this._uploading||this.fileInput?.click()}),this.fileInput?.addEventListener("change",()=>{const u=this.fileInput?.files;if(u?.length){for(const d of Array.from(u))this.dispatchEvent(new CustomEvent("file-pick",{detail:{file:d},bubbles:!0,composed:!0}));this.fileInput&&(this.fileInput.value="")}})}set disabled(e){this._disabled=e,this.textarea&&(this.textarea.disabled=e),this.attachBtn&&(this.attachBtn.disabled=e||this._uploading),this.refreshSendDisabled()}get disabled(){return this._disabled}set uploading(e){this._uploading=e,this.attachBtn&&(this.attachBtn.dataset.uploading=String(e),this.attachBtn.disabled=this._disabled||e)}get uploading(){return this._uploading}focus(){this.textarea?.focus()}clear(){this.textarea&&(this.textarea.value="",this.textarea.style.height="auto",this.refreshSendDisabled())}refreshSendDisabled(){this.sendBtn&&(this.sendBtn.disabled=this._disabled||this._uploading||!this.textarea.value.trim())}handleSend(){const e=this.textarea.value.trim();!e||this._disabled||(this.dispatchEvent(new CustomEvent("send",{detail:{content:e},bubbles:!0,composed:!0})),this.clear(),this.textarea.focus())}autoGrow(){this.textarea.style.height="auto",this.textarea.style.height=Math.min(this.textarea.scrollHeight,120)+"px"}}class El extends HTMLElement{shadow;constructor(){super(),this.shadow=this.attachShadow({mode:"open"})}connectedCallback(){this.shadow.innerHTML=`
558
+ `,this.textarea=this.shadow.querySelector("textarea"),this.sendBtn=this.shadow.querySelector(".send-btn"),this.attachBtn=this.shadow.querySelector(".attach-btn"),this.fileInput=this.shadow.querySelector('input[type="file"]'),this.textarea.addEventListener("input",()=>{this.autoGrow(),this.refreshSendDisabled()}),this.textarea.addEventListener("keydown",u=>{u.key==="Enter"&&!u.shiftKey&&(u.preventDefault(),this.handleSend())}),this.sendBtn.addEventListener("click",()=>this.handleSend()),this.attachBtn?.addEventListener("click",()=>{this._disabled||this._uploading||this.fileInput?.click()}),this.fileInput?.addEventListener("change",()=>{const u=this.fileInput?.files;if(u?.length){for(const d of Array.from(u))this.dispatchEvent(new CustomEvent("file-pick",{detail:{file:d},bubbles:!0,composed:!0}));this.fileInput&&(this.fileInput.value="")}})}set disabled(e){this._disabled=e,this.textarea&&(this.textarea.disabled=e),this.attachBtn&&(this.attachBtn.disabled=e||this._uploading),this.refreshSendDisabled()}get disabled(){return this._disabled}set uploading(e){this._uploading=e,this.attachBtn&&(this.attachBtn.dataset.uploading=String(e),this.attachBtn.disabled=this._disabled||e)}get uploading(){return this._uploading}focus(){this.textarea?.focus()}clear(){this.textarea&&(this.textarea.value="",this.textarea.style.height="auto",this.refreshSendDisabled())}refreshSendDisabled(){this.sendBtn&&(this.sendBtn.disabled=this._disabled||this._uploading||!this.textarea.value.trim())}handleSend(){const e=this.textarea.value.trim();!e||this._disabled||(this.dispatchEvent(new CustomEvent("send",{detail:{content:e},bubbles:!0,composed:!0})),this.clear(),this.textarea.focus())}autoGrow(){this.textarea.style.height="auto",this.textarea.style.height=Math.min(this.textarea.scrollHeight,120)+"px"}}class xl extends HTMLElement{shadow;constructor(){super(),this.shadow=this.attachShadow({mode:"open"})}connectedCallback(){this.shadow.innerHTML=`
559
559
  <style>
560
560
  :host { display: none; }
561
561
  :host([visible]) { display: block; }
@@ -589,7 +589,7 @@ In order to be iterable, non-array objects must have a [Symbol.iterator]() metho
589
589
  <span class="dot"></span>
590
590
  <span class="dot"></span>
591
591
  </div>
592
- `}show(){this.setAttribute("visible","")}hide(){this.removeAttribute("visible")}}class xl extends HTMLElement{shadow;bubble;constructor(){super(),this.shadow=this.attachShadow({mode:"open"})}connectedCallback(){this.shadow.innerHTML=`
592
+ `}show(){this.setAttribute("visible","")}hide(){this.removeAttribute("visible")}}class Al extends HTMLElement{shadow;bubble;constructor(){super(),this.shadow=this.attachShadow({mode:"open"})}connectedCallback(){this.shadow.innerHTML=`
593
593
  <style>
594
594
  :host {
595
595
  display: flex;
@@ -638,7 +638,7 @@ In order to be iterable, non-array objects must have a [Symbol.iterator]() metho
638
638
  }
639
639
  </style>
640
640
  <div class="bubble cursor"></div>
641
- `,this.bubble=this.shadow.querySelector(".bubble")}updateContent(e){this.bubble&&(this.bubble.innerHTML=jt(Rt(e)),this.bubble.classList.add("cursor"))}finalize(){this.bubble?.classList.remove("cursor")}}class Al extends HTMLElement{shadow;container;dismissTimer=null;constructor(){super(),this.shadow=this.attachShadow({mode:"open"})}connectedCallback(){this.shadow.innerHTML=`
641
+ `,this.bubble=this.shadow.querySelector(".bubble")}updateContent(e){this.bubble&&(this.bubble.innerHTML=jt(Rt(e)),this.bubble.classList.add("cursor"))}finalize(){this.bubble?.classList.remove("cursor")}}class Il extends HTMLElement{shadow;container;dismissTimer=null;constructor(){super(),this.shadow=this.attachShadow({mode:"open"})}connectedCallback(){this.shadow.innerHTML=`
642
642
  <style>
643
643
  .banner {
644
644
  display: none;
@@ -666,14 +666,14 @@ In order to be iterable, non-array objects must have a [Symbol.iterator]() metho
666
666
  <span class="message"></span>
667
667
  <button class="dismiss">Dismiss</button>
668
668
  </div>
669
- `,this.container=this.shadow.querySelector(".banner"),this.shadow.querySelector(".dismiss")?.addEventListener("click",()=>this.hide())}show(e,t){const r=this.container.querySelector(".message");r&&(r.textContent=e),this.container.classList.add("visible"),this.dismissTimer&&clearTimeout(this.dismissTimer),t&&(this.dismissTimer=setTimeout(()=>this.hide(),t))}hide(){this.container.classList.remove("visible"),this.dismissTimer&&(clearTimeout(this.dismissTimer),this.dismissTimer=null)}}const qr=new Map;function Eh(c){const e=qr.get(c);if(e)return e;const t=new Promise((r,a)=>{const n=document.querySelector(`script[data-aikaara-src="${CSS.escape(c)}"]`);if(n){n.dataset.aikaaraReady==="1"?r():(n.addEventListener("load",()=>r(),{once:!0}),n.addEventListener("error",()=>a(new Error(`Failed to load ${c}`)),{once:!0}));return}const i=document.createElement("script");i.src=c,i.async=!0,i.crossOrigin="anonymous",i.dataset.aikaaraSrc=c,i.addEventListener("load",()=>{i.dataset.aikaaraReady="1",r()},{once:!0}),i.addEventListener("error",()=>{qr.delete(c),a(new Error(`Failed to load ${c}`))},{once:!0}),document.head.appendChild(i)});return qr.set(c,t),t}function xh(c,e=5e3){return new Promise((t,r)=>{const a=setTimeout(()=>r(new Error(`Custom element <${c}> not registered within ${e}ms`)),e);customElements.whenDefined(c).then(()=>{clearTimeout(a),t()})})}function Ah(c){const e=`template:${c}`,t=window.__aikaara_descriptor__?.components?.[e];return t&&t.kind==="iife-element"?{render:t.tag,scriptUrl:t.scriptUrl,props:t.props}:window.__aikaara_descriptor__?.templates?.[c]}class Il extends HTMLElement{shadow;payloadData=null;innerMessage="";static get observedAttributes(){return["content-type","template-id","message-id"]}constructor(){super(),this.shadow=this.attachShadow({mode:"open"})}connectedCallback(){this.render(),this.addEventListener("template-action",()=>{this.dataset.consumed="true"})}attributeChangedCallback(){this.render()}setPayload(e,t){this.payloadData=e,t!==void 0&&(this.innerMessage=t),this.render()}render(){const e=this.getAttribute("content-type")??"",t=this.getAttribute("template-id")??"";for(this.shadow.innerHTML=`
669
+ `,this.container=this.shadow.querySelector(".banner"),this.shadow.querySelector(".dismiss")?.addEventListener("click",()=>this.hide())}show(e,t){const r=this.container.querySelector(".message");r&&(r.textContent=e),this.container.classList.add("visible"),this.dismissTimer&&clearTimeout(this.dismissTimer),t&&(this.dismissTimer=setTimeout(()=>this.hide(),t))}hide(){this.container.classList.remove("visible"),this.dismissTimer&&(clearTimeout(this.dismissTimer),this.dismissTimer=null)}}const qr=new Map;function Tl(c){const e=qr.get(c);if(e)return e;const t=new Promise((r,a)=>{const n=document.querySelector(`script[data-aikaara-src="${CSS.escape(c)}"]`);if(n){n.dataset.aikaaraReady==="1"?r():(n.addEventListener("load",()=>r(),{once:!0}),n.addEventListener("error",()=>a(new Error(`Failed to load ${c}`)),{once:!0}));return}const i=document.createElement("script");i.src=c,i.async=!0,i.crossOrigin="anonymous",i.dataset.aikaaraSrc=c,i.addEventListener("load",()=>{i.dataset.aikaaraReady="1",r()},{once:!0}),i.addEventListener("error",()=>{qr.delete(c),a(new Error(`Failed to load ${c}`))},{once:!0}),document.head.appendChild(i)});return qr.set(c,t),t}function Ch(c,e=5e3){return new Promise((t,r)=>{const a=setTimeout(()=>r(new Error(`Custom element <${c}> not registered within ${e}ms`)),e);customElements.whenDefined(c).then(()=>{clearTimeout(a),t()})})}function Oh(c){const e=`template:${c}`,t=window.__aikaara_descriptor__?.components?.[e];return t&&t.kind==="iife-element"?{render:t.tag,scriptUrl:t.scriptUrl,props:t.props}:window.__aikaara_descriptor__?.templates?.[c]}class Cl extends HTMLElement{shadow;payloadData=null;innerMessage="";static get observedAttributes(){return["content-type","template-id","message-id"]}constructor(){super(),this.shadow=this.attachShadow({mode:"open"})}connectedCallback(){this.render(),this.addEventListener("template-action",()=>{this.dataset.consumed="true"})}attributeChangedCallback(){this.render()}setPayload(e,t){this.payloadData=e,t!==void 0&&(this.innerMessage=t),this.render()}render(){const e=this.getAttribute("content-type")??"",t=this.getAttribute("template-id")??"";for(this.shadow.innerHTML=`
670
670
  <style>
671
671
  :host { display: block; }
672
672
  :host([data-consumed]) ::slotted(*) { display: none !important; }
673
673
  ::slotted(*) { display: block; }
674
674
  </style>
675
675
  <slot></slot>
676
- `;this.firstChild;)this.removeChild(this.firstChild);if(!e)return;const r=t?Ah(t):void 0,a=r?.render??(t?`aikaara-template-${t}`:`aikaara-template-${e}`);if(r?.scriptUrl&&!customElements.get(a)&&Eh(r.scriptUrl).then(()=>xh(a)).then(()=>this.render()).catch(n=>console.warn(`[aikaara-template-renderer] failed to lazy-load ${r.scriptUrl}`,n)),customElements.get(a)){const n=document.createElement(a);if(r?.props){for(const[i,s]of Object.entries(r.props))if(typeof n[i]=="function")try{n[i](s)}catch(o){console.warn(`[aikaara-template-renderer] props.${i} threw on <${a}>`,o)}}n.setPayload?.(this.payloadData,this.innerMessage),this.appendChild(n);return}if(Array.isArray(this.payloadData)){const n=this.payloadData;if(n.length>0&&n.every(s=>s&&typeof s=="object"&&!Array.isArray(s)&&!("type"in s)&&!("data"in s)&&typeof s.message=="string")){const s=document.createElement("aikaara-option-list");s.setPayload({name:"quick-reply",type:"button",options:n.map(o=>{const l=typeof o.title=="string"?o.title:"",u=o.message;return{label:l||u,value:u}})}),this.appendChild(s);return}for(const s of n)this.mountField(s)}else if(this.payloadData&&typeof this.payloadData=="object"){const n=this.payloadData;typeof n.message=="string"&&(n.okLabel||n.action||n.ok)&&this.mountModal(n)}}mountField(e){if(!e||typeof e!="object")return;const t=e.type??e.data?.type;if(t==="link"){this.mountLinkButton(e);return}const r=e.data;if(r){if(t==="checkbox"||t==="radio"||t==="button"){const a=document.createElement("aikaara-option-list");a.setPayload({name:r.name??"",title:r.title,options:r.options??[],type:t}),this.appendChild(a);return}if(t==="submit"){const a=document.createElement("aikaara-submit-action"),n=this.getAttribute("message-id")??void 0;a.setPayload({name:r.name??"Submit",action:r.action??{message:r.name??"Submit"},messageId:n}),this.appendChild(a);return}t==="modal"&&this.mountModal({message:r.message??"",okLabel:r.okLabel,cancelLabel:r.cancelLabel,action:r.action})}}mountLinkButton(e){Promise.resolve().then(()=>require("./AikaaraLinkButton-VDNx7RfC.cjs")).then(({registerAikaaraLinkButton:t,AikaaraLinkButton:r})=>{t();const a=document.createElement("aikaara-link-button");a.setPayload({name:e.name??"Open",url:e.url??"",openLinkInNewTab:e.openLinkInNewTab,orderId:e.orderId,extra:Th(e),messageId:this.getAttribute("message-id")??void 0}),this.appendChild(a)})}mountModal(e){const t=document.createElement("aikaara-modal-action");t.setPayload(e),this.appendChild(t)}}const Ih=new Set(["type","url","name","openLinkInNewTab","orderId"]);function Th(c){const e={};for(const[t,r]of Object.entries(c))Ih.has(t)||(e[t]=r);return e}class Tl extends HTMLElement{shadow;static get observedAttributes(){return["text","subtext"]}constructor(){super(),this.shadow=this.attachShadow({mode:"open"})}connectedCallback(){this.render()}attributeChangedCallback(){this.render()}render(){const e=this.getAttribute("text")??this.textContent??"",t=this.getAttribute("subtext")??"";this.shadow.innerHTML=`
676
+ `;this.firstChild;)this.removeChild(this.firstChild);if(!e)return;const r=t?Oh(t):void 0,a=r?.render??(t?`aikaara-template-${t}`:`aikaara-template-${e}`);if(r?.scriptUrl&&!customElements.get(a)&&Tl(r.scriptUrl).then(()=>Ch(a)).then(()=>this.render()).catch(n=>console.warn(`[aikaara-template-renderer] failed to lazy-load ${r.scriptUrl}`,n)),customElements.get(a)){const n=document.createElement(a);if(r?.props){for(const[i,s]of Object.entries(r.props))if(typeof n[i]=="function")try{n[i](s)}catch(o){console.warn(`[aikaara-template-renderer] props.${i} threw on <${a}>`,o)}}n.setPayload?.(this.payloadData,this.innerMessage),this.appendChild(n);return}if(Array.isArray(this.payloadData)){const n=this.payloadData;if(n.length>0&&n.every(s=>s&&typeof s=="object"&&!Array.isArray(s)&&!("type"in s)&&!("data"in s)&&typeof s.message=="string")){const s=document.createElement("aikaara-option-list");s.setPayload({name:"quick-reply",type:"button",options:n.map(o=>{const l=typeof o.title=="string"?o.title:"",u=o.message;return{label:l||u,value:u}})}),this.appendChild(s);return}for(const s of n)this.mountField(s)}else if(this.payloadData&&typeof this.payloadData=="object"){const n=this.payloadData;typeof n.message=="string"&&(n.okLabel||n.action||n.ok)&&this.mountModal(n)}}mountField(e){if(!e||typeof e!="object")return;const t=e.type??e.data?.type;if(t==="link"){this.mountLinkButton(e);return}const r=e.data;if(r){if(t==="checkbox"||t==="radio"||t==="button"){const a=document.createElement("aikaara-option-list");a.setPayload({name:r.name??"",title:r.title,options:r.options??[],type:t}),this.appendChild(a);return}if(t==="submit"){const a=document.createElement("aikaara-submit-action"),n=this.getAttribute("message-id")??void 0;a.setPayload({name:r.name??"Submit",action:r.action??{message:r.name??"Submit"},messageId:n}),this.appendChild(a);return}t==="modal"&&this.mountModal({message:r.message??"",okLabel:r.okLabel,cancelLabel:r.cancelLabel,action:r.action})}}mountLinkButton(e){Promise.resolve().then(()=>require("./AikaaraLinkButton-VDNx7RfC.cjs")).then(({registerAikaaraLinkButton:t,AikaaraLinkButton:r})=>{t();const a=document.createElement("aikaara-link-button");a.setPayload({name:e.name??"Open",url:e.url??"",openLinkInNewTab:e.openLinkInNewTab,orderId:e.orderId,extra:Mh(e),messageId:this.getAttribute("message-id")??void 0}),this.appendChild(a)})}mountModal(e){const t=document.createElement("aikaara-modal-action");t.setPayload(e),this.appendChild(t)}}const Ph=new Set(["type","url","name","openLinkInNewTab","orderId"]);function Mh(c){const e={};for(const[t,r]of Object.entries(c))Ph.has(t)||(e[t]=r);return e}class Ol extends HTMLElement{shadow;static get observedAttributes(){return["text","subtext"]}constructor(){super(),this.shadow=this.attachShadow({mode:"open"})}connectedCallback(){this.render()}attributeChangedCallback(){this.render()}render(){const e=this.getAttribute("text")??this.textContent??"",t=this.getAttribute("subtext")??"";this.shadow.innerHTML=`
677
677
  <style>
678
678
  :host {
679
679
  display: flex;
@@ -698,9 +698,9 @@ In order to be iterable, non-array objects must have a [Symbol.iterator]() metho
698
698
  color: var(--aikaara-text-secondary, #9ca3af);
699
699
  }
700
700
  </style>
701
- <span class="pill">${xs(e)}</span>
702
- ${t?`<span class="sub">${xs(t)}</span>`:""}
703
- `}}function xs(c){return String(c).replace(/[&<>]/g,e=>({"&":"&amp;","<":"&lt;",">":"&gt;"})[e])}class Cl extends HTMLElement{shadow;data=null;selected=new Set;constructor(){super(),this.shadow=this.attachShadow({mode:"open"})}connectedCallback(){this.render()}setPayload(e){this.data=e,this.selected.clear(),this.render()}getValues(){return{name:this.data?.name??"",values:[...this.selected],type:this.data?.type??"checkbox"}}toggle(e){this.data&&(this.data.type==="radio"||this.data.type==="button"?(this.selected.clear(),this.selected.add(e)):this.selected.has(e)?this.selected.delete(e):this.selected.add(e),this.data.type==="button"?this.dispatchEvent(new CustomEvent("template-action",{detail:{text:e,attributes:{action:{[this.data.name]:e}}},bubbles:!0,composed:!0})):this.dispatchEvent(new CustomEvent("option-change",{detail:this.getValues(),bubbles:!0,composed:!0})),this.render())}render(){if(!this.data){this.shadow.innerHTML="";return}const{title:e,options:t,type:r}=this.data,a=r==="checkbox";if(r==="checkbox"&&t.length===1&&(t[0]?.label??"").trim()===""&&(e??"").trim()!==""){const i=t[0],s=this.selected.has(i.value);this.shadow.innerHTML=`
701
+ <span class="pill">${As(e)}</span>
702
+ ${t?`<span class="sub">${As(t)}</span>`:""}
703
+ `}}function As(c){return String(c).replace(/[&<>]/g,e=>({"&":"&amp;","<":"&lt;",">":"&gt;"})[e])}class Pl extends HTMLElement{shadow;data=null;selected=new Set;constructor(){super(),this.shadow=this.attachShadow({mode:"open"})}connectedCallback(){this.render()}setPayload(e){this.data=e,this.selected.clear(),this.render()}getValues(){return{name:this.data?.name??"",values:[...this.selected],type:this.data?.type??"checkbox"}}toggle(e){this.data&&(this.data.type==="radio"||this.data.type==="button"?(this.selected.clear(),this.selected.add(e)):this.selected.has(e)?this.selected.delete(e):this.selected.add(e),this.data.type==="button"?this.dispatchEvent(new CustomEvent("template-action",{detail:{text:e,attributes:{action:{[this.data.name]:e}}},bubbles:!0,composed:!0})):this.dispatchEvent(new CustomEvent("option-change",{detail:this.getValues(),bubbles:!0,composed:!0})),this.render())}render(){if(!this.data){this.shadow.innerHTML="";return}const{title:e,options:t,type:r}=this.data,a=r==="checkbox";if(r==="checkbox"&&t.length===1&&(t[0]?.label??"").trim()===""&&(e??"").trim()!==""){const i=t[0],s=this.selected.has(i.value);this.shadow.innerHTML=`
704
704
  <style>
705
705
  :host { display: block; margin: 8px 0; }
706
706
  .row {
@@ -735,7 +735,7 @@ In order to be iterable, non-array objects must have a [Symbol.iterator]() metho
735
735
  .row[aria-checked="true"] .check { opacity: 1; }
736
736
  .text { flex: 1; }
737
737
  </style>
738
- <div class="row" role="checkbox" tabindex="0" aria-checked="${s}" data-value="${As(i.value)}">
738
+ <div class="row" role="checkbox" tabindex="0" aria-checked="${s}" data-value="${Is(i.value)}">
739
739
  <span class="box" aria-hidden="true">
740
740
  <svg class="check" viewBox="0 0 16 16" fill="none" stroke-width="2.5" stroke-linecap="round" stroke-linejoin="round">
741
741
  <path d="M3 8 L7 12 L13 4" />
@@ -780,13 +780,13 @@ In order to be iterable, non-array objects must have a [Symbol.iterator]() metho
780
780
  <div class="grid" role="${a?"group":"radiogroup"}" aria-label="${rr(e??this.data.name)}">
781
781
  ${t.map(i=>`
782
782
  <button class="opt" type="button"
783
- data-value="${As(i.value)}"
783
+ data-value="${Is(i.value)}"
784
784
  role="${a?"checkbox":"radio"}"
785
785
  aria-pressed="${this.selected.has(i.value)}">
786
786
  ${rr(i.label)}
787
787
  </button>`).join("")}
788
788
  </div>
789
- `,this.shadow.querySelectorAll("button.opt").forEach(i=>{i.addEventListener("click",()=>this.toggle(i.dataset.value||""))})}}function rr(c){return String(c).replace(/[&<>]/g,e=>({"&":"&amp;","<":"&lt;",">":"&gt;"})[e])}function As(c){return String(c).replace(/[&<>"']/g,e=>({"&":"&amp;","<":"&lt;",">":"&gt;",'"':"&quot;","'":"&#39;"})[e])}class Ol extends HTMLElement{shadow;data=null;constructor(){super(),this.shadow=this.attachShadow({mode:"open"})}connectedCallback(){this.render()}setPayload(e){this.data=e,this.render()}collectFormValues(){const e={},t=this.closest("aikaara-template-renderer")??this.parentElement;return t&&t.querySelectorAll("aikaara-option-list").forEach(r=>{const a=r.getValues?.();a?.name&&(e[a.name]=a.values)}),e}handleClick(){if(!this.data)return;const e=this.data.action??{message:this.data.name},t=this.collectFormValues(),r={...this.data.messageId?{message_id:this.data.messageId}:{},...t};e.formAction&&(r.formAction=e.formAction),e.requestType&&(r.requestType=e.requestType),this.dispatchEvent(new CustomEvent("template-action",{detail:{text:e.message,attributes:{action:r}},bubbles:!0,composed:!0}))}render(){if(!this.data){this.shadow.innerHTML="";return}const e=this.data.name;this.shadow.innerHTML=`
789
+ `,this.shadow.querySelectorAll("button.opt").forEach(i=>{i.addEventListener("click",()=>this.toggle(i.dataset.value||""))})}}function rr(c){return String(c).replace(/[&<>]/g,e=>({"&":"&amp;","<":"&lt;",">":"&gt;"})[e])}function Is(c){return String(c).replace(/[&<>"']/g,e=>({"&":"&amp;","<":"&lt;",">":"&gt;",'"':"&quot;","'":"&#39;"})[e])}class Ml extends HTMLElement{shadow;data=null;constructor(){super(),this.shadow=this.attachShadow({mode:"open"})}connectedCallback(){this.render()}setPayload(e){this.data=e,this.render()}collectFormValues(){const e={},t=this.closest("aikaara-template-renderer")??this.parentElement;return t&&t.querySelectorAll("aikaara-option-list").forEach(r=>{const a=r.getValues?.();a?.name&&(e[a.name]=a.values)}),e}handleClick(){if(!this.data)return;const e=this.data.action??{message:this.data.name},t=this.collectFormValues(),r={...this.data.messageId?{message_id:this.data.messageId}:{},...t};e.formAction&&(r.formAction=e.formAction),e.requestType&&(r.requestType=e.requestType),this.dispatchEvent(new CustomEvent("template-action",{detail:{text:e.message,attributes:{action:r}},bubbles:!0,composed:!0}))}render(){if(!this.data){this.shadow.innerHTML="";return}const e=this.data.name;this.shadow.innerHTML=`
790
790
  <style>
791
791
  :host { display: block; margin: 12px 0 4px; }
792
792
  button {
@@ -804,8 +804,8 @@ In order to be iterable, non-array objects must have a [Symbol.iterator]() metho
804
804
  button:hover { background: var(--aikaara-submit-hover-bg, var(--aikaara-primary-hover, #4f46e5)); }
805
805
  button:disabled { opacity: var(--aikaara-submit-disabled-opacity, 0.5); cursor: not-allowed; }
806
806
  </style>
807
- <button type="button">${Ch(e)}</button>
808
- `,this.shadow.querySelector("button").addEventListener("click",()=>this.handleClick())}}function Ch(c){return String(c).replace(/[&<>]/g,e=>({"&":"&amp;","<":"&lt;",">":"&gt;"})[e])}class Pl extends HTMLElement{shadow;data=null;dismissed=!1;constructor(){super(),this.shadow=this.attachShadow({mode:"open"})}connectedCallback(){this.render()}setPayload(e){this.data=e,this.dismissed=!1,this.render()}dismiss(){this.dismissed=!0,this.render()}handleOk(){if(!this.data)return;const e=this.data.action;this.dispatchEvent(new CustomEvent("template-action",{detail:{text:e?.message??this.data.message,attributes:{action:{confirmed:!0,requestType:e?.requestType??"postBackToBotPlatform"}}},bubbles:!0,composed:!0})),this.dismiss()}render(){if(!this.data||this.dismissed){this.shadow.innerHTML="";return}const e=this.data.okLabel??"Ok",t=this.data.cancelLabel;this.shadow.innerHTML=`
807
+ <button type="button">${Rh(e)}</button>
808
+ `,this.shadow.querySelector("button").addEventListener("click",()=>this.handleClick())}}function Rh(c){return String(c).replace(/[&<>]/g,e=>({"&":"&amp;","<":"&lt;",">":"&gt;"})[e])}class Rl extends HTMLElement{shadow;data=null;dismissed=!1;constructor(){super(),this.shadow=this.attachShadow({mode:"open"})}connectedCallback(){this.render()}setPayload(e){this.data=e,this.dismissed=!1,this.render()}dismiss(){this.dismissed=!0,this.render()}handleOk(){if(!this.data)return;const e=this.data.action;this.dispatchEvent(new CustomEvent("template-action",{detail:{text:e?.message??this.data.message,attributes:{action:{confirmed:!0,requestType:e?.requestType??"postBackToBotPlatform"}}},bubbles:!0,composed:!0})),this.dismiss()}render(){if(!this.data||this.dismissed){this.shadow.innerHTML="";return}const e=this.data.okLabel??"Ok",t=this.data.cancelLabel;this.shadow.innerHTML=`
809
809
  <style>
810
810
  :host { all: initial; }
811
811
  .overlay {
@@ -853,7 +853,7 @@ In order to be iterable, non-array objects must have a [Symbol.iterator]() metho
853
853
  </div>
854
854
  </div>
855
855
  </div>
856
- `,this.shadow.querySelector("button.ok").addEventListener("click",()=>this.handleOk()),this.shadow.querySelector("button.cancel")?.addEventListener("click",()=>this.dismiss())}}function Hr(c){return String(c).replace(/[&<>]/g,e=>({"&":"&amp;","<":"&lt;",">":"&gt;"})[e])}class Ml extends HTMLElement{static get observedAttributes(){return["slug","user-id","user-name","user-token","department-id","config-base","api-key"]}tokenGetter;apiKey;configHeaders;identity;credentialProviders;mounted=null;mountInflight=null;connectedCallback(){this.style.display||(this.style.display="flex"),this.style.flexDirection||(this.style.flexDirection="column"),this.style.minHeight||(this.style.minHeight="0"),this.tryMount()}disconnectedCallback(){this.mounted?.destroy(),this.mounted=null}attributeChangedCallback(){this.isConnected&&(this.mounted?.destroy(),this.mounted=null,this.tryMount())}async refreshAuth(){await this.mounted?.refreshAuth()}async tryMount(){if(this.mountInflight)return this.mountInflight;const e=this.getAttribute("slug"),t=this.getAttribute("user-id");if(!e||!t)return;const r=this.getAttribute("user-token"),a=this.tokenGetter??r;if(!a){this.dispatchEvent(new CustomEvent("error",{detail:new Error("aikaara-chat: user-token attribute or tokenGetter property required")}));return}const n={...this.configHeaders??{}},i=Object.keys(n).find(l=>l.toLowerCase()==="x-api-key"),s=this.apiKey??this.getAttribute("api-key")??(i?n[i]:void 0);s&&(i&&i!=="X-Api-Key"&&delete n[i],n["X-Api-Key"]=s);const o=Object.keys(n).length>0?n:void 0;return this.mountInflight=(async()=>{try{this.mounted=await Hl({container:this,slug:e,configBase:this.getAttribute("config-base")??void 0,configHeaders:o,user:{id:t,name:this.getAttribute("user-name")??void 0,departmentId:this.getAttribute("department-id")??void 0,token:a,identity:this.identity,credentialProviders:this.credentialProviders},hooks:{onError:l=>this.dispatchEvent(new CustomEvent("error",{detail:l}))}}),this.dispatchEvent(new CustomEvent("ready",{detail:{requestId:this.mounted.requestId,fullName:this.mounted.fullName}}))}catch(l){this.dispatchEvent(new CustomEvent("error",{detail:l}))}finally{this.mountInflight=null}})(),this.mountInflight}}class Rl extends HTMLElement{shadow;root=null;iframe=null;fallbackTimer=null;constructor(){super(),this.shadow=this.attachShadow({mode:"open"})}connectedCallback(){this.root||this.render()}show(e,t){if(this.root||this.render(),!this.root||!this.iframe)return;const r=this.shadow.querySelector(".modal-title");r&&(r.textContent=t||"Link"),this.swapBody("iframe"),this.iframe.src=e,this.root.classList.add("open"),this.dispatchEvent(new CustomEvent("aikaara-link-modal-open",{detail:{url:e},bubbles:!0,composed:!0})),this.fallbackTimer&&window.clearTimeout(this.fallbackTimer);let a=!1;this.iframe.addEventListener("load",()=>{a=!0},{once:!0}),this.fallbackTimer=window.setTimeout(()=>{a||(this.close(),window.open(e,"_blank","noopener,noreferrer"))},3500)}showElement(e,t,r){if(this.root||this.render(),!this.root)return;const a=this.shadow.querySelector(".modal-title");a&&(a.textContent=t||"Details"),this.swapBody("element");const n=this.shadow.querySelector(".modal-body-element");if(n){n.innerHTML="";const i=document.createElement(e);n.appendChild(i),requestAnimationFrame(()=>r?.(i))}this.root.classList.add("open"),this.dispatchEvent(new CustomEvent("aikaara-link-modal-open",{detail:{element:e},bubbles:!0,composed:!0}))}swapBody(e){if(!this.iframe)return;const t=this.shadow.querySelector(".modal-body-element");e==="iframe"?(this.iframe.style.display="",t&&(t.style.display="none")):(this.iframe.style.display="none",t&&(t.style.display=""))}close(){this.root&&(this.root.classList.remove("open"),this.iframe&&(this.iframe.src="about:blank"),this.fallbackTimer&&(window.clearTimeout(this.fallbackTimer),this.fallbackTimer=null),this.dispatchEvent(new CustomEvent("aikaara-link-modal-close",{bubbles:!0,composed:!0})))}render(){this.shadow.innerHTML=`
856
+ `,this.shadow.querySelector("button.ok").addEventListener("click",()=>this.handleOk()),this.shadow.querySelector("button.cancel")?.addEventListener("click",()=>this.dismiss())}}function Hr(c){return String(c).replace(/[&<>]/g,e=>({"&":"&amp;","<":"&lt;",">":"&gt;"})[e])}class jl extends HTMLElement{static get observedAttributes(){return["slug","user-id","user-name","user-token","department-id","config-base","api-key"]}tokenGetter;apiKey;configHeaders;identity;credentialProviders;mounted=null;mountInflight=null;connectedCallback(){this.style.display||(this.style.display="flex"),this.style.flexDirection||(this.style.flexDirection="column"),this.style.minHeight||(this.style.minHeight="0"),this.tryMount()}disconnectedCallback(){this.mounted?.destroy(),this.mounted=null}attributeChangedCallback(){this.isConnected&&(this.mounted?.destroy(),this.mounted=null,this.tryMount())}async refreshAuth(){await this.mounted?.refreshAuth()}async tryMount(){if(this.mountInflight)return this.mountInflight;const e=this.getAttribute("slug"),t=this.getAttribute("user-id");if(!e||!t)return;const r=this.getAttribute("user-token"),a=this.tokenGetter??r;if(!a){this.dispatchEvent(new CustomEvent("error",{detail:new Error("aikaara-chat: user-token attribute or tokenGetter property required")}));return}const n={...this.configHeaders??{}},i=Object.keys(n).find(l=>l.toLowerCase()==="x-api-key"),s=this.apiKey??this.getAttribute("api-key")??(i?n[i]:void 0);s&&(i&&i!=="X-Api-Key"&&delete n[i],n["X-Api-Key"]=s);const o=Object.keys(n).length>0?n:void 0;return this.mountInflight=(async()=>{try{this.mounted=await Vl({container:this,slug:e,configBase:this.getAttribute("config-base")??void 0,configHeaders:o,user:{id:t,name:this.getAttribute("user-name")??void 0,departmentId:this.getAttribute("department-id")??void 0,token:a,identity:this.identity,credentialProviders:this.credentialProviders},hooks:{onError:l=>this.dispatchEvent(new CustomEvent("error",{detail:l}))}}),this.dispatchEvent(new CustomEvent("ready",{detail:{requestId:this.mounted.requestId,fullName:this.mounted.fullName}}))}catch(l){this.dispatchEvent(new CustomEvent("error",{detail:l}))}finally{this.mountInflight=null}})(),this.mountInflight}}class Ll extends HTMLElement{shadow;root=null;iframe=null;fallbackTimer=null;constructor(){super(),this.shadow=this.attachShadow({mode:"open"})}connectedCallback(){this.root||this.render()}show(e,t){if(this.root||this.render(),!this.root||!this.iframe)return;const r=this.shadow.querySelector(".modal-title");r&&(r.textContent=t||"Link"),this.swapBody("iframe"),this.iframe.src=e,this.root.classList.add("open"),this.dispatchEvent(new CustomEvent("aikaara-link-modal-open",{detail:{url:e},bubbles:!0,composed:!0})),this.fallbackTimer&&window.clearTimeout(this.fallbackTimer);let a=!1;this.iframe.addEventListener("load",()=>{a=!0},{once:!0}),this.fallbackTimer=window.setTimeout(()=>{a||(this.close(),window.open(e,"_blank","noopener,noreferrer"))},3500)}showElement(e,t,r){if(this.root||this.render(),!this.root)return;const a=this.shadow.querySelector(".modal-title");a&&(a.textContent=t||"Details"),this.swapBody("element");const n=this.shadow.querySelector(".modal-body-element");if(n){n.innerHTML="";const i=document.createElement(e);n.appendChild(i),requestAnimationFrame(()=>r?.(i))}this.root.classList.add("open"),this.dispatchEvent(new CustomEvent("aikaara-link-modal-open",{detail:{element:e},bubbles:!0,composed:!0}))}swapBody(e){if(!this.iframe)return;const t=this.shadow.querySelector(".modal-body-element");e==="iframe"?(this.iframe.style.display="",t&&(t.style.display="none")):(this.iframe.style.display="none",t&&(t.style.display=""))}close(){this.root&&(this.root.classList.remove("open"),this.iframe&&(this.iframe.src="about:blank"),this.fallbackTimer&&(window.clearTimeout(this.fallbackTimer),this.fallbackTimer=null),this.dispatchEvent(new CustomEvent("aikaara-link-modal-close",{bubbles:!0,composed:!0})))}render(){this.shadow.innerHTML=`
857
857
  <style>
858
858
  :host { display: block; }
859
859
  .backdrop {
@@ -903,7 +903,7 @@ In order to be iterable, non-array objects must have a [Symbol.iterator]() metho
903
903
  <div class="modal-body-element" style="display:none; flex:1; overflow:auto; padding:18px;"></div>
904
904
  </div>
905
905
  </div>
906
- `,this.root=this.shadow.querySelector(".backdrop"),this.iframe=this.shadow.querySelector("iframe"),this.shadow.querySelector(".modal-close")?.addEventListener("click",()=>this.close()),this.root?.addEventListener("click",t=>{t.target===this.root&&this.close()}),document.addEventListener("keydown",t=>{t.key==="Escape"&&this.classList.contains("open")&&this.close()})}}const Oh=[{label:"Self-filing guidance"},{label:"Smart tax suggestions"},{label:"Auto-fetch 26AS / AIS"},{label:"Notice management"},{label:"Dedicated tax expert"},{label:"End-to-end filing"},{label:"Document handling"}],Ph=[{label:"DIY",match:["DIY","DIY_SALARY"],selectLabel:"Select DIY — Without Notice (₹{price}/yr)",postback:"Without Notice",features:[!0,!0,!0,!1,!1,!1,!1]},{label:"DIY + Notice",match:["NOTICE_DIY","DIY_NOTICE"],selectLabel:"Select DIY — With Notice (₹{price}/yr)",postback:"With Notice",features:[!0,!0,!0,!0,!1,!1,!1]},{label:"Assisted",match:["ASSISTED"],selectLabel:"Switch to Assisted (₹{price}/yr)",postback:"Assisted",features:[!0,!0,!0,!0,!0,!0,!0]}];class jl extends HTMLElement{shadow;data=null;columns=Ph;features=Oh;constructor(){super(),this.shadow=this.attachShadow({mode:"open"})}connectedCallback(){this.render()}setData(e){this.data=e,this.render()}setColumns(e){this.columns=e,this.render()}setFeatures(e){this.features=e,this.render()}priceFor(e){if(!this.data?.data)return null;for(const t of this.data.data)if(e.match.includes(t.planType))return t.planMaster?.basePrice??null;return null}render(){const e=this.columns,t=this.features;this.shadow.innerHTML=`
906
+ `,this.root=this.shadow.querySelector(".backdrop"),this.iframe=this.shadow.querySelector("iframe"),this.shadow.querySelector(".modal-close")?.addEventListener("click",()=>this.close()),this.root?.addEventListener("click",t=>{t.target===this.root&&this.close()}),document.addEventListener("keydown",t=>{t.key==="Escape"&&this.classList.contains("open")&&this.close()})}}const jh=[{label:"Self-filing guidance"},{label:"Smart tax suggestions"},{label:"Auto-fetch 26AS / AIS"},{label:"Notice management"},{label:"Dedicated tax expert"},{label:"End-to-end filing"},{label:"Document handling"}],Lh=[{label:"DIY",match:["DIY","DIY_SALARY"],selectLabel:"Select DIY — Without Notice (₹{price}/yr)",postback:"Without Notice",features:[!0,!0,!0,!1,!1,!1,!1]},{label:"DIY + Notice",match:["NOTICE_DIY","DIY_NOTICE"],selectLabel:"Select DIY — With Notice (₹{price}/yr)",postback:"With Notice",features:[!0,!0,!0,!0,!1,!1,!1]},{label:"Assisted",match:["ASSISTED"],selectLabel:"Switch to Assisted (₹{price}/yr)",postback:"Assisted",features:[!0,!0,!0,!0,!0,!0,!0]}];class Nl extends HTMLElement{shadow;data=null;columns=Lh;features=jh;constructor(){super(),this.shadow=this.attachShadow({mode:"open"})}connectedCallback(){this.render()}setData(e){this.data=e,this.render()}setColumns(e){this.columns=e,this.render()}setFeatures(e){this.features=e,this.render()}priceFor(e){if(!this.data?.data)return null;for(const t of this.data.data)if(e.match.includes(t.planType))return t.planMaster?.basePrice??null;return null}render(){const e=this.columns,t=this.features;this.shadow.innerHTML=`
907
907
  <style>
908
908
  :host {
909
909
  display: block;
@@ -980,4 +980,4 @@ In order to be iterable, non-array objects must have a [Symbol.iterator]() metho
980
980
  <small>Tap to select</small>
981
981
  </button>`}).join("")}
982
982
  </div>
983
- `,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 zr(c){return c.replace(/[&<>"']/g,e=>({"&":"&amp;","<":"&lt;",">":"&gt;",'"':"&quot;","'":"&#39;"})[e])}function Ll(){const c=[["aikaara-chat-widget",ml],["aikaara-chat-bubble",bl],["aikaara-chat-header",yl],["aikaara-message-list",wl],["aikaara-message-bubble",kl],["aikaara-chat-input",Sl],["aikaara-typing-indicator",El],["aikaara-streaming-message",xl],["aikaara-error-banner",Al],["aikaara-template-renderer",Il],["aikaara-system-pill",Tl],["aikaara-option-list",Cl],["aikaara-submit-action",Ol],["aikaara-modal-action",Pl],["aikaara-chat",Ml],["aikaara-link-modal",Rl],["aikaara-compare-plans",jl]];for(const[e,t]of c)customElements.get(e)||customElements.define(e,t)}Ll();function Kr(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 Mh(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 Pr(c){return typeof c=="function"?await c():c}class Nl{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 Pr(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 y=await s.text().catch(()=>"");throw new Error(`Session auth failed: ${s.status} ${y.slice(0,200)}`)}const o=await s.json().catch(()=>({})),l=Kr(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=Kr(o,this.descriptor.requestIdPath??"data.requestId"),b=this.cache?.requestId||p;if(!b)throw new Error("Session auth response missing requestId");const f=Kr(o,this.descriptor.fullNamePath??"data.fullName"),g=Mh(d)||Date.now()+3600*1e3;return this.cache={token:d,requestId:b,fullName:f,expiresAt:g},this.cache}}async function Ul(c){const e={};for(const t of c.spec){const r=await Rh(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 Rh(c,e){const t=c.key??c.name;switch(c.source){case"cookie":return jh(t);case"localStorage":return nr(()=>window.localStorage.getItem(t)??void 0);case"sessionStorage":return nr(()=>window.sessionStorage.getItem(t)??void 0);case"url_param":return nr(()=>new URL(window.location.href).searchParams.get(t)??void 0);case"header_meta":return nr(()=>document.querySelector(`meta[name="${Lh(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 jh(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 nr(c){try{return c()}catch{return}}function Lh(c){return c.replace(/["\\]/g,"\\$&")}const Nh=1800;class Bl{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 Ul({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??Nh;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 Uh=3e4,Bh=2e3,Dh=100;async function Dl(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=Fh(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=$h(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=Kh(typeof t.origins=="string"?t.origins:""),i=typeof t.timeoutMs=="number"&&t.timeoutMs>0?t.timeoutMs:Uh;return{token:await zh({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=Wh(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=qh(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:Bh,n=typeof t.intervalMs=="number"&&t.intervalMs>0?t.intervalMs:Dh,i=await Hh(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 Fl{constructor(e){this.opts=e}cached=null;get descriptor(){return this.opts.descriptor}async get(){if(this.cached)return this.cached;const e=await Dl(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 Fh(c){if(!(typeof window>"u"))try{return new URL(window.location.href).searchParams.get(c)??void 0}catch{return}}function $h(c){if(!(typeof window>"u"))try{const e=window.location.hash.replace(/^#/,"");return new URLSearchParams(e).get(c)??void 0}catch{return}}function Wh(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 qh(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=$l(n,t);return typeof i=="string"?i:void 0}catch{return}}async function Hh(c,e,t){if(typeof window>"u")return;const r=Date.now()+e;for(;Date.now()<r;){const a=$l(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 zh(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 Kh(c){return c?c.split(/[,\s]+/).map(e=>e.trim()).filter(Boolean):[]}function $l(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 Vh(){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 Gh="aikaara_chat:requestId";function uo(c,e){return`${Gh}:${c}:${e}`}function Yh(c,e){try{return localStorage.getItem(uo(c,e))}catch{return null}}function Qh(c,e,t){try{localStorage.setItem(uo(c,e),t)}catch{}}function Jh(c,e){try{localStorage.removeItem(uo(c,e))}catch{}}async function Xh(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 Pr(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 y=o.authHeaderTemplate??"Bearer {token}";d.authorization=y.replace("{token}",n)}const p={method:u,headers:d};o.body&&(d["content-type"]="application/json",p.body=JSON.stringify(a(o.body)));let b=0,f="",g=0;for(;;)try{const y=await fetch(l,p);if(y.ok)break;if(b=y.status,f=await y.text().catch(()=>""),g<i.length&&Zh(b,f)){const m=i[g++];console.warn(`[aikaara-chat-sdk] preflight #${s} ${u} ${l} → ${b} (transient). Retry #${g} in ${m}ms.`),await new Promise(w=>setTimeout(w,m));continue}const k=`Preflight #${s} ${u} ${l} → ${b} ${f.slice(0,200)}`;if(o.soft){console.warn("[aikaara-chat-sdk]",k);break}throw new Error(k)}catch(y){if(g<i.length){const k=i[g++];console.warn(`[aikaara-chat-sdk] preflight #${s} threw, retry #${g} in ${k}ms`,y),await new Promise(m=>setTimeout(m,k));continue}if(o.soft){console.warn(`[aikaara-chat-sdk] preflight #${s} soft-failed:`,y);break}throw y}}}function Zh(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 Wl(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 ef(c,e){return c.replace("{projectId}",e).replace("{uuid}",Vh().replace(/-/g,""))}async function ql(c){const e={...c.config??(c.configUrl?await Wl(c.configUrl,c.configHeaders):{}),...c.overrides??{}},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:Yh(n,a),s=r?.requestIdTemplate??"support-group-{projectId}-{uuid}",o=c.conversationId??i??ef(s,a);(!i||c.forceNewConversation)&&a&&Qh(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,b=c.uploadAdapter??(e.uploadEndpoint?co({endpoint:e.uploadEndpoint,fieldName:e.uploadFieldName,extraFields:e.uploadExtraFields}):void 0),f=c.historyAdapter??(e.historyApiBase?gl({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:b,historyAdapter:f,onError:c.onError,onMessage:c.onMessage},y=document.createElement("aikaara-chat-widget");return y.configure(g),g.title&&y.setAttribute("title",g.title),g.primaryColor&&y.setAttribute("primary-color",g.primaryColor),g.display&&y.setAttribute("display",g.display),g.display==="embed"&&(y.style.cssText="display:flex;flex-direction:column;width:100%;height:100%;min-height:0;"),c.container.appendChild(y),{widget:y,requestId:o,config:g,destroy(){y.remove()}}}function tf(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 Hl(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 Wl(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(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 Fl({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 Bl({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 Xh(a.preflight,{sessionToken:l,userId:i,projectId:a.tiledesk?.projectId??"",slug:c.slug,identity:c.user.identity});const d=new Nl(a.auth,l),p=await d.get(),b=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,y=async()=>`Bearer ${g&&"tokenSource"in g&&g.tokenSource==="chat"?(await d.get()).token:await Pr(c.user.token)}`,k=c.hooks?.upload??(g&&g.mode==="presigned-3step"?pl({...g,authHeader:y}):g&&g.mode==="direct"?co({endpoint:g.endpoint,fieldName:g.fieldName,extraFields:g.extraFields,headers:async()=>({authorization:await y()})}):void 0),m=await ql({container:tf(c.container),config:a,userToken:o||void 0,identity:{userId:i,userName:b,departmentId:c.user.departmentId,senderFullname:b},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:Pr(c.user.token)});return Object.assign(m,{fullName:b,requestId:p.requestId,descriptor:a,async refreshAuth(){d.reset(),await d.get()},async refreshPartnerAuth(){return f?f():null}})}exports.ActionCableClient=Vr;exports.AikaaraChat=Ml;exports.AikaaraChatBubble=bl;exports.AikaaraChatClient=dl;exports.AikaaraChatHeader=yl;exports.AikaaraChatInput=Sl;exports.AikaaraChatWidget=ml;exports.AikaaraComparePlans=jl;exports.AikaaraErrorBanner=Al;exports.AikaaraLinkModal=Rl;exports.AikaaraMessageBubble=kl;exports.AikaaraMessageList=wl;exports.AikaaraModalAction=Pl;exports.AikaaraOptionList=Cl;exports.AikaaraStreamingMessage=xl;exports.AikaaraSubmitAction=Ol;exports.AikaaraSystemPill=Tl;exports.AikaaraTemplateRenderer=Il;exports.AikaaraTypingIndicator=El;exports.ApiClient=Cs;exports.ChannelSubscription=Is;exports.ConnectionManager=Ts;exports.ConversationManager=Ps;exports.EventEmitter=Vi;exports.MessageStore=Os;exports.SessionAuthAdapter=Nl;exports.SsoExchangeAdapter=Bl;exports.TiledeskTransport=cl;exports.TokenDiscoveryError=Ke;exports.TokenDiscoveryReader=Fl;exports.clearPersistedConversationId=Jh;exports.collectSsoCredentials=Ul;exports.createFetchUploadAdapter=co;exports.createPresigned3StepUploadAdapter=pl;exports.createTiledeskHistoryAdapter=gl;exports.discoverToken=Dl;exports.extractTiledeskFileEnvelope=fl;exports.inferTiledeskRole=hl;exports.isTiledeskSelfEcho=ul;exports.mount=ql;exports.mountFromSlug=Hl;exports.parseTiledeskTemplate=lo;exports.registerComponents=Ll;
983
+ `,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 zr(c){return c.replace(/[&<>"']/g,e=>({"&":"&amp;","<":"&lt;",">":"&gt;",'"':"&quot;","'":"&#39;"})[e])}function Ul(){const c=[["aikaara-chat-widget",bl],["aikaara-chat-bubble",yl],["aikaara-chat-header",vl],["aikaara-message-list",_l],["aikaara-message-bubble",Sl],["aikaara-chat-input",El],["aikaara-typing-indicator",xl],["aikaara-streaming-message",Al],["aikaara-error-banner",Il],["aikaara-template-renderer",Cl],["aikaara-system-pill",Ol],["aikaara-option-list",Pl],["aikaara-submit-action",Ml],["aikaara-modal-action",Rl],["aikaara-chat",jl],["aikaara-link-modal",Ll],["aikaara-compare-plans",Nl]];for(const[e,t]of c)customElements.get(e)||customElements.define(e,t)}Ul();function Kr(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 Nh(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 Pr(c){return typeof c=="function"?await c():c}class Bl{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 Pr(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=Kr(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=Kr(o,this.descriptor.requestIdPath??"data.requestId"),y=this.cache?.requestId||p;if(!y)throw new Error("Session auth response missing requestId");const f=Kr(o,this.descriptor.fullNamePath??"data.fullName"),g=Nh(d)||Date.now()+3600*1e3;return this.cache={token:d,requestId:y,fullName:f,expiresAt:g},this.cache}}async function Dl(c){const e={};for(const t of c.spec){const r=await Uh(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 Uh(c,e){const t=c.key??c.name;switch(c.source){case"cookie":return Bh(t);case"localStorage":return nr(()=>window.localStorage.getItem(t)??void 0);case"sessionStorage":return nr(()=>window.sessionStorage.getItem(t)??void 0);case"url_param":return nr(()=>new URL(window.location.href).searchParams.get(t)??void 0);case"header_meta":return nr(()=>document.querySelector(`meta[name="${Dh(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 Bh(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 nr(c){try{return c()}catch{return}}function Dh(c){return c.replace(/["\\]/g,"\\$&")}const Fh=1800;class Fl{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 Dl({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??Fh;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 $h=3e4,Wh=2e3,qh=100;async function $l(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=Hh(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=Qh(typeof t.origins=="string"?t.origins:""),i=typeof t.timeoutMs=="number"&&t.timeoutMs>0?t.timeoutMs:$h;return{token:await Yh({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=Kh(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=Vh(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:Wh,n=typeof t.intervalMs=="number"&&t.intervalMs>0?t.intervalMs:qh,i=await Gh(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 Wl{constructor(e){this.opts=e}cached=null;get descriptor(){return this.opts.descriptor}async get(){if(this.cached)return this.cached;const e=await $l(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 Hh(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 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 Vh(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=ql(n,t);return typeof i=="string"?i:void 0}catch{return}}async function Gh(c,e,t){if(typeof window>"u")return;const r=Date.now()+e;for(;Date.now()<r;){const a=ql(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 Yh(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 Qh(c){return c?c.split(/[,\s]+/).map(e=>e.trim()).filter(Boolean):[]}function ql(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 Jh(){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 Xh="aikaara_chat:requestId";function uo(c,e){return`${Xh}:${c}:${e}`}function Zh(c,e){try{return localStorage.getItem(uo(c,e))}catch{return null}}function ef(c,e,t){try{localStorage.setItem(uo(c,e),t)}catch{}}function tf(c,e){try{localStorage.removeItem(uo(c,e))}catch{}}async function rf(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 Pr(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&&nf(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 nf(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 Hl(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 of(c,e){return c.replace("{projectId}",e).replace("{uuid}",Jh().replace(/-/g,""))}function zl(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=>Tl(r)))}async function Kl(c){const e={...c.config??(c.configUrl?await Hl(c.configUrl,c.configHeaders):{}),...c.overrides??{}};zl(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:Zh(n,a),s=r?.requestIdTemplate??"support-group-{projectId}-{uuid}",o=c.conversationId??i??of(s,a);(!i||c.forceNewConversation)&&a&&ef(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?co({endpoint:e.uploadEndpoint,fieldName:e.uploadFieldName,extraFields:e.uploadExtraFields}):void 0),f=c.historyAdapter??(e.historyApiBase?ml({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 sf(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 Vl(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 Hl(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(zl(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 Wl({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 Fl({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 rf(a.preflight,{sessionToken:l,userId:i,projectId:a.tiledesk?.projectId??"",slug:c.slug,identity:c.user.identity});const d=new Bl(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 Pr(c.user.token)}`,k=c.hooks?.upload??(g&&g.mode==="presigned-3step"?gl({...g,authHeader:b}):g&&g.mode==="direct"?co({endpoint:g.endpoint,fieldName:g.fieldName,extraFields:g.extraFields,headers:async()=>({authorization:await b()})}):void 0),m=await Kl({container:sf(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:Pr(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}})}exports.ActionCableClient=Vr;exports.AikaaraChat=jl;exports.AikaaraChatBubble=yl;exports.AikaaraChatClient=pl;exports.AikaaraChatHeader=vl;exports.AikaaraChatInput=El;exports.AikaaraChatWidget=bl;exports.AikaaraComparePlans=Nl;exports.AikaaraErrorBanner=Il;exports.AikaaraLinkModal=Ll;exports.AikaaraMessageBubble=Sl;exports.AikaaraMessageList=_l;exports.AikaaraModalAction=Rl;exports.AikaaraOptionList=Pl;exports.AikaaraStreamingMessage=Al;exports.AikaaraSubmitAction=Ml;exports.AikaaraSystemPill=Ol;exports.AikaaraTemplateRenderer=Cl;exports.AikaaraTypingIndicator=xl;exports.ApiClient=Os;exports.ChannelSubscription=Ts;exports.ConnectionManager=Cs;exports.ConversationManager=Ms;exports.EventEmitter=Vi;exports.MessageStore=Ps;exports.SessionAuthAdapter=Bl;exports.SsoExchangeAdapter=Fl;exports.TiledeskTransport=ul;exports.TokenDiscoveryError=Ke;exports.TokenDiscoveryReader=Wl;exports.clearPersistedConversationId=tf;exports.collectSsoCredentials=Dl;exports.createFetchUploadAdapter=co;exports.createPresigned3StepUploadAdapter=gl;exports.createTiledeskHistoryAdapter=ml;exports.discoverToken=$l;exports.extractTiledeskFileEnvelope=dl;exports.inferTiledeskRole=fl;exports.isTiledeskSelfEcho=hl;exports.mount=Kl;exports.mountFromSlug=Vl;exports.parseTiledeskTemplate=lo;exports.registerComponents=Ul;