@aikaara/chat-sdk 1.1.9 → 1.1.10

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,11 +1,11 @@
1
- var AikaaraChat=(function(Ce){"use strict";class ko{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 Gr{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 ko(t,s=>{this.send({command:"message",identifier:t,data:JSON.stringify(s)})});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((s,n)=>{this.pendingSubscriptions.set(r,{resolve:()=>s(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 ir{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(s){console.error(`Error in event handler for "${e}":`,s)}})}removeAllListeners(){this.handlers.clear()}}const uc=1e3,hc=10,dc=400,fc=600,xo="#6366f1",pc=12,mc="system-ui, -apple-system, sans-serif",So="Type a message...",gc="bottom-right",bc="light",yc={x:20,y:20},Kr="aikaara_conversation_id";class Eo extends ir{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 Gr(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,s){const n=JSON.stringify({channel:"ConversationChannel",conversation_id:e});this.client.perform(n,"send_user_event",{event_key:t,...r&&{value:r},...s&&{source:s}})}get connectionState(){return this.state}setState(e){this.state!==e&&(this.state=e,this.emit("connection:state",e))}scheduleReconnect(){const e=this.config.maxReconnectAttempts??hc;if(this.reconnectAttempt>=e){this.emit("error",new Error("Max reconnection attempts reached"));return}this.setState("reconnecting");const r=(this.config.reconnectInterval??uc)*Math.pow(2,this.reconnectAttempt);this.reconnectAttempt++,this.reconnectTimer=setTimeout(async()=>{try{const s=this.buildWsUrl(this.config.baseUrl,this.config.userToken);this.client=new Gr(s),await this.connect()}catch{}},r)}clearReconnectTimer(){this.reconnectTimer&&(clearTimeout(this.reconnectTimer),this.reconnectTimer=null)}buildWsUrl(e,t){if(this.config.wsUrl){const s=this.config.wsUrl.includes("?")?"&":"?";return`${this.config.wsUrl}${s}token=${t}`}return`${e.replace(/^http/,"ws")}/cable?token=${t}`}}class Ao{baseUrl;apiKey;authToken;userToken;refreshHook=null;constructor(e,t,r,s){this.baseUrl=e,this.userToken=t,this.apiKey=r,this.authToken=s}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 s=`${this.baseUrl}${t}`;let n=await this.fetchWithHeaders(s,e,r);if(n.status===401&&this.refreshHook){let o=null;try{o=await this.refreshHook()}catch(a){console.warn("[aikaara-chat-sdk] auth refresh hook threw",a)}o&&(this.authToken=o,n=await this.fetchWithHeaders(s,e,r))}if(!n.ok){const o=await n.text();let a;try{const c=JSON.parse(o);a=c.error||c.message||o}catch{a=o}throw new Error(`API error ${n.status}: ${a}`)}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 s={"Content-Type":"application/json",Accept:"application/json"};this.apiKey&&(s["X-Api-Key"]=this.apiKey),this.authToken&&(s.Authorization=`Bearer ${this.authToken}`);const n={method:t,headers:s};return r&&(n.body=JSON.stringify(r)),fetch(e,n)}}class Io{_messages=[];optimisticCounter=0;get messages(){return[...this._messages]}addOptimistic(e,t,r){const s={id:`optimistic_${++this.optimisticCounter}`,conversationId:r,role:e,content:t,createdAt:new Date().toISOString(),status:"sending"};return this._messages.push(s),s}reconcileOptimistic(e,t=3e4){const r=this._messages.findLast(s=>s.status==="sending"&&s.role===e.role&&s.content===e.content&&s.conversationId===e.conversationId&&Date.now()-new Date(s.createdAt).getTime()<t);return r?(r.status=e.status??"sent",r.externalId=e.externalId??e.id,e.template&&(r.template=e.template),e.attachments&&(r.attachments=e.attachments),e.metadata&&(r.metadata={...r.metadata??{},...e.metadata}),r):null}upsertRemoteMessage(e){const t=this.reconcileOptimistic(e);if(t)return{message:t,deduped:!0};const r=e.externalId?this._messages.find(n=>n.externalId&&n.externalId===e.externalId):void 0;if(r)return Object.assign(r,e,{id:r.id}),{message:r,deduped:!0};const s=To(this._messages,e);return s?(Object.assign(s,e,{id:s.id}),{message:s,deduped:!0}):(this._messages.push(e),{message:e,deduped:!1})}updateMessageStatus(e,t){const r=this._messages.find(s=>s.externalId===e||s.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){const t=[];for(const r of e){const s=To(t,r);if(s){const n=or(s),i=or(r);!n&&i&&Object.assign(s,r,{id:s.id});continue}t.push({...r})}this._messages=t}clear(){this._messages=[]}}function To(l,e,t=15e3){const r=e.attachments&&e.attachments[0],s=(e.metadata??{}).attributes;if(!(!!r||!!(s&&s.fileMessage)))return null;const i=or(e),o=Co(e),a=Oo(e);if(!i&&!o&&!a)return null;const c=new Date(e.createdAt).getTime();for(let u=l.length-1;u>=0;u--){const h=l[u],p=h.attachments&&h.attachments[0],b=(h.metadata??{}).attributes;if(!(!!p||!!(b&&b.fileMessage)))continue;const g=(h.content||"").trim().toLowerCase();if(g==="file_uploaded"||g==="file_upload"||Math.abs(c-new Date(h.createdAt).getTime())>t)continue;const y=or(h);if(i&&y&&i===y)return h;const k=Co(h);if(o&&k&&o===k)return h;const m=Oo(h);if(a&&m&&a===m)return h}return null}function Co(l){const e=l.attachments&&l.attachments[0];if(e&&typeof e.fileUrl=="string")return e.fileUrl;const t=Po(l);if(t)return t}function Oo(l){const e=l.attachments&&l.attachments[0];if(e&&typeof e.fileName=="string")return e.fileName;const t=(l.metadata??{}).attributes;if(t&&typeof t.fileName=="string")return t.fileName;const n=l.template?.payload?.elements?.[0]?.description;if(typeof n=="string"&&n)return n}function or(l){const e=l.attachments&&l.attachments[0];if(e&&typeof e.cloudFileId=="string")return e.cloudFileId;const t=(l.metadata??{}).attributes;if(t&&typeof t.cloudFileId=="string")return t.cloudFileId;const r=Po(l);if(r){const s=/[?&]cloudFileId=([^&]+)/.exec(r);if(s)return decodeURIComponent(s[1])}}function Po(l){const e=l.template;if(e?.templateId!=="7")return;const r=e.payload?.elements?.[0]?.action?.url;return typeof r=="string"?r:void 0}class Mo{_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(Kr)}catch{}}loadFromStorage(){if(!this.persist)return null;try{return localStorage.getItem(Kr)}catch{return null}}saveToStorage(e){try{localStorage.setItem(Kr,e)}catch{}}}var Yr=Object.defineProperty,vc=Object.getOwnPropertyDescriptor,wc=Object.getOwnPropertyNames,_c=Object.prototype.hasOwnProperty,Ve=(l,e)=>()=>(l&&(e=l(l=0)),e),pe=(l,e)=>()=>(e||l((e={exports:{}}).exports,e),e.exports),Rt=(l,e)=>{for(var t in e)Yr(l,t,{get:e[t],enumerable:!0})},kc=(l,e,t,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let s of wc(e))!_c.call(l,s)&&s!==t&&Yr(l,s,{get:()=>e[s],enumerable:!(r=vc(e,s))||r.enumerable});return l},Me=l=>kc(Yr({},"__esModule",{value:!0}),l),le=Ve(()=>{}),Le={};Rt(Le,{_debugEnd:()=>Pn,_debugProcess:()=>On,_events:()=>Gn,_eventsCount:()=>Kn,_exiting:()=>gn,_fatalExceptions:()=>In,_getActiveHandles:()=>Do,_getActiveRequests:()=>Bo,_kill:()=>vn,_linkedBinding:()=>No,_maxListeners:()=>Vn,_preload_modules:()=>Hn,_rawDebug:()=>fn,_startProfilerIdleNotifier:()=>Mn,_stopProfilerIdleNotifier:()=>Rn,_tickCallback:()=>Cn,abort:()=>Un,addListener:()=>Yn,allowedNodeEnvironmentFlags:()=>En,arch:()=>Xr,argv:()=>tn,argv0:()=>qn,assert:()=>Fo,binding:()=>an,browser:()=>dn,chdir:()=>un,config:()=>bn,cpuUsage:()=>zt,cwd:()=>cn,debugPort:()=>$n,default:()=>ni,dlopen:()=>Uo,domain:()=>mn,emit:()=>ei,emitWarning:()=>sn,env:()=>en,execArgv:()=>rn,execPath:()=>Fn,exit:()=>xn,features:()=>An,hasUncaughtExceptionCaptureCallback:()=>$o,hrtime:()=>sr,kill:()=>kn,listeners:()=>Ho,memoryUsage:()=>_n,moduleLoadList:()=>pn,nextTick:()=>Lo,off:()=>Jn,on:()=>st,once:()=>Qn,openStdin:()=>Sn,pid:()=>Bn,platform:()=>Zr,ppid:()=>Dn,prependListener:()=>ti,prependOnceListener:()=>ri,reallyExit:()=>yn,release:()=>hn,removeAllListeners:()=>Zn,removeListener:()=>Xn,resourceUsage:()=>wn,setSourceMapsEnabled:()=>Wn,setUncaughtExceptionCaptureCallback:()=>Tn,stderr:()=>jn,stdin:()=>Nn,stdout:()=>Ln,title:()=>Jr,umask:()=>ln,uptime:()=>qo,version:()=>nn,versions:()=>on});function Qr(l){throw new Error("Node.js process "+l+" is not supported by JSPM core outside of Node.js")}function xc(){!xt||!St||(xt=!1,St.length?Xe=St.concat(Xe):Wt=-1,Xe.length&&Ro())}function Ro(){if(!xt){var l=setTimeout(xc,0);xt=!0;for(var e=Xe.length;e;){for(St=Xe,Xe=[];++Wt<e;)St&&St[Wt].run();Wt=-1,e=Xe.length}St=null,xt=!1,clearTimeout(l)}}function Lo(l){var e=new Array(arguments.length-1);if(arguments.length>1)for(var t=1;t<arguments.length;t++)e[t-1]=arguments[t];Xe.push(new jo(l,e)),Xe.length===1&&!xt&&setTimeout(Ro,0)}function jo(l,e){this.fun=l,this.array=e}function Fe(){}function No(l){Qr("_linkedBinding")}function Uo(l){Qr("dlopen")}function Bo(){return[]}function Do(){return[]}function Fo(l,e){if(!l)throw new Error(e||"assertion error")}function $o(){return!1}function qo(){return at.now()/1e3}function sr(l){var e=Math.floor((Date.now()-at.now())*.001),t=at.now()*.001,r=Math.floor(t)+e,s=Math.floor(t%1*1e9);return l&&(r=r-l[0],s=s-l[1],s<0&&(r--,s+=ar)),[r,s]}function st(){return ni}function Ho(l){return[]}var Xe,xt,St,Wt,Jr,Xr,Zr,en,tn,rn,nn,on,sn,an,ln,cn,un,hn,dn,fn,pn,mn,gn,bn,yn,vn,zt,wn,_n,kn,xn,Sn,En,An,In,Tn,Cn,On,Pn,Mn,Rn,Ln,jn,Nn,Un,Bn,Dn,Fn,$n,qn,Hn,Wn,at,zn,ar,Vn,Gn,Kn,Yn,Qn,Jn,Xn,Zn,ei,ti,ri,ni,Sc=Ve(()=>{le(),ue(),ce(),Xe=[],xt=!1,Wt=-1,jo.prototype.run=function(){this.fun.apply(null,this.array)},Jr="browser",Xr="x64",Zr="browser",en={PATH:"/usr/bin",LANG:typeof navigator<"u"?navigator.language+".UTF-8":void 0,PWD:"/",HOME:"/home",TMP:"/tmp"},tn=["/usr/bin/node"],rn=[],nn="v16.8.0",on={},sn=function(l,e){console.warn((e?e+": ":"")+l)},an=function(l){Qr("binding")},ln=function(l){return 0},cn=function(){return"/"},un=function(l){},hn={name:"node",sourceUrl:"",headersUrl:"",libUrl:""},dn=!0,fn=Fe,pn=[],mn={},gn=!1,bn={},yn=Fe,vn=Fe,zt=function(){return{}},wn=zt,_n=zt,kn=Fe,xn=Fe,Sn=Fe,En={},An={inspector:!1,debug:!1,uv:!1,ipv6:!1,tls_alpn:!1,tls_sni:!1,tls_ocsp:!1,tls:!1,cached_builtins:!0},In=Fe,Tn=Fe,Cn=Fe,On=Fe,Pn=Fe,Mn=Fe,Rn=Fe,Ln=void 0,jn=void 0,Nn=void 0,Un=Fe,Bn=2,Dn=1,Fn="/bin/usr/node",$n=9229,qn="node",Hn=[],Wn=Fe,at={now:typeof performance<"u"?performance.now.bind(performance):void 0,timing:typeof performance<"u"?performance.timing:void 0},at.now===void 0&&(zn=Date.now(),at.timing&&at.timing.navigationStart&&(zn=at.timing.navigationStart),at.now=()=>Date.now()-zn),ar=1e9,sr.bigint=function(l){var e=sr(l);return typeof BigInt>"u"?e[0]*ar+e[1]:BigInt(e[0]*ar)+BigInt(e[1])},Vn=10,Gn={},Kn=0,Yn=st,Qn=st,Jn=st,Xn=st,Zn=st,ei=Fe,ti=st,ri=st,ni={version:nn,versions:on,arch:Xr,platform:Zr,browser:dn,release:hn,_rawDebug:fn,moduleLoadList:pn,binding:an,_linkedBinding:No,_events:Gn,_eventsCount:Kn,_maxListeners:Vn,on:st,addListener:Yn,once:Qn,off:Jn,removeListener:Xn,removeAllListeners:Zn,emit:ei,prependListener:ti,prependOnceListener:ri,listeners:Ho,domain:mn,_exiting:gn,config:bn,dlopen:Uo,uptime:qo,_getActiveRequests:Bo,_getActiveHandles:Do,reallyExit:yn,_kill:vn,cpuUsage:zt,resourceUsage:wn,memoryUsage:_n,kill:kn,exit:xn,openStdin:Sn,allowedNodeEnvironmentFlags:En,assert:Fo,features:An,_fatalExceptions:In,setUncaughtExceptionCaptureCallback:Tn,hasUncaughtExceptionCaptureCallback:$o,emitWarning:sn,nextTick:Lo,_tickCallback:Cn,_debugProcess:On,_debugEnd:Pn,_startProfilerIdleNotifier:Mn,_stopProfilerIdleNotifier:Rn,stdout:Ln,stdin:Nn,stderr:jn,abort:Un,umask:ln,chdir:un,cwd:cn,env:en,title:Jr,argv:tn,execArgv:rn,pid:Bn,ppid:Dn,execPath:Fn,debugPort:$n,hrtime:sr,argv0:qn,_preload_modules:Hn,setSourceMapsEnabled:Wn}}),ce=Ve(()=>{Sc()});function Ec(){if(ii)return Lt;ii=!0,Lt.byteLength=o,Lt.toByteArray=c,Lt.fromByteArray=p;for(var l=[],e=[],t=typeof Uint8Array<"u"?Uint8Array:Array,r="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",s=0,n=r.length;s<n;++s)l[s]=r[s],e[r.charCodeAt(s)]=s;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 o(b){var f=i(b),g=f[0],y=f[1];return(g+y)*3/4-y}function a(b,f,g){return(f+g)*3/4-g}function c(b){var f,g=i(b),y=g[0],k=g[1],m=new t(a(b,y,k)),w=0,S=k>0?y-4:y,v;for(v=0;v<S;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 l[b>>18&63]+l[b>>12&63]+l[b>>6&63]+l[b&63]}function h(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,S=g-y;w<S;w+=m)k.push(h(b,w,w+m>S?S:w+m));return y===1?(f=b[g-1],k.push(l[f>>2]+l[f<<4&63]+"==")):y===2&&(f=(b[g-2]<<8)+b[g-1],k.push(l[f>>10]+l[f>>4&63]+l[f<<2&63]+"=")),k.join("")}return Lt}function Ac(){return oi?Vt:(oi=!0,Vt.read=function(l,e,t,r,s){var n,i,o=s*8-r-1,a=(1<<o)-1,c=a>>1,u=-7,h=t?s-1:0,p=t?-1:1,b=l[e+h];for(h+=p,n=b&(1<<-u)-1,b>>=-u,u+=o;u>0;n=n*256+l[e+h],h+=p,u-=8);for(i=n&(1<<-u)-1,n>>=-u,u+=r;u>0;i=i*256+l[e+h],h+=p,u-=8);if(n===0)n=1-c;else{if(n===a)return i?NaN:(b?-1:1)*(1/0);i=i+Math.pow(2,r),n=n-c}return(b?-1:1)*i*Math.pow(2,n-r)},Vt.write=function(l,e,t,r,s,n){var i,o,a,c=n*8-s-1,u=(1<<c)-1,h=u>>1,p=s===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?(o=isNaN(e)?1:0,i=u):(i=Math.floor(Math.log(e)/Math.LN2),e*(a=Math.pow(2,-i))<1&&(i--,a*=2),i+h>=1?e+=p/a:e+=p*Math.pow(2,1-h),e*a>=2&&(i++,a/=2),i+h>=u?(o=0,i=u):i+h>=1?(o=(e*a-1)*Math.pow(2,s),i=i+h):(o=e*Math.pow(2,h-1)*Math.pow(2,s),i=0));s>=8;l[t+b]=o&255,b+=f,o/=256,s-=8);for(i=i<<s|o,c+=s;c>0;l[t+b]=i&255,b+=f,i/=256,c-=8);l[t+b-f]|=g*128},Vt)}function Ic(){if(si)return gt;si=!0;let l=Ec(),e=Ac(),t=typeof Symbol=="function"&&typeof Symbol.for=="function"?Symbol.for("nodejs.util.inspect.custom"):null;gt.Buffer=i,gt.SlowBuffer=k,gt.INSPECT_MAX_BYTES=50;let r=2147483647;gt.kMaxLength=r,i.TYPED_ARRAY_SUPPORT=s(),!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 s(){try{let d=new Uint8Array(1),_={foo:function(){return 42}};return Object.setPrototypeOf(_,Uint8Array.prototype),Object.setPrototypeOf(d,_),d.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(d){if(d>r)throw new RangeError('The value "'+d+'" is invalid for option "size"');let _=new Uint8Array(d);return Object.setPrototypeOf(_,i.prototype),_}function i(d,_,A){if(typeof d=="number"){if(typeof _=="string")throw new TypeError('The "string" argument must be of type string. Received type number');return u(d)}return o(d,_,A)}i.poolSize=8192;function o(d,_,A){if(typeof d=="string")return h(d,_);if(ArrayBuffer.isView(d))return b(d);if(d==null)throw new TypeError("The first argument must be one of type string, Buffer, ArrayBuffer, Array, or Array-like Object. Received type "+typeof d);if(H(d,ArrayBuffer)||d&&H(d.buffer,ArrayBuffer)||typeof SharedArrayBuffer<"u"&&(H(d,SharedArrayBuffer)||d&&H(d.buffer,SharedArrayBuffer)))return f(d,_,A);if(typeof d=="number")throw new TypeError('The "value" argument must not be of type number. Received type number');let U=d.valueOf&&d.valueOf();if(U!=null&&U!==d)return i.from(U,_,A);let X=g(d);if(X)return X;if(typeof Symbol<"u"&&Symbol.toPrimitive!=null&&typeof d[Symbol.toPrimitive]=="function")return i.from(d[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 d)}i.from=function(d,_,A){return o(d,_,A)},Object.setPrototypeOf(i.prototype,Uint8Array.prototype),Object.setPrototypeOf(i,Uint8Array);function a(d){if(typeof d!="number")throw new TypeError('"size" argument must be of type number');if(d<0)throw new RangeError('The value "'+d+'" is invalid for option "size"')}function c(d,_,A){return a(d),d<=0?n(d):_!==void 0?typeof A=="string"?n(d).fill(_,A):n(d).fill(_):n(d)}i.alloc=function(d,_,A){return c(d,_,A)};function u(d){return a(d),n(d<0?0:y(d)|0)}i.allocUnsafe=function(d){return u(d)},i.allocUnsafeSlow=function(d){return u(d)};function h(d,_){if((typeof _!="string"||_==="")&&(_="utf8"),!i.isEncoding(_))throw new TypeError("Unknown encoding: "+_);let A=m(d,_)|0,U=n(A),X=U.write(d,_);return X!==A&&(U=U.slice(0,X)),U}function p(d){let _=d.length<0?0:y(d.length)|0,A=n(_);for(let U=0;U<_;U+=1)A[U]=d[U]&255;return A}function b(d){if(H(d,Uint8Array)){let _=new Uint8Array(d);return f(_.buffer,_.byteOffset,_.byteLength)}return p(d)}function f(d,_,A){if(_<0||d.byteLength<_)throw new RangeError('"offset" is outside of buffer bounds');if(d.byteLength<_+(A||0))throw new RangeError('"length" is outside of buffer bounds');let U;return _===void 0&&A===void 0?U=new Uint8Array(d):A===void 0?U=new Uint8Array(d,_):U=new Uint8Array(d,_,A),Object.setPrototypeOf(U,i.prototype),U}function g(d){if(i.isBuffer(d)){let _=y(d.length)|0,A=n(_);return A.length===0||d.copy(A,0,0,_),A}if(d.length!==void 0)return typeof d.length!="number"||me(d.length)?n(0):p(d);if(d.type==="Buffer"&&Array.isArray(d.data))return p(d.data)}function y(d){if(d>=r)throw new RangeError("Attempt to allocate Buffer larger than maximum size: 0x"+r.toString(16)+" bytes");return d|0}function k(d){return+d!=d&&(d=0),i.alloc(+d)}i.isBuffer=function(d){return d!=null&&d._isBuffer===!0&&d!==i.prototype},i.compare=function(d,_){if(H(d,Uint8Array)&&(d=i.from(d,d.offset,d.byteLength)),H(_,Uint8Array)&&(_=i.from(_,_.offset,_.byteLength)),!i.isBuffer(d)||!i.isBuffer(_))throw new TypeError('The "buf1", "buf2" arguments must be one of type Buffer or Uint8Array');if(d===_)return 0;let A=d.length,U=_.length;for(let X=0,he=Math.min(A,U);X<he;++X)if(d[X]!==_[X]){A=d[X],U=_[X];break}return A<U?-1:U<A?1:0},i.isEncoding=function(d){switch(String(d).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(d,_){if(!Array.isArray(d))throw new TypeError('"list" argument must be an Array of Buffers');if(d.length===0)return i.alloc(0);let A;if(_===void 0)for(_=0,A=0;A<d.length;++A)_+=d[A].length;let U=i.allocUnsafe(_),X=0;for(A=0;A<d.length;++A){let he=d[A];if(H(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(d,_){if(i.isBuffer(d))return d.length;if(ArrayBuffer.isView(d)||H(d,ArrayBuffer))return d.byteLength;if(typeof d!="string")throw new TypeError('The "string" argument must be one of type string, Buffer, or ArrayBuffer. Received type '+typeof d);let A=d.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 $(d).length;case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return A*2;case"hex":return A>>>1;case"base64":return fe(d).length;default:if(X)return U?-1:$(d).length;_=(""+_).toLowerCase(),X=!0}}i.byteLength=m;function w(d,_,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(d||(d="utf8");;)switch(d){case"hex":return V(this,_,A);case"utf8":case"utf-8":return q(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: "+d);d=(d+"").toLowerCase(),U=!0}}i.prototype._isBuffer=!0;function S(d,_,A){let U=d[_];d[_]=d[A],d[A]=U}i.prototype.swap16=function(){let d=this.length;if(d%2!==0)throw new RangeError("Buffer size must be a multiple of 16-bits");for(let _=0;_<d;_+=2)S(this,_,_+1);return this},i.prototype.swap32=function(){let d=this.length;if(d%4!==0)throw new RangeError("Buffer size must be a multiple of 32-bits");for(let _=0;_<d;_+=4)S(this,_,_+3),S(this,_+1,_+2);return this},i.prototype.swap64=function(){let d=this.length;if(d%8!==0)throw new RangeError("Buffer size must be a multiple of 64-bits");for(let _=0;_<d;_+=8)S(this,_,_+7),S(this,_+1,_+6),S(this,_+2,_+5),S(this,_+3,_+4);return this},i.prototype.toString=function(){let d=this.length;return d===0?"":arguments.length===0?q(this,0,d):w.apply(this,arguments)},i.prototype.toLocaleString=i.prototype.toString,i.prototype.equals=function(d){if(!i.isBuffer(d))throw new TypeError("Argument must be a Buffer");return this===d?!0:i.compare(this,d)===0},i.prototype.inspect=function(){let d="",_=gt.INSPECT_MAX_BYTES;return d=this.toString("hex",0,_).replace(/(.{2})/g,"$1 ").trim(),this.length>_&&(d+=" ... "),"<Buffer "+d+">"},t&&(i.prototype[t]=i.prototype.inspect),i.prototype.compare=function(d,_,A,U,X){if(H(d,Uint8Array)&&(d=i.from(d,d.offset,d.byteLength)),!i.isBuffer(d))throw new TypeError('The "target" argument must be one of type Buffer or Uint8Array. Received type '+typeof d);if(_===void 0&&(_=0),A===void 0&&(A=d?d.length:0),U===void 0&&(U=0),X===void 0&&(X=this.length),_<0||A>d.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===d)return 0;let he=X-U,ke=A-_,z=Math.min(he,ke),ie=this.slice(U,X),Ee=d.slice(_,A);for(let Ae=0;Ae<z;++Ae)if(ie[Ae]!==Ee[Ae]){he=ie[Ae],ke=Ee[Ae];break}return he<ke?-1:ke<he?1:0};function v(d,_,A,U,X){if(d.length===0)return-1;if(typeof A=="string"?(U=A,A=0):A>2147483647?A=2147483647:A<-2147483648&&(A=-2147483648),A=+A,me(A)&&(A=X?0:d.length-1),A<0&&(A=d.length+A),A>=d.length){if(X)return-1;A=d.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:E(d,_,A,U,X);if(typeof _=="number")return _=_&255,typeof Uint8Array.prototype.indexOf=="function"?X?Uint8Array.prototype.indexOf.call(d,_,A):Uint8Array.prototype.lastIndexOf.call(d,_,A):E(d,[_],A,U,X);throw new TypeError("val must be string, number or Buffer")}function E(d,_,A,U,X){let he=1,ke=d.length,z=_.length;if(U!==void 0&&(U=String(U).toLowerCase(),U==="ucs2"||U==="ucs-2"||U==="utf16le"||U==="utf-16le")){if(d.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 Ee;if(X){let Ae=-1;for(Ee=A;Ee<ke;Ee++)if(ie(d,Ee)===ie(_,Ae===-1?0:Ee-Ae)){if(Ae===-1&&(Ae=Ee),Ee-Ae+1===z)return Ae*he}else Ae!==-1&&(Ee-=Ee-Ae),Ae=-1}else for(A+z>ke&&(A=ke-z),Ee=A;Ee>=0;Ee--){let Ae=!0;for(let Ie=0;Ie<z;Ie++)if(ie(d,Ee+Ie)!==ie(_,Ie)){Ae=!1;break}if(Ae)return Ee}return-1}i.prototype.includes=function(d,_,A){return this.indexOf(d,_,A)!==-1},i.prototype.indexOf=function(d,_,A){return v(this,d,_,A,!0)},i.prototype.lastIndexOf=function(d,_,A){return v(this,d,_,A,!1)};function x(d,_,A,U){A=Number(A)||0;let X=d.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(me(z))return ke;d[A+ke]=z}return ke}function I(d,_,A,U){return ye($(_,d.length-A),d,A,U)}function P(d,_,A,U){return ye(ee(_),d,A,U)}function O(d,_,A,U){return ye(fe(_),d,A,U)}function B(d,_,A,U){return ye(de(_,d.length-A),d,A,U)}i.prototype.write=function(d,_,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),d.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 x(this,d,_,A);case"utf8":case"utf-8":return I(this,d,_,A);case"ascii":case"latin1":case"binary":return P(this,d,_,A);case"base64":return O(this,d,_,A);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return B(this,d,_,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(d,_,A){return _===0&&A===d.length?l.fromByteArray(d):l.fromByteArray(d.slice(_,A))}function q(d,_,A){A=Math.min(d.length,A);let U=[],X=_;for(;X<A;){let he=d[X],ke=null,z=he>239?4:he>223?3:he>191?2:1;if(X+z<=A){let ie,Ee,Ae,Ie;switch(z){case 1:he<128&&(ke=he);break;case 2:ie=d[X+1],(ie&192)===128&&(Ie=(he&31)<<6|ie&63,Ie>127&&(ke=Ie));break;case 3:ie=d[X+1],Ee=d[X+2],(ie&192)===128&&(Ee&192)===128&&(Ie=(he&15)<<12|(ie&63)<<6|Ee&63,Ie>2047&&(Ie<55296||Ie>57343)&&(ke=Ie));break;case 4:ie=d[X+1],Ee=d[X+2],Ae=d[X+3],(ie&192)===128&&(Ee&192)===128&&(Ae&192)===128&&(Ie=(he&15)<<18|(ie&63)<<12|(Ee&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(d){let _=d.length;if(_<=D)return String.fromCharCode.apply(String,d);let A="",U=0;for(;U<_;)A+=String.fromCharCode.apply(String,d.slice(U,U+=D));return A}function ae(d,_,A){let U="";A=Math.min(d.length,A);for(let X=_;X<A;++X)U+=String.fromCharCode(d[X]&127);return U}function Y(d,_,A){let U="";A=Math.min(d.length,A);for(let X=_;X<A;++X)U+=String.fromCharCode(d[X]);return U}function V(d,_,A){let U=d.length;(!_||_<0)&&(_=0),(!A||A<0||A>U)&&(A=U);let X="";for(let he=_;he<A;++he)X+=ve[d[he]];return X}function re(d,_,A){let U=d.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(d,_){let A=this.length;d=~~d,_=_===void 0?A:~~_,d<0?(d+=A,d<0&&(d=0)):d>A&&(d=A),_<0?(_+=A,_<0&&(_=0)):_>A&&(_=A),_<d&&(_=d);let U=this.subarray(d,_);return Object.setPrototypeOf(U,i.prototype),U};function F(d,_,A){if(d%1!==0||d<0)throw new RangeError("offset is not uint");if(d+_>A)throw new RangeError("Trying to access beyond buffer length")}i.prototype.readUintLE=i.prototype.readUIntLE=function(d,_,A){d=d>>>0,_=_>>>0,A||F(d,_,this.length);let U=this[d],X=1,he=0;for(;++he<_&&(X*=256);)U+=this[d+he]*X;return U},i.prototype.readUintBE=i.prototype.readUIntBE=function(d,_,A){d=d>>>0,_=_>>>0,A||F(d,_,this.length);let U=this[d+--_],X=1;for(;_>0&&(X*=256);)U+=this[d+--_]*X;return U},i.prototype.readUint8=i.prototype.readUInt8=function(d,_){return d=d>>>0,_||F(d,1,this.length),this[d]},i.prototype.readUint16LE=i.prototype.readUInt16LE=function(d,_){return d=d>>>0,_||F(d,2,this.length),this[d]|this[d+1]<<8},i.prototype.readUint16BE=i.prototype.readUInt16BE=function(d,_){return d=d>>>0,_||F(d,2,this.length),this[d]<<8|this[d+1]},i.prototype.readUint32LE=i.prototype.readUInt32LE=function(d,_){return d=d>>>0,_||F(d,4,this.length),(this[d]|this[d+1]<<8|this[d+2]<<16)+this[d+3]*16777216},i.prototype.readUint32BE=i.prototype.readUInt32BE=function(d,_){return d=d>>>0,_||F(d,4,this.length),this[d]*16777216+(this[d+1]<<16|this[d+2]<<8|this[d+3])},i.prototype.readBigUInt64LE=se(function(d){d=d>>>0,Q(d,"offset");let _=this[d],A=this[d+7];(_===void 0||A===void 0)&&ge(d,this.length-8);let U=_+this[++d]*2**8+this[++d]*2**16+this[++d]*2**24,X=this[++d]+this[++d]*2**8+this[++d]*2**16+A*2**24;return BigInt(U)+(BigInt(X)<<BigInt(32))}),i.prototype.readBigUInt64BE=se(function(d){d=d>>>0,Q(d,"offset");let _=this[d],A=this[d+7];(_===void 0||A===void 0)&&ge(d,this.length-8);let U=_*2**24+this[++d]*2**16+this[++d]*2**8+this[++d],X=this[++d]*2**24+this[++d]*2**16+this[++d]*2**8+A;return(BigInt(U)<<BigInt(32))+BigInt(X)}),i.prototype.readIntLE=function(d,_,A){d=d>>>0,_=_>>>0,A||F(d,_,this.length);let U=this[d],X=1,he=0;for(;++he<_&&(X*=256);)U+=this[d+he]*X;return X*=128,U>=X&&(U-=Math.pow(2,8*_)),U},i.prototype.readIntBE=function(d,_,A){d=d>>>0,_=_>>>0,A||F(d,_,this.length);let U=_,X=1,he=this[d+--U];for(;U>0&&(X*=256);)he+=this[d+--U]*X;return X*=128,he>=X&&(he-=Math.pow(2,8*_)),he},i.prototype.readInt8=function(d,_){return d=d>>>0,_||F(d,1,this.length),this[d]&128?(255-this[d]+1)*-1:this[d]},i.prototype.readInt16LE=function(d,_){d=d>>>0,_||F(d,2,this.length);let A=this[d]|this[d+1]<<8;return A&32768?A|4294901760:A},i.prototype.readInt16BE=function(d,_){d=d>>>0,_||F(d,2,this.length);let A=this[d+1]|this[d]<<8;return A&32768?A|4294901760:A},i.prototype.readInt32LE=function(d,_){return d=d>>>0,_||F(d,4,this.length),this[d]|this[d+1]<<8|this[d+2]<<16|this[d+3]<<24},i.prototype.readInt32BE=function(d,_){return d=d>>>0,_||F(d,4,this.length),this[d]<<24|this[d+1]<<16|this[d+2]<<8|this[d+3]},i.prototype.readBigInt64LE=se(function(d){d=d>>>0,Q(d,"offset");let _=this[d],A=this[d+7];(_===void 0||A===void 0)&&ge(d,this.length-8);let U=this[d+4]+this[d+5]*2**8+this[d+6]*2**16+(A<<24);return(BigInt(U)<<BigInt(32))+BigInt(_+this[++d]*256+this[++d]*65536+this[++d]*16777216)}),i.prototype.readBigInt64BE=se(function(d){d=d>>>0,Q(d,"offset");let _=this[d],A=this[d+7];(_===void 0||A===void 0)&&ge(d,this.length-8);let U=(_<<24)+this[++d]*2**16+this[++d]*2**8+this[++d];return(BigInt(U)<<BigInt(32))+BigInt(this[++d]*16777216+this[++d]*65536+this[++d]*256+A)}),i.prototype.readFloatLE=function(d,_){return d=d>>>0,_||F(d,4,this.length),e.read(this,d,!0,23,4)},i.prototype.readFloatBE=function(d,_){return d=d>>>0,_||F(d,4,this.length),e.read(this,d,!1,23,4)},i.prototype.readDoubleLE=function(d,_){return d=d>>>0,_||F(d,8,this.length),e.read(this,d,!0,52,8)},i.prototype.readDoubleBE=function(d,_){return d=d>>>0,_||F(d,8,this.length),e.read(this,d,!1,52,8)};function Z(d,_,A,U,X,he){if(!i.isBuffer(d))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>d.length)throw new RangeError("Index out of range")}i.prototype.writeUintLE=i.prototype.writeUIntLE=function(d,_,A,U){if(d=+d,_=_>>>0,A=A>>>0,!U){let ke=Math.pow(2,8*A)-1;Z(this,d,_,A,ke,0)}let X=1,he=0;for(this[_]=d&255;++he<A&&(X*=256);)this[_+he]=d/X&255;return _+A},i.prototype.writeUintBE=i.prototype.writeUIntBE=function(d,_,A,U){if(d=+d,_=_>>>0,A=A>>>0,!U){let ke=Math.pow(2,8*A)-1;Z(this,d,_,A,ke,0)}let X=A-1,he=1;for(this[_+X]=d&255;--X>=0&&(he*=256);)this[_+X]=d/he&255;return _+A},i.prototype.writeUint8=i.prototype.writeUInt8=function(d,_,A){return d=+d,_=_>>>0,A||Z(this,d,_,1,255,0),this[_]=d&255,_+1},i.prototype.writeUint16LE=i.prototype.writeUInt16LE=function(d,_,A){return d=+d,_=_>>>0,A||Z(this,d,_,2,65535,0),this[_]=d&255,this[_+1]=d>>>8,_+2},i.prototype.writeUint16BE=i.prototype.writeUInt16BE=function(d,_,A){return d=+d,_=_>>>0,A||Z(this,d,_,2,65535,0),this[_]=d>>>8,this[_+1]=d&255,_+2},i.prototype.writeUint32LE=i.prototype.writeUInt32LE=function(d,_,A){return d=+d,_=_>>>0,A||Z(this,d,_,4,4294967295,0),this[_+3]=d>>>24,this[_+2]=d>>>16,this[_+1]=d>>>8,this[_]=d&255,_+4},i.prototype.writeUint32BE=i.prototype.writeUInt32BE=function(d,_,A){return d=+d,_=_>>>0,A||Z(this,d,_,4,4294967295,0),this[_]=d>>>24,this[_+1]=d>>>16,this[_+2]=d>>>8,this[_+3]=d&255,_+4};function M(d,_,A,U,X){K(_,U,X,d,A,7);let he=Number(_&BigInt(4294967295));d[A++]=he,he=he>>8,d[A++]=he,he=he>>8,d[A++]=he,he=he>>8,d[A++]=he;let ke=Number(_>>BigInt(32)&BigInt(4294967295));return d[A++]=ke,ke=ke>>8,d[A++]=ke,ke=ke>>8,d[A++]=ke,ke=ke>>8,d[A++]=ke,A}function J(d,_,A,U,X){K(_,U,X,d,A,7);let he=Number(_&BigInt(4294967295));d[A+7]=he,he=he>>8,d[A+6]=he,he=he>>8,d[A+5]=he,he=he>>8,d[A+4]=he;let ke=Number(_>>BigInt(32)&BigInt(4294967295));return d[A+3]=ke,ke=ke>>8,d[A+2]=ke,ke=ke>>8,d[A+1]=ke,ke=ke>>8,d[A]=ke,A+8}i.prototype.writeBigUInt64LE=se(function(d,_=0){return M(this,d,_,BigInt(0),BigInt("0xffffffffffffffff"))}),i.prototype.writeBigUInt64BE=se(function(d,_=0){return J(this,d,_,BigInt(0),BigInt("0xffffffffffffffff"))}),i.prototype.writeIntLE=function(d,_,A,U){if(d=+d,_=_>>>0,!U){let z=Math.pow(2,8*A-1);Z(this,d,_,A,z-1,-z)}let X=0,he=1,ke=0;for(this[_]=d&255;++X<A&&(he*=256);)d<0&&ke===0&&this[_+X-1]!==0&&(ke=1),this[_+X]=(d/he>>0)-ke&255;return _+A},i.prototype.writeIntBE=function(d,_,A,U){if(d=+d,_=_>>>0,!U){let z=Math.pow(2,8*A-1);Z(this,d,_,A,z-1,-z)}let X=A-1,he=1,ke=0;for(this[_+X]=d&255;--X>=0&&(he*=256);)d<0&&ke===0&&this[_+X+1]!==0&&(ke=1),this[_+X]=(d/he>>0)-ke&255;return _+A},i.prototype.writeInt8=function(d,_,A){return d=+d,_=_>>>0,A||Z(this,d,_,1,127,-128),d<0&&(d=255+d+1),this[_]=d&255,_+1},i.prototype.writeInt16LE=function(d,_,A){return d=+d,_=_>>>0,A||Z(this,d,_,2,32767,-32768),this[_]=d&255,this[_+1]=d>>>8,_+2},i.prototype.writeInt16BE=function(d,_,A){return d=+d,_=_>>>0,A||Z(this,d,_,2,32767,-32768),this[_]=d>>>8,this[_+1]=d&255,_+2},i.prototype.writeInt32LE=function(d,_,A){return d=+d,_=_>>>0,A||Z(this,d,_,4,2147483647,-2147483648),this[_]=d&255,this[_+1]=d>>>8,this[_+2]=d>>>16,this[_+3]=d>>>24,_+4},i.prototype.writeInt32BE=function(d,_,A){return d=+d,_=_>>>0,A||Z(this,d,_,4,2147483647,-2147483648),d<0&&(d=4294967295+d+1),this[_]=d>>>24,this[_+1]=d>>>16,this[_+2]=d>>>8,this[_+3]=d&255,_+4},i.prototype.writeBigInt64LE=se(function(d,_=0){return M(this,d,_,-BigInt("0x8000000000000000"),BigInt("0x7fffffffffffffff"))}),i.prototype.writeBigInt64BE=se(function(d,_=0){return J(this,d,_,-BigInt("0x8000000000000000"),BigInt("0x7fffffffffffffff"))});function be(d,_,A,U,X,he){if(A+U>d.length)throw new RangeError("Index out of range");if(A<0)throw new RangeError("Index out of range")}function te(d,_,A,U,X){return _=+_,A=A>>>0,X||be(d,_,A,4),e.write(d,_,A,U,23,4),A+4}i.prototype.writeFloatLE=function(d,_,A){return te(this,d,_,!0,A)},i.prototype.writeFloatBE=function(d,_,A){return te(this,d,_,!1,A)};function we(d,_,A,U,X){return _=+_,A=A>>>0,X||be(d,_,A,8),e.write(d,_,A,U,52,8),A+8}i.prototype.writeDoubleLE=function(d,_,A){return we(this,d,_,!0,A)},i.prototype.writeDoubleBE=function(d,_,A){return we(this,d,_,!1,A)},i.prototype.copy=function(d,_,A,U){if(!i.isBuffer(d))throw new TypeError("argument should be a Buffer");if(A||(A=0),!U&&U!==0&&(U=this.length),_>=d.length&&(_=d.length),_||(_=0),U>0&&U<A&&(U=A),U===A||d.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),d.length-_<U-A&&(U=d.length-_+A);let X=U-A;return this===d&&typeof Uint8Array.prototype.copyWithin=="function"?this.copyWithin(_,A,U):Uint8Array.prototype.set.call(d,this.subarray(A,U),_),X},i.prototype.fill=function(d,_,A,U){if(typeof d=="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(d.length===1){let he=d.charCodeAt(0);(U==="utf8"&&he<128||U==="latin1")&&(d=he)}}else typeof d=="number"?d=d&255:typeof d=="boolean"&&(d=Number(d));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,d||(d=0);let X;if(typeof d=="number")for(X=_;X<A;++X)this[X]=d;else{let he=i.isBuffer(d)?d:i.from(d,U),ke=he.length;if(ke===0)throw new TypeError('The value "'+d+'" is invalid for argument "value"');for(X=0;X<A-_;++X)this[X+_]=he[X%ke]}return this};let G={};function j(d,_,A){G[d]=class extends A{constructor(){super(),Object.defineProperty(this,"message",{value:_.apply(this,arguments),writable:!0,configurable:!0}),this.name=`${this.name} [${d}]`,this.stack,delete this.name}get code(){return d}set code(U){Object.defineProperty(this,"code",{configurable:!0,enumerable:!0,value:U,writable:!0})}toString(){return`${this.name} [${d}]: ${this.message}`}}}j("ERR_BUFFER_OUT_OF_BOUNDS",function(d){return d?`${d} is outside of buffer bounds`:"Attempt to access memory outside buffer bounds"},RangeError),j("ERR_INVALID_ARG_TYPE",function(d,_){return`The "${d}" argument must be of type number. Received type ${typeof _}`},TypeError),j("ERR_OUT_OF_RANGE",function(d,_,A){let U=`The value of "${d}" is out of range.`,X=A;return Number.isInteger(A)&&Math.abs(A)>4294967296?X=ne(String(A)):typeof A=="bigint"&&(X=String(A),(A>BigInt(2)**BigInt(32)||A<-(BigInt(2)**BigInt(32)))&&(X=ne(X)),X+="n"),U+=` It must be ${_}. Received ${X}`,U},RangeError);function ne(d){let _="",A=d.length,U=d[0]==="-"?1:0;for(;A>=U+4;A-=3)_=`_${d.slice(A-3,A)}${_}`;return`${d.slice(0,A)}${_}`}function W(d,_,A){Q(_,"offset"),(d[_]===void 0||d[_+A]===void 0)&&ge(_,d.length-(A+1))}function K(d,_,A,U,X,he){if(d>A||d<_){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 G.ERR_OUT_OF_RANGE("value",z,d)}W(U,X,he)}function Q(d,_){if(typeof d!="number")throw new G.ERR_INVALID_ARG_TYPE(_,"number",d)}function ge(d,_,A){throw Math.floor(d)!==d?(Q(d,A),new G.ERR_OUT_OF_RANGE("offset","an integer",d)):_<0?new G.ERR_BUFFER_OUT_OF_BOUNDS:new G.ERR_OUT_OF_RANGE("offset",`>= 0 and <= ${_}`,d)}let oe=/[^+/0-9A-Za-z-_]/g;function R(d){if(d=d.split("=")[0],d=d.trim().replace(oe,""),d.length<2)return"";for(;d.length%4!==0;)d=d+"=";return d}function $(d,_){_=_||1/0;let A,U=d.length,X=null,he=[];for(let ke=0;ke<U;++ke){if(A=d.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(d){let _=[];for(let A=0;A<d.length;++A)_.push(d.charCodeAt(A)&255);return _}function de(d,_){let A,U,X,he=[];for(let ke=0;ke<d.length&&!((_-=2)<0);++ke)A=d.charCodeAt(ke),U=A>>8,X=A%256,he.push(X),he.push(U);return he}function fe(d){return l.toByteArray(R(d))}function ye(d,_,A,U){let X;for(X=0;X<U&&!(X+A>=_.length||X>=d.length);++X)_[X+A]=d[X];return X}function H(d,_){return d instanceof _||d!=null&&d.constructor!=null&&d.constructor.name!=null&&d.constructor.name===_.name}function me(d){return d!==d}let ve=(function(){let d="0123456789abcdef",_=new Array(256);for(let A=0;A<16;++A){let U=A*16;for(let X=0;X<16;++X)_[U+X]=d[A]+d[X]}return _})();function se(d){return typeof BigInt>"u"?Te:d}function Te(){throw new Error("BigInt not supported")}return gt}var Lt,ii,Vt,oi,gt,si,Tc=Ve(()=>{le(),ue(),ce(),Lt={},ii=!1,Vt={},oi=!1,gt={},si=!1}),Be={};Rt(Be,{Buffer:()=>lr,INSPECT_MAX_BYTES:()=>Wo,default:()=>lt,kMaxLength:()=>zo});var lt,lr,Wo,zo,De=Ve(()=>{le(),ue(),ce(),Tc(),lt=Ic(),lt.Buffer,lt.SlowBuffer,lt.INSPECT_MAX_BYTES,lt.kMaxLength,lr=lt.Buffer,Wo=lt.INSPECT_MAX_BYTES,zo=lt.kMaxLength}),ue=Ve(()=>{De()}),Ne=pe((l,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 s="";for(let n=0;n<r.length;n++)s+=` ${r[n].stack}
2
- `;super(s),this.name="AggregateError",this.errors=r}};e.exports={AggregateError:t,ArrayIsArray(r){return Array.isArray(r)},ArrayPrototypeIncludes(r,s){return r.includes(s)},ArrayPrototypeIndexOf(r,s){return r.indexOf(s)},ArrayPrototypeJoin(r,s){return r.join(s)},ArrayPrototypeMap(r,s){return r.map(s)},ArrayPrototypePop(r,s){return r.pop(s)},ArrayPrototypePush(r,s){return r.push(s)},ArrayPrototypeSlice(r,s,n){return r.slice(s,n)},Error,FunctionPrototypeCall(r,s,...n){return r.call(s,...n)},FunctionPrototypeSymbolHasInstance(r,s){return Function.prototype[Symbol.hasInstance].call(r,s)},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,s){return Object.defineProperties(r,s)},ObjectDefineProperty(r,s,n){return Object.defineProperty(r,s,n)},ObjectGetOwnPropertyDescriptor(r,s){return Object.getOwnPropertyDescriptor(r,s)},ObjectKeys(r){return Object.keys(r)},ObjectSetPrototypeOf(r,s){return Object.setPrototypeOf(r,s)},Promise,PromisePrototypeCatch(r,s){return r.catch(s)},PromisePrototypeThen(r,s,n){return r.then(s,n)},PromiseReject(r){return Promise.reject(r)},PromiseResolve(r){return Promise.resolve(r)},ReflectApply:Reflect.apply,RegExpPrototypeTest(r,s){return r.test(s)},SafeSet:Set,String,StringPrototypeSlice(r,s,n){return r.slice(s,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,s,n){return r.set(s,n)},Boolean,Uint8Array}}),Vo=pe((l,e)=>{le(),ue(),ce(),e.exports={format(t,...r){return t.replace(/%([sdifj])/g,function(...[s,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((l,e)=>{le(),ue(),ce();var{format:t,inspect:r}=Vo(),{AggregateError:s}=Ne(),n=globalThis.AggregateError||s,i=Symbol("kIsNodeError"),o=["string","function","number","object","Function","Object","boolean","bigint","symbol"],a=/^([A-Z][a-z0-9]*)+$/,c="__node_internal_",u={};function h(m,w){if(!m)throw new u.ERR_INTERNAL_ASSERTION(w)}function p(m){let w="",S=m.length,v=m[0]==="-"?1:0;for(;S>=v+4;S-=3)w=`_${m.slice(S-3,S)}${w}`;return`${m.slice(0,S)}${w}`}function b(m,w,S){if(typeof w=="function")return h(w.length<=S.length,`Code: ${m}; The provided arguments length (${S.length}) does not match the required ones (${w.length}).`),w(...S);let v=(w.match(/%[dfijoOs]/g)||[]).length;return h(v===S.length,`Code: ${m}; The provided arguments length (${S.length}) does not match the required ones (${v}).`),S.length===0?w:t(w,...S)}function f(m,w,S){S||(S=Error);class v extends S{constructor(...x){super(b(m,w,x))}toString(){return`${this.name} [${m}]: ${this.message}`}}Object.defineProperties(v.prototype,{name:{value:S.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=c+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 S=new n([w,m],w.message);return S.code=w.code,S}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,S)=>{h(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 E=[],x=[],I=[];for(let O of w)h(typeof O=="string","All expected entries have to be of type string"),o.includes(O)?E.push(O.toLowerCase()):a.test(O)?x.push(O):(h(O!=="object",'The value "object" should be written as "Object"'),I.push(O));if(x.length>0){let O=E.indexOf("object");O!==-1&&(E.splice(E,O,1),x.push("Object"))}if(E.length>0){switch(E.length){case 1:v+=`of type ${E[0]}`;break;case 2:v+=`one of type ${E[0]} or ${E[1]}`;break;default:{let O=E.pop();v+=`one of type ${E.join(", ")}, or ${O}`}}(x.length>0||I.length>0)&&(v+=" or ")}if(x.length>0){switch(x.length){case 1:v+=`an instance of ${x[0]}`;break;case 2:v+=`an instance of ${x[0]} or ${x[1]}`;break;default:{let O=x.pop();v+=`an instance of ${x.join(", ")}, or ${O}`}}I.length>0&&(v+=" or ")}switch(I.length){case 0:break;case 1:I[0].toLowerCase()!==I[0]&&(v+="an "),v+=`${I[0]}`;break;case 2:v+=`one of ${I[0]} or ${I[1]}`;break;default:{let O=I.pop();v+=`one of ${I.join(", ")}, or ${O}`}}if(S==null)v+=`. Received ${S}`;else if(typeof S=="function"&&S.name)v+=`. Received function ${S.name}`;else if(typeof S=="object"){var P;if((P=S.constructor)!==null&&P!==void 0&&P.name)v+=`. Received an instance of ${S.constructor.name}`;else{let O=r(S,{depth:-1});v+=`. Received ${O}`}}else{let O=r(S,{colors:!1});O.length>25&&(O=`${O.slice(0,25)}...`),v+=`. Received type ${typeof S} (${O})`}return v},TypeError),f("ERR_INVALID_ARG_VALUE",(m,w,S="is invalid")=>{let v=r(w);return v.length>128&&(v=v.slice(0,128)+"..."),`The ${m.includes(".")?"property":"argument"} '${m}' ${S}. Received ${v}`},TypeError),f("ERR_INVALID_RETURN_VALUE",(m,w,S)=>{var v;let E=S!=null&&(v=S.constructor)!==null&&v!==void 0&&v.name?`instance of ${S.constructor.name}`:`type ${typeof S}`;return`Expected ${m} to be returned from the "${w}" function but got ${E}.`},TypeError),f("ERR_MISSING_ARGS",(...m)=>{h(m.length>0,"At least one arg needs to be specified");let w,S=m.length;switch(m=(Array.isArray(m)?m:[m]).map(v=>`"${v}"`).join(" or "),S){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,S)=>{h(w,'Missing "range" argument');let v;if(Number.isInteger(S)&&Math.abs(S)>2**32)v=p(String(S));else if(typeof S=="bigint"){v=String(S);let E=BigInt(2)**BigInt(32);(S>E||S<-E)&&(v=p(v)),v+="n"}else v=r(S);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}}),Gt=pe((l,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={};Rt(bt,{EventEmitter:()=>Go,default:()=>jt,defaultMaxListeners:()=>Ko,init:()=>Yo,listenerCount:()=>Qo,on:()=>Jo,once:()=>Xo});function Cc(){if(ai)return Kt;ai=!0;var l=typeof Reflect=="object"?Reflect:null,e=l&&typeof l.apply=="function"?l.apply:function(S,v,E){return Function.prototype.apply.call(S,v,E)},t;l&&typeof l.ownKeys=="function"?t=l.ownKeys:Object.getOwnPropertySymbols?t=function(S){return Object.getOwnPropertyNames(S).concat(Object.getOwnPropertySymbols(S))}:t=function(S){return Object.getOwnPropertyNames(S)};function r(S){console&&console.warn&&console.warn(S)}var s=Number.isNaN||function(S){return S!==S};function n(){n.init.call(this)}Kt=n,Kt.once=k,n.EventEmitter=n,n.prototype._events=void 0,n.prototype._eventsCount=0,n.prototype._maxListeners=void 0;var i=10;function o(S){if(typeof S!="function")throw new TypeError('The "listener" argument must be of type Function. Received type '+typeof S)}Object.defineProperty(n,"defaultMaxListeners",{enumerable:!0,get:function(){return i},set:function(S){if(typeof S!="number"||S<0||s(S))throw new RangeError('The value of "defaultMaxListeners" is out of range. It must be a non-negative number. Received '+S+".");i=S}}),n.init=function(){(this._events===void 0||this._events===Object.getPrototypeOf(this)._events)&&(this._events=Object.create(null),this._eventsCount=0),this._maxListeners=this._maxListeners||void 0},n.prototype.setMaxListeners=function(S){if(typeof S!="number"||S<0||s(S))throw new RangeError('The value of "n" is out of range. It must be a non-negative number. Received '+S+".");return this._maxListeners=S,this};function a(S){return S._maxListeners===void 0?n.defaultMaxListeners:S._maxListeners}n.prototype.getMaxListeners=function(){return a(this)},n.prototype.emit=function(S){for(var v=[],E=1;E<arguments.length;E++)v.push(arguments[E]);var x=S==="error",I=this._events;if(I!==void 0)x=x&&I.error===void 0;else if(!x)return!1;if(x){var P;if(v.length>0&&(P=v[0]),P instanceof Error)throw P;var O=new Error("Unhandled error."+(P?" ("+P.message+")":""));throw O.context=P,O}var B=I[S];if(B===void 0)return!1;if(typeof B=="function")e(B,this,v);else for(var T=B.length,q=f(B,T),E=0;E<T;++E)e(q[E],this,v);return!0};function c(S,v,E,x){var I,P,O;if(o(E),P=S._events,P===void 0?(P=S._events=Object.create(null),S._eventsCount=0):(P.newListener!==void 0&&(S.emit("newListener",v,E.listener?E.listener:E),P=S._events),O=P[v]),O===void 0)O=P[v]=E,++S._eventsCount;else if(typeof O=="function"?O=P[v]=x?[E,O]:[O,E]:x?O.unshift(E):O.push(E),I=a(S),I>0&&O.length>I&&!O.warned){O.warned=!0;var B=new Error("Possible EventEmitter memory leak detected. "+O.length+" "+String(v)+" listeners added. Use emitter.setMaxListeners() to increase limit");B.name="MaxListenersExceededWarning",B.emitter=S,B.type=v,B.count=O.length,r(B)}return S}n.prototype.addListener=function(S,v){return c(this,S,v,!1)},n.prototype.on=n.prototype.addListener,n.prototype.prependListener=function(S,v){return c(this,S,v,!0)};function u(){if(!this.fired)return this.target.removeListener(this.type,this.wrapFn),this.fired=!0,arguments.length===0?this.listener.call(this.target):this.listener.apply(this.target,arguments)}function h(S,v,E){var x={fired:!1,wrapFn:void 0,target:S,type:v,listener:E},I=u.bind(x);return I.listener=E,x.wrapFn=I,I}n.prototype.once=function(S,v){return o(v),this.on(S,h(this,S,v)),this},n.prototype.prependOnceListener=function(S,v){return o(v),this.prependListener(S,h(this,S,v)),this},n.prototype.removeListener=function(S,v){var E,x,I,P,O;if(o(v),x=this._events,x===void 0)return this;if(E=x[S],E===void 0)return this;if(E===v||E.listener===v)--this._eventsCount===0?this._events=Object.create(null):(delete x[S],x.removeListener&&this.emit("removeListener",S,E.listener||v));else if(typeof E!="function"){for(I=-1,P=E.length-1;P>=0;P--)if(E[P]===v||E[P].listener===v){O=E[P].listener,I=P;break}if(I<0)return this;I===0?E.shift():g(E,I),E.length===1&&(x[S]=E[0]),x.removeListener!==void 0&&this.emit("removeListener",S,O||v)}return this},n.prototype.off=n.prototype.removeListener,n.prototype.removeAllListeners=function(S){var v,E,x;if(E=this._events,E===void 0)return this;if(E.removeListener===void 0)return arguments.length===0?(this._events=Object.create(null),this._eventsCount=0):E[S]!==void 0&&(--this._eventsCount===0?this._events=Object.create(null):delete E[S]),this;if(arguments.length===0){var I=Object.keys(E),P;for(x=0;x<I.length;++x)P=I[x],P!=="removeListener"&&this.removeAllListeners(P);return this.removeAllListeners("removeListener"),this._events=Object.create(null),this._eventsCount=0,this}if(v=E[S],typeof v=="function")this.removeListener(S,v);else if(v!==void 0)for(x=v.length-1;x>=0;x--)this.removeListener(S,v[x]);return this};function p(S,v,E){var x=S._events;if(x===void 0)return[];var I=x[v];return I===void 0?[]:typeof I=="function"?E?[I.listener||I]:[I]:E?y(I):f(I,I.length)}n.prototype.listeners=function(S){return p(this,S,!0)},n.prototype.rawListeners=function(S){return p(this,S,!1)},n.listenerCount=function(S,v){return typeof S.listenerCount=="function"?S.listenerCount(v):b.call(S,v)},n.prototype.listenerCount=b;function b(S){var v=this._events;if(v!==void 0){var E=v[S];if(typeof E=="function")return 1;if(E!==void 0)return E.length}return 0}n.prototype.eventNames=function(){return this._eventsCount>0?t(this._events):[]};function f(S,v){for(var E=new Array(v),x=0;x<v;++x)E[x]=S[x];return E}function g(S,v){for(;v+1<S.length;v++)S[v]=S[v+1];S.pop()}function y(S){for(var v=new Array(S.length),E=0;E<v.length;++E)v[E]=S[E].listener||S[E];return v}function k(S,v){return new Promise(function(E,x){function I(O){S.removeListener(v,P),x(O)}function P(){typeof S.removeListener=="function"&&S.removeListener("error",I),E([].slice.call(arguments))}w(S,v,P,{once:!0}),v!=="error"&&m(S,I,{once:!0})})}function m(S,v,E){typeof S.on=="function"&&w(S,"error",v,E)}function w(S,v,E,x){if(typeof S.on=="function")x.once?S.once(v,E):S.on(v,E);else if(typeof S.addEventListener=="function")S.addEventListener(v,function I(P){x.once&&S.removeEventListener(v,I),E(P)});else throw new TypeError('The "emitter" argument must be of type EventEmitter. Received type '+typeof S)}return Kt}var Kt,ai,jt,Go,Ko,Yo,Qo,Jo,Xo,Et=Ve(()=>{le(),ue(),ce(),Kt={},ai=!1,jt=Cc(),jt.once,jt.once=function(l,e){return new Promise((t,r)=>{function s(...i){n!==void 0&&l.removeListener("error",n),t(i)}let n;e!=="error"&&(n=i=>{l.removeListener(name,s),r(i)},l.once("error",n)),l.once(e,s)})},jt.on=function(l,e){let t=[],r=[],s=null,n=!1,i={async next(){let c=t.shift();if(c)return createIterResult(c,!1);if(s){let u=Promise.reject(s);return s=null,u}return n?createIterResult(void 0,!0):new Promise((u,h)=>r.push({resolve:u,reject:h}))},async return(){l.removeListener(e,o),l.removeListener("error",a),n=!0;for(let c of r)c.resolve(createIterResult(void 0,!0));return createIterResult(void 0,!0)},throw(c){s=c,l.removeListener(e,o),l.removeListener("error",a)},[Symbol.asyncIterator](){return this}};return l.on(e,o),l.on("error",a),i;function o(...c){let u=r.shift();u?u.resolve(createIterResult(c,!1)):t.push(c)}function a(c){n=!0;let u=r.shift();u?u.reject(c):s=c,i.return()}},{EventEmitter:Go,defaultMaxListeners:Ko,init:Yo,listenerCount:Qo,on:Jo,once:Xo}=jt}),Ge=pe((l,e)=>{le(),ue(),ce();var t=(De(),Me(Be)),{format:r,inspect:s}=Vo(),{codes:{ERR_INVALID_ARG_TYPE:n}}=We(),{kResistStopPropagation:i,AggregateError:o,SymbolDispose:a}=Ne(),c=globalThis.AbortSignal||Gt().AbortSignal,u=globalThis.AbortController||Gt().AbortController,h=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:o,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,...S)=>w?m(w):k(...S))})},debuglog(){return function(){}},format:r,inspect:s,types:{isAsyncFunction(y){return y instanceof h},isArrayBufferView(y){return ArrayBuffer.isView(y)}},isBlob:b,deprecate(y,k){return y},addAbortListener:(Et(),Me(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,[a](){var w;(w=m)===null||w===void 0||w()}}},AbortSignalAny:c.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")}),Yt=pe((l,e)=>{le(),ue(),ce();var{ArrayIsArray:t,ArrayPrototypeIncludes:r,ArrayPrototypeJoin:s,ArrayPrototypeMap:n,NumberIsInteger:i,NumberIsNaN:o,NumberMAX_SAFE_INTEGER:a,NumberMIN_SAFE_INTEGER:c,NumberParseInt:u,ObjectPrototypeHasOwnProperty:h,RegExpPrototypeExec:p,String:b,StringPrototypeToUpperCase:f,StringPrototypeTrim:g}=Ne(),{hideStackFrames:y,codes:{ERR_SOCKET_BAD_PORT:k,ERR_INVALID_ARG_TYPE:m,ERR_INVALID_ARG_VALUE:w,ERR_OUT_OF_RANGE:S,ERR_UNKNOWN_SIGNAL:v}}=We(),{normalizeEncoding:E}=Ge(),{isAsyncFunction:x,isArrayBufferView:I}=Ge().types,P={};function O(H){return H===(H|0)}function B(H){return H===H>>>0}var T=/^[0-7]+$/,q="must be a 32-bit unsigned integer or an octal string";function D(H,me,ve){if(typeof H>"u"&&(H=ve),typeof H=="string"){if(p(T,H)===null)throw new w(me,H,q);H=u(H,8)}return Y(H,me),H}var N=y((H,me,ve=c,se=a)=>{if(typeof H!="number")throw new m(me,"number",H);if(!i(H))throw new S(me,"an integer",H);if(H<ve||H>se)throw new S(me,`>= ${ve} && <= ${se}`,H)}),ae=y((H,me,ve=-2147483648,se=2147483647)=>{if(typeof H!="number")throw new m(me,"number",H);if(!i(H))throw new S(me,"an integer",H);if(H<ve||H>se)throw new S(me,`>= ${ve} && <= ${se}`,H)}),Y=y((H,me,ve=!1)=>{if(typeof H!="number")throw new m(me,"number",H);if(!i(H))throw new S(me,"an integer",H);let se=ve?1:0,Te=4294967295;if(H<se||H>Te)throw new S(me,`>= ${se} && <= ${Te}`,H)});function V(H,me){if(typeof H!="string")throw new m(me,"string",H)}function re(H,me,ve=void 0,se){if(typeof H!="number")throw new m(me,"number",H);if(ve!=null&&H<ve||se!=null&&H>se||(ve!=null||se!=null)&&o(H))throw new S(me,`${ve!=null?`>= ${ve}`:""}${ve!=null&&se!=null?" && ":""}${se!=null?`<= ${se}`:""}`,H)}var F=y((H,me,ve)=>{if(!r(ve,H)){let se="must be one of: "+s(n(ve,Te=>typeof Te=="string"?`'${Te}'`:b(Te)),", ");throw new w(me,H,se)}});function Z(H,me){if(typeof H!="boolean")throw new m(me,"boolean",H)}function M(H,me,ve){return H==null||!h(H,me)?ve:H[me]}var J=y((H,me,ve=null)=>{let se=M(ve,"allowArray",!1),Te=M(ve,"allowFunction",!1);if(!M(ve,"nullable",!1)&&H===null||!se&&t(H)||typeof H!="object"&&(!Te||typeof H!="function"))throw new m(me,"Object",H)}),be=y((H,me)=>{if(H!=null&&typeof H!="object"&&typeof H!="function")throw new m(me,"a dictionary",H)}),te=y((H,me,ve=0)=>{if(!t(H))throw new m(me,"Array",H);if(H.length<ve){let se=`must be longer than ${ve}`;throw new w(me,H,se)}});function we(H,me){te(H,me);for(let ve=0;ve<H.length;ve++)V(H[ve],`${me}[${ve}]`)}function G(H,me){te(H,me);for(let ve=0;ve<H.length;ve++)Z(H[ve],`${me}[${ve}]`)}function j(H,me){te(H,me);for(let ve=0;ve<H.length;ve++){let se=H[ve],Te=`${me}[${ve}]`;if(se==null)throw new m(Te,"AbortSignal",se);ge(se,Te)}}function ne(H,me="signal"){if(V(H,me),P[H]===void 0)throw P[f(H)]!==void 0?new v(H+" (signals must use all capital letters)"):new v(H)}var W=y((H,me="buffer")=>{if(!I(H))throw new m(me,["Buffer","TypedArray","DataView"],H)});function K(H,me){let ve=E(me),se=H.length;if(ve==="hex"&&se%2!==0)throw new w("encoding",me,`is invalid for data of length ${se}`)}function Q(H,me="Port",ve=!0){if(typeof H!="number"&&typeof H!="string"||typeof H=="string"&&g(H).length===0||+H!==+H>>>0||H>65535||H===0&&!ve)throw new k(me,H,ve);return H|0}var ge=y((H,me)=>{if(H!==void 0&&(H===null||typeof H!="object"||!("aborted"in H)))throw new m(me,"AbortSignal",H)}),oe=y((H,me)=>{if(typeof H!="function")throw new m(me,"Function",H)}),R=y((H,me)=>{if(typeof H!="function"||x(H))throw new m(me,"Function",H)}),$=y((H,me)=>{if(H!==void 0)throw new m(me,"undefined",H)});function ee(H,me,ve){if(!r(ve,H))throw new m(me,`('${s(ve,"|")}')`,H)}var de=/^(?:<[^>]*>)(?:\s*;\s*[^;"\s]+(?:=(")?[^;"\s]*\1)?)*$/;function fe(H,me){if(typeof H>"u"||!p(de,H))throw new w(me,H,'must be an array or string of format "</styles.css>; rel=preload; as=style"')}function ye(H){if(typeof H=="string")return fe(H,"hints"),H;if(t(H)){let me=H.length,ve="";if(me===0)return ve;for(let se=0;se<me;se++){let Te=H[se];fe(Te,"hints"),ve+=Te,se!==me-1&&(ve+=", ")}return ve}throw new w("hints",H,'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:G,validateAbortSignalArray:j,validateBoolean:Z,validateBuffer:W,validateDictionary:be,validateEncoding:K,validateFunction:oe,validateInt32:ae,validateInteger:N,validateNumber:re,validateObject:J,validateOneOf:F,validatePlainFunction:R,validatePort:Q,validateSignalName:ne,validateString:V,validateUint32:Y,validateUndefined:$,validateUnion:ee,validateAbortSignal:ge,validateLinkHeaderValue:ye}}),At=pe((l,e)=>{le(),ue(),ce();var t=e.exports={},r,s;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"?s=clearTimeout:s=i}catch{s=i}})();function o(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 a(k){if(s===clearTimeout)return clearTimeout(k);if((s===i||!s)&&clearTimeout)return s=clearTimeout,clearTimeout(k);try{return s(k)}catch{try{return s.call(null,k)}catch{return s.call(this,k)}}}var c=[],u=!1,h,p=-1;function b(){!u||!h||(u=!1,h.length?c=h.concat(c):p=-1,c.length&&f())}function f(){if(!u){var k=o(b);u=!0;for(var m=c.length;m;){for(h=c,c=[];++p<m;)h&&h[p].run();p=-1,m=c.length}h=null,u=!1,a(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];c.push(new g(k,m)),c.length===1&&!u&&o(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((l,e)=>{le(),ue(),ce();var{SymbolAsyncIterator:t,SymbolIterator:r,SymbolFor:s}=Ne(),n=s("nodejs.stream.destroyed"),i=s("nodejs.stream.errored"),o=s("nodejs.stream.readable"),a=s("nodejs.stream.writable"),c=s("nodejs.stream.disturbed"),u=s("nodejs.webstream.isClosedPromise"),h=s("nodejs.webstream.controllerErrorFunction");function p(M,J=!1){var be;return!!(M&&typeof M.pipe=="function"&&typeof M.on=="function"&&(!J||typeof M.pause=="function"&&typeof M.resume=="function")&&(!M._writableState||((be=M._readableState)===null||be===void 0?void 0:be.readable)!==!1)&&(!M._writableState||M._readableState))}function b(M){var J;return!!(M&&typeof M.write=="function"&&typeof M.on=="function"&&(!M._readableState||((J=M._writableState)===null||J===void 0?void 0:J.writable)!==!1))}function f(M){return!!(M&&typeof M.pipe=="function"&&M._readableState&&typeof M.on=="function"&&typeof M.write=="function")}function g(M){return M&&(M._readableState||M._writableState||typeof M.write=="function"&&typeof M.on=="function"||typeof M.pipe=="function"&&typeof M.on=="function")}function y(M){return!!(M&&!g(M)&&typeof M.pipeThrough=="function"&&typeof M.getReader=="function"&&typeof M.cancel=="function")}function k(M){return!!(M&&!g(M)&&typeof M.getWriter=="function"&&typeof M.abort=="function")}function m(M){return!!(M&&!g(M)&&typeof M.readable=="object"&&typeof M.writable=="object")}function w(M){return y(M)||k(M)||m(M)}function S(M,J){return M==null?!1:J===!0?typeof M[t]=="function":J===!1?typeof M[r]=="function":typeof M[t]=="function"||typeof M[r]=="function"}function v(M){if(!g(M))return null;let J=M._writableState,be=M._readableState,te=J||be;return!!(M.destroyed||M[n]||te!=null&&te.destroyed)}function E(M){if(!b(M))return null;if(M.writableEnded===!0)return!0;let J=M._writableState;return J!=null&&J.errored?!1:typeof J?.ended!="boolean"?null:J.ended}function x(M,J){if(!b(M))return null;if(M.writableFinished===!0)return!0;let be=M._writableState;return be!=null&&be.errored?!1:typeof be?.finished!="boolean"?null:!!(be.finished||J===!1&&be.ended===!0&&be.length===0)}function I(M){if(!p(M))return null;if(M.readableEnded===!0)return!0;let J=M._readableState;return!J||J.errored?!1:typeof J?.ended!="boolean"?null:J.ended}function P(M,J){if(!p(M))return null;let be=M._readableState;return be!=null&&be.errored?!1:typeof be?.endEmitted!="boolean"?null:!!(be.endEmitted||J===!1&&be.ended===!0&&be.length===0)}function O(M){return M&&M[o]!=null?M[o]:typeof M?.readable!="boolean"?null:v(M)?!1:p(M)&&M.readable&&!P(M)}function B(M){return M&&M[a]!=null?M[a]:typeof M?.writable!="boolean"?null:v(M)?!1:b(M)&&M.writable&&!E(M)}function T(M,J){return g(M)?v(M)?!0:!(J?.readable!==!1&&O(M)||J?.writable!==!1&&B(M)):null}function q(M){var J,be;return g(M)?M.writableErrored?M.writableErrored:(J=(be=M._writableState)===null||be===void 0?void 0:be.errored)!==null&&J!==void 0?J:null:null}function D(M){var J,be;return g(M)?M.readableErrored?M.readableErrored:(J=(be=M._readableState)===null||be===void 0?void 0:be.errored)!==null&&J!==void 0?J:null:null}function N(M){if(!g(M))return null;if(typeof M.closed=="boolean")return M.closed;let J=M._writableState,be=M._readableState;return typeof J?.closed=="boolean"||typeof be?.closed=="boolean"?J?.closed||be?.closed:typeof M._closed=="boolean"&&ae(M)?M._closed:null}function ae(M){return typeof M._closed=="boolean"&&typeof M._defaultKeepAlive=="boolean"&&typeof M._removedConnection=="boolean"&&typeof M._removedContLen=="boolean"}function Y(M){return typeof M._sent100=="boolean"&&ae(M)}function V(M){var J;return typeof M._consuming=="boolean"&&typeof M._dumped=="boolean"&&((J=M.req)===null||J===void 0?void 0:J.upgradeOrConnect)===void 0}function re(M){if(!g(M))return null;let J=M._writableState,be=M._readableState,te=J||be;return!te&&Y(M)||!!(te&&te.autoDestroy&&te.emitClose&&te.closed===!1)}function F(M){var J;return!!(M&&((J=M[c])!==null&&J!==void 0?J:M.readableDidRead||M.readableAborted))}function Z(M){var J,be,te,we,G,j,ne,W,K,Q;return!!(M&&((J=(be=(te=(we=(G=(j=M[i])!==null&&j!==void 0?j:M.readableErrored)!==null&&G!==void 0?G:M.writableErrored)!==null&&we!==void 0?we:(ne=M._readableState)===null||ne===void 0?void 0:ne.errorEmitted)!==null&&te!==void 0?te:(W=M._writableState)===null||W===void 0?void 0:W.errorEmitted)!==null&&be!==void 0?be:(K=M._readableState)===null||K===void 0?void 0:K.errored)!==null&&J!==void 0?J:!((Q=M._writableState)===null||Q===void 0)&&Q.errored))}e.exports={isDestroyed:v,kIsDestroyed:n,isDisturbed:F,kIsDisturbed:c,isErrored:Z,kIsErrored:i,isReadable:O,kIsReadable:o,kIsClosedPromise:u,kControllerErrorFunction:h,kIsWritable:a,isClosed:N,isDuplexNodeStream:f,isFinished:T,isIterable:S,isReadableNodeStream:p,isReadableStream:y,isReadableEnded:I,isReadableFinished:P,isReadableErrored:D,isNodeStream:g,isWebStream:w,isWritable:B,isWritableNodeStream:b,isWritableStream:k,isWritableEnded:E,isWritableFinished:x,isWritableErrored:q,isServerRequest:V,isServerResponse:Y,willEmitClose:re,isTransformStream:m}}),yt=pe((l,e)=>{le(),ue(),ce();var t=At(),{AbortError:r,codes:s}=We(),{ERR_INVALID_ARG_TYPE:n,ERR_STREAM_PREMATURE_CLOSE:i}=s,{kEmptyObject:o,once:a}=Ge(),{validateAbortSignal:c,validateFunction:u,validateObject:h,validateBoolean:p}=Yt(),{Promise:b,PromisePrototypeThen:f,SymbolDispose:g}=Ne(),{isClosed:y,isReadable:k,isReadableNodeStream:m,isReadableStream:w,isReadableFinished:S,isReadableErrored:v,isWritable:E,isWritableNodeStream:x,isWritableStream:I,isWritableFinished:P,isWritableErrored:O,isNodeStream:B,willEmitClose:T,kIsClosedPromise:q}=ct(),D;function N(F){return F.setHeader&&typeof F.abort=="function"}var ae=()=>{};function Y(F,Z,M){var J,be;if(arguments.length===2?(M=Z,Z=o):Z==null?Z=o:h(Z,"options"),u(M,"callback"),c(Z.signal,"options.signal"),M=a(M),w(F)||I(F))return V(F,Z,M);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:x(F),G=F._writableState,j=F._readableState,ne=()=>{F.writable||Q()},W=T(F)&&m(F)===te&&x(F)===we,K=P(F,!1),Q=()=>{K=!0,F.destroyed&&(W=!1),!(W&&(!F.readable||te))&&(!te||ge)&&M.call(F)},ge=S(F,!1),oe=()=>{ge=!0,F.destroyed&&(W=!1),!(W&&(!F.writable||we))&&(!we||K)&&M.call(F)},R=H=>{M.call(F,H)},$=y(F),ee=()=>{$=!0;let H=O(F)||v(F);if(H&&typeof H!="boolean")return M.call(F,H);if(te&&!ge&&m(F,!0)&&!S(F,!1))return M.call(F,new i);if(we&&!K&&!P(F,!1))return M.call(F,new i);M.call(F)},de=()=>{$=!0;let H=O(F)||v(F);if(H&&typeof H!="boolean")return M.call(F,H);M.call(F)},fe=()=>{F.req.on("finish",Q)};N(F)?(F.on("complete",Q),W||F.on("abort",ee),F.req?fe():F.on("request",fe)):we&&!G&&(F.on("end",ne),F.on("close",ne)),!W&&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):G!=null&&G.errorEmitted||j!=null&&j.errorEmitted?W||t.nextTick(de):(!te&&(!W||k(F))&&(K||E(F)===!1)||!we&&(!W||E(F))&&(ge||k(F)===!1)||j&&F.req&&F.aborted)&&t.nextTick(de);let ye=()=>{M=ae,F.removeListener("aborted",ee),F.removeListener("complete",Q),F.removeListener("abort",ee),F.removeListener("request",fe),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 H=()=>{let me=M;ye(),me.call(F,new r(void 0,{cause:Z.signal.reason}))};if(Z.signal.aborted)t.nextTick(H);else{D=D||Ge().addAbortListener;let me=D(Z.signal,H),ve=M;M=a((...se)=>{me[g](),ve.apply(F,se)})}}return ye}function V(F,Z,M){let J=!1,be=ae;if(Z.signal)if(be=()=>{J=!0,M.call(F,new r(void 0,{cause:Z.signal.reason}))},Z.signal.aborted)t.nextTick(be);else{D=D||Ge().addAbortListener;let we=D(Z.signal,be),G=M;M=a((...j)=>{we[g](),G.apply(F,j)})}let te=(...we)=>{J||t.nextTick(()=>M.apply(F,we))};return f(F[q].promise,te,te),ae}function re(F,Z){var M;let J=!1;return Z===null&&(Z=o),(M=Z)!==null&&M!==void 0&&M.cleanup&&(p(Z.cleanup,"cleanup"),J=Z.cleanup),new b((be,te)=>{let we=Y(F,Z,G=>{J&&we(),G?te(G):be()})})}e.exports=Y,e.exports.finished=re}),Nt=pe((l,e)=>{le(),ue(),ce();var t=At(),{aggregateTwoErrors:r,codes:{ERR_MULTIPLE_CALLBACK:s},AbortError:n}=We(),{Symbol:i}=Ne(),{kIsDestroyed:o,isDestroyed:a,isFinished:c,isServerRequest:u}=ct(),h=i("kDestroy"),p=i("kConstruct");function b(T,q,D){T&&(T.stack,q&&!q.errored&&(q.errored=T),D&&!D.errored&&(D.errored=T))}function f(T,q){let D=this._readableState,N=this._writableState,ae=N||D;return N!=null&&N.destroyed||D!=null&&D.destroyed?(typeof q=="function"&&q(),this):(b(T,N,D),N&&(N.destroyed=!0),D&&(D.destroyed=!0),ae.constructed?g(this,T,q):this.once(h,function(Y){g(this,r(Y,T),q)}),this)}function g(T,q,D){let N=!1;function ae(Y){if(N)return;N=!0;let V=T._readableState,re=T._writableState;b(Y,re,V),re&&(re.closed=!0),V&&(V.closed=!0),typeof D=="function"&&D(Y),Y?t.nextTick(y,T,Y):t.nextTick(k,T)}try{T._destroy(q||null,ae)}catch(Y){ae(Y)}}function y(T,q){m(T,q),k(T)}function k(T){let q=T._readableState,D=T._writableState;D&&(D.closeEmitted=!0),q&&(q.closeEmitted=!0),(D!=null&&D.emitClose||q!=null&&q.emitClose)&&T.emit("close")}function m(T,q){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",q))}function w(){let T=this._readableState,q=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),q&&(q.constructed=!0,q.destroyed=!1,q.closed=!1,q.closeEmitted=!1,q.errored=null,q.errorEmitted=!1,q.finalCalled=!1,q.prefinished=!1,q.ended=q.writable===!1,q.ending=q.writable===!1,q.finished=q.writable===!1)}function S(T,q,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(q):q&&(q.stack,ae&&!ae.errored&&(ae.errored=q),N&&!N.errored&&(N.errored=q),D?t.nextTick(m,T,q):m(T,q))}function v(T,q){if(typeof T._construct!="function")return;let D=T._readableState,N=T._writableState;D&&(D.constructed=!1),N&&(N.constructed=!1),T.once(p,q),!(T.listenerCount(p)>1)&&t.nextTick(E,T)}function E(T){let q=!1;function D(N){if(q){S(T,N??new s);return}q=!0;let ae=T._readableState,Y=T._writableState,V=Y||ae;ae&&(ae.constructed=!0),Y&&(Y.constructed=!0),V.destroyed?T.emit(h,N):N?S(T,N,!0):t.nextTick(x,T)}try{T._construct(N=>{t.nextTick(D,N)})}catch(N){t.nextTick(D,N)}}function x(T){T.emit(p)}function I(T){return T?.setHeader&&typeof T.abort=="function"}function P(T){T.emit("close")}function O(T,q){T.emit("error",q),t.nextTick(P,T)}function B(T,q){!T||a(T)||(!q&&!c(T)&&(q=new n),u(T)?(T.socket=null,T.destroy(q)):I(T)?T.abort():I(T.req)?T.req.abort():typeof T.destroy=="function"?T.destroy(q):typeof T.close=="function"?T.close():q?t.nextTick(O,T,q):t.nextTick(P,T),T.destroyed||(T[o]=!0))}e.exports={construct:v,destroyer:B,destroy:f,undestroy:w,errorOrDestroy:S}}),li=pe((l,e)=>{le(),ue(),ce();var{ArrayIsArray:t,ObjectSetPrototypeOf:r}=Ne(),{EventEmitter:s}=(Et(),Me(bt));function n(o){s.call(this,o)}r(n.prototype,s.prototype),r(n,s),n.prototype.pipe=function(o,a){let c=this;function u(k){o.writable&&o.write(k)===!1&&c.pause&&c.pause()}c.on("data",u);function h(){c.readable&&c.resume&&c.resume()}o.on("drain",h),!o._isStdio&&(!a||a.end!==!1)&&(c.on("end",b),c.on("close",f));let p=!1;function b(){p||(p=!0,o.end())}function f(){p||(p=!0,typeof o.destroy=="function"&&o.destroy())}function g(k){y(),s.listenerCount(this,"error")===0&&this.emit("error",k)}i(c,"error",g),i(o,"error",g);function y(){c.removeListener("data",u),o.removeListener("drain",h),c.removeListener("end",b),c.removeListener("close",f),c.removeListener("error",g),o.removeListener("error",g),c.removeListener("end",y),c.removeListener("close",y),o.removeListener("close",y)}return c.on("end",y),c.on("close",y),o.on("close",y),o.emit("pipe",c),o};function i(o,a,c){if(typeof o.prependListener=="function")return o.prependListener(a,c);!o._events||!o._events[a]?o.on(a,c):t(o._events[a])?o._events[a].unshift(c):o._events[a]=[c,o._events[a]]}e.exports={Stream:n,prependListener:i}}),cr=pe((l,e)=>{le(),ue(),ce();var{SymbolDispose:t}=Ne(),{AbortError:r,codes:s}=We(),{isNodeStream:n,isWebStream:i,kControllerErrorFunction:o}=ct(),a=yt(),{ERR_INVALID_ARG_TYPE:c}=s,u,h=(p,b)=>{if(typeof p!="object"||!("aborted"in p))throw new c(b,"AbortSignal",p)};e.exports.addAbortSignal=function(p,b){if(h(p,"signal"),!n(b)&&!i(b))throw new c("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[o](new r(void 0,{cause:p.reason}))};if(p.aborted)f();else{u=u||Ge().addAbortListener;let g=u(p,f);a(b,g[t])}return b}}),Oc=pe((l,e)=>{le(),ue(),ce();var{StringPrototypeSlice:t,SymbolIterator:r,TypedArrayPrototypeSet:s,Uint8Array:n}=Ne(),{Buffer:i}=(De(),Me(Be)),{inspect:o}=Ge();e.exports=class{constructor(){this.head=null,this.tail=null,this.length=0}push(a){let c={data:a,next:null};this.length>0?this.tail.next=c:this.head=c,this.tail=c,++this.length}unshift(a){let c={data:a,next:this.head};this.length===0&&(this.tail=c),this.head=c,++this.length}shift(){if(this.length===0)return;let a=this.head.data;return this.length===1?this.head=this.tail=null:this.head=this.head.next,--this.length,a}clear(){this.head=this.tail=null,this.length=0}join(a){if(this.length===0)return"";let c=this.head,u=""+c.data;for(;(c=c.next)!==null;)u+=a+c.data;return u}concat(a){if(this.length===0)return i.alloc(0);let c=i.allocUnsafe(a>>>0),u=this.head,h=0;for(;u;)s(c,u.data,h),h+=u.data.length,u=u.next;return c}consume(a,c){let u=this.head.data;if(a<u.length){let h=u.slice(0,a);return this.head.data=u.slice(a),h}return a===u.length?this.shift():c?this._getString(a):this._getBuffer(a)}first(){return this.head.data}*[r](){for(let a=this.head;a;a=a.next)yield a.data}_getString(a){let c="",u=this.head,h=0;do{let p=u.data;if(a>p.length)c+=p,a-=p.length;else{a===p.length?(c+=p,++h,u.next?this.head=u.next:this.head=this.tail=null):(c+=t(p,0,a),this.head=u,u.data=t(p,a));break}++h}while((u=u.next)!==null);return this.length-=h,c}_getBuffer(a){let c=i.allocUnsafe(a),u=a,h=this.head,p=0;do{let b=h.data;if(a>b.length)s(c,b,u-a),a-=b.length;else{a===b.length?(s(c,b,u-a),++p,h.next?this.head=h.next:this.head=this.tail=null):(s(c,new n(b.buffer,b.byteOffset,a),u-a),this.head=h,h.data=b.slice(a));break}++p}while((h=h.next)!==null);return this.length-=p,c}[Symbol.for("nodejs.util.inspect.custom")](a,c){return o(this,{...c,depth:0,customInspect:!1})}}}),ur=pe((l,e)=>{le(),ue(),ce();var{MathFloor:t,NumberIsInteger:r}=Ne(),{validateInteger:s}=Yt(),{ERR_INVALID_ARG_VALUE:n}=We().codes,i=16*1024,o=16;function a(p,b,f){return p.highWaterMark!=null?p.highWaterMark:b?p[f]:null}function c(p){return p?o:i}function u(p,b){s(b,"value",0),p?o=b:i=b}function h(p,b,f,g){let y=a(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 c(p.objectMode)}e.exports={getHighWaterMark:h,getDefaultHighWaterMark:c,setDefaultHighWaterMark:u}}),Pc=pe((l,e)=>{le(),ue(),ce();var t=(De(),Me(Be)),r=t.Buffer;function s(i,o){for(var a in i)o[a]=i[a]}r.from&&r.alloc&&r.allocUnsafe&&r.allocUnsafeSlow?e.exports=t:(s(t,l),l.Buffer=n);function n(i,o,a){return r(i,o,a)}n.prototype=Object.create(r.prototype),s(r,n),n.from=function(i,o,a){if(typeof i=="number")throw new TypeError("Argument must not be a number");return r(i,o,a)},n.alloc=function(i,o,a){if(typeof i!="number")throw new TypeError("Argument must be a number");var c=r(i);return o!==void 0?typeof a=="string"?c.fill(o,a):c.fill(o):c.fill(0),c},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(l=>{le(),ue(),ce();var e=Pc().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 s(m){var w=r(m);if(typeof w!="string"&&(e.isEncoding===t||!t(m)))throw new Error("Unknown encoding: "+m);return w||m}l.StringDecoder=n;function n(m){this.encoding=s(m);var w;switch(this.encoding){case"utf16le":this.text=p,this.end=b,w=4;break;case"utf8":this.fillLast=c,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,S;if(this.lastNeed){if(w=this.fillLast(m),w===void 0)return"";S=this.lastNeed,this.lastNeed=0}else S=0;return S<m.length?w?w+this.text(m,S):this.text(m,S):w||""},n.prototype.end=h,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 o(m,w,S){var v=w.length-1;if(v<S)return 0;var E=i(w[v]);return E>=0?(E>0&&(m.lastNeed=E-1),E):--v<S||E===-2?0:(E=i(w[v]),E>=0?(E>0&&(m.lastNeed=E-2),E):--v<S||E===-2?0:(E=i(w[v]),E>=0?(E>0&&(E===2?E=0:m.lastNeed=E-3),E):0))}function a(m,w,S){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 c(m){var w=this.lastTotal-this.lastNeed,S=a(this,m);if(S!==void 0)return S;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 S=o(this,m,w);if(!this.lastNeed)return m.toString("utf8",w);this.lastTotal=S;var v=m.length-(S-this.lastNeed);return m.copy(this.lastChar,0,v),m.toString("utf8",w,v)}function h(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 S=m.toString("utf16le",w);if(S){var v=S.charCodeAt(S.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],S.slice(0,-1)}return S}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 S=this.lastTotal-this.lastNeed;return w+this.lastChar.toString("utf16le",0,S)}return w}function f(m,w){var S=(m.length-w)%3;return S===0?m.toString("base64",w):(this.lastNeed=3-S,this.lastTotal=3,S===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-S))}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):""}}),Zo=pe((l,e)=>{le(),ue(),ce();var t=At(),{PromisePrototypeThen:r,SymbolAsyncIterator:s,SymbolIterator:n}=Ne(),{Buffer:i}=(De(),Me(Be)),{ERR_INVALID_ARG_TYPE:o,ERR_STREAM_NULL_VALUES:a}=We().codes;function c(u,h,p){let b;if(typeof h=="string"||h instanceof i)return new u({objectMode:!0,...p,read(){this.push(h),this.push(null)}});let f;if(h&&h[s])f=!0,b=h[s]();else if(h&&h[n])f=!1,b=h[n]();else throw new o("iterable",["Iterable"],h);let g=new u({objectMode:!0,highWaterMark:1,...p}),y=!1;g._read=function(){y||(y=!0,m())},g._destroy=function(w,S){r(k(w),()=>t.nextTick(S,w),v=>t.nextTick(S,v||w))};async function k(w){let S=w!=null,v=typeof b.throw=="function";if(S&&v){let{value:E,done:x}=await b.throw(w);if(await E,x)return}if(typeof b.return=="function"){let{value:E}=await b.return();await E}}async function m(){for(;;){try{let{value:w,done:S}=f?await b.next():b.next();if(S)g.push(null);else{let v=w&&typeof w.then=="function"?await w:w;if(v===null)throw y=!1,new a;if(g.push(v))continue;y=!1}}catch(w){g.destroy(w)}break}}return g}e.exports=c}),hr=pe((l,e)=>{le(),ue(),ce();var t=At(),{ArrayPrototypeIndexOf:r,NumberIsInteger:s,NumberIsNaN:n,NumberParseInt:i,ObjectDefineProperties:o,ObjectKeys:a,ObjectSetPrototypeOf:c,Promise:u,SafeSet:h,SymbolAsyncDispose:p,SymbolAsyncIterator:b,Symbol:f}=Ne();e.exports=se,se.ReadableState=ve;var{EventEmitter:g}=(Et(),Me(bt)),{Stream:y,prependListener:k}=li(),{Buffer:m}=(De(),Me(Be)),{addAbortSignal:w}=cr(),S=yt(),v=Ge().debuglog("stream",C=>{v=C}),E=Oc(),x=Nt(),{getHighWaterMark:I,getDefaultHighWaterMark:P}=ur(),{aggregateTwoErrors:O,codes:{ERR_INVALID_ARG_TYPE:B,ERR_METHOD_NOT_IMPLEMENTED:T,ERR_OUT_OF_RANGE:q,ERR_STREAM_PUSH_AFTER_EOF:D,ERR_STREAM_UNSHIFT_AFTER_END_EVENT:N},AbortError:ae}=We(),{validateObject:Y}=Yt(),V=f("kPaused"),{StringDecoder:re}=Mc(),F=Zo();c(se.prototype,y.prototype),c(se,y);var Z=()=>{},{errorOrDestroy:M}=x,J=1,be=2,te=4,we=8,G=16,j=32,ne=64,W=128,K=256,Q=512,ge=1024,oe=2048,R=4096,$=8192,ee=16384,de=32768,fe=65536,ye=1<<17,H=1<<18;function me(C){return{enumerable:!1,get(){return(this.state&C)!==0},set(L){L?this.state|=C:this.state&=~C}}}o(ve.prototype,{objectMode:me(J),ended:me(be),endEmitted:me(te),reading:me(we),constructed:me(G),sync:me(j),needReadable:me(ne),emittedReadable:me(W),readableListening:me(K),resumeScheduled:me(Q),errorEmitted:me(ge),emitClose:me(oe),autoDestroy:me(R),destroyed:me($),closed:me(ee),closeEmitted:me(de),multiAwaitDrain:me(fe),readingMore:me(ye),dataEmitted:me(H)});function ve(C,L,_e){typeof _e!="boolean"&&(_e=L instanceof ut()),this.state=oe|R|G|j,C&&C.objectMode&&(this.state|=J),_e&&C&&C.readableObjectMode&&(this.state|=J),this.highWaterMark=C?I(this,C,"readableHighWaterMark",_e):P(!1),this.buffer=new E,this.length=0,this.pipes=[],this.flowing=null,this[V]=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 L=this instanceof ut();this._readableState=new ve(C,this,L),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&&!L&&w(C.signal,this)),y.call(this,C),x.construct(this,()=>{this._readableState.needReadable&&z(this,this._readableState)})}se.prototype.destroy=x.destroy,se.prototype._undestroy=x.undestroy,se.prototype._destroy=function(C,L){L(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((L,_e)=>S(this,xe=>xe&&xe!==C?_e(xe):L(null)))},se.prototype.push=function(C,L){return Te(this,C,L,!1)},se.prototype.unshift=function(C,L){return Te(this,C,L,!0)};function Te(C,L,_e,xe){v("readableAddChunk",L);let Se=C._readableState,Ue;if((Se.state&J)===0&&(typeof L=="string"?(_e=_e||Se.defaultEncoding,Se.encoding!==_e&&(xe&&Se.encoding?L=m.from(L,_e).toString(Se.encoding):(L=m.from(L,_e),_e=""))):L instanceof m?_e="":y._isUint8Array(L)?(L=y._uint8ArrayToBuffer(L),_e=""):L!=null&&(Ue=new B("chunk",["string","Buffer","Uint8Array"],L))),Ue)M(C,Ue);else if(L===null)Se.state&=~we,X(C,Se);else if((Se.state&J)!==0||L&&L.length>0)if(xe)if((Se.state&te)!==0)M(C,new N);else{if(Se.destroyed||Se.errored)return!1;d(C,Se,L,!0)}else if(Se.ended)M(C,new D);else{if(Se.destroyed||Se.errored)return!1;Se.state&=~we,Se.decoder&&!_e?(L=Se.decoder.write(L),Se.objectMode||L.length!==0?d(C,Se,L,!1):z(C,Se)):d(C,Se,L,!1)}else xe||(Se.state&=~we,z(C,Se));return!Se.ended&&(Se.length<Se.highWaterMark||Se.length===0)}function d(C,L,_e,xe){L.flowing&&L.length===0&&!L.sync&&C.listenerCount("data")>0?((L.state&fe)!==0?L.awaitDrainWriters.clear():L.awaitDrainWriters=null,L.dataEmitted=!0,C.emit("data",_e)):(L.length+=L.objectMode?1:_e.length,xe?L.buffer.unshift(_e):L.buffer.push(_e),(L.state&ne)!==0&&he(C)),z(C,L)}se.prototype.isPaused=function(){let C=this._readableState;return C[V]===!0||C.flowing===!1},se.prototype.setEncoding=function(C){let L=new re(C);this._readableState.decoder=L,this._readableState.encoding=this._readableState.decoder.encoding;let _e=this._readableState.buffer,xe="";for(let Se of _e)xe+=L.write(Se);return _e.clear(),xe!==""&&_e.push(xe),this._readableState.length=xe.length,this};var _=1073741824;function A(C){if(C>_)throw new q("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,L){return C<=0||L.length===0&&L.ended?0:(L.state&J)!==0?1:n(C)?L.flowing&&L.length?L.buffer.first().length:L.length:C<=L.length?C:L.ended?L.length:0}se.prototype.read=function(C){v("read",C),C===void 0?C=NaN:s(C)||(C=i(C,10));let L=this._readableState,_e=C;if(C>L.highWaterMark&&(L.highWaterMark=A(C)),C!==0&&(L.state&=~W),C===0&&L.needReadable&&((L.highWaterMark!==0?L.length>=L.highWaterMark:L.length>0)||L.ended))return v("read: emitReadable",L.length,L.ended),L.length===0&&L.ended?nt(this):he(this),null;if(C=U(C,L),C===0&&L.ended)return L.length===0&&nt(this),null;let xe=(L.state&ne)!==0;if(v("need readable",xe),(L.length===0||L.length-C<L.highWaterMark)&&(xe=!0,v("length less than watermark",xe)),L.ended||L.reading||L.destroyed||L.errored||!L.constructed)xe=!1,v("reading, ended or constructing",xe);else if(xe){v("do read"),L.state|=we|j,L.length===0&&(L.state|=ne);try{this._read(L.highWaterMark)}catch(Ue){M(this,Ue)}L.state&=~j,L.reading||(C=U(_e,L))}let Se;return C>0?Se=qt(C,L):Se=null,Se===null?(L.needReadable=L.length<=L.highWaterMark,C=0):(L.length-=C,L.multiAwaitDrain?L.awaitDrainWriters.clear():L.awaitDrainWriters=null),L.length===0&&(L.ended||(L.needReadable=!0),_e!==C&&L.ended&&nt(this)),Se!==null&&!L.errorEmitted&&!L.closeEmitted&&(L.dataEmitted=!0,this.emit("data",Se)),Se};function X(C,L){if(v("onEofChunk"),!L.ended){if(L.decoder){let _e=L.decoder.end();_e&&_e.length&&(L.buffer.push(_e),L.length+=L.objectMode?1:_e.length)}L.ended=!0,L.sync?he(C):(L.needReadable=!1,L.emittedReadable=!0,ke(C))}}function he(C){let L=C._readableState;v("emitReadable",L.needReadable,L.emittedReadable),L.needReadable=!1,L.emittedReadable||(v("emitReadable",L.flowing),L.emittedReadable=!0,t.nextTick(ke,C))}function ke(C){let L=C._readableState;v("emitReadable_",L.destroyed,L.length,L.ended),!L.destroyed&&!L.errored&&(L.length||L.ended)&&(C.emit("readable"),L.emittedReadable=!1),L.needReadable=!L.flowing&&!L.ended&&L.length<=L.highWaterMark,tt(C)}function z(C,L){!L.readingMore&&L.constructed&&(L.readingMore=!0,t.nextTick(ie,C,L))}function ie(C,L){for(;!L.reading&&!L.ended&&(L.length<L.highWaterMark||L.flowing&&L.length===0);){let _e=L.length;if(v("maybeReadMore read 0"),C.read(0),_e===L.length)break}L.readingMore=!1}se.prototype._read=function(C){throw new T("_read()")},se.prototype.pipe=function(C,L){let _e=this,xe=this._readableState;xe.pipes.length===1&&(xe.multiAwaitDrain||(xe.multiAwaitDrain=!0,xe.awaitDrainWriters=new h(xe.awaitDrainWriters?[xe.awaitDrainWriters]:[]))),xe.pipes.push(C),v("pipe count=%d opts=%j",xe.pipes.length,L);let Se=(!L||L.end!==!1)&&C!==t.stdout&&C!==t.stderr?ze:Mt;xe.endEmitted?t.nextTick(Se):_e.once("end",Se),C.on("unpipe",Ue);function Ue(ot,mt){v("onunpipe"),ot===_e&&mt&&mt.hasUnpiped===!1&&(mt.hasUnpiped=!0,tr())}function ze(){v("onend"),C.end()}let Je,er=!1;function tr(){v("cleanup"),C.removeListener("close",it),C.removeListener("finish",kt),Je&&C.removeListener("drain",Je),C.removeListener("error",Pt),C.removeListener("unpipe",Ue),_e.removeListener("end",ze),_e.removeListener("end",Mt),_e.removeListener("data",Vr),er=!0,Je&&xe.awaitDrainWriters&&(!C._writableState||C._writableState.needDrain)&&Je()}function rr(){er||(xe.pipes.length===1&&xe.pipes[0]===C?(v("false write response, pause",0),xe.awaitDrainWriters=C,xe.multiAwaitDrain=!1):xe.pipes.length>1&&xe.pipes.includes(C)&&(v("false write response, pause",xe.awaitDrainWriters.size),xe.awaitDrainWriters.add(C)),_e.pause()),Je||(Je=Ee(_e,C),C.on("drain",Je))}_e.on("data",Vr);function Vr(ot){v("ondata");let mt=C.write(ot);v("dest.write",mt),mt===!1&&rr()}function Pt(ot){if(v("onerror",ot),Mt(),C.removeListener("error",Pt),C.listenerCount("error")===0){let mt=C._writableState||C._readableState;mt&&!mt.errorEmitted?M(C,ot):C.emit("error",ot)}}k(C,"error",Pt);function it(){C.removeListener("finish",kt),Mt()}C.once("close",it);function kt(){v("onfinish"),C.removeListener("close",it),Mt()}C.once("finish",kt);function Mt(){v("unpipe"),_e.unpipe(C)}return C.emit("pipe",_e),C.writableNeedDrain===!0?rr():xe.flowing||(v("pipe resume"),_e.resume()),C};function Ee(C,L){return function(){let _e=C._readableState;_e.awaitDrainWriters===L?(v("pipeOnDrain",1),_e.awaitDrainWriters=null):_e.multiAwaitDrain&&(v("pipeOnDrain",_e.awaitDrainWriters.size),_e.awaitDrainWriters.delete(L)),(!_e.awaitDrainWriters||_e.awaitDrainWriters.size===0)&&C.listenerCount("data")&&C.resume()}}se.prototype.unpipe=function(C){let L=this._readableState,_e={hasUnpiped:!1};if(L.pipes.length===0)return this;if(!C){let Se=L.pipes;L.pipes=[],this.pause();for(let Ue=0;Ue<Se.length;Ue++)Se[Ue].emit("unpipe",this,{hasUnpiped:!1});return this}let xe=r(L.pipes,C);return xe===-1?this:(L.pipes.splice(xe,1),L.pipes.length===0&&this.pause(),C.emit("unpipe",this,_e),this)},se.prototype.on=function(C,L){let _e=y.prototype.on.call(this,C,L),xe=this._readableState;return C==="data"?(xe.readableListening=this.listenerCount("readable")>0,xe.flowing!==!1&&this.resume()):C==="readable"&&!xe.endEmitted&&!xe.readableListening&&(xe.readableListening=xe.needReadable=!0,xe.flowing=!1,xe.emittedReadable=!1,v("on readable",xe.length,xe.reading),xe.length?he(this):xe.reading||t.nextTick(Ie,this)),_e},se.prototype.addListener=se.prototype.on,se.prototype.removeListener=function(C,L){let _e=y.prototype.removeListener.call(this,C,L);return C==="readable"&&t.nextTick(Ae,this),_e},se.prototype.off=se.prototype.removeListener,se.prototype.removeAllListeners=function(C){let L=y.prototype.removeAllListeners.apply(this,arguments);return(C==="readable"||C===void 0)&&t.nextTick(Ae,this),L};function Ae(C){let L=C._readableState;L.readableListening=C.listenerCount("readable")>0,L.resumeScheduled&&L[V]===!1?L.flowing=!0:C.listenerCount("data")>0?C.resume():L.readableListening||(L.flowing=null)}function Ie(C){v("readable nexttick read 0"),C.read(0)}se.prototype.resume=function(){let C=this._readableState;return C.flowing||(v("resume"),C.flowing=!C.readableListening,Oe(this,C)),C[V]=!1,this};function Oe(C,L){L.resumeScheduled||(L.resumeScheduled=!0,t.nextTick(et,C,L))}function et(C,L){v("resume",L.reading),L.reading||C.read(0),L.resumeScheduled=!1,C.emit("resume"),tt(C),L.flowing&&!L.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[V]=!0,this};function tt(C){let L=C._readableState;for(v("flow",L.flowing);L.flowing&&C.read()!==null;);}se.prototype.wrap=function(C){let L=!1;C.on("data",xe=>{!this.push(xe)&&C.pause&&(L=!0,C.pause())}),C.on("end",()=>{this.push(null)}),C.on("error",xe=>{M(this,xe)}),C.on("close",()=>{this.destroy()}),C.on("destroy",()=>{this.destroy()}),this._read=()=>{L&&C.resume&&(L=!1,C.resume())};let _e=a(C);for(let xe=1;xe<_e.length;xe++){let Se=_e[xe];this[Se]===void 0&&typeof C[Se]=="function"&&(this[Se]=C[Se].bind(C))}return this},se.prototype[b]=function(){return He(this)},se.prototype.iterator=function(C){return C!==void 0&&Y(C,"options"),He(this,C)};function He(C,L){typeof C.read!="function"&&(C=se.wrap(C,{objectMode:!0}));let _e=rt(C,L);return _e.stream=C,_e}async function*rt(C,L){let _e=Z;function xe(ze){this===C?(_e(),_e=Z):_e=ze}C.on("readable",xe);let Se,Ue=S(C,{writable:!1},ze=>{Se=ze?O(Se,ze):null,_e(),_e=Z});try{for(;;){let ze=C.destroyed?null:C.read();if(ze!==null)yield ze;else{if(Se)throw Se;if(Se===null)return;await new u(xe)}}}catch(ze){throw Se=O(Se,ze),Se}finally{(Se||L?.destroyOnReturn!==!1)&&(Se===void 0||C._readableState.autoDestroy)?x.destroyer(C,null):(C.off("readable",xe),Ue())}}o(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}}}),o(ve.prototype,{pipesCount:{__proto__:null,get(){return this.pipes.length}},paused:{__proto__:null,get(){return this[V]!==!1},set(C){this[V]=!!C}}}),se._fromList=qt;function qt(C,L){if(L.length===0)return null;let _e;return L.objectMode?_e=L.buffer.shift():!C||C>=L.length?(L.decoder?_e=L.buffer.join(""):L.buffer.length===1?_e=L.buffer.first():_e=L.buffer.concat(L.length),L.buffer.clear()):_e=L.buffer.consume(C,L.decoder),_e}function nt(C){let L=C._readableState;v("endReadable",L.endEmitted),L.endEmitted||(L.ended=!0,t.nextTick(Ye,L,C))}function Ye(C,L){if(v("endReadableNT",C.endEmitted,C.length),!C.errored&&!C.closeEmitted&&!C.endEmitted&&C.length===0){if(C.endEmitted=!0,L.emit("end"),L.writable&&L.allowHalfOpen===!1)t.nextTick(zr,L);else if(C.autoDestroy){let _e=L._writableState;(!_e||_e.autoDestroy&&(_e.finished||_e.writable===!1))&&L.destroy()}}}function zr(C){C.writable&&!C.writableEnded&&!C.destroyed&&C.end()}se.from=function(C,L){return F(se,C,L)};var Ht;function Zt(){return Ht===void 0&&(Ht={}),Ht}se.fromWeb=function(C,L){return Zt().newStreamReadableFromReadableStream(C,L)},se.toWeb=function(C,L){return Zt().newReadableStreamFromStreamReadable(C,L)},se.wrap=function(C,L){var _e,xe;return new se({objectMode:(_e=(xe=C.readableObjectMode)!==null&&xe!==void 0?xe:C.objectMode)!==null&&_e!==void 0?_e:!0,...L,destroy(Se,Ue){x.destroyer(C,Se),Ue(Se)}}).wrap(C)}}),ci=pe((l,e)=>{le(),ue(),ce();var t=At(),{ArrayPrototypeSlice:r,Error:s,FunctionPrototypeSymbolHasInstance:n,ObjectDefineProperty:i,ObjectDefineProperties:o,ObjectSetPrototypeOf:a,StringPrototypeToLowerCase:c,Symbol:u,SymbolHasInstance:h}=Ne();e.exports=Y,Y.WritableState=N;var{EventEmitter:p}=(Et(),Me(bt)),b=li().Stream,{Buffer:f}=(De(),Me(Be)),g=Nt(),{addAbortSignal:y}=cr(),{getHighWaterMark:k,getDefaultHighWaterMark:m}=ur(),{ERR_INVALID_ARG_TYPE:w,ERR_METHOD_NOT_IMPLEMENTED:S,ERR_MULTIPLE_CALLBACK:v,ERR_STREAM_CANNOT_PIPE:E,ERR_STREAM_DESTROYED:x,ERR_STREAM_ALREADY_FINISHED:I,ERR_STREAM_NULL_VALUES:P,ERR_STREAM_WRITE_AFTER_END:O,ERR_UNKNOWN_ENCODING:B}=We().codes,{errorOrDestroy:T}=g;a(Y.prototype,b.prototype),a(Y,b);function q(){}var D=u("kOnFinished");function N(R,$,ee){typeof ee!="boolean"&&(ee=$ instanceof ut()),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 de=!!(R&&R.decodeStrings===!1);this.decodeStrings=!de,this.defaultEncoding=R&&R.defaultEncoding||"utf8",this.length=0,this.writing=!1,this.corked=0,this.sync=!0,this.bufferProcessing=!1,this.onwrite=M.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 ut();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),W(this,ee)})}i(Y,h,{__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 E)};function V(R,$,ee,de){let fe=R._writableState;if(typeof ee=="function")de=ee,ee=fe.defaultEncoding;else{if(!ee)ee=fe.defaultEncoding;else if(ee!=="buffer"&&!f.isEncoding(ee))throw new B(ee);typeof de!="function"&&(de=q)}if($===null)throw new P;if(!fe.objectMode)if(typeof $=="string")fe.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 fe.ending?ye=new O:fe.destroyed&&(ye=new x("write")),ye?(t.nextTick(de,ye),T(R,ye,!0),ye):(fe.pendingcb++,re(R,fe,$,ee,de))}Y.prototype.write=function(R,$,ee){return V(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=c(R)),!f.isEncoding(R))throw new B(R);return this._writableState.defaultEncoding=R,this};function re(R,$,ee,de,fe){let ye=$.objectMode?1:ee.length;$.length+=ye;let H=$.length<$.highWaterMark;return H||($.needDrain=!0),$.writing||$.corked||$.errored||!$.constructed?($.buffered.push({chunk:ee,encoding:de,callback:fe}),$.allBuffers&&de!=="buffer"&&($.allBuffers=!1),$.allNoop&&fe!==q&&($.allNoop=!1)):($.writelen=ye,$.writecb=fe,$.writing=!0,$.sync=!0,R._write(ee,de,$.onwrite),$.sync=!1),H&&!$.errored&&!$.destroyed}function F(R,$,ee,de,fe,ye,H){$.writelen=de,$.writecb=H,$.writing=!0,$.sync=!0,$.destroyed?$.onwrite(new x("write")):ee?R._writev(fe,$.onwrite):R._write(fe,ye,$.onwrite),$.sync=!1}function Z(R,$,ee,de){--$.pendingcb,de(ee),te($),T(R,ee)}function M(R,$){let ee=R._writableState,de=ee.sync,fe=ee.writecb;if(typeof fe!="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=$),de?t.nextTick(Z,R,ee,$,fe):Z(R,ee,$,fe)):(ee.buffered.length>ee.bufferedIndex&&we(R,ee),de?ee.afterWriteTickInfo!==null&&ee.afterWriteTickInfo.cb===fe?ee.afterWriteTickInfo.count++:(ee.afterWriteTickInfo={count:1,cb:fe,stream:R,state:ee},t.nextTick(J,ee.afterWriteTickInfo)):be(R,ee,1,fe))}function J({stream:R,state:$,count:ee,cb:de}){return $.afterWriteTickInfo=null,be(R,$,ee,de)}function be(R,$,ee,de){for(!$.ending&&!R.destroyed&&$.length===0&&$.needDrain&&($.needDrain=!1,R.emit("drain"));ee-- >0;)$.pendingcb--,de();$.destroyed&&te($),W(R,$)}function te(R){if(R.writing)return;for(let fe=R.bufferedIndex;fe<R.buffered.length;++fe){var $;let{chunk:ye,callback:H}=R.buffered[fe],me=R.objectMode?1:ye.length;R.length-=me,H(($=R.errored)!==null&&$!==void 0?$:new x("write"))}let ee=R[D].splice(0);for(let fe=0;fe<ee.length;fe++){var de;ee[fe]((de=R.errored)!==null&&de!==void 0?de:new x("end"))}ae(R)}function we(R,$){if($.corked||$.bufferProcessing||$.destroyed||!$.constructed)return;let{buffered:ee,bufferedIndex:de,objectMode:fe}=$,ye=ee.length-de;if(!ye)return;let H=de;if($.bufferProcessing=!0,ye>1&&R._writev){$.pendingcb-=ye-1;let me=$.allNoop?q:se=>{for(let Te=H;Te<ee.length;++Te)ee[Te].callback(se)},ve=$.allNoop&&H===0?ee:r(ee,H);ve.allBuffers=$.allBuffers,F(R,$,!0,$.length,ve,"",me),ae($)}else{do{let{chunk:me,encoding:ve,callback:se}=ee[H];ee[H++]=null;let Te=fe?1:me.length;F(R,$,!1,Te,me,ve,se)}while(H<ee.length&&!$.writing);H===ee.length?ae($):H>256?(ee.splice(0,H),$.bufferedIndex=0):$.bufferedIndex=H}$.bufferProcessing=!1}Y.prototype._write=function(R,$,ee){if(this._writev)this._writev([{chunk:R,encoding:$}],ee);else throw new S("_write()")},Y.prototype._writev=null,Y.prototype.end=function(R,$,ee){let de=this._writableState;typeof R=="function"?(ee=R,R=null,$=null):typeof $=="function"&&(ee=$,$=null);let fe;if(R!=null){let ye=V(this,R,$);ye instanceof s&&(fe=ye)}return de.corked&&(de.corked=1,this.uncork()),fe||(!de.errored&&!de.ending?(de.ending=!0,W(this,de,!0),de.ended=!0):de.finished?fe=new I("end"):de.destroyed&&(fe=new x("end"))),typeof ee=="function"&&(fe||de.finished?t.nextTick(ee,fe):de[D].push(ee)),this};function G(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 j(R,$){let ee=!1;function de(fe){if(ee){T(R,fe??v());return}if(ee=!0,$.pendingcb--,fe){let ye=$[D].splice(0);for(let H=0;H<ye.length;H++)ye[H](fe);T(R,fe,$.sync)}else G($)&&($.prefinished=!0,R.emit("prefinish"),$.pendingcb++,t.nextTick(K,R,$))}$.sync=!0,$.pendingcb++;try{R._final(de)}catch(fe){de(fe)}$.sync=!1}function ne(R,$){!$.prefinished&&!$.finalCalled&&(typeof R._final=="function"&&!$.destroyed?($.finalCalled=!0,j(R,$)):($.prefinished=!0,R.emit("prefinish")))}function W(R,$,ee){G($)&&(ne(R,$),$.pendingcb===0&&(ee?($.pendingcb++,t.nextTick((de,fe)=>{G(fe)?K(de,fe):fe.pendingcb--},R,$)):G($)&&($.pendingcb++,K(R,$))))}function K(R,$){$.pendingcb--,$.finished=!0;let ee=$[D].splice(0);for(let de=0;de<ee.length;de++)ee[de]();if(R.emit("finish"),$.autoDestroy){let de=R._readableState;(!de||de.autoDestroy&&(de.endEmitted||de.readable===!1))&&R.destroy()}}o(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 ge;function oe(){return ge===void 0&&(ge={}),ge}Y.fromWeb=function(R,$){return oe().newStreamWritableFromWritableStream(R,$)},Y.toWeb=function(R){return oe().newWritableStreamFromStreamWritable(R)}}),Rc=pe((l,e)=>{le(),ue(),ce();var t=At(),r=(De(),Me(Be)),{isReadable:s,isWritable:n,isIterable:i,isNodeStream:o,isReadableNodeStream:a,isWritableNodeStream:c,isDuplexNodeStream:u,isReadableStream:h,isWritableStream:p}=ct(),b=yt(),{AbortError:f,codes:{ERR_INVALID_ARG_TYPE:g,ERR_INVALID_RETURN_VALUE:y}}=We(),{destroyer:k}=Nt(),m=ut(),w=hr(),S=ci(),{createDeferredPromise:v}=Ge(),E=Zo(),x=globalThis.Blob||r.Blob,I=typeof x<"u"?function(D){return D instanceof x}:function(D){return!1},P=globalThis.AbortController||Gt().AbortController,{FunctionPrototypeCall:O}=Ne(),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(a(N))return q({readable:N});if(c(N))return q({writable:N});if(o(N))return q({writable:!1,readable:!1});if(h(N))return q({readable:w.fromWeb(N)});if(p(N))return q({writable:S.fromWeb(N)});if(typeof N=="function"){let{value:V,write:re,final:F,destroy:Z}=T(N);if(i(V))return E(B,V,{objectMode:!0,write:re,final:F,destroy:Z});let M=V?.then;if(typeof M=="function"){let J,be=O(M,V,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,V)}if(I(N))return D(N.arrayBuffer());if(i(N))return E(B,N,{objectMode:!0,writable:!1});if(h(N?.readable)&&p(N?.writable))return B.fromWeb(N);if(typeof N?.writable=="object"||typeof N?.readable=="object"){let V=N!=null&&N.readable?a(N?.readable)?N?.readable:D(N.readable):void 0,re=N!=null&&N.writable?c(N?.writable)?N?.writable:D(N.writable):void 0;return q({readable:V,writable:re})}let Y=N?.then;if(typeof Y=="function"){let V;return O(Y,N,re=>{re!=null&&V.push(re),V.push(null)},re=>{k(V,re)}),V=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 P,V=Y.signal;return{value:D((async function*(){for(;;){let re=N;N=null;let{chunk:F,done:Z,cb:M}=await re;if(t.nextTick(M),Z)return;if(V.aborted)throw new f(void 0,{cause:V.reason});({promise:N,resolve:ae}=v()),yield F}})(),{signal:V}),write(re,F,Z){let M=ae;ae=null,M({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 q(D){let N=D.readable&&typeof D.readable.read!="function"?w.wrap(D.readable):D.readable,ae=D.writable,Y=!!s(N),V=!!n(ae),re,F,Z,M,J;function be(te){let we=M;M=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:V}),V&&(b(ae,te=>{V=!1,te&&k(N,te),be(te)}),J._write=function(te,we,G){ae.write(te,we)?G():re=G},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&&M!==null&&(te=new f),Z=null,re=null,F=null,M===null?we(te):(M=we,k(ae,te),k(N,te))},J}}),ut=pe((l,e)=>{le(),ue(),ce();var{ObjectDefineProperties:t,ObjectGetOwnPropertyDescriptor:r,ObjectKeys:s,ObjectSetPrototypeOf:n}=Ne();e.exports=a;var i=hr(),o=ci();n(a.prototype,i.prototype),n(a,i);{let p=s(o.prototype);for(let b=0;b<p.length;b++){let f=p[b];a.prototype[f]||(a.prototype[f]=o.prototype[f])}}function a(p){if(!(this instanceof a))return new a(p);i.call(this,p),o.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(a.prototype,{writable:{__proto__:null,...r(o.prototype,"writable")},writableHighWaterMark:{__proto__:null,...r(o.prototype,"writableHighWaterMark")},writableObjectMode:{__proto__:null,...r(o.prototype,"writableObjectMode")},writableBuffer:{__proto__:null,...r(o.prototype,"writableBuffer")},writableLength:{__proto__:null,...r(o.prototype,"writableLength")},writableFinished:{__proto__:null,...r(o.prototype,"writableFinished")},writableCorked:{__proto__:null,...r(o.prototype,"writableCorked")},writableEnded:{__proto__:null,...r(o.prototype,"writableEnded")},writableNeedDrain:{__proto__:null,...r(o.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 c;function u(){return c===void 0&&(c={}),c}a.fromWeb=function(p,b){return u().newStreamDuplexFromReadableWritablePair(p,b)},a.toWeb=function(p){return u().newReadableWritablePairFromDuplex(p)};var h;a.from=function(p){return h||(h=Rc()),h(p,"body")}}),es=pe((l,e)=>{le(),ue(),ce();var{ObjectSetPrototypeOf:t,Symbol:r}=Ne();e.exports=a;var{ERR_METHOD_NOT_IMPLEMENTED:s}=We().codes,n=ut(),{getHighWaterMark:i}=ur();t(a.prototype,n.prototype),t(a,n);var o=r("kCallback");function a(h){if(!(this instanceof a))return new a(h);let p=h?i(this,h,"readableHighWaterMark",!0):null;p===0&&(h={...h,highWaterMark:null,readableHighWaterMark:p,writableHighWaterMark:h.writableHighWaterMark||0}),n.call(this,h),this._readableState.sync=!1,this[o]=null,h&&(typeof h.transform=="function"&&(this._transform=h.transform),typeof h.flush=="function"&&(this._flush=h.flush)),this.on("prefinish",u)}function c(h){typeof this._flush=="function"&&!this.destroyed?this._flush((p,b)=>{if(p){h?h(p):this.destroy(p);return}b!=null&&this.push(b),this.push(null),h&&h()}):(this.push(null),h&&h())}function u(){this._final!==c&&c.call(this)}a.prototype._final=c,a.prototype._transform=function(h,p,b){throw new s("_transform()")},a.prototype._write=function(h,p,b){let f=this._readableState,g=this._writableState,y=f.length;this._transform(h,p,(k,m)=>{if(k){b(k);return}m!=null&&this.push(m),g.ended||y===f.length||f.length<f.highWaterMark?b():this[o]=b})},a.prototype._read=function(){if(this[o]){let h=this[o];this[o]=null,h()}}}),ts=pe((l,e)=>{le(),ue(),ce();var{ObjectSetPrototypeOf:t}=Ne();e.exports=s;var r=es();t(s.prototype,r.prototype),t(s,r);function s(n){if(!(this instanceof s))return new s(n);r.call(this,n)}s.prototype._transform=function(n,i,o){o(null,n)}}),ui=pe((l,e)=>{le(),ue(),ce();var t=At(),{ArrayIsArray:r,Promise:s,SymbolAsyncIterator:n,SymbolDispose:i}=Ne(),o=yt(),{once:a}=Ge(),c=Nt(),u=ut(),{aggregateTwoErrors:h,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}=Yt(),{isIterable:S,isReadable:v,isReadableNodeStream:E,isNodeStream:x,isTransformStream:I,isWebStream:P,isReadableStream:O,isReadableFinished:B}=ct(),T=globalThis.AbortController||Gt().AbortController,q,D,N;function ae(te,we,G){let j=!1;te.on("close",()=>{j=!0});let ne=o(te,{readable:we,writable:G},W=>{j=!W});return{destroy:W=>{j||(j=!0,c.destroyer(te,W||new g("pipe")))},cleanup:ne}}function Y(te){return m(te[te.length-1],"streams[stream.length - 1]"),te.pop()}function V(te){if(S(te))return te;if(E(te))return re(te);throw new p("val",["Readable","Iterable","AsyncIterable"],te)}async function*re(te){D||(D=hr()),yield*D.prototype[n].call(te)}async function F(te,we,G,{end:j}){let ne,W=null,K=oe=>{if(oe&&(ne=oe),W){let R=W;W=null,R()}},Q=()=>new s((oe,R)=>{ne?R(ne):W=()=>{ne?R(ne):oe()}});we.on("drain",K);let ge=o(we,{readable:!1},K);try{we.writableNeedDrain&&await Q();for await(let oe of te)we.write(oe)||await Q();j&&(we.end(),await Q()),G()}catch(oe){G(ne!==oe?h(ne,oe):oe)}finally{ge(),we.off("drain",K)}}async function Z(te,we,G,{end:j}){I(we)&&(we=we.writable);let ne=we.getWriter();try{for await(let W of te)await ne.ready,ne.write(W).catch(()=>{});await ne.ready,j&&await ne.close(),G()}catch(W){try{await ne.abort(W),G(W)}catch(K){G(K)}}}function M(...te){return J(te,a(Y(te)))}function J(te,we,G){if(te.length===1&&r(te[0])&&(te=te[0]),te.length<2)throw new f("streams");let j=new T,ne=j.signal,W=G?.signal,K=[];w(W,"options.signal");function Q(){fe(new k)}N=N||Ge().addAbortListener;let ge;W&&(ge=N(W,Q));let oe,R,$=[],ee=0;function de(ve){fe(ve,--ee===0)}function fe(ve,se){var Te;if(ve&&(!oe||oe.code==="ERR_STREAM_PREMATURE_CLOSE")&&(oe=ve),!(!oe&&!se)){for(;$.length;)$.shift()(oe);(Te=ge)===null||Te===void 0||Te[i](),j.abort(),se&&(oe||K.forEach(d=>d()),t.nextTick(we,oe,R))}}let ye;for(let ve=0;ve<te.length;ve++){let se=te[ve],Te=ve<te.length-1,d=ve>0,_=Te||G?.end!==!1,A=ve===te.length-1;if(x(se)){let U=function(X){X&&X.name!=="AbortError"&&X.code!=="ERR_STREAM_PREMATURE_CLOSE"&&de(X)};if(_){let{destroy:X,cleanup:he}=ae(se,Te,d);$.push(X),v(se)&&A&&K.push(he)}se.on("error",U),v(se)&&A&&K.push(()=>{se.removeListener("error",U)})}if(ve===0)if(typeof se=="function"){if(ye=se({signal:ne}),!S(ye))throw new b("Iterable, AsyncIterable or Stream","source",ye)}else S(se)||E(se)||I(se)?ye=se:ye=u.from(se);else if(typeof se=="function"){if(I(ye)){var H;ye=V((H=ye)===null||H===void 0?void 0:H.readable)}else ye=V(ye);if(ye=se(ye,{signal:ne}),Te){if(!S(ye,!0))throw new b("AsyncIterable",`transform[${ve-1}]`,ye)}else{var me;q||(q=ts());let U=new q({objectMode:!0}),X=(me=ye)===null||me===void 0?void 0:me.then;if(typeof X=="function")ee++,X.call(ye,z=>{R=z,z!=null&&U.write(z),_&&U.end(),t.nextTick(de)},z=>{U.destroy(z),t.nextTick(de,z)});else if(S(ye,!0))ee++,F(ye,U,de,{end:_});else if(O(ye)||I(ye)){let z=ye.readable||ye;ee++,F(z,U,de,{end:_})}else throw new b("AsyncIterable or Promise","destination",ye);ye=U;let{destroy:he,cleanup:ke}=ae(ye,!1,!0);$.push(he),A&&K.push(ke)}}else if(x(se)){if(E(ye)){ee+=2;let U=be(ye,se,de,{end:_});v(se)&&A&&K.push(U)}else if(I(ye)||O(ye)){let U=ye.readable||ye;ee++,F(U,se,de,{end:_})}else if(S(ye))ee++,F(ye,se,de,{end:_});else throw new p("val",["Readable","Iterable","AsyncIterable","ReadableStream","TransformStream"],ye);ye=se}else if(P(se)){if(E(ye))ee++,Z(V(ye),se,de,{end:_});else if(O(ye)||S(ye))ee++,Z(ye,se,de,{end:_});else if(I(ye))ee++,Z(ye.readable,se,de,{end:_});else throw new p("val",["Readable","Iterable","AsyncIterable","ReadableStream","TransformStream"],ye);ye=se}else ye=u.from(se)}return(ne!=null&&ne.aborted||W!=null&&W.aborted)&&t.nextTick(Q),ye}function be(te,we,G,{end:j}){let ne=!1;if(we.on("close",()=>{ne||G(new y)}),te.pipe(we,{end:!1}),j){let W=function(){ne=!0,we.end()};B(te)?t.nextTick(W):te.once("end",W)}else G();return o(te,{readable:!0,writable:!1},W=>{let K=te._readableState;W&&W.code==="ERR_STREAM_PREMATURE_CLOSE"&&K&&K.ended&&!K.errored&&!K.errorEmitted?te.once("end",G).once("error",G):G(W)}),o(we,{readable:!1,writable:!0},G)}e.exports={pipelineImpl:J,pipeline:M}}),rs=pe((l,e)=>{le(),ue(),ce();var{pipeline:t}=ui(),r=ut(),{destroyer:s}=Nt(),{isNodeStream:n,isReadable:i,isWritable:o,isWebStream:a,isTransformStream:c,isWritableStream:u,isReadableStream:h}=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])&&!a(y[T]))){if(T<y.length-1&&!(i(y[T])||h(y[T])||c(y[T])))throw new b(`streams[${T}]`,k[T],"must be readable");if(T>0&&!(o(y[T])||u(y[T])||c(y[T])))throw new b(`streams[${T}]`,k[T],"must be writable")}let m,w,S,v,E;function x(T){let q=v;v=null,q?q(T):T?E.destroy(T):!B&&!O&&E.destroy()}let I=y[0],P=t(y,x),O=!!(o(I)||u(I)||c(I)),B=!!(i(P)||h(P)||c(P));if(E=new r({writableObjectMode:!!(I!=null&&I.writableObjectMode),readableObjectMode:!!(P!=null&&P.readableObjectMode),writable:O,readable:B}),O){if(n(I))E._write=function(q,D,N){I.write(q,D)?N():m=N},E._final=function(q){I.end(),w=q},I.on("drain",function(){if(m){let q=m;m=null,q()}});else if(a(I)){let q=(c(I)?I.writable:I).getWriter();E._write=async function(D,N,ae){try{await q.ready,q.write(D).catch(()=>{}),ae()}catch(Y){ae(Y)}},E._final=async function(D){try{await q.ready,q.close().catch(()=>{}),w=D}catch(N){D(N)}}}let T=c(P)?P.readable:P;g(T,()=>{if(w){let q=w;w=null,q()}})}if(B){if(n(P))P.on("readable",function(){if(S){let T=S;S=null,T()}}),P.on("end",function(){E.push(null)}),E._read=function(){for(;;){let T=P.read();if(T===null){S=E._read;return}if(!E.push(T))return}};else if(a(P)){let T=(c(P)?P.readable:P).getReader();E._read=async function(){for(;;)try{let{value:q,done:D}=await T.read();if(!E.push(q))return;if(D){E.push(null);return}}catch{return}}}}return E._destroy=function(T,q){!T&&v!==null&&(T=new p),S=null,m=null,w=null,v===null?q(T):(v=q,n(P)&&s(P,T))},E}}),Lc=pe((l,e)=>{le(),ue(),ce();var t=globalThis.AbortController||Gt().AbortController,{codes:{ERR_INVALID_ARG_VALUE:r,ERR_INVALID_ARG_TYPE:s,ERR_MISSING_ARGS:n,ERR_OUT_OF_RANGE:i},AbortError:o}=We(),{validateAbortSignal:a,validateInteger:c,validateObject:u}=Yt(),h=Ne().Symbol("kWeak"),p=Ne().Symbol("kResistStopPropagation"),{finished:b}=yt(),f=rs(),{addAbortSignalNoValidate:g}=cr(),{isWritable:y,isNodeStream:k}=ct(),{deprecate:m}=Ge(),{ArrayPrototypePush:w,Boolean:S,MathFloor:v,Number:E,NumberIsNaN:x,Promise:I,PromiseReject:P,PromiseResolve:O,PromisePrototypeThen:B,Symbol:T}=Ne(),q=T("kEmpty"),D=T("kEof");function N(W,K){if(K!=null&&u(K,"options"),K?.signal!=null&&a(K.signal,"options.signal"),k(W)&&!y(W))throw new r("stream",W,"must be writable");let Q=f(this,W);return K!=null&&K.signal&&g(K.signal,Q),Q}function ae(W,K){if(typeof W!="function")throw new s("fn",["Function","AsyncFunction"],W);K!=null&&u(K,"options"),K?.signal!=null&&a(K.signal,"options.signal");let Q=1;K?.concurrency!=null&&(Q=v(K.concurrency));let ge=Q-1;return K?.highWaterMark!=null&&(ge=v(K.highWaterMark)),c(Q,"options.concurrency",1),c(ge,"options.highWaterMark",0),ge+=Q,(async function*(){let oe=Ge().AbortSignalAny([K?.signal].filter(S)),R=this,$=[],ee={signal:oe},de,fe,ye=!1,H=0;function me(){ye=!0,ve()}function ve(){H-=1,se()}function se(){fe&&!ye&&H<Q&&$.length<ge&&(fe(),fe=null)}async function Te(){try{for await(let d of R){if(ye)return;if(oe.aborted)throw new o;try{if(d=W(d,ee),d===q)continue;d=O(d)}catch(_){d=P(_)}H+=1,B(d,ve,me),$.push(d),de&&(de(),de=null),!ye&&($.length>=ge||H>=Q)&&await new I(_=>{fe=_})}$.push(D)}catch(d){let _=P(d);B(_,ve,me),$.push(_)}finally{ye=!0,de&&(de(),de=null)}}Te();try{for(;;){for(;$.length>0;){let d=await $[0];if(d===D)return;if(oe.aborted)throw new o;d!==q&&(yield d),$.shift(),se()}await new I(d=>{de=d})}}finally{ye=!0,fe&&(fe(),fe=null)}}).call(this)}function Y(W=void 0){return W!=null&&u(W,"options"),W?.signal!=null&&a(W.signal,"options.signal"),(async function*(){let K=0;for await(let ge of this){var Q;if(W!=null&&(Q=W.signal)!==null&&Q!==void 0&&Q.aborted)throw new o({cause:W.signal.reason});yield[K++,ge]}}).call(this)}async function V(W,K=void 0){for await(let Q of M.call(this,W,K))return!0;return!1}async function re(W,K=void 0){if(typeof W!="function")throw new s("fn",["Function","AsyncFunction"],W);return!await V.call(this,async(...Q)=>!await W(...Q),K)}async function F(W,K){for await(let Q of M.call(this,W,K))return Q}async function Z(W,K){if(typeof W!="function")throw new s("fn",["Function","AsyncFunction"],W);async function Q(ge,oe){return await W(ge,oe),q}for await(let ge of ae.call(this,Q,K));}function M(W,K){if(typeof W!="function")throw new s("fn",["Function","AsyncFunction"],W);async function Q(ge,oe){return await W(ge,oe)?ge:q}return ae.call(this,Q,K)}var J=class extends n{constructor(){super("reduce"),this.message="Reduce of an empty stream requires an initial value"}};async function be(W,K,Q){var ge;if(typeof W!="function")throw new s("reducer",["Function","AsyncFunction"],W);Q!=null&&u(Q,"options"),Q?.signal!=null&&a(Q.signal,"options.signal");let oe=arguments.length>1;if(Q!=null&&(ge=Q.signal)!==null&&ge!==void 0&&ge.aborted){let fe=new o(void 0,{cause:Q.signal.reason});throw this.once("error",()=>{}),await b(this.destroy(fe)),fe}let R=new t,$=R.signal;if(Q!=null&&Q.signal){let fe={once:!0,[h]:this,[p]:!0};Q.signal.addEventListener("abort",()=>R.abort(),fe)}let ee=!1;try{for await(let fe of this){var de;if(ee=!0,Q!=null&&(de=Q.signal)!==null&&de!==void 0&&de.aborted)throw new o;oe?K=await W(K,fe,{signal:$}):(K=fe,oe=!0)}if(!ee&&!oe)throw new J}finally{R.abort()}return K}async function te(W){W!=null&&u(W,"options"),W?.signal!=null&&a(W.signal,"options.signal");let K=[];for await(let ge of this){var Q;if(W!=null&&(Q=W.signal)!==null&&Q!==void 0&&Q.aborted)throw new o(void 0,{cause:W.signal.reason});w(K,ge)}return K}function we(W,K){let Q=ae.call(this,W,K);return(async function*(){for await(let ge of Q)yield*ge}).call(this)}function G(W){if(W=E(W),x(W))return 0;if(W<0)throw new i("number",">= 0",W);return W}function j(W,K=void 0){return K!=null&&u(K,"options"),K?.signal!=null&&a(K.signal,"options.signal"),W=G(W),(async function*(){var Q;if(K!=null&&(Q=K.signal)!==null&&Q!==void 0&&Q.aborted)throw new o;for await(let oe of this){var ge;if(K!=null&&(ge=K.signal)!==null&&ge!==void 0&&ge.aborted)throw new o;W--<=0&&(yield oe)}}).call(this)}function ne(W,K=void 0){return K!=null&&u(K,"options"),K?.signal!=null&&a(K.signal,"options.signal"),W=G(W),(async function*(){var Q;if(K!=null&&(Q=K.signal)!==null&&Q!==void 0&&Q.aborted)throw new o;for await(let oe of this){var ge;if(K!=null&&(ge=K.signal)!==null&&ge!==void 0&&ge.aborted)throw new o;if(W-- >0&&(yield oe),W<=0)return}}).call(this)}e.exports.streamReturningOperators={asIndexedPairs:m(Y,"readable.asIndexedPairs will be removed in a future version."),drop:j,filter:M,flatMap:we,map:ae,take:ne,compose:N},e.exports.promiseReturningOperators={every:re,forEach:Z,reduce:be,toArray:te,some:V,find:F}}),ns=pe((l,e)=>{le(),ue(),ce();var{ArrayPrototypePop:t,Promise:r}=Ne(),{isIterable:s,isNodeStream:n,isWebStream:i}=ct(),{pipelineImpl:o}=ui(),{finished:a}=yt();is();function c(...u){return new r((h,p)=>{let b,f,g=u[u.length-1];if(g&&typeof g=="object"&&!n(g)&&!s(g)&&!i(g)){let y=t(u);b=y.signal,f=y.end}o(u,(y,k)=>{y?p(y):h(k)},{signal:b,end:f})})}e.exports={finished:a,pipeline:c}}),is=pe((l,e)=>{le(),ue(),ce();var{Buffer:t}=(De(),Me(Be)),{ObjectDefineProperty:r,ObjectKeys:s,ReflectApply:n}=Ne(),{promisify:{custom:i}}=Ge(),{streamReturningOperators:o,promiseReturningOperators:a}=Lc(),{codes:{ERR_ILLEGAL_CONSTRUCTOR:c}}=We(),u=rs(),{setDefaultHighWaterMark:h,getDefaultHighWaterMark:p}=ur(),{pipeline:b}=ui(),{destroyer:f}=Nt(),g=yt(),y=ns(),k=ct(),m=e.exports=li().Stream;m.isDestroyed=k.isDestroyed,m.isDisturbed=k.isDisturbed,m.isErrored=k.isErrored,m.isReadable=k.isReadable,m.isWritable=k.isWritable,m.Readable=hr();for(let S of s(o)){let v=function(...x){if(new.target)throw c();return m.Readable.from(n(E,this,x))},E=o[S];r(v,"name",{__proto__:null,value:E.name}),r(v,"length",{__proto__:null,value:E.length}),r(m.Readable.prototype,S,{__proto__:null,value:v,enumerable:!1,configurable:!0,writable:!0})}for(let S of s(a)){let v=function(...x){if(new.target)throw c();return n(E,this,x)},E=a[S];r(v,"name",{__proto__:null,value:E.name}),r(v,"length",{__proto__:null,value:E.length}),r(m.Readable.prototype,S,{__proto__:null,value:v,enumerable:!1,configurable:!0,writable:!0})}m.Writable=ci(),m.Duplex=ut(),m.Transform=es(),m.PassThrough=ts(),m.pipeline=b;var{addAbortSignal:w}=cr();m.addAbortSignal=w,m.finished=g,m.destroy=f,m.compose=u,m.setDefaultHighWaterMark=h,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(S){return S instanceof Uint8Array},m._uint8ArrayToBuffer=function(S){return t.from(S.buffer,S.byteOffset,S.byteLength)}}),It=pe((l,e)=>{le(),ue(),ce();var t=is(),r=ns(),s=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=s,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}),jc=pe((l,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 s=function(){};s.prototype=r.prototype,t.prototype=new s,t.prototype.constructor=t}}}),Nc=pe((l,e)=>{le(),ue(),ce();var{Buffer:t}=(De(),Me(Be)),r=Symbol.for("BufferList");function s(n){if(!(this instanceof s))return new s(n);s._init.call(this,n)}s._init=function(n){Object.defineProperty(this,r,{value:!0}),this._bufs=[],this.length=0,n&&this.append(n)},s.prototype._new=function(n){return new s(n)},s.prototype._offset=function(n){if(n===0)return[0,0];let i=0;for(let o=0;o<this._bufs.length;o++){let a=i+this._bufs[o].length;if(n<a||o===this._bufs.length-1)return[o,n-i];i=a}},s.prototype._reverseOffset=function(n){let i=n[0],o=n[1];for(let a=0;a<i;a++)o+=this._bufs[a].length;return o},s.prototype.getBuffers=function(){return this._bufs},s.prototype.get=function(n){if(n>this.length||n<0)return;let i=this._offset(n);return this._bufs[i[0]][i[1]]},s.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)},s.prototype.copy=function(n,i,o,a){if((typeof o!="number"||o<0)&&(o=0),(typeof a!="number"||a>this.length)&&(a=this.length),o>=this.length||a<=0)return n||t.alloc(0);let c=!!n,u=this._offset(o),h=a-o,p=h,b=c&&i||0,f=u[1];if(o===0&&a===this.length){if(!c)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 c?this._bufs[u[0]].copy(n,i,f,f+p):this._bufs[u[0]].slice(f,f+p);c||(n=t.allocUnsafe(h));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},s.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 o=this._offset(n),a=this._offset(i),c=this._bufs.slice(o[0],a[0]+1);return a[1]===0?c.pop():c[c.length-1]=c[c.length-1].slice(0,a[1]),o[1]!==0&&(c[0]=c[0].slice(o[1])),this._new(c)},s.prototype.toString=function(n,i,o){return this.slice(i,o).toString(n)},s.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},s.prototype.duplicate=function(){let n=this._new();for(let i=0;i<this._bufs.length;i++)n.append(this._bufs[i]);return n},s.prototype.append=function(n){return this._attach(n,s.prototype._appendBuffer)},s.prototype.prepend=function(n){return this._attach(n,s.prototype._prependBuffer,!0)},s.prototype._attach=function(n,i,o){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[a,c]=o?[n.length-1,-1]:[0,1];for(let u=a;u>=0&&u<n.length;u+=c)this._attach(n[u],i,o)}else if(this._isBufferList(n)){let[a,c]=o?[n._bufs.length-1,-1]:[0,1];for(let u=a;u>=0&&u<n._bufs.length;u+=c)this._attach(n._bufs[u],i,o)}else typeof n=="number"&&(n=n.toString()),i.call(this,t.from(n));return this},s.prototype._appendBuffer=function(n){this._bufs.push(n),this.length+=n.length},s.prototype._prependBuffer=function(n){this._bufs.unshift(n),this.length+=n.length},s.prototype.indexOf=function(n,i,o){if(o===void 0&&typeof i=="string"&&(o=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,o):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 a=this._offset(i),c=a[0],u=a[1];for(;c<this._bufs.length;c++){let h=this._bufs[c];for(;u<h.length;)if(h.length-u>=n.length){let p=h.indexOf(n,u);if(p!==-1)return this._reverseOffset([c,p]);u=h.length-n.length+1}else{let p=this._reverseOffset([c,u]);if(this._match(p,n))return p;u++}u=0}return-1},s.prototype._match=function(n,i){if(this.length-n<i.length)return!1;for(let o=0;o<i.length;o++)if(this.get(n+o)!==i[o])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(o){n[o]===null?s.prototype[o]=function(a,c){return this.slice(a,a+c)[o](0,c)}:s.prototype[o]=function(a=0){return this.slice(a,a+n[o])[o](0)}})(i)})(),s.prototype._isBufferList=function(n){return n instanceof s||s.isBufferList(n)},s.isBufferList=function(n){return n!=null&&n[r]},e.exports=s}),Uc=pe((l,e)=>{le(),ue(),ce();var t=It().Duplex,r=jc(),s=Nc();function n(i){if(!(this instanceof n))return new n(i);if(typeof i=="function"){this._callback=i;let o=(function(a){this._callback&&(this._callback(a),this._callback=null)}).bind(this);this.on("pipe",function(a){a.on("error",o)}),this.on("unpipe",function(a){a.removeListener("error",o)}),i=null}s._init.call(this,i),t.call(this)}r(n,t),Object.assign(n.prototype,s.prototype),n.prototype._new=function(i){return new n(i)},n.prototype._write=function(i,o,a){this._appendBuffer(i),typeof a=="function"&&a()},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,o){this._bufs.length=0,this.length=0,o(i)},n.prototype._isBufferList=function(i){return i instanceof n||i instanceof s||n.isBufferList(i)},n.isBufferList=s.isBufferList,e.exports=n,e.exports.BufferListStream=n,e.exports.BufferList=s}),Bc=pe((l,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}),os=pe((l,e)=>{le(),ue(),ce();var t=e.exports,{Buffer:r}=(De(),Me(Be));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 s(n){return[0,1,2].map(i=>[0,1].map(o=>[0,1].map(a=>{let c=r.alloc(1);return c.writeUInt8(t.codes[n]<<t.CMD_SHIFT|(o?t.DUP_MASK:0)|i<<t.QOS_SHIFT|a,0,!0),c})))}t.PUBLISH_HEADER=s("publish"),t.SUBSCRIBE_HEADER=s("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=s("unsubscribe"),t.ACKS={unsuback:s("unsuback"),puback:s("puback"),pubcomp:s("pubcomp"),pubrel:s("pubrel"),pubrec:s("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"}}),Dc=pe((l,e)=>{le(),ue(),ce();var t=1e3,r=t*60,s=r*60,n=s*24,i=n*7,o=n*365.25;e.exports=function(p,b){b=b||{};var f=typeof p;if(f==="string"&&p.length>0)return a(p);if(f==="number"&&isFinite(p))return b.long?u(p):c(p);throw new Error("val is not a non-empty string or a valid number. val="+JSON.stringify(p))};function a(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*o;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*s;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 c(p){var b=Math.abs(p);return b>=n?Math.round(p/n)+"d":b>=s?Math.round(p/s)+"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?h(p,b,n,"day"):b>=s?h(p,b,s,"hour"):b>=r?h(p,b,r,"minute"):b>=t?h(p,b,t,"second"):p+" ms"}function h(p,b,f,g){var y=b>=f*1.5;return Math.round(p/f)+" "+g+(y?"s":"")}}),Fc=pe((l,e)=>{le(),ue(),ce();function t(r){n.debug=n,n.default=n,n.coerce=h,n.disable=c,n.enable=o,n.enabled=u,n.humanize=Dc(),n.destroy=p,Object.keys(r).forEach(b=>{n[b]=r[b]}),n.names=[],n.skips=[],n.formatters={};function s(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=s;function n(b){let f,g=null,y,k;function m(...w){if(!m.enabled)return;let S=m,v=Number(new Date),E=v-(f||v);S.diff=E,S.prev=f,S.curr=v,f=v,w[0]=n.coerce(w[0]),typeof w[0]!="string"&&w.unshift("%O");let x=0;w[0]=w[0].replace(/%([a-zA-Z%])/g,(I,P)=>{if(I==="%%")return"%";x++;let O=n.formatters[P];if(typeof O=="function"){let B=w[x];I=O.call(S,B),w.splice(x,1),x--}return I}),n.formatArgs.call(S,w),(S.log||n.log).apply(S,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 o(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 a(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 c(){let b=[...n.names,...n.skips.map(f=>"-"+f)].join(",");return n.enable(""),b}function u(b){for(let f of n.skips)if(a(b,f))return!1;for(let f of n.names)if(a(b,f))return!0;return!1}function h(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}),ht=pe((l,e)=>{le(),ue(),ce(),l.formatArgs=r,l.save=s,l.load=n,l.useColors=t,l.storage=i(),l.destroy=(()=>{let a=!1;return()=>{a||(a=!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`."))}})(),l.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 a;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&&(a=navigator.userAgent.toLowerCase().match(/firefox\/(\d+)/))&&parseInt(a[1],10)>=31||typeof navigator<"u"&&navigator.userAgent&&navigator.userAgent.toLowerCase().match(/applewebkit\/(\d+)/)}function r(a){if(a[0]=(this.useColors?"%c":"")+this.namespace+(this.useColors?" %c":" ")+a[0]+(this.useColors?"%c ":" ")+"+"+e.exports.humanize(this.diff),!this.useColors)return;let c="color: "+this.color;a.splice(1,0,c,"color: inherit");let u=0,h=0;a[0].replace(/%[a-zA-Z%]/g,p=>{p!=="%%"&&(u++,p==="%c"&&(h=u))}),a.splice(h,0,c)}l.log=console.debug||console.log||(()=>{});function s(a){try{a?l.storage.setItem("debug",a):l.storage.removeItem("debug")}catch{}}function n(){let a;try{a=l.storage.getItem("debug")||l.storage.getItem("DEBUG")}catch{}return!a&&typeof Le<"u"&&"env"in Le&&(a=Le.env.DEBUG),a}function i(){try{return localStorage}catch{}}e.exports=Fc()(l);var{formatters:o}=e.exports;o.j=function(a){try{return JSON.stringify(a)}catch(c){return"[UnexpectedJSONParseError]: "+c.message}}}),$c=pe((l,e)=>{le(),ue(),ce();var t=Uc(),{EventEmitter:r}=(Et(),Me(bt)),s=Bc(),n=os(),i=ht()("mqtt-packet:parser"),o=class wo extends r{constructor(){super(),this.parser=this.constructor.parser}static parser(c){return this instanceof wo?(this.settings=c||{},this._states=["_parseHeader","_parseLength","_parsePayload","_newPacket"],this._resetState(),this):new wo().parser(c)}_resetState(){i("_resetState: resetting packet, error, _list, and _stateCounter"),this.packet=new s,this.error=null,this._list=t(),this._stateCounter=0}parse(c){for(this.error&&this._resetState(),this._list.append(c),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 c=this._list.readUInt8(0),u=c>>n.CMD_SHIFT;this.packet.cmd=n.types[u];let h=c&15,p=n.requiredHeaderFlags[u];return p!=null&&h!==p?this._emitError(new Error(n.requiredHeaderFlagsErrors[u])):(this.packet.retain=(c&n.RETAIN_MASK)!==0,this.packet.qos=c>>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=(c&n.DUP_MASK)!==0,i("_parseHeader: packet: %o",this.packet),this._list.consume(1),!0))}_parseLength(){let c=this._parseVarByteNum(!0);return c&&(this.packet.length=c.value,this._list.consume(c.bytes)),i("_parseLength %d",c.value),!!c}_parsePayload(){i("_parsePayload: payload %O",this._list);let c=!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"))}c=!0}return i("_parsePayload complete result: %s",c),c}_parseConnect(){i("_parseConnect");let c,u,h,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(c=this._parseString(),c===null)return this._emitError(new Error("Cannot parse will topic"));if(f.will.topic=c,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(h=this._parseBuffer(),h===null)return this._emitError(new Error("Cannot parse password"));f.password=h}return this.settings=f,i("_parseConnect: complete"),f}_parseConnack(){i("_parseConnack");let c=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(c.sessionPresent=!!(u&n.SESSIONPRESENT_MASK),this.settings.protocolVersion===5)this._list.length>=2?c.reasonCode=this._list.readUInt8(this._pos++):c.reasonCode=0;else{if(this._list.length<2)return null;c.returnCode=this._list.readUInt8(this._pos++)}if(c.returnCode===-1||c.reasonCode===-1)return this._emitError(new Error("Cannot parse return code"));if(this.settings.protocolVersion===5){let h=this._parseProperties();Object.getOwnPropertyNames(h).length&&(c.properties=h)}i("_parseConnack: complete")}_parsePublish(){i("_parsePublish");let c=this.packet;if(c.topic=this._parseString(),c.topic===null)return this._emitError(new Error("Cannot parse topic"));if(!(c.qos>0&&!this._parseMessageId())){if(this.settings.protocolVersion===5){let u=this._parseProperties();Object.getOwnPropertyNames(u).length&&(c.properties=u)}c.payload=this._list.slice(this._pos,c.length),i("_parsePublish: payload from buffer list: %o",c.payload)}}_parseSubscribe(){i("_parseSubscribe");let c=this.packet,u,h,p,b,f,g,y;if(c.subscriptions=[],!!this._parseMessageId()){if(this.settings.protocolVersion===5){let k=this._parseProperties();Object.getOwnPropertyNames(k).length&&(c.properties=k)}if(c.length<=0)return this._emitError(new Error("Malformed subscribe, no payload specified"));for(;this._pos<c.length;){if(u=this._parseString(),u===null)return this._emitError(new Error("Cannot parse topic"));if(this._pos>=c.length)return this._emitError(new Error("Malformed Subscribe Payload"));if(h=this._parseByte(),this.settings.protocolVersion===5){if(h&192)return this._emitError(new Error("Invalid subscribe topic flag bits, bits 7-6 must be 0"))}else if(h&252)return this._emitError(new Error("Invalid subscribe topic flag bits, bits 7-2 must be 0"));if(p=h&n.SUBSCRIBE_OPTIONS_QOS_MASK,p>2)return this._emitError(new Error("Invalid subscribe QoS, must be <= 2"));if(g=(h>>n.SUBSCRIBE_OPTIONS_NL_SHIFT&n.SUBSCRIBE_OPTIONS_NL_MASK)!==0,f=(h>>n.SUBSCRIBE_OPTIONS_RAP_SHIFT&n.SUBSCRIBE_OPTIONS_RAP_MASK)!==0,b=h>>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),c.subscriptions.push(y)}}}_parseSuback(){i("_parseSuback");let c=this.packet;if(this.packet.granted=[],!!this._parseMessageId()){if(this.settings.protocolVersion===5){let u=this._parseProperties();Object.getOwnPropertyNames(u).length&&(c.properties=u)}if(c.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 c=this.packet;if(c.unsubscriptions=[],!!this._parseMessageId()){if(this.settings.protocolVersion===5){let u=this._parseProperties();Object.getOwnPropertyNames(u).length&&(c.properties=u)}if(c.length<=0)return this._emitError(new Error("Malformed unsubscribe, no payload specified"));for(;this._pos<c.length;){let u=this._parseString();if(u===null)return this._emitError(new Error("Cannot parse topic"));i("_parseUnsubscribe: push topic `%s` to unsubscriptions",u),c.unsubscriptions.push(u)}}}_parseUnsuback(){i("_parseUnsuback");let c=this.packet;if(!this._parseMessageId())return this._emitError(new Error("Cannot parse messageId"));if((this.settings.protocolVersion===3||this.settings.protocolVersion===4)&&c.length!==2)return this._emitError(new Error("Malformed unsuback, payload length must be 2"));if(c.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&&(c.properties=u),c.granted=[];this._pos<this.packet.length;){let h=this._list.readUInt8(this._pos++);if(!n.MQTT5_UNSUBACK_CODES[h])return this._emitError(new Error("Invalid unsuback code"));this.packet.granted.push(h)}}}_parseConfirmation(){i("_parseConfirmation: packet.cmd: `%s`",this.packet.cmd);let c=this.packet;if(this._parseMessageId(),this.settings.protocolVersion===5){if(c.length>2){switch(c.reasonCode=this._parseByte(),this.packet.cmd){case"puback":case"pubrec":if(!n.MQTT5_PUBACK_PUBREC_CODES[c.reasonCode])return this._emitError(new Error("Invalid "+this.packet.cmd+" reason code"));break;case"pubrel":case"pubcomp":if(!n.MQTT5_PUBREL_PUBCOMP_CODES[c.reasonCode])return this._emitError(new Error("Invalid "+this.packet.cmd+" reason code"));break}i("_parseConfirmation: packet.reasonCode `%d`",c.reasonCode)}else c.reasonCode=0;if(c.length>3){let u=this._parseProperties();Object.getOwnPropertyNames(u).length&&(c.properties=u)}}return!0}_parseDisconnect(){let c=this.packet;if(i("_parseDisconnect"),this.settings.protocolVersion===5){this._list.length>0?(c.reasonCode=this._parseByte(),n.MQTT5_DISCONNECT_CODES[c.reasonCode]||this._emitError(new Error("Invalid disconnect reason code"))):c.reasonCode=0;let u=this._parseProperties();Object.getOwnPropertyNames(u).length&&(c.properties=u)}return i("_parseDisconnect result: true"),!0}_parseAuth(){i("_parseAuth");let c=this.packet;if(this.settings.protocolVersion!==5)return this._emitError(new Error("Not supported auth packet for this version MQTT"));if(c.reasonCode=this._parseByte(),!n.MQTT5_AUTH_CODES[c.reasonCode])return this._emitError(new Error("Invalid auth reason code"));let u=this._parseProperties();return Object.getOwnPropertyNames(u).length&&(c.properties=u),i("_parseAuth: result: true"),!0}_parseMessageId(){let c=this.packet;return c.messageId=this._parseNum(),c.messageId===null?(this._emitError(new Error("Cannot parse messageId")),!1):(i("_parseMessageId: packet.messageId %d",c.messageId),!0)}_parseString(c){let u=this._parseNum(),h=u+this._pos;if(u===-1||h>this._list.length||h>this.packet.length)return null;let p=this._list.toString("utf8",this._pos,h);return this._pos+=u,i("_parseString: result: %s",p),p}_parseStringPair(){return i("_parseStringPair"),{name:this._parseString(),value:this._parseString()}}_parseBuffer(){let c=this._parseNum(),u=c+this._pos;if(c===-1||u>this._list.length||u>this.packet.length)return null;let h=this._list.slice(this._pos,u);return this._pos+=c,i("_parseBuffer: result: %o",h),h}_parseNum(){if(this._list.length-this._pos<2)return-1;let c=this._list.readUInt16BE(this._pos);return this._pos+=2,i("_parseNum: result: %s",c),c}_parse4ByteNum(){if(this._list.length-this._pos<4)return-1;let c=this._list.readUInt32BE(this._pos);return this._pos+=4,i("_parse4ByteNum: result: %s",c),c}_parseVarByteNum(c){i("_parseVarByteNum");let u=4,h=0,p=1,b=0,f=!1,g,y=this._pos?this._pos:0;for(;h<u&&y+h<this._list.length;){if(g=this._list.readUInt8(y+h++),b+=p*(g&n.VARBYTEINT_MASK),p*=128,(g&n.VARBYTEINT_FIN_MASK)===0){f=!0;break}if(this._list.length<=h)break}return!f&&h===u&&this._list.length>=h&&this._emitError(new Error("Invalid variable byte integer")),y&&(this._pos+=h),f?c?f={bytes:h,value:b}:f=b:f=!1,i("_parseVarByteNum: result: %o",f),f}_parseByte(){let c;return this._pos<this._list.length&&(c=this._list.readUInt8(this._pos),this._pos++),i("_parseByte: result: %o",c),c}_parseByType(c){switch(i("_parseByType: type: %s",c),c){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 c=this._parseVarByteNum(),u=this._pos+c,h={};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"){h[b]||(h[b]=Object.create(null));let f=this._parseByType(n.propertiesTypes[b]);if(h[b][f.name])if(Array.isArray(h[b][f.name]))h[b][f.name].push(f.value);else{let g=h[b][f.name];h[b][f.name]=[g],h[b][f.name].push(f.value)}else h[b][f.name]=f.value;continue}h[b]?Array.isArray(h[b])?h[b].push(this._parseByType(n.propertiesTypes[b])):(h[b]=[h[b]],h[b].push(this._parseByType(n.propertiesTypes[b]))):h[b]=this._parseByType(n.propertiesTypes[b])}return h}_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 s,this._pos=0,!0}_emitError(c){i("_emitError",c),this.error=c,this.emit("error",c)}};e.exports=o}),qc=pe((l,e)=>{le(),ue(),ce();var{Buffer:t}=(De(),Me(Be)),r=65536,s={},n=t.isBuffer(t.from([1,2]).subarray(0,1));function i(u){let h=t.allocUnsafe(2);return h.writeUInt8(u>>8,0),h.writeUInt8(u&255,1),h}function o(){for(let u=0;u<r;u++)s[u]=i(u)}function a(u){let h=0,p=0,b=t.allocUnsafe(4);do h=u%128|0,u=u/128|0,u>0&&(h=h|128),b.writeUInt8(h,p++);while(u>0&&p<4);return u>0&&(p=0),n?b.subarray(0,p):b.slice(0,p)}function c(u){let h=t.allocUnsafe(4);return h.writeUInt32BE(u,0),h}e.exports={cache:s,generateCache:o,generateNumber:i,genBufVariableByteInt:a,generate4ByteBuffer:c}}),Hc=pe((l,e)=>{le(),ue(),ce(),typeof Le>"u"||!Le.version||Le.version.indexOf("v0.")===0||Le.version.indexOf("v1.")===0&&Le.version.indexOf("v1.8.")!==0?e.exports={nextTick:t}:e.exports=Le;function t(r,s,n,i){if(typeof r!="function")throw new TypeError('"callback" argument must be a function');var o=arguments.length,a,c;switch(o){case 0:case 1:return Le.nextTick(r);case 2:return Le.nextTick(function(){r.call(null,s)});case 3:return Le.nextTick(function(){r.call(null,s,n)});case 4:return Le.nextTick(function(){r.call(null,s,n,i)});default:for(a=new Array(o-1),c=0;c<a.length;)a[c++]=arguments[c];return Le.nextTick(function(){r.apply(null,a)})}}}),ss=pe((l,e)=>{le(),ue(),ce();var t=os(),{Buffer:r}=(De(),Me(Be)),s=r.allocUnsafe(0),n=r.from([0]),i=qc(),o=Hc().nextTick,a=ht()("mqtt-packet:writeToStream"),c=i.cache,u=i.generateNumber,h=i.generateCache,p=i.genBufVariableByteInt,b=i.generate4ByteBuffer,f=Y,g=!0;function y(G,j,ne){switch(a("generate called"),j.cork&&(j.cork(),o(k,j)),g&&(g=!1,h()),a("generate: packet.cmd: %s",G.cmd),G.cmd){case"connect":return m(G,j);case"connack":return w(G,j,ne);case"publish":return S(G,j,ne);case"puback":case"pubrec":case"pubrel":case"pubcomp":return v(G,j,ne);case"subscribe":return E(G,j,ne);case"suback":return x(G,j,ne);case"unsubscribe":return I(G,j,ne);case"unsuback":return P(G,j,ne);case"pingreq":case"pingresp":return O(G,j);case"disconnect":return B(G,j,ne);case"auth":return T(G,j,ne);default:return j.destroy(new Error("Unknown command")),!1}}Object.defineProperty(y,"cacheNumbers",{get(){return f===Y},set(G){G?((!c||Object.keys(c).length===0)&&(g=!0),f=Y):(g=!1,f=V)}});function k(G){G.uncork()}function m(G,j,ne){let W=G||{},K=W.protocolId||"MQTT",Q=W.protocolVersion||4,ge=W.will,oe=W.clean,R=W.keepalive||0,$=W.clientId||"",ee=W.username,de=W.password,fe=W.properties;oe===void 0&&(oe=!0);let ye=0;if(typeof K!="string"&&!r.isBuffer(K))return j.destroy(new Error("Invalid protocolId")),!1;if(ye+=K.length+2,Q!==3&&Q!==4&&Q!==5)return j.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 j.destroy(new Error("clientId must be supplied before 3.1.1")),!1;if(oe*1===0)return j.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 j.destroy(new Error("Invalid keepalive")),!1;ye+=2,ye+=1;let H,me;if(Q===5){if(H=Z(j,fe),!H)return!1;ye+=H.length}if(ge){if(typeof ge!="object")return j.destroy(new Error("Invalid will")),!1;if(!ge.topic||typeof ge.topic!="string")return j.destroy(new Error("Invalid will topic")),!1;if(ye+=r.byteLength(ge.topic)+2,ye+=2,ge.payload)if(ge.payload.length>=0)typeof ge.payload=="string"?ye+=r.byteLength(ge.payload):ye+=ge.payload.length;else return j.destroy(new Error("Invalid will payload")),!1;if(me={},Q===5){if(me=Z(j,ge.properties),!me)return!1;ye+=me.length}}let ve=!1;if(ee!=null)if(we(ee))ve=!0,ye+=r.byteLength(ee)+2;else return j.destroy(new Error("Invalid username")),!1;if(de!=null){if(!ve)return j.destroy(new Error("Username is required to use password")),!1;if(we(de))ye+=te(de)+2;else return j.destroy(new Error("Invalid password")),!1}j.write(t.CONNECT_HEADER),D(j,ye),F(j,K),W.bridgeMode&&(Q+=128),j.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|=de!=null?t.PASSWORD_MASK:0,se|=ge&&ge.retain?t.WILL_RETAIN_MASK:0,se|=ge&&ge.qos?ge.qos<<t.WILL_QOS_SHIFT:0,se|=ge?t.WILL_FLAG_MASK:0,se|=oe?t.CLEAN_SESSION_MASK:0,j.write(r.from([se])),f(j,R),Q===5&&H.write(),F(j,$),ge&&(Q===5&&me.write(),N(j,ge.topic),F(j,ge.payload)),ee!=null&&F(j,ee),de!=null&&F(j,de),!0}function w(G,j,ne){let W=ne?ne.protocolVersion:4,K=G||{},Q=W===5?K.reasonCode:K.returnCode,ge=K.properties,oe=2;if(typeof Q!="number")return j.destroy(new Error("Invalid return code")),!1;let R=null;if(W===5){if(R=Z(j,ge),!R)return!1;oe+=R.length}return j.write(t.CONNACK_HEADER),D(j,oe),j.write(K.sessionPresent?t.SESSIONPRESENT_HEADER:n),j.write(r.from([Q])),R?.write(),!0}function S(G,j,ne){a("publish: packet: %o",G);let W=ne?ne.protocolVersion:4,K=G||{},Q=K.qos||0,ge=K.retain?t.RETAIN_MASK:0,oe=K.topic,R=K.payload||s,$=K.messageId,ee=K.properties,de=0;if(typeof oe=="string")de+=r.byteLength(oe)+2;else if(r.isBuffer(oe))de+=oe.length+2;else return j.destroy(new Error("Invalid topic")),!1;if(r.isBuffer(R)?de+=R.length:de+=r.byteLength(R),Q&&typeof $!="number")return j.destroy(new Error("Invalid messageId")),!1;Q&&(de+=2);let fe=null;if(W===5){if(fe=Z(j,ee),!fe)return!1;de+=fe.length}return j.write(t.PUBLISH_HEADER[Q][K.dup?1:0][ge?1:0]),D(j,de),f(j,te(oe)),j.write(oe),Q>0&&f(j,$),fe?.write(),a("publish: payload: %o",R),j.write(R)}function v(G,j,ne){let W=ne?ne.protocolVersion:4,K=G||{},Q=K.cmd||"puback",ge=K.messageId,oe=K.dup&&Q==="pubrel"?t.DUP_MASK:0,R=0,$=K.reasonCode,ee=K.properties,de=W===5?3:2;if(Q==="pubrel"&&(R=1),typeof ge!="number")return j.destroy(new Error("Invalid messageId")),!1;let fe=null;if(W===5&&typeof ee=="object"){if(fe=M(j,ee,ne,de),!fe)return!1;de+=fe.length}return j.write(t.ACKS[Q][R][oe][0]),de===3&&(de+=$!==0?1:-1),D(j,de),f(j,ge),W===5&&de!==2&&j.write(r.from([$])),fe!==null?fe.write():de===4&&j.write(r.from([0])),!0}function E(G,j,ne){a("subscribe: packet: ");let W=ne?ne.protocolVersion:4,K=G||{},Q=K.dup?t.DUP_MASK:0,ge=K.messageId,oe=K.subscriptions,R=K.properties,$=0;if(typeof ge!="number")return j.destroy(new Error("Invalid messageId")),!1;$+=2;let ee=null;if(W===5){if(ee=Z(j,R),!ee)return!1;$+=ee.length}if(typeof oe=="object"&&oe.length)for(let fe=0;fe<oe.length;fe+=1){let ye=oe[fe].topic,H=oe[fe].qos;if(typeof ye!="string")return j.destroy(new Error("Invalid subscriptions - invalid topic")),!1;if(typeof H!="number")return j.destroy(new Error("Invalid subscriptions - invalid qos")),!1;if(W===5){if(typeof(oe[fe].nl||!1)!="boolean")return j.destroy(new Error("Invalid subscriptions - invalid No Local")),!1;if(typeof(oe[fe].rap||!1)!="boolean")return j.destroy(new Error("Invalid subscriptions - invalid Retain as Published")),!1;let me=oe[fe].rh||0;if(typeof me!="number"||me>2)return j.destroy(new Error("Invalid subscriptions - invalid Retain Handling")),!1}$+=r.byteLength(ye)+2+1}else return j.destroy(new Error("Invalid subscriptions")),!1;a("subscribe: writing to stream: %o",t.SUBSCRIBE_HEADER),j.write(t.SUBSCRIBE_HEADER[1][Q?1:0][0]),D(j,$),f(j,ge),ee!==null&&ee.write();let de=!0;for(let fe of oe){let ye=fe.topic,H=fe.qos,me=+fe.nl,ve=+fe.rap,se=fe.rh,Te;N(j,ye),Te=t.SUBSCRIBE_OPTIONS_QOS[H],W===5&&(Te|=me?t.SUBSCRIBE_OPTIONS_NL:0,Te|=ve?t.SUBSCRIBE_OPTIONS_RAP:0,Te|=se?t.SUBSCRIBE_OPTIONS_RH[se]:0),de=j.write(r.from([Te]))}return de}function x(G,j,ne){let W=ne?ne.protocolVersion:4,K=G||{},Q=K.messageId,ge=K.granted,oe=K.properties,R=0;if(typeof Q!="number")return j.destroy(new Error("Invalid messageId")),!1;if(R+=2,typeof ge=="object"&&ge.length)for(let ee=0;ee<ge.length;ee+=1){if(typeof ge[ee]!="number")return j.destroy(new Error("Invalid qos vector")),!1;R+=1}else return j.destroy(new Error("Invalid qos vector")),!1;let $=null;if(W===5){if($=M(j,oe,ne,R),!$)return!1;R+=$.length}return j.write(t.SUBACK_HEADER),D(j,R),f(j,Q),$!==null&&$.write(),j.write(r.from(ge))}function I(G,j,ne){let W=ne?ne.protocolVersion:4,K=G||{},Q=K.messageId,ge=K.dup?t.DUP_MASK:0,oe=K.unsubscriptions,R=K.properties,$=0;if(typeof Q!="number")return j.destroy(new Error("Invalid messageId")),!1;if($+=2,typeof oe=="object"&&oe.length)for(let fe=0;fe<oe.length;fe+=1){if(typeof oe[fe]!="string")return j.destroy(new Error("Invalid unsubscriptions")),!1;$+=r.byteLength(oe[fe])+2}else return j.destroy(new Error("Invalid unsubscriptions")),!1;let ee=null;if(W===5){if(ee=Z(j,R),!ee)return!1;$+=ee.length}j.write(t.UNSUBSCRIBE_HEADER[1][ge?1:0][0]),D(j,$),f(j,Q),ee!==null&&ee.write();let de=!0;for(let fe=0;fe<oe.length;fe++)de=N(j,oe[fe]);return de}function P(G,j,ne){let W=ne?ne.protocolVersion:4,K=G||{},Q=K.messageId,ge=K.dup?t.DUP_MASK:0,oe=K.granted,R=K.properties,$=K.cmd,ee=0,de=2;if(typeof Q!="number")return j.destroy(new Error("Invalid messageId")),!1;if(W===5)if(typeof oe=="object"&&oe.length)for(let ye=0;ye<oe.length;ye+=1){if(typeof oe[ye]!="number")return j.destroy(new Error("Invalid qos vector")),!1;de+=1}else return j.destroy(new Error("Invalid qos vector")),!1;let fe=null;if(W===5){if(fe=M(j,R,ne,de),!fe)return!1;de+=fe.length}return j.write(t.ACKS[$][ee][ge][0]),D(j,de),f(j,Q),fe!==null&&fe.write(),W===5&&j.write(r.from(oe)),!0}function O(G,j,ne){return j.write(t.EMPTY[G.cmd])}function B(G,j,ne){let W=ne?ne.protocolVersion:4,K=G||{},Q=K.reasonCode,ge=K.properties,oe=W===5?1:0,R=null;if(W===5){if(R=M(j,ge,ne,oe),!R)return!1;oe+=R.length}return j.write(r.from([t.codes.disconnect<<4])),D(j,oe),W===5&&j.write(r.from([Q])),R!==null&&R.write(),!0}function T(G,j,ne){let W=ne?ne.protocolVersion:4,K=G||{},Q=K.reasonCode,ge=K.properties,oe=W===5?1:0;W!==5&&j.destroy(new Error("Invalid mqtt version for auth packet"));let R=M(j,ge,ne,oe);return R?(oe+=R.length,j.write(r.from([t.codes.auth<<4])),D(j,oe),j.write(r.from([Q])),R!==null&&R.write(),!0):!1}var q={};function D(G,j){if(j>t.VARBYTEINT_MAX)return G.destroy(new Error(`Invalid variable byte integer: ${j}`)),!1;let ne=q[j];return ne||(ne=p(j),j<16384&&(q[j]=ne)),a("writeVarByteInt: writing to stream: %o",ne),G.write(ne)}function N(G,j){let ne=r.byteLength(j);return f(G,ne),a("writeString: %s",j),G.write(j,"utf8")}function ae(G,j,ne){N(G,j),N(G,ne)}function Y(G,j){return a("writeNumberCached: number: %d",j),a("writeNumberCached: %o",c[j]),G.write(c[j])}function V(G,j){let ne=u(j);return a("writeNumberGenerated: %o",ne),G.write(ne)}function re(G,j){let ne=b(j);return a("write4ByteNumber: %o",ne),G.write(ne)}function F(G,j){typeof j=="string"?N(G,j):j?(f(G,j.length),G.write(j)):f(G,0)}function Z(G,j){if(typeof j!="object"||j.length!=null)return{length:1,write(){be(G,{},0)}};let ne=0;function W(K,Q){let ge=t.propertiesTypes[K],oe=0;switch(ge){case"byte":{if(typeof Q!="boolean")return G.destroy(new Error(`Invalid ${K}: ${Q}`)),!1;oe+=2;break}case"int8":{if(typeof Q!="number"||Q<0||Q>255)return G.destroy(new Error(`Invalid ${K}: ${Q}`)),!1;oe+=2;break}case"binary":{if(Q&&Q===null)return G.destroy(new Error(`Invalid ${K}: ${Q}`)),!1;oe+=1+r.byteLength(Q)+2;break}case"int16":{if(typeof Q!="number"||Q<0||Q>65535)return G.destroy(new Error(`Invalid ${K}: ${Q}`)),!1;oe+=3;break}case"int32":{if(typeof Q!="number"||Q<0||Q>4294967295)return G.destroy(new Error(`Invalid ${K}: ${Q}`)),!1;oe+=5;break}case"var":{if(typeof Q!="number"||Q<0||Q>268435455)return G.destroy(new Error(`Invalid ${K}: ${Q}`)),!1;oe+=1+r.byteLength(p(Q));break}case"string":{if(typeof Q!="string")return G.destroy(new Error(`Invalid ${K}: ${Q}`)),!1;oe+=3+r.byteLength(Q.toString());break}case"pair":{if(typeof Q!="object")return G.destroy(new Error(`Invalid ${K}: ${Q}`)),!1;oe+=Object.getOwnPropertyNames(Q).reduce((R,$)=>{let ee=Q[$];return Array.isArray(ee)?R+=ee.reduce((de,fe)=>(de+=3+r.byteLength($.toString())+2+r.byteLength(fe.toString()),de),0):R+=3+r.byteLength($.toString())+2+r.byteLength(Q[$].toString()),R},0);break}default:return G.destroy(new Error(`Invalid property ${K}: ${Q}`)),!1}return oe}if(j)for(let K in j){let Q=0,ge=0,oe=j[K];if(oe!==void 0){if(Array.isArray(oe))for(let R=0;R<oe.length;R++){if(ge=W(K,oe[R]),!ge)return!1;Q+=ge}else{if(ge=W(K,oe),!ge)return!1;Q=ge}if(!Q)return!1;ne+=Q}}return{length:r.byteLength(p(ne))+ne,write(){be(G,j,ne)}}}function M(G,j,ne,W){let K=["reasonString","userProperties"],Q=ne&&ne.properties&&ne.properties.maximumPacketSize?ne.properties.maximumPacketSize:0,ge=Z(G,j);if(Q)for(;W+ge.length>Q;){let oe=K.shift();if(oe&&j[oe])delete j[oe],ge=Z(G,j);else return!1}return ge}function J(G,j,ne){switch(t.propertiesTypes[j]){case"byte":{G.write(r.from([t.properties[j]])),G.write(r.from([+ne]));break}case"int8":{G.write(r.from([t.properties[j]])),G.write(r.from([ne]));break}case"binary":{G.write(r.from([t.properties[j]])),F(G,ne);break}case"int16":{G.write(r.from([t.properties[j]])),f(G,ne);break}case"int32":{G.write(r.from([t.properties[j]])),re(G,ne);break}case"var":{G.write(r.from([t.properties[j]])),D(G,ne);break}case"string":{G.write(r.from([t.properties[j]])),N(G,ne);break}case"pair":{Object.getOwnPropertyNames(ne).forEach(W=>{let K=ne[W];Array.isArray(K)?K.forEach(Q=>{G.write(r.from([t.properties[j]])),ae(G,W.toString(),Q.toString())}):(G.write(r.from([t.properties[j]])),ae(G,W.toString(),K.toString()))});break}default:return G.destroy(new Error(`Invalid property ${j} value: ${ne}`)),!1}}function be(G,j,ne){D(G,ne);for(let W in j)if(Object.prototype.hasOwnProperty.call(j,W)&&j[W]!=null){let K=j[W];if(Array.isArray(K))for(let Q=0;Q<K.length;Q++)J(G,W,K[Q]);else J(G,W,K)}}function te(G){return G?G instanceof r?G.length:r.byteLength(G):0}function we(G){return typeof G=="string"||G instanceof r}e.exports=y}),Wc=pe((l,e)=>{le(),ue(),ce();var t=ss(),{EventEmitter:r}=(Et(),Me(bt)),{Buffer:s}=(De(),Me(Be));function n(o,a){let c=new i;return t(o,c,a),c.concat()}var i=class extends r{constructor(){super(),this._array=new Array(20),this._i=0}write(o){return this._array[this._i++]=o,!0}concat(){let o=0,a=new Array(this._array.length),c=this._array,u=0,h;for(h=0;h<c.length&&c[h]!==void 0;h++)typeof c[h]!="string"?a[h]=c[h].length:a[h]=s.byteLength(c[h]),o+=a[h];let p=s.allocUnsafe(o);for(h=0;h<c.length&&c[h]!==void 0;h++)typeof c[h]!="string"?(c[h].copy(p,u),u+=a[h]):(p.write(c[h],u),u+=a[h]);return p}destroy(o){o&&this.emit("error",o)}};e.exports=n}),zc=pe(l=>{le(),ue(),ce(),l.parser=$c().parser,l.generate=Wc(),l.writeToStream=ss()}),Vc=pe((l,e)=>{le(),ue(),ce(),e.exports=r;function t(n){return n instanceof lr?lr.from(n):new n.constructor(n.buffer.slice(),n.byteOffset,n.length)}function r(n){if(n=n||{},n.circles)return s(n);let i=new Map;if(i.set(Date,h=>new Date(h)),i.set(Map,(h,p)=>new Map(a(Array.from(h),p))),i.set(Set,(h,p)=>new Set(a(Array.from(h),p))),n.constructorHandlers)for(let h of n.constructorHandlers)i.set(h[0],h[1]);let o=null;return n.proto?u:c;function a(h,p){let b=Object.keys(h),f=new Array(b.length);for(let g=0;g<b.length;g++){let y=b[g],k=h[y];typeof k!="object"||k===null?f[y]=k:k.constructor!==Object&&(o=i.get(k.constructor))?f[y]=o(k,p):ArrayBuffer.isView(k)?f[y]=t(k):f[y]=p(k)}return f}function c(h){if(typeof h!="object"||h===null)return h;if(Array.isArray(h))return a(h,c);if(h.constructor!==Object&&(o=i.get(h.constructor)))return o(h,c);let p={};for(let b in h){if(Object.hasOwnProperty.call(h,b)===!1)continue;let f=h[b];typeof f!="object"||f===null?p[b]=f:f.constructor!==Object&&(o=i.get(f.constructor))?p[b]=o(f,c):ArrayBuffer.isView(f)?p[b]=t(f):p[b]=c(f)}return p}function u(h){if(typeof h!="object"||h===null)return h;if(Array.isArray(h))return a(h,u);if(h.constructor!==Object&&(o=i.get(h.constructor)))return o(h,u);let p={};for(let b in h){let f=h[b];typeof f!="object"||f===null?p[b]=f:f.constructor!==Object&&(o=i.get(f.constructor))?p[b]=o(f,u):ArrayBuffer.isView(f)?p[b]=t(f):p[b]=u(f)}return p}}function s(n){let i=[],o=[],a=new Map;if(a.set(Date,b=>new Date(b)),a.set(Map,(b,f)=>new Map(u(Array.from(b),f))),a.set(Set,(b,f)=>new Set(u(Array.from(b),f))),n.constructorHandlers)for(let b of n.constructorHandlers)a.set(b[0],b[1]);let c=null;return n.proto?p:h;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&&(c=a.get(w.constructor)))y[m]=c(w,f);else if(ArrayBuffer.isView(w))y[m]=t(w);else{let S=i.indexOf(w);S!==-1?y[m]=o[S]:y[m]=f(w)}}return y}function h(b){if(typeof b!="object"||b===null)return b;if(Array.isArray(b))return u(b,h);if(b.constructor!==Object&&(c=a.get(b.constructor)))return c(b,h);let f={};i.push(b),o.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&&(c=a.get(y.constructor)))f[g]=c(y,h);else if(ArrayBuffer.isView(y))f[g]=t(y);else{let k=i.indexOf(y);k!==-1?f[g]=o[k]:f[g]=h(y)}}return i.pop(),o.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&&(c=a.get(b.constructor)))return c(b,p);let f={};i.push(b),o.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&&(c=a.get(y.constructor)))f[g]=c(y,p);else if(ArrayBuffer.isView(y))f[g]=t(y);else{let k=i.indexOf(y);k!==-1?f[g]=o[k]:f[g]=p(y)}}return i.pop(),o.pop(),f}}}),Gc=pe((l,e)=>{le(),ue(),ce(),e.exports=Vc()()}),as=pe(l=>{le(),ue(),ce(),Object.defineProperty(l,"__esModule",{value:!0}),l.validateTopic=e,l.validateTopics=t;function e(r){let s=r.split("/");for(let n=0;n<s.length;n++)if(s[n]!=="+"){if(s[n]==="#")return n===s.length-1;if(s[n].indexOf("+")!==-1||s[n].indexOf("#")!==-1)return!1}return!0}function t(r){if(r.length===0)return"empty_topic_list";for(let s=0;s<r.length;s++)if(!e(r[s]))return r[s];return null}}),ls=pe(l=>{le(),ue(),ce(),Object.defineProperty(l,"__esModule",{value:!0});var e=It(),t={objectMode:!0},r={clean:!0},s=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=[],o=!1,a=0;return this._inflights.forEach((c,u)=>{i.push(c)}),n._read=()=>{!o&&a<i.length?n.push(i[a++]):n.push(null)},n.destroy=c=>{if(!o)return o=!0,setTimeout(()=>{n.emit("close")},0),n},n}del(n,i){let o=this._inflights.get(n.messageId);return o?(this._inflights.delete(n.messageId),i(null,o)):i&&i(new Error("missing packet")),this}get(n,i){let o=this._inflights.get(n.messageId);return o?i(null,o):i&&i(new Error("missing packet")),this}close(n){this.options.clean&&(this._inflights=null),n&&n()}};l.default=s}),Kc=pe(l=>{le(),ue(),ce(),Object.defineProperty(l,"__esModule",{value:!0});var e=[0,16,128,131,135,144,145,151,153],t=(r,s,n)=>{r.log("handlePublish: packet %o",s),n=typeof n<"u"?n:r.noop;let i=s.topic.toString(),o=s.payload,{qos:a}=s,{messageId:c}=s,{options:u}=r;if(r.options.protocolVersion===5){let h;if(s.properties&&(h=s.properties.topicAlias),typeof h<"u")if(i.length===0)if(h>0&&h<=65535){let p=r.topicAliasRecv.getTopicByAlias(h);if(p)i=p,r.log("handlePublish :: topic complemented by alias. topic: %s - alias: %d",i,h);else{r.log("handlePublish :: unregistered topic alias. alias: %d",h),r.emit("error",new Error("Received unregistered Topic Alias"));return}}else{r.log("handlePublish :: topic alias out of range. alias: %d",h),r.emit("error",new Error("Received Topic Alias is out of range"));return}else if(r.topicAliasRecv.put(i,h))r.log("handlePublish :: registered topic: %s - alias: %d",i,h);else{r.log("handlePublish :: topic alias out of range. alias: %d",h),r.emit("error",new Error("Received Topic Alias is out of range"));return}}switch(r.log("handlePublish: qos %d",a),a){case 2:{u.customHandleAcks(i,o,s,(h,p)=>{if(typeof h=="number"&&(p=h,h=null),h)return r.emit("error",h);if(e.indexOf(p)===-1)return r.emit("error",new Error("Wrong reason code for pubrec"));p?r._sendPacket({cmd:"pubrec",messageId:c,reasonCode:p},n):r.incomingStore.put(s,()=>{r._sendPacket({cmd:"pubrec",messageId:c},n)})});break}case 1:{u.customHandleAcks(i,o,s,(h,p)=>{if(typeof h=="number"&&(p=h,h=null),h)return r.emit("error",h);if(e.indexOf(p)===-1)return r.emit("error",new Error("Wrong reason code for puback"));p||r.emit("message",i,o,s),r.handleMessage(s,b=>{if(b)return n&&n(b);r._sendPacket({cmd:"puback",messageId:c,reasonCode:p},n)})});break}case 0:r.emit("message",i,o,s),r.handleMessage(s,n);break;default:r.log("handlePublish: unknown QoS. Doing nothing.");break}};l.default=t}),Yc=pe((l,e)=>{e.exports={version:"5.15.0"}}),Ut=pe(l=>{le(),ue(),ce(),Object.defineProperty(l,"__esModule",{value:!0}),l.MQTTJS_VERSION=l.nextTick=l.ErrorWithSubackPacket=l.ErrorWithReasonCode=void 0,l.applyMixin=r;var e=class ec extends Error{code;constructor(n,i){super(n),this.code=i,Object.setPrototypeOf(this,ec.prototype),Object.getPrototypeOf(this).name="ErrorWithReasonCode"}};l.ErrorWithReasonCode=e;var t=class tc extends Error{packet;constructor(n,i){super(n),this.packet=i,Object.setPrototypeOf(this,tc.prototype),Object.getPrototypeOf(this).name="ErrorWithSubackPacket"}};l.ErrorWithSubackPacket=t;function r(s,n,i=!1){let o=[n];for(;;){let a=o[0],c=Object.getPrototypeOf(a);if(c?.prototype)o.unshift(c);else break}for(let a of o)for(let c of Object.getOwnPropertyNames(a.prototype))(i||c!=="constructor")&&Object.defineProperty(s.prototype,c,Object.getOwnPropertyDescriptor(a.prototype,c)??Object.create(null))}l.nextTick=typeof Le?.nextTick=="function"?Le.nextTick:s=>{setTimeout(s,0)},l.MQTTJS_VERSION=Yc().version}),dr=pe(l=>{le(),ue(),ce(),Object.defineProperty(l,"__esModule",{value:!0}),l.ReasonCodes=void 0;var e=Ut();l.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,s)=>{let{messageId:n}=s,i=s.cmd,o=null,a=r.outgoing[n]?r.outgoing[n].cb:null,c=null;if(!a){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=s.reasonCode;u&&u>0&&u!==16?(c=new e.ErrorWithReasonCode(`Publish error: ${l.ReasonCodes[u]}`,u),r._removeOutgoingAndStoreMessage(n,()=>{a(c,s)})):r._removeOutgoingAndStoreMessage(n,a);break}case"pubrec":{o={cmd:"pubrel",qos:2,messageId:n};let u=s.reasonCode;u&&u>0&&u!==16?(c=new e.ErrorWithReasonCode(`Publish error: ${l.ReasonCodes[u]}`,u),r._removeOutgoingAndStoreMessage(n,()=>{a(c,s)})):r._sendPacket(o);break}case"suback":{delete r.outgoing[n],r.messageIdProvider.deallocate(n);let u=s.granted;for(let h=0;h<u.length;h++){let p=u[h];if((p&128)!==0){c=new Error(`Subscribe error: ${l.ReasonCodes[p]}`),c.code=p;let b=r.messageIdToTopic[n];b&&b.forEach(f=>{delete r._resubscribeTopics[f]})}}delete r.messageIdToTopic[n],r._invokeStoreProcessingQueue(),a(c,s);break}case"unsuback":{delete r.outgoing[n],r.messageIdProvider.deallocate(n),r._invokeStoreProcessingQueue(),a(null,s);break}default:r.emit("error",new Error("unrecognized packet type"))}r.disconnecting&&Object.keys(r.outgoing).length===0&&r.emit("outgoingEmpty")};l.default=t}),Qc=pe(l=>{le(),ue(),ce(),Object.defineProperty(l,"__esModule",{value:!0});var e=Ut(),t=dr(),r=(s,n)=>{let{options:i}=s,o=i.protocolVersion,a=o===5?n.reasonCode:n.returnCode;if(o!==5){let c=new e.ErrorWithReasonCode(`Protocol error: Auth packets are only supported in MQTT 5. Your version:${o}`,a);s.emit("error",c);return}s.handleAuth(n,(c,u)=>{if(c){s.emit("error",c);return}if(a===24)s.reconnecting=!1,s._sendPacket(u);else{let h=new e.ErrorWithReasonCode(`Connection refused: ${t.ReasonCodes[a]}`,a);s.emit("error",h)}})};l.default=r}),Jc=pe(l=>{le(),ue(),ce(),Object.defineProperty(l,"__esModule",{value:!0}),l.LRUCache=void 0;var e=typeof performance=="object"&&performance&&typeof performance.now=="function"?performance:Date,t=new Set,r=typeof Le=="object"&&Le?Le:{},s=(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,s("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 o=b=>!t.has(b),a=b=>b&&b===Math.floor(b)&&b>0&&isFinite(b),c=b=>a(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)}},h=class nr{heap;length;static#l=!1;static create(f){let g=c(f);if(!g)return[];nr.#l=!0;let y=new nr(f,g);return nr.#l=!1,y}constructor(f,g){if(!nr.#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 rc{#l;#h;#m;#g;#O;#P;ttl;ttlResolution;ttlAutopurge;updateAgeOnGet;updateAgeOnHas;allowStale;noDisposeOnSet;noUpdateTTL;maxEntrySize;sizeCalculation;noDeleteOnFetchRejection;noDeleteOnStaleGet;allowStaleOnFetchAbort;allowStaleOnFetchRejection;ignoreFetchAbort;#i;#b;#n;#r;#e;#c;#d;#a;#o;#y;#s;#v;#w;#f;#_;#A;#u;static unsafeExposeInternals(f){return{starts:f.#w,ttls:f.#f,sizes:f.#v,keyMap:f.#n,keyList:f.#r,valList:f.#e,next:f.#c,prev:f.#d,get head(){return f.#a},get tail(){return f.#o},free:f.#y,isBackgroundFetch:g=>f.#t(g),backgroundFetch:(g,y,k,m)=>f.#L(g,y,k,m),moveToTail:g=>f.#C(g),indexes:g=>f.#k(g),rindexes:g=>f.#x(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.#m}get disposeAfter(){return this.#g}constructor(f){let{max:g=0,ttl:y,ttlResolution:k=1,ttlAutopurge:m,updateAgeOnGet:w,updateAgeOnHas:S,allowStale:v,dispose:E,disposeAfter:x,noDisposeOnSet:I,noUpdateTTL:P,maxSize:O=0,maxEntrySize:B=0,sizeCalculation:T,fetchMethod:q,memoMethod:D,noDeleteOnFetchRejection:N,noDeleteOnStaleGet:ae,allowStaleOnFetchRejection:Y,allowStaleOnFetchAbort:V,ignoreFetchAbort:re}=f;if(g!==0&&!a(g))throw new TypeError("max option must be a nonnegative integer");let F=g?c(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,q!==void 0&&typeof q!="function")throw new TypeError("fetchMethod must be a function if specified");if(this.#O=q,this.#A=!!q,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.#d=new F(g),this.#a=0,this.#o=0,this.#y=h.create(g),this.#i=0,this.#b=0,typeof E=="function"&&(this.#m=E),typeof x=="function"?(this.#g=x,this.#s=[]):(this.#g=void 0,this.#s=void 0),this.#_=!!this.#m,this.#u=!!this.#g,this.noDisposeOnSet=!!I,this.noUpdateTTL=!!P,this.noDeleteOnFetchRejection=!!N,this.allowStaleOnFetchRejection=!!Y,this.allowStaleOnFetchAbort=!!V,this.ignoreFetchAbort=!!re,this.maxEntrySize!==0){if(this.#h!==0&&!a(this.#h))throw new TypeError("maxSize must be a positive integer if specified");if(!a(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=!!S,this.ttlResolution=a(k)||k===0?k:1,this.ttlAutopurge=!!m,this.ttl=y||0,this.ttl){if(!a(this.ttl))throw new TypeError("ttl must be a positive integer if specified");this.#j()}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";o(Z)&&(t.add(Z),s("TTL caching without ttlAutopurge, max, or maxSize can result in unbounded memory consumption.","UnboundedCacheWarning",Z,rc))}}getRemainingTTL(f){return this.#n.has(f)?1/0:0}#j(){let f=new u(this.#l),g=new u(this.#l);this.#f=f,this.#w=g,this.#N=(m,w,S=e.now())=>{if(g[m]=w!==0?S:0,f[m]=w,w!==0&&this.ttlAutopurge){let v=setTimeout(()=>{this.#p(m)&&this.#S(this.#r[m],"expire")},w+1);v.unref&&v.unref()}},this.#I=m=>{g[m]=f[m]!==0?e.now():0},this.#E=(m,w)=>{if(f[w]){let S=f[w],v=g[w];if(!S||!v)return;m.ttl=S,m.start=v,m.now=y||k();let E=m.now-v;m.remainingTTL=S-E}};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 S=f[w],v=g[w];if(!S||!v)return 1/0;let E=(y||k())-v;return S-E},this.#p=m=>{let w=g[m],S=f[m];return!!S&&!!w&&(y||k())-w>S}}#I=()=>{};#E=()=>{};#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(!a(k))if(m){if(typeof m!="function")throw new TypeError("sizeCalculation must be a function");if(k=m(y,g),!a(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.#d[g]}*#x({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.#x())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.#x()){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.#x())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.#x()){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.#x({allowStale:!0}))this.#p(g)&&(this.#S(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.#f&&this.#w){let w=this.#f[g],S=this.#w[g];if(w&&S){let v=w-(e.now()-S);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.#f&&this.#w){w.ttl=this.#f[g];let S=e.now()-this.#w[g];w.start=Math.floor(Date.now()-S)}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:S=this.sizeCalculation,status:v}=y,{noUpdateTTL:E=this.noUpdateTTL}=y,x=this.#U(f,g,y.size||0,S);if(this.maxEntrySize&&x>this.maxEntrySize)return v&&(v.set="miss",v.maxEntrySizeExceeded=!0),this.#S(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.#d[I]=this.#o,this.#o=I,this.#i++,this.#M(I,x,v),v&&(v.set="add"),E=!1;else{this.#C(I);let P=this.#e[I];if(g!==P){if(this.#A&&this.#t(P)){P.__abortController.abort(new Error("replaced"));let{__staleWhileFetching:O}=P;O!==void 0&&!w&&(this.#_&&this.#m?.(O,f,"set"),this.#u&&this.#s?.push([O,f,"set"]))}else w||(this.#_&&this.#m?.(P,f,"set"),this.#u&&this.#s?.push([P,f,"set"]));if(this.#T(I),this.#M(I,x,v),this.#e[I]=g,v){v.set="replace";let O=P&&this.#t(P)?P.__staleWhileFetching:P;O!==void 0&&(v.oldValue=O)}}else v&&(v.set="update")}if(k!==0&&!this.#f&&this.#j(),this.#f&&(E||this.#N(I,k,m),v&&this.#E(v,I)),!w&&this.#u&&this.#s){let P=this.#s,O;for(;O=P?.shift();)this.#g?.(...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.#g?.(...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.#m?.(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.#E(k,m));else return y&&this.#I(m),k&&(k.has="hit",this.#E(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}#L(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:S}=y;S?.addEventListener("abort",()=>w.abort(S.reason),{signal:w.signal});let v={signal:w.signal,options:y,context:k},E=(T,q=!1)=>{let{aborted:D}=w.signal,N=y.ignoreFetchAbort&&T!==void 0;if(y.status&&(D&&!q?(y.status.fetchAborted=!0,y.status.fetchError=w.signal.reason,N&&(y.status.fetchAbortIgnored=!0)):y.status.fetchResolved=!0),D&&!N&&!q)return I(w.signal.reason);let ae=O;return this.#e[g]===O&&(T===void 0?ae.__staleWhileFetching?this.#e[g]=ae.__staleWhileFetching:this.#S(f,"fetch"):(y.status&&(y.status.fetchUpdated=!0),this.set(f,T,v.options))),T},x=T=>(y.status&&(y.status.fetchRejected=!0,y.status.fetchError=T),I(T)),I=T=>{let{aborted:q}=w.signal,D=q&&y.allowStaleOnFetchAbort,N=D||y.allowStaleOnFetchRejection,ae=N||y.noDeleteOnFetchRejection,Y=O;if(this.#e[g]===O&&(!ae||Y.__staleWhileFetching===void 0?this.#S(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},P=(T,q)=>{let D=this.#O?.(f,m,v);D&&D instanceof Promise&&D.then(N=>T(N===void 0?void 0:N),q),w.signal.addEventListener("abort",()=>{(!y.ignoreFetchAbort||y.allowStaleOnFetchAbort)&&(T(void 0),y.allowStaleOnFetchAbort&&(T=N=>E(N,!0)))})};y.status&&(y.status.fetchDispatched=!0);let O=new Promise(P).then(E,x),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:S=this.noDisposeOnSet,size:v=0,sizeCalculation:E=this.sizeCalculation,noUpdateTTL:x=this.noUpdateTTL,noDeleteOnFetchRejection:I=this.noDeleteOnFetchRejection,allowStaleOnFetchRejection:P=this.allowStaleOnFetchRejection,ignoreFetchAbort:O=this.ignoreFetchAbort,allowStaleOnFetchAbort:B=this.allowStaleOnFetchAbort,context:T,forceRefresh:q=!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:S,size:v,sizeCalculation:E,noUpdateTTL:x,noDeleteOnFetchRejection:I,allowStaleOnFetchRejection:P,allowStaleOnFetchAbort:B,ignoreFetchAbort:O,status:D,signal:N},Y=this.#n.get(f);if(Y===void 0){D&&(D.fetch="miss");let V=this.#L(f,Y,ae,T);return V.__returned=V}else{let V=this.#e[Y];if(this.#t(V)){let M=y&&V.__staleWhileFetching!==void 0;return D&&(D.fetch="inflight",M&&(D.returnedStale=!0)),M?V.__staleWhileFetching:V.__returned=V}let re=this.#p(Y);if(!q&&!re)return D&&(D.fetch="hit"),this.#C(Y),k&&this.#I(Y),D&&this.#E(D,Y),V;let F=this.#L(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,S=this.get(f,w);if(!m&&S!==void 0)return S;let v=y(f,S,{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,S=this.#n.get(f);if(S!==void 0){let v=this.#e[S],E=this.#t(v);return w&&this.#E(w,S),this.#p(S)?(w&&(w.get="stale"),E?(w&&y&&v.__staleWhileFetching!==void 0&&(w.returnedStale=!0),y?v.__staleWhileFetching:void 0):(m||this.#S(f,"expire"),w&&y&&(w.returnedStale=!0),y?v:void 0)):(w&&(w.get="hit"),E?v.__staleWhileFetching:(this.#C(S),k&&this.#I(S),v))}else w&&(w.get="miss")}#D(f,g){this.#d[g]=f,this.#c[f]=g}#C(f){f!==this.#o&&(f===this.#a?this.#a=this.#c[f]:this.#D(this.#d[f],this.#c[f]),this.#D(this.#o,f),this.#o=f)}delete(f){return this.#S(f,"delete")}#S(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.#m?.(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.#d[k];else if(k===this.#a)this.#a=this.#c[k];else{let w=this.#d[k];this.#c[w]=this.#c[k];let S=this.#c[k];this.#d[S]=this.#d[k]}this.#i--,this.#y.push(k)}}if(this.#u&&this.#s?.length){let k=this.#s,m;for(;m=k?.shift();)this.#g?.(...m)}return y}clear(){return this.#F("delete")}#F(f){for(let g of this.#x({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.#m?.(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.#f&&this.#w&&(this.#f.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.#g?.(...y)}}};l.LRUCache=p}),dt=pe(l=>{le(),ue(),ce(),Object.defineProperty(l,"t",{value:!0}),l.ContainerIterator=l.Container=l.Base=void 0;var e=class{constructor(s=0){this.iteratorType=s}equals(s){return this.o===s.o}};l.ContainerIterator=e;var t=class{constructor(){this.i=0}get length(){return this.i}size(){return this.i}empty(){return this.i===0}};l.Base=t;var r=class extends t{};l.Container=r}),Xc=pe(l=>{le(),ue(),ce(),Object.defineProperty(l,"t",{value:!0}),l.default=void 0;var e=dt(),t=class extends e.Base{constructor(s=[]){super(),this.S=[];let n=this;s.forEach(function(i){n.push(i)})}clear(){this.i=0,this.S=[]}push(s){return this.S.push(s),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;l.default=r}),Zc=pe(l=>{le(),ue(),ce(),Object.defineProperty(l,"t",{value:!0}),l.default=void 0;var e=dt(),t=class extends e.Base{constructor(s=[]){super(),this.j=0,this.q=[];let n=this;s.forEach(function(i){n.push(i)})}clear(){this.q=[],this.i=this.j=0}push(s){let n=this.q.length;if(this.j/n>.5&&this.j+this.i>=n&&n>4096){let i=this.i;for(let o=0;o<i;++o)this.q[o]=this.q[this.j+o];this.j=0,this.q[this.i]=s}else this.q[this.j+this.i]=s;return++this.i}pop(){if(this.i===0)return;let s=this.q[this.j++];return this.i-=1,s}front(){if(this.i!==0)return this.q[this.j]}},r=t;l.default=r}),eu=pe(l=>{le(),ue(),ce(),Object.defineProperty(l,"t",{value:!0}),l.default=void 0;var e=dt(),t=class extends e.Base{constructor(s=[],n=function(o,a){return o>a?-1:o<a?1:0},i=!0){if(super(),this.v=n,Array.isArray(s))this.C=i?[...s]:s;else{this.C=[];let a=this;s.forEach(function(c){a.C.push(c)})}this.i=this.C.length;let o=this.i>>1;for(let a=this.i-1>>1;a>=0;--a)this.k(a,o)}m(s){let n=this.C[s];for(;s>0;){let i=s-1>>1,o=this.C[i];if(this.v(o,n)<=0)break;this.C[s]=o,s=i}this.C[s]=n}k(s,n){let i=this.C[s];for(;s<n;){let o=s<<1|1,a=o+1,c=this.C[o];if(a<this.i&&this.v(c,this.C[a])>0&&(o=a,c=this.C[a]),this.v(c,i)>=0)break;this.C[s]=c,s=o}this.C[s]=i}clear(){this.i=0,this.C.length=0}push(s){this.C.push(s),this.m(this.i),this.i+=1}pop(){if(this.i===0)return;let s=this.C[0],n=this.C.pop();return this.i-=1,this.i&&(this.C[0]=n,this.k(0,this.i>>1)),s}top(){return this.C[0]}find(s){return this.C.indexOf(s)>=0}remove(s){let n=this.C.indexOf(s);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(s){let n=this.C.indexOf(s);return n<0?!1:(this.m(n),this.k(n,this.i>>1),!0)}toArray(){return[...this.C]}},r=t;l.default=r}),hi=pe(l=>{le(),ue(),ce(),Object.defineProperty(l,"t",{value:!0}),l.default=void 0;var e=dt(),t=class extends e.Container{},r=t;l.default=r}),ft=pe(l=>{le(),ue(),ce(),Object.defineProperty(l,"t",{value:!0}),l.throwIteratorAccessError=e;function e(){throw new RangeError("Iterator access denied!")}}),cs=pe(l=>{le(),ue(),ce(),Object.defineProperty(l,"t",{value:!0}),l.RandomIterator=void 0;var e=dt(),t=ft(),r=class extends e.ContainerIterator{constructor(s,n){super(n),this.o=s,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(s){this.container.setElementByPos(this.o,s)}};l.RandomIterator=r}),tu=pe(l=>{le(),ue(),ce(),Object.defineProperty(l,"t",{value:!0}),l.default=void 0;var e=r(hi()),t=cs();function r(o){return o&&o.t?o:{default:o}}var s=class nc extends t.RandomIterator{constructor(a,c,u){super(a,u),this.container=c}copy(){return new nc(this.o,this.container,this.iteratorType)}},n=class extends e.default{constructor(o=[],a=!0){if(super(),Array.isArray(o))this.J=a?[...o]:o,this.i=o.length;else{this.J=[];let c=this;o.forEach(function(u){c.pushBack(u)})}}clear(){this.i=0,this.J.length=0}begin(){return new s(0,this)}end(){return new s(this.i,this)}rBegin(){return new s(this.i-1,this,1)}rEnd(){return new s(-1,this,1)}front(){return this.J[0]}back(){return this.J[this.i-1]}getElementByPos(o){if(o<0||o>this.i-1)throw new RangeError;return this.J[o]}eraseElementByPos(o){if(o<0||o>this.i-1)throw new RangeError;return this.J.splice(o,1),this.i-=1,this.i}eraseElementByValue(o){let a=0;for(let c=0;c<this.i;++c)this.J[c]!==o&&(this.J[a++]=this.J[c]);return this.i=this.J.length=a,this.i}eraseElementByIterator(o){let a=o.o;return o=o.next(),this.eraseElementByPos(a),o}pushBack(o){return this.J.push(o),this.i+=1,this.i}popBack(){if(this.i!==0)return this.i-=1,this.J.pop()}setElementByPos(o,a){if(o<0||o>this.i-1)throw new RangeError;this.J[o]=a}insert(o,a,c=1){if(o<0||o>this.i)throw new RangeError;return this.J.splice(o,0,...new Array(c).fill(a)),this.i+=c,this.i}find(o){for(let a=0;a<this.i;++a)if(this.J[a]===o)return new s(a,this);return this.end()}reverse(){this.J.reverse()}unique(){let o=1;for(let a=1;a<this.i;++a)this.J[a]!==this.J[a-1]&&(this.J[o++]=this.J[a]);return this.i=this.J.length=o,this.i}sort(o){this.J.sort(o)}forEach(o){for(let a=0;a<this.i;++a)o(this.J[a],a,this)}[Symbol.iterator](){return(function*(){yield*this.J}).bind(this)()}},i=n;l.default=i}),ru=pe(l=>{le(),ue(),ce(),Object.defineProperty(l,"t",{value:!0}),l.default=void 0;var e=s(hi()),t=dt(),r=ft();function s(a){return a&&a.t?a:{default:a}}var n=class ic extends t.ContainerIterator{constructor(c,u,h,p){super(p),this.o=c,this.h=u,this.container=h,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(c){this.o===this.h&&(0,r.throwIteratorAccessError)(),this.o.l=c}copy(){return new ic(this.o,this.h,this.container,this.iteratorType)}},i=class extends e.default{constructor(a=[]){super(),this.h={},this.p=this._=this.h.L=this.h.B=this.h;let c=this;a.forEach(function(u){c.pushBack(u)})}V(a){let{L:c,B:u}=a;c.B=u,u.L=c,a===this.p&&(this.p=u),a===this._&&(this._=c),this.i-=1}G(a,c){let u=c.B,h={l:a,L:c,B:u};c.B=h,u.L=h,c===this.h&&(this.p=h),u===this.h&&(this._=h),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(a){if(a<0||a>this.i-1)throw new RangeError;let c=this.p;for(;a--;)c=c.B;return c.l}eraseElementByPos(a){if(a<0||a>this.i-1)throw new RangeError;let c=this.p;for(;a--;)c=c.B;return this.V(c),this.i}eraseElementByValue(a){let c=this.p;for(;c!==this.h;)c.l===a&&this.V(c),c=c.B;return this.i}eraseElementByIterator(a){let c=a.o;return c===this.h&&(0,r.throwIteratorAccessError)(),a=a.next(),this.V(c),a}pushBack(a){return this.G(a,this._),this.i}popBack(){if(this.i===0)return;let a=this._.l;return this.V(this._),a}pushFront(a){return this.G(a,this.h),this.i}popFront(){if(this.i===0)return;let a=this.p.l;return this.V(this.p),a}setElementByPos(a,c){if(a<0||a>this.i-1)throw new RangeError;let u=this.p;for(;a--;)u=u.B;u.l=c}insert(a,c,u=1){if(a<0||a>this.i)throw new RangeError;if(u<=0)return this.i;if(a===0)for(;u--;)this.pushFront(c);else if(a===this.i)for(;u--;)this.pushBack(c);else{let h=this.p;for(let b=1;b<a;++b)h=h.B;let p=h.B;for(this.i+=u;u--;)h.B={l:c,L:h},h.B.L=h,h=h.B;h.B=p,p.L=h}return this.i}find(a){let c=this.p;for(;c!==this.h;){if(c.l===a)return new n(c,this.h,this);c=c.B}return this.end()}reverse(){if(this.i<=1)return;let a=this.p,c=this._,u=0;for(;u<<1<this.i;){let h=a.l;a.l=c.l,c.l=h,a=a.B,c=c.L,u+=1}}unique(){if(this.i<=1)return this.i;let a=this.p;for(;a!==this.h;){let c=a;for(;c.B!==this.h&&c.l===c.B.l;)c=c.B,this.i-=1;a.B=c.B,a.B.L=a,a=a.B}return this.i}sort(a){if(this.i<=1)return;let c=[];this.forEach(function(h){c.push(h)}),c.sort(a);let u=this.p;c.forEach(function(h){u.l=h,u=u.B})}merge(a){let c=this;if(this.i===0)a.forEach(function(u){c.pushBack(u)});else{let u=this.p;a.forEach(function(h){for(;u!==c.h&&u.l<=h;)u=u.B;c.G(h,u.L)})}return this.i}forEach(a){let c=this.p,u=0;for(;c!==this.h;)a(c.l,u++,this),c=c.B}[Symbol.iterator](){return(function*(){if(this.i===0)return;let a=this.p;for(;a!==this.h;)yield a.l,a=a.B}).bind(this)()}},o=i;l.default=o}),nu=pe(l=>{le(),ue(),ce(),Object.defineProperty(l,"t",{value:!0}),l.default=void 0;var e=r(hi()),t=cs();function r(o){return o&&o.t?o:{default:o}}var s=class oc extends t.RandomIterator{constructor(a,c,u){super(a,u),this.container=c}copy(){return new oc(this.o,this.container,this.iteratorType)}},n=class extends e.default{constructor(o=[],a=4096){super(),this.j=0,this.D=0,this.R=0,this.N=0,this.P=0,this.A=[];let c=(()=>{if(typeof o.length=="number")return o.length;if(typeof o.size=="number")return o.size;if(typeof o.size=="function")return o.size();throw new TypeError("Cannot get the length or size of the container")})();this.F=a,this.P=Math.max(Math.ceil(c/this.F),1);for(let p=0;p<this.P;++p)this.A.push(new Array(this.F));let u=Math.ceil(c/this.F);this.j=this.R=(this.P>>1)-(u>>1),this.D=this.N=this.F-c%this.F>>1;let h=this;o.forEach(function(p){h.pushBack(p)})}T(){let o=[],a=Math.max(this.P>>1,1);for(let c=0;c<a;++c)o[c]=new Array(this.F);for(let c=this.j;c<this.P;++c)o[o.length]=this.A[c];for(let c=0;c<this.R;++c)o[o.length]=this.A[c];o[o.length]=[...this.A[this.R]],this.j=a,this.R=o.length-1;for(let c=0;c<a;++c)o[o.length]=new Array(this.F);this.A=o,this.P=o.length}O(o){let a=this.D+o+1,c=a%this.F,u=c-1,h=this.j+(a-c)/this.F;return c===0&&(h-=1),h%=this.P,u<0&&(u+=this.F),{curNodeBucketIndex:h,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 s(0,this)}end(){return new s(this.i,this)}rBegin(){return new s(this.i-1,this,1)}rEnd(){return new s(-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(o){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]=o,this.i}popBack(){if(this.i===0)return;let o=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,o}pushFront(o){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]=o,this.i}popFront(){if(this.i===0)return;let o=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,o}getElementByPos(o){if(o<0||o>this.i-1)throw new RangeError;let{curNodeBucketIndex:a,curNodePointerIndex:c}=this.O(o);return this.A[a][c]}setElementByPos(o,a){if(o<0||o>this.i-1)throw new RangeError;let{curNodeBucketIndex:c,curNodePointerIndex:u}=this.O(o);this.A[c][u]=a}insert(o,a,c=1){if(o<0||o>this.i)throw new RangeError;if(o===0)for(;c--;)this.pushFront(a);else if(o===this.i)for(;c--;)this.pushBack(a);else{let u=[];for(let h=o;h<this.i;++h)u.push(this.getElementByPos(h));this.cut(o-1);for(let h=0;h<c;++h)this.pushBack(a);for(let h=0;h<u.length;++h)this.pushBack(u[h])}return this.i}cut(o){if(o<0)return this.clear(),0;let{curNodeBucketIndex:a,curNodePointerIndex:c}=this.O(o);return this.R=a,this.N=c,this.i=o+1,this.i}eraseElementByPos(o){if(o<0||o>this.i-1)throw new RangeError;if(o===0)this.popFront();else if(o===this.i-1)this.popBack();else{let a=[];for(let u=o+1;u<this.i;++u)a.push(this.getElementByPos(u));this.cut(o),this.popBack();let c=this;a.forEach(function(u){c.pushBack(u)})}return this.i}eraseElementByValue(o){if(this.i===0)return 0;let a=[];for(let u=0;u<this.i;++u){let h=this.getElementByPos(u);h!==o&&a.push(h)}let c=a.length;for(let u=0;u<c;++u)this.setElementByPos(u,a[u]);return this.cut(c-1)}eraseElementByIterator(o){let a=o.o;return this.eraseElementByPos(a),o=o.next(),o}find(o){for(let a=0;a<this.i;++a)if(this.getElementByPos(a)===o)return new s(a,this);return this.end()}reverse(){let o=0,a=this.i-1;for(;o<a;){let c=this.getElementByPos(o);this.setElementByPos(o,this.getElementByPos(a)),this.setElementByPos(a,c),o+=1,a-=1}}unique(){if(this.i<=1)return this.i;let o=1,a=this.getElementByPos(0);for(let c=1;c<this.i;++c){let u=this.getElementByPos(c);u!==a&&(a=u,this.setElementByPos(o++,u))}for(;this.i>o;)this.popBack();return this.i}sort(o){let a=[];for(let c=0;c<this.i;++c)a.push(this.getElementByPos(c));a.sort(o);for(let c=0;c<this.i;++c)this.setElementByPos(c,a[c])}shrinkToFit(){if(this.i===0)return;let o=[];this.forEach(function(a){o.push(a)}),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 a=0;a<this.P;++a)this.A.push(new Array(this.F));for(let a=0;a<o.length;++a)this.pushBack(o[a])}forEach(o){for(let a=0;a<this.i;++a)o(this.getElementByPos(a),a,this)}[Symbol.iterator](){return(function*(){for(let o=0;o<this.i;++o)yield this.getElementByPos(o)}).bind(this)()}},i=n;l.default=i}),iu=pe(l=>{le(),ue(),ce(),Object.defineProperty(l,"t",{value:!0}),l.TreeNodeEnableIndex=l.TreeNode=void 0;var e=class{constructor(r,s){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=s}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 s=r.tt;for(;s.U===r;)r=s,s=r.tt;r=s}return r}B(){let r=this;if(r.W){for(r=r.W;r.U;)r=r.U;return r}else{let s=r.tt;for(;s.W===r;)r=s,s=r.tt;return r.W!==s?s:r}}te(){let r=this.tt,s=this.W,n=s.U;return r.tt===this?r.tt=s:r.U===this?r.U=s:r.W=s,s.tt=r,s.U=this,this.tt=s,this.W=n,n&&(n.tt=this),s}se(){let r=this.tt,s=this.U,n=s.W;return r.tt===this?r.tt=s:r.U===this?r.U=s:r.W=s,s.tt=r,s.W=this,this.tt=s,this.U=n,n&&(n.tt=this),s}};l.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)}};l.TreeNodeEnableIndex=t}),us=pe(l=>{le(),ue(),ce(),Object.defineProperty(l,"t",{value:!0}),l.default=void 0;var e=iu(),t=dt(),r=ft(),s=class extends t.Container{constructor(i=function(a,c){return a<c?-1:a>c?1:0},o=!1){super(),this.Y=void 0,this.v=i,o?(this.re=e.TreeNodeEnableIndex,this.M=function(a,c,u){let h=this.ne(a,c,u);if(h){let p=h.tt;for(;p!==this.h;)p.rt+=1,p=p.tt;let b=this.he(h);if(b){let{parentNode:f,grandParent:g,curNode:y}=b;f.ie(),g.ie(),y.ie()}}return this.i},this.V=function(a){let c=this.fe(a);for(;c!==this.h;)c.rt-=1,c=c.tt}):(this.re=e.TreeNode,this.M=function(a,c,u){let h=this.ne(a,c,u);return h&&this.he(h),this.i},this.V=this.fe),this.h=new this.re}X(i,o){let a=this.h;for(;i;){let c=this.v(i.u,o);if(c<0)i=i.W;else if(c>0)a=i,i=i.U;else return i}return a}Z(i,o){let a=this.h;for(;i;)this.v(i.u,o)<=0?i=i.W:(a=i,i=i.U);return a}$(i,o){let a=this.h;for(;i;){let c=this.v(i.u,o);if(c<0)a=i,i=i.W;else if(c>0)i=i.U;else return i}return a}rr(i,o){let a=this.h;for(;i;)this.v(i.u,o)<0?(a=i,i=i.W):i=i.U;return a}ue(i){for(;;){let o=i.tt;if(o===this.h)return;if(i.ee===1){i.ee=0;return}if(i===o.U){let a=o.W;if(a.ee===1)a.ee=0,o.ee=1,o===this.Y?this.Y=o.te():o.te();else if(a.W&&a.W.ee===1){a.ee=o.ee,o.ee=0,a.W.ee=0,o===this.Y?this.Y=o.te():o.te();return}else a.U&&a.U.ee===1?(a.ee=1,a.U.ee=0,a.se()):(a.ee=1,i=o)}else{let a=o.U;if(a.ee===1)a.ee=0,o.ee=1,o===this.Y?this.Y=o.se():o.se();else if(a.U&&a.U.ee===1){a.ee=o.ee,o.ee=0,a.U.ee=0,o===this.Y?this.Y=o.se():o.se();return}else a.W&&a.W.ee===1?(a.ee=1,a.W.ee=0,a.te()):(a.ee=1,i=o)}}}fe(i){if(this.i===1)return this.clear(),this.h;let o=i;for(;o.U||o.W;){if(o.W)for(o=o.W;o.U;)o=o.U;else o=o.U;[i.u,o.u]=[o.u,i.u],[i.l,o.l]=[o.l,i.l],i=o}this.h.U===o?this.h.U=o.tt:this.h.W===o&&(this.h.W=o.tt),this.ue(o);let a=o.tt;return o===a.U?a.U=void 0:a.W=void 0,this.i-=1,this.Y.ee=0,a}oe(i,o){return i===void 0?!1:this.oe(i.U,o)||o(i)?!0:this.oe(i.W,o)}he(i){for(;;){let o=i.tt;if(o.ee===0)return;let a=o.tt;if(o===a.U){let c=a.W;if(c&&c.ee===1){if(c.ee=o.ee=0,a===this.Y)return;a.ee=1,i=a;continue}else if(i===o.W){if(i.ee=0,i.U&&(i.U.tt=o),i.W&&(i.W.tt=a),o.W=i.U,a.U=i.W,i.U=o,i.W=a,a===this.Y)this.Y=i,this.h.tt=i;else{let u=a.tt;u.U===a?u.U=i:u.W=i}return i.tt=a.tt,o.tt=i,a.tt=i,a.ee=1,{parentNode:o,grandParent:a,curNode:i}}else o.ee=0,a===this.Y?this.Y=a.se():a.se(),a.ee=1}else{let c=a.U;if(c&&c.ee===1){if(c.ee=o.ee=0,a===this.Y)return;a.ee=1,i=a;continue}else if(i===o.U){if(i.ee=0,i.U&&(i.U.tt=a),i.W&&(i.W.tt=o),a.W=i.U,o.U=i.W,i.U=a,i.W=o,a===this.Y)this.Y=i,this.h.tt=i;else{let u=a.tt;u.U===a?u.U=i:u.W=i}return i.tt=a.tt,o.tt=i,a.tt=i,a.ee=1,{parentNode:o,grandParent:a,curNode:i}}else o.ee=0,a===this.Y?this.Y=a.te():a.te(),a.ee=1}return}}ne(i,o,a){if(this.Y===void 0){this.i+=1,this.Y=new this.re(i,o),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 c,u=this.h.U,h=this.v(u.u,i);if(h===0){u.l=o;return}else if(h>0)u.U=new this.re(i,o),u.U.tt=u,c=u.U,this.h.U=c;else{let p=this.h.W,b=this.v(p.u,i);if(b===0){p.l=o;return}else if(b<0)p.W=new this.re(i,o),p.W.tt=p,c=p.W,this.h.W=c;else{if(a!==void 0){let f=a.o;if(f!==this.h){let g=this.v(f.u,i);if(g===0){f.l=o;return}else if(g>0){let y=f.L(),k=this.v(y.u,i);if(k===0){y.l=o;return}else k<0&&(c=new this.re(i,o),y.W===void 0?(y.W=c,c.tt=y):(f.U=c,c.tt=f))}}}if(c===void 0)for(c=this.Y;;){let f=this.v(c.u,i);if(f>0){if(c.U===void 0){c.U=new this.re(i,o),c.U.tt=c,c=c.U;break}c=c.U}else if(f<0){if(c.W===void 0){c.W=new this.re(i,o),c.W.tt=c,c=c.W;break}c=c.W}else{c.l=o;return}}}}return this.i+=1,c}I(i,o){for(;i;){let a=this.v(i.u,o);if(a<0)i=i.W;else if(a>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,o){let a=i.o;if(a===this.h&&(0,r.throwIteratorAccessError)(),this.i===1)return a.u=o,!0;if(a===this.h.U)return this.v(a.B().u,o)>0?(a.u=o,!0):!1;if(a===this.h.W)return this.v(a.L().u,o)<0?(a.u=o,!0):!1;let c=a.L().u;if(this.v(c,o)>=0)return!1;let u=a.B().u;return this.v(u,o)<=0?!1:(a.u=o,!0)}eraseElementByPos(i){if(i<0||i>this.i-1)throw new RangeError;let o=0,a=this;return this.oe(this.Y,function(c){return i===o?(a.V(c),!0):(o+=1,!1)}),this.i}eraseElementByKey(i){if(this.i===0)return!1;let o=this.I(this.Y,i);return o===this.h?!1:(this.V(o),!0)}eraseElementByIterator(i){let o=i.o;o===this.h&&(0,r.throwIteratorAccessError)();let a=o.W===void 0;return i.iteratorType===0?a&&i.next():(!a||o.U===void 0)&&i.next(),this.V(o),i}forEach(i){let o=0;for(let a of this)i(a,o++,this)}getElementByPos(i){if(i<0||i>this.i-1)throw new RangeError;let o,a=0;for(let c of this){if(a===i){o=c;break}a+=1}return o}getHeight(){if(this.i===0)return 0;let i=function(o){return o?Math.max(i(o.U),i(o.W))+1:0};return i(this.Y)}},n=s;l.default=n}),hs=pe(l=>{le(),ue(),ce(),Object.defineProperty(l,"t",{value:!0}),l.default=void 0;var e=dt(),t=ft(),r=class extends e.ContainerIterator{constructor(n,i,o){super(o),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 o=0;for(n.U&&(o+=n.U.rt);n!==i;){let a=n.tt;n===a.W&&(o+=1,a.U&&(o+=a.U.rt)),n=a}return o}},s=r;l.default=s}),ou=pe(l=>{le(),ue(),ce(),Object.defineProperty(l,"t",{value:!0}),l.default=void 0;var e=s(us()),t=s(hs()),r=ft();function s(a){return a&&a.t?a:{default:a}}var n=class sc extends t.default{constructor(c,u,h,p){super(c,u,p),this.container=h}get pointer(){return this.o===this.h&&(0,r.throwIteratorAccessError)(),this.o.u}copy(){return new sc(this.o,this.h,this.container,this.iteratorType)}},i=class extends e.default{constructor(a=[],c,u){super(c,u);let h=this;a.forEach(function(p){h.insert(p)})}*K(a){a!==void 0&&(yield*this.K(a.U),yield a.u,yield*this.K(a.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(a,c){return this.M(a,void 0,c)}find(a){let c=this.I(this.Y,a);return new n(c,this.h,this)}lowerBound(a){let c=this.X(this.Y,a);return new n(c,this.h,this)}upperBound(a){let c=this.Z(this.Y,a);return new n(c,this.h,this)}reverseLowerBound(a){let c=this.$(this.Y,a);return new n(c,this.h,this)}reverseUpperBound(a){let c=this.rr(this.Y,a);return new n(c,this.h,this)}union(a){let c=this;return a.forEach(function(u){c.insert(u)}),this.i}[Symbol.iterator](){return this.K(this.Y)}},o=i;l.default=o}),su=pe(l=>{le(),ue(),ce(),Object.defineProperty(l,"t",{value:!0}),l.default=void 0;var e=s(us()),t=s(hs()),r=ft();function s(a){return a&&a.t?a:{default:a}}var n=class ac extends t.default{constructor(c,u,h,p){super(c,u,p),this.container=h}get pointer(){this.o===this.h&&(0,r.throwIteratorAccessError)();let c=this;return new Proxy([],{get(u,h){if(h==="0")return c.o.u;if(h==="1")return c.o.l},set(u,h,p){if(h!=="1")throw new TypeError("props must be 1");return c.o.l=p,!0}})}copy(){return new ac(this.o,this.h,this.container,this.iteratorType)}},i=class extends e.default{constructor(a=[],c,u){super(c,u);let h=this;a.forEach(function(p){h.setElement(p[0],p[1])})}*K(a){a!==void 0&&(yield*this.K(a.U),yield[a.u,a.l],yield*this.K(a.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 a=this.h.U;return[a.u,a.l]}back(){if(this.i===0)return;let a=this.h.W;return[a.u,a.l]}lowerBound(a){let c=this.X(this.Y,a);return new n(c,this.h,this)}upperBound(a){let c=this.Z(this.Y,a);return new n(c,this.h,this)}reverseLowerBound(a){let c=this.$(this.Y,a);return new n(c,this.h,this)}reverseUpperBound(a){let c=this.rr(this.Y,a);return new n(c,this.h,this)}setElement(a,c,u){return this.M(a,c,u)}find(a){let c=this.I(this.Y,a);return new n(c,this.h,this)}getElementByKey(a){return this.I(this.Y,a).l}union(a){let c=this;return a.forEach(function(u){c.setElement(u[0],u[1])}),this.i}[Symbol.iterator](){return this.K(this.Y)}},o=i;l.default=o}),ds=pe(l=>{le(),ue(),ce(),Object.defineProperty(l,"t",{value:!0}),l.default=e;function e(t){let r=typeof t;return r==="object"&&t!==null||r==="function"}}),fs=pe(l=>{le(),ue(),ce(),Object.defineProperty(l,"t",{value:!0}),l.HashContainerIterator=l.HashContainer=void 0;var e=dt(),t=s(ds()),r=ft();function s(o){return o&&o.t?o:{default:o}}var n=class extends e.ContainerIterator{constructor(o,a,c){super(c),this.o=o,this.h=a,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})}};l.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(o){let{L:a,B:c}=o;a.B=c,c.L=a,o===this.p&&(this.p=c),o===this._&&(this._=a),this.i-=1}M(o,a,c){c===void 0&&(c=(0,t.default)(o));let u;if(c){let h=o[this.HASH_TAG];if(h!==void 0)return this.H[h].l=a,this.i;Object.defineProperty(o,this.HASH_TAG,{value:this.H.length,configurable:!0}),u={u:o,l:a,L:this._,B:this.h},this.H.push(u)}else{let h=this.g[o];if(h)return h.l=a,this.i;u={u:o,l:a,L:this._,B:this.h},this.g[o]=u}return this.i===0?(this.p=u,this.h.B=u):this._.B=u,this._=u,this.h.L=u,++this.i}I(o,a){if(a===void 0&&(a=(0,t.default)(o)),a){let c=o[this.HASH_TAG];return c===void 0?this.h:this.H[c]}else return this.g[o]||this.h}clear(){let o=this.HASH_TAG;this.H.forEach(function(a){delete a.u[o]}),this.H=[],this.g={},Object.setPrototypeOf(this.g,null),this.i=0,this.p=this._=this.h.L=this.h.B=this.h}eraseElementByKey(o,a){let c;if(a===void 0&&(a=(0,t.default)(o)),a){let u=o[this.HASH_TAG];if(u===void 0)return!1;delete o[this.HASH_TAG],c=this.H[u],delete this.H[u]}else{if(c=this.g[o],c===void 0)return!1;delete this.g[o]}return this.V(c),!0}eraseElementByIterator(o){let a=o.o;return a===this.h&&(0,r.throwIteratorAccessError)(),this.V(a),o.next()}eraseElementByPos(o){if(o<0||o>this.i-1)throw new RangeError;let a=this.p;for(;o--;)a=a.B;return this.V(a),this.i}};l.HashContainer=i}),au=pe(l=>{le(),ue(),ce(),Object.defineProperty(l,"t",{value:!0}),l.default=void 0;var e=fs(),t=ft(),r=class lc extends e.HashContainerIterator{constructor(o,a,c,u){super(o,a,u),this.container=c}get pointer(){return this.o===this.h&&(0,t.throwIteratorAccessError)(),this.o.u}copy(){return new lc(this.o,this.h,this.container,this.iteratorType)}},s=class extends e.HashContainer{constructor(i=[]){super();let o=this;i.forEach(function(a){o.insert(a)})}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,o){return this.M(i,void 0,o)}getElementByPos(i){if(i<0||i>this.i-1)throw new RangeError;let o=this.p;for(;i--;)o=o.B;return o.u}find(i,o){let a=this.I(i,o);return new r(a,this.h,this)}forEach(i){let o=0,a=this.p;for(;a!==this.h;)i(a.u,o++,this),a=a.B}[Symbol.iterator](){return(function*(){let i=this.p;for(;i!==this.h;)yield i.u,i=i.B}).bind(this)()}},n=s;l.default=n}),lu=pe(l=>{le(),ue(),ce(),Object.defineProperty(l,"t",{value:!0}),l.default=void 0;var e=fs(),t=s(ds()),r=ft();function s(a){return a&&a.t?a:{default:a}}var n=class cc extends e.HashContainerIterator{constructor(c,u,h,p){super(c,u,p),this.container=h}get pointer(){this.o===this.h&&(0,r.throwIteratorAccessError)();let c=this;return new Proxy([],{get(u,h){if(h==="0")return c.o.u;if(h==="1")return c.o.l},set(u,h,p){if(h!=="1")throw new TypeError("props must be 1");return c.o.l=p,!0}})}copy(){return new cc(this.o,this.h,this.container,this.iteratorType)}},i=class extends e.HashContainer{constructor(a=[]){super();let c=this;a.forEach(function(u){c.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(a,c,u){return this.M(a,c,u)}getElementByKey(a,c){if(c===void 0&&(c=(0,t.default)(a)),c){let h=a[this.HASH_TAG];return h!==void 0?this.H[h].l:void 0}let u=this.g[a];return u?u.l:void 0}getElementByPos(a){if(a<0||a>this.i-1)throw new RangeError;let c=this.p;for(;a--;)c=c.B;return[c.u,c.l]}find(a,c){let u=this.I(a,c);return new n(u,this.h,this)}forEach(a){let c=0,u=this.p;for(;u!==this.h;)a([u.u,u.l],c++,this),u=u.B}[Symbol.iterator](){return(function*(){let a=this.p;for(;a!==this.h;)yield[a.u,a.l],a=a.B}).bind(this)()}},o=i;l.default=o}),cu=pe(l=>{le(),ue(),ce(),Object.defineProperty(l,"t",{value:!0}),Object.defineProperty(l,"Deque",{enumerable:!0,get:function(){return i.default}}),Object.defineProperty(l,"HashMap",{enumerable:!0,get:function(){return u.default}}),Object.defineProperty(l,"HashSet",{enumerable:!0,get:function(){return c.default}}),Object.defineProperty(l,"LinkList",{enumerable:!0,get:function(){return n.default}}),Object.defineProperty(l,"OrderedMap",{enumerable:!0,get:function(){return a.default}}),Object.defineProperty(l,"OrderedSet",{enumerable:!0,get:function(){return o.default}}),Object.defineProperty(l,"PriorityQueue",{enumerable:!0,get:function(){return r.default}}),Object.defineProperty(l,"Queue",{enumerable:!0,get:function(){return t.default}}),Object.defineProperty(l,"Stack",{enumerable:!0,get:function(){return e.default}}),Object.defineProperty(l,"Vector",{enumerable:!0,get:function(){return s.default}});var e=h(Xc()),t=h(Zc()),r=h(eu()),s=h(tu()),n=h(ru()),i=h(nu()),o=h(ou()),a=h(su()),c=h(au()),u=h(lu());function h(p){return p&&p.t?p:{default:p}}}),uu=pe((l,e)=>{le(),ue(),ce();var t=cu().OrderedSet,r=ht()("number-allocator:trace"),s=ht()("number-allocator:error");function n(o,a){this.low=o,this.high=a}n.prototype.equals=function(o){return this.low===o.low&&this.high===o.high},n.prototype.compare=function(o){return this.low<o.low&&this.high<o.low?-1:o.low<this.low&&o.high<this.low?1:0};function i(o,a){if(!(this instanceof i))return new i(o,a);this.min=o,this.max=a,this.ss=new t([],(c,u)=>c.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 o=this.ss.begin(),a=o.pointer.low,c=o.pointer.high,u=a;return u+1<=c?this.ss.updateKeyByIterator(o,new n(a+1,c)):this.ss.eraseElementByPos(0),r("alloc():"+u),u},i.prototype.use=function(o){let a=new n(o,o),c=this.ss.lowerBound(a);if(!c.equals(this.ss.end())){let u=c.pointer.low,h=c.pointer.high;return c.pointer.equals(a)?(this.ss.eraseElementByIterator(c),r("use():"+o),!0):u>o?!1:u===o?(this.ss.updateKeyByIterator(c,new n(u+1,h)),r("use():"+o),!0):h===o?(this.ss.updateKeyByIterator(c,new n(u,h-1)),r("use():"+o),!0):(this.ss.updateKeyByIterator(c,new n(o+1,h)),this.ss.insert(new n(u,o-1)),r("use():"+o),!0)}return r("use():failed"),!1},i.prototype.free=function(o){if(o<this.min||o>this.max){s("free():"+o+" is out of range");return}let a=new n(o,o),c=this.ss.upperBound(a);if(c.equals(this.ss.end())){if(c.equals(this.ss.begin())){this.ss.insert(a);return}c.pre();let u=c.pointer.high;c.pointer.high+1===o?this.ss.updateKeyByIterator(c,new n(u,o)):this.ss.insert(a)}else if(c.equals(this.ss.begin()))if(o+1===c.pointer.low){let u=c.pointer.high;this.ss.updateKeyByIterator(c,new n(o,u))}else this.ss.insert(a);else{let u=c.pointer.low,h=c.pointer.high;c.pre();let p=c.pointer.low;c.pointer.high+1===o?o+1===u?(this.ss.eraseElementByIterator(c),this.ss.updateKeyByIterator(c,new n(p,h))):this.ss.updateKeyByIterator(c,new n(p,o)):o+1===u?(this.ss.eraseElementByIterator(c.next()),this.ss.insert(new n(o,h))):this.ss.insert(a)}r("free():"+o)},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 o of this.ss)console.log(o)},e.exports=i}),ps=pe((l,e)=>{le(),ue(),ce();var t=uu();e.exports.NumberAllocator=t}),hu=pe(l=>{le(),ue(),ce(),Object.defineProperty(l,"__esModule",{value:!0});var e=Jc(),t=ps(),r=class{aliasToTopic;topicToAlias;max;numberAllocator;length;constructor(s){s>0&&(this.aliasToTopic=new e.LRUCache({max:s}),this.topicToAlias={},this.numberAllocator=new t.NumberAllocator(1,s),this.max=s,this.length=0)}put(s,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,s),this.topicToAlias[s]=n,this.numberAllocator.use(n),this.length=this.aliasToTopic.size,!0}getTopicByAlias(s){return this.aliasToTopic.get(s)}getAliasByTopic(s){let n=this.topicToAlias[s];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]}};l.default=r}),du=pe(l=>{le(),ue(),ce();var e=l&&l.__importDefault||function(i){return i&&i.__esModule?i:{default:i}};Object.defineProperty(l,"__esModule",{value:!0});var t=dr(),r=e(hu()),s=Ut(),n=(i,o)=>{i.log("_handleConnack");let{options:a}=i,c=a.protocolVersion===5?o.reasonCode:o.returnCode;if(clearTimeout(i.connackTimer),delete i.topicAliasSend,o.properties){if(o.properties.topicAliasMaximum){if(o.properties.topicAliasMaximum>65535){i.emit("error",new Error("topicAliasMaximum from broker is out of range"));return}o.properties.topicAliasMaximum>0&&(i.topicAliasSend=new r.default(o.properties.topicAliasMaximum))}o.properties.serverKeepAlive&&a.keepalive&&(a.keepalive=o.properties.serverKeepAlive),o.properties.maximumPacketSize&&(a.properties||(a.properties={}),a.properties.maximumPacketSize=o.properties.maximumPacketSize)}if(c===0)i.reconnecting=!1,i._onConnect(o);else if(c>0){let u=new s.ErrorWithReasonCode(`Connection refused: ${t.ReasonCodes[c]}`,c);i.emit("error",u),i.options.reconnectOnConnackError&&i._cleanUp(!0)}};l.default=n}),fu=pe(l=>{le(),ue(),ce(),Object.defineProperty(l,"__esModule",{value:!0});var e=(t,r,s)=>{t.log("handling pubrel packet");let n=typeof s<"u"?s:t.noop,{messageId:i}=r,o={cmd:"pubcomp",messageId:i};t.incomingStore.get(r,(a,c)=>{a?t._sendPacket(o,n):(t.emit("message",c.topic,c.payload,c),t.handleMessage(c,u=>{if(u)return n(u);t.incomingStore.del(c,t.noop),t._sendPacket(o,n)}))})};l.default=e}),pu=pe(l=>{le(),ue(),ce();var e=l&&l.__importDefault||function(a){return a&&a.__esModule?a:{default:a}};Object.defineProperty(l,"__esModule",{value:!0});var t=e(Kc()),r=e(Qc()),s=e(du()),n=e(dr()),i=e(fu()),o=(a,c,u)=>{let{options:h}=a;if(h.protocolVersion===5&&h.properties&&h.properties.maximumPacketSize&&h.properties.maximumPacketSize<c.length)return a.emit("error",new Error(`exceeding packets size ${c.cmd}`)),a.end({reasonCode:149,properties:{reasonString:"Maximum packet size was exceeded"}}),a;switch(a.log("_handlePacket :: emitting packetreceive"),a.emit("packetreceive",c),c.cmd){case"publish":(0,t.default)(a,c,u);break;case"puback":case"pubrec":case"pubcomp":case"suback":case"unsuback":a.reschedulePing(),(0,n.default)(a,c),u();break;case"pubrel":a.reschedulePing(),(0,i.default)(a,c,u);break;case"connack":(0,s.default)(a,c),u();break;case"auth":a.reschedulePing(),(0,r.default)(a,c),u();break;case"pingresp":a.log("_handlePacket :: received pingresp"),a.reschedulePing(!0),u();break;case"disconnect":a.emit("disconnect",c),u();break;default:a.log("_handlePacket :: unknown command"),u();break}};l.default=o}),ms=pe(l=>{le(),ue(),ce(),Object.defineProperty(l,"__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(){}};l.default=e}),mu=pe(l=>{le(),ue(),ce(),Object.defineProperty(l,"__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={}}};l.default=e}),gu=pe(l=>{le(),ue(),ce();var e=l&&l.__importDefault||function(n){return n&&n.__esModule?n:{default:n}};Object.defineProperty(l,"__esModule",{value:!0}),l.TypedEventEmitter=void 0;var t=e((Et(),Me(bt))),r=Ut(),s=class{};l.TypedEventEmitter=s,(0,r.applyMixin)(s,t.default)}),fr=pe((l,e)=>{le(),ue(),ce();function t(r){"@babel/helpers - typeof";return e.exports=t=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(s){return typeof s}:function(s){return s&&typeof Symbol=="function"&&s.constructor===Symbol&&s!==Symbol.prototype?"symbol":typeof s},e.exports.__esModule=!0,e.exports.default=e.exports,t(r)}e.exports=t,e.exports.__esModule=!0,e.exports.default=e.exports}),bu=pe((l,e)=>{le(),ue(),ce();var t=fr().default;function r(s,n){if(t(s)!="object"||!s)return s;var i=s[Symbol.toPrimitive];if(i!==void 0){var o=i.call(s,n||"default");if(t(o)!="object")return o;throw new TypeError("@@toPrimitive must return a primitive value.")}return(n==="string"?String:Number)(s)}e.exports=r,e.exports.__esModule=!0,e.exports.default=e.exports}),yu=pe((l,e)=>{le(),ue(),ce();var t=fr().default,r=bu();function s(n){var i=r(n,"string");return t(i)=="symbol"?i:i+""}e.exports=s,e.exports.__esModule=!0,e.exports.default=e.exports}),vu=pe((l,e)=>{le(),ue(),ce();var t=yu();function r(s,n,i){return(n=t(n))in s?Object.defineProperty(s,n,{value:i,enumerable:!0,configurable:!0,writable:!0}):s[n]=i,s}e.exports=r,e.exports.__esModule=!0,e.exports.default=e.exports}),wu=pe((l,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}),_u=pe((l,e)=>{le(),ue(),ce();function t(r,s){var n=r==null?null:typeof Symbol<"u"&&r[Symbol.iterator]||r["@@iterator"];if(n!=null){var i,o,a,c,u=[],h=!0,p=!1;try{if(a=(n=n.call(r)).next,s===0){if(Object(n)!==n)return;h=!1}else for(;!(h=(i=a.call(n)).done)&&(u.push(i.value),u.length!==s);h=!0);}catch(b){p=!0,o=b}finally{try{if(!h&&n.return!=null&&(c=n.return(),Object(c)!==c))return}finally{if(p)throw o}}return u}}e.exports=t,e.exports.__esModule=!0,e.exports.default=e.exports}),ku=pe((l,e)=>{le(),ue(),ce();function t(r,s){(s==null||s>r.length)&&(s=r.length);for(var n=0,i=Array(s);n<s;n++)i[n]=r[n];return i}e.exports=t,e.exports.__esModule=!0,e.exports.default=e.exports}),xu=pe((l,e)=>{le(),ue(),ce();var t=ku();function r(s,n){if(s){if(typeof s=="string")return t(s,n);var i={}.toString.call(s).slice(8,-1);return i==="Object"&&s.constructor&&(i=s.constructor.name),i==="Map"||i==="Set"?Array.from(s):i==="Arguments"||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(i)?t(s,n):void 0}}e.exports=r,e.exports.__esModule=!0,e.exports.default=e.exports}),Su=pe((l,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}),Eu=pe((l,e)=>{le(),ue(),ce();var t=wu(),r=_u(),s=xu(),n=Su();function i(o,a){return t(o)||r(o,a)||s(o,a)||n()}e.exports=i,e.exports.__esModule=!0,e.exports.default=e.exports}),gs=pe((l,e)=>{le(),ue(),ce(),(function(t,r){typeof l=="object"&&typeof e<"u"?r(l):typeof define=="function"&&define.amd?define(["exports"],r):(t=typeof globalThis<"u"?globalThis:t||self,r(t.fastUniqueNumbers={}))})(l,function(t){var r=function(b){return function(f){var g=b(f);return f.add(g),g}},s=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,o=i*2,a=function(b,f){return function(g){var y=f.get(g),k=y===void 0?g.size:y<o?y+1:0;if(!g.has(k))return b(g,k);if(g.size<i){for(;g.has(k);)k=Math.floor(Math.random()*o);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)}},c=new WeakMap,u=s(c),h=a(u,c),p=r(h);t.addUniqueNumber=p,t.generateUniqueNumber=h})}),Au=pe((l,e)=>{le(),ue(),ce();function t(s,n,i,o,a,c,u){try{var h=s[c](u),p=h.value}catch(b){return void i(b)}h.done?n(p):Promise.resolve(p).then(o,a)}function r(s){return function(){var n=this,i=arguments;return new Promise(function(o,a){var c=s.apply(n,i);function u(p){t(c,o,a,u,h,"next",p)}function h(p){t(c,o,a,u,h,"throw",p)}u(void 0)})}}e.exports=r,e.exports.__esModule=!0,e.exports.default=e.exports}),bs=pe((l,e)=>{le(),ue(),ce();function t(r,s){this.v=r,this.k=s}e.exports=t,e.exports.__esModule=!0,e.exports.default=e.exports}),ys=pe((l,e)=>{le(),ue(),ce();function t(r,s,n,i){var o=Object.defineProperty;try{o({},"",{})}catch{o=0}e.exports=t=function(a,c,u,h){function p(b,f){t(a,b,function(g){return this._invoke(b,f,g)})}c?o?o(a,c,{value:u,enumerable:!h,configurable:!h,writable:!h}):a[c]=u:(p("next",0),p("throw",1),p("return",2))},e.exports.__esModule=!0,e.exports.default=e.exports,t(r,s,n,i)}e.exports=t,e.exports.__esModule=!0,e.exports.default=e.exports}),vs=pe((l,e)=>{le(),ue(),ce();var t=ys();function r(){var s,n,i=typeof Symbol=="function"?Symbol:{},o=i.iterator||"@@iterator",a=i.toStringTag||"@@toStringTag";function c(k,m,w,S){var v=m&&m.prototype instanceof h?m:h,E=Object.create(v.prototype);return t(E,"_invoke",(function(x,I,P){var O,B,T,q=0,D=P||[],N=!1,ae={p:0,n:0,v:s,a:Y,f:Y.bind(s,4),d:function(V,re){return O=V,B=0,T=s,ae.n=re,u}};function Y(V,re){for(B=V,T=re,n=0;!N&&q&&!F&&n<D.length;n++){var F,Z=D[n],M=ae.p,J=Z[2];V>3?(F=J===re)&&(T=Z[(B=Z[4])?5:(B=3,3)],Z[4]=Z[5]=s):Z[0]<=M&&((F=V<2&&M<Z[1])?(B=0,ae.v=re,ae.n=Z[1]):M<J&&(F=V<3||Z[0]>re||re>J)&&(Z[4]=V,Z[5]=re,ae.n=J,B=0))}if(F||V>1)return u;throw N=!0,re}return function(V,re,F){if(q>1)throw TypeError("Generator is already running");for(N&&re===1&&Y(re,F),B=re,T=F;(n=B<2?s:T)||!N;){O||(B?B<3?(B>1&&(ae.n=-1),Y(B,T)):ae.n=T:ae.v=T);try{if(q=2,O){if(B||(V="next"),n=O[V]){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 '"+V+"' method"),B=1);O=s}else if((n=(N=ae.n<0)?T:x.call(I,ae))!==u)break}catch(Z){O=s,B=1,T=Z}finally{q=1}}return{value:n,done:N}}})(k,w,S),!0),E}var u={};function h(){}function p(){}function b(){}n=Object.getPrototypeOf;var f=[][o]?n(n([][o]())):(t(n={},o,function(){return this}),n),g=b.prototype=h.prototype=Object.create(f);function y(k){return Object.setPrototypeOf?Object.setPrototypeOf(k,b):(k.__proto__=b,t(k,a,"GeneratorFunction")),k.prototype=Object.create(g),k}return p.prototype=b,t(g,"constructor",b),t(b,"constructor",p),p.displayName="GeneratorFunction",t(b,a,"GeneratorFunction"),t(g),t(g,a,"Generator"),t(g,o,function(){return this}),t(g,"toString",function(){return"[object Generator]"}),(e.exports=r=function(){return{w:c,m:y}},e.exports.__esModule=!0,e.exports.default=e.exports)()}e.exports=r,e.exports.__esModule=!0,e.exports.default=e.exports}),ws=pe((l,e)=>{le(),ue(),ce();var t=bs(),r=ys();function s(n,i){function o(c,u,h,p){try{var b=n[c](u),f=b.value;return f instanceof t?i.resolve(f.v).then(function(g){o("next",g,h,p)},function(g){o("throw",g,h,p)}):i.resolve(f).then(function(g){b.value=g,h(b)},function(g){return o("throw",g,h,p)})}catch(g){p(g)}}var a;this.next||(r(s.prototype),r(s.prototype,typeof Symbol=="function"&&Symbol.asyncIterator||"@asyncIterator",function(){return this})),r(this,"_invoke",function(c,u,h){function p(){return new i(function(b,f){o(c,h,b,f)})}return a=a?a.then(p,p):p()},!0)}e.exports=s,e.exports.__esModule=!0,e.exports.default=e.exports}),_s=pe((l,e)=>{le(),ue(),ce();var t=vs(),r=ws();function s(n,i,o,a,c){return new r(t().w(n,i,o,a),c||Promise)}e.exports=s,e.exports.__esModule=!0,e.exports.default=e.exports}),Iu=pe((l,e)=>{le(),ue(),ce();var t=_s();function r(s,n,i,o,a){var c=t(s,n,i,o,a);return c.next().then(function(u){return u.done?u.value:c.next()})}e.exports=r,e.exports.__esModule=!0,e.exports.default=e.exports}),Tu=pe((l,e)=>{le(),ue(),ce();function t(r){var s=Object(r),n=[];for(var i in s)n.unshift(i);return function o(){for(;n.length;)if((i=n.pop())in s)return o.value=i,o.done=!1,o;return o.done=!0,o}}e.exports=t,e.exports.__esModule=!0,e.exports.default=e.exports}),Cu=pe((l,e)=>{le(),ue(),ce();var t=fr().default;function r(s){if(s!=null){var n=s[typeof Symbol=="function"&&Symbol.iterator||"@@iterator"],i=0;if(n)return n.call(s);if(typeof s.next=="function")return s;if(!isNaN(s.length))return{next:function(){return s&&i>=s.length&&(s=void 0),{value:s&&s[i++],done:!s}}}}throw new TypeError(t(s)+" is not iterable")}e.exports=r,e.exports.__esModule=!0,e.exports.default=e.exports}),Ou=pe((l,e)=>{le(),ue(),ce();var t=bs(),r=vs(),s=Iu(),n=_s(),i=ws(),o=Tu(),a=Cu();function c(){var u=r(),h=u.m(c),p=(Object.getPrototypeOf?Object.getPrototypeOf(h):h.__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(S,v){return m(w.a,f[S],v)},delegateYield:function(S,v,E){return k.resultName=v,m(w.d,a(S),E)},finish:function(S){return m(w.f,S)}},m=function(S,v,E){w.p=k.prev,w.n=k.next;try{return S(v,E)}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=c=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,S){return(b(k)?n:s)(g(y),k,m,w,S)},keys:o,values:a}},e.exports.__esModule=!0,e.exports.default=e.exports)()}e.exports=c,e.exports.__esModule=!0,e.exports.default=e.exports}),Pu=pe((l,e)=>{le(),ue(),ce();var t=Ou()();e.exports=t;try{regeneratorRuntime=t}catch{typeof globalThis=="object"?globalThis.regeneratorRuntime=t:Function("r","regeneratorRuntime = r")(t)}}),Mu=pe((l,e)=>{le(),ue(),ce(),(function(t,r){typeof l=="object"&&typeof e<"u"?r(l,vu(),Eu(),gs(),Au(),Pu()):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))})(l,function(t,r,s,n,i,o){var a=function(m){return typeof m.start=="function"},c=new WeakMap;function u(m,w){var S=Object.keys(m);if(Object.getOwnPropertySymbols){var v=Object.getOwnPropertySymbols(m);w&&(v=v.filter(function(E){return Object.getOwnPropertyDescriptor(m,E).enumerable})),S.push.apply(S,v)}return S}function h(m){for(var w=1;w<arguments.length;w++){var S=arguments[w]!=null?arguments[w]:{};w%2?u(Object(S),!0).forEach(function(v){r(m,v,S[v])}):Object.getOwnPropertyDescriptors?Object.defineProperties(m,Object.getOwnPropertyDescriptors(S)):u(Object(S)).forEach(function(v){Object.defineProperty(m,v,Object.getOwnPropertyDescriptor(S,v))})}return m}var p=function(m){return h(h({},m),{},{connect:function(w){var S=w.call;return i(o.mark(function v(){var E,x,I,P;return o.wrap(function(O){for(;;)switch(O.prev=O.next){case 0:return E=new MessageChannel,x=E.port1,I=E.port2,O.next=1,S("connect",{port:x},[x]);case 1:return P=O.sent,c.set(I,P),O.abrupt("return",I);case 2:case"end":return O.stop()}},v)}))},disconnect:function(w){var S=w.call;return(function(){var v=i(o.mark(function E(x){var I;return o.wrap(function(P){for(;;)switch(P.prev=P.next){case 0:if(I=c.get(x),I!==void 0){P.next=1;break}throw new Error("The given port is not connected.");case 1:return P.next=2,S("disconnect",{portId:I});case 2:case"end":return P.stop()}},E)}));return function(E){return v.apply(this,arguments)}})()},isSupported:function(w){var S=w.call;return function(){return S("isSupported")}}})};function b(m,w){var S=Object.keys(m);if(Object.getOwnPropertySymbols){var v=Object.getOwnPropertySymbols(m);w&&(v=v.filter(function(E){return Object.getOwnPropertyDescriptor(m,E).enumerable})),S.push.apply(S,v)}return S}function f(m){for(var w=1;w<arguments.length;w++){var S=arguments[w]!=null?arguments[w]:{};w%2?b(Object(S),!0).forEach(function(v){r(m,v,S[v])}):Object.getOwnPropertyDescriptors?Object.defineProperties(m,Object.getOwnPropertyDescriptors(S)):b(Object(S)).forEach(function(v){Object.defineProperty(m,v,Object.getOwnPropertyDescriptor(S,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(S){var v=y(S);S.addEventListener("message",function(D){var N=D.data,ae=N.id;if(ae!==null&&v.has(ae)){var Y=v.get(ae),V=Y.reject,re=Y.resolve;v.delete(ae),N.error===void 0?re(N.result):V(new Error(N.error.message))}}),a(S)&&S.start();for(var E=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,V){var re=n.generateUniqueNumber(v);v.set(re,{reject:V,resolve:Y}),N===null?S.postMessage({id:re,method:D},ae):S.postMessage({id:re,method:D,params:N},ae)})},x=function(D,N){var ae=arguments.length>2&&arguments[2]!==void 0?arguments[2]:[];S.postMessage({id:null,method:D,params:N},ae)},I={},P=0,O=Object.entries(w);P<O.length;P++){var B=s(O[P],2),T=B[0],q=B[1];I=f(f({},I),{},r({},T,q({call:E,notify:x})))}return f({},I)}};t.createBroker=k})}),Ru=pe((l,e)=>{le(),ue(),ce(),(function(t,r){typeof l=="object"&&typeof e<"u"?r(l,fr(),Mu(),gs()):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))})(l,function(t,r,s,n){var i=new Map([[0,null]]),o=new Map([[0,null]]),a=s.createBroker({clearInterval:function(u){var h=u.call;return function(p){r(i.get(p))==="symbol"&&(i.set(p,null),h("clear",{timerId:p,timerType:"interval"}).then(function(){i.delete(p)}))}},clearTimeout:function(u){var h=u.call;return function(p){r(o.get(p))==="symbol"&&(o.set(p,null),h("clear",{timerId:p,timerType:"timeout"}).then(function(){o.delete(p)}))}},setInterval:function(u){var h=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 h("set",{delay:b,now:performance.timeOrigin+performance.now(),timerId:m,timerType:"interval"}).then(function(){var S=i.get(m);if(S===void 0)throw new Error("The timer is in an undefined state.");S===k&&(p.apply(void 0,g),i.get(m)===k&&w())})};return w(),m}},setTimeout:function(u){var h=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(o);return o.set(m,k),h("set",{delay:b,now:performance.timeOrigin+performance.now(),timerId:m,timerType:"timeout"}).then(function(){var w=o.get(m);if(w===void 0)throw new Error("The timer is in an undefined state.");w===k&&(o.delete(m),p.apply(void 0,g))}),m}}}),c=function(u){var h=new Worker(u);return a(h)};t.load=c,t.wrap=a})}),Lu=pe((l,e)=>{le(),ue(),ce(),(function(t,r){typeof l=="object"&&typeof e<"u"?r(l,Ru()):typeof define=="function"&&define.amd?define(["exports","worker-timers-broker"],r):(t=typeof globalThis<"u"?globalThis:t||self,r(t.workerTimers={},t.workerTimersBroker))})(l,function(t,r){var s=function(h,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=h(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=s(r.load,n),o=function(h){return i().clearInterval(h)},a=function(h){return i().clearTimeout(h)},c=function(){var h;return(h=i()).setInterval.apply(h,arguments)},u=function(){var h;return(h=i()).setTimeout.apply(h,arguments)};t.clearInterval=o,t.clearTimeout=a,t.setInterval=c,t.setTimeout=u})}),pr=pe(l=>{le(),ue(),ce(),Object.defineProperty(l,"__esModule",{value:!0}),l.isReactNativeBrowser=l.isWebWorker=void 0;var e=()=>typeof window<"u"?typeof navigator<"u"&&navigator.userAgent?.toLowerCase().indexOf(" electron/")>-1&&Le?.versions?!Object.prototype.hasOwnProperty.call(Le.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",s=e()||t()||r();l.isWebWorker=t(),l.isReactNativeBrowser=r(),l.default=s}),ju=pe(l=>{le(),ue(),ce();var e=l&&l.__createBinding||(Object.create?function(c,u,h,p){p===void 0&&(p=h);var b=Object.getOwnPropertyDescriptor(u,h);(!b||("get"in b?!u.__esModule:b.writable||b.configurable))&&(b={enumerable:!0,get:function(){return u[h]}}),Object.defineProperty(c,p,b)}:function(c,u,h,p){p===void 0&&(p=h),c[p]=u[h]}),t=l&&l.__setModuleDefault||(Object.create?function(c,u){Object.defineProperty(c,"default",{enumerable:!0,value:u})}:function(c,u){c.default=u}),r=l&&l.__importStar||(function(){var c=function(u){return c=Object.getOwnPropertyNames||function(h){var p=[];for(var b in h)Object.prototype.hasOwnProperty.call(h,b)&&(p[p.length]=b);return p},c(u)};return function(u){if(u&&u.__esModule)return u;var h={};if(u!=null)for(var p=c(u),b=0;b<p.length;b++)p[b]!=="default"&&e(h,u,p[b]);return t(h,u),h}})();Object.defineProperty(l,"__esModule",{value:!0});var s=Lu(),n=r(pr()),i={set:s.setInterval,clear:s.clearInterval},o={set:(c,u)=>setInterval(c,u),clear:c=>clearInterval(c)},a=c=>{switch(c){case"native":return o;case"worker":return i;default:return n.default&&!n.isWebWorker&&!n.isReactNativeBrowser?i:o}};l.default=a}),ks=pe(l=>{le(),ue(),ce();var e=l&&l.__importDefault||function(s){return s&&s.__esModule?s:{default:s}};Object.defineProperty(l,"__esModule",{value:!0});var t=e(ju()),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(s,n){this.client=s,this.timer=typeof n=="object"&&"set"in n&&"clear"in n?n:(0,t.default)(n),this.setKeepalive(s.options.keepalive)}clear(){this.timerId&&(this.timer.clear(this.timerId),this.timerId=null)}setKeepalive(s){if(s*=1e3,isNaN(s)||s<=0||s>2147483647)throw new Error(`Keepalive value must be an integer between 0 and 2147483647. Provided value is ${s}`);this._keepalive=s,this.reschedule(),this.client.log(`KeepaliveManager: set keepalive to ${s}ms`)}destroy(){this.clear(),this.destroyed=!0}reschedule(){if(this.destroyed)return;this.clear(),this.counter=0;let s=Math.ceil(this._keepalive*1.5);this._keepaliveTimeoutTimestamp=Date.now()+s,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)}};l.default=r}),di=pe(l=>{le(),ue(),ce();var e=l&&l.__createBinding||(Object.create?function(v,E,x,I){I===void 0&&(I=x);var P=Object.getOwnPropertyDescriptor(E,x);(!P||("get"in P?!E.__esModule:P.writable||P.configurable))&&(P={enumerable:!0,get:function(){return E[x]}}),Object.defineProperty(v,I,P)}:function(v,E,x,I){I===void 0&&(I=x),v[I]=E[x]}),t=l&&l.__setModuleDefault||(Object.create?function(v,E){Object.defineProperty(v,"default",{enumerable:!0,value:E})}:function(v,E){v.default=E}),r=l&&l.__importStar||(function(){var v=function(E){return v=Object.getOwnPropertyNames||function(x){var I=[];for(var P in x)Object.prototype.hasOwnProperty.call(x,P)&&(I[I.length]=P);return I},v(E)};return function(E){if(E&&E.__esModule)return E;var x={};if(E!=null)for(var I=v(E),P=0;P<I.length;P++)I[P]!=="default"&&e(x,E,I[P]);return t(x,E),x}})(),s=l&&l.__importDefault||function(v){return v&&v.__esModule?v:{default:v}};Object.defineProperty(l,"__esModule",{value:!0});var n=s(zc()),i=It(),o=s(Gc()),a=s(ht()),c=r(as()),u=s(ls()),h=s(pu()),p=s(ms()),b=s(mu()),f=Ut(),g=gu(),y=s(ks()),k=r(pr()),m=globalThis.setImmediate||((...v)=>{let E=v.shift();(0,f.nextTick)(()=>{E(...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"},S=class _o 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(E,x){super(),this.options=x||{};for(let I in w)typeof this.options[I]>"u"?this.options[I]=w[I]:this.options[I]=x[I];this.log=this.options.log||(0,a.default)("mqttjs:client"),this.noop=this._noop.bind(this),this.log("MqttClient :: version:",_o.VERSION),k.isWebWorker?this.log("MqttClient :: environment","webworker"):this.log("MqttClient :: environment",k.default?"browser":"node"),this.log("MqttClient :: options.protocol",x.protocol),this.log("MqttClient :: options.protocolVersion",x.protocolVersion),this.log("MqttClient :: options.username",x.username),this.log("MqttClient :: options.keepalive",x.keepalive),this.log("MqttClient :: options.reconnectPeriod",x.reconnectPeriod),this.log("MqttClient :: options.rejectUnauthorized",x.rejectUnauthorized),this.log("MqttClient :: options.properties.topicAliasMaximum",x.properties?x.properties.topicAliasMaximum:void 0),this.options.clientId=typeof x.clientId=="string"?x.clientId:_o.defaultId(),this.log("MqttClient :: clientId",this.options.clientId),this.options.customHandleAcks=x.protocolVersion===5&&x.customHandleAcks?x.customHandleAcks:(...I)=>{I[3](null,0)},this.options.writeCache||(n.default.writeToStream.cacheNumbers=!1),this.streamBuilder=E,this.messageIdProvider=typeof this.options.messageIdProvider>"u"?new p.default:this.options.messageIdProvider,this.outgoingStore=x.outgoingStore||new u.default,this.incomingStore=x.incomingStore||new u.default,this.queueQoSZero=x.queueQoSZero===void 0?!0:x.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,x.properties&&x.properties.topicAliasMaximum>0&&(x.properties.topicAliasMaximum>65535?this.log("MqttClient :: options.properties.topicAliasMaximum is out of range"):this.topicAliasRecv=new b.default(x.properties.topicAliasMaximum)),this.on("connect",()=>{let{queue:I}=this,P=()=>{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,q=>{O.cb&&O.cb(q),P()}):(this.log("messageId: %d has already used. The message is skipped and removed.",B.messageId),P())};this.log("connect :: sending queued packets"),P()}),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(E,x){x()}handleMessage(E,x){x()}_nextId(){return this.messageIdProvider.allocate()}getLastMessageId(){return this.messageIdProvider.getLastAllocated()}connect(){let E=new i.Writable,x=n.default.parser(this.options),I=null,P=[];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),x.on("packet",D=>{this.log("parser :: on packet push to packets array."),P.push(D)});let O=()=>{this.log("work :: getting next packet in queue");let D=P.shift();if(D)this.log("work :: packet pulled from queue"),(0,h.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(P.length)(0,f.nextTick)(O);else{let D=I;I=null,D()}};E._write=(D,N,ae)=>{I=ae,this.log("writable stream :: parsing buffer"),x.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(E),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 q={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&&(q.will={...this.options.will,payload:this.options.will?.payload}),this.topicAliasRecv&&(q.properties||(q.properties={}),this.topicAliasRecv&&(q.properties.topicAliasMaximum=this.topicAliasRecv.max)),this._writePacket(q),x.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(E,x,I,P){this.log("publish :: message `%s` to topic `%s`",x,E);let{options:O}=this;typeof I=="function"&&(P=I,I=null),I=I||{},I={qos:0,retain:!1,dup:!1,...I};let{qos:B,retain:T,dup:q,properties:D,cbStorePut:N}=I;if(this._checkDisconnecting(P))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 V={cmd:"publish",topic:E,payload:x,qos:B,retain:T,messageId:Y,dup:q};switch(O.protocolVersion===5&&(V.properties=D),this.log("publish :: qos",B),B){case 1:case 2:this.outgoing[V.messageId]={volatile:!1,cb:P||this.noop},this.log("MqttClient:publish: packet cmd: %s",V.cmd),this._sendPacket(V,void 0,N);break;default:this.log("MqttClient:publish: packet cmd: %s",V.cmd),this._sendPacket(V,P,N);break}return!0};return(this._storeProcessing||this._storeProcessingQueue.length>0||!ae())&&this._storeProcessingQueue.push({invoke:ae,cbStorePut:I.cbStorePut,callback:P}),this}publishAsync(E,x,I){return new Promise((P,O)=>{this.publish(E,x,I,(B,T)=>{B?O(B):P(T)})})}subscribe(E,x,I){let P=this.options.protocolVersion;typeof x=="function"&&(I=x),I=I||this.noop;let O=!1,B=[];typeof E=="string"?(E=[E],B=E):Array.isArray(E)?B=E:typeof E=="object"&&(O=E.resubscribe,delete E.resubscribe,B=Object.keys(E));let T=c.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 q={qos:0};P===5&&(q.nl=!1,q.rap=!1,q.rh=0),x={...q,...x};let{properties:D}=x,N=[],ae=(re,F)=>{if(F=F||x,!Object.prototype.hasOwnProperty.call(this._resubscribeTopics,re)||this._resubscribeTopics[re].qos<F.qos||O){let Z={topic:re,qos:F.qos};P===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(E)?E.forEach(re=>{this.log("subscribe: array topic %s",re),ae(re)}):Object.keys(E).forEach(re=>{this.log("subscribe: object topic %s, %o",re,E[re]),ae(re,E[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};P===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 M=new Promise((J,be)=>{this.outgoing[Z.messageId]={volatile:!0,cb(te,we){if(!te){let{granted:G}=we;for(let j=0;j<G.length;j+=1)re[j].qos=G[j]}te?be(new f.ErrorWithSubackPacket(te.message,we)):J(we)}}});return this.log("subscribe :: call _sendPacket"),this._sendPacket(Z),M},V=()=>{let re=this.options.subscribeBatchSize??N.length,F=[];for(let Z=0;Z<N.length;Z+=re){let M=N.slice(Z,Z+re),J=this._nextId();if(J===null)return this.log("No messageId left"),!1;F.push(Y(M,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||!V())&&this._storeProcessingQueue.push({invoke:V,callback:I}),this}subscribeAsync(E,x){return new Promise((I,P)=>{this.subscribe(E,x,(O,B)=>{O?P(O):I(B)})})}unsubscribe(E,x,I){typeof E=="string"&&(E=[E]),typeof x=="function"&&(I=x),I=I||this.noop;let P=c.validateTopics(E);if(P!==null)return m(I,new Error(`Invalid topic ${P}`)),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 E=="string"?T.unsubscriptions=[E]:Array.isArray(E)&&(T.unsubscriptions=E),this.options.resubscribe&&T.unsubscriptions.forEach(q=>{delete this._resubscribeTopics[q]}),typeof x=="object"&&x.properties&&(T.properties=x.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(E,x){return new Promise((I,P)=>{this.unsubscribe(E,x,(O,B)=>{O?P(O):I(B)})})}end(E,x,I){this.log("end :: (%s)",this.options.clientId),(E==null||typeof E!="boolean")&&(I=I||x,x=E,E=!1),typeof x!="object"&&(I=I||x,x=null),this.log("end :: cb? %s",!!I),(!I||typeof I!="function")&&(I=this.noop);let P=()=>{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 q=B||T;this.log("end :: closeStores: invoking callback with args"),I(q)}})}),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,E),this._cleanUp(E,()=>{this.log("end :: finish :: calling process.nextTick on closeStores"),(0,f.nextTick)(P)},x)};return this.disconnecting?(I(),this):(this._clearReconnect(),this.disconnecting=!0,!E&&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(E,x){return new Promise((I,P)=>{this.end(E,x,O=>{O?P(O):I()})})}removeOutgoingMessage(E){if(this.outgoing[E]){let{cb:x}=this.outgoing[E];this._removeOutgoingAndStoreMessage(E,()=>{x(new Error("Message removed"))})}return this}reconnect(E){this.log("client reconnect");let x=()=>{E?(this.options.incomingStore=E.incomingStore,this.options.outgoingStore=E.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=x:x(),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(E=>{this.outgoing[E].volatile&&typeof this.outgoing[E].cb=="function"&&(this.outgoing[E].cb(new Error("Connection closed")),delete this.outgoing[E])}))}_flush(){this.outgoing&&(this.log("_flush: queue exists? %b",!!this.outgoing),Object.keys(this.outgoing).forEach(E=>{typeof this.outgoing[E].cb=="function"&&(this.outgoing[E].cb(new Error("Connection closed")),delete this.outgoing[E])}))}_removeTopicAliasAndRecoverTopicName(E){let x;E.properties&&(x=E.properties.topicAlias);let I=E.topic.toString();if(this.log("_removeTopicAliasAndRecoverTopicName :: alias %d, topic %o",x,I),I.length===0){if(typeof x>"u")return new Error("Unregistered Topic Alias");if(I=this.topicAliasSend.getTopicByAlias(x),typeof I>"u")return new Error("Unregistered Topic Alias");E.topic=I}x&&delete E.properties.topicAlias}_checkDisconnecting(E){return this.disconnecting&&(E&&E!==this.noop?E(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(E,x,I={}){if(x&&(this.log("_cleanUp :: done callback provided for on stream close"),this.stream.on("close",x)),this.log("_cleanUp :: forced? %s",E),E)this.options.reconnectPeriod===0&&this.options.clean&&this._flush(),this.log("_cleanUp :: (%s) :: destroying stream",this.options.clientId),this.stream.destroy();else{let P={cmd:"disconnect",...I};this.log("_cleanUp :: (%s) :: call _sendPacket with disconnect packet",this.options.clientId),this._sendPacket(P,()=>{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(),x&&!this.connected&&(this.log("_cleanUp :: (%s) :: removing stream `done` callback `close` listener",this.options.clientId),this.stream.removeListener("close",x),x())}_storeAndSend(E,x,I){this.log("storeAndSend :: store packet with cmd %s to outgoingStore",E.cmd);let P=E,O;if(P.cmd==="publish"&&(P=(0,o.default)(E),O=this._removeTopicAliasAndRecoverTopicName(P),O))return x&&x(O);this.outgoingStore.put(P,B=>{if(B)return x&&x(B);I(),this._writePacket(E,x)})}_applyTopicAlias(E){if(this.options.protocolVersion===5&&E.cmd==="publish"){let x;E.properties&&(x=E.properties.topicAlias);let I=E.topic.toString();if(this.topicAliasSend)if(x){if(I.length!==0&&(this.log("applyTopicAlias :: register topic: %s - alias: %d",I,x),!this.topicAliasSend.put(I,x)))return this.log("applyTopicAlias :: error out of range. topic: %s - alias: %d",I,x),new Error("Sending Topic Alias out of range")}else I.length!==0&&(this.options.autoAssignTopicAlias?(x=this.topicAliasSend.getAliasByTopic(I),x?(E.topic="",E.properties={...E.properties,topicAlias:x},this.log("applyTopicAlias :: auto assign(use) topic: %s - alias: %d",I,x)):(x=this.topicAliasSend.getLruAlias(),this.topicAliasSend.put(I,x),E.properties={...E.properties,topicAlias:x},this.log("applyTopicAlias :: auto assign topic: %s - alias: %d",I,x))):this.options.autoUseTopicAlias&&(x=this.topicAliasSend.getAliasByTopic(I),x&&(E.topic="",E.properties={...E.properties,topicAlias:x},this.log("applyTopicAlias :: auto use topic: %s - alias: %d",I,x))));else if(x)return this.log("applyTopicAlias :: error out of range. topic: %s - alias: %d",I,x),new Error("Sending Topic Alias out of range")}}_noop(E){this.log("noop ::",E)}_writePacket(E,x){this.log("_writePacket :: packet: %O",E),this.log("_writePacket :: emitting `packetsend`"),this.emit("packetsend",E),this.log("_writePacket :: writing to stream");let I=n.default.writeToStream(E,this.stream,this.options);this.log("_writePacket :: writeToStream result %s",I),!I&&x&&x!==this.noop?(this.log("_writePacket :: handle events on `drain` once through callback."),this.stream.once("drain",x)):x&&(this.log("_writePacket :: invoking cb"),x())}_sendPacket(E,x,I,P){this.log("_sendPacket :: (%s) :: start",this.options.clientId),I=I||this.noop,x=x||this.noop;let O=this._applyTopicAlias(E);if(O){x(O);return}if(!this.connected){if(E.cmd==="auth"){this._writePacket(E,x);return}this.log("_sendPacket :: client not connected. Storing packet offline."),this._storePacket(E,x,I);return}if(P){this._writePacket(E,x);return}switch(E.cmd){case"publish":break;case"pubrel":this._storeAndSend(E,x,I);return;default:this._writePacket(E,x);return}switch(E.qos){case 2:case 1:this._storeAndSend(E,x,I);break;default:this._writePacket(E,x);break}this.log("_sendPacket :: (%s) :: end",this.options.clientId)}_storePacket(E,x,I){this.log("_storePacket :: packet: %o",E),this.log("_storePacket :: cb? %s",!!x),I=I||this.noop;let P=E;if(P.cmd==="publish"){P=(0,o.default)(E);let B=this._removeTopicAliasAndRecoverTopicName(P);if(B)return x&&x(B)}let O=P.qos||0;O===0&&this.queueQoSZero||P.cmd!=="publish"?this.queue.push({packet:P,cb:x}):O>0?(x=this.outgoing[P.messageId]?this.outgoing[P.messageId].cb:null,this.outgoingStore.put(P,B=>{if(B)return x&&x(B);I()})):x&&x(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(E=!1){this.keepaliveManager&&this.options.keepalive&&(E||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 E=Object.keys(this._resubscribeTopics);if(!this._firstConnection&&(this.options.clean||this.options.protocolVersion>=4&&!this.connackPacket.sessionPresent)&&E.length>0)if(this.options.resubscribe)if(this.options.protocolVersion===5){this.log("_resubscribe: protocolVersion 5");for(let x=0;x<E.length;x++){let I={};I[E[x]]=this._resubscribeTopics[E[x]],I.resubscribe=!0,this.subscribe(I,{properties:I[E[x]].properties})}}else this._resubscribeTopics.resubscribe=!0,this.subscribe(this._resubscribeTopics);else this._resubscribeTopics={};this._firstConnection=!1}_onConnect(E){if(this.disconnected){this.emit("connect",E);return}this.connackPacket=E,this.messageIdProvider.clear(),this._setupKeepaliveManager(),this.connected=!0;let x=()=>{let I=this.outgoingStore.createStream(),P=()=>{I.destroy(),I=null,this._flushStoreProcessingQueue(),O()},O=()=>{this._storeProcessing=!1,this._packetIdsDuringStoreProcessing={}};this.once("close",P),I.on("error",T=>{O(),this._flushStoreProcessingQueue(),this.removeListener("close",P),this.emit("error",T)});let B=()=>{if(!I)return;let T=I.read(1),q;if(!T){I.once("readable",B);return}if(this._storeProcessing=!0,this._packetIdsDuringStoreProcessing[T.messageId]){B();return}!this.disconnecting&&!this.reconnectTimer?(q=this.outgoing[T.messageId]?this.outgoing[T.messageId].cb:null,this.outgoing[T.messageId]={volatile:!1,cb(D,N){q&&q(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 q in this._packetIdsDuringStoreProcessing)if(!this._packetIdsDuringStoreProcessing[q]){T=!1;break}this.removeListener("close",P),T?(O(),this._invokeAllStoreProcessingQueue(),this.emit("connect",E)):x()}),B()};x()}_invokeStoreProcessingQueue(){if(!this._storeProcessing&&this._storeProcessingQueue.length>0){let E=this._storeProcessingQueue[0];if(E&&E.invoke())return this._storeProcessingQueue.shift(),!0}return!1}_invokeAllStoreProcessingQueue(){for(;this._invokeStoreProcessingQueue(););}_flushStoreProcessingQueue(){for(let E of this._storeProcessingQueue)E.cbStorePut&&E.cbStorePut(new Error("Connection closed")),E.callback&&E.callback(new Error("Connection closed"));this._storeProcessingQueue.splice(0)}_removeOutgoingAndStoreMessage(E,x){delete this.outgoing[E],this.outgoingStore.del({messageId:E},(I,P)=>{x(I,P),this.messageIdProvider.deallocate(E),this._invokeStoreProcessingQueue()})}};l.default=S}),Nu=pe(l=>{le(),ue(),ce(),Object.defineProperty(l,"__esModule",{value:!0});var e=ps(),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()}};l.default=t});function Uu(){if(fi)return mr;fi=!0;let l=2147483647,e=36,t=1,r=26,s=38,n=700,i=72,o=128,a="-",c=/^xn--/,u=/[^\0-\x7F]/,h=/[\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=[],q=O.length;for(;q--;)T[q]=B(O[q]);return T}function m(O,B){let T=O.split("@"),q="";T.length>1&&(q=T[0]+"@",O=T[1]),O=O.replace(h,".");let D=O.split("."),N=k(D,B).join(".");return q+N}function w(O){let B=[],T=0,q=O.length;for(;T<q;){let D=O.charCodeAt(T++);if(D>=55296&&D<=56319&&T<q){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 S=O=>String.fromCodePoint(...O),v=function(O){return O>=48&&O<58?26+(O-48):O>=65&&O<91?O-65:O>=97&&O<123?O-97:e},E=function(O,B){return O+22+75*(O<26)-((B!=0)<<5)},x=function(O,B,T){let q=0;for(O=T?f(O/n):O>>1,O+=f(O/B);O>b*r>>1;q+=e)O=f(O/b);return f(q+(b+1)*O/(O+s))},I=function(O){let B=[],T=O.length,q=0,D=o,N=i,ae=O.lastIndexOf(a);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 V=q;for(let F=1,Z=e;;Z+=e){Y>=T&&y("invalid-input");let M=v(O.charCodeAt(Y++));M>=e&&y("invalid-input"),M>f((l-q)/F)&&y("overflow"),q+=M*F;let J=Z<=N?t:Z>=N+r?r:Z-N;if(M<J)break;let be=e-J;F>f(l/be)&&y("overflow"),F*=be}let re=B.length+1;N=x(q-V,re,V==0),f(q/re)>l-D&&y("overflow"),D+=f(q/re),q%=re,B.splice(q++,0,D)}return String.fromCodePoint(...B)},P=function(O){let B=[];O=w(O);let T=O.length,q=o,D=0,N=i;for(let V of O)V<128&&B.push(g(V));let ae=B.length,Y=ae;for(ae&&B.push(a);Y<T;){let V=l;for(let F of O)F>=q&&F<V&&(V=F);let re=Y+1;V-q>f((l-D)/re)&&y("overflow"),D+=(V-q)*re,q=V;for(let F of O)if(F<q&&++D>l&&y("overflow"),F===q){let Z=D;for(let M=e;;M+=e){let J=M<=N?t:M>=N+r?r:M-N;if(Z<J)break;let be=Z-J,te=e-J;B.push(g(E(J+be%te,0))),Z=f(be/te)}B.push(g(E(Z,0))),N=x(D,re,Y===ae),D=0,++Y}++D,++q}return B.join("")};return mr={version:"2.3.1",ucs2:{decode:w,encode:S},decode:I,encode:P,toASCII:function(O){return m(O,function(B){return u.test(B)?"xn--"+P(B):B})},toUnicode:function(O){return m(O,function(B){return c.test(B)?I(B.slice(4).toLowerCase()):B})}},mr}var mr,fi,vt,Bu=Ve(()=>{le(),ue(),ce(),mr={},fi=!1,vt=Uu(),vt.decode,vt.encode,vt.toASCII,vt.toUnicode,vt.ucs2,vt.version});function Du(){return bi||(bi=!0,gi=function(){if(typeof Symbol!="function"||typeof Object.getOwnPropertySymbols!="function")return!1;if(typeof Symbol.iterator=="symbol")return!0;var l={},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;l[e]=r;for(e in l)return!1;if(typeof Object.keys=="function"&&Object.keys(l).length!==0||typeof Object.getOwnPropertyNames=="function"&&Object.getOwnPropertyNames(l).length!==0)return!1;var s=Object.getOwnPropertySymbols(l);if(s.length!==1||s[0]!==e||!Object.prototype.propertyIsEnumerable.call(l,e))return!1;if(typeof Object.getOwnPropertyDescriptor=="function"){var n=Object.getOwnPropertyDescriptor(l,e);if(n.value!==r||n.enumerable!==!0)return!1}return!0}),gi}function Fu(){return vi||(vi=!0,yi=Error),yi}function $u(){return _i||(_i=!0,wi=EvalError),wi}function qu(){return xi||(xi=!0,ki=RangeError),ki}function Hu(){return Ei||(Ei=!0,Si=ReferenceError),Si}function xs(){return Ii||(Ii=!0,Ai=SyntaxError),Ai}function Qt(){return Ci||(Ci=!0,Ti=TypeError),Ti}function Wu(){return Pi||(Pi=!0,Oi=URIError),Oi}function zu(){if(Mi)return gr;Mi=!0;var l=typeof Symbol<"u"&&Symbol,e=Du();return gr=function(){return typeof l!="function"||typeof Symbol!="function"||typeof l("foo")!="symbol"||typeof Symbol("bar")!="symbol"?!1:e()},gr}function Vu(){if(Ri)return br;Ri=!0;var l={__proto__:null,foo:{}},e=Object;return br=function(){return{__proto__:l}.foo===l.foo&&!(l instanceof e)},br}function Gu(){if(Li)return yr;Li=!0;var l="Function.prototype.bind called on incompatible ",e=Object.prototype.toString,t=Math.max,r="[object Function]",s=function(o,a){for(var c=[],u=0;u<o.length;u+=1)c[u]=o[u];for(var h=0;h<a.length;h+=1)c[h+o.length]=a[h];return c},n=function(o,a){for(var c=[],u=a,h=0;u<o.length;u+=1,h+=1)c[h]=o[u];return c},i=function(o,a){for(var c="",u=0;u<o.length;u+=1)c+=o[u],u+1<o.length&&(c+=a);return c};return yr=function(o){var a=this;if(typeof a!="function"||e.apply(a)!==r)throw new TypeError(l+a);for(var c=n(arguments,1),u,h=function(){if(this instanceof u){var y=a.apply(this,s(c,arguments));return Object(y)===y?y:this}return a.apply(o,s(c,arguments))},p=t(0,a.length-c.length),b=[],f=0;f<p;f++)b[f]="$"+f;if(u=Function("binder","return function ("+i(b,",")+"){ return binder.apply(this,arguments); }")(h),a.prototype){var g=function(){};g.prototype=a.prototype,u.prototype=new g,g.prototype=null}return u},yr}function pi(){if(ji)return vr;ji=!0;var l=Gu();return vr=Function.prototype.bind||l,vr}function Ku(){if(Ni)return wr;Ni=!0;var l=Function.prototype.call,e=Object.prototype.hasOwnProperty,t=pi();return wr=t.call(l,e),wr}function Bt(){if(Ui)return _r;Ui=!0;var l,e=Fu(),t=$u(),r=qu(),s=Hu(),n=xs(),i=Qt(),o=Wu(),a=Function,c=function(Y){try{return a('"use strict"; return ('+Y+").constructor;")()}catch{}},u=Object.getOwnPropertyDescriptor;if(u)try{u({},"")}catch{u=null}var h=function(){throw new i},p=u?(function(){try{return arguments.callee,h}catch{try{return u(arguments,"callee").get}catch{return h}}})():h,b=zu()(),f=Vu()(),g=Object.getPrototypeOf||(f?function(Y){return Y.__proto__}:null),y={},k=typeof Uint8Array>"u"||!g?l:g(Uint8Array),m={__proto__:null,"%AggregateError%":typeof AggregateError>"u"?l:AggregateError,"%Array%":Array,"%ArrayBuffer%":typeof ArrayBuffer>"u"?l:ArrayBuffer,"%ArrayIteratorPrototype%":b&&g?g([][Symbol.iterator]()):l,"%AsyncFromSyncIteratorPrototype%":l,"%AsyncFunction%":y,"%AsyncGenerator%":y,"%AsyncGeneratorFunction%":y,"%AsyncIteratorPrototype%":y,"%Atomics%":typeof Atomics>"u"?l:Atomics,"%BigInt%":typeof BigInt>"u"?l:BigInt,"%BigInt64Array%":typeof BigInt64Array>"u"?l:BigInt64Array,"%BigUint64Array%":typeof BigUint64Array>"u"?l:BigUint64Array,"%Boolean%":Boolean,"%DataView%":typeof DataView>"u"?l:DataView,"%Date%":Date,"%decodeURI%":decodeURI,"%decodeURIComponent%":decodeURIComponent,"%encodeURI%":encodeURI,"%encodeURIComponent%":encodeURIComponent,"%Error%":e,"%eval%":eval,"%EvalError%":t,"%Float32Array%":typeof Float32Array>"u"?l:Float32Array,"%Float64Array%":typeof Float64Array>"u"?l:Float64Array,"%FinalizationRegistry%":typeof FinalizationRegistry>"u"?l:FinalizationRegistry,"%Function%":a,"%GeneratorFunction%":y,"%Int8Array%":typeof Int8Array>"u"?l:Int8Array,"%Int16Array%":typeof Int16Array>"u"?l:Int16Array,"%Int32Array%":typeof Int32Array>"u"?l:Int32Array,"%isFinite%":isFinite,"%isNaN%":isNaN,"%IteratorPrototype%":b&&g?g(g([][Symbol.iterator]())):l,"%JSON%":typeof JSON=="object"?JSON:l,"%Map%":typeof Map>"u"?l:Map,"%MapIteratorPrototype%":typeof Map>"u"||!b||!g?l:g(new Map()[Symbol.iterator]()),"%Math%":Math,"%Number%":Number,"%Object%":Object,"%parseFloat%":parseFloat,"%parseInt%":parseInt,"%Promise%":typeof Promise>"u"?l:Promise,"%Proxy%":typeof Proxy>"u"?l:Proxy,"%RangeError%":r,"%ReferenceError%":s,"%Reflect%":typeof Reflect>"u"?l:Reflect,"%RegExp%":RegExp,"%Set%":typeof Set>"u"?l:Set,"%SetIteratorPrototype%":typeof Set>"u"||!b||!g?l:g(new Set()[Symbol.iterator]()),"%SharedArrayBuffer%":typeof SharedArrayBuffer>"u"?l:SharedArrayBuffer,"%String%":String,"%StringIteratorPrototype%":b&&g?g(""[Symbol.iterator]()):l,"%Symbol%":b?Symbol:l,"%SyntaxError%":n,"%ThrowTypeError%":p,"%TypedArray%":k,"%TypeError%":i,"%Uint8Array%":typeof Uint8Array>"u"?l:Uint8Array,"%Uint8ClampedArray%":typeof Uint8ClampedArray>"u"?l:Uint8ClampedArray,"%Uint16Array%":typeof Uint16Array>"u"?l:Uint16Array,"%Uint32Array%":typeof Uint32Array>"u"?l:Uint32Array,"%URIError%":o,"%WeakMap%":typeof WeakMap>"u"?l:WeakMap,"%WeakRef%":typeof WeakRef>"u"?l:WeakRef,"%WeakSet%":typeof WeakSet>"u"?l:WeakSet};if(g)try{null.error}catch(Y){var w=g(g(Y));m["%Error.prototype%"]=w}var S=function Y(V){var re;if(V==="%AsyncFunction%")re=c("async function () {}");else if(V==="%GeneratorFunction%")re=c("function* () {}");else if(V==="%AsyncGeneratorFunction%")re=c("async function* () {}");else if(V==="%AsyncGenerator%"){var F=Y("%AsyncGeneratorFunction%");F&&(re=F.prototype)}else if(V==="%AsyncIteratorPrototype%"){var Z=Y("%AsyncGenerator%");Z&&g&&(re=g(Z.prototype))}return m[V]=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"]},E=pi(),x=Ku(),I=E.call(Function.call,Array.prototype.concat),P=E.call(Function.apply,Array.prototype.splice),O=E.call(Function.call,String.prototype.replace),B=E.call(Function.call,String.prototype.slice),T=E.call(Function.call,RegExp.prototype.exec),q=/[^%.[\]]+|\[(?:(-?\d+(?:\.\d+)?)|(["'])((?:(?!\2)[^\\]|\\.)*?)\2)\]|(?=(?:\.|\[\])(?:\.|\[\]|%$))/g,D=/\\(\\)?/g,N=function(Y){var V=B(Y,0,1),re=B(Y,-1);if(V==="%"&&re!=="%")throw new n("invalid intrinsic syntax, expected closing `%`");if(re==="%"&&V!=="%")throw new n("invalid intrinsic syntax, expected opening `%`");var F=[];return O(Y,q,function(Z,M,J,be){F[F.length]=J?O(be,D,"$1"):M||Z}),F},ae=function(Y,V){var re=Y,F;if(x(v,re)&&(F=v[re],re="%"+F[0]+"%"),x(m,re)){var Z=m[re];if(Z===y&&(Z=S(re)),typeof Z>"u"&&!V)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 _r=function(Y,V){if(typeof Y!="string"||Y.length===0)throw new i("intrinsic name must be a non-empty string");if(arguments.length>1&&typeof V!="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+"%",V),M=Z.name,J=Z.value,be=!1,te=Z.alias;te&&(F=te[0],P(re,I([0,1],te)));for(var we=1,G=!0;we<re.length;we+=1){var j=re[we],ne=B(j,0,1),W=B(j,-1);if((ne==='"'||ne==="'"||ne==="`"||W==='"'||W==="'"||W==="`")&&ne!==W)throw new n("property names with quotes must have matching quotes");if((j==="constructor"||!G)&&(be=!0),F+="."+j,M="%"+F+"%",x(m,M))J=m[M];else if(J!=null){if(!(j in J)){if(!V)throw new i("base intrinsic for "+Y+" exists, but the property is not available.");return}if(u&&we+1>=re.length){var K=u(J,j);G=!!K,G&&"get"in K&&!("originalValue"in K.get)?J=K.get:J=J[j]}else G=x(J,j),J=J[j];G&&!be&&(m[M]=J)}}return J},_r}function mi(){if(Bi)return kr;Bi=!0;var l=Bt(),e=l("%Object.defineProperty%",!0)||!1;if(e)try{e({},"a",{value:1})}catch{e=!1}return kr=e,kr}function Ss(){if(Di)return xr;Di=!0;var l=Bt(),e=l("%Object.getOwnPropertyDescriptor%",!0);if(e)try{e([],"length")}catch{e=null}return xr=e,xr}function Yu(){if(Fi)return Sr;Fi=!0;var l=mi(),e=xs(),t=Qt(),r=Ss();return Sr=function(s,n,i){if(!s||typeof s!="object"&&typeof s!="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 o=arguments.length>3?arguments[3]:null,a=arguments.length>4?arguments[4]:null,c=arguments.length>5?arguments[5]:null,u=arguments.length>6?arguments[6]:!1,h=!!r&&r(s,n);if(l)l(s,n,{configurable:c===null&&h?h.configurable:!c,enumerable:o===null&&h?h.enumerable:!o,value:i,writable:a===null&&h?h.writable:!a});else if(u||!o&&!a&&!c)s[n]=i;else throw new e("This environment does not support defining a property as non-configurable, non-writable, or non-enumerable.")},Sr}function Qu(){if($i)return Er;$i=!0;var l=mi(),e=function(){return!!l};return e.hasArrayLengthDefineBug=function(){if(!l)return null;try{return l([],"length",{value:1}).length!==1}catch{return!0}},Er=e,Er}function Ju(){if(qi)return Ar;qi=!0;var l=Bt(),e=Yu(),t=Qu()(),r=Ss(),s=Qt(),n=l("%Math.floor%");return Ar=function(i,o){if(typeof i!="function")throw new s("`fn` is not a function");if(typeof o!="number"||o<0||o>4294967295||n(o)!==o)throw new s("`length` must be a positive 32-bit integer");var a=arguments.length>2&&!!arguments[2],c=!0,u=!0;if("length"in i&&r){var h=r(i,"length");h&&!h.configurable&&(c=!1),h&&!h.writable&&(u=!1)}return(c||u||!a)&&(t?e(i,"length",o,!0,!0):e(i,"length",o)),i},Ar}function Xu(){if(Hi)return Dt;Hi=!0;var l=pi(),e=Bt(),t=Ju(),r=Qt(),s=e("%Function.prototype.apply%"),n=e("%Function.prototype.call%"),i=e("%Reflect.apply%",!0)||l.call(n,s),o=mi(),a=e("%Math.max%");Dt=function(u){if(typeof u!="function")throw new r("a function is required");var h=i(l,n,arguments);return t(h,1+a(0,u.length-(arguments.length-1)),!0)};var c=function(){return i(l,s,arguments)};return o?o(Dt,"apply",{value:c}):Dt.apply=c,Dt}function Zu(){if(Wi)return Ir;Wi=!0;var l=Bt(),e=Xu(),t=e(l("String.prototype.indexOf"));return Ir=function(r,s){var n=l(r,!!s);return typeof n=="function"&&t(r,".prototype.")>-1?e(n):n},Ir}var gi,bi,yi,vi,wi,_i,ki,xi,Si,Ei,Ai,Ii,Ti,Ci,Oi,Pi,gr,Mi,br,Ri,yr,Li,vr,ji,wr,Ni,_r,Ui,kr,Bi,xr,Di,Sr,Fi,Er,$i,Ar,qi,Dt,Hi,Ir,Wi,eh=Ve(()=>{le(),ue(),ce(),gi={},bi=!1,yi={},vi=!1,wi={},_i=!1,ki={},xi=!1,Si={},Ei=!1,Ai={},Ii=!1,Ti={},Ci=!1,Oi={},Pi=!1,gr={},Mi=!1,br={},Ri=!1,yr={},Li=!1,vr={},ji=!1,wr={},Ni=!1,_r={},Ui=!1,kr={},Bi=!1,xr={},Di=!1,Sr={},Fi=!1,Er={},$i=!1,Ar={},qi=!1,Dt={},Hi=!1,Ir={},Wi=!1});function zi(l){throw new Error("Node.js process "+l+" is not supported by JSPM core outside of Node.js")}function th(){!Tt||!Ct||(Tt=!1,Ct.length?Ze=Ct.concat(Ze):Jt=-1,Ze.length&&Es())}function Es(){if(!Tt){var l=setTimeout(th,0);Tt=!0;for(var e=Ze.length;e;){for(Ct=Ze,Ze=[];++Jt<e;)Ct&&Ct[Jt].run();Jt=-1,e=Ze.length}Ct=null,Tt=!1,clearTimeout(l)}}function rh(l){var e=new Array(arguments.length-1);if(arguments.length>1)for(var t=1;t<arguments.length;t++)e[t-1]=arguments[t];Ze.push(new As(l,e)),Ze.length===1&&!Tt&&setTimeout(Es,0)}function As(l,e){this.fun=l,this.array=e}function $e(){}function nh(l){zi("_linkedBinding")}function ih(l){zi("dlopen")}function oh(){return[]}function sh(){return[]}function ah(l,e){if(!l)throw new Error(e||"assertion error")}function lh(){return!1}function ch(){return pt.now()/1e3}function Vi(l){var e=Math.floor((Date.now()-pt.now())*.001),t=pt.now()*.001,r=Math.floor(t)+e,s=Math.floor(t%1*1e9);return l&&(r=r-l[0],s=s-l[1],s<0&&(r--,s+=Cr)),[r,s]}function wt(){return Ki}function uh(l){return[]}var Ze,Tt,Ct,Jt,Is,Ts,Cs,Os,Ps,Ms,Rs,Ls,js,Ns,Us,Bs,Ds,Fs,$s,qs,Hs,Ws,zs,Vs,Gs,Tr,Ks,Ys,Qs,Js,Xs,Zs,ea,ta,ra,na,ia,oa,sa,aa,la,ca,ua,ha,da,fa,pa,ma,ga,ba,ya,pt,Gi,Cr,va,wa,_a,ka,xa,Sa,Ea,Aa,Ia,Ta,Ca,Ki,Oa=Ve(()=>{le(),ue(),ce(),Ze=[],Tt=!1,Jt=-1,As.prototype.run=function(){this.fun.apply(null,this.array)},Is="browser",Ts="x64",Cs="browser",Os={PATH:"/usr/bin",LANG:navigator.language+".UTF-8",PWD:"/",HOME:"/home",TMP:"/tmp"},Ps=["/usr/bin/node"],Ms=[],Rs="v16.8.0",Ls={},js=function(l,e){console.warn((e?e+": ":"")+l)},Ns=function(l){zi("binding")},Us=function(l){return 0},Bs=function(){return"/"},Ds=function(l){},Fs={name:"node",sourceUrl:"",headersUrl:"",libUrl:""},$s=$e,qs=[],Hs={},Ws=!1,zs={},Vs=$e,Gs=$e,Tr=function(){return{}},Ks=Tr,Ys=Tr,Qs=$e,Js=$e,Xs=$e,Zs={},ea={inspector:!1,debug:!1,uv:!1,ipv6:!1,tls_alpn:!1,tls_sni:!1,tls_ocsp:!1,tls:!1,cached_builtins:!0},ta=$e,ra=$e,na=$e,ia=$e,oa=$e,sa=$e,aa=$e,la=void 0,ca=void 0,ua=void 0,ha=$e,da=2,fa=1,pa="/bin/usr/node",ma=9229,ga="node",ba=[],ya=$e,pt={now:typeof performance<"u"?performance.now.bind(performance):void 0,timing:typeof performance<"u"?performance.timing:void 0},pt.now===void 0&&(Gi=Date.now(),pt.timing&&pt.timing.navigationStart&&(Gi=pt.timing.navigationStart),pt.now=()=>Date.now()-Gi),Cr=1e9,Vi.bigint=function(l){var e=Vi(l);return typeof BigInt>"u"?e[0]*Cr+e[1]:BigInt(e[0]*Cr)+BigInt(e[1])},va=10,wa={},_a=0,ka=wt,xa=wt,Sa=wt,Ea=wt,Aa=wt,Ia=$e,Ta=wt,Ca=wt,Ki={version:Rs,versions:Ls,arch:Ts,platform:Cs,release:Fs,_rawDebug:$s,moduleLoadList:qs,binding:Ns,_linkedBinding:nh,_events:wa,_eventsCount:_a,_maxListeners:va,on:wt,addListener:ka,once:xa,off:Sa,removeListener:Ea,removeAllListeners:Aa,emit:Ia,prependListener:Ta,prependOnceListener:Ca,listeners:uh,domain:Hs,_exiting:Ws,config:zs,dlopen:ih,uptime:ch,_getActiveRequests:oh,_getActiveHandles:sh,reallyExit:Vs,_kill:Gs,cpuUsage:Tr,resourceUsage:Ks,memoryUsage:Ys,kill:Qs,exit:Js,openStdin:Xs,allowedNodeEnvironmentFlags:Zs,assert:ah,features:ea,_fatalExceptions:ta,setUncaughtExceptionCaptureCallback:ra,hasUncaughtExceptionCaptureCallback:lh,emitWarning:js,nextTick:rh,_tickCallback:na,_debugProcess:ia,_debugEnd:oa,_startProfilerIdleNotifier:sa,_stopProfilerIdleNotifier:aa,stdout:la,stdin:ua,stderr:ca,abort:ha,umask:Us,chdir:Ds,cwd:Bs,env:Os,title:Is,argv:Ps,execArgv:Ms,pid:da,ppid:fa,execPath:pa,debugPort:ma,hrtime:Vi,argv0:ga,_preload_modules:ba,setSourceMapsEnabled:ya}});function hh(){if(Yi)return Or;Yi=!0;var l=Ki;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 o="",a=0,c=-1,u=0,h,p=0;p<=n.length;++p){if(p<n.length)h=n.charCodeAt(p);else{if(h===47)break;h=47}if(h===47){if(!(c===p-1||u===1))if(c!==p-1&&u===2){if(o.length<2||a!==2||o.charCodeAt(o.length-1)!==46||o.charCodeAt(o.length-2)!==46){if(o.length>2){var b=o.lastIndexOf("/");if(b!==o.length-1){b===-1?(o="",a=0):(o=o.slice(0,b),a=o.length-1-o.lastIndexOf("/")),c=p,u=0;continue}}else if(o.length===2||o.length===1){o="",a=0,c=p,u=0;continue}}i&&(o.length>0?o+="/..":o="..",a=2)}else o.length>0?o+="/"+n.slice(c+1,p):o=n.slice(c+1,p),a=p-c-1;c=p,u=0}else h===46&&u!==-1?++u:u=-1}return o}function r(n,i){var o=i.dir||i.root,a=i.base||(i.name||"")+(i.ext||"");return o?o===i.root?o+a:o+n+a:a}var s={resolve:function(){for(var n="",i=!1,o,a=arguments.length-1;a>=-1&&!i;a--){var c;a>=0?c=arguments[a]:(o===void 0&&(o=l.cwd()),c=o),e(c),c.length!==0&&(n=c+"/"+n,i=c.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,o=n.charCodeAt(n.length-1)===47;return n=t(n,!i),n.length===0&&!i&&(n="."),n.length>0&&o&&(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 o=arguments[i];e(o),o.length>0&&(n===void 0?n=o:n+="/"+o)}return n===void 0?".":s.normalize(n)},relative:function(n,i){if(e(n),e(i),n===i||(n=s.resolve(n),i=s.resolve(i),n===i))return"";for(var o=1;o<n.length&&n.charCodeAt(o)===47;++o);for(var a=n.length,c=a-o,u=1;u<i.length&&i.charCodeAt(u)===47;++u);for(var h=i.length,p=h-u,b=c<p?c: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 c>b&&(n.charCodeAt(o+g)===47?f=g:g===0&&(f=0));break}var y=n.charCodeAt(o+g),k=i.charCodeAt(u+g);if(y!==k)break;y===47&&(f=g)}var m="";for(g=o+f+1;g<=a;++g)(g===a||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),o=i===47,a=-1,c=!0,u=n.length-1;u>=1;--u)if(i=n.charCodeAt(u),i===47){if(!c){a=u;break}}else c=!1;return a===-1?o?"/":".":o&&a===1?"//":n.slice(0,a)},basename:function(n,i){if(i!==void 0&&typeof i!="string")throw new TypeError('"ext" argument must be a string');e(n);var o=0,a=-1,c=!0,u;if(i!==void 0&&i.length>0&&i.length<=n.length){if(i.length===n.length&&i===n)return"";var h=i.length-1,p=-1;for(u=n.length-1;u>=0;--u){var b=n.charCodeAt(u);if(b===47){if(!c){o=u+1;break}}else p===-1&&(c=!1,p=u+1),h>=0&&(b===i.charCodeAt(h)?--h===-1&&(a=u):(h=-1,a=p))}return o===a?a=p:a===-1&&(a=n.length),n.slice(o,a)}else{for(u=n.length-1;u>=0;--u)if(n.charCodeAt(u)===47){if(!c){o=u+1;break}}else a===-1&&(c=!1,a=u+1);return a===-1?"":n.slice(o,a)}},extname:function(n){e(n);for(var i=-1,o=0,a=-1,c=!0,u=0,h=n.length-1;h>=0;--h){var p=n.charCodeAt(h);if(p===47){if(!c){o=h+1;break}continue}a===-1&&(c=!1,a=h+1),p===46?i===-1?i=h:u!==1&&(u=1):i!==-1&&(u=-1)}return i===-1||a===-1||u===0||u===1&&i===a-1&&i===o+1?"":n.slice(i,a)},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 o=n.charCodeAt(0),a=o===47,c;a?(i.root="/",c=1):c=0;for(var u=-1,h=0,p=-1,b=!0,f=n.length-1,g=0;f>=c;--f){if(o=n.charCodeAt(f),o===47){if(!b){h=f+1;break}continue}p===-1&&(b=!1,p=f+1),o===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===h+1?p!==-1&&(h===0&&a?i.base=i.name=n.slice(1,p):i.base=i.name=n.slice(h,p)):(h===0&&a?(i.name=n.slice(1,u),i.base=n.slice(1,p)):(i.name=n.slice(h,u),i.base=n.slice(h,p)),i.ext=n.slice(u,p)),h>0?i.dir=n.slice(0,h-1):a&&(i.dir="/"),i},sep:"/",delimiter:":",win32:null,posix:null};return s.posix=s,Or=s,Or}var Or,Yi,Qi,dh=Ve(()=>{le(),ue(),ce(),Oa(),Or={},Yi=!1,Qi=hh()}),Pa={};Rt(Pa,{URL:()=>qa,Url:()=>Ua,default:()=>qe,fileURLToPath:()=>Ra,format:()=>Ba,parse:()=>$a,pathToFileURL:()=>La,resolve:()=>Da,resolveObject:()=>Fa});function fh(){if(Xi)return Pr;Xi=!0;var l=typeof Map=="function"&&Map.prototype,e=Object.getOwnPropertyDescriptor&&l?Object.getOwnPropertyDescriptor(Map.prototype,"size"):null,t=l&&e&&typeof e.get=="function"?e.get:null,r=l&&Map.prototype.forEach,s=typeof Set=="function"&&Set.prototype,n=Object.getOwnPropertyDescriptor&&s?Object.getOwnPropertyDescriptor(Set.prototype,"size"):null,i=s&&n&&typeof n.get=="function"?n.get:null,o=s&&Set.prototype.forEach,a=typeof WeakMap=="function"&&WeakMap.prototype,c=a?WeakMap.prototype.has:null,u=typeof WeakSet=="function"&&WeakSet.prototype,h=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,S=String.prototype.toUpperCase,v=String.prototype.toLowerCase,E=RegExp.prototype.test,x=Array.prototype.concat,I=Array.prototype.join,P=Array.prototype.slice,O=Math.floor,B=typeof BigInt=="function"?BigInt.prototype.valueOf:null,T=Object.getOwnPropertySymbols,q=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 V(z,ie){if(z===1/0||z===-1/0||z!==z||z&&z>-1e3&&z<1e3||E.call(/e/,ie))return ie;var Ee=/[0-9](?=(?:[0-9]{3})+(?![0-9]))/g;if(typeof z=="number"){var Ae=z<0?-O(-z):O(z);if(Ae!==z){var Ie=String(Ae),Oe=m.call(ie,Ie.length+1);return w.call(Ie,Ee,"$&_")+"."+w.call(w.call(Oe,/([0-9]{3})/g,"$&_"),/_$/,"")}}return w.call(ie,Ee,"$&_")}var re=ja,F=re.custom,Z=K(F)?F:null;Pr=function z(ie,Ee,Ae,Ie){var Oe=Ee||{};if(oe(Oe,"quoteStyle")&&Oe.quoteStyle!=="single"&&Oe.quoteStyle!=="double")throw new TypeError('option "quoteStyle" must be "single" or "double"');if(oe(Oe,"maxStringLength")&&(typeof Oe.maxStringLength=="number"?Oe.maxStringLength<0&&Oe.maxStringLength!==1/0:Oe.maxStringLength!==null))throw new TypeError('option "maxStringLength", if provided, must be a positive integer, Infinity, or `null`');var et=oe(Oe,"customInspect")?Oe.customInspect:!0;if(typeof et!="boolean"&&et!=="symbol")throw new TypeError("option \"customInspect\", if provided, must be `true`, `false`, or `'symbol'`");if(oe(Oe,"indent")&&Oe.indent!==null&&Oe.indent!==" "&&!(parseInt(Oe.indent,10)===Oe.indent&&Oe.indent>0))throw new TypeError('option "indent" must be "\\t", an integer > 0, or `null`');if(oe(Oe,"numericSeparator")&&typeof Oe.numericSeparator!="boolean")throw new TypeError('option "numericSeparator", if provided, must be `true` or `false`');var tt=Oe.numericSeparator;if(typeof ie>"u")return"undefined";if(ie===null)return"null";if(typeof ie=="boolean")return ie?"true":"false";if(typeof ie=="string")return se(ie,Oe);if(typeof ie=="number"){if(ie===0)return 1/0/ie>0?"0":"-0";var He=String(ie);return tt?V(ie,He):He}if(typeof ie=="bigint"){var rt=String(ie)+"n";return tt?V(ie,rt):rt}var qt=typeof Oe.depth>"u"?5:Oe.depth;if(typeof Ae>"u"&&(Ae=0),Ae>=qt&&qt>0&&typeof ie=="object")return be(ie)?"[Array]":"[Object]";var nt=X(Oe,Ae);if(typeof Ie>"u")Ie=[];else if(ee(Ie,ie)>=0)return"[Circular]";function Ye(it,kt,Mt){if(kt&&(Ie=P.call(Ie),Ie.push(kt)),Mt){var ot={depth:Oe.depth};return oe(Oe,"quoteStyle")&&(ot.quoteStyle=Oe.quoteStyle),z(it,ot,Ae+1,Ie)}return z(it,Oe,Ae+1,Ie)}if(typeof ie=="function"&&!we(ie)){var zr=$(ie),Ht=ke(ie,Ye);return"[Function"+(zr?": "+zr:" (anonymous)")+"]"+(Ht.length>0?" { "+I.call(Ht,", ")+" }":"")}if(K(ie)){var Zt=D?w.call(String(ie),/^(Symbol\(.*\))_[^)]*$/,"$1"):q.call(ie);return typeof ie=="object"&&!D?d(Zt):Zt}if(ve(ie)){for(var C="<"+v.call(String(ie.nodeName)),L=ie.attributes||[],_e=0;_e<L.length;_e++)C+=" "+L[_e].name+"="+M(J(L[_e].value),"double",Oe);return C+=">",ie.childNodes&&ie.childNodes.length&&(C+="..."),C+="</"+v.call(String(ie.nodeName))+">",C}if(be(ie)){if(ie.length===0)return"[]";var xe=ke(ie,Ye);return nt&&!U(xe)?"["+he(xe,nt)+"]":"[ "+I.call(xe,", ")+" ]"}if(G(ie)){var Se=ke(ie,Ye);return!("cause"in Error.prototype)&&"cause"in ie&&!ae.call(ie,"cause")?"{ ["+String(ie)+"] "+I.call(x.call("[cause]: "+Ye(ie.cause),Se),", ")+" }":Se.length===0?"["+String(ie)+"]":"{ ["+String(ie)+"] "+I.call(Se,", ")+" }"}if(typeof ie=="object"&&et){if(Z&&typeof ie[Z]=="function"&&re)return re(ie,{depth:qt-Ae});if(et!=="symbol"&&typeof ie.inspect=="function")return ie.inspect()}if(de(ie)){var Ue=[];return r&&r.call(ie,function(it,kt){Ue.push(Ye(kt,ie,!0)+" => "+Ye(it,ie))}),A("Map",t.call(ie),Ue,nt)}if(H(ie)){var ze=[];return o&&o.call(ie,function(it){ze.push(Ye(it,ie))}),A("Set",i.call(ie),ze,nt)}if(fe(ie))return _("WeakMap");if(me(ie))return _("WeakSet");if(ye(ie))return _("WeakRef");if(ne(ie))return d(Ye(Number(ie)));if(Q(ie))return d(Ye(B.call(ie)));if(W(ie))return d(f.call(ie));if(j(ie))return d(Ye(String(ie)));if(typeof window<"u"&&ie===window)return"{ [object Window] }";if(typeof globalThis<"u"&&ie===globalThis||typeof Mr<"u"&&ie===Mr)return"{ [object globalThis] }";if(!te(ie)&&!we(ie)){var Je=ke(ie,Ye),er=Y?Y(ie)===Object.prototype:ie instanceof Object||ie.constructor===Object,tr=ie instanceof Object?"":"null prototype",rr=!er&&N&&Object(ie)===ie&&N in ie?m.call(R(ie),8,-1):tr?"Object":"",Vr=er||typeof ie.constructor!="function"?"":ie.constructor.name?ie.constructor.name+" ":"",Pt=Vr+(rr||tr?"["+I.call(x.call([],rr||[],tr||[]),": ")+"] ":"");return Je.length===0?Pt+"{}":nt?Pt+"{"+he(Je,nt)+"}":Pt+"{ "+I.call(Je,", ")+" }"}return String(ie)};function M(z,ie,Ee){var Ae=(Ee.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 G(z){return R(z)==="[object Error]"&&(!N||!(typeof z=="object"&&N in z))}function j(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 W(z){return R(z)==="[object Boolean]"&&(!N||!(typeof z=="object"&&N in z))}function K(z){if(D)return z&&typeof z=="object"&&z instanceof Symbol;if(typeof z=="symbol")return!0;if(!z||typeof z!="object"||!q)return!1;try{return q.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 ge=Object.prototype.hasOwnProperty||function(z){return z in(this||Mr)};function oe(z,ie){return ge.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 Ee=0,Ae=z.length;Ee<Ae;Ee++)if(z[Ee]===ie)return Ee;return-1}function de(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 fe(z){if(!c||!z||typeof z!="object")return!1;try{c.call(z,c);try{h.call(z,h)}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 H(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 me(z){if(!h||!z||typeof z!="object")return!1;try{h.call(z,h);try{c.call(z,c)}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 Ee=z.length-ie.maxStringLength,Ae="... "+Ee+" more character"+(Ee>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 M(Ie,"single",ie)}function Te(z){var ie=z.charCodeAt(0),Ee={8:"b",9:"t",10:"n",12:"f",13:"r"}[ie];return Ee?"\\"+Ee:"\\x"+(ie<16?"0":"")+S.call(ie.toString(16))}function d(z){return"Object("+z+")"}function _(z){return z+" { ? }"}function A(z,ie,Ee,Ae){var Ie=Ae?he(Ee,Ae):I.call(Ee,", ");return z+" ("+ie+") {"+Ie+"}"}function U(z){for(var ie=0;ie<z.length;ie++)if(ee(z[ie],`
1
+ var AikaaraChat=(function(Ce){"use strict";class ko{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 Gr{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 ko(t,s=>{this.send({command:"message",identifier:t,data:JSON.stringify(s)})});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((s,n)=>{this.pendingSubscriptions.set(r,{resolve:()=>s(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 ir{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(s){console.error(`Error in event handler for "${e}":`,s)}})}removeAllListeners(){this.handlers.clear()}}const uc=1e3,hc=10,dc=400,fc=600,xo="#6366f1",pc=12,mc="system-ui, -apple-system, sans-serif",So="Type a message...",gc="bottom-right",bc="light",yc={x:20,y:20},Kr="aikaara_conversation_id";class Eo extends ir{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 Gr(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,s){const n=JSON.stringify({channel:"ConversationChannel",conversation_id:e});this.client.perform(n,"send_user_event",{event_key:t,...r&&{value:r},...s&&{source:s}})}get connectionState(){return this.state}setState(e){this.state!==e&&(this.state=e,this.emit("connection:state",e))}scheduleReconnect(){const e=this.config.maxReconnectAttempts??hc;if(this.reconnectAttempt>=e){this.emit("error",new Error("Max reconnection attempts reached"));return}this.setState("reconnecting");const r=(this.config.reconnectInterval??uc)*Math.pow(2,this.reconnectAttempt);this.reconnectAttempt++,this.reconnectTimer=setTimeout(async()=>{try{const s=this.buildWsUrl(this.config.baseUrl,this.config.userToken);this.client=new Gr(s),await this.connect()}catch{}},r)}clearReconnectTimer(){this.reconnectTimer&&(clearTimeout(this.reconnectTimer),this.reconnectTimer=null)}buildWsUrl(e,t){if(this.config.wsUrl){const s=this.config.wsUrl.includes("?")?"&":"?";return`${this.config.wsUrl}${s}token=${t}`}return`${e.replace(/^http/,"ws")}/cable?token=${t}`}}class Ao{baseUrl;apiKey;authToken;userToken;refreshHook=null;constructor(e,t,r,s){this.baseUrl=e,this.userToken=t,this.apiKey=r,this.authToken=s}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 s=`${this.baseUrl}${t}`;let n=await this.fetchWithHeaders(s,e,r);if(n.status===401&&this.refreshHook){let o=null;try{o=await this.refreshHook()}catch(a){console.warn("[aikaara-chat-sdk] auth refresh hook threw",a)}o&&(this.authToken=o,n=await this.fetchWithHeaders(s,e,r))}if(!n.ok){const o=await n.text();let a;try{const c=JSON.parse(o);a=c.error||c.message||o}catch{a=o}throw new Error(`API error ${n.status}: ${a}`)}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 s={"Content-Type":"application/json",Accept:"application/json"};this.apiKey&&(s["X-Api-Key"]=this.apiKey),this.authToken&&(s.Authorization=`Bearer ${this.authToken}`);const n={method:t,headers:s};return r&&(n.body=JSON.stringify(r)),fetch(e,n)}}class Io{_messages=[];optimisticCounter=0;get messages(){return[...this._messages]}addOptimistic(e,t,r){const s={id:`optimistic_${++this.optimisticCounter}`,conversationId:r,role:e,content:t,createdAt:new Date().toISOString(),status:"sending"};return this._messages.push(s),s}reconcileOptimistic(e,t=3e4){const r=this._messages.findLast(s=>s.status==="sending"&&s.role===e.role&&s.content===e.content&&s.conversationId===e.conversationId&&Date.now()-new Date(s.createdAt).getTime()<t);return r?(r.status=e.status??"sent",r.externalId=e.externalId??e.id,e.template&&(r.template=e.template),e.attachments&&(r.attachments=e.attachments),e.metadata&&(r.metadata={...r.metadata??{},...e.metadata}),r):null}upsertRemoteMessage(e){const t=this.reconcileOptimistic(e);if(t)return{message:t,deduped:!0};const r=e.externalId?this._messages.find(n=>n.externalId&&n.externalId===e.externalId):void 0;if(r)return Object.assign(r,e,{id:r.id}),{message:r,deduped:!0};const s=To(this._messages,e);return s?(Object.assign(s,e,{id:s.id}),{message:s,deduped:!0}):(this._messages.push(e),{message:e,deduped:!1})}updateMessageStatus(e,t){const r=this._messages.find(s=>s.externalId===e||s.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){const t=[];for(const r of e){const s=To(t,r);if(s){const n=or(s),i=or(r);!n&&i&&Object.assign(s,r,{id:s.id});continue}t.push({...r})}this._messages=t}clear(){this._messages=[]}}function To(l,e,t=15e3){const r=e.attachments&&e.attachments[0],s=(e.metadata??{}).attributes;if(!(!!r||!!(s&&s.fileMessage)))return null;const i=or(e),o=Co(e),a=Oo(e);if(!i&&!o&&!a)return null;const c=new Date(e.createdAt).getTime();for(let u=l.length-1;u>=0;u--){const h=l[u],p=h.attachments&&h.attachments[0],y=(h.metadata??{}).attributes;if(!(!!p||!!(y&&y.fileMessage)))continue;const g=(h.content||"").trim().toLowerCase();if(g==="file_uploaded"||g==="file_upload"||Math.abs(c-new Date(h.createdAt).getTime())>t)continue;const b=or(h);if(i&&b&&i===b)return h;const k=Co(h);if(o&&k&&o===k)return h;const m=Oo(h);if(a&&m&&a===m)return h}return null}function Co(l){const e=l.attachments&&l.attachments[0];if(e&&typeof e.fileUrl=="string")return e.fileUrl;const t=Po(l);if(t)return t}function Oo(l){const e=l.attachments&&l.attachments[0];if(e&&typeof e.fileName=="string")return e.fileName;const t=(l.metadata??{}).attributes;if(t&&typeof t.fileName=="string")return t.fileName;const n=l.template?.payload?.elements?.[0]?.description;if(typeof n=="string"&&n)return n}function or(l){const e=l.attachments&&l.attachments[0];if(e&&typeof e.cloudFileId=="string")return e.cloudFileId;const t=(l.metadata??{}).attributes;if(t&&typeof t.cloudFileId=="string")return t.cloudFileId;const r=Po(l);if(r){const s=/[?&]cloudFileId=([^&]+)/.exec(r);if(s)return decodeURIComponent(s[1])}}function Po(l){const e=l.template;if(e?.templateId!=="7")return;const r=e.payload?.elements?.[0]?.action?.url;return typeof r=="string"?r:void 0}class Mo{_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(Kr)}catch{}}loadFromStorage(){if(!this.persist)return null;try{return localStorage.getItem(Kr)}catch{return null}}saveToStorage(e){try{localStorage.setItem(Kr,e)}catch{}}}var Yr=Object.defineProperty,vc=Object.getOwnPropertyDescriptor,wc=Object.getOwnPropertyNames,_c=Object.prototype.hasOwnProperty,Ve=(l,e)=>()=>(l&&(e=l(l=0)),e),pe=(l,e)=>()=>(e||l((e={exports:{}}).exports,e),e.exports),Rt=(l,e)=>{for(var t in e)Yr(l,t,{get:e[t],enumerable:!0})},kc=(l,e,t,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let s of wc(e))!_c.call(l,s)&&s!==t&&Yr(l,s,{get:()=>e[s],enumerable:!(r=vc(e,s))||r.enumerable});return l},Me=l=>kc(Yr({},"__esModule",{value:!0}),l),le=Ve(()=>{}),Le={};Rt(Le,{_debugEnd:()=>Pn,_debugProcess:()=>On,_events:()=>Gn,_eventsCount:()=>Kn,_exiting:()=>gn,_fatalExceptions:()=>In,_getActiveHandles:()=>Do,_getActiveRequests:()=>Bo,_kill:()=>vn,_linkedBinding:()=>No,_maxListeners:()=>Vn,_preload_modules:()=>Hn,_rawDebug:()=>fn,_startProfilerIdleNotifier:()=>Mn,_stopProfilerIdleNotifier:()=>Rn,_tickCallback:()=>Cn,abort:()=>Un,addListener:()=>Yn,allowedNodeEnvironmentFlags:()=>En,arch:()=>Xr,argv:()=>tn,argv0:()=>qn,assert:()=>Fo,binding:()=>an,browser:()=>dn,chdir:()=>un,config:()=>bn,cpuUsage:()=>zt,cwd:()=>cn,debugPort:()=>$n,default:()=>ni,dlopen:()=>Uo,domain:()=>mn,emit:()=>ei,emitWarning:()=>sn,env:()=>en,execArgv:()=>rn,execPath:()=>Fn,exit:()=>xn,features:()=>An,hasUncaughtExceptionCaptureCallback:()=>$o,hrtime:()=>sr,kill:()=>kn,listeners:()=>Ho,memoryUsage:()=>_n,moduleLoadList:()=>pn,nextTick:()=>Lo,off:()=>Jn,on:()=>st,once:()=>Qn,openStdin:()=>Sn,pid:()=>Bn,platform:()=>Zr,ppid:()=>Dn,prependListener:()=>ti,prependOnceListener:()=>ri,reallyExit:()=>yn,release:()=>hn,removeAllListeners:()=>Zn,removeListener:()=>Xn,resourceUsage:()=>wn,setSourceMapsEnabled:()=>Wn,setUncaughtExceptionCaptureCallback:()=>Tn,stderr:()=>jn,stdin:()=>Nn,stdout:()=>Ln,title:()=>Jr,umask:()=>ln,uptime:()=>qo,version:()=>nn,versions:()=>on});function Qr(l){throw new Error("Node.js process "+l+" is not supported by JSPM core outside of Node.js")}function xc(){!xt||!St||(xt=!1,St.length?Xe=St.concat(Xe):Wt=-1,Xe.length&&Ro())}function Ro(){if(!xt){var l=setTimeout(xc,0);xt=!0;for(var e=Xe.length;e;){for(St=Xe,Xe=[];++Wt<e;)St&&St[Wt].run();Wt=-1,e=Xe.length}St=null,xt=!1,clearTimeout(l)}}function Lo(l){var e=new Array(arguments.length-1);if(arguments.length>1)for(var t=1;t<arguments.length;t++)e[t-1]=arguments[t];Xe.push(new jo(l,e)),Xe.length===1&&!xt&&setTimeout(Ro,0)}function jo(l,e){this.fun=l,this.array=e}function Fe(){}function No(l){Qr("_linkedBinding")}function Uo(l){Qr("dlopen")}function Bo(){return[]}function Do(){return[]}function Fo(l,e){if(!l)throw new Error(e||"assertion error")}function $o(){return!1}function qo(){return at.now()/1e3}function sr(l){var e=Math.floor((Date.now()-at.now())*.001),t=at.now()*.001,r=Math.floor(t)+e,s=Math.floor(t%1*1e9);return l&&(r=r-l[0],s=s-l[1],s<0&&(r--,s+=ar)),[r,s]}function st(){return ni}function Ho(l){return[]}var Xe,xt,St,Wt,Jr,Xr,Zr,en,tn,rn,nn,on,sn,an,ln,cn,un,hn,dn,fn,pn,mn,gn,bn,yn,vn,zt,wn,_n,kn,xn,Sn,En,An,In,Tn,Cn,On,Pn,Mn,Rn,Ln,jn,Nn,Un,Bn,Dn,Fn,$n,qn,Hn,Wn,at,zn,ar,Vn,Gn,Kn,Yn,Qn,Jn,Xn,Zn,ei,ti,ri,ni,Sc=Ve(()=>{le(),ue(),ce(),Xe=[],xt=!1,Wt=-1,jo.prototype.run=function(){this.fun.apply(null,this.array)},Jr="browser",Xr="x64",Zr="browser",en={PATH:"/usr/bin",LANG:typeof navigator<"u"?navigator.language+".UTF-8":void 0,PWD:"/",HOME:"/home",TMP:"/tmp"},tn=["/usr/bin/node"],rn=[],nn="v16.8.0",on={},sn=function(l,e){console.warn((e?e+": ":"")+l)},an=function(l){Qr("binding")},ln=function(l){return 0},cn=function(){return"/"},un=function(l){},hn={name:"node",sourceUrl:"",headersUrl:"",libUrl:""},dn=!0,fn=Fe,pn=[],mn={},gn=!1,bn={},yn=Fe,vn=Fe,zt=function(){return{}},wn=zt,_n=zt,kn=Fe,xn=Fe,Sn=Fe,En={},An={inspector:!1,debug:!1,uv:!1,ipv6:!1,tls_alpn:!1,tls_sni:!1,tls_ocsp:!1,tls:!1,cached_builtins:!0},In=Fe,Tn=Fe,Cn=Fe,On=Fe,Pn=Fe,Mn=Fe,Rn=Fe,Ln=void 0,jn=void 0,Nn=void 0,Un=Fe,Bn=2,Dn=1,Fn="/bin/usr/node",$n=9229,qn="node",Hn=[],Wn=Fe,at={now:typeof performance<"u"?performance.now.bind(performance):void 0,timing:typeof performance<"u"?performance.timing:void 0},at.now===void 0&&(zn=Date.now(),at.timing&&at.timing.navigationStart&&(zn=at.timing.navigationStart),at.now=()=>Date.now()-zn),ar=1e9,sr.bigint=function(l){var e=sr(l);return typeof BigInt>"u"?e[0]*ar+e[1]:BigInt(e[0]*ar)+BigInt(e[1])},Vn=10,Gn={},Kn=0,Yn=st,Qn=st,Jn=st,Xn=st,Zn=st,ei=Fe,ti=st,ri=st,ni={version:nn,versions:on,arch:Xr,platform:Zr,browser:dn,release:hn,_rawDebug:fn,moduleLoadList:pn,binding:an,_linkedBinding:No,_events:Gn,_eventsCount:Kn,_maxListeners:Vn,on:st,addListener:Yn,once:Qn,off:Jn,removeListener:Xn,removeAllListeners:Zn,emit:ei,prependListener:ti,prependOnceListener:ri,listeners:Ho,domain:mn,_exiting:gn,config:bn,dlopen:Uo,uptime:qo,_getActiveRequests:Bo,_getActiveHandles:Do,reallyExit:yn,_kill:vn,cpuUsage:zt,resourceUsage:wn,memoryUsage:_n,kill:kn,exit:xn,openStdin:Sn,allowedNodeEnvironmentFlags:En,assert:Fo,features:An,_fatalExceptions:In,setUncaughtExceptionCaptureCallback:Tn,hasUncaughtExceptionCaptureCallback:$o,emitWarning:sn,nextTick:Lo,_tickCallback:Cn,_debugProcess:On,_debugEnd:Pn,_startProfilerIdleNotifier:Mn,_stopProfilerIdleNotifier:Rn,stdout:Ln,stdin:Nn,stderr:jn,abort:Un,umask:ln,chdir:un,cwd:cn,env:en,title:Jr,argv:tn,execArgv:rn,pid:Bn,ppid:Dn,execPath:Fn,debugPort:$n,hrtime:sr,argv0:qn,_preload_modules:Hn,setSourceMapsEnabled:Wn}}),ce=Ve(()=>{Sc()});function Ec(){if(ii)return Lt;ii=!0,Lt.byteLength=o,Lt.toByteArray=c,Lt.fromByteArray=p;for(var l=[],e=[],t=typeof Uint8Array<"u"?Uint8Array:Array,r="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",s=0,n=r.length;s<n;++s)l[s]=r[s],e[r.charCodeAt(s)]=s;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 o(y){var f=i(y),g=f[0],b=f[1];return(g+b)*3/4-b}function a(y,f,g){return(f+g)*3/4-g}function c(y){var f,g=i(y),b=g[0],k=g[1],m=new t(a(y,b,k)),w=0,x=k>0?b-4:b,v;for(v=0;v<x;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 l[y>>18&63]+l[y>>12&63]+l[y>>6&63]+l[y&63]}function h(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,x=g-b;w<x;w+=m)k.push(h(y,w,w+m>x?x:w+m));return b===1?(f=y[g-1],k.push(l[f>>2]+l[f<<4&63]+"==")):b===2&&(f=(y[g-2]<<8)+y[g-1],k.push(l[f>>10]+l[f>>4&63]+l[f<<2&63]+"=")),k.join("")}return Lt}function Ac(){return oi?Vt:(oi=!0,Vt.read=function(l,e,t,r,s){var n,i,o=s*8-r-1,a=(1<<o)-1,c=a>>1,u=-7,h=t?s-1:0,p=t?-1:1,y=l[e+h];for(h+=p,n=y&(1<<-u)-1,y>>=-u,u+=o;u>0;n=n*256+l[e+h],h+=p,u-=8);for(i=n&(1<<-u)-1,n>>=-u,u+=r;u>0;i=i*256+l[e+h],h+=p,u-=8);if(n===0)n=1-c;else{if(n===a)return i?NaN:(y?-1:1)*(1/0);i=i+Math.pow(2,r),n=n-c}return(y?-1:1)*i*Math.pow(2,n-r)},Vt.write=function(l,e,t,r,s,n){var i,o,a,c=n*8-s-1,u=(1<<c)-1,h=u>>1,p=s===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?(o=isNaN(e)?1:0,i=u):(i=Math.floor(Math.log(e)/Math.LN2),e*(a=Math.pow(2,-i))<1&&(i--,a*=2),i+h>=1?e+=p/a:e+=p*Math.pow(2,1-h),e*a>=2&&(i++,a/=2),i+h>=u?(o=0,i=u):i+h>=1?(o=(e*a-1)*Math.pow(2,s),i=i+h):(o=e*Math.pow(2,h-1)*Math.pow(2,s),i=0));s>=8;l[t+y]=o&255,y+=f,o/=256,s-=8);for(i=i<<s|o,c+=s;c>0;l[t+y]=i&255,y+=f,i/=256,c-=8);l[t+y-f]|=g*128},Vt)}function Ic(){if(si)return gt;si=!0;let l=Ec(),e=Ac(),t=typeof Symbol=="function"&&typeof Symbol.for=="function"?Symbol.for("nodejs.util.inspect.custom"):null;gt.Buffer=i,gt.SlowBuffer=k,gt.INSPECT_MAX_BYTES=50;let r=2147483647;gt.kMaxLength=r,i.TYPED_ARRAY_SUPPORT=s(),!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 s(){try{let d=new Uint8Array(1),_={foo:function(){return 42}};return Object.setPrototypeOf(_,Uint8Array.prototype),Object.setPrototypeOf(d,_),d.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(d){if(d>r)throw new RangeError('The value "'+d+'" is invalid for option "size"');let _=new Uint8Array(d);return Object.setPrototypeOf(_,i.prototype),_}function i(d,_,A){if(typeof d=="number"){if(typeof _=="string")throw new TypeError('The "string" argument must be of type string. Received type number');return u(d)}return o(d,_,A)}i.poolSize=8192;function o(d,_,A){if(typeof d=="string")return h(d,_);if(ArrayBuffer.isView(d))return y(d);if(d==null)throw new TypeError("The first argument must be one of type string, Buffer, ArrayBuffer, Array, or Array-like Object. Received type "+typeof d);if(H(d,ArrayBuffer)||d&&H(d.buffer,ArrayBuffer)||typeof SharedArrayBuffer<"u"&&(H(d,SharedArrayBuffer)||d&&H(d.buffer,SharedArrayBuffer)))return f(d,_,A);if(typeof d=="number")throw new TypeError('The "value" argument must not be of type number. Received type number');let B=d.valueOf&&d.valueOf();if(B!=null&&B!==d)return i.from(B,_,A);let X=g(d);if(X)return X;if(typeof Symbol<"u"&&Symbol.toPrimitive!=null&&typeof d[Symbol.toPrimitive]=="function")return i.from(d[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 d)}i.from=function(d,_,A){return o(d,_,A)},Object.setPrototypeOf(i.prototype,Uint8Array.prototype),Object.setPrototypeOf(i,Uint8Array);function a(d){if(typeof d!="number")throw new TypeError('"size" argument must be of type number');if(d<0)throw new RangeError('The value "'+d+'" is invalid for option "size"')}function c(d,_,A){return a(d),d<=0?n(d):_!==void 0?typeof A=="string"?n(d).fill(_,A):n(d).fill(_):n(d)}i.alloc=function(d,_,A){return c(d,_,A)};function u(d){return a(d),n(d<0?0:b(d)|0)}i.allocUnsafe=function(d){return u(d)},i.allocUnsafeSlow=function(d){return u(d)};function h(d,_){if((typeof _!="string"||_==="")&&(_="utf8"),!i.isEncoding(_))throw new TypeError("Unknown encoding: "+_);let A=m(d,_)|0,B=n(A),X=B.write(d,_);return X!==A&&(B=B.slice(0,X)),B}function p(d){let _=d.length<0?0:b(d.length)|0,A=n(_);for(let B=0;B<_;B+=1)A[B]=d[B]&255;return A}function y(d){if(H(d,Uint8Array)){let _=new Uint8Array(d);return f(_.buffer,_.byteOffset,_.byteLength)}return p(d)}function f(d,_,A){if(_<0||d.byteLength<_)throw new RangeError('"offset" is outside of buffer bounds');if(d.byteLength<_+(A||0))throw new RangeError('"length" is outside of buffer bounds');let B;return _===void 0&&A===void 0?B=new Uint8Array(d):A===void 0?B=new Uint8Array(d,_):B=new Uint8Array(d,_,A),Object.setPrototypeOf(B,i.prototype),B}function g(d){if(i.isBuffer(d)){let _=b(d.length)|0,A=n(_);return A.length===0||d.copy(A,0,0,_),A}if(d.length!==void 0)return typeof d.length!="number"||me(d.length)?n(0):p(d);if(d.type==="Buffer"&&Array.isArray(d.data))return p(d.data)}function b(d){if(d>=r)throw new RangeError("Attempt to allocate Buffer larger than maximum size: 0x"+r.toString(16)+" bytes");return d|0}function k(d){return+d!=d&&(d=0),i.alloc(+d)}i.isBuffer=function(d){return d!=null&&d._isBuffer===!0&&d!==i.prototype},i.compare=function(d,_){if(H(d,Uint8Array)&&(d=i.from(d,d.offset,d.byteLength)),H(_,Uint8Array)&&(_=i.from(_,_.offset,_.byteLength)),!i.isBuffer(d)||!i.isBuffer(_))throw new TypeError('The "buf1", "buf2" arguments must be one of type Buffer or Uint8Array');if(d===_)return 0;let A=d.length,B=_.length;for(let X=0,he=Math.min(A,B);X<he;++X)if(d[X]!==_[X]){A=d[X],B=_[X];break}return A<B?-1:B<A?1:0},i.isEncoding=function(d){switch(String(d).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(d,_){if(!Array.isArray(d))throw new TypeError('"list" argument must be an Array of Buffers');if(d.length===0)return i.alloc(0);let A;if(_===void 0)for(_=0,A=0;A<d.length;++A)_+=d[A].length;let B=i.allocUnsafe(_),X=0;for(A=0;A<d.length;++A){let he=d[A];if(H(he,Uint8Array))X+he.length>B.length?(i.isBuffer(he)||(he=i.from(he)),he.copy(B,X)):Uint8Array.prototype.set.call(B,he,X);else if(i.isBuffer(he))he.copy(B,X);else throw new TypeError('"list" argument must be an Array of Buffers');X+=he.length}return B};function m(d,_){if(i.isBuffer(d))return d.length;if(ArrayBuffer.isView(d)||H(d,ArrayBuffer))return d.byteLength;if(typeof d!="string")throw new TypeError('The "string" argument must be one of type string, Buffer, or ArrayBuffer. Received type '+typeof d);let A=d.length,B=arguments.length>2&&arguments[2]===!0;if(!B&&A===0)return 0;let X=!1;for(;;)switch(_){case"ascii":case"latin1":case"binary":return A;case"utf8":case"utf-8":return $(d).length;case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return A*2;case"hex":return A>>>1;case"base64":return fe(d).length;default:if(X)return B?-1:$(d).length;_=(""+_).toLowerCase(),X=!0}}i.byteLength=m;function w(d,_,A){let B=!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(d||(d="utf8");;)switch(d){case"hex":return V(this,_,A);case"utf8":case"utf-8":return q(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(B)throw new TypeError("Unknown encoding: "+d);d=(d+"").toLowerCase(),B=!0}}i.prototype._isBuffer=!0;function x(d,_,A){let B=d[_];d[_]=d[A],d[A]=B}i.prototype.swap16=function(){let d=this.length;if(d%2!==0)throw new RangeError("Buffer size must be a multiple of 16-bits");for(let _=0;_<d;_+=2)x(this,_,_+1);return this},i.prototype.swap32=function(){let d=this.length;if(d%4!==0)throw new RangeError("Buffer size must be a multiple of 32-bits");for(let _=0;_<d;_+=4)x(this,_,_+3),x(this,_+1,_+2);return this},i.prototype.swap64=function(){let d=this.length;if(d%8!==0)throw new RangeError("Buffer size must be a multiple of 64-bits");for(let _=0;_<d;_+=8)x(this,_,_+7),x(this,_+1,_+6),x(this,_+2,_+5),x(this,_+3,_+4);return this},i.prototype.toString=function(){let d=this.length;return d===0?"":arguments.length===0?q(this,0,d):w.apply(this,arguments)},i.prototype.toLocaleString=i.prototype.toString,i.prototype.equals=function(d){if(!i.isBuffer(d))throw new TypeError("Argument must be a Buffer");return this===d?!0:i.compare(this,d)===0},i.prototype.inspect=function(){let d="",_=gt.INSPECT_MAX_BYTES;return d=this.toString("hex",0,_).replace(/(.{2})/g,"$1 ").trim(),this.length>_&&(d+=" ... "),"<Buffer "+d+">"},t&&(i.prototype[t]=i.prototype.inspect),i.prototype.compare=function(d,_,A,B,X){if(H(d,Uint8Array)&&(d=i.from(d,d.offset,d.byteLength)),!i.isBuffer(d))throw new TypeError('The "target" argument must be one of type Buffer or Uint8Array. Received type '+typeof d);if(_===void 0&&(_=0),A===void 0&&(A=d?d.length:0),B===void 0&&(B=0),X===void 0&&(X=this.length),_<0||A>d.length||B<0||X>this.length)throw new RangeError("out of range index");if(B>=X&&_>=A)return 0;if(B>=X)return-1;if(_>=A)return 1;if(_>>>=0,A>>>=0,B>>>=0,X>>>=0,this===d)return 0;let he=X-B,ke=A-_,z=Math.min(he,ke),ie=this.slice(B,X),Ee=d.slice(_,A);for(let Ae=0;Ae<z;++Ae)if(ie[Ae]!==Ee[Ae]){he=ie[Ae],ke=Ee[Ae];break}return he<ke?-1:ke<he?1:0};function v(d,_,A,B,X){if(d.length===0)return-1;if(typeof A=="string"?(B=A,A=0):A>2147483647?A=2147483647:A<-2147483648&&(A=-2147483648),A=+A,me(A)&&(A=X?0:d.length-1),A<0&&(A=d.length+A),A>=d.length){if(X)return-1;A=d.length-1}else if(A<0)if(X)A=0;else return-1;if(typeof _=="string"&&(_=i.from(_,B)),i.isBuffer(_))return _.length===0?-1:E(d,_,A,B,X);if(typeof _=="number")return _=_&255,typeof Uint8Array.prototype.indexOf=="function"?X?Uint8Array.prototype.indexOf.call(d,_,A):Uint8Array.prototype.lastIndexOf.call(d,_,A):E(d,[_],A,B,X);throw new TypeError("val must be string, number or Buffer")}function E(d,_,A,B,X){let he=1,ke=d.length,z=_.length;if(B!==void 0&&(B=String(B).toLowerCase(),B==="ucs2"||B==="ucs-2"||B==="utf16le"||B==="utf-16le")){if(d.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 Ee;if(X){let Ae=-1;for(Ee=A;Ee<ke;Ee++)if(ie(d,Ee)===ie(_,Ae===-1?0:Ee-Ae)){if(Ae===-1&&(Ae=Ee),Ee-Ae+1===z)return Ae*he}else Ae!==-1&&(Ee-=Ee-Ae),Ae=-1}else for(A+z>ke&&(A=ke-z),Ee=A;Ee>=0;Ee--){let Ae=!0;for(let Ie=0;Ie<z;Ie++)if(ie(d,Ee+Ie)!==ie(_,Ie)){Ae=!1;break}if(Ae)return Ee}return-1}i.prototype.includes=function(d,_,A){return this.indexOf(d,_,A)!==-1},i.prototype.indexOf=function(d,_,A){return v(this,d,_,A,!0)},i.prototype.lastIndexOf=function(d,_,A){return v(this,d,_,A,!1)};function S(d,_,A,B){A=Number(A)||0;let X=d.length-A;B?(B=Number(B),B>X&&(B=X)):B=X;let he=_.length;B>he/2&&(B=he/2);let ke;for(ke=0;ke<B;++ke){let z=parseInt(_.substr(ke*2,2),16);if(me(z))return ke;d[A+ke]=z}return ke}function I(d,_,A,B){return ye($(_,d.length-A),d,A,B)}function O(d,_,A,B){return ye(ee(_),d,A,B)}function P(d,_,A,B){return ye(fe(_),d,A,B)}function N(d,_,A,B){return ye(de(_,d.length-A),d,A,B)}i.prototype.write=function(d,_,A,B){if(_===void 0)B="utf8",A=this.length,_=0;else if(A===void 0&&typeof _=="string")B=_,A=this.length,_=0;else if(isFinite(_))_=_>>>0,isFinite(A)?(A=A>>>0,B===void 0&&(B="utf8")):(B=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),d.length>0&&(A<0||_<0)||_>this.length)throw new RangeError("Attempt to write outside buffer bounds");B||(B="utf8");let he=!1;for(;;)switch(B){case"hex":return S(this,d,_,A);case"utf8":case"utf-8":return I(this,d,_,A);case"ascii":case"latin1":case"binary":return O(this,d,_,A);case"base64":return P(this,d,_,A);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return N(this,d,_,A);default:if(he)throw new TypeError("Unknown encoding: "+B);B=(""+B).toLowerCase(),he=!0}},i.prototype.toJSON=function(){return{type:"Buffer",data:Array.prototype.slice.call(this._arr||this,0)}};function T(d,_,A){return _===0&&A===d.length?l.fromByteArray(d):l.fromByteArray(d.slice(_,A))}function q(d,_,A){A=Math.min(d.length,A);let B=[],X=_;for(;X<A;){let he=d[X],ke=null,z=he>239?4:he>223?3:he>191?2:1;if(X+z<=A){let ie,Ee,Ae,Ie;switch(z){case 1:he<128&&(ke=he);break;case 2:ie=d[X+1],(ie&192)===128&&(Ie=(he&31)<<6|ie&63,Ie>127&&(ke=Ie));break;case 3:ie=d[X+1],Ee=d[X+2],(ie&192)===128&&(Ee&192)===128&&(Ie=(he&15)<<12|(ie&63)<<6|Ee&63,Ie>2047&&(Ie<55296||Ie>57343)&&(ke=Ie));break;case 4:ie=d[X+1],Ee=d[X+2],Ae=d[X+3],(ie&192)===128&&(Ee&192)===128&&(Ae&192)===128&&(Ie=(he&15)<<18|(ie&63)<<12|(Ee&63)<<6|Ae&63,Ie>65535&&Ie<1114112&&(ke=Ie))}}ke===null?(ke=65533,z=1):ke>65535&&(ke-=65536,B.push(ke>>>10&1023|55296),ke=56320|ke&1023),B.push(ke),X+=z}return U(B)}let D=4096;function U(d){let _=d.length;if(_<=D)return String.fromCharCode.apply(String,d);let A="",B=0;for(;B<_;)A+=String.fromCharCode.apply(String,d.slice(B,B+=D));return A}function ae(d,_,A){let B="";A=Math.min(d.length,A);for(let X=_;X<A;++X)B+=String.fromCharCode(d[X]&127);return B}function Y(d,_,A){let B="";A=Math.min(d.length,A);for(let X=_;X<A;++X)B+=String.fromCharCode(d[X]);return B}function V(d,_,A){let B=d.length;(!_||_<0)&&(_=0),(!A||A<0||A>B)&&(A=B);let X="";for(let he=_;he<A;++he)X+=ve[d[he]];return X}function re(d,_,A){let B=d.slice(_,A),X="";for(let he=0;he<B.length-1;he+=2)X+=String.fromCharCode(B[he]+B[he+1]*256);return X}i.prototype.slice=function(d,_){let A=this.length;d=~~d,_=_===void 0?A:~~_,d<0?(d+=A,d<0&&(d=0)):d>A&&(d=A),_<0?(_+=A,_<0&&(_=0)):_>A&&(_=A),_<d&&(_=d);let B=this.subarray(d,_);return Object.setPrototypeOf(B,i.prototype),B};function F(d,_,A){if(d%1!==0||d<0)throw new RangeError("offset is not uint");if(d+_>A)throw new RangeError("Trying to access beyond buffer length")}i.prototype.readUintLE=i.prototype.readUIntLE=function(d,_,A){d=d>>>0,_=_>>>0,A||F(d,_,this.length);let B=this[d],X=1,he=0;for(;++he<_&&(X*=256);)B+=this[d+he]*X;return B},i.prototype.readUintBE=i.prototype.readUIntBE=function(d,_,A){d=d>>>0,_=_>>>0,A||F(d,_,this.length);let B=this[d+--_],X=1;for(;_>0&&(X*=256);)B+=this[d+--_]*X;return B},i.prototype.readUint8=i.prototype.readUInt8=function(d,_){return d=d>>>0,_||F(d,1,this.length),this[d]},i.prototype.readUint16LE=i.prototype.readUInt16LE=function(d,_){return d=d>>>0,_||F(d,2,this.length),this[d]|this[d+1]<<8},i.prototype.readUint16BE=i.prototype.readUInt16BE=function(d,_){return d=d>>>0,_||F(d,2,this.length),this[d]<<8|this[d+1]},i.prototype.readUint32LE=i.prototype.readUInt32LE=function(d,_){return d=d>>>0,_||F(d,4,this.length),(this[d]|this[d+1]<<8|this[d+2]<<16)+this[d+3]*16777216},i.prototype.readUint32BE=i.prototype.readUInt32BE=function(d,_){return d=d>>>0,_||F(d,4,this.length),this[d]*16777216+(this[d+1]<<16|this[d+2]<<8|this[d+3])},i.prototype.readBigUInt64LE=se(function(d){d=d>>>0,Q(d,"offset");let _=this[d],A=this[d+7];(_===void 0||A===void 0)&&ge(d,this.length-8);let B=_+this[++d]*2**8+this[++d]*2**16+this[++d]*2**24,X=this[++d]+this[++d]*2**8+this[++d]*2**16+A*2**24;return BigInt(B)+(BigInt(X)<<BigInt(32))}),i.prototype.readBigUInt64BE=se(function(d){d=d>>>0,Q(d,"offset");let _=this[d],A=this[d+7];(_===void 0||A===void 0)&&ge(d,this.length-8);let B=_*2**24+this[++d]*2**16+this[++d]*2**8+this[++d],X=this[++d]*2**24+this[++d]*2**16+this[++d]*2**8+A;return(BigInt(B)<<BigInt(32))+BigInt(X)}),i.prototype.readIntLE=function(d,_,A){d=d>>>0,_=_>>>0,A||F(d,_,this.length);let B=this[d],X=1,he=0;for(;++he<_&&(X*=256);)B+=this[d+he]*X;return X*=128,B>=X&&(B-=Math.pow(2,8*_)),B},i.prototype.readIntBE=function(d,_,A){d=d>>>0,_=_>>>0,A||F(d,_,this.length);let B=_,X=1,he=this[d+--B];for(;B>0&&(X*=256);)he+=this[d+--B]*X;return X*=128,he>=X&&(he-=Math.pow(2,8*_)),he},i.prototype.readInt8=function(d,_){return d=d>>>0,_||F(d,1,this.length),this[d]&128?(255-this[d]+1)*-1:this[d]},i.prototype.readInt16LE=function(d,_){d=d>>>0,_||F(d,2,this.length);let A=this[d]|this[d+1]<<8;return A&32768?A|4294901760:A},i.prototype.readInt16BE=function(d,_){d=d>>>0,_||F(d,2,this.length);let A=this[d+1]|this[d]<<8;return A&32768?A|4294901760:A},i.prototype.readInt32LE=function(d,_){return d=d>>>0,_||F(d,4,this.length),this[d]|this[d+1]<<8|this[d+2]<<16|this[d+3]<<24},i.prototype.readInt32BE=function(d,_){return d=d>>>0,_||F(d,4,this.length),this[d]<<24|this[d+1]<<16|this[d+2]<<8|this[d+3]},i.prototype.readBigInt64LE=se(function(d){d=d>>>0,Q(d,"offset");let _=this[d],A=this[d+7];(_===void 0||A===void 0)&&ge(d,this.length-8);let B=this[d+4]+this[d+5]*2**8+this[d+6]*2**16+(A<<24);return(BigInt(B)<<BigInt(32))+BigInt(_+this[++d]*256+this[++d]*65536+this[++d]*16777216)}),i.prototype.readBigInt64BE=se(function(d){d=d>>>0,Q(d,"offset");let _=this[d],A=this[d+7];(_===void 0||A===void 0)&&ge(d,this.length-8);let B=(_<<24)+this[++d]*2**16+this[++d]*2**8+this[++d];return(BigInt(B)<<BigInt(32))+BigInt(this[++d]*16777216+this[++d]*65536+this[++d]*256+A)}),i.prototype.readFloatLE=function(d,_){return d=d>>>0,_||F(d,4,this.length),e.read(this,d,!0,23,4)},i.prototype.readFloatBE=function(d,_){return d=d>>>0,_||F(d,4,this.length),e.read(this,d,!1,23,4)},i.prototype.readDoubleLE=function(d,_){return d=d>>>0,_||F(d,8,this.length),e.read(this,d,!0,52,8)},i.prototype.readDoubleBE=function(d,_){return d=d>>>0,_||F(d,8,this.length),e.read(this,d,!1,52,8)};function Z(d,_,A,B,X,he){if(!i.isBuffer(d))throw new TypeError('"buffer" argument must be a Buffer instance');if(_>X||_<he)throw new RangeError('"value" argument is out of bounds');if(A+B>d.length)throw new RangeError("Index out of range")}i.prototype.writeUintLE=i.prototype.writeUIntLE=function(d,_,A,B){if(d=+d,_=_>>>0,A=A>>>0,!B){let ke=Math.pow(2,8*A)-1;Z(this,d,_,A,ke,0)}let X=1,he=0;for(this[_]=d&255;++he<A&&(X*=256);)this[_+he]=d/X&255;return _+A},i.prototype.writeUintBE=i.prototype.writeUIntBE=function(d,_,A,B){if(d=+d,_=_>>>0,A=A>>>0,!B){let ke=Math.pow(2,8*A)-1;Z(this,d,_,A,ke,0)}let X=A-1,he=1;for(this[_+X]=d&255;--X>=0&&(he*=256);)this[_+X]=d/he&255;return _+A},i.prototype.writeUint8=i.prototype.writeUInt8=function(d,_,A){return d=+d,_=_>>>0,A||Z(this,d,_,1,255,0),this[_]=d&255,_+1},i.prototype.writeUint16LE=i.prototype.writeUInt16LE=function(d,_,A){return d=+d,_=_>>>0,A||Z(this,d,_,2,65535,0),this[_]=d&255,this[_+1]=d>>>8,_+2},i.prototype.writeUint16BE=i.prototype.writeUInt16BE=function(d,_,A){return d=+d,_=_>>>0,A||Z(this,d,_,2,65535,0),this[_]=d>>>8,this[_+1]=d&255,_+2},i.prototype.writeUint32LE=i.prototype.writeUInt32LE=function(d,_,A){return d=+d,_=_>>>0,A||Z(this,d,_,4,4294967295,0),this[_+3]=d>>>24,this[_+2]=d>>>16,this[_+1]=d>>>8,this[_]=d&255,_+4},i.prototype.writeUint32BE=i.prototype.writeUInt32BE=function(d,_,A){return d=+d,_=_>>>0,A||Z(this,d,_,4,4294967295,0),this[_]=d>>>24,this[_+1]=d>>>16,this[_+2]=d>>>8,this[_+3]=d&255,_+4};function M(d,_,A,B,X){K(_,B,X,d,A,7);let he=Number(_&BigInt(4294967295));d[A++]=he,he=he>>8,d[A++]=he,he=he>>8,d[A++]=he,he=he>>8,d[A++]=he;let ke=Number(_>>BigInt(32)&BigInt(4294967295));return d[A++]=ke,ke=ke>>8,d[A++]=ke,ke=ke>>8,d[A++]=ke,ke=ke>>8,d[A++]=ke,A}function J(d,_,A,B,X){K(_,B,X,d,A,7);let he=Number(_&BigInt(4294967295));d[A+7]=he,he=he>>8,d[A+6]=he,he=he>>8,d[A+5]=he,he=he>>8,d[A+4]=he;let ke=Number(_>>BigInt(32)&BigInt(4294967295));return d[A+3]=ke,ke=ke>>8,d[A+2]=ke,ke=ke>>8,d[A+1]=ke,ke=ke>>8,d[A]=ke,A+8}i.prototype.writeBigUInt64LE=se(function(d,_=0){return M(this,d,_,BigInt(0),BigInt("0xffffffffffffffff"))}),i.prototype.writeBigUInt64BE=se(function(d,_=0){return J(this,d,_,BigInt(0),BigInt("0xffffffffffffffff"))}),i.prototype.writeIntLE=function(d,_,A,B){if(d=+d,_=_>>>0,!B){let z=Math.pow(2,8*A-1);Z(this,d,_,A,z-1,-z)}let X=0,he=1,ke=0;for(this[_]=d&255;++X<A&&(he*=256);)d<0&&ke===0&&this[_+X-1]!==0&&(ke=1),this[_+X]=(d/he>>0)-ke&255;return _+A},i.prototype.writeIntBE=function(d,_,A,B){if(d=+d,_=_>>>0,!B){let z=Math.pow(2,8*A-1);Z(this,d,_,A,z-1,-z)}let X=A-1,he=1,ke=0;for(this[_+X]=d&255;--X>=0&&(he*=256);)d<0&&ke===0&&this[_+X+1]!==0&&(ke=1),this[_+X]=(d/he>>0)-ke&255;return _+A},i.prototype.writeInt8=function(d,_,A){return d=+d,_=_>>>0,A||Z(this,d,_,1,127,-128),d<0&&(d=255+d+1),this[_]=d&255,_+1},i.prototype.writeInt16LE=function(d,_,A){return d=+d,_=_>>>0,A||Z(this,d,_,2,32767,-32768),this[_]=d&255,this[_+1]=d>>>8,_+2},i.prototype.writeInt16BE=function(d,_,A){return d=+d,_=_>>>0,A||Z(this,d,_,2,32767,-32768),this[_]=d>>>8,this[_+1]=d&255,_+2},i.prototype.writeInt32LE=function(d,_,A){return d=+d,_=_>>>0,A||Z(this,d,_,4,2147483647,-2147483648),this[_]=d&255,this[_+1]=d>>>8,this[_+2]=d>>>16,this[_+3]=d>>>24,_+4},i.prototype.writeInt32BE=function(d,_,A){return d=+d,_=_>>>0,A||Z(this,d,_,4,2147483647,-2147483648),d<0&&(d=4294967295+d+1),this[_]=d>>>24,this[_+1]=d>>>16,this[_+2]=d>>>8,this[_+3]=d&255,_+4},i.prototype.writeBigInt64LE=se(function(d,_=0){return M(this,d,_,-BigInt("0x8000000000000000"),BigInt("0x7fffffffffffffff"))}),i.prototype.writeBigInt64BE=se(function(d,_=0){return J(this,d,_,-BigInt("0x8000000000000000"),BigInt("0x7fffffffffffffff"))});function be(d,_,A,B,X,he){if(A+B>d.length)throw new RangeError("Index out of range");if(A<0)throw new RangeError("Index out of range")}function te(d,_,A,B,X){return _=+_,A=A>>>0,X||be(d,_,A,4),e.write(d,_,A,B,23,4),A+4}i.prototype.writeFloatLE=function(d,_,A){return te(this,d,_,!0,A)},i.prototype.writeFloatBE=function(d,_,A){return te(this,d,_,!1,A)};function we(d,_,A,B,X){return _=+_,A=A>>>0,X||be(d,_,A,8),e.write(d,_,A,B,52,8),A+8}i.prototype.writeDoubleLE=function(d,_,A){return we(this,d,_,!0,A)},i.prototype.writeDoubleBE=function(d,_,A){return we(this,d,_,!1,A)},i.prototype.copy=function(d,_,A,B){if(!i.isBuffer(d))throw new TypeError("argument should be a Buffer");if(A||(A=0),!B&&B!==0&&(B=this.length),_>=d.length&&(_=d.length),_||(_=0),B>0&&B<A&&(B=A),B===A||d.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(B<0)throw new RangeError("sourceEnd out of bounds");B>this.length&&(B=this.length),d.length-_<B-A&&(B=d.length-_+A);let X=B-A;return this===d&&typeof Uint8Array.prototype.copyWithin=="function"?this.copyWithin(_,A,B):Uint8Array.prototype.set.call(d,this.subarray(A,B),_),X},i.prototype.fill=function(d,_,A,B){if(typeof d=="string"){if(typeof _=="string"?(B=_,_=0,A=this.length):typeof A=="string"&&(B=A,A=this.length),B!==void 0&&typeof B!="string")throw new TypeError("encoding must be a string");if(typeof B=="string"&&!i.isEncoding(B))throw new TypeError("Unknown encoding: "+B);if(d.length===1){let he=d.charCodeAt(0);(B==="utf8"&&he<128||B==="latin1")&&(d=he)}}else typeof d=="number"?d=d&255:typeof d=="boolean"&&(d=Number(d));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,d||(d=0);let X;if(typeof d=="number")for(X=_;X<A;++X)this[X]=d;else{let he=i.isBuffer(d)?d:i.from(d,B),ke=he.length;if(ke===0)throw new TypeError('The value "'+d+'" is invalid for argument "value"');for(X=0;X<A-_;++X)this[X+_]=he[X%ke]}return this};let G={};function j(d,_,A){G[d]=class extends A{constructor(){super(),Object.defineProperty(this,"message",{value:_.apply(this,arguments),writable:!0,configurable:!0}),this.name=`${this.name} [${d}]`,this.stack,delete this.name}get code(){return d}set code(B){Object.defineProperty(this,"code",{configurable:!0,enumerable:!0,value:B,writable:!0})}toString(){return`${this.name} [${d}]: ${this.message}`}}}j("ERR_BUFFER_OUT_OF_BOUNDS",function(d){return d?`${d} is outside of buffer bounds`:"Attempt to access memory outside buffer bounds"},RangeError),j("ERR_INVALID_ARG_TYPE",function(d,_){return`The "${d}" argument must be of type number. Received type ${typeof _}`},TypeError),j("ERR_OUT_OF_RANGE",function(d,_,A){let B=`The value of "${d}" is out of range.`,X=A;return Number.isInteger(A)&&Math.abs(A)>4294967296?X=ne(String(A)):typeof A=="bigint"&&(X=String(A),(A>BigInt(2)**BigInt(32)||A<-(BigInt(2)**BigInt(32)))&&(X=ne(X)),X+="n"),B+=` It must be ${_}. Received ${X}`,B},RangeError);function ne(d){let _="",A=d.length,B=d[0]==="-"?1:0;for(;A>=B+4;A-=3)_=`_${d.slice(A-3,A)}${_}`;return`${d.slice(0,A)}${_}`}function W(d,_,A){Q(_,"offset"),(d[_]===void 0||d[_+A]===void 0)&&ge(_,d.length-(A+1))}function K(d,_,A,B,X,he){if(d>A||d<_){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 G.ERR_OUT_OF_RANGE("value",z,d)}W(B,X,he)}function Q(d,_){if(typeof d!="number")throw new G.ERR_INVALID_ARG_TYPE(_,"number",d)}function ge(d,_,A){throw Math.floor(d)!==d?(Q(d,A),new G.ERR_OUT_OF_RANGE("offset","an integer",d)):_<0?new G.ERR_BUFFER_OUT_OF_BOUNDS:new G.ERR_OUT_OF_RANGE("offset",`>= 0 and <= ${_}`,d)}let oe=/[^+/0-9A-Za-z-_]/g;function R(d){if(d=d.split("=")[0],d=d.trim().replace(oe,""),d.length<2)return"";for(;d.length%4!==0;)d=d+"=";return d}function $(d,_){_=_||1/0;let A,B=d.length,X=null,he=[];for(let ke=0;ke<B;++ke){if(A=d.charCodeAt(ke),A>55295&&A<57344){if(!X){if(A>56319){(_-=3)>-1&&he.push(239,191,189);continue}else if(ke+1===B){(_-=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(d){let _=[];for(let A=0;A<d.length;++A)_.push(d.charCodeAt(A)&255);return _}function de(d,_){let A,B,X,he=[];for(let ke=0;ke<d.length&&!((_-=2)<0);++ke)A=d.charCodeAt(ke),B=A>>8,X=A%256,he.push(X),he.push(B);return he}function fe(d){return l.toByteArray(R(d))}function ye(d,_,A,B){let X;for(X=0;X<B&&!(X+A>=_.length||X>=d.length);++X)_[X+A]=d[X];return X}function H(d,_){return d instanceof _||d!=null&&d.constructor!=null&&d.constructor.name!=null&&d.constructor.name===_.name}function me(d){return d!==d}let ve=(function(){let d="0123456789abcdef",_=new Array(256);for(let A=0;A<16;++A){let B=A*16;for(let X=0;X<16;++X)_[B+X]=d[A]+d[X]}return _})();function se(d){return typeof BigInt>"u"?Te:d}function Te(){throw new Error("BigInt not supported")}return gt}var Lt,ii,Vt,oi,gt,si,Tc=Ve(()=>{le(),ue(),ce(),Lt={},ii=!1,Vt={},oi=!1,gt={},si=!1}),Be={};Rt(Be,{Buffer:()=>lr,INSPECT_MAX_BYTES:()=>Wo,default:()=>lt,kMaxLength:()=>zo});var lt,lr,Wo,zo,De=Ve(()=>{le(),ue(),ce(),Tc(),lt=Ic(),lt.Buffer,lt.SlowBuffer,lt.INSPECT_MAX_BYTES,lt.kMaxLength,lr=lt.Buffer,Wo=lt.INSPECT_MAX_BYTES,zo=lt.kMaxLength}),ue=Ve(()=>{De()}),Ne=pe((l,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 s="";for(let n=0;n<r.length;n++)s+=` ${r[n].stack}
2
+ `;super(s),this.name="AggregateError",this.errors=r}};e.exports={AggregateError:t,ArrayIsArray(r){return Array.isArray(r)},ArrayPrototypeIncludes(r,s){return r.includes(s)},ArrayPrototypeIndexOf(r,s){return r.indexOf(s)},ArrayPrototypeJoin(r,s){return r.join(s)},ArrayPrototypeMap(r,s){return r.map(s)},ArrayPrototypePop(r,s){return r.pop(s)},ArrayPrototypePush(r,s){return r.push(s)},ArrayPrototypeSlice(r,s,n){return r.slice(s,n)},Error,FunctionPrototypeCall(r,s,...n){return r.call(s,...n)},FunctionPrototypeSymbolHasInstance(r,s){return Function.prototype[Symbol.hasInstance].call(r,s)},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,s){return Object.defineProperties(r,s)},ObjectDefineProperty(r,s,n){return Object.defineProperty(r,s,n)},ObjectGetOwnPropertyDescriptor(r,s){return Object.getOwnPropertyDescriptor(r,s)},ObjectKeys(r){return Object.keys(r)},ObjectSetPrototypeOf(r,s){return Object.setPrototypeOf(r,s)},Promise,PromisePrototypeCatch(r,s){return r.catch(s)},PromisePrototypeThen(r,s,n){return r.then(s,n)},PromiseReject(r){return Promise.reject(r)},PromiseResolve(r){return Promise.resolve(r)},ReflectApply:Reflect.apply,RegExpPrototypeTest(r,s){return r.test(s)},SafeSet:Set,String,StringPrototypeSlice(r,s,n){return r.slice(s,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,s,n){return r.set(s,n)},Boolean,Uint8Array}}),Vo=pe((l,e)=>{le(),ue(),ce(),e.exports={format(t,...r){return t.replace(/%([sdifj])/g,function(...[s,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((l,e)=>{le(),ue(),ce();var{format:t,inspect:r}=Vo(),{AggregateError:s}=Ne(),n=globalThis.AggregateError||s,i=Symbol("kIsNodeError"),o=["string","function","number","object","Function","Object","boolean","bigint","symbol"],a=/^([A-Z][a-z0-9]*)+$/,c="__node_internal_",u={};function h(m,w){if(!m)throw new u.ERR_INTERNAL_ASSERTION(w)}function p(m){let w="",x=m.length,v=m[0]==="-"?1:0;for(;x>=v+4;x-=3)w=`_${m.slice(x-3,x)}${w}`;return`${m.slice(0,x)}${w}`}function y(m,w,x){if(typeof w=="function")return h(w.length<=x.length,`Code: ${m}; The provided arguments length (${x.length}) does not match the required ones (${w.length}).`),w(...x);let v=(w.match(/%[dfijoOs]/g)||[]).length;return h(v===x.length,`Code: ${m}; The provided arguments length (${x.length}) does not match the required ones (${v}).`),x.length===0?w:t(w,...x)}function f(m,w,x){x||(x=Error);class v extends x{constructor(...S){super(y(m,w,S))}toString(){return`${this.name} [${m}]: ${this.message}`}}Object.defineProperties(v.prototype,{name:{value:x.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=c+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 x=new n([w,m],w.message);return x.code=w.code,x}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,x)=>{h(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 E=[],S=[],I=[];for(let P of w)h(typeof P=="string","All expected entries have to be of type string"),o.includes(P)?E.push(P.toLowerCase()):a.test(P)?S.push(P):(h(P!=="object",'The value "object" should be written as "Object"'),I.push(P));if(S.length>0){let P=E.indexOf("object");P!==-1&&(E.splice(E,P,1),S.push("Object"))}if(E.length>0){switch(E.length){case 1:v+=`of type ${E[0]}`;break;case 2:v+=`one of type ${E[0]} or ${E[1]}`;break;default:{let P=E.pop();v+=`one of type ${E.join(", ")}, or ${P}`}}(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 P=S.pop();v+=`an instance of ${S.join(", ")}, or ${P}`}}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 P=I.pop();v+=`one of ${I.join(", ")}, or ${P}`}}if(x==null)v+=`. Received ${x}`;else if(typeof x=="function"&&x.name)v+=`. Received function ${x.name}`;else if(typeof x=="object"){var O;if((O=x.constructor)!==null&&O!==void 0&&O.name)v+=`. Received an instance of ${x.constructor.name}`;else{let P=r(x,{depth:-1});v+=`. Received ${P}`}}else{let P=r(x,{colors:!1});P.length>25&&(P=`${P.slice(0,25)}...`),v+=`. Received type ${typeof x} (${P})`}return v},TypeError),f("ERR_INVALID_ARG_VALUE",(m,w,x="is invalid")=>{let v=r(w);return v.length>128&&(v=v.slice(0,128)+"..."),`The ${m.includes(".")?"property":"argument"} '${m}' ${x}. Received ${v}`},TypeError),f("ERR_INVALID_RETURN_VALUE",(m,w,x)=>{var v;let E=x!=null&&(v=x.constructor)!==null&&v!==void 0&&v.name?`instance of ${x.constructor.name}`:`type ${typeof x}`;return`Expected ${m} to be returned from the "${w}" function but got ${E}.`},TypeError),f("ERR_MISSING_ARGS",(...m)=>{h(m.length>0,"At least one arg needs to be specified");let w,x=m.length;switch(m=(Array.isArray(m)?m:[m]).map(v=>`"${v}"`).join(" or "),x){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,x)=>{h(w,'Missing "range" argument');let v;if(Number.isInteger(x)&&Math.abs(x)>2**32)v=p(String(x));else if(typeof x=="bigint"){v=String(x);let E=BigInt(2)**BigInt(32);(x>E||x<-E)&&(v=p(v)),v+="n"}else v=r(x);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}}),Gt=pe((l,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={};Rt(bt,{EventEmitter:()=>Go,default:()=>jt,defaultMaxListeners:()=>Ko,init:()=>Yo,listenerCount:()=>Qo,on:()=>Jo,once:()=>Xo});function Cc(){if(ai)return Kt;ai=!0;var l=typeof Reflect=="object"?Reflect:null,e=l&&typeof l.apply=="function"?l.apply:function(x,v,E){return Function.prototype.apply.call(x,v,E)},t;l&&typeof l.ownKeys=="function"?t=l.ownKeys:Object.getOwnPropertySymbols?t=function(x){return Object.getOwnPropertyNames(x).concat(Object.getOwnPropertySymbols(x))}:t=function(x){return Object.getOwnPropertyNames(x)};function r(x){console&&console.warn&&console.warn(x)}var s=Number.isNaN||function(x){return x!==x};function n(){n.init.call(this)}Kt=n,Kt.once=k,n.EventEmitter=n,n.prototype._events=void 0,n.prototype._eventsCount=0,n.prototype._maxListeners=void 0;var i=10;function o(x){if(typeof x!="function")throw new TypeError('The "listener" argument must be of type Function. Received type '+typeof x)}Object.defineProperty(n,"defaultMaxListeners",{enumerable:!0,get:function(){return i},set:function(x){if(typeof x!="number"||x<0||s(x))throw new RangeError('The value of "defaultMaxListeners" is out of range. It must be a non-negative number. Received '+x+".");i=x}}),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(x){if(typeof x!="number"||x<0||s(x))throw new RangeError('The value of "n" is out of range. It must be a non-negative number. Received '+x+".");return this._maxListeners=x,this};function a(x){return x._maxListeners===void 0?n.defaultMaxListeners:x._maxListeners}n.prototype.getMaxListeners=function(){return a(this)},n.prototype.emit=function(x){for(var v=[],E=1;E<arguments.length;E++)v.push(arguments[E]);var S=x==="error",I=this._events;if(I!==void 0)S=S&&I.error===void 0;else if(!S)return!1;if(S){var O;if(v.length>0&&(O=v[0]),O instanceof Error)throw O;var P=new Error("Unhandled error."+(O?" ("+O.message+")":""));throw P.context=O,P}var N=I[x];if(N===void 0)return!1;if(typeof N=="function")e(N,this,v);else for(var T=N.length,q=f(N,T),E=0;E<T;++E)e(q[E],this,v);return!0};function c(x,v,E,S){var I,O,P;if(o(E),O=x._events,O===void 0?(O=x._events=Object.create(null),x._eventsCount=0):(O.newListener!==void 0&&(x.emit("newListener",v,E.listener?E.listener:E),O=x._events),P=O[v]),P===void 0)P=O[v]=E,++x._eventsCount;else if(typeof P=="function"?P=O[v]=S?[E,P]:[P,E]:S?P.unshift(E):P.push(E),I=a(x),I>0&&P.length>I&&!P.warned){P.warned=!0;var N=new Error("Possible EventEmitter memory leak detected. "+P.length+" "+String(v)+" listeners added. Use emitter.setMaxListeners() to increase limit");N.name="MaxListenersExceededWarning",N.emitter=x,N.type=v,N.count=P.length,r(N)}return x}n.prototype.addListener=function(x,v){return c(this,x,v,!1)},n.prototype.on=n.prototype.addListener,n.prototype.prependListener=function(x,v){return c(this,x,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 h(x,v,E){var S={fired:!1,wrapFn:void 0,target:x,type:v,listener:E},I=u.bind(S);return I.listener=E,S.wrapFn=I,I}n.prototype.once=function(x,v){return o(v),this.on(x,h(this,x,v)),this},n.prototype.prependOnceListener=function(x,v){return o(v),this.prependListener(x,h(this,x,v)),this},n.prototype.removeListener=function(x,v){var E,S,I,O,P;if(o(v),S=this._events,S===void 0)return this;if(E=S[x],E===void 0)return this;if(E===v||E.listener===v)--this._eventsCount===0?this._events=Object.create(null):(delete S[x],S.removeListener&&this.emit("removeListener",x,E.listener||v));else if(typeof E!="function"){for(I=-1,O=E.length-1;O>=0;O--)if(E[O]===v||E[O].listener===v){P=E[O].listener,I=O;break}if(I<0)return this;I===0?E.shift():g(E,I),E.length===1&&(S[x]=E[0]),S.removeListener!==void 0&&this.emit("removeListener",x,P||v)}return this},n.prototype.off=n.prototype.removeListener,n.prototype.removeAllListeners=function(x){var v,E,S;if(E=this._events,E===void 0)return this;if(E.removeListener===void 0)return arguments.length===0?(this._events=Object.create(null),this._eventsCount=0):E[x]!==void 0&&(--this._eventsCount===0?this._events=Object.create(null):delete E[x]),this;if(arguments.length===0){var I=Object.keys(E),O;for(S=0;S<I.length;++S)O=I[S],O!=="removeListener"&&this.removeAllListeners(O);return this.removeAllListeners("removeListener"),this._events=Object.create(null),this._eventsCount=0,this}if(v=E[x],typeof v=="function")this.removeListener(x,v);else if(v!==void 0)for(S=v.length-1;S>=0;S--)this.removeListener(x,v[S]);return this};function p(x,v,E){var S=x._events;if(S===void 0)return[];var I=S[v];return I===void 0?[]:typeof I=="function"?E?[I.listener||I]:[I]:E?b(I):f(I,I.length)}n.prototype.listeners=function(x){return p(this,x,!0)},n.prototype.rawListeners=function(x){return p(this,x,!1)},n.listenerCount=function(x,v){return typeof x.listenerCount=="function"?x.listenerCount(v):y.call(x,v)},n.prototype.listenerCount=y;function y(x){var v=this._events;if(v!==void 0){var E=v[x];if(typeof E=="function")return 1;if(E!==void 0)return E.length}return 0}n.prototype.eventNames=function(){return this._eventsCount>0?t(this._events):[]};function f(x,v){for(var E=new Array(v),S=0;S<v;++S)E[S]=x[S];return E}function g(x,v){for(;v+1<x.length;v++)x[v]=x[v+1];x.pop()}function b(x){for(var v=new Array(x.length),E=0;E<v.length;++E)v[E]=x[E].listener||x[E];return v}function k(x,v){return new Promise(function(E,S){function I(P){x.removeListener(v,O),S(P)}function O(){typeof x.removeListener=="function"&&x.removeListener("error",I),E([].slice.call(arguments))}w(x,v,O,{once:!0}),v!=="error"&&m(x,I,{once:!0})})}function m(x,v,E){typeof x.on=="function"&&w(x,"error",v,E)}function w(x,v,E,S){if(typeof x.on=="function")S.once?x.once(v,E):x.on(v,E);else if(typeof x.addEventListener=="function")x.addEventListener(v,function I(O){S.once&&x.removeEventListener(v,I),E(O)});else throw new TypeError('The "emitter" argument must be of type EventEmitter. Received type '+typeof x)}return Kt}var Kt,ai,jt,Go,Ko,Yo,Qo,Jo,Xo,Et=Ve(()=>{le(),ue(),ce(),Kt={},ai=!1,jt=Cc(),jt.once,jt.once=function(l,e){return new Promise((t,r)=>{function s(...i){n!==void 0&&l.removeListener("error",n),t(i)}let n;e!=="error"&&(n=i=>{l.removeListener(name,s),r(i)},l.once("error",n)),l.once(e,s)})},jt.on=function(l,e){let t=[],r=[],s=null,n=!1,i={async next(){let c=t.shift();if(c)return createIterResult(c,!1);if(s){let u=Promise.reject(s);return s=null,u}return n?createIterResult(void 0,!0):new Promise((u,h)=>r.push({resolve:u,reject:h}))},async return(){l.removeListener(e,o),l.removeListener("error",a),n=!0;for(let c of r)c.resolve(createIterResult(void 0,!0));return createIterResult(void 0,!0)},throw(c){s=c,l.removeListener(e,o),l.removeListener("error",a)},[Symbol.asyncIterator](){return this}};return l.on(e,o),l.on("error",a),i;function o(...c){let u=r.shift();u?u.resolve(createIterResult(c,!1)):t.push(c)}function a(c){n=!0;let u=r.shift();u?u.reject(c):s=c,i.return()}},{EventEmitter:Go,defaultMaxListeners:Ko,init:Yo,listenerCount:Qo,on:Jo,once:Xo}=jt}),Ge=pe((l,e)=>{le(),ue(),ce();var t=(De(),Me(Be)),{format:r,inspect:s}=Vo(),{codes:{ERR_INVALID_ARG_TYPE:n}}=We(),{kResistStopPropagation:i,AggregateError:o,SymbolDispose:a}=Ne(),c=globalThis.AbortSignal||Gt().AbortSignal,u=globalThis.AbortController||Gt().AbortController,h=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:o,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,...x)=>w?m(w):k(...x))})},debuglog(){return function(){}},format:r,inspect:s,types:{isAsyncFunction(b){return b instanceof h},isArrayBufferView(b){return ArrayBuffer.isView(b)}},isBlob:y,deprecate(b,k){return b},addAbortListener:(Et(),Me(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,[a](){var w;(w=m)===null||w===void 0||w()}}},AbortSignalAny:c.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")}),Yt=pe((l,e)=>{le(),ue(),ce();var{ArrayIsArray:t,ArrayPrototypeIncludes:r,ArrayPrototypeJoin:s,ArrayPrototypeMap:n,NumberIsInteger:i,NumberIsNaN:o,NumberMAX_SAFE_INTEGER:a,NumberMIN_SAFE_INTEGER:c,NumberParseInt:u,ObjectPrototypeHasOwnProperty:h,RegExpPrototypeExec:p,String:y,StringPrototypeToUpperCase:f,StringPrototypeTrim:g}=Ne(),{hideStackFrames:b,codes:{ERR_SOCKET_BAD_PORT:k,ERR_INVALID_ARG_TYPE:m,ERR_INVALID_ARG_VALUE:w,ERR_OUT_OF_RANGE:x,ERR_UNKNOWN_SIGNAL:v}}=We(),{normalizeEncoding:E}=Ge(),{isAsyncFunction:S,isArrayBufferView:I}=Ge().types,O={};function P(H){return H===(H|0)}function N(H){return H===H>>>0}var T=/^[0-7]+$/,q="must be a 32-bit unsigned integer or an octal string";function D(H,me,ve){if(typeof H>"u"&&(H=ve),typeof H=="string"){if(p(T,H)===null)throw new w(me,H,q);H=u(H,8)}return Y(H,me),H}var U=b((H,me,ve=c,se=a)=>{if(typeof H!="number")throw new m(me,"number",H);if(!i(H))throw new x(me,"an integer",H);if(H<ve||H>se)throw new x(me,`>= ${ve} && <= ${se}`,H)}),ae=b((H,me,ve=-2147483648,se=2147483647)=>{if(typeof H!="number")throw new m(me,"number",H);if(!i(H))throw new x(me,"an integer",H);if(H<ve||H>se)throw new x(me,`>= ${ve} && <= ${se}`,H)}),Y=b((H,me,ve=!1)=>{if(typeof H!="number")throw new m(me,"number",H);if(!i(H))throw new x(me,"an integer",H);let se=ve?1:0,Te=4294967295;if(H<se||H>Te)throw new x(me,`>= ${se} && <= ${Te}`,H)});function V(H,me){if(typeof H!="string")throw new m(me,"string",H)}function re(H,me,ve=void 0,se){if(typeof H!="number")throw new m(me,"number",H);if(ve!=null&&H<ve||se!=null&&H>se||(ve!=null||se!=null)&&o(H))throw new x(me,`${ve!=null?`>= ${ve}`:""}${ve!=null&&se!=null?" && ":""}${se!=null?`<= ${se}`:""}`,H)}var F=b((H,me,ve)=>{if(!r(ve,H)){let se="must be one of: "+s(n(ve,Te=>typeof Te=="string"?`'${Te}'`:y(Te)),", ");throw new w(me,H,se)}});function Z(H,me){if(typeof H!="boolean")throw new m(me,"boolean",H)}function M(H,me,ve){return H==null||!h(H,me)?ve:H[me]}var J=b((H,me,ve=null)=>{let se=M(ve,"allowArray",!1),Te=M(ve,"allowFunction",!1);if(!M(ve,"nullable",!1)&&H===null||!se&&t(H)||typeof H!="object"&&(!Te||typeof H!="function"))throw new m(me,"Object",H)}),be=b((H,me)=>{if(H!=null&&typeof H!="object"&&typeof H!="function")throw new m(me,"a dictionary",H)}),te=b((H,me,ve=0)=>{if(!t(H))throw new m(me,"Array",H);if(H.length<ve){let se=`must be longer than ${ve}`;throw new w(me,H,se)}});function we(H,me){te(H,me);for(let ve=0;ve<H.length;ve++)V(H[ve],`${me}[${ve}]`)}function G(H,me){te(H,me);for(let ve=0;ve<H.length;ve++)Z(H[ve],`${me}[${ve}]`)}function j(H,me){te(H,me);for(let ve=0;ve<H.length;ve++){let se=H[ve],Te=`${me}[${ve}]`;if(se==null)throw new m(Te,"AbortSignal",se);ge(se,Te)}}function ne(H,me="signal"){if(V(H,me),O[H]===void 0)throw O[f(H)]!==void 0?new v(H+" (signals must use all capital letters)"):new v(H)}var W=b((H,me="buffer")=>{if(!I(H))throw new m(me,["Buffer","TypedArray","DataView"],H)});function K(H,me){let ve=E(me),se=H.length;if(ve==="hex"&&se%2!==0)throw new w("encoding",me,`is invalid for data of length ${se}`)}function Q(H,me="Port",ve=!0){if(typeof H!="number"&&typeof H!="string"||typeof H=="string"&&g(H).length===0||+H!==+H>>>0||H>65535||H===0&&!ve)throw new k(me,H,ve);return H|0}var ge=b((H,me)=>{if(H!==void 0&&(H===null||typeof H!="object"||!("aborted"in H)))throw new m(me,"AbortSignal",H)}),oe=b((H,me)=>{if(typeof H!="function")throw new m(me,"Function",H)}),R=b((H,me)=>{if(typeof H!="function"||S(H))throw new m(me,"Function",H)}),$=b((H,me)=>{if(H!==void 0)throw new m(me,"undefined",H)});function ee(H,me,ve){if(!r(ve,H))throw new m(me,`('${s(ve,"|")}')`,H)}var de=/^(?:<[^>]*>)(?:\s*;\s*[^;"\s]+(?:=(")?[^;"\s]*\1)?)*$/;function fe(H,me){if(typeof H>"u"||!p(de,H))throw new w(me,H,'must be an array or string of format "</styles.css>; rel=preload; as=style"')}function ye(H){if(typeof H=="string")return fe(H,"hints"),H;if(t(H)){let me=H.length,ve="";if(me===0)return ve;for(let se=0;se<me;se++){let Te=H[se];fe(Te,"hints"),ve+=Te,se!==me-1&&(ve+=", ")}return ve}throw new w("hints",H,'must be an array or string of format "</styles.css>; rel=preload; as=style"')}e.exports={isInt32:P,isUint32:N,parseFileMode:D,validateArray:te,validateStringArray:we,validateBooleanArray:G,validateAbortSignalArray:j,validateBoolean:Z,validateBuffer:W,validateDictionary:be,validateEncoding:K,validateFunction:oe,validateInt32:ae,validateInteger:U,validateNumber:re,validateObject:J,validateOneOf:F,validatePlainFunction:R,validatePort:Q,validateSignalName:ne,validateString:V,validateUint32:Y,validateUndefined:$,validateUnion:ee,validateAbortSignal:ge,validateLinkHeaderValue:ye}}),At=pe((l,e)=>{le(),ue(),ce();var t=e.exports={},r,s;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"?s=clearTimeout:s=i}catch{s=i}})();function o(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 a(k){if(s===clearTimeout)return clearTimeout(k);if((s===i||!s)&&clearTimeout)return s=clearTimeout,clearTimeout(k);try{return s(k)}catch{try{return s.call(null,k)}catch{return s.call(this,k)}}}var c=[],u=!1,h,p=-1;function y(){!u||!h||(u=!1,h.length?c=h.concat(c):p=-1,c.length&&f())}function f(){if(!u){var k=o(y);u=!0;for(var m=c.length;m;){for(h=c,c=[];++p<m;)h&&h[p].run();p=-1,m=c.length}h=null,u=!1,a(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];c.push(new g(k,m)),c.length===1&&!u&&o(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((l,e)=>{le(),ue(),ce();var{SymbolAsyncIterator:t,SymbolIterator:r,SymbolFor:s}=Ne(),n=s("nodejs.stream.destroyed"),i=s("nodejs.stream.errored"),o=s("nodejs.stream.readable"),a=s("nodejs.stream.writable"),c=s("nodejs.stream.disturbed"),u=s("nodejs.webstream.isClosedPromise"),h=s("nodejs.webstream.controllerErrorFunction");function p(M,J=!1){var be;return!!(M&&typeof M.pipe=="function"&&typeof M.on=="function"&&(!J||typeof M.pause=="function"&&typeof M.resume=="function")&&(!M._writableState||((be=M._readableState)===null||be===void 0?void 0:be.readable)!==!1)&&(!M._writableState||M._readableState))}function y(M){var J;return!!(M&&typeof M.write=="function"&&typeof M.on=="function"&&(!M._readableState||((J=M._writableState)===null||J===void 0?void 0:J.writable)!==!1))}function f(M){return!!(M&&typeof M.pipe=="function"&&M._readableState&&typeof M.on=="function"&&typeof M.write=="function")}function g(M){return M&&(M._readableState||M._writableState||typeof M.write=="function"&&typeof M.on=="function"||typeof M.pipe=="function"&&typeof M.on=="function")}function b(M){return!!(M&&!g(M)&&typeof M.pipeThrough=="function"&&typeof M.getReader=="function"&&typeof M.cancel=="function")}function k(M){return!!(M&&!g(M)&&typeof M.getWriter=="function"&&typeof M.abort=="function")}function m(M){return!!(M&&!g(M)&&typeof M.readable=="object"&&typeof M.writable=="object")}function w(M){return b(M)||k(M)||m(M)}function x(M,J){return M==null?!1:J===!0?typeof M[t]=="function":J===!1?typeof M[r]=="function":typeof M[t]=="function"||typeof M[r]=="function"}function v(M){if(!g(M))return null;let J=M._writableState,be=M._readableState,te=J||be;return!!(M.destroyed||M[n]||te!=null&&te.destroyed)}function E(M){if(!y(M))return null;if(M.writableEnded===!0)return!0;let J=M._writableState;return J!=null&&J.errored?!1:typeof J?.ended!="boolean"?null:J.ended}function S(M,J){if(!y(M))return null;if(M.writableFinished===!0)return!0;let be=M._writableState;return be!=null&&be.errored?!1:typeof be?.finished!="boolean"?null:!!(be.finished||J===!1&&be.ended===!0&&be.length===0)}function I(M){if(!p(M))return null;if(M.readableEnded===!0)return!0;let J=M._readableState;return!J||J.errored?!1:typeof J?.ended!="boolean"?null:J.ended}function O(M,J){if(!p(M))return null;let be=M._readableState;return be!=null&&be.errored?!1:typeof be?.endEmitted!="boolean"?null:!!(be.endEmitted||J===!1&&be.ended===!0&&be.length===0)}function P(M){return M&&M[o]!=null?M[o]:typeof M?.readable!="boolean"?null:v(M)?!1:p(M)&&M.readable&&!O(M)}function N(M){return M&&M[a]!=null?M[a]:typeof M?.writable!="boolean"?null:v(M)?!1:y(M)&&M.writable&&!E(M)}function T(M,J){return g(M)?v(M)?!0:!(J?.readable!==!1&&P(M)||J?.writable!==!1&&N(M)):null}function q(M){var J,be;return g(M)?M.writableErrored?M.writableErrored:(J=(be=M._writableState)===null||be===void 0?void 0:be.errored)!==null&&J!==void 0?J:null:null}function D(M){var J,be;return g(M)?M.readableErrored?M.readableErrored:(J=(be=M._readableState)===null||be===void 0?void 0:be.errored)!==null&&J!==void 0?J:null:null}function U(M){if(!g(M))return null;if(typeof M.closed=="boolean")return M.closed;let J=M._writableState,be=M._readableState;return typeof J?.closed=="boolean"||typeof be?.closed=="boolean"?J?.closed||be?.closed:typeof M._closed=="boolean"&&ae(M)?M._closed:null}function ae(M){return typeof M._closed=="boolean"&&typeof M._defaultKeepAlive=="boolean"&&typeof M._removedConnection=="boolean"&&typeof M._removedContLen=="boolean"}function Y(M){return typeof M._sent100=="boolean"&&ae(M)}function V(M){var J;return typeof M._consuming=="boolean"&&typeof M._dumped=="boolean"&&((J=M.req)===null||J===void 0?void 0:J.upgradeOrConnect)===void 0}function re(M){if(!g(M))return null;let J=M._writableState,be=M._readableState,te=J||be;return!te&&Y(M)||!!(te&&te.autoDestroy&&te.emitClose&&te.closed===!1)}function F(M){var J;return!!(M&&((J=M[c])!==null&&J!==void 0?J:M.readableDidRead||M.readableAborted))}function Z(M){var J,be,te,we,G,j,ne,W,K,Q;return!!(M&&((J=(be=(te=(we=(G=(j=M[i])!==null&&j!==void 0?j:M.readableErrored)!==null&&G!==void 0?G:M.writableErrored)!==null&&we!==void 0?we:(ne=M._readableState)===null||ne===void 0?void 0:ne.errorEmitted)!==null&&te!==void 0?te:(W=M._writableState)===null||W===void 0?void 0:W.errorEmitted)!==null&&be!==void 0?be:(K=M._readableState)===null||K===void 0?void 0:K.errored)!==null&&J!==void 0?J:!((Q=M._writableState)===null||Q===void 0)&&Q.errored))}e.exports={isDestroyed:v,kIsDestroyed:n,isDisturbed:F,kIsDisturbed:c,isErrored:Z,kIsErrored:i,isReadable:P,kIsReadable:o,kIsClosedPromise:u,kControllerErrorFunction:h,kIsWritable:a,isClosed:U,isDuplexNodeStream:f,isFinished:T,isIterable:x,isReadableNodeStream:p,isReadableStream:b,isReadableEnded:I,isReadableFinished:O,isReadableErrored:D,isNodeStream:g,isWebStream:w,isWritable:N,isWritableNodeStream:y,isWritableStream:k,isWritableEnded:E,isWritableFinished:S,isWritableErrored:q,isServerRequest:V,isServerResponse:Y,willEmitClose:re,isTransformStream:m}}),yt=pe((l,e)=>{le(),ue(),ce();var t=At(),{AbortError:r,codes:s}=We(),{ERR_INVALID_ARG_TYPE:n,ERR_STREAM_PREMATURE_CLOSE:i}=s,{kEmptyObject:o,once:a}=Ge(),{validateAbortSignal:c,validateFunction:u,validateObject:h,validateBoolean:p}=Yt(),{Promise:y,PromisePrototypeThen:f,SymbolDispose:g}=Ne(),{isClosed:b,isReadable:k,isReadableNodeStream:m,isReadableStream:w,isReadableFinished:x,isReadableErrored:v,isWritable:E,isWritableNodeStream:S,isWritableStream:I,isWritableFinished:O,isWritableErrored:P,isNodeStream:N,willEmitClose:T,kIsClosedPromise:q}=ct(),D;function U(F){return F.setHeader&&typeof F.abort=="function"}var ae=()=>{};function Y(F,Z,M){var J,be;if(arguments.length===2?(M=Z,Z=o):Z==null?Z=o:h(Z,"options"),u(M,"callback"),c(Z.signal,"options.signal"),M=a(M),w(F)||I(F))return V(F,Z,M);if(!N(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),G=F._writableState,j=F._readableState,ne=()=>{F.writable||Q()},W=T(F)&&m(F)===te&&S(F)===we,K=O(F,!1),Q=()=>{K=!0,F.destroyed&&(W=!1),!(W&&(!F.readable||te))&&(!te||ge)&&M.call(F)},ge=x(F,!1),oe=()=>{ge=!0,F.destroyed&&(W=!1),!(W&&(!F.writable||we))&&(!we||K)&&M.call(F)},R=H=>{M.call(F,H)},$=b(F),ee=()=>{$=!0;let H=P(F)||v(F);if(H&&typeof H!="boolean")return M.call(F,H);if(te&&!ge&&m(F,!0)&&!x(F,!1))return M.call(F,new i);if(we&&!K&&!O(F,!1))return M.call(F,new i);M.call(F)},de=()=>{$=!0;let H=P(F)||v(F);if(H&&typeof H!="boolean")return M.call(F,H);M.call(F)},fe=()=>{F.req.on("finish",Q)};U(F)?(F.on("complete",Q),W||F.on("abort",ee),F.req?fe():F.on("request",fe)):we&&!G&&(F.on("end",ne),F.on("close",ne)),!W&&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):G!=null&&G.errorEmitted||j!=null&&j.errorEmitted?W||t.nextTick(de):(!te&&(!W||k(F))&&(K||E(F)===!1)||!we&&(!W||E(F))&&(ge||k(F)===!1)||j&&F.req&&F.aborted)&&t.nextTick(de);let ye=()=>{M=ae,F.removeListener("aborted",ee),F.removeListener("complete",Q),F.removeListener("abort",ee),F.removeListener("request",fe),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 H=()=>{let me=M;ye(),me.call(F,new r(void 0,{cause:Z.signal.reason}))};if(Z.signal.aborted)t.nextTick(H);else{D=D||Ge().addAbortListener;let me=D(Z.signal,H),ve=M;M=a((...se)=>{me[g](),ve.apply(F,se)})}}return ye}function V(F,Z,M){let J=!1,be=ae;if(Z.signal)if(be=()=>{J=!0,M.call(F,new r(void 0,{cause:Z.signal.reason}))},Z.signal.aborted)t.nextTick(be);else{D=D||Ge().addAbortListener;let we=D(Z.signal,be),G=M;M=a((...j)=>{we[g](),G.apply(F,j)})}let te=(...we)=>{J||t.nextTick(()=>M.apply(F,we))};return f(F[q].promise,te,te),ae}function re(F,Z){var M;let J=!1;return Z===null&&(Z=o),(M=Z)!==null&&M!==void 0&&M.cleanup&&(p(Z.cleanup,"cleanup"),J=Z.cleanup),new y((be,te)=>{let we=Y(F,Z,G=>{J&&we(),G?te(G):be()})})}e.exports=Y,e.exports.finished=re}),Nt=pe((l,e)=>{le(),ue(),ce();var t=At(),{aggregateTwoErrors:r,codes:{ERR_MULTIPLE_CALLBACK:s},AbortError:n}=We(),{Symbol:i}=Ne(),{kIsDestroyed:o,isDestroyed:a,isFinished:c,isServerRequest:u}=ct(),h=i("kDestroy"),p=i("kConstruct");function y(T,q,D){T&&(T.stack,q&&!q.errored&&(q.errored=T),D&&!D.errored&&(D.errored=T))}function f(T,q){let D=this._readableState,U=this._writableState,ae=U||D;return U!=null&&U.destroyed||D!=null&&D.destroyed?(typeof q=="function"&&q(),this):(y(T,U,D),U&&(U.destroyed=!0),D&&(D.destroyed=!0),ae.constructed?g(this,T,q):this.once(h,function(Y){g(this,r(Y,T),q)}),this)}function g(T,q,D){let U=!1;function ae(Y){if(U)return;U=!0;let V=T._readableState,re=T._writableState;y(Y,re,V),re&&(re.closed=!0),V&&(V.closed=!0),typeof D=="function"&&D(Y),Y?t.nextTick(b,T,Y):t.nextTick(k,T)}try{T._destroy(q||null,ae)}catch(Y){ae(Y)}}function b(T,q){m(T,q),k(T)}function k(T){let q=T._readableState,D=T._writableState;D&&(D.closeEmitted=!0),q&&(q.closeEmitted=!0),(D!=null&&D.emitClose||q!=null&&q.emitClose)&&T.emit("close")}function m(T,q){let D=T._readableState,U=T._writableState;U!=null&&U.errorEmitted||D!=null&&D.errorEmitted||(U&&(U.errorEmitted=!0),D&&(D.errorEmitted=!0),T.emit("error",q))}function w(){let T=this._readableState,q=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),q&&(q.constructed=!0,q.destroyed=!1,q.closed=!1,q.closeEmitted=!1,q.errored=null,q.errorEmitted=!1,q.finalCalled=!1,q.prefinished=!1,q.ended=q.writable===!1,q.ending=q.writable===!1,q.finished=q.writable===!1)}function x(T,q,D){let U=T._readableState,ae=T._writableState;if(ae!=null&&ae.destroyed||U!=null&&U.destroyed)return this;U!=null&&U.autoDestroy||ae!=null&&ae.autoDestroy?T.destroy(q):q&&(q.stack,ae&&!ae.errored&&(ae.errored=q),U&&!U.errored&&(U.errored=q),D?t.nextTick(m,T,q):m(T,q))}function v(T,q){if(typeof T._construct!="function")return;let D=T._readableState,U=T._writableState;D&&(D.constructed=!1),U&&(U.constructed=!1),T.once(p,q),!(T.listenerCount(p)>1)&&t.nextTick(E,T)}function E(T){let q=!1;function D(U){if(q){x(T,U??new s);return}q=!0;let ae=T._readableState,Y=T._writableState,V=Y||ae;ae&&(ae.constructed=!0),Y&&(Y.constructed=!0),V.destroyed?T.emit(h,U):U?x(T,U,!0):t.nextTick(S,T)}try{T._construct(U=>{t.nextTick(D,U)})}catch(U){t.nextTick(D,U)}}function S(T){T.emit(p)}function I(T){return T?.setHeader&&typeof T.abort=="function"}function O(T){T.emit("close")}function P(T,q){T.emit("error",q),t.nextTick(O,T)}function N(T,q){!T||a(T)||(!q&&!c(T)&&(q=new n),u(T)?(T.socket=null,T.destroy(q)):I(T)?T.abort():I(T.req)?T.req.abort():typeof T.destroy=="function"?T.destroy(q):typeof T.close=="function"?T.close():q?t.nextTick(P,T,q):t.nextTick(O,T),T.destroyed||(T[o]=!0))}e.exports={construct:v,destroyer:N,destroy:f,undestroy:w,errorOrDestroy:x}}),li=pe((l,e)=>{le(),ue(),ce();var{ArrayIsArray:t,ObjectSetPrototypeOf:r}=Ne(),{EventEmitter:s}=(Et(),Me(bt));function n(o){s.call(this,o)}r(n.prototype,s.prototype),r(n,s),n.prototype.pipe=function(o,a){let c=this;function u(k){o.writable&&o.write(k)===!1&&c.pause&&c.pause()}c.on("data",u);function h(){c.readable&&c.resume&&c.resume()}o.on("drain",h),!o._isStdio&&(!a||a.end!==!1)&&(c.on("end",y),c.on("close",f));let p=!1;function y(){p||(p=!0,o.end())}function f(){p||(p=!0,typeof o.destroy=="function"&&o.destroy())}function g(k){b(),s.listenerCount(this,"error")===0&&this.emit("error",k)}i(c,"error",g),i(o,"error",g);function b(){c.removeListener("data",u),o.removeListener("drain",h),c.removeListener("end",y),c.removeListener("close",f),c.removeListener("error",g),o.removeListener("error",g),c.removeListener("end",b),c.removeListener("close",b),o.removeListener("close",b)}return c.on("end",b),c.on("close",b),o.on("close",b),o.emit("pipe",c),o};function i(o,a,c){if(typeof o.prependListener=="function")return o.prependListener(a,c);!o._events||!o._events[a]?o.on(a,c):t(o._events[a])?o._events[a].unshift(c):o._events[a]=[c,o._events[a]]}e.exports={Stream:n,prependListener:i}}),cr=pe((l,e)=>{le(),ue(),ce();var{SymbolDispose:t}=Ne(),{AbortError:r,codes:s}=We(),{isNodeStream:n,isWebStream:i,kControllerErrorFunction:o}=ct(),a=yt(),{ERR_INVALID_ARG_TYPE:c}=s,u,h=(p,y)=>{if(typeof p!="object"||!("aborted"in p))throw new c(y,"AbortSignal",p)};e.exports.addAbortSignal=function(p,y){if(h(p,"signal"),!n(y)&&!i(y))throw new c("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[o](new r(void 0,{cause:p.reason}))};if(p.aborted)f();else{u=u||Ge().addAbortListener;let g=u(p,f);a(y,g[t])}return y}}),Oc=pe((l,e)=>{le(),ue(),ce();var{StringPrototypeSlice:t,SymbolIterator:r,TypedArrayPrototypeSet:s,Uint8Array:n}=Ne(),{Buffer:i}=(De(),Me(Be)),{inspect:o}=Ge();e.exports=class{constructor(){this.head=null,this.tail=null,this.length=0}push(a){let c={data:a,next:null};this.length>0?this.tail.next=c:this.head=c,this.tail=c,++this.length}unshift(a){let c={data:a,next:this.head};this.length===0&&(this.tail=c),this.head=c,++this.length}shift(){if(this.length===0)return;let a=this.head.data;return this.length===1?this.head=this.tail=null:this.head=this.head.next,--this.length,a}clear(){this.head=this.tail=null,this.length=0}join(a){if(this.length===0)return"";let c=this.head,u=""+c.data;for(;(c=c.next)!==null;)u+=a+c.data;return u}concat(a){if(this.length===0)return i.alloc(0);let c=i.allocUnsafe(a>>>0),u=this.head,h=0;for(;u;)s(c,u.data,h),h+=u.data.length,u=u.next;return c}consume(a,c){let u=this.head.data;if(a<u.length){let h=u.slice(0,a);return this.head.data=u.slice(a),h}return a===u.length?this.shift():c?this._getString(a):this._getBuffer(a)}first(){return this.head.data}*[r](){for(let a=this.head;a;a=a.next)yield a.data}_getString(a){let c="",u=this.head,h=0;do{let p=u.data;if(a>p.length)c+=p,a-=p.length;else{a===p.length?(c+=p,++h,u.next?this.head=u.next:this.head=this.tail=null):(c+=t(p,0,a),this.head=u,u.data=t(p,a));break}++h}while((u=u.next)!==null);return this.length-=h,c}_getBuffer(a){let c=i.allocUnsafe(a),u=a,h=this.head,p=0;do{let y=h.data;if(a>y.length)s(c,y,u-a),a-=y.length;else{a===y.length?(s(c,y,u-a),++p,h.next?this.head=h.next:this.head=this.tail=null):(s(c,new n(y.buffer,y.byteOffset,a),u-a),this.head=h,h.data=y.slice(a));break}++p}while((h=h.next)!==null);return this.length-=p,c}[Symbol.for("nodejs.util.inspect.custom")](a,c){return o(this,{...c,depth:0,customInspect:!1})}}}),ur=pe((l,e)=>{le(),ue(),ce();var{MathFloor:t,NumberIsInteger:r}=Ne(),{validateInteger:s}=Yt(),{ERR_INVALID_ARG_VALUE:n}=We().codes,i=16*1024,o=16;function a(p,y,f){return p.highWaterMark!=null?p.highWaterMark:y?p[f]:null}function c(p){return p?o:i}function u(p,y){s(y,"value",0),p?o=y:i=y}function h(p,y,f,g){let b=a(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 c(p.objectMode)}e.exports={getHighWaterMark:h,getDefaultHighWaterMark:c,setDefaultHighWaterMark:u}}),Pc=pe((l,e)=>{le(),ue(),ce();var t=(De(),Me(Be)),r=t.Buffer;function s(i,o){for(var a in i)o[a]=i[a]}r.from&&r.alloc&&r.allocUnsafe&&r.allocUnsafeSlow?e.exports=t:(s(t,l),l.Buffer=n);function n(i,o,a){return r(i,o,a)}n.prototype=Object.create(r.prototype),s(r,n),n.from=function(i,o,a){if(typeof i=="number")throw new TypeError("Argument must not be a number");return r(i,o,a)},n.alloc=function(i,o,a){if(typeof i!="number")throw new TypeError("Argument must be a number");var c=r(i);return o!==void 0?typeof a=="string"?c.fill(o,a):c.fill(o):c.fill(0),c},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(l=>{le(),ue(),ce();var e=Pc().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 s(m){var w=r(m);if(typeof w!="string"&&(e.isEncoding===t||!t(m)))throw new Error("Unknown encoding: "+m);return w||m}l.StringDecoder=n;function n(m){this.encoding=s(m);var w;switch(this.encoding){case"utf16le":this.text=p,this.end=y,w=4;break;case"utf8":this.fillLast=c,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,x;if(this.lastNeed){if(w=this.fillLast(m),w===void 0)return"";x=this.lastNeed,this.lastNeed=0}else x=0;return x<m.length?w?w+this.text(m,x):this.text(m,x):w||""},n.prototype.end=h,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 o(m,w,x){var v=w.length-1;if(v<x)return 0;var E=i(w[v]);return E>=0?(E>0&&(m.lastNeed=E-1),E):--v<x||E===-2?0:(E=i(w[v]),E>=0?(E>0&&(m.lastNeed=E-2),E):--v<x||E===-2?0:(E=i(w[v]),E>=0?(E>0&&(E===2?E=0:m.lastNeed=E-3),E):0))}function a(m,w,x){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 c(m){var w=this.lastTotal-this.lastNeed,x=a(this,m);if(x!==void 0)return x;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 x=o(this,m,w);if(!this.lastNeed)return m.toString("utf8",w);this.lastTotal=x;var v=m.length-(x-this.lastNeed);return m.copy(this.lastChar,0,v),m.toString("utf8",w,v)}function h(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 x=m.toString("utf16le",w);if(x){var v=x.charCodeAt(x.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],x.slice(0,-1)}return x}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 x=this.lastTotal-this.lastNeed;return w+this.lastChar.toString("utf16le",0,x)}return w}function f(m,w){var x=(m.length-w)%3;return x===0?m.toString("base64",w):(this.lastNeed=3-x,this.lastTotal=3,x===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-x))}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):""}}),Zo=pe((l,e)=>{le(),ue(),ce();var t=At(),{PromisePrototypeThen:r,SymbolAsyncIterator:s,SymbolIterator:n}=Ne(),{Buffer:i}=(De(),Me(Be)),{ERR_INVALID_ARG_TYPE:o,ERR_STREAM_NULL_VALUES:a}=We().codes;function c(u,h,p){let y;if(typeof h=="string"||h instanceof i)return new u({objectMode:!0,...p,read(){this.push(h),this.push(null)}});let f;if(h&&h[s])f=!0,y=h[s]();else if(h&&h[n])f=!1,y=h[n]();else throw new o("iterable",["Iterable"],h);let g=new u({objectMode:!0,highWaterMark:1,...p}),b=!1;g._read=function(){b||(b=!0,m())},g._destroy=function(w,x){r(k(w),()=>t.nextTick(x,w),v=>t.nextTick(x,v||w))};async function k(w){let x=w!=null,v=typeof y.throw=="function";if(x&&v){let{value:E,done:S}=await y.throw(w);if(await E,S)return}if(typeof y.return=="function"){let{value:E}=await y.return();await E}}async function m(){for(;;){try{let{value:w,done:x}=f?await y.next():y.next();if(x)g.push(null);else{let v=w&&typeof w.then=="function"?await w:w;if(v===null)throw b=!1,new a;if(g.push(v))continue;b=!1}}catch(w){g.destroy(w)}break}}return g}e.exports=c}),hr=pe((l,e)=>{le(),ue(),ce();var t=At(),{ArrayPrototypeIndexOf:r,NumberIsInteger:s,NumberIsNaN:n,NumberParseInt:i,ObjectDefineProperties:o,ObjectKeys:a,ObjectSetPrototypeOf:c,Promise:u,SafeSet:h,SymbolAsyncDispose:p,SymbolAsyncIterator:y,Symbol:f}=Ne();e.exports=se,se.ReadableState=ve;var{EventEmitter:g}=(Et(),Me(bt)),{Stream:b,prependListener:k}=li(),{Buffer:m}=(De(),Me(Be)),{addAbortSignal:w}=cr(),x=yt(),v=Ge().debuglog("stream",C=>{v=C}),E=Oc(),S=Nt(),{getHighWaterMark:I,getDefaultHighWaterMark:O}=ur(),{aggregateTwoErrors:P,codes:{ERR_INVALID_ARG_TYPE:N,ERR_METHOD_NOT_IMPLEMENTED:T,ERR_OUT_OF_RANGE:q,ERR_STREAM_PUSH_AFTER_EOF:D,ERR_STREAM_UNSHIFT_AFTER_END_EVENT:U},AbortError:ae}=We(),{validateObject:Y}=Yt(),V=f("kPaused"),{StringDecoder:re}=Mc(),F=Zo();c(se.prototype,b.prototype),c(se,b);var Z=()=>{},{errorOrDestroy:M}=S,J=1,be=2,te=4,we=8,G=16,j=32,ne=64,W=128,K=256,Q=512,ge=1024,oe=2048,R=4096,$=8192,ee=16384,de=32768,fe=65536,ye=1<<17,H=1<<18;function me(C){return{enumerable:!1,get(){return(this.state&C)!==0},set(L){L?this.state|=C:this.state&=~C}}}o(ve.prototype,{objectMode:me(J),ended:me(be),endEmitted:me(te),reading:me(we),constructed:me(G),sync:me(j),needReadable:me(ne),emittedReadable:me(W),readableListening:me(K),resumeScheduled:me(Q),errorEmitted:me(ge),emitClose:me(oe),autoDestroy:me(R),destroyed:me($),closed:me(ee),closeEmitted:me(de),multiAwaitDrain:me(fe),readingMore:me(ye),dataEmitted:me(H)});function ve(C,L,_e){typeof _e!="boolean"&&(_e=L instanceof ut()),this.state=oe|R|G|j,C&&C.objectMode&&(this.state|=J),_e&&C&&C.readableObjectMode&&(this.state|=J),this.highWaterMark=C?I(this,C,"readableHighWaterMark",_e):O(!1),this.buffer=new E,this.length=0,this.pipes=[],this.flowing=null,this[V]=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 L=this instanceof ut();this._readableState=new ve(C,this,L),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&&!L&&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,L){L(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((L,_e)=>x(this,xe=>xe&&xe!==C?_e(xe):L(null)))},se.prototype.push=function(C,L){return Te(this,C,L,!1)},se.prototype.unshift=function(C,L){return Te(this,C,L,!0)};function Te(C,L,_e,xe){v("readableAddChunk",L);let Se=C._readableState,Ue;if((Se.state&J)===0&&(typeof L=="string"?(_e=_e||Se.defaultEncoding,Se.encoding!==_e&&(xe&&Se.encoding?L=m.from(L,_e).toString(Se.encoding):(L=m.from(L,_e),_e=""))):L instanceof m?_e="":b._isUint8Array(L)?(L=b._uint8ArrayToBuffer(L),_e=""):L!=null&&(Ue=new N("chunk",["string","Buffer","Uint8Array"],L))),Ue)M(C,Ue);else if(L===null)Se.state&=~we,X(C,Se);else if((Se.state&J)!==0||L&&L.length>0)if(xe)if((Se.state&te)!==0)M(C,new U);else{if(Se.destroyed||Se.errored)return!1;d(C,Se,L,!0)}else if(Se.ended)M(C,new D);else{if(Se.destroyed||Se.errored)return!1;Se.state&=~we,Se.decoder&&!_e?(L=Se.decoder.write(L),Se.objectMode||L.length!==0?d(C,Se,L,!1):z(C,Se)):d(C,Se,L,!1)}else xe||(Se.state&=~we,z(C,Se));return!Se.ended&&(Se.length<Se.highWaterMark||Se.length===0)}function d(C,L,_e,xe){L.flowing&&L.length===0&&!L.sync&&C.listenerCount("data")>0?((L.state&fe)!==0?L.awaitDrainWriters.clear():L.awaitDrainWriters=null,L.dataEmitted=!0,C.emit("data",_e)):(L.length+=L.objectMode?1:_e.length,xe?L.buffer.unshift(_e):L.buffer.push(_e),(L.state&ne)!==0&&he(C)),z(C,L)}se.prototype.isPaused=function(){let C=this._readableState;return C[V]===!0||C.flowing===!1},se.prototype.setEncoding=function(C){let L=new re(C);this._readableState.decoder=L,this._readableState.encoding=this._readableState.decoder.encoding;let _e=this._readableState.buffer,xe="";for(let Se of _e)xe+=L.write(Se);return _e.clear(),xe!==""&&_e.push(xe),this._readableState.length=xe.length,this};var _=1073741824;function A(C){if(C>_)throw new q("size","<= 1GiB",C);return C--,C|=C>>>1,C|=C>>>2,C|=C>>>4,C|=C>>>8,C|=C>>>16,C++,C}function B(C,L){return C<=0||L.length===0&&L.ended?0:(L.state&J)!==0?1:n(C)?L.flowing&&L.length?L.buffer.first().length:L.length:C<=L.length?C:L.ended?L.length:0}se.prototype.read=function(C){v("read",C),C===void 0?C=NaN:s(C)||(C=i(C,10));let L=this._readableState,_e=C;if(C>L.highWaterMark&&(L.highWaterMark=A(C)),C!==0&&(L.state&=~W),C===0&&L.needReadable&&((L.highWaterMark!==0?L.length>=L.highWaterMark:L.length>0)||L.ended))return v("read: emitReadable",L.length,L.ended),L.length===0&&L.ended?nt(this):he(this),null;if(C=B(C,L),C===0&&L.ended)return L.length===0&&nt(this),null;let xe=(L.state&ne)!==0;if(v("need readable",xe),(L.length===0||L.length-C<L.highWaterMark)&&(xe=!0,v("length less than watermark",xe)),L.ended||L.reading||L.destroyed||L.errored||!L.constructed)xe=!1,v("reading, ended or constructing",xe);else if(xe){v("do read"),L.state|=we|j,L.length===0&&(L.state|=ne);try{this._read(L.highWaterMark)}catch(Ue){M(this,Ue)}L.state&=~j,L.reading||(C=B(_e,L))}let Se;return C>0?Se=qt(C,L):Se=null,Se===null?(L.needReadable=L.length<=L.highWaterMark,C=0):(L.length-=C,L.multiAwaitDrain?L.awaitDrainWriters.clear():L.awaitDrainWriters=null),L.length===0&&(L.ended||(L.needReadable=!0),_e!==C&&L.ended&&nt(this)),Se!==null&&!L.errorEmitted&&!L.closeEmitted&&(L.dataEmitted=!0,this.emit("data",Se)),Se};function X(C,L){if(v("onEofChunk"),!L.ended){if(L.decoder){let _e=L.decoder.end();_e&&_e.length&&(L.buffer.push(_e),L.length+=L.objectMode?1:_e.length)}L.ended=!0,L.sync?he(C):(L.needReadable=!1,L.emittedReadable=!0,ke(C))}}function he(C){let L=C._readableState;v("emitReadable",L.needReadable,L.emittedReadable),L.needReadable=!1,L.emittedReadable||(v("emitReadable",L.flowing),L.emittedReadable=!0,t.nextTick(ke,C))}function ke(C){let L=C._readableState;v("emitReadable_",L.destroyed,L.length,L.ended),!L.destroyed&&!L.errored&&(L.length||L.ended)&&(C.emit("readable"),L.emittedReadable=!1),L.needReadable=!L.flowing&&!L.ended&&L.length<=L.highWaterMark,tt(C)}function z(C,L){!L.readingMore&&L.constructed&&(L.readingMore=!0,t.nextTick(ie,C,L))}function ie(C,L){for(;!L.reading&&!L.ended&&(L.length<L.highWaterMark||L.flowing&&L.length===0);){let _e=L.length;if(v("maybeReadMore read 0"),C.read(0),_e===L.length)break}L.readingMore=!1}se.prototype._read=function(C){throw new T("_read()")},se.prototype.pipe=function(C,L){let _e=this,xe=this._readableState;xe.pipes.length===1&&(xe.multiAwaitDrain||(xe.multiAwaitDrain=!0,xe.awaitDrainWriters=new h(xe.awaitDrainWriters?[xe.awaitDrainWriters]:[]))),xe.pipes.push(C),v("pipe count=%d opts=%j",xe.pipes.length,L);let Se=(!L||L.end!==!1)&&C!==t.stdout&&C!==t.stderr?ze:Mt;xe.endEmitted?t.nextTick(Se):_e.once("end",Se),C.on("unpipe",Ue);function Ue(ot,mt){v("onunpipe"),ot===_e&&mt&&mt.hasUnpiped===!1&&(mt.hasUnpiped=!0,tr())}function ze(){v("onend"),C.end()}let Je,er=!1;function tr(){v("cleanup"),C.removeListener("close",it),C.removeListener("finish",kt),Je&&C.removeListener("drain",Je),C.removeListener("error",Pt),C.removeListener("unpipe",Ue),_e.removeListener("end",ze),_e.removeListener("end",Mt),_e.removeListener("data",Vr),er=!0,Je&&xe.awaitDrainWriters&&(!C._writableState||C._writableState.needDrain)&&Je()}function rr(){er||(xe.pipes.length===1&&xe.pipes[0]===C?(v("false write response, pause",0),xe.awaitDrainWriters=C,xe.multiAwaitDrain=!1):xe.pipes.length>1&&xe.pipes.includes(C)&&(v("false write response, pause",xe.awaitDrainWriters.size),xe.awaitDrainWriters.add(C)),_e.pause()),Je||(Je=Ee(_e,C),C.on("drain",Je))}_e.on("data",Vr);function Vr(ot){v("ondata");let mt=C.write(ot);v("dest.write",mt),mt===!1&&rr()}function Pt(ot){if(v("onerror",ot),Mt(),C.removeListener("error",Pt),C.listenerCount("error")===0){let mt=C._writableState||C._readableState;mt&&!mt.errorEmitted?M(C,ot):C.emit("error",ot)}}k(C,"error",Pt);function it(){C.removeListener("finish",kt),Mt()}C.once("close",it);function kt(){v("onfinish"),C.removeListener("close",it),Mt()}C.once("finish",kt);function Mt(){v("unpipe"),_e.unpipe(C)}return C.emit("pipe",_e),C.writableNeedDrain===!0?rr():xe.flowing||(v("pipe resume"),_e.resume()),C};function Ee(C,L){return function(){let _e=C._readableState;_e.awaitDrainWriters===L?(v("pipeOnDrain",1),_e.awaitDrainWriters=null):_e.multiAwaitDrain&&(v("pipeOnDrain",_e.awaitDrainWriters.size),_e.awaitDrainWriters.delete(L)),(!_e.awaitDrainWriters||_e.awaitDrainWriters.size===0)&&C.listenerCount("data")&&C.resume()}}se.prototype.unpipe=function(C){let L=this._readableState,_e={hasUnpiped:!1};if(L.pipes.length===0)return this;if(!C){let Se=L.pipes;L.pipes=[],this.pause();for(let Ue=0;Ue<Se.length;Ue++)Se[Ue].emit("unpipe",this,{hasUnpiped:!1});return this}let xe=r(L.pipes,C);return xe===-1?this:(L.pipes.splice(xe,1),L.pipes.length===0&&this.pause(),C.emit("unpipe",this,_e),this)},se.prototype.on=function(C,L){let _e=b.prototype.on.call(this,C,L),xe=this._readableState;return C==="data"?(xe.readableListening=this.listenerCount("readable")>0,xe.flowing!==!1&&this.resume()):C==="readable"&&!xe.endEmitted&&!xe.readableListening&&(xe.readableListening=xe.needReadable=!0,xe.flowing=!1,xe.emittedReadable=!1,v("on readable",xe.length,xe.reading),xe.length?he(this):xe.reading||t.nextTick(Ie,this)),_e},se.prototype.addListener=se.prototype.on,se.prototype.removeListener=function(C,L){let _e=b.prototype.removeListener.call(this,C,L);return C==="readable"&&t.nextTick(Ae,this),_e},se.prototype.off=se.prototype.removeListener,se.prototype.removeAllListeners=function(C){let L=b.prototype.removeAllListeners.apply(this,arguments);return(C==="readable"||C===void 0)&&t.nextTick(Ae,this),L};function Ae(C){let L=C._readableState;L.readableListening=C.listenerCount("readable")>0,L.resumeScheduled&&L[V]===!1?L.flowing=!0:C.listenerCount("data")>0?C.resume():L.readableListening||(L.flowing=null)}function Ie(C){v("readable nexttick read 0"),C.read(0)}se.prototype.resume=function(){let C=this._readableState;return C.flowing||(v("resume"),C.flowing=!C.readableListening,Oe(this,C)),C[V]=!1,this};function Oe(C,L){L.resumeScheduled||(L.resumeScheduled=!0,t.nextTick(et,C,L))}function et(C,L){v("resume",L.reading),L.reading||C.read(0),L.resumeScheduled=!1,C.emit("resume"),tt(C),L.flowing&&!L.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[V]=!0,this};function tt(C){let L=C._readableState;for(v("flow",L.flowing);L.flowing&&C.read()!==null;);}se.prototype.wrap=function(C){let L=!1;C.on("data",xe=>{!this.push(xe)&&C.pause&&(L=!0,C.pause())}),C.on("end",()=>{this.push(null)}),C.on("error",xe=>{M(this,xe)}),C.on("close",()=>{this.destroy()}),C.on("destroy",()=>{this.destroy()}),this._read=()=>{L&&C.resume&&(L=!1,C.resume())};let _e=a(C);for(let xe=1;xe<_e.length;xe++){let Se=_e[xe];this[Se]===void 0&&typeof C[Se]=="function"&&(this[Se]=C[Se].bind(C))}return this},se.prototype[y]=function(){return He(this)},se.prototype.iterator=function(C){return C!==void 0&&Y(C,"options"),He(this,C)};function He(C,L){typeof C.read!="function"&&(C=se.wrap(C,{objectMode:!0}));let _e=rt(C,L);return _e.stream=C,_e}async function*rt(C,L){let _e=Z;function xe(ze){this===C?(_e(),_e=Z):_e=ze}C.on("readable",xe);let Se,Ue=x(C,{writable:!1},ze=>{Se=ze?P(Se,ze):null,_e(),_e=Z});try{for(;;){let ze=C.destroyed?null:C.read();if(ze!==null)yield ze;else{if(Se)throw Se;if(Se===null)return;await new u(xe)}}}catch(ze){throw Se=P(Se,ze),Se}finally{(Se||L?.destroyOnReturn!==!1)&&(Se===void 0||C._readableState.autoDestroy)?S.destroyer(C,null):(C.off("readable",xe),Ue())}}o(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}}}),o(ve.prototype,{pipesCount:{__proto__:null,get(){return this.pipes.length}},paused:{__proto__:null,get(){return this[V]!==!1},set(C){this[V]=!!C}}}),se._fromList=qt;function qt(C,L){if(L.length===0)return null;let _e;return L.objectMode?_e=L.buffer.shift():!C||C>=L.length?(L.decoder?_e=L.buffer.join(""):L.buffer.length===1?_e=L.buffer.first():_e=L.buffer.concat(L.length),L.buffer.clear()):_e=L.buffer.consume(C,L.decoder),_e}function nt(C){let L=C._readableState;v("endReadable",L.endEmitted),L.endEmitted||(L.ended=!0,t.nextTick(Ye,L,C))}function Ye(C,L){if(v("endReadableNT",C.endEmitted,C.length),!C.errored&&!C.closeEmitted&&!C.endEmitted&&C.length===0){if(C.endEmitted=!0,L.emit("end"),L.writable&&L.allowHalfOpen===!1)t.nextTick(zr,L);else if(C.autoDestroy){let _e=L._writableState;(!_e||_e.autoDestroy&&(_e.finished||_e.writable===!1))&&L.destroy()}}}function zr(C){C.writable&&!C.writableEnded&&!C.destroyed&&C.end()}se.from=function(C,L){return F(se,C,L)};var Ht;function Zt(){return Ht===void 0&&(Ht={}),Ht}se.fromWeb=function(C,L){return Zt().newStreamReadableFromReadableStream(C,L)},se.toWeb=function(C,L){return Zt().newReadableStreamFromStreamReadable(C,L)},se.wrap=function(C,L){var _e,xe;return new se({objectMode:(_e=(xe=C.readableObjectMode)!==null&&xe!==void 0?xe:C.objectMode)!==null&&_e!==void 0?_e:!0,...L,destroy(Se,Ue){S.destroyer(C,Se),Ue(Se)}}).wrap(C)}}),ci=pe((l,e)=>{le(),ue(),ce();var t=At(),{ArrayPrototypeSlice:r,Error:s,FunctionPrototypeSymbolHasInstance:n,ObjectDefineProperty:i,ObjectDefineProperties:o,ObjectSetPrototypeOf:a,StringPrototypeToLowerCase:c,Symbol:u,SymbolHasInstance:h}=Ne();e.exports=Y,Y.WritableState=U;var{EventEmitter:p}=(Et(),Me(bt)),y=li().Stream,{Buffer:f}=(De(),Me(Be)),g=Nt(),{addAbortSignal:b}=cr(),{getHighWaterMark:k,getDefaultHighWaterMark:m}=ur(),{ERR_INVALID_ARG_TYPE:w,ERR_METHOD_NOT_IMPLEMENTED:x,ERR_MULTIPLE_CALLBACK:v,ERR_STREAM_CANNOT_PIPE:E,ERR_STREAM_DESTROYED:S,ERR_STREAM_ALREADY_FINISHED:I,ERR_STREAM_NULL_VALUES:O,ERR_STREAM_WRITE_AFTER_END:P,ERR_UNKNOWN_ENCODING:N}=We().codes,{errorOrDestroy:T}=g;a(Y.prototype,y.prototype),a(Y,y);function q(){}var D=u("kOnFinished");function U(R,$,ee){typeof ee!="boolean"&&(ee=$ instanceof ut()),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 de=!!(R&&R.decodeStrings===!1);this.decodeStrings=!de,this.defaultEncoding=R&&R.defaultEncoding||"utf8",this.length=0,this.writing=!1,this.corked=0,this.sync=!0,this.bufferProcessing=!1,this.onwrite=M.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}U.prototype.getBuffer=function(){return r(this.buffered,this.bufferedIndex)},i(U.prototype,"bufferedRequestCount",{__proto__:null,get(){return this.buffered.length-this.bufferedIndex}});function Y(R){let $=this instanceof ut();if(!$&&!n(Y,this))return new Y(R);this._writableState=new U(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),W(this,ee)})}i(Y,h,{__proto__:null,value:function(R){return n(this,R)?!0:this!==Y?!1:R&&R._writableState instanceof U}}),Y.prototype.pipe=function(){T(this,new E)};function V(R,$,ee,de){let fe=R._writableState;if(typeof ee=="function")de=ee,ee=fe.defaultEncoding;else{if(!ee)ee=fe.defaultEncoding;else if(ee!=="buffer"&&!f.isEncoding(ee))throw new N(ee);typeof de!="function"&&(de=q)}if($===null)throw new O;if(!fe.objectMode)if(typeof $=="string")fe.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 fe.ending?ye=new P:fe.destroyed&&(ye=new S("write")),ye?(t.nextTick(de,ye),T(R,ye,!0),ye):(fe.pendingcb++,re(R,fe,$,ee,de))}Y.prototype.write=function(R,$,ee){return V(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=c(R)),!f.isEncoding(R))throw new N(R);return this._writableState.defaultEncoding=R,this};function re(R,$,ee,de,fe){let ye=$.objectMode?1:ee.length;$.length+=ye;let H=$.length<$.highWaterMark;return H||($.needDrain=!0),$.writing||$.corked||$.errored||!$.constructed?($.buffered.push({chunk:ee,encoding:de,callback:fe}),$.allBuffers&&de!=="buffer"&&($.allBuffers=!1),$.allNoop&&fe!==q&&($.allNoop=!1)):($.writelen=ye,$.writecb=fe,$.writing=!0,$.sync=!0,R._write(ee,de,$.onwrite),$.sync=!1),H&&!$.errored&&!$.destroyed}function F(R,$,ee,de,fe,ye,H){$.writelen=de,$.writecb=H,$.writing=!0,$.sync=!0,$.destroyed?$.onwrite(new S("write")):ee?R._writev(fe,$.onwrite):R._write(fe,ye,$.onwrite),$.sync=!1}function Z(R,$,ee,de){--$.pendingcb,de(ee),te($),T(R,ee)}function M(R,$){let ee=R._writableState,de=ee.sync,fe=ee.writecb;if(typeof fe!="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=$),de?t.nextTick(Z,R,ee,$,fe):Z(R,ee,$,fe)):(ee.buffered.length>ee.bufferedIndex&&we(R,ee),de?ee.afterWriteTickInfo!==null&&ee.afterWriteTickInfo.cb===fe?ee.afterWriteTickInfo.count++:(ee.afterWriteTickInfo={count:1,cb:fe,stream:R,state:ee},t.nextTick(J,ee.afterWriteTickInfo)):be(R,ee,1,fe))}function J({stream:R,state:$,count:ee,cb:de}){return $.afterWriteTickInfo=null,be(R,$,ee,de)}function be(R,$,ee,de){for(!$.ending&&!R.destroyed&&$.length===0&&$.needDrain&&($.needDrain=!1,R.emit("drain"));ee-- >0;)$.pendingcb--,de();$.destroyed&&te($),W(R,$)}function te(R){if(R.writing)return;for(let fe=R.bufferedIndex;fe<R.buffered.length;++fe){var $;let{chunk:ye,callback:H}=R.buffered[fe],me=R.objectMode?1:ye.length;R.length-=me,H(($=R.errored)!==null&&$!==void 0?$:new S("write"))}let ee=R[D].splice(0);for(let fe=0;fe<ee.length;fe++){var de;ee[fe]((de=R.errored)!==null&&de!==void 0?de:new S("end"))}ae(R)}function we(R,$){if($.corked||$.bufferProcessing||$.destroyed||!$.constructed)return;let{buffered:ee,bufferedIndex:de,objectMode:fe}=$,ye=ee.length-de;if(!ye)return;let H=de;if($.bufferProcessing=!0,ye>1&&R._writev){$.pendingcb-=ye-1;let me=$.allNoop?q:se=>{for(let Te=H;Te<ee.length;++Te)ee[Te].callback(se)},ve=$.allNoop&&H===0?ee:r(ee,H);ve.allBuffers=$.allBuffers,F(R,$,!0,$.length,ve,"",me),ae($)}else{do{let{chunk:me,encoding:ve,callback:se}=ee[H];ee[H++]=null;let Te=fe?1:me.length;F(R,$,!1,Te,me,ve,se)}while(H<ee.length&&!$.writing);H===ee.length?ae($):H>256?(ee.splice(0,H),$.bufferedIndex=0):$.bufferedIndex=H}$.bufferProcessing=!1}Y.prototype._write=function(R,$,ee){if(this._writev)this._writev([{chunk:R,encoding:$}],ee);else throw new x("_write()")},Y.prototype._writev=null,Y.prototype.end=function(R,$,ee){let de=this._writableState;typeof R=="function"?(ee=R,R=null,$=null):typeof $=="function"&&(ee=$,$=null);let fe;if(R!=null){let ye=V(this,R,$);ye instanceof s&&(fe=ye)}return de.corked&&(de.corked=1,this.uncork()),fe||(!de.errored&&!de.ending?(de.ending=!0,W(this,de,!0),de.ended=!0):de.finished?fe=new I("end"):de.destroyed&&(fe=new S("end"))),typeof ee=="function"&&(fe||de.finished?t.nextTick(ee,fe):de[D].push(ee)),this};function G(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 j(R,$){let ee=!1;function de(fe){if(ee){T(R,fe??v());return}if(ee=!0,$.pendingcb--,fe){let ye=$[D].splice(0);for(let H=0;H<ye.length;H++)ye[H](fe);T(R,fe,$.sync)}else G($)&&($.prefinished=!0,R.emit("prefinish"),$.pendingcb++,t.nextTick(K,R,$))}$.sync=!0,$.pendingcb++;try{R._final(de)}catch(fe){de(fe)}$.sync=!1}function ne(R,$){!$.prefinished&&!$.finalCalled&&(typeof R._final=="function"&&!$.destroyed?($.finalCalled=!0,j(R,$)):($.prefinished=!0,R.emit("prefinish")))}function W(R,$,ee){G($)&&(ne(R,$),$.pendingcb===0&&(ee?($.pendingcb++,t.nextTick((de,fe)=>{G(fe)?K(de,fe):fe.pendingcb--},R,$)):G($)&&($.pendingcb++,K(R,$))))}function K(R,$){$.pendingcb--,$.finished=!0;let ee=$[D].splice(0);for(let de=0;de<ee.length;de++)ee[de]();if(R.emit("finish"),$.autoDestroy){let de=R._readableState;(!de||de.autoDestroy&&(de.endEmitted||de.readable===!1))&&R.destroy()}}o(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 ge;function oe(){return ge===void 0&&(ge={}),ge}Y.fromWeb=function(R,$){return oe().newStreamWritableFromWritableStream(R,$)},Y.toWeb=function(R){return oe().newWritableStreamFromStreamWritable(R)}}),Rc=pe((l,e)=>{le(),ue(),ce();var t=At(),r=(De(),Me(Be)),{isReadable:s,isWritable:n,isIterable:i,isNodeStream:o,isReadableNodeStream:a,isWritableNodeStream:c,isDuplexNodeStream:u,isReadableStream:h,isWritableStream:p}=ct(),y=yt(),{AbortError:f,codes:{ERR_INVALID_ARG_TYPE:g,ERR_INVALID_RETURN_VALUE:b}}=We(),{destroyer:k}=Nt(),m=ut(),w=hr(),x=ci(),{createDeferredPromise:v}=Ge(),E=Zo(),S=globalThis.Blob||r.Blob,I=typeof S<"u"?function(D){return D instanceof S}:function(D){return!1},O=globalThis.AbortController||Gt().AbortController,{FunctionPrototypeCall:P}=Ne(),N=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(U,ae){if(u(U))return U;if(a(U))return q({readable:U});if(c(U))return q({writable:U});if(o(U))return q({writable:!1,readable:!1});if(h(U))return q({readable:w.fromWeb(U)});if(p(U))return q({writable:x.fromWeb(U)});if(typeof U=="function"){let{value:V,write:re,final:F,destroy:Z}=T(U);if(i(V))return E(N,V,{objectMode:!0,write:re,final:F,destroy:Z});let M=V?.then;if(typeof M=="function"){let J,be=P(M,V,te=>{if(te!=null)throw new b("nully","body",te)},te=>{k(J,te)});return J=new N({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,V)}if(I(U))return D(U.arrayBuffer());if(i(U))return E(N,U,{objectMode:!0,writable:!1});if(h(U?.readable)&&p(U?.writable))return N.fromWeb(U);if(typeof U?.writable=="object"||typeof U?.readable=="object"){let V=U!=null&&U.readable?a(U?.readable)?U?.readable:D(U.readable):void 0,re=U!=null&&U.writable?c(U?.writable)?U?.writable:D(U.writable):void 0;return q({readable:V,writable:re})}let Y=U?.then;if(typeof Y=="function"){let V;return P(Y,U,re=>{re!=null&&V.push(re),V.push(null)},re=>{k(V,re)}),V=new N({objectMode:!0,writable:!1,read(){}})}throw new g(ae,["Blob","ReadableStream","WritableStream","Stream","Iterable","AsyncIterable","Function","{ readable, writable } pair","Promise"],U)};function T(D){let{promise:U,resolve:ae}=v(),Y=new O,V=Y.signal;return{value:D((async function*(){for(;;){let re=U;U=null;let{chunk:F,done:Z,cb:M}=await re;if(t.nextTick(M),Z)return;if(V.aborted)throw new f(void 0,{cause:V.reason});({promise:U,resolve:ae}=v()),yield F}})(),{signal:V}),write(re,F,Z){let M=ae;ae=null,M({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 q(D){let U=D.readable&&typeof D.readable.read!="function"?w.wrap(D.readable):D.readable,ae=D.writable,Y=!!s(U),V=!!n(ae),re,F,Z,M,J;function be(te){let we=M;M=null,we?we(te):te&&J.destroy(te)}return J=new N({readableObjectMode:!!(U!=null&&U.readableObjectMode),writableObjectMode:!!(ae!=null&&ae.writableObjectMode),readable:Y,writable:V}),V&&(y(ae,te=>{V=!1,te&&k(U,te),be(te)}),J._write=function(te,we,G){ae.write(te,we)?G():re=G},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(U,te=>{Y=!1,te&&k(U,te),be(te)}),U.on("readable",function(){if(Z){let te=Z;Z=null,te()}}),U.on("end",function(){J.push(null)}),J._read=function(){for(;;){let te=U.read();if(te===null){Z=J._read;return}if(!J.push(te))return}}),J._destroy=function(te,we){!te&&M!==null&&(te=new f),Z=null,re=null,F=null,M===null?we(te):(M=we,k(ae,te),k(U,te))},J}}),ut=pe((l,e)=>{le(),ue(),ce();var{ObjectDefineProperties:t,ObjectGetOwnPropertyDescriptor:r,ObjectKeys:s,ObjectSetPrototypeOf:n}=Ne();e.exports=a;var i=hr(),o=ci();n(a.prototype,i.prototype),n(a,i);{let p=s(o.prototype);for(let y=0;y<p.length;y++){let f=p[y];a.prototype[f]||(a.prototype[f]=o.prototype[f])}}function a(p){if(!(this instanceof a))return new a(p);i.call(this,p),o.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(a.prototype,{writable:{__proto__:null,...r(o.prototype,"writable")},writableHighWaterMark:{__proto__:null,...r(o.prototype,"writableHighWaterMark")},writableObjectMode:{__proto__:null,...r(o.prototype,"writableObjectMode")},writableBuffer:{__proto__:null,...r(o.prototype,"writableBuffer")},writableLength:{__proto__:null,...r(o.prototype,"writableLength")},writableFinished:{__proto__:null,...r(o.prototype,"writableFinished")},writableCorked:{__proto__:null,...r(o.prototype,"writableCorked")},writableEnded:{__proto__:null,...r(o.prototype,"writableEnded")},writableNeedDrain:{__proto__:null,...r(o.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 c;function u(){return c===void 0&&(c={}),c}a.fromWeb=function(p,y){return u().newStreamDuplexFromReadableWritablePair(p,y)},a.toWeb=function(p){return u().newReadableWritablePairFromDuplex(p)};var h;a.from=function(p){return h||(h=Rc()),h(p,"body")}}),es=pe((l,e)=>{le(),ue(),ce();var{ObjectSetPrototypeOf:t,Symbol:r}=Ne();e.exports=a;var{ERR_METHOD_NOT_IMPLEMENTED:s}=We().codes,n=ut(),{getHighWaterMark:i}=ur();t(a.prototype,n.prototype),t(a,n);var o=r("kCallback");function a(h){if(!(this instanceof a))return new a(h);let p=h?i(this,h,"readableHighWaterMark",!0):null;p===0&&(h={...h,highWaterMark:null,readableHighWaterMark:p,writableHighWaterMark:h.writableHighWaterMark||0}),n.call(this,h),this._readableState.sync=!1,this[o]=null,h&&(typeof h.transform=="function"&&(this._transform=h.transform),typeof h.flush=="function"&&(this._flush=h.flush)),this.on("prefinish",u)}function c(h){typeof this._flush=="function"&&!this.destroyed?this._flush((p,y)=>{if(p){h?h(p):this.destroy(p);return}y!=null&&this.push(y),this.push(null),h&&h()}):(this.push(null),h&&h())}function u(){this._final!==c&&c.call(this)}a.prototype._final=c,a.prototype._transform=function(h,p,y){throw new s("_transform()")},a.prototype._write=function(h,p,y){let f=this._readableState,g=this._writableState,b=f.length;this._transform(h,p,(k,m)=>{if(k){y(k);return}m!=null&&this.push(m),g.ended||b===f.length||f.length<f.highWaterMark?y():this[o]=y})},a.prototype._read=function(){if(this[o]){let h=this[o];this[o]=null,h()}}}),ts=pe((l,e)=>{le(),ue(),ce();var{ObjectSetPrototypeOf:t}=Ne();e.exports=s;var r=es();t(s.prototype,r.prototype),t(s,r);function s(n){if(!(this instanceof s))return new s(n);r.call(this,n)}s.prototype._transform=function(n,i,o){o(null,n)}}),ui=pe((l,e)=>{le(),ue(),ce();var t=At(),{ArrayIsArray:r,Promise:s,SymbolAsyncIterator:n,SymbolDispose:i}=Ne(),o=yt(),{once:a}=Ge(),c=Nt(),u=ut(),{aggregateTwoErrors:h,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}=Yt(),{isIterable:x,isReadable:v,isReadableNodeStream:E,isNodeStream:S,isTransformStream:I,isWebStream:O,isReadableStream:P,isReadableFinished:N}=ct(),T=globalThis.AbortController||Gt().AbortController,q,D,U;function ae(te,we,G){let j=!1;te.on("close",()=>{j=!0});let ne=o(te,{readable:we,writable:G},W=>{j=!W});return{destroy:W=>{j||(j=!0,c.destroyer(te,W||new g("pipe")))},cleanup:ne}}function Y(te){return m(te[te.length-1],"streams[stream.length - 1]"),te.pop()}function V(te){if(x(te))return te;if(E(te))return re(te);throw new p("val",["Readable","Iterable","AsyncIterable"],te)}async function*re(te){D||(D=hr()),yield*D.prototype[n].call(te)}async function F(te,we,G,{end:j}){let ne,W=null,K=oe=>{if(oe&&(ne=oe),W){let R=W;W=null,R()}},Q=()=>new s((oe,R)=>{ne?R(ne):W=()=>{ne?R(ne):oe()}});we.on("drain",K);let ge=o(we,{readable:!1},K);try{we.writableNeedDrain&&await Q();for await(let oe of te)we.write(oe)||await Q();j&&(we.end(),await Q()),G()}catch(oe){G(ne!==oe?h(ne,oe):oe)}finally{ge(),we.off("drain",K)}}async function Z(te,we,G,{end:j}){I(we)&&(we=we.writable);let ne=we.getWriter();try{for await(let W of te)await ne.ready,ne.write(W).catch(()=>{});await ne.ready,j&&await ne.close(),G()}catch(W){try{await ne.abort(W),G(W)}catch(K){G(K)}}}function M(...te){return J(te,a(Y(te)))}function J(te,we,G){if(te.length===1&&r(te[0])&&(te=te[0]),te.length<2)throw new f("streams");let j=new T,ne=j.signal,W=G?.signal,K=[];w(W,"options.signal");function Q(){fe(new k)}U=U||Ge().addAbortListener;let ge;W&&(ge=U(W,Q));let oe,R,$=[],ee=0;function de(ve){fe(ve,--ee===0)}function fe(ve,se){var Te;if(ve&&(!oe||oe.code==="ERR_STREAM_PREMATURE_CLOSE")&&(oe=ve),!(!oe&&!se)){for(;$.length;)$.shift()(oe);(Te=ge)===null||Te===void 0||Te[i](),j.abort(),se&&(oe||K.forEach(d=>d()),t.nextTick(we,oe,R))}}let ye;for(let ve=0;ve<te.length;ve++){let se=te[ve],Te=ve<te.length-1,d=ve>0,_=Te||G?.end!==!1,A=ve===te.length-1;if(S(se)){let B=function(X){X&&X.name!=="AbortError"&&X.code!=="ERR_STREAM_PREMATURE_CLOSE"&&de(X)};if(_){let{destroy:X,cleanup:he}=ae(se,Te,d);$.push(X),v(se)&&A&&K.push(he)}se.on("error",B),v(se)&&A&&K.push(()=>{se.removeListener("error",B)})}if(ve===0)if(typeof se=="function"){if(ye=se({signal:ne}),!x(ye))throw new y("Iterable, AsyncIterable or Stream","source",ye)}else x(se)||E(se)||I(se)?ye=se:ye=u.from(se);else if(typeof se=="function"){if(I(ye)){var H;ye=V((H=ye)===null||H===void 0?void 0:H.readable)}else ye=V(ye);if(ye=se(ye,{signal:ne}),Te){if(!x(ye,!0))throw new y("AsyncIterable",`transform[${ve-1}]`,ye)}else{var me;q||(q=ts());let B=new q({objectMode:!0}),X=(me=ye)===null||me===void 0?void 0:me.then;if(typeof X=="function")ee++,X.call(ye,z=>{R=z,z!=null&&B.write(z),_&&B.end(),t.nextTick(de)},z=>{B.destroy(z),t.nextTick(de,z)});else if(x(ye,!0))ee++,F(ye,B,de,{end:_});else if(P(ye)||I(ye)){let z=ye.readable||ye;ee++,F(z,B,de,{end:_})}else throw new y("AsyncIterable or Promise","destination",ye);ye=B;let{destroy:he,cleanup:ke}=ae(ye,!1,!0);$.push(he),A&&K.push(ke)}}else if(S(se)){if(E(ye)){ee+=2;let B=be(ye,se,de,{end:_});v(se)&&A&&K.push(B)}else if(I(ye)||P(ye)){let B=ye.readable||ye;ee++,F(B,se,de,{end:_})}else if(x(ye))ee++,F(ye,se,de,{end:_});else throw new p("val",["Readable","Iterable","AsyncIterable","ReadableStream","TransformStream"],ye);ye=se}else if(O(se)){if(E(ye))ee++,Z(V(ye),se,de,{end:_});else if(P(ye)||x(ye))ee++,Z(ye,se,de,{end:_});else if(I(ye))ee++,Z(ye.readable,se,de,{end:_});else throw new p("val",["Readable","Iterable","AsyncIterable","ReadableStream","TransformStream"],ye);ye=se}else ye=u.from(se)}return(ne!=null&&ne.aborted||W!=null&&W.aborted)&&t.nextTick(Q),ye}function be(te,we,G,{end:j}){let ne=!1;if(we.on("close",()=>{ne||G(new b)}),te.pipe(we,{end:!1}),j){let W=function(){ne=!0,we.end()};N(te)?t.nextTick(W):te.once("end",W)}else G();return o(te,{readable:!0,writable:!1},W=>{let K=te._readableState;W&&W.code==="ERR_STREAM_PREMATURE_CLOSE"&&K&&K.ended&&!K.errored&&!K.errorEmitted?te.once("end",G).once("error",G):G(W)}),o(we,{readable:!1,writable:!0},G)}e.exports={pipelineImpl:J,pipeline:M}}),rs=pe((l,e)=>{le(),ue(),ce();var{pipeline:t}=ui(),r=ut(),{destroyer:s}=Nt(),{isNodeStream:n,isReadable:i,isWritable:o,isWebStream:a,isTransformStream:c,isWritableStream:u,isReadableStream:h}=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])&&!a(b[T]))){if(T<b.length-1&&!(i(b[T])||h(b[T])||c(b[T])))throw new y(`streams[${T}]`,k[T],"must be readable");if(T>0&&!(o(b[T])||u(b[T])||c(b[T])))throw new y(`streams[${T}]`,k[T],"must be writable")}let m,w,x,v,E;function S(T){let q=v;v=null,q?q(T):T?E.destroy(T):!N&&!P&&E.destroy()}let I=b[0],O=t(b,S),P=!!(o(I)||u(I)||c(I)),N=!!(i(O)||h(O)||c(O));if(E=new r({writableObjectMode:!!(I!=null&&I.writableObjectMode),readableObjectMode:!!(O!=null&&O.readableObjectMode),writable:P,readable:N}),P){if(n(I))E._write=function(q,D,U){I.write(q,D)?U():m=U},E._final=function(q){I.end(),w=q},I.on("drain",function(){if(m){let q=m;m=null,q()}});else if(a(I)){let q=(c(I)?I.writable:I).getWriter();E._write=async function(D,U,ae){try{await q.ready,q.write(D).catch(()=>{}),ae()}catch(Y){ae(Y)}},E._final=async function(D){try{await q.ready,q.close().catch(()=>{}),w=D}catch(U){D(U)}}}let T=c(O)?O.readable:O;g(T,()=>{if(w){let q=w;w=null,q()}})}if(N){if(n(O))O.on("readable",function(){if(x){let T=x;x=null,T()}}),O.on("end",function(){E.push(null)}),E._read=function(){for(;;){let T=O.read();if(T===null){x=E._read;return}if(!E.push(T))return}};else if(a(O)){let T=(c(O)?O.readable:O).getReader();E._read=async function(){for(;;)try{let{value:q,done:D}=await T.read();if(!E.push(q))return;if(D){E.push(null);return}}catch{return}}}}return E._destroy=function(T,q){!T&&v!==null&&(T=new p),x=null,m=null,w=null,v===null?q(T):(v=q,n(O)&&s(O,T))},E}}),Lc=pe((l,e)=>{le(),ue(),ce();var t=globalThis.AbortController||Gt().AbortController,{codes:{ERR_INVALID_ARG_VALUE:r,ERR_INVALID_ARG_TYPE:s,ERR_MISSING_ARGS:n,ERR_OUT_OF_RANGE:i},AbortError:o}=We(),{validateAbortSignal:a,validateInteger:c,validateObject:u}=Yt(),h=Ne().Symbol("kWeak"),p=Ne().Symbol("kResistStopPropagation"),{finished:y}=yt(),f=rs(),{addAbortSignalNoValidate:g}=cr(),{isWritable:b,isNodeStream:k}=ct(),{deprecate:m}=Ge(),{ArrayPrototypePush:w,Boolean:x,MathFloor:v,Number:E,NumberIsNaN:S,Promise:I,PromiseReject:O,PromiseResolve:P,PromisePrototypeThen:N,Symbol:T}=Ne(),q=T("kEmpty"),D=T("kEof");function U(W,K){if(K!=null&&u(K,"options"),K?.signal!=null&&a(K.signal,"options.signal"),k(W)&&!b(W))throw new r("stream",W,"must be writable");let Q=f(this,W);return K!=null&&K.signal&&g(K.signal,Q),Q}function ae(W,K){if(typeof W!="function")throw new s("fn",["Function","AsyncFunction"],W);K!=null&&u(K,"options"),K?.signal!=null&&a(K.signal,"options.signal");let Q=1;K?.concurrency!=null&&(Q=v(K.concurrency));let ge=Q-1;return K?.highWaterMark!=null&&(ge=v(K.highWaterMark)),c(Q,"options.concurrency",1),c(ge,"options.highWaterMark",0),ge+=Q,(async function*(){let oe=Ge().AbortSignalAny([K?.signal].filter(x)),R=this,$=[],ee={signal:oe},de,fe,ye=!1,H=0;function me(){ye=!0,ve()}function ve(){H-=1,se()}function se(){fe&&!ye&&H<Q&&$.length<ge&&(fe(),fe=null)}async function Te(){try{for await(let d of R){if(ye)return;if(oe.aborted)throw new o;try{if(d=W(d,ee),d===q)continue;d=P(d)}catch(_){d=O(_)}H+=1,N(d,ve,me),$.push(d),de&&(de(),de=null),!ye&&($.length>=ge||H>=Q)&&await new I(_=>{fe=_})}$.push(D)}catch(d){let _=O(d);N(_,ve,me),$.push(_)}finally{ye=!0,de&&(de(),de=null)}}Te();try{for(;;){for(;$.length>0;){let d=await $[0];if(d===D)return;if(oe.aborted)throw new o;d!==q&&(yield d),$.shift(),se()}await new I(d=>{de=d})}}finally{ye=!0,fe&&(fe(),fe=null)}}).call(this)}function Y(W=void 0){return W!=null&&u(W,"options"),W?.signal!=null&&a(W.signal,"options.signal"),(async function*(){let K=0;for await(let ge of this){var Q;if(W!=null&&(Q=W.signal)!==null&&Q!==void 0&&Q.aborted)throw new o({cause:W.signal.reason});yield[K++,ge]}}).call(this)}async function V(W,K=void 0){for await(let Q of M.call(this,W,K))return!0;return!1}async function re(W,K=void 0){if(typeof W!="function")throw new s("fn",["Function","AsyncFunction"],W);return!await V.call(this,async(...Q)=>!await W(...Q),K)}async function F(W,K){for await(let Q of M.call(this,W,K))return Q}async function Z(W,K){if(typeof W!="function")throw new s("fn",["Function","AsyncFunction"],W);async function Q(ge,oe){return await W(ge,oe),q}for await(let ge of ae.call(this,Q,K));}function M(W,K){if(typeof W!="function")throw new s("fn",["Function","AsyncFunction"],W);async function Q(ge,oe){return await W(ge,oe)?ge:q}return ae.call(this,Q,K)}var J=class extends n{constructor(){super("reduce"),this.message="Reduce of an empty stream requires an initial value"}};async function be(W,K,Q){var ge;if(typeof W!="function")throw new s("reducer",["Function","AsyncFunction"],W);Q!=null&&u(Q,"options"),Q?.signal!=null&&a(Q.signal,"options.signal");let oe=arguments.length>1;if(Q!=null&&(ge=Q.signal)!==null&&ge!==void 0&&ge.aborted){let fe=new o(void 0,{cause:Q.signal.reason});throw this.once("error",()=>{}),await y(this.destroy(fe)),fe}let R=new t,$=R.signal;if(Q!=null&&Q.signal){let fe={once:!0,[h]:this,[p]:!0};Q.signal.addEventListener("abort",()=>R.abort(),fe)}let ee=!1;try{for await(let fe of this){var de;if(ee=!0,Q!=null&&(de=Q.signal)!==null&&de!==void 0&&de.aborted)throw new o;oe?K=await W(K,fe,{signal:$}):(K=fe,oe=!0)}if(!ee&&!oe)throw new J}finally{R.abort()}return K}async function te(W){W!=null&&u(W,"options"),W?.signal!=null&&a(W.signal,"options.signal");let K=[];for await(let ge of this){var Q;if(W!=null&&(Q=W.signal)!==null&&Q!==void 0&&Q.aborted)throw new o(void 0,{cause:W.signal.reason});w(K,ge)}return K}function we(W,K){let Q=ae.call(this,W,K);return(async function*(){for await(let ge of Q)yield*ge}).call(this)}function G(W){if(W=E(W),S(W))return 0;if(W<0)throw new i("number",">= 0",W);return W}function j(W,K=void 0){return K!=null&&u(K,"options"),K?.signal!=null&&a(K.signal,"options.signal"),W=G(W),(async function*(){var Q;if(K!=null&&(Q=K.signal)!==null&&Q!==void 0&&Q.aborted)throw new o;for await(let oe of this){var ge;if(K!=null&&(ge=K.signal)!==null&&ge!==void 0&&ge.aborted)throw new o;W--<=0&&(yield oe)}}).call(this)}function ne(W,K=void 0){return K!=null&&u(K,"options"),K?.signal!=null&&a(K.signal,"options.signal"),W=G(W),(async function*(){var Q;if(K!=null&&(Q=K.signal)!==null&&Q!==void 0&&Q.aborted)throw new o;for await(let oe of this){var ge;if(K!=null&&(ge=K.signal)!==null&&ge!==void 0&&ge.aborted)throw new o;if(W-- >0&&(yield oe),W<=0)return}}).call(this)}e.exports.streamReturningOperators={asIndexedPairs:m(Y,"readable.asIndexedPairs will be removed in a future version."),drop:j,filter:M,flatMap:we,map:ae,take:ne,compose:U},e.exports.promiseReturningOperators={every:re,forEach:Z,reduce:be,toArray:te,some:V,find:F}}),ns=pe((l,e)=>{le(),ue(),ce();var{ArrayPrototypePop:t,Promise:r}=Ne(),{isIterable:s,isNodeStream:n,isWebStream:i}=ct(),{pipelineImpl:o}=ui(),{finished:a}=yt();is();function c(...u){return new r((h,p)=>{let y,f,g=u[u.length-1];if(g&&typeof g=="object"&&!n(g)&&!s(g)&&!i(g)){let b=t(u);y=b.signal,f=b.end}o(u,(b,k)=>{b?p(b):h(k)},{signal:y,end:f})})}e.exports={finished:a,pipeline:c}}),is=pe((l,e)=>{le(),ue(),ce();var{Buffer:t}=(De(),Me(Be)),{ObjectDefineProperty:r,ObjectKeys:s,ReflectApply:n}=Ne(),{promisify:{custom:i}}=Ge(),{streamReturningOperators:o,promiseReturningOperators:a}=Lc(),{codes:{ERR_ILLEGAL_CONSTRUCTOR:c}}=We(),u=rs(),{setDefaultHighWaterMark:h,getDefaultHighWaterMark:p}=ur(),{pipeline:y}=ui(),{destroyer:f}=Nt(),g=yt(),b=ns(),k=ct(),m=e.exports=li().Stream;m.isDestroyed=k.isDestroyed,m.isDisturbed=k.isDisturbed,m.isErrored=k.isErrored,m.isReadable=k.isReadable,m.isWritable=k.isWritable,m.Readable=hr();for(let x of s(o)){let v=function(...S){if(new.target)throw c();return m.Readable.from(n(E,this,S))},E=o[x];r(v,"name",{__proto__:null,value:E.name}),r(v,"length",{__proto__:null,value:E.length}),r(m.Readable.prototype,x,{__proto__:null,value:v,enumerable:!1,configurable:!0,writable:!0})}for(let x of s(a)){let v=function(...S){if(new.target)throw c();return n(E,this,S)},E=a[x];r(v,"name",{__proto__:null,value:E.name}),r(v,"length",{__proto__:null,value:E.length}),r(m.Readable.prototype,x,{__proto__:null,value:v,enumerable:!1,configurable:!0,writable:!0})}m.Writable=ci(),m.Duplex=ut(),m.Transform=es(),m.PassThrough=ts(),m.pipeline=y;var{addAbortSignal:w}=cr();m.addAbortSignal=w,m.finished=g,m.destroy=f,m.compose=u,m.setDefaultHighWaterMark=h,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(x){return x instanceof Uint8Array},m._uint8ArrayToBuffer=function(x){return t.from(x.buffer,x.byteOffset,x.byteLength)}}),It=pe((l,e)=>{le(),ue(),ce();var t=is(),r=ns(),s=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=s,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}),jc=pe((l,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 s=function(){};s.prototype=r.prototype,t.prototype=new s,t.prototype.constructor=t}}}),Nc=pe((l,e)=>{le(),ue(),ce();var{Buffer:t}=(De(),Me(Be)),r=Symbol.for("BufferList");function s(n){if(!(this instanceof s))return new s(n);s._init.call(this,n)}s._init=function(n){Object.defineProperty(this,r,{value:!0}),this._bufs=[],this.length=0,n&&this.append(n)},s.prototype._new=function(n){return new s(n)},s.prototype._offset=function(n){if(n===0)return[0,0];let i=0;for(let o=0;o<this._bufs.length;o++){let a=i+this._bufs[o].length;if(n<a||o===this._bufs.length-1)return[o,n-i];i=a}},s.prototype._reverseOffset=function(n){let i=n[0],o=n[1];for(let a=0;a<i;a++)o+=this._bufs[a].length;return o},s.prototype.getBuffers=function(){return this._bufs},s.prototype.get=function(n){if(n>this.length||n<0)return;let i=this._offset(n);return this._bufs[i[0]][i[1]]},s.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)},s.prototype.copy=function(n,i,o,a){if((typeof o!="number"||o<0)&&(o=0),(typeof a!="number"||a>this.length)&&(a=this.length),o>=this.length||a<=0)return n||t.alloc(0);let c=!!n,u=this._offset(o),h=a-o,p=h,y=c&&i||0,f=u[1];if(o===0&&a===this.length){if(!c)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 c?this._bufs[u[0]].copy(n,i,f,f+p):this._bufs[u[0]].slice(f,f+p);c||(n=t.allocUnsafe(h));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},s.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 o=this._offset(n),a=this._offset(i),c=this._bufs.slice(o[0],a[0]+1);return a[1]===0?c.pop():c[c.length-1]=c[c.length-1].slice(0,a[1]),o[1]!==0&&(c[0]=c[0].slice(o[1])),this._new(c)},s.prototype.toString=function(n,i,o){return this.slice(i,o).toString(n)},s.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},s.prototype.duplicate=function(){let n=this._new();for(let i=0;i<this._bufs.length;i++)n.append(this._bufs[i]);return n},s.prototype.append=function(n){return this._attach(n,s.prototype._appendBuffer)},s.prototype.prepend=function(n){return this._attach(n,s.prototype._prependBuffer,!0)},s.prototype._attach=function(n,i,o){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[a,c]=o?[n.length-1,-1]:[0,1];for(let u=a;u>=0&&u<n.length;u+=c)this._attach(n[u],i,o)}else if(this._isBufferList(n)){let[a,c]=o?[n._bufs.length-1,-1]:[0,1];for(let u=a;u>=0&&u<n._bufs.length;u+=c)this._attach(n._bufs[u],i,o)}else typeof n=="number"&&(n=n.toString()),i.call(this,t.from(n));return this},s.prototype._appendBuffer=function(n){this._bufs.push(n),this.length+=n.length},s.prototype._prependBuffer=function(n){this._bufs.unshift(n),this.length+=n.length},s.prototype.indexOf=function(n,i,o){if(o===void 0&&typeof i=="string"&&(o=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,o):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 a=this._offset(i),c=a[0],u=a[1];for(;c<this._bufs.length;c++){let h=this._bufs[c];for(;u<h.length;)if(h.length-u>=n.length){let p=h.indexOf(n,u);if(p!==-1)return this._reverseOffset([c,p]);u=h.length-n.length+1}else{let p=this._reverseOffset([c,u]);if(this._match(p,n))return p;u++}u=0}return-1},s.prototype._match=function(n,i){if(this.length-n<i.length)return!1;for(let o=0;o<i.length;o++)if(this.get(n+o)!==i[o])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(o){n[o]===null?s.prototype[o]=function(a,c){return this.slice(a,a+c)[o](0,c)}:s.prototype[o]=function(a=0){return this.slice(a,a+n[o])[o](0)}})(i)})(),s.prototype._isBufferList=function(n){return n instanceof s||s.isBufferList(n)},s.isBufferList=function(n){return n!=null&&n[r]},e.exports=s}),Uc=pe((l,e)=>{le(),ue(),ce();var t=It().Duplex,r=jc(),s=Nc();function n(i){if(!(this instanceof n))return new n(i);if(typeof i=="function"){this._callback=i;let o=(function(a){this._callback&&(this._callback(a),this._callback=null)}).bind(this);this.on("pipe",function(a){a.on("error",o)}),this.on("unpipe",function(a){a.removeListener("error",o)}),i=null}s._init.call(this,i),t.call(this)}r(n,t),Object.assign(n.prototype,s.prototype),n.prototype._new=function(i){return new n(i)},n.prototype._write=function(i,o,a){this._appendBuffer(i),typeof a=="function"&&a()},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,o){this._bufs.length=0,this.length=0,o(i)},n.prototype._isBufferList=function(i){return i instanceof n||i instanceof s||n.isBufferList(i)},n.isBufferList=s.isBufferList,e.exports=n,e.exports.BufferListStream=n,e.exports.BufferList=s}),Bc=pe((l,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}),os=pe((l,e)=>{le(),ue(),ce();var t=e.exports,{Buffer:r}=(De(),Me(Be));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 s(n){return[0,1,2].map(i=>[0,1].map(o=>[0,1].map(a=>{let c=r.alloc(1);return c.writeUInt8(t.codes[n]<<t.CMD_SHIFT|(o?t.DUP_MASK:0)|i<<t.QOS_SHIFT|a,0,!0),c})))}t.PUBLISH_HEADER=s("publish"),t.SUBSCRIBE_HEADER=s("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=s("unsubscribe"),t.ACKS={unsuback:s("unsuback"),puback:s("puback"),pubcomp:s("pubcomp"),pubrel:s("pubrel"),pubrec:s("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"}}),Dc=pe((l,e)=>{le(),ue(),ce();var t=1e3,r=t*60,s=r*60,n=s*24,i=n*7,o=n*365.25;e.exports=function(p,y){y=y||{};var f=typeof p;if(f==="string"&&p.length>0)return a(p);if(f==="number"&&isFinite(p))return y.long?u(p):c(p);throw new Error("val is not a non-empty string or a valid number. val="+JSON.stringify(p))};function a(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*o;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*s;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 c(p){var y=Math.abs(p);return y>=n?Math.round(p/n)+"d":y>=s?Math.round(p/s)+"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?h(p,y,n,"day"):y>=s?h(p,y,s,"hour"):y>=r?h(p,y,r,"minute"):y>=t?h(p,y,t,"second"):p+" ms"}function h(p,y,f,g){var b=y>=f*1.5;return Math.round(p/f)+" "+g+(b?"s":"")}}),Fc=pe((l,e)=>{le(),ue(),ce();function t(r){n.debug=n,n.default=n,n.coerce=h,n.disable=c,n.enable=o,n.enabled=u,n.humanize=Dc(),n.destroy=p,Object.keys(r).forEach(y=>{n[y]=r[y]}),n.names=[],n.skips=[],n.formatters={};function s(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=s;function n(y){let f,g=null,b,k;function m(...w){if(!m.enabled)return;let x=m,v=Number(new Date),E=v-(f||v);x.diff=E,x.prev=f,x.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,O)=>{if(I==="%%")return"%";S++;let P=n.formatters[O];if(typeof P=="function"){let N=w[S];I=P.call(x,N),w.splice(S,1),S--}return I}),n.formatArgs.call(x,w),(x.log||n.log).apply(x,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 o(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 a(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 c(){let y=[...n.names,...n.skips.map(f=>"-"+f)].join(",");return n.enable(""),y}function u(y){for(let f of n.skips)if(a(y,f))return!1;for(let f of n.names)if(a(y,f))return!0;return!1}function h(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}),ht=pe((l,e)=>{le(),ue(),ce(),l.formatArgs=r,l.save=s,l.load=n,l.useColors=t,l.storage=i(),l.destroy=(()=>{let a=!1;return()=>{a||(a=!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`."))}})(),l.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 a;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&&(a=navigator.userAgent.toLowerCase().match(/firefox\/(\d+)/))&&parseInt(a[1],10)>=31||typeof navigator<"u"&&navigator.userAgent&&navigator.userAgent.toLowerCase().match(/applewebkit\/(\d+)/)}function r(a){if(a[0]=(this.useColors?"%c":"")+this.namespace+(this.useColors?" %c":" ")+a[0]+(this.useColors?"%c ":" ")+"+"+e.exports.humanize(this.diff),!this.useColors)return;let c="color: "+this.color;a.splice(1,0,c,"color: inherit");let u=0,h=0;a[0].replace(/%[a-zA-Z%]/g,p=>{p!=="%%"&&(u++,p==="%c"&&(h=u))}),a.splice(h,0,c)}l.log=console.debug||console.log||(()=>{});function s(a){try{a?l.storage.setItem("debug",a):l.storage.removeItem("debug")}catch{}}function n(){let a;try{a=l.storage.getItem("debug")||l.storage.getItem("DEBUG")}catch{}return!a&&typeof Le<"u"&&"env"in Le&&(a=Le.env.DEBUG),a}function i(){try{return localStorage}catch{}}e.exports=Fc()(l);var{formatters:o}=e.exports;o.j=function(a){try{return JSON.stringify(a)}catch(c){return"[UnexpectedJSONParseError]: "+c.message}}}),$c=pe((l,e)=>{le(),ue(),ce();var t=Uc(),{EventEmitter:r}=(Et(),Me(bt)),s=Bc(),n=os(),i=ht()("mqtt-packet:parser"),o=class wo extends r{constructor(){super(),this.parser=this.constructor.parser}static parser(c){return this instanceof wo?(this.settings=c||{},this._states=["_parseHeader","_parseLength","_parsePayload","_newPacket"],this._resetState(),this):new wo().parser(c)}_resetState(){i("_resetState: resetting packet, error, _list, and _stateCounter"),this.packet=new s,this.error=null,this._list=t(),this._stateCounter=0}parse(c){for(this.error&&this._resetState(),this._list.append(c),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 c=this._list.readUInt8(0),u=c>>n.CMD_SHIFT;this.packet.cmd=n.types[u];let h=c&15,p=n.requiredHeaderFlags[u];return p!=null&&h!==p?this._emitError(new Error(n.requiredHeaderFlagsErrors[u])):(this.packet.retain=(c&n.RETAIN_MASK)!==0,this.packet.qos=c>>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=(c&n.DUP_MASK)!==0,i("_parseHeader: packet: %o",this.packet),this._list.consume(1),!0))}_parseLength(){let c=this._parseVarByteNum(!0);return c&&(this.packet.length=c.value,this._list.consume(c.bytes)),i("_parseLength %d",c.value),!!c}_parsePayload(){i("_parsePayload: payload %O",this._list);let c=!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"))}c=!0}return i("_parsePayload complete result: %s",c),c}_parseConnect(){i("_parseConnect");let c,u,h,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(c=this._parseString(),c===null)return this._emitError(new Error("Cannot parse will topic"));if(f.will.topic=c,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(h=this._parseBuffer(),h===null)return this._emitError(new Error("Cannot parse password"));f.password=h}return this.settings=f,i("_parseConnect: complete"),f}_parseConnack(){i("_parseConnack");let c=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(c.sessionPresent=!!(u&n.SESSIONPRESENT_MASK),this.settings.protocolVersion===5)this._list.length>=2?c.reasonCode=this._list.readUInt8(this._pos++):c.reasonCode=0;else{if(this._list.length<2)return null;c.returnCode=this._list.readUInt8(this._pos++)}if(c.returnCode===-1||c.reasonCode===-1)return this._emitError(new Error("Cannot parse return code"));if(this.settings.protocolVersion===5){let h=this._parseProperties();Object.getOwnPropertyNames(h).length&&(c.properties=h)}i("_parseConnack: complete")}_parsePublish(){i("_parsePublish");let c=this.packet;if(c.topic=this._parseString(),c.topic===null)return this._emitError(new Error("Cannot parse topic"));if(!(c.qos>0&&!this._parseMessageId())){if(this.settings.protocolVersion===5){let u=this._parseProperties();Object.getOwnPropertyNames(u).length&&(c.properties=u)}c.payload=this._list.slice(this._pos,c.length),i("_parsePublish: payload from buffer list: %o",c.payload)}}_parseSubscribe(){i("_parseSubscribe");let c=this.packet,u,h,p,y,f,g,b;if(c.subscriptions=[],!!this._parseMessageId()){if(this.settings.protocolVersion===5){let k=this._parseProperties();Object.getOwnPropertyNames(k).length&&(c.properties=k)}if(c.length<=0)return this._emitError(new Error("Malformed subscribe, no payload specified"));for(;this._pos<c.length;){if(u=this._parseString(),u===null)return this._emitError(new Error("Cannot parse topic"));if(this._pos>=c.length)return this._emitError(new Error("Malformed Subscribe Payload"));if(h=this._parseByte(),this.settings.protocolVersion===5){if(h&192)return this._emitError(new Error("Invalid subscribe topic flag bits, bits 7-6 must be 0"))}else if(h&252)return this._emitError(new Error("Invalid subscribe topic flag bits, bits 7-2 must be 0"));if(p=h&n.SUBSCRIBE_OPTIONS_QOS_MASK,p>2)return this._emitError(new Error("Invalid subscribe QoS, must be <= 2"));if(g=(h>>n.SUBSCRIBE_OPTIONS_NL_SHIFT&n.SUBSCRIBE_OPTIONS_NL_MASK)!==0,f=(h>>n.SUBSCRIBE_OPTIONS_RAP_SHIFT&n.SUBSCRIBE_OPTIONS_RAP_MASK)!==0,y=h>>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),c.subscriptions.push(b)}}}_parseSuback(){i("_parseSuback");let c=this.packet;if(this.packet.granted=[],!!this._parseMessageId()){if(this.settings.protocolVersion===5){let u=this._parseProperties();Object.getOwnPropertyNames(u).length&&(c.properties=u)}if(c.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 c=this.packet;if(c.unsubscriptions=[],!!this._parseMessageId()){if(this.settings.protocolVersion===5){let u=this._parseProperties();Object.getOwnPropertyNames(u).length&&(c.properties=u)}if(c.length<=0)return this._emitError(new Error("Malformed unsubscribe, no payload specified"));for(;this._pos<c.length;){let u=this._parseString();if(u===null)return this._emitError(new Error("Cannot parse topic"));i("_parseUnsubscribe: push topic `%s` to unsubscriptions",u),c.unsubscriptions.push(u)}}}_parseUnsuback(){i("_parseUnsuback");let c=this.packet;if(!this._parseMessageId())return this._emitError(new Error("Cannot parse messageId"));if((this.settings.protocolVersion===3||this.settings.protocolVersion===4)&&c.length!==2)return this._emitError(new Error("Malformed unsuback, payload length must be 2"));if(c.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&&(c.properties=u),c.granted=[];this._pos<this.packet.length;){let h=this._list.readUInt8(this._pos++);if(!n.MQTT5_UNSUBACK_CODES[h])return this._emitError(new Error("Invalid unsuback code"));this.packet.granted.push(h)}}}_parseConfirmation(){i("_parseConfirmation: packet.cmd: `%s`",this.packet.cmd);let c=this.packet;if(this._parseMessageId(),this.settings.protocolVersion===5){if(c.length>2){switch(c.reasonCode=this._parseByte(),this.packet.cmd){case"puback":case"pubrec":if(!n.MQTT5_PUBACK_PUBREC_CODES[c.reasonCode])return this._emitError(new Error("Invalid "+this.packet.cmd+" reason code"));break;case"pubrel":case"pubcomp":if(!n.MQTT5_PUBREL_PUBCOMP_CODES[c.reasonCode])return this._emitError(new Error("Invalid "+this.packet.cmd+" reason code"));break}i("_parseConfirmation: packet.reasonCode `%d`",c.reasonCode)}else c.reasonCode=0;if(c.length>3){let u=this._parseProperties();Object.getOwnPropertyNames(u).length&&(c.properties=u)}}return!0}_parseDisconnect(){let c=this.packet;if(i("_parseDisconnect"),this.settings.protocolVersion===5){this._list.length>0?(c.reasonCode=this._parseByte(),n.MQTT5_DISCONNECT_CODES[c.reasonCode]||this._emitError(new Error("Invalid disconnect reason code"))):c.reasonCode=0;let u=this._parseProperties();Object.getOwnPropertyNames(u).length&&(c.properties=u)}return i("_parseDisconnect result: true"),!0}_parseAuth(){i("_parseAuth");let c=this.packet;if(this.settings.protocolVersion!==5)return this._emitError(new Error("Not supported auth packet for this version MQTT"));if(c.reasonCode=this._parseByte(),!n.MQTT5_AUTH_CODES[c.reasonCode])return this._emitError(new Error("Invalid auth reason code"));let u=this._parseProperties();return Object.getOwnPropertyNames(u).length&&(c.properties=u),i("_parseAuth: result: true"),!0}_parseMessageId(){let c=this.packet;return c.messageId=this._parseNum(),c.messageId===null?(this._emitError(new Error("Cannot parse messageId")),!1):(i("_parseMessageId: packet.messageId %d",c.messageId),!0)}_parseString(c){let u=this._parseNum(),h=u+this._pos;if(u===-1||h>this._list.length||h>this.packet.length)return null;let p=this._list.toString("utf8",this._pos,h);return this._pos+=u,i("_parseString: result: %s",p),p}_parseStringPair(){return i("_parseStringPair"),{name:this._parseString(),value:this._parseString()}}_parseBuffer(){let c=this._parseNum(),u=c+this._pos;if(c===-1||u>this._list.length||u>this.packet.length)return null;let h=this._list.slice(this._pos,u);return this._pos+=c,i("_parseBuffer: result: %o",h),h}_parseNum(){if(this._list.length-this._pos<2)return-1;let c=this._list.readUInt16BE(this._pos);return this._pos+=2,i("_parseNum: result: %s",c),c}_parse4ByteNum(){if(this._list.length-this._pos<4)return-1;let c=this._list.readUInt32BE(this._pos);return this._pos+=4,i("_parse4ByteNum: result: %s",c),c}_parseVarByteNum(c){i("_parseVarByteNum");let u=4,h=0,p=1,y=0,f=!1,g,b=this._pos?this._pos:0;for(;h<u&&b+h<this._list.length;){if(g=this._list.readUInt8(b+h++),y+=p*(g&n.VARBYTEINT_MASK),p*=128,(g&n.VARBYTEINT_FIN_MASK)===0){f=!0;break}if(this._list.length<=h)break}return!f&&h===u&&this._list.length>=h&&this._emitError(new Error("Invalid variable byte integer")),b&&(this._pos+=h),f?c?f={bytes:h,value:y}:f=y:f=!1,i("_parseVarByteNum: result: %o",f),f}_parseByte(){let c;return this._pos<this._list.length&&(c=this._list.readUInt8(this._pos),this._pos++),i("_parseByte: result: %o",c),c}_parseByType(c){switch(i("_parseByType: type: %s",c),c){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 c=this._parseVarByteNum(),u=this._pos+c,h={};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"){h[y]||(h[y]=Object.create(null));let f=this._parseByType(n.propertiesTypes[y]);if(h[y][f.name])if(Array.isArray(h[y][f.name]))h[y][f.name].push(f.value);else{let g=h[y][f.name];h[y][f.name]=[g],h[y][f.name].push(f.value)}else h[y][f.name]=f.value;continue}h[y]?Array.isArray(h[y])?h[y].push(this._parseByType(n.propertiesTypes[y])):(h[y]=[h[y]],h[y].push(this._parseByType(n.propertiesTypes[y]))):h[y]=this._parseByType(n.propertiesTypes[y])}return h}_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 s,this._pos=0,!0}_emitError(c){i("_emitError",c),this.error=c,this.emit("error",c)}};e.exports=o}),qc=pe((l,e)=>{le(),ue(),ce();var{Buffer:t}=(De(),Me(Be)),r=65536,s={},n=t.isBuffer(t.from([1,2]).subarray(0,1));function i(u){let h=t.allocUnsafe(2);return h.writeUInt8(u>>8,0),h.writeUInt8(u&255,1),h}function o(){for(let u=0;u<r;u++)s[u]=i(u)}function a(u){let h=0,p=0,y=t.allocUnsafe(4);do h=u%128|0,u=u/128|0,u>0&&(h=h|128),y.writeUInt8(h,p++);while(u>0&&p<4);return u>0&&(p=0),n?y.subarray(0,p):y.slice(0,p)}function c(u){let h=t.allocUnsafe(4);return h.writeUInt32BE(u,0),h}e.exports={cache:s,generateCache:o,generateNumber:i,genBufVariableByteInt:a,generate4ByteBuffer:c}}),Hc=pe((l,e)=>{le(),ue(),ce(),typeof Le>"u"||!Le.version||Le.version.indexOf("v0.")===0||Le.version.indexOf("v1.")===0&&Le.version.indexOf("v1.8.")!==0?e.exports={nextTick:t}:e.exports=Le;function t(r,s,n,i){if(typeof r!="function")throw new TypeError('"callback" argument must be a function');var o=arguments.length,a,c;switch(o){case 0:case 1:return Le.nextTick(r);case 2:return Le.nextTick(function(){r.call(null,s)});case 3:return Le.nextTick(function(){r.call(null,s,n)});case 4:return Le.nextTick(function(){r.call(null,s,n,i)});default:for(a=new Array(o-1),c=0;c<a.length;)a[c++]=arguments[c];return Le.nextTick(function(){r.apply(null,a)})}}}),ss=pe((l,e)=>{le(),ue(),ce();var t=os(),{Buffer:r}=(De(),Me(Be)),s=r.allocUnsafe(0),n=r.from([0]),i=qc(),o=Hc().nextTick,a=ht()("mqtt-packet:writeToStream"),c=i.cache,u=i.generateNumber,h=i.generateCache,p=i.genBufVariableByteInt,y=i.generate4ByteBuffer,f=Y,g=!0;function b(G,j,ne){switch(a("generate called"),j.cork&&(j.cork(),o(k,j)),g&&(g=!1,h()),a("generate: packet.cmd: %s",G.cmd),G.cmd){case"connect":return m(G,j);case"connack":return w(G,j,ne);case"publish":return x(G,j,ne);case"puback":case"pubrec":case"pubrel":case"pubcomp":return v(G,j,ne);case"subscribe":return E(G,j,ne);case"suback":return S(G,j,ne);case"unsubscribe":return I(G,j,ne);case"unsuback":return O(G,j,ne);case"pingreq":case"pingresp":return P(G,j);case"disconnect":return N(G,j,ne);case"auth":return T(G,j,ne);default:return j.destroy(new Error("Unknown command")),!1}}Object.defineProperty(b,"cacheNumbers",{get(){return f===Y},set(G){G?((!c||Object.keys(c).length===0)&&(g=!0),f=Y):(g=!1,f=V)}});function k(G){G.uncork()}function m(G,j,ne){let W=G||{},K=W.protocolId||"MQTT",Q=W.protocolVersion||4,ge=W.will,oe=W.clean,R=W.keepalive||0,$=W.clientId||"",ee=W.username,de=W.password,fe=W.properties;oe===void 0&&(oe=!0);let ye=0;if(typeof K!="string"&&!r.isBuffer(K))return j.destroy(new Error("Invalid protocolId")),!1;if(ye+=K.length+2,Q!==3&&Q!==4&&Q!==5)return j.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 j.destroy(new Error("clientId must be supplied before 3.1.1")),!1;if(oe*1===0)return j.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 j.destroy(new Error("Invalid keepalive")),!1;ye+=2,ye+=1;let H,me;if(Q===5){if(H=Z(j,fe),!H)return!1;ye+=H.length}if(ge){if(typeof ge!="object")return j.destroy(new Error("Invalid will")),!1;if(!ge.topic||typeof ge.topic!="string")return j.destroy(new Error("Invalid will topic")),!1;if(ye+=r.byteLength(ge.topic)+2,ye+=2,ge.payload)if(ge.payload.length>=0)typeof ge.payload=="string"?ye+=r.byteLength(ge.payload):ye+=ge.payload.length;else return j.destroy(new Error("Invalid will payload")),!1;if(me={},Q===5){if(me=Z(j,ge.properties),!me)return!1;ye+=me.length}}let ve=!1;if(ee!=null)if(we(ee))ve=!0,ye+=r.byteLength(ee)+2;else return j.destroy(new Error("Invalid username")),!1;if(de!=null){if(!ve)return j.destroy(new Error("Username is required to use password")),!1;if(we(de))ye+=te(de)+2;else return j.destroy(new Error("Invalid password")),!1}j.write(t.CONNECT_HEADER),D(j,ye),F(j,K),W.bridgeMode&&(Q+=128),j.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|=de!=null?t.PASSWORD_MASK:0,se|=ge&&ge.retain?t.WILL_RETAIN_MASK:0,se|=ge&&ge.qos?ge.qos<<t.WILL_QOS_SHIFT:0,se|=ge?t.WILL_FLAG_MASK:0,se|=oe?t.CLEAN_SESSION_MASK:0,j.write(r.from([se])),f(j,R),Q===5&&H.write(),F(j,$),ge&&(Q===5&&me.write(),U(j,ge.topic),F(j,ge.payload)),ee!=null&&F(j,ee),de!=null&&F(j,de),!0}function w(G,j,ne){let W=ne?ne.protocolVersion:4,K=G||{},Q=W===5?K.reasonCode:K.returnCode,ge=K.properties,oe=2;if(typeof Q!="number")return j.destroy(new Error("Invalid return code")),!1;let R=null;if(W===5){if(R=Z(j,ge),!R)return!1;oe+=R.length}return j.write(t.CONNACK_HEADER),D(j,oe),j.write(K.sessionPresent?t.SESSIONPRESENT_HEADER:n),j.write(r.from([Q])),R?.write(),!0}function x(G,j,ne){a("publish: packet: %o",G);let W=ne?ne.protocolVersion:4,K=G||{},Q=K.qos||0,ge=K.retain?t.RETAIN_MASK:0,oe=K.topic,R=K.payload||s,$=K.messageId,ee=K.properties,de=0;if(typeof oe=="string")de+=r.byteLength(oe)+2;else if(r.isBuffer(oe))de+=oe.length+2;else return j.destroy(new Error("Invalid topic")),!1;if(r.isBuffer(R)?de+=R.length:de+=r.byteLength(R),Q&&typeof $!="number")return j.destroy(new Error("Invalid messageId")),!1;Q&&(de+=2);let fe=null;if(W===5){if(fe=Z(j,ee),!fe)return!1;de+=fe.length}return j.write(t.PUBLISH_HEADER[Q][K.dup?1:0][ge?1:0]),D(j,de),f(j,te(oe)),j.write(oe),Q>0&&f(j,$),fe?.write(),a("publish: payload: %o",R),j.write(R)}function v(G,j,ne){let W=ne?ne.protocolVersion:4,K=G||{},Q=K.cmd||"puback",ge=K.messageId,oe=K.dup&&Q==="pubrel"?t.DUP_MASK:0,R=0,$=K.reasonCode,ee=K.properties,de=W===5?3:2;if(Q==="pubrel"&&(R=1),typeof ge!="number")return j.destroy(new Error("Invalid messageId")),!1;let fe=null;if(W===5&&typeof ee=="object"){if(fe=M(j,ee,ne,de),!fe)return!1;de+=fe.length}return j.write(t.ACKS[Q][R][oe][0]),de===3&&(de+=$!==0?1:-1),D(j,de),f(j,ge),W===5&&de!==2&&j.write(r.from([$])),fe!==null?fe.write():de===4&&j.write(r.from([0])),!0}function E(G,j,ne){a("subscribe: packet: ");let W=ne?ne.protocolVersion:4,K=G||{},Q=K.dup?t.DUP_MASK:0,ge=K.messageId,oe=K.subscriptions,R=K.properties,$=0;if(typeof ge!="number")return j.destroy(new Error("Invalid messageId")),!1;$+=2;let ee=null;if(W===5){if(ee=Z(j,R),!ee)return!1;$+=ee.length}if(typeof oe=="object"&&oe.length)for(let fe=0;fe<oe.length;fe+=1){let ye=oe[fe].topic,H=oe[fe].qos;if(typeof ye!="string")return j.destroy(new Error("Invalid subscriptions - invalid topic")),!1;if(typeof H!="number")return j.destroy(new Error("Invalid subscriptions - invalid qos")),!1;if(W===5){if(typeof(oe[fe].nl||!1)!="boolean")return j.destroy(new Error("Invalid subscriptions - invalid No Local")),!1;if(typeof(oe[fe].rap||!1)!="boolean")return j.destroy(new Error("Invalid subscriptions - invalid Retain as Published")),!1;let me=oe[fe].rh||0;if(typeof me!="number"||me>2)return j.destroy(new Error("Invalid subscriptions - invalid Retain Handling")),!1}$+=r.byteLength(ye)+2+1}else return j.destroy(new Error("Invalid subscriptions")),!1;a("subscribe: writing to stream: %o",t.SUBSCRIBE_HEADER),j.write(t.SUBSCRIBE_HEADER[1][Q?1:0][0]),D(j,$),f(j,ge),ee!==null&&ee.write();let de=!0;for(let fe of oe){let ye=fe.topic,H=fe.qos,me=+fe.nl,ve=+fe.rap,se=fe.rh,Te;U(j,ye),Te=t.SUBSCRIBE_OPTIONS_QOS[H],W===5&&(Te|=me?t.SUBSCRIBE_OPTIONS_NL:0,Te|=ve?t.SUBSCRIBE_OPTIONS_RAP:0,Te|=se?t.SUBSCRIBE_OPTIONS_RH[se]:0),de=j.write(r.from([Te]))}return de}function S(G,j,ne){let W=ne?ne.protocolVersion:4,K=G||{},Q=K.messageId,ge=K.granted,oe=K.properties,R=0;if(typeof Q!="number")return j.destroy(new Error("Invalid messageId")),!1;if(R+=2,typeof ge=="object"&&ge.length)for(let ee=0;ee<ge.length;ee+=1){if(typeof ge[ee]!="number")return j.destroy(new Error("Invalid qos vector")),!1;R+=1}else return j.destroy(new Error("Invalid qos vector")),!1;let $=null;if(W===5){if($=M(j,oe,ne,R),!$)return!1;R+=$.length}return j.write(t.SUBACK_HEADER),D(j,R),f(j,Q),$!==null&&$.write(),j.write(r.from(ge))}function I(G,j,ne){let W=ne?ne.protocolVersion:4,K=G||{},Q=K.messageId,ge=K.dup?t.DUP_MASK:0,oe=K.unsubscriptions,R=K.properties,$=0;if(typeof Q!="number")return j.destroy(new Error("Invalid messageId")),!1;if($+=2,typeof oe=="object"&&oe.length)for(let fe=0;fe<oe.length;fe+=1){if(typeof oe[fe]!="string")return j.destroy(new Error("Invalid unsubscriptions")),!1;$+=r.byteLength(oe[fe])+2}else return j.destroy(new Error("Invalid unsubscriptions")),!1;let ee=null;if(W===5){if(ee=Z(j,R),!ee)return!1;$+=ee.length}j.write(t.UNSUBSCRIBE_HEADER[1][ge?1:0][0]),D(j,$),f(j,Q),ee!==null&&ee.write();let de=!0;for(let fe=0;fe<oe.length;fe++)de=U(j,oe[fe]);return de}function O(G,j,ne){let W=ne?ne.protocolVersion:4,K=G||{},Q=K.messageId,ge=K.dup?t.DUP_MASK:0,oe=K.granted,R=K.properties,$=K.cmd,ee=0,de=2;if(typeof Q!="number")return j.destroy(new Error("Invalid messageId")),!1;if(W===5)if(typeof oe=="object"&&oe.length)for(let ye=0;ye<oe.length;ye+=1){if(typeof oe[ye]!="number")return j.destroy(new Error("Invalid qos vector")),!1;de+=1}else return j.destroy(new Error("Invalid qos vector")),!1;let fe=null;if(W===5){if(fe=M(j,R,ne,de),!fe)return!1;de+=fe.length}return j.write(t.ACKS[$][ee][ge][0]),D(j,de),f(j,Q),fe!==null&&fe.write(),W===5&&j.write(r.from(oe)),!0}function P(G,j,ne){return j.write(t.EMPTY[G.cmd])}function N(G,j,ne){let W=ne?ne.protocolVersion:4,K=G||{},Q=K.reasonCode,ge=K.properties,oe=W===5?1:0,R=null;if(W===5){if(R=M(j,ge,ne,oe),!R)return!1;oe+=R.length}return j.write(r.from([t.codes.disconnect<<4])),D(j,oe),W===5&&j.write(r.from([Q])),R!==null&&R.write(),!0}function T(G,j,ne){let W=ne?ne.protocolVersion:4,K=G||{},Q=K.reasonCode,ge=K.properties,oe=W===5?1:0;W!==5&&j.destroy(new Error("Invalid mqtt version for auth packet"));let R=M(j,ge,ne,oe);return R?(oe+=R.length,j.write(r.from([t.codes.auth<<4])),D(j,oe),j.write(r.from([Q])),R!==null&&R.write(),!0):!1}var q={};function D(G,j){if(j>t.VARBYTEINT_MAX)return G.destroy(new Error(`Invalid variable byte integer: ${j}`)),!1;let ne=q[j];return ne||(ne=p(j),j<16384&&(q[j]=ne)),a("writeVarByteInt: writing to stream: %o",ne),G.write(ne)}function U(G,j){let ne=r.byteLength(j);return f(G,ne),a("writeString: %s",j),G.write(j,"utf8")}function ae(G,j,ne){U(G,j),U(G,ne)}function Y(G,j){return a("writeNumberCached: number: %d",j),a("writeNumberCached: %o",c[j]),G.write(c[j])}function V(G,j){let ne=u(j);return a("writeNumberGenerated: %o",ne),G.write(ne)}function re(G,j){let ne=y(j);return a("write4ByteNumber: %o",ne),G.write(ne)}function F(G,j){typeof j=="string"?U(G,j):j?(f(G,j.length),G.write(j)):f(G,0)}function Z(G,j){if(typeof j!="object"||j.length!=null)return{length:1,write(){be(G,{},0)}};let ne=0;function W(K,Q){let ge=t.propertiesTypes[K],oe=0;switch(ge){case"byte":{if(typeof Q!="boolean")return G.destroy(new Error(`Invalid ${K}: ${Q}`)),!1;oe+=2;break}case"int8":{if(typeof Q!="number"||Q<0||Q>255)return G.destroy(new Error(`Invalid ${K}: ${Q}`)),!1;oe+=2;break}case"binary":{if(Q&&Q===null)return G.destroy(new Error(`Invalid ${K}: ${Q}`)),!1;oe+=1+r.byteLength(Q)+2;break}case"int16":{if(typeof Q!="number"||Q<0||Q>65535)return G.destroy(new Error(`Invalid ${K}: ${Q}`)),!1;oe+=3;break}case"int32":{if(typeof Q!="number"||Q<0||Q>4294967295)return G.destroy(new Error(`Invalid ${K}: ${Q}`)),!1;oe+=5;break}case"var":{if(typeof Q!="number"||Q<0||Q>268435455)return G.destroy(new Error(`Invalid ${K}: ${Q}`)),!1;oe+=1+r.byteLength(p(Q));break}case"string":{if(typeof Q!="string")return G.destroy(new Error(`Invalid ${K}: ${Q}`)),!1;oe+=3+r.byteLength(Q.toString());break}case"pair":{if(typeof Q!="object")return G.destroy(new Error(`Invalid ${K}: ${Q}`)),!1;oe+=Object.getOwnPropertyNames(Q).reduce((R,$)=>{let ee=Q[$];return Array.isArray(ee)?R+=ee.reduce((de,fe)=>(de+=3+r.byteLength($.toString())+2+r.byteLength(fe.toString()),de),0):R+=3+r.byteLength($.toString())+2+r.byteLength(Q[$].toString()),R},0);break}default:return G.destroy(new Error(`Invalid property ${K}: ${Q}`)),!1}return oe}if(j)for(let K in j){let Q=0,ge=0,oe=j[K];if(oe!==void 0){if(Array.isArray(oe))for(let R=0;R<oe.length;R++){if(ge=W(K,oe[R]),!ge)return!1;Q+=ge}else{if(ge=W(K,oe),!ge)return!1;Q=ge}if(!Q)return!1;ne+=Q}}return{length:r.byteLength(p(ne))+ne,write(){be(G,j,ne)}}}function M(G,j,ne,W){let K=["reasonString","userProperties"],Q=ne&&ne.properties&&ne.properties.maximumPacketSize?ne.properties.maximumPacketSize:0,ge=Z(G,j);if(Q)for(;W+ge.length>Q;){let oe=K.shift();if(oe&&j[oe])delete j[oe],ge=Z(G,j);else return!1}return ge}function J(G,j,ne){switch(t.propertiesTypes[j]){case"byte":{G.write(r.from([t.properties[j]])),G.write(r.from([+ne]));break}case"int8":{G.write(r.from([t.properties[j]])),G.write(r.from([ne]));break}case"binary":{G.write(r.from([t.properties[j]])),F(G,ne);break}case"int16":{G.write(r.from([t.properties[j]])),f(G,ne);break}case"int32":{G.write(r.from([t.properties[j]])),re(G,ne);break}case"var":{G.write(r.from([t.properties[j]])),D(G,ne);break}case"string":{G.write(r.from([t.properties[j]])),U(G,ne);break}case"pair":{Object.getOwnPropertyNames(ne).forEach(W=>{let K=ne[W];Array.isArray(K)?K.forEach(Q=>{G.write(r.from([t.properties[j]])),ae(G,W.toString(),Q.toString())}):(G.write(r.from([t.properties[j]])),ae(G,W.toString(),K.toString()))});break}default:return G.destroy(new Error(`Invalid property ${j} value: ${ne}`)),!1}}function be(G,j,ne){D(G,ne);for(let W in j)if(Object.prototype.hasOwnProperty.call(j,W)&&j[W]!=null){let K=j[W];if(Array.isArray(K))for(let Q=0;Q<K.length;Q++)J(G,W,K[Q]);else J(G,W,K)}}function te(G){return G?G instanceof r?G.length:r.byteLength(G):0}function we(G){return typeof G=="string"||G instanceof r}e.exports=b}),Wc=pe((l,e)=>{le(),ue(),ce();var t=ss(),{EventEmitter:r}=(Et(),Me(bt)),{Buffer:s}=(De(),Me(Be));function n(o,a){let c=new i;return t(o,c,a),c.concat()}var i=class extends r{constructor(){super(),this._array=new Array(20),this._i=0}write(o){return this._array[this._i++]=o,!0}concat(){let o=0,a=new Array(this._array.length),c=this._array,u=0,h;for(h=0;h<c.length&&c[h]!==void 0;h++)typeof c[h]!="string"?a[h]=c[h].length:a[h]=s.byteLength(c[h]),o+=a[h];let p=s.allocUnsafe(o);for(h=0;h<c.length&&c[h]!==void 0;h++)typeof c[h]!="string"?(c[h].copy(p,u),u+=a[h]):(p.write(c[h],u),u+=a[h]);return p}destroy(o){o&&this.emit("error",o)}};e.exports=n}),zc=pe(l=>{le(),ue(),ce(),l.parser=$c().parser,l.generate=Wc(),l.writeToStream=ss()}),Vc=pe((l,e)=>{le(),ue(),ce(),e.exports=r;function t(n){return n instanceof lr?lr.from(n):new n.constructor(n.buffer.slice(),n.byteOffset,n.length)}function r(n){if(n=n||{},n.circles)return s(n);let i=new Map;if(i.set(Date,h=>new Date(h)),i.set(Map,(h,p)=>new Map(a(Array.from(h),p))),i.set(Set,(h,p)=>new Set(a(Array.from(h),p))),n.constructorHandlers)for(let h of n.constructorHandlers)i.set(h[0],h[1]);let o=null;return n.proto?u:c;function a(h,p){let y=Object.keys(h),f=new Array(y.length);for(let g=0;g<y.length;g++){let b=y[g],k=h[b];typeof k!="object"||k===null?f[b]=k:k.constructor!==Object&&(o=i.get(k.constructor))?f[b]=o(k,p):ArrayBuffer.isView(k)?f[b]=t(k):f[b]=p(k)}return f}function c(h){if(typeof h!="object"||h===null)return h;if(Array.isArray(h))return a(h,c);if(h.constructor!==Object&&(o=i.get(h.constructor)))return o(h,c);let p={};for(let y in h){if(Object.hasOwnProperty.call(h,y)===!1)continue;let f=h[y];typeof f!="object"||f===null?p[y]=f:f.constructor!==Object&&(o=i.get(f.constructor))?p[y]=o(f,c):ArrayBuffer.isView(f)?p[y]=t(f):p[y]=c(f)}return p}function u(h){if(typeof h!="object"||h===null)return h;if(Array.isArray(h))return a(h,u);if(h.constructor!==Object&&(o=i.get(h.constructor)))return o(h,u);let p={};for(let y in h){let f=h[y];typeof f!="object"||f===null?p[y]=f:f.constructor!==Object&&(o=i.get(f.constructor))?p[y]=o(f,u):ArrayBuffer.isView(f)?p[y]=t(f):p[y]=u(f)}return p}}function s(n){let i=[],o=[],a=new Map;if(a.set(Date,y=>new Date(y)),a.set(Map,(y,f)=>new Map(u(Array.from(y),f))),a.set(Set,(y,f)=>new Set(u(Array.from(y),f))),n.constructorHandlers)for(let y of n.constructorHandlers)a.set(y[0],y[1]);let c=null;return n.proto?p:h;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&&(c=a.get(w.constructor)))b[m]=c(w,f);else if(ArrayBuffer.isView(w))b[m]=t(w);else{let x=i.indexOf(w);x!==-1?b[m]=o[x]:b[m]=f(w)}}return b}function h(y){if(typeof y!="object"||y===null)return y;if(Array.isArray(y))return u(y,h);if(y.constructor!==Object&&(c=a.get(y.constructor)))return c(y,h);let f={};i.push(y),o.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&&(c=a.get(b.constructor)))f[g]=c(b,h);else if(ArrayBuffer.isView(b))f[g]=t(b);else{let k=i.indexOf(b);k!==-1?f[g]=o[k]:f[g]=h(b)}}return i.pop(),o.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&&(c=a.get(y.constructor)))return c(y,p);let f={};i.push(y),o.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&&(c=a.get(b.constructor)))f[g]=c(b,p);else if(ArrayBuffer.isView(b))f[g]=t(b);else{let k=i.indexOf(b);k!==-1?f[g]=o[k]:f[g]=p(b)}}return i.pop(),o.pop(),f}}}),Gc=pe((l,e)=>{le(),ue(),ce(),e.exports=Vc()()}),as=pe(l=>{le(),ue(),ce(),Object.defineProperty(l,"__esModule",{value:!0}),l.validateTopic=e,l.validateTopics=t;function e(r){let s=r.split("/");for(let n=0;n<s.length;n++)if(s[n]!=="+"){if(s[n]==="#")return n===s.length-1;if(s[n].indexOf("+")!==-1||s[n].indexOf("#")!==-1)return!1}return!0}function t(r){if(r.length===0)return"empty_topic_list";for(let s=0;s<r.length;s++)if(!e(r[s]))return r[s];return null}}),ls=pe(l=>{le(),ue(),ce(),Object.defineProperty(l,"__esModule",{value:!0});var e=It(),t={objectMode:!0},r={clean:!0},s=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=[],o=!1,a=0;return this._inflights.forEach((c,u)=>{i.push(c)}),n._read=()=>{!o&&a<i.length?n.push(i[a++]):n.push(null)},n.destroy=c=>{if(!o)return o=!0,setTimeout(()=>{n.emit("close")},0),n},n}del(n,i){let o=this._inflights.get(n.messageId);return o?(this._inflights.delete(n.messageId),i(null,o)):i&&i(new Error("missing packet")),this}get(n,i){let o=this._inflights.get(n.messageId);return o?i(null,o):i&&i(new Error("missing packet")),this}close(n){this.options.clean&&(this._inflights=null),n&&n()}};l.default=s}),Kc=pe(l=>{le(),ue(),ce(),Object.defineProperty(l,"__esModule",{value:!0});var e=[0,16,128,131,135,144,145,151,153],t=(r,s,n)=>{r.log("handlePublish: packet %o",s),n=typeof n<"u"?n:r.noop;let i=s.topic.toString(),o=s.payload,{qos:a}=s,{messageId:c}=s,{options:u}=r;if(r.options.protocolVersion===5){let h;if(s.properties&&(h=s.properties.topicAlias),typeof h<"u")if(i.length===0)if(h>0&&h<=65535){let p=r.topicAliasRecv.getTopicByAlias(h);if(p)i=p,r.log("handlePublish :: topic complemented by alias. topic: %s - alias: %d",i,h);else{r.log("handlePublish :: unregistered topic alias. alias: %d",h),r.emit("error",new Error("Received unregistered Topic Alias"));return}}else{r.log("handlePublish :: topic alias out of range. alias: %d",h),r.emit("error",new Error("Received Topic Alias is out of range"));return}else if(r.topicAliasRecv.put(i,h))r.log("handlePublish :: registered topic: %s - alias: %d",i,h);else{r.log("handlePublish :: topic alias out of range. alias: %d",h),r.emit("error",new Error("Received Topic Alias is out of range"));return}}switch(r.log("handlePublish: qos %d",a),a){case 2:{u.customHandleAcks(i,o,s,(h,p)=>{if(typeof h=="number"&&(p=h,h=null),h)return r.emit("error",h);if(e.indexOf(p)===-1)return r.emit("error",new Error("Wrong reason code for pubrec"));p?r._sendPacket({cmd:"pubrec",messageId:c,reasonCode:p},n):r.incomingStore.put(s,()=>{r._sendPacket({cmd:"pubrec",messageId:c},n)})});break}case 1:{u.customHandleAcks(i,o,s,(h,p)=>{if(typeof h=="number"&&(p=h,h=null),h)return r.emit("error",h);if(e.indexOf(p)===-1)return r.emit("error",new Error("Wrong reason code for puback"));p||r.emit("message",i,o,s),r.handleMessage(s,y=>{if(y)return n&&n(y);r._sendPacket({cmd:"puback",messageId:c,reasonCode:p},n)})});break}case 0:r.emit("message",i,o,s),r.handleMessage(s,n);break;default:r.log("handlePublish: unknown QoS. Doing nothing.");break}};l.default=t}),Yc=pe((l,e)=>{e.exports={version:"5.15.0"}}),Ut=pe(l=>{le(),ue(),ce(),Object.defineProperty(l,"__esModule",{value:!0}),l.MQTTJS_VERSION=l.nextTick=l.ErrorWithSubackPacket=l.ErrorWithReasonCode=void 0,l.applyMixin=r;var e=class ec extends Error{code;constructor(n,i){super(n),this.code=i,Object.setPrototypeOf(this,ec.prototype),Object.getPrototypeOf(this).name="ErrorWithReasonCode"}};l.ErrorWithReasonCode=e;var t=class tc extends Error{packet;constructor(n,i){super(n),this.packet=i,Object.setPrototypeOf(this,tc.prototype),Object.getPrototypeOf(this).name="ErrorWithSubackPacket"}};l.ErrorWithSubackPacket=t;function r(s,n,i=!1){let o=[n];for(;;){let a=o[0],c=Object.getPrototypeOf(a);if(c?.prototype)o.unshift(c);else break}for(let a of o)for(let c of Object.getOwnPropertyNames(a.prototype))(i||c!=="constructor")&&Object.defineProperty(s.prototype,c,Object.getOwnPropertyDescriptor(a.prototype,c)??Object.create(null))}l.nextTick=typeof Le?.nextTick=="function"?Le.nextTick:s=>{setTimeout(s,0)},l.MQTTJS_VERSION=Yc().version}),dr=pe(l=>{le(),ue(),ce(),Object.defineProperty(l,"__esModule",{value:!0}),l.ReasonCodes=void 0;var e=Ut();l.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,s)=>{let{messageId:n}=s,i=s.cmd,o=null,a=r.outgoing[n]?r.outgoing[n].cb:null,c=null;if(!a){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=s.reasonCode;u&&u>0&&u!==16?(c=new e.ErrorWithReasonCode(`Publish error: ${l.ReasonCodes[u]}`,u),r._removeOutgoingAndStoreMessage(n,()=>{a(c,s)})):r._removeOutgoingAndStoreMessage(n,a);break}case"pubrec":{o={cmd:"pubrel",qos:2,messageId:n};let u=s.reasonCode;u&&u>0&&u!==16?(c=new e.ErrorWithReasonCode(`Publish error: ${l.ReasonCodes[u]}`,u),r._removeOutgoingAndStoreMessage(n,()=>{a(c,s)})):r._sendPacket(o);break}case"suback":{delete r.outgoing[n],r.messageIdProvider.deallocate(n);let u=s.granted;for(let h=0;h<u.length;h++){let p=u[h];if((p&128)!==0){c=new Error(`Subscribe error: ${l.ReasonCodes[p]}`),c.code=p;let y=r.messageIdToTopic[n];y&&y.forEach(f=>{delete r._resubscribeTopics[f]})}}delete r.messageIdToTopic[n],r._invokeStoreProcessingQueue(),a(c,s);break}case"unsuback":{delete r.outgoing[n],r.messageIdProvider.deallocate(n),r._invokeStoreProcessingQueue(),a(null,s);break}default:r.emit("error",new Error("unrecognized packet type"))}r.disconnecting&&Object.keys(r.outgoing).length===0&&r.emit("outgoingEmpty")};l.default=t}),Qc=pe(l=>{le(),ue(),ce(),Object.defineProperty(l,"__esModule",{value:!0});var e=Ut(),t=dr(),r=(s,n)=>{let{options:i}=s,o=i.protocolVersion,a=o===5?n.reasonCode:n.returnCode;if(o!==5){let c=new e.ErrorWithReasonCode(`Protocol error: Auth packets are only supported in MQTT 5. Your version:${o}`,a);s.emit("error",c);return}s.handleAuth(n,(c,u)=>{if(c){s.emit("error",c);return}if(a===24)s.reconnecting=!1,s._sendPacket(u);else{let h=new e.ErrorWithReasonCode(`Connection refused: ${t.ReasonCodes[a]}`,a);s.emit("error",h)}})};l.default=r}),Jc=pe(l=>{le(),ue(),ce(),Object.defineProperty(l,"__esModule",{value:!0}),l.LRUCache=void 0;var e=typeof performance=="object"&&performance&&typeof performance.now=="function"?performance:Date,t=new Set,r=typeof Le=="object"&&Le?Le:{},s=(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,s("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 o=y=>!t.has(y),a=y=>y&&y===Math.floor(y)&&y>0&&isFinite(y),c=y=>a(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)}},h=class nr{heap;length;static#l=!1;static create(f){let g=c(f);if(!g)return[];nr.#l=!0;let b=new nr(f,g);return nr.#l=!1,b}constructor(f,g){if(!nr.#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 rc{#l;#h;#m;#g;#O;#P;ttl;ttlResolution;ttlAutopurge;updateAgeOnGet;updateAgeOnHas;allowStale;noDisposeOnSet;noUpdateTTL;maxEntrySize;sizeCalculation;noDeleteOnFetchRejection;noDeleteOnStaleGet;allowStaleOnFetchAbort;allowStaleOnFetchRejection;ignoreFetchAbort;#i;#b;#n;#r;#e;#c;#d;#a;#o;#y;#s;#v;#w;#f;#_;#A;#u;static unsafeExposeInternals(f){return{starts:f.#w,ttls:f.#f,sizes:f.#v,keyMap:f.#n,keyList:f.#r,valList:f.#e,next:f.#c,prev:f.#d,get head(){return f.#a},get tail(){return f.#o},free:f.#y,isBackgroundFetch:g=>f.#t(g),backgroundFetch:(g,b,k,m)=>f.#L(g,b,k,m),moveToTail:g=>f.#C(g),indexes:g=>f.#k(g),rindexes:g=>f.#x(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.#m}get disposeAfter(){return this.#g}constructor(f){let{max:g=0,ttl:b,ttlResolution:k=1,ttlAutopurge:m,updateAgeOnGet:w,updateAgeOnHas:x,allowStale:v,dispose:E,disposeAfter:S,noDisposeOnSet:I,noUpdateTTL:O,maxSize:P=0,maxEntrySize:N=0,sizeCalculation:T,fetchMethod:q,memoMethod:D,noDeleteOnFetchRejection:U,noDeleteOnStaleGet:ae,allowStaleOnFetchRejection:Y,allowStaleOnFetchAbort:V,ignoreFetchAbort:re}=f;if(g!==0&&!a(g))throw new TypeError("max option must be a nonnegative integer");let F=g?c(g):Array;if(!F)throw new Error("invalid max value: "+g);if(this.#l=g,this.#h=P,this.maxEntrySize=N||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,q!==void 0&&typeof q!="function")throw new TypeError("fetchMethod must be a function if specified");if(this.#O=q,this.#A=!!q,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.#d=new F(g),this.#a=0,this.#o=0,this.#y=h.create(g),this.#i=0,this.#b=0,typeof E=="function"&&(this.#m=E),typeof S=="function"?(this.#g=S,this.#s=[]):(this.#g=void 0,this.#s=void 0),this.#_=!!this.#m,this.#u=!!this.#g,this.noDisposeOnSet=!!I,this.noUpdateTTL=!!O,this.noDeleteOnFetchRejection=!!U,this.allowStaleOnFetchRejection=!!Y,this.allowStaleOnFetchAbort=!!V,this.ignoreFetchAbort=!!re,this.maxEntrySize!==0){if(this.#h!==0&&!a(this.#h))throw new TypeError("maxSize must be a positive integer if specified");if(!a(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=!!x,this.ttlResolution=a(k)||k===0?k:1,this.ttlAutopurge=!!m,this.ttl=b||0,this.ttl){if(!a(this.ttl))throw new TypeError("ttl must be a positive integer if specified");this.#j()}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";o(Z)&&(t.add(Z),s("TTL caching without ttlAutopurge, max, or maxSize can result in unbounded memory consumption.","UnboundedCacheWarning",Z,rc))}}getRemainingTTL(f){return this.#n.has(f)?1/0:0}#j(){let f=new u(this.#l),g=new u(this.#l);this.#f=f,this.#w=g,this.#N=(m,w,x=e.now())=>{if(g[m]=w!==0?x:0,f[m]=w,w!==0&&this.ttlAutopurge){let v=setTimeout(()=>{this.#p(m)&&this.#S(this.#r[m],"expire")},w+1);v.unref&&v.unref()}},this.#I=m=>{g[m]=f[m]!==0?e.now():0},this.#E=(m,w)=>{if(f[w]){let x=f[w],v=g[w];if(!x||!v)return;m.ttl=x,m.start=v,m.now=b||k();let E=m.now-v;m.remainingTTL=x-E}};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 x=f[w],v=g[w];if(!x||!v)return 1/0;let E=(b||k())-v;return x-E},this.#p=m=>{let w=g[m],x=f[m];return!!x&&!!w&&(b||k())-w>x}}#I=()=>{};#E=()=>{};#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(!a(k))if(m){if(typeof m!="function")throw new TypeError("sizeCalculation must be a function");if(k=m(b,g),!a(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.#d[g]}*#x({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.#x())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.#x()){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.#x())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.#x()){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.#x({allowStale:!0}))this.#p(g)&&(this.#S(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.#f&&this.#w){let w=this.#f[g],x=this.#w[g];if(w&&x){let v=w-(e.now()-x);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.#f&&this.#w){w.ttl=this.#f[g];let x=e.now()-this.#w[g];w.start=Math.floor(Date.now()-x)}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:x=this.sizeCalculation,status:v}=b,{noUpdateTTL:E=this.noUpdateTTL}=b,S=this.#U(f,g,b.size||0,x);if(this.maxEntrySize&&S>this.maxEntrySize)return v&&(v.set="miss",v.maxEntrySizeExceeded=!0),this.#S(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.#d[I]=this.#o,this.#o=I,this.#i++,this.#M(I,S,v),v&&(v.set="add"),E=!1;else{this.#C(I);let O=this.#e[I];if(g!==O){if(this.#A&&this.#t(O)){O.__abortController.abort(new Error("replaced"));let{__staleWhileFetching:P}=O;P!==void 0&&!w&&(this.#_&&this.#m?.(P,f,"set"),this.#u&&this.#s?.push([P,f,"set"]))}else w||(this.#_&&this.#m?.(O,f,"set"),this.#u&&this.#s?.push([O,f,"set"]));if(this.#T(I),this.#M(I,S,v),this.#e[I]=g,v){v.set="replace";let P=O&&this.#t(O)?O.__staleWhileFetching:O;P!==void 0&&(v.oldValue=P)}}else v&&(v.set="update")}if(k!==0&&!this.#f&&this.#j(),this.#f&&(E||this.#N(I,k,m),v&&this.#E(v,I)),!w&&this.#u&&this.#s){let O=this.#s,P;for(;P=O?.shift();)this.#g?.(...P)}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.#g?.(...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.#m?.(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.#E(k,m));else return b&&this.#I(m),k&&(k.has="hit",this.#E(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}#L(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:x}=b;x?.addEventListener("abort",()=>w.abort(x.reason),{signal:w.signal});let v={signal:w.signal,options:b,context:k},E=(T,q=!1)=>{let{aborted:D}=w.signal,U=b.ignoreFetchAbort&&T!==void 0;if(b.status&&(D&&!q?(b.status.fetchAborted=!0,b.status.fetchError=w.signal.reason,U&&(b.status.fetchAbortIgnored=!0)):b.status.fetchResolved=!0),D&&!U&&!q)return I(w.signal.reason);let ae=P;return this.#e[g]===P&&(T===void 0?ae.__staleWhileFetching?this.#e[g]=ae.__staleWhileFetching:this.#S(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:q}=w.signal,D=q&&b.allowStaleOnFetchAbort,U=D||b.allowStaleOnFetchRejection,ae=U||b.noDeleteOnFetchRejection,Y=P;if(this.#e[g]===P&&(!ae||Y.__staleWhileFetching===void 0?this.#S(f,"fetch"):D||(this.#e[g]=Y.__staleWhileFetching)),U)return b.status&&Y.__staleWhileFetching!==void 0&&(b.status.returnedStale=!0),Y.__staleWhileFetching;if(Y.__returned===Y)throw T},O=(T,q)=>{let D=this.#O?.(f,m,v);D&&D instanceof Promise&&D.then(U=>T(U===void 0?void 0:U),q),w.signal.addEventListener("abort",()=>{(!b.ignoreFetchAbort||b.allowStaleOnFetchAbort)&&(T(void 0),b.allowStaleOnFetchAbort&&(T=U=>E(U,!0)))})};b.status&&(b.status.fetchDispatched=!0);let P=new Promise(O).then(E,S),N=Object.assign(P,{__abortController:w,__staleWhileFetching:m,__returned:void 0});return g===void 0?(this.set(f,N,{...v.options,status:void 0}),g=this.#n.get(f)):this.#e[g]=N,N}#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:x=this.noDisposeOnSet,size:v=0,sizeCalculation:E=this.sizeCalculation,noUpdateTTL:S=this.noUpdateTTL,noDeleteOnFetchRejection:I=this.noDeleteOnFetchRejection,allowStaleOnFetchRejection:O=this.allowStaleOnFetchRejection,ignoreFetchAbort:P=this.ignoreFetchAbort,allowStaleOnFetchAbort:N=this.allowStaleOnFetchAbort,context:T,forceRefresh:q=!1,status:D,signal:U}=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:x,size:v,sizeCalculation:E,noUpdateTTL:S,noDeleteOnFetchRejection:I,allowStaleOnFetchRejection:O,allowStaleOnFetchAbort:N,ignoreFetchAbort:P,status:D,signal:U},Y=this.#n.get(f);if(Y===void 0){D&&(D.fetch="miss");let V=this.#L(f,Y,ae,T);return V.__returned=V}else{let V=this.#e[Y];if(this.#t(V)){let M=b&&V.__staleWhileFetching!==void 0;return D&&(D.fetch="inflight",M&&(D.returnedStale=!0)),M?V.__staleWhileFetching:V.__returned=V}let re=this.#p(Y);if(!q&&!re)return D&&(D.fetch="hit"),this.#C(Y),k&&this.#I(Y),D&&this.#E(D,Y),V;let F=this.#L(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,x=this.get(f,w);if(!m&&x!==void 0)return x;let v=b(f,x,{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,x=this.#n.get(f);if(x!==void 0){let v=this.#e[x],E=this.#t(v);return w&&this.#E(w,x),this.#p(x)?(w&&(w.get="stale"),E?(w&&b&&v.__staleWhileFetching!==void 0&&(w.returnedStale=!0),b?v.__staleWhileFetching:void 0):(m||this.#S(f,"expire"),w&&b&&(w.returnedStale=!0),b?v:void 0)):(w&&(w.get="hit"),E?v.__staleWhileFetching:(this.#C(x),k&&this.#I(x),v))}else w&&(w.get="miss")}#D(f,g){this.#d[g]=f,this.#c[f]=g}#C(f){f!==this.#o&&(f===this.#a?this.#a=this.#c[f]:this.#D(this.#d[f],this.#c[f]),this.#D(this.#o,f),this.#o=f)}delete(f){return this.#S(f,"delete")}#S(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.#m?.(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.#d[k];else if(k===this.#a)this.#a=this.#c[k];else{let w=this.#d[k];this.#c[w]=this.#c[k];let x=this.#c[k];this.#d[x]=this.#d[k]}this.#i--,this.#y.push(k)}}if(this.#u&&this.#s?.length){let k=this.#s,m;for(;m=k?.shift();)this.#g?.(...m)}return b}clear(){return this.#F("delete")}#F(f){for(let g of this.#x({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.#m?.(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.#f&&this.#w&&(this.#f.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.#g?.(...b)}}};l.LRUCache=p}),dt=pe(l=>{le(),ue(),ce(),Object.defineProperty(l,"t",{value:!0}),l.ContainerIterator=l.Container=l.Base=void 0;var e=class{constructor(s=0){this.iteratorType=s}equals(s){return this.o===s.o}};l.ContainerIterator=e;var t=class{constructor(){this.i=0}get length(){return this.i}size(){return this.i}empty(){return this.i===0}};l.Base=t;var r=class extends t{};l.Container=r}),Xc=pe(l=>{le(),ue(),ce(),Object.defineProperty(l,"t",{value:!0}),l.default=void 0;var e=dt(),t=class extends e.Base{constructor(s=[]){super(),this.S=[];let n=this;s.forEach(function(i){n.push(i)})}clear(){this.i=0,this.S=[]}push(s){return this.S.push(s),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;l.default=r}),Zc=pe(l=>{le(),ue(),ce(),Object.defineProperty(l,"t",{value:!0}),l.default=void 0;var e=dt(),t=class extends e.Base{constructor(s=[]){super(),this.j=0,this.q=[];let n=this;s.forEach(function(i){n.push(i)})}clear(){this.q=[],this.i=this.j=0}push(s){let n=this.q.length;if(this.j/n>.5&&this.j+this.i>=n&&n>4096){let i=this.i;for(let o=0;o<i;++o)this.q[o]=this.q[this.j+o];this.j=0,this.q[this.i]=s}else this.q[this.j+this.i]=s;return++this.i}pop(){if(this.i===0)return;let s=this.q[this.j++];return this.i-=1,s}front(){if(this.i!==0)return this.q[this.j]}},r=t;l.default=r}),eu=pe(l=>{le(),ue(),ce(),Object.defineProperty(l,"t",{value:!0}),l.default=void 0;var e=dt(),t=class extends e.Base{constructor(s=[],n=function(o,a){return o>a?-1:o<a?1:0},i=!0){if(super(),this.v=n,Array.isArray(s))this.C=i?[...s]:s;else{this.C=[];let a=this;s.forEach(function(c){a.C.push(c)})}this.i=this.C.length;let o=this.i>>1;for(let a=this.i-1>>1;a>=0;--a)this.k(a,o)}m(s){let n=this.C[s];for(;s>0;){let i=s-1>>1,o=this.C[i];if(this.v(o,n)<=0)break;this.C[s]=o,s=i}this.C[s]=n}k(s,n){let i=this.C[s];for(;s<n;){let o=s<<1|1,a=o+1,c=this.C[o];if(a<this.i&&this.v(c,this.C[a])>0&&(o=a,c=this.C[a]),this.v(c,i)>=0)break;this.C[s]=c,s=o}this.C[s]=i}clear(){this.i=0,this.C.length=0}push(s){this.C.push(s),this.m(this.i),this.i+=1}pop(){if(this.i===0)return;let s=this.C[0],n=this.C.pop();return this.i-=1,this.i&&(this.C[0]=n,this.k(0,this.i>>1)),s}top(){return this.C[0]}find(s){return this.C.indexOf(s)>=0}remove(s){let n=this.C.indexOf(s);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(s){let n=this.C.indexOf(s);return n<0?!1:(this.m(n),this.k(n,this.i>>1),!0)}toArray(){return[...this.C]}},r=t;l.default=r}),hi=pe(l=>{le(),ue(),ce(),Object.defineProperty(l,"t",{value:!0}),l.default=void 0;var e=dt(),t=class extends e.Container{},r=t;l.default=r}),ft=pe(l=>{le(),ue(),ce(),Object.defineProperty(l,"t",{value:!0}),l.throwIteratorAccessError=e;function e(){throw new RangeError("Iterator access denied!")}}),cs=pe(l=>{le(),ue(),ce(),Object.defineProperty(l,"t",{value:!0}),l.RandomIterator=void 0;var e=dt(),t=ft(),r=class extends e.ContainerIterator{constructor(s,n){super(n),this.o=s,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(s){this.container.setElementByPos(this.o,s)}};l.RandomIterator=r}),tu=pe(l=>{le(),ue(),ce(),Object.defineProperty(l,"t",{value:!0}),l.default=void 0;var e=r(hi()),t=cs();function r(o){return o&&o.t?o:{default:o}}var s=class nc extends t.RandomIterator{constructor(a,c,u){super(a,u),this.container=c}copy(){return new nc(this.o,this.container,this.iteratorType)}},n=class extends e.default{constructor(o=[],a=!0){if(super(),Array.isArray(o))this.J=a?[...o]:o,this.i=o.length;else{this.J=[];let c=this;o.forEach(function(u){c.pushBack(u)})}}clear(){this.i=0,this.J.length=0}begin(){return new s(0,this)}end(){return new s(this.i,this)}rBegin(){return new s(this.i-1,this,1)}rEnd(){return new s(-1,this,1)}front(){return this.J[0]}back(){return this.J[this.i-1]}getElementByPos(o){if(o<0||o>this.i-1)throw new RangeError;return this.J[o]}eraseElementByPos(o){if(o<0||o>this.i-1)throw new RangeError;return this.J.splice(o,1),this.i-=1,this.i}eraseElementByValue(o){let a=0;for(let c=0;c<this.i;++c)this.J[c]!==o&&(this.J[a++]=this.J[c]);return this.i=this.J.length=a,this.i}eraseElementByIterator(o){let a=o.o;return o=o.next(),this.eraseElementByPos(a),o}pushBack(o){return this.J.push(o),this.i+=1,this.i}popBack(){if(this.i!==0)return this.i-=1,this.J.pop()}setElementByPos(o,a){if(o<0||o>this.i-1)throw new RangeError;this.J[o]=a}insert(o,a,c=1){if(o<0||o>this.i)throw new RangeError;return this.J.splice(o,0,...new Array(c).fill(a)),this.i+=c,this.i}find(o){for(let a=0;a<this.i;++a)if(this.J[a]===o)return new s(a,this);return this.end()}reverse(){this.J.reverse()}unique(){let o=1;for(let a=1;a<this.i;++a)this.J[a]!==this.J[a-1]&&(this.J[o++]=this.J[a]);return this.i=this.J.length=o,this.i}sort(o){this.J.sort(o)}forEach(o){for(let a=0;a<this.i;++a)o(this.J[a],a,this)}[Symbol.iterator](){return(function*(){yield*this.J}).bind(this)()}},i=n;l.default=i}),ru=pe(l=>{le(),ue(),ce(),Object.defineProperty(l,"t",{value:!0}),l.default=void 0;var e=s(hi()),t=dt(),r=ft();function s(a){return a&&a.t?a:{default:a}}var n=class ic extends t.ContainerIterator{constructor(c,u,h,p){super(p),this.o=c,this.h=u,this.container=h,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(c){this.o===this.h&&(0,r.throwIteratorAccessError)(),this.o.l=c}copy(){return new ic(this.o,this.h,this.container,this.iteratorType)}},i=class extends e.default{constructor(a=[]){super(),this.h={},this.p=this._=this.h.L=this.h.B=this.h;let c=this;a.forEach(function(u){c.pushBack(u)})}V(a){let{L:c,B:u}=a;c.B=u,u.L=c,a===this.p&&(this.p=u),a===this._&&(this._=c),this.i-=1}G(a,c){let u=c.B,h={l:a,L:c,B:u};c.B=h,u.L=h,c===this.h&&(this.p=h),u===this.h&&(this._=h),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(a){if(a<0||a>this.i-1)throw new RangeError;let c=this.p;for(;a--;)c=c.B;return c.l}eraseElementByPos(a){if(a<0||a>this.i-1)throw new RangeError;let c=this.p;for(;a--;)c=c.B;return this.V(c),this.i}eraseElementByValue(a){let c=this.p;for(;c!==this.h;)c.l===a&&this.V(c),c=c.B;return this.i}eraseElementByIterator(a){let c=a.o;return c===this.h&&(0,r.throwIteratorAccessError)(),a=a.next(),this.V(c),a}pushBack(a){return this.G(a,this._),this.i}popBack(){if(this.i===0)return;let a=this._.l;return this.V(this._),a}pushFront(a){return this.G(a,this.h),this.i}popFront(){if(this.i===0)return;let a=this.p.l;return this.V(this.p),a}setElementByPos(a,c){if(a<0||a>this.i-1)throw new RangeError;let u=this.p;for(;a--;)u=u.B;u.l=c}insert(a,c,u=1){if(a<0||a>this.i)throw new RangeError;if(u<=0)return this.i;if(a===0)for(;u--;)this.pushFront(c);else if(a===this.i)for(;u--;)this.pushBack(c);else{let h=this.p;for(let y=1;y<a;++y)h=h.B;let p=h.B;for(this.i+=u;u--;)h.B={l:c,L:h},h.B.L=h,h=h.B;h.B=p,p.L=h}return this.i}find(a){let c=this.p;for(;c!==this.h;){if(c.l===a)return new n(c,this.h,this);c=c.B}return this.end()}reverse(){if(this.i<=1)return;let a=this.p,c=this._,u=0;for(;u<<1<this.i;){let h=a.l;a.l=c.l,c.l=h,a=a.B,c=c.L,u+=1}}unique(){if(this.i<=1)return this.i;let a=this.p;for(;a!==this.h;){let c=a;for(;c.B!==this.h&&c.l===c.B.l;)c=c.B,this.i-=1;a.B=c.B,a.B.L=a,a=a.B}return this.i}sort(a){if(this.i<=1)return;let c=[];this.forEach(function(h){c.push(h)}),c.sort(a);let u=this.p;c.forEach(function(h){u.l=h,u=u.B})}merge(a){let c=this;if(this.i===0)a.forEach(function(u){c.pushBack(u)});else{let u=this.p;a.forEach(function(h){for(;u!==c.h&&u.l<=h;)u=u.B;c.G(h,u.L)})}return this.i}forEach(a){let c=this.p,u=0;for(;c!==this.h;)a(c.l,u++,this),c=c.B}[Symbol.iterator](){return(function*(){if(this.i===0)return;let a=this.p;for(;a!==this.h;)yield a.l,a=a.B}).bind(this)()}},o=i;l.default=o}),nu=pe(l=>{le(),ue(),ce(),Object.defineProperty(l,"t",{value:!0}),l.default=void 0;var e=r(hi()),t=cs();function r(o){return o&&o.t?o:{default:o}}var s=class oc extends t.RandomIterator{constructor(a,c,u){super(a,u),this.container=c}copy(){return new oc(this.o,this.container,this.iteratorType)}},n=class extends e.default{constructor(o=[],a=4096){super(),this.j=0,this.D=0,this.R=0,this.N=0,this.P=0,this.A=[];let c=(()=>{if(typeof o.length=="number")return o.length;if(typeof o.size=="number")return o.size;if(typeof o.size=="function")return o.size();throw new TypeError("Cannot get the length or size of the container")})();this.F=a,this.P=Math.max(Math.ceil(c/this.F),1);for(let p=0;p<this.P;++p)this.A.push(new Array(this.F));let u=Math.ceil(c/this.F);this.j=this.R=(this.P>>1)-(u>>1),this.D=this.N=this.F-c%this.F>>1;let h=this;o.forEach(function(p){h.pushBack(p)})}T(){let o=[],a=Math.max(this.P>>1,1);for(let c=0;c<a;++c)o[c]=new Array(this.F);for(let c=this.j;c<this.P;++c)o[o.length]=this.A[c];for(let c=0;c<this.R;++c)o[o.length]=this.A[c];o[o.length]=[...this.A[this.R]],this.j=a,this.R=o.length-1;for(let c=0;c<a;++c)o[o.length]=new Array(this.F);this.A=o,this.P=o.length}O(o){let a=this.D+o+1,c=a%this.F,u=c-1,h=this.j+(a-c)/this.F;return c===0&&(h-=1),h%=this.P,u<0&&(u+=this.F),{curNodeBucketIndex:h,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 s(0,this)}end(){return new s(this.i,this)}rBegin(){return new s(this.i-1,this,1)}rEnd(){return new s(-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(o){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]=o,this.i}popBack(){if(this.i===0)return;let o=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,o}pushFront(o){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]=o,this.i}popFront(){if(this.i===0)return;let o=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,o}getElementByPos(o){if(o<0||o>this.i-1)throw new RangeError;let{curNodeBucketIndex:a,curNodePointerIndex:c}=this.O(o);return this.A[a][c]}setElementByPos(o,a){if(o<0||o>this.i-1)throw new RangeError;let{curNodeBucketIndex:c,curNodePointerIndex:u}=this.O(o);this.A[c][u]=a}insert(o,a,c=1){if(o<0||o>this.i)throw new RangeError;if(o===0)for(;c--;)this.pushFront(a);else if(o===this.i)for(;c--;)this.pushBack(a);else{let u=[];for(let h=o;h<this.i;++h)u.push(this.getElementByPos(h));this.cut(o-1);for(let h=0;h<c;++h)this.pushBack(a);for(let h=0;h<u.length;++h)this.pushBack(u[h])}return this.i}cut(o){if(o<0)return this.clear(),0;let{curNodeBucketIndex:a,curNodePointerIndex:c}=this.O(o);return this.R=a,this.N=c,this.i=o+1,this.i}eraseElementByPos(o){if(o<0||o>this.i-1)throw new RangeError;if(o===0)this.popFront();else if(o===this.i-1)this.popBack();else{let a=[];for(let u=o+1;u<this.i;++u)a.push(this.getElementByPos(u));this.cut(o),this.popBack();let c=this;a.forEach(function(u){c.pushBack(u)})}return this.i}eraseElementByValue(o){if(this.i===0)return 0;let a=[];for(let u=0;u<this.i;++u){let h=this.getElementByPos(u);h!==o&&a.push(h)}let c=a.length;for(let u=0;u<c;++u)this.setElementByPos(u,a[u]);return this.cut(c-1)}eraseElementByIterator(o){let a=o.o;return this.eraseElementByPos(a),o=o.next(),o}find(o){for(let a=0;a<this.i;++a)if(this.getElementByPos(a)===o)return new s(a,this);return this.end()}reverse(){let o=0,a=this.i-1;for(;o<a;){let c=this.getElementByPos(o);this.setElementByPos(o,this.getElementByPos(a)),this.setElementByPos(a,c),o+=1,a-=1}}unique(){if(this.i<=1)return this.i;let o=1,a=this.getElementByPos(0);for(let c=1;c<this.i;++c){let u=this.getElementByPos(c);u!==a&&(a=u,this.setElementByPos(o++,u))}for(;this.i>o;)this.popBack();return this.i}sort(o){let a=[];for(let c=0;c<this.i;++c)a.push(this.getElementByPos(c));a.sort(o);for(let c=0;c<this.i;++c)this.setElementByPos(c,a[c])}shrinkToFit(){if(this.i===0)return;let o=[];this.forEach(function(a){o.push(a)}),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 a=0;a<this.P;++a)this.A.push(new Array(this.F));for(let a=0;a<o.length;++a)this.pushBack(o[a])}forEach(o){for(let a=0;a<this.i;++a)o(this.getElementByPos(a),a,this)}[Symbol.iterator](){return(function*(){for(let o=0;o<this.i;++o)yield this.getElementByPos(o)}).bind(this)()}},i=n;l.default=i}),iu=pe(l=>{le(),ue(),ce(),Object.defineProperty(l,"t",{value:!0}),l.TreeNodeEnableIndex=l.TreeNode=void 0;var e=class{constructor(r,s){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=s}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 s=r.tt;for(;s.U===r;)r=s,s=r.tt;r=s}return r}B(){let r=this;if(r.W){for(r=r.W;r.U;)r=r.U;return r}else{let s=r.tt;for(;s.W===r;)r=s,s=r.tt;return r.W!==s?s:r}}te(){let r=this.tt,s=this.W,n=s.U;return r.tt===this?r.tt=s:r.U===this?r.U=s:r.W=s,s.tt=r,s.U=this,this.tt=s,this.W=n,n&&(n.tt=this),s}se(){let r=this.tt,s=this.U,n=s.W;return r.tt===this?r.tt=s:r.U===this?r.U=s:r.W=s,s.tt=r,s.W=this,this.tt=s,this.U=n,n&&(n.tt=this),s}};l.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)}};l.TreeNodeEnableIndex=t}),us=pe(l=>{le(),ue(),ce(),Object.defineProperty(l,"t",{value:!0}),l.default=void 0;var e=iu(),t=dt(),r=ft(),s=class extends t.Container{constructor(i=function(a,c){return a<c?-1:a>c?1:0},o=!1){super(),this.Y=void 0,this.v=i,o?(this.re=e.TreeNodeEnableIndex,this.M=function(a,c,u){let h=this.ne(a,c,u);if(h){let p=h.tt;for(;p!==this.h;)p.rt+=1,p=p.tt;let y=this.he(h);if(y){let{parentNode:f,grandParent:g,curNode:b}=y;f.ie(),g.ie(),b.ie()}}return this.i},this.V=function(a){let c=this.fe(a);for(;c!==this.h;)c.rt-=1,c=c.tt}):(this.re=e.TreeNode,this.M=function(a,c,u){let h=this.ne(a,c,u);return h&&this.he(h),this.i},this.V=this.fe),this.h=new this.re}X(i,o){let a=this.h;for(;i;){let c=this.v(i.u,o);if(c<0)i=i.W;else if(c>0)a=i,i=i.U;else return i}return a}Z(i,o){let a=this.h;for(;i;)this.v(i.u,o)<=0?i=i.W:(a=i,i=i.U);return a}$(i,o){let a=this.h;for(;i;){let c=this.v(i.u,o);if(c<0)a=i,i=i.W;else if(c>0)i=i.U;else return i}return a}rr(i,o){let a=this.h;for(;i;)this.v(i.u,o)<0?(a=i,i=i.W):i=i.U;return a}ue(i){for(;;){let o=i.tt;if(o===this.h)return;if(i.ee===1){i.ee=0;return}if(i===o.U){let a=o.W;if(a.ee===1)a.ee=0,o.ee=1,o===this.Y?this.Y=o.te():o.te();else if(a.W&&a.W.ee===1){a.ee=o.ee,o.ee=0,a.W.ee=0,o===this.Y?this.Y=o.te():o.te();return}else a.U&&a.U.ee===1?(a.ee=1,a.U.ee=0,a.se()):(a.ee=1,i=o)}else{let a=o.U;if(a.ee===1)a.ee=0,o.ee=1,o===this.Y?this.Y=o.se():o.se();else if(a.U&&a.U.ee===1){a.ee=o.ee,o.ee=0,a.U.ee=0,o===this.Y?this.Y=o.se():o.se();return}else a.W&&a.W.ee===1?(a.ee=1,a.W.ee=0,a.te()):(a.ee=1,i=o)}}}fe(i){if(this.i===1)return this.clear(),this.h;let o=i;for(;o.U||o.W;){if(o.W)for(o=o.W;o.U;)o=o.U;else o=o.U;[i.u,o.u]=[o.u,i.u],[i.l,o.l]=[o.l,i.l],i=o}this.h.U===o?this.h.U=o.tt:this.h.W===o&&(this.h.W=o.tt),this.ue(o);let a=o.tt;return o===a.U?a.U=void 0:a.W=void 0,this.i-=1,this.Y.ee=0,a}oe(i,o){return i===void 0?!1:this.oe(i.U,o)||o(i)?!0:this.oe(i.W,o)}he(i){for(;;){let o=i.tt;if(o.ee===0)return;let a=o.tt;if(o===a.U){let c=a.W;if(c&&c.ee===1){if(c.ee=o.ee=0,a===this.Y)return;a.ee=1,i=a;continue}else if(i===o.W){if(i.ee=0,i.U&&(i.U.tt=o),i.W&&(i.W.tt=a),o.W=i.U,a.U=i.W,i.U=o,i.W=a,a===this.Y)this.Y=i,this.h.tt=i;else{let u=a.tt;u.U===a?u.U=i:u.W=i}return i.tt=a.tt,o.tt=i,a.tt=i,a.ee=1,{parentNode:o,grandParent:a,curNode:i}}else o.ee=0,a===this.Y?this.Y=a.se():a.se(),a.ee=1}else{let c=a.U;if(c&&c.ee===1){if(c.ee=o.ee=0,a===this.Y)return;a.ee=1,i=a;continue}else if(i===o.U){if(i.ee=0,i.U&&(i.U.tt=a),i.W&&(i.W.tt=o),a.W=i.U,o.U=i.W,i.U=a,i.W=o,a===this.Y)this.Y=i,this.h.tt=i;else{let u=a.tt;u.U===a?u.U=i:u.W=i}return i.tt=a.tt,o.tt=i,a.tt=i,a.ee=1,{parentNode:o,grandParent:a,curNode:i}}else o.ee=0,a===this.Y?this.Y=a.te():a.te(),a.ee=1}return}}ne(i,o,a){if(this.Y===void 0){this.i+=1,this.Y=new this.re(i,o),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 c,u=this.h.U,h=this.v(u.u,i);if(h===0){u.l=o;return}else if(h>0)u.U=new this.re(i,o),u.U.tt=u,c=u.U,this.h.U=c;else{let p=this.h.W,y=this.v(p.u,i);if(y===0){p.l=o;return}else if(y<0)p.W=new this.re(i,o),p.W.tt=p,c=p.W,this.h.W=c;else{if(a!==void 0){let f=a.o;if(f!==this.h){let g=this.v(f.u,i);if(g===0){f.l=o;return}else if(g>0){let b=f.L(),k=this.v(b.u,i);if(k===0){b.l=o;return}else k<0&&(c=new this.re(i,o),b.W===void 0?(b.W=c,c.tt=b):(f.U=c,c.tt=f))}}}if(c===void 0)for(c=this.Y;;){let f=this.v(c.u,i);if(f>0){if(c.U===void 0){c.U=new this.re(i,o),c.U.tt=c,c=c.U;break}c=c.U}else if(f<0){if(c.W===void 0){c.W=new this.re(i,o),c.W.tt=c,c=c.W;break}c=c.W}else{c.l=o;return}}}}return this.i+=1,c}I(i,o){for(;i;){let a=this.v(i.u,o);if(a<0)i=i.W;else if(a>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,o){let a=i.o;if(a===this.h&&(0,r.throwIteratorAccessError)(),this.i===1)return a.u=o,!0;if(a===this.h.U)return this.v(a.B().u,o)>0?(a.u=o,!0):!1;if(a===this.h.W)return this.v(a.L().u,o)<0?(a.u=o,!0):!1;let c=a.L().u;if(this.v(c,o)>=0)return!1;let u=a.B().u;return this.v(u,o)<=0?!1:(a.u=o,!0)}eraseElementByPos(i){if(i<0||i>this.i-1)throw new RangeError;let o=0,a=this;return this.oe(this.Y,function(c){return i===o?(a.V(c),!0):(o+=1,!1)}),this.i}eraseElementByKey(i){if(this.i===0)return!1;let o=this.I(this.Y,i);return o===this.h?!1:(this.V(o),!0)}eraseElementByIterator(i){let o=i.o;o===this.h&&(0,r.throwIteratorAccessError)();let a=o.W===void 0;return i.iteratorType===0?a&&i.next():(!a||o.U===void 0)&&i.next(),this.V(o),i}forEach(i){let o=0;for(let a of this)i(a,o++,this)}getElementByPos(i){if(i<0||i>this.i-1)throw new RangeError;let o,a=0;for(let c of this){if(a===i){o=c;break}a+=1}return o}getHeight(){if(this.i===0)return 0;let i=function(o){return o?Math.max(i(o.U),i(o.W))+1:0};return i(this.Y)}},n=s;l.default=n}),hs=pe(l=>{le(),ue(),ce(),Object.defineProperty(l,"t",{value:!0}),l.default=void 0;var e=dt(),t=ft(),r=class extends e.ContainerIterator{constructor(n,i,o){super(o),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 o=0;for(n.U&&(o+=n.U.rt);n!==i;){let a=n.tt;n===a.W&&(o+=1,a.U&&(o+=a.U.rt)),n=a}return o}},s=r;l.default=s}),ou=pe(l=>{le(),ue(),ce(),Object.defineProperty(l,"t",{value:!0}),l.default=void 0;var e=s(us()),t=s(hs()),r=ft();function s(a){return a&&a.t?a:{default:a}}var n=class sc extends t.default{constructor(c,u,h,p){super(c,u,p),this.container=h}get pointer(){return this.o===this.h&&(0,r.throwIteratorAccessError)(),this.o.u}copy(){return new sc(this.o,this.h,this.container,this.iteratorType)}},i=class extends e.default{constructor(a=[],c,u){super(c,u);let h=this;a.forEach(function(p){h.insert(p)})}*K(a){a!==void 0&&(yield*this.K(a.U),yield a.u,yield*this.K(a.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(a,c){return this.M(a,void 0,c)}find(a){let c=this.I(this.Y,a);return new n(c,this.h,this)}lowerBound(a){let c=this.X(this.Y,a);return new n(c,this.h,this)}upperBound(a){let c=this.Z(this.Y,a);return new n(c,this.h,this)}reverseLowerBound(a){let c=this.$(this.Y,a);return new n(c,this.h,this)}reverseUpperBound(a){let c=this.rr(this.Y,a);return new n(c,this.h,this)}union(a){let c=this;return a.forEach(function(u){c.insert(u)}),this.i}[Symbol.iterator](){return this.K(this.Y)}},o=i;l.default=o}),su=pe(l=>{le(),ue(),ce(),Object.defineProperty(l,"t",{value:!0}),l.default=void 0;var e=s(us()),t=s(hs()),r=ft();function s(a){return a&&a.t?a:{default:a}}var n=class ac extends t.default{constructor(c,u,h,p){super(c,u,p),this.container=h}get pointer(){this.o===this.h&&(0,r.throwIteratorAccessError)();let c=this;return new Proxy([],{get(u,h){if(h==="0")return c.o.u;if(h==="1")return c.o.l},set(u,h,p){if(h!=="1")throw new TypeError("props must be 1");return c.o.l=p,!0}})}copy(){return new ac(this.o,this.h,this.container,this.iteratorType)}},i=class extends e.default{constructor(a=[],c,u){super(c,u);let h=this;a.forEach(function(p){h.setElement(p[0],p[1])})}*K(a){a!==void 0&&(yield*this.K(a.U),yield[a.u,a.l],yield*this.K(a.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 a=this.h.U;return[a.u,a.l]}back(){if(this.i===0)return;let a=this.h.W;return[a.u,a.l]}lowerBound(a){let c=this.X(this.Y,a);return new n(c,this.h,this)}upperBound(a){let c=this.Z(this.Y,a);return new n(c,this.h,this)}reverseLowerBound(a){let c=this.$(this.Y,a);return new n(c,this.h,this)}reverseUpperBound(a){let c=this.rr(this.Y,a);return new n(c,this.h,this)}setElement(a,c,u){return this.M(a,c,u)}find(a){let c=this.I(this.Y,a);return new n(c,this.h,this)}getElementByKey(a){return this.I(this.Y,a).l}union(a){let c=this;return a.forEach(function(u){c.setElement(u[0],u[1])}),this.i}[Symbol.iterator](){return this.K(this.Y)}},o=i;l.default=o}),ds=pe(l=>{le(),ue(),ce(),Object.defineProperty(l,"t",{value:!0}),l.default=e;function e(t){let r=typeof t;return r==="object"&&t!==null||r==="function"}}),fs=pe(l=>{le(),ue(),ce(),Object.defineProperty(l,"t",{value:!0}),l.HashContainerIterator=l.HashContainer=void 0;var e=dt(),t=s(ds()),r=ft();function s(o){return o&&o.t?o:{default:o}}var n=class extends e.ContainerIterator{constructor(o,a,c){super(c),this.o=o,this.h=a,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})}};l.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(o){let{L:a,B:c}=o;a.B=c,c.L=a,o===this.p&&(this.p=c),o===this._&&(this._=a),this.i-=1}M(o,a,c){c===void 0&&(c=(0,t.default)(o));let u;if(c){let h=o[this.HASH_TAG];if(h!==void 0)return this.H[h].l=a,this.i;Object.defineProperty(o,this.HASH_TAG,{value:this.H.length,configurable:!0}),u={u:o,l:a,L:this._,B:this.h},this.H.push(u)}else{let h=this.g[o];if(h)return h.l=a,this.i;u={u:o,l:a,L:this._,B:this.h},this.g[o]=u}return this.i===0?(this.p=u,this.h.B=u):this._.B=u,this._=u,this.h.L=u,++this.i}I(o,a){if(a===void 0&&(a=(0,t.default)(o)),a){let c=o[this.HASH_TAG];return c===void 0?this.h:this.H[c]}else return this.g[o]||this.h}clear(){let o=this.HASH_TAG;this.H.forEach(function(a){delete a.u[o]}),this.H=[],this.g={},Object.setPrototypeOf(this.g,null),this.i=0,this.p=this._=this.h.L=this.h.B=this.h}eraseElementByKey(o,a){let c;if(a===void 0&&(a=(0,t.default)(o)),a){let u=o[this.HASH_TAG];if(u===void 0)return!1;delete o[this.HASH_TAG],c=this.H[u],delete this.H[u]}else{if(c=this.g[o],c===void 0)return!1;delete this.g[o]}return this.V(c),!0}eraseElementByIterator(o){let a=o.o;return a===this.h&&(0,r.throwIteratorAccessError)(),this.V(a),o.next()}eraseElementByPos(o){if(o<0||o>this.i-1)throw new RangeError;let a=this.p;for(;o--;)a=a.B;return this.V(a),this.i}};l.HashContainer=i}),au=pe(l=>{le(),ue(),ce(),Object.defineProperty(l,"t",{value:!0}),l.default=void 0;var e=fs(),t=ft(),r=class lc extends e.HashContainerIterator{constructor(o,a,c,u){super(o,a,u),this.container=c}get pointer(){return this.o===this.h&&(0,t.throwIteratorAccessError)(),this.o.u}copy(){return new lc(this.o,this.h,this.container,this.iteratorType)}},s=class extends e.HashContainer{constructor(i=[]){super();let o=this;i.forEach(function(a){o.insert(a)})}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,o){return this.M(i,void 0,o)}getElementByPos(i){if(i<0||i>this.i-1)throw new RangeError;let o=this.p;for(;i--;)o=o.B;return o.u}find(i,o){let a=this.I(i,o);return new r(a,this.h,this)}forEach(i){let o=0,a=this.p;for(;a!==this.h;)i(a.u,o++,this),a=a.B}[Symbol.iterator](){return(function*(){let i=this.p;for(;i!==this.h;)yield i.u,i=i.B}).bind(this)()}},n=s;l.default=n}),lu=pe(l=>{le(),ue(),ce(),Object.defineProperty(l,"t",{value:!0}),l.default=void 0;var e=fs(),t=s(ds()),r=ft();function s(a){return a&&a.t?a:{default:a}}var n=class cc extends e.HashContainerIterator{constructor(c,u,h,p){super(c,u,p),this.container=h}get pointer(){this.o===this.h&&(0,r.throwIteratorAccessError)();let c=this;return new Proxy([],{get(u,h){if(h==="0")return c.o.u;if(h==="1")return c.o.l},set(u,h,p){if(h!=="1")throw new TypeError("props must be 1");return c.o.l=p,!0}})}copy(){return new cc(this.o,this.h,this.container,this.iteratorType)}},i=class extends e.HashContainer{constructor(a=[]){super();let c=this;a.forEach(function(u){c.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(a,c,u){return this.M(a,c,u)}getElementByKey(a,c){if(c===void 0&&(c=(0,t.default)(a)),c){let h=a[this.HASH_TAG];return h!==void 0?this.H[h].l:void 0}let u=this.g[a];return u?u.l:void 0}getElementByPos(a){if(a<0||a>this.i-1)throw new RangeError;let c=this.p;for(;a--;)c=c.B;return[c.u,c.l]}find(a,c){let u=this.I(a,c);return new n(u,this.h,this)}forEach(a){let c=0,u=this.p;for(;u!==this.h;)a([u.u,u.l],c++,this),u=u.B}[Symbol.iterator](){return(function*(){let a=this.p;for(;a!==this.h;)yield[a.u,a.l],a=a.B}).bind(this)()}},o=i;l.default=o}),cu=pe(l=>{le(),ue(),ce(),Object.defineProperty(l,"t",{value:!0}),Object.defineProperty(l,"Deque",{enumerable:!0,get:function(){return i.default}}),Object.defineProperty(l,"HashMap",{enumerable:!0,get:function(){return u.default}}),Object.defineProperty(l,"HashSet",{enumerable:!0,get:function(){return c.default}}),Object.defineProperty(l,"LinkList",{enumerable:!0,get:function(){return n.default}}),Object.defineProperty(l,"OrderedMap",{enumerable:!0,get:function(){return a.default}}),Object.defineProperty(l,"OrderedSet",{enumerable:!0,get:function(){return o.default}}),Object.defineProperty(l,"PriorityQueue",{enumerable:!0,get:function(){return r.default}}),Object.defineProperty(l,"Queue",{enumerable:!0,get:function(){return t.default}}),Object.defineProperty(l,"Stack",{enumerable:!0,get:function(){return e.default}}),Object.defineProperty(l,"Vector",{enumerable:!0,get:function(){return s.default}});var e=h(Xc()),t=h(Zc()),r=h(eu()),s=h(tu()),n=h(ru()),i=h(nu()),o=h(ou()),a=h(su()),c=h(au()),u=h(lu());function h(p){return p&&p.t?p:{default:p}}}),uu=pe((l,e)=>{le(),ue(),ce();var t=cu().OrderedSet,r=ht()("number-allocator:trace"),s=ht()("number-allocator:error");function n(o,a){this.low=o,this.high=a}n.prototype.equals=function(o){return this.low===o.low&&this.high===o.high},n.prototype.compare=function(o){return this.low<o.low&&this.high<o.low?-1:o.low<this.low&&o.high<this.low?1:0};function i(o,a){if(!(this instanceof i))return new i(o,a);this.min=o,this.max=a,this.ss=new t([],(c,u)=>c.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 o=this.ss.begin(),a=o.pointer.low,c=o.pointer.high,u=a;return u+1<=c?this.ss.updateKeyByIterator(o,new n(a+1,c)):this.ss.eraseElementByPos(0),r("alloc():"+u),u},i.prototype.use=function(o){let a=new n(o,o),c=this.ss.lowerBound(a);if(!c.equals(this.ss.end())){let u=c.pointer.low,h=c.pointer.high;return c.pointer.equals(a)?(this.ss.eraseElementByIterator(c),r("use():"+o),!0):u>o?!1:u===o?(this.ss.updateKeyByIterator(c,new n(u+1,h)),r("use():"+o),!0):h===o?(this.ss.updateKeyByIterator(c,new n(u,h-1)),r("use():"+o),!0):(this.ss.updateKeyByIterator(c,new n(o+1,h)),this.ss.insert(new n(u,o-1)),r("use():"+o),!0)}return r("use():failed"),!1},i.prototype.free=function(o){if(o<this.min||o>this.max){s("free():"+o+" is out of range");return}let a=new n(o,o),c=this.ss.upperBound(a);if(c.equals(this.ss.end())){if(c.equals(this.ss.begin())){this.ss.insert(a);return}c.pre();let u=c.pointer.high;c.pointer.high+1===o?this.ss.updateKeyByIterator(c,new n(u,o)):this.ss.insert(a)}else if(c.equals(this.ss.begin()))if(o+1===c.pointer.low){let u=c.pointer.high;this.ss.updateKeyByIterator(c,new n(o,u))}else this.ss.insert(a);else{let u=c.pointer.low,h=c.pointer.high;c.pre();let p=c.pointer.low;c.pointer.high+1===o?o+1===u?(this.ss.eraseElementByIterator(c),this.ss.updateKeyByIterator(c,new n(p,h))):this.ss.updateKeyByIterator(c,new n(p,o)):o+1===u?(this.ss.eraseElementByIterator(c.next()),this.ss.insert(new n(o,h))):this.ss.insert(a)}r("free():"+o)},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 o of this.ss)console.log(o)},e.exports=i}),ps=pe((l,e)=>{le(),ue(),ce();var t=uu();e.exports.NumberAllocator=t}),hu=pe(l=>{le(),ue(),ce(),Object.defineProperty(l,"__esModule",{value:!0});var e=Jc(),t=ps(),r=class{aliasToTopic;topicToAlias;max;numberAllocator;length;constructor(s){s>0&&(this.aliasToTopic=new e.LRUCache({max:s}),this.topicToAlias={},this.numberAllocator=new t.NumberAllocator(1,s),this.max=s,this.length=0)}put(s,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,s),this.topicToAlias[s]=n,this.numberAllocator.use(n),this.length=this.aliasToTopic.size,!0}getTopicByAlias(s){return this.aliasToTopic.get(s)}getAliasByTopic(s){let n=this.topicToAlias[s];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]}};l.default=r}),du=pe(l=>{le(),ue(),ce();var e=l&&l.__importDefault||function(i){return i&&i.__esModule?i:{default:i}};Object.defineProperty(l,"__esModule",{value:!0});var t=dr(),r=e(hu()),s=Ut(),n=(i,o)=>{i.log("_handleConnack");let{options:a}=i,c=a.protocolVersion===5?o.reasonCode:o.returnCode;if(clearTimeout(i.connackTimer),delete i.topicAliasSend,o.properties){if(o.properties.topicAliasMaximum){if(o.properties.topicAliasMaximum>65535){i.emit("error",new Error("topicAliasMaximum from broker is out of range"));return}o.properties.topicAliasMaximum>0&&(i.topicAliasSend=new r.default(o.properties.topicAliasMaximum))}o.properties.serverKeepAlive&&a.keepalive&&(a.keepalive=o.properties.serverKeepAlive),o.properties.maximumPacketSize&&(a.properties||(a.properties={}),a.properties.maximumPacketSize=o.properties.maximumPacketSize)}if(c===0)i.reconnecting=!1,i._onConnect(o);else if(c>0){let u=new s.ErrorWithReasonCode(`Connection refused: ${t.ReasonCodes[c]}`,c);i.emit("error",u),i.options.reconnectOnConnackError&&i._cleanUp(!0)}};l.default=n}),fu=pe(l=>{le(),ue(),ce(),Object.defineProperty(l,"__esModule",{value:!0});var e=(t,r,s)=>{t.log("handling pubrel packet");let n=typeof s<"u"?s:t.noop,{messageId:i}=r,o={cmd:"pubcomp",messageId:i};t.incomingStore.get(r,(a,c)=>{a?t._sendPacket(o,n):(t.emit("message",c.topic,c.payload,c),t.handleMessage(c,u=>{if(u)return n(u);t.incomingStore.del(c,t.noop),t._sendPacket(o,n)}))})};l.default=e}),pu=pe(l=>{le(),ue(),ce();var e=l&&l.__importDefault||function(a){return a&&a.__esModule?a:{default:a}};Object.defineProperty(l,"__esModule",{value:!0});var t=e(Kc()),r=e(Qc()),s=e(du()),n=e(dr()),i=e(fu()),o=(a,c,u)=>{let{options:h}=a;if(h.protocolVersion===5&&h.properties&&h.properties.maximumPacketSize&&h.properties.maximumPacketSize<c.length)return a.emit("error",new Error(`exceeding packets size ${c.cmd}`)),a.end({reasonCode:149,properties:{reasonString:"Maximum packet size was exceeded"}}),a;switch(a.log("_handlePacket :: emitting packetreceive"),a.emit("packetreceive",c),c.cmd){case"publish":(0,t.default)(a,c,u);break;case"puback":case"pubrec":case"pubcomp":case"suback":case"unsuback":a.reschedulePing(),(0,n.default)(a,c),u();break;case"pubrel":a.reschedulePing(),(0,i.default)(a,c,u);break;case"connack":(0,s.default)(a,c),u();break;case"auth":a.reschedulePing(),(0,r.default)(a,c),u();break;case"pingresp":a.log("_handlePacket :: received pingresp"),a.reschedulePing(!0),u();break;case"disconnect":a.emit("disconnect",c),u();break;default:a.log("_handlePacket :: unknown command"),u();break}};l.default=o}),ms=pe(l=>{le(),ue(),ce(),Object.defineProperty(l,"__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(){}};l.default=e}),mu=pe(l=>{le(),ue(),ce(),Object.defineProperty(l,"__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={}}};l.default=e}),gu=pe(l=>{le(),ue(),ce();var e=l&&l.__importDefault||function(n){return n&&n.__esModule?n:{default:n}};Object.defineProperty(l,"__esModule",{value:!0}),l.TypedEventEmitter=void 0;var t=e((Et(),Me(bt))),r=Ut(),s=class{};l.TypedEventEmitter=s,(0,r.applyMixin)(s,t.default)}),fr=pe((l,e)=>{le(),ue(),ce();function t(r){"@babel/helpers - typeof";return e.exports=t=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(s){return typeof s}:function(s){return s&&typeof Symbol=="function"&&s.constructor===Symbol&&s!==Symbol.prototype?"symbol":typeof s},e.exports.__esModule=!0,e.exports.default=e.exports,t(r)}e.exports=t,e.exports.__esModule=!0,e.exports.default=e.exports}),bu=pe((l,e)=>{le(),ue(),ce();var t=fr().default;function r(s,n){if(t(s)!="object"||!s)return s;var i=s[Symbol.toPrimitive];if(i!==void 0){var o=i.call(s,n||"default");if(t(o)!="object")return o;throw new TypeError("@@toPrimitive must return a primitive value.")}return(n==="string"?String:Number)(s)}e.exports=r,e.exports.__esModule=!0,e.exports.default=e.exports}),yu=pe((l,e)=>{le(),ue(),ce();var t=fr().default,r=bu();function s(n){var i=r(n,"string");return t(i)=="symbol"?i:i+""}e.exports=s,e.exports.__esModule=!0,e.exports.default=e.exports}),vu=pe((l,e)=>{le(),ue(),ce();var t=yu();function r(s,n,i){return(n=t(n))in s?Object.defineProperty(s,n,{value:i,enumerable:!0,configurable:!0,writable:!0}):s[n]=i,s}e.exports=r,e.exports.__esModule=!0,e.exports.default=e.exports}),wu=pe((l,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}),_u=pe((l,e)=>{le(),ue(),ce();function t(r,s){var n=r==null?null:typeof Symbol<"u"&&r[Symbol.iterator]||r["@@iterator"];if(n!=null){var i,o,a,c,u=[],h=!0,p=!1;try{if(a=(n=n.call(r)).next,s===0){if(Object(n)!==n)return;h=!1}else for(;!(h=(i=a.call(n)).done)&&(u.push(i.value),u.length!==s);h=!0);}catch(y){p=!0,o=y}finally{try{if(!h&&n.return!=null&&(c=n.return(),Object(c)!==c))return}finally{if(p)throw o}}return u}}e.exports=t,e.exports.__esModule=!0,e.exports.default=e.exports}),ku=pe((l,e)=>{le(),ue(),ce();function t(r,s){(s==null||s>r.length)&&(s=r.length);for(var n=0,i=Array(s);n<s;n++)i[n]=r[n];return i}e.exports=t,e.exports.__esModule=!0,e.exports.default=e.exports}),xu=pe((l,e)=>{le(),ue(),ce();var t=ku();function r(s,n){if(s){if(typeof s=="string")return t(s,n);var i={}.toString.call(s).slice(8,-1);return i==="Object"&&s.constructor&&(i=s.constructor.name),i==="Map"||i==="Set"?Array.from(s):i==="Arguments"||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(i)?t(s,n):void 0}}e.exports=r,e.exports.__esModule=!0,e.exports.default=e.exports}),Su=pe((l,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}),Eu=pe((l,e)=>{le(),ue(),ce();var t=wu(),r=_u(),s=xu(),n=Su();function i(o,a){return t(o)||r(o,a)||s(o,a)||n()}e.exports=i,e.exports.__esModule=!0,e.exports.default=e.exports}),gs=pe((l,e)=>{le(),ue(),ce(),(function(t,r){typeof l=="object"&&typeof e<"u"?r(l):typeof define=="function"&&define.amd?define(["exports"],r):(t=typeof globalThis<"u"?globalThis:t||self,r(t.fastUniqueNumbers={}))})(l,function(t){var r=function(y){return function(f){var g=y(f);return f.add(g),g}},s=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,o=i*2,a=function(y,f){return function(g){var b=f.get(g),k=b===void 0?g.size:b<o?b+1:0;if(!g.has(k))return y(g,k);if(g.size<i){for(;g.has(k);)k=Math.floor(Math.random()*o);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)}},c=new WeakMap,u=s(c),h=a(u,c),p=r(h);t.addUniqueNumber=p,t.generateUniqueNumber=h})}),Au=pe((l,e)=>{le(),ue(),ce();function t(s,n,i,o,a,c,u){try{var h=s[c](u),p=h.value}catch(y){return void i(y)}h.done?n(p):Promise.resolve(p).then(o,a)}function r(s){return function(){var n=this,i=arguments;return new Promise(function(o,a){var c=s.apply(n,i);function u(p){t(c,o,a,u,h,"next",p)}function h(p){t(c,o,a,u,h,"throw",p)}u(void 0)})}}e.exports=r,e.exports.__esModule=!0,e.exports.default=e.exports}),bs=pe((l,e)=>{le(),ue(),ce();function t(r,s){this.v=r,this.k=s}e.exports=t,e.exports.__esModule=!0,e.exports.default=e.exports}),ys=pe((l,e)=>{le(),ue(),ce();function t(r,s,n,i){var o=Object.defineProperty;try{o({},"",{})}catch{o=0}e.exports=t=function(a,c,u,h){function p(y,f){t(a,y,function(g){return this._invoke(y,f,g)})}c?o?o(a,c,{value:u,enumerable:!h,configurable:!h,writable:!h}):a[c]=u:(p("next",0),p("throw",1),p("return",2))},e.exports.__esModule=!0,e.exports.default=e.exports,t(r,s,n,i)}e.exports=t,e.exports.__esModule=!0,e.exports.default=e.exports}),vs=pe((l,e)=>{le(),ue(),ce();var t=ys();function r(){var s,n,i=typeof Symbol=="function"?Symbol:{},o=i.iterator||"@@iterator",a=i.toStringTag||"@@toStringTag";function c(k,m,w,x){var v=m&&m.prototype instanceof h?m:h,E=Object.create(v.prototype);return t(E,"_invoke",(function(S,I,O){var P,N,T,q=0,D=O||[],U=!1,ae={p:0,n:0,v:s,a:Y,f:Y.bind(s,4),d:function(V,re){return P=V,N=0,T=s,ae.n=re,u}};function Y(V,re){for(N=V,T=re,n=0;!U&&q&&!F&&n<D.length;n++){var F,Z=D[n],M=ae.p,J=Z[2];V>3?(F=J===re)&&(T=Z[(N=Z[4])?5:(N=3,3)],Z[4]=Z[5]=s):Z[0]<=M&&((F=V<2&&M<Z[1])?(N=0,ae.v=re,ae.n=Z[1]):M<J&&(F=V<3||Z[0]>re||re>J)&&(Z[4]=V,Z[5]=re,ae.n=J,N=0))}if(F||V>1)return u;throw U=!0,re}return function(V,re,F){if(q>1)throw TypeError("Generator is already running");for(U&&re===1&&Y(re,F),N=re,T=F;(n=N<2?s:T)||!U;){P||(N?N<3?(N>1&&(ae.n=-1),Y(N,T)):ae.n=T:ae.v=T);try{if(q=2,P){if(N||(V="next"),n=P[V]){if(!(n=n.call(P,T)))throw TypeError("iterator result is not an object");if(!n.done)return n;T=n.value,N<2&&(N=0)}else N===1&&(n=P.return)&&n.call(P),N<2&&(T=TypeError("The iterator does not provide a '"+V+"' method"),N=1);P=s}else if((n=(U=ae.n<0)?T:S.call(I,ae))!==u)break}catch(Z){P=s,N=1,T=Z}finally{q=1}}return{value:n,done:U}}})(k,w,x),!0),E}var u={};function h(){}function p(){}function y(){}n=Object.getPrototypeOf;var f=[][o]?n(n([][o]())):(t(n={},o,function(){return this}),n),g=y.prototype=h.prototype=Object.create(f);function b(k){return Object.setPrototypeOf?Object.setPrototypeOf(k,y):(k.__proto__=y,t(k,a,"GeneratorFunction")),k.prototype=Object.create(g),k}return p.prototype=y,t(g,"constructor",y),t(y,"constructor",p),p.displayName="GeneratorFunction",t(y,a,"GeneratorFunction"),t(g),t(g,a,"Generator"),t(g,o,function(){return this}),t(g,"toString",function(){return"[object Generator]"}),(e.exports=r=function(){return{w:c,m:b}},e.exports.__esModule=!0,e.exports.default=e.exports)()}e.exports=r,e.exports.__esModule=!0,e.exports.default=e.exports}),ws=pe((l,e)=>{le(),ue(),ce();var t=bs(),r=ys();function s(n,i){function o(c,u,h,p){try{var y=n[c](u),f=y.value;return f instanceof t?i.resolve(f.v).then(function(g){o("next",g,h,p)},function(g){o("throw",g,h,p)}):i.resolve(f).then(function(g){y.value=g,h(y)},function(g){return o("throw",g,h,p)})}catch(g){p(g)}}var a;this.next||(r(s.prototype),r(s.prototype,typeof Symbol=="function"&&Symbol.asyncIterator||"@asyncIterator",function(){return this})),r(this,"_invoke",function(c,u,h){function p(){return new i(function(y,f){o(c,h,y,f)})}return a=a?a.then(p,p):p()},!0)}e.exports=s,e.exports.__esModule=!0,e.exports.default=e.exports}),_s=pe((l,e)=>{le(),ue(),ce();var t=vs(),r=ws();function s(n,i,o,a,c){return new r(t().w(n,i,o,a),c||Promise)}e.exports=s,e.exports.__esModule=!0,e.exports.default=e.exports}),Iu=pe((l,e)=>{le(),ue(),ce();var t=_s();function r(s,n,i,o,a){var c=t(s,n,i,o,a);return c.next().then(function(u){return u.done?u.value:c.next()})}e.exports=r,e.exports.__esModule=!0,e.exports.default=e.exports}),Tu=pe((l,e)=>{le(),ue(),ce();function t(r){var s=Object(r),n=[];for(var i in s)n.unshift(i);return function o(){for(;n.length;)if((i=n.pop())in s)return o.value=i,o.done=!1,o;return o.done=!0,o}}e.exports=t,e.exports.__esModule=!0,e.exports.default=e.exports}),Cu=pe((l,e)=>{le(),ue(),ce();var t=fr().default;function r(s){if(s!=null){var n=s[typeof Symbol=="function"&&Symbol.iterator||"@@iterator"],i=0;if(n)return n.call(s);if(typeof s.next=="function")return s;if(!isNaN(s.length))return{next:function(){return s&&i>=s.length&&(s=void 0),{value:s&&s[i++],done:!s}}}}throw new TypeError(t(s)+" is not iterable")}e.exports=r,e.exports.__esModule=!0,e.exports.default=e.exports}),Ou=pe((l,e)=>{le(),ue(),ce();var t=bs(),r=vs(),s=Iu(),n=_s(),i=ws(),o=Tu(),a=Cu();function c(){var u=r(),h=u.m(c),p=(Object.getPrototypeOf?Object.getPrototypeOf(h):h.__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(x,v){return m(w.a,f[x],v)},delegateYield:function(x,v,E){return k.resultName=v,m(w.d,a(x),E)},finish:function(x){return m(w.f,x)}},m=function(x,v,E){w.p=k.prev,w.n=k.next;try{return x(v,E)}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=c=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,x){return(y(k)?n:s)(g(b),k,m,w,x)},keys:o,values:a}},e.exports.__esModule=!0,e.exports.default=e.exports)()}e.exports=c,e.exports.__esModule=!0,e.exports.default=e.exports}),Pu=pe((l,e)=>{le(),ue(),ce();var t=Ou()();e.exports=t;try{regeneratorRuntime=t}catch{typeof globalThis=="object"?globalThis.regeneratorRuntime=t:Function("r","regeneratorRuntime = r")(t)}}),Mu=pe((l,e)=>{le(),ue(),ce(),(function(t,r){typeof l=="object"&&typeof e<"u"?r(l,vu(),Eu(),gs(),Au(),Pu()):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))})(l,function(t,r,s,n,i,o){var a=function(m){return typeof m.start=="function"},c=new WeakMap;function u(m,w){var x=Object.keys(m);if(Object.getOwnPropertySymbols){var v=Object.getOwnPropertySymbols(m);w&&(v=v.filter(function(E){return Object.getOwnPropertyDescriptor(m,E).enumerable})),x.push.apply(x,v)}return x}function h(m){for(var w=1;w<arguments.length;w++){var x=arguments[w]!=null?arguments[w]:{};w%2?u(Object(x),!0).forEach(function(v){r(m,v,x[v])}):Object.getOwnPropertyDescriptors?Object.defineProperties(m,Object.getOwnPropertyDescriptors(x)):u(Object(x)).forEach(function(v){Object.defineProperty(m,v,Object.getOwnPropertyDescriptor(x,v))})}return m}var p=function(m){return h(h({},m),{},{connect:function(w){var x=w.call;return i(o.mark(function v(){var E,S,I,O;return o.wrap(function(P){for(;;)switch(P.prev=P.next){case 0:return E=new MessageChannel,S=E.port1,I=E.port2,P.next=1,x("connect",{port:S},[S]);case 1:return O=P.sent,c.set(I,O),P.abrupt("return",I);case 2:case"end":return P.stop()}},v)}))},disconnect:function(w){var x=w.call;return(function(){var v=i(o.mark(function E(S){var I;return o.wrap(function(O){for(;;)switch(O.prev=O.next){case 0:if(I=c.get(S),I!==void 0){O.next=1;break}throw new Error("The given port is not connected.");case 1:return O.next=2,x("disconnect",{portId:I});case 2:case"end":return O.stop()}},E)}));return function(E){return v.apply(this,arguments)}})()},isSupported:function(w){var x=w.call;return function(){return x("isSupported")}}})};function y(m,w){var x=Object.keys(m);if(Object.getOwnPropertySymbols){var v=Object.getOwnPropertySymbols(m);w&&(v=v.filter(function(E){return Object.getOwnPropertyDescriptor(m,E).enumerable})),x.push.apply(x,v)}return x}function f(m){for(var w=1;w<arguments.length;w++){var x=arguments[w]!=null?arguments[w]:{};w%2?y(Object(x),!0).forEach(function(v){r(m,v,x[v])}):Object.getOwnPropertyDescriptors?Object.defineProperties(m,Object.getOwnPropertyDescriptors(x)):y(Object(x)).forEach(function(v){Object.defineProperty(m,v,Object.getOwnPropertyDescriptor(x,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(x){var v=b(x);x.addEventListener("message",function(D){var U=D.data,ae=U.id;if(ae!==null&&v.has(ae)){var Y=v.get(ae),V=Y.reject,re=Y.resolve;v.delete(ae),U.error===void 0?re(U.result):V(new Error(U.error.message))}}),a(x)&&x.start();for(var E=function(D){var U=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,V){var re=n.generateUniqueNumber(v);v.set(re,{reject:V,resolve:Y}),U===null?x.postMessage({id:re,method:D},ae):x.postMessage({id:re,method:D,params:U},ae)})},S=function(D,U){var ae=arguments.length>2&&arguments[2]!==void 0?arguments[2]:[];x.postMessage({id:null,method:D,params:U},ae)},I={},O=0,P=Object.entries(w);O<P.length;O++){var N=s(P[O],2),T=N[0],q=N[1];I=f(f({},I),{},r({},T,q({call:E,notify:S})))}return f({},I)}};t.createBroker=k})}),Ru=pe((l,e)=>{le(),ue(),ce(),(function(t,r){typeof l=="object"&&typeof e<"u"?r(l,fr(),Mu(),gs()):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))})(l,function(t,r,s,n){var i=new Map([[0,null]]),o=new Map([[0,null]]),a=s.createBroker({clearInterval:function(u){var h=u.call;return function(p){r(i.get(p))==="symbol"&&(i.set(p,null),h("clear",{timerId:p,timerType:"interval"}).then(function(){i.delete(p)}))}},clearTimeout:function(u){var h=u.call;return function(p){r(o.get(p))==="symbol"&&(o.set(p,null),h("clear",{timerId:p,timerType:"timeout"}).then(function(){o.delete(p)}))}},setInterval:function(u){var h=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 h("set",{delay:y,now:performance.timeOrigin+performance.now(),timerId:m,timerType:"interval"}).then(function(){var x=i.get(m);if(x===void 0)throw new Error("The timer is in an undefined state.");x===k&&(p.apply(void 0,g),i.get(m)===k&&w())})};return w(),m}},setTimeout:function(u){var h=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(o);return o.set(m,k),h("set",{delay:y,now:performance.timeOrigin+performance.now(),timerId:m,timerType:"timeout"}).then(function(){var w=o.get(m);if(w===void 0)throw new Error("The timer is in an undefined state.");w===k&&(o.delete(m),p.apply(void 0,g))}),m}}}),c=function(u){var h=new Worker(u);return a(h)};t.load=c,t.wrap=a})}),Lu=pe((l,e)=>{le(),ue(),ce(),(function(t,r){typeof l=="object"&&typeof e<"u"?r(l,Ru()):typeof define=="function"&&define.amd?define(["exports","worker-timers-broker"],r):(t=typeof globalThis<"u"?globalThis:t||self,r(t.workerTimers={},t.workerTimersBroker))})(l,function(t,r){var s=function(h,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=h(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=s(r.load,n),o=function(h){return i().clearInterval(h)},a=function(h){return i().clearTimeout(h)},c=function(){var h;return(h=i()).setInterval.apply(h,arguments)},u=function(){var h;return(h=i()).setTimeout.apply(h,arguments)};t.clearInterval=o,t.clearTimeout=a,t.setInterval=c,t.setTimeout=u})}),pr=pe(l=>{le(),ue(),ce(),Object.defineProperty(l,"__esModule",{value:!0}),l.isReactNativeBrowser=l.isWebWorker=void 0;var e=()=>typeof window<"u"?typeof navigator<"u"&&navigator.userAgent?.toLowerCase().indexOf(" electron/")>-1&&Le?.versions?!Object.prototype.hasOwnProperty.call(Le.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",s=e()||t()||r();l.isWebWorker=t(),l.isReactNativeBrowser=r(),l.default=s}),ju=pe(l=>{le(),ue(),ce();var e=l&&l.__createBinding||(Object.create?function(c,u,h,p){p===void 0&&(p=h);var y=Object.getOwnPropertyDescriptor(u,h);(!y||("get"in y?!u.__esModule:y.writable||y.configurable))&&(y={enumerable:!0,get:function(){return u[h]}}),Object.defineProperty(c,p,y)}:function(c,u,h,p){p===void 0&&(p=h),c[p]=u[h]}),t=l&&l.__setModuleDefault||(Object.create?function(c,u){Object.defineProperty(c,"default",{enumerable:!0,value:u})}:function(c,u){c.default=u}),r=l&&l.__importStar||(function(){var c=function(u){return c=Object.getOwnPropertyNames||function(h){var p=[];for(var y in h)Object.prototype.hasOwnProperty.call(h,y)&&(p[p.length]=y);return p},c(u)};return function(u){if(u&&u.__esModule)return u;var h={};if(u!=null)for(var p=c(u),y=0;y<p.length;y++)p[y]!=="default"&&e(h,u,p[y]);return t(h,u),h}})();Object.defineProperty(l,"__esModule",{value:!0});var s=Lu(),n=r(pr()),i={set:s.setInterval,clear:s.clearInterval},o={set:(c,u)=>setInterval(c,u),clear:c=>clearInterval(c)},a=c=>{switch(c){case"native":return o;case"worker":return i;default:return n.default&&!n.isWebWorker&&!n.isReactNativeBrowser?i:o}};l.default=a}),ks=pe(l=>{le(),ue(),ce();var e=l&&l.__importDefault||function(s){return s&&s.__esModule?s:{default:s}};Object.defineProperty(l,"__esModule",{value:!0});var t=e(ju()),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(s,n){this.client=s,this.timer=typeof n=="object"&&"set"in n&&"clear"in n?n:(0,t.default)(n),this.setKeepalive(s.options.keepalive)}clear(){this.timerId&&(this.timer.clear(this.timerId),this.timerId=null)}setKeepalive(s){if(s*=1e3,isNaN(s)||s<=0||s>2147483647)throw new Error(`Keepalive value must be an integer between 0 and 2147483647. Provided value is ${s}`);this._keepalive=s,this.reschedule(),this.client.log(`KeepaliveManager: set keepalive to ${s}ms`)}destroy(){this.clear(),this.destroyed=!0}reschedule(){if(this.destroyed)return;this.clear(),this.counter=0;let s=Math.ceil(this._keepalive*1.5);this._keepaliveTimeoutTimestamp=Date.now()+s,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)}};l.default=r}),di=pe(l=>{le(),ue(),ce();var e=l&&l.__createBinding||(Object.create?function(v,E,S,I){I===void 0&&(I=S);var O=Object.getOwnPropertyDescriptor(E,S);(!O||("get"in O?!E.__esModule:O.writable||O.configurable))&&(O={enumerable:!0,get:function(){return E[S]}}),Object.defineProperty(v,I,O)}:function(v,E,S,I){I===void 0&&(I=S),v[I]=E[S]}),t=l&&l.__setModuleDefault||(Object.create?function(v,E){Object.defineProperty(v,"default",{enumerable:!0,value:E})}:function(v,E){v.default=E}),r=l&&l.__importStar||(function(){var v=function(E){return v=Object.getOwnPropertyNames||function(S){var I=[];for(var O in S)Object.prototype.hasOwnProperty.call(S,O)&&(I[I.length]=O);return I},v(E)};return function(E){if(E&&E.__esModule)return E;var S={};if(E!=null)for(var I=v(E),O=0;O<I.length;O++)I[O]!=="default"&&e(S,E,I[O]);return t(S,E),S}})(),s=l&&l.__importDefault||function(v){return v&&v.__esModule?v:{default:v}};Object.defineProperty(l,"__esModule",{value:!0});var n=s(zc()),i=It(),o=s(Gc()),a=s(ht()),c=r(as()),u=s(ls()),h=s(pu()),p=s(ms()),y=s(mu()),f=Ut(),g=gu(),b=s(ks()),k=r(pr()),m=globalThis.setImmediate||((...v)=>{let E=v.shift();(0,f.nextTick)(()=>{E(...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"},x=class _o 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(E,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,a.default)("mqttjs:client"),this.noop=this._noop.bind(this),this.log("MqttClient :: version:",_o.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:_o.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=E,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,O=()=>{let P=I.shift();this.log("deliver :: entry %o",P);let N=null;if(!P){this._resubscribe();return}N=P.packet,this.log("deliver :: call _sendPacket for %o",N);let T=!0;N.messageId&&N.messageId!==0&&(this.messageIdProvider.register(N.messageId)||(T=!1)),T?this._sendPacket(N,q=>{P.cb&&P.cb(q),O()}):(this.log("messageId: %d has already used. The message is skipped and removed.",N.messageId),O())};this.log("connect :: sending queued packets"),O()}),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(E,S){S()}handleMessage(E,S){S()}_nextId(){return this.messageIdProvider.allocate()}getLastMessageId(){return this.messageIdProvider.getLastAllocated()}connect(){let E=new i.Writable,S=n.default.parser(this.options),I=null,O=[];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."),O.push(D)});let P=()=>{this.log("work :: getting next packet in queue");let D=O.shift();if(D)this.log("work :: packet pulled from queue"),(0,h.default)(this,D,N);else{this.log("work :: no packets in queue");let U=I;I=null,this.log("work :: done flag is %s",!!U),U&&U()}},N=()=>{if(O.length)(0,f.nextTick)(P);else{let D=I;I=null,D()}};E._write=(D,U,ae)=>{I=ae,this.log("writable stream :: parsing buffer"),S.parse(D),P()};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(E),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 q={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&&(q.will={...this.options.will,payload:this.options.will?.payload}),this.topicAliasRecv&&(q.properties||(q.properties={}),this.topicAliasRecv&&(q.properties.topicAliasMaximum=this.topicAliasRecv.max)),this._writePacket(q),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(E,S,I,O){this.log("publish :: message `%s` to topic `%s`",S,E);let{options:P}=this;typeof I=="function"&&(O=I,I=null),I=I||{},I={qos:0,retain:!1,dup:!1,...I};let{qos:N,retain:T,dup:q,properties:D,cbStorePut:U}=I;if(this._checkDisconnecting(O))return this;let ae=()=>{let Y=0;if((N===1||N===2)&&(Y=this._nextId(),Y===null))return this.log("No messageId left"),!1;let V={cmd:"publish",topic:E,payload:S,qos:N,retain:T,messageId:Y,dup:q};switch(P.protocolVersion===5&&(V.properties=D),this.log("publish :: qos",N),N){case 1:case 2:this.outgoing[V.messageId]={volatile:!1,cb:O||this.noop},this.log("MqttClient:publish: packet cmd: %s",V.cmd),this._sendPacket(V,void 0,U);break;default:this.log("MqttClient:publish: packet cmd: %s",V.cmd),this._sendPacket(V,O,U);break}return!0};return(this._storeProcessing||this._storeProcessingQueue.length>0||!ae())&&this._storeProcessingQueue.push({invoke:ae,cbStorePut:I.cbStorePut,callback:O}),this}publishAsync(E,S,I){return new Promise((O,P)=>{this.publish(E,S,I,(N,T)=>{N?P(N):O(T)})})}subscribe(E,S,I){let O=this.options.protocolVersion;typeof S=="function"&&(I=S),I=I||this.noop;let P=!1,N=[];typeof E=="string"?(E=[E],N=E):Array.isArray(E)?N=E:typeof E=="object"&&(P=E.resubscribe,delete E.resubscribe,N=Object.keys(E));let T=c.validateTopics(N);if(T!==null)return m(I,new Error(`Invalid topic ${T}`)),this;if(this._checkDisconnecting(I))return this.log("subscribe: discconecting true"),this;let q={qos:0};O===5&&(q.nl=!1,q.rap=!1,q.rh=0),S={...q,...S};let{properties:D}=S,U=[],ae=(re,F)=>{if(F=F||S,!Object.prototype.hasOwnProperty.call(this._resubscribeTopics,re)||this._resubscribeTopics[re].qos<F.qos||P){let Z={topic:re,qos:F.qos};O===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),U.push(Z)}};if(Array.isArray(E)?E.forEach(re=>{this.log("subscribe: array topic %s",re),ae(re)}):Object.keys(E).forEach(re=>{this.log("subscribe: object topic %s, %o",re,E[re]),ae(re,E[re])}),!U.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};O===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 M=new Promise((J,be)=>{this.outgoing[Z.messageId]={volatile:!0,cb(te,we){if(!te){let{granted:G}=we;for(let j=0;j<G.length;j+=1)re[j].qos=G[j]}te?be(new f.ErrorWithSubackPacket(te.message,we)):J(we)}}});return this.log("subscribe :: call _sendPacket"),this._sendPacket(Z),M},V=()=>{let re=this.options.subscribeBatchSize??U.length,F=[];for(let Z=0;Z<U.length;Z+=re){let M=U.slice(Z,Z+re),J=this._nextId();if(J===null)return this.log("No messageId left"),!1;F.push(Y(M,J))}return Promise.all(F).then(Z=>{I(null,U,Z.at(-1))}).catch(Z=>{I(Z,U,Z.packet)}),!0};return(this._storeProcessing||this._storeProcessingQueue.length>0||!V())&&this._storeProcessingQueue.push({invoke:V,callback:I}),this}subscribeAsync(E,S){return new Promise((I,O)=>{this.subscribe(E,S,(P,N)=>{P?O(P):I(N)})})}unsubscribe(E,S,I){typeof E=="string"&&(E=[E]),typeof S=="function"&&(I=S),I=I||this.noop;let O=c.validateTopics(E);if(O!==null)return m(I,new Error(`Invalid topic ${O}`)),this;if(this._checkDisconnecting(I))return this;let P=()=>{let N=this._nextId();if(N===null)return this.log("No messageId left"),!1;let T={cmd:"unsubscribe",messageId:N,unsubscriptions:[]};return typeof E=="string"?T.unsubscriptions=[E]:Array.isArray(E)&&(T.unsubscriptions=E),this.options.resubscribe&&T.unsubscriptions.forEach(q=>{delete this._resubscribeTopics[q]}),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||!P())&&this._storeProcessingQueue.push({invoke:P,callback:I}),this}unsubscribeAsync(E,S){return new Promise((I,O)=>{this.unsubscribe(E,S,(P,N)=>{P?O(P):I(N)})})}end(E,S,I){this.log("end :: (%s)",this.options.clientId),(E==null||typeof E!="boolean")&&(I=I||S,S=E,E=!1),typeof S!="object"&&(I=I||S,S=null),this.log("end :: cb? %s",!!I),(!I||typeof I!="function")&&(I=this.noop);let O=()=>{this.log("end :: closeStores: closing incoming and outgoing stores"),this.disconnected=!0,this.incomingStore.close(N=>{this.outgoingStore.close(T=>{if(this.log("end :: closeStores: emitting end"),this.emit("end"),I){let q=N||T;this.log("end :: closeStores: invoking callback with args"),I(q)}})}),this._deferredReconnect?this._deferredReconnect():(this.options.reconnectPeriod===0||this.options.manualConnect)&&(this.disconnecting=!1)},P=()=>{this.log("end :: (%s) :: finish :: calling _cleanUp with force %s",this.options.clientId,E),this._cleanUp(E,()=>{this.log("end :: finish :: calling process.nextTick on closeStores"),(0,f.nextTick)(O)},S)};return this.disconnecting?(I(),this):(this._clearReconnect(),this.disconnecting=!0,!E&&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,P,10))):(this.log("end :: (%s) :: immediately calling finish",this.options.clientId),P()),this)}endAsync(E,S){return new Promise((I,O)=>{this.end(E,S,P=>{P?O(P):I()})})}removeOutgoingMessage(E){if(this.outgoing[E]){let{cb:S}=this.outgoing[E];this._removeOutgoingAndStoreMessage(E,()=>{S(new Error("Message removed"))})}return this}reconnect(E){this.log("client reconnect");let S=()=>{E?(this.options.incomingStore=E.incomingStore,this.options.outgoingStore=E.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(E=>{this.outgoing[E].volatile&&typeof this.outgoing[E].cb=="function"&&(this.outgoing[E].cb(new Error("Connection closed")),delete this.outgoing[E])}))}_flush(){this.outgoing&&(this.log("_flush: queue exists? %b",!!this.outgoing),Object.keys(this.outgoing).forEach(E=>{typeof this.outgoing[E].cb=="function"&&(this.outgoing[E].cb(new Error("Connection closed")),delete this.outgoing[E])}))}_removeTopicAliasAndRecoverTopicName(E){let S;E.properties&&(S=E.properties.topicAlias);let I=E.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");E.topic=I}S&&delete E.properties.topicAlias}_checkDisconnecting(E){return this.disconnecting&&(E&&E!==this.noop?E(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(E,S,I={}){if(S&&(this.log("_cleanUp :: done callback provided for on stream close"),this.stream.on("close",S)),this.log("_cleanUp :: forced? %s",E),E)this.options.reconnectPeriod===0&&this.options.clean&&this._flush(),this.log("_cleanUp :: (%s) :: destroying stream",this.options.clientId),this.stream.destroy();else{let O={cmd:"disconnect",...I};this.log("_cleanUp :: (%s) :: call _sendPacket with disconnect packet",this.options.clientId),this._sendPacket(O,()=>{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(E,S,I){this.log("storeAndSend :: store packet with cmd %s to outgoingStore",E.cmd);let O=E,P;if(O.cmd==="publish"&&(O=(0,o.default)(E),P=this._removeTopicAliasAndRecoverTopicName(O),P))return S&&S(P);this.outgoingStore.put(O,N=>{if(N)return S&&S(N);I(),this._writePacket(E,S)})}_applyTopicAlias(E){if(this.options.protocolVersion===5&&E.cmd==="publish"){let S;E.properties&&(S=E.properties.topicAlias);let I=E.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?(E.topic="",E.properties={...E.properties,topicAlias:S},this.log("applyTopicAlias :: auto assign(use) topic: %s - alias: %d",I,S)):(S=this.topicAliasSend.getLruAlias(),this.topicAliasSend.put(I,S),E.properties={...E.properties,topicAlias:S},this.log("applyTopicAlias :: auto assign topic: %s - alias: %d",I,S))):this.options.autoUseTopicAlias&&(S=this.topicAliasSend.getAliasByTopic(I),S&&(E.topic="",E.properties={...E.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(E){this.log("noop ::",E)}_writePacket(E,S){this.log("_writePacket :: packet: %O",E),this.log("_writePacket :: emitting `packetsend`"),this.emit("packetsend",E),this.log("_writePacket :: writing to stream");let I=n.default.writeToStream(E,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(E,S,I,O){this.log("_sendPacket :: (%s) :: start",this.options.clientId),I=I||this.noop,S=S||this.noop;let P=this._applyTopicAlias(E);if(P){S(P);return}if(!this.connected){if(E.cmd==="auth"){this._writePacket(E,S);return}this.log("_sendPacket :: client not connected. Storing packet offline."),this._storePacket(E,S,I);return}if(O){this._writePacket(E,S);return}switch(E.cmd){case"publish":break;case"pubrel":this._storeAndSend(E,S,I);return;default:this._writePacket(E,S);return}switch(E.qos){case 2:case 1:this._storeAndSend(E,S,I);break;default:this._writePacket(E,S);break}this.log("_sendPacket :: (%s) :: end",this.options.clientId)}_storePacket(E,S,I){this.log("_storePacket :: packet: %o",E),this.log("_storePacket :: cb? %s",!!S),I=I||this.noop;let O=E;if(O.cmd==="publish"){O=(0,o.default)(E);let N=this._removeTopicAliasAndRecoverTopicName(O);if(N)return S&&S(N)}let P=O.qos||0;P===0&&this.queueQoSZero||O.cmd!=="publish"?this.queue.push({packet:O,cb:S}):P>0?(S=this.outgoing[O.messageId]?this.outgoing[O.messageId].cb:null,this.outgoingStore.put(O,N=>{if(N)return S&&S(N);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(E=!1){this.keepaliveManager&&this.options.keepalive&&(E||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 E=Object.keys(this._resubscribeTopics);if(!this._firstConnection&&(this.options.clean||this.options.protocolVersion>=4&&!this.connackPacket.sessionPresent)&&E.length>0)if(this.options.resubscribe)if(this.options.protocolVersion===5){this.log("_resubscribe: protocolVersion 5");for(let S=0;S<E.length;S++){let I={};I[E[S]]=this._resubscribeTopics[E[S]],I.resubscribe=!0,this.subscribe(I,{properties:I[E[S]].properties})}}else this._resubscribeTopics.resubscribe=!0,this.subscribe(this._resubscribeTopics);else this._resubscribeTopics={};this._firstConnection=!1}_onConnect(E){if(this.disconnected){this.emit("connect",E);return}this.connackPacket=E,this.messageIdProvider.clear(),this._setupKeepaliveManager(),this.connected=!0;let S=()=>{let I=this.outgoingStore.createStream(),O=()=>{I.destroy(),I=null,this._flushStoreProcessingQueue(),P()},P=()=>{this._storeProcessing=!1,this._packetIdsDuringStoreProcessing={}};this.once("close",O),I.on("error",T=>{P(),this._flushStoreProcessingQueue(),this.removeListener("close",O),this.emit("error",T)});let N=()=>{if(!I)return;let T=I.read(1),q;if(!T){I.once("readable",N);return}if(this._storeProcessing=!0,this._packetIdsDuringStoreProcessing[T.messageId]){N();return}!this.disconnecting&&!this.reconnectTimer?(q=this.outgoing[T.messageId]?this.outgoing[T.messageId].cb:null,this.outgoing[T.messageId]={volatile:!1,cb(D,U){q&&q(D,U),N()}},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 q in this._packetIdsDuringStoreProcessing)if(!this._packetIdsDuringStoreProcessing[q]){T=!1;break}this.removeListener("close",O),T?(P(),this._invokeAllStoreProcessingQueue(),this.emit("connect",E)):S()}),N()};S()}_invokeStoreProcessingQueue(){if(!this._storeProcessing&&this._storeProcessingQueue.length>0){let E=this._storeProcessingQueue[0];if(E&&E.invoke())return this._storeProcessingQueue.shift(),!0}return!1}_invokeAllStoreProcessingQueue(){for(;this._invokeStoreProcessingQueue(););}_flushStoreProcessingQueue(){for(let E of this._storeProcessingQueue)E.cbStorePut&&E.cbStorePut(new Error("Connection closed")),E.callback&&E.callback(new Error("Connection closed"));this._storeProcessingQueue.splice(0)}_removeOutgoingAndStoreMessage(E,S){delete this.outgoing[E],this.outgoingStore.del({messageId:E},(I,O)=>{S(I,O),this.messageIdProvider.deallocate(E),this._invokeStoreProcessingQueue()})}};l.default=x}),Nu=pe(l=>{le(),ue(),ce(),Object.defineProperty(l,"__esModule",{value:!0});var e=ps(),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()}};l.default=t});function Uu(){if(fi)return mr;fi=!0;let l=2147483647,e=36,t=1,r=26,s=38,n=700,i=72,o=128,a="-",c=/^xn--/,u=/[^\0-\x7F]/,h=/[\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(P){throw new RangeError(p[P])}function k(P,N){let T=[],q=P.length;for(;q--;)T[q]=N(P[q]);return T}function m(P,N){let T=P.split("@"),q="";T.length>1&&(q=T[0]+"@",P=T[1]),P=P.replace(h,".");let D=P.split("."),U=k(D,N).join(".");return q+U}function w(P){let N=[],T=0,q=P.length;for(;T<q;){let D=P.charCodeAt(T++);if(D>=55296&&D<=56319&&T<q){let U=P.charCodeAt(T++);(U&64512)==56320?N.push(((D&1023)<<10)+(U&1023)+65536):(N.push(D),T--)}else N.push(D)}return N}let x=P=>String.fromCodePoint(...P),v=function(P){return P>=48&&P<58?26+(P-48):P>=65&&P<91?P-65:P>=97&&P<123?P-97:e},E=function(P,N){return P+22+75*(P<26)-((N!=0)<<5)},S=function(P,N,T){let q=0;for(P=T?f(P/n):P>>1,P+=f(P/N);P>y*r>>1;q+=e)P=f(P/y);return f(q+(y+1)*P/(P+s))},I=function(P){let N=[],T=P.length,q=0,D=o,U=i,ae=P.lastIndexOf(a);ae<0&&(ae=0);for(let Y=0;Y<ae;++Y)P.charCodeAt(Y)>=128&&b("not-basic"),N.push(P.charCodeAt(Y));for(let Y=ae>0?ae+1:0;Y<T;){let V=q;for(let F=1,Z=e;;Z+=e){Y>=T&&b("invalid-input");let M=v(P.charCodeAt(Y++));M>=e&&b("invalid-input"),M>f((l-q)/F)&&b("overflow"),q+=M*F;let J=Z<=U?t:Z>=U+r?r:Z-U;if(M<J)break;let be=e-J;F>f(l/be)&&b("overflow"),F*=be}let re=N.length+1;U=S(q-V,re,V==0),f(q/re)>l-D&&b("overflow"),D+=f(q/re),q%=re,N.splice(q++,0,D)}return String.fromCodePoint(...N)},O=function(P){let N=[];P=w(P);let T=P.length,q=o,D=0,U=i;for(let V of P)V<128&&N.push(g(V));let ae=N.length,Y=ae;for(ae&&N.push(a);Y<T;){let V=l;for(let F of P)F>=q&&F<V&&(V=F);let re=Y+1;V-q>f((l-D)/re)&&b("overflow"),D+=(V-q)*re,q=V;for(let F of P)if(F<q&&++D>l&&b("overflow"),F===q){let Z=D;for(let M=e;;M+=e){let J=M<=U?t:M>=U+r?r:M-U;if(Z<J)break;let be=Z-J,te=e-J;N.push(g(E(J+be%te,0))),Z=f(be/te)}N.push(g(E(Z,0))),U=S(D,re,Y===ae),D=0,++Y}++D,++q}return N.join("")};return mr={version:"2.3.1",ucs2:{decode:w,encode:x},decode:I,encode:O,toASCII:function(P){return m(P,function(N){return u.test(N)?"xn--"+O(N):N})},toUnicode:function(P){return m(P,function(N){return c.test(N)?I(N.slice(4).toLowerCase()):N})}},mr}var mr,fi,vt,Bu=Ve(()=>{le(),ue(),ce(),mr={},fi=!1,vt=Uu(),vt.decode,vt.encode,vt.toASCII,vt.toUnicode,vt.ucs2,vt.version});function Du(){return bi||(bi=!0,gi=function(){if(typeof Symbol!="function"||typeof Object.getOwnPropertySymbols!="function")return!1;if(typeof Symbol.iterator=="symbol")return!0;var l={},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;l[e]=r;for(e in l)return!1;if(typeof Object.keys=="function"&&Object.keys(l).length!==0||typeof Object.getOwnPropertyNames=="function"&&Object.getOwnPropertyNames(l).length!==0)return!1;var s=Object.getOwnPropertySymbols(l);if(s.length!==1||s[0]!==e||!Object.prototype.propertyIsEnumerable.call(l,e))return!1;if(typeof Object.getOwnPropertyDescriptor=="function"){var n=Object.getOwnPropertyDescriptor(l,e);if(n.value!==r||n.enumerable!==!0)return!1}return!0}),gi}function Fu(){return vi||(vi=!0,yi=Error),yi}function $u(){return _i||(_i=!0,wi=EvalError),wi}function qu(){return xi||(xi=!0,ki=RangeError),ki}function Hu(){return Ei||(Ei=!0,Si=ReferenceError),Si}function xs(){return Ii||(Ii=!0,Ai=SyntaxError),Ai}function Qt(){return Ci||(Ci=!0,Ti=TypeError),Ti}function Wu(){return Pi||(Pi=!0,Oi=URIError),Oi}function zu(){if(Mi)return gr;Mi=!0;var l=typeof Symbol<"u"&&Symbol,e=Du();return gr=function(){return typeof l!="function"||typeof Symbol!="function"||typeof l("foo")!="symbol"||typeof Symbol("bar")!="symbol"?!1:e()},gr}function Vu(){if(Ri)return br;Ri=!0;var l={__proto__:null,foo:{}},e=Object;return br=function(){return{__proto__:l}.foo===l.foo&&!(l instanceof e)},br}function Gu(){if(Li)return yr;Li=!0;var l="Function.prototype.bind called on incompatible ",e=Object.prototype.toString,t=Math.max,r="[object Function]",s=function(o,a){for(var c=[],u=0;u<o.length;u+=1)c[u]=o[u];for(var h=0;h<a.length;h+=1)c[h+o.length]=a[h];return c},n=function(o,a){for(var c=[],u=a,h=0;u<o.length;u+=1,h+=1)c[h]=o[u];return c},i=function(o,a){for(var c="",u=0;u<o.length;u+=1)c+=o[u],u+1<o.length&&(c+=a);return c};return yr=function(o){var a=this;if(typeof a!="function"||e.apply(a)!==r)throw new TypeError(l+a);for(var c=n(arguments,1),u,h=function(){if(this instanceof u){var b=a.apply(this,s(c,arguments));return Object(b)===b?b:this}return a.apply(o,s(c,arguments))},p=t(0,a.length-c.length),y=[],f=0;f<p;f++)y[f]="$"+f;if(u=Function("binder","return function ("+i(y,",")+"){ return binder.apply(this,arguments); }")(h),a.prototype){var g=function(){};g.prototype=a.prototype,u.prototype=new g,g.prototype=null}return u},yr}function pi(){if(ji)return vr;ji=!0;var l=Gu();return vr=Function.prototype.bind||l,vr}function Ku(){if(Ni)return wr;Ni=!0;var l=Function.prototype.call,e=Object.prototype.hasOwnProperty,t=pi();return wr=t.call(l,e),wr}function Bt(){if(Ui)return _r;Ui=!0;var l,e=Fu(),t=$u(),r=qu(),s=Hu(),n=xs(),i=Qt(),o=Wu(),a=Function,c=function(Y){try{return a('"use strict"; return ('+Y+").constructor;")()}catch{}},u=Object.getOwnPropertyDescriptor;if(u)try{u({},"")}catch{u=null}var h=function(){throw new i},p=u?(function(){try{return arguments.callee,h}catch{try{return u(arguments,"callee").get}catch{return h}}})():h,y=zu()(),f=Vu()(),g=Object.getPrototypeOf||(f?function(Y){return Y.__proto__}:null),b={},k=typeof Uint8Array>"u"||!g?l:g(Uint8Array),m={__proto__:null,"%AggregateError%":typeof AggregateError>"u"?l:AggregateError,"%Array%":Array,"%ArrayBuffer%":typeof ArrayBuffer>"u"?l:ArrayBuffer,"%ArrayIteratorPrototype%":y&&g?g([][Symbol.iterator]()):l,"%AsyncFromSyncIteratorPrototype%":l,"%AsyncFunction%":b,"%AsyncGenerator%":b,"%AsyncGeneratorFunction%":b,"%AsyncIteratorPrototype%":b,"%Atomics%":typeof Atomics>"u"?l:Atomics,"%BigInt%":typeof BigInt>"u"?l:BigInt,"%BigInt64Array%":typeof BigInt64Array>"u"?l:BigInt64Array,"%BigUint64Array%":typeof BigUint64Array>"u"?l:BigUint64Array,"%Boolean%":Boolean,"%DataView%":typeof DataView>"u"?l:DataView,"%Date%":Date,"%decodeURI%":decodeURI,"%decodeURIComponent%":decodeURIComponent,"%encodeURI%":encodeURI,"%encodeURIComponent%":encodeURIComponent,"%Error%":e,"%eval%":eval,"%EvalError%":t,"%Float32Array%":typeof Float32Array>"u"?l:Float32Array,"%Float64Array%":typeof Float64Array>"u"?l:Float64Array,"%FinalizationRegistry%":typeof FinalizationRegistry>"u"?l:FinalizationRegistry,"%Function%":a,"%GeneratorFunction%":b,"%Int8Array%":typeof Int8Array>"u"?l:Int8Array,"%Int16Array%":typeof Int16Array>"u"?l:Int16Array,"%Int32Array%":typeof Int32Array>"u"?l:Int32Array,"%isFinite%":isFinite,"%isNaN%":isNaN,"%IteratorPrototype%":y&&g?g(g([][Symbol.iterator]())):l,"%JSON%":typeof JSON=="object"?JSON:l,"%Map%":typeof Map>"u"?l:Map,"%MapIteratorPrototype%":typeof Map>"u"||!y||!g?l:g(new Map()[Symbol.iterator]()),"%Math%":Math,"%Number%":Number,"%Object%":Object,"%parseFloat%":parseFloat,"%parseInt%":parseInt,"%Promise%":typeof Promise>"u"?l:Promise,"%Proxy%":typeof Proxy>"u"?l:Proxy,"%RangeError%":r,"%ReferenceError%":s,"%Reflect%":typeof Reflect>"u"?l:Reflect,"%RegExp%":RegExp,"%Set%":typeof Set>"u"?l:Set,"%SetIteratorPrototype%":typeof Set>"u"||!y||!g?l:g(new Set()[Symbol.iterator]()),"%SharedArrayBuffer%":typeof SharedArrayBuffer>"u"?l:SharedArrayBuffer,"%String%":String,"%StringIteratorPrototype%":y&&g?g(""[Symbol.iterator]()):l,"%Symbol%":y?Symbol:l,"%SyntaxError%":n,"%ThrowTypeError%":p,"%TypedArray%":k,"%TypeError%":i,"%Uint8Array%":typeof Uint8Array>"u"?l:Uint8Array,"%Uint8ClampedArray%":typeof Uint8ClampedArray>"u"?l:Uint8ClampedArray,"%Uint16Array%":typeof Uint16Array>"u"?l:Uint16Array,"%Uint32Array%":typeof Uint32Array>"u"?l:Uint32Array,"%URIError%":o,"%WeakMap%":typeof WeakMap>"u"?l:WeakMap,"%WeakRef%":typeof WeakRef>"u"?l:WeakRef,"%WeakSet%":typeof WeakSet>"u"?l:WeakSet};if(g)try{null.error}catch(Y){var w=g(g(Y));m["%Error.prototype%"]=w}var x=function Y(V){var re;if(V==="%AsyncFunction%")re=c("async function () {}");else if(V==="%GeneratorFunction%")re=c("function* () {}");else if(V==="%AsyncGeneratorFunction%")re=c("async function* () {}");else if(V==="%AsyncGenerator%"){var F=Y("%AsyncGeneratorFunction%");F&&(re=F.prototype)}else if(V==="%AsyncIteratorPrototype%"){var Z=Y("%AsyncGenerator%");Z&&g&&(re=g(Z.prototype))}return m[V]=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"]},E=pi(),S=Ku(),I=E.call(Function.call,Array.prototype.concat),O=E.call(Function.apply,Array.prototype.splice),P=E.call(Function.call,String.prototype.replace),N=E.call(Function.call,String.prototype.slice),T=E.call(Function.call,RegExp.prototype.exec),q=/[^%.[\]]+|\[(?:(-?\d+(?:\.\d+)?)|(["'])((?:(?!\2)[^\\]|\\.)*?)\2)\]|(?=(?:\.|\[\])(?:\.|\[\]|%$))/g,D=/\\(\\)?/g,U=function(Y){var V=N(Y,0,1),re=N(Y,-1);if(V==="%"&&re!=="%")throw new n("invalid intrinsic syntax, expected closing `%`");if(re==="%"&&V!=="%")throw new n("invalid intrinsic syntax, expected opening `%`");var F=[];return P(Y,q,function(Z,M,J,be){F[F.length]=J?P(be,D,"$1"):M||Z}),F},ae=function(Y,V){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=x(re)),typeof Z>"u"&&!V)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 _r=function(Y,V){if(typeof Y!="string"||Y.length===0)throw new i("intrinsic name must be a non-empty string");if(arguments.length>1&&typeof V!="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=U(Y),F=re.length>0?re[0]:"",Z=ae("%"+F+"%",V),M=Z.name,J=Z.value,be=!1,te=Z.alias;te&&(F=te[0],O(re,I([0,1],te)));for(var we=1,G=!0;we<re.length;we+=1){var j=re[we],ne=N(j,0,1),W=N(j,-1);if((ne==='"'||ne==="'"||ne==="`"||W==='"'||W==="'"||W==="`")&&ne!==W)throw new n("property names with quotes must have matching quotes");if((j==="constructor"||!G)&&(be=!0),F+="."+j,M="%"+F+"%",S(m,M))J=m[M];else if(J!=null){if(!(j in J)){if(!V)throw new i("base intrinsic for "+Y+" exists, but the property is not available.");return}if(u&&we+1>=re.length){var K=u(J,j);G=!!K,G&&"get"in K&&!("originalValue"in K.get)?J=K.get:J=J[j]}else G=S(J,j),J=J[j];G&&!be&&(m[M]=J)}}return J},_r}function mi(){if(Bi)return kr;Bi=!0;var l=Bt(),e=l("%Object.defineProperty%",!0)||!1;if(e)try{e({},"a",{value:1})}catch{e=!1}return kr=e,kr}function Ss(){if(Di)return xr;Di=!0;var l=Bt(),e=l("%Object.getOwnPropertyDescriptor%",!0);if(e)try{e([],"length")}catch{e=null}return xr=e,xr}function Yu(){if(Fi)return Sr;Fi=!0;var l=mi(),e=xs(),t=Qt(),r=Ss();return Sr=function(s,n,i){if(!s||typeof s!="object"&&typeof s!="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 o=arguments.length>3?arguments[3]:null,a=arguments.length>4?arguments[4]:null,c=arguments.length>5?arguments[5]:null,u=arguments.length>6?arguments[6]:!1,h=!!r&&r(s,n);if(l)l(s,n,{configurable:c===null&&h?h.configurable:!c,enumerable:o===null&&h?h.enumerable:!o,value:i,writable:a===null&&h?h.writable:!a});else if(u||!o&&!a&&!c)s[n]=i;else throw new e("This environment does not support defining a property as non-configurable, non-writable, or non-enumerable.")},Sr}function Qu(){if($i)return Er;$i=!0;var l=mi(),e=function(){return!!l};return e.hasArrayLengthDefineBug=function(){if(!l)return null;try{return l([],"length",{value:1}).length!==1}catch{return!0}},Er=e,Er}function Ju(){if(qi)return Ar;qi=!0;var l=Bt(),e=Yu(),t=Qu()(),r=Ss(),s=Qt(),n=l("%Math.floor%");return Ar=function(i,o){if(typeof i!="function")throw new s("`fn` is not a function");if(typeof o!="number"||o<0||o>4294967295||n(o)!==o)throw new s("`length` must be a positive 32-bit integer");var a=arguments.length>2&&!!arguments[2],c=!0,u=!0;if("length"in i&&r){var h=r(i,"length");h&&!h.configurable&&(c=!1),h&&!h.writable&&(u=!1)}return(c||u||!a)&&(t?e(i,"length",o,!0,!0):e(i,"length",o)),i},Ar}function Xu(){if(Hi)return Dt;Hi=!0;var l=pi(),e=Bt(),t=Ju(),r=Qt(),s=e("%Function.prototype.apply%"),n=e("%Function.prototype.call%"),i=e("%Reflect.apply%",!0)||l.call(n,s),o=mi(),a=e("%Math.max%");Dt=function(u){if(typeof u!="function")throw new r("a function is required");var h=i(l,n,arguments);return t(h,1+a(0,u.length-(arguments.length-1)),!0)};var c=function(){return i(l,s,arguments)};return o?o(Dt,"apply",{value:c}):Dt.apply=c,Dt}function Zu(){if(Wi)return Ir;Wi=!0;var l=Bt(),e=Xu(),t=e(l("String.prototype.indexOf"));return Ir=function(r,s){var n=l(r,!!s);return typeof n=="function"&&t(r,".prototype.")>-1?e(n):n},Ir}var gi,bi,yi,vi,wi,_i,ki,xi,Si,Ei,Ai,Ii,Ti,Ci,Oi,Pi,gr,Mi,br,Ri,yr,Li,vr,ji,wr,Ni,_r,Ui,kr,Bi,xr,Di,Sr,Fi,Er,$i,Ar,qi,Dt,Hi,Ir,Wi,eh=Ve(()=>{le(),ue(),ce(),gi={},bi=!1,yi={},vi=!1,wi={},_i=!1,ki={},xi=!1,Si={},Ei=!1,Ai={},Ii=!1,Ti={},Ci=!1,Oi={},Pi=!1,gr={},Mi=!1,br={},Ri=!1,yr={},Li=!1,vr={},ji=!1,wr={},Ni=!1,_r={},Ui=!1,kr={},Bi=!1,xr={},Di=!1,Sr={},Fi=!1,Er={},$i=!1,Ar={},qi=!1,Dt={},Hi=!1,Ir={},Wi=!1});function zi(l){throw new Error("Node.js process "+l+" is not supported by JSPM core outside of Node.js")}function th(){!Tt||!Ct||(Tt=!1,Ct.length?Ze=Ct.concat(Ze):Jt=-1,Ze.length&&Es())}function Es(){if(!Tt){var l=setTimeout(th,0);Tt=!0;for(var e=Ze.length;e;){for(Ct=Ze,Ze=[];++Jt<e;)Ct&&Ct[Jt].run();Jt=-1,e=Ze.length}Ct=null,Tt=!1,clearTimeout(l)}}function rh(l){var e=new Array(arguments.length-1);if(arguments.length>1)for(var t=1;t<arguments.length;t++)e[t-1]=arguments[t];Ze.push(new As(l,e)),Ze.length===1&&!Tt&&setTimeout(Es,0)}function As(l,e){this.fun=l,this.array=e}function $e(){}function nh(l){zi("_linkedBinding")}function ih(l){zi("dlopen")}function oh(){return[]}function sh(){return[]}function ah(l,e){if(!l)throw new Error(e||"assertion error")}function lh(){return!1}function ch(){return pt.now()/1e3}function Vi(l){var e=Math.floor((Date.now()-pt.now())*.001),t=pt.now()*.001,r=Math.floor(t)+e,s=Math.floor(t%1*1e9);return l&&(r=r-l[0],s=s-l[1],s<0&&(r--,s+=Cr)),[r,s]}function wt(){return Ki}function uh(l){return[]}var Ze,Tt,Ct,Jt,Is,Ts,Cs,Os,Ps,Ms,Rs,Ls,js,Ns,Us,Bs,Ds,Fs,$s,qs,Hs,Ws,zs,Vs,Gs,Tr,Ks,Ys,Qs,Js,Xs,Zs,ea,ta,ra,na,ia,oa,sa,aa,la,ca,ua,ha,da,fa,pa,ma,ga,ba,ya,pt,Gi,Cr,va,wa,_a,ka,xa,Sa,Ea,Aa,Ia,Ta,Ca,Ki,Oa=Ve(()=>{le(),ue(),ce(),Ze=[],Tt=!1,Jt=-1,As.prototype.run=function(){this.fun.apply(null,this.array)},Is="browser",Ts="x64",Cs="browser",Os={PATH:"/usr/bin",LANG:navigator.language+".UTF-8",PWD:"/",HOME:"/home",TMP:"/tmp"},Ps=["/usr/bin/node"],Ms=[],Rs="v16.8.0",Ls={},js=function(l,e){console.warn((e?e+": ":"")+l)},Ns=function(l){zi("binding")},Us=function(l){return 0},Bs=function(){return"/"},Ds=function(l){},Fs={name:"node",sourceUrl:"",headersUrl:"",libUrl:""},$s=$e,qs=[],Hs={},Ws=!1,zs={},Vs=$e,Gs=$e,Tr=function(){return{}},Ks=Tr,Ys=Tr,Qs=$e,Js=$e,Xs=$e,Zs={},ea={inspector:!1,debug:!1,uv:!1,ipv6:!1,tls_alpn:!1,tls_sni:!1,tls_ocsp:!1,tls:!1,cached_builtins:!0},ta=$e,ra=$e,na=$e,ia=$e,oa=$e,sa=$e,aa=$e,la=void 0,ca=void 0,ua=void 0,ha=$e,da=2,fa=1,pa="/bin/usr/node",ma=9229,ga="node",ba=[],ya=$e,pt={now:typeof performance<"u"?performance.now.bind(performance):void 0,timing:typeof performance<"u"?performance.timing:void 0},pt.now===void 0&&(Gi=Date.now(),pt.timing&&pt.timing.navigationStart&&(Gi=pt.timing.navigationStart),pt.now=()=>Date.now()-Gi),Cr=1e9,Vi.bigint=function(l){var e=Vi(l);return typeof BigInt>"u"?e[0]*Cr+e[1]:BigInt(e[0]*Cr)+BigInt(e[1])},va=10,wa={},_a=0,ka=wt,xa=wt,Sa=wt,Ea=wt,Aa=wt,Ia=$e,Ta=wt,Ca=wt,Ki={version:Rs,versions:Ls,arch:Ts,platform:Cs,release:Fs,_rawDebug:$s,moduleLoadList:qs,binding:Ns,_linkedBinding:nh,_events:wa,_eventsCount:_a,_maxListeners:va,on:wt,addListener:ka,once:xa,off:Sa,removeListener:Ea,removeAllListeners:Aa,emit:Ia,prependListener:Ta,prependOnceListener:Ca,listeners:uh,domain:Hs,_exiting:Ws,config:zs,dlopen:ih,uptime:ch,_getActiveRequests:oh,_getActiveHandles:sh,reallyExit:Vs,_kill:Gs,cpuUsage:Tr,resourceUsage:Ks,memoryUsage:Ys,kill:Qs,exit:Js,openStdin:Xs,allowedNodeEnvironmentFlags:Zs,assert:ah,features:ea,_fatalExceptions:ta,setUncaughtExceptionCaptureCallback:ra,hasUncaughtExceptionCaptureCallback:lh,emitWarning:js,nextTick:rh,_tickCallback:na,_debugProcess:ia,_debugEnd:oa,_startProfilerIdleNotifier:sa,_stopProfilerIdleNotifier:aa,stdout:la,stdin:ua,stderr:ca,abort:ha,umask:Us,chdir:Ds,cwd:Bs,env:Os,title:Is,argv:Ps,execArgv:Ms,pid:da,ppid:fa,execPath:pa,debugPort:ma,hrtime:Vi,argv0:ga,_preload_modules:ba,setSourceMapsEnabled:ya}});function hh(){if(Yi)return Or;Yi=!0;var l=Ki;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 o="",a=0,c=-1,u=0,h,p=0;p<=n.length;++p){if(p<n.length)h=n.charCodeAt(p);else{if(h===47)break;h=47}if(h===47){if(!(c===p-1||u===1))if(c!==p-1&&u===2){if(o.length<2||a!==2||o.charCodeAt(o.length-1)!==46||o.charCodeAt(o.length-2)!==46){if(o.length>2){var y=o.lastIndexOf("/");if(y!==o.length-1){y===-1?(o="",a=0):(o=o.slice(0,y),a=o.length-1-o.lastIndexOf("/")),c=p,u=0;continue}}else if(o.length===2||o.length===1){o="",a=0,c=p,u=0;continue}}i&&(o.length>0?o+="/..":o="..",a=2)}else o.length>0?o+="/"+n.slice(c+1,p):o=n.slice(c+1,p),a=p-c-1;c=p,u=0}else h===46&&u!==-1?++u:u=-1}return o}function r(n,i){var o=i.dir||i.root,a=i.base||(i.name||"")+(i.ext||"");return o?o===i.root?o+a:o+n+a:a}var s={resolve:function(){for(var n="",i=!1,o,a=arguments.length-1;a>=-1&&!i;a--){var c;a>=0?c=arguments[a]:(o===void 0&&(o=l.cwd()),c=o),e(c),c.length!==0&&(n=c+"/"+n,i=c.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,o=n.charCodeAt(n.length-1)===47;return n=t(n,!i),n.length===0&&!i&&(n="."),n.length>0&&o&&(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 o=arguments[i];e(o),o.length>0&&(n===void 0?n=o:n+="/"+o)}return n===void 0?".":s.normalize(n)},relative:function(n,i){if(e(n),e(i),n===i||(n=s.resolve(n),i=s.resolve(i),n===i))return"";for(var o=1;o<n.length&&n.charCodeAt(o)===47;++o);for(var a=n.length,c=a-o,u=1;u<i.length&&i.charCodeAt(u)===47;++u);for(var h=i.length,p=h-u,y=c<p?c: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 c>y&&(n.charCodeAt(o+g)===47?f=g:g===0&&(f=0));break}var b=n.charCodeAt(o+g),k=i.charCodeAt(u+g);if(b!==k)break;b===47&&(f=g)}var m="";for(g=o+f+1;g<=a;++g)(g===a||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),o=i===47,a=-1,c=!0,u=n.length-1;u>=1;--u)if(i=n.charCodeAt(u),i===47){if(!c){a=u;break}}else c=!1;return a===-1?o?"/":".":o&&a===1?"//":n.slice(0,a)},basename:function(n,i){if(i!==void 0&&typeof i!="string")throw new TypeError('"ext" argument must be a string');e(n);var o=0,a=-1,c=!0,u;if(i!==void 0&&i.length>0&&i.length<=n.length){if(i.length===n.length&&i===n)return"";var h=i.length-1,p=-1;for(u=n.length-1;u>=0;--u){var y=n.charCodeAt(u);if(y===47){if(!c){o=u+1;break}}else p===-1&&(c=!1,p=u+1),h>=0&&(y===i.charCodeAt(h)?--h===-1&&(a=u):(h=-1,a=p))}return o===a?a=p:a===-1&&(a=n.length),n.slice(o,a)}else{for(u=n.length-1;u>=0;--u)if(n.charCodeAt(u)===47){if(!c){o=u+1;break}}else a===-1&&(c=!1,a=u+1);return a===-1?"":n.slice(o,a)}},extname:function(n){e(n);for(var i=-1,o=0,a=-1,c=!0,u=0,h=n.length-1;h>=0;--h){var p=n.charCodeAt(h);if(p===47){if(!c){o=h+1;break}continue}a===-1&&(c=!1,a=h+1),p===46?i===-1?i=h:u!==1&&(u=1):i!==-1&&(u=-1)}return i===-1||a===-1||u===0||u===1&&i===a-1&&i===o+1?"":n.slice(i,a)},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 o=n.charCodeAt(0),a=o===47,c;a?(i.root="/",c=1):c=0;for(var u=-1,h=0,p=-1,y=!0,f=n.length-1,g=0;f>=c;--f){if(o=n.charCodeAt(f),o===47){if(!y){h=f+1;break}continue}p===-1&&(y=!1,p=f+1),o===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===h+1?p!==-1&&(h===0&&a?i.base=i.name=n.slice(1,p):i.base=i.name=n.slice(h,p)):(h===0&&a?(i.name=n.slice(1,u),i.base=n.slice(1,p)):(i.name=n.slice(h,u),i.base=n.slice(h,p)),i.ext=n.slice(u,p)),h>0?i.dir=n.slice(0,h-1):a&&(i.dir="/"),i},sep:"/",delimiter:":",win32:null,posix:null};return s.posix=s,Or=s,Or}var Or,Yi,Qi,dh=Ve(()=>{le(),ue(),ce(),Oa(),Or={},Yi=!1,Qi=hh()}),Pa={};Rt(Pa,{URL:()=>qa,Url:()=>Ua,default:()=>qe,fileURLToPath:()=>Ra,format:()=>Ba,parse:()=>$a,pathToFileURL:()=>La,resolve:()=>Da,resolveObject:()=>Fa});function fh(){if(Xi)return Pr;Xi=!0;var l=typeof Map=="function"&&Map.prototype,e=Object.getOwnPropertyDescriptor&&l?Object.getOwnPropertyDescriptor(Map.prototype,"size"):null,t=l&&e&&typeof e.get=="function"?e.get:null,r=l&&Map.prototype.forEach,s=typeof Set=="function"&&Set.prototype,n=Object.getOwnPropertyDescriptor&&s?Object.getOwnPropertyDescriptor(Set.prototype,"size"):null,i=s&&n&&typeof n.get=="function"?n.get:null,o=s&&Set.prototype.forEach,a=typeof WeakMap=="function"&&WeakMap.prototype,c=a?WeakMap.prototype.has:null,u=typeof WeakSet=="function"&&WeakSet.prototype,h=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,x=String.prototype.toUpperCase,v=String.prototype.toLowerCase,E=RegExp.prototype.test,S=Array.prototype.concat,I=Array.prototype.join,O=Array.prototype.slice,P=Math.floor,N=typeof BigInt=="function"?BigInt.prototype.valueOf:null,T=Object.getOwnPropertySymbols,q=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?Symbol.prototype.toString:null,D=typeof Symbol=="function"&&typeof Symbol.iterator=="object",U=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 V(z,ie){if(z===1/0||z===-1/0||z!==z||z&&z>-1e3&&z<1e3||E.call(/e/,ie))return ie;var Ee=/[0-9](?=(?:[0-9]{3})+(?![0-9]))/g;if(typeof z=="number"){var Ae=z<0?-P(-z):P(z);if(Ae!==z){var Ie=String(Ae),Oe=m.call(ie,Ie.length+1);return w.call(Ie,Ee,"$&_")+"."+w.call(w.call(Oe,/([0-9]{3})/g,"$&_"),/_$/,"")}}return w.call(ie,Ee,"$&_")}var re=ja,F=re.custom,Z=K(F)?F:null;Pr=function z(ie,Ee,Ae,Ie){var Oe=Ee||{};if(oe(Oe,"quoteStyle")&&Oe.quoteStyle!=="single"&&Oe.quoteStyle!=="double")throw new TypeError('option "quoteStyle" must be "single" or "double"');if(oe(Oe,"maxStringLength")&&(typeof Oe.maxStringLength=="number"?Oe.maxStringLength<0&&Oe.maxStringLength!==1/0:Oe.maxStringLength!==null))throw new TypeError('option "maxStringLength", if provided, must be a positive integer, Infinity, or `null`');var et=oe(Oe,"customInspect")?Oe.customInspect:!0;if(typeof et!="boolean"&&et!=="symbol")throw new TypeError("option \"customInspect\", if provided, must be `true`, `false`, or `'symbol'`");if(oe(Oe,"indent")&&Oe.indent!==null&&Oe.indent!==" "&&!(parseInt(Oe.indent,10)===Oe.indent&&Oe.indent>0))throw new TypeError('option "indent" must be "\\t", an integer > 0, or `null`');if(oe(Oe,"numericSeparator")&&typeof Oe.numericSeparator!="boolean")throw new TypeError('option "numericSeparator", if provided, must be `true` or `false`');var tt=Oe.numericSeparator;if(typeof ie>"u")return"undefined";if(ie===null)return"null";if(typeof ie=="boolean")return ie?"true":"false";if(typeof ie=="string")return se(ie,Oe);if(typeof ie=="number"){if(ie===0)return 1/0/ie>0?"0":"-0";var He=String(ie);return tt?V(ie,He):He}if(typeof ie=="bigint"){var rt=String(ie)+"n";return tt?V(ie,rt):rt}var qt=typeof Oe.depth>"u"?5:Oe.depth;if(typeof Ae>"u"&&(Ae=0),Ae>=qt&&qt>0&&typeof ie=="object")return be(ie)?"[Array]":"[Object]";var nt=X(Oe,Ae);if(typeof Ie>"u")Ie=[];else if(ee(Ie,ie)>=0)return"[Circular]";function Ye(it,kt,Mt){if(kt&&(Ie=O.call(Ie),Ie.push(kt)),Mt){var ot={depth:Oe.depth};return oe(Oe,"quoteStyle")&&(ot.quoteStyle=Oe.quoteStyle),z(it,ot,Ae+1,Ie)}return z(it,Oe,Ae+1,Ie)}if(typeof ie=="function"&&!we(ie)){var zr=$(ie),Ht=ke(ie,Ye);return"[Function"+(zr?": "+zr:" (anonymous)")+"]"+(Ht.length>0?" { "+I.call(Ht,", ")+" }":"")}if(K(ie)){var Zt=D?w.call(String(ie),/^(Symbol\(.*\))_[^)]*$/,"$1"):q.call(ie);return typeof ie=="object"&&!D?d(Zt):Zt}if(ve(ie)){for(var C="<"+v.call(String(ie.nodeName)),L=ie.attributes||[],_e=0;_e<L.length;_e++)C+=" "+L[_e].name+"="+M(J(L[_e].value),"double",Oe);return C+=">",ie.childNodes&&ie.childNodes.length&&(C+="..."),C+="</"+v.call(String(ie.nodeName))+">",C}if(be(ie)){if(ie.length===0)return"[]";var xe=ke(ie,Ye);return nt&&!B(xe)?"["+he(xe,nt)+"]":"[ "+I.call(xe,", ")+" ]"}if(G(ie)){var Se=ke(ie,Ye);return!("cause"in Error.prototype)&&"cause"in ie&&!ae.call(ie,"cause")?"{ ["+String(ie)+"] "+I.call(S.call("[cause]: "+Ye(ie.cause),Se),", ")+" }":Se.length===0?"["+String(ie)+"]":"{ ["+String(ie)+"] "+I.call(Se,", ")+" }"}if(typeof ie=="object"&&et){if(Z&&typeof ie[Z]=="function"&&re)return re(ie,{depth:qt-Ae});if(et!=="symbol"&&typeof ie.inspect=="function")return ie.inspect()}if(de(ie)){var Ue=[];return r&&r.call(ie,function(it,kt){Ue.push(Ye(kt,ie,!0)+" => "+Ye(it,ie))}),A("Map",t.call(ie),Ue,nt)}if(H(ie)){var ze=[];return o&&o.call(ie,function(it){ze.push(Ye(it,ie))}),A("Set",i.call(ie),ze,nt)}if(fe(ie))return _("WeakMap");if(me(ie))return _("WeakSet");if(ye(ie))return _("WeakRef");if(ne(ie))return d(Ye(Number(ie)));if(Q(ie))return d(Ye(N.call(ie)));if(W(ie))return d(f.call(ie));if(j(ie))return d(Ye(String(ie)));if(typeof window<"u"&&ie===window)return"{ [object Window] }";if(typeof globalThis<"u"&&ie===globalThis||typeof Mr<"u"&&ie===Mr)return"{ [object globalThis] }";if(!te(ie)&&!we(ie)){var Je=ke(ie,Ye),er=Y?Y(ie)===Object.prototype:ie instanceof Object||ie.constructor===Object,tr=ie instanceof Object?"":"null prototype",rr=!er&&U&&Object(ie)===ie&&U in ie?m.call(R(ie),8,-1):tr?"Object":"",Vr=er||typeof ie.constructor!="function"?"":ie.constructor.name?ie.constructor.name+" ":"",Pt=Vr+(rr||tr?"["+I.call(S.call([],rr||[],tr||[]),": ")+"] ":"");return Je.length===0?Pt+"{}":nt?Pt+"{"+he(Je,nt)+"}":Pt+"{ "+I.call(Je,", ")+" }"}return String(ie)};function M(z,ie,Ee){var Ae=(Ee.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]"&&(!U||!(typeof z=="object"&&U in z))}function te(z){return R(z)==="[object Date]"&&(!U||!(typeof z=="object"&&U in z))}function we(z){return R(z)==="[object RegExp]"&&(!U||!(typeof z=="object"&&U in z))}function G(z){return R(z)==="[object Error]"&&(!U||!(typeof z=="object"&&U in z))}function j(z){return R(z)==="[object String]"&&(!U||!(typeof z=="object"&&U in z))}function ne(z){return R(z)==="[object Number]"&&(!U||!(typeof z=="object"&&U in z))}function W(z){return R(z)==="[object Boolean]"&&(!U||!(typeof z=="object"&&U in z))}function K(z){if(D)return z&&typeof z=="object"&&z instanceof Symbol;if(typeof z=="symbol")return!0;if(!z||typeof z!="object"||!q)return!1;try{return q.call(z),!0}catch{}return!1}function Q(z){if(!z||typeof z!="object"||!N)return!1;try{return N.call(z),!0}catch{}return!1}var ge=Object.prototype.hasOwnProperty||function(z){return z in(this||Mr)};function oe(z,ie){return ge.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 Ee=0,Ae=z.length;Ee<Ae;Ee++)if(z[Ee]===ie)return Ee;return-1}function de(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 fe(z){if(!c||!z||typeof z!="object")return!1;try{c.call(z,c);try{h.call(z,h)}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 H(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 me(z){if(!h||!z||typeof z!="object")return!1;try{h.call(z,h);try{c.call(z,c)}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 Ee=z.length-ie.maxStringLength,Ae="... "+Ee+" more character"+(Ee>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 M(Ie,"single",ie)}function Te(z){var ie=z.charCodeAt(0),Ee={8:"b",9:"t",10:"n",12:"f",13:"r"}[ie];return Ee?"\\"+Ee:"\\x"+(ie<16?"0":"")+x.call(ie.toString(16))}function d(z){return"Object("+z+")"}function _(z){return z+" { ? }"}function A(z,ie,Ee,Ae){var Ie=Ae?he(Ee,Ae):I.call(Ee,", ");return z+" ("+ie+") {"+Ie+"}"}function B(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 Ee;if(z.indent===" ")Ee=" ";else if(typeof z.indent=="number"&&z.indent>0)Ee=I.call(Array(z.indent+1)," ");else return null;return{base:Ee,prev:I.call(Array(ie+1),Ee)}}function he(z,ie){if(z.length===0)return"";var Ee=`
5
5
  `+ie.prev+ie.base;return Ee+I.call(z,","+Ee)+`
6
- `+ie.prev}function ke(z,ie){var Ee=be(z),Ae=[];if(Ee){Ae.length=z.length;for(var Ie=0;Ie<z.length;Ie++)Ae[Ie]=oe(z,Ie)?ie(z[Ie],z):""}var Oe=typeof T=="function"?T(z):[],et;if(D){et={};for(var tt=0;tt<Oe.length;tt++)et["$"+Oe[tt]]=Oe[tt]}for(var He in z)oe(z,He)&&(Ee&&String(Number(He))===He&&He<z.length||D&&et["$"+He]instanceof Symbol||(E.call(/[^\w$]/,He)?Ae.push(ie(He,z)+": "+ie(z[He],z)):Ae.push(He+": "+ie(z[He],z))));if(typeof T=="function")for(var rt=0;rt<Oe.length;rt++)ae.call(z,Oe[rt])&&Ae.push("["+ie(Oe[rt])+"]: "+ie(z[Oe[rt]],z));return Ae}return Pr}function ph(){if(Zi)return Rr;Zi=!0;var l=Bt(),e=Zu(),t=fh(),r=Qt(),s=l("%WeakMap%",!0),n=l("%Map%",!0),i=e("WeakMap.prototype.get",!0),o=e("WeakMap.prototype.set",!0),a=e("WeakMap.prototype.has",!0),c=e("Map.prototype.get",!0),u=e("Map.prototype.set",!0),h=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 Rr=function(){var y,k,m,w={assert:function(S){if(!w.has(S))throw new r("Side channel does not contain "+t(S))},get:function(S){if(s&&S&&(typeof S=="object"||typeof S=="function")){if(y)return i(y,S)}else if(n){if(k)return c(k,S)}else if(m)return b(m,S)},has:function(S){if(s&&S&&(typeof S=="object"||typeof S=="function")){if(y)return a(y,S)}else if(n){if(k)return h(k,S)}else if(m)return g(m,S);return!1},set:function(S,v){s&&S&&(typeof S=="object"||typeof S=="function")?(y||(y=new s),o(y,S,v)):n?(k||(k=new n),u(k,S,v)):(m||(m={key:{},next:null}),f(m,S,v))}};return w},Rr}function Ji(){if(eo)return Lr;eo=!0;var l=String.prototype.replace,e=/%20/g,t={RFC1738:"RFC1738",RFC3986:"RFC3986"};return Lr={default:t.RFC3986,formatters:{RFC1738:function(r){return l.call(r,e,"+")},RFC3986:function(r){return String(r)}},RFC1738:t.RFC1738,RFC3986:t.RFC3986},Lr}function Ma(){if(to)return jr;to=!0;var l=Ji(),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})(),s=function(y){for(;y.length>1;){var k=y.pop(),m=k.obj[k.prop];if(t(m)){for(var w=[],S=0;S<m.length;++S)typeof m[S]<"u"&&w.push(m[S]);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 S=k;return t(k)&&!t(m)&&(S=n(k,w)),t(k)&&t(m)?(m.forEach(function(v,E){if(e.call(k,E)){var x=k[E];x&&typeof x=="object"&&v&&typeof v=="object"?k[E]=y(x,v,w):k.push(v)}else k[E]=v}),k):Object.keys(m).reduce(function(v,E){var x=m[E];return e.call(v,E)?v[E]=y(v[E],x,w):v[E]=x,v},S)},o=function(y,k){return Object.keys(k).reduce(function(m,w){return m[w]=k[w],m},y)},a=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}},c=1024,u=function(y,k,m,w,S){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 E="",x=0;x<v.length;x+=c){for(var I=v.length>=c?v.slice(x,x+c):v,P=[],O=0;O<I.length;++O){var B=I.charCodeAt(O);if(B===45||B===46||B===95||B===126||B>=48&&B<=57||B>=65&&B<=90||B>=97&&B<=122||S===l.RFC1738&&(B===40||B===41)){P[P.length]=I.charAt(O);continue}if(B<128){P[P.length]=r[B];continue}if(B<2048){P[P.length]=r[192|B>>6]+r[128|B&63];continue}if(B<55296||B>=57344){P[P.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),P[P.length]=r[240|B>>18]+r[128|B>>12&63]+r[128|B>>6&63]+r[128|B&63]}E+=P.join("")}return E},h=function(y){for(var k=[{obj:{o:y},prop:"o"}],m=[],w=0;w<k.length;++w)for(var S=k[w],v=S.obj[S.prop],E=Object.keys(v),x=0;x<E.length;++x){var I=E[x],P=v[I];typeof P=="object"&&P!==null&&m.indexOf(P)===-1&&(k.push({obj:v,prop:I}),m.push(P))}return s(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 jr={arrayToObject:n,assign:o,combine:f,compact:h,decode:a,encode:u,isBuffer:b,isRegExp:p,maybeMap:g,merge:i},jr}function mh(){if(ro)return Nr;ro=!0;var l=ph(),e=Ma(),t=Ji(),r=Object.prototype.hasOwnProperty,s={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,o=function(g,y){i.apply(g,n(y)?y:[y])},a=Date.prototype.toISOString,c=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:c,formatter:t.formatters[c],indices:!1,serializeDate:function(g){return a.call(g)},skipNulls:!1,strictNullHandling:!1},h=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,S,v,E,x,I,P,O,B,T,q,D,N,ae,Y){for(var V=y,re=Y,F=0,Z=!1;(re=re.get(p))!==void 0&&!Z;){var M=re.get(y);if(F+=1,typeof M<"u"){if(M===F)throw new RangeError("Cyclic object value");Z=!0}typeof re.get(p)>"u"&&(F=0)}if(typeof P=="function"?V=P(k,V):V instanceof Date?V=T(V):m==="comma"&&n(V)&&(V=e.maybeMap(V,function(R){return R instanceof Date?T(R):R})),V===null){if(v)return I&&!N?I(k,u.encoder,ae,"key",q):k;V=""}if(h(V)||e.isBuffer(V)){if(I){var J=N?k:I(k,u.encoder,ae,"key",q);return[D(J)+"="+D(I(V,u.encoder,ae,"value",q))]}return[D(k)+"="+D(String(V))]}var be=[];if(typeof V>"u")return be;var te;if(m==="comma"&&n(V))N&&I&&(V=e.maybeMap(V,I)),te=[{value:V.length>0?V.join(",")||null:void 0}];else if(n(P))te=P;else{var we=Object.keys(V);te=O?we.sort(O):we}var G=x?k.replace(/\./g,"%2E"):k,j=w&&n(V)&&V.length===1?G+"[]":G;if(S&&n(V)&&V.length===0)return j+"[]";for(var ne=0;ne<te.length;++ne){var W=te[ne],K=typeof W=="object"&&typeof W.value<"u"?W.value:V[W];if(!(E&&K===null)){var Q=B&&x?W.replace(/\./g,"%2E"):W,ge=n(V)?typeof m=="function"?m(j,Q):j:j+(B?"."+Q:"["+Q+"]");Y.set(y,F);var oe=l();oe.set(p,Y),o(be,g(K,ge,m,w,S,v,E,x,m==="comma"&&N&&n(V)?null:I,P,O,B,T,q,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 S;if(g.arrayFormat in s?S=g.arrayFormat:"indices"in g?S=g.indices?"indices":"repeat":S=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:S,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 Nr=function(g,y){var k=g,m=f(y),w,S;typeof m.filter=="function"?(S=m.filter,k=S("",k)):n(m.filter)&&(S=m.filter,w=S);var v=[];if(typeof k!="object"||k===null)return"";var E=s[m.arrayFormat],x=E==="comma"&&m.commaRoundTrip;w||(w=Object.keys(k)),m.sort&&w.sort(m.sort);for(var I=l(),P=0;P<w.length;++P){var O=w[P];m.skipNulls&&k[O]===null||o(v,b(k[O],O,E,x,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:""},Nr}function gh(){if(no)return Ur;no=!0;var l=Ma(),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:l.decode,delimiter:"&",depth:5,duplicates:"combine",ignoreQueryPrefix:!1,interpretNumericEntities:!1,parameterLimit:1e3,parseArrays:!0,plainObjects:!1,strictDepth:!1,strictNullHandling:!1},s=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",o="utf8=%E2%9C%93",a=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,S=b.charset;if(b.charsetSentinel)for(w=0;w<k.length;++w)k[w].indexOf("utf8=")===0&&(k[w]===o?S="utf-8":k[w]===i&&(S="iso-8859-1"),m=w,w=k.length);for(w=0;w<k.length;++w)if(w!==m){var v=k[w],E=v.indexOf("]="),x=E===-1?v.indexOf("="):E+1,I,P;x===-1?(I=b.decoder(v,r.decoder,S,"key"),P=b.strictNullHandling?null:""):(I=b.decoder(v.slice(0,x),r.decoder,S,"key"),P=l.maybeMap(n(v.slice(x+1),b),function(B){return b.decoder(B,r.decoder,S,"value")})),P&&b.interpretNumericEntities&&S==="iso-8859-1"&&(P=s(P)),v.indexOf("[]=")>-1&&(P=t(P)?[P]:P);var O=e.call(f,I);O&&b.duplicates==="combine"?f[I]=l.combine(f[I],P):(!O||b.duplicates==="last")&&(f[I]=P)}return f},c=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 S=w.charAt(0)==="["&&w.charAt(w.length-1)==="]"?w.slice(1,-1):w,v=f.decodeDotInKeys?S.replace(/%2E/g,"."):S,E=parseInt(v,10);!f.parseArrays&&v===""?m={0:y}:!isNaN(E)&&w!==v&&String(E)===v&&E>=0&&f.parseArrays&&E<=f.arrayLimit?(m=[],m[E]=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),S=w?y.slice(0,w.index):y,v=[];if(S){if(!f.plainObjects&&e.call(Object.prototype,S)&&!f.allowPrototypes)return;v.push(S)}for(var E=0;f.depth>0&&(w=m.exec(y))!==null&&E<f.depth;){if(E+=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 c(v,b,f,g)}},h=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"||l.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 Ur=function(p,b){var f=h(b);if(p===""||p===null||typeof p>"u")return f.plainObjects?Object.create(null):{};for(var g=typeof p=="string"?a(p,f):p,y=f.plainObjects?Object.create(null):{},k=Object.keys(g),m=0;m<k.length;++m){var w=k[m],S=u(w,g[w],f,typeof p=="string");y=l.merge(y,S,f)}return f.allowSparse===!0?y:l.compact(y)},Ur}function bh(){if(io)return Br;io=!0;var l=mh(),e=gh(),t=Ji();return Br={formats:t,parse:e,stringify:l},Br}function yh(){if(oo)return _t;oo=!0;var l=vt;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]*$/,s=/^(\/\/?(?!\/)[^?\s]*)(\?[^\s]*)?$/,n=["<",">",'"',"`"," ","\r",`
7
- `," "],i=["{","}","|","\\","^","`"].concat(n),o=["'"].concat(i),a=["%","/","?",";","#"].concat(o),c=["/","?","#"],u=255,h=/^[+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=bh();function k(v,E,x){if(v&&typeof v=="object"&&v instanceof e)return v;var I=new e;return I.parse(v,E,x),I}e.prototype.parse=function(v,E,x){if(typeof v!="string")throw new TypeError("Parameter 'url' must be a string, not "+typeof v);var I=v.indexOf("?"),P=I!==-1&&I<v.indexOf("#")?"?":"#",O=v.split(P),B=/\\/g;O[0]=O[0].replace(B,"/"),v=O.join(P);var T=v;if(T=T.trim(),!x&&v.split("#").length===1){var q=s.exec(T);if(q)return this.path=T,this.href=T,this.pathname=q[1],q[2]?(this.search=q[2],E?this.query=y.parse(this.search.substr(1)):this.query=this.search.substr(1)):E&&(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(x||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,V=0;V<c.length;V++){var re=T.indexOf(c[V]);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 V=0;V<a.length;V++){var re=T.indexOf(a[V]);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 M=this.hostname[0]==="["&&this.hostname[this.hostname.length-1]==="]";if(!M)for(var J=this.hostname.split(/\./),V=0,be=J.length;V<be;V++){var te=J[V];if(te&&!te.match(h)){for(var we="",G=0,j=te.length;G<j;G++)te.charCodeAt(G)>127?we+="x":we+=te[G];if(!we.match(h)){var ne=J.slice(0,V),W=J.slice(V+1),K=te.match(p);K&&(ne.push(K[1]),W.unshift(K[2])),W.length&&(T="/"+W.join(".")+T),this.hostname=ne.join(".");break}}}this.hostname.length>u?this.hostname="":this.hostname=this.hostname.toLowerCase(),M||(this.hostname=l.toASCII(this.hostname));var Q=this.port?":"+this.port:"",ge=this.hostname||"";this.host=ge+Q,this.href+=this.host,M&&(this.hostname=this.hostname.substr(1,this.hostname.length-2),T[0]!=="/"&&(T="/"+T))}if(!b[N])for(var V=0,be=o.length;V<be;V++){var oe=o[V];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),E&&(this.query=y.parse(this.query)),T=T.slice(0,ee)):E&&(this.search="",this.query={}),T&&(this.pathname=T),g[N]&&this.hostname&&!this.pathname&&(this.pathname="/"),this.pathname||this.search){var Q=this.pathname||"",de=this.search||"";this.path=Q+de}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 E=this.protocol||"",x=this.pathname||"",I=this.hash||"",P=!1,O="";this.host?P=v+this.host:this.hostname&&(P=v+(this.hostname.indexOf(":")===-1?this.hostname:"["+this.hostname+"]"),this.port&&(P+=":"+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 E&&E.substr(-1)!==":"&&(E+=":"),this.slashes||(!E||g[E])&&P!==!1?(P="//"+(P||""),x&&x.charAt(0)!=="/"&&(x="/"+x)):P||(P=""),I&&I.charAt(0)!=="#"&&(I="#"+I),B&&B.charAt(0)!=="?"&&(B="?"+B),x=x.replace(/[?#]/g,function(T){return encodeURIComponent(T)}),B=B.replace("#","%23"),E+P+x+B+I};function w(v,E){return k(v,!1,!0).resolve(E)}e.prototype.resolve=function(v){return this.resolveObject(k(v,!1,!0)).format()};function S(v,E){return v?k(v,!1,!0).resolveObject(E):E}return e.prototype.resolveObject=function(v){if(typeof v=="string"){var E=new e;E.parse(v,!1,!0),v=E}for(var x=new e,I=Object.keys(this),P=0;P<I.length;P++){var O=I[P];x[O]=this[O]}if(x.hash=v.hash,v.href==="")return x.href=x.format(),x;if(v.slashes&&!v.protocol){for(var B=Object.keys(v),T=0;T<B.length;T++){var q=B[T];q!=="protocol"&&(x[q]=v[q])}return g[x.protocol]&&x.hostname&&!x.pathname&&(x.pathname="/",x.path=x.pathname),x.href=x.format(),x}if(v.protocol&&v.protocol!==x.protocol){if(!g[v.protocol]){for(var D=Object.keys(v),N=0;N<D.length;N++){var ae=D[N];x[ae]=v[ae]}return x.href=x.format(),x}if(x.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(""),x.pathname=be.join("/")}else x.pathname=v.pathname;if(x.search=v.search,x.query=v.query,x.host=v.host||"",x.auth=v.auth,x.hostname=v.hostname||v.host,x.port=v.port,x.pathname||x.search){var Y=x.pathname||"",V=x.search||"";x.path=Y+V}return x.slashes=x.slashes||v.slashes,x.href=x.format(),x}var re=x.pathname&&x.pathname.charAt(0)==="/",F=v.host||v.pathname&&v.pathname.charAt(0)==="/",Z=F||re||x.host&&v.pathname,M=Z,J=x.pathname&&x.pathname.split("/")||[],be=v.pathname&&v.pathname.split("/")||[],te=x.protocol&&!g[x.protocol];if(te&&(x.hostname="",x.port=null,x.host&&(J[0]===""?J[0]=x.host:J.unshift(x.host)),x.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)x.host=v.host||v.host===""?v.host:x.host,x.hostname=v.hostname||v.hostname===""?v.hostname:x.hostname,x.search=v.search,x.query=v.query,J=be;else if(be.length)J||(J=[]),J.pop(),J=J.concat(be),x.search=v.search,x.query=v.query;else if(v.search!=null){if(te){x.host=J.shift(),x.hostname=x.host;var we=x.host&&x.host.indexOf("@")>0?x.host.split("@"):!1;we&&(x.auth=we.shift(),x.hostname=we.shift(),x.host=x.hostname)}return x.search=v.search,x.query=v.query,(x.pathname!==null||x.search!==null)&&(x.path=(x.pathname?x.pathname:"")+(x.search?x.search:"")),x.href=x.format(),x}if(!J.length)return x.pathname=null,x.search?x.path="/"+x.search:x.path=null,x.href=x.format(),x;for(var G=J.slice(-1)[0],j=(x.host||v.host||J.length>1)&&(G==="."||G==="..")||G==="",ne=0,W=J.length;W>=0;W--)G=J[W],G==="."?J.splice(W,1):G===".."?(J.splice(W,1),ne++):ne&&(J.splice(W,1),ne--);if(!Z&&!M)for(;ne--;ne)J.unshift("..");Z&&J[0]!==""&&(!J[0]||J[0].charAt(0)!=="/")&&J.unshift(""),j&&J.join("/").substr(-1)!=="/"&&J.push("");var K=J[0]===""||J[0]&&J[0].charAt(0)==="/";if(te){x.hostname=K?"":J.length?J.shift():"",x.host=x.hostname;var we=x.host&&x.host.indexOf("@")>0?x.host.split("@"):!1;we&&(x.auth=we.shift(),x.hostname=we.shift(),x.host=x.hostname)}return Z=Z||x.host&&J.length,Z&&!K&&J.unshift(""),J.length>0?x.pathname=J.join("/"):(x.pathname=null,x.path=null),(x.pathname!==null||x.search!==null)&&(x.path=(x.pathname?x.pathname:"")+(x.search?x.search:"")),x.auth=v.auth||x.auth,x.slashes=x.slashes||v.slashes,x.href=x.format(),x},e.prototype.parseHost=function(){var v=this.host,E=r.exec(v);E&&(E=E[0],E!==":"&&(this.port=E.substr(1)),v=v.substr(0,v.length-E.length)),v&&(this.hostname=v)},_t.parse=k,_t.resolve=w,_t.resolveObject=S,_t.format=m,_t.Url=e,_t}function Ra(l){if(typeof l=="string")l=new URL(l);else if(!(l instanceof URL))throw new Deno.errors.InvalidData("invalid argument path , must be a string or URL");if(l.protocol!=="file:")throw new Deno.errors.InvalidData("invalid url scheme");return Dr?vh(l):wh(l)}function vh(l){let e=l.hostname,t=l.pathname;for(let r=0;r<t.length;r++)if(t[r]==="%"){let s=t.codePointAt(r+2)||32;if(t[r+1]==="2"&&s===102||t[r+1]==="5"&&s===99)throw new Deno.errors.InvalidData("must not include encoded \\ or / characters")}if(t=t.replace(Ga,"\\"),t=decodeURIComponent(t),e!=="")return`\\\\${e}${t}`;{let r=t.codePointAt(1)|32,s=t[2];if(r<za||r>Va||s!==":")throw new Deno.errors.InvalidData("file url path must be absolute");return t.slice(1)}}function wh(l){if(l.hostname!=="")throw new Deno.errors.InvalidData("invalid file url hostname");let e=l.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 La(l){let e=Qi.resolve(l),t=l.charCodeAt(l.length-1);(t===Wa||Dr&&t===Ha)&&e[e.length-1]!==Qi.sep&&(e+="/");let r=new URL("file://");return e.includes("%")&&(e=e.replace(Ka,"%25")),!Dr&&e.includes("\\")&&(e=e.replace(Ya,"%5C")),e.includes(`
8
- `)&&(e=e.replace(Qa,"%0A")),e.includes("\r")&&(e=e.replace(Ja,"%0D")),e.includes(" ")&&(e=e.replace(Xa,"%09")),r.pathname=e,r}var ja,Pr,Xi,Mr,Rr,Zi,Lr,eo,jr,to,Nr,ro,Ur,no,Br,io,_t,oo,qe,Na,Ua,Ba,Da,Fa,$a,qa,Ha,Wa,za,Va,Dr,Ga,Ka,Ya,Qa,Ja,Xa,_h=Ve(()=>{le(),ue(),ce(),Bu(),eh(),dh(),Oa(),ja=Object.freeze(Object.create(null)),Pr={},Xi=!1,Mr=typeof globalThis<"u"?globalThis:typeof self<"u"?self:global,Rr={},Zi=!1,Lr={},eo=!1,jr={},to=!1,Nr={},ro=!1,Ur={},no=!1,Br={},io=!1,_t={},oo=!1,qe=yh(),qe.parse,qe.resolve,qe.resolveObject,qe.format,qe.Url,Na=typeof Deno<"u"?Deno.build.os==="windows"?"win32":Deno.build.os:void 0,qe.URL=typeof URL<"u"?URL:null,qe.pathToFileURL=La,qe.fileURLToPath=Ra,Ua=qe.Url,Ba=qe.format,Da=qe.resolve,Fa=qe.resolveObject,$a=qe.parse,qa=qe.URL,Ha=92,Wa=47,za=97,Va=122,Dr=Na==="win32",Ga=/\//g,Ka=/%/g,Ya=/\\/g,Qa=/\n/g,Ja=/\r/g,Xa=/\t/g}),kh=pe((l,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(l=>{le(),ue(),ce(),Object.defineProperty(l,"__esModule",{value:!0}),l.BufferedDuplex=void 0,l.writev=r;var e=It(),t=(De(),Me(Be));function r(n,i){let o=new Array(n.length);for(let a=0;a<n.length;a++)typeof n[a].chunk=="string"?o[a]=t.Buffer.from(n[a].chunk,"utf8"):o[a]=n[a].chunk;this._write(t.Buffer.concat(o),"binary",i)}var s=class extends e.Duplex{socket;proxy;isSocketOpen;writeQueue;constructor(n,i,o){super({objectMode:!0}),this.proxy=i,this.socket=o,this.writeQueue=[],n.objectMode||(this._writev=r.bind(this)),this.isSocketOpen=!1,this.proxy.on("data",a=>{!this.destroyed&&this.readable&&this.push(a)})}_read(n){this.proxy.read(n)}_write(n,i,o){this.isSocketOpen?this.writeToProxy(n,i,o):this.writeQueue.push({chunk:n,encoding:i,cb:o})}_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,o){this.proxy.write(n,i)===!1?this.proxy.once("drain",o):o()}processWriteQueue(){for(;this.writeQueue.length>0;){let{chunk:n,encoding:i,cb:o}=this.writeQueue.shift();this.writeToProxy(n,i,o)}}};l.BufferedDuplex=s}),Fr=pe(l=>{le(),ue(),ce();var e=l&&l.__importDefault||function(k){return k&&k.__esModule?k:{default:k}};Object.defineProperty(l,"__esModule",{value:!0}),l.streamBuilder=l.browserStreamBuilder=void 0;var t=(De(),Me(Be)),r=e(kh()),s=e(ht()),n=It(),i=e(pr()),o=so(),a=(0,s.default)("mqttjs:ws"),c=["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 h(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"&&c.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=h(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){a("createWebSocket"),a(`protocol: ${w.protocolId} ${w.protocolVersion}`);let S=w.protocolId==="MQIsdp"&&w.protocolVersion===3?"mqttv3.1":"mqtt";a(`creating new Websocket for url: ${m} and protocol: ${S}`);let v;return w.createWebsocket?v=w.createWebsocket(m,[S],w):v=new r.default(m,[S],w.wsOptions),v}function f(k,m){let w=m.protocolId==="MQIsdp"&&m.protocolVersion===3?"mqttv3.1":"mqtt",S=u(m,k),v;return m.createWebsocket?v=m.createWebsocket(S,[w],m):v=new WebSocket(S,[w]),v.binaryType="arraybuffer",v}var g=(k,m)=>{a("streamBuilder");let w=h(m);w.hostname=w.hostname||w.host||"localhost";let S=u(w,k),v=b(k,S,w),E=r.default.createWebSocketStream(v,w.wsOptions);return E.url=S,v.on("close",()=>{E.destroy()}),E};l.streamBuilder=g;var y=(k,m)=>{a("browserStreamBuilder");let w,S=p(m).browserBufferSize||1024*512,v=m.browserBufferTimeout||1e3,E=!m.objectMode,x=f(k,m),I=O(m,N,ae);m.objectMode||(I._writev=o.writev.bind(I)),I.on("close",()=>{x.close()});let P=typeof x.addEventListener<"u";x.readyState===x.OPEN?(w=I,w.socket=x):(w=new o.BufferedDuplex(m,I,x),P?x.addEventListener("open",B):x.onopen=B),P?(x.addEventListener("close",T),x.addEventListener("error",q),x.addEventListener("message",D)):(x.onclose=T,x.onerror=q,x.onmessage=D);function O(Y,V,re){let F=new n.Transform({objectMode:Y.objectMode});return F._write=V,F._flush=re,F}function B(){a("WebSocket onOpen"),w instanceof o.BufferedDuplex&&w.socketReady()}function T(Y){a("WebSocket onClose",Y),w.end(),w.destroy()}function q(Y){a("WebSocket onError",Y);let V=new Error("WebSocket error");V.event=Y,w.destroy(V)}async function D(Y){if(!I||!I.readable||!I.writable)return;let{data:V}=Y;V instanceof ArrayBuffer?V=t.Buffer.from(V):V instanceof Blob?V=t.Buffer.from(await new Response(V).arrayBuffer()):V=t.Buffer.from(V,"utf8"),I.push(V)}function N(Y,V,re){if(x.bufferedAmount>S){setTimeout(N,v,Y,V,re);return}E&&typeof Y=="string"&&(Y=t.Buffer.from(Y,"utf8"));try{x.send(Y)}catch(F){return re(F)}re()}function ae(Y){x.close(),Y()}return w};l.browserStreamBuilder=y}),ao={};Rt(ao,{Server:()=>je,Socket:()=>je,Stream:()=>je,_createServerHandle:()=>je,_normalizeArgs:()=>je,_setSimultaneousAccepts:()=>je,connect:()=>je,createConnection:()=>je,createServer:()=>je,default:()=>Za,isIP:()=>je,isIPv4:()=>je,isIPv6:()=>je});function je(){throw new Error("Node.js net module is not supported by JSPM core outside of Node.js")}var Za,el=Ve(()=>{le(),ue(),ce(),Za={_createServerHandle:je,_normalizeArgs:je,_setSimultaneousAccepts:je,connect:je,createConnection:je,createServer:je,isIP:je,isIPv4:je,isIPv6:je,Server:je,Socket:je,Stream:je}}),tl=pe((l,e)=>{le(),ue(),ce(),e.exports={}}),rl=pe(l=>{le(),ue(),ce();var e=l&&l.__importDefault||function(o){return o&&o.__esModule?o:{default:o}};Object.defineProperty(l,"__esModule",{value:!0});var t=e((el(),Me(ao))),r=e(ht()),s=e(tl()),n=(0,r.default)("mqttjs:tcp"),i=(o,a)=>{if(a.port=a.port||1883,a.hostname=a.hostname||a.host||"localhost",a.socksProxy)return(0,s.default)(a.hostname,a.port,a.socksProxy,{timeout:a.socksTimeout});let{port:c,path:u}=a,h=a.hostname;return n("port %d and host %s",c,h),t.default.createConnection({port:c,host:h,path:u})};l.default=i}),nl={};Rt(nl,{default:()=>il});var il,xh=Ve(()=>{le(),ue(),ce(),il={}}),ol=pe(l=>{le(),ue(),ce();var e=l&&l.__importDefault||function(c){return c&&c.__esModule?c:{default:c}};Object.defineProperty(l,"__esModule",{value:!0});var t=(xh(),Me(nl)),r=e((el(),Me(ao))),s=e(ht()),n=e(tl()),i=(0,s.default)("mqttjs:tls");function o(c){let{host:u,port:h,socksProxy:p,...b}=c;if(p!==void 0){let f=(0,n.default)(u,h,p,{timeout:c.socksTimeout});return(0,t.connect)({...b,socket:f})}return(0,t.connect)(c)}var a=(c,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 h=o(u);h.on("secureConnect",()=>{u.rejectUnauthorized&&!h.authorized?h.emit("error",new Error("TLS not authorized")):h.removeListener("error",p)});function p(b){u.rejectUnauthorized&&c.emit("error",b),h.end()}return h.on("error",p),h};l.default=a}),sl=pe(l=>{le(),ue(),ce(),Object.defineProperty(l,"__esModule",{value:!0});var e=(De(),Me(Be)),t=It(),r=so(),s,n,i;function o(){let p=new t.Transform;return p._write=(b,f,g)=>{s.send({data:b.buffer,success(){g()},fail(y){g(new Error(y))}})},p._flush=b=>{s.close({success(){b()}})},p}function a(p){p.hostname||(p.hostname="localhost"),p.path||(p.path="/"),p.wsOptions||(p.wsOptions={})}function c(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(){s.onOpen(()=>{i.socketReady()}),s.onMessage(p=>{let{data:b}=p;b instanceof ArrayBuffer?b=e.Buffer.from(b):b=e.Buffer.from(b,"utf8"),n.push(b)}),s.onClose(()=>{i.emit("close"),i.end(),i.destroy()}),s.onError(p=>{let b=new Error(p.errMsg);i.destroy(b)})}var h=(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";a(b);let g=c(b,p);s=wx.connectSocket({url:g,protocols:[f]}),n=o(),i=new r.BufferedDuplex(b,n,s),i._destroy=(k,m)=>{s.close({success(){m&&m(k)}})};let y=i.destroy;return i.destroy=(k,m)=>(i.destroy=y,setTimeout(()=>{s.close({fail(){i._destroy(k,m)}})},0),i),u(),i};l.default=h}),al=pe(l=>{le(),ue(),ce(),Object.defineProperty(l,"__esModule",{value:!0});var e=(De(),Me(Be)),t=It(),r=so(),s,n,i,o=!1;function a(){let b=new t.Transform;return b._write=(f,g,y)=>{s.sendSocketMessage({data:f.buffer,success(){y()},fail(){y(new Error)}})},b._flush=f=>{s.closeSocket({success(){f()}})},b}function c(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 h(){o||(o=!0,s.onSocketOpen(()=>{i.socketReady()}),s.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)}}),s.onSocketClose(()=>{i.end(),i.destroy()}),s.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";c(f);let y=u(f,b);return s=f.my,s.connectSocket({url:y,protocols:g}),n=a(),i=new r.BufferedDuplex(f,n,s),h(),i};l.default=p}),Sh=pe(l=>{le(),ue(),ce();var e=l&&l.__importDefault||function(h){return h&&h.__esModule?h:{default:h}};Object.defineProperty(l,"__esModule",{value:!0}),l.connectAsync=u;var t=e(ht()),r=e((_h(),Me(Pa))),s=e(di()),n=e(pr());typeof Le?.nextTick!="function"&&(Le.nextTick=setImmediate);var i=(0,t.default)("mqttjs"),o=null;function a(h){let p;if(h.auth)if(p=h.auth.match(/^(.+):(.+)$/),p){let[,b,f]=p;h.username=b,h.password=f}else h.username=h.auth}function c(h,p){if(i("connecting to an MQTT broker..."),typeof h=="object"&&!p&&(p=h,h=""),p=p||{},h&&typeof h=="string"){let g=r.default.parse(h,!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,a(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 Le<"u"&&(p.socksProxy=Le.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(o||(o={},!n.default&&!p.forceNativeWebSocket?(o.ws=Fr().streamBuilder,o.wss=Fr().streamBuilder,o.mqtt=rl().default,o.tcp=rl().default,o.ssl=ol().default,o.tls=o.ssl,o.mqtts=ol().default):(o.ws=Fr().browserStreamBuilder,o.wss=Fr().browserStreamBuilder,o.wx=sl().default,o.wxs=sl().default,o.ali=al().default,o.alis=al().default)),!o[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 o[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),o[p.protocol](g,p)}let f=new s.default(b,p);return f.on("error",()=>{}),f}function u(h,p,b=!0){return new Promise((f,g)=>{let y=c(h,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])})})}l.default=c}),ll=pe(l=>{le(),ue(),ce();var e=l&&l.__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=l&&l.__setModuleDefault||(Object.create?function(b,f){Object.defineProperty(b,"default",{enumerable:!0,value:f})}:function(b,f){b.default=f}),r=l&&l.__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}})(),s=l&&l.__exportStar||function(b,f){for(var g in b)g!=="default"&&!Object.prototype.hasOwnProperty.call(f,g)&&e(f,b,g)},n=l&&l.__importDefault||function(b){return b&&b.__esModule?b:{default:b}};Object.defineProperty(l,"__esModule",{value:!0}),l.ReasonCodes=l.KeepaliveManager=l.UniqueMessageIdProvider=l.DefaultMessageIdProvider=l.Store=l.MqttClient=l.connectAsync=l.connect=l.Client=void 0;var i=n(di());l.MqttClient=i.default;var o=n(ms());l.DefaultMessageIdProvider=o.default;var a=n(Nu());l.UniqueMessageIdProvider=a.default;var c=n(ls());l.Store=c.default;var u=r(Sh());l.connect=u.default,Object.defineProperty(l,"connectAsync",{enumerable:!0,get:function(){return u.connectAsync}});var h=n(ks());l.KeepaliveManager=h.default,l.Client=i.default,s(di(),l),s(Ut(),l),s(as(),l);var p=dr();Object.defineProperty(l,"ReasonCodes",{enumerable:!0,get:function(){return p.ReasonCodes}})}),Eh=pe(l=>{le(),ue(),ce();var e=l&&l.__createBinding||(Object.create?function(i,o,a,c){c===void 0&&(c=a);var u=Object.getOwnPropertyDescriptor(o,a);(!u||("get"in u?!o.__esModule:u.writable||u.configurable))&&(u={enumerable:!0,get:function(){return o[a]}}),Object.defineProperty(i,c,u)}:function(i,o,a,c){c===void 0&&(c=a),i[c]=o[a]}),t=l&&l.__setModuleDefault||(Object.create?function(i,o){Object.defineProperty(i,"default",{enumerable:!0,value:o})}:function(i,o){i.default=o}),r=l&&l.__importStar||(function(){var i=function(o){return i=Object.getOwnPropertyNames||function(a){var c=[];for(var u in a)Object.prototype.hasOwnProperty.call(a,u)&&(c[c.length]=u);return c},i(o)};return function(o){if(o&&o.__esModule)return o;var a={};if(o!=null)for(var c=i(o),u=0;u<c.length;u++)c[u]!=="default"&&e(a,o,c[u]);return t(a,o),a}})(),s=l&&l.__exportStar||function(i,o){for(var a in i)a!=="default"&&!Object.prototype.hasOwnProperty.call(o,a)&&e(o,i,a)};Object.defineProperty(l,"__esModule",{value:!0});var n=r(ll());l.default=n,s(ll(),l)});const Ah=Eh();const Ih={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}/#"},Th=300,Ch={templateId:"7",type:"link",isDeepLink:!0},Oh={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;connectedAt=0;disposed=!1;reconnectTimer=null;lifecycleHandlersAttached=!1;onOnlineHandler=null;onVisibilityHandler=null;onPageShowHandler=null;inboundRegex;inboundUpdateRegex;constructor(e){this.config=e,this.currentToken=e.jwtToken,this.appId=e.appId??"tilechat",this.clientId=e.clientId??this.freshClientId(),this.topics={...Ih,...e.topicTemplates??{}},this.maxReconnectAttempts=e.maxReconnectAttempts??1/0,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};this.clientId=this.config.clientId??this.freshClientId();const r=this.config.connectTimeoutMs??1e4,s={clientId:this.clientId,username:this.config.mqttUsername??"JWT",password:this.currentToken,clean:!1,resubscribe:!0,reconnectPeriod:0,connectTimeout:r,keepalive:this.config.keepAliveSec??30,protocolVersion:this.config.protocolVersion??4,protocolId:this.config.protocolId??"MQTT"};return this.config.enablePresence!==!1&&(s.will={topic:e,payload:JSON.stringify(t),qos:0,retain:!1}),this.attachLifecycleHandlers(),new Promise((n,i)=>{let o=!1;const a=h=>{o||(o=!0,clearTimeout(u),h())},c=(h,p)=>{o||(this.debugLog("CONNECT_FAIL",{reason:h,message:p?.message}),a(()=>i(p??new Error(`tiledesk-transport: ${h}`))))},u=setTimeout(()=>c("connect-timeout"),r+500);this.client=Ah.connect(this.config.mqttEndpoint,s),this.client.on("connect",()=>{if(this.connectedAt=Date.now(),o||a(()=>n()),this.debugLog("CONNECT",{endpoint:this.config.mqttEndpoint,clientId:this.clientId}),this.notifyStateChange(!0),this.config.enablePresence!==!1){const h=this.config.presencePayloadConnected??{connected:!0};this.client.publish(e,JSON.stringify(h),{qos:0,retain:!1}),this.debugLog("PUBLISH",{topic:e,payload:h})}}),this.client.on("message",(h,p)=>{this.dispatchInbound(h,p)}),this.client.on("close",()=>{if(this.debugLog("CLOSE",{}),this.notifyStateChange(!1),!o){c("socket-closed-pre-connack");return}this.disposed||this.scheduleReconnect()}),this.client.on("error",h=>{this.debugLog("ERROR",{message:h.message}),o||c("mqtt-error",h)}),this.client.on("disconnect",h=>{this.debugLog("DISCONNECT",{reasonCode:h?.reasonCode,properties:h?.properties})}),this.client.on("offline",()=>{this.debugLog("OFFLINE",{}),o||c("mqtt-offline")}),this.client.on("packetsend",h=>{(h.cmd==="subscribe"||h.cmd==="unsubscribe"||h.cmd==="pingreq")&&this.debugLog(h.cmd.toUpperCase(),{topic:h.topic,packetId:h.messageId})})})}freshClientId(){const e=Math.random().toString(36).slice(2,8);return`aikaara_${this.config.userId}_${Date.now()}_${e}`}debugLog(e,t){if(!this.config.debug)return;const r={};for(const[s,n]of Object.entries(t))typeof n=="string"&&n.length>200?r[s]=`${n.slice(0,200)}…(${n.length})`:r[s]=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 s=this.buildOutgoingEnvelope(e,{text:t,type:"text",...r});this.publishEnvelope(e,s)}publishFileMessage(e,t){if(!this.client)return;const r={...Ch,...this.config.fileTemplate??{},...Ph(t)},s={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(s),type:"html",attributes:n,metadata:s.metadata});this.publishEnvelope(e,i)}publishRaw(e,t){this.client&&this.publishEnvelope(e,t)}publishReadReceipt(e,t,r=Th){if(!this.client)return;const s=this.renderTemplate(this.topics.inboundUpdate,{conversationId:e,messageId:t});this.client.publish(s,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.detachLifecycleHandlers(),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||this.reconnectTimer)return;if(typeof navigator<"u"&&navigator.onLine===!1){this.debugLog("RECONNECT_SKIP_OFFLINE",{attempt:this.reconnectAttempt});return}this.connectedAt>0&&Date.now()-this.connectedAt>=5e3&&(this.reconnectAttempt=0),this.connectedAt=0;const e=Math.min(1e3*Math.pow(2,this.reconnectAttempt),this.reconnectMaxDelayMs),t=e*.2*(Math.random()*2-1),r=Math.max(0,Math.round(e+t));this.reconnectAttempt++,this.reconnectTimer=setTimeout(async()=>{if(this.reconnectTimer=null,!this.disposed){if(this.config.tokenProvider)try{this.currentToken=await this.config.tokenProvider()}catch{}try{await this.connect();const s=[...this.subscribedTopics];this.subscribedTopics.clear(),s.forEach(n=>{this.client&&(this.client.subscribe(n,{qos:this.config.subscribeQos??2}),this.subscribedTopics.add(n))})}catch{}}},r)}reconnectNow(e){this.disposed||this.isConnected||typeof navigator<"u"&&navigator.onLine===!1||(this.debugLog("RECONNECT_NOW",{reason:e}),this.reconnectTimer&&(clearTimeout(this.reconnectTimer),this.reconnectTimer=null),this.reconnectAttempt=0,this.scheduleReconnect())}attachLifecycleHandlers(){this.lifecycleHandlersAttached||typeof window>"u"||typeof document>"u"||(this.onOnlineHandler=()=>this.reconnectNow("online"),this.onVisibilityHandler=()=>{document.visibilityState==="visible"&&this.reconnectNow("visible")},this.onPageShowHandler=e=>{e.persisted&&this.reconnectNow("pageshow-bfcache")},window.addEventListener("online",this.onOnlineHandler),document.addEventListener("visibilitychange",this.onVisibilityHandler),window.addEventListener("pageshow",this.onPageShowHandler),this.lifecycleHandlersAttached=!0)}detachLifecycleHandlers(){this.lifecycleHandlersAttached&&(typeof window>"u"||typeof document>"u"||(this.onOnlineHandler&&window.removeEventListener("online",this.onOnlineHandler),this.onVisibilityHandler&&document.removeEventListener("visibilitychange",this.onVisibilityHandler),this.onPageShowHandler&&window.removeEventListener("pageshow",this.onPageShowHandler),this.onOnlineHandler=null,this.onVisibilityHandler=null,this.onPageShowHandler=null,this.lifecycleHandlersAttached=!1))}notifyStateChange(e){this.stateHandlers.forEach(t=>t(e))}dispatchInbound(e,t){const r=t.toString();let s=null;try{s=JSON.parse(r)}catch{this.debugLog("RECV (non-json)",{topic:e,raw:r});return}if(!s)return;this.debugLog("RECV",{topic:e,sender:s.sender,type:s.type,contentType:s.metadata?.contentType,templateId:s.metadata?.templateId,messageId:s.message_id,text:typeof s.text=="string"?s.text:void 0});const n=e.match(this.inboundUpdateRegex);if(n){const c=n.groups?.conversationId??"",u=n.groups?.messageId??"",h=typeof s.status=="number"?s.status:Number(s.status??0),p={conversationId:c,messageId:u,status:h,raw:s};this.statusUpdateHandlers.forEach(b=>b(p)),this.messageHandlers.forEach(b=>b(s,{topic:e,conversationId:c,messageId:u,kind:"update"}));return}const i=e.match(this.inboundRegex),o=i?.groups?.conversationId,a={topic:e,conversationId:o,messageId:typeof s.message_id=="string"?s.message_id:void 0,kind:i?"clientadded":"unknown"};this.messageHandlers.forEach(c=>c(s,a))}buildOutgoingEnvelope(e,t){const r={...Oh,...this.config.messageDefaults??{}},s=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:s,senderFullname:s,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,(s,n)=>r[n]??"")}buildTopicRegex(e,t){const r=e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&").replace(/\\\{(\w+)\\\}/g,(s,n)=>{const i={appId:this.appId,userId:this.config.userId,projectId:this.config.projectId,clientId:this.clientId};if(t.includes(n))return`(?<${n}>[^/]+)`;const o=i[n];return o?o.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"):"[^/]+"});return new RegExp(`^${r}$`)}}function Ph(l){const e={};for(const[t,r]of Object.entries(l))r!==void 0&&(e[t]=r);return e}function ul(l,e){return(l.sender??"").toString()===e}function hl(l,e){const t=(l.sender??"").toString(),r=e.systemSenders??["metadata","system"],s=e.botSenderPrefix??"bot_";return t?t===e.userId?"user":t.startsWith(s)?"assistant":r.includes(t)?"system":"agent":"system"}function lo(l){const e={raw:l},t=l.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 l.text=="string"&&l.text.trim().startsWith("{"))try{const s=JSON.parse(l.text);typeof s.message=="string"&&(e.innerMessage=s.message);const n=s.metadata;n&&typeof n=="object"&&(!e.contentType&&typeof n.contentType=="string"&&(e.contentType=n.contentType),!e.templateId&&typeof n.templateId=="string"&&(e.templateId=n.templateId),e.payload===void 0&&n.payload!==void 0&&(e.payload=n.payload))}catch{}const r=l.attributes;if(r&&typeof r=="object"){const s=r.attachment;!e.contentType&&typeof r.contentType=="string"&&(e.contentType=r.contentType),!e.contentType&&s&&typeof s.contentType=="string"&&(e.contentType=s.contentType),!e.templateId&&typeof r.templateId=="string"&&(e.templateId=r.templateId),!e.templateId&&s&&typeof s.templateId=="string"&&(e.templateId=s.templateId),e.payload===void 0&&r.payload!==void 0&&(e.payload=r.payload),e.payload===void 0&&s&&s.payload!==void 0&&(e.payload=s.payload),e.payload===void 0&&s&&s.template!==void 0&&(e.payload=s.template)}return e}function dl(l){const e=lo(l);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 s=r[0],n=s.action,i=n&&typeof n.url=="string"?n.url:void 0,o=typeof s.description=="string"?s.description:void 0,a=l.attributes,c=a&&typeof a.cloudFileId=="string"?a.cloudFileId:void 0;return!i&&!o?null:{fileName:o,fileUrl:i,cloudFileId:c,templateId:e.templateId}}function fl(l,e,t){const r=hl(l,t),s=lo(l),n=dl(l);let i="";s.innerMessage?i=s.innerMessage:typeof l.text=="string"&&(l.text.trim().startsWith("{")?s.contentType!=="300"&&(i=l.text):i=l.text);const o=typeof l.message_id=="string"?l.message_id:`td_${Date.now()}_${Math.random().toString(36).slice(2,8)}`,a=typeof l.timestamp=="number"?new Date(l.timestamp).toISOString():new Date().toISOString(),c=r==="assistant"?"assistant":r==="agent"?"agent":r==="system"?"system":"user",u=typeof l.status=="number"?Mh(l.status):"delivered",h={id:o,externalId:o,conversationId:e,role:c,content:i,createdAt:a,status:u,metadata:{sender:l.sender,sender_fullname:l.sender_fullname??l.senderFullname,app_id:l.app_id,attributes:l.attributes}};return s.contentType&&(h.template={contentType:s.contentType,templateId:s.templateId,payload:s.payload}),n?.fileUrl&&(h.attachments=[{fileName:n.fileName??"file",fileUrl:n.fileUrl,cloudFileId:n.cloudFileId}]),{message:h,template:s}}function Mh(l){return l<0?"error":l>=250?"read":l>=150?"delivered":"sent"}class pl extends ir{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 Ao(e.baseUrl,e.userToken,e.apiKey,e.authToken),this.messageStore=new Io,this.conversationManager=new Mo(e.conversationId),this.usesAikaara()&&(this.connection=new Eo(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 s=r?"connected":"disconnected";this.emit("connection:state",s),this.config.onConnectionStateChange?.(s)})),this.tiledeskUnsubs.push(this.tiledesk.onMessage((r,s)=>this.handleTiledeskMessage(r,s))),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),s=this.config.tiledesk?.autoInitiateOnEmpty??!0,n=this.config.tiledesk?.autoInitiateOnUnknown??!1;s&&(r==="empty"||r==="unknown"&&n)&&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(o){return this.config.onError?.(o instanceof Error?o:new Error(String(o))),"unknown"}if(!r.length)return"empty";const s=r.map(o=>fl(o,e,{userId:t}).message).sort((o,a)=>new Date(o.createdAt).getTime()-new Date(a.createdAt).getTime()),n=this.messageStore.messages,i=[...s,...n.filter(o=>!s.some(a=>a.externalId&&a.externalId===o.externalId))];if(this.messageStore.setMessages(i),this.config.onMessage)for(const o of s)try{this.config.onMessage(o)}catch(a){console.warn("[aikaara-chat-sdk] onMessage threw on history replay",a)}return"has-history"}async sendMessage(e,t={}){const r=this.conversationManager.conversationId;if(!r)throw new Error("No active conversation");const s=this.messageStore.addOptimistic("user",e,r);this.emit("message:sent",s),this.config.onMessage?.(s);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 s=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:s.fileName,fileUrl:s.url,cloudFileId:s.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 s=this.conversationManager.conversationId;if(!s)throw new Error("No active conversation");this.connection&&this.connection.sendUserEvent(s,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 s=this.config.tiledeskIdentity?.userId??"",{message:n,template:i}=fl(e,r,{userId:s,systemSenders:this.config.tiledesk?.messageDefaults?.attributes?.systemSenders});if(this.mode==="dual"&&n.role==="assistant")return;if(ul(e,s)){const c=this.messageStore.reconcileOptimistic(n);if(c){this.emit("message:updated",c);return}}const{message:o,deduped:a}=this.messageStore.upsertRemoteMessage(n);if(a)this.emit("message:updated",o);else{this.emit("message:received",o),this.config.onMessage?.(o);try{typeof window<"u"&&window.dispatchEvent(new CustomEvent("aikaara:message",{detail:{role:o.role,hasAttachments:Array.isArray(o.attachments)&&o.attachments.length>0,templateId:o.template?.templateId,messageId:o.id,conversationId:o.conversationId}}))}catch{}}if(i.contentType){const c={messageId:o.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?.(c)}}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||"",s=e.content||"";s?this.messageStore.updateStreaming(s):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,s=this.messageStore.finalizeStreaming(r?{tokensInput:r.tokens_input||0,tokensOutput:r.tokens_output||0}:void 0);this.emit("typing:stop",void 0),s&&(this.emit("stream:end",{messageId:s.id,usage:r?{tokensInput:r.tokens_input||0,tokensOutput:r.tokens_output||0}:void 0}),this.emit("message:received",s),this.config.onMessage?.(s));break}case"message_queued":{const r=this.messageStore.messages.findLast(s=>s.status==="sending");r&&this.messageStore.confirmOptimistic(r.id);break}case"tool_execution_start":{this.emit("tool:start",{toolName:e.tool_name||"",args:e.args||{}}),this.emit("status",e.type);break}case"tool_execution_end":{this.emit("tool:end",{toolName:e.tool_name||"",result:e.result,isError:!!e.is_error}),this.emit("status",e.type),this.parseActionResult(e.result);break}case"tool_execution_update":case"agent_start":case"agent_end":case"turn_start":case"turn_end":case"auto_retry_start":case"auto_retry_end":case"cancelled":this.emit("status",e.type);break}}}class Rh extends ir{registration=null;pendingEdits=[];constructor(e){super(),this.setupListeners(e)}registerForm(e){this.registration=e;const t=this.pendingEdits.filter(r=>r.entity_type===e.entityType&&String(r.entity_id)===String(e.entityId));if(t.length>0){for(const r of t)e.onFieldUpdate(r.fields),this.emit("edit:applied",{entityType:r.entity_type,entityId:r.entity_id,fields:r.fields});this.pendingEdits=this.pendingEdits.filter(r=>!(r.entity_type===e.entityType&&String(r.entity_id)===String(e.entityId)))}}unregisterForm(e,t){this.registration?.entityType===e&&String(this.registration?.entityId)===String(t)&&(this.registration=null)}get currentForm(){return this.registration}pushFieldUpdates(e,t,r){this.registration&&this.registration.entityType===e&&String(this.registration.entityId)===String(t)?(this.registration.onFieldUpdate(r),this.emit("edit:applied",{entityType:e,entityId:t,fields:r})):(this.pendingEdits.push({action:"edit_entity",entity_type:e,entity_id:t,fields:r}),this.emit("edit:pending",{entityType:e,entityId:t,fields:r}))}async requestSave(){if(!this.registration)return{success:!1,error:"No form registered"};try{return await this.registration.onSave(),this.emit("save:success",{entityType:this.registration.entityType,entityId:this.registration.entityId}),{success:!0}}catch(e){const t=e instanceof Error?e.message:"Save failed";return this.emit("save:error",{entityType:this.registration.entityType,entityId:this.registration.entityId,error:t}),{success:!1,error:t}}}async requestTest(e){if(!this.registration?.onTest)return{success:!1,error:"Current form does not support testing"};try{return await this.registration.onTest(e),{success:!0}}catch(t){return{success:!1,error:t instanceof Error?t.message:"Test failed"}}}setupListeners(e){e.on("action:edit_entity",t=>{this.pushFieldUpdates(t.entity_type,t.entity_id,t.fields)}),e.on("action:save_entity",t=>{this.requestSave()}),e.on("action:test_tool",t=>{this.emit("test:triggered",{toolId:t.tool_id,parameters:t.parameters}),this.requestTest(t.parameters)})}}const ml={txt:"text/plain",pdf:"application/pdf",jpg:"image/jpeg",jpeg:"image/jpeg",png:"image/png",csv:"text/csv",doc:"application/msword",json:"application/json"};function Lh(l){const e=l.lastIndexOf(".");return e<0||e===l.length-1?"":l.slice(e+1).toLowerCase()}function jh(l,e,t){const r=Lh(l.name||"");if(r&&e&&e[r])return e[r];const s=l.type;return s&&s.trim().length>0?s:r&&ml[r]?ml[r]:t}function co(l,e){return l.replace(/\{(\w+)\}/g,(t,r)=>e[r]??"")}function Nh(l,e){const t=e.split(".");let r=l;for(const s of t)if(r&&typeof r=="object"&&s in r)r=r[s];else return"";return typeof r=="string"?r:""}function gl(l){const e=l.signedUrlPath??"data.s3SignedUrl";return{async upload(t,r){const s=t.name||`upload-${Date.now()}`,n=jh(t,l.contentTypeMap,l.contentTypeFallback??"application/octet-stream"),i={fileName:s,userId:r.userId,requestId:r.conversationId,conversationId:r.conversationId,contentType:n},o=l.authHeader?await l.authHeader():void 0,a={accept:"application/json",...l.extraHeaders??{},...o?{authorization:o}:{}};let c=l.signEndpoint.includes("{")?l.signEndpoint:`${l.signEndpoint}?fileName={fileName}`;if(!c.includes("{contentType}")){const k=c.includes("?")?"&":"?";c=`${c}${k}contentType={contentType}`}const u=co(c,i),h=await fetch(u,{method:l.signMethod??"GET",headers:a});if(!h.ok)throw new Error(`Sign request failed: ${h.status}`);const p=await h.json().catch(()=>({})),b=Nh(p,e);if(!b)throw new Error(`Sign response missing path "${e}"`);const f=l.s3HostRewrite?b.replace(/^https:\/\/[^/]+/i,l.s3HostRewrite):b,g=await fetch(f,{method:"PUT",headers:{"content-type":n},body:t});if(!g.ok){const k=await g.text().catch(()=>"");throw new Error(`S3 PUT failed: ${g.status} ${k.slice(0,200)}`)}if(l.registerEndpoint){const k=JSON.parse(co(JSON.stringify(l.registerBody??{}),i)),m=await fetch(l.registerEndpoint,{method:"POST",headers:{...a,"content-type":"application/json"},body:JSON.stringify(k)});if(!m.ok){const w=await m.text().catch(()=>"");throw new Error(`Register failed: ${m.status} ${w.slice(0,200)}`)}}return{url:l.viewerTemplate?co(l.viewerTemplate,i):b.split("?")[0],fileName:s,contentType:n,byteSize:t.size,meta:{requestId:r.conversationId}}}}}function uo(l){return{async upload(e,t){const r=new FormData,s=l.fieldName??"file";r.append(s,e,e.name);const n=typeof l.extraFields=="function"?l.extraFields(t):l.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 l.headers=="function"?await l.headers():l.headers??{},o=await fetch(l.endpoint,{method:l.method??"POST",body:r,headers:i,credentials:l.credentials});if(!o.ok)throw new Error(`Upload failed: ${o.status} ${o.statusText}`);const a=await o.json().catch(()=>({}));if(l.parseResponse)return l.parseResponse(a,t);const c=a,u=c.url??c.fileUrl??c.publicUrl,h=c.fileName??c.name??e.name;if(!u)throw new Error('Upload response missing "url" / "fileUrl" / "publicUrl"');return{url:u,fileName:h,cloudFileId:typeof c.cloudFileId=="string"?c.cloudFileId:void 0,relativePath:typeof c.path=="string"?c.path:void 0,contentType:typeof c.contentType=="string"?c.contentType:void 0,byteSize:typeof c.byteSize=="number"?c.byteSize:void 0,meta:c}}}}const Uh="/tilechat/{userId}/conversations/{conversationId}/messages?pageSize={pageSize}";function bl(l){const e=l.apiBase.replace(/\/$/,""),t=l.pageSize??200,r=l.pathTemplate??Uh;return{async fetchMessages(s,n){const i=r.replace("{userId}",encodeURIComponent(n.userId)).replace("{conversationId}",encodeURIComponent(s)).replace("{appId}",encodeURIComponent(n.appId??"tilechat")).replace("{projectId}",encodeURIComponent(n.projectId??"")).replace("{pageSize}",String(t)),o=i.startsWith("http")?i:`${e}${i.startsWith("/")?i:`/${i}`}`,a={accept:"application/json","content-type":"application/json",...l.extraHeaders??{}};if(l.getToken){const p=await l.getToken();p&&(a.authorization=p)}const c=await fetch(o,{method:"GET",headers:a}),u=await c.json().catch(()=>null);if(l.parseResponse&&u)return l.parseResponse(u);const h=u;if(h&&Array.isArray(h.result))return h.result;if(!c.ok)throw new Error(`History fetch failed: ${c.status} ${c.statusText}`);return[]}}}const Bh="^[A-Z]{5}[0-9]{4}[A-Z]$",Dh="^[A-Z]{4}[0-9]{5}[A-Z]$",Fh="^[A-Z]{4}0[A-Z0-9]{6}$",yl="^[0-9]{6}$",$h=[{id:"salary-hra",title:"Salary / HRA / Allowances",icon:"💰",dataPath:"salaryDetails[]",repeatable:{maxCount:4,labelTemplate:"Employer {index}"},entryIcon:"🏢",fields:[{id:"employerDetails",type:"group",title:"Employer Details",fields:[{id:"employerName",type:"text",label:"Employer Name",required:!0},{id:"employerTan",type:"text",label:"TAN (Tax Deduction Account Number)",required:!0,pattern:Dh,maxLength:10}]},{id:"salaryComponents",type:"group",title:"Salary Components",fields:[{id:"basicSalary",type:"number",label:"Basic Salary",currency:"₹",required:!0,min:0},{id:"hraReceived",type:"number",label:"HRA Received",currency:"₹",min:0},{id:"leaveTravelAllowance",type:"number",label:"Leave Travel Allowance",currency:"₹",min:0},{id:"anyOtherAllowance",type:"number",label:"Other Allowances",currency:"₹",min:0},{id:"leaveEncashment",type:"number",label:"Leave Encashment",currency:"₹",min:0},{id:"grossSalary",type:"number",label:"Gross Salary (Total)",currency:"₹",min:0}]}],submitLabel:"Save"},{id:"business-profession",title:"Business / Profession",icon:"💼",fields:[{id:"businessGroup",type:"group",title:"Business Details",fields:[{id:"businessName",type:"text",label:"Business / Profession Name"},{id:"businessNatureOfWork",type:"text",label:"Nature of Work"},{id:"grossReceipts",type:"number",label:"Gross Receipts / Turnover",currency:"₹",min:0},{id:"netProfit",type:"number",label:"Net Profit",currency:"₹"}]}],submitLabel:"Save"},{id:"capital-gains",title:"Capital Gains",icon:"📈",fields:[{id:"equityGains",type:"group",title:"Equity & Mutual Funds",fields:[{id:"shortTermEquityGain",type:"number",label:"Short-Term Capital Gain",currency:"₹"},{id:"longTermEquityGain",type:"number",label:"Long-Term Capital Gain",currency:"₹"}]},{id:"propertyGains",type:"group",title:"Land & Building",fields:[{id:"landBuildingTermType",type:"radio",label:"Holding Period",options:[{value:"short",label:"Short-Term"},{value:"long",label:"Long-Term"}]},{id:"landBuildingPurchaseValue",type:"number",label:"Purchase Value",currency:"₹"},{id:"landBuildingSellValue",type:"number",label:"Sale Value",currency:"₹"}]}],submitLabel:"Save"},{id:"other-sources",title:"Income from Other Sources",icon:"💵",fields:[{id:"interestIncome",type:"group",title:"Interest Income",fields:[{id:"savingBankInterest",type:"number",label:"Savings Bank Interest",currency:"₹",min:0},{id:"fdInterest",type:"number",label:"Fixed Deposit Interest",currency:"₹",min:0}]},{id:"otherIncomeGroup",type:"group",title:"Other Income",fields:[{id:"dividend",type:"number",label:"Dividend Income",currency:"₹",min:0},{id:"anyOtherIncome",type:"number",label:"Any Other Income",currency:"₹",min:0}]}],submitLabel:"Save"},{id:"crypto-income",title:"Crypto Income",icon:"🪙",fields:[{id:"cryptoGroup",type:"group",title:"Virtual Digital Assets",hint:"Gains from crypto / VDAs are taxed at a flat 30%",fields:[{id:"cryptoSellPrice",type:"number",label:"Total Sale Value",currency:"₹",min:0},{id:"cryptoPurchasePrice",type:"number",label:"Total Cost of Acquisition",currency:"₹",min:0}]}],submitLabel:"Save"},{id:"agricultural-income",title:"Agricultural Income",icon:"🌾",fields:[{id:"agricultureIncome",type:"number",label:"Total Agricultural Income",currency:"₹",min:0},{id:"agricultureIncomeGt5Lakh",type:"yes-no",label:"Is agricultural income above ₹5,00,000?"}],submitLabel:"Save"},{id:"exempt-income",title:"Other Exempt Income",icon:"🧾",fields:[{id:"exemptIncome",type:"number",label:"Total Exempt Income",currency:"₹",min:0},{id:"exemptIncomeNature",type:"text",label:"Nature of Exempt Income",placeholder:"e.g. PPF interest, gratuity"}],submitLabel:"Save"},{id:"house-property",title:"House Property",icon:"🏠",dataPath:"hpDetails[]",repeatable:{maxCount:2,labelTemplate:"Property {index}"},entryIcon:"🏠",fields:[{id:"typeOfHouseProperty",type:"radio",label:"Property Type",required:!0,options:[{value:"SOP",label:"Self-Occupied"},{value:"LOP",label:"Let-Out"}]},{id:"homeLoanDetails",type:"group",title:"Home Loan Details",hint:"Interest deduction capped at ₹2,00,000",fields:[{id:"loanTakenFrom",type:"text",label:"Loan Taken From",required:!0},{id:"lenderName",type:"text",label:"Lender Name",required:!0},{id:"loanAccountNumber",type:"text",label:"Loan Account Number",required:!0},{id:"sanctionDate",type:"date",label:"Sanction Date",format:"DD/MM/YYYY",required:!0},{id:"totalLoanAmount",type:"number",label:"Total Loan Amount",currency:"₹",min:0},{id:"homeLoanInterest",type:"number",label:"Home Loan Interest",currency:"₹",min:0,max:2e5},{id:"homeLoanPrinciple",type:"number",label:"Home Loan Principal",currency:"₹",min:0}]},{id:"addressDetails",type:"group",title:"Property Address",fields:[{id:"housePropertyAddress",type:"text",label:"Address"},{id:"housePropertyPincode",type:"text",label:"Pincode",maxLength:6,pattern:yl}]},{id:"rentalDetails",type:"group",title:"Rental Income Details",showWhen:{field:"typeOfHouseProperty",equals:"LOP"},fields:[{id:"rentalIncome",type:"number",label:"Annual Rental Income",currency:"₹",required:!0,min:0},{id:"nameOfTenant",type:"text",label:"Tenant Name",required:!0},{id:"propertyTax",type:"number",label:"Municipal / Property Tax Paid",currency:"₹",min:0}]},{id:"hasCoOwnedProperty",type:"yes-no",label:"Is this property co-owned?"},{id:"coOwnerGroup",type:"group",title:"Co-Owner Details",showWhen:{field:"hasCoOwnedProperty",equals:!0},fields:[{id:"coOwnerName",type:"text",label:"Co-Owner Name",required:!0},{id:"coOwnerPan",type:"text",label:"Co-Owner PAN",required:!0,pattern:Bh,maxLength:10},{id:"coOwnerShare",type:"text",label:"Co-Owner Share (%)",placeholder:"e.g. 50",maxLength:5}]}],submitLabel:"Save"},{id:"deductions",title:"Deductions",icon:"📋",fields:[{id:"section80c",type:"group",title:"Section 80C",hint:"Maximum deduction allowed: ₹1,50,000",fields:[{id:"us80cAmount",type:"number",label:"80C Investment Amount",currency:"₹",min:0,max:15e4}]},{id:"section80d",type:"group",title:"Section 80D — Health Insurance",fields:[{id:"us80dForSelfAndFamilyAmount",type:"number",label:"Premium for Self / Spouse / Children",currency:"₹",min:0,max:25e3},{id:"us80dForParentsAmount",type:"number",label:"Premium for Parents",currency:"₹",min:0,max:5e4},{id:"hasParentOverSixty",type:"yes-no",label:"Are your parents senior citizens (60+)?"},{id:"preventiveHealthCheckUp",type:"number",label:"Preventive Health Check-up",currency:"₹",min:0},{id:"medicalExpenditure",type:"number",label:"Medical Expenditure (senior citizen)",currency:"₹",min:0}]}],submitLabel:"Save"},{id:"tax-paid-tds",title:"Tax Paid / TDS",icon:"🧮",fields:[{id:"tdsGroup",type:"group",title:"Tax Deducted at Source",fields:[{id:"tdsOnSalary",type:"number",label:"TDS on Salary",currency:"₹",min:0},{id:"tdsOtherThanSalary",type:"number",label:"TDS (other than salary)",currency:"₹",min:0}]},{id:"advanceTaxGroup",type:"group",title:"Advance / Self-Assessment Tax",fields:[{id:"selfAssessmentOrAdvanceTax",type:"number",label:"Advance / Self-Assessment Tax Paid",currency:"₹",min:0}]}],submitLabel:"Save"},{id:"bank-details",title:"Personal / Bank Details",icon:"🏦",fields:[{id:"bankGroup",type:"group",title:"Bank Account (for refund)",fields:[{id:"bankAccountNumber",type:"text",label:"Bank Account Number",required:!0},{id:"bankIfscCode",type:"text",label:"IFSC Code",required:!0,pattern:Fh,maxLength:11}]},{id:"immovableGroup",type:"group",title:"Immovable Assets",hint:"Required if total income exceeds ₹50,00,000",fields:[{id:"immovableAssetDescription",type:"text",label:"Description"},{id:"immovableAssetFlatNo",type:"text",label:"Flat / House No."},{id:"immovableAssetArea",type:"text",label:"Area / Locality"},{id:"immovableAssetPincode",type:"text",label:"Pincode",maxLength:6,pattern:yl},{id:"immovableAssetCost",type:"number",label:"Cost of Asset",currency:"₹",min:0}]}],submitLabel:"Save"},{id:"have-a-question",title:"I only have a question",icon:"❓",fields:[{id:"question",type:"textarea",label:"What would you like to ask?",placeholder:"Type your question for the TaxBuddy expert…",required:!0,rows:5,maxLength:1e3}],submitLabel:"Send Question"}];function qh(l,e){const t=l||{},r={userId:zh(e.userId),assessmentYear:e.assessmentYear,isRevised:e.isRevised||"N"};r.us80cAmount=Pe(t.us80cAmount),r.us80dForSelfAndFamilyAmount=Pe(t.us80dForSelfAndFamilyAmount),r.us80dForParentsAmount=Pe(t.us80dForParentsAmount),r.hasParentOverSixty=ho(t.hasParentOverSixty),r.preventiveHealthCheckUp=Pe(t.preventiveHealthCheckUp),r.medicalExpenditure=Pe(t.medicalExpenditure),r.savingBankInterest=Pe(t.savingBankInterest),r.fdInterest=Pe(t.fdInterest),r.dividend=Pe(t.dividend),r.anyOtherIncome=Pe(t.anyOtherIncome),r.cryptoSellValue=Pe(t.cryptoSellPrice),r.cryptoPurchaseAmount=Pe(t.cryptoPurchasePrice),r.vdaPurchaseCost=Pe(t.cryptoPurchasePrice),r.businessName=Re(t.businessName),r.businessAnnualTurnOver=Pe(t.grossReceipts),r.businessNetProfit=Pe(t.netProfit),r.agricultureDetails={income:Pe(t.agricultureIncome)},r.exemptIncomeAmount=Pe(t.exemptIncome),r.exemptIncomeNature=Re(t.exemptIncomeNature),Pe(t.exemptIncome)!==void 0&&(r.exemptIncomes=[{name:Re(t.exemptIncomeNature)??"Exempt income",value:String(Pe(t.exemptIncome))}]),r.bankAccountNumber=Re(t.bankAccountNumber),r.bankIfscCode=Re(t.bankIfscCode),(Re(t.bankAccountNumber)||Re(t.bankIfscCode))&&(r.bankDetails=[{bankAccountNumber:Re(t.bankAccountNumber),bankIfscCode:Re(t.bankIfscCode)}]);const s={description:Re(t.immovableAssetDescription),flatNo:Re(t.immovableAssetFlatNo),area:Re(t.immovableAssetArea),pinCode:Re(t.immovableAssetPincode),amount:Pe(t.immovableAssetCost)};Object.values(s).some(o=>o!==void 0)&&(r.immovableAsset=[s]);const n=fo(t.hpDetails,Hh);n.length&&(r.hpDetails=n);const i=fo(t.salaryDetails,Wh);if(i.length){r.salaryIncome=i;const o=fo(t.salaryDetails,c=>({grossSalary:Pe(c.grossSalary),employerName:Re(c.employerName)}));o.length&&(r.salary=o);const a=vl(t.salaryDetails)[0]??{};r.hraAmount=Pe(a.hraReceived),r.leaveTravelAllowanceAmount=Pe(a.leaveTravelAllowance),r.leaveEncashmentAllowanceAmount=Pe(a.leaveEncashment),r.anyOtherAllowanceAmount=Pe(a.anyOtherAllowance),r.salaryIncomeFlag=!0}return $r(r)}function Hh(l){const e={loanType:"HOME_LOAN",loanTakenFrom:Re(l.loanTakenFrom),bankOrInstituteName:Re(l.lenderName),loanAccountNo:Re(l.loanAccountNumber),loanSanctionDate:Vh(l.sanctionDate),totalLoanAmount:Pe(l.totalLoanAmount),interest:Pe(l.homeLoanInterest)},t=Object.entries(e).some(([r,s])=>r!=="loanType"&&s!==void 0);return{typeOfHouseProperty:Re(l.typeOfHouseProperty),hasRentalIncome:l.typeOfHouseProperty==="LOP"?!0:ho(l.hasRentalIncome),homeLoanInterest:Pe(l.homeLoanInterest),homeLoanPrinciple:Pe(l.homeLoanPrinciple),housePropertyAddress:Re(l.housePropertyAddress),housePropertyPincode:Re(l.housePropertyPincode),rentalIncome:Pe(l.rentalIncome),nameOfTenant:Re(l.nameOfTenant),propertyTax:Pe(l.propertyTax),hasCoOwnedProperty:ho(l.hasCoOwnedProperty),coOwnerName:Re(l.coOwnerName),coOwnerPan:Re(l.coOwnerPan),coOwnerShare:Re(l.coOwnerShare),loanDetails:t?[e]:void 0}}function Wh(l){return{grossSalaryIncome:Pe(l.grossSalary),salary:Pe(l.basicSalary),employer:{employerName:Re(l.employerName),employerTan:Re(l.employerTan)},allowance:{hraAmount:Pe(l.hraReceived),leaveTravelAllowanceAmount:Pe(l.leaveTravelAllowance),leaveEncashmentAllowanceAmount:Pe(l.leaveEncashment),anyOtherAllowanceAmount:Pe(l.anyOtherAllowance)}}}function zh(l){if(l===void 0||l==="")return;const e=Number(l);return Number.isFinite(e)&&String(e)===String(l)?e:l}function Pe(l){if(l==null||l==="")return;const e=typeof l=="number"?l:Number(l);return Number.isFinite(e)?e:void 0}function Re(l){if(l==null)return;const e=String(l).trim();return e===""?void 0:e}function ho(l){return l===!0||l===!1?l:void 0}function Vh(l){const e=Re(l);if(e)return e.includes("T")?e:/^\d{4}-\d{2}-\d{2}$/.test(e)?`${e}T00:00:00Z`:e}function vl(l){return Array.isArray(l)?l.filter(e=>e&&typeof e=="object"):[]}function fo(l,e){return vl(l).map(t=>$r(e(t))).filter(t=>t!==void 0)}function $r(l){if(Array.isArray(l)){const e=l.map($r).filter(t=>t!==void 0);return e.length?e:void 0}if(l&&typeof l=="object"){const e={};for(const[t,r]of Object.entries(l)){const s=$r(r);s!==void 0&&(e[t]=s)}return Object.keys(e).length?e:void 0}return l}function wl(){if(typeof window>"u")return null;const l=window,e=l.__aikaara_runtime__;if(!e||typeof e.getChatJwt!="function")return console.warn("[smart-edit] API disabled: window.__aikaara_runtime__.getChatJwt is missing — the chat was not mounted via the SDK mountFromSlug path."),null;const t=e.getChatJwt,r=l.__aikaara_descriptor__??{},s=Qh(r.api?.baseUrl)??Jh(r.auth?.endpoint)??"",n=r.itr?.automationSubmitUrl||Gh(e.configBase,e.slug);return!n&&!s?(console.warn(`[smart-edit] API disabled: no submit URL could be derived (configBase=${e.configBase??"undefined"}, slug=${e.slug??"undefined"}).`),null):(console.info("[smart-edit] API config — submitUrl:",n||"(none)","· baseUrl:",s||"(none)"),{baseUrl:s,getToken:()=>t(),headers:Xh(r.auth?.headers),assessmentYear:r.itr?.assessmentYear||ed(),isRevised:"N",userId:Zh(e.identity),submitUrl:n})}function Gh(l,e){return!l||!e?void 0:`${l.replace(/\/+$/,"")}/api/v1/projects/by-slug/${encodeURIComponent(e)}/itr/automation-data`}async function Kh(l){const e=await l.getToken(),t=l.userId||_l(e,"sub");if(!t)throw new Error("[smart-edit] could not resolve userId for GET /itr/automation/eligible");const r=new URLSearchParams({userId:t,assessmentYear:l.assessmentYear,isRevised:l.isRevised}),s=await fetch(`${l.baseUrl}/itr/automation/eligible?${r}`,{method:"GET",headers:{accept:"application/json",authorization:`Bearer ${e}`,...l.headers}});if(!s.ok){const n=await s.text().catch(()=>"");throw new Error(`[smart-edit] GET /itr/automation/eligible → ${s.status} ${n.slice(0,200)}`)}return kl(await s.json().catch(()=>({})))}async function Yh(l,e){const t=await l.getToken(),r=l.userId||_l(t,"sub"),s=qh(e,{userId:r,assessmentYear:l.assessmentYear,isRevised:l.isRevised}),n=l.submitUrl||`${l.baseUrl}/itr/v1/lanretni/automation/data`,i={accept:"application/json","content-type":"application/json",authorization:`Bearer ${t}`,...l.headers};l.txbdyApiKey&&(i["txbdy-api-key"]=l.txbdyApiKey),console.info("[smart-edit] PUT",n,"— DTO keys:",Object.keys(s).join(", "));const o=await fetch(n,{method:"PUT",headers:i,body:JSON.stringify(s)});if(!o.ok){const a=await o.text().catch(()=>"");throw new Error(`[smart-edit] PUT ${n} → ${o.status} ${a.slice(0,200)}`)}return kl(await o.json().catch(()=>({})))}function Qh(l){if(!l)return null;let e=l.trim().replace(/\/+$/,"");return e=e.replace(/\/itr$/i,""),e||null}function Jh(l){if(!l)return null;try{return new URL(l).origin}catch{return null}}function Xh(l){const e={};if(!l)return e;const t=/^(authorization|content-type|accept)$/i;for(const[r,s]of Object.entries(l))!t.test(r)&&typeof s=="string"&&(e[r]=s);return e}function Zh(l){if(!l)return;const e=l.userId??l.id??l.ext_uid??l.extUid;return e==null||e===""?void 0:String(e)}function _l(l,e){try{const t=l.split(".")[1];if(!t)return"";const s=JSON.parse(atob(t.replace(/-/g,"+").replace(/_/g,"/")))[e];return s==null?"":String(s)}catch{return""}}function kl(l){if(l&&typeof l=="object"){const e=l;return e.data&&typeof e.data=="object"?e.data:e}return{}}function ed(){const l=new Date,e=l.getMonth()>=3?l.getFullYear():l.getFullYear()-1;return`${e}-${e+1}`}class td{client;panel;bubble;header;messageList;input;errorBanner;isOpen=!1;isEmbed=!1;smartEditModal=null;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.header.addEventListener("aikaara-chat-action",(e=>{this.handleChatAction(e.detail)})),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??{},s=t.attributes?.action??{},n={...t.attributes,action:{...r,...s}};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}async handleChatAction(e){if(e.id==="edit-itr"){this.openSmartEdit();return}console.info("[chat-action]",e.id,e.label)}async openSmartEdit(){const e=this.ensureSmartEditModal();e.open({schemas:$h,data:{}});const t=wl();if(!(!t||!t.baseUrl))try{const r=await Kh(t);e.setData(r)}catch(r){console.warn("[smart-edit] fetch failed",r),this.errorBanner.show("Could not load your ITR details — starting from a blank form.",4e3)}}ensureSmartEditModal(){if(this.smartEditModal)return this.smartEditModal;const e=document.createElement("aikaara-smart-edit-modal");return document.body.appendChild(e),e.addEventListener("smart-edit-recalculate",(t=>{const r=t.detail;this.handleSmartEditSave(r.record)})),this.smartEditModal=e,e}async handleSmartEditSave(e){console.info("[smart-edit] Save & Recalculate — persisting record");const t=wl();if(!t){console.warn("[smart-edit] save skipped — no API config (see the warning above for why)");return}try{await Yh(t,e)}catch(r){console.warn("[smart-edit] save failed",r),this.errorBanner.show("Failed to save your ITR details. Please try again.",4e3)}}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 xl 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||bc,primaryColor:this.getAttribute("primary-color")||this._config.primaryColor||xo,position:this.getAttribute("position")||this._config.position||gc,width:Number(this.getAttribute("width"))||this._config.width||dc,height:Number(this.getAttribute("height"))||this._config.height||fc,fontFamily:this._config.fontFamily||mc,borderRadius:this._config.borderRadius??pc,placeholder:this.getAttribute("placeholder")||this._config.placeholder||So,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||yc,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,s){if(typeof document>"u")return;const n=document.documentElement,i=(o,a)=>{a!==void 0&&a!==""&&n.style.setProperty(`--aikaara-${o}`,a)};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??s),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=s=>typeof s=="number"?`${s}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(([,s])=>s!==void 0&&s!=="").map(([s,n])=>`--aikaara-${s}: ${n};`).join(`
6
+ `+ie.prev}function ke(z,ie){var Ee=be(z),Ae=[];if(Ee){Ae.length=z.length;for(var Ie=0;Ie<z.length;Ie++)Ae[Ie]=oe(z,Ie)?ie(z[Ie],z):""}var Oe=typeof T=="function"?T(z):[],et;if(D){et={};for(var tt=0;tt<Oe.length;tt++)et["$"+Oe[tt]]=Oe[tt]}for(var He in z)oe(z,He)&&(Ee&&String(Number(He))===He&&He<z.length||D&&et["$"+He]instanceof Symbol||(E.call(/[^\w$]/,He)?Ae.push(ie(He,z)+": "+ie(z[He],z)):Ae.push(He+": "+ie(z[He],z))));if(typeof T=="function")for(var rt=0;rt<Oe.length;rt++)ae.call(z,Oe[rt])&&Ae.push("["+ie(Oe[rt])+"]: "+ie(z[Oe[rt]],z));return Ae}return Pr}function ph(){if(Zi)return Rr;Zi=!0;var l=Bt(),e=Zu(),t=fh(),r=Qt(),s=l("%WeakMap%",!0),n=l("%Map%",!0),i=e("WeakMap.prototype.get",!0),o=e("WeakMap.prototype.set",!0),a=e("WeakMap.prototype.has",!0),c=e("Map.prototype.get",!0),u=e("Map.prototype.set",!0),h=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 Rr=function(){var b,k,m,w={assert:function(x){if(!w.has(x))throw new r("Side channel does not contain "+t(x))},get:function(x){if(s&&x&&(typeof x=="object"||typeof x=="function")){if(b)return i(b,x)}else if(n){if(k)return c(k,x)}else if(m)return y(m,x)},has:function(x){if(s&&x&&(typeof x=="object"||typeof x=="function")){if(b)return a(b,x)}else if(n){if(k)return h(k,x)}else if(m)return g(m,x);return!1},set:function(x,v){s&&x&&(typeof x=="object"||typeof x=="function")?(b||(b=new s),o(b,x,v)):n?(k||(k=new n),u(k,x,v)):(m||(m={key:{},next:null}),f(m,x,v))}};return w},Rr}function Ji(){if(eo)return Lr;eo=!0;var l=String.prototype.replace,e=/%20/g,t={RFC1738:"RFC1738",RFC3986:"RFC3986"};return Lr={default:t.RFC3986,formatters:{RFC1738:function(r){return l.call(r,e,"+")},RFC3986:function(r){return String(r)}},RFC1738:t.RFC1738,RFC3986:t.RFC3986},Lr}function Ma(){if(to)return jr;to=!0;var l=Ji(),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})(),s=function(b){for(;b.length>1;){var k=b.pop(),m=k.obj[k.prop];if(t(m)){for(var w=[],x=0;x<m.length;++x)typeof m[x]<"u"&&w.push(m[x]);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 x=k;return t(k)&&!t(m)&&(x=n(k,w)),t(k)&&t(m)?(m.forEach(function(v,E){if(e.call(k,E)){var S=k[E];S&&typeof S=="object"&&v&&typeof v=="object"?k[E]=b(S,v,w):k.push(v)}else k[E]=v}),k):Object.keys(m).reduce(function(v,E){var S=m[E];return e.call(v,E)?v[E]=b(v[E],S,w):v[E]=S,v},x)},o=function(b,k){return Object.keys(k).reduce(function(m,w){return m[w]=k[w],m},b)},a=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}},c=1024,u=function(b,k,m,w,x){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 E="",S=0;S<v.length;S+=c){for(var I=v.length>=c?v.slice(S,S+c):v,O=[],P=0;P<I.length;++P){var N=I.charCodeAt(P);if(N===45||N===46||N===95||N===126||N>=48&&N<=57||N>=65&&N<=90||N>=97&&N<=122||x===l.RFC1738&&(N===40||N===41)){O[O.length]=I.charAt(P);continue}if(N<128){O[O.length]=r[N];continue}if(N<2048){O[O.length]=r[192|N>>6]+r[128|N&63];continue}if(N<55296||N>=57344){O[O.length]=r[224|N>>12]+r[128|N>>6&63]+r[128|N&63];continue}P+=1,N=65536+((N&1023)<<10|I.charCodeAt(P)&1023),O[O.length]=r[240|N>>18]+r[128|N>>12&63]+r[128|N>>6&63]+r[128|N&63]}E+=O.join("")}return E},h=function(b){for(var k=[{obj:{o:b},prop:"o"}],m=[],w=0;w<k.length;++w)for(var x=k[w],v=x.obj[x.prop],E=Object.keys(v),S=0;S<E.length;++S){var I=E[S],O=v[I];typeof O=="object"&&O!==null&&m.indexOf(O)===-1&&(k.push({obj:v,prop:I}),m.push(O))}return s(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 jr={arrayToObject:n,assign:o,combine:f,compact:h,decode:a,encode:u,isBuffer:y,isRegExp:p,maybeMap:g,merge:i},jr}function mh(){if(ro)return Nr;ro=!0;var l=ph(),e=Ma(),t=Ji(),r=Object.prototype.hasOwnProperty,s={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,o=function(g,b){i.apply(g,n(b)?b:[b])},a=Date.prototype.toISOString,c=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:c,formatter:t.formatters[c],indices:!1,serializeDate:function(g){return a.call(g)},skipNulls:!1,strictNullHandling:!1},h=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,x,v,E,S,I,O,P,N,T,q,D,U,ae,Y){for(var V=b,re=Y,F=0,Z=!1;(re=re.get(p))!==void 0&&!Z;){var M=re.get(b);if(F+=1,typeof M<"u"){if(M===F)throw new RangeError("Cyclic object value");Z=!0}typeof re.get(p)>"u"&&(F=0)}if(typeof O=="function"?V=O(k,V):V instanceof Date?V=T(V):m==="comma"&&n(V)&&(V=e.maybeMap(V,function(R){return R instanceof Date?T(R):R})),V===null){if(v)return I&&!U?I(k,u.encoder,ae,"key",q):k;V=""}if(h(V)||e.isBuffer(V)){if(I){var J=U?k:I(k,u.encoder,ae,"key",q);return[D(J)+"="+D(I(V,u.encoder,ae,"value",q))]}return[D(k)+"="+D(String(V))]}var be=[];if(typeof V>"u")return be;var te;if(m==="comma"&&n(V))U&&I&&(V=e.maybeMap(V,I)),te=[{value:V.length>0?V.join(",")||null:void 0}];else if(n(O))te=O;else{var we=Object.keys(V);te=P?we.sort(P):we}var G=S?k.replace(/\./g,"%2E"):k,j=w&&n(V)&&V.length===1?G+"[]":G;if(x&&n(V)&&V.length===0)return j+"[]";for(var ne=0;ne<te.length;++ne){var W=te[ne],K=typeof W=="object"&&typeof W.value<"u"?W.value:V[W];if(!(E&&K===null)){var Q=N&&S?W.replace(/\./g,"%2E"):W,ge=n(V)?typeof m=="function"?m(j,Q):j:j+(N?"."+Q:"["+Q+"]");Y.set(b,F);var oe=l();oe.set(p,Y),o(be,g(K,ge,m,w,x,v,E,S,m==="comma"&&U&&n(V)?null:I,O,P,N,T,q,D,U,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 x;if(g.arrayFormat in s?x=g.arrayFormat:"indices"in g?x=g.indices?"indices":"repeat":x=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:x,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 Nr=function(g,b){var k=g,m=f(b),w,x;typeof m.filter=="function"?(x=m.filter,k=x("",k)):n(m.filter)&&(x=m.filter,w=x);var v=[];if(typeof k!="object"||k===null)return"";var E=s[m.arrayFormat],S=E==="comma"&&m.commaRoundTrip;w||(w=Object.keys(k)),m.sort&&w.sort(m.sort);for(var I=l(),O=0;O<w.length;++O){var P=w[O];m.skipNulls&&k[P]===null||o(v,y(k[P],P,E,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 N=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&"),N.length>0?T+N:""},Nr}function gh(){if(no)return Ur;no=!0;var l=Ma(),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:l.decode,delimiter:"&",depth:5,duplicates:"combine",ignoreQueryPrefix:!1,interpretNumericEntities:!1,parameterLimit:1e3,parseArrays:!0,plainObjects:!1,strictDepth:!1,strictNullHandling:!1},s=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",o="utf8=%E2%9C%93",a=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,x=y.charset;if(y.charsetSentinel)for(w=0;w<k.length;++w)k[w].indexOf("utf8=")===0&&(k[w]===o?x="utf-8":k[w]===i&&(x="iso-8859-1"),m=w,w=k.length);for(w=0;w<k.length;++w)if(w!==m){var v=k[w],E=v.indexOf("]="),S=E===-1?v.indexOf("="):E+1,I,O;S===-1?(I=y.decoder(v,r.decoder,x,"key"),O=y.strictNullHandling?null:""):(I=y.decoder(v.slice(0,S),r.decoder,x,"key"),O=l.maybeMap(n(v.slice(S+1),y),function(N){return y.decoder(N,r.decoder,x,"value")})),O&&y.interpretNumericEntities&&x==="iso-8859-1"&&(O=s(O)),v.indexOf("[]=")>-1&&(O=t(O)?[O]:O);var P=e.call(f,I);P&&y.duplicates==="combine"?f[I]=l.combine(f[I],O):(!P||y.duplicates==="last")&&(f[I]=O)}return f},c=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 x=w.charAt(0)==="["&&w.charAt(w.length-1)==="]"?w.slice(1,-1):w,v=f.decodeDotInKeys?x.replace(/%2E/g,"."):x,E=parseInt(v,10);!f.parseArrays&&v===""?m={0:b}:!isNaN(E)&&w!==v&&String(E)===v&&E>=0&&f.parseArrays&&E<=f.arrayLimit?(m=[],m[E]=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),x=w?b.slice(0,w.index):b,v=[];if(x){if(!f.plainObjects&&e.call(Object.prototype,x)&&!f.allowPrototypes)return;v.push(x)}for(var E=0;f.depth>0&&(w=m.exec(b))!==null&&E<f.depth;){if(E+=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 c(v,y,f,g)}},h=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"||l.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 Ur=function(p,y){var f=h(y);if(p===""||p===null||typeof p>"u")return f.plainObjects?Object.create(null):{};for(var g=typeof p=="string"?a(p,f):p,b=f.plainObjects?Object.create(null):{},k=Object.keys(g),m=0;m<k.length;++m){var w=k[m],x=u(w,g[w],f,typeof p=="string");b=l.merge(b,x,f)}return f.allowSparse===!0?b:l.compact(b)},Ur}function bh(){if(io)return Br;io=!0;var l=mh(),e=gh(),t=Ji();return Br={formats:t,parse:e,stringify:l},Br}function yh(){if(oo)return _t;oo=!0;var l=vt;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]*$/,s=/^(\/\/?(?!\/)[^?\s]*)(\?[^\s]*)?$/,n=["<",">",'"',"`"," ","\r",`
7
+ `," "],i=["{","}","|","\\","^","`"].concat(n),o=["'"].concat(i),a=["%","/","?",";","#"].concat(o),c=["/","?","#"],u=255,h=/^[+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=bh();function k(v,E,S){if(v&&typeof v=="object"&&v instanceof e)return v;var I=new e;return I.parse(v,E,S),I}e.prototype.parse=function(v,E,S){if(typeof v!="string")throw new TypeError("Parameter 'url' must be a string, not "+typeof v);var I=v.indexOf("?"),O=I!==-1&&I<v.indexOf("#")?"?":"#",P=v.split(O),N=/\\/g;P[0]=P[0].replace(N,"/"),v=P.join(O);var T=v;if(T=T.trim(),!S&&v.split("#").length===1){var q=s.exec(T);if(q)return this.path=T,this.href=T,this.pathname=q[1],q[2]?(this.search=q[2],E?this.query=b.parse(this.search.substr(1)):this.query=this.search.substr(1)):E&&(this.search="",this.query={}),this}var D=t.exec(T);if(D){D=D[0];var U=D.toLowerCase();this.protocol=U,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,V=0;V<c.length;V++){var re=T.indexOf(c[V]);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 V=0;V<a.length;V++){var re=T.indexOf(a[V]);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 M=this.hostname[0]==="["&&this.hostname[this.hostname.length-1]==="]";if(!M)for(var J=this.hostname.split(/\./),V=0,be=J.length;V<be;V++){var te=J[V];if(te&&!te.match(h)){for(var we="",G=0,j=te.length;G<j;G++)te.charCodeAt(G)>127?we+="x":we+=te[G];if(!we.match(h)){var ne=J.slice(0,V),W=J.slice(V+1),K=te.match(p);K&&(ne.push(K[1]),W.unshift(K[2])),W.length&&(T="/"+W.join(".")+T),this.hostname=ne.join(".");break}}}this.hostname.length>u?this.hostname="":this.hostname=this.hostname.toLowerCase(),M||(this.hostname=l.toASCII(this.hostname));var Q=this.port?":"+this.port:"",ge=this.hostname||"";this.host=ge+Q,this.href+=this.host,M&&(this.hostname=this.hostname.substr(1,this.hostname.length-2),T[0]!=="/"&&(T="/"+T))}if(!y[U])for(var V=0,be=o.length;V<be;V++){var oe=o[V];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),E&&(this.query=b.parse(this.query)),T=T.slice(0,ee)):E&&(this.search="",this.query={}),T&&(this.pathname=T),g[U]&&this.hostname&&!this.pathname&&(this.pathname="/"),this.pathname||this.search){var Q=this.pathname||"",de=this.search||"";this.path=Q+de}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 E=this.protocol||"",S=this.pathname||"",I=this.hash||"",O=!1,P="";this.host?O=v+this.host:this.hostname&&(O=v+(this.hostname.indexOf(":")===-1?this.hostname:"["+this.hostname+"]"),this.port&&(O+=":"+this.port)),this.query&&typeof this.query=="object"&&Object.keys(this.query).length&&(P=b.stringify(this.query,{arrayFormat:"repeat",addQueryPrefix:!1}));var N=this.search||P&&"?"+P||"";return E&&E.substr(-1)!==":"&&(E+=":"),this.slashes||(!E||g[E])&&O!==!1?(O="//"+(O||""),S&&S.charAt(0)!=="/"&&(S="/"+S)):O||(O=""),I&&I.charAt(0)!=="#"&&(I="#"+I),N&&N.charAt(0)!=="?"&&(N="?"+N),S=S.replace(/[?#]/g,function(T){return encodeURIComponent(T)}),N=N.replace("#","%23"),E+O+S+N+I};function w(v,E){return k(v,!1,!0).resolve(E)}e.prototype.resolve=function(v){return this.resolveObject(k(v,!1,!0)).format()};function x(v,E){return v?k(v,!1,!0).resolveObject(E):E}return e.prototype.resolveObject=function(v){if(typeof v=="string"){var E=new e;E.parse(v,!1,!0),v=E}for(var S=new e,I=Object.keys(this),O=0;O<I.length;O++){var P=I[O];S[P]=this[P]}if(S.hash=v.hash,v.href==="")return S.href=S.format(),S;if(v.slashes&&!v.protocol){for(var N=Object.keys(v),T=0;T<N.length;T++){var q=N[T];q!=="protocol"&&(S[q]=v[q])}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),U=0;U<D.length;U++){var ae=D[U];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||"",V=S.search||"";S.path=Y+V}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,M=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 G=J.slice(-1)[0],j=(S.host||v.host||J.length>1)&&(G==="."||G==="..")||G==="",ne=0,W=J.length;W>=0;W--)G=J[W],G==="."?J.splice(W,1):G===".."?(J.splice(W,1),ne++):ne&&(J.splice(W,1),ne--);if(!Z&&!M)for(;ne--;ne)J.unshift("..");Z&&J[0]!==""&&(!J[0]||J[0].charAt(0)!=="/")&&J.unshift(""),j&&J.join("/").substr(-1)!=="/"&&J.push("");var K=J[0]===""||J[0]&&J[0].charAt(0)==="/";if(te){S.hostname=K?"":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&&!K&&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,E=r.exec(v);E&&(E=E[0],E!==":"&&(this.port=E.substr(1)),v=v.substr(0,v.length-E.length)),v&&(this.hostname=v)},_t.parse=k,_t.resolve=w,_t.resolveObject=x,_t.format=m,_t.Url=e,_t}function Ra(l){if(typeof l=="string")l=new URL(l);else if(!(l instanceof URL))throw new Deno.errors.InvalidData("invalid argument path , must be a string or URL");if(l.protocol!=="file:")throw new Deno.errors.InvalidData("invalid url scheme");return Dr?vh(l):wh(l)}function vh(l){let e=l.hostname,t=l.pathname;for(let r=0;r<t.length;r++)if(t[r]==="%"){let s=t.codePointAt(r+2)||32;if(t[r+1]==="2"&&s===102||t[r+1]==="5"&&s===99)throw new Deno.errors.InvalidData("must not include encoded \\ or / characters")}if(t=t.replace(Ga,"\\"),t=decodeURIComponent(t),e!=="")return`\\\\${e}${t}`;{let r=t.codePointAt(1)|32,s=t[2];if(r<za||r>Va||s!==":")throw new Deno.errors.InvalidData("file url path must be absolute");return t.slice(1)}}function wh(l){if(l.hostname!=="")throw new Deno.errors.InvalidData("invalid file url hostname");let e=l.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 La(l){let e=Qi.resolve(l),t=l.charCodeAt(l.length-1);(t===Wa||Dr&&t===Ha)&&e[e.length-1]!==Qi.sep&&(e+="/");let r=new URL("file://");return e.includes("%")&&(e=e.replace(Ka,"%25")),!Dr&&e.includes("\\")&&(e=e.replace(Ya,"%5C")),e.includes(`
8
+ `)&&(e=e.replace(Qa,"%0A")),e.includes("\r")&&(e=e.replace(Ja,"%0D")),e.includes(" ")&&(e=e.replace(Xa,"%09")),r.pathname=e,r}var ja,Pr,Xi,Mr,Rr,Zi,Lr,eo,jr,to,Nr,ro,Ur,no,Br,io,_t,oo,qe,Na,Ua,Ba,Da,Fa,$a,qa,Ha,Wa,za,Va,Dr,Ga,Ka,Ya,Qa,Ja,Xa,_h=Ve(()=>{le(),ue(),ce(),Bu(),eh(),dh(),Oa(),ja=Object.freeze(Object.create(null)),Pr={},Xi=!1,Mr=typeof globalThis<"u"?globalThis:typeof self<"u"?self:global,Rr={},Zi=!1,Lr={},eo=!1,jr={},to=!1,Nr={},ro=!1,Ur={},no=!1,Br={},io=!1,_t={},oo=!1,qe=yh(),qe.parse,qe.resolve,qe.resolveObject,qe.format,qe.Url,Na=typeof Deno<"u"?Deno.build.os==="windows"?"win32":Deno.build.os:void 0,qe.URL=typeof URL<"u"?URL:null,qe.pathToFileURL=La,qe.fileURLToPath=Ra,Ua=qe.Url,Ba=qe.format,Da=qe.resolve,Fa=qe.resolveObject,$a=qe.parse,qa=qe.URL,Ha=92,Wa=47,za=97,Va=122,Dr=Na==="win32",Ga=/\//g,Ka=/%/g,Ya=/\\/g,Qa=/\n/g,Ja=/\r/g,Xa=/\t/g}),kh=pe((l,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(l=>{le(),ue(),ce(),Object.defineProperty(l,"__esModule",{value:!0}),l.BufferedDuplex=void 0,l.writev=r;var e=It(),t=(De(),Me(Be));function r(n,i){let o=new Array(n.length);for(let a=0;a<n.length;a++)typeof n[a].chunk=="string"?o[a]=t.Buffer.from(n[a].chunk,"utf8"):o[a]=n[a].chunk;this._write(t.Buffer.concat(o),"binary",i)}var s=class extends e.Duplex{socket;proxy;isSocketOpen;writeQueue;constructor(n,i,o){super({objectMode:!0}),this.proxy=i,this.socket=o,this.writeQueue=[],n.objectMode||(this._writev=r.bind(this)),this.isSocketOpen=!1,this.proxy.on("data",a=>{!this.destroyed&&this.readable&&this.push(a)})}_read(n){this.proxy.read(n)}_write(n,i,o){this.isSocketOpen?this.writeToProxy(n,i,o):this.writeQueue.push({chunk:n,encoding:i,cb:o})}_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,o){this.proxy.write(n,i)===!1?this.proxy.once("drain",o):o()}processWriteQueue(){for(;this.writeQueue.length>0;){let{chunk:n,encoding:i,cb:o}=this.writeQueue.shift();this.writeToProxy(n,i,o)}}};l.BufferedDuplex=s}),Fr=pe(l=>{le(),ue(),ce();var e=l&&l.__importDefault||function(k){return k&&k.__esModule?k:{default:k}};Object.defineProperty(l,"__esModule",{value:!0}),l.streamBuilder=l.browserStreamBuilder=void 0;var t=(De(),Me(Be)),r=e(kh()),s=e(ht()),n=It(),i=e(pr()),o=so(),a=(0,s.default)("mqttjs:ws"),c=["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 h(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"&&c.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=h(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){a("createWebSocket"),a(`protocol: ${w.protocolId} ${w.protocolVersion}`);let x=w.protocolId==="MQIsdp"&&w.protocolVersion===3?"mqttv3.1":"mqtt";a(`creating new Websocket for url: ${m} and protocol: ${x}`);let v;return w.createWebsocket?v=w.createWebsocket(m,[x],w):v=new r.default(m,[x],w.wsOptions),v}function f(k,m){let w=m.protocolId==="MQIsdp"&&m.protocolVersion===3?"mqttv3.1":"mqtt",x=u(m,k),v;return m.createWebsocket?v=m.createWebsocket(x,[w],m):v=new WebSocket(x,[w]),v.binaryType="arraybuffer",v}var g=(k,m)=>{a("streamBuilder");let w=h(m);w.hostname=w.hostname||w.host||"localhost";let x=u(w,k),v=y(k,x,w),E=r.default.createWebSocketStream(v,w.wsOptions);return E.url=x,v.on("close",()=>{E.destroy()}),E};l.streamBuilder=g;var b=(k,m)=>{a("browserStreamBuilder");let w,x=p(m).browserBufferSize||1024*512,v=m.browserBufferTimeout||1e3,E=!m.objectMode,S=f(k,m),I=P(m,U,ae);m.objectMode||(I._writev=o.writev.bind(I)),I.on("close",()=>{S.close()});let O=typeof S.addEventListener<"u";S.readyState===S.OPEN?(w=I,w.socket=S):(w=new o.BufferedDuplex(m,I,S),O?S.addEventListener("open",N):S.onopen=N),O?(S.addEventListener("close",T),S.addEventListener("error",q),S.addEventListener("message",D)):(S.onclose=T,S.onerror=q,S.onmessage=D);function P(Y,V,re){let F=new n.Transform({objectMode:Y.objectMode});return F._write=V,F._flush=re,F}function N(){a("WebSocket onOpen"),w instanceof o.BufferedDuplex&&w.socketReady()}function T(Y){a("WebSocket onClose",Y),w.end(),w.destroy()}function q(Y){a("WebSocket onError",Y);let V=new Error("WebSocket error");V.event=Y,w.destroy(V)}async function D(Y){if(!I||!I.readable||!I.writable)return;let{data:V}=Y;V instanceof ArrayBuffer?V=t.Buffer.from(V):V instanceof Blob?V=t.Buffer.from(await new Response(V).arrayBuffer()):V=t.Buffer.from(V,"utf8"),I.push(V)}function U(Y,V,re){if(S.bufferedAmount>x){setTimeout(U,v,Y,V,re);return}E&&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};l.browserStreamBuilder=b}),ao={};Rt(ao,{Server:()=>je,Socket:()=>je,Stream:()=>je,_createServerHandle:()=>je,_normalizeArgs:()=>je,_setSimultaneousAccepts:()=>je,connect:()=>je,createConnection:()=>je,createServer:()=>je,default:()=>Za,isIP:()=>je,isIPv4:()=>je,isIPv6:()=>je});function je(){throw new Error("Node.js net module is not supported by JSPM core outside of Node.js")}var Za,el=Ve(()=>{le(),ue(),ce(),Za={_createServerHandle:je,_normalizeArgs:je,_setSimultaneousAccepts:je,connect:je,createConnection:je,createServer:je,isIP:je,isIPv4:je,isIPv6:je,Server:je,Socket:je,Stream:je}}),tl=pe((l,e)=>{le(),ue(),ce(),e.exports={}}),rl=pe(l=>{le(),ue(),ce();var e=l&&l.__importDefault||function(o){return o&&o.__esModule?o:{default:o}};Object.defineProperty(l,"__esModule",{value:!0});var t=e((el(),Me(ao))),r=e(ht()),s=e(tl()),n=(0,r.default)("mqttjs:tcp"),i=(o,a)=>{if(a.port=a.port||1883,a.hostname=a.hostname||a.host||"localhost",a.socksProxy)return(0,s.default)(a.hostname,a.port,a.socksProxy,{timeout:a.socksTimeout});let{port:c,path:u}=a,h=a.hostname;return n("port %d and host %s",c,h),t.default.createConnection({port:c,host:h,path:u})};l.default=i}),nl={};Rt(nl,{default:()=>il});var il,xh=Ve(()=>{le(),ue(),ce(),il={}}),ol=pe(l=>{le(),ue(),ce();var e=l&&l.__importDefault||function(c){return c&&c.__esModule?c:{default:c}};Object.defineProperty(l,"__esModule",{value:!0});var t=(xh(),Me(nl)),r=e((el(),Me(ao))),s=e(ht()),n=e(tl()),i=(0,s.default)("mqttjs:tls");function o(c){let{host:u,port:h,socksProxy:p,...y}=c;if(p!==void 0){let f=(0,n.default)(u,h,p,{timeout:c.socksTimeout});return(0,t.connect)({...y,socket:f})}return(0,t.connect)(c)}var a=(c,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 h=o(u);h.on("secureConnect",()=>{u.rejectUnauthorized&&!h.authorized?h.emit("error",new Error("TLS not authorized")):h.removeListener("error",p)});function p(y){u.rejectUnauthorized&&c.emit("error",y),h.end()}return h.on("error",p),h};l.default=a}),sl=pe(l=>{le(),ue(),ce(),Object.defineProperty(l,"__esModule",{value:!0});var e=(De(),Me(Be)),t=It(),r=so(),s,n,i;function o(){let p=new t.Transform;return p._write=(y,f,g)=>{s.send({data:y.buffer,success(){g()},fail(b){g(new Error(b))}})},p._flush=y=>{s.close({success(){y()}})},p}function a(p){p.hostname||(p.hostname="localhost"),p.path||(p.path="/"),p.wsOptions||(p.wsOptions={})}function c(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(){s.onOpen(()=>{i.socketReady()}),s.onMessage(p=>{let{data:y}=p;y instanceof ArrayBuffer?y=e.Buffer.from(y):y=e.Buffer.from(y,"utf8"),n.push(y)}),s.onClose(()=>{i.emit("close"),i.end(),i.destroy()}),s.onError(p=>{let y=new Error(p.errMsg);i.destroy(y)})}var h=(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";a(y);let g=c(y,p);s=wx.connectSocket({url:g,protocols:[f]}),n=o(),i=new r.BufferedDuplex(y,n,s),i._destroy=(k,m)=>{s.close({success(){m&&m(k)}})};let b=i.destroy;return i.destroy=(k,m)=>(i.destroy=b,setTimeout(()=>{s.close({fail(){i._destroy(k,m)}})},0),i),u(),i};l.default=h}),al=pe(l=>{le(),ue(),ce(),Object.defineProperty(l,"__esModule",{value:!0});var e=(De(),Me(Be)),t=It(),r=so(),s,n,i,o=!1;function a(){let y=new t.Transform;return y._write=(f,g,b)=>{s.sendSocketMessage({data:f.buffer,success(){b()},fail(){b(new Error)}})},y._flush=f=>{s.closeSocket({success(){f()}})},y}function c(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 h(){o||(o=!0,s.onSocketOpen(()=>{i.socketReady()}),s.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)}}),s.onSocketClose(()=>{i.end(),i.destroy()}),s.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";c(f);let b=u(f,y);return s=f.my,s.connectSocket({url:b,protocols:g}),n=a(),i=new r.BufferedDuplex(f,n,s),h(),i};l.default=p}),Sh=pe(l=>{le(),ue(),ce();var e=l&&l.__importDefault||function(h){return h&&h.__esModule?h:{default:h}};Object.defineProperty(l,"__esModule",{value:!0}),l.connectAsync=u;var t=e(ht()),r=e((_h(),Me(Pa))),s=e(di()),n=e(pr());typeof Le?.nextTick!="function"&&(Le.nextTick=setImmediate);var i=(0,t.default)("mqttjs"),o=null;function a(h){let p;if(h.auth)if(p=h.auth.match(/^(.+):(.+)$/),p){let[,y,f]=p;h.username=y,h.password=f}else h.username=h.auth}function c(h,p){if(i("connecting to an MQTT broker..."),typeof h=="object"&&!p&&(p=h,h=""),p=p||{},h&&typeof h=="string"){let g=r.default.parse(h,!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,a(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 Le<"u"&&(p.socksProxy=Le.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(o||(o={},!n.default&&!p.forceNativeWebSocket?(o.ws=Fr().streamBuilder,o.wss=Fr().streamBuilder,o.mqtt=rl().default,o.tcp=rl().default,o.ssl=ol().default,o.tls=o.ssl,o.mqtts=ol().default):(o.ws=Fr().browserStreamBuilder,o.wss=Fr().browserStreamBuilder,o.wx=sl().default,o.wxs=sl().default,o.ali=al().default,o.alis=al().default)),!o[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 o[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),o[p.protocol](g,p)}let f=new s.default(y,p);return f.on("error",()=>{}),f}function u(h,p,y=!0){return new Promise((f,g)=>{let b=c(h,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])})})}l.default=c}),ll=pe(l=>{le(),ue(),ce();var e=l&&l.__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=l&&l.__setModuleDefault||(Object.create?function(y,f){Object.defineProperty(y,"default",{enumerable:!0,value:f})}:function(y,f){y.default=f}),r=l&&l.__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}})(),s=l&&l.__exportStar||function(y,f){for(var g in y)g!=="default"&&!Object.prototype.hasOwnProperty.call(f,g)&&e(f,y,g)},n=l&&l.__importDefault||function(y){return y&&y.__esModule?y:{default:y}};Object.defineProperty(l,"__esModule",{value:!0}),l.ReasonCodes=l.KeepaliveManager=l.UniqueMessageIdProvider=l.DefaultMessageIdProvider=l.Store=l.MqttClient=l.connectAsync=l.connect=l.Client=void 0;var i=n(di());l.MqttClient=i.default;var o=n(ms());l.DefaultMessageIdProvider=o.default;var a=n(Nu());l.UniqueMessageIdProvider=a.default;var c=n(ls());l.Store=c.default;var u=r(Sh());l.connect=u.default,Object.defineProperty(l,"connectAsync",{enumerable:!0,get:function(){return u.connectAsync}});var h=n(ks());l.KeepaliveManager=h.default,l.Client=i.default,s(di(),l),s(Ut(),l),s(as(),l);var p=dr();Object.defineProperty(l,"ReasonCodes",{enumerable:!0,get:function(){return p.ReasonCodes}})}),Eh=pe(l=>{le(),ue(),ce();var e=l&&l.__createBinding||(Object.create?function(i,o,a,c){c===void 0&&(c=a);var u=Object.getOwnPropertyDescriptor(o,a);(!u||("get"in u?!o.__esModule:u.writable||u.configurable))&&(u={enumerable:!0,get:function(){return o[a]}}),Object.defineProperty(i,c,u)}:function(i,o,a,c){c===void 0&&(c=a),i[c]=o[a]}),t=l&&l.__setModuleDefault||(Object.create?function(i,o){Object.defineProperty(i,"default",{enumerable:!0,value:o})}:function(i,o){i.default=o}),r=l&&l.__importStar||(function(){var i=function(o){return i=Object.getOwnPropertyNames||function(a){var c=[];for(var u in a)Object.prototype.hasOwnProperty.call(a,u)&&(c[c.length]=u);return c},i(o)};return function(o){if(o&&o.__esModule)return o;var a={};if(o!=null)for(var c=i(o),u=0;u<c.length;u++)c[u]!=="default"&&e(a,o,c[u]);return t(a,o),a}})(),s=l&&l.__exportStar||function(i,o){for(var a in i)a!=="default"&&!Object.prototype.hasOwnProperty.call(o,a)&&e(o,i,a)};Object.defineProperty(l,"__esModule",{value:!0});var n=r(ll());l.default=n,s(ll(),l)});const Ah=Eh();const Ih={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}/#"},Th=300,Ch={templateId:"7",type:"link",isDeepLink:!0},Oh={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;connectedAt=0;disposed=!1;reconnectTimer=null;lifecycleHandlersAttached=!1;onOnlineHandler=null;onVisibilityHandler=null;onPageShowHandler=null;inboundRegex;inboundUpdateRegex;constructor(e){this.config=e,this.currentToken=e.jwtToken,this.appId=e.appId??"tilechat",this.clientId=e.clientId??this.freshClientId(),this.topics={...Ih,...e.topicTemplates??{}},this.maxReconnectAttempts=e.maxReconnectAttempts??1/0,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};this.clientId=this.config.clientId??this.freshClientId();const r=this.config.connectTimeoutMs??1e4,s={clientId:this.clientId,username:this.config.mqttUsername??"JWT",password:this.currentToken,clean:!1,resubscribe:!0,reconnectPeriod:0,connectTimeout:r,keepalive:this.config.keepAliveSec??30,protocolVersion:this.config.protocolVersion??4,protocolId:this.config.protocolId??"MQTT"};return this.config.enablePresence!==!1&&(s.will={topic:e,payload:JSON.stringify(t),qos:0,retain:!1}),this.attachLifecycleHandlers(),new Promise((n,i)=>{let o=!1;const a=h=>{o||(o=!0,clearTimeout(u),h())},c=(h,p)=>{o||(this.debugLog("CONNECT_FAIL",{reason:h,message:p?.message}),a(()=>i(p??new Error(`tiledesk-transport: ${h}`))))},u=setTimeout(()=>c("connect-timeout"),r+500);this.client=Ah.connect(this.config.mqttEndpoint,s),this.client.on("connect",()=>{if(this.connectedAt=Date.now(),o||a(()=>n()),this.debugLog("CONNECT",{endpoint:this.config.mqttEndpoint,clientId:this.clientId}),this.notifyStateChange(!0),this.config.enablePresence!==!1){const h=this.config.presencePayloadConnected??{connected:!0};this.client.publish(e,JSON.stringify(h),{qos:0,retain:!1}),this.debugLog("PUBLISH",{topic:e,payload:h})}}),this.client.on("message",(h,p)=>{this.dispatchInbound(h,p)}),this.client.on("close",()=>{if(this.debugLog("CLOSE",{}),this.notifyStateChange(!1),!o){c("socket-closed-pre-connack");return}this.disposed||this.scheduleReconnect()}),this.client.on("error",h=>{this.debugLog("ERROR",{message:h.message}),o||c("mqtt-error",h)}),this.client.on("disconnect",h=>{this.debugLog("DISCONNECT",{reasonCode:h?.reasonCode,properties:h?.properties})}),this.client.on("offline",()=>{this.debugLog("OFFLINE",{}),o||c("mqtt-offline")}),this.client.on("packetsend",h=>{(h.cmd==="subscribe"||h.cmd==="unsubscribe"||h.cmd==="pingreq")&&this.debugLog(h.cmd.toUpperCase(),{topic:h.topic,packetId:h.messageId})})})}freshClientId(){const e=Math.random().toString(36).slice(2,8);return`aikaara_${this.config.userId}_${Date.now()}_${e}`}debugLog(e,t){if(!this.config.debug)return;const r={};for(const[s,n]of Object.entries(t))typeof n=="string"&&n.length>200?r[s]=`${n.slice(0,200)}…(${n.length})`:r[s]=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 s=this.buildOutgoingEnvelope(e,{text:t,type:"text",...r});this.publishEnvelope(e,s)}publishFileMessage(e,t){if(!this.client)return;const r={...Ch,...this.config.fileTemplate??{},...Ph(t)},s={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(s),type:"html",attributes:n,metadata:s.metadata});this.publishEnvelope(e,i)}publishRaw(e,t){this.client&&this.publishEnvelope(e,t)}publishReadReceipt(e,t,r=Th){if(!this.client)return;const s=this.renderTemplate(this.topics.inboundUpdate,{conversationId:e,messageId:t});this.client.publish(s,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.detachLifecycleHandlers(),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||this.reconnectTimer)return;if(typeof navigator<"u"&&navigator.onLine===!1){this.debugLog("RECONNECT_SKIP_OFFLINE",{attempt:this.reconnectAttempt});return}this.connectedAt>0&&Date.now()-this.connectedAt>=5e3&&(this.reconnectAttempt=0),this.connectedAt=0;const e=Math.min(1e3*Math.pow(2,this.reconnectAttempt),this.reconnectMaxDelayMs),t=e*.2*(Math.random()*2-1),r=Math.max(0,Math.round(e+t));this.reconnectAttempt++,this.reconnectTimer=setTimeout(async()=>{if(this.reconnectTimer=null,!this.disposed){if(this.config.tokenProvider)try{this.currentToken=await this.config.tokenProvider()}catch{}try{await this.connect();const s=[...this.subscribedTopics];this.subscribedTopics.clear(),s.forEach(n=>{this.client&&(this.client.subscribe(n,{qos:this.config.subscribeQos??2}),this.subscribedTopics.add(n))})}catch{}}},r)}reconnectNow(e){this.disposed||this.isConnected||typeof navigator<"u"&&navigator.onLine===!1||(this.debugLog("RECONNECT_NOW",{reason:e}),this.reconnectTimer&&(clearTimeout(this.reconnectTimer),this.reconnectTimer=null),this.reconnectAttempt=0,this.scheduleReconnect())}attachLifecycleHandlers(){this.lifecycleHandlersAttached||typeof window>"u"||typeof document>"u"||(this.onOnlineHandler=()=>this.reconnectNow("online"),this.onVisibilityHandler=()=>{document.visibilityState==="visible"&&this.reconnectNow("visible")},this.onPageShowHandler=e=>{e.persisted&&this.reconnectNow("pageshow-bfcache")},window.addEventListener("online",this.onOnlineHandler),document.addEventListener("visibilitychange",this.onVisibilityHandler),window.addEventListener("pageshow",this.onPageShowHandler),this.lifecycleHandlersAttached=!0)}detachLifecycleHandlers(){this.lifecycleHandlersAttached&&(typeof window>"u"||typeof document>"u"||(this.onOnlineHandler&&window.removeEventListener("online",this.onOnlineHandler),this.onVisibilityHandler&&document.removeEventListener("visibilitychange",this.onVisibilityHandler),this.onPageShowHandler&&window.removeEventListener("pageshow",this.onPageShowHandler),this.onOnlineHandler=null,this.onVisibilityHandler=null,this.onPageShowHandler=null,this.lifecycleHandlersAttached=!1))}notifyStateChange(e){this.stateHandlers.forEach(t=>t(e))}dispatchInbound(e,t){const r=t.toString();let s=null;try{s=JSON.parse(r)}catch{this.debugLog("RECV (non-json)",{topic:e,raw:r});return}if(!s)return;this.debugLog("RECV",{topic:e,sender:s.sender,type:s.type,contentType:s.metadata?.contentType,templateId:s.metadata?.templateId,messageId:s.message_id,text:typeof s.text=="string"?s.text:void 0});const n=e.match(this.inboundUpdateRegex);if(n){const c=n.groups?.conversationId??"",u=n.groups?.messageId??"",h=typeof s.status=="number"?s.status:Number(s.status??0),p={conversationId:c,messageId:u,status:h,raw:s};this.statusUpdateHandlers.forEach(y=>y(p)),this.messageHandlers.forEach(y=>y(s,{topic:e,conversationId:c,messageId:u,kind:"update"}));return}const i=e.match(this.inboundRegex),o=i?.groups?.conversationId,a={topic:e,conversationId:o,messageId:typeof s.message_id=="string"?s.message_id:void 0,kind:i?"clientadded":"unknown"};this.messageHandlers.forEach(c=>c(s,a))}buildOutgoingEnvelope(e,t){const r={...Oh,...this.config.messageDefaults??{}},s=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:s,senderFullname:s,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,(s,n)=>r[n]??"")}buildTopicRegex(e,t){const r=e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&").replace(/\\\{(\w+)\\\}/g,(s,n)=>{const i={appId:this.appId,userId:this.config.userId,projectId:this.config.projectId,clientId:this.clientId};if(t.includes(n))return`(?<${n}>[^/]+)`;const o=i[n];return o?o.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"):"[^/]+"});return new RegExp(`^${r}$`)}}function Ph(l){const e={};for(const[t,r]of Object.entries(l))r!==void 0&&(e[t]=r);return e}function ul(l,e){return(l.sender??"").toString()===e}function hl(l,e){const t=(l.sender??"").toString(),r=e.systemSenders??["metadata","system"],s=e.botSenderPrefix??"bot_";return t?t===e.userId?"user":t.startsWith(s)?"assistant":r.includes(t)?"system":"agent":"system"}function lo(l){const e={raw:l},t=l.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 l.text=="string"&&l.text.trim().startsWith("{"))try{const s=JSON.parse(l.text);typeof s.message=="string"&&(e.innerMessage=s.message);const n=s.metadata;n&&typeof n=="object"&&(!e.contentType&&typeof n.contentType=="string"&&(e.contentType=n.contentType),!e.templateId&&typeof n.templateId=="string"&&(e.templateId=n.templateId),e.payload===void 0&&n.payload!==void 0&&(e.payload=n.payload))}catch{}const r=l.attributes;if(r&&typeof r=="object"){const s=r.attachment;!e.contentType&&typeof r.contentType=="string"&&(e.contentType=r.contentType),!e.contentType&&s&&typeof s.contentType=="string"&&(e.contentType=s.contentType),!e.templateId&&typeof r.templateId=="string"&&(e.templateId=r.templateId),!e.templateId&&s&&typeof s.templateId=="string"&&(e.templateId=s.templateId),e.payload===void 0&&r.payload!==void 0&&(e.payload=r.payload),e.payload===void 0&&s&&s.payload!==void 0&&(e.payload=s.payload),e.payload===void 0&&s&&s.template!==void 0&&(e.payload=s.template)}return e}function dl(l){const e=lo(l);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 s=r[0],n=s.action,i=n&&typeof n.url=="string"?n.url:void 0,o=typeof s.description=="string"?s.description:void 0,a=l.attributes,c=a&&typeof a.cloudFileId=="string"?a.cloudFileId:void 0;return!i&&!o?null:{fileName:o,fileUrl:i,cloudFileId:c,templateId:e.templateId}}function fl(l,e,t){const r=hl(l,t),s=lo(l),n=dl(l);let i="";s.innerMessage?i=s.innerMessage:typeof l.text=="string"&&(l.text.trim().startsWith("{")?s.contentType!=="300"&&(i=l.text):i=l.text);const o=typeof l.message_id=="string"?l.message_id:`td_${Date.now()}_${Math.random().toString(36).slice(2,8)}`,a=typeof l.timestamp=="number"?new Date(l.timestamp).toISOString():new Date().toISOString(),c=r==="assistant"?"assistant":r==="agent"?"agent":r==="system"?"system":"user",u=typeof l.status=="number"?Mh(l.status):"delivered",h={id:o,externalId:o,conversationId:e,role:c,content:i,createdAt:a,status:u,metadata:{sender:l.sender,sender_fullname:l.sender_fullname??l.senderFullname,app_id:l.app_id,attributes:l.attributes}};return s.contentType&&(h.template={contentType:s.contentType,templateId:s.templateId,payload:s.payload}),n?.fileUrl&&(h.attachments=[{fileName:n.fileName??"file",fileUrl:n.fileUrl,cloudFileId:n.cloudFileId}]),{message:h,template:s}}function Mh(l){return l<0?"error":l>=250?"read":l>=150?"delivered":"sent"}class pl extends ir{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 Ao(e.baseUrl,e.userToken,e.apiKey,e.authToken),this.messageStore=new Io,this.conversationManager=new Mo(e.conversationId),this.usesAikaara()&&(this.connection=new Eo(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 s=r?"connected":"disconnected";this.emit("connection:state",s),this.config.onConnectionStateChange?.(s)})),this.tiledeskUnsubs.push(this.tiledesk.onMessage((r,s)=>this.handleTiledeskMessage(r,s))),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),s=this.config.tiledesk?.autoInitiateOnEmpty??!0,n=this.config.tiledesk?.autoInitiateOnUnknown??!1;s&&(r==="empty"||r==="unknown"&&n)&&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(o){return this.config.onError?.(o instanceof Error?o:new Error(String(o))),"unknown"}if(!r.length)return"empty";const s=r.map(o=>fl(o,e,{userId:t}).message).sort((o,a)=>new Date(o.createdAt).getTime()-new Date(a.createdAt).getTime()),n=this.messageStore.messages,i=[...s,...n.filter(o=>!s.some(a=>a.externalId&&a.externalId===o.externalId))];if(this.messageStore.setMessages(i),this.config.onMessage)for(const o of s)try{this.config.onMessage(o)}catch(a){console.warn("[aikaara-chat-sdk] onMessage threw on history replay",a)}return"has-history"}async sendMessage(e,t={}){const r=this.conversationManager.conversationId;if(!r)throw new Error("No active conversation");const s=this.messageStore.addOptimistic("user",e,r);this.emit("message:sent",s),this.config.onMessage?.(s);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 s=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:s.fileName,fileUrl:s.url,cloudFileId:s.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 s=this.conversationManager.conversationId;if(!s)throw new Error("No active conversation");this.connection&&this.connection.sendUserEvent(s,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 s=this.config.tiledeskIdentity?.userId??"",{message:n,template:i}=fl(e,r,{userId:s,systemSenders:this.config.tiledesk?.messageDefaults?.attributes?.systemSenders});if(this.mode==="dual"&&n.role==="assistant")return;if(ul(e,s)){const c=this.messageStore.reconcileOptimistic(n);if(c){this.emit("message:updated",c);return}}const{message:o,deduped:a}=this.messageStore.upsertRemoteMessage(n);if(a)this.emit("message:updated",o);else{this.emit("message:received",o),this.config.onMessage?.(o);try{typeof window<"u"&&window.dispatchEvent(new CustomEvent("aikaara:message",{detail:{role:o.role,hasAttachments:Array.isArray(o.attachments)&&o.attachments.length>0,templateId:o.template?.templateId,messageId:o.id,conversationId:o.conversationId}}))}catch{}}if(i.contentType){const c={messageId:o.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?.(c)}}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||"",s=e.content||"";s?this.messageStore.updateStreaming(s):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,s=this.messageStore.finalizeStreaming(r?{tokensInput:r.tokens_input||0,tokensOutput:r.tokens_output||0}:void 0);this.emit("typing:stop",void 0),s&&(this.emit("stream:end",{messageId:s.id,usage:r?{tokensInput:r.tokens_input||0,tokensOutput:r.tokens_output||0}:void 0}),this.emit("message:received",s),this.config.onMessage?.(s));break}case"message_queued":{const r=this.messageStore.messages.findLast(s=>s.status==="sending");r&&this.messageStore.confirmOptimistic(r.id);break}case"tool_execution_start":{this.emit("tool:start",{toolName:e.tool_name||"",args:e.args||{}}),this.emit("status",e.type);break}case"tool_execution_end":{this.emit("tool:end",{toolName:e.tool_name||"",result:e.result,isError:!!e.is_error}),this.emit("status",e.type),this.parseActionResult(e.result);break}case"tool_execution_update":case"agent_start":case"agent_end":case"turn_start":case"turn_end":case"auto_retry_start":case"auto_retry_end":case"cancelled":this.emit("status",e.type);break}}}class Rh extends ir{registration=null;pendingEdits=[];constructor(e){super(),this.setupListeners(e)}registerForm(e){this.registration=e;const t=this.pendingEdits.filter(r=>r.entity_type===e.entityType&&String(r.entity_id)===String(e.entityId));if(t.length>0){for(const r of t)e.onFieldUpdate(r.fields),this.emit("edit:applied",{entityType:r.entity_type,entityId:r.entity_id,fields:r.fields});this.pendingEdits=this.pendingEdits.filter(r=>!(r.entity_type===e.entityType&&String(r.entity_id)===String(e.entityId)))}}unregisterForm(e,t){this.registration?.entityType===e&&String(this.registration?.entityId)===String(t)&&(this.registration=null)}get currentForm(){return this.registration}pushFieldUpdates(e,t,r){this.registration&&this.registration.entityType===e&&String(this.registration.entityId)===String(t)?(this.registration.onFieldUpdate(r),this.emit("edit:applied",{entityType:e,entityId:t,fields:r})):(this.pendingEdits.push({action:"edit_entity",entity_type:e,entity_id:t,fields:r}),this.emit("edit:pending",{entityType:e,entityId:t,fields:r}))}async requestSave(){if(!this.registration)return{success:!1,error:"No form registered"};try{return await this.registration.onSave(),this.emit("save:success",{entityType:this.registration.entityType,entityId:this.registration.entityId}),{success:!0}}catch(e){const t=e instanceof Error?e.message:"Save failed";return this.emit("save:error",{entityType:this.registration.entityType,entityId:this.registration.entityId,error:t}),{success:!1,error:t}}}async requestTest(e){if(!this.registration?.onTest)return{success:!1,error:"Current form does not support testing"};try{return await this.registration.onTest(e),{success:!0}}catch(t){return{success:!1,error:t instanceof Error?t.message:"Test failed"}}}setupListeners(e){e.on("action:edit_entity",t=>{this.pushFieldUpdates(t.entity_type,t.entity_id,t.fields)}),e.on("action:save_entity",t=>{this.requestSave()}),e.on("action:test_tool",t=>{this.emit("test:triggered",{toolId:t.tool_id,parameters:t.parameters}),this.requestTest(t.parameters)})}}const ml={txt:"text/plain",pdf:"application/pdf",jpg:"image/jpeg",jpeg:"image/jpeg",png:"image/png",csv:"text/csv",doc:"application/msword",json:"application/json"};function Lh(l){const e=l.lastIndexOf(".");return e<0||e===l.length-1?"":l.slice(e+1).toLowerCase()}function jh(l,e,t){const r=Lh(l.name||"");if(r&&e&&e[r])return e[r];const s=l.type;return s&&s.trim().length>0?s:r&&ml[r]?ml[r]:t}function co(l,e){return l.replace(/\{(\w+)\}/g,(t,r)=>e[r]??"")}function Nh(l,e){const t=e.split(".");let r=l;for(const s of t)if(r&&typeof r=="object"&&s in r)r=r[s];else return"";return typeof r=="string"?r:""}function gl(l){const e=l.signedUrlPath??"data.s3SignedUrl";return{async upload(t,r){const s=t.name||`upload-${Date.now()}`,n=jh(t,l.contentTypeMap,l.contentTypeFallback??"application/octet-stream"),i={fileName:s,userId:r.userId,requestId:r.conversationId,conversationId:r.conversationId,contentType:n},o=l.authHeader?await l.authHeader():void 0,a={accept:"application/json",...l.extraHeaders??{},...o?{authorization:o}:{}};let c=l.signEndpoint.includes("{")?l.signEndpoint:`${l.signEndpoint}?fileName={fileName}`;if(!c.includes("{contentType}")){const k=c.includes("?")?"&":"?";c=`${c}${k}contentType={contentType}`}const u=co(c,i),h=await fetch(u,{method:l.signMethod??"GET",headers:a});if(!h.ok)throw new Error(`Sign request failed: ${h.status}`);const p=await h.json().catch(()=>({})),y=Nh(p,e);if(!y)throw new Error(`Sign response missing path "${e}"`);const f=l.s3HostRewrite?y.replace(/^https:\/\/[^/]+/i,l.s3HostRewrite):y,g=await fetch(f,{method:"PUT",headers:{"content-type":n},body:t});if(!g.ok){const k=await g.text().catch(()=>"");throw new Error(`S3 PUT failed: ${g.status} ${k.slice(0,200)}`)}if(l.registerEndpoint){const k=JSON.parse(co(JSON.stringify(l.registerBody??{}),i)),m=await fetch(l.registerEndpoint,{method:"POST",headers:{...a,"content-type":"application/json"},body:JSON.stringify(k)});if(!m.ok){const w=await m.text().catch(()=>"");throw new Error(`Register failed: ${m.status} ${w.slice(0,200)}`)}}return{url:l.viewerTemplate?co(l.viewerTemplate,i):y.split("?")[0],fileName:s,contentType:n,byteSize:t.size,meta:{requestId:r.conversationId}}}}}function uo(l){return{async upload(e,t){const r=new FormData,s=l.fieldName??"file";r.append(s,e,e.name);const n=typeof l.extraFields=="function"?l.extraFields(t):l.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 l.headers=="function"?await l.headers():l.headers??{},o=await fetch(l.endpoint,{method:l.method??"POST",body:r,headers:i,credentials:l.credentials});if(!o.ok)throw new Error(`Upload failed: ${o.status} ${o.statusText}`);const a=await o.json().catch(()=>({}));if(l.parseResponse)return l.parseResponse(a,t);const c=a,u=c.url??c.fileUrl??c.publicUrl,h=c.fileName??c.name??e.name;if(!u)throw new Error('Upload response missing "url" / "fileUrl" / "publicUrl"');return{url:u,fileName:h,cloudFileId:typeof c.cloudFileId=="string"?c.cloudFileId:void 0,relativePath:typeof c.path=="string"?c.path:void 0,contentType:typeof c.contentType=="string"?c.contentType:void 0,byteSize:typeof c.byteSize=="number"?c.byteSize:void 0,meta:c}}}}const Uh="/tilechat/{userId}/conversations/{conversationId}/messages?pageSize={pageSize}";function bl(l){const e=l.apiBase.replace(/\/$/,""),t=l.pageSize??200,r=l.pathTemplate??Uh;return{async fetchMessages(s,n){const i=r.replace("{userId}",encodeURIComponent(n.userId)).replace("{conversationId}",encodeURIComponent(s)).replace("{appId}",encodeURIComponent(n.appId??"tilechat")).replace("{projectId}",encodeURIComponent(n.projectId??"")).replace("{pageSize}",String(t)),o=i.startsWith("http")?i:`${e}${i.startsWith("/")?i:`/${i}`}`,a={accept:"application/json","content-type":"application/json",...l.extraHeaders??{}};if(l.getToken){const p=await l.getToken();p&&(a.authorization=p)}const c=await fetch(o,{method:"GET",headers:a}),u=await c.json().catch(()=>null);if(l.parseResponse&&u)return l.parseResponse(u);const h=u;if(h&&Array.isArray(h.result))return h.result;if(!c.ok)throw new Error(`History fetch failed: ${c.status} ${c.statusText}`);return[]}}}const Bh="^[A-Z]{5}[0-9]{4}[A-Z]$",Dh="^[A-Z]{4}[0-9]{5}[A-Z]$",Fh="^[A-Z]{4}0[A-Z0-9]{6}$",yl="^[0-9]{6}$",$h=[{id:"salary-hra",title:"Salary / HRA / Allowances",icon:"💰",dataPath:"salaryDetails[]",repeatable:{maxCount:4,labelTemplate:"Employer {index}"},entryIcon:"🏢",fields:[{id:"employerDetails",type:"group",title:"Employer Details",fields:[{id:"employerName",type:"text",label:"Employer Name",required:!0},{id:"employerTan",type:"text",label:"TAN (Tax Deduction Account Number)",required:!0,pattern:Dh,maxLength:10}]},{id:"salaryComponents",type:"group",title:"Salary Components",fields:[{id:"basicSalary",type:"number",label:"Basic Salary",currency:"₹",required:!0,min:0},{id:"hraReceived",type:"number",label:"HRA Received",currency:"₹",min:0},{id:"leaveTravelAllowance",type:"number",label:"Leave Travel Allowance",currency:"₹",min:0},{id:"anyOtherAllowance",type:"number",label:"Other Allowances",currency:"₹",min:0},{id:"leaveEncashment",type:"number",label:"Leave Encashment",currency:"₹",min:0},{id:"grossSalary",type:"number",label:"Gross Salary (Total)",currency:"₹",min:0}]}],submitLabel:"Save"},{id:"business-profession",title:"Business / Profession",icon:"💼",fields:[{id:"businessGroup",type:"group",title:"Business Details",fields:[{id:"businessName",type:"text",label:"Business / Profession Name"},{id:"businessNatureOfWork",type:"text",label:"Nature of Work"},{id:"grossReceipts",type:"number",label:"Gross Receipts / Turnover",currency:"₹",min:0},{id:"netProfit",type:"number",label:"Net Profit",currency:"₹"}]}],submitLabel:"Save"},{id:"capital-gains",title:"Capital Gains",icon:"📈",fields:[{id:"equityGains",type:"group",title:"Equity & Mutual Funds",fields:[{id:"shortTermEquityGain",type:"number",label:"Short-Term Capital Gain",currency:"₹"},{id:"longTermEquityGain",type:"number",label:"Long-Term Capital Gain",currency:"₹"}]},{id:"propertyGains",type:"group",title:"Land & Building",fields:[{id:"landBuildingTermType",type:"radio",label:"Holding Period",options:[{value:"short",label:"Short-Term"},{value:"long",label:"Long-Term"}]},{id:"landBuildingPurchaseValue",type:"number",label:"Purchase Value",currency:"₹"},{id:"landBuildingSellValue",type:"number",label:"Sale Value",currency:"₹"}]}],submitLabel:"Save"},{id:"other-sources",title:"Income from Other Sources",icon:"💵",fields:[{id:"interestIncome",type:"group",title:"Interest Income",fields:[{id:"savingBankInterest",type:"number",label:"Savings Bank Interest",currency:"₹",min:0},{id:"fdInterest",type:"number",label:"Fixed Deposit Interest",currency:"₹",min:0}]},{id:"otherIncomeGroup",type:"group",title:"Other Income",fields:[{id:"dividend",type:"number",label:"Dividend Income",currency:"₹",min:0},{id:"anyOtherIncome",type:"number",label:"Any Other Income",currency:"₹",min:0}]}],submitLabel:"Save"},{id:"crypto-income",title:"Crypto Income",icon:"🪙",fields:[{id:"cryptoGroup",type:"group",title:"Virtual Digital Assets",hint:"Gains from crypto / VDAs are taxed at a flat 30%",fields:[{id:"cryptoSellPrice",type:"number",label:"Total Sale Value",currency:"₹",min:0},{id:"cryptoPurchasePrice",type:"number",label:"Total Cost of Acquisition",currency:"₹",min:0}]}],submitLabel:"Save"},{id:"agricultural-income",title:"Agricultural Income",icon:"🌾",fields:[{id:"agricultureIncome",type:"number",label:"Total Agricultural Income",currency:"₹",min:0},{id:"agricultureIncomeGt5Lakh",type:"yes-no",label:"Is agricultural income above ₹5,00,000?"}],submitLabel:"Save"},{id:"exempt-income",title:"Other Exempt Income",icon:"🧾",fields:[{id:"exemptIncome",type:"number",label:"Total Exempt Income",currency:"₹",min:0},{id:"exemptIncomeNature",type:"text",label:"Nature of Exempt Income",placeholder:"e.g. PPF interest, gratuity"}],submitLabel:"Save"},{id:"house-property",title:"House Property",icon:"🏠",dataPath:"hpDetails[]",repeatable:{maxCount:2,labelTemplate:"Property {index}"},entryIcon:"🏠",fields:[{id:"typeOfHouseProperty",type:"radio",label:"Property Type",required:!0,options:[{value:"SOP",label:"Self-Occupied"},{value:"LOP",label:"Let-Out"}]},{id:"homeLoanDetails",type:"group",title:"Home Loan Details",hint:"Interest deduction capped at ₹2,00,000",fields:[{id:"loanTakenFrom",type:"text",label:"Loan Taken From",required:!0},{id:"lenderName",type:"text",label:"Lender Name",required:!0},{id:"loanAccountNumber",type:"text",label:"Loan Account Number",required:!0},{id:"sanctionDate",type:"date",label:"Sanction Date",format:"DD/MM/YYYY",required:!0},{id:"totalLoanAmount",type:"number",label:"Total Loan Amount",currency:"₹",min:0},{id:"homeLoanInterest",type:"number",label:"Home Loan Interest",currency:"₹",min:0,max:2e5},{id:"homeLoanPrinciple",type:"number",label:"Home Loan Principal",currency:"₹",min:0}]},{id:"addressDetails",type:"group",title:"Property Address",fields:[{id:"housePropertyAddress",type:"text",label:"Address"},{id:"housePropertyPincode",type:"text",label:"Pincode",maxLength:6,pattern:yl}]},{id:"rentalDetails",type:"group",title:"Rental Income Details",showWhen:{field:"typeOfHouseProperty",equals:"LOP"},fields:[{id:"rentalIncome",type:"number",label:"Annual Rental Income",currency:"₹",required:!0,min:0},{id:"nameOfTenant",type:"text",label:"Tenant Name",required:!0},{id:"propertyTax",type:"number",label:"Municipal / Property Tax Paid",currency:"₹",min:0}]},{id:"hasCoOwnedProperty",type:"yes-no",label:"Is this property co-owned?"},{id:"coOwnerGroup",type:"group",title:"Co-Owner Details",showWhen:{field:"hasCoOwnedProperty",equals:!0},fields:[{id:"coOwnerName",type:"text",label:"Co-Owner Name",required:!0},{id:"coOwnerPan",type:"text",label:"Co-Owner PAN",required:!0,pattern:Bh,maxLength:10},{id:"coOwnerShare",type:"text",label:"Co-Owner Share (%)",placeholder:"e.g. 50",maxLength:5}]}],submitLabel:"Save"},{id:"deductions",title:"Deductions",icon:"📋",fields:[{id:"section80c",type:"group",title:"Section 80C",hint:"Maximum deduction allowed: ₹1,50,000",fields:[{id:"us80cAmount",type:"number",label:"80C Investment Amount",currency:"₹",min:0,max:15e4}]},{id:"section80d",type:"group",title:"Section 80D — Health Insurance",fields:[{id:"us80dForSelfAndFamilyAmount",type:"number",label:"Premium for Self / Spouse / Children",currency:"₹",min:0,max:25e3},{id:"us80dForParentsAmount",type:"number",label:"Premium for Parents",currency:"₹",min:0,max:5e4},{id:"hasParentOverSixty",type:"yes-no",label:"Are your parents senior citizens (60+)?"},{id:"preventiveHealthCheckUp",type:"number",label:"Preventive Health Check-up",currency:"₹",min:0},{id:"medicalExpenditure",type:"number",label:"Medical Expenditure (senior citizen)",currency:"₹",min:0}]}],submitLabel:"Save"},{id:"tax-paid-tds",title:"Tax Paid / TDS",icon:"🧮",fields:[{id:"tdsGroup",type:"group",title:"Tax Deducted at Source",fields:[{id:"tdsOnSalary",type:"number",label:"TDS on Salary",currency:"₹",min:0},{id:"tdsOtherThanSalary",type:"number",label:"TDS (other than salary)",currency:"₹",min:0}]},{id:"advanceTaxGroup",type:"group",title:"Advance / Self-Assessment Tax",fields:[{id:"selfAssessmentOrAdvanceTax",type:"number",label:"Advance / Self-Assessment Tax Paid",currency:"₹",min:0}]}],submitLabel:"Save"},{id:"bank-details",title:"Personal / Bank Details",icon:"🏦",fields:[{id:"bankGroup",type:"group",title:"Bank Account (for refund)",fields:[{id:"bankAccountNumber",type:"text",label:"Bank Account Number",required:!0},{id:"bankIfscCode",type:"text",label:"IFSC Code",required:!0,pattern:Fh,maxLength:11}]},{id:"immovableGroup",type:"group",title:"Immovable Assets",hint:"Required if total income exceeds ₹50,00,000",fields:[{id:"immovableAssetDescription",type:"text",label:"Description"},{id:"immovableAssetFlatNo",type:"text",label:"Flat / House No."},{id:"immovableAssetArea",type:"text",label:"Area / Locality"},{id:"immovableAssetPincode",type:"text",label:"Pincode",maxLength:6,pattern:yl},{id:"immovableAssetCost",type:"number",label:"Cost of Asset",currency:"₹",min:0}]}],submitLabel:"Save"},{id:"have-a-question",title:"I only have a question",icon:"❓",fields:[{id:"question",type:"textarea",label:"What would you like to ask?",placeholder:"Type your question for the TaxBuddy expert…",required:!0,rows:5,maxLength:1e3}],submitLabel:"Send Question"}];function qh(l,e){const t=l||{},r={userId:zh(e.userId),assessmentYear:e.assessmentYear,isRevised:e.isRevised||"N"};r.us80cAmount=Pe(t.us80cAmount),r.us80dForSelfAndFamilyAmount=Pe(t.us80dForSelfAndFamilyAmount),r.us80dForParentsAmount=Pe(t.us80dForParentsAmount),r.hasParentOverSixty=ho(t.hasParentOverSixty),r.preventiveHealthCheckUp=Pe(t.preventiveHealthCheckUp),r.medicalExpenditure=Pe(t.medicalExpenditure),r.savingBankInterest=Pe(t.savingBankInterest),r.fdInterest=Pe(t.fdInterest),r.dividend=Pe(t.dividend),r.anyOtherIncome=Pe(t.anyOtherIncome),r.cryptoSellValue=Pe(t.cryptoSellPrice),r.cryptoPurchaseAmount=Pe(t.cryptoPurchasePrice),r.vdaPurchaseCost=Pe(t.cryptoPurchasePrice),r.businessName=Re(t.businessName),r.businessAnnualTurnOver=Pe(t.grossReceipts),r.businessNetProfit=Pe(t.netProfit),r.agricultureDetails={income:Pe(t.agricultureIncome)},r.exemptIncomeAmount=Pe(t.exemptIncome),r.exemptIncomeNature=Re(t.exemptIncomeNature),Pe(t.exemptIncome)!==void 0&&(r.exemptIncomes=[{name:Re(t.exemptIncomeNature)??"Exempt income",value:String(Pe(t.exemptIncome))}]),r.bankAccountNumber=Re(t.bankAccountNumber),r.bankIfscCode=Re(t.bankIfscCode),(Re(t.bankAccountNumber)||Re(t.bankIfscCode))&&(r.bankDetails=[{bankAccountNumber:Re(t.bankAccountNumber),bankIfscCode:Re(t.bankIfscCode)}]);const s={description:Re(t.immovableAssetDescription),flatNo:Re(t.immovableAssetFlatNo),area:Re(t.immovableAssetArea),pinCode:Re(t.immovableAssetPincode),amount:Pe(t.immovableAssetCost)};Object.values(s).some(o=>o!==void 0)&&(r.immovableAsset=[s]);const n=fo(t.hpDetails,Hh);n.length&&(r.hpDetails=n);const i=fo(t.salaryDetails,Wh);if(i.length){r.salaryIncome=i;const o=fo(t.salaryDetails,c=>({grossSalary:Pe(c.grossSalary),employerName:Re(c.employerName)}));o.length&&(r.salary=o);const a=vl(t.salaryDetails)[0]??{};r.hraAmount=Pe(a.hraReceived),r.leaveTravelAllowanceAmount=Pe(a.leaveTravelAllowance),r.leaveEncashmentAllowanceAmount=Pe(a.leaveEncashment),r.anyOtherAllowanceAmount=Pe(a.anyOtherAllowance),r.salaryIncomeFlag=!0}return $r(r)}function Hh(l){const e={loanType:"HOME_LOAN",loanTakenFrom:Re(l.loanTakenFrom),bankOrInstituteName:Re(l.lenderName),loanAccountNo:Re(l.loanAccountNumber),loanSanctionDate:Vh(l.sanctionDate),totalLoanAmount:Pe(l.totalLoanAmount),interest:Pe(l.homeLoanInterest)},t=Object.entries(e).some(([r,s])=>r!=="loanType"&&s!==void 0);return{typeOfHouseProperty:Re(l.typeOfHouseProperty),hasRentalIncome:l.typeOfHouseProperty==="LOP"?!0:ho(l.hasRentalIncome),homeLoanInterest:Pe(l.homeLoanInterest),homeLoanPrinciple:Pe(l.homeLoanPrinciple),housePropertyAddress:Re(l.housePropertyAddress),housePropertyPincode:Re(l.housePropertyPincode),rentalIncome:Pe(l.rentalIncome),nameOfTenant:Re(l.nameOfTenant),propertyTax:Pe(l.propertyTax),hasCoOwnedProperty:ho(l.hasCoOwnedProperty),coOwnerName:Re(l.coOwnerName),coOwnerPan:Re(l.coOwnerPan),coOwnerShare:Re(l.coOwnerShare),loanDetails:t?[e]:void 0}}function Wh(l){return{grossSalaryIncome:Pe(l.grossSalary),salary:Pe(l.basicSalary),employer:{employerName:Re(l.employerName),employerTan:Re(l.employerTan)},allowance:{hraAmount:Pe(l.hraReceived),leaveTravelAllowanceAmount:Pe(l.leaveTravelAllowance),leaveEncashmentAllowanceAmount:Pe(l.leaveEncashment),anyOtherAllowanceAmount:Pe(l.anyOtherAllowance)}}}function zh(l){if(l===void 0||l==="")return;const e=Number(l);return Number.isFinite(e)&&String(e)===String(l)?e:l}function Pe(l){if(l==null||l==="")return;const e=typeof l=="number"?l:Number(l);return Number.isFinite(e)?e:void 0}function Re(l){if(l==null)return;const e=String(l).trim();return e===""?void 0:e}function ho(l){return l===!0||l===!1?l:void 0}function Vh(l){const e=Re(l);if(e)return e.includes("T")?e:/^\d{4}-\d{2}-\d{2}$/.test(e)?`${e}T00:00:00Z`:e}function vl(l){return Array.isArray(l)?l.filter(e=>e&&typeof e=="object"):[]}function fo(l,e){return vl(l).map(t=>$r(e(t))).filter(t=>t!==void 0)}function $r(l){if(Array.isArray(l)){const e=l.map($r).filter(t=>t!==void 0);return e.length?e:void 0}if(l&&typeof l=="object"){const e={};for(const[t,r]of Object.entries(l)){const s=$r(r);s!==void 0&&(e[t]=s)}return Object.keys(e).length?e:void 0}return l}function wl(){if(typeof window>"u")return null;const l=window,e=l.__aikaara_runtime__;if(!e||typeof e.getChatJwt!="function")return console.warn("[smart-edit] API disabled: window.__aikaara_runtime__.getChatJwt is missing — the chat was not mounted via the SDK mountFromSlug path."),null;const t=e.getChatJwt,r=l.__aikaara_descriptor__??{},s=Qh(r.api?.baseUrl)??Jh(r.auth?.endpoint)??"",n=r.itr?.automationSubmitUrl||Gh(e.configBase,e.slug);return!n&&!s?(console.warn(`[smart-edit] API disabled: no submit URL could be derived (configBase=${e.configBase??"undefined"}, slug=${e.slug??"undefined"}).`),null):(console.info("[smart-edit] API config — submitUrl:",n||"(none)","· baseUrl:",s||"(none)"),{baseUrl:s,getToken:()=>t(),headers:Xh(r.auth?.headers),assessmentYear:r.itr?.assessmentYear||ed(),isRevised:"N",userId:Zh(e.identity),submitUrl:n})}function Gh(l,e){return!l||!e?void 0:`${l.replace(/\/+$/,"")}/api/v1/projects/by-slug/${encodeURIComponent(e)}/itr/automation-data`}async function Kh(l){const e=await l.getToken(),t=l.userId||_l(e,"sub");if(!t)throw new Error("[smart-edit] could not resolve userId for GET /itr/automation/eligible");const r=new URLSearchParams({userId:t,assessmentYear:l.assessmentYear,isRevised:l.isRevised}),s=await fetch(`${l.baseUrl}/itr/automation/eligible?${r}`,{method:"GET",headers:{accept:"application/json",authorization:`Bearer ${e}`,...l.headers}});if(!s.ok){const n=await s.text().catch(()=>"");throw new Error(`[smart-edit] GET /itr/automation/eligible → ${s.status} ${n.slice(0,200)}`)}return kl(await s.json().catch(()=>({})))}async function Yh(l,e){const t=await l.getToken(),r=l.userId||_l(t,"sub"),s=qh(e,{userId:r,assessmentYear:l.assessmentYear,isRevised:l.isRevised}),n=l.submitUrl||`${l.baseUrl}/itr/v1/lanretni/automation/data`,i={accept:"application/json","content-type":"application/json",authorization:`Bearer ${t}`,...l.headers};l.txbdyApiKey&&(i["txbdy-api-key"]=l.txbdyApiKey),console.info("[smart-edit] PUT",n,"— DTO keys:",Object.keys(s).join(", "));const o=await fetch(n,{method:"PUT",headers:i,body:JSON.stringify(s)});if(!o.ok){const a=await o.text().catch(()=>"");throw new Error(`[smart-edit] PUT ${n} → ${o.status} ${a.slice(0,200)}`)}return kl(await o.json().catch(()=>({})))}function Qh(l){if(!l)return null;let e=l.trim().replace(/\/+$/,"");return e=e.replace(/\/itr$/i,""),e||null}function Jh(l){if(!l)return null;try{return new URL(l).origin}catch{return null}}function Xh(l){const e={};if(!l)return e;const t=/^(authorization|content-type|accept)$/i;for(const[r,s]of Object.entries(l))!t.test(r)&&typeof s=="string"&&(e[r]=s);return e}function Zh(l){if(!l)return;const e=l.userId??l.id??l.ext_uid??l.extUid;return e==null||e===""?void 0:String(e)}function _l(l,e){try{const t=l.split(".")[1];if(!t)return"";const s=JSON.parse(atob(t.replace(/-/g,"+").replace(/_/g,"/")))[e];return s==null?"":String(s)}catch{return""}}function kl(l){if(l&&typeof l=="object"){const e=l;return e.data&&typeof e.data=="object"?e.data:e}return{}}function ed(){const l=new Date,e=l.getMonth()>=3?l.getFullYear():l.getFullYear()-1;return`${e}-${e+1}`}class td{client;panel;bubble;header;messageList;input;errorBanner;isOpen=!1;isEmbed=!1;smartEditModal=null;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.header.addEventListener("aikaara-chat-action",(e=>{this.handleChatAction(e.detail)})),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??{},s=t.attributes?.action??{},n={...t.attributes,action:{...r,...s}};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}async handleChatAction(e){if(e.id==="edit-itr"){this.openSmartEdit();return}console.info("[chat-action]",e.id,e.label)}async openSmartEdit(){const e=this.ensureSmartEditModal();e.open({schemas:$h,data:{}});const t=wl();if(!(!t||!t.baseUrl))try{const r=await Kh(t);e.setData(r)}catch(r){console.warn("[smart-edit] fetch failed",r),this.errorBanner.show("Could not load your ITR details — starting from a blank form.",4e3)}}ensureSmartEditModal(){if(this.smartEditModal)return this.smartEditModal;const e=document.createElement("aikaara-smart-edit-modal");return document.body.appendChild(e),e.addEventListener("smart-edit-recalculate",(t=>{const r=t.detail;this.handleSmartEditSave(r.record)})),this.smartEditModal=e,e}async handleSmartEditSave(e){console.info("[smart-edit] Save & Recalculate — persisting record");const t=wl();if(!t){console.warn("[smart-edit] save skipped — no API config (see the warning above for why)");return}try{await Yh(t,e)}catch(r){console.warn("[smart-edit] save failed",r),this.errorBanner.show("Failed to save your ITR details. Please try again.",4e3)}}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 xl 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||bc,primaryColor:this.getAttribute("primary-color")||this._config.primaryColor||xo,position:this.getAttribute("position")||this._config.position||gc,width:Number(this.getAttribute("width"))||this._config.width||dc,height:Number(this.getAttribute("height"))||this._config.height||fc,fontFamily:this._config.fontFamily||mc,borderRadius:this._config.borderRadius??pc,placeholder:this.getAttribute("placeholder")||this._config.placeholder||So,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||yc,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,s){if(typeof document>"u")return;const n=document.documentElement,i=(o,a)=>{a!==void 0&&a!==""&&n.style.setProperty(`--aikaara-${o}`,a)};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??s),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=s=>typeof s=="number"?`${s}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(([,s])=>s!==void 0&&s!=="").map(([s,n])=>`--aikaara-${s}: ${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;
@@ -474,7 +474,7 @@ In order to be iterable, non-array objects must have a [Symbol.iterator]() metho
474
474
  }
475
475
  </style>
476
476
  <div class="message-list"></div>
477
- `,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">${$t(Ft(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 s=e.length-1;s>=0;s--)if(e[s].role==="user"){r=s;break}for(let s=0;s<e.length;s++){const n=e[s];if(n.role==="user"){const i=n.metadata?.attributes?.action;i?.message_id&&t.add(i.message_id)}n.role!=="user"&&n.template?.contentType&&s<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=$t(Ft(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))return;if(e.role==="system"){if(!e.content||!e.content.trim())return;const c=document.createElement("div");c.classList.add("message-wrap","system"),c.dataset.messageId=e.id,e.externalId&&(c.dataset.externalId=e.externalId);const u=document.createElement("aikaara-system-pill");u.setAttribute("text",e.content),c.appendChild(u),this.container.appendChild(c);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 s=document.createElement("div");s.classList.add("bubble",e.role);const i=!!e.template?.contentType&&e.role!=="user";e.role==="user"?!!e.attachments?.length&&!e.content?.trim()?s.classList.add("attachment-only"):s.textContent=e.content:i?e.content&&(s.innerHTML=$t(Ft(e.content))):(s.innerHTML=$t(Ft(e.content||"")),e.status==="streaming"&&s.classList.add("streaming-cursor"));let o=null;if(e.template?.contentType){const c=document.createElement("aikaara-template-renderer");c.setAttribute("content-type",e.template.contentType),e.template.templateId&&c.setAttribute("template-id",e.template.templateId);const u=e.externalId??e.id;u&&c.setAttribute("message-id",u),c.setPayload(e.template.payload),t&&(c.dataset.consumed="true"),this.templateLayout==="outside"?(c.classList.add("template-outside"),o=c):s.appendChild(c)}const a=e.template?.templateId==="7";if(e.attachments?.length&&!a){const c=document.createElement("div");c.classList.add("attachments");for(const u of e.attachments){const h=document.createElement("aikaara-template-renderer");h.setAttribute("content-type","300"),h.setAttribute("template-id","7");const p={elements:[{description:u.fileName,action:{url:u.fileUrl,type:"link",isDeepLink:!0}}]};h.setPayload(p,""),c.appendChild(h)}s.appendChild(c)}if(r.appendChild(s),o&&r.appendChild(o),this.showTimestamps&&(e.createdAt||e.role==="user"&&e.status)){const c=document.createElement("div");if(c.classList.add("timestamp"),this.showTimestamps&&e.createdAt&&(c.textContent=this.formatTime(e.createdAt)),e.role==="user"&&e.status){const u=document.createElement("span");u.classList.add("status-tick"),e.status==="read"&&u.classList.add("read"),u.textContent={sending:" ○",sent:" ✓",delivered:" ✓✓",read:" ✓✓"}[e.status]??"",c.appendChild(u)}r.appendChild(c)}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(){const e=()=>{this.scrollTop=this.scrollHeight,this.container.scrollTop=this.container.scrollHeight};requestAnimationFrame(()=>{e(),requestAnimationFrame(e)}),setTimeout(e,150)}formatTime(e){try{const t=new Date(e),r=t.toLocaleDateString(void 0,{month:"short",day:"2-digit"});switch(this.timestampFormat){case"datetime":return`${r}, ${t.toLocaleTimeString(void 0,{hour:"2-digit",minute:"2-digit"})}`;case"datetime-seconds":return`${r}, ${t.toLocaleTimeString(void 0,{hour:"2-digit",minute:"2-digit",second:"2-digit"})}`;case"datetime-24":return`${r}, ${t.toLocaleTimeString(void 0,{hour:"2-digit",minute:"2-digit",hour12:!1})}`;case"date":return r;case"relative":return ud(t);case"time-24":return t.toLocaleTimeString(void 0,{hour:"2-digit",minute:"2-digit",hour12:!1});case"time-seconds":return t.toLocaleTimeString(void 0,{hour:"2-digit",minute:"2-digit",second:"2-digit"});case"none":return"";default:return t.toLocaleTimeString(void 0,{hour:"2-digit",minute:"2-digit"})}}catch{return""}}async handleLinkClick(e,t){const r=this.linkHandlers.find(b=>hd(e,b.match)),s=r?.target??"iframe";if(s==="tab"){window.open(e,"_blank","noopener,noreferrer");return}const n=this.getOrCreateModal(),i=r?.title??t??"Link";if(s==="iframe"||!r?.fetch||!r.render){requestAnimationFrame(()=>n.show?.(e,i));return}const o=dd(e),a=Tl(r.fetch.url,o),c={accept:"application/json",...r.fetch.headers??{}},u=r.fetch.authHeader??"session";if(u!=="none"&&this.getLinkBearer){const b=await this.getLinkBearer(u);b&&(c.authorization=`Bearer ${b}`)}const h={method:r.fetch.method??"GET",headers:c};r.fetch.body&&(c["content-type"]="application/json",h.body=JSON.stringify(po(r.fetch.body,o)));let p=null;try{const b=await fetch(a,h);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 hd(l,e){const t=e.replace(/[.+^${}()|[\]\\]/g,"\\$&");return new RegExp("^"+t.replace(/\*/g,".*").replace(/\?/g,".")+"$","i").test(l)}function dd(l){try{const e=new URL(l),t={};return e.searchParams.forEach((r,s)=>{t[s]=r}),t}catch{return{}}}function Tl(l,e){return l.replace(/\{(\w+)\}/g,(t,r)=>e[r]??"")}function po(l,e){if(typeof l=="string")return Tl(l,e);if(Array.isArray(l))return l.map(t=>po(t,e));if(l&&typeof l=="object"){const t={};for(const[r,s]of Object.entries(l))t[r]=po(s,e);return t}return l}class Cl 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")||"",s=this.getAttribute("status")||"",n=this.getAttribute("content-type")||"",i=this.getAttribute("template-id")||"",o=this.getAttribute("inner-message")||"",a=e==="user"?document.createTextNode(t).textContent||"":$t(Ft(t)),c=e==="user"&&s,u=s==="sending"?"○":s==="sent"?"✓":s==="delivered"||s==="read"?"✓✓":"";this.shadow.innerHTML=`
477
+ `,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">${$t(Ft(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 s=e.length-1;s>=0;s--)if(e[s].role==="user"){r=s;break}for(let s=0;s<e.length;s++){const n=e[s];if(n.role==="user"){const i=n.metadata?.attributes?.action;i?.message_id&&t.add(i.message_id)}n.role!=="user"&&n.template?.contentType&&s<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=$t(Ft(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))return;if(e.role==="system"){if(!e.content||!e.content.trim())return;const c=document.createElement("div");c.classList.add("message-wrap","system"),c.dataset.messageId=e.id,e.externalId&&(c.dataset.externalId=e.externalId);const u=document.createElement("aikaara-system-pill");u.setAttribute("text",e.content),c.appendChild(u),this.container.appendChild(c);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 s=document.createElement("div");s.classList.add("bubble",e.role);const i=!!e.template?.contentType&&e.role!=="user";e.role==="user"?!!e.attachments?.length&&!e.content?.trim()?s.classList.add("attachment-only"):s.textContent=e.content:i?e.content&&(s.innerHTML=$t(Ft(e.content))):(s.innerHTML=$t(Ft(e.content||"")),e.status==="streaming"&&s.classList.add("streaming-cursor"));let o=null;if(e.template?.contentType){const c=document.createElement("aikaara-template-renderer");c.setAttribute("content-type",e.template.contentType),e.template.templateId&&c.setAttribute("template-id",e.template.templateId);const u=e.externalId??e.id;u&&c.setAttribute("message-id",u),c.setPayload(e.template.payload),t&&(c.dataset.consumed="true"),this.templateLayout==="outside"?(c.classList.add("template-outside"),o=c):s.appendChild(c)}const a=e.template?.templateId==="7";if(e.attachments?.length&&!a){const c=document.createElement("div");c.classList.add("attachments");for(const u of e.attachments){const h=document.createElement("aikaara-template-renderer");h.setAttribute("content-type","300"),h.setAttribute("template-id","7");const p={elements:[{description:u.fileName,action:{url:u.fileUrl,type:"link",isDeepLink:!0}}]};h.setPayload(p,""),c.appendChild(h)}s.appendChild(c)}if(r.appendChild(s),o&&r.appendChild(o),this.showTimestamps&&(e.createdAt||e.role==="user"&&e.status)){const c=document.createElement("div");if(c.classList.add("timestamp"),this.showTimestamps&&e.createdAt&&(c.textContent=this.formatTime(e.createdAt)),e.role==="user"&&e.status){const u=document.createElement("span");u.classList.add("status-tick"),e.status==="read"&&u.classList.add("read"),u.textContent={sending:" ○",sent:" ✓",delivered:" ✓✓",read:" ✓✓"}[e.status]??"",c.appendChild(u)}r.appendChild(c)}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(){const e=()=>{this.scrollTop=this.scrollHeight,this.container.scrollTop=this.container.scrollHeight};requestAnimationFrame(()=>{e(),requestAnimationFrame(e)}),setTimeout(e,150)}formatTime(e){try{const t=new Date(e),r=t.toLocaleDateString(void 0,{month:"short",day:"2-digit"});switch(this.timestampFormat){case"datetime":return`${r}, ${t.toLocaleTimeString(void 0,{hour:"2-digit",minute:"2-digit"})}`;case"datetime-seconds":return`${r}, ${t.toLocaleTimeString(void 0,{hour:"2-digit",minute:"2-digit",second:"2-digit"})}`;case"datetime-24":return`${r}, ${t.toLocaleTimeString(void 0,{hour:"2-digit",minute:"2-digit",hour12:!1})}`;case"date":return r;case"relative":return ud(t);case"time-24":return t.toLocaleTimeString(void 0,{hour:"2-digit",minute:"2-digit",hour12:!1});case"time-seconds":return t.toLocaleTimeString(void 0,{hour:"2-digit",minute:"2-digit",second:"2-digit"});case"none":return"";default:return t.toLocaleTimeString(void 0,{hour:"2-digit",minute:"2-digit"})}}catch{return""}}async handleLinkClick(e,t){const r=this.linkHandlers.find(y=>hd(e,y.match)),s=r?.target??"iframe";if(s==="tab"){window.open(e,"_blank","noopener,noreferrer");return}const n=this.getOrCreateModal(),i=r?.title??t??"Link";if(s==="iframe"||!r?.fetch||!r.render){requestAnimationFrame(()=>n.show?.(e,i));return}const o=dd(e),a=Tl(r.fetch.url,o),c={accept:"application/json",...r.fetch.headers??{}},u=r.fetch.authHeader??"session";if(u!=="none"&&this.getLinkBearer){const y=await this.getLinkBearer(u);y&&(c.authorization=`Bearer ${y}`)}const h={method:r.fetch.method??"GET",headers:c};r.fetch.body&&(c["content-type"]="application/json",h.body=JSON.stringify(po(r.fetch.body,o)));let p=null;try{const y=await fetch(a,h);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 hd(l,e){const t=e.replace(/[.+^${}()|[\]\\]/g,"\\$&");return new RegExp("^"+t.replace(/\*/g,".*").replace(/\?/g,".")+"$","i").test(l)}function dd(l){try{const e=new URL(l),t={};return e.searchParams.forEach((r,s)=>{t[s]=r}),t}catch{return{}}}function Tl(l,e){return l.replace(/\{(\w+)\}/g,(t,r)=>e[r]??"")}function po(l,e){if(typeof l=="string")return Tl(l,e);if(Array.isArray(l))return l.map(t=>po(t,e));if(l&&typeof l=="object"){const t={};for(const[r,s]of Object.entries(l))t[r]=po(s,e);return t}return l}class Cl 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")||"",s=this.getAttribute("status")||"",n=this.getAttribute("content-type")||"",i=this.getAttribute("template-id")||"",o=this.getAttribute("inner-message")||"",a=e==="user"?document.createTextNode(t).textContent||"":$t(Ft(t)),c=e==="user"&&s,u=s==="sending"?"○":s==="sent"?"✓":s==="delivered"||s==="read"?"✓✓":"";this.shadow.innerHTML=`
478
478
  <style>
479
479
  :host { display: flex; flex-direction: column; }
480
480
  :host([role="user"]) { align-items: flex-end; }
@@ -1244,7 +1244,7 @@ In order to be iterable, non-array objects must have a [Symbol.iterator]() metho
1244
1244
  ${Qe(s)}
1245
1245
  </span>
1246
1246
  ${n}
1247
- </div>`:""}<div class="entry-body">${i}</div></section>`}renderField(e,t,r){if(!this.fieldVisible(e,t))return"";if(e.type==="group"){const h=e,p=h.fields.map(b=>this.renderField(b,t,r)).join("");return`
1247
+ </div>`:""}<div class="entry-body">${i}</div></section>`}renderField(e,t,r){if(!this.fieldVisible(e,t))return"";if(e.type==="group"){const h=e,p=h.fields.map(y=>this.renderField(y,t,r)).join("");return`
1248
1248
  <fieldset class="group">
1249
1249
  ${h.title?`<legend class="group-title">${Qe(h.title)}</legend>`:""}
1250
1250
  ${h.hint?`<div class="group-hint">${Qe(h.hint)}</div>`:""}
@@ -1458,7 +1458,7 @@ In order to be iterable, non-array objects must have a [Symbol.iterator]() metho
1458
1458
  }
1459
1459
  .save-btn:hover { filter: brightness(1.07); }
1460
1460
  .save-btn:active { filter: brightness(0.95); }
1461
- `}}function Ot(l){return l.replace(/&/g,"&amp;").replace(/"/g,"&quot;").replace(/</g,"&lt;").replace(/>/g,"&gt;")}function Qe(l){return l.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;")}function yo(){const l=[["aikaara-chat-widget",xl],["aikaara-chat-bubble",Sl],["aikaara-chat-header",El],["aikaara-message-list",Il],["aikaara-message-bubble",Cl],["aikaara-chat-input",Pl],["aikaara-typing-indicator",Ml],["aikaara-streaming-message",Rl],["aikaara-error-banner",Ll],["aikaara-template-renderer",gd],["aikaara-system-pill",vd],["aikaara-option-list",wd],["aikaara-submit-action",_d],["aikaara-modal-action",xd],["aikaara-chat",Sd],["aikaara-link-modal",Ed],["aikaara-compare-plans",Td],["aikaara-smart-edit-modal",Cd],["aikaara-schema-form",Md]];for(const[e,t]of l)customElements.get(e)||customElements.define(e,t)}yo();function Hr(l,e,t=""){if(!e)return t;const r=e.split(".");let s=l;for(const n of r)if(s&&typeof s=="object"&&n in s)s=s[n];else return t;return typeof s=="string"?s:t}function Fl(l){try{const e=l.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 Xt(l){return typeof l=="function"?await l():l}class $l{constructor(e,t){this.descriptor=e,this.sessionToken=t}cache=null;inflight=null;reset(){this.cache=null,this.inflight=null}prime(e,t={}){if(!e)return;const r=Fl(e)||Date.now()+3600*1e3;this.cache={token:e,requestId:t.requestId??this.cache?.requestId??"",fullName:t.fullName??this.cache?.fullName??"",userId:t.userId??this.cache?.userId??"",expiresAt:r}}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 Xt(this.sessionToken),t=this.descriptor.authHeader??"Authorization",r=this.descriptor.authHeaderTemplate??"Bearer {token}",s={accept:"application/json",...this.descriptor.headers??{},[t]:r.replace("{token}",e)},n=this.descriptor.method??"POST",i={method:n,headers:s};n==="POST"&&(s["content-type"]="application/json",i.body=JSON.stringify(this.descriptor.body??{}));const o=await fetch(this.descriptor.endpoint,i);if(!o.ok){const k=await o.text().catch(()=>"");throw new Error(`Session auth failed: ${o.status} ${k.slice(0,200)}`)}const a=await o.json().catch(()=>({})),c=Hr(a,this.descriptor.tokenPath??"data.token"),u=this.descriptor.tokenStripPrefix,h=u?c.replace(new RegExp(`^${u}`,"i"),"").trim():c;if(!h)throw new Error("Session auth response missing token");const p=Hr(a,this.descriptor.requestIdPath??"data.requestId"),b=this.cache?.requestId||p||"",f=Hr(a,this.descriptor.fullNamePath??"data.fullName"),g=Hr(a,this.descriptor.userPath??"data.userId"),y=Fl(h)||Date.now()+3600*1e3;return this.cache={token:h,requestId:b,fullName:f,userId:g,expiresAt:y},this.cache}}async function ql(l){const e={};for(const t of l.spec){const r=await Rd(t,l.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 Rd(l,e){const t=l.key??l.name;switch(l.source){case"cookie":return Ld(t);case"localStorage":return Wr(()=>window.localStorage.getItem(t)??void 0);case"sessionStorage":return Wr(()=>window.sessionStorage.getItem(t)??void 0);case"url_param":return Wr(()=>new URL(window.location.href).searchParams.get(t)??void 0);case"header_meta":return Wr(()=>document.querySelector(`meta[name="${jd(t)}"]`)?.content??void 0);case"callback":{const r=e?.[l.name];if(!r)return;const s=await r();return typeof s=="string"?s:void 0}default:return}}function Ld(l){if(typeof document>"u")return;const e=encodeURIComponent(l),t=document.cookie?document.cookie.split("; "):[];for(const r of t){const s=r.indexOf("=");if(s===-1)continue;const n=r.slice(0,s);if(n===l||n===e)try{return decodeURIComponent(r.slice(s+1))}catch{return r.slice(s+1)}}}function Wr(l){try{return l()}catch{return}}function jd(l){return l.replace(/["\\]/g,"\\$&")}const Nd=1800;class Hl{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 ql({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 s=this.opts.descriptor.exchangeEndpoint||this.opts.exchangeUrl;if(!s)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(s,{method:"POST",headers:r,body:t});if(!n.ok){const h=await n.text().catch(()=>"");throw new Error(`SSO exchange failed: ${n.status} ${h.slice(0,240)}`)}const o=(await n.json().catch(()=>({}))).user??{},a=String(o.ext_uid??o.extUid??""),c=String(o.token??o.user_token??o.userToken??"");if(!a)throw new Error("SSO exchange response missing user.ext_uid");if(!c)throw new Error("SSO exchange response missing user.token");const u={id:o.id,extUid:a,userToken:c,email:typeof o.email=="string"?o.email:void 0,displayName:typeof o.display_name=="string"?o.display_name:typeof o.displayName=="string"?o.displayName:void 0,properties:o.properties&&typeof o.properties=="object"?o.properties:void 0,expiresAt:this.computeExpiry()};return this.cache=u,this.persistCache(u),u}computeExpiry(){const e=this.opts.descriptor.cacheTtlSec??Nd;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 Ud=3e4,Bd=2e3,Dd=100;async function Wl(l){const{descriptor:e}=l,t=e.tokenSourceConfig??{};switch(e.tokenSource){case"init":{if(!l.initToken)throw new Ke("init","No init token supplied to Aikaara.init({token})");return{token:l.initToken,source:"init"}}case"query":{const r=typeof t.key=="string"&&t.key?t.key:"token",s=Fd(r);if(!s)throw new Ke("query",`?${r}= not present`);return{token:s,source:"query"}}case"hash":{const r=typeof t.key=="string"&&t.key?t.key:"token",s=$d(r);if(!s)throw new Ke("hash",`#${r}= not present`);return{token:s,source:"hash"}}case"postmsg":{const r=typeof t.type=="string"?t.type:"",s=typeof t.key=="string"&&t.key?t.key:"token",n=Vd(typeof t.origins=="string"?t.origins:""),i=typeof t.timeoutMs=="number"&&t.timeoutMs>0?t.timeoutMs:Ud;return{token:await zd({type:r,key:s,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 s=qd(r);if(!s)throw new Ke("cookie",`cookie "${r}" not set`);return{token:s,source:"cookie"}}case"storage":{const r=t.store==="session"?"session":"local",s=typeof t.key=="string"&&t.key?t.key:"",n=typeof t.path=="string"?t.path:"";if(!s)throw new Ke("storage","storage.key not configured");const i=Hd(r,s,n);if(!i)throw new Ke("storage",`${r}Storage["${s}"] 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 s=typeof t.timeoutMs=="number"&&t.timeoutMs>0?t.timeoutMs:Bd,n=typeof t.intervalMs=="number"&&t.intervalMs>0?t.intervalMs:Dd,i=await Wd(r,s,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 zl{constructor(e){this.opts=e}cached=null;get descriptor(){return this.opts.descriptor}async get(){if(this.cached)return this.cached;const e=await Wl(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 Fd(l){if(!(typeof window>"u"))try{return new URL(window.location.href).searchParams.get(l)??void 0}catch{return}}function $d(l){if(!(typeof window>"u"))try{const e=window.location.hash.replace(/^#/,"");return new URLSearchParams(e).get(l)??void 0}catch{return}}function qd(l){if(typeof document>"u")return;const e=encodeURIComponent(l),t=document.cookie?document.cookie.split("; "):[];for(const r of t){const s=r.indexOf("=");if(s===-1)continue;const n=r.slice(0,s);if(n===l||n===e)try{return decodeURIComponent(r.slice(s+1))}catch{return r.slice(s+1)}}}function Hd(l,e,t){if(!(typeof window>"u"))try{const s=(l==="session"?window.sessionStorage:window.localStorage).getItem(e);if(s==null)return;if(!t)return s;let n;try{n=JSON.parse(s)}catch{return s}const i=Vl(n,t);return typeof i=="string"?i:void 0}catch{return}}async function Wd(l,e,t){if(typeof window>"u")return;const r=Date.now()+e;for(;Date.now()<r;){const s=Vl(window,l);if(typeof s=="string"&&s.length>0)return s;if(typeof s=="function")try{const n=s();if(typeof n=="string"&&n.length>0)return n}catch{}await new Promise(n=>setTimeout(n,t))}}function zd(l){return new Promise((e,t)=>{if(typeof window>"u"){t(new Ke("postmsg","no window"));return}const r=()=>{window.removeEventListener("message",n),clearTimeout(s)},s=setTimeout(()=>{r(),t(new Ke("postmsg",`timeout after ${l.timeoutMs}ms`))},l.timeoutMs),n=i=>{if(l.origins.length>0&&!l.origins.includes(i.origin))return;const o=i.data;if(!o||typeof o!="object")return;const a=o;if(l.type&&a.type!==l.type)return;const c=a[l.key];typeof c=="string"&&c.length>0&&(r(),e(c))};window.addEventListener("message",n)})}function Vd(l){return l?l.split(/[,\s]+/).map(e=>e.trim()).filter(Boolean):[]}function Vl(l,e){if(!e)return l;const t=e.split(".").filter(Boolean);let r=l;for(const s of t)if(r&&typeof r=="object"&&s in r)r=r[s];else return;return r}function Gd(){const l=typeof crypto<"u"?crypto:null;if(l?.randomUUID)return l.randomUUID();if(l?.getRandomValues){const e=new Uint8Array(16);l.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 Kd="aikaara_chat:requestId";function vo(l,e){return`${Kd}:${l}:${e}`}function Gl(l,e){try{return localStorage.getItem(vo(l,e))}catch{return null}}function Yd(l,e,t){try{localStorage.setItem(vo(l,e),t)}catch{}}function Qd(l,e){try{localStorage.removeItem(vo(l,e))}catch{}}async function Jd(l,e){console.log("[aikaara-chat-sdk] preflight running",l.length,"steps");const t={userId:e.userId,projectId:e.projectId,slug:e.slug};if(e.identity)for(const[a,c]of Object.entries(e.identity))typeof c=="string"&&(t[a]=c);const r=a=>a.replace(/\{(\w+)\}/g,(c,u)=>u in t?t[u]:""),s=a=>{if(typeof a=="string")return r(a);if(Array.isArray(a))return a.map(s);if(a&&typeof a=="object"){const c={};for(const[u,h]of Object.entries(a))c[u]=s(h);return c}return a},n=await Xt(e.sessionToken),i={},o=[800,1500,3e3,5e3,8e3];for(let a=0;a<l.length;a++){const c=l[a],u=r(c.url),h=c.method??(c.body?"POST":"GET"),p={accept:"application/json",...c.headers??{}};if((c.authHeader??"session")==="session"){const m=c.authHeaderTemplate??"Bearer {token}";p.authorization=m.replace("{token}",n)}const b={method:h,headers:p};c.body&&(p["content-type"]="application/json",b.body=JSON.stringify(s(c.body)));let f=0,g="",y=0,k=null;for(;;)try{const m=await fetch(u,b);if(m.ok){k=m;break}if(f=m.status,g=await m.text().catch(()=>""),y<o.length&&Xd(f,g)){const S=o[y++];console.warn(`[aikaara-chat-sdk] preflight #${a} ${h} ${u} → ${f} (transient). Retry #${y} in ${S}ms.`),await new Promise(v=>setTimeout(v,S));continue}const w=`Preflight #${a} ${h} ${u} → ${f} ${g.slice(0,200)}`;if(c.soft){console.warn("[aikaara-chat-sdk]",w);break}throw new Error(w)}catch(m){if(y<o.length){const w=o[y++];console.warn(`[aikaara-chat-sdk] preflight #${a} threw, retry #${y} in ${w}ms`,m),await new Promise(S=>setTimeout(S,w));continue}if(c.soft){console.warn(`[aikaara-chat-sdk] preflight #${a} soft-failed:`,m);break}throw m}if(k&&c.capture&&c.capture.as)try{const m=await k.clone().text();let w=m;try{w=JSON.parse(m)}catch{}if(c.capture.path)for(const S of c.capture.path.split("."))if(w&&typeof w=="object"&&S in w)w=w[S];else{w=void 0;break}if(typeof w=="string"&&w.length>0){let S=w;c.capture.stripPrefix&&S.startsWith(c.capture.stripPrefix)&&(S=S.slice(c.capture.stripPrefix.length)),i[c.capture.as]=S,t[c.capture.as]=S,console.log(`[aikaara-chat-sdk] preflight #${a} captured ${c.capture.as} (${S.slice(0,24)}…)`)}}catch(m){console.warn(`[aikaara-chat-sdk] preflight #${a} capture failed`,m)}}return{captured:i}}function Xd(l,e){if(l===503||l===504||l===502)return!0;if(l===401||l===403)return e.trim().length===0;if(l===500){const t=e.toLowerCase();return t.includes("customernew")||t.includes("is null")||t.includes("not yet ready")}return!1}async function Kl(l,e){const t=await fetch(l,{method:"GET",headers:{accept:"application/json",...e??{}}});if(!t.ok){const s=await t.text().catch(()=>"");throw new Error(`Widget config fetch failed: ${t.status} ${t.statusText} ${s.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 Yl(l,e){return l.replace("{projectId}",e).replace("{uuid}",Gd().replace(/-/g,""))}function Ql(l){const e=l._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=>jl(r)))}async function Jl(l){const e={...l.config??(l.configUrl?await Kl(l.configUrl,l.configHeaders):{}),...l.overrides??{}};Ql(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 s=r?.projectId??"",n=l.identity.userId,i=l.forceNewConversation?null:Gl(n,s),o=r?.requestIdTemplate??"support-group-{projectId}-{uuid}",a=l.conversationId??i??Yl(o,s);(!i||l.forceNewConversation)&&s&&Yd(n,s,a);const c=await l.tokenProvider(),u=l.tokenProvider,h=l.historyTokenProvider??u,p=r?{mqttEndpoint:r.mqttEndpoint,jwtToken:c,userId:n,userName:l.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,...l.identity.departmentId?{departmentId:l.identity.departmentId}:r.messageDefaults?.departmentId?{departmentId:r.messageDefaults.departmentId}:{}},fileTemplate:r.fileTemplate,topicTemplates:r.topicTemplates,debug:r.debug,senderFullname:l.identity.senderFullname??l.identity.userName,tokenProvider:u}:void 0,b=l.uploadAdapter??(e.uploadEndpoint?uo({endpoint:e.uploadEndpoint,fieldName:e.uploadFieldName,extraFields:e.uploadExtraFields}):void 0),f=l.historyAdapter??(e.historyApiBase?bl({apiBase:e.historyApiBase,pageSize:e.historyPageSize??200,pathTemplate:e.historyPathTemplate,extraHeaders:e.historyHeaders,getToken:h}):void 0),g={transport:t,baseUrl:"",userToken:l.userToken??n,conversationId:a,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:l.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:l.identity.userName,departmentId:l.identity.departmentId,senderFullname:l.identity.senderFullname??l.identity.userName},templateActionAttributes:e.templateActionAttributes,uploadAdapter:b,historyAdapter:f,onError:l.onError,onMessage:l.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;--aikaara-close-btn-display:none;"),l.container.appendChild(y),{widget:y,requestId:a,config:g,destroy(){y.remove()}}}function Zd(l){if(typeof l!="string")return l;const e=document.querySelector(l);if(!e)throw new Error(`mountFromSlug: container "${l}" not found`);return e}async function Xl(l){const e=(l.configBase??"https://api.aikaara.com").replace(/\/$/,""),t=`${e}/api/v1/widget_configs/${encodeURIComponent(l.slug)}`;let r=null;try{r=await Kl(t,l.configHeaders)}catch(x){if(!l.fallbackConfig)throw x;console.warn(`[aikaara-chat-sdk] Widget config fetch failed for slug "${l.slug}" — using fallbackConfig.`,x)}const s={...l.fallbackConfig??{},...r??{},...l.overrides??{}};if(Ql(s),s.templates&&Object.keys(s.templates).length>0){s.components={...s.components??{}};for(const[x,I]of Object.entries(s.templates)){const P=`template:${x}`;s.components[P]||!I?.scriptUrl||!I?.render||(s.components[P]={kind:"iife-element",scriptUrl:I.scriptUrl,tag:I.render,...I.props?{props:I.props}:{}})}}const n=window;if(n.__aikaara_descriptor__={...n.__aikaara_descriptor__??{},templates:s.templates,components:s.components,razorpay:s.razorpay,title:s.title,cloud:s.cloud??n.__aikaara_descriptor__?.cloud,upload:s.upload??n.__aikaara_descriptor__?.upload,themeSource:s.themeSource??n.__aikaara_descriptor__?.themeSource,api:s.api,auth:s.auth},!s.auth)throw new Error(`mountFromSlug: widget_configs/${l.slug} descriptor must include "auth" block`);let i=null,o=l.user.id,a=l.user.name,c="",u=l.user.token,h=null;const p=await Xt(l.user.token).catch(()=>""),b=typeof p=="string"&&p.length>0;if(!b&&s.sso?.tokenSource){h=new zl({descriptor:{provider:s.sso.provider,flow:s.sso.flow,skipLogin:s.sso.skipLogin,autoRefresh:s.sso.autoRefresh,tokenSource:s.sso.tokenSource,tokenSourceConfig:s.sso.tokenSourceConfig,fallback:s.sso.fallback,map:s.sso.map},initToken:l.user.partnerToken});const x=await h.get();u=async()=>(await h.get()).token,l.user.identity&&!l.user.identity.partnerToken&&(l.user.identity.partnerToken=x.token)}else if(!b&&s.sso&&s.sso.collect&&s.sso.collect.length>0){const x=`${e}/api/v1/projects/by-slug/${encodeURIComponent(l.slug)}/sso_exchange`;i=await new Hl({descriptor:s.sso,providers:l.user.credentialProviders,exchangeUrl:x}).get(),o=i.extUid||o,a=a??i.displayName,c=i.userToken}let f="";if(s.preflight&&s.preflight.length){const x=await Jd(s.preflight,{sessionToken:u,userId:o,projectId:s.tiledesk?.projectId??"",slug:l.slug,identity:l.user.identity});if(x.captured.sessionToken){f=x.captured.sessionToken;const I=f;u=()=>I}x.captured.userId&&(o=x.captured.userId)}const g=new $l(s.auth,u);if(f){const x=s.tiledesk?.projectId??"",I=x?Gl(o,x):null,P=s.tiledesk?.requestIdTemplate??"support-group-{projectId}-{uuid}",O=I??(x?Yl(P,x):"");g.prime(f,{requestId:O,fullName:a})}const y=await g.get();o=o||y.userId;const k=y.fullName||a||o;window.__aikaara_runtime__={getChatJwt:async()=>(await g.get()).token,identity:l.user.identity,slug:l.slug,configBase:e};const m=h&&s.sso?.autoRefresh?async()=>{try{return await h.refresh(),g.reset(),(await g.get()).token}catch(x){return console.warn("[aikaara-chat-sdk] partner auto-refresh failed",x),null}}:null,w=s.upload,S=async()=>`Bearer ${w&&"tokenSource"in w&&w.tokenSource==="chat"?(await g.get()).token:await Xt(l.user.token)}`,v=l.hooks?.upload??(w&&w.mode==="presigned-3step"?gl({...w,authHeader:S}):w&&w.mode==="direct"?uo({endpoint:w.endpoint,fieldName:w.fieldName,extraFields:w.extraFields,headers:async()=>({authorization:await S()})}):void 0),E=await Jl({container:Zd(l.container),config:s,userToken:c||void 0,identity:{userId:o,userName:k,departmentId:l.user.departmentId,senderFullname:k},tokenProvider:async()=>(await g.get()).token,historyTokenProvider:async()=>(await g.get()).token,uploadAdapter:v,historyAdapter:l.hooks?.history,conversationId:y.requestId||void 0,onError:l.hooks?.onError,onMessage:l.hooks?.onMessage,getLinkBearer:async x=>x==="none"?null:x==="chat"?(await g.get()).token:Xt(l.user.token)});return Object.assign(E,{fullName:k,requestId:y.requestId,descriptor:s,async refreshAuth(){g.reset(),await g.get()},async refreshPartnerAuth(){return m?m():null}})}function ef(l){yo();const e=document.createElement("aikaara-chat-widget"),t={baseUrl:"base-url",userToken:"user-token",apiKey:"api-key",title:"title",subtitle:"subtitle",theme:"theme",primaryColor:"primary-color",position:"position",width:"width",height:"height",placeholder:"placeholder",welcomeMessage:"welcome-message",avatarUrl:"avatar-url"};for(const[r,s]of Object.entries(t)){const n=l[r];n!=null&&e.setAttribute(s,String(n))}return e.configure(l),document.body.appendChild(e),e}function tf(){const l=document.querySelector("aikaara-chat-widget");l&&l.remove()}class Zl extends HTMLElement{shadow;payload=null;constructor(){super(),this.shadow=this.attachShadow({mode:"open"})}connectedCallback(){this.render()}setPayload(e){this.payload=e,this.render()}render(){const e=this.payload;this.shadow.innerHTML=`
1461
+ `}}function Ot(l){return l.replace(/&/g,"&amp;").replace(/"/g,"&quot;").replace(/</g,"&lt;").replace(/>/g,"&gt;")}function Qe(l){return l.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;")}function yo(){const l=[["aikaara-chat-widget",xl],["aikaara-chat-bubble",Sl],["aikaara-chat-header",El],["aikaara-message-list",Il],["aikaara-message-bubble",Cl],["aikaara-chat-input",Pl],["aikaara-typing-indicator",Ml],["aikaara-streaming-message",Rl],["aikaara-error-banner",Ll],["aikaara-template-renderer",gd],["aikaara-system-pill",vd],["aikaara-option-list",wd],["aikaara-submit-action",_d],["aikaara-modal-action",xd],["aikaara-chat",Sd],["aikaara-link-modal",Ed],["aikaara-compare-plans",Td],["aikaara-smart-edit-modal",Cd],["aikaara-schema-form",Md]];for(const[e,t]of l)customElements.get(e)||customElements.define(e,t)}yo();function Hr(l,e,t=""){if(!e)return t;const r=e.split(".");let s=l;for(const n of r)if(s&&typeof s=="object"&&n in s)s=s[n];else return t;return typeof s=="string"?s:t}function Fl(l){try{const e=l.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 Xt(l){return typeof l=="function"?await l():l}class $l{constructor(e,t){this.descriptor=e,this.sessionToken=t}cache=null;inflight=null;reset(){this.cache=null,this.inflight=null}prime(e,t={}){if(!e)return;const r=Fl(e)||Date.now()+3600*1e3;this.cache={token:e,requestId:t.requestId??this.cache?.requestId??"",fullName:t.fullName??this.cache?.fullName??"",userId:t.userId??this.cache?.userId??"",expiresAt:r}}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 Xt(this.sessionToken),t=this.descriptor.authHeader??"Authorization",r=this.descriptor.authHeaderTemplate??"Bearer {token}",s={accept:"application/json",...this.descriptor.headers??{},[t]:r.replace("{token}",e)},n=this.descriptor.method??"POST",i={method:n,headers:s};n==="POST"&&(s["content-type"]="application/json",i.body=JSON.stringify(this.descriptor.body??{}));const o=await fetch(this.descriptor.endpoint,i);if(!o.ok){const k=await o.text().catch(()=>"");throw new Error(`Session auth failed: ${o.status} ${k.slice(0,200)}`)}const a=await o.json().catch(()=>({})),c=Hr(a,this.descriptor.tokenPath??"data.token"),u=this.descriptor.tokenStripPrefix,h=u?c.replace(new RegExp(`^${u}`,"i"),"").trim():c;if(!h)throw new Error("Session auth response missing token");const p=Hr(a,this.descriptor.requestIdPath??"data.requestId"),y=this.cache?.requestId||p||"",f=Hr(a,this.descriptor.fullNamePath??"data.fullName"),g=Hr(a,this.descriptor.userPath??"data.userId"),b=Fl(h)||Date.now()+3600*1e3;return this.cache={token:h,requestId:y,fullName:f,userId:g,expiresAt:b},this.cache}}async function ql(l){const e={};for(const t of l.spec){const r=await Rd(t,l.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 Rd(l,e){const t=l.key??l.name;switch(l.source){case"cookie":return Ld(t);case"localStorage":return Wr(()=>window.localStorage.getItem(t)??void 0);case"sessionStorage":return Wr(()=>window.sessionStorage.getItem(t)??void 0);case"url_param":return Wr(()=>new URL(window.location.href).searchParams.get(t)??void 0);case"header_meta":return Wr(()=>document.querySelector(`meta[name="${jd(t)}"]`)?.content??void 0);case"callback":{const r=e?.[l.name];if(!r)return;const s=await r();return typeof s=="string"?s:void 0}default:return}}function Ld(l){if(typeof document>"u")return;const e=encodeURIComponent(l),t=document.cookie?document.cookie.split("; "):[];for(const r of t){const s=r.indexOf("=");if(s===-1)continue;const n=r.slice(0,s);if(n===l||n===e)try{return decodeURIComponent(r.slice(s+1))}catch{return r.slice(s+1)}}}function Wr(l){try{return l()}catch{return}}function jd(l){return l.replace(/["\\]/g,"\\$&")}const Nd=1800;class Hl{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 ql({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 s=this.opts.descriptor.exchangeEndpoint||this.opts.exchangeUrl;if(!s)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(s,{method:"POST",headers:r,body:t});if(!n.ok){const h=await n.text().catch(()=>"");throw new Error(`SSO exchange failed: ${n.status} ${h.slice(0,240)}`)}const o=(await n.json().catch(()=>({}))).user??{},a=String(o.ext_uid??o.extUid??""),c=String(o.token??o.user_token??o.userToken??"");if(!a)throw new Error("SSO exchange response missing user.ext_uid");if(!c)throw new Error("SSO exchange response missing user.token");const u={id:o.id,extUid:a,userToken:c,email:typeof o.email=="string"?o.email:void 0,displayName:typeof o.display_name=="string"?o.display_name:typeof o.displayName=="string"?o.displayName:void 0,properties:o.properties&&typeof o.properties=="object"?o.properties:void 0,expiresAt:this.computeExpiry()};return this.cache=u,this.persistCache(u),u}computeExpiry(){const e=this.opts.descriptor.cacheTtlSec??Nd;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 Ud=3e4,Bd=2e3,Dd=100;async function Wl(l){const{descriptor:e}=l,t=e.tokenSourceConfig??{};switch(e.tokenSource){case"init":{if(!l.initToken)throw new Ke("init","No init token supplied to Aikaara.init({token})");return{token:l.initToken,source:"init"}}case"query":{const r=typeof t.key=="string"&&t.key?t.key:"token",s=Fd(r);if(!s)throw new Ke("query",`?${r}= not present`);return{token:s,source:"query"}}case"hash":{const r=typeof t.key=="string"&&t.key?t.key:"token",s=$d(r);if(!s)throw new Ke("hash",`#${r}= not present`);return{token:s,source:"hash"}}case"postmsg":{const r=typeof t.type=="string"?t.type:"",s=typeof t.key=="string"&&t.key?t.key:"token",n=Vd(typeof t.origins=="string"?t.origins:""),i=typeof t.timeoutMs=="number"&&t.timeoutMs>0?t.timeoutMs:Ud;return{token:await zd({type:r,key:s,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 s=qd(r);if(!s)throw new Ke("cookie",`cookie "${r}" not set`);return{token:s,source:"cookie"}}case"storage":{const r=t.store==="session"?"session":"local",s=typeof t.key=="string"&&t.key?t.key:"",n=typeof t.path=="string"?t.path:"";if(!s)throw new Ke("storage","storage.key not configured");const i=Hd(r,s,n);if(!i)throw new Ke("storage",`${r}Storage["${s}"] 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 s=typeof t.timeoutMs=="number"&&t.timeoutMs>0?t.timeoutMs:Bd,n=typeof t.intervalMs=="number"&&t.intervalMs>0?t.intervalMs:Dd,i=await Wd(r,s,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 zl{constructor(e){this.opts=e}cached=null;get descriptor(){return this.opts.descriptor}async get(){if(this.cached)return this.cached;const e=await Wl(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 Fd(l){if(!(typeof window>"u"))try{return new URL(window.location.href).searchParams.get(l)??void 0}catch{return}}function $d(l){if(!(typeof window>"u"))try{const e=window.location.hash.replace(/^#/,"");return new URLSearchParams(e).get(l)??void 0}catch{return}}function qd(l){if(typeof document>"u")return;const e=encodeURIComponent(l),t=document.cookie?document.cookie.split("; "):[];for(const r of t){const s=r.indexOf("=");if(s===-1)continue;const n=r.slice(0,s);if(n===l||n===e)try{return decodeURIComponent(r.slice(s+1))}catch{return r.slice(s+1)}}}function Hd(l,e,t){if(!(typeof window>"u"))try{const s=(l==="session"?window.sessionStorage:window.localStorage).getItem(e);if(s==null)return;if(!t)return s;let n;try{n=JSON.parse(s)}catch{return s}const i=Vl(n,t);return typeof i=="string"?i:void 0}catch{return}}async function Wd(l,e,t){if(typeof window>"u")return;const r=Date.now()+e;for(;Date.now()<r;){const s=Vl(window,l);if(typeof s=="string"&&s.length>0)return s;if(typeof s=="function")try{const n=s();if(typeof n=="string"&&n.length>0)return n}catch{}await new Promise(n=>setTimeout(n,t))}}function zd(l){return new Promise((e,t)=>{if(typeof window>"u"){t(new Ke("postmsg","no window"));return}const r=()=>{window.removeEventListener("message",n),clearTimeout(s)},s=setTimeout(()=>{r(),t(new Ke("postmsg",`timeout after ${l.timeoutMs}ms`))},l.timeoutMs),n=i=>{if(l.origins.length>0&&!l.origins.includes(i.origin))return;const o=i.data;if(!o||typeof o!="object")return;const a=o;if(l.type&&a.type!==l.type)return;const c=a[l.key];typeof c=="string"&&c.length>0&&(r(),e(c))};window.addEventListener("message",n)})}function Vd(l){return l?l.split(/[,\s]+/).map(e=>e.trim()).filter(Boolean):[]}function Vl(l,e){if(!e)return l;const t=e.split(".").filter(Boolean);let r=l;for(const s of t)if(r&&typeof r=="object"&&s in r)r=r[s];else return;return r}function Gd(){const l=typeof crypto<"u"?crypto:null;if(l?.randomUUID)return l.randomUUID();if(l?.getRandomValues){const e=new Uint8Array(16);l.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 Kd="aikaara_chat:requestId";function vo(l,e){return`${Kd}:${l}:${e}`}function Gl(l,e){try{return localStorage.getItem(vo(l,e))}catch{return null}}function Yd(l,e,t){try{localStorage.setItem(vo(l,e),t)}catch{}}function Qd(l,e){try{localStorage.removeItem(vo(l,e))}catch{}}async function Jd(l,e){console.log("[aikaara-chat-sdk] preflight running",l.length,"steps");const t={userId:e.userId,projectId:e.projectId,slug:e.slug};if(e.identity)for(const[a,c]of Object.entries(e.identity))typeof c=="string"&&(t[a]=c);const r=a=>a.replace(/\{(\w+)\}/g,(c,u)=>u in t?t[u]:""),s=a=>{if(typeof a=="string")return r(a);if(Array.isArray(a))return a.map(s);if(a&&typeof a=="object"){const c={};for(const[u,h]of Object.entries(a))c[u]=s(h);return c}return a},n=await Xt(e.sessionToken),i={},o=[800,1500,3e3,5e3,8e3];for(let a=0;a<l.length;a++){const c=l[a],u=r(c.url),h=c.method??(c.body?"POST":"GET"),p={accept:"application/json",...c.headers??{}};if((c.authHeader??"session")==="session"){const m=c.authHeaderTemplate??"Bearer {token}";p.authorization=m.replace("{token}",n)}const y={method:h,headers:p};c.body&&(p["content-type"]="application/json",y.body=JSON.stringify(s(c.body)));let f=0,g="",b=0,k=null;for(;;)try{const m=await fetch(u,y);if(m.ok){k=m;break}if(f=m.status,g=await m.text().catch(()=>""),b<o.length&&Xd(f,g)){const x=o[b++];console.warn(`[aikaara-chat-sdk] preflight #${a} ${h} ${u} → ${f} (transient). Retry #${b} in ${x}ms.`),await new Promise(v=>setTimeout(v,x));continue}const w=`Preflight #${a} ${h} ${u} → ${f} ${g.slice(0,200)}`;if(c.soft){console.warn("[aikaara-chat-sdk]",w);break}throw new Error(w)}catch(m){if(b<o.length){const w=o[b++];console.warn(`[aikaara-chat-sdk] preflight #${a} threw, retry #${b} in ${w}ms`,m),await new Promise(x=>setTimeout(x,w));continue}if(c.soft){console.warn(`[aikaara-chat-sdk] preflight #${a} soft-failed:`,m);break}throw m}if(k&&c.capture&&c.capture.as)try{const m=await k.clone().text();let w=m;try{w=JSON.parse(m)}catch{}if(c.capture.path)for(const x of c.capture.path.split("."))if(w&&typeof w=="object"&&x in w)w=w[x];else{w=void 0;break}if(typeof w=="string"&&w.length>0){let x=w;c.capture.stripPrefix&&x.startsWith(c.capture.stripPrefix)&&(x=x.slice(c.capture.stripPrefix.length)),i[c.capture.as]=x,t[c.capture.as]=x,console.log(`[aikaara-chat-sdk] preflight #${a} captured ${c.capture.as} (${x.slice(0,24)}…)`)}}catch(m){console.warn(`[aikaara-chat-sdk] preflight #${a} capture failed`,m)}}return{captured:i}}function Xd(l,e){if(l===503||l===504||l===502)return!0;if(l===401||l===403)return e.trim().length===0;if(l===500){const t=e.toLowerCase();return t.includes("customernew")||t.includes("is null")||t.includes("not yet ready")}return!1}async function Kl(l,e){const t=await fetch(l,{method:"GET",headers:{accept:"application/json",...e??{}}});if(!t.ok){const s=await t.text().catch(()=>"");throw new Error(`Widget config fetch failed: ${t.status} ${t.statusText} ${s.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 Yl(l,e){return l.replace("{projectId}",e).replace("{uuid}",Gd().replace(/-/g,""))}function Ql(l){const e=l._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=>jl(r)))}async function Jl(l){const e={...l.config??(l.configUrl?await Kl(l.configUrl,l.configHeaders):{}),...l.overrides??{}};Ql(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 s=r?.projectId??"",n=l.identity.userId,i=l.forceNewConversation?null:Gl(n,s),o=r?.requestIdTemplate??"support-group-{projectId}-{uuid}",a=l.conversationId??i??Yl(o,s);(l.conversationId||!i||l.forceNewConversation)&&s&&Yd(n,s,a);const c=await l.tokenProvider(),u=l.tokenProvider,h=l.historyTokenProvider??u,p=r?{mqttEndpoint:r.mqttEndpoint,jwtToken:c,userId:n,userName:l.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,...l.identity.departmentId?{departmentId:l.identity.departmentId}:r.messageDefaults?.departmentId?{departmentId:r.messageDefaults.departmentId}:{}},fileTemplate:r.fileTemplate,topicTemplates:r.topicTemplates,debug:r.debug,senderFullname:l.identity.senderFullname??l.identity.userName,tokenProvider:u}:void 0,y=l.uploadAdapter??(e.uploadEndpoint?uo({endpoint:e.uploadEndpoint,fieldName:e.uploadFieldName,extraFields:e.uploadExtraFields}):void 0),f=l.historyAdapter??(e.historyApiBase?bl({apiBase:e.historyApiBase,pageSize:e.historyPageSize??200,pathTemplate:e.historyPathTemplate,extraHeaders:e.historyHeaders,getToken:h}):void 0),g={transport:t,baseUrl:"",userToken:l.userToken??n,conversationId:a,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:l.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:l.identity.userName,departmentId:l.identity.departmentId,senderFullname:l.identity.senderFullname??l.identity.userName},templateActionAttributes:e.templateActionAttributes,uploadAdapter:y,historyAdapter:f,onError:l.onError,onMessage:l.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;--aikaara-close-btn-display:none;"),l.container.appendChild(b),{widget:b,requestId:a,config:g,destroy(){b.remove()}}}function Zd(l){if(typeof l!="string")return l;const e=document.querySelector(l);if(!e)throw new Error(`mountFromSlug: container "${l}" not found`);return e}async function Xl(l){const e=(l.configBase??"https://api.aikaara.com").replace(/\/$/,""),t=`${e}/api/v1/widget_configs/${encodeURIComponent(l.slug)}`;let r=null;try{r=await Kl(t,l.configHeaders)}catch(I){if(!l.fallbackConfig)throw I;console.warn(`[aikaara-chat-sdk] Widget config fetch failed for slug "${l.slug}" — using fallbackConfig.`,I)}const s={...l.fallbackConfig??{},...r??{},...l.overrides??{}};if(Ql(s),s.templates&&Object.keys(s.templates).length>0){s.components={...s.components??{}};for(const[I,O]of Object.entries(s.templates)){const P=`template:${I}`;s.components[P]||!O?.scriptUrl||!O?.render||(s.components[P]={kind:"iife-element",scriptUrl:O.scriptUrl,tag:O.render,...O.props?{props:O.props}:{}})}}const n=window;if(n.__aikaara_descriptor__={...n.__aikaara_descriptor__??{},templates:s.templates,components:s.components,razorpay:s.razorpay,title:s.title,cloud:s.cloud??n.__aikaara_descriptor__?.cloud,upload:s.upload??n.__aikaara_descriptor__?.upload,themeSource:s.themeSource??n.__aikaara_descriptor__?.themeSource,api:s.api,auth:s.auth},!s.auth)throw new Error(`mountFromSlug: widget_configs/${l.slug} descriptor must include "auth" block`);let i=null,o=l.user.id,a=l.user.name,c="",u=l.user.token,h=null;const p=await Xt(l.user.token).catch(()=>""),y=typeof p=="string"&&p.length>0;if(!y&&s.sso?.tokenSource){h=new zl({descriptor:{provider:s.sso.provider,flow:s.sso.flow,skipLogin:s.sso.skipLogin,autoRefresh:s.sso.autoRefresh,tokenSource:s.sso.tokenSource,tokenSourceConfig:s.sso.tokenSourceConfig,fallback:s.sso.fallback,map:s.sso.map},initToken:l.user.partnerToken});const I=await h.get();u=async()=>(await h.get()).token,l.user.identity&&!l.user.identity.partnerToken&&(l.user.identity.partnerToken=I.token)}else if(!y&&s.sso&&s.sso.collect&&s.sso.collect.length>0){const I=`${e}/api/v1/projects/by-slug/${encodeURIComponent(l.slug)}/sso_exchange`;i=await new Hl({descriptor:s.sso,providers:l.user.credentialProviders,exchangeUrl:I}).get(),o=i.extUid||o,a=a??i.displayName,c=i.userToken}let f="",g="";if(s.preflight&&s.preflight.length){const I=await Jd(s.preflight,{sessionToken:u,userId:o,projectId:s.tiledesk?.projectId??"",slug:l.slug,identity:l.user.identity});if(I.captured.sessionToken){f=I.captured.sessionToken;const O=f;u=()=>O}I.captured.userId&&(o=I.captured.userId),I.captured.requestId&&(g=I.captured.requestId)}const b=new $l(s.auth,u);if(f){const I=s.tiledesk?.projectId??"",O=I?Gl(o,I):null,P=s.tiledesk?.requestIdTemplate??"support-group-{projectId}-{uuid}",N=O??(I?Yl(P,I):"");b.prime(f,{requestId:N,fullName:a})}const k=await b.get();o=o||k.userId;const m=k.fullName||a||o;window.__aikaara_runtime__={getChatJwt:async()=>(await b.get()).token,identity:l.user.identity,slug:l.slug,configBase:e};const w=h&&s.sso?.autoRefresh?async()=>{try{return await h.refresh(),b.reset(),(await b.get()).token}catch(I){return console.warn("[aikaara-chat-sdk] partner auto-refresh failed",I),null}}:null,x=s.upload,v=async()=>`Bearer ${x&&"tokenSource"in x&&x.tokenSource==="chat"?(await b.get()).token:await Xt(l.user.token)}`,E=l.hooks?.upload??(x&&x.mode==="presigned-3step"?gl({...x,authHeader:v}):x&&x.mode==="direct"?uo({endpoint:x.endpoint,fieldName:x.fieldName,extraFields:x.extraFields,headers:async()=>({authorization:await v()})}):void 0),S=await Jl({container:Zd(l.container),config:s,userToken:c||void 0,identity:{userId:o,userName:m,departmentId:l.user.departmentId,senderFullname:m},tokenProvider:async()=>(await b.get()).token,historyTokenProvider:async()=>(await b.get()).token,uploadAdapter:E,historyAdapter:l.hooks?.history,conversationId:k.requestId||g||void 0,onError:l.hooks?.onError,onMessage:l.hooks?.onMessage,getLinkBearer:async I=>I==="none"?null:I==="chat"?(await b.get()).token:Xt(l.user.token)});return Object.assign(S,{fullName:m,requestId:k.requestId,descriptor:s,async refreshAuth(){b.reset(),await b.get()},async refreshPartnerAuth(){return w?w():null}})}function ef(l){yo();const e=document.createElement("aikaara-chat-widget"),t={baseUrl:"base-url",userToken:"user-token",apiKey:"api-key",title:"title",subtitle:"subtitle",theme:"theme",primaryColor:"primary-color",position:"position",width:"width",height:"height",placeholder:"placeholder",welcomeMessage:"welcome-message",avatarUrl:"avatar-url"};for(const[r,s]of Object.entries(t)){const n=l[r];n!=null&&e.setAttribute(s,String(n))}return e.configure(l),document.body.appendChild(e),e}function tf(){const l=document.querySelector("aikaara-chat-widget");l&&l.remove()}class Zl extends HTMLElement{shadow;payload=null;constructor(){super(),this.shadow=this.attachShadow({mode:"open"})}connectedCallback(){this.render()}setPayload(e){this.payload=e,this.render()}render(){const e=this.payload;this.shadow.innerHTML=`
1462
1462
  <style>
1463
1463
  :host { display: block; margin-top: 8px; }
1464
1464
  button {